claude-code-cost 0.14.0 → 0.15.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/public/app.js CHANGED
@@ -24,7 +24,9 @@ const DEFAULT_SORT = {
24
24
  sessions: { field: 'lastTimestamp', order: 'desc' },
25
25
  };
26
26
  const viewSort = structuredClone(DEFAULT_SORT);
27
- let dateRange = 3;
27
+ // A tagged union: a rolling preset the server recomputes per request, or a concrete window of
28
+ // two local dates. Persisted as JSON under cc-cost:range (see loadDateRange).
29
+ let dateRange = { kind: 'preset', value: '3' };
28
30
  const charts = {};
29
31
  let lastRenderHash = {};
30
32
  let navCounter = 0;
@@ -100,6 +102,43 @@ function bucketLabel(key, bucket) {
100
102
  return new Date(`${key}T00:00:00`).toLocaleDateString(undefined, { month: 'short', day: 'numeric' });
101
103
  }
102
104
 
105
+ // Local calendar dates as YYYY-MM-DD: the shape the range API takes, comparable with < and >.
106
+ const ISO_DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
107
+
108
+ function isoDate(d) {
109
+ return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
110
+ }
111
+
112
+ function todayIso() {
113
+ return isoDate(new Date());
114
+ }
115
+
116
+ function isoParts(iso) {
117
+ return iso.split('-').map(Number);
118
+ }
119
+
120
+ function isoShift(iso, days) {
121
+ const [y, m, d] = isoParts(iso);
122
+ return isoDate(new Date(y, m - 1, d + days));
123
+ }
124
+
125
+ // Inclusive, so a single day counts as 1. Midday avoids a DST shift landing on a boundary.
126
+ function isoDayCount(from, to) {
127
+ const [ay, am, ad] = isoParts(from);
128
+ const [by, bm, bd] = isoParts(to);
129
+ return Math.round((new Date(by, bm - 1, bd, 12) - new Date(ay, am - 1, ad, 12)) / 86400000) + 1;
130
+ }
131
+
132
+ // "AUG 12", carrying a two-digit year only when the date falls outside the current one: "DEC 28 '25".
133
+ function isoDayLabel(iso) {
134
+ const [y] = isoParts(iso);
135
+ const yearTag = y === new Date().getFullYear() ? '' : ` '${String(y).slice(2)}`;
136
+ const dayLabel = new Date(`${iso}T00:00:00`)
137
+ .toLocaleDateString(undefined, { month: 'short', day: 'numeric' })
138
+ .toUpperCase();
139
+ return `${dayLabel}${yearTag}`;
140
+ }
141
+
103
142
  function costSeriesTitle(series) {
104
143
  return series?.bucket === 'hour' ? 'Hourly Cost' : 'Daily Cost';
105
144
  }
@@ -189,15 +228,58 @@ function getUrlState() {
189
228
  };
190
229
  }
191
230
 
231
+ const DEFAULT_RANGE_PRESET = '3';
232
+
233
+ function presetRange(value) {
234
+ return { kind: 'preset', value: String(value) };
235
+ }
236
+
237
+ function presetDef(value) {
238
+ return RANGE_PRESETS.find((p) => p.value === String(value));
239
+ }
240
+
241
+ function isPresetValue(v) {
242
+ return !!presetDef(v);
243
+ }
244
+
245
+ function isCustomRange(r) {
246
+ return r?.kind === 'custom';
247
+ }
248
+
249
+ // '1 DAY' is gone: under calendar semantics it would have duplicated TODAY, so the rolling day it
250
+ // used to mean is now '24h'. Without this, a stored "1" stops being a preset value and silently
251
+ // lands on the default instead of on the shortcut that kept its meaning.
252
+ function migrateStoredPreset(value) {
253
+ const s = String(value);
254
+ return s === '1' ? '24h' : s;
255
+ }
256
+
257
+ // Reads the JSON tagged union and the legacy bare "3" / "today" scalar that predates it: the key is
258
+ // a preference, so clearLocalCache() never evicts it and old values outlive any cache clear.
259
+ // Anything unrecognized returns null, which lands on the default preset.
260
+ function parseStoredRange(raw) {
261
+ if (!raw) return null;
262
+ let v;
263
+ try {
264
+ v = JSON.parse(raw);
265
+ } catch {
266
+ v = raw; // the legacy bare 'today' is not valid JSON
267
+ }
268
+ if (v?.kind === 'custom') {
269
+ return ISO_DATE_RE.test(v.from) && ISO_DATE_RE.test(v.to) && v.from <= v.to
270
+ ? { kind: 'custom', from: v.from, to: v.to }
271
+ : null;
272
+ }
273
+ const s = migrateStoredPreset(v?.kind === 'preset' ? v.value : v);
274
+ return isPresetValue(s) ? presetRange(s) : null;
275
+ }
276
+
192
277
  function loadDateRange() {
193
- const v = localStorage.getItem('cc-cost:range');
194
- if (!v) return 3;
195
- if (v === 'today') return 'today';
196
- return parseInt(v, 10) || 3;
278
+ return parseStoredRange(localStorage.getItem('cc-cost:range')) || presetRange(DEFAULT_RANGE_PRESET);
197
279
  }
198
280
 
199
281
  function saveDateRange(val) {
200
- localStorage.setItem('cc-cost:range', String(val));
282
+ localStorage.setItem('cc-cost:range', JSON.stringify(val));
201
283
  }
202
284
 
203
285
  function loadScope() {
@@ -222,12 +304,79 @@ function saveScope() {
222
304
  }
223
305
  }
224
306
 
225
- function rangeLabel(r) {
226
- return r === 'today' ? 'today' : `${r} days`;
227
- }
307
+ // The range reaches these labels either as the client's tagged union or as the shape the server
308
+ // echoes back on the session detail payload: 'today', N days, null for all time, or a bare
309
+ // { from, to } window.
310
+ function normalizeRange(r) {
311
+ if (r == null) return null;
312
+ if (typeof r === 'object') {
313
+ if (r.kind === 'preset' && isPresetValue(r.value)) return presetRange(r.value);
314
+ if (r.from && r.to) return { kind: 'custom', from: r.from, to: r.to };
315
+ return null;
316
+ }
317
+ if (isPresetValue(r)) return presetRange(r);
318
+ // A legacy `range=1` from a bookmarked URL: the server reads it as one calendar day, which is
319
+ // today. Without this it is a positive integer that names no preset, so it would label as
320
+ // "all time" — the shape normalizeRange returns for something it does not recognize.
321
+ if (String(r) === '1') return presetRange('today');
322
+ const n = Number(r);
323
+ return Number.isFinite(n) && n > 0 ? presetRange(n) : null;
324
+ }
325
+
326
+ // "AUG 1 - AUG 12"; a single-day window is just "AUG 12".
327
+ function rangeSpanLabel(r) {
328
+ return r.from === r.to ? isoDayLabel(r.to) : `${isoDayLabel(r.from)} - ${isoDayLabel(r.to)}`;
329
+ }
330
+
331
+ // Every label variant is the same four-way classification of the range — all time, a custom window,
332
+ // today, a rolling preset — with one phrase per class, so only the phrasing lives in the callers:
333
+ // presets keep their rolling phrasing ("last 7 days"), while a custom window is named by its dates,
334
+ // where a "last" prefix would be nonsense. The rolling preset measured in hours must never be
335
+ // pluralized as days, and the empty-state article only fits the rolling presets.
336
+ function rangeText(r, prefix = {}) {
337
+ const n = normalizeRange(r);
338
+ const kind = !n ? 'all' : n.kind === 'custom' ? 'custom' : n.value === 'today' ? 'today' : 'rolling';
339
+ const base =
340
+ kind === 'all'
341
+ ? 'all time'
342
+ : kind === 'custom'
343
+ ? rangeSpanLabel(n)
344
+ : kind === 'today'
345
+ ? 'today'
346
+ : n.value === '24h'
347
+ ? '24 hours'
348
+ : `${n.value} days`;
349
+ return (prefix[kind] || '') + base;
350
+ }
351
+
352
+ const rangeLabel = (r) => rangeText(r);
353
+ const rangeScopeLabel = (r) => rangeText(r, { rolling: 'last ' });
354
+ const rangeInLabel = (r) => rangeText(r, { all: 'in ', custom: 'in ', rolling: 'in the last ' });
355
+
356
+ // Uppercase, for the picker trigger: the preset's own name, or the window's dates.
357
+ const rangeTriggerLabel = (r) => {
358
+ const n = normalizeRange(r) || presetRange(DEFAULT_RANGE_PRESET);
359
+ if (n.kind === 'custom') return rangeSpanLabel(n);
360
+ const def = presetDef(n.value);
361
+ return (def ? def.label : rangeText(n)).toUpperCase();
362
+ };
363
+
364
+ // The overview's window card: "3 Days" for an N-day preset, the preset's own name for a clock preset
365
+ // ("Last 24h"), the date span for a custom window. '1 Year' is the one name that does not fit the
366
+ // card, hence cardLabel.
367
+ const rangeCardLabel = (r) => {
368
+ const n = normalizeRange(r);
369
+ if (!n) return 'All Time';
370
+ if (n.kind === 'custom') return rangeSpanLabel(n);
371
+ const def = presetDef(n.value);
372
+ return def ? def.cardLabel || def.label : `${n.value} Days`;
373
+ };
228
374
 
229
- function rangeScopeLabel(r) {
230
- return r === 'today' ? rangeLabel(r) : `last ${rangeLabel(r)}`;
375
+ // That card duplicates the Today card when the window is exactly today, so it is dropped instead.
376
+ function isTodayOnlyRange(r) {
377
+ const n = normalizeRange(r);
378
+ if (!n) return false;
379
+ return n.kind === 'custom' ? n.from === n.to && n.to === todayIso() : n.value === 'today';
231
380
  }
232
381
 
233
382
  function loadSort() {
@@ -267,7 +416,7 @@ function updateUrl() {
267
416
  // #region FETCH
268
417
 
269
418
  const BROWSER_CACHE_TTL = 5 * 60 * 1000; // 5 min
270
- const CACHE_VERSION = 4;
419
+ const CACHE_VERSION = 6;
271
420
  let forceRefresh = false;
272
421
  // Age of the data on screen, for the auto-refresh staleness check. A cache hit carries its own
273
422
  // timestamp forward, so a reload with a warm cache doesn't look freshly fetched.
@@ -348,8 +497,14 @@ function scopeParam() {
348
497
  return scopeProject ? `&project=${encodeURIComponent(scopeProject)}` : '';
349
498
  }
350
499
 
500
+ // Presets stay on the rolling `range` param, recomputed server-side; a custom window sends its two
501
+ // local dates, which take precedence over `range`. Every range-consuming fetch goes through this.
502
+ function rangeParams(r = dateRange) {
503
+ return isCustomRange(r) ? `from=${r.from}&to=${r.to}` : `range=${encodeURIComponent(r.value)}`;
504
+ }
505
+
351
506
  async function fetchOverview() {
352
- overviewData = await fetchJSON(`/api/overview?range=${dateRange}${scopeParam()}`);
507
+ overviewData = await fetchJSON(`/api/overview?${rangeParams()}${scopeParam()}`);
353
508
  }
354
509
 
355
510
  // Fire-and-forget label upgrade: /api/projects/:path/sessions carries no project name, so ask
@@ -357,7 +512,7 @@ async function fetchOverview() {
357
512
  async function resolveScopeName() {
358
513
  const target = scopeProject;
359
514
  try {
360
- const rows = await fetchJSON(`/api/projects?range=${dateRange}${scopeParam()}`);
515
+ const rows = await fetchJSON(`/api/projects?${rangeParams()}${scopeParam()}`);
361
516
  const name = rows?.[0]?.encodedPath === target ? rows[0].name : null;
362
517
  if (!name || scopeProject !== target) return;
363
518
  scopeProjectName = name;
@@ -374,18 +529,18 @@ async function resolveScopeName() {
374
529
  }
375
530
 
376
531
  async function fetchProjects() {
377
- projectsData = await fetchJSON(`/api/projects?range=${dateRange}${scopeParam()}`);
532
+ projectsData = await fetchJSON(`/api/projects?${rangeParams()}${scopeParam()}`);
378
533
  }
379
534
 
380
535
  async function fetchSessions(encodedPath) {
381
- const data = await fetchJSON(`/api/projects/${encodeURIComponent(encodedPath)}/sessions?range=${dateRange}`, true);
536
+ const data = await fetchJSON(`/api/projects/${encodeURIComponent(encodedPath)}/sessions?${rangeParams()}`, true);
382
537
  sessionsData = data.sessions;
383
538
  sessionsCostSeries = data.costSeries;
384
539
  sessionsModelDistribution = data.modelDistribution || [];
385
540
  }
386
541
 
387
542
  async function fetchSessionDetail(sessionId) {
388
- sessionDetailData = await fetchJSON(`/api/sessions/${encodeURIComponent(sessionId)}?range=${dateRange}`, true);
543
+ sessionDetailData = await fetchJSON(`/api/sessions/${encodeURIComponent(sessionId)}?${rangeParams()}`, true);
389
544
  // Populate project context when opening via deep link (no project in URL)
390
545
  if (sessionDetailData && !currentProjectPath) {
391
546
  currentProjectPath = sessionDetailData.encodedProjectPath;
@@ -421,7 +576,7 @@ function renderOverview() {
421
576
  ${scopeIndicator()}
422
577
  <div class="empty-state">
423
578
  <div class="empty-icon">$</div>
424
- <div>No usage for ${esc(scopeProjectName || scopeProject)} in the last ${rangeLabel(dateRange)}</div>
579
+ <div>No usage for ${esc(scopeProjectName || scopeProject)} ${esc(rangeInLabel(dateRange))}</div>
425
580
  <div>Clear the project scope to see everything.</div>
426
581
  </div>
427
582
  </div>`;
@@ -432,16 +587,23 @@ function renderOverview() {
432
587
  <div class="dashboard-content">
433
588
  ${scopeIndicator()}
434
589
  <div class="cards-row">
590
+ ${
591
+ // Null rather than 0 when the window ends before today: a zero here would read as
592
+ // "nothing spent today" instead of "today is outside the selected window".
593
+ s.todayCost == null
594
+ ? ''
595
+ : `
435
596
  <div class="stat-card">
436
597
  <div class="card-label">Today</div>
437
598
  <div class="card-value cost">${formatCost(s.todayCost)}</div>
438
- </div>
599
+ </div>`
600
+ }
439
601
  ${
440
- dateRange === 'today'
602
+ isTodayOnlyRange(dateRange)
441
603
  ? ''
442
604
  : `
443
605
  <div class="stat-card">
444
- <div class="card-label">${dateRange} Days</div>
606
+ <div class="card-label">${esc(rangeCardLabel(dateRange))}</div>
445
607
  <div class="card-value cost">${formatCost(s.totalCost)}</div>
446
608
  </div>`
447
609
  }
@@ -504,7 +666,7 @@ function renderOverview() {
504
666
 
505
667
  // Render charts after DOM is ready
506
668
  requestAnimationFrame(() => {
507
- renderCostChart(costSeries);
669
+ renderCostChart(costSeries, 'costChart', 'cost', models);
508
670
  renderModelChart(models);
509
671
  });
510
672
  }
@@ -534,7 +696,7 @@ function renderProjects() {
534
696
  <div class="empty-icon">$</div>
535
697
  ${
536
698
  scopeProject
537
- ? `<div>No usage for ${esc(scopeProjectName || scopeProject)} in the last ${rangeLabel(dateRange)}</div>
699
+ ? `<div>No usage for ${esc(scopeProjectName || scopeProject)} ${esc(rangeInLabel(dateRange))}</div>
538
700
  <div>Clear the project scope to see everything.</div>`
539
701
  : `<div>No project data found</div>
540
702
  <div>Make sure Claude Code session files exist in ~/.claude/projects/</div>`
@@ -654,7 +816,7 @@ function renderSessions() {
654
816
  </div>`;
655
817
 
656
818
  requestAnimationFrame(() => {
657
- renderCostChart(sessionsCostSeries, 'sessionsCostChart', 'sessionsCost');
819
+ renderCostChart(sessionsCostSeries, 'sessionsCostChart', 'sessionsCost', sessionsModelDistribution || []);
658
820
  renderModelChart(sessionsModelDistribution || [], 'sessionsModelChart', 'sessionsModel');
659
821
  });
660
822
  }
@@ -822,6 +984,11 @@ function getChartColors() {
822
984
  };
823
985
  }
824
986
 
987
+ // Single source of the series palette so per-model colors match across charts.
988
+ function chartPalette(c) {
989
+ return [c.chart1, c.chart2, c.chart3, c.chart4, c.chart5, c.chart6];
990
+ }
991
+
825
992
  // Translucent fill from a hex color so chart bars read as a quiet wash, not a solid block.
826
993
  function hexToRgba(hex, alpha) {
827
994
  const h = hex.replace('#', '');
@@ -866,7 +1033,7 @@ function destroyChart(id) {
866
1033
  }
867
1034
  }
868
1035
 
869
- function renderCostChart(series, canvasId = 'costChart', chartKey = 'cost') {
1036
+ function renderCostChart(series, canvasId = 'costChart', chartKey = 'cost', distribution = []) {
870
1037
  const points = series?.points;
871
1038
  const canvas = document.getElementById(canvasId);
872
1039
  if (!canvas || !points?.length) return;
@@ -875,20 +1042,32 @@ function renderCostChart(series, canvasId = 'costChart', chartKey = 'cost') {
875
1042
  const c = getChartColors();
876
1043
  const defaults = chartDefaults();
877
1044
 
1045
+ // Stack order follows modelDistribution so segment colors line up with the Cost by Model
1046
+ // chart rendered next to it. 'other' (synthetic models) is absent from the distribution
1047
+ // and lands at the end.
1048
+ const present = new Set();
1049
+ for (const p of points) {
1050
+ for (const m in p.byModel) if (p.byModel[m] > 0) present.add(m);
1051
+ }
1052
+ const models = distribution.filter((d) => present.has(d.model)).map((d) => d.model);
1053
+ for (const m of present) if (!models.includes(m)) models.push(m);
1054
+ const palette = chartPalette(c);
1055
+
1056
+ const datasets = models.map((m, i) => ({
1057
+ label: shortModel(m),
1058
+ data: points.map((p) => p.byModel?.[m] || 0),
1059
+ backgroundColor: hexToRgba(palette[i % palette.length], 0.5),
1060
+ borderColor: palette[i % palette.length],
1061
+ borderWidth: 1.5,
1062
+ borderRadius: 2,
1063
+ stack: 'cost',
1064
+ }));
1065
+
878
1066
  charts[chartKey] = new Chart(canvas, {
879
1067
  type: 'bar',
880
1068
  data: {
881
1069
  labels: points.map((p) => bucketLabel(p.key, series.bucket)),
882
- datasets: [
883
- {
884
- label: costSeriesTitle(series),
885
- data: points.map((p) => p.cost),
886
- backgroundColor: c.chartFill,
887
- borderColor: c.accent,
888
- borderWidth: 1.5,
889
- borderRadius: 3,
890
- },
891
- ],
1070
+ datasets,
892
1071
  },
893
1072
  options: {
894
1073
  ...defaults,
@@ -896,6 +1075,12 @@ function renderCostChart(series, canvasId = 'costChart', chartKey = 'cost') {
896
1075
  events: [],
897
1076
  plugins: {
898
1077
  ...defaults.plugins,
1078
+ // events: [] disables tooltips, so the legend is the only place segment names show.
1079
+ legend: {
1080
+ display: models.length > 1,
1081
+ position: 'bottom',
1082
+ labels: { color: c.text, font: { size: 9 }, boxWidth: 8, boxHeight: 8 },
1083
+ },
899
1084
  tooltip: {
900
1085
  ...defaults.plugins.tooltip,
901
1086
  callbacks: { label: (ctx) => `$${ctx.parsed.y.toFixed(2)}` },
@@ -903,8 +1088,10 @@ function renderCostChart(series, canvasId = 'costChart', chartKey = 'cost') {
903
1088
  },
904
1089
  scales: {
905
1090
  ...defaults.scales,
1091
+ x: { ...defaults.scales.x, stacked: true },
906
1092
  y: {
907
1093
  ...defaults.scales.y,
1094
+ stacked: true,
908
1095
  ticks: { ...defaults.scales.y.ticks, callback: (v) => `$${v.toFixed(2)}` },
909
1096
  },
910
1097
  },
@@ -918,7 +1105,7 @@ function renderModelChart(models, canvasId = 'modelChart', chartKey = 'model') {
918
1105
  destroyChart(chartKey);
919
1106
 
920
1107
  const colors = getChartColors();
921
- const palette = [colors.chart1, colors.chart2, colors.chart3, colors.chart4, colors.chart5, colors.chart6];
1108
+ const palette = chartPalette(colors);
922
1109
  const defaults = chartDefaults();
923
1110
  const total = models.reduce((s, m) => s + m.cost, 0);
924
1111
 
@@ -1154,6 +1341,326 @@ function setColorTheme(id) {
1154
1341
 
1155
1342
  // #endregion
1156
1343
 
1344
+ // #region DATE_PICKER
1345
+
1346
+ // Presets are sticky: what is stored is the preset, and the server recomputes its rolling window on
1347
+ // every request. `days` only previews the span inside the calendar.
1348
+ const RANGE_PRESETS = [
1349
+ { value: 'today', label: 'Today', days: 0 },
1350
+ { value: '24h', label: 'Last 24h', days: 1 },
1351
+ { value: '3', label: '3 Days', days: 3 },
1352
+ { value: '7', label: '7 Days', days: 7 },
1353
+ { value: '30', label: '30 Days', days: 30 },
1354
+ { value: '90', label: '90 Days', days: 90 },
1355
+ { value: '365', label: '1 Year', days: 365, cardLabel: '365 Days' },
1356
+ ];
1357
+ const RANGE_DOW = ['M', 'T', 'W', 'T', 'F', 'S', 'S'];
1358
+ // Two months do not fit a narrow window, so below this the calendar collapses to one. Kept in step
1359
+ // with the same breakpoint in style.css.
1360
+ const ONE_MONTH_QUERY = '(max-width: 760px)';
1361
+ // One live MediaQueryList: matchMedia() hands back a new object each call, so add/removeEventListener
1362
+ // have to share this one or the listener never comes off.
1363
+ const oneMonthMql = window.matchMedia(ONE_MONTH_QUERY);
1364
+ const RANGE_ARROWS = {
1365
+ prev: '<path d="M6.5 1L2.5 5l4 4"/>',
1366
+ next: '<path d="M3.5 1l4 4-4 4"/>',
1367
+ };
1368
+
1369
+ // Non-null only while the popover is open — it is both the draft and the open flag. `picking` is
1370
+ // which end the next day click lands on; `hover` previews the span before the second click.
1371
+ let rangeDraft = null;
1372
+
1373
+ function isRangePickerOpen() {
1374
+ return !!rangeDraft;
1375
+ }
1376
+
1377
+ function oneMonthMode() {
1378
+ return oneMonthMql.matches;
1379
+ }
1380
+
1381
+ // What a preset covers, for highlighting only. '24h' is named here because its span is not a day
1382
+ // count: it straddles the two calendar days a rolling day touches. Everything else is the last N
1383
+ // calendar days ending today, which is now exactly the window the server fetches — 'today' included,
1384
+ // since a span of one day or less is today itself.
1385
+ function rangePresetSpan(value) {
1386
+ const today = todayIso();
1387
+ if (value === '24h') return { from: isoShift(today, -1), to: today };
1388
+ const days = Number(value) || 1;
1389
+ return { from: days <= 1 ? today : isoShift(today, -(days - 1)), to: today };
1390
+ }
1391
+
1392
+ function buildRangePresets() {
1393
+ const host = document.getElementById('rangePresets');
1394
+ if (!host) return;
1395
+ for (const p of RANGE_PRESETS) {
1396
+ const b = document.createElement('button');
1397
+ b.type = 'button';
1398
+ b.className = 'range-preset';
1399
+ b.dataset.value = p.value;
1400
+ b.textContent = p.label;
1401
+ // A shortcut is one click, like the dropdown it replaces: apply and close, no Apply button.
1402
+ b.addEventListener('click', () => {
1403
+ closeRangePicker();
1404
+ applyRange(presetRange(p.value));
1405
+ });
1406
+ host.appendChild(b);
1407
+ }
1408
+ }
1409
+
1410
+ function renderRangeTrigger() {
1411
+ const el = document.getElementById('rangeTriggerLabel');
1412
+ if (el) el.textContent = rangeTriggerLabel(dateRange);
1413
+ }
1414
+
1415
+ // biome-ignore lint/correctness/noUnusedVariables: called from topbar markup
1416
+ function toggleRangePicker(e) {
1417
+ e?.stopPropagation();
1418
+ if (isRangePickerOpen()) closeRangePicker();
1419
+ else openRangePicker();
1420
+ }
1421
+
1422
+ function openRangePicker() {
1423
+ const applied = normalizeRange(dateRange) || presetRange(DEFAULT_RANGE_PRESET);
1424
+ const span = applied.kind === 'custom' ? { from: applied.from, to: applied.to } : rangePresetSpan(applied.value);
1425
+ // The left pane shows the month before the window's end, so today sits in the right one; with a
1426
+ // single month it is that month itself.
1427
+ const [ay, am] = isoParts(span.to);
1428
+ const first = new Date(ay, am - 1 - (oneMonthMode() ? 0 : 1), 1);
1429
+ rangeDraft = {
1430
+ from: span.from,
1431
+ to: span.to,
1432
+ preset: applied.kind === 'custom' ? null : applied.value,
1433
+ picking: 'from',
1434
+ hover: null,
1435
+ month: { y: first.getFullYear(), m: first.getMonth() },
1436
+ };
1437
+ document.getElementById('rangePop').classList.add('open');
1438
+ document.getElementById('rangeTrigger').classList.add('on');
1439
+ // Capture phase: a day click re-renders the grid and detaches its own button, so by the bubble
1440
+ // phase the target is no longer inside #rangePicker and would read as an outside click.
1441
+ document.addEventListener('click', onRangePickerOutsideClick, true);
1442
+ const months = document.getElementById('rangeMonths');
1443
+ months.addEventListener('click', onRangeDayClick);
1444
+ months.addEventListener('mouseover', onRangeDayHover);
1445
+ oneMonthMql.addEventListener('change', renderRangePicker);
1446
+ renderRangePicker();
1447
+ }
1448
+
1449
+ function closeRangePicker() {
1450
+ if (!rangeDraft) return;
1451
+ rangeDraft = null;
1452
+ document.getElementById('rangePop').classList.remove('open');
1453
+ document.getElementById('rangeTrigger').classList.remove('on');
1454
+ document.removeEventListener('click', onRangePickerOutsideClick, true);
1455
+ const months = document.getElementById('rangeMonths');
1456
+ months.removeEventListener('click', onRangeDayClick);
1457
+ months.removeEventListener('mouseover', onRangeDayHover);
1458
+ oneMonthMql.removeEventListener('change', renderRangePicker);
1459
+ }
1460
+
1461
+ // Both grids are delegated: one listener pair on #rangeMonths instead of two per day cell. Only the
1462
+ // selectable days carry data-iso, so the lead padding and the days after today stay inert. It has to
1463
+ // be 'mouseover' — 'mouseenter' does not bubble, so it cannot be delegated.
1464
+ function onRangeDayClick(e) {
1465
+ const iso = e.target.dataset?.iso;
1466
+ if (iso) pickRangeDay(iso);
1467
+ }
1468
+
1469
+ function onRangeDayHover(e) {
1470
+ const iso = e.target.dataset?.iso;
1471
+ if (iso && rangeDraft?.from && !rangeDraft.to && rangeDraft.hover !== iso) {
1472
+ rangeDraft.hover = iso;
1473
+ paintRangeSpan();
1474
+ }
1475
+ }
1476
+
1477
+ // Outside click cancels: the draft is dropped and the applied range stays.
1478
+ function onRangePickerOutsideClick(e) {
1479
+ if (!document.getElementById('rangePicker').contains(e.target)) closeRangePicker();
1480
+ }
1481
+
1482
+ // biome-ignore lint/correctness/noUnusedVariables: called from popover markup
1483
+ function aimRangePicker(which) {
1484
+ if (!rangeDraft) return;
1485
+ rangeDraft.picking = which;
1486
+ renderRangePicker();
1487
+ }
1488
+
1489
+ // biome-ignore lint/correctness/noUnusedVariables: called from popover markup
1490
+ function applyRangeDraft() {
1491
+ const d = rangeDraft;
1492
+ if (!d?.from || !d.to) return;
1493
+ const next = { kind: 'custom', from: d.from, to: d.to };
1494
+ closeRangePicker();
1495
+ applyRange(next);
1496
+ }
1497
+
1498
+ function pickRangeDay(iso) {
1499
+ const d = rangeDraft;
1500
+ d.preset = null;
1501
+ if (d.picking === 'from' || !d.from) {
1502
+ d.from = iso;
1503
+ d.to = null;
1504
+ d.picking = 'to';
1505
+ } else if (iso < d.from) {
1506
+ // A second click before the first flips the pair instead of refusing it.
1507
+ d.to = d.from;
1508
+ d.from = iso;
1509
+ d.picking = 'from';
1510
+ } else {
1511
+ d.to = iso;
1512
+ d.picking = 'from';
1513
+ }
1514
+ d.hover = null;
1515
+ renderRangePicker();
1516
+ }
1517
+
1518
+ function rangeMonthStep(step) {
1519
+ const c = new Date(rangeDraft.month.y, rangeDraft.month.m + step, 1);
1520
+ rangeDraft.month = { y: c.getFullYear(), m: c.getMonth() };
1521
+ renderRangePicker();
1522
+ }
1523
+
1524
+ // There is no cost data ahead of today, so the calendar stops at the current month.
1525
+ function rangeNextDisabled() {
1526
+ const last = new Date(rangeDraft.month.y, rangeDraft.month.m + (oneMonthMode() ? 0 : 1), 1);
1527
+ const now = new Date();
1528
+ return last >= new Date(now.getFullYear(), now.getMonth(), 1);
1529
+ }
1530
+
1531
+ // The highlighted span: the picked window, or from -> the hovered day while the second end is open.
1532
+ function rangeDraftSpan() {
1533
+ const d = rangeDraft;
1534
+ if (!d?.from) return [null, null];
1535
+ if (d.to) return [d.from, d.to];
1536
+ if (!d.hover) return [d.from, d.from];
1537
+ return d.hover < d.from ? [d.hover, d.from] : [d.from, d.hover];
1538
+ }
1539
+
1540
+ // The span highlight is four classes on day cells that already exist, so a hover repaint toggles
1541
+ // them in place instead of rebuilding both grids. Sole owner of those classes — buildRangeMonth
1542
+ // leaves them to the paint pass that follows it, so the two can never drift apart.
1543
+ function paintRangeSpan() {
1544
+ const [a, b] = rangeDraftSpan();
1545
+ for (const btn of document.querySelectorAll('#rangeMonths .range-day[data-iso]')) {
1546
+ const iso = btn.dataset.iso;
1547
+ const inSpan = !!(a && b && iso >= a && iso <= b);
1548
+ const edge = inSpan && (iso === a || iso === b);
1549
+ btn.classList.toggle('edge', edge);
1550
+ btn.classList.toggle('in', inSpan && !edge);
1551
+ btn.classList.toggle('start', inSpan && !edge && isoShift(iso, -1) === a);
1552
+ btn.classList.toggle('end', inSpan && !edge && isoShift(iso, 1) === b);
1553
+ }
1554
+ }
1555
+
1556
+ function renderRangePicker() {
1557
+ const d = rangeDraft;
1558
+ if (!d) return;
1559
+
1560
+ for (const b of document.querySelectorAll('#rangePresets .range-preset')) {
1561
+ b.classList.toggle('on', b.dataset.value === d.preset);
1562
+ }
1563
+
1564
+ const fromBox = document.getElementById('rangeFromBox');
1565
+ const toBox = document.getElementById('rangeToBox');
1566
+ fromBox.textContent = d.from ? isoDayLabel(d.from) : '—';
1567
+ toBox.textContent = d.to ? isoDayLabel(d.to) : '—';
1568
+ fromBox.classList.toggle('empty', !d.from);
1569
+ toBox.classList.toggle('empty', !d.to);
1570
+ fromBox.classList.toggle('active', d.picking === 'from');
1571
+ toBox.classList.toggle('active', d.picking === 'to');
1572
+
1573
+ const [a, b] = rangeDraftSpan();
1574
+ const days = d.from && d.to ? isoDayCount(a, b) : 0;
1575
+ document.getElementById('rangeSummary').textContent = days
1576
+ ? `${days} ${days === 1 ? 'day' : 'days'}`
1577
+ : 'pick an end date';
1578
+ document.getElementById('rangeApply').disabled = !(d.from && d.to);
1579
+
1580
+ const host = document.getElementById('rangeMonths');
1581
+ host.innerHTML = '';
1582
+ const single = oneMonthMode();
1583
+ const first = new Date(d.month.y, d.month.m, 1);
1584
+ host.appendChild(buildRangeMonth(first.getFullYear(), first.getMonth(), { prev: true, next: single }));
1585
+ if (!single) {
1586
+ const second = new Date(d.month.y, d.month.m + 1, 1);
1587
+ host.appendChild(buildRangeMonth(second.getFullYear(), second.getMonth(), { prev: false, next: true }));
1588
+ }
1589
+ paintRangeSpan();
1590
+ }
1591
+
1592
+ function rangeNavButton(dir) {
1593
+ const step = dir === 'next' ? 1 : -1;
1594
+ const btn = document.createElement('button');
1595
+ btn.type = 'button';
1596
+ btn.className = 'range-nav';
1597
+ btn.innerHTML = `<svg viewBox="0 0 10 10" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round">${RANGE_ARROWS[dir]}</svg>`;
1598
+ if (step > 0) btn.disabled = rangeNextDisabled();
1599
+ btn.addEventListener('click', () => rangeMonthStep(step));
1600
+ return btn;
1601
+ }
1602
+
1603
+ // Holds the title centred on the side that carries no arrow.
1604
+ function rangeNavGap() {
1605
+ const gap = document.createElement('span');
1606
+ gap.className = 'range-nav-gap';
1607
+ return gap;
1608
+ }
1609
+
1610
+ function buildRangeMonth(y, m, nav) {
1611
+ const wrap = document.createElement('div');
1612
+ wrap.className = 'range-cal';
1613
+
1614
+ const title = new Date(y, m, 1).toLocaleDateString(undefined, { month: 'short' }).toUpperCase();
1615
+
1616
+ const head = document.createElement('div');
1617
+ head.className = 'range-cal-head';
1618
+ head.appendChild(nav.prev ? rangeNavButton('prev') : rangeNavGap());
1619
+ const titleEl = document.createElement('span');
1620
+ titleEl.className = 'range-cal-title';
1621
+ titleEl.textContent = `${title} ${y}`;
1622
+ head.appendChild(titleEl);
1623
+ head.appendChild(nav.next ? rangeNavButton('next') : rangeNavGap());
1624
+ wrap.appendChild(head);
1625
+
1626
+ const dow = document.createElement('div');
1627
+ dow.className = 'range-dow';
1628
+ dow.innerHTML = RANGE_DOW.map((d) => `<span>${d}</span>`).join('');
1629
+ wrap.appendChild(dow);
1630
+
1631
+ const grid = document.createElement('div');
1632
+ grid.className = 'range-grid';
1633
+ const lead = (new Date(y, m, 1).getDay() + 6) % 7; // Monday-first
1634
+ const dayCount = new Date(y, m + 1, 0).getDate();
1635
+ const today = todayIso();
1636
+
1637
+ for (let i = 0; i < lead; i++) {
1638
+ const pad = document.createElement('span');
1639
+ pad.className = 'range-day pad';
1640
+ grid.appendChild(pad);
1641
+ }
1642
+ for (let day = 1; day <= dayCount; day++) {
1643
+ const iso = isoDate(new Date(y, m, day));
1644
+ const btn = document.createElement('button');
1645
+ btn.type = 'button';
1646
+ btn.className = 'range-day';
1647
+ btn.textContent = day;
1648
+ if (iso === today) btn.classList.add('today');
1649
+ if (iso > today) {
1650
+ btn.classList.add('off');
1651
+ btn.disabled = true;
1652
+ } else {
1653
+ // What the delegated click/hover handlers and paintRangeSpan read the cell's day back from.
1654
+ btn.dataset.iso = iso;
1655
+ }
1656
+ grid.appendChild(btn);
1657
+ }
1658
+ wrap.appendChild(grid);
1659
+ return wrap;
1660
+ }
1661
+
1662
+ // #endregion
1663
+
1157
1664
  // #region ROUTER
1158
1665
 
1159
1666
  function setActiveNav(view) {
@@ -1226,11 +1733,13 @@ function sortBy(field) {
1226
1733
  else renderProjects();
1227
1734
  }
1228
1735
 
1229
- // biome-ignore lint/correctness/noUnusedVariables: called from HTML onchange
1230
- async function onRangeChange(val) {
1231
- dateRange = val === 'today' ? 'today' : parseInt(val, 10) || 7;
1736
+ // The one entry point for a range change, from either half of the picker. The lastRenderHash reset
1737
+ // is load-bearing: the renderers are hash-gated and would not repaint the new window otherwise.
1738
+ async function applyRange(next) {
1739
+ dateRange = next;
1232
1740
  saveDateRange(dateRange);
1233
1741
  lastRenderHash = {};
1742
+ renderRangeTrigger();
1234
1743
  updateUrl();
1235
1744
  const t = showToast(`Recalculating for ${rangeLabel(dateRange)}...`, true);
1236
1745
  await loadAndRender(currentView);
@@ -1461,6 +1970,16 @@ document.addEventListener('keydown', (e) => {
1461
1970
  return;
1462
1971
  }
1463
1972
 
1973
+ // The same exemption the modal above gets: the popover is a div, so the INPUT/SELECT guard does
1974
+ // not cover it, and r/t/j/k/Esc would otherwise fire straight through an open picker.
1975
+ if (isRangePickerOpen()) {
1976
+ if (e.key === 'Escape') {
1977
+ closeRangePicker();
1978
+ e.preventDefault();
1979
+ }
1980
+ return;
1981
+ }
1982
+
1464
1983
  if (e.ctrlKey || e.altKey || e.metaKey) return;
1465
1984
 
1466
1985
  if (e.key === '?' || (e.key === '/' && e.shiftKey)) {
@@ -1698,7 +2217,8 @@ document.addEventListener('click', async (e) => {
1698
2217
  document.addEventListener('DOMContentLoaded', async () => {
1699
2218
  const state = getUrlState();
1700
2219
  dateRange = loadDateRange();
1701
- document.getElementById('rangeSelect').value = dateRange;
2220
+ buildRangePresets();
2221
+ renderRangeTrigger();
1702
2222
 
1703
2223
  // Resolve the scope before any navigate() so the first /api/overview already carries
1704
2224
  // &project=. Read window.location.search directly, not getUrlState() — that falls back to