@pritzlaff/agile 1.0.0 → 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,103 +1,179 @@
1
- # Agile board
2
-
3
- **[▶ Open the board](https://aaronp.github.io/agile/)** ·
4
- [Acme example](https://aaronp.github.io/agile/?src=examples/acme-sprint/board.md)
5
-
6
- A kanban board driven by **one markdown file**: columns, tasks, their owners, tags, history and the board's
7
- style. This repo is the app. Your board can live in its own repo and be loaded with `?src=` (see
8
- [Publishing your own board](#publishing-your-own-board)).
9
-
10
- - **Board**, **Split** (board beside its markdown), **Archive** and **Markdown** views.
11
- - The **☰ menu** holds **New**, **Open**, **Save**, **Download**, **Copy link** and **Style**.
12
- - **Copy link** copies a URL with the whole board compressed into it (`#board=…`, deflate + base64url), plus the current view and filters. Opening it shows that board without overwriting the one saved in that browser, and edits to it update the `#board=` in the address bar; it lives in the hash, so it never reaches the server. Links over 2000 characters copy with a warning, since some apps cut them.
13
- - **Badge and card**: the top of the ☰ menu shows an SVG badge of task counts, like `B: 4 📋 | P: 2 ⏳ | D: 7 ✅`. Click it to choose which columns it shows, each with a symbol (up to 6 characters), an icon and a color (saved in the file as `badge:` in the front matter), and to download or copy the badge and `card.json`. `card.json` is the board as data for a dashboard: title, a status pill (`3 open` or `All done`), done/total, and a count per badge column in the badge's colors; the dialog previews it. In CI, `agile badge` and `agile card` write the same files (see [Using it in a project](#using-it-in-a-project)).
14
- - **New** starts a blank board (To Do, Doing, Done) in the current style, after asking, since it replaces the board saved in this browser.
15
- - **Child tasks**: the **+** on a card (on hover) or **Create child task** in the task panel adds a task under it, nested as deep as you like. Children sit indented beneath their parent with a connecting line; one moved to another column shows "↳ parent", and leaves a dotted stand-in under the parent that jumps to it. The chevron on a parent folds its children away. Saved as `- parent: t-03`.
16
- - **History** (the clock beside Undo / Redo): a time slider with a step for every move in the tasks' history, archived ones included. It shows the board, archive and markdown as they stood then, read-only; **Now** returns to the live board. It's replayed from each task's `history:`, so deleted tasks don't appear, columns since renamed come back under their old names, and titles, tags and descriptions are today's.
17
- - **Undo / Redo** (↶ ↷, or Ctrl/⌘ Z and Ctrl/⌘ Shift Z / Ctrl Y) step back through every change, up to 100. Typing in one field counts as one step; opening a board or starting a new one clears the history.
18
- - **Open**: drop a `.md` file, choose one, open one from a URL (GitHub file links work) or pick a recent one.
19
- - **Save** (Ctrl/⌘ S) writes a board served by `make dev` or the `agile` command back to its file. Otherwise
20
- it writes to a file you pick once, then to the same file each time; browsers without a file picker
21
- (Firefox, Safari) download it instead. **Download** always downloads `<title>.md`.
22
- - Nine styles (Minimal, Paper, Terminal, Ocean, Ball pit, plus Graph paper, Night shift, Blueprint and Warm ledger from [Decision Ledger](https://aaronp.github.io/adr/)), with their settings stored in the file.
23
-
24
- Edits are saved in this browser (localStorage), except for a board opened from a URL. **The `.md` file is the
25
- real copy**, so keep it in git.
26
-
27
- | Query | Shows |
28
- | --- | --- |
29
- | _(none)_ | The board saved in this browser, or the sample |
30
- | `?src=<url>` | That markdown file (absolute, or relative to the page). It isn't saved in the browser, so it never overwrites your board. |
31
- | `?view=` | `board` (default), `split`, `archive` or `markdown` |
32
- | `?q=` `?tags=a,b` `?owners=a,b` | Search text and filters |
33
- | `?task=<id>` | Opens that task, e.g. `?task=t-07` |
34
- | `?theme=` | `minimal`, `paper`, `terminal`, `ocean`, `ballpit`, `graph`, `night`, `blueprint` or `ledger`, without changing the file. Picking a style saves it in the file. |
1
+ # Gantt
2
+
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)).
35
14
 
36
- The address bar follows the app, so any view can be bookmarked or shared. Files on another host must allow
37
- CORS (GitHub Pages and raw.githubusercontent.com both do).
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.
38
63
 
39
64
  ## Viewing locally
40
65
 
41
66
  ```sh
42
- make dev # serves the repo on http://localhost:8000/ and prints the example's URL
67
+ make dev # serves on http://localhost:8000/ and prints the example's URL
43
68
  ```
44
69
 
45
- Save writes the `?src=` file back to disk (any existing `.md` in the repo). The server only listens on loopback.
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.
46
73
 
47
- ## Using it in a project
74
+ ## The `agile` CLI
75
+
76
+ ```sh
77
+ bunx @pritzlaff/agile ROADMAP.md # or npx; no install needed
78
+ ```
48
79
 
49
- The app is published to npm as [`@pritzlaff/agile`](https://www.npmjs.com/package/@pritzlaff/agile):
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
50
86
 
51
87
  ```sh
52
- bunx @pritzlaff/agile board.md # serves the board on localhost and opens it; Save writes board.md
53
- bunx @pritzlaff/agile badge board.md # writes badge.svg beside it (or: badge board.md out-dir)
54
- bunx @pritzlaff/agile card board.md # writes card.json
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
55
90
  ```
56
91
 
57
- The card links to `AGILE_HOST` (default `https://aaronp.github.io/agile/`) with `?src=AGILE_SRC` (default:
58
- the path given). [`examples/bun-app`](examples/bun-app) keeps its board beside the code, with a
59
- `make snapshot` target and a Pages workflow that publishes the board, badge and card.
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
+ ```
60
109
 
61
- ## Hosting
110
+ ### Adding it to your Bun project
62
111
 
63
- `.github/workflows/pages.yml` runs the tests on pushes to `main` or `master`, then publishes the app as
64
- `index.html` with `examples/` beside it. Set Settings → Pages → Source: **GitHub Actions**; the
65
- `github-pages` environment must allow your branch. `.md` files are served raw, without Jekyll.
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
+ ```
66
118
 
67
- ## Publishing your own board
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.
68
121
 
69
- Your board lives in its own data-only repo (`board.md`, a redirecting `index.html` and a Pages workflow),
70
- and this repo stays the app. Create an empty repo on GitHub, then:
122
+ ### Releasing
71
123
 
72
124
  ```sh
73
- git clone https://github.com/aaronp/agile.git
74
- cd agile/examples/acme-sprint
75
- make clone REPO=you/your-board # or ./clone.sh to be prompted
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
76
128
  ```
77
129
 
78
- This copies the example to `../your-board` as a fresh repo on `main`, points its README link at
79
- `https://you.github.io/your-board/` and sets the `origin` remote. Edit `board.md`, commit and
80
- `git push -u origin main`, then set Settings → Pages → Source: **GitHub Actions**.
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.
81
136
 
82
- ## Development
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**
83
144
 
84
145
  ```sh
85
- make test # bun test: the format, the address bar, opening, recents, saving, the card and the CLI
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
86
149
  ```
87
150
 
88
- Releasing to npm (needs a clean tree and `npm login`):
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**
89
155
 
90
156
  ```sh
91
- make bump-patch # or bump-minor / bump-major: bumps package.json, commits and tags v<version>
92
- make publish # tests, then npm publish
93
- git push --follow-tags
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
94
160
  ```
95
161
 
96
- | Path | What |
97
- | --- | --- |
98
- | `Main.dc.html` | The app: an `<x-dc>` template plus its logic (schema, markdown parser and serializer, board operations, themes, effects) |
99
- | `support.js`, `vendor/` | The runtime that renders the template in a browser |
100
- | `bin/agile.mjs` | The `agile` command: a local server with write-back, and `badge` / `card` (loads the logic from `Main.dc.html`) |
101
- | `examples/acme-sprint/` | A cloneable data-only repo that points back at this app |
102
- | `examples/bun-app/` | A Bun project using the published package for its own board |
103
- | `app.test.ts` | Runs the logic with the browser stubbed out |
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 CHANGED
@@ -1,74 +1,81 @@
1
1
  #!/usr/bin/env node
2
- // agile <board.md | dir>: serves the app on localhost with the board's folder beside it, then opens the board.
3
- // Files are re-read on every request; Save (Ctrl/⌘ S) writes an existing .md in that folder back (PUT).
4
- // agile card <board.md> [out-dir]: writes card.json, the board as a dashboard card (out-dir defaults to the file's folder).
5
- // agile badge <board.md> [out-dir]: writes badge.svg. Both follow the badge settings in the board's front matter.
6
- // The card links to the app at AGILE_HOST (default https://aaronp.github.io/agile/) with ?src=AGILE_SRC,
7
- // where AGILE_SRC is where the published board lives (default: the path given, relative to AGILE_HOST).
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).
8
9
  import { createServer } from 'node:http';
9
10
  import { readFile, rename, stat, writeFile } from 'node:fs/promises';
10
11
  import { spawn } from 'node:child_process';
11
- import { basename, dirname, extname, join, resolve, sep } from 'node:path';
12
+ import { dirname, join, relative, resolve, sep } from 'node:path';
12
13
  import { fileURLToPath } from 'node:url';
14
+ import { badgeSvg, card, coreFrom, parsePrefs, sidecarOf } from '../card.js';
13
15
 
14
- const app = fileURLToPath(new URL('..', import.meta.url));
15
-
16
- /** The board logic, straight from the app page (it only needs a component base class to load). */
17
- async function logic() {
18
- const html = await readFile(join(app, 'Main.dc.html'), 'utf8');
19
- const js = html.split('<script type="text/x-dc" data-dc-script')[1].split('>').slice(1).join('>').split('</script>')[0];
20
- return new Function('DCLogic', `${js}\nreturn { parseBoard, badgeSvg, boardCard, boardLink, AGILE_HOST };`)(class {});
21
- }
22
-
16
+ const pkg = fileURLToPath(new URL('..', import.meta.url));
17
+ const die = (msg) => { console.error(`agile: ${msg}`); process.exit(1); };
23
18
  const [cmd, ...args] = process.argv.slice(2);
19
+
24
20
  if (cmd === 'card' || cmd === 'badge') {
25
21
  const [md, out = dirname(md ?? '')] = args;
26
- if (!md) { console.error(`Usage: agile ${cmd} <board.md> [out-dir]`); process.exit(1); }
22
+ if (!md) die(`usage: agile ${cmd} <plan.md> [out-dir]`);
23
+ let prefs = {};
27
24
  try {
28
- const { parseBoard, badgeSvg, boardCard, boardLink, AGILE_HOST } = await logic();
29
- const board = parseBoard(await readFile(md, 'utf8'));
30
- const today = new Date().toLocaleDateString('en-CA');
31
- const card = boardCard(board, today, { label: md, url: boardLink(process.env.AGILE_HOST || AGILE_HOST, process.env.AGILE_SRC || md) });
32
- const [name, body] = cmd === 'card' ? ['card.json', JSON.stringify(card, null, 2) + '\n'] : ['badge.svg', badgeSvg(board) + '\n'];
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)];
33
35
  await writeFile(join(out, name), body);
34
36
  console.log(`Wrote ${join(out, name)}`);
35
- process.exit(0);
36
37
  } catch (e) {
37
- console.error(`agile: ${md}: ${e.message}`);
38
- process.exit(1);
38
+ die(`${md}: ${e.message}`);
39
39
  }
40
+ process.exit(0);
40
41
  }
41
42
 
42
43
  if (!cmd || cmd === '-h' || cmd === '--help') {
43
- console.error('Usage: agile <board.md | dir> (PORT=8000 to pick the port, NO_OPEN=1 to skip opening a browser)');
44
- console.error(' agile card <board.md> [out-dir] (writes card.json)');
45
- console.error(' agile badge <board.md> [out-dir] (writes badge.svg)');
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)');
46
47
  process.exit(cmd ? 0 : 1);
47
48
  }
48
- const target = resolve(cmd);
49
- const isDir = await stat(target).then((s) => s.isDirectory(), (e) => { console.error(`agile: cannot read ${cmd}: ${e.message}`); process.exit(1); });
50
- const root = isDir ? target : dirname(target);
51
- const APP_FILES = new Set(['/support.js', '/vendor/react.js', '/vendor/react-dom.js']);
52
- const TYPES = { '.html': 'text/html', '.js': 'text/javascript', '.md': 'text/markdown', '.json': 'application/json', '.svg': 'image/svg+xml', '.css': 'text/css' };
53
- /** An existing markdown file inside the served folder: the only thing a PUT may overwrite. */
54
- const writable = (abs) => abs.startsWith(root + sep) && /\.md$/i.test(abs);
55
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')));
56
62
  // Loopback names a browser may use for this server. Anything else in Host means DNS rebinding, so it is refused.
57
63
  const hosts = (port) => new Set([`127.0.0.1:${port}`, `localhost:${port}`, `[::1]:${port}`]);
64
+
58
65
  const handler = async (req, res) => {
59
66
  if (!hosts(server.address().port).has(req.headers.host)) return res.writeHead(403).end('Forbidden host');
60
67
  const p = decodeURIComponent(new URL(req.url, 'http://x').pathname);
61
- const file = p === '/' ? join(app, 'Main.dc.html') : APP_FILES.has(p) ? join(app, p) : resolve(root, '.' + (p.endsWith('/') ? p + 'index.html' : p));
62
- if (file !== join(app, 'Main.dc.html') && !APP_FILES.has(p) && !file.startsWith(root + sep)) return res.writeHead(404).end('Not found');
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');
63
71
  if (req.method === 'PUT') {
64
72
  // Cross-site pages cannot get here: a PUT needs a CORS preflight, which this server never answers.
65
- if (!writable(file) || !(await stat(file).then((s) => s.isFile(), () => false))) return res.writeHead(403).end('Not writable');
73
+ if (viewer || !(await writable(target))) return res.writeHead(403).end('Not writable');
66
74
  try {
67
75
  const chunks = [];
68
76
  for await (const c of req) chunks.push(c);
69
- const tmp = `${file}.agile-tmp`;
70
- await writeFile(tmp, Buffer.concat(chunks));
71
- await rename(tmp, file); // whole file or nothing, never half-written
77
+ await writeFile(`${target}.agile-tmp`, Buffer.concat(chunks));
78
+ await rename(`${target}.agile-tmp`, target); // whole file or nothing, never half-written
72
79
  return res.writeHead(204).end();
73
80
  } catch (e) {
74
81
  return res.writeHead(500).end(e.message);
@@ -76,21 +83,21 @@ const handler = async (req, res) => {
76
83
  }
77
84
  if (req.method !== 'GET' && req.method !== 'HEAD') return res.writeHead(405).end('Method not allowed');
78
85
  try {
79
- const body = await readFile(file);
80
- const type = TYPES[extname(file).toLowerCase()] ?? 'application/octet-stream';
81
- // x-agile-writable tells the app that Save can PUT the board back to this URL.
82
- res.writeHead(200, { 'content-type': `${type}; charset=utf-8`, 'cache-control': 'no-store', ...(writable(file) ? { 'x-agile-writable': '1' } : {}) }).end(body);
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);
83
90
  } catch (e) {
84
- res.writeHead(e.code === 'ENOENT' || e.code === 'EISDIR' ? 404 : 500).end(e.code === 'ENOENT' ? 'Not found' : e.message);
91
+ res.writeHead(e.code === 'ENOENT' ? 404 : 500).end(e.message);
85
92
  }
86
93
  };
87
94
  const server = createServer(handler);
88
95
 
89
96
  server.listen(Number(process.env.PORT ?? 0), '127.0.0.1', () => {
90
97
  const { port } = server.address();
91
- // Also answer on ::1 so http://localhost:<port> works; skipped if IPv6 loopback is unavailable.
98
+ // Also answer on ::1 so http://localhost:<port> works where it resolves to IPv6; skipped if that is unavailable.
92
99
  createServer(handler).on('error', () => {}).listen(port, '::1');
93
- const url = `http://localhost:${port}/` + (isDir ? '' : `?src=${encodeURIComponent(basename(target))}`);
100
+ const url = `http://127.0.0.1:${port}/?src=${relative(root, plan).split(sep).map(encodeURIComponent).join('/')}`;
94
101
  console.log(`Serving ${cmd} at ${url} (Ctrl-C to stop)`);
95
102
  if (process.env.NO_OPEN) return;
96
103
  const [open, argv] = process.platform === 'darwin' ? ['open', [url]] : process.platform === 'win32' ? ['cmd', ['/c', 'start', '', url]] : ['xdg-open', [url]];
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>