An open source alternative to Tableau. Embeddable visual analytic
TypeScript bidatadata-analysisdata-miningdata-visualizationedak6skanarieslow-codepivot-tablereacttableautableau-alternativetypescriptvegavega-litevisualization
feat: leaflet geojson support (#94)
Bob3fd9ee300cbd
diff --git a/packages/graphic-walker/package.json b/packages/graphic-walker/package.jsonindex da3ace68..e2cc94a6 100644--- a/packages/graphic-walker/package.json+++ b/packages/graphic-walker/package.json@@ -40,9 +40,13 @@"@kanaries/web-data-loader": "^0.1.7","@tailwindcss/forms": "^0.5.4","autoprefixer": "^10.3.5",+ "d3-format": "^3.1.0",+ "d3-scale": "^4.0.2",+ "d3-time-format": "^4.1.0","i18next": "^21.9.1","i18next-browser-languagedetector": "^6.1.5","immer": "^9.0.15",+ "leaflet": "^1.9.4","mobx": "^6.3.3","mobx-react-lite": "^3.2.1","nanoid": "^4.0.2",@@ -50,9 +54,11 @@"postinstall-postinstall": "^2.1.0","re-resizable": "^6.9.8","react-i18next": "^11.18.6",+ "react-leaflet": "^4.2.1","react-shadow": "^20.0.0","rxjs": "^7.3.0","tailwindcss": "^3.2.4",+ "topojson-client": "^3.1.0","uuid": "^8.3.2","vega": "^5.22.1","vega-embed": "^6.21.0",@@ -60,10 +66,16 @@},"devDependencies": {"@rollup/plugin-typescript": "^8.2.5",+ "@types/d3-format": "^3.0.1",+ "@types/d3-scale": "^4.0.3",+ "@types/d3-time-format": "^4.0.0",+ "@types/geojson": "^7946.0.10",+ "@types/leaflet": "^1.9.3","@types/react": "^17.x","@types/react-beautiful-dnd": "^13.1.2","@types/react-dom": "^17.x","@types/styled-components": "^5.1.26",+ "@types/topojson-client": "^3.1.1","@types/uuid": "^8.3.1","@vercel/analytics": "^0.1.8","@vitejs/plugin-react": "^3.1.0",diff --git a/packages/graphic-walker/src/App.tsx b/packages/graphic-walker/src/App.tsxindex 8115495b..d1d7efd2 100644--- a/packages/graphic-walker/src/App.tsx+++ b/packages/graphic-walker/src/App.tsx@@ -1,7 +1,7 @@import React, { useEffect, useRef, useMemo, useState } from 'react';import { observer } from 'mobx-react-lite';import { useTranslation } from 'react-i18next';-import { IComputationFunction, IDarkMode, IMutField, IRow, ISegmentKey, IThemeKey, Specification } from './interfaces';+import { IGeographicData, IComputationFunction, IDarkMode, IMutField, IRow, ISegmentKey, IThemeKey, Specification } from './interfaces';import type { IReactVegaHandler } from './vis/react-vega';import VisualSettings from './visualSettings';import PosFields from './fields/posFields';@@ -19,6 +19,7 @@ import DatasetConfig from './dataSource/datasetConfig';import { useCurrentMediaTheme } from './utils/media';import CodeExport from './components/codeExport';import VisualConfig from './components/visualConfig';+import GeoConfigPanel from './components/leafletRenderer/geoConfigPanel';import type { ToolbarItemProps } from './components/toolbar';import AskViz from './components/askViz';import { getComputation } from './computation/clientComputation';@@ -44,6 +45,9 @@ export interface IGWProps {extra?: ToolbarItemProps[];exclude?: string[];};+ geographicData?: IGeographicData & {+ key: string;+ };enhanceAPI?: {header?: Record<string, string>;features?: {@@ -65,6 +69,7 @@ const App = observer<IGWProps>(function App(props) {dark = 'media',computation,toolbar,+ geographicData,enhanceAPI,} = props;const { commonStore, vizStore } = useGlobalStore();@@ -134,6 +139,12 @@ const App = observer<IGWProps>(function App(props) {}}, [spec, safeDataset]);+ useEffect(() => {+ if (geographicData) {+ vizStore.setGeographicData(geographicData, geographicData.key);+ }+ }, [geographicData]);+useEffect(() => {if (computation) {vizStore.setComputationFunction(computation);@@ -172,6 +183,7 @@ const App = observer<IGWProps>(function App(props) {<VisualSettings rendererHandler={rendererRef} darkModePreference={dark} exclude={toolbar?.exclude} extra={toolbar?.extra} /><CodeExport /><VisualConfig />+ <GeoConfigPanel /><div className="md:grid md:grid-cols-12 xl:grid-cols-6"><div className="md:col-span-3 xl:col-span-1"><DatasetFields />diff --git a/packages/graphic-walker/src/components/leafletRenderer/ChoroplethRenderer.tsx b/packages/graphic-walker/src/components/leafletRenderer/ChoroplethRenderer.tsxnew file mode 100644index 00000000..66e0767a--- /dev/null+++ b/packages/graphic-walker/src/components/leafletRenderer/ChoroplethRenderer.tsx@@ -0,0 +1,293 @@+import React, { Fragment, forwardRef, useEffect, useImperativeHandle, useMemo, useRef } from "react";+import { CircleMarker, MapContainer, Polygon, Marker, TileLayer, Tooltip } from "react-leaflet";+import { type Map, divIcon } from "leaflet";+import type { DeepReadonly, 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";+++export interface IChoroplethRendererProps {+ data: IRow[];+ allFields: DeepReadonly<IViewField[]>;+ features: FeatureCollection | undefined;+ geoKey: string;+ defaultAggregated: boolean;+ geoId: DeepReadonly<IViewField>;+ color: DeepReadonly<IViewField> | undefined;+ opacity: DeepReadonly<IViewField> | undefined;+ text: DeepReadonly<IViewField> | undefined;+ details: readonly DeepReadonly<IViewField>[];+ vegaConfig: VegaGlobalConfig;+ scaleIncludeUnmatchedChoropleth: boolean;+}++export interface IChoroplethRendererRef {}++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]])];+ }+ case 'Point': {+ const coords = featureGeom.coordinates;+ return [[[coords[1], coords[0]]]];+ }+ case 'GeometryCollection': {+ const coords = featureGeom.geometries.map<[lat: number, lng: number][][]>(resolveCoords);+ return coords.flat();+ }+ case 'LineString': {+ const coords = featureGeom.coordinates;+ 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]]));+ }+ case 'MultiPoint': {+ const coords = featureGeom.coordinates;+ 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]]));+ }+ default: {+ return [];+ }+ }+};++const resolveCenter = (coordinates: [lat: number, lng: number][]): [lng: number, lat: number] => {+ let area = 0;+ let centroid: [lat: number, lng: number] = [0, 0];++ for (let i = 0; i < coordinates.length - 1; i++) {+ let [x1, y1] = coordinates[i];+ let [x2, y2] = coordinates[i + 1];++ let tempArea = x1 * y2 - x2 * y1;+ area += tempArea;++ centroid[0] += (x1 + x2) * tempArea;+ centroid[1] += (y1 + y2) * tempArea;+ }++ area /= 2;++ centroid[0] /= 6 * area;+ centroid[1] /= 6 * area;++ return centroid;+};++const ChoroplethRenderer = forwardRef<IChoroplethRendererRef, IChoroplethRendererProps>(function ChoroplethRenderer (props, ref) {+ const { data, allFields, features, geoKey, defaultAggregated, geoId, color, opacity, text, details, vegaConfig, scaleIncludeUnmatchedChoropleth } = props;++ useImperativeHandle(ref, () => ({}));++ const geoIndices = useMemo(() => {+ if (geoId) {+ return data.map(row => row[geoId.fid]);+ }+ return [];+ }, [geoId, data]);++ const [indices, geoShapes] = useMemo<[indices: number[], geoShapes: (FeatureCollection['features'][number] | undefined)[]]>(() => {+ if (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;+ if (feature) {+ indices.push(i);+ }+ return feature;+ });+ return [indices, shapes];+ }+ return [[], []];+ }, [geoIndices, features, geoKey]);++ useEffect(() => {+ if (geoShapes.length > 0) {+ 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.`);+ }+ }+ }, [geoShapes]);++ const lngLat = useMemo<[lat: number, lng: number][][][]>(() => {+ if (geoShapes.length > 0) {+ return geoShapes.map<[lat: number, lng: number][][]>(feature => {+ if (feature) {+ return resolveCoords(feature.geometry);+ }+ return [];+ }, []);+ }+ return [];+ }, [geoShapes]);++ const [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 (lng < bounds[0][0]) {+ bounds[0][0] = lng;+ }+ if (lng > bounds[1][0]) {+ bounds[1][0] = lng;+ }+ if (lat < bounds[0][1]) {+ bounds[0][1] = lat;+ }+ if (lat > bounds[1][1]) {+ bounds[1][1] = lat;+ }+ return [bounds, [acc[0] + lng, acc[1] + lat]];+ }, [[[-180, -90], [180, 90]], [0, 0]]);+ return [bounds, [coords[0] / lngLat.length, coords[1] / lngLat.length] as [number, number]];+ }++ return [[[-180, -90], [180, 90]], [0, 0]];+ }, [lngLat]);++ const distribution = useMemo(() => {+ if (scaleIncludeUnmatchedChoropleth) {+ return data;+ }+ return indices.map(i => data[i]);+ }, [data, indices, scaleIncludeUnmatchedChoropleth]);++ const opacityScale = useOpacityScale(distribution, opacity, defaultAggregated);+ const colorScale = useColorScale(distribution, color, defaultAggregated, vegaConfig);++ const tooltipFields = useMemo(() => {+ return details.concat(+ [color!, opacity!].filter(Boolean)+ ).map(f => ({+ ...f,+ key: defaultAggregated && f.analyticType === 'measure' && f.aggName ? getMeaAggKey(f.fid, f.aggName) : f.fid,+ }));+ }, [defaultAggregated, details, color, opacity]);++ const mapRef = useRef<Map>(null);++ useEffect(() => {+ const container = mapRef.current?.getContainer();+ if (container) {+ const ro = new ResizeObserver(() => {+ mapRef.current?.invalidateSize();+ });+ ro.observe(container);+ return () => {+ ro.unobserve(container);+ };+ }+ });++ useEffect(() => {+ mapRef.current?.flyToBounds(bounds);+ }, [`${bounds[0][0]},${bounds[0][1]},${bounds[1][0]},${bounds[1][1]}`]);++ return (+ <MapContainer center={center} ref={mapRef} zoom={5} bounds={bounds} style={{ width: '100%', height: '100%', zIndex: 1 }}>+ <TileLayer+ attribution='© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'+ url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"+ />+ {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 (+ <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>+ );+ })}+ </MapContainer>+ );+});+++export default ChoroplethRenderer;diff --git a/packages/graphic-walker/src/components/leafletRenderer/POIRenderer.tsx b/packages/graphic-walker/src/components/leafletRenderer/POIRenderer.tsxnew file mode 100644index 00000000..549a4a6d--- /dev/null+++ b/packages/graphic-walker/src/components/leafletRenderer/POIRenderer.tsx@@ -0,0 +1,170 @@+import React, { forwardRef, useEffect, useMemo, useRef } from "react";+import { MapContainer, TileLayer, Tooltip, CircleMarker } 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";+++export interface IPOIRendererProps {+ data: IRow[];+ allFields: DeepReadonly<IViewField[]>;+ defaultAggregated: boolean;+ latitude: DeepReadonly<IViewField> | undefined;+ longitude: DeepReadonly<IViewField> | undefined;+ color: DeepReadonly<IViewField> | undefined;+ opacity: DeepReadonly<IViewField> | undefined;+ size: DeepReadonly<IViewField> | undefined;+ details: readonly DeepReadonly<IViewField>[];+ vegaConfig: VegaGlobalConfig;+}++export interface IPOIRendererRef {}++export const isValidLatLng = (latRaw: unknown, lngRaw: unknown) => {+ const lat = Number(latRaw);+ const lng = Number(lngRaw);+ return lat >= -90 && lat <= 90 && lng >= -180 && lng <= 180;+};++const formatCoerceLatLng = (latRaw: unknown, lngRaw: unknown) => {+ 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 { data, allFields, latitude, longitude, color, opacity, size, details, defaultAggregated, vegaConfig } = 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 [];+ }, [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 (lng < bounds[0][0]) {+ bounds[0][0] = lng;+ }+ if (lng > bounds[1][0]) {+ bounds[1][0] = lng;+ }+ if (lat < bounds[0][1]) {+ bounds[0][1] = lat;+ }+ if (lat > bounds[1][1]) {+ bounds[1][1] = lat;+ }+ return [bounds, [acc[0] + lng, acc[1] + lat]];+ }, [[[-180, -90], [180, 90]], [0, 0]]);+ return [bounds, [coords[0] / lngLat.length, coords[1] / lngLat.length] as [number, number]];+ }++ return [[[-180, -90], [180, 90]], [0, 0]];+ }, [lngLat]);++ const failedLatLngListRef = useRef<[index: number, lng: unknown, lat: unknown][]>([]);+ failedLatLngListRef.current = [];++ useEffect(() => {+ 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`);+ }+ });++ const mapRef = useRef<Map>(null);++ useEffect(() => {+ const container = mapRef.current?.getContainer();+ if (container) {+ const ro = new ResizeObserver(() => {+ mapRef.current?.invalidateSize();+ });+ ro.observe(container);+ return () => {+ ro.unobserve(container);+ };+ }+ });++ useEffect(() => {+ mapRef.current?.flyToBounds(bounds);+ }, [`${bounds[0][0]},${bounds[0][1]},${bounds[1][0]},${bounds[1][1]}`]);++ const sizeScale = useSizeScale(data, size, defaultAggregated);+ const opacityScale = useOpacityScale(data, opacity, defaultAggregated);+ const colorScale = useColorScale(data, color, defaultAggregated, vegaConfig);++ const tooltipFields = useMemo(() => {+ 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 center={center} ref={mapRef} zoom={5} bounds={bounds} style={{ width: '100%', height: '100%', zIndex: 1 }}>+ <TileLayer+ attribution='© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'+ url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"+ />+ {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="#0004"+ weight={1}+ stroke+ fill+ >+ {tooltipFields.length > 0 && (+ <Tooltip>+ {tooltipFields.map((f, j) => (+ <TooltipContent+ key={j}+ allFields={allFields}+ vegaConfig={vegaConfig}+ field={f}+ value={row[f.key]}+ />+ ))}+ </Tooltip>+ )}+ </CircleMarker>+ );+ })}+ </MapContainer>+ );+});+++export default POIRenderer;diff --git a/packages/graphic-walker/src/components/leafletRenderer/encodings.ts b/packages/graphic-walker/src/components/leafletRenderer/encodings.tsnew file mode 100644index 00000000..25c232a3--- /dev/null+++ b/packages/graphic-walker/src/components/leafletRenderer/encodings.ts@@ -0,0 +1,194 @@+import { useCallback, useMemo } from "react";+import { scaleLinear, scaleOrdinal } from "d3-scale";+import type { IRow, IViewField, VegaGlobalConfig } from "../../interfaces";+import { getMeaAggKey } from "../../utils";+++export interface Scale<T> {+ (record: IRow): T;+}++const DEFAULT_COLOR = "#5B8FF9";+const DEFAULT_COLOR_STEP_1 = "#EBCCFF";+const DEFAULT_COLOR_STEP_2 = "#0D1090";+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]);+ const key = useMemo(() => {+ if (!field) {+ return '';+ }+ if (defaultAggregate && field.aggName && field.analyticType === 'measure') {+ return getMeaAggKey(field.fid, field.aggName);+ }+ return field.fid;+ }, [field, defaultAggregate]);+ const domain = useMemo<[number, number]>(() => {+ if (!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]);+ }, [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>())];+ }, [data, field, key]);+ const continuousScale = useMemo(() => {+ const scale = scaleLinear<string, string>().domain(domain).range(colorRange);+ return function ColorScale (row: IRow) {+ return scale(Number(row[key]));+ };+ }, [domain, key, colorRange]);+ const discreteScale = useMemo(() => {+ const scale = scaleOrdinal<string, string>().domain(distributions).range(schemeCategory);+ return function ColorScale (row: IRow) {+ return scale(row[key]);+ };+ }, [distributions, schemeCategory]);++ if (!field) {+ return fixedScale;+ }+ if (field.semanticType === 'quantitative' || field.semanticType === 'temporal') {+ // continuous+ return continuousScale;+ }+ return discreteScale;+};++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> => {+ const key = useMemo(() => {+ if (!field) {+ return '';+ }+ if (defaultAggregate && field.aggName && field.analyticType === 'measure') {+ return getMeaAggKey(field.fid, field.aggName);+ }+ 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;+ }+ if (val > acc[1]) {+ acc[1] = val;+ }+ 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 MIN_OPACITY = 0.33;+const MAX_OPACITY = 1.0;+const DEFAULT_OPACITY = 1;++export const useOpacityScale = (data: IRow[], field: IViewField | null | undefined, defaultAggregate: boolean): Scale<number> => {+ const key = useMemo(() => {+ if (!field) {+ return '';+ }+ if (defaultAggregate && field.aggName && field.analyticType === 'measure') {+ return getMeaAggKey(field.fid, field.aggName);+ }+ 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;+ }+ if (val > acc[1]) {+ acc[1] = val;+ }+ 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]);+};diff --git a/packages/graphic-walker/src/components/leafletRenderer/geoConfigPanel.tsx b/packages/graphic-walker/src/components/leafletRenderer/geoConfigPanel.tsxnew file mode 100644index 00000000..57ea6c5c--- /dev/null+++ b/packages/graphic-walker/src/components/leafletRenderer/geoConfigPanel.tsx@@ -0,0 +1,197 @@+import { observer } from 'mobx-react-lite';+import React, { useEffect, useMemo, useState } from 'react';+import { useTranslation } from 'react-i18next';+import { runInAction } from 'mobx';+import { useGlobalStore } from '../../store';+import Modal from '../modal';+import PrimaryButton from '../button/primary';+import DefaultButton from '../button/default';+import type { Topology } from '../../interfaces';++const GeoConfigPanel: React.FC = (props) => {+ const { commonStore, vizStore } = useGlobalStore();+ const { showGeoJSONConfigPanel } = commonStore;+ const { visualConfig } = vizStore;+ const { geoKey, geojson } = visualConfig;+ const { t: tGlobal } = useTranslation('translation');+ const { t } = useTranslation('translation', { keyPrefix: 'main.tabpanel.settings' });++ const [dataMode, setDataMode] = useState<'GeoJSON' | 'TopoJSON'>('GeoJSON');+ const [featureId, setFeatureId] = useState('');+ const [url, setUrl] = useState('');+ const [geoJSON, setGeoJSON] = useState('');+ const [topoJSON, setTopoJSON] = useState('');+ const [topoJSONKey, setTopoJSONKey] = useState('');++ const defaultTopoJSONKey = useMemo(() => {+ try {+ const value = JSON.parse(topoJSON) as Topology;+ return Object.keys(value.objects)[0] || '';+ } catch (error) {+ return '';+ }+ }, [topoJSON]);++ useEffect(() => {+ setFeatureId(geoKey || '');+ }, [geoKey]);++ useEffect(() => {+ setGeoJSON(geojson ? JSON.stringify(geojson, null, 2) : '');+ }, [geojson]);++ return (+ <Modal+ show={showGeoJSONConfigPanel}+ onClose={() => {+ commonStore.setShowGeoJSONConfigPanel(false);+ }}+ >+ <div>+ <h2 className="text-lg mb-4">{t('geography')}</h2>+ <div>+ <div className="my-2">+ <label className="block text-xs font-medium leading-6 text-gray-900">{t('geography_settings.geoKey')}</label>+ <div className="mt-1">+ <input+ type="text"+ className="block w-full rounded-md border-0 py-1 px-2 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-1 focus:ring-inset focus:ring-indigo-600 sm:text-sm sm:leading-6"+ value={featureId}+ onChange={(e) => {+ setFeatureId(e.target.value);+ }}+ />+ </div>+ </div>+ <div className="my-2">+ <label className="block text-xs font-medium leading-6 text-gray-900">{t(`geography_settings.${dataMode.toLowerCase()}`)}</label>+ <div className="mt-1 flex flex-col space-y-2">+ <div role="radiogroup">+ <div className="flex items-center space-x-2">+ <input+ type="radio"+ name="dataMode"+ id="geojson"+ className="focus:ring-indigo-500 h-4 w-4 text-indigo-600 border-gray-300 dark:bg-gray-800 dark:border-gray-600"+ checked={dataMode === 'GeoJSON'}+ onChange={() => {+ setDataMode('GeoJSON');+ }}+ />+ <label htmlFor="geojson" className="text-xs whitespace-nowrap">+ {t('geography_settings.geojson')}+ </label>+ <input+ type="radio"+ name="dataMode"+ id="topojson"+ className="focus:ring-indigo-500 h-4 w-4 text-indigo-600 border-gray-300 dark:bg-gray-800 dark:border-gray-600"+ checked={dataMode === 'TopoJSON'}+ onChange={() => {+ setDataMode('TopoJSON');+ }}+ />+ <label htmlFor="topojson" className="text-xs whitespace-nowrap">+ {t('geography_settings.topojson')}+ </label>+ </div>+ </div>+ <div className="flex items-center space-x-2">+ <label className="text-xs whitespace-nowrap capitalize">+ {t('geography_settings.href', { format: dataMode.toLowerCase() })}+ </label>+ <input+ type="text"+ className="block w-full rounded-md border-0 py-1 px-2 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-1 focus:ring-inset focus:ring-indigo-600 sm:text-sm sm:leading-6"+ value={url}+ placeholder={t('geography_settings.hrefPlaceholder', { format: dataMode.toLowerCase() })}+ onChange={(e) => {+ setUrl(e.target.value);+ }}+ />+ <DefaultButton+ text={t('geography_settings.load')}+ className="mr-2"+ onClick={() => {+ if (url) {+ fetch(url)+ .then((res) => res.json())+ .then((json) => {+ (dataMode === 'GeoJSON' ? setGeoJSON : setTopoJSON)(+ JSON.stringify(json, null, 2)+ );+ });+ }+ }}+ />+ </div>+ <textarea+ className="block w-full h-40 rounded-md border-0 py-1 px-2 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-1 focus:ring-inset focus:ring-indigo-600 sm:text-sm sm:leading-6 resize-none"+ value={dataMode === 'GeoJSON' ? geoJSON : topoJSON}+ placeholder={t('geography_settings.jsonInputPlaceholder', { format: dataMode.toLowerCase() })}+ onChange={(e) => {+ (dataMode === 'GeoJSON' ? setGeoJSON : setTopoJSON)(e.target.value);+ }}+ />+ {dataMode === 'TopoJSON' && (+ <div className="flex items-center space-x-2">+ <label className="text-xs whitespace-nowrap capitalize">+ {t('geography_settings.objectKey')}+ </label>+ <input+ type="text"+ className="block w-full rounded-md border-0 py-1 px-2 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-1 focus:ring-inset focus:ring-indigo-600 sm:text-sm sm:leading-6"+ value={topoJSONKey}+ placeholder={defaultTopoJSONKey}+ onChange={(e) => {+ setTopoJSONKey(e.target.value);+ }}+ />+ </div>+ )}+ </div>+ </div>+ </div>+ <div className="mt-4">+ <PrimaryButton+ text={tGlobal('actions.confirm')}+ className="mr-2"+ onClick={() => {+ try {+ const json = JSON.parse(dataMode === 'GeoJSON' ? geoJSON : topoJSON);+ if (dataMode === 'TopoJSON') {+ runInAction(() => {+ vizStore.setGeographicData({+ type: 'TopoJSON',+ data: json,+ objectKey: topoJSONKey || defaultTopoJSONKey,+ }, featureId);+ });+ } else {+ runInAction(() => {+ vizStore.setGeographicData({+ type: 'GeoJSON',+ data: json,+ }, featureId);+ });+ }+ commonStore.setShowGeoJSONConfigPanel(false);+ } catch (err) {+ console.error(err);+ }+ }}+ />+ <DefaultButton+ text={tGlobal('actions.cancel')}+ className="mr-2"+ onClick={() => {+ commonStore.setShowGeoJSONConfigPanel(false);+ }}+ />+ </div>+ </div>+ </Modal>+ );+};++export default observer(GeoConfigPanel);diff --git a/packages/graphic-walker/src/components/leafletRenderer/index.tsx b/packages/graphic-walker/src/components/leafletRenderer/index.tsxnew file mode 100644index 00000000..2bb4ba78--- /dev/null+++ b/packages/graphic-walker/src/components/leafletRenderer/index.tsx@@ -0,0 +1,67 @@+import React, { forwardRef, useMemo } from "react";+import type { DeepReadonly, DraggableFieldState, IRow, IVisualConfig, VegaGlobalConfig } from "../../interfaces";+import POIRenderer from "./POIRenderer";+import ChoroplethRenderer from "./ChoroplethRenderer";+++export interface ILeafletRendererProps {+ vegaConfig?: VegaGlobalConfig;+ draggableFieldState: DeepReadonly<DraggableFieldState>;+ visualConfig: DeepReadonly<IVisualConfig>;+ data: IRow[];+}++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 { draggableFieldState, data, visualConfig, 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], geojson, geoKey = '', scaleIncludeUnmatchedChoropleth = false } = visualConfig;+ 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]);++ if (markType === 'poi') {+ return (+ <POIRenderer+ data={data}+ allFields={allFields}+ defaultAggregated={defaultAggregated}+ latitude={latitude}+ longitude={longitude}+ color={color}+ opacity={opacity}+ size={size}+ details={details}+ vegaConfig={vegaConfig}+ />+ );+ } else if (markType === 'choropleth') {+ return (+ <ChoroplethRenderer+ data={data}+ allFields={allFields}+ features={geojson}+ geoKey={geoKey}+ defaultAggregated={defaultAggregated}+ geoId={geoId}+ color={color}+ opacity={opacity}+ text={text}+ details={details}+ vegaConfig={vegaConfig}+ scaleIncludeUnmatchedChoropleth={scaleIncludeUnmatchedChoropleth}+ />+ );+ }++ return null;+});+++export default LeafletRenderer;diff --git a/packages/graphic-walker/src/components/leafletRenderer/tooltip.tsx b/packages/graphic-walker/src/components/leafletRenderer/tooltip.tsxnew file mode 100644index 00000000..87bdf405--- /dev/null+++ b/packages/graphic-walker/src/components/leafletRenderer/tooltip.tsx@@ -0,0 +1,24 @@+import React, { memo, useMemo } from "react";+import type { DeepReadonly, IViewField, VegaGlobalConfig } from "../../interfaces";+import { useDisplayValueFormatter } from "./utils";+++export interface ITooltipContentProps {+ allFields: readonly DeepReadonly<IViewField>[];+ vegaConfig: VegaGlobalConfig;+ field: DeepReadonly<IViewField>;+ value: unknown;+}++export const TooltipContent = memo<ITooltipContentProps>(function TooltipContent ({ allFields, vegaConfig, field, value }) {+ const { fid, analyticType, aggName } = field;+ const fieldDisplayLabel = useMemo(() => {+ const name = allFields.find(f => f.fid === fid)?.name ?? fid;+ return analyticType === 'measure' && aggName ? `${aggName}(${name})` : name;+ }, [allFields, fid, analyticType, aggName]);+ const formatter = useDisplayValueFormatter(field.semanticType, vegaConfig);++ return (+ <p>{fieldDisplayLabel}: {formatter(value)}</p>+ );+});diff --git a/packages/graphic-walker/src/components/leafletRenderer/utils.ts b/packages/graphic-walker/src/components/leafletRenderer/utils.tsnew file mode 100644index 00000000..48ff332e--- /dev/null+++ b/packages/graphic-walker/src/components/leafletRenderer/utils.ts@@ -0,0 +1,52 @@+import { useMemo } from "react";+import { timeFormat as tFormat } from "d3-time-format";+import { format } from "d3-format";+import type { Config as VlConfig } from 'vega-lite';+import type { ISemanticType, VegaGlobalConfig } from "../../interfaces";+++const defaultFormatter = (value: unknown): string => `${value}`;++export const useDisplayValueFormatter = (semanticType: ISemanticType, vegaConfig: VegaGlobalConfig): (value: unknown) => string => {+ const { timeFormat = "%b %d, %Y", numberFormat } = vegaConfig as Partial<VlConfig>;+ const timeFormatter = useMemo<(value: unknown) => string>(() => {+ const tf = tFormat(timeFormat);+ return (value: unknown) => {+ if (typeof value !== 'number' && typeof value !== 'string') {+ return '';+ }+ const date = new Date(value);+ if (isNaN(date.getTime())) {+ return 'Invalid Date';+ }+ return tf(date);+ };+ }, [timeFormat]);+ const numberFormatter = useMemo<(value: unknown) => string>(() => {+ if (!numberFormat) {+ return (value: unknown) => {+ if (typeof value !== 'number') {+ return '';+ }+ return value.toLocaleString();+ };+ }+ const nf = format(numberFormat);+ return (value: unknown) => {+ if (typeof value !== 'number') {+ return '';+ }+ return nf(value);+ };+ }, [numberFormat]);+ const formatter = useMemo(() => {+ if (semanticType === 'quantitative') {+ return numberFormatter;+ } else if (semanticType === 'temporal') {+ return timeFormatter;+ } else {+ return defaultFormatter;+ }+ }, [semanticType, numberFormatter, timeFormatter]);+ return formatter;+};diff --git a/packages/graphic-walker/src/components/visualConfig/index.tsx b/packages/graphic-walker/src/components/visualConfig/index.tsxindex 3a8ecdb2..62435e14 100644--- a/packages/graphic-walker/src/components/visualConfig/index.tsx+++ b/packages/graphic-walker/src/components/visualConfig/index.tsx@@ -1,5 +1,5 @@import { observer } from 'mobx-react-lite';-import React, { useEffect, useRef, useState } from 'react';+import React, { useEffect, useState } from 'react';import { useGlobalStore } from '../../store';import { NonPositionChannelConfigList,PositionChannelConfigList } from '../../config';@@ -15,6 +15,8 @@ const VisualConfigPanel: React.FC = (props) => {const { commonStore, vizStore } = useGlobalStore();const { showVisualConfigPanel } = commonStore;const { visualConfig } = vizStore;+ const { coordSystem, geoms: [markType] } = visualConfig;+ const isChoropleth = coordSystem === 'geographic' && markType === 'choropleth';const { t } = useTranslation();const formatConfigList: (keyof IVisualConfig['format'])[] = ['numberFormat',@@ -35,12 +37,14 @@ const VisualConfigPanel: React.FC = (props) => {size: visualConfig.resolve.size,});const [zeroScale, setZeroScale] = useState<boolean>(visualConfig.zeroScale);+ const [scaleIncludeUnmatchedChoropleth, setScaleIncludeUnmatchedChoropleth] = useState<boolean>(visualConfig.scaleIncludeUnmatchedChoropleth ?? false);const [background, setBackground] = useState<string | undefined>(visualConfig.background);useEffect(() => {setZeroScale(visualConfig.zeroScale);setBackground(visualConfig.background);setResolve(toJS(visualConfig.resolve));+ setScaleIncludeUnmatchedChoropleth(visualConfig.scaleIncludeUnmatchedChoropleth ?? false);setFormat({numberFormat: visualConfig.format.numberFormat,timeFormat: visualConfig.format.timeFormat,@@ -140,6 +144,17 @@ const VisualConfigPanel: React.FC = (props) => {}}/></div>+ {isChoropleth && (+ <div className="my-2">+ <Toggle+ label="include unmatched choropleth in scale"+ enabled={scaleIncludeUnmatchedChoropleth}+ onChange={(en) => {+ setScaleIncludeUnmatchedChoropleth(en);+ }}+ />+ </div>+ )}<div className="mt-4"><PrimaryButtontext={t('actions.confirm')}@@ -148,6 +163,7 @@ const VisualConfigPanel: React.FC = (props) => {runInAction(() => {vizStore.setVisualConfig('format', format);vizStore.setVisualConfig('zeroScale', zeroScale);+ vizStore.setVisualConfig('scaleIncludeUnmatchedChoropleth', scaleIncludeUnmatchedChoropleth);vizStore.setVisualConfig('background', background);vizStore.setVisualConfig('resolve', resolve);commonStore.setShowVisualConfigPanel(false);diff --git a/packages/graphic-walker/src/config.ts b/packages/graphic-walker/src/config.tsindex bab858dd..a3f0f7d1 100644--- a/packages/graphic-walker/src/config.ts+++ b/packages/graphic-walker/src/config.ts@@ -1,20 +1,31 @@-import { DraggableFieldState, IStackMode, IVisualConfig } from "./interfaces";+import { DraggableFieldState, ICoordMode, IStackMode, IVisualConfig } from "./interfaces";-export const GEMO_TYPES: Readonly<string[]> = [- 'auto',- 'bar',- 'line',- 'area',- 'trail',- 'point',- 'circle',- 'tick',- 'rect',- 'arc',- 'text',- 'boxplot',- 'table'-] as const;+export const GEMO_TYPES: Record<ICoordMode, Readonly<string[]>> = {+ generic: [+ 'auto',+ 'bar',+ 'line',+ 'area',+ 'trail',+ 'point',+ 'circle',+ 'tick',+ 'rect',+ 'arc',+ 'text',+ 'boxplot',+ 'table',+ ],+ geographic: [+ 'poi',+ 'choropleth',+ ],+} as const;++export const COORD_TYPES: Readonly<ICoordMode[]> = [+ 'generic',+ 'geographic',+];export const STACK_MODE: Readonly<IStackMode[]> = ['none',diff --git a/packages/graphic-walker/src/fields/aestheticFields.tsx b/packages/graphic-walker/src/fields/aestheticFields.tsxindex 27ec766e..99dc41b5 100644--- a/packages/graphic-walker/src/fields/aestheticFields.tsx+++ b/packages/graphic-walker/src/fields/aestheticFields.tsx@@ -26,6 +26,10 @@ const AestheticFields: React.FC = props => {return aestheticFields.filter(f => f.id === 'text' || f.id === 'color' || f.id === 'size' || f.id === 'opacity');case 'table':return []+ case 'poi':+ return aestheticFields.filter(f => f.id === 'color' || f.id === 'opacity' || f.id === 'size' || f.id === 'details');+ case 'choropleth':+ return aestheticFields.filter(f => f.id === 'color' || f.id === 'opacity' || f.id === 'text' || f.id === 'details');default:return aestheticFields.filter(f => f.id !== 'text');}diff --git a/packages/graphic-walker/src/fields/fieldsContext.tsx b/packages/graphic-walker/src/fields/fieldsContext.tsxindex 32f2a18d..5aa3ffe1 100644--- a/packages/graphic-walker/src/fields/fieldsContext.tsx+++ b/packages/graphic-walker/src/fields/fieldsContext.tsx@@ -48,6 +48,9 @@ export const DRAGGABLE_STATE_KEYS: Readonly<IDraggableStateKey[]> = [{ id: 'shape', mode: 1},{ id: 'theta', mode: 1 },{ id: 'radius', mode: 1 },+ { id: 'longitude', mode: 1 },+ { id: 'latitude', mode: 1 },+ { id: 'geoId', mode: 1 },{ id: 'filters', mode: 1 },{ id: 'details', mode: 1 },{ id: 'text', mode: 1 },diff --git a/packages/graphic-walker/src/fields/posFields/index.tsx b/packages/graphic-walker/src/fields/posFields/index.tsxindex dfb380d5..821c5be2 100644--- a/packages/graphic-walker/src/fields/posFields/index.tsx+++ b/packages/graphic-walker/src/fields/posFields/index.tsx@@ -9,14 +9,20 @@ import OBFieldContainer from '../obComponents/obFContainer';const PosFields: React.FC = props => {const { vizStore } = useGlobalStore();const { visualConfig } = vizStore;- const { geoms } = visualConfig;+ const { geoms, coordSystem = 'generic' } = visualConfig;const channels = useMemo(() => {+ if (coordSystem === 'geographic') {+ if (geoms[0] === 'choropleth') {+ return DRAGGABLE_STATE_KEYS.filter(f => f.id === 'geoId');+ }+ return DRAGGABLE_STATE_KEYS.filter(f => f.id === 'longitude' || f.id === 'latitude');+ }if (geoms[0] === 'arc') {return DRAGGABLE_STATE_KEYS.filter(f => f.id === 'radius' || f.id === 'theta');}return DRAGGABLE_STATE_KEYS.filter(f => f.id === 'columns' || f.id === 'rows');- }, [geoms[0]])+ }, [geoms[0], coordSystem])return <div>{channels.map(dkey => <FieldListContainer name={dkey.id} key={dkey.id}>diff --git a/packages/graphic-walker/src/interfaces.ts b/packages/graphic-walker/src/interfaces.tsindex 4626a6a0..c146767a 100644--- a/packages/graphic-walker/src/interfaces.ts+++ b/packages/graphic-walker/src/interfaces.ts@@ -1,5 +1,7 @@import {Config as VgConfig, View} from 'vega';import {Config as VlConfig} from 'vega-lite';+import type { FeatureCollection } from 'geojson';+import type { feature } from 'topojson-client';import type {IViewQuery} from "./lib/viewQuery";export type DeepReadonly<T extends Record<keyof any, any>> = {@@ -86,6 +88,8 @@ export interface IExpression {as: string;}+export type IGeoRole = 'longitude' | 'latitude' | 'none';+export interface IField {/*** fid: key in data record@@ -101,6 +105,7 @@ export interface IField {aggName?: string;semanticType: ISemanticType;analyticType: IAnalyticType;+ geoRole?: IGeoRole;cmp?: (a: any, b: any) => number;computed?: boolean;expression?: IExpression;@@ -183,6 +188,9 @@ export interface DraggableFieldState {shape: IViewField[];theta: IViewField[];radius: IViewField[];+ longitude: IViewField[];+ latitude: IViewField[];+ geoId: IViewField[];details: IViewField[];filters: IFilterField[];text: IViewField[];@@ -209,14 +217,20 @@ export type IFilterRule =export type IStackMode = 'none' | 'stack' | 'normalize' | 'zero' | 'center';+export type ICoordMode = 'generic' | 'geographic';+export interface IVisualConfig {defaultAggregated: boolean;geoms: string[];+ /** @default "generic" */+ coordSystem?: ICoordMode;stack: IStackMode;showActions: boolean;interactiveScale: boolean;sorted: ISortMode;zeroScale: boolean;+ /** @default false */+ scaleIncludeUnmatchedChoropleth?: boolean;background?: string;format: {numberFormat?: string;@@ -236,6 +250,8 @@ export interface IVisualConfig {width: number;height: number;};+ geojson?: FeatureCollection;+ geoKey?: string;limit: number;}@@ -448,3 +464,20 @@ export type IResponse<T> = (};});++export type Topology = Parameters<typeof feature>[0];++export type IGeographicData = (+ | {+ type: 'GeoJSON';+ data: FeatureCollection;+ }+ | {+ type: 'TopoJSON';+ data: Topology;+ /**+ * default to the first key of `objects` in Topology+ */+ objectKey?: string;+ }+);diff --git a/packages/graphic-walker/src/locales/en-US.json b/packages/graphic-walker/src/locales/en-US.jsonindex 8330453e..c6e3897d 100644--- a/packages/graphic-walker/src/locales/en-US.json+++ b/packages/graphic-walker/src/locales/en-US.json@@ -39,7 +39,14 @@"arc": "Arc","boxplot": "Box (Box Plot)","table": "Table",- "text": "Text"+ "text": "Text",+ "poi": "POI",+ "choropleth": "Choropleth"+ },+ "coord_system": {+ "__enum__": "Coordinate System",+ "generic": "Generic",+ "geographic": "Geographic"},"stack_mode": {"__enum__": "Stack Mode",@@ -77,7 +84,10 @@"radius": "Radius","filters": "Filters","details": "Details",- "text": "Text"+ "text": "Text",+ "longitude": "Longitude",+ "latitude": "Latitude",+ "geoId": "Geometry ID"},"aggregator": {"sum": "Sum",@@ -168,6 +178,18 @@"size_setting": {"width": "Width","height": "Height"+ },+ "geography": "Geography Configuration",+ "geography_settings": {+ "geoKey": "Feature ID",+ "format": "Format",+ "geojson": "GeoJSON",+ "topojson": "TopoJSON",+ "objectKey": "Extract Feature Key",+ "jsonInputPlaceholder": "Paste {{format}} here",+ "href": "{{format}} URL",+ "hrefPlaceholder": "Enter {{format}} URL",+ "load": "Load"}},"DatasetFields": {diff --git a/packages/graphic-walker/src/locales/ja-JP.json b/packages/graphic-walker/src/locales/ja-JP.jsonindex 99256942..fafed3b7 100644--- a/packages/graphic-walker/src/locales/ja-JP.json+++ b/packages/graphic-walker/src/locales/ja-JP.json@@ -39,7 +39,14 @@"arc": "アーク","boxplot": "ボックスプロット","table": "表",- "text": "本文"+ "text": "テキスト",+ "poi": "POI",+ "choropleth": "コロプレス"+ },+ "coord_system": {+ "__enum__": "座標系",+ "generic": "ジェネリック",+ "geographic": "地理"},"stack_mode": {"__enum__": "スタックモード",@@ -76,7 +83,10 @@"theta": "角度","radius": "半径","filters": "フィルター",- "text": "本文"+ "text": "本文",+ "longitude": "経度",+ "latitude": "緯度",+ "geoId": "地理ID"},"aggregator": {"sum": "合計",@@ -167,6 +177,18 @@"size_setting": {"width": "幅","height": "高さ"+ },+ "geography": "地理情報設定",+ "geography_settings": {+ "geoKey": "フィーチャーID",+ "format": "データ形式",+ "geojson": "GeoJSON",+ "topojson": "TopoJSON",+ "objectKey": "Feature のキー",+ "jsonInputPlaceholder": "{{format}}をここに貼り付けてください",+ "href": "{{format}} URL",+ "hrefPlaceholder": "{{format}} URLを入力",+ "load": "ロード"}},"DatasetFields": {diff --git a/packages/graphic-walker/src/locales/zh-CN.json b/packages/graphic-walker/src/locales/zh-CN.jsonindex b95133af..d2d5335e 100644--- a/packages/graphic-walker/src/locales/zh-CN.json+++ b/packages/graphic-walker/src/locales/zh-CN.json@@ -39,7 +39,14 @@"arc": "弧形","boxplot": "统计箱","table": "表格",- "text": "文本"+ "text": "文本",+ "poi": "兴趣点",+ "choropleth": "区域图"+ },+ "coord_system": {+ "__enum__": "坐标系统",+ "generic": "通用",+ "geographic": "地理"},"layout_type": {"__enum__": "尺寸模式",@@ -77,7 +84,10 @@"radius": "半径","filters": "筛选器","details": "信息",- "text": "文本"+ "text": "文本",+ "longitude": "经度",+ "latitude": "纬度",+ "geoId": "地理 ID"},"aggregator": {"sum": "求和",@@ -168,6 +178,18 @@"size_setting": {"width": "宽度","height": "高度"+ },+ "geography": "地理信息配置",+ "geography_settings": {+ "geoKey": "地理 ID",+ "format": "数据格式",+ "geojson": "GeoJSON",+ "topojson": "TopoJSON",+ "objectKey": "提取要素键",+ "jsonInputPlaceholder": "在此粘贴 {{format}}",+ "href": "{{format}} URL",+ "hrefPlaceholder": "输入在线资源地址",+ "load": "加载"}},"DatasetFields": {diff --git a/packages/graphic-walker/src/renderer/index.tsx b/packages/graphic-walker/src/renderer/index.tsxindex 7402ecb2..fffa5b9e 100644--- a/packages/graphic-walker/src/renderer/index.tsx+++ b/packages/graphic-walker/src/renderer/index.tsx@@ -8,8 +8,9 @@ import { useGlobalStore } from '../store';import { IReactVegaHandler } from '../vis/react-vega';import { unstable_batchedUpdates } from 'react-dom';import { useRenderer } from './hooks';-import { initEncoding } from '../store/visualSpecStore';+import { initEncoding } from '../utils/save';import { useChartIndexControl } from '../utils/chartIndexControl';+import { LEAFLET_DEFAULT_HEIGHT, LEAFLET_DEFAULT_WIDTH } from '../components/leafletRenderer';import { initVisualConfig } from '../utils/save';interface RendererProps {@@ -102,6 +103,27 @@ const Renderer = forwardRef<IReactVegaHandler, RendererProps>(function (props, r[vizStore]);+ const isSpatial = viewConfig.coordSystem === 'geographic';++ const sizeRef = useRef(viewConfig.size);+ sizeRef.current = viewConfig.size;++ useEffect(() => {+ if (isSpatial) {+ const prevSizeConfig = sizeRef.current;+ if (sizeRef.current.width < LEAFLET_DEFAULT_WIDTH || sizeRef.current.height < LEAFLET_DEFAULT_HEIGHT) {+ vizStore.setChartLayout({+ mode: sizeRef.current.mode,+ width: Math.max(prevSizeConfig.width, LEAFLET_DEFAULT_WIDTH),+ height: Math.max(prevSizeConfig.height, LEAFLET_DEFAULT_HEIGHT),+ });+ return () => {+ vizStore.setChartLayout(prevSizeConfig);+ };+ }+ }+ }, [isSpatial, vizStore]);+return (<SpecRenderername={chart?.name}diff --git a/packages/graphic-walker/src/renderer/pureRenderer.tsx b/packages/graphic-walker/src/renderer/pureRenderer.tsxindex 2b6f4648..fe7e008b 100644--- a/packages/graphic-walker/src/renderer/pureRenderer.tsx+++ b/packages/graphic-walker/src/renderer/pureRenderer.tsx@@ -3,6 +3,7 @@ import { unstable_batchedUpdates } from 'react-dom';import { toJS } from 'mobx';import { observer } from 'mobx-react-lite';import { ShadowDom } from '../shadow-dom';+import LeafletRenderer from '../components/leafletRenderer';import { withAppRoot } from '../components/appRoot';import type {IDarkMode,@@ -99,20 +100,32 @@ const PureRenderer = forwardRef<IReactVegaHandler, IPureRendererProps>(function}}, [waiting]);+ const { coordSystem = 'generic' } = visualConfig;+ const isSpatial = coordSystem === 'geographic';+return (<ShadowDom><div className="relative">- <SpecRenderer- name={name}- loading={waiting}- data={viewData}- ref={ref}- themeKey={themeKey}- dark={dark}- draggableFieldState={visualState}- visualConfig={visualConfig}- locale={locale ?? 'en-US'}- />+ {isSpatial && (+ <LeafletRenderer+ data={data}+ draggableFieldState={visualState}+ visualConfig={visualConfig}+ />+ )}+ {isSpatial || (+ <SpecRenderer+ name={name}+ loading={waiting}+ data={viewData}+ ref={ref}+ themeKey={themeKey}+ dark={dark}+ draggableFieldState={visualState}+ visualConfig={visualConfig}+ locale={locale ?? 'en-US'}+ />+ )}</div></ShadowDom>);diff --git a/packages/graphic-walker/src/renderer/specRenderer.tsx b/packages/graphic-walker/src/renderer/specRenderer.tsxindex 8ce9051e..d7bda8d3 100644--- a/packages/graphic-walker/src/renderer/specRenderer.tsx+++ b/packages/graphic-walker/src/renderer/specRenderer.tsx@@ -3,6 +3,7 @@ import { Resizable } from 're-resizable';import React, { forwardRef, useMemo } from 'react';import PivotTable from '../components/pivotTable';+import LeafletRenderer from '../components/leafletRenderer';import ReactVega, { IReactVegaHandler } from '../vis/react-vega';import { DeepReadonly, DraggableFieldState, IDarkMode, IRow, IThemeKey, IVisualConfig, VegaGlobalConfig } from '../interfaces';import LoadingLayer from '../components/loadingLayer';@@ -30,7 +31,7 @@ const SpecRenderer = forwardRef<IReactVegaHandler, SpecRendererProps>(function (ref) {// const { draggableFieldState, visualConfig } = vizStore;- const { geoms, interactiveScale, defaultAggregated, stack, showActions, size, format: _format, background, zeroScale, resolve } = visualConfig;+ const { geoms, coordSystem = 'generic', interactiveScale, defaultAggregated, stack, showActions, size, format: _format, background, zeroScale, resolve } = visualConfig;const rows = draggableFieldState.rows;const columns = draggableFieldState.columns;@@ -112,6 +113,8 @@ const SpecRenderer = forwardRef<IReactVegaHandler, SpecRendererProps>(function ();}+ const isSpatial = coordSystem === 'geographic';+return (<ResizableclassName={enableResize ? 'border-blue-400 border-2 overflow-hidden' : ''}@@ -139,33 +142,43 @@ const SpecRenderer = forwardRef<IReactVegaHandler, SpecRendererProps>(function (}}>{loading && <LoadingLayer />}- <ReactVega- name={name}- vegaConfig={vegaConfig}- // format={format}- layoutMode={size.mode}- interactiveScale={interactiveScale}- geomType={geoms[0]}- defaultAggregate={defaultAggregated}- stack={stack}- dataSource={data}- rows={rows}- columns={columns}- color={color[0]}- theta={theta[0]}- radius={radius[0]}- shape={shape[0]}- opacity={opacity[0]}- size={sizeChannel[0]}- details={details}- text={text[0]}- showActions={showActions}- width={size.width - 12 * 4}- height={size.height - 12 * 4}- ref={ref}- onGeomClick={onGeomClick}- locale={locale}- />+ {isSpatial && (+ <LeafletRenderer+ data={data}+ draggableFieldState={draggableFieldState}+ visualConfig={visualConfig}+ vegaConfig={vegaConfig}+ />+ )}+ {isSpatial || (+ <ReactVega+ name={name}+ vegaConfig={vegaConfig}+ // format={format}+ layoutMode={size.mode}+ interactiveScale={interactiveScale}+ geomType={geoms[0]}+ defaultAggregate={defaultAggregated}+ stack={stack}+ dataSource={data}+ rows={rows}+ columns={columns}+ color={color[0]}+ theta={theta[0]}+ radius={radius[0]}+ shape={shape[0]}+ opacity={opacity[0]}+ size={sizeChannel[0]}+ details={details}+ text={text[0]}+ showActions={showActions}+ width={size.width - 12 * 4}+ height={size.height - 12 * 4}+ ref={ref}+ onGeomClick={onGeomClick}+ locale={locale}+ />+ )}</Resizable>);});diff --git a/packages/graphic-walker/src/shadow-dom.tsx b/packages/graphic-walker/src/shadow-dom.tsxindex 22922989..ad543363 100644--- a/packages/graphic-walker/src/shadow-dom.tsx+++ b/packages/graphic-walker/src/shadow-dom.tsx@@ -36,6 +36,13 @@ export const ShadowDom: React.FC<IShadowDomProps> = function ShadowDom ({ onMoun<root.div {...attrs} mode="open" ref={rootRef}><style>{tailwindStyle}</style><style>{style}</style>+ {/* Leaflet CSS file */}+ <link+ rel="stylesheet"+ href="https://unpkg.com/[email protected]/dist/leaflet.css"+ integrity="sha256-p4NxAoJBhIIN+hmNHrzRCf9tD/miZyoHS5obTRR9BMY="+ crossOrigin=""+ />{shadowRoot && (<StyleSheetManager target={shadowRoot}><ShadowDomContext.Provider value={{ root: shadowRoot }}>diff --git a/packages/graphic-walker/src/store/commonStore.ts b/packages/graphic-walker/src/store/commonStore.tsindex 78bd735a..15747311 100644--- a/packages/graphic-walker/src/store/commonStore.ts+++ b/packages/graphic-walker/src/store/commonStore.ts@@ -15,6 +15,7 @@ export class CommonStore {public showDataConfig: boolean = false;public showCodeExportPanel: boolean = false;public showVisualConfigPanel: boolean = false;+ public showGeoJSONConfigPanel: boolean = false;public filters: Filters = {};public segmentKey: ISegmentKey = ISegmentKey.vis;constructor () {@@ -68,6 +69,9 @@ export class CommonStore {public setShowVisualConfigPanel (show: boolean) {this.showVisualConfigPanel = show;}+ public setShowGeoJSONConfigPanel (show: boolean) {+ this.showGeoJSONConfigPanel = show;+ }public closeEmbededMenu () {this.vizEmbededMenu.show = false;}diff --git a/packages/graphic-walker/src/store/visualSpecStore.ts b/packages/graphic-walker/src/store/visualSpecStore.tsindex c7ba74b4..bf7c3dd4 100644--- a/packages/graphic-walker/src/store/visualSpecStore.ts+++ b/packages/graphic-walker/src/store/visualSpecStore.ts@@ -1,9 +1,12 @@import { IReactionDisposer, makeAutoObservable, observable, computed, reaction, toJS } from 'mobx';import produce from 'immer';+import { feature } from 'topojson-client';+import type { FeatureCollection } from "geojson";import {DataSet,DraggableFieldState,IFilterRule,+ IGeographicData,ISortMode,IStackMode,IViewField,@@ -25,6 +28,7 @@ import {initVisualConfig,forwardVisualConfigs,visSpecDecoder,+ initEncoding,} from '../utils/save';import { CommonStore } from './commonStore';import { createCountField } from '../utils';@@ -68,24 +72,6 @@ function geomAdapter(geom: string) {}}-export function initEncoding(): DraggableFieldState {- return {- dimensions: [],- measures: [],- rows: [],- columns: [],- color: [],- opacity: [],- size: [],- shape: [],- radius: [],- theta: [],- details: [],- filters: [],- text: [],- };-}-function stackValueTransform(vlValue: string | undefined | null): IStackMode {if (vlValue === 'center') return 'center';if (vlValue === 'normalize') return 'normalize';@@ -387,10 +373,11 @@ export class VizSpecStore {public setVisualConfig<K extends keyof IVisualConfig>(configKey: K, value: IVisualConfig[K]) {this.useMutable(({ config }) => {switch (true) {- case ['defaultAggregated', 'defaultStack', 'showActions', 'interactiveScale'].includes(configKey): {+ case ['defaultAggregated', 'defaultStack', 'showActions', 'interactiveScale', 'scaleIncludeUnmatchedChoropleth'].includes(configKey): {return ((config as unknown as { [k: string]: boolean })[configKey] = Boolean(value));}case configKey === 'geoms' && Array.isArray(value):+ case configKey === "coordSystem":case configKey === 'size' && typeof value === 'object':case configKey === 'sorted':case configKey === 'zeroScale':@@ -511,6 +498,10 @@ export class VizSpecStore {encodings.columns = encodings.rows;encodings.rows = fieldsInCup as typeof encodings.rows; // assume this as writable++ const fieldsInCup2 = encodings.longitude;+ encodings.longitude = encodings.latitude;+ encodings.latitude = fieldsInCup2 as typeof encodings.latitude; // assume this as writable});}public createBinField(stateKey: keyof DraggableFieldState, index: number, binType: 'bin' | 'binCount'): string {@@ -819,6 +810,23 @@ export class VizSpecStore {const content = parseGWContent(raw);this.importStoInfo(content);}++ public setGeographicData(data: IGeographicData, geoKey: string) {+ const geoJSON = data.type === 'GeoJSON' ? data.data : feature(data.data, data.objectKey || Object.keys(data.data.objects)[0]) as unknown as FeatureCollection;+ if (!('features' in geoJSON)) {+ console.error('Invalid GeoJSON: GeoJSON must be a FeatureCollection, but got', geoJSON);+ return;+ }+ this.useMutable(({ config }) => {+ config.geojson = geoJSON;+ config.geoKey = geoKey;+ });+ }+ public updateGeoKey(key: string) {+ this.useMutable(({ config }) => {+ config.geoKey = key;+ });+ }private visSpecEncoder(visList: IVisSpec[]): IVisSpecForExport[] {const updatedVisList = visList.map((visSpec) => {diff --git a/packages/graphic-walker/src/utils/save.ts b/packages/graphic-walker/src/utils/save.tsindex e28a1ccf..fc8c5c16 100644--- a/packages/graphic-walker/src/utils/save.ts+++ b/packages/graphic-walker/src/utils/save.ts@@ -11,15 +11,38 @@ export function parseGWPureSpec(list: IVisSpec[]): VisSpecWithHistory[] {return list.map((l) => new VisSpecWithHistory(l));}+export function initEncoding(): DraggableFieldState {+ return {+ dimensions: [],+ measures: [],+ rows: [],+ columns: [],+ color: [],+ opacity: [],+ size: [],+ shape: [],+ radius: [],+ theta: [],+ longitude: [],+ latitude: [],+ geoId: [],+ details: [],+ filters: [],+ text: [],+ };+}+export function initVisualConfig(): IVisualConfig {return {defaultAggregated: true,geoms: [GEMO_TYPES[0]!],+ coordSystem: 'generic',stack: 'stack',showActions: false,interactiveScale: false,sorted: 'none',zeroScale: true,+ scaleIncludeUnmatchedChoropleth: false,background: undefined,size: {mode: "auto",@@ -31,6 +54,7 @@ export function initVisualConfig(): IVisualConfig {timeFormat: undefined,normalizedNumberFormat: undefined,},+ geoKey: 'name',resolve: {x: false,y: false,@@ -60,6 +84,7 @@ export function visSpecDecoder(visList: IVisSpecForExport[]): IVisSpec[] {return {...visSpec,encodings: {+ ...initEncoding(),...visSpec.encodings,filters: updatedFilters,},diff --git a/packages/graphic-walker/src/visualSettings/index.tsx b/packages/graphic-walker/src/visualSettings/index.tsxindex 95c62af4..836fdd66 100644--- a/packages/graphic-walker/src/visualSettings/index.tsx+++ b/packages/graphic-walker/src/visualSettings/index.tsx@@ -19,6 +19,10 @@ import {LightBulbIcon,CodeBracketSquareIcon,Cog6ToothIcon,+ MapPinIcon,+ GlobeAltIcon,+ RectangleGroupIcon,+ GlobeAmericasIcon,HashtagIcon,} from '@heroicons/react/24/outline';import { observer } from 'mobx-react-lite';@@ -26,7 +30,7 @@ import React, { SVGProps, useCallback, useMemo } from 'react';import styled from 'styled-components';import { useTranslation } from 'react-i18next';import { ResizeDialog } from '../components/sizeSetting';-import { GEMO_TYPES, STACK_MODE, CHART_LAYOUT_TYPE } from '../config';+import { GEMO_TYPES, STACK_MODE, CHART_LAYOUT_TYPE, COORD_TYPES } from '../config';import { useGlobalStore } from '../store';import { IStackMode, IDarkMode } from '../interfaces';import { IReactVegaHandler } from '../vis/react-vega';@@ -82,6 +86,7 @@ const VisualSettings: React.FC<IVisualSettings> = ({const {defaultAggregated,geoms: [markType],+ coordSystem = 'generic',stack,interactiveScale,size: { mode: sizeMode, width, height },@@ -163,7 +168,7 @@ const VisualSettings: React.FC<IVisualSettings> = ({color: 'rgb(294,115,22)',},},- options: GEMO_TYPES.map((g) => ({+ options: GEMO_TYPES[coordSystem].map((g) => ({key: g,label: tGlobal(`constant.mark_type.${g}`),icon: {@@ -348,6 +353,8 @@ const VisualSettings: React.FC<IVisualSettings> = ({/></svg>),+ poi: MapPinIcon,+ choropleth: RectangleGroupIcon,}[g],})),value: markType,@@ -438,6 +445,34 @@ const VisualSettings: React.FC<IVisualSettings> = ({),},'-',+ {+ key: 'coord_system',+ label: tGlobal('constant.coord_system.__enum__'),+ icon: StopIcon,+ options: COORD_TYPES.map(c => ({+ key: c,+ label: tGlobal(`constant.coord_system.${c}`),+ icon: {+ generic: (props: SVGProps<SVGSVGElement>) => <svg stroke="currentColor" fill="none" strokeWidth="1.5" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" aria-hidden {...props}><path strokeLinecap="round" strokeLinejoin="round" d="M2 12h20M12 2v20" /><path strokeLinecap="round" strokeLinejoin="round" d="M12 7h2M12 16h2M7 12v-2M16 12v-2"/></svg>,+ geographic: GlobeAltIcon,+ }[c],+ })),+ value: coordSystem,+ onSelect: value => {+ const coord = value as typeof COORD_TYPES[number];+ vizStore.setVisualConfig('coordSystem', coord);+ vizStore.setVisualConfig('geoms', [GEMO_TYPES[coord][0]]);+ },+ },+ coordSystem === 'geographic' && markType === 'choropleth' && {+ key: 'geojson',+ label: t('button.geojson'),+ icon: GlobeAmericasIcon,+ onClick: () => {+ commonStore.setShowGeoJSONConfigPanel(true);+ },+ },+ '-',{key: 'debug',label: t('toggle.debug'),@@ -447,7 +482,7 @@ const VisualSettings: React.FC<IVisualSettings> = ({vizStore.setVisualConfig('showActions', checked);},},- {+ ...coordSystem === 'generic' ?[{key: 'export_chart',label: t('button.export_chart'),icon: PhotoIcon,@@ -477,7 +512,7 @@ const VisualSettings: React.FC<IVisualSettings> = ({</button></FormContainer>),- },+ }]:[],{key: 'config',label: 'config',@@ -529,7 +564,7 @@ const VisualSettings: React.FC<IVisualSettings> = ({</a>),},- ] as ToolbarItemProps[];+ ].filter(Boolean) as ToolbarItemProps[];const items = builtInItems.filter((item) => typeof item === 'string' || !exclude.includes(item.key));@@ -540,6 +575,7 @@ const VisualSettings: React.FC<IVisualSettings> = ({canRedo,defaultAggregated,markType,+ coordSystem,stack,interactiveScale,sizeMode,diff --git a/yarn.lock b/yarn.lockindex 8bce2bf0..f5e465ce 100644--- a/yarn.lock+++ b/yarn.lock@@ -553,6 +553,77 @@"@jridgewell/resolve-uri" "3.1.0""@jridgewell/sourcemap-codec" "1.4.14"+"@kanaries/[email protected]":+ version "0.3.10"+ resolved "https://registry.npmmirror.com/@kanaries/graphic-walker/-/graphic-walker-0.3.10.tgz#55e071389ef7673b6d9ede377a0ce02e960e62b0"+ integrity sha512-xLGVDHZAihgh23wSwZeF3dcLQ5TfU+y02WvUL/CF8mf8OSsDJoVtqNmpHsXHEsXk/G1ZFs10DLsrimKGxfw+CA==+ dependencies:+ "@headlessui/react" "^1.7.12"+ "@heroicons/react" "^2.0.8"+ "@kanaries/graphic-walker" "0.3.9"+ "@kanaries/react-beautiful-dnd" "0.0.2"+ "@kanaries/web-data-loader" "^0.1.7"+ autoprefixer "^10.3.5"+ i18next "^21.9.1"+ i18next-browser-languagedetector "^6.1.5"+ immer "^9.0.15"+ mobx "^6.3.3"+ mobx-react-lite "^3.2.1"+ nanoid "^4.0.2"+ postcss "^8.3.7"+ postinstall-postinstall "^2.1.0"+ re-resizable "^6.9.8"+ react-i18next "^11.18.6"+ react-shadow "^20.0.0"+ rxjs "^7.3.0"+ tailwindcss "^3.2.4"+ uuid "^8.3.2"+ vega "^5.22.1"+ vega-embed "^6.21.0"+ vega-lite "^5.6.0"++"@kanaries/[email protected]":+ version "0.3.9"+ resolved "https://registry.npmmirror.com/@kanaries/graphic-walker/-/graphic-walker-0.3.9.tgz#cd2d090503fae366769a95b86a92676a44ed1ad2"+ integrity sha512-ox7WE7bUX5M71L7DIRFWi8hrABthN0KET/f3ODOt8iMfJ7cHd8j+7hkzMkeyB2zCj1CV2vw7f4xnNhf8dTCt0g==+ dependencies:+ "@headlessui/react" "^1.7.12"+ "@heroicons/react" "^2.0.8"+ "@kanaries/graphic-walker" "0.3.9"+ "@kanaries/react-beautiful-dnd" "0.0.1"+ "@kanaries/web-data-loader" "^0.1.7"+ autoprefixer "^10.3.5"+ i18next "^21.9.1"+ i18next-browser-languagedetector "^6.1.5"+ immer "^9.0.15"+ mobx "^6.3.3"+ mobx-react-lite "^3.2.1"+ nanoid "^4.0.2"+ postcss "^8.3.7"+ postinstall-postinstall "^2.1.0"+ re-resizable "^6.9.8"+ react-i18next "^11.18.6"+ react-shadow "^20.0.0"+ rxjs "^7.3.0"+ tailwindcss "^3.2.4"+ uuid "^8.3.2"+ vega "^5.22.1"+ vega-embed "^6.21.0"+ vega-lite "^5.6.0"++"@kanaries/[email protected]":+ version "0.0.1"+ resolved "https://registry.npmmirror.com/@kanaries/react-beautiful-dnd/-/react-beautiful-dnd-0.0.1.tgz#18369ecd87649ff3d939ef0559e0e38f848de0b3"+ integrity sha512-4gUYrpNXOU+mLZ/Dsl/rGkmEEdxZ70pq2d2vMLIbeuGo+qCJSHL2UC5sTXfS6bAZcjcjBsim1ZpCwVc/EO2PYg==+ dependencies:+ "@babel/runtime" "^7.9.2"+ css-box-model "^1.2.0"+ memoize-one "^5.1.1"+ raf-schd "^4.0.2"+ react-redux "^7.2.0"+ redux "^4.0.4"+ use-memo-one "^1.1.1"+"@kanaries/[email protected]":version "0.0.2"resolved "https://registry.npmjs.org/@kanaries/react-beautiful-dnd/-/react-beautiful-dnd-0.0.2.tgz#2d8b5284b185189ae3927612e80bbd423eed477f"@@ -595,6 +666,11 @@"@nodelib/fs.scandir" "2.1.5"fastq "^1.6.0"+"@react-leaflet/core@^2.1.0":+ version "2.1.0"+ resolved "https://registry.npmmirror.com/@react-leaflet/core/-/core-2.1.0.tgz#383acd31259d7c9ae8fb1b02d5e18fe613c2a13d"+ integrity sha512-Qk7Pfu8BSarKGqILj4x7bCSZ1pjuAPZ+qmRwH5S7mDS91VSbVVsJSrW4qA+GPrro8t69gFYVMWb1Zc4yFmPiVg==+"@rollup/plugin-typescript@^8.2.5":version "8.5.0"resolved "https://registry.yarnpkg.com/@rollup/plugin-typescript/-/plugin-typescript-8.5.0.tgz#7ea11599a15b0a30fa7ea69ce3b791d41b862515"@@ -689,6 +765,28 @@resolved "https://registry.yarnpkg.com/@types/clone/-/clone-2.1.1.tgz#9b880d0ce9b1f209b5e0bd6d9caa38209db34024"integrity sha512-BZIU34bSYye0j/BFcPraiDZ5ka6MJADjcDVELGf7glr9K+iE8NYVjFslJFVWzskSxkLLyCrSPScE82/UUoBSvg==+"@types/d3-format@^3.0.1":+ version "3.0.1"+ resolved "https://registry.npmmirror.com/@types/d3-format/-/d3-format-3.0.1.tgz#194f1317a499edd7e58766f96735bdc0216bb89d"+ integrity sha512-5KY70ifCCzorkLuIkDe0Z9YTf9RR2CjBX1iaJG+rgM/cPP+sO+q9YdQ9WdhQcgPj1EQiJ2/0+yUkkziTG6Lubg==++"@types/d3-scale@^4.0.3":+ version "4.0.3"+ resolved "https://registry.npmmirror.com/@types/d3-scale/-/d3-scale-4.0.3.tgz#7a5780e934e52b6f63ad9c24b105e33dd58102b5"+ integrity sha512-PATBiMCpvHJSMtZAMEhc2WyL+hnzarKzI6wAHYjhsonjWJYGq5BXTzQjv4l8m2jO183/4wZ90rKvSeT7o72xNQ==+ dependencies:+ "@types/d3-time" "*"++"@types/d3-time-format@^4.0.0":+ version "4.0.0"+ resolved "https://registry.npmmirror.com/@types/d3-time-format/-/d3-time-format-4.0.0.tgz#ee7b6e798f8deb2d9640675f8811d0253aaa1946"+ integrity sha512-yjfBUe6DJBsDin2BMIulhSHmr5qNR5Pxs17+oW4DoVPyVIXZ+m6bs7j1UVKP08Emv6jRmYrYqxYzO63mQxy1rw==++"@types/d3-time@*":+ version "3.0.0"+ resolved "https://registry.npmmirror.com/@types/d3-time/-/d3-time-3.0.0.tgz#e1ac0f3e9e195135361fa1a1d62f795d87e6e819"+ integrity sha512-sZLCdHvBUcNby1cB6Fd3ZBrABbjz3v1Vm90nysCQ6Vt7vd6e/h9Lt7SiJUoEX0l4Dzc7P5llKyhqSi1ycSf1Hg==+"@types/[email protected]":version "0.0.39"resolved "https://registry.yarnpkg.com/@types/estree/-/estree-0.0.39.tgz#e177e699ee1b8c22d23174caaa7422644389509f"@@ -699,6 +797,11 @@resolved "https://registry.yarnpkg.com/@types/estree/-/estree-0.0.50.tgz#1e0caa9364d3fccd2931c3ed96fdbeaa5d4cca83"integrity sha512-C6N5s2ZFtuZRj54k2/zyRhNDjJwwcViAM3Nbm8zjBpbqAdZ00mr0CFxvSKeO8Y/e03WVFLpQMdHYVfUd6SB+Hw==+"@types/geojson@*", "@types/geojson@^7946.0.10":+ version "7946.0.10"+ resolved "https://registry.npmmirror.com/@types/geojson/-/geojson-7946.0.10.tgz#6dfbf5ea17142f7f9a043809f1cd4c448cb68249"+ integrity sha512-Nmh0K3iWQJzniTuPRcJn5hxXkfB1T1pgB89SBig5PlJQU5yocazeu4jATJlaA0GYFKWMqDdvYemoSnF2pXgLVA==+"@types/hoist-non-react-statics@*", "@types/hoist-non-react-statics@^3.3.0":version "3.3.1"resolved "https://registry.yarnpkg.com/@types/hoist-non-react-statics/-/hoist-non-react-statics-3.3.1.tgz#1124aafe5118cb591977aeb1ceaaed1070eb039f"@@ -712,6 +815,13 @@resolved "https://registry.yarnpkg.com/@types/js-cookie/-/js-cookie-2.2.7.tgz#226a9e31680835a6188e887f3988e60c04d3f6a3"integrity sha512-aLkWa0C0vO5b4Sr798E26QgOkss68Un0bLjs7u9qxzPT5CG+8DuNTffWES58YzJs3hrVAOs1wonycqEBqNJubA==+"@types/leaflet@^1.9.3":+ version "1.9.3"+ resolved "https://registry.npmmirror.com/@types/leaflet/-/leaflet-1.9.3.tgz#7aac302189eb3aa283f444316167995df42a5467"+ integrity sha512-Caa1lYOgKVqDkDZVWkto2Z5JtVo09spEaUt2S69LiugbBpoqQu92HYFMGUbYezZbnBkyOxMNPXHSgRrRY5UyIA==+ dependencies:+ "@types/geojson" "*"+"@types/node@*", "@types/node@^18.7.10":version "18.14.1"resolved "https://registry.yarnpkg.com/@types/node/-/node-18.14.1.tgz#90dad8476f1e42797c49d6f8b69aaf9f876fc69f"@@ -776,6 +886,21 @@"@types/react" "*"csstype "^3.0.2"+"@types/topojson-client@^3.1.1":+ version "3.1.1"+ resolved "https://registry.npmmirror.com/@types/topojson-client/-/topojson-client-3.1.1.tgz#d1396b2e79f530ef69bb162523cddf94576bd5a9"+ integrity sha512-E4/Z2Xg56kVLRzYWem/6uOKVcVNqqxEqlWM9qCG2tCV1BxuzvvXC02/ELoGJWgtKkQhfycBPlMFEuTFdA/YiTg==+ dependencies:+ "@types/geojson" "*"+ "@types/topojson-specification" "*"++"@types/topojson-specification@*":+ version "1.0.2"+ resolved "https://registry.npmmirror.com/@types/topojson-specification/-/topojson-specification-1.0.2.tgz#e20df2c5a611e31f51d606473dbaccc1d90461c8"+ integrity sha512-SGc1NdX9g3UGDp6S+p+uyG+Z8CehS51sUJ9bejA25Xgn2kkAguILk6J9nxXK+0M/mbTBN7ypMA7+4HVLNMJ8ag==+ dependencies:+ "@types/geojson" "*"+"@types/uuid@^8.3.1":version "8.3.4"resolved "https://registry.yarnpkg.com/@types/uuid/-/uuid-8.3.4.tgz#bd86a43617df0594787d38b735f55c805becf1bc"@@ -1160,7 +1285,7 @@ d3-path@^3.0.1, d3-path@^3.1.0:d3-scale@^4.0.2:version "4.0.2"- resolved "https://registry.yarnpkg.com/d3-scale/-/d3-scale-4.0.2.tgz#82b38e8e8ff7080764f8dcec77bd4be393689396"+ resolved "https://registry.npmmirror.com/d3-scale/-/d3-scale-4.0.2.tgz#82b38e8e8ff7080764f8dcec77bd4be393689396"integrity sha512-GZW464g1SH7ag3Y7hXjf8RoUuAFIqklOAq3MRl4OaWabTFJY9PN/E1YklhXLh+OQ3fM9yS2nOkCoS+WLZ6kvxQ==dependencies:d3-array "2.10.0 - 3"@@ -1684,6 +1809,11 @@ json5@^2.2.2:resolved "https://registry.yarnpkg.com/json5/-/json5-2.2.3.tgz#78cd6f1a19bdc12b73db5ad0c61efd66c1e29283"integrity sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==+leaflet@^1.9.4:+ version "1.9.4"+ resolved "https://registry.npmmirror.com/leaflet/-/leaflet-1.9.4.tgz#23fae724e282fa25745aff82ca4d394748db7d8d"+ integrity sha512-nxS1ynzJOmOlHp+iL3FyWqK89GtNL8U8rvlMOsQdTTssxZwCXh8N2NB3GDQOL+YR3XnWyZAxwQixURb+FA74PA==+lilconfig@^2.0.5, lilconfig@^2.0.6:version "2.0.6"resolved "https://registry.yarnpkg.com/lilconfig/-/lilconfig-2.0.6.tgz#32a384558bd58af3d4c6e077dd1ad1d397bc69d4"@@ -1986,6 +2116,13 @@ react-is@^17.0.2:resolved "https://registry.yarnpkg.com/react-is/-/react-is-17.0.2.tgz#e691d4a8e9c789365655539ab372762b0efb54f0"integrity sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==+react-leaflet@^4.2.1:+ version "4.2.1"+ resolved "https://registry.npmmirror.com/react-leaflet/-/react-leaflet-4.2.1.tgz#c300e9eccaf15cb40757552e181200aa10b94780"+ integrity sha512-p9chkvhcKrWn/H/1FFeVSqLdReGwn2qmiobOQGO3BifX+/vV/39qhY8dGqbdcPh1e6jxh/QHriLXr7a4eLFK4Q==+ dependencies:+ "@react-leaflet/core" "^2.1.0"+react-redux@^7.2.0:version "7.2.9"resolved "https://registry.yarnpkg.com/react-redux/-/react-redux-7.2.9.tgz#09488fbb9416a4efe3735b7235055442b042481d"@@ -2342,7 +2479,7 @@ toggle-selection@^1.0.6:topojson-client@^3.1.0:version "3.1.0"- resolved "https://registry.yarnpkg.com/topojson-client/-/topojson-client-3.1.0.tgz#22e8b1ed08a2b922feeb4af6f53b6ef09a467b99"+ resolved "https://registry.npmmirror.com/topojson-client/-/topojson-client-3.1.0.tgz#22e8b1ed08a2b922feeb4af6f53b6ef09a467b99"integrity sha512-605uxS6bcYxGXw9qi62XyrV6Q3xwbndjachmNxu8HWTtVPxZfEJN9fd/SZS1Q54Sn2y0TMyMxFj/cJINqGHrKw==dependencies:commander "2"