dracosh 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/session.js CHANGED
@@ -1,9 +1,9 @@
1
1
  import { t as say } from "./i18n.js"; // `t` and `text` are taken here (the clock, an answer)
2
2
  import { blankGap, plainFront } from "./cardline.js";
3
3
  import { ALMOST, closestCandidate, judge } from "./judge.js";
4
- import { addVacation, applyAnswer, applyCaughtUp, markWorkWaiting, applyOverrule, calendarMonth, cancelVacations, ensureProgress, markBadgesSeen, missedOn, recordMiss, snapshot, undoMiss, unseenBadges, vacationInfo } from "./progress.js";
5
- import { BOX_INTERVALS_DAYS, describeDue, grade, itemKey, nextDueAt, pickNext, startOfTomorrow } from "./scheduler.js";
6
- import { recordAnswer, saveState } from "./store.js";
4
+ import { addVacation, applyAnswer, applyCaughtUp, markWorkWaiting, applyOverrule, calendarMonth, cancelVacations, dropElement, ensureProgress, markBadgesSeen, missedOn, recordMiss, snapshot, undoMiss, unseenBadges, vacationInfo } from "./progress.js";
5
+ import { describeDue, grade, intervalDays, itemKey, nextDueAt, pickNext, Rating, ratingFor, startOfTomorrow } from "./scheduler.js";
6
+ import { recordAnswer, saveState, STATE_VERSION } from "./store.js";
7
7
  import { createTipDeck } from "./tips.js";
8
8
  import { dayKey } from "./dates.js";
9
9
  import { parsePause } from "./pause.js";
@@ -32,6 +32,14 @@ export function toSpeak(question, answer = null) {
32
32
 
33
33
  // Quiz logic without any I/O of its own: words, settings and persistence are injected, the UI only renders what this returns.
34
34
  // `loadAllWords` → [{ words, deck }] for every deck of yours: "all done for today" means the whole library.
35
+ // the days until a card comes back (0: minutes away, still being learned), and the days a clean answer
36
+ // would have given it; null when the difference isn't worth a line (a day or two, or under a quarter)
37
+ function heldBack(entry, would) {
38
+ const [days, wouldDays] = [intervalDays(entry), intervalDays(would)];
39
+ const worth = days === 0 ? wouldDays > 0 : wouldDays - days >= 2 && wouldDays >= days * 1.25;
40
+ return worth ? { days, would: wouldDays } : null;
41
+ }
42
+
35
43
  export function createSession({ loadWords, loadAllWords, state, getSettings, save = saveState, now = Date.now, tipDeck = createTipDeck({ state }) }) {
36
44
  const rules = () => ({ skipWeekends: getSettings().skipWeekends });
37
45
  const totals = { asked: 0, correct: 0, combo: 0 };
@@ -90,6 +98,7 @@ export function createSession({ loadWords, loadAllWords, state, getSettings, sav
90
98
  }
91
99
  lastNoteId = item.word.noteId;
92
100
  lastWrong = null;
101
+ const from = item.word.deck ?? deck; // decks practised together: the card's own deck
93
102
 
94
103
  const forward = item.direction === "en-pl";
95
104
  const gap = item.direction.startsWith("c") ? Number(item.direction.slice(1)) - 1 : null;
@@ -102,15 +111,15 @@ export function createSession({ loadWords, loadAllWords, state, getSettings, sav
102
111
  return {
103
112
  word: item.word,
104
113
  direction: item.direction,
105
- label: labelOf(deck),
114
+ label: labelOf(from),
106
115
  prompt,
107
116
  expected,
108
117
  // a cloze card's back is a hint under the sentence ("Cieszę się na to")
109
118
  context: gap !== null ? item.word.translations.join(" / ") : "",
110
119
  // what the answer is written in, when the deck's languages are known: its own spellings count
111
- answerLanguage: (forward ? deck?.languages?.back : deck?.languages?.front) ?? null,
112
- promptLanguage: (forward ? deck?.languages?.front : deck?.languages?.back) ?? null,
113
- learningLanguage: deck?.learning?.lang ?? null,
120
+ answerLanguage: (forward ? from?.languages?.back : from?.languages?.front) ?? null,
121
+ promptLanguage: (forward ? from?.languages?.front : from?.languages?.back) ?? null,
122
+ learningLanguage: from?.learning?.lang ?? null,
114
123
  wordCount: words.length,
115
124
  tour: Boolean(deck?.tour) // the tour marks what to type with `backticks`
116
125
  };
@@ -134,7 +143,7 @@ export function createSession({ loadWords, loadAllWords, state, getSettings, sav
134
143
  // An empty Enter shows the answer and nothing is written yet: you say whether you knew it (selfGrade).
135
144
  const reveal = (question) => ({ expected: question.expected, example: question.word.example });
136
145
 
137
- // After a reveal. "Knew it" counts exactly like a typed right answer: boxes, goal, streak, combo and
146
+ // After a reveal. "Knew it" counts exactly like a typed right answer: scheduling, goal, streak, combo and
138
147
  // badges. Long answers can't be typed word for word, and they must be able to earn everything too.
139
148
  async function selfGrade(question, knew, { hinted = false } = {}) {
140
149
  return { ...(await record(question, { result: knew ? "exact" : "wrong", text: "", hinted })), self: true };
@@ -146,11 +155,13 @@ export function createSession({ loadWords, loadAllWords, state, getSettings, sav
146
155
  const t = now();
147
156
  const before = state.items[key];
148
157
  const comboBefore = totals.combo;
149
- // almost right (an article left out, an umlaut left plain) counts, but the card doesn't move up, like with a hint
150
- const almost = ALMOST.includes(result);
151
- const entry = grade(before, correct, t, { hinted: hinted || almost });
152
- const would = almost ? grade(before, true, t, { hinted }) : entry; // a hint alone would have held it too
153
- const held = would.box > entry.box ? { days: BOX_INTERVALS_DAYS[entry.box - 1], would: BOX_INTERVALS_DAYS[would.box - 1] } : null;
158
+ // almost right (an article left out, an umlaut left plain) or a typo counts, but like with a hint
159
+ // the card comes back sooner than after a clean answer: `held` says when, and when it would have
160
+ const almost = ALMOST.includes(result) || result === "typo";
161
+ const rating = ratingFor({ correct, hinted, almost });
162
+ const entry = grade(before, rating, t);
163
+ // a tour card never comes back, so there's nothing to say about when
164
+ const held = rating === Rating.Hard && !question.tour ? heldBack(entry, grade(before, Rating.Good, t)) : null;
154
165
  recordAnswer(state, question.word.noteId, question.direction, entry, t, { countNew: !question.tour });
155
166
 
156
167
  totals.asked += 1;
@@ -179,7 +190,7 @@ export function createSession({ loadWords, loadAllWords, state, getSettings, sav
179
190
  const { question, text, key, before, comboBefore, hinted, at } = lastWrong;
180
191
  lastWrong = null;
181
192
 
182
- const entry = grade(before, true, at, { hinted });
193
+ const entry = grade(before, ratingFor({ correct: true, hinted }), at);
183
194
  state.items[key] = entry;
184
195
  undoMiss(state, key, at);
185
196
  state.accepted ??= {};
@@ -243,6 +254,23 @@ export function createSession({ loadWords, loadAllWords, state, getSettings, sav
243
254
  await save(state);
244
255
  }
245
256
 
257
+ // the progress of these cards, as the trash keeps it with a deleted deck: how well each direction is
258
+ // known, answers you declared right, directions resting
259
+ function progressOf(cardIds) {
260
+ const ids = new Set(cardIds);
261
+ const mine = (key) => ids.has(key.slice(0, key.lastIndexOf(":")));
262
+ const pick = (object) => Object.fromEntries(Object.entries(object ?? {}).filter(([key]) => mine(key)));
263
+ return structuredClone({ items: pick(state.items), accepted: pick(state.accepted), dormant: (state.dormant ?? []).filter(mine) });
264
+ }
265
+
266
+ // a deck back from the trash: its progress with it
267
+ async function restoreProgress({ items = {}, accepted = {}, dormant = [] } = {}) {
268
+ Object.assign(state.items, items);
269
+ if (Object.keys(accepted).length) state.accepted = { ...state.accepted, ...accepted };
270
+ if (dormant.length) state.dormant = [...new Set([...(state.dormant ?? []), ...dormant])];
271
+ await save(state);
272
+ }
273
+
246
274
  // A deck is asked another way now (/decks): the directions it no longer asks rest. Their progress stays
247
275
  // for when they're back, but doesn't count against mastering the card.
248
276
  async function setDirections(cardIds, directions) {
@@ -264,12 +292,12 @@ export function createSession({ loadWords, loadAllWords, state, getSettings, sav
264
292
  }
265
293
 
266
294
  // Reset from /settings (the caller makes a backup first). "progress" starts the game over: badges,
267
- // streak, stats and the dragon's form and element; your cards and their boxes stay. "everything"
295
+ // streak, stats and the dragon's form and element; your cards and how well you know them stay. "everything"
268
296
  // empties the state as on a fresh install, so the egg hatches again.
269
297
  async function reset(scope) {
270
298
  if (scope === "everything") {
271
299
  for (const key of Object.keys(state)) delete state[key];
272
- Object.assign(state, { version: 1, items: {}, newToday: { date: "", count: 0 } });
300
+ Object.assign(state, { version: STATE_VERSION, items: {}, newToday: { date: "", count: 0 } });
273
301
  } else {
274
302
  delete state.progress;
275
303
  delete state.tips;
@@ -282,8 +310,22 @@ export function createSession({ loadWords, loadAllWords, state, getSettings, sav
282
310
  // the hatching intro plays once ever: on a brand-new state that has never answered anything
283
311
  const isFirstRun = () => !state.hatched && Object.keys(state.items).length === 0;
284
312
 
313
+ // the welcome follows the hatching (languages, then a way to start); `welcome` is its step to come
314
+ // back to, so a welcome left halfway goes on there next time
285
315
  async function markHatched() {
286
316
  state.hatched = true;
317
+ state.welcome = "language";
318
+ await save(state);
319
+ }
320
+ const welcomeStep = () => state.welcome ?? null;
321
+ async function setWelcomeStep(step) {
322
+ if (step) state.welcome = step;
323
+ else delete state.welcome;
324
+ await save(state);
325
+ }
326
+
327
+ async function defaultLook() {
328
+ dropElement(state, now());
287
329
  await save(state);
288
330
  }
289
331
 
@@ -305,5 +347,5 @@ export function createSession({ loadWords, loadAllWords, state, getSettings, sav
305
347
  await settleDay(); // nothing askable after all (a direction switched off): the quiet stretch goes on
306
348
  }
307
349
 
308
- return { totals, next, answer, workAdded, reveal, selfGrade, setDirections, forgetKeys, overrule, canOverrule, wrongAnswer, stats, month, missed, nextTip, pause, isFirstRun, markHatched, openBadges, forget, reset, inTour: () => inTour };
350
+ return { totals, next, answer, workAdded, reveal, selfGrade, setDirections, forgetKeys, progressOf, restoreProgress, overrule, canOverrule, wrongAnswer, stats, month, missed, nextTip, pause, isFirstRun, markHatched, welcomeStep, setWelcomeStep, openBadges, defaultLook, forget, reset, inTour: () => inTour };
309
351
  }
package/src/settings.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { LANGUAGES, systemLanguage, t } from "./i18n.js";
2
2
 
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 };
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, mix: null, homeLanguage: null, learningLanguage: null };
4
4
 
5
5
  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
6
  export const GOALS = [5, 10, 15, 20, 25, 30, 40, 50, 75, 100, 150, 200];
@@ -25,6 +25,7 @@ const normalizeTips = (value) => (value === true ? "always" : value === false ?
25
25
  const isHour = (v) => Number.isInteger(v) && v >= 0 && v <= 23;
26
26
 
27
27
  const isNumber = (v) => typeof v === "number" && Number.isFinite(v);
28
+ const isLanguage = (v) => typeof v === "string" && /^[a-z]{2,3}$/.test(v);
28
29
 
29
30
  // settings.json is hand-editable, so anything invalid falls back to the default instead of crashing
30
31
  export function normalizeSettings(raw = {}) {
@@ -40,6 +41,11 @@ export function normalizeSettings(raw = {}) {
40
41
  skipWeekends: typeof raw.skipWeekends === "boolean" ? raw.skipWeekends : DEFAULTS.skipWeekends,
41
42
  quiet: raw.quiet && isHour(raw.quiet.from) && isHour(raw.quiet.to) ? { from: raw.quiet.from, to: raw.quiet.to } : null,
42
43
  deck: typeof raw.deck === "string" && raw.deck.trim() ? raw.deck : null, // picked in /decks; null = your first deck
44
+ // decks practised together (/decks, space): "all" of yours, or two or more by name; null = only `deck`
45
+ 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,
46
+ // the language you speak and the one you're learning, from the welcome (codes; null: not said)
47
+ homeLanguage: isLanguage(raw.homeLanguage) ? raw.homeLanguage : null,
48
+ learningLanguage: isLanguage(raw.learningLanguage) ? raw.learningLanguage : null,
43
49
  language: typeof raw.language === "string" && Object.hasOwn(LANGUAGES, raw.language) ? raw.language : systemLanguage() // until picked in /settings, the system's
44
50
  };
45
51
  }
package/src/store.js CHANGED
@@ -4,7 +4,7 @@ import { homedir } from "node:os";
4
4
  import { dirname, join } from "node:path";
5
5
  import { dayKey } from "./dates.js";
6
6
  import { upgradeLibrary } from "./library.js";
7
- import { itemKey, newToday } from "./scheduler.js";
7
+ import { fromBox, itemKey, newToday } from "./scheduler.js";
8
8
 
9
9
  export const HOME = process.env.DRACOSH_HOME || join(homedir(), ".dracosh");
10
10
  const LIBRARY_FILE = join(HOME, "library.json");
@@ -13,7 +13,8 @@ const SETTINGS_FILE = join(HOME, "settings.json");
13
13
  // everything a backup holds, by name
14
14
  export const DATA_FILES = { library: LIBRARY_FILE, state: STATE_FILE, settings: SETTINGS_FILE };
15
15
 
16
- export const STATE_VERSION = 1;
16
+ // 1: Leitner boxes (Dracosh 0.5 and older); 2: FSRS
17
+ export const STATE_VERSION = 2;
17
18
  const emptyState = () => ({ version: STATE_VERSION, items: {}, newToday: { date: "", count: 0 } });
18
19
 
19
20
  const isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
@@ -57,19 +58,37 @@ export async function loadLibrary() {
57
58
  }
58
59
  export const saveLibrary = (library) => writeJson(LIBRARY_FILE, library);
59
60
 
60
- // Progress, checked for the shape the quiz relies on; a file from a newer Dracosh is never overwritten
61
+ // Progress, checked for the shape the quiz relies on; a file from a newer Dracosh is never overwritten.
62
+ // An older one is brought up to date in memory, `upgraded` saying so: it's written with the next save,
63
+ // once a backup holds the file as it was (see upgradeState).
61
64
  export async function loadState() {
62
65
  const state = await readJson(STATE_FILE, undefined);
63
66
  if (state === undefined) return emptyState();
64
67
  checkState(state, STATE_FILE);
65
68
  if (!isObject(state.newToday)) state.newToday = { date: "", count: 0 };
69
+ return upgradeState(state);
70
+ }
71
+
72
+ // progress of an older version → this one's (the same object); `upgraded` (not saved) says it changed
73
+ export function upgradeState(state) {
74
+ if ((state.version ?? 1) >= STATE_VERSION) return state;
75
+ for (const [key, entry] of Object.entries(state.items)) if (!("phase" in entry)) state.items[key] = fromBox(entry);
76
+ state.version = STATE_VERSION;
77
+ Object.defineProperty(state, "upgraded", { value: true, enumerable: false });
66
78
  return state;
67
79
  }
68
80
 
81
+ // a card's progress: Leitner's box in version 1, FSRS's memory since 2
82
+ const PHASES = new Set(["learning", "review", "relearning"]);
83
+ const fsrsEntry = (entry) => PHASES.has(entry.phase) && entry.stability > 0 && entry.difficulty > 0 && Number.isFinite(entry.last) && Number.isFinite(entry.seen);
84
+ const validEntry = (entry, version) => isObject(entry) && Number.isFinite(entry.due) && (fsrsEntry(entry) || (version < 2 && Number.isFinite(entry.box)));
85
+
69
86
  // throws when `state` (read from `file`) isn't progress the quiz can use
70
87
  export function checkState(state, file = STATE_FILE) {
71
88
  if (!isObject(state) || !isObject(state.items)) throw damaged(file, t("errors.why.noProgress"));
72
- if (!Object.values(state.items).every((entry) => isObject(entry) && Number.isFinite(entry.box) && Number.isFinite(entry.due))) throw damaged(file, t("errors.why.progressEntry"));
89
+ // a newer Dracosh's progress may look different: said as that, not as damage
90
+ if (state.version > STATE_VERSION) throw new Error(t("errors.newerState", { file }));
91
+ if (!Object.values(state.items).every((entry) => validEntry(entry, state.version ?? 1))) throw damaged(file, t("errors.why.progressEntry"));
73
92
  const { progress } = state;
74
93
  const validProgress =
75
94
  isObject(progress) &&
@@ -80,7 +99,6 @@ export function checkState(state, file = STATE_FILE) {
80
99
  isObject(progress.badges) &&
81
100
  (progress.vacations === undefined || Array.isArray(progress.vacations));
82
101
  if (progress !== undefined && !validProgress) throw damaged(file, t("errors.why.streak"));
83
- if (state.version > STATE_VERSION) throw new Error(t("errors.newerState", { file }));
84
102
  }
85
103
  export const saveState = (state) => writeJson(STATE_FILE, state);
86
104
 
@@ -101,8 +119,14 @@ export const loadSettingsRaw = async () => {
101
119
  return isObject(raw) ? raw : {};
102
120
  };
103
121
 
104
- // merges into what's on disk, so a one-off CLI flag never gets persisted by accident
105
- export async function patchSettings(patch) {
106
- const current = await loadSettingsRaw();
107
- 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;
108
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
@@ -61,7 +61,9 @@ function withRepeats(items) {
61
61
  // replaces the tour), then add cards one line each until Esc: "kot = cat; kitty // example". After a new
62
62
  // deck's first card it asks which way the deck is asked. A pasted list opens a review first.
63
63
  // `actions` reads and writes the library; `startNew` skips the deck list ("+ New deck" in /decks).
64
- export function AddCard({ current, actions, onDone, startNew = false }) {
64
+ // `suggest` (from the welcome): { name, example }, a deck name to start from and a card in your pair.
65
+ // `into`: straight to adding cards to this deck (+ Add cards in /cards).
66
+ export function AddCard({ current, actions, onDone, startNew = false, suggest = null, into = null }) {
65
67
  const panel = usePanelWidth();
66
68
  const [step, setStep] = useState("loading"); // loading | pick | deck | line | back | direction | review | fix | saving
67
69
  const [decks, setDecks] = useState([]);
@@ -89,6 +91,9 @@ export function AddCard({ current, actions, onDone, startNew = false }) {
89
91
  setDecks(own);
90
92
  setPicked(Math.max(0, own.findIndex((d) => d.name === current)));
91
93
  setStep(own.length && !startNew ? "pick" : "deck");
94
+ if (suggest?.name && (startNew || !own.length)) clearField(suggest.name);
95
+ const given = into ? own.findIndex((d) => d.name === into) : -1;
96
+ if (given >= 0) pickDeck(given, own);
92
97
  },
93
98
  (err) => setError(err.message)
94
99
  );
@@ -263,10 +268,10 @@ export function AddCard({ current, actions, onDone, startNew = false }) {
263
268
  clearField(formatLine(last));
264
269
  }
265
270
 
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)), () => {});
271
+ function pickDeck(index, list = decks) {
272
+ if (index === list.length) return setStep("deck");
273
+ setDeck({ name: list[index].name, directions: list[index].directions, isNew: false });
274
+ actions.languagesOf(list[index].name).then((found) => (shownPair.current = pairText(found)), () => {});
270
275
  clearField();
271
276
  setStep("line");
272
277
  }
@@ -417,7 +422,7 @@ export function AddCard({ current, actions, onDone, startNew = false }) {
417
422
  html`
418
423
  <${Box} flexDirection="column" marginTop=${1}>
419
424
  <${Text} bold>${t(`add.fields.${fieldLabel}.label`)}<//>
420
- <${Text} dimColor>${t(`add.fields.${fieldLabel}.hint`)}<//>
425
+ <${Text} dimColor>${fieldLabel === "line" && suggest?.example ? t("add.lineHintFor", { example: suggest.example }) : t(`add.fields.${fieldLabel}.hint`)}<//>
421
426
  <${Box} marginTop=${1}>
422
427
  <${AnswerInput}
423
428
  key=${`${fieldLabel}-${field.key}`}
@@ -427,6 +432,7 @@ export function AddCard({ current, actions, onDone, startNew = false }) {
427
432
  onExit=${back}
428
433
  onChange=${onType}
429
434
  onRecall=${step === "line" ? recall : undefined}
435
+ cardLine=${step === "line" || step === "fix"}
430
436
  onPaste=${step === "line" ? openPaste : undefined}
431
437
  />
432
438
  <//>
@@ -521,11 +527,7 @@ export function AddCard({ current, actions, onDone, startNew = false }) {
521
527
  ? t("keyHints.pasteFix")
522
528
  : step === "back"
523
529
  ? t("keyHints.addBack")
524
- : step === "line" && editing
525
- ? t("keyHints.addFixing")
526
- : step === "line" && added.length
527
- ? t("keyHints.addMore")
528
- : t("keyHints.addFirst")}
530
+ : `${t("keyHints.tabPart")} · ${editing ? t("keyHints.addFixing") : added.length ? t("keyHints.addMore") : t("keyHints.addFirst")}`}
529
531
  />
530
532
  <//>
531
533
  <//>
@@ -25,10 +25,26 @@ const args = (value) => value.trim().split(/\s+/).slice(1).join(" ");
25
25
  // Answer line with a movable cursor (←/→, Ctrl+A/E). Typing "/" opens a command palette:
26
26
  // ↑/↓ choose, Tab completes, Enter runs.
27
27
  // `commandOnly` is the between-questions variant: it starts at "/" and Esc or erasing the "/" closes it.
28
- // `plain` is a text field with no commands at all ("and/or" is just text there).
28
+ // `plain` is a text field with no commands at all ("and/or" is just text there); `escLeaves`: Esc leaves
29
+ // it at once, typed text and all, instead of clearing it first (a name being changed, a path).
29
30
  // `onChange` hears every edit; `onRecall` is ↑ on an empty plain field (/add brings back the last card);
30
31
  // `onPaste` takes a paste of several lines, as it came (/add reviews them as cards); anything else is typed in.
31
- export function AnswerInput({ onSubmit, onCommand, onExit, onEdit, onCancel, onChange, onRecall, onPaste, commands = COMMANDS, initial = "", commandOnly = false, plain = false }) {
32
+ // A card line's next part from the cursor: front → back → example → front again. A part that isn't
33
+ // there yet is started: "kot" → "kot = ", "kot = cat" → "kot = cat // ". → { value, cursor }
34
+ export function nextPart(value, cursor) {
35
+ const end = (text) => ({ value: text, cursor: text.length });
36
+ const eq = value.indexOf(" = ");
37
+ if (eq < 0) return end(`${value.trimEnd()} = `);
38
+ const example = value.indexOf(" // ", eq + 3);
39
+ if (cursor < eq + 3) return { value, cursor: eq + 3 };
40
+ if (example < 0) return end(`${value.trimEnd()} // `);
41
+ if (cursor < example + 4) return { value, cursor: example + 4 };
42
+ return { value, cursor: 0 };
43
+ }
44
+
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 }) {
32
48
  const [value, setValue] = useState(initial);
33
49
  const [cursor, setCursor] = useState(initial.length);
34
50
  const [selected, setSelected] = useState(0);
@@ -54,7 +70,7 @@ export function AnswerInput({ onSubmit, onCommand, onExit, onEdit, onCancel, onC
54
70
  usePaste(paste);
55
71
 
56
72
  useInput((input, key) => {
57
- if (key.escape) return commandOnly ? onCancel() : value ? edit("") : onExit();
73
+ if (key.escape) return commandOnly ? onCancel() : value && !escLeaves ? edit("") : onExit();
58
74
  if (key.return) {
59
75
  // no command starts like this: on a card it's simply the answer (some answers begin with "/")
60
76
  if (!isCommand || (!matches.length && !commandOnly)) return onSubmit(value);
@@ -62,6 +78,11 @@ export function AnswerInput({ onSubmit, onCommand, onExit, onEdit, onCancel, onC
62
78
  edit("");
63
79
  return onCommand(matches[pick]?.name ?? token, rest.join(" "));
64
80
  }
81
+ if (key.tab && cardLine) {
82
+ if (!value.trim()) return;
83
+ const next = nextPart(value, cursor);
84
+ return next.value === value ? setCursor(next.cursor) : edit(next.value, next.cursor);
85
+ }
65
86
  if (key.tab) return matches.length ? edit(`${matches[pick].name}${args(value) ? ` ${args(value)}` : ""}`) : undefined;
66
87
  if (key.upArrow && !value && onRecall) return onRecall();
67
88
  if (key.upArrow) return setSelected(Math.max(0, pick - 1));