dracosh 0.5.0 → 0.7.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/App.js CHANGED
@@ -11,6 +11,8 @@ import { Bar, cellWidth, cutToWidth, html, KeyHints, Marked, Text, theme, Typewr
11
11
  import { hintTarget, makeHint } from "../hint.js";
12
12
  import { formatClock, inQuietHours, quietEnd } from "../quiet.js";
13
13
  import { NEW_PER_DAY, startOfTomorrow } from "../scheduler.js";
14
+ import { languageName, setOwnLanguage } from "../language.js";
15
+ import { hasFirstWords, sampleCard } from "../firstwords.js";
14
16
  import { formatDay } from "../vacation.js";
15
17
  import { dayKey } from "../dates.js";
16
18
  import { shouldShowTip } from "../tips.js";
@@ -22,8 +24,15 @@ import { BadgeUnlock, badgeSound } from "./BadgeUnlock.js";
22
24
  import { DieRoll } from "./DieRoll.js";
23
25
  import { Evolution } from "./Evolution.js";
24
26
  import { Hatch } from "./Hatch.js";
27
+ import { LanguageSearch } from "./Languages.js";
28
+ import { Welcome } from "./Welcome.js";
25
29
  import { AddCard } from "./AddCard.js";
30
+ import { ImportScreen } from "./Import.js";
26
31
  import { Decks } from "./Decks.js";
32
+ import { Choice, choiceHints } from "./Choice.js";
33
+ import { elementName } from "../progress.js";
34
+ import { Trash } from "./Trash.js";
35
+ import { Cards, CardsDeckPick } from "./Cards.js";
27
36
  import { Reset } from "./Reset.js";
28
37
  import { Help } from "./Help.js";
29
38
  import { Missed } from "./Missed.js";
@@ -75,20 +84,26 @@ function AccentedAnswers({ expected, given, closest }) {
75
84
  });
76
85
  }
77
86
 
87
+ // "The card comes back in a few minutes, not in 2 days." Two months and more are said in months.
88
+ const comesBack = (days) => (days < 1 ? t("quiz.almost.soon") : days < 60 ? t("quiz.almost.days", { count: days }) : t("quiz.almost.months", { count: Math.round(days / 30) }));
89
+ const heldText = (held) => (comesBack(held.days) === comesBack(held.would) ? null : t("quiz.almost.held", { now: comesBack(held.days), would: comesBack(held.would) }));
90
+
78
91
  function Verdict({ outcome, question }) {
79
92
  const wrong = outcome.result === "wrong";
80
93
  const showDiff = outcome.closest && outcome.given && !outcome.overruled && (wrong || outcome.result === "typo");
94
+ // a typo, an "almost" or a hint: the card comes back sooner, said on a line of its own
95
+ const held = outcome.held ? heldText(outcome.held) : null;
81
96
  return html`
82
97
  <${Box} flexDirection="column">
83
98
  <${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 }) })}` : ""}<//>`}
99
+ ${ALMOST.includes(outcome.result) && html`<${Text} color=${theme.warn}>${t(`quiz.almost.${outcome.result}`)}<//>`}
86
100
  ${showDiff && html`<${AnswerDiff} given=${outcome.given} closest=${outcome.closest} />`}
87
101
  ${question.word.example && html`<${Box} marginTop=${1}>${question.tour ? html`<${Marked} dimColor text=${question.word.example} />` : html`<${Text} dimColor italic>“${question.word.example}”<//>`}<//>`}
88
- ${(outcome.hinted || outcome.overruled) &&
102
+ ${(outcome.hinted || outcome.overruled || held) &&
89
103
  html`
90
104
  <${Box} marginTop=${1} flexDirection="column">
91
105
  ${outcome.hinted && html`<${Text} dimColor>${t("quiz.hintUsed")}<//>`}
106
+ ${held && html`<${Text} dimColor>${held}<//>`}
92
107
  ${outcome.overruled && html`<${Text} color=${theme.good}>${t("quiz.countedCorrect")}${question.tour ? "" : t("quiz.acceptedFromNow", { answer: outcome.accepted })}<//>`}
93
108
  <//>
94
109
  `}
@@ -172,6 +187,22 @@ function EmptyDeck({ deck, tour, count, nextDue, dayDone, heldNew = 0, now, widt
172
187
  `;
173
188
  }
174
189
 
190
+ // /settings → the default look: asked first, since the element can't come back
191
+ function DragonLook({ element, onConfirm, onClose }) {
192
+ const width = usePanelWidth();
193
+ const [selected, setSelected] = useState(1);
194
+ return html`
195
+ <${Fragment}>
196
+ <${Box} flexDirection="column" borderStyle="round" borderColor=${theme.bad} paddingX=${2} width=${width}>
197
+ <${Text} bold color=${theme.bad}>${t("settings.lookQuestion")}<//>
198
+ <${Text} dimColor>${t("settings.lookNote", { element: elementName(element) })}<//>
199
+ <${Box} marginTop=${1}><${Choice} options=${[{ label: t("settings.lookYes"), danger: true }, { label: t("settings.lookNo") }]} selected=${selected} onMove=${setSelected} onPick=${(i) => (i === 0 ? onConfirm() : onClose())} onCancel=${onClose} /><//>
200
+ <//>
201
+ <${Box} paddingX=${1}><${KeyHints} text=${choiceHints("cancel")} /><//>
202
+ <//>
203
+ `;
204
+ }
205
+
175
206
  function TipBox({ tip, width }) {
176
207
  return html`
177
208
  <${Box} flexDirection="column" paddingX=${1} marginTop=${2} width=${width}>
@@ -183,17 +214,27 @@ function TipBox({ tip, width }) {
183
214
 
184
215
  // `library` holds the /add actions (src/manage.js) and `onSwitchDeck` points the session at another
185
216
  // deck; the preview gallery passes neither.
186
- export function App({ session, deck: initialDeck, initialSettings, alerts, persistSettings, onExit, library, onSwitchDeck }) {
217
+ // `initialMix`: the decks practised together this run (null with --deck, while settings keep the saved ones)
218
+ export function App({ session, deck: initialDeck, initialSettings, initialMix, alerts, persistSettings, onExit, library, onSwitchDeck, onMix }) {
187
219
  const { exit: exitApp } = useApp();
188
220
  const exit = onExit ?? exitApp; // the preview gallery runs the quiz as a scene and takes quitting back to its menu
189
221
  const { stdout } = useStdout();
190
222
  const [settings, setSettings] = useState(initialSettings);
191
223
  const [deck, setDeck] = useState(initialDeck);
224
+ const [mix, setMix] = useState(initialMix !== undefined ? initialMix : (initialSettings.mix ?? null)); // decks practised together: "all", or their names
192
225
  const [addNew, setAddNew] = useState(false); // /add opened from "+ New deck" in /decks
226
+ const [cardsDeck, setCardsDeck] = useState(null); // the deck /cards shows (one of several practised together)
227
+ const [addInto, setAddInto] = useState(null); // /add from /cards: straight into that deck
228
+ const [addSuggest, setAddSuggest] = useState(null); // /add from the welcome: a name and an example in your pair
229
+ const [importFrom, setImportFrom] = useState(null); // "welcome" when /import was picked there: cancelling goes back
193
230
  const [restUntil, setRestUntil] = useState(null); // nothing is waiting until then (after the last card due now)
194
231
  const [empty, setEmpty] = useState(null); // { tour, count, nextDue } when there is nothing to ask right now
195
- // quiz | settings | reset | add | decks | stats | badges | companion | help | missed | evolve | the-one | die | summary | hatch
196
- const [screen, setScreen] = useState(() => (session.isFirstRun() ? "hatch" : "quiz"));
232
+ // quiz | settings | reset | home-language | add | decks | stats | badges | companion | help | missed | evolve | the-one | die
233
+ // | summary | hatch | welcome
234
+ const [screen, setScreen] = useState(() => (session.isFirstRun() ? "hatch" : session.welcomeStep() ? "welcome" : "quiz"));
235
+ const [welcomeStep, setWelcomeStep] = useState(() => session.welcomeStep() ?? "language");
236
+ const [tourThere, setTourThere] = useState(true); // the welcome offers the tour only while there is one
237
+ const settingsRow = useRef(0); // /settings opens on the row it was left on (Your language comes back to it)
197
238
  const [tip, setTip] = useState(null);
198
239
  const [phase, setPhase] = useState("loading"); // loading | asking | grading (answer revealed) | waiting | empty
199
240
  const [nudge, setNudge] = useState(false); // Enter while grading: the 1/2 keys light up
@@ -396,6 +437,9 @@ export function App({ session, deck: initialDeck, initialSettings, alerts, persi
396
437
  if (name === "/missed") return setScreen("missed");
397
438
  if (name === "/help") return setScreen("help");
398
439
  if (name === "/add") return library ? (setAddNew(false), setScreen("add")) : setNotice(t("quiz.previewNoAdd"));
440
+ if (name === "/import") return library ? (setImportFrom(null), setScreen("import")) : setNotice(t("quiz.previewNoImport"));
441
+ if (name === "/cards") return !library ? setNotice(t("quiz.previewNoDecks")) : !mix && (question?.tour || empty?.tour) ? setNotice(t("cards.tourNot")) : mix ? setScreen("cards-pick") : (setCardsDeck(deck), setScreen("cards"));
442
+ if (name === "/trash") return library ? setScreen("trash") : setNotice(t("quiz.previewNoDecks"));
399
443
  if (name === "/decks") return library ? setScreen("decks") : setNotice(t("quiz.previewNoDecks"));
400
444
  if (name === "/hint" && phase === "asking") return setHintLevel((level) => level + 1);
401
445
  if (name === "/pause") {
@@ -449,6 +493,57 @@ export function App({ session, deck: initialDeck, initialSettings, alerts, persi
449
493
  }
450
494
  if (patch.volume !== undefined || patch.sound === true) alerts.play("correct-0"); // audible preview
451
495
  if (patch.language) changeLanguage(patch.language);
496
+ if (patch.homeLanguage !== undefined) setOwnLanguage(patch.homeLanguage);
497
+ }
498
+
499
+ // the welcome: each answer kept at once, and the step, so it goes on there after a restart
500
+ function welcomeTo(step, patch) {
501
+ if (patch) changeSettings(patch);
502
+ setWelcomeStep(step);
503
+ session.setWelcomeStep(step).catch(() => {});
504
+ }
505
+
506
+ useEffect(() => {
507
+ if (screen === "welcome" && library) library.allDecks().then((decks) => setTourThere(decks.some((d) => d.tour)), () => {});
508
+ }, [screen, library]);
509
+
510
+ async function startWith(how) {
511
+ if (busy.current) return; // a second Enter while the first words are being made
512
+ busy.current = true;
513
+ try {
514
+ await begin(how);
515
+ } finally {
516
+ busy.current = false;
517
+ }
518
+ }
519
+
520
+ async function begin(how) {
521
+ // the import may still be cancelled, back to the welcome: it ends the welcome once it's done
522
+ if (how === "import" && library) {
523
+ setImportFrom("welcome");
524
+ return setScreen("import");
525
+ }
526
+ session.setWelcomeStep(null).catch(() => {});
527
+ if (how === "tour" || !library) return setScreen("quiz");
528
+ if (how === "own") {
529
+ // the deck named after the language you're learning, and an example card in your pair
530
+ const { homeLanguage, language: ui, learningLanguage: learning } = settingsRef.current;
531
+ const home = homeLanguage ?? ui;
532
+ const name = languageName(learning) ?? "";
533
+ const sample = learning && hasFirstWords(home, learning) ? sampleCard(home, learning) : null;
534
+ setAddSuggest({ name: name && name.charAt(0).toLocaleUpperCase(ui) + name.slice(1), example: sample && `${sample.front} = ${sample.back[0]}` });
535
+ setAddNew(true);
536
+ return setScreen("add");
537
+ }
538
+ try {
539
+ const { deck: started, removed } = await library.startFirstWords({ home: settingsRef.current.homeLanguage ?? settingsRef.current.language, learning: settingsRef.current.learningLanguage });
540
+ if (removed.length) await session.forget(removed);
541
+ await session.workAdded();
542
+ switchDeck(started.name);
543
+ } catch (err) {
544
+ setScreen("quiz");
545
+ setProblem(err.message);
546
+ }
452
547
  }
453
548
 
454
549
  // Every text follows at the next render; the tour is translated too, and asked again in the new
@@ -518,9 +613,8 @@ export function App({ session, deck: initialDeck, initialSettings, alerts, persi
518
613
  }
519
614
  }
520
615
 
521
- // /decks and a first deck from /add: quiz another deck from now on, and remember it
522
- function switchDeck(name) {
523
- setScreen("quiz");
616
+ // the deck practised from now on, without leaving the screen you're on (a deck deleted or renamed in /decks)
617
+ function followDeck(name) {
524
618
  if (name === deck) return;
525
619
  onSwitchDeck?.(name);
526
620
  setDeck(name);
@@ -528,6 +622,97 @@ export function App({ session, deck: initialDeck, initialSettings, alerts, persi
528
622
  ask();
529
623
  }
530
624
 
625
+ // /decks → Delete, confirmed: the deck and its progress into the trash; another deck if it was this one
626
+ async function deleteDeck(name) {
627
+ const done = await library.deleteDeck(name, session.progressOf);
628
+ await session.forget(done.cardIds);
629
+ keepSavedMix((names) => names.filter((each) => each !== name));
630
+ if (Array.isArray(mix) && mix.includes(name)) {
631
+ const left = mix.filter((each) => each !== name);
632
+ practise({ deck: name === deck ? left[0] : deck, mix: left.length >= 2 ? left : null });
633
+ } else if (name === deck) followDeck(done.next);
634
+ else if (phase === "empty" || mix === "all" || question?.label === name) ask(); // its card may be the one on screen
635
+ return done;
636
+ }
637
+
638
+ // the decks saved to practise together when this run practises others (--deck): kept in step too
639
+ function keepSavedMix(change) {
640
+ const saved = settingsRef.current.mix;
641
+ if (!Array.isArray(saved) || saved === mix) return;
642
+ const next = [...new Set(change(saved))];
643
+ changeSettings({ mix: next.length >= 2 ? next : null });
644
+ }
645
+
646
+ // a deck back from the trash, with its progress; the tour gives way to it
647
+ async function restoreDeck(entryId) {
648
+ const back = await library.restoreFromTrash(entryId);
649
+ await session.restoreProgress(back.progress);
650
+ if (back.removed.length) await session.forget(back.removed);
651
+ await session.workAdded();
652
+ if (back.removed.length || (back.kind === "deck" && phase === "empty")) followDeck(back.deck);
653
+ else if (phase === "empty") ask();
654
+ return back;
655
+ }
656
+
657
+ // /cards → Delete: the cards and their progress into the trash
658
+ async function deleteCards(cardIds) {
659
+ const done = await library.deleteCards(cardsDeck ?? deck, cardIds, session.progressOf);
660
+ await session.forget(cardIds);
661
+ return done;
662
+ }
663
+
664
+ // /decks → Merge: the cards into the other deck, the emptied deck (with what was there already) to the
665
+ // trash; the decks practised follow
666
+ async function mergeDecks(from, into) {
667
+ const done = await library.mergeDecks(from, into, session.progressOf);
668
+ if (done.left.length) await session.forget(done.left);
669
+ if (Array.isArray(mix) && mix.includes(from)) {
670
+ const left = [...new Set(mix.map((name) => (name === from ? into : name)))];
671
+ practise({ deck: deck === from ? into : deck, mix: left.length >= 2 ? left : null });
672
+ } else if (deck === from) followDeck(into);
673
+ else if (phase === "empty") ask();
674
+ return done;
675
+ }
676
+
677
+ function cardsClosed(changed) {
678
+ setScreen("quiz");
679
+ if (changed && (phase === "asking" || phase === "empty")) ask(); // the card on screen may be one you changed
680
+ }
681
+
682
+ function deckRenamed(from, to) {
683
+ keepSavedMix((names) => names.map((name) => (name === from ? to : name)));
684
+ if (Array.isArray(mix) && mix.includes(from)) {
685
+ const renamed = mix.map((name) => (name === from ? to : name));
686
+ onMix?.(renamed);
687
+ setMix(renamed);
688
+ changeSettings({ mix: renamed });
689
+ }
690
+ if (from !== deck) return;
691
+ onSwitchDeck?.(to);
692
+ setDeck(to);
693
+ changeSettings({ deck: to });
694
+ }
695
+
696
+ // /decks and a first deck from /add: quiz another deck from now on, and remember it
697
+ function switchDeck(name) {
698
+ setScreen("quiz");
699
+ if (name === deck && !mix) return;
700
+ practise({ deck: name, mix: null });
701
+ }
702
+
703
+ // what the quiz asks from now on: one deck, or several together (`mix`: "all" or names), remembered
704
+ function practise({ deck: name = deck, mix: together }) {
705
+ onMix?.(together);
706
+ setMix(together);
707
+ if (name !== deck) {
708
+ onSwitchDeck?.(name);
709
+ setDeck(name);
710
+ }
711
+ changeSettings({ deck: name, mix: together });
712
+ ask();
713
+ }
714
+ const deckLabel = mix === "all" ? t("decks.allLabel") : mix ? t("decks.mixLabel", { count: mix.length }) : deck;
715
+
531
716
  // Reset (from /settings), after a backup. Everything brings back the tour and the hatching egg.
532
717
  async function reset(scope) {
533
718
  await library.backupBeforeReset();
@@ -540,15 +725,45 @@ export function App({ session, deck: initialDeck, initialSettings, alerts, persi
540
725
  const tour = await library.resetLibrary();
541
726
  onSwitchDeck?.(tour);
542
727
  setDeck(tour);
543
- changeSettings({ deck: null });
728
+ onMix?.(null);
729
+ setMix(null);
730
+ changeSettings({ deck: null, mix: null });
544
731
  setScreen("hatch");
545
732
  ask();
546
733
  }
547
734
 
735
+ // after /import: its first new deck (or the one cards went into) is the one you practise; the tour's
736
+ // progress goes if a deck of your own took its place
737
+ async function importDone({ deck: target, removed, added, updated }) {
738
+ if (importFrom === "welcome") session.setWelcomeStep(null).catch(() => {});
739
+ setImportFrom(null);
740
+ try {
741
+ if (removed.length) await session.forget(removed);
742
+ if (added || updated) await session.workAdded();
743
+ } catch {
744
+ // progress of removed tour cards stays: harmless
745
+ }
746
+ if (target && target !== deck) return switchDeck(target);
747
+ setScreen("quiz");
748
+ // the open card may be one the file just changed: asked again as it is now
749
+ if ((added || updated) && (phase === "asking" || phase === "empty")) ask();
750
+ }
751
+
752
+ function importCancelled() {
753
+ if (importFrom === "welcome") {
754
+ setImportFrom(null);
755
+ return setScreen("welcome");
756
+ }
757
+ setScreen("quiz");
758
+ setNotice(t("cli.restore.nothingChanged"));
759
+ }
760
+
548
761
  // after /add: a first deck of your own replaces the tour; a deck started from /decks (or in place
549
762
  // of an empty one) becomes the one you practise; new cards end an empty state
550
763
  function addDone({ deck: started, removed, stale = [], added, dropped }) {
551
764
  setScreen("quiz");
765
+ setAddSuggest(null);
766
+ setAddInto(null);
552
767
  if (removed.length) session.forget(removed).catch(() => {});
553
768
  if (stale.length) session.forgetKeys(stale).catch(() => {});
554
769
  if (added) session.workAdded().catch(() => {});
@@ -579,8 +794,11 @@ export function App({ session, deck: initialDeck, initialSettings, alerts, persi
579
794
  if (screen === "hatch")
580
795
  return html`<${Box} flexDirection="column" marginY=${1}><${Hatch} play=${alerts.play} onDone=${() => {
581
796
  session.markHatched().catch(() => {});
582
- setScreen("quiz");
797
+ setWelcomeStep("language");
798
+ setScreen("welcome");
583
799
  }} /><//>`;
800
+ if (screen === "welcome")
801
+ return html`<${Box} flexDirection="column" marginY=${1}><${Welcome} step=${welcomeStep} settings=${settings} tour=${tourThere} onPreviewLanguage=${setLanguage} onStep=${welcomeTo} onStart=${startWith} /><//>`;
584
802
  if (screen === "summary") return html`<${Box} flexDirection="column" marginY=${1}><${Summary} stats=${stats} totals=${session.totals} bestCombo=${bestCombo.current} onDone=${exit} /><//>`;
585
803
  if (screen === "evolve" && evolution)
586
804
  return html`<${Box} flexDirection="column" marginY=${1}><${Evolution} ...${evolution} onClose=${() => {
@@ -598,17 +816,23 @@ export function App({ session, deck: initialDeck, initialSettings, alerts, persi
598
816
 
599
817
  return html`
600
818
  <${Box} flexDirection="column" marginY=${1}>
601
- <${Header} deck=${deck} everyMs=${settings.everyMs} rhythm=${settings.rhythm} wordCount=${question?.wordCount ?? empty?.count} stats=${stats} combo=${session.totals.combo} face=${face} event=${petEvent} tick=${tick} asleep=${asleep} />
819
+ <${Header} deck=${deckLabel} everyMs=${settings.everyMs} rhythm=${settings.rhythm} wordCount=${question?.wordCount ?? empty?.count} stats=${stats} combo=${session.totals.combo} face=${face} event=${petEvent} tick=${tick} asleep=${asleep} />
602
820
  <${Box} marginTop=${1} flexDirection="column">
603
- ${screen === "settings" && html`<${Settings} settings=${settings} onChange=${changeSettings} onClose=${() => setScreen("quiz")} onAction=${library ? () => setScreen("reset") : null} />`}
821
+ ${screen === "settings" && html`<${Settings} settings=${settings} element=${stats.companion.element} startRow=${settingsRow.current} onRow=${(row) => (settingsRow.current = row)} onChange=${changeSettings} onClose=${() => setScreen("quiz")} onAction=${library ? (row) => setScreen({ reset: "reset", homeLanguage: "home-language", dragonLook: "dragon-look" }[row]) : null} />`}
822
+ ${screen === "dragon-look" && html`<${DragonLook} element=${stats.companion.element} onConfirm=${() => session.defaultLook().then(() => (setScreen("settings"), setNotice(t("settings.lookDropped")))).catch((err) => setProblem(err.message))} onClose=${() => setScreen("settings")} />`}
823
+ ${screen === "home-language" && html`<${LanguageSearch} title=${t("settings.homeTitle")} note=${t("welcome.homeNote")} current=${settings.homeLanguage ?? settings.language} currentNote=${settings.homeLanguage ? t("languages.current") : t("welcome.suggested")} onBack=${() => setScreen("settings")} onPick=${(code) => (changeSettings({ homeLanguage: code }), setScreen("settings"))} />`}
604
824
  ${screen === "reset" && html`<${Reset} stats=${stats} actions=${library} onConfirm=${reset} onClose=${() => setScreen("settings")} />`}
605
- ${screen === "add" && html`<${AddCard} current=${deck} actions=${library} onDone=${addDone} startNew=${addNew} />`}
606
- ${screen === "decks" && html`<${Decks} current=${deck} actions=${library} onDirections=${async (cardIds, directions) => {
825
+ ${screen === "import" && html`<${ImportScreen} actions=${library} fromWelcome=${importFrom === "welcome"} onDone=${importDone} onCancel=${importCancelled} />`}
826
+ ${screen === "add" && html`<${AddCard} current=${deck} actions=${library} onDone=${addDone} startNew=${addNew} suggest=${addSuggest} into=${addInto} />`}
827
+ ${screen === "decks" && html`<${Decks} current=${deck} mix=${mix} onPractise=${practise} actions=${library} onDirections=${async (cardIds, directions) => {
607
828
  await session.setDirections(cardIds, directions);
608
829
  await session.workAdded();
609
830
  if (phase === "asking" && question && cardIds.includes(question.word.noteId)) ask(); // the open card follows the new way at once
610
- }} onLanguages=${(name) => name === deck && phase === "asking" && ask()} onPick=${switchDeck} onNew=${() => (setAddNew(true), setScreen("add"))} onClose=${() => setScreen("quiz")} />`}
611
- ${!["settings", "reset", "add", "decks"].includes(screen) &&
831
+ }} onLanguages=${(name) => name === deck && phase === "asking" && ask()} onPick=${switchDeck} onNew=${() => (setAddNew(true), setScreen("add"))} onDeleted=${deleteDeck} onRestored=${restoreDeck} onRenamed=${deckRenamed} onMerged=${mergeDecks} onClose=${() => setScreen("quiz")} />`}
832
+ ${screen === "cards" && html`<${Cards} deck=${cardsDeck ?? deck} actions=${library} onDeleted=${deleteCards} onRestored=${restoreDeck} onEdited=${(keys) => session.forgetKeys(keys)} onAdd=${() => (setAddNew(false), setAddInto(cardsDeck ?? deck), setScreen("add"))} onClose=${cardsClosed} />`}
833
+ ${screen === "cards-pick" && html`<${CardsDeckPick} actions=${library} mix=${mix} current=${deck} onPick=${(name) => (setCardsDeck(name), setScreen("cards"))} onClose=${() => setScreen("quiz")} />`}
834
+ ${screen === "trash" && html`<${Trash} actions=${library} onRestore=${restoreDeck} onClose=${() => setScreen("quiz")} />`}
835
+ ${!["settings", "reset", "home-language", "dragon-look", "import", "add", "decks", "trash", "cards", "cards-pick"].includes(screen) &&
612
836
  html`
613
837
  <${Fragment}>
614
838
  ${question &&
@@ -627,7 +851,7 @@ export function App({ session, deck: initialDeck, initialSettings, alerts, persi
627
851
  <//>
628
852
  <//>
629
853
  `}
630
- ${phase === "empty" && html`<${EmptyDeck} deck=${deck} ...${empty} now=${now} width=${width} />`}
854
+ ${phase === "empty" && html`<${EmptyDeck} deck=${deckLabel} ...${empty} now=${now} width=${width} />`}
631
855
  ${confetti && html`<${Confetti} width=${width} onDone=${() => setConfetti(false)} />`}
632
856
  ${outcome?.cheers?.length > 0 && html`<${Cheers} cheers=${outcome.cheers} play=${alerts.play} />`}
633
857
  ${phase === "waiting" && tip && html`<${TipBox} tip=${tip} width=${width} />`}
@@ -0,0 +1,236 @@
1
+ import { Fragment, useEffect, useRef, useState } from "react";
2
+ import { Box, useInput } from "ink";
3
+ import { t } from "../i18n.js";
4
+ import { formatLine, parseLine, plainFront } from "../cardline.js";
5
+ import { fold } from "../judge.js";
6
+ import { TRASH_DAYS } from "../library.js";
7
+ import { AnswerInput } from "./AnswerInput.js";
8
+ import { Choice, choiceHints } from "./Choice.js";
9
+ import { cutToWidth, html, KeyHints, Text, theme, usePanelWidth } from "./kit.js";
10
+
11
+ const SHOWN = 8; // rows of the list at a time
12
+
13
+ const look = (text) => fold(String(text).toLowerCase());
14
+ const lineOf = (card) => (card.cloze ? plainFront(card.front) : `${card.front} = ${card.back.join("; ")}`);
15
+ // a card matches what's typed in its front, any answer or its example, accents or not
16
+ const matches = (card, query) => !query || [card.front, ...card.back, card.example].some((text) => look(text).includes(look(query)));
17
+
18
+ // /cards: the cards of a deck, to search (type), fix, move to another deck or delete. A deleted card
19
+ // goes to the trash, and the row on top brings it straight back. `actions`: the library's;
20
+ // `onDeleted`(cardIds) → { entry }, `onRestored`(entry), `onEdited`(staleKeys) let the app keep the
21
+ // progress in step; `onAdd` opens /add for the deck; onClose(changed).
22
+ export function Cards({ deck, actions, onDeleted, onRestored, onEdited, onAdd, onClose }) {
23
+ const panel = usePanelWidth();
24
+ const [cards, setCards] = useState(null);
25
+ const [decks, setDecks] = useState([]); // your other decks, to move a card to
26
+ const [query, setQuery] = useState("");
27
+ const [selected, setSelected] = useState(0);
28
+ const [open, setOpen] = useState(null); // { card, step: "menu" | "edit" | "move" | "delete", selected }
29
+ const [undo, setUndo] = useState(null); // { entry, card }: the card just deleted
30
+ const [message, setMessage] = useState("");
31
+ const [error, setError] = useState("");
32
+ const changed = useRef(false);
33
+ const busy = useRef(false);
34
+
35
+ const load = () => actions.cardsIn(deck).then(setCards, (err) => setError(err.message));
36
+ useEffect(() => {
37
+ load();
38
+ actions.ownDecks().then((own) => setDecks(own.filter((d) => d.name !== deck)), () => {});
39
+ }, []);
40
+
41
+ const found = (cards ?? []).filter((card) => matches(card, query));
42
+ // the rows: bring back the card just deleted, add cards (with no search), then the cards found
43
+ // (both only with no search: Enter on what's found never brings a card back by accident)
44
+ const rows = [...(undo && !query ? [{ undo: true }] : []), ...(query ? [] : [{ add: true }]), ...found];
45
+
46
+ async function run(work) {
47
+ if (busy.current) return;
48
+ busy.current = true;
49
+ setError("");
50
+ try {
51
+ await work();
52
+ } catch (err) {
53
+ setError(err.message);
54
+ } finally {
55
+ busy.current = false;
56
+ }
57
+ }
58
+
59
+ const pick = (row) => {
60
+ setMessage("");
61
+ if (row.undo) return restore();
62
+ if (row.add) return onAdd();
63
+ setOpen({ card: row, step: "menu", selected: 0 });
64
+ };
65
+
66
+ const restore = () =>
67
+ run(async () => {
68
+ await onRestored(undo.entry);
69
+ setMessage(t("cards.restored", { card: cutToWidth(lineOf(undo.card), 40) }));
70
+ setUndo(null);
71
+ changed.current = true;
72
+ await load();
73
+ });
74
+
75
+ const remove = (card) =>
76
+ run(async () => {
77
+ const { entry } = await onDeleted([card.id]);
78
+ setOpen(null);
79
+ setUndo({ entry, card });
80
+ setQuery(""); // the whole list again, the way back on top
81
+ setSelected(2); // on the cards, past the way back and + Add cards: a second Enter can't undo it
82
+ setMessage(t("cards.deleted", { card: cutToWidth(lineOf(card), 40), days: TRASH_DAYS }));
83
+ changed.current = true;
84
+ await load();
85
+ });
86
+
87
+ const edit = (card, text) =>
88
+ run(async () => {
89
+ const fields = parseLine(text);
90
+ if (!fields.front) throw new Error(t("add.needFront"));
91
+ if (!fields.cloze && !fields.back.length) throw new Error(t("add.needBack"));
92
+ const { staleKeys } = await actions.updateCardIn(deck, card.id, fields);
93
+ await onEdited(staleKeys);
94
+ setOpen(null);
95
+ setMessage(t("add.fixed", { front: cutToWidth(plainFront(fields.front), 40) }));
96
+ changed.current = true;
97
+ await load();
98
+ });
99
+
100
+ const move = (card, to) =>
101
+ run(async () => {
102
+ const { moved } = await actions.moveCards(deck, [card.id], to);
103
+ if (!moved.length) throw new Error(t("cards.alreadyThere", { deck: to }));
104
+ setOpen(null);
105
+ setMessage(t("cards.moved", { card: cutToWidth(lineOf(card), 40), deck: to }));
106
+ changed.current = true;
107
+ await load();
108
+ });
109
+
110
+ useInput((input, key) => {
111
+ if (open) {
112
+ if (key.leftArrow && open.step === "menu") setOpen(null);
113
+ return;
114
+ }
115
+ if (key.escape) return query ? (setQuery(""), setSelected(0)) : onClose(changed.current);
116
+ if (key.upArrow) return setSelected((i) => Math.max(0, i - 1));
117
+ if (key.downArrow) return setSelected((i) => Math.min(rows.length - 1, i + 1));
118
+ if (key.return) return rows[selected] && pick(rows[selected]);
119
+ if (key.rightArrow) return rows[selected] && !rows[selected].add && !rows[selected].undo && pick(rows[selected]);
120
+ if (key.backspace || key.delete) return query && (setQuery((q) => q.slice(0, -1)), setSelected(0));
121
+ if (key.ctrl && input === "u") return setQuery("");
122
+ const text = input.replace(/[\u0000-\u001f\u007f]/g, "");
123
+ if (text && !key.ctrl && !key.meta) {
124
+ setQuery((q) => q + text);
125
+ setSelected(0);
126
+ setMessage("");
127
+ }
128
+ });
129
+
130
+ const frame = (title, body, hints, color = theme.accent) => html`
131
+ <${Fragment}>
132
+ <${Box} flexDirection="column" borderStyle="round" borderColor=${color} paddingX=${2} width=${panel}>
133
+ <${Text} bold color=${color}>${title}<//>
134
+ ${body}
135
+ ${message && html`<${Box} marginTop=${1}><${Text} color=${theme.good}>${message}<//><//>`}
136
+ ${error && html`<${Box} marginTop=${1}><${Text} color=${theme.bad}>${error}<//><//>`}
137
+ <//>
138
+ <${Box} paddingX=${1}><${KeyHints} text=${hints} /><//>
139
+ <//>
140
+ `;
141
+
142
+ if (open?.step === "edit")
143
+ return frame(
144
+ t("cards.editTitle", { deck }),
145
+ html`
146
+ <${Box} flexDirection="column" marginTop=${1}>
147
+ <${Text} dimColor>${t("cards.editHint")}<//>
148
+ <${Box} marginTop=${1}><${AnswerInput} plain escLeaves cardLine initial=${formatLine(open.card)} onSubmit=${(text) => edit(open.card, text)} onExit=${() => setOpen((o) => ({ ...o, step: "menu" }))} onChange=${() => setError("")} /><//>
149
+ <//>
150
+ `,
151
+ `${t("keyHints.tabPart")} · ${t("keyHints.addFixing")}`
152
+ );
153
+
154
+ if (open?.step === "move")
155
+ return frame(
156
+ t("cards.moveTitle", { card: cutToWidth(lineOf(open.card), 40) }),
157
+ html`<${Box} marginTop=${1}>${decks.length ? html`<${Choice} options=${decks.map((d) => ({ label: d.name, note: t("count.cards", { count: d.cards }) }))} selected=${open.selected} onMove=${(i) => setOpen((o) => ({ ...o, selected: i }))} onPick=${(i) => move(open.card, decks[i].name)} onCancel=${() => setOpen((o) => ({ ...o, step: "menu", selected: 1 }))} />` : html`<${Text}>${t("cards.noOtherDeck")}<//>`}<//>`,
158
+ choiceHints("back")
159
+ );
160
+
161
+ if (open?.step === "delete")
162
+ return frame(
163
+ t("cards.deleteQuestion", { card: cutToWidth(lineOf(open.card), 50) }),
164
+ html`
165
+ <${Box} flexDirection="column">
166
+ <${Text} dimColor>${t("cards.deleteNote", { days: TRASH_DAYS })}<//>
167
+ <${Box} marginTop=${1}><${Choice} options=${[{ label: t("decks.deleteYes"), danger: true }, { label: t("cards.deleteNo") }]} selected=${open.selected} onMove=${(i) => setOpen((o) => ({ ...o, selected: i }))} onPick=${(i) => (i === 0 ? remove(open.card) : setOpen((o) => ({ ...o, step: "menu", selected: 2 })))} onCancel=${() => setOpen((o) => ({ ...o, step: "menu", selected: 2 }))} /><//>
168
+ <//>
169
+ `,
170
+ choiceHints("cancel"),
171
+ theme.bad
172
+ );
173
+
174
+ if (open?.step === "menu") {
175
+ const options = [{ label: t("cards.editRow") }, { label: t("cards.moveRow") }, { label: t("cards.deleteRow"), danger: true }];
176
+ const steps = ["edit", "move", "delete"];
177
+ return frame(
178
+ cutToWidth(lineOf(open.card), panel - 8),
179
+ html`
180
+ <${Box} flexDirection="column">
181
+ ${open.card.example && html`<${Text} dimColor italic>“${open.card.example}”<//>`}
182
+ <${Box} marginTop=${1}><${Choice} options=${options} selected=${open.selected} onMove=${(i) => setOpen((o) => ({ ...o, selected: i }))} onPick=${(i) => setOpen((o) => ({ ...o, step: steps[i], selected: steps[i] === "delete" ? 1 : 0 }))} onCancel=${() => setOpen(null)} /><//>
183
+ <//>
184
+ `,
185
+ t("keyHints.choiceLeft", { choose: t("choice.keys") })
186
+ );
187
+ }
188
+
189
+ // the list, with the search on top
190
+ const top = Math.max(0, Math.min(selected - Math.floor(SHOWN / 2), rows.length - SHOWN));
191
+ const rowText = (row) => (row.undo ? t("cards.undoRow", { card: cutToWidth(lineOf(row.undo === true ? undo.card : row), 40) }) : row.add ? t("cards.addRow") : lineOf(row));
192
+ return frame(
193
+ t("cards.title", { deck, count: cards?.length ?? 0 }),
194
+ html`
195
+ <${Box} flexDirection="column">
196
+ <${Box} marginTop=${1}>
197
+ <${Box} flexShrink=${0}><${Text} dimColor>${t("languages.search")} <//><//>
198
+ <${Text} wrap="truncate-start">${query}<//>
199
+ <${Box} flexShrink=${0}><${Text} inverse> <//><//>
200
+ <//>
201
+ ${cards && query && !found.length && html`<${Text} dimColor wrap="truncate-end">${t("cards.noMatch", { query: cutToWidth(query, 20) })}<//>`}
202
+ <${Text} dimColor>${top > 0 ? " ↑" : " "}<//>
203
+ ${rows.slice(top, top + SHOWN).map((row, i) => {
204
+ const on = top + i === selected;
205
+ return html`<${Text} key=${row.id ?? (row.undo ? "undo" : "add")} color=${on ? theme.accent : row.undo || row.add ? theme.good : undefined} bold=${on} wrap="truncate-end">${on ? "❯" : " "} ${rowText(row)}<//>`;
206
+ })}
207
+ <${Text} dimColor>${top + SHOWN < rows.length ? " ↓" : " "}<//>
208
+ ${query && found.length > 0 && html`<${Text} dimColor>${t("cards.found", { count: found.length })}<//>`}
209
+ <//>
210
+ `,
211
+ t("keyHints.cards")
212
+ );
213
+ }
214
+
215
+ // /cards while several decks are practised together: which deck's cards (`mix`: "all" or names)
216
+ export function CardsDeckPick({ actions, mix, current, onPick, onClose }) {
217
+ const panel = usePanelWidth();
218
+ const [decks, setDecks] = useState(null);
219
+ const [selected, setSelected] = useState(0);
220
+ useEffect(() => {
221
+ actions.ownDecks().then((own) => {
222
+ const list = mix === "all" ? own : own.filter((d) => mix.includes(d.name));
223
+ setDecks(list);
224
+ setSelected(Math.max(0, list.findIndex((d) => d.name === current)));
225
+ }, () => setDecks([]));
226
+ }, []);
227
+ return html`
228
+ <${Fragment}>
229
+ <${Box} flexDirection="column" borderStyle="round" borderColor=${theme.accent} paddingX=${2} width=${panel}>
230
+ <${Text} bold color=${theme.accent}>${t("cards.whichDeck")}<//>
231
+ ${decks && html`<${Box} marginTop=${1}><${Choice} options=${decks.map((d) => ({ label: d.name, note: t("count.cards", { count: d.cards }) }))} selected=${selected} onMove=${setSelected} onPick=${(i) => onPick(decks[i].name)} onCancel=${onClose} /><//>`}
232
+ <//>
233
+ <${Box} paddingX=${1}><${KeyHints} text=${choiceHints("back")} /><//>
234
+ <//>
235
+ `;
236
+ }
package/src/ui/Choice.js CHANGED
@@ -1,14 +1,19 @@
1
+ import { useRef } from "react";
1
2
  import { Box, useInput } from "ink";
2
3
  import { t } from "../i18n.js";
3
4
  import { cellWidth, html, Text, theme, usePanelWidth } from "./kit.js";
4
5
 
5
6
  // A question's answers as a list: ↑/↓ and Enter, a number, or an option's own keys ("t|y" in Polish).
6
7
  // Each option: { label, note?, key?, danger? }; `danger` paints it red while it's chosen.
8
+ const SETTLE_MS = 300; // a pick right after the list appears is the second half of the Enter before it
9
+
7
10
  export function Choice({ options, selected, onMove, onPick, onCancel }) {
11
+ const shownAt = useRef(Date.now());
8
12
  useInput((input, key) => {
9
13
  if (key.escape) return onCancel?.();
10
14
  if (key.upArrow) return onMove(Math.max(0, selected - 1));
11
15
  if (key.downArrow) return onMove(Math.min(options.length - 1, selected + 1));
16
+ if (Date.now() - shownAt.current < SETTLE_MS && (key.return || /^\d$/.test(input))) return;
12
17
  if (key.return) return onPick(selected);
13
18
  const index = options.findIndex((o, i) => input === String(i + 1) || (o.key && o.key.split("|").includes(input.toLowerCase())));
14
19
  if (index >= 0) onPick(index);
@@ -24,7 +29,7 @@ export function Choice({ options, selected, onMove, onPick, onCancel }) {
24
29
  const on = i === selected;
25
30
  const color = on ? (o.danger ? theme.bad : theme.accent) : undefined;
26
31
  return html`
27
- <${Box} key=${o.label} flexDirection=${stacked ? "column" : "row"}>
32
+ <${Box} key=${`${i}:${o.label}`} flexDirection=${stacked ? "column" : "row"}>
28
33
  <${Box} flexShrink=${0}><${Text} color=${color} bold=${on}>${on ? "❯" : " "} ${i + 1}. ${stacked ? o.label : o.label + " ".repeat(width - cellWidth(o.label))}<//><//>
29
34
  ${o.note && html`<${Box} marginLeft=${stacked ? 5 : 0}><${Text} dimColor>${o.note}<//><//>`}
30
35
  <//>