An open source alternative to Tableau. Embeddable visual analytic
TypeScript bidatadata-analysisdata-miningdata-visualizationedak6skanarieslow-codepivot-tablereacttableautableau-alternativetypescriptvegavega-litevisualization
fix: dragging count field to left side is broken (#230)
islxyqwea699b7c2198f
diff --git a/packages/graphic-walker/src/components/visualConfig/index.tsx b/packages/graphic-walker/src/components/visualConfig/index.tsxindex ac8e9267..3d9f1ba5 100644--- a/packages/graphic-walker/src/components/visualConfig/index.tsx+++ b/packages/graphic-walker/src/components/visualConfig/index.tsx@@ -98,6 +98,7 @@ const VisualConfigPanel: React.FC = () => {useEffect(() => {setZeroScale(layout.zeroScale);+ setSvg(layout.useSvg ?? false);setBackground(layout.background);setResolve(layout.resolve);setDefaultColor(extractRGBA(layout.primaryColor));diff --git a/packages/graphic-walker/src/lib/gog.ts b/packages/graphic-walker/src/lib/gog.tsindex 2d5cbfc5..90e6d82d 100644--- a/packages/graphic-walker/src/lib/gog.ts+++ b/packages/graphic-walker/src/lib/gog.ts@@ -1,17 +1,16 @@// File name: gog represents the Grammar of Graphics (theory by Wilkinson)-import { DraggableFieldState, IAnalyticType, ISemanticType } from "../interfaces";+import { DraggableFieldState, IAnalyticType, ISemanticType } from '../interfaces';-type SpitialEncodings = Pick<DraggableFieldState, 'columns' | 'rows'> | Pick<DraggableFieldState, 'latitude' | 'longitude'>type DraggableFieldValues = DraggableFieldState[Exclude<keyof DraggableFieldState, 'filters'>];// LR = Lint Rulesconst LR = {/*** measures should appear after dimensions, for we do not apply cross operator on measures.- * @param fields- * @returns+ * @param fields+ * @returns*/measureAfterDimension(fields: DraggableFieldValues): DraggableFieldValues {- return fields.filter(f => f.analyticType === 'dimension').concat(fields.filter(f => f.analyticType === 'measure'));+ return fields.filter((f) => f.analyticType === 'dimension').concat(fields.filter((f) => f.analyticType === 'measure'));},// due to renderer, we set a limit of var can be applied to cross operator in GoG.crossLimit(maxLimit: number) {@@ -27,25 +26,25 @@ const LR = {}return acc;}, [] as DraggableFieldValues);- }+ };},- forceAnalyticType (analyticType: IAnalyticType) {+ forceAnalyticType(analyticType: IAnalyticType) {return function (fields: DraggableFieldValues): DraggableFieldValues {- return fields.map(f => ({+ return fields.map((f) => ({...f,- analyticType- }))- }+ analyticType,+ }));+ };},- forceSemanticType (semanticType: ISemanticType) {+ forceSemanticType(semanticType: ISemanticType) {return function (fields: DraggableFieldValues): DraggableFieldValues {- return fields.map(f => ({+ return fields.map((f) => ({...f,- semanticType- }))- }+ semanticType,+ }));+ };},-}+};type Operator<T> = (value: T) => T;function applyOperations<T>(initialValue: T, operators: Operator<T>[]): T {return operators.reduce((currentValue, operator) => operator(currentValue), initialValue);@@ -55,33 +54,22 @@ function applyOperations<T>(initialValue: T, operators: Operator<T>[]): T {* Algebra lint is the lint fix encoding settings in algebra stage in the grammar of graphics.* graphic-walker calculates the algebra on spitial channels (axises) (for now, rows, columns)* This steps mainly decide how the sql is generated.- * @param encodings- * @returns+ * @param encodings+ * @returns*/-export function algebraLint <T extends SpitialEncodings | DraggableFieldValues>(encodings: T): T {- if (Array.isArray(encodings)) {- return LR.measureAfterDimension(encodings) as T+export function algebraLint<T extends Partial<DraggableFieldState>>(encodings: T): Partial<T> {+ const result: Partial<T> = {};+ if (encodings.rows && encodings.rows.length > 0) {+ result.rows = applyOperations(encodings.rows, [LR.measureAfterDimension, LR.crossLimit(2)]);}- if ('rows' in encodings && 'columns' in encodings && (encodings.rows.length > 0 || encodings.columns.length > 0)) {- return {- ...encodings,- rows: applyOperations(encodings.rows, [LR.measureAfterDimension, LR.crossLimit(2)]),- columns: applyOperations(encodings.columns, [LR.measureAfterDimension, LR.crossLimit(2)])- };- } else if ('latitude' in encodings && 'longitude' in encodings && (encodings.latitude.length > 0 || encodings.longitude.length > 0)) {- return {- ...encodings,- latitude: applyOperations(encodings.latitude, [- LR.forceAnalyticType('dimension'),- LR.forceSemanticType('quantitative'),- LR.crossLimit(1)- ]),- longitude: applyOperations(encodings.longitude, [- LR.forceAnalyticType('dimension'),- LR.forceSemanticType('quantitative'),- LR.crossLimit(1)- ])- };+ if (encodings.columns && encodings.columns.length > 0) {+ result.columns = applyOperations(encodings.columns, [LR.measureAfterDimension, LR.crossLimit(2)]);+ }+ if (encodings.latitude && encodings.latitude.length > 0) {+ result.latitude = applyOperations(encodings.latitude, [LR.forceAnalyticType('dimension'), LR.forceSemanticType('quantitative'), LR.crossLimit(1)]);}- return encodings;-}\ No newline at end of file+ if (encodings.longitude && encodings.longitude.length > 0) {+ result.longitude = applyOperations(encodings.longitude, [LR.forceAnalyticType('dimension'), LR.forceSemanticType('quantitative'), LR.crossLimit(1)]);+ }+ return result;+}diff --git a/packages/graphic-walker/src/models/visSpecHistory.ts b/packages/graphic-walker/src/models/visSpecHistory.tsindex 1e1f69c5..74e7b736 100644--- a/packages/graphic-walker/src/models/visSpecHistory.ts+++ b/packages/graphic-walker/src/models/visSpecHistory.ts@@ -23,7 +23,7 @@ import { emptyEncodings, emptyVisualConfig, emptyVisualLayout } from '../utils/simport { AssertSameKey, KVTuple, insert, mutPath, remove, replace, uniqueId } from './utils';import { WithHistory, atWith, create, freeze, performWith, redoWith, undoWith } from './withHistory';import { GLOBAL_CONFIG } from '../config';-import { DATE_TIME_DRILL_LEVELS, DATE_TIME_FEATURE_LEVELS } from '../constants';+import { COUNT_FIELD_ID, DATE_TIME_DRILL_LEVELS, DATE_TIME_FEATURE_LEVELS, MEA_KEY_ID, MEA_VAL_ID } from '../constants';import { algebraLint } from '../lib/gog';type normalKeys = keyof Omit<DraggableFieldState, 'filters'>;@@ -87,13 +87,11 @@ const actions: {[Methods.removeField]: (data, encoding, index) => mutPath(data, `encodings.${encoding}`, (fields) => remove(fields, index)) as IChart,[Methods.reorderField]: (data, encoding, from, to) =>mutPath(data, `encodings.${encoding}`, (fields) =>- algebraLint(- fields.map((x, i, a) => {- if (i === from) return a[to];- if (i === to) return a[from];- return x;- })- )+ fields.map((x, i, a) => {+ if (i === from) return a[to];+ if (i === to) return a[from];+ return x;+ })),[Methods.moveField]: (data, from, findex, to, tindex, limit) => {const oriField = data.encodings[from][findex];@@ -103,22 +101,18 @@ const actions: {: to === 'measures'? mutPath(oriField, 'analyticType', () => 'measure'): oriField;- return mutPath(data, 'encodings', (e) =>- algebraLint({- ...e,- [from]: remove(data.encodings[from], findex),- [to]: insert(data.encodings[to], field, tindex).slice(0, limit ?? Infinity),- })- );+ return mutPath(data, 'encodings', (e) => ({+ ...e,+ [from]: remove(data.encodings[from], findex),+ [to]: insert(data.encodings[to], field, tindex).slice(0, limit ?? Infinity),+ }));},[Methods.cloneField]: (data, from, findex, to, tindex, newVarKey, limit) => {const field = { ...data.encodings[from][findex], dragId: newVarKey };- return mutPath(data, 'encodings', (e) =>- algebraLint({- ...e,- [to]: insert(data.encodings[to], field, tindex).slice(0, limit ?? Infinity),- })- );+ return mutPath(data, 'encodings', (e) => ({+ ...e,+ [to]: insert(data.encodings[to], field, tindex).slice(0, limit ?? Infinity),+ }));},[Methods.createBinlogField]: (data, encoding, index, op, newVarKey, num) => {const originField = data.encodings[encoding][index];@@ -191,13 +185,11 @@ const actions: {return data;},[Methods.transpose]: (data) =>- mutPath(data, 'encodings', (e) =>- algebraLint({- ...e,- columns: e.rows,- rows: e.columns,- })- ),+ mutPath(data, 'encodings', (e) => ({+ ...e,+ columns: e.rows,+ rows: e.columns,+ })),[Methods.setLayout]: (data, kvs) => mutPath(data, 'layout', (l) => Object.assign({}, l, Object.fromEntries(kvs))),[Methods.setFieldAggregator]: (data, encoding, index, aggName) =>mutPath(data, `encodings.${encoding}`, (f) => replace(f, index, (x) => ({ ...x, aggName }))),@@ -283,14 +275,61 @@ const actions: {return mutPath(data, `encodings.${channel}`, (f) => replace(f, index, (x) => ({ ...x, semanticType })));},[Methods.setFilterAggregator]: (data, index, aggName) => {- return mutPath(data, `encodings.filters`, (f) => replace(f, index, (x) => ({ ...x, aggName: aggName || 'sum', enableAgg: aggName ? true : false, rule: null })));+ return mutPath(data, `encodings.filters`, (f) =>+ replace(f, index, (x) => ({ ...x, aggName: aggName || 'sum', enableAgg: aggName ? true : false, rule: null }))+ );},};+const diffChangedEncodings = (prev: IChart, next: IChart) => {+ const result: Partial<DraggableFieldState> = {};+ Object.keys(next.encodings).forEach((k) => {+ if (next.encodings[k] !== prev.encodings[k]) {+ result[k] = next.encodings[k];+ }+ });+ return result;+};++function makeFieldAtLast<T>(arr: T[], lasts: ((item: T) => boolean)[]): T[] {+ const result: T[] = [];+ const found: T[][] = new Array(lasts.length).fill(null).map(() => []);+ arr.forEach((x) => {+ const i = lasts.findIndex((f) => f(x));+ if (i >= 0) {+ found[i].push(x);+ } else {+ result.push(x);+ }+ });+ return result.concat(found.flat());+}++function lintExtraFields<T extends Partial<DraggableFieldState>>(encodings: T): Partial<T> {+ const result: Partial<T> = {};+ if (encodings.dimensions && encodings.dimensions.length > 0) {+ result.dimensions = makeFieldAtLast(encodings.dimensions, [(i) => i.fid === MEA_KEY_ID]);+ }+ if (encodings.measures && encodings.measures.length > 0) {+ result.measures = makeFieldAtLast(encodings.measures, [(i) => i.fid === COUNT_FIELD_ID, (i) => i.fid === MEA_VAL_ID]);+ }+ return result;+}++type reducerMiddleware<T> = (item: T, original: T) => T;++const diffLinter: reducerMiddleware<IChart> = (item, original) => {+ const diffs = diffChangedEncodings(original, item);+ return mutPath(item, 'encodings', (x) => ({ ...x, ...algebraLint(diffs), ...lintExtraFields(diffs) }));+};++const reducerMiddleWares: reducerMiddleware<IChart>[] = [diffLinter];function reducerT<T>(data: IChart, action: VisActionOf<T>): IChart {const [type, ...props] = action;- return actions[type](data, ...props);+ const result = actions[type](data, ...props);+ return reducerMiddleWares.reduce((item, f) => f(item, data), result);}+export type VisSpecWithHistory = WithHistory<IChart, VisAction>;export const reducer: (data: IChart, action: VisAction) => IChart = reducerT;export const perform: (data: VisSpecWithHistory, action: VisAction) => VisSpecWithHistory = performWith(reducerT);@@ -336,7 +375,7 @@ function emptyChart(visId: string, name: string): IChart {}export function newChart(fields: IMutField[], name: string, visId?: string): IChart {if (fields.length === 0) return emptyChart(visId || uniqueId(), name);- const extraFields = [...createVirtualFields(), createCountField()];+ const extraFields = [createCountField(), ...createVirtualFields()];const extraDimensions = extraFields.filter((x) => x.analyticType === 'dimension');const extraMeasures = extraFields.filter((x) => x.analyticType === 'measure');return mutPath(emptyChart(visId || uniqueId(), name), 'encodings', (e) => ({diff --git a/packages/graphic-walker/src/store/visualSpecStore.ts b/packages/graphic-walker/src/store/visualSpecStore.tsindex 95222aa5..4e125aac 100644--- a/packages/graphic-walker/src/store/visualSpecStore.ts+++ b/packages/graphic-walker/src/store/visualSpecStore.ts@@ -334,7 +334,7 @@ export class VizSpecStore {const oriF = this.currentEncodings[sourceKey][sourceIndex];const sourceMeta = GLOBAL_CONFIG.META_FIELD_KEYS.includes(sourceKey);const destMeta = GLOBAL_CONFIG.META_FIELD_KEYS.includes(destinationKey);- if (destMeta && (oriF.fid === MEA_KEY_ID || oriF.fid === MEA_VAL_ID || oriF.fid === COUNT_FIELD_ID)) {+ if (sourceMeta && destMeta && (oriF.fid === MEA_KEY_ID || oriF.fid === MEA_VAL_ID || oriF.fid === COUNT_FIELD_ID)) {return;}const limit = GLOBAL_CONFIG.CHANNEL_LIMIT[destinationKey] ?? Infinity;