An open source alternative to Tableau. Embeddable visual analytic
TypeScript bidatadata-analysisdata-miningdata-visualizationedak6skanarieslow-codepivot-tablereacttableautableau-alternativetypescriptvegavega-litevisualization
feat: release 0.6.0 with worksheet as the default renderer (#529)
Elwynn Chen9dfff5967803
diff --git a/packages/computation-conformance/package.json b/packages/computation-conformance/package.jsonindex fa085162..397e0002 100644--- a/packages/computation-conformance/package.json+++ b/packages/computation-conformance/package.json@@ -13,7 +13,7 @@"singleQuote": true},"dependencies": {- "@kanaries/graphic-walker": "0.5.3"+ "@kanaries/graphic-walker": "0.6.0"},"devDependencies": {"@duckdb/duckdb-wasm": "^1.28.0",diff --git a/packages/duckdb-wasm-computation/package.json b/packages/duckdb-wasm-computation/package.jsonindex 8d7daf8d..0ffd459e 100644--- a/packages/duckdb-wasm-computation/package.json+++ b/packages/duckdb-wasm-computation/package.json@@ -16,7 +16,7 @@},"devDependencies": {"@duckdb/duckdb-wasm": "^1.28.0",- "@kanaries/graphic-walker": "0.5.3",+ "@kanaries/graphic-walker": "0.6.0","@kanaries/gw-dsl-parser": "^0.1.48-rc3","apache-arrow": "^17.0.0","nanoid": "^5.0.1",diff --git a/packages/graphic-walker/package.json b/packages/graphic-walker/package.jsonindex 392c3158..731b445b 100644--- a/packages/graphic-walker/package.json+++ b/packages/graphic-walker/package.json@@ -1,12 +1,12 @@{"name": "@kanaries/graphic-walker",- "version": "0.5.3",+ "version": "0.6.0","scripts": {"dev:front_end": "vite --host","dev": "npm run dev:front_end","sync:datasets": "node ../../scripts/demo-datasets.mjs ./public/datasets","gen-schema": "node scripts/create-json-schema.js",- "build": "vite build && tspc --build && yarn gen-schema",+ "build": "vite build && node scripts/build-types.mjs && yarn gen-schema","build:app": "vite build --config vite-app.config.ts","serve": "vite preview","type": "tsc src/lib.ts --declaration --emitDeclarationOnly --jsx react --esModuleInterop --outDir dist",diff --git a/packages/graphic-walker/public/tersespec_v1.json b/packages/graphic-walker/public/tersespec_v1.jsonindex 3c317427..f2c77022 100644--- a/packages/graphic-walker/public/tersespec_v1.json+++ b/packages/graphic-walker/public/tersespec_v1.json@@ -265,9 +265,11 @@"type": "string","enum": ["vega-lite",- "observable-plot"+ "observable-plot",+ "native"],- "default": "vega-lite"+ "description": "'native' is the bundled default worksheet renderer. Unsupported charts show a notice; renderers never replace one another automatically. Maps and tables use their own components regardless of this setting.",+ "default": "native"}},"additionalProperties": falsediff --git a/packages/graphic-walker/scripts/build-types.mjs b/packages/graphic-walker/scripts/build-types.mjsnew file mode 100644index 00000000..14c70820--- /dev/null+++ b/packages/graphic-walker/scripts/build-types.mjs@@ -0,0 +1,12 @@+import { execFileSync } from 'node:child_process';+import { createRequire } from 'node:module';+import { fileURLToPath } from 'node:url';++const require = createRequire(import.meta.url);+const cwd = fileURLToPath(new URL('..', import.meta.url));+const run = (module, args) => execFileSync(process.execPath, [require.resolve(module), ...args], { cwd, stdio: 'inherit' });++// The runtime is bundled by Vite. Ship its modules and declarations inside this package as well,+// so consumers never need the private worksheet workspace or the monorepo's paths.+run('typescript/bin/tsc', ['-p', '../worksheet-renderer/tsconfig.json', '--noEmit', 'false', '--declaration', '--rootDir', '../worksheet-renderer/src', '--outDir', 'dist/worksheet']);+run('ts-patch/bin/tspc.js', ['-p', 'tsconfig.build.json']);diff --git a/packages/graphic-walker/src/components/visualConfig/index.tsx b/packages/graphic-walker/src/components/visualConfig/index.tsxindex 3a7de330..c219d785 100644--- a/packages/graphic-walker/src/components/visualConfig/index.tsx+++ b/packages/graphic-walker/src/components/visualConfig/index.tsx@@ -21,6 +21,7 @@ import { DropdownMenu, DropdownMenuCheckboxItem, DropdownMenuContent, DropdownMeimport { vegaThemeContext } from '../../store/theme';import { ColorPickerComponent } from './color-picker';import { Switch } from '../ui/switch';+import { useNativeRenderer } from '../../renderer/nativeRegistry';function SettingRow(props: { title: React.ReactNode; description?: React.ReactNode; htmlFor?: string; children?: React.ReactNode }) {return (@@ -160,7 +161,8 @@ const VisualConfigPanel: React.FC = () => {const [svg, setSvg] = useState<boolean>(layout.useSvg ?? false);const [scaleIncludeUnmatchedChoropleth, setScaleIncludeUnmatchedChoropleth] = useState<boolean>(layout.scaleIncludeUnmatchedChoropleth ?? false);const [showAllGeoshapeInChoropleth, setShowAllGeoshapeInChoropleth] = useState<boolean>(layout.showAllGeoshapeInChoropleth ?? false);- const [renderer, setRenderer] = useState<'vega-lite' | 'observable-plot'>(layout.renderer ?? 'vega-lite');+ const [renderer, setRenderer] = useState<NonNullable<IVisualLayout['renderer']>>(layout.renderer ?? 'native');+ const nativeAvailable = Boolean(useNativeRenderer());const [background, setBackground] = useState({ r: 255, g: 255, b: 255, a: 0 });const [defaultColor, setDefaultColor] = useState({ r: 91, g: 143, b: 249, a: 1 });const [primaryColorEdited, setPrimaryColorEdited] = useState(false);@@ -189,7 +191,7 @@ const VisualConfigPanel: React.FC = () => {useEffect(() => {setZeroScale(layout.zeroScale);setSvg(layout.useSvg ?? false);- setRenderer(layout.renderer ?? 'vega-lite');+ setRenderer(layout.renderer ?? 'native');setBackground(extractRGBA({@@ -585,18 +587,22 @@ const VisualConfigPanel: React.FC = () => {<div><label className="text-xs font-medium leading-6">Renderer</label><p className="text-xs text-gray-500">- Choose between VegaLite and Observable Plot renderers+ Choose between Worksheet, VegaLite and Observable Plot renderers</p></div><ComboboxclassName="w-40 h-fit"popClassName="w-40"selectedKey={renderer}- onSelect={(value) => setRenderer(value as 'vega-lite' | 'observable-plot')}- options={GLOBAL_CONFIG.RENDERER_TYPES.map((type) => ({- value: type,- label: type === 'vega-lite' ? 'VegaLite' : 'Observable Plot',- }))}+ onSelect={(value) => setRenderer(value as NonNullable<IVisualLayout['renderer']>)}+ options={[+ ...GLOBAL_CONFIG.RENDERER_TYPES.map((type) => ({+ value: type as string,+ label: type === 'vega-lite' ? 'VegaLite' : 'Observable Plot',+ })),+ // Offered only where a host has registered the worksheet renderer.+ ...(nativeAvailable || renderer === 'native' ? [{ value: 'native', label: 'Worksheet' }] : []),+ ]}/></div></div>diff --git a/packages/graphic-walker/src/fields/posFields/index.tsx b/packages/graphic-walker/src/fields/posFields/index.tsxindex 15b7dfdf..508bccdf 100644--- a/packages/graphic-walker/src/fields/posFields/index.tsx+++ b/packages/graphic-walker/src/fields/posFields/index.tsx@@ -7,11 +7,14 @@ import { DRAGGABLE_STATE_KEYS } from '../fieldsContext';import OBFieldContainer from '../obComponents/obFContainer';import { IDraggableViewStateKey } from '../../interfaces';+import { useNativeRenderer } from '../../renderer/nativeRegistry';const PosFields: React.FC = (props) => {const vizStore = useVizStore();- const { config } = vizStore;+ const { config, layout } = vizStore;const { geoms, coordSystem = 'generic' } = config;+ // The native worksheet renderer draws one pie per cell of the rows and columns, so those shelves stay in view.+ const facetedPie = Boolean(useNativeRenderer()) && layout.renderer === 'native';const channels = useMemo(() => {if (coordSystem === 'geographic') {@@ -21,10 +24,10 @@ const PosFields: React.FC = (props) => {return DRAGGABLE_STATE_KEYS.filter((f) => f.id === 'longitude' || f.id === 'latitude') as IDraggableViewStateKey[];}if (geoms[0] === 'arc') {- return DRAGGABLE_STATE_KEYS.filter((f) => f.id === 'radius' || f.id === 'theta') as IDraggableViewStateKey[];+ return DRAGGABLE_STATE_KEYS.filter((f) => f.id === 'radius' || f.id === 'theta' || (facetedPie && (f.id === 'columns' || f.id === 'rows'))) as IDraggableViewStateKey[];}return DRAGGABLE_STATE_KEYS.filter((f) => f.id === 'columns' || f.id === 'rows') as IDraggableViewStateKey[];- }, [geoms[0], coordSystem]);+ }, [geoms[0], coordSystem, facetedPie]);return (<div>{channels.map((dkey, i) => (diff --git a/packages/graphic-walker/src/interfaces.ts b/packages/graphic-walker/src/interfaces.tsindex bcd98b53..16e90167 100644--- a/packages/graphic-walker/src/interfaces.ts+++ b/packages/graphic-walker/src/interfaces.ts@@ -430,8 +430,13 @@ export interface IVisualLayout {/** @default false */scaleIncludeUnmatchedChoropleth?: boolean;showAllGeoshapeInChoropleth?: boolean;- /** @default "vega-lite" */- renderer?: 'vega-lite' | 'observable-plot';+ /**+ * 'native' is the bundled default worksheet renderer. Unsupported charts show a notice;+ * renderers never replace one another automatically. Maps and tables use their own+ * components regardless of this setting.+ * @default "native"+ */+ renderer?: 'vega-lite' | 'observable-plot' | 'native';}export interface IVisualConfigNew {@@ -1038,7 +1043,7 @@ export interface IVizStoreProps {defaultConfig?: IDefaultConfig;/** Initial UI defaults. Changes do not override user actions or a reused keepAlive store. */defaultUIConfig?: IDefaultUIConfig;- defaultRenderer?: 'vega-lite' | 'observable-plot';+ defaultRenderer?: 'vega-lite' | 'observable-plot' | 'native';}export interface ILocalComputationProps {diff --git a/packages/graphic-walker/src/lib/gog.ts b/packages/graphic-walker/src/lib/gog.tsindex 2d69c595..b6e7f8f3 100644--- a/packages/graphic-walker/src/lib/gog.ts+++ b/packages/graphic-walker/src/lib/gog.ts@@ -45,6 +45,12 @@ const LR = {};},};+/**+ * How many dimensions the Vega-Lite and Observable Plot renderers take on rows and on columns:+ * one for the position inside a facet, one for the facet. A shelf with more would be drawn+ * with levels left out.+ */+export const CLASSIC_CROSS_LIMIT = 2;type Operator<T> = (value: T) => T;function applyOperations<T>(initialValue: T, operators: Operator<T>[]): T {return operators.reduce((currentValue, operator) => operator(currentValue), initialValue);@@ -57,14 +63,16 @@ function applyOperations<T>(initialValue: T, operators: Operator<T>[]): T {* @param encodings* @returns*/-export function algebraLint<T extends Partial<DraggableFieldState>>(geom: string, encodings: T): Partial<T> {+export function algebraLint<T extends Partial<DraggableFieldState>>(geom: string, encodings: T, options: { unlimitedCross?: boolean } = {}): Partial<T> {+ // The native worksheet renderer nests any number of dimensions, like the pivot table does.+ const crossLimit = geom === 'table' || options.unlimitedCross ? Infinity : CLASSIC_CROSS_LIMIT;const result: Partial<T> = {};if (encodings.rows && encodings.rows.length > 0) {- result.rows = applyOperations(encodings.rows, [LR.measureAfterDimension, LR.crossLimit(geom === 'table' ? Infinity : 2)]);+ result.rows = applyOperations(encodings.rows, [LR.measureAfterDimension, LR.crossLimit(crossLimit)]);}if (encodings.columns && encodings.columns.length > 0) {- result.columns = applyOperations(encodings.columns, [LR.measureAfterDimension, LR.crossLimit(geom === 'table' ? Infinity : 2)]);+ result.columns = applyOperations(encodings.columns, [LR.measureAfterDimension, LR.crossLimit(crossLimit)]);}if (encodings.latitude && encodings.latitude.length > 0) {result.latitude = applyOperations(encodings.latitude, [LR.forceAnalyticType('dimension'), LR.forceSemanticType('quantitative'), LR.crossLimit(1)]);diff --git a/packages/graphic-walker/src/lib/sql.ts b/packages/graphic-walker/src/lib/sql.tsindex 3d1c352a..ec85cef7 100644--- a/packages/graphic-walker/src/lib/sql.ts+++ b/packages/graphic-walker/src/lib/sql.ts@@ -578,18 +578,21 @@ export function getSQLItemAnalyticType(item: parser.Expr, fields: IMutField[]) {return walk(item);}+/**+ * The fields an expression reads, wherever they stand in it: as operands, as the arguments of a+ * function such as sum(a), in the branches of a case. The star of count(*) is not a field.+ */export function walkFid(sql: string): string[] {const set = new Set<string>();- const walk = (i: parser.Expr) => {- if (i.type === 'ref') {- set.add(i.name);- } else {- Object.values(i).forEach((x) => {- if (x !== null && typeof x === 'object' && 'type' in x) {- walk(x);- }- });+ const walk = (node: unknown) => {+ if (node === null || typeof node !== 'object') return;+ if (Array.isArray(node)) return node.forEach(walk);+ if ((node as parser.Expr).type === 'ref') {+ const { name } = node as parser.ExprRef;+ if (name !== '*') set.add(name);+ return;}+ Object.values(node).forEach(walk);};walk(parseSQLExpr(sql));return Array.from(set);diff --git a/packages/graphic-walker/src/locales/en-US.json b/packages/graphic-walker/src/locales/en-US.jsonindex efbec6f6..03190642 100644--- a/packages/graphic-walker/src/locales/en-US.json+++ b/packages/graphic-walker/src/locales/en-US.json@@ -123,6 +123,21 @@"more": "Analyze more fields"}},+ "chart_notice": {+ "loading_title": "Loading the worksheet renderer…",+ "unavailable_title": "The worksheet renderer is not available here",+ "unavailable_desc": "This chart is set to be drawn by the worksheet renderer, which this environment does not include. The chart is kept as it is, and no other renderer draws it in its place. Open it where the worksheet renderer is available, or choose another renderer in the chart settings.",+ "unsupported_title": "The worksheet renderer cannot draw this chart yet",+ "unsupported_desc": "The chart is kept as it is. Change what the message names, or choose another renderer in the chart settings.",+ "failed_title": "The chart could not be drawn",+ "failed_desc": "The chart and its renderer are kept as they are. Try again, or change the chart.",+ "retry": "Try again",+ "levels_title": "{{renderer}} cannot show every level of this chart",+ "levels_reason": "{{shelf}} holds {{count}} dimensions ({{fields}}). {{renderer}} shows two at most.",+ "levels_desc": "Drawing it would leave levels out, so nothing is drawn. The chart is kept as it is. Take dimensions off the shelf, or choose a renderer that nests them in the chart settings.",+ "shelf_rows": "Rows",+ "shelf_columns": "Columns"+ },"constant": {"row_count": "Row count","mea_key": "Measure names",diff --git a/packages/graphic-walker/src/locales/ja-JP.json b/packages/graphic-walker/src/locales/ja-JP.jsonindex a19de6f8..cbda9357 100644--- a/packages/graphic-walker/src/locales/ja-JP.json+++ b/packages/graphic-walker/src/locales/ja-JP.json@@ -122,6 +122,21 @@"more": "さらにフィールドを分析"}},+ "chart_notice": {+ "loading_title": "ワークシートレンダラーを読み込み中…",+ "unavailable_title": "この環境ではワークシートレンダラーを利用できません",+ "unavailable_desc": "このチャートはワークシートレンダラー(プレビュー)で描画する設定ですが、この環境には含まれていません。チャートの設定はそのまま保持され、他のレンダラーで代わりに描画されることはありません。ワークシートレンダラーを利用できる環境で開くか、チャート設定で別のレンダラーを選択してください。",+ "unsupported_title": "ワークシートレンダラーはこのチャートをまだ描画できません",+ "unsupported_desc": "チャートの設定はそのまま保持されます。上記の内容を変更するか、チャート設定で別のレンダラーを選択してください。",+ "failed_title": "チャートを描画できませんでした",+ "failed_desc": "チャートの設定と選択したレンダラーはそのまま保持されます。再試行するか、チャートを変更してください。",+ "retry": "再試行",+ "levels_title": "{{renderer}} はこのチャートのすべての階層を表示できません",+ "levels_reason": "{{shelf}}に {{count}} 個のディメンションがあります({{fields}})。{{renderer}} が表示できるのは 2 個までです。",+ "levels_desc": "描画すると階層が欠けるため、描画していません。チャートの設定はそのまま保持されます。シェルフからディメンションを外すか、チャート設定で入れ子に対応したレンダラーを選択してください。",+ "shelf_rows": "行",+ "shelf_columns": "列"+ },"constant": {"row_count": "行数","mea_key": "名",diff --git a/packages/graphic-walker/src/locales/zh-CN.json b/packages/graphic-walker/src/locales/zh-CN.jsonindex a6581f83..a588d1cb 100644--- a/packages/graphic-walker/src/locales/zh-CN.json+++ b/packages/graphic-walker/src/locales/zh-CN.json@@ -122,6 +122,21 @@"more": "分析更多字段"}},+ "chart_notice": {+ "loading_title": "正在加载工作表渲染器…",+ "unavailable_title": "当前环境没有工作表渲染器",+ "unavailable_desc": "这张图表设置为由工作表渲染器(预览)绘制,当前环境没有提供它。图表配置保持不变,也不会改用其他渲染器绘制。请在提供工作表渲染器的环境中打开,或在图表设置里选择其他渲染器。",+ "unsupported_title": "工作表渲染器暂时不能绘制这张图表",+ "unsupported_desc": "图表配置保持不变。请调整上面提到的内容,或在图表设置里选择其他渲染器。",+ "failed_title": "图表绘制失败",+ "failed_desc": "图表配置和所选渲染器保持不变。可以重试,或修改图表。",+ "retry": "重试",+ "levels_title": "{{renderer}} 无法展示这张图表的全部层级",+ "levels_reason": "{{shelf}}上有 {{count}} 个维度({{fields}}),{{renderer}} 最多展示两个。",+ "levels_desc": "继续绘制会漏掉层级,所以没有绘制。图表配置保持不变。请从该栏移除维度,或在图表设置里选择支持多层嵌套的渲染器。",+ "shelf_rows": "行",+ "shelf_columns": "列"+ },"constant": {"row_count": "行数","mea_key": "度量名称",diff --git a/packages/graphic-walker/src/main.tsx b/packages/graphic-walker/src/main.tsxindex d5b87a27..fd18a3fe 100644--- a/packages/graphic-walker/src/main.tsx+++ b/packages/graphic-walker/src/main.tsx@@ -6,7 +6,11 @@ if (!import.meta.env.DEV) {inject();}+// In development `?lang=zh-CN` opens the editor in that language, to check translated output without a host app.+const lang = import.meta.env.DEV ? new URLSearchParams(window.location.search).get('lang') : null;+embedGraphicWalker(document.getElementById('root') as HTMLElement, {+ ...(lang ? { i18nLang: lang } : {}),geoList: [{ name: 'World Countries', type: 'GeoJSON', url: 'https://raw.githubusercontent.com/johan/world.geo.json/master/countries.geo.json' },{diff --git a/packages/graphic-walker/src/models/chat.test.ts b/packages/graphic-walker/src/models/chat.test.tsindex 3433bd74..6ade7d71 100644--- a/packages/graphic-walker/src/models/chat.test.ts+++ b/packages/graphic-walker/src/models/chat.test.ts@@ -58,7 +58,7 @@ const createTestChart = (defaultAggregated = true): IChart => {stack: 'stack',showActions: false,zeroScale: true,- renderer: 'vega-lite',+ renderer: 'native',};return {diff --git a/packages/graphic-walker/src/models/normalize.test.ts b/packages/graphic-walker/src/models/normalize.test.tsindex efe3bf80..5eb83fa3 100644--- a/packages/graphic-walker/src/models/normalize.test.ts+++ b/packages/graphic-walker/src/models/normalize.test.ts@@ -74,7 +74,7 @@ describe('normalize', () => {expect(result.name).toBe('Chart');expect(result.config).toEqual({ defaultAggregated: true, geoms: ['auto'], coordSystem: 'generic', limit: -1 });expect(result.layout.size).toEqual({ mode: 'auto', width: 320, height: 200 });- expect(result.layout.renderer).toBe('vega-lite');+ expect(result.layout.renderer).toBe('native');expect(result.encodings.columns).toEqual([dim('category')]);expect(result.encodings.rows).toEqual([mea('sales')]);expect(result.$schema).toBe(IChartSchemaUrl);@@ -150,7 +150,7 @@ describe('normalize', () => {expect(result.$schema).toBe(IChartSchemaUrl);});- test('applies algebraLint: dimensions first, at most 2 cross dimensions for non-table geoms', () => {+ test('the default worksheet renderer keeps every dimension, before measures', () => {const result = normalize({config: { geoms: ['bar'], defaultAggregated: true, limit: -1 },@@ -158,7 +158,7 @@ describe('normalize', () => {},META,);- expect(result.encodings.rows.map((f) => f.fid)).toEqual(['category', 'region', 'sales']);+ expect(result.encodings.rows.map((f) => f.fid)).toEqual(['category', 'region', 'city', 'sales']);});test('algebraLint keeps all dimensions for table geom', () => {diff --git a/packages/graphic-walker/src/models/normalize.ts b/packages/graphic-walker/src/models/normalize.tsindex 94b77426..3c34568e 100644--- a/packages/graphic-walker/src/models/normalize.ts+++ b/packages/graphic-walker/src/models/normalize.ts@@ -167,7 +167,7 @@ export function normalize(input: IChart | IVisSpec | PartialChart | TerseSpec |// so normalized output matches what the UI would converge to for the same spec.const encodings: DraggableFieldState = {...filled.encodings,- ...algebraLint(geom, filled.encodings),+ ...algebraLint(geom, filled.encodings, { unlimitedCross: filled.layout.renderer === 'native' }),...lintExtraFields(filled.encodings),};return {diff --git a/packages/graphic-walker/src/models/visSpecHistory.ts b/packages/graphic-walker/src/models/visSpecHistory.tsindex 75a3321b..9f872ee1 100644--- a/packages/graphic-walker/src/models/visSpecHistory.ts+++ b/packages/graphic-walker/src/models/visSpecHistory.ts@@ -532,11 +532,12 @@ type reducerMiddleware<T> = (item: T, original: T) => T;const diffLinter: reducerMiddleware<IChart> = (item, original) => {const diffs = diffChangedEncodings(original, item);const geom = item.config.geoms[0];+ const lintOptions = { unlimitedCross: item.layout.renderer === 'native' };if (Object.keys(diffs).length === 0 && arrayEqual(item.config.geoms, original.config.geoms)) return item;if (!arrayEqual(item.config.geoms, original.config.geoms)) {- return mutPath(item, 'encodings', (x) => ({ ...x, ...algebraLint(geom, x), ...lintExtraFields(x) }));+ return mutPath(item, 'encodings', (x) => ({ ...x, ...algebraLint(geom, x, lintOptions), ...lintExtraFields(x) }));}- return mutPath(item, 'encodings', (x) => ({ ...x, ...algebraLint(geom, diffs), ...lintExtraFields(diffs) }));+ return mutPath(item, 'encodings', (x) => ({ ...x, ...algebraLint(geom, diffs, lintOptions), ...lintExtraFields(diffs) }));};const reducerMiddleWares: reducerMiddleware<IChart>[] = [diffLinter];diff --git a/packages/graphic-walker/src/renderer/chartNotice.tsx b/packages/graphic-walker/src/renderer/chartNotice.tsxnew file mode 100644index 00000000..cd3b2c82--- /dev/null+++ b/packages/graphic-walker/src/renderer/chartNotice.tsx@@ -0,0 +1,60 @@+import React from 'react';+import { useTranslation } from 'react-i18next';+import { Button } from '@/components/ui/button';+import type { ChartNoticeContent } from './route';++// What is shown where the translations are not loaded, as in a renderer mounted without the editor.+const english = {+ loading_title: 'Loading the worksheet renderer…',+ unavailable_title: 'The worksheet renderer is not available here',+ unavailable_desc:+ 'This chart is set to be drawn by the worksheet renderer, which this environment does not include. The chart is kept as it is, and no other renderer draws it in its place. Open it where the worksheet renderer is available, or choose another renderer in the chart settings.',+ unsupported_title: 'The worksheet renderer cannot draw this chart yet',+ unsupported_desc: 'The chart is kept as it is. Change what the message names, or choose another renderer in the chart settings.',+ failed_title: 'The chart could not be drawn',+ failed_desc: 'The chart and its renderer are kept as they are. Try again, or change the chart.',+ retry: 'Try again',+ levels_title: '{{renderer}} cannot show every level of this chart',+ levels_reason: '{{shelf}} holds {{count}} dimensions ({{fields}}). {{renderer}} shows two at most.',+ levels_desc:+ 'Drawing it would leave levels out, so nothing is drawn. The chart is kept as it is. Take dimensions off the shelf, or choose a renderer that nests them in the chart settings.',+ shelf_rows: 'Rows',+ shelf_columns: 'Columns',+};+const rendererNames = { 'vega-lite': 'VegaLite', 'observable-plot': 'Observable Plot' };++/**+ * Stands in the chart area for a chart that is not drawn, and says why. The chart and its+ * renderer setting are untouched; nothing else is drawn in its place.+ */+export default function ChartNotice({ notice, onRetry }: { notice: ChartNoticeContent; onRetry?: () => void }) {+ const { t } = useTranslation('translation', { keyPrefix: 'chart_notice' });+ const say = (key: keyof typeof english, values?: Record<string, string | number>) => t(key, { defaultValue: english[key], ...values });+ const renderer = notice.state === 'levels' ? rendererNames[notice.renderer] : '';+ const title = notice.state === 'levels' ? say('levels_title', { renderer }) : say(`${notice.state}_title`);+ const reasons =+ notice.state === 'levels'+ ? notice.shelves.map((held) => say('levels_reason', { shelf: say(`shelf_${held.shelf}`), count: held.fields.length, fields: held.fields.join(', '), renderer }))+ : 'reason' in notice+ ? [notice.reason]+ : [];+ const detail = notice.state === 'loading' ? '' : say(`${notice.state}_desc`);+ return (+ <div role={notice.state === 'loading' ? 'status' : 'alert'} data-testid="chart-notice" data-state={notice.state} className="flex w-full items-start p-6">+ <div className="max-w-xl space-y-2 text-sm">+ <p className="font-medium text-foreground">{title}</p>+ {reasons.map((reason) => (+ <p key={reason} className="text-foreground" data-testid="chart-notice-reason">+ {reason}+ </p>+ ))}+ {detail && <p className="text-muted-foreground">{detail}</p>}+ {notice.state === 'failed' && onRetry && (+ <Button size="sm" variant="outline" onClick={onRetry} data-testid="chart-notice-retry">+ {say('retry')}+ </Button>+ )}+ </div>+ </div>+ );+}diff --git a/packages/graphic-walker/src/renderer/index.tsx b/packages/graphic-walker/src/renderer/index.tsxindex 1b8fb9b7..dfcb962c 100644--- a/packages/graphic-walker/src/renderer/index.tsx+++ b/packages/graphic-walker/src/renderer/index.tsx@@ -1,5 +1,6 @@+import './native';import { observer } from 'mobx-react-lite';-import React, { useState, useEffect, forwardRef, useRef, useCallback, useMemo } from 'react';+import React, { useState, useEffect, forwardRef, useRef, useCallback, useMemo, useContext, useImperativeHandle } from 'react';import {DraggableFieldState,IDarkMode,@@ -27,10 +28,19 @@ import { COUNT_FIELD_ID } from '../constants';import { GWGlobalConfig } from '../vis/theme';import { GLOBAL_CONFIG } from '../config';import { Item } from 'vega';+import { Resizable } from 're-resizable';import { viewEncodingKeys } from '@/models/visSpec';import LoadingLayer from '@/components/loadingLayer';import { getTimeFormat } from '@/lib/inferMeta';import { unexceptedUTCParsedPatternFormats } from '@/lib/op/offset';+import { useNativeRegistry, type NativeRendererColors, type NativeRendererHandle } from './nativeRegistry';+import { routeChart, type ChartRoute } from './route';+import ChartNotice from './chartNotice';+import { getColor, getTheme } from '../utils/useTheme';+import { installNativeExport } from './nativeHostExport';+import { useAppRootContext } from '@/components/appRoot';+import type { IRenderStatus } from '../interfaces';+import { themeContext } from '@/store/theme';interface RendererProps {vizThemeConfig: IThemeKey | GWGlobalConfig;@@ -54,8 +64,6 @@ const Renderer = forwardRef<IReactVegaHandler, RendererProps>(function (props, rconfig: visualConfig,layout,currentVis: chart,- visIndex,- visLength,sort,limit,} = vizStore;@@ -137,12 +145,6 @@ const Renderer = forwardRef<IReactVegaHandler, RendererProps>(function (props, r}}, [waiting, data, vizStore]);- useChartIndexControl({- count: visLength,- index: visIndex,- onChange: (idx) => vizStore.selectVisualization(idx),- });-const handleGeomClick = useCallback((values: any, e: MouseEvent & { item: Item }) => {e.stopPropagation();@@ -247,4 +249,229 @@ const Renderer = forwardRef<IReactVegaHandler, RendererProps>(function (props, r);});-export default observer(Renderer);+const ObservedRenderer = observer(Renderer);++// The same default name the Vega renderer gives its downloads.+const defaultExportName = () => `gw chart ${Date.now() % 1_000_000}`.padStart(6, '0');+function saveDataURL(url: string, filename: string) {+ const anchor = document.createElement('a');+ anchor.download = filename;+ anchor.href = url;+ anchor.click();+}++/**+ * Draws the current chart with the component that its kind and its renderer setting call for; see+ * `routeChart`. The worksheet renderer plans its own queries from the chart, so the query and Vega+ * pipeline above is not mounted for it. No renderer stands in for another: a chart that its renderer+ * cannot draw, or that failed while it was drawn, leaves a notice in the chart area and stays as saved.+ */+const RendererSwitch = forwardRef<IReactVegaHandler, RendererProps>(function (props, ref) {+ const vizStore = useVizStore();+ const registry = useNativeRegistry();+ const chart = vizStore.currentVis;+ const { i18n } = useTranslation();+ // The host's chart count, chart index and openChart. They are registered here, above every renderer,+ // so they stay in place whichever one draws and while one is swapped for the other.+ useChartIndexControl({+ count: vizStore.visLength,+ index: vizStore.visIndex,+ onChange: (idx) => vizStore.selectVisualization(idx),+ });+ // The same resolution the Vega path does: theme preset, then the chart's primary color and palette on top.+ const mediaTheme = useContext(themeContext);+ const { primaryColor, colorPalette, background } = chart.layout;+ const colors = useMemo<NativeRendererColors>(() => {+ // The theme is a Vega config. What the native renderer can use of it is read out here, so that it+ // does not need to know that format. A setting that is not a plain color or number is left out.+ const config: any = getTheme({ vizThemeConfig: props.vizThemeConfig, mediaTheme, primaryColor, colorPalette });+ const resolved = getColor(config);+ const plain = (value: unknown) => (typeof value === 'string' && value !== 'transparent' ? value : undefined);+ const amount = (value: unknown) => (typeof value === 'number' && Number.isFinite(value) ? value : undefined);+ const dash = config.axis?.gridDash;+ return {+ dark: mediaTheme === 'dark',+ primary: resolved.primaryColor,+ category: resolved.nominalPalette,+ ramp: resolved.quantitativePalette,+ diverging: resolved.divergingPalette,+ heatmap: resolved.heatmapPalette,+ background: background || undefined,+ text: plain(config.header?.labelColor) ?? plain(config.legend?.labelColor) ?? plain(config.text?.color),+ muted: plain(config.axis?.labelColor),+ line: plain(config.view?.stroke),+ grid: plain(config.axis?.gridColor),+ style: {+ font: plain(config.font),+ gridDash: Array.isArray(dash) && dash.length === 2 && dash.every((n: unknown) => typeof n === 'number') ? [dash[0], dash[1]] : undefined,+ lineWidth: amount(config.line?.strokeWidth),+ pointStrokeWidth: amount(config.point?.strokeWidth),+ pointFilled: config.point?.filled === true ? true : undefined,+ barRadius: amount(config.bar?.cornerRadiusEnd),+ },+ };+ }, [props.vizThemeConfig, mediaTheme, primaryColor, colorPalette, background]);+ // A chart that failed while it was queried or drawn shows the error until someone tries again, or until+ // its fields, filters, mark type, aggregation or data source change. Size and color changes keep the error.+ const { encodings, config } = chart;+ const shape = useMemo(() => JSON.stringify([encodings, config]), [encodings, config]);+ const [failed, setFailed] = useState<{ shape: string; reason: string }>();+ const onError = useCallback((reason: string) => setFailed({ shape, reason }), [shape]);+ const retry = useCallback(() => setFailed(undefined), []);+ useEffect(() => setFailed(undefined), [props.computationFunction]);+ const planned = useMemo(() => routeChart(chart, registry), [chart, registry]);+ const route: ChartRoute = planned.to === 'native' && failed?.shape === shape ? { to: 'notice', notice: { state: 'failed', reason: failed.reason } } : planned;++ // Who answers the export buttons and the host: the worksheet renderer, the editor's own renderers,+ // or nobody while a notice or a blank area stands where the chart would be.+ const drawn: 'native' | 'classic' | 'nothing' = route.to === 'native' ? 'native' : route.to === 'classic' || route.to === 'dedicated' ? 'classic' : 'nothing';+ const nativeHandle = useRef<NativeRendererHandle>(null);+ const innerHandle = useRef<IReactVegaHandler>(null);+ const drawing = useRef(drawn);+ drawing.current = drawn;+ useImperativeHandle(ref, () => {+ // An export that cannot be made, such as one asked for while the chart is loading, saves nothing.+ const guarded = async (make: () => Promise<string>, save?: (data: string) => void): Promise<string[]> => {+ try {+ const data = await make();+ save?.(data);+ return [data];+ } catch (error) {+ console.error('[worksheet renderer] export failed:', error);+ return [];+ }+ };+ const fromNative: IReactVegaHandler = {+ getSVGData: () => guarded(() => nativeHandle.current!.exportSVG()),+ getCanvasData: () => guarded(() => nativeHandle.current!.exportPNG()),+ downloadSVG: (filename = defaultExportName()) => guarded(() => nativeHandle.current!.exportSVG(), (svg) => download(svg, `${filename}.svg`, 'image/svg+xml')),+ downloadPNG: (filename = defaultExportName()) => guarded(() => nativeHandle.current!.exportPNG(), (url) => saveDataURL(url, `${filename}.png`)),+ };+ // A chart that is not drawn has nothing to export. In particular it does not hand out what an earlier chart left behind.+ const pick = <K extends keyof IReactVegaHandler>(key: K): IReactVegaHandler[K] =>+ ((...args: [string?]) =>+ drawing.current === 'native'+ ? fromNative[key](...args)+ : drawing.current === 'classic'+ ? innerHandle.current?.[key](...args) ?? Promise.resolve([])+ : Promise.resolve([])) as IReactVegaHandler[K];+ return { getSVGData: pick('getSVGData'), getCanvasData: pick('getCanvasData'), downloadSVG: pick('downloadSVG'), downloadPNG: pick('downloadPNG') };+ }, []);+ // The CSV button reads a slot the drawing renderer fills. The editor's own renderers fill it when they+ // mount. Otherwise it is filled here, also where nothing is drawn, so that it never holds an earlier chart's data.+ const { csvRef } = props;+ const chartName = chart.name;+ useEffect(() => {+ if (drawn === 'classic' || !csvRef) return;+ csvRef.current = {+ download() {+ if (drawing.current !== 'native') return console.warn('[chart] There is no data to export: the chart is not drawn.');+ try {+ download(nativeHandle.current!.exportCSV(), `${chartName}.csv`, 'text/plain');+ } catch (error) {+ console.error('[worksheet renderer] export failed:', error);+ }+ },+ };+ }, [drawn, csvRef, chartName]);++ // Where the chart stands, for the loading layer here and for the host's render status.+ const appRoot = useAppRootContext();+ const [status, setStatus] = useState<IRenderStatus>('idle');+ const onStatusChange = useCallback(+ (next: IRenderStatus) => {+ setStatus(next);+ appRoot.current?.updateRenderStatus(next);+ },+ [appRoot]+ );+ const container = useRef<HTMLDivElement>(null);+ const hosted = drawn !== 'classic';+ useEffect(() => {+ if (!hosted) return;+ // The host's exportChart is answered from here also while nothing is drawn. It then reports a chart without images.+ const ctx = appRoot.current;+ return ctx ? installNativeExport(ctx, { handle: nativeHandle, container, title: chartName ?? '' }) : undefined;+ }, [hosted, appRoot, chartName]);+ useEffect(() => {+ if (!hosted) return;+ // The editor's own renderers start from a clean state when they take over. Between two charts that are+ // both answered from here the status is left alone: the sheet goes on reporting it, and a sheet that+ // was loading one chart and now loads the next has nothing new to say.+ return () => {+ setStatus('idle');+ appRoot.current?.updateRenderStatus('idle');+ };+ }, [hosted, appRoot]);+ // A chart that is not drawn says so to the host: an export waits for a renderer that is still loading,+ // and gets no image from a chart that has no renderer, cannot be drawn or failed.+ const standing: IRenderStatus | undefined = route.to === 'notice' ? (route.notice.state === 'loading' ? 'computing' : 'error') : route.to === 'blank' ? 'idle' : undefined;+ useEffect(() => {+ if (standing) onStatusChange(standing);+ }, [standing, onStatusChange, chartName]);+ // A click on a mark opens the editor's menu there, with the mark's dimension values as what the menu's+ // actions work on. The click must not reach the chart area, whose own handler closes the menu.+ const onMarkClick = useCallback(+ (mark: Record<string, unknown>, event: MouseEvent) => {+ if (GLOBAL_CONFIG.EMBEDED_MENU_LIST.length === 0) return;+ event.stopPropagation();+ runInAction(() => {+ vizStore.showEmbededMenu([event.clientX, event.clientY]);+ vizStore.setFilters(Object.fromEntries(Object.entries(mark).map(([fid, value]) => [fid, [value]])));+ vizStore.updateSelectedMarkObject(mark as Record<string, string | number | undefined>);+ });+ },+ [vizStore]+ );++ if (route.to === 'classic' || route.to === 'dedicated') return <ObservedRenderer {...props} ref={innerHandle} />;+ if (route.to !== 'native') {+ return (+ <div className="w-full h-full relative overflow-auto" ref={container} data-testid="chart-not-drawn">+ {status === 'computing' && <LoadingLayer />}+ {route.to === 'notice' && <ChartNotice notice={route.notice} onRetry={retry} />}+ </div>+ );+ }+ const Native = registry.renderer!.component;+ // Auto: value axes take the room the chart area has, member steps keep their size, and what does not fit scrolls.+ // Fixed: it fills a box of the chosen size, which the viewer can drag to resize.+ // Full: it fills the chart area.+ const size = props.overrideSize ?? chart.layout.size;+ const sheet = (+ <Native+ chart={chart}+ fields={vizStore.allFields}+ computation={props.computationFunction}+ colors={colors}+ locale={i18n.language}+ fill={size.mode !== 'auto'}+ onError={onError}+ handle={nativeHandle}+ onStatusChange={onStatusChange}+ onMarkClick={onMarkClick}+ />+ );+ return (+ <div className={size.mode === 'fixed' ? 'w-full h-full relative overflow-auto' : 'w-full h-full relative'} ref={container}>+ {status === 'computing' && <LoadingLayer />}+ {size.mode === 'fixed' ? (+ <Resizable+ className="border-primary border-2 max-h-screen max-w-[100vw]"+ size={{ width: `${size.width}px`, height: `${size.height}px` }}+ minWidth={120}+ minHeight={120}+ onResizeStop={(_event, _direction, _element, delta) => {+ vizStore.setVisualLayout('size', { mode: 'fixed', width: size.width + delta.width, height: size.height + delta.height });+ }}+ >+ {sheet}+ </Resizable>+ ) : (+ sheet+ )}+ </div>+ );+});++export default observer(RendererSwitch);diff --git a/packages/graphic-walker/src/renderer/native/adapter.test.ts b/packages/graphic-walker/src/renderer/native/adapter.test.tsnew file mode 100644index 00000000..3c209690--- /dev/null+++ b/packages/graphic-walker/src/renderer/native/adapter.test.ts@@ -0,0 +1,234 @@+import { chartToWorksheet } from './adapter';+import { MEA_KEY_ID } from '../../constants';+import type { IChart, IViewField } from '../../interfaces';+import { emptyEncodings, emptyVisualConfig, emptyVisualLayout } from '../../utils/save';++const dim = (fid: string, semanticType: IViewField['semanticType'] = 'nominal', extra: Partial<IViewField> = {}): IViewField => ({ fid, name: fid, semanticType, analyticType: 'dimension', ...extra });+const mea = (fid: string, aggName = 'sum'): IViewField => ({ fid, name: fid, semanticType: 'quantitative', analyticType: 'measure', aggName });+function chart(encodings: Partial<IChart['encodings']>, config: Partial<IChart['config']> = {}, layout: Partial<IChart['layout']> = {}): IChart {+ return {+ visId: 'v', name: 'test',+ encodings: { ...emptyEncodings, ...encodings },+ config: { ...emptyVisualConfig, ...config },+ layout: { ...emptyVisualLayout, renderer: 'native', ...layout },+ };+}+const ids = (expr: any): string[] => (expr.kind === 'field' ? [expr.instanceId] : (expr.items ?? []).flatMap(ids));++describe('chartToWorksheet', () => {+ test('dimensions nest in shelf order and each measure gets its own value axis', () => {+ const { spec, error, viewDimensions, viewMeasures } = chartToWorksheet(chart({+ rows: [dim('Region'), dim('Category'), dim('Sub-Category')],+ columns: [dim('Year', 'ordinal'), mea('Sales'), mea('Profit', 'mean')],+ }));+ expect(error).toBeUndefined();+ expect(ids(spec!.rows).map((id) => spec!.instances[id].field)).toEqual(['Region', 'Category', 'Sub-Category']);+ expect(spec!.rows).toMatchObject({ kind: 'nest' });+ expect((spec!.columns as any).items[1]).toMatchObject({ kind: 'concat' });+ expect(ids(spec!.columns).map((id) => spec!.instances[id])).toMatchObject([+ { field: 'Year', display: 'discrete' },+ { field: 'Sales', display: 'continuous', aggregate: 'sum', label: 'sum(Sales)' },+ { field: 'Profit', display: 'continuous', aggregate: 'mean', label: 'mean(Profit)' },+ ]);+ expect(spec!.mark).toBe('bar');+ expect(viewDimensions.map((f) => f.fid)).toEqual(['Region', 'Category', 'Sub-Category', 'Year']);+ expect(viewMeasures.map((f) => f.fid)).toEqual(['Sales', 'Profit']);+ });+ test('the last dimension of a shelf without measures becomes an axis when it is a date or a number', () => {+ const { spec } = chartToWorksheet(chart({ rows: [mea('Sales')], columns: [dim('Region'), dim('Order Date', 'temporal')] }));+ expect(ids(spec!.columns).map((id) => spec!.instances[id])).toMatchObject([+ { field: 'Region', display: 'discrete' },+ { field: 'Order Date', display: 'continuous', scale: 'time' },+ ]);+ // No unit: the axis shows moments, not periods.+ expect(spec!.instances[ids(spec!.columns)[1]].timeUnit).toBeUndefined();+ expect(spec!.mark).toBe('line');+ const numeric = chartToWorksheet(chart({ rows: [mea('Sales')], columns: [dim('Age', 'quantitative')] })).spec!;+ expect(numeric.instances[ids(numeric.columns)[0]]).toMatchObject({ display: 'continuous', scale: 'linear', zero: false });+ // A date that is not last on its shelf, or shares the shelf with a measure, stays a header.+ const header = chartToWorksheet(chart({ rows: [dim('Order Date', 'temporal'), mea('Sales')], columns: [dim('Region')] })).spec!;+ expect(header.instances[ids(header.rows)[0]]).toMatchObject({ display: 'discrete', scale: 'time' });+ });+ test('automatic mark follows the shelves', () => {+ const mark = (encodings: Partial<IChart['encodings']>) => chartToWorksheet(chart(encodings)).spec!.mark;+ expect(mark({ rows: [mea('Sales')], columns: [mea('Profit')] })).toBe('point');+ expect(mark({ rows: [dim('Region')], columns: [mea('Sales')] })).toBe('bar');+ expect(mark({ rows: [dim('Region')], columns: [dim('Segment')], text: [mea('Sales')] })).toBe('text');+ expect(mark({ rows: [dim('Region')], columns: [dim('Segment')], color: [mea('Sales')] })).toBe('rect');+ expect(chartToWorksheet(chart({ rows: [dim('Region')], columns: [mea('Sales')] }, { geoms: ['area'] })).spec!.mark).toBe('area');+ // With every record drawn, bars would pile up; the editor's own renderer draws ticks there too.+ expect(chartToWorksheet(chart({ rows: [dim('Region')], columns: [mea('Sales')] }, { defaultAggregated: false })).spec!.mark).toBe('tick');+ });+ test('point, circle and tick stay three different marks', () => {+ const mark = (geom: string) => chartToWorksheet(chart({ rows: [dim('Region')], columns: [mea('Sales')] }, { geoms: [geom] })).spec!.mark;+ expect(['point', 'circle', 'tick'].map(mark)).toEqual(['point', 'circle', 'tick']);+ });+ test('a pie keeps the dimensions on rows and columns as headers and takes its measure from the angle shelf', () => {+ const { spec, notes, viewMeasures } = chartToWorksheet(chart({+ rows: [dim('Region'), dim('Order Date', 'temporal'), mea('Sales')], columns: [dim('Category')],+ theta: [mea('Profit', 'mean')], color: [dim('Segment')], radius: [mea('Quantity')],+ }, { geoms: ['arc'] }));+ expect(spec!.mark).toBe('arc');+ expect(ids(spec!.rows).map((id) => spec!.instances[id])).toMatchObject([{ field: 'Region', display: 'discrete' }, { field: 'Order Date', display: 'discrete' }]);+ expect(ids(spec!.columns).map((id) => spec!.instances[id].field)).toEqual(['Category']);+ expect(spec!.instances[spec!.angle!]).toMatchObject({ field: 'Profit', aggregate: 'mean' });+ expect(viewMeasures.map((f) => f.fid)).toEqual(['Profit']);+ expect(notes).toEqual(['Measures on the row shelf are not part of a pie. The angle shelf sizes the slices.', 'Not drawn yet: radius.']);+ expect(chartToWorksheet(chart({ color: [dim('Segment')] }, { geoms: ['arc'] })).spec!.angle).toBeUndefined();+ expect(chartToWorksheet(chart({ theta: [dim('Segment')] }, { geoms: ['arc'] })).error).toMatch(/Angle is a dimension/);+ });+ test('a box plot keeps every dimension as a header and does not start its axis from zero', () => {+ const { spec, notes } = chartToWorksheet(chart({+ columns: [dim('Region'), dim('Category'), dim('Age', 'quantitative')], rows: [mea('Sales')], color: [mea('Profit')], details: [dim('Customer')],+ }, { geoms: ['boxplot'], defaultAggregated: false }));+ expect(spec!.mark).toBe('boxplot');+ expect(ids(spec!.columns).map((id) => spec!.instances[id].display)).toEqual(['discrete', 'discrete', 'discrete']);+ expect(spec!.instances[ids(spec!.rows)[0]]).toMatchObject({ field: 'Sales', display: 'continuous', zero: false });+ expect(spec!.instances[ids(spec!.rows)[0]].aggregate).toBeUndefined();+ expect(spec!.color).toBeUndefined();+ expect(spec!.detail!.map((id) => spec!.instances[id].field)).toEqual(['Customer']);+ expect(notes).toEqual(['Profit on Color is ignored: a box plot takes a dimension there.']);+ });+ test('color takes a dimension as categories and a measure as a continuous scale', () => {+ const byDimension = chartToWorksheet(chart({ rows: [dim('Region')], columns: [mea('Sales')], color: [dim('Segment')], details: [dim('Ship Mode')] })).spec!;+ expect(byDimension.instances[byDimension.color!]).toMatchObject({ field: 'Segment', display: 'discrete' });+ expect(byDimension.detail!.map((id) => byDimension.instances[id].field)).toEqual(['Ship Mode']);+ const byMeasure = chartToWorksheet(chart({ rows: [dim('Region')], columns: [mea('Sales')], color: [mea('Profit', 'mean')] })).spec!;+ expect(byMeasure.instances[byMeasure.color!]).toMatchObject({ field: 'Profit', display: 'continuous', aggregate: 'mean' });+ });+ test('without aggregation measures are plain continuous fields', () => {+ const { spec } = chartToWorksheet(chart({ rows: [mea('Sales')], columns: [mea('Profit')] }, { defaultAggregated: false }));+ expect(Object.values(spec!.instances).every((f) => f.display === 'continuous' && !f.aggregate)).toBe(true);+ });+ test('a date drilled to a unit is labelled by its period in the display time zone', () => {+ const year = dim('Order Year', 'temporal', { computed: true, timeUnit: 'year' });+ const header = chartToWorksheet(chart({ rows: [year, mea('Sales')], columns: [dim('Region')] }, { timezoneDisplayOffset: 480 })).spec!;+ expect(header.instances[ids(header.rows)[0]]).toMatchObject({ display: 'discrete', scale: 'time', timeUnit: 'year', timeOffset: -480 * 60000 });+ const axis = chartToWorksheet(chart({ rows: [mea('Sales')], columns: [year] }, { timezoneDisplayOffset: 0 })).spec!;+ expect(axis.instances[ids(axis.columns)[0]]).toMatchObject({ display: 'continuous', scale: 'time', timeOffset: -0 });+ expect(axis.mark).toBe('line');+ });+ test('a sorted dimension is ordered by the measure across from it, and the limit follows that order', () => {+ const sorted = (extra: Partial<IViewField> = {}) => dim('Sub-Category', 'nominal', { sort: 'descending', ...extra });+ const { spec, notes } = chartToWorksheet(chart({ rows: [dim('Category'), sorted()], columns: [dim('Year', 'ordinal'), mea('Sales'), mea('Profit', 'mean')] }, { limit: 10 }));+ const sub = ids(spec!.rows)[1], sales = ids(spec!.columns)[1];+ expect(spec!.instances[sales]).toMatchObject({ field: 'Sales', aggregate: 'sum' });+ // The first of several measures decides, as the leftmost does in Tableau.+ expect(spec!.order).toEqual({ [sub]: { by: sales, direction: 'descending' } });+ expect(spec!.limit).toEqual({ rows: 10, by: sales, direction: 'descending' });+ expect(notes).toEqual([]);+ // Measure on the same shelf as the dimension: the dimension across from it is the one that carries the sort.+ const across = chartToWorksheet(chart({ rows: [dim('Region'), mea('Sales')], columns: [dim('Year', 'ordinal', { sort: 'ascending' })] })).spec!;+ expect(across.order).toEqual({ [ids(across.columns)[0]]: { by: ids(across.rows)[1], direction: 'ascending' } });+ expect(across.limit).toBeUndefined();+ // A date axis has no members to reorder.+ expect(chartToWorksheet(chart({ rows: [mea('Sales')], columns: [dim('Order Date', 'temporal', { sort: 'descending' })] })).spec!.order).toEqual({});+ expect(chartToWorksheet(chart({ rows: [sorted()], columns: [dim('Region')] })).notes).toEqual(['There is no measure to sort by; members are in value order.']);+ // A limit without a sort keeps the first records as they come.+ expect(chartToWorksheet(chart({ rows: [dim('Region')], columns: [mea('Sales')] }, { limit: 5 })).spec!.limit).toEqual({ rows: 5 });+ });+ test('with every record drawn, members are ordered by a total and the limit by the records', () => {+ const raw = chartToWorksheet(chart({ rows: [dim('Region', 'nominal', { sort: 'descending' })], columns: [mea('Sales')] }, { defaultAggregated: false, limit: 100 })).spec!;+ const region = ids(raw.rows)[0], sales = ids(raw.columns)[0];+ expect(raw.instances[sales].aggregate).toBeUndefined();+ expect(raw.instances.order).toMatchObject({ field: 'Sales', aggregate: 'sum' });+ expect(raw.order).toEqual({ [region]: { by: 'order', direction: 'descending' } });+ expect(raw.limit).toEqual({ rows: 100, by: sales, direction: 'descending' });+ const box = chartToWorksheet(chart({ columns: [dim('Region', 'nominal', { sort: 'ascending' })], rows: [mea('Sales')] }, { defaultAggregated: false, geoms: ['boxplot'] })).spec!;+ expect(box.instances.order).toMatchObject({ field: 'Sales', aggregate: 'median' });+ });+ test('size, opacity, shape and labels map from the shelves the mark type shows', () => {+ const shelves = { rows: [mea('Sales')], columns: [dim('Region')], size: [mea('Profit', 'mean')], opacity: [dim('Segment')], shape: [dim('Ship Mode')], text: [mea('Quantity')] };+ const point = chartToWorksheet(chart(shelves, { geoms: ['point'] }));+ expect(point.spec!.instances[point.spec!.size!]).toMatchObject({ field: 'Profit', display: 'continuous', aggregate: 'mean' });+ expect(point.spec!.instances[point.spec!.opacity!]).toMatchObject({ field: 'Segment', display: 'discrete' });+ expect(point.spec!.instances[point.spec!.shape!]).toMatchObject({ field: 'Ship Mode', display: 'discrete' });+ // The editor hides the Text shelf for points, so a field left on it is not part of the chart.+ expect(point.spec!.text).toBeUndefined();+ expect(point.viewMeasures.map((f) => f.fid)).toEqual(['Sales', 'Profit']);+ expect(point.notes).toEqual([]);+ // Bars show Text and hide Shape.+ const bar = chartToWorksheet(chart(shelves, { geoms: ['bar'] }));+ expect(bar.spec!.instances[bar.spec!.text!]).toMatchObject({ field: 'Quantity', aggregate: 'sum' });+ expect(bar.spec!.shape).toBeUndefined();+ expect(bar.spec!.size).toBeDefined();+ expect(bar.notes).toEqual([]);+ const box = chartToWorksheet(chart({ ...shelves, size: [dim('Segment')], text: [dim('Segment')] }, { geoms: ['boxplot'], defaultAggregated: false }));+ expect([box.spec!.size, box.spec!.opacity, box.spec!.text]).toEqual([undefined, undefined, undefined]);+ expect(box.notes).toEqual(['Labels are not drawn on box plots.', 'Size is not drawn on box plot marks.', 'Opacity is not drawn on box plots.']);+ expect(chartToWorksheet(chart({ ...shelves, shape: [mea('Profit')] }, { geoms: ['circle'] })).notes).toEqual(['Profit on Shape is ignored: only a dimension picks symbols.']);+ expect(chartToWorksheet(chart({ color: [dim('Segment')], theta: [mea('Sales')], radius: [mea('Profit')] }, { geoms: ['arc'] })).notes).toEqual(['Not drawn yet: radius.']);+ });+ test('a stored date is shifted to the display time zone by the kind of value it holds', () => {+ const local = new Date().getTimezoneOffset() * 60000;+ // Display eight hours east of UTC; the field was recorded five hours west.+ const { spec } = chartToWorksheet(chart({ rows: [mea('Sales')], columns: [dim('Order Date', 'temporal', { offset: 300 })] }, { timezoneDisplayOffset: -480 }));+ expect(spec!.instances[ids(spec!.columns)[0]].timeOffset).toEqual({ epoch: 480 * 60000, date: (480 + 300) * 60000, dateTime: (480 + 300) * 60000 - local });+ // With nothing set, a day written as text stays that day.+ const plain = chartToWorksheet(chart({ rows: [dim('Order Date', 'temporal'), mea('Sales')], columns: [dim('Region')] })).spec!;+ expect(plain.instances[ids(plain.rows)[0]].timeOffset).toMatchObject({ date: 0, epoch: -local });+ // A computed date field that is not a drill is left as a plain dimension.+ const computed = chartToWorksheet(chart({ rows: [dim('Derived', 'temporal', { computed: true }), mea('Sales')], columns: [dim('Region')] })).spec!;+ expect(computed.instances[ids(computed.rows)[0]].scale).toBeUndefined();+ });+ test('scale settings map to the axes of a shelf and to the color, size and opacity channels', () => {+ const shelves = { rows: [dim('Region')], columns: [mea('Sales')], color: [mea('Profit')], size: [mea('Quantity')], opacity: [dim('Segment')] };+ const { spec, notes } = chartToWorksheet(chart(shelves, { geoms: ['point'] }, {+ scale: {+ column: { type: 'log', domainMin: 1 }, row: { type: 'pow' }, color: { domainMin: -5, domainMax: 5, type: 'symlog' },+ size: { rangeMin: 4, rangeMax: 80 }, opacity: { rangeMin: 0.3, rangeMax: 0.9, type: 'sqrt' }, theta: { domainMax: 10 },+ },+ resolve: { ...emptyVisualLayout.resolve, color: true, size: true, opacity: true, shape: true },+ }));+ expect(spec!.scales).toEqual({+ columns: { type: 'log', min: 1 },+ color: { type: 'symlog', min: -5, max: 5, independent: true },+ size: { range: [4, 80], independent: true },+ // Opacity is on a dimension: its range applies, a scale type and independence do not.+ opacity: { range: [0.3, 0.9] },+ });+ expect(notes).toEqual([+ 'The opacity scale type and domain apply to a measure, not to a dimension.',+ 'An independent opacity scale applies to a measure; each member of a dimension keeps its opacity in every pane.',+ 'The theta scale is not applied.',+ ]);+ expect(chartToWorksheet(chart({ rows: [dim('Region')], columns: [mea('Sales')] })).spec!.scales).toBeUndefined();+ });+ test('layout options carry over', () => {+ const base = { rows: [dim('Region')], columns: [mea('Sales')] };+ expect(chartToWorksheet(chart(base, {}, { stack: 'none' })).spec!.stack).toBe(false);+ expect(chartToWorksheet(chart(base, {}, { stack: 'stack' })).spec!.stack).toBe(true);+ expect(chartToWorksheet(chart(base, {}, { stack: 'zero' })).spec!.stack).toBe(true);+ expect(chartToWorksheet(chart(base, {}, { stack: 'normalize' })).spec!.stack).toBe('normalize');+ expect(chartToWorksheet(chart(base, {}, { stack: 'center' })).spec!.stack).toBe('center');+ // Each direction is set on its own: x is the columns shelf, y the rows shelf.+ const scope = (resolve: Partial<IChart['layout']['resolve']>) => chartToWorksheet(chart(base, {}, { resolve: { ...emptyVisualLayout.resolve, ...resolve } })).spec!.scaleScope;+ expect(scope({})).toEqual({ columns: 'shared', rows: 'shared' });+ expect(scope({ x: true })).toEqual({ columns: 'independent', rows: 'shared' });+ expect(scope({ y: true })).toEqual({ columns: 'shared', rows: 'independent' });+ expect(scope({ x: true, y: true })).toEqual({ columns: 'independent', rows: 'independent' });+ const noZero = chartToWorksheet(chart(base, {}, { zeroScale: false })).spec!;+ expect(noZero.instances[ids(noZero.columns)[0]].zero).toBe(false);+ });+ test('what cannot be drawn is reported, not dropped silently', () => {+ expect(chartToWorksheet(chart({ rows: [dim(MEA_KEY_ID)], columns: [mea('Sales')] })).error).toMatch(/Measure names/);+ expect(chartToWorksheet(chart({ rows: [dim('Region')], columns: [mea('Sales')] }, { geoms: ['table'] })).error).toMatch(/"table"/);+ expect(chartToWorksheet(chart({ rows: [dim('Region')], columns: [mea('Sales', 'ntile')] })).error).toMatch(/"ntile"/);+ // An aggregate expression needs its expression; a field that only carries the name of one is not drawn.+ expect(chartToWorksheet(chart({ rows: [dim('Region')], columns: [mea('Sales', 'expr')] })).error).toMatch(/Sales is an aggregate expression, but the dataset has no expression for it/);+ expect(chartToWorksheet(chart({}, { coordSystem: 'geographic' })).error).toMatch(/Maps/);+ expect(chartToWorksheet(chart({}))).toMatchObject({ error: expect.stringMatching(/nothing on rows or columns/), empty: true });+ expect(chartToWorksheet(chart({ rows: [dim(MEA_KEY_ID)], columns: [mea('Sales')] })).empty).toBeUndefined();+ expect(chartToWorksheet(chart({ color: [dim('Segment')] })).error).toMatch(/nothing on rows or columns/);+ const { spec, notes } = chartToWorksheet(chart({ rows: [dim('Region')], columns: [mea('Sales')], size: [mea('Profit')], details: [mea('Quantity')] }, { geoms: ['area'] }));+ expect(spec).toBeDefined();+ expect(notes).toEqual(['Quantity on Details is ignored: only dimensions split marks.', 'Size is not drawn on area marks.']);+ const settings = chartToWorksheet(chart({ rows: [dim('Region')], columns: [mea('Sales')] }, { limit: 10, geoms: ['trail'] },+ { format: { numberFormat: '.2f' }, scale: { opacity: { rangeMax: 1 } }, interactiveScale: true, size: { mode: 'fixed', width: 300, height: 200 }, useSvg: true, resolve: { color: true } }));+ expect(settings.notes).toEqual([+ 'Trail is drawn as a line of one width.', 'The sheet is always drawn on a canvas.',+ ]);+ // A chart with default settings drops nothing.+ expect(chartToWorksheet(chart({ rows: [dim('Region')], columns: [mea('Sales')] })).notes).toEqual([]);+ });+});diff --git a/packages/graphic-walker/src/renderer/native/adapter.ts b/packages/graphic-walker/src/renderer/native/adapter.tsnew file mode 100644index 00000000..0badc07e--- /dev/null+++ b/packages/graphic-walker/src/renderer/native/adapter.ts@@ -0,0 +1,273 @@+import type { Aggregate, AxisExpr, FieldInstance, ScaleOptions, WorksheetSpec } from '@kanaries/worksheet-renderer';+import { MEA_KEY_ID, MEA_VAL_ID } from '../../constants';+import type { IChart, IViewField } from '../../interfaces';+import { viewEncodingKeys } from '../../models/visSpec';++export interface AdaptedChart {+ /** Absent when the worksheet renderer cannot draw the chart; `error` says why. */+ spec?: WorksheetSpec;+ error?: string;+ /** The chart has nothing on its shelves to draw yet, which is no fault of the chart. */+ empty?: boolean;+ /** Parts of the chart that were left out or approximated. */+ notes: string[];+ /** The fields the worksheet queries, split the way the editor's workflow builder takes them. */+ viewDimensions: IViewField[];+ viewMeasures: IViewField[];+}++const aggregates = new Set<string>(['sum', 'mean', 'median', 'min', 'max', 'count', 'distinctCount', 'variance', 'stdev']);+const shelves = ['rows', 'columns', 'color', 'details', 'text', 'theta', 'radius', 'size', 'opacity', 'shape'] as const;+const marks: Record<string, WorksheetSpec['mark'] | undefined> = {+ bar: 'bar', line: 'line', area: 'area', trail: 'line', point: 'point', circle: 'circle', tick: 'tick', rect: 'rect', text: 'text',+ arc: 'arc', boxplot: 'boxplot',+};+const isMeasure = (f: IViewField) => f.analyticType === 'measure';+const isNumber = (value: unknown): value is number => typeof value === 'number' && Number.isFinite(value);++/**+ * Maps a stored chart to the worksheet renderer's input. The chart stays the source of+ * truth; nothing here is saved.+ *+ * Shelf rule, per axis, after the editor has put dimensions before measures:+ * - with measures, every dimension is a header level and each measure is a value axis;+ * - without measures, the last dimension is the position inside a pane: one slot per+ * member when nominal or ordinal, a linear axis when quantitative, a time axis when temporal.+ *+ * Two mark types read the shelves differently. A pie has no axes: every dimension on rows and+ * columns is a header, one pie is drawn per cell, and the measure comes from the angle shelf.+ * A box plot has one axis, its measure, so its dimensions are all headers too.+ */+export function chartToWorksheet(chart: IChart): AdaptedChart {+ const { config, layout } = chart;+ const aggregated = config.defaultAggregated;+ const notes: string[] = [];+ // A measure made from other aggregates, such as sum(Sales) / sum(Cost), has no value per source row.+ // Without aggregation the editor greys its pill out and no renderer draws it; it is left out here too.+ const idle = aggregated ? [] : shelves.flatMap((shelf) => chart.encodings[shelf].filter((f) => f.aggName === 'expr'));+ if (idle.length) notes.push(`${[...new Set(idle.map((f) => f.name))].join(', ')}: an aggregate expression is not drawn while aggregation is off.`);+ const encodings = { ...chart.encodings, ...Object.fromEntries(shelves.map((shelf) => [shelf, chart.encodings[shelf].filter((f) => !idle.includes(f))])) } as IChart['encodings'];+ // The dataset's own entry for a field is what the editor's workflow builder reads an expression from.+ const defined = new Map([...chart.encodings.dimensions, ...chart.encodings.measures].map((f) => [f.fid, f]));+ const used: IViewField[] = [];+ const instances: Record<string, FieldInstance> = {};+ const result = (extra: Partial<AdaptedChart>): AdaptedChart => ({+ notes,+ viewDimensions: unique(used.filter((f) => !isMeasure(f))),+ viewMeasures: unique(used.filter(isMeasure)),+ ...extra,+ });+ if (config.coordSystem === 'geographic') return result({ error: 'Maps are not drawn by the worksheet renderer.' });+ const geom = config.geoms[0] ?? 'auto';+ const headersOnly = geom === 'arc' || geom === 'boxplot';+ const all = [...encodings.rows, ...encodings.columns, ...encodings.color, ...encodings.details, ...encodings.text, ...(geom === 'arc' ? encodings.theta : [])];+ if (all.some((f) => f.fid === MEA_KEY_ID || f.fid === MEA_VAL_ID)) {+ return result({ error: 'Measure names and Measure values are not supported yet. Put the measures on the shelf one by one.' });+ }+ // A box shows where the records lie, so its axis does not reach back to zero.+ const zero = geom !== 'boxplot' && layout.zeroScale !== false;++ function instance(id: string, f: IViewField, position: 'header' | 'terminal' | 'encoding'): FieldInstance | string {+ used.push(f);+ if (isMeasure(f)) {+ if (!aggregated) return (instances[id] = { id, field: f.fid, label: f.name, display: 'continuous', zero });+ const aggregate = f.aggName ?? 'sum';+ if (aggregate === 'expr') {+ // The expression stays with the editor: its workflow builder resolves the fields it names and the+ // data source works it out per group. The sheet asks for it by field id at each grain it draws.+ if ((defined.get(f.fid) ?? f).expression?.op !== 'expr') return `${f.name} is an aggregate expression, but the dataset has no expression for it.`;+ return (instances[id] = { id, field: f.fid, label: f.name, display: 'continuous', aggregate: 'expr', zero });+ }+ if (!aggregates.has(aggregate)) return `${f.name} uses the aggregation "${aggregate}", which is not supported yet.`;+ return (instances[id] = { id, field: f.fid, label: `${aggregate}(${f.name})`, display: 'continuous', aggregate: aggregate as Aggregate, zero });+ }+ // The editor types an expression by its first operand, and one over fields it cannot resolve comes out as+ // a dimension. An aggregate has one value per group and no members to group by.+ if (f.aggName === 'expr') return `${f.name} is an aggregate expression, but it is set as a dimension. An aggregate has a value per group, so it is drawn as a measure only.`;+ // A date drilled to a unit, such as the year of a date, holds the start of each period as a+ // timestamp. It is shifted to the display time zone, as the editor's other renderers do, and+ // its members are named after the period.+ const drilled = f.semanticType === 'temporal' && f.computed && f.timeUnit;+ // A date field as stored. Its values are shifted to the display time zone by the same rule the+ // editor's other renderers use: a timestamp by the display offset alone; text also by the offset+ // the field was recorded in, less the machine's own zone where the text is read in that zone.+ const stored = f.semanticType === 'temporal' && !f.computed;+ const local = new Date().getTimezoneOffset() * 60000;+ const display = (config.timezoneDisplayOffset ?? new Date().getTimezoneOffset()) * -60000;+ const recorded = f.offset === undefined ? local : f.offset * 60000;+ const time = drilled ? { scale: 'time' as const, timeUnit: f.timeUnit, timeOffset: display }+ : stored ? { scale: 'time' as const, timeOffset: { epoch: display, date: display + recorded, dateTime: display + recorded - local } } : undefined;+ // A dimension becomes an axis only where it ends a shelf that has no measure.+ if (position === 'terminal' && !headersOnly && (f.semanticType === 'quantitative' || time)) {+ return (instances[id] = { id, field: f.fid, label: f.name, display: 'continuous', scale: time ? 'time' : 'linear', zero: false, ...(time ? { timeOffset: time.timeOffset } : {}) });+ }+ // As a header a stored date is written as a date, a drilled one as its period.+ return (instances[id] = { id, field: f.fid, label: f.name, display: 'discrete', ...time });+ }++ interface Shelf { expr: AxisExpr; measures: number; terminal?: FieldInstance; values: FieldInstance[]; sorted: { id: string; direction: 'ascending' | 'descending' }[] }+ function shelf(name: string, fields: IViewField[]): Shelf | string {+ const dimensions = fields.filter((f) => !isMeasure(f));+ const measures = geom === 'arc' ? [] : fields.filter(isMeasure);+ if (geom === 'arc' && fields.some(isMeasure)) notes.push(`Measures on the ${name} shelf are not part of a pie. The angle shelf sizes the slices.`);+ const items: AxisExpr[] = [];+ let terminal: FieldInstance | undefined;+ const sorted: Shelf['sorted'] = [];+ for (const [index, f] of dimensions.entries()) {+ const last = index === dimensions.length - 1 && measures.length === 0;+ const made = instance(`${name}${index}`, f, last ? 'terminal' : 'header');+ if (typeof made === 'string') return made;+ if (last) terminal = made;+ // An axis has no members to reorder; only headers do.+ if ((f.sort === 'ascending' || f.sort === 'descending') && made.display === 'discrete') sorted.push({ id: made.id, direction: f.sort });+ items.push({ kind: 'field', instanceId: made.id });+ }+ const values: FieldInstance[] = [];+ for (const [index, f] of measures.entries()) {+ const made = instance(`${name}m${index}`, f, 'terminal');+ if (typeof made === 'string') return made;+ values.push(made);+ }+ const axes: AxisExpr[] = values.map((made) => ({ kind: 'field', instanceId: made.id }));+ if (axes.length) items.push(axes.length === 1 ? axes[0] : { kind: 'concat', items: axes });+ return { expr: items.length ? { kind: 'nest', items } : { kind: 'empty' }, measures: measures.length, terminal, values, sorted };+ }++ const rows = shelf('row', encodings.rows);+ if (typeof rows === 'string') return result({ error: rows });+ const columns = shelf('column', encodings.columns);+ if (typeof columns === 'string') return result({ error: columns });++ let color: string | undefined;+ if (geom === 'boxplot' && encodings.color[0] && isMeasure(encodings.color[0])) {+ notes.push(`${encodings.color[0].name} on Color is ignored: a box plot takes a dimension there.`);+ } else if (encodings.color[0]) {+ const made = instance('color', encodings.color[0], 'encoding');+ if (typeof made === 'string') return result({ error: made });+ color = made.id;+ }+ const detail: string[] = [];+ for (const [index, f] of encodings.details.entries()) {+ if (isMeasure(f)) { notes.push(`${f.name} on Details is ignored: only dimensions split marks.`); continue; }+ const made = instance(`detail${index}`, f, 'encoding');+ if (typeof made !== 'string') detail.push(made.id);+ }++ let mark = marks[geom];+ if (geom === 'auto') {+ // The editor's automatic choice: two value axes make a scatter; one makes a line along a date,+ // otherwise bars, or ticks when every record is drawn; none makes a table of text or colored cells.+ if (rows.measures && columns.measures) mark = 'point';+ else if (rows.measures || columns.measures) mark = (rows.measures ? columns : rows).terminal?.scale === 'time' ? 'line' : aggregated ? 'bar' : 'tick';+ else mark = encodings.text[0] ? 'text' : color && instances[color].display === 'continuous' ? 'rect' : 'point';+ }+ if (!mark) return result({ error: `The mark type "${geom}" is not drawn by the worksheet renderer yet.` });+ if (geom === 'trail') notes.push('Trail is drawn as a line of one width.');++ // A shelf the editor hides for this mark type may still hold a field from an earlier mark type.+ // Such a field is not part of the chart, as in the editor's own renderers.+ const shown = new Set<string>(viewEncodingKeys(geom));+ let text: string | undefined;+ // On a text mark the text field is what is written; on other marks it labels them.+ if (encodings.text[0] && (mark === 'text' || shown.has('text'))) {+ if (mark === 'boxplot') notes.push('Labels are not drawn on box plots.');+ else {+ const made = instance('text', encodings.text[0], 'encoding');+ if (typeof made === 'string') return result({ error: made });+ text = made.id;+ }+ }+ const channels: { size?: string; opacity?: string; shape?: string } = {};+ const unsized = mark === 'area' || mark === 'arc' || mark === 'boxplot';+ for (const channel of ['size', 'opacity', 'shape'] as const) {+ const f = encodings[channel][0];+ if (!f || !shown.has(channel)) continue;+ if (channel === 'size' && unsized) notes.push(`Size is not drawn on ${mark === 'boxplot' ? 'box plot' : mark} marks.`);+ else if (channel === 'opacity' && mark === 'boxplot') notes.push('Opacity is not drawn on box plots.');+ else if (channel === 'shape' && mark !== 'point' && mark !== 'circle') notes.push(`Shape is not drawn on ${mark} marks.`);+ else if (channel === 'shape' && isMeasure(f)) notes.push(`${f.name} on Shape is ignored: only a dimension picks symbols.`);+ else {+ const made = instance(channel, f, 'encoding');+ if (typeof made === 'string') return result({ error: made });+ channels[channel] = made.id;+ }+ }++ let angle: string | undefined;+ if (mark === 'arc' && encodings.theta[0]) {+ if (!isMeasure(encodings.theta[0])) return result({ error: `${encodings.theta[0].name} on Angle is a dimension. The worksheet renderer sizes slices by a measure.` });+ const made = instance('angle', encodings.theta[0], 'encoding');+ if (typeof made === 'string') return result({ error: made });+ angle = made.id;+ }++ // A chart with nothing on its shelves is not at fault. The editor leaves the chart area blank for it.+ const empty = rows.expr.kind === 'empty' && columns.expr.kind === 'empty';+ if (empty && !(mark === 'arc' && (angle || color))) return result({ error: 'There is nothing on rows or columns to draw yet.', empty: true });++ if (shown.has('radius') && encodings.radius.length) notes.push('Not drawn yet: radius.');+ // The editor's sort orders a dimension by the measure across from it, the first one where there are+ // several, as Tableau's toolbar sort takes the leftmost. Each parent header is ordered on its own.+ // A measure that is drawn per record still orders the members by one number per member: its sum,+ // or its median under a box plot, which is the line the box shows.+ const order: NonNullable<WorksheetSpec['order']> = {};+ // The limit orders the records themselves, so under it a measure drawn per record stays as it is.+ let ranked: { by: string; direction: 'ascending' | 'descending' } | undefined;+ for (const [own, other] of [[rows, columns], [columns, rows]] as const) {+ if (!own.sorted.length) continue;+ const candidates = [other.values[0], own.values[0], angle ? instances[angle] : undefined, text ? instances[text] : undefined, color && instances[color].display === 'continuous' ? instances[color] : undefined];+ let by = candidates.find((f): f is FieldInstance => Boolean(f));+ if (!by) { notes.push('There is no measure to sort by; members are in value order.'); continue; }+ ranked ??= { by: by.id, direction: own.sorted[own.sorted.length - 1].direction };+ if (!by.aggregate) by = instances.order = { id: 'order', field: by.field, label: by.label, display: 'continuous', aggregate: geom === 'boxplot' ? 'median' : 'sum' };+ for (const { id, direction } of own.sorted) order[id] = { by: by.id, direction };+ }+ // Settings the editor offers that this renderer does not read yet. Every one of them is listed in+ // the gap table of the plan document; a setting that starts to work is removed here and there.+ // Scale settings: the axes of each shelf, and the color, size and opacity channels. The editor's+ // 'pow' has no exponent setting and is a linear scale, as in its other renderers.+ const scales: NonNullable<WorksheetSpec['scales']> = {};+ const continuous = (id?: string) => Boolean(id && instances[id].display === 'continuous');+ for (const [from, to, id] of [['row', 'rows', undefined], ['column', 'columns', undefined], ['color', 'color', color], ['size', 'size', channels.size], ['opacity', 'opacity', channels.opacity]] as const) {+ const set = layout.scale?.[from];+ const channel = to !== 'rows' && to !== 'columns';+ const options: ScaleOptions = {};+ if (set?.type && set.type !== 'linear' && set.type !== 'pow') options.type = set.type;+ if (isNumber(set?.domainMin)) options.min = set!.domainMin;+ if (isNumber(set?.domainMax)) options.max = set!.domainMax;+ if (channel && to !== 'color' && isNumber(set?.rangeMin) && isNumber(set?.rangeMax)) options.range = [set!.rangeMin!, set!.rangeMax!];+ if (channel && Object.keys(options).length && id && !continuous(id)) {+ // A dimension has members, not a range; only what the levels turn into applies to it.+ if (options.type || options.min !== undefined || options.max !== undefined) notes.push(`The ${to} scale type and domain apply to a measure, not to a dimension.`);+ delete options.type; delete options.min; delete options.max;+ }+ // Independent: every pane ranges over its own values. A dimension keeps one look per member everywhere.+ if (channel && layout.resolve?.[to]) {+ if (continuous(id)) options.independent = true;+ else if (id) notes.push(`An independent ${to} scale applies to a measure; each member of a dimension keeps its ${to} in every pane.`);+ }+ if (Object.keys(options).length) scales[to] = options;+ }+ if (layout.resolve?.shape && channels.shape) notes.push('An independent shape scale is not applied; each member keeps its symbol in every pane.');+ for (const unused of ['theta', 'radius'] as const) if (layout.scale?.[unused] && Object.keys(layout.scale[unused]!).length) notes.push(`The ${unused} scale is not applied.`);+ if (layout.useSvg) notes.push('The sheet is always drawn on a canvas.');++ const spec: WorksheetSpec = {+ kind: 'worksheet', specVersion: 2, instances,+ rows: rows.expr, columns: columns.expr,+ mark, color, detail, text, angle, ...channels,+ // 'zero' is the editor's older name for a plain stack. Only bars and areas pile up.+ stack: layout.stack === 'none' ? false : layout.stack === 'normalize' || layout.stack === 'center' ? layout.stack : true,+ order,+ ...(Object.keys(scales).length ? { scales } : {}),+ // The editor's limit cuts the query result, after ordering it by the sort measure when a sort is on.+ limit: config.limit > 0 ? { rows: config.limit, ...ranked } : undefined,+ // The editor's switches are per direction: x is the axes along the columns, y the axes along the rows.+ scaleScope: { columns: layout.resolve?.x ? 'independent' : 'shared', rows: layout.resolve?.y ? 'independent' : 'shared' },+ };+ return result({ spec });+}++function unique(fields: IViewField[]): IViewField[] {+ return [...new Map(fields.map((f) => [`${f.fid}|${f.aggName ?? ''}`, f])).values()];+}diff --git a/packages/graphic-walker/src/renderer/native/expression.test.ts b/packages/graphic-walker/src/renderer/native/expression.test.tsnew file mode 100644index 00000000..3f42888e--- /dev/null+++ b/packages/graphic-walker/src/renderer/native/expression.test.ts@@ -0,0 +1,196 @@+import { buildScene } from '../../../../worksheet-renderer/src/scene';+import type { IDataQueryPayload, IFilterField, IRow, IViewField } from '../../interfaces';+import { toWorkflow } from '../../utils/workflow';+import { chartToWorksheet } from './adapter';+import { calc, chart, dim, drawn, local, mea } from './testing';++// Aggregate expressions in the worksheet renderer, checked against the editor's own workflow and the+// functions its local computation runs. Nothing here works an expression out by other means.++const ratio = calc('f_ratio', 'Ratio', 'sum(Sales) / sum(Cost)', 'aggregate');+const margin = calc('f_margin', 'Margin', 'Sales - Cost', 'row');+const rate = calc('f_rate', 'Rate', 'sum(Margin) / sum(Sales)', 'aggregate');+const broken = calc('f_broken', 'Broken', 'sum(Nope) / sum(Cost)', 'aggregate');+const dimensions = [dim('Region'), dim('Category'), dim('Sub')];+const measures = [mea('Sales'), mea('Cost'), ratio, margin, rate, broken];+const dataset = { dimensions, measures };+// East and West hold members of the same name. West, B, b1 has a cost of zero.+const orders: IRow[] = [+ { Region: 'East', Category: 'A', Sub: 'a1', Sales: 10, Cost: 1 },+ { Region: 'East', Category: 'A', Sub: 'a1', Sales: 20, Cost: 9 },+ { Region: 'East', Category: 'A', Sub: 'a2', Sales: 8, Cost: 4 },+ { Region: 'East', Category: 'B', Sub: 'b1', Sales: 9, Cost: 3 },+ { Region: 'West', Category: 'A', Sub: 'a1', Sales: 6, Cost: 12 },+ { Region: 'West', Category: 'A', Sub: 'a2', Sales: 15, Cost: 5 },+ { Region: 'West', Category: 'B', Sub: 'b1', Sales: 7, Cost: 0 },+];+const key = (row: IRow, fields: string[]) => fields.map((f) => row[f]).join(' / ');+/** What the editor's other renderers would be given for the same fields: its own workflow, run by its own functions. */+async function reference(viewDimensions: IViewField[], measure: IViewField, filters: IFilterField[] = [], sort: 'none' | 'ascending' | 'descending' = 'none', limit?: number) {+ const rows = await local(orders, toWorkflow(filters, [...dimensions, ...measures], viewDimensions, [measure], true, sort, [], limit), limit);+ return Object.fromEntries(rows.map((row) => [key(row, viewDimensions.map((f) => f.fid)), row[measure.fid]]));+}+const views = (payload: IDataQueryPayload) => payload.workflow.flatMap((step) => (step.type === 'view' ? step.query : [])).flatMap((query) => (query.op === 'aggregate' ? [query] : []));++describe('aggregate expressions', () => {+ test('E1: three levels of headers, each mark at the grain of all of them, as the editor computes it', async () => {+ const { model, marks, plan } = await drawn(chart({ ...dataset, rows: dimensions, columns: [ratio] }), orders);+ expect(model.rows.levels.map((level) => [...new Set(level.map((span) => span.part.value))])).toEqual([['East', 'West'], ['A', 'B'], ['a1', 'a2', 'b1']]);+ expect(model.rows.leaves.length).toBe(6);+ expect(plan.tasks.map((task) => task.groupBy)).toEqual([['Category', 'Region', 'Sub']]);+ const shown = Object.fromEntries(marks.map((r) => [key(r, ['Region', 'Category', 'Sub']), r.__ws_columnm0]));+ expect(shown).toEqual(await reference(dimensions, ratio));+ // Members of the same name under East and under West are different marks.+ expect(shown['East / A / a1']).toBe(3);+ expect(shown['West / A / a1']).toBe(0.5);+ });++ test('E2: the expression is worked out over the rows of a group, not per row and not from finer groups', async () => {+ // East, A, a1 holds 10 / 1 and 20 / 9. A ratio of sums is 30 / 10; ratios per row would add up to 12.2 or average 6.1.+ const fine = await drawn(chart({ ...dataset, rows: dimensions, columns: [ratio] }), orders);+ expect(fine.marks.find((r) => r.Region === 'East' && r.Sub === 'a1')!.__ws_columnm0).toBe(3);+ // East as a whole is 47 / 17. Its three finer groups are 3, 2 and 3, which neither add up nor average to that.+ const coarse = await drawn(chart({ ...dataset, rows: [dim('Region')], columns: [ratio] }), orders);+ expect(coarse.marks.find((r) => r.Region === 'East')!.__ws_columnm0).toBeCloseTo(47 / 17, 10);+ // The fields the expression reads do not join the grouping.+ expect(views(coarse.sent[0])[0].groupBy).toEqual(['Region']);+ });++ test('E3: next to a plain measure and on several channels at once, every use has its own result column', async () => {+ const c = chart({ ...dataset, rows: [dim('Region')], columns: [ratio, mea('Sales')], color: [ratio], text: [ratio], size: [ratio] }, { geoms: ['bar'] });+ const { sent, marks, model, csv, plan } = await drawn(c, orders);+ expect(plan.tasks.length).toBe(1);+ const [query] = views(sent[0]);+ const expression = '((sum ("Sales") ) / (sum ("Cost") ))';+ expect(query.measures).toEqual([+ { field: expression, agg: 'expr', asFieldKey: '__ws_columnm0' },+ { field: expression, agg: 'expr', asFieldKey: '__ws_color' },+ { field: expression, agg: 'expr', asFieldKey: '__ws_text' },+ { field: expression, agg: 'expr', asFieldKey: '__ws_size' },+ { field: 'Sales', agg: 'sum', asFieldKey: '__ws_columnm1' },+ ]);+ const east = marks.find((r) => r.Region === 'East')!, west = marks.find((r) => r.Region === 'West')!;+ for (const [record, value, sales] of [[east, 47 / 17, 47], [west, 28 / 17, 28]] as const) {+ for (const column of ['__ws_columnm0', '__ws_color', '__ws_text', '__ws_size']) expect(record[column]).toBeCloseTo(value, 10);+ expect(record.__ws_columnm1).toBe(sales);+ }+ // Tooltips name the expression once and the plain measure next to it, in both panes; labels write the same number.+ const scene = buildScene(model, { x: 0, y: 0, width: model.width, height: model.height });+ const tips = scene.items.filter((p) => p.selection?.values.Region === 'East' && p.tooltip).map((p) => p.tooltip!);+ // A mark names the fields of its own pane: the bar on the Ratio axis the ratio, the bar on the Sales axis both.+ expect([...new Set(tips)].sort()).toEqual(['Region: East\nRatio: 2.76', 'Region: East\nsum(Sales): 47\nRatio: 2.76']);+ expect(scene.items.some((p) => p.kind === 'text' && p.text === '2.76')).toBe(true);+ // The exported table holds what the marks were drawn from.+ expect(csv).toHaveLength(1);+ const [header, ...lines] = csv[0].split('\n');+ expect(header).toBe('Region,Ratio,Ratio,Ratio,Ratio,sum(Sales)');+ expect(lines.map((line) => line.split(','))).toEqual([+ ['East', ...Array(4).fill(String(47 / 17)), '47'],+ ['West', ...Array(4).fill(String(28 / 17)), '28'],+ ]);+ });++ test('E4: row filters, a filter on the expression, ordering and the limit keep their order and meaning', async () => {+ const onlyA: IFilterField = { ...dim('Category'), rule: { type: 'one of', value: ['A'] } };+ const atLeast = (least: number): IFilterField => ({ ...ratio, enableAgg: true, rule: { type: 'range', value: [least, null] } });+ const rows = [dim('Region'), dim('Sub')];+ // Category A alone: East a1 is 3, East a2 is 2, West a1 is 0.5, West a2 is 3.+ const some = await drawn(chart({ ...dataset, rows, columns: [ratio], filters: [onlyA, atLeast(2.5)] }), orders);+ expect(some.marks.map((r) => key(r, ['Region', 'Sub'])).sort()).toEqual(['East / a1', 'West / a2']);+ expect(Object.fromEntries(some.marks.map((r) => [key(r, ['Region', 'Sub']), r.__ws_columnm0]))).toEqual(await reference(rows, ratio, [onlyA, atLeast(2.5)]));+ // Rows are filtered first, groups are filtered after the expression is worked out, under the filter's own name.+ expect(some.sent[0].workflow.map((step) => step.type)).toEqual(['filter', 'view', 'filter']);+ expect(views(some.sent[0])[0].measures.map((m) => m.asFieldKey)).toEqual(['__ws_columnm0', 'f_ratio']);+ expect(some.sent[0].workflow[2]).toMatchObject({ filters: [{ fid: 'f_ratio', rule: { type: 'range', value: [2.5, null] } }] });+ // A filter no group passes leaves an empty sheet, not an error and not the unfiltered marks.+ const none = await drawn(chart({ ...dataset, rows, columns: [ratio], filters: [onlyA, atLeast(100)] }), orders);+ expect(none.marks).toEqual([]);+ expect(none.model.panes.flatMap((pane) => pane.marks)).toEqual([]);++ // The three groups with the highest ratio, as the editor's own sort and limit pick them.+ const sorted = [dim('Region'), { ...dim('Sub'), sort: 'descending' as const }];+ const top = await drawn(chart({ ...dataset, rows: sorted, columns: [ratio], filters: [onlyA] }, { limit: 3 }), orders);+ expect(Object.fromEntries(top.marks.map((r) => [key(r, ['Region', 'Sub']), r.__ws_columnm0]))).toEqual(await reference(rows, ratio, [onlyA], 'descending', 3));+ expect(top.marks.map((r) => key(r, ['Region', 'Sub'])).sort()).toEqual(['East / a1', 'East / a2', 'West / a2']);+ const cut = top.sent.find((payload) => payload.limit)!;+ expect(cut.workflow.map((step) => step.type)).toEqual(['filter', 'view', 'sort']);+ expect(cut.limit).toBe(3);+ // The query that orders the members of Sub inside each region is another one. It is not cut, and it works+ // the expression out again at its own grain under its own name rather than reading the marks' column.+ const others = top.sent.filter((payload) => payload !== cut);+ expect(others.length).toBeGreaterThan(0);+ for (const payload of others) {+ expect(payload.limit).toBeUndefined();+ expect(views(payload)[0].measures.every((m) => m.agg === 'expr' && m.field.includes('sum'))).toBe(true);+ }+ });++ test('E5: computed inputs, missing values, division by zero and a wrong expression follow the editor', async () => {+ // Rate reads Margin, which is computed per row and is not on any shelf. It has to exist before the grouping.+ const rated = await drawn(chart({ ...dataset, rows: [dim('Region')], columns: [rate] }), orders);+ expect(rated.sent[0].workflow.map((step) => step.type)).toEqual(['transform', 'view']);+ expect(rated.sent[0].workflow[0]).toMatchObject({ transform: [{ key: 'f_margin' }] });+ expect(views(rated.sent[0])[0].groupBy).toEqual(['Region']);+ const shown = Object.fromEntries(rated.marks.map((r) => [r.Region, r.__ws_columnm0]));+ expect(shown.East).toBeCloseTo((47 - 17) / 47, 10);+ expect(shown.West).toBeCloseTo((28 - 17) / 28, 10);+ expect(shown).toEqual(await reference([dim('Region')], rate));++ // A group whose divisor is zero comes out of the editor's computation as infinity. The sheet keeps the record+ // as computed and draws no mark for it: no length is made up, and the axis ranges over the finite values only.+ const fine = await drawn(chart({ ...dataset, rows: dimensions, columns: [ratio] }), orders);+ const expected = await reference(dimensions, ratio);+ expect(expected['West / B / b1']).toBe(Infinity);+ expect(fine.marks.find((r) => r.Region === 'West' && r.Sub === 'b1')!.__ws_columnm0).toBe(Infinity);+ const mark = fine.model.panes.flatMap((pane) => pane.marks).find((m) => m.record.Region === 'West' && m.record.Sub === 'b1')!;+ expect([mark.start, mark.end]).toEqual([NaN, NaN]);+ expect(fine.model.columns.leaves[0].scale!.domain).toEqual([0, 3]);+ // A missing value among the rows of a group is treated as the editor's sum treats it.+ const sparse = [...orders, { Region: 'North', Category: 'A', Sub: 'a1', Sales: null, Cost: 4 }];+ const north = await drawn(chart({ ...dataset, rows: [dim('Region')], columns: [ratio] }), sparse);+ const northReference = await local(sparse, toWorkflow([], [...dimensions, ...measures], [dim('Region')], [ratio], true, 'none'));+ expect(north.marks.find((r) => r.Region === 'North')!.__ws_columnm0).toBe(northReference.find((r) => r.Region === 'North')!.f_ratio);++ // An expression the computation rejects is an error with its message. Nothing is drawn in its place.+ await expect(drawn(chart({ ...dataset, rows: [dim('Region')], columns: [broken] }), orders)).rejects.toThrow(/no field named nope/);+ // So is an aggregate expression the editor has typed as a dimension: there are no members to group by.+ expect(chartToWorksheet(chart({ ...dataset, rows: [{ ...ratio, analyticType: 'dimension', semanticType: 'nominal' }], columns: [mea('Sales')] })).error).toMatch(/Ratio is an aggregate expression, but it is set as a dimension/);+ // A field that claims to be an aggregate expression without one is refused before any query.+ expect(chartToWorksheet(chart({ dimensions, measures: [], rows: [dim('Region')], columns: [{ ...ratio, expression: undefined }] })).error).toMatch(/Ratio is an aggregate expression/);+ });++ test('E5: without aggregation an aggregate expression is not drawn, as in the other renderers', async () => {+ const { sent, plan, marks } = await drawn(chart({ ...dataset, rows: [dim('Region')], columns: [ratio, mea('Sales')] }, { defaultAggregated: false }), orders);+ expect(Object.values(plan.spec.instances).map((f) => f.field)).toEqual(['Region', 'Sales']);+ expect(JSON.stringify(sent)).not.toMatch(/expr/);+ expect(marks.length).toBe(orders.length);+ expect(chartToWorksheet(chart({ ...dataset, rows: [dim('Region')], columns: [ratio] }, { defaultAggregated: false })).notes.join(' ')).toMatch(/Ratio: an aggregate expression is not drawn while aggregation is off/);+ });++ test("E6: the expression goes to the host's computation as the editor writes it, and the sheet shows what comes back", async () => {+ // A host that answers every group with a number no local computation would give.+ const received: IDataQueryPayload[] = [];+ const host = async (payload: IDataQueryPayload) => {+ received.push(payload);+ const [query] = views(payload);+ return ['East', 'West'].map((Region, index) => ({ Region, ...Object.fromEntries(query.measures.map((m) => [m.asFieldKey, 1000 + index])) }));+ };+ const sorted = { ...dim('Region'), sort: 'descending' as const };+ const { marks, model } = await drawn(chart({ ...dataset, rows: [sorted], columns: [rate], color: [ratio] }), orders, host);+ expect(received.length).toBeGreaterThan(0);+ for (const payload of received) {+ // Computed inputs first, then one grouping that carries the expressions as text for the host to evaluate.+ expect(payload.workflow.map((step) => step.type)).toEqual(['transform', 'view']);+ expect(payload.workflow[0]).toMatchObject({ transform: [{ key: 'f_margin', expression: { op: 'expr' } }] });+ const [query] = views(payload);+ expect(query.groupBy).toEqual(['Region']);+ expect(query.measures).toEqual([+ { field: '((sum (f_margin) ) / (sum ("Sales") ))', agg: 'expr', asFieldKey: '__ws_columnm0' },+ { field: '((sum ("Sales") ) / (sum ("Cost") ))', agg: 'expr', asFieldKey: '__ws_color' },+ ]);+ }+ expect(marks.map((r) => [r.Region, r.__ws_columnm0, r.__ws_color])).toEqual([['East', 1000, 1000], ['West', 1001, 1001]]);+ // The members are ordered by what the host returned, highest first.+ expect(model.rows.levels[0].map((span) => span.part.value)).toEqual(['West', 'East']);+ });+});diff --git a/packages/graphic-walker/src/renderer/native/formats.ts b/packages/graphic-walker/src/renderer/native/formats.tsnew file mode 100644index 00000000..c4bf592c--- /dev/null+++ b/packages/graphic-walker/src/renderer/native/formats.ts@@ -0,0 +1,49 @@+import { format as numberFormat } from 'd3-format';+import { timeFormatLocale, type TimeLocaleDefinition } from 'd3-time-format';+import type { Formats, Words } from '@kanaries/worksheet-renderer';+import type { IVisualLayout } from '../../interfaces';+import { getVegaTimeFormatRules } from '../../vis/temporalFormat';++// The words the sheet writes itself, for the languages the editor ships, by language without region:+// the editor may report 'zh' as well as 'zh-CN'. Other languages read English.+const words: Record<string, Partial<Words>> = {+ zh: {+ share: '占比', upperWhisker: '上须', upperQuartile: '上四分位数', median: '中位数', lowerQuartile: '下四分位数', lowerWhisker: '下须',+ records: '记录数', more: (count) => `另有 ${count} 项`, empty: '没有符合筛选条件的数据',+ },+ ja: {+ share: '割合', upperWhisker: '上ひげ', upperQuartile: '第3四分位数', median: '中央値', lowerQuartile: '第1四分位数', lowerWhisker: '下ひげ',+ records: 'レコード数', more: (count) => `他 ${count} 件`, empty: 'フィルターに一致するデータがありません',+ },+};++/**+ * The chart's format settings and the editor's language, as the worksheet takes them.+ * The settings are d3 format strings, as for the editor's other renderers. A string d3 cannot+ * read is reported and left out, so the chart keeps its standard format instead of failing.+ */+export function chartFormats(format: IVisualLayout['format'], locale: string): { formats: Formats; problems: string[] } {+ const problems: string[] = [];+ const attempt = <T>(name: string, specifier: string | undefined, make: (specifier: string) => (value: T) => string) => {+ if (!specifier) return undefined;+ try {+ const made = make(specifier);+ return (value: T) => made(value);+ } catch (error) {+ problems.push(`The ${name} "${specifier}" is not a format d3 can read: ${error instanceof Error ? error.message : String(error)}`);+ return undefined;+ }+ };+ // Times reach the sheet already shifted to the display zone, to be read as UTC.+ const dates = timeFormatLocale(getVegaTimeFormatRules(locale) as TimeLocaleDefinition);+ return {+ formats: {+ locale,+ number: attempt<number>('number format', format?.numberFormat, numberFormat),+ share: attempt<number>('normalized number format', format?.normalizedNumberFormat, numberFormat),+ time: attempt<number>('time format', format?.timeFormat, (specifier) => { const made = dates.utcFormat(specifier); return (ms) => made(new Date(ms)); }),+ words: words[locale.split('-')[0]],+ },+ problems,+ };+}diff --git a/packages/graphic-walker/src/renderer/native/having.test.ts b/packages/graphic-walker/src/renderer/native/having.test.tsnew file mode 100644index 00000000..a1d11487--- /dev/null+++ b/packages/graphic-walker/src/renderer/native/having.test.ts@@ -0,0 +1,76 @@+import { compileWorksheet } from '../../../../worksheet-renderer/src/compiler';+import type { IFilterField, IRow, IViewField } from '../../interfaces';+import { chartToWorksheet } from './adapter';+import { drawnAtGrain } from './having';+import { chart, dim, drawn, mea } from './testing';++const atLeast = (fid: string, least: number, aggName = 'sum'): IFilterField => ({ ...mea(fid, aggName), enableAgg: true, rule: { type: 'range', value: [least, null] } });++const sales: IRow[] = [+ { Region: 'East', Category: 'A', Sales: 60, Profit: 5 }, { Region: 'East', Category: 'A', Sales: 70, Profit: 5 },+ { Region: 'East', Category: 'B', Sales: 20, Profit: 9 },+ { Region: 'West', Category: 'A', Sales: 30, Profit: 1 },+ { Region: 'West', Category: 'B', Sales: 90, Profit: 2 }, { Region: 'West', Category: 'B', Sales: 40, Profit: 2 },+];++describe('filters on aggregated values', () => {+ test('a group that fails the filter is not drawn', async () => {+ const base = { rows: [dim('Region')], columns: [mea('Sales')] };+ const all = await drawn(chart(base), sales);+ expect(all.having).toBeUndefined();+ expect(all.marks.map((r) => r.Region).sort()).toEqual(['East', 'West']);+ // East sums to 150, West to 160.+ const some = await drawn(chart({ ...base, filters: [atLeast('Sales', 155)] }), sales);+ expect(some.having).toMatchObject({ groupBy: ['Region'], measures: [{ field: 'Sales', agg: 'sum', asFieldKey: 'Sales_sum' }] });+ expect(some.marks.map((r) => r.Region)).toEqual(['West']);+ // The filter comes after the grouping and reads the aggregate under its own name.+ const [{ workflow }] = some.sent;+ expect(workflow.map((step) => step.type)).toEqual(['view', 'filter']);+ expect(workflow[1]).toMatchObject({ filters: [{ fid: 'Sales_sum', rule: { type: 'range', value: [155, null] } }] });+ });+ test('the filter holds at the grain of the marks, in every level of headers', async () => {+ // Sums per Region and Category: East A 130, East B 20, West A 30, West B 130.+ const { marks, model } = await drawn(chart({ rows: [dim('Region'), dim('Category')], columns: [mea('Sales')], filters: [atLeast('Sales', 100)] }), sales);+ expect(marks.map((r) => `${r.Region} ${r.Category}`).sort()).toEqual(['East A', 'West B']);+ expect(model.rows.leaves.length).toBe(2);+ });+ test('a filter may read an aggregate that is not drawn, and every measure axis is filtered alike', async () => {+ // Mean profit per region: East 6.33, West 1.67. Two measures make two queries.+ const { marks, sent } = await drawn(chart({ rows: [dim('Region')], columns: [mea('Sales'), mea('Profit')], filters: [atLeast('Profit', 5, 'mean')] }), sales);+ expect(marks.length).toBeGreaterThan(0);+ expect(new Set(marks.map((r) => r.Region))).toEqual(new Set(['East']));+ for (const { workflow } of sent) {+ const view = workflow.find((step) => step.type === 'view')!;+ expect(view.type === 'view' && view.query[0].op === 'aggregate' && view.query[0].measures.map((m) => m.asFieldKey)).toContain('Profit_mean');+ expect(workflow.some((step) => step.type === 'filter')).toBe(true);+ }+ });+ test('a query that orders members by their totals is not filtered', async () => {+ const sorted: IViewField = { ...dim('Category'), sort: 'descending' };+ const { plan, sent, marks } = await drawn(chart({ rows: [dim('Region'), sorted], columns: [mea('Sales')], filters: [atLeast('Sales', 100)] }), sales);+ expect(plan.rankings.length).toBeGreaterThan(0);+ expect(marks.map((r) => `${r.Region} ${r.Category}`).sort()).toEqual(['East A', 'West B']);+ const grains = sent.map(({ workflow }) => {+ const view = workflow.find((step) => step.type === 'view')!;+ return { groupBy: view.type === 'view' && view.query[0].op === 'aggregate' ? view.query[0].groupBy.length : -1, filtered: workflow.some((step) => step.type === 'filter') };+ });+ // Only queries at the grain of the marks, Region and Category, carry the filter.+ expect(grains.every((g) => g.filtered === (g.groupBy === 2))).toBe(true);+ expect(grains.some((g) => g.filtered)).toBe(true);+ });+ test('without aggregation there is nothing to filter after grouping, as in the other renderers', async () => {+ const { having, marks } = await drawn(chart({ rows: [dim('Region')], columns: [mea('Sales')], filters: [atLeast('Sales', 155)] }, { defaultAggregated: false }), sales);+ expect(having).toBeUndefined();+ expect(marks.length).toBe(sales.length);+ });+ test('a sheet drawn from another grain than the filter is told apart', () => {+ const filtered = chart({ rows: [dim('Region')], columns: [mea('Sales')], filters: [atLeast('Sales', 100)] });+ const bars = compileWorksheet(chartToWorksheet(filtered).spec!);+ expect(drawnAtGrain(bars, ['Region'])).toBe(true);+ expect(drawnAtGrain(bars, ['Region', 'Category'])).toBe(false);+ // A box plot without aggregation reads source rows, which a filter on groups says nothing about.+ const boxes = compileWorksheet(chartToWorksheet(chart({ rows: [dim('Region')], columns: [mea('Sales')] }, { geoms: ['boxplot'], defaultAggregated: false })).spec!);+ expect(boxes.tasks.some((task) => task.raw)).toBe(true);+ expect(drawnAtGrain(boxes, ['Region'])).toBe(false);+ });+});diff --git a/packages/graphic-walker/src/renderer/native/having.ts b/packages/graphic-walker/src/renderer/native/having.tsnew file mode 100644index 00000000..d07a868c--- /dev/null+++ b/packages/graphic-walker/src/renderer/native/having.ts@@ -0,0 +1,92 @@+import type { Plan, QueryPayload } from '@kanaries/worksheet-renderer';+import type { IDataQueryWorkflowStep, IFilterWorkflowStep, IViewWorkflowStep } from '../../interfaces';++type Measure = Extract<IViewWorkflowStep['query'][number], { op: 'aggregate' }>['measures'][number];++/**+ * The editor's filters on aggregated values, such as sum(Sales) >= 100. The editor applies them to+ * the rows of its one aggregated query, so they hold at one grain: the dimensions that query+ * groups by. `measures` are the aggregates the filters read, under the names the filters use.+ */+export interface Having {+ groupBy: string[];+ measures: Measure[];+ filters: IFilterWorkflowStep[];+}++/**+ * What the editor's own workflow says about a chart, for the worksheet's queries to be built around.+ * - `before`: the steps ahead of the editor's view step, which every worksheet query starts with:+ * row filters, computed fields, filters on those.+ * - `expressions`: the aggregate expressions of the chart by field id, as the editor's workflow+ * builder wrote them out, with the fields they name resolved.+ * - `having`: the filters on aggregated values that come after the view step.+ */+export interface Around {+ before: IDataQueryWorkflowStep[];+ expressions: Record<string, string>;+ having?: Having;+}++/** Reads `Around` out of the workflow the editor would run for the chart. */+export function splitWorkflow(steps: IDataQueryWorkflowStep[]): Around {+ const at = steps.findIndex((step) => step.type === 'view');+ if (at < 0) return { before: [], expressions: {} };+ const before = steps.slice(0, at);+ const view = steps[at];+ const query = view.type === 'view' ? view.query[0] : undefined;+ if (query?.op !== 'aggregate') return { before, expressions: {} };+ // Where the dataset has no expression for such a field, the builder leaves the field id in its place.+ const expressions = Object.fromEntries(query.measures.filter((m) => m.agg === 'expr' && m.field !== m.asFieldKey).map((m) => [m.asFieldKey, m.field]));+ const filters = steps.slice(at + 1).filter((step): step is IFilterWorkflowStep => step.type === 'filter');+ if (!filters.length) return { before, expressions };+ const read = new Set(filters.flatMap((step) => step.filters.map((f) => f.fid)));+ return { before, expressions, having: { groupBy: query.groupBy, measures: query.measures.filter((m) => read.has(m.asFieldKey)), filters } };+}++const sameFields = (a: string[], b: string[]) => {+ const set = new Set(a);+ return set.size === new Set(b).size && b.every((field) => set.has(field));+};++/**+ * Whether every query the sheet draws its marks from is an aggregate at the grain the filters hold+ * at. Only then do the filters mean in the sheet what they mean in the editor's other renderers.+ * Queries that only order members are at a coarser grain and are not asked about.+ */+export function drawnAtGrain(plan: Plan, groupBy: string[]): boolean {+ const drawn = new Set(plan.bindings.map((binding) => binding.taskId));+ return plan.tasks.filter((task) => drawn.has(task.id)).every((task) => !task.raw && sameFields(task.groupBy, groupBy));+}++/**+ * The workflow sent for one worksheet query: the editor's steps before its view step, the+ * worksheet's own grouping, the filters on aggregated values where the query is at their grain,+ * and the worksheet's ordering. A query at another grain, which orders members by their totals,+ * is not filtered.+ *+ * An aggregate expression is asked for by field id and sent as the editor's expression, to be+ * worked out by the data source over the rows of each group of this query. So a query that orders+ * members gets the expression's value for each member as a whole, not one put together from the+ * values of the marks.+ */+export function composeWorkflow({ before, expressions, having }: Around, aggregated: boolean, payload: QueryPayload): IDataQueryWorkflowStep[] {+ const view = payload.workflow.find((step) => step.type === 'view');+ const query = view && view.type === 'view' ? view.query[0] : undefined;+ if (!query) return [];+ // What the worksheet wants done with the result: put it in order and keep the first rows.+ const after = payload.workflow.filter((step): step is Extract<typeof step, { type: 'sort' }> => step.type === 'sort');+ // Without aggregation every source row is a mark, duplicates included, as in the other renderers.+ if (query.op === 'raw') return [...before, { type: 'view', query: [{ op: 'raw', fields: query.fields }] }, ...after];+ if (!aggregated && query.measures.length === 0) return [...before, { type: 'view', query: [{ op: 'raw', fields: query.groupBy }] }, ...after];+ const filtered = having && sameFields(query.groupBy, having.groupBy) ? having : undefined;+ const own = query.measures.map((m): Measure => {+ if (m.agg !== 'expr') return m;+ const expression = expressions[m.field];+ if (!expression) throw new Error(`There is no expression for the aggregate field "${m.field}".`);+ return { ...m, field: expression };+ });+ // The aggregates the filters read are added under the filters' own names, next to the worksheet's.+ const measures: Measure[] = [...own, ...(filtered?.measures.filter((m) => !own.some((mine) => mine.asFieldKey === m.asFieldKey)) ?? [])];+ return [...before, { type: 'view', query: [{ op: 'aggregate', groupBy: query.groupBy, measures }] }, ...(filtered?.filters ?? []), ...after];+}diff --git a/packages/graphic-walker/src/renderer/native/index.tsx b/packages/graphic-walker/src/renderer/native/index.tsxnew file mode 100644index 00000000..86bdd87e--- /dev/null+++ b/packages/graphic-walker/src/renderer/native/index.tsx@@ -0,0 +1,164 @@+import { useEffect, useImperativeHandle, useMemo, useRef, useState, type RefObject } from 'react';+import { Worksheet, compileWorksheet, darkTheme, lightTheme, tableToCSV, type Computation, type Theme, type WorksheetHandle } from '@kanaries/worksheet-renderer';+import type { IChart } from '../../interfaces';+import { registerNativeRenderer, type NativeRendererProps, type NativeUnsupported } from '../../renderer/nativeRegistry';+import { toWorkflow } from '../../utils/workflow';+import { chartToWorksheet } from './adapter';+import { composeWorkflow, drawnAtGrain, splitWorkflow, type Around } from './having';+import { chartFormats } from './formats';++/** Red, green, blue and alpha of a CSS rgb(), rgba() or #rrggbb color. Alpha is 1 where the color names none. */+function channels(color: string): [number, number, number, number] {+ const hex = /^#([0-9a-f]{6})$/i.exec(color.trim())?.[1];+ if (hex) return [parseInt(hex.slice(0, 2), 16), parseInt(hex.slice(2, 4), 16), parseInt(hex.slice(4, 6), 16), 1];+ const [r = 255, g = 255, b = 255, a = 1] = (color.match(/[\d.]+/g) ?? []).map(Number);+ return [r, g, b, a];+}+const isDark = (color: string) => { const [r, g, b] = channels(color); return (0.2126 * r + 0.7152 * g + 0.0722 * b) / 255 < 0.45; };+/** `top` painted over `bottom`, as one opaque color. The sheet's frozen headers must hide what scrolls under them. */+function over(top: string | undefined, bottom: string): string {+ if (!top) return bottom;+ const [r, g, b, a] = channels(top), under = channels(bottom);+ if (a <= 0) return bottom;+ return `rgb(${[r, g, b].map((v, i) => Math.round(v * a + under[i] * (1 - a))).join(', ')})`;+}++/**+ * The color of the surface the chart sits on: the first opaque background above it, through+ * shadow roots. The editor has no single value for this; its look comes from classes and+ * from the system setting. Until one is found, `fallback` stands in.+ */+function useSurface(host: RefObject<HTMLElement | null>, fallback: string): string {+ const [surface, setSurface] = useState<string>();+ useEffect(() => {+ const ancestors: Element[] = [];+ for (let node: Node | null = host.current; node; node = node.parentNode ?? (node as ShadowRoot).host ?? null) {+ if (node instanceof Element) ancestors.push(node);+ }+ const media = window.matchMedia('(prefers-color-scheme: dark)');+ const read = () => setSurface(ancestors.map((element) => getComputedStyle(element).backgroundColor).find((color) => channels(color)[3] > 0.9));+ read();+ // A theme switch shows up as a class or style change on some ancestor, or as a system change.+ const observer = new MutationObserver(read);+ for (const element of ancestors) observer.observe(element, { attributes: true, attributeFilter: ['class', 'style', 'data-theme'] });+ media.addEventListener('change', read);+ return () => { observer.disconnect(); media.removeEventListener('change', read); };+ }, [host]);+ return surface ?? fallback;+}++/**+ * The worksheet renderer inside the editor. The chart is mapped on every change and is+ * never rewritten. Filters and computed fields go through the editor's own workflow+ * builder; only the grouping step comes from the worksheet, which asks for one result+ * per grain it draws.+ */+function NativeWorksheet({ chart, fields, computation, colors, locale, fill, onError, handle, onStatusChange, onMarkClick }: NativeRendererProps) {+ const adapted = useMemo(() => chartToWorksheet(chart), [chart]);+ // In the fixed and full layout modes the whole sheet is scaled to the box the editor gives it. In the auto+ // mode only the value axes take up the room of the chart area, and a sheet that is too large scrolls.+ const spec = useMemo(() => adapted.spec && (fill ? { ...adapted.spec, fit: 'both' as const } : { ...adapted.spec, stretch: 'both' as const }), [adapted.spec, fill]);+ const aggregated = chart.config.defaultAggregated;+ // Everything the editor would run before its own view step: row filters, computed fields, filters on+ // those. The aggregate expressions as it would send them. And what it would run after: filters on+ // aggregated values, which go into the worksheet's queries.+ const around = useMemo(+ () => JSON.stringify(splitWorkflow(toWorkflow(chart.encodings.filters, fields, adapted.viewDimensions, adapted.viewMeasures, aggregated, 'none', chart.config.folds, undefined, chart.config.timezoneDisplayOffset))),+ [chart, fields, adapted, aggregated]+ );+ // `around` is compared as text so that an unrelated store update does not restart the queries.+ // Every query goes to the computation the host gave the editor, expressions included. Nothing is worked out here.+ const run = useMemo<Computation>(() => {+ const parsed: Around = JSON.parse(around);+ return async (payload) => {+ const workflow = composeWorkflow(parsed, aggregated, payload);+ return workflow.length ? computation({ workflow, limit: payload.limit }) : [];+ };+ }, [around, aggregated, computation]);++ // Exports are of the whole sheet, not only the part scrolled into view. The CSV holds the query+ // result the marks are drawn from, with the values as stored.+ const sheet = useRef<WorksheetHandle>(null);+ useImperativeHandle(handle, () => {+ const ready = () => { if (!sheet.current) throw new Error('The chart is not drawn yet.'); return sheet.current; };+ return {+ exportSVG: async () => ready().exportSVG(),+ exportPNG: async () => ready().exportPNG(),+ exportCSV: () => ready().exportRecords().map(tableToCSV).join('\n\n'),+ size: () => ready().size(),+ };+ }, []);+ // Number and time formats from the chart settings, and the editor's language for everything they leave open.+ const { numberFormat, timeFormat, normalizedNumberFormat } = chart.layout.format ?? {};+ const written = useMemo(() => chartFormats({ numberFormat, timeFormat, normalizedNumberFormat }, locale), [numberFormat, timeFormat, normalizedNumberFormat, locale]);+ // The chart area shows nothing but the chart, so what was left out goes to the console.+ const dropped = [...adapted.notes, ...written.problems].join(' ');+ useEffect(() => { if (dropped) console.info(`[worksheet renderer] ${dropped}`); }, [dropped]);+ const host = useRef<HTMLDivElement>(null);+ const surface = useSurface(host, colors.dark ? darkTheme.paper : lightTheme.paper);+ // The canvas paints the surface color itself, or the chart's own background over it, so it blends in.+ // Text and rules follow how bright that is; marks follow the editor's theme, primary color and palette.+ const theme = useMemo<Theme>(() => {+ const paper = over(colors.background, surface);+ const dark = isDark(paper);+ const base = dark ? darkTheme : lightTheme;+ // The theme's text and rule colors are made for the editor's own surface. On a background the user+ // set that is the other way round, light on dark or dark on light, they would not read, and the standard ones stay.+ const fits = dark === colors.dark;+ return {+ ...base, paper, mark: colors.primary,+ category: colors.category.length ? colors.category : base.category,+ ramp: colors.ramp.length ? colors.ramp : base.ramp,+ diverging: colors.diverging?.length ? colors.diverging : base.diverging,+ heatmap: colors.heatmap,+ ...(fits && colors.text ? { text: colors.text } : {}),+ ...(fits && colors.muted ? { muted: colors.muted } : {}),+ ...(fits && colors.line ? { line: colors.line } : {}),+ ...(fits && colors.grid ? { grid: colors.grid } : {}),+ ...colors.style,+ };+ }, [surface, colors]);+ const [height, setHeight] = useState(520);+ useEffect(() => {+ const element = host.current!;+ // A box the viewer sized is taken as it is; otherwise the sheet keeps a height worth drawing in.+ const observer = new ResizeObserver(() => setHeight(Math.max(fill ? 60 : 160, element.clientHeight - 16)));+ observer.observe(element);+ return () => observer.disconnect();+ }, [fill]);+ // Nothing but the chart is drawn here. What the adapter left out is listed in adapted.notes+ // and covered by the adapter tests; the editor has no place for it next to the chart yet.+ return (+ <div ref={host} style={{ height: '100%', padding: 8, color: theme.text, overflow: 'hidden', boxSizing: 'border-box' }}>+ {spec ? <Worksheet ref={sheet} spec={spec} computation={run} height={height} theme={theme} formats={written.formats} compact zoomable={chart.layout.interactiveScale}+ onError={(message) => { if (message) onError(message); }}+ // The worksheet's own words for where it stands, in the editor's.+ onStatusChange={(status) => onStatusChange?.(status === 'querying' ? 'computing' : status === 'drawing' ? 'rendering' : status)}+ // What identifies the mark: its dimension values, as stored. Measures are left out, as an aggregated value is not a filter on rows.+ onMarkClick={(selection, event) => onMarkClick?.(Object.fromEntries(selection.predicates.map((p) => [p.field, p.value])), event)}+ /> : null}+ </div>+ );+}++// Says why a chart cannot be drawn here, before anything is mounted or queried: it does not map to a+// worksheet, or the worksheet does not compile. The editor shows the reason in the chart area.+function check(chart: IChart): NativeUnsupported | undefined {+ const { spec, error, empty, viewDimensions, viewMeasures } = chartToWorksheet(chart);+ if (!spec) return { reason: error ?? 'The chart does not map to a worksheet.', empty };+ try {+ const plan = compileWorksheet(spec);+ // A filter on an aggregated value holds at the grain of the editor's one query. A sheet that draws+ // from another grain would show marks the filter should have removed.+ const fields = [...chart.encodings.dimensions, ...chart.encodings.measures];+ const { having } = splitWorkflow(toWorkflow(chart.encodings.filters, fields, viewDimensions, viewMeasures, chart.config.defaultAggregated, 'none', chart.config.folds));+ if (having && !drawnAtGrain(plan, having.groupBy)) {+ const names = chart.encodings.filters.filter((f) => f.enableAgg && f.aggName && f.rule).map((f) => f.name);+ return { reason: `The filter on an aggregated value (${names.join(', ')}) applies to groups of rows, and this chart is not drawn from those groups.` };+ }+ } catch (error) {+ return { reason: error instanceof Error ? error.message : String(error) };+ }+}+export const worksheetRenderer = { component: NativeWorksheet, check };+registerNativeRenderer(worksheetRenderer);diff --git a/packages/graphic-walker/src/renderer/native/testing.ts b/packages/graphic-walker/src/renderer/native/testing.tsnew file mode 100644index 00000000..841a92b2--- /dev/null+++ b/packages/graphic-walker/src/renderer/native/testing.ts@@ -0,0 +1,59 @@+import { compileWorksheet, executePlan } from '../../../../worksheet-renderer/src/compiler';+import { resultTables, tableToCSV } from '../../../../worksheet-renderer/src/export';+import { buildModel } from '../../../../worksheet-renderer/src/model';+import type { Computation } from '../../../../worksheet-renderer/src/types';+import { filter } from '../../lib/filter';+import { sortBy } from '../../lib/sort';+import { transformData } from '../../lib/transform';+import { queryView } from '../../lib/viewQuery';+import type { IChart, IDataQueryPayload, IDataQueryWorkflowStep, IRow, IViewField } from '../../interfaces';+import { emptyEncodings, emptyVisualConfig, emptyVisualLayout } from '../../utils/save';+import { toWorkflow } from '../../utils/workflow';+import { chartToWorksheet } from './adapter';+import { composeWorkflow, splitWorkflow } from './having';++// Shared by the tests of this folder. Nothing here is loaded by the editor.++export const dim = (fid: string): IViewField => ({ fid, name: fid, semanticType: 'nominal', analyticType: 'dimension' });+export const mea = (fid: string, aggName = 'sum'): IViewField => ({ fid, name: fid, semanticType: 'quantitative', analyticType: 'measure', aggName });+/** A computed field as the editor stores it: an aggregate when its expression is one, otherwise a value per row. */+export const calc = (fid: string, name: string, sql: string, kind: 'aggregate' | 'row'): IViewField => ({+ fid, name, semanticType: 'quantitative', analyticType: 'measure', computed: true, aggName: kind === 'aggregate' ? 'expr' : 'sum',+ expression: { op: 'expr', as: fid, params: [{ type: 'sql', value: sql }] },+});+export function chart(encodings: Partial<IChart['encodings']>, config: Partial<IChart['config']> = {}, layout: Partial<IChart['layout']> = {}): IChart {+ return { visId: 'v', name: 'test', encodings: { ...emptyEncodings, ...encodings }, config: { ...emptyVisualConfig, ...config }, layout: { ...emptyVisualLayout, renderer: 'native', ...layout } };+}++/** The editor's local query, step by step, with the functions its workers run. */+export async function local(data: IRow[], workflow: IDataQueryWorkflowStep[], limit?: number): Promise<IRow[]> {+ let rows = data;+ for (const step of workflow) {+ if (step.type === 'filter') rows = filter(rows, step.filters);+ else if (step.type === 'transform') rows = rows.length ? await transformData(rows, step.transform) : rows;+ else if (step.type === 'view') for (const query of step.query) rows = queryView(rows, query);+ else if (step.type === 'sort') rows = sortBy(rows, step.by, step.sort);+ }+ return limit ? rows.slice(0, limit) : rows;+}++/**+ * What the native renderer does with a chart, up to the model it draws and the table it exports.+ * `host` stands for the computation a host gives the editor; every query is recorded as it is sent.+ */+export async function drawn(c: IChart, data: IRow[], host: (payload: IDataQueryPayload) => Promise<IRow[]> = (payload) => local(data, payload.workflow, payload.limit)) {+ const adapted = chartToWorksheet(c);+ if (!adapted.spec) throw new Error(adapted.error);+ const plan = compileWorksheet(adapted.spec);+ const fields = [...c.encodings.dimensions, ...c.encodings.measures];+ const around = splitWorkflow(toWorkflow(c.encodings.filters, fields, adapted.viewDimensions, adapted.viewMeasures, c.config.defaultAggregated, 'none', c.config.folds));+ const sent: IDataQueryPayload[] = [];+ const run: Computation = async (payload) => {+ const query = { workflow: composeWorkflow(around, c.config.defaultAggregated, payload), limit: payload.limit };+ sent.push(query);+ return host(query);+ };+ const results = await executePlan(plan, run);+ const model = buildModel(plan, results);+ return { plan, around, having: around.having, sent, model, marks: model.panes.flatMap((pane) => pane.records), csv: resultTables(plan, results).map(tableToCSV) };+}diff --git a/packages/graphic-walker/src/renderer/nativeHostExport.test.ts b/packages/graphic-walker/src/renderer/nativeHostExport.test.tsnew file mode 100644index 00000000..afd4f0b2--- /dev/null+++ b/packages/graphic-walker/src/renderer/nativeHostExport.test.ts@@ -0,0 +1,100 @@+import type { IGWHandlerInsider, IRenderStatus } from '../interfaces';+import { installNativeExport } from './nativeHostExport';+import type { NativeRendererHandle } from './nativeRegistry';++function host(initial: IRenderStatus = 'idle') {+ let status = initial;+ let listeners: ((status: IRenderStatus) => void)[] = [];+ const opened: number[] = [];+ const ctx = {+ get renderStatus() {+ return status;+ },+ onRenderStatusChange(cb: (status: IRenderStatus) => void) {+ listeners.push(cb);+ return () => {+ listeners = listeners.filter((which) => which !== cb);+ };+ },+ updateRenderStatus(next: IRenderStatus) {+ status = next;+ listeners.forEach((cb) => cb(next));+ },+ chartCount: 2,+ chartIndex: 1,+ // As the editor does it: the chart it shows is reported a moment after it was asked for.+ openChart(index: number) {+ opened.push(index);+ setTimeout(() => (ctx.chartIndex = index), 5);+ },+ exportChart: undefined as unknown,+ exportChartList: undefined as unknown,+ } as unknown as IGWHandlerInsider;+ return { ctx, opened, listening: () => listeners.length };+}+const handle: NativeRendererHandle = {+ exportSVG: async () => '<svg/>',+ exportPNG: async () => 'data:image/png;base64,AAAA',+ exportCSV: () => 'a,b',+ size: () => ({ width: 640, height: 320 }),+};+const source = (current: NativeRendererHandle | null = handle) => ({ handle: { current }, container: { current: null }, title: 'Sales' });++describe('installNativeExport', () => {+ test('exports the chart as one cell, as SVG or as a PNG data URL', async () => {+ const { ctx } = host();+ installNativeExport(ctx, source());+ const svg = await ctx.exportChart();+ expect(svg).toMatchObject({ mode: 'svg', title: 'Sales', nCols: 1, nRows: 1, combinedData: '<svg/>', chartType: 'worksheet' });+ expect(svg.charts).toMatchObject([{ rowIndex: 0, colIndex: 0, width: 640, height: 320, canvasWidth: 640, canvasHeight: 320, data: '<svg/>' }]);+ expect(svg.charts[0].canvas()).toBeNull();+ const png = await ctx.exportChart('data-url');+ expect(png.charts[0].data).toBe('data:image/png;base64,AAAA');+ });+ test('waits for a chart that is still loading and gives an empty result when it fails', async () => {+ const loading = host('computing');+ installNativeExport(loading.ctx, source());+ const pending = loading.ctx.exportChart();+ loading.ctx.updateRenderStatus('rendering');+ loading.ctx.updateRenderStatus('idle');+ expect((await pending).charts).toHaveLength(1);+ expect(loading.listening()).toBe(0);++ const errors = jest.spyOn(console, 'error').mockImplementation(() => undefined);+ const failing = host('computing');+ installNativeExport(failing.ctx, source());+ const failed = failing.ctx.exportChart();+ failing.ctx.updateRenderStatus('error');+ expect(await failed).toMatchObject({ charts: [], nCols: 0 });+ // Nothing to export from: an empty result, not a rejection.+ const unmounted = host();+ installNativeExport(unmounted.ctx, source(null));+ expect((await unmounted.ctx.exportChart()).charts).toEqual([]);+ errors.mockRestore();+ });+ test('the list opens every chart in turn and returns to the one that was open', async () => {+ const { ctx, opened } = host();+ installNativeExport(ctx, source());+ const results: unknown[] = [];+ for await (const item of ctx.exportChartList()) results.push([item.index, item.total, item.hasNext, item.data.charts.length]);+ expect(results).toEqual([+ [0, 2, true, 1],+ [1, 2, false, 1],+ ]);+ expect(opened).toEqual([0, 1, 1]);+ });+ test('uninstalling leaves a later renderer’s functions alone', async () => {+ const { ctx } = host();+ const uninstall = installNativeExport(ctx, source());+ const own = ctx.exportChart;+ uninstall();+ expect(ctx.exportChart).not.toBe(own);+ expect((await ctx.exportChart()).charts).toEqual([]);++ const again = installNativeExport(ctx, source());+ const later = (async () => ({ mode: 'svg', title: 'vega', nCols: 1, nRows: 1, charts: [], container: () => null })) as unknown as IGWHandlerInsider['exportChart'];+ ctx.exportChart = later;+ again();+ expect(ctx.exportChart).toBe(later);+ });+});diff --git a/packages/graphic-walker/src/renderer/nativeHostExport.ts b/packages/graphic-walker/src/renderer/nativeHostExport.tsnew file mode 100644index 00000000..10fe4e55--- /dev/null+++ b/packages/graphic-walker/src/renderer/nativeHostExport.ts@@ -0,0 +1,88 @@+import type { RefObject } from 'react';+import type { IChartExportResult, IGWHandlerInsider } from '../interfaces';+import type { NativeRendererHandle } from './nativeRegistry';++const empty = (mode: IChartExportResult['mode']): IChartExportResult => ({ mode, title: '', nCols: 0, nRows: 0, charts: [], chartType: 'worksheet', container: () => null });++/**+ * Gives the host's `exportChart` and `exportChartList` to the native renderer while it draws.+ * The Vega renderer installs its own on mount and removes them on unmount; this does the same,+ * so whichever renderer is on screen answers. A native chart is one image, reported as a+ * single cell. Returns the function that takes them out again.+ */+export function installNativeExport(+ ctx: IGWHandlerInsider,+ source: { handle: RefObject<NativeRendererHandle | null>; container: RefObject<HTMLDivElement | null>; title: string }+): () => void {+ // As for the Vega renderer: wait for a chart that is still loading, up to ten seconds.+ const settled = () =>+ new Promise<void>((resolve, reject) => {+ if (ctx.renderStatus === 'idle') return resolve();+ if (ctx.renderStatus === 'error') return reject(new Error('Error occurred when rendering chart'));+ const timer = setTimeout(() => finish(new Error('Timeout')), 10_000);+ const dispose = ctx.onRenderStatusChange((status) => {+ if (status === 'idle') finish();+ else if (status === 'error') finish(new Error('Error occurred when rendering chart'));+ });+ function finish(error?: Error) {+ clearTimeout(timer);+ dispose();+ if (error) reject(error);+ else resolve();+ }+ });+ const exportChart = async (mode: IChartExportResult['mode'] = 'svg'): Promise<IChartExportResult> => {+ try {+ await settled();+ const handle = source.handle.current;+ if (!handle) throw new Error('The chart is not drawn yet.');+ const { width, height } = handle.size();+ const data = mode === 'svg' ? await handle.exportSVG() : await handle.exportPNG();+ return {+ mode,+ title: source.title || 'untitled',+ combinedData: data,+ nCols: 1,+ nRows: 1,+ charts: [{ rowIndex: 0, colIndex: 0, width, height, canvasWidth: width, canvasHeight: height, data, canvas: () => source.container.current?.querySelector('canvas') ?? null }],+ container: () => source.container.current,+ chartType: 'worksheet',+ };+ } catch (error) {+ console.error('exportChart failed:', `${error}`);+ return empty(mode);+ }+ };+ // The editor reports the chart it shows once that chart is mounted. Two seconds is far more than that takes;+ // after it the export goes on and reports what it finds.+ const opened = async (index: number) => {+ const tick = () => new Promise<void>((resolve) => setTimeout(resolve, 0));+ const deadline = Date.now() + 2_000;+ await tick();+ while (ctx.chartIndex !== index && Date.now() < deadline) await tick();+ };+ const exportChartList = async function* (mode: IChartExportResult['mode'] = 'svg') {+ const total = ctx.chartCount;+ const current = ctx.chartIndex;+ for (let index = 0; index < total; index += 1) {+ ctx.openChart(index);+ // Wait until the editor shows that chart. By then whichever renderer draws it has put its own+ // exportChart in place and has said that it is at work, so the export waits for this chart+ // and not for the one that was on screen before.+ await opened(index);+ yield { mode, total, index, data: await ctx.exportChart(mode), hasNext: index < total - 1 };+ }+ ctx.openChart(current);+ };+ ctx.exportChart = exportChart as IGWHandlerInsider['exportChart'];+ ctx.exportChartList = exportChartList as IGWHandlerInsider['exportChartList'];+ return () => {+ // Only take out what is still ours; the next renderer may already have installed its own.+ if (ctx.exportChart === exportChart) ctx.exportChart = (async (mode: IChartExportResult['mode'] = 'svg') => empty(mode)) as IGWHandlerInsider['exportChart'];+ if (ctx.exportChartList === exportChartList) {+ ctx.exportChartList = async function* (mode: IChartExportResult['mode'] = 'svg') {+ yield { mode, total: 1, completed: 0, index: 0, data: empty(mode), hasNext: false };+ } as IGWHandlerInsider['exportChartList'];+ }+ };+}diff --git a/packages/graphic-walker/src/renderer/nativeRegistry.test.ts b/packages/graphic-walker/src/renderer/nativeRegistry.test.tsnew file mode 100644index 00000000..7d17f9f5--- /dev/null+++ b/packages/graphic-walker/src/renderer/nativeRegistry.test.ts@@ -0,0 +1,40 @@+// The registry is one per module instance, so each test loads its own.+function load() {+ let registry!: typeof import('./nativeRegistry');+ jest.isolateModules(() => {+ registry = require('./nativeRegistry');+ });+ return registry;+}+// What a component reading the registry would see. React is not needed for that: the hook reads this snapshot.+jest.mock('react', () => ({ useSyncExternalStore: (_subscribe: unknown, snapshot: () => unknown) => snapshot() }));+const renderer = { component: () => null, check: () => undefined };+const settle = () => new Promise<void>((resolve) => setTimeout(resolve, 0));++describe('native renderer registry', () => {+ test('there is no renderer and none on its way until a host says so', () => {+ const { useNativeRegistry, useNativeRenderer } = load();+ expect(useNativeRegistry()).toEqual({ loading: false });+ expect(useNativeRenderer()).toBeUndefined();+ });+ test('an announced renderer is loading until it registers', async () => {+ const { expectNativeRenderer, registerNativeRenderer, useNativeRegistry } = load();+ let arrive!: () => void;+ expectNativeRenderer(new Promise<void>((resolve) => (arrive = resolve)));+ expect(useNativeRegistry()).toEqual({ renderer: undefined, loading: true });+ registerNativeRenderer(renderer);+ expect(useNativeRegistry()).toEqual({ renderer, loading: false });+ arrive();+ await settle();+ expect(useNativeRegistry()).toEqual({ renderer, loading: false });+ });+ test('an announced renderer that fails to load, or loads without registering, is not waited for any longer', async () => {+ for (const arrival of [Promise.reject(new Error('network')), Promise.resolve()]) {+ const { expectNativeRenderer, useNativeRegistry } = load();+ expectNativeRenderer(arrival);+ expect(useNativeRegistry().loading).toBe(true);+ await settle();+ expect(useNativeRegistry()).toEqual({ renderer: undefined, loading: false });+ }+ });+});diff --git a/packages/graphic-walker/src/renderer/nativeRegistry.ts b/packages/graphic-walker/src/renderer/nativeRegistry.tsnew file mode 100644index 00000000..7cb882fa--- /dev/null+++ b/packages/graphic-walker/src/renderer/nativeRegistry.ts@@ -0,0 +1,154 @@+import { useSyncExternalStore, type ComponentType, type Ref } from 'react';+import type { IChart, IComputationFunction, IRenderStatus, IViewField } from '../interfaces';++/**+ * What the editor hands to the native worksheet renderer: the chart as stored, every+ * field of the dataset including computed ones, and the function that runs queries.+ * The renderer plans its own queries, so it gets no prepared view data.+ */+export interface NativeRendererProps {+ chart: IChart;+ fields: IViewField[];+ computation: IComputationFunction;+ /**+ * The chart colors the editor's other renderers would use for this chart: its theme preset+ * with the chart's own primary color and palette applied, for the current light or dark mode.+ */+ colors: NativeRendererColors;+ /** The editor's interface language, such as 'en-US' or 'zh-CN'. */+ locale: string;+ /**+ * Whether the whole chart is scaled into the box it is given, which the editor sizes. True for+ * the fixed and full layout modes. In the auto mode it is false: the value axes take the room+ * the box has, the steps of dimension members keep their size, and a chart that does not fit+ * scrolls inside the box.+ */+ fill: boolean;+ /**+ * Report that this chart could not be drawn after all, for a reason `check` could not see+ * in the chart alone, such as a query that fails or an expression the data source rejects.+ * The editor shows the reason in place of the chart and offers to try again. The chart and+ * its renderer stay as they are.+ */+ onError: (reason: string) => void;+ /** Where the renderer puts its export functions, for the toolbar's image and CSV buttons. */+ handle?: Ref<NativeRendererHandle>;+ /** Where the chart stands: querying, painting, done, or failed. Drives the loading layer and the host's render status. */+ onStatusChange?: (status: IRenderStatus) => void;+ /**+ * A mark was clicked. `mark` holds the value of every dimension that identifies it, by field id,+ * as stored in the data. The editor opens its menu at the event's position.+ */+ onMarkClick?: (mark: Record<string, unknown>, event: MouseEvent) => void;+}++/** Each function rejects or throws while the chart is still loading. */+export interface NativeRendererHandle {+ /** The whole chart as SVG text. */+ exportSVG(): Promise<string>;+ /** The whole chart as a PNG data URL. */+ exportPNG(): Promise<string>;+ /** The records behind the marks as comma-separated text with a header line. */+ exportCSV(): string;+ /** Size of the whole chart in CSS px. */+ size(): { width: number; height: number };+}++export interface NativeRendererColors {+ dark: boolean;+ /** Color of marks without a color field. */+ primary: string;+ /** Colors for the members of a dimension on color. */+ category: string[];+ /** Stops for a measure on color. */+ ramp: string[];+ /** Stops for a measure on color whose range crosses zero, when the theme has them. */+ diverging?: string[];+ /** Stops for heat map cells, when the theme has them. */+ heatmap?: string[];+ /** The chart's own background, when the user set one. */+ background?: string;+ /**+ * What the theme says about everything that is not a mark, each where the theme sets it:+ * header and legend text, axis labels, the borders between panes, grid lines.+ */+ text?: string;+ muted?: string;+ line?: string;+ grid?: string;+ /** The theme's settings that are not colors, each where the theme sets it. */+ style: {+ font?: string;+ /** Dash and gap of grid lines in px. */+ gridDash?: [number, number];+ /** Stroke width of line marks and of the outline of point marks, in px. */+ lineWidth?: number;+ pointStrokeWidth?: number;+ /** Point marks are drawn filled. */+ pointFilled?: boolean;+ /** Radius of the far end of bars, in px. */+ barRadius?: number;+ };+}++/** Why the native renderer does not draw a chart. */+export interface NativeUnsupported {+ /** For the person looking at the chart. It names the field, calculation or mark type in the way. */+ reason: string;+ /** The chart has nothing on its shelves to draw yet. That is not a fault, and the chart area stays blank. */+ empty?: boolean;+}++export interface NativeRenderer {+ component: ComponentType<NativeRendererProps>;+ /**+ * Whether the renderer can draw this chart: nothing when it can, the reason when it cannot.+ * The editor shows the reason in the chart area. It never gives the chart to another renderer.+ */+ check(chart: IChart): NativeUnsupported | undefined;+}++/**+ * The bundled worksheet renderer registers when the rendering entry point loads.+ * A chart that asks for it is drawn by it or not at all; custom hosts can also+ * announce loading or replace the registration explicitly.+ */+export interface NativeRegistry {+ renderer?: NativeRenderer;+ /** A renderer was announced with `expectNativeRenderer` and has not registered yet. */+ loading: boolean;+}+let registry: NativeRegistry = { loading: false };+let expected = 0;+const listeners = new Set<() => void>();+function update(next: NativeRegistry) {+ if (next.renderer === registry.renderer && next.loading === registry.loading) return;+ registry = next;+ listeners.forEach((listener) => listener());+}++export function registerNativeRenderer(renderer: NativeRenderer | undefined) {+ update({ renderer, loading: !renderer && expected > 0 });+}+/**+ * Says that a renderer is being fetched, so that charts which ask for it wait instead of+ * reporting that there is none. Waiting ends when it registers, or when `arrival` settles without it.+ */+export function expectNativeRenderer(arrival: Promise<unknown>) {+ expected += 1;+ update({ renderer: registry.renderer, loading: !registry.renderer });+ const settled = () => {+ expected -= 1;+ update({ renderer: registry.renderer, loading: !registry.renderer && expected > 0 });+ };+ arrival.then(settled, settled);+}+const subscribe = (listener: () => void) => {+ listeners.add(listener);+ return () => {+ listeners.delete(listener);+ };+};+const current = () => registry;+export const useNativeRegistry = () => useSyncExternalStore(subscribe, current, current);+export const useNativeRenderer = () => useNativeRegistry().renderer;diff --git a/packages/graphic-walker/src/renderer/pureRenderer.tsx b/packages/graphic-walker/src/renderer/pureRenderer.tsxindex a1395b51..68f95cc0 100644--- a/packages/graphic-walker/src/renderer/pureRenderer.tsx+++ b/packages/graphic-walker/src/renderer/pureRenderer.tsx@@ -1,4 +1,4 @@-import React, { useState, useEffect, forwardRef, useMemo, useRef } from 'react';+import React, { useState, useEffect, forwardRef, useMemo, useRef, useImperativeHandle } from 'react';import { unstable_batchedUpdates } from 'react-dom';import { observer } from 'mobx-react-lite';import { ShadowDom } from '../shadow-dom';@@ -16,6 +16,7 @@ import type {IVisualLayout,IChannelScales,IUIThemeConfig,+ IGWHandler,} from '../interfaces';import type { IReactVegaHandler } from '../vis/react-vega';import SpecRenderer from './specRenderer';@@ -26,6 +27,8 @@ import { GWGlobalConfig } from '../vis/theme';import { VizAppContext } from '../store/context';import { useCurrentMediaTheme } from '../utils/media';import LoadingLayer from '@/components/loadingLayer';+import { GraphicRenderer } from '../root';+import { emptyVisualConfig, emptyVisualLayout, download } from '../utils/save';type IPureRendererProps = {className?: string;@@ -69,7 +72,7 @@ export type ILocalPureRendererProps = IPureRendererProps & LocalProps & React.Re* Render a readonly chart with given visualization schema.* This is a pure component, which means it will not depend on any global state.*/-const PureRenderer = forwardRef<IReactVegaHandler, IPureRendererProps & (LocalProps | RemoteProps)>(function PureRenderer(props, ref) {+const LegacyPureRenderer = forwardRef<IReactVegaHandler, IPureRendererProps & (LocalProps | RemoteProps)>(function PureRenderer(props, ref) {const {name,className,@@ -204,6 +207,48 @@ const PureRenderer = forwardRef<IReactVegaHandler, IPureRendererProps & (LocalPr);});+const NativePureRenderer = forwardRef<IReactVegaHandler, IPureRendererProps & (LocalProps | RemoteProps)>(function NativePureRenderer(props, ref) {+ const host = useRef<IGWHandler>(null);+ const chart = useMemo(() => [{+ visId: 'pure-renderer', name: props.name ?? '', encodings: props.visualState,+ config: { ...emptyVisualConfig, ...props.visualConfig },+ layout: { ...emptyVisualLayout, ...(props.visualLayout ?? (props.visualConfig as IVisualConfig)), renderer: 'native' as const },+ }], [props.name, props.visualState, props.visualConfig, props.visualLayout]);+ useImperativeHandle(ref, () => {+ const image = async (mode: 'svg' | 'data-url', filename?: string) => {+ const result = await host.current?.exportChart(mode);+ const data = result?.combinedData ?? result?.charts[0]?.data;+ if (!data) return [];+ if (filename !== undefined) {+ if (mode === 'svg') download(data, `${filename}.svg`, 'image/svg+xml');+ else { const anchor = document.createElement('a'); anchor.href = data; anchor.download = `${filename}.png`; anchor.click(); }+ }+ return [data];+ };+ return {+ getSVGData: () => image('svg'), getCanvasData: () => image('data-url'),+ downloadSVG: (name = props.name ?? 'chart') => image('svg', name),+ downloadPNG: (name = props.name ?? 'chart') => image('data-url', name),+ };+ }, [props.name]);+ return <GraphicRenderer+ ref={host} chart={chart} fields={[...props.visualState.dimensions, ...props.visualState.measures]}+ {...(props.type === 'remote' ? { computation: props.computation } : { data: props.rawData })}+ className={props.className} appearance={props.appearance ?? props.dark}+ style={(props.overrideSize ?? chart[0].layout.size).mode === 'full' ? { width: '100%', height: '100%' } : undefined}+ uiTheme={props.uiTheme ?? props.colorConfig} vizThemeConfig={props.vizThemeConfig ?? props.themeConfig ?? props.themeKey}+ i18nLang={props.locale} overrideSize={props.overrideSize} scales={props.scales ?? props.channelScales}+ />;+});++const PureRenderer = forwardRef<IReactVegaHandler, IPureRendererProps & (LocalProps | RemoteProps)>(function PureRenderer(props, ref) {+ const layout = props.visualLayout ?? (props.visualConfig as IVisualConfig & { renderer?: IVisualLayout['renderer'] });+ const dedicated = props.visualConfig.coordSystem === 'geographic' || props.visualConfig.geoms[0] === 'table';+ return !dedicated && (layout.renderer ?? 'native') === 'native'+ ? <NativePureRenderer {...props} ref={ref} />+ : <LegacyPureRenderer {...props} ref={ref} />;+});+export default observer(withAppRoot<IPureRendererProps>(PureRenderer)) as {(p: ILocalPureRendererProps): React.ReactNode;(p: IRemotePureRendererProps): React.ReactNode;diff --git a/packages/graphic-walker/src/renderer/route.test.ts b/packages/graphic-walker/src/renderer/route.test.tsnew file mode 100644index 00000000..76efce06--- /dev/null+++ b/packages/graphic-walker/src/renderer/route.test.ts@@ -0,0 +1,70 @@+import type { IChart, IViewField } from '../interfaces';+import { emptyEncodings, emptyVisualConfig, emptyVisualLayout } from '../utils/save';+import type { NativeRegistry, NativeRenderer, NativeUnsupported } from './nativeRegistry';+import { routeChart } from './route';++const dim = (fid: string): IViewField => ({ fid, name: fid, semanticType: 'nominal', analyticType: 'dimension' });+const mea = (fid: string): IViewField => ({ fid, name: fid, semanticType: 'quantitative', analyticType: 'measure', aggName: 'sum' });+const renderers = ['vega-lite', 'observable-plot', 'native'] as const;+function chart(renderer: IChart['layout']['renderer'], encodings: Partial<IChart['encodings']> = {}, config: Partial<IChart['config']> = {}): IChart {+ return { visId: 'v', name: 'test', encodings: { ...emptyEncodings, rows: [dim('Region')], columns: [mea('Sales')], ...encodings }, config: { ...emptyVisualConfig, ...config }, layout: { ...emptyVisualLayout, renderer } };+}+/** A registry whose renderer answers every chart the same way, and counts how often it was asked. */+function registered(answer?: NativeUnsupported) {+ const asked: IChart[] = [];+ const renderer: NativeRenderer = { component: () => null, check: (c) => (asked.push(c), answer) };+ return { registry: { renderer, loading: false } as NativeRegistry, asked };+}+const absent: NativeRegistry = { loading: false };+const threeLevels = { rows: [dim('Region'), dim('Category'), dim('Subcategory')] };++describe('routeChart', () => {+ test('a map goes to the map component under every renderer setting, registered or not', () => {+ const refusing = registered({ reason: 'never' });+ for (const renderer of renderers) {+ for (const registry of [absent, { loading: true }, refusing.registry]) {+ expect(routeChart(chart(renderer, {}, { coordSystem: 'geographic', geoms: ['poi'] }), registry)).toEqual({ to: 'dedicated', kind: 'map' });+ }+ }+ // The worksheet renderer is not asked about a chart that is not its to draw.+ expect(refusing.asked).toEqual([]);+ });+ test('a table goes to the table component under every renderer setting, with any number of levels', () => {+ for (const renderer of renderers) {+ expect(routeChart(chart(renderer, threeLevels, { geoms: ['table'] }), absent)).toEqual({ to: 'dedicated', kind: 'table' });+ }+ });+ test('an ordinary chart goes to the renderer it names, and to Worksheet where it names none', () => {+ const { registry, asked } = registered();+ expect(routeChart(chart(undefined), registry)).toEqual({ to: 'native' });+ expect(routeChart(chart('vega-lite'), registry)).toEqual({ to: 'classic' });+ expect(routeChart(chart('observable-plot'), registry)).toEqual({ to: 'classic' });+ expect(asked).toHaveLength(1);+ expect(routeChart(chart('native'), registry)).toEqual({ to: 'native' });+ expect(asked.length).toBe(2);+ });+ test('a chart the worksheet renderer cannot draw is not drawn by another renderer', () => {+ const route = routeChart(chart('native'), registered({ reason: 'Bar marks need one measure axis.' }).registry);+ expect(route).toEqual({ to: 'notice', notice: { state: 'unsupported', reason: 'Bar marks need one measure axis.' } });+ // Nothing on the shelves yet is not a fault: the area stays blank.+ expect(routeChart(chart('native'), registered({ reason: 'There is nothing to draw yet.', empty: true }).registry)).toEqual({ to: 'blank' });+ });+ test('a chart that asks for the worksheet renderer waits for it, and says so where there is none', () => {+ expect(routeChart(chart('native'), { loading: true })).toEqual({ to: 'notice', notice: { state: 'loading' } });+ expect(routeChart(chart('native'), absent)).toEqual({ to: 'notice', notice: { state: 'unavailable' } });+ // Also with a chart the other renderers could draw as it is.+ expect(routeChart(chart('native', { rows: [dim('Region')] }), absent).to).toBe('notice');+ });+ test('Vega-Lite and Observable Plot do not draw a shelf with more dimensions than they show', () => {+ for (const renderer of ['vega-lite', 'observable-plot'] as const) {+ expect(routeChart(chart(renderer, threeLevels), absent)).toEqual({+ to: 'notice',+ notice: { state: 'levels', renderer: renderer ?? 'vega-lite', shelves: [{ shelf: 'rows', fields: ['Region', 'Category', 'Subcategory'] }] },+ });+ }+ const both = routeChart(chart('vega-lite', { ...threeLevels, columns: [dim('Year'), dim('Quarter'), dim('Month'), mea('Sales')] }), absent);+ expect(both).toMatchObject({ notice: { shelves: [{ shelf: 'rows' }, { shelf: 'columns', fields: ['Year', 'Quarter', 'Month'] }] } });+ // Two dimensions on a shelf is what the editor allows for these renderers; measures do not count.+ expect(routeChart(chart('vega-lite', { rows: [dim('Region'), dim('Category'), mea('Profit'), mea('Cost')] }), absent)).toEqual({ to: 'classic' });+ });+});diff --git a/packages/graphic-walker/src/renderer/route.ts b/packages/graphic-walker/src/renderer/route.tsnew file mode 100644index 00000000..57b0a636--- /dev/null+++ b/packages/graphic-walker/src/renderer/route.ts@@ -0,0 +1,57 @@+import type { IChart } from '../interfaces';+import { CLASSIC_CROSS_LIMIT } from '../lib/gog';+import type { NativeRegistry } from './nativeRegistry';++/** A shelf that holds more dimensions than the chart's renderer shows. */+export interface ShelfOverflow {+ shelf: 'rows' | 'columns';+ fields: string[];+}++/**+ * What the chart area says in place of a chart it does not draw.+ * - loading: the worksheet renderer is being fetched.+ * - unavailable: the chart asks for the worksheet renderer and this environment has none.+ * - unsupported: the worksheet renderer cannot draw the chart; `reason` says what is in the way.+ * - failed: a query or the drawing went wrong; `reason` is the error.+ * - levels: the chart has more dimensions on a shelf than its renderer shows.+ */+export type ChartNoticeContent =+ | { state: 'loading' | 'unavailable' }+ | { state: 'unsupported' | 'failed'; reason: string }+ | { state: 'levels'; renderer: 'vega-lite' | 'observable-plot'; shelves: ShelfOverflow[] };++/**+ * Where a chart is drawn.+ * - dedicated: maps and tables have components of their own, whichever renderer draws ordinary charts.+ * - classic: Vega-Lite or Observable Plot, as the chart says.+ * - native: the worksheet renderer.+ * - blank: the worksheet renderer, with nothing on the shelves to draw yet.+ * - notice: nowhere. The chart area says why.+ */+export type ChartRoute = { to: 'dedicated'; kind: 'table' | 'map' } | { to: 'classic' } | { to: 'native' } | { to: 'blank' } | { to: 'notice'; notice: ChartNoticeContent };++/**+ * Picks the component that draws a chart. The kind of chart comes first: a table or a map goes to+ * its own component and the chart's renderer setting is not looked at. An ordinary chart goes to+ * the renderer it names, Worksheet where it names none. A renderer that cannot draw the chart is+ * never replaced by another one; the chart area says what is wrong and the chart stays as saved.+ */+export function routeChart(chart: IChart, registry: NativeRegistry): ChartRoute {+ if (chart.config.geoms[0] === 'table') return { to: 'dedicated', kind: 'table' };+ if (chart.config.coordSystem === 'geographic') return { to: 'dedicated', kind: 'map' };+ const renderer = chart.layout.renderer ?? 'native';+ if (renderer === 'native') {+ if (!registry.renderer) return { to: 'notice', notice: { state: registry.loading ? 'loading' : 'unavailable' } };+ const cannot = registry.renderer.check(chart);+ if (!cannot) return { to: 'native' };+ return cannot.empty ? { to: 'blank' } : { to: 'notice', notice: { state: 'unsupported', reason: cannot.reason } };+ }+ // The editor keeps these shelves within the limit while one of these renderers is chosen. A chart+ // built under the worksheet renderer can hold more, and would be drawn here with levels left out.+ const shelves = (['rows', 'columns'] as const)+ .map((shelf) => ({ shelf, fields: chart.encodings[shelf].filter((f) => f.analyticType === 'dimension').map((f) => f.name) }))+ .filter((held) => held.fields.length > CLASSIC_CROSS_LIMIT);+ if (shelves.length) return { to: 'notice', notice: { state: 'levels', renderer, shelves } };+ return { to: 'classic' };+}diff --git a/packages/graphic-walker/src/renderer/specRenderer.tsx b/packages/graphic-walker/src/renderer/specRenderer.tsxindex cd979aae..ae2643e2 100644--- a/packages/graphic-walker/src/renderer/specRenderer.tsx+++ b/packages/graphic-walker/src/renderer/specRenderer.tsx@@ -1,5 +1,5 @@import { Resizable } from 're-resizable';-import React, { forwardRef, useMemo, useContext } from 'react';+import React, { forwardRef, useMemo, useContext, useState, useEffect } from 'react';import { PivotTableCore } from '../components/pivotTable';import LeafletRenderer, { LEAFLET_DEFAULT_HEIGHT, LEAFLET_DEFAULT_WIDTH } from '../components/leafletRenderer';@@ -12,6 +12,7 @@ import { parseColorToHex } from '@/utils/colors';import ObservablePlotRenderer from '@/vis/observable-plot-renderer';import { useCompututaion } from '@/store';import { useAppRootContext } from '@/components/appRoot';+import ChartNotice from './chartNotice';interface SpecRendererProps {name?: string;@@ -70,6 +71,8 @@ const SpecRenderer = forwardRef<IReactVegaHandler, SpecRendererProps>(function (const format = _format;const isPivotTable = geoms[0] === 'table';+ // Why the table could not be built, shown in its place. Without this a failed table is a blank area.+ const [tableError, setTableError] = useState('');const computation = useCompututaion();const appRootRef = useAppRootContext();@@ -117,6 +120,13 @@ const SpecRenderer = forwardRef<IReactVegaHandler, SpecRendererProps>(function (return config;}, [themeConfig, mediaTheme, zeroScale, resolve, background, format.normalizedNumberFormat, format.numberFormat, format.timeFormat]);+ // An ordinary chart set to the worksheet renderer, in a place that only has the renderers below.+ const nativeMissing = !isPivotTable && coordSystem !== 'geographic' && layout.renderer === 'native';+ useEffect(() => {+ // Nothing is drawn, so the host must not take the chart for a finished one.+ if (nativeMissing) appRootRef.current?.updateRenderStatus('error');+ }, [nativeMissing, data, appRootRef]);+if (isPivotTable) {return (<PivotTableCore@@ -133,8 +143,21 @@ const SpecRenderer = forwardRef<IReactVegaHandler, SpecRendererProps>(function (showTableSummary={layout.showTableSummary}numberFormat={layout.format.numberFormat}disableCollapse={disableCollapse}- onRenderStatusChange={(status) => appRootRef.current?.updateRenderStatus(status)}- onError={(error) => console.error(error)}+ onRenderStatusChange={(status) => {+ if (status === 'computing') setTableError('');+ appRootRef.current?.updateRenderStatus(status);+ }}+ onError={(error) => {+ console.error(error);+ setTableError(error.message);+ }}+ emptyContent={+ tableError ? (+ <div role="alert" className="p-4 text-sm text-muted-foreground" data-testid="pivot-table-error">+ {tableError}+ </div>+ ) : null+ }/>);}@@ -194,7 +217,9 @@ const SpecRenderer = forwardRef<IReactVegaHandler, SpecRendererProps>(function (scale={scale}/>)}- {!isSpatial && (!layout.renderer || layout.renderer === 'vega-lite') && (+ {/* The worksheet renderer is mounted by the editor's renderer switch, not here. A chart that asks for it is not drawn by another renderer in its place. */}+ {nativeMissing && <ChartNotice notice={{ state: 'unavailable' }} />}+ {!isSpatial && layout.renderer !== 'observable-plot' && layout.renderer !== 'native' && (<ReactVeganame={name}vegaConfig={vegaConfig}diff --git a/packages/graphic-walker/src/store/index.tsx b/packages/graphic-walker/src/store/index.tsxindex 23fd7c31..67035adc 100644--- a/packages/graphic-walker/src/store/index.tsx+++ b/packages/graphic-walker/src/store/index.tsx@@ -40,7 +40,7 @@ interface VizStoreWrapperProps {defaultConfig?: IDefaultConfig;defaultUIConfig?: IDefaultUIConfig;defaultTab?: 'data' | 'visualization';- defaultRenderer?: 'vega-lite' | 'observable-plot';+ defaultRenderer?: 'vega-lite' | 'observable-plot' | 'native';}export const VizStoreWrapper = (props: VizStoreWrapperProps) => {diff --git a/packages/graphic-walker/src/utils/save.ts b/packages/graphic-walker/src/utils/save.tsindex 4acb1751..73b4e843 100644--- a/packages/graphic-walker/src/utils/save.ts+++ b/packages/graphic-walker/src/utils/save.ts@@ -92,7 +92,7 @@ export const emptyVisualLayout: IVisualLayout = {shape: false,size: false,},- renderer: 'vega-lite',+ renderer: 'native',};export const emptyVisualConfig: IVisualConfigNew = {diff --git a/packages/graphic-walker/src/utils/useTheme.ts b/packages/graphic-walker/src/utils/useTheme.tsindex 05eb9635..c4f29fca 100644--- a/packages/graphic-walker/src/utils/useTheme.ts+++ b/packages/graphic-walker/src/utils/useTheme.ts@@ -67,5 +67,8 @@ export function getColor(theme: VegaGlobalConfig) {primaryColor,nominalPalette,quantitativePalette,+ /** Undefined where the theme sets none; the renderer then keeps its own. */+ divergingPalette: parsePalette(theme.range?.diverging),+ heatmapPalette: parsePalette(theme.range?.heatmap),};}diff --git a/packages/graphic-walker/src/utils/workflow.test.ts b/packages/graphic-walker/src/utils/workflow.test.tsnew file mode 100644index 00000000..fd7e5fca--- /dev/null+++ b/packages/graphic-walker/src/utils/workflow.test.ts@@ -0,0 +1,40 @@+import type { IViewField } from '../interfaces';+import { walkFid } from '../lib/sql';+import { toWorkflow } from './workflow';++const dim = (fid: string): IViewField => ({ fid, name: fid, semanticType: 'nominal', analyticType: 'dimension' });+const mea = (fid: string): IViewField => ({ fid, name: fid, semanticType: 'quantitative', analyticType: 'measure', aggName: 'sum' });+const calc = (fid: string, name: string, sql: string, aggName: string): IViewField => ({+ fid, name, semanticType: 'quantitative', analyticType: 'measure', computed: true, aggName,+ expression: { op: 'expr', as: fid, params: [{ type: 'sql', value: sql }] },+});++describe('fields an expression reads', () => {+ test('are found inside function calls and branches, and the star of count(*) is not one', () => {+ expect(walkFid('sum(a) / sum("B")').sort()).toEqual(['B', 'a']);+ expect(walkFid('case when a > 1 then round(b, 2) else c end').sort()).toEqual(['a', 'b', 'c']);+ expect(walkFid('count(*)')).toEqual([]);+ expect(walkFid('a + 1')).toEqual(['a']);+ });+});++describe('toWorkflow with aggregate expressions', () => {+ const margin = calc('f_margin', 'Margin', 'Sales - Cost', 'sum');+ const logged = calc('f_logged', 'Logged', 'ln(Margin)', 'sum');+ const rate = calc('f_rate', 'Rate', 'sum(Margin) / sum(Sales)', 'expr');+ const fields = [dim('Region'), mea('Sales'), mea('Cost'), margin, logged, rate];++ test('a computed field that only an aggregate expression reads is computed before the grouping', () => {+ const steps = toWorkflow([], fields, [dim('Region')], [rate], true, 'none');+ expect(steps.map((step) => step.type)).toEqual(['transform', 'view']);+ expect(steps[0]).toMatchObject({ transform: [{ key: 'f_margin' }] });+ expect(steps[1]).toMatchObject({ query: [{ op: 'aggregate', groupBy: ['Region'], measures: [{ field: '((sum (f_margin) ) / (sum ("Sales") ))', agg: 'expr', asFieldKey: 'f_rate' }] }] });+ });+ test('a computed field that reads another one through a function comes after it', () => {+ const steps = toWorkflow([], fields, [dim('Region')], [logged], true, 'none');+ expect(steps[0]).toMatchObject({ type: 'transform', transform: [{ key: 'f_margin' }, { key: 'f_logged' }] });+ });+ test('a chart without computed fields has no transform step', () => {+ expect(toWorkflow([], fields, [dim('Region')], [mea('Sales')], true, 'none').map((step) => step.type)).toEqual(['view']);+ });+});diff --git a/packages/graphic-walker/src/utils/workflow.ts b/packages/graphic-walker/src/utils/workflow.tsindex d227f00e..96860a44 100644--- a/packages/graphic-walker/src/utils/workflow.ts+++ b/packages/graphic-walker/src/utils/workflow.ts@@ -173,6 +173,22 @@ export const toWorkflow = (};}+ // Computed fields that are aggregates themselves, such as sum(a) / sum(b). They are worked out in the view step.+ const aggergatedComputed = treeShake(+ allFields+ .filter((f) => f.computed && f.expression && f.expression.op === 'expr' && f.aggName === 'expr')+ .map((f) => {+ return {+ key: f.fid,+ expression: processExpression(f.expression!, allFields, { timezoneDisplayOffset }),+ };+ }),+ [...viewKeys]+ );+ // A field such an aggregate reads may be computed row by row, and then has to exist before the view step.+ const aggregatedInputs = new Set<string>();+ for (const f of aggergatedComputed) walkExpression(f.expression, (field) => aggregatedInputs.add(field));+// Second, to transform the data by rows 1 by 1const computedFields = treeShake(allFields@@ -183,7 +199,7 @@ export const toWorkflow = (expression: processExpression(f.expression!, allFields, { timezoneDisplayOffset }),};}),- [...viewKeys]+ [...viewKeys, ...aggregatedInputs]);if (computedFields.length) {transformWorkflow = {@@ -206,17 +222,6 @@ export const toWorkflow = (// 1. If any of the measures is aggregated, then we apply the aggregation// 2. If there's no measure in the view, then we apply the aggregationconst aggergatedFilter = viewFilters.filter((f) => f.enableAgg && f.aggName && f.rule);- const aggergatedComputed = treeShake(- allFields- .filter((f) => f.computed && f.expression && f.expression.op === 'expr' && f.aggName === 'expr')- .map((f) => {- return {- key: f.fid,- expression: processExpression(f.expression!, allFields, { timezoneDisplayOffset }),- };- }),- [...viewKeys]- );const aggregateOn = viewMeasures.filter((f) => f.aggName).map((f) => [f.fid, f.aggName as string])diff --git a/packages/graphic-walker/tests/e2e/native-renderer.fixture.tsx b/packages/graphic-walker/tests/e2e/native-renderer.fixture.tsxnew file mode 100644index 00000000..017d7fca--- /dev/null+++ b/packages/graphic-walker/tests/e2e/native-renderer.fixture.tsx@@ -0,0 +1,161 @@+import React from 'react';+import { createRoot } from 'react-dom/client';+import PureRenderer from '../../src/renderer/pureRenderer';+import type { IReactVegaHandler } from '../../src/vis/react-vega';+import { GraphicWalker } from '../../src/root';+import { getComputation } from '../../src/computation/clientComputation';+import { expectNativeRenderer, registerNativeRenderer } from '../../src/renderer/nativeRegistry';+import { worksheetRenderer } from '../../src/renderer/native';+import { emptyEncodings, emptyVisualConfig, emptyVisualLayout } from '../../src/utils/save';+import type { IChart, IChartExportResult, IDataQueryPayload, IGWHandler, IRow, IViewField } from '../../src/interfaces';+import type { VizSpecStore } from '../../src/store/visualSpecStore';++/**+ * The editor with a data source the tests control and, as the query asks, with or without the+ * worksheet renderer:+ * ?native=on it is bundled, as in the published package+ * ?native=slow it is announced and arrives when the test calls arrive()+ * ?native=fail it is announced and its code never loads+ * ?native=off nobody mentions it, as in a host that does not have it+ */+export interface ChartRequest {+ name: string;+ renderer?: IChart['layout']['renderer'];+ rows?: string[];+ columns?: string[];+ geom?: string;+ map?: boolean;+}+export interface RendererFixture {+ load(charts: ChartRequest[]): void;+ /** The charts as the editor would save them. */+ saved(): IChart[];+ setRenderer(renderer: NonNullable<IChart['layout']['renderer']>): void;+ setMap(on: boolean): void;+ setGeom(geom: string): void;+ /** Lets the worksheet renderer through, under ?native=slow. */+ arrive(): void;+ /** Makes every query fail from now on, or work again. */+ failQueries(on: boolean): void;+ queries(): IDataQueryPayload[];+ host: {+ status(): string;+ chartCount(): number;+ chartIndex(): number;+ openChart(index: number): void;+ exportChart(): Promise<{ title: string; chartType?: string; images: number; data: string }>;+ exportChartList(): Promise<{ index: number; title: string; chartType?: string; images: number }[]>;+ };+}+declare global {+ interface Window {+ gw: RendererFixture;+ pureExport(): Promise<string[]>;+ }+}++const dimension = (fid: string, extra: Partial<IViewField> = {}): IViewField => ({ fid, name: fid, semanticType: 'nominal', analyticType: 'dimension', ...extra });+const measure = (fid: string): IViewField => ({ fid, name: fid, semanticType: 'quantitative', analyticType: 'measure', aggName: 'sum' });+const ratio: IViewField = {+ fid: 'f_ratio', name: 'Ratio', semanticType: 'quantitative', analyticType: 'measure', aggName: 'expr', computed: true,+ expression: { op: 'expr', as: 'f_ratio', params: [{ type: 'sql', value: 'sum(Sales) / sum(Cost)' }] },+};+const dimensions = [dimension('Region'), dimension('Category'), dimension('Subcategory'), dimension('Lat', { semanticType: 'quantitative' }), dimension('Lon', { semanticType: 'quantitative' })];+const measures = [measure('Sales'), measure('Cost'), ratio];+const byId = new Map([...dimensions, ...measures].map((f) => [f.fid, f]));+// East and West hold members of the same name. Each row is a place, so the map has seven points.+const data: IRow[] = [+ { Region: 'East', Category: 'A', Subcategory: 'a1', Sales: 10, Cost: 1, Lat: 40.7, Lon: -74.0 },+ { Region: 'East', Category: 'A', Subcategory: 'a1', Sales: 20, Cost: 9, Lat: 42.4, Lon: -71.1 },+ { Region: 'East', Category: 'A', Subcategory: 'a2', Sales: 8, Cost: 4, Lat: 39.9, Lon: -75.2 },+ { Region: 'East', Category: 'B', Subcategory: 'b1', Sales: 9, Cost: 3, Lat: 38.9, Lon: -77.0 },+ { Region: 'West', Category: 'A', Subcategory: 'a1', Sales: 6, Cost: 12, Lat: 37.8, Lon: -122.4 },+ { Region: 'West', Category: 'A', Subcategory: 'a2', Sales: 15, Cost: 5, Lat: 34.1, Lon: -118.2 },+ { Region: 'West', Category: 'B', Subcategory: 'b1', Sales: 7, Cost: 2, Lat: 47.6, Lon: -122.3 },+];++function chartOf(request: ChartRequest, index: number): IChart {+ const pick = (ids: string[] = []) => ids.map((id) => byId.get(id)!);+ return {+ visId: `chart-${index}`,+ name: request.name,+ encodings: {+ // Every chart knows where its rows are, so that any of them can be turned into a map and back.+ ...emptyEncodings, dimensions, measures, rows: pick(request.rows), columns: pick(request.columns), latitude: pick(['Lat']), longitude: pick(['Lon']),+ },+ config: { ...emptyVisualConfig, geoms: [request.geom ?? (request.map ? 'poi' : 'auto')], coordSystem: request.map ? 'geographic' : 'generic' },+ // Map tiles are asked of this server, which has none. What is checked is the map itself, not a tile service.+ layout: { ...emptyVisualLayout, geoMapTileUrl: '/tests/e2e/no-tiles/{z}/{x}/{y}.png', ...(request.renderer ? { renderer: request.renderer } : {}) },+ };+}++const params = new URLSearchParams(window.location.search);+const pure = params.has('pure');+const mode = params.get('native') ?? 'on';+registerNativeRenderer(mode === 'on' ? worksheetRenderer : undefined);+const preview = async () => { registerNativeRenderer(worksheetRenderer); };+let arrive = () => {};+if (mode === 'on') expectNativeRenderer(preview());+else if (mode === 'slow') expectNativeRenderer(new Promise<void>((resolve) => (arrive = resolve)).then(preview));+else if (mode === 'fail') expectNativeRenderer(Promise.reject(new Error('The preview could not be fetched.')));++const local = getComputation(data);+const queries: IDataQueryPayload[] = [];+let failing = false;+const computation = async (payload: IDataQueryPayload) => {+ queries.push(JSON.parse(JSON.stringify(payload)));+ if (failing) throw new Error('The data source is offline.');+ return local(payload);+};++const storeRef = React.createRef<VizSpecStore>();+const hostRef = React.createRef<IGWHandler>();+const store = () => {+ if (!storeRef.current) throw new Error('The editor is not mounted yet.');+ return storeRef.current;+};+const host = () => {+ if (!hostRef.current) throw new Error('The editor is not mounted yet.');+ return hostRef.current;+};+const told = (result: IChartExportResult) => ({ title: result.title, chartType: result.chartType, images: result.charts.length, data: result.charts[0]?.data ?? '' });++window.gw = {+ load: (charts) => store().importCode(charts.map(chartOf)),+ saved: () => JSON.parse(JSON.stringify(store().exportCode())),+ setRenderer: (renderer) => store().setVisualLayout('renderer', renderer),+ setMap: (on) => store().setCoordSystem(on ? 'geographic' : 'generic'),+ setGeom: (geom) => store().setVisualConfig('geoms', [geom]),+ arrive: () => arrive(),+ failQueries: (on) => void (failing = on),+ queries: () => queries,+ host: {+ status: () => host().renderStatus,+ chartCount: () => host().chartCount,+ chartIndex: () => host().chartIndex,+ openChart: (index) => host().openChart(index),+ exportChart: async () => told(await host().exportChart('svg')),+ exportChartList: async () => {+ const list: { index: number; title: string; chartType?: string; images: number }[] = [];+ for await (const item of host().exportChartList('svg')) {+ const { title, chartType, images } = told(item.data);+ list.push({ index: item.index, title, chartType, images });+ }+ return list;+ },+ },+};++const pureRef = React.createRef<IReactVegaHandler>();+const pureChart = chartOf({ name: 'Default worksheet', rows: ['Region', 'Category', 'Subcategory'], columns: ['Sales'] }, 0);+window.pureExport = () => pureRef.current!.getSVGData();++createRoot(document.getElementById('root')!).render(+ pure ? <PureRenderer ref={pureRef} rawData={data} visualState={pureChart.encodings} visualConfig={pureChart.config} /> : <GraphicWalker ref={hostRef} storeRef={storeRef} fields={[...dimensions, ...measures]} computation={computation} appearance="light" style={{ width: '100%', height: '100%' }} />+);++function ready() {+ if (pure ? !pureRef.current : !storeRef.current || !hostRef.current) return void requestAnimationFrame(ready);+ document.body.dataset.fixtureReady = 'true';+}+requestAnimationFrame(ready);diff --git a/packages/graphic-walker/tests/e2e/native-renderer.html b/packages/graphic-walker/tests/e2e/native-renderer.htmlnew file mode 100644index 00000000..025db24c--- /dev/null+++ b/packages/graphic-walker/tests/e2e/native-renderer.html@@ -0,0 +1,26 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>Renderer routing fixture</title>+ <style>+ html,+ body {+ margin: 0;+ height: 100%;+ font-family: sans-serif;+ }++ #root {+ display: flex;+ width: 100vw;+ height: 100vh;+ }+ </style>+ </head>+ <body>+ <div id="root"></div>+ <script type="module" src="./native-renderer.fixture.tsx"></script>+ </body>+</html>diff --git a/packages/graphic-walker/tests/e2e/renderer-routing.spec.ts b/packages/graphic-walker/tests/e2e/renderer-routing.spec.tsnew file mode 100644index 00000000..a6506c55--- /dev/null+++ b/packages/graphic-walker/tests/e2e/renderer-routing.spec.ts@@ -0,0 +1,260 @@+import { expect, test, type Page } from '@playwright/test';+import type { ChartRequest } from './native-renderer.fixture';++// How a chart finds its renderer, in the mounted editor: an ordinary chart is drawn by the renderer it+// names or not at all, maps and tables keep their own components, and the host is told the truth.++type Native = 'on' | 'slow' | 'fail' | 'off';+const bars: ChartRequest = { name: 'Bars', renderer: 'native', rows: ['Region'], columns: ['Sales'] };+const levels: ChartRequest = { name: 'Levels', renderer: 'native', rows: ['Region', 'Category', 'Subcategory'], columns: ['f_ratio'] };+const betweenMeasures: ChartRequest = { name: 'Between measures', renderer: 'native', geom: 'bar', rows: ['Sales'], columns: ['Cost'] };+const renderers = ['vega-lite', 'observable-plot', 'native'] as const;++async function open(page: Page, native: Native, charts: ChartRequest[]) {+ await page.goto(`/tests/e2e/native-renderer.html?native=${native}`);+ await expect(page.locator('body')).toHaveAttribute('data-fixture-ready', 'true');+ await page.evaluate((list) => window.gw.load(list), charts);+}+const sheet = (page: Page) => page.getByTestId('worksheet-scroll');+const notice = (page: Page) => page.getByTestId('chart-notice');+const vega = (page: Page) => page.locator('.vega-embed');+const plot = (page: Page) => page.locator('svg[class^="plot-"], figure[class^="plot-"]');+const map = (page: Page) => page.locator('.leaflet-container');+const status = (page: Page) => page.evaluate(() => window.gw.host.status());+const saved = (page: Page) => page.evaluate(() => window.gw.saved());+const shelves = (chart: Awaited<ReturnType<typeof saved>>[number]) => ({ rows: chart.encodings.rows.map((f) => f.fid), columns: chart.encodings.columns.map((f) => f.fid) });+/** The editor reports every failed query in a dialog of its own, over the chart area. */+async function dismissErrorDialog(page: Page) {+ const dialog = page.getByRole('dialog').filter({ hasText: 'Computation service' });+ await expect(dialog).toBeVisible();+ await dialog.getByRole('button', { name: 'Close' }).first().click();+ await expect(dialog).toHaveCount(0);+}+/** No renderer other than the notice has anything on screen. */+async function nothingDrawn(page: Page) {+ await expect(sheet(page)).toHaveCount(0);+ await expect(vega(page)).toHaveCount(0);+ await expect(plot(page)).toHaveCount(0);+ await expect(map(page)).toHaveCount(0);+}++test('R1: a chart the worksheet renderer cannot draw says why and is not drawn by another renderer', async ({ page }) => {+ await open(page, 'on', [betweenMeasures]);+ await expect(notice(page)).toHaveAttribute('data-state', 'unsupported');+ await expect(page.getByTestId('chart-notice-reason')).toContainText('Bar marks need one measure axis');+ await nothingDrawn(page);+ const [chart] = await saved(page);+ expect(chart.layout.renderer).toBe('native');+ expect(chart.config.geoms).toEqual(['bar']);+ expect(shelves(chart)).toEqual({ rows: ['Sales'], columns: ['Cost'] });+ await expect.poll(() => status(page)).toBe('error');+ expect(await page.evaluate(() => window.gw.host.exportChart())).toMatchObject({ images: 0 });+ // The same shelves under a mark type it draws: the notice goes and the sheet comes, with no reload.+ await page.evaluate(() => window.gw.setGeom('point'));+ await expect(sheet(page)).toBeVisible();+ await expect(notice(page)).toHaveCount(0);+ await expect.poll(() => status(page)).toBe('idle');+});++test('R2: a failed query shows the error, no other renderer takes over, and trying again or changing the chart recovers', async ({ page }) => {+ await open(page, 'on', [bars, { ...bars, name: 'By category', rows: ['Category'] }]);+ await expect(sheet(page)).toBeVisible();+ await expect.poll(() => status(page)).toBe('idle');+ const first = await page.evaluate(() => window.gw.host.exportChart());+ expect(first).toMatchObject({ title: 'Bars', chartType: 'worksheet', images: 1 });+ expect(first.data).toContain('<svg');++ // The second chart is opened while the data source is down.+ await page.evaluate(() => { window.gw.failQueries(true); window.gw.host.openChart(1); });+ await expect(notice(page)).toHaveAttribute('data-state', 'failed');+ await expect(page.getByTestId('chart-notice-reason')).toHaveText('The data source is offline.');+ await nothingDrawn(page);+ await expect.poll(() => status(page)).toBe('error');+ // The host gets no image, in particular not the one of the chart drawn before.+ expect(await page.evaluate(() => window.gw.host.exportChart())).toMatchObject({ images: 0, data: '' });+ let [, chart] = await saved(page);+ expect(chart.layout.renderer).toBe('native');+ expect(shelves(chart)).toEqual({ rows: ['Category'], columns: ['Sales'] });+ // Trying again while it is still down fails again, in the same place.+ await dismissErrorDialog(page);+ await page.getByTestId('chart-notice-retry').click();+ await dismissErrorDialog(page);+ await expect(notice(page)).toHaveAttribute('data-state', 'failed');+ await nothingDrawn(page);++ await page.evaluate(() => window.gw.failQueries(false));+ await page.getByTestId('chart-notice-retry').click();+ await expect(sheet(page)).toBeVisible();+ await expect(notice(page)).toHaveCount(0);+ await expect.poll(() => status(page)).toBe('idle');+ expect(await page.evaluate(() => window.gw.host.exportChart())).toMatchObject({ title: 'By category', chartType: 'worksheet', images: 1 });++ // A failure also clears when the chart itself is changed.+ await page.evaluate(() => { window.gw.failQueries(true); window.gw.load([{ name: 'Costs', renderer: 'native', rows: ['Region'], columns: ['Cost'] }]); });+ await expect(notice(page)).toHaveAttribute('data-state', 'failed');+ await dismissErrorDialog(page);+ await page.evaluate(() => { window.gw.failQueries(false); window.gw.setGeom('point'); });+ await expect(sheet(page)).toBeVisible();+ [chart] = await saved(page);+ expect(chart.layout.renderer).toBe('native');+});++test('R3: while the worksheet renderer loads the chart waits for it', async ({ page }) => {+ await open(page, 'slow', [bars]);+ await expect(notice(page)).toHaveAttribute('data-state', 'loading');+ await nothingDrawn(page);+ expect(await status(page)).toBe('computing');+ await page.evaluate(() => window.gw.arrive());+ await expect(sheet(page)).toBeVisible();+ await expect(notice(page)).toHaveCount(0);+ await expect.poll(() => status(page)).toBe('idle');+});++for (const native of ['off', 'fail'] as const) {+ test(`R3: where the worksheet renderer is missing (${native}) a chart saved for it is not drawn by Vega`, async ({ page }) => {+ await open(page, native, [bars, { name: 'History', renderer: 'vega-lite', rows: ['Region'], columns: ['Sales'] }]);+ await expect(notice(page)).toHaveAttribute('data-state', 'unavailable');+ await nothingDrawn(page);+ await expect.poll(() => status(page)).toBe('error');+ expect(await page.evaluate(() => window.gw.host.exportChart())).toMatchObject({ images: 0 });+ const [chart] = await saved(page);+ expect(chart.layout.renderer).toBe('native');+ expect(shelves(chart)).toEqual({ rows: ['Region'], columns: ['Sales'] });+ // An explicit Vega choice is preserved even when the worksheet renderer is absent.+ await page.evaluate(() => window.gw.host.openChart(1));+ await expect(vega(page)).toBeVisible();+ await expect(notice(page)).toHaveCount(0);+ // Saving preserves the explicit choice.+ expect((await saved(page))[1].layout.renderer).toBe('vega-lite');+ });+}++test('R4: only the user changes the renderer, and a renderer that cannot show every level draws none of them', async ({ page }) => {+ await open(page, 'on', [levels]);+ await expect(sheet(page)).toBeVisible();+ await expect.poll(() => status(page)).toBe('idle');+ // E1 in the mounted editor: the ratio is asked for at the grain of all three levels, through the host's computation.+ const asked = await page.evaluate(() => window.gw.queries().flatMap((q) => q.workflow).flatMap((step) => (step.type === 'view' ? step.query : [])));+ expect(asked).toContainEqual({ op: 'aggregate', groupBy: ['Category', 'Region', 'Subcategory'], measures: [{ field: '((sum ("Sales") ) / (sum ("Cost") ))', agg: 'expr', asFieldKey: '__ws_columnm0' }] });+ const before = shelves((await saved(page))[0]);+ expect(before).toEqual({ rows: ['Region', 'Category', 'Subcategory'], columns: ['f_ratio'] });++ for (const [renderer, name] of [['vega-lite', 'VegaLite'], ['observable-plot', 'Observable Plot']] as const) {+ await page.evaluate((to) => window.gw.setRenderer(to), renderer);+ await expect(notice(page)).toHaveAttribute('data-state', 'levels');+ await expect(notice(page)).toContainText(`${name} cannot show every level of this chart`);+ await expect(page.getByTestId('chart-notice-reason')).toContainText('Region, Category, Subcategory');+ await nothingDrawn(page);+ await expect.poll(() => status(page)).toBe('error');+ const [chart] = await saved(page);+ // The choice is the user's and stays; the fields are all still there.+ expect(chart.layout.renderer).toBe(renderer);+ expect(shelves(chart)).toEqual(before);+ }+ await page.evaluate(() => window.gw.setRenderer('native'));+ await expect(sheet(page)).toBeVisible();+ await expect(notice(page)).toHaveCount(0);++ // A chart the other renderers can show in full is drawn by the one the user picks.+ await page.evaluate((chart) => window.gw.load([chart]), { ...bars, rows: ['Region', 'Category'] });+ await expect(sheet(page)).toBeVisible();+ await page.evaluate(() => window.gw.setRenderer('vega-lite'));+ await expect(vega(page)).toBeVisible();+ await expect(sheet(page)).toHaveCount(0);+ await expect(notice(page)).toHaveCount(0);+ await page.evaluate(() => window.gw.setRenderer('observable-plot'));+ await expect(plot(page).first()).toBeVisible();+ await expect(vega(page)).toHaveCount(0);+});++for (const native of ['on', 'off', 'fail'] as const) {+ test(`M1: a map is drawn by the map component under every renderer setting (worksheet renderer ${native})`, async ({ page }) => {+ await open(page, native, renderers.map((renderer) => ({ name: `Map ${renderer}`, renderer, map: true })));+ for (const [index, renderer] of renderers.entries()) {+ await page.evaluate((to) => window.gw.host.openChart(to), index);+ await expect(map(page)).toBeVisible();+ // The points are painted on Leaflet's own canvas, from the map's own query.+ await expect(map(page).locator('canvas')).toHaveCount(1);+ await expect(notice(page)).toHaveCount(0);+ await expect(sheet(page)).toHaveCount(0);+ await expect(vega(page)).toHaveCount(0);+ expect((await saved(page))[index].layout.renderer).toBe(renderer);+ }+ const fields = await page.evaluate(() => window.gw.queries().flatMap((q) => q.workflow).flatMap((step) => (step.type === 'view' ? step.query : [])).flatMap((query) => (query.op === 'aggregate' ? query.groupBy : query.op === 'raw' ? query.fields : [])));+ expect(fields).toEqual(expect.arrayContaining(['Lat', 'Lon']));+ });+}++test('M2: an ordinary chart turned into a map and back keeps its renderer', async ({ page }) => {+ await open(page, 'on', [bars]);+ await expect(sheet(page)).toBeVisible();+ await page.evaluate(() => window.gw.setMap(true));+ await expect(map(page)).toBeVisible();+ await expect(sheet(page)).toHaveCount(0);+ await expect(notice(page)).toHaveCount(0);+ let [chart] = await saved(page);+ expect(chart.layout.renderer).toBe('native');+ expect(chart.config).toMatchObject({ coordSystem: 'geographic', geoms: ['poi'] });+ expect(shelves(chart)).toEqual({ rows: ['Region'], columns: ['Sales'] });++ await page.evaluate(() => window.gw.setMap(false));+ await expect(sheet(page)).toBeVisible();+ await expect(map(page)).toHaveCount(0);+ await expect(vega(page)).toHaveCount(0);+ [chart] = await saved(page);+ expect(chart.layout.renderer).toBe('native');+ expect(chart.config).toMatchObject({ coordSystem: 'generic' });+ await expect.poll(() => status(page)).toBe('idle');+});++test('H1: the host switches and exports charts across renderers, and a chart that is not drawn exports no image', async ({ page }) => {+ await open(page, 'on', [bars, { name: 'Vega bars', renderer: 'vega-lite', rows: ['Region'], columns: ['Sales'] }, betweenMeasures, levels]);+ await expect(sheet(page)).toBeVisible();+ expect(await page.evaluate(() => [window.gw.host.chartCount(), window.gw.host.chartIndex()])).toEqual([4, 0]);++ await page.evaluate(() => window.gw.host.openChart(1));+ await expect(vega(page)).toBeVisible();+ await expect(sheet(page)).toHaveCount(0);+ expect(await page.evaluate(() => [window.gw.host.chartCount(), window.gw.host.chartIndex()])).toEqual([4, 1]);+ await page.evaluate(() => window.gw.host.openChart(2));+ await expect(notice(page)).toHaveAttribute('data-state', 'unsupported');+ expect(await page.evaluate(() => [window.gw.host.chartCount(), window.gw.host.chartIndex()])).toEqual([4, 2]);+ await page.evaluate(() => window.gw.host.openChart(3));+ await expect(sheet(page)).toBeVisible();++ // Exporting them all, started from a worksheet chart and from the chart that is not drawn alike.+ for (const start of [3, 2, 1]) {+ await page.evaluate((index) => window.gw.host.openChart(index), start);+ const list = await page.evaluate(() => window.gw.host.exportChartList());+ expect(list).toEqual([+ { index: 0, title: 'Bars', chartType: 'worksheet', images: 1 },+ { index: 1, title: 'Vega bars', chartType: 'vega', images: 1 },+ // The chart its renderer cannot draw is reported without an image, not with its neighbor's.+ expect.objectContaining({ index: 2, images: 0 }),+ { index: 3, title: 'Levels', chartType: 'worksheet', images: 1 },+ ]);+ // The export leaves the editor on the chart it started from.+ expect(await page.evaluate(() => window.gw.host.chartIndex())).toBe(start);+ }+});+++test('release default: new and unspecified charts use the bundled worksheet renderer', async ({ page }) => {+ await page.goto('/tests/e2e/native-renderer.html');+ await expect(page.locator('body')).toHaveAttribute('data-fixture-ready', 'true');+ expect((await saved(page))[0].layout.renderer).toBe('native');+ await page.evaluate(() => window.gw.load([{ name: 'Default', rows: ['Region', 'Category', 'Subcategory'], columns: ['Sales'] }]));+ await expect(sheet(page)).toBeVisible();+ await expect.poll(() => status(page)).toBe('idle');+ expect(await page.evaluate(() => window.gw.host.exportChart())).toMatchObject({ chartType: 'worksheet', images: 1 });+});++test('release default: PureRenderer renders and exports a worksheet without a renderer setting', async ({ page }) => {+ await page.goto('/tests/e2e/native-renderer.html?pure=1');+ await expect(sheet(page)).toBeVisible();+ await expect.poll(async () => {+ try { return (await page.evaluate(() => window.pureExport()))[0] ?? ''; }+ catch { return ''; }+ }).toContain('<svg');+ await expect(vega(page)).toHaveCount(0);+});diff --git a/packages/graphic-walker/tests/e2e/vite.config.ts b/packages/graphic-walker/tests/e2e/vite.config.tsindex b38bd0d6..b98cbb5d 100644--- a/packages/graphic-walker/tests/e2e/vite.config.ts+++ b/packages/graphic-walker/tests/e2e/vite.config.ts@@ -13,13 +13,15 @@ export default defineConfig({resolve: {alias: {'@': path.resolve(packageRoot, 'src'),+ // Resolve the bundled worksheet runtime just as the library build does.+ '@kanaries/worksheet-renderer': path.resolve(packageRoot, '../worksheet-renderer/src/index.ts'),},},build: {outDir: path.resolve(workspaceRoot, 'node_modules/.cache/graphic-walker-e2e'),emptyOutDir: true,rollupOptions: {- input: path.resolve(__dirname, 'issue-501.html'),+ input: [path.resolve(__dirname, 'issue-501.html'), path.resolve(__dirname, 'native-renderer.html')],},},preview: {diff --git a/packages/graphic-walker/tests/fixtures/spec-compat/chart-geographic.expected.json b/packages/graphic-walker/tests/fixtures/spec-compat/chart-geographic.expected.jsonindex 5e593706..45550bf3 100644--- a/packages/graphic-walker/tests/fixtures/spec-compat/chart-geographic.expected.json+++ b/packages/graphic-walker/tests/fixtures/spec-compat/chart-geographic.expected.json@@ -99,7 +99,7 @@"format": {},"geoKey": "name","resolve": {},- "renderer": "vega-lite",+ "renderer": "native","geoUrl": {"type": "GeoJSON","url": "https://example.com/regions.geo.json"diff --git a/packages/graphic-walker/tests/fixtures/spec-compat/partial-minimal.expected.json b/packages/graphic-walker/tests/fixtures/spec-compat/partial-minimal.expected.jsonindex 3d52fed6..592ddc7b 100644--- a/packages/graphic-walker/tests/fixtures/spec-compat/partial-minimal.expected.json+++ b/packages/graphic-walker/tests/fixtures/spec-compat/partial-minimal.expected.json@@ -61,7 +61,7 @@"shape": false,"size": false},- "renderer": "vega-lite"+ "renderer": "native"},"visId": "gw_mock-id","name": "Chart",diff --git a/packages/graphic-walker/tests/fixtures/spec-compat/special-chars.expected.json b/packages/graphic-walker/tests/fixtures/spec-compat/special-chars.expected.jsonindex 50ed140a..a0558344 100644--- a/packages/graphic-walker/tests/fixtures/spec-compat/special-chars.expected.json+++ b/packages/graphic-walker/tests/fixtures/spec-compat/special-chars.expected.json@@ -75,7 +75,7 @@"shape": false,"size": false},- "renderer": "vega-lite"+ "renderer": "native"},"visId": "gw-fixture-special","name": "特殊字符 \"图表\"",diff --git a/packages/graphic-walker/tests/fixtures/spec-compat/stoinfo-old.expected.json b/packages/graphic-walker/tests/fixtures/spec-compat/stoinfo-old.expected.jsonindex 78164b66..13931696 100644--- a/packages/graphic-walker/tests/fixtures/spec-compat/stoinfo-old.expected.json+++ b/packages/graphic-walker/tests/fixtures/spec-compat/stoinfo-old.expected.json@@ -34,7 +34,7 @@],"visDict": {"meta-sales": [- "{\"base\":{\"config\":{\"defaultAggregated\":true,\"geoms\":[\"bar\"],\"coordSystem\":\"generic\",\"limit\":-1},\"encodings\":{\"dimensions\":[{\"fid\":\"category\",\"name\":\"Category\",\"semanticType\":\"nominal\",\"analyticType\":\"dimension\"}],\"measures\":[{\"fid\":\"sales\",\"name\":\"Sales\",\"semanticType\":\"quantitative\",\"analyticType\":\"measure\",\"aggName\":\"sum\"}],\"rows\":[{\"fid\":\"sales\",\"name\":\"Sales\",\"semanticType\":\"quantitative\",\"analyticType\":\"measure\",\"aggName\":\"sum\"}],\"columns\":[{\"fid\":\"category\",\"name\":\"Category\",\"semanticType\":\"nominal\",\"analyticType\":\"dimension\"}],\"color\":[],\"opacity\":[],\"size\":[],\"shape\":[],\"radius\":[],\"theta\":[],\"longitude\":[],\"latitude\":[],\"geoId\":[],\"details\":[],\"filters\":[],\"text\":[]},\"layout\":{\"showActions\":false,\"showTableSummary\":false,\"stack\":\"stack\",\"interactiveScale\":false,\"zeroScale\":true,\"size\":{\"mode\":\"auto\",\"width\":320,\"height\":200},\"format\":{},\"geoKey\":\"name\",\"resolve\":{\"x\":false,\"y\":false,\"color\":false,\"opacity\":false,\"shape\":false,\"size\":false},\"renderer\":\"vega-lite\",\"scaleIncludeUnmatchedChoropleth\":false},\"visId\":\"gw-old-app-chart\",\"name\":\"Chart 1\"},\"timeline\":[]}"+ "{\"base\":{\"config\":{\"defaultAggregated\":true,\"geoms\":[\"bar\"],\"coordSystem\":\"generic\",\"limit\":-1},\"encodings\":{\"dimensions\":[{\"fid\":\"category\",\"name\":\"Category\",\"semanticType\":\"nominal\",\"analyticType\":\"dimension\"}],\"measures\":[{\"fid\":\"sales\",\"name\":\"Sales\",\"semanticType\":\"quantitative\",\"analyticType\":\"measure\",\"aggName\":\"sum\"}],\"rows\":[{\"fid\":\"sales\",\"name\":\"Sales\",\"semanticType\":\"quantitative\",\"analyticType\":\"measure\",\"aggName\":\"sum\"}],\"columns\":[{\"fid\":\"category\",\"name\":\"Category\",\"semanticType\":\"nominal\",\"analyticType\":\"dimension\"}],\"color\":[],\"opacity\":[],\"size\":[],\"shape\":[],\"radius\":[],\"theta\":[],\"longitude\":[],\"latitude\":[],\"geoId\":[],\"details\":[],\"filters\":[],\"text\":[]},\"layout\":{\"showActions\":false,\"showTableSummary\":false,\"stack\":\"stack\",\"interactiveScale\":false,\"zeroScale\":true,\"size\":{\"mode\":\"auto\",\"width\":320,\"height\":200},\"format\":{},\"geoKey\":\"name\",\"resolve\":{\"x\":false,\"y\":false,\"color\":false,\"opacity\":false,\"shape\":false,\"size\":false},\"renderer\":\"native\",\"scaleIncludeUnmatchedChoropleth\":false},\"visId\":\"gw-old-app-chart\",\"name\":\"Chart 1\"},\"timeline\":[]}"]},"exportData": {@@ -74,7 +74,7 @@},"specDict": {"meta-sales": [- "{\"base\":{\"config\":{\"defaultAggregated\":true,\"geoms\":[\"bar\"],\"coordSystem\":\"generic\",\"limit\":-1},\"encodings\":{\"dimensions\":[{\"fid\":\"category\",\"name\":\"Category\",\"semanticType\":\"nominal\",\"analyticType\":\"dimension\"}],\"measures\":[{\"fid\":\"sales\",\"name\":\"Sales\",\"semanticType\":\"quantitative\",\"analyticType\":\"measure\",\"aggName\":\"sum\"}],\"rows\":[{\"fid\":\"sales\",\"name\":\"Sales\",\"semanticType\":\"quantitative\",\"analyticType\":\"measure\",\"aggName\":\"sum\"}],\"columns\":[{\"fid\":\"category\",\"name\":\"Category\",\"semanticType\":\"nominal\",\"analyticType\":\"dimension\"}],\"color\":[],\"opacity\":[],\"size\":[],\"shape\":[],\"radius\":[],\"theta\":[],\"longitude\":[],\"latitude\":[],\"geoId\":[],\"details\":[],\"filters\":[],\"text\":[]},\"layout\":{\"showActions\":false,\"showTableSummary\":false,\"stack\":\"stack\",\"interactiveScale\":false,\"zeroScale\":true,\"size\":{\"mode\":\"auto\",\"width\":320,\"height\":200},\"format\":{},\"geoKey\":\"name\",\"resolve\":{\"x\":false,\"y\":false,\"color\":false,\"opacity\":false,\"shape\":false,\"size\":false},\"renderer\":\"vega-lite\",\"scaleIncludeUnmatchedChoropleth\":false},\"visId\":\"gw-old-app-chart\",\"name\":\"Chart 1\"},\"timeline\":[]}"+ "{\"base\":{\"config\":{\"defaultAggregated\":true,\"geoms\":[\"bar\"],\"coordSystem\":\"generic\",\"limit\":-1},\"encodings\":{\"dimensions\":[{\"fid\":\"category\",\"name\":\"Category\",\"semanticType\":\"nominal\",\"analyticType\":\"dimension\"}],\"measures\":[{\"fid\":\"sales\",\"name\":\"Sales\",\"semanticType\":\"quantitative\",\"analyticType\":\"measure\",\"aggName\":\"sum\"}],\"rows\":[{\"fid\":\"sales\",\"name\":\"Sales\",\"semanticType\":\"quantitative\",\"analyticType\":\"measure\",\"aggName\":\"sum\"}],\"columns\":[{\"fid\":\"category\",\"name\":\"Category\",\"semanticType\":\"nominal\",\"analyticType\":\"dimension\"}],\"color\":[],\"opacity\":[],\"size\":[],\"shape\":[],\"radius\":[],\"theta\":[],\"longitude\":[],\"latitude\":[],\"geoId\":[],\"details\":[],\"filters\":[],\"text\":[]},\"layout\":{\"showActions\":false,\"showTableSummary\":false,\"stack\":\"stack\",\"interactiveScale\":false,\"zeroScale\":true,\"size\":{\"mode\":\"auto\",\"width\":320,\"height\":200},\"format\":{},\"geoKey\":\"name\",\"resolve\":{\"x\":false,\"y\":false,\"color\":false,\"opacity\":false,\"shape\":false,\"size\":false},\"renderer\":\"native\",\"scaleIncludeUnmatchedChoropleth\":false},\"visId\":\"gw-old-app-chart\",\"name\":\"Chart 1\"},\"timeline\":[]}"]}}diff --git a/packages/graphic-walker/tests/fixtures/spec-compat/visspec-old-full.expected.json b/packages/graphic-walker/tests/fixtures/spec-compat/visspec-old-full.expected.jsonindex 7c5209de..02466bff 100644--- a/packages/graphic-walker/tests/fixtures/spec-compat/visspec-old-full.expected.json+++ b/packages/graphic-walker/tests/fixtures/spec-compat/visspec-old-full.expected.json@@ -165,7 +165,7 @@"shape": false,"size": false},- "renderer": "vega-lite",+ "renderer": "native","colorPalette": "tableau10","primaryColor": "#4e79a7","scaleIncludeUnmatchedChoropleth": false,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.jsonindex 6d51f740..50c3b904 100644--- 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@@ -150,7 +150,7 @@"shape": false,"size": false},- "renderer": "vega-lite",+ "renderer": "native","geojson": {"type": "FeatureCollection","features": [diff --git a/packages/graphic-walker/tests/fixtures/spec-compat/visspec-old-sparse.expected.json b/packages/graphic-walker/tests/fixtures/spec-compat/visspec-old-sparse.expected.jsonindex d7fbad3b..1866af5a 100644--- a/packages/graphic-walker/tests/fixtures/spec-compat/visspec-old-sparse.expected.json+++ b/packages/graphic-walker/tests/fixtures/spec-compat/visspec-old-sparse.expected.json@@ -61,7 +61,7 @@"shape": false,"size": false},- "renderer": "vega-lite",+ "renderer": "native","scaleIncludeUnmatchedChoropleth": false},"visId": "gw-fixture-old-sparse",diff --git a/packages/graphic-walker/tests/specCompat.test.ts b/packages/graphic-walker/tests/specCompat.test.tsindex 96162fbc..fcaf0304 100644--- a/packages/graphic-walker/tests/specCompat.test.ts+++ b/packages/graphic-walker/tests/specCompat.test.ts@@ -6,7 +6,8 @@* releases, and the *.expected.json files are explicitly committed, hand-verified* canonical outputs. If a change to the spec pipeline breaks any of these assertions,* it breaks previously persisted user charts — fix the change, not the fixture,- * unless a migration path is added deliberately.+ * unless a migration path is added deliberately. Version 0.6 deliberately defaults+ * specs without a renderer selection to native; explicit renderer selections stay intact.*/jest.mock('nanoid', () => ({ nanoid: () => 'mock-id' }));diff --git a/packages/graphic-walker/tsconfig.app-dist.json b/packages/graphic-walker/tsconfig.app-dist.jsonindex e77a4f55..e714c0cc 100644--- a/packages/graphic-walker/tsconfig.app-dist.json+++ b/packages/graphic-walker/tsconfig.app-dist.json@@ -1,4 +1,5 @@{+ "extends": "./tsconfig.json","compilerOptions": {"target": "ESNext","lib": ["DOM", "DOM.Iterable", "ESNext"],@@ -15,7 +16,7 @@"resolveJsonModule": true,"isolatedModules": true,"noEmit": true,- "jsx": "react",+ "jsx": "react-jsx","declaration": false,"sourceMap": false,"outDir": "./app-dist",diff --git a/packages/graphic-walker/tsconfig.build.json b/packages/graphic-walker/tsconfig.build.jsonnew file mode 100644index 00000000..3128ae03--- /dev/null+++ b/packages/graphic-walker/tsconfig.build.json@@ -0,0 +1,19 @@+{+ "extends": "./tsconfig.json",+ "compilerOptions": {+ "rootDir": "src",+ "paths": {+ "@/*": [+ "./src/*"+ ],+ "@kanaries/worksheet-renderer": [+ "./dist/worksheet/index.d.ts"+ ]+ }+ },+ "exclude": [+ "src/**/*.test.ts",+ "src/**/*.test.tsx",+ "src/renderer/native/testing.ts"+ ]+}diff --git a/packages/graphic-walker/tsconfig.json b/packages/graphic-walker/tsconfig.jsonindex 94280f87..e8d08d1f 100644--- a/packages/graphic-walker/tsconfig.json+++ b/packages/graphic-walker/tsconfig.json@@ -14,7 +14,7 @@"moduleResolution": "Node","resolveJsonModule": true,"isolatedModules": true,- "jsx": "react",+ "jsx": "react-jsx","declaration": true,"sourceMap": true,"outDir": "./dist",@@ -22,6 +22,9 @@"paths": {"@/*": ["./src/*"+ ],+ "@kanaries/worksheet-renderer": [+ "../worksheet-renderer/src/index.ts"]},"plugins": [diff --git a/packages/graphic-walker/vite-app.config.ts b/packages/graphic-walker/vite-app.config.tsindex 10804949..f19c924e 100644--- a/packages/graphic-walker/vite-app.config.ts+++ b/packages/graphic-walker/vite-app.config.ts@@ -25,6 +25,7 @@ export default defineConfig({resolve: {alias: {"@": path.resolve(__dirname, "./src"),+ "@kanaries/worksheet-renderer": path.resolve(__dirname, "../worksheet-renderer/src/index.ts"),},}})diff --git a/packages/graphic-walker/vite.config.ts b/packages/graphic-walker/vite.config.tsindex 7de92deb..58bbe808 100644--- a/packages/graphic-walker/vite.config.ts+++ b/packages/graphic-walker/vite.config.ts@@ -2,7 +2,6 @@ import { defineConfig } from 'vite'import fs from 'node:fs/promises';import path from 'path';import react from '@vitejs/plugin-react'-import typescript from '@rollup/plugin-typescript'import { peerDependencies } from './package.json'import { DEMO_DATASETS, downloadDemoDataset } from '../../scripts/demo-datasets.mjs';@@ -64,18 +63,13 @@ export default defineConfig({plugins: [demoDatasetFallbackPlugin(),react(),- // @ts-ignore- {- ...typescript({- tsconfig: path.resolve(__dirname, './tsconfig.json'),- }),- apply: 'build'- }],resolve: {dedupe: modulesNotToBundle,alias: {"@": path.resolve(__dirname, "./src"),+ // Bundle the worksheet runtime into the published library.+ "@kanaries/worksheet-renderer": path.resolve(__dirname, "../worksheet-renderer/src/index.ts"),},},build: {diff --git a/packages/playground/package.json b/packages/playground/package.jsonindex 4e020018..82af3d60 100644--- a/packages/playground/package.json+++ b/packages/playground/package.json@@ -21,7 +21,8 @@"@headlessui/react": "2.2.10","@heroicons/react": "^2.0.8","@kanaries/duckdb-computation": "0.0.1",- "@kanaries/graphic-walker": "0.5.3",+ "@kanaries/graphic-walker": "0.6.0",+ "@kanaries/worksheet-renderer": "0.0.0","@vercel/analytics": "^1.1.1","color-space": "2.0.1","react": "^19.2.0",diff --git a/packages/playground/src/examples/nav.tsx b/packages/playground/src/examples/nav.tsxindex 70853854..a797dfa0 100644--- a/packages/playground/src/examples/nav.tsx+++ b/packages/playground/src/examples/nav.tsx@@ -18,6 +18,7 @@ const raw: { group: string; name: string; comp: () => Promise<{ default: React.C{ group: 'Teasers', comp: () => import('./pages/teaserPie'), name: 'Pie: Car Sales' },// ── Core ─────────────────────────────────────+ { group: 'Core', comp: () => import('./pages/worksheetRenderer'), name: 'Worksheet Renderer' },{ group: 'Core', comp: () => import('./pages/gw'), name: 'GraphicWalker' },{ group: 'Core', comp: () => import('./pages/pureRenderer'), name: 'PureRenderer' },{ group: 'Core', comp: () => import('./pages/pivotTable'), name: 'PivotTable' },diff --git a/packages/playground/src/examples/pages/worksheetRenderer.css b/packages/playground/src/examples/pages/worksheetRenderer.cssnew file mode 100644index 00000000..bbb07af3--- /dev/null+++ b/packages/playground/src/examples/pages/worksheetRenderer.css@@ -0,0 +1,30 @@+.worksheet-lab { color: #263248; font-family: system-ui, sans-serif; max-width: 1600px; }+.ws-heading { display: flex; align-items: center; justify-content: space-between; gap: 20px; margin-bottom: 22px; }+.ws-heading h1 { font-size: 28px; font-weight: 650; letter-spacing: -.7px; margin: 5px 0 8px; }+.ws-heading p { color: #667085; font-size: 13px; }+.ws-heading .ws-eyebrow { color: #4263eb; font-size: 10px; letter-spacing: 1.8px; font-weight: 700; }+.worksheet-lab button, .worksheet-lab select { font: inherit; font-size: 12px; border-radius: 5px; }+.worksheet-lab button { cursor: pointer; }+.worksheet-lab button:disabled { cursor: default; opacity: .45; }+.worksheet-lab button:focus-visible, .worksheet-lab select:focus-visible { outline: 2px solid #4263eb; outline-offset: 2px; }+.ws-export, .ws-presets button, .ws-toolbar > button, .ws-diagnostics > button { border: 1px solid #d5dce7; padding: 7px 11px; background: white; }+.ws-export { white-space: nowrap; }+.ws-presets { display: flex; flex-wrap: wrap; gap: 7px; margin-bottom: 18px; }+.ws-presets button:hover { background: #eef2ff; border-color: #a3b3ef; }+.ws-shelves { background: #fafbfe; border: 1px solid #e0e6ef; border-radius: 8px; overflow: hidden; }+.ws-shelf { display: flex; align-items: center; flex-wrap: wrap; gap: 6px; padding: 9px 12px; min-height: 44px; border-bottom: 1px solid #e8ecf3; }+.ws-shelf:last-child { border-bottom: 0; }+.ws-shelf-label { width: 110px; color: #667085; font-size: 12px; }+.ws-pill { display: inline-flex; align-items: center; gap: 7px; padding: 4px 9px; border-radius: 5px; background: #e5edff; color: #284c9d; font-size: 12px; }+.ws-pill.ws-measure { background: #e1f2ec; color: #25654f; }+.ws-pill button { padding: 0 2px; background: transparent; font-size: 15px; line-height: 1; }+.ws-shelf select { background: transparent; border: 0; color: #667085; padding: 5px; max-width: 140px; }+.ws-toolbar { display: flex; align-items: flex-end; flex-wrap: wrap; gap: 12px; margin-top: 18px; }+.ws-toolbar label { display: flex; flex-direction: column; gap: 5px; color: #667085; font-size: 11px; }+.ws-toolbar select { background: white; border: 1px solid #d5dce7; padding: 6px 8px; color: #263248; }+.ws-toolbar .ws-check { flex-direction: row; align-items: center; padding-bottom: 7px; }+.ws-note { font-size: 12px; color: #778195; line-height: 1.7; margin: 16px 0 4px; }+.ws-diagnostics { margin-top: 20px; border-top: 1px solid #e0e6ef; padding-top: 14px; font-size: 12px; }+.ws-diagnostics summary { cursor: pointer; margin-bottom: 10px; }+.ws-code-columns { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }+.ws-code-columns pre { padding: 14px; background: #f5f7fb; overflow: auto; max-height: 420px; font-size: 11px; }diff --git a/packages/playground/src/examples/pages/worksheetRenderer.data.ts b/packages/playground/src/examples/pages/worksheetRenderer.data.tsnew file mode 100644index 00000000..bbb6ed38--- /dev/null+++ b/packages/playground/src/examples/pages/worksheetRenderer.data.ts@@ -0,0 +1,60 @@+import { concat, field, nest, type FieldInstance, type Row, type WorksheetSpec } from '@kanaries/worksheet-renderer';++export const instances: Record<string, FieldInstance> = Object.fromEntries([+ ...['Country', 'Region', 'Category', 'Subcategory', 'Year', 'Month', 'Segment'].map(name => ({ id: name, field: name, label: name, display: 'discrete' as const })),+ { id: 'sales', field: 'Sales', label: 'SUM(Sales)', display: 'continuous' as const, aggregate: 'sum' as const },+ { id: 'profit', field: 'Profit', label: 'AVG(Profit)', display: 'continuous' as const, aggregate: 'mean' as const },+ { id: 'orders', field: 'OrderId', label: 'COUNTD(Order)', display: 'continuous' as const, aggregate: 'distinctCount' as const },+ // A continuous date: it makes a time axis instead of one header per month.+ { id: 'date', field: 'OrderMonth', label: 'Order month', display: 'continuous' as const, scale: 'time' as const },+].map(f => [f.id, f]));++export const dimensions = Object.values(instances).filter(f => f.display === 'discrete').map(f => f.id);+export const measures = ['sales', 'profit', 'orders'];+/** Fields that end an axis branch with a continuous axis. */+export const axisFields = [...measures, 'date'];+export const regions = ['Central', 'East', 'South', 'West'];+export interface Shelves { rows: string[]; columns: string[]; rowMeasures: string[]; columnMeasures: string[]; mark: WorksheetSpec['mark']; color?: string; text?: string; fit?: WorksheetSpec['fit'] }+export const presets: Record<string, Shelves & { label: string }> = {+ nested: { label: 'Nested bars', rows: ['Region', 'Category', 'Subcategory'], columns: ['Year'], rowMeasures: [], columnMeasures: ['sales', 'profit'], mark: 'bar', color: 'Segment' },+ line: { label: 'Monthly lines', rows: ['Region'], columns: ['Year', 'Month'], rowMeasures: ['sales'], columnMeasures: [], mark: 'line', color: 'Segment' },+ scatter: { label: 'Faceted scatter', rows: ['Region', 'Category'], columns: ['Year'], rowMeasures: ['profit'], columnMeasures: ['sales'], mark: 'point', color: 'Segment' },+ deep: { label: 'Five-level hierarchy', rows: ['Country', 'Region', 'Category', 'Subcategory', 'Segment'], columns: ['Year'], rowMeasures: [], columnMeasures: ['sales', 'profit', 'orders'], mark: 'bar', color: 'Segment' },+ // The three Tableau reference views the layout is checked against.+ ref1: { label: 'Ref 1 · Year / Category / Sub-Category', rows: [], columns: ['Year', 'Category', 'Subcategory'], rowMeasures: ['sales'], columnMeasures: [], mark: 'bar' },+ ref2: { label: 'Ref 2 · Category / Sub-Category × Region', rows: ['Category', 'Subcategory'], columns: ['Region'], rowMeasures: [], columnMeasures: ['sales'], mark: 'bar', color: 'profit' },+ ref3: { label: 'Ref 3 · Category / Segment × Year', rows: ['Category', 'Segment'], columns: ['Year'], rowMeasures: [], columnMeasures: ['sales'], mark: 'bar', color: 'Segment' },+ time: { label: 'Time series', rows: ['Region'], columns: [], rowMeasures: ['sales'], columnMeasures: ['date'], mark: 'line', color: 'Segment', fit: 'width' },+ timeBars: { label: 'Bars over time', rows: ['Category'], columns: [], rowMeasures: ['sales'], columnMeasures: ['date'], mark: 'bar', color: 'Segment', fit: 'width' },+ heat: { label: 'Heat map', rows: ['Category', 'Subcategory'], columns: ['Year', 'Month'], rowMeasures: [], columnMeasures: [], mark: 'rect', color: 'profit' },+ crosstab: { label: 'Crosstab', rows: ['Category', 'Subcategory'], columns: ['Region'], rowMeasures: [], columnMeasures: [], mark: 'text', text: 'sales' },+};+export function axis(dims: string[], metrics: string[]) {+ const items = dims.map(field);+ if (metrics.length) items.push(metrics.length === 1 ? field(metrics[0]) : concat(...metrics.map(field)));+ return items.length ? nest(...items) : { kind: 'empty' as const };+}++// Deterministic order-level fixture. Groups have 4, 9 and 4 members, so a layout that+// divides a fixed pane by its member count shows up as uneven bars. It also has negative+// profit, repeated order IDs, one member missing from one region and one empty combination.+export const orders: Row[] = [];+const products = {+ Furniture: ['Bookcases', 'Chairs', 'Furnishings', 'Tables'],+ 'Office Supplies': ['Appliances', 'Art', 'Binders', 'Envelopes', 'Fasteners', 'Labels', 'Paper', 'Storage', 'Supplies'],+ Technology: ['Accessories', 'Copiers', 'Machines', 'Phones'],+};+let seed = 12345;+function random() { seed = (seed * 16807) % 2147483647; return seed / 2147483647; }+for (const Country of ['Canada', 'US']) for (const Region of regions)+ for (const [Category, subs] of Object.entries(products)) for (const Subcategory of subs)+ for (const Year of [2024, 2025]) for (let Month = 1; Month <= 12; Month++) for (const Segment of ['Consumer', 'Corporate']) {+ if (Country === 'Canada' && Region === 'West' && Category === 'Technology' && Year === 2024) continue;+ if (Subcategory === 'Fasteners' && Region === 'South') continue;+ const count = 1 + Math.floor(random() * 3);+ for (let i = 0; i < count; i++) {+ const Sales = Math.round((30 + random() * 400) * (Category === 'Technology' ? 2.2 : 1) * (Year === 2025 ? 1.3 : 1) * (1 + Month / 24) * (Subcategory === 'Fasteners' ? .15 : 1));+ const Profit = Math.round(Sales * (random() * .45 - .12));+ orders.push({ Country, Region, Category, Subcategory, Year, Month, OrderMonth: `${Year}-${String(Month).padStart(2, '0')}-01`, Segment, Sales, Profit, OrderId: `order-${Math.floor(orders.length / 2)}` });+ }+ }diff --git a/packages/playground/src/examples/pages/worksheetRenderer.tsx b/packages/playground/src/examples/pages/worksheetRenderer.tsxnew file mode 100644index 00000000..b01742a6--- /dev/null+++ b/packages/playground/src/examples/pages/worksheetRenderer.tsx@@ -0,0 +1,92 @@+import { useMemo, useRef, useState } from 'react';+import { getComputation } from '@kanaries/graphic-walker';+import { Worksheet, compileWorksheet, type ScaleScope, type WorksheetHandle, type WorksheetSpec } from '@kanaries/worksheet-renderer';+import { axis, axisFields, dimensions, instances, measures, orders, presets, regions, type Shelves } from './worksheetRenderer.data';+import './worksheetRenderer.css';++const computation = getComputation(orders);+function Shelf({ name, values, options, onChange }: { name: string; values: string[]; options: string[]; onChange: (value: string[]) => void }) {+ return <div className="ws-shelf">+ <span className="ws-shelf-label">{name}</span>+ {values.map((id, i) => <span className={`ws-pill ${instances[id].display === 'continuous' ? 'ws-measure' : ''}`} key={id}>+ {instances[id].label}+ {i > 0 ? <button type="button" aria-label={`Move ${name} ${id} left`} title="Move left" onClick={() => { const next = [...values]; [next[i - 1], next[i]] = [next[i], next[i - 1]]; onChange(next); }}>‹</button> : null}+ <button type="button" aria-label={`Remove ${name} ${id}`} title="Remove field" onClick={() => onChange(values.filter(v => v !== id))}>×</button>+ </span>)}+ <select aria-label={`Add ${name}`} value="" onChange={e => { if (e.target.value) onChange([...values, e.target.value]); }}>+ <option value="">+ Add field</option>{options.filter(id => !values.includes(id)).map(id => <option key={id} value={id}>{instances[id].label}</option>)}+ </select>+ </div>;+}+function download(filename: string, contents: string, type: string) {+ const url = URL.createObjectURL(new Blob([contents], { type }));+ const a = document.createElement('a'); a.href = url; a.download = filename; a.click();+ setTimeout(() => URL.revokeObjectURL(url), 1000);+}++export default function WorksheetRendererPage() {+ const [shelves, setShelves] = useState<Shelves>(presets.nested);+ const [scaleScope, setScaleScope] = useState<ScaleScope>('shared');+ const [color, setColor] = useState(presets.nested.color ?? '');+ const [detail, setDetail] = useState('');+ const [text, setText] = useState('sales');+ const [stack, setStack] = useState(true);+ const [sort, setSort] = useState<WorksheetSpec['sort']>('ascending');+ const [region, setRegion] = useState('');+ const [slot, setSlot] = useState(200);+ const [step, setStep] = useState(24);+ const [fit, setFit] = useState<WorksheetSpec['fit'] | ''>('');+ const [exportError, setExportError] = useState('');+ const handle = useRef<WorksheetHandle>(null);+ const spec = useMemo<WorksheetSpec>(() => ({+ kind: 'worksheet', specVersion: 2, instances,+ rows: axis(shelves.rows, shelves.rowMeasures), columns: axis(shelves.columns, shelves.columnMeasures),+ mark: shelves.mark, color: color || undefined, detail: detail ? [detail] : [], text: shelves.mark === 'text' ? text : undefined,+ stack, scaleScope, sort, pane: { width: slot, height: Math.round(slot * .8) }, band: { width: shelves.mark === 'text' ? undefined : step + 4, height: step }, fit: fit || undefined,+ filters: region ? [{ field: 'Region', values: [region] }] : [],+ }), [shelves, color, detail, text, stack, scaleScope, sort, slot, step, fit, region]);+ const diagnostic = useMemo(() => { try { return compileWorksheet(spec).tasks; } catch { return []; } }, [spec]);+ const updateShelf = (key: keyof Omit<Shelves, 'mark' | 'color' | 'text' | 'fit'>, values: string[]) => setShelves(s => ({ ...s, [key]: values }));+ return <section className="worksheet-lab">+ <div className="ws-heading"><div><p className="ws-eyebrow">INTERNAL RENDERER · V0</p><h1>Nested worksheets</h1>+ <p>多层嵌套、度量并列和分面。每个成员占一个等宽的格子,数值轴画在表格边缘,表头和轴在滚动时固定。点击标记选中,按住 Ctrl 或 Cmd 加选,Esc 清空。</p></div>+ <button className="ws-export" type="button" onClick={async () => {+ try { const svg = await handle.current!.exportSVG(); download('worksheet.svg', svg, 'image/svg+xml'); setExportError(''); }+ catch (error) { setExportError(String(error)); }+ }}>Export full SVG</button>+ </div>+ <div className="ws-presets" aria-label="Worksheet presets">+ {Object.entries(presets).map(([key, preset]) =>+ <button type="button" key={key} onClick={() => { setShelves(preset); setColor(preset.color ?? ''); setText(preset.text ?? 'sales'); setFit(preset.fit ?? ''); setDetail(''); setStack(true); }}>{preset.label}</button>)}+ </div>+ <div className="ws-shelves">+ <Shelf name="Rows" values={shelves.rows} options={dimensions} onChange={v => updateShelf('rows', v)} />+ <Shelf name="Row axis" values={shelves.rowMeasures} options={axisFields} onChange={v => updateShelf('rowMeasures', v)} />+ <Shelf name="Columns" values={shelves.columns} options={dimensions} onChange={v => updateShelf('columns', v)} />+ <Shelf name="Column axis" values={shelves.columnMeasures} options={axisFields} onChange={v => updateShelf('columnMeasures', v)} />+ </div>+ <div className="ws-toolbar">+ <label>Mark<select value={shelves.mark} onChange={e => setShelves(s => ({ ...s, mark: e.target.value as Shelves['mark'] }))}>{['bar', 'point', 'circle', 'tick', 'line', 'area', 'rect', 'text'].map(v => <option key={v}>{v}</option>)}</select></label>+ <label>Axis range<select value={scaleScope} onChange={e => setScaleScope(e.target.value as ScaleScope)}>+ <option value="shared">Uniform per measure</option><option value="prefix">Per outer header</option><option value="independent">Independent per row / column</option>+ </select></label>+ <label>Color<select value={color} onChange={e => setColor(e.target.value)}><option value="">None</option>{[...dimensions, ...measures].map(id => <option key={id} value={id}>{instances[id].label}</option>)}</select></label>+ <label>Text<select value={text} disabled={shelves.mark !== 'text'} onChange={e => setText(e.target.value)}>{measures.map(id => <option key={id} value={id}>{instances[id].label}</option>)}</select></label>+ <label>Detail<select value={detail} onChange={e => setDetail(e.target.value)}><option value="">None</option>{dimensions.map(id => <option key={id}>{id}</option>)}</select></label>+ <label>Region filter<select value={region} onChange={e => setRegion(e.target.value)}><option value="">All regions</option>{regions.map(r => <option key={r}>{r}</option>)}</select></label>+ <label>Order<select value={sort} onChange={e => setSort(e.target.value as WorksheetSpec['sort'])}><option value="ascending">Ascending</option><option value="descending">Descending</option></select></label>+ <label>Member step<select value={step} onChange={e => setStep(Number(e.target.value))}><option value="18">Compact</option><option value="24">Default</option><option value="32">Roomy</option></select></label>+ <label>Axis slot<select value={slot} onChange={e => setSlot(Number(e.target.value))}><option value="150">Compact</option><option value="200">Default</option><option value="280">Wide</option></select></label>+ <label>Fit<select value={fit} onChange={e => setFit(e.target.value as WorksheetSpec['fit'] | '')}><option value="">Standard</option><option value="width">Fit width</option><option value="height">Fit height</option><option value="both">Entire view</option></select></label>+ <label className="ws-check"><input type="checkbox" checked={stack} disabled={shelves.mark !== 'bar' && shelves.mark !== 'area'} onChange={e => setStack(e.target.checked)} /> Stack bars</label>+ </div>+ <p className="ws-note">{orders.length.toLocaleString()} synthetic order lines · SUM(Sales), AVG(Profit), COUNTD(Order) 保留独立聚合。三个 Category 分别有 4、9、4 个 Subcategory,Fasteners 在 South 没有记录。导出包含整张工作表。</p>+ {exportError ? <p role="alert">{exportError}</p> : null}+ <Worksheet ref={handle} spec={spec} computation={computation} height={620} />+ <details className="ws-diagnostics"><summary>Inspect worksheet spec and query plan</summary>+ <button type="button" onClick={() => download('worksheet.json', JSON.stringify(spec, null, 2), 'application/json')}>Download spec</button>+ <div className="ws-code-columns"><pre>{JSON.stringify({ ...spec, instances: undefined }, null, 2)}</pre><pre>{JSON.stringify(diagnostic.map(t => t.payload), null, 2)}</pre></div>+ </details>+ <p className="ws-note">V0 独立实验入口。尚未接入旧编辑器的历史记录,没有折叠、双轴、LOD 或表计算。</p>+ </section>;+}diff --git a/packages/playground/tsconfig.json b/packages/playground/tsconfig.jsonindex a7fc6fbf..b426b635 100644--- a/packages/playground/tsconfig.json+++ b/packages/playground/tsconfig.json@@ -8,6 +8,7 @@/* Bundler mode */"moduleResolution": "bundler",+ "paths": { "@kanaries/worksheet-renderer": ["../worksheet-renderer/src/index.ts"] },"allowImportingTsExtensions": true,"resolveJsonModule": true,"isolatedModules": true,diff --git a/packages/playground/vite.config.ts b/packages/playground/vite.config.tsindex b78fb75c..100275c3 100644--- a/packages/playground/vite.config.ts+++ b/packages/playground/vite.config.ts@@ -53,6 +53,9 @@ function demoDatasetFallbackPlugin() {// https://vitejs.dev/config/export default defineConfig({+ resolve: {+ alias: { '@kanaries/worksheet-renderer': path.resolve(__dirname, '../worksheet-renderer/src/index.ts') },+ },plugins: [demoDatasetFallbackPlugin(),react(),diff --git a/packages/worksheet-renderer/package.json b/packages/worksheet-renderer/package.jsonnew file mode 100644index 00000000..09f7a26e--- /dev/null+++ b/packages/worksheet-renderer/package.json@@ -0,0 +1,11 @@+{+ "name": "@kanaries/worksheet-renderer",+ "version": "0.0.0",+ "private": true,+ "type": "module",+ "exports": { ".": "./src/index.ts" },+ "scripts": { "typecheck": "tsc --noEmit", "test": "node tests/run.mjs" },+ "dependencies": { "vega": "^5.22.1" },+ "peerDependencies": { "react": ">=19" },+ "devDependencies": { "typescript": "^5.2.2", "@types/react": "^19.2.17", "esbuild": "^0.18.10" }+}diff --git a/packages/worksheet-renderer/src/Worksheet.tsx b/packages/worksheet-renderer/src/Worksheet.tsxnew file mode 100644index 00000000..1885fbe0--- /dev/null+++ b/packages/worksheet-renderer/src/Worksheet.tsx@@ -0,0 +1,377 @@+import { forwardRef, useEffect, useImperativeHandle, useMemo, useRef, useState } from 'react';+import { parse, View } from 'vega';+import { continuousColor, darkTheme, lightTheme, type Theme } from './color';+import { compileWorksheet, executePlan } from './compiler';+import { valueKey } from './keys';+import { defaultFont, setTextMeasure } from './layout';+import type { Formats } from './formats';+import { memberLabel } from './time';+import { buildModel, type Zoom } from './model';+import { axesAt, panned, withRange, zoomed } from './zoom';+import { buildScene, type Primitive, type Scene } from './scene';+import { sceneData, sceneToPNG, sceneToSVG, vegaSpec } from './vegaBackend';+import { resultTables, type ResultTable } from './export';+import type { Computation, Row, Selection, WorksheetSpec } from './types';++export interface WorksheetHandle {+ /** The whole sheet, not only the part in the window, with headers, axes and legend. */+ exportSVG(): Promise<string>;+ /**+ * The whole sheet as a PNG data URL, at `scale` device pixels per CSS pixel. A sheet too+ * large for a canvas at that scale is drawn at the largest scale that fits.+ */+ exportPNG(scale?: number): Promise<string>;+ /** The records behind the marks, one table per query that is drawn. */+ exportRecords(): ResultTable[];+ /** Size of the whole sheet in CSS px, which is the size of an exported SVG. */+ size(): { width: number; height: number };+}+/**+ * querying: results are on their way; the last sheet stays on screen, faded and inert.+ * drawing: results are in and the sheet is being painted. idle: what is on screen is current.+ */+export type WorksheetStatus = 'querying' | 'drawing' | 'idle' | 'error';+// The canvas limits that hold across current browsers.+const maxCanvasSide = 16_000, maxCanvasArea = 64_000_000;+export interface WorksheetProps {+ spec: WorksheetSpec;+ computation: Computation;+ /**+ * Upper bound of the scroll window. A shorter worksheet takes only the height it needs. A sheet+ * that is fitted or stretched in height takes all of it.+ */+ height?: number;+ /** Called with every selected mark. Click selects one, Ctrl or Cmd click adds or removes, a click on empty space or Escape clears. */+ onSelectionChange?: (selections: Selection[]) => void;+ /**+ * Called with the mark under a plain click, after the sheet's own selection, and with the DOM+ * event, whose position places a menu and whose propagation the host may stop.+ */+ onMarkClick?: (selection: Selection, event: MouseEvent) => void;+ onStatusChange?: (status: WorksheetStatus) => void;+ /**+ * Lets the viewer zoom and pan the value axes: the wheel zooms around the pointer, a drag+ * pans, a double click returns every axis to the range the data asks for. Every pane that+ * shares an axis range moves together. Over a zoomable pane the wheel no longer scrolls.+ */+ zoomable?: boolean;+ /** How numbers, dates and the sheet's own words are written. Keep the object the same between renders while nothing in it changes. */+ formats?: Formats;+ /**+ * Called when the sheet cannot be drawn: the spec does not compile, a query fails, or the data+ * does not fit, with the message shown in its place. Called with '' once it draws again.+ */+ onError?: (message: string) => void;+ /** Surface, text, rule and mark colors. Pass the host's own surface color as `paper` so the sheet blends in, and its palette so marks match its other charts. */+ theme?: 'light' | 'dark' | Theme;+ /**+ * Draws nothing but the chart: no status line, no frame around the scroll area and no+ * panel listing the selected records. For hosts that already provide that chrome.+ */+ compact?: boolean;+}+// Header widths and label truncation use the same font the canvas draws with.+if (typeof document !== 'undefined') {+ const context = document.createElement('canvas').getContext('2d');+ if (context) setTextMeasure((text, fontSize, fontWeight, font) => {+ context.font = `${fontWeight} ${fontSize}px ${font || defaultFont}`;+ return context.measureText(text).width;+ });+}+const emptyScene = (background: string): Scene => ({ width: 1, height: 1, items: [], visiblePanes: 0, background, legend: 'none', body: { x0: 0, y0: 0, x1: 0, y1: 0 } });+const message = (error: unknown) => error instanceof Error ? error.message : String(error);++function VegaViewport({ scene, onClick, onPainted }: { scene: Scene; onClick: (item: Primitive | undefined, additive: boolean, event: MouseEvent) => void; onPainted?: () => void }) {+ const host = useRef<HTMLDivElement>(null);+ const tip = useRef<HTMLDivElement>(null);+ const instance = useRef<View | null>(null);+ const click = useRef(onClick);+ click.current = onClick;+ const painted = useRef(onPainted);+ painted.current = onPainted;+ const [error, setError] = useState('');+ useEffect(() => {+ const view = new View(parse(vegaSpec(emptyScene(scene.background))), { renderer: 'canvas' }).initialize(host.current!);+ instance.current = view;+ view.addEventListener('click', (event, item) => {+ const mouse = event as MouseEvent;+ click.current(item?.datum as Primitive | undefined, mouse.ctrlKey || mouse.metaKey, mouse);+ });+ // The tooltip follows the pointer and is moved without a React render.+ const hide = () => { if (tip.current) tip.current.style.visibility = 'hidden'; };+ view.addEventListener('mousemove', (event, item) => {+ const box = tip.current, text = (item?.datum as Primitive | undefined)?.tooltip;+ if (!box || !text) return hide();+ if (box.textContent !== text) box.textContent = text;+ const area = host.current!.getBoundingClientRect();+ const x = (event as MouseEvent).clientX - area.left, y = (event as MouseEvent).clientY - area.top;+ // Flip to the other side of the pointer near the right and bottom edges.+ box.style.left = `${x + 14 + box.offsetWidth > area.width ? Math.max(0, x - 14 - box.offsetWidth) : x + 14}px`;+ box.style.top = `${y + 16 + box.offsetHeight > area.height ? Math.max(0, y - 12 - box.offsetHeight) : y + 16}px`;+ box.style.visibility = 'visible';+ });+ view.addEventListener('mouseout', hide);+ return () => { instance.current = null; view.finalize(); };+ }, []);+ useEffect(() => {+ let active = true;+ const view = instance.current;+ // What was under the pointer may have moved or gone; the next pointer move brings the tooltip back.+ if (tip.current) tip.current.style.visibility = 'hidden';+ if (view) {+ view.width(scene.width).height(scene.height).background(scene.background);+ for (const [name, values] of sceneData(scene)) view.data(name, values);+ // The callback of the render this scene came from, so a host learns which sheet is now on screen.+ const notify = painted.current;+ void view.runAsync().then(() => { if (active) { setError(''); notify?.(); } }, reason => { if (active) setError(message(reason)); });+ }+ return () => { active = false; };+ }, [scene]);+ return <div style={{ position: 'relative', width: scene.width, height: scene.height }}>+ <div ref={host} role="img" aria-label={`Worksheet chart, ${scene.visiblePanes} visible panes.`} />+ <div ref={tip} role="tooltip" style={{ position: 'absolute', left: 0, top: 0, visibility: 'hidden', maxWidth: 360, whiteSpace: 'pre-line', background: '#172033', color: '#fff', borderRadius: 6, padding: '8px 12px', fontSize: 12, lineHeight: 1.5, pointerEvents: 'none', zIndex: 1 }} />+ {error ? <div role="alert">{error}</div> : null}+ </div>;+}++export const Worksheet = forwardRef<WorksheetHandle, WorksheetProps>(function Worksheet({ spec, computation, height = 570, onSelectionChange, onMarkClick, onStatusChange, onError, formats, zoomable = false, theme: themeProp = 'light', compact = false }, ref) {+ const theme = useMemo<Theme>(() => themeProp === 'light' ? lightTheme : themeProp === 'dark' ? darkTheme : themeProp,+ [typeof themeProp === 'string' ? themeProp : JSON.stringify(themeProp)]);+ const compiled = useMemo(() => {+ try { return { plan: compileWorksheet(spec), error: '' }; }+ catch (error) { return { plan: undefined, error: message(error) }; }+ }, [spec]);+ const queryKey = compiled.plan ? JSON.stringify(compiled.plan.tasks.map(t => t.payload)) : '';+ const latestPlan = useRef(compiled.plan);+ latestPlan.current = compiled.plan;+ const [result, setResult] = useState<{ key: string; data?: Map<string, Row[]>; error?: string }>();+ const [loading, setLoading] = useState(false);+ const [selection, setSelection] = useState<ReadonlyMap<string, Selection>>(new Map());+ const notify = useRef(onSelectionChange);+ notify.current = onSelectionChange;+ const current = useRef(selection);+ current.current = selection;+ const select = (next: ReadonlyMap<string, Selection>) => { setSelection(next); notify.current?.([...next.values()]); };+ // Axis ranges the viewer zoomed or panned to. They belong to one set of queries and go when it changes.+ const [zoom, setZoom] = useState<Zoom>({});+ useEffect(() => setZoom({}), [queryKey]);+ useEffect(() => { if (!zoomable) setZoom({}); }, [zoomable]);+ useEffect(() => {+ const plan = latestPlan.current;+ if (!plan) { setLoading(false); setResult(undefined); return; }+ const controller = new AbortController();+ setLoading(true);+ // Marks of the previous result may not exist in the next one.+ if (current.current.size) select(new Map());+ void executePlan(plan, computation, controller.signal).then(data => {+ if (!controller.signal.aborted) { setResult({ key: queryKey, data }); setLoading(false); }+ }, error => {+ if (!controller.signal.aborted) { setResult({ key: queryKey, error: message(error) }); setLoading(false); }+ });+ return () => controller.abort();+ }, [queryKey, computation]);+ const scrollHost = useRef<HTMLDivElement>(null);+ // `outer` is the width of the window with a vertical scroll bar counted in, `bar` how thick a scroll bar is.+ const [viewport, setViewport] = useState({ x: 0, y: 0, width: 800, height, outer: 800, bar: 0 });+ // Only a fitted or stretched axis makes the layout depend on the window size.+ const fit = compiled.plan?.spec.fit;+ const stretch = fit ? undefined : compiled.plan?.spec.stretch;+ // A stretched sheet decides for itself where scroll bars come, so it is told the window without them.+ const targetWidth = stretch ? viewport.outer : fit === 'width' || fit === 'both' ? viewport.width : 0;+ const targetHeight = stretch ? height - (compact ? 0 : 2) : fit === 'height' || fit === 'both' ? height - 2 : 0;+ const scrollbar = stretch ? viewport.bar : 0;+ // Row headers get at most 40% of the window. Rounded so that dragging a window edge does not rebuild the layout on every pixel.+ const headerWidth = Math.max(96, Math.round(viewport.width * 0.4 / 24) * 24);+ const built = useMemo(() => {+ if (!compiled.plan || result?.key !== queryKey || !result.data) return undefined;+ try { return { model: buildModel(compiled.plan, result.data, { width: targetWidth, height: targetHeight, headerWidth, font: theme.font, scrollbar }, formats, zoom), error: '' }; }+ catch (error) { return { model: undefined, error: message(error) }; }+ }, [compiled.plan, result, queryKey, targetWidth, targetHeight, scrollbar, headerWidth, formats, zoom, theme.font]);+ const fresh = built?.model;+ // While the next result is on its way the last sheet stays up, so a change of fields does not blank the chart.+ const last = useRef(fresh);+ if (fresh) last.current = fresh;+ const model = fresh ?? (loading ? last.current : undefined);+ // Room for a horizontal scroll bar, so a short worksheet does not gain a vertical one.+ const hostHeight = model ? Math.min(height, model.height + 18) : height;+ useEffect(() => {+ const host = scrollHost.current!;+ // The thickness of a scroll bar here, read off a box that always shows one. Zero where bars lie over the content.+ const probe = document.createElement('div');+ probe.style.cssText = 'position:absolute;visibility:hidden;width:80px;height:80px;overflow:scroll';+ host.parentNode!.appendChild(probe);+ const bar = probe.offsetWidth - probe.clientWidth;+ probe.remove();+ const read = () => setViewport(v => {+ const next = { x: host.scrollLeft, y: host.scrollTop, width: host.clientWidth, height: host.clientHeight, outer: host.offsetWidth - host.clientLeft * 2, bar };+ return next.x === v.x && next.y === v.y && next.width === v.width && next.height === v.height && next.outer === v.outer && next.bar === v.bar ? v : next;+ });+ const observer = new ResizeObserver(read);+ observer.observe(host);+ read();+ let frame = 0;+ const scroll = () => { cancelAnimationFrame(frame); frame = requestAnimationFrame(read); };+ host.addEventListener('scroll', scroll, { passive: true });+ return () => { observer.disconnect(); cancelAnimationFrame(frame); host.removeEventListener('scroll', scroll); };+ }, []);+ // The scroll range can shrink when the worksheet changes; the browser clamps the offsets without a scroll event.+ useEffect(() => {+ const host = scrollHost.current!;+ setViewport(v => v.x === host.scrollLeft && v.y === host.scrollTop ? v : { ...v, x: host.scrollLeft, y: host.scrollTop });+ }, [model, hostHeight]);+ const selected = useMemo(() => new Set(selection.keys()), [selection]);+ const scene = useMemo(() => model ? buildScene(model, viewport, { selected, theme }) : emptyScene(theme.paper), [model, viewport, selected, theme]);+ useImperativeHandle(ref, () => {+ const whole = () => {+ if (!model || loading) throw new Error('Wait for the worksheet query to finish.');+ return buildScene(model, { x: 0, y: 0, width: model.width, height: model.height }, { theme });+ };+ return {+ async exportSVG() {+ const scene = whole();+ if (scene.width * scene.height > 100_000_000) throw new Error('Full export exceeds the V0 size limit. Filter the worksheet first.');+ return sceneToSVG(scene);+ },+ async exportPNG(scale = 2) {+ const scene = whole();+ const fit = Math.min(scale, maxCanvasSide / scene.width, maxCanvasSide / scene.height, Math.sqrt(maxCanvasArea / (scene.width * scene.height)));+ if (fit < 0.25) throw new Error('The worksheet is too large for an image. Filter it first, or export SVG.');+ return sceneToPNG(scene, fit);+ },+ exportRecords() {+ if (!compiled.plan || loading || result?.key !== queryKey || !result.data) throw new Error('Wait for the worksheet query to finish.');+ return resultTables(compiled.plan, result.data);+ },+ size() {+ const scene = whole();+ return { width: scene.width, height: scene.height };+ },+ };+ }, [model, loading, theme, compiled.plan, result, queryKey]);+ const error = compiled.error || built?.error || (result?.key === queryKey ? result.error : '');+ const [painted, setPainted] = useState<typeof fresh>();+ // A sheet whose queries have changed is waiting from that very render on, before the new ones are sent.+ // A host that looks right after it changed the sheet is not told that the sheet is ready.+ const waiting = loading || Boolean(compiled.plan && result?.key !== queryKey);+ const status: WorksheetStatus = error ? 'error' : waiting ? 'querying' : fresh && painted !== fresh ? 'drawing' : 'idle';+ const reportStatus = useRef(onStatusChange);+ reportStatus.current = onStatusChange;+ useEffect(() => { reportStatus.current?.(status); }, [status]);+ const markClick = useRef(onMarkClick);+ markClick.current = onMarkClick;++ // Zooming and panning. The listeners read the latest sheet through a ref, so they are attached once.+ const surface = useRef<HTMLDivElement>(null);+ const live = useRef({ model, scene, viewport, zoom });+ live.current = { model, scene, viewport, zoom };+ useEffect(() => {+ const element = surface.current;+ if (!zoomable || !element) return;+ const at = (event: MouseEvent) => {+ const { model, scene, viewport } = live.current;+ if (!model) return {};+ const area = element.getBoundingClientRect();+ return axesAt(model, scene.body, viewport, event.clientX - area.left, event.clientY - area.top);+ };+ // Several wheel or move events between two frames are folded into one rebuild of the sheet.+ let pending: Zoom | undefined, frame = 0;+ const apply = (change: (zoom: Zoom) => Zoom) => {+ pending = change(pending ?? live.current.zoom);+ if (!frame) frame = requestAnimationFrame(() => { frame = 0; if (pending) setZoom(pending); pending = undefined; });+ };+ const wheel = (event: WheelEvent) => {+ const axes = at(event);+ if (!axes.x && !axes.y) return;+ // The wheel belongs to the axes here; elsewhere it still scrolls the sheet.+ event.preventDefault();+ const factor = Math.exp(event.deltaY * (event.deltaMode === 1 ? 0.05 : 0.0015));+ apply(zoom => {+ let next = zoom;+ for (const axis of [axes.x, axes.y]) {+ if (!axis) continue;+ // An axis without an entry shows the range the data asks for.+ const { key, full, domain } = axis.leaf.scale!;+ next = withRange(next, axis.leaf, zoomed(axis.leaf, next[key!] ?? full ?? domain, axis.t, factor));+ }+ return next;+ });+ };+ let drag: { x: number; y: number; axes: ReturnType<typeof at>; from: { x?: readonly [number, number]; y?: readonly [number, number] }; moved: boolean } | undefined;+ let swallow = false;+ const down = (event: PointerEvent) => {+ if (event.button !== 0) return;+ const axes = at(event);+ swallow = false;+ if (axes.x || axes.y) drag = { x: event.clientX, y: event.clientY, axes, from: { x: axes.x?.leaf.scale!.domain, y: axes.y?.leaf.scale!.domain }, moved: false };+ };+ const move = (event: PointerEvent) => {+ if (!drag) return;+ const dx = event.clientX - drag.x, dy = event.clientY - drag.y;+ if (!drag.moved && Math.hypot(dx, dy) < 4) return;+ drag.moved = true;+ const { axes, from } = drag;+ apply(zoom => {+ let next = zoom;+ if (axes.x && from.x) next = withRange(next, axes.x.leaf, panned(axes.x.leaf, from.x, dx));+ // Screen y runs down, values run up.+ if (axes.y && from.y) next = withRange(next, axes.y.leaf, panned(axes.y.leaf, from.y, -dy));+ return next;+ });+ };+ const up = () => { swallow = Boolean(drag?.moved); drag = undefined; };+ // The click that ends a drag must not select the mark under it.+ const click = (event: MouseEvent) => { if (swallow) { event.stopPropagation(); swallow = false; } };+ const reset = (event: MouseEvent) => { const axes = at(event); if ((axes.x || axes.y) && Object.keys(live.current.zoom).length) setZoom({}); };+ element.addEventListener('wheel', wheel, { passive: false });+ element.addEventListener('pointerdown', down);+ window.addEventListener('pointermove', move);+ window.addEventListener('pointerup', up);+ element.addEventListener('click', click, true);+ element.addEventListener('dblclick', reset);+ return () => {+ cancelAnimationFrame(frame);+ element.removeEventListener('wheel', wheel);+ element.removeEventListener('pointerdown', down);+ window.removeEventListener('pointermove', move);+ window.removeEventListener('pointerup', up);+ element.removeEventListener('click', click, true);+ element.removeEventListener('dblclick', reset);+ };+ }, [zoomable]);+ const colorField = model?.plan.spec.color ? model.plan.spec.instances[model.plan.spec.color] : undefined;+ const report = useRef(onError);+ report.current = onError;+ useEffect(() => { report.current?.(error || ''); }, [error]);+ return <div style={{ position: 'relative', color: theme.text, fontFamily: 'system-ui, sans-serif', fontSize: 13 }}>+ {/* Compact hosts still get the status, for screen readers and tests, without it taking space. */}+ <div aria-live="polite" data-testid="worksheet-status" style={compact+ ? { position: 'absolute', width: 1, height: 1, overflow: 'hidden', clipPath: 'inset(50%)', whiteSpace: 'nowrap' }+ : { display: 'flex', gap: 16, padding: '10px 0', flexWrap: 'wrap', color: theme.muted }}>+ {loading ? 'Querying…' : model ? `${model.panes.length} panes · ${scene.visiblePanes} visible · ${model.rows.leaves.length} × ${model.columns.leaves.length} positions · ${model.plan.tasks.length} query tasks · ${model.panes.reduce((n, p) => n + p.records.length, 0)} marks` : 'Worksheet'}+ </div>+ {/* In a window too narrow for the legend strip the colors are named here instead. */}+ {model && colorField && scene.legend === 'omitted' ? <div data-testid="worksheet-legend" style={{ display: 'flex', gap: 10, flexWrap: 'wrap', alignItems: 'center', paddingBottom: 6, fontSize: 11 }}>+ <strong>{colorField.label}</strong>+ {model.colorScale+ ? <><span>{model.format.ticks(model.colorScale.domain)[0]}</span><span style={{ width: 72, height: 8, borderRadius: 2, background: `linear-gradient(to right, ${[0, .25, .5, .75, 1].map(t => continuousColor(model.colorScale!, model.colorScale!.domain[0] + (model.colorScale!.domain[1] - model.colorScale!.domain[0]) * t, theme, model.plan.spec.mark === 'rect')).join(', ')})` }} /><span>{model.format.ticks(model.colorScale.domain)[1]}</span></>+ : <>{model.colors.slice(0, 12).map((c, i) => <span key={valueKey(c)}><span style={{ display: 'inline-block', width: 8, height: 8, borderRadius: 2, background: theme.category[i % theme.category.length], marginRight: 4 }} />{memberLabel(colorField, c, model.format)}</span>)}{model.colors.length > 12 ? <span>{model.format.words.more(model.colors.length - 12)}</span> : null}</>}+ </div> : null}+ {error ? <p role="alert" style={{ color: '#d92d20' }}>{error}</p> : null}+ {!loading && model && !model.panes.length ? <p>{model.format.words.empty}</p> : null}+ <div ref={scrollHost} data-testid="worksheet-scroll" aria-label="Scrollable worksheet" tabIndex={0} onKeyDown={event => { if (event.key === 'Escape' && selection.size) select(new Map()); }} style={{ position: 'relative', overflow: 'auto', height: hostHeight, background: theme.paper, ...(compact ? {} : { border: `1px solid ${theme.line}`, borderRadius: 8 }) }}>+ <div style={{ width: model?.width ?? 1, height: model?.height ?? 1, position: 'relative' }}>+ <div ref={surface} style={{ position: 'sticky', top: 0, left: 0, width: viewport.width, height: viewport.height, visibility: error ? 'hidden' : 'visible', ...(loading ? { opacity: 0.5, pointerEvents: 'none' as const } : {}) }}>+ <VegaViewport scene={scene} onPainted={() => setPainted(fresh)} onClick={(item, additive, event) => {+ const hit = item?.selection;+ if (!hit) { if (!additive && selection.size && (!item || item.layer === 'body')) select(new Map()); return; }+ const next = new Map(additive ? selection : []);+ if (additive && next.has(hit.id)) next.delete(hit.id); else next.set(hit.id, hit);+ select(next);+ if (!additive) markClick.current?.(hit, event);+ }} />+ </div>+ </div>+ </div>+ {selection.size && !compact ? <details style={{ marginTop: 12 }}><summary data-testid="worksheet-selection-count">{selection.size} selected · Esc clears</summary><pre data-testid="worksheet-selection" style={{ whiteSpace: 'pre-wrap', fontSize: 12 }}>{JSON.stringify([...selection.values()].map(s => ({ predicates: s.predicates, values: s.values })), null, 2)}</pre></details> : null}+ </div>;+});diff --git a/packages/worksheet-renderer/src/channels.ts b/packages/worksheet-renderer/src/channels.tsnew file mode 100644index 00000000..da532cd5--- /dev/null+++ b/packages/worksheet-renderer/src/channels.ts@@ -0,0 +1,74 @@+import { valueKey } from './keys';+import { resultKey, type FieldInstance, type Row, type Value } from './types';+import { position, type ScaleType } from './warp';++/**+ * What a field on size or opacity spans. A dimension has members, ranked in value order; a+ * continuous field has a range. Both come from the complete result, like an axis range.+ */+export interface ChannelScale {+ field: FieldInstance;+ members?: Value[];+ domain?: [number, number];+ type?: ScaleType;+ /** An end of the range was set by hand; a size then no longer measures from zero on its own. */+ fixed?: boolean;+ /** What the lowest and the highest level turn into, in place of the built-in steps. */+ range?: [number, number];+}+/** One block of the legend strip: a title and what explains one channel. */+export interface LegendBlock {+ channel: 'color' | 'size' | 'opacity' | 'shape';+ title: string;+ /** 'ramp' is a continuous color band from the first entry to the last; 'list' has one row per entry. */+ kind: 'list' | 'ramp';+ /** `level` is where the entry sits on its channel, from 0 to 1. */+ entries: { label: string; level: number }[];+ /** Height of one row of a list. */+ step: number;+ height: number;+}+export const legendTitleHeight = 28;++/**+ * Where a record sits on a channel, from 0 to 1. NaN when it has no value there.+ * A member's level is its rank, so the first member is already above zero. A continuous+ * value is placed in its range; `fromZero` measures it from zero instead when the whole+ * range is on one side of zero, which is what makes a size read as a quantity.+ */+export function level(scale: ChannelScale, record: Row, fromZero = false): number {+ if (scale.members) {+ const index = memberIndex(scale, record[scale.field.field]);+ return index < 0 ? NaN : (index + 1) / scale.members.length;+ }+ const raw = record[resultKey(scale.field)];+ return raw == null ? NaN : levelOf(scale, Number(raw), fromZero);+}+export function levelOf(scale: ChannelScale, value: number, fromZero = false): number {+ if (!Number.isFinite(value) || !scale.domain) return NaN;+ let [low, high] = scale.domain;+ // A log scale has no zero to measure from.+ if (fromZero && !scale.fixed && scale.type !== 'log') {+ if (low >= 0) low = 0;+ else if (high <= 0) [low, high] = [0, low];+ }+ // A range of one value puts everything at the top.+ return high === low ? 1 : Math.min(1, Math.max(0, position([low, high], value, scale.type)));+}+const indices = new WeakMap<ChannelScale, Map<string, number>>();+export function memberIndex(scale: ChannelScale, value: Value): number {+ let index = indices.get(scale);+ if (!index) indices.set(scale, index = new Map(scale.members!.map((member, i) => [valueKey(member), i])));+ return index.get(valueKey(value)) ?? -1;+}++/** Symbol outlines in the order members take them. They start over when the members outnumber them. */+export const shapes = ['circle', 'square', 'triangle-up', 'diamond', 'cross', 'triangle-down', 'triangle-right', 'triangle-left'] as const;+/** Area of a point mark at a size level, in square px. */+export const pointArea = (t: number) => 12 + t * 244;+/** Share of the default thickness a bar or the default length a tick takes at a size level. */+export const thicknessShare = (t: number) => 0.25 + 0.75 * t;+/** Opacity at an opacity level. The faintest mark stays readable. */+export const opacityAt = (t: number) => 0.25 + 0.75 * t;+/** The value at a level of a range set by hand. */+export const inRange = (range: [number, number], t: number) => range[0] + (range[1] - range[0]) * t;diff --git a/packages/worksheet-renderer/src/clip.ts b/packages/worksheet-renderer/src/clip.tsnew file mode 100644index 00000000..4d5530b7--- /dev/null+++ b/packages/worksheet-renderer/src/clip.ts@@ -0,0 +1,66 @@+/** A screen rectangle: left, top, right, bottom. */+export interface Box { x0: number; y0: number; x1: number; y1: number }+export type Point = [number, number];++export const inside = (box: Box, x: number, y: number) => x >= box.x0 && x <= box.x1 && y >= box.y0 && y <= box.y1;++/** The part of a rectangle inside the box, or nothing when they do not overlap. */+export function clipRect(box: Box, x: number, y: number, width: number, height: number): [number, number, number, number] | undefined {+ const x0 = Math.max(x, box.x0), y0 = Math.max(y, box.y0), x1 = Math.min(x + width, box.x1), y1 = Math.min(y + height, box.y1);+ return x1 > x0 && y1 > y0 ? [x0, y0, x1 - x0, y1 - y0] : undefined;+}++// Liang–Barsky: the stretch of a segment inside the box, as the two parameters along it.+function span(box: Box, a: Point, b: Point): [number, number] | undefined {+ let t0 = 0, t1 = 1;+ const dx = b[0] - a[0], dy = b[1] - a[1];+ for (const [p, q] of [[-dx, a[0] - box.x0], [dx, box.x1 - a[0]], [-dy, a[1] - box.y0], [dy, box.y1 - a[1]]]) {+ if (p === 0) { if (q < 0) return undefined; continue; }+ const t = q / p;+ if (p < 0) { if (t > t1) return undefined; if (t > t0) t0 = t; }+ else { if (t < t0) return undefined; if (t < t1) t1 = t; }+ }+ return [t0, t1];+}+const lerp = (a: Point, b: Point, t: number): Point => [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t];++/** The pieces of a line that lie inside the box. A line that leaves and comes back is cut in two. */+export function clipLine(box: Box, points: Point[]): Point[][] {+ const pieces: Point[][] = [];+ let open: Point[] | undefined;+ // A line of one point is kept where the point is inside, so a lone value still shows.+ if (points.length === 1) return inside(box, points[0][0], points[0][1]) ? [points] : [];+ for (let i = 1; i < points.length; i++) {+ const a = points[i - 1], b = points[i];+ const cut = span(box, a, b);+ if (!cut) { open = undefined; continue; }+ const from = lerp(a, b, cut[0]), to = lerp(a, b, cut[1]);+ // The piece carries on only where this segment starts at the very point the last one ended.+ if (!open || cut[0] > 0) pieces.push(open = [from]);+ open.push(to);+ if (cut[1] < 1) open = undefined;+ }+ return pieces;+}++/** The part of a closed outline inside the box, by clipping against each side in turn (Sutherland–Hodgman). */+export function clipPolygon(box: Box, points: Point[]): Point[] {+ const sides: [(p: Point) => boolean, (a: Point, b: Point) => Point][] = [+ [p => p[0] >= box.x0, (a, b) => lerp(a, b, (box.x0 - a[0]) / (b[0] - a[0]))],+ [p => p[0] <= box.x1, (a, b) => lerp(a, b, (box.x1 - a[0]) / (b[0] - a[0]))],+ [p => p[1] >= box.y0, (a, b) => lerp(a, b, (box.y0 - a[1]) / (b[1] - a[1]))],+ [p => p[1] <= box.y1, (a, b) => lerp(a, b, (box.y1 - a[1]) / (b[1] - a[1]))],+ ];+ let outline = points;+ for (const [within, cross] of sides) {+ const next: Point[] = [];+ for (let i = 0; i < outline.length; i++) {+ const a = outline[(i + outline.length - 1) % outline.length], b = outline[i];+ if (within(b)) { if (!within(a)) next.push(cross(a, b)); next.push(b); }+ else if (within(a)) next.push(cross(a, b));+ }+ outline = next;+ if (!outline.length) break;+ }+ return outline;+}diff --git a/packages/worksheet-renderer/src/color.ts b/packages/worksheet-renderer/src/color.tsnew file mode 100644index 00000000..1c8a33b4--- /dev/null+++ b/packages/worksheet-renderer/src/color.ts@@ -0,0 +1,91 @@+import { valueKey } from './keys';+import { resultKey, type ColorScale, type FieldInstance, type Row, type Value } from './types';+import { position } from './warp';++/**+ * Every color the sheet paints. The first six are the surface, text and rules; the rest+ * color the marks. A host passes its own to make the sheet follow its theme.+ */+export interface Theme {+ paper: string; text: string; muted: string; line: string; grid: string; zero: string;+ /** Color of marks when no field is on color. */+ mark: string;+ /** Colors of the members of a discrete color field, in legend order. Reused from the start when there are more members. */+ category: string[];+ /** Stops for a continuous color field whose range stays on one side of zero, from the value nearest zero to the furthest. */+ ramp: string[];+ /** Stops for a continuous color field whose range crosses zero, from the negative end through the middle to the positive end. */+ diverging: string[];+ /** Stops for the cells of a heat map, when they differ from `ramp`. */+ heatmap?: string[];+ /** Font family of every text. The system font when absent. */+ font?: string;+ /** Dash and gap of grid lines in px. Solid when absent. The zero line is always solid. */+ gridDash?: [number, number];+ /** Width of line marks in px, where no field is on size. */+ lineWidth?: number;+ /** Width of the outline of point marks in px. */+ pointStrokeWidth?: number;+ /** Draws point marks filled, like circle marks. */+ pointFilled?: boolean;+ /** Rounds the far end of bars by this many px. */+ barRadius?: number;+}+const marks = {+ mark: '#4263eb',+ category: ['#4263eb', '#e88739', '#169b8d', '#b46bd0', '#dc6275', '#809432', '#3689ab', '#8c6a52'],+ ramp: ['#cddef2', '#1c4a96'],+ diverging: ['#e27026', '#e0e0e0', '#2b6ab2'],+};+export const lightTheme: Theme = { paper: '#ffffff', text: '#344054', muted: '#667085', line: '#d9dfe9', grid: '#eef1f6', zero: '#c2c9d6', ...marks };+export const darkTheme: Theme = { paper: '#0b0c0e', text: '#e4e7ec', muted: '#98a2b3', line: '#30353f', grid: '#1b1e25', zero: '#4b5363', ...marks };+const missing = '#c8cdd6';++const parsed = new Map<string, [number, number, number]>();+/** Red, green and blue of a hex or rgb() color. Anything else reads as the missing-value grey. */+export function rgb(color: string): [number, number, number] {+ let value = parsed.get(color);+ if (!value) {+ const hex = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(color.trim())?.[1];+ const full = hex?.length === 3 ? [...hex].map(c => c + c).join('') : hex;+ const numbers = full ? [0, 2, 4].map(i => parseInt(full.slice(i, i + 2), 16)) : (/^rgba?\(([^)]+)\)$/i.exec(color.trim())?.[1].split(/[\s,/]+/).slice(0, 3).map(Number) ?? []);+ value = numbers.length === 3 && numbers.every(Number.isFinite) ? [numbers[0], numbers[1], numbers[2]] : [200, 205, 214];+ if (parsed.size > 2000) parsed.clear();+ parsed.set(color, value);+ }+ return value;+}+/** The color at share t of a list of evenly spaced stops. */+function along(stops: string[], t: number): string {+ if (stops.length === 1) return stops[0];+ const at = Math.min(1, Math.max(0, t)) * (stops.length - 1), i = Math.min(stops.length - 2, Math.floor(at));+ const a = rgb(stops[i]), b = rgb(stops[i + 1]);+ return `rgb(${a.map((v, k) => Math.round(v + (b[k] - v) * (at - i))).join(',')})`;+}++/**+ * Color of a value on a continuous scale. A range on one side of zero runs along the ramp,+ * further from zero meaning further along it. A range that crosses zero runs along the+ * diverging stops with zero in the middle and both sides scaled by the larger magnitude.+ * `cells` picks the heat map stops where the theme has them.+ */+export function continuousColor(scale: ColorScale, value: number, theme: Theme = lightTheme, cells = false): string {+ if (!Number.isFinite(value)) return missing;+ const [low, high] = scale.domain;+ if (scale.diverging) {+ const reach = Math.max(Math.abs(low), Math.abs(high));+ return along(theme.diverging, .5 + value / reach / 2);+ }+ const t = high === low ? 1 : position(scale.domain, value, scale.type);+ // A value with no place on the scale, such as zero on a log scale, has no color either.+ if (Number.isNaN(t)) return missing;+ return along(cells && theme.heatmap?.length ? theme.heatmap : theme.ramp, high <= 0 ? 1 - t : t);+}++/** Fill of a record, for a categorical color field, a continuous one, or none. */+export function fillOf(field: FieldInstance | undefined, colors: Value[], scale: ColorScale | undefined, theme: Theme = lightTheme, cells = false): (record: Row) => string {+ if (!field) return () => theme.mark;+ if (scale) return record => { const raw = record[resultKey(field)]; return continuousColor(scale, raw == null ? NaN : Number(raw), theme, cells); };+ const map = new Map(colors.map((c, i) => [valueKey(c), theme.category[i % theme.category.length]]));+ return record => map.get(valueKey(record[field.field])) ?? missing;+}diff --git a/packages/worksheet-renderer/src/compiler.ts b/packages/worksheet-renderer/src/compiler.tsnew file mode 100644index 00000000..592bc819--- /dev/null+++ b/packages/worksheet-renderer/src/compiler.ts@@ -0,0 +1,173 @@+import { resultKey, type AxisBranch, type AxisExpr, type Binding, type Computation, type FieldInstance, type Plan, type QueryTask, type Ranking, type Row, type WorksheetSpec } from './types';++function expand(expr: AxisExpr): string[][] {+ if (expr.kind === 'empty') return [[]];+ if (expr.kind === 'field') return [[expr.instanceId]];+ if (!expr.items.length) throw new Error(`${expr.kind} must contain at least one expression.`);+ if (expr.kind === 'concat') {+ const branches = expr.items.flatMap(expand);+ if (branches.length > 256) throw new Error('V0 supports at most 256 axis branches. Reduce concatenated alternatives.');+ return branches;+ }+ return expr.items.reduce<string[][]>((left, item) => {+ const right = expand(item);+ if (left.length * right.length > 256) throw new Error('V0 supports at most 256 axis branches. Reduce crossed alternatives.');+ return left.flatMap(a => right.map(b => [...a, ...b]));+ }, [[]]);+}++export function compileAxis(expr: AxisExpr, instances: WorksheetSpec['instances'], axis: string): AxisBranch[] {+ return expand(expr).map((ids, order) => {+ if (new Set(ids).size !== ids.length) throw new Error('An axis branch cannot contain the same field instance twice.');+ const fields = ids.map(id => {+ const f = instances[id];+ if (!f || f.id !== id) throw new Error(`Unknown or inconsistent field instance: ${id}`);+ if (f.aggregate && f.display === 'discrete') throw new Error('Discrete aggregated fields are not supported in V0.');+ return f;+ });+ const position = fields[fields.length - 1];+ const facets = fields.slice(0, -1);+ if (facets.some(f => f.display !== 'discrete' || f.aggregate)) {+ throw new Error('Continuous fields must terminate an axis branch. Use concat for multiple measures.');+ }+ return { id: `${axis}:${JSON.stringify(ids)}:${order}`, facets, position, order };+ });+}++export function branchFields(branch: AxisBranch): FieldInstance[] {+ return branch.position ? [...branch.facets, branch.position] : branch.facets;+}+/**+ * The axis that carries a bar's length. With two continuous fields it is the aggregated+ * one; the other is a position along which bars are placed, such as a date.+ */+export function valueAxis(x?: FieldInstance, y?: FieldInstance): 'x' | 'y' | undefined {+ const xContinuous = x?.display === 'continuous', yContinuous = y?.display === 'continuous';+ if (xContinuous && yContinuous) return y!.aggregate && !x!.aggregate ? 'y' : 'x';+ return xContinuous ? 'x' : yContinuous ? 'y' : undefined;+}++/** Query tasks are deduplicated by grain, never by pane. No dependency on Vega. */+export function compileWorksheet(spec: WorksheetSpec): Plan {+ if (spec.kind !== 'worksheet' || spec.specVersion !== 2) throw new Error('Expected WorksheetSpec version 2.');+ const rows = compileAxis(spec.rows, spec.instances, 'row');+ const columns = compileAxis(spec.columns, spec.instances, 'column');+ const instance = (id: string, role: string) => {+ const f = spec.instances[id];+ if (!f) throw new Error(`Unknown field instance on ${role}: ${id}`);+ return f;+ };+ const details = (spec.detail ?? []).map(id => {+ const f = instance(id, 'Detail');+ if (f.aggregate || f.display !== 'discrete') throw new Error('Detail requires discrete, unaggregated field instances.');+ return f;+ });+ const encodings = [...details];+ if (spec.color) {+ const f = instance(spec.color, 'Color');+ if (f.aggregate && f.display !== 'continuous') throw new Error('Color takes a dimension or a continuous field, not a discrete aggregate.');+ if (spec.mark === 'boxplot' && f.display !== 'discrete') throw new Error('A box plot takes a dimension on color.');+ encodings.unshift(f);+ }+ if (spec.text) encodings.push(instance(spec.text, 'Text'));+ for (const [id, role] of [[spec.size, 'Size'], [spec.opacity, 'Opacity']] as const) {+ if (!id) continue;+ const f = instance(id, role);+ if (f.scale === 'time' && f.display === 'continuous') throw new Error(`${role} takes a dimension or a measure, not a date axis.`);+ encodings.push(f);+ }+ if (spec.shape) {+ const f = instance(spec.shape, 'Shape');+ if (f.aggregate || f.display !== 'discrete') throw new Error('Shape takes a dimension.');+ encodings.push(f);+ }+ if (spec.angle && spec.mark === 'arc') {+ const f = instance(spec.angle, 'Angle');+ if (f.display !== 'continuous' || f.scale === 'time') throw new Error('Angle takes a measure.');+ encodings.push(f);+ }+ const tasks = new Map<string, QueryTask>();+ const bindings: Binding[] = [];+ for (const row of rows) for (const column of columns) {+ const continuous = [row.position, column.position].filter(f => f?.display === 'continuous');+ if ((spec.mark === 'bar' || spec.mark === 'area') && (!continuous.length || (continuous.length === 2 && continuous.filter(f => f!.aggregate).length !== 1))) {+ throw new Error(`${spec.mark === 'bar' ? 'Bar' : 'Area'} marks need one measure axis. The other axis can be discrete, or an unaggregated continuous field such as a date.`);+ }+ if (spec.mark === 'arc' && continuous.length) throw new Error('Arc marks take dimensions on rows and columns. The measure goes on angle.');+ if (spec.mark === 'boxplot' && (continuous.length !== 1 || continuous[0]!.scale === 'time')) {+ throw new Error('A box plot needs exactly one measure axis. The other axis takes dimensions.');+ }+ const used = [...branchFields(row), ...branchFields(column), ...encodings];+ const groupBy = [...new Set(used.filter(f => !f.aggregate).map(f => f.field))].sort();+ // A box over an unaggregated field summarises source rows, so equal rows must not be merged.+ const raw = spec.mark === 'boxplot' && !continuous[0]!.aggregate;+ const id = JSON.stringify(groupBy);+ let task = tasks.get(id);+ if (!task) {+ task = { id, groupBy, measures: [], raw, payload: { workflow: [] } };+ tasks.set(id, task);+ }+ for (const f of used.filter(f => f.aggregate)) if (!task.measures.some(m => m.id === f.id)) task.measures.push(f);+ bindings.push({ row, column, taskId: id });+ }+ // A row limit applies to the records that become marks, never to the values that only order members.+ const limit = spec.limit && spec.limit.rows > 0 ? spec.limit : undefined;+ const limitBy = limit?.by ? instance(limit.by, 'Limit') : undefined;+ const limited = new Map<string, FieldInstance | undefined>();+ if (limit) for (const task of tasks.values()) {+ // An aggregate joins the query; a plain field can order the rows only where it is part of the grain.+ if (limitBy?.aggregate && !task.raw && !task.measures.some(m => m.id === limitBy.id)) task.measures.push(limitBy);+ limited.set(task.id, limitBy && (limitBy.aggregate ? !task.raw : task.groupBy.includes(limitBy.field)) ? limitBy : undefined);+ }+ // Members ordered by a measure need that measure per member, at the grain of the member's own+ // axis path. Where a query of that grain already exists the measure joins it.+ const rankings: Ranking[] = [];+ for (const [id, order] of Object.entries(spec.order ?? {})) {+ if (typeof order !== 'object' || Array.isArray(order)) continue;+ const { by: byId, direction = 'ascending' } = order as { by: string; direction?: 'ascending' | 'descending' };+ const f = instance(id, 'Order'), by = instance(byId, 'Order');+ if (f.display !== 'discrete') throw new Error(`Only the members of a dimension can be ordered by a measure: ${f.label}`);+ if (!by.aggregate || by.display !== 'continuous') throw new Error(`Members are ordered by an aggregated measure, not by ${by.label}.`);+ for (const branch of [...rows, ...columns]) {+ const fields = branchFields(branch), index = fields.indexOf(f);+ if (index < 0) continue;+ const parents = fields.slice(0, index);+ if (rankings.some(r => r.instanceId === id && r.parents.length === parents.length && r.parents.every((p, i) => p === parents[i]))) continue;+ const groupBy = [...new Set([...parents, f].map(p => p.field))].sort();+ const taskId = JSON.stringify(groupBy);+ let task = tasks.get(taskId);+ // A query that returns source rows or is cut by the limit cannot also carry complete totals.+ if (task?.raw || (task && limited.has(taskId))) task = undefined;+ const rankId = task ? taskId : `order:${taskId}`;+ if (!task && !(task = tasks.get(rankId))) tasks.set(rankId, task = { id: rankId, groupBy, measures: [], payload: { workflow: [] } });+ if (!task.measures.some(m => m.id === by.id)) task.measures.push(by);+ rankings.push({ instanceId: id, parents, by, direction, taskId: rankId });+ }+ }+ for (const task of tasks.values()) {+ // Alias collisions must fail before dispatch rather than overwrite grouped data.+ if (task.measures.some(m => task.groupBy.includes(resultKey(m)))) throw new Error('A source field conflicts with a reserved worksheet result alias.');+ task.payload = { workflow: [+ ...(spec.filters?.length ? [{ type: 'filter' as const, filters: spec.filters.map(f => ({ fid: f.field, rule: { type: 'one of' as const, value: f.values } })) }] : []),+ { type: 'view', query: [task.raw ? { op: 'raw', fields: task.groupBy } : { op: 'aggregate', groupBy: task.groupBy,+ measures: task.measures.map(m => ({ field: m.field, agg: m.aggregate!, asFieldKey: resultKey(m) })) }] },+ ...(limited.get(task.id) ? [{ type: 'sort' as const, by: [resultKey(limited.get(task.id)!)], sort: limit!.direction ?? 'ascending' }] : []),+ ], ...(limited.has(task.id) ? { limit: limit!.rows } : {}) };+ }+ return { spec, rows, columns, tasks: [...tasks.values()], bindings, rankings };+}++export async function executePlan(plan: Plan, computation: Computation, signal?: AbortSignal): Promise<Map<string, Row[]>> {+ const results = new Map<string, Row[]>();+ let next = 0;+ await Promise.all(Array.from({ length: Math.min(4, plan.tasks.length) }, async () => {+ while (next < plan.tasks.length) {+ signal?.throwIfAborted();+ const task = plan.tasks[next++];+ const rows = await computation(task.payload);+ signal?.throwIfAborted();+ results.set(task.id, rows);+ }+ }));+ return results;+}diff --git a/packages/worksheet-renderer/src/export.ts b/packages/worksheet-renderer/src/export.tsnew file mode 100644index 00000000..30b42850--- /dev/null+++ b/packages/worksheet-renderer/src/export.ts@@ -0,0 +1,43 @@+import { branchFields } from './compiler';+import { isRange } from './keys';+import { resultKey, type Plan, type Row } from './types';++/** The records behind the marks of a sheet, as a table a host can save. */+export interface ResultTable {+ columns: { key: string; label: string }[];+ rows: Row[];+}++/**+ * One table per query whose records are drawn. Queries that only order members are left out.+ * Columns read like a table: the dimensions first, in the order of rows, columns and then+ * the rest; after them the fields drawn as an axis without aggregation, such as a date or+ * the values of a box plot; last the aggregated measures. Rows are what the query+ * returned, in its order and after any limit.+ */+export function resultTables(plan: Plan, results: Map<string, Row[]>): ResultTable[] {+ const instances = Object.values(plan.spec.instances);+ const shelf = [...plan.rows, ...plan.columns].flatMap(branchFields).filter(f => !f.aggregate).map(f => f.field);+ return [...new Set(plan.bindings.map(binding => binding.taskId))].map(id => {+ const task = plan.tasks.find(t => t.id === id)!;+ const discrete = (field: string) => instances.some(f => f.field === field && !f.aggregate && f.display === 'discrete');+ const position = (field: string) => { const index = shelf.indexOf(field); return (discrete(field) ? 0 : 1e6) + (index < 0 ? shelf.length : index); };+ const dimensions = [...task.groupBy].sort((a, b) => position(a) - position(b));+ return {+ columns: [+ ...dimensions.map(field => ({ key: field, label: instances.find(f => f.field === field && !f.aggregate)?.label ?? field })),+ ...task.measures.map(f => ({ key: resultKey(f), label: f.label })),+ ],+ rows: results.get(id) ?? [],+ };+ });+}++const cell = (value: unknown): string => {+ const text = value == null ? '' : value instanceof Date ? value.toISOString() : isRange(value) ? value.join(' – ') : String(value);+ return /[",\r\n]/.test(text) ? `"${text.replace(/"/g, '""')}"` : text;+};+/** Comma-separated text with a header line. Values are written as stored; a bin is written as its two bounds. */+export function tableToCSV(table: ResultTable): string {+ return [table.columns.map(c => cell(c.label)), ...table.rows.map(row => table.columns.map(c => cell(row[c.key])))].map(line => line.join(',')).join('\n');+}diff --git a/packages/worksheet-renderer/src/formats.ts b/packages/worksheet-renderer/src/formats.tsnew file mode 100644index 00000000..ff0aafa8--- /dev/null+++ b/packages/worksheet-renderer/src/formats.ts@@ -0,0 +1,109 @@+/** The words the sheet writes itself. A host replaces them to match its language. */+export interface Words {+ share: string;+ upperWhisker: string; upperQuartile: string; median: string; lowerQuartile: string; lowerWhisker: string;+ records: string;+ /** The ends of a legend whose range differs from pane to pane. */+ low: string; high: string;+ /** What stands for a missing member. */+ missing: string;+ /** The end of a legend list that does not fit, for `count` entries left out. */+ more: (count: number) => string;+ /** Shown in place of a sheet whose queries returned nothing. */+ empty: string;+}+/**+ * How the sheet writes numbers, dates and its own words. Every part is optional; what is+ * left out follows `locale`.+ */+export interface Formats {+ /** A BCP 47 language tag such as 'en-US' or 'zh-CN'. English when absent. */+ locale?: string;+ /** A number in full: tooltips, labels and cells. */+ number?: (value: number) => string;+ /** A number on an axis or at the end of a legend. Follows `number` when that is given, else it is abbreviated. */+ tick?: (value: number) => string;+ /** A share between 0 and 1: the axis and tooltips of a normalized stack, the tooltip of a pie slice. */+ share?: (value: number) => string;+ /**+ * A moment, as milliseconds to be read in UTC: tooltips and labels of a time field, and the+ * members of a discrete time field that has no unit. Ticks of a time axis pick their own+ * format by the spacing between them and are not affected.+ */+ time?: (ms: number) => string;+ words?: Partial<Words>;+}+/** Formats with nothing left out. */+export interface Format {+ locale: string;+ number: (value: number) => string;+ tick: (value: number) => string;+ /**+ * The ticks of one axis, or the steps of one legend, written so that they can be told apart. The standard+ * tick keeps one decimal; where that makes two different values read the same, as on an axis of small+ * ratios, decimals are added. A format of the host's is used as it is.+ */+ ticks: (values: number[]) => string[];+ share: (value: number) => string;+ time: (ms: number) => string;+ /** Parts of a date for the ticks of a time axis, in UTC. */+ date: Record<'year' | 'month' | 'monthYear' | 'day' | 'time' | 'seconds', (ms: number) => string>;+ words: Words;+}+export const englishWords: Words = {+ share: 'Share', upperWhisker: 'Upper whisker', upperQuartile: 'Upper quartile', median: 'Median', lowerQuartile: 'Lower quartile', lowerWhisker: 'Lower whisker',+ records: 'Records', low: 'Low', high: 'High', missing: '(null)', more: count => `+${count} more`, empty: 'No data matches these filters.',+};+const day = 86_400_000;+const resolved = new WeakMap<Formats, Format>();+let fallback: Format | undefined;++/** Fills in what a host left out. The result is kept per input object, so resolving again is free. */+export function resolveFormats(formats?: Formats): Format {+ if (!formats) return fallback ??= build({});+ let made = resolved.get(formats);+ if (!made) resolved.set(formats, made = build(formats));+ return made;+}+function build(formats: Formats): Format {+ // A tag the runtime does not know falls back to English instead of failing the sheet.+ let locale = formats.locale ?? 'en';+ try { new Intl.NumberFormat(locale); } catch { locale = 'en'; }+ const plain = new Intl.NumberFormat(locale, { maximumFractionDigits: 2 });+ const compact = new Intl.NumberFormat(locale, { notation: 'compact', maximumFractionDigits: 1 });+ const percent = new Intl.NumberFormat(locale, { style: 'percent', maximumFractionDigits: 2 });+ const part = (options: Intl.DateTimeFormatOptions) => { const f = new Intl.DateTimeFormat(locale, { timeZone: 'UTC', ...options }); return (ms: number) => f.format(ms); };+ const date = part({ year: 'numeric', month: 'short', day: 'numeric' });+ const dateTime = part({ year: 'numeric', month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit', hourCycle: 'h23' });+ // A formatter of the host's must not take the sheet down with it on a value it cannot write.+ const safe = <T>(own: ((value: T) => string) | undefined, standard: (value: T) => string) => own ? (value: T) => { try { return String(own(value)); } catch { return standard(value); } } : standard;+ // Two decimals say little about a number below one, such as a ratio of 0.0342, so those keep three digits that count.+ const small = new Intl.NumberFormat(locale, { maximumSignificantDigits: 3 });+ const number = safe(formats.number, (value: number) => (value !== 0 && Math.abs(value) < 1 ? small : plain).format(value));+ const tick = safe(formats.tick, formats.number ? number : (value: number) => compact.format(value));+ const finer: Intl.NumberFormat[] = [];+ const ticks = (values: number[]) => {+ const labels = values.map(tick), distinct = new Set(values).size;+ if (formats.tick || formats.number || new Set(labels).size === distinct) return labels;+ for (let digits = 2; digits <= 8; digits++) {+ const format = finer[digits] ??= new Intl.NumberFormat(locale, { notation: 'compact', maximumFractionDigits: digits });+ const next = values.map(value => format.format(value));+ if (new Set(next).size === distinct) return next;+ }+ return labels;+ };+ return {+ locale,+ number,+ tick,+ ticks,+ share: safe(formats.share, (value: number) => percent.format(value)),+ // The day, with the time of day unless it is midnight.+ time: safe(formats.time, (ms: number) => Number.isFinite(ms) ? (ms % day === 0 ? date : dateTime)(ms) : ''),+ date: {+ year: part({ year: 'numeric' }), month: part({ month: 'short' }), monthYear: part({ month: 'short', year: 'numeric' }), day: part({ month: 'short', day: 'numeric' }),+ time: part({ hour: '2-digit', minute: '2-digit', hourCycle: 'h23' }), seconds: part({ hour: '2-digit', minute: '2-digit', second: '2-digit', hourCycle: 'h23' }),+ },+ words: { ...englishWords, ...formats.words },+ };+}diff --git a/packages/worksheet-renderer/src/index.ts b/packages/worksheet-renderer/src/index.tsnew file mode 100644index 00000000..84798440--- /dev/null+++ b/packages/worksheet-renderer/src/index.ts@@ -0,0 +1,17 @@+export * from './types';+export { compileAxis, compileWorksheet, executePlan } from './compiler';+export { metrics, setTextMeasure, tickScale } from './layout';+export { buildModel } from './model';+export type { Zoom } from './model';+export type { ScaleType } from './warp';+export { darkTheme, lightTheme } from './color';+export { englishWords, resolveFormats } from './formats';+export type { Formats, Words } from './formats';+export type { Theme } from './color';+export { buildScene, layers } from './scene';+export type { Layer, Primitive, Scene, SceneState, Viewport } from './scene';+export { sceneToPNG, sceneToSVG } from './vegaBackend';+export { resultTables, tableToCSV } from './export';+export type { ResultTable } from './export';+export { Worksheet } from './Worksheet';+export type { WorksheetHandle, WorksheetProps, WorksheetStatus } from './Worksheet';diff --git a/packages/worksheet-renderer/src/keys.ts b/packages/worksheet-renderer/src/keys.tsnew file mode 100644index 00000000..4412a562--- /dev/null+++ b/packages/worksheet-renderer/src/keys.ts@@ -0,0 +1,26 @@+import type { PathPart, Value } from './types';++export function typed(value: Value): [string, string | number | boolean | null] {+ if (value === null) return ['null', null];+ if (value === undefined) return ['undefined', null];+ if (typeof value === 'number' && !Number.isFinite(value)) return ['number', String(value)];+ if (value instanceof Date) return ['time', value.getTime()];+ if (isRange(value)) return ['range', value.join('|')];+ if (!['string', 'number', 'boolean'].includes(typeof value)) throw new Error('Worksheet V0 requires scalar dimension values.');+ return [typeof value, value];+}+export const valueKey = (value: Value) => JSON.stringify(typed(value));+export const pathKey = (axis: 'row' | 'column', path: PathPart[]) => JSON.stringify([axis, path.map(p => [p.instanceId, typed(p.value)])]);+// Without a sheet's formats to go by, as in an error message.+const rangeNumber = new Intl.NumberFormat('en', { maximumFractionDigits: 2 });+/** A bin, as binned fields return it: the lower and upper bound of the member. */+export function isRange(value: unknown): value is readonly number[] {+ return Array.isArray(value) && value.length > 0 && value.every(v => typeof v === 'number');+}+export const displayValue = (value: Value) => value == null ? '(null)' : isRange(value) ? value.map(v => rangeNumber.format(v)).join(' – ') : value instanceof Date ? (Number.isNaN(value.getTime()) ? '(invalid date)' : value.toISOString().replace(/T00:00:00\.000Z$/, '')) : String(value);+export function compareValue(a: Value, b: Value): number {+ if (typeof a === 'number' && typeof b === 'number') return a - b;+ if (a instanceof Date && b instanceof Date) return a.getTime() - b.getTime();+ if (isRange(a) && isRange(b)) return a[0] - b[0] || (a[1] ?? 0) - (b[1] ?? 0);+ return displayValue(a).localeCompare(displayValue(b), undefined, { numeric: true }) || valueKey(a).localeCompare(valueKey(b));+}diff --git a/packages/worksheet-renderer/src/layout.ts b/packages/worksheet-renderer/src/layout.tsnew file mode 100644index 00000000..6eb9a9d8--- /dev/null+++ b/packages/worksheet-renderer/src/layout.ts@@ -0,0 +1,255 @@+import { pathKey, valueKey } from './keys';+import type { AxisBranch, AxisGroup, AxisLayout, AxisLeaf, AxisScale, HeaderSpan, PathPart, Value, WorksheetSpec } from './types';++/** The only place layout sizes are defined. CSS px. */+export const metrics = {+ bandWidth: 40,+ bandHeight: 24,+ /** Member width when the marks are numbers rather than shapes. */+ textCellWidth: 76,+ legendMinWidth: 96,+ legendMaxWidth: 190,+ slotWidth: 200,+ slotHeight: 160,+ /** The least a continuous axis slot gets, whatever a host asks for and however little room there is. */+ slotMinWidth: 80,+ slotMinHeight: 60,+ /** Side of the cell that holds one pie. */+ pieSize: 160,+ /** The least a pie gets when the sheet is stretched to its window. */+ pieMinSize: 96,+ headerHeight: 24,+ captionHeight: 22,+ xAxisHeight: 40,+ headerMinWidth: 56,+ headerMaxWidth: 180,+ headerPadding: 6,+ rotatedLabelMax: 96,+ /** Inset of a continuous scale inside its slot, at the domain start and end. */+ scalePadStart: 2,+ scalePadEnd: 12,+ fontSize: 11,+ /** Share of a member step covered by a bar. */+ barFill: 0.7,+};++export interface LeafSizes { band: number; continuous: number }+export function leafSizes(spec: WorksheetSpec): { row: LeafSizes; column: LeafSizes } {+ // A pie fills a cell of its own, so every position is as large as an axis slot.+ if (spec.mark === 'arc') {+ const height = Math.max(48, spec.pane?.height ?? metrics.pieSize), width = Math.max(48, spec.pane?.width ?? metrics.pieSize);+ return { row: { band: height, continuous: height }, column: { band: width, continuous: width } };+ }+ return {+ row: { band: Math.max(12, spec.band?.height ?? metrics.bandHeight), continuous: Math.max(metrics.slotMinHeight, spec.pane?.height ?? metrics.slotHeight) },+ column: { band: Math.max(12, spec.band?.width ?? (spec.mark === 'text' ? metrics.textCellWidth : metrics.bandWidth)), continuous: Math.max(metrics.slotMinWidth, spec.pane?.width ?? metrics.slotWidth) },+ };+}+/**+ * The least a stretched slot gets before the sheet scrolls instead. A pane size the host set is+ * that least size; without one a slot may get smaller than it is in a sheet that is not stretched.+ */+export function leafFloors(spec: WorksheetSpec): { row: number; column: number } {+ if (spec.mark === 'arc') {+ const side = Math.max(48, Math.min(spec.pane?.width ?? metrics.pieMinSize, spec.pane?.height ?? metrics.pieMinSize));+ return { row: side, column: side };+ }+ return { row: Math.max(metrics.slotMinHeight, spec.pane?.height ?? 0), column: Math.max(metrics.slotMinWidth, spec.pane?.width ?? 0) };+}++export type TextMeasure = (text: string, fontSize: number, fontWeight: number, font: string) => number;+export const defaultFont = 'system-ui, sans-serif';+let measure: TextMeasure | undefined;+let font = defaultFont;+/**+ * The font every width is measured in until the next call. Layout and scene building are+ * synchronous and each sets it on entry, so two sheets with different fonts do not mix.+ */+export function setFont(next?: string) { font = next || defaultFont; }+const measured = new Map<string, number>();+/**+ * Installs a real text measurer, for example a canvas context in the browser. Layout and+ * every backend read widths through textWidth, so they always agree. Without a measurer,+ * as in Node, widths are estimated from character counts.+ */+export function setTextMeasure(next?: TextMeasure) { measure = next; measured.clear(); }+export function textWidth(text: string, fontSize = metrics.fontSize, fontWeight = 400): number {+ if (measure) {+ const key = `${font}|${fontWeight}|${fontSize}|${text}`;+ let width = measured.get(key);+ if (width === undefined) {+ if (measured.size > 50_000) measured.clear();+ measured.set(key, width = measure(text, fontSize, fontWeight, font));+ }+ return width;+ }+ let width = 0;+ for (const char of text) width += char.codePointAt(0)! > 0x2e7f ? fontSize : fontSize * 0.58;+ return width;+}+export function fitText(text: string, width: number, fontSize = metrics.fontSize, fontWeight = 400): string {+ if (textWidth(text, fontSize, fontWeight) <= width) return text;+ let result = '';+ let used = textWidth('…', fontSize, fontWeight);+ for (const char of text) {+ used += textWidth(char, fontSize, fontWeight);+ if (used > width) break;+ result += char;+ }+ return result ? `${result}…` : '';+}++/**+ * Ticks at multiples of 1, 2 or 5 times a power of ten. The domain stays the data range,+ * so marks use the whole slot and the last tick may sit below the maximum.+ */+export function tickScale(min: number, max: number, pixels: number, gap: number, least = 2): AxisScale {+ if (min === max) { if (min > 0) min = 0; else if (min < 0) max = 0; else max = 1; }+ // At least `least` steps across the range, however little room there is.+ const raw = (max - min) / Math.max(least, Math.floor(pixels / gap));+ const power = 10 ** Math.floor(Math.log10(raw));+ const unit = raw / power;+ // Geometric midpoints between 1, 2, 5 and 10 pick the step nearest to the wanted spacing.+ const step = (unit < Math.SQRT2 ? 1 : unit < Math.sqrt(10) ? 2 : unit < Math.sqrt(50) ? 5 : 10) * power;+ const ticks: number[] = [];+ for (let i = Math.ceil(min / step - 1e-9); i <= Math.floor(max / step + 1e-9); i++) ticks.push(Number((i * step).toPrecision(12)));+ return { domain: [min, max], ticks };+}++export interface LeafDraft {+ id: string;+ groupId: string;+ branch: AxisBranch;+ path: PathPart[];+ kind: AxisLeaf['kind'];+}++// Orders leaves as a tree walk. Children of a node are bucketed by field, buckets follow+// branch order, members inside a bucket follow value order. This is a total order for any+// mix of concatenated branches, and it keeps the leaves under one header contiguous.+/** `parent` is the header path above the two members, which a per-parent order needs. */+export type MemberCompare = (instanceId: string, a: Value, b: Value, parent: PathPart[]) => number;+function orderLeaves(drafts: LeafDraft[], compare: MemberCompare): LeafDraft[] {+ const visit = (items: LeafDraft[], level: number): LeafDraft[] => {+ const buckets = new Map<string, { rank: number; terminal: boolean; items: LeafDraft[] }>();+ for (const item of items) {+ const part = item.path[level];+ // The member level of a band branch stays with its branch so that a pane's members are contiguous.+ const own = part && item.kind === 'band' && level === item.path.length - 1;+ const key = part ? `m:${part.instanceId}${own ? `:${item.branch.order}` : ''}` : `t:${item.branch.order}`;+ const bucket = buckets.get(key) ?? { rank: item.branch.order, terminal: !part, items: [] };+ bucket.rank = Math.min(bucket.rank, item.branch.order);+ bucket.items.push(item);+ buckets.set(key, bucket);+ }+ return [...buckets.values()].sort((a, b) => a.rank - b.rank || Number(a.terminal) - Number(b.terminal)).flatMap(bucket => {+ if (bucket.terminal) return bucket.items;+ const members = new Map<string, LeafDraft[]>();+ for (const item of bucket.items) {+ const key = valueKey(item.path[level].value);+ const list = members.get(key) ?? [];+ list.push(item);+ members.set(key, list);+ }+ const field = bucket.items[0].path[level].instanceId, parent = bucket.items[0].path.slice(0, level);+ return [...members.values()].sort((a, b) => compare(field, a[0].path[level].value, b[0].path[level].value, parent)).flatMap(list => visit(list, level + 1));+ });+ };+ return visit(drafts, 0);+}++export function buildAxis(axis: 'row' | 'column', drafts: Iterable<LeafDraft>, compare: MemberCompare, sizes: LeafSizes, instances: WorksheetSpec['instances']): AxisLayout {+ const leaves: AxisLeaf[] = [];+ const groups: AxisGroup[] = [];+ let offset = 0;+ for (const draft of orderLeaves([...drafts], compare)) {+ const size = draft.kind === 'continuous' ? sizes.continuous : sizes.band;+ let group = groups[groups.length - 1];+ if (!group || group.id !== draft.groupId) {+ group = { id: draft.groupId, index: groups.length, branch: draft.branch, path: draft.path.slice(0, draft.branch.facets.length), start: leaves.length, end: leaves.length, offset, size: 0 };+ groups.push(group);+ }+ leaves.push({ id: draft.id, index: leaves.length, branch: draft.branch, path: draft.path, kind: draft.kind, group: group.index, offset, size });+ group.end = leaves.length;+ group.size += size;+ offset += size;+ }+ const depth = Math.max(0, ...leaves.map(leaf => leaf.path.length));+ const levels: HeaderSpan[][] = [];+ const captions: string[] = [];+ for (let level = 0; level < depth; level++) {+ const spans: HeaderSpan[] = [];+ const names = new Set<string>();+ for (const leaf of leaves) {+ const part = leaf.path[level];+ if (!part) continue;+ names.add(instances[part.instanceId].label);+ const key = pathKey(axis, leaf.path.slice(0, level + 1));+ const open = spans[spans.length - 1];+ if (open && open.end === leaf.index && open.key === key) open.end = leaf.index + 1;+ else spans.push({ key, part, start: leaf.index, end: leaf.index + 1 });+ }+ levels.push(spans);+ captions.push([...names].join(', '));+ }+ return { axis, leaves, groups, levels, captions, size: offset };+}++/** Gives every leaf the size `sizeOf` returns and moves the leaves and groups after it along. */+export function resizeAxis(layout: AxisLayout, sizeOf: (leaf: AxisLeaf) => number) {+ let offset = 0;+ for (const group of layout.groups) {+ group.offset = offset;+ for (let i = group.start; i < group.end; i++) {+ const leaf = layout.leaves[i];+ leaf.offset = offset;+ leaf.size = sizeOf(leaf);+ offset += leaf.size;+ }+ group.size = offset - group.offset;+ }+ layout.size = offset;+}+/** Stretches or squeezes every leaf by the same factor, so members keep one shared step. */+export function scaleAxis(layout: AxisLayout, factor: number) {+ resizeAxis(layout, leaf => leaf.size * factor);+}+/** What the axis measures with every continuous slot at `floor`: the least room it can be stretched into. */+export function leastSize(layout: AxisLayout, floor: number): number {+ return layout.leaves.reduce((sum, leaf) => sum + (leaf.kind === 'continuous' ? floor : leaf.size), 0);+}+/**+ * Shares `room` among the continuous slots, after the member steps have taken theirs. The steps+ * keep their size whatever the room is. No slot gets less than `floor`, so an axis that does not+ * fit comes out longer than the room.+ */+export function stretchAxis(layout: AxisLayout, room: number, floor: number) {+ let fixed = 0, slots = 0;+ for (const leaf of layout.leaves) { if (leaf.kind === 'continuous') slots++; else fixed += leaf.size; }+ if (!slots) return;+ const size = Math.max(floor, (room - fixed) / slots);+ resizeAxis(layout, leaf => leaf.kind === 'continuous' ? size : leaf.size);+}++function lowerBound(length: number, before: (index: number) => boolean): number {+ let low = 0;+ let high = length;+ while (low < high) {+ const middle = (low + high) >> 1;+ if (before(middle)) low = middle + 1; else high = middle;+ }+ return low;+}+/** Half-open range of leaves that intersect the logical interval [from, to). */+export function leafRange(layout: AxisLayout, from: number, to: number): [number, number] {+ const { leaves } = layout;+ const start = lowerBound(leaves.length, i => leaves[i].offset + leaves[i].size <= from);+ const end = lowerBound(leaves.length, i => leaves[i].offset < to);+ return [start, Math.max(start, end)];+}+/** Spans that intersect the half-open leaf range. */+export function spansIn(spans: HeaderSpan[], start: number, end: number): HeaderSpan[] {+ const first = lowerBound(spans.length, i => spans[i].end <= start);+ const last = lowerBound(spans.length, i => spans[i].start < end);+ return spans.slice(first, last);+}diff --git a/packages/worksheet-renderer/src/model.ts b/packages/worksheet-renderer/src/model.tsnew file mode 100644index 00000000..788c79f2--- /dev/null+++ b/packages/worksheet-renderer/src/model.ts@@ -0,0 +1,539 @@+import { compareValue, pathKey, typed, valueKey } from './keys';+import { resolveFormats, type Format, type Formats } from './formats';+import { buildAxis, leafFloors, leafSizes, leastSize, metrics, resizeAxis, scaleAxis, setFont, stretchAxis, tickScale, textWidth, type LeafDraft, type MemberCompare } from './layout';+import { logTicks, position } from './warp';+import { memberLabel, positionValue, timeScale } from './time';+import { branchFields, valueAxis } from './compiler';+import { legendTitleHeight, levelOf, type ChannelScale, type LegendBlock } from './channels';+import { resultKey, type AxisBranch, type AxisLayout, type AxisLeaf, type ColorScale, type Frame, type Pane, type PaneMark, type Plan, type Row, type ScaleOptions, type Value, type WorksheetModel, type WorksheetSpec } from './types';++function draft(axis: 'row' | 'column', branch: AxisBranch, record: Row): LeafDraft {+ const facets = branch.facets.map(f => ({ instanceId: f.id, value: record[f.field] as Value }));+ const groupId = JSON.stringify([branch.id, pathKey(axis, facets)]);+ if (branch.position?.display !== 'discrete') return { id: groupId, groupId, branch, path: facets, kind: branch.position ? 'continuous' : 'single' };+ const path = [...facets, { instanceId: branch.position.id, value: record[branch.position.field] as Value }];+ return { id: JSON.stringify([branch.id, pathKey(axis, path)]), groupId, branch, path, kind: 'band' };+}++/** How marks that share a position pile up. Only bars and areas do. */+export function stackMode(plan: Plan): false | 'stack' | 'normalize' | 'center' {+ const { mark, stack } = plan.spec;+ if ((mark !== 'bar' && mark !== 'area') || stack === false) return false;+ return stack === 'normalize' || stack === 'center' ? stack : 'stack';+}++interface CellItem { record: Row; row: string; column: string }+/** Value at share p of an ascending list, interpolated between neighbours. */+const quantile = (sorted: number[], p: number) => {+ const at = (sorted.length - 1) * p, i = Math.floor(at);+ return sorted[i] + (sorted[Math.min(i + 1, sorted.length - 1)] - sorted[i]) * (at - i);+};++// Orders the records of one pane by series and gives each its interval on the measure axis.+// Stacking accumulates per member, positive and negative values apart.+// slots places the members of the color field side by side inside a member step; box plots use it.+function paneMarks(items: CellItem[], rowBranch: AxisBranch, columnBranch: AxisBranch, plan: Plan, rowIndex: Map<string, number>, columnIndex: Map<string, number>, slots?: Map<string, number>): PaneMark[] {+ const x = columnBranch.position;+ const y = rowBranch.position;+ const axis = valueAxis(x, y);+ const measure = axis === 'x' ? x : axis === 'y' ? y : undefined;+ // Bars placed along a continuous field stack per position, not per pane.+ const other = axis === 'x' ? y : x;+ const along = other?.display === 'continuous' ? other : undefined;+ // Only dimensions split a pane into series. A measure on color tints the marks without dividing them.+ const series = [plan.spec.color, ...(plan.spec.detail ?? []), plan.spec.size, plan.spec.opacity, plan.spec.shape, plan.spec.text]+ .filter((id): id is string => Boolean(id)).map(id => plan.spec.instances[id]).filter(f => f.display === 'discrete');+ const sorted = [...items].sort((a, b) => {+ for (const f of series) {+ const cmp = compareValue(a.record[f.field], b.record[f.field]);+ if (cmp) return cmp;+ }+ return 0;+ });+ const place = (item: CellItem) => ({ record: item.record, row: rowIndex.get(item.row)!, column: columnIndex.get(item.column)! });+ if (plan.spec.mark === 'arc') {+ // One pie per cell. A slice is its share of the cell's total; a record without a positive value gets none.+ const angle = plan.spec.angle ? plan.spec.instances[plan.spec.angle] : undefined;+ const share = (record: Row) => { const value = angle ? positionValue(angle, record) : 1; return value > 0 ? value : NaN; };+ const cell = (item: CellItem) => `${item.row}\n${item.column}`;+ const sums = new Map<string, number>();+ for (const item of sorted) { const value = share(item.record); if (value > 0) sums.set(cell(item), (sums.get(cell(item)) ?? 0) + value); }+ const turned = new Map<string, number>();+ return sorted.map(item => {+ const value = share(item.record), key = cell(item);+ if (!(value > 0)) return { ...place(item), start: NaN, end: NaN };+ const start = turned.get(key) ?? 0, end = start + value / sums.get(key)!;+ turned.set(key, end);+ return { ...place(item), start, end };+ });+ }+ if (plan.spec.mark === 'boxplot') {+ // One box per member and color. Detail fields only decide what one record is.+ const color = series.find(f => f.id === plan.spec.color);+ const kept = [...branchFields(rowBranch), ...branchFields(columnBranch), ...(color ? [color] : [])].filter(f => f.display === 'discrete');+ const boxes = new Map<string, CellItem[]>();+ for (const item of sorted) {+ const key = JSON.stringify([item.row, item.column, color ? valueKey(item.record[color.field]) : '']);+ const box = boxes.get(key) ?? [];+ box.push(item);+ boxes.set(key, box);+ }+ const marks: PaneMark[] = [];+ for (const box of boxes.values()) {+ const values = box.map(item => positionValue(measure!, item.record));+ const finite = values.filter(Number.isFinite).sort((a, b) => a - b);+ if (!finite.length) continue;+ const q1 = quantile(finite, .25), median = quantile(finite, .5), q3 = quantile(finite, .75), reach = 1.5 * (q3 - q1);+ const low = finite.find(v => v >= q1 - reach)!, high = finite.filter(v => v <= q3 + reach).pop()!;+ const slot: [number, number] | undefined = color && slots ? [slots.get(valueKey(box[0].record[color.field])) ?? 0, slots.size] : undefined;+ const record = { ...Object.fromEntries(kept.map(f => [f.field, box[0].record[f.field]])), [resultKey(measure!)]: median };+ marks.push({ ...place(box[0]), record, start: low, end: high, box: { low, q1, median, q3, high, count: finite.length }, slot });+ box.forEach((item, index) => {+ if (values[index] < low || values[index] > high) marks.push({ ...place(item), start: values[index], end: values[index], outlier: true, slot });+ });+ }+ return marks;+ }+ const mode = stackMode(plan);+ // Marks pile up where they share a member, or a position along a continuous field.+ const pile = (item: CellItem) => (axis === 'x' ? item.row : item.column) + (along ? `|${positionValue(along, item.record)}` : '');+ const valueOf = (item: CellItem) => measure ? positionValue(measure, item.record) : 0;+ if (mode === 'normalize' || mode === 'center') {+ // Both pile magnitudes in one direction, so a negative value takes room like a positive one.+ const sums = new Map<string, number>();+ for (const item of sorted) { const value = valueOf(item); if (Number.isFinite(value)) sums.set(pile(item), (sums.get(pile(item)) ?? 0) + Math.abs(value)); }+ const reached = new Map<string, number>();+ return sorted.map(item => {+ const value = valueOf(item), key = pile(item), sum = sums.get(key) ?? 0;+ // A pile that adds up to nothing has no shares to show.+ if (!Number.isFinite(value) || (mode === 'normalize' && !(sum > 0))) return { ...place(item), start: NaN, end: NaN };+ const size = mode === 'normalize' ? Math.abs(value) / sum : Math.abs(value);+ const start = reached.get(key) ?? (mode === 'center' ? -sum / 2 : 0);+ reached.set(key, start + size);+ return { ...place(item), start, end: start + size, ...(mode === 'normalize' ? { share: size } : {}) };+ });+ }+ const totals = new Map<string, [number, number]>();+ const stack = Boolean(mode);+ const marks = sorted.map(item => {+ const leaves = place(item);+ const value = valueOf(item);+ if (!Number.isFinite(value)) return { ...leaves, start: NaN, end: NaN };+ if (!stack) return { ...leaves, start: 0, end: value };+ const key = pile(item);+ const total = totals.get(key) ?? [0, 0];+ const sign = value >= 0 ? 0 : 1;+ const start = total[sign];+ total[sign] += value;+ totals.set(key, total);+ return { ...leaves, start, end: total[sign] };+ });+ // Bars that overlap are painted longest first, so a short one is not hidden behind a long one.+ if (!stack && plan.spec.mark === 'bar') marks.sort((a, b) => (Math.abs(b.end) || 0) - (Math.abs(a.end) || 0));+ return marks;+}++// Ranges come from the complete result, never from the visible window. A range is keyed+// by measure and by a scope along the axis itself, so every pane in one row or column+// shares it and the axis can be drawn once on the table edge.+// The ranges are read from the records once. What comes back places the ticks for the sizes the+// slots have at that moment, and is called again whenever the slots are resized.+function assignScales(layout: AxisLayout, axis: 'x' | 'y', panes: Pane[], plan: Plan, format: Format, zoom?: Zoom): () => void {+ const set = plan.spec.scaleScope;+ const scope = (typeof set === 'object' ? set[axis === 'x' ? 'columns' : 'rows'] : set) ?? 'shared';+ const keyOf = (leaf: AxisLeaf) => {+ const id = leaf.branch.position!.id;+ return scope === 'independent' ? leaf.id : scope === 'prefix' ? JSON.stringify([id, pathKey(layout.axis, leaf.path.slice(0, 1))]) : id;+ };+ const extents = new Map<string, [number, number]>();+ const positions = new Map<string, Set<number>>();+ // Bars and areas run from where their pile has reached to where they end, boxes from whisker to+ // whisker. Their axis covers those intervals, not the values of single records.+ const spans = plan.spec.mark === 'bar' || plan.spec.mark === 'area' || plan.spec.mark === 'boxplot';+ const bars = plan.spec.mark === 'bar';+ const shares = stackMode(plan) === 'normalize';+ const shared = new Set<string>();+ // The axis settings of this shelf. They do not apply to time axes.+ const options = plan.spec.scales?.[axis === 'x' ? 'columns' : 'rows'];+ for (const pane of panes) {+ const group = axis === 'x' ? pane.column : pane.row;+ const f = group.branch.position;+ if (!f || f.display !== 'continuous') continue;+ const key = keyOf(layout.leaves[group.start]);+ const time = f.scale === 'time';+ const log = !time && options?.type === 'log';+ // A value axis starts from zero. A date axis has no zero worth showing, and a log axis has no zero at all.+ const extent = extents.get(key) ?? (time || log || f.zero === false ? [Infinity, -Infinity] : [0, 0]);+ const carriesValue = valueAxis(pane.column.branch.position, pane.row.branch.position) === axis;+ const distinct = bars && !carriesValue ? positions.get(key) ?? new Set<number>() : undefined;+ for (const mark of pane.marks) {+ const raw = mark.record[resultKey(f)];+ const value = positionValue(f, mark.record);+ // A number that is not finite, such as the logarithm of zero, is a missing value and leaves no mark.+ // Anything that is not a number at all means the field is not continuous, which is the caller's mistake.+ if (raw != null && (time ? Number.isNaN(value) : typeof raw !== 'number')) {+ throw new Error(time ? `Time field ${f.label} returned a value that is not a date: ${String(raw)}`+ : `Continuous field ${f.label} returned a value that is not a number: ${String(raw)}`);+ }+ if (Number.isFinite(value)) distinct?.add(value);+ for (const v of spans && carriesValue ? [mark.start, mark.end] : [value]) {+ if (Number.isFinite(v) && !(log && v <= 0)) { extent[0] = Math.min(extent[0], v); extent[1] = Math.max(extent[1], v); }+ }+ }+ extents.set(key, extent);+ if (shares && carriesValue) shared.add(key);+ if (distinct) positions.set(key, distinct);+ }+ return () => { for (const leaf of layout.leaves) {+ if (leaf.kind !== 'continuous') continue;+ const key = keyOf(leaf);+ const time = leaf.branch.position!.scale === 'time';+ let [min, max] = extents.get(key) ?? [0, 1];+ if (min > max) [min, max] = time ? [0, 86_400_000] : [0, 1];+ // Bars along this axis need half a step of room at both ends, or the outer ones are cut in half.+ const sorted = [...positions.get(key) ?? []].sort((a, b) => a - b);+ const step = sorted.length > 1 ? Math.min(...sorted.slice(1).map((v, i) => v - sorted[i])) : undefined;+ if (step) { min -= step / 2; max += step / 2; }+ const type = time ? undefined : options?.type;+ // Ends of the range set by hand win over the data.+ const fixed = !time && (options?.min !== undefined || options?.max !== undefined);+ if (!time && options?.min !== undefined) min = options.min;+ if (!time && options?.max !== undefined) max = options.max;+ if (type === 'log') {+ // Only positive values have a place. A range that reaches zero starts three powers of ten below its end.+ if (!(max > 0)) max = 1;+ if (!(min > 0) || min >= max) min = min === max && min > 0 ? min / 10 : max / 1000;+ if (min === max) max = min * 10;+ } else if (!time && min >= max && fixed) max = min + 1;+ const pixels = leaf.size - metrics.scalePadStart - metrics.scalePadEnd;+ // Every axis carries its labels: dates from the time scale, shares in percent, other numbers as ticks.+ const make = (gap: number, least = 2) => {+ const scale = time ? timeScale(min, max, pixels, gap, format) : tickScale(min, max, pixels, gap, least);+ if (type === 'log') scale.ticks = logTicks(min, max, Math.max(2, Math.floor(pixels / gap))) ?? scale.ticks;+ if (!time) scale.labels = shared.has(key) ? scale.ticks.map(format.share) : format.ticks(scale.ticks);+ return scale;+ };+ const at = (scale: { domain: [number, number] }, tick: number) => position(scale.domain, tick, type) * pixels;+ let gap = axis === 'x' ? (time ? 62 : 46) : 30;+ // The range the data asks for, and in its place the one the viewer zoomed or panned to.+ const id = `${axis}|${key}`;+ const full = make(gap).domain;+ const zoomed = zoom?.[id];+ if (zoomed && zoomed[0] < zoomed[1] && zoomed.every(Number.isFinite)) [min, max] = zoomed;+ let scale = make(gap);+ // Labels along a horizontal axis must not run into each other. A format that writes long labels gets fewer ticks.+ for (let round = 0; axis === 'x' && round < 3 && scale.ticks.length > 1; round++) {+ const widest = Math.max(...scale.labels!.map(label => textWidth(label, 10)));+ // The two closest ticks decide; on an axis that is not linear they are not the first two.+ const spacing = Math.min(...scale.ticks.slice(1).map((tick, i) => at(scale, tick) - at(scale, scale.ticks[i])));+ if (widest + 10 <= spacing) break;+ // Where even two steps are too many, one step keeps a label at each end of the range.+ scale = make(gap = Math.max(gap * 1.5, widest + 14), 1);+ }+ // In a slot too narrow even for that, a label that would run into the one before it is left blank. Its tick stays.+ // The same goes for a vertical axis whose ticks crowd together, as near the start of a square root axis.+ if (scale.labels && (axis === 'x' || type)) {+ let free = -Infinity;+ scale.labels = scale.labels.map((label, i) => {+ const center = at(scale, scale.ticks[i]), half = axis === 'x' ? textWidth(label, 10) / 2 : 5;+ if (center - half < free) return '';+ free = center + half + (axis === 'x' ? 6 : 2);+ return label;+ });+ }+ leaf.scale = { ...scale, step, key: id, full, ...(type && type !== 'linear' ? { type } : {}), ...(fixed ? { fixed } : {}) };+ } };+}++// The range of a continuous channel: the extent of the data, with the ends set by hand in their place.+function continuousRange(extent: [number, number], options?: ScaleOptions): { domain?: [number, number]; type?: ScaleOptions['type']; fixed?: boolean } {+ const fixed = options?.min !== undefined || options?.max !== undefined;+ let [low, high] = extent[0] <= extent[1] ? extent : [NaN, NaN];+ if (options?.min !== undefined) low = options.min;+ if (options?.max !== undefined) high = options.max;+ const type = options?.type && options.type !== 'linear' ? options.type : undefined;+ // A log range needs a positive start.+ if (type === 'log' && !(low > 0) && high > 0) low = high / 1000;+ return { domain: Number.isFinite(low) && Number.isFinite(high) && low <= high ? [low, high] : undefined, ...(type ? { type } : {}), ...(fixed ? { fixed } : {}) };+}++// What explains each channel, in the order the strip shows it: color, size, opacity, shape.+function buildLegends(spec: WorksheetSpec, colors: Value[], colorScale: ColorScale | undefined, channels: WorksheetModel['channels'], format: Format): LegendBlock[] {+ const blocks: LegendBlock[] = [];+ const list = (channel: LegendBlock['channel'], title: string, entries: LegendBlock['entries'], step = 18) =>+ blocks.push({ channel, title, kind: 'list', entries, step, height: legendTitleHeight + entries.length * step + 6 });+ const color = spec.color ? spec.instances[spec.color] : undefined;+ // A channel whose range differs from pane to pane has no numbers to show, only which end is which.+ const ends = [format.words.low, format.words.high];+ if (color && colorScale) blocks.push({ channel: 'color', title: color.label, kind: 'ramp', step: 0, height: 64,+ entries: (spec.scales?.color?.independent ? ends : format.ticks(colorScale.domain)).map((label, level) => ({ label, level })) });+ else if (color) list('color', color.label, colors.map((value, i) => ({ label: memberLabel(color, value, format), level: i })));+ for (const channel of ['size', 'opacity', 'shape'] as const) {+ const scale = channels[channel];+ if (!scale) continue;+ if (scale.members) {+ list(channel, scale.field.label, scale.members.map((value, i) => ({ label: memberLabel(scale.field, value, format), level: channel === 'shape' ? i : (i + 1) / scale.members!.length })), channel === 'size' ? 22 : 18);+ } else if (scale.domain) {+ // The ends of the range and the middle are enough to read a size or an opacity against.+ const [low, high] = scale.domain;+ const own = spec.scales?.[channel as 'size' | 'opacity']?.independent;+ const samples = own ? [0, 1] : low === high ? [low] : [low, (low + high) / 2, high];+ list(channel, scale.field.label, own ? samples.map((level, i) => ({ label: ends[i], level }))+ : format.ticks(samples).map((label, i) => ({ label, level: levelOf(scale, samples[i], channel === 'size') })), channel === 'size' ? 22 : 18);+ }+ }+ return blocks;+}+function legendWidth(blocks: LegendBlock[]): number {+ if (!blocks.length) return 0;+ const widest = Math.max(...blocks.map(block => Math.max(textWidth(block.title, metrics.fontSize, 600),+ block.kind === 'ramp' ? 110 : Math.max(0, ...block.entries.map(entry => textWidth(entry.label))) + (block.channel === 'size' ? 26 : 18))));+ return Math.ceil(Math.min(metrics.legendMaxWidth, Math.max(metrics.legendMinWidth, widest + 24)));+}++function buildFrame(rows: AxisLayout, columns: AxisLayout, spec: WorksheetSpec, right: number, format: Format, headerBudget?: number): Frame {+ const pad = metrics.headerPadding * 2;+ const widest = (layout: AxisLayout, level: number) => Math.max(0, ...layout.levels[level].map(span => textWidth(memberLabel(spec.instances[span.part.instanceId], span.part.value, format))));+ const rowHeaderWidths = rows.levels.map((_, level) => Math.min(metrics.headerMaxWidth,+ Math.max(metrics.headerMinWidth, Math.ceil(Math.max(widest(rows, level), textWidth(rows.captions[level], metrics.fontSize, 600)) + pad))));+ // Deep row headers must not push the marks out of a narrow window. Over budget, every level+ // gives up width in proportion and its labels are cut with an ellipsis; no level is dropped.+ const headerTotal = rowHeaderWidths.reduce((a, b) => a + b, 0);+ if (headerBudget && headerTotal > headerBudget) {+ const floor = metrics.headerMinWidth / 2;+ const scale = Math.max(headerBudget, floor * rowHeaderWidths.length) / headerTotal;+ rowHeaderWidths.forEach((width, level) => { rowHeaderWidths[level] = Math.max(floor, Math.floor(width * scale)); });+ }+ const tickWidth = Math.max(0, ...rows.leaves.flatMap(leaf => leaf.scale ? leaf.scale.ticks.map((t, i) => textWidth(leaf.scale!.labels?.[i] ?? format.tick(t), 10)) : []));+ const yAxisWidth = rows.leaves.some(leaf => leaf.kind === 'continuous') ? Math.ceil(tickWidth) + 30 : 0;+ const inner = columns.levels.length - 1;+ const innerWidth = inner >= 0 ? widest(columns, inner) : 0;+ const member = columns.leaves.find(leaf => leaf.kind === 'band' && leaf.path.length === inner + 1);+ const rotateColumnLabels = Boolean(member) && innerWidth + 8 > member!.size;+ const columnHeaderHeights = columns.levels.map((_, level) => rotateColumnLabels && level === inner ? Math.ceil(Math.min(innerWidth, metrics.rotatedLabelMax)) + 10 : metrics.headerHeight);+ const columnCaptionHeight = columns.levels.length ? metrics.captionHeight : 0;+ // With a value axis on the rows, the member names of the innermost column field read better under the marks.+ const valueAxisOnRows = rows.leaves.some(leaf => leaf.kind === 'continuous');+ const membersOnly = columns.leaves.length > 0 && columns.leaves.every(leaf => leaf.kind === 'band' && leaf.path.length === inner + 1);+ const atBottom = membersOnly && (spec.innerColumnHeader ? spec.innerColumnHeader === 'bottom' : valueAxisOnRows);+ const bottomHeaderHeight = atBottom ? columnHeaderHeights[inner] : 0;+ const top = Math.max(rows.levels.length ? metrics.captionHeight : 0, columnCaptionHeight + columnHeaderHeights.reduce((a, b) => a + b, 0) - bottomHeaderHeight);+ return {+ left: rowHeaderWidths.reduce((a, b) => a + b, 0) + yAxisWidth,+ top,+ bottom: columns.leaves.some(leaf => leaf.kind === 'continuous') ? metrics.xAxisHeight : bottomHeaderHeight,+ right, bottomHeaderHeight,+ rowHeaderWidths, columnHeaderHeights, rotateColumnLabels, columnCaptionHeight, yAxisWidth,+ };+}++/**+ * Builds the axis layouts and sparse panes. The members under a header are the union of+ * what occurs anywhere along the other axis, so a pane without a record for some member+ * still leaves that member's slot empty. Absent intersections allocate no pane.+ * With spec.fit and a target size, leaf steps are scaled so the sheet fills the target.+ * With spec.stretch, the target is the window the sheet scrolls in: continuous slots share what the+ * member steps leave of it, and target.scrollbar is the thickness of a scroll bar, which takes+ * its room from the other direction when the sheet does not fit.+ * target.headerWidth caps the total width of the row headers. target.font is the font texts are measured in.+ * formats says how numbers, dates and the sheet's own words are written; the labels built here already follow it.+ * zoom replaces the range of the axes it names; marks outside a zoomed range are cut off at the edge of their pane.+ */+/** Ranges that replace what the data asks for, by the key of the axis scale. */+export type Zoom = Readonly<Record<string, readonly [number, number]>>;++export function buildModel(plan: Plan, results: Map<string, Row[]>, target?: { width: number; height: number; headerWidth?: number; font?: string; scrollbar?: number }, formats?: Formats, zoom?: Zoom): WorksheetModel {+ const { spec } = plan;+ setFont(target?.font);+ const format = resolveFormats(formats);+ const rowDrafts = new Map<string, LeafDraft>();+ const columnDrafts = new Map<string, LeafDraft>();+ const cells = new Map<string, { row: string; column: string; items: CellItem[] }>();+ for (const binding of plan.bindings) {+ for (const record of results.get(binding.taskId) ?? []) {+ const row = draft('row', binding.row, record);+ const column = draft('column', binding.column, record);+ if (!rowDrafts.has(row.id)) rowDrafts.set(row.id, row);+ if (!columnDrafts.has(column.id)) columnDrafts.set(column.id, column);+ const id = JSON.stringify([row.groupId, column.groupId]);+ let cell = cells.get(id);+ if (!cell) cells.set(id, cell = { row: row.groupId, column: column.groupId, items: [] });+ cell.items.push({ record, row: row.id, column: column.id });+ }+ }+ const direction = spec.sort === 'descending' ? -1 : 1;+ const ranks = new Map(Object.entries(spec.order ?? {}).filter(([, order]) => Array.isArray(order))+ .map(([id, order]) => [id, new Map((order as Value[]).map((value, index) => [valueKey(value), index]))]));+ // Values that order members by a measure, per field and per parent path.+ const parentKey = (id: string, parent: { instanceId: string; value: Value }[]) => JSON.stringify([id, parent.map(p => [p.instanceId, typed(p.value)])]);+ const measured = new Map<string, Map<string, number>>();+ for (const ranking of plan.rankings) for (const record of results.get(ranking.taskId) ?? []) {+ const key = parentKey(ranking.instanceId, ranking.parents.map(p => ({ instanceId: p.id, value: record[p.field] as Value })));+ const raw = record[resultKey(ranking.by)];+ let values = measured.get(key);+ if (!values) measured.set(key, values = new Map());+ if (typeof raw === 'number' && Number.isFinite(raw)) values.set(valueKey(record[spec.instances[ranking.instanceId].field]), raw);+ }+ const byMeasure = new Map(plan.rankings.map(r => [r.instanceId, r.direction === 'descending' ? -1 : 1]));+ const compare: MemberCompare = (id, a, b, parent) => {+ const sign = byMeasure.get(id);+ if (sign) {+ const values = measured.get(parentKey(id, parent));+ const va = values?.get(valueKey(a)), vb = values?.get(valueKey(b));+ // A member without a value comes last whichever way the rest runs. Equal values fall back to value order.+ if (va === undefined || vb === undefined) return va !== undefined ? -1 : vb !== undefined ? 1 : compareValue(a, b);+ return (va - vb) * sign || compareValue(a, b);+ }+ const order = spec.order?.[id];+ const rank = ranks.get(id);+ if (!rank) return compareValue(a, b) * (order ? (order === 'descending' ? -1 : 1) : direction);+ // Listed members come first in list order, the rest follow by value.+ const ra = rank.get(valueKey(a)), rb = rank.get(valueKey(b));+ return ra !== undefined && rb !== undefined ? ra - rb : ra !== undefined ? -1 : rb !== undefined ? 1 : compareValue(a, b);+ };+ const sizes = leafSizes(spec);+ const rows = buildAxis('row', rowDrafts.values(), compare, sizes.row, spec.instances);+ const columns = buildAxis('column', columnDrafts.values(), compare, sizes.column, spec.instances);+ const rowIndex = new Map(rows.leaves.map(leaf => [leaf.id, leaf.index]));+ const columnIndex = new Map(columns.leaves.map(leaf => [leaf.id, leaf.index]));+ const rowGroups = new Map(rows.groups.map(group => [group.id, group]));+ const columnGroups = new Map(columns.groups.map(group => [group.id, group]));++ const panes: Pane[] = [];+ const paneIndex = new Map<string, Pane>();+ const colors = new Map<string, Value>();+ const color = spec.color ? spec.instances[spec.color] : undefined;+ const extent: [number, number] = [Infinity, -Infinity];+ // Size, opacity and shape span the complete result too, so a mark keeps its look when the window moves.+ const channels: WorksheetModel['channels'] = {};+ const spans = (['size', 'opacity', 'shape'] as const).flatMap(channel => {+ const field = spec[channel] ? spec.instances[spec[channel]!] : undefined;+ return field ? [{ channel, field, members: new Map<string, Value>(), domain: [Infinity, -Infinity] as [number, number] }] : [];+ });+ for (const cell of cells.values()) for (const { record } of cell.items) {+ for (const span of spans) {+ if (span.field.display === 'discrete') span.members.set(valueKey(record[span.field.field]), record[span.field.field]);+ else {+ const raw = record[resultKey(span.field)];+ if (typeof raw === 'number' && Number.isFinite(raw)) { span.domain[0] = Math.min(span.domain[0], raw); span.domain[1] = Math.max(span.domain[1], raw); }+ }+ }+ if (color?.display === 'discrete') colors.set(valueKey(record[color.field]), record[color.field]);+ if (color?.display === 'continuous') {+ const raw = record[resultKey(color)];+ if (raw != null && Number.isFinite(Number(raw))) { extent[0] = Math.min(extent[0], Number(raw)); extent[1] = Math.max(extent[1], Number(raw)); }+ }+ }+ const palette = [...colors.values()].sort(compareValue);+ for (const span of spans) {+ const options = span.channel === 'shape' ? undefined : spec.scales?.[span.channel];+ const scale: ChannelScale = span.field.display === 'discrete' ? { field: span.field, members: [...span.members.values()].sort(compareValue) }+ : { field: span.field, ...continuousRange(span.domain, options) };+ if (options?.range) scale.range = options.range;+ if (scale.members?.length || scale.domain) channels[span.channel] = scale;+ }+ // Boxes of different colors stand side by side in a member step, in legend order and in the same+ // place in every pane. A color field that already heads the members has one box per step anyway.+ const onAxis = color && [...plan.rows, ...plan.columns].some(branch => branchFields(branch).some(f => f.field === color.field));+ const slots = spec.mark === 'boxplot' && color && !onAxis ? new Map(palette.map((value, index) => [valueKey(value), index])) : undefined;+ for (const [id, cell] of cells) {+ const row = rowGroups.get(cell.row)!;+ const column = columnGroups.get(cell.column)!;+ const marks = paneMarks(cell.items, row.branch, column.branch, plan, rowIndex, columnIndex, slots);+ const pane: Pane = { id, row, column, records: marks.map(mark => mark.record), marks, xDomain: [0, 1], yDomain: [0, 1] };+ panes.push(pane);+ paneIndex.set(id, pane);+ }+ const scaleColumns = assignScales(columns, 'x', panes, plan, format, zoom), scaleRows = assignScales(rows, 'y', panes, plan, format, zoom);+ const scales = () => { scaleColumns(); scaleRows(); };+ scales();+ // A color range comes from the complete result, like an axis range.+ const colorRange = continuousRange(extent, spec.scales?.color);+ // A range across zero diverges from it, unless its ends or its spread were set by hand.+ const colorScale: ColorScale | undefined = color?.display === 'continuous'+ ? { field: color, domain: colorRange.domain ?? [0, 1], type: colorRange.type, diverging: !colorRange.fixed && !colorRange.type && extent[0] < 0 && extent[1] > 0 } : undefined;+ // Channels set to range independently: every pane gets the extent of its own records.+ for (const channel of ['color', 'size', 'opacity'] as const) {+ const field = spec[channel] ? spec.instances[spec[channel]!] : undefined;+ if (!spec.scales?.[channel]?.independent || field?.display !== 'continuous') continue;+ for (const pane of panes) {+ const own: [number, number] = [Infinity, -Infinity];+ for (const record of pane.records) {+ const raw = record[resultKey(field)];+ if (typeof raw === 'number' && Number.isFinite(raw)) { own[0] = Math.min(own[0], raw); own[1] = Math.max(own[1], raw); }+ }+ const range = continuousRange(own, spec.scales[channel]).domain;+ if (range) (pane.domains ??= {})[channel] = range;+ }+ }+ const legends = buildLegends(spec, palette, colorScale, channels, format);+ const measure = () => buildFrame(rows, columns, spec, legendWidth(legends), format, target?.headerWidth);+ let frame = measure();+ const fitWidth = target && (spec.fit === 'width' || spec.fit === 'both') && columns.size > 0;+ const fitHeight = target && (spec.fit === 'height' || spec.fit === 'both') && rows.size > 0;+ // Header and axis sizes depend on the steps and the steps on what the headers leave over.+ // Two rounds settle it; the frame of the first round is kept so the second fits it exactly.+ if (fitWidth || fitHeight) for (let round = 0; round < 2; round++) {+ if (fitWidth) scaleAxis(columns, Math.max(1, target!.width - frame.left - frame.right) / columns.size);+ if (fitHeight) scaleAxis(rows, Math.max(1, target!.height - frame.top - frame.bottom) / rows.size);+ scales();+ if (round === 0) frame = measure();+ }+ // A short table still leaves room for its legend.+ const legendHeight = legends.reduce((sum, block) => sum + Math.min(block.height, legendTitleHeight + 16 * block.step + 6), 0);+ const stretch = target && !spec.fit ? spec.stretch : undefined;+ if (target && stretch && columns.leaves.length && rows.leaves.length) {+ const { width: windowWidth, height: windowHeight } = target;+ const pie = spec.mark === 'arc', wide = stretch !== 'height', tall = stretch !== 'width';+ const floors = leafFloors(spec);+ // Pies are squares, so they only grow when both directions may.+ const grows = pie ? stretch === 'both' : true;+ const least = {+ width: pie ? (grows ? columns.leaves.length * floors.column : columns.size) : wide ? leastSize(columns, floors.column) : columns.size,+ height: pie ? (grows ? rows.leaves.length * floors.row : rows.size) : tall ? leastSize(rows, floors.row) : rows.size,+ };+ // A sheet that does not fit one way gets a scroll bar, which takes room from the other way.+ // Whether it fits is decided on the least size, and a bar that came never goes, so this settles.+ const bar = target.scrollbar ?? 0;+ let across = false, down = false;+ const bars = () => {+ let changed = false;+ for (let pass = 0; pass < 2; pass++) {+ if (!across && frame.left + least.width + frame.right > windowWidth - (down ? bar : 0) + .5) across = changed = true;+ if (!down && windowHeight > 0 && Math.max(frame.top + least.height + frame.bottom, legendHeight) > windowHeight - (across ? bar : 0) + .5) down = changed = true;+ }+ return changed;+ };+ const place = () => {+ const roomX = windowWidth - (down ? bar : 0) - frame.left - frame.right, roomY = windowHeight - (across ? bar : 0) - frame.top - frame.bottom;+ if (pie) {+ if (!grows) return;+ const side = Math.max(floors.column, Math.min(roomX / columns.leaves.length, roomY / rows.leaves.length));+ resizeAxis(columns, () => side);+ resizeAxis(rows, () => side);+ } else {+ if (wide) stretchAxis(columns, roomX, floors.column);+ if (tall) stretchAxis(rows, roomY, floors.row);+ }+ scales();+ };+ // The axis labels depend on the slot sizes and the slot sizes on the room the labels leave.+ let settled = false;+ for (let round = 0; round < 3 && !settled; round++) {+ bars();+ place();+ const next = measure();+ settled = next.left === frame.left && next.right === frame.right && next.top === frame.top && next.bottom === frame.bottom;+ frame = next;+ if (settled) settled = !bars();+ }+ // The last frame is kept and the slots are fitted to it exactly.+ if (!settled) place();+ }+ for (const pane of panes) {+ pane.xDomain = columns.leaves[pane.column.start].scale?.domain ?? [0, 1];+ pane.yDomain = rows.leaves[pane.row.start].scale?.domain ?? [0, 1];+ }+ return { plan, rows, columns, panes, paneIndex, frame, width: frame.left + columns.size + frame.right,+ height: Math.max(frame.top + rows.size + frame.bottom, legendHeight), colors: palette, colorScale, channels, legends, format };+}diff --git a/packages/worksheet-renderer/src/scene.ts b/packages/worksheet-renderer/src/scene.tsnew file mode 100644index 00000000..9b88e835--- /dev/null+++ b/packages/worksheet-renderer/src/scene.ts@@ -0,0 +1,583 @@+import { continuousColor, fillOf, lightTheme, rgb, type Theme } from './color';+import { inRange, legendTitleHeight, level, memberIndex, opacityAt, pointArea, shapes, thicknessShare } from './channels';+import { position } from './warp';+import { valueKey } from './keys';+import { clipLine, clipPolygon, clipRect, inside, type Box } from './clip';+import { branchFields, valueAxis } from './compiler';+import { stackMode } from './model';+import { fitText, leafRange, metrics, setFont, spansIn, textWidth } from './layout';+import { fieldTime, memberLabel as labelMember, positionValue } from './time';+import { resultKey, type AxisGroup, type AxisLeaf, type FieldInstance, type Pane, type Selection, type Value, type WorksheetModel } from './types';++/** x and y are the scroll offsets, width and height the size of the visible window. */+export interface Viewport { x: number; y: number; width: number; height: number }+/**+ * Painted in this order. The body scrolls both ways, row headers and the value axis on+ * the left scroll vertically, column headers and the bottom axis scroll horizontally,+ * corners and the legend stay put. Each later layer has an opaque background and covers+ * what is below. The xAxis layer is the strip under the body: the value axis of the+ * columns, or the innermost column headers when those are placed at the bottom.+ */+export const layers = ['body', 'rowHeader', 'columnHeader', 'xAxis', 'corner', 'legend'] as const;+export type Layer = typeof layers[number];+export interface Primitive {+ /** path is an open stroked line. shape is a closed filled outline, such as a pie slice; its path is relative to x and y. */+ kind: 'rect' | 'symbol' | 'path' | 'shape' | 'text';+ layer: Layer;+ x: number; y: number; width?: number; height?: number;+ fill?: string; stroke?: string; strokeWidth?: number; path?: string; text?: string;+ /** Dash and gap of a path in px. */+ dash?: [number, number];+ /** Painted before everything else in its layer, whatever its kind: the surface and the grid, which marks cover. */+ under?: boolean;+ /** Corner radii of a rect: top left, top right, bottom right, bottom left. */+ radius?: [number, number, number, number];+ /** Font family of a text. The system font when absent. */+ font?: string;+ /** Outline of a symbol. A circle when absent. */+ symbol?: string;+ align?: 'left' | 'center' | 'right'; angle?: number; size?: number; fontSize?: number; fontWeight?: number; opacity?: number;+ selection?: Selection; tooltip?: string;+}+export interface Scene {+ width: number; height: number; items: Primitive[]; visiblePanes: number;+ /** The surface color. Every layer paints it, so the backend may also clear with it. */+ background: string;+ /** 'omitted' when the window is too narrow for the legend strip; the host should show the colors some other way. */+ legend: 'none' | 'side' | 'omitted';+ /** Screen rectangle of the scrolling body, where the marks are. */+ body: Box;+}+/** Opacity of marks outside a non-empty selection. */+const dimmed = 0.25;+/** Outline of a pie slice around the origin, from share `start` to share `end` of a turn, clockwise from twelve o'clock. */+function slice(radius: number, start: number, end: number): string {+ const point = (share: number) => `${(Math.sin(share * 2 * Math.PI) * radius).toFixed(2)},${(-Math.cos(share * 2 * Math.PI) * radius).toFixed(2)}`;+ const arc = (to: number, large: boolean) => `A${radius},${radius} 0 ${large ? 1 : 0} 1 ${point(to)}`;+ // A whole disc cannot be one arc, because its start and end coincide.+ if (end - start > 1 - 1e-9) return `M${point(0)}${arc(.5, false)}${arc(1, false)}Z`;+ return `M0,0L${point(start)}${arc(end, end - start > .5)}Z`;+}+export interface SceneState {+ /** Selection ids. While any is set, every other mark is dimmed. */+ selected?: ReadonlySet<string>;+ /** Surface, text and rule colors. Light when absent. */+ theme?: Theme;+}++/** Produces pixel geometry for the window. The drawing backend does no grouping, stacking or scaling. */+export function buildScene(model: WorksheetModel, viewport: Viewport, state: SceneState = {}): Scene {+ const items: Primitive[] = [];+ const { spec } = model.plan;+ const { rows, columns, frame } = model;+ const { left, top } = frame;+ const ink = state.theme ?? lightTheme;+ setFont(ink.font);+ const { format } = model, { words } = format;+ const memberLabel = (field: FieldInstance | undefined, value: Value) => labelMember(field, value, format);+ const pad = metrics.headerPadding;+ // The legend strip is drawn when the whole sheet fits, or when the body still keeps a usable+ // share of a window narrower than the sheet. Otherwise it is left out.+ const roomy = left + columns.size + frame.right <= viewport.width || viewport.width - left - frame.right >= Math.max(120, viewport.width * 0.3);+ const right = frame.right && roomy ? frame.right : 0;+ // Screen rectangle of the body. The bottom axis sits under the last row, or on the window edge when the sheet is taller.+ const axisY = Math.max(top, Math.min(viewport.height - frame.bottom, top + rows.size - viewport.y));+ const bodyRight = Math.max(left, Math.min(viewport.width - right, left + columns.size - viewport.x));+ const [c0, c1] = leafRange(columns, viewport.x, viewport.x + bodyRight - left);+ const [r0, r1] = leafRange(rows, viewport.y, viewport.y + axisY - top);+ const sx = (logical: number) => left + logical - viewport.x;+ const sy = (logical: number) => top + logical - viewport.y;+ const rect = (layer: Layer, x: number, y: number, width: number, height: number, fill: string, extra: Partial<Primitive> = {}) => {+ if (width > 0 && height > 0) items.push({ kind: 'rect', layer, x, y, width, height, fill, ...extra });+ };+ const text = (layer: Layer, x: number, y: number, value: string, extra: Partial<Primitive> = {}) => {+ if (value) items.push({ kind: 'text', layer, x, y, text: value, fill: ink.text, fontSize: metrics.fontSize, ...(ink.font ? { font: ink.font } : {}), ...extra });+ };+ // Distance of a value from the start of its slot.+ const along = (leaf: AxisLeaf, value: number) => {+ // A value with no place on the axis, such as the zero a bar starts from on a log axis, sits at its start.+ const share = position(leaf.scale!.domain, value, leaf.scale!.type);+ return metrics.scalePadStart + (Number.isNaN(share) ? 0 : share) * (leaf.size - metrics.scalePadStart - metrics.scalePadEnd);+ };+ const px = (leaf: AxisLeaf, value: number) => sx(leaf.offset + along(leaf, value));+ const py = (leaf: AxisLeaf, value: number) => sy(leaf.offset + leaf.size - along(leaf, value));+ const tickLabel = (leaf: AxisLeaf, index: number) => leaf.scale!.labels?.[index] ?? format.tick(leaf.scale!.ticks[index]);+ // Width of a bar placed at a continuous position: a share of the smallest gap between positions, so+ // neighbours never touch and every pane on the same scale gets the same width.+ const barAt = (leaf: AxisLeaf) => {+ const { step, domain } = leaf.scale!;+ if (!step) return 12;+ return Math.min(28, Math.max(1, step / (domain[1] - domain[0]) * (leaf.size - metrics.scalePadStart - metrics.scalePadEnd) * metrics.barFill));+ };++ const colorField = spec.color ? spec.instances[spec.color] : undefined;+ // Cells of a heat map take the theme's heat map stops, other marks its ramp.+ const cells = spec.mark === 'rect';+ const fill = fillOf(colorField, model.colors, model.colorScale, ink, cells);+ const textField = spec.mark === 'text' && spec.text ? spec.instances[spec.text] : undefined;+ // On other marks the text field is a label next to the mark. A box stands for many records and gets none.+ const labelField = spec.mark !== 'text' && spec.mark !== 'boxplot' && spec.text ? spec.instances[spec.text] : undefined;+ const angleField = spec.mark === 'arc' && spec.angle ? spec.instances[spec.angle] : undefined;+ const { size: sizeScale, opacity: opacityScale, shape: shapeScale } = model.channels;+ // Ranges set by hand: sizes in px, opacities from 0 to 1.+ const sizeRange = sizeScale?.range, opacityRange = opacityScale?.range;+ const encodingFields = [...new Set([spec.color, ...(spec.detail ?? []), spec.text, angleField?.id, spec.size, spec.opacity, spec.shape].filter((id): id is string => Boolean(id)))].map(id => spec.instances[id]);+ // Dimensions on color, detail and the other channels divide a pane into series; a measure does not.+ const seriesFields = encodingFields.filter(f => f.display === 'discrete' && f !== textField);+ // Label boxes already written, so that a later label does not run into them.+ const written: [number, number, number, number][] = [];+ // White on a dark fill, dark on a light one.+ const inkOn = (fill: string) => { const [r, g, b] = rgb(fill); return (0.2126 * r + 0.7152 * g + 0.0722 * b) / 255 < 0.55 ? '#ffffff' : '#1f2937'; };+ const selecting = Boolean(state.selected?.size);+ // Labels of members squeezed below one line of text are thinned out, the members themselves stay.+ const stride = (size: number, room: number) => Math.max(1, Math.ceil(room / size));++ // ---- body+ rect('body', left, top, bodyRight - left, axisY - top, ink.paper, { under: true });+ let visiblePanes = 0;+ if (r1 > r0 && c1 > c0) {+ for (let r = rows.leaves[r0].group; r <= rows.leaves[r1 - 1].group; r++) {+ for (let c = columns.leaves[c0].group; c <= columns.leaves[c1 - 1].group; c++) drawPane(rows.groups[r], columns.groups[c]);+ }+ }+ // A grid line is one px wide. A dashed one is a stroked path, as a rect has no dashes.+ function gridLine(x0: number, y0: number, x1: number, y1: number, zero: boolean) {+ if (zero || !ink.gridDash) rect('body', x0, y0, Math.max(1, x1 - x0), Math.max(1, y1 - y0), zero ? ink.zero : ink.grid, { under: true });+ else if (x1 > x0 || y1 > y0) items.push({ kind: 'path', layer: 'body', under: true, x: 0, y: 0, path: `M${x0 + (x1 === x0 ? .5 : 0)},${y0 + (y1 === y0 ? .5 : 0)}L${x1 + (x1 === x0 ? .5 : 0)},${y1 + (y1 === y0 ? .5 : 0)}`, stroke: ink.grid, strokeWidth: 1, dash: ink.gridDash });+ }+ function drawPane(row: AxisGroup, column: AxisGroup) {+ const x0 = Math.max(sx(column.offset), left), x1 = Math.min(sx(column.offset + column.size), bodyRight);+ const y0 = Math.max(sy(row.offset), top), y1 = Math.min(sy(row.offset + row.size), axisY);+ const xLeaf = columns.leaves[column.start], yLeaf = rows.leaves[row.start];+ // Zero on a date axis is the start of 1970, which is a date like any other and gets no zero line.+ const xTime = xLeaf.branch.position?.scale === 'time', yTime = yLeaf.branch.position?.scale === 'time';+ // Grid lines belong to the row or column, so they are drawn for empty intersections too.+ if (xLeaf.scale) for (const tick of xLeaf.scale.ticks) {+ const x = Math.round(px(xLeaf, tick));+ if (x >= left && x < bodyRight) gridLine(x, y0, x, y1, tick === 0 && !xTime);+ }+ if (yLeaf.scale) for (const tick of yLeaf.scale.ticks) {+ const y = Math.round(py(yLeaf, tick));+ if (y >= top && y < axisY) gridLine(x0, y, x1, y, tick === 0 && !yTime);+ }+ if (sx(column.offset) >= left && column.offset > 0) rect('body', sx(column.offset), y0, 1, y1 - y0, ink.line);+ if (sy(row.offset) >= top && row.offset > 0) rect('body', x0, sy(row.offset), x1 - x0, 1, ink.line);+ const pane = model.paneIndex.get(JSON.stringify([row.id, column.id]));+ if (!pane) return;+ visiblePanes++;+ drawMarks(pane);+ }+ function drawMarks(pane: Pane) {+ const xField = pane.column.branch.position, yField = pane.row.branch.position;+ const xContinuous = xField?.display === 'continuous', yContinuous = yField?.display === 'continuous';+ const used = [...branchFields(pane.row.branch), ...branchFields(pane.column.branch), ...encodingFields];+ const dimensions = [...new Map(used.filter(f => !f.aggregate).map(f => [f.field, f])).values()];+ // A field that is on a shelf twice, such as a measure that is both the axis and the label, is described once.+ const described = used.filter((f, i) => used.findIndex(g => g.field === f.field && g.aggregate === f.aggregate) === i);+ // What a value of a field reads as: a moment or a period for a time field, a number for a continuous one, the member's name otherwise.+ const read = (f: FieldInstance, value: unknown): string => f.display === 'continuous' && f.scale === 'time' ? format.time(fieldTime(f, value))+ : f.display === 'continuous' && typeof value === 'number' ? format.number(value) : memberLabel(f, value as Value);+ const describe = (f: FieldInstance, value: unknown) => `${f.label}: ${read(f, value)}`;+ const lengthAxis = valueAxis(xField, yField);+ const isLine = spec.mark === 'line', isArea = spec.mark === 'area', joined = isLine || isArea;+ // A line runs along x unless x is the only value axis. An area runs across its value axis.+ const alongY = isArea ? lengthAxis === 'x' : xContinuous && !yContinuous;+ // x and y are where the mark is; for an area that is its upper edge, and bx and by its lower edge.+ const lines = new Map<string, { selected: boolean; points: { order: number; x: number; y: number; bx: number; by: number; missing: boolean; color: string; size: number; alpha: number }[] }>();+ const box = { x0: sx(pane.column.offset), x1: sx(pane.column.offset + pane.column.size), y0: sy(pane.row.offset), y1: sy(pane.row.offset + pane.row.size) };+ // On a zoomed or panned axis some marks lie outside the pane. They are cut off at its edge.+ const moved = (leaf: AxisLeaf) => Boolean(leaf.scale?.full && (leaf.scale.domain[0] !== leaf.scale.full[0] || leaf.scale.domain[1] !== leaf.scale.full[1]));+ const cut = (leaf: AxisLeaf) => moved(leaf) || Boolean(leaf.scale?.fixed);+ const clip: Box | undefined = cut(columns.leaves[pane.column.start]) || cut(rows.leaves[pane.row.start]) ? box : undefined;+ // A pane that ranges over its own values on a channel reads its marks against that range.+ const own = pane.domains;+ const paneFill = own?.color && model.colorScale ? fillOf(colorField, model.colors, { ...model.colorScale, domain: own.color }, ink, cells) : fill;+ const paneSize = own?.size && sizeScale ? { ...sizeScale, domain: own.size } : sizeScale;+ const paneOpacity = own?.opacity && opacityScale ? { ...opacityScale, domain: own.opacity } : opacityScale;+ // A value that has no place on an axis, such as zero or less on a log axis, leaves no mark.+ const placed = (leaf: AxisLeaf, value: number) => leaf.scale!.type !== 'log' || value > 0;+ // What counts as inside is the range of the axes themselves, without the margin a slot keeps around it.+ // A mark that lies wholly in that margin is outside the range and is not drawn.+ const range: Box | undefined = clip && {+ x0: clip.x0 + (xContinuous ? metrics.scalePadStart : 0), x1: clip.x1 - (xContinuous ? metrics.scalePadEnd : 0),+ y0: clip.y0 + (yContinuous ? metrics.scalePadEnd : 0), y1: clip.y1 - (yContinuous ? metrics.scalePadStart : 0),+ };+ const bar = (x: number, y: number, width: number, height: number, fill: string, extra: Partial<Primitive>) => {+ if (range && !clipRect(range, x, y, Math.max(width, 1e-6), Math.max(height, 1e-6))) return;+ const cut = clip ? clipRect(clip, x, y, width, height) : [x, y, width, height] as const;+ // A bar cut short has lost its rounded end.+ if (cut) rect('body', cut[0], cut[1], cut[2], cut[3], fill, extra.radius && (cut[2] !== width || cut[3] !== height) ? { ...extra, radius: undefined } : extra);+ };+ // Marks drawn at one point are either in or out; bars, boxes, ticks and cells are cut to what is inside.+ const pointLike = spec.mark !== 'bar' && spec.mark !== 'boxplot' && spec.mark !== 'tick' && spec.mark !== 'rect';+ type Spot = { x: number; y: number; align: 'left' | 'center' | 'right'; fill?: string };+ // Writes a label at the first spot that lies inside its pane and clear of the labels already written.+ const write = (value: string, width: number, spots: (Spot | false)[]) => {+ for (const spot of spots) {+ if (!spot) continue;+ const x0 = spot.align === 'left' ? spot.x : spot.align === 'right' ? spot.x - width : spot.x - width / 2;+ const next: [number, number, number, number] = [x0, spot.y - 10, x0 + width, spot.y + 2];+ if (next[0] < box.x0 + 1 || next[2] > box.x1 - 1 || next[1] < box.y0 || next[3] > box.y1) continue;+ if (written.some(w => next[0] < w[2] && next[2] > w[0] && next[1] < w[3] && next[3] > w[1])) continue;+ written.push(next);+ // Labels outside the window take their place all the same, so scrolling does not reshuffle them.+ if (next[2] >= left && next[0] <= bodyRight && next[3] >= top && next[1] <= axisY) text('body', spot.x, spot.y, value, { align: spot.align, fontSize: 10, fill: spot.fill ?? ink.text });+ return;+ }+ };+ const labelOf = (record: Record<string, unknown>) => {+ const raw = record[resultKey(labelField!)];+ if (raw == null) return '';+ return read(labelField!, raw);+ };+ for (const mark of pane.marks) {+ // Points of a line outside the window still shape the visible segments.+ if (!joined && (mark.row < r0 || mark.row >= r1 || mark.column < c0 || mark.column >= c1)) continue;+ const { record } = mark;+ const rowLeaf = rows.leaves[mark.row], columnLeaf = columns.leaves[mark.column];+ const xValue = xContinuous ? positionValue(xField!, record) : 0;+ const yValue = yContinuous ? positionValue(yField!, record) : 0;+ let missing = !Number.isFinite(xValue) || !Number.isFinite(yValue) || (xContinuous && !placed(columnLeaf, xValue)) || (yContinuous && !placed(rowLeaf, yValue));+ let x = xContinuous ? px(columnLeaf, xValue) : sx(columnLeaf.offset + columnLeaf.size / 2);+ let y = yContinuous ? py(rowLeaf, yValue) : sy(rowLeaf.offset + rowLeaf.size / 2);+ let bx = x, by = y;+ if (isArea) {+ // The edges are where the mark's interval starts and ends, which under a stack is not its own value.+ missing ||= !Number.isFinite(mark.start) || !Number.isFinite(mark.end);+ if (lengthAxis === 'x') { bx = px(columnLeaf, mark.start); x = px(columnLeaf, mark.end); }+ else { by = py(rowLeaf, mark.start); y = py(rowLeaf, mark.end); }+ }+ const color = paneFill(record);+ // Where the record sits on size and opacity. Without a value there it keeps the default look.+ const sizeLevel = paneSize ? level(paneSize, record, true) : NaN;+ const sized = Number.isFinite(sizeLevel);+ const opacityLevel = paneOpacity ? level(paneOpacity, record) : NaN;+ const alpha = !Number.isFinite(opacityLevel) ? 1 : opacityRange ? Math.min(1, Math.max(0, inRange(opacityRange, opacityLevel))) : opacityAt(opacityLevel);+ const shapeIndex = shapeScale ? memberIndex(shapeScale, record[shapeScale.field.field] as Value) : -1;+ const symbol = shapeIndex < 0 ? undefined : shapes[shapeIndex % shapes.length];+ const label = labelField && !mark.outlier ? labelOf(record) : '';+ const labelWidth = label ? textWidth(label, 10) : 0;+ // A box stands for all its records, so only its dimensions identify it.+ const keys = mark.box ? dimensions.filter(f => f.display === 'discrete') : dimensions;+ const id = JSON.stringify([pane.row.branch.order, pane.column.branch.order, ...keys.map(f => valueKey(record[f.field]))]);+ const selected = selecting && state.selected!.has(id);+ if (joined) {+ const order = alongY ? (yContinuous ? y : mark.row) : (xContinuous ? x : mark.column);+ if (Number.isFinite(order)) {+ const key = JSON.stringify(seriesFields.map(f => valueKey(record[f.field])));+ const line = lines.get(key) ?? { selected: false, points: [] };+ line.points.push({ order, x, y, bx, by, missing, color, size: sizeLevel, alpha });+ line.selected ||= selected;+ lines.set(key, line);+ }+ }+ if (missing) continue;+ if (range && pointLike && !inside(range, x, y)) continue;+ const selection: Selection = { id, paneId: pane.id, rowPath: rowLeaf.path, columnPath: columnLeaf.path,+ predicates: keys.map(f => ({ field: f.field, value: record[f.field] as Value })), values: mark.box ? { ...record, ...mark.box } : record };+ const extra: Partial<Primitive> = { selection, tooltip: described.map(f => describe(f, record[resultKey(f)])).join('\n') };+ if (mark.share !== undefined) extra.tooltip += `\n${words.share}: ${format.share(mark.share)}`;+ const fade = alpha * (selecting && !selected ? dimmed : 1);+ if (fade < 1) extra.opacity = fade;+ if (spec.mark === 'arc') {+ if (!Number.isFinite(mark.start)) continue;+ const radius = Math.max(4, Math.min(columnLeaf.size, rowLeaf.size) / 2 - 10);+ const share = `${words.share}: ${format.share(mark.end - mark.start)}`;+ items.push({ kind: 'shape', layer: 'body', x, y, path: slice(radius, mark.start, mark.end), fill: color, stroke: ink.paper, strokeWidth: 1, ...extra, tooltip: `${extra.tooltip}\n${share}` });+ // Inside the slice, where it is wide enough to hold the text.+ const middle = (mark.start + mark.end) * Math.PI;+ if (label && mark.end - mark.start >= 0.05) write(label, labelWidth, [{ x: x + Math.sin(middle) * radius * 0.62, y: y - Math.cos(middle) * radius * 0.62 + 4, align: 'center', fill: inkOn(color) }]);+ } else if (spec.mark === 'boxplot') {+ // The box sits in the member step across the value axis. Several colors share the step side by side.+ const flat = lengthAxis === 'x';+ const step = flat ? rowLeaf.size : columnLeaf.size;+ const [index, count] = mark.slot ?? [0, 1];+ const room = step * metrics.barFill / count;+ const thickness = Math.max(2, Math.min(28, room - (count > 1 ? 1 : 0)));+ const center = (flat ? y : x) + (index - (count - 1) / 2) * room;+ const at = (value: number) => flat ? px(columnLeaf, value) : py(rowLeaf, value);+ if (mark.outlier) {+ const ox = flat ? at(mark.start) : center, oy = flat ? center : at(mark.start);+ if (!range || inside(range, ox, oy)) items.push({ kind: 'symbol', layer: 'body', x: ox, y: oy, size: 18, fill: 'transparent', stroke: color, strokeWidth: 1, ...extra });+ continue;+ }+ const box = mark.box!, measure = flat ? xField! : yField!;+ const tooltip = [...keys.map(f => describe(f, record[f.field])), measure.label,+ ...([[words.upperWhisker, box.high], [words.upperQuartile, box.q3], [words.median, box.median], [words.lowerQuartile, box.q1], [words.lowerWhisker, box.low]] as const).map(([name, value]) => `${name}: ${format.number(value)}`),+ `${words.records}: ${box.count}`].join('\n');+ // A stretch along the value axis, `across` px wide and at least `least` px long.+ const stretch = (from: number, to: number, across: number, color: string, least = 1) => {+ const a = Math.min(at(from), at(to)), length = Math.max(least, Math.abs(at(to) - at(from)));+ const start = Math.abs(at(to) - at(from)) < least ? a - least / 2 : a;+ if (flat) bar(start, center - across / 2, length, across, color, { ...extra, tooltip });+ else bar(center - across / 2, start, across, length, color, { ...extra, tooltip });+ };+ stretch(box.low, box.high, 1, color);+ stretch(box.low, box.low, thickness / 2, color);+ stretch(box.high, box.high, thickness / 2, color);+ // A box too short to hold a median line, as when it has a single record, is drawn as a dash.+ const short = Math.abs(at(box.q3) - at(box.q1)) < 4;+ stretch(box.q1, box.q3, thickness, color, short ? 2 : 1);+ if (!short) stretch(box.median, box.median, thickness, ink.paper, 2);+ } else if (spec.mark === 'tick') {+ // A tick is a short line across its value axis. Between two value axes it stands upright.+ const length = (leafSize: number, continuous: boolean) => sized && sizeRange ? Math.max(1, inRange(sizeRange, sizeLevel))+ : (continuous ? 14 : Math.max(3, leafSize * metrics.barFill)) * (sized ? thicknessShare(sizeLevel) : 1);+ if (xContinuous) { const h = length(rowLeaf.size, yContinuous); bar(Math.round(x) - 1, y - h / 2, 2, h, color, extra); }+ else { const w = length(columnLeaf.size, false); bar(x - w / 2, Math.round(y) - 1, w, 2, color, extra); }+ if (label) write(label, labelWidth, xContinuous ? [{ x: x + 5, y: y + 4, align: 'left' }, { x: x - 5, y: y + 4, align: 'right' }] : [{ x, y: y - 5, align: 'center' }, { x, y: y + 14, align: 'center' }]);+ } else if (spec.mark === 'bar') {+ if (!Number.isFinite(mark.start) || !Number.isFinite(mark.end)) continue;+ const slim = sized && !sizeRange ? thicknessShare(sizeLevel) : 1;+ // A thickness set in px may not spill over the member's own step.+ const thick = (full: number, step: number) => sized && sizeRange ? Math.min(step, Math.max(1, inRange(sizeRange, sizeLevel))) : full * slim;+ // The far end of the bar is rounded where the theme asks for it.+ const round = ink.barRadius ?? 0;+ // A bar that is one of several in a pile is labelled inside, where the label cannot be taken for a+ // neighbour's. A bar on its own is labelled past its end, or just inside the end when there is no room.+ const piled = Boolean(stackMode(model.plan)) && seriesFields.length > 0;+ const forward = mark.end >= mark.start;+ if (lengthAxis === 'x') {+ const a = px(columnLeaf, mark.start), b = px(columnLeaf, mark.end), thickness = thick(yContinuous ? barAt(rowLeaf) : Math.max(1, rowLeaf.size * metrics.barFill), rowLeaf.size);+ bar(Math.min(a, b), y - thickness / 2, Math.max(.5, Math.abs(b - a)), thickness, color, round ? { ...extra, radius: forward ? [0, round, round, 0] : [round, 0, 0, round] } : extra);+ const end = forward ? Math.max(a, b) : Math.min(a, b), out = forward ? 1 : -1, fits = Math.abs(b - a) >= labelWidth + 8 && thickness >= 11;+ if (label) write(label, labelWidth, piled ? [fits && { x: (a + b) / 2, y: y + 4, align: 'center', fill: inkOn(color) }]+ : [{ x: end + out * 4, y: y + 4, align: forward ? 'left' : 'right' }, fits && { x: end - out * 4, y: y + 4, align: forward ? 'right' : 'left', fill: inkOn(color) }]);+ } else {+ const a = py(rowLeaf, mark.start), b = py(rowLeaf, mark.end), thickness = thick(xContinuous ? barAt(columnLeaf) : Math.max(1, columnLeaf.size * metrics.barFill), columnLeaf.size);+ bar(x - thickness / 2, Math.min(a, b), thickness, Math.max(.5, Math.abs(b - a)), color, round ? { ...extra, radius: forward ? [round, round, 0, 0] : [0, 0, round, round] } : extra);+ const end = forward ? Math.min(a, b) : Math.max(a, b), fits = Math.abs(b - a) >= 14 && thickness >= labelWidth + 2;+ if (label) write(label, labelWidth, piled ? [fits && { x, y: (a + b) / 2 + 4, align: 'center', fill: inkOn(color) }]+ : [{ x, y: forward ? end - 4 : end + 12, align: 'center' }, fits && { x, y: forward ? end + 12 : end - 4, align: 'center', fill: inkOn(color) }]);+ }+ } else if (spec.mark === 'text') {+ // In a cell the number is written in full; along a value axis it is abbreviated like a tick.+ const f = textField ?? (xField?.aggregate ? xField : yField?.aggregate ? yField : undefined);+ const raw = f ? record[resultKey(f)] : undefined;+ const cell = !xContinuous && !yContinuous;+ const shown = !f ? '•' : raw == null ? '' : typeof raw !== 'number' || f.display !== 'continuous' ? read(f, raw) : cell || (raw !== 0 && Math.abs(raw) < 1) ? format.number(raw) : format.tick(raw);+ const fontSize = !sized ? metrics.fontSize : sizeRange ? Math.max(6, Math.round(inRange(sizeRange, sizeLevel))) : Math.round(9 + 15 * sizeLevel);+ text('body', x, y + fontSize * 0.36, cell ? fitText(shown, columnLeaf.size - 6, fontSize) : shown, { align: 'center', fill: colorField ? color : ink.text, fontSize, ...extra });+ } else if (spec.mark === 'rect') {+ // A cell mark fills its member step; on a value axis it stays a small square.+ // Sized cells keep their place in the grid and shrink towards their center.+ const share = sized ? 0.3 + 0.7 * sizeLevel : 1;+ const width = (xContinuous ? 10 : columnLeaf.size - 1) * share, height = (yContinuous ? 10 : rowLeaf.size - 1) * share;+ bar(x - width / 2, y - height / 2, width, height, color, extra);+ if (label) write(label, labelWidth, [width >= labelWidth + 4 && height >= 12 && { x, y: y + 4, align: 'center', fill: inkOn(color) }]);+ } else if (isArea) {+ // The area itself is drawn per series below. Each of its points keeps an unseen spot on the+ // upper edge that answers the pointer.+ items.push({ kind: 'symbol', layer: 'body', x, y, size: 64, fill: 'transparent', ...extra, opacity: undefined });+ if (label) write(label, labelWidth, [{ x, y: y - 6, align: 'center' }]);+ } else if (isLine) {+ items.push({ kind: 'symbol', layer: 'body', x, y, size: 22, fill: color, ...extra });+ if (label) write(label, labelWidth, [{ x, y: y - 7, align: 'center' }, { x, y: y + 15, align: 'center' }]);+ } else {+ const area = !sized ? 44 : sizeRange ? Math.max(1, inRange(sizeRange, sizeLevel)) : pointArea(sizeLevel), reach = Math.sqrt(area / Math.PI) + 3;+ // A point is hollow, with a transparent fill so the inside still takes the pointer. A circle is filled.+ items.push(spec.mark === 'point' && !ink.pointFilled ? { kind: 'symbol', layer: 'body', x, y, size: area, symbol, fill: 'transparent', stroke: color, strokeWidth: ink.pointStrokeWidth ?? 1.5, ...extra }+ : { kind: 'symbol', layer: 'body', x, y, size: area, symbol, fill: color, ...extra });+ if (label) write(label, labelWidth, [{ x: x + reach, y: y + 4, align: 'left' }, { x, y: y - reach - 1, align: 'center' }, { x: x - reach, y: y + 4, align: 'right' }]);+ }+ }+ // Areas that pile up do not cover each other and can be solid; areas that overlap must let the others show through.+ const areaOpacity = stackMode(model.plan) ? 0.85 : 0.5;+ for (const { points, selected } of lines.values()) {+ points.sort((a, b) => a.order - b.order);+ // A missing value ends the current segment; the next valid point starts a new one.+ type Point = typeof points[number];+ const segments: Point[][] = [];+ let open: Point[] | undefined;+ for (const point of points) {+ if (point.missing) { open = undefined; continue; }+ if (!open) segments.push(open = []);+ open.push(point);+ }+ if (!segments.length) continue;+ // A line or an area has one color. With a measure on color only its points are tinted.+ const color = model.colorScale ? ink.mark : points[0].color;+ // It has one width and one opacity too: the average over its points, which for a dimension is the member's own.+ const drawn = segments.flat();+ const mean = (values: number[]) => { const finite = values.filter(Number.isFinite); return finite.length ? finite.reduce((a, b) => a + b, 0) / finite.length : NaN; };+ const sizeLevel = mean(drawn.map(p => p.size));+ const faded = (selecting && !selected ? dimmed : 1) * (mean(drawn.map(p => p.alpha)) || 1);+ const at = (x: number, y: number) => `${x.toFixed(1)},${y.toFixed(1)}`;+ if (isArea) for (const segment of segments) {+ const [only] = segment;+ // One point has no extent along the axis, so it is drawn as a thin bar from edge to edge.+ if (segment.length === 1) { bar(Math.min(only.x, only.bx) - (alongY ? 0 : 1.5), Math.min(only.y, only.by) - (alongY ? 1.5 : 0),+ alongY ? Math.max(1, Math.abs(only.x - only.bx)) : 3, alongY ? 3 : Math.max(1, Math.abs(only.y - only.by)), color, { opacity: faded * areaOpacity }); continue; }+ // Out along the upper edge and back along the lower one.+ const outline: [number, number][] = [...segment.map(p => [p.x, p.y] as [number, number]), ...[...segment].reverse().map(p => [p.bx, p.by] as [number, number])];+ const shown = clip ? clipPolygon(clip, outline) : outline;+ if (shown.length > 2) items.push({ kind: 'shape', layer: 'body', x: 0, y: 0, fill: color, opacity: faded * areaOpacity, path: `M${shown.map(p => at(p[0], p[1])).join('L')}Z` });+ }+ const strokes = segments.flatMap(segment => { const line = segment.map(p => [p.x, p.y] as [number, number]); return clip ? clipLine(clip, line) : [line]; });+ if (strokes.length) items.push({ kind: 'path', layer: 'body', x: 0, y: 0, path: strokes.map(line => `M${line.map(p => at(p[0], p[1])).join('L')}`).join(' '), stroke: color,+ ...(isLine && Number.isFinite(sizeLevel) ? { strokeWidth: sizeRange ? Math.max(.5, inRange(sizeRange, sizeLevel)) : 1 + 5 * sizeLevel } : ink.lineWidth ? { strokeWidth: ink.lineWidth } : {}),+ ...(faded < 1 ? { opacity: faded } : {}) });+ }+ }++ // ---- row headers and the value axis on the left+ rect('rowHeader', 0, top, left, axisY - top, ink.paper);+ let headerX = 0;+ rows.levels.forEach((spans, level) => {+ const width = frame.rowHeaderWidths[level];+ for (const span of spansIn(spans, r0, r1)) {+ const first = rows.leaves[span.start], last = rows.leaves[span.end - 1];+ const y0 = sy(first.offset), y1 = sy(last.offset + last.size);+ const label = memberLabel(spec.instances[span.part.instanceId], span.part.value);+ const tooltip = `${spec.instances[span.part.instanceId].label}: ${label}`;+ // Dividers separate groups, not the members inside a pane.+ const member = first.kind === 'band' && level === first.path.length - 1;+ if (!member && y0 >= top && first.offset > 0) rect('rowHeader', headerX, y0, left - headerX, 1, ink.line);+ // A parent whose start has scrolled away keeps its label in the visible part.+ if (member && span.start % stride(first.size, 13)) continue;+ const baseline = member ? (y0 + y1) / 2 + 4 : Math.max(y0, top) + 16;+ if (baseline > top + 6 && baseline <= (member ? axisY : Math.min(y1, axisY) - 3)) text('rowHeader', headerX + pad, baseline, fitText(label, width - pad * 2), { tooltip });+ }+ headerX += width;+ });+ for (let i = r0; i < r1; i++) {+ const leaf = rows.leaves[i];+ if (!leaf.scale) continue;+ leaf.scale.ticks.forEach((tick, index) => {+ const y = Math.round(py(leaf, tick));+ if (y < top || y > axisY) return;+ rect('rowHeader', left - 4, y, 4, 1, ink.line);+ text('rowHeader', left - 7, y + 3.5, tickLabel(leaf, index), { align: 'right', fontSize: 10, fill: ink.muted });+ });+ const y0 = Math.max(sy(leaf.offset), top), y1 = Math.min(sy(leaf.offset + leaf.size), axisY);+ const title = leaf.branch.position!.label;+ if (y1 - y0 > 40) text('rowHeader', left - frame.yAxisWidth + 11, (y0 + y1) / 2, fitText(title, y1 - y0 - 8, 10, 600), { angle: 270, align: 'center', fontSize: 10, fontWeight: 600, tooltip: title });+ }+ rect('rowHeader', left - 1, top, 1, axisY - top, ink.line);++ // ---- column headers+ rect('columnHeader', left, 0, viewport.width - left, top, ink.paper);+ if (frame.columnCaptionHeight && bodyRight - left > 40) {+ const caption = columns.captions.join(' / ');+ text('columnHeader', (left + bodyRight) / 2, 15, fitText(caption, bodyRight - left - 8, 10), { align: 'center', fontSize: 10, fill: ink.muted, tooltip: caption });+ }+ let headerY = frame.columnCaptionHeight;+ columns.levels.forEach((spans, level) => {+ const height = frame.columnHeaderHeights[level];+ const rotated = frame.rotateColumnLabels && level === columns.levels.length - 1;+ if (frame.bottomHeaderHeight && level === columns.levels.length - 1) return bottomHeaders(spans, height, rotated);+ for (const span of spansIn(spans, c0, c1)) {+ const first = columns.leaves[span.start], last = columns.leaves[span.end - 1];+ const x0 = sx(first.offset), x1 = sx(last.offset + last.size);+ const label = memberLabel(spec.instances[span.part.instanceId], span.part.value);+ const tooltip = `${spec.instances[span.part.instanceId].label}: ${label}`;+ const member = first.kind === 'band' && level === first.path.length - 1;+ if (!member && x0 >= left && first.offset > 0) rect('columnHeader', x0, headerY, 1, top - headerY, ink.line);+ const v0 = Math.max(x0, left), v1 = Math.min(x1, bodyRight);+ if (member && span.start % stride(first.size, rotated ? 12 : 1)) continue;+ if (rotated) {+ const center = (x0 + x1) / 2;+ if (center >= left && center <= bodyRight) text('columnHeader', center + 4, headerY + height - 5, fitText(label, height - 8), { angle: 270, tooltip });+ } else if (v1 - v0 > 14) {+ text('columnHeader', (v0 + v1) / 2, headerY + 16, fitText(label, v1 - v0 - 8), { align: 'center', tooltip });+ }+ }+ headerY += height;+ });+ rect('columnHeader', left, top - 1, viewport.width - left, 1, ink.line);++ // ---- strip under the body: member names of the innermost column field, or the value axis+ function bottomHeaders(spans: typeof columns.levels[number], height: number, rotated: boolean) {+ for (const span of spansIn(spans, c0, c1)) {+ const leaf = columns.leaves[span.start];+ if (span.start % stride(leaf.size, rotated ? 12 : 1)) continue;+ const center = sx(leaf.offset + leaf.size / 2);+ if (center < left || center > bodyRight) continue;+ const label = memberLabel(spec.instances[span.part.instanceId], span.part.value);+ const tooltip = `${spec.instances[span.part.instanceId].label}: ${label}`;+ // Vertical names hang from the axis line and read upwards.+ if (rotated) text('xAxis', center + 4, axisY + 6, fitText(label, height - 8), { angle: 270, align: 'right', tooltip });+ else text('xAxis', center, axisY + 16, fitText(label, leaf.size - 4), { align: 'center', tooltip });+ }+ }+ if (frame.bottom) {+ rect('xAxis', left, axisY, viewport.width - left, frame.bottom, ink.paper);+ rect('xAxis', left, axisY, bodyRight - left, 1, ink.line);+ // Group dividers run on through the strip.+ if (frame.bottomHeaderHeight && c1 > c0) for (let g = columns.leaves[c0].group; g <= columns.leaves[c1 - 1].group; g++) {+ const x = sx(columns.groups[g].offset);+ if (x >= left && columns.groups[g].offset > 0) rect('xAxis', x, axisY, 1, frame.bottom, ink.line);+ }+ for (let i = c0; i < c1; i++) {+ const leaf = columns.leaves[i];+ if (!leaf.scale) continue;+ const s0 = sx(leaf.offset), s1 = s0 + leaf.size;+ if (s0 >= left && leaf.offset > 0) rect('xAxis', s0, axisY, 1, frame.bottom, ink.line);+ leaf.scale.ticks.forEach((tick, index) => {+ const x = Math.round(px(leaf, tick));+ if (x < left || x > bodyRight) return;+ const label = tickLabel(leaf, index);+ const half = textWidth(label, 10) / 2;+ rect('xAxis', x, axisY, 1, 4, ink.line);+ text('xAxis', x, axisY + 15, label, { align: x - half < s0 + 2 ? 'left' : x + half > s1 - 2 ? 'right' : 'center', fontSize: 10, fill: ink.muted });+ });+ const v0 = Math.max(s0, left), v1 = Math.min(s1, bodyRight);+ const title = leaf.branch.position!.label;+ if (v1 - v0 > 40) text('xAxis', (v0 + v1) / 2, axisY + 31, fitText(title, v1 - v0 - 8, 10, 600), { align: 'center', fontSize: 10, fontWeight: 600, tooltip: title });+ }+ }++ // ---- corners+ rect('corner', 0, 0, left, top, ink.paper);+ let captionX = 0;+ rows.captions.forEach((caption, level) => {+ const width = frame.rowHeaderWidths[level];+ text('corner', captionX + pad, top - 8, fitText(caption, width - pad * 2, metrics.fontSize, 600), { fontWeight: 600, tooltip: caption });+ captionX += width;+ });+ rect('corner', 0, top - 1, left, 1, ink.line);+ rect('corner', left - 1, 0, 1, top, ink.line);+ if (frame.bottom) {+ rect('corner', 0, axisY, left, frame.bottom, ink.paper);+ rect('corner', 0, axisY, left, 1, ink.line);+ }++ // ---- legend, right after the body or on the window edge when the sheet is wider+ if (right && model.legends.length) {+ const x = bodyRight, inner = right - 24;+ rect('legend', x, 0, Math.max(right, viewport.width - x), viewport.height, ink.paper);+ rect('legend', x, 0, 1, Math.min(viewport.height, axisY + frame.bottom), ink.line);+ // One block per channel, top to bottom. A block that does not fit whole ends with a count; one+ // that has no room for a single row is left out.+ let y = 0;+ for (const block of model.legends) {+ const room = viewport.height - y - legendTitleHeight - 2;+ if (block.kind === 'ramp' ? room < 36 : room < block.step) break;+ text('legend', x + 12, y + 17, fitText(block.title, inner, metrics.fontSize, 600), { fontWeight: 600, tooltip: block.title });+ if (block.kind === 'ramp' && model.colorScale) {+ const [low, high] = model.colorScale.domain, steps = 40;+ for (let i = 0; i < steps; i++) rect('legend', x + 12 + i * inner / steps, y + 28, inner / steps + .5, 10, continuousColor(model.colorScale, low + (high - low) * (i + .5) / steps, ink, cells));+ text('legend', x + 12, y + 52, block.entries[0].label, { fontSize: 10, fill: ink.muted });+ text('legend', x + 12 + inner, y + 52, block.entries[1].label, { fontSize: 10, fill: ink.muted, align: 'right' });+ y += block.height;+ continue;+ }+ const rows = Math.max(1, Math.floor(room / block.step));+ const shown = block.entries.length > rows ? rows - 1 : block.entries.length;+ const gutter = block.channel === 'size' ? 24 : 16;+ block.entries.slice(0, shown).forEach((entry, i) => {+ const middle = y + legendTitleHeight + i * block.step + block.step / 2 - 4;+ if (block.channel === 'color') rect('legend', x + 12, middle - 5, 10, 10, ink.category[entry.level % ink.category.length]);+ // Sizes are drawn as circles whatever the mark, small enough for a row.+ else if (block.channel === 'size') items.push({ kind: 'symbol', layer: 'legend', x: x + 21, y: middle, size: (4 + 14 * entry.level) ** 2 * Math.PI / 4, fill: ink.muted });+ else if (block.channel === 'opacity') rect('legend', x + 12, middle - 5, 10, 10, colorField ? ink.text : ink.mark, { opacity: opacityRange ? Math.min(1, Math.max(0, inRange(opacityRange, entry.level))) : opacityAt(entry.level) });+ else items.push({ kind: 'symbol', layer: 'legend', x: x + 17, y: middle, size: 60, symbol: shapes[entry.level % shapes.length], ...(spec.mark === 'point' ? { fill: 'transparent', stroke: ink.text, strokeWidth: 1.5 } : { fill: ink.text }) });+ text('legend', x + 12 + gutter, middle + 4, fitText(entry.label, inner - gutter), { tooltip: entry.label });+ });+ if (shown < block.entries.length) text('legend', x + 12, y + legendTitleHeight + shown * block.step + block.step / 2, words.more(block.entries.length - shown), { fill: ink.muted });+ y += legendTitleHeight + Math.min(block.entries.length, shown + (shown < block.entries.length ? 1 : 0)) * block.step + 6;+ }+ }+ return { width: viewport.width, height: viewport.height, items, visiblePanes, background: ink.paper, legend: !model.legends.length ? 'none' : right ? 'side' : 'omitted',+ body: { x0: left, y0: top, x1: bodyRight, y1: axisY } };+}diff --git a/packages/worksheet-renderer/src/time.ts b/packages/worksheet-renderer/src/time.tsnew file mode 100644index 00000000..b332c451--- /dev/null+++ b/packages/worksheet-renderer/src/time.ts@@ -0,0 +1,101 @@+import { resolveFormats, type Format } from './formats';+import { displayValue, isRange } from './keys';+import { resultKey, type AxisScale, type FieldInstance, type Row, type TimeUnit, type Value } from './types';++/** Milliseconds since the epoch for a Date, an ISO string or a number. NaN for null or anything unreadable. */+export function timeValue(raw: unknown): number {+ if (raw == null) return NaN;+ if (raw instanceof Date) return raw.getTime();+ if (typeof raw === 'number') return raw;+ return typeof raw === 'string' ? Date.parse(raw) : NaN;+}+/** The number a continuous field places a record at. NaN when the record has no value. */+export function positionValue(field: FieldInstance, record: Row): number {+ const raw = record[resultKey(field)];+ return field.scale === 'time' ? fieldTime(field, raw) : raw == null ? NaN : Number(raw);+}+/** The time a time field stands for, with the field's own offset applied. */+export function fieldTime(field: FieldInstance, raw: unknown): number {+ const offset = field.timeOffset ?? 0;+ if (typeof offset === 'number') return timeValue(raw) + offset;+ return timeValue(raw) + (typeof raw !== 'string' ? offset.epoch : /^\d{4}(-\d{2}(-\d{2})?)?$/.test(raw.trim()) ? offset.date : offset.dateTime);+}++const second = 1000, minute = 60 * second, hour = 60 * minute, day = 24 * hour;+type Unit = 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year';+// Candidate tick spacings, smallest first. Months and years step on the calendar, the rest on fixed durations.+const spacings: { unit: Unit; count: number; size: number }[] = [+ ...[1, 5, 15, 30].map(count => ({ unit: 'second' as const, count, size: count * second })),+ ...[1, 5, 15, 30].map(count => ({ unit: 'minute' as const, count, size: count * minute })),+ ...[1, 3, 6, 12].map(count => ({ unit: 'hour' as const, count, size: count * hour })),+ ...[1, 2].map(count => ({ unit: 'day' as const, count, size: count * day })),+ { unit: 'week', count: 1, size: 7 * day },+ ...[1, 2, 3, 6].map(count => ({ unit: 'month' as const, count, size: count * 30.44 * day })),+ ...[1, 2, 5, 10, 20, 50, 100, 200, 500, 1000].map(count => ({ unit: 'year' as const, count, size: count * 365.25 * day })),+];+// All calendar arithmetic and labels are in UTC, so a sheet looks the same on every machine.+const two = (n: number) => String(n).padStart(2, '0');+// ISO 8601 week: weeks start on Monday and week 1 holds the year's first Thursday.+function isoWeek(ms: number): [number, number] {+ const date = new Date(ms);+ const thursday = Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate() + 3 - (date.getUTCDay() + 6) % 7);+ const year = new Date(thursday).getUTCFullYear();+ return [year, 1 + Math.round((thursday - Date.UTC(year, 0, 4)) / (7 * day))];+}+/** The name of the calendar period that starts at `ms`, such as 2024, 2024 Q3 or 2024-07. The same in every language. */+export function formatPeriod(ms: number, unit: TimeUnit): string {+ if (!Number.isFinite(ms)) return '';+ const date = new Date(ms), year = date.getUTCFullYear(), ymd = `${year}-${two(date.getUTCMonth() + 1)}-${two(date.getUTCDate())}`;+ switch (unit) {+ case 'year': return String(year);+ case 'quarter': return `${year} Q${Math.floor(date.getUTCMonth() / 3) + 1}`;+ case 'month': return `${year}-${two(date.getUTCMonth() + 1)}`;+ case 'week': case 'day': return ymd;+ case 'hour': case 'minute': return `${ymd} ${two(date.getUTCHours())}:${two(date.getUTCMinutes())}`;+ case 'second': return `${ymd} ${two(date.getUTCHours())}:${two(date.getUTCMinutes())}:${two(date.getUTCSeconds())}`;+ case 'iso_year': return String(isoWeek(ms)[0]);+ case 'iso_week': { const [isoYear, week] = isoWeek(ms); return `${isoYear} W${two(week)}`; }+ }+}+/**+ * What a member of a discrete field is called. A member of a time field is named after its+ * period, or written as a moment when the field has no unit; a bin is written as its range.+ */+export function memberLabel(field: FieldInstance | undefined, value: Value, format: Format = resolveFormats()): string {+ if (value == null) return format.words.missing;+ if (isRange(value)) return value.map(format.number).join(' – ');+ if (field?.scale !== 'time') return displayValue(value);+ const ms = fieldTime(field, value);+ return (field.timeUnit ? formatPeriod(ms, field.timeUnit) : format.time(ms)) || displayValue(value);+}++/** Calendar ticks for a time range. The domain stays the data range, like tickScale. */+export function timeScale(min: number, max: number, pixels: number, gap: number, format: Format = resolveFormats()): AxisScale {+ const formats = format.date;+ if (min === max) { min -= day / 2; max += day / 2; }+ const wanted = Math.max(2, Math.floor(pixels / gap));+ // The spacing whose tick count is closest to the wanted one, compared as a ratio like the linear ticks.+ const distance = (size: number) => Math.abs(Math.log((max - min) / size / wanted));+ const spacing = spacings.reduce((best, next) => distance(next.size) < distance(best.size) ? next : best);+ const ticks: number[] = [];+ if (spacing.unit === 'month' || spacing.unit === 'year') {+ const months = spacing.unit === 'year' ? spacing.count * 12 : spacing.count;+ const start = new Date(min);+ let index = Math.ceil((start.getUTCFullYear() * 12 + start.getUTCMonth()) / months) * months;+ if (Date.UTC(Math.floor(index / 12), index % 12, 1) < min) index += months;+ for (let t = Date.UTC(Math.floor(index / 12), index % 12, 1); t <= max; index += months, t = Date.UTC(Math.floor(index / 12), index % 12, 1)) ticks.push(t);+ } else {+ // Weeks start on Monday; the epoch was a Thursday.+ const shift = spacing.unit === 'week' ? 4 * day : 0;+ for (let t = Math.ceil((min - shift) / spacing.size) * spacing.size + shift; t <= max; t += spacing.size) ticks.push(t);+ }+ const labels = ticks.map((t, i) => {+ const date = new Date(t);+ if (spacing.unit === 'year') return formats.year(t);+ // The year shows where it changes, and on the first tick so a range inside one year still names it.+ if (spacing.unit === 'month') return date.getUTCMonth() === 0 ? formats.year(t) : i === 0 ? formats.monthYear(t) : formats.month(t);+ if (spacing.unit === 'day' || spacing.unit === 'week' || t % day === 0) return formats.day(t);+ return (spacing.unit === 'second' ? formats.seconds : formats.time)(t);+ });+ return { domain: [min, max], ticks, labels };+}diff --git a/packages/worksheet-renderer/src/types.ts b/packages/worksheet-renderer/src/types.tsnew file mode 100644index 00000000..e762abbd--- /dev/null+++ b/packages/worksheet-renderer/src/types.ts@@ -0,0 +1,347 @@+/** A pair of numbers is a bin: the range of values one member of a binned field covers. */+export type Value = string | number | boolean | Date | null | undefined | readonly number[];+export type Row = Record<string, any>;+/**+ * 'expr' is an aggregate the host defines, such as a ratio of two sums. `field` names it; the host's+ * computation works its value out per group from an expression of its own. The sheet only asks for+ * it at each grain it draws and reads the result.+ */+export type Aggregate = 'sum' | 'mean' | 'median' | 'min' | 'max' | 'count' | 'distinctCount' | 'variance' | 'stdev' | 'expr';+export interface FieldInstance {+ id: string;+ field: string;+ label: string;+ display: 'discrete' | 'continuous';+ /**+ * 'time' reads Dates, ISO strings or epoch milliseconds. A continuous field then draws a+ * calendar axis; a discrete one labels its members as dates instead of raw values.+ */+ scale?: 'linear' | 'time';+ /** For a discrete time field: the calendar unit its members were truncated to, which picks the label. A full date without it. */+ timeUnit?: TimeUnit;+ /**+ * Milliseconds added to every time of this field before it is placed or labelled. Labels are+ * written in UTC, so a host that wants another zone passes that zone's offset here.+ * Stored times come in three kinds that a host may need to shift differently: `epoch` for+ * numbers and Dates, `date` for text that names a day, month or year only, which is read+ * as UTC, and `dateTime` for any other text, which is read in the machine's own zone+ * unless it names one.+ */+ timeOffset?: number | { epoch: number; date: number; dateTime: number };+ /** Whether a linear axis for this field starts from zero. Defaults to true; a time axis never does. */+ zero?: boolean;+ aggregate?: Aggregate;+}+/**+ * Settings of the value axes on one shelf, or of one channel. What is left out follows the data.+ */+export interface ScaleOptions {+ type?: import('./warp').ScaleType;+ /** Fixed ends of the range. Marks outside a fixed axis range are cut off at the edge of their pane. */+ min?: number;+ max?: number;+ /**+ * Channels only: what the lowest and the highest value turn into. For opacity, two numbers+ * between 0 and 1. For size, px: the area of a point in square px, the thickness of a bar,+ * the length of a tick, the width of a line, the font size of text.+ */+ range?: [number, number];+ /** Channels with a continuous field only: every pane ranges over its own values, and the legend names no numbers. */+ independent?: boolean;+}+export type TimeUnit = 'year' | 'quarter' | 'month' | 'week' | 'day' | 'hour' | 'minute' | 'second' | 'iso_year' | 'iso_week';+export type AxisExpr =+ | { kind: 'empty' }+ | { kind: 'field'; instanceId: string }+ | { kind: 'nest' | 'cross'; items: AxisExpr[] }+ | { kind: 'concat'; items: AxisExpr[] };+/**+ * shared: one range per measure for the whole sheet.+ * prefix: one range per measure inside each outermost header on the same axis.+ * independent: one range per row or column of panes.+ * A range never varies inside one row or column, so its axis can sit on the table edge.+ */+export type ScaleScope = 'shared' | 'independent' | 'prefix';+export interface WorksheetSpec {+ kind: 'worksheet';+ specVersion: 2;+ instances: Record<string, FieldInstance>;+ rows: AxisExpr;+ columns: AxisExpr;+ /**+ * point is a hollow circle, circle a filled one, tick a short line across the value axis.+ * area fills from the start of each mark's interval to its end, joined along the other axis.+ * arc draws one pie per cell of the table; rows and columns then take dimensions only.+ * boxplot summarises the records of each member along the one continuous axis.+ */+ mark: 'bar' | 'point' | 'circle' | 'tick' | 'line' | 'area' | 'rect' | 'text' | 'arc' | 'boxplot';+ /** A discrete field gives one color per member. A continuous field, aggregated or not, gives a continuous scale. */+ color?: string;+ /**+ * Dimensions that split marks without coloring them. For a box plot they only set the+ * grain of the records a box summarises; boxes are split by color alone.+ */+ detail?: string[];+ /** The measure that sizes the slices of arc marks. Without it every slice gets the same share. */+ angle?: string;+ /**+ * The value written by text marks; without it a text mark shows the measure it is positioned+ * by. On any other mark it is a label written next to the mark, or inside it where it fits.+ * Labels that would run into each other are left out.+ */+ text?: string;+ /**+ * Sizes marks by a field: the area of points, the thickness of bars, the length of ticks, the+ * width of lines, the font size of text, the side of heat map cells. A measure sizes from+ * zero; a dimension gives each member its own step.+ */+ size?: string;+ /** Makes marks more or less opaque by a field. A dimension gives each member its own step. */+ opacity?: string;+ /** Gives each member of a dimension its own symbol. Only point and circle marks have one. */+ shape?: string;+ /** `rows` and `columns` apply to every value axis on that shelf, time axes excepted. */+ scales?: { rows?: ScaleOptions; columns?: ScaleOptions; color?: ScaleOptions; size?: ScaleOptions; opacity?: ScaleOptions };+ /**+ * How bars and areas that share a position pile up. They stack end to end unless this is+ * false, in which case they overlap from the zero line. 'normalize' stacks their shares of+ * the pile, so every pile runs from 0 to 100%. 'center' stacks them end to end with the+ * pile centered on zero. Both of those pile magnitudes, whatever the sign.+ */+ stack?: boolean | 'normalize' | 'center';+ /**+ * How far a value axis range is shared. One value applies to both shelves; `rows` and `columns`+ * set it for the value axes on each shelf, and a shelf left out shares its ranges across the sheet.+ */+ scaleScope?: ScaleScope | { rows?: ScaleScope; columns?: ScaleScope };+ sort?: 'ascending' | 'descending';+ /**+ * Member order per field instance, overriding sort. A list gives the order outright;+ * members it omits follow in value order. A measure orders the members by its value.+ */+ order?: Record<string, 'ascending' | 'descending' | Value[] | MeasureOrder>;+ /**+ * Keeps only the first `rows` records of each result, as a query limit does. With `by`+ * the records are first ordered by that field, which makes it a top or bottom N.+ */+ limit?: { rows: number; by?: string; direction?: 'ascending' | 'descending' };+ /** Where the innermost column headers go. By default at the bottom when rows carry a value axis, as in Tableau. */+ innerColumnHeader?: 'top' | 'bottom';+ filters?: { field: string; values: Value[] }[];+ /** Extent of one continuous axis slot. */+ pane?: { width?: number; height?: number };+ /** Step of one discrete member. Every member on an axis gets the same step. */+ band?: { width?: number; height?: number };+ /** Scale the steps so the sheet fills the available width, height or both. */+ fit?: 'width' | 'height' | 'both';+ /**+ * Lets the continuous axis slots share the room the window leaves over, in width, height or+ * both. Member steps keep their size, so three bars stay three narrow bars in a wide window.+ * A sheet that does not fit with every slot at its least size scrolls. Pies grow as squares,+ * and only with 'both'. Where `fit` is set too, `fit` wins.+ */+ stretch?: 'width' | 'height' | 'both';+}+/**+ * Orders the members of a dimension by an aggregated measure. The measure is computed per+ * member inside its parent headers on the same axis, over everything else in the sheet, so+ * each parent group is ordered on its own, as Tableau's nested sort is. Members without a+ * value come last in either direction.+ */+export interface MeasureOrder { by: string; direction?: 'ascending' | 'descending' }+// A structural subset of Graphic Walker's IComputationFunction protocol.+// Keep the renderer independent of the host's React/store/query implementation.+export interface QueryPayload {+ workflow: (+ | { type: 'filter'; filters: { fid: string; rule: { type: 'one of'; value: any[] } }[] }+ | { type: 'view'; query: ViewQuery[] }+ | { type: 'sort'; by: string[]; sort: 'ascending' | 'descending' }+ )[];+ /** Number of result rows to return, counted after every step. */+ limit?: number;+}+/** 'raw' returns the listed fields of every source row, duplicates included. Only box plots of an unaggregated field ask for it. */+export type ViewQuery =+ | { op: 'aggregate'; groupBy: string[]; measures: { field: string; agg: Aggregate; asFieldKey: string }[] }+ | { op: 'raw'; fields: string[] };+export type Computation = (payload: QueryPayload) => Promise<Row[]>;+export interface AxisBranch {+ id: string;+ facets: FieldInstance[];+ position?: FieldInstance;+ order: number;+}+export interface QueryTask {+ id: string;+ groupBy: string[];+ measures: FieldInstance[];+ /** Every source row is wanted, not one row per group. */+ raw?: boolean;+ payload: QueryPayload;+}+export interface Binding {+ row: AxisBranch;+ column: AxisBranch;+ taskId: string;+}+/** Where the values that order the members of one field under one chain of parent fields come from. */+export interface Ranking {+ instanceId: string;+ /** The fields above it on its axis, outermost first. */+ parents: FieldInstance[];+ by: FieldInstance;+ direction: 'ascending' | 'descending';+ taskId: string;+}+export interface Plan {+ spec: WorksheetSpec;+ rows: AxisBranch[];+ columns: AxisBranch[];+ tasks: QueryTask[];+ bindings: Binding[];+ rankings: Ranking[];+}+export interface PathPart { instanceId: string; value: Value }+export interface AxisScale {+ domain: [number, number];+ ticks: number[];+ /** Tick labels when they are not plain numbers, as on a time axis. */+ labels?: string[];+ /** Smallest distance between two positions on this axis, in domain units. Sizes bars drawn at continuous positions. */+ step?: number;+ /** Names the range this axis shows. Every leaf that shares the range has the same key; a zoom is stored under it. */+ key?: string;+ /** The range the data and the axis settings ask for. It differs from `domain` while the axis is zoomed or panned. */+ full?: [number, number];+ /** How values are spread along the axis. Linear when absent. */+ type?: import('./warp').ScaleType;+ /** An end of the range was set by hand, so some marks may lie outside it. */+ fixed?: boolean;+}+/**+ * One layout position along an axis. A discrete terminal field contributes one leaf per+ * member, a continuous terminal field one leaf per axis slot.+ */+export interface AxisLeaf {+ id: string;+ index: number;+ branch: AxisBranch;+ /** Header path: the facets, then the member when the terminal field is discrete. */+ path: PathPart[];+ kind: 'band' | 'continuous' | 'single';+ /** Index of the pane group this leaf belongs to. */+ group: number;+ offset: number;+ size: number;+ scale?: AxisScale;+}+/** The extent of a pane along one axis: a contiguous run of leaves below one facet path. */+export interface AxisGroup {+ id: string;+ index: number;+ branch: AxisBranch;+ path: PathPart[];+ /** Half-open leaf range. */+ start: number;+ end: number;+ offset: number;+ size: number;+}+export interface HeaderSpan {+ key: string;+ part: PathPart;+ /** Half-open leaf range. */+ start: number;+ end: number;+}+export interface AxisLayout {+ axis: 'row' | 'column';+ leaves: AxisLeaf[];+ groups: AxisGroup[];+ /** Header spans per level, ordered by leaf position. */+ levels: HeaderSpan[][];+ /** Field labels per header level. */+ captions: string[];+ size: number;+}+export interface Selection {+ /** Identity of the mark: its branch pair and dimension values. Survives scrolling and re-sorting. */+ id: string;+ paneId: string;+ rowPath: PathPart[];+ columnPath: PathPart[];+ predicates: { field: string; value: Value }[];+ values: Row;+}+export interface PaneMark {+ record: Row;+ /** Leaf indices on each axis. */+ row: number;+ column: number;+ /**+ * Value interval on the continuous axis. NaN when the record has no value.+ * For an arc, the slice as shares of a full turn. For a box, the whisker ends.+ */+ start: number;+ end: number;+ /** Under a normalized stack: the mark's share of its pile, between 0 and 1. */+ share?: number;+ /** Set on the one mark that stands for a whole box. Its record holds the dimensions and the median. */+ box?: BoxSummary;+ /** A record outside the whiskers of its box, drawn on its own. */+ outlier?: boolean;+ /** Which share of the member step the mark takes when several series sit side by side: index and count. */+ slot?: [number, number];+}+/** Tukey box: quartiles, and whiskers at the furthest records within 1.5 times the box length. */+export interface BoxSummary { low: number; q1: number; median: number; q3: number; high: number; count: number }+export interface Pane {+ id: string;+ row: AxisGroup;+ column: AxisGroup;+ records: Row[];+ marks: PaneMark[];+ xDomain: [number, number];+ yDomain: [number, number];+ /** The pane's own range on a channel that is set to range independently. */+ domains?: { color?: [number, number]; size?: [number, number]; opacity?: [number, number] };+}+/** Fixed chrome around the scrolling body, in CSS px. */+export interface ColorScale { field: FieldInstance; domain: [number, number]; diverging: boolean; type?: import('./warp').ScaleType }+export interface Frame {+ left: number;+ top: number;+ bottom: number;+ /** Width of the legend strip, 0 without a color field. */+ right: number;+ /** Height of the innermost column header level when it is drawn under the body, else 0. */+ bottomHeaderHeight: number;+ rowHeaderWidths: number[];+ columnHeaderHeights: number[];+ /** The innermost column header level is drawn vertically. */+ rotateColumnLabels: boolean;+ columnCaptionHeight: number;+ yAxisWidth: number;+}+export interface WorksheetModel {+ /** How numbers, dates and the sheet's own words are written. */+ format: import('./formats').Format;+ /** The spans of the fields on size and opacity, and the members of the field on shape. */+ channels: { size?: import('./channels').ChannelScale; opacity?: import('./channels').ChannelScale; shape?: import('./channels').ChannelScale };+ /** What the legend strip shows, top to bottom. */+ legends: import('./channels').LegendBlock[];+ plan: Plan;+ rows: AxisLayout;+ columns: AxisLayout;+ panes: Pane[];+ paneIndex: Map<string, Pane>;+ frame: Frame;+ width: number;+ height: number;+ colors: Value[];+ colorScale?: ColorScale;+}+export const field = (instanceId: string): AxisExpr => ({ kind: 'field', instanceId });+export const nest = (...items: AxisExpr[]): AxisExpr => ({ kind: 'nest', items });+export const concat = (...items: AxisExpr[]): AxisExpr => ({ kind: 'concat', items });+export const resultKey = (instance: FieldInstance) => instance.aggregate ? `__ws_${instance.id}` : instance.field;diff --git a/packages/worksheet-renderer/src/vegaBackend.ts b/packages/worksheet-renderer/src/vegaBackend.tsnew file mode 100644index 00000000..03defe9e--- /dev/null+++ b/packages/worksheet-renderer/src/vegaBackend.ts@@ -0,0 +1,76 @@+import { parse, View, type Spec } from 'vega';+import { layers, type Layer, type Primitive, type Scene } from './scene';++// The order things are painted in within a layer. 'surface' and 'rule' hold the rects and lines marked+// `under`, so the paper and the grid stay below the marks whatever kind those are.+const slots = ['surface', 'rule', 'rect', 'shape', 'path', 'symbol', 'text'] as const;+type Slot = typeof slots[number];+export const dataName = (layer: Layer, slot: Slot) => `${layer}_${slot}`;+const slotOf = (item: Primitive): Slot => item.under && item.kind === 'rect' ? 'surface' : item.under && item.kind === 'path' ? 'rule' : item.kind;+export function sceneData(scene: Scene): Map<string, Primitive[]> {+ const data = new Map<string, Primitive[]>(layers.flatMap(layer => slots.map(slot => [dataName(layer, slot), []] as [string, Primitive[]])));+ for (const item of scene.items) data.get(dataName(item.layer, slotOf(item)))!.push(item);+ return data;+}++// Vega only paints positioned primitives. One group per scene layer keeps the paint order+// across mark types; there is one View and one canvas for the whole worksheet.+export function vegaSpec(scene: Scene): Spec {+ const data = sceneData(scene);+ const pointer = { signal: "datum.selection ? 'pointer' : 'default'" };+ return {+ $schema: 'https://vega.github.io/schema/vega/v5.json',+ width: scene.width, height: scene.height, padding: 0, autosize: 'none', background: scene.background,+ data: [...data].map(([name, values]) => ({ name, values })),+ marks: layers.map(layer => ({+ type: 'group' as const,+ encode: { update: { x: { value: 0 }, y: { value: 0 } } },+ marks: [+ { type: 'rect' as const, from: { data: dataName(layer, 'surface') }, encode: { update: {+ x: { field: 'x' }, y: { field: 'y' }, width: { field: 'width' }, height: { field: 'height' }, fill: { field: 'fill' },+ } } },+ { type: 'path' as const, from: { data: dataName(layer, 'rule') }, interactive: false, encode: { update: {+ x: { field: 'x' }, y: { field: 'y' }, path: { field: 'path' }, stroke: { field: 'stroke' }, strokeWidth: { signal: 'datum.strokeWidth || 1' }, strokeDash: { field: 'dash' },+ } } },+ { type: 'rect' as const, from: { data: dataName(layer, 'rect') }, encode: { update: {+ x: { field: 'x' }, y: { field: 'y' }, width: { field: 'width' }, height: { field: 'height' },+ fill: { field: 'fill' }, stroke: { field: 'stroke' }, opacity: { field: 'opacity' }, cursor: pointer,+ cornerRadiusTopLeft: { signal: 'datum.radius ? datum.radius[0] : 0' }, cornerRadiusTopRight: { signal: 'datum.radius ? datum.radius[1] : 0' },+ cornerRadiusBottomRight: { signal: 'datum.radius ? datum.radius[2] : 0' }, cornerRadiusBottomLeft: { signal: 'datum.radius ? datum.radius[3] : 0' },+ } } },+ { type: 'path' as const, from: { data: dataName(layer, 'shape') }, encode: { update: {+ x: { field: 'x' }, y: { field: 'y' }, path: { field: 'path' }, fill: { field: 'fill' }, stroke: { field: 'stroke' }, strokeWidth: { field: 'strokeWidth' },+ opacity: { field: 'opacity' }, cursor: pointer,+ } } },+ { type: 'path' as const, from: { data: dataName(layer, 'path') }, interactive: false, encode: { update: {+ x: { field: 'x' }, y: { field: 'y' }, path: { field: 'path' }, stroke: { field: 'stroke' }, strokeWidth: { signal: 'datum.strokeWidth || 1.8' }, strokeDash: { field: 'dash' }, opacity: { field: 'opacity' },+ } } },+ { type: 'symbol' as const, from: { data: dataName(layer, 'symbol') }, encode: { update: {+ x: { field: 'x' }, y: { field: 'y' }, size: { field: 'size' }, shape: { signal: "datum.symbol || 'circle'" }, fill: { field: 'fill' }, stroke: { field: 'stroke' }, strokeWidth: { field: 'strokeWidth' },+ opacity: { field: 'opacity' }, cursor: pointer,+ } } },+ { type: 'text' as const, from: { data: dataName(layer, 'text') }, encode: { update: {+ x: { field: 'x' }, y: { field: 'y' }, text: { field: 'text' }, fill: { field: 'fill' }, align: { field: 'align' },+ angle: { field: 'angle' }, fontSize: { field: 'fontSize' }, fontWeight: { field: 'fontWeight' },+ font: { signal: "datum.font || 'system-ui, sans-serif'" }, opacity: { field: 'opacity' }, cursor: pointer,+ } } },+ ],+ })),+ };+}++/**+ * The scene as a PNG data URL, `scale` device pixels per CSS pixel. Needs a canvas, so it+ * works in a browser and not in plain Node.+ */+export async function sceneToPNG(scene: Scene, scale = 2): Promise<string> {+ const view = new View(parse(vegaSpec(scene)), { renderer: 'none' });+ try { await view.runAsync(); return (await view.toCanvas(scale)).toDataURL('image/png'); }+ finally { view.finalize(); }+}++export async function sceneToSVG(scene: Scene): Promise<string> {+ const view = new View(parse(vegaSpec(scene)), { renderer: 'none' });+ try { await view.runAsync(); return await view.toSVG(); }+ finally { view.finalize(); }+}diff --git a/packages/worksheet-renderer/src/warp.ts b/packages/worksheet-renderer/src/warp.tsnew file mode 100644index 00000000..a29d8cc6--- /dev/null+++ b/packages/worksheet-renderer/src/warp.ts@@ -0,0 +1,55 @@+/**+ * How values are spread along an axis or a channel. 'linear' spreads them evenly. 'log'+ * gives every power of ten the same room and has no place for zero or negative values.+ * 'sqrt' and 'symlog' compress large values and keep zero and negative ones.+ */+export type ScaleType = 'linear' | 'log' | 'sqrt' | 'symlog';++interface Warp { to: (value: number) => number; from: (warped: number) => number }+const warps: Record<ScaleType, Warp> = {+ linear: { to: v => v, from: w => w },+ log: { to: v => v > 0 ? Math.log10(v) : NaN, from: w => 10 ** w },+ sqrt: { to: v => Math.sign(v) * Math.sqrt(Math.abs(v)), from: w => Math.sign(w) * w * w },+ symlog: { to: v => Math.sign(v) * Math.log1p(Math.abs(v)), from: w => Math.sign(w) * Math.expm1(Math.abs(w)) },+};++/** The two directions of a scale type: into the space where values are spread evenly, and back. */+export const warp = (type: ScaleType = 'linear'): Warp => warps[type];++/**+ * Where a value sits in a range, from 0 at its start to 1 at its end; outside that for a+ * value outside the range. NaN when the value has no place, such as zero on a log scale.+ */+export function position(domain: readonly [number, number], value: number, type: ScaleType = 'linear'): number {+ const { to } = warps[type];+ const low = to(domain[0]), high = to(domain[1]);+ return (to(value) - low) / (high - low);+}+/** The value at a share of a range. The inverse of `position`. */+export function valueAt(domain: readonly [number, number], share: number, type: ScaleType = 'linear'): number {+ const { to, from } = warps[type];+ const low = to(domain[0]), high = to(domain[1]);+ return from(low + (high - low) * share);+}++/**+ * Ticks for a log axis: the powers of ten in the range, and between them the multiples+ * 2 and 5 while there is room for them. A range inside one power of ten gets linear ticks.+ */+export function logTicks(min: number, max: number, wanted: number): number[] | undefined {+ const first = Math.ceil(Math.log10(min) - 1e-9), last = Math.floor(Math.log10(max) + 1e-9);+ const decades = last - first + 1;+ if (decades < 1 || (decades === 1 && Math.log10(max / min) < 1)) return undefined;+ // With many decades only every nth power is shown.+ const every = Math.max(1, Math.ceil(decades / Math.max(2, wanted)));+ const between = decades * 3 <= wanted ? [1, 2, 5] : [1];+ const ticks: number[] = [];+ for (let power = first - 1; power <= last; power++) {+ if (between.length === 1 && (power - first) % every) continue;+ for (const multiple of between) {+ const tick = Number((multiple * 10 ** power).toPrecision(12));+ if (tick >= min * (1 - 1e-9) && tick <= max * (1 + 1e-9)) ticks.push(tick);+ }+ }+ return ticks;+}diff --git a/packages/worksheet-renderer/src/zoom.ts b/packages/worksheet-renderer/src/zoom.tsnew file mode 100644index 00000000..f911daf0--- /dev/null+++ b/packages/worksheet-renderer/src/zoom.ts@@ -0,0 +1,55 @@+import type { Box } from './clip';+import { leafRange, metrics } from './layout';+import type { Zoom } from './model';+import type { Viewport } from './scene';+import type { AxisLeaf, WorksheetModel } from './types';+import { warp } from './warp';++/** The continuous axes under a point of the window, each with how far along its range the point is, from 0 to 1. */+export interface AxesAt { x?: { leaf: AxisLeaf; t: number }; y?: { leaf: AxisLeaf; t: number } }++const inner = (leaf: AxisLeaf) => leaf.size - metrics.scalePadStart - metrics.scalePadEnd;++/**+ * What a pointer at window position (px, py) can zoom: the value axes of the pane it is over.+ * Nothing outside the body, and nothing in a pane without a value axis, such as a table of text.+ */+export function axesAt(model: WorksheetModel, body: Box, viewport: Viewport, px: number, py: number): AxesAt {+ if (px < body.x0 || px >= body.x1 || py < body.y0 || py >= body.y1) return {};+ const lx = px - model.frame.left + viewport.x, ly = py - model.frame.top + viewport.y;+ const column = model.columns.leaves[leafRange(model.columns, lx, lx + 1e-6)[0]];+ const row = model.rows.leaves[leafRange(model.rows, ly, ly + 1e-6)[0]];+ const found: AxesAt = {};+ if (column?.scale?.key) found.x = { leaf: column, t: (lx - column.offset - metrics.scalePadStart) / inner(column) };+ // Values grow upwards.+ if (row?.scale?.key) found.y = { leaf: row, t: (row.offset + row.size - ly - metrics.scalePadStart) / inner(row) };+ return found;+}++// How far in and out an axis can go, as multiples of the range the data asks for.+const closest = 1e-4, widest = 20;++/** The range after zooming `from` by `factor` around the point at share `t` of it. Below 1 zooms in. */+export function zoomed(leaf: AxisLeaf, from: readonly [number, number], t: number, factor: number): [number, number] {+ // On an axis that is not linear the zoom works where its values are spread evenly, so the point under the pointer stays put.+ const { to, from: back } = warp(leaf.scale!.type);+ const low = to(from[0]), high = to(from[1]), [fullLow, fullHigh] = (leaf.scale!.full ?? leaf.scale!.domain).map(to);+ const span = high - low, whole = fullHigh - fullLow;+ const next = Math.min(whole * widest, Math.max(whole * closest, span * factor));+ const at = low + span * t;+ return [back(at - next * t), back(at + next * (1 - t))];+}+/** The range after moving the axis by `pixels` on screen, in the direction its values grow. */+export function panned(leaf: AxisLeaf, from: readonly [number, number], pixels: number): [number, number] {+ const { to, from: back } = warp(leaf.scale!.type);+ const low = to(from[0]), high = to(from[1]), shift = -pixels / inner(leaf) * (high - low);+ return [back(low + shift), back(high + shift)];+}+/** `zoom` with the range of one axis replaced. Returning to the range the data asks for drops the entry. */+export function withRange(zoom: Zoom, leaf: AxisLeaf, range: [number, number]): Zoom {+ const { key, full } = leaf.scale!;+ const next = { ...zoom };+ if (full && Math.abs(range[0] - full[0]) < 1e-9 * Math.abs(full[1] - full[0]) && Math.abs(range[1] - full[1]) < 1e-9 * Math.abs(full[1] - full[0])) delete next[key!];+ else next[key!] = range;+ return next;+}diff --git a/packages/worksheet-renderer/tests/channels.test.ts b/packages/worksheet-renderer/tests/channels.test.tsnew file mode 100644index 00000000..225ba903--- /dev/null+++ b/packages/worksheet-renderer/tests/channels.test.ts@@ -0,0 +1,111 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { compileWorksheet } from '../src/compiler';+import { opacityAt, pointArea, thicknessShare } from '../src/channels';+import { metrics } from '../src/layout';+import { field, nest, type Row, type WorksheetSpec } from '../src/types';+import { fields, fullScene, model, near } from './helpers';++const instances = { ...fields(['product', 'segment', 'region'], { sum: ['value', 'sum'], qty: ['qty', 'sum'], mean: ['value', 'mean'] }) };+const base = { kind: 'worksheet' as const, specVersion: 2 as const, instances };+const rows: Row[] = [{ product: 'a', segment: 's', region: 'E', value: 10, qty: 0 }, { product: 'b', segment: 't', region: 'E', value: 20, qty: 50 }, { product: 'c', segment: 'u', region: 'W', value: 40, qty: 100 }];+const marks = (m: Awaited<ReturnType<typeof model>>) => fullScene(m).items.filter(p => p.selection).sort((a, b) => String(a.selection!.values.product).localeCompare(String(b.selection!.values.product)));+const scatter: WorksheetSpec = { ...base, rows: field('sum'), columns: field('product'), mark: 'circle' };++test('a measure on size sizes marks from zero, and joins the query without splitting marks', async () => {+ const m = await model({ ...scatter, size: 'qty' }, rows);+ assert.equal(m.plan.tasks.length, 1);+ assert.deepEqual(m.plan.tasks[0].measures.map(f => f.id), ['sum', 'qty']);+ assert.deepEqual(m.channels.size!.domain, [0, 100]);+ assert.deepEqual(marks(m).map(p => p.size), [pointArea(0), pointArea(.5), pointArea(1)]);+ // Bars get thinner, ticks shorter, text smaller, heat cells smaller; none of them moves.+ const barModel = await model({ ...base, rows: field('product'), columns: field('sum'), mark: 'bar', size: 'qty' }, rows);+ const bars = marks(barModel);+ const full = metrics.bandHeight * metrics.barFill;+ assert.ok(near(bars[0].height!, full * thicknessShare(0), .01) && near(bars[2].height!, full, .01));+ bars.forEach((bar, i) => assert.ok(near(bar.y + bar.height! / 2, barModel.frame.top + metrics.bandHeight * (i + .5), .01), 'a thinner bar stays centered on its member'));+ const cells = marks(await model({ ...base, rows: field('product'), columns: field('segment'), mark: 'rect', color: 'sum', size: 'qty' }, rows));+ assert.ok(cells[0].width! < cells[1].width! && cells[1].width! < cells[2].width!);+ const texts = marks(await model({ ...base, rows: field('product'), columns: field('segment'), mark: 'text', text: 'sum', size: 'qty' }, rows));+ assert.deepEqual(texts.map(p => p.fontSize), [9, 17, 24]);+});+test('a dimension on size or opacity gives each member a step and splits the marks', async () => {+ const m = await model({ ...base, rows: field('sum'), columns: field('region'), mark: 'circle', size: 'segment', opacity: 'segment' }, rows);+ assert.deepEqual(m.plan.tasks[0].groupBy, ['region', 'segment']);+ const drawn = marks(m);+ assert.equal(drawn.length, 3);+ assert.deepEqual(drawn.map(p => p.size), [1 / 3, 2 / 3, 1].map(pointArea));+ assert.ok(drawn.every((p, i) => near(p.opacity ?? 1, opacityAt((i + 1) / 3), 1e-9)), 'the last member is fully opaque');+});+test('a measure on opacity runs from faint to solid over its own range', async () => {+ const drawn = marks(await model({ ...scatter, opacity: 'sum' }, rows));+ assert.deepEqual(drawn.map(p => p.opacity), [opacityAt(0), opacityAt(1 / 3), undefined]);+});+test('shape gives each member of a dimension its own symbol on points and circles', async () => {+ const m = await model({ ...scatter, mark: 'point', shape: 'segment' }, rows);+ assert.deepEqual(marks(m).map(p => p.symbol), ['circle', 'square', 'triangle-up']);+ assert.ok(marks(m).every(p => p.fill === 'transparent' && p.stroke));+ assert.throws(() => compileWorksheet({ ...scatter, shape: 'sum' }), /Shape takes a dimension/);+});+test('each channel gets its own block in the legend strip', async () => {+ const m = await model({ ...scatter, color: 'region', size: 'qty', opacity: 'segment', shape: 'segment' }, rows);+ assert.deepEqual(m.legends.map(b => [b.channel, b.title, b.entries.map(e => e.label)]), [+ ['color', 'region', ['E', 'W']], ['size', 'QTY', ['0', '50', '100']], ['opacity', 'segment', ['s', 't', 'u']], ['shape', 'segment', ['s', 't', 'u']],+ ]);+ const legend = fullScene(m).items.filter(p => p.layer === 'legend');+ const titles = legend.filter(p => p.fontWeight === 600).map(p => [p.text, p.y]);+ assert.deepEqual(titles.map(t => t[0]), ['region', 'QTY', 'segment', 'segment']);+ assert.ok(titles.every((t, i) => i === 0 || (t[1] as number) > (titles[i - 1][1] as number)), 'blocks follow one another down the strip');+ assert.equal(legend.filter(p => p.kind === 'symbol' && p.symbol).length, 3);+ assert.ok(m.height >= m.legends.reduce((sum, block) => sum + block.height, 0), 'a short sheet still shows the whole legend');+ assert.equal(fullScene(await model(scatter, rows)).legend, 'none');+});+test('a line takes one width and one opacity from its member', async () => {+ const data: Row[] = ['s', 't'].flatMap(segment => [1, 2, 3].map(product => ({ product, segment, value: product })));+ const paths = fullScene(await model({ ...base, rows: field('sum'), columns: field('product'), mark: 'line', size: 'segment', opacity: 'segment' }, data)).items.filter(p => p.kind === 'path');+ assert.deepEqual(paths.map(p => p.strokeWidth), [1 + 5 * .5, 1 + 5]);+ assert.deepEqual(paths.map(p => p.opacity), [opacityAt(.5), undefined]);+});++// ---- labels+const labelled = (m: Awaited<ReturnType<typeof model>>) => fullScene(m).items.filter(p => p.layer === 'body' && p.kind === 'text');+test('a bar on its own is labelled past its end, or just inside the end when there is no room', async () => {+ const m = await model({ ...base, rows: field('product'), columns: field('sum'), mark: 'bar', text: 'sum' }, rows);+ const bars = marks(m), labels = labelled(m).sort((a, b) => a.y - b.y);+ assert.deepEqual(labels.map(p => p.text), ['10', '20', '40']);+ assert.ok(near(labels[0].x, bars[0].x + bars[0].width! + 4) && labels[0].align === 'left');+ // The longest bar ends at the edge of its slot, so its label moves inside and takes a color that reads on the bar.+ assert.ok(labels[2].align === 'right' && near(labels[2].x, bars[2].x + bars[2].width! - 4));+ assert.equal(labels[2].fill, '#ffffff');+ assert.ok(labels.every(p => !p.selection), 'labels do not take the pointer');+ assert.equal(bars[0].tooltip, 'product: a\nSUM: 10', 'the measure that is both the axis and the label is described once');+});+test('bars in a pile are labelled inside, and only where the label fits', async () => {+ const data: Row[] = [{ product: 'p', segment: 'a', value: 1 }, { product: 'p', segment: 'b', value: 500 }, { product: 'p', segment: 'c', value: 499 }];+ const labels = labelled(await model({ ...base, rows: field('product'), columns: field('sum'), mark: 'bar', color: 'segment', text: 'sum' }, data));+ assert.deepEqual(labels.map(p => p.text).sort(), ['499', '500']);+ assert.ok(labels.every(p => p.align === 'center'));+});+test('labels that would run into each other are left out, first come first kept', async () => {+ // Three points at almost the same place: one label has room on each side, the third has none.+ const data: Row[] = [{ product: 'a', value: 100 }, { product: 'b', value: 100.01 }, { product: 'c', value: 100.02 }, { product: 'd', value: 100.03 }, { product: 'e', value: 0 }];+ const spec: WorksheetSpec = { ...base, rows: field('sum'), columns: field('region'), mark: 'circle', detail: ['product'], text: 'product' };+ const labels = labelled(await model(spec, data.map(r => ({ ...r, region: 'E' }))));+ assert.ok(labels.length >= 2 && labels.length < 5, `${labels.length} labels`);+ const boxes = labels.map(p => { const w = 6; const x0 = p.align === 'left' ? p.x : p.align === 'right' ? p.x - w : p.x - w / 2; return [x0, p.y - 10, x0 + w, p.y + 2]; });+ for (let i = 0; i < boxes.length; i++) for (let j = 0; j < i; j++) {+ assert.ok(!(boxes[i][0] < boxes[j][2] && boxes[i][2] > boxes[j][0] && boxes[i][1] < boxes[j][3] && boxes[i][3] > boxes[j][1]), 'two labels overlap');+ }+});+test('slices, cells, lines and points carry labels; boxes and text marks do not gain a second one', async () => {+ const pie = labelled(await model({ ...base, rows: { kind: 'empty' }, columns: { kind: 'empty' }, mark: 'arc', color: 'product', angle: 'sum', text: 'sum' }, rows));+ assert.deepEqual(pie.map(p => p.text).sort(), ['10', '20', '40']);+ const heat = labelled(await model({ ...base, rows: field('product'), columns: field('segment'), mark: 'rect', color: 'sum', text: 'sum', band: { width: 60 } }, rows));+ assert.equal(heat.length, 3);+ const line = labelled(await model({ ...base, rows: field('sum'), columns: field('product'), mark: 'line', text: 'sum', band: { width: 60 } }, rows));+ assert.deepEqual(line.map(p => p.text), ['10', '20', '40']);+ const box = labelled(await model({ ...base, rows: field('mean'), columns: field('region'), mark: 'boxplot', detail: ['product'], text: 'mean' }, rows));+ assert.equal(box.length, 0);+ const text = fullScene(await model({ ...base, rows: field('product'), columns: field('segment'), mark: 'text', text: 'sum' }, rows)).items.filter(p => p.layer === 'body' && p.kind === 'text');+ assert.equal(text.length, 3);+});diff --git a/packages/worksheet-renderer/tests/core.test.ts b/packages/worksheet-renderer/tests/core.test.tsnew file mode 100644index 00000000..ebc593f5--- /dev/null+++ b/packages/worksheet-renderer/tests/core.test.ts@@ -0,0 +1,201 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { compileWorksheet, executePlan } from '../src/compiler';+import { buildModel } from '../src/model';+import { buildScene } from '../src/scene';+import { sceneToSVG } from '../src/vegaBackend';+import { concat, field, nest, type Computation, type Row, type WorksheetSpec } from '../src/types';+import { fields, fullScene, model as build } from './helpers';++const instances = fields(['region', 'category', 'product', 'year', 'month', 'segment', 'country'],+ { sum: ['value', 'sum'], mean: ['value', 'mean'], count: ['order', 'distinctCount'] });+const base: WorksheetSpec = { kind: 'worksheet', specVersion: 2, instances,+ rows: nest(field('region'), field('category'), field('product')),+ columns: nest(field('year'), concat(field('sum'), field('mean'))), mark: 'bar', color: 'segment' };+const data: Row[] = [];+for (const region of ['East', 'West']) for (const category of ['A', 'B', 'C']) for (const product of ['p', 'q'])+ for (const year of [2024, 2025]) for (const segment of ['a', 'b']) for (let i = 0; i < (product === 'p' ? 1 : 3); i++) {+ data.push({ region, category, product, year, segment, value: product === 'p' ? 100 : 10, order: i, month: i + 1, country: 'US' });+ }+const model = (spec = base, rows = data) => build(spec, rows);++test('three dimensions + two measures: one query, 24 panes, members are layout positions', async () => {+ const m = await model();+ assert.equal(m.plan.tasks.length, 1);+ assert.equal(m.panes.length, 24);+ assert.equal(m.plan.rows[0].facets.length, 2);+ assert.equal(m.plan.rows[0].position?.id, 'product');+ assert.equal(m.rows.groups.length, 6);+ assert.equal(m.rows.leaves.length, 12);+ assert.equal(m.columns.leaves.length, 4);+ assert.equal(m.panes[0].records.length, 4);+ assert.deepEqual(m.plan.tasks[0].measures.map(m => m.aggregate), ['sum', 'mean']);+});+test('six discrete levels compile without dropping or reordering fields', () => {+ const spec = { ...base, rows: nest(...['country', 'region', 'category', 'product', 'year', 'month'].map(field)) };+ const plan = compileWorksheet(spec);+ assert.deepEqual(plan.rows[0].facets.map(f => f.id), ['country', 'region', 'category', 'product', 'year']);+ assert.equal(plan.rows[0].position?.id, 'month');+});+test('six discrete levels become six header levels', async () => {+ const m = await model({ ...base, rows: nest(...['country', 'region', 'category', 'product', 'year', 'month'].map(field)), columns: field('sum') });+ assert.equal(m.rows.levels.length, 6);+ assert.deepEqual(m.rows.captions, ['country', 'region', 'category', 'product', 'year', 'month']);+ assert.equal(m.frame.rowHeaderWidths.length, 6);+});+test('invalid mixed continuous axes fail before executing queries', () => {+ assert.throws(() => compileWorksheet({ ...base, rows: nest(field('sum'), field('region')) }), /Continuous fields/);+ assert.throws(() => compileWorksheet({ ...base, rows: field('missing') }), /Unknown/);+});+test('mean and distinct count are aggregated at the pane grain, not summed from members', async () => {+ const m = await model({ ...base, rows: field('region'), columns: concat(field('mean'), field('count')), color: undefined });+ const east = m.panes[0].records.find(r => r.region === 'East')!;+ assert.equal(east.__ws_mean, 32.5);+ assert.equal(east.__ws_count, 3);+});+test('null coordinates produce no mark and nonnumeric continuous data fails explicitly', async () => {+ const spec: WorksheetSpec = { ...base, instances: { ...instances, raw: { id: 'raw', field: 'value', display: 'continuous', label: 'raw' } },+ rows: field('product'), columns: field('raw'), color: undefined, mark: 'point' };+ const m = await model(spec, [{ product: 'p', value: null }]);+ assert.equal(buildScene(m, { x: 0, y: 0, width: 800, height: 600 }).items.filter(p => p.selection).length, 0);+ await assert.rejects(model(spec, [{ product: 'p', value: 'hello' }]), /not a number: hello/);+ // Infinity and NaN are missing values: no mark, and they do not stretch the axis.+ const holes = await model(spec, [{ product: 'p', value: -Infinity }, { product: 'q', value: NaN }, { product: 'r', value: 4 }]);+ assert.equal(buildScene(holes, { x: 0, y: 0, width: 800, height: 600 }).items.filter(p => p.selection).length, 1);+ assert.deepEqual(holes.columns.leaves[0].scale!.domain, [0, 4]);+});+test('monthly line uses month positions inside year panes', async () => {+ const m = await model({ ...base, rows: nest(field('region'), field('sum')), columns: nest(field('year'), field('month')), mark: 'line' });+ assert.equal(m.panes.length, 4);+ const scene = fullScene(m);+ assert.equal(scene.items.filter(p => p.kind === 'path').length, 8);+ assert.ok(scene.items.filter(p => p.kind === 'path').every(p => p.path!.includes('L')));+});+test('sparse intersections and number/string keys remain distinct', async () => {+ const rows = [{ region: 1, year: 'A', value: 1 }, { region: '1', year: 'B', value: 2 }];+ const m = await model({ ...base, rows: nest(field('region'), field('sum')), columns: nest(field('year'), field('mean')), mark: 'point', color: undefined }, rows);+ assert.equal(m.rows.leaves.length, 2); assert.equal(m.columns.leaves.length, 2); assert.equal(m.panes.length, 2);+});+test('nesting keeps actual paths, crossing keeps empty slots without inventing records', async () => {+ const rows = [{ category: 'Furniture', product: 'Chair', value: 1 }, { category: 'Office', product: 'Paper', value: 2 }];+ const nested = await model({ ...base, rows: nest(field('category'), field('product')), columns: field('sum'), color: undefined }, rows);+ assert.equal(nested.rows.leaves.length, 2);+ const crossed = await model({ ...base, rows: field('category'), columns: field('product'), mark: 'rect', color: undefined }, rows);+ assert.equal(crossed.rows.leaves.length * crossed.columns.leaves.length, 4);+ assert.equal(fullScene(crossed).items.filter(p => p.selection).length, 2);+});+test('stack domain includes cumulative positive and negative endpoints', async () => {+ const m = await model({ ...base, rows: field('product'), columns: field('sum') }, [+ { product: 'p', segment: 'a', value: 10 }, { product: 'p', segment: 'b', value: 20 }, { product: 'p', segment: 'c', value: -15 },+ ]);+ assert.deepEqual(m.panes[0].xDomain, [-15, 30]);+ const overlapped = await model({ ...base, rows: field('product'), columns: field('sum'), stack: false }, [+ { product: 'p', segment: 'a', value: 10 }, { product: 'p', segment: 'b', value: 20 }, { product: 'p', segment: 'c', value: -15 },+ ]);+ assert.deepEqual(overlapped.panes[0].xDomain, [-15, 20]);+});+test('a range is shared by the sheet, by an outer header, or by one column of panes', async () => {+ const rows = [+ { year: 2024, category: 'A', product: 'p', value: 10 },+ { year: 2024, category: 'B', product: 'p', value: 20 },+ { year: 2025, category: 'A', product: 'p', value: 100 },+ ];+ const spec: WorksheetSpec = { ...base, rows: field('product'), columns: nest(field('year'), field('category'), field('sum')), color: undefined };+ const maxima = async (scaleScope?: WorksheetSpec['scaleScope']) => (await model({ ...spec, scaleScope }, rows)).columns.leaves.map(leaf => leaf.scale!.domain[1]);+ assert.deepEqual(await maxima(), [100, 100, 100]);+ assert.deepEqual(await maxima('independent'), [10, 20, 100]);+ assert.deepEqual(await maxima('prefix'), [20, 20, 100]);+});+test('rows and columns take their scale scope separately', async () => {+ // A value axis each way, in two regions and two years. Sales differ by region, profit by year.+ const instances = fields(['region', 'year'], { sales: ['sales', 'sum'], profit: ['profit', 'sum'] });+ const rows = [+ { region: 'E', year: 2024, sales: 10, profit: 1 }, { region: 'E', year: 2025, sales: 8, profit: 50 },+ { region: 'W', year: 2024, sales: 1000, profit: 2 }, { region: 'W', year: 2025, sales: 900, profit: 40 },+ ];+ const spec: WorksheetSpec = { kind: 'worksheet', specVersion: 2, instances, rows: nest(field('region'), field('sales')), columns: nest(field('year'), field('profit')), mark: 'point' };+ const maxima = async (scaleScope?: WorksheetSpec['scaleScope']) => {+ const m = await model({ ...spec, scaleScope }, rows);+ return { y: m.rows.leaves.map(leaf => leaf.scale!.domain[1]), x: m.columns.leaves.map(leaf => leaf.scale!.domain[1]) };+ };+ assert.deepEqual(await maxima(), { y: [1000, 1000], x: [50, 50] });+ // Only the axes along the columns: the sales axes stay comparable between the regions.+ assert.deepEqual(await maxima({ columns: 'independent' }), { y: [1000, 1000], x: [2, 50] });+ assert.deepEqual(await maxima({ columns: 'independent', rows: 'shared' }), { y: [1000, 1000], x: [2, 50] });+ // Only the axes along the rows.+ assert.deepEqual(await maxima({ rows: 'independent' }), { y: [10, 1000], x: [50, 50] });+ assert.deepEqual(await maxima({ rows: 'independent', columns: 'independent' }), { y: [10, 1000], x: [2, 50] });+ assert.deepEqual(await maxima('independent'), { y: [10, 1000], x: [2, 50] });+ // The panes carry the ranges of their axes.+ const m = await model({ ...spec, scaleScope: { columns: 'independent' } }, rows);+ assert.deepEqual(m.panes.map(p => p.yDomain[1]), [1000, 1000, 1000, 1000]);+});+test('viewport culling never changes global domains or exported pane count', async () => {+ const m = await model();+ const domains = JSON.stringify(m.panes.map(p => p.xDomain));+ const scene = buildScene(m, { x: 0, y: 0, width: 420, height: 200 });+ assert.ok(scene.visiblePanes > 0 && scene.visiblePanes < m.panes.length);+ assert.equal(JSON.stringify(m.panes.map(p => p.xDomain)), domains);+ const full = fullScene(m);+ assert.equal(full.visiblePanes, m.panes.length);+ const svg = await sceneToSVG(full);+ assert.ok(svg.startsWith('<svg'));+ assert.ok(svg.includes('SUM') && svg.includes('MEAN'));+});+test('selection carries complete surviving grain and raw field predicates', async () => {+ const m = await model();+ const scene = buildScene(m, { x: 0, y: 0, width: 800, height: 600 });+ const selection = scene.items.find(p => p.selection)!.selection!;+ assert.deepEqual(selection.predicates.map(p => p.field).sort(), ['category', 'product', 'region', 'segment', 'year']);+});+test('filter workflows run before aggregation', async () => {+ const m = await model({ ...base, filters: [{ field: 'region', values: ['West'] }] });+ assert.equal(m.panes.length, 12);+ assert.ok(m.panes.every(p => p.row.path[0].value === 'West'));+});+test('an aggregate the host defines is asked for by name at every grain, one result column per use', async () => {+ // The host knows `ratio` as sum(sales) / sum(cost). The sheet passes the name on and reads what comes back.+ const data = [+ { region: 'E', city: 'a', sales: 10, cost: 1 }, { region: 'E', city: 'a', sales: 20, cost: 9 },+ { region: 'E', city: 'b', sales: 8, cost: 4 }, { region: 'W', city: 'c', sales: 9, cost: 3 },+ ];+ const asked: { groupBy: string[]; measures: { field: string; agg: string; asFieldKey: string }[] }[] = [];+ const host: Computation = async payload => {+ const view = payload.workflow.find(step => step.type === 'view')!;+ const query = view.type === 'view' ? view.query[0] : undefined;+ if (query?.op !== 'aggregate') throw new Error('expected an aggregate query');+ asked.push({ groupBy: query.groupBy, measures: query.measures });+ const groups = new Map<string, Row[]>();+ for (const row of data) { const key = query.groupBy.map(f => row[f]).join('|'); groups.set(key, [...(groups.get(key) ?? []), row]); }+ const sum = (rows: Row[], f: string) => rows.reduce((n, r) => n + r[f], 0);+ return [...groups.values()].map(rows => ({+ ...Object.fromEntries(query.groupBy.map(f => [f, rows[0][f]])),+ ...Object.fromEntries(query.measures.map(m => [m.asFieldKey, m.agg === 'expr' ? sum(rows, 'sales') / sum(rows, 'cost') : sum(rows, m.field)])),+ }));+ };+ const spec: WorksheetSpec = { kind: 'worksheet', specVersion: 2, mark: 'bar',+ instances: { ...fields(['region', 'city'], { x: ['ratio', 'expr'], shade: ['ratio', 'expr'], total: ['sales', 'sum'] }) },+ rows: nest(field('region'), field('city')), columns: concat(field('x'), field('total')), color: 'shade',+ order: { region: { by: 'x', direction: 'descending' } } };+ const plan = compileWorksheet(spec);+ const m = buildModel(plan, await executePlan(plan, host));+ // The marks are at the grain of region and city; the regions are ordered by the ratio of each whole region.+ const marks = asked.find(q => q.groupBy.length === 2)!, order = asked.find(q => q.groupBy.length === 1)!;+ assert.deepEqual(marks.measures.filter(q => q.agg === 'expr'), [{ field: 'ratio', agg: 'expr', asFieldKey: '__ws_x' }, { field: 'ratio', agg: 'expr', asFieldKey: '__ws_shade' }]);+ assert.deepEqual(order.measures, [{ field: 'ratio', agg: 'expr', asFieldKey: '__ws_x' }]);+ const values = Object.fromEntries(m.panes.flatMap(p => p.records).map(r => [r.city, [r.__ws_x, r.__ws_shade, r.__ws_total]]));+ assert.deepEqual(values, { a: [3, 3, 30], b: [2, 2, 8], c: [3, 3, 9] });+ // E is 38 / 14, W is 9 / 3: a ratio of the region's sums, not a sum of its cities' ratios (which would put E first).+ assert.deepEqual(m.rows.levels[0].map(span => span.part.value), ['W', 'E']);+});+test('executor caps concurrency and stops scheduling after cancellation', async () => {+ const plan = compileWorksheet(base);+ plan.tasks = Array.from({ length: 10 }, (_, i) => ({ ...plan.tasks[0], id: String(i) }));+ let running = 0, max = 0, calls = 0;+ const computation: Computation = async () => { calls++; max = Math.max(max, ++running); await new Promise(r => setTimeout(r, 2)); running--; return []; };+ await executePlan(plan, computation);+ assert.equal(max, 4); assert.equal(calls, 10);+ const controller = new AbortController(); controller.abort(); calls = 0;+ await assert.rejects(executePlan(plan, computation, controller.signal));+ assert.equal(calls, 0);+});diff --git a/packages/worksheet-renderer/tests/export.test.ts b/packages/worksheet-renderer/tests/export.test.tsnew file mode 100644index 00000000..1a487d57--- /dev/null+++ b/packages/worksheet-renderer/tests/export.test.ts@@ -0,0 +1,39 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { compileWorksheet, executePlan } from '../src/compiler';+import { resultTables, tableToCSV } from '../src/export';+import { concat, field, nest, type Row, type WorksheetSpec } from '../src/types';+import { fields, reference } from './helpers';++const instances = { ...fields(['region', 'product', 'segment'], { sum: ['value', 'sum'], count: ['value', 'count'] }),+ value: { id: 'value', field: 'value', label: 'Value', display: 'continuous' as const } };+const base = { kind: 'worksheet' as const, specVersion: 2 as const, instances };+const rows: Row[] = [+ { region: 'East', product: 'a, "large"', segment: 's', value: 3 }, { region: 'East', product: 'a, "large"', segment: 't', value: 4 },+ { region: 'West', product: 'b', segment: 's', value: 5 }, { region: 'West', product: 'c', segment: 's', value: null },+];+const tables = async (spec: WorksheetSpec) => { const plan = compileWorksheet(spec); return resultTables(plan, await executePlan(plan, reference(rows))); };++test('the exported table holds the records behind the marks, columns in shelf order', async () => {+ const [table, ...rest] = await tables({ ...base, rows: nest(field('region'), field('product')), columns: concat(field('sum'), field('count')), mark: 'bar', color: 'segment' });+ assert.equal(rest.length, 0);+ // Rows first, then the color dimension, then the measures; not the alphabetical order of the query.+ assert.deepEqual(table.columns, [{ key: 'region', label: 'region' }, { key: 'product', label: 'product' }, { key: 'segment', label: 'segment' }, { key: '__ws_sum', label: 'SUM' }, { key: '__ws_count', label: 'COUNT' }]);+ assert.equal(table.rows.length, 4);+ assert.equal(tableToCSV(table), ['region,product,segment,SUM,COUNT', 'East,"a, ""large""",s,3,1', 'East,"a, ""large""",t,4,1', 'West,b,s,5,1', 'West,c,s,,0'].join('\n'));+});+test('queries that only order members are not exported, and a limit shows in the table', async () => {+ const spec: WorksheetSpec = { ...base, rows: nest(field('region'), field('product')), columns: field('sum'), mark: 'bar', color: 'segment',+ order: { product: { by: 'sum', direction: 'descending' } }, limit: { rows: 2, by: 'sum', direction: 'descending' } };+ assert.equal(compileWorksheet(spec).tasks.length, 2);+ const [table, ...rest] = await tables(spec);+ assert.equal(rest.length, 0);+ assert.deepEqual(table.rows.map(r => r.__ws_sum), [5, 4]);+});+test('a box plot exports its source rows, duplicates included, and bins are written as their bounds', async () => {+ const [table] = await tables({ ...base, rows: field('value'), columns: field('region'), mark: 'boxplot' });+ // The dimension leads although the values are on rows.+ assert.deepEqual(table.columns.map(c => c.label), ['region', 'Value']);+ assert.equal(table.rows.length, 4);+ assert.equal(tableToCSV({ columns: [{ key: 'bin', label: 'bin' }, { key: 'when', label: 'when' }], rows: [{ bin: [0, 23.5], when: new Date(Date.UTC(2024, 0, 2)) }] }), 'bin,when\n0 – 23.5,2024-01-02T00:00:00.000Z');+});diff --git a/packages/worksheet-renderer/tests/formats.test.ts b/packages/worksheet-renderer/tests/formats.test.tsnew file mode 100644index 00000000..a18e84da--- /dev/null+++ b/packages/worksheet-renderer/tests/formats.test.ts@@ -0,0 +1,119 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { compileWorksheet, executePlan } from '../src/compiler';+import { resolveFormats, type Formats } from '../src/formats';+import { buildModel } from '../src/model';+import { buildScene } from '../src/scene';+import { fieldTime } from '../src/time';+import { field, type Row, type WorksheetSpec } from '../src/types';+import { fields, reference } from './helpers';++const instances = { ...fields(['product', 'segment'], { sum: ['value', 'sum'] }),+ when: { id: 'when', field: 'when', label: 'When', display: 'continuous' as const, scale: 'time' as const },+ day: { id: 'day', field: 'when', label: 'Day', display: 'discrete' as const, scale: 'time' as const } };+const base = { kind: 'worksheet' as const, specVersion: 2 as const, instances };+async function scene(spec: WorksheetSpec, rows: Row[], formats?: Formats) {+ const plan = compileWorksheet(spec);+ const m = buildModel(plan, await executePlan(plan, reference(rows)), undefined, formats);+ return { m, items: buildScene(m, { x: 0, y: 0, width: m.width, height: m.height }).items };+}+const sales: Row[] = [{ product: 'a', segment: 's', value: 1234.5 }, { product: 'a', segment: 't', value: 8765.5 }, { product: 'b', segment: 's', value: 2500 }];+const money: Formats = { number: value => 'USD ' + value.toFixed(1), share: value => (value * 100).toFixed(1) + ' pct' };++test('a number format reaches axis ticks, tooltips, labels, cells and legends alike', async () => {+ const bars = await scene({ ...base, rows: field('product'), columns: field('sum'), mark: 'bar', text: 'sum', color: 'sum' }, sales, money);+ const ticks = bars.items.filter(p => p.layer === 'xAxis' && p.fontSize === 10 && !p.fontWeight).map(p => p.text);+ assert.ok(ticks.length > 2 && ticks.every(t => /^USD \d+\.0$/.test(t!)), 'ticks are ' + ticks);+ assert.match(bars.items.find(p => p.selection?.values.product === 'a')!.tooltip!, /SUM: USD 10000\.0/);+ assert.deepEqual(bars.items.filter(p => p.layer === 'body' && p.kind === 'text').map(p => p.text).sort(), ['USD 10000.0', 'USD 2500.0']);+ assert.deepEqual(bars.items.filter(p => p.layer === 'legend' && p.fontSize === 10).map(p => p.text), ['USD 2500.0', 'USD 10000.0']);+ // The axis is as wide as its labels need.+ const upright: WorksheetSpec = { ...base, columns: field('product'), rows: field('sum'), mark: 'bar' };+ const wide = await scene(upright, sales, { number: value => value + ' units of something' });+ const plain = await scene(upright, sales);+ assert.ok(wide.m.frame.yAxisWidth > plain.m.frame.yAxisWidth + 60);+ // Long labels along the bottom get fewer ticks instead of running into each other.+ const long = await scene({ ...base, rows: field('product'), columns: field('sum'), mark: 'bar' }, sales, { number: value => value.toFixed(2) + ' dollars' });+ const bottom = long.items.filter(p => p.layer === 'xAxis' && p.fontSize === 10 && !p.fontWeight).sort((x, y) => x.x - y.x);+ const short = (await scene({ ...base, rows: field('product'), columns: field('sum'), mark: 'bar' }, sales)).items.filter(p => p.layer === 'xAxis' && p.fontSize === 10 && !p.fontWeight);+ assert.ok(bottom.length >= 2 && bottom.length < short.length, bottom.length + ' ticks against ' + short.length);+ const leaf = long.m.columns.leaves[0];+ const spacing = (leaf.scale!.ticks[1] - leaf.scale!.ticks[0]) / (leaf.scale!.domain[1] - leaf.scale!.domain[0]) * (leaf.size - 14);+ assert.ok(bottom.every(p => p.text!.length * 10 * 0.58 + 10 <= spacing), 'every label fits between two ticks');+ // In a slot too narrow for even two labels, the ones that would collide are blank and their ticks stay.+ const narrow = await scene({ ...base, rows: field('product'), columns: field('sum'), mark: 'bar', pane: { width: 80 } }, sales, { number: value => value.toFixed(2) + ' dollars' });+ const squeezed = narrow.m.columns.leaves[0].scale!;+ assert.ok(squeezed.ticks.length >= 2 && squeezed.labels!.filter(Boolean).length === 1, 'labels are ' + JSON.stringify(squeezed.labels));+ const cells = await scene({ ...base, rows: field('product'), columns: field('segment'), mark: 'text', text: 'sum' }, sales, money);+ assert.deepEqual(cells.items.filter(p => p.layer === 'body' && p.kind === 'text').map(p => p.text).sort(), ['USD 1234.5', 'USD 2500.0', 'USD 8765.5']);+});+test('without a number format ticks are abbreviated and values written in full; a tick format alone changes only ticks', async () => {+ const spec: WorksheetSpec = { ...base, rows: field('product'), columns: field('sum'), mark: 'bar' };+ const plain = await scene(spec, sales);+ assert.ok(plain.items.some(p => p.layer === 'xAxis' && p.text === '10K'));+ assert.match(plain.items.find(p => p.selection?.values.product === 'a')!.tooltip!, /SUM: 10,000$/);+ const ticked = await scene(spec, sales, { tick: value => value / 1000 + 'k' });+ assert.ok(ticked.items.some(p => p.layer === 'xAxis' && p.text === '10k'));+ assert.match(ticked.items.find(p => p.selection?.values.product === 'a')!.tooltip!, /SUM: 10,000$/);+});+test('small numbers such as ratios keep the digits that tell them apart, on the axis, in the legend, in labels and in tooltips', async () => {+ const ratios: Row[] = [{ product: 'a', segment: 's', value: 0.0342 }, { product: 'b', segment: 's', value: 0.0291 }, { product: 'c', segment: 's', value: 0.0388 }];+ const bars = await scene({ ...base, rows: field('product'), columns: field('sum'), mark: 'bar', text: 'sum', color: 'sum' }, ratios);+ const ticks = bars.items.filter(p => p.layer === 'xAxis' && p.fontSize === 10 && !p.fontWeight).map(p => p.text!).filter(Boolean);+ // With one decimal every tick of this axis would read 0.+ assert.ok(ticks.length > 2 && new Set(ticks).size === ticks.length, 'ticks are ' + ticks);+ assert.deepEqual(ticks.slice(0, 3), ['0', '0.01', '0.02']);+ assert.deepEqual(bars.items.filter(p => p.layer === 'legend' && p.fontSize === 10).map(p => p.text), ['0.03', '0.04']);+ assert.deepEqual(bars.items.filter(p => p.layer === 'body' && p.kind === 'text').map(p => p.text).sort(), ['0.0291', '0.0342', '0.0388']);+ assert.match(bars.items.find(p => p.selection?.values.product === 'a')!.tooltip!, /SUM: 0\.0342$/);+ // Larger numbers are written as before, and a format of the host's is never second-guessed.+ const format = resolveFormats();+ assert.deepEqual(format.ticks([0, 500, 1000, 1500]), ['0', '500', '1K', '1.5K']);+ assert.deepEqual([format.number(1234.567), format.number(2.7647), format.number(0.5), format.number(0)], ['1,234.57', '2.76', '0.5', '0']);+ assert.deepEqual(resolveFormats({ number: value => value.toFixed(0) }).ticks([0.01, 0.02]), ['0', '0']);+});+test('a share format reaches the axis and tooltips of a normalized stack and the slices of a pie', async () => {+ const stack = await scene({ ...base, rows: field('product'), columns: field('sum'), mark: 'bar', color: 'segment', stack: 'normalize' }, sales, money);+ assert.ok(stack.items.some(p => p.layer === 'xAxis' && p.text === '100.0 pct'));+ assert.match(stack.items.find(p => p.selection?.values.product === 'b')!.tooltip!, /Share: 100\.0 pct$/);+ const pie = await scene({ ...base, rows: { kind: 'empty' }, columns: { kind: 'empty' }, mark: 'arc', color: 'product', angle: 'sum' }, sales, money);+ assert.match(pie.items.find(p => p.kind === 'shape' && p.selection?.values.product === 'b')!.tooltip!, /Share: 20\.0 pct$/);+});+const dated: Row[] = [{ when: '2024-01-15', product: 'a', value: 1 }, { when: '2024-03-15', product: 'a', value: 2 }];+test('a time format reaches tooltips, labels and unit-less members, and leaves the ticks of a time axis alone', async () => {+ const slashed: Formats = { time: ms => new Date(ms).toISOString().slice(0, 10).replace(/-/g, '/') };+ const line = await scene({ ...base, rows: field('sum'), columns: field('when'), mark: 'line' }, dated, slashed);+ assert.match(line.items.find(p => p.selection)!.tooltip!, /When: 2024\/01\/15/);+ assert.ok(line.items.filter(p => p.layer === 'xAxis' && p.fontSize === 10 && !p.fontWeight).every(p => !p.text!.includes('/')));+ const byDay: WorksheetSpec = { ...base, rows: field('day'), columns: field('sum'), mark: 'bar' };+ const headers = await scene(byDay, dated, slashed);+ assert.deepEqual(headers.items.filter(p => p.layer === 'rowHeader' && p.tooltip?.startsWith('Day')).map(p => p.text), ['2024/01/15', '2024/03/15']);+ const standard = await scene(byDay, dated);+ assert.deepEqual(standard.items.filter(p => p.layer === 'rowHeader' && p.tooltip?.startsWith('Day')).map(p => p.text), ['Jan 15, 2024', 'Mar 15, 2024']);+});+test('a locale changes the default numbers and dates, and words can be replaced one by one', async () => {+ const zh: Formats = { locale: 'zh-CN', words: { share: '占比', missing: '(空)', more: count => '另有 ' + count + ' 项' } };+ const line = await scene({ ...base, rows: field('sum'), columns: field('when'), mark: 'line' }, [{ when: '2024-01-15', value: 12000 }, { when: '2024-03-15', value: 34000 }], zh);+ assert.match(line.items.find(p => p.selection)!.tooltip!, /When: 2024年1月15日/);+ assert.ok(line.items.some(p => p.layer === 'xAxis' && /^\d+月/.test(p.text ?? '')), 'month ticks are written in Chinese');+ assert.ok(line.items.some(p => p.layer === 'rowHeader' && /万$/.test(p.text ?? '')), 'ticks are abbreviated the Chinese way');+ const stack = await scene({ ...base, rows: field('product'), columns: field('sum'), mark: 'bar', color: 'segment', stack: 'normalize' }, [...sales, { product: null, segment: 's', value: 1 }], zh);+ assert.match(stack.items.find(p => p.selection?.values.product === 'b')!.tooltip!, /占比: 100%$/);+ assert.ok(stack.items.some(p => p.layer === 'rowHeader' && p.text === '(空)'));+ // A word that was not replaced stays English, and an unknown locale does not fail the sheet.+ assert.equal(resolveFormats(zh).words.median, 'Median');+ assert.equal(resolveFormats({ locale: 'not a locale' }).number(1234.5), '1,234.5');+ // A host's formatter that throws falls back to the standard one.+ assert.equal(resolveFormats({ number: () => { throw new Error('bad'); } }).number(1234.5), '1,234.5');+});+test('bins are written with the number format, and stored times shift by their kind', async () => {+ const binned = await scene({ ...base, rows: field('product'), columns: field('sum'), mark: 'bar' }, [{ product: [0, 2.5], value: 1 }], money);+ assert.ok(binned.items.some(p => p.layer === 'rowHeader' && p.text === 'USD 0.0 – USD 2.5'));+ const f = { id: 't', field: 't', label: 't', display: 'continuous' as const, scale: 'time' as const, timeOffset: { epoch: 1000, date: 2000, dateTime: 3000 } };+ assert.equal(fieldTime(f, 0), 1000);+ assert.equal(fieldTime(f, new Date(0)), 1000);+ assert.equal(fieldTime(f, '2024-01-15') - Date.parse('2024-01-15'), 2000);+ assert.equal(fieldTime(f, '2024') - Date.parse('2024'), 2000);+ assert.equal(fieldTime(f, '2024-01-15T10:00:00') - Date.parse('2024-01-15T10:00:00'), 3000);+ assert.equal(fieldTime({ ...f, timeOffset: 500 }, '2024-01-15') - Date.parse('2024-01-15'), 500);+});diff --git a/packages/worksheet-renderer/tests/geometry.test.ts b/packages/worksheet-renderer/tests/geometry.test.tsnew file mode 100644index 00000000..73e1626a--- /dev/null+++ b/packages/worksheet-renderer/tests/geometry.test.ts@@ -0,0 +1,305 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { compileWorksheet, executePlan } from '../src/compiler';+import { buildModel } from '../src/model';+import { buildScene } from '../src/scene';+import { darkTheme, lightTheme } from '../src/color';+import { metrics } from '../src/layout';+import { concat, field, nest, type Row, type WorksheetSpec } from '../src/types';+import { fields, fullScene, model, near, reference } from './helpers';++const instances = fields(['category', 'sub', 'region', 'year', 'month', 'product', 'segment'], { sum: ['value', 'sum'] });+const base = { kind: 'worksheet' as const, specVersion: 2 as const, instances };++// Requirement A17. Groups of 4, 9 and 4 members, as in the Tableau reference views.+const unequal: Row[] = [];+for (const [category, count] of [['Furniture', 4], ['Office Supplies', 9], ['Technology', 4]] as const)+ for (let i = 0; i < count; i++) unequal.push({ category, sub: `${category[0]}${i}`, value: 10 + i });++test('A17: horizontal bars share one member step and one thickness across groups of 4, 9 and 4', async () => {+ const m = await model({ ...base, rows: nest(field('category'), field('sub')), columns: field('sum'), mark: 'bar' }, unequal);+ const bars = fullScene(m).items.filter(p => p.selection).sort((a, b) => a.y - b.y);+ assert.equal(bars.length, 17);+ assert.ok(bars.every(b => near(b.height!, bars[0].height!)), `thickness differs: ${[...new Set(bars.map(b => b.height!.toFixed(1)))]}`);+ const steps = bars.slice(1).map((b, i) => b.y - bars[i].y);+ assert.ok(steps.every(s => near(s, steps[0])), `step differs: ${[...new Set(steps.map(s => s.toFixed(1)))]}`);+});+test('A17: vertical bars share one member step and one width across groups of 4, 9 and 4', async () => {+ const m = await model({ ...base, columns: nest(field('category'), field('sub')), rows: field('sum'), mark: 'bar' }, unequal);+ const bars = fullScene(m).items.filter(p => p.selection).sort((a, b) => a.x - b.x);+ assert.ok(bars.every(b => near(b.width!, bars[0].width!)), `width differs: ${[...new Set(bars.map(b => b.width!.toFixed(1)))]}`);+ const steps = bars.slice(1).map((b, i) => b.x - bars[i].x);+ assert.ok(steps.every(s => near(s, steps[0])), `step differs: ${[...new Set(steps.map(s => s.toFixed(1)))]}`);+});+test('a member without records in one pane keeps its slot there', async () => {+ const rows: Row[] = [];+ for (const region of ['E', 'W']) for (const year of [2024, 2025]) for (let month = 1; month <= 4; month++) {+ if (region === 'E' && year === 2025 && month === 2) continue;+ rows.push({ region, year, month, value: month });+ }+ const spec: WorksheetSpec = { ...base, rows: nest(field('region'), field('sum')), columns: nest(field('year'), field('month')), mark: 'point' };+ const points = fullScene(await model(spec, rows)).items.filter(p => p.selection);+ const x = (region: string, month: number) => points.find(p => p.selection!.values.region === region && p.selection!.values.year === 2025 && p.selection!.values.month === month)!.x;+ assert.ok(near(x('E', 3), x('W', 3)), `March sits at ${x('E', 3)} for E and ${x('W', 3)} for W`);+ assert.ok(near(x('E', 3) - x('E', 1), x('W', 3) - x('W', 1)));+});+test('an explicit null breaks the line instead of joining its neighbours', async () => {+ const rows: Row[] = [1, 2, 3, 4].map(month => ({ month, value: month === 2 ? null : month }));+ const paths = fullScene(await model({ ...base, rows: field('sum'), columns: field('month'), mark: 'line' }, rows)).items.filter(p => p.kind === 'path');+ const segments = paths.map(p => p.path!).join(' ').split('L').length - 1;+ assert.equal(segments, 1, 'only March to April may be joined');+});+test('bars split by a color dimension stack by default', async () => {+ const rows: Row[] = [{ product: 'p', segment: 'a', value: 10 }, { product: 'p', segment: 'b', value: 20 }];+ const m = await model({ ...base, rows: field('product'), columns: field('sum'), mark: 'bar', color: 'segment' }, rows);+ const [first, second] = fullScene(m).items.filter(p => p.selection).sort((a, b) => a.x - b.x);+ assert.ok(near(second.x, first.x + first.width!), `second bar starts at ${second.x}, first ends at ${first.x + first.width!}`);+ assert.ok(near(second.width!, first.width! * 2, 2));+});++// ---- layout model+const sales = fields(['region', 'category', 'sub', 'year', 'segment'], { sum: ['value', 'sum'], mean: ['value', 'mean'], max: ['value', 'max'] });+const nested: Row[] = [];+for (const region of ['East', 'West']) for (const [category, count] of [['Furniture', 4], ['Office Supplies', 9], ['Technology', 4]] as const)+ for (let i = 0; i < count; i++) for (const year of [2024, 2025]) nested.push({ region, category, sub: `${category[0]}${i}`, year, segment: i % 2 ? 'a' : 'b', value: 1000 * (i + 1) + year });+const twoMeasures: WorksheetSpec = { kind: 'worksheet', specVersion: 2, instances: sales, mark: 'bar',+ rows: nest(field('region'), field('category'), field('sub')), columns: nest(field('year'), concat(field('sum'), field('mean'))) };++test('A17: a group is as tall as its member count times the shared step', async () => {+ const m = await model({ ...base, rows: nest(field('category'), field('sub')), columns: field('sum'), mark: 'bar' }, unequal);+ assert.deepEqual(m.rows.groups.map(g => g.size), [4, 9, 4].map(n => n * metrics.bandHeight));+ assert.equal(new Set(m.rows.leaves.map(leaf => leaf.size)).size, 1);+});+test('value axes are drawn once per column of panes, never inside a pane', async () => {+ const m = await model(twoMeasures, nested);+ assert.equal(m.panes.length, 24);+ const scene = fullScene(m);+ assert.equal(scene.items.filter(p => p.layer === 'body' && p.kind === 'text').length, 0);+ const titles = scene.items.filter(p => p.layer === 'xAxis' && p.fontWeight === 600).map(p => p.text);+ assert.deepEqual(titles, ['SUM', 'MEAN', 'SUM', 'MEAN']);+});+test('ticks are multiples of 1, 2 or 5 times a power of ten', async () => {+ const m = await model(twoMeasures, nested);+ for (const leaf of m.columns.leaves) {+ const { ticks, domain } = leaf.scale!;+ assert.ok(ticks.length >= 2, `too few ticks for ${domain}`);+ const step = ticks[1] - ticks[0];+ const mantissa = Number((step / 10 ** Math.floor(Math.log10(step))).toPrecision(6));+ assert.ok([1, 2, 5].includes(mantissa), `step ${step}`);+ assert.ok(ticks.every(t => near(t / step, Math.round(t / step), 1e-6) && t >= domain[0] && t <= domain[1]));+ }+});+test('headers and axes stay in place while the body scrolls', async () => {+ const m = await model(twoMeasures, nested);+ const window = { width: 520, height: 300 };+ const at = (x: number, y: number) => buildScene(m, { x, y, ...window }).items;+ const layer = (items: ReturnType<typeof at>, name: string) => items.filter(p => p.layer === name);+ // Vertical scrolling leaves column headers and the bottom axis untouched; horizontal scrolling leaves row headers untouched.+ assert.deepEqual(layer(at(40, 0), 'columnHeader'), layer(at(40, 180), 'columnHeader'));+ assert.deepEqual(layer(at(40, 0), 'xAxis'), layer(at(40, 180), 'xAxis'));+ assert.deepEqual(layer(at(0, 180), 'rowHeader'), layer(at(160, 180), 'rowHeader'));+ const scrolled = at(160, 180);+ const { left, top, bottom } = m.frame;+ assert.ok(layer(scrolled, 'columnHeader').every(p => p.y < top));+ assert.ok(layer(scrolled, 'xAxis').every(p => p.y >= window.height - bottom));+ assert.ok(layer(scrolled, 'rowHeader').filter(p => p.kind === 'text').every(p => p.x < left && p.y > top && p.y < window.height - bottom));+ // East starts above the window after scrolling 180 px, yet its label is still shown.+ assert.ok(layer(scrolled, 'rowHeader').some(p => p.text === 'East'));+ assert.ok(layer(scrolled, 'body').filter(p => p.selection).length > 0);+});+test('field names label the header levels', async () => {+ const m = await model(twoMeasures, nested);+ const scene = fullScene(m);+ assert.deepEqual(scene.items.filter(p => p.layer === 'corner' && p.kind === 'text').map(p => p.text), ['region', 'category', 'sub']);+ assert.ok(scene.items.some(p => p.layer === 'columnHeader' && p.text === 'year'));+});+test('mixed concatenated branches get one total order with contiguous headers', async () => {+ const rows: Row[] = [];+ for (const region of ['E', 'W']) for (const category of ['A', 'B']) for (const segment of ['s1', 's2']) rows.push({ region, category, segment, year: 2024, value: 1 });+ const spec: WorksheetSpec = { kind: 'worksheet', specVersion: 2, instances: sales, mark: 'bar', columns: field('year'),+ rows: concat(nest(field('region'), field('category'), field('sum')), nest(field('region'), field('segment'), field('mean')), nest(field('region'), field('category'), field('max'))) };+ const m = await model(spec, rows);+ assert.deepEqual(m.rows.leaves.slice(0, 6).map(leaf => `${leaf.path.map(p => p.value).join('/')} ${leaf.branch.position!.id}`),+ ['E/A sum', 'E/A max', 'E/B sum', 'E/B max', 'E/s1 mean', 'E/s2 mean']);+ assert.equal(m.rows.levels[0].length, 2);+});+test('unstacked bars overlap from the zero line', async () => {+ const rows: Row[] = [{ product: 'p', segment: 'a', value: 10 }, { product: 'p', segment: 'b', value: 20 }];+ const m = await model({ ...base, rows: field('product'), columns: field('sum'), mark: 'bar', color: 'segment', stack: false }, rows);+ const [first, second] = fullScene(m).items.filter(p => p.selection);+ assert.ok(near(first.x, second.x) && near(first.y, second.y) && near(first.height!, second.height!));+});++// ---- selection and fit+test('a selection dims every other mark and survives scrolling and re-sorting', async () => {+ const m = await model(twoMeasures, nested);+ const all = fullScene(m).items.filter(p => p.selection);+ assert.equal(new Set(all.map(p => p.selection!.id)).size, all.length, 'mark ids are unique');+ const target = all.find(p => p.selection!.values.sub === 'O4' && p.selection!.values.region === 'West')!.selection!;+ const selected = new Set([target.id]);+ const scrolled = buildScene(m, { x: 0, y: 500, width: 700, height: 400 }, { selected }).items.filter(p => p.selection);+ const hit = scrolled.filter(p => p.opacity === undefined);+ assert.equal(hit.length, 1);+ assert.deepEqual(hit[0].selection!.values, target.values);+ assert.ok(scrolled.length > 1 && scrolled.every(p => p === hit[0] || p.opacity! < 1));+ const resorted = await model({ ...twoMeasures, sort: 'descending' }, nested);+ const again = buildScene(resorted, { x: 0, y: 0, width: resorted.width, height: resorted.height }, { selected }).items.filter(p => p.selection && p.opacity === undefined);+ assert.deepEqual(again.map(p => p.selection!.values), [target.values]);+ assert.ok(fullScene(m).items.every(p => p.opacity === undefined), 'nothing is dimmed without a selection');+});+test('a line stays opaque when one of its points is selected', async () => {+ const rows: Row[] = [];+ for (const segment of ['a', 'b']) for (let month = 1; month <= 3; month++) rows.push({ segment, month, value: month });+ const m = await model({ ...base, rows: field('sum'), columns: field('month'), mark: 'line', color: 'segment' }, rows);+ const id = fullScene(m).items.find(p => p.selection?.values.segment === 'a')!.selection!.id;+ const paths = buildScene(m, { x: 0, y: 0, width: m.width, height: m.height }, { selected: new Set([id]) }).items.filter(p => p.kind === 'path');+ assert.deepEqual(paths.map(p => p.opacity === undefined), [true, false]);+});+test('fit scales the steps to the target and keeps one step per axis', async () => {+ const plan = compileWorksheet({ ...twoMeasures, fit: 'both' });+ const results = await executePlan(plan, reference(nested));+ for (const target of [{ width: 1300, height: 900 }, { width: 640, height: 260 }]) {+ const m = buildModel(plan, results, target);+ assert.ok(near(m.width, target.width, .5) && near(m.height, target.height, .5), `${m.width}×${m.height} for ${target.width}×${target.height}`);+ assert.ok(m.rows.leaves.every(leaf => near(leaf.size, m.rows.leaves[0].size, 1e-6)));+ assert.ok(m.columns.leaves.every(leaf => near(leaf.size, m.columns.leaves[0].size, 1e-6)));+ const last = m.rows.leaves[m.rows.leaves.length - 1];+ assert.ok(near(last.offset + last.size, m.rows.size, 1e-6));+ }+ const untouched = buildModel(compileWorksheet(twoMeasures), results, { width: 640, height: 260 });+ assert.equal(untouched.rows.leaves[0].size, metrics.bandHeight);+});+test('member labels thin out when the step is smaller than a line of text', async () => {+ const plan = compileWorksheet({ ...twoMeasures, fit: 'height' });+ const m = buildModel(plan, await executePlan(plan, reference(nested)), { width: 900, height: 300 });+ assert.ok(m.rows.leaves[0].size < 12);+ const scene = buildScene(m, { x: 0, y: 0, width: m.width, height: m.height });+ assert.equal(scene.items.filter(p => p.selection).length, 34 * 4, 'every mark is still drawn');+ const x = m.frame.rowHeaderWidths[0] + m.frame.rowHeaderWidths[1];+ const labels = scene.items.filter(p => p.layer === 'rowHeader' && p.kind === 'text' && p.x > x && !p.angle).map(p => p.y).sort((a, b) => a - b);+ assert.ok(labels.length > 0 && labels.length < 34);+ assert.ok(labels.slice(1).every((y, i) => y - labels[i] >= 11 || near(y - labels[i], 11)));+});++// ---- color, text cells, bottom headers, member order+const rgb = (color: string) => color.match(/\d+/g)!.map(Number);+test('a measure on color tints the marks on a continuous scale without splitting them', async () => {+ const spec: WorksheetSpec = { ...base, instances: sales, rows: nest(field('category'), field('sub')), columns: field('sum'), mark: 'bar', color: 'mean' };+ const rowsOf = (region: string) => nested.filter(r => r.region === region && r.year === 2024);+ const m = await model(spec, rowsOf('East'));+ assert.equal(m.plan.tasks.length, 1);+ assert.deepEqual(m.plan.tasks[0].groupBy, ['category', 'sub']);+ assert.equal(m.colorScale!.diverging, false);+ const scene = fullScene(m);+ const bars = scene.items.filter(p => p.selection);+ assert.equal(bars.length, 17, 'one bar per member');+ const byValue = [...bars].sort((a, b) => a.selection!.values.__ws_mean - b.selection!.values.__ws_mean);+ assert.deepEqual(m.colorScale!.domain, [byValue[0].selection!.values.__ws_mean, byValue[16].selection!.values.__ws_mean]);+ const blue = byValue.map(b => rgb(b.fill!)[0]);+ assert.ok(blue.every((v, i) => i === 0 || v <= blue[i - 1]) && blue[0] > blue[16], 'larger values are darker');+ const legend = scene.items.filter(p => p.layer === 'legend');+ assert.ok(legend.filter(p => p.kind === 'rect' && p.height === 10).length >= 40, 'gradient');+ assert.deepEqual(legend.filter(p => p.kind === 'text').map(p => p.text), ['MEAN', '3K', '11K']);+});+test('a color range that crosses zero diverges around it', async () => {+ const rows: Row[] = [-40, -5, 0, 5, 80].map((value, i) => ({ product: `p${i}`, value }));+ const m = await model({ ...base, rows: field('product'), columns: field('sum'), mark: 'bar', color: 'sum' }, rows);+ assert.equal(m.colorScale!.diverging, true);+ const fills = fullScene(m).items.filter(p => p.selection).sort((a, b) => a.selection!.values.__ws_sum - b.selection!.values.__ws_sum).map(p => rgb(p.fill!));+ assert.ok(fills[0][0] > fills[0][2], 'negative is warm');+ assert.ok(fills[4][2] > fills[4][0], 'positive is cool');+ assert.ok(Math.abs(fills[2][0] - fills[2][2]) < 8, 'zero is neutral');+ assert.ok(fills[0][0] - fills[0][2] < fills[4][2] - fills[4][0], '-40 is weaker than +80');+});+test('the legend is part of the sheet and lists each color member once', async () => {+ const m = await model({ ...twoMeasures, color: 'segment' }, nested);+ assert.ok(m.frame.right > 0);+ assert.ok(near(m.width, m.frame.left + m.columns.size + m.frame.right));+ const scene = buildScene(m, { x: 0, y: 200, width: 600, height: 300 });+ const legend = scene.items.filter(p => p.layer === 'legend');+ assert.deepEqual(legend.filter(p => p.kind === 'text').map(p => p.text), ['segment', 'a', 'b']);+ assert.ok(legend.every(p => p.x >= 600 - m.frame.right), 'pinned to the window edge while the body scrolls');+ assert.ok(scene.items.filter(p => p.layer === 'body' && p.selection).every(p => p.x < 600 - m.frame.right));+ assert.equal((await model(twoMeasures, nested)).frame.right, 0);+});+test('text marks fill a crosstab with full numbers', async () => {+ const m = await model({ ...base, instances: sales, rows: nest(field('category'), field('sub')), columns: field('year'), mark: 'text', text: 'sum' }, nested);+ assert.equal(m.columns.leaves[0].size, metrics.textCellWidth);+ const cells = fullScene(m).items.filter(p => p.layer === 'body' && p.kind === 'text');+ assert.equal(cells.length, 17 * 2);+ const first = cells.find(p => p.selection!.values.sub === 'F0' && p.selection!.values.year === 2024)!;+ assert.equal(first.text, '6,048');+ assert.ok(near(first.x, m.frame.left + m.columns.leaves[0].size / 2) && first.align === 'center');+});+test('with a value axis on the rows, the innermost column members are named under the body', async () => {+ const spec: WorksheetSpec = { ...base, columns: nest(field('category'), field('sub')), rows: field('sum'), mark: 'bar' };+ const m = await model(spec, unequal);+ assert.ok(m.frame.bottomHeaderHeight > 0 && m.frame.bottom === m.frame.bottomHeaderHeight);+ const scene = fullScene(m);+ const axisY = m.frame.top + m.rows.size;+ const members = scene.items.filter(p => p.kind === 'text' && /^[FOT]\d$/.test(p.text!));+ assert.equal(members.length, 17);+ assert.ok(members.every(p => p.layer === 'xAxis' && p.y >= axisY));+ assert.ok(scene.items.some(p => p.layer === 'columnHeader' && p.text === 'Furniture'), 'outer levels stay on top');+ const onTop = fullScene(await model({ ...spec, innerColumnHeader: 'top' }, unequal));+ assert.ok(onTop.items.filter(p => /^[FOT]\d$/.test(p.text ?? '')).every(p => p.layer === 'columnHeader'));+ const horizontal = await model({ ...base, rows: nest(field('category'), field('sub')), columns: field('sum'), mark: 'bar' }, unequal);+ assert.equal(horizontal.frame.bottomHeaderHeight, 0);+});+test('member order can be set per field, by direction or by an explicit list', async () => {+ const spec: WorksheetSpec = { ...base, rows: nest(field('category'), field('sub')), columns: field('sum'), mark: 'bar' };+ const names = async (order: WorksheetSpec['order'], sort?: WorksheetSpec['sort']) => (await model({ ...spec, order, sort }, unequal)).rows.leaves.map(leaf => leaf.path[1].value);+ assert.deepEqual((await names({ category: 'descending' })).slice(0, 5), ['T0', 'T1', 'T2', 'T3', 'O0']);+ assert.deepEqual((await names({ sub: ['O7', 'O2'] })).slice(4, 8), ['O7', 'O2', 'O0', 'O1']);+ assert.deepEqual((await names({ sub: 'ascending' }, 'descending')).slice(0, 2), ['T0', 'T1'], 'a field without its own order follows sort');+});++// ---- narrow windows and adapter-facing options+test('row headers stay inside their budget and keep every level', async () => {+ const plan = compileWorksheet(twoMeasures);+ const results = await executePlan(plan, reference(nested));+ const free = buildModel(plan, results);+ const tight = buildModel(plan, results, { width: 0, height: 0, headerWidth: 120 });+ const total = (m: typeof free) => m.frame.rowHeaderWidths.reduce((a, b) => a + b, 0);+ assert.ok(total(free) > 120);+ assert.ok(total(tight) <= 120);+ assert.equal(tight.frame.rowHeaderWidths.length, 3);+ const scene = buildScene(tight, { x: 0, y: 0, width: 260, height: 300 });+ assert.ok(scene.visiblePanes > 0, 'marks are reachable in a 260 px window');+ assert.deepEqual(scene.items.filter(p => p.layer === 'corner' && p.kind === 'text').map(p => p.tooltip), ['region', 'category', 'sub']);+});+test('a field can opt out of the zero baseline, and a continuous field can color without aggregation', async () => {+ const instances = { ...sales, raw: { id: 'raw', field: 'value', label: 'value', display: 'continuous' as const, zero: false } };+ const rows: Row[] = [{ sub: 'a', value: 1000 }, { sub: 'b', value: 1010 }];+ const m = await model({ kind: 'worksheet', specVersion: 2, instances, rows: field('raw'), columns: field('sub'), mark: 'point', color: 'raw' }, rows);+ assert.deepEqual(m.rows.leaves[0].scale!.domain, [1000, 1010]);+ assert.deepEqual(m.colorScale!.domain, [1000, 1010]);+ assert.deepEqual(m.plan.tasks[0].groupBy, ['sub', 'value']);+ assert.equal(fullScene(m).items.filter(p => p.selection).length, 2);+});++// ---- theme and narrow windows+test('a dark theme recolors surfaces, text and rules, and leaves the marks alone', async () => {+ const m = await model({ ...twoMeasures, color: 'segment' }, nested);+ const window = { x: 0, y: 0, width: 900, height: 500 };+ const light = buildScene(m, window);+ const dark = buildScene(m, window, { theme: darkTheme });+ assert.equal(light.background, lightTheme.paper);+ assert.equal(dark.background, darkTheme.paper);+ assert.equal(dark.items.length, light.items.length);+ const lightOnly = new Set(Object.values(lightTheme));+ const chrome = dark.items.filter(p => !p.selection && !(p.layer === 'legend' && p.kind === 'rect' && p.width === 10));+ assert.ok(chrome.every(p => !lightOnly.has(p.fill ?? '')), 'no light surface or text color is left');+ assert.deepEqual(dark.items.filter(p => p.selection).map(p => p.fill), light.items.filter(p => p.selection).map(p => p.fill));+});+test('a window too narrow for the legend strip drops it and keeps the marks reachable', async () => {+ const plan = compileWorksheet({ ...twoMeasures, color: 'segment' });+ const m = buildModel(plan, await executePlan(plan, reference(nested)), { width: 0, height: 0, headerWidth: 96 });+ const narrow = buildScene(m, { x: 0, y: 0, width: 230, height: 320 });+ assert.equal(narrow.legend, 'omitted');+ assert.equal(narrow.items.filter(p => p.layer === 'legend').length, 0);+ assert.ok(narrow.visiblePanes > 0 && narrow.items.some(p => p.selection));+ const wide = buildScene(m, { x: 0, y: 0, width: 900, height: 320 });+ assert.equal(wide.legend, 'side');+ assert.equal((await model(twoMeasures, nested).then(plain => buildScene(plain, { x: 0, y: 0, width: 900, height: 320 }))).legend, 'none');+});diff --git a/packages/worksheet-renderer/tests/helpers.ts b/packages/worksheet-renderer/tests/helpers.tsnew file mode 100644index 00000000..bf625faa--- /dev/null+++ b/packages/worksheet-renderer/tests/helpers.ts@@ -0,0 +1,58 @@+import { compileWorksheet, executePlan } from '../src/compiler';+import { buildModel } from '../src/model';+import { buildScene } from '../src/scene';+import { valueKey } from '../src/keys';+import type { Aggregate, Computation, Row, WorksheetSpec } from '../src/types';++export function fields(dimensions: string[], measures: Record<string, [string, Aggregate]> = {}): WorksheetSpec['instances'] {+ return Object.fromEntries([+ ...dimensions.map(id => ({ id, field: id, label: id, display: 'discrete' as const })),+ ...Object.entries(measures).map(([id, [field, aggregate]]) => ({ id, field, label: id.toUpperCase(), display: 'continuous' as const, aggregate })),+ ].map(f => [f.id, f]));+}++// Independent reference evaluator. Tests validate generated workflows against raw rows,+// including non-additive aggregates and typed grouping keys. A group without any+// non-null input yields null, as SQL aggregates do.+export function reference(data: Row[]): Computation {+ return async payload => {+ let rows = data;+ for (const step of payload.workflow) {+ if (step.type === 'filter') rows = rows.filter(r => step.filters.every(f => f.rule.value.some(v => valueKey(v) === valueKey(r[f.fid]))));+ else if (step.type === 'sort') {+ // As the host's own sort step: by the listed result fields in turn, nulls as the smallest value.+ const sign = step.sort === 'descending' ? -1 : 1;+ rows = [...rows].sort((x, y) => { for (const f of step.by) { const d = (x[f] ?? -Infinity) - (y[f] ?? -Infinity); if (d) return d * sign; } return 0; });+ } else if (step.query[0].op === 'raw') {+ const { fields } = step.query[0];+ rows = rows.map(row => Object.fromEntries(fields.map(f => [f, row[f]])));+ } else {+ const q = step.query[0];+ const groups = new Map<string, Row[]>();+ for (const row of rows) {+ const key = JSON.stringify(q.groupBy.map(f => valueKey(row[f])));+ const bucket = groups.get(key) ?? []; bucket.push(row); groups.set(key, bucket);+ }+ rows = [...groups.values()].map(bucket => {+ const output = Object.fromEntries(q.groupBy.map(f => [f, bucket[0][f]]));+ for (const m of q.measures) {+ const values = bucket.map(r => r[m.field]).filter(v => v != null);+ const total = values.reduce((n, v) => n + Number(v), 0);+ output[m.asFieldKey] = m.agg === 'count' ? values.length : m.agg === 'distinctCount' ? new Set(values.map(valueKey)).size+ : !values.length ? null : m.agg === 'sum' ? total : m.agg === 'mean' ? total / values.length : m.agg === 'min' ? Math.min(...values) : Math.max(...values);+ }+ return output;+ });+ }+ }+ return payload.limit ? rows.slice(0, payload.limit) : rows;+ };+}++export async function model(spec: WorksheetSpec, rows: Row[]) {+ const plan = compileWorksheet(spec);+ return buildModel(plan, await executePlan(plan, reference(rows)));+}+export type Model = Awaited<ReturnType<typeof model>>;+export const fullScene = (m: Model) => buildScene(m, { x: 0, y: 0, width: m.width, height: m.height });+export const near = (a: number, b: number, tolerance = 1) => Math.abs(a - b) <= tolerance;diff --git a/packages/worksheet-renderer/tests/marks.test.ts b/packages/worksheet-renderer/tests/marks.test.tsnew file mode 100644index 00000000..abf48ab9--- /dev/null+++ b/packages/worksheet-renderer/tests/marks.test.ts@@ -0,0 +1,178 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { compileWorksheet } from '../src/compiler';+import { metrics } from '../src/layout';+import { field, nest, type Row, type WorksheetSpec } from '../src/types';+import { fields, fullScene, model, near } from './helpers';++const instances = {+ ...fields(['region', 'category', 'segment', 'name'], { sum: ['value', 'sum'] }),+ value: { id: 'value', field: 'value', label: 'Value', display: 'continuous' as const, zero: false },+};+const base = { kind: 'worksheet' as const, specVersion: 2 as const, instances };++// ---- point, circle, tick+const three: Row[] = [{ category: 'a', value: 1 }, { category: 'b', value: 2 }, { category: 'c', value: 3 }];+test('point is a hollow circle and circle a filled one', async () => {+ const marks = async (mark: WorksheetSpec['mark']) => fullScene(await model({ ...base, rows: field('sum'), columns: field('category'), mark }, three)).items.filter(p => p.selection);+ const points = await marks('point'), circles = await marks('circle');+ assert.equal(points.length, 3);+ assert.ok(points.every(p => p.kind === 'symbol' && p.fill === 'transparent' && p.stroke && p.strokeWidth), 'points are outlines');+ assert.ok(circles.every(p => p.kind === 'symbol' && p.fill !== 'transparent' && !p.stroke), 'circles are filled');+ assert.deepEqual(points.map(p => [p.x, p.y]), circles.map(p => [p.x, p.y]));+});+test('a tick is a thin line across its value axis', async () => {+ const upright = fullScene(await model({ ...base, rows: field('category'), columns: field('sum'), mark: 'tick' }, three)).items.filter(p => p.selection);+ assert.ok(upright.every(p => p.kind === 'rect' && p.width === 2 && near(p.height!, metrics.bandHeight * metrics.barFill)), 'ticks on a horizontal axis stand upright');+ const flat = fullScene(await model({ ...base, rows: field('sum'), columns: field('category'), mark: 'tick' }, three)).items.filter(p => p.selection);+ assert.ok(flat.every(p => p.kind === 'rect' && p.height === 2 && near(p.width!, metrics.bandWidth * metrics.barFill)), 'ticks on a vertical axis lie flat');+ assert.equal(new Set(flat.map(p => p.y)).size, 3, 'each tick sits at its own value');+});++// ---- arc+const shares: Row[] = [];+for (const region of ['East', 'West']) for (const category of ['x', 'y']) for (const [segment, value] of [['a', 1], ['b', 3]] as const) {+ if (region === 'West' && category === 'y' && segment === 'a') continue;+ shares.push({ region, category, segment, value: value * (region === 'East' ? 1 : 10) });+}+test('arc draws one pie per cell and a slice is its share of that cell', async () => {+ const m = await model({ ...base, rows: field('region'), columns: field('category'), mark: 'arc', color: 'segment', angle: 'sum' }, shares);+ assert.deepEqual([m.rows.leaves.length, m.columns.leaves.length], [2, 2]);+ assert.ok([...m.rows.leaves, ...m.columns.leaves].every(leaf => leaf.size === metrics.pieSize), 'every cell is one pie wide and high');+ const slices = fullScene(m).items.filter(p => p.kind === 'shape');+ assert.equal(slices.length, 7);+ const share = (region: string, category: string, segment: string) => {+ const mark = m.panes.flatMap(p => p.marks).find(k => k.record.region === region && k.record.category === category && k.record.segment === segment)!;+ return mark.end - mark.start;+ };+ // The same split in every cell although West is ten times larger: a pie shows shares, not sizes.+ assert.ok(near(share('East', 'x', 'a'), .25, 1e-9) && near(share('West', 'x', 'b'), .75, 1e-9));+ assert.ok(near(share('West', 'y', 'b'), 1, 1e-9), 'a lone slice is the whole disc');+ const centers = new Set(slices.map(p => `${p.x},${p.y}`));+ assert.equal(centers.size, 4, 'slices of one cell share a center');+ assert.ok(slices.every(p => p.path!.endsWith('Z') && p.selection && /Share: \d/.test(p.tooltip!)));+});+test('arc without an angle field gives every slice the same share, and takes no measure on an axis', async () => {+ const m = await model({ ...base, rows: { kind: 'empty' }, columns: { kind: 'empty' }, mark: 'arc', color: 'segment' }, shares);+ assert.deepEqual(m.panes[0].marks.map(k => k.end - k.start), [.5, .5]);+ assert.throws(() => compileWorksheet({ ...base, rows: field('sum'), columns: field('category'), mark: 'arc' }), /dimensions on rows and columns/);+});++// ---- box plot+const sample = [1, 2, 3, 4, 5, 6, 7, 8, 9, 40];+const records: Row[] = [];+for (const region of ['East', 'West']) for (const category of ['x', 'y', 'z']) for (const segment of ['a', 'b']) {+ if (region === 'West' && category === 'z') continue;+ sample.forEach((value, i) => records.push({ region, category, segment, name: `n${i}`, value: value + (segment === 'b' ? 100 : 0) }));+}+const boxes: WorksheetSpec = { ...base, rows: field('value'), columns: nest(field('region'), field('category')), mark: 'boxplot' };+test('a box summarises every record of its member: quartiles, whiskers and outliers', async () => {+ const rows = sample.map(value => ({ category: 'x', value }));+ const m = await model({ ...base, rows: field('value'), columns: field('category'), mark: 'boxplot' }, [...rows, { category: 'x', value: 5 }, { category: 'x', value: 5 }]);+ const [box, ...outliers] = m.panes[0].marks;+ // 1..9, 40 and two more fives: equal rows count, they are not merged by the query.+ assert.equal(box.box!.count, 12);+ assert.deepEqual([box.box!.q1, box.box!.median, box.box!.q3], [3.75, 5, 7.25]);+ assert.deepEqual([box.box!.low, box.box!.high], [1, 9], 'whiskers end at the furthest records within 1.5 box lengths');+ assert.deepEqual(outliers.map(k => [k.outlier, k.start]), [[true, 40]]);+ const scene = fullScene(m);+ const leaf = m.rows.leaves[0];+ const y = (value: number) => m.frame.top + leaf.size - metrics.scalePadStart - (value - leaf.scale!.domain[0]) / (leaf.scale!.domain[1] - leaf.scale!.domain[0]) * (leaf.size - metrics.scalePadStart - metrics.scalePadEnd);+ const body = scene.items.filter(p => p.kind === 'rect' && p.selection).sort((a, b) => b.width! * b.height! - a.width! * a.height!)[0];+ assert.ok(near(body.y, y(7.25)) && near(body.y + body.height!, y(3.75)), 'the box spans the quartiles');+ assert.deepEqual(leaf.scale!.domain, [1, 40], 'the axis covers whiskers and outliers and does not start from zero');+ assert.equal(scene.items.filter(p => p.kind === 'symbol').length, 1);+ assert.match(body.tooltip!, /Median: 5\n/);+ assert.deepEqual(body.selection!.predicates, [{ field: 'category', value: 'x' }]);+});+test('boxes nest under every header level and keep one member step', async () => {+ const m = await model(boxes, records);+ assert.equal(m.columns.levels.length, 2);+ assert.deepEqual(m.columns.groups.map(g => g.size), [3, 2].map(n => n * metrics.bandWidth));+ assert.equal(m.panes.flatMap(p => p.marks).filter(k => k.box).length, 5);+ assert.equal(m.plan.tasks[0].payload.workflow.at(-1)!.type, 'view');+ assert.deepEqual((m.plan.tasks[0].payload.workflow.at(-1) as any).query[0], { op: 'raw', fields: ['category', 'region', 'value'] });+});+test('boxes of different colors stand side by side in the same order in every pane', async () => {+ const m = await model({ ...boxes, color: 'segment' }, records);+ const bodies = fullScene(m).items.filter(p => p.kind === 'rect' && p.selection && p.height! > 4 && p.width! > 4);+ assert.equal(bodies.length, 10);+ const leaf = (p: typeof bodies[number]) => m.columns.leaves.find(l => p.x >= m.frame.left + l.offset && p.x < m.frame.left + l.offset + l.size)!;+ for (const segment of ['a', 'b']) {+ const offsets = bodies.filter(p => p.selection!.values.segment === segment).map(p => p.x - m.frame.left - leaf(p).offset);+ assert.ok(offsets.every(o => near(o, offsets[0], .01)), `segment ${segment} sits at ${[...new Set(offsets)]}`);+ }+ assert.ok(bodies.every(p => near(p.width!, bodies[0].width!, .01)));+ // Coloring by the field that already heads the members does not halve the boxes.+ const same = fullScene(await model({ ...boxes, color: 'category' }, records)).items.filter(p => p.kind === 'rect' && p.selection && p.height! > 4 && p.width! > 4);+ assert.ok(same.every(p => near(p.width!, metrics.bandWidth * metrics.barFill, .01)));+});+test('detail sets the grain of an aggregated box plot without splitting the boxes', async () => {+ const m = await model({ ...base, rows: field('sum'), columns: field('category'), mark: 'boxplot', detail: ['name'] }, records.filter(r => r.region === 'East'));+ const marks = m.panes.flatMap(p => p.marks).filter(k => k.box);+ assert.equal(marks.length, 3);+ // One record per name: the sum over both segments.+ assert.equal(marks[0].box!.count, 10);+ assert.equal(marks[0].box!.median, 111);+});+test('a box plot needs exactly one measure axis and a dimension on color', () => {+ assert.throws(() => compileWorksheet({ ...base, rows: field('value'), columns: field('sum'), mark: 'boxplot' }), /exactly one measure axis/);+ assert.throws(() => compileWorksheet({ ...base, rows: field('category'), columns: field('region'), mark: 'boxplot' }), /exactly one measure axis/);+ assert.throws(() => compileWorksheet({ ...base, rows: field('value'), columns: field('category'), mark: 'boxplot', color: 'sum' }), /dimension on color/);+});++// ---- drawing backend+test('the backend paints slices as filled outlines and points as strokes', async () => {+ const { sceneToSVG } = await import('../src/vegaBackend');+ const pie = await sceneToSVG(fullScene(await model({ ...base, rows: field('region'), columns: field('category'), mark: 'arc', color: 'segment', angle: 'sum' }, shares)));+ assert.equal(pie.match(/<path[^>]*d="M0,0L[^"]*Z"[^>]*fill="#/g)?.length, 6, 'six slices that are not a whole disc');+ const points = await sceneToSVG(fullScene(await model({ ...base, rows: field('sum'), columns: field('category'), mark: 'point' }, three)));+ // An outline carries a stroke and no fill of its own.+ const outlines = points.match(/<path[^>]*stroke="#4263eb" stroke-width="1.5"[^>]*>/g) ?? [];+ assert.equal(outlines.length, 3);+ assert.ok(outlines.every(path => !/fill="#/.test(path)));+});+test('a box with a single record is still visible', async () => {+ const m = await model({ ...base, rows: field('value'), columns: field('category'), mark: 'boxplot' }, [{ category: 'x', value: 3 }, { category: 'y', value: 9 }]);+ const scene = fullScene(m);+ const drawn = scene.items.filter(p => p.kind === 'rect' && p.selection);+ assert.ok(drawn.length >= 2 && drawn.every(p => p.fill !== scene.background), 'nothing is painted in the surface color');+ assert.ok(drawn.some(p => p.height === 2 && near(p.width!, metrics.bandWidth * metrics.barFill, .01)));+});++// ---- theme colors+test('marks, legend and color scales take their colors from the theme', async () => {+ const { lightTheme } = await import('../src/color');+ const { buildScene } = await import('../src/scene');+ const theme = { ...lightTheme, mark: '#111111', category: ['#aa0000', '#00aa00'], ramp: ['#000000', '#808080', '#ffffff'], diverging: ['#ff0000', '#000000', '#0000ff'], heatmap: ['#000000', '#00ff00'] };+ const scene = (m: Awaited<ReturnType<typeof model>>) => buildScene(m, { x: 0, y: 0, width: m.width, height: m.height }, { theme });+ const marks = (m: Awaited<ReturnType<typeof model>>) => scene(m).items.filter(p => p.selection);+ const rows: Row[] = [{ category: 'a', segment: 's', value: 0 }, { category: 'b', segment: 't', value: 50 }, { category: 'c', segment: 'u', value: 100 }];+ const bars = { ...base, rows: field('category'), columns: field('sum'), mark: 'bar' as const };+ // No color field: the theme's mark color.+ assert.deepEqual([...new Set(marks(await model(bars, rows)).map(p => p.fill))], ['#111111']);+ // Members take the category colors in order and start over when they run out; the legend shows the same.+ const byMember = await model({ ...bars, color: 'segment' }, rows);+ assert.deepEqual(marks(byMember).sort((a, b) => a.y - b.y).map(p => p.fill), ['#aa0000', '#00aa00', '#aa0000']);+ assert.deepEqual(scene(byMember).items.filter(p => p.layer === 'legend' && p.width === 10).map(p => p.fill), ['#aa0000', '#00aa00', '#aa0000']);+ // A one-sided range runs along the ramp through every stop.+ const byValue = marks(await model({ ...bars, color: 'sum' }, rows)).sort((a, b) => a.y - b.y).map(p => p.fill);+ assert.deepEqual(byValue, ['rgb(0,0,0)', 'rgb(128,128,128)', 'rgb(255,255,255)']);+ // A range across zero runs along the diverging stops with zero on the middle one.+ const crossing = marks(await model({ ...bars, color: 'sum' }, [{ category: 'a', value: -100 }, { category: 'b', value: 0 }, { category: 'c', value: 100 }])).sort((a, b) => a.y - b.y).map(p => p.fill);+ assert.deepEqual(crossing, ['rgb(255,0,0)', 'rgb(0,0,0)', 'rgb(0,0,255)']);+ // Heat map cells use the heat map stops.+ const cells = marks(await model({ ...base, rows: field('category'), columns: field('segment'), mark: 'rect', color: 'sum' }, rows)).map(p => p.fill);+ assert.ok(cells.includes('rgb(0,255,0)') && !cells.includes('rgb(255,255,255)'), `cells are ${cells}`);+});++// ---- binned fields+test('a bin is a member: ordered by its lower bound and labelled with its range', async () => {+ const rows: Row[] = [{ category: [20, 30], value: 2 }, { category: [0, 10], value: 1 }, { category: [10, 20.5], value: 3 }, { category: [0, 10], value: 4 }];+ const m = await model({ ...base, rows: field('category'), columns: field('sum'), mark: 'bar' }, rows);+ assert.equal(m.rows.leaves.length, 3, 'equal bins are one member');+ const labels = fullScene(m).items.filter(p => p.layer === 'rowHeader' && p.kind === 'text' && p.tooltip?.startsWith('category')).map(p => p.text);+ assert.deepEqual(labels, ['0 – 10', '10 – 20.5', '20 – 30']);+ const first = fullScene(m).items.filter(p => p.selection).sort((a, b) => a.y - b.y)[0];+ assert.equal(first.selection!.values.__ws_sum, 5);+});diff --git a/packages/worksheet-renderer/tests/order.test.ts b/packages/worksheet-renderer/tests/order.test.tsnew file mode 100644index 00000000..31fc53ee--- /dev/null+++ b/packages/worksheet-renderer/tests/order.test.ts@@ -0,0 +1,75 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { compileWorksheet } from '../src/compiler';+import { concat, field, nest, type Row, type WorksheetSpec } from '../src/types';+import { fields, fullScene, model } from './helpers';++const instances = fields(['category', 'sub', 'year', 'segment'], { sum: ['value', 'sum'], mean: ['value', 'mean'], count: ['value', 'count'] });+const base = { kind: 'worksheet' as const, specVersion: 2 as const, instances };+// Two categories whose members rank differently: under F the order by total is b, c, a; under T it is a, c, b.+const totals: Record<string, Record<string, number>> = { F: { a: 10, b: 30, c: 20 }, T: { a: 90, b: 5, c: 40 } };+const rows: Row[] = [];+for (const [category, members] of Object.entries(totals)) for (const [sub, total] of Object.entries(members)) {+ // Split over two years and two segments, so no single record or pane carries the total.+ for (const year of [2024, 2025]) for (const segment of ['x', 'y']) rows.push({ category, sub, year, segment, value: total / 4 });+}+const members = (m: Awaited<ReturnType<typeof model>>, axis: 'rows' | 'columns' = 'rows') => m[axis].groups.map(g => m[axis].leaves.slice(g.start, g.end).map(leaf => leaf.path[leaf.path.length - 1].value));++test('members are ordered by a measure inside each parent, over everything on the other axis', async () => {+ const spec: WorksheetSpec = { ...base, rows: nest(field('category'), field('sub')), columns: nest(field('year'), field('sum')), mark: 'bar', color: 'segment',+ order: { sub: { by: 'sum', direction: 'descending' } } };+ const m = await model(spec, rows);+ assert.deepEqual(members(m), [['b', 'c', 'a'], ['a', 'c', 'b']]);+ assert.deepEqual(members(await model({ ...spec, order: { sub: { by: 'sum' } } }, rows)), [['a', 'c', 'b'], ['b', 'c', 'a']], 'ascending by default');+ // The totals come from a query of their own grain; the marks keep theirs.+ assert.deepEqual(m.plan.tasks.map(t => t.groupBy), [['category', 'segment', 'sub', 'year'], ['category', 'sub']]);+ assert.equal(m.panes.flatMap(p => p.marks).length, 24);+ // Bars follow their members: the first bar of the first pane is b's.+ const first = fullScene(m).items.filter(p => p.selection).sort((a, b) => a.y - b.y || a.x - b.x)[0];+ assert.equal(first.selection!.values.sub, 'b');+});+test('a sheet whose marks already have the member grain needs no second query', async () => {+ const m = await model({ ...base, rows: field('sub'), columns: field('sum'), mark: 'bar', order: { sub: { by: 'sum', direction: 'descending' } } }, rows);+ assert.equal(m.plan.tasks.length, 1);+ // Across both categories: a 100, c 60, b 35.+ assert.deepEqual(members(m), [['a', 'c', 'b']]);+});+test('the ordering measure is aggregated at the member grain, not derived from finer records', async () => {+ // p has one large record in 2024 and many small ones in 2025: the mean of its yearly means is 51, its true mean 11.+ const data: Row[] = [{ sub: 'p', year: 2024, value: 100 }, ...Array.from({ length: 9 }, () => ({ sub: 'p', year: 2025, value: 2 })), { sub: 'q', year: 2024, value: 20 }, { sub: 'q', year: 2025, value: 20 }];+ const m = await model({ ...base, rows: field('sub'), columns: nest(field('year'), field('sum')), mark: 'bar', order: { sub: { by: 'mean', direction: 'descending' } } }, data);+ assert.deepEqual(members(m), [['q', 'p']]);+ // The measure need not be drawn anywhere.+ assert.deepEqual(m.plan.tasks.map(t => t.measures.map(f => f.id)), [['sum'], ['mean']]);+});+test('with several measures side by side the named one decides, and outer headers can be ordered too', async () => {+ const data: Row[] = [{ category: 'F', sub: 'a', value: 50 }, { category: 'T', sub: 'a', value: 5 }, { category: 'T', sub: 'b', value: 6 }, { category: 'T', sub: 'c', value: 7 }];+ const spec: WorksheetSpec = { ...base, rows: nest(field('category'), field('sub')), columns: concat(field('sum'), field('count')), mark: 'bar' };+ const order = async (by: string) => (await model({ ...spec, order: { category: { by, direction: 'descending' } } }, data)).rows.groups.map(g => g.path[0].value);+ assert.deepEqual(await order('sum'), ['F', 'T']);+ assert.deepEqual(await order('count'), ['T', 'F']);+});+test('members on columns are ordered the same way, and equal or missing values have a fixed place', async () => {+ const data: Row[] = [{ sub: 'd', value: null }, { sub: 'c', value: 5 }, { sub: 'b', value: 9 }, { sub: 'a', value: 5 }];+ const spec: WorksheetSpec = { ...base, columns: field('sub'), rows: field('sum'), mark: 'bar' };+ assert.deepEqual(members(await model({ ...spec, order: { sub: { by: 'sum', direction: 'descending' } } }, data), 'columns'), [['b', 'a', 'c', 'd']]);+ assert.deepEqual(members(await model({ ...spec, order: { sub: { by: 'sum', direction: 'ascending' } } }, data), 'columns'), [['a', 'c', 'b', 'd']], 'the member without a value stays last');+});+test('a row limit keeps the first records; with a field to order by it is a top N', async () => {+ const data: Row[] = [{ sub: 'a', value: 1 }, { sub: 'b', value: 9 }, { sub: 'c', value: 5 }, { sub: 'd', value: 7 }];+ const spec: WorksheetSpec = { ...base, rows: field('sub'), columns: field('sum'), mark: 'bar' };+ const top = await model({ ...spec, limit: { rows: 2, by: 'sum', direction: 'descending' }, order: { sub: { by: 'sum', direction: 'descending' } } }, data);+ assert.deepEqual(members(top), [['b', 'd']]);+ assert.deepEqual(top.plan.tasks[0].payload.workflow.at(-1), { type: 'sort', by: ['__ws_sum'], sort: 'descending' });+ assert.equal(top.plan.tasks[0].payload.limit, 2);+ // The values that order members are never cut by the limit, so they get a query of their own.+ assert.deepEqual(top.plan.tasks.map(t => [t.id.startsWith('order:'), t.payload.limit]), [[false, 2], [true, undefined]]);+ assert.deepEqual(members(await model({ ...spec, limit: { rows: 3 } }, data)), [['a', 'b', 'c']], 'without a field the records keep their arrival order');+ assert.equal((await model({ ...spec, limit: { rows: 0 } }, data)).rows.leaves.length, 4, 'zero means no limit');+});+test('only a dimension can be ordered, and only by an aggregated measure', () => {+ const spec: WorksheetSpec = { ...base, rows: field('sub'), columns: field('sum'), mark: 'bar' };+ assert.throws(() => compileWorksheet({ ...spec, order: { sub: { by: 'year' } } }), /aggregated measure/);+ assert.throws(() => compileWorksheet({ ...spec, order: { sum: { by: 'sum' } } }), /members of a dimension/);+ assert.throws(() => compileWorksheet({ ...spec, order: { sub: { by: 'nope' } } }), /Unknown field instance/);+});diff --git a/packages/worksheet-renderer/tests/run.mjs b/packages/worksheet-renderer/tests/run.mjsnew file mode 100644index 00000000..149b97f3--- /dev/null+++ b/packages/worksheet-renderer/tests/run.mjs@@ -0,0 +1,14 @@+import { build } from 'esbuild';+import { mkdtemp, readdir, rm } from 'node:fs/promises';+import { spawnSync } from 'node:child_process';+import { fileURLToPath } from 'node:url';+import path from 'node:path';++const root = fileURLToPath(new URL('..', import.meta.url));+const temp = await mkdtemp(path.join(root, '.test-'));+try {+ const names = (await readdir(path.join(root, 'tests'))).filter(name => name.endsWith('.test.ts'));+ await build({ entryPoints: names.map(name => path.join(root, 'tests', name)), outdir: temp, outExtension: { '.js': '.cjs' }, bundle: true, platform: 'node', format: 'cjs', packages: 'external' });+ const result = spawnSync(process.execPath, ['--test', ...names.map(name => path.join(temp, name.replace(/\.ts$/, '.cjs')))], { stdio: 'inherit' });+ process.exitCode = result.status ?? 1;+} finally { await rm(temp, { recursive: true, force: true }); }diff --git a/packages/worksheet-renderer/tests/scales.test.ts b/packages/worksheet-renderer/tests/scales.test.tsnew file mode 100644index 00000000..7614a9c2--- /dev/null+++ b/packages/worksheet-renderer/tests/scales.test.ts@@ -0,0 +1,157 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { lightTheme } from '../src/color';+import { compileWorksheet, executePlan } from '../src/compiler';+import { metrics } from '../src/layout';+import { buildModel } from '../src/model';+import { buildScene } from '../src/scene';+import { field, nest, type Row, type WorksheetSpec } from '../src/types';+import { logTicks, position, valueAt } from '../src/warp';+import { panned, zoomed } from '../src/zoom';+import { sceneToSVG } from '../src/vegaBackend';+import { fields, near, reference } from './helpers';++const instances = fields(['region', 'product'], { sum: ['value', 'sum'], qty: ['qty', 'sum'] });+const base = { kind: 'worksheet' as const, specVersion: 2 as const, instances };+async function build(spec: WorksheetSpec, rows: Row[], theme = lightTheme) {+ const plan = compileWorksheet(spec);+ const m = buildModel(plan, await executePlan(plan, reference(rows)), { width: 0, height: 0, font: theme.font });+ return { m, items: buildScene(m, { x: 0, y: 0, width: m.width, height: m.height }, { theme }).items };+}+const decades: Row[] = [{ product: 'a', value: 1, qty: 1 }, { product: 'b', value: 10, qty: 4 }, { product: 'c', value: 100, qty: 9 }, { product: 'd', value: 1000, qty: 16 }];+const marks = (items: Awaited<ReturnType<typeof build>>['items']) => items.filter(p => p.selection).sort((a, b) => String(a.selection!.values.product).localeCompare(String(b.selection!.values.product)));++test('scale types place values and give them back', () => {+ assert.equal(position([1, 1000], 10, 'log'), 1 / 3);+ assert.ok(near(valueAt([1, 1000], 2 / 3, 'log'), 100, 1e-9));+ assert.ok(Number.isNaN(position([1, 1000], 0, 'log')));+ assert.equal(position([0, 100], 25, 'sqrt'), .5);+ assert.equal(position([-100, 100], 0, 'symlog'), .5);+ assert.equal(position([0, 100], 25), .25);+ assert.deepEqual(logTicks(1, 1000, 4), [1, 10, 100, 1000]);+ assert.deepEqual(logTicks(1, 100, 12), [1, 2, 5, 10, 20, 50, 100]);+ assert.equal(logTicks(20, 60, 5), undefined, 'inside one power of ten the ticks are linear');+});+test('a log axis gives every power of ten the same room and leaves out what has no place on it', async () => {+ const spec: WorksheetSpec = { ...base, rows: field('product'), columns: field('sum'), mark: 'circle', scales: { columns: { type: 'log' } } };+ const { m, items } = await build(spec, decades);+ const scale = m.columns.leaves[0].scale!;+ assert.deepEqual([scale.domain, scale.type, scale.ticks], [[1, 1000], 'log', [1, 10, 100, 1000]]);+ const xs = marks(items).map(p => p.x);+ assert.ok(near(xs[1] - xs[0], xs[2] - xs[1], .01) && near(xs[2] - xs[1], xs[3] - xs[2], .01), `steps are ${xs}`);+ // Zero and negative values have no place and leave no mark; the axis is unaffected by them.+ const holes = await build(spec, [...decades, { product: 'e', value: 0 }, { product: 'f', value: -5 }]);+ assert.equal(marks(holes.items).length, 4);+ assert.deepEqual(holes.m.columns.leaves[0].scale!.domain, [1, 1000]);+ // Bars start at the edge of the axis, as there is no zero to start from.+ const bars = await build({ ...spec, mark: 'bar' }, decades);+ const leaf = bars.m.columns.leaves[0], start = bars.m.frame.left + leaf.offset + metrics.scalePadStart;+ assert.ok(marks(bars.items).every(p => near(p.x, start, .01)));+ assert.deepEqual(marks(bars.items).map(p => Math.round(p.width!)), [1, 62, 124, 186].map((w, i) => i === 0 ? 1 : w));+});+test('a square root axis keeps zero and thins the labels that crowd near it', async () => {+ const { m, items } = await build({ ...base, columns: field('product'), rows: field('sum'), mark: 'circle', scales: { rows: { type: 'sqrt' } } }, decades);+ const scale = m.rows.leaves[0].scale!;+ assert.equal(scale.domain[0], 0);+ const ys = marks(items).map(p => p.y);+ // 10 sits a tenth of the way up, not a hundredth.+ assert.ok(near((ys[0] - ys[1]) / (ys[0] - ys[3]), (Math.sqrt(10) - 1) / (Math.sqrt(1000) - 1), .01));+ assert.ok(scale.labels!.length === scale.ticks.length);+});+test('fixed ends of an axis win over the data, and marks outside are cut off', async () => {+ const spec: WorksheetSpec = { ...base, rows: field('product'), columns: field('sum'), mark: 'bar', scales: { columns: { min: 5, max: 500 } } };+ const { m, items } = await build(spec, decades);+ const scale = m.columns.leaves[0].scale!;+ assert.deepEqual([scale.domain, scale.full, scale.fixed], [[5, 500], [5, 500], true]);+ const leaf = m.columns.leaves[0], x0 = m.frame.left + leaf.offset, x1 = x0 + leaf.size;+ const drawn = marks(items);+ // The bar of 1 ends before the range and is gone; the bar of 1000 is cut at the right edge.+ assert.deepEqual(drawn.map(p => p.selection!.values.product), ['b', 'c', 'd']);+ assert.ok(drawn.every(p => p.x >= x0 && p.x + p.width! <= x1 + 1e-6));+ assert.ok(near(drawn[2].x + drawn[2].width!, x1));+ // One end alone: the other still follows the data.+ assert.deepEqual((await build({ ...spec, scales: { columns: { max: 50 } } }, decades)).m.columns.leaves[0].scale!.domain, [0, 50]);+ // Rows and columns are set apart.+ assert.equal((await build({ ...spec, scales: { rows: { max: 50 } } }, decades)).m.columns.leaves[0].scale!.fixed, undefined);+});+test('zooming a log axis keeps the value under the pointer and never reaches zero', async () => {+ const { m } = await build({ ...base, rows: field('product'), columns: field('sum'), mark: 'circle', scales: { columns: { type: 'log' } } }, decades);+ const leaf = m.columns.leaves[0];+ // A third of the way along 1..1000 is 10.+ const closer = zoomed(leaf, [1, 1000], 1 / 3, .5);+ assert.ok(near(position(closer, 10, 'log'), 1 / 3, 1e-9));+ assert.ok(closer[0] > 1 && closer[1] < 1000);+ const far = panned(leaf, [1, 1000], 5000);+ assert.ok(far[0] > 0 && far[1] > far[0]);+});++// ---- channels+test('a color range can be fixed and spread by a scale type', async () => {+ const theme = { ...lightTheme, ramp: ['#000000', '#ffffff'] };+ const spec: WorksheetSpec = { ...base, rows: field('product'), columns: field('qty'), mark: 'bar', color: 'sum' };+ const fills = async (scales: WorksheetSpec['scales']) => marks((await build({ ...spec, scales }, decades, theme)).items).map(p => p.fill);+ assert.deepEqual(await fills({ color: { type: 'log' } }), ['rgb(0,0,0)', 'rgb(85,85,85)', 'rgb(170,170,170)', 'rgb(255,255,255)']);+ // Values past a fixed end take the color of that end.+ assert.deepEqual(await fills({ color: { min: 10, max: 100 } }), ['rgb(0,0,0)', 'rgb(0,0,0)', 'rgb(255,255,255)', 'rgb(255,255,255)']);+ const legend = (await build({ ...spec, scales: { color: { min: 10, max: 100 } } }, decades, theme)).items.filter(p => p.layer === 'legend' && p.fontSize === 10).map(p => p.text);+ assert.deepEqual(legend, ['10', '100']);+});+test('size and opacity take a range set by hand, in px and in opacity', async () => {+ const points: WorksheetSpec = { ...base, rows: field('sum'), columns: field('product'), mark: 'circle', size: 'qty', opacity: 'qty', scales: { size: { range: [10, 90] }, opacity: { range: [.2, .6] } } };+ const { items } = await build(points, decades);+ // Sizes still measure from zero: qty runs 1, 4, 9, 16.+ assert.deepEqual(marks(items).map(p => p.size), [15, 30, 55, 90]);+ // Opacity runs over its own range, 1..16.+ assert.ok(marks(items).every((p, i) => near(p.opacity!, .2 + .4 * ([1, 4, 9, 16][i] - 1) / 15, 1e-9)));+ // A fixed start replaces the zero a size measures from.+ const fixed = await build({ ...points, scales: { size: { range: [10, 90], min: 1 } } }, decades);+ assert.deepEqual(marks(fixed.items).map(p => p.size), [10, 26, 10 + 80 * 8 / 15, 90]);+ // Bars take their thickness in px, never more than the member's step.+ const bars = await build({ ...base, rows: field('product'), columns: field('sum'), mark: 'bar', size: 'qty', scales: { size: { range: [4, 20] } } }, decades);+ assert.deepEqual(marks(bars.items).map(p => p.height), [5, 8, 13, 20]);+ const wide = await build({ ...base, rows: field('product'), columns: field('sum'), mark: 'bar', size: 'qty', scales: { size: { range: [4, 400] } } }, decades);+ assert.equal(Math.max(...marks(wide.items).map(p => p.height!)), metrics.bandHeight);+});+test('a channel set to range independently reads every pane against its own values', async () => {+ const theme = { ...lightTheme, ramp: ['#000000', '#ffffff'] };+ const rows: Row[] = [{ region: 'E', product: 'a', value: 1 }, { region: 'E', product: 'b', value: 2 }, { region: 'W', product: 'a', value: 100 }, { region: 'W', product: 'b', value: 300 }];+ const spec: WorksheetSpec = { ...base, rows: nest(field('region'), field('product')), columns: field('sum'), mark: 'bar', color: 'sum' };+ const shared = await build(spec, rows, theme);+ assert.equal(new Set(shared.items.filter(p => p.selection).map(p => p.fill)).size, 4);+ const own = await build({ ...spec, scales: { color: { independent: true } } }, rows, theme);+ const fills = own.items.filter(p => p.selection).sort((a, b) => a.y - b.y).map(p => p.fill);+ assert.deepEqual(fills, ['rgb(0,0,0)', 'rgb(255,255,255)', 'rgb(0,0,0)', 'rgb(255,255,255)']);+ assert.deepEqual(own.m.panes.map(p => p.domains!.color), [[1, 2], [100, 300]]);+ // The legend can name no numbers, only which end is which.+ assert.deepEqual(own.items.filter(p => p.layer === 'legend' && p.fontSize === 10).map(p => p.text), ['Low', 'High']);+ // A dimension keeps one color per member in every pane, whatever the setting.+ const members = await build({ ...spec, color: 'product', scales: { color: { independent: true } } }, rows, theme);+ assert.equal(members.m.panes.every(p => !p.domains), true);+});++// ---- theme style+test('the theme sets font, grid dashes, line and point strokes, filled points and rounded bar ends', async () => {+ const styled = { ...lightTheme, font: 'Georgia, serif', gridDash: [1, 3] as [number, number], lineWidth: 2.5, pointStrokeWidth: 3, barRadius: 4 };+ const bars = await build({ ...base, rows: field('product'), columns: field('sum'), mark: 'bar' }, decades, styled);+ assert.ok(bars.items.filter(p => p.kind === 'text').every(p => p.font === 'Georgia, serif'));+ assert.ok(marks(bars.items).every(p => JSON.stringify(p.radius) === '[0,4,4,0]'), 'the far end of a bar that runs right is its right end');+ const grid = bars.items.filter(p => p.kind === 'path' && p.dash);+ assert.ok(grid.length > 0 && grid.every(p => p.stroke === styled.grid && JSON.stringify(p.dash) === '[1,3]'));+ // The grid is painted under the bars, though a stroked line is a different kind of primitive than a bar.+ assert.ok(grid.every(p => p.under));+ const svg = await sceneToSVG(buildScene(bars.m, { x: 0, y: 0, width: bars.m.width, height: bars.m.height }, { theme: styled }));+ assert.ok(svg.indexOf('stroke-dasharray') > 0 && svg.indexOf('stroke-dasharray') < svg.indexOf(lightTheme.mark), 'dashed grid lines come before the first bar');+ // The zero line stays solid.+ assert.ok(bars.items.some(p => p.kind === 'rect' && p.fill === styled.zero && p.width === 1));+ const upright = await build({ ...base, columns: field('product'), rows: field('sum'), mark: 'bar' }, decades.map(r => ({ ...r, value: -r.value })), styled);+ assert.ok(marks(upright.items).every(p => JSON.stringify(p.radius) === '[0,0,4,4]'), 'a bar that runs down is rounded at the bottom');+ const line = await build({ ...base, columns: field('product'), rows: field('sum'), mark: 'line' }, decades, styled);+ assert.equal(line.items.find(p => p.kind === 'path' && !p.dash)!.strokeWidth, 2.5);+ const points = await build({ ...base, columns: field('product'), rows: field('sum'), mark: 'point' }, decades, styled);+ assert.ok(marks(points.items).every(p => p.strokeWidth === 3 && p.fill === 'transparent'));+ const filled = await build({ ...base, columns: field('product'), rows: field('sum'), mark: 'point' }, decades, { ...styled, pointFilled: true });+ assert.ok(marks(filled.items).every(p => p.fill !== 'transparent' && !p.stroke));+ // Without these the scene is what it was.+ const plain = await build({ ...base, rows: field('product'), columns: field('sum'), mark: 'bar' }, decades);+ assert.ok(plain.items.every(p => !p.font && !p.radius && !p.dash));+});diff --git a/packages/worksheet-renderer/tests/stack.test.ts b/packages/worksheet-renderer/tests/stack.test.tsnew file mode 100644index 00000000..96a8e9a1--- /dev/null+++ b/packages/worksheet-renderer/tests/stack.test.ts@@ -0,0 +1,114 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { compileWorksheet } from '../src/compiler';+import { metrics } from '../src/layout';+import { field, nest, type Row, type WorksheetSpec } from '../src/types';+import { fields, fullScene, model, near } from './helpers';++const instances = { ...fields(['product', 'segment', 'region'], { sum: ['value', 'sum'] }),+ month: { id: 'month', field: 'month', label: 'Month', display: 'continuous' as const, scale: 'time' as const } };+const base = { kind: 'worksheet' as const, specVersion: 2 as const, instances };+// p piles 10 + 30, q piles 20 + 20 + 60.+const piles: Row[] = [{ product: 'p', segment: 'a', value: 10 }, { product: 'p', segment: 'b', value: 30 },+ { product: 'q', segment: 'a', value: 20 }, { product: 'q', segment: 'b', value: 20 }, { product: 'q', segment: 'c', value: 60 }];+const bars: WorksheetSpec = { ...base, rows: field('product'), columns: field('sum'), mark: 'bar', color: 'segment' };+const intervals = (m: Awaited<ReturnType<typeof model>>) => m.panes.flatMap(p => p.marks).map(k => [k.record.product, k.record.segment, k.start, k.end]);++test('normalize stacks shares, so every pile runs from 0 to 100%', async () => {+ const m = await model({ ...bars, stack: 'normalize' }, piles);+ assert.deepEqual(intervals(m), [['p', 'a', 0, .25], ['q', 'a', 0, .2], ['p', 'b', .25, 1], ['q', 'b', .2, .4], ['q', 'c', .4, 1]]);+ const leaf = m.columns.leaves[0];+ assert.deepEqual(leaf.scale!.domain, [0, 1]);+ assert.deepEqual([leaf.scale!.labels![0], leaf.scale!.labels!.at(-1)], ['0%', '100%']);+ const scene = fullScene(m);+ // Both piles end at the same place although q is more than twice p.+ const ends = scene.items.filter(p => p.selection).map(p => p.x + p.width!);+ assert.ok(near(Math.max(...ends.slice(0, 5)), m.frame.left + leaf.size - metrics.scalePadEnd));+ const byProduct = (product: string) => Math.max(...scene.items.filter(p => p.selection?.values.product === product).map(p => p.x + p.width!));+ assert.ok(near(byProduct('p'), byProduct('q'), .01));+ assert.match(scene.items.find(p => p.selection?.values.product === 'p' && p.selection.values.segment === 'a')!.tooltip!, /SUM: 10\n(.*\n)?Share: 25%$/);+ assert.ok(scene.items.some(p => p.layer === 'xAxis' && p.text === '100%'));+});+test('normalize piles magnitudes, and a pile that adds up to nothing draws nothing', async () => {+ const m = await model({ ...bars, stack: 'normalize' }, [{ product: 'p', segment: 'a', value: -10 }, { product: 'p', segment: 'b', value: 30 }, { product: 'z', segment: 'a', value: 0 }]);+ assert.deepEqual(intervals(m).filter(i => i[0] === 'p'), [['p', 'a', 0, .25], ['p', 'b', .25, 1]]);+ assert.equal(fullScene(m).items.filter(p => p.selection).length, 2);+});+test('center stacks end to end with each pile centered on zero', async () => {+ const m = await model({ ...bars, stack: 'center' }, piles);+ assert.deepEqual(intervals(m), [['p', 'a', -20, -10], ['q', 'a', -50, -30], ['p', 'b', -10, 20], ['q', 'b', -30, -10], ['q', 'c', -10, 50]]);+ assert.deepEqual(m.columns.leaves[0].scale!.domain, [-50, 50]);+});+test('stack: true is unchanged and stack: false overlaps from zero, longest painted first', async () => {+ assert.deepEqual(intervals(await model({ ...bars, stack: true }, piles)).filter(i => i[0] === 'p'), [['p', 'a', 0, 10], ['p', 'b', 10, 40]]);+ const loose = await model({ ...bars, stack: false }, piles);+ assert.deepEqual(intervals(loose).filter(i => i[0] === 'q').map(i => i[3]), [60, 20, 20]);+ assert.deepEqual(loose.columns.leaves[0].scale!.domain, [0, 60]);+ // Bars reach back to zero even on an axis told not to start there.+ const free = await model({ ...bars, stack: false, instances: { ...instances, sum: { ...instances.sum, zero: false } } }, piles);+ assert.equal(free.columns.leaves[0].scale!.domain[0], 0);+});++// ---- area+const months = ['2024-01-01', '2024-02-01', '2024-03-01'];+const series: Row[] = months.flatMap((month, i) => [{ month, segment: 'a', value: 10 * (i + 1) }, { month, segment: 'b', value: 5 }]);+const area: WorksheetSpec = { ...base, rows: field('sum'), columns: field('month'), mark: 'area', color: 'segment' };+const corners = (path: string) => path.replace(/[MZ]/g, '').split('L').map(p => p.split(',').map(Number));++test('stacked areas fill from where the pile has reached to where the series ends', async () => {+ const m = await model(area, series);+ const scene = fullScene(m);+ const shapes = scene.items.filter(p => p.kind === 'shape');+ assert.equal(shapes.length, 2);+ assert.deepEqual(m.rows.leaves[0].scale!.domain, [0, 35]);+ const [a, b] = shapes.map(p => corners(p.path!));+ // Three points out along the upper edge and three back along the lower one.+ assert.equal(a.length, 6);+ // The lower edge of b is the upper edge of a, point for point.+ assert.deepEqual(b.slice(3).reverse(), a.slice(0, 3));+ // a sits on the zero line.+ assert.ok(a.slice(3).every(([, y]) => near(y, a[5][1], .01)));+ // Each series has an outline on its upper edge and a spot per point that answers the pointer.+ assert.equal(scene.items.filter(p => p.kind === 'path').length, 2);+ const spots = scene.items.filter(p => p.kind === 'symbol' && p.selection);+ assert.equal(spots.length, 6);+ assert.ok(spots.every(p => p.fill === 'transparent' && p.tooltip));+ const top = spots.find(p => p.selection!.values.segment === 'b' && String(p.selection!.values.month) === months[2])!;+ assert.ok(near(top.y, b[2][1], .1), 'the spot of a stacked series sits on its upper edge, not at its own value');+});+test('unstacked areas all start from zero and let each other show through', async () => {+ const stackedOpacity = fullScene(await model(area, series)).items.find(p => p.kind === 'shape')!.opacity!;+ const scene = fullScene(await model({ ...area, stack: false }, series));+ const shapes = scene.items.filter(p => p.kind === 'shape');+ const bases = shapes.map(p => corners(p.path!).slice(3).map(([, y]) => y));+ assert.ok(bases.flat().every(y => near(y, bases[0][0], .01)));+ assert.ok(shapes[0].opacity! < stackedOpacity);+});+test('normalized areas fill the whole height at every position', async () => {+ const m = await model({ ...area, stack: 'normalize' }, series);+ const [, b] = fullScene(m).items.filter(p => p.kind === 'shape').map(p => corners(p.path!));+ const leaf = m.rows.leaves[0];+ assert.ok(b.slice(0, 3).every(([, y]) => near(y, m.frame.top + metrics.scalePadEnd, .1)), 'the last series ends at 100% everywhere');+ assert.deepEqual(leaf.scale!.domain, [0, 1]);+});+test('a missing value breaks an area, and a lone point is still drawn', async () => {+ const holes: Row[] = [{ month: months[0], value: 4 }, { month: months[1], value: null }, { month: months[2], value: 6 }];+ const scene = fullScene(await model({ ...area, color: undefined }, holes));+ assert.equal(scene.items.filter(p => p.kind === 'shape').length, 0, 'no segment has two points');+ const slivers = scene.items.filter(p => p.kind === 'rect' && p.layer === 'body' && p.width === 3);+ assert.equal(slivers.length, 2);+ assert.ok(slivers.every(p => p.height! > 10));+});+test('areas run along members too, sideways when the measure is on columns, and need one measure axis', async () => {+ const data: Row[] = ['x', 'y', 'z'].map((product, i) => ({ product, region: 'r', value: i + 1 }));+ const down = fullScene(await model({ ...base, rows: field('product'), columns: field('sum'), mark: 'area' }, data));+ const [shape] = down.items.filter(p => p.kind === 'shape');+ const points = corners(shape.path!);+ // Upper edge: x grows with the value while y steps down the members.+ assert.ok(points[0][0] < points[1][0] && points[1][0] < points[2][0]);+ assert.ok(points[0][1] < points[1][1] && points[1][1] < points[2][1]);+ assert.ok(points.slice(3).every(([x]) => near(x, points[5][0], .01)), 'the lower edge is the zero line');+ const nested = await model({ ...base, rows: field('sum'), columns: nest(field('region'), field('product')), mark: 'area' }, data);+ assert.equal(fullScene(nested).items.filter(p => p.kind === 'shape').length, 1);+ assert.throws(() => compileWorksheet({ ...base, rows: field('product'), columns: field('region'), mark: 'area' }), /Area marks need one measure axis/);+});diff --git a/packages/worksheet-renderer/tests/stretch.test.ts b/packages/worksheet-renderer/tests/stretch.test.tsnew file mode 100644index 00000000..5d62d636--- /dev/null+++ b/packages/worksheet-renderer/tests/stretch.test.ts@@ -0,0 +1,117 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { compileWorksheet, executePlan } from '../src/compiler';+import { buildModel } from '../src/model';+import { metrics } from '../src/layout';+import { field, nest, type Row, type WorksheetSpec } from '../src/types';+import { fields, fullScene, near, reference } from './helpers';++const instances = fields(['product', 'region', 'segment'], { sum: ['value', 'sum'], cost: ['cost', 'sum'] });+const base = { kind: 'worksheet' as const, specVersion: 2 as const, instances };+const data = (regions: number, products = 3): Row[] => {+ const rows: Row[] = [];+ for (let r = 0; r < regions; r++) for (let p = 0; p < products; p++) rows.push({ region: `R${String(r).padStart(2, '0')}`, product: `P${p}`, segment: p % 2 ? 'a' : 'b', value: 10 + r + p, cost: 3 + p * 2 + r });+ return rows;+};+type Window = { width: number; height: number; scrollbar?: number };+async function stretched(spec: Omit<WorksheetSpec, 'kind' | 'specVersion' | 'instances'>, rows: Row[], window: Window) {+ const plan = compileWorksheet({ ...base, stretch: 'both', ...spec });+ return buildModel(plan, await executePlan(plan, reference(rows)), window);+}+const window = { width: 1200, height: 600 };++test('three bars stay three narrow bars: the value axis takes the height, the steps keep their width', async () => {+ const bars = { columns: field('product'), rows: field('sum'), mark: 'bar' as const };+ const m = await stretched(bars, data(1), window);+ assert.ok(m.columns.leaves.every(leaf => leaf.size === metrics.bandWidth));+ assert.ok(near(m.height, window.height, .5), `height ${m.height}`);+ assert.ok(near(m.rows.leaves[0].size, window.height - m.frame.top - m.frame.bottom, .5));+ assert.ok(near(m.width, m.frame.left + 3 * metrics.bandWidth + m.frame.right, .5) && m.width < window.width / 2, 'the room to the right stays empty');+ // The marks follow: the longest bar spans the slot, and no bar is wider than its step.+ const drawn = fullScene(m).items.filter(p => p.selection);+ assert.ok(Math.max(...drawn.map(p => p.height!)) > window.height * .7);+ assert.ok(drawn.every(p => p.width! <= metrics.bandWidth));+ // The same sheet in a larger window: only the height of the slot changes.+ const larger = await stretched(bars, data(1), { width: 1800, height: 900 });+ assert.ok(near(larger.width, m.width, 12), 'only the width of the axis labels may differ');+ assert.ok(near(larger.height, 900, .5));+});+test('a sheet with a value axis each way fills the window', async () => {+ const m = await stretched({ columns: field('cost'), rows: field('sum'), mark: 'point', detail: ['product'] }, data(1, 8), window);+ assert.ok(near(m.width, window.width, .5) && near(m.height, window.height, .5), `${m.width}×${m.height}`);+});+test('facets share the room evenly', async () => {+ const m = await stretched({ columns: field('product'), rows: nest(field('region'), field('sum')), mark: 'bar' }, data(4), window);+ assert.equal(m.rows.leaves.length, 4);+ const size = (window.height - m.frame.top - m.frame.bottom) / 4;+ assert.ok(m.rows.leaves.every(leaf => near(leaf.size, size, 1e-6)));+ assert.ok(near(m.height, window.height, .5));+});+test('value slots next to member steps on one axis get what the steps leave', async () => {+ // Horizontal bars: members down the rows, one value slot per region across the columns.+ const m = await stretched({ rows: field('product'), columns: nest(field('region'), field('sum')), mark: 'bar' }, data(3), window);+ assert.ok(m.rows.leaves.every(leaf => leaf.size === metrics.bandHeight));+ assert.ok(near(m.width, window.width, .5));+ assert.ok(m.height < window.height / 2);+});+test('slots stop at their least size, and the sheet scrolls from there', async () => {+ const spec = { columns: field('cost'), rows: nest(field('region'), field('sum')), mark: 'point' as const, detail: ['product'] };+ const m = await stretched(spec, data(20), window);+ assert.ok(m.rows.leaves.every(leaf => leaf.size === metrics.slotMinHeight));+ assert.ok(m.height > window.height);+ assert.ok(near(m.width, window.width, .5), 'a scroll bar that lies over the content takes no room');+ // A scroll bar that takes room leaves the other direction that much less.+ const barred = await stretched(spec, data(20), { ...window, scrollbar: 15 });+ assert.ok(near(barred.width, window.width - 15, .5), `width ${barred.width}`);+ // Without a bar the sheet has the whole window.+ const fits = await stretched(spec, data(3), { ...window, scrollbar: 15 });+ assert.ok(near(fits.width, window.width, .5) && near(fits.height, window.height, .5));+});+test('a bar across the bottom shortens the value axis, and never the other way round twice', async () => {+ // Sixty member steps do not fit in 1200 px, so the rows lose the height of a scroll bar.+ const m = await stretched({ columns: field('product'), rows: field('sum'), mark: 'bar' }, data(1, 60), { ...window, scrollbar: 15 });+ assert.ok(m.width > window.width);+ assert.ok(near(m.height, window.height - 15, .5), `height ${m.height}`);+});+test('a sheet of member steps only is not stretched', async () => {+ const spec = { columns: field('product'), rows: field('region'), mark: 'rect' as const, color: 'sum' };+ const plan = compileWorksheet({ ...base, ...spec });+ const natural = buildModel(plan, await executePlan(plan, reference(data(4))));+ const m = await stretched(spec, data(4), window);+ assert.equal(m.width, natural.width);+ assert.equal(m.height, natural.height);+});+test('stretch in one direction leaves the other alone', async () => {+ const m = await stretched({ columns: field('cost'), rows: field('sum'), mark: 'point', detail: ['product'], stretch: 'width' }, data(1, 8), window);+ assert.ok(near(m.width, window.width, .5));+ assert.equal(m.rows.leaves[0].size, metrics.slotHeight);+});+test('a pane size the host set is the least a stretched slot gets', async () => {+ const m = await stretched({ columns: field('product'), rows: nest(field('region'), field('sum')), mark: 'bar', pane: { height: 150 } }, data(8), window);+ assert.ok(m.rows.leaves.every(leaf => leaf.size === 150));+ assert.ok(m.height > window.height);+});+test('pies grow as squares, and only when both directions may', async () => {+ const pie = { mark: 'arc' as const, angle: 'sum', color: 'product', columns: field('region'), rows: { kind: 'empty' as const } };+ const m = await stretched(pie, data(3), window);+ const side = m.columns.leaves[0].size;+ assert.ok(side > metrics.pieSize, `side ${side}`);+ assert.ok(m.columns.leaves.every(leaf => leaf.size === side) && m.rows.leaves.every(leaf => leaf.size === side));+ assert.ok(m.width <= window.width + .5 && m.height <= window.height + .5);+ // Three in a row: the width of a third is less than the height, so the width decides.+ assert.ok(near(side, (window.width - m.frame.left - m.frame.right) / 3, .5));+ const oneWay = await stretched({ ...pie, stretch: 'width' }, data(3), window);+ assert.equal(oneWay.columns.leaves[0].size, metrics.pieSize);+ const many = await stretched(pie, data(30), window);+ assert.equal(many.columns.leaves[0].size, metrics.pieMinSize);+});+test('fit wins where a sheet asks for both', async () => {+ const m = await stretched({ columns: field('product'), rows: field('sum'), mark: 'bar', fit: 'both' }, data(1), window);+ assert.ok(near(m.width, window.width, .5), 'the member steps are scaled up');+ assert.ok(m.columns.leaves[0].size > metrics.bandWidth);+});+test('ticks follow the stretched slot', async () => {+ const short = await stretched({ columns: field('product'), rows: field('sum'), mark: 'bar' }, data(1), { width: 800, height: 200 });+ const tall = await stretched({ columns: field('product'), rows: field('sum'), mark: 'bar' }, data(1), { width: 800, height: 900 });+ assert.ok(tall.rows.leaves[0].scale!.ticks.length > short.rows.leaves[0].scale!.ticks.length);+});diff --git a/packages/worksheet-renderer/tests/time.test.ts b/packages/worksheet-renderer/tests/time.test.tsnew file mode 100644index 00000000..5e401c90--- /dev/null+++ b/packages/worksheet-renderer/tests/time.test.ts@@ -0,0 +1,114 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { compileWorksheet } from '../src/compiler';+import { timeScale, timeValue } from '../src/time';+import { field, nest, type Row, type WorksheetSpec } from '../src/types';+import { fields, fullScene, model, near } from './helpers';++const utc = (iso: string) => Date.parse(iso);+const day = 86_400_000;+const instances: WorksheetSpec['instances'] = {+ ...fields(['region', 'segment'], { sum: ['value', 'sum'] }),+ date: { id: 'date', field: 'date', label: 'Date', display: 'continuous', scale: 'time' },+};+const base = { kind: 'worksheet' as const, specVersion: 2 as const, instances };++test('time ticks fall on calendar boundaries and name the year where it changes', () => {+ const months = timeScale(utc('2024-02-10'), utc('2025-11-20'), 400, 62);+ assert.deepEqual(months.domain, [utc('2024-02-10'), utc('2025-11-20')]);+ assert.deepEqual(months.ticks, ['2024-04-01', '2024-07-01', '2024-10-01', '2025-01-01', '2025-04-01', '2025-07-01', '2025-10-01'].map(utc));+ assert.deepEqual(months.labels, ['Apr 2024', 'Jul', 'Oct', '2025', 'Apr', 'Jul', 'Oct']);+ const days = timeScale(utc('2024-03-01T08:00:00Z'), utc('2024-03-09T20:00:00Z'), 400, 62);+ assert.deepEqual(days.labels, ['Mar 2', 'Mar 4', 'Mar 6', 'Mar 8']);+ assert.ok(days.ticks.every(t => t % day === 0));+ const weeks = timeScale(utc('2024-03-01'), utc('2024-04-10'), 400, 62);+ assert.ok(weeks.ticks.every(t => new Date(t).getUTCDay() === 1), 'weeks start on Monday');+ const hours = timeScale(utc('2024-03-01T22:00:00Z'), utc('2024-03-02T09:00:00Z'), 400, 62);+ assert.deepEqual(hours.labels, ['Mar 2', '03:00', '06:00', '09:00']);+ const years = timeScale(utc('1991-06-01'), utc('2024-06-01'), 300, 62);+ assert.deepEqual(years.labels, ['2000', '2010', '2020']);+ assert.equal(timeScale(utc('2024-03-01'), utc('2024-03-01'), 200, 62).domain[1] - utc('2024-03-01'), day / 2);+});+test('dates given as ISO strings, Date objects or milliseconds land on the same positions', async () => {+ const isoDates = ['2024-01-01', '2024-01-02', '2024-01-10'];+ const spec: WorksheetSpec = { ...base, rows: field('sum'), columns: field('date'), mark: 'line' };+ const xs = async (convert: (iso: string) => unknown) => {+ const m = await model(spec, isoDates.map((iso, i) => ({ date: convert(iso), value: i + 1 })));+ assert.deepEqual(m.columns.leaves[0].scale!.domain, [utc('2024-01-01'), utc('2024-01-10')], 'a date axis does not start at zero');+ return fullScene(m).items.filter(p => p.selection).map(p => p.x).sort((a, b) => a - b);+ };+ const fromStrings = await xs(iso => iso);+ assert.ok(near((fromStrings[2] - fromStrings[1]) / (fromStrings[1] - fromStrings[0]), 8, .05), 'spacing follows elapsed time');+ assert.deepEqual(await xs(iso => new Date(iso)), fromStrings);+ assert.deepEqual(await xs(iso => utc(iso)), fromStrings);+ assert.ok(Number.isNaN(timeValue('not a date')) && Number.isNaN(timeValue(null)));+ await assert.rejects(model(spec, [{ date: 'soon', value: 1 }]), /not a date: soon/);+});+test('a time axis is labelled with dates on the table edge and in tooltips', async () => {+ const rows: Row[] = [];+ for (const region of ['E', 'W']) for (let month = 0; month < 12; month++) rows.push({ region, date: new Date(Date.UTC(2024, month, 1)).toISOString(), value: month });+ const m = await model({ ...base, rows: nest(field('region'), field('sum')), columns: field('date'), mark: 'line', pane: { width: 420 } }, rows);+ const scene = fullScene(m);+ const ticks = scene.items.filter(p => p.layer === 'xAxis' && p.kind === 'text' && p.fontWeight !== 600).map(p => p.text);+ assert.deepEqual(ticks, ['2024', 'Mar', 'May', 'Jul', 'Sep', 'Nov']);+ assert.equal(scene.items.filter(p => p.kind === 'path').length, 2);+ assert.ok(scene.items.find(p => p.selection)!.tooltip!.includes('Date: Jan 1, 2024'));+});+test('bars along a date axis keep one width, stack per date and are not cut at the ends', async () => {+ const rows: Row[] = [];+ for (const region of ['E', 'W']) for (let month = 0; month < 6; month++) for (const segment of ['a', 'b']) {+ if (region === 'W' && month % 2) continue;+ rows.push({ region, segment, date: new Date(Date.UTC(2024, month, 1)).toISOString(), value: 10 + month });+ }+ const spec: WorksheetSpec = { ...base, rows: nest(field('region'), field('sum')), columns: field('date'), mark: 'bar', color: 'segment', pane: { width: 360 } };+ const m = await model(spec, rows);+ const leaf = m.columns.leaves[0];+ assert.equal(leaf.scale!.step, 29 * day, 'February is the shortest gap');+ assert.deepEqual(leaf.scale!.domain, [utc('2024-01-01') - 14.5 * day, utc('2024-06-01') + 14.5 * day]);+ const bars = fullScene(m).items.filter(p => p.selection);+ assert.equal(bars.length, 18);+ assert.ok(bars.every(b => near(b.width!, bars[0].width!, 1e-6)), 'W has half the dates but the same bar width');+ const bodyLeft = m.frame.left, bodyRight = m.frame.left + m.columns.size;+ assert.ok(bars.every(b => b.x >= bodyLeft && b.x + b.width! <= bodyRight));+ const january = bars.filter(b => b.selection!.values.region === 'E' && b.selection!.values.date.startsWith('2024-01')).sort((a, b) => b.y - a.y);+ assert.ok(near(january[0].x, january[1].x) && near(january[1].y + january[1].height!, january[0].y), 'segments stack at one date');+ const march = bars.find(b => b.selection!.values.region === 'E' && b.selection!.values.date.startsWith('2024-03'))!;+ assert.ok(march.x > january[0].x + january[0].width!, 'neighbouring dates do not touch');+});+test('bars need exactly one measure axis', () => {+ const two = { ...base, instances: { ...instances, ...fields([], { mean: ['value', 'mean'] }) } };+ assert.throws(() => compileWorksheet({ ...two, rows: field('sum'), columns: field('mean'), mark: 'bar' }), /one measure axis/);+ assert.throws(() => compileWorksheet({ ...base, rows: field('region'), columns: field('segment'), mark: 'bar' }), /one measure axis/);+ assert.doesNotThrow(() => compileWorksheet({ ...base, rows: field('sum'), columns: field('date'), mark: 'bar' }));+});++test('members of a discrete time field are named after their period, in the zone the offset selects', async () => {+ const { formatPeriod, memberLabel } = await import('../src/time');+ const t = Date.UTC(2024, 6, 15, 13, 5, 9);+ assert.deepEqual((['year', 'quarter', 'month', 'day', 'hour', 'second'] as const).map(unit => formatPeriod(t, unit)),+ ['2024', '2024 Q3', '2024-07', '2024-07-15', '2024-07-15 13:05', '2024-07-15 13:05:09']);+ // 30 December 2024 is a Monday and already belongs to the first ISO week of 2025.+ assert.deepEqual([formatPeriod(Date.UTC(2024, 11, 30), 'iso_week'), formatPeriod(Date.UTC(2024, 11, 30), 'iso_year'), formatPeriod(Date.UTC(2021, 0, 3), 'iso_week')], ['2025 W01', '2025', '2020 W53']);+ // The start of 2024 in a zone eight hours behind UTC, as a host in that zone stores it.+ const year = { id: 'y', field: 'y', label: 'Year', display: 'discrete' as const, scale: 'time' as const, timeUnit: 'year' as const, timeOffset: -8 * 3600_000 };+ assert.equal(memberLabel(year, Date.UTC(2024, 0, 1, 8)), '2024');+ assert.equal(memberLabel({ ...year, timeOffset: undefined }, Date.UTC(2023, 11, 31, 23)), '2023');+ assert.equal(memberLabel(year, null), '(null)');+ const rows = [{ y: Date.UTC(2025, 0, 1, 8), value: 2 }, { y: Date.UTC(2024, 0, 1, 8), value: 1 }];+ const instances = { y: year, sum: { id: 'sum', field: 'value', label: 'SUM', display: 'continuous' as const, aggregate: 'sum' as const } };+ const m = await model({ kind: 'worksheet', specVersion: 2, instances, rows: field('y'), columns: field('sum'), mark: 'bar' }, rows);+ const scene = fullScene(m);+ assert.deepEqual(scene.items.filter(p => p.layer === 'rowHeader' && p.tooltip?.startsWith('Year')).map(p => p.text), ['2024', '2025']);+ assert.deepEqual(scene.items.filter(p => p.selection).sort((a, b) => a.y - b.y).map(p => p.tooltip), ['Year: 2024\nSUM: 1', 'Year: 2025\nSUM: 2']);+});++test('a date axis that passes the start of 1970 draws no zero line there', async () => {+ const rows: Row[] = [{ date: '1969-01-01', value: 3 }, { date: '1970-01-01', value: 5 }, { date: '1971-01-01', value: 4 }];+ const m = await model({ ...base, rows: field('sum'), columns: field('date'), mark: 'line' }, rows);+ assert.ok(m.columns.leaves[0].scale!.ticks.includes(0), 'the axis has a tick at the start of 1970');+ const scene = fullScene(m);+ const { lightTheme } = await import('../src/color');+ // The value axis starts at zero and keeps its zero line; it is the only one.+ const zero = scene.items.filter(p => p.kind === 'rect' && p.fill === lightTheme.zero);+ assert.ok(zero.length === 1 && zero[0].height === 1, `zero lines: ${JSON.stringify(zero.map(p => [p.width, p.height]))}`);+});diff --git a/packages/worksheet-renderer/tests/zoom.test.ts b/packages/worksheet-renderer/tests/zoom.test.tsnew file mode 100644index 00000000..642ea72a--- /dev/null+++ b/packages/worksheet-renderer/tests/zoom.test.ts@@ -0,0 +1,114 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { clipLine, clipPolygon, clipRect } from '../src/clip';+import { compileWorksheet, executePlan } from '../src/compiler';+import { metrics } from '../src/layout';+import { buildModel, type Zoom } from '../src/model';+import { buildScene } from '../src/scene';+import { field, nest, type Row, type WorksheetSpec } from '../src/types';+import { axesAt, panned, withRange, zoomed } from '../src/zoom';+import { fields, near, reference } from './helpers';++const box = { x0: 0, y0: 0, x1: 10, y1: 10 };+test('rectangles, lines and outlines are cut to a box', () => {+ assert.deepEqual(clipRect(box, -5, 2, 10, 3), [0, 2, 5, 3]);+ assert.equal(clipRect(box, 11, 2, 4, 3), undefined);+ // A line that leaves the box and comes back becomes two pieces.+ assert.deepEqual(clipLine(box, [[-5, 5], [5, 5], [5, 15], [8, 15], [8, 5]]), [[[0, 5], [5, 5], [5, 10]], [[8, 10], [8, 5]]]);+ assert.deepEqual(clipLine(box, [[20, 20], [30, 30]]), []);+ assert.deepEqual(clipLine(box, [[2, 2], [4, 4], [6, 2]]), [[[2, 2], [4, 4], [6, 2]]]);+ // A segment that crosses the whole box without a point inside it still shows.+ assert.deepEqual(clipLine(box, [[-5, 5], [15, 5]]), [[[0, 5], [10, 5]]]);+ const cut = clipPolygon(box, [[-5, 2], [5, 2], [5, 8], [-5, 8]]);+ assert.deepEqual([Math.min(...cut.map(p => p[0])), Math.max(...cut.map(p => p[0]))], [0, 5]);+ assert.deepEqual(clipPolygon(box, [[20, 20], [30, 20], [30, 30]]), []);+});++const instances = { ...fields(['region', 'product'], { sum: ['value', 'sum'], qty: ['qty', 'sum'] }),+ when: { id: 'when', field: 'when', label: 'When', display: 'continuous' as const, scale: 'time' as const } };+const base = { kind: 'worksheet' as const, specVersion: 2 as const, instances };+const rows: Row[] = [];+for (const region of ['E', 'W']) for (const [product, value] of [['a', 20], ['b', 60], ['c', 100]] as const) rows.push({ region, product, value: region === 'E' ? value : value / 2, qty: value / 10, when: `2024-0${'abc'.indexOf(product) + 1}-01` });+async function build(spec: WorksheetSpec, zoom?: Zoom) {+ const plan = compileWorksheet(spec);+ const m = buildModel(plan, await executePlan(plan, reference(rows)), undefined, undefined, zoom);+ return { m, scene: buildScene(m, { x: 0, y: 0, width: m.width, height: m.height }) };+}+const bars: WorksheetSpec = { ...base, rows: nest(field('region'), field('product')), columns: field('sum'), mark: 'bar' };++test('a zoomed axis shows its new range in every pane that shares it, and keeps the range the data asks for', async () => {+ const plain = await build(bars);+ const scale = plain.m.columns.leaves[0].scale!;+ assert.deepEqual(scale.domain, [0, 100]);+ assert.deepEqual(scale.full, [0, 100]);+ const { m, scene } = await build(bars, { [scale.key!]: [40, 80] });+ assert.deepEqual(m.columns.leaves[0].scale!.domain, [40, 80]);+ assert.deepEqual(m.columns.leaves[0].scale!.full, [0, 100]);+ assert.ok(m.columns.leaves[0].scale!.ticks.every(t => t >= 40 && t <= 80));+ // The frame does not move with the zoom.+ assert.equal(m.width, plain.m.width);+ const leaf = m.columns.leaves[0], x0 = m.frame.left + leaf.offset, x1 = x0 + leaf.size;+ const drawn = scene.items.filter(p => p.selection);+ // 20 and the three halved values of W up to 30 end before the range and leave nothing; the rest are cut at both edges.+ assert.deepEqual(drawn.map(p => p.selection!.values.__ws_sum).sort((a, b) => a - b), [50, 60, 100]);+ assert.ok(drawn.every(p => p.x >= x0 - 1e-6 && p.x + p.width! <= x1 + 1e-6), 'no bar leaves its pane');+ const longest = drawn.find(p => p.selection!.values.__ws_sum === 100)!;+ assert.ok(near(longest.x, x0) && near(longest.x + longest.width!, x1), 'a bar that spans the range fills the pane from edge to edge');+ // A range that is not one is ignored.+ assert.deepEqual((await build(bars, { [scale.key!]: [80, 40] })).m.columns.leaves[0].scale!.domain, [0, 100]);+});+test('points outside a zoomed range are left out, lines are cut at the pane edge, and a time axis zooms too', async () => {+ const scatter: WorksheetSpec = { ...base, rows: field('sum'), columns: field('qty'), mark: 'circle', detail: ['product', 'region'] };+ const plain = await build(scatter);+ const key = plain.m.columns.leaves[0].scale!.key!;+ assert.equal(plain.scene.items.filter(p => p.selection).length, 6);+ assert.equal((await build(scatter, { [key]: [5, 7] })).scene.items.filter(p => p.selection).length, 2);+ const line: WorksheetSpec = { ...base, rows: field('sum'), columns: field('when'), mark: 'line', detail: ['region'] };+ const whole = await build(line);+ const time = whole.m.columns.leaves[0].scale!;+ const middle: [number, number] = [Date.parse('2024-01-20'), Date.parse('2024-02-10')];+ const cut = await build(line, { [time.key!]: middle });+ const leaf = cut.m.columns.leaves[0], x0 = cut.m.frame.left + leaf.offset, x1 = x0 + leaf.size;+ const paths = cut.scene.items.filter(p => p.kind === 'path');+ assert.equal(paths.length, 2);+ for (const path of paths) {+ const xs = path.path!.replace(/M/g, '').split(/[L ]/).map(p => Number(p.split(',')[0]));+ assert.ok(xs.every(x => x >= x0 - .1 && x <= x1 + .1), `a line leaves its pane: ${xs}`);+ assert.ok(near(xs[0], x0, .1), 'the line starts on the left edge although its first point is outside');+ }+ assert.equal(cut.scene.items.filter(p => p.kind === 'symbol' && p.selection).length, 2, 'only the February points are inside');+ assert.ok(cut.m.columns.leaves[0].scale!.labels!.length > 0);+});+test('the pointer finds the value axes of the pane under it and where along them it is', async () => {+ const { m, scene } = await build({ ...base, rows: nest(field('region'), field('sum')), columns: nest(field('product'), field('qty')), mark: 'circle' });+ const viewport = { x: 0, y: 0, width: m.width, height: m.height };+ const column = m.columns.leaves[1], row = m.rows.leaves[1];+ const px = m.frame.left + column.offset + metrics.scalePadStart + (column.size - metrics.scalePadStart - metrics.scalePadEnd) * .25;+ const py = m.frame.top + row.offset + row.size - metrics.scalePadStart - (row.size - metrics.scalePadStart - metrics.scalePadEnd) * .75;+ const at = axesAt(m, scene.body, viewport, px, py);+ assert.equal(at.x!.leaf, column);+ assert.equal(at.y!.leaf, row);+ assert.ok(near(at.x!.t, .25, 1e-9) && near(at.y!.t, .75, 1e-9));+ // Scrolled, the same window position is over a later pane.+ assert.equal(axesAt(m, scene.body, { ...viewport, x: column.size }, px, py).x!.leaf, m.columns.leaves[2]);+ // Outside the body, and over a pane without a value axis, there is nothing to zoom.+ assert.deepEqual(axesAt(m, scene.body, viewport, 2, py), {});+ const table = await build({ ...base, rows: field('region'), columns: field('product'), mark: 'text', text: 'sum' });+ assert.deepEqual(axesAt(table.m, table.scene.body, { x: 0, y: 0, width: table.m.width, height: table.m.height }, table.m.frame.left + 5, table.m.frame.top + 5), {});+});+test('zooming keeps the value under the pointer in place, panning moves the range with the drag', async () => {+ const { m } = await build(bars);+ const leaf = m.columns.leaves[0];+ // A quarter of the way along 0..100 is 25; after zooming in by half it is still a quarter of the way along.+ assert.deepEqual(zoomed(leaf, [0, 100], .25, .5), [12.5, 62.5]);+ assert.deepEqual(zoomed(leaf, [12.5, 62.5], .25, 2), [0, 100]);+ // Zoom stops at 20 times the range the data asks for, and at a ten-thousandth of it.+ assert.equal(zoomed(leaf, [0, 100], .5, 1e9)[1] - zoomed(leaf, [0, 100], .5, 1e9)[0], 2000);+ assert.ok(near(zoomed(leaf, [0, 100], .5, 1e-9)[1] - zoomed(leaf, [0, 100], .5, 1e-9)[0], .01, 1e-9));+ const pixels = leaf.size - metrics.scalePadStart - metrics.scalePadEnd;+ // Dragging right by half the axis brings lower values into view.+ assert.deepEqual(panned(leaf, [0, 100], pixels / 2), [-50, 50]);+ const key = leaf.scale!.key!;+ assert.deepEqual(withRange({}, leaf, [10, 20]), { [key]: [10, 20] });+ assert.deepEqual(withRange({ [key]: [10, 20] }, leaf, [0, 100]), {}, 'back at the full range there is no zoom left');+});diff --git a/packages/worksheet-renderer/tsconfig.json b/packages/worksheet-renderer/tsconfig.jsonnew file mode 100644index 00000000..4057545d--- /dev/null+++ b/packages/worksheet-renderer/tsconfig.json@@ -0,0 +1,9 @@+{+ "compilerOptions": {+ "target": "ES2020", "lib": ["ES2020", "DOM"], "module": "ESNext",+ "moduleResolution": "Bundler", "jsx": "react-jsx", "strict": true,+ "skipLibCheck": true, "noEmit": true, "noUnusedLocals": true,+ "noUnusedParameters": true, "esModuleInterop": true+ },+ "include": ["src"]+}