dracosh 0.0.0-stage → 0.1.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/LICENSE +202 -0
- package/NOTICE +10 -0
- package/README.md +78 -2
- package/assets/sounds/ask.wav +0 -0
- package/assets/sounds/badge.wav +0 -0
- package/assets/sounds/close.wav +0 -0
- package/assets/sounds/combo.wav +0 -0
- package/assets/sounds/correct-0.wav +0 -0
- package/assets/sounds/correct-1.wav +0 -0
- package/assets/sounds/correct-2.wav +0 -0
- package/assets/sounds/correct-3.wav +0 -0
- package/assets/sounds/correct-4.wav +0 -0
- package/assets/sounds/correct-5.wav +0 -0
- package/assets/sounds/evolve.wav +0 -0
- package/assets/sounds/goal.wav +0 -0
- package/assets/sounds/wrong.wav +0 -0
- package/data/tips.json +1362 -0
- package/package.json +47 -4
- package/src/alerts.js +37 -0
- package/src/anki.js +36 -0
- package/src/cli.js +116 -0
- package/src/commands.js +28 -0
- package/src/dates.js +15 -0
- package/src/demo.js +11 -0
- package/src/diff.js +46 -0
- package/src/hint.js +12 -0
- package/src/judge.js +57 -0
- package/src/parse.js +42 -0
- package/src/progress.js +363 -0
- package/src/quiet.js +32 -0
- package/src/scheduler.js +82 -0
- package/src/session.js +129 -0
- package/src/settings.js +43 -0
- package/src/store.js +61 -0
- package/src/tips.js +47 -0
- package/src/ui/AnswerInput.js +82 -0
- package/src/ui/App.js +369 -0
- package/src/ui/Badges.js +64 -0
- package/src/ui/Companion.js +60 -0
- package/src/ui/Confetti.js +46 -0
- package/src/ui/Evolution.js +58 -0
- package/src/ui/Hatch.js +99 -0
- package/src/ui/Header.js +116 -0
- package/src/ui/Mascot.js +128 -0
- package/src/ui/Missed.js +52 -0
- package/src/ui/Preview.js +181 -0
- package/src/ui/Settings.js +65 -0
- package/src/ui/Stats.js +108 -0
- package/src/ui/Summary.js +34 -0
- package/src/ui/Tip.js +25 -0
- package/src/ui/icons.js +209 -0
- package/src/ui/kit.js +63 -0
- package/src/vacation.js +51 -0
- package/src/words.js +16 -0
package/package.json
CHANGED
|
@@ -1,6 +1,49 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dracosh",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "A gamified language or definitions trainer for your terminal. Your personal pixel dragon grows with your progress.",
|
|
5
|
+
"author": "Tomasz Przyborowski (https://github.com/lynthius)",
|
|
6
|
+
"license": "Apache-2.0",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/lynthius/dracosh.git"
|
|
10
|
+
},
|
|
11
|
+
"homepage": "https://github.com/lynthius/dracosh#readme",
|
|
12
|
+
"bugs": {
|
|
13
|
+
"url": "https://github.com/lynthius/dracosh/issues"
|
|
14
|
+
},
|
|
15
|
+
"keywords": [
|
|
16
|
+
"cli",
|
|
17
|
+
"tui",
|
|
18
|
+
"vocabulary",
|
|
19
|
+
"flashcards",
|
|
20
|
+
"spaced-repetition",
|
|
21
|
+
"anki",
|
|
22
|
+
"ink",
|
|
23
|
+
"pixel-art",
|
|
24
|
+
"language-learning"
|
|
25
|
+
],
|
|
26
|
+
"type": "module",
|
|
27
|
+
"bin": {
|
|
28
|
+
"dracosh": "src/cli.js"
|
|
29
|
+
},
|
|
30
|
+
"files": [
|
|
31
|
+
"src",
|
|
32
|
+
"assets",
|
|
33
|
+
"data",
|
|
34
|
+
"NOTICE"
|
|
35
|
+
],
|
|
36
|
+
"engines": {
|
|
37
|
+
"node": ">=22"
|
|
38
|
+
},
|
|
39
|
+
"scripts": {
|
|
40
|
+
"start": "node src/cli.js",
|
|
41
|
+
"test": "node --test test/",
|
|
42
|
+
"sounds": "node scripts/make-sounds.js"
|
|
43
|
+
},
|
|
44
|
+
"dependencies": {
|
|
45
|
+
"htm": "3.1.1",
|
|
46
|
+
"ink": "7.1.1",
|
|
47
|
+
"react": "19.2.4"
|
|
48
|
+
}
|
|
49
|
+
}
|
package/src/alerts.js
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
4
|
+
|
|
5
|
+
// 8-bit chiptune effects generated by scripts/make-sounds.js (see `npm run sounds`)
|
|
6
|
+
const SOUND_DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "assets", "sounds");
|
|
7
|
+
const LADDER_STEPS = 6; // correct-0 … correct-5: the pitch climbs with your combo
|
|
8
|
+
|
|
9
|
+
export function createAlerts(initial = {}) {
|
|
10
|
+
const enabled = process.platform === "darwin";
|
|
11
|
+
const config = { sound: true, volume: 0.5, ...initial };
|
|
12
|
+
|
|
13
|
+
const play = (name) => {
|
|
14
|
+
if (!config.sound || !enabled) return;
|
|
15
|
+
execFile("afplay", ["-v", String(config.volume), path.join(SOUND_DIR, `${name}.wav`)], () => {});
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
return {
|
|
19
|
+
play,
|
|
20
|
+
configure: (patch) => Object.assign(config, patch),
|
|
21
|
+
// a new question while you're in another window: sound plus a Notification Center banner
|
|
22
|
+
ask() {
|
|
23
|
+
play("ask");
|
|
24
|
+
if (enabled) execFile("osascript", ["-e", 'display notification "A new word is waiting" with title "Dracosh"'], () => {});
|
|
25
|
+
},
|
|
26
|
+
// The biggest thing that just happened wins: evolution > badge > goal > combo cheer > the answer itself.
|
|
27
|
+
// On a plain correct answer the pitch rises with the combo and resets on a miss.
|
|
28
|
+
result(result, { cheers = [], combo = 0 } = {}) {
|
|
29
|
+
if (result === "wrong") return play("wrong");
|
|
30
|
+
for (const kind of ["evolve", "badge", "goal", "combo"]) {
|
|
31
|
+
if (cheers.includes(kind)) return play(kind);
|
|
32
|
+
}
|
|
33
|
+
if (result === "typo") return play("close");
|
|
34
|
+
play(`correct-${Math.min(Math.max(combo - 1, 0), LADDER_STEPS - 1)}`);
|
|
35
|
+
}
|
|
36
|
+
};
|
|
37
|
+
}
|
package/src/anki.js
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
// Read-only AnkiConnect client: the quiz never writes to Anki.
|
|
2
|
+
const ANKI_URL = process.env.ANKI_CONNECT_URL || "http://localhost:8765";
|
|
3
|
+
|
|
4
|
+
async function invoke(action, params = {}) {
|
|
5
|
+
let res;
|
|
6
|
+
try {
|
|
7
|
+
res = await fetch(ANKI_URL, {
|
|
8
|
+
method: "POST",
|
|
9
|
+
headers: { "Content-Type": "application/json" },
|
|
10
|
+
body: JSON.stringify({ action, version: 6, params }),
|
|
11
|
+
signal: AbortSignal.timeout(10000)
|
|
12
|
+
});
|
|
13
|
+
} catch {
|
|
14
|
+
throw new Error("Can't reach Anki. Make sure Anki is running with AnkiConnect.");
|
|
15
|
+
}
|
|
16
|
+
const data = await res.json();
|
|
17
|
+
if (data.error) throw new Error(data.error);
|
|
18
|
+
return data.result;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
const escapeQuery = (s) => s.replace(/[\\"]/g, "\\$&");
|
|
22
|
+
|
|
23
|
+
export async function fetchNotes(deck) {
|
|
24
|
+
const ids = await invoke("findNotes", { query: `deck:"${escapeQuery(deck)}"` });
|
|
25
|
+
if (!ids.length) return [];
|
|
26
|
+
const infos = await invoke("notesInfo", { notes: ids });
|
|
27
|
+
return infos.map(toFrontBack).filter(Boolean);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// The first two fields of a note, by position: field names depend on the note type and on
|
|
31
|
+
// Anki's UI language ("Front"/"Back", "Przód"/"Tył", "Vorderseite"/"Rückseite"…).
|
|
32
|
+
export function toFrontBack(info) {
|
|
33
|
+
const fields = Object.values(info.fields ?? {}).sort((a, b) => a.order - b.order);
|
|
34
|
+
if (fields.length < 2) return null;
|
|
35
|
+
return { noteId: info.noteId, front: fields[0].value, back: fields[1].value };
|
|
36
|
+
}
|
package/src/cli.js
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { render } from "ink";
|
|
3
|
+
import React from "react";
|
|
4
|
+
import { parseArgs } from "node:util";
|
|
5
|
+
import { createAlerts } from "./alerts.js";
|
|
6
|
+
import { ensureProgress, snapshot } from "./progress.js";
|
|
7
|
+
import { BOX_INTERVALS_DAYS } from "./scheduler.js";
|
|
8
|
+
import { createSession } from "./session.js";
|
|
9
|
+
import { DEFAULTS, formatInterval, normalizeSettings } from "./settings.js";
|
|
10
|
+
import { loadSettingsRaw, loadState, patchSettings } from "./store.js";
|
|
11
|
+
import { App } from "./ui/App.js";
|
|
12
|
+
import { Preview } from "./ui/Preview.js";
|
|
13
|
+
import { loadWords } from "./words.js";
|
|
14
|
+
|
|
15
|
+
const DEFAULT_DECK = "English";
|
|
16
|
+
|
|
17
|
+
const HELP = `Dracosh: vocabulary quiz from your Anki deck (read-only)
|
|
18
|
+
|
|
19
|
+
Usage: dracosh [options]
|
|
20
|
+
|
|
21
|
+
--deck <name> Anki deck to take words from (default: ${DEFAULT_DECK})
|
|
22
|
+
--every <time> pause between questions: 30s, 10m, 1h (default: ${formatInterval(DEFAULTS.everyMs)})
|
|
23
|
+
--no-sound turn sound effects off
|
|
24
|
+
--volume <0-1> sound volume (default: ${DEFAULTS.volume})
|
|
25
|
+
--stats print progress and exit
|
|
26
|
+
--preview browse every animation and screen on made-up data (nothing is saved)
|
|
27
|
+
-h, --help show this help
|
|
28
|
+
|
|
29
|
+
Flags override your saved settings for this run only. Change the saved ones with /settings.
|
|
30
|
+
|
|
31
|
+
While running: Enter submits, "/" opens the command menu (/settings, /stats, /badges, /skip, /quit),
|
|
32
|
+
Esc quits (clears the line first if you typed something). Ctrl+C also works.
|
|
33
|
+
Between questions: Enter asks the next word right away, q quits.`;
|
|
34
|
+
|
|
35
|
+
function parseEvery(value) {
|
|
36
|
+
const match = /^(\d+(?:\.\d+)?)(s|m|h)$/.exec(value);
|
|
37
|
+
if (!match) throw new Error(`Invalid --every "${value}". Use e.g. 30s, 10m, 1h.`);
|
|
38
|
+
return Number(match[1]) * { s: 1000, m: 60_000, h: 3_600_000 }[match[2]];
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function parseVolume(value) {
|
|
42
|
+
const volume = Number(value);
|
|
43
|
+
if (!(volume >= 0 && volume <= 1)) throw new Error(`Invalid --volume "${value}". Use a number from 0 to 1.`);
|
|
44
|
+
return volume;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function printStats(state, settings) {
|
|
48
|
+
ensureProgress(state);
|
|
49
|
+
const stats = snapshot(state, { goal: settings.dailyGoal });
|
|
50
|
+
const { streak, today } = stats;
|
|
51
|
+
console.log(`Streak ${streak.days} days (best ${streak.best}) · ${streak.freezes} freeze(s) in stock`);
|
|
52
|
+
console.log(`Today ${today.correct}/${stats.goal} correct${today.goalMet ? " ✓ goal reached" : ""}`);
|
|
53
|
+
console.log(`Badges ${stats.badges.filter((b) => b.unlockedOn).length}/${stats.badges.length} · ${stats.mastered} cards mastered · companion: ${stats.companion.name}`);
|
|
54
|
+
|
|
55
|
+
const entries = Object.values(state.items);
|
|
56
|
+
if (!entries.length) return;
|
|
57
|
+
const perBox = BOX_INTERVALS_DAYS.map((days, i) => `box ${i + 1} (${days}d): ${entries.filter((e) => e.box === i + 1).length}`);
|
|
58
|
+
const correct = entries.reduce((sum, e) => sum + e.correct, 0);
|
|
59
|
+
const total = entries.reduce((sum, e) => sum + e.seen, 0);
|
|
60
|
+
console.log(`${entries.length} cards practiced, ${correct}/${total} correct (${Math.round((correct / total) * 100)}%)`);
|
|
61
|
+
console.log(perBox.join(" "));
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
async function main() {
|
|
65
|
+
const { values } = parseArgs({
|
|
66
|
+
options: {
|
|
67
|
+
deck: { type: "string", default: DEFAULT_DECK },
|
|
68
|
+
every: { type: "string" },
|
|
69
|
+
volume: { type: "string" },
|
|
70
|
+
"no-sound": { type: "boolean", default: false },
|
|
71
|
+
stats: { type: "boolean", default: false },
|
|
72
|
+
preview: { type: "boolean", default: false },
|
|
73
|
+
help: { type: "boolean", short: "h", default: false }
|
|
74
|
+
}
|
|
75
|
+
});
|
|
76
|
+
if (values.help) return console.log(HELP);
|
|
77
|
+
|
|
78
|
+
const saved = normalizeSettings(await loadSettingsRaw());
|
|
79
|
+
const settings = {
|
|
80
|
+
...saved,
|
|
81
|
+
...(values.every && { everyMs: parseEvery(values.every) }),
|
|
82
|
+
...(values.volume && { volume: parseVolume(values.volume) }),
|
|
83
|
+
...(values["no-sound"] && { sound: false })
|
|
84
|
+
};
|
|
85
|
+
|
|
86
|
+
if (values.preview) {
|
|
87
|
+
if (!process.stdin.isTTY) throw new Error("dracosh needs an interactive terminal.");
|
|
88
|
+
const alerts = createAlerts({ sound: settings.sound, volume: settings.volume });
|
|
89
|
+
return render(React.createElement(Preview, { alerts })).waitUntilExit();
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const state = await loadState();
|
|
93
|
+
if (values.stats) return printStats(state, settings);
|
|
94
|
+
if (!process.stdin.isTTY) throw new Error("dracosh needs an interactive terminal.");
|
|
95
|
+
|
|
96
|
+
// fail fast (and readably) when there is nothing to quiz on, before taking over the screen
|
|
97
|
+
const { words } = await loadWords(values.deck);
|
|
98
|
+
if (!words.length) throw new Error(`No translation cards found in deck "${values.deck}".`);
|
|
99
|
+
|
|
100
|
+
let current = settings; // the session reads settings live, so /settings changes apply immediately
|
|
101
|
+
const session = createSession({ loadWords: () => loadWords(values.deck), state, getSettings: () => current });
|
|
102
|
+
const alerts = createAlerts({ sound: settings.sound, volume: settings.volume });
|
|
103
|
+
const persistSettings = async (patch) => {
|
|
104
|
+
current = { ...current, ...patch };
|
|
105
|
+
await patchSettings(patch);
|
|
106
|
+
};
|
|
107
|
+
|
|
108
|
+
// the session summary screen stays on screen after exit, so nothing more to print here
|
|
109
|
+
const app = render(React.createElement(App, { session, deck: values.deck, initialSettings: settings, alerts, persistSettings }));
|
|
110
|
+
await app.waitUntilExit();
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
main().catch((err) => {
|
|
114
|
+
console.error(err.message);
|
|
115
|
+
process.exit(1);
|
|
116
|
+
});
|
package/src/commands.js
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
// `only` limits a command to one phase: "asking" (a question is open) or "waiting" (between questions)
|
|
2
|
+
export const COMMANDS = [
|
|
3
|
+
{ name: "/hint", only: "asking", hint: "Reveal another letter (the card won't climb a box)" },
|
|
4
|
+
{ name: "/settings", hint: "Interval, quiet hours, sound, goal, tips" },
|
|
5
|
+
{ name: "/stats", hint: "Streak, month calendar and badges summary" },
|
|
6
|
+
{ name: "/badges", hint: "All badges and what unlocks them" },
|
|
7
|
+
{ name: "/companion", hint: "Your companion's forms and moods" },
|
|
8
|
+
{ name: "/tip", aliases: ["/grammar"], hint: "Grammar tip: show a random one" },
|
|
9
|
+
{ name: "/missed", hint: "Words you got wrong today" },
|
|
10
|
+
{ name: "/snooze", hint: "Pause questions: /snooze 30m, 2h, off" },
|
|
11
|
+
{ name: "/vacation", hint: "Days off that keep your streak: 7, 24.12 2.01, off" },
|
|
12
|
+
{ name: "/skip", only: "asking", hint: "Skip this word" },
|
|
13
|
+
{ name: "/quit", hint: "Exit Dracosh" }
|
|
14
|
+
];
|
|
15
|
+
|
|
16
|
+
const CORRECT = { name: "/correct", hint: "Count my last answer as correct" };
|
|
17
|
+
|
|
18
|
+
// What the "/" menu offers right now (phase-only commands, and /correct right after a wrong answer)
|
|
19
|
+
export function commandsFor({ phase, canOverrule = false }) {
|
|
20
|
+
const base = COMMANDS.filter((command) => !command.only || command.only === phase);
|
|
21
|
+
return canOverrule ? [CORRECT, ...base] : base;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// "/s" narrows to commands starting with it (aliases count: "/gram" finds /tip). Arguments are ignored: "/snooze 30m" matches /snooze.
|
|
25
|
+
export function matchCommands(value, commands = COMMANDS) {
|
|
26
|
+
const query = value.trim().split(/\s+/)[0].toLowerCase();
|
|
27
|
+
return commands.filter((command) => command.name.startsWith(query) || command.aliases?.some((alias) => alias.startsWith(query)));
|
|
28
|
+
}
|
package/src/dates.js
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
// Calendar days as local "YYYY-MM-DD" keys. Noon avoids DST edge cases when doing day arithmetic.
|
|
2
|
+
export const dayKey = (now) => new Date(now).toLocaleDateString("sv");
|
|
3
|
+
|
|
4
|
+
const parse = (key) => new Date(`${key}T12:00:00`);
|
|
5
|
+
|
|
6
|
+
export const daysBetween = (from, to) => Math.round((parse(to) - parse(from)) / 86_400_000);
|
|
7
|
+
|
|
8
|
+
export function addDays(key, n) {
|
|
9
|
+
const date = parse(key);
|
|
10
|
+
date.setDate(date.getDate() + n);
|
|
11
|
+
return dayKey(date);
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
// Monday of the week containing `key`
|
|
15
|
+
export const weekStart = (key) => addDays(key, -((parse(key).getDay() + 6) % 7));
|
package/src/demo.js
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
// A small built-in EN ↔ PL word set: used by the preview gallery, and a seed for the future demo deck.
|
|
2
|
+
export const DEMO_WORDS = [
|
|
3
|
+
{ noteId: 1, word: "dragon", translations: ["smok"], example: "The dragon guarded its gold." },
|
|
4
|
+
{ noteId: 2, word: "egg", translations: ["jajko", "jajo"], example: "The egg began to crack." },
|
|
5
|
+
{ noteId: 3, word: "to hatch", translations: ["wykluć się"], example: "The chicks will hatch tomorrow." },
|
|
6
|
+
{ noteId: 4, word: "genuine", translations: ["autentyczny", "szczery"], example: "Her apology felt genuine." },
|
|
7
|
+
{ noteId: 5, word: "software", translations: ["oprogramowanie"], example: "The software update fixed the bug." },
|
|
8
|
+
{ noteId: 6, word: "to grow", translations: ["rosnąć"], example: "Plants grow towards the light." },
|
|
9
|
+
{ noteId: 7, word: "fire", translations: ["ogień"], example: "Dragons breathe fire." },
|
|
10
|
+
{ noteId: 8, word: "streak", translations: ["seria", "passa"], example: "She kept her streak for a month." }
|
|
11
|
+
];
|
package/src/diff.js
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
// Character diff of your answer against the expected one, for the "you wrote" line after a miss.
|
|
2
|
+
// Comparison is as forgiving as the judge: case, Polish diacritics and ł are ignored per character.
|
|
3
|
+
|
|
4
|
+
const foldChar = (ch) =>
|
|
5
|
+
ch
|
|
6
|
+
.toLowerCase()
|
|
7
|
+
.replace(/ł/g, "l")
|
|
8
|
+
.normalize("NFD")
|
|
9
|
+
.replace(/[̀-ͯ]/g, "");
|
|
10
|
+
|
|
11
|
+
// → [{ ch, ok }] for every character of `given`: ok = this character lines up with `target`.
|
|
12
|
+
// Alignment comes from a Levenshtein backtrace, so a single missing or extra letter doesn't
|
|
13
|
+
// mark the whole rest of the word wrong.
|
|
14
|
+
export function diffChars(given, target) {
|
|
15
|
+
const a = [...given].map(foldChar);
|
|
16
|
+
const b = [...target].map(foldChar);
|
|
17
|
+
const rows = a.length + 1;
|
|
18
|
+
const cols = b.length + 1;
|
|
19
|
+
const d = Array.from({ length: rows }, (_, i) => new Array(cols).fill(0));
|
|
20
|
+
for (let i = 0; i < rows; i++) d[i][0] = i;
|
|
21
|
+
for (let j = 0; j < cols; j++) d[0][j] = j;
|
|
22
|
+
for (let i = 1; i < rows; i++) {
|
|
23
|
+
for (let j = 1; j < cols; j++) {
|
|
24
|
+
const cost = a[i - 1] === b[j - 1] ? 0 : 1;
|
|
25
|
+
d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// walk back, preferring matches; deletions in `target` don't produce a character of `given`
|
|
30
|
+
const marks = new Array(a.length).fill(false);
|
|
31
|
+
let i = a.length;
|
|
32
|
+
let j = b.length;
|
|
33
|
+
while (i > 0 || j > 0) {
|
|
34
|
+
if (i > 0 && j > 0 && d[i][j] === d[i - 1][j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1)) {
|
|
35
|
+
marks[i - 1] = a[i - 1] === b[j - 1];
|
|
36
|
+
i -= 1;
|
|
37
|
+
j -= 1;
|
|
38
|
+
} else if (i > 0 && d[i][j] === d[i - 1][j] + 1) {
|
|
39
|
+
marks[i - 1] = false; // extra character you typed
|
|
40
|
+
i -= 1;
|
|
41
|
+
} else {
|
|
42
|
+
j -= 1; // character you missed: nothing of yours to mark
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
return [...given].map((ch, k) => ({ ch, ok: marks[k] }));
|
|
46
|
+
}
|
package/src/hint.js
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
const isLetter = (ch) => /\p{L}/u.test(ch);
|
|
2
|
+
|
|
3
|
+
// The answer to hint at: the shortest of the accepted ones (the easiest to recall).
|
|
4
|
+
export const hintTarget = (expected) => [...expected].sort((a, b) => a.length - b.length)[0];
|
|
5
|
+
|
|
6
|
+
// "fine-tuned" at level 2 → "f i _ _ - _ _ _ _ _". Never reveals the last letter, so a hint is never the answer.
|
|
7
|
+
export function makeHint(answer, level) {
|
|
8
|
+
const letters = [...answer].filter(isLetter).length;
|
|
9
|
+
const reveal = Math.min(level, Math.max(letters - 1, 0));
|
|
10
|
+
let shown = 0;
|
|
11
|
+
return [...answer].map((ch) => (isLetter(ch) ? (shown++ < reveal ? ch : "_") : ch)).join(" ");
|
|
12
|
+
}
|
package/src/judge.js
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
// Typos are forgiven only on longer answers: on short words one edit often makes a different word
|
|
2
|
+
const TYPO_MIN_LENGTH = 6;
|
|
3
|
+
|
|
4
|
+
// lowercase, strip diacritics (ł doesn't decompose, so it is mapped by hand), drop punctuation
|
|
5
|
+
export function normalize(s) {
|
|
6
|
+
return s
|
|
7
|
+
.toLowerCase()
|
|
8
|
+
.replace(/ł/g, "l")
|
|
9
|
+
.normalize("NFD")
|
|
10
|
+
.replace(/[̀-ͯ]/g, "")
|
|
11
|
+
.replace(/[^\p{L}\p{N}\s]/gu, "")
|
|
12
|
+
.replace(/\s+/g, " ")
|
|
13
|
+
.trim();
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
// Damerau-Levenshtein (optimal string alignment): a swap of two neighbours counts as one edit
|
|
17
|
+
export function editDistance(a, b) {
|
|
18
|
+
const rows = a.length + 1;
|
|
19
|
+
const cols = b.length + 1;
|
|
20
|
+
const d = Array.from({ length: rows }, (_, i) => [i, ...new Array(cols - 1).fill(0)]);
|
|
21
|
+
for (let j = 0; j < cols; j++) d[0][j] = j;
|
|
22
|
+
for (let i = 1; i < rows; i++) {
|
|
23
|
+
for (let j = 1; j < cols; j++) {
|
|
24
|
+
const cost = a[i - 1] === b[j - 1] ? 0 : 1;
|
|
25
|
+
d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
|
|
26
|
+
if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
|
|
27
|
+
d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
return d[rows - 1][cols - 1];
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// The candidate the answer came closest to (fewest edits after normalizing): what a miss is diffed against
|
|
35
|
+
export function closestCandidate(answer, candidates) {
|
|
36
|
+
const given = normalize(answer);
|
|
37
|
+
let best = candidates[0];
|
|
38
|
+
let bestDistance = Infinity;
|
|
39
|
+
for (const candidate of candidates) {
|
|
40
|
+
const distance = editDistance(given, normalize(candidate));
|
|
41
|
+
if (distance < bestDistance) {
|
|
42
|
+
bestDistance = distance;
|
|
43
|
+
best = candidate;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
return best;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// → "exact" | "typo" | "wrong"; accepts any one of the candidate answers
|
|
50
|
+
export function judge(answer, candidates) {
|
|
51
|
+
const given = normalize(answer);
|
|
52
|
+
if (!given) return "wrong";
|
|
53
|
+
const targets = candidates.map(normalize).filter(Boolean);
|
|
54
|
+
if (targets.includes(given)) return "exact";
|
|
55
|
+
const close = targets.some((t) => t.length >= TYPO_MIN_LENGTH && editDistance(given, t) <= 1);
|
|
56
|
+
return close ? "typo" : "wrong";
|
|
57
|
+
}
|
package/src/parse.js
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
const ENTITIES = { " ": " ", "&": "&", "<": "<", ">": ">", """: '"', "'": "'" };
|
|
2
|
+
|
|
3
|
+
const decode = (s) => s.replace(/&(?:nbsp|amp|lt|gt|quot|#39);/g, (m) => ENTITIES[m]);
|
|
4
|
+
|
|
5
|
+
// block-level closers and <br> become line breaks, every other tag disappears
|
|
6
|
+
function htmlToLines(html) {
|
|
7
|
+
return decode(
|
|
8
|
+
html
|
|
9
|
+
.replace(/<br\s*\/?>|<\/(?:div|p|span)>/gi, "\n")
|
|
10
|
+
.replace(/<[^>]*>/g, "")
|
|
11
|
+
)
|
|
12
|
+
.split("\n")
|
|
13
|
+
.map((l) => l.trim())
|
|
14
|
+
.filter(Boolean);
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const unquote = (s) => s.replace(/^["“”]+|["“”]+$/g, "").trim();
|
|
18
|
+
|
|
19
|
+
// "define" cards (uppercase domain tag + English definition) have no translation to quiz on
|
|
20
|
+
const isDefineCard = (backHtml) => /text-transform:\s*uppercase/i.test(backHtml);
|
|
21
|
+
|
|
22
|
+
// → { noteId, word, translations[], example } or null when the card isn't a translation card
|
|
23
|
+
export function parseNote({ noteId, front, back }) {
|
|
24
|
+
if (isDefineCard(back)) return null;
|
|
25
|
+
const word = htmlToLines(front).join(" ");
|
|
26
|
+
const [first, ...rest] = htmlToLines(back);
|
|
27
|
+
if (!word || !first) return null;
|
|
28
|
+
const translations = first.split(/[,;]/).map((t) => t.trim()).filter(Boolean);
|
|
29
|
+
if (!translations.length) return null;
|
|
30
|
+
return { noteId, word, translations, example: rest.length ? unquote(rest.join(" ")) : "" };
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function parseNotes(notes) {
|
|
34
|
+
const words = [];
|
|
35
|
+
let skipped = 0;
|
|
36
|
+
for (const note of notes) {
|
|
37
|
+
const parsed = parseNote(note);
|
|
38
|
+
if (parsed) words.push(parsed);
|
|
39
|
+
else skipped += 1;
|
|
40
|
+
}
|
|
41
|
+
return { words, skipped };
|
|
42
|
+
}
|