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.
@@ -0,0 +1,361 @@
1
+ // A deck's languages: what its front and back are written in (ISO 639-1 codes). Guessed from the
2
+ // cards until you set them in /decks; a side that can't be told stays unknown and gets the general
3
+ // answer checking. "und" (undetermined) is a side you said isn't any one language.
4
+
5
+ import { language, LANGUAGES as UI_LANGUAGES } from "./i18n.js";
6
+
7
+ export const UNKNOWN = "und";
8
+ // languages whose articles show the gender: where "almost" checks them
9
+ export const GENDERED_LANGUAGES = ["de", "fr", "es", "it", "pt", "ca", "nl", "sv", "da", "no", "nb", "nn"];
10
+ export const isKnown = (code) => Boolean(code) && code !== UNKNOWN;
11
+
12
+ // the languages offered in /decks, most learned first; any other ISO 639-1 code still works if typed
13
+ export const DECK_LANGUAGES = [
14
+ "en", "es", "de", "fr", "it", "pt", "pl", "nl", "sv", "da", "no", "fi", "cs", "sk", "hu", "ro", "hr", "sl", "sr",
15
+ "bg", "uk", "ru", "be", "el", "tr", "lt", "lv", "et", "is", "ga", "ca", "eu", "la", "eo", "ja", "zh", "ko", "ar",
16
+ "he", "fa", "hi", "th", "vi", "id", "ka", "hy"
17
+ ];
18
+
19
+ // "es" → "Spanish" (in the UI's language: "hiszpański"; languageName("es", "es") is "español"); an
20
+ // unknown side → null
21
+ const namers = new Map(); // one Intl.DisplayNames per UI language: making one is slow
22
+ export function languageName(code, ui = language()) {
23
+ if (!code || code === UNKNOWN) return null;
24
+ try {
25
+ if (!namers.has(ui)) namers.set(ui, new Intl.DisplayNames([ui], { type: "language" }));
26
+ return namers.get(ui).of(code) ?? code;
27
+ } catch {
28
+ return code;
29
+ }
30
+ }
31
+
32
+ // Scripts that tell the language (nearly) on their own. Han alone could be Chinese or Japanese
33
+ // (Japanese writes many words in kanji only): it takes kana to say Japanese, and characters only
34
+ // simplified Chinese uses to say Chinese.
35
+ const SCRIPTS = [
36
+ ["ko", /\p{Script=Hangul}/u],
37
+ ["ja", /[\p{Script=Hiragana}\p{Script=Katakana}]/u],
38
+ ["zh", /\p{Script=Han}/u],
39
+ ["el", /\p{Script=Greek}/u],
40
+ ["he", /\p{Script=Hebrew}/u],
41
+ ["ar", /\p{Script=Arabic}/u],
42
+ ["hi", /\p{Script=Devanagari}/u],
43
+ ["th", /\p{Script=Thai}/u],
44
+ ["ka", /\p{Script=Georgian}/u],
45
+ ["hy", /\p{Script=Armenian}/u]
46
+ ];
47
+ const SIMPLIFIED = /[们这说对时么车东见语长书爱电话马鸟鱼风飞龙门问间关开头买卖钱银红绿蓝网谢请习颜脑饭汤鸡]/u;
48
+ const PERSIAN = /[پچژگ]/u;
49
+ const URDU = /[ٹڈڑںےھہ]/u;
50
+
51
+ // Letters that point to a language: [language, letters, weight]. Strong ones (3 and up) are (nearly)
52
+ // only used there; weak ones are shared by a few languages and only tip the balance.
53
+ const STRONG = 3;
54
+ const LETTERS = [
55
+ ["pl", "ąęłśźżń", 3], ["pl", "ćó", 1],
56
+ ["de", "ß", 4], ["de", "äöü", 1],
57
+ ["fr", "œùûÿ", 3], ["fr", "çèêëîïôàâé", 1],
58
+ ["es", "ñ¿¡", 4], ["es", "áíóúé", 1],
59
+ ["pt", "ãõ", 4], ["pt", "çâêôáéíóú", 1],
60
+ ["it", "ìò", 3], ["it", "àèéù", 1],
61
+ ["cs", "řěů", 4], ["cs", "čšžýáíéú", 1],
62
+ ["sk", "ľĺŕ", 4], ["sk", "ô", 2], ["sk", "äčšžýáíéú", 1],
63
+ ["hu", "őű", 4], ["hu", "áéíóöúü", 1],
64
+ ["ro", "ășțşţ", 4], ["ro", "âî", 1],
65
+ ["tr", "ğış", 4], ["tr", "çöü", 1],
66
+ ["sv", "å", 2], ["sv", "äö", 1],
67
+ ["da", "æø", 2], ["da", "å", 1],
68
+ ["no", "æø", 2], ["no", "å", 1],
69
+ ["fi", "äö", 1],
70
+ ["hr", "đ", 3], ["hr", "čćšž", 1],
71
+ ["sl", "čšž", 1],
72
+ ["lt", "ėįų", 4], ["lt", "ąčęšūž", 1],
73
+ ["lv", "āēīūģķļņ", 4], ["lv", "čšž", 1],
74
+ ["et", "õ", 2], ["et", "äöü", 1],
75
+ ["is", "þð", 4], ["is", "æáéíóúý", 1],
76
+ ["ca", "·", 4], ["ca", "çàèòéíóú", 1],
77
+ ["vi", "ơưạảấầẩẫậắằẳẵặẹẻẽếềểễệỉịọỏốồổỗộớờởỡợụủứừửữựỳỵỷỹđ", 3],
78
+ // Cyrillic: plain Cyrillic words are left unguessed, only letters a language owns count
79
+ ["uk", "їєґ", 4], ["uk", "і", 2],
80
+ ["be", "ў", 4], ["be", "і", 1],
81
+ ["ru", "ыэё", 3],
82
+ ["bg", "ъ", 3],
83
+ ["sr", "јљњћђџ", 4],
84
+ ["mk", "ѓќѕ", 4]
85
+ ];
86
+
87
+ // Short words every sentence has: a few matches tell languages that share their letters apart
88
+ const WORDS = {
89
+ en: "the a an and of in is are you i it this that with for not my your be have do what",
90
+ de: "der die das und ist nicht ein eine ich du sie es mit zu den dem auf für wir",
91
+ fr: "le la les et est un une des je tu il elle pas de du que qui avec pour nous vous",
92
+ es: "el la los las lo y es un una que de no yo tú en con por para está son muy",
93
+ it: "il lo la gli e è un una di che non io tu con per sono mi ti",
94
+ pt: "o a os as e é um uma de que não eu você em com por para do da são",
95
+ nl: "de het een en is niet ik jij je van met op dat zijn wat",
96
+ pl: "i w się nie jest na że z do co jak ja ty mi być",
97
+ sv: "och är en ett att det jag du inte på med som för",
98
+ da: "og er en et at det jeg du ikke på med som for",
99
+ no: "og er en ei et å det jeg du ikke på med som for eg ikkje ein",
100
+ fi: "ja on se minä sinä että mutta kanssa olla",
101
+ cs: "a je se v na že s jsem není ten",
102
+ sk: "a je sa v na že som nie aj ako sú",
103
+ hr: "je i u na da se ne sam su što kako",
104
+ ro: "și este un o de în nu eu cu pe la să ce mai",
105
+ tr: "ve bir bu ne ben sen için ile değil var",
106
+ ru: "и в не на что это я ты он она с как",
107
+ uk: "і в не на що це я ти він вона з як та але й",
108
+ bg: "и в не на е съм се да за от ще аз ти",
109
+ be: "і ў не на што гэта я ты ён яна з як"
110
+ };
111
+ // a word shared by several languages ("la", "de") counts for each of them a little
112
+ const WORD_LANGS = new Map();
113
+ for (const [lang, list] of Object.entries(WORDS)) for (const word of list.split(" ")) WORD_LANGS.set(word, [...(WORD_LANGS.get(word) ?? []), lang]);
114
+ const WORD_POINTS = 3;
115
+
116
+ // Spellings typical of a language, in words of plain letters ("the", "szkoła", "Schule")
117
+ const SPELLINGS = [
118
+ ["en", /th|wh|ght|ing$|ck$/],
119
+ ["de", /sch|tz|ung$/],
120
+ ["nl", /ij|aa|uu|oe/],
121
+ ["pl", /sz|cz|rz|ść/],
122
+ ["hu", /gy|zs/],
123
+ ["hr", /ije|lj|nj/],
124
+ ["it", /tt|zz|gli|cch|zion|zie/],
125
+ ["fr", /eau|eux|oi[rstx]/],
126
+ ["es", /ción/],
127
+ ["pt", /ção|nh|lh/],
128
+ ["fi", /ää|yy|yö|nen$|ss[aä]$/],
129
+ ["bg", /ът$|ят$/],
130
+ ["be", /дз/]
131
+ ];
132
+ // elisions: "l'" is French, Italian and Catalan; "qu'", "j'", "n'"… are French
133
+ const ELISION = /^(l|qu|j|n|s|c|m|t|d)['’]/;
134
+
135
+ const MIN_SCORE = 3;
136
+ const PLAIN_ENGLISH = 5; // cards
137
+ const MARGIN = 1.5; // the winner needs more than half again the runner-up's score
138
+ // English words rarely end in a, i, o or u; Polish, Czech, Italian, Spanish or Finnish written
139
+ // without accents often do. Nor do they have these letter pairs.
140
+ const NOT_ENGLISH = /sz|cz|rz|ij|gy|zs/;
141
+
142
+ // → { script, scores }: a script that names the language on its own, or each language's points
143
+ // with the texts that gave any (one stray word, like Polish "las", doesn't make a deck Spanish)
144
+ function scoresOf(texts) {
145
+ const all = texts.map((one) => String(one ?? "").normalize("NFC").toLowerCase());
146
+ const text = all.join(" ");
147
+ const letters = [...text].filter((ch) => /\p{L}/u.test(ch));
148
+ if (!letters.length) return { all, text, letters, scores: new Map() };
149
+ for (const [lang, pattern] of SCRIPTS) {
150
+ const share = letters.filter((ch) => pattern.test(ch)).length / letters.length;
151
+ if (share <= 0.3) continue;
152
+ if (lang === "zh") return { all, text, letters, script: SCRIPTS[1][1].test(text) ? "ja" : SIMPLIFIED.test(text) ? "zh" : null };
153
+ if (lang === "ar") return { all, text, letters, script: URDU.test(text) ? null : PERSIAN.test(text) ? "fa" : "ar" };
154
+ return { all, text, letters, script: lang };
155
+ }
156
+
157
+ const scores = new Map();
158
+ const add = (lang, points, from, strong = false) => {
159
+ const score = scores.get(lang) ?? { points: 0, texts: new Set(), hits: 0, strong: false };
160
+ score.points += points;
161
+ score.texts.add(from);
162
+ score.hits += 1;
163
+ score.strong ||= strong;
164
+ scores.set(lang, score);
165
+ };
166
+ all.forEach((one, from) => {
167
+ for (const ch of one) for (const [lang, set, weight] of LETTERS) if (set.includes(ch)) add(lang, weight, from, weight >= STRONG);
168
+ if (/^to \p{L}+$/u.test(one.trim())) add("en", 2, from); // "to go": an English verb (Polish "to dom" isn't one word)
169
+ for (const word of one.split(/[^\p{L}'’]+/u).filter(Boolean)) {
170
+ const bare = word.replace(ELISION, "");
171
+ const langs = WORD_LANGS.get(word) ?? WORD_LANGS.get(bare) ?? [];
172
+ for (const lang of langs) add(lang, WORD_POINTS / langs.length, from);
173
+ if (bare !== word) for (const lang of /^l['’]/.test(word) ? ["fr", "it", "ca"] : ["fr"]) add(lang, /^l['’]/.test(word) ? 0.5 : 1, from);
174
+ for (const [lang, pattern] of SPELLINGS) if (pattern.test(bare)) add(lang, 1, from);
175
+ }
176
+ });
177
+ // Russian has none of these letters, Belarusian has ы and э as well
178
+ if (/[іїєґўјљњћђџѓќѕ]/u.test(text)) scores.delete("ru");
179
+ return { all, text, letters, scores };
180
+ }
181
+
182
+ // → the language most of these texts are written in, or null when they don't say: better unknown
183
+ // than wrong (one plain word like "kot" could be many languages)
184
+ export function guessLanguage(texts) {
185
+ const { all, text, letters, script, scores } = scoresOf(texts);
186
+ if (script !== undefined) return script;
187
+ if (!letters.length) return null;
188
+
189
+ const ranked = [...scores].sort((a, b) => b[1].points - a[1].points);
190
+ const [best, second] = ranked;
191
+ if (!best || best[0] === "en") {
192
+ // plain a-z on many cards and nothing pointing elsewhere: English, by far the most learned language
193
+ const words = text.split(/[^a-z]+/).filter((word) => word.length >= 3);
194
+ const vowelEnds = words.filter((word) => /[aiou]$/.test(word)).length;
195
+ const plain = /^[a-z\s\p{P}\p{N}]+$/u.test(text) && !words.some((word) => NOT_ENGLISH.test(word));
196
+ if (plain && all.length >= PLAIN_ENGLISH && words.length >= PLAIN_ENGLISH && vowelEnds < words.length * 0.4) return "en";
197
+ }
198
+ if (!best || best[1].points < MIN_SCORE) return null;
199
+ // one card has to say it clearly: a letter only that language has, or two hints
200
+ if (all.length === 1 ? !best[1].strong && best[1].hits < 2 : best[1].texts.size < 2) return null;
201
+ if (second && best[1].points <= second[1].points * MARGIN) return null;
202
+ return best[0];
203
+ }
204
+
205
+ // how strongly these texts point to one language (0: not at all)
206
+ function pointsFor(texts, lang) {
207
+ const { script, scores } = scoresOf(texts);
208
+ if (script !== undefined) return script === lang ? 10 : 0;
209
+ return scores.get(lang)?.points ?? 0;
210
+ }
211
+
212
+ // the most points any language gets from these texts
213
+ function strongest(texts) {
214
+ const { script, scores } = scoresOf(texts);
215
+ if (script !== undefined) return script ? 10 : 0; // kanji alone: a script, but no one language yet
216
+ return Math.max(0, ...[...scores.values()].map((score) => score.points));
217
+ }
218
+
219
+ // The script a language is written in; Latin for the rest
220
+ const WRITTEN_IN = {
221
+ Cyrillic: ["ru", "uk", "be", "bg", "sr", "mk"], Greek: ["el"], Han: ["zh", "ja"], Hiragana: ["ja"], Katakana: ["ja"], Hangul: ["ko"],
222
+ Arabic: ["ar", "fa"], Hebrew: ["he"], Devanagari: ["hi"], Thai: ["th"], Georgian: ["ka"], Armenian: ["hy"]
223
+ };
224
+ const SCRIPT_TESTS = Object.keys(WRITTEN_IN).map((name) => [name, new RegExp(`\\p{Script=${name}}`, "u")]);
225
+ function scriptOf(texts) {
226
+ const letters = [...texts.join(" ")].filter((ch) => /\p{L}/u.test(ch));
227
+ const counts = new Map();
228
+ for (const ch of letters) {
229
+ const script = SCRIPT_TESTS.find(([, test]) => test.test(ch))?.[0] ?? (/\p{Script=Latin}/u.test(ch) ? "Latin" : null);
230
+ if (script) counts.set(script, (counts.get(script) ?? 0) + 1);
231
+ }
232
+ return [...counts].sort((a, b) => b[1] - a[1])[0]?.[0] ?? null;
233
+ }
234
+ // can these texts be in this language at all: Latin "kot" is never Ukrainian, Cyrillic never Polish
235
+ function writtenIn(lang, texts) {
236
+ const script = scriptOf(texts);
237
+ if (!script) return false;
238
+ const scripts = Object.entries(WRITTEN_IN).filter(([, langs]) => langs.includes(lang)).map(([name]) => name);
239
+ return script === "Latin" ? scripts.length === 0 || lang === "sr" : scripts.includes(script);
240
+ }
241
+
242
+ // other words people name a language deck with
243
+ const NAME_ALIASES = { mandarin: "zh", mandaryński: "zh", mandarynski: "zh", farsi: "fa", cantonese: "zh", flemish: "nl", bokmal: "no", nynorsk: "no" };
244
+
245
+ const fold = (text) => text.normalize("NFD").replace(/[\u0300-\u036f]/g, "").replace(/ł/g, "l").toLowerCase();
246
+
247
+ // The languages a deck is named after, in the order the name gives them: "Hiszpański" → ["es"],
248
+ // "Polish to German" → ["pl", "de"], "Español", "Німецька A1". Names are read in every language
249
+ // Dracosh speaks, whatever the UI's, and in the language itself.
250
+ export function languagesInName(name, ui = language()) {
251
+ const words = fold(String(name ?? "")).split(/[^\p{L}]+/u).filter(Boolean);
252
+ const found = [];
253
+ words.forEach((word, at) => {
254
+ for (const code of DECK_LANGUAGES) {
255
+ const names = [...new Set([ui, ...Object.keys(UI_LANGUAGES), code])].map((name) => languageName(code, name));
256
+ if ((names.some((one) => one && fold(one) === word) || NAME_ALIASES[word] === code) && !found.some((f) => f.code === code)) found.push({ code, at });
257
+ }
258
+ });
259
+ return found.sort((a, b) => a.at - b.at).map((f) => f.code);
260
+ }
261
+ export const languageInName = (name, ui = language()) => languagesInName(name, ui)[0] ?? null;
262
+
263
+ const SAMPLE_CARDS = 200; // enough to tell, and cheap to read before every question
264
+ const SAMPLE_LENGTH = 300; // characters of each side of a card: long answers say no more
265
+
266
+ // What a person's own language seems to be, from outside the deck → [{ code, sure }], likeliest first: the
267
+ // one most of their other language decks share (sure), then Dracosh's language and the system's, which
268
+ // are only hints (plenty of people run both in English and speak something else)
269
+ export function homeLanguages({ others = [], ui = language(), system = systemLocale() } = {}) {
270
+ const counts = new Map();
271
+ for (const pair of others) for (const code of new Set([pair.front, pair.back].filter(isKnown))) counts.set(code, (counts.get(code) ?? 0) + 1);
272
+ const shared = [...counts].filter(([, n]) => n >= 2 && n > others.length / 2).sort((a, b) => b[1] - a[1]).map(([code]) => code);
273
+ const hints = [ui, system].filter((code) => code && !shared.includes(code));
274
+ return [...shared.map((code) => ({ code, sure: true })), ...[...new Set(hints)].map((code) => ({ code, sure: false }))];
275
+ }
276
+ const systemLocale = () => {
277
+ const set = [process.env.LC_ALL, process.env.LC_MESSAGES, process.env.LANG].find((v) => v && !/^(C|POSIX)\b/i.test(v));
278
+ return (set ?? Intl.DateTimeFormat().resolvedOptions().locale).slice(0, 2).toLowerCase();
279
+ };
280
+
281
+ // The language you're learning in a deck → { side: "front" | "back", lang, sure }, or null for a deck
282
+ // that isn't for a language (one language on both sides, like definitions, or none known). Your own
283
+ // choice (deck.learning, a language code) wins; else, in turn: the language the deck is named after
284
+ // ("Chiński", "Polish to German": the second); the side that isn't your own language (homeLanguages);
285
+ // a lone known side that isn't yours; and last the back, as cards usually go "word you know = new
286
+ // word", though that's only a guess (`sure: false`), so the app asks. Pronunciation reads that
287
+ // language and "almost" applies to it.
288
+ export function learningSide(languages, deck, home = homeLanguages()) {
289
+ const { front, back } = languages ?? {};
290
+ const known = [front, back].filter(isKnown);
291
+ if (!known.length || front === back) return null;
292
+ const pick = (side, sure = true) => ({ side, lang: side === "front" ? front : back, sure });
293
+ if (deck?.learning && deck.learning === front) return pick("front");
294
+ if (deck?.learning && deck.learning === back) return pick("back");
295
+ const mine = home.map((h) => (typeof h === "string" ? { code: h, sure: true } : h)); // (a plain code is sure)
296
+ if (known.length === 2) {
297
+ const named = languagesInName(deck?.name).filter((code) => code === front || code === back);
298
+ if (named.length) return pick(named.at(-1) === front ? "front" : "back"); // "X to Y": Y
299
+ const own = mine.find((h) => h.code === front || h.code === back);
300
+ if (own) return pick(own.code === front ? "back" : "front", own.sure);
301
+ return pick("back", false);
302
+ }
303
+ // one side known (the other couldn't be told yet): learn it, unless it's yours; a guess either way
304
+ const own = mine.find((h) => h.code === known[0]);
305
+ return own?.sure ? null : own ? null : pick(isKnown(front) ? "front" : "back", false);
306
+ }
307
+
308
+ // → { front, back, guessed }: the languages you set, else the ones the cards suggest. A side the cards
309
+ // don't tell may come from the deck's name ("Hiszpański", "Polish to German") or, when its cards
310
+ // show a sign of it, from the language you use Dracosh in. A guess has to fit the side's script, and
311
+ // when nothing points either way the side stays unknown: better unknown than wrong. A cloze card's
312
+ // front is a sentence in the front language; its back is only a hint, so it isn't guessed from.
313
+ export function deckLanguages(deck, cards = [], ui = language()) {
314
+ if (deck?.languages) return { front: deck.languages.front, back: deck.languages.back, guessed: false };
315
+ try {
316
+ return guessDeck(deck, cards, ui);
317
+ } catch {
318
+ return { front: UNKNOWN, back: UNKNOWN, guessed: true }; // a guess is never worth a crash
319
+ }
320
+ }
321
+
322
+ function guessDeck(deck, cards, ui) {
323
+ const some = cards.slice(0, SAMPLE_CARDS);
324
+ const text = (value) => String(value ?? "").slice(0, SAMPLE_LENGTH);
325
+ const fronts = some.map((card) => text(card.front).replace(/\{\{|\}\}/g, ""));
326
+ const backs = some.filter((card) => !card.cloze).flatMap((card) => (Array.isArray(card.back) ? card.back : [card.back]).map(text));
327
+ const sides = { front: fronts, back: backs };
328
+ const found = { front: fronts.length ? guessLanguage(fronts) : null, back: backs.length ? guessLanguage(backs) : null };
329
+
330
+ // a language the side's cards could be in: the right script, and nothing pointing elsewhere
331
+ const fits = (lang, side) => sides[side].length > 0 && writtenIn(lang, sides[side]) && pointsFor(sides[side], lang) >= strongest(sides[side]) - 1;
332
+ const named = languagesInName(deck?.name, ui);
333
+ const open = (side) => !found[side];
334
+ const other = (side) => (side === "front" ? "back" : "front");
335
+
336
+ if (named.length >= 2 && open("front") && open("back")) {
337
+ const [a, b] = named;
338
+ const asIs = pointsFor(fronts, a) + pointsFor(backs, b);
339
+ const turned = pointsFor(fronts, b) + pointsFor(backs, a);
340
+ const [front, back] = turned > asIs ? [b, a] : [a, b];
341
+ if (fits(front, "front") && fits(back, "back")) Object.assign(found, { front, back });
342
+ }
343
+ // twice round: a side filled in on the way may be what the other one needed ("English" with a Polish back)
344
+ for (const side of ["front", "back", "front"]) {
345
+ if (!open(side)) continue;
346
+ const taken = found[other(side)];
347
+ // the deck's language goes where the cards lean to it, or opposite a side known to be another one
348
+ // (with two in the name, the one the other side isn't)
349
+ const byName = named.find((lang) => lang !== taken && fits(lang, side) && (pointsFor(sides[side], lang) > 0 || (taken && (!named.includes(taken) || named.length >= 2))));
350
+ if (byName) found[side] = byName;
351
+ // your own language, where the cards show some sign of it
352
+ else if (ui !== taken && fits(ui, side) && pointsFor(sides[side], ui) > 0) found[side] = ui;
353
+ }
354
+ // both sides read as one language, while the name says another: the name wins on the side it fits
355
+ // ("Spanish verbs": "hablar", "comer" look like plain English letters, but the deck says Spanish)
356
+ if (found.front && found.front === found.back) {
357
+ const side = ["front", "back"].find((side) => named.some((lang) => lang !== found[side] && fits(lang, side)));
358
+ if (side) found[side] = named.find((lang) => lang !== found[side] && fits(lang, side));
359
+ }
360
+ return { front: found.front ?? UNKNOWN, back: found.back ?? UNKNOWN, guessed: true };
361
+ }
package/src/library.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { t } from "./i18n.js";
2
2
  import { randomBytes } from "node:crypto";
3
- import { normalize } from "./judge.js";
3
+ import { frontKey } from "./judge.js";
4
4
  import { gapsOf } from "./cardline.js";
5
5
 
6
6
  // The card library: decks and their cards. Pure functions over a plain object; saving is the caller's job.
@@ -37,8 +37,7 @@ function cleanList(values) {
37
37
 
38
38
  const isText = (value) => typeof value === "string";
39
39
  const filled = (value) => isText(value) && value.trim() !== "";
40
- const validLanguages = (languages) => languages == null || (typeof languages === "object" && filled(languages.front) && filled(languages.back));
41
- const validDeck = (deck) => deck && isText(deck.id) && filled(deck.name) && validLanguages(deck.languages);
40
+ const validDeck = (deck) => deck && isText(deck.id) && filled(deck.name); // odd languages are tidied below
42
41
  // a cloze card's answers are its gaps, so its back (shown as a hint) may be empty
43
42
  const validCard = (card) =>
44
43
  card && isText(card.id) && isText(card.deckId) && filled(card.front) && Array.isArray(card.back) && (card.cloze ? gapsOf(card.front).length > 0 : card.back.length > 0) && card.back.every(filled);
@@ -59,13 +58,22 @@ export function upgradeLibrary(raw) {
59
58
  const deckIds = new Set(decks.map((deck) => deck.id));
60
59
  if (!cards.every((card) => deckIds.has(card.deckId))) throw broken(t("errors.why.cardDeck"));
61
60
  if (new Set(cards.map((card) => card.id)).size !== cards.length) throw broken(t("errors.why.cardIds"));
62
- return { version: LIBRARY_VERSION, decks, cards };
61
+ // languages edited by hand ("EN", "pt-BR", "english") are tidied, or left to be guessed again
62
+ const tidy = (languages) => {
63
+ try {
64
+ if (!languages || typeof languages !== "object") return null;
65
+ return cleanLanguages({ front: String(languages.front).split(/[-_]/)[0], back: String(languages.back).split(/[-_]/)[0] });
66
+ } catch {
67
+ return null;
68
+ }
69
+ };
70
+ return { version: LIBRARY_VERSION, decks: decks.map((deck) => ({ ...deck, languages: tidy(deck.languages) })), cards };
63
71
  }
64
72
 
65
73
  export const findDeck = (library, nameOrId) =>
66
74
  library.decks.find((deck) => deck.id === nameOrId) ?? library.decks.find((deck) => sameName(deck.name, nameOrId)) ?? null;
67
75
 
68
- export function createDeck(library, { name, type = "translation", languages = { front: "en", back: "pl" }, directions = "both", tour = false, now = Date.now() }) {
76
+ export function createDeck(library, { name, type = "translation", languages = null, directions = "both", tour = false, now = Date.now() }) {
69
77
  const trimmed = String(name ?? "").trim();
70
78
  if (!trimmed) throw new Error(t("errors.deckNeedsName"));
71
79
  if (Array.from(trimmed).length > MAX_DECK_NAME) throw new Error(t("errors.deckNameTooLong", { max: MAX_DECK_NAME }));
@@ -74,20 +82,40 @@ export function createDeck(library, { name, type = "translation", languages = {
74
82
  if (!CARD_TYPES.includes(type)) throw new Error(`Unknown card type "${type}".`);
75
83
  if (!DIRECTIONS.includes(directions)) throw new Error(`Unknown direction "${directions}".`);
76
84
 
77
- const deck = { id: newId("d"), name: trimmed, type, languages: languages ? { ...languages } : null, directions, tour, created: now };
85
+ const deck = { id: newId("d"), name: trimmed, type, languages: cleanLanguages(languages), directions, tour, created: now };
78
86
  library.decks.push(deck);
79
87
  return deck;
80
88
  }
81
89
 
82
90
  // Progress is kept per direction, so turning one off only stops asking it: its boxes stay for later.
83
- export function setDirections(library, deckId, directions) {
91
+ // `updated` says when: an Anki package written later makes its notes ask the new way too
92
+ export function setDirections(library, deckId, directions, now = Date.now()) {
84
93
  if (!DIRECTIONS.includes(directions)) throw new Error(`Unknown direction "${directions}".`);
85
94
  const deck = library.decks.find((d) => d.id === deckId);
86
95
  if (!deck) throw new Error("That deck doesn't exist.");
96
+ if (deck.directions !== directions) deck.updated = now;
87
97
  deck.directions = directions;
88
98
  return deck;
89
99
  }
90
100
 
101
+ // `languages`: { front, back } as ISO 639-1 codes ("und": not one language), or null to go back to guessing
102
+ const LANGUAGE_CODE = /^[a-z]{2,3}$/;
103
+ function cleanLanguages(languages) {
104
+ if (!languages) return null;
105
+ const code = (value) => (typeof value === "string" ? value.trim().toLowerCase() : "");
106
+ const [front, back] = [code(languages.front), code(languages.back)];
107
+ if (!LANGUAGE_CODE.test(front) || !LANGUAGE_CODE.test(back)) throw new Error(`Unknown language "${languages.front} → ${languages.back}".`);
108
+ return { front, back };
109
+ }
110
+
111
+ export function setLanguages(library, deckId, languages) {
112
+ const clean = cleanLanguages(languages);
113
+ const deck = library.decks.find((d) => d.id === deckId);
114
+ if (!deck) throw new Error("That deck doesn't exist.");
115
+ deck.languages = clean;
116
+ return deck;
117
+ }
118
+
91
119
  // → the ids of the cards that went with it, so their progress can be dropped too
92
120
  export function removeDeck(library, deckId) {
93
121
  const removed = cardsOf(library, deckId).map((card) => card.id);
@@ -98,15 +126,21 @@ export function removeDeck(library, deckId) {
98
126
 
99
127
  export const cardsOf = (library, deckId) => library.cards.filter((card) => card.deckId === deckId);
100
128
 
101
- // a card with the same front (ignoring case, accents and punctuation) in the same deck
102
- export const findDuplicate = (library, deckId, front) => {
103
- const key = normalize(front);
104
- return library.cards.find((card) => card.deckId === deckId && normalize(card.front) === key) ?? null;
129
+ // a card with the same front (ignoring case and punctuation: see frontKey) in the same deck. `index`,
130
+ // a Map of frontKey → card for the deck, saves reading every card again (an import adds thousands)
131
+ export const findDuplicate = (library, deckId, front, index = null) => {
132
+ const key = frontKey(front);
133
+ if (index) return index.get(key) ?? null;
134
+ return library.cards.find((card) => card.deckId === deckId && frontKey(card.front) === key) ?? null;
105
135
  };
136
+ export const frontIndex = (library, deckId) => new Map(cardsOf(library, deckId).map((card) => [frontKey(card.front), card]));
106
137
 
107
138
  // → { card, duplicate }: `duplicate` is the existing card when the front is already in the deck (nothing is added then)
108
139
  // `cloze`: the front has {{gaps}}, each asked as a card of its own; the back is then only a hint
109
- export function addCard(library, deckId, { front, back, example = "", tags = [], cloze = false, id, now = Date.now() }) {
140
+ // `index`: the deck's frontIndex, kept up to date here (see findDuplicate)
141
+ // `guid`: the note in a Dracosh package it came from, so going back to Anki it's that note again;
142
+ // `fromAnki`: it came from a note of Anki's own (see apkg.js), which Anki still has
143
+ export function addCard(library, deckId, { front, back, example = "", tags = [], cloze = false, id, guid, fromAnki = false, now = Date.now() }, index = null) {
110
144
  if (!library.decks.some((deck) => deck.id === deckId)) throw new Error("That deck doesn't exist.");
111
145
  const cleanFront = String(front ?? "").trim();
112
146
  const cleanBack = cleanList(back);
@@ -114,12 +148,13 @@ export function addCard(library, deckId, { front, back, example = "", tags = [],
114
148
  if (!cleanFront) throw new Error(t("errors.cardNeedsFront"));
115
149
  if (!cleanBack.length && !isCloze) throw new Error(t("errors.cardNeedsBack"));
116
150
 
117
- const duplicate = findDuplicate(library, deckId, cleanFront);
151
+ const duplicate = findDuplicate(library, deckId, cleanFront, index);
118
152
  if (duplicate) return { card: null, duplicate };
119
153
 
120
- const card = { id: id ? String(id) : newId("c"), deckId, front: cleanFront, back: cleanBack, example: String(example).trim(), tags: cleanList(tags), ...(isCloze && { cloze: true }), created: now, updated: now };
121
- if (library.cards.some((c) => c.id === card.id)) throw new Error(`A card with id ${card.id} already exists.`);
154
+ const card = { id: id ? String(id) : newId("c"), deckId, front: cleanFront, back: cleanBack, example: String(example).trim(), tags: cleanList(tags), ...(isCloze && { cloze: true }), ...(guid && { guid: String(guid) }), ...(fromAnki && { fromAnki: true }), created: now, updated: now };
155
+ if (id && library.cards.some((c) => c.id === card.id)) throw new Error(`A card with id ${card.id} already exists.`);
122
156
  library.cards.push(card);
157
+ index?.set(frontKey(cleanFront), card);
123
158
  return { card, duplicate: null };
124
159
  }
125
160
 
package/src/manage.js CHANGED
@@ -2,7 +2,8 @@ import { t } from "./i18n.js";
2
2
  import { backupNow } from "./backup.js";
3
3
  import { seedLibrary } from "./starter.js";
4
4
  import { gapsOf } from "./cardline.js";
5
- import { addCard, cardsOf, createDeck, emptyLibrary, findDeck, findDuplicate, removeDeck, setDirections as setLibraryDirections, typedSides, updateCard } from "./library.js";
5
+ import { addCard, cardsOf, createDeck, emptyLibrary, findDeck, findDuplicate, removeDeck, setDirections as setLibraryDirections, setLanguages as setLibraryLanguages, typedSides, updateCard } from "./library.js";
6
+ import { deckLanguages, homeLanguages, learningSide } from "./language.js";
6
7
  import { itemKey } from "./scheduler.js";
7
8
  import { loadLibrary, saveLibrary } from "./store.js";
8
9
 
@@ -24,6 +25,23 @@ function checkSlashes(deck, fields) {
24
25
  // Library changes made from inside the app (/add, /decks). Each one reads the library fresh, so nothing
25
26
  // written meanwhile by another Dracosh window is lost. `load`, `save` and `backup` are the store's; the
26
27
  // preview gallery passes its own, so nothing it does is saved.
28
+ // your own language, as your other decks with languages set suggest (see homeLanguages)
29
+ const homeOf = (library, deck) => homeLanguages({ others: library.decks.filter((d) => d !== deck && d.languages).map((d) => d.languages) });
30
+ const learningOf = (library, deck, languages = deckLanguages(deck, cardsOf(library, deck.id))) => learningSide(languages, deck, homeOf(library, deck));
31
+ const withLearning = (library, deck) => {
32
+ const languages = deckLanguages(deck, cardsOf(library, deck.id));
33
+ return { ...languages, learning: learningOf(library, deck, languages), home: homeOf(library, deck) };
34
+ };
35
+
36
+ // A language picked as the one you're learning is kept, unless it's what a sure guess says anyway: then
37
+ // the guess goes on following the deck (its name, your other decks)
38
+ function chooseLearning(library, deck, lang) {
39
+ const languages = deckLanguages(deck, cardsOf(library, deck.id));
40
+ if (lang && lang !== languages.front && lang !== languages.back) return; // only a language the deck has
41
+ const guess = learningOf(library, { ...deck, learning: undefined });
42
+ deck.learning = !lang || (guess?.sure && guess.lang === lang) ? undefined : lang;
43
+ }
44
+
27
45
  export function libraryActions({ load = loadLibrary, save = saveLibrary, backup = backupNow } = {}) {
28
46
  async function deckNamed(library, deckName) {
29
47
  const deck = findDeck(library, deckName);
@@ -38,7 +56,8 @@ export function libraryActions({ load = loadLibrary, save = saveLibrary, backup
38
56
  return library.decks.map((deck) => {
39
57
  const cards = cardsOf(library, deck.id);
40
58
  const sample = cards.find((card) => !card.cloze); // shows the deck's directions in /decks
41
- return { name: deck.name, cards: cards.length, tour: Boolean(deck.tour), directions: deck.directions, sample: sample ? { front: sample.front, back: sample.back } : null };
59
+ const languages = deckLanguages(deck, cards);
60
+ return { name: deck.name, cards: cards.length, tour: Boolean(deck.tour), directions: deck.directions, languages, learning: learningOf(library, deck, languages), home: homeOf(library, deck), sample: sample ? { front: sample.front, back: sample.back } : null };
42
61
  });
43
62
  },
44
63
 
@@ -77,6 +96,32 @@ export function libraryActions({ load = loadLibrary, save = saveLibrary, backup
77
96
  return { deck, cardIds: cards.map((card) => card.id) };
78
97
  },
79
98
 
99
+ // → { front, back, guessed }: the languages set for the deck, or guessed from its cards
100
+ // (with `learning`: the language you're learning, see learningSide; null for a deck in one language)
101
+ async languagesOf(deckName) {
102
+ const library = await load();
103
+ return withLearning(library, await deckNamed(library, deckName));
104
+ },
105
+
106
+ // { front, back, learning? } from /decks or /add (`learning`: a language code); null goes back to
107
+ // guessing from the cards
108
+ async setLanguages(deckName, languages) {
109
+ const library = await load();
110
+ const deck = setLibraryLanguages(library, (await deckNamed(library, deckName)).id, languages);
111
+ if (languages?.learning !== undefined) chooseLearning(library, deck, languages.learning);
112
+ await save(library);
113
+ return withLearning(library, deck);
114
+ },
115
+
116
+ // the language you're learning in a deck (a code), from /decks → Learning → as it now stands
117
+ async setLearning(deckName, lang) {
118
+ const library = await load();
119
+ const deck = await deckNamed(library, deckName);
120
+ chooseLearning(library, deck, lang);
121
+ await save(library);
122
+ return learningOf(library, deck);
123
+ },
124
+
80
125
  // the deck with this name (ignoring case), if any: /add says so before asking anything else
81
126
  async existingDeck(name) {
82
127
  const deck = findDeck(await load(), name.trim());
@@ -162,4 +207,4 @@ export function libraryActions({ load = loadLibrary, save = saveLibrary, backup
162
207
 
163
208
  // the app's own: reads and writes ~/.dracosh
164
209
  const actions = libraryActions();
165
- export const { allDecks, ownDecks, startDeck, setDirections, existingDeck, existingCard, addCardTo, addCardsTo, updateCardIn, matchTourLanguage, backupBeforeReset, resetLibrary } = actions;
210
+ export const { allDecks, ownDecks, startDeck, setDirections, languagesOf, setLanguages, setLearning, existingDeck, existingCard, addCardTo, addCardsTo, updateCardIn, matchTourLanguage, backupBeforeReset, resetLibrary } = actions;