An open source alternative to Tableau. Embeddable visual analytic
TypeScript bidatadata-analysisdata-miningdata-visualizationedak6skanarieslow-codepivot-tablereacttableautableau-alternativetypescriptvegavega-litevisualization
fix: map mark with color, size, opacity scales (#203)
islxyqwe90c0506cbcac
diff --git a/packages/graphic-walker/src/components/leafletRenderer/ChoroplethRenderer.tsx b/packages/graphic-walker/src/components/leafletRenderer/ChoroplethRenderer.tsxindex 2c0c15f4..58488bd6 100644--- a/packages/graphic-walker/src/components/leafletRenderer/ChoroplethRenderer.tsx+++ b/packages/graphic-walker/src/components/leafletRenderer/ChoroplethRenderer.tsx@@ -1,17 +1,17 @@-import React, { Fragment, forwardRef, useEffect, useImperativeHandle, useMemo, useRef } from "react";-import { CircleMarker, MapContainer, Polygon, Marker, TileLayer, Tooltip, AttributionControl } from "react-leaflet";-import { type Map, divIcon } from "leaflet";-import type { DeepReadonly, IGeoUrl, IRow, IViewField, VegaGlobalConfig } from "../../interfaces";-import type { FeatureCollection, Geometry } from "geojson";-import { getMeaAggKey } from "../../utils";-import { useColorScale, useOpacityScale } from "./encodings";-import { isValidLatLng } from "./POIRenderer";-import { TooltipContent } from "./tooltip";-import { useAppRootContext } from "../appRoot";-import { useGeoJSON } from "../../hooks/service";-import { useTranslation } from "react-i18next";-import { ChangeView } from "./utils";-+import React, { Fragment, forwardRef, useEffect, useImperativeHandle, useMemo, useRef } from 'react';+import { CircleMarker, MapContainer, Polygon, Marker, TileLayer, Tooltip, AttributionControl } from 'react-leaflet';+import { type Map, divIcon } from 'leaflet';+import type { DeepReadonly, IChannelScales, IGeoUrl, IRow, IViewField, VegaGlobalConfig } from '../../interfaces';+import type { FeatureCollection, Geometry } from 'geojson';+import { getMeaAggKey } from '../../utils';+import { useColorScale, useOpacityScale } from './encodings';+import { isValidLatLng } from './POIRenderer';+import { TooltipContent } from './tooltip';+import { useAppRootContext } from '../appRoot';+import { useGeoJSON } from '../../hooks/service';+import { useTranslation } from 'react-i18next';+import { ChangeView } from './utils';+import ColorPanel from './color';export interface IChoroplethRendererProps {name?: string;@@ -28,6 +28,7 @@ export interface IChoroplethRendererProps {details: readonly DeepReadonly<IViewField>[];vegaConfig: VegaGlobalConfig;scaleIncludeUnmatchedChoropleth: boolean;+ channelScales: IChannelScales;}export interface IChoroplethRendererRef {}@@ -36,7 +37,7 @@ const resolveCoords = (featureGeom: Geometry): [lat: number, lng: number][][] =>switch (featureGeom.type) {case 'Polygon': {const coords = featureGeom.coordinates[0];- return [coords.map<[lat: number, lng: number]>(c => [c[1], c[0]])];+ return [coords.map<[lat: number, lng: number]>((c) => [c[1], c[0]])];}case 'Point': {const coords = featureGeom.coordinates;@@ -48,19 +49,19 @@ const resolveCoords = (featureGeom: Geometry): [lat: number, lng: number][][] =>}case 'LineString': {const coords = featureGeom.coordinates;- return [coords.map<[lat: number, lng: number]>(c => [c[1], c[0]])];+ return [coords.map<[lat: number, lng: number]>((c) => [c[1], c[0]])];}case 'MultiLineString': {const coords = featureGeom.coordinates;- return coords.map<[lat: number, lng: number][]>(c => c.map<[lat: number, lng: number]>(c => [c[1], c[0]]));+ return coords.map<[lat: number, lng: number][]>((c) => c.map<[lat: number, lng: number]>((c) => [c[1], c[0]]));}case 'MultiPoint': {const coords = featureGeom.coordinates;- return [coords.map<[lat: number, lng: number]>(c => [c[1], c[0]])];+ return [coords.map<[lat: number, lng: number]>((c) => [c[1], c[0]])];}case 'MultiPolygon': {const coords = featureGeom.coordinates;- return coords.map<[lat: number, lng: number][]>(c => c[0].map<[lat: number, lng: number]>(c => [c[1], c[0]]));+ return coords.map<[lat: number, lng: number][]>((c) => c[0].map<[lat: number, lng: number]>((c) => [c[1], c[0]]));}default: {return [];@@ -91,17 +92,33 @@ const resolveCenter = (coordinates: [lat: number, lng: number][]): [lng: number,return centroid;};-const ChoroplethRenderer = forwardRef<IChoroplethRendererRef, IChoroplethRendererProps>(function ChoroplethRenderer (props, ref) {- const { name, data, allFields, features: localFeatures, featuresUrl, geoKey, defaultAggregated, geoId, color, opacity, text, details, vegaConfig, scaleIncludeUnmatchedChoropleth } = props;+const ChoroplethRenderer = forwardRef<IChoroplethRendererRef, IChoroplethRendererProps>(function ChoroplethRenderer(props, ref) {+ const {+ name,+ data,+ allFields,+ features: localFeatures,+ featuresUrl,+ geoKey,+ defaultAggregated,+ geoId,+ color,+ opacity,+ text,+ details,+ vegaConfig,+ scaleIncludeUnmatchedChoropleth,+ channelScales,+ } = props;useImperativeHandle(ref, () => ({}));- const features = useGeoJSON(localFeatures, featuresUrl)+ const features = useGeoJSON(localFeatures, featuresUrl);const { t } = useTranslation('translation');const geoIndices = useMemo(() => {if (geoId) {- return data.map(row => row[geoId.fid]);+ return data.map((row) => row[geoId.fid]);}return [];}, [geoId, data]);@@ -110,7 +127,7 @@ const ChoroplethRenderer = forwardRef<IChoroplethRendererRef, IChoroplethRendereif (geoIndices.length && geoKey && features) {const indices: number[] = [];const shapes = geoIndices.map((id, i) => {- const feature = id ? features.features.find(f => f.properties?.[geoKey] === id) : undefined;+ const feature = id ? features.features.find((f) => f.properties?.[geoKey] === id) : undefined;if (feature) {indices.push(i);}@@ -123,16 +140,18 @@ const ChoroplethRenderer = forwardRef<IChoroplethRendererRef, IChoroplethRendereuseEffect(() => {if (geoShapes.length > 0) {- const notMatched = geoShapes.filter(f => !f);+ const notMatched = geoShapes.filter((f) => !f);if (notMatched.length) {- console.warn(`Failed to render ${notMatched.length.toLocaleString()} items of ${data.length.toLocaleString()} rows due to missing geojson feature.`);+ console.warn(+ `Failed to render ${notMatched.length.toLocaleString()} items of ${data.length.toLocaleString()} rows due to missing geojson feature.`+ );}}}, [geoShapes]);const lngLat = useMemo<[lat: number, lng: number][][][]>(() => {if (geoShapes.length > 0) {- return geoShapes.map<[lat: number, lng: number][][]>(feature => {+ return geoShapes.map<[lat: number, lng: number][][]>((feature) => {if (feature) {return resolveCoords(feature.geometry);}@@ -145,41 +164,51 @@ const ChoroplethRenderer = forwardRef<IChoroplethRendererRef, IChoroplethRendereconst [bounds, center] = useMemo<[bounds: [[n: number, w: number], [s: number, e: number]], center: [lng: number, lat: number]]>(() => {const allLngLat = lngLat.flat(2);if (allLngLat.length > 0) {- const [bounds, coords] = allLngLat.reduce<[bounds: [[w: number, n: number], [e: number, s: number]], center: [lat: number, lng: number]]>(([bounds, acc], [lat, lng]) => {- if (lat < bounds[0][0]) {- bounds[0][0] = lat;- }- if (lat > bounds[1][0]) {- bounds[1][0] = lat;- }- if (lng < bounds[0][1]) {- bounds[0][1] = lng;- }- if (lng > bounds[1][1]) {- bounds[1][1] = lng;- }- return [bounds, [acc[0] + lng, acc[1] + lat]];- }, [[[...allLngLat[0]] ,[...allLngLat[0]]], [0, 0]]);+ const [bounds, coords] = allLngLat.reduce<[bounds: [[w: number, n: number], [e: number, s: number]], center: [lat: number, lng: number]]>(+ ([bounds, acc], [lat, lng]) => {+ if (lat < bounds[0][0]) {+ bounds[0][0] = lat;+ }+ if (lat > bounds[1][0]) {+ bounds[1][0] = lat;+ }+ if (lng < bounds[0][1]) {+ bounds[0][1] = lng;+ }+ if (lng > bounds[1][1]) {+ bounds[1][1] = lng;+ }+ return [bounds, [acc[0] + lng, acc[1] + lat]];+ },+ [+ [[...allLngLat[0]], [...allLngLat[0]]],+ [0, 0],+ ]+ );return [bounds, [coords[0] / lngLat.length, coords[1] / lngLat.length] as [number, number]];}-- return [[[-180, -90], [180, 90]], [0, 0]];++ return [+ [+ [-180, -90],+ [180, 90],+ ],+ [0, 0],+ ];}, [lngLat]);const distribution = useMemo(() => {if (scaleIncludeUnmatchedChoropleth) {return data;}- return indices.map(i => data[i]);+ return indices.map((i) => data[i]);}, [data, indices, scaleIncludeUnmatchedChoropleth]);- const opacityScale = useOpacityScale(distribution, opacity, defaultAggregated);- const colorScale = useColorScale(distribution, color, defaultAggregated, vegaConfig);+ const opacityScale = useOpacityScale(distribution, opacity, defaultAggregated, channelScales);+ const { mapper: colorScale, display: colorDisplay } = useColorScale(distribution, color, defaultAggregated, vegaConfig);const tooltipFields = useMemo(() => {- return details.concat(- [color!, opacity!].filter(Boolean)- ).map(f => ({+ return details.concat([color!, opacity!].filter(Boolean)).map((f) => ({...f,key: defaultAggregated && f.analyticType === 'measure' && f.aggName ? getMeaAggKey(f.fid, f.aggName) : f.fid,}));@@ -198,7 +227,7 @@ const ChoroplethRenderer = forwardRef<IChoroplethRendererRef, IChoroplethRendere};}});-+const appRef = useAppRootContext();useEffect(() => {@@ -210,14 +239,14 @@ const ChoroplethRenderer = forwardRef<IChoroplethRendererRef, IChoroplethRenderenCols: 0,nRows: 0,charts: [],- container: () => mapRef.current?.getContainer() as HTMLDivElement ?? null,- chartType: 'map'- })+ container: () => (mapRef.current?.getContainer() as HTMLDivElement) ?? null,+ chartType: 'map',+ });}}, []);if (!features && (localFeatures || featuresUrl)) {- return <div className="flex items-center justify-center w-full h-full">{t('main.tabpanel.settings.geography_settings.loading')}</div>+ return <div className="flex items-center justify-center w-full h-full">{t('main.tabpanel.settings.geography_settings.loading')}</div>;}return (@@ -228,93 +257,84 @@ const ChoroplethRenderer = forwardRef<IChoroplethRendererRef, IChoroplethRendereurl="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"/><AttributionControl prefix="Leaflet" />- {lngLat.length > 0 && data.map((row, i) => {- const coords = lngLat[i];- const opacity = opacityScale(row);- const color = colorScale(row);- return (- <Fragment key={`${i}-${opacity}-${color}`}>- {coords.map((coord, j) => {- if (coord.length === 0) {- return null;- }- if (coord.length === 1) {+ {lngLat.length > 0 &&+ data.map((row, i) => {+ const coords = lngLat[i];+ const opacity = opacityScale(row);+ const color = colorScale(row);+ return (+ <Fragment key={`${i}-${opacity}-${color}`}>+ {coords.map((coord, j) => {+ if (coord.length === 0) {+ return null;+ }+ if (coord.length === 1) {+ return (+ <CircleMarker+ key={j}+ center={coord[0]}+ radius={3}+ opacity={0.8}+ fillOpacity={opacity}+ fillColor={color}+ color="#0004"+ weight={1}+ stroke+ fill+ >+ {tooltipFields.length > 0 && (+ <Tooltip>+ <header>{data[i][geoId.fid]}</header>+ {tooltipFields.map((f, j) => (+ <TooltipContent key={j} allFields={allFields} vegaConfig={vegaConfig} field={f} value={row[f.key]} />+ ))}+ </Tooltip>+ )}+ </CircleMarker>+ );+ }+ const center: [lat: number, lng: number] = text && coord.length >= 3 ? resolveCenter(coord) : [NaN, NaN];return (- <CircleMarker- key={j}- center={coord[0]}- radius={3}- opacity={0.8}- fillOpacity={opacity}- fillColor={color}- color="#0004"- weight={1}- stroke- fill- >- {tooltipFields.length > 0 && (+ <Fragment key={j}>+ <Polygon+ positions={coord}+ pathOptions={{+ fillOpacity: opacity * 0.8,+ fillColor: color,+ color: '#0004',+ weight: 1,+ stroke: true,+ fill: true,+ }}+ ><Tooltip><header>{data[i][geoId.fid]}</header>{tooltipFields.map((f, j) => (- <TooltipContent- key={j}- allFields={allFields}- vegaConfig={vegaConfig}- field={f}- value={row[f.key]}- />+ <TooltipContent key={j} allFields={allFields} vegaConfig={vegaConfig} field={f} value={row[f.key]} />))}</Tooltip>+ </Polygon>+ {text && data[i][text.fid] && isValidLatLng(center[0], center[1]) && (+ <Marker+ position={center}+ interactive={false}+ icon={divIcon({+ className: '!bg-transparent !border-none',+ html: `<div style="font-size: 11px; transform: translate(-50%, -50%); opacity: 0.8;">${+ data[i][text.fid]+ }</div>`,+ })}+ />)}- </CircleMarker>- )- }- const center: [lat: number, lng: number] = text && coord.length >= 3 ? resolveCenter(coord) : [NaN, NaN];- return (- <Fragment key={j}>- <Polygon- positions={coord}- pathOptions={{- fillOpacity: opacity * 0.8,- fillColor: color,- color: "#0004",- weight: 1,- stroke: true,- fill: true,- }}- >- <Tooltip>- <header>{data[i][geoId.fid]}</header>- {tooltipFields.map((f, j) => (- <TooltipContent- key={j}- allFields={allFields}- vegaConfig={vegaConfig}- field={f}- value={row[f.key]}- />- ))}- </Tooltip>- </Polygon>- {text && data[i][text.fid] && isValidLatLng(center[0], center[1]) && (- <Marker- position={center}- interactive={false}- icon={divIcon({- className: '!bg-transparent !border-none',- html: `<div style="font-size: 11px; transform: translate(-50%, -50%); opacity: 0.8;">${data[i][text.fid]}</div>`,- })}- />- )}- </Fragment>- );- })}- </Fragment>- );- })}+ </Fragment>+ );+ })}+ </Fragment>+ );+ })}+ {colorDisplay && <ColorPanel display={colorDisplay} field={color!} />}</MapContainer>);});-export default ChoroplethRenderer;diff --git a/packages/graphic-walker/src/components/leafletRenderer/POIRenderer.tsx b/packages/graphic-walker/src/components/leafletRenderer/POIRenderer.tsxindex e4137485..552778d6 100644--- a/packages/graphic-walker/src/components/leafletRenderer/POIRenderer.tsx+++ b/packages/graphic-walker/src/components/leafletRenderer/POIRenderer.tsx@@ -1,12 +1,13 @@-import React, { forwardRef, useEffect, useMemo, useRef } from "react";-import { MapContainer, TileLayer, Tooltip, CircleMarker, AttributionControl } from "react-leaflet";-import type { Map } from "leaflet";-import type { DeepReadonly, IRow, IViewField, VegaGlobalConfig } from "../../interfaces";-import { getMeaAggKey } from "../../utils";-import { useColorScale, useOpacityScale, useSizeScale } from "./encodings";-import { TooltipContent } from "./tooltip";-import { useAppRootContext } from "../appRoot";-import { ChangeView } from "./utils";+import React, { forwardRef, useEffect, useMemo, useRef } from 'react';+import { MapContainer, TileLayer, Tooltip, CircleMarker, AttributionControl, Pane } from 'react-leaflet';+import { type Map } from 'leaflet';+import type { DeepReadonly, IChannelScales, IRow, IViewField, VegaGlobalConfig } from '../../interfaces';+import { getMeaAggKey } from '../../utils';+import { useColorScale, useOpacityScale, useSizeScale } from './encodings';+import { TooltipContent } from './tooltip';+import { useAppRootContext } from '../appRoot';+import { ChangeView } from './utils';+import ColorPanel from './color';export interface IPOIRendererProps {name?: string;@@ -20,6 +21,7 @@ export interface IPOIRendererProps {size: DeepReadonly<IViewField> | undefined;details: readonly DeepReadonly<IViewField>[];vegaConfig: VegaGlobalConfig;+ channelScales: IChannelScales;}export interface IPOIRendererRef {}@@ -31,46 +33,56 @@ export const isValidLatLng = (latRaw: unknown, lngRaw: unknown) => {};const formatCoerceLatLng = (latRaw: unknown, lngRaw: unknown) => {- return `${- typeof latRaw === 'number' ? latRaw : JSON.stringify(latRaw)- }, ${- typeof lngRaw === 'number' ? lngRaw : JSON.stringify(lngRaw)- }`;+ return `${typeof latRaw === 'number' ? latRaw : JSON.stringify(latRaw)}, ${typeof lngRaw === 'number' ? lngRaw : JSON.stringify(lngRaw)}`;};const debugMaxLen = 20;--const POIRenderer = forwardRef<IPOIRendererRef, IPOIRendererProps>(function POIRenderer (props, ref) {- const { name, data, allFields, latitude, longitude, color, opacity, size, details, defaultAggregated, vegaConfig } = props;-++const POIRenderer = forwardRef<IPOIRendererRef, IPOIRendererProps>(function POIRenderer(props, ref) {+ const { name, data, allFields, latitude, longitude, color, opacity, size, details, defaultAggregated, vegaConfig, channelScales } = props;+const lngLat = useMemo<[lat: number, lng: number][]>(() => {if (longitude && latitude) {- return data.map<[lat: number, lng: number]>(row => [Number(row[latitude.fid]), Number(row[longitude.fid])]).filter(v => isValidLatLng(v[0], v[1]));+ return data+ .map<[lat: number, lng: number]>((row) => [Number(row[latitude.fid]), Number(row[longitude.fid])])+ .filter((v) => isValidLatLng(v[0], v[1]));}return [];}, [longitude, latitude, data]);const [bounds, center] = useMemo<[bounds: [[n: number, w: number], [s: number, e: number]], center: [lng: number, lat: number]]>(() => {if (lngLat.length > 0) {- const [bounds, coords] = lngLat.reduce<[bounds: [[w: number, n: number], [e: number, s: number]], center: [lat: number, lng: number]]>(([bounds, acc], [lat, lng]) => {- if (lat < bounds[0][0]) {- bounds[0][0] = lat;- }- if (lat > bounds[1][0]) {- bounds[1][0] = lat;- }- if (lng < bounds[0][1]) {- bounds[0][1] = lng;- }- if (lng > bounds[1][1]) {- bounds[1][1] = lng;- }- return [bounds, [acc[0] + lng, acc[1] + lat]];- }, [[[...lngLat[0]] ,[...lngLat[0]]], [0, 0]]);+ const [bounds, coords] = lngLat.reduce<[bounds: [[w: number, n: number], [e: number, s: number]], center: [lat: number, lng: number]]>(+ ([bounds, acc], [lat, lng]) => {+ if (lat < bounds[0][0]) {+ bounds[0][0] = lat;+ }+ if (lat > bounds[1][0]) {+ bounds[1][0] = lat;+ }+ if (lng < bounds[0][1]) {+ bounds[0][1] = lng;+ }+ if (lng > bounds[1][1]) {+ bounds[1][1] = lng;+ }+ return [bounds, [acc[0] + lng, acc[1] + lat]];+ },+ [+ [[...lngLat[0]], [...lngLat[0]]],+ [0, 0],+ ]+ );return [bounds, [coords[0] / lngLat.length, coords[1] / lngLat.length] as [number, number]];}-- return [[[-180, -90], [180, 90]], [0, 0]];++ return [+ [+ [-180, -90],+ [180, 90],+ ],+ [0, 0],+ ];}, [lngLat]);const failedLatLngListRef = useRef<[index: number, lng: unknown, lat: unknown][]>([]);@@ -78,12 +90,17 @@ const POIRenderer = forwardRef<IPOIRendererRef, IPOIRendererProps>(function POIRuseEffect(() => {if (failedLatLngListRef.current.length > 0) {- console.warn(`Failed to render ${failedLatLngListRef.current.length.toLocaleString()} markers of ${data.length.toLocaleString()} rows due to invalid lat/lng.\n--------\n${- `${failedLatLngListRef.current.slice(0, debugMaxLen).map(([idx, lng, lat]) =>- `[${idx + 1}] ${formatCoerceLatLng(lat, lng)}`- ).join('\n')}`- + (failedLatLngListRef.current.length > debugMaxLen ? `\n\t... and ${(failedLatLngListRef.current.length - debugMaxLen).toLocaleString()} more` : '')- }\n`);+ console.warn(+ `Failed to render ${failedLatLngListRef.current.length.toLocaleString()} markers of ${data.length.toLocaleString()} rows due to invalid lat/lng.\n--------\n${+ `${failedLatLngListRef.current+ .slice(0, debugMaxLen)+ .map(([idx, lng, lat]) => `[${idx + 1}] ${formatCoerceLatLng(lat, lng)}`)+ .join('\n')}` ++ (failedLatLngListRef.current.length > debugMaxLen+ ? `\n\t... and ${(failedLatLngListRef.current.length - debugMaxLen).toLocaleString()} more`+ : '')+ }\n`+ );}});@@ -113,25 +130,22 @@ const POIRenderer = forwardRef<IPOIRendererRef, IPOIRendererProps>(function POIRnCols: 0,nRows: 0,charts: [],- container: () => mapRef.current?.getContainer() as HTMLDivElement ?? null,+ container: () => (mapRef.current?.getContainer() as HTMLDivElement) ?? null,chartType: 'map',- })+ });}}, []);- const sizeScale = useSizeScale(data, size, defaultAggregated);- const opacityScale = useOpacityScale(data, opacity, defaultAggregated);- const colorScale = useColorScale(data, color, defaultAggregated, vegaConfig);+ const sizeScale = useSizeScale(data, size, defaultAggregated, channelScales);+ const opacityScale = useOpacityScale(data, opacity, defaultAggregated, channelScales);+ const { mapper: colorScale, display: colorDisplay } = useColorScale(data, color, defaultAggregated, vegaConfig);const tooltipFields = useMemo(() => {- return details.concat(- [size!, color!, opacity!].filter(Boolean)- ).map(f => ({+ return details.concat([size!, color!, opacity!].filter(Boolean)).map((f) => ({...f,key: defaultAggregated && f.analyticType === 'measure' && f.aggName ? getMeaAggKey(f.fid, f.aggName) : f.fid,}));}, [defaultAggregated, details, size, color, opacity]);-return (<MapContainer attributionControl={false} center={center} ref={mapRef} zoom={5} bounds={bounds} style={{ width: '100%', height: '100%', zIndex: 1 }}><ChangeView bounds={bounds} />@@ -140,48 +154,43 @@ const POIRenderer = forwardRef<IPOIRendererRef, IPOIRendererProps>(function POIRurl="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"/><AttributionControl prefix="Leaflet" />- {Boolean(latitude && longitude) && data.map((row, i) => {- const lat = row[latitude!.fid];- const lng = row[longitude!.fid];- if (!isValidLatLng(lat, lng)) {- failedLatLngListRef.current.push([i, lat, lng]);- return null;- }- const radius = sizeScale(row);- const opacity = opacityScale(row);- const color = colorScale(row);- return (- <CircleMarker- key={`${i}-${radius}-${opacity}-${color}`}- center={[Number(lat), Number(lng)]}- radius={radius}- opacity={0.8}- fillOpacity={opacity}- fillColor={color}- color="#00000022"- stroke- weight={1}- fill- >- {tooltipFields.length > 0 && (- <Tooltip>- {tooltipFields.map((f, j) => (- <TooltipContent- key={j}- allFields={allFields}- vegaConfig={vegaConfig}- field={f}- value={row[f.key]}- />- ))}- </Tooltip>- )}- </CircleMarker>- );- })}+ {Boolean(latitude && longitude) &&+ data.map((row, i) => {+ const lat = row[latitude!.fid];+ const lng = row[longitude!.fid];+ if (!isValidLatLng(lat, lng)) {+ failedLatLngListRef.current.push([i, lat, lng]);+ return null;+ }+ const radius = sizeScale(row);+ const opacity = opacityScale(row);+ const color = colorScale(row);+ return (+ <CircleMarker+ key={`${i}-${radius}-${opacity}-${color}`}+ center={[Number(lat), Number(lng)]}+ radius={radius}+ opacity={0.8}+ fillOpacity={opacity}+ fillColor={color}+ color="#00000022"+ stroke+ weight={1}+ fill+ >+ {tooltipFields.length > 0 && (+ <Tooltip>+ {tooltipFields.map((f, j) => (+ <TooltipContent key={j} allFields={allFields} vegaConfig={vegaConfig} field={f} value={row[f.key]} />+ ))}+ </Tooltip>+ )}+ </CircleMarker>+ );+ })}+ {colorDisplay && <ColorPanel display={colorDisplay} field={color!} />}</MapContainer>);});-export default POIRenderer;diff --git a/packages/graphic-walker/src/components/leafletRenderer/color.tsx b/packages/graphic-walker/src/components/leafletRenderer/color.tsxnew file mode 100644index 00000000..596bdc01--- /dev/null+++ b/packages/graphic-walker/src/components/leafletRenderer/color.tsx@@ -0,0 +1,53 @@+import React from 'react';+import { IField } from '../../interfaces';+import { ColorDisplay } from './encodings';++const MAX_COLORS = 15;++export default function ColorPanel(props: { display: ColorDisplay; field: IField; aggerated?: boolean }) {+ const { display, field, aggerated } = props;+ const fieldName = aggerated && field.analyticType === 'measure' && field.aggName ? `${field.aggName}(${field.name})` : field.name;+ return (+ <div className="absolute right-5 top-5 bg-white/30 rounded p-2" style={{ zIndex: 999 }}>+ {display.type === 'nominal' && (+ <div className="font-xs flex flex-col space-y-1">+ <div className="font-medium max-w-[160px] overflow-hidden text-ellipsis whitespace-nowrap">{fieldName}</div>+ {display.colors.slice(0, MAX_COLORS).map(({ name, color }) => {+ return (+ <div className="flex space-x-1 items-center" key={name}>+ <div className="w-3 h-3" style={{ backgroundColor: color }}></div>+ <div>{name}</div>+ </div>+ );+ })}+ {display.colors.length > MAX_COLORS && (+ <div className="flex space-x-1 items-center">+ <div className="w-3 h-3" style={{ backgroundColor: display.colors[MAX_COLORS].color }}></div>+ <div>...{display.colors.length - MAX_COLORS} entries</div>+ </div>+ )}+ </div>+ )}+ {display.type === 'quantitative' && (+ <div className="font-xs flex flex-col space-y-1">+ <div className="font-medium max-w-[160px] overflow-hidden text-ellipsis whitespace-nowrap">{fieldName}</div>+ <div className="flex space-x-1">+ <div+ className="w-4 h-48"+ style={{+ background: `linear-gradient(${[...display.color].reverse().join(',')})`,+ }}+ ></div>+ <div className="font-xs flex flex-col justify-between">+ <div>{Math.floor(display.domain[1])}</div>+ <div>{Math.floor(display.domain[1] * 0.75 + display.domain[0] * 0.25)}</div>+ <div>{Math.floor(display.domain[1] * 0.5 + display.domain[0] * 0.5)}</div>+ <div>{Math.floor(display.domain[1] * 0.25 + display.domain[0] * 0.75)}</div>+ <div>{Math.floor(display.domain[0])}</div>+ </div>+ </div>+ </div>+ )}+ </div>+ );+}diff --git a/packages/graphic-walker/src/components/leafletRenderer/encodings.ts b/packages/graphic-walker/src/components/leafletRenderer/encodings.tsindex 48666f29..74e6788f 100644--- a/packages/graphic-walker/src/components/leafletRenderer/encodings.ts+++ b/packages/graphic-walker/src/components/leafletRenderer/encodings.ts@@ -1,48 +1,33 @@-import { useCallback, useMemo } from "react";-import { scaleLinear, scaleOrdinal } from "d3-scale";-import type { IRow, IViewField, VegaGlobalConfig } from "../../interfaces";-import { getMeaAggKey } from "../../utils";-+import { useCallback, useMemo } from 'react';+import { scaleLinear, scaleOrdinal } from 'd3-scale';+import type { IChannelScales, IRow, IScale, IViewField, VegaGlobalConfig } from '../../interfaces';+import { getMeaAggKey } from '../../utils';+import { getColor } from '../../utils/useTheme';+import { resolveScale } from '../../vis/spec/view';export interface Scale<T> {(record: IRow): T;}-const DEFAULT_COLOR = "#5B8FF9";-const DEFAULT_COLOR_STEP_1 = "#d4d4e8";-const DEFAULT_COLOR_STEP_2 = "#3b196f";-const DEFAULT_SCHEME_CATEGORY = [- "#5B8FF9",- "#61DDAA",- "#65789B",- "#F6BD16",- "#7262FD",- "#78D3F8",- "#9661BC",- "#F6903D",- "#008685",- "#F08BB4",-];--export const useColorScale = (data: IRow[], field: IViewField | null | undefined, defaultAggregate: boolean, vegaConfig: VegaGlobalConfig): Scale<string> => {- const color = (vegaConfig as any).circle?.fill || DEFAULT_COLOR;- const fixedScale = useCallback(function ColorScale (row: IRow) {- return color;- }, [color]);- const colorRange = useMemo(() => {- if ('scale' in vegaConfig && typeof vegaConfig.scale === 'object' && 'continuous' in vegaConfig.scale) {- if (Array.isArray((vegaConfig.scale?.continuous as any).range)) {- return ((vegaConfig.scale?.continuous as any).range as string[]).slice(0, 2);- }- }- return [DEFAULT_COLOR_STEP_1, DEFAULT_COLOR_STEP_2];- }, [vegaConfig]);- const schemeCategory = useMemo(() => {- if (Array.isArray(vegaConfig.range?.category)) {- return vegaConfig.range!.category as string[];- }- return DEFAULT_SCHEME_CATEGORY;- }, [vegaConfig]);+export type ColorDisplay =+ | { type: 'nominal'; colors: { name: string; color: string }[] }+ | {+ type: 'quantitative' | 'temporal';+ color: string[];+ domain: [number, number];+ };++export const useColorScale = (+ data: IRow[],+ field: IViewField | null | undefined,+ defaultAggregate: boolean,+ vegaConfig: VegaGlobalConfig+): {+ mapper: Scale<string>;+ display?: ColorDisplay;+} => {+ const { nominalPalette, primaryColor, quantitativePalette } = useMemo(() => getColor(vegaConfig), [vegaConfig]);+ const fixedScale = useMemo(() => () => primaryColor, [primaryColor]);const key = useMemo(() => {if (!field) {return '';@@ -56,53 +41,132 @@ export const useColorScale = (data: IRow[], field: IViewField | null | undefinedif (!field || field.semanticType === 'nominal') {return [0, 0];}- return data.reduce((dom: [number, number], { [key]: cur }) => {- if (cur < dom[0]) {- dom[0] = cur;- }- if (cur > dom[1]) {- dom[1] = cur;- }- return dom;- }, [Infinity, -Infinity]);+ return data.reduce(+ (dom: [number, number], { [key]: cur }) => {+ if (cur < dom[0]) {+ dom[0] = cur;+ }+ if (cur > dom[1]) {+ dom[1] = cur;+ }+ return dom;+ },+ [Infinity, -Infinity]+ );}, [data, field, key]);const distributions = useMemo(() => {if (!field || field.semanticType !== 'nominal') {return [];}- return [...data.reduce((set: Set<string>, row) => {- set.add(row[key]);- return set;- }, new Set<string>())];+ return [+ ...data.reduce((set: Set<string>, row) => {+ set.add(row[key]);+ return set;+ }, new Set<string>()),+ ];}, [data, field, key]);+const continuousScale = useMemo(() => {- const scale = scaleLinear<string, string>().domain(domain).range(colorRange);- return function ColorScale (row: IRow) {+ const [min, max] = domain;+ const linearDomains = quantitativePalette.map((_, i) => min + (max - min) * i / (quantitativePalette.length - 1));+ const scale = scaleLinear<string, string>().domain(linearDomains).range(quantitativePalette);+ return function ColorScale(row: IRow) {return scale(Number(row[key]));};- }, [domain, key, colorRange]);+ }, [domain, key, quantitativePalette]);const discreteScale = useMemo(() => {- const scale = scaleOrdinal<string, string>().domain(distributions).range(schemeCategory);- return function ColorScale (row: IRow) {+ const scale = scaleOrdinal<string, string>().domain(distributions).range(nominalPalette);+ return function ColorScale(row: IRow) {return scale(row[key]);};- }, [distributions, schemeCategory]);+ }, [distributions, nominalPalette]);+ const discreteScaleList = useMemo(() => distributions.map((name) => ({ name, color: discreteScale({ [key]: name }) })), [distributions, discreteScale]);if (!field) {- return fixedScale;+ return {+ mapper: fixedScale,+ };}if (field.semanticType === 'quantitative' || field.semanticType === 'temporal') {// continuous- return continuousScale;+ return {+ mapper: continuousScale,+ display: { type: field.semanticType, color: quantitativePalette, domain },+ };}- return discreteScale;+ return {+ mapper: discreteScale,+ display: { type: 'nominal', colors: discreteScaleList },+ };+};++const useDomain = (key: string, data: IRow[], scale?: IScale) => {+ return useMemo(() => {+ let minDomain: number | undefined;+ let maxDomain: number | undefined;+ if (scale) {+ if (scale.domain) {+ minDomain = Number(scale.domain[0]);+ maxDomain = Number(scale.domain[1]);+ }+ if (scale.domainMin !== undefined) {+ minDomain = scale.domainMin;+ }+ if (scale.domainMax !== undefined) {+ maxDomain = scale.domainMax;+ }+ }+ if (minDomain !== undefined && maxDomain !== undefined) {+ return [minDomain, maxDomain];+ }+ if (!key) {+ return [minDomain ?? 0, maxDomain ?? 0];+ }+ const values = data.map((row) => Number(row[key])).filter((val) => !isNaN(val));+ if (values.length === 0) {+ return [minDomain ?? 0, maxDomain ?? 0];+ }+ const [minDataDomain, maxDataDomain] = values.slice(1).reduce<[number, number]>(+ (acc, val) => {+ if (val < acc[0]) {+ acc[0] = val;+ }+ if (val > acc[1]) {+ acc[1] = val;+ }+ return acc;+ },+ [values[0], values[0]]+ );+ return [minDomain ?? minDataDomain, maxDomain ?? maxDataDomain];+ }, [key, data, scale]);+};++const useRange = (defaultMin: number, defaultMax: number, scale?: IScale) => {+ return useMemo(() => {+ let minRange: number | undefined;+ let maxRange: number | undefined;+ if (scale) {+ if (scale.range) {+ minRange = Number(scale.range[0]);+ maxRange = Number(scale.range[1]);+ }+ if (scale.rangeMin !== undefined) {+ minRange = scale.rangeMin;+ }+ if (scale.rangeMax !== undefined) {+ maxRange = scale.rangeMax;+ }+ }+ return [minRange ?? defaultMin, maxRange ?? defaultMax];+ }, [scale, defaultMax, defaultMin]);};const MIN_SIZE = 2;const MAX_SIZE = 10;const DEFAULT_SIZE = 3;-export const useSizeScale = (data: IRow[], field: IViewField | null | undefined, defaultAggregate: boolean): Scale<number> => {+export const useSizeScale = (data: IRow[], field: IViewField | null | undefined, defaultAggregate: boolean, scaleConfig: IChannelScales): Scale<number> => {const key = useMemo(() => {if (!field) {return '';@@ -113,44 +177,37 @@ export const useSizeScale = (data: IRow[], field: IViewField | null | undefined,return field.fid;}, [field, defaultAggregate]);- const [domainMin, domainMax] = useMemo(() => {- if (!key) {- return [0, 0];- }- const values = data.map((row) => Number(row[key])).filter((val) => !isNaN(val));- if (values.length === 0) {- return [0, 0];- }- return values.slice(1).reduce<[number, number]>((acc, val) => {- if (val < acc[0]) {- acc[0] = val;+ const resolvedScale = useMemo(() => {+ if (!scaleConfig.size) return undefined;+ return resolveScale(scaleConfig.size, field, data, 'light');+ }, [scaleConfig, data, field]);++ const [domainMin, domainMax] = useDomain(key, data, resolvedScale);++ const [minSize, maxSize] = useRange(MIN_SIZE, MAX_SIZE, resolvedScale);++ return useCallback(+ function SizeScale(record: IRow): number {+ const defaultSize = Math.max(minSize, Math.min(DEFAULT_SIZE, maxSize));+ if (!key) {+ return defaultSize;}- if (val > acc[1]) {- acc[1] = val;+ const val = Number(record[key]);+ if (isNaN(val)) {+ return defaultSize;}- return acc;- }, [values[0], values[0]]);- }, [key, data]);-- return useCallback(function SizeScale (record: IRow): number {- if (!key) {- return DEFAULT_SIZE;- }- const val = Number(record[key]);- if (isNaN(val)) {- return 0;- }- const size = (val - domainMin) / (domainMax - domainMin);- return MIN_SIZE + Math.sqrt(size) * (MAX_SIZE - MIN_SIZE);- }, [key, domainMin, domainMax, defaultAggregate]);+ const percent = Math.max(Math.min((val - domainMin) / (domainMax - domainMin), 1), 0);+ return minSize + Math.sqrt(percent) * (maxSize - minSize);+ },+ [key, domainMin, domainMax, minSize, maxSize, defaultAggregate]+ );};--const MIN_OPACITY = 0.33;-const MAX_OPACITY = 1.0;+const MIN_OPACITY = 0.3;+const MAX_OPACITY = 0.8;const DEFAULT_OPACITY = 1;-export const useOpacityScale = (data: IRow[], field: IViewField | null | undefined, defaultAggregate: boolean): Scale<number> => {+export const useOpacityScale = (data: IRow[], field: IViewField | null | undefined, defaultAggregate: boolean, scaleConfig: IChannelScales): Scale<number> => {const key = useMemo(() => {if (!field) {return '';@@ -161,34 +218,27 @@ export const useOpacityScale = (data: IRow[], field: IViewField | null | undefinreturn field.fid;}, [field, defaultAggregate]);- const [domainMin, domainMax] = useMemo(() => {- if (!key) {- return [0, 0];- }- const values = data.map((row) => Number(row[key])).filter((val) => !isNaN(val));- if (values.length === 0) {- return [0, 0];- }- return values.slice(1).reduce<[number, number]>((acc, val) => {- if (val < acc[0]) {- acc[0] = val;+ const resolvedScale = useMemo(() => {+ if (!scaleConfig.opacity) return undefined;+ return resolveScale(scaleConfig.opacity, field, data, 'light');+ }, [scaleConfig, data, field]);++ const [domainMin, domainMax] = useDomain(key, data, resolvedScale);++ const [minOpacity, maxOpacity] = useRange(MIN_OPACITY, MAX_OPACITY, resolvedScale);++ return useCallback(+ function OpacityScale(record: IRow): number {+ if (!key) {+ return DEFAULT_OPACITY;}- if (val > acc[1]) {- acc[1] = val;+ const val = Number(record[key]);+ if (isNaN(val)) {+ return 0;}- return acc;- }, [values[0], values[0]]);- }, [key, data]);-- return useCallback(function OpacityScale (record: IRow): number {- if (!key) {- return DEFAULT_OPACITY;- }- const val = Number(record[key]);- if (isNaN(val)) {- return 0;- }- const size = (val - domainMin) / (domainMax - domainMin);- return MIN_OPACITY + size * (MAX_OPACITY - MIN_OPACITY);- }, [key, domainMin, domainMax, defaultAggregate]);+ const percent = Math.max(Math.min((val - domainMin) / (domainMax - domainMin), 1), 0);+ return minOpacity + percent * (maxOpacity - minOpacity);+ },+ [key, domainMin, domainMax, minOpacity, maxOpacity, defaultAggregate]+ );};diff --git a/packages/graphic-walker/src/components/leafletRenderer/index.tsx b/packages/graphic-walker/src/components/leafletRenderer/index.tsxindex eaf4256d..91534abf 100644--- a/packages/graphic-walker/src/components/leafletRenderer/index.tsx+++ b/packages/graphic-walker/src/components/leafletRenderer/index.tsx@@ -1,8 +1,7 @@-import React, { forwardRef, useMemo } from "react";-import type { DraggableFieldState, IRow, IVisualConfigNew, IVisualLayout, VegaGlobalConfig } from "../../interfaces";-import POIRenderer from "./POIRenderer";-import ChoroplethRenderer from "./ChoroplethRenderer";-+import React, { forwardRef, useMemo } from 'react';+import type { DraggableFieldState, IChannelScales, IConfigScale, IRow, IVisualConfigNew, IVisualLayout, VegaGlobalConfig } from '../../interfaces';+import POIRenderer from './POIRenderer';+import ChoroplethRenderer from './ChoroplethRenderer';export interface ILeafletRendererProps {name?: string;@@ -11,6 +10,11 @@ export interface ILeafletRendererProps {visualConfig: IVisualConfigNew;visualLayout: IVisualLayout;data: IRow[];+ channelScales?: IChannelScales;+ scale?: {+ opacity: IConfigScale;+ size: IConfigScale;+ };}export interface ILeafletRendererRef {}@@ -18,16 +22,47 @@ export interface ILeafletRendererRef {}export const LEAFLET_DEFAULT_WIDTH = 800;export const LEAFLET_DEFAULT_HEIGHT = 600;-const LeafletRenderer = forwardRef<ILeafletRendererRef, ILeafletRendererProps>(function LeafletRenderer (props, ref) {- const { name, draggableFieldState, data, visualConfig, visualLayout, vegaConfig = {} } = props;- const { latitude: [lat], longitude: [lng], geoId: [geoId], dimensions, measures, size: [size], color: [color], opacity: [opacity], text: [text], details } = draggableFieldState;- const { defaultAggregated, geoms: [markType], } = visualConfig;+const LeafletRenderer = forwardRef<ILeafletRendererRef, ILeafletRendererProps>(function LeafletRenderer(props, ref) {+ const { name, draggableFieldState, data, visualConfig, visualLayout, vegaConfig = {}, channelScales: channelScaleRaw, scale } = props;+ const {+ latitude: [lat],+ longitude: [lng],+ geoId: [geoId],+ dimensions,+ measures,+ size: [size],+ color: [color],+ opacity: [opacity],+ text: [text],+ details,+ } = draggableFieldState;+ const {+ defaultAggregated,+ geoms: [markType],+ } = visualConfig;const { geojson, geoKey = '', geoUrl, scaleIncludeUnmatchedChoropleth = false } = visualLayout;const allFields = useMemo(() => [...dimensions, ...measures], [dimensions, measures]);const latField = useMemo(() => allFields.find((f) => f.geoRole === 'latitude'), [allFields]);const lngField = useMemo(() => allFields.find((f) => f.geoRole === 'longitude'), [allFields]);const latitude = useMemo(() => lat ?? latField, [lat, latField]);const longitude = useMemo(() => lng ?? lngField, [lng, lngField]);+ const channelScales = useMemo(() => {+ const cs = channelScaleRaw ?? {};+ if (scale?.opacity) {+ cs.opacity = {+ ...(cs.opacity ?? {}),+ ...scale.opacity,+ };+ }+ if (scale?.size) {+ cs.size = {+ ...(cs.size ?? {}),+ ...scale.size,+ };+ }+ return cs;+ }, [channelScaleRaw, scale]);+if (markType === 'poi') {return (@@ -43,6 +78,7 @@ const LeafletRenderer = forwardRef<ILeafletRendererRef, ILeafletRendererProps>(fsize={size}details={details}vegaConfig={vegaConfig}+ channelScales={channelScales}/>);} else if (markType === 'choropleth') {@@ -62,6 +98,7 @@ const LeafletRenderer = forwardRef<ILeafletRendererRef, ILeafletRendererProps>(fdetails={details}vegaConfig={vegaConfig}scaleIncludeUnmatchedChoropleth={scaleIncludeUnmatchedChoropleth}+ channelScales={channelScales}/>);}@@ -69,5 +106,4 @@ const LeafletRenderer = forwardRef<ILeafletRendererRef, ILeafletRendererProps>(freturn null;});-export default LeafletRenderer;diff --git a/packages/graphic-walker/src/components/visualConfig/colorScheme.tsx b/packages/graphic-walker/src/components/visualConfig/colorScheme.tsxindex cd1876ac..6789bfcf 100644--- a/packages/graphic-walker/src/components/visualConfig/colorScheme.tsx+++ b/packages/graphic-walker/src/components/visualConfig/colorScheme.tsx@@ -1,100 +1,95 @@-export const ColorSchemes = [- {- name: 'accent',- value: ['#7fc97f', '#beaed4', '#fdc086', '#ffff99', '#386cb0', '#f0027f', '#bf5b17', '#666666'],- },- {- name: 'category10',- value: ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf'],- },- {- name: 'category20',- value: [- '#1f77b4',- '#aec7e8',- '#ff7f0e',- '#ffbb78',- '#2ca02c',- '#98df8a',- '#d62728',- '#ff9896',- '#9467bd',- '#c5b0d5',- '#8c564b',- '#c49c94',- '#e377c2',- '#f7b6d2',- '#7f7f7f',- '#c7c7c7',- '#bcbd22',- '#dbdb8d',- '#17becf',- '#9edae5',- ],- },- {- name: 'category20b',- value: [- '#393b79',- '#5254a3',- '#6b6ecf',- '#9c9ede',- '#637939',- '#8ca252',- '#b5cf6b',- '#cedb9c',- '#8c6d31',- '#bd9e39',- '#e7ba52',- '#e7cb94',- '#843c39',- '#ad494a',- '#d6616b',- '#e7969c',- '#7b4173',- '#a55194',- '#ce6dbd',- '#de9ed6',- ],- },- {- name: 'category20c',- value: [- '#3182bd',- '#6baed6',- '#9ecae1',- '#c6dbef',- '#e6550d',- '#fd8d3c',- '#fdae6b',- '#fdd0a2',- '#31a354',- '#74c476',- '#a1d99b',- '#c7e9c0',- '#756bb1',- '#9e9ac8',- '#bcbddc',- '#dadaeb',- '#636363',- '#969696',- '#bdbdbd',- '#d9d9d9',- ],- },- {- name: 'dark2',- value: ['#1b9e77', '#d95f02', '#7570b3', '#e7298a', '#66a61e', '#e6ab02', '#a6761d', '#666666'],- },- {- name: 'paired',- value: ['#a6cee3', '#1f78b4', '#b2df8a', '#33a02c', '#fb9a99', '#e31a1c', '#fdbf6f', '#ff7f00', '#cab2d6', '#6a3d9a', '#ffff99', '#b15928'],- },- {- name: 'pastel1',- value: ['#fbb4ae', '#b3cde3', '#ccebc5', '#decbe4', '#fed9a6', '#ffffcc', '#e5d8bd', '#fddaec', '#f2f2f2'],- },-];+// From Vega source+const palettes = {+ category10: '1f77b4ff7f0e2ca02cd627289467bd8c564be377c27f7f7fbcbd2217becf',+ category20: '1f77b4aec7e8ff7f0effbb782ca02c98df8ad62728ff98969467bdc5b0d58c564bc49c94e377c2f7b6d27f7f7fc7c7c7bcbd22dbdb8d17becf9edae5',+ category20b: '393b795254a36b6ecf9c9ede6379398ca252b5cf6bcedb9c8c6d31bd9e39e7ba52e7cb94843c39ad494ad6616be7969c7b4173a55194ce6dbdde9ed6',+ category20c: '3182bd6baed69ecae1c6dbefe6550dfd8d3cfdae6bfdd0a231a35474c476a1d99bc7e9c0756bb19e9ac8bcbddcdadaeb636363969696bdbdbdd9d9d9',+ tableau10: '4c78a8f58518e4575672b7b254a24beeca3bb279a2ff9da69d755dbab0ac',+ tableau20: '4c78a89ecae9f58518ffbf7954a24b88d27ab79a20f2cf5b43989483bcb6e45756ff9d9879706ebab0acd67195fcbfd2b279a2d6a5c99e765fd8b5a5',+ accent: '7fc97fbeaed4fdc086ffff99386cb0f0027fbf5b17666666',+ dark2: '1b9e77d95f027570b3e7298a66a61ee6ab02a6761d666666',+ paired: 'a6cee31f78b4b2df8a33a02cfb9a99e31a1cfdbf6fff7f00cab2d66a3d9affff99b15928',+ pastel1: 'fbb4aeb3cde3ccebc5decbe4fed9a6ffffcce5d8bdfddaecf2f2f2',+ pastel2: 'b3e2cdfdcdaccbd5e8f4cae4e6f5c9fff2aef1e2cccccccc',+ set1: 'e41a1c377eb84daf4a984ea3ff7f00ffff33a65628f781bf999999',+ set2: '66c2a5fc8d628da0cbe78ac3a6d854ffd92fe5c494b3b3b3',+ set3: '8dd3c7ffffb3bebadafb807280b1d3fdb462b3de69fccde5d9d9d9bc80bdccebc5ffed6f',+ blues: 'cfe1f2bed8eca8cee58fc1de74b2d75ba3cf4592c63181bd206fb2125ca40a4a90',+ greens: 'd3eecdc0e6baabdda594d3917bc77d60ba6c46ab5e329a512089430e7735036429',+ greys: 'e2e2e2d4d4d4c4c4c4b1b1b19d9d9d8888887575756262624d4d4d3535351e1e1e',+ oranges: 'fdd8b3fdc998fdb87bfda55efc9244f87f2cf06b18e4580bd14904b93d029f3303',+ purples: 'e2e1efd4d4e8c4c5e0b4b3d6a3a0cc928ec3827cb97566ae684ea25c3696501f8c',+ reds: 'fdc9b4fcb49afc9e80fc8767fa7051f6573fec3f2fdc2a25c81b1db21218970b13',+ blueGreen: 'd5efedc1e8e0a7ddd18bd2be70c6a958ba9144ad77319c5d2089460e7736036429',+ bluePurple: 'ccddecbad0e4a8c2dd9ab0d4919cc98d85be8b6db28a55a6873c99822287730f71',+ greenBlue: 'd3eecec5e8c3b1e1bb9bd8bb82cec269c2ca51b2cd3c9fc7288abd1675b10b60a1',+ orangeRed: 'fddcaffdcf9bfdc18afdad77fb9562f67d53ee6545e24932d32d1ebf130da70403',+ purpleBlue: 'dbdaebc8cee4b1c3de97b7d87bacd15b9fc93a90c01e7fb70b70ab056199045281',+ purpleBlueGreen: 'dbd8eac8cee4b0c3de93b7d872acd1549fc83892bb1c88a3097f8702736b016353',+ purpleRed: 'dcc9e2d3b3d7ce9eccd186c0da6bb2e14da0e23189d91e6fc61159ab07498f023a',+ redPurple: 'fccfccfcbec0faa9b8f98faff571a5ec539ddb3695c41b8aa908808d0179700174',+ yellowGreen: 'e4f4acd1eca0b9e2949ed68880c97c62bb6e47aa5e3297502083440e723b036034',+ yellowOrangeBrown: 'feeaa1fedd84fecc63feb746fca031f68921eb7215db5e0bc54c05ab3d038f3204',+ yellowOrangeRed: 'fee087fed16ffebd59fea849fd903efc7335f9522bee3423de1b20ca0b22af0225',+ blueOrange: '134b852f78b35da2cb9dcae1d2e5eff2f0ebfce0bafbbf74e8932fc5690d994a07',+ brownBlueGreen: '704108a0651ac79548e3c78af3e6c6eef1eac9e9e48ed1c74da79e187a72025147',+ purpleGreen: '5b1667834792a67fb6c9aed3e6d6e8eff0efd9efd5aedda971bb75368e490e5e29',+ purpleOrange: '4114696647968f83b7b9b4d6dadbebf3eeeafce0bafbbf74e8932fc5690d994a07',+ redBlue: '8c0d25bf363adf745ef4ae91fbdbc9f2efeed2e5ef9dcae15da2cb2f78b3134b85',+ redGrey: '8c0d25bf363adf745ef4ae91fcdccbfaf4f1e2e2e2c0c0c0969696646464343434',+ yellowGreenBlue: 'eff9bddbf1b4bde5b594d5b969c5be45b4c22c9ec02182b82163aa23479c1c3185',+ redYellowBlue: 'a50026d4322cf16e43fcac64fedd90faf8c1dcf1ecabd6e875abd04a74b4313695',+ redYellowGreen: 'a50026d4322cf16e43fcac63fedd8df9f7aed7ee8ea4d86e64bc6122964f006837',+ pinkYellowGreen: '8e0152c0267edd72adf0b3d6faddedf5f3efe1f2cab6de8780bb474f9125276419',+ spectral: '9e0142d13c4bf0704afcac63fedd8dfbf8b0e0f3a1a9dda269bda94288b55e4fa2',+ viridis:+ '440154470e61481a6c482575472f7d443a834144873d4e8a39568c35608d31688e2d708e2a788e27818e23888e21918d1f988b1fa08822a8842ab07f35b77943bf7154c56866cc5d7ad1518fd744a5db36bcdf27d2e21be9e51afde725',+ magma: '0000040404130b0924150e3720114b2c11603b0f704a107957157e651a80721f817f24828c29819a2e80a8327db6377ac43c75d1426fde4968e95462f1605df76f5cfa7f5efc8f65fe9f6dfeaf78febf84fece91fddea0fcedaffcfdbf',+ inferno:+ '0000040403130c0826170c3b240c4f330a5f420a68500d6c5d126e6b176e781c6d86216b932667a12b62ae305cbb3755c73e4cd24644dd513ae65c30ed6925f3771af8850ffb9506fca50afcb519fac62df6d645f2e661f3f484fcffa4',+ plasma: '0d088723069033059742039d5002a25d01a66a00a87801a88405a7900da49c179ea72198b12a90ba3488c33d80cb4779d35171da5a69e16462e76e5bed7953f2834cf68f44fa9a3dfca636fdb32ffec029fcce25f9dc24f5ea27f0f921',+ cividis:+ '00205100235800265d002961012b65042e670831690d346b11366c16396d1c3c6e213f6e26426e2c456e31476e374a6e3c4d6e42506e47536d4c566d51586e555b6e5a5e6e5e616e62646f66676f6a6a706e6d717270717573727976737c79747f7c75827f758682768985778c8877908b78938e789691789a94789e9778a19b78a59e77a9a177aea575b2a874b6ab73bbaf71c0b26fc5b66dc9b96acebd68d3c065d8c462ddc85fe2cb5ce7cf58ebd355f0d652f3da4ff7de4cfae249fce647',+ rainbow:+ '6e40aa883eb1a43db3bf3cafd83fa4ee4395fe4b83ff576eff6659ff7847ff8c38f3a130e2b72fcfcc36bee044aff05b8ff4576ff65b52f6673af27828ea8d1ddfa319d0b81cbecb23abd82f96e03d82e14c6edb5a5dd0664dbf6e40aa',+ sinebow:+ 'ff4040fc582af47218e78d0bd5a703bfbf00a7d5038de70b72f41858fc2a40ff402afc5818f4720be78d03d5a700bfbf03a7d50b8de71872f42a58fc4040ff582afc7218f48d0be7a703d5bf00bfd503a7e70b8df41872fc2a58ff4040',+ turbo: '23171b32204a3e2a71453493493eae4b49c54a53d7485ee44569ee4074f53c7ff8378af93295f72e9ff42ba9ef28b3e926bce125c5d925cdcf27d5c629dcbc2de3b232e9a738ee9d3ff39347f68950f9805afc7765fd6e70fe667cfd5e88fc5795fb51a1f84badf545b9f140c5ec3cd0e637dae034e4d931ecd12ef4c92bfac029ffb626ffad24ffa223ff9821ff8d1fff821dff771cfd6c1af76118f05616e84b14df4111d5380fcb2f0dc0260ab61f07ac1805a313029b0f00950c00910b00',+ browns: 'eedbbdecca96e9b97ae4a865dc9856d18954c7784cc0673fb85536ad44339f3632',+ tealBlues: 'bce4d89dd3d181c3cb65b3c245a2b9368fae347da0306a932c5985',+ teals: 'bbdfdfa2d4d58ac9c975bcbb61b0af4da5a43799982b8b8c1e7f7f127273006667',+ warmGreys: 'dcd4d0cec5c1c0b8b4b3aaa7a59c9998908c8b827f7e7673726866665c5a59504e',+ goldGreen: 'f4d166d5ca60b6c35c98bb597cb25760a6564b9c533f8f4f33834a257740146c36',+ goldOrange: 'f4d166f8be5cf8aa4cf5983bf3852aef701be2621fd65322c54923b142239e3a26',+ goldRed: 'f4d166f6be59f9aa51fc964ef6834bee734ae56249db5247cf4244c43141b71d3e',+ lightGreyRed: 'efe9e6e1dad7d5cbc8c8bdb9bbaea9cd967ddc7b43e15f19df4011dc000b',+ lightGreyTeal: 'e4eaead6dcddc8ced2b7c2c7a6b4bc64b0bf22a6c32295c11f85be1876bc',+ lightMulti: 'e0f1f2c4e9d0b0de9fd0e181f6e072f6c053f3993ef77440ef4a3c',+ lightOrange: 'f2e7daf7d5baf9c499fab184fa9c73f68967ef7860e8645bde515bd43d5b',+ lightTealBlue: 'e3e9e0c0dccf9aceca7abfc859afc0389fb9328dad2f7ca0276b95255988',+ darkBlue: '3232322d46681a5c930074af008cbf05a7ce25c0dd38daed50f3faffffff',+ darkGold: '3c3c3c584b37725e348c7631ae8b2bcfa424ecc31ef9de30fff184ffffff',+ darkGreen: '3a3a3a215748006f4d048942489e4276b340a6c63dd2d836ffeb2cffffaa',+ darkMulti: '3737371f5287197d8c29a86995ce3fffe800ffffff',+ darkRed: '3434347036339e3c38cc4037e75d1eec8620eeab29f0ce32ffeb2c',+};++export type PaletteName = keyof typeof palettes;++function colors(palette: string) {+ const colorLength = (palette.length / 6) | 0;+ const color = new Array<string>(colorLength);+ for (let i = 0; i < colorLength; ) {+ color[i] = '#' + palette.slice(i * 6, ++i * 6);+ }+ return color;+}++export const ColorSchemes = Object.entries(palettes).map(([name, palette]) => ({ name, value: colors(palette) }));++export const getPalette = (name: PaletteName) => {+ return colors(palettes[name] ?? palettes.tableau10);+};export const extractRGBA = (rgba?: string) => {if (!rgba) {@@ -105,4 +100,3 @@ export const extractRGBA = (rgba?: string) => {const [r = 0, g = 0, b = 0, a = 0] = arr.map(Number);return { r, g, b, a };};-diff --git a/packages/graphic-walker/src/interfaces.ts b/packages/graphic-walker/src/interfaces.tsindex 59626c26..0d2ebe09 100644--- a/packages/graphic-walker/src/interfaces.ts+++ b/packages/graphic-walker/src/interfaces.ts@@ -367,7 +367,7 @@ export type IThemeKey = 'vega' | 'g2';export type IDarkMode = 'media' | 'light' | 'dark';export type IComputationFunction = (payload: IDataQueryPayload) => Promise<IRow[]>;-export type VegaGlobalConfig = VgConfig | VlConfig;+export type VegaGlobalConfig = VgConfig & VlConfig;export interface IVegaChartRef {x: number;diff --git a/packages/graphic-walker/src/renderer/specRenderer.tsx b/packages/graphic-walker/src/renderer/specRenderer.tsxindex 30910dad..4f7d1025 100644--- a/packages/graphic-walker/src/renderer/specRenderer.tsx+++ b/packages/graphic-walker/src/renderer/specRenderer.tsx@@ -191,6 +191,8 @@ const SpecRenderer = forwardRef<IReactVegaHandler, SpecRendererProps>(function (visualConfig={visualConfig}visualLayout={layout}vegaConfig={vegaConfig}+ channelScales={channelScales}+ scale={scale}/>)}{isSpatial || (diff --git a/packages/graphic-walker/src/utils/useTheme.ts b/packages/graphic-walker/src/utils/useTheme.tsindex 3bb49b62..9d2efc6d 100644--- a/packages/graphic-walker/src/utils/useTheme.ts+++ b/packages/graphic-walker/src/utils/useTheme.ts@@ -1,5 +1,7 @@-import { IThemeKey } from '../interfaces';-import { builtInThemes, getColorPalette, getPrimaryColor } from '../vis/theme';+import { IThemeKey, VegaGlobalConfig } from '../interfaces';+import { DEFAULT_COLOR, builtInThemes, getColorPalette, getPrimaryColor } from '../vis/theme';+import { RangeScheme } from 'vega-typings';+import { PaletteName, getPalette } from '../components/visualConfig/colorScheme';type PlainObject = { [key: string]: any };@@ -31,7 +33,13 @@ const deepMergeAll = (...objects: PlainObject[]): PlainObject => {return objects.reduce((acc, obj) => deepMerge(acc, obj), {});};-export function getTheme(props: { themeKey?: IThemeKey; themeConfig?: any; primaryColor?: string; colorPalette?: string; mediaTheme: 'dark' | 'light' }) {+export function getTheme(props: {+ themeKey?: IThemeKey;+ themeConfig?: any;+ primaryColor?: string;+ colorPalette?: string;+ mediaTheme: 'dark' | 'light';+}): VegaGlobalConfig {const { themeConfig, themeKey, mediaTheme, colorPalette, primaryColor } = props;const presetConfig = themeConfig ?? builtInThemes[themeKey ?? 'vega'];const colorConfig = primaryColor ? getPrimaryColor(primaryColor) : {};@@ -39,3 +47,31 @@ export function getTheme(props: { themeKey?: IThemeKey; themeConfig?: any; primaconst config = deepMergeAll(presetConfig, colorConfig, paletteConfig)?.[mediaTheme];return config;}++function parsePalette(v?: RangeScheme): string[] | undefined {+ if (!v) {+ return undefined;+ }+ if (v instanceof Array) {+ return v as string[];+ }+ if (typeof v === 'object' && 'scheme' in v) {+ if (v.scheme instanceof Array) {+ return v.scheme;+ }+ return getPalette(v.scheme as PaletteName);+ }+ return undefined;+}++export function getColor(theme: VegaGlobalConfig) {+ const stroke = theme.point?.stroke ?? DEFAULT_COLOR;+ const primaryColor = typeof stroke === 'string' ? stroke : DEFAULT_COLOR;+ const nominalPalette = parsePalette(theme.range?.category) ?? getPalette('tableau10');+ const quantitativePalette = parsePalette(theme.range?.ramp) ?? getPalette('blues');+ return {+ primaryColor,+ nominalPalette,+ quantitativePalette,+ };+}diff --git a/packages/graphic-walker/src/vis/spec/view.ts b/packages/graphic-walker/src/vis/spec/view.tsindex e7e1382d..f9a96207 100644--- a/packages/graphic-walker/src/vis/spec/view.ts+++ b/packages/graphic-walker/src/vis/spec/view.ts@@ -1,4 +1,4 @@-import { IChannelScales, ISemanticType, IStackMode, IViewField } from '../../interfaces';+import { IChannelScales, IField, IFieldInfos, IRow, ISemanticType, IStackMode, IViewField } from '../../interfaces';import { autoMark } from './mark';import { NULL_FIELD } from './field';import { channelAggregate } from './aggregate';@@ -62,7 +62,7 @@ export function getSingleView(props: SingleViewProps) {theta,radius,details,- text+ text,});if (defaultAggregated) {channelAggregate(encoding, fields);@@ -72,7 +72,7 @@ export function getSingleView(props: SingleViewProps) {const mark = {type: markType,opacity: 0.96,- tooltip: { content: 'data' }+ tooltip: { content: 'data' },};return {config,@@ -81,22 +81,34 @@ export function getSingleView(props: SingleViewProps) {};}-export function resolveScales(scale: IChannelScales, view: any, data: readonly any[], theme: 'dark' | 'light') {- const newEncoding = {...view.encoding};+export function resolveScale<T extends Object>(scale: T | ((info: IFieldInfos) => T), field: IField | null | undefined, data: readonly IRow[], theme: 'dark' | 'light') {+ if (typeof scale === 'function') {+ if (!field) return undefined;+ const values = data.map((x) => x[field.fid]);+ return scale({+ semanticType: field.semanticType,+ theme,+ values,+ });+ }+ return scale;+}++export function resolveScales(scale: IChannelScales, view: any, data: readonly IRow[], theme: 'dark' | 'light') {+ const newEncoding = { ...view.encoding };function addScale(c: string) {if (scale[c] && newEncoding[c]) {if (typeof scale[c] === 'function') {const field = newEncoding[c].field;- const values = data.map(x => x[field]);+ const values = data.map((x) => x[field]);newEncoding[c].scale = scale[c]({semanticType: newEncoding[c].type,theme,values,- })+ });} else {newEncoding[c].scale = scale[c];}-}}addScale('color');@@ -107,6 +119,6 @@ export function resolveScales(scale: IChannelScales, view: any, data: readonly areturn {...view,- encoding: newEncoding+ encoding: newEncoding,};-}\ No newline at end of file+}diff --git a/packages/graphic-walker/src/vis/theme.ts b/packages/graphic-walker/src/vis/theme.tsindex af8b4a1a..9ba36d3e 100644--- a/packages/graphic-walker/src/vis/theme.ts+++ b/packages/graphic-walker/src/vis/theme.ts@@ -13,7 +13,7 @@ export type GWGlobalConfig<dark: T;};-const DEFAULT_COLOR = '#5B8FF9';+export const DEFAULT_COLOR = '#5B8FF9';const DARK_COMMON_DESIGN = {background: 'transparent',header: {