-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkaniwani-synonym-checker.js
421 lines (337 loc) · 12.4 KB
/
kaniwani-synonym-checker.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
// ==UserScript==
// @name KaniWani Synonym Checker
// @namespace http://tampermonkey.net/
// @version 0.1
// @description Checks for synonyms before answer is submit.
// @author You
// @match https://www.kaniwani.com/*
// @icon https://www.google.com/s2/favicons?sz=64&domain=kaniwani.com
// @grant none
// @require https://unpkg.com/wanakana
// ==/UserScript==
(async function() {
'use strict';
class Utils {
// modified from https://stackoverflow.com/a/16436975
static arraysEqualOrdered(a, b) {
if (a === b) return true;
if (a == null || b == null) return (a == null && b == null);
if (a.length !== b.length) return false;
for (let i = 0; i < a.length; ++i) {
if (a[i] !== b[i]) return false;
}
return true;
}
// https://developer.mozilla.org/en-US/docs/Web/JavaScript
// /Reference/Global_Objects/Set
static intersection(a, b) {
return new Set([...a].filter(x => b.has(x)));
}
static areSetsIntersecting(a, b) {
for (const x of a) {
if (b.has(x)) return true;
}
return false;
}
// https://stackoverflow.com/a/44827922
static areSetsEqual(a, b) {
return a.size === b.size && [...a].every(value => b.has(value));
}
}
class Hook {
#session;
#callbacks = [];
constructor(session) {
this.#session = session;
}
register(callback) {
this.#callbacks.push(callback);
}
call(event = null, data = null) {
const messages = []
for (const callback of this.#callbacks) {
const result = callback(this.#session, event, data, messages);
messages.push(result);
if ((result === false) || (event && event.cancelBubble)) {
return false;
}
}
return true;
}
clear() {
this.#callbacks = [];
}
}
class Session {
sessionStartHook;
sessionEndHook;
submitAnswerHook;
#selectors = new Map([
['answerField', '#answer'],
['questionBox', 'div.lltPfd'],
['primary', 'div[data-question-primary]'],
['secondary', 'div[data-question-secondary]'],
['partsOfSpeech', 'ul.hyPboY'],
['submitButton', 'button[aria-label="Submit answer"]'],
]);
#elements = new Map();
#app;
#subjects;
#twins;
#possibleAnswers = null;
static states = Object.freeze({
INITIALIZING: Symbol('INITIALIZING'),
NOT_IN_SESSION: Symbol('NOT_IN_SESSION'),
AWAITING_ANSWER: Symbol('AWAITING_ANSWER'),
AWAITING_CONFIRMATION: Symbol('AWAITING_CONFIRMATION'),
});
#state = Session.states.NOT_IN_SESSION;
constructor(subjects, twins) {
this.#subjects = subjects;
this.#twins = twins;
this.#app = document.querySelector('#app');
this.sessionStartHook = new Hook(this);
this.sessionEndHook = new Hook(this);
this.submitAnswerHook = new Hook(this);
this.#observeReviewSession();
}
static createSession() {
const url = 'https://raw.githubusercontent.com/panda-byte/'
+ 'kaniwani-synonym-checker/main/data/';
return Promise.all([
fetch(`${url}vocab_subjects.json`),
fetch(`${url}twins.json`),
]).then(responses => Promise.all(responses.map(
response => response.json()
))).then(objects => {
return new Session(
new Map(Object.entries(objects[0])),
new Map(objects[1])
);
});
}
#observeReviewSession() {
const checkURL = () => {
if (document.URL.endsWith('/reviews/session')) {
if (!this.inSession()) {
this.#setState(Session.states.INITIALIZING);
this.#initSession();
}
} else {
if (this.inSession()) {
this.#endSession();
}
}
}
checkURL();
new MutationObserver(checkURL).observe(
this.#app, {childList: true, subtree: true}
);
}
get state(){
return this.#state;
}
#setState(state) {
console.log("New state: ");
console.log(state);
this.#state = state;
}
inSession() {
return this.#state !== Session.states.NOT_IN_SESSION
}
#startSession() {
console.log("Session started!");
this.#awaitAnswer();
window.addEventListener(
'click', this.#clickListener.bind(this), {capture: true}
);
window.addEventListener(
'keydown', this.#keyDownListener.bind(this), {capture: true}
);
this.sessionStartHook.call();
}
#awaitAnswer() {
this.#setState(Session.states.AWAITING_ANSWER);
const secondaryText = this.#elements.get('secondary').textContent.trim();
// TODO: find out correct answer
const hints = {
primary: this.#elements.get('primary').textContent,
secondary: secondaryText ?
secondaryText.split(', ') : [],
partsOfSpeech: [
...this.#elements.get('partsOfSpeech')
.querySelectorAll('li > span')
].map(span => this.#adjustPartOfSpeech(span.textContent))
}
const meanings = new Set([hints.primary, ...hints.secondary]);
this.#possibleAnswers = Array.from(this.#subjects.values()).filter(
subject => Utils.areSetsIntersecting(
meanings, new Set([
subject.primary_meaning, ...subject.other_meanings
])
)
);
console.log("Possible answers: ");
console.log(this.#possibleAnswers);
console.log(hints.partsOfSpeech);
console.log(this.#possibleAnswers[0].parts_of_speech);
console.log(Utils.areSetsEqual(
new Set(hints.partsOfSpeech),
new Set(this.#possibleAnswers[0].parts_of_speech)
));
// TODO Include parts of speech in vocab!
}
#endSession() {
console.log("Session ended!");
this.#setState(Session.states.NOT_IN_SESSION);
this.sessionEndHook.call();
this.#elements.clear();
}
#clickListener(event) {
if (!this.inSession()) {
return;
}
console.log("Captured click!");
if (this.#elements.get('submitButton').contains(event.target)) {
this.#submitAnswer(event);
}
}
#keyDownListener(event) {
if (!this.inSession()) {
return;
}
console.log("Captured keydown!");
if (event.key === 'Enter') {
this.#submitAnswer(event);
} else if (event.key === 'Backspace') {
if (this.#state === Session.states.AWAITING_CONFIRMATION) {
this.#ignoreResult();
}
}
}
#isValidCharacter(char) {
// see https://stackoverflow.com/questions/19899554/unicode-range-for-japanese
return (
wanakana.isKana()
|| wanakana.isKanji()
|| char.match(/[\d!?n\u3000-\u30ff\uff00-\uffef\u4e00-\u9faf]/)
);
}
#isValidAnswer(answer) {
for (const char of answer) {
if (!this.#isValidCharacter(char)) {
return false;
}
}
return true;
}
#adjustAnswer(answer) {
if (answer.endsWith('n')) {
return answer.replace('n', 'ん');
}
return answer;
}
#adjustPartOfSpeech(partOfSpeech) {
partOfSpeech = partOfSpeech.toLowerCase();
const mapping = new Map([
['numeric', 'numeral']
]);
if (mapping.has(partOfSpeech)) {
partOfSpeech = mapping.get(partOfSpeech);
}
return partOfSpeech;
}
#submitAnswer(event) {
const answer = this.#elements.get('answerField').value;
if (!this.#isValidAnswer(answer)) {
console.log("Invalid answer!");
return;
}
const secondary = this.#elements.get('secondary').textContent;
const data = {
answer: this.#adjustAnswer(answer),
question: {
primary: this.#elements.get('primary').textContent,
secondary: secondary ? secondary.split(', ') : [],
partsOfSpeech: [
...this.#elements.get('partsOfSpeech')
.querySelectorAll('li > span')
].map(span => this.#adjustPartOfSpeech(span.textContent))
}
};
if (!this.submitAnswerHook.call(event, data)) {
console.log("Submitting answer was stopped by callback!");
return;
}
this.#setState(Session.states.AWAITING_CONFIRMATION);
}
#ignoreResult() {
this.#setState(Session.states.AWAITING_ANSWER);
}
#initSession() {
const findElements = (_, observer) => {
let foundAll = true;
for (const [name, selector] of this.#selectors.entries()) {
if (this.#elements.has(name)) {
continue;
}
const element = document.querySelector(selector);
if (element) {
this.#elements.set(name, element);
} else {
foundAll = false;
}
}
if (foundAll) {
observer.disconnect();
this.#elements.set(
'answerBox',
this.#elements.get('answerField').parentElement
);
this.#startSession();
}
}
const observer = new MutationObserver(findElements);
findElements(null, observer);
observer.observe(this.#app, {childList: true, subtree: true});
}
}
class SynonymChecker {
#session;
#subjects;
#allSynonyms;
#allTwins;
constructor(session) {
this.#session = session;
this.#fetchSubjects().then(this.#registerHooks.bind(this));
}
#fetchSubjects() {
const url = 'https://raw.githubusercontent.com/panda-byte/'
+ 'kaniwani-synonym-checker/main/data/';
return Promise.all([
fetch(`${url}vocab_subjects.json`),
fetch(`${url}vocab_synonyms.json`),
fetch(`${url}twins.json`),
]).then(responses => Promise.all(responses.map(
response => response.json()
))).then(objects => {
this.#subjects = new Map(Object.entries(objects[0]));
this.#allSynonyms = new Map(Object.entries(objects[1]));
this.#allTwins = new Map(objects[2]);
}).catch(() => {
console.error("Could not fetch subjects!");
});
}
#registerHooks() {
this.#session.submitAnswerHook.register((session, event, data, messages) => {
console.log("Answer submitted!");
console.log(session);
console.log(event);
console.log(data);
console.log(messages);
}
);
}
}
Session.createSession().then(session => new SynonymChecker(session));
})();