An open source alternative to Tableau. Embeddable visual analytic
TypeScript bidatadata-analysisdata-miningdata-visualizationedak6skanarieslow-codepivot-tablereacttableautableau-alternativetypescriptvegavega-litevisualization
feat: add nominal support for data painter (#288)
islxyqwe02903fc84099
diff --git a/packages/graphic-walker/src/components/painter/components.tsx b/packages/graphic-walker/src/components/painter/components.tsxindex a067b3b1..45c034cf 100644--- a/packages/graphic-walker/src/components/painter/components.tsx+++ b/packages/graphic-walker/src/components/painter/components.tsx@@ -1,7 +1,6 @@import React, { useEffect } from 'react';import { getCircle } from '../../lib/paint';import { SketchPicker } from 'react-color';-import Default from '../tabs/defaultTab';import DefaultButton from '../button/default';import { ShadowDomContext } from '../../shadow-dom';@@ -43,16 +42,30 @@ export const PixelCursor = (props: { color: string; dia: number; factor: number;);};-export const Container = (props: {+export type CursorDef =+ | {+ type: 'circle';+ dia: number;+ factor: number;+ }+ | {+ type: 'rect';+ x: number;+ xFactor: number;+ y: number;+ yFactor: number;+ };++export const PixelContainer = (props: {color: string;- dia: number;- factor: number;+ cursor: CursorDef;+ offsetX: number;+ offsetY: number;children?: React.ReactNode | Iterable<React.ReactNode>;showPreview?: boolean;}) => {- const { color, factor, dia, children, showPreview } = props;+ const { color, cursor, offsetX, offsetY, children, showPreview } = props;const [cursorPos, setCursorPos] = React.useState<[number, number] | null>(null);- const size = dia * factor;return (<divclassName="relative cursor-none"@@ -65,83 +78,78 @@ export const Container = (props: {onTouchEnd={() => setCursorPos(null)}>{children}- {cursorPos !== null && (- <div- className="absolute pointer-events-none"- style={{- background: color,- width: size,- height: size,- borderRadius: size,- opacity: 0.6,- left: cursorPos[0] - size / 2,- top: cursorPos[1] - size / 2,- }}- />+ {cursorPos !== null && cursor.type === 'rect' && (+ <>+ <div+ className="absolute pointer-events-none"+ style={{+ backgroundColor: color,+ left:+ Math.floor((cursorPos[0] - offsetX) / cursor.xFactor) * cursor.xFactor ++ offsetX -+ ((cursor.x - (cursor.x % 2)) / 2) * cursor.xFactor,+ top:+ Math.floor((cursorPos[1] - offsetY) / cursor.yFactor) * cursor.yFactor ++ offsetY -+ ((cursor.y - (cursor.y % 2)) / 2 - 1 + (cursor.y % 2)) * cursor.yFactor,+ width: cursor.x * cursor.xFactor,+ height: cursor.y * cursor.yFactor,+ opacity: 0.6,+ }}+ />+ <div+ className="absolute pointer-events-none bg-black dark:bg-white"+ style={{+ width: 16,+ height: 16,+ borderRadius: 16,+ opacity: 0.4,+ left: cursorPos[0] - 8,+ top: cursorPos[1] - 8,+ }}+ />+ </>)}- {showPreview && !cursorPos && (+ {showPreview && !cursorPos && cursor.type === 'rect' && (<divclassName="absolute pointer-events-none"style={{- background: color,- width: size,- height: size,- borderRadius: size,+ backgroundColor: color,+ width: cursor.x * cursor.xFactor,+ height: cursor.y * cursor.yFactor,opacity: 0.6,- left: `calc(50% - ${size / 2}px)`,- top: `calc(50% - ${size / 2}px)`,+ left: `calc(50% - ${((cursor.x - (cursor.x % 2)) / 2) * cursor.xFactor}px)`,+ top: `calc(50% - ${((cursor.y - (cursor.y % 2)) / 2) * cursor.yFactor}px)`,}}/>)}- </div>- );-};--export const PixelContainer = (props: {- color: string;- dia: number;- factor: number;- offsetX: number;- offsetY: number;- children?: React.ReactNode | Iterable<React.ReactNode>;- showPreview?: boolean;-}) => {- const { color, dia, factor, offsetX, offsetY, children, showPreview } = props;- const [cursorPos, setCursorPos] = React.useState<[number, number] | null>(null);- const center = (dia - (dia % 2)) / 2;- return (- <div- className="relative cursor-none"- onMouseOut={() => setCursorPos(null)}- onMouseMoveCapture={(e) => setCursorPos([e.nativeEvent.offsetX, e.nativeEvent.offsetY])}- onTouchMoveCapture={(e) => {- const rect = e.currentTarget.getBoundingClientRect();- setCursorPos([e.changedTouches[0].pageX - rect.left, e.changedTouches[0].pageY - rect.top]);- }}- onTouchEnd={() => setCursorPos(null)}- >- {children}- {cursorPos !== null && (+ {cursorPos !== null && cursor.type === 'circle' && (<PixelCursorclassName="absolute pointer-events-none"color={color}- factor={factor}- dia={dia}+ factor={cursor.factor}+ dia={cursor.dia}style={{- left: Math.floor((cursorPos[0] - offsetX) / factor) * factor + offsetX - center * factor,- top: Math.floor((cursorPos[1] - offsetY) / factor) * factor + offsetY - (center - 1 + (dia % 2)) * factor,+ left:+ Math.floor((cursorPos[0] - offsetX) / cursor.factor) * cursor.factor ++ offsetX -+ ((cursor.dia - (cursor.dia % 2)) / 2) * cursor.factor,+ top:+ Math.floor((cursorPos[1] - offsetY) / cursor.factor) * cursor.factor ++ offsetY -+ ((cursor.dia - (cursor.dia % 2)) / 2 - 1 + (cursor.dia % 2)) * cursor.factor,}}/>)}- {showPreview && !cursorPos && (+ {showPreview && !cursorPos && cursor.type === 'circle' && (<PixelCursorclassName="absolute pointer-events-none"color={color}- factor={factor}- dia={dia}+ factor={cursor.factor}+ dia={cursor.dia}style={{- left: `calc(50% - ${center * factor}px)`,- top: `calc(50% - ${center * factor}px)`,+ left: `calc(50% - ${((cursor.dia - (cursor.dia % 2)) / 2) * cursor.factor}px)`,+ top: `calc(50% - ${((cursor.dia - (cursor.dia % 2)) / 2) * cursor.factor}px)`,}}/>)}diff --git a/packages/graphic-walker/src/components/painter/index.tsx b/packages/graphic-walker/src/components/painter/index.tsxindex a1b1ff66..ad1d3bea 100644--- a/packages/graphic-walker/src/components/painter/index.tsx+++ b/packages/graphic-walker/src/components/painter/index.tsx@@ -1,10 +1,10 @@import React, { useEffect, useState, useRef, useMemo } from 'react';import { observer } from 'mobx-react-lite';import { useCompututaion, useVizStore } from '../../store';-import { calcIndexs, compressMap, decompressMap, emptyMap, indexesFrom } from '../../lib/paint';-import { getRange } from '../../computation';+import { calcIndexsV2, compressMap, createMap, decompressMap, indexesFrom } from '../../lib/paint';+import { fieldStat } from '../../computation';import { useRenderer } from '../../renderer/hooks';-import { IDarkMode, IThemeKey, IViewField, VegaGlobalConfig } from '../../interfaces';+import { IDarkMode, IPaintDimension, IThemeKey, IViewField, VegaGlobalConfig } from '../../interfaces';import embed from 'vega-embed';import Modal from '../modal';import { PAINT_FIELD_ID } from '../../constants';@@ -12,13 +12,14 @@ import { Scene, SceneGroup, SceneItem, ScenegraphEvent } from 'vega-typings';import { sceneVisit } from 'vega';import throttle from '../../utils/throttle';import { useTranslation } from 'react-i18next';-import { ClickInput, ColorEditor, Container, PixelContainer } from './components';+import { ClickInput, ColorEditor, CursorDef, PixelContainer } from './components';import LoadingLayer from '../loadingLayer';import DefaultButton from '../button/default';import PrimaryButton from '../button/primary';import { GLOBAL_CONFIG } from '../../config';import { GWGlobalConfig, builtInThemes } from '../../vis/theme';import { useCurrentMediaTheme } from '../../utils/media';+import { unstable_batchedUpdates } from 'react-dom';const MAGIC_PADDING = 5;const PIXEL_INDEX = '_gw_pixel_index';@@ -34,7 +35,7 @@ const MouseButtons = {const scheme = ['#4c78a8', '#f58518', '#e45756', '#72b7b2', '#54a24b', '#eeca3b', '#b279a2', '#ff9da6', '#9d755d', '#bab0ac'];-const defaultScheme = Object.fromEntries(scheme.map((color, i) => [i, { name: `L_${i + 1}`, color }]));+const defaultScheme = Object.fromEntries(scheme.map((color, i) => [i + 1, { name: `L_${i + 1}`, color }]));const emptyField = [];@@ -59,15 +60,19 @@ function selectInteractive(scene: { root: Scene }) {return selected;}+const getFactor = (f: IPaintDimension) =>+ f.domain.type === 'nominal' ? (GLOBAL_CONFIG.PAINT_SIZE_FACTOR * GLOBAL_CONFIG.PAINT_MAP_SIZE) / f.domain.width : GLOBAL_CONFIG.PAINT_SIZE_FACTOR;+const PainterContent = (props: {x: IViewField;y: IViewField;- domainX: [number, number];- domainY: [number, number];+ domainX: IPaintDimension;+ domainY: IPaintDimension;dict: typeof defaultScheme;vegaConfig: VegaGlobalConfig;onChangeDict: (d: typeof defaultScheme) => void;mapRef: React.MutableRefObject<Uint8Array | undefined>;+ allFields: IViewField[];onDelete: () => void;onCancel: () => void;onSave: () => void;@@ -90,38 +95,29 @@ const PainterContent = (props: {const brushSizeRef = useRef(GLOBAL_CONFIG.PAINT_DEFAULT_BRUSH_SIZE);const [brushSize, setBrushSize] = useState(GLOBAL_CONFIG.PAINT_DEFAULT_BRUSH_SIZE);brushSizeRef.current = brushSize;- const brushIdRef = useRef(1);- const [brushId, setBrushId] = useState(1);+ const brushIdRef = useRef(2);+ const [brushId, setBrushId] = useState(2);brushIdRef.current = brushId;const containerRef = useRef<HTMLDivElement>(null);const { loading, viewData } = useRenderer({computationFunction: computation,defaultAggregated: false,filters: emptyField,- allFields: fields,+ allFields: props.allFields,limit: -1,sort: 'none',viewDimensions: emptyField,viewMeasures: fields,});const indexes = useMemo(() => {- return calcIndexs(- viewData.map((x) => {- return x[props.x.fid];- }),- viewData.map((x) => {- return x[props.y.fid];- }),- props.domainX,- props.domainY,- GLOBAL_CONFIG.PAINT_MAP_SIZE- );- }, [viewData, props.x, props.y, props.domainX, props.domainY]);+ const mapper = calcIndexsV2([props.domainY, props.domainX]);+ return viewData.map(mapper);+ }, [viewData, props.domainX, props.domainY]);const data = useMemo(() => {return viewData.map((x, i) => {return {...x,- [PAINT_FIELD_ID]: props.dict[props.mapRef.current![indexes[i]]]?.name,+ [PAINT_FIELD_ID]: props.dict[props.mapRef.current![indexes[i]] || 1]?.name,[PIXEL_INDEX]: indexes[i],};});@@ -133,27 +129,29 @@ const PainterContent = (props: {useEffect(() => {if (!loading && containerRef.current) {+ const xQuan = props.domainX.domain.type === 'quantitative';+ const yQuan = props.domainY.domain.type === 'quantitative';const colors = Object.entries(props.dict);const spec: any = {data: {name: 'data',values: data,},- mark: { type: 'circle', opacity: 0.66 },+ mark: { type: xQuan && yQuan ? 'circle' : xQuan || yQuan ? 'tick' : 'square', opacity: 0.66 },encoding: {x: {field: props.x.fid,title: props.x.name,- type: 'quantitative',+ type: props.domainX.domain.type,axis: { labelOverlap: true },- scale: { domain: props.domainX },+ scale: { domain: props.domainX.domain.value },},y: {field: props.y.fid,title: props.y.name,- type: 'quantitative',+ type: props.domainY.domain.type,axis: { labelOverlap: true },- scale: { domain: props.domainY },+ scale: { domain: props.domainY.domain.type === 'quantitative' ? props.domainY.domain.value : props.domainY.domain.value.toReversed() },},color: {field: PAINT_FIELD_ID,@@ -188,8 +186,8 @@ const PainterContent = (props: {//@ts-ignoreconst rerender = throttle(() => res.view._renderer._render(scene.root), 100, { trailing: true });resetRef.current = () => {- props.mapRef.current! = emptyMap(GLOBAL_CONFIG.PAINT_MAP_SIZE);- const { name, color } = props.dict[0];+ props.mapRef.current! = createMap([props.domainY, props.domainX]);+ const { name, color } = props.dict[1];interactive.forEach((item) =>sceneVisit(item, (item) => {if ('datum' in item) {@@ -213,12 +211,9 @@ const PainterContent = (props: {: props.dict[brushIdRef.current];if (!targetColor) return;const pts = indexesFrom(- [- Math.floor(x / GLOBAL_CONFIG.PAINT_SIZE_FACTOR),- GLOBAL_CONFIG.PAINT_MAP_SIZE - 1 - Math.floor(y / GLOBAL_CONFIG.PAINT_SIZE_FACTOR),- ],+ [Math.floor(x / getFactor(props.domainX)), props.domainY.domain.width - 1 - Math.floor(y / getFactor(props.domainY))],brushSizeRef.current,- GLOBAL_CONFIG.PAINT_MAP_SIZE+ [props.domainY, props.domainX]);let i = 0;pts.forEach((x) => {@@ -247,11 +242,28 @@ const PainterContent = (props: {res.view.addEventListener('touchmove', handleDraw);});}- }, [loading, data, props.dict, props.vegaConfig]);+ }, [loading, data, props.dict, props.vegaConfig, props.domainX, props.domainY]);const [showCursorPreview, setShowCursorPreview] = React.useState(false);- const [pixelContainer] = React.useState(true);+ const cursor = useMemo((): CursorDef => {+ if (props.domainX.domain.type === 'quantitative' && props.domainY.domain.type === 'quantitative') {+ return { dia: brushSize, factor: GLOBAL_CONFIG.PAINT_SIZE_FACTOR, type: 'circle' };+ }+ return {+ type: 'rect',+ x: props.domainX.domain.type === 'nominal' ? 1 : brushSize,+ xFactor:+ props.domainX.domain.type === 'nominal'+ ? (GLOBAL_CONFIG.PAINT_SIZE_FACTOR * GLOBAL_CONFIG.PAINT_MAP_SIZE) / props.domainX.domain.width+ : GLOBAL_CONFIG.PAINT_SIZE_FACTOR,+ y: props.domainY.domain.type === 'nominal' ? 1 : brushSize,+ yFactor:+ props.domainY.domain.type === 'nominal'+ ? (GLOBAL_CONFIG.PAINT_SIZE_FACTOR * GLOBAL_CONFIG.PAINT_MAP_SIZE) / props.domainY.domain.width+ : GLOBAL_CONFIG.PAINT_SIZE_FACTOR,+ };+ }, [props.domainX, props.domainY, brushSize]);useEffect(() => {setShowCursorPreview(true);@@ -264,20 +276,17 @@ const PainterContent = (props: {};}, [brushSize, brushId]);- const CursorContainer = pixelContainer ? PixelContainer : Container;-return (<div className="flex">- <CursorContainer+ <PixelContainercolor={props.dict[brushId]?.color ?? '#333'}- dia={brushSize}- factor={GLOBAL_CONFIG.PAINT_SIZE_FACTOR}+ cursor={cursor}offsetX={pixelOffset[0]}offsetY={pixelOffset[1]}showPreview={showCursorPreview}><div ref={containerRef} id="painter-container" className="!cursor-none"></div>- </CursorContainer>+ </PixelContainer><div className="flex flex-col space-y-2 pt-10 w-40 flex-shrink-0"><div className="flex space-x-4" aria-label="Tabs"><a@@ -285,7 +294,7 @@ const PainterContent = (props: {(brushId === ERASER ? 'text-gray-500 hover:text-gray-700' : 'bg-indigo-100 text-indigo-700') +' rounded-md px-3 py-2 text-sm font-medium'}- onClick={() => setBrushId(1)}+ onClick={() => setBrushId(2)}>{t('main.tabpanel.settings.paint.palette')}</a>@@ -380,7 +389,7 @@ const PainterContent = (props: {const Painter = ({ dark, themeConfig, themeKey }: { dark?: IDarkMode; themeConfig?: GWGlobalConfig; themeKey?: IThemeKey }) => {const vizStore = useVizStore();- const { showPainterPanel } = vizStore;+ const { showPainterPanel, allFields } = vizStore;const { t } = useTranslation();const compuation = useCompututaion();@@ -389,8 +398,8 @@ const Painter = ({ dark, themeConfig, themeKey }: { dark?: IDarkMode; themeConficonst [dict, setDict] = useState(defaultScheme);const [fieldX, setX] = useState<IViewField>();const [fieldY, setY] = useState<IViewField>();- const [domainX, setDomainX] = useState<[number, number]>([0, 0]);- const [domainY, setDomainY] = useState<[number, number]>([0, 0]);+ const [domainX, setDomainX] = useState<IPaintDimension>();+ const [domainY, setDomainY] = useState<IPaintDimension>();useEffect(() => {if (showPainterPanel) {@@ -398,44 +407,78 @@ const Painter = ({ dark, themeConfig, themeKey }: { dark?: IDarkMode; themeConfi(async () => {const { paintInfo, allFields } = vizStore;if (paintInfo) {- const { x, y } = paintInfo;- const xf = allFields.find((a) => a.fid === x);- const yf = allFields.find((a) => a.fid === y);- if ('map' in paintInfo) {- mapRef.current = await decompressMap(paintInfo.map);- setDict(paintInfo.dict);- setDomainX(paintInfo.domainX);- setDomainY(paintInfo.domainY);- } else {- mapRef.current = emptyMap(GLOBAL_CONFIG.PAINT_MAP_SIZE);- const xs = getRange(compuation, paintInfo.x);- const ys = getRange(compuation, paintInfo.y);+ if (paintInfo.type === 'exist') {+ mapRef.current = await decompressMap(paintInfo.item.facets[0].map);+ const x = paintInfo.item.facets[0].dimensions.at(-1)?.fid;+ const y = paintInfo.item.facets[0].dimensions.at(-2)?.fid;+ const xf = allFields.find((a) => a.fid === x);+ const yf = allFields.find((a) => a.fid === y);+ unstable_batchedUpdates(() => {+ setDict(paintInfo.item.dict);+ setDomainX(paintInfo.item.facets[0].dimensions.at(-1));+ setDomainY(paintInfo.item.facets[0].dimensions.at(-2));+ setX(xf);+ setY(yf);+ setLoading(false);+ });+ } else if (paintInfo.type === 'new') {+ const getDomain = async (f: IViewField): Promise<IPaintDimension> => {+ if (f.semanticType === 'quantitative') {+ const res = await fieldStat(compuation, f, { range: true, values: false, valuesMeta: false }, allFields);+ return {+ domain: {+ type: 'quantitative',+ value: res.range,+ width: GLOBAL_CONFIG.PAINT_MAP_SIZE,+ },+ fid: f.fid,+ };+ } else {+ const res = await fieldStat(compuation, f, { range: false, values: true, valuesMeta: false }, allFields);+ const value = res.values.map((x) => x.value);+ return {+ domain: {+ type: 'nominal',+ value,+ width: value.length,+ },+ fid: f.fid,+ };+ }+ };+ let xs: Promise<IPaintDimension>;+ let ys: Promise<IPaintDimension>;+ xs = getDomain(paintInfo.x);+ ys = getDomain(paintInfo.y);const domainX = await xs;const domainY = await ys;- setDict(defaultScheme);- setDomainX(domainX);- setDomainY(domainY);+ mapRef.current = createMap([domainY, domainX]);+ unstable_batchedUpdates(() => {+ setDict(defaultScheme);+ setDomainX(domainX);+ setDomainY(domainY);+ setX(paintInfo.x);+ setY(paintInfo.y);+ setLoading(false);+ });}- setX(xf);- setY(yf);- setLoading(false);}})();}}, [showPainterPanel, vizStore, compuation]);const saveMap = async () => {- if (fieldX && fieldY && mapRef.current) {+ if (domainX && domainY && mapRef.current) {vizStore.updatePaint({dict,- domainX,- domainY,- map: await compressMap(mapRef.current),- x: fieldX.fid,- y: fieldY.fid,- usedColor: [...new Set(mapRef.current).values()],- mapwidth: GLOBAL_CONFIG.PAINT_MAP_SIZE,+ usedColor: [...new Set(mapRef.current).values()].map(x => x || 1),+ facets: [+ {+ map: await compressMap(mapRef.current),+ dimensions: [domainY, domainX],+ },+ ],},t('constant.paint_key'));@@ -476,8 +519,9 @@ const Painter = ({ dark, themeConfig, themeKey }: { dark?: IDarkMode; themeConfi}}x={fieldX!}y={fieldY!}- domainX={domainX}- domainY={domainY}+ allFields={allFields}+ domainX={domainX!}+ domainY={domainY!}dict={dict}onChangeDict={setDict}mapRef={mapRef}diff --git a/packages/graphic-walker/src/interfaces.ts b/packages/graphic-walker/src/interfaces.tsindex 10756b93..bd9f7f02 100644--- a/packages/graphic-walker/src/interfaces.ts+++ b/packages/graphic-walker/src/interfaces.ts@@ -78,6 +78,7 @@ export interface IFieldStats {range: [number, number];}+/** @deprecated */export interface IPaintMap {/** fid of x */x: string;@@ -94,6 +95,42 @@ export interface IPaintMap {usedColor: number[];}+export interface IPaintDimension {+ fid: string;+ domain:+ | {+ type: 'nominal';+ value: any[];+ // = value.length+ width: number;+ }+ | {+ type: 'quantitative';+ value: [number, number];+ width: number;+ };+ // TODO: impement the temporal support+ // | {+ // type: 'temporal';+ // value: [number, number];+ // width: number;+ // offset?: number;+ // format?: string;+ // };+}++export interface IPaintMapFacet {+ dimensions: IPaintDimension[];+ /** compressed array of UInt8[dimensions.reduce((x,d) => x * d.domain.width, 1)] */+ map: string;+}++export interface IPaintMapV2 {+ facets: IPaintMapFacet[];+ dict: Record<number, { name: string; color: string }>;+ usedColor: number[];+}+export type IExpParameter =| {type: 'field';@@ -126,6 +163,10 @@ export type IExpParameter =| {type: 'sql';value: string;+ }+ | {+ type: 'newmap';+ value: IPaintMapV2;};export interface IExpression {diff --git a/packages/graphic-walker/src/lib/execExp.ts b/packages/graphic-walker/src/lib/execExp.tsindex abc845c2..d0b13b02 100644--- a/packages/graphic-walker/src/lib/execExp.ts+++ b/packages/graphic-walker/src/lib/execExp.ts@@ -1,7 +1,7 @@-import { IExpParameter, IExpression, IPaintMap, IRow } from '../interfaces';+import { IExpParameter, IExpression, IPaintMap, IPaintMapV2, IRow } from '../interfaces';import dateTimeDrill from './op/dateTimeDrill';import dateTimeFeature from './op/dateTimeFeature';-import { calcMap } from './paint';+import { calcMap, calcMapV2 } from './paint';import { expr } from './sql';export interface IDataFrame {@@ -140,12 +140,20 @@ function one(resKey: string, params: IExpParameter[], data: IDataFrame): IDataFr}async function paint(resKey: string, params: IExpParameter[], data: IDataFrame): Promise<IDataFrame> {- const param = params.find((x) => x.type === 'map');- if (!param) return data;- const map: IPaintMap = param.value;+ const param = params.find((x) => x.type === 'newmap');+ if (!param) {+ const oldParam = params.find((x) => x.type === 'map');+ if (!oldParam) return data;+ const map: IPaintMap = oldParam.value;+ return {+ ...data,+ [resKey]: await calcMap(data[map.x], data[map.y], map),+ };+ }+ const map: IPaintMapV2 = param.value;return {...data,- [resKey]: await calcMap(data[map.x], data[map.y], map),+ [resKey]: await calcMapV2(dataframe2Dataset(data), map),};}diff --git a/packages/graphic-walker/src/lib/paint.ts b/packages/graphic-walker/src/lib/paint.tsindex b087535c..f348f46e 100644--- a/packages/graphic-walker/src/lib/paint.ts+++ b/packages/graphic-walker/src/lib/paint.ts@@ -1,4 +1,4 @@-import { IPaintMap } from '../interfaces';+import { IPaintDimension, IPaintMap, IPaintMapV2, IRow } from '../interfaces';const circles = new Map<number, [number, number][]>();@@ -42,8 +42,26 @@ export function getCircleFrom([x0, y0]: [number, number], dia: number, mapWidth:* @param mapWidth Width of the Map (points outside map will be croped)* @returns Indexes of circle points in the map.*/-export function indexesFrom(center: [number, number], dia: number, mapWidth: number) {- return getCircleFrom(center, dia, mapWidth).map(([x, y]) => index(x, y, mapWidth));+export function indexesFrom(center: [number, number], dia: number, dimensions: [IPaintDimension, IPaintDimension]) {+ const [y, x] = dimensions;+ const index = indexV2(dimensions);+ if (y.domain.type === 'quantitative' && x.domain.type === 'quantitative') {+ const mapWidth = y.domain.width;+ return getCircleFrom(center, dia, mapWidth).map(([x, y]) => index([y, x]));+ }+ const getI = (c: number, domain: IPaintDimension): number[] => {+ if (domain.domain.type === 'nominal') {+ return [c];+ }+ const half = (dia - (dia % 2)) / 2;+ return new Array(dia)+ .fill(0)+ .map((_, i) => i + c - half)+ .filter((x) => x >= 0 && x < domain.domain.width);+ };+ return getI(center[0], x)+ .flatMap((x) => getI(center[1], y).map((y) => [x, y] as const))+ .map(([x, y]) => index([y, x]));}function index(x: number, y: number, mapWidth: number) {@@ -79,8 +97,8 @@ export async function decompressMap(base64: string) {return new Uint8Array(result);}-export function emptyMap(mapWidth: number) {- return new Uint8Array(mapWidth * mapWidth);+export function createMap(dimensions: IPaintDimension[]) {+ return new Uint8Array(dimensions.reduce((x, d) => x * d.domain.width, 1));}/**@@ -117,7 +135,7 @@ export function calcIndexs(dataX: number[], dataY: number[], domainX: [number, n* @param dataX data of item in X axis.* @param dataY data of item in Y axis.* @param paintMap the PaintMap to use.- * @returns+ * @returns*/export async function calcMap(dataX: number[], dataY: number[], paintMap: IPaintMap) {const { dict, domainX, domainY, map: raw, mapwidth } = paintMap;@@ -126,3 +144,82 @@ export async function calcMap(dataX: number[], dataY: number[], paintMap: IPaintreturn dict[map[x]]?.name;});}++// e.g. [3,3,3] => [9,3,1]+function indexV2(dimensions: IPaintDimension[]) {+ const indexWeights = dimensions+ .map((x) => x.domain.width)+ .reduceRight(([n, ...rest], a) => [a * n, n, ...rest], [1])+ .slice(1);+ return (indexs: number[]) => indexs.map((i, wi) => i * indexWeights[wi]).reduce((x, y) => x + y);+}++/**+ * calc indexes of items in the map.+ * @param dimensions the dimensions of the map+ * @returns mapper for data.+ */+export function calcIndexsV2(dimensions: IPaintDimension[]) {+ const getSingleIndex = dimensions.map(({ domain, fid }) => {+ if (domain.type === 'nominal') {+ const indexDict = new Map(domain.value.map((x, i) => [x, i]));+ return (data: IRow) => indexDict.get(data[fid]) ?? 0;+ }+ if (domain.type === 'quantitative') {+ return (data: IRow) => calcIndex(domain.value, data[fid], domain.width);+ }+ const neverType: never = domain;+ throw new Error(`unsupported domain type ${neverType['type']}`);+ });++ const index = indexV2(dimensions);+ return (data: IRow) => index(getSingleIndex.map((f) => f(data)));+}++export function IPaintMapAdapter(paintMap: IPaintMap): IPaintMapV2 {+ return {+ dict: paintMap.dict,+ usedColor: paintMap.usedColor,+ facets: [+ {+ map: paintMap.map,+ dimensions: [+ {+ fid: paintMap.y,+ domain: {+ type: 'quantitative',+ value: paintMap.domainY,+ width: paintMap.mapwidth,+ },+ },+ {+ fid: paintMap.x,+ domain: {+ type: 'quantitative',+ value: paintMap.domainX,+ width: paintMap.mapwidth,+ },+ },+ ],+ },+ ],+ };+}++/**+ * calc result of items in paintMap.+ * @param data data+ * @param paintMap paintMap+ * @returns result+ */+export async function calcMapV2(data: IRow[], paintMap: IPaintMapV2) {+ const { dict, facets } = paintMap;+ let result = data.map(() => dict[1].name);+ for (const { map: raw, dimensions } of facets) {+ const map = await decompressMap(raw);+ const index = calcIndexsV2(dimensions);+ result = data.map(index).map((x, i) => (map[x] !== 0 ? dict[map[x]]?.name : result[i]));+ }++ return result;+}diff --git a/packages/graphic-walker/src/locales/en-US.json b/packages/graphic-walker/src/locales/en-US.jsonindex 4ac6eb17..ac563d61 100644--- a/packages/graphic-walker/src/locales/en-US.json+++ b/packages/graphic-walker/src/locales/en-US.json@@ -134,7 +134,7 @@"segments": {"vis": "Visualization","data": "Data"- },+ },"feedback": {"vote": "Is the result of Askviz good?","voteup": "Yes",@@ -203,7 +203,11 @@"export_code": "Export Code","geojson": "Geography Configuration","painter": "Open Painter",- "disabled_painter": "Use quantitative fields on XY and disable aggregation to create a paint"+ "disabled_painter": {+ "aggergation": "disable aggregation to create a paint",+ "temporal": "painter doesn't support temporal fields now",+ "count": "drag single field on x and y to create a paint"+ }},"paint": {"palette": "Palette",@@ -336,4 +340,4 @@"log_panel_desc": "Set log config for field","log_panel_number": "Logarithmic base"}-}\ No newline at end of file+}diff --git a/packages/graphic-walker/src/locales/ja-JP.json b/packages/graphic-walker/src/locales/ja-JP.jsonindex ac54d21e..4ce5fe9d 100644--- a/packages/graphic-walker/src/locales/ja-JP.json+++ b/packages/graphic-walker/src/locales/ja-JP.json@@ -197,7 +197,11 @@"export_code": "コードをエクスポート","geojson": "地理情報設定","painter": "データキャンバスを開く",- "disabled_painter": "データキャンバスを作るには数量尺度フィールドをXY軸に設置して集計をオフにするが必要"+ "disabled_painter": {+ "aggergation": "データキャンバスを作るには集計をオフにするが必要",+ "temporal": "時間的フィールドはまたデータキャンバスで使うことができない",+ "count": "データキャンバスを作るにはフィールドをXY軸に設置してください"+ }},"paint": {"palette": "パレット",@@ -330,4 +334,4 @@"log_panel_desc": "フィールドの対数設定を設定する","log_panel_number": "対数の底"}-}\ No newline at end of file+}diff --git a/packages/graphic-walker/src/locales/zh-CN.json b/packages/graphic-walker/src/locales/zh-CN.jsonindex 7ca0caf4..f1f37058 100644--- a/packages/graphic-walker/src/locales/zh-CN.json+++ b/packages/graphic-walker/src/locales/zh-CN.json@@ -203,7 +203,11 @@"export_code": "导出代码","geojson": "地理信息配置","painter": "打开数据绘板",- "disabled_painter": "创建绘制字段需要在XY轴使用数据类型并关闭聚合"+ "disabled_painter": {+ "aggergation": "创建绘制字段需要关闭聚合",+ "temporal": "绘制字段暂不支持时间字段",+ "count": "在x和y轴上分别放置一个字段来创建绘制字段"+ }},"paint": {"palette": "色板",@@ -336,4 +340,4 @@"log_panel_desc": "设置字段的对数配置","log_panel_number": "对数底数"}-}\ No newline at end of file+}diff --git a/packages/graphic-walker/src/models/visSpecHistory.ts b/packages/graphic-walker/src/models/visSpecHistory.tsindex 5c6a7caf..b2c3ef8c 100644--- a/packages/graphic-walker/src/models/visSpecHistory.ts+++ b/packages/graphic-walker/src/models/visSpecHistory.ts@@ -19,6 +19,7 @@ import {IExpression,IFilterField,IField,+ IPaintMapV2,} from '../interfaces';import type { FeatureCollection } from 'geojson';import { createCountField, createVirtualFields } from '../utils';@@ -83,7 +84,7 @@ type PropsMap = {[Methods.changeSemanticType]: [normalKeys, number, ISemanticType];[Methods.setFilterAggregator]: [number, IAggregator | ''];[Methods.addFoldField]: [normalKeys, number, normalKeys, number, string, number | null];- [Methods.upsertPaintField]: [IPaintMap | null, string];+ [Methods.upsertPaintField]: [IPaintMap | IPaintMapV2 | null, string];[Methods.addSQLComputedField]: [string, string, string];[Methods.removeAllField]: [string];[Methods.editAllField]: [string, Partial<IField>];@@ -343,11 +344,14 @@ const actions: {Object.fromEntries(Object.entries(encodings).map(([c, f]) => [c, f.filter((x) => x.fid !== PAINT_FIELD_ID)])) as DraggableFieldState);}- const expression: IExpression = {- op: 'paint',- as: PAINT_FIELD_ID,- params: [{ type: 'map', value: map }],- };+ const expression: IExpression =+ 'facets' in map+ ? { op: 'paint', as: PAINT_FIELD_ID, params: [{ type: 'newmap', value: map }] }+ : {+ op: 'paint',+ as: PAINT_FIELD_ID,+ params: [{ type: 'map', value: map }],+ };const hasErased = map.usedColor.includes(255);return mutPath(data, 'encodings', (enc) => {let hasPaintField = false;@@ -502,7 +506,7 @@ type reducerMiddleware<T> = (item: T, original: T) => T;const diffLinter: reducerMiddleware<IChart> = (item, original) => {const diffs = diffChangedEncodings(original, item);- if (Object.keys(diffs).length === 0) return item;+ if (Object.keys(diffs).length === 0) return item;return mutPath(item, 'encodings', (x) => ({ ...x, ...algebraLint(diffs), ...lintExtraFields(diffs) }));};diff --git a/packages/graphic-walker/src/store/visualSpecStore.ts b/packages/graphic-walker/src/store/visualSpecStore.tsindex a3c4854f..613acbd6 100644--- a/packages/graphic-walker/src/store/visualSpecStore.ts+++ b/packages/graphic-walker/src/store/visualSpecStore.ts@@ -38,6 +38,7 @@ import {ISemanticType,IChartForExport,IPaintMap,+ IPaintMapV2,} from '../interfaces';import { GLOBAL_CONFIG } from '../config';import { COUNT_FIELD_ID, DATE_TIME_DRILL_LEVELS, DATE_TIME_FEATURE_LEVELS, PAINT_FIELD_ID, MEA_KEY_ID, MEA_VAL_ID } from '../constants';@@ -48,6 +49,7 @@ import { encodeFilterRule } from '../utils/filter';import { INestNode } from '../components/pivotTable/inteface';import { getSort, getSortedEncoding } from '../utils';import { getSQLItemAnalyticType, parseSQLExpr } from '../lib/sql';+import { IPaintMapAdapter } from '../lib/paint';const encodingKeys = (Object.keys(emptyEncodings) as (keyof DraggableFieldState)[]).filter((dkey) => !GLOBAL_CONFIG.META_FIELD_KEYS.includes(dkey));export const viewEncodingKeys = (geom: string) => {@@ -245,25 +247,47 @@ export class VizSpecStore {if (existPaintField) {const param: IPaintMap = existPaintField.expression?.params.find((x) => x.type === 'map')?.value;if (param) {- return param;+ return {+ type: 'exist',+ item: IPaintMapAdapter(param),+ } as const;+ }+ const paramV2: IPaintMapV2 = existPaintField.expression?.params.find((x) => x.type === 'newmap')?.value;+ if (paramV2) {+ return {+ type: 'exist',+ item: paramV2,+ } as const;}}if (!this.currentVis.config.defaultAggregated) {const { columns, rows } = this.currentEncodings;if (columns.length !== 1 || rows.length !== 1) {- return null;+ return { type: 'error', key: 'count' }as const;}const col = columns[0];const row = rows[0];- if (col.semanticType != 'quantitative' || row.semanticType != 'quantitative') {- return null;+ // range on temporal need use a temporal Domain, which is not impemented+ if (col.semanticType === 'temporal' || row.semanticType === 'temporal') {+ return { type: 'error', key: 'temporal' }as const;+ }+ if (+ col.aggName === 'expr' ||+ row.aggName === 'expr' ||+ col.fid === MEA_KEY_ID ||+ col.fid === MEA_VAL_ID ||+ row.fid === MEA_KEY_ID ||+ row.fid === MEA_VAL_ID+ ) {+ return { type: 'error', key: 'count' } as const;}return {- x: col.fid,- y: row.fid,- };+ type: 'new',+ x: col,+ y: row,+ } as const;}- return null;+ return { type: 'error', key: 'aggergation' } as const;}private appendFilter(index: number, sourceKey: keyof Omit<DraggableFieldState, 'filters'>, sourceIndex: number) {@@ -618,7 +642,7 @@ export class VizSpecStore {this.visList[this.visIndex] = performers.changeSemanticType(this.visList[this.visIndex], stateKey, index, semanticType);}- updatePaint(paintMap: IPaintMap | null, name: string) {+ updatePaint(paintMap: IPaintMapV2 | null, name: string) {this.visList[this.visIndex] = performers.upsertPaintField(this.visList[this.visIndex], paintMap, name);}diff --git a/packages/graphic-walker/src/utils/workflow.ts b/packages/graphic-walker/src/utils/workflow.tsindex ab159c93..8d1e1c10 100644--- a/packages/graphic-walker/src/utils/workflow.ts+++ b/packages/graphic-walker/src/utils/workflow.ts@@ -12,11 +12,11 @@ import type {IFilterField,IChartForExport,IMutField,+ IPaintMapV2,} from '../interfaces';import { viewEncodingKeys, type VizSpecStore } from '../store/visualSpecStore';import { getFilterMeaAggKey, getMeaAggKey, getSort } from '.';import { MEA_KEY_ID, MEA_VAL_ID } from '../constants';-import { encodeFilterRule } from './filter';import { decodeVisSpec } from '../models/visSpecHistory';import { replaceFid, walkFid } from '../lib/sql';@@ -28,6 +28,11 @@ const walkExpression = (expression: IExpression, each: (field: string) => void):walkExpression(param.value, each);} else if (param.type === 'sql') {walkFid(param.value).forEach(each);+ } else if (param.type === 'map') {+ each(param.value.x);+ each(param.value.y);+ } else if (param.type === 'newmap') {+ param.value.facets.flatMap((x) => x.dimensions).forEach((x) => each(x.fid));}}};@@ -43,7 +48,7 @@ const treeShake = (viewKeys: readonly string[]): { key: string; expression: IExpression }[] => {const usedFields = new Set(viewKeys);- const result = computedFields.filter((f) => usedFields.has(f.key));+ let result = computedFields.filter((f) => usedFields.has(f.key));let currentFields = result.slice();let rest = computedFields.filter((f) => !usedFields.has(f.key));while (currentFields.length && rest.length) {@@ -52,6 +57,8 @@ const treeShake = (walkExpression(f.expression, (field) => dependencies.add(field));}const nextFields = rest.filter((f) => dependencies.has(f.key));+ const deps = computedFields.filter((f) => dependencies.has(f.key));+ result = deps.concat(result.filter((f) => !dependencies.has(f.key)));currentFields = nextFields;rest = rest.filter((f) => !dependencies.has(f.key));}@@ -381,6 +388,25 @@ export const processExpression = (exp: IExpression, allFields: IMutField[]): IExmapwidth: x.value.mapwidth,} as IPaintMap,};+ } else if (x.type === 'newmap') {+ const dict = {+ ...x.value.dict,+ '255': { name: '' },+ };+ return {+ type: 'newmap',+ value: {+ facets: x.value.facets,+ dict: Object.fromEntries(+ x.value.usedColor.map((i) => [+ i,+ {+ name: dict[i].name,+ },+ ])+ ),+ } as IPaintMapV2,+ };} else {return x;}diff --git a/packages/graphic-walker/src/vis/spec/encode.ts b/packages/graphic-walker/src/vis/spec/encode.tsindex 153a18c8..f9f11225 100644--- a/packages/graphic-walker/src/vis/spec/encode.ts+++ b/packages/graphic-walker/src/vis/spec/encode.ts@@ -1,5 +1,5 @@import { DATE_TIME_DRILL_LEVELS } from '../../constants';-import { IPaintMap, IViewField } from '../../interfaces';+import { IPaintMap, IPaintMapV2, IViewField } from '../../interfaces';import { NULL_FIELD } from './field';export interface IEncodeProps {geomType: string;@@ -76,10 +76,10 @@ export function channelEncode(props: IEncodeProps) {encoding[c].type = 'quantitative';}if (props[c].semanticType === 'temporal' && props[c].timeUnit) {- encoding[c].timeUnit = encodeTimeunit(props[c].timeUnit);;+ encoding[c].timeUnit = encodeTimeunit(props[c].timeUnit);}if (c === 'color' && props[c].expression?.op === 'paint') {- const map: IPaintMap = props[c].expression!.params.find((x) => x.type === 'map')!.value;+ const map: IPaintMap = props[c].expression!.params.find((x) => x.type === 'map' || x.type === 'newmap')!.value;const colors = map.usedColor.map((x) => map.dict[x]).filter(Boolean);encoding[c].scale = {domain: colors.map((x) => x.name),diff --git a/packages/graphic-walker/src/visualSettings/index.tsx b/packages/graphic-walker/src/visualSettings/index.tsxindex d23b5277..c0e4672c 100644--- a/packages/graphic-walker/src/visualSettings/index.tsx+++ b/packages/graphic-walker/src/visualSettings/index.tsx@@ -78,6 +78,19 @@ interface IVisualSettings {experimentalFeatures?: IExperimentalFeatures;}+const KanariesIcon = () => (+ <a href="https://docs.kanaries.net" target="_blank">+ <ImageWithFallback+ id="kanaries-logo"+ className="p-1.5 opacity-70 hover:opacity-100"+ src="https://imagedelivery.net/tSvh1MGEu9IgUanmf58srQ/b6bc899f-a129-4c3a-d08f-d406166d0c00/public"+ fallbackSrc={KanariesLogo}+ timeout={1000}+ alt="kanaries documents"+ />+ </a>+)+const VisualSettings: React.FC<IVisualSettings> = ({ rendererHandler, darkModePreference, csvHandler, extra = [], exclude = [], experimentalFeatures }) => {const vizStore = useVizStore();const { config, layout, canUndo, canRedo, limit, paintInfo } = vizStore;@@ -583,9 +596,9 @@ const VisualSettings: React.FC<IVisualSettings> = ({ rendererHandler, darkModePr},{key: 'painter',- label: paintInfo === null ? t('button.disabled_painter') : t('button.painter'),+ label: paintInfo.type === 'error' ? t(`button.disabled_painter.${paintInfo.key}`) : t('button.painter'),icon: PaintBrushIcon,- disabled: paintInfo === null,+ disabled: paintInfo.type === 'error',onClick: () => {vizStore.setShowPainter(true);},@@ -594,19 +607,8 @@ const VisualSettings: React.FC<IVisualSettings> = ({ rendererHandler, darkModePr{key: 'kanaries',label: 'kanaries docs',- icon: () => (- // Kanaries brand info is not allowed to be removed or changed unless you are granted with special permission.- <a href="https://docs.kanaries.net" target="_blank">- <ImageWithFallback- id="kanaries-logo"- className="p-1.5 opacity-70 hover:opacity-100"- src="https://imagedelivery.net/tSvh1MGEu9IgUanmf58srQ/b6bc899f-a129-4c3a-d08f-d406166d0c00/public"- fallbackSrc={KanariesLogo}- timeout={1000}- alt="kanaries documents"- />- </a>- ),+ // Kanaries brand info is not allowed to be removed or changed unless you are granted with special permission.+ icon: KanariesIcon,},].filter(Boolean) as ToolbarItemProps[];@@ -639,7 +641,7 @@ const VisualSettings: React.FC<IVisualSettings> = ({ rendererHandler, darkModePrlimit,showTableSummary,experimentalFeatures,- paintInfo+ paintInfo,]);return (