An open source alternative to Tableau. Embeddable visual analytic
TypeScript bidatadata-analysisdata-miningdata-visualizationedak6skanarieslow-codepivot-tablereacttableautableau-alternativetypescriptvegavega-litevisualization
style: format code
ObservedObserverbee89e833d7a
diff --git a/packages/graphic-walker/src/App.tsx b/packages/graphic-walker/src/App.tsxindex 707bdfbe..e8985ec8 100644--- a/packages/graphic-walker/src/App.tsx+++ b/packages/graphic-walker/src/App.tsx@@ -20,7 +20,6 @@ import { preAnalysis, destroyWorker } from "./services";import VisNav from "./segments/visNav";import { mergeLocaleRes, setLocaleLanguage } from "./locales/i18n";import FilterField from "./fields/filterField";-import PageNav from "./components/pageNav";export interface EditorProps {dataSource?: IRow[];@@ -30,7 +29,6 @@ export interface EditorProps {i18nLang?: string;i18nResources?: { [lang: string]: Record<string, string | any> };keepAlive?: boolean;- fixContainer?: boolean;}const App: React.FC<EditorProps> = (props) => {diff --git a/packages/graphic-walker/src/fields/datasetFields/dimFields.tsx b/packages/graphic-walker/src/fields/datasetFields/dimFields.tsxindex ef249145..adef304f 100644--- a/packages/graphic-walker/src/fields/datasetFields/dimFields.tsx+++ b/packages/graphic-walker/src/fields/datasetFields/dimFields.tsx@@ -10,7 +10,7 @@ interface Props {}const DimFields: React.FC<Props> = props => {const { provided } = props;- const { vizStore, commonStore } = useGlobalStore();+ const { vizStore } = useGlobalStore();const dimensions = vizStore.draggableFieldState.dimensions;return <div {...provided.droppableProps} ref={provided.innerRef}>{dimensions.map((f, index) => (diff --git a/packages/graphic-walker/src/fields/datasetFields/meaFields.tsx b/packages/graphic-walker/src/fields/datasetFields/meaFields.tsxindex 14dca9db..09514860 100644--- a/packages/graphic-walker/src/fields/datasetFields/meaFields.tsx+++ b/packages/graphic-walker/src/fields/datasetFields/meaFields.tsx@@ -10,7 +10,7 @@ interface Props {}const MeaFields: React.FC<Props> = props => {const { provided } = props;- const { vizStore, commonStore } = useGlobalStore();+ const { vizStore } = useGlobalStore();const measures = vizStore.draggableFieldState.measures;return <div {...provided.droppableProps} ref={provided.innerRef}>{measures.map((f, index) => (diff --git a/packages/graphic-walker/src/fields/obComponents/obFContainer.tsx b/packages/graphic-walker/src/fields/obComponents/obFContainer.tsxindex 1c43f8cd..f56bbd9a 100644--- a/packages/graphic-walker/src/fields/obComponents/obFContainer.tsx+++ b/packages/graphic-walker/src/fields/obComponents/obFContainer.tsx@@ -18,7 +18,7 @@ interface FieldContainerProps {}const OBFieldContainer: React.FC<FieldContainerProps> = props => {const { provided, dkey } = props;- const { vizStore, commonStore } = useGlobalStore();+ const { vizStore} = useGlobalStore();const { draggableFieldState } = vizStore;return <FieldsContainer{...provided.droppableProps}diff --git a/packages/graphic-walker/src/index.tsx b/packages/graphic-walker/src/index.tsxindex c9ca603b..6b852e64 100644--- a/packages/graphic-walker/src/index.tsx+++ b/packages/graphic-walker/src/index.tsx@@ -17,7 +17,6 @@ export const ShadowDomContext = createContext<{ root: ShadowRoot | null }>({ rooexport const GraphicWalker: React.FC<EditorProps> = observer(props => {const [shadowRoot, setShadowRoot] = useState<ShadowRoot | null>(null);const rootRef = useRef<HTMLDivElement>(null);- const fixContainer = props.fixContainer ?? false;useEffect(() => {if (rootRef.current) {@@ -38,7 +37,7 @@ export const GraphicWalker: React.FC<EditorProps> = observer(props => {<style>{style}</style>{shadowRoot && (<StyleSheetManager target={shadowRoot}>- <StoreWrapper keepAlive={props.keepAlive} rootContainer={fixContainer ? rootRef.current : null}>+ <StoreWrapper keepAlive={props.keepAlive}><FieldsContextWrapper><ShadowDomContext.Provider value={{ root: shadowRoot }}><App {...props} />diff --git a/packages/graphic-walker/src/main.tsx b/packages/graphic-walker/src/main.tsxindex 96201f19..aef3f60f 100644--- a/packages/graphic-walker/src/main.tsx+++ b/packages/graphic-walker/src/main.tsx@@ -9,7 +9,7 @@ inject();ReactDOM.render(<React.StrictMode>- <GraphicWalker fixContainer />+ <GraphicWalker /></React.StrictMode>,document.getElementById("root"));diff --git a/packages/graphic-walker/src/store/commonStore.ts b/packages/graphic-walker/src/store/commonStore.tsindex 8ca3e860..db74cf22 100644--- a/packages/graphic-walker/src/store/commonStore.ts+++ b/packages/graphic-walker/src/store/commonStore.ts@@ -13,7 +13,6 @@ export class CommonStore {public showDSPanel: boolean = false;public showInsightBoard: boolean = false;public vizEmbededMenu: { show: boolean; position: [number, number] } = { show: false, position: [0, 0] };- public rootContainer: HTMLDivElement | null = null;public filters: Filters = {};constructor () {@@ -22,8 +21,7 @@ export class CommonStore {makeAutoObservable(this, {dataSources: observable.ref,tmpDataSource: observable.ref,- filters: observable.ref,- rootContainer: false+ filters: observable.ref});}public get currentDataset (): DataSet {diff --git a/packages/graphic-walker/src/store/index.tsx b/packages/graphic-walker/src/store/index.tsxindex b0cc0438..d2c660bb 100644--- a/packages/graphic-walker/src/store/index.tsx+++ b/packages/graphic-walker/src/store/index.tsx@@ -31,7 +31,6 @@ export function rebootGWStore() {interface StoreWrapperProps {keepAlive?: boolean;- rootContainer?: HTMLDivElement | null;}export class StoreWrapper extends React.Component<StoreWrapperProps> {constructor(props: StoreWrapperProps) {@@ -46,7 +45,6 @@ export class StoreWrapper extends React.Component<StoreWrapperProps> {}}render() {- initStore.commonStore.rootContainer = this.props.rootContainer ?? null;return <StoreContext.Provider value={initStore}>{ this.props.children }</StoreContext.Provider>diff --git a/packages/graphic-walker/src/store/visualSpecStore.ts b/packages/graphic-walker/src/store/visualSpecStore.tsindex 6f9e2f43..13c8762c 100644--- a/packages/graphic-walker/src/store/visualSpecStore.ts+++ b/packages/graphic-walker/src/store/visualSpecStore.ts@@ -1,6 +1,6 @@import { IReactionDisposer, makeAutoObservable, observable, reaction, toJS } from "mobx";-import produce from 'immer';-import { v4 as uuidv4 } from 'uuid';+import produce from "immer";+import { v4 as uuidv4 } from "uuid";import { Specification } from "visual-insights";import { DataSet, DraggableFieldState, IFilterRule, IViewField, IVisSpec, IVisualConfig } from "../interfaces";import { CHANNEL_LIMIT, GEMO_TYPES, MetaFieldKeys } from "../config";@@ -9,34 +9,34 @@ import { VisSpecWithHistory } from "../models/visSpecHistory";import { dumpsGWPureSpec, parseGWContent, parseGWPureSpec, stringifyGWContent } from "../utils/save";import { CommonStore } from "./commonStore";-function getChannelSizeLimit (channel: string): number {- if (typeof CHANNEL_LIMIT[channel] === 'undefined') return Infinity;+function getChannelSizeLimit(channel: string): number {+ if (typeof CHANNEL_LIMIT[channel] === "undefined") return Infinity;return CHANNEL_LIMIT[channel];}-function geomAdapter (geom: string) {+function geomAdapter(geom: string) {switch (geom) {- case 'interval':- return 'bar';- case 'line':- return 'line';- case 'boxplot':- return 'boxplot';- case 'area':- return 'area';- case 'point':- return 'point';- case 'arc':- return 'arc';- case 'circle':- return 'circle';- case 'heatmap':- return 'circle'- case 'rect':- return 'rect'- case 'tick':+ case "interval":+ return "bar";+ case "line":+ return "line";+ case "boxplot":+ return "boxplot";+ case "area":+ return "area";+ case "point":+ return "point";+ case "arc":+ return "arc";+ case "circle":+ return "circle";+ case "heatmap":+ return "circle";+ case "rect":+ return "rect";+ case "tick":default:- return 'tick'+ return "tick";}}@@ -57,32 +57,32 @@ function initEncoding(): DraggableFieldState {};}-function initVisualConfig (): IVisualConfig {+function initVisualConfig(): IVisualConfig {return {defaultAggregated: true,geoms: [GEMO_TYPES[0]!],- stack: 'stack',+ stack: "stack",showActions: false,interactiveScale: false,- sorted: 'none',+ sorted: "none",size: {- mode: 'auto',+ mode: "auto",width: 320,- height: 200+ height: 200,},exploration: {- mode: 'none',- brushDirection: 'default',+ mode: "none",+ brushDirection: "default",},- }+ };}type DeepReadonly<T extends Record<keyof any, any>> = {readonly [K in keyof T]: T[K] extends Record<keyof any, any> ? DeepReadonly<T[K]> : T[K];};-const forwardVisualConfigs = (backwards: ReturnType<typeof parseGWContent>['specList']): IVisSpec[] => {- return backwards.map(content => ({+const forwardVisualConfigs = (backwards: ReturnType<typeof parseGWContent>["specList"]): IVisSpec[] => {+ return backwards.map((content) => ({...content,config: {...initVisualConfig(),@@ -91,7 +91,6 @@ const forwardVisualConfigs = (backwards: ReturnType<typeof parseGWContent>['spec}));};-export class VizSpecStore {// public fields: IViewField[] = [];private commonStore: CommonStore;@@ -105,13 +104,13 @@ export class VizSpecStore {* Assignment or mutable operations applied to ANY members of this segment* is strictly FORBIDDEN.* Members of it can only be got as READONLY objects.- *+ ** If you're trying to change the value of it and let mobx catch the action to trigger an update,* please use `this.useMutable()` to access to a writable reference* (an `immer` draft) of `this.visList[this.visIndex]`.*/public readonly draggableFieldState: DeepReadonly<DraggableFieldState>;- private reactions: IReactionDisposer[] = []+ private reactions: IReactionDisposer[] = [];/*** This segment will always refers to the state of the active tab -* `this.visList[this.visIndex].config`.@@ -122,7 +121,7 @@ export class VizSpecStore {* Assignment or mutable operations applied to ANY members of this segment* is strictly FORBIDDEN.* Members of it can only be got as READONLY objects.- *+ ** If you're trying to change the value of it and let mobx catch the action to trigger an update,* please use `this.useMutable()` to access to a writable reference* (an `immer` draft) of `this.visList[this.visIndex]`.@@ -133,34 +132,42 @@ export class VizSpecStore {public canUndo = false;public canRedo = false;public editingFilterIdx: number | null = null;- constructor (commonStore: CommonStore) {+ constructor(commonStore: CommonStore) {this.commonStore = commonStore;this.draggableFieldState = initEncoding();this.visualConfig = initVisualConfig();- this.visList.push(new VisSpecWithHistory({- name: ['main.tablist.autoTitle', { idx: 1 }],- visId: uuidv4(),- config: this.visualConfig,- encodings: this.draggableFieldState,- }));+ this.visList.push(+ new VisSpecWithHistory({+ name: ["main.tablist.autoTitle", { idx: 1 }],+ visId: uuidv4(),+ config: this.visualConfig,+ encodings: this.draggableFieldState,+ })+ );makeAutoObservable(this, {visList: observable.shallow,// @ts-expect-error private fields are not supported- reactions: false+ reactions: false,});this.reactions.push(- reaction(() => commonStore.currentDataset, (dataset) => {- // this.initState();- this.initMetaState(dataset);- }),- reaction(() => this.visList[this.visIndex], frame => {- // @ts-ignore Allow assignment here to trigger watch- this.draggableFieldState = frame.encodings;- // @ts-ignore Allow assignment here to trigger watch- this.visualConfig = frame.config;- this.canUndo = frame.canUndo;- this.canRedo = frame.canRedo;- }),+ reaction(+ () => commonStore.currentDataset,+ (dataset) => {+ // this.initState();+ this.initMetaState(dataset);+ }+ ),+ reaction(+ () => this.visList[this.visIndex],+ (frame) => {+ // @ts-ignore Allow assignment here to trigger watch+ this.draggableFieldState = frame.encodings;+ // @ts-ignore Allow assignment here to trigger watch+ this.visualConfig = frame.config;+ this.canUndo = frame.canUndo;+ this.canRedo = frame.canRedo;+ }+ ));}private __dangerous_is_inside_useMutable__ = false;@@ -169,38 +176,38 @@ export class VizSpecStore {* because the state will be overwritten by the root `useMutable()` call,* update caused by recursive `useMutable()` call will be reverted or lead to unexpected behaviors.* Inline your invoking or just use block with IF statement to avoid this in your cases.- *+ ** Allow to change any deep member of `encodings` or `config`* in the active tab `this.visList[this.visIndex]`.- *+ ** - `tab.encodings`- *+ ** A mutable reference of `this.draggableFieldState`- *+ ** - `tab.config`- *+ ** A mutable reference of `this.visualConfig`*/- private useMutable(- cb: (tab: {- encodings: DraggableFieldState;- config: IVisualConfig;- }) => void,- ) {+ private useMutable(cb: (tab: { encodings: DraggableFieldState; config: IVisualConfig }) => void) {if (this.__dangerous_is_inside_useMutable__) {throw new Error(- 'A recursive call of useMutable() is detected, '- + 'this is prevented because update will be overwritten by parent execution context.'+ "A recursive call of useMutable() is detected, " ++ "this is prevented because update will be overwritten by parent execution context.");}this.__dangerous_is_inside_useMutable__ = true;- const { encodings, config } = produce({- encodings: this.visList[this.visIndex].encodings,- config: this.visList[this.visIndex].config,- }, draft => { cb(draft) }); // notice that cb() may unexpectedly returns a non-nullable value-+ const { encodings, config } = produce(+ {+ encodings: this.visList[this.visIndex].encodings,+ config: this.visList[this.visIndex].config,+ },+ (draft) => {+ cb(draft);+ }+ ); // notice that cb() may unexpectedly returns a non-nullable value+this.visList[this.visIndex].encodings = encodings;this.visList[this.visIndex].config = config;@@ -242,96 +249,98 @@ export class VizSpecStore {/*** dimension fields in visualization*/- public get viewDimensions (): IViewField[] {+ public get viewDimensions(): IViewField[] {const { draggableFieldState } = this;const state = toJS(draggableFieldState);const fields: IViewField[] = [];(Object.keys(state) as (keyof DraggableFieldState)[])- .filter(dkey => !MetaFieldKeys.includes(dkey))- .forEach(dkey => {- fields.push(...state[dkey].filter(f => f.analyticType === 'dimension'))- })+ .filter((dkey) => !MetaFieldKeys.includes(dkey))+ .forEach((dkey) => {+ fields.push(...state[dkey].filter((f) => f.analyticType === "dimension"));+ });return fields;}/*** dimension fields in visualization*/- public get viewMeasures (): IViewField[] {+ public get viewMeasures(): IViewField[] {const { draggableFieldState } = this;const state = toJS(draggableFieldState);const fields: IViewField[] = [];(Object.keys(state) as (keyof DraggableFieldState)[])- .filter(dkey => !MetaFieldKeys.includes(dkey))- .forEach(dkey => {- fields.push(...state[dkey].filter(f => f.analyticType === 'measure'))- })+ .filter((dkey) => !MetaFieldKeys.includes(dkey))+ .forEach((dkey) => {+ fields.push(...state[dkey].filter((f) => f.analyticType === "measure"));+ });return fields;}- public addVisualization () {- this.visList.push(new VisSpecWithHistory({- name: ['main.tablist.autoTitle', { idx: this.visList.length + 1 }],- visId: uuidv4(),- config: initVisualConfig(),- encodings: initEncoding()- }));+ public addVisualization() {+ this.visList.push(+ new VisSpecWithHistory({+ name: ["main.tablist.autoTitle", { idx: this.visList.length + 1 }],+ visId: uuidv4(),+ config: initVisualConfig(),+ encodings: initEncoding(),+ })+ );this.visIndex = this.visList.length - 1;}- public selectVisualization (visIndex: number) {+ public selectVisualization(visIndex: number) {this.visIndex = visIndex;}- public setVisName (visIndex: number, name: string) {+ public setVisName(visIndex: number, name: string) {this.useMutable(() => {this.visList[visIndex].name = [name];});}- public initState () {- this.useMutable(tab => {+ public initState() {+ this.useMutable((tab) => {tab.encodings = initEncoding();this.freezeHistory();});}- public initMetaState (dataset: DataSet) {+ public initMetaState(dataset: DataSet) {this.useMutable(({ encodings }) => {encodings.fields = dataset.rawFields.map((f) => ({dragId: uuidv4(),fid: f.fid,name: f.name || f.fid,- aggName: f.analyticType === 'measure' ? 'sum' : undefined,+ aggName: f.analyticType === "measure" ? "sum" : undefined,analyticType: f.analyticType,- semanticType: f.semanticType+ semanticType: f.semanticType,}));encodings.dimensions = dataset.rawFields- .filter(f => f.analyticType === 'dimension')+ .filter((f) => f.analyticType === "dimension").map((f) => ({dragId: uuidv4(),fid: f.fid,name: f.name || f.fid,semanticType: f.semanticType,analyticType: f.analyticType,- }));+ }));encodings.measures = dataset.rawFields- .filter(f => f.analyticType === 'measure')+ .filter((f) => f.analyticType === "measure").map((f) => ({dragId: uuidv4(),fid: f.fid,name: f.name || f.fid,analyticType: f.analyticType,semanticType: f.semanticType,- aggName: 'sum'- }));+ aggName: "sum",+ }));});this.freezeHistory();// this.draggableFieldState.measures.push({- // dragId: uuidv4(),- // fid: COUNT_FIELD_ID,- // name: '记录数',- // analyticType: 'measure',- // semanticType: 'quantitative',- // aggName: 'count'- // })- }- public clearState () {+ // dragId: uuidv4(),+ // fid: COUNT_FIELD_ID,+ // name: '记录数',+ // analyticType: 'measure',+ // semanticType: 'quantitative',+ // aggName: 'count'+ // })+ }+ public clearState() {this.useMutable(({ encodings }) => {for (let key in encodings) {if (!MetaFieldKeys.includes(key as keyof DraggableFieldState)) {@@ -343,41 +352,35 @@ export class VizSpecStore {public setVisualConfig<K extends keyof IVisualConfig>(configKey: K, value: IVisualConfig[K]) {this.useMutable(({ config }) => {switch (true) {- case ['defaultAggregated', 'defaultStack', 'showActions', 'interactiveScale'].includes(configKey): {- return (config as unknown as {[k: string]: boolean})[configKey] = Boolean(value);+ case ["defaultAggregated", "defaultStack", "showActions", "interactiveScale"].includes(configKey): {+ return ((config as unknown as { [k: string]: boolean })[configKey] = Boolean(value));}- case configKey === 'geoms' && Array.isArray(value):- case configKey === 'size' && typeof value === 'object':- case configKey === 'sorted':- case configKey === 'stack':- {- return config[configKey] = value;+ case configKey === "geoms" && Array.isArray(value):+ case configKey === "size" && typeof value === "object":+ case configKey === "sorted":+ case configKey === "stack": {+ return (config[configKey] = value);}default: {- console.error('unknown key' + configKey);+ console.error("unknown key" + configKey);}}});}- public transformCoord (coord: 'cartesian' | 'polar') {- if (coord === 'polar') {-+ public transformCoord(coord: "cartesian" | "polar") {+ if (coord === "polar") {}}- public setChartLayout(props: {mode: IVisualConfig['size']['mode'], width?: number, height?: number }) {+ public setChartLayout(props: { mode: IVisualConfig["size"]["mode"]; width?: number; height?: number }) {this.useMutable(({ config }) => {- const {- mode = config.size.mode,- width = config.size.width,- height = config.size.height- } = props;+ const { mode = config.size.mode, width = config.size.width, height = config.size.height } = props;config.size.mode = mode;config.size.width = width;config.size.height = height;});}- public setExploration(value: Partial<IVisualConfig['exploration']>) {+ public setExploration(value: Partial<IVisualConfig["exploration"]>) {this.useMutable(({ config }) => {if (value.mode) {config.exploration.mode = value.mode;@@ -397,13 +400,18 @@ export class VizSpecStore {fields.splice(destinationIndex, 0, field);});}- public moveField(sourceKey: keyof DraggableFieldState, sourceIndex: number, destinationKey: keyof DraggableFieldState, destinationIndex: number) {- if (sourceKey === 'filters') {+ public moveField(+ sourceKey: keyof DraggableFieldState,+ sourceIndex: number,+ destinationKey: keyof DraggableFieldState,+ destinationIndex: number+ ) {+ if (sourceKey === "filters") {return this.removeField(sourceKey, sourceIndex);- } else if (destinationKey === 'filters') {- return this.appendFilter(destinationIndex, this.draggableFieldState[sourceKey][sourceIndex])+ } else if (destinationKey === "filters") {+ return this.appendFilter(destinationIndex, this.draggableFieldState[sourceKey][sourceIndex]);}-+this.useMutable(({ encodings }) => {let movingField: IViewField;// 来源是不是metafield,是->clone;不是->直接删掉@@ -418,9 +426,9 @@ export class VizSpecStore {}// 目的地是metafields的情况,只有在来源也是metafields时,会执行字段类型转化操作if (MetaFieldKeys.includes(destinationKey)) {- if (!MetaFieldKeys.includes(sourceKey))return;+ if (!MetaFieldKeys.includes(sourceKey)) return;encodings[sourceKey].splice(sourceIndex, 1);- movingField.analyticType = destinationKey === 'dimensions' ? 'dimension' : 'measure';+ movingField.analyticType = destinationKey === "dimensions" ? "dimension" : "measure";}const limitSize = getChannelSizeLimit(destinationKey);const fixedDestinationIndex = Math.min(destinationIndex, limitSize - 1);@@ -429,7 +437,7 @@ export class VizSpecStore {});}public removeField(sourceKey: keyof DraggableFieldState, sourceIndex: number) {- if (MetaFieldKeys.includes(sourceKey))return;+ if (MetaFieldKeys.includes(sourceKey)) return;this.useMutable(({ encodings }) => {const fields = encodings[sourceKey];@@ -462,25 +470,29 @@ export class VizSpecStore {const fieldsInCup = encodings.columns;encodings.columns = encodings.rows;- encodings.rows = fieldsInCup as typeof encodings.rows; // assume this as writable+ encodings.rows = fieldsInCup as typeof encodings.rows; // assume this as writable});}public createBinField(stateKey: keyof DraggableFieldState, index: number) {this.useMutable(({ encodings }) => {- const originField = encodings[stateKey][index]+ const originField = encodings[stateKey][index];const binField: IViewField = {fid: uuidv4(),dragId: uuidv4(),name: `bin(${originField.name})`,- semanticType: 'ordinal',- analyticType: 'dimension',+ semanticType: "ordinal",+ analyticType: "dimension",};encodings.dimensions.push(binField);- this.commonStore.currentDataset.dataSource = makeBinField(this.commonStore.currentDataset.dataSource, originField.fid, binField.fid)+ this.commonStore.currentDataset.dataSource = makeBinField(+ this.commonStore.currentDataset.dataSource,+ originField.fid,+ binField.fid+ );});}public createLogField(stateKey: keyof DraggableFieldState, index: number) {- if (stateKey === 'filters') {+ if (stateKey === "filters") {return;}@@ -490,14 +502,18 @@ export class VizSpecStore {fid: uuidv4(),dragId: uuidv4(),name: `log10(${originField.name})`,- semanticType: 'quantitative',- analyticType: originField.analyticType+ semanticType: "quantitative",+ analyticType: originField.analyticType,};encodings[stateKey].push(logField);- this.commonStore.currentDataset.dataSource = makeLogField(this.commonStore.currentDataset.dataSource, originField.fid, logField.fid)+ this.commonStore.currentDataset.dataSource = makeLogField(+ this.commonStore.currentDataset.dataSource,+ originField.fid,+ logField.fid+ );});}- public setFieldAggregator (stateKey: keyof DraggableFieldState, index: number, aggName: string) {+ public setFieldAggregator(stateKey: keyof DraggableFieldState, index: number, aggName: string) {this.useMutable(({ encodings }) => {const fields = encodings[stateKey];@@ -506,54 +522,77 @@ export class VizSpecStore {}});}- public get sortCondition () {+ public get sortCondition() {const { rows, columns } = this.draggableFieldState;const yField = rows.length > 0 ? rows[rows.length - 1] : null;const xField = columns.length > 0 ? columns[columns.length - 1] : null;- if (xField !== null && xField.analyticType === 'dimension' && yField !== null && yField.analyticType === 'measure') {- return true+ if (+ xField !== null &&+ xField.analyticType === "dimension" &&+ yField !== null &&+ yField.analyticType === "measure"+ ) {+ return true;}- if (xField !== null && xField.analyticType === 'measure' && yField !== null && yField.analyticType === 'dimension') {- return true+ if (+ xField !== null &&+ xField.analyticType === "measure" &&+ yField !== null &&+ yField.analyticType === "dimension"+ ) {+ return true;}return false;}- public setFieldSort (stateKey: keyof DraggableFieldState, index: number, sortType: 'none' | 'ascending' | 'descending') {+ public setFieldSort(+ stateKey: keyof DraggableFieldState,+ index: number,+ sortType: "none" | "ascending" | "descending"+ ) {this.useMutable(({ encodings }) => {encodings[stateKey][index].sort = sortType;});}- public applyDefaultSort(sortType: 'none' | 'ascending' | 'descending' = 'ascending') {+ public applyDefaultSort(sortType: "none" | "ascending" | "descending" = "ascending") {this.useMutable(({ encodings }) => {const { rows, columns } = encodings;const yField = rows.length > 0 ? rows[rows.length - 1] : null;const xField = columns.length > 0 ? columns[columns.length - 1] : null;-- if (xField !== null && xField.analyticType === 'dimension' && yField !== null && yField.analyticType === 'measure') {++ if (+ xField !== null &&+ xField.analyticType === "dimension" &&+ yField !== null &&+ yField.analyticType === "measure"+ ) {encodings.columns[columns.length - 1].sort = sortType;return;}- if (xField !== null && xField.analyticType === 'measure' && yField !== null && yField.analyticType === 'dimension') {+ if (+ xField !== null &&+ xField.analyticType === "measure" &&+ yField !== null &&+ yField.analyticType === "dimension"+ ) {encodings.rows[rows.length - 1].sort = sortType;return;}});}- public appendField (destinationKey: keyof DraggableFieldState, field: IViewField | undefined) {+ public appendField(destinationKey: keyof DraggableFieldState, field: IViewField | undefined) {if (MetaFieldKeys.includes(destinationKey)) return;- if (typeof field === 'undefined') return;- if (destinationKey === 'filters') {+ if (typeof field === "undefined") return;+ if (destinationKey === "filters") {return;}--+this.useMutable(({ encodings }) => {const cloneField = { ...toJS(field) };cloneField.dragId = uuidv4();encodings[destinationKey].push(cloneField);});}- public renderSpec (spec: Specification) {+ public renderSpec(spec: Specification) {const tab = this.visList[this.visIndex];if (tab) {@@ -562,44 +601,67 @@ export class VizSpecStore {// const [xField, yField, ] = spec.position;this.clearState();if ((spec.geomType?.length ?? 0) > 0) {- this.setVisualConfig('geoms', spec.geomType!.map(g => geomAdapter(g)));+ this.setVisualConfig(+ "geoms",+ spec.geomType!.map((g) => geomAdapter(g))+ );}if ((spec.facets?.length ?? 0) > 0) {const facets = (spec.facets || []).concat(spec.highFacets || []);for (let facet of facets) {- this.appendField('rows', fields.find(f => f.fid === facet));+ this.appendField(+ "rows",+ fields.find((f) => f.fid === facet)+ );}}if (spec.position) {const [cols, rows] = spec.position;- if (cols) this.appendField('columns', fields.find(f => f.fid === cols));- if (rows) this.appendField('rows', fields.find(f => f.fid === rows));+ if (cols)+ this.appendField(+ "columns",+ fields.find((f) => f.fid === cols)+ );+ if (rows)+ this.appendField(+ "rows",+ fields.find((f) => f.fid === rows)+ );}if ((spec.color?.length ?? 0) > 0) {- this.appendField('color', fields.find(f => f.fid === spec.color![0]));+ this.appendField(+ "color",+ fields.find((f) => f.fid === spec.color![0])+ );}if ((spec.size?.length ?? 0) > 0) {- this.appendField('size', fields.find(f => f.fid === spec.size![0]));+ this.appendField(+ "size",+ fields.find((f) => f.fid === spec.size![0])+ );}if ((spec.opacity?.length ?? 0) > 0) {- this.appendField('opacity', fields.find(f => f.fid === spec.opacity![0]));+ this.appendField(+ "opacity",+ fields.find((f) => f.fid === spec.opacity![0])+ );}}}- public destroy () {- this.reactions.forEach(rec => {+ public destroy() {+ this.reactions.forEach((rec) => {rec();- })+ });}- public exportAsRaw () {+ public exportAsRaw() {const pureVisList = dumpsGWPureSpec(this.visList);return stringifyGWContent({datasets: toJS(this.commonStore.datasets),dataSources: this.commonStore.dataSources,- specList: pureVisList- })+ specList: pureVisList,+ });}- public importRaw (raw: string) {+ public importRaw(raw: string) {const content = parseGWContent(raw);this.commonStore.datasets = content.datasets;this.commonStore.dataSources = content.dataSources;@@ -608,4 +670,4 @@ export class VizSpecStore {this.visList = parseGWPureSpec(forwardVisualConfigs(content.specList));this.visIndex = 0;}-}\ No newline at end of file+}diff --git a/packages/graphic-walker/src/utils/autoMark.ts b/packages/graphic-walker/src/utils/autoMark.tsindex 255b6b6e..495310e5 100644--- a/packages/graphic-walker/src/utils/autoMark.ts+++ b/packages/graphic-walker/src/utils/autoMark.ts@@ -1,30 +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'+ 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)- })+ (["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("nominal") === 1 || couter.get("ordinal") === 1) {+ return "bar";}- if (couter.get('temporal') === 1 && couter.get('quantitative') === 1) {- return 'line'+ if (couter.get("temporal") === 1 && couter.get("quantitative") === 1) {+ return "line";}- if (couter.get('quantitative') === 2) {- return 'point'+ if (couter.get("quantitative") === 2) {+ return "point";}- return 'point'-}\ No newline at end of file+ return "point";+}diff --git a/packages/graphic-walker/src/utils/normalization.ts b/packages/graphic-walker/src/utils/normalization.tsindex 4b2c9f8f..78dcc241 100644--- a/packages/graphic-walker/src/utils/normalization.ts+++ b/packages/graphic-walker/src/utils/normalization.ts@@ -1,4 +1,4 @@-import { IRow } from '../interfaces';+import { IRow } from "../interfaces";export function normalizeWithParent(data: IRow[],@@ -11,69 +11,72 @@ export function normalizeWithParent(} {const totalMeasuresOfParent: IRow = {};const totalMeasures: IRow = {};- measures.forEach(mea => {+ measures.forEach((mea) => {totalMeasuresOfParent[mea] = 0;totalMeasures[mea] = 0;- })- parentData.forEach(record => {- measures.forEach(mea => {- totalMeasuresOfParent[mea] += Math.abs(record[mea])- })- })- data.forEach(record => {- measures.forEach(mea => {+ });+ parentData.forEach((record) => {+ measures.forEach((mea) => {+ totalMeasuresOfParent[mea] += Math.abs(record[mea]);+ });+ });+ data.forEach((record) => {+ measures.forEach((mea) => {totalMeasures[mea] += Math.abs(record[mea]);- })- })+ });+ });const normalizedParentData: IRow[] = [];- parentData.forEach(record => {+ parentData.forEach((record) => {const newRecord = { ...record };- measures.forEach(mea => {+ measures.forEach((mea) => {newRecord[mea] /= totalMeasuresOfParent[mea];- })+ });normalizedParentData.push(newRecord);- })+ });const normalizedData: IRow[] = [];- data.forEach(record => {+ data.forEach((record) => {const newRecord = { ...record };- measures.forEach(mea => {+ measures.forEach((mea) => {if (syncScale) {newRecord[mea] /= totalMeasuresOfParent[mea];} else {- newRecord[mea] /= totalMeasures[mea]+ newRecord[mea] /= totalMeasures[mea];}- })+ });normalizedData.push(newRecord);- })+ });return {normalizedData,- normalizedParentData+ normalizedParentData,};}-export function compareDistribution (distribution1: IRow[], distribution2: IRow[], dimensions: string[], measures: string[]): number {+export function compareDistribution(+ distribution1: IRow[],+ distribution2: IRow[],+ dimensions: string[],+ measures: string[]+): number {let score = 0;let count = 0;const tagsForD2: boolean[] = distribution2.map(() => false);for (let record of distribution1) {let targetRecordIndex = distribution2.findIndex((r, i) => {- return !tagsForD2[i] && dimensions.every(dim => r[dim] === record[dim])- })+ return !tagsForD2[i] && dimensions.every((dim) => r[dim] === record[dim]);+ });if (targetRecordIndex > -1) {tagsForD2[targetRecordIndex] = true;const targetRecord = distribution2[targetRecordIndex];for (let mea of measures) {-score = Math.max(score,- Math.max(targetRecord[mea], record[mea]) /- Math.min(targetRecord[mea], record[mea])+ Math.max(targetRecord[mea], record[mea]) / Math.min(targetRecord[mea], record[mea]));count++;}} else {for (let mea of measures) {- score = Math.max(score, record[mea])+ score = Math.max(score, record[mea]);count++;}}@@ -90,31 +93,36 @@ export function compareDistribution (distribution1: IRow[], distribution2: IRow[return score;}-export function normalizeByMeasures (dataSource: IRow[], measures: string[]) {+export function normalizeByMeasures(dataSource: IRow[], measures: string[]) {let sums: Map<string, number> = new Map();- measures.forEach(mea => {+ measures.forEach((mea) => {sums.set(mea, 0);- })+ });- dataSource.forEach(record => {- measures.forEach(mea => {+ dataSource.forEach((record) => {+ measures.forEach((mea) => {sums.set(mea, sums.get(mea)! + Math.abs(record[mea]));- })- })+ });+ });const ans: IRow[] = [];- dataSource.forEach(record => {+ dataSource.forEach((record) => {const norRecord: IRow = { ...record };- measures.forEach(mea => {+ measures.forEach((mea) => {norRecord[mea] /= sums.get(mea)!;- })+ });ans.push(norRecord);});return ans;}-export function getDistributionDifference(dataSource: IRow[], dimensions: string[], measure1: string, measure2: string): number {+export function getDistributionDifference(+ dataSource: IRow[],+ dimensions: string[],+ measure1: string,+ measure2: string+): number {let score = 0;for (let record of dataSource) {if (record[measure1] === 0 || record[measure2] === 0) continue;@@ -123,7 +131,7 @@ export function getDistributionDifference(dataSource: IRow[], dimensions: stringreturn score;}-export function makeBinField (dataSource: IRow[], fid: string, binFid: string, binSize: number | undefined = 10) {+export function makeBinField(dataSource: IRow[], fid: string, binFid: string, binSize: number | undefined = 10) {let _min = Infinity;let _max = -Infinity;for (let i = 0; i < dataSource.length; i++) {@@ -132,21 +140,21 @@ export function makeBinField (dataSource: IRow[], fid: string, binFid: string, bif (val < _min) _min = val;}const step = (_max - _min) / binSize;- return dataSource.map(r => {+ return dataSource.map((r) => {let bIndex = Math.floor((r[fid] - _min) / step);if (bIndex === binSize) bIndex = binSize - 1;return {...r,- [binFid]: bIndex * step + _min- }- })+ [binFid]: bIndex * step + _min,+ };+ });}-export function makeLogField (dataSource: IRow[], fid: string, logFid: string) {- return dataSource.map(r => {+export function makeLogField(dataSource: IRow[], fid: string, logFid: string) {+ return dataSource.map((r) => {return {...r,- [logFid]: (typeof r[fid] === 'number' && r[fid] > 0) ? Math.log10(r[fid]) : null- }- })-}\ No newline at end of file+ [logFid]: typeof r[fid] === "number" && r[fid] > 0 ? Math.log10(r[fid]) : null,+ };+ });+}diff --git a/packages/graphic-walker/src/utils/save.ts b/packages/graphic-walker/src/utils/save.tsindex 6a0f42f5..1f43b2e3 100644--- a/packages/graphic-walker/src/utils/save.ts+++ b/packages/graphic-walker/src/utils/save.ts@@ -1,48 +1,49 @@import { IDataSet, IDataSource, IVisSpec } from "../interfaces";import { VisSpecWithHistory } from "../models/visSpecHistory";--export function dumpsGWPureSpec (list: VisSpecWithHistory[]): IVisSpec[] {- return list.map(l => l.exportGW())+export function dumpsGWPureSpec(list: VisSpecWithHistory[]): IVisSpec[] {+ return list.map((l) => l.exportGW());}-export function parseGWPureSpec (list: IVisSpec[]): VisSpecWithHistory[] {- return list.map(l => new VisSpecWithHistory(l))+export function parseGWPureSpec(list: IVisSpec[]): VisSpecWithHistory[] {+ return list.map((l) => new VisSpecWithHistory(l));}interface IStoInfo {datasets: IDataSet[];- specList: ({+ specList: {/** 由于 gw 内部实现暂时未锁版本,这里获取到的信息可能会与当前实例内容有偏差,需要用初始值合入 */- [K in keyof IVisSpec]: K extends 'config' ? Partial<IVisSpec[K]> : IVisSpec[K];- })[];- dataSources: IDataSource[]+ [K in keyof IVisSpec]: K extends "config" ? Partial<IVisSpec[K]> : IVisSpec[K];+ }[];+ dataSources: IDataSource[];}-export function stringifyGWContent (info: IStoInfo) {- return JSON.stringify(info)+export function stringifyGWContent(info: IStoInfo) {+ return JSON.stringify(info);}-export function parseGWContent (raw: string): IStoInfo {- return JSON.parse(raw)+export function parseGWContent(raw: string): IStoInfo {+ return JSON.parse(raw);}export function download(data: string, filename: string, type: string) {- var file = new Blob([data], {type: type});+ var file = new Blob([data], { type: type });// @ts-ignore- if (window.navigator.msSaveOrOpenBlob) // IE10++ if (window.navigator.msSaveOrOpenBlob)+ // IE10+// @ts-ignorewindow.navigator.msSaveOrOpenBlob(file, filename);- else { // Others+ else {+ // Othersvar a = document.createElement("a"),- url = URL.createObjectURL(file);+ url = URL.createObjectURL(file);a.href = url;a.download = filename;document.body.appendChild(a);a.click();- setTimeout(function() {+ setTimeout(function () {document.body.removeChild(a);- window.URL.revokeObjectURL(url);- }, 0);+ window.URL.revokeObjectURL(url);+ }, 0);}-}\ No newline at end of file+}diff --git a/packages/graphic-walker/src/utils/throttle.ts b/packages/graphic-walker/src/utils/throttle.tsindex b635fab2..3d826bf3 100644--- a/packages/graphic-walker/src/utils/throttle.ts+++ b/packages/graphic-walker/src/utils/throttle.ts@@ -1,4 +1,8 @@-const throttle = (fn: () => void, time: number, options?: Partial<{ leading: boolean; trailing: boolean }>): () => void => {+const throttle = (+ fn: () => void,+ time: number,+ options?: Partial<{ leading: boolean; trailing: boolean }>+): (() => void) => {const { leading = true, trailing = false } = options ?? {};let dirty = false;