Skip to content

An open source alternative to Tableau. Embeddable visual analytic

fix: keep the default worksheet renderer in production builds

observedobservera4b3bc1e87c0
diff --git a/packages/graphic-walker/playwright.config.ts b/packages/graphic-walker/playwright.config.ts
index c9f12f80..95c77e38 100644
--- a/packages/graphic-walker/playwright.config.ts
+++ b/packages/graphic-walker/playwright.config.ts
@@ -35,11 +35,12 @@ export default defineConfig({
},
],
webServer: {
+ // Build the published library first: routing tests consume it without test-only registration.
// Serve a production bundle so every isolated browser context loads a bounded
// asset set. The dev-server module graph can crash Playwright's WebKit network
// inspector while it processes hundreds of concurrent module responses.
command:
- 'yarn vite build --config tests/e2e/vite.config.ts && yarn vite preview --config tests/e2e/vite.config.ts',
+ 'yarn build && yarn vite build --config tests/e2e/vite.config.ts && yarn vite preview --config tests/e2e/vite.config.ts',
url: 'http://127.0.0.1:4175/tests/e2e/issue-501.html',
reuseExistingServer: !process.env.CI,
timeout: 300_000,
diff --git a/packages/graphic-walker/src/components/visualConfig/index.tsx b/packages/graphic-walker/src/components/visualConfig/index.tsx
index c219d785..34cef60d 100644
--- a/packages/graphic-walker/src/components/visualConfig/index.tsx
+++ b/packages/graphic-walker/src/components/visualConfig/index.tsx
@@ -21,7 +21,6 @@ import { DropdownMenu, DropdownMenuCheckboxItem, DropdownMenuContent, DropdownMe
import { 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 (
@@ -162,7 +161,6 @@ const VisualConfigPanel: React.FC = () => {
const [scaleIncludeUnmatchedChoropleth, setScaleIncludeUnmatchedChoropleth] = useState<boolean>(layout.scaleIncludeUnmatchedChoropleth ?? false);
const [showAllGeoshapeInChoropleth, setShowAllGeoshapeInChoropleth] = useState<boolean>(layout.showAllGeoshapeInChoropleth ?? false);
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);
@@ -600,8 +598,7 @@ const VisualConfigPanel: React.FC = () => {
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' }] : []),
+ { value: 'native', label: 'Worksheet' },
]}
/>
</div>
diff --git a/packages/graphic-walker/src/fields/posFields/index.tsx b/packages/graphic-walker/src/fields/posFields/index.tsx
index 508bccdf..4b5171cc 100644
--- a/packages/graphic-walker/src/fields/posFields/index.tsx
+++ b/packages/graphic-walker/src/fields/posFields/index.tsx
@@ -7,14 +7,13 @@ 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, 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 facetedPie = (layout.renderer ?? 'native') === 'native';
const channels = useMemo(() => {
if (coordSystem === 'geographic') {
diff --git a/packages/graphic-walker/src/locales/en-US.json b/packages/graphic-walker/src/locales/en-US.json
index 03190642..ccd370d5 100644
--- a/packages/graphic-walker/src/locales/en-US.json
+++ b/packages/graphic-walker/src/locales/en-US.json
@@ -124,13 +124,10 @@
}
},
"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.",
+ "unsupported_title": "This chart configuration is not supported yet",
+ "unsupported_desc": "Adjust the fields or chart type to continue.",
"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.",
+ "failed_desc": "Try again. Your chart settings are saved.",
"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.",
diff --git a/packages/graphic-walker/src/locales/ja-JP.json b/packages/graphic-walker/src/locales/ja-JP.json
index cbda9357..a6c9a10a 100644
--- a/packages/graphic-walker/src/locales/ja-JP.json
+++ b/packages/graphic-walker/src/locales/ja-JP.json
@@ -123,13 +123,10 @@
}
},
"chart_notice": {
- "loading_title": "ワークシートレンダラーを読み込み中…",
- "unavailable_title": "この環境ではワークシートレンダラーを利用できません",
- "unavailable_desc": "このチャートはワークシートレンダラー(プレビュー)で描画する設定ですが、この環境には含まれていません。チャートの設定はそのまま保持され、他のレンダラーで代わりに描画されることはありません。ワークシートレンダラーを利用できる環境で開くか、チャート設定で別のレンダラーを選択してください。",
- "unsupported_title": "ワークシートレンダラーはこのチャートをまだ描画できません",
- "unsupported_desc": "チャートの設定はそのまま保持されます。上記の内容を変更するか、チャート設定で別のレンダラーを選択してください。",
+ "unsupported_title": "このチャート設定にはまだ対応していません",
+ "unsupported_desc": "フィールドまたはチャートの種類を変更してください。",
"failed_title": "チャートを描画できませんでした",
- "failed_desc": "チャートの設定と選択したレンダラーはそのまま保持されます。再試行するか、チャートを変更してください。",
+ "failed_desc": "再試行してください。チャートの設定は保存されています。",
"retry": "再試行",
"levels_title": "{{renderer}} はこのチャートのすべての階層を表示できません",
"levels_reason": "{{shelf}}に {{count}} 個のディメンションがあります({{fields}})。{{renderer}} が表示できるのは 2 個までです。",
diff --git a/packages/graphic-walker/src/locales/zh-CN.json b/packages/graphic-walker/src/locales/zh-CN.json
index a588d1cb..d4b14d75 100644
--- a/packages/graphic-walker/src/locales/zh-CN.json
+++ b/packages/graphic-walker/src/locales/zh-CN.json
@@ -123,13 +123,10 @@
}
},
"chart_notice": {
- "loading_title": "正在加载工作表渲染器…",
- "unavailable_title": "当前环境没有工作表渲染器",
- "unavailable_desc": "这张图表设置为由工作表渲染器(预览)绘制,当前环境没有提供它。图表配置保持不变,也不会改用其他渲染器绘制。请在提供工作表渲染器的环境中打开,或在图表设置里选择其他渲染器。",
- "unsupported_title": "工作表渲染器暂时不能绘制这张图表",
- "unsupported_desc": "图表配置保持不变。请调整上面提到的内容,或在图表设置里选择其他渲染器。",
+ "unsupported_title": "暂不支持这种图表配置",
+ "unsupported_desc": "请调整字段或图表类型。",
"failed_title": "图表绘制失败",
- "failed_desc": "图表配置和所选渲染器保持不变。可以重试,或修改图表。",
+ "failed_desc": "请重试,图表设置已保留。",
"retry": "重试",
"levels_title": "{{renderer}} 无法展示这张图表的全部层级",
"levels_reason": "{{shelf}}上有 {{count}} 个维度({{fields}}),{{renderer}} 最多展示两个。",
diff --git a/packages/graphic-walker/src/renderer/chartNotice.tsx b/packages/graphic-walker/src/renderer/chartNotice.tsx
index cd3b2c82..e9928e10 100644
--- a/packages/graphic-walker/src/renderer/chartNotice.tsx
+++ b/packages/graphic-walker/src/renderer/chartNotice.tsx
@@ -5,14 +5,10 @@ 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.',
+ unsupported_title: 'This chart configuration is not supported yet',
+ unsupported_desc: 'Adjust the fields or chart type to continue.',
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.',
+ failed_desc: 'Try again. Your chart settings are saved.',
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.',
@@ -35,12 +31,12 @@ export default function ChartNotice({ notice, onRetry }: { notice: ChartNoticeCo
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
? [notice.reason]
: [];
- const detail = notice.state === 'loading' ? '' : say(`${notice.state}_desc`);
+ const detail = 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 role="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) => (
diff --git a/packages/graphic-walker/src/renderer/index.tsx b/packages/graphic-walker/src/renderer/index.tsx
index dfcb962c..6b0beacc 100644
--- a/packages/graphic-walker/src/renderer/index.tsx
+++ b/packages/graphic-walker/src/renderer/index.tsx
@@ -1,4 +1,5 @@
-import './native';
+// A direct dependency: production bundlers must retain the default renderer.
+import { worksheetRenderer } from './native';
import { observer } from 'mobx-react-lite';
import React, { useState, useEffect, forwardRef, useRef, useCallback, useMemo, useContext, useImperativeHandle } from 'react';
import {
@@ -33,7 +34,7 @@ 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 type { NativeRendererColors, NativeRendererHandle } from './nativeTypes';
import { routeChart, type ChartRoute } from './route';
import ChartNotice from './chartNotice';
import { getColor, getTheme } from '../utils/useTheme';
@@ -268,7 +269,6 @@ function saveDataURL(url: string, filename: string) {
*/
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,
@@ -319,7 +319,7 @@ const RendererSwitch = forwardRef<IReactVegaHandler, RendererProps>(function (pr
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 planned = useMemo(() => routeChart(chart, worksheetRenderer), [chart]);
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,
@@ -403,9 +403,8 @@ const RendererSwitch = forwardRef<IReactVegaHandler, RendererProps>(function (pr
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;
+ // Empty charts are idle; unsupported or failed charts report an error and export no image.
+ const standing: IRenderStatus | undefined = route.to === 'notice' ? 'error' : route.to === 'blank' ? 'idle' : undefined;
useEffect(() => {
if (standing) onStatusChange(standing);
}, [standing, onStatusChange, chartName]);
@@ -433,7 +432,7 @@ const RendererSwitch = forwardRef<IReactVegaHandler, RendererProps>(function (pr
</div>
);
}
- const Native = registry.renderer!.component;
+ const Native = worksheetRenderer.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.
diff --git a/packages/graphic-walker/src/renderer/native/index.tsx b/packages/graphic-walker/src/renderer/native/index.tsx
index 86bdd87e..c27f24a0 100644
--- a/packages/graphic-walker/src/renderer/native/index.tsx
+++ b/packages/graphic-walker/src/renderer/native/index.tsx
@@ -1,7 +1,7 @@
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 type { NativeRendererProps, NativeUnsupported } from '../nativeTypes';
import { toWorkflow } from '../../utils/workflow';
import { chartToWorksheet } from './adapter';
import { composeWorkflow, drawnAtGrain, splitWorkflow, type Around } from './having';
@@ -161,4 +161,3 @@ function check(chart: IChart): NativeUnsupported | undefined {
}
}
export const worksheetRenderer = { component: NativeWorksheet, check };
-registerNativeRenderer(worksheetRenderer);
diff --git a/packages/graphic-walker/src/renderer/nativeHostExport.test.ts b/packages/graphic-walker/src/renderer/nativeHostExport.test.ts
index afd4f0b2..17f09e46 100644
--- a/packages/graphic-walker/src/renderer/nativeHostExport.test.ts
+++ b/packages/graphic-walker/src/renderer/nativeHostExport.test.ts
@@ -1,6 +1,6 @@
import type { IGWHandlerInsider, IRenderStatus } from '../interfaces';
import { installNativeExport } from './nativeHostExport';
-import type { NativeRendererHandle } from './nativeRegistry';
+import type { NativeRendererHandle } from './nativeTypes';
function host(initial: IRenderStatus = 'idle') {
let status = initial;
diff --git a/packages/graphic-walker/src/renderer/nativeHostExport.ts b/packages/graphic-walker/src/renderer/nativeHostExport.ts
index 10fe4e55..4b75dd53 100644
--- a/packages/graphic-walker/src/renderer/nativeHostExport.ts
+++ b/packages/graphic-walker/src/renderer/nativeHostExport.ts
@@ -1,6 +1,6 @@
import type { RefObject } from 'react';
import type { IChartExportResult, IGWHandlerInsider } from '../interfaces';
-import type { NativeRendererHandle } from './nativeRegistry';
+import type { NativeRendererHandle } from './nativeTypes';
const empty = (mode: IChartExportResult['mode']): IChartExportResult => ({ mode, title: '', nCols: 0, nRows: 0, charts: [], chartType: 'worksheet', container: () => null });
diff --git a/packages/graphic-walker/src/renderer/nativeRegistry.test.ts b/packages/graphic-walker/src/renderer/nativeRegistry.test.ts
deleted file mode 100644
index 7d17f9f5..00000000
--- a/packages/graphic-walker/src/renderer/nativeRegistry.test.ts
+++ /dev/null
@@ -1,40 +0,0 @@
-// 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/nativeTypes.ts
similarity index 71%
rename from packages/graphic-walker/src/renderer/nativeRegistry.ts
rename to packages/graphic-walker/src/renderer/nativeTypes.ts
index 7cb882fa..0c18459e 100644
--- a/packages/graphic-walker/src/renderer/nativeRegistry.ts
+++ b/packages/graphic-walker/src/renderer/nativeTypes.ts
@@ -1,4 +1,4 @@
-import { useSyncExternalStore, type ComponentType, type Ref } from 'react';
+import type { ComponentType, Ref } from 'react';
import type { IChart, IComputationFunction, IRenderStatus, IViewField } from '../interfaces';
/**
@@ -108,47 +108,3 @@ export interface NativeRenderer {
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/route.test.ts b/packages/graphic-walker/src/renderer/route.test.ts
index 76efce06..7ac19891 100644
--- a/packages/graphic-walker/src/renderer/route.test.ts
+++ b/packages/graphic-walker/src/renderer/route.test.ts
@@ -1,6 +1,6 @@
import type { IChart, IViewField } from '../interfaces';
import { emptyEncodings, emptyVisualConfig, emptyVisualLayout } from '../utils/save';
-import type { NativeRegistry, NativeRenderer, NativeUnsupported } from './nativeRegistry';
+import type { NativeRenderer, NativeUnsupported } from './nativeTypes';
import { routeChart } from './route';
const dim = (fid: string): IViewField => ({ fid, name: fid, semanticType: 'nominal', analyticType: 'dimension' });
@@ -9,62 +9,54 @@ 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. */
+/** A worksheet capability check whose calls can be inspected. */
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 };
+ return { renderer, asked };
}
-const absent: NativeRegistry = { loading: false };
+const worksheet = registered().renderer;
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', () => {
+ test('a map goes to the map component under every renderer setting, without consulting the worksheet', () => {
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' });
- }
+ expect(routeChart(chart(renderer, {}, { coordSystem: 'geographic', geoms: ['poi'] }), refusing.renderer)).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' });
+ expect(routeChart(chart(renderer, threeLevels, { geoms: ['table'] }), worksheet)).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' });
+ const { renderer: worksheet, asked } = registered();
+ expect(routeChart(chart(undefined), worksheet)).toEqual({ to: 'native' });
+ expect(routeChart(chart('vega-lite'), worksheet)).toEqual({ to: 'classic' });
+ expect(routeChart(chart('observable-plot'), worksheet)).toEqual({ to: 'classic' });
expect(asked).toHaveLength(1);
- expect(routeChart(chart('native'), registry)).toEqual({ to: 'native' });
+ expect(routeChart(chart('native'), worksheet)).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);
+ const route = routeChart(chart('native'), registered({ reason: 'Bar marks need one measure axis.' }).renderer);
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');
+ expect(routeChart(chart('native'), registered({ reason: 'There is nothing to draw yet.', empty: true }).renderer)).toEqual({ to: 'blank' });
});
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({
+ expect(routeChart(chart(renderer, threeLevels), worksheet)).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);
+ const both = routeChart(chart('vega-lite', { ...threeLevels, columns: [dim('Year'), dim('Quarter'), dim('Month'), mea('Sales')] }), worksheet);
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' });
+ expect(routeChart(chart('vega-lite', { rows: [dim('Region'), dim('Category'), mea('Profit'), mea('Cost')] }), worksheet)).toEqual({ to: 'classic' });
});
});
diff --git a/packages/graphic-walker/src/renderer/route.ts b/packages/graphic-walker/src/renderer/route.ts
index 57b0a636..f9c690a9 100644
--- a/packages/graphic-walker/src/renderer/route.ts
+++ b/packages/graphic-walker/src/renderer/route.ts
@@ -1,6 +1,6 @@
import type { IChart } from '../interfaces';
import { CLASSIC_CROSS_LIMIT } from '../lib/gog';
-import type { NativeRegistry } from './nativeRegistry';
+import type { NativeRenderer } from './nativeTypes';
/** A shelf that holds more dimensions than the chart's renderer shows. */
export interface ShelfOverflow {
@@ -10,14 +10,11 @@ export interface ShelfOverflow {
/**
* 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[] };
@@ -37,13 +34,12 @@ export type ChartRoute = { to: 'dedicated'; kind: 'table' | 'map' } | { to: 'cla
* 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 {
+export function routeChart(chart: IChart, worksheet: NativeRenderer): 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);
+ const cannot = worksheet.check(chart);
if (!cannot) return { to: 'native' };
return cannot.empty ? { to: 'blank' } : { to: 'notice', notice: { state: 'unsupported', reason: cannot.reason } };
}
diff --git a/packages/graphic-walker/src/renderer/specRenderer.tsx b/packages/graphic-walker/src/renderer/specRenderer.tsx
index ae2643e2..9f6891e4 100644
--- a/packages/graphic-walker/src/renderer/specRenderer.tsx
+++ b/packages/graphic-walker/src/renderer/specRenderer.tsx
@@ -218,7 +218,7 @@ const SpecRenderer = forwardRef<IReactVegaHandler, SpecRendererProps>(function (
/>
)}
{/* 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' }} />}
+ {nativeMissing && <ChartNotice notice={{ state: 'failed', reason: '' }} />}
{!isSpatial && layout.renderer !== 'observable-plot' && layout.renderer !== 'native' && (
<ReactVega
name={name}
diff --git a/packages/graphic-walker/tests/e2e/native-renderer.fixture.tsx b/packages/graphic-walker/tests/e2e/native-renderer.fixture.tsx
index 017d7fca..5fc56c1b 100644
--- a/packages/graphic-walker/tests/e2e/native-renderer.fixture.tsx
+++ b/packages/graphic-walker/tests/e2e/native-renderer.fixture.tsx
@@ -1,23 +1,13 @@
import React from 'react';
import { createRoot } from 'react-dom/client';
-import PureRenderer from '../../src/renderer/pureRenderer';
+// Use the published entry point, without manually importing or registering a renderer.
+import { GraphicWalker, PureRenderer, getComputation } from '@kanaries/graphic-walker';
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
- */
+/** Production-package editor with a controlled data source. */
export interface ChartRequest {
name: string;
renderer?: IChart['layout']['renderer'];
@@ -33,8 +23,6 @@ export interface RendererFixture {
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[];
@@ -91,14 +79,6 @@ function chartOf(request: ChartRequest, index: number): IChart {
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;
@@ -126,7 +106,6 @@ window.gw = {
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: {
@@ -151,7 +130,7 @@ const pureChart = chartOf({ name: 'Default worksheet', rows: ['Region', 'Categor
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%' }} />
+ pure ? <PureRenderer ref={pureRef} rawData={data} visualState={pureChart.encodings} visualConfig={pureChart.config} /> : <GraphicWalker ref={hostRef} storeRef={storeRef} fields={params.has('empty') ? [] : [...dimensions, ...measures]} computation={computation} appearance="light" style={{ width: '100%', height: '100%' }} />
);
function ready() {
diff --git a/packages/graphic-walker/tests/e2e/renderer-routing.spec.ts b/packages/graphic-walker/tests/e2e/renderer-routing.spec.ts
index a6506c55..c504d7d6 100644
--- a/packages/graphic-walker/tests/e2e/renderer-routing.spec.ts
+++ b/packages/graphic-walker/tests/e2e/renderer-routing.spec.ts
@@ -4,14 +4,13 @@ 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}`);
+async function open(page: Page, charts: ChartRequest[]) {
+ await page.goto('/tests/e2e/native-renderer.html');
await expect(page.locator('body')).toHaveAttribute('data-fixture-ready', 'true');
await page.evaluate((list) => window.gw.load(list), charts);
}
@@ -39,7 +38,7 @@ async function nothingDrawn(page: Page) {
}
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 open(page, [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);
@@ -57,7 +56,7 @@ test('R1: a chart the worksheet renderer cannot draw says why and is not drawn b
});
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 open(page, [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());
@@ -99,38 +98,8 @@ test('R2: a failed query shows the error, no other renderer takes over, and tryi
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 open(page, [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.
@@ -167,26 +136,24 @@ test('R4: only the user changes the renderer, and a renderer that cannot show ev
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('M1: a map is drawn by the map component under every renderer setting', async ({ page }) => {
+ await open(page, 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 open(page, [bars]);
await expect(sheet(page)).toBeVisible();
await page.evaluate(() => window.gw.setMap(true));
await expect(map(page)).toBeVisible();
@@ -208,7 +175,7 @@ test('M2: an ordinary chart turned into a map and back keeps its renderer', asyn
});
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 open(page, [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]);
@@ -258,3 +225,24 @@ test('release default: PureRenderer renders and exports a worksheet without a re
}).toContain('<svg');
await expect(vega(page)).toHaveCount(0);
});
+
+
+test('an empty app and cleared shelves stay blank and idle in the production package', async ({ page }) => {
+ await page.goto('/tests/e2e/native-renderer.html?empty=1');
+ await expect(page.locator('body')).toHaveAttribute('data-fixture-ready', 'true');
+ await expect(notice(page)).toHaveCount(0);
+ await expect(sheet(page)).toHaveCount(0);
+ await expect.poll(() => status(page)).toBe('idle');
+ expect(await page.evaluate(() => window.gw.host.exportChart())).toMatchObject({ images: 0 });
+ await page.evaluate((chart) => window.gw.load([chart]), bars);
+ await expect(sheet(page)).toBeVisible();
+ await expect.poll(() => status(page)).toBe('idle');
+ const drawn = await page.evaluate(() => window.gw.host.exportChart());
+ expect(drawn).toMatchObject({ chartType: 'worksheet', images: 1 });
+ expect(drawn.data).toContain('<svg');
+ await page.evaluate(() => window.gw.load([{ name: 'Cleared' }]));
+ await expect(notice(page)).toHaveCount(0);
+ await expect(sheet(page)).toHaveCount(0);
+ await expect.poll(() => status(page)).toBe('idle');
+ expect(await page.evaluate(() => window.gw.host.exportChart())).toMatchObject({ images: 0, data: '' });
+});