Skip to content

An open source alternative to Tableau. Embeddable visual analytic

feat: implement TerseSpec authoring format with expand and project

Elwynn Chend80afb273b69
diff --git a/docs/terse-spec-design.md b/docs/terse-spec-design.md
index 4077ebc1..2cbc1cb5 100644
--- a/docs/terse-spec-design.md
+++ b/docs/terse-spec-design.md
@@ -175,9 +175,9 @@ aggName := 'sum' | 'count' | 'max' | 'min' | 'mean' | 'median'
## 6. 与 `normalize()` 的接入方式(第三阶段)
-- `detectSpecKind` 增加规则(**排在 vega-lite 判定之后**,避免与 VL unit spec 冲突):`$schema` 为 tersespec URL → `'terse'`;或同时满足 ① 存在 `x`/`y`/`computed`/`filters` 任一 terse 特征键、② 不含任何 VL 结构键(`mark` 单独出现不算 terse 特征,`{mark, encoding}` 是 VL)、③ 不含 `encodings`/`layout` → `'terse'`。纯 `{mark: 'bar'}` 无通道时维持现状路由到 vega-lite(空图语义一致);
+- `detectSpecKind` 探测顺序(实现定稿,2026-07-07):① vega `$schema` → vega-lite;② tersespec `$schema` → terse;③ VL 独占键(`encoding`/`spec`/`layer`/`concat` 系)→ vega-lite;④ terse 特征键(`x`/`y`/`computed`/`filters`)存在且无 `encodings` → terse(**排在 layout 规则之前**,使 terse 的 `layout` 逃生舱不会把 spec 误路由到 chart);⑤ 裸 `mark`(无 terse 通道)→ vega-lite(维持现状);⑥ `layout` → chart;⑦ legacy config 键 → vis-spec;⑧ 其余 → partial-chart;
- `normalize()` switch 增加 `case 'terse': chart = expandTerse(input, meta)`,之后共用现有出口管线;
-- 新增 `project(chart: IChart, meta: IMutField[]): TerseSpec` 反向投影:遍历 channels/filters/folds 收集实际引用的字段,computed 字段内联为 `TerseComputedField`,未引用字段全部丢弃(有损,文档明示);`expr`/`bin`/`log` 之外的 expression op(dateTimeDrill 等)投影为对象形式的 `timeUnit`,paint 跳过并 warning;
+- 新增 `projectTerse(chart: IChart): TerseSpec` 反向投影(实现名,原设计名 `project` 因过于泛化改名):遍历 channels/filters 收集实际引用的字段(folds 经 config 逃生舱携带),computed 字段内联为 `TerseComputedField`,未引用字段全部丢弃(有损,文档明示);`dateTimeDrill` 投影为对象形式的 `timeUnit`;`paint`/`binCount`/`dateTimeFeature` computed 字段与 `regexp` 过滤器无法表达,跳过并 warning;字段名与 shorthand 文法冲突或重名时回退 `fid:` 前缀形式;非默认的 config/layout 残差经逃生舱携带以满足往返标准;
- `gen-schema` 管线新增 `tersespec_v1.json` 产物,`$schema` URL 指向它;
- 废弃 `Specification` 接口与 `renderSpec()`(标 `@deprecated`,下个 major 删除)。
diff --git a/packages/graphic-walker/scripts/create-json-schema.js b/packages/graphic-walker/scripts/create-json-schema.js
index 8ebc560b..f622945f 100644
--- a/packages/graphic-walker/scripts/create-json-schema.js
+++ b/packages/graphic-walker/scripts/create-json-schema.js
@@ -15,3 +15,4 @@ if (!fs.existsSync(resolve(__dirname, '../public'))) {
}
fs.writeFileSync(resolve(__dirname, '../public/chartinfo.json'), JSON.stringify(generator.createSchema('IChart'), undefined, 4));
fs.writeFileSync(resolve(__dirname, '../public/stoinfo_v2.json'), JSON.stringify(generator.createSchema('IStoInfoV2'), undefined, 4));
+fs.writeFileSync(resolve(__dirname, '../public/tersespec_v1.json'), JSON.stringify(generator.createSchema('TerseSpec'), undefined, 4));
diff --git a/packages/graphic-walker/src/index.tsx b/packages/graphic-walker/src/index.tsx
index 03cce15e..9ac8c034 100644
--- a/packages/graphic-walker/src/index.tsx
+++ b/packages/graphic-walker/src/index.tsx
@@ -7,6 +7,7 @@ export * from './store/visualSpecStore';
export { resolveChart, convertChart, parseChart } from './models/visSpecHistory';
export { normalize, detectSpecKind } from './models/normalize';
export type { ISpecKind } from './models/normalize';
+export { expandTerse, projectTerse, parseShorthand, terseComputedFid } from './models/terse';
export { getGlobalConfig } from './config';
export { DataSourceSegmentComponent } from './dataSource';
export * from './models/visSpecHistory';
diff --git a/packages/graphic-walker/src/interfaces.ts b/packages/graphic-walker/src/interfaces.ts
index 8e480884..db9d818a 100644
--- a/packages/graphic-walker/src/interfaces.ts
+++ b/packages/graphic-walker/src/interfaces.ts
@@ -23,6 +23,7 @@ export interface IRow {
export type IAggregator = 'sum' | 'count' | 'max' | 'min' | 'mean' | 'median' | 'variance' | 'stdev' | 'distinctCount' | 'expr';
export type IEmbedMenuItem = 'data_interpretation' | 'data_view';
+/** @deprecated Superseded by {@link TerseSpec} + `normalize()`; will be removed in the next major version. */
export interface Specification {
position?: string[];
color?: string[];
@@ -716,6 +717,76 @@ export interface PartialChart {
layout?: Partial<IVisualLayout>;
}
+export const TerseSpecSchemaUrl = 'https://graphic-walker.kanaries.net/tersespec_v1.json';
+
+/**
+ * A field reference inside a TerseSpec. A plain string is resolved by name
+ * (with optional aggregate shorthand like `'sum(Sales)'`, or a `'fid:'` prefix
+ * to bypass name resolution); the object form carries per-channel overrides
+ * and its `field` string is never shorthand-parsed.
+ */
+export type TerseFieldRef =
+ | string
+ | {
+ field: string;
+ aggregate?: IAggregator;
+ sort?: ISortMode;
+ timeUnit?: (typeof DATE_TIME_DRILL_LEVELS)[number];
+ };
+
+/** Filter literals. `timeRange` takes epoch milliseconds only, word-for-word aligned with the `temporal range` rule in computation.md. */
+export type TerseFilter =
+ | { field: string; oneOf: any[] }
+ | { field: string; notIn: any[] }
+ | { field: string; range: [number | null, number | null] }
+ | { field: string; timeRange: [number | null, number | null] };
+
+/** An inline computed-field definition; exactly one of `expr` / `bin` / `log` must be set. */
+export interface TerseComputedField {
+ name: string;
+ expr?: string;
+ bin?: { field: string; count?: number };
+ log?: { field: string; base?: number };
+ analyticType?: IAnalyticType;
+}
+
+/**
+ * The human-authored terse spec (authoring format). Expanded into a canonical
+ * IChart by `normalize()`; never used for persistence. See docs/terse-spec-design.md.
+ */
+export interface TerseSpec {
+ $schema?: string;
+ /** chart type; maps to config.geoms[0], defaults to 'auto' */
+ mark?: string;
+ name?: string;
+ x?: TerseFieldRef | TerseFieldRef[];
+ y?: TerseFieldRef | TerseFieldRef[];
+ color?: TerseFieldRef;
+ opacity?: TerseFieldRef;
+ size?: TerseFieldRef;
+ shape?: TerseFieldRef;
+ text?: TerseFieldRef;
+ details?: TerseFieldRef | TerseFieldRef[];
+ theta?: TerseFieldRef;
+ radius?: TerseFieldRef;
+ longitude?: TerseFieldRef;
+ latitude?: TerseFieldRef;
+ geoId?: TerseFieldRef;
+ filters?: TerseFilter[];
+ computed?: TerseComputedField[];
+ /** → config.defaultAggregated, defaults to true */
+ aggregate?: boolean;
+ /** → layout.stack */
+ stack?: IStackMode;
+ /** → config.limit */
+ limit?: number;
+ /** applied to the last y measure */
+ sort?: 'ascending' | 'descending';
+ /** canonical escape hatch, shallow-merged last (highest priority) */
+ config?: Partial<IVisualConfigNew>;
+ layout?: Partial<IVisualLayout>;
+}
+
export type Topology = Parameters<typeof feature>[0];
export type IGeographicData =
diff --git a/packages/graphic-walker/src/models/normalize.ts b/packages/graphic-walker/src/models/normalize.ts
index 4fc69ed1..5877ca62 100644
--- a/packages/graphic-walker/src/models/normalize.ts
+++ b/packages/graphic-walker/src/models/normalize.ts
@@ -1,8 +1,9 @@
-import { DraggableFieldState, IChart, IChartSchemaUrl, IMutField, IVisSpec, PartialChart } from '../interfaces';
+import { DraggableFieldState, IChart, IChartSchemaUrl, IMutField, IVisSpec, PartialChart, TerseSpec, TerseSpecSchemaUrl } from '../interfaces';
import { fillChart, lintExtraFields, newChart, parseChart } from './visSpecHistory';
import { uniqueId } from './utils';
import { VegaliteMapper } from '../lib/vl2gw';
import { algebraLint } from '../lib/gog';
+import { expandTerse } from './terse';
/**
* The kind of spec accepted by {@link normalize}:
@@ -13,14 +14,22 @@ import { algebraLint } from '../lib/gog';
* migration chain inside `parseChart`.
* - `vega-lite`: a Vega-Lite-like spec. Routed through `VegaliteMapper`; requires `meta` to
* resolve field names, otherwise unresolved fields fall back to the count field.
+ * - `terse`: the human-authored TerseSpec authoring format (docs/terse-spec-design.md).
+ * Expanded via `expandTerse`; requires `meta` to resolve field names.
* - `partial-chart`: everything else — treated as `PartialChart` and completed with defaults.
*/
-export type ISpecKind = 'chart' | 'vis-spec' | 'vega-lite' | 'partial-chart';
+export type ISpecKind = 'chart' | 'vis-spec' | 'vega-lite' | 'terse' | 'partial-chart';
-// Structural keys that exist on Vega-Lite specs but never on IChart / IVisSpec / PartialChart.
-// `layer` is detected so layered specs fail loudly in VegaliteMapper territory instead of
-// silently normalizing into an empty default chart via the partial-chart path.
-const VEGA_LITE_KEYS = ['mark', 'encoding', 'spec', 'layer', 'concat', 'hconcat', 'vconcat'] as const;
+// Structural keys that exist on Vega-Lite specs but never on IChart / IVisSpec / PartialChart /
+// TerseSpec. `layer` is detected so layered specs fail loudly in VegaliteMapper territory instead
+// of silently normalizing into an empty default chart via the partial-chart path. `mark` is NOT
+// in this list because TerseSpec shares it; a bare `mark` with no terse channel keys still routes
+// to vega-lite (see detectSpecKind).
+const VEGA_LITE_EXCLUSIVE_KEYS = ['encoding', 'spec', 'layer', 'concat', 'hconcat', 'vconcat'] as const;
+
+// Top-level keys that exist on TerseSpec but never on IChart / IVisSpec / PartialChart
+// (canonical specs keep fields and filters inside `encodings`).
+const TERSE_TRIGGER_KEYS = ['x', 'y', 'computed', 'filters'] as const;
// Keys of the deprecated IVisualConfig that IVisualConfigNew does not have. Real-world IVisSpec
// exports always carry them because they were serialized from initVisualConfig()-filled configs;
@@ -50,11 +59,16 @@ const LEGACY_CONFIG_KEYS = [
/**
* Detect which input format a spec is in. The rules are ordered and explicit:
- * 1. a `$schema` pointing at vega.github.io, or any Vega-Lite structural key
- * (`mark` / `encoding` / `spec` / `concat` / `hconcat` / `vconcat`) → `vega-lite`;
- * 2. a `layout` key → `chart` (same duck-typing as `parseChart` / `importCode`);
- * 3. a `config` carrying legacy-only keys (`stack`, `size`, `resolve`, …) → `vis-spec`;
- * 4. anything else → `partial-chart`.
+ * 1. a `$schema` pointing at vega.github.io → `vega-lite`; the tersespec URL → `terse`;
+ * 2. any Vega-Lite-exclusive structural key (`encoding` / `spec` / `layer` / `concat` /
+ * `hconcat` / `vconcat`) → `vega-lite`;
+ * 3. any terse trigger key (`x` / `y` / `computed` / `filters`) without an `encodings`
+ * key → `terse` (this runs before the `layout` rule so the canonical `layout`
+ * escape hatch inside a terse spec does not shadow it);
+ * 4. a bare `mark` (shared key, no terse channels present) → `vega-lite`;
+ * 5. a `layout` key → `chart` (same duck-typing as `parseChart` / `importCode`);
+ * 6. a `config` carrying legacy-only keys (`stack`, `size`, `resolve`, …) → `vis-spec`;
+ * 7. anything else → `partial-chart`.
*/
export function detectSpecKind(input: object): ISpecKind {
if (input === null || typeof input !== 'object' || Array.isArray(input)) {
@@ -64,7 +78,16 @@ export function detectSpecKind(input: object): ISpecKind {
if (typeof spec.$schema === 'string' && spec.$schema.includes('vega.github.io')) {
return 'vega-lite';
}
- if (VEGA_LITE_KEYS.some((key) => key in spec)) {
+ if (spec.$schema === TerseSpecSchemaUrl) {
+ return 'terse';
+ }
+ if (VEGA_LITE_EXCLUSIVE_KEYS.some((key) => key in spec)) {
+ return 'vega-lite';
+ }
+ if (TERSE_TRIGGER_KEYS.some((key) => key in spec) && !('encodings' in spec)) {
+ return 'terse';
+ }
+ if ('mark' in spec) {
return 'vega-lite';
}
if ('layout' in spec) {
@@ -89,7 +112,7 @@ export function detectSpecKind(input: object): ISpecKind {
* @param input a full or partial IChart, a deprecated IVisSpec, or a Vega-Lite-like spec.
* @param meta dataset fields; required to resolve field names for the Vega-Lite path.
*/
-export function normalize(input: IChart | IVisSpec | PartialChart | Record<string, unknown>, meta: IMutField[] = []): IChart {
+export function normalize(input: IChart | IVisSpec | PartialChart | TerseSpec | Record<string, unknown>, meta: IMutField[] = []): IChart {
const kind = detectSpecKind(input);
let chart: IChart;
switch (kind) {
@@ -101,6 +124,9 @@ export function normalize(input: IChart | IVisSpec | PartialChart | Record<strin
chart = VegaliteMapper(vl, allFields, uniqueId(), name);
break;
}
+ case 'terse':
+ chart = fillChart(expandTerse(input as TerseSpec, meta));
+ break;
case 'chart':
case 'vis-spec':
chart = parseChart(input as IChart | IVisSpec);
diff --git a/packages/graphic-walker/src/models/terse.test.ts b/packages/graphic-walker/src/models/terse.test.ts
new file mode 100644
index 00000000..135da000
--- /dev/null
+++ b/packages/graphic-walker/src/models/terse.test.ts
@@ -0,0 +1,325 @@
+jest.mock('nanoid', () => ({ nanoid: () => 'mock-id' }));
+
+import { IMutField, TerseSpec, TerseSpecSchemaUrl } from '../interfaces';
+import { detectSpecKind, normalize } from './normalize';
+import { expandTerse, parseShorthand, projectTerse, terseComputedFid } from './terse';
+import { chartToWorkflow } from '../utils/workflow';
+import { COUNT_FIELD_ID } from '../constants';
+
+const META: IMutField[] = [
+ { fid: 'region', name: 'Region', semanticType: 'nominal', analyticType: 'dimension' },
+ { fid: 'segment', name: 'Segment', semanticType: 'nominal', analyticType: 'dimension' },
+ { fid: 'order_date', name: 'Order Date', semanticType: 'temporal', analyticType: 'dimension' },
+ { fid: 'sales', name: 'Sales', semanticType: 'quantitative', analyticType: 'measure' },
+ { fid: 'profit', name: 'Profit', semanticType: 'quantitative', analyticType: 'measure' },
+];
+
+const silent = () => void 0;
+
+describe('parseShorthand', () => {
+ test('valid aggregate prefixes parse', () => {
+ expect(parseShorthand('sum(Sales)')).toEqual({ field: 'Sales', aggregate: 'sum' });
+ expect(parseShorthand('distinctCount(Region)')).toEqual({ field: 'Region', aggregate: 'distinctCount' });
+ expect(parseShorthand('count()')).toEqual({ field: '', aggregate: 'count' });
+ });
+ test('non-aggregate prefixes are plain field names', () => {
+ expect(parseShorthand('log(x)')).toEqual({ field: 'log(x)' });
+ expect(parseShorthand('expr(a)')).toEqual({ field: 'expr(a)' });
+ expect(parseShorthand('Sales')).toEqual({ field: 'Sales' });
+ });
+ test('nested parens keep the inner ref intact', () => {
+ expect(parseShorthand('sum(Price (USD))')).toEqual({ field: 'Price (USD)', aggregate: 'sum' });
+ });
+});
+
+describe('field resolution', () => {
+ test('resolves by exact name, fid, and fid: prefix', () => {
+ const chart = normalize({ x: 'Region', y: ['fid:sales', 'profit'] } as TerseSpec, META);
+ expect(chart.encodings.columns.map((f) => f.fid)).toEqual(['region']);
+ expect(chart.encodings.rows.map((f) => f.fid)).toEqual(['sales', 'profit']);
+ });
+ test('case-insensitive unique fallback warns but resolves', () => {
+ const warnings: string[] = [];
+ // 'REGION' matches neither a name nor a fid exactly, so it exercises the fallback;
+ // lowercase 'region' would hit the exact-fid rule first (by design).
+ const partial = expandTerse({ x: 'REGION' } as TerseSpec, META, (m) => warnings.push(m));
+ expect(partial.encodings?.columns?.[0].fid).toBe('region');
+ expect(warnings.some((w) => w.includes('case-insensitively'))).toBe(true);
+ });
+ test('unknown field errors with nearest candidates', () => {
+ expect(() => expandTerse({ x: 'Salez' } as TerseSpec, META, silent)).toThrow(/Nearest candidates: \[Sales/);
+ });
+ test('duplicate names demand a fid: prefix', () => {
+ const dupMeta: IMutField[] = [
+ { fid: 'a1', name: 'Amount', semanticType: 'quantitative', analyticType: 'measure' },
+ { fid: 'a2', name: 'Amount', semanticType: 'quantitative', analyticType: 'measure' },
+ ];
+ expect(() => expandTerse({ y: 'Amount' } as TerseSpec, dupMeta, silent)).toThrow(/ambiguous.*fid/s);
+ const partial = expandTerse({ y: 'fid:a2' } as TerseSpec, dupMeta, silent);
+ expect(partial.encodings?.rows?.[0].fid).toBe('a2');
+ });
+ test('a field literally named like a shorthand wins over the shorthand reading', () => {
+ const trickyMeta: IMutField[] = [...META, { fid: 'weird', name: 'sum(Sales)', semanticType: 'quantitative', analyticType: 'measure' }];
+ const warnings: string[] = [];
+ const partial = expandTerse({ y: 'sum(Sales)' } as TerseSpec, trickyMeta, (m) => warnings.push(m));
+ expect(partial.encodings?.rows?.[0].fid).toBe('weird');
+ expect(warnings.some((w) => w.includes('literally named'))).toBe(true);
+ });
+ test('count() maps to the built-in count field', () => {
+ const chart = normalize({ x: 'Region', y: 'count()' } as TerseSpec, META);
+ expect(chart.encodings.rows[0].fid).toBe(COUNT_FIELD_ID);
+ });
+});
+
+describe('expandTerse', () => {
+ test('minimal spec expands to a complete canonical chart', () => {
+ const chart = normalize({ x: 'Region', y: 'sum(Sales)' } as TerseSpec, META);
+ expect(chart.encodings.columns[0]).toMatchObject({ fid: 'region', analyticType: 'dimension' });
+ expect(chart.encodings.rows[0]).toMatchObject({ fid: 'sales', aggName: 'sum', analyticType: 'measure' });
+ expect(chart.config.geoms).toEqual(['auto']);
+ expect(chart.config.defaultAggregated).toBe(true);
+ // pools rebuilt from meta: all fields + count + virtual fields
+ expect(chart.encodings.dimensions.map((f) => f.fid)).toContain('region');
+ expect(chart.encodings.measures.map((f) => f.fid)).toContain(COUNT_FIELD_ID);
+ });
+
+ test('knobs map to config/layout and canonical fragments win with a warning', () => {
+ const warnings: string[] = [];
+ const partial = expandTerse({ mark: 'bar', aggregate: false, stack: 'normalize', limit: 5, config: { geoms: ['line'] } } as TerseSpec, META, (m) =>
+ warnings.push(m),
+ );
+ expect(partial.config?.geoms).toEqual(['line']);
+ expect(partial.config?.defaultAggregated).toBe(false);
+ expect(partial.config?.limit).toBe(5);
+ expect(partial.layout?.stack).toBe('normalize');
+ expect(warnings.some((w) => w.includes("Both 'mark' and canonical"))).toBe(true);
+ });
+
+ test('sort knob lands on the last y measure', () => {
+ const chart = normalize({ x: 'Region', y: ['sum(Sales)', 'mean(Profit)'], sort: 'descending' } as TerseSpec, META);
+ expect(chart.encodings.rows[0].sort).toBeUndefined();
+ expect(chart.encodings.rows[1].sort).toBe('descending');
+ });
+
+ test('object refs carry sort and timeUnit overrides', () => {
+ const chart = normalize(
+ { x: { field: 'Order Date', timeUnit: 'month' }, y: { field: 'Sales', aggregate: 'mean', sort: 'ascending' } } as TerseSpec,
+ META,
+ );
+ expect(chart.encodings.columns[0].timeUnit).toBe('month');
+ expect(chart.encodings.rows[0]).toMatchObject({ aggName: 'mean', sort: 'ascending' });
+ });
+
+ test('filters expand to IFilterField rules', () => {
+ const chart = normalize(
+ {
+ x: 'Region',
+ y: 'sum(Sales)',
+ filters: [
+ { field: 'Segment', oneOf: ['A', 'B'] },
+ { field: 'Profit', range: [0, 100] },
+ { field: 'Order Date', timeRange: [1704067200000, null] },
+ ],
+ } as TerseSpec,
+ META,
+ );
+ expect(chart.encodings.filters.map((f) => f.rule)).toEqual([
+ { type: 'one of', value: ['A', 'B'] },
+ { type: 'range', value: [0, 100] },
+ { type: 'temporal range', value: [1704067200000, null] },
+ ]);
+ });
+
+ test('computed fields mirror store action semantics', () => {
+ const chart = normalize(
+ {
+ computed: [
+ { name: 'Net Sales', expr: '"Sales" * 0.85' },
+ { name: 'Sales Bucket', bin: { field: 'Sales', count: 4 } },
+ { name: 'Log Profit', log: { field: 'Profit', base: 2 } },
+ ],
+ x: 'Sales Bucket',
+ y: 'sum(Net Sales)',
+ color: 'Log Profit',
+ } as TerseSpec,
+ META,
+ );
+ const bucket = chart.encodings.columns[0];
+ expect(bucket).toMatchObject({ semanticType: 'ordinal', analyticType: 'dimension', computed: true });
+ expect(bucket.expression).toMatchObject({ op: 'bin', num: 4, params: [{ type: 'field', value: 'sales' }] });
+ const net = chart.encodings.rows[0];
+ expect(net).toMatchObject({ analyticType: 'measure', aggName: 'sum', computed: true });
+ expect(net.expression).toMatchObject({ op: 'expr', params: [{ type: 'sql', value: '"Sales" * 0.85' }] });
+ const log = chart.encodings.color[0];
+ expect(log.expression).toMatchObject({ op: 'log2', num: 2 });
+ // deterministic fids
+ expect(bucket.fid).toBe(terseComputedFid('Sales Bucket'));
+ expect(
+ normalize({ computed: [{ name: 'Sales Bucket', bin: { field: 'Sales', count: 4 } }], x: 'Sales Bucket' } as TerseSpec, META).encodings.columns[0]
+ .fid,
+ ).toBe(bucket.fid);
+ });
+
+ test('aggregate SQL expressions get aggName expr', () => {
+ const chart = normalize({ computed: [{ name: 'Ratio', expr: 'sum("Sales") / sum("Profit")' }], y: 'Ratio' } as TerseSpec, META);
+ expect(chart.encodings.rows[0].aggName).toBe('expr');
+ });
+
+ test('conflicting duplicate computed names error, identical ones dedupe', () => {
+ expect(() =>
+ expandTerse(
+ {
+ computed: [
+ { name: 'X', expr: '"Sales" + 1' },
+ { name: 'X', expr: '"Sales" + 2' },
+ ],
+ } as TerseSpec,
+ META,
+ silent,
+ ),
+ ).toThrow(/defined twice/);
+ const partial = expandTerse(
+ {
+ computed: [
+ { name: 'X', expr: '"Sales" + 1' },
+ { name: 'X', expr: '"Sales" + 1' },
+ ],
+ y: 'X',
+ } as TerseSpec,
+ META,
+ silent,
+ );
+ expect(partial.encodings?.measures?.filter((f) => f.name === 'X')).toHaveLength(1);
+ });
+
+ test('invalid definitions error clearly', () => {
+ expect(() => expandTerse({ computed: [{ name: 'Bad', expr: 'sum((' }] } as TerseSpec, META, silent)).toThrow(/invalid expression/);
+ expect(() => expandTerse({ computed: [{ name: 'Bad' }] } as TerseSpec, META, silent)).toThrow(/exactly one of/);
+ expect(() => expandTerse({ y: 'sum()' } as TerseSpec, META, silent)).toThrow(/needs a field/);
+ expect(() => expandTerse({ filters: [{ field: 'Region' } as any] } as TerseSpec, META, silent)).toThrow(/must define one of/);
+ });
+});
+
+describe('normalize integration', () => {
+ test('detectSpecKind routes terse correctly, including the layout escape hatch', () => {
+ expect(detectSpecKind({ x: 'Region' })).toBe('terse');
+ expect(detectSpecKind({ $schema: TerseSpecSchemaUrl })).toBe('terse');
+ expect(detectSpecKind({ x: 'Region', mark: 'bar' })).toBe('terse');
+ expect(detectSpecKind({ x: 'Region', layout: { stack: 'none' } })).toBe('terse');
+ // unchanged existing routes
+ expect(detectSpecKind({ mark: 'bar' })).toBe('vega-lite');
+ expect(detectSpecKind({ mark: 'bar', encoding: {} })).toBe('vega-lite');
+ expect(detectSpecKind({ layout: {} })).toBe('chart');
+ expect(detectSpecKind({ encodings: { rows: [] } })).toBe('partial-chart');
+ });
+
+ test('terse normalize output is canonical, stamped, idempotent, and feeds toWorkflow', () => {
+ const terse: TerseSpec = { mark: 'bar', x: 'Region', y: 'sum(Sales)', filters: [{ field: 'Segment', oneOf: ['A'] }] };
+ const once = normalize(terse, META);
+ expect(once.$schema).toBeDefined();
+ expect(Object.keys(once.encodings)).toHaveLength(16);
+ expect(normalize(once, META)).toEqual(once);
+ expect(Array.isArray(chartToWorkflow(once).workflow)).toBe(true);
+ });
+});
+
+describe('projectTerse', () => {
+ const roundtrip = (t: TerseSpec) => {
+ const canonical = normalize(t, META);
+ const projected = projectTerse(canonical, silent);
+ return { canonical, projected, reNormalized: normalize(projected, META) };
+ };
+
+ test('roundtrip standard: normalize(project(normalize(t))) equals normalize(t)', () => {
+ const cases: TerseSpec[] = [
+ { x: 'Region', y: 'sum(Sales)' },
+ { mark: 'bar', x: 'Region', y: ['sum(Sales)', 'mean(Profit)'], color: 'Segment', stack: 'normalize', limit: 20 },
+ { x: { field: 'Order Date', timeUnit: 'month' }, y: { field: 'Sales', aggregate: 'mean', sort: 'ascending' }, aggregate: true },
+ {
+ computed: [
+ { name: 'Net', expr: '"Sales" * 0.85' },
+ { name: 'Bucket', bin: { field: 'Sales', count: 6 } },
+ ],
+ x: 'Bucket',
+ y: 'sum(Net)',
+ },
+ { x: 'Region', y: 'count()', filters: [{ field: 'Profit', range: [0, null] }], aggregate: false },
+ { x: 'Region', y: 'sum(Sales)', config: { coordSystem: 'generic', folds: ['sales'] }, layout: { background: '#fff' } },
+ ];
+ for (const t of cases) {
+ const { canonical, reNormalized } = roundtrip(t);
+ const stripVisId = ({ visId, ...rest }: Record<string, unknown>) => rest;
+ expect(stripVisId(reNormalized as never)).toEqual(stripVisId(canonical as never));
+ }
+ });
+
+ test('projection drops pool fields not referenced by any channel', () => {
+ const { projected } = roundtrip({ x: 'Region', y: 'sum(Sales)' });
+ const flat = JSON.stringify(projected);
+ expect(flat).not.toContain('Profit');
+ expect(flat).not.toContain('Segment');
+ expect(projected.computed).toBeUndefined();
+ });
+
+ test('projection emits shorthand and knobs, not canonical noise', () => {
+ const { projected } = roundtrip({ mark: 'bar', x: 'Region', y: 'sum(Sales)', stack: 'center', limit: 10, aggregate: false });
+ expect(projected.y).toBe('sum(Sales)');
+ expect(projected.x).toBe('Region');
+ expect(projected.mark).toBe('bar');
+ expect(projected.stack).toBe('center');
+ expect(projected.limit).toBe(10);
+ expect(projected.aggregate).toBe(false);
+ });
+
+ test('inexpressible pieces are skipped with warnings', () => {
+ const warnings: string[] = [];
+ const canonical = normalize({ x: 'Region', y: 'sum(Sales)' } as TerseSpec, META);
+ const doctored = {
+ ...canonical,
+ encodings: {
+ ...canonical.encodings,
+ color: [
+ {
+ fid: 'gw_bc1',
+ name: 'bucket',
+ semanticType: 'ordinal' as const,
+ analyticType: 'dimension' as const,
+ computed: true,
+ expression: { op: 'binCount' as const, as: 'gw_bc1', params: [{ type: 'field' as const, value: 'sales' }] },
+ },
+ ],
+ filters: [
+ {
+ fid: 'region',
+ name: 'Region',
+ semanticType: 'nominal' as const,
+ analyticType: 'dimension' as const,
+ rule: { type: 'regexp' as const, value: '^a' },
+ },
+ ],
+ },
+ };
+ const projected = projectTerse(doctored, (m) => warnings.push(m));
+ expect(projected.color).toBeUndefined();
+ expect(projected.filters).toBeUndefined();
+ expect(warnings.some((w) => w.includes('binCount'))).toBe(true);
+ expect(warnings.some((w) => w.includes('regexp'))).toBe(true);
+ });
+
+ test('dateTimeDrill computed fields project as timeUnit refs', () => {
+ const canonical = normalize({ x: { field: 'Order Date', timeUnit: 'month' }, y: 'sum(Sales)' } as TerseSpec, META);
+ const projected = projectTerse(canonical, silent);
+ expect(projected.x).toEqual({ field: 'Order Date', timeUnit: 'month' });
+ });
+
+ test('duplicate pool names fall back to fid: refs', () => {
+ const dupMeta: IMutField[] = [
+ { fid: 'a1', name: 'Amount', semanticType: 'quantitative', analyticType: 'measure' },
+ { fid: 'a2', name: 'Amount', semanticType: 'quantitative', analyticType: 'measure' },
+ ];
+ const canonical = normalize({ y: 'fid:a2' } as TerseSpec, dupMeta);
+ const projected = projectTerse(canonical, silent);
+ expect(projected.y).toBe('sum(fid:a2)');
+ expect(normalize(projected, dupMeta).encodings.rows[0].fid).toBe('a2');
+ });
+});
diff --git a/packages/graphic-walker/src/models/terse.ts b/packages/graphic-walker/src/models/terse.ts
new file mode 100644
index 00000000..403d179e
--- /dev/null
+++ b/packages/graphic-walker/src/models/terse.ts
@@ -0,0 +1,503 @@
+import {
+ DraggableFieldState,
+ IAggregator,
+ IChart,
+ IFilterField,
+ IFilterRule,
+ IMutField,
+ IViewField,
+ PartialChart,
+ TerseComputedField,
+ TerseFieldRef,
+ TerseFilter,
+ TerseSpec,
+} from '../interfaces';
+import { newChart } from './visSpecHistory';
+import { getSQLItemAnalyticType, parseSQLExpr } from '../lib/sql';
+import { COUNT_FIELD_ID, MEA_KEY_ID, MEA_VAL_ID, PAINT_FIELD_ID } from '../constants';
+import { emptyVisualConfig, emptyVisualLayout } from '../utils/save';
+
+type OnWarn = (message: string) => void;
+
+// Shorthand aggregates: IAggregator minus 'expr' (aggregate expressions have no
+// sensible shorthand syntax and must go through inline computed fields).
+const SHORTHAND_AGGS = new Set<IAggregator>(['sum', 'count', 'max', 'min', 'mean', 'median', 'variance', 'stdev', 'distinctCount']);
+
+// terse channel key → canonical encoding channel
+const CHANNEL_MAP = {
+ x: 'columns',
+ y: 'rows',
+ color: 'color',
+ opacity: 'opacity',
+ size: 'size',
+ shape: 'shape',
+ text: 'text',
+ details: 'details',
+ theta: 'theta',
+ radius: 'radius',
+ longitude: 'longitude',
+ latitude: 'latitude',
+ geoId: 'geoId',
+} as const;
+type TerseChannelKey = keyof typeof CHANNEL_MAP;
+const TERSE_CHANNEL_KEYS = Object.keys(CHANNEL_MAP) as TerseChannelKey[];
+
+/** Deterministic djb2-based short hash so the same inline computed name always yields the same fid (idempotency). */
+function shortHash(input: string): string {
+ let h = 5381;
+ for (let i = 0; i < input.length; i++) {
+ h = ((h * 33) ^ input.charCodeAt(i)) >>> 0;
+ }
+ return h.toString(36);
+}
+
+export function terseComputedFid(name: string): string {
+ return `gw_t_${shortHash(name)}`;
+}
+
+function levenshtein(a: string, b: string): number {
+ const dp = Array.from({ length: a.length + 1 }, (_, i) => [i, ...new Array<number>(b.length).fill(0)]);
+ for (let j = 0; j <= b.length; j++) dp[0][j] = j;
+ for (let i = 1; i <= a.length; i++) {
+ for (let j = 1; j <= b.length; j++) {
+ dp[i][j] = Math.min(dp[i - 1][j] + 1, dp[i][j - 1] + 1, dp[i - 1][j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
+ }
+ }
+ return dp[a.length][b.length];
+}
+
+/**
+ * Parse the aggregate shorthand: `aggName '(' fieldRef ')'` where aggName must be
+ * exactly one of the shorthand aggregates and the parens are the outermost pair.
+ * Anything else is returned as a plain field name (e.g. `'log(x)'`).
+ */
+export function parseShorthand(ref: string): { field: string; aggregate?: IAggregator } {
+ const match = /^([a-zA-Z]+)\((.*)\)$/.exec(ref);
+ if (match && SHORTHAND_AGGS.has(match[1] as IAggregator)) {
+ return { field: match[2], aggregate: match[1] as IAggregator };
+ }
+ return { field: ref };
+}
+
+class FieldIndex {
+ private byName = new Map<string, IViewField[]>();
+ private byFid = new Map<string, IViewField>();
+ private names: string[] = [];
+
+ add(field: IViewField) {
+ // Virtual fields may have no display name when i18n is not initialized (e.g. headless use).
+ if (typeof field.name === 'string') {
+ const named = this.byName.get(field.name);
+ if (named) {
+ named.push(field);
+ } else {
+ this.byName.set(field.name, [field]);
+ this.names.push(field.name);
+ }
+ }
+ if (!this.byFid.has(field.fid)) {
+ this.byFid.set(field.fid, field);
+ }
+ }
+
+ /**
+ * Resolution order (docs/terse-spec-design.md §3): `fid:` prefix → exact name
+ * (inline computed fields are in the same index) → exact fid → case-insensitive
+ * unique fallback (with warning) → error with nearest candidates.
+ */
+ resolve(raw: string, onWarn: OnWarn): IViewField {
+ if (raw.startsWith('fid:')) {
+ const field = this.byFid.get(raw.slice(4));
+ if (!field) {
+ throw new Error(`Unknown field id '${raw.slice(4)}' (from '${raw}'). ${this.candidateHint(raw.slice(4))}`);
+ }
+ return field;
+ }
+ const named = this.byName.get(raw);
+ if (named) {
+ if (named.length > 1) {
+ throw new Error(`Field name '${raw}' is ambiguous between fids [${named.map((f) => f.fid).join(', ')}]; reference it with a 'fid:' prefix.`);
+ }
+ return named[0];
+ }
+ const byFid = this.byFid.get(raw);
+ if (byFid) {
+ return byFid;
+ }
+ const lower = raw.toLowerCase();
+ const caseHits = this.names.filter((n) => n.toLowerCase() === lower);
+ if (caseHits.length === 1) {
+ onWarn(`Field '${raw}' matched '${caseHits[0]}' case-insensitively.`);
+ return this.byName.get(caseHits[0])![0];
+ }
+ if (caseHits.length > 1) {
+ throw new Error(`Field '${raw}' matches multiple fields case-insensitively [${caseHits.join(', ')}]; use the exact name.`);
+ }
+ throw new Error(`Unknown field '${raw}'. ${this.candidateHint(raw)}`);
+ }
+
+ candidateHint(raw: string): string {
+ const nearest = [...this.names].sort((a, b) => levenshtein(raw, a) - levenshtein(raw, b)).slice(0, 3);
+ return `Nearest candidates: [${nearest.join(', ')}] among ${this.names.length} fields.`;
+ }
+}
+
+/**
+ * Build the inline computed fields, mirroring the store actions byte-for-byte:
+ * `expr` mirrors `addSQLComputedField`, `bin`/`log` mirror `createBinlogField`.
+ */
+function buildComputedFields(defs: TerseComputedField[], index: FieldIndex, poolFields: IViewField[], onWarn: OnWarn): IViewField[] {
+ const results: IViewField[] = [];
+ const seen = new Map<string, string>();
+ for (const def of defs) {
+ const kinds = [def.expr !== undefined, def.bin !== undefined, def.log !== undefined].filter(Boolean).length;
+ if (kinds !== 1) {
+ throw new Error(`Computed field '${def.name}' must define exactly one of expr / bin / log.`);
+ }
+ const definition = JSON.stringify([def.expr, def.bin, def.log, def.analyticType]);
+ const previous = seen.get(def.name);
+ if (previous !== undefined) {
+ if (previous !== definition) {
+ throw new Error(`Computed field '${def.name}' is defined twice with different definitions.`);
+ }
+ continue;
+ }
+ seen.set(def.name, definition);
+ const fid = terseComputedFid(def.name);
+ let field: IViewField;
+ if (def.expr !== undefined) {
+ let parsed;
+ try {
+ parsed = parseSQLExpr(def.expr);
+ } catch (error) {
+ throw new Error(`Computed field '${def.name}' has an invalid expression '${def.expr}': ${error instanceof Error ? error.message : error}`);
+ }
+ const [semanticType, isAgg] = getSQLItemAnalyticType(parsed, poolFields.concat(results) as IMutField[]);
+ const analyticType = def.analyticType ?? (semanticType === 'quantitative' ? 'measure' : 'dimension');
+ field = {
+ analyticType,
+ fid,
+ name: def.name,
+ semanticType,
+ computed: true,
+ aggName: isAgg ? 'expr' : analyticType === 'dimension' ? undefined : 'sum',
+ expression: { op: 'expr', as: fid, params: [{ type: 'sql', value: def.expr }] },
+ };
+ } else if (def.bin) {
+ const base = index.resolve(def.bin.field, onWarn);
+ const num = def.bin.count ?? 10;
+ field = {
+ fid,
+ name: def.name,
+ semanticType: 'ordinal',
+ analyticType: def.analyticType ?? 'dimension',
+ computed: true,
+ expression: { op: 'bin', as: fid, params: [{ type: 'field', value: base.fid }], num },
+ };
+ } else {
+ const base = index.resolve(def.log!.field, onWarn);
+ const num = def.log!.base ?? 10;
+ const op = num === 10 ? 'log10' : num === 2 ? 'log2' : 'log';
+ field = {
+ fid,
+ name: def.name,
+ semanticType: 'quantitative',
+ analyticType: def.analyticType ?? base.analyticType,
+ aggName: 'sum',
+ computed: true,
+ expression: { op, as: fid, params: [{ type: 'field', value: base.fid }], num },
+ };
+ }
+ index.add(field);
+ results.push(field);
+ }
+ return results;
+}
+
+function resolveRef(ref: TerseFieldRef, index: FieldIndex, onWarn: OnWarn): IViewField {
+ let base: IViewField;
+ let overrides: { aggregate?: IAggregator; sort?: 'ascending' | 'descending' | 'none'; timeUnit?: IViewField['timeUnit'] } = {};
+ if (typeof ref === 'string') {
+ const shorthand = parseShorthand(ref);
+ if (shorthand.aggregate && shorthand.field === '') {
+ if (shorthand.aggregate !== 'count') {
+ throw new Error(`Aggregate shorthand '${ref}' needs a field, e.g. '${shorthand.aggregate}(Sales)'.`);
+ }
+ base = index.resolve(`fid:${COUNT_FIELD_ID}`, onWarn);
+ } else if (shorthand.aggregate) {
+ // A field whose literal name is the whole string wins over the shorthand reading.
+ try {
+ base = index.resolve(ref, () => void 0);
+ onWarn(`'${ref}' resolved to a field literally named '${ref}', not as ${shorthand.aggregate}(${shorthand.field}).`);
+ } catch {
+ base = index.resolve(shorthand.field, onWarn);
+ overrides.aggregate = shorthand.aggregate;
+ }
+ } else {
+ base = index.resolve(ref, onWarn);
+ }
+ } else {
+ base = index.resolve(ref.field, onWarn);
+ overrides = { aggregate: ref.aggregate, sort: ref.sort, timeUnit: ref.timeUnit };
+ }
+ const field: IViewField = { ...base };
+ if (overrides.aggregate) {
+ if (field.analyticType === 'dimension') {
+ onWarn(`Aggregate '${overrides.aggregate}' on dimension '${field.name}' follows existing semantics (ignored unless the field acts as a measure).`);
+ }
+ field.aggName = overrides.aggregate;
+ }
+ if (overrides.sort) field.sort = overrides.sort;
+ if (overrides.timeUnit) field.timeUnit = overrides.timeUnit;
+ return field;
+}
+
+function toFilterRule(filter: TerseFilter): IFilterRule {
+ if ('oneOf' in filter) return { type: 'one of', value: filter.oneOf };
+ if ('notIn' in filter) return { type: 'not in', value: filter.notIn };
+ if ('range' in filter) return { type: 'range', value: filter.range };
+ if ('timeRange' in filter) return { type: 'temporal range', value: filter.timeRange };
+ throw new Error(`Filter on '${(filter as { field: string }).field}' must define one of oneOf / notIn / range / timeRange.`);
+}
+
+/**
+ * Expand a TerseSpec into a PartialChart (docs/terse-spec-design.md §5).
+ * The dimensions/measures pools are rebuilt from `meta` (newChart semantics)
+ * plus the inline computed fields; terse never carries pools.
+ * Pure: no store, no side effects beyond `onWarn`.
+ */
+export function expandTerse(spec: TerseSpec, meta: IMutField[], onWarn: OnWarn = (msg) => console.warn(`[terse] ${msg}`)): PartialChart {
+ const base = newChart(meta, spec.name || 'Chart');
+ const index = new FieldIndex();
+ for (const field of [...base.encodings.dimensions, ...base.encodings.measures]) {
+ index.add(field);
+ }
+ const poolFields = [...base.encodings.dimensions, ...base.encodings.measures];
+ const computedFields = buildComputedFields(spec.computed ?? [], index, poolFields, onWarn);
+
+ const encodings: Partial<DraggableFieldState> = {
+ dimensions: base.encodings.dimensions.concat(computedFields.filter((f) => f.analyticType === 'dimension')),
+ measures: base.encodings.measures.concat(computedFields.filter((f) => f.analyticType === 'measure')),
+ };
+
+ for (const key of TERSE_CHANNEL_KEYS) {
+ const value = spec[key];
+ if (value === undefined) continue;
+ const refs = Array.isArray(value) ? value : [value];
+ encodings[CHANNEL_MAP[key]] = refs.map((ref) => resolveRef(ref, index, onWarn));
+ }
+
+ if (spec.filters) {
+ encodings.filters = spec.filters.map((filter): IFilterField => {
+ const field = index.resolve(filter.field, onWarn);
+ return { ...field, rule: toFilterRule(filter) };
+ });
+ }
+
+ if (spec.sort) {
+ const rows = encodings.rows ?? [];
+ const lastMeasure = [...rows].reverse().find((f) => f.analyticType === 'measure');
+ if (lastMeasure) {
+ encodings.rows = rows.map((f) => (f === lastMeasure ? { ...f, sort: spec.sort } : f));
+ } else {
+ onWarn(`'sort' knob ignored: no measure on y.`);
+ }
+ }
+
+ const knobConflict = (knob: string, canonicalKey: string) => onWarn(`Both '${knob}' and canonical '${canonicalKey}' are set; the canonical value wins.`);
+ if (spec.mark !== undefined && spec.config?.geoms !== undefined) knobConflict('mark', 'config.geoms');
+ if (spec.aggregate !== undefined && spec.config?.defaultAggregated !== undefined) knobConflict('aggregate', 'config.defaultAggregated');
+ if (spec.limit !== undefined && spec.config?.limit !== undefined) knobConflict('limit', 'config.limit');
+ if (spec.stack !== undefined && spec.layout?.stack !== undefined) knobConflict('stack', 'layout.stack');
+
+ return {
+ visId: base.visId,
+ name: spec.name || 'Chart',
+ encodings,
+ config: {
+ defaultAggregated: spec.aggregate ?? true,
+ geoms: [spec.mark ?? 'auto'],
+ ...(spec.limit !== undefined ? { limit: spec.limit } : {}),
+ ...spec.config,
+ },
+ layout: {
+ ...(spec.stack !== undefined ? { stack: spec.stack } : {}),
+ ...spec.layout,
+ },
+ };
+}
+
+const PROJECT_CHANNEL_ENTRIES = Object.entries(CHANNEL_MAP) as [TerseChannelKey, (typeof CHANNEL_MAP)[TerseChannelKey]][];
+const SYNTHETIC_FIDS = new Set([MEA_KEY_ID, MEA_VAL_ID, PAINT_FIELD_ID]);
+
+/**
+ * Project a canonical IChart back into a TerseSpec (docs/terse-spec-design.md §6).
+ * Lossy by design: pool fields not referenced by any channel/filter are dropped,
+ * and inexpressible pieces (paint / binCount / dateTimeFeature computed fields,
+ * regexp filters) are skipped with a warning. Persistence must stay canonical.
+ */
+export function projectTerse(chart: IChart, onWarn: OnWarn = (msg) => console.warn(`[terse] ${msg}`)): TerseSpec {
+ const pools = [...chart.encodings.dimensions, ...chart.encodings.measures];
+ const nameCount = new Map<string, Set<string>>();
+ for (const field of pools) {
+ const set = nameCount.get(field.name) ?? new Set<string>();
+ set.add(field.fid);
+ nameCount.set(field.name, set);
+ }
+ const computedDefs = new Map<string, TerseComputedField>();
+ const poolByFid = new Map(pools.map((f) => [f.fid, f]));
+
+ const refName = (field: IViewField): string => {
+ const fids = nameCount.get(field.name);
+ if (!fids || fids.size > 1 || parseShorthand(field.name).aggregate || field.name.startsWith('fid:')) {
+ return `fid:${field.fid}`;
+ }
+ return field.name;
+ };
+
+ const emitComputed = (field: IViewField): boolean => {
+ const expression = field.expression;
+ if (!expression) return true;
+ if (field.fid === COUNT_FIELD_ID) return true;
+ const baseParam = expression.params.find((p) => p.type === 'field');
+ const baseField = baseParam ? poolByFid.get(baseParam.value as string) : undefined;
+ let def: TerseComputedField;
+ switch (expression.op) {
+ case 'expr': {
+ const sql = expression.params.find((p) => p.type === 'sql');
+ if (!sql) return false;
+ def = { name: field.name, expr: sql.value as string, analyticType: field.analyticType };
+ break;
+ }
+ case 'bin':
+ if (!baseField) return false;
+ def = { name: field.name, bin: { field: refName(baseField), count: expression.num ?? 10 } };
+ break;
+ case 'log':
+ case 'log2':
+ case 'log10':
+ if (!baseField) return false;
+ def = { name: field.name, log: { field: refName(baseField), base: expression.num ?? (expression.op === 'log2' ? 2 : 10) } };
+ break;
+ default:
+ return false;
+ }
+ if (!computedDefs.has(field.name)) {
+ computedDefs.set(field.name, def);
+ }
+ return true;
+ };
+
+ const emitRef = (field: IViewField): TerseFieldRef | null => {
+ if (SYNTHETIC_FIDS.has(field.fid)) {
+ onWarn(`Field '${field.name}' (${field.fid}) is a synthetic field and cannot be expressed in a terse spec; skipped.`);
+ return null;
+ }
+ let name: string;
+ if (field.fid === COUNT_FIELD_ID) {
+ name = 'count()';
+ } else {
+ if (field.computed || field.expression) {
+ if (field.expression && (field.expression.op === 'dateTimeDrill' || field.expression.op === 'dateTimeFeature')) {
+ const baseParam = field.expression.params.find((p) => p.type === 'field');
+ const level = field.expression.params.find((p) => p.type === 'value');
+ const baseField = baseParam ? poolByFid.get(baseParam.value as string) : undefined;
+ if (field.expression.op === 'dateTimeDrill' && baseField && level) {
+ return { field: refName(baseField), timeUnit: level.value, ...(field.sort && field.sort !== 'none' ? { sort: field.sort } : {}) };
+ }
+ onWarn(`Computed field '${field.name}' (${field.expression.op}) cannot be expressed in a terse spec; skipped.`);
+ return null;
+ }
+ if (!emitComputed(field)) {
+ onWarn(`Computed field '${field.name}' (${field.expression?.op}) cannot be expressed in a terse spec; skipped.`);
+ return null;
+ }
+ }
+ name = refName(field);
+ }
+ const needsObject = (field.sort && field.sort !== 'none') || field.timeUnit;
+ const aggregate = field.analyticType === 'measure' && field.aggName && SHORTHAND_AGGS.has(field.aggName as IAggregator);
+ if (needsObject) {
+ return {
+ field: name,
+ ...(aggregate ? { aggregate: field.aggName as IAggregator } : {}),
+ ...(field.sort && field.sort !== 'none' ? { sort: field.sort } : {}),
+ ...(field.timeUnit ? { timeUnit: field.timeUnit } : {}),
+ };
+ }
+ if (field.fid === COUNT_FIELD_ID) return 'count()';
+ if (aggregate) {
+ const shorthand = `${field.aggName}(${name})`;
+ const roundtrip = parseShorthand(shorthand);
+ if (roundtrip.aggregate === field.aggName && roundtrip.field === name) return shorthand;
+ return { field: name, aggregate: field.aggName as IAggregator };
+ }
+ return name;
+ };
+
+ const spec: TerseSpec = {};
+ if (chart.name && chart.name !== 'Chart') spec.name = chart.name;
+ if (chart.config.geoms[0] && chart.config.geoms[0] !== 'auto') spec.mark = chart.config.geoms[0];
+
+ for (const [terseKey, channel] of PROJECT_CHANNEL_ENTRIES) {
+ const fields = chart.encodings[channel];
+ if (!fields || fields.length === 0) continue;
+ const refs = fields.map(emitRef).filter((r): r is TerseFieldRef => r !== null);
+ if (refs.length === 0) continue;
+ if (terseKey === 'x' || terseKey === 'y' || terseKey === 'details') {
+ spec[terseKey] = refs.length === 1 ? refs[0] : refs;
+ } else {
+ if (refs.length > 1) onWarn(`Channel '${channel}' has ${refs.length} fields; only the first is kept in the terse spec.`);
+ spec[terseKey] = refs[0];
+ }
+ }
+
+ if (chart.encodings.filters.length > 0) {
+ const filters: TerseFilter[] = [];
+ for (const filter of chart.encodings.filters) {
+ if (!filter.rule) continue;
+ if (filter.computed || filter.expression) emitComputed(filter);
+ const field = refName(filter);
+ switch (filter.rule.type) {
+ case 'one of':
+ filters.push({ field, oneOf: [...filter.rule.value] });
+ break;
+ case 'not in':
+ filters.push({ field, notIn: [...filter.rule.value] });
+ break;
+ case 'range':
+ filters.push({ field, range: [...filter.rule.value] as [number | null, number | null] });
+ break;
+ case 'temporal range':
+ filters.push({ field, timeRange: [...filter.rule.value] as [number | null, number | null] });
+ break;
+ default:
+ onWarn(`Filter on '${filter.name}' (${(filter.rule as { type: string }).type}) cannot be expressed in a terse spec; skipped.`);
+ }
+ }
+ if (filters.length > 0) spec.filters = filters;
+ }
+
+ if (computedDefs.size > 0) spec.computed = [...computedDefs.values()];
+ if (chart.config.defaultAggregated === false) spec.aggregate = false;
+ if (chart.layout.stack !== emptyVisualLayout.stack) spec.stack = chart.layout.stack;
+ if (chart.config.limit > 0) spec.limit = chart.config.limit;
+
+ const configRest: Record<string, unknown> = {};
+ for (const [key, value] of Object.entries(chart.config)) {
+ if (key === 'geoms' || key === 'defaultAggregated' || key === 'limit' || key === '$schema') continue;
+ const defaultValue = (emptyVisualConfig as unknown as Record<string, unknown>)[key];
+ if (value !== undefined && JSON.stringify(value) !== JSON.stringify(defaultValue)) configRest[key] = value;
+ }
+ if (Object.keys(configRest).length > 0) spec.config = configRest;
+
+ const layoutRest: Record<string, unknown> = {};
+ for (const [key, value] of Object.entries(chart.layout)) {
+ if (key === 'stack') continue;
+ const defaultValue = (emptyVisualLayout as unknown as Record<string, unknown>)[key];
+ if (value !== undefined && JSON.stringify(value) !== JSON.stringify(defaultValue)) layoutRest[key] = value;
+ }
+ if (Object.keys(layoutRest).length > 0) spec.layout = layoutRest;
+
+ return spec;
+}
diff --git a/packages/graphic-walker/src/store/visualSpecStore.ts b/packages/graphic-walker/src/store/visualSpecStore.ts
index 16cdf801..97eb3df9 100644
--- a/packages/graphic-walker/src/store/visualSpecStore.ts
+++ b/packages/graphic-walker/src/store/visualSpecStore.ts
@@ -868,6 +868,7 @@ export class VizSpecStore {
}
}
+/** @deprecated Superseded by `normalize()` with a {@link TerseSpec}; will be removed in the next major version. */
export function renderSpec(spec: Specification, meta: IMutField[], name: string, visId: string) {
const chart = newChart(meta, name, visId);
const fields = chart.encodings.dimensions.concat(chart.encodings.measures);