forked from ynoproject/forest-orb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
2kki.js
513 lines (441 loc) · 19.4 KB
/
2kki.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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
const is2kki = gameId === '2kki';
let gameVersion;
const pendingRequests = {};
function send2kkiApiRequest(url, callback) {
if (pendingRequests.hasOwnProperty(url))
pendingRequests[url].push(callback);
else {
pendingRequests[url] = [ callback ];
const req = new XMLHttpRequest();
req.responseType = 'json';
req.open('GET', url);
req.timeout = 10000;
req.send();
let onReqEnd = _e => {
for (let cb of pendingRequests[url])
// response is null if request was not successful
cb(req.response);
delete pendingRequests[url];
};
req.onloadend = req.ontimeout = onReqEnd;
}
}
function onLoad2kkiMap(mapId) {
const prevMapId = cachedMapId;
const prevLocations = prevMapId ? cached2kkiLocations : null;
const locationKey = `${(prevMapId || '0000')}_${mapId}`;
let locations = locationCache[locationKey] || null;
if (locations && typeof locations === 'string')
locations = null;
if (!cachedMapId)
document.getElementById('location').classList.remove('hidden');
if (locations && locations.length) {
const locationNames = Array.isArray(locations) ? locations.map(l => l.title) : null;
set2kkiClientLocation(mapId, prevMapId, locations, prevLocations);
cachedPrevMapId = cachedMapId;
cachedMapId = mapId;
cachedPrev2kkiLocations = cached2kkiLocations;
cached2kkiLocations = locationNames ? locations : null;
if (localizedMapLocations) {
if (!cached2kkiLocations || !cachedLocations || JSON.stringify(locations) !== JSON.stringify(cachedLocations))
addChatMapLocation(cached2kkiLocations);
cachedLocations = cached2kkiLocations;
}
if (!locationNames) {
set2kkiExplorerLinks(null);
setMaps([]);
} else {
set2kkiExplorerLinks(locationNames);
if (mapCache.hasOwnProperty(locationNames.join(',')))
setMaps(mapCache[locationNames.join(',')], locationNames);
else
queryAndSet2kkiMaps(locationNames).catch(err => console.error(err));
}
if (playerData?.badge && badgeCache.find(b => b.badgeId === playerData.badge)?.overlayType & BadgeOverlayType.LOCATION)
updateBadgeButton();
} else {
queryAndSet2kkiLocation(mapId, prevMapId, prevLocations, set2kkiClientLocation, true)
.then(locations => {
const locationNames = locations ? locations.map(l => l.title) : null;
set2kkiExplorerLinks(locationNames);
if (locationNames)
queryAndSet2kkiMaps(locationNames).catch(err => console.error(err));
else {
setMaps([], null, true, true);
set2kkiExplorerLinks(null);
}
syncLocationChange();
checkEventLocations();
if (playerData?.badge && badgeCache.find(b => b.badgeId === playerData.badge)?.overlayType & BadgeOverlayType.LOCATION)
updateBadgeButton();
}).catch(err => console.error(err));
}
}
function queryAndSet2kkiLocation(mapId, prevMapId, prevLocations, setLocationFunc, forClient) {
return new Promise((resolve, reject) => {
let url = `${apiUrl}/2kki?action=getMapLocationNames&mapId=${mapId}`;
if (prevMapId) {
url += `&prevMapId=${prevMapId}`;
if (prevLocations && prevLocations.length)
url += `&prevLocationNames=${prevLocations.map(l => l.title).join('&prevLocationNames=')}`;
}
if (!setLocationFunc)
setLocationFunc = () => {};
const callback = response => {
const locationsArray = response;
const locations = [];
const cacheAndResolve = () => {
if (forClient) {
cachedPrevMapId = cachedMapId;
cachedMapId = mapId;
cachedPrev2kkiLocations = cached2kkiLocations;
cached2kkiLocations = locations;
if (localizedMapLocations) {
if (!locations || !cachedLocations || JSON.stringify(locations) !== JSON.stringify(cachedLocations))
addChatMapLocation(cached2kkiLocations);
cachedLocations = cached2kkiLocations;
}
}
resolve(locations);
};
if (Array.isArray(locationsArray) && locationsArray.length) {
let location = locationsArray[0];
let usePrevLocations = false;
if (locationsArray.length > 1 && prevLocations && prevLocations.length) {
for (let l of locationsArray) {
if (l.title === prevLocations[0].title) {
location = l;
usePrevLocations = true;
break;
}
}
}
if (usePrevLocations)
locations.push(location);
else {
for (let l of locationsArray)
locations.push(l);
}
if (usePrevLocations) {
queryConnected2kkiLocationNames(location.title, locationsArray.filter(l => l.title !== location.title).map(l => l.title))
.then(connectedLocationNames => {
const connectedLocations = locationsArray.filter(l => connectedLocationNames.indexOf(l.title) > -1);
for (let cl of connectedLocations)
locations.push(cl);
setLocationFunc(mapId, prevMapId, locations, prevLocations, true, true);
cacheAndResolve();
}).catch(err => reject(err));
return;
} else
setLocationFunc(mapId, prevMapId, locations, prevLocations, true, true);
} else {
const errCode = !Array.isArray(response) ? response?.err_code : null;
if (errCode)
console.error({ error: response.error, errCode: errCode });
if (prevMapId) {
queryAndSet2kkiLocation(mapId, null, null, setLocationFunc, forClient).then(() => resolve(null)).catch(err => reject(err));
return;
}
setLocationFunc(mapId, prevMapId, null, prevLocations, true, true);
}
cacheAndResolve();
};
send2kkiApiRequest(url, callback);
setLocationFunc(mapId, prevMapId, getMassagedLabel(localizedMessages.location.queryingLocation), prevLocations, true);
});
}
function set2kkiClientLocation(mapId, prevMapId, locations, prevLocations, cacheLocation, saveLocation) {
document.getElementById('locationText').innerHTML = getLocalized2kkiLocationsHtml(locations, '<br>');
onUpdateChatboxInfo();
preloadFilesFromMapId(mapId);
if (cacheLocation) {
const locationKey = `${(prevMapId || '0000')}_${mapId}`;
const prevLocationKey = `${mapId}_${(prevMapId || '0000')}`;
const cachePrev = Array.isArray(prevLocations) && prevLocations.filter(l => l.titleJP).length;
if (locations)
locationCache[locationKey] = locations;
if (cachePrev)
locationCache[prevLocationKey] = prevLocations;
if (saveLocation && (locations || prevLocations)) {
if (locations)
setCacheValue(CACHE_TYPE.location, locationKey, locations);
if (cachePrev)
setCacheValue(CACHE_TYPE.location, prevLocationKey, prevLocations);
updateCache(CACHE_TYPE.location);
}
}
}
function getLocalized2kkiLocation(title, titleJP, asHtml, forDisplay) {
let template = localizedMessages[forDisplay ? 'locationDisplay' : 'location']['2kki'].template;
if (asHtml)
template = template.replace(/}([^{]+)/g, '}<span class="infoLabel">$1</span>');
return getMassagedLabel(template).replace('{LOCATION}', title).replace('{LOCATION_JP}', titleJP || '');
}
function getLocalized2kkiLocations(locations, separator, forDisplay) {
return locations && locations.length
? Array.isArray(locations)
? locations.map(l => getLocalized2kkiLocation(l.title, l.titleJP, false, forDisplay)).join(separator)
: locations
: getMassagedLabel(localizedMessages.location.unknownLocation);
}
function get2kkiLocationHtml(location) {
const urlTitle = location.urlTitle || location.title;
const urlTitleJP = location.urlTitleJP || (location.titleJP && location.titleJP.indexOf(':') > -1 ? location.titleJP.slice(0, location.titleJP.indexOf(':')) : location.titleJP);
const locationHtml = `<a href="${gameLocationUrlRoots['2kki'] || locationUrlRoot}${urlTitle}" target="_blank">${location.title}</a>`;
const locationHtmlJP = urlTitleJP ? `<a href="${gameLocalizedLocationUrlRoots['2kki'] || localizedLocationUrlRoot}${urlTitleJP}" target="_blank">${location.titleJP}</a>` : null;
return locationHtmlJP ? getLocalized2kkiLocation(locationHtml, locationHtmlJP, true) : locationHtml;
}
function getLocalized2kkiLocationsHtml(locations, separator) {
return locations && locations.length
? Array.isArray(locations)
? locations.map(l => get2kkiLocationHtml(l)).join(separator)
: getInfoLabel(locations)
: getInfoLabel(getMassagedLabel(localizedMessages.location.unknownLocation));
}
function getOrQuery2kkiLocations(mapId, prevMapId, prevLocations, callback) {
const callbackFunc = (_mapId, _prevMapId, locations, prevLocations, cacheLocation, saveLocation) => {
callback(locations);
if (cacheLocation) {
const locationKey = `${prevMapId}_${mapId}`;
const prevLocationKey = `${mapId}_${prevMapId}`;
const cachePrev = Array.isArray(prevLocations) && prevLocations.filter(l => l.titleJP).length;
if (locations)
locationCache[locationKey] = locations;
if (cachePrev)
locationCache[prevLocationKey] = prevLocations;
if (saveLocation && (locations || prevLocations)) {
if (locations)
setCacheValue(CACHE_TYPE.location, locationKey, locations);
if (cachePrev)
setCacheValue(CACHE_TYPE.location, prevLocationKey, prevLocations);
updateCache(CACHE_TYPE.location);
}
}
};
if (localizedMapLocations?.hasOwnProperty(mapId))
callbackFunc(mapId, prevMapId, localizedMapLocations[mapId], prevLocations);
else {
if (!prevMapId)
prevMapId = '0000';
const locationKey = `${prevMapId}_${mapId}`;
if (locationCache?.hasOwnProperty(locationKey) && Array.isArray(locationCache[locationKey]))
callbackFunc(mapId, prevMapId, locationCache[locationKey], prevLocations);
else
queryAndSet2kkiLocation(mapId, prevMapId !== '0000' ? prevMapId : null, prevLocations, callbackFunc)
.catch(err => console.error(err));
}
}
function set2kkiGlobalChatMessageLocation(globalMessageLocation, mapId, prevMapId, prevLocations) {
getOrQuery2kkiLocations(mapId, prevMapId, prevLocations, locations => {
const locationsHtml = getLocalized2kkiLocationsHtml(locations, getInfoLabel(' | '));
globalMessageLocation.innerHTML = locationsHtml;
if (globalMessageLocation.dataset.systemOverride)
applyThemeStyles(globalMessageLocation, globalMessageLocation.dataset.systemOverride);
});
}
function getOrQuery2kkiLocationsHtml(mapId, callback) {
let locationKey = `0000_${mapId}`;
if (locationCache && !locationCache.hasOwnProperty(locationKey)) {
const locationKeys = Object.keys(locationCache).filter(k => k.endsWith(mapId) && Array.isArray(locationCache[k]));
if (locationKeys.length === 1 || locationKeys.map(k => JSON.stringify(locationCache[k])).filter((value, index, self) => self.indexOf(value) === index).length === 1)
locationKey = locationKeys[0];
}
let prevMapId = locationKey.slice(0, 4);
const setLocationFunc = (_mapId, _prevMapId, locations, _prevLocations, cacheLocation, saveLocation) => {
if (cacheLocation) {
const locationKey = `${prevMapId}_${mapId}`;
if (locations)
locationCache[locationKey] = locations;
if (saveLocation && locations) {
setCacheValue(CACHE_TYPE.location, locationKey, locations);
updateCache(CACHE_TYPE.location);
}
}
callback(getLocalized2kkiLocationsHtml(locations, getInfoLabel(' | ')));
};
if (locationCache?.hasOwnProperty(locationKey) && Array.isArray(locationCache[locationKey]))
setLocationFunc(mapId, null, locationCache[locationKey]);
else {
prevMapId = '0000';
queryAndSet2kkiLocation(mapId, prevMapId, null, setLocationFunc)
.catch(err => console.error(err));
}
}
function queryConnected2kkiLocationNames(locationName, connLocationNames) {
return new Promise((resolve, _reject) => {
const url = `${apiUrl}/2kki?action=getConnectedLocations&locationName=${locationName}&connLocationNames=${connLocationNames.join('&connLocationNames=')}`;
const callback = response => {
let ret = [];
let errCode = null;
if (Array.isArray(response))
ret = response;
else
errCode = response?.err_code;
if (errCode)
console.error({ error: response.error, errCode: errCode });
resolve(ret);
};
send2kkiApiRequest(url, callback);
});
}
function queryAndSet2kkiMaps(locationNames) {
return new Promise((resolve, _reject) => {
const massagedLocationNames = locationNames.map(locationName => {
const colonIndex = locationName.indexOf(':');
if (colonIndex > -1)
locationName = locationName.slice(0, colonIndex);
return locationName;
});
const url = `${apiUrl}/2kki?action=getLocationMaps&locationNames=${massagedLocationNames.join('&locationNames=')}`;
const callback = response => {
let errCode = null;
if (Array.isArray(response))
setMaps(response, locationNames, true, true);
else
errCode = response?.err_code;
if (errCode)
console.error({ error: response.error, errCode: errCode });
resolve();
};
send2kkiApiRequest(url, callback);
setMaps([], null, true);
});
}
function set2kkiExplorerLinks(locationNames) {
const explorerControls = document.getElementById('explorerControls');
if (!explorerControls)
return;
explorerControls.innerHTML = '';
if (!locationNames)
return;
for (let locationName of locationNames)
explorerControls.appendChild(get2kkiExplorerButton(locationName, locationNames.length > 1))
}
function get2kkiExplorerButton(locationName, isMulti) {
const ret = document.createElement('button');
const localizedExplorerLinks = localizedMessages['2kki'].explorerLink;
addTooltip(ret, getMassagedLabel(!isMulti ? localizedExplorerLinks.generic : localizedExplorerLinks.multi, true).replace('{LOCATION}', locationName), true, true);
ret.classList.add('unselectable', 'iconButton');
const url = `https://2kki.app/?location=${locationName}&lang=${globalConfig.lang}`;
ret.onclick = () => {
const handle = window.open(url, '_blank');
if (handle)
handle.focus();
};
ret.innerHTML = '<svg viewbox="0 0 18 18" fill="none" xmlns="http://www.w3.org/2000/svg" width="24" height="24"><path d="m6.75 0v4.5h4.5v-4.5h-4.5m2.25 4.5v4.5h-1.5v3h3v-3h-1.5m0-3h-7.5v3h-1.5v3h3v-3h-1.5m7.5-3h7.5v3h-1.5v3h3v-3h-1.5m-7.5 3v3.75h-1.125v2.25h2.25v-2.25h-1.125m0-2.25h-7.5v2.25h-1.125v2.25h2.25v-2.25h-1.125m7.5-2.25h7.5v2.25h-1.125v2.25h2.25v-2.25h-1.125"></path></svg>';
return ret;
}
function get2kkiWikiLocationName(location) {
if (typeof location === 'string')
return location;
let locationName = location.title;
if (location.urlTitle)
locationName = location.urlTitle.replace(/%26/g, "&").replace(/%27/g, "'").replace(/\_/g, " ").replace(/#.*/, "");
else {
const colonIndex = locationName.indexOf(':');
if (colonIndex > -1)
locationName = locationName.slice(0, colonIndex);
}
return locationName;
}
function init2kkiFileVersionAppend() {
if (!gameVersion)
return;
const ca = wasmImports.ca;
wasmImports.ca = function (url, file, request, param, arg, onload, onerror, onprogress) {
let _url = UTF8ToString(url);
if (_url)
url = stringToNewUTF8(`${_url}${_url.indexOf('?') > -1 ? '&' : '?'}v=${gameVersion}`);
ca(url, file, request, param, arg, onload, onerror, onprogress);
};
}
function checkShow2kkiVersionUpdate() {
return new Promise(resolve => {
const chatboxContainer = document.getElementById('chatboxContainer');
const versionDisplay = document.querySelector('.versionDisplay');
const removeUpdateDisplayAndResolve = () => {
chatboxContainer.classList.remove('hidden');
setTimeout(() => versionDisplay.remove());
document.querySelector('.versionDisplayZoom')?.remove();
onResize();
resolve();
};
const currentVersion = document.querySelector('meta[name="2kkiVersion"]').content;
if (!currentVersion || currentVersion === config.last2kkiVersion)
return removeUpdateDisplayAndResolve();
chatboxContainer.classList.add('hidden');
const versionText = document.querySelector('.version').innerText;
const versionPrefixText = versionText.slice(0, versionText.indexOf(currentVersion));
const versionNewSuffixText = versionText.slice(versionPrefixText.length);
const versionOldSuffixText = getLocalizedVersion(config.last2kkiVersion).slice(versionPrefixText.length);
const versionPrefix = document.createElement('h1');
versionPrefix.innerText = versionPrefixText.trim();
if (versionPrefixText.endsWith(' '))
versionPrefix.innerHTML += ' ';
versionDisplay.appendChild(versionPrefix);
const versionSuffix = document.createElement('h1');
versionSuffix.classList.add('versionDisplaySuffix');
const versionNewSuffix = document.createElement('span');
versionNewSuffix.classList.add('infoLabel');
versionNewSuffix.innerText = versionNewSuffixText;
const versionOldSuffix = document.createElement('span');
versionOldSuffix.classList.add('infoLabel');
versionOldSuffix.innerText = versionOldSuffixText;
versionSuffix.appendChild(versionOldSuffix);
versionSuffix.appendChild(versionNewSuffix);
versionDisplay.appendChild(versionSuffix);
versionDisplay.classList.remove('hidden');
config.last2kkiVersion = currentVersion;
updateConfig(config);
setTimeout(() => {
const textHeight = versionPrefix.offsetHeight;
versionSuffix.style.height = `${textHeight}px`;
versionDisplay.classList.remove('transparent');
setTimeout(() => versionOldSuffix.style.marginTop = `-${textHeight + 4}px`, 1000);
setTimeout(() => {
const versionDisplayZoom = versionDisplay.cloneNode(true);
versionDisplayZoom.classList.add('versionDisplayZoom');
versionDisplay.after(versionDisplayZoom);
setTimeout(() => versionDisplayZoom.classList.add('zoom', 'transparent'), 10);
}, 1875);
setTimeout(removeUpdateDisplayAndResolve, 3500);
}, 0);
});
}
(function () {
if (!is2kki)
return;
addSessionCommandHandler('l', () => {
if (!config.enableExplorer)
return;
const explorerFrame = document.getElementById('explorerFrame');
if (!cachedLocations) {
explorerFrame.src = '';
return;
}
const locationNames = cachedLocations.map(l => get2kkiWikiLocationName(l));
if (explorerFrame && locationNames && loginToken) {
addLoader(explorerFrame, true);
explorerFrame.onload = () => removeLoader(explorerFrame);
apiFetch('explorer').then(response => {
if (!response.ok)
throw new Error(response.statusText);
return response.text();
})
.then(url => {
const newUrl = url ? `${url}&lang=${globalConfig.lang}` : '';
if (explorerFrame.src !== newUrl) {
explorerFrame.src = newUrl;
apiFetch('explorercompletion')
.then(response => response.text())
.then(textResponse => {
const completionPercent = parseInt(textResponse);
document.getElementById('explorerUndiscoveredLocationsLink').classList.toggle('hidden', !completionPercent || completionPercent < 95);
});
} else
removeLoader(explorerFrame);
})
.catch(err => console.error(err));
}
});
})();