-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathamqVivaceShortcuts.user.js
512 lines (456 loc) · 14 KB
/
amqVivaceShortcuts.user.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
// ==UserScript==
// @name AMQ Vivace! Shortcuts
// @namespace http://tampermonkey.net/
// @version 1.6
// @description Displays at least 3 of the shortest shortcuts for an anime after guessing phase, defined as the shortest substrings of length 10 or less for which the target anime (or any of its alt names) is the first suggestion in the dropdown list (or one of the top ones, in case it is not possible to do better). Adapted from https://github.com/tutti-amq/amq-scripts/blob/main/animeShortcuts.user.js All shortcuts with the smallest length are displayed. Click on a shortcut to highlight it and move it to the front of the list.
// @author Einlar, Tutti
// @match https://animemusicquiz.com/*
// @match https://*.animemusicquiz.com/*
// @downloadURL https://github.com/Einlar/AMQScripts/raw/main/amqVivaceShortcuts.user.js
// @updateURL https://github.com/Einlar/AMQScripts/raw/main/amqVivaceShortcuts.user.js
// @require https://github.com/joske2865/AMQ-Scripts/raw/master/common/amqScriptInfo.js
// @grant none
// @icon https://i.imgur.com/o8hOqsv.png
// ==/UserScript==
/**
* CHANGELOG
*
* v1.6
* - Remove shortcuts containing "∞" (e.g. for "Naki∞Neko")
* - Fix a bug that prevented to highlight shortcuts containing a " (double quote).
*
* v1.5
* - Make the script work also on AMQ subdomains (since at the moment the main AMQ domain is not working).
*
* v1.4
* - Click on a shortcut to highlight it and move it to the front of the list. The highlighed shortcuts are stored in local storage.
*
* v1.3
* - Shortcuts are now even more optimized! They will exploit the replacement rules used by AMQ.
* For instance, an optimal shortcut for "Kaguya-sama wa Kokurasetai?: Tensai-tachi no Renai Zunousen" is "? t", because a single space can be used to match any number of consecutive special characters.
* - A few special characters are now allowed in the shortcuts (currently any of /*=+:;-?,.!@_#). Also all the characters that AMQ does not match with a space are allowed (e.g. "°", so you can use it as a shortcut for "Gintama°")
*/
/** @type {JQuery<HTMLElement>} */
var infoDiv;
/**
* The maximum number of items in the dropdown list.
*/
const MAX_DROPDOWN_ITEMS = 25;
/**
* The maximum length of shortcuts to consider. If a "perfect" shortcut is found (i.e. one that is the first suggestion in the dropdown list), the search will stop.
*/
const MAX_SUBSTRING_LENGTH = 10;
/**
* Minimum number of shortcuts to display.
*/
const NUM_SHORTCUTS = 3;
/**
* @see SEARCH_CHARACTER_REPLACEMENT_MAP from AMQ code
*/
const NORMALIZATION_MAP = {
ō: "o",
ó: "o",
ò: "o",
ö: "o",
ô: "o",
ø: "o",
Φ: "o",
ū: "u",
û: "u",
ú: "u",
ù: "u",
ü: "u",
ǖ: "u",
ä: "a",
â: "a",
à: "a",
á: "a",
ạ: "a",
å: "a",
æ: "a",
ā: "a",
č: "c",
"★": " ",
"☆": " ",
"/": " ",
"*": " ",
"=": " ",
"+": " ",
"·": " ",
"♥": " ",
"∽": " ",
"・": " ",
"〜": " ",
"†": " ",
"×": "x", // I think we can safely replace this with "x"
"♪": " ",
"→": " ",
"␣": " ",
":": " ",
";": " ",
"~": " ",
"-": " ",
"?": " ",
",": " ",
".": " ",
"!": " ",
"@": " ",
_: " ",
"#": " ",
é: "e",
ê: "e",
ë: "e",
è: "e",
ē: "e",
ñ: "n",
"²": "",
í: "i",
"³": "",
ß: "b",
};
/**
* These special characters can normally be collapsed into a space, but they are easy enough to type, so they will be allowed in the shortcuts.
*
* @type {(keyof typeof NORMALIZATION_MAP)[]}
*/
const ALLOWED_SPECIAL_CHARACTERS = [
"/",
"*",
"=",
"+",
":",
";",
"-",
"?",
",",
".",
"!",
"@",
"_",
"#",
];
/**
* These special characters are not matched by AMQ with a space, but they should still not be allowed in shortcuts.
*
* @type {string[]}
*/
const DISALLOWED_SPECIAL_CHARACTERS = ["∞"];
/**
* Shortcuts to be shown
*
* @type {string[]}
*/
let shortcuts = [];
/**
* Key for storing the highlighted shortcuts in local storage.
*
* @type {string}
*/
const LOCAL_STORAGE_KEY = "vivaceHighlightedShortcuts";
/**
* Simulate a search in the dropdown, returning the list of suggestions.
*
* @param {string} search
* @returns {string[]}
*/
const getSuggestions = (search) => {
const regex = new RegExp(createAnimeSearchRegexQuery(search), "i");
const filteredList =
quiz.answerInput.typingInput.autoCompleteController.list.filter((anime) =>
regex.test(anime)
);
filteredList.sort((a, b) => {
return a.length - b.length || a.localeCompare(b);
});
return filteredList.slice(0, MAX_DROPDOWN_ITEMS);
};
/**
* Compute all substrings of a given string.
*
* @param {string} str
* @returns {string[]}
*/
const getAllSubstrings = (str) => {
const result = [];
for (let i = 0; i < str.length; i++) {
for (let j = i + 1; j < str.length + 1; j++) {
result.push(str.slice(i, j));
}
}
return result;
};
/**
* Transform a substring into a list of allowed alternative substrings that are equivalent for the search.
*
* @see ANIME_REGEX_REPLACE_RULES from AMQ code
*
* @param {string} substring
* @returns {string[]}
*/
const mapToAlternativeSubstrings = (substring) => {
/** @type {Set<string>} */
const alternatives = new Set();
// Add the AMQ replacement
alternatives.add(
replaceCharactersForSeachCharacters(substring).replace(
new RegExp(DISALLOWED_SPECIAL_CHARACTERS.join("|"), "g"),
""
)
);
// Apply mandatory replacements
let normalized = substring.replace(/./g, (char) => {
if (DISALLOWED_SPECIAL_CHARACTERS.includes(char)) return "";
if (ALLOWED_SPECIAL_CHARACTERS.includes(/** @type {any} */ (char)))
return char;
return NORMALIZATION_MAP[char] || char;
});
alternatives.add(normalized);
// Simple alternatives
alternatives
.add(normalized.replace(/oo/g, "o"))
.add(normalized.replace(/ou/g, "o"))
.add(normalized.replace(/uu/g, "u"));
// Find the indexes of all allowed special characters (if any)
let specialCharIndexes = Array.from(substring)
.map((char, index) =>
ALLOWED_SPECIAL_CHARACTERS.includes(/** @type {any} */ (char))
? index
: -1
)
.filter((index) => index !== -1);
// Limit to at most 3 special characters to avoid combinatorial explosion
if (specialCharIndexes.length > 3) {
specialCharIndexes = specialCharIndexes.slice(0, 3);
}
// Generate all possible combinations of replacing special characters with spaces, using a bitmask.
for (let i = 0; i < 1 << specialCharIndexes.length; i++) {
let current = normalized;
for (let j = 0; j < specialCharIndexes.length; j++) {
if (i & (1 << j)) {
current =
current.substring(0, specialCharIndexes[j]) +
" " +
current.substring(specialCharIndexes[j] + 1);
}
}
alternatives.add(current);
// Since a single space can work for multiple spaces, we need to account for other alternatives (e.g. "a c" can work also as "a c" or "a c").
while (current.includes(" ")) {
current = current.replace(" ", " ");
alternatives.add(current);
}
}
return Array.from(alternatives);
};
/**
* Find the optimal shortcuts matching any of the targets.
*
* @param {string[]} targets
* @returns
*/
const optimizedShortcuts = (targets) => {
// Create a set of all unique substrings
const allSubstrings = new Set(
// Replace non printable characters with spaces
targets
.map((t) => t.toLocaleLowerCase())
.flatMap(getAllSubstrings)
.flatMap(mapToAlternativeSubstrings)
);
// Sort the substrings by length
let sortedSubstrings = Array.from(allSubstrings).sort(
(a, b) => a.length - b.length
);
// Filter out substrings that are too long
sortedSubstrings = sortedSubstrings.filter(
(substring) => substring.length <= MAX_SUBSTRING_LENGTH
);
let minPos = Infinity;
let bestSubstring = "";
let shortcuts = [];
let currentLength = 0;
for (const substring of sortedSubstrings) {
const newLength = substring.length;
// Search for longer substrings only if there are not enough shortcuts yet, but display *all* the shortest ones
if (newLength > currentLength && shortcuts.length >= NUM_SHORTCUTS) break;
const suggestions = getSuggestions(substring);
currentLength = newLength;
const positions = targets
.map((target) => suggestions.indexOf(target))
.filter((pos) => pos != -1);
if (positions.length) {
const pos = Math.min(...positions);
if (pos < minPos) {
minPos = pos;
bestSubstring = substring;
}
// If a perfect shortcut is found, append it to the results
if (pos === 0) {
shortcuts.push(substring);
}
}
}
return shortcuts.length ? shortcuts : [bestSubstring];
};
/**
* Render the shortcuts in the infoDiv.
*/
const renderShortcuts = () => {
$(infoDiv)
.empty()
.append(
$("<h5/>").html("<b>Anime shortcuts</b>"),
...formatShortcuts(shortcuts),
$("<br/><br/>")
);
// Add event listener to the shortcuts
$(infoDiv)
.off("click", ".vivaceShortcut")
.on("click", ".vivaceShortcut", function () {
toggleHighlight($(this).data("shortcut"));
});
};
/**
* Compute the shortcuts when a song is played.
*
* @param {import('./types').AnswerResultsPayload} data
*/
const onSongPlayed = (data) => {
const targets = [
data.songInfo.animeNames.english,
data.songInfo.animeNames.romaji,
...data.songInfo.altAnimeNames,
].flatMap((a) => a);
shortcuts = optimizedShortcuts(targets);
renderShortcuts();
};
/**
* Toggle the highlight of a shortcut and store the state in local storage.
*
* @param {string | number} shortcut
*/
const toggleHighlight = (shortcut) => {
const str = String(shortcut);
/** @type {string[]} */
let highlightedShortcuts = JSON.parse(
localStorage.getItem(LOCAL_STORAGE_KEY) || "[]"
);
if (highlightedShortcuts.includes(str)) {
highlightedShortcuts = highlightedShortcuts.filter((s) => s !== str);
} else {
highlightedShortcuts.push(str);
}
localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(highlightedShortcuts));
renderShortcuts();
};
/**
* Convert a list of shortcuts into a formatted HTML string.
*
* @param {string[]} shortcuts
* @returns {JQuery<HTMLElement>[]}
*/
const formatShortcuts = (shortcuts) => {
let uniqueShortcuts = shortcuts.filter(onlyUnique);
let highlightedShortcuts = JSON.parse(
localStorage.getItem(LOCAL_STORAGE_KEY) || "[]"
).map(String);
/** @type {JQuery<HTMLElement>[]} */
let shortcutEls = [];
// Reorder the shortcuts so that the highlighted ones are first. Keep the order of the rest.
uniqueShortcuts = uniqueShortcuts.sort(
(a, b) =>
highlightedShortcuts.includes(b) - highlightedShortcuts.includes(a)
);
uniqueShortcuts.forEach((shortcut) => {
let isHighlighted = highlightedShortcuts.includes(shortcut);
shortcutEls.push(
$(`<code/>`, {
class: `vivaceShortcut${isHighlighted ? " vivaceHighlighted" : ""}`,
data: { shortcut },
}).html(shortcut.replace(/ /g, " "))
);
});
return shortcutEls;
};
/**
* A filter function to keep only the unique elements in an array.
*
* @template T
* @param {T} value
* @param {number} index
* @param {T[]} self
* @returns {boolean}
*/
function onlyUnique(value, index, self) {
return self.indexOf(value) === index;
}
/**
* Preload dropdown when spectating, so that the shortcuts are available immediately
*/
const preloadDropdown = () => {
if (quiz.answerInput.typingInput.autoCompleteController.list.length === 0) {
quiz.answerInput.typingInput.autoCompleteController.updateList();
}
};
const setupShortcuts = () => {
const boxDiv = document.querySelector("div.qpSideContainer > div.row");
infoDiv = $("<div/>", {
class: "rowAnimeShortcuts",
css: {
overflow: "auto",
maxHeight: "100px",
lineHeight: "1.7",
},
});
const parentDiv = boxDiv?.parentElement;
if (!parentDiv) return;
$(parentDiv).children().eq(4).before(infoDiv);
new Listener("answer results", onSongPlayed).bindListener();
new Listener("Spectate Game", (game) => {
if (!game.inLobby) preloadDropdown();
}).bindListener();
new Listener("Game Starting", preloadDropdown).bindListener();
};
/**
* Add metadata to the "Installed Userscripts" list & populate CSS
*/
const setupMetadata = () => {
// @ts-ignore
// eslint-disable-next-line no-undef
AMQ_addScriptData({
name: "AMQ Vivace! Shortcuts",
author: "Einlar",
version: "1.4",
link: "https://github.com/Einlar/AMQScripts",
description: `
<p>Displays 3 or more shortest dropdown shortcuts during the results phase.</p>
<p>The shortcuts displayed are the shortest substrings of length 10 or less for which the target anime (or any of its alt names) is the first suggestion in the dropdown list (or one of the top ones, in case it is not possible to do better).</p>
<p>Shortcuts account for romaji/english names, and exploit the AMQ replacement rules for the dropdown (for instance, an optimal shortcut for "Kaguya-sama wa Kokurasetai?: Tensai-tachi no Renai Zunousen" is "? t", because a single space can be used to match any number of consecutive special characters).</p>
<p>A few special characters are now allowed in the shortcuts (currently any of /*=+:;-?,.!@_#). Also all the characters that AMQ does not match with a space are allowed (e.g. "°", so you can use it as a shortcut for "Gintama°")</p>
<p>Click on a shortcut to highlight it and move it to the front of the list. The highlighed shortcuts are stored.</p>
`,
});
// @ts-ignore
// eslint-disable-next-line no-undef
AMQ_addStyle(/*css*/ `
.vivaceShortcut {
cursor: pointer;
color: white;
background-color: #2e2c2c;
border-width: 0.5px;
border-style: solid;
border-color: white;
margin-right: 5px;
white-space: nowrap;
display: inline-block;
}
.vivaceHighlighted {
background-color: #ffeb3b;
color: black;
}
`);
};
if (window.quiz) {
setupShortcuts();
setupMetadata();
}