dracosh 0.3.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +14 -11
- package/locales/de.json +61 -9
- package/locales/en.json +61 -9
- package/locales/fr.json +63 -9
- package/locales/pl.json +65 -9
- package/locales/uk.json +65 -9
- package/package.json +1 -1
- package/src/alerts.js +68 -3
- package/src/cli.js +2 -2
- package/src/diff.js +8 -4
- package/src/judge.js +143 -10
- package/src/language.js +355 -0
- package/src/library.js +31 -5
- package/src/manage.js +48 -3
- package/src/progress.js +43 -4
- package/src/scheduler.js +23 -3
- package/src/session.js +54 -22
- package/src/settings.js +2 -1
- package/src/store.js +2 -1
- package/src/ui/AddCard.js +46 -2
- package/src/ui/App.js +33 -12
- package/src/ui/BadgeUnlock.js +1 -1
- package/src/ui/Decks.js +120 -12
- package/src/ui/Help.js +13 -1
- package/src/ui/Languages.js +167 -0
- package/src/ui/Settings.js +1 -0
- package/src/ui/Summary.js +23 -9
- package/src/words.js +6 -1
package/locales/uk.json
CHANGED
|
@@ -71,10 +71,12 @@
|
|
|
71
71
|
"pasteFix": "enter готово · esc назад",
|
|
72
72
|
"grading": "1 або ← не пам'ятаю · 2 або → пам'ятаю",
|
|
73
73
|
"sessionWaiting": "enter наступна картка · / команди · q вийти",
|
|
74
|
-
"decks": "→
|
|
75
|
-
"directionPick": "{choose} · esc або набір далі залишає 1",
|
|
74
|
+
"decks": "→ налаштування · {choose}",
|
|
75
|
+
"directionPick": "{choose} · → мови · esc або набір далі залишає 1",
|
|
76
76
|
"addName": "enter створити · esc скасувати",
|
|
77
|
-
"confirm": "{yes} так · {no} ні"
|
|
77
|
+
"confirm": "{yes} так · {no} ні",
|
|
78
|
+
"languagePick": "пиши, щоб шукати · ↑/↓ вибрати · enter підтвердити · ← назад",
|
|
79
|
+
"choiceLeft": "{choose} · ← назад"
|
|
78
80
|
},
|
|
79
81
|
"settings": {
|
|
80
82
|
"title": "Налаштування",
|
|
@@ -95,6 +97,10 @@
|
|
|
95
97
|
"label": "Звук",
|
|
96
98
|
"hint": "звуки відповідей і нових карток"
|
|
97
99
|
},
|
|
100
|
+
"speak": {
|
|
101
|
+
"label": "Вимова",
|
|
102
|
+
"hint": "читає вголос слово мовою, яку ти вчиш, коли відповідь уже видно (голоси macOS)"
|
|
103
|
+
},
|
|
98
104
|
"volume": {
|
|
99
105
|
"label": "Гучність",
|
|
100
106
|
"hint": "після зміни грає зразок"
|
|
@@ -198,7 +204,12 @@
|
|
|
198
204
|
"directionSaved": "Колода «{deck}» питає по-новому з наступної картки.",
|
|
199
205
|
"front": "лицьова сторона",
|
|
200
206
|
"back": "зворот",
|
|
201
|
-
"progressKept": "Прогрес зберігається для кожного напряму, навіть вимкненого."
|
|
207
|
+
"progressKept": "Прогрес зберігається для кожного напряму, навіть вимкненого.",
|
|
208
|
+
"askRow": "Як питає",
|
|
209
|
+
"languagesRow": "Мови",
|
|
210
|
+
"detectRow": "Визначити за картками",
|
|
211
|
+
"learningRow": "Мова навчання",
|
|
212
|
+
"learningShort": "мова навчання: {language}"
|
|
202
213
|
},
|
|
203
214
|
"add": {
|
|
204
215
|
"fields": {
|
|
@@ -250,7 +261,7 @@
|
|
|
250
261
|
"youType": "вводиш {answer}",
|
|
251
262
|
"bothWays": "В обидва боки",
|
|
252
263
|
"bothWaysNote": "кожна картка в обидва боки",
|
|
253
|
-
"directionLater": "
|
|
264
|
+
"directionLater": "Усе це зміниш пізніше: /decks, потім →.",
|
|
254
265
|
"directionSet": "Гаразд: {how} · наступна картка:",
|
|
255
266
|
"paste": {
|
|
256
267
|
"title": "Вставлені картки · {deck}",
|
|
@@ -278,7 +289,12 @@
|
|
|
278
289
|
"many": "Пропущено {count} рядків: їх треба було виправити.",
|
|
279
290
|
"other": "Пропущено {count} рядка: їх треба було виправити."
|
|
280
291
|
}
|
|
281
|
-
}
|
|
292
|
+
},
|
|
293
|
+
"languagesLine": "Мови: {pair}",
|
|
294
|
+
"languagesNow": "Схоже на: {pair}. Якщо ні, виправ у /decks →.",
|
|
295
|
+
"languagesSoon": "Мови: визначу після кількох карток",
|
|
296
|
+
"learningLine": "Мова навчання: {language}",
|
|
297
|
+
"learningGuess": "це лише здогадка: → змінити"
|
|
282
298
|
},
|
|
283
299
|
"quiz": {
|
|
284
300
|
"youWrote": "твоя відповідь: ",
|
|
@@ -307,7 +323,14 @@
|
|
|
307
323
|
"dayDoneTitle": "На сьогодні все.",
|
|
308
324
|
"dayDoneNext": "Картки повернуться {when}. Хочеш ще сьогодні? Додай нові через /add.",
|
|
309
325
|
"laterTitle": "Поки що нічого повторювати.",
|
|
310
|
-
"laterNext": "Наступна картка: {when}. Вона прийде сама."
|
|
326
|
+
"laterNext": "Наступна картка: {when}. Вона прийде сама.",
|
|
327
|
+
"newTomorrow": {
|
|
328
|
+
"one": "{count} нова картка чекає на завтра (до {max} нових на день).",
|
|
329
|
+
"few": "{count} нові картки чекають на завтра (до {max} нових на день).",
|
|
330
|
+
"many": "{count} нових карток чекають на завтра (до {max} нових на день).",
|
|
331
|
+
"other": "{count} нової картки чекають на завтра (до {max} нових на день)."
|
|
332
|
+
},
|
|
333
|
+
"dayDoneHeldNext": "Картки повернуться {when}."
|
|
311
334
|
},
|
|
312
335
|
"previewNoAdd": "Попередній перегляд не додає карток; для цього запусти dracosh.",
|
|
313
336
|
"previewNoDecks": "У попередньому перегляді одна демоколода; для своїх запусти dracosh.",
|
|
@@ -329,7 +352,19 @@
|
|
|
329
352
|
},
|
|
330
353
|
"sessionProgress": "{done} з {count} у цій сесії",
|
|
331
354
|
"escAgain": "Ще раз Esc, щоб вийти.",
|
|
332
|
-
"correctConfirm": "Зарахувати «{answer}» як правильну й приймати її надалі?"
|
|
355
|
+
"correctConfirm": "Зарахувати «{answer}» як правильну й приймати її надалі?",
|
|
356
|
+
"almost": {
|
|
357
|
+
"article": "Майже: зверни увагу на артикль.",
|
|
358
|
+
"umlaut": "Майже: зверни увагу на умлаут (ä, ö, ü); можна писати ae, oe, ue.",
|
|
359
|
+
"article-umlaut": "Майже: зверни увагу на артикль і умлаут; можна писати ae, oe, ue.",
|
|
360
|
+
"held": "Картка повернеться {now}, а не {would}.",
|
|
361
|
+
"days": {
|
|
362
|
+
"one": "завтра",
|
|
363
|
+
"few": "за {count} дні",
|
|
364
|
+
"many": "за {count} днів",
|
|
365
|
+
"other": "за {count} дня"
|
|
366
|
+
}
|
|
367
|
+
}
|
|
333
368
|
},
|
|
334
369
|
"dragon": {
|
|
335
370
|
"stages": {
|
|
@@ -591,7 +626,7 @@
|
|
|
591
626
|
"weekends": "вихідні",
|
|
592
627
|
"noWeekends": "без вихідних",
|
|
593
628
|
"daysOff": " · відпустка {ranges}",
|
|
594
|
-
"month": "
|
|
629
|
+
"month": "Дні з досягнутою ціллю: {goalDays}/{days} · правильних відповідей: {correct}",
|
|
595
630
|
"weekdays": "П В С Ч П С Н",
|
|
596
631
|
"badgesLine": "Значки: {unlocked}/{total} · /badges показує всі"
|
|
597
632
|
},
|
|
@@ -1114,5 +1149,26 @@
|
|
|
1114
1149
|
"example": "Тепер твоя черга: введи `/add` і створи власну колоду. Навчальний тур звільнить для неї місце."
|
|
1115
1150
|
}
|
|
1116
1151
|
]
|
|
1152
|
+
},
|
|
1153
|
+
"languages": {
|
|
1154
|
+
"notYet": "ще невідомо",
|
|
1155
|
+
"mixed": "інша або змішана",
|
|
1156
|
+
"mixedNote": "без правил однієї мови",
|
|
1157
|
+
"current": "поточна",
|
|
1158
|
+
"guessed": "визначено за картками",
|
|
1159
|
+
"frontQuestion": "Якою мовою написано лицьовий бік карток у колоді «{deck}»?",
|
|
1160
|
+
"backQuestion": "Якою мовою написано зворот карток у колоді «{deck}»?",
|
|
1161
|
+
"example": "напр. {sample}",
|
|
1162
|
+
"search": "пошук:",
|
|
1163
|
+
"noMatch": "Жодна мова не відповідає «{query}».",
|
|
1164
|
+
"saved": "Мови колоди «{deck}»: {pair}.",
|
|
1165
|
+
"detecting": "Колода «{deck}» знову визначає мови за картками.",
|
|
1166
|
+
"learningQuestion": "Яку мову ти вчиш у колоді «{deck}»?",
|
|
1167
|
+
"learningNote": "Слова цією мовою читаються вголос, якщо вимову ввімкнено в /settings.",
|
|
1168
|
+
"learningSaved": "Мова навчання в колоді «{deck}»: {language}.",
|
|
1169
|
+
"guessShort": "здогадка",
|
|
1170
|
+
"learningArticles": "Пропущений або неправильний артикль у ній зараховується як «майже».",
|
|
1171
|
+
"savedWithLearning": "Мови колоди «{deck}»: {pair}, мова навчання: {language}.",
|
|
1172
|
+
"learningUmlauts": "У німецькій так само пропущений умлаут."
|
|
1117
1173
|
}
|
|
1118
1174
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dracosh",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"description": "A gamified language or definitions trainer for your terminal. Your personal pixel dragon grows with your progress.",
|
|
5
5
|
"author": "Tomasz Przyborowski (https://github.com/lynthius)",
|
|
6
6
|
"license": "Apache-2.0",
|
package/src/alerts.js
CHANGED
|
@@ -1,15 +1,54 @@
|
|
|
1
1
|
import { t } from "./i18n.js";
|
|
2
2
|
import { execFile } from "node:child_process";
|
|
3
3
|
import path from "node:path";
|
|
4
|
+
import { tmpdir } from "node:os";
|
|
5
|
+
import { rm } from "node:fs/promises";
|
|
4
6
|
import { fileURLToPath } from "node:url";
|
|
5
7
|
|
|
6
8
|
// 8-bit chiptune effects generated by scripts/make-sounds.js (see `npm run sounds`)
|
|
7
9
|
const SOUND_DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "assets", "sounds");
|
|
8
10
|
const LADDER_STEPS = 6; // correct-0 … correct-5: the pitch climbs with your combo
|
|
9
11
|
|
|
12
|
+
// Voices macOS has for a language (`say -v ?`), the novelty ones left out, the best first: a premium or
|
|
13
|
+
// enhanced voice, then a plain named one. Read once, when the first word is spoken.
|
|
14
|
+
const NOVELTY = new Set(["Albert", "Bad News", "Bahh", "Bells", "Boing", "Bubbles", "Cellos", "Good News", "Jester", "Organ", "Superstar", "Trinoids", "Whisper", "Wobble", "Zarvox", "Fred", "Junior", "Kathy", "Ralph", "Grandma", "Grandpa", "Rocko"]);
|
|
15
|
+
const MAX_SPOKEN = 200; // characters: a long definition isn't read out whole
|
|
16
|
+
const SPEECH_CODE = { no: "nb", nn: "nb" }; // macOS reads Norwegian as Bokmål
|
|
17
|
+
const SPEAK_AFTER_MS = 500; // after the answer's chime, not over it
|
|
18
|
+
let voices = null;
|
|
19
|
+
function voicesOnce() {
|
|
20
|
+
voices ??= new Promise((resolve) =>
|
|
21
|
+
execFile("say", ["-v", "?"], (err, out) =>
|
|
22
|
+
resolve(err ? [] : String(out).split("\n").map((line) => line.match(/^(.+?)\s+([a-z]{2,3})_([A-Za-z0-9]+)\s+#/)).filter(Boolean).map(([, name, lang, region]) => ({ name: name.trim(), lang, region })))
|
|
23
|
+
)
|
|
24
|
+
);
|
|
25
|
+
return voices;
|
|
26
|
+
}
|
|
27
|
+
// the region most learners mean (English from the US or Britain, not India; Chinese from the mainland)
|
|
28
|
+
const REGIONS = { en: ["US", "GB"], zh: ["CN", "TW"], pt: ["PT", "BR"], es: ["ES", "MX"], fr: ["FR"], de: ["DE"], nl: ["NL"] };
|
|
29
|
+
const rank = (voice) => {
|
|
30
|
+
const regions = REGIONS[voice.lang] ?? [];
|
|
31
|
+
const region = regions.includes(voice.region) ? regions.indexOf(voice.region) : regions.length;
|
|
32
|
+
const quality = /\((Premium|Enhanced)\)/.test(voice.name) ? 0 : /\(/.test(voice.name) ? 2 : 1;
|
|
33
|
+
return region * 10 + quality;
|
|
34
|
+
};
|
|
35
|
+
export async function voiceFor(lang) {
|
|
36
|
+
const code = SPEECH_CODE[lang] ?? lang;
|
|
37
|
+
const found = (await voicesOnce()).filter((voice) => voice.lang === code && !NOVELTY.has(voice.name));
|
|
38
|
+
return found.sort((a, b) => rank(a) - rank(b))[0]?.name ?? null;
|
|
39
|
+
}
|
|
40
|
+
|
|
10
41
|
export function createAlerts(initial = {}) {
|
|
11
42
|
const enabled = process.platform === "darwin";
|
|
12
|
-
const config = { sound: true, volume: 0.5, ...initial };
|
|
43
|
+
const config = { sound: true, volume: 0.5, speak: false, ...initial };
|
|
44
|
+
// one word at a time: a newer one (or switching pronunciation off) cancels the one waiting or playing
|
|
45
|
+
let waiting = null;
|
|
46
|
+
let speaking = null;
|
|
47
|
+
const hush = () => {
|
|
48
|
+
clearTimeout(waiting);
|
|
49
|
+
speaking?.kill();
|
|
50
|
+
waiting = speaking = null;
|
|
51
|
+
};
|
|
13
52
|
|
|
14
53
|
const play = (name) => {
|
|
15
54
|
if (!config.sound || !enabled) return;
|
|
@@ -18,7 +57,10 @@ export function createAlerts(initial = {}) {
|
|
|
18
57
|
|
|
19
58
|
return {
|
|
20
59
|
play,
|
|
21
|
-
configure
|
|
60
|
+
configure(patch) {
|
|
61
|
+
Object.assign(config, patch);
|
|
62
|
+
if (!config.speak) hush();
|
|
63
|
+
},
|
|
22
64
|
// a new question while you're in another window: sound plus a Notification Center banner
|
|
23
65
|
ask() {
|
|
24
66
|
play("ask");
|
|
@@ -28,12 +70,35 @@ export function createAlerts(initial = {}) {
|
|
|
28
70
|
// The biggest thing that just happened wins: evolution > goal > combo cheer > the answer itself.
|
|
29
71
|
// On a plain correct answer the pitch rises with the combo and resets on a miss. Badges ring
|
|
30
72
|
// on their own, each as its line lights up (see BadgeUnlock).
|
|
73
|
+
// a word read aloud in its language (/settings → Pronunciation); nothing when macOS has no voice for it
|
|
74
|
+
// Rendered to a file and played with afplay, so it follows the volume like the sounds do (say's own
|
|
75
|
+
// volume command is ignored by today's voices).
|
|
76
|
+
async speak(text, lang) {
|
|
77
|
+
hush();
|
|
78
|
+
if (!config.speak || !enabled || !text || !lang) return;
|
|
79
|
+
const voice = await voiceFor(lang);
|
|
80
|
+
if (!voice) return;
|
|
81
|
+
hush(); // another word may have come meanwhile
|
|
82
|
+
const words = text.replace(/\[\[|\]\]|[{}\\]/g, "").slice(0, MAX_SPOKEN); // [[…]] would be a command; cloze braces aren't words
|
|
83
|
+
const file = path.join(tmpdir(), `dracosh-${process.pid}-${Date.now()}.aiff`);
|
|
84
|
+
waiting = setTimeout(() => {
|
|
85
|
+
waiting = null;
|
|
86
|
+
if (!config.speak) return;
|
|
87
|
+
const render = (speaking = execFile("say", ["-v", voice, "-o", file, "--", words], (err) => {
|
|
88
|
+
if (err || speaking !== render) return void rm(file, { force: true }).catch(() => {});
|
|
89
|
+
const voiceOut = (speaking = execFile("afplay", ["-v", String(config.volume), file], () => rm(file, { force: true }).catch(() => {})));
|
|
90
|
+
voiceOut.unref();
|
|
91
|
+
}));
|
|
92
|
+
render.unref();
|
|
93
|
+
}, SPEAK_AFTER_MS);
|
|
94
|
+
waiting.unref(); // quitting right after an answer doesn't wait for the word
|
|
95
|
+
},
|
|
31
96
|
result(result, { cheers = [], combo = 0 } = {}) {
|
|
32
97
|
if (result === "wrong") return play("wrong");
|
|
33
98
|
for (const kind of ["evolve", "goal", "combo"]) {
|
|
34
99
|
if (cheers.includes(kind)) return play(kind);
|
|
35
100
|
}
|
|
36
|
-
if (result === "typo") return play("close");
|
|
101
|
+
if (result === "typo" || result === "article" || result === "umlaut" || result === "article-umlaut") return play("close");
|
|
37
102
|
play(`correct-${Math.min(Math.max(combo - 1, 0), LADDER_STEPS - 1)}`);
|
|
38
103
|
}
|
|
39
104
|
};
|
package/src/cli.js
CHANGED
|
@@ -140,7 +140,7 @@ async function main() {
|
|
|
140
140
|
|
|
141
141
|
if (values.preview) {
|
|
142
142
|
if (!process.stdin.isTTY) throw new Error(t("cli.needsTerminal"));
|
|
143
|
-
const alerts = createAlerts({ sound: settings.sound, volume: settings.volume });
|
|
143
|
+
const alerts = createAlerts({ sound: settings.sound, volume: settings.volume, speak: settings.speak });
|
|
144
144
|
return render(React.createElement(Preview, { alerts })).waitUntilExit();
|
|
145
145
|
}
|
|
146
146
|
|
|
@@ -163,7 +163,7 @@ async function main() {
|
|
|
163
163
|
let current = settings; // the session reads settings live, so /settings changes apply immediately
|
|
164
164
|
let active = deck.name; // /add can switch to your first own deck
|
|
165
165
|
const session = createSession({ loadWords: () => loadWords(active), loadAllWords, state, getSettings: () => current });
|
|
166
|
-
const alerts = createAlerts({ sound: settings.sound, volume: settings.volume });
|
|
166
|
+
const alerts = createAlerts({ sound: settings.sound, volume: settings.volume, speak: settings.speak });
|
|
167
167
|
const persistSettings = async (patch) => {
|
|
168
168
|
current = { ...current, ...patch };
|
|
169
169
|
await patchSettings(patch);
|
package/src/diff.js
CHANGED
|
@@ -7,7 +7,8 @@ const foldChar = (ch) => fold(ch.toLowerCase());
|
|
|
7
7
|
// → [{ ch, ok }] for every character of `given`: ok = this character lines up with `target`.
|
|
8
8
|
// Alignment comes from a Levenshtein backtrace, so a single missing or extra letter doesn't
|
|
9
9
|
// mark the whole rest of the word wrong.
|
|
10
|
-
|
|
10
|
+
// `gaps`: also a { ch: "_", missing: true } where letters of `target` were left out ("tomor_ow")
|
|
11
|
+
export function diffChars(given, target, { gaps = false } = {}) {
|
|
11
12
|
const a = [...given].map(foldChar);
|
|
12
13
|
const b = [...target].map(foldChar);
|
|
13
14
|
const rows = a.length + 1;
|
|
@@ -24,6 +25,7 @@ export function diffChars(given, target) {
|
|
|
24
25
|
|
|
25
26
|
// walk back, preferring matches; deletions in `target` don't produce a character of `given`
|
|
26
27
|
const marks = new Array(a.length).fill(false);
|
|
28
|
+
const missedBefore = new Array(a.length + 1).fill(false);
|
|
27
29
|
let i = a.length;
|
|
28
30
|
let j = b.length;
|
|
29
31
|
while (i > 0 || j > 0) {
|
|
@@ -35,17 +37,19 @@ export function diffChars(given, target) {
|
|
|
35
37
|
marks[i - 1] = false; // extra character you typed
|
|
36
38
|
i -= 1;
|
|
37
39
|
} else {
|
|
38
|
-
|
|
40
|
+
missedBefore[i] = true; // character you missed: nothing of yours to mark, a gap at most
|
|
41
|
+
j -= 1;
|
|
39
42
|
}
|
|
40
43
|
}
|
|
41
|
-
|
|
44
|
+
const parts = [...given].flatMap((ch, k) => [...(gaps && missedBefore[k] ? [{ ch: "_", ok: false, missing: true }] : []), { ch, ok: marks[k] }]);
|
|
45
|
+
return gaps && missedBefore[a.length] ? [...parts, { ch: "_", ok: false, missing: true }] : parts;
|
|
42
46
|
}
|
|
43
47
|
|
|
44
48
|
// → [{ ch, ok }] for every character of `target`, after an answer right but for its accents ("jablko"
|
|
45
49
|
// for "jabłko"): ok = you wrote this very letter, so only ł is marked. null when the two don't line
|
|
46
50
|
// up letter for letter ("strasse" for "straße").
|
|
47
51
|
export function accentMarks(given, target) {
|
|
48
|
-
const mine = [...given.trim().normalize("
|
|
52
|
+
const mine = [...given.trim().normalize("NFKC").toLowerCase()]; // "neko" typed full-width is "neko"
|
|
49
53
|
const letters = [...target.normalize("NFC")];
|
|
50
54
|
if (mine.length !== letters.length) return null;
|
|
51
55
|
return letters.map((ch, i) => ({ ch, ok: ch.toLowerCase() === mine[i] }));
|
package/src/judge.js
CHANGED
|
@@ -1,9 +1,12 @@
|
|
|
1
|
+
import { GENDERED_LANGUAGES } from "./language.js";
|
|
1
2
|
// Typos are forgiven only on longer answers: on short words one edit often makes a different word
|
|
2
3
|
const TYPO_MIN_LENGTH = 6;
|
|
3
4
|
|
|
4
5
|
// Sentence punctuation that never changes what an answer means ("Hello, world!" = "hello world").
|
|
5
6
|
// Everything else stays: "3.14" isn't "31.4", "-5" isn't "5", "C#" isn't "C", and 🐉 is an answer too.
|
|
6
|
-
const LOOSE = /[;!?¡¿"“”„«»()[\]'
|
|
7
|
+
const LOOSE = /[;!?¡¿"“”„«»()[\]'’ʼʹ`「」『』【】・]/g; // ʼ: the Ukrainian apostrophe (сімʼя)
|
|
8
|
+
// full-width letters and signs, as a Japanese or Chinese keyboard types them: "neko" is "neko"
|
|
9
|
+
const halfWidth = (s) => s.replace(/[\uff01-\uff5e]/g, (ch) => String.fromCharCode(ch.charCodeAt(0) - 0xfee0)).replace(/\u3000/g, " ");
|
|
7
10
|
|
|
8
11
|
// lowercase, loose punctuation dropped, a trailing full stop dropped, hyphens between letters as spaces.
|
|
9
12
|
// Commas and colons count between digits only: "3,14" is "3.14" (a decimal comma), "10:30" stays.
|
|
@@ -11,6 +14,9 @@ function plain(s) {
|
|
|
11
14
|
const text = s
|
|
12
15
|
.normalize("NFC") // "café" typed or pasted with a separate accent mark is the same word
|
|
13
16
|
.toLowerCase()
|
|
17
|
+
.replace(/[\uff01-\uff5e\u3000]/g, halfWidth)
|
|
18
|
+
.replace(/。/g, ".") // the CJK full stop and comma read like ours
|
|
19
|
+
.replace(/、/g, ",")
|
|
14
20
|
.replace(/(?<=\d),(?=\d)/g, ".")
|
|
15
21
|
.replace(/,/g, " ")
|
|
16
22
|
.replace(/(?<!\d):|:(?!\d)/g, "")
|
|
@@ -62,12 +68,13 @@ export function editDistance(a, b) {
|
|
|
62
68
|
return d[rows - 1][cols - 1];
|
|
63
69
|
}
|
|
64
70
|
|
|
65
|
-
// The candidate the answer came closest to (fewest edits after normalizing): what a miss is diffed against
|
|
66
|
-
|
|
71
|
+
// The candidate the answer came closest to (fewest edits after normalizing): what a miss is diffed against.
|
|
72
|
+
// In German "Maedchn" is diffed against "Maedchen", so the spelled-out ä isn't taken for the mistake.
|
|
73
|
+
export function closestCandidate(answer, candidates, { lang = null } = {}) {
|
|
67
74
|
const given = normalize(answer);
|
|
68
75
|
let best = candidates[0];
|
|
69
76
|
let bestDistance = Infinity;
|
|
70
|
-
for (const candidate of candidates) {
|
|
77
|
+
for (const candidate of candidates.flatMap((c) => [c, spelledOut(c, lang)])) {
|
|
71
78
|
const distance = editDistance(given, normalize(candidate));
|
|
72
79
|
if (distance < bestDistance) {
|
|
73
80
|
bestDistance = distance;
|
|
@@ -77,16 +84,142 @@ export function closestCandidate(answer, candidates) {
|
|
|
77
84
|
return best;
|
|
78
85
|
}
|
|
79
86
|
|
|
80
|
-
//
|
|
87
|
+
// The way a language writes its own letters without them: German "Baer" for "Bär", Danish "aa" for "å".
|
|
88
|
+
// Only for answers in that language: in Finnish or Swedish "ae" isn't "ä".
|
|
89
|
+
const NORWEGIAN = { æ: "ae", ø: "oe", å: "aa" };
|
|
90
|
+
const SPELLED_OUT = { de: { ä: "ae", ö: "oe", ü: "ue" }, da: NORWEGIAN, no: NORWEGIAN, nb: NORWEGIAN, nn: NORWEGIAN };
|
|
91
|
+
const spelledOut = (candidate, lang) => {
|
|
92
|
+
const letters = SPELLED_OUT[lang];
|
|
93
|
+
return letters ? candidate.normalize("NFC").replace(/[äöüæøåÄÖÜÆØÅ]/g, (ch) => {
|
|
94
|
+
const out = letters[ch.toLowerCase()];
|
|
95
|
+
return !out ? ch : ch === ch.toLowerCase() ? out : out[0].toUpperCase() + out.slice(1);
|
|
96
|
+
}) : candidate;
|
|
97
|
+
};
|
|
98
|
+
// the candidate's forms after folding: as written, and spelled out
|
|
99
|
+
const spellings = (candidate, lang) => [...new Set([normalize(candidate), normalize(spelledOut(candidate, lang))])];
|
|
100
|
+
|
|
101
|
+
// Does the answer write the candidate with each such letter kept, spelled out or left plain, as it comes:
|
|
102
|
+
// "Gruesse aus Köln" and "Baer und Madchen" both write "Grüße aus Köln", "Bär und Mädchen". → "spelled"
|
|
103
|
+
// (every such letter kept or spelled out), "plain" (some left as a plain a, o, u…) or false.
|
|
104
|
+
function spelledAnyWay(answer, candidate, lang) {
|
|
105
|
+
const letters = SPELLED_OUT[lang];
|
|
106
|
+
if (!letters) return false;
|
|
107
|
+
// letter by letter, keeping every place the answer could have got to and whether a letter was left
|
|
108
|
+
// plain on the way there: no regex, so a long run of å can't make it slow
|
|
109
|
+
const given = plain(cyrillicLookalikes(answer));
|
|
110
|
+
let at = new Map([[0, false]]);
|
|
111
|
+
for (const ch of plain(candidate)) {
|
|
112
|
+
const ways = letters[ch] ? [[ch, false], [letters[ch], false], [fold(ch), true]] : [[ch, false], [fold(ch), false]];
|
|
113
|
+
const next = new Map();
|
|
114
|
+
for (const [from, leftPlain] of at)
|
|
115
|
+
for (const [way, plainHere] of ways) if (given.startsWith(way, from)) next.set(from + way.length, (next.get(from + way.length) ?? true) && (leftPlain || plainHere));
|
|
116
|
+
if (!next.size) return false;
|
|
117
|
+
at = next;
|
|
118
|
+
}
|
|
119
|
+
return at.has(given.length) ? (at.get(given.length) ? "plain" : "spelled") : false;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// German umlauts and articles are what a learner has to get right: an answer without them still counts,
|
|
123
|
+
// but as "almost" (the card doesn't move up)
|
|
124
|
+
const NO_GENDER = new Set(["to", "att", "at", "å"]); // infinitive markers
|
|
125
|
+
// elided or plural articles that don't show the gender, per language
|
|
126
|
+
const NO_GENDER_SHOWN = { fr: new Set(["l'", "les", "des", "de l'"]), it: new Set(["l'"]), ca: new Set(["l'"]) };
|
|
127
|
+
const GENDERED = new Set(GENDERED_LANGUAGES);
|
|
128
|
+
|
|
129
|
+
// Articles (and the infinitive's "to", "att", "å") in front of a word. An answer in that language may
|
|
130
|
+
// leave them out or add them, and still counts: "cat" for "the cat", "Hund" for "der Hund". A
|
|
131
|
+
// different one counts too, but shows as close, not quite right: "die Hund" for "der Hund".
|
|
132
|
+
const ARTICLES = {
|
|
133
|
+
en: ["the", "a", "an", "to"],
|
|
134
|
+
de: ["der", "die", "das", "den", "dem", "des", "ein", "eine", "einen", "einem", "einer", "eines"],
|
|
135
|
+
fr: ["le", "la", "les", "un", "une", "des", "du", "de la", "de l'", "l'"],
|
|
136
|
+
es: ["el", "la", "los", "las", "un", "una", "unos", "unas"],
|
|
137
|
+
it: ["il", "lo", "la", "i", "gli", "le", "un", "uno", "una", "l'", "un'"],
|
|
138
|
+
pt: ["o", "a", "os", "as", "um", "uma", "uns", "umas"],
|
|
139
|
+
ca: ["el", "la", "els", "les", "un", "una", "l'"],
|
|
140
|
+
nl: ["de", "het", "een", "'t"],
|
|
141
|
+
sv: ["en", "ett", "att"],
|
|
142
|
+
da: ["en", "et", "at"],
|
|
143
|
+
no: ["en", "ei", "et", "å"]
|
|
144
|
+
};
|
|
145
|
+
ARTICLES.nb = ARTICLES.nn = ARTICLES.no;
|
|
146
|
+
// "the cat" → { article: "the", word: "cat" }; an answer that is only an article stays itself
|
|
147
|
+
function splitArticle(text, lang) {
|
|
148
|
+
const lower = text.normalize("NFC").toLowerCase().trim().replace(/’/g, "'");
|
|
149
|
+
for (const article of [...(ARTICLES[lang] ?? [])].sort((a, b) => b.length - a.length)) {
|
|
150
|
+
const glued = article.endsWith("'");
|
|
151
|
+
if (lower.startsWith(glued ? article : `${article} `)) {
|
|
152
|
+
const word = lower.slice(article.length).trim();
|
|
153
|
+
if (word && !ARTICLES[lang].includes(word)) return { article, word }; // "the the" isn't "the"
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
return { article: "", word: lower };
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// A Cyrillic answer with a Latin letter that looks the same ("вiкно" typed on a keyboard without і):
|
|
160
|
+
// the letters are read as the Cyrillic ones they look like
|
|
161
|
+
const LOOKALIKES = { a: "а", c: "с", e: "е", i: "і", o: "о", p: "р", x: "х", y: "у" };
|
|
162
|
+
const cyrillicLookalikes = (answer) =>
|
|
163
|
+
answer.replace(/\S+/g, (word) => (/\p{Script=Cyrillic}/u.test(word) ? word.replace(/[aceiopxy]/gi, (ch) => LOOKALIKES[ch.toLowerCase()]) : word)); // "Excel" next to "файл" stays Latin
|
|
164
|
+
|
|
165
|
+
// Chinese, Japanese and Korean: one character is a whole word, so nothing is folded or forgiven. A
|
|
166
|
+
// reading in brackets is an answer too: "猫 (ねこ)" takes 猫, ねこ or both.
|
|
167
|
+
const ONE_CHARACTER_WORDS = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u;
|
|
168
|
+
const exactly = (s) => plain(s.normalize("NFKC")).replace(/\s/g, ""); // full-width "ABC" is "abc"; spaces don't count
|
|
169
|
+
const readings = (candidate) => {
|
|
170
|
+
const bracket = candidate.normalize("NFKC").match(/^(.+?)\s*\((.+)\)\s*$/);
|
|
171
|
+
if (!bracket) return [candidate];
|
|
172
|
+
// a reading in kana or hangul counts on its own; a note in brackets ("猫 (animal)") doesn't
|
|
173
|
+
return ONE_CHARACTER_WORDS.test(bracket[2]) ? [candidate, bracket[1], bracket[2]] : [candidate, bracket[1]];
|
|
174
|
+
};
|
|
175
|
+
|
|
176
|
+
// → "exact" | "accent" | "article" | "umlaut" | "typo" | "wrong"; accepts any one of the candidate answers. Missing or wrong
|
|
81
177
|
// diacritics ("zolw" for "żółw") are "accent": right, quietly (not everyone has the letters on their
|
|
82
|
-
// keyboard), with the missing letters marked in the verdict.
|
|
83
|
-
//
|
|
84
|
-
|
|
178
|
+
// keyboard), with the missing letters marked in the verdict. `lang` is the answer's language, when the
|
|
179
|
+
// deck's languages are known: it adds that language's own spellings ("Baer" for "Bär"), and lets an
|
|
180
|
+
// article be left out ("cat" for "the cat": "accent"). Where the article carries the gender, one left
|
|
181
|
+
// out or swapped ("Hund", "die Hund" for "der Hund") is "article", and a German umlaut left plain
|
|
182
|
+
// ("Bar" for "Bär") is "umlaut": right, but not quite, so the card stays where it was. One more typo
|
|
183
|
+
// is forgiven on longer answers, but never in numbers: "123457" isn't "123456".
|
|
184
|
+
// `otherLang`: the other side's language (a card may be written the other way round); `learning`: the
|
|
185
|
+
// language you're learning in this deck (null: none), the only one where "almost" applies; not given,
|
|
186
|
+
// the answer's own language
|
|
187
|
+
export const ALMOST = ["article", "umlaut", "article-umlaut"];
|
|
188
|
+
export function judge(answer, candidates, { lang = null, otherLang = null, learning = lang } = {}) {
|
|
85
189
|
if (!answer.trim()) return "wrong";
|
|
86
|
-
const given = normalize(answer);
|
|
87
190
|
if (candidates.some((c) => plain(c) === plain(answer))) return "exact";
|
|
88
|
-
|
|
191
|
+
// each candidate on its own: a card with "猫" and "cat" still forgives a typo in "cat"
|
|
192
|
+
const words = candidates.filter((c) => ONE_CHARACTER_WORDS.test(c));
|
|
193
|
+
if (words.some((c) => readings(c).some((one) => exactly(one) === exactly(answer)))) return "exact";
|
|
194
|
+
candidates = candidates.filter((c) => !ONE_CHARACTER_WORDS.test(c));
|
|
195
|
+
if (!candidates.length) return "wrong";
|
|
196
|
+
const given = normalize(cyrillicLookalikes(answer));
|
|
197
|
+
const targets = candidates.flatMap((c) => spellings(c, lang));
|
|
198
|
+
const ways = candidates.map((c) => spelledAnyWay(answer, c, lang));
|
|
199
|
+
if (ways.includes("spelled")) return "accent";
|
|
200
|
+
if (ways.includes("plain")) return lang === "de" && learning === "de" ? "umlaut" : "accent";
|
|
89
201
|
if (targets.includes(given)) return "accent";
|
|
202
|
+
// the answer's language first, then the other side's, for a card written the other way round
|
|
203
|
+
// (only when the answer's own language has articles too, and for an article of two letters or more:
|
|
204
|
+
// Italian "i" in Polish "i tak" is no article)
|
|
205
|
+
for (const one of [...new Set([lang, ARTICLES[lang] ? otherLang : null])].filter((l) => ARTICLES[l])) {
|
|
206
|
+
const mine = splitArticle(answer, one);
|
|
207
|
+
const other = one !== lang;
|
|
208
|
+
const same = candidates
|
|
209
|
+
.map((c) => splitArticle(c, one))
|
|
210
|
+
.filter((c) => (!other || c.article.length >= 2) && spellings(c.word, one).includes(normalize(mine.word)));
|
|
211
|
+
if (!same.length) continue;
|
|
212
|
+
// Strict only in the language you're learning (your own you know), and only where the article
|
|
213
|
+
// shows the gender: an article added, English "the", an infinitive's "to", an elided "l'" or a
|
|
214
|
+
// plural "les" is as good as none
|
|
215
|
+
const strict = GENDERED.has(one) && one === learning;
|
|
216
|
+
const genderless = (c) => !strict || !c.article || c.article === mine.article || NO_GENDER.has(c.article) || NO_GENDER.has(mine.article) || Boolean(NO_GENDER_SHOWN[one]?.has(c.article));
|
|
217
|
+
const fine = same.filter(genderless);
|
|
218
|
+
// a German word still needs its umlauts after an added article ("die Bar" for "Bär")
|
|
219
|
+
const plainUmlaut = (list) => one === "de" && strict && list.every((c) => spelledAnyWay(mine.word, c.word, one) === "plain");
|
|
220
|
+
if (fine.length) return plainUmlaut(fine) ? "umlaut" : "accent";
|
|
221
|
+
return plainUmlaut(same) ? "article-umlaut" : "article";
|
|
222
|
+
}
|
|
90
223
|
// "email" for "e-mail", "icecream" for "ice cream": right, but shown with the spelling
|
|
91
224
|
const compact = (s) => s.replace(/\s/g, ""); // hyphens between letters are spaces by now
|
|
92
225
|
if (targets.some((t) => compact(t) === compact(given))) return "typo";
|