grind-tracker 0.1.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/LICENSE ADDED
@@ -0,0 +1,216 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
203
+
204
+ Copyright 2026 jycd25
205
+
206
+ Licensed under the Apache License, Version 2.0 (the "License");
207
+ you may not use this file except in compliance with the License.
208
+ You may obtain a copy of the License at
209
+
210
+ http://www.apache.org/licenses/LICENSE-2.0
211
+
212
+ Unless required by applicable law or agreed to in writing, software
213
+ distributed under the License is distributed on an "AS IS" BASIS,
214
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
215
+ See the License for the specific language governing permissions and
216
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,75 @@
1
+ # grind-tracker
2
+
3
+ A local-first spaced-repetition tracker for things you're learning, with a
4
+ local web UI.
5
+
6
+ ## Quick start
7
+
8
+ ```bash
9
+ npx grind-tracker
10
+ ```
11
+
12
+ This opens `http://127.0.0.1:8777` in your browser. All data lives in a
13
+ SQLite file at `~/.grind-tracker/grind.db` — nothing leaves your machine.
14
+ Requires Node 24+.
15
+
16
+ ## How it works
17
+
18
+ - **Add items manually** in the web UI, or point the server at a folder of
19
+ notes with `--notes <dir>` to pull in `*.md` / `*.txt` headings as
20
+ candidates you can add with one click.
21
+ - Each item gets a **review ladder**: by default `1, 3, 7, 14, 30` days from
22
+ its grind date (the date you added it). Five reviews get scheduled up
23
+ front, one per ladder step.
24
+ - The **due list** on the home page shows everything due today or overdue,
25
+ across all items.
26
+ - Mark a review **done** when you've reviewed it, or **undo** if you marked
27
+ it by mistake.
28
+ - The ladder can be changed in settings, but an edit only affects items added
29
+ afterward — existing items keep the schedule they were created with.
30
+
31
+ ## CLI reference
32
+
33
+ ```
34
+ usage: grind-tracker [command] [options]
35
+
36
+ commands:
37
+ serve (default) start the local web UI
38
+ export [file] write all data as JSON (stdout if no file)
39
+ import <file> merge a JSON export into the database
40
+ import-legacy <grind.db>
41
+ one-time import from the legacy Python tracker
42
+
43
+ options:
44
+ --db <path> database file (default ~/.grind-tracker/grind.db)
45
+ --port <n> serve port (default 8777)
46
+ --notes <dir> index *.md / *.txt headings from this folder
47
+ --no-open do not open the browser
48
+ ```
49
+
50
+ ## Export, import, and migrating from the legacy tracker
51
+
52
+ `grind-tracker export [file]` writes a versioned JSON snapshot of your
53
+ ladder and every item (with its full review history) — to stdout, or to
54
+ `file` if given. `grind-tracker import <file>` merges an export back in;
55
+ items are matched by label, so importing the same file twice just skips the
56
+ duplicates instead of doubling them up.
57
+
58
+ If you're moving from the legacy Python tracker, run:
59
+
60
+ ```bash
61
+ grind-tracker import-legacy path/to/grind.db
62
+ ```
63
+
64
+ This is a one-time read of the old SQLite schema (`entries`, `reviews`,
65
+ `settings`) into the same versioned export format, then merges it into your
66
+ grind-tracker database.
67
+
68
+ ## Security note
69
+
70
+ The web server only binds to `127.0.0.1` — it is never reachable from
71
+ another machine on your network.
72
+
73
+ ## License
74
+
75
+ Apache License 2.0 — see [LICENSE](LICENSE).
@@ -0,0 +1,110 @@
1
+ #!/usr/bin/env node
2
+ import { spawn } from "node:child_process";
3
+ import { readFileSync, writeFileSync } from "node:fs";
4
+ import { homedir } from "node:os";
5
+ import { dirname, join } from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+ import { parseArgs } from "node:util";
8
+ import { parseExport } from "../core/exportFile.js";
9
+ import { exportData, importData, openDb } from "./db.js";
10
+ import { legacyToExport } from "./legacyImport.js";
11
+ import { createApp } from "./server.js";
12
+ const PUBLIC_DIR = join(dirname(fileURLToPath(import.meta.url)), "../../public");
13
+ const DEFAULT_DB = join(homedir(), ".grind-tracker", "grind.db");
14
+ const USAGE = `usage: grind-tracker [command] [options]
15
+
16
+ commands:
17
+ serve (default) start the local web UI
18
+ export [file] write all data as JSON (stdout if no file)
19
+ import <file> merge a JSON export into the database
20
+ import-legacy <grind.db>
21
+ one-time import from the legacy Python tracker
22
+
23
+ options:
24
+ --db <path> database file (default ${DEFAULT_DB})
25
+ --port <n> serve port (default 8777)
26
+ --notes <dir> index *.md / *.txt headings from this folder
27
+ --no-open do not open the browser
28
+ `;
29
+ function openBrowser(url) {
30
+ const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "start" : "xdg-open";
31
+ try {
32
+ spawn(cmd, [url], { stdio: "ignore", detached: true, shell: process.platform === "win32" }).unref();
33
+ }
34
+ catch {
35
+ // best effort only
36
+ }
37
+ }
38
+ function main() {
39
+ const { values, positionals } = parseArgs({
40
+ allowPositionals: true,
41
+ options: {
42
+ db: { type: "string", default: DEFAULT_DB },
43
+ port: { type: "string", default: "8777" },
44
+ notes: { type: "string" },
45
+ "no-open": { type: "boolean", default: false },
46
+ help: { type: "boolean", default: false },
47
+ },
48
+ });
49
+ if (values.help) {
50
+ process.stdout.write(USAGE);
51
+ return 0;
52
+ }
53
+ const command = positionals[0] ?? "serve";
54
+ if (command === "serve") {
55
+ const db = openDb(values.db);
56
+ const port = Number(values.port);
57
+ const app = createApp(db, { publicDir: PUBLIC_DIR, notesDir: values.notes });
58
+ app.on("error", (err) => {
59
+ if (err.code === "EADDRINUSE") {
60
+ console.error(`Port ${port} is already in use — the tracker is probably already running. Open http://127.0.0.1:${port}/`);
61
+ process.exit(1);
62
+ }
63
+ throw err;
64
+ });
65
+ app.listen(port, "127.0.0.1", () => {
66
+ const url = `http://127.0.0.1:${port}/`;
67
+ console.log(`Grind tracker running at ${url} (Ctrl+C to stop)`);
68
+ console.log(`Database: ${values.db}`);
69
+ if (!values["no-open"])
70
+ openBrowser(url);
71
+ });
72
+ return 0;
73
+ }
74
+ if (command === "export") {
75
+ const db = openDb(values.db);
76
+ const json = JSON.stringify(exportData(db), null, 2);
77
+ if (positionals[1]) {
78
+ writeFileSync(positionals[1], json + "\n");
79
+ console.log(`Exported to ${positionals[1]}`);
80
+ }
81
+ else {
82
+ process.stdout.write(json + "\n");
83
+ }
84
+ return 0;
85
+ }
86
+ if (command === "import") {
87
+ if (!positionals[1]) {
88
+ console.error("import requires a file argument");
89
+ return 1;
90
+ }
91
+ const db = openDb(values.db);
92
+ const file = parseExport(JSON.parse(readFileSync(positionals[1], "utf-8")));
93
+ const result = importData(db, file);
94
+ console.log(`Imported ${result.added} item(s), skipped ${result.skipped} duplicate(s).`);
95
+ return 0;
96
+ }
97
+ if (command === "import-legacy") {
98
+ if (!positionals[1]) {
99
+ console.error("import-legacy requires the path to the legacy grind.db");
100
+ return 1;
101
+ }
102
+ const db = openDb(values.db);
103
+ const result = importData(db, legacyToExport(positionals[1]));
104
+ console.log(`Imported ${result.added} item(s), skipped ${result.skipped} duplicate(s).`);
105
+ return 0;
106
+ }
107
+ console.error(USAGE);
108
+ return 1;
109
+ }
110
+ process.exitCode = main();
package/dist/app/db.js ADDED
@@ -0,0 +1,140 @@
1
+ import { mkdirSync } from "node:fs";
2
+ import { dirname } from "node:path";
3
+ import { DatabaseSync } from "node:sqlite";
4
+ import { DEFAULT_LADDER, parseLadder, scheduleDates, todayStr } from "../core/schedule.js";
5
+ import { buildExport } from "../core/exportFile.js";
6
+ const SCHEMA = `
7
+ CREATE TABLE IF NOT EXISTS items (
8
+ id INTEGER PRIMARY KEY,
9
+ label TEXT NOT NULL,
10
+ source TEXT,
11
+ anchor TEXT,
12
+ note TEXT NOT NULL DEFAULT '',
13
+ first_date TEXT NOT NULL
14
+ );
15
+ CREATE TABLE IF NOT EXISTS reviews (
16
+ id INTEGER PRIMARY KEY,
17
+ item_id INTEGER NOT NULL REFERENCES items(id) ON DELETE CASCADE,
18
+ due_date TEXT NOT NULL,
19
+ step INTEGER NOT NULL,
20
+ done_at TEXT
21
+ );
22
+ CREATE TABLE IF NOT EXISTS settings (
23
+ key TEXT PRIMARY KEY,
24
+ value TEXT NOT NULL
25
+ );
26
+ `;
27
+ export function openDb(path) {
28
+ if (path !== ":memory:")
29
+ mkdirSync(dirname(path), { recursive: true });
30
+ const db = new DatabaseSync(path, { timeout: 5000 });
31
+ db.exec("PRAGMA journal_mode = WAL");
32
+ db.exec("PRAGMA foreign_keys = ON");
33
+ db.exec(SCHEMA);
34
+ db.prepare("INSERT OR IGNORE INTO settings (key, value) VALUES ('ladder', ?)").run(DEFAULT_LADDER);
35
+ return db;
36
+ }
37
+ export function getLadder(db) {
38
+ const row = db.prepare("SELECT value FROM settings WHERE key = 'ladder'").get();
39
+ return row.value;
40
+ }
41
+ export function setLadder(db, s) {
42
+ parseLadder(s);
43
+ db.prepare("UPDATE settings SET value = ? WHERE key = 'ladder'").run(s.trim());
44
+ }
45
+ export function getItem(db, id) {
46
+ const item = db.prepare("SELECT * FROM items WHERE id = ?").get(id);
47
+ if (!item)
48
+ return null;
49
+ const reviews = db
50
+ .prepare("SELECT * FROM reviews WHERE item_id = ? ORDER BY due_date, id")
51
+ .all(id);
52
+ return { ...item, reviews };
53
+ }
54
+ export function addItem(db, input) {
55
+ const label = (input.label ?? "").trim();
56
+ if (!label)
57
+ throw new Error("label is required");
58
+ const steps = parseLadder(getLadder(db));
59
+ const dues = scheduleDates(input.first_date, steps);
60
+ const cur = db
61
+ .prepare("INSERT INTO items (label, source, anchor, note, first_date) VALUES (?, ?, ?, ?, ?)")
62
+ .run(label, input.source ?? null, input.anchor ?? null, input.note ?? "", input.first_date);
63
+ const id = Number(cur.lastInsertRowid);
64
+ const ins = db.prepare("INSERT INTO reviews (item_id, due_date, step) VALUES (?, ?, ?)");
65
+ steps.forEach((step, i) => ins.run(id, dues[i], step));
66
+ return getItem(db, id);
67
+ }
68
+ export function listItems(db) {
69
+ const ids = db.prepare("SELECT id FROM items ORDER BY first_date DESC, id DESC").all();
70
+ return ids.map((row) => getItem(db, row.id));
71
+ }
72
+ export function findItemByLabel(db, label) {
73
+ const row = db.prepare("SELECT id FROM items WHERE label = ?").get(label.trim());
74
+ return row ? getItem(db, row.id) : null;
75
+ }
76
+ export function updateItem(db, id, fields) {
77
+ const existing = getItem(db, id);
78
+ if (!existing)
79
+ return null;
80
+ const label = fields.label !== undefined ? fields.label.trim() : existing.label;
81
+ if (!label)
82
+ throw new Error("label is required");
83
+ db.prepare("UPDATE items SET label = ?, note = ?, source = ?, anchor = ? WHERE id = ?").run(label, fields.note !== undefined ? fields.note : existing.note, fields.source !== undefined ? fields.source : existing.source, fields.anchor !== undefined ? fields.anchor : existing.anchor, id);
84
+ return getItem(db, id);
85
+ }
86
+ export function deleteItem(db, id) {
87
+ return db.prepare("DELETE FROM items WHERE id = ?").run(id).changes > 0;
88
+ }
89
+ export function markReview(db, reviewId, done) {
90
+ const doneAt = done ? new Date().toISOString().slice(0, 19) : null;
91
+ return db.prepare("UPDATE reviews SET done_at = ? WHERE id = ?").run(doneAt, reviewId).changes > 0;
92
+ }
93
+ export function listDue(db, date) {
94
+ const cutoff = date ?? todayStr();
95
+ const rows = db
96
+ .prepare(`SELECT r.id AS r_id, r.item_id, r.due_date, r.step, r.done_at,
97
+ i.id AS i_id, i.label, i.source, i.anchor, i.note, i.first_date
98
+ FROM reviews r JOIN items i ON i.id = r.item_id
99
+ WHERE r.done_at IS NULL AND r.due_date <= ?
100
+ ORDER BY r.due_date, r.id`)
101
+ .all(cutoff);
102
+ return rows.map((row) => ({
103
+ review: {
104
+ id: row.r_id,
105
+ item_id: row.item_id,
106
+ due_date: row.due_date,
107
+ step: row.step,
108
+ done_at: row.done_at,
109
+ },
110
+ item: {
111
+ id: row.i_id,
112
+ label: row.label,
113
+ source: row.source,
114
+ anchor: row.anchor,
115
+ note: row.note,
116
+ first_date: row.first_date,
117
+ },
118
+ }));
119
+ }
120
+ export function exportData(db) {
121
+ return buildExport(getLadder(db), listItems(db));
122
+ }
123
+ export function importData(db, file) {
124
+ let added = 0;
125
+ let skipped = 0;
126
+ const exists = db.prepare("SELECT id FROM items WHERE label = ? AND first_date = ?");
127
+ const insItem = db.prepare("INSERT INTO items (label, source, anchor, note, first_date) VALUES (?, ?, ?, ?, ?)");
128
+ const insReview = db.prepare("INSERT INTO reviews (item_id, due_date, step, done_at) VALUES (?, ?, ?, ?)");
129
+ for (const item of file.items) {
130
+ if (exists.get(item.label, item.first_date)) {
131
+ skipped += 1;
132
+ continue;
133
+ }
134
+ const id = Number(insItem.run(item.label, item.source, item.anchor, item.note, item.first_date).lastInsertRowid);
135
+ for (const r of item.reviews)
136
+ insReview.run(id, r.due_date, r.step, r.done_at);
137
+ added += 1;
138
+ }
139
+ return { added, skipped };
140
+ }
@@ -0,0 +1,67 @@
1
+ import { readFileSync, readdirSync } from "node:fs";
2
+ import { basename, extname, join } from "node:path";
3
+ const HEADING_RE = /^(#{2,4})\s+(.+?)\s*$/;
4
+ export function githubSlug(text) {
5
+ return text
6
+ .trim()
7
+ .toLowerCase()
8
+ .replace(/[^\w\- ]/g, "")
9
+ .replace(/ /g, "-");
10
+ }
11
+ export function scan(notesDir) {
12
+ const sections = [];
13
+ let names;
14
+ try {
15
+ names = readdirSync(notesDir).filter((n) => [".md", ".txt"].includes(extname(n).toLowerCase()));
16
+ }
17
+ catch {
18
+ return sections;
19
+ }
20
+ names.sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()));
21
+ for (const name of names) {
22
+ let lines;
23
+ try {
24
+ lines = readFileSync(join(notesDir, name), "utf-8").split("\n");
25
+ }
26
+ catch {
27
+ continue;
28
+ }
29
+ const stem = basename(name, extname(name));
30
+ const counts = new Map();
31
+ let inCode = false;
32
+ let inToc = false;
33
+ lines.forEach((line, i) => {
34
+ if (line.includes("<!-- START doctoc")) {
35
+ inToc = true;
36
+ return;
37
+ }
38
+ if (line.includes("<!-- END doctoc")) {
39
+ inToc = false;
40
+ return;
41
+ }
42
+ if (inToc)
43
+ return;
44
+ if (line.trimStart().startsWith("```")) {
45
+ inCode = !inCode;
46
+ return;
47
+ }
48
+ if (inCode)
49
+ return;
50
+ const m = HEADING_RE.exec(line);
51
+ if (!m)
52
+ return;
53
+ const title = m[2];
54
+ const base = githubSlug(title);
55
+ const n = counts.get(base) ?? 0;
56
+ counts.set(base, n + 1);
57
+ sections.push({
58
+ file: name,
59
+ anchor: n === 0 ? base : `${base}-${n}`,
60
+ label: `${stem} > ${title}`,
61
+ line: i + 1,
62
+ level: m[1].length,
63
+ });
64
+ });
65
+ }
66
+ return sections;
67
+ }
@@ -0,0 +1,25 @@
1
+ import { DatabaseSync } from "node:sqlite";
2
+ import { EXPORT_VERSION } from "../core/exportFile.js";
3
+ import { DEFAULT_LADDER } from "../core/schedule.js";
4
+ export function legacyToExport(legacyDbPath) {
5
+ const db = new DatabaseSync(legacyDbPath, { readOnly: true });
6
+ try {
7
+ const ladderRow = db.prepare("SELECT value FROM settings WHERE key = 'ladder'").get();
8
+ const entries = db
9
+ .prepare("SELECT id, label, file, anchor, note, first_date FROM entries ORDER BY id")
10
+ .all();
11
+ const reviewStmt = db.prepare("SELECT due_date, step, done_at FROM reviews WHERE entry_id = ? ORDER BY due_date, id");
12
+ const items = entries.map((entry) => ({
13
+ label: entry.label,
14
+ source: entry.file,
15
+ anchor: entry.anchor,
16
+ note: entry.note,
17
+ first_date: entry.first_date,
18
+ reviews: reviewStmt.all(entry.id),
19
+ }));
20
+ return { version: EXPORT_VERSION, ladder: ladderRow?.value ?? DEFAULT_LADDER, items };
21
+ }
22
+ finally {
23
+ db.close();
24
+ }
25
+ }
@@ -0,0 +1,117 @@
1
+ import http from "node:http";
2
+ import { readFileSync } from "node:fs";
3
+ import { join, resolve } from "node:path";
4
+ import { parseExport } from "../core/exportFile.js";
5
+ import * as store from "./db.js";
6
+ import { scan } from "./indexer.js";
7
+ const STATIC = {
8
+ "/": ["index.html", "text/html; charset=utf-8"],
9
+ "/app.js": ["app.js", "application/javascript; charset=utf-8"],
10
+ "/style.css": ["style.css", "text/css; charset=utf-8"],
11
+ };
12
+ const REVIEW_RE = /^\/api\/reviews\/(\d+)\/(done|undone)$/;
13
+ const ITEM_RE = /^\/api\/items\/(\d+)$/;
14
+ function send(res, status, obj, headers = {}) {
15
+ const body = JSON.stringify(obj);
16
+ res.writeHead(status, { "Content-Type": "application/json; charset=utf-8", ...headers });
17
+ res.end(body);
18
+ }
19
+ function readBody(req) {
20
+ return new Promise((resolvePromise, reject) => {
21
+ const chunks = [];
22
+ req.on("data", (c) => chunks.push(c));
23
+ req.on("error", reject);
24
+ req.on("end", () => {
25
+ const raw = Buffer.concat(chunks).toString("utf-8");
26
+ if (raw === "")
27
+ return resolvePromise({});
28
+ try {
29
+ resolvePromise(JSON.parse(raw));
30
+ }
31
+ catch {
32
+ reject(new Error("invalid JSON body"));
33
+ }
34
+ });
35
+ });
36
+ }
37
+ function asRecord(v) {
38
+ return typeof v === "object" && v !== null ? v : {};
39
+ }
40
+ export function createApp(db, opts) {
41
+ return http.createServer(async (req, res) => {
42
+ try {
43
+ await route(db, opts, req, res);
44
+ }
45
+ catch (err) {
46
+ send(res, 400, { error: err instanceof Error ? err.message : String(err) });
47
+ }
48
+ });
49
+ }
50
+ async function route(db, opts, req, res) {
51
+ const path = new URL(req.url ?? "/", "http://localhost").pathname;
52
+ const method = req.method ?? "GET";
53
+ if (method === "GET" && path in STATIC) {
54
+ const [name, ctype] = STATIC[path];
55
+ try {
56
+ const body = readFileSync(join(opts.publicDir, name));
57
+ res.writeHead(200, { "Content-Type": ctype });
58
+ res.end(body);
59
+ }
60
+ catch {
61
+ send(res, 404, { error: `missing static file: ${name}` });
62
+ }
63
+ return;
64
+ }
65
+ if (method === "GET") {
66
+ if (path === "/api/items")
67
+ return send(res, 200, store.listItems(db));
68
+ if (path === "/api/settings")
69
+ return send(res, 200, { ladder: store.getLadder(db) });
70
+ if (path === "/api/sections") {
71
+ return send(res, 200, {
72
+ base: opts.notesDir ? resolve(opts.notesDir) : null,
73
+ sections: opts.notesDir ? scan(opts.notesDir) : [],
74
+ });
75
+ }
76
+ if (path === "/api/export") {
77
+ return send(res, 200, store.exportData(db), {
78
+ "Content-Disposition": 'attachment; filename="grind-export.json"',
79
+ });
80
+ }
81
+ return send(res, 404, { error: "not found" });
82
+ }
83
+ if (method === "POST") {
84
+ const payload = asRecord(await readBody(req));
85
+ const review = REVIEW_RE.exec(path);
86
+ if (path === "/api/items") {
87
+ const item = store.addItem(db, {
88
+ label: String(payload.label ?? ""),
89
+ source: payload.source == null ? null : String(payload.source),
90
+ anchor: payload.anchor == null ? null : String(payload.anchor),
91
+ note: String(payload.note ?? ""),
92
+ first_date: String(payload.first_date ?? ""),
93
+ });
94
+ return send(res, 201, item);
95
+ }
96
+ if (review) {
97
+ const ok = store.markReview(db, Number(review[1]), review[2] === "done");
98
+ return ok ? send(res, 200, { ok: true }) : send(res, 404, { error: "review not found" });
99
+ }
100
+ if (path === "/api/settings") {
101
+ store.setLadder(db, String(payload.ladder ?? ""));
102
+ return send(res, 200, { ok: true });
103
+ }
104
+ if (path === "/api/import") {
105
+ return send(res, 200, store.importData(db, parseExport(payload)));
106
+ }
107
+ return send(res, 404, { error: "not found" });
108
+ }
109
+ if (method === "DELETE") {
110
+ const m = ITEM_RE.exec(path);
111
+ if (!m)
112
+ return send(res, 404, { error: "not found" });
113
+ const ok = store.deleteItem(db, Number(m[1]));
114
+ return ok ? send(res, 200, { ok: true }) : send(res, 404, { error: "item not found" });
115
+ }
116
+ send(res, 404, { error: "not found" });
117
+ }
@@ -0,0 +1,72 @@
1
+ export const EXPORT_VERSION = 1;
2
+ export function buildExport(ladder, items) {
3
+ return {
4
+ version: EXPORT_VERSION,
5
+ ladder,
6
+ items: items.map((item) => ({
7
+ label: item.label,
8
+ source: item.source,
9
+ anchor: item.anchor,
10
+ note: item.note,
11
+ first_date: item.first_date,
12
+ reviews: item.reviews.map((r) => ({ due_date: r.due_date, step: r.step, done_at: r.done_at })),
13
+ })),
14
+ };
15
+ }
16
+ const DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
17
+ function fail(path, expected) {
18
+ throw new Error(`invalid export file: ${path} must be ${expected}`);
19
+ }
20
+ function isRecord(v) {
21
+ return typeof v === "object" && v !== null && !Array.isArray(v);
22
+ }
23
+ function parseReview(v, path) {
24
+ if (!isRecord(v))
25
+ fail(path, "an object");
26
+ if (typeof v.due_date !== "string" || !DATE_RE.test(v.due_date))
27
+ fail(`${path}.due_date`, "a YYYY-MM-DD string");
28
+ if (typeof v.step !== "number" || !Number.isInteger(v.step) || v.step <= 0)
29
+ fail(`${path}.step`, "a positive integer");
30
+ if (v.done_at !== null && typeof v.done_at !== "string")
31
+ fail(`${path}.done_at`, "a string or null");
32
+ return { due_date: v.due_date, step: v.step, done_at: v.done_at ?? null };
33
+ }
34
+ function parseItem(v, path) {
35
+ if (!isRecord(v))
36
+ fail(path, "an object");
37
+ if (typeof v.label !== "string" || v.label.trim() === "")
38
+ fail(`${path}.label`, "a non-empty string");
39
+ if (v.source !== null && v.source !== undefined && typeof v.source !== "string")
40
+ fail(`${path}.source`, "a string or null");
41
+ if (v.anchor !== null && v.anchor !== undefined && typeof v.anchor !== "string")
42
+ fail(`${path}.anchor`, "a string or null");
43
+ if (v.note !== undefined && typeof v.note !== "string")
44
+ fail(`${path}.note`, "a string");
45
+ if (typeof v.first_date !== "string" || !DATE_RE.test(v.first_date))
46
+ fail(`${path}.first_date`, "a YYYY-MM-DD string");
47
+ if (!Array.isArray(v.reviews))
48
+ fail(`${path}.reviews`, "an array");
49
+ return {
50
+ label: v.label,
51
+ source: v.source ?? null,
52
+ anchor: v.anchor ?? null,
53
+ note: v.note ?? "",
54
+ first_date: v.first_date,
55
+ reviews: v.reviews.map((r, i) => parseReview(r, `${path}.reviews[${i}]`)),
56
+ };
57
+ }
58
+ export function parseExport(data) {
59
+ if (!isRecord(data))
60
+ throw new Error("invalid export file: expected a JSON object");
61
+ if (data.version !== EXPORT_VERSION)
62
+ throw new Error(`unsupported export file version: ${String(data.version)}`);
63
+ if (typeof data.ladder !== "string")
64
+ fail("ladder", "a string");
65
+ if (!Array.isArray(data.items))
66
+ fail("items", "an array");
67
+ return {
68
+ version: EXPORT_VERSION,
69
+ ladder: data.ladder,
70
+ items: data.items.map((item, i) => parseItem(item, `items[${i}]`)),
71
+ };
72
+ }
@@ -0,0 +1,46 @@
1
+ export const DEFAULT_LADDER = "1,3,7,14,30";
2
+ export function parseLadder(s) {
3
+ const parts = s.split(",").map((p) => p.trim());
4
+ if (parts.some((p) => !/^\d+$/.test(p))) {
5
+ throw new Error("ladder must be comma-separated integers, e.g. 1,3,7,14,30");
6
+ }
7
+ const steps = parts.map(Number);
8
+ if (steps.some((x) => x <= 0)) {
9
+ throw new Error("ladder steps must be positive integers");
10
+ }
11
+ if (!steps.every((x, i) => i === 0 || steps[i - 1] < x)) {
12
+ throw new Error("ladder steps must be strictly ascending");
13
+ }
14
+ return steps;
15
+ }
16
+ const DAY_MS = 86_400_000;
17
+ export function addDays(isoDate, days) {
18
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(isoDate)) {
19
+ throw new Error("invalid date: " + isoDate);
20
+ }
21
+ const t = Date.parse(isoDate + "T00:00:00Z");
22
+ if (Number.isNaN(t)) {
23
+ throw new Error("invalid date: " + isoDate);
24
+ }
25
+ try {
26
+ const roundTrip = new Date(t).toISOString().slice(0, 10);
27
+ if (roundTrip !== isoDate) {
28
+ throw new Error("invalid date: " + isoDate);
29
+ }
30
+ }
31
+ catch (e) {
32
+ throw new Error("invalid date: " + isoDate);
33
+ }
34
+ try {
35
+ return new Date(t + days * DAY_MS).toISOString().slice(0, 10);
36
+ }
37
+ catch (e) {
38
+ throw new Error("invalid date: " + isoDate);
39
+ }
40
+ }
41
+ export function scheduleDates(firstDate, steps) {
42
+ return steps.map((step) => addDays(firstDate, step));
43
+ }
44
+ export function todayStr() {
45
+ return new Date().toLocaleDateString("en-CA");
46
+ }
@@ -0,0 +1 @@
1
+ export {};
package/package.json ADDED
@@ -0,0 +1,22 @@
1
+ {
2
+ "name": "grind-tracker",
3
+ "version": "0.1.0",
4
+ "description": "Local-first spaced-repetition tracker for things you're learning, with a local web UI.",
5
+ "license": "Apache-2.0",
6
+ "author": "jycd25",
7
+ "type": "module",
8
+ "bin": { "grind-tracker": "dist/app/cli.js" },
9
+ "engines": { "node": ">=24" },
10
+ "files": ["dist", "public", "README.md"],
11
+ "scripts": {
12
+ "test": "node --test 'src/**/*.test.ts'",
13
+ "typecheck": "tsc --noEmit",
14
+ "build": "tsc -p tsconfig.build.json",
15
+ "dev": "node src/app/cli.ts",
16
+ "prepublishOnly": "npm run typecheck && npm test && npm run build"
17
+ },
18
+ "devDependencies": {
19
+ "@types/node": "^24.0.0",
20
+ "typescript": "^5.8.0"
21
+ }
22
+ }
package/public/app.js ADDED
@@ -0,0 +1,262 @@
1
+ "use strict";
2
+
3
+ const state = { base: null, sections: [], items: [], selected: [] };
4
+
5
+ const $ = (sel) => document.querySelector(sel);
6
+
7
+ function esc(s) {
8
+ return String(s).replace(/[&<>"']/g, (c) => ({
9
+ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;",
10
+ }[c]));
11
+ }
12
+
13
+ function todayStr() {
14
+ return new Date().toLocaleDateString("en-CA");
15
+ }
16
+
17
+ async function api(method, path, body) {
18
+ const opts = { method, headers: {} };
19
+ if (body !== undefined) {
20
+ opts.headers["Content-Type"] = "application/json";
21
+ opts.body = JSON.stringify(body);
22
+ }
23
+ const resp = await fetch(path, opts);
24
+ const data = await resp.json().catch(() => null);
25
+ if (!resp.ok) throw new Error((data && data.error) || ("HTTP " + resp.status));
26
+ return data;
27
+ }
28
+
29
+ async function loadAll() {
30
+ const [sec, items, settings] = await Promise.all([
31
+ api("GET", "/api/sections"),
32
+ api("GET", "/api/items"),
33
+ api("GET", "/api/settings"),
34
+ ]);
35
+ state.base = sec.base;
36
+ state.sections = sec.sections;
37
+ state.items = items;
38
+ $("#ladder").value = settings.ladder;
39
+ $("#search-wrap").classList.toggle("hidden", state.sections.length === 0);
40
+ renderDue();
41
+ renderAll();
42
+ }
43
+
44
+ function sourceLink(item) {
45
+ if (!item.source) return "";
46
+ const live = state.base &&
47
+ state.sections.find((s) => s.file === item.source && s.anchor === item.anchor);
48
+ if (!live) return '<span class="badge moved">' + esc(item.source) + "</span>";
49
+ const href = "vscode://file/" + state.base + "/" + live.file + ":" + live.line;
50
+ return '<a href="' + esc(href) + '">open notes</a>';
51
+ }
52
+
53
+ function dueRows() {
54
+ const today = todayStr();
55
+ const rows = [];
56
+ for (const item of state.items) {
57
+ for (const review of item.reviews) {
58
+ if (!review.done_at && review.due_date <= today) {
59
+ rows.push({ item, review });
60
+ }
61
+ }
62
+ }
63
+ rows.sort((a, b) => a.review.due_date.localeCompare(b.review.due_date));
64
+ return rows;
65
+ }
66
+
67
+ function daysLate(dueDate) {
68
+ const ms = new Date(todayStr()) - new Date(dueDate);
69
+ return Math.round(ms / 86400000);
70
+ }
71
+
72
+ function renderDue() {
73
+ const rows = dueRows();
74
+ const el = $("#due-list");
75
+ if (rows.length === 0) {
76
+ el.innerHTML = '<p class="empty">Nothing due. Go grind something.</p>';
77
+ return;
78
+ }
79
+ el.innerHTML = rows.map(({ item, review }) => {
80
+ const late = daysLate(review.due_date);
81
+ const lateBadge = late > 0 ? '<span class="badge late">' + late + "d late</span>" : "";
82
+ return '<div class="row">' +
83
+ '<span class="badge step">+' + review.step + "d</span>" +
84
+ "<strong>" + esc(item.label) + "</strong>" + lateBadge +
85
+ (item.note ? '<span class="note">' + esc(item.note) + "</span>" : "") +
86
+ sourceLink(item) +
87
+ '<button data-done="' + review.id + '">Done</button>' +
88
+ "</div>";
89
+ }).join("");
90
+ }
91
+
92
+ function renderAll() {
93
+ const el = $("#all-list");
94
+ if (state.items.length === 0) {
95
+ el.innerHTML = '<p class="empty">No items yet.</p>';
96
+ return;
97
+ }
98
+ el.innerHTML = state.items.map((item) => {
99
+ const chips = item.reviews.map((r) => {
100
+ const cls = r.done_at ? "done" : (r.due_date <= todayStr() ? "duenow" : "future");
101
+ return '<span class="chip ' + cls + '">+' + r.step + "d " +
102
+ r.due_date.slice(5) + (r.done_at ? " ✓" : "") + "</span>";
103
+ }).join("");
104
+ return '<div class="card">' +
105
+ "<strong>" + esc(item.label) + "</strong> " + sourceLink(item) +
106
+ '<div class="meta">grinded ' + esc(item.first_date) +
107
+ (item.note ? " — " + esc(item.note) : "") + "</div>" +
108
+ '<div class="chips">' + chips + "</div>" +
109
+ '<button class="danger" data-del="' + item.id + '">Delete</button>' +
110
+ "</div>";
111
+ }).join("");
112
+ }
113
+
114
+ function renderSearch() {
115
+ const q = $("#search").value.trim().toLowerCase();
116
+ const el = $("#search-results");
117
+ if (!q) { el.innerHTML = ""; return; }
118
+ const matches = state.sections.filter((s) => s.label.toLowerCase().includes(q)).slice(0, 50);
119
+ el.innerHTML = matches.map((s, i) =>
120
+ '<div class="result" data-idx="' + i + '">' + esc(s.label) + "</div>"
121
+ ).join("") || '<p class="empty">No matching sections.</p>';
122
+ el.querySelectorAll(".result").forEach((node, i) => {
123
+ node.addEventListener("click", () => {
124
+ selectCandidate({ label: matches[i].label, source: matches[i].file, anchor: matches[i].anchor });
125
+ $("#search-results").innerHTML = "";
126
+ $("#search").value = "";
127
+ $("#search").focus();
128
+ });
129
+ });
130
+ }
131
+
132
+ function candidateKey(c) {
133
+ return c.label + "\n" + (c.source || "") + "\n" + (c.anchor || "");
134
+ }
135
+
136
+ function selectCandidate(candidate) {
137
+ if (!state.selected.some((s) => candidateKey(s) === candidateKey(candidate))) {
138
+ state.selected.push(candidate);
139
+ }
140
+ renderSelected();
141
+ }
142
+
143
+ function renderSelected() {
144
+ const el = $("#selected-section");
145
+ if (state.selected.length === 0) {
146
+ el.classList.add("hidden");
147
+ el.innerHTML = "";
148
+ $("#add-save").disabled = true;
149
+ return;
150
+ }
151
+ el.classList.remove("hidden");
152
+ el.innerHTML = "Selected: " + state.selected.map((s, i) =>
153
+ '<span class="chip">' + esc(s.label) +
154
+ '<button class="unsel" data-unsel="' + i + '" title="Remove">&times;</button></span>'
155
+ ).join("");
156
+ el.querySelectorAll("[data-unsel]").forEach((node) => {
157
+ node.addEventListener("click", () => {
158
+ state.selected.splice(Number(node.getAttribute("data-unsel")), 1);
159
+ renderSelected();
160
+ });
161
+ });
162
+ $("#add-save").disabled = false;
163
+ }
164
+
165
+ function addManual() {
166
+ const label = $("#manual-label").value.trim();
167
+ if (!label) return;
168
+ selectCandidate({ label: label, source: null, anchor: null });
169
+ $("#manual-label").value = "";
170
+ $("#manual-label").focus();
171
+ }
172
+
173
+ async function saveItems() {
174
+ if (state.selected.length === 0) return;
175
+ const note = $("#add-note").value.trim();
176
+ const firstDate = $("#add-date").value;
177
+ const saved = [];
178
+ try {
179
+ for (const s of [...state.selected]) {
180
+ const item = await api("POST", "/api/items", {
181
+ label: s.label, source: s.source, anchor: s.anchor,
182
+ note: note, first_date: firstDate,
183
+ });
184
+ saved.push(item);
185
+ state.selected = state.selected.filter((x) => candidateKey(x) !== candidateKey(s));
186
+ }
187
+ $("#add-confirm").textContent = "Saved " + saved.length +
188
+ (saved.length === 1 ? " item." : " items.") +
189
+ " Reviews due: " + saved[0].reviews.map((r) => r.due_date).join(", ");
190
+ $("#add-note").value = "";
191
+ } catch (err) {
192
+ $("#add-confirm").textContent = "Error: " + err.message +
193
+ (saved.length ? " (" + saved.length + " saved before the error)" : "");
194
+ }
195
+ renderSelected();
196
+ await refreshItems();
197
+ }
198
+
199
+ async function refreshItems() {
200
+ state.items = await api("GET", "/api/items");
201
+ renderDue();
202
+ renderAll();
203
+ }
204
+
205
+ async function importFile(file) {
206
+ try {
207
+ const data = JSON.parse(await file.text());
208
+ const result = await api("POST", "/api/import", data);
209
+ $("#import-msg").textContent =
210
+ "Imported " + result.added + " item(s), skipped " + result.skipped + " duplicate(s).";
211
+ await refreshItems();
212
+ } catch (err) {
213
+ $("#import-msg").textContent = "Error: " + err.message;
214
+ }
215
+ }
216
+
217
+ document.addEventListener("click", async (event) => {
218
+ const done = event.target.getAttribute && event.target.getAttribute("data-done");
219
+ const del = event.target.getAttribute && event.target.getAttribute("data-del");
220
+ if (done) {
221
+ await api("POST", "/api/reviews/" + done + "/done");
222
+ await refreshItems();
223
+ } else if (del) {
224
+ if (confirm("Delete this item and its whole schedule?")) {
225
+ await api("DELETE", "/api/items/" + del);
226
+ await refreshItems();
227
+ }
228
+ }
229
+ });
230
+
231
+ $("#tabs").addEventListener("click", (event) => {
232
+ const tab = event.target.getAttribute("data-tab");
233
+ if (!tab) return;
234
+ document.querySelectorAll("#tabs button").forEach((b) => b.classList.toggle("active", b === event.target));
235
+ document.querySelectorAll(".tab").forEach((s) => s.classList.toggle("active", s.id === "tab-" + tab));
236
+ });
237
+
238
+ $("#search").addEventListener("input", renderSearch);
239
+ $("#manual-add").addEventListener("click", addManual);
240
+ $("#manual-label").addEventListener("keydown", (event) => {
241
+ if (event.key === "Enter") addManual();
242
+ });
243
+ $("#add-save").addEventListener("click", saveItems);
244
+ $("#ladder-save").addEventListener("click", async () => {
245
+ try {
246
+ await api("POST", "/api/settings", { ladder: $("#ladder").value.trim() });
247
+ $("#settings-msg").textContent = "Saved.";
248
+ } catch (err) {
249
+ $("#settings-msg").textContent = "Error: " + err.message;
250
+ }
251
+ });
252
+ $("#import-file").addEventListener("change", (event) => {
253
+ const file = event.target.files && event.target.files[0];
254
+ if (file) importFile(file);
255
+ event.target.value = "";
256
+ });
257
+
258
+ $("#add-date").value = todayStr();
259
+ loadAll().catch((err) => {
260
+ document.body.insertAdjacentHTML("afterbegin",
261
+ '<p class="empty">Failed to load: ' + esc(err.message) + "</p>");
262
+ });
@@ -0,0 +1,70 @@
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <title>Grind Tracker</title>
7
+ <link rel="stylesheet" href="/style.css">
8
+ </head>
9
+ <body>
10
+ <header>
11
+ <h1>Grind Tracker</h1>
12
+ <nav id="tabs">
13
+ <button data-tab="due" class="active">Due</button>
14
+ <button data-tab="add">Add</button>
15
+ <button data-tab="all">All</button>
16
+ <button data-tab="settings">Settings</button>
17
+ </nav>
18
+ </header>
19
+
20
+ <main>
21
+ <section id="tab-due" class="tab active">
22
+ <div id="due-list"></div>
23
+ </section>
24
+
25
+ <section id="tab-add" class="tab">
26
+ <label>What did you grind?
27
+ <span class="add-row">
28
+ <input id="manual-label" type="text" placeholder="e.g. 0/1 knapsack" autocomplete="off">
29
+ <button id="manual-add">Add</button>
30
+ </span>
31
+ </label>
32
+ <div id="search-wrap" class="hidden">
33
+ <label>Or pick from your notes
34
+ <input id="search" type="text" placeholder="Type to search indexed sections" autocomplete="off">
35
+ </label>
36
+ <div id="search-results"></div>
37
+ </div>
38
+ <div id="selected-section" class="hidden"></div>
39
+ <label>Grind date
40
+ <input id="add-date" type="date">
41
+ </label>
42
+ <label>Note (optional)
43
+ <input id="add-note" type="text" placeholder="e.g. forgot the reverse-iteration trick">
44
+ </label>
45
+ <button id="add-save" disabled>Save</button>
46
+ <p id="add-confirm" class="confirm"></p>
47
+ </section>
48
+
49
+ <section id="tab-all" class="tab">
50
+ <div id="all-list"></div>
51
+ </section>
52
+
53
+ <section id="tab-settings" class="tab">
54
+ <label>Review ladder (days after first grind)
55
+ <input id="ladder" type="text">
56
+ </label>
57
+ <button id="ladder-save">Save</button>
58
+ <p class="hint">Changes affect new items only.</p>
59
+ <p id="settings-msg" class="confirm"></p>
60
+ <p id="export-row"><a href="/api/export" download="grind-export.json">Export JSON</a></p>
61
+ <label>Import JSON
62
+ <input id="import-file" type="file" accept="application/json">
63
+ </label>
64
+ <p id="import-msg" class="confirm"></p>
65
+ </section>
66
+ </main>
67
+
68
+ <script src="/app.js"></script>
69
+ </body>
70
+ </html>
@@ -0,0 +1,78 @@
1
+ :root {
2
+ --bg: #ffffff; --fg: #1f2328; --muted: #656d76; --line: #d0d7de;
3
+ --accent: #0969da; --late: #cf222e; --ok: #1a7f37; --chipbg: #f6f8fa;
4
+ }
5
+ @media (prefers-color-scheme: dark) {
6
+ :root {
7
+ --bg: #0d1117; --fg: #e6edf3; --muted: #8b949e; --line: #30363d;
8
+ --accent: #58a6ff; --late: #f85149; --ok: #3fb950; --chipbg: #161b22;
9
+ }
10
+ }
11
+ * { box-sizing: border-box; }
12
+ body {
13
+ margin: 0 auto; max-width: 760px; padding: 16px;
14
+ font: 15px/1.5 -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
15
+ background: var(--bg); color: var(--fg);
16
+ }
17
+ header { display: flex; align-items: baseline; gap: 24px; flex-wrap: wrap; }
18
+ h1 { font-size: 20px; margin: 8px 0; }
19
+ nav button {
20
+ background: none; border: none; color: var(--muted); font-size: 15px;
21
+ padding: 6px 10px; cursor: pointer; border-bottom: 2px solid transparent;
22
+ }
23
+ nav button.active { color: var(--fg); border-bottom-color: var(--accent); }
24
+ .tab { display: none; margin-top: 16px; }
25
+ .tab.active { display: block; }
26
+ label { display: block; margin: 12px 0 4px; color: var(--muted); font-size: 13px; }
27
+ input[type="text"], input[type="date"] {
28
+ width: 100%; padding: 8px; font-size: 15px; color: var(--fg);
29
+ background: var(--chipbg); border: 1px solid var(--line); border-radius: 6px;
30
+ }
31
+ button {
32
+ margin-top: 10px; padding: 6px 14px; font-size: 14px; cursor: pointer;
33
+ background: var(--accent); color: #fff; border: none; border-radius: 6px;
34
+ }
35
+ button:disabled { opacity: 0.4; cursor: default; }
36
+ button.danger { background: var(--late); }
37
+ .row, .card {
38
+ border: 1px solid var(--line); border-radius: 8px;
39
+ padding: 10px 12px; margin: 8px 0;
40
+ }
41
+ .row { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
42
+ .row button { margin: 0 0 0 auto; }
43
+ .badge {
44
+ font-size: 12px; padding: 1px 8px; border-radius: 10px;
45
+ background: var(--chipbg); border: 1px solid var(--line);
46
+ }
47
+ .badge.late { color: var(--late); border-color: var(--late); }
48
+ .badge.moved { color: var(--muted); }
49
+ .badge.step { color: var(--accent); }
50
+ .note, .meta, .hint { color: var(--muted); font-size: 13px; }
51
+ .chips { margin: 6px 0; display: flex; gap: 6px; flex-wrap: wrap; }
52
+ .chip {
53
+ font-size: 12px; padding: 1px 8px; border-radius: 10px;
54
+ background: var(--chipbg); border: 1px solid var(--line);
55
+ }
56
+ .chip.done { color: var(--ok); }
57
+ .chip.duenow { color: var(--late); }
58
+ #selected-section {
59
+ margin-top: 8px; display: flex; gap: 6px; flex-wrap: wrap;
60
+ align-items: center; font-size: 13px; color: var(--muted);
61
+ }
62
+ .chip button.unsel {
63
+ margin: 0 0 0 4px; padding: 0 2px; font-size: 13px; line-height: 1;
64
+ background: none; color: var(--muted); border: none; cursor: pointer;
65
+ }
66
+ .chip button.unsel:hover { color: var(--late); }
67
+ .result { padding: 6px 10px; border-bottom: 1px solid var(--line); cursor: pointer; }
68
+ .result:hover { background: var(--chipbg); }
69
+ #search-results { max-height: 320px; overflow-y: auto; margin-top: 4px; }
70
+ .confirm { color: var(--ok); font-size: 13px; }
71
+ .empty { color: var(--muted); }
72
+ .hidden { display: none; }
73
+ a { color: var(--accent); }
74
+
75
+ /* public-version additions */
76
+ .add-row { display: flex; gap: 8px; align-items: center; }
77
+ .add-row input { flex: 1; }
78
+ #import-msg, #export-row { margin-top: 12px; }