dracosh 0.6.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/settings.js CHANGED
@@ -1,6 +1,8 @@
1
+ import { normalizeAi } from "./ai.js";
2
+ import { normalizeVoice } from "./voice.js";
1
3
  import { LANGUAGES, systemLanguage, t } from "./i18n.js";
2
4
 
3
- export const DEFAULTS = { everyMs: 600_000, rhythm: "minutes", sound: true, speak: false, volume: 0.5, dailyGoal: 20, tips: "sometimes", quiet: null, skipWeekends: true, deck: null };
5
+ export const DEFAULTS = { everyMs: 600_000, rhythm: "minutes", sound: true, speak: false, volume: 0.5, dailyGoal: 20, tips: "sometimes", quiet: null, skipWeekends: true, deck: null, mix: null, homeLanguage: null, learningLanguage: null, ai: null, voice: null };
4
6
 
5
7
  export const INTERVALS = [60_000, 120_000, 300_000, 600_000, 900_000, 1_200_000, 1_800_000, 2_700_000, 3_600_000];
6
8
  export const GOALS = [5, 10, 15, 20, 25, 30, 40, 50, 75, 100, 150, 200];
@@ -25,6 +27,7 @@ const normalizeTips = (value) => (value === true ? "always" : value === false ?
25
27
  const isHour = (v) => Number.isInteger(v) && v >= 0 && v <= 23;
26
28
 
27
29
  const isNumber = (v) => typeof v === "number" && Number.isFinite(v);
30
+ const isLanguage = (v) => typeof v === "string" && /^[a-z]{2,3}$/.test(v);
28
31
 
29
32
  // settings.json is hand-editable, so anything invalid falls back to the default instead of crashing
30
33
  export function normalizeSettings(raw = {}) {
@@ -40,6 +43,13 @@ export function normalizeSettings(raw = {}) {
40
43
  skipWeekends: typeof raw.skipWeekends === "boolean" ? raw.skipWeekends : DEFAULTS.skipWeekends,
41
44
  quiet: raw.quiet && isHour(raw.quiet.from) && isHour(raw.quiet.to) ? { from: raw.quiet.from, to: raw.quiet.to } : null,
42
45
  deck: typeof raw.deck === "string" && raw.deck.trim() ? raw.deck : null, // picked in /decks; null = your first deck
46
+ // decks practised together (/decks, space): "all" of yours, or two or more by name; null = only `deck`
47
+ mix: raw.mix === "all" ? "all" : Array.isArray(raw.mix) && raw.mix.filter((name) => typeof name === "string" && name.trim()).length >= 2 ? raw.mix.filter((name) => typeof name === "string" && name.trim()) : null,
48
+ // the language you speak and the one you're learning, from the welcome (codes; null: not said)
49
+ homeLanguage: isLanguage(raw.homeLanguage) ? raw.homeLanguage : null,
50
+ learningLanguage: isLanguage(raw.learningLanguage) ? raw.learningLanguage : null,
51
+ ai: normalizeAi(raw.ai), // AI help (/settings): provider, model and address; the key is kept apart
52
+ voice: normalizeVoice(raw.voice), // natural voice (/settings → Voice); null: the system's voices
43
53
  language: typeof raw.language === "string" && Object.hasOwn(LANGUAGES, raw.language) ? raw.language : systemLanguage() // until picked in /settings, the system's
44
54
  };
45
55
  }
package/src/store.js CHANGED
@@ -119,8 +119,14 @@ export const loadSettingsRaw = async () => {
119
119
  return isObject(raw) ? raw : {};
120
120
  };
121
121
 
122
- // merges into what's on disk, so a one-off CLI flag never gets persisted by accident
123
- export async function patchSettings(patch) {
124
- const current = await loadSettingsRaw();
125
- await writeJson(SETTINGS_FILE, { ...current, ...patch });
122
+ // merges into what's on disk, so a one-off CLI flag never gets persisted by accident. One patch at a
123
+ // time: two read before either wrote would leave out the first one's change.
124
+ let patching = Promise.resolve();
125
+ export function patchSettings(patch) {
126
+ const next = patching.then(async () => {
127
+ const current = await loadSettingsRaw();
128
+ await writeJson(SETTINGS_FILE, { ...current, ...patch });
129
+ });
130
+ patching = next.catch(() => {});
131
+ return next;
126
132
  }
package/src/transfer.js CHANGED
@@ -59,15 +59,15 @@ async function confirm(question, byDefault) {
59
59
  const answers = (back) => back.join("; ");
60
60
  // a cloze card keeps its {{gaps}} in the preview, so you see what will be asked
61
61
  // a cloze card's back is a hint, not an answer: "Ella {{come}} pan. (hint: verb)"
62
- const cardText = (fields) => (!fields.back.length ? fields.front : fields.cloze ? `${fields.front} ${t("import.hint", { hint: fields.back[0] })}` : `${fields.front} = ${answers(fields.back)}`);
62
+ export const cardText = (fields) => (!fields.back.length ? fields.front : fields.cloze ? `${fields.front} ${t("import.hint", { hint: fields.back[0] })}` : `${fields.front} = ${answers(fields.back)}`);
63
63
  const cut = (text, max = 60) => (Array.from(text).length > max ? `${Array.from(text).slice(0, max - 1).join("")}…` : text);
64
64
  const more = (count) => count > 0 && out(` ${t("import.more", { count })}`);
65
65
 
66
66
  // a file's name without its extension, as a deck name: "spanish-verbs.csv" → "spanish-verbs"
67
- const deckFromFile = (file) => Array.from(basename(file, extname(file)).trim()).slice(0, MAX_DECK_NAME).join("");
67
+ export const deckFromFile = (file) => Array.from(basename(file, extname(file)).trim()).slice(0, MAX_DECK_NAME).join("");
68
68
 
69
69
  const SEPARATOR_NAMES = { "\t": "tab", ",": "comma", ";": "semicolon", "|": "pipe", ":": "colon", " ": "space" };
70
- function describeRead(read) {
70
+ export function describeRead(read) {
71
71
  if (read.format !== "table") return t(`import.formats.${read.format}`);
72
72
  const separator = SEPARATOR_NAMES[read.separator] ? t(`import.separators.${SEPARATOR_NAMES[read.separator]}`) : `"${read.separator}"`;
73
73
  const roles = ["deck", "front", "back", "example"].filter((role) => read.columns?.[role] !== null && read.columns?.[role] !== undefined);
@@ -76,7 +76,7 @@ function describeRead(read) {
76
76
  }
77
77
 
78
78
  // `notes`: the cards came from an Anki package, so a place in it is a note's number, not a line
79
- function issueText(problem, notes) {
79
+ export function issueText(problem, notes) {
80
80
  if (problem.issue === "twice") return t(notes ? "import.issues.twiceNote" : "import.issues.twice", { line: problem.first });
81
81
  if (problem.issue === "tooLong") return t("import.issues.tooLong", { max: MAX_DECK_NAME, deck: cut(problem.deck, 30) });
82
82
  if (problem.issue === "tour") return t("import.issues.tour", { deck: problem.deck });
@@ -103,7 +103,7 @@ async function readPackage(file) {
103
103
  }
104
104
  }
105
105
 
106
- async function readInput(file, encoding) {
106
+ async function readInput(file, encoding, { inApp = false } = {}) {
107
107
  let bytes;
108
108
  if (file === "-") {
109
109
  const chunks = [];
@@ -125,11 +125,28 @@ async function readInput(file, encoding) {
125
125
  return decodeText(bytes, encoding);
126
126
  } catch (err) {
127
127
  if (!err.samples) throw err;
128
+ if (inApp) throw new Error(t("importScreen.notUtf8", { file: name }));
128
129
  const lines = err.samples.map((sample) => ` --encoding ${sample.encoding} ${sample.line}`);
129
130
  throw new Error([t("import.notUtf8", { file: name }), ...lines, t("import.notUtf8Hint")].join("\n"));
130
131
  }
131
132
  }
132
133
 
134
+ // A file for /import, read as `dracosh import` reads it → { text, list, isPackage, csv, encoding }: an Anki
135
+ // package's cards in `list`, a text file's `text`. Encodings other than UTF-8 and UTF-16 are left to the
136
+ // command (--encoding), and so are full backups, which can't be brought back while the quiz runs.
137
+ export async function readImportFile(file) {
138
+ const ending = extname(file).toLowerCase();
139
+ if (ending === ".json") {
140
+ if (!existsSync(file)) throw new Error(t("import.noFile", { file }));
141
+ const backup = await readJson(file, null).catch(() => null);
142
+ if (backup?.format !== 1 || !backup.files || typeof backup.files !== "object") throw new Error(t("errors.notABackup", { file: basename(file) }));
143
+ throw new Error(t("importScreen.backup", { file: shellQuote(file) }));
144
+ }
145
+ if (ending === ".apkg" || ending === ".colpkg") return { text: null, list: await readPackage(file), isPackage: true, csv: false, encoding: "utf-8" };
146
+ const { text, encoding } = await readInput(file, undefined, { inApp: true });
147
+ return { text, list: null, isPackage: false, csv: ending === ".csv", encoding };
148
+ }
149
+
133
150
  // a full backup made by `dracosh export x.json`: brought back like `dracosh restore`, once each of its
134
151
  // files is known to be one Dracosh can use (nothing is written otherwise)
135
152
  async function importBackup(file, { yes: sure }) {
package/src/ui/AddCard.js CHANGED
@@ -6,20 +6,22 @@ import { readCardList } from "../cardlist.js";
6
6
  import { frontKey } from "../judge.js";
7
7
  import { isKnown, languageName } from "../language.js";
8
8
  import { LanguagePicker, pairText } from "./Languages.js";
9
+ import { providerName } from "../ai.js";
10
+ import { suggestCard, suggestCards } from "../assist.js";
9
11
  import { AnswerInput } from "./AnswerInput.js";
10
12
  import { Choice, choiceHints } from "./Choice.js";
11
13
  import { t } from "../i18n.js";
12
- import { cutToWidth, html, KeyHints, Text, theme, usePanelWidth } from "./kit.js";
14
+ import { cellWidth, cutToWidth, html, KeyHints, Text, theme, usePanelWidth } from "./kit.js";
13
15
 
14
16
  const SHOWN_CARDS = 5; // the cards added so far, newest last
15
17
  const PASTE_ROWS = 8; // rows of a pasted list on screen at once
16
18
  const answers = (back) => back.join(" / ");
17
19
 
18
- // How a card will be asked in a deck, for the line under the field: "kot → ? you type cat / kitty"
20
+ // How a card will be asked: a cloze's gaps under the field, and a new deck's way once picked
21
+ // ("kot → ? you type cat / kitty")
19
22
  function askedAs(fields, directions) {
20
23
  if (fields.cloze) return t("add.preview.cloze", { prompt: blankGap(fields.front, 0) + (fields.back.length ? ` (${answers(fields.back)})` : ""), count: gapsOf(fields.front).length });
21
24
  const [front, back] = [fields.front, answers(fields.back)];
22
- if (!directions) return t("add.preview.pair", { front, back });
23
25
  if (directions === "backward") return t("add.preview.asks", { prompt: back, answer: front });
24
26
  const forward = t("add.preview.asks", { prompt: front, answer: back });
25
27
  return directions === "both" ? t("add.preview.both", { forward, backward: t("add.preview.asks", { prompt: back, answer: front }) }) : forward;
@@ -61,7 +63,33 @@ function withRepeats(items) {
61
63
  // replaces the tour), then add cards one line each until Esc: "kot = cat; kitty // example". After a new
62
64
  // deck's first card it asks which way the deck is asked. A pasted list opens a review first.
63
65
  // `actions` reads and writes the library; `startNew` skips the deck list ("+ New deck" in /decks).
64
- export function AddCard({ current, actions, onDone, startNew = false }) {
66
+ // `suggest` (from the welcome): { name, example, request? }, a deck name to start from, a card in your
67
+ // pair and, for a first deck from AI help, what to ask it for.
68
+ // `into`: straight to adding cards to this deck (+ Add cards in /cards). `ai`: settings.ai, for
69
+ // suggestions while a card is typed (null: none).
70
+ // the ways to add a card, a name and what to type side by side
71
+ function Ways({ example, ai }) {
72
+ const rows = [
73
+ { name: t("add.ways.type"), what: example, typed: true },
74
+ { name: t("add.ways.paste"), what: t("add.ways.pasteWhat") },
75
+ ai && { name: `✦ ${t("add.ways.ai")}`, what: t("add.ways.aiExample"), typed: true, color: theme.accent }
76
+ ].filter(Boolean);
77
+ const width = Math.max(...rows.map((row) => cellWidth(row.name))) + 3;
78
+ return html`
79
+ <${Box} flexDirection="column" marginTop=${1}>
80
+ ${rows.map(
81
+ (row) => html`
82
+ <${Box} key=${row.name}>
83
+ <${Box} width=${width} flexShrink=${0}><${Text} color=${row.color} dimColor=${!row.color}>${row.name}<//><//>
84
+ <${Text} wrap="truncate-end" color=${row.typed ? row.color : undefined} dimColor=${!row.typed}>${row.what}<//>
85
+ <//>
86
+ `
87
+ )}
88
+ <//>
89
+ `;
90
+ }
91
+
92
+ export function AddCard({ current, actions, onDone, startNew = false, suggest = null, into = null, ai = null }) {
65
93
  const panel = usePanelWidth();
66
94
  const [step, setStep] = useState("loading"); // loading | pick | deck | line | back | direction | review | fix | saving
67
95
  const [decks, setDecks] = useState([]);
@@ -78,10 +106,21 @@ export function AddCard({ current, actions, onDone, startNew = false }) {
78
106
  const [direction, setDirection] = useState(0);
79
107
  const [sample, setSample] = useState(null); // the card the direction question shows
80
108
  const busy = useRef(false); // a save in flight: Enter again does nothing
81
- const [pasted, setPasted] = useState(null); // { items, selected, confirm, fixing }
109
+ const [pasted, setPasted] = useState(null); // { items, selected, confirm, total, ai? }: ai = { request, writing, problem } for a list from AI help
110
+ const listing = useRef(null); // the AI list being written: its AbortController
111
+ const [spin, setSpin] = useState(0);
112
+ const writing = Boolean(pasted?.ai?.writing);
113
+ useEffect(() => {
114
+ if (!writing) return;
115
+ const timer = setInterval(() => setSpin((n) => n + 1), 100);
116
+ return () => clearInterval(timer);
117
+ }, [writing]);
118
+ useEffect(() => () => listing.current?.abort(), []);
82
119
  const [message, setMessage] = useState("");
83
120
  const [error, setError] = useState("");
84
121
  const lookup = useRef(0);
122
+ const taken = useRef(new Set()); // the fronts whose suggestion was taken (Tab) in this /add
123
+ const help = useAssist({ ai, actions, deck, step, typed, draft, added });
85
124
 
86
125
  useEffect(() => {
87
126
  actions.ownDecks().then(
@@ -89,6 +128,9 @@ export function AddCard({ current, actions, onDone, startNew = false }) {
89
128
  setDecks(own);
90
129
  setPicked(Math.max(0, own.findIndex((d) => d.name === current)));
91
130
  setStep(own.length && !startNew ? "pick" : "deck");
131
+ if (suggest?.name && (startNew || !own.length)) clearField(suggest.name);
132
+ const given = into ? own.findIndex((d) => d.name === into) : -1;
133
+ if (given >= 0) pickDeck(given, own);
92
134
  },
93
135
  (err) => setError(err.message)
94
136
  );
@@ -121,8 +163,8 @@ export function AddCard({ current, actions, onDone, startNew = false }) {
121
163
  const { deck: created, removed } = await actions.startDeck({ name });
122
164
  setDeck({ name: created.name, directions: created.directions, isNew: true });
123
165
  setNewDeck({ name: created.name, removed });
124
- setMessage(t("add.deckReady", { deck: created.name }));
125
- clearField();
166
+ setMessage(t(suggest?.request ? "add.deckReadyAi" : "add.deckReady", { deck: created.name }));
167
+ clearField(suggest?.request ? `?${suggest.request}` : ""); // from the welcome: a list from AI, ready to ask for
126
168
  setStep("line");
127
169
  } catch (err) {
128
170
  setError(err.message);
@@ -163,9 +205,15 @@ export function AddCard({ current, actions, onDone, startNew = false }) {
163
205
  }, () => {});
164
206
  }
165
207
 
166
- async function save(fields) {
208
+ async function save(typed) {
167
209
  if (busy.current) return;
168
210
  busy.current = true;
211
+ // an answer or the example AI suggested for this front, taken and still there: the card is AI's,
212
+ // marked until it's checked. A card fixed (↑) with nothing changed keeps its mark.
213
+ const same = (a, b) => a.trim().toLowerCase() === b.trim().toLowerCase();
214
+ const suggested = taken.current.has(frontKey(typed.front)) && help.suggestionFor(typed.front);
215
+ const written = Boolean(suggested && (typed.back.some((answer) => suggested.back.some((other) => same(answer, other))) || (typed.example && suggested.example && same(typed.example, suggested.example))));
216
+ const fields = { ...typed, ai: written || Boolean(editing?.ai && formatLine(typed) === formatLine(editing)) };
169
217
  try {
170
218
  if (editing) {
171
219
  const { card, staleKeys } = await actions.updateCardIn(deck.name, editing.id, fields);
@@ -204,6 +252,11 @@ export function AddCard({ current, actions, onDone, startNew = false }) {
204
252
  }
205
253
  if (step === "line") {
206
254
  if (!value) return setError(t("add.needFront"));
255
+ if (ai && value === "?") return setError(t("add.ai.needRequest"));
256
+ if (/^\?\s*\S/.test(value) && !value.includes(" = ")) {
257
+ if (ai) return askForList(value.slice(1).trim());
258
+ return setError(t("add.ai.listOff"));
259
+ }
207
260
  const fields = parseLine(value);
208
261
  if (!fields.front) return setError(t("add.needFront"));
209
262
  if (duplicate) return; // the warning is already under the field
@@ -229,7 +282,7 @@ export function AddCard({ current, actions, onDone, startNew = false }) {
229
282
  .then((existing) => {
230
283
  setPasted((p) => {
231
284
  const issue = issueOf(fields, deck.isNew ? null : deck.directions, Boolean(existing));
232
- return { ...p, items: p.items.map((item, i) => (i === p.selected ? { line: value, fields, issue, dropped: false } : item)), confirm: false };
285
+ return { ...p, items: p.items.map((item, i) => (i === p.selected ? { ...item, line: value, fields, issue, dropped: false, changed: item.changed || value !== item.line } : item)), confirm: false };
233
286
  });
234
287
  setStep("review");
235
288
  });
@@ -263,10 +316,10 @@ export function AddCard({ current, actions, onDone, startNew = false }) {
263
316
  clearField(formatLine(last));
264
317
  }
265
318
 
266
- function pickDeck(index) {
267
- if (index === decks.length) return setStep("deck");
268
- setDeck({ name: decks[index].name, directions: decks[index].directions, isNew: false });
269
- actions.languagesOf(decks[index].name).then((found) => (shownPair.current = pairText(found)), () => {});
319
+ function pickDeck(index, list = decks) {
320
+ if (index === list.length) return setStep("deck");
321
+ setDeck({ name: list[index].name, directions: list[index].directions, isNew: false });
322
+ actions.languagesOf(list[index].name).then((found) => (shownPair.current = pairText(found)), () => {});
270
323
  clearField();
271
324
  setStep("line");
272
325
  }
@@ -313,6 +366,7 @@ export function AddCard({ current, actions, onDone, startNew = false }) {
313
366
  async function openPaste(text) {
314
367
  const list = readCardList(text, { comments: false }); // a pasted "#tag = hashtag" is a card
315
368
  if (!list.items.length) return setStep("line");
369
+ setEditing(null);
316
370
  const fronts = await Promise.all(list.items.map((item) => actions.existingCard(deck.name, item.fields.front).catch(() => null)));
317
371
  const existing = new Set(fronts.filter(Boolean).map((card) => frontKey(card.front)));
318
372
  setPasted({ items: readPaste(list, existing, deck.isNew ? null : deck.directions), selected: 0, confirm: false, total: list.items.length });
@@ -321,12 +375,46 @@ export function AddCard({ current, actions, onDone, startNew = false }) {
321
375
  setStep("review");
322
376
  }
323
377
 
378
+ // "?20 words for the kitchen": AI help writes a list into the review as it goes; none is kept
379
+ // until you keep it (space, or a for all)
380
+ async function askForList(request) {
381
+ listing.current?.abort();
382
+ const controller = (listing.current = new AbortController());
383
+ setEditing(null); // the list's cards are new ones: the last card isn't being fixed any more
384
+ setPasted({ items: [], selected: 0, confirm: false, total: 0, ai: { request, writing: true, problem: "" } });
385
+ setError("");
386
+ setMessage("");
387
+ clearField();
388
+ setStep("review");
389
+ const update = (change) => setPasted((p) => (p && listing.current === controller ? change(p) : p));
390
+ try {
391
+ const [languages, cards] = await Promise.all([actions.languagesOf(deck.name).catch(() => ({})), actions.cardsIn(deck.name).catch(() => [])]);
392
+ const known = new Set([...cards, ...added].map((card) => frontKey(card.front)));
393
+ const directions = deck.isNew ? null : deck.directions;
394
+ await suggestCards(ai, {
395
+ request,
396
+ languages,
397
+ cards: [...cards, ...added],
398
+ signal: controller.signal,
399
+ onCard: (fields) => update((p) => ({ ...p, total: p.total + 1, items: [...p.items, { line: formatLine(fields), fields, issue: issueOf(fields, directions, known.has(frontKey(fields.front))), dropped: true, ai: true }] }))
400
+ });
401
+ update((p) => ({ ...p, ai: { ...p.ai, writing: false, problem: p.items.length ? "" : t("add.ai.noList") } }));
402
+ } catch (err) {
403
+ if (controller.signal.aborted) return;
404
+ update((p) => ({ ...p, ai: { ...p.ai, writing: false, problem: err.message } }));
405
+ }
406
+ }
407
+
324
408
  async function addPasted() {
325
409
  const ready = withRepeats(pasted.items).filter((item) => !item.dropped && !item.issue);
326
- if (!ready.length) return setError(t("add.paste.nothing"));
410
+ if (!ready.length) return setError(t(pasted.ai ? "add.ai.nothingKept" : "add.paste.nothing"));
411
+ // what's kept so far is added; the rest of the list isn't written
412
+ listing.current?.abort();
413
+ listing.current = null;
414
+ if (pasted.ai?.writing) setPasted((p) => ({ ...p, ai: { ...p.ai, writing: false } }));
327
415
  setStep("saving");
328
416
  try {
329
- const { added: cards } = await actions.addCardsTo(deck.name, ready.map((item) => item.fields));
417
+ const { added: cards } = await actions.addCardsTo(deck.name, ready.map((item) => ({ ...item.fields, ai: Boolean(item.ai && !item.changed) })));
330
418
  setAdded((list) => [...list, ...cards]);
331
419
  setPasted(null);
332
420
  const skipped = pasted.items.length - ready.length - pasted.items.filter((item) => item.dropped).length;
@@ -354,8 +442,14 @@ export function AddCard({ current, actions, onDone, startNew = false }) {
354
442
 
355
443
  useInput(
356
444
  (input, key) => {
445
+ const keeping = pasted.items.some((item) => !item.dropped && !item.issue);
357
446
  if (key.escape) {
358
- if (pasted.confirm) {
447
+ // an AI list with nothing kept goes at once; anything kept or pasted is asked about first
448
+ if (pasted.confirm || (pasted.ai && !keeping)) {
449
+ listing.current?.abort();
450
+ listing.current = null;
451
+ // an AI list let go: its request is back in the field, to change and ask again
452
+ if (pasted.ai) clearField(`?${pasted.ai.request}`);
359
453
  setPasted(null);
360
454
  setError("");
361
455
  return setStep("line");
@@ -363,9 +457,15 @@ export function AddCard({ current, actions, onDone, startNew = false }) {
363
457
  return setPasted((p) => ({ ...p, confirm: true }));
364
458
  }
365
459
  if (pasted.confirm) setPasted((p) => ({ ...p, confirm: false }));
460
+ if (!pasted.items.length) return; // an AI list still on its way
366
461
  if (key.upArrow) return setPasted((p) => ({ ...p, selected: Math.max(0, p.selected - 1) }));
367
- if (key.downArrow) return setPasted((p) => ({ ...p, selected: Math.min(p.items.length - 1, p.selected + 1) }));
368
- if (input === "x") return setPasted((p) => ({ ...p, items: p.items.map((item, i) => (i === p.selected ? { ...item, dropped: !item.dropped } : item)) }));
462
+ if (key.downArrow) return setPasted((p) => ({ ...p, selected: Math.max(0, Math.min(p.items.length - 1, p.selected + 1)) }));
463
+ if (input === "x" || (pasted.ai && input === " ")) return setPasted((p) => ({ ...p, items: p.items.map((item, i) => (i === p.selected ? { ...item, dropped: !item.dropped } : item)) }));
464
+ if (pasted.ai && input === "a") {
465
+ // all kept, or with all kept already, none
466
+ const all = pasted.items.every((item) => item.issue || !item.dropped);
467
+ return setPasted((p) => ({ ...p, items: p.items.map((item) => (item.issue ? item : { ...item, dropped: all })) }));
468
+ }
369
469
  if (input === "e") {
370
470
  clearField(pasted.items[pasted.selected].line);
371
471
  return setStep("fix");
@@ -389,10 +489,14 @@ export function AddCard({ current, actions, onDone, startNew = false }) {
389
489
  if (step === "languages") return html`<${LanguagePicker} deck=${deck.name} sample=${sample} languages=${langs} learning=${langs.learning} home=${langs.home} onDone=${saveLanguages} onCancel=${() => setStep("direction")} />`;
390
490
 
391
491
  const title =
392
- step === "pick" ? t("add.titlePick") : step === "deck" ? t(decks.length ? "add.titleNew" : "add.titleFirst") : step === "review" || step === "fix" ? t("add.paste.title", { deck: deck.name }) : t("add.titleCard", { deck: deck?.name ?? "" });
492
+ step === "pick" ? t("add.titlePick") : step === "deck" ? t(decks.length ? "add.titleNew" : "add.titleFirst") : step === "review" || step === "fix" ? t(pasted?.ai ? "add.ai.listTitle" : "add.paste.title", { deck: deck.name }) : t("add.titleCard", { deck: deck?.name ?? "" });
393
493
  const fieldLabel = step === "deck" ? "deck" : step === "back" ? "back" : step === "line" || step === "fix" ? "line" : null;
394
- const parsed = step === "line" && typed.trim() ? parseLine(typed) : null;
395
- const preview = !parsed ? null : parsed.cloze || parsed.back.length ? askedAs(parsed, deck.isNew ? null : deck.directions) : parsed.hasBack ? null : t("add.preview.noBack");
494
+ // with a suggestion on screen, the card it would make (Tab takes it)
495
+ const asking = Boolean(ai && step === "line" && !editing && typed.startsWith("?")); // "?…" asks AI for a list
496
+ const parsed = step === "line" && typed.trim() && !asking ? parseLine(typed + help.ghost) : null;
497
+ // only what isn't plain from the line itself: a cloze's gaps, or how a lone front goes on (unless AI
498
+ // help is busy with its back)
499
+ const preview = !parsed ? null : parsed.cloze ? askedAs(parsed, null) : parsed.back.length || parsed.hasBack || help.status ? null : t("add.preview.noBack");
396
500
  const shownPaste = pasted ? withRepeats(pasted.items) : [];
397
501
  const ready = shownPaste.filter((item) => !item.dropped && !item.issue).length;
398
502
  const narrow = panel < 60;
@@ -407,7 +511,7 @@ export function AddCard({ current, actions, onDone, startNew = false }) {
407
511
  html`
408
512
  <${Box} flexDirection="column" marginTop=${1}>
409
513
  ${added.length > SHOWN_CARDS && html`<${Text} dimColor>${t("add.more", { count: added.length - SHOWN_CARDS })}<//>`}
410
- ${added.slice(-SHOWN_CARDS).map((card) => html`<${Text} key=${card.id} dimColor wrap="truncate-end"><${Text} color=${theme.good}>${card.fixed ? "✎" : "✓"}<//> ${card.cloze ? plainFront(card.front) : `${card.front} = ${answers(card.back)}`}<//>`)}
514
+ ${added.slice(-SHOWN_CARDS).map((card) => html`<${Text} key=${card.id} dimColor wrap="truncate-end"><${Text} color=${card.ai ? theme.accent : theme.good}>${card.ai ? "✦" : card.fixed ? "✎" : "✓"}<//> ${card.cloze ? plainFront(card.front) : `${card.front} = ${answers(card.back)}`}<//>`)}
411
515
  <//>
412
516
  `}
413
517
  ${message && html`<${Box} marginTop=${1}><${Text} color=${theme.good}>${message}<//><//>`}
@@ -417,7 +521,9 @@ export function AddCard({ current, actions, onDone, startNew = false }) {
417
521
  html`
418
522
  <${Box} flexDirection="column" marginTop=${1}>
419
523
  <${Text} bold>${t(`add.fields.${fieldLabel}.label`)}<//>
420
- <${Text} dimColor>${t(`add.fields.${fieldLabel}.hint`)}<//>
524
+ ${fieldLabel === "line"
525
+ ? !asking && html`<${Ways} example=${suggest?.example || t("add.fields.line.hint")} ai=${ai && !editing} />`
526
+ : html`<${Text} dimColor>${t(`add.fields.${fieldLabel}.hint`)}<//>`}
421
527
  <${Box} marginTop=${1}>
422
528
  <${AnswerInput}
423
529
  key=${`${fieldLabel}-${field.key}`}
@@ -427,9 +533,13 @@ export function AddCard({ current, actions, onDone, startNew = false }) {
427
533
  onExit=${back}
428
534
  onChange=${onType}
429
535
  onRecall=${step === "line" ? recall : undefined}
536
+ cardLine=${step === "line" || step === "fix"}
430
537
  onPaste=${step === "line" ? openPaste : undefined}
538
+ ghost=${help.ghost}
539
+ onGhost=${() => help.front && taken.current.add(frontKey(help.front))}
431
540
  />
432
541
  <//>
542
+ ${help.status && html`<${Box} paddingLeft=${2} marginTop=${1}><${Text} color=${help.problem ? theme.warn : theme.accent}>${help.spinner ?? "✦"} ${help.status}<//><//>`}
433
543
  ${preview && html`<${Box} paddingLeft=${2}><${Text} dimColor>${preview}<//><//>`}
434
544
  ${duplicate && step === "line" && html`<${Box} paddingLeft=${2}><${Text} color=${theme.warn}>${t("add.duplicateCard", { front: duplicate.front, deck: deck.name })}<//><//>`}
435
545
  <//>
@@ -480,29 +590,39 @@ export function AddCard({ current, actions, onDone, startNew = false }) {
480
590
  pasted &&
481
591
  html`
482
592
  <${Box} flexDirection="column" marginTop=${1}>
483
- <${Text}>${t("add.paste.summary", { lines: pasted.total, count: ready })}${shownPaste.some((item) => item.issue && !item.dropped) ? t("add.paste.attention", { count: shownPaste.filter((item) => item.issue && !item.dropped).length }) : ""}<//>
593
+ ${pasted.ai
594
+ ? html`<${Box} flexDirection="column">
595
+ ${pasted.ai.writing
596
+ ? html`<${Text} color=${theme.accent}>${SPIN[spin % SPIN.length]} ${t("add.ai.request", { request: cutToWidth(pasted.ai.request, Math.max(16, panel - 40)) })} · ${pasted.items.length ? t("add.ai.writing", { provider: providerName(ai.provider), count: pasted.items.length }) : t("add.ai.writingStart", { provider: providerName(ai.provider) })}<//>`
597
+ : html`<${Text}>${t("add.ai.request", { request: cutToWidth(pasted.ai.request, Math.max(16, panel - 40)) })} · ${t("add.ai.listSummary", { count: pasted.items.length, kept: ready })}<//>`}
598
+ ${pasted.ai.problem && html`<${Text} color=${theme.warn}>${pasted.ai.problem}<//>`}
599
+ <//>`
600
+ : html`<${Text}>${t("add.paste.summary", { lines: pasted.total, count: ready })}${shownPaste.some((item) => item.issue && !item.dropped) ? t("add.paste.attention", { count: shownPaste.filter((item) => item.issue && !item.dropped).length }) : ""}<//>`}
484
601
  <${Box} flexDirection="column" marginTop=${1}>
485
602
  ${shownPaste.slice(firstRow, firstRow + PASTE_ROWS).map((item, i) => {
486
603
  const index = firstRow + i;
487
604
  const on = index === pasted.selected && step === "review";
488
- const mark = item.dropped ? "✗" : item.issue ? "!" : "✓";
489
- const color = item.dropped ? undefined : item.issue ? theme.warn : theme.good;
605
+ // a suggestion not kept (yet) is a plain circle, not a line crossed out
606
+ const mark = item.ai ? (item.issue ? "!" : item.dropped ? "○" : "✓") : item.dropped ? "✗" : item.issue ? "!" : "✓";
607
+ const color = item.issue && (item.ai || !item.dropped) ? theme.warn : item.dropped ? undefined : theme.good;
608
+ const crossed = item.dropped && !item.ai;
609
+ const showIssue = item.issue && (item.ai || !item.dropped);
490
610
  return html`
491
- <${Box} key=${index} flexDirection=${narrow && item.issue && !item.dropped ? "column" : "row"}>
611
+ <${Box} key=${index} flexDirection=${narrow && showIssue ? "column" : "row"}>
492
612
  <${Box}>
493
613
  <${Box} flexShrink=${0}>
494
614
  <${Text} color=${on ? theme.accent : undefined}>${on ? "❯ " : " "}<//>
495
- <${Text} color=${color} dimColor=${item.dropped}>${mark} <//>
615
+ <${Text} color=${color} dimColor=${item.dropped && !item.issue}>${mark} <//>
496
616
  <//>
497
- <${Box} flexGrow=${1}><${Text} dimColor=${item.dropped} strikethrough=${item.dropped} wrap="truncate-end">${item.fields.cloze ? plainFront(item.fields.front) : item.fields.back.length ? `${item.fields.front} = ${answers(item.fields.back)}` : item.fields.front}<//><//>
617
+ <${Box} flexGrow=${1}><${Text} dimColor=${item.dropped} strikethrough=${crossed} wrap="truncate-end">${item.fields.cloze ? plainFront(item.fields.front) : item.fields.back.length ? `${item.fields.front} = ${answers(item.fields.back)}${item.fields.example ? " " : ""}` : item.fields.front}${item.fields.example && !item.fields.cloze ? html`<${Text} dimColor>${item.fields.example}<//>` : ""}<//><//>
498
618
  <//>
499
- ${item.issue && !item.dropped && html`<${Box} flexShrink=${0} marginLeft=${narrow ? 4 : 0}><${Text} color=${theme.warn}>${narrow ? "" : " "}${t(`add.paste.issues.${item.issue}`)}<//><//>`}
619
+ ${showIssue && html`<${Box} flexShrink=${0} marginLeft=${narrow ? 4 : 0}><${Text} color=${theme.warn}>${narrow ? "" : " "}${t(`add.paste.issues.${item.issue}`)}<//><//>`}
500
620
  <//>
501
621
  `;
502
622
  })}
503
623
  <//>
504
624
  ${pasted.items.length > PASTE_ROWS && html`<${Text} dimColor>${t("add.paste.position", { at: pasted.selected + 1, count: pasted.items.length })}<//>`}
505
- ${pasted.confirm && html`<${Box} marginTop=${1}><${Text} color=${theme.warn}>${t("add.paste.confirm", { count: ready })}<//><//>`}
625
+ ${pasted.confirm && html`<${Box} marginTop=${1}><${Text} color=${theme.warn}>${t(pasted.ai ? "add.ai.confirm" : "add.paste.confirm", { count: ready })}<//><//>`}
506
626
  <//>
507
627
  `}
508
628
  ${error && html`<${Box} marginTop=${1}><${Text} color=${theme.bad}>${error}<//><//>`}
@@ -516,18 +636,96 @@ export function AddCard({ current, actions, onDone, startNew = false }) {
516
636
  : step === "deck"
517
637
  ? t("keyHints.addName")
518
638
  : step === "review"
519
- ? t("keyHints.pasteReview", { count: ready })
639
+ ? pasted?.ai
640
+ ? t(!pasted.items.length ? "keyHints.aiWaiting" : ready ? "keyHints.aiReview" : "keyHints.aiReviewNone", { count: ready })
641
+ : t("keyHints.pasteReview", { count: ready })
520
642
  : step === "fix"
521
643
  ? t("keyHints.pasteFix")
522
644
  : step === "back"
523
- ? t("keyHints.addBack")
524
- : step === "line" && editing
525
- ? t("keyHints.addFixing")
526
- : step === "line" && added.length
527
- ? t("keyHints.addMore")
528
- : t("keyHints.addFirst")}
645
+ ? (help.ghost ? `${t("keyHints.takeSuggestion")} · ` : "") + t("keyHints.addBack")
646
+ : asking
647
+ ? t("keyHints.askList")
648
+ : `${help.ghost ? t("keyHints.takeSuggestion") : t("keyHints.tabPart")} · ${editing ? t("keyHints.addFixing") : added.length ? t("keyHints.addMore") : t("keyHints.addFirst")}`}
529
649
  />
530
650
  <//>
531
651
  <//>
532
652
  `;
533
653
  }
654
+
655
+ const PAUSE_MS = 350; // typing stops this long before a suggestion is asked for
656
+ const SPIN = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
657
+ const STOPPING = new Set(["noKey", "badKey", "noModel", "noCredit", "offline", "offlineLocal"]); // no point asking again in this /add
658
+
659
+ // Suggestions for the card being typed: once its front is followed by " = " (or on the back's own
660
+ // field), the model is asked for the back and an example, shown dimmed after what's typed (`ghost`).
661
+ // It goes away as soon as the typing no longer matches it; every key cancels a request in flight.
662
+ // The ghost is one part at a time: Tab takes the back, then the example. → { ghost, status, spinner, problem }
663
+ function useAssist({ ai, actions, deck, step, typed, draft, added }) {
664
+ const [answers, setAnswers] = useState({}); // front → suggestion line ("" for nothing usable)
665
+ const [asking, setAsking] = useState(null); // the front asked about now
666
+ const [problem, setProblem] = useState("");
667
+ const context = useRef(null); // { deck, languages, cards } of the deck being added to
668
+ const [spin, setSpin] = useState(0);
669
+ const stopped = useRef(false);
670
+
671
+ // what's typed → the front to ask about, and the text the suggestion follows
672
+ const target = (() => {
673
+ if (!ai || !deck || stopped.current) return null;
674
+ if (step === "back" && draft && !draft.cloze && !typed.includes(" // ")) return { front: draft.front, base: "" };
675
+ if (step !== "line" || typed.startsWith("?")) return null; // "?…" asks for a list
676
+ const at = typed.indexOf(" = ");
677
+ if (at < 1 || typed.includes(" // ") || typed.indexOf(" = ", at + 3) >= 0) return null;
678
+ const fields = parseLine(typed.slice(0, at));
679
+ return fields.front && !fields.cloze ? { front: fields.front, base: typed.slice(0, at + 3) } : null;
680
+ })();
681
+ const front = target?.front ?? null;
682
+
683
+ useEffect(() => {
684
+ if (!front || front in answers) return;
685
+ const controller = new AbortController();
686
+ const timer = setTimeout(async () => {
687
+ setAsking(front);
688
+ try {
689
+ if (context.current?.deck !== deck.name) {
690
+ const [languages, cards] = await Promise.all([actions.languagesOf(deck.name).catch(() => ({})), actions.cardsIn(deck.name).catch(() => [])]);
691
+ context.current = { deck: deck.name, languages, cards };
692
+ }
693
+ const cards = [...context.current.cards, ...added];
694
+ const found = await suggestCard(ai, { front, languages: context.current.languages, cards, signal: controller.signal });
695
+ setProblem("");
696
+ setAnswers((all) => ({ ...all, [front]: found ? found.back.join("; ") + (found.example ? ` // ${found.example}` : "") : "" }));
697
+ } catch (err) {
698
+ if (controller.signal.aborted) return;
699
+ if (STOPPING.has(err.code)) stopped.current = true;
700
+ setProblem(err.message);
701
+ } finally {
702
+ setAsking((now) => (now === front ? null : now));
703
+ }
704
+ }, PAUSE_MS);
705
+ return () => {
706
+ clearTimeout(timer);
707
+ controller.abort();
708
+ };
709
+ }, [front, deck?.name]);
710
+
711
+ const waiting = Boolean(ai && front && asking === front);
712
+ useEffect(() => {
713
+ if (!waiting) return;
714
+ const timer = setInterval(() => setSpin((n) => n + 1), 100);
715
+ return () => clearInterval(timer);
716
+ }, [waiting]);
717
+
718
+ // what was suggested for a front → { back, example } (null: nothing)
719
+ const suggestionFor = (asked) => (answers[asked] ? parseBack(answers[asked]) : null);
720
+ if (!ai) return { ghost: "", status: "", problem: false, suggestionFor };
721
+ const line = target && answers[target.front] ? target.base + answers[target.front] : "";
722
+ const rest = line && line.length > typed.length && line.toLowerCase().startsWith(typed.toLowerCase()) ? line.slice(typed.length) : "";
723
+ const cut = rest.indexOf(" // ");
724
+ const ghost = cut > 0 ? rest.slice(0, cut) : rest; // the back first; its example once the back is in
725
+ const name = providerName(ai.provider);
726
+ const common = { ghost, front, suggestionFor };
727
+ if (problem) return { ...common, status: problem, problem: true };
728
+ if (ghost) return { ...common, status: t(ghost.startsWith(" // ") ? "add.ai.example" : "add.ai.suggested", { provider: name }), problem: false };
729
+ if (waiting) return { ...common, status: t("add.ai.thinking", { provider: name }), spinner: SPIN[spin % SPIN.length], problem: false };
730
+ return { ...common, status: "", problem: false };
731
+ }