From b90ef9b5fd2cb7c8fc461425238857e4823a80c6 Mon Sep 17 00:00:00 2001 From: Will Mobley Date: Fri, 20 Nov 2026 13:08:38 -0600 Subject: [PATCH] Framing boundary picker: readable names, grouped, searchable, families collapsed Boundary options show region names (never ids), sorted and grouped by category, in a type-to-filter combobox. Numbered parts of one registered region (TRINITY_1..55) collapse into one family entry that selects the whole region and expands to single parts. The map shows one category at a time and draws the selection highlighted over faint context. Layer configs gain label_field, label_prefix and label_suffix so the GMA layer reads 'GMA 1' instead of '1'. --- svo-adapter-service/app/main.py | 5 + .../lib/__tests__/spatial-boundaries.test.ts | 119 +++++++++ ui-react/src/lib/spatial-boundaries.ts | 246 ++++++++++++++++++ .../modeling/thread/BoundaryCombobox.tsx | 173 ++++++++++++ .../pages/modeling/thread/SpatialScopeMap.tsx | 190 +++++++++----- .../thread/__tests__/MintParameters.test.tsx | 16 +- .../thread/__tests__/SpatialScopeMap.test.tsx | 156 +++++++++++ .../modeling/thread/wizard/FramingStep.tsx | 2 +- 8 files changed, 825 insertions(+), 82 deletions(-) create mode 100644 ui-react/src/lib/__tests__/spatial-boundaries.test.ts create mode 100644 ui-react/src/lib/spatial-boundaries.ts create mode 100644 ui-react/src/pages/modeling/thread/BoundaryCombobox.tsx create mode 100644 ui-react/src/pages/modeling/thread/__tests__/SpatialScopeMap.test.tsx diff --git a/svo-adapter-service/app/main.py b/svo-adapter-service/app/main.py index 171e28fd..f170b75c 100755 --- a/svo-adapter-service/app/main.py +++ b/svo-adapter-service/app/main.py @@ -1046,6 +1046,8 @@ def _default_spatial_layers() -> list[dict[str, Any]]: "source_type": "feature-service", "geometry_type": "polygon", "default_filter_field": "GMAnum", + # The layer's only attribute is the number. + "label_prefix": "GMA ", "crs": "EPSG:4326", "format": "geojson", "tags": ["twdb", "gma", "boundary"], @@ -1058,6 +1060,7 @@ def _default_spatial_layers() -> list[dict[str, Any]]: "source_type": "feature-service", "geometry_type": "polygon", "default_filter_field": "DistrictName", + "label_field": "DistrictName", "crs": "EPSG:4326", "format": "geojson", "tags": ["twdb", "gcd", "boundary"], @@ -1070,6 +1073,8 @@ def _default_spatial_layers() -> list[dict[str, Any]]: "source_type": "feature-service", "geometry_type": "polygon", "default_filter_field": "Name", + "label_field": "Name", + "label_suffix": " County", "crs": "EPSG:4326", "format": "geojson", "tags": ["twdb", "county", "boundary"], diff --git a/ui-react/src/lib/__tests__/spatial-boundaries.test.ts b/ui-react/src/lib/__tests__/spatial-boundaries.test.ts new file mode 100644 index 00000000..2e4df4a9 --- /dev/null +++ b/ui-react/src/lib/__tests__/spatial-boundaries.test.ts @@ -0,0 +1,119 @@ +import { describe, expect, it } from 'vitest'; + +import { + boundaryFeatureLabel, + boundaryGroups, + buildLayerOptions, + buildRegionOptions, + filterBoundaryOptions, + findBoundaryOption, + prettyRegionName, + regionFamilyOf, +} from '@/lib/spatial-boundaries'; + +const region = (id: string, name: string, category = 'Aquifers'): GeoJSON.Feature => ({ + type: 'Feature', + properties: { region_id: id, region_name: name, category_name: category }, + geometry: { type: 'Point', coordinates: [0, 0] }, +}); + +describe('boundaryFeatureLabel', () => { + it('labels a number-only layer from the configured prefix', () => { + expect(boundaryFeatureLabel({ GMAnum: 1 }, 'GMAnum', { label_prefix: 'GMA ' })).toBe('GMA 1'); + }); + + it('adds the name when the layer has one', () => { + expect( + boundaryFeatureLabel({ GMAnum: 8, GMAName: 'Gulf Coast' }, 'GMAnum', { + label_prefix: 'GMA ', + }), + ).toBe('GMA 8 — Gulf Coast'); + }); + + it('uses the configured label field and suffix for named layers', () => { + expect( + boundaryFeatureLabel({ Name: 'Anderson', Fips: 1 }, 'Name', { + label_field: 'Name', + label_suffix: ' County', + }), + ).toBe('Anderson County'); + }); +}); + +describe('regionFamilyOf', () => { + it('finds the family of a numbered name', () => { + expect(regionFamilyOf('TRINITY_53')?.label).toBe('Trinity'); + expect(regionFamilyOf('EDWARDS-TRINITY_3')?.label).toBe('Edwards-Trinity'); + }); + it('ignores names without a base or a number', () => { + expect(regionFamilyOf('Alwero')).toBeNull(); + expect(regionFamilyOf('1')).toBeNull(); + }); + it('prettifies underscore names only', () => { + expect(prettyRegionName('SEYMOUR_3')).toBe('Seymour 3'); + expect(prettyRegionName('GMA 12')).toBe('GMA 12'); + }); +}); + +describe('buildRegionOptions', () => { + const features = [ + region('zz1', 'TRINITY_2'), + region('zz2', 'TRINITY_10'), + region('zz3', 'TRINITY_1'), + region('aa9', 'Alwero', 'Watersheds'), + region('lone', 'CARRIZO_1'), + region('1790434732014', '1', 'Watersheds'), + ]; + const options = buildRegionOptions(features, 'region_id'); + + it('never puts an id in a label', () => { + for (const option of options) { + expect(option.label).not.toMatch(/zz\d|aa9|lone|1790434732014/); + } + }); + + it('collapses numbered parts into one family that selects every part', () => { + const family = options.find((o) => o.label === 'Trinity (3 parts)'); + expect(family?.values.sort()).toEqual(['zz1', 'zz2', 'zz3']); + expect(family?.parts?.map((p) => p.label)).toEqual(['Trinity 1', 'Trinity 2', 'Trinity 10']); + expect(options.filter((o) => o.label.startsWith('Trinity'))).toHaveLength(1); + }); + + it('leaves a lone numbered region as itself', () => { + expect(options.find((o) => o.label === 'Carrizo 1')?.parts).toBeUndefined(); + }); + + it('sorts by group then name, and lists the groups', () => { + expect(options.map((o) => o.label)).toEqual(['Carrizo 1', 'Trinity (3 parts)', '1', 'Alwero']); + expect(boundaryGroups(options)).toEqual(['Aquifers', 'Watersheds']); + }); + + it('filters by typing, keeping only matching parts of a family', () => { + const hits = filterBoundaryOptions(options, 'trinity 10'); + expect(hits).toHaveLength(1); + expect(hits[0]?.parts?.map((p) => p.label)).toEqual(['Trinity 10']); + expect(filterBoundaryOptions(options, 'alw').map((o) => o.label)).toEqual(['Alwero']); + expect(filterBoundaryOptions(options, 'nothing')).toEqual([]); + }); + + it('finds a saved single part or family by its value', () => { + expect(findBoundaryOption(options, 'zz2')?.label).toBe('Trinity 10'); + const family = options.find((o) => o.parts); + expect(findBoundaryOption(options, family?.value ?? '')?.label).toBe('Trinity (3 parts)'); + }); +}); + +describe('buildLayerOptions', () => { + it('labels and sorts GMA features', () => { + const features = [10, 2, 1].map( + (n): GeoJSON.Feature => ({ + type: 'Feature', + properties: { GMAnum: n }, + geometry: { type: 'Point', coordinates: [0, 0] }, + }), + ); + expect( + buildLayerOptions(features, 'GMAnum', { label_prefix: 'GMA ' }).map((o) => o.label), + ).toEqual(['GMA 1', 'GMA 2', 'GMA 10']); + }); +}); diff --git a/ui-react/src/lib/spatial-boundaries.ts b/ui-react/src/lib/spatial-boundaries.ts new file mode 100644 index 00000000..90afd971 --- /dev/null +++ b/ui-react/src/lib/spatial-boundaries.ts @@ -0,0 +1,246 @@ +/** + * Boundary picker options for the Framing step's spatial map. + * + * A boundary option is what a person reads in the dropdown: a name, never an + * id. The id stays in `value`. Registered MINT regions that are numbered parts + * of one region (TRINITY_1 .. TRINITY_55) collapse into one family option whose + * `parts` the user can expand. + */ + +/** How a layer labels its features. Comes from the layer config, not the component. */ +export interface BoundaryLabelConfig { + /** Attribute holding the readable name. Defaults to the filter field. */ + label_field?: string; + /** Text before the label, e.g. "GMA " for a layer whose only attribute is a number. */ + label_prefix?: string; + /** Text after a label that is only the filter value, e.g. " County". */ + label_suffix?: string; +} + +export interface BoundaryOption { + /** The filter value saved with the selection. A family joins its parts' values with commas. */ + value: string; + /** Every filter value the option stands for. One for a single boundary. */ + values: string[]; + label: string; + /** Category heading for registered MINT regions. */ + group?: string; + /** Present on a family: the numbered parts, sorted. */ + parts?: BoundaryOption[]; +} + +/** Attributes some layers carry a name in, tried in order when the config names none. */ +const NAME_ATTRIBUTES = [ + 'GMAName', + 'GMA_Name', + 'GMA_NAME', + 'DistrictName', + 'Name', + 'name', + 'region_name', + 'label', +]; + +const collator = new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' }); + +export function compareLabels(left: string, right: string): number { + return collator.compare(left, right); +} + +/** "TRINITY_53" becomes "Trinity 53". Names without an underscore are left as written. */ +export function prettyRegionName(name: string): string { + const trimmed = name.trim(); + if (!trimmed.includes('_')) return trimmed; + const spaced = trimmed.replace(/_+/g, ' '); + if (spaced !== spaced.toUpperCase()) return spaced; + return spaced.toLowerCase().replace(/(^|[\s-])([a-z])/g, (_m, lead: string, ch: string) => { + return `${lead}${ch.toUpperCase()}`; + }); +} + +/** + * The readable label for a feature. A named attribute wins; otherwise the + * filter value itself, wrapped in the layer's prefix and suffix. When the layer + * also has a name the label is "prefix value — name". + */ +export function boundaryFeatureLabel( + properties: Record | null | undefined, + filterField: string, + config: BoundaryLabelConfig = {}, +): string { + const props = properties ?? {}; + const raw = props[filterField]; + const value = raw == null ? '' : String(raw).trim(); + const prefix = config.label_prefix ?? ''; + const suffix = config.label_suffix ?? ''; + + const nameFields = config.label_field ? [config.label_field] : NAME_ATTRIBUTES; + let name = ''; + for (const field of nameFields) { + const candidate = props[field]; + if (candidate != null && String(candidate).trim() !== '') { + name = String(candidate).trim(); + break; + } + } + + if (name && name !== value) return `${prefix}${value} — ${name}`; + return `${prefix}${value}${suffix}`; +} + +/** + * The family a registered region belongs to, from its name: "TRINITY_53" and + * "Trinity 7" are both parts of the "trinity" family. A name with no trailing + * number, or only a number, is not part of a family. + */ +export function regionFamilyOf(name: string): { key: string; label: string } | null { + const match = /^(.*[^\s_-])[\s_-]+\d+$/.exec(name.trim()); + if (!match?.[1]) return null; + const pretty = /^(.*[^\s-])\s+\d+$/.exec(prettyRegionName(name)); + return { + key: match[1].toLowerCase().replace(/[\s_]+/g, ' '), + label: pretty?.[1] ?? prettyRegionName(match[1]), + }; +} + +interface RegionFeatureProps { + region_name?: unknown; + category_name?: unknown; + category_id?: unknown; +} + +/** + * Options for a registered-region layer. The name is the label and the + * category is the group. Numbered parts of one family (two or more in a + * category) collapse to one family option. + */ +export function buildRegionOptions( + features: GeoJSON.Feature[], + filterField: string, +): BoundaryOption[] { + const singles = new Map(); + for (const feature of features) { + const props = (feature.properties ?? {}) as Record & RegionFeatureProps; + const raw = props[filterField]; + if (raw == null || String(raw).trim() === '') continue; + const value = String(raw); + if (singles.has(value)) continue; + const rawName = props.region_name == null ? '' : String(props.region_name); + const family = regionFamilyOf(rawName); + const group = + props.category_name != null + ? String(props.category_name) + : props.category_id != null + ? String(props.category_id) + : undefined; + singles.set(value, { + value, + values: [value], + label: rawName ? prettyRegionName(rawName) : value, + group, + familyKey: family ? `${group ?? ''}|${family.key}` : undefined, + familyLabel: family?.label, + }); + } + + const byFamily = new Map>(); + for (const option of singles.values()) { + if (!option.familyKey) continue; + const members = byFamily.get(option.familyKey) ?? []; + members.push(option); + byFamily.set(option.familyKey, members); + } + + const result: BoundaryOption[] = []; + for (const option of singles.values()) { + const members = option.familyKey ? byFamily.get(option.familyKey) : undefined; + if (!members || members.length < 2) { + result.push(stripFamily(option)); + continue; + } + // Emit the family once, at its first member. + if (members[0] !== option) continue; + const parts = members.map(stripFamily).sort((a, b) => compareLabels(a.label, b.label)); + const values = parts.flatMap((part) => part.values); + result.push({ + value: values.join(','), + values, + label: `${option.familyLabel ?? option.label} (${parts.length} parts)`, + group: option.group, + parts, + }); + } + return sortBoundaryOptions(result); +} + +function stripFamily(option: BoundaryOption & { familyKey?: string; familyLabel?: string }) { + const { familyKey: _key, familyLabel: _label, ...rest } = option; + void _key; + void _label; + return rest; +} + +/** Options for a feature-service layer, labelled from the layer config. */ +export function buildLayerOptions( + features: GeoJSON.Feature[], + filterField: string, + config: BoundaryLabelConfig = {}, +): BoundaryOption[] { + const seen = new Set(); + const options: BoundaryOption[] = []; + for (const feature of features) { + const raw = feature.properties?.[filterField]; + if (raw == null || String(raw).trim() === '') continue; + const value = String(raw); + if (seen.has(value)) continue; + seen.add(value); + options.push({ + value, + values: [value], + label: boundaryFeatureLabel(feature.properties, filterField, config), + }); + } + return sortBoundaryOptions(options); +} + +/** Sort by group, then by name. Parts of a family sort the same way. */ +export function sortBoundaryOptions(options: BoundaryOption[]): BoundaryOption[] { + return [...options].sort( + (a, b) => compareLabels(a.group ?? '', b.group ?? '') || compareLabels(a.label, b.label), + ); +} + +/** The distinct groups, sorted. */ +export function boundaryGroups(options: BoundaryOption[]): string[] { + return [...new Set(options.flatMap((o) => (o.group ? [o.group] : [])))].sort(compareLabels); +} + +/** Every option including family parts, flat. */ +export function flattenBoundaryOptions(options: BoundaryOption[]): BoundaryOption[] { + return options.flatMap((option) => [option, ...(option.parts ?? [])]); +} + +/** + * Filter by what the user typed. A family stays when its own label or any part + * matches; when a part matched, only the matching parts are kept so the user + * sees where the match was. + */ +export function filterBoundaryOptions(options: BoundaryOption[], query: string): BoundaryOption[] { + const needle = query.trim().toLowerCase(); + if (!needle) return options; + const matches = (label: string) => label.toLowerCase().includes(needle); + return options.flatMap((option) => { + if (!option.parts) return matches(option.label) ? [option] : []; + if (matches(option.label)) return [option]; + const parts = option.parts.filter((part) => matches(part.label)); + return parts.length > 0 ? [{ ...option, parts }] : []; + }); +} + +/** The option for a saved filter value: a single boundary, a part, or a whole family. */ +export function findBoundaryOption( + options: BoundaryOption[], + value: string, +): BoundaryOption | undefined { + return flattenBoundaryOptions(options).find((option) => option.value === value); +} diff --git a/ui-react/src/pages/modeling/thread/BoundaryCombobox.tsx b/ui-react/src/pages/modeling/thread/BoundaryCombobox.tsx new file mode 100644 index 00000000..0e0aef9b --- /dev/null +++ b/ui-react/src/pages/modeling/thread/BoundaryCombobox.tsx @@ -0,0 +1,173 @@ +import { useMemo, useState } from 'react'; +import { Check, ChevronDown, ChevronRight, ChevronsUpDown } from 'lucide-react'; + +import { cn } from '@/lib/utils'; +import { + boundaryGroups, + filterBoundaryOptions, + type BoundaryOption, +} from '@/lib/spatial-boundaries'; +import { Button } from '@/components/ui/button'; +import { + Command, + CommandEmpty, + CommandGroup, + CommandInput, + CommandItem, + CommandList, +} from '@/components/ui/command'; +import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'; + +interface BoundaryComboboxProps { + options: BoundaryOption[]; + /** The selected option's value, or '' for all boundaries. */ + value: string; + /** Shown on the trigger when nothing in `options` is selected, e.g. a saved region's name. */ + fallbackLabel?: string; + disabled?: boolean; + onSelect: (option: BoundaryOption | null) => void; +} + +/** + * Type-to-filter picker for a layer's boundaries. Options show names only, + * grouped under their category when there is one. A family of numbered parts is + * one row that selects the whole region; its chevron expands the parts. + */ +export function BoundaryCombobox({ + options, + value, + fallbackLabel, + disabled, + onSelect, +}: BoundaryComboboxProps) { + const [open, setOpen] = useState(false); + const [query, setQuery] = useState(''); + const [expanded, setExpanded] = useState>(() => new Set()); + + const visible = useMemo(() => filterBoundaryOptions(options, query), [options, query]); + const groups = useMemo(() => boundaryGroups(visible), [visible]); + const selected = useMemo( + () => options.flatMap((o) => [o, ...(o.parts ?? [])]).find((option) => option.value === value), + [options, value], + ); + const triggerLabel = selected?.label ?? fallbackLabel ?? 'All boundaries'; + + const choose = (option: BoundaryOption | null) => { + onSelect(option); + setOpen(false); + }; + + const renderOption = (option: BoundaryOption) => { + // While filtering, a family shows the parts that matched. + const isExpanded = Boolean(option.parts) && (query.trim() !== '' || expanded.has(option.value)); + return ( +
+
+ {option.parts ? ( + + ) : ( + + )} + choose(option)} + > + + {option.label} + +
+ {isExpanded && + option.parts?.map((part) => ( +
+ choose(part)}> + + {part.label} + +
+ ))} +
+ ); + }; + + const ungrouped = visible.filter((option) => !option.group); + + return ( + { + setOpen(next); + if (!next) setQuery(''); + }} + > + + + + + + + + No matching boundaries. + {query.trim() === '' && ( + + choose(null)}> + + All boundaries + + + )} + {ungrouped.length > 0 && {ungrouped.map(renderOption)}} + {groups.map((group) => ( + + {visible.filter((option) => option.group === group).map(renderOption)} + + ))} + + + + + ); +} diff --git a/ui-react/src/pages/modeling/thread/SpatialScopeMap.tsx b/ui-react/src/pages/modeling/thread/SpatialScopeMap.tsx index c35cc070..70cf3b5d 100644 --- a/ui-react/src/pages/modeling/thread/SpatialScopeMap.tsx +++ b/ui-react/src/pages/modeling/thread/SpatialScopeMap.tsx @@ -8,8 +8,17 @@ import 'leaflet/dist/leaflet.css'; import { parseGeometry } from '@/pages/regions/regionUtils'; import { LIST_REGISTERED_BOUNDARY_REGIONS } from '@/graphql/queries/regions'; import { fetchSpatialLayers, spatialLayersAvailable } from '@/lib/spatial-layers'; +import { + boundaryGroups, + buildLayerOptions, + buildRegionOptions, + findBoundaryOption, + type BoundaryLabelConfig, + type BoundaryOption, +} from '@/lib/spatial-boundaries'; +import { BoundaryCombobox } from './BoundaryCombobox'; -interface SpatialLayerCatalogEntry { +interface SpatialLayerCatalogEntry extends BoundaryLabelConfig { id: string; label: string; uri: string; @@ -85,6 +94,9 @@ type RegisteredBoundaryRegionsData = { // pulling the much larger administrative level datasets into every map. const REGISTERED_BOUNDARY_CATEGORY_IDS = ['hydrology']; +/** Sentinel for the category select's "All categories" entry. */ +const ALL_CATEGORIES = '__all__'; + /** Cartographic preview of the spatial scope carried by the problem statement. */ export function SpatialScopeMap({ geometries = [], @@ -103,6 +115,7 @@ export function SpatialScopeMap({ const [selectedLayerId, setSelectedLayerId] = useState(''); const [layerFeatures, setLayerFeatures] = useState([]); const [selectedFeatureValue, setSelectedFeatureValue] = useState(''); + const [categoryChoice, setCategoryChoice] = useState(''); const [layerLoading, setLayerLoading] = useState(false); const [layerError, setLayerError] = useState(null); @@ -187,42 +200,49 @@ export function SpatialScopeMap({ const activeFilterField = filterField?.trim() || selectedLayer?.default_filter_field; - const featureOptions = useMemo(() => { + const isRegionLayer = selectedLayer?.source_type === 'mint-regions'; + const allOptions = useMemo(() => { if (!activeFilterField) return []; - const options = layerFeatures.flatMap((feature) => { - const rawValue = feature.properties?.[activeFilterField]; - if (rawValue == null || String(rawValue).trim() === '') return []; - const value = String(rawValue); - const name = - feature.properties?.GMAName ?? - feature.properties?.GMA_Name ?? - feature.properties?.GMA_NAME ?? - feature.properties?.Name ?? - feature.properties?.name ?? - feature.properties?.region_name ?? - feature.properties?.label ?? - ''; - return [ - { - value, - label: name ? `${value} — ${String(name)}` : value, - }, - ]; - }); - return options - .filter( - (option, index) => - options.findIndex((candidate) => candidate.value === option.value) === index, - ) - .sort((left, right) => left.label.localeCompare(right.label, undefined, { numeric: true })); - }, [activeFilterField, layerFeatures]); + return isRegionLayer + ? buildRegionOptions(layerFeatures, activeFilterField) + : buildLayerOptions(layerFeatures, activeFilterField, selectedLayer); + }, [activeFilterField, isRegionLayer, layerFeatures, selectedLayer]); + + // Registered regions span several categories. Show one at a time, starting + // with the saved selection's category, so the map is not a pile of overlaps. + const categories = useMemo(() => boundaryGroups(allOptions), [allOptions]); + const savedOption = findBoundaryOption( + allOptions, + selectedFeatureValue || filterValue?.trim() || '', + ); + const activeCategory = + categories.length > 1 && categoryChoice !== ALL_CATEGORIES + ? categories.includes(categoryChoice) + ? categoryChoice + : (savedOption?.group ?? categories[0] ?? '') + : ''; + const featureOptions = useMemo( + () => (activeCategory ? allOptions.filter((o) => o.group === activeCategory) : allOptions), + [activeCategory, allOptions], + ); + const visibleFeatures = useMemo( + () => + activeCategory + ? layerFeatures.filter((f) => f.properties?.category_name === activeCategory) + : layerFeatures, + [activeCategory, layerFeatures], + ); + const selectedOption = findBoundaryOption(allOptions, selectedFeatureValue); + const selectedValues = useMemo(() => new Set(selectedOption?.values ?? []), [selectedOption]); + const isSelectedFeature = (feature: GeoJSON.Feature) => + selectedValues.has(String(feature.properties?.[activeFilterField ?? ''])); useEffect(() => { const nextValue = filterValue?.trim() ?? ''; setSelectedFeatureValue( - nextValue && featureOptions.some((option) => option.value === nextValue) ? nextValue : '', + nextValue && findBoundaryOption(allOptions, nextValue) ? nextValue : '', ); - }, [featureOptions, filterValue]); + }, [allOptions, filterValue]); useEffect(() => { if (!selectedLayer) { @@ -249,6 +269,8 @@ export function SpatialScopeMap({ // (for example GMAnum=12) for ETL arguments. region_id: region.id.split('__').pop() ?? region.id, region_name: region.name, + category_id: region.category_id, + category_name: region.region_category?.name ?? region.category_id, }, geometry: parsed, } as GeoJSON.Feature, @@ -318,20 +340,20 @@ export function SpatialScopeMap({ () => ({ type: 'FeatureCollection', features: [ - ...layerFeatures.map((feature) => ({ + ...visibleFeatures.map((feature) => ({ ...feature, properties: { ...(feature.properties ?? {}), catalogLayer: true, selectedBoundary: - Boolean(selectedFeatureValue) && - String(feature.properties?.[activeFilterField ?? '']) === selectedFeatureValue, + selectedValues.size > 0 && + selectedValues.has(String(feature.properties?.[activeFilterField ?? ''])), }, })), ...selectedScopeFeatures, ], }), - [activeFilterField, layerFeatures, selectedFeatureValue, selectedScopeFeatures], + [activeFilterField, selectedValues, selectedScopeFeatures, visibleFeatures], ); const sourceIsCustom = Boolean( @@ -341,11 +363,8 @@ export function SpatialScopeMap({ ), ); const activeLayerLabel = sourceIsCustom ? 'Custom geometry source' : selectedLayer?.label; - const focusedFeatures = selectedFeatureValue - ? layerFeatures.filter( - (feature) => String(feature.properties?.[activeFilterField ?? '']) === selectedFeatureValue, - ) - : []; + const focusedFeatures = selectedFeatureValue ? visibleFeatures.filter(isSelectedFeature) : []; + const hasSelection = selectedValues.size > 0; const style = (feature?: GeoJSON.Feature): PathOptions => feature?.properties?.selectedBoundary @@ -363,12 +382,15 @@ export function SpatialScopeMap({ fillOpacity: 0, interactive: false, } - : { - color: '#1d4ed8', - weight: 1.5, - fillColor: '#3b82f6', - fillOpacity: 0.12, - }; + : hasSelection + ? // Everything but the selection is faint, so the choice stands out. + { color: '#94a3b8', weight: 1, fillColor: '#94a3b8', fillOpacity: 0.04 } + : { + color: '#1d4ed8', + weight: 1.5, + fillColor: '#3b82f6', + fillOpacity: 0.08, + }; return (
@@ -386,6 +408,7 @@ export function SpatialScopeMap({ const nextId = event.target.value; setSelectedLayerId(nextId); setSelectedFeatureValue(''); + setCategoryChoice(''); const nextLayer = layers.find((layer) => layer.id === nextId); if (nextLayer) onLayerSelect?.(nextLayer); }} @@ -397,41 +420,50 @@ export function SpatialScopeMap({ ))} - {featureOptions.length > 0 && ( + {categories.length > 1 && ( )} + {allOptions.length > 0 && ( +
+ Boundary + { + setSelectedFeatureValue(option?.value ?? ''); + if (!option || !activeFilterField) return; + onFeatureSelect?.({ + filterField: activeFilterField, + filterValue: option.value, + label: option.label, + layer: selectedLayer, + geometry: boundaryGeometry(layerFeatures, activeFilterField, option), + }); + }} + /> +
+ )}
)}
@@ -457,7 +489,7 @@ export function SpatialScopeMap({ const option = featureValue == null ? undefined - : featureOptions.find((item) => item.value === String(featureValue)); + : findBoundaryOption(allOptions, String(featureValue)); const scopeName = option?.label ?? (featureValue == null ? activeLayerLabel : String(featureValue)); if (scopeName && (!isStoredScope || layerFeatures.length === 0)) { @@ -470,7 +502,7 @@ export function SpatialScopeMap({ ) { layer.on('click', () => { const value = String(feature.properties?.[activeFilterField]); - const option = featureOptions.find((item) => item.value === value); + const option = findBoundaryOption(allOptions, value); setSelectedFeatureValue(value); onFeatureSelect?.({ filterField: activeFilterField, @@ -497,7 +529,7 @@ export function SpatialScopeMap({
{activeLayerLabel ?? 'Stored region geometry'} - {scopeId ? ` · ${label ?? scopeId}` : ''} + {scopeId && label ? ` · ${label}` : ''} {layerLoading ? 'Loading layer…' : (layerError ?? 'OpenStreetMap base map')}
@@ -505,6 +537,20 @@ export function SpatialScopeMap({ ); } +/** The geometry a boundary option stands for: one feature's, or the union of a family's parts. */ +function boundaryGeometry( + features: GeoJSON.Feature[], + filterField: string, + option: BoundaryOption, +): GeoJSON.Geometry | undefined { + const values = new Set(option.values); + const geometries = features + .filter((feature) => values.has(String(feature.properties?.[filterField]))) + .flatMap((feature) => (feature.geometry ? [feature.geometry] : [])); + if (geometries.length <= 1) return geometries[0]; + return { type: 'GeometryCollection', geometries }; +} + function spatialLayerQueryUrl(uri: string): string | null { try { const url = new URL(uri); diff --git a/ui-react/src/pages/modeling/thread/__tests__/MintParameters.test.tsx b/ui-react/src/pages/modeling/thread/__tests__/MintParameters.test.tsx index 78d1a612..e6b87469 100644 --- a/ui-react/src/pages/modeling/thread/__tests__/MintParameters.test.tsx +++ b/ui-react/src/pages/modeling/thread/__tests__/MintParameters.test.tsx @@ -205,14 +205,10 @@ describe('MintParameters', () => { expect( screen.getByRole('option', { name: 'TWDB Statewide GMA Boundaries' }), ).toBeInTheDocument(); - await waitFor(() => { - expect(screen.getByRole('option', { name: '8 — Gulf Coast' })).toBeInTheDocument(); - expect( - Array.from( - screen.getByLabelText('Spatial boundary feature').querySelectorAll('option'), - ).map((option) => option.textContent), - ).toEqual(['All boundaries', '2 — Central High Plains', '8 — Gulf Coast']); - }); + const picker = await screen.findByRole('combobox', { name: 'Spatial boundary feature' }); + fireEvent.click(picker); + expect(await screen.findByText('2 — Central High Plains')).toBeInTheDocument(); + expect(screen.getByText('8 — Gulf Coast')).toBeInTheDocument(); // The layers come from the Ensemble Manager; the browser does not call the adapter. expect(fetchMock).toHaveBeenCalledWith( 'http://em/v1/spatial/layers', @@ -326,7 +322,9 @@ describe('MintParameters', () => { fireEvent.change(screen.getByLabelText('Spatial boundary layer'), { target: { value: 'mint_registered_ground_water_availability_models' }, }); - expect(await screen.findByRole('option', { name: 'gams_12 — GMA 12' })).toBeInTheDocument(); + fireEvent.click(await screen.findByRole('combobox', { name: 'Spatial boundary feature' })); + expect(await screen.findByText('GMA 12')).toBeInTheDocument(); + expect(screen.queryByText(/gams_12/)).not.toBeInTheDocument(); vi.unstubAllGlobals(); Reflect.deleteProperty(window, '__MINT_CONFIG__'); diff --git a/ui-react/src/pages/modeling/thread/__tests__/SpatialScopeMap.test.tsx b/ui-react/src/pages/modeling/thread/__tests__/SpatialScopeMap.test.tsx new file mode 100644 index 00000000..4b33a008 --- /dev/null +++ b/ui-react/src/pages/modeling/thread/__tests__/SpatialScopeMap.test.tsx @@ -0,0 +1,156 @@ +import { fireEvent, screen, within } from '@testing-library/react'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import { LIST_REGISTERED_BOUNDARY_REGIONS } from '@/graphql/queries/regions'; +import { renderWithProviders } from '@/test/utils/render'; +import { SpatialScopeMap } from '../SpatialScopeMap'; + +// jsdom has no SVG renderer for Leaflet vectors; the picker is what is under test. +vi.mock('react-leaflet', () => ({ + MapContainer: ({ children }: { children?: React.ReactNode }) =>
{children}
, + TileLayer: () => null, + GeoJSON: () => null, + useMap: () => ({ fitBounds: () => undefined }), +})); + +const square = (x: number) => ({ + type: 'Polygon', + coordinates: [ + [ + [x, 29], + [x + 1, 29], + [x + 1, 30], + [x, 30], + [x, 29], + ], + ], +}); + +const region = (id: string, name: string, categoryId: string, categoryName: string, x: number) => ({ + id: `mint__${id}`, + name, + category_id: categoryId, + region_category: { id: categoryId, name: categoryName }, + geometries: [{ geometry: square(x) }], +}); + +const REGIONS = [ + region('0B4wIEBZthkf9gclJk1F', 'SEYMOUR_3', 'hydrology', 'Hydrology', -100), + region('1ap0Inly6Lq3jYZgDDKy', 'TRINITY_53', 'hydrology', 'Hydrology', -99), + region('2ap0Inly6Lq3jYZgDDKy', 'TRINITY_2', 'hydrology', 'Hydrology', -98), + region('3wKEpR6sL8AtkDM8hXAo', 'Alwero', 'hydrology', 'Hydrology', -97), +]; + +function mount(props: Parameters[0] = {}) { + return renderWithProviders(, { + apolloMocks: [ + { + request: { + query: LIST_REGISTERED_BOUNDARY_REGIONS, + variables: { categoryIds: ['hydrology'] }, + }, + result: { data: { region: REGIONS } }, + }, + ], + }); +} + +async function openPicker() { + fireEvent.click(await screen.findByRole('combobox', { name: 'Spatial boundary feature' })); +} + +describe('SpatialScopeMap boundary picker', () => { + beforeEach(() => { + window.__MINT_CONFIG__ = { + HASURA_ENDPOINT: 'http://hasura/graphql', + AUTH_SERVER: '', + AUTH_CLIENT_ID: '', + AUTH_REALM: '', + AUTH_PROVIDER: 'keycloak', + ENSEMBLE_MANAGER_API: 'http://em/v1', + }; + vi.stubGlobal( + 'fetch', + vi.fn().mockResolvedValue({ ok: true, json: async () => ({ layers: [] }) }), + ); + }); + + afterEach(() => { + vi.unstubAllGlobals(); + Reflect.deleteProperty(window, '__MINT_CONFIG__'); + }); + + it('shows region names sorted, with no ids, and one entry for a numbered family', async () => { + mount(); + await openPicker(); + const labels = within(await screen.findByRole('listbox')) + .getAllByRole('option') + .map((option) => option.textContent); + expect(labels).toEqual(['All boundaries', 'Alwero', 'Seymour 3', 'Trinity (2 parts)']); + expect(document.body.textContent).not.toMatch(/0B4wIEBZthkf9gclJk1F|1ap0Inly6Lq3jYZgDDKy/); + }); + + it('groups the options under their category', async () => { + mount(); + await openPicker(); + expect(await screen.findByText('Hydrology')).toBeInTheDocument(); + }); + + it('selects the whole family, and lets the user expand to one part', async () => { + const onFeatureSelect = vi.fn(); + mount({ onFeatureSelect }); + await openPicker(); + fireEvent.click(await screen.findByText('Trinity (2 parts)')); + expect(onFeatureSelect).toHaveBeenCalledTimes(1); + const whole = onFeatureSelect.mock.calls[0]?.[0]; + expect(whole.label).toBe('Trinity (2 parts)'); + expect(whole.filterField).toBe('region_id'); + expect(whole.filterValue.split(',').sort()).toEqual([ + '1ap0Inly6Lq3jYZgDDKy', + '2ap0Inly6Lq3jYZgDDKy', + ]); + expect(whole.geometry.type).toBe('GeometryCollection'); + expect(whole.geometry.geometries).toHaveLength(2); + + await openPicker(); + fireEvent.click(screen.getByRole('button', { name: 'Expand Trinity (2 parts)' })); + fireEvent.click(await screen.findByText('Trinity 53')); + expect(onFeatureSelect).toHaveBeenCalledTimes(2); + expect(onFeatureSelect.mock.calls[1]?.[0].filterValue).toBe('1ap0Inly6Lq3jYZgDDKy'); + expect(onFeatureSelect.mock.calls[1]?.[0].geometry.type).toBe('Polygon'); + }); + + it('filters as the user types', async () => { + mount(); + await openPicker(); + fireEvent.change(await screen.findByPlaceholderText('Search boundaries...'), { + target: { value: 'sey' }, + }); + const labels = within(screen.getByRole('listbox')) + .getAllByRole('option') + .map((option) => option.textContent); + expect(labels).toEqual(['Seymour 3']); + }); + + it('still shows a saved region by its readable name', async () => { + mount({ + scopeId: 'a-region-hash-id', + label: 'Texas Panhandle', + geometries: [square(-101)], + }); + const picker = await screen.findByRole('combobox', { name: 'Spatial boundary feature' }); + expect(picker).toHaveTextContent('Texas Panhandle'); + expect(document.body.textContent).not.toContain('a-region-hash-id'); + }); + + it('shows a saved boundary selection by name', async () => { + mount({ + filterField: 'region_id', + filterValue: '3wKEpR6sL8AtkDM8hXAo', + label: 'Alwero', + scopeId: '3wKEpR6sL8AtkDM8hXAo', + }); + const picker = await screen.findByRole('combobox', { name: 'Spatial boundary feature' }); + await vi.waitFor(() => expect(picker).toHaveTextContent('Alwero')); + }); +}); diff --git a/ui-react/src/pages/modeling/thread/wizard/FramingStep.tsx b/ui-react/src/pages/modeling/thread/wizard/FramingStep.tsx index 7a906519..2bc0791b 100644 --- a/ui-react/src/pages/modeling/thread/wizard/FramingStep.tsx +++ b/ui-react/src/pages/modeling/thread/wizard/FramingStep.tsx @@ -155,7 +155,7 @@ export function FramingStep({ geometries={(thread.region?.geometries ?? []) .map((geometry) => geometry.geometry) .filter(Boolean)} - label={spatialSelection?.feature?.label ?? thread.region?.name ?? regionId} + label={spatialSelection?.feature?.label ?? thread.region?.name} scopeId={spatialSelection?.feature?.filterValue ?? regionId} sourceUri={spatialSelection?.layer?.source_uri ?? spatialSelection?.layer?.uri} filterField={spatialSelection?.feature?.filterField}