dracosh 0.7.0 → 0.8.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
@@ -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";
@@ -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")} <//>
@@ -226,6 +229,7 @@ export function App({ session, deck: initialDeck, initialSettings, initialMix, a
226
229
  const [cardsDeck, setCardsDeck] = useState(null); // the deck /cards shows (one of several practised together)
227
230
  const [addInto, setAddInto] = useState(null); // /add from /cards: straight into that deck
228
231
  const [addSuggest, setAddSuggest] = useState(null); // /add from the welcome: a name and an example in your pair
232
+ const [aiFrom, setAiFrom] = useState(null); // "welcome" while AI help is set up for a first deck
229
233
  const [importFrom, setImportFrom] = useState(null); // "welcome" when /import was picked there: cancelling goes back
230
234
  const [restUntil, setRestUntil] = useState(null); // nothing is waiting until then (after the last card due now)
231
235
  const [empty, setEmpty] = useState(null); // { tour, count, nextDue } when there is nothing to ask right now
@@ -319,6 +323,12 @@ export function App({ session, deck: initialDeck, initialSettings, initialMix, a
319
323
  ask();
320
324
  }, [ask]);
321
325
 
326
+ // a natural voice that stopped working (key, credit) says so once; words go on in the system's voice
327
+ useEffect(() => {
328
+ alerts.configure({ onVoiceProblem: (message) => setNotice(message) });
329
+ return () => alerts.configure({ onVoiceProblem: null });
330
+ }, [alerts]);
331
+
322
332
  // one steady clock for the whole app: spinner, countdown, mascot blink and combo flicker
323
333
  useEffect(() => {
324
334
  const id = setInterval(() => setNow(Date.now()), TICK_MS);
@@ -484,7 +494,7 @@ export function App({ session, deck: initialDeck, initialSettings, initialMix, a
484
494
  const next = { ...previous, ...patch };
485
495
  settingsRef.current = next;
486
496
  setSettings(next);
487
- alerts.configure({ sound: next.sound, volume: next.volume, speak: next.speak });
497
+ alerts.configure({ sound: next.sound, volume: next.volume, speak: next.speak, voice: next.voice });
488
498
  persistSettings(patch).catch(() => {});
489
499
  if (patch.everyMs && phase === "waiting") setNextAt((at) => at - previous.everyMs + patch.everyMs);
490
500
  if (patch.rhythm) {
@@ -523,15 +533,22 @@ export function App({ session, deck: initialDeck, initialSettings, initialMix, a
523
533
  setImportFrom("welcome");
524
534
  return setScreen("import");
525
535
  }
536
+ // a first deck from AI help: set up first, Esc there goes back to the welcome
537
+ if (how === "ai" && library && !settingsRef.current.ai) {
538
+ setAiFrom("welcome");
539
+ return setScreen("ai");
540
+ }
526
541
  session.setWelcomeStep(null).catch(() => {});
527
542
  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
543
+ if (how === "own" || how === "ai") {
544
+ // the deck named after the language you're learning, and an example card in your pair; from AI
545
+ // help, a list of everyday words of the pair to ask for
530
546
  const { homeLanguage, language: ui, learningLanguage: learning } = settingsRef.current;
531
547
  const home = homeLanguage ?? ui;
532
548
  const name = languageName(learning) ?? "";
533
549
  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]}` });
550
+ const request = how === "ai" && name ? t("welcome.aiRequest", { count: FIRST_WORDS_COUNT, language: name, home: languageName(home) }) : null;
551
+ setAddSuggest({ name: name && name.charAt(0).toLocaleUpperCase(ui) + name.slice(1), example: sample && `${sample.front} = ${sample.back[0]}`, request });
535
552
  setAddNew(true);
536
553
  return setScreen("add");
537
554
  }
@@ -749,6 +766,14 @@ export function App({ session, deck: initialDeck, initialSettings, initialMix, a
749
766
  if ((added || updated) && (phase === "asking" || phase === "empty")) ask();
750
767
  }
751
768
 
769
+ // AI help set up (or not): from the welcome, on to the first deck, or back to the welcome
770
+ function aiClosed(said) {
771
+ if (aiFrom !== "welcome") return setScreen("settings"), said && setNotice(said);
772
+ setAiFrom(null);
773
+ if (settingsRef.current.ai) return begin("ai");
774
+ setScreen("welcome");
775
+ }
776
+
752
777
  function importCancelled() {
753
778
  if (importFrom === "welcome") {
754
779
  setImportFrom(null);
@@ -818,21 +843,23 @@ export function App({ session, deck: initialDeck, initialSettings, initialMix, a
818
843
  <${Box} flexDirection="column" marginY=${1}>
819
844
  <${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
845
  <${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} />`}
846
+ ${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
847
  ${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
848
  ${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"))} />`}
849
+ ${screen === "ai" && html`<${AiSetup} current=${settings.ai} onSave=${(ai) => changeSettings({ ai })} onClose=${aiClosed} note=${aiFrom === "welcome" ? t("ai.noteWelcome") : undefined} />`}
850
+ ${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
851
  ${screen === "reset" && html`<${Reset} stats=${stats} actions=${library} onConfirm=${reset} onClose=${() => setScreen("settings")} />`}
825
852
  ${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} />`}
853
+ ${screen === "add" && html`<${AddCard} current=${deck} actions=${library} ai=${settings.ai} onDone=${addDone} startNew=${addNew} suggest=${addSuggest} into=${addInto} />`}
827
854
  ${screen === "decks" && html`<${Decks} current=${deck} mix=${mix} onPractise=${practise} actions=${library} onDirections=${async (cardIds, directions) => {
828
855
  await session.setDirections(cardIds, directions);
829
856
  await session.workAdded();
830
857
  if (phase === "asking" && question && cardIds.includes(question.word.noteId)) ask(); // the open card follows the new way at once
831
858
  }} 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} />`}
859
+ ${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
860
  ${screen === "cards-pick" && html`<${CardsDeckPick} actions=${library} mix=${mix} current=${deck} onPick=${(name) => (setCardsDeck(name), setScreen("cards"))} onClose=${() => setScreen("quiz")} />`}
834
861
  ${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) &&
862
+ ${!["settings", "ai", "voice", "reset", "home-language", "dragon-look", "import", "add", "decks", "trash", "cards", "cards-pick"].includes(screen) &&
836
863
  html`
837
864
  <${Fragment}>
838
865
  ${question &&