dracosh 0.3.0 → 0.5.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 +84 -15
- package/locales/de.json +291 -12
- package/locales/en.json +291 -12
- package/locales/fr.json +315 -12
- package/locales/pl.json +339 -12
- package/locales/uk.json +339 -12
- package/package.json +2 -2
- package/src/alerts.js +68 -3
- package/src/ankiconnect.js +106 -0
- package/src/apkg.js +472 -0
- package/src/backup.js +12 -1
- package/src/cardline.js +11 -3
- package/src/cardlist.js +381 -0
- package/src/cli.js +13 -2
- package/src/diff.js +8 -4
- package/src/entities.js +40 -0
- package/src/exporter.js +71 -0
- package/src/importer.js +222 -0
- package/src/judge.js +147 -10
- package/src/language.js +361 -0
- package/src/library.js +50 -15
- 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/sqlite.js +28 -0
- package/src/store.js +13 -7
- package/src/transfer.js +557 -0
- package/src/ui/AddCard.js +64 -27
- package/src/ui/AnswerInput.js +3 -3
- 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/src/zip.js +157 -0
package/src/importer.js
ADDED
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
import { t } from "./i18n.js";
|
|
2
|
+
import { gapsOf } from "./cardline.js";
|
|
3
|
+
import { readCardList } from "./cardlist.js";
|
|
4
|
+
import { frontKey } from "./judge.js";
|
|
5
|
+
import { addCard, cardsOf, createDeck, findDeck, frontIndex, MAX_DECK_NAME, removeDeck, typedSides, updateCard } from "./library.js";
|
|
6
|
+
|
|
7
|
+
// Importing a list of cards: reading the file, a plan of what it would change (shown before anything is
|
|
8
|
+
// saved), then that plan carried out. Pure apart from decodeText's input; the CLI does the asking.
|
|
9
|
+
|
|
10
|
+
// A file's text, read the way it was saved: UTF-8 (with or without a BOM), or UTF-16 (Excel's "Unicode
|
|
11
|
+
// text"). Anything else isn't guessed: → throws with the start of the file read as the usual legacy
|
|
12
|
+
// encodings, so the right --encoding can be picked.
|
|
13
|
+
export function decodeText(bytes, encoding = null) {
|
|
14
|
+
const buffer = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
|
|
15
|
+
if (encoding) {
|
|
16
|
+
let decoder;
|
|
17
|
+
try {
|
|
18
|
+
decoder = new TextDecoder(encoding);
|
|
19
|
+
} catch {
|
|
20
|
+
throw new Error(t("import.unknownEncoding", { encoding }));
|
|
21
|
+
}
|
|
22
|
+
return { text: decoder.decode(buffer), encoding: decoder.encoding };
|
|
23
|
+
}
|
|
24
|
+
const starts = (...prefix) => prefix.every((byte, i) => buffer[i] === byte);
|
|
25
|
+
if (starts(0xff, 0xfe)) return { text: new TextDecoder("utf-16le").decode(buffer), encoding: "utf-16le" };
|
|
26
|
+
if (starts(0xfe, 0xff)) return { text: new TextDecoder("utf-16be").decode(buffer), encoding: "utf-16be" };
|
|
27
|
+
// UTF-16 without a BOM: every other byte is zero in text that's mostly Latin
|
|
28
|
+
const sample = buffer.subarray(0, 4000);
|
|
29
|
+
const zeros = (offset) => sample.filter((byte, i) => i % 2 === offset && byte === 0).length;
|
|
30
|
+
if (sample.length >= 4 && zeros(1) > sample.length * 0.3) return { text: new TextDecoder("utf-16le").decode(buffer), encoding: "utf-16le" };
|
|
31
|
+
if (sample.length >= 4 && zeros(0) > sample.length * 0.3) return { text: new TextDecoder("utf-16be").decode(buffer), encoding: "utf-16be" };
|
|
32
|
+
try {
|
|
33
|
+
return { text: new TextDecoder("utf-8", { fatal: true }).decode(buffer), encoding: "utf-8" };
|
|
34
|
+
} catch {
|
|
35
|
+
const line = (label) => new TextDecoder(label).decode(buffer).split(/\r?\n/).find((l) => /[^\x00-\x7f]/.test(l)) ?? "";
|
|
36
|
+
const samples = ["windows-1250", "windows-1252"].map((label) => ({ encoding: label, line: line(label).slice(0, 60) }));
|
|
37
|
+
throw Object.assign(new Error(t("import.notUtf8")), { samples });
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// the same answers, maybe in another order: a fixed accent or letter case is a change
|
|
42
|
+
const answersKey = (back) => back.map((answer) => answer.trim()).sort().join("\u0001");
|
|
43
|
+
|
|
44
|
+
// → { decks: [{ name, deck (existing or null), direction, items }], problems, read: { format, separator,
|
|
45
|
+
// columns, ignored, count } }, each item one of:
|
|
46
|
+
// { kind: "new", line, fields } added
|
|
47
|
+
// { kind: "same", line, fields, card } already in the deck as it is: left alone
|
|
48
|
+
// { kind: "changed", line, fields, card } in the deck with other answers or example: asked about
|
|
49
|
+
// problems: [{ line, issue, text, first? }]: issue is noFront, noBack, noSeparator (a Dracosh line
|
|
50
|
+
// without " = "), slash (an answer to type starts with "/"), twice (first: the line it was on before),
|
|
51
|
+
// noDeck, tooLong (a deck name), tour (a deck name taken by the tour), picture (an Anki note that
|
|
52
|
+
// is a picture, from a package).
|
|
53
|
+
// `deck`: every card goes into this deck (--deck); `deckName`: the deck for cards the file doesn't put
|
|
54
|
+
// in one (what was asked). `directions`: { deck name: direction } picked for new decks.
|
|
55
|
+
// `split`: in a table, one answer listing several ("cat, kitty", "cat / kitty") becomes several;
|
|
56
|
+
// read.splittable says how many there are, with an example. `list`: the cards already read (an Anki
|
|
57
|
+
// package, by apkg.js), instead of `text`.
|
|
58
|
+
export function planImport(library, text, { deck: only = null, deckName = null, separator = null, csv = false, directions = {}, split = false, list: given = null } = {}) {
|
|
59
|
+
const list = given ?? readCardList(text, { separator, csv });
|
|
60
|
+
const decks = new Map();
|
|
61
|
+
const problems = [];
|
|
62
|
+
const seen = new Map(); // deck name + front → the line it was first on
|
|
63
|
+
const fronts = new Map(); // deck id → its frontIndex
|
|
64
|
+
const splittable = [];
|
|
65
|
+
|
|
66
|
+
for (const { line, text: source } of list.unknown) problems.push({ line, issue: "badDirection", text: source });
|
|
67
|
+
const fittedFrom = new Map(); // a shortened deck name → the long one it came from
|
|
68
|
+
for (const item of list.items) {
|
|
69
|
+
const full = (only ?? item.deck ?? deckName ?? "").trim();
|
|
70
|
+
const name = fitName(full);
|
|
71
|
+
let { fields } = item;
|
|
72
|
+
const problem = (issue, extra = {}) => problems.push({ line: item.line, issue, text: item.source, ...extra });
|
|
73
|
+
if (item.skip) {
|
|
74
|
+
problem(item.skip);
|
|
75
|
+
continue;
|
|
76
|
+
}
|
|
77
|
+
if (!fields.front) {
|
|
78
|
+
problem("noFront");
|
|
79
|
+
continue;
|
|
80
|
+
}
|
|
81
|
+
if (!fields.cloze && !fields.back.length) {
|
|
82
|
+
problem(list.format === "lines" && !item.source.includes("=") ? "noSeparator" : "noBack");
|
|
83
|
+
continue;
|
|
84
|
+
}
|
|
85
|
+
// a phrase ("Hello, world") is translated by a phrase, not a list
|
|
86
|
+
const listed = (list.format === "table" || list.format === "apkg") && !fields.cloze && fields.back.length === 1 && !fields.front.includes(",") && listedAnswers(fields.back[0]);
|
|
87
|
+
if (listed) {
|
|
88
|
+
splittable.push(fields.back[0]);
|
|
89
|
+
if (split) fields = { ...fields, back: listed };
|
|
90
|
+
}
|
|
91
|
+
if (!name) {
|
|
92
|
+
problem("noDeck");
|
|
93
|
+
continue;
|
|
94
|
+
}
|
|
95
|
+
// two long names that shorten to the same one stay apart: the second one is named instead
|
|
96
|
+
const before = fittedFrom.get(name.toLowerCase()) ?? full;
|
|
97
|
+
fittedFrom.set(name.toLowerCase(), before);
|
|
98
|
+
if (Array.from(name).length > MAX_DECK_NAME || before !== full) {
|
|
99
|
+
problem("tooLong", { deck: full });
|
|
100
|
+
continue;
|
|
101
|
+
}
|
|
102
|
+
const key = `${name.toLowerCase()}\u0001${frontKey(fields.front)}`;
|
|
103
|
+
if (seen.has(key)) {
|
|
104
|
+
problem("twice", { first: seen.get(key) });
|
|
105
|
+
continue;
|
|
106
|
+
}
|
|
107
|
+
seen.set(key, item.line);
|
|
108
|
+
|
|
109
|
+
if (!decks.has(name.toLowerCase())) {
|
|
110
|
+
const deck = findDeck(library, name);
|
|
111
|
+
decks.set(name.toLowerCase(), { name: deck?.name ?? name, deck, direction: deck ? deck.directions : item.direction, items: [] });
|
|
112
|
+
}
|
|
113
|
+
const target = decks.get(name.toLowerCase());
|
|
114
|
+
if (target.deck?.tour) {
|
|
115
|
+
problem("tour", { deck: target.deck.name });
|
|
116
|
+
continue;
|
|
117
|
+
}
|
|
118
|
+
if (target.deck && !fronts.has(target.deck.id)) fronts.set(target.deck.id, frontIndex(library, target.deck.id));
|
|
119
|
+
const existing = target.deck ? (fronts.get(target.deck.id).get(frontKey(fields.front)) ?? null) : null;
|
|
120
|
+
const direction = target.deck?.directions ?? directions[target.name] ?? target.direction ?? "forward";
|
|
121
|
+
if (slashIn(fields, direction)) {
|
|
122
|
+
problem("slash");
|
|
123
|
+
continue;
|
|
124
|
+
}
|
|
125
|
+
if (!existing) target.items.push({ kind: "new", line: item.line, fields });
|
|
126
|
+
else {
|
|
127
|
+
// the same answers in another order, or an example left out of the file, change nothing
|
|
128
|
+
const sameBack = answersKey(existing.back) === answersKey(fields.back);
|
|
129
|
+
const sameExample = !fields.example || fields.example === existing.example;
|
|
130
|
+
const sameGaps = !(fields.cloze || existing.cloze) || fields.front === existing.front;
|
|
131
|
+
target.items.push({ kind: sameBack && sameExample && sameGaps ? "same" : "changed", line: item.line, fields, card: existing });
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
return {
|
|
135
|
+
decks: [...decks.values()].filter((deck) => deck.items.length),
|
|
136
|
+
problems,
|
|
137
|
+
read: { anki: list.anki, html: list.html, media: list.media ?? 0, format: list.format, separator: list.separator, columns: list.columns, ignored: list.ignored, count: list.items.length, splittable: splittable.length, splitExample: splittable[0] ?? null }
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
// Anki's nested decks ("Languages::Spanish::Verbs for travel") are long: one that doesn't fit keeps its
|
|
142
|
+
// last part, the deck the cards are really in
|
|
143
|
+
const fitName = (name) => {
|
|
144
|
+
if (Array.from(name).length <= MAX_DECK_NAME || !name.includes("::")) return name;
|
|
145
|
+
// as many of the last parts as fit: "Languages::Spanish for my trip::Verbs" → "Spanish for my trip::Verbs"
|
|
146
|
+
const parts = name.split("::").map((part) => part.trim());
|
|
147
|
+
let fitted = parts.at(-1);
|
|
148
|
+
for (let i = parts.length - 2; i >= 0 && Array.from(`${parts[i]}::${fitted}`).length <= MAX_DECK_NAME; i--) fitted = `${parts[i]}::${fitted}`;
|
|
149
|
+
return fitted;
|
|
150
|
+
};
|
|
151
|
+
|
|
152
|
+
// "cat, kitty" or "cat / kitty": answers listed the way Anki and Quizlet decks often do → ["cat", "kitty"];
|
|
153
|
+
// null for a sentence ("Yes, I do.") or a single answer
|
|
154
|
+
function listedAnswers(answer) {
|
|
155
|
+
if (/[.?!…]$/.test(answer.trim())) return null;
|
|
156
|
+
const parts = answer.split(/\s*,\s+|\s+\/\s+/).map((part) => part.trim()).filter(Boolean);
|
|
157
|
+
return parts.length > 1 && parts.every((part) => part.split(/\s+/).length <= 3) ? parts : null;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
// in the quiz "/" opens the commands, so nothing to be typed may start with it
|
|
161
|
+
const slashIn = (fields, directions) => {
|
|
162
|
+
const slash = (text) => text.startsWith("/");
|
|
163
|
+
if (fields.cloze) return gapsOf(fields.front).some(slash);
|
|
164
|
+
return typedSides({ directions }).some((side) => [fields[side]].flat().some(slash));
|
|
165
|
+
};
|
|
166
|
+
|
|
167
|
+
// Carries out a plan. `update`: changed cards take the file's answers and example (their progress
|
|
168
|
+
// stays): true for all of them, or a Set of the card ids that were shown and agreed to; otherwise
|
|
169
|
+
// they're left as they are. `directions`: { deck name: direction } for new decks
|
|
170
|
+
// (forward when not given). → { added, updated, slash: [{ line, text }] (left out: an answer to type
|
|
171
|
+
// starts with "/"), decks: [{ name, isNew, added, updated }], removedTour: the tour's card ids (it goes
|
|
172
|
+
// once you have a deck of your own, as in /add; `keepTour` keeps it) }
|
|
173
|
+
// A card already in a deck that the import found among Anki's own notes is marked as from Anki too
|
|
174
|
+
// (as a new one is), so `export --anki` never sends Anki a second copy of it. → how many were marked
|
|
175
|
+
export function markFromAnki(library, plan) {
|
|
176
|
+
let marked = 0;
|
|
177
|
+
for (const item of plan.decks.flatMap((deck) => deck.items)) {
|
|
178
|
+
const card = item.card && item.fields.fromAnki && library.cards.find((each) => each.id === item.card.id);
|
|
179
|
+
if (card && !card.fromAnki) [card.fromAnki, marked] = [true, marked + 1];
|
|
180
|
+
}
|
|
181
|
+
return marked;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
export function applyImport(library, plan, { update = false, directions = {}, keepTour = false, now = Date.now() } = {}) {
|
|
185
|
+
const result = { added: 0, updated: 0, slash: [], decks: [], removedTour: [] };
|
|
186
|
+
markFromAnki(library, plan);
|
|
187
|
+
for (const target of plan.decks) {
|
|
188
|
+
let deck = target.deck && library.decks.find((d) => d.id === target.deck.id);
|
|
189
|
+
const isNew = !deck;
|
|
190
|
+
if (isNew) deck = createDeck(library, { name: target.name, directions: directions[target.name] ?? target.direction ?? "forward", now });
|
|
191
|
+
const counts = { name: deck.name, isNew, added: 0, updated: 0 };
|
|
192
|
+
const index = frontIndex(library, deck.id);
|
|
193
|
+
for (const item of target.items) {
|
|
194
|
+
const updating = item.kind === "changed" && (update === true || update?.has?.(item.card.id));
|
|
195
|
+
if ((item.kind === "new" || updating) && slashIn(item.fields, deck.directions)) {
|
|
196
|
+
result.slash.push({ line: item.line, text: item.fields.front });
|
|
197
|
+
continue;
|
|
198
|
+
}
|
|
199
|
+
if (item.kind === "new") {
|
|
200
|
+
addCard(library, deck.id, { ...item.fields, now }, index);
|
|
201
|
+
counts.added++;
|
|
202
|
+
} else if (updating) {
|
|
203
|
+
updateCard(library, item.card.id, { front: item.fields.front, back: item.fields.back, cloze: item.fields.cloze, ...(item.fields.example && { example: item.fields.example }) }, now);
|
|
204
|
+
counts.updated++;
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
result.added += counts.added;
|
|
208
|
+
result.updated += counts.updated;
|
|
209
|
+
result.decks.push(counts);
|
|
210
|
+
}
|
|
211
|
+
// your first deck of your own replaces the tour, as in /add
|
|
212
|
+
const tour = library.decks.find((d) => d.tour);
|
|
213
|
+
if (tour && !keepTour && library.decks.some((d) => !d.tour && cardsOf(library, d.id).length)) result.removedTour = removeDeck(library, tour.id);
|
|
214
|
+
return result;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
// the items of a plan that would be asked about, saved, or left: for the preview
|
|
218
|
+
export const planCounts = (plan) => {
|
|
219
|
+
const items = plan.decks.flatMap((deck) => deck.items);
|
|
220
|
+
const count = (kind) => items.filter((item) => item.kind === kind).length;
|
|
221
|
+
return { new: count("new"), same: count("same"), changed: count("changed"), problems: plan.problems.length };
|
|
222
|
+
};
|
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, "")
|
|
@@ -39,6 +45,10 @@ export function fold(s) {
|
|
|
39
45
|
.replace(/[\ue000-\ue002]/g, (ch) => OWN_BACK[ch]);
|
|
40
46
|
}
|
|
41
47
|
|
|
48
|
+
// One card's front, as duplicates are found: letter case and punctuation don't count, accents do
|
|
49
|
+
// ("el" and "él", "kat" and "kąt" are different words)
|
|
50
|
+
export const frontKey = (s) => plain(String(s ?? ""));
|
|
51
|
+
|
|
42
52
|
// plain(), and diacritics folded too
|
|
43
53
|
export function normalize(s) {
|
|
44
54
|
return fold(plain(s));
|
|
@@ -62,12 +72,13 @@ export function editDistance(a, b) {
|
|
|
62
72
|
return d[rows - 1][cols - 1];
|
|
63
73
|
}
|
|
64
74
|
|
|
65
|
-
// The candidate the answer came closest to (fewest edits after normalizing): what a miss is diffed against
|
|
66
|
-
|
|
75
|
+
// The candidate the answer came closest to (fewest edits after normalizing): what a miss is diffed against.
|
|
76
|
+
// In German "Maedchn" is diffed against "Maedchen", so the spelled-out ä isn't taken for the mistake.
|
|
77
|
+
export function closestCandidate(answer, candidates, { lang = null } = {}) {
|
|
67
78
|
const given = normalize(answer);
|
|
68
79
|
let best = candidates[0];
|
|
69
80
|
let bestDistance = Infinity;
|
|
70
|
-
for (const candidate of candidates) {
|
|
81
|
+
for (const candidate of candidates.flatMap((c) => [c, spelledOut(c, lang)])) {
|
|
71
82
|
const distance = editDistance(given, normalize(candidate));
|
|
72
83
|
if (distance < bestDistance) {
|
|
73
84
|
bestDistance = distance;
|
|
@@ -77,16 +88,142 @@ export function closestCandidate(answer, candidates) {
|
|
|
77
88
|
return best;
|
|
78
89
|
}
|
|
79
90
|
|
|
80
|
-
//
|
|
91
|
+
// The way a language writes its own letters without them: German "Baer" for "Bär", Danish "aa" for "å".
|
|
92
|
+
// Only for answers in that language: in Finnish or Swedish "ae" isn't "ä".
|
|
93
|
+
const NORWEGIAN = { æ: "ae", ø: "oe", å: "aa" };
|
|
94
|
+
const SPELLED_OUT = { de: { ä: "ae", ö: "oe", ü: "ue" }, da: NORWEGIAN, no: NORWEGIAN, nb: NORWEGIAN, nn: NORWEGIAN };
|
|
95
|
+
const spelledOut = (candidate, lang) => {
|
|
96
|
+
const letters = SPELLED_OUT[lang];
|
|
97
|
+
return letters ? candidate.normalize("NFC").replace(/[äöüæøåÄÖÜÆØÅ]/g, (ch) => {
|
|
98
|
+
const out = letters[ch.toLowerCase()];
|
|
99
|
+
return !out ? ch : ch === ch.toLowerCase() ? out : out[0].toUpperCase() + out.slice(1);
|
|
100
|
+
}) : candidate;
|
|
101
|
+
};
|
|
102
|
+
// the candidate's forms after folding: as written, and spelled out
|
|
103
|
+
const spellings = (candidate, lang) => [...new Set([normalize(candidate), normalize(spelledOut(candidate, lang))])];
|
|
104
|
+
|
|
105
|
+
// Does the answer write the candidate with each such letter kept, spelled out or left plain, as it comes:
|
|
106
|
+
// "Gruesse aus Köln" and "Baer und Madchen" both write "Grüße aus Köln", "Bär und Mädchen". → "spelled"
|
|
107
|
+
// (every such letter kept or spelled out), "plain" (some left as a plain a, o, u…) or false.
|
|
108
|
+
function spelledAnyWay(answer, candidate, lang) {
|
|
109
|
+
const letters = SPELLED_OUT[lang];
|
|
110
|
+
if (!letters) return false;
|
|
111
|
+
// letter by letter, keeping every place the answer could have got to and whether a letter was left
|
|
112
|
+
// plain on the way there: no regex, so a long run of å can't make it slow
|
|
113
|
+
const given = plain(cyrillicLookalikes(answer));
|
|
114
|
+
let at = new Map([[0, false]]);
|
|
115
|
+
for (const ch of plain(candidate)) {
|
|
116
|
+
const ways = letters[ch] ? [[ch, false], [letters[ch], false], [fold(ch), true]] : [[ch, false], [fold(ch), false]];
|
|
117
|
+
const next = new Map();
|
|
118
|
+
for (const [from, leftPlain] of at)
|
|
119
|
+
for (const [way, plainHere] of ways) if (given.startsWith(way, from)) next.set(from + way.length, (next.get(from + way.length) ?? true) && (leftPlain || plainHere));
|
|
120
|
+
if (!next.size) return false;
|
|
121
|
+
at = next;
|
|
122
|
+
}
|
|
123
|
+
return at.has(given.length) ? (at.get(given.length) ? "plain" : "spelled") : false;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// German umlauts and articles are what a learner has to get right: an answer without them still counts,
|
|
127
|
+
// but as "almost" (the card doesn't move up)
|
|
128
|
+
const NO_GENDER = new Set(["to", "att", "at", "å"]); // infinitive markers
|
|
129
|
+
// elided or plural articles that don't show the gender, per language
|
|
130
|
+
const NO_GENDER_SHOWN = { fr: new Set(["l'", "les", "des", "de l'"]), it: new Set(["l'"]), ca: new Set(["l'"]) };
|
|
131
|
+
const GENDERED = new Set(GENDERED_LANGUAGES);
|
|
132
|
+
|
|
133
|
+
// Articles (and the infinitive's "to", "att", "å") in front of a word. An answer in that language may
|
|
134
|
+
// leave them out or add them, and still counts: "cat" for "the cat", "Hund" for "der Hund". A
|
|
135
|
+
// different one counts too, but shows as close, not quite right: "die Hund" for "der Hund".
|
|
136
|
+
const ARTICLES = {
|
|
137
|
+
en: ["the", "a", "an", "to"],
|
|
138
|
+
de: ["der", "die", "das", "den", "dem", "des", "ein", "eine", "einen", "einem", "einer", "eines"],
|
|
139
|
+
fr: ["le", "la", "les", "un", "une", "des", "du", "de la", "de l'", "l'"],
|
|
140
|
+
es: ["el", "la", "los", "las", "un", "una", "unos", "unas"],
|
|
141
|
+
it: ["il", "lo", "la", "i", "gli", "le", "un", "uno", "una", "l'", "un'"],
|
|
142
|
+
pt: ["o", "a", "os", "as", "um", "uma", "uns", "umas"],
|
|
143
|
+
ca: ["el", "la", "els", "les", "un", "una", "l'"],
|
|
144
|
+
nl: ["de", "het", "een", "'t"],
|
|
145
|
+
sv: ["en", "ett", "att"],
|
|
146
|
+
da: ["en", "et", "at"],
|
|
147
|
+
no: ["en", "ei", "et", "å"]
|
|
148
|
+
};
|
|
149
|
+
ARTICLES.nb = ARTICLES.nn = ARTICLES.no;
|
|
150
|
+
// "the cat" → { article: "the", word: "cat" }; an answer that is only an article stays itself
|
|
151
|
+
function splitArticle(text, lang) {
|
|
152
|
+
const lower = text.normalize("NFC").toLowerCase().trim().replace(/’/g, "'");
|
|
153
|
+
for (const article of [...(ARTICLES[lang] ?? [])].sort((a, b) => b.length - a.length)) {
|
|
154
|
+
const glued = article.endsWith("'");
|
|
155
|
+
if (lower.startsWith(glued ? article : `${article} `)) {
|
|
156
|
+
const word = lower.slice(article.length).trim();
|
|
157
|
+
if (word && !ARTICLES[lang].includes(word)) return { article, word }; // "the the" isn't "the"
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
return { article: "", word: lower };
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
// A Cyrillic answer with a Latin letter that looks the same ("вiкно" typed on a keyboard without і):
|
|
164
|
+
// the letters are read as the Cyrillic ones they look like
|
|
165
|
+
const LOOKALIKES = { a: "а", c: "с", e: "е", i: "і", o: "о", p: "р", x: "х", y: "у" };
|
|
166
|
+
const cyrillicLookalikes = (answer) =>
|
|
167
|
+
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
|
|
168
|
+
|
|
169
|
+
// Chinese, Japanese and Korean: one character is a whole word, so nothing is folded or forgiven. A
|
|
170
|
+
// reading in brackets is an answer too: "猫 (ねこ)" takes 猫, ねこ or both.
|
|
171
|
+
const ONE_CHARACTER_WORDS = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u;
|
|
172
|
+
const exactly = (s) => plain(s.normalize("NFKC")).replace(/\s/g, ""); // full-width "ABC" is "abc"; spaces don't count
|
|
173
|
+
const readings = (candidate) => {
|
|
174
|
+
const bracket = candidate.normalize("NFKC").match(/^(.+?)\s*\((.+)\)\s*$/);
|
|
175
|
+
if (!bracket) return [candidate];
|
|
176
|
+
// a reading in kana or hangul counts on its own; a note in brackets ("猫 (animal)") doesn't
|
|
177
|
+
return ONE_CHARACTER_WORDS.test(bracket[2]) ? [candidate, bracket[1], bracket[2]] : [candidate, bracket[1]];
|
|
178
|
+
};
|
|
179
|
+
|
|
180
|
+
// → "exact" | "accent" | "article" | "umlaut" | "typo" | "wrong"; accepts any one of the candidate answers. Missing or wrong
|
|
81
181
|
// 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
|
-
|
|
182
|
+
// keyboard), with the missing letters marked in the verdict. `lang` is the answer's language, when the
|
|
183
|
+
// deck's languages are known: it adds that language's own spellings ("Baer" for "Bär"), and lets an
|
|
184
|
+
// article be left out ("cat" for "the cat": "accent"). Where the article carries the gender, one left
|
|
185
|
+
// out or swapped ("Hund", "die Hund" for "der Hund") is "article", and a German umlaut left plain
|
|
186
|
+
// ("Bar" for "Bär") is "umlaut": right, but not quite, so the card stays where it was. One more typo
|
|
187
|
+
// is forgiven on longer answers, but never in numbers: "123457" isn't "123456".
|
|
188
|
+
// `otherLang`: the other side's language (a card may be written the other way round); `learning`: the
|
|
189
|
+
// language you're learning in this deck (null: none), the only one where "almost" applies; not given,
|
|
190
|
+
// the answer's own language
|
|
191
|
+
export const ALMOST = ["article", "umlaut", "article-umlaut"];
|
|
192
|
+
export function judge(answer, candidates, { lang = null, otherLang = null, learning = lang } = {}) {
|
|
85
193
|
if (!answer.trim()) return "wrong";
|
|
86
|
-
const given = normalize(answer);
|
|
87
194
|
if (candidates.some((c) => plain(c) === plain(answer))) return "exact";
|
|
88
|
-
|
|
195
|
+
// each candidate on its own: a card with "猫" and "cat" still forgives a typo in "cat"
|
|
196
|
+
const words = candidates.filter((c) => ONE_CHARACTER_WORDS.test(c));
|
|
197
|
+
if (words.some((c) => readings(c).some((one) => exactly(one) === exactly(answer)))) return "exact";
|
|
198
|
+
candidates = candidates.filter((c) => !ONE_CHARACTER_WORDS.test(c));
|
|
199
|
+
if (!candidates.length) return "wrong";
|
|
200
|
+
const given = normalize(cyrillicLookalikes(answer));
|
|
201
|
+
const targets = candidates.flatMap((c) => spellings(c, lang));
|
|
202
|
+
const ways = candidates.map((c) => spelledAnyWay(answer, c, lang));
|
|
203
|
+
if (ways.includes("spelled")) return "accent";
|
|
204
|
+
if (ways.includes("plain")) return lang === "de" && learning === "de" ? "umlaut" : "accent";
|
|
89
205
|
if (targets.includes(given)) return "accent";
|
|
206
|
+
// the answer's language first, then the other side's, for a card written the other way round
|
|
207
|
+
// (only when the answer's own language has articles too, and for an article of two letters or more:
|
|
208
|
+
// Italian "i" in Polish "i tak" is no article)
|
|
209
|
+
for (const one of [...new Set([lang, ARTICLES[lang] ? otherLang : null])].filter((l) => ARTICLES[l])) {
|
|
210
|
+
const mine = splitArticle(answer, one);
|
|
211
|
+
const other = one !== lang;
|
|
212
|
+
const same = candidates
|
|
213
|
+
.map((c) => splitArticle(c, one))
|
|
214
|
+
.filter((c) => (!other || c.article.length >= 2) && spellings(c.word, one).includes(normalize(mine.word)));
|
|
215
|
+
if (!same.length) continue;
|
|
216
|
+
// Strict only in the language you're learning (your own you know), and only where the article
|
|
217
|
+
// shows the gender: an article added, English "the", an infinitive's "to", an elided "l'" or a
|
|
218
|
+
// plural "les" is as good as none
|
|
219
|
+
const strict = GENDERED.has(one) && one === learning;
|
|
220
|
+
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));
|
|
221
|
+
const fine = same.filter(genderless);
|
|
222
|
+
// a German word still needs its umlauts after an added article ("die Bar" for "Bär")
|
|
223
|
+
const plainUmlaut = (list) => one === "de" && strict && list.every((c) => spelledAnyWay(mine.word, c.word, one) === "plain");
|
|
224
|
+
if (fine.length) return plainUmlaut(fine) ? "umlaut" : "accent";
|
|
225
|
+
return plainUmlaut(same) ? "article-umlaut" : "article";
|
|
226
|
+
}
|
|
90
227
|
// "email" for "e-mail", "icecream" for "ice cream": right, but shown with the spelling
|
|
91
228
|
const compact = (s) => s.replace(/\s/g, ""); // hyphens between letters are spaces by now
|
|
92
229
|
if (targets.some((t) => compact(t) === compact(given))) return "typo";
|