dracosh 0.7.0 → 0.9.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/Cards.js CHANGED
@@ -1,6 +1,8 @@
1
1
  import { Fragment, useEffect, useRef, useState } from "react";
2
2
  import { Box, useInput } from "ink";
3
- import { t } from "../i18n.js";
3
+ import { language, t } from "../i18n.js";
4
+ import { providerName } from "../ai.js";
5
+ import { checkCard } from "../assist.js";
4
6
  import { formatLine, parseLine, plainFront } from "../cardline.js";
5
7
  import { fold } from "../judge.js";
6
8
  import { TRASH_DAYS } from "../library.js";
@@ -9,6 +11,9 @@ import { Choice, choiceHints } from "./Choice.js";
9
11
  import { cutToWidth, html, KeyHints, Text, theme, usePanelWidth } from "./kit.js";
10
12
 
11
13
  const SHOWN = 8; // rows of the list at a time
14
+ const SPIN = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
15
+ // a card's menu: checked first for a card written by AI help; a check by AI when it's set up
16
+ const menuOf = (card, ai) => [...(card.ai ? ["confirm"] : []), ...(ai && !card.cloze ? ["check"] : []), "edit", "move", "delete"];
12
17
 
13
18
  const look = (text) => fold(String(text).toLowerCase());
14
19
  const lineOf = (card) => (card.cloze ? plainFront(card.front) : `${card.front} = ${card.back.join("; ")}`);
@@ -19,7 +24,7 @@ const matches = (card, query) => !query || [card.front, ...card.back, card.examp
19
24
  // goes to the trash, and the row on top brings it straight back. `actions`: the library's;
20
25
  // `onDeleted`(cardIds) → { entry }, `onRestored`(entry), `onEdited`(staleKeys) let the app keep the
21
26
  // progress in step; `onAdd` opens /add for the deck; onClose(changed).
22
- export function Cards({ deck, actions, onDeleted, onRestored, onEdited, onAdd, onClose }) {
27
+ export function Cards({ deck, actions, onDeleted, onRestored, onEdited, onAdd, onClose, ai = null }) {
23
28
  const panel = usePanelWidth();
24
29
  const [cards, setCards] = useState(null);
25
30
  const [decks, setDecks] = useState([]); // your other decks, to move a card to
@@ -31,6 +36,16 @@ export function Cards({ deck, actions, onDeleted, onRestored, onEdited, onAdd, o
31
36
  const [error, setError] = useState("");
32
37
  const changed = useRef(false);
33
38
  const busy = useRef(false);
39
+ const checking = useRef(null); // the check by AI in flight: its AbortController
40
+ const [spin, setSpin] = useState(0);
41
+ const menuAt = (card, step) => menuOf(card, ai).indexOf(step);
42
+ const waiting = open?.step === "check" && !open.verdict;
43
+ useEffect(() => {
44
+ if (!waiting) return;
45
+ const timer = setInterval(() => setSpin((n) => n + 1), 100);
46
+ return () => clearInterval(timer);
47
+ }, [waiting]);
48
+ useEffect(() => () => checking.current?.abort(), []);
34
49
 
35
50
  const load = () => actions.cardsIn(deck).then(setCards, (err) => setError(err.message));
36
51
  useEffect(() => {
@@ -38,7 +53,9 @@ export function Cards({ deck, actions, onDeleted, onRestored, onEdited, onAdd, o
38
53
  actions.ownDecks().then((own) => setDecks(own.filter((d) => d.name !== deck)), () => {});
39
54
  }, []);
40
55
 
41
- const found = (cards ?? []).filter((card) => matches(card, query));
56
+ // the cards AI wrote and you haven't checked come first, in their own order
57
+ const found = (cards ?? []).filter((card) => matches(card, query)).sort((a, b) => Number(Boolean(b.ai)) - Number(Boolean(a.ai)));
58
+ const toCheck = (cards ?? []).filter((card) => card.ai).length;
42
59
  // the rows: bring back the card just deleted, add cards (with no search), then the cards found
43
60
  // (both only with no search: Enter on what's found never brings a card back by accident)
44
61
  const rows = [...(undo && !query ? [{ undo: true }] : []), ...(query ? [] : [{ add: true }]), ...found];
@@ -89,7 +106,8 @@ export function Cards({ deck, actions, onDeleted, onRestored, onEdited, onAdd, o
89
106
  const fields = parseLine(text);
90
107
  if (!fields.front) throw new Error(t("add.needFront"));
91
108
  if (!fields.cloze && !fields.back.length) throw new Error(t("add.needBack"));
92
- const { staleKeys } = await actions.updateCardIn(deck, card.id, fields);
109
+ // Enter on the card as it was keeps it marked as AI's: only a change or "It's right" checks it
110
+ const { staleKeys } = await actions.updateCardIn(deck, card.id, { ...fields, ai: card.ai && formatLine(fields) === formatLine(card) });
93
111
  await onEdited(staleKeys);
94
112
  setOpen(null);
95
113
  setMessage(t("add.fixed", { front: cutToWidth(plainFront(fields.front), 40) }));
@@ -97,6 +115,52 @@ export function Cards({ deck, actions, onDeleted, onRestored, onEdited, onAdd, o
97
115
  await load();
98
116
  });
99
117
 
118
+ const confirm = (card) =>
119
+ run(async () => {
120
+ await actions.confirmCardIn(deck, card.id);
121
+ setOpen(null);
122
+ setMessage(t("cards.confirmed", { card: cutToWidth(lineOf(card), 40) }));
123
+ changed.current = true;
124
+ await load();
125
+ });
126
+
127
+ // AI looks the card over: nothing wrong, or what is, with a fix to take or leave. One check at a time,
128
+ // and an answer that comes after Esc (or after the menu was left) changes nothing.
129
+ async function check(card) {
130
+ if (checking.current) return;
131
+ const controller = new AbortController();
132
+ checking.current = controller;
133
+ setError("");
134
+ setOpen((o) => ({ ...o, step: "check", verdict: null, selected: 0 }));
135
+ const name = providerName(ai.provider);
136
+ try {
137
+ const [languages, all] = await Promise.all([actions.languagesOf(deck).catch(() => ({})), actions.cardsIn(deck).catch(() => [])]);
138
+ const verdict = await checkCard(ai, { card, languages, cards: all, language: language(), signal: controller.signal });
139
+ if (controller.signal.aborted) return;
140
+ const still = (o) => o?.step === "check" && !o.verdict && o.card.id === card.id;
141
+ if (!verdict.ok) return setOpen((o) => (still(o) ? { ...o, verdict } : o));
142
+ // an AI card keeps its ✦: AI saying it's right isn't you checking it
143
+ setOpen((o) => (still(o) ? null : o));
144
+ setMessage(t("cards.checkOk", { provider: name, card: cutToWidth(lineOf(card), 40) }));
145
+ } catch (err) {
146
+ if (controller.signal.aborted) return;
147
+ setOpen((o) => (o?.step === "check" && !o.verdict ? { ...o, step: "menu", selected: menuAt(o.card, "check") } : o));
148
+ setError(err.code === "unreadable" ? t("cards.checkUnclear", { provider: name }) : err.message);
149
+ } finally {
150
+ if (checking.current === controller) checking.current = null;
151
+ }
152
+ }
153
+
154
+ const useFix = (card, fix) =>
155
+ run(async () => {
156
+ const { staleKeys } = await actions.updateCardIn(deck, card.id, fix);
157
+ await onEdited(staleKeys);
158
+ setOpen(null);
159
+ setMessage(t("add.fixed", { front: cutToWidth(plainFront(fix.front), 40) }));
160
+ changed.current = true;
161
+ await load();
162
+ });
163
+
100
164
  const move = (card, to) =>
101
165
  run(async () => {
102
166
  const { moved } = await actions.moveCards(deck, [card.id], to);
@@ -108,6 +172,14 @@ export function Cards({ deck, actions, onDeleted, onRestored, onEdited, onAdd, o
108
172
  });
109
173
 
110
174
  useInput((input, key) => {
175
+ if (open?.step === "check" && !open.verdict) {
176
+ if (key.escape || key.leftArrow) {
177
+ checking.current?.abort();
178
+ checking.current = null;
179
+ setOpen((o) => ({ ...o, step: "menu", selected: menuAt(o.card, "check") }));
180
+ }
181
+ return;
182
+ }
111
183
  if (open) {
112
184
  if (key.leftArrow && open.step === "menu") setOpen(null);
113
185
  return;
@@ -145,7 +217,7 @@ export function Cards({ deck, actions, onDeleted, onRestored, onEdited, onAdd, o
145
217
  html`
146
218
  <${Box} flexDirection="column" marginTop=${1}>
147
219
  <${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("")} /><//>
220
+ <${Box} marginTop=${1}><${AnswerInput} plain escLeaves cardLine initial=${formatLine(open.card)} onSubmit=${(text) => edit(open.card, text)} onExit=${() => setOpen((o) => ({ ...o, step: "menu", selected: menuAt(o.card, "edit") }))} onChange=${() => setError("")} /><//>
149
221
  <//>
150
222
  `,
151
223
  `${t("keyHints.tabPart")} · ${t("keyHints.addFixing")}`
@@ -154,7 +226,7 @@ export function Cards({ deck, actions, onDeleted, onRestored, onEdited, onAdd, o
154
226
  if (open?.step === "move")
155
227
  return frame(
156
228
  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")}<//>`}<//>`,
229
+ 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: menuAt(o.card, "move") }))} />` : html`<${Text}>${t("cards.noOtherDeck")}<//>`}<//>`,
158
230
  choiceHints("back")
159
231
  );
160
232
 
@@ -164,22 +236,51 @@ export function Cards({ deck, actions, onDeleted, onRestored, onEdited, onAdd, o
164
236
  html`
165
237
  <${Box} flexDirection="column">
166
238
  <${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 }))} /><//>
239
+ <${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: menuAt(o.card, "delete") })))} onCancel=${() => setOpen((o) => ({ ...o, step: "menu", selected: menuAt(o.card, "delete") }))} /><//>
168
240
  <//>
169
241
  `,
170
242
  choiceHints("cancel"),
171
243
  theme.bad
172
244
  );
173
245
 
246
+ if (open?.step === "check") {
247
+ const name = providerName(ai.provider);
248
+ const { verdict } = open;
249
+ const back = () => setOpen((o) => ({ ...o, step: "menu", verdict: null, selected: menuAt(o.card, "check") }));
250
+ return frame(
251
+ cutToWidth(lineOf(open.card), panel - 8),
252
+ verdict
253
+ ? html`
254
+ <${Box} flexDirection="column">
255
+ ${open.card.example && html`<${Text} dimColor italic>“${open.card.example}”<//>`}
256
+ <${Box} marginTop=${1}><${Box} flexShrink=${0}><${Text} color=${theme.accent}>✦ <//><//><${Text} color=${theme.accent}>${verdict.note || t("cards.checkFix", { provider: name })}<//><//>
257
+ <${Box} marginTop=${1} flexDirection="column" paddingLeft=${2}>
258
+ ${verdict.fix && html`<${Fixed} card=${open.card} fix=${verdict.fix} />`}
259
+ <//>
260
+ <${Box} marginTop=${1}><${Choice} options=${verdict.fix ? [{ label: t("cards.useFix") }, { label: t("cards.keepMine") }] : [{ label: t("cards.keepMine") }]} selected=${open.selected} onMove=${(i) => setOpen((o) => ({ ...o, selected: i }))} onPick=${(i) => (verdict.fix && i === 0 ? useFix(open.card, verdict.fix) : back())} onCancel=${back} /><//>
261
+ <//>
262
+ `
263
+ : html`
264
+ <${Box} flexDirection="column">
265
+ ${open.card.example && html`<${Text} dimColor italic>“${open.card.example}”<//>`}
266
+ <${Box} marginTop=${1}><${Text} color=${theme.accent}>${SPIN[spin % SPIN.length]} ${t("cards.checking", { provider: name })}<//><//>
267
+ <//>
268
+ `,
269
+ verdict ? choiceHints("back") : t("keyHints.aiWaiting")
270
+ );
271
+ }
272
+
174
273
  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"];
274
+ const steps = menuOf(open.card, ai);
275
+ const labels = { confirm: t("cards.confirmRow"), check: t("cards.checkRow"), edit: t("cards.editRow"), move: t("cards.moveRow"), delete: t("cards.deleteRow") };
276
+ const options = steps.map((step) => ({ label: labels[step], danger: step === "delete" }));
177
277
  return frame(
178
278
  cutToWidth(lineOf(open.card), panel - 8),
179
279
  html`
180
280
  <${Box} flexDirection="column">
181
281
  ${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)} /><//>
282
+ ${open.card.ai && html`<${Box} marginTop=${1}><${Text} color=${theme.accent}>${t("cards.aiNote")}<//><//>`}
283
+ <${Box} marginTop=${1}><${Choice} options=${options} selected=${open.selected} onMove=${(i) => setOpen((o) => ({ ...o, selected: i }))} onPick=${(i) => (steps[i] === "confirm" ? confirm(open.card) : steps[i] === "check" ? check(open.card) : setOpen((o) => ({ ...o, step: steps[i], selected: steps[i] === "delete" ? 1 : 0 })))} onCancel=${() => setOpen(null)} /><//>
183
284
  <//>
184
285
  `,
185
286
  t("keyHints.choiceLeft", { choose: t("choice.keys") })
@@ -188,9 +289,10 @@ export function Cards({ deck, actions, onDeleted, onRestored, onEdited, onAdd, o
188
289
 
189
290
  // the list, with the search on top
190
291
  const top = Math.max(0, Math.min(selected - Math.floor(SHOWN / 2), rows.length - SHOWN));
292
+ const gutter = (cards ?? []).some((card) => card.ai); // room for a ✦ before every card, so they line up
191
293
  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
294
  return frame(
193
- t("cards.title", { deck, count: cards?.length ?? 0 }),
295
+ html`<${Fragment}>${t("cards.title", { deck, count: cards?.length ?? 0 })}${toCheck > 0 ? html`<${Text} bold=${false}> ${t("cards.toCheck", { count: toCheck })}<//>` : ""}<//>`,
194
296
  html`
195
297
  <${Box} flexDirection="column">
196
298
  <${Box} marginTop=${1}>
@@ -202,7 +304,7 @@ export function Cards({ deck, actions, onDeleted, onRestored, onEdited, onAdd, o
202
304
  <${Text} dimColor>${top > 0 ? " ↑" : " "}<//>
203
305
  ${rows.slice(top, top + SHOWN).map((row, i) => {
204
306
  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)}<//>`;
307
+ 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 ? "❯" : " "} ${row.ai ? html`<${Text} color=${theme.accent}>✦ <//>` : gutter && row.id ? " " : ""}${rowText(row)}<//>`;
206
308
  })}
207
309
  <${Text} dimColor>${top + SHOWN < rows.length ? " ↓" : " "}<//>
208
310
  ${query && found.length > 0 && html`<${Text} dimColor>${t("cards.found", { count: found.length })}<//>`}
@@ -212,6 +314,18 @@ export function Cards({ deck, actions, onDeleted, onRestored, onEdited, onAdd, o
212
314
  );
213
315
  }
214
316
 
317
+ // the card as AI would fix it, what it changes in the accent colour
318
+ function Fixed({ card, fix }) {
319
+ const changed = (on) => (on ? theme.accent : undefined);
320
+ const parts = fix.back.map((answer, i) => html`<${Text} key=${i} color=${changed(!card.back.includes(answer))}>${i ? "; " : ""}${answer}<//>`);
321
+ return html`
322
+ <${Box} flexDirection="column">
323
+ <${Text} bold wrap="truncate-end"><${Text} color=${changed(fix.front !== card.front)}>${fix.front}<//> = ${parts}<//>
324
+ ${fix.example && html`<${Text} italic color=${changed(fix.example !== (card.example ?? ""))} dimColor=${fix.example === (card.example ?? "")}>“${fix.example}”<//>`}
325
+ <//>
326
+ `;
327
+ }
328
+
215
329
  // /cards while several decks are practised together: which deck's cards (`mix`: "all" or names)
216
330
  export function CardsDeckPick({ actions, mix, current, onPick, onClose }) {
217
331
  const panel = usePanelWidth();
@@ -2,7 +2,7 @@ import { t } from "../i18n.js";
2
2
  import { Fragment } from "react";
3
3
  import { Box, useInput } from "ink";
4
4
  import { dragonName, elementName, STAGES } from "../progress.js";
5
- import { html, KeyHints, Text, theme, usePanelWidth } from "./kit.js";
5
+ import { html, KeyHints, readable, Text, theme, usePanelWidth } from "./kit.js";
6
6
  import { ELEMENT_COLOR, Mascot } from "./Mascot.js";
7
7
 
8
8
  const requirement = (stage, locked) => (stage.from === 0 ? t("companion.fromStart") : t(locked ? "companion.needsDays" : "companion.days", { count: stage.from }));
@@ -21,7 +21,7 @@ export function Companion({ current, best, element = null, roll = null, onClose
21
21
  <${Text} bold color=${theme.accent}>${t("companion.title")}<//>
22
22
  <${Box} marginTop=${1}>
23
23
  <${Text}>${t("companion.yourDragon")}<//>
24
- <${Text} bold color=${element ? ELEMENT_COLOR[element] : undefined}>${dragonName(current, element)}<//>
24
+ <${Text} bold color=${element ? readable(ELEMENT_COLOR[element]) : undefined}>${dragonName(current, element)}<//>
25
25
  <//>
26
26
  <${Text} dimColor>${element ? `${t("companion.element", { element: elementName(element) })}${roll ? t("companion.rolled", { face: roll.face, day: roll.on }) : ""}` : t("companion.noElement")}<//>
27
27
  <${Box} marginTop=${1}><${Text} dimColor>${t("companion.evolves", { count: best })}<//><//>
@@ -4,7 +4,7 @@ import { html, Text, theme } from "./kit.js";
4
4
 
5
5
  const ROWS = 4;
6
6
  const FRAME_MS = 100;
7
- const COLORS = [theme.accent, theme.good, theme.warn, "#7dd3fc", "#f0abfc"];
7
+ const COLORS = ["accent", "good", "warn", "sky", "pink"]; // theme colors
8
8
  const GLYPHS = ["▪", "▘", "▝", "▖", "▗", "•"];
9
9
 
10
10
  // A short burst of falling pixels over the card, played once when the daily goal lands.
@@ -36,7 +36,7 @@ export function Confetti({ width, onDone }) {
36
36
  for (const p of here) {
37
37
  if (p.col < at) continue; // two particles on one cell: draw the first
38
38
  cells.push(html`<${Text} key=${`g${p.col}`}>${" ".repeat(p.col - at)}<//>`);
39
- cells.push(html`<${Text} key=${`p${p.col}`} color=${p.color}>${p.glyph}<//>`);
39
+ cells.push(html`<${Text} key=${`p${p.col}`} color=${theme[p.color]}>${p.glyph}<//>`);
40
40
  at = p.col + 1;
41
41
  }
42
42
  return html`<${Text} key=${r}>${cells.length ? cells : " "}<//>`;
package/src/ui/DieRoll.js CHANGED
@@ -2,7 +2,7 @@ import { t } from "../i18n.js";
2
2
  import React, { Fragment, useEffect, useState } from "react";
3
3
  import { Box, useInput } from "ink";
4
4
  import { elementName, ELEMENTS } from "../progress.js";
5
- import { html, KeyHints, Text, theme, usePanelWidth } from "./kit.js";
5
+ import { html, KeyHints, readable, Text, theme, usePanelWidth } from "./kit.js";
6
6
  import { ELEMENT_COLOR, Mascot } from "./Mascot.js";
7
7
 
8
8
  const FRAME_MS = 80;
@@ -26,9 +26,9 @@ const BOUNCE = [2, 1, 0, 0, 1, 2, 2, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0];
26
26
 
27
27
  function dieGrid(face, pipColor) {
28
28
  const last = SIZE - 1;
29
- const grid = Array.from({ length: SIZE }, (_, r) => Array.from({ length: SIZE }, (_, c) => ((r === 0 || r === last) && (c === 0 || c === last) ? null : "#f4f4f5")));
30
- for (let r = 1; r < last; r++) grid[r][last] = "#c7c9d1"; // a shaded edge
31
- for (let c = 1; c < last; c++) grid[last][c] = "#c7c9d1";
29
+ const grid = Array.from({ length: SIZE }, (_, r) => Array.from({ length: SIZE }, (_, c) => ((r === 0 || r === last) && (c === 0 || c === last) ? null : theme.dieFace)));
30
+ for (let r = 1; r < last; r++) grid[r][last] = theme.dieEdge; // a shaded edge
31
+ for (let c = 1; c < last; c++) grid[last][c] = theme.dieEdge;
32
32
  for (const pip of FACES[face]) {
33
33
  const [r, c] = PIPS[pip];
34
34
  grid[r][c] = pipColor;
@@ -81,7 +81,7 @@ export function DieRoll({ element, stage = 0, onClose, play = () => {} }) {
81
81
  <${Text} bold color=${theme.warn}>${t("die.title")}<//>
82
82
  <${Box} marginTop=${1} alignItems="flex-end">
83
83
  <${Box} flexDirection="column" marginBottom=${bounce} marginRight=${4}>
84
- <${BigGrid} grid=${dieGrid(face, landed ? color : "#2a2440")} />
84
+ <${BigGrid} grid=${dieGrid(face, landed ? color : theme.diePips)} />
85
85
  <//>
86
86
  <${Box} flexDirection="column">
87
87
  <${Mascot} stage=${stage} face=${revealed ? "happy" : "idle"} flash=${FLASH_FRAMES.includes(frame)} element=${revealed ? element : null} scale=${2} />
@@ -91,7 +91,7 @@ export function DieRoll({ element, stage = 0, onClose, play = () => {} }) {
91
91
  ${revealed
92
92
  ? html`
93
93
  <${Fragment}>
94
- <${Text} bold color=${color}>${t("die.result", { face: result, element: elementName(element) })}<//>
94
+ <${Text} bold color=${readable(color)}>${t("die.result", { face: result, element: elementName(element) })}<//>
95
95
  <${Text} dimColor>${t("die.awakened", { element: elementName(element) })}<//>
96
96
  <//>
97
97
  `
package/src/ui/Import.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { Fragment, useEffect, useRef, useState } from "react";
2
2
  import { Box, useInput } from "ink";
3
3
  import { homedir } from "node:os";
4
- import { basename, resolve } from "node:path";
4
+ import { basename, posix, win32 } from "node:path";
5
5
  import { fileURLToPath } from "node:url";
6
6
  import { t } from "../i18n.js";
7
7
  import { plainFront } from "../cardline.js";
@@ -16,20 +16,20 @@ const SHOWN = 3; // cards of each deck, changed cards and lines that can't be ad
16
16
  const SETTLE_MS = 400; // a key right after a screen appears is the second half of the Enter before it
17
17
 
18
18
  // A path as a terminal pastes a file dragged into it: in quotes, with its spaces escaped, or as a
19
- // file:// address; "~" is your home folder
20
- export function cleanPath(typed) {
19
+ // file:// address; "~" is your home folder. On Windows a backslash separates folders, never escapes.
20
+ export function cleanPath(typed, { windows = process.platform === "win32" } = {}) {
21
21
  let path = typed.trim();
22
22
  if (/^(['"]).*\1$/.test(path)) path = path.slice(1, -1);
23
- else path = path.replace(/\\(.)/g, "$1");
23
+ else if (!windows) path = path.replace(/\\(.)/g, "$1");
24
24
  if (path.startsWith("file://")) {
25
25
  try {
26
- path = fileURLToPath(path);
26
+ path = fileURLToPath(path, { windows });
27
27
  } catch {
28
28
  // not a file address after all: read as typed
29
29
  }
30
30
  }
31
- if (path === "~" || path.startsWith("~/")) path = homedir() + path.slice(1);
32
- return path && resolve(path);
31
+ if (path === "~" || path.startsWith("~/") || (windows && path.startsWith("~\\"))) path = homedir() + path.slice(1);
32
+ return path && (windows ? win32 : posix).resolve(path);
33
33
  }
34
34
 
35
35
  const answers = (back) => back.join("; ");
package/src/ui/Preview.js CHANGED
@@ -18,7 +18,7 @@ import { Evolution } from "./Evolution.js";
18
18
  import { Hatch } from "./Hatch.js";
19
19
  import { Welcome } from "./Welcome.js";
20
20
  import { Header, Snore, useBlink, useMove } from "./Header.js";
21
- import { html, KeyHints, Text, theme, usePanelWidth } from "./kit.js";
21
+ import { applyTheme, html, KeyHints, Text, theme, themeName, usePanelWidth } from "./kit.js";
22
22
  import { Mascot } from "./Mascot.js";
23
23
  import { Stats } from "./Stats.js";
24
24
  import { Summary } from "./Summary.js";
@@ -210,13 +210,14 @@ const SCENES = [
210
210
  ...["mascot", "quiz", "add", "reveal", "cloze", "quiz-look", "unlock", "the-one", "die", "confetti", "stats", "badges", "summary"].map((id) => scene(id))
211
211
  ];
212
212
 
213
- function Menu({ selected, onMove, onPick, onQuit }) {
213
+ function Menu({ selected, onMove, onPick, onTheme, onQuit }) {
214
214
  const panel = usePanelWidth();
215
215
  useInput((input, key) => {
216
216
  if (key.escape || input === "q") return onQuit();
217
217
  if (key.upArrow) return onMove(-1);
218
218
  if (key.downArrow) return onMove(1);
219
219
  if (key.return) onPick();
220
+ if (input === "t") onTheme();
220
221
  });
221
222
  return html`
222
223
  <${Fragment}>
@@ -241,11 +242,13 @@ function Menu({ selected, onMove, onPick, onQuit }) {
241
242
  }
242
243
 
243
244
  // `dracosh --preview`: a gallery of every scene and animation, to look at without playing for weeks.
244
- export function Preview({ alerts }) {
245
+ export function Preview({ alerts, theme: saved }) {
245
246
  const { exit } = useApp();
246
247
  const [selected, setSelected] = useState(0);
247
248
  const [scene, setScene] = useState(null);
248
249
  const [run, setRun] = useState(0); // a fresh key per play, so every scene starts from its first frame
250
+ const [look, setLook] = useState(() => themeName(saved)); // t flips between dark and light
251
+ applyTheme(look);
249
252
  const back = () => setScene(null);
250
253
  const history = useMemo(() => fakeSession({ progress: true }), []);
251
254
  const quizSession = useMemo(() => fakeSession(), [run]); // every quiz run starts from zero
@@ -261,7 +264,7 @@ export function Preview({ alerts }) {
261
264
  }
262
265
 
263
266
  if (!scene) {
264
- return wrap(html`<${Menu} selected=${selected} onMove=${(d) => setSelected((s) => (s + d + SCENES.length) % SCENES.length)} onPick=${pick} onQuit=${exit} />`);
267
+ return wrap(html`<${Menu} selected=${selected} onMove=${(d) => setSelected((s) => (s + d + SCENES.length) % SCENES.length)} onPick=${pick} onTheme=${() => setLook((name) => (name === "dark" ? "light" : "dark"))} onQuit=${exit} />`);
265
268
  }
266
269
  if (scene === "hatch") return wrap(html`<${Hatch} key=${run} play=${alerts.play} onDone=${back} />`);
267
270
  if (scene.startsWith("evolve-")) {
@@ -287,10 +290,10 @@ export function Preview({ alerts }) {
287
290
  if (scene === "reveal" || scene === "cloze") {
288
291
  const words = scene === "reveal" ? DEMO_SENTENCES : DEMO_CLOZE;
289
292
  const session = fakeSession({ words, deck: { name: "Demo", directions: "forward" } });
290
- return html`<${App} key=${run} session=${session} deck="Demo" initialSettings=${{ ...DEFAULTS, dailyGoal: 5, everyMs: 6000, tips: "off", rhythm: "session" }} alerts=${alerts} persistSettings=${async () => {}} onExit=${back} />`;
293
+ return html`<${App} key=${run} session=${session} deck="Demo" initialSettings=${{ ...DEFAULTS, dailyGoal: 5, everyMs: 6000, tips: "off", rhythm: "session", theme: look }} alerts=${alerts} persistSettings=${async () => {}} onExit=${back} />`;
291
294
  }
292
295
  if (scene === "quiz") {
293
- return html`<${App} key=${run} session=${quizSession} deck="Demo" initialSettings=${{ ...DEFAULTS, dailyGoal: 5, everyMs: 6000, tips: "always" }} alerts=${alerts} persistSettings=${async () => {}} onExit=${back} />`;
296
+ return html`<${App} key=${run} session=${quizSession} deck="Demo" initialSettings=${{ ...DEFAULTS, dailyGoal: 5, everyMs: 6000, tips: "always", theme: look }} alerts=${alerts} persistSettings=${async () => {}} onExit=${back} />`;
294
297
  }
295
298
  return null;
296
299
  }
@@ -1,8 +1,11 @@
1
1
  import { Fragment, useState } from "react";
2
2
  import { Box, useInput } from "ink";
3
3
  import { language, LANGUAGES, t } from "../i18n.js";
4
- import { GOALS, INTERVALS, QUIET_PRESETS, RHYTHMS, TIP_MODES, VOLUMES, formatInterval } from "../settings.js";
4
+ import { GOALS, INTERVALS, QUIET_PRESETS, RHYTHMS, THEMES, TIP_MODES, VOLUMES, formatInterval } from "../settings.js";
5
5
  import { formatQuiet } from "../quiet.js";
6
+ import { aiCostLabel } from "../ai.js";
7
+ import { PLAYS_SOUNDS } from "../player.js";
8
+ import { voiceLabel } from "../voice.js";
6
9
  import { languageName } from "../language.js";
7
10
  import { elementName } from "../progress.js";
8
11
  import { Bar, html, KeyHints, Text, theme, usePanelWidth } from "./kit.js";
@@ -14,12 +17,15 @@ function VolumeValue({ value }) {
14
17
  // label and hint come from settings.rows.<key> in the locale
15
18
  const ALL_ROWS = [
16
19
  { key: "language", options: Object.keys(LANGUAGES), format: (code) => LANGUAGES[code] },
20
+ { key: "theme", options: THEMES, format: (v) => t(`settings.themes.${v}`) },
17
21
  { key: "homeLanguage", action: true, format: (code) => languageName(code) ?? t("settings.notSet") },
22
+ { key: "ai", action: true, format: aiCostLabel },
18
23
  { key: "rhythm", options: RHYTHMS, format: (v) => t(`settings.rhythms.${v}`) },
19
24
  { key: "everyMs", options: INTERVALS, format: formatInterval },
20
- { key: "sound", options: [true, false], format: (v) => t(v ? "settings.on" : "settings.off"), toggle: true },
21
- { key: "speak", options: [false, true], format: (v) => t(v ? "settings.on" : "settings.off"), toggle: true },
22
- { key: "volume", options: VOLUMES, format: (v) => html`<${VolumeValue} value=${v} />` },
25
+ { key: "sound", options: [true, false], format: (v) => t(v ? "settings.on" : "settings.off"), toggle: true, onlyWith: "sounds" },
26
+ { key: "speak", options: [false, true], format: (v) => t(v ? "settings.on" : "settings.off"), toggle: true, onlyWith: "sounds" },
27
+ { key: "voice", action: true, format: voiceLabel, onlyWith: "sounds" },
28
+ { key: "volume", options: VOLUMES, format: (v) => html`<${VolumeValue} value=${v} />`, onlyWith: "sounds" },
23
29
  { key: "dailyGoal", options: GOALS, format: (n) => t("settings.goal", { n }) },
24
30
  { key: "tips", options: TIP_MODES, format: (v) => t(`settings.tipModes.${v}`) },
25
31
  { key: "skipWeekends", options: [true, false], format: (v) => t(v ? "settings.weekendsRest" : "settings.weekendsCount"), toggle: true },
@@ -40,7 +46,8 @@ const nearestIndex = (options, value) => {
40
46
  // `startRow` and `onRow`: the row to open on, and each row moved to, so a screen opened from a row
41
47
  // comes back to it
42
48
  // `element`: the dragon's element, if the die gave it one (the row to go back to the default look)
43
- export function Settings({ settings, element = null, onChange, onClose, onAction, startRow = 0, onRow = () => {} }) {
49
+ // `sounds`: whether this system plays sounds (Windows doesn't: no Sound, Read aloud, Voice or Volume rows)
50
+ export function Settings({ settings, element = null, sounds = PLAYS_SOUNDS, onChange, onClose, onAction, startRow = 0, onRow = () => {} }) {
44
51
  const panel = usePanelWidth();
45
52
  const [row, setRowState] = useState(startRow);
46
53
  const setRow = (next) => setRowState((r) => {
@@ -48,7 +55,7 @@ export function Settings({ settings, element = null, onChange, onClose, onAction
48
55
  onRow(value);
49
56
  return value;
50
57
  });
51
- const ROWS = (onAction ? ALL_ROWS : ALL_ROWS.filter((item) => !item.action)).filter((item) => item.onlyWith !== "element" || element);
58
+ const ROWS = (onAction ? ALL_ROWS : ALL_ROWS.filter((item) => !item.action)).filter((item) => (item.onlyWith === "element" ? element : item.onlyWith === "sounds" ? sounds : true));
52
59
  const values = { ...settings, language: settings.language ?? language(), dragonLook: element };
53
60
  const labelWidth = Math.max(...ROWS.map((item) => label(item).length)) + 2;
54
61
 
@@ -76,7 +83,7 @@ export function Settings({ settings, element = null, onChange, onClose, onAction
76
83
  (item, i) => html`
77
84
  <${Box} key=${item.key}>
78
85
  <${Box} flexShrink=${0}><${Text} color=${i === row ? theme.accent : undefined} bold=${i === row}>${i === row ? "❯" : " "} ${label(item).padEnd(labelWidth)}<//><//>
79
- <${Text} color=${i === row ? theme.accent : undefined}>${i === row && !item.action ? "❮ " : " "}${item.format(values[item.key])}${i === row && !item.action ? " ❯" : ""}<//>
86
+ <${Text} wrap="truncate-end" color=${i === row ? theme.accent : undefined}>${i === row && !item.action ? "❮ " : " "}${item.format(values[item.key])}${i === row && !item.action ? " ❯" : ""}<//>
80
87
  <//>
81
88
  `
82
89
  )}
package/src/ui/Stats.js CHANGED
@@ -6,22 +6,12 @@ import { formatRange } from "../vacation.js";
6
6
  import { html, KeyHints, Text, theme, usePanelWidth } from "./kit.js";
7
7
 
8
8
  // One shape for every day; only the color tells them apart, GitHub-contribution style.
9
- const TILE = {
10
- goal: theme.good,
11
- halfway: "#3f9d5e",
12
- some: "#2f6b45",
13
- none: "#3a3f47",
14
- rest: "#2a2e35",
15
- future: "#1c1f25",
16
- today: theme.accent // today with nothing done yet
17
- };
18
-
19
9
  function tileColor(cell, goal) {
20
- if (cell.goalMet) return TILE.goal;
21
- if (cell.correct > 0) return cell.correct >= goal / 2 ? TILE.halfway : TILE.some;
22
- if (cell.today) return TILE.today;
23
- if (cell.future) return TILE.future;
24
- return cell.rest ? TILE.rest : TILE.none;
10
+ if (cell.goalMet) return theme.good;
11
+ if (cell.correct > 0) return cell.correct >= goal / 2 ? theme.dayHalfway : theme.daySome;
12
+ if (cell.today) return theme.accent; // today with nothing done yet
13
+ if (cell.future) return theme.dayFuture;
14
+ return cell.rest ? theme.dayRest : theme.dayNone;
25
15
  }
26
16
 
27
17
  // A plain full-month grid: weeks as rows under one-letter day headers.
@@ -48,12 +38,12 @@ function Calendar({ month, goal }) {
48
38
 
49
39
  function Legend({ goal }) {
50
40
  const items = [
51
- [TILE.goal, t("stats.legend.goal", { goal })],
52
- [TILE.halfway, t("stats.legend.halfway")],
53
- [TILE.some, t("stats.legend.some")],
54
- [TILE.none, t("stats.legend.none")],
55
- [TILE.rest, t("stats.legend.rest")],
56
- [TILE.today, t("stats.legend.today")]
41
+ [theme.good, t("stats.legend.goal", { goal })],
42
+ [theme.dayHalfway, t("stats.legend.halfway")],
43
+ [theme.daySome, t("stats.legend.some")],
44
+ [theme.dayNone, t("stats.legend.none")],
45
+ [theme.dayRest, t("stats.legend.rest")],
46
+ [theme.accent, t("stats.legend.today")]
57
47
  ];
58
48
  // a box per item, so a longer language wraps whole items instead of splitting one
59
49
  return html`
package/src/ui/TheOne.js CHANGED
@@ -2,7 +2,7 @@ import { t } from "../i18n.js";
2
2
  import React, { Fragment, useEffect, useState } from "react";
3
3
  import { Box, useInput } from "ink";
4
4
  import { RING } from "./icons.js";
5
- import { html, KeyHints, Text, theme, usePanelWidth } from "./kit.js";
5
+ import { html, KeyHints, readable, Text, theme, usePanelWidth } from "./kit.js";
6
6
 
7
7
  const FRAME_MS = 110;
8
8
  const WIDTH = 16; // pixels; each is drawn two characters wide
@@ -109,7 +109,7 @@ export function TheOne({ onClose, play = () => {} }) {
109
109
  ${revealed
110
110
  ? html`
111
111
  <${Fragment}>
112
- <${Text} bold color=${RING.palette.G}>${t("theOne.title")}<//>
112
+ <${Text} bold color=${readable(RING.palette.G)}>${t("theOne.title")}<//>
113
113
  <${Text} dimColor>${t("theOne.line")}<//>
114
114
  <//>
115
115
  `