@n1kname/components 0.18.0 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@n1kname/components",
3
- "version": "0.18.0",
3
+ "version": "0.19.0",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "exports": {
@@ -14,6 +14,7 @@
14
14
  "./dotrows.js": "./src/dotrows.js",
15
15
  "./rangebars.js": "./src/rangebars.js",
16
16
  "./daystrips.js": "./src/daystrips.js",
17
+ "./yearcalendar.js": "./src/yearcalendar.js",
17
18
  "./period.js": "./src/period.js",
18
19
  "./search.js": "./src/search.js",
19
20
  "./chips.js": "./src/chips.js",
@@ -26,7 +27,7 @@
26
27
  "./match.css": "./src/match.css"
27
28
  },
28
29
  "dependencies": {
29
- "@n1kname/charts": "0.10.0"
30
+ "@n1kname/charts": "0.11.0"
30
31
  },
31
32
  "peerDependencies": {
32
33
  "@n1kname/tokens": "^0.5.0",
@@ -44,5 +45,7 @@
44
45
  "src",
45
46
  "THIRD_PARTY.md"
46
47
  ],
47
- "scripts": {}
48
+ "scripts": {
49
+ "check": "node src/yearcalendar.test.mjs"
50
+ }
48
51
  }
@@ -9,7 +9,10 @@
9
9
  * Back steps back through it; "all" is no parameter at all. The periods are known at build time
10
10
  * (`periods`) or set later from script with setPeriods() from period.js, such as years read from
11
11
  * an API. Each change fires `period-change` on the element, with the period as `detail.value`
12
- * ("all" for all of them).
12
+ * ("all" for all of them) and the words shown for it as `detail.label`.
13
+ *
14
+ * A period is a string, or { value, label } when the button should say something other than what
15
+ * the address keeps: "Nov 2026" shown, "2026-11" in ?month= and in the event.
13
16
  *
14
17
  * Keyboard: Tab reaches each part; in the list, the arrow keys move through the periods and
15
18
  * Escape closes it.
@@ -17,11 +20,11 @@
17
20
  interface Props {
18
21
  /** The address parameter that holds the choice. Leave it out to keep the choice in the page. */
19
22
  param?: string;
20
- /** Periods known at build time, oldest first. */
21
- periods?: string[];
23
+ /** Periods known at build time, oldest first: strings, or { value, label }. */
24
+ periods?: (string | { value: string; label?: string })[];
22
25
  /** The words for a choice covering every period, such as "All years". Leave it out for none. */
23
26
  all?: string;
24
- /** The period chosen when the address says nothing: "all", or one of the periods. Default: all if there is one, otherwise the newest. */
27
+ /** The period chosen when the address says nothing: "all", or one of the periods' values. Default: all if there is one, otherwise the newest. */
25
28
  initial?: string;
26
29
  /** The words a screen reader hears. */
27
30
  labels?: { name?: string; previous?: string; next?: string; list?: string };
@@ -29,12 +32,13 @@ interface Props {
29
32
  id?: string;
30
33
  }
31
34
 
32
- const { param, periods = [], all, initial, labels = {}, id = 'period' } = Astro.props;
35
+ const { param, periods: given = [], all, initial, labels = {}, id = 'period' } = Astro.props;
36
+ const periods = given.map((p) => (typeof p === 'object' ? { value: String(p.value), label: String(p.label ?? p.value) } : { value: String(p), label: String(p) }));
33
37
  const words = { name: 'Period', previous: 'Previous', next: 'Next', list: 'Choose a period', ...labels };
34
38
  const chevron = (d: string) =>
35
39
  `<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="${d}"/></svg>`;
36
- const start = initial ?? (all ? 'all' : periods.at(-1));
37
- const shown = start === 'all' ? all : start;
40
+ const start = initial ?? (all ? 'all' : periods.at(-1)?.value);
41
+ const shown = start === 'all' ? all : (periods.find((p) => p.value === start)?.label ?? start);
38
42
  ---
39
43
 
40
44
  <div
@@ -57,8 +61,8 @@ const shown = start === 'all' ? all : start;
57
61
  <div class="periods">
58
62
  {
59
63
  [...periods].reverse().map((p) => (
60
- <button type="button" class="option" data-value={p}>
61
- {p}
64
+ <button type="button" class="option" data-value={p.value}>
65
+ {p.label}
62
66
  </button>
63
67
  ))
64
68
  }
@@ -0,0 +1,207 @@
1
+ ---
2
+ /**
3
+ * One year of days at a glance, a week to a column: which days had something, and how much, in
4
+ * steps of colour. The days are squares that share the width there is, so the year fits a phone
5
+ * and fills a card.
6
+ *
7
+ * It draws the empty year at build time, so the page keeps its shape; fill it with
8
+ * setYearCalendar from `@n1kname/components/yearcalendar.js` when the days arrive, or pass `days`
9
+ * to draw them now (the card and keys still need setYearCalendar). The heat ramp by default; `tone`
10
+ * for one colour in `levels` strengths, or `colors` for any ramp.
11
+ */
12
+ import '@n1kname/charts/pointer.css';
13
+ import { calendarHTML } from './yearcalendar.js';
14
+
15
+ interface Props {
16
+ /** Unique on the page; setYearCalendar finds the calendar by it. */
17
+ id: string;
18
+ year: number;
19
+ /** ISO date → number, drawn at build time. */
20
+ days?: Record<string, number>;
21
+ /** One colour, in `levels` strengths: var(--c-chart-6). */
22
+ tone?: string;
23
+ levels?: number;
24
+ /** Low to high. Any CSS colours, best tokens. */
25
+ colors?: string[];
26
+ /** Where each colour after the first starts. */
27
+ steps?: number[];
28
+ /** 1 for Monday, 0 for Sunday. */
29
+ weekStart?: 0 | 1;
30
+ /** What the grid says to a screen reader: "Running in 2026: 84 days". */
31
+ label?: string;
32
+ [key: string]: unknown;
33
+ }
34
+
35
+ const { id, year, days, tone, levels, colors, steps, weekStart = 1, label, class: className, ...rest } = Astro.props;
36
+ const html = calendarHTML({ year, days, tone, levels, colors, steps, weekStart, label });
37
+ ---
38
+
39
+ <div id={id} class:list={['year-calendar', className]} {...rest}><Fragment set:html={html} /></div>
40
+
41
+ <style>
42
+ .year-calendar {
43
+ container-type: inline-size;
44
+ position: relative;
45
+ /* Wide, the days stop growing at --year-calendar-cell; the frame is as wide as they need. */
46
+ --yc-gap: 2px;
47
+ }
48
+
49
+ .year-calendar :global(.yc-frame) {
50
+ position: relative;
51
+ display: grid;
52
+ grid-template-columns: 1rem minmax(0, 1fr);
53
+ grid-template-areas: '. months' 'wd grid';
54
+ gap: 2px 4px;
55
+ max-width: calc(1rem + 4px + var(--weeks) * (var(--year-calendar-cell, 16px) + var(--yc-gap)));
56
+ }
57
+
58
+ /* Each month's name over the week holding its first day. */
59
+ .year-calendar :global(.yc-months) {
60
+ grid-area: months;
61
+ position: relative;
62
+ height: 0.875rem;
63
+ font-size: 0.625rem;
64
+ line-height: 1;
65
+ color: var(--c-text-muted);
66
+ }
67
+
68
+ .year-calendar :global(.yc-months span) {
69
+ position: absolute;
70
+ left: var(--at);
71
+ white-space: nowrap;
72
+ }
73
+
74
+ /* On a phone the gaps would take a third of the width: a pixel each gives it to the days. */
75
+ @container (max-width: 480px) {
76
+ .year-calendar :global(.yc-frame) {
77
+ --yc-gap: 1px;
78
+ }
79
+
80
+ .year-calendar :global(.yc-grid i) {
81
+ border-radius: 1px;
82
+ }
83
+ }
84
+
85
+ /* Narrow, a letter each. */
86
+ @container (max-width: 320px) {
87
+ .year-calendar :global(.yc-months span) {
88
+ font-size: 0;
89
+ }
90
+
91
+ .year-calendar :global(.yc-months span)::before {
92
+ content: attr(data-short);
93
+ font-size: 0.625rem;
94
+ }
95
+ }
96
+
97
+ /* The letters take the grid's height and never set it (contain: size): when the days are
98
+ smaller than a letter, the rows stay as tall as the days. */
99
+ .year-calendar :global(.yc-wd) {
100
+ grid-area: wd;
101
+ contain: size;
102
+ display: grid;
103
+ grid-template-rows: repeat(7, minmax(0, 1fr));
104
+ gap: var(--yc-gap);
105
+ align-items: center;
106
+ font-size: 0.5625rem;
107
+ line-height: 1;
108
+ color: var(--c-text-muted);
109
+ text-align: right;
110
+ }
111
+
112
+ /* Each day a square: the weeks share the width and the rows follow from it. */
113
+ .year-calendar :global(.yc-grid) {
114
+ grid-area: grid;
115
+ min-width: 0;
116
+ display: grid;
117
+ grid-template-rows: repeat(7, auto);
118
+ grid-auto-columns: minmax(0, 1fr);
119
+ grid-auto-flow: column;
120
+ gap: var(--yc-gap);
121
+ align-content: start;
122
+ border-radius: 2px;
123
+ }
124
+
125
+ .year-calendar :global(.yc-grid:focus-visible) {
126
+ outline: 2px solid var(--c-focus);
127
+ outline-offset: 3px;
128
+ }
129
+
130
+ .year-calendar :global(.yc-grid i) {
131
+ aspect-ratio: 1;
132
+ border-radius: 2px;
133
+ }
134
+
135
+ .year-calendar :global(.yc-grid .off) {
136
+ background: color-mix(in oklab, var(--c-text) 9%, var(--c-surface));
137
+ }
138
+
139
+ /* Days still to come: paler, so the year so far reads as one shape. */
140
+ .year-calendar :global(.yc-grid .later) {
141
+ background: color-mix(in oklab, var(--c-text) 4%, var(--c-surface));
142
+ }
143
+
144
+ .year-calendar :global(.yc-grid .out) {
145
+ visibility: hidden;
146
+ }
147
+
148
+ /* A hairline edge, so a pale step (the heat ramp's yellow) keeps its shape on a light surface. */
149
+ .year-calendar :global(.yc-grid .on) {
150
+ box-shadow: inset 0 0 0 1px color-mix(in oklab, var(--c-text) 10%, transparent);
151
+ }
152
+
153
+ .year-calendar :global([data-step='1']) { background: var(--yc-1); }
154
+ .year-calendar :global([data-step='2']) { background: var(--yc-2); }
155
+ .year-calendar :global([data-step='3']) { background: var(--yc-3); }
156
+ .year-calendar :global([data-step='4']) { background: var(--yc-4); }
157
+ .year-calendar :global([data-step='5']) { background: var(--yc-5); }
158
+ .year-calendar :global([data-step='6']) { background: var(--yc-6); }
159
+ .year-calendar :global([data-step='7']) { background: var(--yc-7); }
160
+ .year-calendar :global([data-step='8']) { background: var(--yc-8); }
161
+ .year-calendar :global([data-step='9']) { background: var(--yc-9); }
162
+
163
+ /* The card's figure beside its colour, and the frame round the day a little rounder. */
164
+ .year-calendar :global(.chart-pointer-one) {
165
+ display: flex;
166
+ align-items: center;
167
+ gap: var(--sp-2);
168
+ }
169
+
170
+ .year-calendar :global(.chart-pointer-one i) {
171
+ box-shadow: inset 0 0 0 1px color-mix(in oklab, var(--c-text) 14%, transparent);
172
+ }
173
+
174
+ .year-calendar :global(.chart-pointer-cell) {
175
+ border-width: 1.5px;
176
+ border-radius: 3px;
177
+ margin: -1.5px 0 0 -1.5px;
178
+ padding: 1.5px;
179
+ box-sizing: content-box;
180
+ }
181
+
182
+ .year-calendar :global(.chart-pointer-card) {
183
+ z-index: 5;
184
+ }
185
+
186
+ .year-calendar :global(.yc-sr) {
187
+ position: absolute;
188
+ width: 1px;
189
+ height: 1px;
190
+ overflow: hidden;
191
+ clip-path: inset(50%);
192
+ white-space: nowrap;
193
+ }
194
+
195
+ @media (forced-colors: active) {
196
+ .year-calendar :global(.yc-grid i) {
197
+ forced-color-adjust: none;
198
+ }
199
+
200
+ .year-calendar :global(.yc-grid .off),
201
+ .year-calendar :global(.yc-grid .later) {
202
+ background: Canvas;
203
+ outline: 1px solid GrayText;
204
+ outline-offset: -1px;
205
+ }
206
+ }
207
+ </style>
package/src/period.js CHANGED
@@ -5,6 +5,9 @@
5
5
  // import { setPeriods } from '@n1kname/components/period.js';
6
6
  // picker.addEventListener('period-change', (e) => show(e.detail.value));
7
7
  // setPeriods(picker, ['2011', '2012', ..., '2026']); // oldest first
8
+ //
9
+ // A period is a string, shown and kept as it is, or { value, label }: the label on the button and
10
+ // in the list ("Nov 2026"), the value in the address and in `period-change` ("2026-11").
8
11
 
9
12
  const reduced = () => matchMedia('(prefers-reduced-motion: reduce)').matches;
10
13
  const token = (name) => getComputedStyle(document.documentElement).getPropertyValue(name).trim();
@@ -16,14 +19,26 @@ const ms = (name, fallback) => {
16
19
  };
17
20
 
18
21
  // Oldest first.
19
- const periodsOf = (root) => [...root.querySelectorAll('.periods .option')].map((o) => o.dataset.value).reverse();
20
- const nameOf = (root, v) => (v === 'all' ? root.dataset.all : v);
22
+ const optionsOf = (root) => [...root.querySelectorAll('.periods .option')].reverse();
23
+ const periodsOf = (root) => optionsOf(root).map((o) => o.dataset.value);
24
+ // What a value says: its option's label, the words for all, or nothing before the periods are known.
25
+ const nameOf = (root, v) => {
26
+ if (v === undefined) return '';
27
+ if (v === 'all') return root.dataset.all ?? '';
28
+ return optionsOf(root).find((o) => o.dataset.value === v)?.textContent ?? v;
29
+ };
30
+ // A period as a string or { value, label }, made { value, label }.
31
+ const asPeriod = (p) => (p !== null && typeof p === 'object' ? { value: String(p.value), label: String(p.label ?? p.value) } : { value: String(p), label: String(p) });
21
32
 
22
- // The choice: the address's, when the picker keeps it there and it names a period or all.
33
+ // The choice: the address's, when the picker keeps it there and it names a period or all. Before
34
+ // the periods are known, a picker with no initial period has no choice (undefined), and a kept
35
+ // choice that is no longer one of the periods falls back to all or the newest.
23
36
  export const periodOf = (root) => {
24
37
  const periods = periodsOf(root);
25
38
  const all = root.dataset.all !== undefined;
26
- const fallback = root.dataset.value ?? (all ? 'all' : periods.at(-1));
39
+ const kept = root.dataset.value;
40
+ const valid = kept !== undefined && (kept === 'all' ? all : !periods.length || periods.includes(kept));
41
+ const fallback = valid ? kept : all ? 'all' : periods.at(-1);
27
42
  if (!root.dataset.param) return fallback;
28
43
  const asked = new URL(location.href).searchParams.get(root.dataset.param);
29
44
  if (asked === null) return all ? 'all' : fallback;
@@ -51,7 +66,9 @@ const sync = (root, dir = 0) => {
51
66
  const v = periodOf(root);
52
67
  const periods = periodsOf(root);
53
68
  const all = root.dataset.all !== undefined;
54
- root.dataset.value = v;
69
+ // Never the word "undefined": a picker built with no periods has no choice until they come.
70
+ if (v === undefined) delete root.dataset.value;
71
+ else root.dataset.value = v;
55
72
  roll(root, v, dir);
56
73
  const [prev, next] = root.querySelectorAll('.step');
57
74
  const at = periods.indexOf(v);
@@ -59,8 +76,8 @@ const sync = (root, dir = 0) => {
59
76
  next.disabled = !periods.length || v === 'all' || (!all && at === periods.length - 1);
60
77
  root.querySelectorAll('.option').forEach((o) => o.setAttribute('aria-pressed', String(o.dataset.value === v)));
61
78
  // The sizer holds the longest words the label may show, so the control keeps its width.
62
- const longest = [root.dataset.all ?? '', ...periods].reduce((a, b) => (b.length > a.length ? b : a), '');
63
- root.querySelector('.sizer').textContent = longest || v;
79
+ const longest = [root.dataset.all ?? '', ...optionsOf(root).map((o) => o.textContent)].reduce((a, b) => (b.length > a.length ? b : a), '');
80
+ root.querySelector('.sizer').textContent = longest || nameOf(root, v);
64
81
  };
65
82
 
66
83
  const go = (root, v, dir) => {
@@ -72,18 +89,25 @@ const go = (root, v, dir) => {
72
89
  }
73
90
  root.dataset.value = v;
74
91
  sync(root, dir);
75
- root.dispatchEvent(new CustomEvent('period-change', { bubbles: true, detail: { value: v } }));
92
+ changed(root);
93
+ };
94
+
95
+ // `period-change`: the value, and the words the button shows for it.
96
+ const changed = (root) => {
97
+ const value = root.dataset.value;
98
+ root.dispatchEvent(new CustomEvent('period-change', { bubbles: true, detail: { value, label: nameOf(root, value) } }));
76
99
  };
77
100
 
78
- // Fills a picker with its periods, oldest first, and shows it.
101
+ // Fills a picker with its periods, oldest first, and shows it. Each a string, or { value, label }.
79
102
  export const setPeriods = (root, periods) => {
80
103
  root.querySelector('.periods').replaceChildren(
81
104
  ...[...periods].reverse().map((p) => {
105
+ const { value, label } = asPeriod(p);
82
106
  const b = document.createElement('button');
83
107
  b.type = 'button';
84
108
  b.className = 'option';
85
- b.dataset.value = String(p);
86
- b.textContent = String(p);
109
+ b.dataset.value = value;
110
+ b.textContent = label;
87
111
  return b;
88
112
  }),
89
113
  );
@@ -153,7 +177,7 @@ export const wirePeriodPicker = (root) => {
153
177
  addEventListener('popstate', () => {
154
178
  const was = root.dataset.value;
155
179
  sync(root);
156
- if (root.dataset.value !== was) root.dispatchEvent(new CustomEvent('period-change', { bubbles: true, detail: { value: root.dataset.value } }));
180
+ if (root.dataset.value !== was) changed(root);
157
181
  });
158
182
  }
159
183
  sync(root);
@@ -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');