An open source alternative to Tableau. Embeddable visual analytic
TypeScript bidatadata-analysisdata-miningdata-visualizationedak6skanarieslow-codepivot-tablereacttableautableau-alternativetypescriptvegavega-litevisualization
fix: import and export with vega-lite (#489)
islxyqwe0f52cabf376e
diff --git a/packages/graphic-walker/jest.config.js b/packages/graphic-walker/jest.config.jsindex 16148cfb..0c0e996f 100644--- a/packages/graphic-walker/jest.config.js+++ b/packages/graphic-walker/jest.config.js@@ -5,4 +5,5 @@ module.exports = {moduleNameMapper: {'^@/(.*)$': '<rootDir>/src/$1',},+ testPathIgnorePatterns: ['<rootDir>/dist/'],};diff --git a/packages/graphic-walker/src/App.tsx b/packages/graphic-walker/src/App.tsxindex e730cccf..911e54f4 100644--- a/packages/graphic-walker/src/App.tsx+++ b/packages/graphic-walker/src/App.tsx@@ -123,10 +123,10 @@ export const VizApp = observer(function VizApp(props: BaseVizProps) {const emptyChart = newChart(vizStore.meta, '');vizStore.replaceNow(VegaliteMapper(- spec,+ vlSpec,[...emptyChart.encodings.dimensions, ...emptyChart.encodings.measures],- vizStore.currentVis.name ?? 'Chart 1',- vizStore.currentVis.visId+ vizStore.currentVis.visId,+ vizStore.currentVis.name ?? 'Chart 1'));}@@ -172,7 +172,11 @@ export const VizApp = observer(function VizApp(props: BaseVizProps) {<FieldsContextWrapper><div className="bg-background text-foreground w-full h-full"><Errorpanel />- <Tabs value={segmentKey} onValueChange={(v) => vizStore.setSegmentKey(v as ISegmentKey)} className='w-full h-full flex flex-col'>+ <Tabs+ value={segmentKey}+ onValueChange={(v) => vizStore.setSegmentKey(v as ISegmentKey)}+ className="w-full h-full flex flex-col"+ >{!hideSegmentNav && (<TabsList className="mx-4"><TabsTrigger value={ISegmentKey.data}>@@ -193,7 +197,7 @@ export const VizApp = observer(function VizApp(props: BaseVizProps) {<DatasetConfig hideProfiling={hideProfiling} /></div></TabsContent>- <TabsContent value={ISegmentKey.vis} className='flex-1 min-h-0 flex flex-col'>+ <TabsContent value={ISegmentKey.vis} className="flex-1 min-h-0 flex flex-col">{!props.hideChartNav && (<div className="px-2 mx-2 mt-2"><VisNav />@@ -342,7 +346,14 @@ export function VizAppWithContext(props: IVizAppProps & IComputationProps) {const darkMode = useCurrentMediaTheme(appearance);return (- <VizStoreWrapper onMetaChange={safeOnMetaChange} meta={safeMetas} keepAlive={keepAlive} storeRef={storeRef} defaultConfig={defaultConfig} defaultRenderer={defaultRenderer}>+ <VizStoreWrapper+ onMetaChange={safeOnMetaChange}+ meta={safeMetas}+ keepAlive={keepAlive}+ storeRef={storeRef}+ defaultConfig={defaultConfig}+ defaultRenderer={defaultRenderer}+ ><VizApp darkMode={darkMode} computation={safeComputation} {...rest} /></VizStoreWrapper>);diff --git a/packages/graphic-walker/src/components/codeExport/index.tsx b/packages/graphic-walker/src/components/codeExport/index.tsxindex f347d7ce..9d7e661e 100644--- a/packages/graphic-walker/src/components/codeExport/index.tsx+++ b/packages/graphic-walker/src/components/codeExport/index.tsx@@ -5,6 +5,7 @@ import { useTranslation } from 'react-i18next';import { Dialog, DialogContent, DialogFooter } from '../ui/dialog';import { Button } from '../ui/button';import { Tabs, TabsList, TabsTrigger } from '../ui/tabs';+import { toVegaSimplifiedWithAggergation } from '@/models/chat';const syntaxHighlight = (json: any) => {if (typeof json != 'string') {@@ -39,7 +40,7 @@ const CodeExport: React.FC = observer((props) => {const { showCodeExportPanel } = vizStore;const { t } = useTranslation();const [tabKey, setTabKey] = useState<string>('graphic-walker');- const [code, setCode] = useState<any>('');+ const [code, setCode] = useState('');const specTabs: { key: string; label: string }[] = [{@@ -64,12 +65,12 @@ const CodeExport: React.FC = observer((props) => {if (showCodeExportPanel) {if (tabKey === 'graphic-walker') {const res = vizStore.exportCode();- setCode(res);+ setCode(JSON.stringify(res, null, 4));} else if (tabKey === 'vega-lite') {- setCode(vizStore.lastSpec);+ setCode(JSON.stringify(vizStore.exportCode().map(toVegaSimplifiedWithAggergation), null, 4));} else if (tabKey === 'workflow') {const workflow = vizStore.workflow;- setCode(workflow);+ setCode(JSON.stringify(workflow, null, 4));} else {console.error('unknown tabKey');}@@ -102,7 +103,7 @@ const CodeExport: React.FC = observer((props) => {<Buttonchildren="Copy to Clipboard"onClick={() => {- navigator.clipboard.writeText(JSON.stringify(code));+ navigator.clipboard.writeText(code);vizStore.setShowCodeExportPanel(false);}}/>diff --git a/packages/graphic-walker/src/models/chat.test.ts b/packages/graphic-walker/src/models/chat.test.tsnew file mode 100644index 00000000..3433bd74--- /dev/null+++ b/packages/graphic-walker/src/models/chat.test.ts@@ -0,0 +1,109 @@+jest.mock('nanoid', () => ({ nanoid: () => 'mock-id' }));++import { toVegaSimplifiedWithAggergation } from './chat';+import type { DraggableFieldState, IChart, IViewField, IVisualLayout } from '@/interfaces';++const createTestChart = (defaultAggregated = true): IChart => {+ const dimensionField: IViewField = {+ fid: 'gender',+ name: 'gender',+ basename: 'gender',+ semanticType: 'nominal',+ analyticType: 'dimension',+ };++ const measureField: IViewField = {+ fid: 'reading score',+ name: 'reading score',+ basename: 'reading score',+ semanticType: 'quantitative',+ analyticType: 'measure',+ aggName: 'mean',+ };++ const encodings: DraggableFieldState = {+ dimensions: [dimensionField],+ measures: [+ {+ ...measureField,+ aggName: 'sum',+ },+ ],+ rows: [measureField],+ columns: [dimensionField],+ color: [],+ opacity: [],+ size: [],+ shape: [],+ theta: [],+ radius: [],+ longitude: [],+ latitude: [],+ geoId: [],+ details: [],+ filters: [],+ text: [],+ };++ const layout: IVisualLayout = {+ showTableSummary: false,+ format: {},+ resolve: {},+ size: {+ mode: 'auto',+ width: 320,+ height: 200,+ },+ interactiveScale: false,+ stack: 'stack',+ showActions: false,+ zeroScale: true,+ renderer: 'vega-lite',+ };++ return {+ visId: 'gw__test',+ name: 'Chart 1',+ config: {+ defaultAggregated,+ geoms: ['auto'],+ coordSystem: 'generic',+ limit: -1,+ },+ encodings,+ layout,+ };+};++describe('toVegaSimplifiedWithAggergation', () => {+ it('restores base field names and adds aggregate metadata when defaultAggregated is true', () => {+ const spec = toVegaSimplifiedWithAggergation(createTestChart(true));++ expect(spec.encoding?.y).toEqual(+ expect.objectContaining({+ field: 'reading score',+ aggregate: 'mean',+ title: 'mean(reading score)',+ })+ );++ expect(spec.encoding?.x).toEqual(+ expect.objectContaining({+ field: 'gender',+ type: 'nominal',+ })+ );+ });++ it('omits aggregate metadata when defaultAggregated is false', () => {+ const spec = toVegaSimplifiedWithAggergation(createTestChart(false));++ expect(spec.encoding?.y?.aggregate).toBeUndefined();+ expect(spec.encoding?.y).toEqual(+ expect.objectContaining({+ field: 'reading score',+ type: 'quantitative',+ })+ );+ });+});diff --git a/packages/graphic-walker/src/models/chat.ts b/packages/graphic-walker/src/models/chat.tsindex 50e4bb2c..278d3e38 100644--- a/packages/graphic-walker/src/models/chat.ts+++ b/packages/graphic-walker/src/models/chat.ts@@ -1,6 +1,6 @@import { toVegaSpec } from '@/lib/vega';import { Methods, PropsMap, VisActionOf, VisSpecWithHistory, reducer } from './visSpecHistory';-import type { IChart, IChatMessage, IFilterField, IViewField } from '@/interfaces';+import type { IAggregator, IChart, IChatMessage, IFilterField, IViewField } from '@/interfaces';import { GLOBAL_CONFIG } from '@/config';import { autoMark } from '@/vis/spec/mark';import { viewEncodingKeys } from './visSpec';@@ -119,6 +119,118 @@ export function toVegaSimplified(chart: IChart) {};}+const aggNameMap: Record<IAggregator, string> = {+ count: 'count',+ sum: 'sum',+ max: 'max',+ min: 'min',+ mean: 'mean',+ median: 'median',+ variance: 'variance',+ stdev: 'stdev',+ distinctCount: 'distinct',+ expr: '', // computed expression aggregations already encode their logic+};++export function toVegaSimplifiedWithAggergation(chart: IChart) {+ const simplifiedSpec = toVegaSimplified(chart);+ const shouldAnnotateAggregate = Boolean(chart.config.defaultAggregated);+ const ROW_COUNT_FID = 'gw_count_fid';++ type FieldMeta = {+ title: string;+ field: string;+ aggregate?: string;+ };++ const fieldMetaMap = new Map<string, FieldMeta>();++ const getFieldTitle = (field: IViewField): string => {+ const fieldLabel = field.name ?? field.fid;+ if (field.fid === ROW_COUNT_FID) {+ return 'Count';+ }+ if (field.analyticType === 'measure' && field.aggName && field.aggName !== 'expr') {+ return `${field.aggName}(${fieldLabel})`;+ }+ return fieldLabel;+ };++ const registerField = (field?: IViewField) => {+ if (!field) return;+ const title = getFieldTitle(field);+ if (!title) {+ return;+ }+ const aggName = shouldAnnotateAggregate ? (field.aggName as IAggregator | undefined) : undefined;+ const aggregate = aggName ? aggNameMap[aggName] : undefined;+ const normalizedAggregate = aggregate && aggregate.length > 0 ? aggregate : undefined;+ const nextMeta: FieldMeta = {+ title,+ field: field.basename ?? field.name ?? field.fid,+ aggregate: normalizedAggregate,+ };+ const existingMeta = fieldMetaMap.get(title);+ if (!existingMeta || (!existingMeta.aggregate && normalizedAggregate)) {+ fieldMetaMap.set(title, nextMeta);+ }+ };++ Object.values(chart.encodings).forEach((fields) => {+ if (Array.isArray(fields)) {+ fields.forEach((field) => registerField(field as IViewField));+ }+ });++ const enhanceFieldDef = (fieldDef: any) => {+ if (!fieldDef || typeof fieldDef !== 'object') {+ return fieldDef;+ }+ const labelKey = typeof fieldDef.field === 'string' ? fieldDef.field : undefined;+ if (!labelKey) {+ return fieldDef;+ }+ const meta = fieldMetaMap.get(labelKey);+ if (!meta) {+ return fieldDef;+ }+ const next: Record<string, any> = { ...fieldDef, field: meta.field, title: meta.title };+ if (meta.aggregate) {+ next.aggregate = meta.aggregate;+ } else if ('aggregate' in next) {+ delete next.aggregate;+ }+ return next;+ };++ const visitSpec = (spec: any) => {+ if (!spec || typeof spec !== 'object') {+ return;+ }+ if (spec.encoding) {+ spec.encoding = Object.fromEntries(+ Object.entries(spec.encoding).map(([channel, value]) => {+ if (Array.isArray(value)) {+ return [channel, value.map((definition) => enhanceFieldDef(definition))];+ }+ return [channel, enhanceFieldDef(value)];+ })+ );+ }+ ['layer', 'concat', 'hconcat', 'vconcat'].forEach((key) => {+ if (Array.isArray(spec[key])) {+ spec[key].forEach(visitSpec);+ }+ });+ if (spec.spec) {+ visitSpec(spec.spec);+ }+ };++ visitSpec(simplifiedSpec);+ return simplifiedSpec;+}+const actionMessageMapper: {[a in Methods]: (data: IChart, ...a: PropsMap[a]) => string;} = {diff --git a/packages/playground/src/examples/nav.tsx b/packages/playground/src/examples/nav.tsxindex a9c31c51..c4ca3156 100644--- a/packages/playground/src/examples/nav.tsx+++ b/packages/playground/src/examples/nav.tsx@@ -51,6 +51,10 @@ export const pages = [comp: () => import('./pages/hideProfiling'),name: 'HideProfiling',},+ {+ comp: () => import('./pages/vlSpec'),+ name: 'VlSpec',+ }].map((Component) => ({name: Component.name,path: Component.name.replace(/\s/g, '_'),diff --git a/packages/playground/src/examples/pages/vlSpec.stories.tsx b/packages/playground/src/examples/pages/vlSpec.stories.tsxnew file mode 100644index 00000000..9ad67c5f--- /dev/null+++ b/packages/playground/src/examples/pages/vlSpec.stories.tsx@@ -0,0 +1,61 @@+import { useContext, useState } from 'react';+import { themeContext } from '../context';+import { GraphicWalker } from '@kanaries/graphic-walker';+import { IDataSource, useFetch } from '../util';++export default function GraphicWalkerComponent() {+ const { theme } = useContext(themeContext);+ const { dataSource, fields } = useFetch<IDataSource>('https://pub-2422ed4100b443659f588f2382cfc7b1.r2.dev/datasets/ds-students-service.json');+ const [vlSpec, setVlspec] = useState<unknown>(undefined);+ const [input, setInput] = useState<string>(`{+ "mark": "bar",+ "encoding": {+ "x": {+ "field": "parental level of education",+ "type": "nominal",+ "title": "parental level of education"+ },+ "y": {+ "field": "math score",+ "type": "quantitative",+ "title": "mean(math score)",+ "aggregate": "mean"+ },+ "color": {+ "field": "gender",+ "type": "nominal",+ "title": "gender"+ }+ }+}`);++ const handleChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {+ setInput(e.target.value);+ };++ const handleApply = () => {+ try {+ const spec = JSON.parse(input);+ setVlspec(spec);+ } catch (error) {+ alert('Invalid JSON');+ }+ };+ return (+ <div>+ <div className="mb-4 flex flex-col gap-2">+ <textarea value={input} onChange={handleChange} placeholder="Enter VL Spec JSON here" className="h-36 m-2 border rounded" />+ <button+ className="ml-2 w-min h-9 px-4 py-2 bg-zinc-950 text-white shadow hover:bg-primary/90 inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50"+ onClick={handleApply}+ >+ Apply VL Spec+ </button>+ </div>+ <div>Try to open `Export Code` and copy the Vega-Lite spec and re-paste it here, then click Apply.</div>+ <div style={{ border: '1px solid #ccc', padding: '8px' }}>+ <GraphicWalker fields={fields} data={dataSource} appearance={theme} vizThemeConfig="g2" vlSpec={vlSpec} />;+ </div>+ </div>+ );+}diff --git a/packages/playground/src/examples/pages/vlSpec.tsx b/packages/playground/src/examples/pages/vlSpec.tsxnew file mode 100644index 00000000..ad52e593--- /dev/null+++ b/packages/playground/src/examples/pages/vlSpec.tsx@@ -0,0 +1,11 @@+import Example from '../components/examplePage';+import code from './vlSpec.stories?raw';+import Comp from './vlSpec.stories';++export default function TableSettingsPage() {+ return (+ <Example name="VlSpec" code={code}>+ <Comp />+ </Example>+ );+}\ No newline at end of file