dracosh 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/ui/AddCard.js CHANGED
@@ -2,7 +2,10 @@ import { Fragment, useEffect, useRef, useState } from "react";
2
2
  import { Box, useInput } from "ink";
3
3
  import { MAX_DECK_NAME, typedSides } from "../library.js";
4
4
  import { blankGap, formatLine, gapsOf, parseBack, parseLine, plainFront } from "../cardline.js";
5
- import { normalize } from "../judge.js";
5
+ import { readCardList } from "../cardlist.js";
6
+ import { frontKey } from "../judge.js";
7
+ import { isKnown, languageName } from "../language.js";
8
+ import { LanguagePicker, pairText } from "./Languages.js";
6
9
  import { AnswerInput } from "./AnswerInput.js";
7
10
  import { Choice, choiceHints } from "./Choice.js";
8
11
  import { t } from "../i18n.js";
@@ -29,23 +32,13 @@ function startsWithSlash(fields, directions) {
29
32
  return typedSides({ directions: directions ?? "forward" }).some((side) => [fields[side]].flat().some(slash));
30
33
  }
31
34
 
32
- // A pasted list, one card per line: a tab splits the lines when every one of them has one (Anki and
33
- // Quizlet exports), " = " otherwise. Lines that can't be added as they are say why.
34
- // A list written with dashes ("apple - jabłko") is taken as it is when most lines have one and none
35
- // has " = "; each line splits on a tab, or on its first dash
36
- const DASHES = [" - ", " – ", " — "];
37
- function separatorFor(lines) {
38
- const dashed = !lines.some((line) => line.includes(" = ")) && lines.filter((line) => DASHES.some((dash) => line.includes(dash))).length * 2 >= lines.length;
39
- return (line) => (line.includes("\t") ? "\t" : dashed ? (DASHES.map((dash) => [dash, line.indexOf(dash)]).filter(([, at]) => at >= 0).sort((a, b) => a[1] - b[1])[0]?.[0] ?? " = ") : " = ");
40
- }
41
-
42
- function readPaste(lines, existing, directions) {
43
- const separatorOf = separatorFor(lines);
44
- return lines.map((line) => {
45
- const separator = separatorOf(line);
46
- const fields = parseLine(line, { separator });
47
- const issue = issueOf(fields, directions, existing.has(normalize(fields.front)));
48
- return { line: separator === " = " ? line.trim() : formatLine(fields), fields, issue, dropped: false };
35
+ // A pasted list, read the way `dracosh import` reads a file (src/cardlist.js): Dracosh lines, rows
36
+ // copied from a spreadsheet or an Anki or Quizlet export, or a list with dashes. Lines that can't be
37
+ // added as they are say why. A row that isn't a Dracosh line is shown as one, for fixing.
38
+ function readPaste(list, existing, directions) {
39
+ return list.items.map(({ source, fields }) => {
40
+ const issue = issueOf(fields, directions, existing.has(frontKey(fields.front)));
41
+ return { line: list.format === "lines" && !source.includes("\t") ? source : formatLine(fields), fields, issue, dropped: false };
49
42
  });
50
43
  }
51
44
 
@@ -57,7 +50,7 @@ function withRepeats(items) {
57
50
  const seen = new Set();
58
51
  return items.map((item) => {
59
52
  if (item.dropped || item.issue) return item;
60
- const key = normalize(item.fields.front);
53
+ const key = frontKey(item.fields.front);
61
54
  if (seen.has(key)) return { ...item, issue: "twice" };
62
55
  seen.add(key);
63
56
  return item;
@@ -144,13 +137,32 @@ export function AddCard({ current, actions, onDone, startNew = false }) {
144
137
  if (deck.isNew && !card.cloze) {
145
138
  setDirection(0);
146
139
  setSample(card);
140
+ setLangs(null);
141
+ actions.languagesOf(deck.name).then((found) => {
142
+ setLangs(found);
143
+ shownPair.current = pairText(found);
144
+ }, () => {});
147
145
  picking.current = false;
148
146
  typedAhead.current = "";
149
147
  return setStep("direction");
150
148
  }
151
149
  setStep("line");
150
+ noticeLanguages();
152
151
  };
153
152
 
153
+ // As cards come in, the guess at the deck's languages firms up: a new guess is said once, so a
154
+ // wrong one doesn't go unnoticed
155
+ const shownPair = useRef(null);
156
+ function noticeLanguages() {
157
+ actions.languagesOf(deck?.name ?? "").then((found) => {
158
+ const pair = pairText(found);
159
+ const tells = isKnown(found.front) && isKnown(found.back);
160
+ // it stays under the field until the next card is saved
161
+ setLanguageNote(found.guessed && tells && shownPair.current !== pair ? pair : "");
162
+ if (tells) shownPair.current = pair;
163
+ }, () => {});
164
+ }
165
+
154
166
  async function save(fields) {
155
167
  if (busy.current) return;
156
168
  busy.current = true;
@@ -209,6 +221,7 @@ export function AddCard({ current, actions, onDone, startNew = false }) {
209
221
  return save({ ...draft, back, example: example || draft.example });
210
222
  }
211
223
  if (step === "fix") {
224
+ if (!value) return setStep("review"); // nothing typed: the line stays as it was
212
225
  const fields = parseLine(value);
213
226
  return actions
214
227
  .existingCard(deck.name, fields.front)
@@ -253,6 +266,7 @@ export function AddCard({ current, actions, onDone, startNew = false }) {
253
266
  function pickDeck(index) {
254
267
  if (index === decks.length) return setStep("deck");
255
268
  setDeck({ name: decks[index].name, directions: decks[index].directions, isNew: false });
269
+ actions.languagesOf(decks[index].name).then((found) => (shownPair.current = pairText(found)), () => {});
256
270
  clearField();
257
271
  setStep("line");
258
272
  }
@@ -261,6 +275,10 @@ export function AddCard({ current, actions, onDone, startNew = false }) {
261
275
  // choice and go into the field, so nothing typed is lost
262
276
  // Typing the next card right away keeps option 1: the keys wait in `typedAhead` until the field is back.
263
277
  // `picking` stays set for the rest of the step, so a key that lands while the pick saves can't pick again.
278
+ const [langs, setLangs] = useState(null); // the new deck's languages, as guessed from its first card
279
+ const [languageNote, setLanguageNote] = useState(""); // a new guess at the deck's languages
280
+ const writes = useRef(Promise.resolve()); // library writes one after another, so none overwrites another
281
+ const inTurn = (write) => (writes.current = writes.current.catch(() => {}).then(write));
264
282
  const typedAhead = useRef("");
265
283
  const picking = useRef(false);
266
284
  const pickedByChoice = useRef(false);
@@ -270,14 +288,14 @@ export function AddCard({ current, actions, onDone, startNew = false }) {
270
288
  picking.current = true;
271
289
  const chosen = ["forward", "backward", "both"][index];
272
290
  try {
273
- await actions.setDirections(deck.name, chosen);
291
+ await inTurn(() => actions.setDirections(deck.name, chosen));
274
292
  setDeck((d) => ({ ...d, directions: chosen, isNew: false }));
275
293
  setMessage(t("add.directionSet", { how: askedAs(sample, chosen) }));
276
294
  } catch (err) {
277
295
  setError(err.message);
278
296
  }
279
297
  const lines = typedAhead.current.split(/\r\n|\r|\n/).filter((line) => line.trim());
280
- if (lines.length > 1) return void openPaste(lines); // a list pasted in: the review, as on the field
298
+ if (lines.length > 1) return void openPaste(typedAhead.current); // a list pasted in: the review, as on the field
281
299
  // `ahead`: the field starts with typedAhead as it is when the field is drawn
282
300
  setField((f) => ({ key: f.key + 1, initial: "", ahead: true }));
283
301
  setDuplicate(null);
@@ -292,11 +310,12 @@ export function AddCard({ current, actions, onDone, startNew = false }) {
292
310
  }, [field]);
293
311
 
294
312
  // a pasted list: each line checked against the deck before anything is saved
295
- async function openPaste(lines) {
296
- const separatorOf = separatorFor(lines);
297
- const fronts = await Promise.all(lines.map((line) => actions.existingCard(deck.name, parseLine(line, { separator: separatorOf(line) }).front).catch(() => null)));
298
- const existing = new Set(fronts.filter(Boolean).map((card) => normalize(card.front)));
299
- setPasted({ items: readPaste(lines, existing, deck.isNew ? null : deck.directions), selected: 0, confirm: false, total: lines.length });
313
+ async function openPaste(text) {
314
+ const list = readCardList(text, { comments: false }); // a pasted "#tag = hashtag" is a card
315
+ if (!list.items.length) return setStep("line");
316
+ const fronts = await Promise.all(list.items.map((item) => actions.existingCard(deck.name, item.fields.front).catch(() => null)));
317
+ const existing = new Set(fronts.filter(Boolean).map((card) => frontKey(card.front)));
318
+ setPasted({ items: readPaste(list, existing, deck.isNew ? null : deck.directions), selected: 0, confirm: false, total: list.items.length });
300
319
  setError("");
301
320
  setMessage("");
302
321
  setStep("review");
@@ -323,6 +342,7 @@ export function AddCard({ current, actions, onDone, startNew = false }) {
323
342
  useInput(
324
343
  (input, key) => {
325
344
  if (pickedByChoice.current) return void (pickedByChoice.current = false);
345
+ if (key.rightArrow && langs && !picking.current) return setStep("languages");
326
346
  if (picking.current && (key.backspace || key.delete)) return void (typedAhead.current = typedAhead.current.slice(0, -1));
327
347
  if (!input || key.ctrl || key.meta || key.tab || key.escape || key.return) return;
328
348
  if (!picking.current && /^[1-3]$/.test(input)) return; // Choice's own key
@@ -355,6 +375,19 @@ export function AddCard({ current, actions, onDone, startNew = false }) {
355
375
  { isActive: step === "review" }
356
376
  );
357
377
 
378
+ async function saveLanguages(languages) {
379
+ setStep("direction");
380
+ try {
381
+ const saved = await inTurn(() => actions.setLanguages(deck.name, languages));
382
+ setLangs(saved);
383
+ shownPair.current = pairText(saved);
384
+ } catch (err) {
385
+ setError(err.message);
386
+ }
387
+ }
388
+
389
+ if (step === "languages") return html`<${LanguagePicker} deck=${deck.name} sample=${sample} languages=${langs} learning=${langs.learning} home=${langs.home} onDone=${saveLanguages} onCancel=${() => setStep("direction")} />`;
390
+
358
391
  const title =
359
392
  step === "pick" ? t("add.titlePick") : step === "deck" ? t(decks.length ? "add.titleNew" : "add.titleFirst") : step === "review" || step === "fix" ? t("add.paste.title", { deck: deck.name }) : t("add.titleCard", { deck: deck?.name ?? "" });
360
393
  const fieldLabel = step === "deck" ? "deck" : step === "back" ? "back" : step === "line" || step === "fix" ? "line" : null;
@@ -378,6 +411,7 @@ export function AddCard({ current, actions, onDone, startNew = false }) {
378
411
  <//>
379
412
  `}
380
413
  ${message && html`<${Box} marginTop=${1}><${Text} color=${theme.good}>${message}<//><//>`}
414
+ ${languageNote && step === "line" && html`<${Text} dimColor>${t("add.languagesNow", { pair: languageNote })}<//>`}
381
415
  ${step === "back" && draft && html`<${Box} marginTop=${1}><${Text} dimColor>${draft.front} =<//><//>`}
382
416
  ${fieldLabel &&
383
417
  html`
@@ -436,7 +470,10 @@ export function AddCard({ current, actions, onDone, startNew = false }) {
436
470
  }}
437
471
  />
438
472
  <//>
439
- <${Box} marginTop=${1}><${Text} dimColor>${t("add.directionLater")}<//><//>
473
+ ${langs && html`<${Box} marginTop=${1}><${Text} dimColor>${isKnown(langs.front) || isKnown(langs.back) ? t("add.languagesLine", { pair: pairText(langs) }) : t("add.languagesSoon")}<//><//>`}
474
+ ${langs?.learning && html`<${Text} color=${langs.learning.sure ? undefined : theme.warn} dimColor=${langs.learning.sure}>${t("add.learningLine", { language: languageName(langs.learning.lang) })}<//>`}
475
+ ${langs?.learning && !langs.learning.sure && html`<${Text} color=${theme.warn}>${t("add.learningGuess")}<//>`}
476
+ <${Box} marginTop=${langs ? 0 : 1}><${Text} dimColor>${t("add.directionLater")}<//><//>
440
477
  <//>
441
478
  `}
442
479
  ${(step === "review" || step === "fix") &&
@@ -27,7 +27,7 @@ const args = (value) => value.trim().split(/\s+/).slice(1).join(" ");
27
27
  // `commandOnly` is the between-questions variant: it starts at "/" and Esc or erasing the "/" closes it.
28
28
  // `plain` is a text field with no commands at all ("and/or" is just text there).
29
29
  // `onChange` hears every edit; `onRecall` is ↑ on an empty plain field (/add brings back the last card);
30
- // `onPaste` takes a paste of several lines (/add reviews them as cards), anything else is typed in.
30
+ // `onPaste` takes a paste of several lines, as it came (/add reviews them as cards); anything else is typed in.
31
31
  export function AnswerInput({ onSubmit, onCommand, onExit, onEdit, onCancel, onChange, onRecall, onPaste, commands = COMMANDS, initial = "", commandOnly = false, plain = false }) {
32
32
  const [value, setValue] = useState(initial);
33
33
  const [cursor, setCursor] = useState(initial.length);
@@ -47,8 +47,8 @@ export function AnswerInput({ onSubmit, onCommand, onExit, onEdit, onCancel, onC
47
47
  // pasted text arrives whole (bracketed paste); lines become spaces unless /add takes them as cards
48
48
  const paste = (text) => {
49
49
  const lines = /[\r\n]/.test(text) ? text.split(/\r\n|\r|\n/).filter((line) => line.trim()) : [text];
50
- if (onPaste && lines.length > 1) return onPaste(lines);
51
- const typed = lines.join(" ");
50
+ if (onPaste && lines.length > 1) return onPaste(text);
51
+ const typed = lines.join(" ").replace(/\t/g, " ");
52
52
  edit(value.slice(0, cursor) + typed + value.slice(cursor), cursor + typed.length);
53
53
  };
54
54
  usePaste(paste);
package/src/ui/App.js CHANGED
@@ -2,13 +2,15 @@ import { Fragment, useCallback, useEffect, useRef, useState } from "react";
2
2
  import { Box, useApp, useInput, useStdout } from "ink";
3
3
  import { commandsFor } from "../commands.js";
4
4
  import { accentMarks, diffChars } from "../diff.js";
5
+ import { ALMOST } from "../judge.js";
6
+ import { toSpeak } from "../session.js";
5
7
  import { AnswerInput } from "./AnswerInput.js";
6
8
  import { Header } from "./Header.js";
7
9
  import { setLanguage, t } from "../i18n.js";
8
10
  import { Bar, cellWidth, cutToWidth, html, KeyHints, Marked, Text, theme, Typewriter, usePanelWidth } from "./kit.js";
9
11
  import { hintTarget, makeHint } from "../hint.js";
10
12
  import { formatClock, inQuietHours, quietEnd } from "../quiet.js";
11
- import { startOfTomorrow } from "../scheduler.js";
13
+ import { NEW_PER_DAY, startOfTomorrow } from "../scheduler.js";
12
14
  import { formatDay } from "../vacation.js";
13
15
  import { dayKey } from "../dates.js";
14
16
  import { shouldShowTip } from "../tips.js";
@@ -42,6 +44,8 @@ const CHEER_STYLE = {
42
44
  combo: { icon: "»", color: theme.warn }
43
45
  };
44
46
 
47
+ const QUIET_NIGHT_UNTIL = 7; // o'clock: no "new card" sound before then when a day's cards come in
48
+
45
49
  function clock(ms) {
46
50
  const total = Math.max(0, Math.ceil(ms / 1000));
47
51
  return `${Math.floor(total / 60)}:${String(total % 60).padStart(2, "0")}`;
@@ -49,11 +53,12 @@ function clock(ms) {
49
53
 
50
54
  // your answer with every letter judged: green lined up with the expected word, underlined didn't
51
55
  function AnswerDiff({ given, closest }) {
52
- const parts = diffChars(given, closest);
56
+ const parts = diffChars(given, closest, { gaps: true });
57
+ if (parts.every((p) => p.ok)) return null; // the same letters after all: nothing to mark
53
58
  return html`
54
59
  <${Text}>
55
60
  <${Text} dimColor>${t("quiz.youWrote")}<//>
56
- ${parts.map((p, i) => html`<${Text} key=${i} color=${p.ok ? theme.good : theme.text} underline=${!p.ok}>${p.ch}<//>`)}
61
+ ${parts.map((p, i) => html`<${Text} key=${i} color=${p.missing ? theme.bad : p.ok ? theme.good : theme.text} underline=${!p.ok && !p.missing}>${p.ch}<//>`)}
57
62
  <//>
58
63
  `;
59
64
  }
@@ -75,7 +80,9 @@ function Verdict({ outcome, question }) {
75
80
  const showDiff = outcome.closest && outcome.given && !outcome.overruled && (wrong || outcome.result === "typo");
76
81
  return html`
77
82
  <${Box} flexDirection="column">
78
- <${Text} color=${wrong ? theme.bad : theme.good} bold>${wrong ? "✗" : "✓"} ${outcome.result === "accent" ? html`<${AccentedAnswers} expected=${question.expected} given=${outcome.given} closest=${outcome.closest} />` : question.expected.join(" / ")}${outcome.result === "typo" ? t("quiz.closeEnough") : ""}<//>
83
+ <${Text} color=${wrong ? theme.bad : theme.good} bold>${wrong ? "✗" : "✓"} ${outcome.result === "accent" || outcome.result === "umlaut" || outcome.result === "article-umlaut" ? html`<${AccentedAnswers} expected=${question.expected} given=${outcome.given} closest=${outcome.closest} />` : question.expected.join(" / ")}${outcome.result === "typo" ? t("quiz.closeEnough") : ""}<//>
84
+ ${ALMOST.includes(outcome.result) &&
85
+ html`<${Text} color=${theme.warn}>${t(`quiz.almost.${outcome.result}`)}${outcome.held ? ` ${t("quiz.almost.held", { now: t("quiz.almost.days", { count: outcome.held.days }), would: t("quiz.almost.days", { count: outcome.held.would }) })}` : ""}<//>`}
79
86
  ${showDiff && html`<${AnswerDiff} given=${outcome.given} closest=${outcome.closest} />`}
80
87
  ${question.word.example && html`<${Box} marginTop=${1}>${question.tour ? html`<${Marked} dimColor text=${question.word.example} />` : html`<${Text} dimColor italic>“${question.word.example}”<//>`}<//>`}
81
88
  ${(outcome.hinted || outcome.overruled) &&
@@ -143,7 +150,7 @@ function whenDue(at, now) {
143
150
  }
144
151
 
145
152
  // what the quiz shows when the deck has nothing to ask: no countdown, just the way on
146
- function EmptyDeck({ deck, tour, count, nextDue, dayDone, now, width }) {
153
+ function EmptyDeck({ deck, tour, count, nextDue, dayDone, heldNew = 0, now, width }) {
147
154
  const [title, next] = tour
148
155
  ? [t("quiz.empty.tourTitle"), t("quiz.empty.tourNext")]
149
156
  : !count
@@ -151,7 +158,7 @@ function EmptyDeck({ deck, tour, count, nextDue, dayDone, now, width }) {
151
158
  : nextDue >= startOfTomorrow(now) && !dayDone
152
159
  ? [t("quiz.empty.deckDoneTitle", { deck }), t("quiz.empty.deckDoneNext", { when: whenDue(nextDue, now) })]
153
160
  : nextDue >= startOfTomorrow(now)
154
- ? [t("quiz.empty.dayDoneTitle"), t("quiz.empty.dayDoneNext", { when: whenDue(nextDue, now) })]
161
+ ? [t("quiz.empty.dayDoneTitle"), t(heldNew > 0 ? "quiz.empty.dayDoneHeldNext" : "quiz.empty.dayDoneNext", { when: whenDue(nextDue, now) })]
155
162
  : [t("quiz.empty.laterTitle"), t("quiz.empty.laterNext", { when: whenDue(nextDue, now) })];
156
163
  return html`
157
164
  <${Box} flexDirection="column" width=${width}>
@@ -159,6 +166,7 @@ function EmptyDeck({ deck, tour, count, nextDue, dayDone, now, width }) {
159
166
  <${Box} flexDirection="column" borderStyle="round" borderTop=${false} borderColor=${theme.accent} paddingX=${2} paddingY=${1}>
160
167
  <${Text} bold>${title}<//>
161
168
  <${Text}>${next}<//>
169
+ ${!tour && heldNew > 0 && html`<${Box} marginTop=${1}><${Text} dimColor>${t("quiz.empty.newTomorrow", { count: heldNew, max: NEW_PER_DAY })}<//><//>`}
162
170
  <//>
163
171
  <//>
164
172
  `;
@@ -259,7 +267,7 @@ export function App({ session, deck: initialDeck, initialSettings, alerts, persi
259
267
  return waitForNext();
260
268
  }
261
269
  setQuestion(null);
262
- setEmpty({ tour: err.tour, count: err.count, nextDue: err.nextDue, dayDone: err.dayDone });
270
+ setEmpty({ tour: err.tour, count: err.count, nextDue: err.nextDue, dayDone: err.dayDone, heldNew: err.heldNew });
263
271
  setOutcome(err.cheers.length ? { result: "done", cheers: err.cheers } : null);
264
272
  if (err.cheers.length) celebrate({ result: "exact", cheers: err.cheers, combo: session.totals.combo });
265
273
  setPhase("empty");
@@ -279,7 +287,8 @@ export function App({ session, deck: initialDeck, initialSettings, alerts, persi
279
287
  // with nothing to practise, the quiz picks up again by itself once the next card is due
280
288
  useEffect(() => {
281
289
  if (phase !== "empty" || !empty?.nextDue || screen !== "quiz" || confirming || now < empty.nextDue || pauseEnd(now)) return;
282
- alerts.ask();
290
+ // a new day's cards are ready from midnight: they wait quietly till morning instead of chiming at night
291
+ if (new Date(now).getHours() >= QUIET_NIGHT_UNTIL) alerts.ask();
283
292
  ask();
284
293
  }, [now, phase, empty, screen, confirming, ask, alerts]);
285
294
 
@@ -396,7 +405,7 @@ export function App({ session, deck: initialDeck, initialSettings, alerts, persi
396
405
  if (snooze === "off") setSnoozeUntil(0);
397
406
  if (typeof snooze === "number") {
398
407
  setSnoozeUntil(Date.now() + snooze);
399
- return phase === "asking" ? setNotice(t("quiz.pausedUntilNotice", { time: formatClock(Date.now() + snooze) })) : undefined; // while waiting, the status line says it
408
+ return phase !== "waiting" ? setNotice(t("quiz.pausedUntilNotice", { time: formatClock(Date.now() + snooze) })) : undefined; // while waiting, the status line says it
400
409
  }
401
410
  const paused = list && snoozeRef.current > Date.now() ? t("quiz.pausedUntilList", { time: formatClock(snoozeRef.current) }) : "";
402
411
  setNotice(paused + message);
@@ -431,7 +440,7 @@ export function App({ session, deck: initialDeck, initialSettings, alerts, persi
431
440
  const next = { ...previous, ...patch };
432
441
  settingsRef.current = next;
433
442
  setSettings(next);
434
- alerts.configure({ sound: next.sound, volume: next.volume });
443
+ alerts.configure({ sound: next.sound, volume: next.volume, speak: next.speak });
435
444
  persistSettings(patch).catch(() => {});
436
445
  if (patch.everyMs && phase === "waiting") setNextAt((at) => at - previous.everyMs + patch.everyMs);
437
446
  if (patch.rhythm) {
@@ -469,11 +478,19 @@ export function App({ session, deck: initialDeck, initialSettings, alerts, persi
469
478
  if (!text) {
470
479
  if (Date.now() - shownAt.current < SETTLE_MS) return;
471
480
  session.reveal(question);
481
+ say(question);
472
482
  shownAt.current = Date.now();
473
483
  setNudge(false);
474
484
  return setPhase("grading");
475
485
  }
476
- await settle(() => session.answer(question, text, { hinted: hintLevel > 0 }));
486
+ const result = await settle(() => session.answer(question, text, { hinted: hintLevel > 0 }));
487
+ if (result) say(question, result.closest);
488
+ }
489
+
490
+ // pronunciation (/settings), once the answer is out
491
+ function say(q, answer) {
492
+ const spoken = toSpeak(q, answer);
493
+ if (spoken) alerts.speak(spoken.text, spoken.lang);
477
494
  }
478
495
 
479
496
  const gradeSelf = (knew) => settle(() => session.selfGrade(question, knew, { hinted: hintLevel > 0 }));
@@ -491,8 +508,10 @@ export function App({ session, deck: initialDeck, initialSettings, alerts, persi
491
508
  if (length !== null && sessionDone.current === length) setNotice(t("quiz.sessionDone", { count: length }));
492
509
  setOutcome(result);
493
510
  celebrate(result);
511
+ return result;
494
512
  } catch (err) {
495
513
  setProblem(t("quiz.saveFailed", { error: err.message }));
514
+ return null;
496
515
  } finally {
497
516
  busy.current = false;
498
517
  waitForNext(nextDue);
@@ -532,6 +551,7 @@ export function App({ session, deck: initialDeck, initialSettings, alerts, persi
532
551
  setScreen("quiz");
533
552
  if (removed.length) session.forget(removed).catch(() => {});
534
553
  if (stale.length) session.forgetKeys(stale).catch(() => {});
554
+ if (added) session.workAdded().catch(() => {});
535
555
  const switching = started && (removed.length || phase === "empty" || addNew);
536
556
  if (switching) switchDeck(started);
537
557
  else if (phase === "empty" && added) ask();
@@ -585,8 +605,9 @@ export function App({ session, deck: initialDeck, initialSettings, alerts, persi
585
605
  ${screen === "add" && html`<${AddCard} current=${deck} actions=${library} onDone=${addDone} startNew=${addNew} />`}
586
606
  ${screen === "decks" && html`<${Decks} current=${deck} actions=${library} onDirections=${async (cardIds, directions) => {
587
607
  await session.setDirections(cardIds, directions);
608
+ await session.workAdded();
588
609
  if (phase === "asking" && question && cardIds.includes(question.word.noteId)) ask(); // the open card follows the new way at once
589
- }} onPick=${switchDeck} onNew=${() => (setAddNew(true), setScreen("add"))} onClose=${() => setScreen("quiz")} />`}
610
+ }} onLanguages=${(name) => name === deck && phase === "asking" && ask()} onPick=${switchDeck} onNew=${() => (setAddNew(true), setScreen("add"))} onClose=${() => setScreen("quiz")} />`}
590
611
  ${!["settings", "reset", "add", "decks"].includes(screen) &&
591
612
  html`
592
613
  <${Fragment}>
@@ -40,7 +40,7 @@ export function BadgeUnlock({ id, name, desc, delay = 0, sound = badgeSound(0),
40
40
  const sparks = frame < SPARKS_UNTIL ? ` ${Array.from({ length: 3 }, (_, i) => SPARKS[(frame + i) % SPARKS.length]).join(" ")}` : "";
41
41
 
42
42
  return html`
43
- <${Box}>
43
+ <${Text}>
44
44
  <${Text} color=${color}>✦ <//>
45
45
  <${Text} color=${theme.warn}>${t("badgeUnlock.label")}<//>
46
46
  <${Text} bold color=${color}>${name}<//>
package/src/ui/Decks.js CHANGED
@@ -1,20 +1,25 @@
1
- import { Fragment, useEffect, useState } from "react";
1
+ import { Fragment, useEffect, useRef, useState } from "react";
2
2
  import { Box, useInput } from "ink";
3
3
  import { t } from "../i18n.js";
4
4
  import { Choice, choiceHints } from "./Choice.js";
5
+ import { LanguagePicker, pairText } from "./Languages.js";
6
+ import { isKnown, languageName } from "../language.js";
5
7
  import { cutToWidth, html, KeyHints, Text, theme, usePanelWidth } from "./kit.js";
6
8
 
7
9
  const DIRECTIONS = ["forward", "backward", "both"];
8
10
 
9
11
  // /decks: your decks with their card counts; Enter quizzes the chosen one from now on, and
10
- // "+ New deck" starts one (`onNew`). → on a deck of yours: which way it's asked. Renaming and deleting
11
- // decks come later.
12
- export function Decks({ current, actions, onPick, onNew, onClose, onDirections }) {
12
+ // "+ New deck" starts one (`onNew`). → on a deck of yours: which way it's asked and its languages.
13
+ // Renaming and deleting decks come later.
14
+ export function Decks({ current, actions, onPick, onNew, onClose, onDirections, onLanguages }) {
13
15
  const panel = usePanelWidth();
14
16
  const [decks, setDecks] = useState(null);
15
17
  const [picked, setPicked] = useState(0);
16
18
  const [error, setError] = useState("");
19
+ const [menu, setMenu] = useState(null); // { deck, selected }: a deck's settings
17
20
  const [setting, setSetting] = useState(null); // { deck, selected }: the direction being picked
21
+ const [naming, setNaming] = useState(null); // the deck whose languages are being picked
22
+ const saving = useRef(false);
18
23
  const [message, setMessage] = useState("");
19
24
 
20
25
  useEffect(() => {
@@ -30,9 +35,15 @@ export function Decks({ current, actions, onPick, onNew, onClose, onDirections }
30
35
  useInput((input, key) => {
31
36
  if (!decks?.length && (key.escape || input === "q")) onClose();
32
37
  const deck = decks?.[picked];
33
- if (key.rightArrow && !setting && deck && !deck.tour) {
38
+ // → into a deck's settings, ← back out of them (Esc works too)
39
+ if (key.leftArrow && !naming) {
40
+ if (setting) return setSetting(null);
41
+ if (menu) return setMenu(null);
42
+ }
43
+ // not while a change is still being saved: the menu would show the deck as it was
44
+ if (key.rightArrow && !menu && !setting && !naming && !saving.current && deck && !deck.tour) {
34
45
  setMessage("");
35
- setSetting({ deck, selected: Math.max(0, DIRECTIONS.indexOf(deck.directions)) });
46
+ setMenu({ deck, selected: 0 });
36
47
  }
37
48
  });
38
49
 
@@ -40,6 +51,9 @@ export function Decks({ current, actions, onPick, onNew, onClose, onDirections }
40
51
  async function setDirections(index) {
41
52
  const { deck } = setting;
42
53
  setSetting(null);
54
+ setMenu(null);
55
+ if (DIRECTIONS[index] === deck.directions) return; // nothing changed, nothing to say
56
+ saving.current = true;
43
57
  try {
44
58
  const { cardIds } = await actions.setDirections(deck.name, DIRECTIONS[index]);
45
59
  await onDirections?.(cardIds, DIRECTIONS[index]);
@@ -47,6 +61,54 @@ export function Decks({ current, actions, onPick, onNew, onClose, onDirections }
47
61
  setMessage(t("decks.directionSaved", { deck: deck.name }));
48
62
  } catch (err) {
49
63
  setError(err.message);
64
+ } finally {
65
+ saving.current = false;
66
+ }
67
+ }
68
+
69
+ // the menu stays underneath: Esc in the direction or language picker comes back to it
70
+ function openSetting(index) {
71
+ const { deck } = menu;
72
+ setMenu((m) => ({ ...m, selected: index })); // coming back, the cursor is on the row you opened
73
+ const rows = ["ask", "languages", ...(deck.learning ? ["learning"] : []), ...(deck.languages.guessed ? [] : ["detect"])];
74
+ if (rows[index] === "ask") return setSetting({ deck, selected: Math.max(0, DIRECTIONS.indexOf(deck.directions)) });
75
+ if (rows[index] === "languages") return setNaming(deck);
76
+ if (rows[index] === "learning") return setNaming({ ...deck, only: "learning" });
77
+ setLanguages(null, deck); // detect them from the cards again
78
+ }
79
+
80
+ // the language you're learning in the deck (pronunciation reads it, "almost" applies to it)
81
+ async function saveLearning(deck, lang) {
82
+ setNaming(null);
83
+ setMenu(null);
84
+ saving.current = true;
85
+ try {
86
+ const learning = await actions.setLearning(deck.name, lang);
87
+ setDecks((all) => all.map((d) => (d.name === deck.name ? { ...d, learning } : d)));
88
+ setMessage(t("languages.learningSaved", { deck: deck.name, language: languageName(learning?.lang) }));
89
+ onLanguages?.(deck.name);
90
+ } catch (err) {
91
+ setError(err.message);
92
+ } finally {
93
+ saving.current = false;
94
+ }
95
+ }
96
+
97
+ async function setLanguages(languages, deck = naming) {
98
+ setNaming(null);
99
+ setMenu(null);
100
+ saving.current = true;
101
+ try {
102
+ const saved = await actions.setLanguages(deck.name, languages);
103
+ setDecks((all) => all.map((d) => (d.name === deck.name ? { ...d, languages: saved, learning: saved.learning } : d)));
104
+ setMessage(
105
+ !languages ? t("languages.detecting", { deck: deck.name }) : saved.learning ? t("languages.savedWithLearning", { deck: deck.name, pair: pairText(saved), language: languageName(saved.learning.lang) }) : t("languages.saved", { deck: deck.name, pair: pairText(saved) })
106
+ );
107
+ onLanguages?.(deck.name);
108
+ } catch (err) {
109
+ setError(err.message);
110
+ } finally {
111
+ saving.current = false;
50
112
  }
51
113
  }
52
114
 
@@ -54,13 +116,55 @@ export function Decks({ current, actions, onPick, onNew, onClose, onDirections }
54
116
  const directionOptions = (deck) => {
55
117
  const [front, back] = deck.sample ? [short(deck.sample.front), short(deck.sample.back.join(" / "))] : [t("decks.front"), t("decks.back")];
56
118
  return [
57
- { label: `${front} → ?`, note: deck.directions === "forward" ? t("decks.now") : "" },
58
- { label: `${back} → ?`, note: deck.directions === "backward" ? t("decks.now") : "" },
59
- { label: t("add.bothWays"), note: deck.directions === "both" ? t("decks.now") : "" }
119
+ { label: `${front} → ?`, note: deck.directions === "forward" ? t("languages.current") : "" },
120
+ { label: `${back} → ?`, note: deck.directions === "backward" ? t("languages.current") : "" },
121
+ { label: t("add.bothWays"), note: deck.directions === "both" ? t("languages.current") : "" }
60
122
  ];
61
123
  };
62
124
 
63
- if (setting)
125
+ if (naming)
126
+ return html`<${LanguagePicker}
127
+ deck=${naming.name}
128
+ sample=${naming.sample}
129
+ languages=${naming.languages}
130
+ learning=${naming.learning}
131
+ home=${naming.home}
132
+ start=${naming.only ?? "front"}
133
+ onDone=${(picked) => (naming.only ? saveLearning(naming, picked.learning) : setLanguages(picked))}
134
+ onCancel=${() => setNaming(null)}
135
+ />`;
136
+
137
+ if (setting) return directionPicker();
138
+
139
+ if (menu) {
140
+ const { deck } = menu;
141
+ const guessedNote = deck.languages.guessed && deck.cards > 0 && (isKnown(deck.languages.front) || isKnown(deck.languages.back)) ? ` · ${t("languages.guessed")}` : "";
142
+ const how = directionOptions(deck)[Math.max(0, DIRECTIONS.indexOf(deck.directions))].label;
143
+ return html`
144
+ <${Fragment}>
145
+ <${Box} flexDirection="column" borderStyle="round" borderColor=${theme.accent} paddingX=${2} width=${panel}>
146
+ <${Text} bold color=${theme.accent}>${deck.name}<//>
147
+ <${Box} marginTop=${1}>
148
+ <${Choice}
149
+ options=${[
150
+ { label: t("decks.askRow"), note: deck.directions === "both" ? t("add.bothWays") : how },
151
+ { label: t("decks.languagesRow"), note: pairText(deck.languages) + guessedNote },
152
+ ...(deck.learning ? [{ label: t("decks.learningRow"), note: languageName(deck.learning.lang) + (deck.learning.sure ? "" : ` · ${t("languages.guessShort")}`) }] : []),
153
+ ...(deck.languages.guessed ? [] : [{ label: t("decks.detectRow") }])
154
+ ]}
155
+ selected=${menu.selected}
156
+ onMove=${(selected) => setMenu((m) => ({ ...m, selected }))}
157
+ onPick=${openSetting}
158
+ onCancel=${() => setMenu(null)}
159
+ />
160
+ <//>
161
+ <//>
162
+ <${Box} paddingX=${1}><${KeyHints} text=${t("keyHints.choiceLeft", { choose: t("choice.keys") })} /><//>
163
+ <//>
164
+ `;
165
+ }
166
+
167
+ function directionPicker() {
64
168
  return html`
65
169
  <${Fragment}>
66
170
  <${Box} flexDirection="column" borderStyle="round" borderColor=${theme.accent} paddingX=${2} width=${panel}>
@@ -70,9 +174,13 @@ export function Decks({ current, actions, onPick, onNew, onClose, onDirections }
70
174
  <//>
71
175
  <${Box} marginTop=${1}><${Text} dimColor>${t("decks.progressKept")}<//><//>
72
176
  <//>
73
- <${Box} paddingX=${1}><${KeyHints} text=${choiceHints()} /><//>
177
+ <${Box} paddingX=${1}><${KeyHints} text=${t("keyHints.choiceLeft", { choose: t("choice.keys") })} /><//>
74
178
  <//>
75
179
  `;
180
+ }
181
+
182
+ // a deck's languages show in the list once the cards tell at least one
183
+ const languagesNote = (d) => (d.tour || !d.cards ? "" : d.learning ? t("decks.learningShort", { language: languageName(d.learning.lang) }) : isKnown(d.languages.front) && isKnown(d.languages.back) ? pairText(d.languages) : "");
76
184
 
77
185
  return html`
78
186
  <${Fragment}>
@@ -82,7 +190,7 @@ export function Decks({ current, actions, onPick, onNew, onClose, onDirections }
82
190
  html`
83
191
  <${Box} marginTop=${1}>
84
192
  <${Choice}
85
- options=${[...decks.map((d) => ({ label: d.name, note: [t("count.cards", { count: d.cards }), d.tour && t("decks.tour"), d.name === current && t("decks.now")].filter(Boolean).join(" · ") })), { label: t("decks.newDeck") }]}
193
+ options=${[...decks.map((d) => ({ label: d.name, note: [t("count.cards", { count: d.cards }), languagesNote(d), d.tour && t("decks.tour"), d.name === current && t("decks.now")].filter(Boolean).join(" · ") })), { label: t("decks.newDeck") }]}
86
194
  selected=${picked}
87
195
  onMove=${setPicked}
88
196
  onPick=${(i) => (i === decks.length ? onNew() : onPick(decks[i].name))}
package/src/ui/Help.js CHANGED
@@ -30,9 +30,21 @@ const outside = () => [
30
30
  ["dracosh --help", t("help.outside.help")]
31
31
  ];
32
32
 
33
- // the left column fits its longest entry, whatever the language
33
+ // the left column fits its longest entry, whatever the language; in a narrow pane each text goes
34
+ // under its key instead of into a thin column
35
+ const NARROW_TEXT = 24;
34
36
  function Rows({ rows }) {
37
+ const panel = usePanelWidth();
35
38
  const width = Math.max(...rows.map(([left]) => cellWidth(left))) + 2;
39
+ if (panel - 6 - width < NARROW_TEXT)
40
+ return rows.map(
41
+ ([left, right]) => html`
42
+ <${Box} key=${left} flexDirection="column">
43
+ <${Text} color=${theme.accent}>${left}<//>
44
+ <${Box} marginLeft=${2}><${Text}>${right}<//><//>
45
+ <//>
46
+ `
47
+ );
36
48
  return rows.map(
37
49
  ([left, right]) => html`
38
50
  <${Box} key=${left}>