forked from thesam73/wordle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
share.ts
105 lines (94 loc) · 2.6 KB
/
share.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
import { UAParser } from 'ua-parser-js'
import { MAX_CHALLENGES } from '../constants/settings'
import { GAME_TITLE } from '../constants/strings'
import { getGuessStatuses } from './statuses'
import { solutionIndex, unicodeSplit } from './words'
const webShareApiDeviceTypes: string[] = ['mobile', 'smarttv', 'wearable']
const parser = new UAParser()
const browser = parser.getBrowser()
const device = parser.getDevice()
export const shareStatus = (
solution: string,
guesses: string[],
lost: boolean,
isHardMode: boolean,
isDarkMode: boolean,
isHighContrastMode: boolean,
handleShareToClipboard: () => void,
handleShareFailure: () => void
) => {
const textToShare =
`${GAME_TITLE} ${solutionIndex} ${
lost ? 'X' : guesses.length
}/${MAX_CHALLENGES}${isHardMode ? '*' : ''}\n\n` +
generateEmojiGrid(
solution,
guesses,
getEmojiTiles(isDarkMode, isHighContrastMode)
)
const shareData = { text: textToShare }
let shareSuccess = false
try {
if (attemptShare(shareData)) {
navigator.share(shareData)
shareSuccess = true
}
} catch (error) {
shareSuccess = false
}
try {
if (!shareSuccess) {
if (navigator.clipboard) {
navigator.clipboard
.writeText(textToShare)
.then(handleShareToClipboard)
.catch(handleShareFailure)
} else {
handleShareFailure()
}
}
} catch (error) {
handleShareFailure()
}
}
export const generateEmojiGrid = (
solution: string,
guesses: string[],
tiles: string[]
) => {
return guesses
.map((guess) => {
const status = getGuessStatuses(solution, guess)
const splitGuess = unicodeSplit(guess)
return splitGuess
.map((_, i) => {
switch (status[i]) {
case 'correct':
return tiles[0]
case 'present':
return tiles[1]
default:
return tiles[2]
}
})
.join('')
})
.join('\n')
}
const attemptShare = (shareData: object) => {
return (
// Deliberately exclude Firefox Mobile, because its Web Share API isn't working correctly
browser.name?.toUpperCase().indexOf('FIREFOX') === -1 &&
webShareApiDeviceTypes.indexOf(device.type ?? '') !== -1 &&
navigator.canShare &&
navigator.canShare(shareData) &&
navigator.share
)
}
const getEmojiTiles = (isDarkMode: boolean, isHighContrastMode: boolean) => {
let tiles: string[] = []
tiles.push(isHighContrastMode ? '🟧' : '🟩')
tiles.push(isHighContrastMode ? '🟦' : '🟨')
tiles.push(isDarkMode ? '⬛' : '⬜')
return tiles
}