Skip to content

Commit 57cde8c

Browse files
refactor(core): dashboard date presets read their bounds from the spec window table (#29320)
<!-- claude-projects-attribution: {"github_login":"zhuangjianguo"} --> _Requested by **Steedos** · [project thread](https://claude.ai/code/project/chan_018ETKaNwMZCNRYD7D8Q9Ubb?thread=cmsg_018ETKaNwMZCNRYD7D8Q9UbbV2JyEd3XiA89ZqaTUz4Nwt)_ Fixes #29116 Clause-②: no Metadata-protocol: none ## 维护者速读 - 改了什么:仪表盘日期筛选不再自带一份预设日期区间表,13 个预设(本月、上季度、近 30 天等)一律读 spec 里那张唯一的表。 - 为什么改:两张表写的是同一组区间,只是本期写法不同(`{current_month_start}` 对 `{month_start}`),迟早会漂移;你已定为低优先级卡。 - 风险与回滚:本期区间的写法从 `{current_*}` 换成同义的 `{month_start}` 这类别名,解析出的日期逐一相同;回滚就是 revert 本 PR。 - 先看:`ui/packages/core/src/utils/dashboard-filters.ts` 里的 `presetBounds`,然后是新测试 `dashboard-filters.presetWindows-29116.test.ts`。 - 两分钟验证:在 `ui/` 下运行 `pnpm exec vitest run packages/core/src/utils/__tests__/dashboard-filters.presetWindows-29116.test.ts`,应看到 44 个测试全部通过。 - 需要你做的:无,席位落地。 ## What changes - `ui/packages/core/src/utils/dashboard-filters.ts`: the local `PRESET_RANGES` table is gone. `presetBounds(preset)` now returns the spec's window from `DATE_RANGE_PRESET_MACRO_WINDOWS` (`@objectstack/spec/data`), and membership is decided by the spec's exact `isDateRangePresetName`, both in `presetBounds` and in `normalizeDateDefault` (which used `defaultValue in PRESET_RANGES`). The docblocks that explained the table's `satisfies` pin now say where that guarantee lives: the spec declaration is typed `Record<DateRangePreset, …>`, so a preset added without a window fails to compile in the spec, and there is no local table to invent a name in. - The emitted condition for the four current-period presets changes spelling only: `this_week`, `this_month`, `this_quarter` and `this_year` emit the bare aliases (`{month_start}` / `{month_end}` and so on) instead of `{current_month_start}` / `{current_month_end}`. The other nine presets emit byte-identical tokens. - No new key, option, schema or export. No spec change. `DATE_RANGE_PRESETS` is still re-exported from `@object-ui/core` as before. - Patch changeset `.changeset/29116-dashboard-preset-windows-from-spec.md` for `@object-ui/core`. ## Why The card: the same 13 presets had two tables, the spec's and this module's, in two spellings of the same days. Both resolve today through `DATE_MACRO_ALIAS_TOKENS`, so nothing was wrong on screen; the risk was the tables drifting. ## Tests New `ui/packages/core/src/utils/__tests__/dashboard-filters.presetWindows-29116.test.ts` (44 tests): - every preset in `DATE_RANGE_PRESETS` emits exactly the spec's window (13 cases), and the preset set equals the retired table's 13 keys; - every preset resolves (`resolveDateMacros`) to the same two calendar dates under the new spelling and under the retired `{current_*}` table, copied verbatim into the test, on six reference dates that cross week, month, quarter and year boundaries plus a leap day (13 cases); - for a compare-to widget fed the same condition, `shiftFilterByCompareTo` gives the same window for `previousPeriod` and `previousYear`, and `compareToTrendLabelKey` gives the same label under both spellings (13 cases); - a stored dashboard written in the `{current_*}` spelling still filters: a custom range `{ from: '{current_month_start}', to: '{current_month_end}' }` passes through and selects the same days as the `this_month` preset, and a date global filter defaulting to `'{current_quarter_start}'` is kept as a token, passed through and resolved; - an unknown preset still misses with the usual warning, including names that are `Object.prototype` members (`constructor`, `toString`, `__proto__`), and such a name is not lifted to `{ preset }` as a date default. Changed pin: `ui/packages/core/src/utils/__tests__/dashboard-filters.test.ts` asserted the literal `{current_month_start}` / `{current_month_end}` emitted for `this_month` (two places). They now assert `{month_start}` / `{month_end}`. This is behaviour-neutral: the pin is on the emitted token string, and the parity cases above prove the two tokens resolve to the same day on every preset and reference date. Pins named by the card stay green without edits: `ui/packages/types/src/__tests__/report-chart-query-spec-parity.test.ts`, the plugin-dashboard `DashboardFilterBar*` and `DashboardRenderer.filters` tests (none of them pins an emitted current-period token). ## Acceptance notes - One small behaviour difference on junk input: a stored preset name that only matched an inherited object member (for example `'constructor'`) used to pass the old `in` check, then resolved to no bounds and was dropped with no warning. It is now dropped with the standard unknown-preset warning. Covered by the prototype-member cases above. - The spec docblock on `DATE_RANGE_PRESET_MACRO_WINDOWS` says the console's lowering "stays the executable mapping" and the table is "deliberately NOT a resolver". That still reads true (the lowering stays in `dashboard-filters`, it now reads the table), so the spec is left untouched as the card requires. - Open PRs whose search hits name `dashboard-filters` (#29162, #29263, #29295, #29251) do not touch `dashboard-filters.ts`. ## Verification <details><summary>Local runs (ui/, locked; b8bd448, core suite again on 97d4d50)</summary> - Prerequisite closure `turbo run build --filter='@object-ui/core^...'` plus formula, sdui-parser, lint, client: 38/38 tasks, exit 0. - `pnpm exec vitest run packages/core/`: Test Files 231 passed (231), Tests 4280 passed, 27 skipped. - Consumer pins (16 files: plugin-dashboard `DashboardFilterBar*`, `DashboardRenderer.filters`, `DashboardPhoneTouchTargets-29078`; types `report-chart-query-spec-parity`; plugin-designer `DashboardDesignPage.presetAlias`; i18n `dashboard-range-preset-labels-4984`; app-shell `DashboardWidgetInspector`): Test Files 16 passed, Tests 142 passed, 6 skipped. - `turbo run type-check --filter=@object-ui/core`: exit 0 (it compiles the test files; the first run caught a typing slip in the new test, fixed in the second commit). </details> <details><summary>Ablations (scripts/ablation-replace.mjs, restored to the HEAD blob each time)</summary> - `presetBounds` guard swapped to `preset in DATE_RANGE_PRESET_MACRO_WINDOWS`: "an unknown preset name still misses, prototype member names included" goes red; restored, blob equals HEAD. - `normalizeDateDefault` guard swapped to `defaultValue in DATE_RANGE_PRESET_MACRO_WINDOWS`: "a non-preset date default is not lifted to a preset" goes red; restored, blob equals HEAD. </details> <details><summary>Derived gates</summary> Derived with `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack` at b8bd448 (34 families) and run there; `--ran` reconciliation: 34 derived, 34 run, 0 NOT-MEASURED, 0 UNRUN. Every family exit 0: - `node scripts/check-adr-0087-registration.mjs --base origin/main` exit 0 - `node scripts/check-adr-0087-registration.mjs --self-test` exit 0 - `node scripts/check-changeset-no-major.mjs --base origin/main` exit 0 - `node scripts/check-closing-keyword-parity.mjs` exit 0 - `node scripts/check-closing-keyword-parity.mjs --self-test` exit 0 - `node scripts/check-comment-mask-corpus.mjs` exit 0 - `node scripts/check-empty-changeset.mjs --base origin/main` exit 0 - `node scripts/check-empty-changeset.mjs --self-test` exit 0 - `node scripts/check-sdui-manifest.mjs` exit 0 - `node scripts/check-sdui-manifest.mjs --self-test` exit 0 - `node scripts/pm/release-rehearsal-clone.mjs --self-test` exit 0 - `node scripts/release-pending-publish.mjs --self-test` exit 0 - `pnpm --filter @objectstack/spec run check:duration-unit-keys` exit 0 - `pnpm check:changeset-gate-self-tests` exit 0 - `pnpm check:closed-ceremony-text` exit 0 - `pnpm check:cross-package-test-inputs` exit 0 - `pnpm check:dispatcher-error-vocabulary` exit 0 - `pnpm check:driver-memory-census` exit 0 - `pnpm check:engine-double-contract` exit 0 - `pnpm check:gitlink-declared` exit 0 - `pnpm check:nul-bytes` exit 0 - `pnpm check:pm-changeset-deadline-census` exit 0 - `pnpm check:published-files` exit 0 - `pnpm check:query-options-erasure` exit 0 - `pnpm check:refd-timer-probe` exit 0 - `pnpm check:skill-identifier-liveness` exit 0 - `pnpm check:test-source-alias` exit 0 - `pnpm check:tier-file-adoption` exit 0 - `pnpm check:type-check-coverage` exit 0 - `pnpm check:type-check-debt` exit 0 - `pnpm check:undeclared-dep-imports` exit 0 - `pnpm check:watch-hint-literal` exit 0 - `pnpm check:where-matcher` exit 0 - `pnpm --dir ui exec vitest run scripts/` exit 0 `pnpm --dir ui exec vitest run scripts/`: Test Files 169 passed, 2 skipped (171). After merging main (head 97d4d50, no change to the touched files or the spec date tables): `vitest run packages/core/` again 231/231 files, `check:nul-bytes` and `check-sdui-manifest.mjs` exit 0. </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01QsR2jSgqmN55SMKRe9YTif)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent bf03ebb commit 57cde8c

4 files changed

Lines changed: 255 additions & 61 deletions

File tree

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
---
2+
'@object-ui/core': patch
3+
---
4+
5+
refactor(core): dashboard date presets read their bounds from the spec's window table
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
`dashboard-filters` no longer keeps its own preset-to-bounds table. Each of the thirteen dashboard date presets now lowers to the window `@objectstack/spec` declares in `DATE_RANGE_PRESET_MACRO_WINDOWS`, so the preset list and its windows live in one place and cannot drift.
11+
12+
The emitted condition spells the current period with the bare macro aliases the spec uses (`{month_start}` instead of `{current_month_start}`, and the same for week, quarter and year). Both spellings name the same day, so a dashboard returns the same rows, and a compare-to widget keeps the same comparison window and trend label. A stored dashboard that writes the `{current_*}` tokens itself, as a custom range or as a date default, still filters as before.
13+
14+
Preset membership is now the spec's exact `isDateRangePresetName` check. A stored preset name that matched only an inherited object member (such as `constructor`) was dropped without a word; it is now dropped with the usual unknown-preset warning.
Lines changed: 199 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,199 @@
1+
/**
2+
* ObjectUI
3+
* Copyright (c) 2024-present ObjectStack Inc.
4+
*
5+
* This source code is licensed under the MIT license found in the
6+
* LICENSE file in the root directory of this source tree.
7+
*/
8+
9+
/**
10+
* Dashboard date presets read the spec's window table, not a local copy.
11+
*
12+
* `dashboard-filters` used to keep its own preset → bounds table
13+
* (`PRESET_RANGES`) holding the spec's thirteen windows in the `{current_*}`
14+
* period spelling. It now lowers every preset through
15+
* `DATE_RANGE_PRESET_MACRO_WINDOWS`, which spells the current period with the
16+
* bare aliases (`{month_start}`). These pins hold three things:
17+
*
18+
* 1. every preset emits exactly the spec's window, so there is one table;
19+
* 2. the new spelling resolves to the same calendar days as the retired one
20+
* on every preset, on reference dates that straddle week, month, quarter
21+
* and year boundaries, so the rows a dashboard returns are unchanged, and
22+
* so is the comparison window and trend label a metric widget derives
23+
* from the same condition;
24+
* 3. a stored dashboard that carries the `{current_*}` spelling itself, as a
25+
* custom range or as a bare macro default, still filters.
26+
*/
27+
28+
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
29+
import { DATE_RANGE_PRESET_MACRO_WINDOWS } from '@objectstack/spec/data';
30+
import {
31+
buildFilterCondition,
32+
resolveDashboardFilterDefs,
33+
resetDashboardFilterWarnings,
34+
DATE_RANGE_FILTER_NAME,
35+
DATE_RANGE_PRESETS,
36+
type DashboardFilterDef,
37+
} from '../dashboard-filters';
38+
import { resolveDateMacros } from '../date-macros';
39+
import { shiftFilterByCompareTo, compareToTrendLabelKey } from '../compare-to';
40+
41+
const dateDef: DashboardFilterDef = {
42+
name: DATE_RANGE_FILTER_NAME,
43+
field: 'created_at',
44+
type: 'dateRange',
45+
};
46+
47+
/**
48+
* The retired local table, verbatim from `dashboard-filters.ts` at main
49+
* 39951d2a — the behaviour this change must keep.
50+
*/
51+
const RETIRED_PRESET_RANGES: Record<string, { from: string; to: string }> = {
52+
today: { from: '{today}', to: '{today}' },
53+
yesterday: { from: '{yesterday}', to: '{yesterday}' },
54+
this_week: { from: '{current_week_start}', to: '{current_week_end}' },
55+
last_week: { from: '{last_week_start}', to: '{last_week_end}' },
56+
this_month: { from: '{current_month_start}', to: '{current_month_end}' },
57+
last_month: { from: '{last_month_start}', to: '{last_month_end}' },
58+
this_quarter: { from: '{current_quarter_start}', to: '{current_quarter_end}' },
59+
last_quarter: { from: '{last_quarter_start}', to: '{last_quarter_end}' },
60+
this_year: { from: '{current_year_start}', to: '{current_year_end}' },
61+
last_year: { from: '{last_year_start}', to: '{last_year_end}' },
62+
last_7_days: { from: '{7_days_ago}', to: '{today}' },
63+
last_30_days: { from: '{30_days_ago}', to: '{today}' },
64+
last_90_days: { from: '{90_days_ago}', to: '{today}' },
65+
};
66+
67+
/**
68+
* Reference instants (local time, which is what `resolveDateMacros` reads):
69+
* a mid-quarter Wednesday, a Sunday that closes a week, a Monday that opens
70+
* one, the last day of a quarter, the first day of a year, and a leap day.
71+
*/
72+
const REFERENCE_NOWS = [
73+
new Date(2026, 6, 15, 10, 30),
74+
new Date(2026, 6, 19, 23, 59),
75+
new Date(2026, 6, 20, 0, 0),
76+
new Date(2026, 8, 30, 12, 0),
77+
new Date(2027, 0, 1, 0, 0),
78+
new Date(2028, 1, 29, 8, 0),
79+
];
80+
81+
describe('dashboard date presets lower through the spec window table', () => {
82+
let warn: ReturnType<typeof vi.spyOn>;
83+
beforeEach(() => {
84+
resetDashboardFilterWarnings();
85+
warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
86+
});
87+
afterEach(() => {
88+
warn.mockRestore();
89+
});
90+
91+
it('covers the same thirteen presets the retired table did', () => {
92+
expect([...DATE_RANGE_PRESETS].sort()).toEqual(Object.keys(RETIRED_PRESET_RANGES).sort());
93+
expect(DATE_RANGE_PRESETS).toHaveLength(13);
94+
});
95+
96+
it.each([...DATE_RANGE_PRESETS])('emits the spec window for %s', (preset) => {
97+
const [start, end] = DATE_RANGE_PRESET_MACRO_WINDOWS[preset];
98+
expect(buildFilterCondition(dateDef, { preset })).toEqual({ $gte: start, $lte: end });
99+
expect(warn).not.toHaveBeenCalled();
100+
});
101+
102+
it.each([...DATE_RANGE_PRESETS])(
103+
'%s resolves to the same days under the retired {current_*} spelling',
104+
(preset) => {
105+
const retired = RETIRED_PRESET_RANGES[preset];
106+
const retiredCondition = { $gte: retired.from, $lte: retired.to };
107+
const condition = buildFilterCondition(dateDef, { preset }) as { $gte: string; $lte: string };
108+
for (const now of REFERENCE_NOWS) {
109+
const resolved = resolveDateMacros(condition, now);
110+
// A real date on both bounds, not a token passed through unresolved.
111+
expect(resolved.$gte, `${preset} @ ${now.toString()}`).toMatch(/^\d{4}-\d{2}-\d{2}$/);
112+
expect(resolved.$lte, `${preset} @ ${now.toString()}`).toMatch(/^\d{4}-\d{2}-\d{2}$/);
113+
expect(resolved, `${preset} @ ${now.toString()}`).toEqual(resolveDateMacros(retiredCondition, now));
114+
}
115+
},
116+
);
117+
118+
it.each([...DATE_RANGE_PRESETS])(
119+
'%s keeps its previous-period window and trend label for a compareTo widget',
120+
(preset) => {
121+
const retired = RETIRED_PRESET_RANGES[preset];
122+
const retiredFilter = { created_at: { $gte: retired.from, $lte: retired.to } };
123+
const filter = { created_at: buildFilterCondition(dateDef, { preset }) };
124+
for (const now of REFERENCE_NOWS) {
125+
for (const kind of ['previousPeriod', 'previousYear'] as const) {
126+
expect(shiftFilterByCompareTo(filter, { kind }, now), `${preset} ${kind} @ ${now.toString()}`).toEqual(
127+
shiftFilterByCompareTo(retiredFilter, { kind }, now),
128+
);
129+
}
130+
}
131+
expect(compareToTrendLabelKey({ kind: 'previousPeriod' }, filter)).toBe(
132+
compareToTrendLabelKey({ kind: 'previousPeriod' }, retiredFilter),
133+
);
134+
},
135+
);
136+
137+
it('an unknown preset name still misses, prototype member names included', () => {
138+
for (const preset of ['last_60_days', 'This_Month', 'constructor', 'toString', '__proto__']) {
139+
warn.mockClear();
140+
expect(buildFilterCondition(dateDef, { preset }), preset).toBeUndefined();
141+
expect(warn, preset).toHaveBeenCalledTimes(1);
142+
expect(String(warn.mock.calls[0][0]), preset).toContain(`unknown date range preset "${preset}"`);
143+
}
144+
});
145+
146+
it('a non-preset date default is not lifted to a preset, prototype member names included', () => {
147+
for (const defaultValue of ['last_60_days', 'constructor', 'toString']) {
148+
const [def] = resolveDashboardFilterDefs({
149+
globalFilters: [{ name: 'when', field: 'created_at', type: 'date', defaultValue }],
150+
} as any);
151+
expect(def.defaultValue, defaultValue).toBe(defaultValue);
152+
}
153+
const [def] = resolveDashboardFilterDefs({
154+
globalFilters: [{ name: 'when', field: 'created_at', type: 'date', defaultValue: 'this_quarter' }],
155+
} as any);
156+
expect(def.defaultValue).toEqual({ preset: 'this_quarter' });
157+
});
158+
});
159+
160+
describe('a stored dashboard written in the {current_*} spelling still filters', () => {
161+
beforeEach(() => resetDashboardFilterWarnings());
162+
163+
it('a custom range bounded by {current_*} tokens selects the same days as the preset', () => {
164+
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
165+
try {
166+
const stored = { from: '{current_month_start}', to: '{current_month_end}' };
167+
const condition = buildFilterCondition(dateDef, stored);
168+
expect(condition).toEqual({ $gte: '{current_month_start}', $lte: '{current_month_end}' });
169+
for (const now of REFERENCE_NOWS) {
170+
expect(resolveDateMacros(condition, now)).toEqual(
171+
resolveDateMacros(buildFilterCondition(dateDef, { preset: 'this_month' }), now),
172+
);
173+
}
174+
expect(warn).not.toHaveBeenCalled();
175+
} finally {
176+
warn.mockRestore();
177+
}
178+
});
179+
180+
it('a date global filter defaulting to a {current_*} token keeps it and passes it through', () => {
181+
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
182+
try {
183+
const [def] = resolveDashboardFilterDefs({
184+
globalFilters: [
185+
{ name: 'opened', field: 'created_at', type: 'date', defaultValue: '{current_quarter_start}' },
186+
],
187+
} as any);
188+
expect(def.defaultValue).toBe('{current_quarter_start}');
189+
const condition = buildFilterCondition(def, def.defaultValue);
190+
expect(condition).toBe('{current_quarter_start}');
191+
const now = new Date(2026, 6, 15, 10, 30);
192+
expect(resolveDateMacros(condition, now)).toBe('2026-07-01');
193+
expect(resolveDateMacros('{quarter_start}', now)).toBe('2026-07-01');
194+
expect(warn).not.toHaveBeenCalled();
195+
} finally {
196+
warn.mockRestore();
197+
}
198+
});
199+
});

‎ui/packages/core/src/utils/__tests__/dashboard-filters.test.ts‎

Lines changed: 10 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -100,8 +100,8 @@ describe('resolveDashboardFilterDefs', () => {
100100
});
101101
// The filter it seeds is a real bound, not an empty value.
102102
expect(buildFilterCondition(defs[0], defs[0].defaultValue)).toEqual({
103-
$gte: '{current_month_start}',
104-
$lte: '{current_month_end}',
103+
$gte: '{month_start}',
104+
$lte: '{month_end}',
105105
});
106106
});
107107

@@ -233,8 +233,8 @@ describe('buildFilterCondition', () => {
233233
$lte: '{today}',
234234
});
235235
expect(buildFilterCondition(dateDef, { preset: 'this_month' })).toEqual({
236-
$gte: '{current_month_start}',
237-
$lte: '{current_month_end}',
236+
$gte: '{month_start}',
237+
$lte: '{month_end}',
238238
});
239239
});
240240

@@ -311,7 +311,7 @@ describe('buildFilterCondition', () => {
311311

312312
it('keeps a date-macro token as an equality, with no warning', () => {
313313
// Macro tokens stay symbolic in the condition and are resolved at query
314-
// time by resolveDateMacros — the same vocabulary PRESET_RANGES emits.
314+
// time by resolveDateMacros — the same vocabulary preset bounds emit.
315315
withWarn((warn) => {
316316
expect(buildFilterCondition(dateDef, '{today}')).toBe('{today}');
317317
expect(buildFilterCondition(dateDef, '{7_days_ago}')).toBe('{7_days_ago}');
@@ -493,13 +493,11 @@ describe('mergeFilters', () => {
493493
* list cannot make. So the first test asks `toBe`, deliberately.
494494
*
495495
* The second is the other half of the burn-down and the one with teeth at
496-
* runtime: the spec owns which presets EXIST, this module owns what each one
497-
* RESOLVES TO, and nothing but the `satisfies` in `dashboard-filters.ts` ties
498-
* them together. That is a compile-time pin, so it is erased here — this test
499-
* is what makes the same claim visible in a suite run, and what would catch a
500-
* future edit that re-annotated the table as `Record<string, …>` (a string index
501-
* signature satisfies every literal key, so the `satisfies` would go vacuously
502-
* green while the bounds table quietly went missing entries).
496+
* runtime: the spec owns which presets EXIST and, since the local bounds table
497+
* retired, what each one RESOLVES TO (`DATE_RANGE_PRESET_MACRO_WINDOWS`). The
498+
* spec types that table `Record<DateRangePreset, …>`, a compile-time pin that
499+
* is erased here — this test is what makes the same claim visible in a suite
500+
* run: every offered preset lowers to a condition.
503501
*/
504502
describe('DATE_RANGE_PRESETS is the spec\'s list, not a copy of it', () => {
505503
it('is the spec\'s own array by REFERENCE, not an equal one', async () => {

‎ui/packages/core/src/utils/dashboard-filters.ts‎

Lines changed: 32 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,8 @@
2222

2323
import type { DashboardComponentSchema, DashboardWidgetSchema, I18nLabel, PageVariable } from '@object-ui/types';
2424
import { liftLegacyGlobalFilterDefault } from '@object-ui/types';
25-
import { DATE_RANGE_PRESETS, DashboardSchema as SpecDashboardSchema, type DateRangePreset } from '@objectstack/spec/ui';
25+
import { DATE_RANGE_PRESET_MACRO_WINDOWS, isDateRangePresetName } from '@objectstack/spec/data';
26+
import { DATE_RANGE_PRESETS, DashboardSchema as SpecDashboardSchema } from '@objectstack/spec/ui';
2627
import { resolveDateMacros } from './date-macros.js';
2728

2829
/** Reserved filter name for the dashboard's built-in date range. */
@@ -146,49 +147,32 @@ export interface DateRangeValue {
146147
}
147148

148149
/**
149-
* Date-range presets → date-macro token bounds. Tokens stay symbolic in the
150-
* generated condition; every widget renderer resolves them at query time via
151-
* `resolveDateMacros`, exactly like hand-authored widget filters.
152-
*
153-
* `satisfies Record<DateRangePreset, …>` is the load-bearing half of
154-
* objectui#4167, not decoration. `DATE_RANGE_PRESETS` below is now the spec's
155-
* list rather than `Object.keys` of this table, so the two could otherwise
156-
* drift in the one direction the spec's own comment on that const names as the
157-
* failure mode: a preset the SCHEMA knows and this table has no bounds for
158-
* "validates clean and then resolves to nothing" — it would reach the filter
159-
* bar's dropdown, be selected, and produce no range. The `satisfies` makes that
160-
* a compile error at the moment the spec adds a preset (missing key), and makes
161-
* a local invention a compile error too (excess key). The annotation form
162-
* `const PRESET_RANGES: Record<DateRangePreset, …>` would NOT do this: a string
163-
* index signature satisfies every literal key, so the check passes vacuously.
150+
* Date-range preset NAME → its date-macro token bounds, read from the spec's
151+
* own window table, `DATE_RANGE_PRESET_MACRO_WINDOWS`. Tokens stay symbolic in
152+
* the generated condition; every widget renderer resolves them at query time
153+
* via `resolveDateMacros`, exactly like hand-authored widget filters.
154+
*
155+
* There is no local bounds table. This module used to carry one
156+
* (`PRESET_RANGES`) holding the same thirteen windows as the spec's, spelled
157+
* with the `{current_*}` period tokens where the spec writes the bare aliases
158+
* (`{month_start}`); both spellings name the same day through
159+
* `DATE_MACRO_ALIAS_TOKENS`, so the copy protected nothing and could only
160+
* drift. The guarantees that table's `satisfies Record<DateRangePreset, …>`
161+
* pin bought (objectui#4167) now sit on the spec's declaration, which is typed
162+
* `Record<DateRangePreset, …>` over a literal union: a preset the spec adds
163+
* without a window is a compile error THERE, and no local name can be invented
164+
* here because there is no local table to add one to.
165+
*
166+
* The runtime receives whatever a stored dashboard carries, so a name that is
167+
* not a preset must miss (and warn, see `buildFilterCondition`) rather than
168+
* fail to compile. Membership is the spec's exact predicate,
169+
* `isDateRangePresetName` — never `in` or a bare index, which would also find
170+
* `Object.prototype` members (`constructor`, `toString`) on a plain object.
164171
*/
165-
const PRESET_RANGES = {
166-
today: { from: '{today}', to: '{today}' },
167-
yesterday: { from: '{yesterday}', to: '{yesterday}' },
168-
this_week: { from: '{current_week_start}', to: '{current_week_end}' },
169-
last_week: { from: '{last_week_start}', to: '{last_week_end}' },
170-
this_month: { from: '{current_month_start}', to: '{current_month_end}' },
171-
last_month: { from: '{last_month_start}', to: '{last_month_end}' },
172-
this_quarter: { from: '{current_quarter_start}', to: '{current_quarter_end}' },
173-
last_quarter: { from: '{last_quarter_start}', to: '{last_quarter_end}' },
174-
this_year: { from: '{current_year_start}', to: '{current_year_end}' },
175-
last_year: { from: '{last_year_start}', to: '{last_year_end}' },
176-
last_7_days: { from: '{7_days_ago}', to: '{today}' },
177-
last_30_days: { from: '{30_days_ago}', to: '{today}' },
178-
last_90_days: { from: '{90_days_ago}', to: '{today}' },
179-
} satisfies Record<DateRangePreset, { from?: string; to?: string }>;
180-
181-
/**
182-
* Bounds for a preset NAME that may not be one.
183-
*
184-
* The runtime receives whatever a stored dashboard carries, so an unrecognised
185-
* name must warn (see `buildFilterCondition`) rather than fail to compile. That
186-
* read is confined here so the `satisfies` pin above stays the single place
187-
* deciding which names exist — an unguarded `PRESET_RANGES[someString]` would
188-
* have forced the table back to a `Record<string, …>` and taken the pin with it.
189-
*/
190-
function presetBounds(preset: string): { from?: string; to?: string } | undefined {
191-
return (PRESET_RANGES as Record<string, { from?: string; to?: string }>)[preset];
172+
function presetBounds(preset: string): { from: string; to: string } | undefined {
173+
if (!isDateRangePresetName(preset)) return undefined;
174+
const [from, to] = DATE_RANGE_PRESET_MACRO_WINDOWS[preset];
175+
return { from, to };
192176
}
193177

194178
/**
@@ -206,10 +190,9 @@ function presetBounds(preset: string): { from?: string; to?: string } | undefine
206190
* already identical in content AND display order — the copy had nothing to
207191
* protect.
208192
*
209-
* What stays local is the BOUNDS table above, which is the other half of
210-
* objectstack-ai/objectstack#4614's design ("the two vocabularies live one import apart and neither
211-
* restates the other's grammar"): the spec owns which presets exist, this
212-
* module owns what each one resolves to in date-macro tokens.
193+
* The BOUNDS each name resolves to are the spec's too (`presetBounds` above
194+
* reads `DATE_RANGE_PRESET_MACRO_WINDOWS`), so this module restates neither the
195+
* preset list nor its windows.
213196
*/
214197
export { DATE_RANGE_PRESETS };
215198

@@ -228,7 +211,7 @@ const ISO_DATE_RE = /^\d{4}-\d{2}-\d{2}(?:[T ][\d:.]+(?:Z|[+-]\d{2}:?\d{2})?)?$/
228211
* - a **date-macro token** (`{today}`, `${current_month_start}`,
229212
* `{7_days_ago}`) — it stays symbolic in the generated condition and is
230213
* resolved at query time by `resolveDateMacros`, exactly like the bounds
231-
* `PRESET_RANGES` emits. The check asks that resolver itself instead of
214+
* `presetBounds` emits. The check asks that resolver itself instead of
232215
* restating its grammar here: one token vocabulary, no second dialect to
233216
* drift — and a token it does not know is precisely the typo this guard
234217
* exists to catch;
@@ -396,7 +379,7 @@ function liftLegacyFilterDeclaration<T>(filter: T): T {
396379
function normalizeDateDefault(type: DashboardFilterDef['type'], defaultValue: unknown): unknown {
397380
if (type !== 'date' && type !== 'dateRange') return defaultValue;
398381
if (typeof defaultValue !== 'string') return defaultValue;
399-
return defaultValue in PRESET_RANGES ? { preset: defaultValue } : defaultValue;
382+
return isDateRangePresetName(defaultValue) ? { preset: defaultValue } : defaultValue;
400383
}
401384

402385
/**

0 commit comments

Comments
 (0)