dracosh 0.2.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.
Files changed (57) hide show
  1. package/README.md +25 -17
  2. package/locales/de.json +1098 -0
  3. package/locales/en.json +1081 -0
  4. package/locales/fr.json +1148 -0
  5. package/locales/pl.json +1173 -0
  6. package/locales/uk.json +1174 -0
  7. package/package.json +2 -2
  8. package/src/alerts.js +71 -4
  9. package/src/backup.js +2 -1
  10. package/src/cardline.js +71 -0
  11. package/src/cli.js +41 -54
  12. package/src/commands.js +14 -12
  13. package/src/demo.js +11 -0
  14. package/src/diff.js +20 -10
  15. package/src/i18n.js +68 -0
  16. package/src/judge.js +164 -13
  17. package/src/language.js +355 -0
  18. package/src/library.js +91 -38
  19. package/src/lock.js +2 -1
  20. package/src/manage.js +193 -58
  21. package/src/pause.js +1 -2
  22. package/src/progress.js +119 -63
  23. package/src/quiet.js +3 -2
  24. package/src/scheduler.js +26 -9
  25. package/src/session.js +118 -36
  26. package/src/settings.js +14 -6
  27. package/src/starter.js +36 -27
  28. package/src/store.js +11 -8
  29. package/src/tips.js +12 -3
  30. package/src/ui/AddCard.js +449 -81
  31. package/src/ui/AnswerInput.js +22 -10
  32. package/src/ui/App.js +209 -57
  33. package/src/ui/BadgeUnlock.js +5 -4
  34. package/src/ui/Badges.js +9 -8
  35. package/src/ui/Choice.js +14 -9
  36. package/src/ui/Companion.js +13 -13
  37. package/src/ui/Confetti.js +2 -2
  38. package/src/ui/Decks.js +167 -9
  39. package/src/ui/DieRoll.js +9 -9
  40. package/src/ui/Evolution.js +7 -7
  41. package/src/ui/Hatch.js +7 -6
  42. package/src/ui/Header.js +58 -16
  43. package/src/ui/Help.js +43 -25
  44. package/src/ui/Languages.js +167 -0
  45. package/src/ui/Mascot.js +1 -2
  46. package/src/ui/Missed.js +13 -12
  47. package/src/ui/Preview.js +48 -29
  48. package/src/ui/Reset.js +13 -14
  49. package/src/ui/Settings.js +27 -19
  50. package/src/ui/Stats.js +24 -23
  51. package/src/ui/Summary.js +30 -15
  52. package/src/ui/TheOne.js +7 -6
  53. package/src/ui/icons.js +1 -2
  54. package/src/ui/kit.js +34 -6
  55. package/src/vacation.js +2 -1
  56. package/src/words.js +8 -2
  57. package/data/tips.json +0 -32
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 = /[;!?¡¿"“”„«»()[\]'’`]/g;
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, "")
@@ -22,9 +28,26 @@ function plain(s) {
22
28
  return text || s.trim().toLowerCase(); // an answer made only of punctuation ("?") is still itself
23
29
  }
24
30
 
25
- // plain(), and diacritics folded too (ł doesn't decompose, so it is mapped by hand)
31
+ // Letters that don't decompose into a base letter and an accent, spelled the way a keyboard without them would
32
+ const SPELLED = { ł: "l", ß: "ss", æ: "ae", œ: "oe", ø: "o", đ: "d", ð: "d", þ: "th", ı: "i" };
33
+ // й, ї and ў are letters of their own in Ukrainian and Belarusian (on every keyboard there), not и, і, у with an accent
34
+ const OWN = { й: "\ue000", ї: "\ue001", ў: "\ue002" };
35
+ const OWN_BACK = Object.fromEntries(Object.entries(OWN).map(([letter, mark]) => [mark, letter]));
36
+
37
+ // Diacritics folded away from lowercase text: "żółw" → "zolw", "straße" → "strasse", "fi" → "fi"
38
+ export function fold(s) {
39
+ return s
40
+ .normalize("NFKC")
41
+ .replace(/[йїў]/g, (ch) => OWN[ch])
42
+ .replace(/[łßæœøđðþı]/g, (ch) => SPELLED[ch])
43
+ .normalize("NFD")
44
+ .replace(/[\u0300-\u036f]/g, "")
45
+ .replace(/[\ue000-\ue002]/g, (ch) => OWN_BACK[ch]);
46
+ }
47
+
48
+ // plain(), and diacritics folded too
26
49
  export function normalize(s) {
27
- return plain(s).replace(/ł/g, "l").normalize("NFD").replace(/[\u0300-\u036f]/g, "");
50
+ return fold(plain(s));
28
51
  }
29
52
 
30
53
  // Damerau-Levenshtein (optimal string alignment): a swap of two neighbours counts as one edit
@@ -45,12 +68,13 @@ export function editDistance(a, b) {
45
68
  return d[rows - 1][cols - 1];
46
69
  }
47
70
 
48
- // The candidate the answer came closest to (fewest edits after normalizing): what a miss is diffed against
49
- export function closestCandidate(answer, candidates) {
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 } = {}) {
50
74
  const given = normalize(answer);
51
75
  let best = candidates[0];
52
76
  let bestDistance = Infinity;
53
- for (const candidate of candidates) {
77
+ for (const candidate of candidates.flatMap((c) => [c, spelledOut(c, lang)])) {
54
78
  const distance = editDistance(given, normalize(candidate));
55
79
  if (distance < bestDistance) {
56
80
  bestDistance = distance;
@@ -60,15 +84,142 @@ export function closestCandidate(answer, candidates) {
60
84
  return best;
61
85
  }
62
86
 
63
- // → "exact" | "typo" | "wrong"; accepts any one of the candidate answers. Missing or wrong
64
- // diacritics ("zolw" for "żółw") count, as "typo", so the right spelling is shown. One more typo is
65
- // forgiven on longer answers, but never in numbers: "123457" isn't "123456".
66
- export function judge(answer, candidates) {
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
177
+ // diacritics ("zolw" for "żółw") are "accent": right, quietly (not everyone has the letters on their
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 } = {}) {
67
189
  if (!answer.trim()) return "wrong";
68
- const given = normalize(answer);
69
190
  if (candidates.some((c) => plain(c) === plain(answer))) return "exact";
70
- const targets = candidates.map(normalize);
71
- if (targets.includes(given)) return "typo";
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";
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
+ }
72
223
  // "email" for "e-mail", "icecream" for "ice cream": right, but shown with the spelling
73
224
  const compact = (s) => s.replace(/\s/g, ""); // hyphens between letters are spaces by now
74
225
  if (targets.some((t) => compact(t) === compact(given))) return "typo";
@@ -0,0 +1,355 @@
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
+ return { front: found.front ?? UNKNOWN, back: found.back ?? UNKNOWN, guessed: true };
355
+ }