@n1kname/components 0.18.0 → 0.20.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.
@@ -0,0 +1,268 @@
1
+ // Fills a YearCalendar: one year of days in a grid, a week to a column and a weekday to a row, each
2
+ // day coloured by its step. HTML, not a chart library, because a day is a square of colour and
3
+ // nothing else, and the squares share the width they have, so the year fits a phone.
4
+ //
5
+ // import { setYearCalendar } from '@n1kname/components/yearcalendar.js';
6
+ // setYearCalendar(box, { year: 2026, days: { '2026-03-02': 2, '2026-03-04': 1 }, format: (n) => `${n} runs` });
7
+ //
8
+ // `days` maps an ISO date to a number, or to anything when `value` reads the number from it. A day
9
+ // with no entry, or a value of 0, is empty: grey, never the lowest colour. Colours are a ramp, low
10
+ // to high: the heat tokens by default, any list in `colors`, or one `tone` in `levels` strengths.
11
+ // `steps` says where each colour after the first starts, as for the heatmap chart; by default the
12
+ // days' values are split into even shares.
13
+ //
14
+ // Pointing at a day, or reaching it with the arrow keys, shows the charts' pointer card: the date,
15
+ // the day's figure and any `extra`. The grid is one tab stop: right and left go a week on, up and
16
+ // down a day, Page Up and Page Down a month, Home and End to the first and last day. Each step is
17
+ // said in a polite live region. A table by month, for screen readers, says how many days had
18
+ // something and, with `total`, how much.
19
+ //
20
+ // calendarHTML() is the markup alone, without the browser: YearCalendar uses it to draw the empty
21
+ // year at build time, so nothing moves when the days arrive.
22
+
23
+ // Text and attributes alike, so a label with quotes stays one attribute.
24
+ const esc = (s) => String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
25
+
26
+ const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
27
+ const LONG_MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
28
+
29
+ /** The heat ramp, cold to warm, as tokens. */
30
+ export const HEAT = [1, 2, 3, 4, 5, 6].map((i) => `var(--c-heat-${i})`);
31
+ /** At most this many colours: the stylesheet has a rule for each. */
32
+ export const MAX_COLOURS = 9;
33
+
34
+ const iso = (t) => new Date(t).toISOString().slice(0, 10);
35
+ const utc = (s) => Date.UTC(Number(s.slice(0, 4)), Number(s.slice(5, 7)) - 1, Number(s.slice(8, 10)));
36
+ const DAY = 86_400_000;
37
+ const localToday = () => {
38
+ const d = new Date();
39
+ return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
40
+ };
41
+
42
+ /**
43
+ * The year's weeks, each a column of seven ISO dates from the week's first day (Monday by default,
44
+ * Sunday with weekStart 0), from the week holding 1 January to the week holding 31 December.
45
+ */
46
+ export const yearWeeks = (year, weekStart = 1) => {
47
+ const jan1 = Date.UTC(year, 0, 1);
48
+ const dec31 = Date.UTC(year, 11, 31);
49
+ let t = jan1 - ((new Date(jan1).getUTCDay() - weekStart + 7) % 7) * DAY;
50
+ const weeks = [];
51
+ while (t <= dec31) {
52
+ weeks.push(Array.from({ length: 7 }, (_, i) => iso(t + i * DAY)));
53
+ t += 7 * DAY;
54
+ }
55
+ return weeks;
56
+ };
57
+
58
+ /** A ramp of one colour: `levels` strengths of `tone` mixed into the surface, the last the tone itself. */
59
+ export const toneRamp = (tone, levels = 4) =>
60
+ Array.from({ length: levels }, (_, i) => {
61
+ const p = levels === 1 ? 100 : Math.round(35 + (65 * i) / (levels - 1));
62
+ return p === 100 ? tone : `color-mix(in oklab, ${tone} ${p}%, var(--c-surface))`;
63
+ });
64
+
65
+ /**
66
+ * Where each colour after the first starts, when none are given: the values above zero split into
67
+ * even shares, so every colour is used when the values allow it. One fewer than the colours.
68
+ */
69
+ export const evenSteps = (values, colours) => {
70
+ const sorted = values.filter((v) => v > 0).sort((a, b) => a - b);
71
+ if (!sorted.length || colours < 2) return [];
72
+ return Array.from({ length: colours - 1 }, (_, k) => sorted[Math.floor(((k + 1) * sorted.length) / colours)] ?? sorted.at(-1));
73
+ };
74
+
75
+ /** The step of a value: 0 for nothing, 1 for the first colour, up to the number of colours. */
76
+ export const stepOf = (v, steps) => (v > 0 ? 1 + steps.filter((s) => v >= s).length : 0);
77
+
78
+ const options = (o) => {
79
+ const { year, days = {}, value = (d) => (typeof d === 'number' ? d : (d?.value ?? 0)), weekStart = 1, tone, levels = 4 } = o;
80
+ const colors = o.colors ?? (tone ? toneRamp(tone, levels) : HEAT);
81
+ if (colors.length > MAX_COLOURS) throw new Error(`YearCalendar: at most ${MAX_COLOURS} colours, not ${colors.length}`);
82
+ const inYear = Object.entries(days).filter(([d]) => d.startsWith(`${year}-`));
83
+ const steps = o.steps ?? evenSteps(inYear.map(([, d]) => value(d)), colors.length);
84
+ return { ...o, year, days, value, weekStart, colors, steps };
85
+ };
86
+
87
+ /**
88
+ * The calendar's markup, as a string: what setYearCalendar draws, without the browser. Takes the
89
+ * same options; `today` is left out unless given, so a build draws no day as still to come.
90
+ */
91
+ export const calendarHTML = (opts) => {
92
+ const { year, days, value, weekStart, colors, steps, today, label, total, months = MONTHS, monthNames = LONG_MONTHS, weekdays, words = {} } = options(opts);
93
+ const say = { month: 'Month', days: 'Days', total: 'Total', ...words };
94
+ const weeks = yearWeeks(year, weekStart);
95
+ const letters = weekdays ?? (weekStart === 1 ? ['M', '', 'W', '', 'F', '', ''] : ['', 'M', '', 'W', '', 'F', '']);
96
+ const prefix = `${year}-`;
97
+
98
+ // A month's name over the week holding its first day.
99
+ const first = weeks[0][0];
100
+ const heads = months
101
+ .map((m, i) => {
102
+ const at = Math.floor((utc(`${year}-${String(i + 1).padStart(2, '0')}-01`) - utc(first)) / DAY / 7);
103
+ return `<span style="--at: ${((at / weeks.length) * 100).toFixed(3)}%" data-short="${esc(m.slice(0, 1))}">${esc(m)}</span>`;
104
+ })
105
+ .join('');
106
+
107
+ let active = 0;
108
+ const byMonth = Array.from({ length: 12 }, () => ({ days: 0, sum: 0 }));
109
+ const cells = weeks
110
+ .flat()
111
+ .map((d) => {
112
+ if (!d.startsWith(prefix)) return '<i class="out"></i>';
113
+ const entry = days[d];
114
+ const v = entry === undefined ? 0 : Number(value(entry)) || 0;
115
+ const step = stepOf(v, steps);
116
+ if (step) {
117
+ active++;
118
+ const m = byMonth[Number(d.slice(5, 7)) - 1];
119
+ m.days++;
120
+ m.sum += v;
121
+ }
122
+ const cls = step ? 'on' : today && d > today ? 'later' : 'off';
123
+ return `<i class="${cls}" data-day="${d}"${step ? ` data-step="${step}"` : ''}></i>`;
124
+ })
125
+ .join('');
126
+
127
+ const named = label ?? `${year}: ${active} day${active === 1 ? '' : 's'} with something`;
128
+ const ramp = colors.map((c, i) => `--yc-${i + 1}: ${c}`).join('; ');
129
+ const table =
130
+ opts.table === false
131
+ ? ''
132
+ : `<table class="yc-sr"><caption>${esc(named)}</caption><thead><tr><th scope="col">${esc(say.month)}</th><th scope="col">${esc(say.days)}</th>${total ? `<th scope="col">${esc(say.total)}</th>` : ''}</tr></thead><tbody>${byMonth
133
+ .map((m, i) => `<tr><th scope="row">${esc(monthNames[i])}</th><td>${m.days}</td>${total ? `<td>${esc(total(m.sum, i))}</td>` : ''}</tr>`)
134
+ .join('')}</tbody></table>`;
135
+
136
+ return (
137
+ `<div class="yc-frame" style="--weeks: ${weeks.length}; ${ramp}">` +
138
+ `<div class="yc-months" aria-hidden="true">${heads}</div>` +
139
+ `<div class="yc-wd" aria-hidden="true">${letters.map((l) => `<span>${esc(l)}</span>`).join('')}</div>` +
140
+ `<div class="yc-grid" role="img" aria-label="${esc(named)}">${cells}</div>` +
141
+ `</div>${table}`
142
+ );
143
+ };
144
+
145
+ const longDate = (d) => new Date(`${d}T12:00:00Z`).toLocaleDateString('en-GB', { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric', timeZone: 'UTC' });
146
+
147
+ // The card's words, as the charts' pointer writes them: the date quiet, the figure bold beside its
148
+ // colour, then [label, value] rows and lines of text from `extra`.
149
+ const cardHTML = (title, line, step, extra) => {
150
+ const pairs = extra.filter(Array.isArray);
151
+ const notes = extra.filter((e) => !Array.isArray(e));
152
+ return (
153
+ `<p class="chart-pointer-title">${esc(title)}</p>` +
154
+ // A day with nothing says so quietly, as a note; a day with something, bold beside its colour.
155
+ (line ? (step ? `<p class="chart-pointer-one"><i style="background: var(--yc-${step})"></i>${esc(line)}</p>` : `<p class="chart-pointer-note">${esc(line)}</p>`) : '') +
156
+ (pairs.length ? `<dl>${pairs.map(([l, v]) => `<div><dt>${esc(l)}</dt><dd>${esc(v)}</dd></div>`).join('')}</dl>` : '') +
157
+ notes.map((n) => `<p class="chart-pointer-note">${esc(n)}</p>`).join('')
158
+ );
159
+ };
160
+
161
+ /**
162
+ * Draws the calendar into `box` (a YearCalendar, or any element) and wires its card and keys.
163
+ * Call it again with new days to draw it again.
164
+ *
165
+ * year; days; value (entry) → number; colors, or tone and levels; steps; weekStart (1 Monday, 0
166
+ * Sunday); today (ISO, default the reader's; later days are paler); label: what the grid says to a
167
+ * screen reader, such as "Running in 2026: 84 days"; format (entry, iso) → the card's figure;
168
+ * empty: the card's words for a day with nothing (default none); date (iso) → the card's title;
169
+ * extra (entry, iso) → [label, value] pairs and lines of text for the card; total (sum, month) →
170
+ * the month table's total, which it leaves out without one; table: false to leave the table out;
171
+ * months, monthNames, weekdays and words for other words.
172
+ */
173
+ export const setYearCalendar = (box, opts) => {
174
+ const o = options({ today: localToday(), ...opts });
175
+ const { days, value, format = (d) => String(value(d)), empty, date = longDate, extra = () => [], today } = o;
176
+ box.classList.add('year-calendar');
177
+ box.innerHTML = calendarHTML(o);
178
+
179
+ const frame = box.querySelector('.yc-frame');
180
+ const grid = box.querySelector('.yc-grid');
181
+ const cells = [...grid.querySelectorAll('[data-day]')];
182
+ const index = new Map(cells.map((c, i) => [c.dataset.day, i]));
183
+
184
+ // The layer the charts' pointer uses (pointer.css): a frame round the day and the card.
185
+ const layer = document.createElement('div');
186
+ layer.className = 'chart-pointer';
187
+ layer.setAttribute('aria-hidden', 'true');
188
+ layer.innerHTML = '<div class="chart-pointer-cell"></div><div class="chart-pointer-card"></div>';
189
+ frame.append(layer);
190
+ const [ring, card] = layer.children;
191
+ const live = document.createElement('p');
192
+ live.className = 'chart-pointer-live';
193
+ live.setAttribute('aria-live', 'polite');
194
+ box.append(live);
195
+
196
+ let at = -1;
197
+ let hide;
198
+ const leave = () => {
199
+ clearTimeout(hide);
200
+ hide = setTimeout(() => {
201
+ layer.classList.remove('is-on');
202
+ at = -1;
203
+ }, 120);
204
+ };
205
+
206
+ const show = (i, fromKeys) => {
207
+ if (i < 0 || i >= cells.length) return;
208
+ clearTimeout(hide);
209
+ at = i;
210
+ const cell = cells[i];
211
+ const d = cell.dataset.day;
212
+ const entry = cell.dataset.step ? days[d] : undefined;
213
+ const line = entry !== undefined ? format(entry, d) : empty;
214
+ const more = entry !== undefined ? (extra(entry, d) ?? []) : [];
215
+ card.innerHTML = cardHTML(date(d), line, entry !== undefined ? Number(cell.dataset.step) : 0, more);
216
+
217
+ const f = frame.getBoundingClientRect();
218
+ const c = cell.getBoundingClientRect();
219
+ const left = c.left - f.left;
220
+ const top = c.top - f.top;
221
+ ring.style.width = `${c.width}px`;
222
+ ring.style.height = `${c.height}px`;
223
+ ring.style.transform = `translate(${left}px, ${top}px)`;
224
+ // Above the day, centred and kept inside the calendar; below it when there's no room above.
225
+ const cw = card.offsetWidth;
226
+ const ch = card.offsetHeight;
227
+ const cx = Math.min(Math.max(left + c.width / 2 - cw / 2, 0), Math.max(f.width - cw, 0));
228
+ const cy = top - ch - 8 >= 0 ? top - ch - 8 : top + c.height + 8;
229
+ card.style.transform = `translate(${cx}px, ${cy}px)`;
230
+
231
+ const first = !layer.classList.contains('is-on');
232
+ layer.classList.toggle('is-jump', first);
233
+ layer.classList.add('is-on');
234
+ if (first) requestAnimationFrame(() => layer.classList.remove('is-jump'));
235
+ if (fromKeys) {
236
+ const said = [line, ...more.map((e) => (Array.isArray(e) ? e.join(' ') : e))].filter(Boolean);
237
+ live.textContent = `${date(d)}${said.length ? `: ${said.join(', ')}` : ''}`;
238
+ }
239
+ };
240
+
241
+ grid.onpointermove = (e) => {
242
+ const cell = e.target.closest?.('[data-day]');
243
+ if (cell) show(index.get(cell.dataset.day));
244
+ };
245
+ grid.onpointerleave = leave;
246
+
247
+ // The keys start from today in this year, otherwise from its last day with something, or 1 January.
248
+ const start = () => index.get(today) ?? cells.findLastIndex((c) => c.dataset.step) ?? 0;
249
+ const month = (i, by) => {
250
+ const [y, m, dd] = cells[i].dataset.day.split('-').map(Number);
251
+ const to = new Date(Date.UTC(y, m - 1 + by, 1));
252
+ const last = new Date(Date.UTC(to.getUTCFullYear(), to.getUTCMonth() + 1, 0)).getUTCDate();
253
+ return index.get(iso(Date.UTC(to.getUTCFullYear(), to.getUTCMonth(), Math.min(dd, last)))) ?? i;
254
+ };
255
+ grid.tabIndex = 0;
256
+ grid.onfocus = () => {
257
+ if (grid.matches(':focus-visible')) show(at < 0 ? Math.max(start(), 0) : at, true);
258
+ };
259
+ grid.onblur = leave;
260
+ grid.onkeydown = (e) => {
261
+ if (e.key === 'Escape') return leave();
262
+ const from = at < 0 ? Math.max(start(), 0) : at;
263
+ const to = { ArrowRight: from + 7, ArrowLeft: from - 7, ArrowDown: from + 1, ArrowUp: from - 1, PageDown: month(from, 1), PageUp: month(from, -1), Home: 0, End: cells.length - 1 }[e.key];
264
+ if (to === undefined) return;
265
+ e.preventDefault();
266
+ show(Math.min(Math.max(to, 0), cells.length - 1), true);
267
+ };
268
+ };
@@ -0,0 +1,77 @@
1
+ // Synthetic days only.
2
+ import assert from 'node:assert/strict';
3
+ import { calendarHTML, evenSteps, HEAT, stepOf, toneRamp, yearWeeks } from './yearcalendar.js';
4
+
5
+ // Weeks: from the week holding 1 January to the week holding 31 December.
6
+ const mon = yearWeeks(2026);
7
+ assert.equal(mon.length, 53);
8
+ assert.equal(mon[0][0], '2025-12-29', 'Monday on or before 1 January');
9
+ assert.ok(mon[0].includes('2026-01-01'));
10
+ assert.ok(mon.at(-1).includes('2026-12-31'));
11
+ assert.ok(mon.every((w) => w.length === 7));
12
+ const sun = yearWeeks(2026, 0);
13
+ assert.equal(sun[0][0], '2025-12-28', 'Sunday on or before 1 January');
14
+ assert.equal(new Date(`${sun[0][0]}T12:00:00Z`).getUTCDay(), 0);
15
+ // A leap year whose 1 January is a Monday starts on it.
16
+ assert.equal(yearWeeks(2024)[0][0], '2024-01-01');
17
+ // Every day of the year exactly once.
18
+ const days2024 = yearWeeks(2024).flat().filter((d) => d.startsWith('2024-'));
19
+ assert.equal(days2024.length, 366);
20
+ assert.equal(new Set(days2024).size, 366);
21
+
22
+ // Steps: even shares of the values above zero, one fewer than the colours.
23
+ assert.deepEqual(evenSteps([1, 2, 3, 4, 5, 6, 7, 8, 0, 0], 4), [3, 5, 7]);
24
+ assert.deepEqual(evenSteps([0, 0], 4), [], 'nothing above zero');
25
+ assert.deepEqual(evenSteps([5, 5, 5], 3), [5, 5], 'all alike');
26
+ assert.deepEqual(evenSteps([1, 2], 1), [], 'one colour has no steps');
27
+ assert.equal(stepOf(0, [3, 5]), 0, 'nothing is no step');
28
+ assert.equal(stepOf(1, [3, 5]), 1, 'anything above zero is the first colour at least');
29
+ assert.equal(stepOf(3, [3, 5]), 2, 'a step starts at its value');
30
+ assert.equal(stepOf(99, [3, 5]), 3);
31
+ assert.equal(stepOf(5, [5, 5]), 3, 'all alike: the top colour');
32
+
33
+ // One tone in strengths, the last the tone itself.
34
+ assert.deepEqual(toneRamp('var(--c-chart-6)', 1), ['var(--c-chart-6)']);
35
+ const four = toneRamp('var(--c-chart-6)', 4);
36
+ assert.equal(four.length, 4);
37
+ assert.equal(four.at(-1), 'var(--c-chart-6)');
38
+ assert.match(four[0], /^color-mix\(in oklab, var\(--c-chart-6\) 35%, var\(--c-surface\)\)$/);
39
+
40
+ // Markup.
41
+ const days = { '2026-01-01': 3, '2026-03-02': 1, '2026-03-03': { value: 0 }, '2025-12-31': 5 };
42
+ const html = calendarHTML({ year: 2026, days, today: '2026-11-10', total: (n) => `${n} km`, label: 'Runs "in" 2026' });
43
+ assert.equal((html.match(/data-day=/g) ?? []).length, 365, 'a cell for every day of the year');
44
+ assert.equal((html.match(/class="out"/g) ?? []).length, 53 * 7 - 365, 'the other days hold their place');
45
+ assert.equal((html.match(/class="on"/g) ?? []).length, 2, 'a day from another year, or with 0, is not drawn');
46
+ assert.equal((html.match(/class="later"/g) ?? []).length, 51, 'the days after today are paler');
47
+ assert.match(html, /aria-label="Runs &quot;in&quot; 2026"/, 'the label stays one attribute');
48
+ assert.match(html, /--weeks: 53/);
49
+ for (let i = 1; i <= 6; i++) assert.ok(html.includes(`--yc-${i}: ${HEAT[i - 1]}`), 'the heat ramp by default');
50
+ assert.match(html, /<th scope="row">January<\/th><td>1<\/td><td>3 km<\/td>/, 'the table: days and total by month');
51
+ assert.match(html, /<th scope="row">March<\/th><td>1<\/td><td>1 km<\/td>/);
52
+ assert.ok(!calendarHTML({ year: 2026, table: false }).includes('<table'), 'table: false leaves it out');
53
+ assert.ok(!calendarHTML({ year: 2026 }).includes('class="later"'), 'without today, nothing is still to come');
54
+ assert.match(calendarHTML({ year: 2026 }), /2026: 0 days with something/);
55
+ assert.match(calendarHTML({ year: 2026, days: { '2026-02-01': 1 } }), /2026: 1 day with something/);
56
+
57
+ // Month names over the week holding the 1st.
58
+ assert.match(html, /<span style="--at: 0.000%" data-short="J">Jan<\/span>/);
59
+ const feb = Math.floor((Date.UTC(2026, 1, 1) - Date.UTC(2025, 11, 29)) / 86_400_000 / 7);
60
+ assert.ok(html.includes(`--at: ${((feb / 53) * 100).toFixed(3)}%" data-short="F">Feb`));
61
+
62
+ // Weekday letters: M, W, F on the rows they name.
63
+ assert.match(html, /<span>M<\/span><span><\/span><span>W<\/span><span><\/span><span>F<\/span><span><\/span><span><\/span>/);
64
+ assert.match(calendarHTML({ year: 2026, weekStart: 0 }), /<span><\/span><span>M<\/span><span><\/span><span>W<\/span>/);
65
+
66
+ // One tone, and given steps.
67
+ const toned = calendarHTML({ year: 2026, tone: 'var(--c-chart-3)', levels: 1, days: { '2026-05-05': 9 } });
68
+ assert.ok(toned.includes('--yc-1: var(--c-chart-3)') && !toned.includes('--yc-2'));
69
+ const stepped = calendarHTML({ year: 2026, steps: [10], colors: ['a', 'b'], days: { '2026-05-05': 9, '2026-05-06': 10 } });
70
+ assert.match(stepped, /data-day="2026-05-05" data-step="1"/);
71
+ assert.match(stepped, /data-day="2026-05-06" data-step="2"/);
72
+ assert.throws(() => calendarHTML({ year: 2026, colors: Array(10).fill('red') }), /at most 9 colours/);
73
+
74
+ // value reads the number from an entry.
75
+ const read = calendarHTML({ year: 2026, days: { '2026-06-01': { count: 2, km: 5 } }, value: (d) => d.count });
76
+ assert.match(read, /data-day="2026-06-01" data-step="\d"/);
77
+ console.log('yearcalendar: all assertions pass');