Skip to content

An open source alternative to Tableau. Embeddable visual analytic

fix: address phase-3 review findings on TerseSpec

Elwynn Cheneea9448cf3e9
diff --git a/docs/terse-spec-design.md b/docs/terse-spec-design.md
index 2cbc1cb5..df6fae48 100644
--- a/docs/terse-spec-design.md
+++ b/docs/terse-spec-design.md
@@ -29,8 +29,9 @@ type TerseFieldRef =
| string // 'Sales' | 'sum(Sales)' | 'fid:sales'(见 §3、§4)
| {
field: string; // 名字、shorthand 或 'fid:' 前缀引用
- aggregate?: IAggregator; // 与 shorthand 二选一,重复时报错
+ aggregate?: Exclude<IAggregator, 'expr'>; // 与 shorthand 二选一,重复时报错;'expr' 不允许(走内联 computed)
sort?: 'ascending' | 'descending';
+ /** 展开为真实的 dateTimeDrill 计算字段(query 级钻取,与 UI 钻取语义一致),而非仅轴显示格式 */
timeUnit?: (typeof DATE_TIME_DRILL_LEVELS)[number];
};
@@ -149,6 +150,8 @@ interface TerseSpec {
**为什么不做模糊匹配**:LLM 与人都会写错字段名,但静默容错会把错误图表当正确结果交付;显式报错 + 候选提示的纠错回路更短。
+**已知边界**(实现定稿):字面名恰为整个引用串的字段优先于 shorthand 解读(exact 匹配限定,大小写不敏感回退不参与此规则),`count()` 同样适用;数据列名字面为 `fid:xxx` 形式时无法按名引用,须用其自身 fid 引用(文档明示的限制);内联 computed 的 fid 哈希与既有 fid 冲突时报错(单图冲突检测)。
+
## 4. 聚合 shorthand 文法
```
@@ -168,7 +171,7 @@ aggName := 'sum' | 'count' | 'max' | 'min' | 'mean' | 'median'
1. **解析引用**:全部 `TerseFieldRef` / `TerseFilter.field` / `TerseComputedField` 内的字段引用按 §3 解析成 fid;内联 computed 字段生成确定性 fid(`gw_t_` + name 的短哈希,同名同 fid,保证幂等);
2. **构建池子**:`dimensions/measures 池 = meta 全体字段(newChart 语义,含 count/mea_key/mea_val 合成字段) + 内联 computed 字段`。这正是 dsl-design-review §3.3 的重建规则——terse 不含池子,池子是推导物;
-3. **通道映射**:`x → columns`、`y → rows`,其余通道同名映射;`TerseFieldRef` 展开为完整 `IViewField`(从池子取字段对象,叠加 aggregate/sort/timeUnit 覆盖);
+3. **通道映射**:`x → columns`、`y → rows`,其余通道同名映射;`TerseFieldRef` 展开为完整 `IViewField`(从池子取字段对象,叠加 aggregate/sort 覆盖);**`timeUnit` 展开为真实的 dateTimeDrill 计算字段**——镜像 UI 的 `createDateDrillField` 语义,drill 字段同时进入 dimensions/measures 池(供 `toWorkflow` 收集 transform)与目标通道,影响查询 group-by 而非仅显示;
4. **旋钮映射**:`mark → config.geoms[0]`、`aggregate → config.defaultAggregated`、`stack → layout.stack`、`limit → config.limit`、`sort → 最后一个 y 度量的 sort`;
5. **canonical 片段合并**:`config`/`layout` 字段浅合并,**优先级最高**(显式的 canonical 写法压过扁平旋钮;两处都写时产生 warning);
6. **进入既有管线**:结果作为 `PartialChart` 走 `fillChart` → `algebraLint` + `lintExtraFields` → `$schema` 戳——与 normalize 现有出口完全一致。
@@ -191,6 +194,8 @@ aggName := 'sum' | 'count' | 'max' | 'min' | 'mean' | 'median'
4. **投影往返标准 → 采纳 canonical 层等价**:`normalize(project(normalize(t))) ≡ normalize(t)`。这是测试标准而非运行时行为,不涉及兼容风险;shorthand 的多种等价写法不可能也不需要逐字往返。
5. **mark 数组 / layer → 明确不做**。GW 的 `geoms` 是单值语义,layer 是全新的渲染能力而非语法问题,不在 DSL 层解决。terse 的 `mark` 保持单值;layered Vega-Lite spec 由 `detectSpecKind` 显式路由到 VL 路径并在能力边界处报错(不静默吞掉)。
+**Conformance 待办**(实现阶段发现):`log: { base: N }` 在 N ≠ 2/10 时映射到 op `'log'`(客户端已实现,但 UI 从不生成),SQL 后端与 conformance 套件从未覆盖此 op——上线前应在 conformance 套件加用例。
+
## 8. 与现有机制的关系速查
| 现有物 | TerseSpec 落地后 |
diff --git a/packages/graphic-walker/src/interfaces.ts b/packages/graphic-walker/src/interfaces.ts
index db9d818a..9e860a0b 100644
--- a/packages/graphic-walker/src/interfaces.ts
+++ b/packages/graphic-walker/src/interfaces.ts
@@ -720,17 +720,20 @@ export interface PartialChart {
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.
+ * 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; its
+ * `field` string accepts the same syntax (name / shorthand / `fid:` prefix),
+ * and setting `aggregate` alongside a shorthand is an error. `timeUnit` expands
+ * to a dateTimeDrill computed field — a query-level drill identical to the UI's
+ * drill, not just axis formatting.
*/
export type TerseFieldRef =
| string
| {
field: string;
- aggregate?: IAggregator;
- sort?: ISortMode;
+ aggregate?: Exclude<IAggregator, 'expr'>;
+ sort?: 'ascending' | 'descending';
timeUnit?: (typeof DATE_TIME_DRILL_LEVELS)[number];
};
diff --git a/packages/graphic-walker/src/models/normalize.ts b/packages/graphic-walker/src/models/normalize.ts
index 5877ca62..44bd601e 100644
--- a/packages/graphic-walker/src/models/normalize.ts
+++ b/packages/graphic-walker/src/models/normalize.ts
@@ -28,8 +28,26 @@ export type ISpecKind = 'chart' | 'vis-spec' | 'vega-lite' | 'terse' | 'partial-
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;
+// (canonical specs keep fields and filters inside `encodings`). All terse channel keys
+// are triggers so charts that use no x/y (pie: theta+color, geo: longitude/latitude)
+// still route to the terse branch.
+const TERSE_TRIGGER_KEYS = [
+ 'x',
+ 'y',
+ 'color',
+ 'opacity',
+ 'size',
+ 'shape',
+ 'text',
+ 'details',
+ 'theta',
+ 'radius',
+ 'longitude',
+ 'latitude',
+ 'geoId',
+ '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;
diff --git a/packages/graphic-walker/src/models/terse.test.ts b/packages/graphic-walker/src/models/terse.test.ts
index 135da000..2b515939 100644
--- a/packages/graphic-walker/src/models/terse.test.ts
+++ b/packages/graphic-walker/src/models/terse.test.ts
@@ -323,3 +323,128 @@ describe('projectTerse', () => {
expect(normalize(projected, dupMeta).encodings.rows[0].fid).toBe('a2');
});
});
+
+describe('review fixes (phase-3 single-agent review)', () => {
+ test('F1: count() with sort survives the roundtrip standard', () => {
+ const t: TerseSpec = { x: 'Region', y: 'count()', sort: 'descending' };
+ const canonical = normalize(t, META);
+ const projected = projectTerse(canonical, silent);
+ const reNormalized = normalize(projected, META);
+ const strip = ({ visId, ...rest }: Record<string, unknown>) => rest;
+ expect(strip(reNormalized as never)).toEqual(strip(canonical as never));
+ });
+
+ test('F1: object-form field strings are shorthand-parsed', () => {
+ const chart = normalize({ y: { field: 'sum(Sales)', sort: 'ascending' } } as TerseSpec, META);
+ expect(chart.encodings.rows[0]).toMatchObject({ fid: 'sales', aggName: 'sum', sort: 'ascending' });
+ expect(() => expandTerse({ y: { field: 'sum(Sales)', aggregate: 'mean' } } as TerseSpec, META, silent)).toThrow(/already carries a shorthand/);
+ });
+
+ test('F2: pie and geo specs without x/y route to terse and roundtrip', () => {
+ expect(detectSpecKind({ mark: 'arc', theta: 'sum(Sales)', color: 'Region' })).toBe('terse');
+ expect(detectSpecKind({ longitude: 'fid:sales', latitude: 'fid:profit' })).toBe('terse');
+ const t: TerseSpec = { mark: 'arc', theta: 'sum(Sales)', color: 'Region' };
+ const canonical = normalize(t, META);
+ expect(canonical.encodings.theta[0].fid).toBe('sales');
+ const reNormalized = normalize(projectTerse(canonical, silent), META);
+ const strip = ({ visId, ...rest }: Record<string, unknown>) => rest;
+ expect(strip(reNormalized as never)).toEqual(strip(canonical as never));
+ });
+
+ test('F2: projected specs carry the terse $schema stamp', () => {
+ const projected = projectTerse(normalize({ x: 'Region', y: 'sum(Sales)' } as TerseSpec, META), silent);
+ expect(projected.$schema).toBe(TerseSpecSchemaUrl);
+ expect(detectSpecKind(projected)).toBe('terse');
+ });
+
+ test('F3: timeUnit expands to a real dateTimeDrill computed field affecting the query', () => {
+ const chart = normalize({ x: { field: 'Order Date', timeUnit: 'month' }, y: 'sum(Sales)' } as TerseSpec, META);
+ const drill = chart.encodings.columns[0];
+ expect(drill.computed).toBe(true);
+ expect(drill.expression).toMatchObject({
+ op: 'dateTimeDrill',
+ params: [
+ { type: 'field', value: 'order_date' },
+ { type: 'value', value: 'month' },
+ ],
+ });
+ const workflow = chartToWorkflow(chart).workflow;
+ const transform = workflow.find((s) => s.type === 'transform') as { transform: { expression: { op: string } }[] } | undefined;
+ expect(transform?.transform.some((x) => x.expression.op === 'dateTimeDrill')).toBe(true);
+ const view = workflow.find((s) => s.type === 'view') as { query: { op: string; groupBy?: string[] }[] };
+ expect(view.query[0].groupBy).toContain(drill.fid);
+ // and the roundtrip preserves the drill
+ const reNormalized = normalize(projectTerse(chart, silent), META);
+ const strip = ({ visId, ...rest }: Record<string, unknown>) => rest;
+ expect(strip(reNormalized as never)).toEqual(strip(chart as never));
+ });
+
+ test('F3: display-only timeUnit (no drill expression) is dropped from projection with a warning', () => {
+ const warnings: string[] = [];
+ const canonical = normalize({ x: 'Region', y: 'sum(Sales)' } as TerseSpec, META);
+ const doctored = {
+ ...canonical,
+ encodings: {
+ ...canonical.encodings,
+ columns: [{ ...canonical.encodings.columns[0], timeUnit: 'month' as const }],
+ },
+ };
+ const projected = projectTerse(doctored, (m) => warnings.push(m));
+ expect(projected.x).toBe('Region');
+ expect(warnings.some((w) => w.includes('Display-only timeUnit'))).toBe(true);
+ });
+
+ test('F4: dimension aggregate override, limit 0, and runtime sort none roundtrip', () => {
+ const t1: TerseSpec = { x: { field: 'Region', aggregate: 'sum' }, y: 'sum(Sales)' };
+ const strip = ({ visId, ...rest }: Record<string, unknown>) => rest;
+ const c1 = normalize(t1, META);
+ expect(strip(normalize(projectTerse(c1, silent), META) as never)).toEqual(strip(c1 as never));
+
+ const t2: TerseSpec = { x: 'Region', y: 'sum(Sales)', limit: 0 };
+ const c2 = normalize(t2, META);
+ expect(c2.config.limit).toBe(0);
+ expect(strip(normalize(projectTerse(c2, silent), META) as never)).toEqual(strip(c2 as never));
+
+ const c3 = normalize({ y: { field: 'Sales', sort: 'none' } } as unknown as TerseSpec, META);
+ expect(c3.encodings.rows[0].sort).toBeUndefined();
+ });
+
+ test('F5: computed fid hash collisions are detected within a spec', () => {
+ // real djb2 collision pair found by brute force during review
+ expect(terseComputedFid('f1sq5ezgx7i')).toBe(terseComputedFid('f1wrzde9o54'));
+ expect(() =>
+ expandTerse(
+ {
+ computed: [
+ { name: 'f1sq5ezgx7i', expr: '"Sales" + 1' },
+ { name: 'f1wrzde9o54', expr: '"Sales" + 2' },
+ ],
+ } as TerseSpec,
+ META,
+ silent,
+ ),
+ ).toThrow(/hashes to fid/);
+ });
+
+ test('F6: a column literally named count() wins over the builtin with a warning', () => {
+ const trickyMeta: IMutField[] = [...META, { fid: 'cnt', name: 'count()', semanticType: 'quantitative', analyticType: 'measure' }];
+ const warnings: string[] = [];
+ const partial = expandTerse({ y: 'count()' } as TerseSpec, trickyMeta, (m) => warnings.push(m));
+ expect(partial.encodings?.rows?.[0].fid).toBe('cnt');
+ expect(warnings.some((w) => w.includes('literally named'))).toBe(true);
+ });
+
+ test('F6: aggregate expr on a field reference is rejected', () => {
+ expect(() => expandTerse({ y: { field: 'Sales', aggregate: 'expr' } } as unknown as TerseSpec, META, silent)).toThrow(
+ /not allowed on a field reference/,
+ );
+ });
+
+ test('F6: case-insensitive fallback no longer masquerades as the literal-name rule', () => {
+ const trickyMeta: IMutField[] = [...META, { fid: 'shout', name: 'SUM(SALES)', semanticType: 'quantitative', analyticType: 'measure' }];
+ const warnings: string[] = [];
+ // exact-name miss → shorthand reading wins (resolves Sales + sum), not the case-insensitive literal
+ const partial = expandTerse({ y: 'sum(Sales)' } as TerseSpec, trickyMeta, (m) => warnings.push(m));
+ expect(partial.encodings?.rows?.[0]).toMatchObject({ fid: 'sales', aggName: 'sum' });
+ });
+});
diff --git a/packages/graphic-walker/src/models/terse.ts b/packages/graphic-walker/src/models/terse.ts
index 403d179e..89ff6ee9 100644
--- a/packages/graphic-walker/src/models/terse.ts
+++ b/packages/graphic-walker/src/models/terse.ts
@@ -11,6 +11,7 @@ import {
TerseFieldRef,
TerseFilter,
TerseSpec,
+ TerseSpecSchemaUrl,
} from '../interfaces';
import { newChart } from './visSpecHistory';
import { getSQLItemAnalyticType, parseSQLExpr } from '../lib/sql';
@@ -21,8 +22,13 @@ type OnWarn = (message: string) => void;
// Shorthand aggregates: IAggregator minus 'expr' (aggregate expressions have no
// sensible shorthand syntax and must go through inline computed fields).
+type ShorthandAgg = Exclude<IAggregator, 'expr'>;
const SHORTHAND_AGGS = new Set<IAggregator>(['sum', 'count', 'max', 'min', 'mean', 'median', 'variance', 'stdev', 'distinctCount']);
+function asShorthandAgg(aggName: string | undefined): ShorthandAgg | undefined {
+ return aggName !== undefined && SHORTHAND_AGGS.has(aggName as IAggregator) ? (aggName as ShorthandAgg) : undefined;
+}
+
// terse channel key → canonical encoding channel
const CHANNEL_MAP = {
x: 'columns',
@@ -100,6 +106,25 @@ class FieldIndex {
}
}
+ hasFid(fid: string): boolean {
+ return this.byFid.has(fid);
+ }
+
+ /**
+ * Exact-only lookup (name, then fid) with no case-insensitive fallback and no
+ * error; used by the literal-name-wins rule before the shorthand reading.
+ */
+ resolveExact(raw: string): IViewField | null {
+ 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];
+ }
+ return this.byFid.get(raw) ?? null;
+ }
+
/**
* Resolution order (docs/terse-spec-design.md §3): `fid:` prefix → exact name
* (inline computed fields are in the same index) → exact fid → case-insensitive
@@ -164,6 +189,9 @@ function buildComputedFields(defs: TerseComputedField[], index: FieldIndex, pool
}
seen.set(def.name, definition);
const fid = terseComputedFid(def.name);
+ if (index.hasFid(fid)) {
+ throw new Error(`Computed field '${def.name}' hashes to fid '${fid}', which is already taken by another field; rename the computed field.`);
+ }
let field: IViewField;
if (def.expr !== undefined) {
let parsed;
@@ -214,31 +242,94 @@ function buildComputedFields(defs: TerseComputedField[], index: FieldIndex, pool
return results;
}
-function resolveRef(ref: TerseFieldRef, index: FieldIndex, onWarn: OnWarn): IViewField {
+/**
+ * Resolve a string reference: `fid:` prefix, then a field literally named the
+ * whole string (exact match only — this wins over the shorthand reading, with a
+ * warning), then the aggregate shorthand, then plain resolution.
+ */
+function resolveStringField(raw: string, index: FieldIndex, onWarn: OnWarn): { base: IViewField; aggregate?: IAggregator } {
+ if (raw.startsWith('fid:')) {
+ return { base: index.resolve(raw, onWarn) };
+ }
+ const shorthand = parseShorthand(raw);
+ if (shorthand.aggregate === undefined) {
+ return { base: index.resolve(raw, onWarn) };
+ }
+ const literal = index.resolveExact(raw);
+ if (literal) {
+ onWarn(`'${raw}' resolved to a field literally named '${raw}', not as the ${shorthand.aggregate} shorthand.`);
+ return { base: literal };
+ }
+ if (shorthand.field === '') {
+ if (shorthand.aggregate !== 'count') {
+ throw new Error(`Aggregate shorthand '${raw}' needs a field, e.g. '${shorthand.aggregate}(Sales)'.`);
+ }
+ return { base: index.resolve(`fid:${COUNT_FIELD_ID}`, onWarn) };
+ }
+ return { base: index.resolve(shorthand.field, onWarn), aggregate: shorthand.aggregate };
+}
+
+/**
+ * Mirror of the store's `createDateDrillField` action (visSpecHistory.ts): a terse
+ * `timeUnit` expands to a real dateTimeDrill computed field on the channel, so the
+ * drill affects the query group-by exactly like the UI drill — not just axis display.
+ */
+function createDrillField(base: IViewField, timeUnit: NonNullable<IViewField['timeUnit']>, aggName: IAggregator | undefined, onWarn: OnWarn): IViewField {
+ if (base.semanticType !== 'temporal') {
+ onWarn(`timeUnit '${timeUnit}' applied to non-temporal field '${base.name}' (${base.semanticType}); existing drill semantics parse values as dates.`);
+ }
+ const name = `${timeUnit}(${base.name})`;
+ const fid = terseComputedFid(name);
+ return {
+ fid,
+ name,
+ semanticType: 'temporal',
+ analyticType: base.analyticType,
+ aggName: aggName ?? 'sum',
+ computed: true,
+ timeUnit,
+ expression: {
+ op: 'dateTimeDrill',
+ as: fid,
+ params: [
+ { type: 'field', value: base.fid },
+ { type: 'value', value: timeUnit },
+ ...(base.offset != null ? [{ type: 'offset', value: base.offset } as const] : []),
+ ],
+ },
+ };
+}
+
+function resolveRef(ref: TerseFieldRef, index: FieldIndex, onWarn: OnWarn, onDrill?: (field: IViewField) => void): 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);
- }
+ const resolved = resolveStringField(ref, index, onWarn);
+ base = resolved.base;
+ overrides.aggregate = resolved.aggregate;
} else {
- base = index.resolve(ref.field, onWarn);
- overrides = { aggregate: ref.aggregate, sort: ref.sort, timeUnit: ref.timeUnit };
+ // runtime JSON may carry 'expr' even though the type excludes it
+ if ((ref.aggregate as string) === 'expr') {
+ throw new Error(`Aggregate 'expr' is not allowed on a field reference ('${ref.field}'); use an inline computed field instead.`);
+ }
+ const resolved = resolveStringField(ref.field, index, onWarn);
+ if (resolved.aggregate !== undefined && ref.aggregate !== undefined) {
+ throw new Error(`'${ref.field}' already carries a shorthand aggregate; do not set 'aggregate' as well.`);
+ }
+ base = resolved.base;
+ // runtime JSON may still carry 'none' even though the type excludes it
+ const sort = (ref.sort as string) === 'none' ? undefined : ref.sort;
+ overrides = { aggregate: ref.aggregate ?? resolved.aggregate, sort, timeUnit: ref.timeUnit };
+ }
+ if (overrides.timeUnit) {
+ const drill = createDrillField(base, overrides.timeUnit, overrides.aggregate, onWarn);
+ // The UI appends drill fields to the dimensions/measures pool (datasetFields/utils.ts
+ // passes originChannel = 'dimensions' | 'measures'), which is where toWorkflow collects
+ // transform steps from — so the pool copy is what makes the drill affect the query.
+ onDrill?.(drill);
+ const channelCopy = { ...drill };
+ if (overrides.sort) channelCopy.sort = overrides.sort;
+ return channelCopy;
}
const field: IViewField = { ...base };
if (overrides.aggregate) {
@@ -248,7 +339,6 @@ function resolveRef(ref: TerseFieldRef, index: FieldIndex, onWarn: OnWarn): IVie
field.aggName = overrides.aggregate;
}
if (overrides.sort) field.sort = overrides.sort;
- if (overrides.timeUnit) field.timeUnit = overrides.timeUnit;
return field;
}
@@ -280,11 +370,20 @@ export function expandTerse(spec: TerseSpec, meta: IMutField[], onWarn: OnWarn =
measures: base.encodings.measures.concat(computedFields.filter((f) => f.analyticType === 'measure')),
};
+ const drillFields = new Map<string, IViewField>();
+ const collectDrill = (field: IViewField) => {
+ if (!drillFields.has(field.fid)) drillFields.set(field.fid, field);
+ };
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));
+ encodings[CHANNEL_MAP[key]] = refs.map((ref) => resolveRef(ref, index, onWarn, collectDrill));
+ }
+ if (drillFields.size > 0) {
+ const drills = [...drillFields.values()];
+ encodings.dimensions = encodings.dimensions!.concat(drills.filter((f) => f.analyticType === 'dimension'));
+ encodings.measures = encodings.measures!.concat(drills.filter((f) => f.analyticType === 'measure'));
}
if (spec.filters) {
@@ -403,7 +502,14 @@ export function projectTerse(chart: IChart, onWarn: OnWarn = (msg) => console.wa
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 } : {}) };
+ const drillAgg = field.aggName !== 'sum' ? asShorthandAgg(field.aggName) : undefined;
+ // Round-trips through expandTerse's drill expansion with identical query semantics.
+ return {
+ field: refName(baseField),
+ timeUnit: level.value,
+ ...(drillAgg ? { aggregate: drillAgg } : {}),
+ ...(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;
@@ -415,27 +521,36 @@ export function projectTerse(chart: IChart, onWarn: OnWarn = (msg) => console.wa
}
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);
+ // A timeUnit without a drill expression is display-only formatting; terse timeUnit
+ // means a query-level drill, so emitting it would change computed data. Drop + warn.
+ if (field.timeUnit && !field.expression) {
+ onWarn(`Display-only timeUnit '${field.timeUnit}' on '${field.name}' cannot be expressed in a terse spec; dropped from the projection.`);
+ }
+ const needsObject = field.sort && field.sort !== 'none';
+ const aggregate = asShorthandAgg(field.aggName);
if (needsObject) {
return {
field: name,
- ...(aggregate ? { aggregate: field.aggName as IAggregator } : {}),
- ...(field.sort && field.sort !== 'none' ? { sort: field.sort } : {}),
- ...(field.timeUnit ? { timeUnit: field.timeUnit } : {}),
+ ...(aggregate ? { aggregate } : {}),
+ sort: field.sort as 'ascending' | 'descending',
};
}
if (field.fid === COUNT_FIELD_ID) return 'count()';
if (aggregate) {
- const shorthand = `${field.aggName}(${name})`;
+ if (field.analyticType !== 'measure') {
+ return { field: name, aggregate };
+ }
+ const shorthand = `${aggregate}(${name})`;
const roundtrip = parseShorthand(shorthand);
- if (roundtrip.aggregate === field.aggName && roundtrip.field === name) return shorthand;
- return { field: name, aggregate: field.aggName as IAggregator };
+ if (roundtrip.aggregate === aggregate && roundtrip.field === name) return shorthand;
+ return { field: name, aggregate };
}
return name;
};
- const spec: TerseSpec = {};
+ // Stamped so the projected spec always routes back to the terse branch in
+ // detectSpecKind, whatever channels it happens to use.
+ const spec: TerseSpec = { $schema: TerseSpecSchemaUrl };
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];
@@ -481,7 +596,7 @@ export function projectTerse(chart: IChart, onWarn: OnWarn = (msg) => console.wa
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;
+ if (chart.config.limit !== emptyVisualConfig.limit) spec.limit = chart.config.limit;
const configRest: Record<string, unknown> = {};
for (const [key, value] of Object.entries(chart.config)) {