-
Notifications
You must be signed in to change notification settings - Fork 59
/
Copy pathutils.js
348 lines (292 loc) · 9.75 KB
/
utils.js
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
import * as htmlToImage from 'html-to-image'
import i18next from 'i18next'
import stringify from 'json-stable-stringify'
import { Constants } from 'lib/constants/constants'
import { v4 as uuidv4 } from 'uuid'
console.debug = (...args) => {
let messageConfig = '%c%s '
args.forEach((argument) => {
const type = typeof argument
switch (type) {
case 'bigint':
case 'number':
case 'boolean':
messageConfig += '%d '
break
case 'string':
messageConfig += '%s '
break
case 'object':
case 'undefined':
default:
messageConfig += '%o '
}
})
console.log(messageConfig, 'color: orange', '[DEBUG]', ...args)
}
export const Utils = {
// Hashes an object for uniqueness checks
objectHash: (obj) => {
return stringify(obj)
},
// Fill array of size n with 0s
arrayOfZeroes: (n) => {
return new Array(n).fill(0)
},
// Fill array of size n with value x
arrayOfValue: (n, x) => {
return new Array(n).fill(x)
},
nullUndefinedToZero: (x) => {
if (x == null) return 0
return x
},
// TODO: Deprecate these
mergeDefinedValues: (target, source) => {
if (!source) return target
for (const key of Object.keys(target)) {
if (source[key] != null) {
target[key] = source[key]
}
}
return target
},
// TODO: Deprecate these
mergeUndefinedValues: (target, source) => {
for (const key of Object.keys(source)) {
if (target[key] == null) {
target[key] = source[key]
}
}
return target
},
// await sleep(ms) to block
sleep: (ms) => {
return new Promise((resolve) => setTimeout(resolve, ms))
},
// Store a count of relic sets into an array indexed by the set index
relicsToSetArrays: (relics) => {
const relicSets = Utils.arrayOfValue(Object.values(Constants.SetsRelics).length, 0)
const ornamentSets = Utils.arrayOfValue(Object.values(Constants.SetsOrnaments).length, 0)
for (const relic of relics) {
if (!relic) continue
if (relic.part == Constants.Parts.PlanarSphere || relic.part == Constants.Parts.LinkRope) {
const set = Constants.OrnamentSetToIndex[relic.set]
ornamentSets[set]++
} else {
const set = Constants.RelicSetToIndex[relic.set]
relicSets[set]++
}
}
return {
relicSets: relicSets,
ornamentSets: ornamentSets,
}
},
// Flat stats HP/ATK/DEF/SPD
isFlat: (stat) => {
return stat == Constants.Stats.HP
|| stat == Constants.Stats.ATK
|| stat == Constants.Stats.DEF
|| stat == Constants.Stats.SPD
},
// Random element of an array
randomElement: (arr) => {
return arr[Math.floor(Math.random() * arr.length)]
},
isMobile: () => {
return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)
},
isMobileOrSafari: () => {
const userAgent = navigator.userAgent
// Detect mobile devices
const isMobile = /Android|iPhone|iPad|iPod|Opera Mini|IEMobile|WPDesktop|BlackBerry/i.test(userAgent)
// Detect Safari (excluding Chrome on iOS)
const isSafari = /^((?!chrome|android).)*safari/i.test(userAgent)
return isMobile || isSafari
},
// Util to capture a div and screenshot it to clipboard/file
screenshotElementById: async (elementId, action, characterName) => {
const isMobileOrSafari = Utils.isMobileOrSafari()
const repeatLoadBlob = async () => {
const minDataLength = 1200000
const maxAttempts = isMobileOrSafari ? 9 : 3
const scale = 1.5
const w = 1100 * scale
const h = 880 * scale
const options = {
pixelRatio: 1,
height: h,
canvasHeight: h,
width: w,
canvasWidth: w,
skipAutoScale: true,
style: {
zoom: scale,
},
}
let i = 0
let blob
while (i < maxAttempts) {
i++
blob = await htmlToImage.toBlob(document.getElementById(elementId), options)
if (blob.size > minDataLength) {
break
}
}
if (isMobileOrSafari) {
// Render again
blob = await htmlToImage.toBlob(document.getElementById(elementId), options)
}
return blob
}
function handleBlob(blob) {
const prefix = characterName || 'Hsr-optimizer'
const date = new Date().toLocaleDateString(resolvedLanguage()).replace(/[^apm\d]+/gi, '-')
const time = new Date().toLocaleTimeString(resolvedLanguage()).replace(/[^apm\d]+/gi, '-')
const filename = `${prefix}_${date}_${time}.png`
if (action == 'clipboard') {
if (isMobileOrSafari) {
const file = new File([blob], filename, { type: 'image/png' })
if (navigator.canShare && navigator.canShare({ files: [file] })) {
navigator.share({
files: [file],
title: '',
text: '',
})
} else {
Message.error('Unable to save screenshot to clipboard, try the download button to the right')
// 'Unable to save screenshot to clipboard, try the download button to the right'
}
} else {
try {
const data = [new window.ClipboardItem({ [blob.type]: blob })]
navigator.clipboard.write(data).then(() => {
Message.success(i18next.t('charactersTab:ScreenshotMessages.ScreenshotSuccess'))// 'Copied screenshot to clipboard'
})
} catch (e) {
console.error(e)
Message.error(i18next.t('charactersTab:ScreenshotMessages.ScreenshotFailed'))
// 'Unable to save screenshot to clipboard, try the download button to the right'
}
}
}
if (action == 'download') {
const fileUrl = window.URL.createObjectURL(blob)
const anchorElement = document.createElement('a')
anchorElement.href = fileUrl
anchorElement.download = filename
anchorElement.style.display = 'none'
document.body.appendChild(anchorElement)
anchorElement.click()
anchorElement.remove()
window.URL.revokeObjectURL(fileUrl)
Message.success(i18next.t('charactersTab:ScreenshotMessages.DownloadSuccess')) // 'Downloaded screenshot'
}
}
return new Promise((resolve) => {
repeatLoadBlob().then((blob) => {
handleBlob(blob)
resolve()
})
})
},
// Convert an array to an object keyed by id field
collectById: (arr) => {
const byId = {}
for (const x of arr) {
byId[x.id] = x
}
return byId
},
// truncate10ths(16.1999999312682) == 16.1
truncate10ths: (x) => {
return Math.floor(x * 10) / 10
},
// truncate100ths(16.1999999312682) == 16.19
truncate100ths: (x) => {
return Math.floor(x * 100) / 100
},
// truncate100ths(16.1999999312682) == 16.199
truncate1000ths: (x) => {
return Math.floor(x * 1000) / 1000
},
// truncate10000ths(16.1999999312682) == 16.1999
truncate10000ths: (x) => {
return Math.floor(x * 10000) / 10000
},
// Round a number to a certain precision. Useful for js floats: precisionRound(16.1999999312682. 5) == 16.2
precisionRound(number, precision = 5) {
const factor = Math.pow(10, precision)
return Math.round(number * factor) / factor
},
// Reverse an object's keys/values
flipMapping: (obj) => {
return Object.fromEntries(Object.entries(obj).map((a) => a.reverse()))
},
// Deep clone an object, different implementations have different browser performance impacts
clone: (obj) => {
if (!obj) return null // TODO is this a good idea
return JSON.parse(JSON.stringify(obj))
},
// Used for antd's selects to allow searching by the lowercase label
labelFilterOption: (input, option) => {
return (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
},
// TODO: standardize all these
nameFilterOption: (input, option) => {
return (option?.name ?? '').toLowerCase().includes(input.toLowerCase())
},
titleFilterOption: (input, option) => {
return (option?.title ?? '').toLowerCase().includes(input.toLowerCase())
},
// Returns body/feet/rope/sphere
hasMainStat: (part) => {
return part == Constants.Parts.Body || part == Constants.Parts.Feet || part == Constants.Parts.LinkRope || part == Constants.Parts.PlanarSphere
},
// Used to convert output formats for relic scorer, snake-case to camelCase
recursiveToCamel: (item) => {
if (Array.isArray(item)) {
return item.map((el) => Utils.recursiveToCamel(el))
} else if (typeof item === 'function' || item !== Object(item)) {
return item
}
return Object.fromEntries(
Object.entries(item).map(([key, value]) => [
key.replace(/([-_][a-z])/gi, (c) => c.toUpperCase().replace(/[-_]/g, '')),
Utils.recursiveToCamel(value),
]),
)
},
// Generate a random uuid
randomId: () => {
return uuidv4()
},
// hsr-optimizer// => hsr-optimizer
stripTrailingSlashes: (str) => {
return str.replace(/\/+$/, '')
},
// 5, 4, 3
sortRarityDesc: (a, b) => {
return b.rarity - a.rarity
},
// [1, 2, 3] => 6
sumArray: (arr) => {
return arr.reduce((accumulator, currentValue) => accumulator + currentValue, 0)
},
msToReadable: (duration) => {
const seconds = Math.floor((duration / 1000) % 60)
const minutes = Math.floor((duration / (1000 * 60)) % 60)
const hours = Math.floor((duration / (1000 * 60 * 60)))
const hoursS = hours > 0 ? `${hours}:` : ''
const minutesS = (minutes < 10) ? `0${minutes}` : `${minutes}`
const secondsS = (seconds < 10) ? `0${seconds}` : `${seconds}`
return `${hoursS}${minutesS}:${secondsS}`
},
filterUnique: (arr) => {
return arr.filter((value, index, array) => array.indexOf(value) === index)
},
}
function resolvedLanguage() {
i18next.resolvedLanguage.replace('_', '-')
}