Skip to content

An open source alternative to Tableau. Embeddable visual analytic

feat: painter support multi facets (#291)

islxyqwec2d16038085d
diff --git a/packages/graphic-walker/src/components/painter/index.tsx b/packages/graphic-walker/src/components/painter/index.tsx
index ad1d3bea..9d1da0cd 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 React, { useEffect, useState, useRef, useMemo, useCallback, DependencyList } from 'react';
import { observer } from 'mobx-react-lite';
import { useCompututaion, useVizStore } from '../../store';
-import { calcIndexsV2, compressMap, createMap, decompressMap, indexesFrom } from '../../lib/paint';
+import { calcIndexesByDimensions, calcPaintMapV2, compressBitMap, createBitMapForMap, decompressBitMap, getCircleIndexes } from '../../lib/paint';
import { fieldStat } from '../../computation';
import { useRenderer } from '../../renderer/hooks';
-import { IDarkMode, IPaintDimension, IThemeKey, IViewField, VegaGlobalConfig } from '../../interfaces';
+import { IDarkMode, IField, IPaintDimension, IPaintMapFacet, ISemanticType, IThemeKey, IViewField, VegaGlobalConfig } from '../../interfaces';
import embed from 'vega-embed';
import Modal from '../modal';
import { PAINT_FIELD_ID } from '../../constants';
@@ -20,6 +20,7 @@ import { GLOBAL_CONFIG } from '../../config';
import { GWGlobalConfig, builtInThemes } from '../../vis/theme';
import { useCurrentMediaTheme } from '../../utils/media';
import { unstable_batchedUpdates } from 'react-dom';
+import { autoMark } from '../../vis/spec/mark';
const MAGIC_PADDING = 5;
const PIXEL_INDEX = '_gw_pixel_index';
@@ -39,6 +40,27 @@ const defaultScheme = Object.fromEntries(scheme.map((color, i) => [i + 1, { name
const emptyField = [];
+function useAsyncMemo<T>(factory: () => Promise<T> | undefined | null, deps: DependencyList, initial?: T) {
+ const [val, setVal] = useState<T | undefined>(initial);
+ const [loading, setLoading] = useState(true);
+ useEffect(() => {
+ let cancel = false;
+ setLoading(true);
+ const promise = factory();
+ if (promise === undefined || promise === null) return;
+ promise.then((val) => {
+ if (!cancel) {
+ setLoading(false);
+ setVal(val);
+ }
+ });
+ return () => {
+ cancel = true;
+ };
+ }, deps);
+ return [val, loading];
+}
+
function selectInteractive(scene: { root: Scene }) {
const selected: (Scene | SceneGroup)[] = [];
let index = 0;
@@ -63,16 +85,32 @@ function selectInteractive(scene: { root: Scene }) {
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;
+function getMarkFor(types: ISemanticType[]) {
+ if (types.every((x) => x === 'quantitative')) {
+ return 'circle';
+ }
+ if (types.find((x) => x === 'quantitative')) {
+ return 'tick';
+ }
+ return 'square';
+}
+
+// TODO: add text: fetch the text channel to show
+const markWhitelist = ['point', 'circle', 'tick'];
+
const PainterContent = (props: {
+ mark: string;
x: IViewField;
y: IViewField;
domainX: IPaintDimension;
domainY: IPaintDimension;
dict: typeof defaultScheme;
+ facets: IPaintMapFacet[];
vegaConfig: VegaGlobalConfig;
onChangeDict: (d: typeof defaultScheme) => void;
- mapRef: React.MutableRefObject<Uint8Array | undefined>;
+ paintMapRef: React.MutableRefObject<Uint8Array | undefined>;
allFields: IViewField[];
+ onReset: () => void;
onDelete: () => void;
onCancel: () => void;
onSave: () => void;
@@ -99,7 +137,7 @@ const PainterContent = (props: {
const [brushId, setBrushId] = useState(2);
brushIdRef.current = brushId;
const containerRef = useRef<HTMLDivElement>(null);
- const { loading, viewData } = useRenderer({
+ const { loading: loadingData, viewData } = useRenderer({
computationFunction: computation,
defaultAggregated: false,
filters: emptyField,
@@ -109,35 +147,36 @@ const PainterContent = (props: {
viewDimensions: emptyField,
viewMeasures: fields,
});
- const indexes = useMemo(() => {
- const mapper = calcIndexsV2([props.domainY, props.domainX]);
- return viewData.map(mapper);
- }, [viewData, props.domainX, props.domainY]);
- const data = useMemo(() => {
+ const indexes = useMemo(() => viewData.map(calcIndexesByDimensions([props.domainY, props.domainX])), [viewData, props.domainX, props.domainY]);
+ const [data, loadingResult] = useAsyncMemo(async () => {
+ const facetResult = await calcPaintMapV2(viewData, { dict: props.dict, facets: props.facets, usedColor: [] });
return viewData.map((x, i) => {
+ const pid = props.paintMapRef.current![indexes[i]];
return {
...x,
- [PAINT_FIELD_ID]: props.dict[props.mapRef.current![indexes[i]] || 1]?.name,
+ [PAINT_FIELD_ID]: pid === 0 ? facetResult[i] : props.dict[pid]?.name,
[PIXEL_INDEX]: indexes[i],
};
});
- }, [indexes, viewData, props.dict]);
+ }, [indexes, viewData, props.dict, props.facets]);
const [pixelOffset, setPixelOffset] = useState([0, 0]);
const resetRef = useRef(() => {});
+ const loading = loadingData || loadingResult;
+
useEffect(() => {
if (!loading && containerRef.current) {
- const xQuan = props.domainX.domain.type === 'quantitative';
- const yQuan = props.domainY.domain.type === 'quantitative';
+ const fallbackMark = getMarkFor([props.domainY.domain.type, props.domainX.domain.type]);
+ const mark = props.mark === 'auto' ? autoMark([props.x.semanticType, props.y.semanticType]) : props.mark;
const colors = Object.entries(props.dict);
const spec: any = {
data: {
name: 'data',
values: data,
},
- mark: { type: xQuan && yQuan ? 'circle' : xQuan || yQuan ? 'tick' : 'square', opacity: 0.66 },
+ mark: { type: markWhitelist.includes(mark) ? mark : fallbackMark, opacity: 0.66 },
encoding: {
x: {
field: props.x.fid,
@@ -186,12 +225,14 @@ const PainterContent = (props: {
//@ts-ignore
const rerender = throttle(() => res.view._renderer._render(scene.root), 100, { trailing: true });
resetRef.current = () => {
- props.mapRef.current! = createMap([props.domainY, props.domainX]);
+ props.onReset();
+ props.paintMapRef.current! = createBitMapForMap([props.domainY, props.domainX]);
const { name, color } = props.dict[1];
interactive.forEach((item) =>
sceneVisit(item, (item) => {
if ('datum' in item) {
- item['fill'] = color;
+ item['fill'] && item['fill'] !== 'transparent' && (item['fill'] = color);
+ item['stroke'] && item['stroke'] !== 'transparent' && (item['stroke'] = color);
item.datum![PAINT_FIELD_ID] = name;
}
})
@@ -210,7 +251,7 @@ const PainterContent = (props: {
}
: props.dict[brushIdRef.current];
if (!targetColor) return;
- const pts = indexesFrom(
+ const pts = getCircleIndexes(
[Math.floor(x / getFactor(props.domainX)), props.domainY.domain.width - 1 - Math.floor(y / getFactor(props.domainY))],
brushSizeRef.current,
[props.domainY, props.domainX]
@@ -218,11 +259,12 @@ const PainterContent = (props: {
let i = 0;
pts.forEach((x) => {
itemsMap.get(x)?.forEach((item) => {
- item['fill'] = targetColor.color;
+ item['fill'] && item['fill'] !== 'transparent' && (item['fill'] = targetColor.color);
+ item['stroke'] && item['stroke'] !== 'transparent' && (item['stroke'] = targetColor.color);
item.datum![PAINT_FIELD_ID] = targetColor.name;
i++;
});
- props.mapRef.current![x] = brushIdRef.current;
+ props.paintMapRef.current![x] = brushIdRef.current;
});
i > 0 && rerender();
};
@@ -242,7 +284,7 @@ const PainterContent = (props: {
res.view.addEventListener('touchmove', handleDraw);
});
}
- }, [loading, data, props.dict, props.vegaConfig, props.domainX, props.domainY]);
+ }, [loading, data, props.dict, props.vegaConfig, props.domainX, props.domainY, props.onReset, props.mark]);
const [showCursorPreview, setShowCursorPreview] = React.useState(false);
@@ -387,98 +429,160 @@ const PainterContent = (props: {
);
};
+function isZeroscaled([min, max]: [number, number]) {
+ return (min < 0 && max > 0) || min === 0 || max === 0;
+}
+
+function isDomainZeroscaledAs(domain: IPaintDimension['domain'] | undefined, exceptedZeroscale: boolean) {
+ if (!domain) return false;
+ if (domain.type === 'nominal') return true;
+ return isZeroscaled(domain.value) === exceptedZeroscale;
+}
+
+function toZeroscaled([min, max]: [number, number]): [number, number] {
+ if (min > 0) {
+ return [0, max];
+ }
+ if (max < 0) {
+ return [min, 0];
+ }
+ return [min, max];
+}
+
const Painter = ({ dark, themeConfig, themeKey }: { dark?: IDarkMode; themeConfig?: GWGlobalConfig; themeKey?: IThemeKey }) => {
const vizStore = useVizStore();
- const { showPainterPanel, allFields } = vizStore;
+ const { showPainterPanel, allFields, layout, config } = vizStore;
+ const { geoms } = config;
+ const { zeroScale } = layout;
const { t } = useTranslation();
const compuation = useCompututaion();
const [loading, setLoading] = useState(true);
- const mapRef = useRef<Uint8Array>();
+ const paintMapRef = useRef<Uint8Array>();
const [dict, setDict] = useState(defaultScheme);
const [fieldX, setX] = useState<IViewField>();
const [fieldY, setY] = useState<IViewField>();
const [domainX, setDomainX] = useState<IPaintDimension>();
const [domainY, setDomainY] = useState<IPaintDimension>();
+ const [facets, setFacets] = useState<IPaintMapFacet[]>([]);
useEffect(() => {
if (showPainterPanel) {
setLoading(true);
(async () => {
const { paintInfo, allFields } = vizStore;
+ const getNewMap = async (paintInfo: { x: IViewField; y: IViewField }) => {
+ 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: zeroScale ? toZeroscaled(res.range) : 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,
+ };
+ }
+ };
+ const [domainX, domainY] = await Promise.all([getDomain(paintInfo.x), getDomain(paintInfo.y)]);
+ return {
+ x: paintInfo.x,
+ y: paintInfo.y,
+ domainX,
+ domainY,
+ map: createBitMapForMap([domainY, domainX]),
+ };
+ };
if (paintInfo) {
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,
- };
+ const lastFacet = paintInfo.item.facets.at(-1)!;
+ if (
+ paintInfo.new.type === 'new' &&
+ (lastFacet.dimensions[0]?.fid !== paintInfo.new.y.fid ||
+ lastFacet.dimensions[1]?.fid !== paintInfo.new.x.fid ||
+ !isDomainZeroscaledAs(lastFacet.dimensions[0]?.domain, zeroScale) ||
+ !isDomainZeroscaledAs(lastFacet.dimensions[1]?.domain, zeroScale))
+ ) {
+ const { domainX, domainY, map } = await getNewMap(paintInfo.new);
+ // adapter for old single facet
+ if (paintInfo.item.facets[0] && !paintInfo.item.facets[0].usedColor) {
+ paintInfo.item.facets[0].usedColor = paintInfo.item.usedColor;
}
- };
- let xs: Promise<IPaintDimension>;
- let ys: Promise<IPaintDimension>;
- xs = getDomain(paintInfo.x);
- ys = getDomain(paintInfo.y);
- const domainX = await xs;
- const domainY = await ys;
- mapRef.current = createMap([domainY, domainX]);
+ paintMapRef.current = map;
+ unstable_batchedUpdates(() => {
+ setDict(paintInfo.item.dict);
+ setDomainX(domainX);
+ setDomainY(domainY);
+ setFacets(paintInfo.item.facets);
+ setX(paintInfo.new.x);
+ setY(paintInfo.new.y);
+ setLoading(false);
+ });
+ } else {
+ paintMapRef.current = await decompressBitMap(lastFacet.map);
+ const x = lastFacet.dimensions.at(-1)?.fid;
+ const y = lastFacet.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(lastFacet.dimensions.at(-1));
+ setDomainY(lastFacet.dimensions.at(-2));
+ setFacets(paintInfo.item.facets.slice(0, -1));
+ setX(xf);
+ setY(yf);
+ setLoading(false);
+ });
+ }
+ } else if (paintInfo.type === 'new') {
+ const { domainX, domainY, map } = await getNewMap(paintInfo);
+ paintMapRef.current = map;
unstable_batchedUpdates(() => {
setDict(defaultScheme);
setDomainX(domainX);
setDomainY(domainY);
setX(paintInfo.x);
setY(paintInfo.y);
+ setFacets([]);
setLoading(false);
});
}
}
})();
}
- }, [showPainterPanel, vizStore, compuation]);
+ }, [showPainterPanel, vizStore, compuation, zeroScale]);
const saveMap = async () => {
- if (domainX && domainY && mapRef.current) {
+ if (domainX && domainY && paintMapRef.current) {
+ const newFacets = [
+ ...facets,
+ {
+ map: await compressBitMap(paintMapRef.current),
+ dimensions: [domainY, domainX],
+ usedColor: Array.from(new Set(paintMapRef.current)).map((x) => x || 1),
+ },
+ ];
+ // all colors in map
+ const defaultUsedColor = Object.keys(dict)
+ .map((x) => parseInt(x))
+ .concat(ERASER);
vizStore.updatePaint(
{
dict,
- usedColor: [...new Set(mapRef.current).values()].map(x => x || 1),
- facets: [
- {
- map: await compressMap(mapRef.current),
- dimensions: [domainY, domainX],
- },
- ],
+ facets: newFacets,
+ usedColor: Array.from(new Set(newFacets.flatMap((f) => f.usedColor ?? defaultUsedColor))),
},
t('constant.paint_key')
);
@@ -486,6 +590,10 @@ const Painter = ({ dark, themeConfig, themeKey }: { dark?: IDarkMode; themeConfi
vizStore.setShowPainter(false);
};
+ const onReset = useCallback(() => {
+ setFacets([]);
+ }, []);
+
const mediaTheme = useCurrentMediaTheme(dark);
const vegaConfig = useMemo<VegaGlobalConfig>(() => {
@@ -508,6 +616,7 @@ const Painter = ({ dark, themeConfig, themeKey }: { dark?: IDarkMode; themeConfi
<LoadingLayer />
) : (
<PainterContent
+ mark={geoms[0]}
vegaConfig={vegaConfig}
onSave={saveMap}
onDelete={() => {
@@ -519,12 +628,14 @@ const Painter = ({ dark, themeConfig, themeKey }: { dark?: IDarkMode; themeConfi
}}
x={fieldX!}
y={fieldY!}
+ facets={facets}
allFields={allFields}
domainX={domainX!}
domainY={domainY!}
dict={dict}
onChangeDict={setDict}
- mapRef={mapRef}
+ paintMapRef={paintMapRef}
+ onReset={onReset}
/>
)}
</Modal>
diff --git a/packages/graphic-walker/src/interfaces.ts b/packages/graphic-walker/src/interfaces.ts
index d45d3861..e3ab5880 100644
--- a/packages/graphic-walker/src/interfaces.ts
+++ b/packages/graphic-walker/src/interfaces.ts
@@ -88,7 +88,7 @@ export interface IPaintMap {
domainY: [number, number];
/** width */
mapwidth: number;
- /** compressed array of UInt8[mapwidth][mapwidth] */
+ /** a bit map, compressed array of UInt8[mapwidth][mapwidth] */
map: string;
/** map values */
dict: Record<number, { name: string; color: string }>;
@@ -121,8 +121,9 @@ export interface IPaintDimension {
export interface IPaintMapFacet {
dimensions: IPaintDimension[];
- /** compressed array of UInt8[dimensions.reduce((x,d) => x * d.domain.width, 1)] */
+ /** a bit map, compressed array of UInt8[dimensions.reduce((x,d) => x * d.domain.width, 1)] */
map: string;
+ usedColor: number[];
}
export interface IPaintMapV2 {
diff --git a/packages/graphic-walker/src/lib/execExp.ts b/packages/graphic-walker/src/lib/execExp.ts
index d0b13b02..c80a4d10 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, IPaintMapV2, IRow } from '../interfaces';
import dateTimeDrill from './op/dateTimeDrill';
import dateTimeFeature from './op/dateTimeFeature';
-import { calcMap, calcMapV2 } from './paint';
+import { calcPaintMap, calcPaintMapV2 } from './paint';
import { expr } from './sql';
export interface IDataFrame {
@@ -147,13 +147,13 @@ async function paint(resKey: string, params: IExpParameter[], data: IDataFrame):
const map: IPaintMap = oldParam.value;
return {
...data,
- [resKey]: await calcMap(data[map.x], data[map.y], map),
+ [resKey]: await calcPaintMap(data[map.x], data[map.y], map),
};
}
const map: IPaintMapV2 = param.value;
return {
...data,
- [resKey]: await calcMapV2(dataframe2Dataset(data), map),
+ [resKey]: await calcPaintMapV2(dataframe2Dataset(data), map),
};
}
diff --git a/packages/graphic-walker/src/lib/paint.ts b/packages/graphic-walker/src/lib/paint.ts
index f348f46e..91aa15a1 100644
--- a/packages/graphic-walker/src/lib/paint.ts
+++ b/packages/graphic-walker/src/lib/paint.ts
@@ -42,9 +42,9 @@ 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, dimensions: [IPaintDimension, IPaintDimension]) {
+export function getCircleIndexes(center: [number, number], dia: number, dimensions: [IPaintDimension, IPaintDimension]) {
const [y, x] = dimensions;
- const index = indexV2(dimensions);
+ const index = indexByDimensions(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]));
@@ -80,7 +80,7 @@ async function bufferToBase64(buffer: Uint8Array | ArrayBuffer): Promise<string>
* @param arr Uint8Array to be compressed.
* @returns Promise of the compressed data in base64-string.
*/
-export async function compressMap(arr: Uint8Array) {
+export async function compressBitMap(arr: Uint8Array) {
const stream = new Response(arr).body!.pipeThrough(new CompressionStream('deflate-raw'));
const result = await new Response(stream).arrayBuffer();
return bufferToBase64(result);
@@ -91,13 +91,13 @@ export async function compressMap(arr: Uint8Array) {
* @param base64 base64-string to be decompressed.
* @returns Promise of the decompressed data.
*/
-export async function decompressMap(base64: string) {
+export async function decompressBitMap(base64: string) {
const stream = await fetch('data:application/octet-stream;base64,' + base64).then((res) => res.body!.pipeThrough(new DecompressionStream('deflate-raw')));
const result = await new Response(stream).arrayBuffer();
return new Uint8Array(result);
}
-export function createMap(dimensions: IPaintDimension[]) {
+export function createBitMapForMap(dimensions: IPaintDimension[]) {
return new Uint8Array(dimensions.reduce((x, d) => x * d.domain.width, 1));
}
@@ -108,7 +108,7 @@ export function createMap(dimensions: IPaintDimension[]) {
* @param mapWidth width of the map.
* @returns index of the item in the map.
*/
-export function calcIndex(domain: [number, number], item: number, mapWidth: number) {
+export function calcIndexInPaintMap(domain: [number, number], item: number, mapWidth: number) {
if (item >= domain[1]) return mapWidth - 1;
if (item <= domain[0]) return 0;
return Math.floor((mapWidth * (item - domain[0])) / (domain[1] - domain[0]));
@@ -123,10 +123,10 @@ export function calcIndex(domain: [number, number], item: number, mapWidth: numb
* @param mapWidth width of the map.
* @returns index of items in the map.
*/
-export function calcIndexs(dataX: number[], dataY: number[], domainX: [number, number], domainY: [number, number], mapWidth: number) {
+export function calcIndexesInPaintMap(dataX: number[], dataY: number[], domainX: [number, number], domainY: [number, number], mapWidth: number) {
return dataX.map((x, i) => {
const y = dataY[i];
- return index(calcIndex(domainX, x, mapWidth), calcIndex(domainY, y, mapWidth), mapWidth);
+ return index(calcIndexInPaintMap(domainX, x, mapWidth), calcIndexInPaintMap(domainY, y, mapWidth), mapWidth);
});
}
@@ -137,21 +137,21 @@ export function calcIndexs(dataX: number[], dataY: number[], domainX: [number, n
* @param paintMap the PaintMap to use.
* @returns
*/
-export async function calcMap(dataX: number[], dataY: number[], paintMap: IPaintMap) {
+export async function calcPaintMap(dataX: number[], dataY: number[], paintMap: IPaintMap) {
const { dict, domainX, domainY, map: raw, mapwidth } = paintMap;
- const map = await decompressMap(raw);
- return calcIndexs(dataX, dataY, domainX, domainY, mapwidth).map((x) => {
+ const map = await decompressBitMap(raw);
+ return calcIndexesInPaintMap(dataX, dataY, domainX, domainY, mapwidth).map((x) => {
return dict[map[x]]?.name;
});
}
// e.g. [3,3,3] => [9,3,1]
-function indexV2(dimensions: IPaintDimension[]) {
+function indexByDimensions(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);
+ return (indexes: number[]) => indexes.map((i, wi) => i * indexWeights[wi]).reduce((x, y) => x + y);
}
/**
@@ -159,20 +159,20 @@ function indexV2(dimensions: IPaintDimension[]) {
* @param dimensions the dimensions of the map
* @returns mapper for data.
*/
-export function calcIndexsV2(dimensions: IPaintDimension[]) {
+export function calcIndexesByDimensions(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);
+ return (data: IRow) => calcIndexInPaintMap(domain.value, data[fid], domain.width);
}
const neverType: never = domain;
throw new Error(`unsupported domain type ${neverType['type']}`);
});
- const index = indexV2(dimensions);
+ const index = indexByDimensions(dimensions);
return (data: IRow) => index(getSingleIndex.map((f) => f(data)));
}
@@ -183,6 +183,7 @@ export function IPaintMapAdapter(paintMap: IPaintMap): IPaintMapV2 {
facets: [
{
map: paintMap.map,
+ usedColor: paintMap.usedColor,
dimensions: [
{
fid: paintMap.y,
@@ -212,12 +213,12 @@ export function IPaintMapAdapter(paintMap: IPaintMap): IPaintMapV2 {
* @param paintMap paintMap
* @returns result
*/
-export async function calcMapV2(data: IRow[], paintMap: IPaintMapV2) {
+export async function calcPaintMapV2(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);
+ const map = await decompressBitMap(raw);
+ const index = calcIndexesByDimensions(dimensions);
result = data.map(index).map((x, i) => (map[x] !== 0 ? dict[map[x]]?.name : result[i]));
}
diff --git a/packages/graphic-walker/src/store/visualSpecStore.ts b/packages/graphic-walker/src/store/visualSpecStore.ts
index 613acbd6..e7349106 100644
--- a/packages/graphic-walker/src/store/visualSpecStore.ts
+++ b/packages/graphic-walker/src/store/visualSpecStore.ts
@@ -242,34 +242,17 @@ export class VizSpecStore {
return viz.cursor !== viz.timeline.length;
}
- get paintInfo() {
- const existPaintField = this.currentEncodings.dimensions.find((x) => x.fid === PAINT_FIELD_ID);
- if (existPaintField) {
- const param: IPaintMap = existPaintField.expression?.params.find((x) => x.type === 'map')?.value;
- if (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;
- }
- }
+ paintFields() {
if (!this.currentVis.config.defaultAggregated) {
const { columns, rows } = this.currentEncodings;
if (columns.length !== 1 || rows.length !== 1) {
- return { type: 'error', key: 'count' }as const;
+ return { type: 'error', key: 'count' } as const;
}
const col = columns[0];
const row = rows[0];
// 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;
+ return { type: 'error', key: 'temporal' } as const;
}
if (
col.aggName === 'expr' ||
@@ -290,6 +273,29 @@ export class VizSpecStore {
return { type: 'error', key: 'aggergation' } as const;
}
+ get paintInfo() {
+ const existPaintField = this.currentEncodings.dimensions.find((x) => x.fid === PAINT_FIELD_ID);
+ if (existPaintField) {
+ const param: IPaintMap = existPaintField.expression?.params.find((x) => x.type === 'map')?.value;
+ if (param) {
+ return {
+ type: 'exist',
+ item: IPaintMapAdapter(param),
+ new: this.paintFields(),
+ } as const;
+ }
+ const paramV2: IPaintMapV2 = existPaintField.expression?.params.find((x) => x.type === 'newmap')?.value;
+ if (paramV2) {
+ return {
+ type: 'exist',
+ item: paramV2,
+ new: this.paintFields(),
+ } as const;
+ }
+ }
+ return this.paintFields();
+ }
+
private appendFilter(index: number, sourceKey: keyof Omit<DraggableFieldState, 'filters'>, sourceIndex: number) {
const oriF = this.currentEncodings[sourceKey][sourceIndex];
if (oriF.fid === MEA_KEY_ID || oriF.fid === MEA_VAL_ID || oriF.fid === COUNT_FIELD_ID || oriF.aggName === 'expr') {
diff --git a/packages/graphic-walker/src/utils/workflow.ts b/packages/graphic-walker/src/utils/workflow.ts
index 1817205d..5d248526 100644
--- a/packages/graphic-walker/src/utils/workflow.ts
+++ b/packages/graphic-walker/src/utils/workflow.ts
@@ -371,7 +371,7 @@ export const processExpression = (exp: IExpression, allFields: IMutField[]): IEx
'255': { name: '' },
};
return {
- type: 'map',
+ type: 'map' as const,
value: {
x: x.value.x,
y: x.value.y,
@@ -397,7 +397,7 @@ export const processExpression = (exp: IExpression, allFields: IMutField[]): IEx
return {
type: 'newmap',
value: {
- facets: x.value.facets,
+ facets: x.value.facets.map(({ dimensions, map }) => ({ dimensions, map })),
dict: Object.fromEntries(
x.value.usedColor.map((i) => [
i,