Skip to content

An open source alternative to Tableau. Embeddable visual analytic

feat: save gw file

observedobserver962dd0891bfc
diff --git a/packages/graphic-walker/src/config.ts b/packages/graphic-walker/src/config.ts
index e1eb044f..9c6fdbbd 100644
--- a/packages/graphic-walker/src/config.ts
+++ b/packages/graphic-walker/src/config.ts
@@ -35,4 +35,6 @@ export const COLORS = {
measure: 'rgba(10, 0, 0, 0.6)',
black: '#141414',
white: '#fafafa'
-}
\ No newline at end of file
+}
+
+export const MAX_HISTORY_SIZE = 20;
\ No newline at end of file
diff --git a/packages/graphic-walker/src/dataSource/dataSelection/csvData.tsx b/packages/graphic-walker/src/dataSource/dataSelection/csvData.tsx
index 43ed99a3..340f1f4e 100644
--- a/packages/graphic-walker/src/dataSource/dataSelection/csvData.tsx
+++ b/packages/graphic-walker/src/dataSource/dataSelection/csvData.tsx
@@ -1,6 +1,6 @@
import React, { useRef, useCallback } from 'react';
import { FileReader } from '@kanaries/web-data-loader';
-import { Record } from '../../interfaces';
+import { IRow } from '../../interfaces';
import Table from '../table';
import styled from 'styled-components';
import { useGlobalStore } from '../../store';
@@ -39,7 +39,7 @@ const CSVData: React.FC<ICSVData> = props => {
config: { type: 'reservoirSampling', size: Infinity },
onLoading: () => {}
}).then((data) => {
- commonStore.updateTempDS(data as Record[]);
+ commonStore.updateTempDS(data as IRow[]);
});
}
}}
diff --git a/packages/graphic-walker/src/dataSource/dataSelection/gwFile.tsx b/packages/graphic-walker/src/dataSource/dataSelection/gwFile.tsx
new file mode 100644
index 00000000..37d414c3
--- /dev/null
+++ b/packages/graphic-walker/src/dataSource/dataSelection/gwFile.tsx
@@ -0,0 +1,38 @@
+import React, { useRef, useCallback } from "react";
+import { FileReader } from "@kanaries/web-data-loader";
+import { IRow } from "../../interfaces";
+import Table from "../table";
+import styled from "styled-components";
+import { useGlobalStore } from "../../store";
+import { observer } from "mobx-react-lite";
+import { useTranslation } from "react-i18next";
+
+const Container = styled.div`
+ overflow-x: auto;
+`;
+
+interface GWFileProps {
+ fileRef: React.RefObject<HTMLInputElement>;
+}
+const GWFile: React.FC<GWFileProps> = (props) => {
+ const { commonStore, vizStore } = useGlobalStore();
+
+ return (
+ <input
+ style={{ display: "none" }}
+ type="file"
+ ref={props.fileRef}
+ onChange={(e) => {
+ const files = e.target.files;
+ if (files !== null) {
+ const file = files[0];
+ file.text().then(res => {
+ vizStore.importRaw(res)
+ })
+ }
+ }}
+ />
+ );
+};
+
+export default observer(GWFile);
diff --git a/packages/graphic-walker/src/dataSource/index.tsx b/packages/graphic-walker/src/dataSource/index.tsx
index 515d4ea9..fc961330 100644
--- a/packages/graphic-walker/src/dataSource/index.tsx
+++ b/packages/graphic-walker/src/dataSource/index.tsx
@@ -1,5 +1,5 @@
import { observer } from 'mobx-react-lite';
-import React from 'react';
+import React, { useRef } from 'react';
import { Container } from '../components/container';
import Modal from '../components/modal';
// import DataSourcePanel from './pannel';
@@ -7,6 +7,8 @@ import DataSelection from './dataSelection';
import { useGlobalStore } from '../store';
import { CheckCircleIcon, ArrowPathIcon } from '@heroicons/react/24/outline';
import { useTranslation } from 'react-i18next';
+import { download } from '../utils/save';
+import GwFile from './dataSelection/gwFile';
interface DSSegmentProps {
preWorkDone: boolean;
@@ -14,12 +16,14 @@ interface DSSegmentProps {
const DataSourceSegment: React.FC<DSSegmentProps> = props => {
const { preWorkDone } = props;
- const { commonStore } = useGlobalStore();
+ const { commonStore, vizStore } = useGlobalStore();
+ const gwFileRef = useRef<HTMLInputElement>(null);
const { t } = useTranslation();
const { currentDataset, datasets, showDSPanel } = commonStore;
return <Container className="flex flex-row items-stretch">
+ <GwFile fileRef={gwFileRef} />
{!preWorkDone && <div className="animate-spin inline-block mr-2 ml-2 w-4 h-4 rounded-full border-t-2 border-l-2 border-blue-500"></div>}
<label className="text-xs mr-1 whitespace-nowrap self-center h-4">
{t('DataSource.labels.cur_dataset')}
@@ -41,6 +45,23 @@ const DataSourceSegment: React.FC<DSSegmentProps> = props => {
>
{t('DataSource.buttons.create_dataset')}
</button>
+ <button className="inline-block min-w-96 text-xs ml-2 pt-1 pb-1 pl-6 pr-6 border border-gray-500 rounded-sm hover:bg-gray-200"
+ onClick={() => {
+ const res = vizStore.exportAsRaw();
+ download(res, 'graphic-walker-notebook.json', 'text/plain')
+ }}
+ >
+ {t('DataSource.buttons.export_as_file')}
+ </button>
+ <button className="inline-block min-w-96 text-xs ml-2 pt-1 pb-1 pl-6 pr-6 border border-gray-500 rounded-sm hover:bg-gray-200"
+ onClick={() => {
+ if (gwFileRef.current) {
+ gwFileRef.current.click();
+ }
+ }}
+ >
+ {t('DataSource.buttons.import_file')}
+ </button>
{showDSPanel && (
<Modal
title={t('DataSource.dialog.create_data_source')}
diff --git a/packages/graphic-walker/src/dataSource/pannel.tsx b/packages/graphic-walker/src/dataSource/pannel.tsx
index 9e9c69d8..136327ab 100644
--- a/packages/graphic-walker/src/dataSource/pannel.tsx
+++ b/packages/graphic-walker/src/dataSource/pannel.tsx
@@ -1,6 +1,6 @@
import React, { useRef, useCallback } from 'react';
import { FileReader } from '@kanaries/web-data-loader';
-import { Record } from '../interfaces';
+import { IRow } from '../interfaces';
import Table from './table';
import styled from 'styled-components';
import { useGlobalStore } from '../store';
@@ -35,7 +35,7 @@ const DataSourcePanel: React.FC<DSPanelProps> = props => {
config: { type: 'reservoirSampling', size: Infinity },
onLoading: () => {}
}).then((data) => {
- commonStore.updateTempDS(data as Record[]);
+ commonStore.updateTempDS(data as IRow[]);
});
}
}}
diff --git a/packages/graphic-walker/src/insightBoard/selectionSpec.ts b/packages/graphic-walker/src/insightBoard/selectionSpec.ts
index 14cf6142..460a6646 100644
--- a/packages/graphic-walker/src/insightBoard/selectionSpec.ts
+++ b/packages/graphic-walker/src/insightBoard/selectionSpec.ts
@@ -1,5 +1,5 @@
import { Specification } from 'visual-insights';
-import { Record, SemanticType } from '../interfaces';
+import { IRow, SemanticType } from '../interfaces';
export const geomTypeMap: { [key: string]: any } = {
interval: 'bar',
line: 'line',
@@ -9,7 +9,7 @@ export const geomTypeMap: { [key: string]: any } = {
};
export function selectionVis(
query: Specification,
- dataSource: Record[],
+ dataSource: IRow[],
dimensions: string[],
measures: string[],
aggregatedMeasures: Array<{ op: string; field: string; as: string }>,
diff --git a/packages/graphic-walker/src/insights.ts b/packages/graphic-walker/src/insights.ts
index 6dccd10e..065be2dd 100644
--- a/packages/graphic-walker/src/insights.ts
+++ b/packages/graphic-walker/src/insights.ts
@@ -1,5 +1,5 @@
import { IMutField, Insight } from 'visual-insights';
-import { Record, IMeasure } from './interfaces';
+import { IRow, IMeasure } from './interfaces';
import { checkMajorFactor, filterByPredicates, checkChildOutlier, IPredicate } from './utils';
import { normalizeWithParent, compareDistribution, normalizeByMeasures, getDistributionDifference } from './utils/normalization';
import { StatFuncName } from 'visual-insights/build/esm/statistics';
@@ -18,10 +18,10 @@ export interface IMeasureWithStat extends IMeasure {
score: number;
}
export class DataExplainer {
- public dataSource: Record[];
+ public dataSource: IRow[];
private engine: Insight.VIEngine;
private defaultAggs: StatFuncName[] = ['min', 'max', 'sum', 'count', 'mean'];
- constructor (dataSource: Record[] = []) {
+ constructor (dataSource: IRow[] = []) {
this.engine = new Insight.VIEngine();
this.dataSource = dataSource;
let keys: string[] = [];
@@ -41,7 +41,6 @@ export class DataExplainer {
// @ts-ignore
key: f.key || f.fid
})));
- // console.log('set fields', fields, fields.map(f => f.fid))
this.engine.univarSelection();
}
public preAnalysis() {
@@ -177,12 +176,10 @@ export class DataExplainer {
// here we do not nomorlize all the dim member's distribution, we use the relative distribution instead.
// 3. the dim member we found can be used to explain current one as major factor.
// const predicates: IPredicate[] = selection === 'all' ? [] : getPredicates(selection, dimensions, []);
- // console.log(predicates)
const parentCuboid = this.engine.cube.getCuboid(dimensions);
const measureNames = measures.map(m => m.key);
const ops = measures.map(m => m.op);
const parentData = filterByPredicates(parentCuboid.getAggregatedRows(measureNames, ops), predicates);
- // console.log(parentData)
const knn = this.getGeneralizeKNN('dimension', dimensions, K_Neighbor, 0);
const majorList: Array<{key: string; score: number; dimensions: string[]; measures: IMeasure[]}> = [];
@@ -190,7 +187,7 @@ export class DataExplainer {
for (let extendDim of knn) {
const cuboid = this.engine.cube.getCuboid([...dimensions, extendDim]);
const data = filterByPredicates(cuboid.getAggregatedRows(measureNames, ops), predicates);
- let groups: Map<any, Record[]> = new Map();
+ let groups: Map<any, IRow[]> = new Map();
for (let record of data) {
if (!groups.has(record[extendDim])) {
groups.set(record[extendDim], [])
diff --git a/packages/graphic-walker/src/interfaces.ts b/packages/graphic-walker/src/interfaces.ts
index 01effc09..63f1396a 100644
--- a/packages/graphic-walker/src/interfaces.ts
+++ b/packages/graphic-walker/src/interfaces.ts
@@ -2,12 +2,9 @@ import { StatFuncName } from "visual-insights/build/esm/statistics";
import { AggFC } from 'cube-core/built/types';
import { IAnalyticType, IMutField as VIMutField, ISemanticType } from 'visual-insights';
-/**
- * @deprecated
- */
-export interface Record {
- [key: string]: any;
-}
+export 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];
+};
export interface IRow {
[key: string]: any;
@@ -133,4 +130,25 @@ export type IFilterRule = {
};
-export type IStackMode = 'none' | 'stack' | 'normalize';
\ No newline at end of file
+export type IStackMode = 'none' | 'stack' | 'normalize';
+
+export interface IVisualConfig {
+ defaultAggregated: boolean;
+ geoms: string[];
+ stack: 'none' | 'stack' | 'normalize';
+ showActions: boolean;
+ interactiveScale: boolean;
+ sorted: 'none' | 'ascending' | 'descending';
+ size: {
+ mode: 'auto' | 'fixed';
+ width: number;
+ height: number;
+ }
+}
+
+export interface IVisSpec {
+ readonly visId: string;
+ readonly name?: [string, Record<string, any>?];
+ readonly encodings: DeepReadonly<DraggableFieldState>;
+ readonly config: DeepReadonly<IVisualConfig>;
+}
\ No newline at end of file
diff --git a/packages/graphic-walker/src/locales/en-US.json b/packages/graphic-walker/src/locales/en-US.json
index 3a944efa..f8aa993b 100644
--- a/packages/graphic-walker/src/locales/en-US.json
+++ b/packages/graphic-walker/src/locales/en-US.json
@@ -58,7 +58,9 @@
"cur_dataset": "Current Dataset"
},
"buttons": {
- "create_dataset": "Create Dataset"
+ "create_dataset": "Create Dataset",
+ "export_as_file": "Save As File",
+ "import_file": "Import Graphic Walker File"
},
"dialog": {
"create_data_source": "New Data Source",
diff --git a/packages/graphic-walker/src/locales/zh-CN.json b/packages/graphic-walker/src/locales/zh-CN.json
index 3cd34504..821d2927 100644
--- a/packages/graphic-walker/src/locales/zh-CN.json
+++ b/packages/graphic-walker/src/locales/zh-CN.json
@@ -58,7 +58,9 @@
"cur_dataset": "当前数据集"
},
"buttons": {
- "create_dataset": "创建数据集"
+ "create_dataset": "创建数据集",
+ "export_as_file": "保存到文件",
+ "import_file": "导入文件"
},
"dialog": {
"create_data_source": "创建数据源",
diff --git a/packages/graphic-walker/src/models/visSpecHistory.ts b/packages/graphic-walker/src/models/visSpecHistory.ts
new file mode 100644
index 00000000..1312170a
--- /dev/null
+++ b/packages/graphic-walker/src/models/visSpecHistory.ts
@@ -0,0 +1,129 @@
+import { toJS } from "mobx";
+import { MAX_HISTORY_SIZE } from "../config";
+import { DeepReadonly, DraggableFieldState, IVisSpec, IVisualConfig } from "../interfaces";
+
+export class VisSpecWithHistory {
+
+ readonly visId: IVisSpec['visId'];
+ private snapshots: Pick<IVisSpec, 'name' | 'encodings' | 'config'>[];
+ private cursor: number;
+
+ constructor(data: IVisSpec) {
+ this.visId = data.visId;
+ this.snapshots = [{
+ name: data.name,
+ encodings: data.encodings,
+ config: data.config,
+ }];
+ this.cursor = 0;
+ }
+
+ private get frame(): Readonly<IVisSpec> {
+ return {
+ visId: this.visId,
+ ...this.snapshots[this.cursor]!,
+ };
+ }
+
+ private batchFlag = false;
+
+ private commit(snapshot: Partial<Readonly<VisSpecWithHistory['snapshots'][0]>>): void {
+ if (this.batchFlag) {
+ // batch this commit
+ this.snapshots[this.cursor] = toJS({
+ ...this.frame,
+ ...snapshot,
+ });
+
+ return;
+ }
+
+ this.batchFlag = true;
+
+ this.snapshots = [
+ ...this.snapshots.slice(0, this.cursor + 1),
+ toJS({
+ ...this.frame,
+ ...snapshot,
+ }),
+ ];
+
+ if (this.snapshots.length > MAX_HISTORY_SIZE) {
+ this.snapshots.splice(0, 1);
+ }
+
+ this.cursor = this.snapshots.length - 1;
+
+ requestAnimationFrame(() => this.batchFlag = false);
+ }
+
+ public get canUndo() {
+ return this.cursor > 0;
+ }
+
+ public undo(): boolean {
+ if (this.cursor === 0) {
+ return false;
+ }
+
+ this.cursor -= 1;
+
+ return true;
+ }
+
+ public get canRedo() {
+ return this.cursor < this.snapshots.length - 1;
+ }
+
+ public redo(): boolean {
+ if (this.cursor === this.snapshots.length - 1) {
+ return false;
+ }
+
+ this.cursor += 1;
+
+ return true;
+ }
+
+ public rebase() {
+ this.snapshots = [this.snapshots[this.cursor]];
+ this.cursor = 0;
+ }
+
+ get name() {
+ return this.frame.name;
+ }
+
+ set name(name: IVisSpec['name']) {
+ this.commit({
+ name,
+ });
+ }
+
+ get encodings(): DeepReadonly<DraggableFieldState> {
+ return this.frame.encodings;
+ }
+
+ set encodings(encodings: IVisSpec['encodings']) {
+ this.commit({
+ encodings,
+ });
+ }
+
+ get config(): DeepReadonly<IVisualConfig> {
+ return this.frame.config;
+ }
+
+ set config(config: IVisSpec['config']) {
+ this.commit({
+ config,
+ });
+ }
+
+ public exportGW (): IVisSpec {
+ return {
+ ...this.frame
+ }
+ }
+
+}
\ No newline at end of file
diff --git a/packages/graphic-walker/src/store/commonStore.ts b/packages/graphic-walker/src/store/commonStore.ts
index 1094cc20..9cb80355 100644
--- a/packages/graphic-walker/src/store/commonStore.ts
+++ b/packages/graphic-walker/src/store/commonStore.ts
@@ -1,4 +1,4 @@
-import { DataSet, Filters, IDataSet, IDataSetInfo, IDataSource, IMutField, Record } from '../interfaces';
+import { DataSet, Filters, IDataSet, IDataSetInfo, IDataSource, IMutField, IRow } from '../interfaces';
import { makeAutoObservable, observable, toJS } from 'mobx';
import { transData } from '../dataSource/utils';
import { extendCountField } from '../utils';
@@ -15,7 +15,7 @@ export class CommonStore {
public dsIndex: number = 0;
public tmpDSName: string = '';
public tmpDSRawFields: IMutField[] = [];
- public tmpDataSource: Record[] = [];
+ public tmpDataSource: IRow[] = [];
public showDSPanel: boolean = false;
public showInsightBoard: boolean = false;
public vizEmbededMenu: { show: boolean; position: [number, number] } = { show: false, position: [0, 0] };
@@ -83,7 +83,7 @@ export class CommonStore {
this.tmpDSName = name;
}
- public updateTempDS (rawData: Record[]) {
+ public updateTempDS (rawData: IRow[]) {
const result = transData(rawData);
// TODO: need fix web-data-loader issue #2
this.tmpDataSource = result.dataSource.slice(0, -1);
diff --git a/packages/graphic-walker/src/store/visualSpecStore.ts b/packages/graphic-walker/src/store/visualSpecStore.ts
index 51f0b24d..657c9cac 100644
--- a/packages/graphic-walker/src/store/visualSpecStore.ts
+++ b/packages/graphic-walker/src/store/visualSpecStore.ts
@@ -2,24 +2,12 @@ import { IReactionDisposer, makeAutoObservable, observable, reaction, toJS } fro
import produce from 'immer';
import { v4 as uuidv4 } from 'uuid';
import { Specification } from "visual-insights";
-import { DataSet, DraggableFieldState, IFilterRule, IViewField } from "../interfaces";
+import { DataSet, DraggableFieldState, IFilterRule, IViewField, IVisSpec, IVisualConfig } from "../interfaces";
import { GEMO_TYPES } from "../config";
import { makeBinField, makeLogField } from "../utils/normalization";
import { CommonStore } from "./commonStore";
-
-interface IVisualConfig {
- defaultAggregated: boolean;
- geoms: string[];
- stack: 'none' | 'stack' | 'normalize';
- showActions: boolean;
- interactiveScale: boolean;
- sorted: 'none' | 'ascending' | 'descending';
- size: {
- mode: 'auto' | 'fixed';
- width: number;
- height: number;
- }
-}
+import { VisSpecWithHistory } from "../models/visSpecHistory";
+import { dumpsGWPureSpec, parseGWContent, parseGWPureSpec, stringifyGWContent } from "../utils/save";
export const MetaFieldKeys: Array<keyof DraggableFieldState> = [
'dimensions',
@@ -43,8 +31,6 @@ function getChannelSizeLimit (channel: string): number {
return CHANNEL_LIMIT[channel];
}
-
-
function geomAdapter (geom: string) {
switch (geom) {
case 'interval':
@@ -108,135 +94,8 @@ 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];
};
-interface IVisSpec {
- readonly visId: string;
- readonly name?: [string, Record<string, any>?];
- readonly encodings: DeepReadonly<DraggableFieldState>;
- readonly config: DeepReadonly<IVisualConfig>;
-}
-
const MAX_HISTORY_SIZE = 20;
-class IVisSpecWithHistory {
-
- readonly visId: IVisSpec['visId'];
- private snapshots: Pick<IVisSpec, 'name' | 'encodings' | 'config'>[];
- private cursor: number;
-
- constructor(data: IVisSpec) {
- this.visId = data.visId;
- this.snapshots = [{
- name: data.name,
- encodings: data.encodings,
- config: data.config,
- }];
- this.cursor = 0;
- }
-
- private get frame(): Readonly<IVisSpec> {
- return {
- visId: this.visId,
- ...this.snapshots[this.cursor]!,
- };
- }
-
- private batchFlag = false;
-
- private commit(snapshot: Partial<Readonly<IVisSpecWithHistory['snapshots'][0]>>): void {
- if (this.batchFlag) {
- // batch this commit
- this.snapshots[this.cursor] = toJS({
- ...this.frame,
- ...snapshot,
- });
-
- return;
- }
-
- this.batchFlag = true;
-
- this.snapshots = [
- ...this.snapshots.slice(0, this.cursor + 1),
- toJS({
- ...this.frame,
- ...snapshot,
- }),
- ];
-
- if (this.snapshots.length > MAX_HISTORY_SIZE) {
- this.snapshots.splice(0, 1);
- }
-
- this.cursor = this.snapshots.length - 1;
-
- requestAnimationFrame(() => this.batchFlag = false);
- }
-
- public get canUndo() {
- return this.cursor > 0;
- }
-
- public undo(): boolean {
- if (this.cursor === 0) {
- return false;
- }
-
- this.cursor -= 1;
-
- return true;
- }
-
- public get canRedo() {
- return this.cursor < this.snapshots.length - 1;
- }
-
- public redo(): boolean {
- if (this.cursor === this.snapshots.length - 1) {
- return false;
- }
-
- this.cursor += 1;
-
- return true;
- }
-
- public rebase() {
- this.snapshots = [this.snapshots[this.cursor]];
- this.cursor = 0;
- }
-
- get name() {
- return this.frame.name;
- }
-
- set name(name: IVisSpec['name']) {
- this.commit({
- name,
- });
- }
-
- get encodings(): DeepReadonly<DraggableFieldState> {
- return this.frame.encodings;
- }
-
- set encodings(encodings: IVisSpec['encodings']) {
- this.commit({
- encodings,
- });
- }
-
- get config(): DeepReadonly<IVisualConfig> {
- return this.frame.config;
- }
-
- set config(config: IVisSpec['config']) {
- this.commit({
- config,
- });
- }
-
-}
-
export class VizSpecStore {
// public fields: IViewField[] = [];
private commonStore: CommonStore;
@@ -273,7 +132,7 @@ export class VizSpecStore {
* (an `immer` draft) of `this.visList[this.visIndex]`.
*/
public readonly visualConfig: Readonly<IVisualConfig>;
- public visList: IVisSpecWithHistory[] = [];
+ public visList: VisSpecWithHistory[] = [];
public visIndex: number = 0;
public canUndo = false;
public canRedo = false;
@@ -282,7 +141,7 @@ export class VizSpecStore {
this.commonStore = commonStore;
this.draggableFieldState = initEncoding();
this.visualConfig = initVisualConfig();
- this.visList.push(new IVisSpecWithHistory({
+ this.visList.push(new VisSpecWithHistory({
name: ['main.tablist.autoTitle', { idx: 1 }],
visId: uuidv4(),
config: this.visualConfig,
@@ -294,7 +153,7 @@ export class VizSpecStore {
// FIXME!!!!!
this.reactions.push(
reaction(() => commonStore.currentDataset, (dataset) => {
- this.initState();
+ // this.initState();
this.initMetaState(dataset);
}),
reaction(() => this.visList[this.visIndex], frame => {
@@ -412,7 +271,7 @@ export class VizSpecStore {
return fields;
}
public addVisualization () {
- this.visList.push(new IVisSpecWithHistory({
+ this.visList.push(new VisSpecWithHistory({
name: ['main.tablist.autoTitle', { idx: this.visList.length + 1 }],
visId: uuidv4(),
config: initVisualConfig(),
@@ -725,4 +584,20 @@ export class VizSpecStore {
rec();
})
}
+ public exportAsRaw () {
+ const pureVisList = dumpsGWPureSpec(this.visList);
+ return stringifyGWContent({
+ datasets: toJS(this.commonStore.datasets),
+ dataSources: this.commonStore.dataSources,
+ specList: pureVisList
+ })
+ }
+ public importRaw (raw: string) {
+ const content = parseGWContent(raw);
+ this.commonStore.datasets = content.datasets;
+ this.commonStore.dataSources = content.dataSources;
+ this.commonStore.dsIndex = Math.max(content.datasets.length - 1, 0);
+ this.visList = parseGWPureSpec(content.specList)
+ this.visIndex = 0;
+ }
}
\ No newline at end of file
diff --git a/packages/graphic-walker/src/utils/index.ts b/packages/graphic-walker/src/utils/index.ts
index 6def1098..30f2b5b7 100644
--- a/packages/graphic-walker/src/utils/index.ts
+++ b/packages/graphic-walker/src/utils/index.ts
@@ -1,15 +1,15 @@
import { COUNT_FIELD_ID } from '../constants';
-import { Record, Filters, IMutField, IRow } from '../interfaces';
+import { IRow, Filters, IMutField } from '../interfaces';
interface NRReturns {
- normalizedData: Record[];
- maxMeasures: Record;
- minMeasures: Record;
- totalMeasures: Record
+ normalizedData: IRow[];
+ maxMeasures:IRow;
+ minMeasures:IRow;
+ totalMeasures:IRow
}
-function normalizeRecords(dataSource: Record[], measures: string[]): NRReturns {
- const maxMeasures: Record = {};
- const minMeasures: Record = {};
- const totalMeasures: Record = {};
+function normalizeRecords(dataSource: IRow[], measures: string[]): NRReturns {
+ const maxMeasures: IRow = {};
+ const minMeasures: IRow = {};
+ const totalMeasures: IRow = {};
measures.forEach(mea => {
maxMeasures[mea] = -Infinity;
minMeasures[mea] = Infinity;
@@ -21,9 +21,9 @@ function normalizeRecords(dataSource: Record[], measures: string[]): NRReturns {
minMeasures[mea] = Math.min(record[mea], minMeasures[mea])
})
})
- const newData: Record[] = [];
+ const newData: IRow[] = [];
dataSource.forEach(record => {
- const norRecord: Record = { ... record };
+ const norRecord: IRow = { ... record };
measures.forEach(mea => {
// norRecord[mea] = norRecord[mea] - minMeasures[mea]
totalMeasures[mea] += Math.abs(norRecord[mea]);
@@ -43,10 +43,10 @@ function normalizeRecords(dataSource: Record[], measures: string[]): NRReturns {
}
}
-function normalize2PositiveRecords(dataSource: Record[], measures: string[]): NRReturns {
- const maxMeasures: Record = {};
- const minMeasures: Record = {};
- const totalMeasures: Record = {};
+function normalize2PositiveRecords(dataSource: IRow[], measures: string[]): NRReturns {
+ const maxMeasures: IRow = {};
+ const minMeasures: IRow = {};
+ const totalMeasures: IRow = {};
measures.forEach((mea) => {
maxMeasures[mea] = -Infinity;
minMeasures[mea] = Infinity;
@@ -58,9 +58,9 @@ function normalize2PositiveRecords(dataSource: Record[], measures: string[]): NR
minMeasures[mea] = Math.min(record[mea], minMeasures[mea]);
});
});
- const newData: Record[] = [];
+ const newData: IRow[] = [];
dataSource.forEach((record) => {
- const norRecord: Record = { ...record };
+ const norRecord: IRow = { ...record };
measures.forEach((mea) => {
norRecord[mea] = norRecord[mea] - minMeasures[mea]
totalMeasures[mea] += norRecord[mea];
@@ -83,7 +83,7 @@ function normalize2PositiveRecords(dataSource: Record[], measures: string[]): NR
};
}
-export function checkMajorFactor(data: Record[], childrenData: Map<any, Record[]>, dimensions: string[], measures: string[]): { majorKey: string; majorSum: number } {
+export function checkMajorFactor(data: IRow[], childrenData: Map<any, IRow[]>, dimensions: string[], measures: string[]): { majorKey: string; majorSum: number } {
const { normalizedData, maxMeasures, minMeasures, totalMeasures } = normalizeRecords(data, measures);
let majorSum = Infinity;
let majorKey = '';
@@ -114,7 +114,7 @@ export function checkMajorFactor(data: Record[], childrenData: Map<any, Record[]
return { majorKey, majorSum };
}
-export function checkChildOutlier(data: Record[], childrenData: Map<any, Record[]>, dimensions: string[], measures: string[]): { outlierKey: string; outlierSum: number } {
+export function checkChildOutlier(data: IRow[], childrenData: Map<any, IRow[]>, dimensions: string[], measures: string[]): { outlierKey: string; outlierSum: number } {
// const { normalizedData, maxMeasures, minMeasures, totalMeasures } = normalize2PositiveRecords(data, measures);
const { normalizedData, maxMeasures, minMeasures, totalMeasures } = normalizeRecords(data, measures);
let outlierSum = -Infinity;
@@ -151,7 +151,7 @@ export interface IPredicate {
type: 'discrete' | 'continuous';
range: Set<any> | [number, number];
}
-export function getPredicates(selection: Record[], dimensions: string[], measures: string[]): IPredicate[] {
+export function getPredicates(selection: IRow[], dimensions: string[], measures: string[]): IPredicate[] {
const predicates: IPredicate[] = [];
dimensions.forEach(dim => {
predicates.push({
@@ -197,7 +197,7 @@ export function getPredicatesFromVegaSignals(signals: Filters, dimensions: strin
return predicates;
}
-export function filterByPredicates(data: Record[], predicates: IPredicate[]): Record[] {
+export function filterByPredicates(data: IRow[], predicates: IPredicate[]): IRow[] {
const filterData = data.filter((record) => {
return predicates.every((pre) => {
if (pre.type === 'continuous') {
@@ -213,7 +213,7 @@ export function filterByPredicates(data: Record[], predicates: IPredicate[]): Re
return filterData;
}
-export function applyFilters(dataSource: Record[], filters: Filters): Record[] {
+export function applyFilters(dataSource: IRow[], filters: Filters): IRow[] {
let filterKeys = Object.keys(filters);
return dataSource.filter((record) => {
let keep = true;
diff --git a/packages/graphic-walker/src/utils/normalization.ts b/packages/graphic-walker/src/utils/normalization.ts
index 35c6e3cd..b0feee84 100644
--- a/packages/graphic-walker/src/utils/normalization.ts
+++ b/packages/graphic-walker/src/utils/normalization.ts
@@ -1,16 +1,16 @@
-import { IRow, Record } from '../interfaces';
+import { IRow } from '../interfaces';
export function normalizeWithParent(
- data: Record[],
- parentData: Record[],
+ data: IRow[],
+ parentData: IRow[],
measures: string[],
syncScale: boolean
): {
- normalizedData: Record[];
- normalizedParentData: Record[];
+ normalizedData: IRow[];
+ normalizedParentData: IRow[];
} {
- const totalMeasuresOfParent: Record = {};
- const totalMeasures: Record = {};
+ const totalMeasuresOfParent: IRow = {};
+ const totalMeasures: IRow = {};
measures.forEach(mea => {
totalMeasuresOfParent[mea] = 0;
totalMeasures[mea] = 0;
@@ -25,7 +25,7 @@ export function normalizeWithParent(
totalMeasures[mea] += Math.abs(record[mea]);
})
})
- const normalizedParentData: Record[] = [];
+ const normalizedParentData: IRow[] = [];
parentData.forEach(record => {
const newRecord = { ...record };
measures.forEach(mea => {
@@ -33,7 +33,7 @@ export function normalizeWithParent(
})
normalizedParentData.push(newRecord);
})
- const normalizedData: Record[] = [];
+ const normalizedData: IRow[] = [];
data.forEach(record => {
const newRecord = { ...record };
measures.forEach(mea => {
@@ -51,7 +51,7 @@ export function normalizeWithParent(
};
}
-export function compareDistribution (distribution1: Record[], distribution2: Record[], 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);
@@ -95,7 +95,7 @@ export function compareDistribution (distribution1: Record[], distribution2: Rec
return score;
}
-export function normalizeByMeasures (dataSource: Record[], measures: string[]) {
+export function normalizeByMeasures (dataSource: IRow[], measures: string[]) {
let sums: Map<string, number> = new Map();
measures.forEach(mea => {
@@ -108,9 +108,9 @@ export function normalizeByMeasures (dataSource: Record[], measures: string[]) {
})
})
- const ans: Record[] = [];
+ const ans: IRow[] = [];
dataSource.forEach(record => {
- const norRecord: Record = { ...record };
+ const norRecord: IRow = { ...record };
measures.forEach(mea => {
norRecord[mea] /= sums.get(mea)!;
})
@@ -119,7 +119,7 @@ export function normalizeByMeasures (dataSource: Record[], measures: string[]) {
return ans;
}
-export function getDistributionDifference(dataSource: Record[], 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) {
// score += Math.abs(record[measure1] - record[measure2])
diff --git a/packages/graphic-walker/src/utils/save.ts b/packages/graphic-walker/src/utils/save.ts
new file mode 100644
index 00000000..93afff02
--- /dev/null
+++ b/packages/graphic-walker/src/utils/save.ts
@@ -0,0 +1,46 @@
+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 parseGWPureSpec (list: IVisSpec[]): VisSpecWithHistory[] {
+ return list.map(l => new VisSpecWithHistory(l))
+}
+
+interface IStoInfo {
+ datasets: IDataSet[];
+ specList: IVisSpec[];
+ dataSources: IDataSource[]
+}
+
+export function stringifyGWContent (info: IStoInfo) {
+ return JSON.stringify(info)
+}
+
+export function parseGWContent (raw: string): IStoInfo {
+ return JSON.parse(raw)
+}
+// JSON.stringify
+
+export function download(data: string, filename: string, type: string) {
+ var file = new Blob([data], {type: type});
+ // @ts-ignore
+ if (window.navigator.msSaveOrOpenBlob) // IE10+
+ // @ts-ignore
+ window.navigator.msSaveOrOpenBlob(file, filename);
+ else { // Others
+ var a = document.createElement("a"),
+ url = URL.createObjectURL(file);
+ a.href = url;
+ a.download = filename;
+ document.body.appendChild(a);
+ a.click();
+ setTimeout(function() {
+ document.body.removeChild(a);
+ window.URL.revokeObjectURL(url);
+ }, 0);
+ }
+}
\ No newline at end of file
diff --git a/packages/graphic-walker/src/vis/future-react-vega.tsx b/packages/graphic-walker/src/vis/future-react-vega.tsx
index 671b4292..5e28f405 100644
--- a/packages/graphic-walker/src/vis/future-react-vega.tsx
+++ b/packages/graphic-walker/src/vis/future-react-vega.tsx
@@ -3,7 +3,7 @@
* https://github.com/vega/vega-lite/issues/4680
*/
import React, { useEffect, useRef } from 'react';
-import { IField, IViewField, Record } from '../interfaces';
+import { IField, IViewField, IRow } from '../interfaces';
import embed from 'vega-embed';
import { Subject } from 'rxjs'
import * as op from 'rxjs/operators';
@@ -12,7 +12,7 @@ const SELECTION_NAME = 'geom';
interface ReactVegaProps {
rows: IField[];
columns: IField[];
- dataSource: Record[];
+ dataSource: IRow[];
defaultAggregate?: boolean;
geomType: string;
color?: IField;