An open source alternative to Tableau. Embeddable visual analytic
TypeScript bidatadata-analysisdata-miningdata-visualizationedak6skanarieslow-codepivot-tablereacttableautableau-alternativetypescriptvegavega-litevisualization
fix(map): report unmatched regions and fix choropleth rendering (#531)
Elwynn Chen244d1d485cc4
diff --git a/packages/graphic-walker/public/tersespec_v1.json b/packages/graphic-walker/public/tersespec_v1.jsonindex f2c77022..33d21fb7 100644--- a/packages/graphic-walker/public/tersespec_v1.json+++ b/packages/graphic-walker/public/tersespec_v1.json@@ -878,6 +878,10 @@},"url": {"type": "string"+ },+ "objectKey": {+ "type": "string",+ "description": "For TopoJSON: the name of the object to draw. Defaults to the first key of `objects`."}},"required": [diff --git a/packages/graphic-walker/src/components/leafletRenderer/ChoroplethRenderer.tsx b/packages/graphic-walker/src/components/leafletRenderer/ChoroplethRenderer.tsxindex 4f1779d4..3665e6a2 100644--- a/packages/graphic-walker/src/components/leafletRenderer/ChoroplethRenderer.tsx+++ b/packages/graphic-walker/src/components/leafletRenderer/ChoroplethRenderer.tsx@@ -1,20 +1,21 @@import React, { Fragment, forwardRef, useContext, useEffect, useImperativeHandle, useMemo, useRef } from 'react';-import { CircleMarker, MapContainer, Polygon, Marker, TileLayer, Tooltip, AttributionControl } from 'react-leaflet';+import { CircleMarker, MapContainer, Polygon, Polyline, 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 type { FeatureCollection } from 'geojson';import { getMeaAggKey, getMeaAggName } 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 { useGeoData } from '../../hooks/service';import { useTranslation } from 'react-i18next';-import { ChangeView } from './utils';+import { ChangeView, useDisplayValueFormatter } from './utils';import ColorPanel from './color';-import { getColor } from '@/utils/useTheme';-import { field } from 'vega';import { themeContext } from '@/store/theme';+import { WORLD_BOUNDS, extendBounds, resolveParts, ringCentroid, type GeoPart, type LatLngBounds } from '../../lib/geo/geometry';+import { featureKeyValue, geoValueText, matchFeatures, quoteGeoValue } from '../../lib/geo/matching';+import { geoDataErrorOf } from '../../lib/geo/parse';+import { GeoLoadFailed, GeoNotice, type GeoNoticeContent } from './geoNotice';export interface IChoroplethRendererProps {name?: string;@@ -38,64 +39,69 @@ export interface IChoroplethRendererProps {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 [];- }- }+/** A label as a DOM node. The text goes in as text, so markup in the data stays inert. */+const labelIcon = (label: string) => {+ const node = document.createElement('div');+ node.style.cssText = 'font-size: 11px; transform: translate(-50%, -50%); opacity: 0.8;';+ node.textContent = label;+ return divIcon({ className: '!bg-transparent !border-none', html: node });};-const resolveCenter = (coordinates: [lat: number, lng: number][]): [lng: number, lat: number] => {- let area = 0;- let centroid: [lat: number, lng: number] = [0, 0];+const fieldKey = (field: DeepReadonly<IViewField>, defaultAggregated: boolean) =>+ defaultAggregated && field.analyticType === 'measure' && field.aggName ? getMeaAggKey(field.fid, field.aggName) : field.fid;- 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;+interface IShapeStyle {+ fill: string;+ fillOpacity: number;+ border: string;+}- centroid[0] += (x1 + x2) * tempArea;- centroid[1] += (y1 + y2) * tempArea;+/** Draws one piece of a feature. `children` is its tooltip. */+function GeoShape({ part, style, label, children }: { part: GeoPart; style: IShapeStyle; label?: string; children?: React.ReactNode }) {+ if (part.type === 'point') {+ return (+ <CircleMarker+ center={part.position}+ radius={3}+ opacity={0.8}+ fillOpacity={style.fillOpacity}+ fillColor={style.fill}+ color={style.border}+ weight={1}+ stroke+ fill+ >+ {children}+ </CircleMarker>+ );}-- area /= 2;-- centroid[0] /= 6 * area;- centroid[1] /= 6 * area;-- return centroid;-};+ if (part.type === 'line') {+ return (+ <Polyline positions={part.positions} pathOptions={{ color: style.fill, opacity: Math.max(style.fillOpacity, 0.3), weight: 2 }}>+ {children}+ </Polyline>+ );+ }+ const centre = label ? ringCentroid(part.rings[0]) : null;+ return (+ <>+ <Polygon+ positions={part.rings}+ pathOptions={{+ fillOpacity: style.fillOpacity * 0.8,+ fillColor: style.fill,+ color: style.border,+ weight: 1,+ stroke: true,+ fill: true,+ }}+ >+ {children}+ </Polygon>+ {label && centre && <Marker position={centre} interactive={false} icon={labelIcon(label)} />}+ </>+ );+}const ChoroplethRenderer = forwardRef<IChoroplethRendererRef, IChoroplethRendererProps>(function ChoroplethRenderer(props, ref) {const {@@ -122,107 +128,45 @@ const ChoroplethRenderer = forwardRef<IChoroplethRendererRef, IChoroplethRendereuseImperativeHandle(ref, () => ({}));- const features = useGeoJSON(localFeatures, featuresUrl);+ const geo = useGeoData(localFeatures, featuresUrl);+ const features = geo.data;const { t } = useTranslation('translation');- const geoIndices: string[] = useMemo(() => {- if (geoId) {- return data.map((row) => row[geoId.fid]);- }- return [];- }, [geoId, data]);+ const geoValues = useMemo<unknown[]>(() => (geoId ? data.map((row) => row[geoId.fid]) : []), [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 && f.properties[geoKey] === id) : undefined;- if (feature) {- indices.push(i);- }- return feature;- });- return [indices, shapes];- }- return [[], []];- }, [geoIndices, features, geoKey]);+ const match = useMemo(() => (features ? matchFeatures(geoValues, features.features, geoKey) : undefined), [geoValues, features, geoKey]);- const missingDataGeoShapes = useMemo(() => {- if (showAllGeoshapeInChoropleth && features) {- const indices = new Set(geoIndices);- return features.features- .filter((x) => x.properties)- .filter((x) => !indices.has(x.properties![geoKey]))- .map((f) => ({ coords: resolveCoords(f.geometry), name: f.properties![geoKey] }));- }- return [];- }, [geoIndices, features, showAllGeoshapeInChoropleth, geoKey]);+ /** The drawable pieces of a feature, worked out on first use. */+ const partsOf = useMemo(() => {+ const cache: GeoPart[][] = [];+ return (index: number) => (cache[index] ??= resolveParts(features?.features[index]?.geometry));+ }, [features]);- 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.`- );+ const bounds = useMemo<LatLngBounds>(() => {+ if (!match) return WORLD_BOUNDS;+ let found: LatLngBounds | null = null;+ const seen = new Set<number>();+ for (const row of match.matchedRows) {+ for (const index of match.rowFeatures[row]) {+ if (seen.has(index)) continue;+ seen.add(index);+ found = extendBounds(found, partsOf(index));}}- }, [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 (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]];+ if (!found && showAllGeoshapeInChoropleth) {+ for (const index of match.unusedFeatures) {+ found = extendBounds(found, partsOf(index));+ }}-- return [- [- [-180, -90],- [180, 90],- ],- [0, 0],- ];- }, [lngLat]);+ return found ?? WORLD_BOUNDS;+ }, [match, partsOf, showAllGeoshapeInChoropleth]);const distribution = useMemo(() => {- if (scaleIncludeUnmatchedChoropleth) {+ if (scaleIncludeUnmatchedChoropleth || !match) {return data;}- return indices.map((i) => data[i]);- }, [data, indices, scaleIncludeUnmatchedChoropleth]);+ return match.matchedRows.map((i) => data[i]);+ }, [data, match, scaleIncludeUnmatchedChoropleth]);const opacityScale = useOpacityScale(distribution, opacity, defaultAggregated, scales);const { mapper: colorScale, display: colorDisplay } = useColorScale(distribution, color, defaultAggregated, vegaConfig);@@ -230,10 +174,106 @@ const ChoroplethRenderer = forwardRef<IChoroplethRendererRef, IChoroplethRendereconst 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,+ key: fieldKey(f, defaultAggregated),}));}, [defaultAggregated, details, color, opacity]);+ const textKey = text ? fieldKey(text, defaultAggregated) : '';+ const formatText = useDisplayValueFormatter(text?.semanticType ?? 'nominal', vegaConfig);+ /** A region without data can still carry its name, when names are what the labels show. */+ const labelsShowGeoId = Boolean(text && geoId && text.fid === geoId.fid);++ const border = darkMode === 'dark' ? '#fff4' : '#0004';++ const shapes = useMemo(() => {+ if (!match || !features || !geoId) return null;+ const labelOf = (row: IRow) => {+ const value = textKey ? row[textKey] : undefined;+ return value === undefined || value === null || value === '' ? '' : formatText(value);+ };+ return match.matchedRows.flatMap((i) => {+ const row = data[i];+ const style: IShapeStyle = { fill: colorScale(row), fillOpacity: opacityScale(row), border };+ const label = labelOf(row);+ const header = geoValueText(row[geoId.fid]);+ return match.rowFeatures[i].flatMap((index) =>+ partsOf(index).map((part, j) => (+ <GeoShape key={`${i}-${index}-${j}-${style.fillOpacity}-${style.fill}`} part={part} style={style} label={label}>+ {(part.type !== 'point' || tooltipFields.length > 0) && (+ <Tooltip>+ <header>{header}</header>+ {tooltipFields.map((f, k) => (+ <TooltipContent key={k} allFields={allFields} vegaConfig={vegaConfig} field={f} value={row[f.key]} />+ ))}+ </Tooltip>+ )}+ </GeoShape>+ ))+ );+ });+ }, [match, features, geoId, data, partsOf, colorScale, opacityScale, border, textKey, formatText, tooltipFields, allFields, vegaConfig]);++ const missingShapes = useMemo(() => {+ if (!match || !features || !showAllGeoshapeInChoropleth) return null;+ const style: IShapeStyle = { fill: '#808080', fillOpacity: 0.3, border };+ return match.unusedFeatures.flatMap((index) => {+ const name = geoValueText(featureKeyValue(features.features[index], geoKey));+ return partsOf(index).map((part, j) => (+ <GeoShape key={`missing-${index}-${j}`} part={part} style={style} label={labelsShowGeoId ? name : ''}>+ {(part.type !== 'point' || tooltipFields.length > 0) && (+ <Tooltip>+ <header>{name}</header>+ {tooltipFields.map((f, k) => (+ <p key={k}>{f.analyticType === 'measure' && f.aggName ? getMeaAggName(f.name, f.aggName) : f.name}: Null</p>+ ))}+ </Tooltip>+ )}+ </GeoShape>+ ));+ });+ }, [match, features, showAllGeoshapeInChoropleth, geoKey, partsOf, border, labelsShowGeoId, tooltipFields]);++ /** Values that found a shape with no geometry, so nothing shows where the reader expects a region. */+ const undrawnValues = useMemo(() => {+ if (!match) return [];+ const seen = new Set<string>();+ const undrawn: string[] = [];+ for (const row of match.matchedRows) {+ const value = geoValueText(geoValues[row]);+ if (seen.has(value)) continue;+ seen.add(value);+ if (match.rowFeatures[row].every((index) => partsOf(index).length === 0)) undrawn.push(value);+ }+ return undrawn;+ }, [match, geoValues, partsOf]);++ const notice = useMemo<GeoNoticeContent | null>(() => {+ if (!features) return localFeatures || featuresUrl ? null : { state: 'no_data' };+ if (!geoId) return { state: 'no_field' };+ if (!match || data.length === 0) return null;+ if (match.keyedFeatures === 0) return { state: 'bad_key', key: geoKey };+ if (match.unmatchedRows === 0 && match.emptyRows === 0 && match.sharedValues.length === 0 && undrawnValues.length === 0) return null;+ return {+ state: 'match',+ key: geoKey,+ matched: match.matchedValues,+ total: match.distinctValues,+ unmatchedValues: match.unmatchedValues,+ featureSamples: match.unmatchedRows > 0 ? match.featureSamples : [],+ emptyRows: match.emptyRows,+ sharedValues: match.sharedValues.map((group) => group.map(quoteGeoValue)),+ undrawnValues,+ };+ }, [features, localFeatures, featuresUrl, geoId, match, data, geoKey, undrawnValues]);++ useEffect(() => {+ if (match && match.unmatchedRows > 0) {+ console.warn(+ `Failed to render ${match.unmatchedRows.toLocaleString()} items of ${data.length.toLocaleString()} rows due to missing geojson feature.`+ );+ }+ }, [match]);+const mapRef = useRef<Map>(null);useEffect(() => {const container = mapRef.current?.getContainer();@@ -265,22 +305,15 @@ const ChoroplethRenderer = forwardRef<IChoroplethRendererRef, IChoroplethRendere}}, []);- if (!features && (localFeatures || featuresUrl)) {+ if (geo.loading) {return <div className="flex items-center justify-center w-full h-full">{t('main.tabpanel.settings.geography_settings.loading')}</div>;}-- const border = darkMode === 'dark' ? '#fff4' : '#0004';+ if (geo.error) {+ return <GeoLoadFailed error={geoDataErrorOf(geo.error)} onRetry={geo.retry} />;+ }return (- <MapContainer- preferCanvas- attributionControl={false}- center={center}- ref={mapRef}- zoom={5}- bounds={bounds}- style={{ width: '100%', height: '100%', zIndex: 1 }}- >+ <MapContainer preferCanvas attributionControl={false} ref={mapRef} zoom={5} bounds={bounds} style={{ width: '100%', height: '100%', zIndex: 1 }}><ChangeView bounds={bounds} />{tileUrl === undefined && (<TileLayer@@ -291,143 +324,10 @@ const ChoroplethRenderer = forwardRef<IChoroplethRendererRef, IChoroplethRendere)}{tileUrl && <TileLayer className="map-tile" url={tileUrl} />}<AttributionControl prefix="Leaflet" />- {lngLat.length > 0 &&- data.flatMap((row, i) => {- const coords = lngLat[i];- const opacity = opacityScale(row);- const color = colorScale(row);- return coords.map((coord, j) => {- if (coord.length === 0) {- return null;- }- if (coord.length === 1) {- return (- <CircleMarker- key={`${i}-${opacity}-${color}-${j}`}- center={coord[0]}- radius={3}- opacity={0.8}- fillOpacity={opacity}- fillColor={color}- color={border}- 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={`${i}-${opacity}-${color}-${j}`}>- <Polygon- positions={coord}- pathOptions={{- fillOpacity: opacity * 0.8,- fillColor: color,- color: border,- 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>- );- });- })}- {missingDataGeoShapes.flatMap(({ coords, name }, i) => {- const opacity = 0.3;- const color = '#808080';- return coords.map((coord, j) => {- if (coord.length === 0) {- return null;- }- if (coord.length === 1) {- return (- <CircleMarker- key={`missing-${i}-${j}`}- center={coord[0]}- radius={3}- opacity={0.8}- fillOpacity={opacity}- fillColor={color}- color={border}- weight={1}- stroke- fill- >- {tooltipFields.length > 0 && (- <Tooltip>- <header>{name}</header>- {tooltipFields.map((f, j) => (- <p key={j}>{f.analyticType === 'measure' && f.aggName ? getMeaAggName(f.name, f.aggName) : f.name}: Null</p>- ))}- </Tooltip>- )}- </CircleMarker>- );- }- const center: [lat: number, lng: number] = text && coord.length >= 3 ? resolveCenter(coord) : [NaN, NaN];- return (- <Fragment key={`missing-${i}-${j}`}>- <Polygon- positions={coord}- pathOptions={{- fillOpacity: opacity * 0.8,- fillColor: color,- color: border,- weight: 1,- stroke: true,- fill: true,- }}- >- <Tooltip>- <header>{name}</header>- {tooltipFields.map((f, j) => (- <p key={j}>{f.analyticType === 'measure' && f.aggName ? getMeaAggName(f.name, f.aggName) : f.name}: Null</p>- ))}- </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>- );- });- })}+ {shapes}+ {missingShapes}{colorDisplay && <ColorPanel display={colorDisplay} field={color!} />}+ {notice && <GeoNotice notice={notice} />}</MapContainer>);});diff --git a/packages/graphic-walker/src/components/leafletRenderer/POIRenderer.tsx b/packages/graphic-walker/src/components/leafletRenderer/POIRenderer.tsxindex edddc3b1..6d4404c8 100644--- a/packages/graphic-walker/src/components/leafletRenderer/POIRenderer.tsx+++ b/packages/graphic-walker/src/components/leafletRenderer/POIRenderer.tsx@@ -8,6 +8,7 @@ import { TooltipContent } from './tooltip';import { useAppRootContext } from '../appRoot';import { ChangeView } from './utils';import ColorPanel from './color';+import { WORLD_BOUNDS } from '../../lib/geo/geometry';export interface IPOIRendererProps {name?: string;@@ -77,13 +78,7 @@ const POIRenderer = forwardRef<IPOIRendererRef, IPOIRendererProps>(function POIRreturn [bounds, [coords[0] / lngLat.length, coords[1] / lngLat.length] as [number, number]];}- return [- [- [-180, -90],- [180, 90],- ],- [0, 0],- ];+ return [WORLD_BOUNDS, [0, 0]];}, [lngLat]);const mapRef = useRef<Map>(null);diff --git a/packages/graphic-walker/src/components/leafletRenderer/geoConfigPanel.tsx b/packages/graphic-walker/src/components/leafletRenderer/geoConfigPanel.tsxindex 46375cdd..020a80a5 100644--- a/packages/graphic-walker/src/components/leafletRenderer/geoConfigPanel.tsx+++ b/packages/graphic-walker/src/components/leafletRenderer/geoConfigPanel.tsx@@ -1,5 +1,5 @@import { observer } from 'mobx-react-lite';-import React, { useEffect, useMemo, useState } from 'react';+import React, { useContext, useEffect, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';import { useVizStore } from '../../store';import Spinner from '../spinner';@@ -8,32 +8,50 @@ import DropdownSelect from '../dropdownSelect';import Dropzone from 'react-dropzone';import { GeojsonRenderer } from './geojsonRenderer';import { Button } from '../ui/button';-import { Dialog, DialogContent, DialogFooter } from '../ui/dialog';+import { Dialog, DialogContent, DialogFooter, DialogTitle } from '../ui/dialog';import { Input } from '../ui/input';import { RadioGroup, RadioGroupItem } from '../ui/radio-group';+import { useGeoData } from '../../hooks/service';+import { fetchGeoJson, geoDataErrorOf, isTopology, parseGeoText, toFeatureCollection, topologyObjectKeys, type GeoDataErrorCode } from '../../lib/geo/parse';+import { listFeatureKeys, suggestFeatureKey } from '../../lib/geo/matching';+import { useGeoErrorText } from './geoNotice';+import { themeContext, vegaThemeContext } from '../../store/theme';+import { getTheme } from '../../utils/useTheme';const emptyList = [];+/** A file or URL the user has loaded in this dialog and not yet confirmed. */+interface ILoadedSource {+ json: unknown;+ /** Where it came from, when it was loaded by URL. */+ url?: string;+}+const GeoConfigPanel = ({ geoList = emptyList }: { geoList?: IGeoDataItem[] }) => {const vizStore = useVizStore();const { layout, showGeoJSONConfigPanel } = vizStore;const { geoKey, geojson, geoUrl } = layout;const { t: tGlobal } = useTranslation('translation');const { t } = useTranslation('translation', { keyPrefix: 'main.tabpanel.settings' });+ const errorText = useGeoErrorText();+ // The preview draws the basemap the chart draws: the chart's own setting, else the host theme's.+ const { vizThemeConfig } = useContext(vegaThemeContext);+ const mediaTheme = useContext(themeContext);+ const tileUrl = layout.geoMapTileUrl ?? getTheme({ vizThemeConfig, mediaTheme })?.leafletGeoTileUrl;const [dataMode, setDataMode] = useState<'GeoJSON' | 'TopoJSON'>(geoUrl?.type ?? 'GeoJSON');const [featureId, setFeatureId] = useState('');const [url, setUrl] = useState(geoUrl?.url ?? '');- const [geoJSON, setGeoJSON] = useState('');- const [topoJSON, setTopoJSON] = useState('');- const [topoJSONKey, setTopoJSONKey] = useState('');- const [loadedUrl, setLoadedUrl] = useState<IGeoUrl | undefined>(geoUrl);+ const [source, setSource] = useState<ILoadedSource>();+ const [objectKey, setObjectKey] = useState('');const [loading, setLoading] = useState(false);+ const [error, setError] = useState<{ code: GeoDataErrorCode | 'empty'; detail: string }>();const hasCustomData = url || geojson;const [selectItem, setSelectItemR] = useState(() => {- const i = geoList.findIndex((x) => x.url === geoUrl?.url && x.type === geoUrl?.type);+ // Two presets can draw different objects of one TopoJSON file, so the object is part of which preset it is.+ const i = geoList.findIndex((x) => x.url === geoUrl?.url && x.type === geoUrl?.type && (x.objectKey ?? '') === (geoUrl?.objectKey ?? ''));if (i === -1 && hasCustomData) {return -2;}@@ -42,84 +60,150 @@ const GeoConfigPanel = ({ geoList = emptyList }: { geoList?: IGeoDataItem[] }) =const options = useMemo(() =>- [{ label: 'Select a Geographic Data', value: '-1' }]+ [{ label: t('geography_settings.selectData'), value: '-1' }].concat(geoList.map((x, i) => ({label: x.name,value: `${i}`,})))- .concat({ label: 'Manual Configuration', value: '-2' }),- [geoList]+ .concat({ label: t('geography_settings.manual'), value: '-2' }),+ [geoList, t]+ );+ const setSelectItem = useMemo(+ () => (a: string) => {+ setSelectItemR(parseInt(a));+ setError(undefined);+ },+ []);- const setSelectItem = useMemo(() => (a: string) => setSelectItemR(parseInt(a)), []);const isCustom = (geoList ?? []).length === 0 || selectItem === -2;- const defaultTopoJSONKey = useMemo(() => {+ // The shapes the dialog is looking at: a preset, a file loaded here, or what the chart already has.+ const listItem = !isCustom && selectItem >= 0 ? geoList[selectItem] : undefined;+ const savedUrl = isCustom && !source && !geojson ? geoUrl : undefined;+ const remoteUrl = useMemo<IGeoUrl | undefined>(+ () => (listItem ? { type: listItem.type, url: listItem.url, ...(listItem.objectKey ? { objectKey: listItem.objectKey } : {}) } : savedUrl),+ [listItem, savedUrl]+ );+ const remote = useGeoData(undefined, remoteUrl);+ const loaded = useMemo(() => {+ if (!source) return undefined;try {- const value = JSON.parse(topoJSON) as Topology;- return Object.keys(value.objects)[0] || '';- } catch (error) {- return '';+ return toFeatureCollection(source.json, objectKey || undefined);+ } catch {+ return undefined;}- }, [topoJSON]);+ }, [source, objectKey]);+ const features = isCustom ? loaded ?? (source ? undefined : geojson) ?? remote.data : remote.data;++ const topologyObjects = useMemo(() => (source ? topologyObjectKeys(source.json) : []), [source]);+ const featureKeys = useMemo(() => (features ? listFeatureKeys(features.features) : []), [features]);+ const featureKeyOptions = useMemo(+ () =>+ featureKeys.map(({ key, samples }) => ({+ value: key,+ label: (+ <span>+ {key}+ <span className="ml-2 text-muted-foreground">{t('geography_settings.geoKeySample', { samples: samples.join(', ') })}</span>+ </span>+ ),+ })),+ [featureKeys, t]+ );useEffect(() => {setFeatureId(geoKey || '');}, [geoKey]);useEffect(() => {- setGeoJSON(geojson ? JSON.stringify(geojson, null, 2) : '');- }, [geojson]);+ // A key the file does not have would match nothing, so move to one it has.+ if (featureKeys.length > 0) setFeatureId((current) => suggestFeatureKey(featureKeys, current));+ }, [featureKeys]);++ // Confirming saves the key on show, so the key has to belong to the shapes on show.+ // - While a preset, a saved address or a typed address is on its way, the key still belongs to+ // the shapes before it, and for a typed address the new shapes would not be saved at all.+ // - Shapes without any property cannot be matched to data, so there is no key to save.+ // - A preset that failed to load has no shapes to check the key against.+ const busy = loading || remote.loading;+ const noKeys = Boolean(features) && featureKeys.length === 0;+ const canConfirm = !busy && (features ? featureKeys.some((k) => k.key === featureId) : !listItem);++ /** Takes over a parsed file once it is known to hold shapes. Throws a GeoDataError when it does not. */+ const acceptSource = (json: unknown, fromUrl?: string) => {+ toFeatureCollection(json);+ setSource({ json, url: fromUrl });+ setObjectKey('');+ setDataMode(isTopology(json) ? 'TopoJSON' : 'GeoJSON');+ setError(undefined);+ };++ const loadUrl = () => {+ if (!url) return;+ setLoading(true);+ setError(undefined);+ fetchGeoJson(url)+ .then((json) => acceptSource(json, url))+ .catch((e) => setError(geoDataErrorOf(e)))+ .finally(() => setLoading(false));+ };++ const loadFile = (file: File) => {+ const reader = new FileReader();+ reader.addEventListener('load', (event) => {+ try {+ acceptSource(parseGeoText(event.target!.result as string));+ } catch (e) {+ setError(geoDataErrorOf(e));+ }+ });+ reader.addEventListener('error', () => setError({ code: 'network', detail: '' }));+ reader.readAsText(file);+ };const handleSubmit = () => {if (!isCustom) {- const item = geoList[selectItem];- if (!item) {+ if (!listItem) {vizStore.clearGeographicData();vizStore.updateGeoKey(featureId);} else {- vizStore.setVisualLayout('geoUrl', {- type: item.type,- url: item.url,- });+ vizStore.setGeoUrl(remoteUrl!, featureId);}vizStore.setShowGeoJSONConfigPanel(false);return;}- try {- if (!(dataMode === 'GeoJSON' ? geoJSON : topoJSON) && loadedUrl) {- vizStore.setShowGeoJSONConfigPanel(false);+ if (source) {+ if (!loaded) {+ setError({ code: 'format', detail: '' });return;}- const json = JSON.parse(dataMode === 'GeoJSON' ? geoJSON : topoJSON);- if (dataMode === 'TopoJSON') {- vizStore.setGeographicData(- {- type: 'TopoJSON',- data: json,- objectKey: topoJSONKey || defaultTopoJSONKey,- },- featureId,- loadedUrl?.type === 'TopoJSON' ? loadedUrl : undefined- );- } else {- vizStore.setGeographicData(- {- type: 'GeoJSON',- data: json,- },- featureId,- loadedUrl?.type === 'GeoJSON' ? loadedUrl : undefined- );- }- vizStore.setShowGeoJSONConfigPanel(false);- } catch (err) {- console.error(err);+ const topology = isTopology(source.json);+ const pickedObject = objectKey || topologyObjects[0];+ const from: IGeoUrl | undefined = source.url+ ? { type: topology ? 'TopoJSON' : 'GeoJSON', url: source.url, ...(topology && objectKey ? { objectKey } : {}) }+ : undefined;+ vizStore.setGeographicData(+ topology ? { type: 'TopoJSON', data: source.json as Topology, objectKey: pickedObject } : { type: 'GeoJSON', data: loaded },+ featureId,+ from+ );+ } else if (geojson) {+ // The shapes are the ones the chart already has. Only the match key can have changed.+ vizStore.updateGeoKey(featureId);+ } else if (geoUrl) {+ vizStore.setGeoUrl(geoUrl, featureId);+ } else {+ setError({ code: 'empty', detail: '' });+ return;}+ vizStore.setShowGeoJSONConfigPanel(false);};+ const shownError = error ?? (remote.error ? geoDataErrorOf(remote.error) : undefined);+return (<Dialogopen={showGeoJSONConfigPanel}@@ -127,24 +211,30 @@ const GeoConfigPanel = ({ geoList = emptyList }: { geoList?: IGeoDataItem[] }) =vizStore.setShowGeoJSONConfigPanel(false);}}>- <DialogContent>- <h2 className="text-lg mb-4">{t('geography')}</h2>+ <DialogContent aria-describedby={undefined}>+ <DialogTitle className="text-lg mb-4 font-normal leading-normal tracking-normal">{t('geography')}</DialogTitle><div><div className="my-2"><label className="block text-xs font-medium leading-6">{t('geography_settings.geoKey')}</label>- <div className="mt-1">- <Input type="text" value={featureId} onChange={(e) => setFeatureId(e.target.value)} />+ <div className="mt-1" data-testid="geo-config-key">+ <DropdownSelect+ options={featureKeyOptions}+ selectedKey={featureKeys.length > 0 ? featureId : ''}+ onSelect={setFeatureId}+ disable={featureKeys.length === 0}+ placeholder={t('geography_settings.geoKeyEmpty')}+ /></div></div>{geoList.length > 0 && (- <div className="my-2">- <label className="block text-xs font-medium leading-6">GeoData</label>+ <div className="my-2" data-testid="geo-config-preset">+ <label className="block text-xs font-medium leading-6">{t('geography_settings.geoData')}</label><DropdownSelect options={options} selectedKey={`${selectItem}`} onSelect={setSelectItem} /></div>)}- {!isCustom && selectItem >= 0 && (+ {listItem && (<div className={`relative justify-center flex w-full h-80 rounded border shadow-sm`}>- <GeojsonRenderer type={geoList[selectItem].type} url={geoList[selectItem]} />+ <GeojsonRenderer data={features} loading={remote.loading} tileUrl={tileUrl} /></div>)}{isCustom && (@@ -179,25 +269,7 @@ const GeoConfigPanel = ({ geoList = emptyList }: { geoList?: IGeoDataItem[] }) =setUrl(e.target.value);}}/>- <Button- className="mr-2 flex-shrink-0"- disabled={loading}- onClick={() => {- if (url) {- setLoading(true);- fetch(url)- .then((res) => res.json())- .then((json) => {- (dataMode === 'GeoJSON' ? setGeoJSON : setTopoJSON)(JSON.stringify(json, null, 2));- setLoadedUrl({ type: dataMode, url });- setLoading(false);- })- .catch(() => {- setLoading(false);- });- }- }}- >+ <Button className="mr-2 flex-shrink-0" disabled={loading} onClick={loadUrl}>{loading && <Spinner />}{t('geography_settings.load')}</Button>@@ -205,15 +277,7 @@ const GeoConfigPanel = ({ geoList = emptyList }: { geoList?: IGeoDataItem[] }) =<DropzoneonDrop={(acceptedFiles) => {const f: File = acceptedFiles[0];- if (f) {- const reader = new FileReader();- reader.addEventListener('load', (event) => {- const data = event.target!.result as string;- setLoadedUrl(undefined);- (dataMode === 'GeoJSON' ? setGeoJSON : setTopoJSON)(data);- });- reader.readAsText(f);- }+ if (f) loadFile(f);}}noClick>@@ -222,33 +286,40 @@ const GeoConfigPanel = ({ geoList = emptyList }: { geoList?: IGeoDataItem[] }) ={isDragActive && (<div className="absolute items-center justify-center left-0 right-0 top-0 bottom-0 z-20 bg-accent opacity-80" />)}- <input {...getInputProps()} />+ <input {...getInputProps()} data-testid="geo-config-file" /><div onClick={open} className="flex h-full items-center justify-center w-48">{t('geography_settings.jsonInputPlaceholder', { format: dataMode.toLowerCase() })}</div>- <GeojsonRenderer data={dataMode === 'GeoJSON' ? geoJSON : topoJSON} type={dataMode} url={loadedUrl} />+ <GeojsonRenderer data={features} loading={remote.loading} tileUrl={tileUrl} /></div>)}</Dropzone>- {dataMode === 'TopoJSON' && (- <div className="flex items-center space-x-2">+ {topologyObjects.length > 1 && (+ <div className="flex items-center space-x-2" data-testid="geo-config-object"><label className="text-xs whitespace-nowrap capitalize">{t('geography_settings.objectKey')}</label>- <Input- type="text"- value={topoJSONKey}- placeholder={defaultTopoJSONKey}- onChange={(e) => {- setTopoJSONKey(e.target.value);- }}+ <DropdownSelect+ options={topologyObjects.map((name) => ({ label: name, value: name }))}+ selectedKey={objectKey || topologyObjects[0]}+ onSelect={setObjectKey}/></div>)}</div></div>)}+ {shownError && (+ <p role="alert" className="my-2 text-xs text-destructive" data-testid="geo-config-error" data-code={shownError.code}>+ {shownError.code === 'empty' ? t('geography_settings.noSource') : errorText({ code: shownError.code, detail: shownError.detail })}+ </p>+ )}+ {!shownError && !busy && noKeys && (+ <p role="alert" className="my-2 text-xs text-destructive" data-testid="geo-config-error" data-code="no_keys">+ {t('geography_settings.noKeys')}+ </p>+ )}</div><DialogFooter>- <Button children={tGlobal('actions.confirm')} onClick={handleSubmit} />+ <Button children={tGlobal('actions.confirm')} onClick={handleSubmit} disabled={!canConfirm} data-testid="geo-config-confirm" /><Buttonchildren={tGlobal('actions.cancel')}variant="outline"diff --git a/packages/graphic-walker/src/components/leafletRenderer/geoNotice.tsx b/packages/graphic-walker/src/components/leafletRenderer/geoNotice.tsxnew file mode 100644index 00000000..46f0dcc7--- /dev/null+++ b/packages/graphic-walker/src/components/leafletRenderer/geoNotice.tsx@@ -0,0 +1,165 @@+import React, { useEffect, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';+import { DomEvent } from 'leaflet';+import { XMarkIcon } from '@heroicons/react/24/outline';+import { Button } from '../ui/button';+import type { GeoDataErrorCode } from '../../lib/geo/parse';+import { GEO_NOTICE_ENGLISH as english } from './geoNoticeText';++type Key = keyof typeof english;++export function useGeoNoticeText() {+ const { t } = useTranslation('translation', { keyPrefix: 'geo_notice' });+ return (key: Key, values?: Record<string, string | number>) => t(key, { defaultValue: english[key], ...values });+}++/** The sentence for a geographic data error, in the user's language. */+export function useGeoErrorText() {+ const say = useGeoNoticeText();+ return (error: { code: GeoDataErrorCode; detail: string }) => say(`error_${error.code}`, { detail: error.detail });+}++export type GeoNoticeContent =+ | { state: 'no_data' | 'no_field' }+ | { state: 'bad_key'; key: string }+ | {+ /** What matching the data to the shapes left to report. */+ state: 'match';+ key: string;+ /** Distinct values that found a shape, and distinct values in all. */+ matched: number;+ total: number;+ unmatchedValues: string[];+ featureSamples: string[];+ emptyRows: number;+ /** Groups of differently written values that found the same shape, each in a form that shows its spaces. */+ sharedValues: string[][];+ /** Values whose shape has no geometry. */+ undrawnValues: string[];+ };++const VALUE_LIMIT = 5;+const GROUP_LIMIT = 3;++/**+ * Says, on the map, why some or all of the data is not drawn. It sits in a corner and can be+ * dismissed. It comes back when what it reports changes.+ */+export function GeoNotice({ notice }: { notice: GeoNoticeContent }) {+ const say = useGeoNoticeText();+ const box = useRef<HTMLDivElement>(null);+ const signature = JSON.stringify(notice);+ const [dismissed, setDismissed] = useState('');++ useEffect(() => {+ // Clicks and scrolls on the notice are not meant for the map under it.+ if (box.current) {+ DomEvent.disableClickPropagation(box.current);+ DomEvent.disableScrollPropagation(box.current);+ }+ });++ if (dismissed === signature) return null;++ /** The first few of a list, with a count of the rest. */+ const some = (items: string[], limit: number, separator = ', ') => {+ const shown = items.slice(0, limit).join(separator);+ return items.length > limit ? say('unmatched_more', { values: shown, count: items.length - limit }) : shown;+ };++ let kind: string = notice.state;+ let title: string;+ const lines: string[] = [];+ if (notice.state === 'match') {+ // Each thing to report has a title and a line that reads on its own. The first one gives+ // the notice its title. The others follow as lines.+ const issues: { kind: string; title: string; line?: string }[] = [];+ if (notice.unmatchedValues.length > 0) {+ issues.push({+ kind: 'unmatched',+ title: say('unmatched_title', { matched: notice.matched, total: notice.total }),+ line: say('unmatched_values', { values: some(notice.unmatchedValues, VALUE_LIMIT) }),+ });+ }+ if (notice.sharedValues.length > 0) {+ const groups = notice.sharedValues.map((group) => some(group, VALUE_LIMIT, ' / '));+ issues.push({ kind: 'shared', title: say('shared_title'), line: say('shared_values', { values: some(groups, GROUP_LIMIT, '; ') }) });+ }+ if (notice.undrawnValues.length > 0) {+ issues.push({+ kind: 'no_geometry',+ title: say('no_geometry_title'),+ line: say('no_geometry_values', { values: some(notice.undrawnValues, VALUE_LIMIT) }),+ });+ }+ if (notice.emptyRows > 0) issues.push({ kind: 'empty_rows', title: say('empty_rows', { count: notice.emptyRows }) });+ if (issues.length === 0) return null;++ kind = issues[0].kind;+ title = issues[0].title;+ if (issues[0].line) lines.push(issues[0].line);+ for (const issue of issues.slice(1)) lines.push(issue.line ?? issue.title);+ if (notice.unmatchedValues.length > 0 && notice.featureSamples.length > 0) {+ lines.push(say('unmatched_key', { key: notice.key, samples: notice.featureSamples.join(', ') }));+ }+ } else if (notice.state === 'bad_key') {+ title = say('bad_key_title', { key: notice.key });+ lines.push(say('bad_key_desc'));+ } else {+ title = say(`${notice.state}_title`);+ lines.push(say(`${notice.state}_desc`));+ }++ return (+ <div+ ref={box}+ role="status"+ data-testid="geo-notice"+ data-state={kind}+ className="absolute bottom-3 left-3 max-w-sm cursor-default rounded-md border bg-popover p-3 pr-8 text-xs text-popover-foreground shadow-md"+ style={{ zIndex: 999 }}+ >+ <p className="font-medium" data-testid="geo-notice-title">+ {title}+ </p>+ {lines.map((line) => (+ <p key={line} className="mt-1 whitespace-pre-wrap break-words text-muted-foreground" data-testid="geo-notice-line">+ {line}+ </p>+ ))}+ <Button+ size="icon-xs"+ variant="ghost"+ className="absolute right-2 top-2"+ aria-label={say('dismiss')}+ title={say('dismiss')}+ data-testid="geo-notice-dismiss"+ onClick={() => setDismissed(signature)}+ >+ <XMarkIcon className="h-4 w-4" />+ </Button>+ </div>+ );+}++/** Fills the chart area when the shapes behind a URL could not be loaded. */+export function GeoLoadFailed({ error, onRetry }: { error: { code: GeoDataErrorCode; detail: string }; onRetry?: () => void }) {+ const say = useGeoNoticeText();+ const reason = useGeoErrorText()(error);+ const canRetry = onRetry && (error.code === 'network' || error.code === 'http');+ return (+ <div role="alert" data-testid="geo-load-failed" data-code={error.code} className="flex h-full w-full items-start p-6">+ <div className="max-w-xl space-y-2 text-sm">+ <p className="font-medium text-foreground">{say('load_failed_title')}</p>+ <p className="text-foreground" data-testid="geo-load-failed-reason">+ {reason}+ </p>+ {canRetry && (+ <Button size="sm" variant="outline" onClick={onRetry} data-testid="geo-load-failed-retry">+ {say('retry')}+ </Button>+ )}+ </div>+ </div>+ );+}diff --git a/packages/graphic-walker/src/components/leafletRenderer/geoNoticeText.test.ts b/packages/graphic-walker/src/components/leafletRenderer/geoNoticeText.test.tsnew file mode 100644index 00000000..2a1445b1--- /dev/null+++ b/packages/graphic-walker/src/components/leafletRenderer/geoNoticeText.test.ts@@ -0,0 +1,35 @@+import { GEO_NOTICE_ENGLISH } from './geoNoticeText';+import en from '../../locales/en-US.json';+import zh from '../../locales/zh-CN.json';+import ja from '../../locales/ja-JP.json';++const locales: Record<string, any> = { 'en-US': en, 'zh-CN': zh, 'ja-JP': ja };+const placeholders = (text: string) => [...text.matchAll(/{{(\w+)}}/g)].map((m) => m[1]).sort();+// The keys the geography settings dialog asks for on top of the ones it had before.+const settingsKeys = ['selectData', 'manual', 'geoData', 'geoKeyEmpty', 'geoKeySample', 'noSource', 'noKeys'];++describe.each(Object.keys(locales))('map messages in %s', (name) => {+ const notice: Record<string, string> = locales[name].geo_notice;+ const settings: Record<string, string> = locales[name].main.tabpanel.settings.geography_settings;++ it('has every message the map can show, and no others', () => {+ expect(Object.keys(notice).sort()).toEqual(Object.keys(GEO_NOTICE_ENGLISH).sort());+ });++ it('fills in the same values as the built-in English text', () => {+ for (const [key, text] of Object.entries(GEO_NOTICE_ENGLISH)) {+ expect([key, placeholders(notice[key])]).toEqual([key, placeholders(text)]);+ }+ });++ it('has the text of the geography settings dialog', () => {+ for (const key of settingsKeys) {+ expect([key, typeof settings[key]]).toEqual([key, 'string']);+ }+ expect(placeholders(settings.geoKeySample)).toEqual(['samples']);+ });+});++it('ships the same English text in the locale file as in the code', () => {+ expect(en.geo_notice).toEqual(GEO_NOTICE_ENGLISH);+});diff --git a/packages/graphic-walker/src/components/leafletRenderer/geoNoticeText.ts b/packages/graphic-walker/src/components/leafletRenderer/geoNoticeText.tsnew file mode 100644index 00000000..68a47abd--- /dev/null+++ b/packages/graphic-walker/src/components/leafletRenderer/geoNoticeText.ts@@ -0,0 +1,26 @@+// What is shown where the translations are not loaded, as in a renderer mounted without the editor.+export const GEO_NOTICE_ENGLISH = {+ no_data_title: 'This map has no shapes yet',+ no_data_desc: 'Choose or upload a GeoJSON or TopoJSON file in Geography Configuration.',+ no_field_title: 'No field says which shape a row belongs to',+ no_field_desc: 'Put the field that names each region on the Geometry ID shelf.',+ bad_key_title: 'No shape has a "{{key}}" value',+ bad_key_desc: 'Pick another Feature ID in Geography Configuration.',+ unmatched_title: '{{matched}} of {{total}} values matched a shape',+ unmatched_values: 'No shape for: {{values}}',+ unmatched_more: '{{values}} and {{count}} more',+ unmatched_key: 'Shapes are matched on "{{key}}", with values such as {{samples}}.',+ shared_title: 'Different values point at the same shape',+ shared_values: 'Values sharing a shape are drawn on top of each other, not added up: {{values}}',+ no_geometry_title: 'Some matched shapes have nothing to draw',+ no_geometry_values: 'The file has no geometry for: {{values}}',+ empty_rows: 'Rows with no value to match: {{count}}',+ load_failed_title: 'The map shapes could not be loaded',+ error_network: 'The request did not complete. Check the address and the network.',+ error_http: 'The server answered with status {{detail}}.',+ error_json: 'The file is not valid JSON.',+ error_format: 'The file is neither a GeoJSON FeatureCollection nor a TopoJSON topology.',+ error_object: 'The TopoJSON file has no object of that name. It has: {{detail}}.',+ retry: 'Try again',+ dismiss: 'Dismiss',+};diff --git a/packages/graphic-walker/src/components/leafletRenderer/geojsonRenderer.tsx b/packages/graphic-walker/src/components/leafletRenderer/geojsonRenderer.tsxindex d9f26992..f7dc7ed2 100644--- a/packages/graphic-walker/src/components/leafletRenderer/geojsonRenderer.tsx+++ b/packages/graphic-walker/src/components/leafletRenderer/geojsonRenderer.tsx@@ -1,102 +1,66 @@import React, { useEffect, useMemo, useState } from 'react';import { GeoJSON, MapContainer, TileLayer, AttributionControl } from 'react-leaflet';-import { useGeoJSON } from '../../hooks/service';-import { IGeoUrl } from '../../interfaces';-import { FeatureCollection, Geometry } from 'geojson';-import { feature } from 'topojson-client';-import { canvas } from 'leaflet';+import type { FeatureCollection } from 'geojson';+import { canvas, circleMarker } from 'leaflet';import { useTranslation } from 'react-i18next';+import { WORLD_BOUNDS, drawableGeometry } from '../../lib/geo/geometry';-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((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((c) => [c[1], c[0]]));- }- default: {- return [];- }- }-};--export function GeojsonRenderer(props: { url?: IGeoUrl; data?: string; type?: 'GeoJSON' | 'TopoJSON' }) {- const d = useMemo(() => (props.data && props.type ? getGeojson(props.data, props.type) : undefined), [props.data, props.type]);- const data = useGeoJSON(d, props.url);+/**+ * A preview of the shapes in a file, for the geography settings. `tileUrl` follows the chart's own+ * setting: undefined draws the default basemap, an empty string draws none.+ */+export function GeojsonRenderer(props: { data?: FeatureCollection; loading?: boolean; tileUrl?: string }) {+ const { data, loading, tileUrl } = props;const [k, setK] = useState(0);+ // Leaflet's GeoJSON layer reads its data once, so new data needs a new layer.useEffect(() => setK((x) => x + 1), [data]);+ // Leaflet throws on a coordinate it cannot read, which would take the whole dialog down. So the+ // preview gets only the geometry the chart itself would draw.+ const drawable = useMemo<FeatureCollection | undefined>(() => {+ if (!data) return undefined;+ return {+ type: 'FeatureCollection',+ features: data.features.flatMap((feature) => {+ const geometry = drawableGeometry(feature?.geometry);+ return geometry ? [{ type: 'Feature' as const, properties: {}, geometry }] : [];+ }),+ };+ }, [data]);const { t } = useTranslation('translation', { keyPrefix: 'main.tabpanel.settings' });- if (!d && !props.url) return null;- if (!data) {+ if (loading) {return <div className="w-full flex-1 flex items-center justify-center border-l">{t('geography_settings.loading')}</div>;}+ if (!drawable) return null;return (- <div className="w-full flex-1 relative">- <Renderer key={k} data={data} />+ <div className="w-full flex-1 relative" data-testid="geo-config-preview">+ <Renderer key={k} data={drawable} tileUrl={tileUrl} /></div>);}-function Renderer(props: { data?: FeatureCollection }) {+function Renderer(props: { data?: FeatureCollection; tileUrl?: string }) {return (<MapContainerpreferCanvasattributionControl={false}center={[0, 0]}- bounds={[- [-180, -90],- [180, 90],- ]}+ bounds={WORLD_BOUNDS}renderer={canvas()}zoom={1}style={{ width: '100%', height: '100%', zIndex: 1 }}>- <TileLayer- className="map-tile"- attribution='© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'- url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"- />+ {props.tileUrl === undefined && (+ <TileLayer+ className="map-tile"+ attribution='© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'+ url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"+ />+ )}+ {props.tileUrl && <TileLayer className="map-tile" url={props.tileUrl} />}<AttributionControl prefix="Leaflet" />- {props.data && <GeoJSON data={props.data} />}+ {/* Points as small circles, the way the chart draws them. Leaflet's default is an image marker. */}+ {props.data && <GeoJSON data={props.data} pointToLayer={(_, position) => circleMarker(position, { radius: 3, weight: 1 })} />}</MapContainer>);}--function getGeojson(str: string, type: 'GeoJSON' | 'TopoJSON') {- try {- const data = JSON.parse(str);- const geoJSON = type === 'GeoJSON' ? data : (feature(data, Object.keys(data.objects)[0]) as unknown as FeatureCollection);- if (!('features' in geoJSON)) {- console.error('Invalid GeoJSON: GeoJSON must be a FeatureCollection, but got', geoJSON);- return undefined;- }- return geoJSON;- } catch (e) {- console.error(e);- }- return undefined;-}diff --git a/packages/graphic-walker/src/components/leafletRenderer/utils.ts b/packages/graphic-walker/src/components/leafletRenderer/utils.tsindex 0ba1a461..3bb4939d 100644--- a/packages/graphic-walker/src/components/leafletRenderer/utils.ts+++ b/packages/graphic-walker/src/components/leafletRenderer/utils.ts@@ -1,10 +1,10 @@-import { useMemo } from "react";+import { useEffect, useMemo, useRef } 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";import { useMap } from "react-leaflet";-import type { LatLngBoundsExpression } from 'leaflet';+import type { LatLngBounds } from '../../lib/geo/geometry';const defaultFormatter = (value: unknown): string => `${value}`;@@ -52,8 +52,32 @@ export const useDisplayValueFormatter = (semanticType: ISemanticType, vegaConfigreturn formatter;};-export function ChangeView({ bounds }: {bounds: LatLngBoundsExpression}) {+/**+ * Moves the map to `bounds` when their values change, and at no other time, so a re-render for an+ * unrelated reason leaves the user's zoom and pan alone. A map that has no size yet is fitted once+ * it gets one.+ */+export function ChangeView({ bounds }: { bounds: LatLngBounds }) {const map = useMap();- map.flyToBounds(bounds);+ const key = bounds.flat().join(',');+ const shown = useRef<string | null>(null);+ useEffect(() => {+ const show = () => {+ if (shown.current === key) return;+ const size = map.getSize();+ if (!size.x || !size.y) return;+ if (shown.current === null) {+ map.fitBounds(bounds, { animate: false });+ } else {+ map.flyToBounds(bounds);+ }+ shown.current = key;+ };+ show();+ map.on('resize', show);+ return () => {+ map.off('resize', show);+ };+ }, [map, key]);return null;}\ No newline at end of filediff --git a/packages/graphic-walker/src/hooks/service.ts b/packages/graphic-walker/src/hooks/service.tsindex 3c608790..261d19d6 100644--- a/packages/graphic-walker/src/hooks/service.ts+++ b/packages/graphic-walker/src/hooks/service.ts@@ -1,35 +1,70 @@import { IGeoUrl } from '../interfaces';-import { useState, useEffect, useRef } from 'react';-import { feature } from 'topojson-client';+import { useCallback, useEffect, useState } from 'react';import type { FeatureCollection } from 'geojson';+import { fetchGeoJson, toFeatureCollection } from '../lib/geo/parse';++const loaded = new Map<string, FeatureCollection>();+const loading = new Map<string, Promise<FeatureCollection>>();++const geoUrlKey = (url: IGeoUrl) => `${url.type}(${url.url})${url.objectKey ? `#${url.objectKey}` : ''}`;++/**+ * Downloads the geometry behind a URL once and keeps it for the page's lifetime. Concurrent+ * callers share one request. A failed request is forgotten, so the next call tries again.+ */+export function loadGeoUrl(url: IGeoUrl): Promise<FeatureCollection> {+ const key = geoUrlKey(url);+ const ready = loaded.get(key);+ if (ready) return Promise.resolve(ready);+ let request = loading.get(key);+ if (!request) {+ request = fetchGeoJson(url.url)+ .then((json) => {+ const collection = toFeatureCollection(json, url.objectKey);+ loaded.set(key, collection);+ return collection;+ })+ .finally(() => loading.delete(key));+ loading.set(key, request);+ }+ return request;+}++export interface IGeoDataState {+ data?: FeatureCollection;+ /** Set when the URL could not be loaded. Read it with `geoDataErrorOf`. */+ error?: unknown;+ loading: boolean;+ retry: () => void;+}++/** The geometry to draw: the one given, or the one behind `url`, with its loading and error state. */+export function useGeoData(geojson?: FeatureCollection, url?: IGeoUrl): IGeoDataState {+ const key = !geojson && url ? geoUrlKey(url) : '';+ const [attempt, setAttempt] = useState(0);+ const [settled, setSettled] = useState<{ key: string; attempt: number; data?: FeatureCollection; error?: unknown }>({ key: '', attempt: 0 });+ const retry = useCallback(() => setAttempt((n) => n + 1), []);-const GeoJSONDict: Record<string, FeatureCollection> = {};-export function useGeoJSON(geojson?: FeatureCollection, url?: IGeoUrl) {- const key = url ? `${url.type}(${url.url})` : '';- const data = (geojson || GeoJSONDict[key] || url) as IGeoUrl | FeatureCollection;- const [_, setLastFetched] = useState(0);- const lastFetchedRef = useRef(0);useEffect(() => {- if (data === url && url) {- const timestamp = Date.now();- lastFetchedRef.current = timestamp;- fetch(url.url)- .then((res) => res.json())- .then((json) => {- if (timestamp !== lastFetchedRef.current) return;- if (url.type === 'GeoJSON') {- if ('features' in json) {- GeoJSONDict[key] = json;- } else {- throw 'invalid geojson';- }- } else {- GeoJSONDict[key] = feature(json, Object.keys(json.objects)[0]) as unknown as FeatureCollection;- }- setLastFetched(timestamp);- })- .catch((e) => console.error(e));- }- }, [data]);- return data === url ? undefined : (data as FeatureCollection);+ if (!key || !url || loaded.has(key)) return;+ let live = true;+ loadGeoUrl(url).then(+ (data) => live && setSettled({ key, attempt, data }),+ (error) => live && setSettled({ key, attempt, error })+ );+ return () => {+ live = false;+ };+ }, [key, attempt]);++ if (geojson) return { data: geojson, loading: false, retry };+ if (!key) return { loading: false, retry };+ const ready = loaded.get(key);+ if (ready) return { data: ready, loading: false, retry };+ if (settled.key === key && settled.attempt === attempt) return { data: settled.data, error: settled.error, loading: false, retry };+ return { loading: true, retry };+}++export function useGeoJSON(geojson?: FeatureCollection, url?: IGeoUrl) {+ return useGeoData(geojson, url).data;}diff --git a/packages/graphic-walker/src/interfaces.ts b/packages/graphic-walker/src/interfaces.tsindex 16e90167..862964d8 100644--- a/packages/graphic-walker/src/interfaces.ts+++ b/packages/graphic-walker/src/interfaces.ts@@ -452,6 +452,8 @@ export interface IVisualConfigNew {export interface IGeoUrl {type: 'GeoJSON' | 'TopoJSON';url: string;+ /** For TopoJSON: the name of the object to draw. Defaults to the first key of `objects`. */+ objectKey?: string;}/** @deprecated */@@ -807,6 +809,8 @@ export type IGeoDataItem = {type: 'GeoJSON' | 'TopoJSON';name: string;url: string;+ /** For TopoJSON: the name of the object to draw. Defaults to the first key of `objects`. */+ objectKey?: string;};function toDict<T extends string>(a: readonly T[]) {diff --git a/packages/graphic-walker/src/lib/geo/geometry.test.ts b/packages/graphic-walker/src/lib/geo/geometry.test.tsnew file mode 100644index 00000000..ed4dba57--- /dev/null+++ b/packages/graphic-walker/src/lib/geo/geometry.test.ts@@ -0,0 +1,141 @@+import type { Geometry } from 'geojson';+import { WORLD_BOUNDS, drawableGeometry, extendBounds, resolveParts, ringCentroid, type LatLng } from './geometry';++// GeoJSON writes [lng, lat]. A 10 by 10 square with a 2 by 2 hole in the middle.+const outline = [[0, 0], [10, 0], [10, 10], [0, 10], [0, 0]];+const hole = [[4, 4], [4, 6], [6, 6], [6, 4], [4, 4]];+const flip = (ring: number[][]) => ring.map(([lng, lat]) => [lat, lng]);++describe('resolveParts', () => {+ it('keeps the holes of a polygon and turns [lng, lat] into [lat, lng]', () => {+ const parts = resolveParts({ type: 'Polygon', coordinates: [outline, hole] });+ expect(parts).toEqual([{ type: 'polygon', rings: [flip(outline), flip(hole)] }]);+ });++ it('keeps the holes of every part of a multipolygon', () => {+ const island = [[20, 20], [21, 20], [21, 21], [20, 20]];+ const parts = resolveParts({ type: 'MultiPolygon', coordinates: [[outline, hole], [island]] });+ expect(parts).toEqual([+ { type: 'polygon', rings: [flip(outline), flip(hole)] },+ { type: 'polygon', rings: [flip(island)] },+ ]);+ });++ it('draws points as points and lines as lines, never as filled areas', () => {+ expect(resolveParts({ type: 'Point', coordinates: [139.7, 35.7] })).toEqual([{ type: 'point', position: [35.7, 139.7] }]);+ expect(resolveParts({ type: 'MultiPoint', coordinates: [[1, 2], [3, 4]] })).toEqual([+ { type: 'point', position: [2, 1] },+ { type: 'point', position: [4, 3] },+ ]);+ expect(resolveParts({ type: 'LineString', coordinates: [[1, 2], [3, 4]] })).toEqual([{ type: 'line', positions: [[2, 1], [4, 3]] }]);+ expect(resolveParts({ type: 'MultiLineString', coordinates: [[[1, 2], [3, 4]], [[5, 6], [7, 8]]] })).toHaveLength(2);+ });++ it('flattens a geometry collection', () => {+ const collection: Geometry = {+ type: 'GeometryCollection',+ geometries: [+ { type: 'Point', coordinates: [1, 2] },+ { type: 'Polygon', coordinates: [outline] },+ ],+ };+ expect(resolveParts(collection).map((p) => p.type)).toEqual(['point', 'polygon']);+ });++ it('returns nothing for a feature without geometry or with a broken one', () => {+ expect(resolveParts(null)).toEqual([]);+ expect(resolveParts(undefined)).toEqual([]);+ expect(resolveParts({ type: 'Polygon', coordinates: [[[0, 0], [1, 1]]] })).toEqual([]);+ expect(resolveParts({ type: 'Polygon', coordinates: [] })).toEqual([]);+ expect(resolveParts({ type: 'Point', coordinates: [] })).toEqual([]);+ // A hole too short to be a ring is dropped. The outline stays.+ expect(resolveParts({ type: 'Polygon', coordinates: [outline, [[1, 1], [2, 2]]] })).toEqual([{ type: 'polygon', rings: [flip(outline)] }]);+ });+});++describe('resolveParts on files that break the format', () => {+ it('returns nothing where coordinates or member geometries are missing', () => {+ const broken = (geometry: object) => resolveParts(geometry as Geometry);+ expect(broken({ type: 'MultiPolygon', coordinates: null })).toEqual([]);+ expect(broken({ type: 'MultiLineString' })).toEqual([]);+ expect(broken({ type: 'GeometryCollection', geometries: null })).toEqual([]);+ expect(resolveParts('Polygon' as unknown as Geometry)).toEqual([]);+ });+});++describe('drawableGeometry', () => {+ it('has nothing for geometry that cannot be drawn', () => {+ expect(drawableGeometry(null)).toBeNull();+ expect(drawableGeometry({ type: 'Point', coordinates: [] })).toBeNull();+ expect(drawableGeometry({ type: 'Polygon', coordinates: [[[0, 0], [1, 1]]] })).toBeNull();+ });+ it('keeps what can be drawn, in GeoJSON order, and leaves the rest out', () => {+ const mixed: Geometry = {+ type: 'GeometryCollection',+ geometries: [+ { type: 'Point', coordinates: [] },+ { type: 'Point', coordinates: [3, 4] },+ { type: 'Polygon', coordinates: [outline, hole] },+ { type: 'MultiLineString', coordinates: [[[0, 0]], [[0, 0], [5, 5]]] },+ ],+ };+ expect(drawableGeometry(mixed)).toEqual({+ type: 'GeometryCollection',+ geometries: [+ { type: 'Point', coordinates: [3, 4] },+ { type: 'Polygon', coordinates: [outline, hole] },+ { type: 'LineString', coordinates: [[0, 0], [5, 5]] },+ ],+ });+ });+});++describe('extendBounds', () => {+ it('returns south-west and north-east corners, latitude first', () => {+ const parts = [+ ...resolveParts({ type: 'Polygon', coordinates: [outline, hole] }),+ ...resolveParts({ type: 'Point', coordinates: [-30, 55] }),+ ...resolveParts({ type: 'LineString', coordinates: [[12, -5], [3, 3]] }),+ ];+ expect(extendBounds(null, parts)).toEqual([+ [-5, -30],+ [55, 12],+ ]);+ });++ it('is null until something has been added, and grows from a given start', () => {+ expect(extendBounds(null, [])).toBeNull();+ const first = extendBounds(null, resolveParts({ type: 'Point', coordinates: [1, 2] }));+ expect(extendBounds(first, resolveParts({ type: 'Point', coordinates: [5, -3] }))).toEqual([+ [-3, 1],+ [2, 5],+ ]);+ });++ it('has a default that is latitude first too', () => {+ expect(WORLD_BOUNDS).toEqual([+ [-90, -180],+ [90, 180],+ ]);+ });+});++describe('ringCentroid', () => {+ const square: LatLng[] = [[0, 0], [0, 10], [10, 10], [10, 0], [0, 0]];+ it('finds the centre of a square, closed or not, in either direction', () => {+ expect(ringCentroid(square)).toEqual([5, 5]);+ expect(ringCentroid(square.slice(0, 4))).toEqual([5, 5]);+ expect(ringCentroid([...square].reverse())).toEqual([5, 5]);+ });+ it('weights by area, so a long thin arm does not pull the centre along with it', () => {+ // An L shape: a 10 by 10 block with a 30 by 1 arm.+ const l: LatLng[] = [[0, 0], [0, 40], [1, 40], [1, 10], [10, 10], [10, 0], [0, 0]];+ const [lat, lng] = ringCentroid(l)!;+ expect(lng).toBeLessThan(12);+ expect(lat).toBeGreaterThan(3);+ });+ it('is null for a ring with no area', () => {+ expect(ringCentroid([[0, 0], [1, 1], [2, 2]])).toBeNull();+ expect(ringCentroid([])).toBeNull();+ });+});diff --git a/packages/graphic-walker/src/lib/geo/geometry.ts b/packages/graphic-walker/src/lib/geo/geometry.tsnew file mode 100644index 00000000..77ae21e8--- /dev/null+++ b/packages/graphic-walker/src/lib/geo/geometry.ts@@ -0,0 +1,129 @@+import type { Geometry, Position } from 'geojson';++export type LatLng = [lat: number, lng: number];+export type LatLngBounds = [southWest: LatLng, northEast: LatLng];++/**+ * One drawable piece of a feature. A polygon keeps every ring: the first is the outline+ * and the rest are holes, which is the order Leaflet expects.+ */+export type GeoPart = { type: 'point'; position: LatLng } | { type: 'line'; positions: LatLng[] } | { type: 'polygon'; rings: LatLng[][] };++export const WORLD_BOUNDS: LatLngBounds = [+ [-90, -180],+ [90, 180],+];++const isPosition = (c: unknown): c is Position => Array.isArray(c) && Number.isFinite(c[0]) && Number.isFinite(c[1]);+const toLatLng = (c: Position): LatLng => [c[1], c[0]];+const toPath = (coords: Position[]): LatLng[] => (Array.isArray(coords) ? coords.filter(isPosition).map(toLatLng) : []);++function lineParts(coords: Position[]): GeoPart[] {+ const positions = toPath(coords);+ return positions.length >= 2 ? [{ type: 'line', positions }] : [];+}++function polygonParts(coords: Position[][]): GeoPart[] {+ if (!Array.isArray(coords) || coords.length === 0) return [];+ const outline = toPath(coords[0]);+ if (outline.length < 3) return [];+ const holes = coords+ .slice(1)+ .map(toPath)+ .filter((ring) => ring.length >= 3);+ return [{ type: 'polygon', rings: [outline, ...holes] }];+}++const listOf = <T>(value: T[] | null | undefined): T[] => (Array.isArray(value) ? value : []);++/**+ * Turns a GeoJSON geometry into the pieces the map draws. GeoJSON is [lng, lat], the result is+ * [lat, lng]. A geometry that is missing or malformed gives no pieces.+ */+export function resolveParts(geometry: Geometry | null | undefined): GeoPart[] {+ if (!geometry) return [];+ switch (geometry.type) {+ case 'Point':+ return isPosition(geometry.coordinates) ? [{ type: 'point', position: toLatLng(geometry.coordinates) }] : [];+ case 'MultiPoint':+ return toPath(geometry.coordinates).map((position) => ({ type: 'point', position }));+ case 'LineString':+ return lineParts(geometry.coordinates);+ case 'MultiLineString':+ return listOf(geometry.coordinates).flatMap(lineParts);+ case 'Polygon':+ return polygonParts(geometry.coordinates);+ case 'MultiPolygon':+ return listOf(geometry.coordinates).flatMap(polygonParts);+ case 'GeometryCollection':+ return listOf(geometry.geometries).flatMap(resolveParts);+ default:+ return [];+ }+}++const toPosition = ([lat, lng]: LatLng): Position => [lng, lat];++/**+ * The geometry as GeoJSON again, holding only what `resolveParts` can draw. Null when nothing is+ * left. For code that hands geometry to Leaflet itself, which throws on a coordinate it cannot read.+ */+export function drawableGeometry(geometry: Geometry | null | undefined): Geometry | null {+ const parts = resolveParts(geometry);+ if (parts.length === 0) return null;+ return {+ type: 'GeometryCollection',+ geometries: parts.map((part): Geometry => {+ if (part.type === 'point') return { type: 'Point', coordinates: toPosition(part.position) };+ if (part.type === 'line') return { type: 'LineString', coordinates: part.positions.map(toPosition) };+ return { type: 'Polygon', coordinates: part.rings.map((ring) => ring.map(toPosition)) };+ }),+ };+}++/** The positions that decide how far a part reaches. Holes lie inside the outline, so they are left out. */+function outerPositions(part: GeoPart): LatLng[] {+ if (part.type === 'point') return [part.position];+ if (part.type === 'line') return part.positions;+ return part.rings[0];+}++/** Grows `bounds` to hold `parts`. Pass null to start. Returns null while nothing has been added. */+export function extendBounds(bounds: LatLngBounds | null, parts: readonly GeoPart[]): LatLngBounds | null {+ let next = bounds;+ for (const part of parts) {+ for (const [lat, lng] of outerPositions(part)) {+ if (!next) {+ next = [+ [lat, lng],+ [lat, lng],+ ];+ continue;+ }+ if (lat < next[0][0]) next[0][0] = lat;+ if (lng < next[0][1]) next[0][1] = lng;+ if (lat > next[1][0]) next[1][0] = lat;+ if (lng > next[1][1]) next[1][1] = lng;+ }+ }+ return next;+}++/** Area-weighted centre of a ring, used to place a label. Null for a ring with no area. */+export function ringCentroid(ring: readonly LatLng[]): LatLng | null {+ let doubleArea = 0;+ let lat = 0;+ let lng = 0;+ for (let i = 0; i < ring.length; i++) {+ const [lat1, lng1] = ring[i];+ // Wrapping to the first point closes a ring whose file left it open.+ const [lat2, lng2] = ring[(i + 1) % ring.length];+ const cross = lat1 * lng2 - lat2 * lng1;+ doubleArea += cross;+ lat += (lat1 + lat2) * cross;+ lng += (lng1 + lng2) * cross;+ }+ if (!doubleArea) return null;+ const centre: LatLng = [lat / (3 * doubleArea), lng / (3 * doubleArea)];+ return Number.isFinite(centre[0]) && Number.isFinite(centre[1]) ? centre : null;+}diff --git a/packages/graphic-walker/src/lib/geo/matching.test.ts b/packages/graphic-walker/src/lib/geo/matching.test.tsnew file mode 100644index 00000000..57d867d1--- /dev/null+++ b/packages/graphic-walker/src/lib/geo/matching.test.ts@@ -0,0 +1,178 @@+import type { Feature } from 'geojson';+import { featureKeyValue, listFeatureKeys, matchFeatures, normalizeGeoValue, quoteGeoValue, suggestFeatureKey } from './matching';++const shape = (properties: Record<string, unknown> | null, id?: string | number): Feature => ({+ type: 'Feature',+ ...(id === undefined ? {} : { id }),+ properties,+ geometry: { type: 'Point', coordinates: [0, 0] },+});++describe('normalizeGeoValue', () => {+ it('ignores case, surrounding and repeated spaces, and full-width forms', () => {+ expect(normalizeGeoValue(' New York ')).toBe('new york');+ expect(normalizeGeoValue('NEW YORK')).toBe('new york');+ expect(normalizeGeoValue('トウキョウ')).toBe(normalizeGeoValue('トウキョウ'));+ });+ it('reads numbers as their text and has nothing for null, objects and blanks', () => {+ expect(normalizeGeoValue(6)).toBe('6');+ expect(normalizeGeoValue(null)).toBe('');+ expect(normalizeGeoValue(undefined)).toBe('');+ expect(normalizeGeoValue({})).toBe('');+ expect(normalizeGeoValue(' ')).toBe('');+ expect(normalizeGeoValue(NaN)).toBe('');+ });+});++describe('featureKeyValue', () => {+ it('reads properties first and falls back to the feature id for the key "id"', () => {+ expect(featureKeyValue(shape({ name: 'Japan' }, 'JPN'), 'name')).toBe('Japan');+ expect(featureKeyValue(shape({ name: 'Japan' }, 'JPN'), 'id')).toBe('JPN');+ expect(featureKeyValue(shape({ id: 'inner' }, 'outer'), 'id')).toBe('inner');+ expect(featureKeyValue(shape(null, 392), 'id')).toBe(392);+ expect(featureKeyValue(shape({ name: 'Japan' }, 'JPN'), 'iso')).toBeUndefined();+ });+});++describe('matchFeatures', () => {+ const features = [shape({ name: 'United States of America', code: 840 }, 'USA'), shape({ name: 'Japan', code: 392 }, 'JPN'), shape({ name: 'South Korea', code: 410 }, 'KOR')];++ it('joins numbers to text and text to numbers', () => {+ expect(matchFeatures(['392', 410], features, 'code').rowFeatures).toEqual([[1], [2]]);+ const numericIds = [shape({}, 1), shape({}, 2)];+ expect(matchFeatures(['2', 1], numericIds, 'id').rowFeatures).toEqual([[1], [0]]);+ });++ it('joins on the feature id, where world files keep their ISO code', () => {+ const match = matchFeatures(['JPN', 'usa', ' KOR '], features, 'id');+ expect(match.rowFeatures).toEqual([[1], [0], [2]]);+ expect(match.matchedRows).toEqual([0, 1, 2]);+ expect(match.unmatchedRows).toBe(0);+ });++ it('ignores case and spacing, and prefers the value as written when the file tells them apart', () => {+ expect(matchFeatures([' japan', 'SOUTH KOREA'], features, 'name').rowFeatures).toEqual([[1], [2]]);+ const twins = [shape({ k: 'al' }), shape({ k: 'AL' })];+ expect(matchFeatures(['AL', 'al', 'Al'], twins, 'k').rowFeatures).toEqual([[1], [0], [0, 1]]);+ });++ it('reports what did not match, each value once and in order', () => {+ const match = matchFeatures(['East', 'Japan', 'West', 'East', null, '', ' '], features, 'name');+ expect(match.matchedRows).toEqual([1]);+ expect(match.unmatchedRows).toBe(3);+ expect(match.unmatchedValues).toEqual(['East', 'West']);+ expect(match.emptyRows).toBe(3);+ expect(match.distinctValues).toBe(3);+ expect(match.unusedFeatures).toEqual([0, 2]);+ expect(match.featureSamples).toEqual(['United States of America', 'Japan', 'South Korea']);+ });++ it('says when no feature has the key at all', () => {+ const match = matchFeatures(['Japan'], features, 'iso_a3');+ expect(match.keyedFeatures).toBe(0);+ expect(match.matchedRows).toEqual([]);+ expect(match.unusedFeatures).toEqual([0, 1, 2]);+ expect(matchFeatures(['Japan'], features, '').keyedFeatures).toBe(0);+ });++ it('gives a row every feature that shares its key', () => {+ const islands = [shape({ name: 'Japan' }), shape({ name: 'Korea' }), shape({ name: 'Japan' })];+ const match = matchFeatures(['Japan'], islands, 'name');+ expect(match.rowFeatures).toEqual([[0, 2]]);+ expect(match.unusedFeatures).toEqual([1]);+ });++ it('treats 0 as a value and skips features without properties', () => {+ const zero = [shape({ code: 0 }), shape(null)];+ const match = matchFeatures([0, '0'], zero, 'code');+ expect(match.rowFeatures).toEqual([[0], [0]]);+ expect(match.keyedFeatures).toBe(1);+ });++ it('reports values that are written differently and reach the same feature', () => {+ const squares = [shape({ name: 'EAST' }), shape({ name: 'Westland' })];+ const match = matchFeatures(['East', 'EAST', 'east', 'EAST', 'West'], squares, 'name');+ // The rows stay apart: adding them up is for the aggregation, which knows the measure.+ expect(match.rowFeatures).toEqual([[0], [0], [0], [0], []]);+ expect(match.sharedValues).toEqual([['East', 'EAST', 'east']]);+ expect(match.distinctValues).toBe(4);+ expect(match.unmatchedValues).toEqual(['West']);+ });++ it('tells values apart as the data has them, so spaces around a value still count', () => {+ const squares = [shape({ name: 'East' }), shape({ name: 'West' })];+ // The aggregation groups on the raw value. These are two rows of two groups, drawn on one shape.+ const match = matchFeatures(['East', ' East '], squares, 'name');+ expect(match.rowFeatures).toEqual([[0], [0]]);+ expect(match.sharedValues).toEqual([['East', ' East ']]);+ expect(match.sharedValues[0].map(quoteGeoValue)).toEqual(['"East"', '" East "']);+ expect([match.distinctValues, match.matchedValues]).toEqual([2, 2]);++ // A number and its text are two groups as well. Unmatched spellings are listed once.+ const codes = matchFeatures([1, '1', 'North', ' North'], [shape({ code: 1 })], 'code');+ expect(codes.sharedValues).toEqual([[1, '1']]);+ expect(codes.sharedValues[0].map(quoteGeoValue)).toEqual(['1', '"1"']);+ expect(codes.unmatchedValues).toEqual(['North']);+ expect([codes.distinctValues, codes.matchedValues, codes.unmatchedRows]).toEqual([4, 2, 2]);+ });++ it('does not report one value that reaches several features, or several rows of one value', () => {+ const islands = [shape({ name: 'Japan' }), shape({ name: 'Japan' }), shape({ name: 'Korea' })];+ expect(matchFeatures(['Japan', 'Japan', 'Korea'], islands, 'name').sharedValues).toEqual([]);+ // Two spellings that reach the same two features are one group, not one per feature.+ expect(matchFeatures(['Japan', 'JAPAN'], islands, 'name').sharedValues).toEqual([['Japan', 'JAPAN']]);+ });++ it('skips an entry that is not a feature', () => {+ const broken = [null, shape({ name: 'Japan' })] as unknown as Feature[];+ expect(matchFeatures(['Japan'], broken, 'name').rowFeatures).toEqual([[1]]);+ expect(listFeatureKeys(broken)).toEqual([{ key: 'name', samples: ['Japan'], count: 1 }]);+ });++ it('looks values up in a table, so many rows against many features stay fast', () => {+ const many = Array.from({ length: 5000 }, (_, i) => shape({ name: `Region ${i}` }));+ const values = Array.from({ length: 100000 }, (_, i) => `region ${i % 6000}`);+ const start = Date.now();+ const match = matchFeatures(values, many, 'name');+ // A scan of every feature for every row is 500 million comparisons and takes many seconds.+ expect(Date.now() - start).toBeLessThan(2000);+ expect(match.matchedRows.length).toBeGreaterThan(80000);+ expect(match.unmatchedValues).toHaveLength(1000);+ });+});++describe('listFeatureKeys', () => {+ const features = [shape({ name: 'Japan', pop: 125, tags: ['a'] }, 'JPN'), shape({ name: 'Japan', iso: 'KR' }, 'KOR'), shape({ name: 'USA', note: null }, 'USA'), shape({ name: 'Peru' })];++ it('lists the properties that hold text or numbers, with samples, and the feature id', () => {+ expect(listFeatureKeys(features)).toEqual([+ { key: 'name', samples: ['Japan', 'USA', 'Peru'], count: 4 },+ { key: 'pop', samples: ['125'], count: 1 },+ { key: 'id', samples: ['JPN', 'KOR', 'USA'], count: 3 },+ { key: 'iso', samples: ['KR'], count: 1 },+ ]);+ });++ it('does not list the feature id a second time when a property is called id', () => {+ expect(listFeatureKeys([shape({ id: 'inner' }, 'outer')])).toEqual([{ key: 'id', samples: ['inner'], count: 1 }]);+ });++ it('offers the feature id when the property called id is empty, as matching reads it', () => {+ const world = [shape({ id: null, name: 'United States' }, 'USA'), shape({ id: null, name: 'Japan' }, 'JPN')];+ expect(listFeatureKeys(world)).toEqual([+ { key: 'id', samples: ['USA', 'JPN'], count: 2 },+ { key: 'name', samples: ['United States', 'Japan'], count: 2 },+ ]);+ expect(suggestFeatureKey(listFeatureKeys(world), 'id')).toBe('id');+ expect(matchFeatures(['USA'], world, 'id').rowFeatures).toEqual([[0]]);+ });++ it('suggests the current key when the file has it, else name, else the first', () => {+ const keys = listFeatureKeys(features);+ expect(suggestFeatureKey(keys, 'iso')).toBe('iso');+ expect(suggestFeatureKey(keys, 'missing')).toBe('name');+ expect(suggestFeatureKey(listFeatureKeys([shape({ NAME: 'x', code: 1 })]), '')).toBe('NAME');+ expect(suggestFeatureKey(listFeatureKeys([shape({ code: 1 })]), 'name')).toBe('code');+ expect(suggestFeatureKey([], 'name')).toBe('');+ });+});diff --git a/packages/graphic-walker/src/lib/geo/matching.ts b/packages/graphic-walker/src/lib/geo/matching.tsnew file mode 100644index 00000000..f7814c82--- /dev/null+++ b/packages/graphic-walker/src/lib/geo/matching.ts@@ -0,0 +1,203 @@+import type { Feature } from 'geojson';++/** The value as written, for an exact comparison. Empty for null, objects and blank text. */+export function geoValueText(value: unknown): string {+ if (typeof value === 'string') return value.trim();+ if (typeof value === 'number') return Number.isFinite(value) ? String(value) : '';+ if (typeof value === 'bigint' || typeof value === 'boolean') return String(value);+ return '';+}++/**+ * The value as a reader can tell it apart from another that trims to the same text: text in quotes+ * with its spaces, anything else as it prints. `East` and ` East ` read `"East"` and `" East "`.+ */+export function quoteGeoValue(value: unknown): string {+ return typeof value === 'string' ? `"${value}"` : String(value);+}++/**+ * The value with spelling differences that carry no meaning removed: full-width and half-width+ * forms (NFKC), letter case, and extra spaces. `" New York "`, `"new york"` and `"NEW YORK"` all agree.+ */+export function normalizeGeoValue(value: unknown): string {+ return geoValueText(value).normalize('NFKC').replace(/\s+/g, ' ').trim().toLowerCase();+}++/**+ * What a feature offers under `key`. Reads `properties` first. The key `id` falls back to the+ * feature's own `id`, where many files keep their ISO or FIPS code.+ */+export function featureKeyValue(feature: Feature, key: string): unknown {+ const value = feature?.properties?.[key];+ if (value !== undefined && value !== null) return value;+ return key === 'id' ? feature?.id : undefined;+}++export interface IFeatureKey {+ key: string;+ /** A few values found under this key, to show next to its name. */+ samples: string[];+ /** How many features carry it. */+ count: number;+}++const SAMPLE_LIMIT = 3;++/** The keys a data field could be matched against, each with sample values. */+export function listFeatureKeys(features: readonly Feature[]): IFeatureKey[] {+ const found = new Map<string, IFeatureKey>();+ const add = (key: string, value: unknown) => {+ const text = geoValueText(value);+ if (!text) return;+ let entry = found.get(key);+ if (!entry) {+ entry = { key, samples: [], count: 0 };+ found.set(key, entry);+ }+ entry.count += 1;+ if (entry.samples.length < SAMPLE_LIMIT && !entry.samples.includes(text)) entry.samples.push(text);+ };+ for (const feature of features) {+ const properties = feature?.properties ?? {};+ // Read through `featureKeyValue`, so the list offers exactly what matching can use.+ for (const key of Object.keys(properties)) add(key, featureKeyValue(feature, key));+ if (!('id' in properties)) add('id', feature?.id);+ }+ return [...found.values()];+}++/** The key to preselect: the current one when the file has it, else `name`, else the first. */+export function suggestFeatureKey(keys: readonly IFeatureKey[], current?: string): string {+ if (current && keys.some((k) => k.key === current)) return current;+ const named = keys.find((k) => k.key.toLowerCase() === 'name');+ return (named ?? keys[0])?.key ?? '';+}++export interface IGeoMatch {+ /** For each row, the indices of the features its value points at. Empty when nothing matched. */+ rowFeatures: number[][];+ /** Indices of the rows that found a feature. */+ matchedRows: number[];+ /** Rows whose value is blank, so there was nothing to look up. */+ emptyRows: number;+ /** Rows with a value that no feature carries. */+ unmatchedRows: number;+ /**+ * How many different non-blank values the rows hold. Values count as the data has them, so+ * `East` and ` East ` are two: the aggregation upstream keeps them in separate rows.+ */+ distinctValues: number;+ /** How many of those found a feature. */+ matchedValues: number;+ /** The distinct values behind `unmatchedRows` as trimmed text, in the order they first appear. */+ unmatchedValues: string[];+ /**+ * Groups of differently written values that reach the same feature, such as `East`, `EAST`+ * and ` East `, as the data has them. The data keeps them as separate rows, so their shapes+ * are drawn on top of each other.+ */+ sharedValues: unknown[][];+ /** Features that no row points at. */+ unusedFeatures: number[];+ /** How many features have a value under the key at all. Zero means the key is wrong for this file. */+ keyedFeatures: number;+ /** A few of the values the features carry under the key, to show what the map expects. */+ featureSamples: string[];+}++const push = (index: Map<string, number[]>, key: string, i: number) => {+ const list = index.get(key);+ if (list) list.push(i);+ else index.set(key, [i]);+};++/**+ * Joins data values to features through `key`. Builds a lookup table once, so the cost grows with+ * rows plus features. A value is tried as written first and then in its normalized form, so a file+ * whose keys differ only by case still resolves each of them exactly. Several features may share a+ * key, as when each island of a country is its own feature. A row then gets all of them.+ *+ * Two values that differ only in spelling reach the same feature. This function does not merge+ * their rows, because only the aggregation knows how to combine them. It reports them in+ * `sharedValues` instead.+ */+export function matchFeatures(values: readonly unknown[], features: readonly Feature[], key: string): IGeoMatch {+ const exact = new Map<string, number[]>();+ const loose = new Map<string, number[]>();+ const featureSamples: string[] = [];+ let keyedFeatures = 0;+ features.forEach((feature, i) => {+ const text = geoValueText(featureKeyValue(feature, key));+ if (!text) return;+ keyedFeatures += 1;+ if (featureSamples.length < SAMPLE_LIMIT && !featureSamples.includes(text)) featureSamples.push(text);+ push(exact, text, i);+ push(loose, normalizeGeoValue(text), i);+ });++ const used = new Set<number>();+ const unmatched = new Set<string>();+ // Each distinct value and the features it reaches, looked up once. The key is the value as the+ // data has it, not its trimmed text, because that is what tells one row's group from another's.+ const resolved = new Map<unknown, number[] | undefined>();+ const matchedRows: number[] = [];+ let emptyRows = 0;+ let unmatchedRows = 0;+ let matchedValues = 0;+ const rowFeatures = values.map((value, row) => {+ const text = geoValueText(value);+ if (!text) {+ emptyRows += 1;+ return [];+ }+ let hit = resolved.get(value);+ if (hit === undefined && !resolved.has(value)) {+ hit = exact.get(text) ?? loose.get(normalizeGeoValue(text));+ resolved.set(value, hit);+ if (hit) {+ matchedValues += 1;+ for (const i of hit) used.add(i);+ }+ }+ if (!hit) {+ unmatchedRows += 1;+ unmatched.add(text);+ return [];+ }+ matchedRows.push(row);+ return hit;+ });++ const reaching = new Map<number, unknown[]>();+ for (const [value, hit] of resolved) {+ if (!hit) continue;+ for (const i of hit) {+ const list = reaching.get(i);+ if (list) list.push(value);+ else reaching.set(i, [value]);+ }+ }+ const shared = new Map<string, unknown[]>();+ for (const list of reaching.values()) {+ if (list.length > 1) shared.set(list.map(quoteGeoValue).join('\u0000'), list);+ }++ const unusedFeatures: number[] = [];+ for (let i = 0; i < features.length; i++) {+ if (!used.has(i)) unusedFeatures.push(i);+ }+ return {+ rowFeatures,+ matchedRows,+ emptyRows,+ unmatchedRows,+ distinctValues: resolved.size,+ matchedValues,+ unmatchedValues: [...unmatched],+ sharedValues: [...shared.values()],+ unusedFeatures,+ keyedFeatures,+ featureSamples,+ };+}diff --git a/packages/graphic-walker/src/lib/geo/parse.test.ts b/packages/graphic-walker/src/lib/geo/parse.test.tsnew file mode 100644index 00000000..c75b58cf--- /dev/null+++ b/packages/graphic-walker/src/lib/geo/parse.test.ts@@ -0,0 +1,115 @@+import { GeoDataError, fetchGeoJson, geoDataErrorOf, isTopology, parseGeoText, toFeatureCollection, topologyObjectKeys } from './parse';++const square = [[0, 0], [1, 0], [1, 1], [0, 1], [0, 0]];+const feature = { type: 'Feature', id: 'a', properties: { name: 'A' }, geometry: { type: 'Polygon', coordinates: [square] } };+const collection = { type: 'FeatureCollection', features: [feature] };+const topology = {+ type: 'Topology',+ arcs: [square, [[5, 5], [6, 5], [6, 6], [5, 5]]],+ objects: {+ outline: { type: 'Polygon', arcs: [[0]], properties: { name: 'Whole' } },+ regions: {+ type: 'GeometryCollection',+ geometries: [+ { type: 'Polygon', arcs: [[0]], id: 'a', properties: { name: 'A' } },+ { type: 'Polygon', arcs: [[1]], id: 'b', properties: { name: 'B' } },+ ],+ },+ },+};+const codeOf = (run: () => unknown) => {+ try {+ run();+ } catch (error) {+ return geoDataErrorOf(error);+ }+ return undefined;+};++describe('toFeatureCollection', () => {+ it('takes a FeatureCollection as it is and wraps a lone feature', () => {+ expect(toFeatureCollection(collection)).toBe(collection);+ expect(toFeatureCollection(feature)).toEqual(collection);+ });++ it('converts a topology, whatever the caller thought the file was', () => {+ expect(isTopology(topology)).toBe(true);+ expect(topologyObjectKeys(topology)).toEqual(['outline', 'regions']);+ expect(topologyObjectKeys(collection)).toEqual([]);+ const regions = toFeatureCollection(topology, 'regions');+ expect(regions.features.map((f) => [f.id, f.properties?.name])).toEqual([+ ['a', 'A'],+ ['b', 'B'],+ ]);+ expect(regions.features[0].geometry).toEqual({ type: 'Polygon', coordinates: [square] });+ });++ it('uses the first object by default, and wraps an object that is a single shape', () => {+ const outline = toFeatureCollection(topology);+ expect(outline.type).toBe('FeatureCollection');+ expect(outline.features).toHaveLength(1);+ expect(outline.features[0].properties).toEqual({ name: 'Whole' });+ });++ it('names the objects a topology has when the requested one is missing', () => {+ expect(codeOf(() => toFeatureCollection(topology, 'states'))).toEqual({ code: 'object', detail: 'outline, regions' });+ });++ it('rejects JSON that holds no shapes', () => {+ expect(codeOf(() => toFeatureCollection({ rows: [] }))).toEqual({ code: 'format', detail: '' });+ expect(codeOf(() => toFeatureCollection({ type: 'Polygon', coordinates: [square] }))).toEqual({ code: 'format', detail: 'Polygon' });+ expect(codeOf(() => toFeatureCollection([collection]))).toEqual({ code: 'format', detail: '' });+ expect(codeOf(() => toFeatureCollection(null))).toEqual({ code: 'format', detail: '' });+ expect(codeOf(() => toFeatureCollection('text'))).toEqual({ code: 'format', detail: '' });+ });++ it('rejects a collection whose features are not objects, and keeps a feature without geometry', () => {+ expect(codeOf(() => toFeatureCollection({ type: 'FeatureCollection', features: [null] }))).toEqual({ code: 'format', detail: 'features' });+ expect(codeOf(() => toFeatureCollection({ type: 'FeatureCollection', features: [feature, 'text'] }))).toEqual({ code: 'format', detail: 'features' });+ const bare = { type: 'FeatureCollection', features: [{ type: 'Feature', properties: { name: 'A' }, geometry: null }] };+ expect(toFeatureCollection(bare)).toBe(bare);+ });+});++describe('parseGeoText', () => {+ it('parses JSON and says so when the text is something else', () => {+ expect(parseGeoText(JSON.stringify(collection))).toEqual(collection);+ expect(codeOf(() => parseGeoText('<html>Not found</html>'))?.code).toBe('json');+ });+});++describe('geoDataErrorOf', () => {+ it('reads a GeoDataError and treats anything else as a format problem', () => {+ expect(geoDataErrorOf(new GeoDataError('http', '404'))).toEqual({ code: 'http', detail: '404' });+ expect(geoDataErrorOf(new TypeError('boom'))).toEqual({ code: 'format', detail: 'boom' });+ expect(geoDataErrorOf('invalid geojson')).toEqual({ code: 'format', detail: '' });+ });+});++describe('fetchGeoJson', () => {+ const realFetch = globalThis.fetch;+ afterEach(() => {+ globalThis.fetch = realFetch;+ });+ const answer = (response: Partial<Response> | Error) => {+ globalThis.fetch = jest.fn(async () => {+ if (response instanceof Error) throw response;+ return response as Response;+ });+ };+ const failure = async () => geoDataErrorOf(await fetchGeoJson('https://example.test/map.json').catch((e) => e));++ it('returns the parsed file', async () => {+ answer({ ok: true, status: 200, text: async () => JSON.stringify(collection) });+ expect(await fetchGeoJson('https://example.test/map.json')).toEqual(collection);+ });++ it('tells a failed request, an error status and a non-JSON answer apart', async () => {+ answer(new TypeError('Failed to fetch'));+ expect(await failure()).toEqual({ code: 'network', detail: 'Failed to fetch' });+ answer({ ok: false, status: 404, text: async () => 'Not Found' });+ expect(await failure()).toEqual({ code: 'http', detail: '404' });+ answer({ ok: true, status: 200, text: async () => '<html></html>' });+ expect((await failure()).code).toBe('json');+ });+});diff --git a/packages/graphic-walker/src/lib/geo/parse.ts b/packages/graphic-walker/src/lib/geo/parse.tsnew file mode 100644index 00000000..f2f4b908--- /dev/null+++ b/packages/graphic-walker/src/lib/geo/parse.ts@@ -0,0 +1,96 @@+import { feature } from 'topojson-client';+import type { Feature, FeatureCollection } from 'geojson';++/**+ * Why geographic data could not be used.+ * - `network`: the request did not complete.+ * - `http`: the server answered with an error status, kept in `detail`.+ * - `json`: the text is not JSON.+ * - `format`: valid JSON that is neither a GeoJSON FeatureCollection nor a TopoJSON topology.+ * - `object`: the topology has no object of the requested name. `detail` lists the ones it has.+ */+export type GeoDataErrorCode = 'network' | 'http' | 'json' | 'format' | 'object';++export class GeoDataError extends Error {+ readonly code: GeoDataErrorCode;+ readonly detail: string;+ constructor(code: GeoDataErrorCode, detail = '') {+ super(detail ? `${code}: ${detail}` : code);+ this.name = 'GeoDataError';+ this.code = code;+ this.detail = detail;+ }+}++/** Reads the code off any thrown value. Anything that is not a GeoDataError counts as a format problem. */+export function geoDataErrorOf(error: unknown): { code: GeoDataErrorCode; detail: string } {+ if (error && typeof error === 'object' && 'code' in error && 'detail' in error) {+ const { code, detail } = error as GeoDataError;+ return { code, detail };+ }+ return { code: 'format', detail: error instanceof Error ? error.message : '' };+}++const isRecord = (value: unknown): value is Record<string, any> => typeof value === 'object' && value !== null && !Array.isArray(value);++export function isTopology(json: unknown): boolean {+ return isRecord(json) && json.type === 'Topology' && isRecord(json.objects);+}++/** Names of the objects in a topology. Empty for anything else. */+export function topologyObjectKeys(json: unknown): string[] {+ return isTopology(json) ? Object.keys((json as { objects: object }).objects) : [];+}++/** Parses the text of a file or response. Throws a GeoDataError with code `json` when it is not JSON. */+export function parseGeoText(text: string): unknown {+ try {+ return JSON.parse(text);+ } catch (error) {+ throw new GeoDataError('json', error instanceof Error ? error.message : '');+ }+}++/**+ * Turns parsed GeoJSON or TopoJSON into a FeatureCollection. The format is read from the content,+ * so a topology is converted whatever format the caller believed it had. `objectKey` picks the+ * topology object and defaults to the first one.+ */+export function toFeatureCollection(json: unknown, objectKey?: string): FeatureCollection {+ if (!isRecord(json)) throw new GeoDataError('format');+ if (isTopology(json)) {+ const keys = topologyObjectKeys(json);+ const key = objectKey || keys[0];+ if (!key || !keys.includes(key)) throw new GeoDataError('object', keys.join(', '));+ const converted = feature(json as Parameters<typeof feature>[0], key) as unknown as Feature | FeatureCollection;+ return converted.type === 'FeatureCollection' ? converted : { type: 'FeatureCollection', features: [converted] };+ }+ if (Array.isArray(json.features)) {+ // A null or a bare value among the features would break everything that reads them.+ // A feature without geometry is valid GeoJSON and passes.+ if (!json.features.every(isRecord)) throw new GeoDataError('format', 'features');+ return json as unknown as FeatureCollection;+ }+ if (json.type === 'Feature' && 'geometry' in json) {+ return { type: 'FeatureCollection', features: [json as unknown as Feature] };+ }+ throw new GeoDataError('format', typeof json.type === 'string' ? json.type : '');+}++/** Downloads and parses a GeoJSON or TopoJSON file. Every failure is a GeoDataError. */+export async function fetchGeoJson(url: string, signal?: AbortSignal): Promise<unknown> {+ let response: Response;+ try {+ response = await fetch(url, { signal });+ } catch (error) {+ throw new GeoDataError('network', error instanceof Error ? error.message : '');+ }+ if (!response.ok) throw new GeoDataError('http', String(response.status));+ let text: string;+ try {+ text = await response.text();+ } catch (error) {+ throw new GeoDataError('network', error instanceof Error ? error.message : '');+ }+ return parseGeoText(text);+}diff --git a/packages/graphic-walker/src/locales/en-US.json b/packages/graphic-walker/src/locales/en-US.jsonindex ccd370d5..e0940a2a 100644--- a/packages/graphic-walker/src/locales/en-US.json+++ b/packages/graphic-walker/src/locales/en-US.json@@ -135,6 +135,31 @@"shelf_rows": "Rows","shelf_columns": "Columns"},+ "geo_notice": {+ "no_data_title": "This map has no shapes yet",+ "no_data_desc": "Choose or upload a GeoJSON or TopoJSON file in Geography Configuration.",+ "no_field_title": "No field says which shape a row belongs to",+ "no_field_desc": "Put the field that names each region on the Geometry ID shelf.",+ "bad_key_title": "No shape has a \"{{key}}\" value",+ "bad_key_desc": "Pick another Feature ID in Geography Configuration.",+ "unmatched_title": "{{matched}} of {{total}} values matched a shape",+ "unmatched_values": "No shape for: {{values}}",+ "unmatched_more": "{{values}} and {{count}} more",+ "unmatched_key": "Shapes are matched on \"{{key}}\", with values such as {{samples}}.",+ "shared_title": "Different values point at the same shape",+ "shared_values": "Values sharing a shape are drawn on top of each other, not added up: {{values}}",+ "no_geometry_title": "Some matched shapes have nothing to draw",+ "no_geometry_values": "The file has no geometry for: {{values}}",+ "empty_rows": "Rows with no value to match: {{count}}",+ "load_failed_title": "The map shapes could not be loaded",+ "error_network": "The request did not complete. Check the address and the network.",+ "error_http": "The server answered with status {{detail}}.",+ "error_json": "The file is not valid JSON.",+ "error_format": "The file is neither a GeoJSON FeatureCollection nor a TopoJSON topology.",+ "error_object": "The TopoJSON file has no object of that name. It has: {{detail}}.",+ "retry": "Try again",+ "dismiss": "Dismiss"+ },"constant": {"row_count": "Row count","mea_key": "Measure names",@@ -370,7 +395,14 @@"href": "{{format}} URL","hrefPlaceholder": "Enter {{format}} URL","load": "Load",- "loading": "Loading Geographic Data..."+ "loading": "Loading Geographic Data...",+ "selectData": "Select geographic data",+ "manual": "Manual Configuration",+ "geoData": "Geographic data",+ "geoKeyEmpty": "Load geographic data to list its properties",+ "geoKeySample": "e.g. {{samples}}",+ "noSource": "Choose a file or load a URL first.",+ "noKeys": "The shapes in this file have no property that data can be matched on. Choose another file."}},"DatasetFields": {diff --git a/packages/graphic-walker/src/locales/ja-JP.json b/packages/graphic-walker/src/locales/ja-JP.jsonindex a6c9a10a..c003e78b 100644--- a/packages/graphic-walker/src/locales/ja-JP.json+++ b/packages/graphic-walker/src/locales/ja-JP.json@@ -134,6 +134,31 @@"shelf_rows": "行","shelf_columns": "列"},+ "geo_notice": {+ "no_data_title": "この地図にはまだ図形がありません",+ "no_data_desc": "「地理情報設定」で GeoJSON または TopoJSON ファイルを選択するかアップロードしてください。",+ "no_field_title": "各行がどの地域に属するかを示すフィールドがありません",+ "no_field_desc": "地域の名前またはコードを持つフィールドを「地理ID」に置いてください。",+ "bad_key_title": "「{{key}}」の値を持つ図形がありません",+ "bad_key_desc": "「地理情報設定」で別のフィーチャーIDを選んでください。",+ "unmatched_title": "{{total}} 件の値のうち {{matched}} 件が図形に一致しました",+ "unmatched_values": "図形が見つからない値: {{values}}",+ "unmatched_more": "{{values}} ほか {{count}} 件",+ "unmatched_key": "図形は「{{key}}」で照合します。値の例: {{samples}}",+ "shared_title": "異なる値が同じ図形を指しています",+ "shared_values": "同じ図形を指す値は重ねて描かれ、合算されません: {{values}}",+ "no_geometry_title": "一致した図形の一部は描画できません",+ "no_geometry_values": "ファイルにジオメトリがない値: {{values}}",+ "empty_rows": "{{count}} 行には照合する値がありません。",+ "load_failed_title": "地図の図形を読み込めませんでした",+ "error_network": "リクエストが完了しませんでした。URL とネットワークを確認してください。",+ "error_http": "サーバーがステータス {{detail}} を返しました。",+ "error_json": "ファイルは有効な JSON ではありません。",+ "error_format": "ファイルは GeoJSON の FeatureCollection でも TopoJSON でもありません。",+ "error_object": "TopoJSON ファイルにその名前のオブジェクトがありません。あるのは: {{detail}}",+ "retry": "再試行",+ "dismiss": "閉じる"+ },"constant": {"row_count": "行数","mea_key": "名",@@ -363,7 +388,14 @@"href": "{{format}} URL","hrefPlaceholder": "{{format}} URLを入力","load": "ロード",- "loading": "地理データを読み込んでいます..."+ "loading": "地理データを読み込んでいます...",+ "selectData": "地理データを選択",+ "manual": "手動設定",+ "geoData": "地理データ",+ "geoKeyEmpty": "地理データを読み込むとプロパティが表示されます",+ "geoKeySample": "例: {{samples}}",+ "noSource": "先にファイルを選ぶか URL を読み込んでください。",+ "noKeys": "このファイルの図形には、データと照合できるプロパティがありません。別のファイルを選んでください。"}},"DatasetFields": {diff --git a/packages/graphic-walker/src/locales/zh-CN.json b/packages/graphic-walker/src/locales/zh-CN.jsonindex d4b14d75..e8d06429 100644--- a/packages/graphic-walker/src/locales/zh-CN.json+++ b/packages/graphic-walker/src/locales/zh-CN.json@@ -134,6 +134,31 @@"shelf_rows": "行","shelf_columns": "列"},+ "geo_notice": {+ "no_data_title": "这张地图还没有区域形状",+ "no_data_desc": "在“地理信息配置”里选择或上传 GeoJSON 或 TopoJSON 文件。",+ "no_field_title": "还没有字段指明每行数据属于哪个区域",+ "no_field_desc": "把表示区域名称或代码的字段拖到“地理 ID”栏。",+ "bad_key_title": "没有区域带“{{key}}”这个属性",+ "bad_key_desc": "在“地理信息配置”里换一个地理 ID 属性。",+ "unmatched_title": "{{total}} 个值里有 {{matched}} 个匹配到区域",+ "unmatched_values": "没有匹配到区域的值:{{values}}",+ "unmatched_more": "{{values}},另有 {{count}} 个",+ "unmatched_key": "地图按“{{key}}”属性匹配,它的值是这样的:{{samples}}。",+ "shared_title": "有不同的值指向同一个区域",+ "shared_values": "指向同一区域的值会叠在一起画,数值不会相加:{{values}}",+ "no_geometry_title": "有些匹配到的区域没有可画的形状",+ "no_geometry_values": "文件里这些区域没有几何数据:{{values}}",+ "empty_rows": "{{count}} 行没有可用来匹配的值。",+ "load_failed_title": "地图形状加载失败",+ "error_network": "请求没有完成。请检查地址和网络。",+ "error_http": "服务器返回了状态码 {{detail}}。",+ "error_json": "文件不是有效的 JSON。",+ "error_format": "文件既不是 GeoJSON FeatureCollection,也不是 TopoJSON。",+ "error_object": "TopoJSON 文件里没有这个名字的对象。文件里有:{{detail}}。",+ "retry": "重试",+ "dismiss": "关闭"+ },"constant": {"row_count": "行数","mea_key": "度量名称",@@ -369,7 +394,14 @@"href": "{{format}} URL","hrefPlaceholder": "输入在线资源地址","load": "加载",- "loading": "加载地理数据中..."+ "loading": "加载地理数据中...",+ "selectData": "选择地理数据",+ "manual": "手动配置",+ "geoData": "地理数据",+ "geoKeyEmpty": "加载地理数据后才能列出属性",+ "geoKeySample": "例如 {{samples}}",+ "noSource": "请先选择文件或加载一个 URL。",+ "noKeys": "这个文件里的区域没有可用来匹配数据的属性。请换一个文件。"}},"DatasetFields": {diff --git a/packages/graphic-walker/src/store/visualSpecStore.ts b/packages/graphic-walker/src/store/visualSpecStore.tsindex b35356a3..4bf125d8 100644--- a/packages/graphic-walker/src/store/visualSpecStore.ts+++ b/packages/graphic-walker/src/store/visualSpecStore.ts@@ -16,7 +16,7 @@ import {} from '../models/visSpecHistory';import { create } from '../models/withHistory';import { emptyEncodings, forwardVisualConfigs, visSpecDecoder } from '../utils/save';-import { feature } from 'topojson-client';+import { toFeatureCollection } from '../lib/geo/parse';import type { FeatureCollection } from 'geojson';import {DraggableFieldState,@@ -771,10 +771,11 @@ export class VizSpecStore {}setGeographicData(data: IGeographicData, geoKey: string, geoUrl?: IGeoUrl) {- 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);+ let geoJSON: FeatureCollection;+ try {+ geoJSON = toFeatureCollection(data.data, data.type === 'TopoJSON' ? data.objectKey : undefined);+ } catch (error) {+ console.error('Invalid geographic data: expected a GeoJSON FeatureCollection or a TopoJSON topology.', error);return;}this.localGeoJSON = geoJSON;@@ -785,6 +786,11 @@ export class VizSpecStore {}}+ /** Points the chart at geometry behind a URL and drops any geometry stored in the chart itself. */+ setGeoUrl(geoUrl: IGeoUrl, geoKey: string) {+ this.visList[this.visIndex] = performers.setGeoData(this.visList[this.visIndex], undefined, geoKey, geoUrl);+ }+clearGeographicData() {this.visList[this.visIndex] = performers.setGeoData(this.visList[this.visIndex], undefined, undefined, undefined);}diff --git a/packages/graphic-walker/src/tersespecSchema.test.ts b/packages/graphic-walker/src/tersespecSchema.test.tsnew file mode 100644index 00000000..c78b91cb--- /dev/null+++ b/packages/graphic-walker/src/tersespecSchema.test.ts@@ -0,0 +1,20 @@+import fs from 'fs';+import path from 'path';++// The TerseSpec schema is generated into this package by `yarn gen-schema`. The playground keeps the+// copy that is served to the public. Both must accept what the types accept.+const read = (file: string) => JSON.parse(fs.readFileSync(path.resolve(__dirname, file), 'utf8'));+const library = read('../public/tersespec_v1.json');+const published = read('../../playground/public/tersespec_v1.json');++describe('the TerseSpec JSON Schema', () => {+ it('lets a TopoJSON address name the object to draw', () => {+ for (const schema of [library, published]) {+ expect(schema.definitions.IGeoUrl.properties.objectKey).toEqual(expect.objectContaining({ type: 'string' }));+ }+ });++ it('is the same in the playground as in the library', () => {+ expect(published).toEqual(library);+ });+});diff --git a/packages/graphic-walker/tests/e2e/geo-map.bare.json b/packages/graphic-walker/tests/e2e/geo-map.bare.jsonnew file mode 100644index 00000000..53056f45--- /dev/null+++ b/packages/graphic-walker/tests/e2e/geo-map.bare.json@@ -0,0 +1,7 @@+{+ "type": "FeatureCollection",+ "features": [+ { "type": "Feature", "properties": {}, "geometry": { "type": "Polygon", "coordinates": [[[10, -10], [30, -10], [30, 10], [10, 10], [10, -10]]] } },+ { "type": "Feature", "properties": {}, "geometry": { "type": "Polygon", "coordinates": [[[-30, -10], [-10, -10], [-10, 10], [-30, 10], [-30, -10]]] } }+ ]+}diff --git a/packages/graphic-walker/tests/e2e/geo-map.fixture.tsx b/packages/graphic-walker/tests/e2e/geo-map.fixture.tsxnew file mode 100644index 00000000..94a2a7f6--- /dev/null+++ b/packages/graphic-walker/tests/e2e/geo-map.fixture.tsx@@ -0,0 +1,160 @@+import React from 'react';+import { createRoot } from 'react-dom/client';+// The published entry point, as a host application would use it.+import { GraphicWalker, getComputation } from '@kanaries/graphic-walker';+import { emptyEncodings, emptyVisualConfig, emptyVisualLayout } from '../../src/utils/save';+import type { IChart, IGeoDataItem, IRow, IViewField, IVisualLayout } from '../../src/interfaces';+import type { FeatureCollection } from 'geojson';+import type { VizSpecStore } from '../../src/store/visualSpecStore';+import { shapes } from './geo-map.shapes';+// The same squares as a topology with two objects: `halves` comes first, `all` holds every square.+import topology from './geo-map.topology.json';++/** A filled map in the production package, with shapes and data that live in this page. */+export interface MapRequest {+ /** The feature key the Region field is matched on. */+ geoKey?: string;+ /** The field shown as a label on each shape. */+ text?: 'Region' | 'Note' | 'Sales';+ /** Leaves the chart without shapes. */+ noShapes?: boolean;+ /** Points the chart at shapes behind a URL instead of storing them in the chart. */+ geoUrl?: IVisualLayout['geoUrl'];+ showAll?: boolean;+ /** Stores these shapes in the chart instead of the three squares. */+ geojson?: FeatureCollection;+ /** Leaves the basemap to the host's theme instead of setting it on the chart. */+ themeTiles?: boolean;+}+export interface MapFixture {+ load(request: MapRequest): void;+ saved(): IChart;+ setLayout<K extends keyof IVisualLayout>(key: K, value: IVisualLayout[K]): void;+ openSettings(): void;+ /** Keeps every download from finishing until `release` is called. */+ hold(): void;+ release(): void;+ /** The text of files a user could upload or load by URL, and where this server keeps them. */+ files: { topology: string; shapes: string; topologyUrl: string; missingUrl: string };+ /** Set by markup in the data, if any of it ever runs. */+ scriptRan(): boolean;+}+declare global {+ interface Window {+ geo: MapFixture;+ __scriptRan?: boolean;+ }+}++const dimension = (fid: string): IViewField => ({ fid, name: fid, semanticType: 'nominal', analyticType: 'dimension' });+const measure = (fid: string): IViewField => ({ fid, name: fid, semanticType: 'quantitative', analyticType: 'measure', aggName: 'sum' });+const fields = [dimension('Region'), dimension('Note'), measure('Sales')];+const byId = new Map(fields.map((f) => [f.fid, f]));+// One row per region, plus one that names none. The note of the first is markup that must stay text.+const markup = '<img src="x" onerror="window.__scriptRan = true"><b>bold</b>';+const data: IRow[] = [+ { Region: 'East', Note: markup, Sales: 10 },+ { Region: 'West', Note: 'plain', Sales: 20 },+ { Region: '', Note: 'nowhere', Sales: 5 },+];++// What the page is opened with decides what cannot change once the editor is mounted.+const query = new URLSearchParams(location.search);+// `?clash` adds a second spelling of East, which the data keeps as a row of its own.+if (query.has('clash')) data.push({ Region: 'EAST', Note: 'shout', Sales: 20 });+// `?spaces` is a table of two rows that differ only by the spaces around the name.+if (query.has('spaces')) data.splice(0, data.length, { Region: 'East', Note: 'bare', Sales: 10 }, { Region: ' East ', Note: 'padded', Sales: 20 });++function chartOf(request: MapRequest): IChart {+ return {+ visId: 'map',+ name: 'Regions',+ encodings: {+ ...emptyEncodings,+ dimensions: fields.filter((f) => f.analyticType === 'dimension'),+ measures: fields.filter((f) => f.analyticType === 'measure'),+ geoId: [byId.get('Region')!],+ color: [byId.get('Sales')!],+ text: request.text ? [byId.get(request.text)!] : [],+ },+ config: { ...emptyVisualConfig, geoms: ['choropleth'], coordSystem: 'geographic' },+ layout: {+ ...emptyVisualLayout,+ // Map tiles are asked of this server, which has none, so no request leaves the machine.+ ...(request.themeTiles ? {} : { geoMapTileUrl: '/tests/e2e/no-tiles/{z}/{x}/{y}.png' }),+ geoKey: request.geoKey ?? 'name',+ showAllGeoshapeInChoropleth: request.showAll ?? false,+ ...(request.noShapes ? {} : request.geoUrl ? { geoUrl: request.geoUrl } : { geojson: request.geojson ?? shapes }),+ },+ };+}++// Vite emits the JSON as a file of its own and gives its address on this server.+const topologyUrl = new URL('./geo-map.topology.json', import.meta.url).href;+// Two squares with empty properties and no id: outlines that no data can be matched to.+const bareUrl = new URL('./geo-map.bare.json', import.meta.url).href;++// `?presets` gives the host two maps to choose from. Both are objects of the same file.+const presets: IGeoDataItem[] = [+ { name: 'Halves', type: 'TopoJSON', url: topologyUrl, objectKey: 'halves' },+ { name: 'All squares', type: 'TopoJSON', url: topologyUrl, objectKey: 'all' },+ { name: 'Bare outlines', type: 'GeoJSON', url: bareUrl },+];+// `?theme-no-tiles` is a host that turns the basemap off for every chart through its theme.+const noTiles = { leafletGeoTileUrl: '' };+const theme = query.has('theme-no-tiles') ? { light: noTiles, dark: noTiles } : undefined;++// Lets a test decide when a download finishes. Done in the page, because WebKit's workers reject+// the network interception Playwright offers.+let gate: Promise<void> | undefined;+let openGate = () => {};+const send = window.fetch.bind(window);+window.fetch = async (...args) => {+ await gate;+ return send(...args);+};++const storeRef = React.createRef<VizSpecStore>();+const store = () => {+ if (!storeRef.current) throw new Error('The editor is not mounted yet.');+ return storeRef.current;+};++window.geo = {+ load: (request) => store().importCode([chartOf(request)]),+ saved: () => JSON.parse(JSON.stringify(store().exportCode()))[0],+ setLayout: (key, value) => store().setVisualLayout(key, value),+ openSettings: () => store().setShowGeoJSONConfigPanel(true),+ hold: () => {+ gate = new Promise((resolve) => (openGate = resolve));+ },+ release: () => {+ gate = undefined;+ openGate();+ },+ files: {+ topology: JSON.stringify(topology),+ shapes: JSON.stringify(shapes),+ topologyUrl,+ missingUrl: '/tests/e2e/no-such-map.json',+ },+ scriptRan: () => window.__scriptRan === true,+};++createRoot(document.getElementById('root')!).render(+ <GraphicWalker+ storeRef={storeRef}+ fields={fields}+ computation={getComputation(data)}+ appearance="light"+ geoList={query.has('presets') ? presets : undefined}+ vizThemeConfig={theme}+ style={{ width: '100%', height: '100%' }}+ />+);++function ready() {+ if (!storeRef.current) return void requestAnimationFrame(ready);+ document.body.dataset.fixtureReady = 'true';+}+requestAnimationFrame(ready);diff --git a/packages/graphic-walker/tests/e2e/geo-map.html b/packages/graphic-walker/tests/e2e/geo-map.htmlnew file mode 100644index 00000000..4dbab04f--- /dev/null+++ b/packages/graphic-walker/tests/e2e/geo-map.html@@ -0,0 +1,26 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>Map fixture</title>+ <style>+ html,+ body {+ margin: 0;+ height: 100%;+ font-family: sans-serif;+ }++ #root {+ display: flex;+ width: 100vw;+ height: 100vh;+ }+ </style>+ </head>+ <body>+ <div id="root"></div>+ <script type="module" src="./geo-map.fixture.tsx"></script>+ </body>+</html>diff --git a/packages/graphic-walker/tests/e2e/geo-map.shapes.ts b/packages/graphic-walker/tests/e2e/geo-map.shapes.tsnew file mode 100644index 00000000..200e71ad--- /dev/null+++ b/packages/graphic-walker/tests/e2e/geo-map.shapes.ts@@ -0,0 +1,20 @@+import type { FeatureCollection } from 'geojson';++// Three squares near the equator, where Web Mercator is close to linear. East has a hole in its+// middle. Each has its code on the feature id and a name that is written unlike the data writes it.+const square = (west: number, south: number, size: number) => [+ [west, south],+ [west + size, south],+ [west + size, south + size],+ [west, south + size],+ [west, south],+];++export const shapes: FeatureCollection = {+ type: 'FeatureCollection',+ features: [+ { type: 'Feature', id: 'East', properties: { name: 'EAST' }, geometry: { type: 'Polygon', coordinates: [square(10, -10, 20), square(17, -3, 6)] } },+ { type: 'Feature', id: 'West', properties: { name: 'Westland' }, geometry: { type: 'Polygon', coordinates: [square(-30, -10, 20)] } },+ { type: 'Feature', id: 'North', properties: { name: 'North' }, geometry: { type: 'Polygon', coordinates: [square(-10, 20, 20)] } },+ ],+};diff --git a/packages/graphic-walker/tests/e2e/geo-map.spec.ts b/packages/graphic-walker/tests/e2e/geo-map.spec.tsnew file mode 100644index 00000000..dedbf5c3--- /dev/null+++ b/packages/graphic-walker/tests/e2e/geo-map.spec.ts@@ -0,0 +1,434 @@+import { expect, test, type Page } from '@playwright/test';+import type { MapRequest } from './geo-map.fixture';++// The filled map in the mounted editor, with shapes and data served by this page. Region holds+// East, West and one blank. The shapes are three squares: East (with a hole), West and North.+// Their names read EAST, Westland and North, and their feature ids read East, West and North.++/** `query` picks what the page fixes at mount: `?clash`, `?spaces`, `?presets` or `?theme-no-tiles`. */+async function load(page: Page, request: MapRequest, query = '') {+ await page.goto(`/tests/e2e/geo-map.html${query}`);+ await expect(page.locator('body')).toHaveAttribute('data-fixture-ready', 'true');+ await page.evaluate((r) => window.geo.load(r), request);+}+async function open(page: Page, request: MapRequest, query = '') {+ await load(page, request, query);+ await expect(map(page)).toBeVisible();+}+/** The chart's map. The settings dialog adds a second one after it for its preview. */+const map = (page: Page) => page.locator('.leaflet-container').first();+const notice = (page: Page) => page.getByTestId('geo-notice');+const noticeTitle = (page: Page) => page.getByTestId('geo-notice-title');+const labels = (page: Page) => map(page).locator('.leaflet-marker-pane .leaflet-marker-icon');+const setLayout = (page: Page, key: string, value: unknown) => page.evaluate(([k, v]) => window.geo.setLayout(k as never, v as never), [key, value] as const);++/**+ * The painted stretches along the horizontal line through the middle of the map, in CSS pixels+ * from the middle. Shapes are drawn on Leaflet's canvas and nothing else is, so this reads their+ * outline straight off the picture.+ */+async function paintedAcrossMiddle(page: Page) {+ return map(page)+ .locator('canvas')+ .evaluate((canvas: HTMLCanvasElement) => {+ const host = canvas.closest('.leaflet-container')!.getBoundingClientRect();+ const box = canvas.getBoundingClientRect();+ const scale = canvas.width / box.width;+ const y = Math.round((host.top + host.height / 2 - box.top) * scale);+ const middle = (host.left + host.width / 2 - box.left) * scale;+ const row = canvas.getContext('2d')!.getImageData(0, y, canvas.width, 1).data;+ const runs: [number, number][] = [];+ for (let x = 0; x < canvas.width; x++) {+ if (row[x * 4 + 3] === 0) continue;+ const last = runs[runs.length - 1];+ if (last && last[1] === x - 1) last[1] = x;+ else runs.push([x, x]);+ }+ return runs.map(([from, to]) => [Math.round((from - middle) / scale), Math.round((to - middle) / scale)]);+ });+}+/**+ * Where the map is looking. Leaflet writes its centre and zoom into the proxy's transform when a+ * move ends, and moves the map pane and scales the canvas on every frame of a flight. Read together,+ * they change for as long as the map is moving and hold still once it has landed.+ */+const view = (page: Page) =>+ map(page).evaluate((container) =>+ ['.leaflet-proxy', '.leaflet-map-pane', 'canvas'].map((selector) => (container.querySelector(selector) as HTMLElement | null)?.style.transform ?? '').join(' | ')+ );+async function settledView(page: Page) {+ let last = '';+ await expect+ .poll(+ async () => {+ const before = last;+ last = await view(page);+ return last !== '' && last === before;+ },+ { intervals: [400] }+ )+ .toBe(true);+ return last;+}++test('G1: values that find no shape are named on the map, and the right key resolves them', async ({ page }) => {+ await open(page, { geoKey: 'name' });+ // "East" finds EAST although the case differs. "West" is not "Westland".+ await expect(notice(page)).toHaveAttribute('data-state', 'unmatched');+ await expect(noticeTitle(page)).toHaveText('1 of 2 values matched a shape');+ await expect(notice(page)).toContainText('No shape for: West');+ await expect(notice(page)).toContainText('Rows with no value to match: 1');+ await expect(notice(page)).toContainText('Shapes are matched on "name", with values such as EAST, Westland, North.');++ // A key no shape has.+ await setLayout(page, 'geoKey', 'iso');+ await expect(notice(page)).toHaveAttribute('data-state', 'bad_key');+ await expect(noticeTitle(page)).toHaveText('No shape has a "iso" value');++ // The codes sit on the feature id, outside `properties`. Only the blank row is left to report.+ await setLayout(page, 'geoKey', 'id');+ await expect(noticeTitle(page)).toHaveText('Rows with no value to match: 1');+ await expect(notice(page)).not.toContainText('No shape for');++ await page.getByTestId('geo-notice-dismiss').click();+ await expect(notice(page)).toHaveCount(0);+ // It returns when what it has to say changes.+ await setLayout(page, 'geoKey', 'name');+ await expect(noticeTitle(page)).toHaveText('1 of 2 values matched a shape');+});++test('G2: a shape keeps its hole, and every matched shape is drawn', async ({ page }) => {+ await open(page, { geoKey: 'name' });+ // Only East is matched, so the map is centred on it and the middle of the map is its hole.+ // The map flies there once the data arrives, and the picture is only true once it has landed.+ await expect.poll(async () => (await paintedAcrossMiddle(page)).length).toBeGreaterThan(0);+ await settledView(page);+ await expect.poll(async () => (await paintedAcrossMiddle(page)).length).toBe(2);+ const [left, right] = await paintedAcrossMiddle(page);+ expect(left[1]).toBeLessThan(0);+ expect(right[0]).toBeGreaterThan(0);+ // The hole is 6 degrees wide in a square of 20.+ const hole = right[0] - left[1];+ const whole = right[1] - left[0];+ expect(hole / whole).toBeGreaterThan(0.27);+ expect(hole / whole).toBeLessThan(0.33);++ // With West matched as well, the line crosses West, then East's two sides.+ const before = await view(page);+ await setLayout(page, 'geoKey', 'id');+ await expect.poll(() => view(page)).not.toBe(before);+ await settledView(page);+ await expect.poll(async () => (await paintedAcrossMiddle(page)).length).toBe(3);+});++test('G3: the map moves when the shapes on it change, and not when anything else does', async ({ page }) => {+ await open(page, { geoKey: 'name' });+ await expect.poll(async () => (await paintedAcrossMiddle(page)).length).toBeGreaterThan(0);+ const fitted = await settledView(page);+ await map(page).locator('.leaflet-control-zoom-in').click();+ await expect.poll(() => view(page)).not.toBe(fitted);+ const zoomed = await settledView(page);++ // Settings that leave the matched shapes as they are. One of them adds the grey shapes.+ await setLayout(page, 'scaleIncludeUnmatchedChoropleth', true);+ await setLayout(page, 'showAllGeoshapeInChoropleth', true);+ await expect.poll(async () => (await paintedAcrossMiddle(page)).length).toBeGreaterThan(0);+ await page.waitForTimeout(800);+ expect(await view(page)).toBe(zoomed);++ // West is matched now, so the map has more to show and moves to show it.+ await setLayout(page, 'geoKey', 'id');+ await expect.poll(() => view(page)).not.toBe(zoomed);+});++test('G4: a label shows markup from the data as text and runs none of it', async ({ page }) => {+ await open(page, { geoKey: 'id', text: 'Note' });+ await expect(labels(page)).toHaveCount(2);+ await expect(labels(page).first()).toHaveText('<img src="x" onerror="window.__scriptRan = true"><b>bold</b>');+ await expect(labels(page).nth(1)).toHaveText('plain');+ await expect(map(page).locator('.leaflet-marker-pane').locator('img, b')).toHaveCount(0);+ expect(await page.evaluate(() => window.geo.scriptRan())).toBe(false);+});++test('G5: labels read aggregated measures, and a shape without data is labelled only by its own name', async ({ page }) => {+ await open(page, { geoKey: 'id', text: 'Sales', showAll: true });+ // North has no row, so it has no sales to show.+ await expect(labels(page)).toHaveText(['10', '20']);++ await page.evaluate(() => window.geo.load({ geoKey: 'id', text: 'Region', showAll: true }));+ await expect(labels(page)).toHaveText(['East', 'West', 'North']);+});++test('G6: a map without shapes, or with shapes that cannot be loaded, says so', async ({ page }) => {+ await open(page, { noShapes: true });+ await expect(notice(page)).toHaveAttribute('data-state', 'no_data');+ await expect(noticeTitle(page)).toHaveText('This map has no shapes yet');++ const files = await page.evaluate(() => window.geo.files);+ await page.evaluate((url) => window.geo.load({ geoUrl: { type: 'GeoJSON', url } }), files.missingUrl);+ const failed = page.getByTestId('geo-load-failed');+ await expect(failed).toHaveAttribute('data-code', 'http');+ await expect(page.getByTestId('geo-load-failed-reason')).toHaveText('The server answered with status 404.');+ await expect(page.getByTestId('geo-load-failed-retry')).toBeVisible();+ await expect(page.locator('.leaflet-container')).toHaveCount(0);++ // A topology loads whatever format the chart says it is, and the object is the one asked for.+ await page.evaluate((url) => window.geo.load({ geoKey: 'region', geoUrl: { type: 'GeoJSON', url, objectKey: 'all' } }), files.topologyUrl);+ await expect(map(page)).toBeVisible();+ await expect(noticeTitle(page)).toHaveText('Rows with no value to match: 1');+ await page.evaluate((url) => window.geo.load({ geoKey: 'region', geoUrl: { type: 'TopoJSON', url, objectKey: 'states' } }), files.topologyUrl);+ await expect(failed).toHaveAttribute('data-code', 'object');+ await expect(page.getByTestId('geo-load-failed-reason')).toHaveText('The TopoJSON file has no object of that name. It has: halves, all.');+ await expect(page.getByTestId('geo-load-failed-retry')).toHaveCount(0);+});++test('G7: the settings dialog lists the keys of a file, reports what it cannot use, and stores a URL with its object', async ({ page }) => {+ await open(page, { geoKey: 'name' });+ const files = await page.evaluate(() => window.geo.files);+ await page.evaluate(() => window.geo.openSettings());+ const dialog = page.getByRole('dialog');+ await expect(dialog).toBeVisible();+ const key = dialog.getByTestId('geo-config-key').getByRole('combobox');+ const error = dialog.getByTestId('geo-config-error');+ const file = dialog.getByTestId('geo-config-file');++ // The chart's own shapes: the key in use, with what its values look like.+ await expect(key).toContainText('name');+ await expect(key).toContainText('EAST, Westland, North');+ await expect(dialog.getByTestId('geo-config-preview')).toBeVisible();++ await file.setInputFiles({ name: 'broken.json', mimeType: 'application/json', buffer: Buffer.from('{ "type": ') });+ await expect(error).toHaveText('The file is not valid JSON.');+ await file.setInputFiles({ name: 'table.json', mimeType: 'application/json', buffer: Buffer.from('{"rows": [1, 2]}') });+ await expect(error).toHaveText('The file is neither a GeoJSON FeatureCollection nor a TopoJSON topology.');+ // A file that was refused replaces nothing.+ await expect(key).toContainText('name');+ // A collection with something that is no feature in it is refused the same way, and the dialog stays.+ await file.setInputFiles({ name: 'other.json', mimeType: 'application/json', buffer: Buffer.from('{"rows": [3]}') });+ await file.setInputFiles({ name: 'holes.json', mimeType: 'application/json', buffer: Buffer.from('{"type":"FeatureCollection","features":[null]}') });+ await expect(error).toHaveText('The file is neither a GeoJSON FeatureCollection nor a TopoJSON topology.');+ await expect(dialog).toBeVisible();+ await expect(key).toContainText('name');+ // A feature whose coordinates cannot be read is left out of the preview. The dialog stays open+ // for the user to pick something else.+ const crashes: string[] = [];+ page.on('pageerror', (e) => crashes.push(e.message));+ const noPlace = { type: 'FeatureCollection', features: [{ type: 'Feature', properties: { title: 'Nowhere' }, geometry: { type: 'Point', coordinates: [] } }] };+ await file.setInputFiles({ name: 'nowhere.json', mimeType: 'application/json', buffer: Buffer.from(JSON.stringify(noPlace)) });+ await expect(key).toContainText('title');+ await expect(key).toContainText('Nowhere');+ await expect(error).toHaveCount(0);+ await expect(dialog.getByTestId('geo-config-preview').locator('.leaflet-container')).toBeVisible();+ expect(crashes).toEqual([]);++ await dialog.getByRole('textbox').fill(files.missingUrl);+ await dialog.getByRole('button', { name: 'Load' }).click();+ await expect(error).toHaveText('The server answered with status 404.');++ // A topology by URL, loaded while the format still says GeoJSON.+ await dialog.getByRole('textbox').fill(files.topologyUrl);+ await dialog.getByRole('button', { name: 'Load' }).click();+ await expect(error).toHaveCount(0);+ await expect(dialog.getByRole('radio', { name: 'TopoJSON' })).toBeChecked();+ const object = dialog.getByTestId('geo-config-object').getByRole('combobox');+ await expect(object).toContainText('halves');+ // The file has no "name", so the key moves to one it has.+ await expect(key).toContainText('label');+ await object.click();+ await page.getByRole('option', { name: 'all', exact: true }).click();+ await expect(key).toContainText('region');+ await expect(key).toContainText('East, West, North');++ await dialog.getByRole('button', { name: 'Confirm' }).click();+ await expect(dialog).toHaveCount(0);+ const saved = await page.evaluate(() => window.geo.saved());+ // The chart keeps the address and the object, not a copy of the shapes.+ expect(saved.layout.geoUrl).toEqual({ type: 'TopoJSON', url: files.topologyUrl, objectKey: 'all' });+ expect(saved.layout.geojson).toBeUndefined();+ expect(saved.layout.geoKey).toBe('region');+ await expect(noticeTitle(page)).toHaveText('Rows with no value to match: 1');+ await expect.poll(async () => (await paintedAcrossMiddle(page)).length).toBe(2);++ // Opening the settings again and confirming them as they are changes nothing.+ await page.evaluate(() => window.geo.openSettings());+ await expect(key).toContainText('region');+ await dialog.getByRole('button', { name: 'Confirm' }).click();+ await expect(dialog).toHaveCount(0);+ const again = await page.evaluate(() => window.geo.saved());+ expect(again.layout.geoUrl).toEqual({ type: 'TopoJSON', url: files.topologyUrl, objectKey: 'all' });+ expect(again.layout.geoKey).toBe('region');+});++test('G8: an uploaded file is stored in the chart with the key chosen for it', async ({ page }) => {+ await open(page, { noShapes: true });+ const files = await page.evaluate(() => window.geo.files);+ await page.evaluate(() => window.geo.openSettings());+ const dialog = page.getByRole('dialog');+ const key = dialog.getByTestId('geo-config-key').getByRole('combobox');+ // Nothing to list yet, and nothing to confirm.+ await expect(key).toBeDisabled();+ await dialog.getByRole('button', { name: 'Confirm' }).click();+ await expect(dialog.getByTestId('geo-config-error')).toHaveText('Choose a file or load a URL first.');++ await dialog.getByTestId('geo-config-file').setInputFiles({ name: 'shapes.geojson', mimeType: 'application/geo+json', buffer: Buffer.from(files.shapes) });+ await expect(dialog.getByTestId('geo-config-error')).toHaveCount(0);+ await expect(key).toContainText('name');+ await key.click();+ await page.getByRole('option', { name: /^id/ }).click();+ await dialog.getByRole('button', { name: 'Confirm' }).click();+ await expect(dialog).toHaveCount(0);++ const saved = await page.evaluate(() => window.geo.saved());+ expect(saved.layout.geoKey).toBe('id');+ expect(saved.layout.geoUrl).toBeUndefined();+ expect(saved.layout.geojson?.features).toHaveLength(3);+ await expect(noticeTitle(page)).toHaveText('Rows with no value to match: 1');+ await expect.poll(async () => (await paintedAcrossMiddle(page)).length).toBe(3);+});++test('G9: two spellings of one region are reported, because their numbers are not added up', async ({ page }) => {+ // The data has East with 10 and EAST with 20. Both find the shape named EAST.+ await open(page, { geoKey: 'name', text: 'Sales' }, '?clash');+ await expect(noticeTitle(page)).toHaveText('2 of 3 values matched a shape');+ await expect(notice(page)).toContainText('No shape for: West');+ await expect(notice(page)).toContainText('Values sharing a shape are drawn on top of each other, not added up: "East" / "EAST"');+ // Both sums sit on the one shape. Neither is the 30 a reader would expect.+ await expect.poll(async () => (await labels(page).allTextContents()).sort()).toEqual(['10', '20']);++ // With every value matched, this is what is left to say.+ await setLayout(page, 'geoKey', 'id');+ await expect(notice(page)).toHaveAttribute('data-state', 'shared');+ await expect(noticeTitle(page)).toHaveText('Different values point at the same shape');+ await expect(notice(page)).toContainText('"East" / "EAST"');+ await expect(notice(page)).not.toContainText('No shape for');+});++test('G9b: two rows that differ only by spaces around the name are reported as well', async ({ page }) => {+ // The whole table is East with 10 and " East " with 20. Nothing else is wrong with it.+ await open(page, { geoKey: 'id', text: 'Sales' }, '?spaces');+ await expect.poll(async () => (await labels(page).allTextContents()).sort()).toEqual(['10', '20']);+ await expect(notice(page)).toHaveAttribute('data-state', 'shared');+ await expect(noticeTitle(page)).toHaveText('Different values point at the same shape');+ // The quotes show where the spaces are.+ await expect(page.getByTestId('geo-notice-line')).toHaveText('Values sharing a shape are drawn on top of each other, not added up: "East" / " East "', {+ useInnerText: true,+ });+});++test('G10: a value whose shape has no geometry is reported, since nothing is drawn for it', async ({ page }) => {+ const geojson: MapRequest['geojson'] = {+ type: 'FeatureCollection',+ features: [+ { type: 'Feature', id: 'East', properties: {}, geometry: null as never },+ { type: 'Feature', id: 'West', properties: {}, geometry: { type: 'Polygon', coordinates: [[[-30, -10], [-10, -10], [-10, 10], [-30, 10], [-30, -10]]] } },+ ],+ };+ await open(page, { geoKey: 'id', geojson });+ await expect(notice(page)).toHaveAttribute('data-state', 'no_geometry');+ await expect(noticeTitle(page)).toHaveText('Some matched shapes have nothing to draw');+ await expect(notice(page)).toContainText('The file has no geometry for: East');+ await expect.poll(async () => (await paintedAcrossMiddle(page)).length).toBe(1);+});++test('G11: a preset is told apart by its object, and cannot be confirmed before its keys are known', async ({ page }) => {+ await load(page, {}, '?presets');+ const files = await page.evaluate(() => window.geo.files);+ // The second of two presets that share one file.+ await page.evaluate((url) => window.geo.load({ geoKey: 'region', geoUrl: { type: 'TopoJSON', url, objectKey: 'all' } }), files.topologyUrl);+ await expect(map(page)).toBeVisible();+ await page.evaluate(() => window.geo.openSettings());+ const dialog = page.getByRole('dialog');+ const key = dialog.getByTestId('geo-config-key').getByRole('combobox');+ const preset = dialog.getByTestId('geo-config-preset').getByRole('combobox');+ const confirm = dialog.getByTestId('geo-config-confirm');+ await expect(preset).toContainText('All squares');+ await expect(key).toContainText('region');+ await confirm.click();+ await expect(dialog).toHaveCount(0);+ const kept = await page.evaluate(() => window.geo.saved());+ expect(kept.layout.geoUrl).toEqual({ type: 'TopoJSON', url: files.topologyUrl, objectKey: 'all' });+ expect(kept.layout.geoKey).toBe('region');++ // The other preset has "label" where this one has "region". Its file is still on the way.+ await page.evaluate(() => window.geo.openSettings());+ await expect(key).toContainText('region');+ await page.evaluate(() => window.geo.hold());+ await preset.click();+ await page.getByRole('option', { name: 'Halves', exact: true }).click();+ await expect(key).toBeDisabled();+ await expect(confirm).toBeDisabled();+ await page.evaluate(() => window.geo.release());+ await expect(key).toContainText('label');+ await expect(confirm).toBeEnabled();+ await confirm.click();+ await expect(dialog).toHaveCount(0);+ const moved = await page.evaluate(() => window.geo.saved());+ expect(moved.layout.geoUrl).toEqual({ type: 'TopoJSON', url: files.topologyUrl, objectKey: 'halves' });+ expect(moved.layout.geoKey).toBe('label');+ await expect(notice(page)).not.toHaveAttribute('data-state', 'bad_key');+});++test('G12: the preview in the settings draws no basemap when the host theme turns it off', async ({ page }) => {+ await open(page, { geoKey: 'id', themeTiles: true }, '?theme-no-tiles');+ await expect.poll(async () => (await paintedAcrossMiddle(page)).length).toBeGreaterThan(0);+ await page.evaluate(() => window.geo.openSettings());+ const preview = page.getByRole('dialog').getByTestId('geo-config-preview');+ await expect(preview.locator('.leaflet-container')).toBeVisible();+ await expect(preview.locator('.leaflet-overlay-pane path, .leaflet-overlay-pane canvas')).not.toHaveCount(0);+ await expect(page.locator('.leaflet-tile-pane .leaflet-layer')).toHaveCount(0);+});++test('G13: shapes without any property cannot be confirmed, and the dialog says why', async ({ page }) => {+ await open(page, { geoKey: 'id' }, '?presets');+ await page.evaluate(() => window.geo.openSettings());+ const dialog = page.getByRole('dialog');+ const key = dialog.getByTestId('geo-config-key').getByRole('combobox');+ const preset = dialog.getByTestId('geo-config-preset').getByRole('combobox');+ const confirm = dialog.getByTestId('geo-config-confirm');+ const error = dialog.getByTestId('geo-config-error');+ await expect(key).toContainText('id');+ await expect(confirm).toBeEnabled();++ await preset.click();+ await page.getByRole('option', { name: 'Bare outlines', exact: true }).click();+ await expect(dialog.getByTestId('geo-config-preview').locator('.leaflet-container')).toBeVisible();+ await expect(error).toHaveAttribute('data-code', 'no_keys');+ await expect(error).toHaveText('The shapes in this file have no property that data can be matched on. Choose another file.');+ await expect(key).toBeDisabled();+ await expect(confirm).toBeDisabled();++ // A preset with keys clears the message and can be saved.+ await preset.click();+ await page.getByRole('option', { name: 'All squares', exact: true }).click();+ await expect(key).toContainText('region');+ await expect(error).toHaveCount(0);+ await confirm.click();+ await expect(dialog).toHaveCount(0);+ expect((await page.evaluate(() => window.geo.saved())).layout.geoKey).toBe('region');+});++test('G14: an address that is still loading cannot be confirmed, and is saved once it has arrived', async ({ page }) => {+ await open(page, { geoKey: 'name' });+ const files = await page.evaluate(() => window.geo.files);+ await page.evaluate(() => window.geo.openSettings());+ const dialog = page.getByRole('dialog');+ const key = dialog.getByTestId('geo-config-key').getByRole('combobox');+ const confirm = dialog.getByTestId('geo-config-confirm');+ await expect(confirm).toBeEnabled();++ await page.evaluate(() => window.geo.hold());+ await dialog.getByRole('textbox').fill(files.topologyUrl);+ await dialog.getByRole('button', { name: 'Load' }).click();+ // Confirming now would close the dialog on the old shapes and drop the address.+ await expect(dialog.getByRole('button', { name: 'Load' })).toBeDisabled();+ await expect(confirm).toBeDisabled();+ await page.evaluate(() => window.geo.release());+ await expect(key).toContainText('label');+ await expect(confirm).toBeEnabled();+ await confirm.click();+ await expect(dialog).toHaveCount(0);+ const saved = await page.evaluate(() => window.geo.saved());+ expect(saved.layout.geoUrl).toEqual({ type: 'TopoJSON', url: files.topologyUrl });+ expect(saved.layout.geojson).toBeUndefined();+ expect(saved.layout.geoKey).toBe('label');+});diff --git a/packages/graphic-walker/tests/e2e/geo-map.topology.json b/packages/graphic-walker/tests/e2e/geo-map.topology.jsonnew file mode 100644index 00000000..a3ffe8b9--- /dev/null+++ b/packages/graphic-walker/tests/e2e/geo-map.topology.json@@ -0,0 +1,143 @@+{+ "type": "Topology",+ "arcs": [+ [+ [+ 10,+ -10+ ],+ [+ 30,+ -10+ ],+ [+ 30,+ 10+ ],+ [+ 10,+ 10+ ],+ [+ 10,+ -10+ ]+ ],+ [+ [+ -30,+ -10+ ],+ [+ -10,+ -10+ ],+ [+ -10,+ 10+ ],+ [+ -30,+ 10+ ],+ [+ -30,+ -10+ ]+ ],+ [+ [+ -10,+ 20+ ],+ [+ 10,+ 20+ ],+ [+ 10,+ 40+ ],+ [+ -10,+ 40+ ],+ [+ -10,+ 20+ ]+ ]+ ],+ "objects": {+ "halves": {+ "type": "GeometryCollection",+ "geometries": [+ {+ "type": "Polygon",+ "arcs": [+ [+ 0+ ]+ ],+ "id": "E",+ "properties": {+ "label": "East"+ }+ },+ {+ "type": "Polygon",+ "arcs": [+ [+ 1+ ]+ ],+ "id": "W",+ "properties": {+ "label": "West"+ }+ }+ ]+ },+ "all": {+ "type": "GeometryCollection",+ "geometries": [+ {+ "type": "Polygon",+ "arcs": [+ [+ 0+ ]+ ],+ "properties": {+ "region": "East",+ "zone": 1+ }+ },+ {+ "type": "Polygon",+ "arcs": [+ [+ 1+ ]+ ],+ "properties": {+ "region": "West",+ "zone": 2+ }+ },+ {+ "type": "Polygon",+ "arcs": [+ [+ 2+ ]+ ],+ "properties": {+ "region": "North",+ "zone": 3+ }+ }+ ]+ }+ }+}diff --git a/packages/graphic-walker/tests/e2e/vite.config.ts b/packages/graphic-walker/tests/e2e/vite.config.tsindex b98cbb5d..e29e1577 100644--- a/packages/graphic-walker/tests/e2e/vite.config.ts+++ b/packages/graphic-walker/tests/e2e/vite.config.ts@@ -20,8 +20,10 @@ export default defineConfig({build: {outDir: path.resolve(workspaceRoot, 'node_modules/.cache/graphic-walker-e2e'),emptyOutDir: true,+ // Files a fixture loads by URL stay files, so a test fetches them over HTTP as a user's browser would.+ assetsInlineLimit: 0,rollupOptions: {- input: [path.resolve(__dirname, 'issue-501.html'), path.resolve(__dirname, 'native-renderer.html')],+ input: [path.resolve(__dirname, 'issue-501.html'), path.resolve(__dirname, 'native-renderer.html'), path.resolve(__dirname, 'geo-map.html')],},},preview: {diff --git a/packages/playground/public/tersespec_v1.json b/packages/playground/public/tersespec_v1.jsonindex 3c317427..33d21fb7 100644--- a/packages/playground/public/tersespec_v1.json+++ b/packages/playground/public/tersespec_v1.json@@ -265,9 +265,11 @@"type": "string","enum": ["vega-lite",- "observable-plot"+ "observable-plot",+ "native"],- "default": "vega-lite"+ "description": "'native' is the bundled default worksheet renderer. Unsupported charts show a notice; renderers never replace one another automatically. Maps and tables use their own components regardless of this setting.",+ "default": "native"}},"additionalProperties": false@@ -876,6 +878,10 @@},"url": {"type": "string"+ },+ "objectKey": {+ "type": "string",+ "description": "For TopoJSON: the name of the object to draw. Defaults to the first key of `objects`."}},"required": [