Skip to content

An open source alternative to Tableau. Embeddable visual analytic

feat: all computation to worker

jojocysc1fda17cc1d0
diff --git a/packages/graphic-walker/package.json b/packages/graphic-walker/package.json
index 0726af49..1d09effc 100644
--- a/packages/graphic-walker/package.json
+++ b/packages/graphic-walker/package.json
@@ -28,7 +28,8 @@
},
"prettier": {
"tabWidth": 4,
- "printWidth": 120
+ "printWidth": 120,
+ "singleQuote": true
},
"types": "./dist/index.d.ts",
"dependencies": {
diff --git a/packages/graphic-walker/src/components/loadingLayer.tsx b/packages/graphic-walker/src/components/loadingLayer.tsx
new file mode 100644
index 00000000..2e14a9d8
--- /dev/null
+++ b/packages/graphic-walker/src/components/loadingLayer.tsx
@@ -0,0 +1,7 @@
+import React from 'react';
+
+export default function LoadingLayer () {
+ return <div className="bg-gray-100/50 dark:bg-gray-700/50 absolute top-0 left-0 right-0 bottom-0 z-50 flex items-center justify-center">
+ Loading...
+ </div>
+}
\ No newline at end of file
diff --git a/packages/graphic-walker/src/lib/interfaces.ts b/packages/graphic-walker/src/lib/interfaces.ts
index ab26b234..c84fab41 100644
--- a/packages/graphic-walker/src/lib/interfaces.ts
+++ b/packages/graphic-walker/src/lib/interfaces.ts
@@ -2,7 +2,15 @@ export interface IAggQuery {
op: 'aggregate';
groupBy: string[];
agg: {
- [field: string]: 'sum' | 'avg' | 'count' | 'max' | 'min';
+ [field: string]:
+ | 'sum'
+ | 'count'
+ | 'max'
+ | 'min'
+ | 'mean'
+ | 'median'
+ | 'variance'
+ | 'stdev';
};
}
@@ -23,4 +31,9 @@ export interface IBinQuery {
binBy: string;
newBinCol: string;
binSize: number;
-}
\ No newline at end of file
+}
+
+
+export interface IRawQuery {
+ op: 'raw';
+}
diff --git a/packages/graphic-walker/src/lib/op/aggregate.ts b/packages/graphic-walker/src/lib/op/aggregate.ts
index b3f88dec..e2aaeb55 100644
--- a/packages/graphic-walker/src/lib/op/aggregate.ts
+++ b/packages/graphic-walker/src/lib/op/aggregate.ts
@@ -1,46 +1,49 @@
import { IRow } from "visual-insights";
import { IAggQuery } from "../interfaces";
+import { sum, mean, median, stdev, variance, max, min, count } from "./stat";
+
+const aggregatorMap = {
+ sum,
+ mean,
+ median,
+ stdev,
+ variance,
+ max,
+ min,
+ count,
+};
const KEY_JOINER = '___';
export function aggregate (data: IRow[], query: IAggQuery): IRow[] {
const { groupBy, agg } = query;
const ans: Map<string, IRow> = new Map();
+ const groups: Map<string, IRow[]> = new Map();
for (let row of data) {
const gk = groupBy.map((k) => row[k]).join(KEY_JOINER);
- let aggRow: IRow = {};
- if (!ans.has(gk)) {
- for (let k of groupBy) {
- aggRow[k] = row[k];
- }
- ans.set(gk, aggRow);
+ if (!groups.has(gk)) {
+ groups.set(gk, []);
}
-
-
- aggRow = ans.get(gk)!;
- for (let k in agg) {
- if (aggRow[k] === undefined) {
- aggRow[k] = 0;
- }
- switch (agg[k]) {
- case 'sum':
- aggRow[k] += row[k];
- break;
- case 'avg':
- aggRow[k] += row[k];
- break;
- case 'count':
- aggRow[k] += 1;
- break;
- case 'max':
- aggRow[k] = Math.max(aggRow[k], row[k]);
- break;
- case 'min':
- aggRow[k] = Math.min(aggRow[k], row[k]);
- break;
+ groups.get(gk)?.push(row);
+ }
+ for (let [gk, subGroup] of groups) {
+ if (subGroup.length === 0) {
+ continue;
+ }
+ let aggRow: IRow = {};
+ for (let k of groupBy) {
+ aggRow[k] = subGroup[0][k];
+ }
+ for (let meaKey in agg) {
+ if (aggRow[meaKey] === undefined) {
+ aggRow[meaKey] = 0;
}
+ const values: number[] = subGroup.map((r) => r[meaKey]) ?? [];
+ const aggregator = aggregatorMap[agg[meaKey]] ?? sum;
+ aggRow[meaKey] = aggregator(values);
}
+ ans.set(gk, aggRow);
}
return Array.from(ans.values());
}
\ No newline at end of file
diff --git a/packages/graphic-walker/src/lib/op/stat.ts b/packages/graphic-walker/src/lib/op/stat.ts
new file mode 100644
index 00000000..8240967a
--- /dev/null
+++ b/packages/graphic-walker/src/lib/op/stat.ts
@@ -0,0 +1,46 @@
+export function mean(nums: number[]): number {
+ return nums.reduce((a, b) => a + b, 0) / nums.length;
+}
+
+export function sum(nums: number[]): number {
+ return nums.reduce((a, b) => a + b, 0);
+}
+
+export function median(nums: number[]): number {
+ const sorted = nums.sort((a, b) => a - b);
+ const mid = Math.floor(sorted.length / 2);
+ return sorted.length % 2 === 0 ? (sorted[mid] + sorted[mid - 1]) / 2 : sorted[mid];
+}
+
+export function variance(nums: number[]): number {
+ const m = mean(nums);
+ return mean(nums.map((x) => (x - m) ** 2));
+}
+
+export function stdev(nums: number[]): number {
+ return Math.sqrt(variance(nums));
+}
+
+export function max(nums: number[]): number {
+ let ans = -Infinity;
+ for (let n of nums) {
+ if (n > ans) {
+ ans = n;
+ }
+ }
+ return ans;
+}
+
+export function min(nums: number[]): number {
+ let ans = Infinity;
+ for (let n of nums) {
+ if (n < ans) {
+ ans = n;
+ }
+ }
+ return ans;
+}
+
+export function count(nums: number[]): number {
+ return nums.length;
+}
diff --git a/packages/graphic-walker/src/lib/viewQuery.ts b/packages/graphic-walker/src/lib/viewQuery.ts
index fcddb89f..b023d5d6 100644
--- a/packages/graphic-walker/src/lib/viewQuery.ts
+++ b/packages/graphic-walker/src/lib/viewQuery.ts
@@ -2,10 +2,10 @@ import { IRow } from "visual-insights";
import { IMutField } from "../interfaces";
import { aggregate } from "./op/aggregate";
import { fold } from "./op/fold";
-import { IAggQuery, IBinQuery, IFoldQuery } from "./interfaces";
+import { IAggQuery, IBinQuery, IFoldQuery, IRawQuery } from "./interfaces";
import { bin } from "./op/bin";
-export type IViewQuery = IAggQuery | IFoldQuery | IBinQuery;
+export type IViewQuery = IAggQuery | IFoldQuery | IBinQuery | IRawQuery;
export function queryView (rawData: IRow[], metas: IMutField[], query: IViewQuery) {
switch (query.op) {
@@ -15,6 +15,7 @@ export function queryView (rawData: IRow[], metas: IMutField[], query: IViewQuer
return fold(rawData, query);
case 'bin':
return bin(rawData, query);
+ case 'raw':
default:
return rawData;
}
diff --git a/packages/graphic-walker/src/renderer/index.tsx b/packages/graphic-walker/src/renderer/index.tsx
index d87da93c..a7b32ac2 100644
--- a/packages/graphic-walker/src/renderer/index.tsx
+++ b/packages/graphic-walker/src/renderer/index.tsx
@@ -1,12 +1,13 @@
-import { observer } from "mobx-react-lite";
-import React, { useState, useEffect, forwardRef } from "react";
-import { applyFilter, applyViewQuery, transformDataService } from "../services";
-import { IDarkMode, IThemeKey } from "../interfaces";
-import SpecRenderer from "./specRenderer";
-import { runInAction, toJS } from 'mobx';
-import { Resizable } from 're-resizable';
+import { observer } from 'mobx-react-lite';
+import React, { useState, useEffect, forwardRef } from 'react';
+import { applyFilter, applyViewQuery, transformDataService } from '../services';
+import { DeepReadonly, DraggableFieldState, IDarkMode, IRow, IThemeKey, IVisualConfig } from '../interfaces';
+import SpecRenderer from './specRenderer';
+import { toJS } from 'mobx';
import { useGlobalStore } from '../store';
-import ReactVega, { IReactVegaHandler } from '../vis/react-vega';
+import { IReactVegaHandler } from '../vis/react-vega';
+import { unstable_batchedUpdates } from 'react-dom';
+import { initEncoding, initVisualConfig } from '../store/visualSpecStore';
interface RendererProps {
themeKey?: IThemeKey;
@@ -14,40 +15,56 @@ interface RendererProps {
}
const Renderer = forwardRef<IReactVegaHandler, RendererProps>(function (props, ref) {
const { themeKey, dark } = props;
+ const [waiting, setWaiting] = useState<boolean>(false);
const { vizStore, commonStore } = useGlobalStore();
const { allFields, viewFilters, viewDimensions, viewMeasures } = vizStore;
const { currentDataset } = commonStore;
const { dataSource } = currentDataset;
+ const [viewConfig, setViewConfig] = useState<IVisualConfig>(initVisualConfig);
+ const [encodings, setEncodings] = useState<DeepReadonly<DraggableFieldState>>(initEncoding);
- const [viewData, setViewData] = useState(dataSource);
+ const [viewData, setViewData] = useState<IRow[]>([]);
useEffect(() => {
+ setWaiting(true);
applyFilter(dataSource, viewFilters)
.then((data) => transformDataService(data, allFields))
.then((d) => {
- setViewData(d);
+ // setViewData(d);
+ const dims = viewDimensions;
+ const meas = viewMeasures;
+ const config = toJS(vizStore.visualConfig);
+ return applyViewQuery(d, dims.concat(meas), {
+ op: config.defaultAggregated ? 'aggregate' : 'raw',
+ groupBy: dims.map((f) => f.fid),
+ agg: Object.fromEntries(meas.map((f) => [f.fid, f.aggName as any])),
+ });
+ })
+ .then((data) => {
+ unstable_batchedUpdates(() => {
+ setViewData(data);
+ setWaiting(false);
+ setEncodings(toJS(vizStore.draggableFieldState));
+ setViewConfig(toJS(vizStore.visualConfig));
+ });
})
.catch((err) => {
console.error(err);
+ setWaiting(false);
});
- }, [dataSource, viewFilters, allFields]);
-
- useEffect(() => {
- const dims = vizStore.viewDimensions
- const meas = vizStore.viewMeasures;
- applyViewQuery(dataSource, dims.concat(meas), {
- op: 'aggregate',
- groupBy: dims.map(f => f.fid),
- agg: Object.fromEntries(meas.map(f => [f.fid, f.aggName as any]))
- }).then(data => {
- setViewData(data);
- }).catch((err) => {
- console.error(err);
- });
- }, [dataSource, viewDimensions, viewMeasures]);
-
+ }, [dataSource, viewFilters, allFields, viewDimensions, viewMeasures]);
- return <SpecRenderer data={viewData} ref={ref} themeKey={themeKey} dark={dark} />;
+ return (
+ <SpecRenderer
+ loading={waiting}
+ data={viewData}
+ ref={ref}
+ themeKey={themeKey}
+ dark={dark}
+ draggableFieldState={encodings}
+ visualConfig={viewConfig}
+ />
+ );
});
export default observer(Renderer);
diff --git a/packages/graphic-walker/src/renderer/specRenderer.tsx b/packages/graphic-walker/src/renderer/specRenderer.tsx
index 259b7e21..d1492933 100644
--- a/packages/graphic-walker/src/renderer/specRenderer.tsx
+++ b/packages/graphic-walker/src/renderer/specRenderer.tsx
@@ -1,40 +1,46 @@
-import { runInAction, toJS } from "mobx";
-import { observer } from "mobx-react-lite";
-import { Resizable } from "re-resizable";
-import React, { useState, useCallback, useEffect, useRef, forwardRef, useMemo } from "react";
-import { applyFilter } from "../services";
-import { useGlobalStore } from "../store";
-import ReactVega, { IReactVegaHandler } from "../vis/react-vega";
-import { IDarkMode, IRow, IThemeKey } from "../interfaces";
+import { runInAction } from 'mobx';
+import { Resizable } from 're-resizable';
+import React, { useCallback, forwardRef, useMemo } from 'react';
+
+import { useGlobalStore } from '../store';
+import ReactVega, { IReactVegaHandler } from '../vis/react-vega';
+import { DeepReadonly, DraggableFieldState, IDarkMode, IRow, IThemeKey, IVisualConfig } from '../interfaces';
+import LoadingLayer from '../components/loadingLayer';
interface SpecRendererProps {
themeKey?: IThemeKey;
dark?: IDarkMode;
data: IRow[];
+ loading: boolean;
+ draggableFieldState: DeepReadonly<DraggableFieldState>;
+ visualConfig: IVisualConfig;
}
const SpecRenderer = forwardRef<IReactVegaHandler, SpecRendererProps>(function (
- { themeKey, dark, data },
+ { themeKey, dark, data, loading, draggableFieldState, visualConfig },
ref
) {
const { vizStore, commonStore } = useGlobalStore();
- const { draggableFieldState, visualConfig } = vizStore;
+ // const { draggableFieldState, visualConfig } = vizStore;
const { geoms, interactiveScale, defaultAggregated, stack, showActions, size, exploration } = visualConfig;
- const rows = toJS(draggableFieldState.rows);
- const columns = toJS(draggableFieldState.columns);
- const color = toJS(draggableFieldState.color);
- const opacity = toJS(draggableFieldState.opacity);
- const shape = toJS(draggableFieldState.shape);
- const theta = toJS(draggableFieldState.theta);
- const radius = toJS(draggableFieldState.radius);
- const sizeChannel = toJS(draggableFieldState.size);
+ const rows = draggableFieldState.rows;
+ const columns = draggableFieldState.columns;
+ const color = draggableFieldState.color;
+ const opacity = draggableFieldState.opacity;
+ const shape = draggableFieldState.shape;
+ const theta = draggableFieldState.theta;
+ const radius = draggableFieldState.radius;
+ const sizeChannel = draggableFieldState.size;
- const rowLeftFacetFields = rows.slice(0, -1).filter((f) => f.analyticType === "dimension");
- const colLeftFacetFields = columns.slice(0, -1).filter((f) => f.analyticType === "dimension");
+ const rowLeftFacetFields = useMemo(() => rows.slice(0, -1).filter((f) => f.analyticType === 'dimension'), [rows]);
+ const colLeftFacetFields = useMemo(
+ () => columns.slice(0, -1).filter((f) => f.analyticType === 'dimension'),
+ [columns]
+ );
const hasFacet = rowLeftFacetFields.length > 0 || colLeftFacetFields.length > 0;
- const shouldTriggerMenu = exploration.mode === "none";
+ const shouldTriggerMenu = exploration.mode === 'none';
const handleGeomClick = useCallback(
(values: any, e: any) => {
@@ -48,15 +54,15 @@ const SpecRenderer = forwardRef<IReactVegaHandler, SpecRendererProps>(function (
},
[shouldTriggerMenu]
);
- const enableResize = size.mode === "fixed" && !hasFacet;
+ const enableResize = size.mode === 'fixed' && !hasFacet;
return (
<Resizable
- className={enableResize ? "border-blue-400 border-2 overflow-hidden" : ""}
- style={{ padding: "12px" }}
+ className={enableResize ? 'border-blue-400 border-2 overflow-hidden' : ''}
+ style={{ padding: '12px' }}
onResizeStop={(e, direction, ref, d) => {
vizStore.setChartLayout({
- mode: "fixed",
+ mode: 'fixed',
width: size.width + d.width,
height: size.height + d.height,
});
@@ -76,10 +82,11 @@ const SpecRenderer = forwardRef<IReactVegaHandler, SpecRendererProps>(function (
}
}
size={{
- width: size.width + "px",
- height: size.height + "px",
+ width: size.width + 'px',
+ height: size.height + 'px',
}}
>
+ {loading && <LoadingLayer />}
<ReactVega
layoutMode={size.mode}
interactiveScale={interactiveScale}
@@ -99,8 +106,8 @@ const SpecRenderer = forwardRef<IReactVegaHandler, SpecRendererProps>(function (
width={size.width - 12 * 4}
height={size.height - 12 * 4}
ref={ref}
- brushEncoding={exploration.mode === "brush" ? exploration.brushDirection : "none"}
- selectEncoding={exploration.mode === "point" ? "default" : "none"}
+ brushEncoding={exploration.mode === 'brush' ? exploration.brushDirection : 'none'}
+ selectEncoding={exploration.mode === 'point' ? 'default' : 'none'}
onGeomClick={handleGeomClick}
themeKey={themeKey}
dark={dark}
@@ -109,4 +116,4 @@ const SpecRenderer = forwardRef<IReactVegaHandler, SpecRendererProps>(function (
);
});
-export default observer(SpecRenderer);
+export default SpecRenderer;
diff --git a/packages/graphic-walker/src/store/visualSpecStore.ts b/packages/graphic-walker/src/store/visualSpecStore.ts
index ceda14a8..d493f47a 100644
--- a/packages/graphic-walker/src/store/visualSpecStore.ts
+++ b/packages/graphic-walker/src/store/visualSpecStore.ts
@@ -41,7 +41,7 @@ function geomAdapter(geom: string) {
}
}
-function initEncoding(): DraggableFieldState {
+export function initEncoding(): DraggableFieldState {
return {
dimensions: [],
measures: [],
@@ -59,7 +59,7 @@ function initEncoding(): DraggableFieldState {
};
}
-function initVisualConfig(): IVisualConfig {
+export function initVisualConfig(): IVisualConfig {
return {
defaultAggregated: true,
geoms: [GEMO_TYPES[0]!],
diff --git a/packages/graphic-walker/src/vis/react-vega.tsx b/packages/graphic-walker/src/vis/react-vega.tsx
index 96c31099..f745527e 100644
--- a/packages/graphic-walker/src/vis/react-vega.tsx
+++ b/packages/graphic-walker/src/vis/react-vega.tsx
@@ -3,16 +3,15 @@ import embed from 'vega-embed';
import { Subject, Subscription } from 'rxjs'
import * as op from 'rxjs/operators';
import type { ScenegraphEvent, View } from 'vega';
-import { ISemanticType } from 'visual-insights';
import styled from 'styled-components';
-import { autoMark } from '../utils/autoMark';
-import { COUNT_FIELD_ID } from '../constants';
import { IViewField, IRow, IStackMode, IDarkMode, IThemeKey } from '../interfaces';
import { useTranslation } from 'react-i18next';
import { getVegaTimeFormatRules } from './temporalFormat';
import { builtInThemes } from './theme';
import { useCurrentMediaTheme } from '../utils/media';
+import { SingleViewProps, getSingleView } from './spec/view';
+import { NULL_FIELD } from './spec/field';
const CanvaContainer = styled.div<{rowSize: number; colSize: number;}>`
display: grid;
@@ -52,14 +51,7 @@ interface ReactVegaProps {
themeKey?: IThemeKey;
dark?: IDarkMode;
}
-const NULL_FIELD: IViewField = {
- dragId: '',
- fid: '',
- name: '',
- semanticType: 'quantitative',
- analyticType: 'measure',
- aggName: 'sum'
-}
+
const click$ = new Subject<ScenegraphEvent>();
const selection$ = new Subject<any>();
const geomClick$ = selection$.pipe(
@@ -71,9 +63,6 @@ const geomClick$ = selection$.pipe(
return false
})
);
-function getFieldType(field: IViewField): 'quantitative' | 'nominal' | 'ordinal' | 'temporal' {
- return field.semanticType
-}
const BRUSH_SIGNAL_NAME = "__gw_brush__";
const POINT_SIGNAL_NAME = "__gw_point__";
@@ -85,301 +74,7 @@ interface ParamStoreEntry {
data: any;
}
-interface SingleViewProps {
- x: IViewField;
- y: IViewField;
- color: IViewField;
- opacity: IViewField;
- size: IViewField;
- shape: IViewField,
- xOffset: IViewField;
- yOffset: IViewField;
- row: IViewField;
- column: IViewField;
- theta: IViewField;
- radius: IViewField;
- defaultAggregated: boolean;
- stack: IStackMode;
- geomType: string;
- enableCrossFilter: boolean;
- asCrossFilterTrigger: boolean;
- selectEncoding: 'default' | 'none';
- brushEncoding: 'x' | 'y' | 'default' | 'none';
- hideLegend?: boolean;
-}
-
-function availableChannels (geomType: string): Set<string> {
- if (geomType === 'arc') {
- return new Set(['opacity', 'color', 'size', 'theta', 'radius'])
- }
- return new Set(['column', 'opacity', 'color', 'row', 'size', 'x', 'y', 'xOffset', 'yOffset', 'shape'])
-}
-interface EncodeProps extends Pick<SingleViewProps, 'column' | 'opacity' | 'color' | 'row' | 'size' | 'x' | 'y' | 'xOffset' | 'yOffset' | 'shape' | 'theta' | 'radius'> {
- geomType: string;
-}
-function channelEncode(props: EncodeProps) {
- const avcs = availableChannels(props.geomType)
- const encoding: {[key: string]: any} = {}
- Object.keys(props).filter(c => avcs.has(c)).forEach(c => {
- if (props[c] !== NULL_FIELD) {
- encoding[c] = {
- field: props[c].fid,
- title: props[c].name,
- type: props[c].semanticType,
- }
- if (props[c].analyticType !== 'measure') {
- // if `aggregate` is set to null,
- // do not aggregate this field
- encoding[c].aggregate = null;
- }
- if (props[c].analyticType === 'measure') {
- encoding[c].type = 'quantitative'
- }
- }
- })
- // FIXME: temporal fix, only for x and y relative order
- if (encoding.x && encoding.y) {
- if ((props.x.sort && props.x.sort) || (props.y && props.y.sort)) {
- if (props.x.sort !== 'none' && (props.y.sort === 'none' || !Boolean(props.y.sort))) {
- encoding.x.sort = {
- encoding: 'y',
- order: props.x.sort
- }
- } else if (props.y.sort && props.y.sort !== 'none' && (props.x.sort === 'none' || !Boolean(props.x.sort))) {
- encoding.y.sort = {
- encoding: 'x',
- order: props.y.sort
- }
- }
- }
- }
- return encoding
-}
-function channelAggregate(encoding: {[key: string]: any}, fields: IViewField[]) {
- Object.values(encoding).forEach(c => {
- const targetField = fields.find(f => f.fid === c.field && !('aggregate' in c));
- if (targetField && targetField.fid === COUNT_FIELD_ID) {
- c.field = undefined;
- c.aggregate = 'count';
- c.title = 'Count'
- } else if (targetField && targetField.analyticType === 'measure') {
- c.title = `${targetField.aggName}(${targetField.name})`;
- c.aggregate = targetField.aggName;
- }
- })
-}
-function channelStack(encoding: {[key: string]: any}, stackMode: IStackMode) {
- if (stackMode === 'stack') return;
- if (encoding.x && encoding.x.type === 'quantitative') {
- encoding.x.stack = stackMode === 'none' ? null : 'normalize'
- }
- if (encoding.y && encoding.y.type === 'quantitative') {
- encoding.y.stack = stackMode === 'none' ? null : 'normalize'
- }
-}
-// TODO: xOffset等通道的特性不太稳定,建议后续vega相关特性稳定后,再使用。
-// 1. 场景太细,仅仅对对应的坐标轴是nominal(可能由ordinal)时,才可用
-// 2. 部分geom type会出现bug,如line,会出现组间的错误连接
-// "vega": "^5.22.0",
-// "vega-embed": "^6.20.8",
-// "vega-lite": "^5.2.0",
-function getSingleView(props: SingleViewProps) {
- const {
- x,
- y,
- color,
- opacity,
- size,
- shape,
- theta,
- radius,
- row,
- column,
- xOffset,
- yOffset,
- defaultAggregated,
- stack,
- geomType,
- selectEncoding,
- brushEncoding,
- enableCrossFilter,
- asCrossFilterTrigger,
- hideLegend = false,
- } = props
- const fields: IViewField[] = [x, y, color, opacity, size, shape, row, column, xOffset, yOffset, theta, radius]
- let markType = geomType;
- let config: any = {};
- if (hideLegend) {
- config.legend = {
- disable: true
- };
- }
- if (geomType === 'auto') {
- const types: ISemanticType[] = [];
- if (x !== NULL_FIELD) types.push(x.semanticType)//types.push(getFieldType(x));
- if (y !== NULL_FIELD) types.push(y.semanticType)//types.push(getFieldType(yField));
- markType = autoMark(types);
- }
-
- let encoding = channelEncode({ geomType: markType, x, y, color, opacity, size, shape, row, column, xOffset, yOffset, theta, radius })
- if (defaultAggregated) {
- channelAggregate(encoding, fields);
- }
- channelStack(encoding, stack);
- if (!enableCrossFilter || brushEncoding === 'none' && selectEncoding === 'none') {
- return {
- config,
- mark: {
- type: markType,
- opacity: 0.96,
- tooltip: true
- },
- encoding
- };
- }
- const mark = {
- type: markType,
- opacity: 0.96,
- tooltip: true
- };
-
- // TODO:
- // 鉴于 Vega 中使用 layer 会导致一些难以覆盖的预期外行为,
- // 破坏掉引入交互后视图的正确性,
- // 目前不使用 layer 来实现交互(注掉以下代码)。
- // 考虑 layer 的目的是 layer + condition 可以用于同时展现“全集”(context)和“选中”两层结构,尤其对于聚合数据有分析帮助;
- // 同时,不需要关心作为筛选器的是哪一张图。
- // 现在采用临时方案,区别产生筛选的来源,并对其他图仅借助 transform 展现筛选后的数据。
- // #[BEGIN bad-layer-interaction]
- // const shouldUseMultipleLayers = brushEncoding !== 'none' && Object.values(encoding).some(channel => {
- // return typeof channel.aggregate === 'string' && /* 这种 case 对应行数 */ typeof channel.field === 'string';
- // });
- // if (shouldUseMultipleLayers) {
- // if (['column', 'row'].some(key => key in encoding && encoding[key].length > 0)) {
- // // 这种情况 Vega 不能处理,是因为 Vega 不支持在 layer 中使用 column / row channel,
- // // 会导致渲染出来的视图无法与不使用交互时的结果不变。
- // return {
- // params: [
- // {
- // name: BRUSH_SIGNAL_NAME,
- // select: { type: 'interval', encodings: brushEncoding === 'default' ? undefined : [brushEncoding] },
- // },
- // ],
- // mark,
- // encoding: {
- // ...encoding,
- // color: {
- // condition: {
- // ...encoding.color,
- // param: BRUSH_SIGNAL_NAME,
- // },
- // value: '#888',
- // },
- // },
- // };
- // }
- // return {
- // layer: [
- // {
- // params: [
- // {
- // name: BRUSH_SIGNAL_NAME,
- // select: { type: 'interval', encodings: brushEncoding === 'default' ? undefined : [brushEncoding] },
- // },
- // ],
- // mark,
- // encoding: {
- // ...encoding,
- // color: 'color' in encoding ? {
- // condition: {
- // ...encoding.color,
- // test: 'false',
- // },
- // value: '#888',
- // } : {
- // value: '#888',
- // },
- // },
- // },
- // {
- // transform: [{ filter: { param: BRUSH_SIGNAL_NAME }}],
- // mark,
- // encoding: {
- // ...encoding,
- // color: encoding.color ?? { value: 'steelblue' },
- // },
- // },
- // ],
- // };
- // } else if (brushEncoding !== 'none') {
- // return {
- // params: [
- // {
- // name: BRUSH_SIGNAL_NAME,
- // select: { type: 'interval', encodings: brushEncoding === 'default' ? undefined : [brushEncoding] },
- // },
- // ],
- // mark,
- // encoding: {
- // ...encoding,
- // color: {
- // condition: {
- // ...encoding.color,
- // param: BRUSH_SIGNAL_NAME,
- // },
- // value: '#888',
- // },
- // },
- // };
- // }
- // #[END bad-layer-interaction]
-
- if (brushEncoding !== 'none') {
- return {
- config,
- transform: asCrossFilterTrigger ? [] : [
- { filter: { param: BRUSH_SIGNAL_NAME } }
- ],
- params: [
- // {
- // name: BRUSH_SIGNAL_DISPLAY_NAME,
- // select: { type: 'interval', encodings: brushEncoding === 'default' ? undefined : [brushEncoding] },
- // on: '__YOU_CANNOT_MODIFY_THIS_SIGNAL__',
- // },
- {
- name: BRUSH_SIGNAL_NAME,
- select: { type: 'interval', encodings: brushEncoding === 'default' ? undefined : [brushEncoding] },
- },
- ],
- mark,
- encoding,
- };
- }
- return {
- config,
- transform: asCrossFilterTrigger ? [] : [
- { filter: { param: POINT_SIGNAL_NAME } }
- ],
- params: [
- {
- name: POINT_SIGNAL_NAME,
- select: { type: 'point' },
- },
- ],
- mark,
- encoding: asCrossFilterTrigger ? {
- ...encoding,
- color: {
- condition: {
- ...encoding.color,
- param: POINT_SIGNAL_NAME,
- },
- value: '#888',
- },
- } : encoding,
- };
-}
const ReactVega = forwardRef<IReactVegaHandler, ReactVegaProps>(function ReactVega (props, ref) {
const {
dataSource = [],
@@ -405,8 +100,6 @@ const ReactVega = forwardRef<IReactVegaHandler, ReactVegaProps>(function ReactVe
themeKey = 'vega',
dark = 'media'
} = props;
- // const container = useRef<HTMLDivElement>(null);
- // const containers = useRef<(HTMLDivElement | null)[]>([]);
const [viewPlaceholders, setViewPlaceholders] = useState<React.MutableRefObject<HTMLDivElement>[]>([]);
const { i18n } = useTranslation();
const mediaTheme = useCurrentMediaTheme(dark);
@@ -504,28 +197,12 @@ const ReactVega = forwardRef<IReactVegaHandler, ReactVegaProps>(function ReactVe
enableCrossFilter: false,
asCrossFilterTrigger: false,
});
- // if (layoutMode === 'fixed') {
- // spec.width = 800;
- // spec.height = 600;
- // }
+
spec.mark = singleView.mark;
if ('encoding' in singleView) {
spec.encoding = singleView.encoding;
}
- // #[BEGIN bad-layer-interaction]
- // if ('layer' in singleView) {
- // if ('params' in spec) {
- // const basicParams = spec['params'];
- // delete spec['params'];
- // singleView.layer![0].params = [...basicParams, ...singleView.layer![0].params ?? []];
- // }
- // spec.layer = singleView.layer;
- // } else if ('params' in singleView) {
- // spec.params.push(...singleView.params!);
- // }
- // #[END bad-layer-interaction]
-
if ('params' in singleView) {
spec.params.push(...singleView.params!);
}
@@ -592,19 +269,6 @@ const ReactVega = forwardRef<IReactVegaHandler, ReactVegaProps>(function ReactVe
const node = i * colRepeatFields.length + j < viewPlaceholders.length ? viewPlaceholders[i * colRepeatFields.length + j].current : null
let commonSpec = { ...spec };
- // #[BEGIN bad-layer-interaction]
- // if ('layer' in singleView) {
- // if ('params' in commonSpec) {
- // const { params: basicParams, ...spec } = commonSpec;
- // commonSpec = spec;
- // singleView.layer![0].params = [...basicParams, ...singleView.layer![0].params ?? []];
- // }
- // commonSpec.layer = singleView.layer;
- // } else if ('params' in singleView) {
- // commonSpec.params = [...commonSpec.params, ...singleView.params!];
- // }
- // #[END bad-layer-interaction]
-
if ('params' in singleView) {
commonSpec.params = [...commonSpec.params, ...singleView.params!];
}
diff --git a/packages/graphic-walker/src/vis/spec/aggregate.ts b/packages/graphic-walker/src/vis/spec/aggregate.ts
new file mode 100644
index 00000000..8c46142c
--- /dev/null
+++ b/packages/graphic-walker/src/vis/spec/aggregate.ts
@@ -0,0 +1,16 @@
+import { COUNT_FIELD_ID } from '../../constants';
+import { IViewField } from '../../interfaces';
+
+export function channelAggregate(encoding: { [key: string]: any }, fields: IViewField[]) {
+ Object.values(encoding).forEach((c) => {
+ const targetField = fields.find((f) => f.fid === c.field && !('aggregate' in c));
+ if (targetField && targetField.fid === COUNT_FIELD_ID) {
+ c.field = undefined;
+ // c.aggregate = 'count';
+ c.title = 'Count';
+ } else if (targetField && targetField.analyticType === 'measure') {
+ c.title = `${targetField.aggName}(${targetField.name})`;
+ // c.aggregate = targetField.aggName;
+ }
+ });
+}
diff --git a/packages/graphic-walker/src/vis/spec/encode.ts b/packages/graphic-walker/src/vis/spec/encode.ts
new file mode 100644
index 00000000..268b3c84
--- /dev/null
+++ b/packages/graphic-walker/src/vis/spec/encode.ts
@@ -0,0 +1,63 @@
+import { IViewField } from '../../interfaces';
+import { NULL_FIELD } from './field';
+export interface IEncodeProps {
+ geomType: string;
+ x: IViewField;
+ y: IViewField;
+ color: IViewField;
+ opacity: IViewField;
+ size: IViewField;
+ shape: IViewField;
+ xOffset: IViewField;
+ yOffset: IViewField;
+ row: IViewField;
+ column: IViewField;
+ theta: IViewField;
+ radius: IViewField;
+}
+function availableChannels(geomType: string): Set<string> {
+ if (geomType === 'arc') {
+ return new Set(['opacity', 'color', 'size', 'theta', 'radius']);
+ }
+ return new Set(['column', 'opacity', 'color', 'row', 'size', 'x', 'y', 'xOffset', 'yOffset', 'shape']);
+}
+export function channelEncode(props: IEncodeProps) {
+ const avcs = availableChannels(props.geomType);
+ const encoding: { [key: string]: any } = {};
+ Object.keys(props)
+ .filter((c) => avcs.has(c))
+ .forEach((c) => {
+ if (props[c] !== NULL_FIELD) {
+ encoding[c] = {
+ field: props[c].fid,
+ title: props[c].name,
+ type: props[c].semanticType,
+ };
+ if (props[c].analyticType !== 'measure') {
+ // if `aggregate` is set to null,
+ // do not aggregate this field
+ encoding[c].aggregate = null;
+ }
+ if (props[c].analyticType === 'measure') {
+ encoding[c].type = 'quantitative';
+ }
+ }
+ });
+ // FIXME: temporal fix, only for x and y relative order
+ if (encoding.x && encoding.y) {
+ if ((props.x.sort && props.x.sort) || (props.y && props.y.sort)) {
+ if (props.x.sort !== 'none' && (props.y.sort === 'none' || !Boolean(props.y.sort))) {
+ encoding.x.sort = {
+ encoding: 'y',
+ order: props.x.sort,
+ };
+ } else if (props.y.sort && props.y.sort !== 'none' && (props.x.sort === 'none' || !Boolean(props.x.sort))) {
+ encoding.y.sort = {
+ encoding: 'x',
+ order: props.y.sort,
+ };
+ }
+ }
+ }
+ return encoding;
+}
diff --git a/packages/graphic-walker/src/vis/spec/field.ts b/packages/graphic-walker/src/vis/spec/field.ts
new file mode 100644
index 00000000..60959ce4
--- /dev/null
+++ b/packages/graphic-walker/src/vis/spec/field.ts
@@ -0,0 +1,10 @@
+import { IViewField } from "../../interfaces";
+
+export const NULL_FIELD: IViewField = {
+ dragId: '',
+ fid: '',
+ name: '',
+ semanticType: 'quantitative',
+ analyticType: 'measure',
+ aggName: 'sum',
+};
diff --git a/packages/graphic-walker/src/vis/spec/mark.ts b/packages/graphic-walker/src/vis/spec/mark.ts
new file mode 100644
index 00000000..495310e5
--- /dev/null
+++ b/packages/graphic-walker/src/vis/spec/mark.ts
@@ -0,0 +1,30 @@
+import { ISemanticType } from "visual-insights";
+
+/**
+ *
+ * @param semanticTypeList semanticTypeList.length <= 2,调用时,手动将columns 和 rows的最后一个元素组合传进来
+ * @returns geom(mark) type
+ */
+export function autoMark(semanticTypeList: ISemanticType[]): string {
+ if (semanticTypeList.length < 2) {
+ if (semanticTypeList[0] === "temporal") return "tick";
+ return "bar";
+ }
+ const couter: Map<ISemanticType, number> = new Map();
+ (["nominal", "ordinal", "quantitative", "temporal"] as ISemanticType[]).forEach((s) => {
+ couter.set(s, 0);
+ });
+ for (let st of semanticTypeList) {
+ couter.set(st, couter.get(st)! + 1);
+ }
+ if (couter.get("nominal") === 1 || couter.get("ordinal") === 1) {
+ return "bar";
+ }
+ if (couter.get("temporal") === 1 && couter.get("quantitative") === 1) {
+ return "line";
+ }
+ if (couter.get("quantitative") === 2) {
+ return "point";
+ }
+ return "point";
+}
diff --git a/packages/graphic-walker/src/vis/spec/stack.ts b/packages/graphic-walker/src/vis/spec/stack.ts
new file mode 100644
index 00000000..f45526b0
--- /dev/null
+++ b/packages/graphic-walker/src/vis/spec/stack.ts
@@ -0,0 +1,11 @@
+import { IStackMode } from "../../interfaces";
+
+export function channelStack(encoding: { [key: string]: any }, stackMode: IStackMode) {
+ if (stackMode === 'stack') return;
+ if (encoding.x && encoding.x.type === 'quantitative') {
+ encoding.x.stack = stackMode === 'none' ? null : 'normalize';
+ }
+ if (encoding.y && encoding.y.type === 'quantitative') {
+ encoding.y.stack = stackMode === 'none' ? null : 'normalize';
+ }
+}
diff --git a/packages/graphic-walker/src/vis/spec/view.ts b/packages/graphic-walker/src/vis/spec/view.ts
new file mode 100644
index 00000000..2a8f7cf8
--- /dev/null
+++ b/packages/graphic-walker/src/vis/spec/view.ts
@@ -0,0 +1,138 @@
+import { ISemanticType } from 'visual-insights';
+import { IStackMode, IViewField } from '../../interfaces';
+import { autoMark } from './mark';
+import { NULL_FIELD } from './field';
+import { channelAggregate } from './aggregate';
+import { IEncodeProps, channelEncode } from './encode';
+import { channelStack } from './stack'
+
+const BRUSH_SIGNAL_NAME = '__gw_brush__';
+const POINT_SIGNAL_NAME = '__gw_point__';
+export interface SingleViewProps extends IEncodeProps {
+
+ defaultAggregated: boolean;
+ stack: IStackMode;
+ enableCrossFilter: boolean;
+ asCrossFilterTrigger: boolean;
+ selectEncoding: 'default' | 'none';
+ brushEncoding: 'x' | 'y' | 'default' | 'none';
+ hideLegend?: boolean;
+}
+export function getSingleView(props: SingleViewProps) {
+ const {
+ x,
+ y,
+ color,
+ opacity,
+ size,
+ shape,
+ theta,
+ radius,
+ row,
+ column,
+ xOffset,
+ yOffset,
+ defaultAggregated,
+ stack,
+ geomType,
+ selectEncoding,
+ brushEncoding,
+ enableCrossFilter,
+ asCrossFilterTrigger,
+ hideLegend = false,
+ } = props;
+ const fields: IViewField[] = [x, y, color, opacity, size, shape, row, column, xOffset, yOffset, theta, radius];
+ let markType = geomType;
+ let config: any = {};
+ if (hideLegend) {
+ config.legend = {
+ disable: true,
+ };
+ }
+ if (geomType === 'auto') {
+ const types: ISemanticType[] = [];
+ if (x !== NULL_FIELD) types.push(x.semanticType); //types.push(getFieldType(x));
+ if (y !== NULL_FIELD) types.push(y.semanticType); //types.push(getFieldType(yField));
+ markType = autoMark(types);
+ }
+
+ let encoding = channelEncode({
+ geomType: markType,
+ x,
+ y,
+ color,
+ opacity,
+ size,
+ shape,
+ row,
+ column,
+ xOffset,
+ yOffset,
+ theta,
+ radius,
+ });
+ if (defaultAggregated) {
+ channelAggregate(encoding, fields);
+ }
+ channelStack(encoding, stack);
+ if (!enableCrossFilter || (brushEncoding === 'none' && selectEncoding === 'none')) {
+ return {
+ config,
+ mark: {
+ type: markType,
+ opacity: 0.96,
+ tooltip: true,
+ },
+ encoding,
+ };
+ }
+ const mark = {
+ type: markType,
+ opacity: 0.96,
+ tooltip: true,
+ };
+
+ if (brushEncoding !== 'none') {
+ return {
+ config,
+ transform: asCrossFilterTrigger ? [] : [{ filter: { param: BRUSH_SIGNAL_NAME } }],
+ params: [
+ // {
+ // name: BRUSH_SIGNAL_DISPLAY_NAME,
+ // select: { type: 'interval', encodings: brushEncoding === 'default' ? undefined : [brushEncoding] },
+ // on: '__YOU_CANNOT_MODIFY_THIS_SIGNAL__',
+ // },
+ {
+ name: BRUSH_SIGNAL_NAME,
+ select: { type: 'interval', encodings: brushEncoding === 'default' ? undefined : [brushEncoding] },
+ },
+ ],
+ mark,
+ encoding,
+ };
+ }
+
+ return {
+ config,
+ transform: asCrossFilterTrigger ? [] : [{ filter: { param: POINT_SIGNAL_NAME } }],
+ params: [
+ {
+ name: POINT_SIGNAL_NAME,
+ select: { type: 'point' },
+ },
+ ],
+ mark,
+ encoding: asCrossFilterTrigger
+ ? {
+ ...encoding,
+ color: {
+ condition: {
+ ...encoding.color,
+ param: POINT_SIGNAL_NAME,
+ },
+ value: '#888',
+ },
+ }
+ : encoding,
+ };
+}
diff --git a/packages/graphic-walker/src/workers/viewQuery.worker.js b/packages/graphic-walker/src/workers/viewQuery.worker.js
index ef97ec00..1e54907d 100644
--- a/packages/graphic-walker/src/workers/viewQuery.worker.js
+++ b/packages/graphic-walker/src/workers/viewQuery.worker.js
@@ -2,10 +2,9 @@ import { queryView } from '../lib/viewQuery'
const main = e => {
try {
const { dataSource, metas, query } = e.data;
-
const ans = queryView(dataSource, metas, query);
-
self.postMessage(ans);
+
} catch (err) {
// console.log(err.s)
// log err stack