Skip to content

An open source alternative to Tableau. Embeddable visual analytic

feat: add import and export vega-lite spec (#262)

islxyqwe6853067de7a7
diff --git a/packages/graphic-walker/src/App.tsx b/packages/graphic-walker/src/App.tsx
index 5ae860e1..57975219 100644
--- a/packages/graphic-walker/src/App.tsx
+++ b/packages/graphic-walker/src/App.tsx
@@ -34,6 +34,8 @@ import { parseErrorMessage } from './utils';
import { VizEmbedMenu } from './components/embedMenu';
import DataBoard from './components/dataBoard';
import SideReisze from './components/side-resize';
+import { VegaliteMapper } from './lib/vl2gw';
+import { newChart } from './models/visSpecHistory';
export type BaseVizProps = IAppI18nProps &
IVizProps &
@@ -57,6 +59,7 @@ export const VizApp = observer(function VizApp(props: BaseVizProps) {
geographicData,
computationTimeout = 60000,
spec,
+ vlSpec,
onError,
} = props;
@@ -89,6 +92,20 @@ export const VizApp = observer(function VizApp(props: BaseVizProps) {
}
}, [spec, vizStore]);
+ useEffect(() => {
+ if (vlSpec) {
+ const emptyChart = newChart(vizStore.meta, '');
+ vizStore.replaceNow(
+ VegaliteMapper(
+ spec,
+ [...emptyChart.encodings.dimensions, ...emptyChart.encodings.measures],
+ vizStore.currentVis.name ?? 'Chart 1',
+ vizStore.currentVis.visId
+ )
+ );
+ }
+ }, [vlSpec, vizStore]);
+
const rendererRef = useRef<IReactVegaHandler>(null);
const downloadCSVRef = useRef<{ download: () => void }>({ download() {} });
@@ -254,6 +271,7 @@ export function VizAppWithContext(props: IVizAppProps) {
geographicData={props.geographicData}
onError={props.onError}
spec={props.spec}
+ vlSpec={props.vlSpec}
themeConfig={props.themeConfig}
/>
</FieldsContextWrapper>
diff --git a/packages/graphic-walker/src/components/codeExport/index.tsx b/packages/graphic-walker/src/components/codeExport/index.tsx
index 0ee2ee94..d5a87008 100644
--- a/packages/graphic-walker/src/components/codeExport/index.tsx
+++ b/packages/graphic-walker/src/components/codeExport/index.tsx
@@ -1,69 +1,65 @@
-import React, { useEffect, useState } from "react";
-import Modal from "../modal";
-import { observer } from "mobx-react-lite";
-import { useVizStore } from "../../store";
-import DefaultButton from "../button/default";
-import PrimaryButton from "../button/primary";
-import { useTranslation } from "react-i18next";
-import DefaultTab, { ITabOption } from "../tabs/defaultTab";
+import React, { useEffect, useState } from 'react';
+import Modal from '../modal';
+import { observer } from 'mobx-react-lite';
+import { useVizStore } from '../../store';
+import DefaultButton from '../button/default';
+import PrimaryButton from '../button/primary';
+import { useTranslation } from 'react-i18next';
+import DefaultTab, { ITabOption } from '../tabs/defaultTab';
const syntaxHighlight = (json: any) => {
- if (typeof json != "string") {
+ if (typeof json != 'string') {
json = JSON.stringify(json, undefined, 4);
}
json = json
- .replace(/&/g, "&amp;")
- .replace(/</g, "&lt;")
- .replace(/>/g, "&gt;")
- .replace(/\n/g, "<br>")
- .replace(/\t/g, "&nbsp;&nbsp;&nbsp;&nbsp;")
- .replace(/\s/g, "&nbsp;");
- return json.replace(
- /("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g,
- function (match) {
- var cls = "text-sky-500"; // number
- if (/^"/.test(match)) {
- if (/:$/.test(match)) {
- cls = "text-purple-500"; // key
- } else {
- cls = "text-emerald-500"; // string
- }
- } else if (/true|false/.test(match)) {
- cls = "text-blue-500";
- } else if (/null/.test(match)) {
- cls = "text-sky-500";
+ .replace(/&/g, '&amp;')
+ .replace(/</g, '&lt;')
+ .replace(/>/g, '&gt;')
+ .replace(/\n/g, '<br>')
+ .replace(/\t/g, '&nbsp;&nbsp;&nbsp;&nbsp;')
+ .replace(/\s/g, '&nbsp;');
+ return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
+ var cls = 'text-sky-500'; // number
+ if (/^"/.test(match)) {
+ if (/:$/.test(match)) {
+ cls = 'text-purple-500'; // key
+ } else {
+ cls = 'text-emerald-500'; // string
}
- return '<span class="' + cls + '">' + match + "</span>";
+ } else if (/true|false/.test(match)) {
+ cls = 'text-blue-500';
+ } else if (/null/.test(match)) {
+ cls = 'text-sky-500';
}
- );
+ return '<span class="' + cls + '">' + match + '</span>';
+ });
};
const CodeExport: React.FC = observer((props) => {
const vizStore = useVizStore();
const { showCodeExportPanel } = vizStore;
const { t } = useTranslation();
- const [tabKey, setTabKey] = useState<string>("graphic-walker");
- const [code, setCode] = useState<any>("");
+ const [tabKey, setTabKey] = useState<string>('graphic-walker');
+ const [code, setCode] = useState<any>('');
const specTabs: ITabOption[] = [
{
- key: "graphic-walker",
- label: "Graphic-Walker",
+ key: 'graphic-walker',
+ label: 'Graphic-Walker',
},
{
- key: "vega-lite",
- label: "Vega-Lite",
- disabled: true
+ key: 'vega-lite',
+ label: 'Vega-Lite',
},
];
useEffect(() => {
if (showCodeExportPanel) {
- if (tabKey === "graphic-walker") {
+ if (tabKey === 'graphic-walker') {
const res = vizStore.exportCode();
setCode(res);
} else {
- setCode("vega code");
+ setCode(vizStore.lastSpec);
}
}
}, [tabKey, showCodeExportPanel, vizStore]);
@@ -83,11 +79,9 @@ const CodeExport: React.FC = observer((props) => {
setTabKey(k as string);
}}
/>
- {tabKey === "graphic-walker" && (
- <div className="text-sm px-6 max-h-96 overflow-auto">
- <code dangerouslySetInnerHTML={{ __html: syntaxHighlight(code) }} />
- </div>
- )}
+ <div className="text-sm px-6 max-h-96 overflow-auto">
+ <code dangerouslySetInnerHTML={{ __html: syntaxHighlight(code) }} />
+ </div>
<div className="mt-4 flex justify-start">
<PrimaryButton
// text={t("actions.confirm")}
@@ -99,7 +93,7 @@ const CodeExport: React.FC = observer((props) => {
}}
/>
<DefaultButton
- text={t("actions.cancel")}
+ text={t('actions.cancel')}
className="mr-2 px-6"
onClick={() => {
vizStore.setShowCodeExportPanel(false);
diff --git a/packages/graphic-walker/src/interfaces.ts b/packages/graphic-walker/src/interfaces.ts
index 67f1de09..8109627a 100644
--- a/packages/graphic-walker/src/interfaces.ts
+++ b/packages/graphic-walker/src/interfaces.ts
@@ -855,6 +855,7 @@ export type IGWProps = IAppI18nProps &
export interface ISpecProps {
spec?: Specification;
+ vlSpec?: any;
}
export interface ITableSpecProps {
diff --git a/packages/graphic-walker/src/lib/vega.ts b/packages/graphic-walker/src/lib/vega.ts
new file mode 100644
index 00000000..67127b38
--- /dev/null
+++ b/packages/graphic-walker/src/lib/vega.ts
@@ -0,0 +1,179 @@
+import { GLOBAL_CONFIG } from '../config';
+import { IChannelScales, IRow, IStackMode, IViewField, VegaGlobalConfig } from '../interfaces';
+import { encodeFid } from '../vis/spec/encode';
+import { NULL_FIELD } from '../vis/spec/field';
+import { getSingleView, resolveScales } from '../vis/spec/view';
+
+export function toVegaSpec({
+ rows,
+ columns,
+ color,
+ opacity,
+ size,
+ details = [],
+ radius,
+ shape,
+ text,
+ theta,
+ interactiveScale,
+ dataSource,
+ layoutMode,
+ width,
+ height,
+ defaultAggregated,
+ geomType,
+ stack,
+ channelScales,
+ mediaTheme,
+ vegaConfig,
+}: {
+ rows: readonly IViewField[];
+ columns: readonly IViewField[];
+ color?: IViewField;
+ opacity?: IViewField;
+ size?: IViewField;
+ shape?: IViewField;
+ theta?: IViewField;
+ radius?: IViewField;
+ text?: IViewField;
+ details?: Readonly<IViewField[]>;
+ interactiveScale: boolean;
+ dataSource: readonly IRow[];
+ layoutMode: string;
+ width: number;
+ height: number;
+ defaultAggregated: boolean;
+ stack: IStackMode;
+ geomType: string;
+ channelScales?: IChannelScales;
+ mediaTheme: 'dark' | 'light';
+ vegaConfig: VegaGlobalConfig;
+}) {
+ const yField = rows.length > 0 ? rows[rows.length - 1] : NULL_FIELD;
+ const xField = columns.length > 0 ? columns[columns.length - 1] : NULL_FIELD;
+ const rowDims = rows.filter((f) => f.analyticType === 'dimension');
+ const colDims = columns.filter((f) => f.analyticType === 'dimension');
+ const rowMeas = rows.filter((f) => f.analyticType === 'measure');
+ const colMeas = columns.filter((f) => f.analyticType === 'measure');
+ const rowRepeatFields = rowMeas.length === 0 ? rowDims.slice(-1) : rowMeas;
+ const colRepeatFields = colMeas.length === 0 ? colDims.slice(-1) : colMeas;
+
+ const rowLeftFacetFields = rows.slice(0, -1).filter((f) => f.analyticType === 'dimension');
+ const colLeftFacetFields = columns.slice(0, -1).filter((f) => f.analyticType === 'dimension');
+
+ const rowFacetField = rowLeftFacetFields.length > 0 ? rowLeftFacetFields[rowLeftFacetFields.length - 1] : NULL_FIELD;
+ const colFacetField = colLeftFacetFields.length > 0 ? colLeftFacetFields[colLeftFacetFields.length - 1] : NULL_FIELD;
+ const allFieldIds = [...rows, ...columns, color, opacity, size].filter((f) => Boolean(f)).map((f) => (f as IViewField).fid);
+
+ const spec: any = {
+ data: {
+ values: dataSource,
+ },
+ params: [
+ {
+ name: 'geom',
+ select: {
+ type: 'point',
+ fields: allFieldIds.map(encodeFid),
+ },
+ },
+ ],
+ };
+ if (interactiveScale) {
+ spec.params.push({
+ name: 'grid',
+ select: 'interval',
+ bind: 'scales',
+ });
+ }
+ if (rowRepeatFields.length <= 1 && colRepeatFields.length <= 1) {
+ if (layoutMode === 'fixed') {
+ if (rowFacetField === NULL_FIELD && colFacetField === NULL_FIELD) {
+ spec.autosize = 'fit';
+ }
+ spec.width = width;
+ spec.height = height;
+ }
+ const v = getSingleView({
+ x: xField,
+ y: yField,
+ color: color ? color : NULL_FIELD,
+ opacity: opacity ? opacity : NULL_FIELD,
+ size: size ? size : NULL_FIELD,
+ shape: shape ? shape : NULL_FIELD,
+ theta: theta ? theta : NULL_FIELD,
+ radius: radius ? radius : NULL_FIELD,
+ text: text ? text : NULL_FIELD,
+ row: rowFacetField,
+ column: colFacetField,
+ xOffset: NULL_FIELD,
+ yOffset: NULL_FIELD,
+ details,
+ defaultAggregated,
+ stack,
+ geomType,
+ });
+ const singleView = channelScales ? resolveScales(channelScales, v, dataSource, mediaTheme) : v;
+
+ spec.mark = singleView.mark;
+ if ('encoding' in singleView) {
+ spec.encoding = singleView.encoding;
+ }
+
+ spec.resolve ||= {};
+ // @ts-ignore
+ let resolve = vegaConfig.resolve;
+ for (let v in resolve) {
+ let value = resolve[v] ? 'independent' : 'shared';
+ spec.resolve.scale = { ...spec.resolve.scale, [v]: value };
+ if ((GLOBAL_CONFIG.POSITION_CHANNEL_CONFIG_LIST as string[]).includes(v)) {
+ spec.resolve.axis = { ...spec.resolve.axis, [v]: value };
+ } else if ((GLOBAL_CONFIG.NON_POSITION_CHANNEL_CONFIG_LIST as string[]).includes(v)) {
+ spec.resolve.legend = { ...spec.resolve.legend, [v]: value };
+ }
+ }
+ return [spec];
+ } else {
+ if (layoutMode === 'fixed') {
+ spec.width = Math.floor(width / colRepeatFields.length) - 5;
+ spec.height = Math.floor(height / rowRepeatFields.length) - 5;
+ spec.autosize = 'fit';
+ }
+ let index = 0;
+ let result = new Array(rowRepeatFields.length * colRepeatFields.length);
+ for (let i = 0; i < rowRepeatFields.length; i++) {
+ for (let j = 0; j < colRepeatFields.length; j++, index++) {
+ const hasLegend = i === 0 && j === colRepeatFields.length - 1;
+ const v = getSingleView({
+ x: colRepeatFields[j] || NULL_FIELD,
+ y: rowRepeatFields[i] || NULL_FIELD,
+ color: color ? color : NULL_FIELD,
+ opacity: opacity ? opacity : NULL_FIELD,
+ size: size ? size : NULL_FIELD,
+ shape: shape ? shape : NULL_FIELD,
+ theta: theta ? theta : NULL_FIELD,
+ radius: radius ? radius : NULL_FIELD,
+ row: rowFacetField,
+ column: colFacetField,
+ text: text ? text : NULL_FIELD,
+ xOffset: NULL_FIELD,
+ yOffset: NULL_FIELD,
+ details,
+ defaultAggregated,
+ stack,
+ geomType,
+ hideLegend: !hasLegend,
+ });
+ const singleView = channelScales ? resolveScales(channelScales, v, dataSource, mediaTheme) : v;
+ let commonSpec = { ...spec };
+
+ const ans = { ...commonSpec, ...singleView };
+ if ('params' in commonSpec) {
+ ans.params = commonSpec.params;
+ }
+ result[index] = ans;
+ }
+ }
+ return result;
+ }
+}
diff --git a/packages/graphic-walker/src/renderer/index.tsx b/packages/graphic-walker/src/renderer/index.tsx
index 265fdf8a..068756d5 100644
--- a/packages/graphic-walker/src/renderer/index.tsx
+++ b/packages/graphic-walker/src/renderer/index.tsx
@@ -202,6 +202,9 @@ const Renderer = forwardRef<IReactVegaHandler, RendererProps>(function (props, r
onChartResize={handleChartResize}
layout={layout}
channelScales={props.channelScales}
+ onReportSpec={(spec) => {
+ vizStore.updateLastSpec(spec);
+ }}
/>
);
});
diff --git a/packages/graphic-walker/src/renderer/specRenderer.tsx b/packages/graphic-walker/src/renderer/specRenderer.tsx
index c869a2f9..041ba72a 100644
--- a/packages/graphic-walker/src/renderer/specRenderer.tsx
+++ b/packages/graphic-walker/src/renderer/specRenderer.tsx
@@ -25,6 +25,7 @@ interface SpecRendererProps {
locale?: string;
themeConfig?: GWGlobalConfig;
channelScales?: IChannelScales;
+ onReportSpec?: (spec: string) => void;
}
/**
* Sans-store renderer of GraphicWalker.
@@ -43,7 +44,7 @@ const SpecRenderer = forwardRef<IReactVegaHandler, SpecRendererProps>(function (
onGeomClick,
onChartResize,
locale,
-
+ onReportSpec,
themeConfig: customizedThemeConfig,
channelScales,
},
@@ -225,6 +226,7 @@ const SpecRenderer = forwardRef<IReactVegaHandler, SpecRendererProps>(function (
channelScales={channelScales}
dark={dark}
scale={scale}
+ onReportSpec={onReportSpec}
/>
)}
</Resizable>
diff --git a/packages/graphic-walker/src/store/visualSpecStore.ts b/packages/graphic-walker/src/store/visualSpecStore.ts
index d3925441..2ef6f636 100644
--- a/packages/graphic-walker/src/store/visualSpecStore.ts
+++ b/packages/graphic-walker/src/store/visualSpecStore.ts
@@ -96,6 +96,7 @@ export class VizSpecStore {
showErrorResolutionPanel: number = 0;
lastErrorMessage: string = '';
showAskvizFeedbackIndex: number | undefined = 0;
+ lastSpec: string = "";
private onMetaChange?: (fid: string, diffMeta: Partial<IMutField>) => void;
@@ -621,6 +622,10 @@ export class VizSpecStore {
this.showErrorResolutionPanel = errCode;
this.lastErrorMessage = msg;
}
+
+ updateLastSpec(spec: string) {
+ this.lastSpec = spec;
+ }
}
export function renderSpec(spec: Specification, meta: IMutField[], name: string, visId: string) {
diff --git a/packages/graphic-walker/src/vis/react-vega.tsx b/packages/graphic-walker/src/vis/react-vega.tsx
index 9cfd6b66..e282d393 100644
--- a/packages/graphic-walker/src/vis/react-vega.tsx
+++ b/packages/graphic-walker/src/vis/react-vega.tsx
@@ -1,492 +1,422 @@
import React, { useEffect, useState, useMemo, forwardRef, useRef } from 'react';
import embed from 'vega-embed';
-import { Subject, Subscription } from 'rxjs'
+import { Subject, Subscription } from 'rxjs';
import * as op from 'rxjs/operators';
import type { ScenegraphEvent } from 'vega';
import styled from 'styled-components';
-import { GLOBAL_CONFIG } from '../config';
import { useVegaExportApi } from '../utils/vegaApiExport';
import { IViewField, IRow, IStackMode, VegaGlobalConfig, IVegaChartRef, IChannelScales, IDarkMode, IConfigScale } from '../interfaces';
import { getVegaTimeFormatRules } from './temporalFormat';
-import { getSingleView, resolveScales } from './spec/view';
-import { NULL_FIELD } from './spec/field';
import canvasSize from 'canvas-size';
import { Errors, useReporter } from '../utils/reportError';
import { useCurrentMediaTheme } from '../utils/media';
+import { toVegaSpec } from '../lib/vega';
-const CanvaContainer = styled.div<{rowSize: number; colSize: number;}>`
- display: grid;
- grid-template-columns: repeat(${props => props.colSize}, 1fr);
- grid-template-rows: repeat(${props => props.rowSize}, 1fr);
-`
+const CanvaContainer = styled.div<{ rowSize: number; colSize: number }>`
+ display: grid;
+ grid-template-columns: repeat(${(props) => props.colSize}, 1fr);
+ grid-template-rows: repeat(${(props) => props.rowSize}, 1fr);
+`;
const SELECTION_NAME = 'geom';
export interface IReactVegaHandler {
- getSVGData: () => Promise<string[]>;
- getCanvasData: () => Promise<string[]>;
- downloadSVG: (filename?: string) => Promise<string[]>;
- downloadPNG: (filename?: string) => Promise<string[]>;
+ getSVGData: () => Promise<string[]>;
+ getCanvasData: () => Promise<string[]>;
+ downloadSVG: (filename?: string) => Promise<string[]>;
+ downloadPNG: (filename?: string) => Promise<string[]>;
}
interface ReactVegaProps {
- name?: string;
- rows: Readonly<IViewField[]>;
- columns: Readonly<IViewField[]>;
- dataSource: readonly IRow[];
- defaultAggregate?: boolean;
- stack: IStackMode;
- interactiveScale: boolean;
- geomType: string;
- color?: IViewField;
- opacity?: IViewField;
- size?: IViewField;
- shape?: IViewField;
- theta?: IViewField;
- radius?: IViewField;
- text?: IViewField;
- details?: Readonly<IViewField[]>;
- showActions: boolean;
- layoutMode: string;
- width: number;
- height: number;
- onGeomClick?: (values: any, e: any) => void
- vegaConfig: VegaGlobalConfig;
- /** @default "en-US" */
- locale?: string;
- useSvg?: boolean;
- dark?: IDarkMode;
- channelScales?: IChannelScales;
- scale?: {
- opacity: IConfigScale,
- size: IConfigScale
- }
+ name?: string;
+ rows: Readonly<IViewField[]>;
+ columns: Readonly<IViewField[]>;
+ dataSource: readonly IRow[];
+ defaultAggregate?: boolean;
+ stack: IStackMode;
+ interactiveScale: boolean;
+ geomType: string;
+ color?: IViewField;
+ opacity?: IViewField;
+ size?: IViewField;
+ shape?: IViewField;
+ theta?: IViewField;
+ radius?: IViewField;
+ text?: IViewField;
+ details?: Readonly<IViewField[]>;
+ showActions: boolean;
+ layoutMode: string;
+ width: number;
+ height: number;
+ onGeomClick?: (values: any, e: any) => void;
+ vegaConfig: VegaGlobalConfig;
+ /** @default "en-US" */
+ locale?: string;
+ useSvg?: boolean;
+ dark?: IDarkMode;
+ channelScales?: IChannelScales;
+ scale?: {
+ opacity: IConfigScale;
+ size: IConfigScale;
+ };
+ onReportSpec?: (spec: string) => void;
}
const click$ = new Subject<ScenegraphEvent>();
const selection$ = new Subject<any>();
const geomClick$ = selection$.pipe(
- op.withLatestFrom(click$),
- op.filter(([values, _]) => {
- if (Object.keys(values).length > 0) {
- return true
- }
- return false
- })
+ op.withLatestFrom(click$),
+ op.filter(([values, _]) => {
+ if (Object.keys(values).length > 0) {
+ return true;
+ }
+ return false;
+ })
);
-const BRUSH_SIGNAL_NAME = "__gw_brush__";
-const POINT_SIGNAL_NAME = "__gw_point__";
+const BRUSH_SIGNAL_NAME = '__gw_brush__';
+const POINT_SIGNAL_NAME = '__gw_point__';
interface ParamStoreEntry {
- signal: typeof BRUSH_SIGNAL_NAME | typeof POINT_SIGNAL_NAME;
- /** 这个标记用于防止循环 */
- source: number;
- data: any;
+ signal: typeof BRUSH_SIGNAL_NAME | typeof POINT_SIGNAL_NAME;
+ /** 这个标记用于防止循环 */
+ source: number;
+ data: any;
}
-
-const ReactVega = forwardRef<IReactVegaHandler, ReactVegaProps>(function ReactVega (props, ref) {
- const {
- name,
- dataSource = [],
- rows = [],
- columns = [],
- defaultAggregate = true,
- stack = 'stack',
- geomType,
- color,
- opacity,
- size,
- theta,
- radius,
- shape,
- text,
- onGeomClick,
- showActions,
- interactiveScale,
- layoutMode,
- width,
- height,
- details = [],
- // themeKey = 'vega',
- dark = 'media',
- vegaConfig,
- // format
- locale = 'en-US',
- useSvg,
- channelScales : channelScaleRaw,
- scale
- } = props;
- const [viewPlaceholders, setViewPlaceholders] = useState<React.MutableRefObject<HTMLDivElement>[]>([]);
- const mediaTheme = useCurrentMediaTheme(dark);
- const channelScales = useMemo(() => {
- const cs = channelScaleRaw ?? {};
- if (scale?.opacity) {
- cs.opacity = {
- ...(cs.opacity ?? {}),
- ...scale.opacity,
- };
- }
- if (scale?.size) {
- cs.size = {
- ...(cs.size ?? {}),
- ...scale.size,
- };
- }
- return cs;
-}, [channelScaleRaw, scale]);
-
- // const themeConfig = builtInThemes[themeKey]?.[mediaTheme];
-
- // const vegaConfig = useMemo(() => {
- // const config: any = {
- // ...themeConfig,
- // }
- // if (format.normalizedNumberFormat && format.normalizedNumberFormat.length > 0) {
- // config.normalizedNumberFormat = format.normalizedNumberFormat;
- // }
- // if (format.numberFormat && format.numberFormat.length > 0) {
- // config.numberFormat = format.numberFormat;
- // }
- // if (format.timeFormat && format.timeFormat.length > 0) {
- // config.timeFormat = format.timeFormat;
- // }
- // return config;
- // }, [themeConfig, format.normalizedNumberFormat, format.numberFormat, format.timeFormat])
-
- useEffect(() => {
- const clickSub = geomClick$.subscribe(([values, e]) => {
- if (onGeomClick) {
- onGeomClick(values, e);
- }
- })
- return () => {
- clickSub.unsubscribe();
- }
- }, [onGeomClick]);
- const rowDims = useMemo(() => rows.filter(f => f.analyticType === 'dimension'), [rows]);
- const colDims = useMemo(() => columns.filter(f => f.analyticType === 'dimension'), [columns]);
- const rowMeas = useMemo(() => rows.filter(f => f.analyticType === 'measure'), [rows]);
- const colMeas = useMemo(() => columns.filter(f => f.analyticType === 'measure'), [columns]);
- const rowFacetFields = useMemo(() => rowDims.slice(0, -1), [rowDims]);
- const colFacetFields = useMemo(() => colDims.slice(0, -1), [colDims]);
- const rowRepeatFields = useMemo(() => rowMeas.length === 0 ? rowDims.slice(-1) : rowMeas, [rowDims, rowMeas]);//rowMeas.slice(0, -1);
- const colRepeatFields = useMemo(() => colMeas.length === 0 ? colDims.slice(-1) : colMeas, [colDims, colMeas]);//colMeas.slice(0, -1);
- const allFieldIds = useMemo(() => [...rows, ...columns, color, opacity, size].filter(f => Boolean(f)).map(f => (f as IViewField).fid), [rows, columns, color, opacity, size]);
-
- const { reportError: reportGWError } = useReporter();
-
- const [crossFilterTriggerIdx, setCrossFilterTriggerIdx] = useState(-1);
-
- useEffect(() => {
- setCrossFilterTriggerIdx(-1);
- setViewPlaceholders(views => {
- const viewNum = Math.max(1, rowRepeatFields.length * colRepeatFields.length)
- const nextViews = new Array(viewNum).fill(null).map((v, i) => views[i] || React.createRef())
- return nextViews;
- })
- }, [rowRepeatFields, colRepeatFields])
-
- 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;
-
- const rowLeftFacetFields = rows.slice(0, -1).filter(f => f.analyticType === 'dimension');
- const colLeftFacetFields = columns.slice(0, -1).filter(f => f.analyticType === 'dimension');
-
- const rowFacetField = rowLeftFacetFields.length > 0 ? rowLeftFacetFields[rowLeftFacetFields.length - 1] : NULL_FIELD;
- const colFacetField = colLeftFacetFields.length > 0 ? colLeftFacetFields[colLeftFacetFields.length - 1] : NULL_FIELD;
-
- const spec: any = {
- data: {
- values: dataSource,
- },
- params: [{
- name: SELECTION_NAME,
- select: {
- type: 'point',
- fields: allFieldIds
+const ReactVega = forwardRef<IReactVegaHandler, ReactVegaProps>(function ReactVega(props, ref) {
+ const {
+ name,
+ dataSource = [],
+ rows = [],
+ columns = [],
+ defaultAggregate = true,
+ stack = 'stack',
+ geomType,
+ color,
+ opacity,
+ size,
+ theta,
+ radius,
+ shape,
+ text,
+ onGeomClick,
+ showActions,
+ interactiveScale,
+ layoutMode,
+ width,
+ height,
+ details = [],
+ // themeKey = 'vega',
+ dark = 'media',
+ vegaConfig,
+ // format
+ locale = 'en-US',
+ useSvg,
+ channelScales: channelScaleRaw,
+ scale,
+ } = props;
+ const [viewPlaceholders, setViewPlaceholders] = useState<React.MutableRefObject<HTMLDivElement>[]>([]);
+ const mediaTheme = useCurrentMediaTheme(dark);
+ const channelScales = useMemo(() => {
+ const cs = channelScaleRaw ?? {};
+ if (scale?.opacity) {
+ cs.opacity = {
+ ...(cs.opacity ?? {}),
+ ...scale.opacity,
+ };
}
- }]
- };
- if (interactiveScale) {
- spec.params.push({
- name: "grid",
- select: "interval",
- bind: "scales"
- })
- }
- if (rowRepeatFields.length <= 1 && colRepeatFields.length <= 1) {
- if (layoutMode === 'fixed') {
- if (rowFacetField === NULL_FIELD && colFacetField === NULL_FIELD) {
- spec.autosize = 'fit'
+ if (scale?.size) {
+ cs.size = {
+ ...(cs.size ?? {}),
+ ...scale.size,
+ };
}
- spec.width = width;
- spec.height = height;
- }
- const v = getSingleView({
- x: xField,
- y: yField,
- color: color ? color : NULL_FIELD,
- opacity: opacity ? opacity : NULL_FIELD,
- size: size ? size : NULL_FIELD,
- shape: shape ? shape : NULL_FIELD,
- theta: theta ? theta : NULL_FIELD,
- radius: radius ? radius : NULL_FIELD,
- text: text ? text : NULL_FIELD,
- row: rowFacetField,
- column: colFacetField,
- xOffset: NULL_FIELD,
- yOffset: NULL_FIELD,
- details,
- defaultAggregated: defaultAggregate,
- stack,
- geomType,
- });
- const singleView = channelScales ? resolveScales(channelScales, v, dataSource, mediaTheme) : v;
+ return cs;
+ }, [channelScaleRaw, scale]);
+
+ // const themeConfig = builtInThemes[themeKey]?.[mediaTheme];
- spec.mark = singleView.mark;
- if ('encoding' in singleView) {
- spec.encoding = singleView.encoding;
- }
+ // const vegaConfig = useMemo(() => {
+ // const config: any = {
+ // ...themeConfig,
+ // }
+ // if (format.normalizedNumberFormat && format.normalizedNumberFormat.length > 0) {
+ // config.normalizedNumberFormat = format.normalizedNumberFormat;
+ // }
+ // if (format.numberFormat && format.numberFormat.length > 0) {
+ // config.numberFormat = format.numberFormat;
+ // }
+ // if (format.timeFormat && format.timeFormat.length > 0) {
+ // config.timeFormat = format.timeFormat;
+ // }
+ // return config;
+ // }, [themeConfig, format.normalizedNumberFormat, format.numberFormat, format.timeFormat])
- spec.resolve ||= {};
- // @ts-ignore
- let resolve = vegaConfig.resolve;
- for (let v in resolve) {
- let value = resolve[v] ? 'independent' : 'shared';
- // @ts-ignore
- spec.resolve.scale = { ...spec.resolve.scale, [v]: value };
- if((GLOBAL_CONFIG.POSITION_CHANNEL_CONFIG_LIST as string[]).includes(v)) {
- spec.resolve.axis = { ...spec.resolve.axis, [v]: value };
- }else if((GLOBAL_CONFIG.NON_POSITION_CHANNEL_CONFIG_LIST as string[]).includes(v)){
- spec.resolve.legend = { ...spec.resolve.legend, [v]: value };
- }
- }
-
- if (viewPlaceholders.length > 0 && viewPlaceholders[0].current) {
- const task = embed(viewPlaceholders[0].current, spec, { renderer: useSvg ? 'svg' : 'canvas', mode: 'vega-lite', actions: showActions, timeFormatLocale: getVegaTimeFormatRules(locale), config: vegaConfig }).then(res => {
- const container = res.view.container();
- const canvas = container?.querySelector('canvas') ?? null;
- const success = useSvg || (canvas && canvasSize.test({ width: canvas.width, height: canvas.height }));
- if (!success) {
- if (canvas) {
- reportGWError("canvas exceed max size", Errors.canvasExceedSize);
- } else {
- reportGWError("canvas not found", Errors.canvasExceedSize);
+ useEffect(() => {
+ const clickSub = geomClick$.subscribe(([values, e]) => {
+ if (onGeomClick) {
+ onGeomClick(values, e);
}
- }
- vegaRefs.current = [{
- 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) => {
- click$.next(e);
- })
- res.view.addSignalListener(SELECTION_NAME, (name: any, values: any) => {
- selection$.next(values);
- });
- } catch (error) {
- console.warn(error)
- }
});
- renderTaskRefs.current = [task];
- }
- } else {
- if (layoutMode === 'fixed') {
- spec.width = Math.floor(width / colRepeatFields.length) - 5;
- spec.height = Math.floor(height / rowRepeatFields.length) - 5;
- spec.autosize = 'fit'
- }
- const combinedParamStore$ = new Subject<ParamStoreEntry>();
- const throttledParamStore$ = combinedParamStore$.pipe(
- op.throttleTime(
- dataSource.length / 64 * rowRepeatFields.length * colRepeatFields.length,
- undefined,
- { leading: false, trailing: true }
- )
- );
- const subscriptions: Subscription[] = [];
- const subscribe = (cb: (entry: ParamStoreEntry) => void) => {
- subscriptions.push(throttledParamStore$.subscribe(cb));
- };
- let index = 0;
- vegaRefs.current = new Array(rowRepeatFields.length * colRepeatFields.length);
- for (let i = 0; i < rowRepeatFields.length; i++) {
- for (let j = 0; j < colRepeatFields.length; j++, index++) {
- const sourceId = index;
- const hasLegend = i === 0 && j === colRepeatFields.length - 1;
- const v = getSingleView({
- x: colRepeatFields[j] || NULL_FIELD,
- y: rowRepeatFields[i] || NULL_FIELD,
- color: color ? color : NULL_FIELD,
- opacity: opacity ? opacity : NULL_FIELD,
- size: size ? size : NULL_FIELD,
- shape: shape ? shape : NULL_FIELD,
- theta: theta ? theta : NULL_FIELD,
- radius: radius ? radius : NULL_FIELD,
- row: rowFacetField,
- column: colFacetField,
- text: text ? text : NULL_FIELD,
- xOffset: NULL_FIELD,
- yOffset: NULL_FIELD,
- details,
- defaultAggregated: defaultAggregate,
- stack,
- geomType,
- hideLegend: !hasLegend,
- });
- const singleView = channelScales ? resolveScales(channelScales, v, dataSource, mediaTheme) : v;
- const node = i * colRepeatFields.length + j < viewPlaceholders.length ? viewPlaceholders[i * colRepeatFields.length + j].current : null
- let commonSpec = { ...spec };
+ return () => {
+ clickSub.unsubscribe();
+ };
+ }, [onGeomClick]);
+ const rowDims = useMemo(() => rows.filter((f) => f.analyticType === 'dimension'), [rows]);
+ const colDims = useMemo(() => columns.filter((f) => f.analyticType === 'dimension'), [columns]);
+ const rowMeas = useMemo(() => rows.filter((f) => f.analyticType === 'measure'), [rows]);
+ const colMeas = useMemo(() => columns.filter((f) => f.analyticType === 'measure'), [columns]);
+ const rowRepeatFields = useMemo(() => (rowMeas.length === 0 ? rowDims.slice(-1) : rowMeas), [rowDims, rowMeas]); //rowMeas.slice(0, -1);
+ const colRepeatFields = useMemo(() => (colMeas.length === 0 ? colDims.slice(-1) : colMeas), [colDims, colMeas]); //colMeas.slice(0, -1);
+ const { reportError: reportGWError } = useReporter();
- const ans = { ...commonSpec, ...singleView }
- if ('params' in commonSpec) {
- ans.params = commonSpec.params;
- }
- if (node) {
- const id = index;
- const task = embed(node, ans, { renderer: useSvg ? 'svg' : 'canvas', mode: 'vega-lite', actions: showActions, timeFormatLocale: getVegaTimeFormatRules(locale), config: vegaConfig }).then(res => {
- const container = res.view.container();
- const canvas = container?.querySelector('canvas') ?? null;
- const success = useSvg || (canvas && canvasSize.test({ width: canvas.width, height: canvas.height }));
- if (!success) {
- if (canvas) {
- reportGWError("canvas exceed max size", Errors.canvasExceedSize);
- } else {
- reportGWError("canvas not found", Errors.canvasExceedSize);
- }
- }
- vegaRefs.current[id] = {
- 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)
- ).map(name => name.replace(/_store$/, ''));
- try {
- for (const param of paramStores) {
- let noBroadcasting = false;
- // 发出
- res.view.addSignalListener(param, name => {
- if (noBroadcasting) {
- noBroadcasting = false;
- return;
+ const [crossFilterTriggerIdx, setCrossFilterTriggerIdx] = useState(-1);
+
+ useEffect(() => {
+ setCrossFilterTriggerIdx(-1);
+ setViewPlaceholders((views) => {
+ const viewNum = Math.max(1, rowRepeatFields.length * colRepeatFields.length);
+ const nextViews = new Array(viewNum).fill(null).map((v, i) => views[i] || React.createRef());
+ return nextViews;
+ });
+ }, [rowRepeatFields, colRepeatFields]);
+
+ const vegaRefs = useRef<IVegaChartRef[]>([]);
+ const renderTaskRefs = useRef<Promise<unknown>[]>([]);
+ const specs = useMemo(
+ () =>
+ toVegaSpec({
+ columns,
+ dataSource,
+ defaultAggregated: defaultAggregate,
+ geomType,
+ height,
+ interactiveScale,
+ layoutMode,
+ mediaTheme,
+ rows,
+ stack,
+ width,
+ channelScales,
+ color,
+ details,
+ opacity,
+ radius,
+ shape,
+ size,
+ text,
+ theta,
+ vegaConfig,
+ }),
+ [
+ columns,
+ dataSource,
+ defaultAggregate,
+ geomType,
+ height,
+ interactiveScale,
+ layoutMode,
+ mediaTheme,
+ rows,
+ stack,
+ width,
+ channelScales,
+ color,
+ details,
+ opacity,
+ radius,
+ shape,
+ size,
+ text,
+ theta,
+ ]
+ );
+ // Render
+ useEffect(() => {
+ props.onReportSpec?.(
+ JSON.stringify(
+ specs.map((x) => ({
+ ...x,
+ data: undefined,
+ })),
+ undefined,
+ 4
+ )
+ );
+ vegaRefs.current = [];
+ renderTaskRefs.current = [];
+ if (rowRepeatFields.length <= 1 && colRepeatFields.length <= 1) {
+ if (viewPlaceholders.length > 0 && viewPlaceholders[0].current) {
+ const task = embed(viewPlaceholders[0].current, specs[0], {
+ renderer: useSvg ? 'svg' : 'canvas',
+ mode: 'vega-lite',
+ actions: showActions,
+ timeFormatLocale: getVegaTimeFormatRules(locale),
+ config: vegaConfig,
+ }).then((res) => {
+ const container = res.view.container();
+ const canvas = container?.querySelector('canvas') ?? null;
+ const success = useSvg || (canvas && canvasSize.test({ width: canvas.width, height: canvas.height }));
+ if (!success) {
+ if (canvas) {
+ reportGWError('canvas exceed max size', Errors.canvasExceedSize);
+ } else {
+ reportGWError('canvas not found', Errors.canvasExceedSize);
+ }
}
- if ([BRUSH_SIGNAL_NAME, POINT_SIGNAL_NAME].includes(name)) {
- const data = res.view.getState().data?.[`${name}_store`];
- if (!data || (Array.isArray(data) && data.length === 0)) {
- setCrossFilterTriggerIdx(-1);
- }
- combinedParamStore$.next({
- signal: name as typeof BRUSH_SIGNAL_NAME | typeof POINT_SIGNAL_NAME,
- source: sourceId,
- data: data ?? null,
- });
+ vegaRefs.current = [
+ {
+ 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) => {
+ click$.next(e);
+ });
+ res.view.addSignalListener(SELECTION_NAME, (name: any, values: any) => {
+ selection$.next(values);
+ });
+ } catch (error) {
+ console.warn(error);
}
- });
- subscribe(entry => {
- if (entry.source === sourceId || !entry.data) {
- return;
+ });
+ renderTaskRefs.current = [task];
+ }
+ } else {
+ let index = 0;
+ vegaRefs.current = new Array(rowRepeatFields.length * colRepeatFields.length);
+ const combinedParamStore$ = new Subject<ParamStoreEntry>();
+ const throttledParamStore$ = combinedParamStore$.pipe(
+ op.throttleTime((dataSource.length / 64) * rowRepeatFields.length * colRepeatFields.length, undefined, { leading: false, trailing: true })
+ );
+ const subscriptions: Subscription[] = [];
+ const subscribe = (cb: (entry: ParamStoreEntry) => void) => {
+ subscriptions.push(throttledParamStore$.subscribe(cb));
+ };
+
+ for (let i = 0; i < rowRepeatFields.length; i++) {
+ for (let j = 0; j < colRepeatFields.length; j++, index++) {
+ const sourceId = index;
+ const node = i * colRepeatFields.length + j < viewPlaceholders.length ? viewPlaceholders[i * colRepeatFields.length + j].current : null;
+ const ans = specs[index];
+ if (node) {
+ const id = index;
+ const task = embed(node, ans, {
+ renderer: useSvg ? 'svg' : 'canvas',
+ mode: 'vega-lite',
+ actions: showActions,
+ timeFormatLocale: getVegaTimeFormatRules(locale),
+ config: vegaConfig,
+ }).then((res) => {
+ const container = res.view.container();
+ const canvas = container?.querySelector('canvas') ?? null;
+ const success = useSvg || (canvas && canvasSize.test({ width: canvas.width, height: canvas.height }));
+ if (!success) {
+ if (canvas) {
+ reportGWError('canvas exceed max size', Errors.canvasExceedSize);
+ } else {
+ reportGWError('canvas not found', Errors.canvasExceedSize);
+ }
+ }
+ vegaRefs.current[id] = {
+ 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))
+ .map((name) => name.replace(/_store$/, ''));
+ try {
+ for (const param of paramStores) {
+ let noBroadcasting = false;
+ // 发出
+ res.view.addSignalListener(param, (name) => {
+ if (noBroadcasting) {
+ noBroadcasting = false;
+ return;
+ }
+ if ([BRUSH_SIGNAL_NAME, POINT_SIGNAL_NAME].includes(name)) {
+ const data = res.view.getState().data?.[`${name}_store`];
+ if (!data || (Array.isArray(data) && data.length === 0)) {
+ setCrossFilterTriggerIdx(-1);
+ }
+ combinedParamStore$.next({
+ signal: name as typeof BRUSH_SIGNAL_NAME | typeof POINT_SIGNAL_NAME,
+ source: sourceId,
+ data: data ?? null,
+ });
+ }
+ });
+ subscribe((entry) => {
+ if (entry.source === sourceId || !entry.data) {
+ return;
+ }
+ noBroadcasting = true;
+ res.view.setState({
+ data: {
+ [`${entry.signal}_store`]: entry.data,
+ },
+ });
+ });
+ }
+ } catch (error) {
+ console.warn('Crossing filter failed', error);
+ }
+ try {
+ res.view.addEventListener('mouseover', () => {
+ if (sourceId !== crossFilterTriggerIdx) {
+ setCrossFilterTriggerIdx(sourceId);
+ }
+ });
+ res.view.addEventListener('click', (e) => {
+ click$.next(e);
+ });
+ res.view.addSignalListener(SELECTION_NAME, (name: any, values: any) => {
+ selection$.next(values);
+ });
+ } catch (error) {
+ console.warn(error);
+ }
+ });
+ renderTaskRefs.current.push(task);
}
- noBroadcasting = true;
- res.view.setState({
- data: {
- [`${entry.signal}_store`]: entry.data,
- },
- });
- });
}
- } catch (error) {
- console.warn('Crossing filter failed', error);
- }
- try {
- res.view.addEventListener('mouseover', () => {
- if (sourceId !== crossFilterTriggerIdx) {
- setCrossFilterTriggerIdx(sourceId);
- }
- });
- res.view.addEventListener('click', (e) => {
- click$.next(e);
- })
- res.view.addSignalListener(SELECTION_NAME, (name: any, values: any) => {
- selection$.next(values);
- });
- } catch (error) {
- console.warn(error);
- }
- })
- renderTaskRefs.current.push(task);
- }
+ }
+ return () => {
+ subscriptions.forEach((sub) => sub.unsubscribe());
+ props.onReportSpec?.('');
+ };
}
- }
- return () => {
- subscriptions.forEach(sub => sub.unsubscribe());
- };
- }
- return () => {
- vegaRefs.current = [];
- renderTaskRefs.current = [];
- };
- }, [
- dataSource,
- allFieldIds,
- rows,
- columns,
- defaultAggregate,
- geomType,
- color,
- opacity,
- size,
- shape,
- theta, radius,
- viewPlaceholders,
- rowFacetFields,
- colFacetFields,
- rowRepeatFields,
- colRepeatFields,
- stack,
- showActions,
- interactiveScale,
- layoutMode,
- width,
- height,
- vegaConfig,
- details,
- text,
- useSvg,
- channelScales,
- mediaTheme
- ]);
+ return () => {
+ vegaRefs.current = [];
+ renderTaskRefs.current = [];
+ props.onReportSpec?.('');
+ };
+ }, [specs, viewPlaceholders, showActions, vegaConfig, useSvg, locale]);
- const containerRef = useRef<HTMLDivElement>(null);
+ const containerRef = useRef<HTMLDivElement>(null);
- useVegaExportApi(name, vegaRefs, ref, renderTaskRefs, containerRef);
+ useVegaExportApi(name, vegaRefs, ref, renderTaskRefs, containerRef);
- 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>)
- }
- </CanvaContainer>
+ 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>
+ ))}
+ </CanvaContainer>
+ );
});
export default ReactVega;
diff --git a/packages/graphic-walker/src/vis/spec/aggregate.ts b/packages/graphic-walker/src/vis/spec/aggregate.ts
index 76a6d9a3..60854f13 100644
--- a/packages/graphic-walker/src/vis/spec/aggregate.ts
+++ b/packages/graphic-walker/src/vis/spec/aggregate.ts
@@ -1,17 +1,18 @@
import { COUNT_FIELD_ID } from '../../constants';
import { IViewField } from '../../interfaces';
import { getMeaAggKey } from '../../utils';
+import { encodeFid } from './encode';
export function channelAggregate(encoding: { [key: string]: any }, fields: IViewField[]) {
Object.values(encoding).forEach((c) => {
if (c.aggregate === null) return;
- const targetField = fields.find((f) => f.fid === c.field && (f.analyticType === 'measure' || f.fid === COUNT_FIELD_ID));
+ const targetField = fields.find((f) => encodeFid(f.fid) === c.field && (f.analyticType === 'measure' || f.fid === COUNT_FIELD_ID));
if (targetField && targetField.fid === COUNT_FIELD_ID) {
c.title = 'Count';
- c.field = getMeaAggKey(targetField.fid, targetField.aggName)
+ c.field = encodeFid(getMeaAggKey(targetField.fid, targetField.aggName))
} else if (targetField) {
c.title = `${targetField.aggName}(${targetField.name})`;
- c.field = getMeaAggKey(targetField.fid, targetField.aggName)
+ c.field = encodeFid(getMeaAggKey(targetField.fid, targetField.aggName))
}
});
}
diff --git a/packages/graphic-walker/src/vis/spec/encode.ts b/packages/graphic-walker/src/vis/spec/encode.ts
index 4890a4a8..02018012 100644
--- a/packages/graphic-walker/src/vis/spec/encode.ts
+++ b/packages/graphic-walker/src/vis/spec/encode.ts
@@ -47,6 +47,10 @@ function encodeTimeunit(unit: (typeof DATE_TIME_DRILL_LEVELS)[number]) {
return unit;
}
+export function encodeFid(fid: string) {
+ return fid.replace(/\"/g, '\\"').replace(/\'/g, "\\'");
+}
+
export function channelEncode(props: IEncodeProps) {
const avcs = availableChannels(props.geomType);
const encoding: { [key: string]: any } = {};
@@ -55,7 +59,7 @@ export function channelEncode(props: IEncodeProps) {
.forEach((c) => {
if (props[c] !== NULL_FIELD) {
encoding[c] = {
- field: props[c].fid,
+ field: encodeFid(props[c].fid),
title: props[c].name,
type: props[c].semanticType,
};