@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/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
+ };