dracosh 0.3.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +14 -11
- package/locales/de.json +61 -9
- package/locales/en.json +61 -9
- package/locales/fr.json +63 -9
- package/locales/pl.json +65 -9
- package/locales/uk.json +65 -9
- package/package.json +1 -1
- package/src/alerts.js +68 -3
- package/src/cli.js +2 -2
- package/src/diff.js +8 -4
- package/src/judge.js +143 -10
- package/src/language.js +355 -0
- package/src/library.js +31 -5
- package/src/manage.js +48 -3
- package/src/progress.js +43 -4
- package/src/scheduler.js +23 -3
- package/src/session.js +54 -22
- package/src/settings.js +2 -1
- package/src/store.js +2 -1
- package/src/ui/AddCard.js +46 -2
- package/src/ui/App.js +33 -12
- package/src/ui/BadgeUnlock.js +1 -1
- package/src/ui/Decks.js +120 -12
- package/src/ui/Help.js +13 -1
- package/src/ui/Languages.js +167 -0
- package/src/ui/Settings.js +1 -0
- package/src/ui/Summary.js +23 -9
- package/src/words.js +6 -1
package/src/language.js
ADDED
|
@@ -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
|
+
}
|
package/src/library.js
CHANGED
|
@@ -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
|
|
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
|
-
|
|
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 =
|
|
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,7 +82,7 @@ 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
|
|
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
|
}
|
|
@@ -88,6 +96,24 @@ export function setDirections(library, deckId, directions) {
|
|
|
88
96
|
return deck;
|
|
89
97
|
}
|
|
90
98
|
|
|
99
|
+
// `languages`: { front, back } as ISO 639-1 codes ("und": not one language), or null to go back to guessing
|
|
100
|
+
const LANGUAGE_CODE = /^[a-z]{2,3}$/;
|
|
101
|
+
function cleanLanguages(languages) {
|
|
102
|
+
if (!languages) return null;
|
|
103
|
+
const code = (value) => (typeof value === "string" ? value.trim().toLowerCase() : "");
|
|
104
|
+
const [front, back] = [code(languages.front), code(languages.back)];
|
|
105
|
+
if (!LANGUAGE_CODE.test(front) || !LANGUAGE_CODE.test(back)) throw new Error(`Unknown language "${languages.front} → ${languages.back}".`);
|
|
106
|
+
return { front, back };
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export function setLanguages(library, deckId, languages) {
|
|
110
|
+
const clean = cleanLanguages(languages);
|
|
111
|
+
const deck = library.decks.find((d) => d.id === deckId);
|
|
112
|
+
if (!deck) throw new Error("That deck doesn't exist.");
|
|
113
|
+
deck.languages = clean;
|
|
114
|
+
return deck;
|
|
115
|
+
}
|
|
116
|
+
|
|
91
117
|
// → the ids of the cards that went with it, so their progress can be dropped too
|
|
92
118
|
export function removeDeck(library, deckId) {
|
|
93
119
|
const removed = cardsOf(library, deckId).map((card) => card.id);
|
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
|
-
|
|
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;
|
package/src/progress.js
CHANGED
|
@@ -52,6 +52,7 @@ export function ensureProgress(state, now = Date.now()) {
|
|
|
52
52
|
vacations: []
|
|
53
53
|
};
|
|
54
54
|
state.progress.vacations ??= [];
|
|
55
|
+
delete state.progress.quiet; // a test build's single stretch, before quietDays
|
|
55
56
|
// badges already shown in /badges; ones unlocked before this was tracked count as seen, so they don't all flash at once
|
|
56
57
|
state.progress.seenBadges ??= Object.keys(state.progress.badges);
|
|
57
58
|
return state.progress;
|
|
@@ -61,8 +62,35 @@ export function ensureProgress(state, now = Date.now()) {
|
|
|
61
62
|
|
|
62
63
|
const NO_RULES = { skipWeekends: false };
|
|
63
64
|
|
|
65
|
+
// A day with nothing to practise: opened and nothing was waiting, or, after a day done, before the next
|
|
66
|
+
// card came back, whether Dracosh was opened or not. Each such stretch is kept in `quietDays` as
|
|
67
|
+
// { from, until } (the days strictly between); a later one never wipes an earlier one out.
|
|
68
|
+
const KEPT_QUIET = 30;
|
|
69
|
+
function nothingToDo(progress, key) {
|
|
70
|
+
if (progress.days?.[key]?.nothingDue) return true;
|
|
71
|
+
return (progress.quietDays ?? []).some((q) => key > q.from && key < q.until);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// The day is done and nothing comes back before `until` (a day key): the days between are rest days.
|
|
75
|
+
// Settling again inside a stretch moves its end, never its start.
|
|
76
|
+
export function markQuiet(progress, today, until) {
|
|
77
|
+
if (!until || until <= today) return;
|
|
78
|
+
const list = (progress.quietDays ??= []);
|
|
79
|
+
const last = list.at(-1);
|
|
80
|
+
if (last && today >= last.from && today < last.until) last.until = until;
|
|
81
|
+
else list.push({ from: today, until });
|
|
82
|
+
progress.quietDays = list.slice(-KEPT_QUIET);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// Something turned up to practise today (cards added, a deck or a direction switched on): the stretch
|
|
86
|
+
// it falls in ends here, so the days ahead aren't rest days any more
|
|
87
|
+
export function markWorkWaiting(progress, today) {
|
|
88
|
+
const last = progress.quietDays?.at(-1);
|
|
89
|
+
if (last && today >= last.from && today < last.until) last.until = today > last.from ? today : addDays(today, 1);
|
|
90
|
+
}
|
|
91
|
+
|
|
64
92
|
export function isRestDay(progress, key, rules = NO_RULES) {
|
|
65
|
-
if (progress
|
|
93
|
+
if (nothingToDo(progress, key)) return true;
|
|
66
94
|
if (rules.skipWeekends) {
|
|
67
95
|
const weekday = new Date(`${key}T12:00:00`).getDay();
|
|
68
96
|
if (weekday === 0 || weekday === 6) return true;
|
|
@@ -318,7 +346,7 @@ export function applyAnswer(state, { result, goal, rules = NO_RULES, combo = 0,
|
|
|
318
346
|
const day = dayOf(progress, today);
|
|
319
347
|
const correct = result !== "wrong";
|
|
320
348
|
// full days away since the last correct answer (a wrong first answer back doesn't end the absence)
|
|
321
|
-
const daysAway =
|
|
349
|
+
const daysAway = awayDays(progress, today);
|
|
322
350
|
|
|
323
351
|
day.asked += 1;
|
|
324
352
|
day.correct += correct ? 1 : 0;
|
|
@@ -327,13 +355,22 @@ export function applyAnswer(state, { result, goal, rules = NO_RULES, combo = 0,
|
|
|
327
355
|
return { cheers: award(state, progress, day, today, { correct, goal, rules, now, daysAway, random }) };
|
|
328
356
|
}
|
|
329
357
|
|
|
358
|
+
// full days since the last correct answer, not counting days with nothing to practise: coming back after
|
|
359
|
+
// those isn't a comeback (a vacation still is)
|
|
360
|
+
function awayDays(progress, today) {
|
|
361
|
+
if (!progress.lastActiveDay) return 0;
|
|
362
|
+
let away = 0;
|
|
363
|
+
for (let key = addDays(progress.lastActiveDay, 1); key < today; key = addDays(key, 1)) if (!nothingToDo(progress, key)) away += 1;
|
|
364
|
+
return away;
|
|
365
|
+
}
|
|
366
|
+
|
|
330
367
|
// A wrong answer the user then declared right: it was already counted as asked, so only credit the correct one
|
|
331
368
|
export function applyOverrule(state, { goal, rules = NO_RULES, combo = 0, now = Date.now(), random = Math.random }) {
|
|
332
369
|
const progress = ensureProgress(state, now);
|
|
333
370
|
const today = dayKey(now);
|
|
334
371
|
const day = dayOf(progress, today);
|
|
335
372
|
|
|
336
|
-
const daysAway =
|
|
373
|
+
const daysAway = awayDays(progress, today);
|
|
337
374
|
day.correct += 1;
|
|
338
375
|
progress.bestCombo = Math.max(progress.bestCombo ?? 0, combo);
|
|
339
376
|
progress.lastActiveDay = today;
|
|
@@ -343,10 +380,12 @@ export function applyOverrule(state, { goal, rules = NO_RULES, combo = 0, now =
|
|
|
343
380
|
// Nothing left to practise today in the whole library → cheers. After at least one right answer today
|
|
344
381
|
// that counts as the goal (see award); with nothing answered at all the day only becomes a rest day, so just
|
|
345
382
|
// opening Dracosh never builds a streak. Nothing happens once the goal is met.
|
|
346
|
-
|
|
383
|
+
// `nextDue`: when the next card anywhere comes back (null: none ever), so the days until then count as rest.
|
|
384
|
+
export function applyCaughtUp(state, { goal, rules = NO_RULES, now = Date.now(), nextDue, random = Math.random }) {
|
|
347
385
|
const progress = ensureProgress(state, now);
|
|
348
386
|
const today = dayKey(now);
|
|
349
387
|
const day = dayOf(progress, today);
|
|
388
|
+
if (nextDue) markQuiet(progress, today, dayKey(nextDue));
|
|
350
389
|
if (day.goalMet) return { cheers: [] };
|
|
351
390
|
if (!day.asked) {
|
|
352
391
|
day.nothingDue = true;
|
package/src/scheduler.js
CHANGED
|
@@ -15,6 +15,24 @@ export function newToday(state, now) {
|
|
|
15
15
|
return state.newToday?.date === dayKey(now) ? state.newToday.count : 0;
|
|
16
16
|
}
|
|
17
17
|
|
|
18
|
+
// A review is waiting for the whole day it falls due, from midnight: a card answered at 17:00 yesterday
|
|
19
|
+
// can be done this morning. But never sooner than half a day after it was answered, so a sitting across
|
|
20
|
+
// midnight doesn't ask it again minutes later. A card just missed (streak 0) comes back at its minute.
|
|
21
|
+
const MIN_GAP = 12 * 60 * MINUTE;
|
|
22
|
+
export function readyAt(entry) {
|
|
23
|
+
if (!entry.streak) return entry.due;
|
|
24
|
+
const day = new Date(entry.due);
|
|
25
|
+
day.setHours(0, 0, 0, 0);
|
|
26
|
+
return Math.min(entry.due, Math.max(day.getTime(), (entry.last ?? 0) + MIN_GAP));
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// the same time of day, `days` calendar days later (a day with a clock change is still one day)
|
|
30
|
+
function daysLater(now, days) {
|
|
31
|
+
const date = new Date(now);
|
|
32
|
+
date.setDate(date.getDate() + days);
|
|
33
|
+
return date.getTime();
|
|
34
|
+
}
|
|
35
|
+
|
|
18
36
|
const NEW_RATIO = 0.3; // when both due and unseen items exist, this share of questions introduces a new one
|
|
19
37
|
const MAX_OVERDUE_WEIGHT_DAYS = 3;
|
|
20
38
|
|
|
@@ -42,7 +60,9 @@ export function pickNext({ words, state, now = Date.now(), lastNoteId = null, di
|
|
|
42
60
|
if (tour) return candidates.find((c) => !c.entry) ?? null;
|
|
43
61
|
|
|
44
62
|
const canIntroduce = newToday(state, now) < NEW_PER_DAY;
|
|
45
|
-
|
|
63
|
+
// the other way round of a card already started is no new card: the daily limit counts cards
|
|
64
|
+
const started = new Set(candidates.filter((c) => c.entry).map((c) => c.word.noteId));
|
|
65
|
+
const waiting = candidates.filter((c) => (c.entry ? readyAt(c.entry) <= now : canIntroduce || started.has(c.word.noteId)));
|
|
46
66
|
if (!waiting.length) return null;
|
|
47
67
|
const pool = waiting.some((c) => c.word.noteId !== lastNoteId) ? waiting.filter((c) => c.word.noteId !== lastNoteId) : waiting;
|
|
48
68
|
|
|
@@ -59,7 +79,7 @@ export function nextDueAt({ words, state, now = Date.now(), directions = DIRECTI
|
|
|
59
79
|
for (const word of words) {
|
|
60
80
|
for (const direction of word.directions ?? directions) {
|
|
61
81
|
const entry = state.items[itemKey(word.noteId, direction)];
|
|
62
|
-
const at = entry ? entry
|
|
82
|
+
const at = entry ? readyAt(entry) : startOfTomorrow(now);
|
|
63
83
|
if (next === null || at < next) next = at;
|
|
64
84
|
}
|
|
65
85
|
}
|
|
@@ -78,7 +98,7 @@ export function grade(entry, correct, now = Date.now(), { hinted = false } = {})
|
|
|
78
98
|
// right after a miss the card starts over at box 1 (back tomorrow) instead of skipping ahead
|
|
79
99
|
const relearning = prev.seen > 0 && prev.streak === 0;
|
|
80
100
|
const box = hinted || relearning ? Math.max(prev.box, 1) : Math.min(prev.box + 1, BOX_INTERVALS_DAYS.length);
|
|
81
|
-
return { ...prev, box, due: now
|
|
101
|
+
return { ...prev, box, due: daysLater(now, BOX_INTERVALS_DAYS[box - 1]), seen: prev.seen + 1, correct: prev.correct + 1, streak: prev.streak + 1, last: now };
|
|
82
102
|
}
|
|
83
103
|
return { ...prev, box: 1, due: now + RELEARN_DELAY, seen: prev.seen + 1, wrong: prev.wrong + 1, streak: 0, last: now };
|
|
84
104
|
}
|