Skip to content

An open source alternative to Tableau. Embeddable visual analytic

[Feat] gw ref update (#108)

Bob0f61ac2fdadd
diff --git a/packages/graphic-walker/src/components/appRoot.tsx b/packages/graphic-walker/src/components/appRoot.tsx
index cc926b6e..14e69321 100644
--- a/packages/graphic-walker/src/components/appRoot.tsx
+++ b/packages/graphic-walker/src/components/appRoot.tsx
@@ -1,24 +1,72 @@
-import React, { createContext, forwardRef, useImperativeHandle, type ForwardedRef, useContext } from "react";
-import type { IGWHandler } from "../interfaces";
+import React, { createContext, forwardRef, useImperativeHandle, type ForwardedRef, useContext, type ComponentType, type RefObject } from "react";
+import type { IChartExportResult, IGWHandler, IGWHandlerInsider, IRenderStatus } from "../interfaces";
-const AppRootContext = createContext<ForwardedRef<IGWHandler>>(null!);
+const AppRootContext = createContext<ForwardedRef<IGWHandlerInsider>>(null);
-export const useAppRootContext = () => {
- return useContext(AppRootContext);
+export const useAppRootContext = (): RefObject<IGWHandlerInsider> => {
+ const context = useContext(AppRootContext);
+ if (context && 'current' in context) {
+ return context;
+ }
+ return {
+ current: null,
+ };
};
-const AppRoot = forwardRef<IGWHandler, { children: any }>(({ children }, ref) => {
+const AppRoot = forwardRef<IGWHandlerInsider, { children: any }>(({ children }, ref) => {
useImperativeHandle(ref, () => {
+ let renderStatus: IRenderStatus = 'idle';
+ let onRenderStatusChangeHandlers: ((status: IRenderStatus) => void)[] = [];
+ const addRenderStatusChangeListener = (cb: typeof onRenderStatusChangeHandlers[number]): (() => void) => {
+ onRenderStatusChangeHandlers.push(cb);
+ const dispose = () => {
+ onRenderStatusChangeHandlers = onRenderStatusChangeHandlers.filter(which => which !== cb);
+ };
+ return dispose;
+ };
+ const updateRenderStatus = (status: IRenderStatus) => {
+ if (renderStatus === status) {
+ return;
+ }
+ renderStatus = status;
+ onRenderStatusChangeHandlers.forEach(cb => cb(renderStatus));
+ };
return {
- exportChart: (async mode => {
+ get renderStatus() {
+ return renderStatus;
+ },
+ onRenderStatusChange: addRenderStatusChangeListener,
+ updateRenderStatus,
+ chartCount: 1,
+ chartIndex: 0,
+ openChart() {},
+ exportChart: (async (mode: IChartExportResult['mode'] = 'svg') => {
return {
mode,
title: '',
nCols: 0,
nRows: 0,
charts: [],
+ container: () => null,
};
}) as IGWHandler['exportChart'],
+ exportChartList: (async function * exportChartList (mode: IChartExportResult['mode'] = 'svg') {
+ yield {
+ mode,
+ total: 1,
+ completed: 0,
+ index: 0,
+ data: {
+ mode,
+ title: '',
+ nCols: 0,
+ nRows: 0,
+ charts: [],
+ container: () => null,
+ },
+ hasNext: false,
+ };
+ }) as IGWHandler['exportChartList'],
};
}, []);
@@ -29,4 +77,14 @@ const AppRoot = forwardRef<IGWHandler, { children: any }>(({ children }, ref) =>
);
});
+export const withAppRoot = <P extends object>(Component: ComponentType<any>) => {
+ return (props: P) => {
+ return (
+ <AppRoot>
+ <Component {...props} />
+ </AppRoot>
+ );
+ };
+};
+
export default AppRoot;
diff --git a/packages/graphic-walker/src/index.tsx b/packages/graphic-walker/src/index.tsx
index aa8ea603..ebf472af 100644
--- a/packages/graphic-walker/src/index.tsx
+++ b/packages/graphic-walker/src/index.tsx
@@ -1,4 +1,4 @@
-import React, { forwardRef } from "react";
+import React, { type ForwardedRef, forwardRef } from "react";
import { DOM } from "@kanaries/react-beautiful-dnd";
import { observer } from "mobx-react-lite";
import App, { IGWProps } from "./App";
@@ -6,7 +6,7 @@ import { StoreWrapper } from "./store/index";
import { FieldsContextWrapper } from "./fields/fieldsContext";
import { ShadowDom } from "./shadow-dom";
import AppRoot from "./components/appRoot";
-import type { IGWHandler } from "./interfaces";
+import type { IGWHandler, IGWHandlerInsider } from "./interfaces";
import "./empty_sheet.css";
@@ -24,7 +24,7 @@ export const GraphicWalker = observer(forwardRef<IGWHandler, IGWProps>((props, r
return (
<StoreWrapper keepAlive={props.keepAlive} storeRef={storeRef}>
- <AppRoot ref={ref}>
+ <AppRoot ref={ref as ForwardedRef<IGWHandlerInsider>}>
<ShadowDom onMount={handleMount} onUnmount={handleUnmount}>
<FieldsContextWrapper>
<App {...props} />
diff --git a/packages/graphic-walker/src/interfaces.ts b/packages/graphic-walker/src/interfaces.ts
index c3824275..466a6712 100644
--- a/packages/graphic-walker/src/interfaces.ts
+++ b/packages/graphic-walker/src/interfaces.ts
@@ -1,4 +1,4 @@
-import {Config as VgConfig} from 'vega';
+import {Config as VgConfig, View} from 'vega';
import {Config as VlConfig} from 'vega-lite';
export type DeepReadonly<T extends Record<keyof any, any>> = {
@@ -225,6 +225,17 @@ export type IDarkMode = 'media' | 'light' | 'dark';
export type VegaGlobalConfig = VgConfig | VlConfig;
+export interface IVegaChartRef {
+ x: number;
+ y: number;
+ w: number;
+ h: number;
+ innerWidth: number;
+ innerHeight: number;
+ view: View;
+ canvas: HTMLCanvasElement | null;
+}
+
export interface IChartExportResult<T extends 'svg' | 'data-url' = 'svg' | 'data-url'> {
mode: T;
title: string;
@@ -235,8 +246,12 @@ export interface IChartExportResult<T extends 'svg' | 'data-url' = 'svg' | 'data
rowIndex: number;
width: number;
height: number;
+ canvasWidth: number;
+ canvasHeight: number;
data: string;
+ canvas(): HTMLCanvasElement | null;
}[];
+ container(): HTMLDivElement | null;
}
interface IExportChart {
@@ -244,6 +259,73 @@ interface IExportChart {
<T extends IChartExportResult['mode']>(mode: T): Promise<IChartExportResult<T>>;
}
+export interface IChartListExportResult<T extends 'svg' | 'data-url' = 'svg' | 'data-url'> {
+ mode: T;
+ total: number;
+ index: number;
+ data: IChartExportResult<T>;
+ hasNext: boolean;
+}
+
+interface IExportChartList {
+ <T extends Extract<IChartExportResult['mode'], 'svg'>>(mode?: T): AsyncGenerator<IChartListExportResult<T>, void, unknown>;
+ <T extends IChartExportResult['mode']>(mode: T): AsyncGenerator<IChartListExportResult<T>, void, unknown>;
+}
+
+/**
+ * The status of the current chart.
+ * * `computing`: _GraphicWalker_ is computing the data view.
+ * * `rendering`: _GraphicWalker_ is rendering the chart.
+ * * `idle`: rendering is finished.
+ * * `error`: an error occurs during the process above.
+ */
+export type IRenderStatus = 'computing' | 'rendering' | 'idle' | 'error';
+
export interface IGWHandler {
+ /** length of the "chart" tab list */
+ chartCount: number;
+ /** current selected chart index */
+ chartIndex: number;
+ /** Switches to the specified chart */
+ openChart: (index: number) => void;
+ /**
+ * Returns the status of the current chart.
+ *
+ * It is computed by the following rules:
+ * - If _GraphicWalker_ is computing the data view, it returns `computing`.
+ * - If _GraphicWalker_ is rendering the chart, it returns `rendering`.
+ * - If rendering is finished, it returns `idle`.
+ * - If an error occurs during the process above, it returns `error`.
+ */
+ get renderStatus(): IRenderStatus;
+ /**
+ * Registers a callback function to listen to the status change of the current chart.
+ *
+ * @param {(renderStatus: IRenderStatus) => void} cb - the callback function
+ * @returns {() => void} a dispose function to remove this callback
+ */
+ onRenderStatusChange: (cb: (renderStatus: IRenderStatus) => void) => (() => void);
+ /**
+ * Exports the current chart.
+ *
+ * @param {IChartExportResult['mode']} [mode='svg'] - the export mode, either `svg` or `data-url`
+ */
exportChart: IExportChart;
+ /**
+ * Exports all charts.
+ *
+ * @param {IChartExportResult['mode']} [mode='svg'] - the export mode, either `svg` or `data-url`
+ * @returns {AsyncGenerator<IChartListExportResult, void, unknown>} an async generator to iterate over all charts
+ * @example
+ * ```ts
+ * for await (const chart of gwRef.current.exportChartList()) {
+ * console.log(chart);
+ * }
+ * ```
+ */
+ exportChartList: IExportChartList;
+}
+
+export interface IGWHandlerInsider extends IGWHandler {
+ updateRenderStatus: (renderStatus: IRenderStatus) => void;
}
diff --git a/packages/graphic-walker/src/renderer/hooks.ts b/packages/graphic-walker/src/renderer/hooks.ts
index de632c63..6aa2fd50 100644
--- a/packages/graphic-walker/src/renderer/hooks.ts
+++ b/packages/graphic-walker/src/renderer/hooks.ts
@@ -3,6 +3,7 @@ import { unstable_batchedUpdates } from 'react-dom';
import type { DeepReadonly, IFilterField, IRow, IViewField } from '../interfaces';
import { applyFilter, applyViewQuery, transformDataService } from '../services';
import { getMeaAggKey } from '../utils';
+import { useAppRootContext } from '../components/appRoot';
interface UseRendererProps {
@@ -26,8 +27,11 @@ export const useRenderer = (props: UseRendererProps): UseRendererResult => {
const [viewData, setViewData] = useState<IRow[]>([]);
+ const appRef = useAppRootContext();
+
useEffect(() => {
const taskId = ++taskIdRef.current;
+ appRef.current?.updateRenderStatus('computing');
setComputing(true);
applyFilter(data, filters)
.then((data) => {
@@ -53,6 +57,7 @@ export const useRenderer = (props: UseRendererProps): UseRendererResult => {
if (taskId !== taskIdRef.current) {
return;
}
+ appRef.current?.updateRenderStatus('rendering');
unstable_batchedUpdates(() => {
setComputing(false);
setViewData(data);
@@ -61,6 +66,7 @@ export const useRenderer = (props: UseRendererProps): UseRendererResult => {
if (taskId !== taskIdRef.current) {
return;
}
+ appRef.current?.updateRenderStatus('error');
console.error(err);
unstable_batchedUpdates(() => {
setComputing(false);
diff --git a/packages/graphic-walker/src/renderer/index.tsx b/packages/graphic-walker/src/renderer/index.tsx
index 9e987f43..ecce1250 100644
--- a/packages/graphic-walker/src/renderer/index.tsx
+++ b/packages/graphic-walker/src/renderer/index.tsx
@@ -8,6 +8,7 @@ import { IReactVegaHandler } from '../vis/react-vega';
import { unstable_batchedUpdates } from 'react-dom';
import { useRenderer } from './hooks';
import { initEncoding, initVisualConfig } from '../store/visualSpecStore';
+import { useChartIndexControl } from '../utils/chartIndexControl';
interface RendererProps {
themeKey?: IThemeKey;
@@ -60,6 +61,12 @@ const Renderer = forwardRef<IReactVegaHandler, RendererProps>(function (props, r
}
}, [waiting, vizStore]);
+ useChartIndexControl({
+ count: visList.length,
+ index: visIndex,
+ onChange: idx => vizStore.selectVisualization(idx),
+ });
+
const handleGeomClick = useCallback(
(values: any, e: any) => {
e.stopPropagation();
diff --git a/packages/graphic-walker/src/renderer/pureRenderer.tsx b/packages/graphic-walker/src/renderer/pureRenderer.tsx
index 9da59dc1..1dc5d574 100644
--- a/packages/graphic-walker/src/renderer/pureRenderer.tsx
+++ b/packages/graphic-walker/src/renderer/pureRenderer.tsx
@@ -3,7 +3,7 @@ import { unstable_batchedUpdates } from 'react-dom';
import { toJS } from 'mobx';
import { observer } from 'mobx-react-lite';
import { ShadowDom } from '../shadow-dom';
-import AppRoot from '../components/appRoot';
+import { withAppRoot } from '../components/appRoot';
import type { IDarkMode, IViewField, IRow, IThemeKey, DraggableFieldState, IVisualConfig } from '../interfaces';
import type { IReactVegaHandler } from '../vis/react-vega';
import SpecRenderer from './specRenderer';
@@ -79,23 +79,21 @@ const PureRenderer = forwardRef<IReactVegaHandler, IPureRendererProps>(function
}, [waiting]);
return (
- <AppRoot>
- <ShadowDom>
- <div className="relative">
- <SpecRenderer
- name={name}
- loading={waiting}
- data={viewData}
- ref={ref}
- themeKey={themeKey}
- dark={dark}
- draggableFieldState={visualState}
- visualConfig={visualConfig}
- />
- </div>
- </ShadowDom>
- </AppRoot>
+ <ShadowDom>
+ <div className="relative">
+ <SpecRenderer
+ name={name}
+ loading={waiting}
+ data={viewData}
+ ref={ref}
+ themeKey={themeKey}
+ dark={dark}
+ draggableFieldState={visualState}
+ visualConfig={visualConfig}
+ />
+ </div>
+ </ShadowDom>
);
});
-export default observer(PureRenderer);
+export default observer(withAppRoot(PureRenderer));
diff --git a/packages/graphic-walker/src/utils/chartIndexControl.ts b/packages/graphic-walker/src/utils/chartIndexControl.ts
new file mode 100644
index 00000000..6d7b04b3
--- /dev/null
+++ b/packages/graphic-walker/src/utils/chartIndexControl.ts
@@ -0,0 +1,39 @@
+import { useEffect } from "react";
+import { useAppRootContext } from "../components/appRoot";
+
+
+interface IUseChartIndexControlOptions {
+ count: number;
+ index: number;
+ onChange: (index: number) => void;
+}
+
+export const useChartIndexControl = (options: IUseChartIndexControlOptions): void => {
+ const appRef = useAppRootContext();
+
+ useEffect(() => {
+ if (appRef.current) {
+ appRef.current.chartCount = options.count;
+ appRef.current.chartIndex = options.index;
+ appRef.current.openChart = function (index: number) {
+ if (index === this.chartIndex) {
+ return;
+ } else if (Number.isInteger(index) && index >= 0 && index < this.chartCount) {
+ options.onChange(index);
+ } else {
+ console.warn(`Invalid chart index: ${index}`);
+ }
+ };
+ }
+ });
+
+ useEffect(() => {
+ return () => {
+ if (appRef.current) {
+ appRef.current.chartCount = 1;
+ appRef.current.chartIndex = 0;
+ appRef.current.openChart = () => {};
+ }
+ };
+ }, []);
+};
diff --git a/packages/graphic-walker/src/utils/vegaApiExport.ts b/packages/graphic-walker/src/utils/vegaApiExport.ts
index 0f3b4ec7..3b9a6fa4 100644
--- a/packages/graphic-walker/src/utils/vegaApiExport.ts
+++ b/packages/graphic-walker/src/utils/vegaApiExport.ts
@@ -1,11 +1,16 @@
-import { useImperativeHandle, type ForwardedRef, type MutableRefObject, useEffect } from "react";
-import type { View } from "vega";
+import { useImperativeHandle, type ForwardedRef, type MutableRefObject, useEffect, RefObject } from "react";
import { useAppRootContext } from "../components/appRoot";
import type { IReactVegaHandler } from "../vis/react-vega";
-import type { IChartExportResult } from "../interfaces";
+import type { IChartExportResult, IVegaChartRef } from "../interfaces";
-export const useVegaExportApi = (name: string | undefined, viewsRef: MutableRefObject<{ x: number; y: number; w: number; h: number; view: View }[]>, ref: ForwardedRef<IReactVegaHandler>) => {
+export const useVegaExportApi = (
+ name: string | undefined,
+ viewsRef: MutableRefObject<IVegaChartRef[]>,
+ ref: ForwardedRef<IReactVegaHandler>,
+ renderTaskRefs: MutableRefObject<Promise<unknown>[]>,
+ containerRef: RefObject<HTMLDivElement>,
+) => {
const renderHandle = {
getSVGData() {
return Promise.all(viewsRef.current.map(item => item.view.toSVG()));
@@ -47,12 +52,73 @@ export const useVegaExportApi = (name: string | undefined, viewsRef: MutableRefO
};
useImperativeHandle(ref, () => renderHandle);
-
+
const appRef = useAppRootContext();
useEffect(() => {
- if (appRef && 'current' in appRef && appRef.current) {
- appRef.current.exportChart = (async (mode: IChartExportResult['mode'] = 'svg') => {
+ const ctx = appRef.current;
+ if (ctx) {
+ Promise.all(renderTaskRefs.current).then(() => {
+ if (appRef.current) {
+ const appCtx = appRef.current;
+ if (appCtx.renderStatus !== 'rendering') {
+ return;
+ }
+ // add a short delay to wait for the canvas to be ready
+ setTimeout(() => {
+ if (appCtx.renderStatus !== 'rendering') {
+ return;
+ }
+ appCtx.updateRenderStatus('idle');
+ }, 0);
+ }
+ }).catch(() => {
+ if (appRef.current) {
+ if (appRef.current.renderStatus !== 'rendering') {
+ return;
+ }
+ appRef.current.updateRenderStatus('error');
+ }
+ });
+ ctx.exportChart = (async (mode: IChartExportResult['mode'] = 'svg') => {
+ if (ctx.renderStatus === 'error') {
+ console.error('exportChart failed because error occurred when rendering chart.');
+ return {
+ mode,
+ title: '',
+ nCols: 0,
+ nRows: 0,
+ charts: [],
+ };
+ }
+ if (ctx.renderStatus !== 'idle') {
+ let dispose = null as (() => void) | null;
+ // try to wait for a while
+ const waitForChartReady = new Promise<void>((resolve, reject) => {
+ dispose = ctx.onRenderStatusChange(status => {
+ if (status === 'error') {
+ reject(new Error('Error occurred when rendering chart'));
+ } else if (status === 'idle') {
+ resolve();
+ }
+ });
+ setTimeout(() => reject(new Error('Timeout')), 10_000);
+ });
+ try {
+ await waitForChartReady;
+ } catch (error) {
+ console.error('exportChart failed:', `${error}`);
+ return {
+ mode,
+ title: '',
+ nCols: 0,
+ nRows: 0,
+ charts: [],
+ };
+ } finally {
+ dispose?.();
+ }
+ }
const res: IChartExportResult = {
mode,
title: name || 'untitled',
@@ -63,8 +129,16 @@ export const useVegaExportApi = (name: string | undefined, viewsRef: MutableRefO
colIndex: item.x,
width: item.w,
height: item.h,
+ canvasWidth: item.innerWidth,
+ canvasHeight: item.innerHeight,
data: '',
+ canvas() {
+ return item.canvas;
+ },
})),
+ container() {
+ return containerRef.current;
+ },
};
if (mode === 'data-url') {
const imgData = await renderHandle.getCanvasData();
@@ -82,20 +156,63 @@ export const useVegaExportApi = (name: string | undefined, viewsRef: MutableRefO
}
}
return res;
- }) as typeof appRef.current.exportChart;
+ }) as typeof ctx.exportChart;
+ ctx.exportChartList = async function * exportChartList (mode: IChartExportResult['mode'] = 'svg') {
+ const total = ctx.chartCount;
+ const indices = new Array(total).fill(0).map((_, i) => i);
+ const currentIdx = ctx.chartIndex;
+ for await (const index of indices) {
+ ctx.openChart(index);
+ // wait for a while to make sure the correct chart is rendered
+ await new Promise<void>(resolve => setTimeout(resolve, 0));
+ const chart = await ctx.exportChart(mode);
+ yield {
+ mode,
+ total,
+ index,
+ data: chart,
+ hasNext: index < total - 1,
+ };
+ }
+ ctx.openChart(currentIdx);
+ };
}
});
useEffect(() => {
+ // NOTE: this is totally a cleanup function
return () => {
- if (appRef && 'current' in appRef && appRef.current) {
- appRef.current.exportChart = async mode => ({
+ if (appRef.current) {
+ appRef.current.updateRenderStatus('idle');
+ appRef.current.exportChart = async (mode: IChartExportResult['mode'] = 'svg') => ({
mode,
title: '',
nCols: 0,
nRows: 0,
charts: [],
+ container() {
+ return null;
+ },
});
+ appRef.current.exportChartList = async function * exportChartList (mode: IChartExportResult['mode'] = 'svg') {
+ yield {
+ mode,
+ total: 1,
+ completed: 0,
+ index: 0,
+ data: {
+ mode,
+ title: '',
+ nCols: 0,
+ nRows: 0,
+ charts: [],
+ container() {
+ return null;
+ },
+ },
+ hasNext: false,
+ };
+ };
}
};
}, []);
diff --git a/packages/graphic-walker/src/vis/react-vega.tsx b/packages/graphic-walker/src/vis/react-vega.tsx
index da4833ff..ad5bef88 100644
--- a/packages/graphic-walker/src/vis/react-vega.tsx
+++ b/packages/graphic-walker/src/vis/react-vega.tsx
@@ -2,11 +2,11 @@ import React, { useEffect, useState, useMemo, forwardRef, useRef } from 'react';
import embed from 'vega-embed';
import { Subject, Subscription } from 'rxjs'
import * as op from 'rxjs/operators';
-import type { ScenegraphEvent, View } from 'vega';
+import type { ScenegraphEvent } from 'vega';
import styled from 'styled-components';
import { useVegaExportApi } from '../utils/vegaApiExport';
-import { IViewField, IRow, IStackMode, VegaGlobalConfig } from '../interfaces';
+import { IViewField, IRow, IStackMode, VegaGlobalConfig, IVegaChartRef } from '../interfaces';
import { useTranslation } from 'react-i18next';
import { getVegaTimeFormatRules } from './temporalFormat';
import { getSingleView } from './spec/view';
@@ -153,10 +153,12 @@ const ReactVega = forwardRef<IReactVegaHandler, ReactVegaProps>(function ReactVe
})
}, [rowRepeatFields, colRepeatFields])
- const vegaRefs = useRef<{ x: number; y: number; w: number; h: number; view: View }[]>([]);
+ const vegaRefs = useRef<IVegaChartRef[]>([]);
+ const renderTaskRefs = useRef<Promise<unknown>[]>([]);
useEffect(() => {
vegaRefs.current = [];
+ renderTaskRefs.current = [];
const yField = rows.length > 0 ? rows[rows.length - 1] : NULL_FIELD;
const xField = columns.length > 0 ? columns[columns.length - 1] : NULL_FIELD;
@@ -220,13 +222,18 @@ const ReactVega = forwardRef<IReactVegaHandler, ReactVegaProps>(function ReactVe
}
if (viewPlaceholders.length > 0 && viewPlaceholders[0].current) {
- embed(viewPlaceholders[0].current, spec, { mode: 'vega-lite', actions: showActions, timeFormatLocale: getVegaTimeFormatRules(i18n.language), config: vegaConfig }).then(res => {
+ const task = embed(viewPlaceholders[0].current, spec, { mode: 'vega-lite', actions: showActions, timeFormatLocale: getVegaTimeFormatRules(i18n.language), config: vegaConfig }).then(res => {
+ const container = res.view.container();
+ const canvas = container?.querySelector('canvas') ?? null;
vegaRefs.current = [{
- w: res.view.container()?.clientWidth ?? res.view.width(),
- h: res.view.container()?.clientHeight ?? res.view.height(),
+ w: container?.clientWidth ?? res.view.width(),
+ h: container?.clientHeight ?? res.view.height(),
+ innerWidth: canvas?.clientWidth ?? res.view.width(),
+ innerHeight: canvas?.clientHeight ?? res.view.height(),
x: 0,
y: 0,
view: res.view,
+ canvas,
}];
try {
res.view.addEventListener('click', (e) => {
@@ -239,6 +246,7 @@ const ReactVega = forwardRef<IReactVegaHandler, ReactVegaProps>(function ReactVe
console.warn(error)
}
});
+ renderTaskRefs.current = [task];
}
} else {
if (layoutMode === 'fixed') {
@@ -293,13 +301,18 @@ const ReactVega = forwardRef<IReactVegaHandler, ReactVegaProps>(function ReactVe
}
if (node) {
const id = index;
- embed(node, ans, { mode: 'vega-lite', actions: showActions, timeFormatLocale: getVegaTimeFormatRules(i18n.language), config: vegaConfig }).then(res => {
+ const task = embed(node, ans, { mode: 'vega-lite', actions: showActions, timeFormatLocale: getVegaTimeFormatRules(i18n.language), config: vegaConfig }).then(res => {
+ const container = res.view.container();
+ const canvas = container?.querySelector('canvas') ?? null;
vegaRefs.current[id] = {
- w: res.view.container()?.clientWidth ?? res.view.width(),
- h: res.view.container()?.clientHeight ?? res.view.height(),
+ w: container?.clientWidth ?? res.view.width(),
+ h: container?.clientHeight ?? res.view.height(),
+ innerWidth: canvas?.clientWidth ?? res.view.width(),
+ innerHeight: canvas?.clientHeight ?? res.view.height(),
x: j,
y: i,
view: res.view,
+ canvas,
};
const paramStores = (res.vgSpec.data?.map(d => d.name) ?? []).filter(
name => [BRUSH_SIGNAL_NAME, POINT_SIGNAL_NAME].map(p => `${p}_store`).includes(name)
@@ -356,6 +369,7 @@ const ReactVega = forwardRef<IReactVegaHandler, ReactVegaProps>(function ReactVe
console.warn(error);
}
})
+ renderTaskRefs.current.push(task);
}
}
}
@@ -363,6 +377,10 @@ const ReactVega = forwardRef<IReactVegaHandler, ReactVegaProps>(function ReactVe
subscriptions.forEach(sub => sub.unsubscribe());
};
}
+ return () => {
+ vegaRefs.current = [];
+ renderTaskRefs.current = [];
+ };
}, [
dataSource,
allFieldIds,
@@ -391,9 +409,11 @@ const ReactVega = forwardRef<IReactVegaHandler, ReactVegaProps>(function ReactVe
text
]);
- useVegaExportApi(name, vegaRefs, ref);
+ const containerRef = useRef<HTMLDivElement>(null);
+
+ useVegaExportApi(name, vegaRefs, ref, renderTaskRefs, containerRef);
- return <CanvaContainer rowSize={Math.max(rowRepeatFields.length, 1)} colSize={Math.max(colRepeatFields.length, 1)}>
+ return <CanvaContainer rowSize={Math.max(rowRepeatFields.length, 1)} colSize={Math.max(colRepeatFields.length, 1)} ref={containerRef}>
{/* <div ref={container}></div> */}
{
viewPlaceholders.map((view, i) => <div key={i} ref={view}></div>)