@pritzlaff/agile 0.0.0-stage → 1.0.1

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/README.md CHANGED
@@ -1,3 +1,179 @@
1
- # Temporary Holding Version
1
+ # Gantt
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **[▶ Open the chart](https://aaronp.github.io/gantt/)** ·
4
+ [Acme example](https://aaronp.github.io/gantt/?src=examples/acme-roadmap/ROADMAP.md)
5
+
6
+ A Gantt chart driven by **one markdown file**. Tasks are ordinary list items
7
+ with a few attributes, and everything else in the file is kept as written.
8
+ Drag a bar to move it, drag its right edge to change its duration, drag ⋮⋮ to
9
+ reorder, and pin a task to a date. Each edit is written straight back into the
10
+ markdown shown alongside the chart.
11
+
12
+ This repo is the viewer. Your plan can live in its own repo and be loaded with
13
+ `?src=` (see [Publishing your own plan](#publishing-your-own-plan)).
14
+
15
+ ## The file format
16
+
17
+ The full format, with a minimal and a complete example, is in
18
+ **[spec.md](spec.md)**. In short:
19
+
20
+ ```markdown
21
+ # Atlas mobile app — v2 launch
22
+
23
+ ## Design
24
+ - [ ] Wireframes `id:wire` `start:2026-10-26` `dur:5d`
25
+ - [ ] Visual design `id:visual` `after:wire+1d` `dur:6d`
26
+ - Launch `id:launch` `after:visual` `dur:0d`
27
+ ```
28
+
29
+ A task needs an `id`, a `dur`, and either a fixed `start` date, `after:` the
30
+ tasks whose **end** it follows, or `with:` the tasks whose **start** it follows.
31
+ `dur:0d` is a milestone. Tasks can also carry `tags:` and named links such as
32
+ `[Figma](https://…)`.
33
+
34
+ ## Query parameters
35
+
36
+ | Query | Values |
37
+ | --- | --- |
38
+ | `src` | The plan to load: absolute, or relative to the page. Without it, a blank plan is shown. |
39
+ | `theme` | `paper` (default), `night`, `blueprint`, `warm`. It also remembers your last choice in the browser. |
40
+ | `zoom` | `day` (default) or `week` |
41
+ | `view` | `split` (default: chart and markdown) or `chart` |
42
+ | `q` | Filter text: tasks whose name, id, section or tags match stay bright and the rest are dimmed |
43
+ | `tags` | Comma-separated tags: tasks carrying any of them stay bright (the **Tags** dropdown in the header) |
44
+ | `task` | A task id: selects it and opens its inspector |
45
+ | `today` | `YYYY-MM-DD`: draws "today" on that date instead of the real one |
46
+
47
+ The address bar follows along as you change these, so you can copy it to share
48
+ the current view.
49
+
50
+ Sources on another host must allow CORS. GitHub Pages and
51
+ `raw.githubusercontent.com` do.
52
+
53
+ The **File** menu in the header has **New**, which starts a fresh plan (asking
54
+ first if you have unsaved edits), **Open**, which loads another plan (drop a `.md`
55
+ file, choose one, or enter a URL; a URL stays in the address bar as `?src=`),
56
+ **Download**, which saves the markdown file, and
57
+ **Copy link**, which copies a link with the whole plan compressed into its `#md=`
58
+ hash (it warns when the link is over 2,048 characters, which some apps cut off).
59
+ **Save** keeps the plan in this browser under a name you choose; reopen it from
60
+ **Open** → *Saved in this browser*, where saves can also be deleted. The badge in
61
+ the header tells you whether the chart has changes that aren't saved anywhere
62
+ yet. Browser saves stay on this device; download the file to keep it in git.
63
+
64
+ ## Viewing locally
65
+
66
+ ```sh
67
+ make dev # serves on http://localhost:8000/ and prints the example's URL
68
+ ```
69
+
70
+ Some browsers block the scripts over `file://`, so serve the folder.
71
+ When the chart is served by `make dev` or the `agile` CLI, **File → Save to ROADMAP.md**
72
+ writes your edits straight back to the file.
73
+
74
+ ## The `agile` CLI
75
+
76
+ ```sh
77
+ bunx @pritzlaff/agile ROADMAP.md # or npx; no install needed
78
+ ```
79
+
80
+ It serves the chart and that file on localhost and opens the browser. Other `.md`
81
+ files under the current directory can be opened with `?src=` too. **File → Save** writes
82
+ the plan back to disk. `PORT=8000` fixes the port; `NO_OPEN=1` skips opening a browser.
83
+ The package has no dependencies: it is `bin/agile.mjs` plus the page itself.
84
+
85
+ ### Card and badge
86
+
87
+ ```sh
88
+ agile card ROADMAP.md [out-dir] # → card.json: the plan as a dashboard card (data only)
89
+ agile badge ROADMAP.md [out-dir] # → badge.svg: drawn from the same card
90
+ ```
91
+
92
+ `card.json` (version 1) has a title (the plan's), a subtitle (its date span), a status pill
93
+ (`N conflicts`, else `N late`, else `On track`), a big number (tasks), a legend with a count per
94
+ status, and a link to the plan. A task is **done** when ticked (or, without a checkbox,
95
+ once its end has passed), **late** when open past its end, **in progress** while today is
96
+ inside it, and **upcoming** otherwise.
97
+
98
+ What the card says (titles, legend labels, colours, order) comes from an optional
99
+ `ROADMAP.card.json` beside the markdown. Design one with **File → Design card…**
100
+ (`card.html?src=…`), which previews the card and badge and downloads the file, or saves it
101
+ beside the plan when served by the CLI. The link opens the chart at `AGILE_HOST` (default
102
+ `https://aaronp.github.io/gantt/`) on `AGILE_SRC` (where your published markdown lives); set both
103
+ as environment variables. The Pages workflow here regenerates the Acme example's files on every
104
+ push, so a README can embed the live badge:
105
+
106
+ ```md
107
+ [![Plan](https://you.github.io/your-plan/badge.svg)](https://you.github.io/your-plan/)
108
+ ```
109
+
110
+ ### Adding it to your Bun project
111
+
112
+ ```sh
113
+ bun add -d @pritzlaff/agile
114
+ bun pm pkg set scripts.plan="agile plan/ROADMAP.md"
115
+ mkdir -p plan && echo '- Launch `id:launch` `start:2026-12-14` `dur:3d`' > plan/ROADMAP.md
116
+ bun run plan
117
+ ```
118
+
119
+ [examples/bun-app](examples/bun-app) is this setup end to end, including a Pages workflow that
120
+ publishes `plan/` with its badge and card.
121
+
122
+ ### Releasing
123
+
124
+ ```sh
125
+ make bump-patch # or bump-minor / bump-major: npm version, which commits and tags (clean tree needed)
126
+ make publish # tests, then npm publish
127
+ make dist # tests, then packs the same thing into a local .tgz
128
+ ```
129
+
130
+ ## Hosting
131
+
132
+ `.github/workflows/pages.yml` publishes the repo to GitHub Pages on pushes to
133
+ `main` or `master` (Settings → Pages → Source: **GitHub Actions**; the
134
+ `github-pages` environment must allow your branch). There is no build step.
135
+ `.md` files are served raw, without Jekyll.
136
+
137
+ ## Publishing your own plan
138
+
139
+ Your plan lives in its own data-only repo (`ROADMAP.md`, a redirecting
140
+ `index.html` and a Pages workflow); this repo stays the viewer. Create an empty
141
+ repo on GitHub, then either:
142
+
143
+ **A. Start from `examples/` in this repo**
144
+
145
+ ```sh
146
+ git clone https://github.com/aaronp/gantt.git
147
+ cd gantt/examples/acme-roadmap
148
+ make clone REPO=you/your-plan # or ./clone.sh to be prompted
149
+ ```
150
+
151
+ This copies the example to `../your-plan` as a fresh repo on `main`, points its
152
+ README link at `https://you.github.io/your-plan/` and sets the `origin` remote.
153
+
154
+ **B. Clone the standalone example**
155
+
156
+ ```sh
157
+ git clone https://github.com/aaronp/gantt-example.git your-plan
158
+ cd your-plan
159
+ git remote set-url origin git@github.com:you/your-plan.git
160
+ ```
161
+
162
+ Then change the **View** link in its README to `https://you.github.io/your-plan/`.
163
+
164
+ Either way, edit `ROADMAP.md`, commit and `git push -u origin main`, then on
165
+ GitHub set Settings → Pages → Source: **GitHub Actions**. Your site at
166
+ `https://you.github.io/your-plan/` redirects here with `?src=` pointing at your
167
+ `ROADMAP.md`, passing on any other query params.
168
+
169
+ ## Files
170
+
171
+ - `index.html`: the page. It holds an `<x-dc>` template, its logic class (the
172
+ parser, scheduler and edit operations are the pure `G` module at its top), and
173
+ the loader that fetches `?src=` before booting.
174
+ - `support.js`, `vendor/react*.js`: the runtime that renders the component.
175
+ - `examples/acme-roadmap/`: a cloneable data-only repo that points back here.
176
+ - `examples/bun-app/`: a Bun project with its own `plan/ROADMAP.md`: `bun run plan` opens it locally, Pages publishes it.
177
+ - `card.js`: `card.json` and the badge, shared by the CLI and `card.html` (the card designer). It reads plans with the page's own parser, cut out of `index.html`.
178
+ - `bin/agile.mjs`: the CLI (local server with save, `card`, `badge`).
179
+ - `spec.md`: the markdown format.
package/bin/agile.mjs ADDED
@@ -0,0 +1,105 @@
1
+ #!/usr/bin/env node
2
+ // agile <plan.md>: serves the chart and that plan on localhost, then opens it in the browser.
3
+ // Markdown (.md) and card settings (.card.json) under the current directory are served too, so ?src= can
4
+ // switch plans; File → Save writes the plan back (PUT), and the card designer saves <plan>.card.json beside it.
5
+ // agile card <plan.md> [out-dir]: writes card.json, the plan as a dashboard card (out-dir defaults to the plan's folder).
6
+ // agile badge <plan.md> [out-dir]: writes badge.svg, drawn from the same card.
7
+ // Both read the optional sidecar <plan>.card.json. The card links to AGILE_HOST (default https://aaronp.github.io/gantt/)
8
+ // with ?src=AGILE_SRC, where the published markdown lives (default: the path given, relative to AGILE_HOST).
9
+ import { createServer } from 'node:http';
10
+ import { readFile, rename, stat, writeFile } from 'node:fs/promises';
11
+ import { spawn } from 'node:child_process';
12
+ import { dirname, join, relative, resolve, sep } from 'node:path';
13
+ import { fileURLToPath } from 'node:url';
14
+ import { badgeSvg, card, coreFrom, parsePrefs, sidecarOf } from '../card.js';
15
+
16
+ const pkg = fileURLToPath(new URL('..', import.meta.url));
17
+ const die = (msg) => { console.error(`agile: ${msg}`); process.exit(1); };
18
+ const [cmd, ...args] = process.argv.slice(2);
19
+
20
+ if (cmd === 'card' || cmd === 'badge') {
21
+ const [md, out = dirname(md ?? '')] = args;
22
+ if (!md) die(`usage: agile ${cmd} <plan.md> [out-dir]`);
23
+ let prefs = {};
24
+ try {
25
+ const r = parsePrefs(JSON.parse(await readFile(sidecarOf(md), 'utf8')));
26
+ if (r.warnings.length > 0) die(`${sidecarOf(md)}: ${r.warnings.join('; ')}`);
27
+ prefs = r.prefs;
28
+ } catch (e) {
29
+ if (e.code !== 'ENOENT') die(`${sidecarOf(md)}: ${e.message}`);
30
+ }
31
+ try {
32
+ const G = coreFrom(await readFile(join(pkg, 'index.html'), 'utf8'));
33
+ const c = card(G, await readFile(md, 'utf8'), prefs, new Date().toLocaleDateString('en-CA'), { label: md, src: process.env.AGILE_SRC || md }, process.env.AGILE_HOST || undefined);
34
+ const [name, body] = cmd === 'card' ? ['card.json', JSON.stringify(c, null, 2) + '\n'] : ['badge.svg', badgeSvg(c)];
35
+ await writeFile(join(out, name), body);
36
+ console.log(`Wrote ${join(out, name)}`);
37
+ } catch (e) {
38
+ die(`${md}: ${e.message}`);
39
+ }
40
+ process.exit(0);
41
+ }
42
+
43
+ if (!cmd || cmd === '-h' || cmd === '--help') {
44
+ console.error('Usage: agile <plan.md> (PORT=8000 picks the port, NO_OPEN=1 skips opening a browser)');
45
+ console.error(' agile card <plan.md> [out-dir] (writes card.json)');
46
+ console.error(' agile badge <plan.md> [out-dir] (writes badge.svg)');
47
+ process.exit(cmd ? 0 : 1);
48
+ }
49
+
50
+ const root = resolve('.');
51
+ const plan = resolve(cmd);
52
+ if (!plan.startsWith(root + sep)) die(`${cmd} must be inside the current directory`);
53
+ await readFile(plan).catch((e) => die(`cannot read ${cmd}: ${e.message}`));
54
+
55
+ /* The viewer's own files, from the package. Nothing else of the package is reachable. */
56
+ const VIEWER = { '/': 'index.html', '/index.html': 'index.html', '/card.html': 'card.html', '/card.js': 'card.js', '/support.js': 'support.js', '/vendor/react.js': 'vendor/react.js', '/vendor/react-dom.js': 'vendor/react-dom.js' };
57
+ const TYPES = { html: 'text/html', js: 'text/javascript', md: 'text/markdown', json: 'application/json' };
58
+ const exists = (p) => stat(p).then(() => true, () => false);
59
+ /* Data: markdown and card settings under the current directory. A .card.json can be created when its plan exists. */
60
+ const data = (abs) => abs.startsWith(root + sep) && /\.(md|card\.json)$/i.test(abs);
61
+ const writable = async (abs) => data(abs) && (/\.md$/i.test(abs) ? exists(abs) : exists(abs.replace(/\.card\.json$/i, '.md')));
62
+ // Loopback names a browser may use for this server. Anything else in Host means DNS rebinding, so it is refused.
63
+ const hosts = (port) => new Set([`127.0.0.1:${port}`, `localhost:${port}`, `[::1]:${port}`]);
64
+
65
+ const handler = async (req, res) => {
66
+ if (!hosts(server.address().port).has(req.headers.host)) return res.writeHead(403).end('Forbidden host');
67
+ const p = decodeURIComponent(new URL(req.url, 'http://x').pathname);
68
+ const viewer = VIEWER[p];
69
+ const target = viewer ? join(pkg, viewer) : resolve(root, '.' + p);
70
+ if (!viewer && !data(target)) return res.writeHead(404).end('Not found');
71
+ if (req.method === 'PUT') {
72
+ // Cross-site pages cannot get here: a PUT needs a CORS preflight, which this server never answers.
73
+ if (viewer || !(await writable(target))) return res.writeHead(403).end('Not writable');
74
+ try {
75
+ const chunks = [];
76
+ for await (const c of req) chunks.push(c);
77
+ await writeFile(`${target}.agile-tmp`, Buffer.concat(chunks));
78
+ await rename(`${target}.agile-tmp`, target); // whole file or nothing, never half-written
79
+ return res.writeHead(204).end();
80
+ } catch (e) {
81
+ return res.writeHead(500).end(e.message);
82
+ }
83
+ }
84
+ if (req.method !== 'GET' && req.method !== 'HEAD') return res.writeHead(405).end('Method not allowed');
85
+ try {
86
+ const body = await readFile(target);
87
+ const type = TYPES[target.split('.').pop()] ?? 'application/octet-stream';
88
+ // x-agile-writable tells the page it can offer File → Save (a PUT back to this URL).
89
+ res.writeHead(200, { 'content-type': `${type}; charset=utf-8`, 'cache-control': 'no-store', ...(!viewer && (await writable(target)) ? { 'x-agile-writable': '1' } : {}) }).end(body);
90
+ } catch (e) {
91
+ res.writeHead(e.code === 'ENOENT' ? 404 : 500).end(e.message);
92
+ }
93
+ };
94
+ const server = createServer(handler);
95
+
96
+ server.listen(Number(process.env.PORT ?? 0), '127.0.0.1', () => {
97
+ const { port } = server.address();
98
+ // Also answer on ::1 so http://localhost:<port> works where it resolves to IPv6; skipped if that is unavailable.
99
+ createServer(handler).on('error', () => {}).listen(port, '::1');
100
+ const url = `http://127.0.0.1:${port}/?src=${relative(root, plan).split(sep).map(encodeURIComponent).join('/')}`;
101
+ console.log(`Serving ${cmd} at ${url} (Ctrl-C to stop)`);
102
+ if (process.env.NO_OPEN) return;
103
+ const [open, argv] = process.platform === 'darwin' ? ['open', [url]] : process.platform === 'win32' ? ['cmd', ['/c', 'start', '', url]] : ['xdg-open', [url]];
104
+ spawn(open, argv, { stdio: 'ignore', detached: true }).on('error', () => {}).unref();
105
+ });
package/card.html ADDED
@@ -0,0 +1,202 @@
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>Card designer</title>
7
+ <style>
8
+ :root{--bg:#F6F5F2;--surface:#FFF;--rule:#E3E1DC;--ink:#17181A;--muted:#5E6168;--accent:#2F5BD3;--bad:#B42318;--good:#1E7A46;--warn:#B26B00;--neutral:#5E6168;color-scheme:light}
9
+ @media (prefers-color-scheme: dark){:root{--bg:#111316;--surface:#1A1D21;--rule:#2E333A;--ink:#ECEFED;--muted:#A9B0B6;--accent:#8FB0FF;--bad:#FF8A9A;--good:#5FD0B8;--warn:#F0C77A;--neutral:#A9B0B6;color-scheme:dark}}
10
+ *{box-sizing:border-box}
11
+ body{margin:0;background:var(--bg);color:var(--ink);font:14px/1.45 system-ui,-apple-system,'Segoe UI',sans-serif}
12
+ header{display:flex;align-items:center;gap:12px;flex-wrap:wrap;padding:12px 16px;border-bottom:1px solid var(--rule);background:var(--surface)}
13
+ header h1{margin:0;font-size:16px}
14
+ header .src{color:var(--muted);font-family:ui-monospace,monospace;font-size:12px;overflow-wrap:anywhere}
15
+ header a{margin-left:auto;color:var(--accent)}
16
+ main{display:grid;grid-template-columns:minmax(0,380px) minmax(0,1fr);gap:24px;padding:16px;max-width:1100px;margin:0 auto}
17
+ @media (max-width:760px){main{grid-template-columns:minmax(0,1fr)}}
18
+ fieldset{border:1px solid var(--rule);border-radius:10px;padding:12px;margin:0 0 12px;background:var(--surface)}
19
+ legend{font-weight:600;padding:0 4px}
20
+ label{display:block;font-size:12px;font-weight:600;color:var(--muted);margin:8px 0 4px}
21
+ input[type=text],select{width:100%;height:32px;padding:0 8px;border:1px solid var(--rule);border-radius:8px;background:var(--bg);color:var(--ink);font:inherit}
22
+ .row{display:grid;grid-template-columns:auto minmax(0,1fr) 36px auto auto;gap:6px;align-items:center;margin-top:6px}
23
+ .row input[type=color]{width:36px;height:32px;padding:2px;border:1px solid var(--rule);border-radius:8px;background:var(--bg)}
24
+ button{height:32px;padding:0 12px;border:1px solid var(--rule);border-radius:8px;background:var(--surface);color:var(--ink);font:inherit;cursor:pointer}
25
+ button.primary{background:var(--ink);color:var(--bg);border-color:var(--ink);font-weight:600}
26
+ button.icon{padding:0 8px}
27
+ .check{display:flex;gap:6px;align-items:center;font-size:13px;margin-top:10px;color:var(--ink);font-weight:400}
28
+ .actions{display:flex;gap:8px;flex-wrap:wrap;margin:12px 0}
29
+ .note{font-size:12px;color:var(--muted)}
30
+ .note.bad{color:var(--bad)}
31
+ h2{font-size:13px;color:var(--muted);margin:0 0 8px;text-transform:uppercase;letter-spacing:.04em}
32
+ .card{background:var(--surface);border:1px solid var(--rule);border-radius:14px;padding:18px;max-width:420px;margin-bottom:20px}
33
+ .card .top{display:flex;justify-content:space-between;gap:12px;align-items:flex-start}
34
+ .card .t{font-weight:700;font-size:16px}
35
+ .card .sub{color:var(--muted);font-size:12px}
36
+ .pill{font-size:12px;font-weight:600;padding:2px 10px;border-radius:999px;border:1px solid currentColor;white-space:nowrap}
37
+ .big{font-size:40px;font-weight:700;line-height:1;margin:16px 0 4px}
38
+ .big span{font-size:14px;font-weight:500;color:var(--muted);margin-left:6px}
39
+ .bar{display:flex;height:8px;border-radius:4px;overflow:hidden;background:var(--rule);margin:12px 0}
40
+ .items{display:flex;flex-wrap:wrap;gap:4px 14px;font-size:12px}
41
+ .items i{display:inline-block;width:8px;height:8px;border-radius:2px;margin-right:5px}
42
+ .card .foot{display:flex;justify-content:space-between;gap:8px;margin-top:14px;font-size:12px;color:var(--muted)}
43
+ .card .foot a{color:var(--accent);overflow-wrap:anywhere}
44
+ pre{background:var(--surface);border:1px solid var(--rule);border-radius:10px;padding:12px;font-size:12px;overflow:auto;max-height:320px}
45
+ </style>
46
+ </head>
47
+ <body>
48
+ <header><h1>Card designer</h1><span class="src" id="src"></span><a id="back" href="./">← Chart</a></header>
49
+ <main>
50
+ <form id="form" onsubmit="return false">
51
+ <fieldset><legend>Text</legend>
52
+ <label for="title">Title</label><input type="text" id="title">
53
+ <label for="subtitle">Subtitle</label><input type="text" id="subtitle">
54
+ <label for="source">Source label</label><input type="text" id="source">
55
+ </fieldset>
56
+ <fieldset><legend>Big number</legend>
57
+ <label for="primary">Counts</label>
58
+ <select id="primary"><option value="total">All tasks</option></select>
59
+ <label for="hlabel">Words after it</label><input type="text" id="hlabel">
60
+ </fieldset>
61
+ <fieldset><legend>Legend</legend>
62
+ <div id="legend"></div>
63
+ <label class="check"><input type="checkbox" id="hideZero"> Leave out items with no tasks</label>
64
+ </fieldset>
65
+ <div class="actions">
66
+ <button class="primary" id="save" hidden>Save</button>
67
+ <button id="download">Download</button>
68
+ <button id="copy">Copy</button>
69
+ <button id="reset">Reset to defaults</button>
70
+ </div>
71
+ <p class="note" id="note"></p>
72
+ </form>
73
+ <section>
74
+ <h2>Card preview</h2>
75
+ <div class="card" id="card"></div>
76
+ <h2>Badge</h2>
77
+ <p id="badge"></p>
78
+ <h2 id="sidecar-name">Settings</h2>
79
+ <pre id="json"></pre>
80
+ </section>
81
+ </main>
82
+ <script type="module">
83
+ import { DEFAULT_COLORS, STATUSES, badgeSvg, card, coreFrom, parsePrefs, sidecarOf } from './card.js';
84
+
85
+ const $ = (id) => document.getElementById(id);
86
+ const note = (text, bad = false) => { $('note').textContent = text; $('note').className = bad ? 'note bad' : 'note'; };
87
+ const NAMES = { done: 'Done', active: 'In progress', upcoming: 'Upcoming', late: 'Late' };
88
+ const today = new Date().toLocaleDateString('en-CA');
89
+ const src = new URLSearchParams(location.search).get('src');
90
+ const fileName = sidecarOf((src ?? 'plan.md').split('/').pop());
91
+
92
+ /* The plan: carried in #md= (deflated, base64url, as the chart's Copy link makes it), else fetched from ?src=. */
93
+ const G = coreFrom(await (await fetch('./index.html')).text());
94
+ let md = '', sidecarUrl = null, writable = false, initial = {};
95
+ try {
96
+ const packed = /^#md=([\w-]+)$/.exec(location.hash);
97
+ if (packed) {
98
+ const bytes = Uint8Array.from(atob(packed[1].replace(/-/g, '+').replace(/_/g, '/')), (c) => c.charCodeAt(0));
99
+ md = await new Response(new Blob([bytes]).stream().pipeThrough(new DecompressionStream('deflate-raw'))).text();
100
+ }
101
+ if (src) {
102
+ const url = new URL(src, location.href);
103
+ if (!packed) {
104
+ const res = await fetch(url);
105
+ if (!res.ok) throw new Error(`could not load ${src}: HTTP ${res.status}`);
106
+ md = await res.text();
107
+ writable = res.headers.get('x-agile-writable') === '1';
108
+ }
109
+ sidecarUrl = new URL(sidecarOf(url.pathname), url).href;
110
+ const res = await fetch(sidecarUrl);
111
+ if (res.ok) {
112
+ const r = parsePrefs(await res.json());
113
+ initial = r.prefs;
114
+ if (r.warnings.length) note(`Ignored in ${fileName}: ${r.warnings.join('; ')}`, true);
115
+ }
116
+ /* Saving needs the plan's own server to accept it (the `agile` CLI); an edited plan from #md= is not checked. */
117
+ if (packed) writable = (await fetch(url, { method: 'HEAD' }).catch(() => null))?.headers.get('x-agile-writable') === '1';
118
+ }
119
+ } catch (e) { note(e.message, true); }
120
+ $('src').textContent = src ?? 'unsaved plan';
121
+ $('sidecar-name').textContent = fileName;
122
+ if (src) $('back').href = './?src=' + encodeURIComponent(src).replace(/%2F/gi, '/');
123
+ $('save').hidden = !writable;
124
+ $('save').textContent = `Save ${fileName}`;
125
+ STATUSES.forEach((id) => $('primary').append(new Option(NAMES[id], id)));
126
+
127
+ /* Legend rows: every status, in order, each shown or not. */
128
+ let rows = [];
129
+ const load = (p) => {
130
+ $('title').value = p.title ?? ''; $('subtitle').value = p.subtitle ?? ''; $('source').value = p.source?.label ?? '';
131
+ $('primary').value = p.heading?.primary ?? 'total'; $('hlabel').value = p.heading?.label ?? '';
132
+ $('hideZero').checked = p.hideZero === true;
133
+ const listed = p.legend ?? STATUSES.map((id) => ({ id }));
134
+ rows = [...listed.map((l) => ({ ...l, on: true })), ...STATUSES.filter((id) => !listed.some((l) => l.id === id)).map((id) => ({ id, on: false }))];
135
+ drawRows();
136
+ };
137
+ const drawRows = () => {
138
+ $('legend').replaceChildren(...rows.map((r, i) => {
139
+ const div = document.createElement('div');
140
+ div.className = 'row';
141
+ div.innerHTML = `<input type="checkbox" aria-label="Show ${NAMES[r.id]}"><input type="text" aria-label="${NAMES[r.id]} label"><input type="color" aria-label="${NAMES[r.id]} colour"><button type="button" class="icon" aria-label="Move ${NAMES[r.id]} up">↑</button><button type="button" class="icon" aria-label="Move ${NAMES[r.id]} down">↓</button>`;
142
+ const [on, label, color, up, down] = div.children;
143
+ on.checked = r.on; label.value = r.label ?? ''; label.placeholder = NAMES[r.id]; color.value = r.color ?? DEFAULT_COLORS[r.id];
144
+ on.onchange = () => { r.on = on.checked; update(); };
145
+ label.oninput = () => { r.label = label.value || undefined; update(); };
146
+ color.oninput = () => { r.color = color.value.toUpperCase() === DEFAULT_COLORS[r.id] ? undefined : color.value.toUpperCase(); update(); };
147
+ const move = (d) => { const j = i + d; if (j < 0 || j >= rows.length) return; [rows[i], rows[j]] = [rows[j], rows[i]]; drawRows(); };
148
+ up.onclick = () => move(-1); down.onclick = () => move(1);
149
+ return div;
150
+ }));
151
+ update();
152
+ };
153
+
154
+ /* The sidecar: only what differs from the defaults. */
155
+ const prefs = () => {
156
+ const p = {};
157
+ const v = (id) => $(id).value.trim();
158
+ if (v('title')) p.title = v('title');
159
+ if (v('subtitle')) p.subtitle = v('subtitle');
160
+ if ($('primary').value !== 'total' || v('hlabel')) p.heading = { ...($('primary').value !== 'total' ? { primary: $('primary').value } : {}), ...(v('hlabel') ? { label: v('hlabel') } : {}) };
161
+ const legend = rows.filter((r) => r.on).map(({ id, label, color }) => ({ id, ...(label ? { label } : {}), ...(color ? { color } : {}) }));
162
+ if (legend.length !== STATUSES.length || legend.some((l, i) => l.id !== STATUSES[i] || l.label || l.color)) p.legend = legend;
163
+ if ($('hideZero').checked) p.hideZero = true;
164
+ if (v('source')) p.source = { label: v('source') };
165
+ return p;
166
+ };
167
+ const esc = (s) => String(s).replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c]);
168
+ let text = '';
169
+ const update = () => {
170
+ const p = prefs();
171
+ text = JSON.stringify(p, null, 2) + '\n';
172
+ $('json').textContent = text;
173
+ let c;
174
+ try { c = card(G, md, p, today, { label: src ?? 'plan.md', src: src ?? 'plan.md' }, new URL('./', location.href).href); } catch (e) { $('card').textContent = `Can’t read the plan: ${e.message}`; return; }
175
+ const total = Object.values(c.report).reduce((a, b) => a + b, 0) || 1;
176
+ $('card').innerHTML = `<div class="top"><div><div class="t">${esc(c.title)}</div><div class="sub">${esc(c.subtitle)}</div></div><span class="pill" style="color:var(--${c.status.tone})">${esc(c.status.label)}</span></div>`
177
+ + `<div class="big">${esc(c.heading.primary)}<span>${esc(c.heading.label)}</span></div>`
178
+ + `<div class="bar">${c.legend.map((l) => `<span style="width:${(100 * c.report[l.id]) / total}%;background:${esc(l.color)}"></span>`).join('')}</div>`
179
+ + `<div class="items">${c.legend.map((l) => `<span><i style="background:${esc(l.color)}"></i>${esc(l.label)} <b>${c.report[l.id]}</b></span>`).join('')}</div>`
180
+ + `<div class="foot"><a href="${esc(c.source.url)}">${esc(c.source.label)}</a><span>Updated ${esc(c.updated)}</span></div>`;
181
+ $('badge').innerHTML = `<img alt="" src="data:image/svg+xml;charset=utf-8,${encodeURIComponent(badgeSvg(c))}">`;
182
+ };
183
+
184
+ $('form').addEventListener('input', update);
185
+ $('form').addEventListener('change', update);
186
+ $('reset').onclick = () => { load({}); note('Back to the defaults (not saved yet).'); };
187
+ $('download').onclick = () => {
188
+ const a = document.createElement('a');
189
+ a.href = URL.createObjectURL(new Blob([text], { type: 'application/json' }));
190
+ a.download = fileName;
191
+ a.click();
192
+ setTimeout(() => URL.revokeObjectURL(a.href), 0);
193
+ note(`Downloaded ${fileName}: put it beside the plan, then run agile card / agile badge.`);
194
+ };
195
+ $('copy').onclick = () => navigator.clipboard.writeText(text).then(() => note('Copied.'), (e) => note(`Couldn’t copy: ${e.message}`, true));
196
+ $('save').onclick = () => fetch(sidecarUrl, { method: 'PUT', body: text, headers: { 'content-type': 'application/json' } })
197
+ .then((res) => { if (!res.ok) throw new Error('HTTP ' + res.status); note(`Saved ${fileName}.`); })
198
+ .catch((e) => note(`Couldn’t save ${fileName}: ${e.message}`, true));
199
+ load(initial);
200
+ </script>
201
+ </body>
202
+ </html>
package/card.js ADDED
@@ -0,0 +1,129 @@
1
+ /**
2
+ * A dashboard card for a plan, as data (card.json), and a status badge drawn from it (badge.svg).
3
+ * Shared by the `agile` CLI (Node) and the card designer (card.html). No DOM, no clock: "today" is passed in.
4
+ *
5
+ * card.json (version 1) is tool-neutral: title, subtitle, a status pill, one big number, a legend with a
6
+ * count per item, and a source link. What it says comes from an optional sidecar, <plan>.card.json.
7
+ */
8
+
9
+ /** Where the card's link opens the plan. The CLI takes AGILE_HOST from the environment to point elsewhere. */
10
+ export const AGILE_HOST = 'https://aaronp.github.io/gantt/';
11
+ export const STATUSES = ['done', 'active', 'upcoming', 'late'];
12
+ export const DEFAULT_COLORS = { done: '#1E7A46', active: '#2F5BD3', upcoming: '#6B7280', late: '#B42318' };
13
+ const DEFAULT_LABELS = { done: 'Done', active: 'In progress', upcoming: 'Upcoming', late: 'Late' };
14
+
15
+ /** ROADMAP.md → ROADMAP.card.json */
16
+ export const sidecarOf = (md) => md.replace(/\.md$/i, '') + '.card.json';
17
+
18
+ /**
19
+ * The page's parser/scheduler (`G`), cut out of index.html so the CLI and designer read plans exactly as the chart does.
20
+ * ponytail: relies on G being the first `})();` in the x-dc script; move G into its own file if that ever stops holding.
21
+ */
22
+ export const coreFrom = (html) => {
23
+ const m = /<script type="text\/x-dc" data-dc-script>\n([\s\S]*?\n\}\)\(\);)\n/.exec(html);
24
+ if (!m || !m[1].includes('const G = (() => {')) throw new Error('could not find the plan parser (G) in index.html');
25
+ return new Function(m[1] + '\nreturn G;')();
26
+ };
27
+
28
+ /** Where a task stands on `today` (a day number). Tasks without a checkbox can't be ticked, so once past they count as done. */
29
+ export const statusOf = (t, s, today) => {
30
+ const last = Math.max(s.end, s.start + 1); /* a milestone occupies its day */
31
+ if (t.done || (!t.box && last <= today)) return 'done';
32
+ return last <= today ? 'late' : s.start <= today ? 'active' : 'upcoming';
33
+ };
34
+
35
+ const KEYS = ['title', 'subtitle', 'heading', 'legend', 'hideZero', 'source'];
36
+ const fail = (msg) => { throw new Error(`card settings: ${msg}`); };
37
+ const isObj = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
38
+ const str = (v, where) => { if (v !== undefined && typeof v !== 'string') fail(`${where} must be a string`); };
39
+
40
+ /** Checks a parsed sidecar. Unknown legend ids are dropped with a warning; anything else wrong throws. */
41
+ export const parsePrefs = (json) => {
42
+ if (!isObj(json)) fail('expected an object');
43
+ const warnings = [];
44
+ Object.keys(json).forEach((k) => { if (!KEYS.includes(k)) fail(`unknown field "${k}" (expected ${KEYS.join(', ')})`); });
45
+ str(json.title, 'title'); str(json.subtitle, 'subtitle');
46
+ if (json.hideZero !== undefined && typeof json.hideZero !== 'boolean') fail('hideZero must be true or false');
47
+ if (json.heading !== undefined) {
48
+ if (!isObj(json.heading)) fail('heading must be an object');
49
+ const p = json.heading.primary;
50
+ if (p !== undefined && p !== 'total' && !STATUSES.includes(p)) fail(`heading.primary must be "total" or one of ${STATUSES.join(', ')}`);
51
+ str(json.heading.label, 'heading.label');
52
+ }
53
+ if (json.source !== undefined) { if (!isObj(json.source)) fail('source must be an object'); str(json.source.label, 'source.label'); }
54
+ let legend;
55
+ if (json.legend !== undefined) {
56
+ if (!Array.isArray(json.legend)) fail('legend must be a list');
57
+ legend = json.legend.filter((l, i) => {
58
+ if (!isObj(l)) fail(`legend[${i}] must be an object`);
59
+ str(l.label, `legend[${i}].label`); str(l.color, `legend[${i}].color`);
60
+ if (STATUSES.includes(l.id)) return true;
61
+ warnings.push(`unknown legend id "${l.id}" (expected one of ${STATUSES.join(', ')})`);
62
+ return false;
63
+ });
64
+ }
65
+ return { prefs: { ...json, ...(legend ? { legend } : {}) }, warnings };
66
+ };
67
+
68
+ /**
69
+ * The card for a plan. `G` comes from coreFrom; `today` is YYYY-MM-DD; `at.label` is the default source label
70
+ * (the markdown path) and `at.src` where the viewer can fetch the markdown (?src=), a URL or a path relative to `host`.
71
+ */
72
+ export const card = (G, md, prefs, today, at, host = AGILE_HOST) => {
73
+ const doc = G.parse(md);
74
+ const sched = G.schedule(doc);
75
+ const tasks = G.tasksOf(doc);
76
+ const day = G.dayFromIso(today);
77
+ const status = tasks.map((t) => statusOf(t, sched.get(t.id), day));
78
+ const count = (id) => status.filter((x) => x === id).length;
79
+ const conflicts = tasks.filter((t) => sched.get(t.id).conflict).length;
80
+ const items = prefs.legend ?? STATUSES.map((id) => ({ id }));
81
+ const legend = items.filter((l) => !prefs.hideZero || count(l.id) > 0)
82
+ .map((l) => ({ id: l.id, label: l.label ?? DEFAULT_LABELS[l.id], color: l.color ?? DEFAULT_COLORS[l.id] }));
83
+ const spans = [...sched.values()];
84
+ const span = spans.length === 0 ? '' : `${G.isoFromDay(Math.min(...spans.map((s) => s.start)))} → ${G.isoFromDay(Math.max(...spans.map((s) => s.end)))}`;
85
+ const primary = prefs.heading?.primary ?? 'total';
86
+ const late = count('late');
87
+ const title = doc.items.find((i) => i.kind === 'title');
88
+ return {
89
+ version: 1,
90
+ title: prefs.title ?? title?.text ?? 'Plan',
91
+ subtitle: prefs.subtitle ?? span,
92
+ status: conflicts > 0 ? { label: `${conflicts} conflict${conflicts === 1 ? '' : 's'}`, tone: 'bad' }
93
+ : late > 0 ? { label: `${late} late`, tone: 'warn' }
94
+ : { label: 'On track', tone: 'good' },
95
+ heading: { primary: String(primary === 'total' ? tasks.length : count(primary)), label: prefs.heading?.label ?? 'tasks' },
96
+ legend,
97
+ report: Object.fromEntries(legend.map((l) => [l.id, count(l.id)])),
98
+ source: { label: prefs.source?.label ?? at.label, url: `${host}?src=${encodeURIComponent(at.src).replace(/%2F/gi, '/').replace(/%3A/gi, ':')}` },
99
+ updated: today,
100
+ };
101
+ };
102
+
103
+ /* Width estimate for 11px Verdana, as shields.io badges use: ~7px a character, emoji a little wider. */
104
+ const width = (t) => [...t].reduce((w, ch) => w + (/\p{Extended_Pictographic}/u.test(ch) ? 14 : 7), 0) + 12;
105
+ const esc = (s) => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
106
+
107
+ /** A shields-style badge: a grey title segment, then "<label> <n>" per legend item with a non-zero count, on its colour. */
108
+ export const badgeSvg = (c) => {
109
+ const items = c.legend.map((l) => ({ ...l, n: c.report[l.id] ?? 0 })).filter((l) => l.n > 0);
110
+ const parts = [{ text: c.title, bg: '#555' }, ...items.map((l) => ({ text: `${l.label} ${l.n}`, bg: l.color ?? '#6B7280' }))];
111
+ let x = 0;
112
+ const segs = parts.map((p) => {
113
+ const w = width(p.text);
114
+ const seg = `<rect x="${x}" width="${w}" height="20" fill="${esc(p.bg)}"/><text x="${x + w / 2}" y="14" fill="#fff">${esc(p.text)}</text>`;
115
+ x += w;
116
+ return seg;
117
+ });
118
+ const label = esc(`${c.title}: ${items.length === 0 ? 'no tasks' : items.map((l) => `${l.n} ${l.label.toLowerCase()}`).join(', ')}`);
119
+ return [
120
+ `<svg xmlns="http://www.w3.org/2000/svg" width="${x}" height="20" role="img" aria-label="${label}">`,
121
+ `<title>${label}</title>`,
122
+ `<clipPath id="r"><rect width="${x}" height="20" rx="3"/></clipPath>`,
123
+ `<g clip-path="url(#r)" font-family="Verdana,DejaVu Sans,sans-serif" font-size="11" text-anchor="middle">`,
124
+ ...segs,
125
+ '</g>',
126
+ '</svg>',
127
+ '',
128
+ ].join('\n');
129
+ };