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/Ai.js ADDED
@@ -0,0 +1,284 @@
1
+ import { Fragment, useEffect, useRef, useState } from "react";
2
+ import { Box, useInput } from "ink";
3
+ import { t } from "../i18n.js";
4
+ import { aiLabel, checkAi, cleanUrl, findKey, forgetKey, isSmallModel, isUrl, listModels, maskKey, PROVIDERS, providerName, saveKey, urlOf } from "../ai.js";
5
+ import { fold } from "../judge.js";
6
+ import { AnswerInput } from "./AnswerInput.js";
7
+ import { Choice, choiceHints } from "./Choice.js";
8
+ import { cutToWidth, html, KeyHints, Text, theme, usePanelWidth } from "./kit.js";
9
+
10
+ const ORDER = ["anthropic", "openai", "openrouter", "ollama", "lmstudio", "custom"];
11
+ const SHOWN = 8; // models listed at a time
12
+ const look = (text) => fold(text.toLowerCase());
13
+
14
+ // /settings → AI help: where it comes from (provider, the address for "other"), the key, the model, then
15
+ // a tiny request to check they work together; only then is anything saved. `current`: settings.ai.
16
+ // onSave(ai | null) keeps the choice (null: AI off). Esc goes back a step, from the first one it leaves.
17
+ export function AiSetup({ current, onSave, onClose, note = t("ai.note") }) {
18
+ const panel = usePanelWidth();
19
+ const [step, setStep] = useState("provider");
20
+ const [selected, setSelected] = useState(() => Math.max(0, ORDER.indexOf(current?.provider)));
21
+ const [draft, setDraft] = useState(current ?? {}); // { provider, url?, model }
22
+ const [key, setKey] = useState(null); // { key, from: "env" | "saved" | "typed", env? }
23
+ const [models, setModels] = useState(null);
24
+ const [query, setQuery] = useState("");
25
+ const [error, setError] = useState("");
26
+ const [message, setMessage] = useState("");
27
+ const history = useRef([]);
28
+ const job = useRef(0); // a newer step makes an older request's answer stale
29
+
30
+ // Esc goes back along the steps taken; going to a step taken before cuts the way back to it, and the
31
+ // passing steps (checking, failed) are never gone back to
32
+ const go = (next, pick = 0) => {
33
+ const at = history.current.indexOf(next);
34
+ if (at >= 0) history.current = history.current.slice(0, at);
35
+ else if (step !== next && step !== "checking" && step !== "failed") history.current.push(step);
36
+ setError("");
37
+ setMessage("");
38
+ setSelected(pick);
39
+ setStep(next);
40
+ };
41
+ const back = () => {
42
+ job.current += 1;
43
+ setError("");
44
+ setMessage("");
45
+ const last = history.current.pop();
46
+ if (!last) return onClose();
47
+ setSelected(last === "provider" ? Math.max(0, ORDER.indexOf(draft.provider)) : 0);
48
+ setStep(last);
49
+ };
50
+ // after a step's answer arrives: still the step it was asked on?
51
+ const stillOn = () => {
52
+ const mine = ++job.current;
53
+ return () => mine === job.current;
54
+ };
55
+
56
+ const preset = PROVIDERS[draft.provider];
57
+
58
+ async function pickProvider(index) {
59
+ if (index === ORDER.length) {
60
+ onSave(null);
61
+ return onClose(t("ai.turnedOff"));
62
+ }
63
+ const provider = ORDER[index];
64
+ const same = current?.provider === provider;
65
+ // a local server moved to another port keeps its address
66
+ const next = { provider, url: same ? current.url : undefined, model: same ? current.model : PROVIDERS[provider].model };
67
+ setDraft(next);
68
+ if (provider === "custom") return go("url");
69
+ if (PROVIDERS[provider].local) return setKey(null), loadModels(next, null);
70
+ await askForKey(next);
71
+ }
72
+
73
+ // the key: the environment's is used as it is, a saved one can stay, be replaced or go
74
+ async function askForKey(next) {
75
+ const fresh = stillOn();
76
+ const found = await findKey(next.provider, urlOf(next));
77
+ if (!fresh()) return;
78
+ setKey(found);
79
+ if (found?.from === "env") return loadModels(next, found);
80
+ go(found ? "keep-key" : "key");
81
+ }
82
+
83
+ async function loadModels(target = draft, withKey = key) {
84
+ go("models");
85
+ const fresh = stillOn();
86
+ setModels(null);
87
+ setQuery("");
88
+ try {
89
+ const list = await listModels(target, { key: withKey?.key ?? null });
90
+ if (!fresh()) return;
91
+ // where you pay per use, the small, cheap models come first
92
+ const sorted = !PROVIDERS[target.provider].needsKey ? list : [...list.filter(isSmallModel), ...list.filter((name) => !isSmallModel(name))];
93
+ setModels(sorted);
94
+ setSelected(Math.max(0, sorted.indexOf(target.model ?? PROVIDERS[target.provider].model)));
95
+ } catch (err) {
96
+ if (!fresh()) return;
97
+ // a key or an address to fix: back where it's typed, the reason with it
98
+ const fixAt = ["badKey", "noKey"].includes(err.code) && withKey?.from !== "env" && !PROVIDERS[target.provider].local ? "key" : err.code === "noApi" && target.provider === "custom" ? "url" : null;
99
+ setModels([]);
100
+ if (fixAt) {
101
+ const at = history.current.indexOf(fixAt);
102
+ if (at >= 0) history.current = history.current.slice(0, at);
103
+ setSelected(0);
104
+ setStep(fixAt);
105
+ }
106
+ setError(err.message);
107
+ }
108
+ }
109
+
110
+ async function check(model) {
111
+ const chosen = { provider: draft.provider, model, ...(draft.url ? { url: cleanUrl(draft.url) } : {}) };
112
+ setDraft(chosen);
113
+ go("checking");
114
+ const fresh = stillOn();
115
+ try {
116
+ await checkAi(chosen, { key: key?.key ?? null });
117
+ if (!fresh()) return;
118
+ if (key?.from === "typed") await saveKey(chosen.provider, key.key, urlOf(chosen));
119
+ onSave(chosen);
120
+ onClose(t("ai.ready", { label: aiLabel(chosen) }));
121
+ } catch (err) {
122
+ if (!fresh()) return;
123
+ setError(err.message);
124
+ setStep("failed");
125
+ setSelected(0);
126
+ }
127
+ }
128
+
129
+ const found = (models ?? []).filter((name) => !query || look(name).includes(look(query)));
130
+ const rows = [...found, null]; // null: type a name
131
+
132
+ useInput((input, key) => {
133
+ if ((step === "checking" || (step === "models" && models === null)) && key.escape) return back();
134
+ if (step !== "models" || models === null) return;
135
+ if (key.escape) return query ? (setQuery(""), setSelected(0)) : back();
136
+ if (key.upArrow) return setSelected((i) => Math.max(0, i - 1));
137
+ if (key.downArrow) return setSelected((i) => Math.min(rows.length - 1, i + 1));
138
+ if (key.return) return rows[selected] === null ? go("model-name") : check(rows[selected]);
139
+ if (key.backspace || key.delete) return query && (setQuery((q) => q.slice(0, -1)), setSelected(0));
140
+ const text = input.replace(/[\u0000-\u001f\u007f]/g, "");
141
+ if (text && !key.ctrl && !key.meta) {
142
+ setQuery((q) => q + text);
143
+ setSelected(0);
144
+ }
145
+ });
146
+
147
+ const problem = error && html`<${Box} marginTop=${1}><${Text} color=${theme.bad}>${error}<//><//>`;
148
+ const frame = (title, body, hints, { errorAbove = false } = {}) => html`
149
+ <${Fragment}>
150
+ <${Box} flexDirection="column" borderStyle="round" borderColor=${theme.accent} paddingX=${2} width=${panel}>
151
+ <${Text} bold color=${theme.accent}>${title}<//>
152
+ ${errorAbove && problem}
153
+ ${body}
154
+ ${message && html`<${Box} marginTop=${1}><${Text} color=${theme.good}>${message}<//><//>`}
155
+ ${!errorAbove && problem}
156
+ <//>
157
+ <${Box} paddingX=${1}><${KeyHints} text=${hints} /><//>
158
+ <//>
159
+ `;
160
+ const name = providerName(draft.provider);
161
+ const keyTitle = draft.provider === "custom" ? t("ai.keyTitleCustom") : t("ai.keyTitle", { provider: name });
162
+
163
+ if (step === "provider") {
164
+ const options = ORDER.map((provider) => ({ label: providerName(provider), note: t(`ai.providers.${provider}`) }));
165
+ if (current) options.push({ label: t("ai.turnOff"), danger: true });
166
+ return frame(
167
+ t("ai.title"),
168
+ html`
169
+ <${Box} flexDirection="column">
170
+ <${Text} dimColor>${note}<//>
171
+ ${current && html`<${Text} dimColor>${t("ai.now", { label: aiLabel(current) })}<//>`}
172
+ <${Box} marginTop=${1}><${Choice} options=${options} selected=${selected} onMove=${setSelected} onPick=${(i) => pickProvider(i).catch((err) => setError(err.message))} onCancel=${() => onClose()} /><//>
173
+ <//>
174
+ `,
175
+ choiceHints("back")
176
+ );
177
+ }
178
+
179
+ if (step === "url")
180
+ return frame(
181
+ t("ai.urlTitle"),
182
+ html`
183
+ <${Box} flexDirection="column">
184
+ <${Text} dimColor>${t("ai.urlNote")}<//>
185
+ <${Box} marginTop=${1}><${AnswerInput} key="url" plain escLeaves initial=${draft.url ?? ""} onChange=${() => setError("")} onExit=${back} onSubmit=${(text) => {
186
+ if (!isUrl(text)) return setError(t("ai.badUrl"));
187
+ const next = { ...draft, url: cleanUrl(text) };
188
+ setDraft(next);
189
+ askForKey(next).catch((err) => setError(err.message));
190
+ }} /><//>
191
+ <//>
192
+ `,
193
+ t("keyHints.importName")
194
+ );
195
+
196
+ if (step === "keep-key") {
197
+ const options = [{ label: t("ai.keepKey"), note: maskKey(key.key) }, { label: t("ai.newKey") }, { label: t("ai.forgetKey"), danger: true }];
198
+ return frame(
199
+ keyTitle,
200
+ html`<${Box} marginTop=${1}><${Choice} options=${options} selected=${selected} onMove=${setSelected} onPick=${(i) => {
201
+ if (i === 0) return loadModels();
202
+ if (i === 1) return go("key");
203
+ forgetKey(draft.provider, urlOf(draft)).then(() => {
204
+ setKey(null);
205
+ go("key");
206
+ setMessage(t("ai.keyForgotten", { provider: name }));
207
+ }, (err) => setError(err.message));
208
+ }} onCancel=${back} /><//>`,
209
+ choiceHints("back")
210
+ );
211
+ }
212
+
213
+ if (step === "key") {
214
+ const optional = !preset?.needsKey;
215
+ return frame(
216
+ keyTitle,
217
+ html`
218
+ <${Box} flexDirection="column">
219
+ <${Text} dimColor>${optional ? t("ai.keyOptional") : t("ai.keyNote", { env: preset.keyEnv, site: preset.site })}<//>
220
+ <${Box} marginTop=${1}><${AnswerInput} key="api-key" plain secret escLeaves onChange=${() => (setError(""), setMessage(""))} onExit=${back} onSubmit=${(text) => {
221
+ const typed = text.trim();
222
+ if (!typed && !optional) return setError(t("ai.needKey"));
223
+ const next = typed ? { key: typed, from: "typed" } : null;
224
+ setKey(next);
225
+ loadModels(draft, next);
226
+ }} /><//>
227
+ <//>
228
+ `,
229
+ t("keyHints.importName")
230
+ );
231
+ }
232
+
233
+ if (step === "model-name")
234
+ return frame(
235
+ t("ai.modelTitle"),
236
+ html`
237
+ <${Box} flexDirection="column">
238
+ <${Text} dimColor>${t("ai.modelNameNote", { provider: name })}<//>
239
+ <${Box} marginTop=${1}><${AnswerInput} key="model-name" plain escLeaves initial=${draft.model ?? ""} onChange=${() => setError("")} onExit=${back} onSubmit=${(text) => (text.trim() ? check(text.trim()) : setError(t("ai.needModel")))} /><//>
240
+ <//>
241
+ `,
242
+ t("keyHints.importName")
243
+ );
244
+
245
+ if (step === "models") {
246
+ const top = Math.max(0, Math.min(selected - Math.floor(SHOWN / 2), rows.length - SHOWN));
247
+ return frame(
248
+ t("ai.modelTitle"),
249
+ html`
250
+ <${Box} flexDirection="column">
251
+ <${Text} dimColor>${[key?.from === "env" && t("ai.keyFromEnv", { env: key.env }), preset.local ? t("ai.localNote", { url: urlOf(draft) }) : t("ai.modelNote")].filter(Boolean).join(" ")}<//>
252
+ ${models?.length === 0 && !error && html`<${Box} marginTop=${1}><${Text}>${preset.local ? t("ai.noModelsLocal") : t("ai.noModels")}<//><//>`}
253
+ ${models === null
254
+ ? html`<${Box} marginTop=${1}><${Text} dimColor>${t("ai.loadingModels", { provider: name })}<//><//>`
255
+ : html`
256
+ <${Box} flexDirection="column" marginTop=${1}>
257
+ ${(models.length > SHOWN || query) && html`<${Box}><${Box} flexShrink=${0}><${Text} dimColor>${t("languages.search")} <//><//><${Text} wrap="truncate-start">${query}<//><${Box} flexShrink=${0}><${Text} inverse> <//><//><//>`}
258
+ <${Text} dimColor>${top > 0 ? " ↑" : " "}<//>
259
+ ${rows.slice(top, top + SHOWN).map((row, i) => {
260
+ const on = top + i === selected;
261
+ return html`<${Text} key=${row ?? "type"} color=${on ? theme.accent : row === null ? theme.good : undefined} bold=${on} wrap="truncate-end">${on ? "❯" : " "} ${row === null ? t("ai.typeModel") : cutToWidth(row, panel - 12)} ${row && row === current?.model && draft.provider === current?.provider ? html`<${Text} dimColor>· ${t("ai.current")}<//>` : row && preset.needsKey && isSmallModel(row) ? html`<${Text} dimColor>· ${t("ai.small")}<//>` : ""}<//>`;
262
+ })}
263
+ <${Text} dimColor>${top + SHOWN < rows.length ? " ↓" : " "}<//>
264
+ <//>
265
+ `}
266
+ <//>
267
+ `,
268
+ models && models.length > SHOWN ? t("keyHints.modelPick") : choiceHints("back")
269
+ );
270
+ }
271
+
272
+ if (step === "checking")
273
+ return frame(t("ai.modelTitle"), html`<${Box} marginTop=${1}><${Text} dimColor>${t("ai.checking", { label: aiLabel(draft) })}<//><//>`, t("keyHints.back"));
274
+
275
+ // failed: what now
276
+ // a key from the environment is changed there, not here
277
+ const options = [{ label: t("ai.tryAgain") }, { label: t("ai.otherModel") }, ...(preset?.local || key?.from === "env" ? [] : [{ label: t("ai.otherKey") }])];
278
+ return frame(
279
+ t("ai.failedTitle", { label: aiLabel(draft) }),
280
+ html`<${Box} marginTop=${1}><${Choice} options=${options} selected=${selected} onMove=${setSelected} onPick=${(i) => (i === 0 ? check(draft.model) : i === 1 ? loadModels() : go("key"))} onCancel=${back} /><//>`,
281
+ choiceHints("back"),
282
+ { errorAbove: true }
283
+ );
284
+ }
@@ -43,8 +43,9 @@ export function nextPart(value, cursor) {
43
43
  }
44
44
 
45
45
  // `cardLine`: the field holds a card line ("front = back // example"), and Tab goes to its next part,
46
- // adding the " = " or " // " that starts it
47
- export function AnswerInput({ onSubmit, onCommand, onExit, onEdit, onCancel, onChange, onRecall, onPaste, commands = COMMANDS, initial = "", commandOnly = false, plain = false, escLeaves = false, cardLine = false }) {
46
+ // adding the " = " or " // " that starts it. `secret`: shown as dots (an API key). `ghost`: a suggestion
47
+ // shown dimmed after the text while the cursor is at its end; Tab or → takes it in (`onGhost` hears that)
48
+ export function AnswerInput({ onSubmit, onCommand, onExit, onEdit, onCancel, onChange, onRecall, onPaste, commands = COMMANDS, initial = "", commandOnly = false, plain = false, escLeaves = false, cardLine = false, secret = false, ghost = "", onGhost }) {
48
49
  const [value, setValue] = useState(initial);
49
50
  const [cursor, setCursor] = useState(initial.length);
50
51
  const [selected, setSelected] = useState(0);
@@ -78,6 +79,11 @@ export function AnswerInput({ onSubmit, onCommand, onExit, onEdit, onCancel, onC
78
79
  edit("");
79
80
  return onCommand(matches[pick]?.name ?? token, rest.join(" "));
80
81
  }
82
+ const atEnd = cursor === value.length;
83
+ if (ghost && atEnd && (key.tab || key.rightArrow)) {
84
+ edit(value + ghost);
85
+ return onGhost?.();
86
+ }
81
87
  if (key.tab && cardLine) {
82
88
  if (!value.trim()) return;
83
89
  const next = nextPart(value, cursor);
@@ -102,14 +108,15 @@ export function AnswerInput({ onSubmit, onCommand, onExit, onEdit, onCancel, onC
102
108
  if (input) paste(input);
103
109
  });
104
110
 
105
- const before = value.slice(0, cursor);
106
- const at = value[cursor] ?? " ";
107
- const after = value.slice(cursor + 1);
111
+ const shown = secret ? "•".repeat(value.length) : value;
112
+ const before = shown.slice(0, cursor);
113
+ const at = shown[cursor] ?? " ";
114
+ const after = shown.slice(cursor + 1);
108
115
  return html`
109
116
  <${Box} flexDirection="column">
110
117
  <${Box}>
111
118
  <${Box} flexShrink=${0}><${Text} color=${theme.accent}>❯ <//><//>
112
- <${Text}>${before}<${Text} inverse>${at}<//>${after}<//>
119
+ <${Text}>${before}${ghost && cursor === value.length ? html`<${Text} dimColor><${Text} inverse>${ghost[0]}<//>${ghost.slice(1)}<//>` : html`<${Text} inverse>${at}<//>`}${after}<//>
113
120
  <//>
114
121
  ${matches.length > 0 && html`<${Palette} matches=${matches} selected=${pick} />`}
115
122
  ${isCommand && matches.length === 0 && html`<${Box} marginTop=${1}>${commandOnly ? html`<${Text} color=${theme.bad}>${t("input.unknownCommand")}<//>` : html`<${Text} dimColor>${t("input.notACommand")}<//>`}<//>`}
package/src/ui/App.js CHANGED
@@ -7,7 +7,7 @@ import { toSpeak } from "../session.js";
7
7
  import { AnswerInput } from "./AnswerInput.js";
8
8
  import { Header } from "./Header.js";
9
9
  import { setLanguage, t } from "../i18n.js";
10
- import { Bar, cellWidth, cutToWidth, html, KeyHints, Marked, Text, theme, Typewriter, usePanelWidth } from "./kit.js";
10
+ import { applyTheme, Bar, cellWidth, cutToWidth, html, KeyHints, Marked, Text, theme, Typewriter, usePanelWidth } from "./kit.js";
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";
@@ -25,7 +25,9 @@ import { DieRoll } from "./DieRoll.js";
25
25
  import { Evolution } from "./Evolution.js";
26
26
  import { Hatch } from "./Hatch.js";
27
27
  import { LanguageSearch } from "./Languages.js";
28
- import { Welcome } from "./Welcome.js";
28
+ import { FIRST_WORDS_COUNT, Welcome } from "./Welcome.js";
29
+ import { AiSetup } from "./Ai.js";
30
+ import { VoiceSetup } from "./Voice.js";
29
31
  import { AddCard } from "./AddCard.js";
30
32
  import { ImportScreen } from "./Import.js";
31
33
  import { Decks } from "./Decks.js";
@@ -47,11 +49,11 @@ const SLEEP_AFTER_MS = 3 * 60_000; // no key pressed for this long while waiting
47
49
  const PAUSED_SLEEP_AFTER_MS = 15_000; // during a pause or quiet hours it nods off again much sooner
48
50
  const SETTLE_MS = 400; // keys right after a card appears or its answer is revealed are a double press, not a choice
49
51
  const CHEER_STYLE = {
50
- goal: { icon: "▪", color: theme.good },
51
- evolve: { icon: "▴", color: theme.accent },
52
- badge: { icon: "✦", color: theme.warn },
53
- combo: { icon: "»", color: theme.warn }
54
- };
52
+ goal: { icon: "▪", color: "good" },
53
+ evolve: { icon: "▴", color: "accent" },
54
+ badge: { icon: "✦", color: "warn" },
55
+ combo: { icon: "»", color: "warn" }
56
+ }; // colors are theme keys, read when drawn
55
57
 
56
58
  const QUIET_NIGHT_UNTIL = 7; // o'clock: no "new card" sound before then when a day's cards come in
57
59
 
@@ -95,10 +97,11 @@ function Verdict({ outcome, question }) {
95
97
  const held = outcome.held ? heldText(outcome.held) : null;
96
98
  return html`
97
99
  <${Box} flexDirection="column">
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") : ""}<//>
100
+ <${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") : ""}${question.word.ai ? html`<${Text} color=${theme.accent} bold=${false}> ✦<//>` : ""}<//>
99
101
  ${ALMOST.includes(outcome.result) && html`<${Text} color=${theme.warn}>${t(`quiz.almost.${outcome.result}`)}<//>`}
100
102
  ${showDiff && html`<${AnswerDiff} given=${outcome.given} closest=${outcome.closest} />`}
101
103
  ${question.word.example && html`<${Box} marginTop=${1}>${question.tour ? html`<${Marked} dimColor text=${question.word.example} />` : html`<${Text} dimColor italic>“${question.word.example}”<//>`}<//>`}
104
+ ${wrong && question.word.ai && html`<${Box} marginTop=${1}><${Text} color=${theme.accent}>${t("quiz.fromAi")}<//><//>`}
102
105
  ${(outcome.hinted || outcome.overruled || held) &&
103
106
  html`
104
107
  <${Box} marginTop=${1} flexDirection="column">
@@ -115,7 +118,7 @@ function Verdict({ outcome, question }) {
115
118
  function Revealed({ question, nudge }) {
116
119
  return html`
117
120
  <${Box} flexDirection="column">
118
- <${Text} color=${theme.accent} bold>${question.expected.join(" / ")}<//>
121
+ <${Text} color=${theme.accent} bold>${question.expected.join(" / ")}${question.word.ai ? html`<${Text} bold=${false}> ✦<//>` : ""}<//>
119
122
  ${question.word.example && html`<${Box} marginTop=${1}>${question.tour ? html`<${Marked} dimColor text=${question.word.example} />` : html`<${Text} dimColor italic>“${question.word.example}”<//>`}<//>`}
120
123
  <${Box} marginTop=${1}>
121
124
  <${Text} bold>${t("quiz.didYouKnow")} <//>
@@ -135,7 +138,7 @@ function Cheers({ cheers, play }) {
135
138
  <${Box} flexDirection="column" paddingX=${1} marginTop=${1}>
136
139
  ${lines.map((cheer, i) => {
137
140
  const style = CHEER_STYLE[cheer.kind] ?? CHEER_STYLE.combo;
138
- return html`<${Text} key=${i} color=${style.color} bold>${style.icon} ${cheer.text}<//>`;
141
+ return html`<${Text} key=${i} color=${theme[style.color]} bold>${style.icon} ${cheer.text}<//>`;
139
142
  })}
140
143
  ${badges.map((badge, i) => html`<${BadgeUnlock} key=${badge.id} ...${badge} delay=${BADGE_FIRST_MS + i * BADGE_STAGGER_MS} sound=${badgeSound(i)} play=${play} />`)}
141
144
  <//>
@@ -220,12 +223,14 @@ export function App({ session, deck: initialDeck, initialSettings, initialMix, a
220
223
  const exit = onExit ?? exitApp; // the preview gallery runs the quiz as a scene and takes quitting back to its menu
221
224
  const { stdout } = useStdout();
222
225
  const [settings, setSettings] = useState(initialSettings);
226
+ applyTheme(settings.theme); // before anything below reads a color; a change in /settings repaints all
223
227
  const [deck, setDeck] = useState(initialDeck);
224
228
  const [mix, setMix] = useState(initialMix !== undefined ? initialMix : (initialSettings.mix ?? null)); // decks practised together: "all", or their names
225
229
  const [addNew, setAddNew] = useState(false); // /add opened from "+ New deck" in /decks
226
230
  const [cardsDeck, setCardsDeck] = useState(null); // the deck /cards shows (one of several practised together)
227
231
  const [addInto, setAddInto] = useState(null); // /add from /cards: straight into that deck
228
232
  const [addSuggest, setAddSuggest] = useState(null); // /add from the welcome: a name and an example in your pair
233
+ const [aiFrom, setAiFrom] = useState(null); // "welcome" while AI help is set up for a first deck
229
234
  const [importFrom, setImportFrom] = useState(null); // "welcome" when /import was picked there: cancelling goes back
230
235
  const [restUntil, setRestUntil] = useState(null); // nothing is waiting until then (after the last card due now)
231
236
  const [empty, setEmpty] = useState(null); // { tour, count, nextDue } when there is nothing to ask right now
@@ -319,6 +324,12 @@ export function App({ session, deck: initialDeck, initialSettings, initialMix, a
319
324
  ask();
320
325
  }, [ask]);
321
326
 
327
+ // a natural voice that stopped working (key, credit) says so once; words go on in the system's voice
328
+ useEffect(() => {
329
+ alerts.configure({ onVoiceProblem: (message) => setNotice(message) });
330
+ return () => alerts.configure({ onVoiceProblem: null });
331
+ }, [alerts]);
332
+
322
333
  // one steady clock for the whole app: spinner, countdown, mascot blink and combo flicker
323
334
  useEffect(() => {
324
335
  const id = setInterval(() => setNow(Date.now()), TICK_MS);
@@ -484,7 +495,7 @@ export function App({ session, deck: initialDeck, initialSettings, initialMix, a
484
495
  const next = { ...previous, ...patch };
485
496
  settingsRef.current = next;
486
497
  setSettings(next);
487
- alerts.configure({ sound: next.sound, volume: next.volume, speak: next.speak });
498
+ alerts.configure({ sound: next.sound, volume: next.volume, speak: next.speak, voice: next.voice });
488
499
  persistSettings(patch).catch(() => {});
489
500
  if (patch.everyMs && phase === "waiting") setNextAt((at) => at - previous.everyMs + patch.everyMs);
490
501
  if (patch.rhythm) {
@@ -523,15 +534,22 @@ export function App({ session, deck: initialDeck, initialSettings, initialMix, a
523
534
  setImportFrom("welcome");
524
535
  return setScreen("import");
525
536
  }
537
+ // a first deck from AI help: set up first, Esc there goes back to the welcome
538
+ if (how === "ai" && library && !settingsRef.current.ai) {
539
+ setAiFrom("welcome");
540
+ return setScreen("ai");
541
+ }
526
542
  session.setWelcomeStep(null).catch(() => {});
527
543
  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
544
+ if (how === "own" || how === "ai") {
545
+ // the deck named after the language you're learning, and an example card in your pair; from AI
546
+ // help, a list of everyday words of the pair to ask for
530
547
  const { homeLanguage, language: ui, learningLanguage: learning } = settingsRef.current;
531
548
  const home = homeLanguage ?? ui;
532
549
  const name = languageName(learning) ?? "";
533
550
  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]}` });
551
+ const request = how === "ai" && name ? t("welcome.aiRequest", { count: FIRST_WORDS_COUNT, language: name, home: languageName(home) }) : null;
552
+ setAddSuggest({ name: name && name.charAt(0).toLocaleUpperCase(ui) + name.slice(1), example: sample && `${sample.front} = ${sample.back[0]}`, request });
535
553
  setAddNew(true);
536
554
  return setScreen("add");
537
555
  }
@@ -749,6 +767,14 @@ export function App({ session, deck: initialDeck, initialSettings, initialMix, a
749
767
  if ((added || updated) && (phase === "asking" || phase === "empty")) ask();
750
768
  }
751
769
 
770
+ // AI help set up (or not): from the welcome, on to the first deck, or back to the welcome
771
+ function aiClosed(said) {
772
+ if (aiFrom !== "welcome") return setScreen("settings"), said && setNotice(said);
773
+ setAiFrom(null);
774
+ if (settingsRef.current.ai) return begin("ai");
775
+ setScreen("welcome");
776
+ }
777
+
752
778
  function importCancelled() {
753
779
  if (importFrom === "welcome") {
754
780
  setImportFrom(null);
@@ -818,21 +844,23 @@ export function App({ session, deck: initialDeck, initialSettings, initialMix, a
818
844
  <${Box} flexDirection="column" marginY=${1}>
819
845
  <${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} />
820
846
  <${Box} marginTop=${1} flexDirection="column">
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} />`}
847
+ ${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", ai: "ai", voice: "voice" }[row]) : null} />`}
822
848
  ${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
849
  ${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"))} />`}
850
+ ${screen === "ai" && html`<${AiSetup} current=${settings.ai} onSave=${(ai) => changeSettings({ ai })} onClose=${aiClosed} note=${aiFrom === "welcome" ? t("ai.noteWelcome") : undefined} />`}
851
+ ${screen === "voice" && html`<${VoiceSetup} current=${settings.voice} speakOn=${settings.speak} play=${alerts.playFile} onSave=${(voice) => changeSettings(voice && !settingsRef.current.speak ? { voice, speak: true } : { voice })} onClose=${(said) => (setScreen("settings"), said && setNotice(said))} />`}
824
852
  ${screen === "reset" && html`<${Reset} stats=${stats} actions=${library} onConfirm=${reset} onClose=${() => setScreen("settings")} />`}
825
853
  ${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} />`}
854
+ ${screen === "add" && html`<${AddCard} current=${deck} actions=${library} ai=${settings.ai} onDone=${addDone} startNew=${addNew} suggest=${addSuggest} into=${addInto} />`}
827
855
  ${screen === "decks" && html`<${Decks} current=${deck} mix=${mix} onPractise=${practise} actions=${library} onDirections=${async (cardIds, directions) => {
828
856
  await session.setDirections(cardIds, directions);
829
857
  await session.workAdded();
830
858
  if (phase === "asking" && question && cardIds.includes(question.word.noteId)) ask(); // the open card follows the new way at once
831
859
  }} 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} />`}
860
+ ${screen === "cards" && html`<${Cards} deck=${cardsDeck ?? deck} actions=${library} ai=${settings.ai} onDeleted=${deleteCards} onRestored=${restoreDeck} onEdited=${(keys) => session.forgetKeys(keys)} onAdd=${() => (setAddNew(false), setAddInto(cardsDeck ?? deck), setScreen("add"))} onClose=${cardsClosed} />`}
833
861
  ${screen === "cards-pick" && html`<${CardsDeckPick} actions=${library} mix=${mix} current=${deck} onPick=${(name) => (setCardsDeck(name), setScreen("cards"))} onClose=${() => setScreen("quiz")} />`}
834
862
  ${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) &&
863
+ ${!["settings", "ai", "voice", "reset", "home-language", "dragon-look", "import", "add", "decks", "trash", "cards", "cards-pick"].includes(screen) &&
836
864
  html`
837
865
  <${Fragment}>
838
866
  ${question &&
@@ -870,7 +898,7 @@ export function App({ session, deck: initialDeck, initialSettings, initialMix, a
870
898
  html`
871
899
  <${Text}>
872
900
  <${Text} color=${theme.accent}>${frame} <//>
873
- <${Bar} value=${Math.max(0, nextAt - now)} max=${settings.everyMs} width=${14} color="#6b5e8a" />
901
+ <${Bar} value=${Math.max(0, nextAt - now)} max=${settings.everyMs} width=${14} color=${theme.countdown} />
874
902
  <${Text} dimColor>${t("quiz.nextCardIn", { time: clock(nextAt - now) })}<//>
875
903
  <//>
876
904
  `}
@@ -2,22 +2,20 @@ import { t } from "../i18n.js";
2
2
  import { useEffect, useState } from "react";
3
3
  import { Box } from "ink";
4
4
  import { badgeColor } from "./icons.js";
5
- import { html, Text, theme } from "./kit.js";
5
+ import { html, readable, Text, theme } from "./kit.js";
6
6
 
7
7
  const FRAME_MS = 90;
8
- const FLASH_FRAMES = [5, 7]; // white-out frames before the name lights up in its rank color
8
+ const FLASH_FRAMES = [5, 7]; // flash frames before the name lights up in its rank color
9
9
  const COLOR_FROM = 8;
10
10
  const SPARKS_UNTIL = 22;
11
11
  const SPARKS = ["✦", "·", "✧", "·"];
12
- const GREY = "#4a5058";
13
- const WHITE = "#ffffff";
14
12
  const STEPS = 4; // badge-1 … badge-4 (scripts/make-sounds.js)
15
13
 
16
14
  // Badges won with the same answer ring one after another, each a step higher. The climb starts
17
15
  // over with every answer: a badge won later, on its own, plays the first step again.
18
16
  export const badgeSound = (i) => `badge-${Math.min(i + 1, STEPS)}`;
19
17
 
20
- // A badge just won, as one line under the card: the name comes out of grey, flashes white and
18
+ // A badge just won, as one line under the card: the name comes out of grey, flashes and
21
19
  // lights up in its rank color while a few sparks fly. The badge art lives in /badges.
22
20
  // `delay` staggers several badges won at once; `sound` rings as the line appears.
23
21
  export function BadgeUnlock({ id, name, desc, delay = 0, sound = badgeSound(0), play }) {
@@ -36,7 +34,7 @@ export function BadgeUnlock({ id, name, desc, delay = 0, sound = badgeSound(0),
36
34
  }, []);
37
35
 
38
36
  if (frame < 0) return null;
39
- const color = FLASH_FRAMES.includes(frame) ? WHITE : frame >= COLOR_FROM ? badgeColor(id) : GREY;
37
+ const color = FLASH_FRAMES.includes(frame) ? theme.flash : frame >= COLOR_FROM ? readable(badgeColor(id)) : theme.locked;
40
38
  const sparks = frame < SPARKS_UNTIL ? ` ${Array.from({ length: 3 }, (_, i) => SPARKS[(frame + i) % SPARKS.length]).join(" ")}` : "";
41
39
 
42
40
  return html`
package/src/ui/Badges.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { t } from "../i18n.js";
2
2
  import { Fragment, useEffect, useState } from "react";
3
3
  import { Box, useInput } from "ink";
4
- import { html, KeyHints, Text, theme, usePanelWidth } from "./kit.js";
4
+ import { html, KeyHints, readable, Text, theme, usePanelWidth } from "./kit.js";
5
5
  import { badgeColor, BadgeIcon, ICON_WIDTH } from "./icons.js";
6
6
 
7
7
  const COLUMNS = 3;
@@ -12,12 +12,10 @@ const FRAME_MS = 90;
12
12
  const STAGGER = 7; // frames between two badges
13
13
  const FLASH_FRAMES = [2, 4];
14
14
  const LIT_FROM = 5;
15
- const GREY = "#4a5058";
16
15
 
17
16
  // a hidden badge reveals nothing until it's won
18
17
  const secret = () => ({ name: t("badgesScreen.secretName"), desc: t("badgesScreen.secretDesc") });
19
18
  const display = (badge) => (badge.hidden && !badge.unlockedOn ? { ...badge, ...secret() } : badge);
20
- const WHITE = "#ffffff";
21
19
 
22
20
  // where a fresh badge is in its little animation: "waiting" (still looks locked), "flash", or "lit"
23
21
  function phaseOf(freshIndex, frame) {
@@ -85,7 +83,7 @@ export function Badges({ badges, fresh = [], onClose }) {
85
83
  <${BadgeIcon} id=${badge.id} locked=${!badge.unlockedOn || phase === "waiting"} flash=${phase === "flash"} secret=${badge.hidden && !badge.unlockedOn} />
86
84
  <//>
87
85
  <${Box} flexDirection="column" justifyContent="center">
88
- <${Box}><${Text} bold color=${shownUnlocked ? badgeColor(badge.id) : undefined} dimColor=${!shownUnlocked}>${badge.name}<//><//>
86
+ <${Box}><${Text} bold color=${shownUnlocked ? readable(badgeColor(badge.id)) : undefined} dimColor=${!shownUnlocked}>${badge.name}<//><//>
89
87
  <${Box}><${Text}>${badge.desc}<//><//>
90
88
  <${Box}><${Text} dimColor>${badge.unlockedOn ? t("badgesScreen.unlocked", { day: badge.unlockedOn }) : t("badgesScreen.locked")}<//><//>
91
89
  <//>
@@ -100,13 +98,13 @@ export function Badges({ badges, fresh = [], onClose }) {
100
98
  const current = index === selected;
101
99
  const rowPhase = phaseOf(fresh.indexOf(b.id), frame);
102
100
  const shown = b.unlockedOn && rowPhase !== "waiting";
103
- const dotColor = !shown ? undefined : rowPhase === "flash" ? WHITE : badgeColor(b.id);
104
- const nameColor = current ? theme.accent : rowPhase === "flash" ? WHITE : shown ? theme.text : undefined;
101
+ const dotColor = !shown ? undefined : rowPhase === "flash" ? theme.flash : readable(badgeColor(b.id));
102
+ const nameColor = current ? theme.accent : rowPhase === "flash" ? theme.flash : shown ? theme.text : undefined;
105
103
  return html`
106
104
  <${Box} key=${b.id}>
107
105
  <${Text} bold=${current} dimColor=${!current && !shown} wrap="truncate">
108
106
  <${Text} color=${current ? theme.accent : undefined}>${current ? "❯" : " "} <//>
109
- <${Text} color=${dotColor ?? (b.unlockedOn ? GREY : undefined)}>${shown ? "●" : "○"} <//>
107
+ <${Text} color=${dotColor ?? (b.unlockedOn ? theme.locked : undefined)}>${shown ? "●" : "○"} <//>
110
108
  <${Text} color=${nameColor}>${display(b).name}<//>
111
109
  <//>
112
110
  <//>