An open source alternative to Tableau. Embeddable visual analytic
TypeScript bidatadata-analysisdata-miningdata-visualizationedak6skanarieslow-codepivot-tablereacttableautableau-alternativetypescriptvegavega-litevisualization
feat: auto viz recommendations
Elwynn Chenbc32962ac8a1
diff --git a/packages/graphic-walker/src/App.tsx b/packages/graphic-walker/src/App.tsxindex 911e54f4..2a6d794d 100644--- a/packages/graphic-walker/src/App.tsx+++ b/packages/graphic-walker/src/App.tsx@@ -25,6 +25,7 @@ import { mergeLocaleRes, setLocaleLanguage } from './locales/i18n';import FilterField from './fields/filterField';import DatasetConfig from './dataSource/datasetConfig';import CodeExport from './components/codeExport';+import AutoVizPanel from './components/autoViz';import VisualConfig from './components/visualConfig';import ExplainData from './components/explainData';import GeoConfigPanel from './components/leafletRenderer/geoConfigPanel';@@ -281,6 +282,7 @@ export const VizApp = observer(function VizApp(props: BaseVizProps) {<VizEmbedMenu /></div></div>+ <AutoVizPanel /></div></div></TabsContent>diff --git a/packages/graphic-walker/src/components/autoViz/chartIcons.tsx b/packages/graphic-walker/src/components/autoViz/chartIcons.tsxnew file mode 100644index 00000000..4df3b4fa--- /dev/null+++ b/packages/graphic-walker/src/components/autoViz/chartIcons.tsx@@ -0,0 +1,237 @@+import React from 'react';+import { IAutoVizChartType } from '../../lib/autoViz';++/**+ * Hand-drawn 32×32 glyphs for the Auto Viz palette.+ * Everything is painted with currentColor (+ opacity layers) so the icons+ * follow the theme in both light and dark mode.+ */++interface IconProps {+ className?: string;+}++const svgProps = (className?: string) =>+ ({+ viewBox: '0 0 32 32',+ fill: 'none',+ stroke: 'currentColor',+ strokeWidth: 1.5,+ strokeLinecap: 'round',+ strokeLinejoin: 'round',+ className,+ 'aria-hidden': true,+ } as const);++const TableIcon: React.FC<IconProps> = ({ className }) => (+ <svg {...svgProps(className)}>+ <rect x="5" y="7" width="22" height="18" rx="1.5" />+ <line x1="5" y1="13" x2="27" y2="13" />+ <line x1="5" y1="19" x2="27" y2="19" />+ <line x1="13" y1="7" x2="13" y2="25" />+ <line x1="20" y1="7" x2="20" y2="25" />+ </svg>+);++const HighlightTableIcon: React.FC<IconProps> = ({ className }) => (+ <svg {...svgProps(className)}>+ <rect x="5" y="7" width="22" height="18" rx="1.5" />+ <line x1="5" y1="13" x2="27" y2="13" />+ <line x1="5" y1="19" x2="27" y2="19" />+ <line x1="13" y1="7" x2="13" y2="25" />+ <line x1="20" y1="7" x2="20" y2="25" />+ <rect x="13" y="13" width="7" height="6" fill="currentColor" opacity="0.55" stroke="none" />+ <rect x="20" y="7" width="7" height="6" fill="currentColor" opacity="0.3" stroke="none" />+ <rect x="5" y="19" width="8" height="6" fill="currentColor" opacity="0.8" stroke="none" />+ </svg>+);++const HeatmapIcon: React.FC<IconProps> = ({ className }) => (+ <svg {...svgProps(className)} stroke="none">+ {[+ [6, 6, 0.2],+ [13.2, 6, 0.5],+ [20.4, 6, 0.9],+ [6, 13.2, 0.55],+ [13.2, 13.2, 0.85],+ [20.4, 13.2, 0.3],+ [6, 20.4, 0.75],+ [13.2, 20.4, 0.25],+ [20.4, 20.4, 0.6],+ ].map(([x, y, o], i) => (+ <rect key={i} x={x} y={y} width="5.8" height="5.8" rx="1" fill="currentColor" opacity={o} />+ ))}+ </svg>+);++const BarIcon: React.FC<IconProps> = ({ className }) => (+ <svg {...svgProps(className)}>+ <rect x="6" y="14" width="5" height="12" rx="0.5" fill="currentColor" stroke="none" />+ <rect x="13.5" y="7" width="5" height="19" rx="0.5" fill="currentColor" stroke="none" />+ <rect x="21" y="17" width="5" height="9" rx="0.5" fill="currentColor" stroke="none" />+ <line x1="4" y1="26.75" x2="28" y2="26.75" opacity="0.4" />+ </svg>+);++const StackedBarIcon: React.FC<IconProps> = ({ className }) => (+ <svg {...svgProps(className)} stroke="none">+ <rect x="6" y="17" width="5" height="9" fill="currentColor" />+ <rect x="6" y="11" width="5" height="5.4" fill="currentColor" opacity="0.4" />+ <rect x="13.5" y="14" width="5" height="12" fill="currentColor" />+ <rect x="13.5" y="6.5" width="5" height="6.9" fill="currentColor" opacity="0.4" />+ <rect x="21" y="20" width="5" height="6" fill="currentColor" />+ <rect x="21" y="15.5" width="5" height="3.9" fill="currentColor" opacity="0.4" />+ <line x1="4" y1="26.75" x2="28" y2="26.75" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" opacity="0.4" />+ </svg>+);++const GroupedBarIcon: React.FC<IconProps> = ({ className }) => (+ <svg {...svgProps(className)} stroke="none">+ <rect x="6" y="12" width="4.2" height="14" fill="currentColor" />+ <rect x="10.8" y="17" width="4.2" height="9" fill="currentColor" opacity="0.45" />+ <rect x="17.5" y="9" width="4.2" height="17" fill="currentColor" />+ <rect x="22.3" y="14" width="4.2" height="12" fill="currentColor" opacity="0.45" />+ <line x1="4" y1="26.75" x2="28" y2="26.75" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" opacity="0.4" />+ </svg>+);++const LineIcon: React.FC<IconProps> = ({ className }) => (+ <svg {...svgProps(className)}>+ <polyline points="5,22 12,11 19,16 27,7" />+ {[+ [5, 22],+ [12, 11],+ [19, 16],+ [27, 7],+ ].map(([cx, cy], i) => (+ <circle key={i} cx={cx} cy={cy} r="1.6" fill="currentColor" stroke="none" />+ ))}+ </svg>+);++const AreaIcon: React.FC<IconProps> = ({ className }) => (+ <svg {...svgProps(className)}>+ <path d="M5,24 L12,12 L19,16.5 L27,7.5 L27,24 Z" fill="currentColor" opacity="0.25" stroke="none" />+ <polyline points="5,24 12,12 19,16.5 27,7.5" />+ </svg>+);++const HistogramIcon: React.FC<IconProps> = ({ className }) => (+ <svg {...svgProps(className)} stroke="none">+ {[6, 10, 15, 19, 13, 7].map((h, i) => (+ <rect key={i} x={5 + i * 3.7} y={26 - h} width="3.3" height={h} rx="0.4" fill="currentColor" opacity={0.85} />+ ))}+ <line x1="4" y1="26.75" x2="28" y2="26.75" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" opacity="0.4" />+ </svg>+);++const ScatterIcon: React.FC<IconProps> = ({ className }) => (+ <svg {...svgProps(className)} stroke="none">+ {[+ [8, 21, 1],+ [11, 15, 1],+ [14.5, 18, 1],+ [17, 10, 1],+ [20.5, 13.5, 1],+ [24.5, 8, 1],+ [22.5, 18.5, 0.45],+ [9.5, 10.5, 0.45],+ [26, 22, 0.45],+ ].map(([cx, cy, o], i) => (+ <circle key={i} cx={cx} cy={cy} r="1.8" fill="currentColor" opacity={o} />+ ))}+ </svg>+);++const CircleViewIcon: React.FC<IconProps> = ({ className }) => (+ <svg {...svgProps(className)} stroke="none">+ {[+ [9, 4],+ [16, 6],+ [23, 3],+ ].flatMap(([cx, n], col) =>+ Array.from({ length: n }, (_, i) => (+ <circle key={`${col}-${i}`} cx={cx} cy={24 - i * 3.4} r="1.6" fill="currentColor" opacity={i === n - 1 ? 1 : 0.45} />+ ))+ )}+ <line x1="4" y1="27.5" x2="28" y2="27.5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" opacity="0.4" />+ </svg>+);++const PieIcon: React.FC<IconProps> = ({ className }) => (+ <svg {...svgProps(className)}>+ <circle cx="16" cy="16" r="10" />+ <path d="M16,16 L16,6 A10,10 0 0 1 25.4,19.4 Z" fill="currentColor" opacity="0.4" stroke="none" />+ <line x1="16" y1="16" x2="16" y2="6" />+ <line x1="16" y1="16" x2="25.4" y2="19.4" />+ </svg>+);++const BoxplotIcon: React.FC<IconProps> = ({ className }) => (+ <svg {...svgProps(className)}>+ <line x1="12.5" y1="5.5" x2="19.5" y2="5.5" />+ <line x1="16" y1="5.5" x2="16" y2="10" />+ <rect x="9.5" y="10" width="13" height="12" rx="1" />+ <line x1="9.5" y1="15.5" x2="22.5" y2="15.5" strokeWidth="2" />+ <line x1="16" y1="22" x2="16" y2="26.5" />+ <line x1="12.5" y1="26.5" x2="19.5" y2="26.5" />+ </svg>+);++const PoiMapIcon: React.FC<IconProps> = ({ className }) => (+ <svg {...svgProps(className)}>+ <path+ d="M6,20.5 C6.5,15 11,12.5 15.5,13.5 C20,14.5 26,12 26.5,16.5 C27,21 21.5,25.5 15,25 C10,24.6 5.6,24.5 6,20.5 Z"+ fill="currentColor"+ opacity="0.18"+ stroke="none"+ />+ <path d="M12,7 a3.2,3.2 0 1 1 0.01,0 Z M12,10.2 L12,15" fill="currentColor" fillOpacity="0.9" />+ <path d="M21.5,13.5 a2.4,2.4 0 1 1 0.01,0 Z M21.5,15.9 L21.5,19.3" fill="currentColor" fillOpacity="0.5" />+ </svg>+);++const ChoroplethMapIcon: React.FC<IconProps> = ({ className }) => (+ <svg {...svgProps(className)}>+ <path d="M6,19 C6,12 11,8 16,8.5 C22,9 27,12 26.5,17.5 C26,23 20,26 14.5,25 C9.5,24 6,23 6,19 Z" />+ <path d="M6,19 C6,12 11,8 16,8.5 L14.5,25 C9.5,24 6,23 6,19 Z" fill="currentColor" opacity="0.7" stroke="none" />+ <path d="M16,8.5 C22,9 27,12 26.5,17.5 L14.5,25 L16,8.5 Z" fill="currentColor" opacity="0.3" stroke="none" />+ </svg>+);++export const chartIcons: Record<IAutoVizChartType, React.FC<IconProps>> = {+ table: TableIcon,+ highlight_table: HighlightTableIcon,+ heatmap: HeatmapIcon,+ bar: BarIcon,+ stacked_bar: StackedBarIcon,+ grouped_bar: GroupedBarIcon,+ line: LineIcon,+ area: AreaIcon,+ histogram: HistogramIcon,+ scatter: ScatterIcon,+ circle_view: CircleViewIcon,+ pie: PieIcon,+ boxplot: BoxplotIcon,+ poi_map: PoiMapIcon,+ choropleth_map: ChoroplethMapIcon,+};++/** English fallbacks; overridden by the `autoviz.charts.*` i18n keys when present */+export const chartTypeLabels: Record<IAutoVizChartType, string> = {+ table: 'Text Table',+ highlight_table: 'Highlight Table',+ heatmap: 'Heat Map',+ bar: 'Bar Chart',+ stacked_bar: 'Stacked Bar',+ grouped_bar: 'Grouped Bar',+ line: 'Line Chart',+ area: 'Area Chart',+ histogram: 'Histogram',+ scatter: 'Scatter Plot',+ circle_view: 'Circle View',+ pie: 'Pie Chart',+ boxplot: 'Box Plot',+ poi_map: 'Symbol Map',+ choropleth_map: 'Filled Map',+};diff --git a/packages/graphic-walker/src/components/autoViz/index.tsx b/packages/graphic-walker/src/components/autoViz/index.tsxnew file mode 100644index 00000000..df44bd03--- /dev/null+++ b/packages/graphic-walker/src/components/autoViz/index.tsx@@ -0,0 +1,238 @@+import React, { useMemo } from 'react';+import { observer } from 'mobx-react-lite';+import { toJS } from 'mobx';+import { Trans, useTranslation } from 'react-i18next';+import { SparklesIcon } from '@heroicons/react/24/solid';+import { ChevronDoubleRightIcon, CursorArrowRaysIcon, XMarkIcon } from '@heroicons/react/24/outline';+import { useVizStore } from '../../store';+import { IChart } from '../../interfaces';+import { COUNT_FIELD_ID, MEA_KEY_ID, MEA_VAL_ID } from '../../constants';+import { cn } from '../../utils';+import { recommend, IAutoVizDisableReason, IAutoVizItem } from '../../lib/autoViz';+import { Button } from '../ui/button';+import Tooltip from '../tooltip';+import { chartIcons, chartTypeLabels } from './chartIcons';++/** English fallbacks; overridden by the `autoviz.reason.*` i18n keys when present */+const reasonLabels: Record<IAutoVizDisableReason, string> = {+ need_fields: 'Select at least one field',+ need_dimension: 'Needs at least 1 dimension',+ need_two_dimensions: 'Needs at least 2 dimensions',+ too_many_dimensions: 'Too many dimensions for this chart',+ need_measure: 'Needs at least 1 measure',+ need_two_measures: 'Needs at least 2 measures',+ need_single_measure: 'Needs exactly 1 measure',+ too_many_measures: 'Too many measures for this chart',+ need_temporal: 'Needs a date/time dimension',+ need_temporal_or_ordinal: 'Needs a date/time or ordinal dimension',+ need_raw_measure: 'Needs a raw measure, not row count',+ need_lon_lat: 'Needs longitude & latitude fields',+ need_geo_feature: 'Needs a configured GeoJSON boundary',+};++const VIRTUAL_FIDS = [MEA_KEY_ID, MEA_VAL_ID];++const IS_MAC = typeof navigator !== 'undefined' && /Mac|iPhone|iPad/.test(navigator.platform);++/** keycap-styled modifier key; the visual anchor of the field-selection hint */+const ModKey: React.FC = () => (+ <kbd className="mx-0.5 inline-flex items-center rounded border bg-muted px-1 font-mono text-[10px] leading-4 text-foreground">+ {IS_MAC ? '⌘' : 'Ctrl'}+ </kbd>+);++/**+ * Tableau "Show Me"-style dock: a collapsible card on the right edge of the vis workspace.+ * Expanded state lives in the store (`showAutoVizPanel`) so the toolbar toggle stays in sync.+ *+ * Recommendation input cascades through three tiers:+ * 1. fields highlighted in the field list (ctrl/cmd+click) — merged with the view fields;+ * 2. no highlight → the fields already encoded in the current chart;+ * 3. empty chart too → cold start: every chart type reverse-matches usable fields+ * from the dataset, so clicking any lit type starts a chart from scratch.+ */+const AutoVizPanel: React.FC = observer(function AutoVizPanel() {+ const vizStore = useVizStore();+ const { t } = useTranslation();+ const expanded = vizStore.showAutoVizPanel;+ const selectedIds = vizStore.selectedFieldIds;++ const allFields = useMemo(+ () => vizStore.dimensions.concat(vizStore.measures).filter((f) => !VIRTUAL_FIDS.includes(f.fid)),+ [vizStore.dimensions, vizStore.measures]+ );++ // tier 1 ∪ tier 2: view fields (count excluded — the chart encodes it implicitly)+ // merged with explicitly highlighted fields+ const inputFields = useMemo(() => {+ const viewFields = vizStore.viewDimensions+ .concat(vizStore.viewMeasures)+ .filter((f) => !VIRTUAL_FIDS.includes(f.fid) && f.fid !== COUNT_FIELD_ID);+ const fids = new Set(viewFields.map((f) => f.fid));+ const picked = allFields.filter((f) => selectedIds.includes(f.fid) && !fids.has(f.fid));+ return viewFields.concat(picked);+ }, [vizStore.viewDimensions, vizStore.viewMeasures, allFields, selectedIds]);++ const mode: 'selection' | 'view' | 'cold' = selectedIds.length > 0 ? 'selection' : inputFields.length > 0 ? 'view' : 'cold';++ const result = useMemo(() => {+ if (!expanded) {+ return null;+ }+ const base = toJS(vizStore.currentVis) as IChart;+ const geoFeatureReady = Boolean(vizStore.layout.geojson || vizStore.layout.geoUrl);+ return recommend({+ fields: inputFields.map((f) => toJS(f)),+ base,+ allFields: allFields.map((f) => toJS(f)),+ geoFeatureReady,+ });+ }, [expanded, inputFields, allFields, vizStore.currentVis, vizStore.layout.geojson, vizStore.layout.geoUrl]);++ const apply = (item: IAutoVizItem | null) => {+ if (!item?.available || !item.chart) {+ return;+ }+ vizStore.applyChart(item.chart);+ };++ if (!expanded) {+ return (+ <div className="hidden sm:flex my-0.5 ml-0.5 flex-shrink-0">+ <button+ type="button"+ title={t('autoviz.expand', 'Show Auto Viz')}+ onClick={() => vizStore.setShowAutoVizPanel(true)}+ className="flex h-full w-7 flex-col items-center gap-2 rounded-md border bg-background py-2 text-muted-foreground transition-colors hover:border-primary/50 hover:text-primary"+ >+ <SparklesIcon className="h-4 w-4" />+ <span className="text-[10px] font-medium tracking-wide [writing-mode:vertical-rl]">{t('autoviz.title', 'Auto Viz')}</span>+ </button>+ </div>+ );+ }++ const availableCount = result?.items.filter((x) => x.available).length ?? 0;++ return (+ <div className="hidden sm:flex my-0.5 ml-0.5 w-[248px] flex-shrink-0 flex-col overflow-hidden rounded-md border bg-background">+ {/* header */}+ <div className="flex flex-shrink-0 items-center gap-1.5 border-b px-2.5 py-2">+ <SparklesIcon className="h-4 w-4 text-primary" />+ <span className="flex-1 truncate text-xs font-medium">{t('autoviz.title', 'Auto Viz')}</span>+ <button+ type="button"+ title={t('autoviz.collapse', 'Collapse panel')}+ onClick={() => vizStore.setShowAutoVizPanel(false)}+ className="rounded p-0.5 text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"+ >+ <ChevronDoubleRightIcon className="h-3.5 w-3.5" />+ </button>+ </div>+ {/* chart palette */}+ <div className="grid flex-1 auto-rows-min grid-cols-3 gap-1.5 overflow-y-auto p-2">+ {(result?.items ?? []).map((item) => {+ const Icon = chartIcons[item.chartType];+ const label = t(`autoviz.charts.${item.chartType}`, chartTypeLabels[item.chartType]);+ const tooltip = !item.available+ ? t(`autoviz.reason.${item.reason}`, reasonLabels[item.reason!])+ : item.matchedFields?.length+ ? t('autoviz.uses', 'Uses: {{fields}}', { fields: item.matchedFields.map((f) => f.name ?? f.fid).join(', ') })+ : item.isDefault+ ? t('autoviz.recommended', 'Recommended')+ : label;+ const card = (+ <div+ role="button"+ aria-disabled={!item.available}+ onClick={() => apply(item)}+ className={cn(+ 'relative flex flex-col items-center gap-1 rounded-lg border p-1.5 transition-all',+ item.available+ ? 'cursor-pointer text-foreground hover:border-primary hover:bg-primary/5 hover:shadow-sm'+ : 'cursor-not-allowed border-transparent text-muted-foreground opacity-35',+ item.isDefault && 'border-primary bg-primary/5 shadow-sm'+ )}+ >+ {item.isDefault && (+ <span className="absolute -right-1 -top-1 rounded-full bg-background">+ <SparklesIcon className="h-3.5 w-3.5 text-primary" />+ </span>+ )}+ <Icon className="h-7 w-7" />+ <span className="w-full truncate text-center text-[10px] leading-tight">{label}</span>+ </div>+ );+ return (+ <Tooltip key={item.chartType} content={tooltip}>+ {card}+ </Tooltip>+ );+ })}+ </div>+ {/* footer */}+ <div className="flex flex-shrink-0 flex-col gap-1.5 border-t px-2.5 py-2">+ {mode === 'selection' && (+ <>+ <div className="flex items-center justify-between gap-1 text-[11px] text-muted-foreground">+ <span className="truncate">+ {t('autoviz.selected_count', '{{count}} fields selected in the field list', { count: selectedIds.length })}+ </span>+ <button+ type="button"+ onClick={() => vizStore.clearFieldSelection()}+ className="flex flex-shrink-0 items-center gap-0.5 rounded px-1 py-0.5 transition-colors hover:bg-accent hover:text-foreground"+ >+ <XMarkIcon className="h-3 w-3" />+ {t('autoviz.clear', 'Clear')}+ </button>+ </div>+ <span className="text-[11px] leading-snug text-muted-foreground">+ {t('autoviz.hint', '{{count}} chart types match your selection', { count: availableCount })}+ </span>+ </>+ )}+ {mode === 'cold' && (+ <>+ {/* the one thing worth reading: how to select fields — keycap as the visual anchor */}+ <span className="flex items-start gap-1 text-[11px] leading-5 text-foreground/90">+ <CursorArrowRaysIcon className="mt-0.5 h-3.5 w-3.5 flex-shrink-0 text-primary" />+ <span>+ <Trans+ t={t}+ i18nKey="autoviz.select_hint"+ components={{ k: <ModKey /> }}+ defaults="Pick fields on the left · <k></k>+click to multi-select"+ />+ </span>+ </span>+ <span className="text-[10px] leading-snug text-muted-foreground/70">+ {t('autoviz.empty', '…or click any lit chart type to start')}+ </span>+ </>+ )}+ {mode === 'view' && (+ <>+ <span className="text-[11px] leading-snug text-muted-foreground">+ {t('autoviz.based_on_view', 'Based on the fields in the current chart · {{count}} types match', { count: availableCount })}+ </span>+ <span className="text-[10px] leading-5 text-muted-foreground/70">+ <Trans+ t={t}+ i18nKey="autoviz.refine_hint"+ components={{ k: <ModKey /> }}+ defaults="Click or <k></k>+click fields on the left to refine"+ />+ </span>+ </>+ )}+ <Button size="sm" className="h-7 w-full text-xs" disabled={!result?.defaultItem} onClick={() => apply(result?.defaultItem ?? null)}>+ <SparklesIcon className="mr-1.5 h-3.5 w-3.5" />+ {t('autoviz.apply_best', 'Apply recommended')}+ </Button>+ </div>+ </div>+ );+});++export default AutoVizPanel;diff --git a/packages/graphic-walker/src/fields/datasetFields/dimFields.tsx b/packages/graphic-walker/src/fields/datasetFields/dimFields.tsxindex d49b1876..5b6b93ec 100644--- a/packages/graphic-walker/src/fields/datasetFields/dimFields.tsx+++ b/packages/graphic-walker/src/fields/datasetFields/dimFields.tsx@@ -12,19 +12,29 @@ import { getFieldIdentifier } from '@/utils';const DimFields: React.FC = (props) => {const vizStore = useVizStore();- const { dimensions } = vizStore;+ // read in the observer render scope: the render prop below runs outside mobx tracking+ const { dimensions, selectedFieldIds } = vizStore;const menuActions = useMenuActions('dimensions');return (<div className="relative touch-none">{dimensions.map((f, index) => (<Draggable key={getFieldIdentifier(f)} draggableId={`dimension_${getFieldIdentifier(f)}`} index={index}>{(provided, snapshot) => {+ const selected = selectedFieldIds.includes(f.fid);return (<ActionMenu title={f.name || f.fid} menu={menuActions[index]} enableContextMenu={false} disabled={snapshot.isDragging}><FieldPill- className={`touch-none flex pt-0.5 pb-0.5 pl-2 pr-2 mx-0 m-1 text-xs hover:bg-dimension/20 transition-colors rounded-md truncate border border-transparent ${- snapshot.isDragging ? 'bg-dimension/20' : ''- }`}+ data-field-pill+ onClick={(e) => {+ if (e.metaKey || e.ctrlKey) {+ vizStore.toggleFieldSelection(f.fid);+ } else {+ vizStore.selectField(f.fid);+ }+ }}+ className={`touch-none flex pt-0.5 pb-0.5 pl-2 pr-2 mx-0 m-1 text-xs hover:bg-dimension/20 transition-colors rounded-md truncate border ${+ selected ? 'border-primary/50 bg-primary/10' : 'border-transparent'+ } ${snapshot.isDragging ? 'bg-dimension/20' : ''}`}ref={refMapper(provided.innerRef)}isDragging={snapshot.isDragging}{...provided.draggableProps}diff --git a/packages/graphic-walker/src/fields/datasetFields/index.tsx b/packages/graphic-walker/src/fields/datasetFields/index.tsxindex 6645c97a..94cdef45 100644--- a/packages/graphic-walker/src/fields/datasetFields/index.tsx+++ b/packages/graphic-walker/src/fields/datasetFields/index.tsx@@ -1,15 +1,36 @@-import React from 'react';+import React, { useEffect } from 'react';import { Droppable } from '@kanaries/react-beautiful-dnd';import { useTranslation } from 'react-i18next';import DimFields from './dimFields';import MeaFields from './meaFields';import { refMapper } from '../fieldsContext';+import { useVizStore } from '../../store';const DatasetFields: React.FC = (props) => {const { t } = useTranslation('translation', { keyPrefix: 'main.tabpanel.DatasetFields' });+ const vizStore = useVizStore();++ useEffect(() => {+ const onKeyDown = (e: KeyboardEvent) => {+ if (e.key === 'Escape') {+ vizStore.clearFieldSelection();+ }+ };+ document.addEventListener('keydown', onKeyDown);+ return () => document.removeEventListener('keydown', onKeyDown);+ }, [vizStore]);return (- <div className="p-1 sm:mr-0.5 my-0.5 border flex sm:flex-col sm:h-full" style={{ paddingBlock: 0, paddingInline: '0.6em' }}>+ <div+ className="p-1 sm:mr-0.5 my-0.5 border flex sm:flex-col sm:h-full"+ style={{ paddingBlock: 0, paddingInline: '0.6em' }}+ onClick={(e) => {+ // clicking blank space (not a field pill) drops the selection+ if (!(e.target as HTMLElement).closest('[data-field-pill]')) {+ vizStore.clearFieldSelection();+ }+ }}+ ><h4 className="text-xs mb-2 flex-grow-0 cursor-default select-none mt-2">{t('field_list')}</h4><Droppable droppableId="dimensions" direction="vertical">{(provided, snapshot) => (diff --git a/packages/graphic-walker/src/fields/datasetFields/meaFields.tsx b/packages/graphic-walker/src/fields/datasetFields/meaFields.tsxindex 09aefce6..de9a6d04 100644--- a/packages/graphic-walker/src/fields/datasetFields/meaFields.tsx+++ b/packages/graphic-walker/src/fields/datasetFields/meaFields.tsx@@ -7,13 +7,14 @@ import DataTypeIcon from '../../components/dataTypeIcon';import ActionMenu from '../../components/actionMenu';import { useMenuActions } from './utils';import { FieldPill } from './fieldPill';-import { MEA_KEY_ID } from '../../constants';+import { MEA_KEY_ID, MEA_VAL_ID } from '../../constants';import { refMapper } from '../fieldsContext';import { getFieldIdentifier } from '@/utils';const MeaFields: React.FC = (props) => {const vizStore = useVizStore();- const { measures } = vizStore;+ // read in the observer render scope: the render prop below runs outside mobx tracking+ const { measures, selectedFieldIds } = vizStore;const menuActions = useMenuActions('measures');@@ -22,6 +23,8 @@ const MeaFields: React.FC = (props) => {{measures.map((f, index) => (<Draggable key={getFieldIdentifier(f)} draggableId={`measure_${getFieldIdentifier(f)}`} index={index}>{(provided, snapshot) => {+ const selectable = f.fid !== MEA_KEY_ID && f.fid !== MEA_VAL_ID;+ const selected = selectable && selectedFieldIds.includes(f.fid);return (<div className="block"><ActionMenu@@ -31,9 +34,20 @@ const MeaFields: React.FC = (props) => {disabled={snapshot.isDragging || f.fid === MEA_KEY_ID}><FieldPill- className={`touch-none flex pt-0.5 pb-0.5 pl-2 pr-2 mx-0 m-1 text-xs hover:bg-measure/20 rounded-md truncate border border-transparent ${- snapshot.isDragging ? 'bg-measure/20' : ''- }`}+ data-field-pill+ onClick={(e) => {+ if (!selectable) {+ return;+ }+ if (e.metaKey || e.ctrlKey) {+ vizStore.toggleFieldSelection(f.fid);+ } else {+ vizStore.selectField(f.fid);+ }+ }}+ className={`touch-none flex pt-0.5 pb-0.5 pl-2 pr-2 mx-0 m-1 text-xs hover:bg-measure/20 rounded-md truncate border ${+ selected ? 'border-primary/50 bg-primary/10' : 'border-transparent'+ } ${snapshot.isDragging ? 'bg-measure/20' : ''}`}isDragging={snapshot.isDragging}ref={refMapper(provided.innerRef)}{...provided.draggableProps}diff --git a/packages/graphic-walker/src/index.tsx b/packages/graphic-walker/src/index.tsxindex addcafe6..0f6053b5 100644--- a/packages/graphic-walker/src/index.tsx+++ b/packages/graphic-walker/src/index.tsx@@ -13,3 +13,5 @@ export { getComputation } from './computation/clientComputation';export { addFilterForQuery, chartToWorkflow } from './utils/workflow';export * from './utils/colors';export * from './components/filterContext';+export { recommend, extractFeatures, AUTO_VIZ_CHART_ORDER, AUTO_VIZ_RULES } from './lib/autoViz';+export type { IAutoVizChartType, IAutoVizItem, IAutoVizResult, IRecommendOptions, IAutoVizDisableReason } from './lib/autoViz';diff --git a/packages/graphic-walker/src/lib/autoViz/autoViz.test.ts b/packages/graphic-walker/src/lib/autoViz/autoViz.test.tsnew file mode 100644index 00000000..22396229--- /dev/null+++ b/packages/graphic-walker/src/lib/autoViz/autoViz.test.ts@@ -0,0 +1,374 @@+import { DraggableFieldState, IChart, ISemanticType, IViewField } from '../../interfaces';+import { GLOBAL_CONFIG } from '../../config';+import { COUNT_FIELD_ID } from '../../constants';+import { viewEncodingKeys } from '../../models/visSpec';+import { recommend, IAutoVizItem, IAutoVizChartType } from './index';++const dim = (fid: string, semanticType: ISemanticType = 'nominal', extra: Partial<IViewField> = {}): IViewField => ({+ fid,+ name: fid,+ analyticType: 'dimension',+ semanticType,+ ...extra,+});++const mea = (fid: string, extra: Partial<IViewField> = {}): IViewField => ({+ fid,+ name: fid,+ analyticType: 'measure',+ semanticType: 'quantitative',+ aggName: 'sum',+ ...extra,+});++const category = dim('category');+const subcategory = dim('subcategory');+const level = dim('level', 'ordinal');+const orderDate = dim('orderDate', 'temporal');+const sales = mea('sales');+const profit = mea('profit');+const discount = mea('discount');+const quantity = mea('quantity');+const tax = mea('tax');+const lon = mea('lon', { geoRole: 'longitude' });+const lat = mea('lat', { geoRole: 'latitude' });+const countMea = mea(COUNT_FIELD_ID, { computed: true, expression: { op: 'one', params: [], as: COUNT_FIELD_ID } });++const ALL_FIELDS = [category, subcategory, level, orderDate, sales, profit, discount, quantity, tax, lon, lat, countMea];++const VIEW_CHANNEL_KEYS: Exclude<keyof DraggableFieldState, 'dimensions' | 'measures' | 'filters'>[] = [+ 'rows',+ 'columns',+ 'color',+ 'opacity',+ 'size',+ 'shape',+ 'radius',+ 'theta',+ 'longitude',+ 'latitude',+ 'geoId',+ 'details',+ 'text',+];++const item = (result: ReturnType<typeof recommend>, chartType: IAutoVizChartType): IAutoVizItem =>+ result.items.find((x) => x.chartType === chartType)!;++const viewFids = (chart: IChart): Set<string> => {+ const fids = new Set<string>();+ for (const key of VIEW_CHANNEL_KEYS) {+ for (const f of chart.encodings[key]) {+ fids.add(f.fid);+ // a computed field (e.g. bin) also encodes the fields it derives from+ f.expression?.params.forEach((p) => {+ if (p.type === 'field') fids.add(p.value);+ });+ }+ }+ return fids;+};++describe('expressiveness filter', () => {+ test('pure dimensions: only table-family charts remain, table is default', () => {+ const result = recommend({ fields: [category, subcategory], allFields: ALL_FIELDS });+ expect(result.defaultItem?.chartType).toBe('table');+ expect(item(result, 'bar').available).toBe(false);+ expect(item(result, 'bar').reason).toBe('need_measure');+ expect(item(result, 'scatter').available).toBe(false);+ expect(item(result, 'scatter').reason).toBe('need_two_measures');+ expect(item(result, 'heatmap').available).toBe(true);+ });++ test('no temporal or ordinal dimension disables line and area', () => {+ const result = recommend({ fields: [category, sales], allFields: ALL_FIELDS });+ expect(item(result, 'line').available).toBe(false);+ expect(item(result, 'line').reason).toBe('need_temporal_or_ordinal');+ expect(item(result, 'area').available).toBe(false);+ expect(item(result, 'area').reason).toBe('need_temporal');+ });++ test('ordinal dimension enables line but not area', () => {+ const result = recommend({ fields: [level, sales], allFields: ALL_FIELDS });+ expect(item(result, 'line').available).toBe(true);+ expect(item(result, 'area').available).toBe(false);+ });++ test('scatter needs 2–4 measures', () => {+ const one = recommend({ fields: [sales], allFields: ALL_FIELDS });+ expect(item(one, 'scatter').reason).toBe('need_two_measures');+ const five = recommend({ fields: [sales, profit, discount, quantity, tax], allFields: ALL_FIELDS });+ expect(item(five, 'scatter').reason).toBe('too_many_measures');+ });++ test('histogram rejects dimensions, extra measures and the row-count field', () => {+ expect(item(recommend({ fields: [category, sales], allFields: ALL_FIELDS }), 'histogram').reason).toBe('too_many_dimensions');+ expect(item(recommend({ fields: [sales, profit], allFields: ALL_FIELDS }), 'histogram').reason).toBe('need_single_measure');+ expect(item(recommend({ fields: [countMea], allFields: ALL_FIELDS }), 'histogram').reason).toBe('need_raw_measure');+ });++ test('maps are gated by geo fields and geo feature', () => {+ const noGeo = recommend({ fields: [category, sales], allFields: ALL_FIELDS });+ expect(item(noGeo, 'poi_map').reason).toBe('need_lon_lat');+ expect(item(noGeo, 'choropleth_map').reason).toBe('need_geo_feature');+ const withFeature = recommend({ fields: [category, sales], allFields: ALL_FIELDS, geoFeatureReady: true });+ expect(item(withFeature, 'choropleth_map').available).toBe(true);+ });++ test('empty selection without allFields disables everything', () => {+ const result = recommend({ fields: [] });+ expect(result.defaultItem).toBeNull();+ expect(result.items.every((x) => !x.available && x.reason === 'need_fields')).toBe(true);+ });+});++describe('effectiveness ranking (default chart)', () => {+ const cases: [string, IViewField[], IAutoVizChartType][] = [+ ['category + measure → bar', [category, sales], 'bar'],+ ['temporal + measure → line', [orderDate, sales], 'line'],+ ['two measures → scatter', [sales, profit], 'scatter'],+ ['single raw measure → histogram', [sales], 'histogram'],+ ['pure dimensions → table', [category, subcategory], 'table'],+ ['lon/lat pair → poi map', [lon, lat], 'poi_map'],+ ['lon/lat + measure → poi map', [lon, lat, sales], 'poi_map'],+ ];+ test.each(cases)('%s', (_name, fields, expected) => {+ const result = recommend({ fields, allFields: ALL_FIELDS });+ expect(result.defaultItem?.chartType).toBe(expected);+ });+});++describe('spec validity of every available recommendation', () => {+ const selections: IViewField[][] = [+ [category, sales],+ [category, subcategory, sales],+ [category, subcategory, level, sales, profit],+ [orderDate, sales],+ [orderDate, category, sales, profit],+ [sales, profit],+ [sales, profit, discount, quantity],+ [sales],+ [category],+ [category, subcategory],+ [lon, lat, sales, category],+ ];++ test.each(selections.map((s): [string, IViewField[]] => [s.map((f) => f.fid).join(','), s]))(+ 'selection [%s]',+ (_name, fields) => {+ const result = recommend({ fields, allFields: ALL_FIELDS, geoFeatureReady: true });+ const available = result.items.filter((x) => x.available);+ expect(available.length).toBeGreaterThan(0);+ for (const rec of available) {+ const chart = rec.chart!;+ const geom = chart.config.geoms[0];+ const legalKeys = new Set<string>(viewEncodingKeys(geom));+ const encoded = viewFids(chart);++ // expressiveness: every selected field is encoded, nothing is dropped+ for (const f of fields) {+ expect(encoded).toContain(f.fid);+ }+ // channels stay within what the geom supports and per-channel limits+ for (const key of VIEW_CHANNEL_KEYS) {+ const bucket = chart.encodings[key];+ if (bucket.length > 0) {+ expect(legalKeys).toContain(key);+ }+ const limit = GLOBAL_CONFIG.CHANNEL_LIMIT[key as keyof typeof GLOBAL_CONFIG.CHANNEL_LIMIT];+ if (limit !== undefined && limit !== Infinity) {+ expect(bucket.length).toBeLessThanOrEqual(limit);+ }+ }+ // field shelves are fully inherited: applying never loses dataset fields+ const shelfFids = new Set(chart.encodings.dimensions.concat(chart.encodings.measures).map((x) => x.fid));+ for (const f of ALL_FIELDS) {+ expect(shelfFids).toContain(f.fid);+ }+ // aggregated views only put aggregator-carrying measures on shelves+ if (chart.config.defaultAggregated) {+ for (const key of VIEW_CHANNEL_KEYS) {+ for (const f of chart.encodings[key]) {+ if (f.analyticType === 'measure') {+ expect(f.aggName).toBeTruthy();+ }+ }+ }+ }+ }+ }+ );+});++describe('base chart inheritance', () => {+ const base: IChart = {+ visId: 'vis-1',+ name: 'My Chart',+ encodings: {+ dimensions: [category, subcategory, level, orderDate].map((x) => ({ ...x })),+ measures: [sales, profit, countMea].map((x) => ({ ...x })),+ filters: [{ ...category, rule: { type: 'one of', value: ['A'] } }],+ rows: [{ ...sales }],+ columns: [{ ...category }],+ color: [],+ opacity: [],+ size: [],+ shape: [],+ radius: [],+ theta: [],+ longitude: [],+ latitude: [],+ geoId: [],+ details: [],+ text: [],+ },+ config: { defaultAggregated: true, geoms: ['bar'], coordSystem: 'generic', limit: -1, timezoneDisplayOffset: 480 },+ layout: {+ showTableSummary: false,+ format: { numberFormat: ',.2f' },+ primaryColor: '#123456',+ resolve: {},+ size: { mode: 'auto', width: 320, height: 200 },+ interactiveScale: false,+ stack: 'stack',+ showActions: false,+ zeroScale: true,+ },+ };++ test('keeps identity, filters, config extras and layout preferences', () => {+ const result = recommend({ fields: [orderDate, sales], base });+ const line = item(result, 'line');+ expect(line.isDefault).toBe(true);+ const chart = line.chart!;+ expect(chart.visId).toBe('vis-1');+ expect(chart.name).toBe('My Chart');+ expect(chart.encodings.filters).toHaveLength(1);+ expect(chart.config.timezoneDisplayOffset).toBe(480);+ expect(chart.layout.primaryColor).toBe('#123456');+ expect(chart.layout.format.numberFormat).toBe(',.2f');+ // view channels are rebuilt, not merged with the previous chart+ expect(chart.encodings.columns.map((x) => x.fid)).toEqual([orderDate.fid]);+ expect(chart.encodings.rows.map((x) => x.fid)).toEqual([sales.fid]);+ });++ test('histogram reuses the existing row-count field and registers its bin field on the shelf', () => {+ const result = recommend({ fields: [sales], base });+ const hist = item(result, 'histogram');+ const chart = hist.chart!;+ const binField = chart.encodings.columns[0];+ expect(binField.expression?.op).toBe('bin');+ expect(binField.expression?.params[0].value).toBe(sales.fid);+ // bin field is registered on the dimension shelf+ expect(chart.encodings.dimensions.some((x) => x.fid === binField.fid)).toBe(true);+ // row count is reused, not duplicated+ expect(chart.encodings.rows[0].fid).toBe(COUNT_FIELD_ID);+ expect(chart.encodings.measures.filter((x) => x.fid === COUNT_FIELD_ID)).toHaveLength(1);+ });++ test('built charts share no field object references with the base chart', () => {+ const result = recommend({ fields: [category, sales], base });+ for (const rec of result.items.filter((x) => x.available)) {+ const chart = rec.chart!;+ for (const key of ['dimensions', 'measures', ...VIEW_CHANNEL_KEYS] as const) {+ for (const f of chart.encodings[key]) {+ for (const baseField of base.encodings.dimensions.concat(base.encodings.measures)) {+ expect(f).not.toBe(baseField);+ }+ }+ }+ }+ });+});++describe('cold-start reverse matching (empty selection + allFields)', () => {+ const coldStart = (allFields = ALL_FIELDS, geoFeatureReady = false) => recommend({ fields: [], allFields, geoFeatureReady });++ test('every chart type except choropleth is available on a rich dataset', () => {+ const result = coldStart();+ for (const it of result.items) {+ if (it.chartType === 'choropleth_map') {+ expect(it.available).toBe(false);+ expect(it.reason).toBe('need_geo_feature');+ } else {+ expect(it.available).toBe(true);+ }+ }+ });++ test('choropleth becomes available once a geo feature is configured', () => {+ expect(item(coldStart(ALL_FIELDS, true), 'choropleth_map').available).toBe(true);+ });++ test('matched combinations are minimal and requirement-driven', () => {+ const result = coldStart();+ const matched = (t: Parameters<typeof item>[1]) => item(result, t).matchedFields!.map((f) => f.fid);+ // line prefers the temporal dimension over list order+ expect(matched('line')).toEqual([orderDate.fid, sales.fid]);+ expect(matched('area')).toEqual([orderDate.fid, sales.fid]);+ // histogram picks the first raw measure, never the count field+ expect(matched('histogram')).toEqual([sales.fid]);+ // scatter fills two generic measures, excluding the lon/lat pair+ expect(matched('scatter')).toEqual([sales.fid, profit.fid]);+ // poi map picks exactly the lon/lat pair+ expect(matched('poi_map').sort()).toEqual([lat.fid, lon.fid].sort());+ // heatmap needs two dimensions, filled in field-list order+ expect(matched('heatmap')).toEqual([category.fid, subcategory.fid]);+ // table stays pure-dimension so its score reflects the recommendation intent+ expect(matched('table')).toEqual([category.fid]);+ });++ test('every available item encodes exactly its matched fields', () => {+ const result = coldStart(ALL_FIELDS, true);+ for (const it of result.items.filter((x) => x.available)) {+ const encoded = viewFids(it.chart!);+ for (const f of it.matchedFields!) {+ expect(encoded).toContain(f.fid);+ }+ // nothing beyond matched fields + derived helpers (count / bin)+ const matchedFids = new Set(it.matchedFields!.map((f) => f.fid));+ const extras = [...encoded].filter((fid) => !matchedFids.has(fid) && fid !== COUNT_FIELD_ID && !fid.startsWith('gw_'));+ expect(extras).toEqual([]);+ }+ });++ test('missing special types surface the blocking reason', () => {+ const noTemporal = [category, subcategory, sales, profit, countMea];+ const result = coldStart(noTemporal);+ expect(item(result, 'line').reason).toBe('need_temporal_or_ordinal');+ expect(item(result, 'area').reason).toBe('need_temporal');+ expect(item(result, 'poi_map').reason).toBe('need_lon_lat');+ // the rest still work+ expect(item(result, 'bar').available).toBe(true);+ expect(item(result, 'scatter').available).toBe(true);+ });++ test('ordinal dimension unlocks line but not area', () => {+ const result = coldStart([level, sales, countMea]);+ expect(item(result, 'line').available).toBe(true);+ expect(item(result, 'line').matchedFields![0].fid).toBe(level.fid);+ expect(item(result, 'area').reason).toBe('need_temporal');+ });++ test('count-only dataset: histogram is rejected, bar falls back to count', () => {+ const result = coldStart([category, countMea]);+ expect(item(result, 'histogram').reason).toBe('need_raw_measure');+ const bar = item(result, 'bar');+ expect(bar.available).toBe(true);+ expect(bar.matchedFields!.map((f) => f.fid)).toEqual([category.fid, COUNT_FIELD_ID]);+ expect(item(result, 'scatter').reason).toBe('need_two_measures');+ });++ test('cold-start default is the poi map when a lon/lat pair exists, scatter otherwise', () => {+ expect(coldStart().defaultItem!.chartType).toBe('poi_map');+ const noGeo = [category, subcategory, level, orderDate, sales, profit, countMea];+ expect(coldStart(noGeo).defaultItem!.chartType).toBe('scatter');+ });++ test('non-empty selection never enters cold-start mode', () => {+ const result = recommend({ fields: [category, sales], allFields: ALL_FIELDS });+ expect(item(result, 'bar').matchedFields).toBeUndefined();+ // line is greyed because the selection has no temporal dim, even though the dataset has one+ expect(item(result, 'line').available).toBe(false);+ });+});diff --git a/packages/graphic-walker/src/lib/autoViz/builders.ts b/packages/graphic-walker/src/lib/autoViz/builders.tsnew file mode 100644index 00000000..327127f6--- /dev/null+++ b/packages/graphic-walker/src/lib/autoViz/builders.ts@@ -0,0 +1,342 @@+import { DraggableFieldState, IChart, IStackMode, IViewField } from '../../interfaces';+import { COUNT_FIELD_ID } from '../../constants';+import { IFieldFeatures, IAutoVizChartType } from './types';++/** local id generator; nanoid (ESM-only) is deliberately avoided to keep this module jest-friendly */+export const autoVizId = (): string => `gw_${Math.random().toString(36).slice(2, 8)}`;++type IViewChannels = Partial<Omit<DraggableFieldState, 'dimensions' | 'measures' | 'filters'>>;++interface IBuildSpec {+ geom: string;+ coordSystem?: 'generic' | 'geographic';+ defaultAggregated: boolean;+ stack?: IStackMode;+ channels: IViewChannels;+ /** computed fields to append to the dimension shelf (e.g. bin field of a histogram) */+ extraDimensions?: IViewField[];+ /** computed fields to append to the measure shelf (e.g. row count) */+ extraMeasures?: IViewField[];+}++const cloneField = (f: IViewField): IViewField => ({ ...f });++/** measures entering an aggregated view must carry an aggregator */+const asMeasure = (f: IViewField): IViewField => ({ ...f, aggName: f.aggName ?? 'sum' });++/**+ * Reuse the row-count field of the base chart when present (newChart always adds one),+ * otherwise create it and report it as an extra shelf field.+ */+function countField(base: IChart): { field: IViewField; extra: IViewField[] } {+ const existed = base.encodings.measures.find((x) => x.fid === COUNT_FIELD_ID);+ if (existed) {+ return { field: cloneField(existed), extra: [] };+ }+ const created: IViewField = {+ fid: COUNT_FIELD_ID,+ name: 'Row count',+ analyticType: 'measure',+ semanticType: 'quantitative',+ aggName: 'sum',+ computed: true,+ expression: {+ op: 'one',+ params: [],+ as: COUNT_FIELD_ID,+ },+ };+ return { field: created, extra: [{ ...created }] };+}++/**+ * Assemble a complete IChart from the base chart and a build spec.+ * Field shelves (dimensions / measures) and filters are inherited so applying+ * a recommendation never loses dataset fields or active filters; all view+ * channels are rebuilt from scratch.+ */+function composeChart(base: IChart, spec: IBuildSpec): IChart {+ const encodings: DraggableFieldState = {+ dimensions: base.encodings.dimensions.map(cloneField).concat(spec.extraDimensions ?? []),+ measures: base.encodings.measures.map(cloneField).concat(spec.extraMeasures ?? []),+ filters: base.encodings.filters.map((f) => ({ ...f })),+ rows: [],+ columns: [],+ color: [],+ opacity: [],+ size: [],+ shape: [],+ radius: [],+ theta: [],+ longitude: [],+ latitude: [],+ geoId: [],+ details: [],+ text: [],+ ...spec.channels,+ };+ return {+ visId: base.visId,+ name: base.name,+ encodings,+ config: {+ ...base.config,+ defaultAggregated: spec.defaultAggregated,+ geoms: [spec.geom],+ coordSystem: spec.coordSystem ?? 'generic',+ },+ layout: {+ ...base.layout,+ size: { ...base.layout.size },+ format: { ...base.layout.format },+ resolve: { ...base.layout.resolve },+ stack: spec.stack ?? base.layout.stack,+ },+ };+}++/**+ * Channel assignment conventions (VizQL-ish):+ * - multiple fields on rows/columns nest outer→inner, the LAST one is the innermost axis;+ * - extra dimensions overflow to facet headers (small multiples) rather than+ * being crammed into a perception-weak channel;+ * - channels respect GLOBAL_CONFIG.CHANNEL_LIMIT (color/size/shape/... hold one field)+ * and viewEncodingKeys(geom).+ */+export const builders: Record<IAutoVizChartType, (f: IFieldFeatures, base: IChart) => IChart> = {+ table: (f, base) =>+ composeChart(base, {+ geom: 'table',+ defaultAggregated: true,+ channels: {+ columns: f.dimensions.map(cloneField),+ rows: f.measures.map(asMeasure),+ },+ }),++ highlight_table: (f, base) => {+ const dims = f.dimensions;+ const hasColumnDim = dims.length >= 2;+ const measure = f.measures[0];+ return composeChart(base, {+ geom: 'text',+ defaultAggregated: true,+ channels: {+ rows: dims.slice(0, hasColumnDim ? -1 : dims.length).map(cloneField),+ columns: hasColumnDim ? [cloneField(dims[dims.length - 1])] : [],+ text: [asMeasure(measure)],+ color: [asMeasure(measure)],+ },+ });+ },++ heatmap: (f, base) => {+ const [xDim, yDim, ...restDims] = f.dimensions;+ const count = f.measures.length === 0 ? countField(base) : null;+ return composeChart(base, {+ geom: 'rect',+ defaultAggregated: true,+ extraMeasures: count?.extra,+ channels: {+ columns: [cloneField(xDim)],+ rows: [cloneField(yDim)],+ details: restDims.map(cloneField),+ color: [count ? count.field : asMeasure(f.measures[0])],+ size: f.measures[1] ? [asMeasure(f.measures[1])] : [],+ },+ });+ },++ bar: (f, base) => {+ const [xDim, ...facetDims] = f.dimensions;+ return composeChart(base, {+ geom: 'bar',+ defaultAggregated: true,+ stack: 'stack',+ channels: {+ columns: [...facetDims.map(cloneField), cloneField(xDim)],+ rows: f.measures.map(asMeasure),+ },+ });+ },++ stacked_bar: (f, base) => {+ const [xDim, colorDim, ...facetDims] = f.dimensions;+ return composeChart(base, {+ geom: 'bar',+ defaultAggregated: true,+ stack: 'stack',+ channels: {+ columns: [...facetDims.map(cloneField), cloneField(xDim)],+ rows: f.measures.map(asMeasure),+ color: [cloneField(colorDim)],+ },+ });+ },++ grouped_bar: (f, base) => {+ const [xDim, groupDim, ...facetDims] = f.dimensions;+ return composeChart(base, {+ geom: 'bar',+ defaultAggregated: true,+ stack: 'none',+ channels: {+ // group dim nests inside the category dim → side-by-side bars+ columns: [...facetDims.map(cloneField), cloneField(xDim), cloneField(groupDim)],+ rows: f.measures.map(asMeasure),+ color: [cloneField(groupDim)],+ },+ });+ },++ line: (f, base) => {+ const axisDim = f.temporalDims[0] ?? f.ordinalDims[0];+ const [colorDim, ...facetDims] = f.dimensions.filter((d) => d !== axisDim);+ return composeChart(base, {+ geom: 'line',+ defaultAggregated: true,+ channels: {+ columns: [...facetDims.map(cloneField), cloneField(axisDim)],+ rows: f.measures.map(asMeasure),+ color: colorDim ? [cloneField(colorDim)] : [],+ },+ });+ },++ area: (f, base) => {+ const axisDim = f.temporalDims[0];+ const [colorDim, ...facetDims] = f.dimensions.filter((d) => d !== axisDim);+ return composeChart(base, {+ geom: 'area',+ defaultAggregated: true,+ stack: 'stack',+ channels: {+ columns: [...facetDims.map(cloneField), cloneField(axisDim)],+ rows: f.measures.map(asMeasure),+ color: colorDim ? [cloneField(colorDim)] : [],+ },+ });+ },++ histogram: (f, base) => {+ const measure = f.measures[0];+ const binFid = autoVizId();+ // same shape as the store's createBinField product, so the two dedupe naturally+ const binField: IViewField = {+ fid: binFid,+ name: `bin10(${measure.name})`,+ semanticType: 'ordinal',+ analyticType: 'dimension',+ computed: true,+ expression: {+ op: 'bin',+ as: binFid,+ params: [{ type: 'field', value: measure.fid }],+ num: 10,+ },+ };+ const count = countField(base);+ return composeChart(base, {+ geom: 'bar',+ defaultAggregated: true,+ stack: 'stack',+ extraDimensions: [{ ...binField }],+ extraMeasures: count.extra,+ channels: {+ columns: [binField],+ rows: [count.field],+ },+ });+ },++ scatter: (f, base) => {+ const [xMea, yMea, sizeMea, opacityMea] = f.measures;+ const [colorDim, ...restDims] = f.dimensions;+ return composeChart(base, {+ geom: 'point',+ defaultAggregated: false,+ channels: {+ columns: [cloneField(xMea)],+ rows: [cloneField(yMea)],+ size: sizeMea ? [cloneField(sizeMea)] : [],+ opacity: opacityMea ? [cloneField(opacityMea)] : [],+ color: colorDim ? [cloneField(colorDim)] : [],+ details: restDims.map(cloneField),+ },+ });+ },++ circle_view: (f, base) => {+ const [xDim, ...facetDims] = f.dimensions;+ return composeChart(base, {+ geom: 'circle',+ defaultAggregated: false,+ channels: {+ columns: [...facetDims.map(cloneField), cloneField(xDim)],+ rows: f.measures.map(cloneField),+ },+ });+ },++ pie: (f, base) => {+ const [colorDim, detailDim] = f.dimensions;+ const [angleMea, sizeMea] = f.measures;+ return composeChart(base, {+ geom: 'arc',+ defaultAggregated: true,+ stack: 'stack',+ channels: {+ theta: [asMeasure(angleMea)],+ color: [cloneField(colorDim)],+ size: sizeMea ? [asMeasure(sizeMea)] : [],+ details: detailDim ? [cloneField(detailDim)] : [],+ },+ });+ },++ boxplot: (f, base) => {+ const [xDim, ...facetDims] = f.dimensions;+ return composeChart(base, {+ geom: 'boxplot',+ defaultAggregated: false,+ channels: {+ columns: [...facetDims.map(cloneField), cloneField(xDim)],+ rows: f.measures.map(cloneField),+ },+ });+ },++ poi_map: (f, base) => {+ const [lon, lat] = f.lonLat!;+ const sizeMea = f.nonGeoMeasures[0];+ const [colorDim, ...restDims] = f.dimensions;+ return composeChart(base, {+ geom: 'poi',+ coordSystem: 'geographic',+ defaultAggregated: false,+ channels: {+ longitude: [cloneField(lon)],+ latitude: [cloneField(lat)],+ size: sizeMea ? [cloneField(sizeMea)] : [],+ color: colorDim ? [cloneField(colorDim)] : [],+ details: restDims.map(cloneField),+ },+ });+ },++ choropleth_map: (f, base) => {+ const [geoDim, ...restDims] = f.dimensions;+ const count = f.measures.length === 0 ? countField(base) : null;+ return composeChart(base, {+ geom: 'choropleth',+ coordSystem: 'geographic',+ defaultAggregated: true,+ extraMeasures: count?.extra,+ channels: {+ geoId: [cloneField(geoDim)],+ color: [count ? count.field : asMeasure(f.measures[0])],+ details: restDims.map(cloneField),+ },+ });+ },+};diff --git a/packages/graphic-walker/src/lib/autoViz/features.ts b/packages/graphic-walker/src/lib/autoViz/features.tsnew file mode 100644index 00000000..9f8add30--- /dev/null+++ b/packages/graphic-walker/src/lib/autoViz/features.ts@@ -0,0 +1,32 @@+import { IViewField } from '../../interfaces';+import { MEA_KEY_ID, MEA_VAL_ID } from '../../constants';+import { IFieldFeatures } from './types';++/**+ * Compute the statistical features of a field selection.+ * This is the "三特征" step of Auto Viz: dimension count, measure count and+ * special data types (temporal / ordinal / geographic).+ */+export function extractFeatures(fields: IViewField[], geoFeatureReady = false): IFieldFeatures {+ const selected = fields.filter((f) => f.fid !== MEA_KEY_ID && f.fid !== MEA_VAL_ID);+ const dimensions = selected.filter((f) => f.analyticType === 'dimension');+ const measures = selected.filter((f) => f.analyticType === 'measure');+ const temporalDims = dimensions.filter((f) => f.semanticType === 'temporal');+ const ordinalDims = dimensions.filter((f) => f.semanticType === 'ordinal');+ const lon = selected.find((f) => f.geoRole === 'longitude');+ const lat = selected.find((f) => f.geoRole === 'latitude');+ const lonLat: [IViewField, IViewField] | null = lon && lat ? [lon, lat] : null;+ const nonGeoMeasures = measures.filter((f) => f !== lon && f !== lat);+ return {+ fields: selected,+ dimensions,+ measures,+ nDim: dimensions.length,+ nMea: measures.length,+ temporalDims,+ ordinalDims,+ lonLat,+ nonGeoMeasures,+ geoFeatureReady,+ };+}diff --git a/packages/graphic-walker/src/lib/autoViz/index.ts b/packages/graphic-walker/src/lib/autoViz/index.tsnew file mode 100644index 00000000..1193dd47--- /dev/null+++ b/packages/graphic-walker/src/lib/autoViz/index.ts@@ -0,0 +1,145 @@+import { IChart, IViewField } from '../../interfaces';+import { MEA_KEY_ID, MEA_VAL_ID } from '../../constants';+import { initEncoding, emptyVisualConfig, emptyVisualLayout } from '../../utils/save';+import { autoVizId } from './builders';+import { extractFeatures } from './features';+import { AUTO_VIZ_RULES } from './rules';+import { synthesizeFields } from './synthesize';+import { IFieldFeatures, IRecommendOptions, IAutoVizDisableReason, IAutoVizItem, IAutoVizResult, IAutoVizRule } from './types';++export * from './types';+export { extractFeatures } from './features';+export { AUTO_VIZ_CHART_ORDER, AUTO_VIZ_RULES } from './rules';+export { builders } from './builders';+export { synthesizeFields } from './synthesize';++/** expressiveness filter: null means the rule is legal for the selection */+function checkExpressiveness(rule: IAutoVizRule, f: IFieldFeatures): IAutoVizDisableReason | null {+ if (f.fields.length === 0) {+ return 'need_fields';+ }+ if (f.nDim < rule.dim[0]) {+ return rule.dim[0] >= 2 ? 'need_two_dimensions' : 'need_dimension';+ }+ if (f.nDim > rule.dim[1]) {+ return 'too_many_dimensions';+ }+ if (f.nMea < rule.mea[0]) {+ return rule.mea[0] >= 2 ? 'need_two_measures' : 'need_measure';+ }+ if (f.nMea > rule.mea[1]) {+ return rule.mea[1] === 1 ? 'need_single_measure' : 'too_many_measures';+ }+ for (const req of rule.requires ?? []) {+ switch (req) {+ case 'temporal':+ if (f.temporalDims.length === 0) return 'need_temporal';+ break;+ case 'temporal_or_ordinal':+ if (f.temporalDims.length === 0 && f.ordinalDims.length === 0) return 'need_temporal_or_ordinal';+ break;+ case 'lon_lat':+ if (!f.lonLat) return 'need_lon_lat';+ break;+ case 'geo_feature':+ if (!f.geoFeatureReady) return 'need_geo_feature';+ break;+ }+ }+ return rule.check?.(f) ?? null;+}++/** minimal chart to inherit from when the caller has no current chart */+function scaffoldChart(allFields: IViewField[]): IChart {+ return {+ visId: autoVizId(),+ name: 'Chart',+ encodings: {+ ...initEncoding(),+ dimensions: allFields.filter((x) => x.analyticType === 'dimension').map((x) => ({ ...x })),+ measures: allFields.filter((x) => x.analyticType === 'measure').map((x) => ({ ...x })),+ },+ config: { ...emptyVisualConfig },+ layout: {+ ...emptyVisualLayout,+ size: { ...emptyVisualLayout.size },+ format: { ...emptyVisualLayout.format },+ resolve: { ...emptyVisualLayout.resolve },+ },+ };+}++/**+ * The Auto Viz entry: filter chart types by expressiveness, rank the survivors+ * by effectiveness, and produce a complete, directly-appliable IChart for each+ * legal candidate.+ *+ * When `fields` is empty and `allFields` is provided, the cold-start mode kicks+ * in: instead of greying everything out, each chart type reverse-matches a+ * minimal legal field combination from `allFields`, so an empty canvas becomes+ * a "click anything to start" palette. Matched fields are surfaced on the item+ * as `matchedFields`.+ *+ * `items` always contains every chart type in palette order, so the UI can+ * render unavailable ones greyed out with their disable reason.+ */+export function recommend(options: IRecommendOptions): IAutoVizResult {+ const { fields, base, allFields, geoFeatureReady = false } = options;+ const features = extractFeatures(fields, geoFeatureReady);+ const baseChart = base ?? scaffoldChart(allFields ?? fields);+ const coldStart = features.fields.length === 0 && (allFields ?? []).some((f) => f.fid !== MEA_KEY_ID && f.fid !== MEA_VAL_ID);+ const unavailable = (rule: IAutoVizRule, reason: IAutoVizDisableReason): IAutoVizItem => ({+ chartType: rule.chartType,+ available: false,+ isDefault: false,+ score: 0,+ reason,+ chart: null,+ });+ const items: IAutoVizItem[] = AUTO_VIZ_RULES.map((rule) => {+ if (coldStart) {+ const syn = synthesizeFields(rule, allFields!, geoFeatureReady);+ if ('reason' in syn) {+ return unavailable(rule, syn.reason);+ }+ const f = extractFeatures(syn.fields, geoFeatureReady);+ // synthesis is requirement-driven, but `check` hooks (e.g. histogram+ // rejecting the count field) still get the final word+ const reason = checkExpressiveness(rule, f);+ if (reason) {+ return unavailable(rule, reason);+ }+ return {+ chartType: rule.chartType,+ available: true,+ isDefault: false,+ score: rule.score(f),+ reason: null,+ chart: rule.build(f, baseChart),+ matchedFields: syn.fields,+ };+ }+ const reason = checkExpressiveness(rule, features);+ if (reason) {+ return unavailable(rule, reason);+ }+ return {+ chartType: rule.chartType,+ available: true,+ isDefault: false,+ score: rule.score(features),+ reason: null,+ chart: rule.build(features, baseChart),+ };+ });+ let defaultItem: IAutoVizItem | null = null;+ for (const item of items) {+ if (item.available && (!defaultItem || item.score > defaultItem.score)) {+ defaultItem = item;+ }+ }+ if (defaultItem) {+ defaultItem.isDefault = true;+ }+ return { items, defaultItem };+}diff --git a/packages/graphic-walker/src/lib/autoViz/rules.ts b/packages/graphic-walker/src/lib/autoViz/rules.tsnew file mode 100644index 00000000..f4fcc86c--- /dev/null+++ b/packages/graphic-walker/src/lib/autoViz/rules.ts@@ -0,0 +1,156 @@+import { COUNT_FIELD_ID } from '../../constants';+import { builders } from './builders';+import { IAutoVizChartType, IAutoVizRule } from './types';++const INF = Infinity;++/** canonical palette order, also the tie-breaker of effectiveness ranking */+export const AUTO_VIZ_CHART_ORDER: IAutoVizChartType[] = [+ 'table',+ 'highlight_table',+ 'heatmap',+ 'bar',+ 'stacked_bar',+ 'grouped_bar',+ 'line',+ 'area',+ 'histogram',+ 'scatter',+ 'circle_view',+ 'pie',+ 'boxplot',+ 'poi_map',+ 'choropleth_map',+];++/**+ * The declarative Auto Viz rule table.+ *+ * `dim` / `mea` / `requires` implement the expressiveness filter (hard constraints):+ * a chart type is only offered when it can encode all selected fields without+ * fabricating facts. `score` implements the effectiveness ranking (soft ordering):+ * among legal candidates, position-encoding, intent-matching charts win.+ *+ * Score conventions — the champion of a typical intent scores in the 85–95 band:+ * - pure dimensions → table (90)+ * - single measure → histogram (90)+ * - two+ measures → scatter (93 alone / 84 with dimensions)+ * - temporal + measure → line (92)+ * - category + measure → bar (85 for the 1×1 case / 80 otherwise)+ * - geographic fields → maps (poi 95 so it beats scatter on a lon/lat pair, choropleth 86)+ * Weak-perception encodings (pie: angle, heatmap: color) stay in the 35–70 band+ * so they are offered but never become the default over a position-based chart.+ */+export const AUTO_VIZ_RULES: IAutoVizRule[] = [+ {+ chartType: 'table',+ dim: [0, INF],+ mea: [0, INF],+ score: (f) => (f.nMea === 0 ? 90 : 20),+ build: builders.table,+ },+ {+ chartType: 'highlight_table',+ dim: [1, INF],+ mea: [1, 1],+ score: () => 55,+ build: builders.highlight_table,+ },+ {+ chartType: 'heatmap',+ dim: [2, INF],+ mea: [0, 2],+ score: (f) => (f.nMea <= 1 ? 70 : 60),+ build: builders.heatmap,+ },+ {+ chartType: 'bar',+ dim: [1, INF],+ mea: [1, INF],+ score: (f) => (f.nDim === 1 && f.nMea === 1 ? 85 : 80),+ build: builders.bar,+ },+ {+ chartType: 'stacked_bar',+ dim: [2, INF],+ mea: [1, INF],+ score: () => 62,+ build: builders.stacked_bar,+ },+ {+ chartType: 'grouped_bar',+ dim: [2, INF],+ mea: [1, INF],+ score: () => 58,+ build: builders.grouped_bar,+ },+ {+ chartType: 'line',+ dim: [1, INF],+ mea: [1, INF],+ requires: ['temporal_or_ordinal'],+ score: (f) => (f.temporalDims.length > 0 ? 92 : 75),+ build: builders.line,+ },+ {+ chartType: 'area',+ dim: [1, INF],+ mea: [1, INF],+ requires: ['temporal'],+ score: () => 68,+ build: builders.area,+ },+ {+ chartType: 'histogram',+ dim: [0, 0],+ mea: [1, 1],+ check: (f) => (f.measures[0]?.fid === COUNT_FIELD_ID ? 'need_raw_measure' : null),+ score: () => 90,+ build: builders.histogram,+ },+ {+ chartType: 'scatter',+ dim: [0, INF],+ mea: [2, 4],+ score: (f) => (f.nDim === 0 ? 93 : 84),+ build: builders.scatter,+ },+ {+ chartType: 'circle_view',+ dim: [1, INF],+ mea: [1, INF],+ score: () => 45,+ build: builders.circle_view,+ },+ {+ chartType: 'pie',+ dim: [1, 2],+ mea: [1, 2],+ score: () => 35,+ build: builders.pie,+ },+ {+ chartType: 'boxplot',+ dim: [1, INF],+ mea: [1, INF],+ score: () => 48,+ build: builders.boxplot,+ },+ {+ chartType: 'poi_map',+ dim: [0, 2],+ mea: [0, INF],+ requires: ['lon_lat'],+ check: (f) => (f.nonGeoMeasures.length > 2 ? 'too_many_measures' : null),+ score: () => 95,+ build: builders.poi_map,+ },+ {+ chartType: 'choropleth_map',+ dim: [1, INF],+ mea: [0, 1],+ requires: ['geo_feature'],+ score: () => 86,+ build: builders.choropleth_map,+ },+];diff --git a/packages/graphic-walker/src/lib/autoViz/synthesize.ts b/packages/graphic-walker/src/lib/autoViz/synthesize.tsnew file mode 100644index 00000000..630d6ef9--- /dev/null+++ b/packages/graphic-walker/src/lib/autoViz/synthesize.ts@@ -0,0 +1,84 @@+import { MEA_KEY_ID, MEA_VAL_ID } from '../../constants';+import { IViewField } from '../../interfaces';+import { IAutoVizDisableReason, IAutoVizRule } from './types';++export type ISynthesizeResult = { fields: IViewField[] } | { reason: IAutoVizDisableReason };++/**+ * Reverse matching for the cold-start mode: given a rule and the dataset's full+ * field list, deterministically pick a minimal legal field combination.+ *+ * Fields demanded by special requirements (temporal, lon/lat) are picked first,+ * then the remaining dim/mea minimums are filled in field-list order, so the+ * result is stable across calls. Returns the blocking reason when the dataset+ * cannot satisfy the rule at all.+ *+ * The picked set is minimal, not scored: rule maximum counts can never be+ * exceeded because only `dim[0]` / `mea[0]` slots are filled.+ */+export function synthesizeFields(rule: IAutoVizRule, allFields: IViewField[], geoFeatureReady = false): ISynthesizeResult {+ const usable = allFields.filter((f) => f.fid !== MEA_KEY_ID && f.fid !== MEA_VAL_ID);+ const dims = usable.filter((f) => f.analyticType === 'dimension');+ // lon/lat only participate when the rule demands them: a coordinate dropped+ // into a generic measure slot produces a nonsense chart+ const genericMeas = usable.filter((f) => f.analyticType === 'measure' && f.geoRole !== 'longitude' && f.geoRole !== 'latitude');++ const pickedDims: IViewField[] = [];+ const pickedMeas: IViewField[] = [];++ for (const req of rule.requires ?? []) {+ switch (req) {+ case 'temporal': {+ const t = dims.find((f) => f.semanticType === 'temporal');+ if (!t) return { reason: 'need_temporal' };+ pickedDims.push(t);+ break;+ }+ case 'temporal_or_ordinal': {+ const t = dims.find((f) => f.semanticType === 'temporal') ?? dims.find((f) => f.semanticType === 'ordinal');+ if (!t) return { reason: 'need_temporal_or_ordinal' };+ pickedDims.push(t);+ break;+ }+ case 'lon_lat': {+ const lonF = usable.find((f) => f.geoRole === 'longitude');+ const latF = usable.find((f) => f.geoRole === 'latitude');+ if (!lonF || !latF) return { reason: 'need_lon_lat' };+ (lonF.analyticType === 'dimension' ? pickedDims : pickedMeas).push(lonF);+ (latF.analyticType === 'dimension' ? pickedDims : pickedMeas).push(latF);+ break;+ }+ case 'geo_feature': {+ if (!geoFeatureReady) return { reason: 'need_geo_feature' };+ break;+ }+ }+ }++ for (const f of dims) {+ if (pickedDims.length >= rule.dim[0]) break;+ if (!pickedDims.includes(f)) pickedDims.push(f);+ }+ if (pickedDims.length < rule.dim[0]) {+ return { reason: rule.dim[0] >= 2 ? 'need_two_dimensions' : 'need_dimension' };+ }++ const meaTarget = rule.mea[0] + pickedMeas.length; // requirement-derived picks (lon/lat) don't consume generic slots+ for (const f of genericMeas) {+ if (pickedMeas.length >= meaTarget) break;+ if (!pickedMeas.includes(f)) pickedMeas.push(f);+ }+ if (pickedMeas.length < meaTarget) {+ return { reason: rule.mea[0] >= 2 ? 'need_two_measures' : 'need_measure' };+ }++ // a zero-minimum rule with no requirement-derived picks (e.g. table) still+ // needs at least one field to say anything+ if (pickedDims.length === 0 && pickedMeas.length === 0) {+ const first = dims[0] ?? genericMeas[0];+ if (!first) return { reason: 'need_fields' };+ (first.analyticType === 'dimension' ? pickedDims : pickedMeas).push(first);+ }++ return { fields: [...pickedDims, ...pickedMeas] };+}diff --git a/packages/graphic-walker/src/lib/autoViz/types.ts b/packages/graphic-walker/src/lib/autoViz/types.tsnew file mode 100644index 00000000..9949d767--- /dev/null+++ b/packages/graphic-walker/src/lib/autoViz/types.ts@@ -0,0 +1,118 @@+import { IChart, IViewField } from '../../interfaces';++/**+ * Business-level chart types of the Auto Viz palette.+ * Multiple chart types may share one geom (e.g. bar / stacked_bar / grouped_bar all use 'bar'),+ * differing in channel assignment, stack mode or aggregation.+ */+export type IAutoVizChartType =+ | 'table'+ | 'highlight_table'+ | 'heatmap'+ | 'bar'+ | 'stacked_bar'+ | 'grouped_bar'+ | 'line'+ | 'area'+ | 'histogram'+ | 'scatter'+ | 'circle_view'+ | 'pie'+ | 'boxplot'+ | 'poi_map'+ | 'choropleth_map';++/**+ * Why a chart type is greyed out in the palette.+ * Rendered through i18n key `autoviz.reason.${reason}`.+ */+export type IAutoVizDisableReason =+ | 'need_fields'+ | 'need_dimension'+ | 'need_two_dimensions'+ | 'too_many_dimensions'+ | 'need_measure'+ | 'need_two_measures'+ | 'need_single_measure'+ | 'too_many_measures'+ | 'need_temporal'+ | 'need_temporal_or_ordinal'+ | 'need_raw_measure'+ | 'need_lon_lat'+ | 'need_geo_feature';++/**+ * Statistical features of the selected fields, the only input of+ * expressiveness filtering and effectiveness scoring.+ */+export interface IFieldFeatures {+ /** selected fields, fold virtual fields (gw_mea_key / gw_mea_val) excluded */+ fields: IViewField[];+ dimensions: IViewField[];+ measures: IViewField[];+ nDim: number;+ nMea: number;+ temporalDims: IViewField[];+ ordinalDims: IViewField[];+ /** [longitude, latitude] pair resolved from field geoRole */+ lonLat: [IViewField, IViewField] | null;+ /** measures excluding the lon/lat pair */+ nonGeoMeasures: IViewField[];+ /** a geojson feature is configured on the current chart, enabling choropleth */+ geoFeatureReady: boolean;+}++export interface IAutoVizRule {+ chartType: IAutoVizChartType;+ /** [min, max] count of selected dimensions */+ dim: [number, number];+ /** [min, max] count of selected measures */+ mea: [number, number];+ /** type-level expressiveness constraints */+ requires?: ('temporal' | 'temporal_or_ordinal' | 'lon_lat' | 'geo_feature')[];+ /** extra expressiveness check beyond the declarative ranges */+ check?: (f: IFieldFeatures) => IAutoVizDisableReason | null;+ /** effectiveness score, only evaluated after the rule passes expressiveness */+ score: (f: IFieldFeatures) => number;+ /** produce a complete chart spec; `base` carries field shelves, filters, config and layout to inherit */+ build: (f: IFieldFeatures, base: IChart) => IChart;+}++export interface IAutoVizItem {+ chartType: IAutoVizChartType;+ available: boolean;+ /** effectiveness champion among available items */+ isDefault: boolean;+ score: number;+ reason: IAutoVizDisableReason | null;+ /** ready to be applied via vizStore.applyChart, null when unavailable */+ chart: IChart | null;+ /** cold-start mode only: the field combination reverse-matched for this chart type */+ matchedFields?: IViewField[] | null;+}++export interface IAutoVizResult {+ /** every chart type in canonical palette order */+ items: IAutoVizItem[];+ defaultItem: IAutoVizItem | null;+}++export interface IRecommendOptions {+ /** fields to encode */+ fields: IViewField[];+ /**+ * current chart; its field shelves, filters, visId, config and layout are inherited+ * so that applying a recommendation never loses dataset fields or user preferences.+ * Pass a plain object (e.g. mobx toJS), not an observable.+ */+ base?: IChart;+ /**+ * full field shelves of the dataset. Two uses: scaffolding a chart when no+ * `base` is provided, and — when `fields` is empty — the cold-start mode,+ * where every chart type reverse-matches a minimal legal field combination+ * from this list instead of being greyed out.+ */+ allFields?: IViewField[];+ /** whether a geojson feature is configured (enables choropleth) */+ geoFeatureReady?: boolean;+}diff --git a/packages/graphic-walker/src/locales/en-US.json b/packages/graphic-walker/src/locales/en-US.jsonindex a6f4f00f..74874c0e 100644--- a/packages/graphic-walker/src/locales/en-US.json+++ b/packages/graphic-walker/src/locales/en-US.json@@ -217,6 +217,7 @@"debug": "debugging"},"sort": "Sorting Order",+ "autoviz": "Auto Viz","button": {"ascending": "Sort in Ascending Order","descending": "Sort in Descending Order",@@ -366,5 +367,53 @@"log_panel_title": "Logarithm Transformation","log_panel_desc": "Set log config for field","log_panel_number": "Logarithmic base"+ },+ "autoviz": {+ "title": "Auto Viz",+ "description": "Pick the fields you care about; legal chart types light up and the best one is starred.",+ "recommended": "Recommended",+ "apply_best": "Apply recommended",+ "hint": "{{count}} chart types match your selection",+ "empty": "…or click any lit chart type to start",+ "based_on_view": "Based on the fields in the current chart · {{count}} types match",+ "selected_count": "{{count}} fields selected in the field list",+ "clear": "Clear",+ "uses": "Uses: {{fields}}",+ "select_hint": "Pick fields on the left · <k></k>+click to multi-select",+ "refine_hint": "Click or <k></k>+click fields on the left to refine",+ "collapse": "Collapse panel",+ "expand": "Show Auto Viz",+ "charts": {+ "table": "Text Table",+ "highlight_table": "Highlight Table",+ "heatmap": "Heat Map",+ "bar": "Bar Chart",+ "stacked_bar": "Stacked Bar",+ "grouped_bar": "Grouped Bar",+ "line": "Line Chart",+ "area": "Area Chart",+ "histogram": "Histogram",+ "scatter": "Scatter Plot",+ "circle_view": "Circle View",+ "pie": "Pie Chart",+ "boxplot": "Box Plot",+ "poi_map": "Symbol Map",+ "choropleth_map": "Filled Map"+ },+ "reason": {+ "need_fields": "Select at least one field",+ "need_dimension": "Needs at least 1 dimension",+ "need_two_dimensions": "Needs at least 2 dimensions",+ "too_many_dimensions": "Too many dimensions for this chart",+ "need_measure": "Needs at least 1 measure",+ "need_two_measures": "Needs at least 2 measures",+ "need_single_measure": "Needs exactly 1 measure",+ "too_many_measures": "Too many measures for this chart",+ "need_temporal": "Needs a date/time dimension",+ "need_temporal_or_ordinal": "Needs a date/time or ordinal dimension",+ "need_raw_measure": "Needs a raw measure, not row count",+ "need_lon_lat": "Needs longitude & latitude fields",+ "need_geo_feature": "Needs a configured GeoJSON boundary"+ }}}diff --git a/packages/graphic-walker/src/locales/ja-JP.json b/packages/graphic-walker/src/locales/ja-JP.jsonindex d9aca057..56ac6d76 100644--- a/packages/graphic-walker/src/locales/ja-JP.json+++ b/packages/graphic-walker/src/locales/ja-JP.json@@ -206,6 +206,7 @@"debug": "デバッグ"},"sort": "並べ替えの順序",+ "autoviz": "Auto Viz","button": {"ascending": "昇順に並べ替える","descending": "降順に並べ替える",@@ -355,5 +356,53 @@"log_panel_title": "対数変換","log_panel_desc": "フィールドの対数設定を設定する","log_panel_number": "対数の底"+ },+ "autoviz": {+ "title": "Auto Viz",+ "description": "関心のあるフィールドを選ぶと、作成可能なチャートがハイライトされ、最適なものに印が付きます。",+ "recommended": "おすすめ",+ "apply_best": "おすすめを適用",+ "hint": "{{count}} 種類のチャートが利用可能です",+ "empty": "またはチャートをクリックして開始",+ "based_on_view": "現在のチャートのフィールドに基づく · {{count}} 種類が利用可能",+ "selected_count": "フィールドリストで {{count}} 個選択中",+ "clear": "クリア",+ "uses": "使用フィールド:{{fields}}",+ "select_hint": "左のフィールドをクリックで選択 · <k></k>+クリックで複数選択",+ "refine_hint": "フィールドをクリック / <k></k>+クリックで絞り込み",+ "collapse": "パネルを折りたたむ",+ "expand": "Auto Viz を表示",+ "charts": {+ "table": "テキストテーブル",+ "highlight_table": "ハイライトテーブル",+ "heatmap": "ヒートマップ",+ "bar": "棒グラフ",+ "stacked_bar": "積み上げ棒グラフ",+ "grouped_bar": "グループ棒グラフ",+ "line": "折れ線グラフ",+ "area": "面グラフ",+ "histogram": "ヒストグラム",+ "scatter": "散布図",+ "circle_view": "サークルビュー",+ "pie": "円グラフ",+ "boxplot": "箱ひげ図",+ "poi_map": "シンボルマップ",+ "choropleth_map": "塗り分けマップ"+ },+ "reason": {+ "need_fields": "フィールドを1つ以上選択してください",+ "need_dimension": "ディメンションが1つ以上必要です",+ "need_two_dimensions": "ディメンションが2つ以上必要です",+ "too_many_dimensions": "ディメンションが多すぎます",+ "need_measure": "メジャーが1つ以上必要です",+ "need_two_measures": "メジャーが2つ以上必要です",+ "need_single_measure": "メジャーは1つだけ選択できます",+ "too_many_measures": "メジャーが多すぎます",+ "need_temporal": "日付/時間ディメンションが必要です",+ "need_temporal_or_ordinal": "日付/時間または順序ディメンションが必要です",+ "need_raw_measure": "行数ではなく生のメジャーが必要です",+ "need_lon_lat": "経度・緯度フィールドが必要です",+ "need_geo_feature": "GeoJSON 境界の設定が必要です"+ }}}diff --git a/packages/graphic-walker/src/locales/zh-CN.json b/packages/graphic-walker/src/locales/zh-CN.jsonindex 8d0c143f..d2b204ac 100644--- a/packages/graphic-walker/src/locales/zh-CN.json+++ b/packages/graphic-walker/src/locales/zh-CN.json@@ -212,6 +212,7 @@"debug": "图表调试"},"sort": "排序",+ "autoviz": "图表推荐","button": {"ascending": "升序排序","descending": "降序排序",@@ -361,5 +362,53 @@"log_panel_title": "对数变换","log_panel_desc": "设置字段的对数配置","log_panel_number": "对数底数"+ },+ "autoviz": {+ "title": "Auto Viz · 图表推荐",+ "description": "勾选你关心的字段,可用的图表类型会亮起,最佳推荐带星标。",+ "recommended": "推荐",+ "apply_best": "应用推荐",+ "hint": "当前选择匹配 {{count}} 种图表类型",+ "empty": "或直接点击任意亮起的图表开始",+ "based_on_view": "基于当前图表中的字段 · 匹配 {{count}} 种类型",+ "selected_count": "字段列表中已选中 {{count}} 个字段",+ "clear": "清除",+ "uses": "将使用:{{fields}}",+ "select_hint": "点击左侧字段进行选择 · <k></k>+点击可多选",+ "refine_hint": "点击或 <k></k>+点击左侧字段可细化推荐",+ "collapse": "收起面板",+ "expand": "展开图表推荐",+ "charts": {+ "table": "文本表",+ "highlight_table": "高亮表",+ "heatmap": "热力图",+ "bar": "条形图",+ "stacked_bar": "堆叠条形图",+ "grouped_bar": "并列条形图",+ "line": "折线图",+ "area": "面积图",+ "histogram": "直方图",+ "scatter": "散点图",+ "circle_view": "圆点视图",+ "pie": "饼图",+ "boxplot": "箱线图",+ "poi_map": "符号地图",+ "choropleth_map": "填充地图"+ },+ "reason": {+ "need_fields": "请至少选择一个字段",+ "need_dimension": "需要至少 1 个维度",+ "need_two_dimensions": "需要至少 2 个维度",+ "too_many_dimensions": "维度数量过多",+ "need_measure": "需要至少 1 个度量",+ "need_two_measures": "需要至少 2 个度量",+ "need_single_measure": "只能选择 1 个度量",+ "too_many_measures": "度量数量过多",+ "need_temporal": "需要一个日期/时间维度",+ "need_temporal_or_ordinal": "需要一个日期/时间或有序维度",+ "need_raw_measure": "需要原始度量(不能是行数)",+ "need_lon_lat": "需要经度和纬度字段",+ "need_geo_feature": "需要先配置 GeoJSON 边界"+ }}}diff --git a/packages/graphic-walker/src/models/chat.ts b/packages/graphic-walker/src/models/chat.tsindex 278d3e38..b0d641cf 100644--- a/packages/graphic-walker/src/models/chat.ts+++ b/packages/graphic-walker/src/models/chat.ts@@ -293,6 +293,7 @@ const actionMessageMapper: {[Methods.removeAllField]: () => '',[Methods.editAllField]: () => '',[Methods.replaceWithNLPQuery]: () => '',+ [Methods.replaceChart]: (_data, chart) => `Replace the chart with a recommended ${chart.config?.geoms?.[0] ?? ''} chart.`,};function toMessage<T>(data: IChart, action: VisActionOf<T>) {diff --git a/packages/graphic-walker/src/models/replaceChart.test.ts b/packages/graphic-walker/src/models/replaceChart.test.tsnew file mode 100644index 00000000..f3e19597--- /dev/null+++ b/packages/graphic-walker/src/models/replaceChart.test.ts@@ -0,0 +1,43 @@+jest.mock('nanoid', () => ({ nanoid: () => 'mock-id' }));++import { exportFullRaw, fromSnapshot, importFull, newChart, performers, redo, undo } from './visSpecHistory';++const FIELDS = [{ fid: 'cat', semanticType: 'nominal', analyticType: 'dimension' }] as const;++const chartA = () => newChart([...FIELDS], 'Chart-A', 'vis-1');+const chartB = () => ({ ...newChart([...FIELDS], 'Chart-B', 'vis-1'), name: 'Chart-B' });++describe('Methods.replaceChart (undoable whole-chart replacement)', () => {+ test('apply → undo → redo roundtrip restores the replacement', () => {+ const applied = performers.replaceChart(fromSnapshot(chartA()), chartB());+ expect(applied.now.name).toBe('Chart-B');+ expect(applied.cursor).toBeLessThanOrEqual(applied.timeline.length);++ const undone = undo(applied);+ expect(undone.now.name).toBe('Chart-A');+ // redo must be able to reach the replacement again+ expect(undone.cursor).toBeLessThan(undone.timeline.length);+ expect(redo(undone).now.name).toBe('Chart-B');+ });++ test('apply → further edit → undo returns to the replacement, not the pre-apply chart', () => {+ const applied = performers.replaceChart(fromSnapshot(chartA()), chartB());+ const edited = performers.setName(applied, 'renamed-by-user');+ expect(edited.now.name).toBe('renamed-by-user');++ const undone = undo(edited);+ expect(undone.now.name).toBe('Chart-B');+ expect(undo(undone).now.name).toBe('Chart-A');+ });++ test('exported history preserves the replacement', () => {+ const applied = performers.replaceChart(fromSnapshot(chartA()), chartB());+ const restored = importFull(exportFullRaw(applied));+ expect(restored.now.name).toBe('Chart-B');+ });++ test('replay keeps the original visId', () => {+ const applied = performers.replaceChart(fromSnapshot(chartA()), { ...chartB(), visId: 'other-vis' });+ expect(applied.now.visId).toBe('vis-1');+ });+});diff --git a/packages/graphic-walker/src/models/visSpecHistory.ts b/packages/graphic-walker/src/models/visSpecHistory.tsindex 944dc03c..d9b7b52d 100644--- a/packages/graphic-walker/src/models/visSpecHistory.ts+++ b/packages/graphic-walker/src/models/visSpecHistory.ts@@ -61,6 +61,8 @@ export enum Methods {removeAllField,editAllField,replaceWithNLPQuery,+ // appended at the end: enum values are serialized in exported timelines+ replaceChart,}export type PropsMap = {[Methods.setConfig]: KVTuple<IVisualConfigNew>;@@ -89,6 +91,7 @@ export type PropsMap = {[Methods.removeAllField]: [string];[Methods.editAllField]: [string, Partial<IField>];[Methods.replaceWithNLPQuery]: [string, string];+ [Methods.replaceChart]: [PartialChart];};// ensure propsMap has all keys of methodstype assertPropsMap = AssertSameKey<PropsMap, { [a in Methods]: any }>;@@ -484,6 +487,9 @@ const actions: {[Methods.replaceWithNLPQuery]: (data, _query, response) => {return { ...JSON.parse(response), visId: data.visId, name: data.name };},+ [Methods.replaceChart]: (data, chart) => {+ return fillChart({ ...chart, visId: data.visId, name: chart.name ?? data.name });+ },};const diffChangedEncodings = (prev: IChart, next: IChart) => {diff --git a/packages/graphic-walker/src/store/visualSpecStore.ts b/packages/graphic-walker/src/store/visualSpecStore.tsindex 7f46bd59..5e5e69d4 100644--- a/packages/graphic-walker/src/store/visualSpecStore.ts+++ b/packages/graphic-walker/src/store/visualSpecStore.ts@@ -67,6 +67,8 @@ export class VizSpecStore {segmentKey: ISegmentKey = ISegmentKey.vis;showInsightBoard: boolean = false;showDataBoard: boolean = false;+ // the Auto Viz dock on the right of the workspace starts expanded; the toolbar toggle collapses it+ showAutoVizPanel: boolean = true;vizEmbededMenu: { show: boolean; position: [number, number] } = { show: false, position: [0, 0] };showDataConfig: boolean = false;showCodeExportPanel: boolean = false;@@ -88,6 +90,8 @@ export class VizSpecStore {lastSpec: string = '';editingComputedFieldFid: string | undefined = undefined;defaultConfig: IDefaultConfig | undefined;+ /** fields highlighted in the field list (Tableau-style multi-select feeding Auto Viz); UI state, not part of the undo timeline */+ selectedFieldIds: string[] = [];onMetaChange?: (fid: string, diffMeta: Partial<IMutField>) => void;@@ -241,7 +245,7 @@ export class VizSpecStore {get canRedo() {const viz = this.visList[this.visIndex];- return viz.cursor !== viz.timeline.length;+ return viz.cursor < viz.timeline.length;}get chatMessages() {@@ -649,10 +653,16 @@ export class VizSpecStore {this.showAskvizFeedbackIndex = show ? this.visIndex : undefined;}+ /** replace the current chart and RESET its history (used by controlled `spec` prop syncing) */replaceNow(chart: IChart) {this.visList[this.visIndex] = fromSnapshot(chart);}+ /** replace the current chart as an undoable/redoable timeline action (used by Auto Viz) */+ applyChart(chart: IChart) {+ this.visList[this.visIndex] = performers.replaceChart(this.visList[this.visIndex], chart);+ }+selectVisualization(index: number) {this.visIndex = index;}@@ -666,6 +676,30 @@ export class VizSpecStore {setShowDataBoard(show: boolean) {this.showDataBoard = show;}+ setShowAutoVizPanel(show: boolean) {+ this.showAutoVizPanel = show;+ }+ /** plain click: make this the only selected field; clicking the sole selected field deselects it */+ selectField(fid: string) {+ if (this.selectedFieldIds.length === 1 && this.selectedFieldIds[0] === fid) {+ this.selectedFieldIds = [];+ } else {+ this.selectedFieldIds = [fid];+ }+ }+ /** ctrl/cmd click: toggle this field in the selection */+ toggleFieldSelection(fid: string) {+ if (this.selectedFieldIds.includes(fid)) {+ this.selectedFieldIds = this.selectedFieldIds.filter((x) => x !== fid);+ } else {+ this.selectedFieldIds = [...this.selectedFieldIds, fid];+ }+ }+ clearFieldSelection() {+ if (this.selectedFieldIds.length > 0) {+ this.selectedFieldIds = [];+ }+ }showEmbededMenu(position: [number, number]) {this.vizEmbededMenu.show = true;this.vizEmbededMenu.position = position;diff --git a/packages/graphic-walker/src/visualSettings/index.tsx b/packages/graphic-walker/src/visualSettings/index.tsxindex 2be96316..324ef2c0 100644--- a/packages/graphic-walker/src/visualSettings/index.tsx+++ b/packages/graphic-walker/src/visualSettings/index.tsx@@ -21,6 +21,7 @@ import {GlobeAmericasIcon,DocumentPlusIcon,PaintBrushIcon,+ SparklesIcon,} from '@heroicons/react/24/outline';import { observer } from 'mobx-react-lite';import React, { SVGProps, useCallback, useMemo } from 'react';@@ -328,6 +329,13 @@ const VisualSettings: React.FC<IVisualSettings> = ({ rendererHandler, csvHandlervizStore.setVisualConfig('geoms', [value]);},},+ {+ key: 'autoviz',+ label: t('autoviz'),+ icon: SparklesIcon,+ checked: vizStore.showAutoVizPanel,+ onChange: (checked: boolean) => vizStore.setShowAutoVizPanel(checked),+ },{key: 'stack_mode',label: tGlobal('constant.stack_mode.__enum__'),