dracosh 0.4.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/ui/AddCard.js CHANGED
@@ -2,7 +2,8 @@ import { Fragment, useEffect, useRef, useState } from "react";
2
2
  import { Box, useInput } from "ink";
3
3
  import { MAX_DECK_NAME, typedSides } from "../library.js";
4
4
  import { blankGap, formatLine, gapsOf, parseBack, parseLine, plainFront } from "../cardline.js";
5
- import { normalize } from "../judge.js";
5
+ import { readCardList } from "../cardlist.js";
6
+ import { frontKey } from "../judge.js";
6
7
  import { isKnown, languageName } from "../language.js";
7
8
  import { LanguagePicker, pairText } from "./Languages.js";
8
9
  import { AnswerInput } from "./AnswerInput.js";
@@ -31,23 +32,13 @@ function startsWithSlash(fields, directions) {
31
32
  return typedSides({ directions: directions ?? "forward" }).some((side) => [fields[side]].flat().some(slash));
32
33
  }
33
34
 
34
- // A pasted list, one card per line: a tab splits the lines when every one of them has one (Anki and
35
- // Quizlet exports), " = " otherwise. Lines that can't be added as they are say why.
36
- // A list written with dashes ("apple - jabłko") is taken as it is when most lines have one and none
37
- // has " = "; each line splits on a tab, or on its first dash
38
- const DASHES = [" - ", " – ", " — "];
39
- function separatorFor(lines) {
40
- const dashed = !lines.some((line) => line.includes(" = ")) && lines.filter((line) => DASHES.some((dash) => line.includes(dash))).length * 2 >= lines.length;
41
- return (line) => (line.includes("\t") ? "\t" : dashed ? (DASHES.map((dash) => [dash, line.indexOf(dash)]).filter(([, at]) => at >= 0).sort((a, b) => a[1] - b[1])[0]?.[0] ?? " = ") : " = ");
42
- }
43
-
44
- function readPaste(lines, existing, directions) {
45
- const separatorOf = separatorFor(lines);
46
- return lines.map((line) => {
47
- const separator = separatorOf(line);
48
- const fields = parseLine(line, { separator });
49
- const issue = issueOf(fields, directions, existing.has(normalize(fields.front)));
50
- return { line: separator === " = " ? line.trim() : formatLine(fields), fields, issue, dropped: false };
35
+ // A pasted list, read the way `dracosh import` reads a file (src/cardlist.js): Dracosh lines, rows
36
+ // copied from a spreadsheet or an Anki or Quizlet export, or a list with dashes. Lines that can't be
37
+ // added as they are say why. A row that isn't a Dracosh line is shown as one, for fixing.
38
+ function readPaste(list, existing, directions) {
39
+ return list.items.map(({ source, fields }) => {
40
+ const issue = issueOf(fields, directions, existing.has(frontKey(fields.front)));
41
+ return { line: list.format === "lines" && !source.includes("\t") ? source : formatLine(fields), fields, issue, dropped: false };
51
42
  });
52
43
  }
53
44
 
@@ -59,7 +50,7 @@ function withRepeats(items) {
59
50
  const seen = new Set();
60
51
  return items.map((item) => {
61
52
  if (item.dropped || item.issue) return item;
62
- const key = normalize(item.fields.front);
53
+ const key = frontKey(item.fields.front);
63
54
  if (seen.has(key)) return { ...item, issue: "twice" };
64
55
  seen.add(key);
65
56
  return item;
@@ -230,6 +221,7 @@ export function AddCard({ current, actions, onDone, startNew = false }) {
230
221
  return save({ ...draft, back, example: example || draft.example });
231
222
  }
232
223
  if (step === "fix") {
224
+ if (!value) return setStep("review"); // nothing typed: the line stays as it was
233
225
  const fields = parseLine(value);
234
226
  return actions
235
227
  .existingCard(deck.name, fields.front)
@@ -303,7 +295,7 @@ export function AddCard({ current, actions, onDone, startNew = false }) {
303
295
  setError(err.message);
304
296
  }
305
297
  const lines = typedAhead.current.split(/\r\n|\r|\n/).filter((line) => line.trim());
306
- if (lines.length > 1) return void openPaste(lines); // a list pasted in: the review, as on the field
298
+ if (lines.length > 1) return void openPaste(typedAhead.current); // a list pasted in: the review, as on the field
307
299
  // `ahead`: the field starts with typedAhead as it is when the field is drawn
308
300
  setField((f) => ({ key: f.key + 1, initial: "", ahead: true }));
309
301
  setDuplicate(null);
@@ -318,11 +310,12 @@ export function AddCard({ current, actions, onDone, startNew = false }) {
318
310
  }, [field]);
319
311
 
320
312
  // a pasted list: each line checked against the deck before anything is saved
321
- async function openPaste(lines) {
322
- const separatorOf = separatorFor(lines);
323
- const fronts = await Promise.all(lines.map((line) => actions.existingCard(deck.name, parseLine(line, { separator: separatorOf(line) }).front).catch(() => null)));
324
- const existing = new Set(fronts.filter(Boolean).map((card) => normalize(card.front)));
325
- setPasted({ items: readPaste(lines, existing, deck.isNew ? null : deck.directions), selected: 0, confirm: false, total: lines.length });
313
+ async function openPaste(text) {
314
+ const list = readCardList(text, { comments: false }); // a pasted "#tag = hashtag" is a card
315
+ if (!list.items.length) return setStep("line");
316
+ const fronts = await Promise.all(list.items.map((item) => actions.existingCard(deck.name, item.fields.front).catch(() => null)));
317
+ const existing = new Set(fronts.filter(Boolean).map((card) => frontKey(card.front)));
318
+ setPasted({ items: readPaste(list, existing, deck.isNew ? null : deck.directions), selected: 0, confirm: false, total: list.items.length });
326
319
  setError("");
327
320
  setMessage("");
328
321
  setStep("review");
@@ -27,7 +27,7 @@ const args = (value) => value.trim().split(/\s+/).slice(1).join(" ");
27
27
  // `commandOnly` is the between-questions variant: it starts at "/" and Esc or erasing the "/" closes it.
28
28
  // `plain` is a text field with no commands at all ("and/or" is just text there).
29
29
  // `onChange` hears every edit; `onRecall` is ↑ on an empty plain field (/add brings back the last card);
30
- // `onPaste` takes a paste of several lines (/add reviews them as cards), anything else is typed in.
30
+ // `onPaste` takes a paste of several lines, as it came (/add reviews them as cards); anything else is typed in.
31
31
  export function AnswerInput({ onSubmit, onCommand, onExit, onEdit, onCancel, onChange, onRecall, onPaste, commands = COMMANDS, initial = "", commandOnly = false, plain = false }) {
32
32
  const [value, setValue] = useState(initial);
33
33
  const [cursor, setCursor] = useState(initial.length);
@@ -47,8 +47,8 @@ export function AnswerInput({ onSubmit, onCommand, onExit, onEdit, onCancel, onC
47
47
  // pasted text arrives whole (bracketed paste); lines become spaces unless /add takes them as cards
48
48
  const paste = (text) => {
49
49
  const lines = /[\r\n]/.test(text) ? text.split(/\r\n|\r|\n/).filter((line) => line.trim()) : [text];
50
- if (onPaste && lines.length > 1) return onPaste(lines);
51
- const typed = lines.join(" ");
50
+ if (onPaste && lines.length > 1) return onPaste(text);
51
+ const typed = lines.join(" ").replace(/\t/g, " ");
52
52
  edit(value.slice(0, cursor) + typed + value.slice(cursor), cursor + typed.length);
53
53
  };
54
54
  usePaste(paste);
package/src/ui/App.js CHANGED
@@ -75,20 +75,26 @@ function AccentedAnswers({ expected, given, closest }) {
75
75
  });
76
76
  }
77
77
 
78
+ // "The card comes back in a few minutes, not in 2 days." Two months and more are said in months.
79
+ const comesBack = (days) => (days < 1 ? t("quiz.almost.soon") : days < 60 ? t("quiz.almost.days", { count: days }) : t("quiz.almost.months", { count: Math.round(days / 30) }));
80
+ const heldText = (held) => (comesBack(held.days) === comesBack(held.would) ? null : t("quiz.almost.held", { now: comesBack(held.days), would: comesBack(held.would) }));
81
+
78
82
  function Verdict({ outcome, question }) {
79
83
  const wrong = outcome.result === "wrong";
80
84
  const showDiff = outcome.closest && outcome.given && !outcome.overruled && (wrong || outcome.result === "typo");
85
+ // a typo, an "almost" or a hint: the card comes back sooner, said on a line of its own
86
+ const held = outcome.held ? heldText(outcome.held) : null;
81
87
  return html`
82
88
  <${Box} flexDirection="column">
83
89
  <${Text} color=${wrong ? theme.bad : theme.good} bold>${wrong ? "✗" : "✓"} ${outcome.result === "accent" || outcome.result === "umlaut" || outcome.result === "article-umlaut" ? html`<${AccentedAnswers} expected=${question.expected} given=${outcome.given} closest=${outcome.closest} />` : question.expected.join(" / ")}${outcome.result === "typo" ? t("quiz.closeEnough") : ""}<//>
84
- ${ALMOST.includes(outcome.result) &&
85
- html`<${Text} color=${theme.warn}>${t(`quiz.almost.${outcome.result}`)}${outcome.held ? ` ${t("quiz.almost.held", { now: t("quiz.almost.days", { count: outcome.held.days }), would: t("quiz.almost.days", { count: outcome.held.would }) })}` : ""}<//>`}
90
+ ${ALMOST.includes(outcome.result) && html`<${Text} color=${theme.warn}>${t(`quiz.almost.${outcome.result}`)}<//>`}
86
91
  ${showDiff && html`<${AnswerDiff} given=${outcome.given} closest=${outcome.closest} />`}
87
92
  ${question.word.example && html`<${Box} marginTop=${1}>${question.tour ? html`<${Marked} dimColor text=${question.word.example} />` : html`<${Text} dimColor italic>“${question.word.example}”<//>`}<//>`}
88
- ${(outcome.hinted || outcome.overruled) &&
93
+ ${(outcome.hinted || outcome.overruled || held) &&
89
94
  html`
90
95
  <${Box} marginTop=${1} flexDirection="column">
91
96
  ${outcome.hinted && html`<${Text} dimColor>${t("quiz.hintUsed")}<//>`}
97
+ ${held && html`<${Text} dimColor>${held}<//>`}
92
98
  ${outcome.overruled && html`<${Text} color=${theme.good}>${t("quiz.countedCorrect")}${question.tour ? "" : t("quiz.acceptedFromNow", { answer: outcome.accepted })}<//>`}
93
99
  <//>
94
100
  `}
package/src/ui/Help.js CHANGED
@@ -2,7 +2,6 @@ import { Fragment } from "react";
2
2
  import { Box, useInput } from "ink";
3
3
  import { t } from "../i18n.js";
4
4
  import { MAX_FREEZES } from "../progress.js";
5
- import { BOX_INTERVALS_DAYS } from "../scheduler.js";
6
5
  import { cellWidth, html, KeyHints, Text, theme, usePanelWidth } from "./kit.js";
7
6
 
8
7
  // built at render time, so the texts follow the app language
@@ -16,7 +15,7 @@ const keys = () => [
16
15
  ];
17
16
 
18
17
  const how = () => [
19
- t("help.how.boxes", { first: BOX_INTERVALS_DAYS.slice(0, -1).join(", "), last: BOX_INTERVALS_DAYS.at(-1) }),
18
+ t("help.how.spacing"),
20
19
  t("help.how.typos"),
21
20
  t("help.how.cards"),
22
21
  t("help.how.streak"),
@@ -62,7 +61,7 @@ const Section = ({ title, children }) => html`
62
61
  <//>
63
62
  `;
64
63
 
65
- // How Dracosh works, on one screen: the keys, the rules behind the boxes and the streak,
64
+ // How Dracosh works, on one screen: the keys, the rules behind the spacing and the streak,
66
65
  // and what you can do from the shell.
67
66
  export function Help({ onClose }) {
68
67
  const panel = usePanelWidth();
package/src/zip.js ADDED
@@ -0,0 +1,157 @@
1
+ import { open } from "node:fs/promises";
2
+ import { crc32, deflateRawSync, inflateRawSync } from "node:zlib";
3
+
4
+ // A zip file (PKWARE APPNOTE 6.3), the container of an Anki package: each file deflated, names in
5
+ // UTF-8, no zip64 (an export never comes near 4 GB).
6
+ // writeZip([{ name: "media", data: Buffer }], { date }) → Buffer
7
+
8
+ const dosTime = (date) => (date.getHours() << 11) | (date.getMinutes() << 5) | (date.getSeconds() >> 1);
9
+ const dosDate = (date) => ((Math.max(date.getFullYear(), 1980) - 1980) << 9) | ((date.getMonth() + 1) << 5) | date.getDate();
10
+ const UTF8_NAMES = 0x0800;
11
+ const DEFLATE = 8;
12
+ const VERSION = 20; // 2.0: deflate
13
+
14
+ export function writeZip(entries, { date = new Date() } = {}) {
15
+ const locals = [];
16
+ const centrals = [];
17
+ let offset = 0;
18
+ for (const { name, data } of entries) {
19
+ const nameBytes = Buffer.from(name, "utf8");
20
+ const packed = deflateRawSync(data);
21
+ if (packed.length > 0xffffffff || data.length > 0xffffffff || offset > 0xffffffff) throw new Error("Too big for a zip without zip64");
22
+ const crc = crc32(data);
23
+
24
+ const local = Buffer.alloc(30);
25
+ local.writeUInt32LE(0x04034b50, 0);
26
+ local.writeUInt16LE(VERSION, 4);
27
+ local.writeUInt16LE(UTF8_NAMES, 6);
28
+ local.writeUInt16LE(DEFLATE, 8);
29
+ local.writeUInt16LE(dosTime(date), 10);
30
+ local.writeUInt16LE(dosDate(date), 12);
31
+ local.writeUInt32LE(crc, 14);
32
+ local.writeUInt32LE(packed.length, 18);
33
+ local.writeUInt32LE(data.length, 22);
34
+ local.writeUInt16LE(nameBytes.length, 26);
35
+ local.writeUInt16LE(0, 28);
36
+ locals.push(local, nameBytes, packed);
37
+
38
+ const central = Buffer.alloc(46);
39
+ central.writeUInt32LE(0x02014b50, 0);
40
+ central.writeUInt16LE(VERSION, 4);
41
+ central.writeUInt16LE(VERSION, 6);
42
+ central.writeUInt16LE(UTF8_NAMES, 8);
43
+ central.writeUInt16LE(DEFLATE, 10);
44
+ central.writeUInt16LE(dosTime(date), 12);
45
+ central.writeUInt16LE(dosDate(date), 14);
46
+ central.writeUInt32LE(crc, 16);
47
+ central.writeUInt32LE(packed.length, 20);
48
+ central.writeUInt32LE(data.length, 24);
49
+ central.writeUInt16LE(nameBytes.length, 28);
50
+ // extra field, comment, disk number, internal and external attributes: all zero
51
+ central.writeUInt32LE(offset, 42);
52
+ centrals.push(central, nameBytes);
53
+
54
+ offset += local.length + nameBytes.length + packed.length;
55
+ }
56
+ const directory = Buffer.concat(centrals);
57
+ const end = Buffer.alloc(22);
58
+ end.writeUInt32LE(0x06054b50, 0);
59
+ end.writeUInt16LE(entries.length, 8);
60
+ end.writeUInt16LE(entries.length, 10);
61
+ end.writeUInt32LE(directory.length, 12);
62
+ end.writeUInt32LE(offset, 16);
63
+ return Buffer.concat([...locals, directory, end]);
64
+ }
65
+
66
+ const STORED = 0;
67
+ const END = 0x06054b50;
68
+ const END64 = 0x06064b50;
69
+ const END64_LOCATOR = 0x07064b50;
70
+ const CENTRAL = 0x02014b50;
71
+ const LOCAL = 0x04034b50;
72
+ const ZIP64_EXTRA = 0x0001;
73
+ const damaged = (why) => Object.assign(new Error(`Damaged zip file: ${why}`), { code: "DAMAGED_ZIP" });
74
+
75
+ // readZip(file, names, { first }) → Map of name → Buffer, for just the files asked for (an Anki
76
+ // package can hold gigabytes of media next to the collection); `first`: only the first of `names`
77
+ // there is. Stored or deflated files, zip64 too (what Anki writes past 4 GB).
78
+ export async function readZip(file, names, { first = false } = {}) {
79
+ const handle = await open(file, "r");
80
+ try {
81
+ const { size } = await handle.stat();
82
+ const read = async (position, length) => {
83
+ if (position < 0 || length < 0 || position + length > size) throw damaged("a part points outside the file");
84
+ const buffer = Buffer.alloc(length);
85
+ const { bytesRead } = await handle.read(buffer, 0, length, position);
86
+ if (bytesRead < length) throw damaged("the file ends early");
87
+ return buffer;
88
+ };
89
+ // the end record is in the last 22 bytes, or before a comment of up to 64 KB
90
+ const tailStart = Math.max(0, size - 22 - 0xffff);
91
+ const tail = await read(tailStart, size - tailStart);
92
+ let endAt = -1;
93
+ for (let i = tail.length - 22; i >= 0 && endAt < 0; i--) if (tail.readUInt32LE(i) === END) endAt = i;
94
+ if (endAt < 0) throw Object.assign(new Error("Not a zip file"), { code: "NOT_ZIP" });
95
+ let count = tail.readUInt16LE(endAt + 10);
96
+ let directorySize = tail.readUInt32LE(endAt + 12);
97
+ let directoryAt = tail.readUInt32LE(endAt + 16);
98
+ // zip64: the real numbers are in a record of their own, which a locator just before this one finds
99
+ if (count === 0xffff || directorySize === 0xffffffff || directoryAt === 0xffffffff) {
100
+ const locator = endAt - 20;
101
+ if (locator < 0 || tail.readUInt32LE(locator) !== END64_LOCATOR) throw damaged("no zip64 end record");
102
+ const end64 = await read(Number(tail.readBigUInt64LE(locator + 8)), 56);
103
+ if (end64.readUInt32LE(0) !== END64) throw damaged("no zip64 end record");
104
+ count = Number(end64.readBigUInt64LE(32));
105
+ directorySize = Number(end64.readBigUInt64LE(40));
106
+ directoryAt = Number(end64.readBigUInt64LE(48));
107
+ }
108
+ const directory = await read(directoryAt, directorySize);
109
+ const found = new Map();
110
+ for (let at = 0, i = 0; i < count; i++) {
111
+ if (at + 46 > directory.length || directory.readUInt32LE(at) !== CENTRAL) throw damaged("a broken directory");
112
+ const nameLength = directory.readUInt16LE(at + 28);
113
+ const extraLength = directory.readUInt16LE(at + 30);
114
+ const next = at + 46 + nameLength + extraLength + directory.readUInt16LE(at + 32);
115
+ if (next > directory.length) throw damaged("a broken directory");
116
+ const name = directory.toString("utf8", at + 46, at + 46 + nameLength);
117
+ if (names.includes(name)) {
118
+ const entry = { method: directory.readUInt16LE(at + 10), packed: directory.readUInt32LE(at + 20), size: directory.readUInt32LE(at + 24), local: directory.readUInt32LE(at + 42) };
119
+ // zip64 sizes and offset, in that order, only for the ones that didn't fit
120
+ let extra = at + 46 + nameLength;
121
+ const extraEnd = extra + extraLength;
122
+ while (extra + 4 <= extraEnd) {
123
+ const [id, length] = [directory.readUInt16LE(extra), directory.readUInt16LE(extra + 2)];
124
+ if (id === ZIP64_EXTRA) {
125
+ let field = extra + 4;
126
+ for (const key of ["size", "packed", "local"]) {
127
+ if (entry[key] !== 0xffffffff) continue;
128
+ if (field + 8 > extra + 4 + length) throw damaged("a broken zip64 field");
129
+ entry[key] = Number(directory.readBigUInt64LE(field));
130
+ field += 8;
131
+ }
132
+ }
133
+ extra += 4 + length;
134
+ }
135
+ found.set(name, entry);
136
+ }
137
+ at = next;
138
+ }
139
+ const wanted = first ? names.filter((name) => found.has(name)).slice(0, 1) : names.filter((name) => found.has(name));
140
+ const files = new Map();
141
+ for (const name of wanted) {
142
+ const { method, packed: packedSize, size: unpackedSize, local } = found.get(name);
143
+ const header = await read(local, 30);
144
+ if (header.readUInt32LE(0) !== LOCAL) throw damaged(`no header for ${name}`);
145
+ const packed = await read(local + 30 + header.readUInt16LE(26) + header.readUInt16LE(28), packedSize);
146
+ if (method === STORED) files.set(name, packed);
147
+ else if (method === DEFLATE) {
148
+ const data = inflateRawSync(packed);
149
+ if (data.length !== unpackedSize) throw damaged(`${name} unpacks to the wrong size`);
150
+ files.set(name, data);
151
+ } else throw damaged(`unsupported compression in ${name}`);
152
+ }
153
+ return files;
154
+ } finally {
155
+ await handle.close();
156
+ }
157
+ }