dracosh 0.6.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/manage.js CHANGED
@@ -1,9 +1,11 @@
1
- import { t } from "./i18n.js";
1
+ import { language as uiLanguage, t } from "./i18n.js";
2
2
  import { backupNow } from "./backup.js";
3
3
  import { seedLibrary } from "./starter.js";
4
4
  import { gapsOf } from "./cardline.js";
5
- import { addCard, cardsOf, createDeck, emptyLibrary, findDeck, findDuplicate, removeDeck, setDirections as setLibraryDirections, setLanguages as setLibraryLanguages, typedSides, updateCard } from "./library.js";
6
- import { deckLanguages, homeLanguages, learningSide } from "./language.js";
5
+ import { addCard, cardsOf, createDeck, emptyLibrary, emptyOldTrash, findDeck, findDuplicate, moveCards as moveLibraryCards, removeDeck, renameDeck as renameLibraryDeck, restoreDeck, trashCards, setDirections as setLibraryDirections, setLanguages as setLibraryLanguages, trashDeck, trashedUntil, typedSides, updateCard } from "./library.js";
6
+ import { firstWords } from "./firstwords.js";
7
+ import { applyImport, planImport } from "./importer.js";
8
+ import { deckLanguages, homeLanguages, languageName, learningSide } from "./language.js";
7
9
  import { itemKey } from "./scheduler.js";
8
10
  import { loadLibrary, saveLibrary } from "./store.js";
9
11
 
@@ -82,6 +84,32 @@ export function libraryActions({ load = loadLibrary, save = saveLibrary, backup
82
84
  return { deck, removed };
83
85
  },
84
86
 
87
+ // The welcome's deck of first words: the new word shown, yours typed (/decks can add the other way);
88
+ // like a deck of your own, it replaces the tour.
89
+ // Taken again (a welcome done twice), the deck made then is the one. → { deck, removed }
90
+ async startFirstWords({ home, learning }) {
91
+ const library = await load();
92
+ const language = languageName(learning);
93
+ const name = t("welcome.firstWordsDeck", { language: language.charAt(0).toLocaleUpperCase(uiLanguage()) + language.slice(1) });
94
+ const pair = (deck) => deck.firstWords && deck.languages?.front === learning && deck.languages?.back === home;
95
+ const existing = library.decks.find(pair);
96
+ if (existing) return { deck: existing, removed: [] };
97
+ // a deck of yours with that name keeps it: these get a number ("German: first words 2")
98
+ let named = name;
99
+ for (let n = 2; findDeck(library, named); n++) named = `${name} ${n}`;
100
+ const tour = library.decks.find((d) => d.tour);
101
+ let removed = [];
102
+ if (tour) {
103
+ await backup("before-delete");
104
+ removed = removeDeck(library, tour.id);
105
+ }
106
+ const deck = createDeck(library, { name: named, languages: { front: learning, back: home }, directions: "forward" });
107
+ deck.firstWords = true;
108
+ for (const fields of firstWords(home, learning)) addCard(library, deck.id, fields);
109
+ await save(library);
110
+ return { deck, removed };
111
+ },
112
+
85
113
  // → { deck, cardIds }: the session rests the directions no longer asked (session.setDirections).
86
114
  // A side that becomes an answer to type may not start with "/", so such a switch is refused.
87
115
  async setDirections(deckName, directions) {
@@ -192,6 +220,123 @@ export function libraryActions({ load = loadLibrary, save = saveLibrary, backup
192
220
  return { from, to: library.decks.find((d) => d.tour).name };
193
221
  },
194
222
 
223
+ // /decks → Rename → the deck as it's called now
224
+ async renameDeck(oldName, newName) {
225
+ const library = await load();
226
+ const deck = renameLibraryDeck(library, (await deckNamed(library, oldName)).id, newName);
227
+ await save(library);
228
+ return deck;
229
+ },
230
+
231
+ // /decks → Delete, confirmed: a backup, then the deck goes to the trash with its cards and their
232
+ // progress (`progressOf(cardIds)`, from the session). The last deck leaves the tour in its place.
233
+ // → { entry, cardIds, next }: the trash entry, the cards gone (their progress goes from the
234
+ // session too) and the deck to practise if this one was it
235
+ async deleteDeck(name, progressOf = () => ({})) {
236
+ await backup("before-delete");
237
+ const library = await load();
238
+ const deck = await deckNamed(library, name);
239
+ const cardIds = cardsOf(library, deck.id).map((card) => card.id);
240
+ const entry = trashDeck(library, deck.id, { progress: progressOf(cardIds) });
241
+ if (!library.decks.length) seedLibrary(library);
242
+ await save(library);
243
+ const next = library.decks.find((d) => !d.tour) ?? library.decks[0];
244
+ return { entry: entry.id, cardIds, next: next.name };
245
+ },
246
+
247
+ // /trash: what's in it, newest first; anything there longer than the trash keeps it goes now.
248
+ // `card`: a deleted card's front and back, when that's what the entry holds (one card)
249
+ async trash() {
250
+ const library = await load();
251
+ if (emptyOldTrash(library)) await save(library);
252
+ return (library.trash ?? []).toReversed().map((entry) => ({
253
+ id: entry.id,
254
+ kind: entry.kind ?? "deck",
255
+ name: entry.deck.name,
256
+ cards: entry.cards.length,
257
+ card: entry.kind === "cards" && entry.cards.length === 1 ? { front: entry.cards[0].front, back: entry.cards[0].back, cloze: entry.cards[0].cloze } : null,
258
+ deletedAt: entry.deletedAt,
259
+ until: trashedUntil(entry)
260
+ }));
261
+ },
262
+
263
+ // /cards: a deck's cards as they are now, in the order they were added
264
+ async cardsIn(deckName) {
265
+ const library = await load();
266
+ return cardsOf(library, (await deckNamed(library, deckName)).id).map(({ id, front, back, example, cloze }) => ({ id, front, back, example: example ?? "", cloze: Boolean(cloze) }));
267
+ },
268
+
269
+ // /cards → Delete: into the trash with their progress (`progressOf`, from the session); the deck stays,
270
+ // even empty. No backup: the trash keeps them, and a backup for every card would push the others out.
271
+ // → { entry }
272
+ async deleteCards(deckName, cardIds, progressOf = () => ({})) {
273
+ const library = await load();
274
+ await deckNamed(library, deckName);
275
+ const entry = trashCards(library, cardIds, { progress: progressOf(cardIds) });
276
+ await save(library);
277
+ return { entry: entry.id };
278
+ },
279
+
280
+ // /cards → Move: into another deck of yours, progress and all → { moved, duplicates } (card ids)
281
+ async moveCards(fromName, cardIds, toName) {
282
+ const library = await load();
283
+ await deckNamed(library, fromName);
284
+ const result = moveLibraryCards(library, cardIds, (await deckNamed(library, toName)).id);
285
+ if (result.moved.length) await save(library);
286
+ return result;
287
+ },
288
+
289
+ // /decks → Merge: every card of one deck into another, after a backup; the emptied deck goes to the
290
+ // trash with the cards the other deck had already (same front), and their progress.
291
+ // Brought back from the trash, it takes the moved cards back with it.
292
+ // → { moved, left: card ids that went to the trash with the deck, entry }
293
+ async mergeDecks(fromName, intoName, progressOf = () => ({})) {
294
+ await backup("before-delete");
295
+ const library = await load();
296
+ const from = await deckNamed(library, fromName);
297
+ const into = await deckNamed(library, intoName);
298
+ const { moved, duplicates } = moveLibraryCards(library, cardsOf(library, from.id).map((card) => card.id), into.id);
299
+ const entry = trashDeck(library, from.id, { progress: progressOf(duplicates) });
300
+ entry.merged = { into: into.id, cardIds: moved }; // u (or /trash) takes them back out
301
+ await save(library);
302
+ return { moved, left: duplicates, entry: entry.id };
303
+ },
304
+
305
+ // A deck back from the trash (/trash, or u right after deleting it). Like a deck of your own, it takes
306
+ // the tour's place. → { deck, progress, removed }: its name now, the progress to give back to the
307
+ // session, and the tour's cards that went
308
+ async restoreFromTrash(entryId) {
309
+ const library = await load();
310
+ const { deck, entry, skipped } = restoreDeck(library, entryId);
311
+ const tour = library.decks.find((d) => d.tour && d !== deck);
312
+ const removed = tour ? removeDeck(library, tour.id) : [];
313
+ await save(library);
314
+ // the progress of the cards that came back (one left in the trash keeps its own there)
315
+ const back = new Set(entry.cards.map((card) => card.id));
316
+ const mine = (object = {}) => Object.fromEntries(Object.entries(object).filter(([key]) => back.has(key.slice(0, key.lastIndexOf(":")))));
317
+ const progress = { items: mine(entry.progress?.items), accepted: mine(entry.progress?.accepted), dormant: (entry.progress?.dormant ?? []).filter((key) => back.has(key.slice(0, key.lastIndexOf(":")))) };
318
+ return { deck: deck.name, cards: entry.cards.length, kind: entry.kind ?? "deck", skipped, progress, removed };
319
+ },
320
+
321
+ // /import: what a file's cards would do to the library now (see planImport); `source` is { text, list }
322
+ // (each deck there already says how many cards it holds: `cards`)
323
+ async previewImport(source, choices) {
324
+ const library = await load();
325
+ const plan = planImport(library, source.text, { ...choices, list: source.list });
326
+ return { ...plan, decks: plan.decks.map((deck) => ({ ...deck, cards: deck.deck ? cardsOf(library, deck.deck.id).length : 0 })) };
327
+ },
328
+
329
+ // /import, carried out: a backup first, then the plan made again on the library as it is now (another
330
+ // window may have changed it). `update`: the changed cards take the file's version. → applyImport's
331
+ // result, and whether a backup was taken (none on a library with nothing in it yet)
332
+ async importCards(source, choices, { update = false } = {}) {
333
+ const backedUp = Boolean(await backup("before-import"));
334
+ const library = await load();
335
+ const result = applyImport(library, planImport(library, source.text, { ...choices, list: source.list }), { update, directions: choices.directions });
336
+ await save(library);
337
+ return { ...result, backedUp };
338
+ },
339
+
195
340
  // a reset is always preceded by a backup, so `dracosh restore` can undo it
196
341
  backupBeforeReset: () => backup("before-reset"),
197
342
 
@@ -207,4 +352,4 @@ export function libraryActions({ load = loadLibrary, save = saveLibrary, backup
207
352
 
208
353
  // the app's own: reads and writes ~/.dracosh
209
354
  const actions = libraryActions();
210
- export const { allDecks, ownDecks, startDeck, setDirections, languagesOf, setLanguages, setLearning, existingDeck, existingCard, addCardTo, addCardsTo, updateCardIn, matchTourLanguage, backupBeforeReset, resetLibrary } = actions;
355
+ export const { allDecks, ownDecks, startDeck, startFirstWords, setDirections, languagesOf, setLanguages, setLearning, existingDeck, existingCard, addCardTo, addCardsTo, updateCardIn, previewImport, importCards, renameDeck, deleteDeck, trash, restoreFromTrash, cardsIn, deleteCards, moveCards, mergeDecks, matchTourLanguage, backupBeforeReset, resetLibrary } = actions;
package/src/progress.js CHANGED
@@ -34,6 +34,14 @@ export const STAGES = [
34
34
  stage("legend", 365)
35
35
  ];
36
36
 
37
+ // /settings → the default look: the element goes for good, and the die never rolls again
38
+ export function dropElement(state, now = Date.now()) {
39
+ const progress = ensureProgress(state, now);
40
+ delete progress.element;
41
+ delete progress.elementRoll;
42
+ progress.elementDropped = true;
43
+ }
44
+
37
45
  export function stageFor(bestStreak) {
38
46
  let index = 0;
39
47
  while (index + 1 < STAGES.length && bestStreak >= STAGES[index + 1].from) index += 1;
package/src/session.js CHANGED
@@ -1,7 +1,7 @@
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";
4
+ import { addVacation, applyAnswer, applyCaughtUp, markWorkWaiting, applyOverrule, calendarMonth, cancelVacations, dropElement, ensureProgress, markBadgesSeen, missedOn, recordMiss, snapshot, undoMiss, unseenBadges, vacationInfo } from "./progress.js";
5
5
  import { describeDue, grade, intervalDays, itemKey, nextDueAt, pickNext, Rating, ratingFor, startOfTomorrow } from "./scheduler.js";
6
6
  import { recordAnswer, saveState, STATE_VERSION } from "./store.js";
7
7
  import { createTipDeck } from "./tips.js";
@@ -98,6 +98,7 @@ export function createSession({ loadWords, loadAllWords, state, getSettings, sav
98
98
  }
99
99
  lastNoteId = item.word.noteId;
100
100
  lastWrong = null;
101
+ const from = item.word.deck ?? deck; // decks practised together: the card's own deck
101
102
 
102
103
  const forward = item.direction === "en-pl";
103
104
  const gap = item.direction.startsWith("c") ? Number(item.direction.slice(1)) - 1 : null;
@@ -110,15 +111,15 @@ export function createSession({ loadWords, loadAllWords, state, getSettings, sav
110
111
  return {
111
112
  word: item.word,
112
113
  direction: item.direction,
113
- label: labelOf(deck),
114
+ label: labelOf(from),
114
115
  prompt,
115
116
  expected,
116
117
  // a cloze card's back is a hint under the sentence ("Cieszę się na to")
117
118
  context: gap !== null ? item.word.translations.join(" / ") : "",
118
119
  // what the answer is written in, when the deck's languages are known: its own spellings count
119
- answerLanguage: (forward ? deck?.languages?.back : deck?.languages?.front) ?? null,
120
- promptLanguage: (forward ? deck?.languages?.front : deck?.languages?.back) ?? null,
121
- 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,
122
123
  wordCount: words.length,
123
124
  tour: Boolean(deck?.tour) // the tour marks what to type with `backticks`
124
125
  };
@@ -253,6 +254,23 @@ export function createSession({ loadWords, loadAllWords, state, getSettings, sav
253
254
  await save(state);
254
255
  }
255
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
+
256
274
  // A deck is asked another way now (/decks): the directions it no longer asks rest. Their progress stays
257
275
  // for when they're back, but doesn't count against mastering the card.
258
276
  async function setDirections(cardIds, directions) {
@@ -292,8 +310,22 @@ export function createSession({ loadWords, loadAllWords, state, getSettings, sav
292
310
  // the hatching intro plays once ever: on a brand-new state that has never answered anything
293
311
  const isFirstRun = () => !state.hatched && Object.keys(state.items).length === 0;
294
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
295
315
  async function markHatched() {
296
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());
297
329
  await save(state);
298
330
  }
299
331
 
@@ -315,5 +347,5 @@ export function createSession({ loadWords, loadAllWords, state, getSettings, sav
315
347
  await settleDay(); // nothing askable after all (a direction switched off): the quiet stretch goes on
316
348
  }
317
349
 
318
- 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 };
319
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
@@ -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
@@ -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));