claude-code-cost 1.7.0 → 1.8.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/README.md CHANGED
@@ -33,7 +33,7 @@ The dashboard is a PWA. With the server running, open it in Chrome or Edge and c
33
33
 
34
34
  - **Drill down from the total to one message.** Open a project to see its sessions, then a session to see each message. <kbd>Backspace</kbd> goes back one level.
35
35
  - **Session detail.** A cumulative cost curve, the tokens of each message, and a table with the model, the tools it called, and the running total. Subagents and Workflow runs are in the totals, with a row per agent. Compactions show with an estimated summarizer cost. A range brush picks which messages to show in long sessions.
36
- - **Date ranges.** Presets from Today and Last 24h up to 1 Year, or two dates on a calendar. The range and the project scope apply to every view.
36
+ - **Date ranges.** Presets from Today and Last 24h up to 1 Year, This Month and This Year, whole months or years (one or several), or two dates on a calendar. The range and the project scope apply to every view.
37
37
  - **Insights.** The active 5-hour block with its time left, burn rate, monthly run-rate, cache savings, and subagent share. Charts for token composition, top tools, an hourly heatmap, and weekly cost, plus a table of past 5-hour blocks.
38
38
  - **Plan usage.** Press <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>S</kbd> to see your plan windows, the percent used, and what drives the cost.
39
39
  - **Pricing.** Live prices from the [LiteLLM](https://github.com/BerriAI/litellm) price list, with the 200K-token tier, cache reads and writes, and fast mode. A built-in table fills in when the list cannot load. Streamed lines are counted once per `message.id` plus `requestId`.
package/lib/cli.js CHANGED
@@ -11,12 +11,42 @@ const LONG_PARSE_DAYS = 30;
11
11
  // The dashboard's longest preset. The overview has no all-time window.
12
12
  const MAX_DAYS = 365;
13
13
  const DAY_MS = 24 * 60 * 60 * 1000;
14
- const WINDOW_HINT = `today, 24h or <n>d up to ${MAX_DAYS}d`;
15
-
16
- function parseWindowValue(raw) {
14
+ const WINDOW_HINT = `today, 24h, <n>d up to ${MAX_DAYS}d, month, year, YYYY-MM or YYYY`;
15
+
16
+ const YEAR_RE = /^20\d{2}$/;
17
+ const MONTH_RE = /^(20\d{2})-(0[1-9]|1[0-2])$/;
18
+ const pad2 = (n) => String(n).padStart(2, '0');
19
+
20
+ // A year (YYYY) or month (YYYY-MM) as the first or last day it covers. Anything else comes back
21
+ // untouched, for parseCustomRange to read as a date or reject.
22
+ function expandBound(raw, edge) {
23
+ if (raw === undefined) return raw;
24
+ const v = String(raw).trim();
25
+ if (YEAR_RE.test(v)) return edge === 'from' ? `${v}-01-01` : `${v}-12-31`;
26
+ const m = MONTH_RE.exec(v);
27
+ if (!m) return v;
28
+ const [y, mo] = [Number(m[1]), Number(m[2])];
29
+ return edge === 'from' ? `${y}-${pad2(mo)}-01` : `${y}-${pad2(mo)}-${pad2(new Date(y, mo, 0).getDate())}`;
30
+ }
31
+
32
+ // A whole month or year as a custom window. The running one ends today: there is no cost data ahead.
33
+ function unitWindow(from, to, label, now) {
34
+ const today = costs.localDateStr(now);
35
+ if (from > today) throw usageError(`${label} has not started`);
36
+ const end = to > today ? today : to;
37
+ const days = Math.round((Date.parse(end) - Date.parse(from)) / DAY_MS) + 1;
38
+ return { ...customWindow(from, end, days), label };
39
+ }
40
+
41
+ function parseWindowValue(raw, now = new Date()) {
17
42
  const v = String(raw).trim().toLowerCase();
18
43
  if (v === 'today') return { range: 'today', days: 1, label: 'Today' };
19
44
  if (v === '24h') return { range: '24h', days: 1, label: 'Last 24 hours' };
45
+ const y = now.getFullYear();
46
+ const ym = `${y}-${pad2(now.getMonth() + 1)}`;
47
+ if (v === 'month') return unitWindow(expandBound(ym, 'from'), expandBound(ym, 'to'), 'This month', now);
48
+ if (v === 'year') return unitWindow(`${y}-01-01`, `${y}-12-31`, 'This year', now);
49
+ if (YEAR_RE.test(v) || MONTH_RE.test(v)) return unitWindow(expandBound(v, 'from'), expandBound(v, 'to'), v, now);
20
50
  const m = /^(\d{1,3})d?$/.exec(v);
21
51
  if (!m || Number(m[1]) < 1 || Number(m[1]) > MAX_DAYS) return null;
22
52
  const n = Number(m[1]);
@@ -35,10 +65,36 @@ function customWindow(from, to, days) {
35
65
  return { range: { from, to }, days, label: from === to ? from : `${from} – ${to}`, query: `from=${from}&to=${to}` };
36
66
  }
37
67
 
38
- // The same number of whole days, ending the day before `win` starts. The API has no rolling window
39
- // that ends in the past, so 24h has no window before it.
68
+ // The window before a window of calendar months, or null for any other window. The months are whole,
69
+ // or the last one runs to today. They move back by their count: September gives August, and
70
+ // Nov 1 - Nov 17 gives Oct 1 - Oct 17. A window from January that is whole years, or runs to today
71
+ // after January, moves back by its years: the year so far gives the same days of last year. An end
72
+ // day the month before does not have stops at that month's last day.
73
+ function calendarBefore(range, now) {
74
+ if (!range?.from || range.from === range.to) return null;
75
+ const [fy, fm, fd] = range.from.split('-').map(Number);
76
+ const [ty, tm, td] = range.to.split('-').map(Number);
77
+ const lastDay = (y, m0) => new Date(y, m0 + 1, 0).getDate();
78
+ const whole = td === lastDay(ty, tm - 1);
79
+ const running = range.to === costs.localDateStr(now);
80
+ if (fd !== 1 || !(whole || running)) return null;
81
+ const years = fm === 1 && (running ? tm !== 1 : tm === 12);
82
+ const shift = years ? (ty - fy + 1) * 12 : (ty - fy) * 12 + tm - fm + 1;
83
+ const start = new Date(fy, fm - 1 - shift, 1);
84
+ const end = new Date(ty, tm - 1 - shift, 1);
85
+ const last = lastDay(end.getFullYear(), end.getMonth());
86
+ end.setDate(whole && !(years && running) ? last : Math.min(td, last));
87
+ const [from, to] = [costs.localDateStr(start), costs.localDateStr(end)];
88
+ return customWindow(from, to, Math.round((Date.parse(to) - Date.parse(from)) / DAY_MS) + 1);
89
+ }
90
+
91
+ // Calendar months move back by months (see calendarBefore). Any other window gives the same number
92
+ // of whole days, ending the day before `win` starts. The API has no rolling window that ends in the
93
+ // past, so 24h has no window before it.
40
94
  function previousWindow(win, now = new Date()) {
41
95
  if (win.range === '24h') throw usageError('--compare needs today, <n>d or --from/--to, not 24h');
96
+ const calendar = calendarBefore(win.range, now);
97
+ if (calendar) return calendar;
42
98
  const start = costs.resolveWindow(win.range, now).cutoff;
43
99
  const day = (delta) => costs.localDateStr(new Date(start.getFullYear(), start.getMonth(), start.getDate() + delta));
44
100
  return customWindow(day(-win.days), day(-1), win.days);
@@ -47,12 +103,18 @@ function previousWindow(win, now = new Date()) {
47
103
  // The flag wins, then CLAUDE_COST_RANGE, then cli.defaultRange in <config dir>/.cost/config.json,
48
104
  // then 7 days. A bad flag is an error; a bad env or config value is skipped with a warning, so a
49
105
  // typo in a file does not break every command.
50
- function resolveWindow(flags, { claudeDir, parseCustomRange, env = process.env, warn = console.error }) {
106
+ function resolveWindow(flags, { claudeDir, parseCustomRange, env = process.env, warn = console.error, now = new Date() }) {
51
107
  if (flags.from !== undefined || flags.to !== undefined) {
52
- const custom = parseCustomRange({ from: flags.from, to: flags.to });
53
- if (!custom) throw usageError('--from and --to take local dates (YYYY-MM-DD) and come as a pair');
108
+ if (flags.from === undefined || flags.to === undefined) throw usageError('--from and --to come as a pair');
109
+ // A year or month bound reaches to the edge of its unit: `--from 2025 --to 2026` is Jan 1, 2025
110
+ // to Dec 31, 2026, and `--from 2026-09 --to 2026-11` is Sep 1 to Nov 30 (both end at today at most).
111
+ let [f, t] = [expandBound(flags.from, 'from'), expandBound(flags.to, 'to')];
112
+ // Reversed bounds swap before they reach their edges, or `--from 2026-11 --to 2026-09` would
113
+ // start at the end of September and stop at the start of November.
114
+ if (f && t && f > t) [f, t] = [expandBound(flags.to, 'from'), expandBound(flags.from, 'to')];
115
+ const custom = parseCustomRange({ from: f, to: t }, now);
116
+ if (!custom) throw usageError('--from and --to take YYYY-MM-DD, YYYY-MM or YYYY');
54
117
  const days = Math.round((Date.parse(custom.to) - Date.parse(custom.from)) / DAY_MS) + 1;
55
- if (days > MAX_DAYS) throw usageError(`--from/--to: at most ${MAX_DAYS} days`);
56
118
  return customWindow(custom.from, custom.to, days);
57
119
  }
58
120
  const sources = [
@@ -63,8 +125,8 @@ function resolveWindow(flags, { claudeDir, parseCustomRange, env = process.env,
63
125
  ];
64
126
  for (const [raw, source] of sources) {
65
127
  if (raw === undefined || raw === null || raw === '') continue;
66
- const w = parseWindowValue(raw);
67
- if (w) return { ...w, source, query: `range=${w.range}` };
128
+ const w = parseWindowValue(raw, now);
129
+ if (w) return { ...w, source, query: w.query || `range=${w.range}` };
68
130
  if (source === '--range') throw usageError(`--range ${raw}: use ${WINDOW_HINT}`);
69
131
  warn(`${source}: "${raw}" is not a window (${WINDOW_HINT}); skipped`);
70
132
  }
@@ -433,8 +495,8 @@ const BIN = 'claude-code-cost';
433
495
 
434
496
  const WINDOW_FLAGS = {
435
497
  '--range <r>': WINDOW_HINT,
436
- '--from <date>': 'Window start, YYYY-MM-DD (needs --to)',
437
- '--to <date>': 'Window end, YYYY-MM-DD',
498
+ '--from <date>': 'Window start: YYYY-MM-DD, YYYY-MM or YYYY (needs --to)',
499
+ '--to <date>': 'Window end: YYYY-MM-DD, YYYY-MM or YYYY',
438
500
  };
439
501
  const COMMON_FLAGS = {
440
502
  '--top <n>': 'Rows per list (default 5)',
@@ -448,8 +510,8 @@ const COMMANDS = {
448
510
  summary: 'Total cost, by model, by day and top projects; --compare to the window before',
449
511
  usage: `${BIN} overview [--range <r>] [--project <name>] [--compare] [--json]`,
450
512
  flags: { ...SCOPED_FLAGS, '--compare': 'Also the window before it, and the change' },
451
- notes: 'The window before has as many days and ends the day before. Today counts so far.\n--compare also parses the window before.',
452
- examples: [`${BIN} overview --range today`, `${BIN} overview --range 30d --project claude-code-hub`, `${BIN} overview --range 7d --compare`],
513
+ notes: 'The window before has as many days and ends the day before. Today counts so far.\nWhole months, or months up to today, compare with the months before; years with the years before.\n--compare also parses the window before.',
514
+ examples: [`${BIN} overview --range today`, `${BIN} overview --range 30d --project claude-code-hub`, `${BIN} overview --range 7d --compare`, `${BIN} overview --range 2026-09 --compare`, `${BIN} overview --from 2025 --to 2026`],
453
515
  window: true,
454
516
  project: true,
455
517
  },
package/lib/costs.js CHANGED
@@ -1554,13 +1554,13 @@ function parseDateParam(raw) {
1554
1554
  // Reversed pairs are ordered and both ends clamped to today — there is no cost data ahead of now,
1555
1555
  // and an inverted window would otherwise render as an unexplained empty chart.
1556
1556
  // Returns undefined when no window was requested, null when one was but is malformed.
1557
- function parseCustomRange(query) {
1557
+ function parseCustomRange(query, now = new Date()) {
1558
1558
  const from = parseDateParam(query.from);
1559
1559
  const to = parseDateParam(query.to);
1560
1560
  if (from === null || to === null) return null;
1561
1561
  if (from === undefined && to === undefined) return undefined;
1562
1562
  if (from === undefined || to === undefined) return null;
1563
- const today = localDateStr(new Date());
1563
+ const today = localDateStr(now);
1564
1564
  const [lo, hi] = from <= to ? [from, to] : [to, from];
1565
1565
  return { from: lo > today ? today : lo, to: hi > today ? today : hi };
1566
1566
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-code-cost",
3
- "version": "1.7.0",
3
+ "version": "1.8.0",
4
4
  "description": "Cost dashboard for Claude Code usage",
5
5
  "main": "server.js",
6
6
  "type": "commonjs",
package/public/app.js CHANGED
@@ -355,8 +355,54 @@ function normalizeRange(r) {
355
355
  return Number.isFinite(n) && n > 0 ? presetRange(n) : null;
356
356
  }
357
357
 
358
- // "AUG 1 - AUG 12"; a single-day window is just "AUG 12".
358
+ const pad2 = (n) => String(n).padStart(2, '0');
359
+
360
+ // The month at (y, m0) as a window: its 1st to its last day, or to today while it is still running.
361
+ function monthSpan(y, m0) {
362
+ const last = isoDate(new Date(y, m0 + 1, 0));
363
+ const today = todayIso();
364
+ return { from: isoDate(new Date(y, m0, 1)), to: last > today ? today : last };
365
+ }
366
+
367
+ function monthToDate() {
368
+ const now = new Date();
369
+ return monthSpan(now.getFullYear(), now.getMonth());
370
+ }
371
+
372
+ // Jan 1 to Dec 31 of `y`, or to today while the year is still running.
373
+ function yearSpan(y) {
374
+ const today = todayIso();
375
+ const last = `${y}-12-31`;
376
+ return { from: `${y}-01-01`, to: last > today ? today : last };
377
+ }
378
+
379
+ // What whole calendar units [from, to] covers, or null for any other window: whole months
380
+ // ({unit:'month', a:'2026-09', b:'2026-11'}) or whole years ({unit:'year', a:2025, b:2026}). The
381
+ // running month or year counts as whole when it ends today, except a running January, which is a
382
+ // month rather than the year it has barely started. Names a window "NOVEMBER 2026" or "2025"
383
+ // instead of by its two dates, and picks the picker's mode on open.
384
+ function periodOf(from, to) {
385
+ if (from === to) return null;
386
+ const [fy, fm, fd] = isoParts(from);
387
+ const [ty, tm] = isoParts(to);
388
+ if (fd !== 1 || monthSpan(ty, tm - 1).to !== to) return null;
389
+ const now = new Date();
390
+ const running = ty === now.getFullYear() && tm - 1 === now.getMonth();
391
+ if (fm === 1 && (tm === 12 || (running && tm !== 1))) return { unit: 'year', a: fy, b: ty };
392
+ return { unit: 'month', a: `${fy}-${pad2(fm)}`, b: `${ty}-${pad2(tm)}` };
393
+ }
394
+
395
+ function monthLabel(ym, style = 'long') {
396
+ const [y, m] = isoParts(`${ym}-01`);
397
+ return new Date(y, m - 1, 1).toLocaleDateString(undefined, { month: style, year: 'numeric' }).toUpperCase();
398
+ }
399
+
400
+ // "AUG 1 - AUG 12"; a single-day window is just "AUG 12"; whole units are "AUGUST 2026",
401
+ // "SEP 2026 - NOV 2026", "2025" or "2024 - 2025".
359
402
  function rangeSpanLabel(r) {
403
+ const p = periodOf(r.from, r.to);
404
+ if (p?.unit === 'year') return p.a === p.b ? String(p.a) : `${p.a} - ${p.b}`;
405
+ if (p) return p.a === p.b ? monthLabel(p.a) : `${monthLabel(p.a, 'short')} - ${monthLabel(p.b, 'short')}`;
360
406
  return r.from === r.to ? isoDayLabel(r.to) : `${isoDayLabel(r.from)} - ${isoDayLabel(r.to)}`;
361
407
  }
362
408
 
@@ -367,7 +413,15 @@ function rangeSpanLabel(r) {
367
413
  // pluralized as days, and the empty-state article only fits the rolling presets.
368
414
  function rangeText(r, prefix = {}) {
369
415
  const n = normalizeRange(r);
370
- const kind = !n ? 'all' : n.kind === 'custom' ? 'custom' : n.value === 'today' ? 'today' : 'rolling';
416
+ const kind = !n
417
+ ? 'all'
418
+ : n.kind === 'custom'
419
+ ? 'custom'
420
+ : n.value === 'today'
421
+ ? 'today'
422
+ : n.value === 'month' || n.value === 'year'
423
+ ? 'calendar'
424
+ : 'rolling';
371
425
  const base =
372
426
  kind === 'all'
373
427
  ? 'all time'
@@ -375,15 +429,17 @@ function rangeText(r, prefix = {}) {
375
429
  ? rangeSpanLabel(n)
376
430
  : kind === 'today'
377
431
  ? 'today'
378
- : n.value === '24h'
379
- ? '24 hours'
380
- : `${n.value} days`;
432
+ : kind === 'calendar'
433
+ ? `this ${n.value}`
434
+ : n.value === '24h'
435
+ ? '24 hours'
436
+ : `${n.value} days`;
381
437
  return (prefix[kind] || '') + base;
382
438
  }
383
439
 
384
440
  const rangeLabel = (r) => rangeText(r);
385
441
  const rangeScopeLabel = (r) => rangeText(r, { rolling: 'last ' });
386
- const rangeInLabel = (r) => rangeText(r, { all: 'in ', custom: 'in ', rolling: 'in the last ' });
442
+ const rangeInLabel = (r) => rangeText(r, { all: 'in ', custom: 'in ', calendar: 'in ', rolling: 'in the last ' });
387
443
 
388
444
  // Uppercase, for the picker trigger: the preset's own name, or the window's dates.
389
445
  const rangeTriggerLabel = (r) => {
@@ -408,7 +464,11 @@ const rangeCardLabel = (r) => {
408
464
  function isTodayOnlyRange(r) {
409
465
  const n = normalizeRange(r);
410
466
  if (!n) return false;
411
- return n.kind === 'custom' ? n.from === n.to && n.to === todayIso() : n.value === 'today';
467
+ if (n.kind === 'custom') return n.from === n.to && n.to === todayIso();
468
+ const t = todayIso();
469
+ return (
470
+ n.value === 'today' || (n.value === 'month' && t.endsWith('-01')) || (n.value === 'year' && t.endsWith('-01-01'))
471
+ );
412
472
  }
413
473
 
414
474
  function loadSort() {
@@ -536,9 +596,16 @@ function scopeParam() {
536
596
  }
537
597
 
538
598
  // Presets stay on the rolling `range` param, recomputed server-side; a custom window sends its two
539
- // local dates, which take precedence over `range`. Every range-consuming fetch goes through this.
599
+ // local dates, which take precedence over `range`. 'month' and 'year' are the presets resolved here, into
600
+ // the dates of the current month or year so far, so it rolls over on the 1st. Every range-consuming fetch goes
601
+ // through this.
540
602
  function rangeParams(r = dateRange) {
541
- return isCustomRange(r) ? `from=${r.from}&to=${r.to}` : `range=${encodeURIComponent(r.value)}`;
603
+ if (isCustomRange(r)) return `from=${r.from}&to=${r.to}`;
604
+ if (r.value === 'month' || r.value === 'year') {
605
+ const { from, to } = rangePresetSpan(r.value);
606
+ return `from=${from}&to=${to}`;
607
+ }
608
+ return `range=${encodeURIComponent(r.value)}`;
542
609
  }
543
610
 
544
611
  async function fetchOverview() {
@@ -2371,15 +2438,19 @@ function setColorTheme(id) {
2371
2438
  // #region DATE_PICKER
2372
2439
 
2373
2440
  // Presets are sticky: what is stored is the preset, and the server recomputes its rolling window on
2374
- // every request. `days` only previews the span inside the calendar.
2441
+ // every request.
2375
2442
  const RANGE_PRESETS = [
2376
- { value: 'today', label: 'Today', days: 0 },
2377
- { value: '24h', label: 'Last 24h', days: 1 },
2378
- { value: '3', label: '3 Days', days: 3 },
2379
- { value: '7', label: '7 Days', days: 7 },
2380
- { value: '30', label: '30 Days', days: 30 },
2381
- { value: '90', label: '90 Days', days: 90 },
2382
- { value: '365', label: '1 Year', days: 365, cardLabel: '365 Days' },
2443
+ { value: 'today', label: 'Today' },
2444
+ { value: '24h', label: 'Last 24h' },
2445
+ { value: '3', label: '3 Days' },
2446
+ { value: '7', label: '7 Days' },
2447
+ { value: '30', label: '30 Days' },
2448
+ // Calendar month to date. Sticky like the rolling presets, but resolved here (see monthToDate): the
2449
+ // server has no such preset and only ever sees its two dates.
2450
+ { value: 'month', label: 'This Month', cardLabel: 'This Month' },
2451
+ { value: '90', label: '90 Days' },
2452
+ { value: '365', label: '1 Year', cardLabel: '365 Days' },
2453
+ { value: 'year', label: 'This Year', cardLabel: 'This Year' },
2383
2454
  ];
2384
2455
  const RANGE_DOW = ['M', 'T', 'W', 'T', 'F', 'S', 'S'];
2385
2456
  // Two months do not fit a narrow window, so below this the calendar collapses to one. Kept in step
@@ -2412,6 +2483,8 @@ function oneMonthMode() {
2412
2483
  function rangePresetSpan(value) {
2413
2484
  const today = todayIso();
2414
2485
  if (value === '24h') return { from: isoShift(today, -1), to: today };
2486
+ if (value === 'month') return monthToDate();
2487
+ if (value === 'year') return yearSpan(new Date().getFullYear());
2415
2488
  const days = Number(value) || 1;
2416
2489
  return { from: days <= 1 ? today : isoShift(today, -(days - 1)), to: today };
2417
2490
  }
@@ -2453,6 +2526,14 @@ function openRangePicker() {
2453
2526
  // single month it is that month itself.
2454
2527
  const [ay, am] = isoParts(span.to);
2455
2528
  const first = new Date(ay, am - 1 - (oneMonthMode() ? 0 : 1), 1);
2529
+ // A window that is whole months or whole years opens on that grid, so it shows what is picked.
2530
+ const period =
2531
+ applied.kind === 'preset' && applied.value === 'month'
2532
+ ? { unit: 'month', a: span.from.slice(0, 7), b: span.to.slice(0, 7) }
2533
+ : applied.kind === 'preset' && applied.value === 'year'
2534
+ ? { unit: 'year', a: ay, b: ay }
2535
+ : periodOf(span.from, span.to);
2536
+ const thisYear = new Date().getFullYear();
2456
2537
  rangeDraft = {
2457
2538
  from: span.from,
2458
2539
  to: span.to,
@@ -2460,6 +2541,11 @@ function openRangePicker() {
2460
2541
  picking: 'from',
2461
2542
  hover: null,
2462
2543
  month: { y: first.getFullYear(), m: first.getMonth() },
2544
+ mode: period ? period.unit : 'period',
2545
+ // The month grid's year, and the last year of the year grid's page.
2546
+ year: period?.unit === 'month' ? Number(period.a.slice(0, 4)) : ay,
2547
+ yearEnd: period?.unit === 'year' ? Math.min(Math.max(period.b, period.a + 11), thisYear) : thisYear,
2548
+ sel: period ? { unit: period.unit, a: String(period.a), b: String(period.b) } : { unit: null, a: null, b: null },
2463
2549
  };
2464
2550
  document.getElementById('rangePop').classList.add('open');
2465
2551
  document.getElementById('rangeTrigger').classList.add('on');
@@ -2489,8 +2575,116 @@ function closeRangePicker() {
2489
2575
  // selectable days carry data-iso, so the lead padding and the days after today stay inert. It has to
2490
2576
  // be 'mouseover' — 'mouseenter' does not bubble, so it cannot be delegated.
2491
2577
  function onRangeDayClick(e) {
2492
- const iso = e.target.dataset?.iso;
2493
- if (iso) pickRangeDay(iso);
2578
+ const { month, year, iso } = e.target.dataset || {};
2579
+ if (month) pickRangeUnit('month', month);
2580
+ else if (year) pickRangeUnit('year', year);
2581
+ else if (iso) pickRangeDay(iso);
2582
+ }
2583
+
2584
+ // Months and years pick a span the way days do: the first click is the start, the second the end (a
2585
+ // click before the start swaps them), and a third starts over. One click and Apply is a single unit.
2586
+ function pickRangeUnit(unit, value) {
2587
+ const d = rangeDraft;
2588
+ const s = d.sel;
2589
+ d.preset = null;
2590
+ if (s.unit !== unit || !s.a || s.b) d.sel = { unit, a: value, b: null };
2591
+ else d.sel = value < s.a ? { unit, a: value, b: s.a } : { unit, a: s.a, b: value };
2592
+ renderRangePicker();
2593
+ }
2594
+
2595
+ // biome-ignore lint/correctness/noUnusedVariables: called from popover markup
2596
+ function setRangeMode(mode) {
2597
+ const d = rangeDraft;
2598
+ if (!d || d.mode === mode) return;
2599
+ d.mode = mode;
2600
+ if (mode !== 'period' && d.sel.unit !== mode) d.sel = { unit: mode, a: null, b: null };
2601
+ renderRangePicker();
2602
+ }
2603
+
2604
+ // What the month or year selection applies. The running month or year is the sticky preset, so it
2605
+ // keeps following the calendar; any other span is a plain custom window.
2606
+ function selectionRange(sel) {
2607
+ const now = new Date();
2608
+ const b = sel.b || sel.a;
2609
+ if (sel.unit === 'year') {
2610
+ if (sel.a === b && Number(b) === now.getFullYear()) return presetRange('year');
2611
+ return { kind: 'custom', from: yearSpan(Number(sel.a)).from, to: yearSpan(Number(b)).to };
2612
+ }
2613
+ const [ay, am] = isoParts(`${sel.a}-01`);
2614
+ const [by, bm] = isoParts(`${b}-01`);
2615
+ if (sel.a === b && ay === now.getFullYear() && am - 1 === now.getMonth()) return presetRange('month');
2616
+ return { kind: 'custom', from: monthSpan(ay, am - 1).from, to: monthSpan(by, bm - 1).to };
2617
+ }
2618
+
2619
+ function unitIndex(value, mode) {
2620
+ if (mode === 'year') return Number(value);
2621
+ const [y, m] = isoParts(`${value}-01`);
2622
+ return y * 12 + m - 1;
2623
+ }
2624
+
2625
+ function rangeGridStep(step) {
2626
+ const d = rangeDraft;
2627
+ if (d.mode === 'year') d.yearEnd += step * 12;
2628
+ else d.year += step;
2629
+ renderRangePicker();
2630
+ }
2631
+
2632
+ // The month grid (one year, with year arrows) or the year grid (twelve years, paged). Both are
2633
+ // 3 x 4 cells that carry data-month / data-year for the delegated click.
2634
+ function renderRangeUnits(host) {
2635
+ const d = rangeDraft;
2636
+ const now = new Date();
2637
+ const isYear = d.mode === 'year';
2638
+ const first = d.yearEnd - 11;
2639
+ const wrap = document.createElement('div');
2640
+ wrap.className = 'range-cal range-years';
2641
+
2642
+ const head = document.createElement('div');
2643
+ head.className = 'range-cal-head';
2644
+ const step = (dir) => {
2645
+ const btn = document.createElement('button');
2646
+ btn.type = 'button';
2647
+ btn.className = 'range-nav';
2648
+ btn.innerHTML = `<svg viewBox="0 0 10 10" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round">${RANGE_ARROWS[dir]}</svg>`;
2649
+ btn.disabled = dir === 'next' && (isYear ? d.yearEnd : d.year) >= now.getFullYear();
2650
+ btn.addEventListener('click', () => rangeGridStep(dir === 'next' ? 1 : -1));
2651
+ return btn;
2652
+ };
2653
+ const title = document.createElement('span');
2654
+ title.className = 'range-cal-title';
2655
+ title.textContent = isYear ? `${first} - ${d.yearEnd}` : String(d.year);
2656
+ head.append(step('prev'), title, step('next'));
2657
+ wrap.appendChild(head);
2658
+
2659
+ const sel = d.sel.unit === d.mode ? d.sel : { a: null, b: null };
2660
+ const lo = sel.a;
2661
+ const hi = sel.b || sel.a;
2662
+ const grid = document.createElement('div');
2663
+ grid.className = 'range-month-grid';
2664
+ for (let i = 0; i < 12; i++) {
2665
+ const y = isYear ? first + i : d.year;
2666
+ const value = isYear ? String(y) : `${y}-${pad2(i + 1)}`;
2667
+ const btn = document.createElement('button');
2668
+ btn.type = 'button';
2669
+ btn.className = 'range-month';
2670
+ btn.textContent = isYear
2671
+ ? String(y)
2672
+ : new Date(y, i, 1).toLocaleDateString(undefined, { month: 'short' }).toUpperCase();
2673
+ const future = isYear ? y > now.getFullYear() : new Date(y, i, 1) > now;
2674
+ if (future) {
2675
+ btn.disabled = true;
2676
+ btn.classList.add('off');
2677
+ } else {
2678
+ btn.dataset[isYear ? 'year' : 'month'] = value;
2679
+ }
2680
+ if (lo && (value === lo || value === hi)) btn.classList.add('on');
2681
+ else if (lo && value > lo && value < hi) btn.classList.add('in');
2682
+ const current = isYear ? y === now.getFullYear() : y === now.getFullYear() && i === now.getMonth();
2683
+ if (current) btn.classList.add('today');
2684
+ grid.appendChild(btn);
2685
+ }
2686
+ wrap.appendChild(grid);
2687
+ host.appendChild(wrap);
2494
2688
  }
2495
2689
 
2496
2690
  function onRangeDayHover(e) {
@@ -2516,8 +2710,8 @@ function aimRangePicker(which) {
2516
2710
  // biome-ignore lint/correctness/noUnusedVariables: called from popover markup
2517
2711
  function applyRangeDraft() {
2518
2712
  const d = rangeDraft;
2519
- if (!d?.from || !d.to) return;
2520
- const next = { kind: 'custom', from: d.from, to: d.to };
2713
+ if (!d || (d.mode === 'period' ? !d.from || !d.to : !d.sel.a)) return;
2714
+ const next = d.mode === 'period' ? { kind: 'custom', from: d.from, to: d.to } : selectionRange(d.sel);
2521
2715
  closeRangePicker();
2522
2716
  applyRange(next);
2523
2717
  }
@@ -2588,6 +2782,22 @@ function renderRangePicker() {
2588
2782
  b.classList.toggle('on', b.dataset.value === d.preset);
2589
2783
  }
2590
2784
 
2785
+ document.getElementById('rangePop').classList.toggle('unit-mode', d.mode !== 'period');
2786
+ for (const btn of document.querySelectorAll('#rangeMode .range-mode-btn')) {
2787
+ btn.setAttribute('aria-pressed', String(btn.dataset.mode === d.mode));
2788
+ }
2789
+ if (d.mode !== 'period') {
2790
+ const unitHost = document.getElementById('rangeMonths');
2791
+ unitHost.innerHTML = '';
2792
+ renderRangeUnits(unitHost);
2793
+ const { a, b } = d.sel.unit === d.mode ? d.sel : {};
2794
+ const n = a ? Math.abs(unitIndex(b || a, d.mode) - unitIndex(a, d.mode)) + 1 : 0;
2795
+ const noun = d.mode === 'year' ? 'year' : 'month';
2796
+ document.getElementById('rangeSummary').textContent = n ? `${n} ${noun}${n === 1 ? '' : 's'}` : `pick a ${noun}`;
2797
+ document.getElementById('rangeApply').disabled = !a;
2798
+ return;
2799
+ }
2800
+
2591
2801
  const fromBox = document.getElementById('rangeFromBox');
2592
2802
  const toBox = document.getElementById('rangeToBox');
2593
2803
  fromBox.textContent = d.from ? isoDayLabel(d.from) : '—';
package/public/index.html CHANGED
@@ -53,6 +53,11 @@
53
53
  <div class="range-head-label">Shortcuts</div>
54
54
  </div>
55
55
  <div class="range-cal-side">
56
+ <div class="range-mode" id="rangeMode" role="group" aria-label="Pick by">
57
+ <button class="range-mode-btn" data-mode="period" aria-pressed="true" onclick="setRangeMode('period')">Days</button>
58
+ <button class="range-mode-btn" data-mode="month" aria-pressed="false" onclick="setRangeMode('month')">Months</button>
59
+ <button class="range-mode-btn" data-mode="year" aria-pressed="false" onclick="setRangeMode('year')">Years</button>
60
+ </div>
56
61
  <div class="range-fields">
57
62
  <div class="range-field">
58
63
  <span class="range-head-label">From</span>
package/public/style.css CHANGED
@@ -620,6 +620,84 @@ body {
620
620
  filter: none;
621
621
  }
622
622
 
623
+ /* Period | Month | Year switch above the calendar; month and year modes swap the day grid for twelve
624
+ cells and drop the From/To fields. Cells pick a span the way days do, then Apply. */
625
+ .range-mode {
626
+ display: inline-flex;
627
+ margin: 0 2px 8px;
628
+ border: 1px solid var(--border);
629
+ border-radius: 5px;
630
+ overflow: hidden;
631
+ }
632
+ .range-mode-btn {
633
+ border: 0;
634
+ background: var(--bg-surface);
635
+ color: var(--text-tertiary);
636
+ font-family: var(--mono);
637
+ font-size: 11px;
638
+ text-transform: uppercase;
639
+ letter-spacing: 0.03em;
640
+ padding: 4px 12px;
641
+ cursor: pointer;
642
+ }
643
+ .range-mode-btn + .range-mode-btn {
644
+ border-left: 1px solid var(--border);
645
+ }
646
+ .range-mode-btn:hover {
647
+ color: var(--text-primary);
648
+ }
649
+ .range-mode-btn[aria-pressed='true'] {
650
+ background: var(--accent-dim);
651
+ color: var(--accent-text);
652
+ }
653
+
654
+ .range-pop.unit-mode .range-fields {
655
+ display: none;
656
+ }
657
+ .range-years {
658
+ width: 100%;
659
+ min-width: 196px;
660
+ }
661
+ .range-month-grid {
662
+ display: grid;
663
+ grid-template-columns: repeat(3, 1fr);
664
+ gap: 4px;
665
+ }
666
+ .range-month {
667
+ height: 34px;
668
+ border: 1px solid var(--border);
669
+ border-radius: 5px;
670
+ background: var(--bg-surface);
671
+ color: var(--text-secondary);
672
+ font-family: var(--mono);
673
+ font-size: 11px;
674
+ letter-spacing: 0.04em;
675
+ cursor: pointer;
676
+ position: relative;
677
+ }
678
+ .range-month:hover:not(.off) {
679
+ border-color: var(--accent);
680
+ color: var(--text-primary);
681
+ }
682
+ .range-month.today {
683
+ color: var(--accent-text);
684
+ }
685
+ .range-month.in {
686
+ background: var(--accent-dim);
687
+ color: var(--text-primary);
688
+ }
689
+ .range-month.on {
690
+ background: var(--accent);
691
+ border-color: var(--accent);
692
+ color: #fff;
693
+ font-weight: 500;
694
+ }
695
+ .range-month.off {
696
+ color: var(--text-muted);
697
+ opacity: 0.5;
698
+ cursor: default;
699
+ }
700
+
623
701
  /* #endregion */
624
702
 
625
703
  /* #region LAYOUT */