Skip to content

An open source alternative to Tableau. Embeddable visual analytic

fix: address review findings on normalize spec entry

Elwynn Chen58b70c40e4bb
diff --git a/docs/terse-spec-design.md b/docs/terse-spec-design.md
index e0200de4..9cf18677 100644
--- a/docs/terse-spec-design.md
+++ b/docs/terse-spec-design.md
@@ -174,7 +174,7 @@ aggName := 'sum' | 'count' | 'max' | 'min' | 'mean' | 'median'
## 6. 与 `normalize()` 的接入方式(第三阶段)
-- `detectSpecKind` 增加第一优先级规则:`$schema` 为 tersespec URL,或存在 terse 特征键(`x`/`y`/`mark`/`computed` 且无 `encodings`/`layout`)→ `'terse'`;
+- `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(空图语义一致);
- `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;
- `gen-schema` 管线新增 `tersespec_v1.json` 产物,`$schema` URL 指向它;
diff --git a/packages/graphic-walker/src/models/normalize.test.ts b/packages/graphic-walker/src/models/normalize.test.ts
index 58bb5fbf..efe3bf80 100644
--- a/packages/graphic-walker/src/models/normalize.test.ts
+++ b/packages/graphic-walker/src/models/normalize.test.ts
@@ -244,4 +244,19 @@ describe('$schema forward compatibility', () => {
const exported = store.exportCode();
expect(JSON.stringify(exported)).not.toContain('$schema');
});
+
+ test('applyChart does not leak the stamp into the undoable timeline or history exports', () => {
+ const store = new VizSpecStore(META);
+ store.applyChart(stamped);
+ expect(JSON.stringify(store.exportCurrentChart())).not.toContain('$schema');
+ expect(JSON.stringify(store.exportAllCharts())).not.toContain('$schema');
+ expect(JSON.stringify(store.exportCode())).not.toContain('$schema');
+ expect(store.exportCode()[0].encodings.columns).toEqual(stamped.encodings.columns);
+ });
+});
+
+describe('vega-lite layer detection', () => {
+ test('layered specs route to the vega-lite path instead of silently normalizing to an empty chart', () => {
+ expect(detectSpecKind({ layer: [{ mark: 'bar' }, { mark: 'line' }] })).toBe('vega-lite');
+ });
});
diff --git a/packages/graphic-walker/src/models/normalize.ts b/packages/graphic-walker/src/models/normalize.ts
index 4f6ae540..4fc69ed1 100644
--- a/packages/graphic-walker/src/models/normalize.ts
+++ b/packages/graphic-walker/src/models/normalize.ts
@@ -18,7 +18,9 @@ import { algebraLint } from '../lib/gog';
export type ISpecKind = 'chart' | 'vis-spec' | 'vega-lite' | 'partial-chart';
// Structural keys that exist on Vega-Lite specs but never on IChart / IVisSpec / PartialChart.
-const VEGA_LITE_KEYS = ['mark', 'encoding', 'spec', 'concat', 'hconcat', 'vconcat'] as const;
+// `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;
// 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/store/visualSpecStore.ts b/packages/graphic-walker/src/store/visualSpecStore.ts
index 5e5e69d4..16cdf801 100644
--- a/packages/graphic-walker/src/store/visualSpecStore.ts
+++ b/packages/graphic-walker/src/store/visualSpecStore.ts
@@ -56,7 +56,9 @@ import { getAllFields, getViewEncodingFields } from './storeStateLib';
const encodingKeys = (Object.keys(emptyEncodings) as (keyof DraggableFieldState)[]).filter((dkey) => !GLOBAL_CONFIG.META_FIELD_KEYS.includes(dkey));
-const disposerRegister = (typeof FinalizationRegistry === 'undefined' ? null : new FinalizationRegistry(disposer => disposer())) as FinalizationRegistry<() => void> | null;
+const disposerRegister = (typeof FinalizationRegistry === 'undefined' ? null : new FinalizationRegistry((disposer) => disposer())) as FinalizationRegistry<
+ () => void
+> | null;
export class VizSpecStore {
instanceID: string = uniqueId();
visList: VisSpecWithHistory[];
@@ -101,7 +103,7 @@ export class VizSpecStore {
empty?: boolean;
onMetaChange?: (fid: string, diffMeta: Partial<IMutField>) => void;
defaultConfig?: IDefaultConfig;
- }
+ },
) {
this.meta = meta;
this.visList = options?.empty ? [] : [fromFields(meta, 'Chart 1', options?.defaultConfig)];
@@ -123,9 +125,9 @@ export class VizSpecStore {
spec: this.currentVis,
instanceID: this.instanceID,
},
- })
+ }),
);
- }
+ },
);
disposerRegister?.register(this, disposer);
}
@@ -231,7 +233,7 @@ export class VizSpecStore {
this.sort,
this.config.folds,
this.config.limit,
- this.config.timezoneDisplayOffset
+ this.config.timezoneDisplayOffset,
);
}
@@ -421,7 +423,7 @@ export class VizSpecStore {
...this.visList[index].now,
name: this.visList[index].now.name + ' Copy',
visId: uniqueId(),
- })
+ }),
);
this.createdVis += 1;
this.visIndex = this.visList.length - 1;
@@ -490,7 +492,7 @@ export class VizSpecStore {
destinationKey,
destinationIndex,
uniqueId(),
- limit
+ limit,
);
return;
}
@@ -501,7 +503,7 @@ export class VizSpecStore {
destinationKey,
destinationIndex,
uniqueId(),
- limit
+ limit,
);
}
}
@@ -532,7 +534,7 @@ export class VizSpecStore {
f.expression &&
f.expression.op === binType &&
f.expression.params[0].value === state[stateKey][index].fid &&
- f.expression.num === binNumber
+ f.expression.num === binNumber,
);
if (existedRelatedBinField) {
return existedRelatedBinField.fid;
@@ -559,7 +561,7 @@ export class VizSpecStore {
drillLevel: (typeof DATE_TIME_DRILL_LEVELS)[number],
name: string,
format: string,
- offset: number | undefined
+ offset: number | undefined,
) {
this.visList[this.visIndex] = performers.createDateDrillField(
this.visList[this.visIndex],
@@ -569,7 +571,7 @@ export class VizSpecStore {
uniqueId(),
name,
format,
- offset ?? new Date().getTimezoneOffset()
+ offset ?? new Date().getTimezoneOffset(),
);
}
@@ -579,7 +581,7 @@ export class VizSpecStore {
drillLevel: (typeof DATE_TIME_FEATURE_LEVELS)[number],
name: string,
format: string,
- offset: number | undefined
+ offset: number | undefined,
) {
this.visList[this.visIndex] = performers.createDateFeatureField(
this.visList[this.visIndex],
@@ -589,7 +591,7 @@ export class VizSpecStore {
uniqueId(),
name,
format,
- offset ?? new Date().getTimezoneOffset()
+ offset ?? new Date().getTimezoneOffset(),
);
}
@@ -660,7 +662,10 @@ export class VizSpecStore {
/** replace the current chart as an undoable/redoable timeline action (used by Auto Viz) */
applyChart(chart: IChart) {
- this.visList[this.visIndex] = performers.replaceChart(this.visList[this.visIndex], chart);
+ // Timeline actions are serialized verbatim by exportFullRaw into persisted formats
+ // (IStoInfoV2.specDict), so the normalize() version stamp must not ride along.
+ const { $schema, ...payload } = chart;
+ this.visList[this.visIndex] = performers.replaceChart(this.visList[this.visIndex], payload);
}
selectVisualization(index: number) {
diff --git a/packages/graphic-walker/tests/fixtures/spec-compat/visspec-old-geo-drill.expected.json b/packages/graphic-walker/tests/fixtures/spec-compat/visspec-old-geo-drill.expected.json
new file mode 100644
index 00000000..6d51f740
--- /dev/null
+++ b/packages/graphic-walker/tests/fixtures/spec-compat/visspec-old-geo-drill.expected.json
@@ -0,0 +1,201 @@
+{
+ "config": {
+ "defaultAggregated": true,
+ "geoms": [
+ "choropleth"
+ ],
+ "coordSystem": "geographic",
+ "limit": -1
+ },
+ "encodings": {
+ "dimensions": [
+ {
+ "fid": "province",
+ "name": "Province",
+ "semanticType": "nominal",
+ "analyticType": "dimension",
+ "geoRole": "none"
+ },
+ {
+ "fid": "gw_drill7",
+ "name": "month(Order Date)",
+ "semanticType": "temporal",
+ "analyticType": "dimension",
+ "computed": true,
+ "expression": {
+ "op": "dateTimeDrill",
+ "as": "gw_drill7",
+ "params": [
+ {
+ "type": "field",
+ "value": "order_date"
+ },
+ {
+ "type": "value",
+ "value": "month"
+ }
+ ]
+ }
+ }
+ ],
+ "measures": [
+ {
+ "fid": "gdp",
+ "name": "GDP",
+ "semanticType": "quantitative",
+ "analyticType": "measure",
+ "aggName": "sum"
+ },
+ {
+ "fid": "gw_log9",
+ "name": "log10(GDP)",
+ "semanticType": "quantitative",
+ "analyticType": "measure",
+ "aggName": "mean",
+ "computed": true,
+ "expression": {
+ "op": "log10",
+ "as": "gw_log9",
+ "params": [
+ {
+ "type": "field",
+ "value": "gdp"
+ }
+ ]
+ }
+ }
+ ],
+ "rows": [],
+ "columns": [],
+ "color": [
+ {
+ "fid": "gw_log9",
+ "name": "log10(GDP)",
+ "semanticType": "quantitative",
+ "analyticType": "measure",
+ "aggName": "mean",
+ "computed": true,
+ "expression": {
+ "op": "log10",
+ "as": "gw_log9",
+ "params": [
+ {
+ "type": "field",
+ "value": "gdp"
+ }
+ ]
+ }
+ }
+ ],
+ "opacity": [],
+ "size": [],
+ "shape": [],
+ "radius": [],
+ "theta": [],
+ "longitude": [],
+ "latitude": [],
+ "geoId": [
+ {
+ "fid": "province",
+ "name": "Province",
+ "semanticType": "nominal",
+ "analyticType": "dimension",
+ "geoRole": "none"
+ }
+ ],
+ "details": [
+ {
+ "fid": "gw_drill7",
+ "name": "month(Order Date)",
+ "semanticType": "temporal",
+ "analyticType": "dimension",
+ "computed": true,
+ "expression": {
+ "op": "dateTimeDrill",
+ "as": "gw_drill7",
+ "params": [
+ {
+ "type": "field",
+ "value": "order_date"
+ },
+ {
+ "type": "value",
+ "value": "month"
+ }
+ ]
+ }
+ }
+ ],
+ "filters": [],
+ "text": []
+ },
+ "layout": {
+ "showActions": false,
+ "showTableSummary": false,
+ "stack": "stack",
+ "interactiveScale": false,
+ "zeroScale": true,
+ "size": {
+ "mode": "auto",
+ "width": 320,
+ "height": 200
+ },
+ "format": {},
+ "geoKey": "iso_3166_2",
+ "resolve": {
+ "x": false,
+ "y": false,
+ "color": false,
+ "opacity": false,
+ "shape": false,
+ "size": false
+ },
+ "renderer": "vega-lite",
+ "geojson": {
+ "type": "FeatureCollection",
+ "features": [
+ {
+ "type": "Feature",
+ "properties": {
+ "iso_3166_2": "CN-BJ"
+ },
+ "geometry": {
+ "type": "Polygon",
+ "coordinates": [
+ [
+ [
+ 116,
+ 39.5
+ ],
+ [
+ 116.8,
+ 39.5
+ ],
+ [
+ 116.8,
+ 40.2
+ ],
+ [
+ 116,
+ 40.2
+ ],
+ [
+ 116,
+ 39.5
+ ]
+ ]
+ ]
+ }
+ }
+ ]
+ },
+ "geoUrl": {
+ "type": "TopoJSON",
+ "url": "https://example.com/cn-provinces.topo.json"
+ },
+ "scaleIncludeUnmatchedChoropleth": true
+ },
+ "visId": "gw-fixture-old-geo-drill",
+ "name": "Legacy Choropleth with Drill",
+ "$schema": "https://graphic-walker.kanaries.net/chartinfo.json"
+}
diff --git a/packages/graphic-walker/tests/fixtures/spec-compat/visspec-old-geo-drill.input.json b/packages/graphic-walker/tests/fixtures/spec-compat/visspec-old-geo-drill.input.json
new file mode 100644
index 00000000..901ee794
--- /dev/null
+++ b/packages/graphic-walker/tests/fixtures/spec-compat/visspec-old-geo-drill.input.json
@@ -0,0 +1,87 @@
+{
+ "visId": "gw-fixture-old-geo-drill",
+ "name": "Legacy Choropleth with Drill",
+ "encodings": {
+ "dimensions": [
+ { "fid": "province", "name": "Province", "semanticType": "nominal", "analyticType": "dimension", "geoRole": "none" },
+ {
+ "fid": "gw_drill7",
+ "name": "month(Order Date)",
+ "semanticType": "temporal",
+ "analyticType": "dimension",
+ "computed": true,
+ "expression": {
+ "op": "dateTimeDrill",
+ "as": "gw_drill7",
+ "params": [
+ { "type": "field", "value": "order_date" },
+ { "type": "value", "value": "month" }
+ ]
+ }
+ }
+ ],
+ "measures": [
+ { "fid": "gdp", "name": "GDP", "semanticType": "quantitative", "analyticType": "measure", "aggName": "sum" },
+ {
+ "fid": "gw_log9",
+ "name": "log10(GDP)",
+ "semanticType": "quantitative",
+ "analyticType": "measure",
+ "aggName": "mean",
+ "computed": true,
+ "expression": { "op": "log10", "as": "gw_log9", "params": [{ "type": "field", "value": "gdp" }] }
+ }
+ ],
+ "geoId": [{ "fid": "province", "name": "Province", "semanticType": "nominal", "analyticType": "dimension", "geoRole": "none" }],
+ "color": [
+ {
+ "fid": "gw_log9",
+ "name": "log10(GDP)",
+ "semanticType": "quantitative",
+ "analyticType": "measure",
+ "aggName": "mean",
+ "computed": true,
+ "expression": { "op": "log10", "as": "gw_log9", "params": [{ "type": "field", "value": "gdp" }] }
+ }
+ ],
+ "details": [
+ {
+ "fid": "gw_drill7",
+ "name": "month(Order Date)",
+ "semanticType": "temporal",
+ "analyticType": "dimension",
+ "computed": true,
+ "expression": {
+ "op": "dateTimeDrill",
+ "as": "gw_drill7",
+ "params": [
+ { "type": "field", "value": "order_date" },
+ { "type": "value", "value": "month" }
+ ]
+ }
+ }
+ ],
+ "filters": []
+ },
+ "config": {
+ "defaultAggregated": true,
+ "geoms": ["choropleth"],
+ "coordSystem": "geographic",
+ "stack": "stack",
+ "showTableSummary": false,
+ "limit": -1,
+ "geoKey": "iso_3166_2",
+ "geoUrl": { "type": "TopoJSON", "url": "https://example.com/cn-provinces.topo.json" },
+ "geojson": {
+ "type": "FeatureCollection",
+ "features": [
+ {
+ "type": "Feature",
+ "properties": { "iso_3166_2": "CN-BJ" },
+ "geometry": { "type": "Polygon", "coordinates": [[[116.0, 39.5], [116.8, 39.5], [116.8, 40.2], [116.0, 40.2], [116.0, 39.5]]] }
+ }
+ ]
+ },
+ "scaleIncludeUnmatchedChoropleth": true
+ }
+}
diff --git a/packages/graphic-walker/tests/specCompat.test.ts b/packages/graphic-walker/tests/specCompat.test.ts
index 9698ece3..96162fbc 100644
--- a/packages/graphic-walker/tests/specCompat.test.ts
+++ b/packages/graphic-walker/tests/specCompat.test.ts
@@ -20,7 +20,15 @@ import { DataStore } from '../src/store/dataStore';
const DIR = path.join(__dirname, 'fixtures', 'spec-compat');
const read = (name: string) => JSON.parse(fs.readFileSync(path.join(DIR, name), 'utf8'));
-const CHART_FIXTURES = ['visspec-old-full', 'visspec-old-sparse', 'chart-current-complex', 'chart-geographic', 'partial-minimal', 'special-chars'];
+const CHART_FIXTURES = [
+ 'visspec-old-full',
+ 'visspec-old-sparse',
+ 'visspec-old-geo-drill',
+ 'chart-current-complex',
+ 'chart-geographic',
+ 'partial-minimal',
+ 'special-chars',
+];
describe.each(CHART_FIXTURES)('chart fixture: %s', (name) => {
const input = read(`${name}.input.json`);