@kivacore/ui-pro-shared 0.0.9 → 0.0.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +187 -21
- package/src/.kiva/config.json +27 -0
- package/src/components/avatar-group.tsx +222 -0
- package/src/components/kiva/bulk-update-dialog/bulk-update-dialog.tsx +240 -0
- package/src/components/kiva/bulk-update-dialog/index.tsx +6 -0
- package/src/components/kiva/bulk-update-dialog/types.ts +33 -0
- package/src/components/kiva/calendar/animations.ts +40 -0
- package/src/components/kiva/calendar/calendar-body.tsx +106 -0
- package/src/components/kiva/calendar/calendar-sidebar.tsx +103 -0
- package/src/components/kiva/calendar/calendar.tsx +243 -0
- package/src/components/kiva/calendar/constants.ts +12 -0
- package/src/components/kiva/calendar/contexts/calendar-context.tsx +696 -0
- package/src/components/kiva/calendar/contexts/dnd-context.tsx +173 -0
- package/src/components/kiva/calendar/dialogs/add-edit-event-dialog.tsx +287 -0
- package/src/components/kiva/calendar/dialogs/delete-event-dialog.tsx +73 -0
- package/src/components/kiva/calendar/dialogs/event-details-dialog.tsx +163 -0
- package/src/components/kiva/calendar/dialogs/events-list-dialog.tsx +122 -0
- package/src/components/kiva/calendar/dnd/draggable-event.tsx +66 -0
- package/src/components/kiva/calendar/dnd/droppable-area.tsx +53 -0
- package/src/components/kiva/calendar/dnd/resizable-event.tsx +190 -0
- package/src/components/kiva/calendar/header/calendar-header.tsx +84 -0
- package/src/components/kiva/calendar/header/date-navigator.tsx +188 -0
- package/src/components/kiva/calendar/header/filter.tsx +80 -0
- package/src/components/kiva/calendar/header/today-button.tsx +49 -0
- package/src/components/kiva/calendar/header/user-select.tsx +111 -0
- package/src/components/kiva/calendar/header/view-tabs.tsx +144 -0
- package/src/components/kiva/calendar/helpers.ts +617 -0
- package/src/components/kiva/calendar/hooks/use-disclosure.ts +19 -0
- package/src/components/kiva/calendar/hooks/use-local-storage.ts +40 -0
- package/src/components/kiva/calendar/hooks/use-media-query.ts +25 -0
- package/src/components/kiva/calendar/hooks.ts +5 -0
- package/src/components/kiva/calendar/index.tsx +27 -0
- package/src/components/kiva/calendar/interfaces.ts +35 -0
- package/src/components/kiva/calendar/schemas.ts +20 -0
- package/src/components/kiva/calendar/settings/settings.tsx +116 -0
- package/src/components/kiva/calendar/skeletons/calendar-header-skeleton.tsx +27 -0
- package/src/components/kiva/calendar/skeletons/calendar-skeleton.tsx +19 -0
- package/src/components/kiva/calendar/skeletons/day-view-skeleton.tsx +40 -0
- package/src/components/kiva/calendar/skeletons/month-view-skeleton.tsx +36 -0
- package/src/components/kiva/calendar/skeletons/week-view-skeleton.tsx +48 -0
- package/src/components/kiva/calendar/skeletons/year-view-skeleton.tsx +42 -0
- package/src/components/kiva/calendar/types.ts +25 -0
- package/src/components/kiva/calendar/views/agenda-view/agenda-events.tsx +150 -0
- package/src/components/kiva/calendar/views/month-view/calendar-month-view.tsx +82 -0
- package/src/components/kiva/calendar/views/month-view/day-cell.tsx +218 -0
- package/src/components/kiva/calendar/views/month-view/event-bullet.tsx +46 -0
- package/src/components/kiva/calendar/views/month-view/month-event-badge.tsx +154 -0
- package/src/components/kiva/calendar/views/timeline/calendar-timeline-view.tsx +100 -0
- package/src/components/kiva/calendar/views/timeline/lib/timeline-layout.ts +130 -0
- package/src/components/kiva/calendar/views/timeline/lib/timeline-model.ts +504 -0
- package/src/components/kiva/calendar/views/timeline/timeline-event-bar.tsx +68 -0
- package/src/components/kiva/calendar/views/timeline/timeline-grid-header.tsx +125 -0
- package/src/components/kiva/calendar/views/timeline/timeline-row.tsx +159 -0
- package/src/components/kiva/calendar/views/timeline/timeline-section.tsx +61 -0
- package/src/components/kiva/calendar/views/timeline/use-timeline-sections.ts +278 -0
- package/src/components/kiva/calendar/views/week-and-day-view/calendar-day-view.tsx +277 -0
- package/src/components/kiva/calendar/views/week-and-day-view/calendar-time-line.tsx +47 -0
- package/src/components/kiva/calendar/views/week-and-day-view/calendar-week-view.tsx +229 -0
- package/src/components/kiva/calendar/views/week-and-day-view/day-view-multi-day-events-row.tsx +79 -0
- package/src/components/kiva/calendar/views/week-and-day-view/event-block.tsx +116 -0
- package/src/components/kiva/calendar/views/week-and-day-view/render-grouped-events.tsx +54 -0
- package/src/components/kiva/calendar/views/week-and-day-view/week-view-multi-day-events-row.tsx +159 -0
- package/src/components/kiva/calendar/views/year-view/calendar-year-view.tsx +159 -0
- package/src/components/kiva/data-table-side-filters/components/side-filter-active-chips.tsx +137 -0
- package/src/components/kiva/data-table-side-filters/components/side-filter-clear.tsx +34 -0
- package/src/components/kiva/data-table-side-filters/components/side-filter-search.tsx +67 -0
- package/src/components/kiva/data-table-side-filters/components/side-filter-section.tsx +77 -0
- package/src/components/kiva/data-table-side-filters/controllers/side-filter-async-options.tsx +354 -0
- package/src/components/kiva/data-table-side-filters/controllers/side-filter-boolean.tsx +66 -0
- package/src/components/kiva/data-table-side-filters/controllers/side-filter-checkbox-list.tsx +137 -0
- package/src/components/kiva/data-table-side-filters/controllers/side-filter-date-range.tsx +204 -0
- package/src/components/kiva/data-table-side-filters/controllers/side-filter-numeric-range.tsx +162 -0
- package/src/components/kiva/data-table-side-filters/controllers/side-filter-options-dropdown.tsx +191 -0
- package/src/components/kiva/data-table-side-filters/controllers/side-filter-text.tsx +53 -0
- package/src/components/kiva/data-table-side-filters/core/query-translator.ts +367 -0
- package/src/components/kiva/data-table-side-filters/core/types.ts +81 -0
- package/src/components/kiva/data-table-side-filters/data-table-side-filters.tsx +483 -0
- package/src/components/kiva/data-table-side-filters/hooks/use-data-table-side-filters.tsx +160 -0
- package/src/components/kiva/data-table-side-filters/hooks/use-show-more.tsx +62 -0
- package/src/components/kiva/data-table-side-filters/index.tsx +44 -0
- package/src/components/kiva/data-table-side-filters/lib/render-mode.ts +62 -0
- package/src/components/kiva/date-time-picker.tsx +163 -0
- package/src/components/kiva/editable-record-detail.tsx +809 -0
- package/src/components/kiva/enum-option-editor/enum-option-editor.tsx +891 -0
- package/src/components/kiva/enum-option-editor/index.tsx +26 -0
- package/src/components/kiva/enum-option-editor/kiva-enum-option-editor.tsx +320 -0
- package/src/components/kiva/enum-option-editor/types.ts +90 -0
- package/src/components/kiva/kanban.tsx +1376 -0
- package/src/components/kiva/kiva-data-export-menu.tsx +543 -0
- package/src/components/kiva/map.tsx +1631 -0
- package/src/components/kiva/pivot-calendar/components/group-sidebar.tsx +95 -0
- package/src/components/kiva/pivot-calendar/components/pivot-calendar-toolbar.tsx +113 -0
- package/src/components/kiva/pivot-calendar/components/stats-cell.tsx +126 -0
- package/src/components/kiva/pivot-calendar/helpers.ts +374 -0
- package/src/components/kiva/pivot-calendar/hooks/use-pivot-calendar.ts +222 -0
- package/src/components/kiva/pivot-calendar/index.tsx +32 -0
- package/src/components/kiva/pivot-calendar/pivot-calendar.tsx +107 -0
- package/src/components/kiva/pivot-calendar/types.ts +154 -0
- package/src/components/kiva/pivot-calendar/views/days-of-month-view.tsx +37 -0
- package/src/components/kiva/pivot-calendar/views/days-of-week-view.tsx +37 -0
- package/src/components/kiva/pivot-calendar/views/month-calendar-view.tsx +154 -0
- package/src/components/kiva/pivot-calendar/views/months-of-year-view.tsx +40 -0
- package/src/components/kiva/pivot-calendar/views/pivot-grid-view.tsx +251 -0
- package/src/components/kiva/pivot-filter/index.tsx +9 -0
- package/src/components/kiva/pivot-filter/pivot-filter-item.tsx +159 -0
- package/src/components/kiva/pivot-filter/pivot-filter-settings.tsx +161 -0
- package/src/components/kiva/pivot-filter/pivot-filter.tsx +187 -0
- package/src/components/kiva/pivot-filter/types.ts +82 -0
- package/src/components/kiva/pivot-grid/hooks/use-pivot-grid.ts +683 -0
- package/src/components/kiva/pivot-grid/index.tsx +23 -0
- package/src/components/kiva/pivot-grid/lib/pivot-grid-color-rules.ts +98 -0
- package/src/components/kiva/pivot-grid/lib/pivot-grid-export.ts +265 -0
- package/src/components/kiva/pivot-grid/lib/pivot-grid-model.ts +1110 -0
- package/src/components/kiva/pivot-grid/pivot-grid-demo-data.ts +200 -0
- package/src/components/kiva/pivot-grid/pivot-grid-export-menu.tsx +66 -0
- package/src/components/kiva/pivot-grid/pivot-grid-toolbar.tsx +85 -0
- package/src/components/kiva/pivot-grid/pivot-grid.tsx +601 -0
- package/src/components/kiva/pivot-grid/types.ts +195 -0
- package/src/components/kiva/place-autocomplete.tsx +484 -0
- package/src/components/kiva/record-delete-confirm-dialog/index.tsx +10 -0
- package/src/components/kiva/record-delete-confirm-dialog/record-delete-confirm-dialog.tsx +266 -0
- package/src/components/kiva/record-delete-confirm-dialog/types.ts +25 -0
- package/src/hooks/kiva/_internal/autonumber-setting.ts +112 -0
- package/src/hooks/kiva/_internal/form-layout-to-view.ts +665 -0
- package/src/hooks/kiva/_internal/kiva-hook-utils.ts +143 -0
- package/src/hooks/kiva/_internal/use-computed-field-evaluator.tsx +310 -0
- package/src/hooks/kiva/_internal/use-field-actions-evaluator.tsx +398 -0
- package/src/hooks/kiva/_internal/use-form-actions-evaluator.tsx +363 -0
- package/src/hooks/kiva/_internal/use-form-view-engine.tsx +2200 -0
- package/src/hooks/kiva/_internal/use-kiva-form-view-fields.tsx +190 -0
- package/src/hooks/kiva/_internal/use-kiva-kanban-cards.tsx +311 -0
- package/src/hooks/kiva/use-data-export.tsx +265 -0
- package/src/hooks/kiva/use-kiva-calendar.tsx +992 -0
- package/src/hooks/kiva/use-kiva-data-export.tsx +173 -0
- package/src/hooks/kiva/use-kiva-data-grid.tsx +4750 -0
- package/src/hooks/kiva/use-kiva-data-view-select.tsx +1273 -0
- package/src/hooks/kiva/use-kiva-form-view.tsx +1581 -0
- package/src/hooks/kiva/use-kiva-inventory.tsx +184 -0
- package/src/hooks/kiva/use-kiva-kanban.tsx +1750 -0
- package/src/hooks/kiva/use-kiva-map-view.tsx +2255 -0
- package/src/hooks/kiva/use-kiva-pivot-calendar.tsx +759 -0
- package/src/hooks/kiva/use-kiva-pivot-filter.tsx +1523 -0
- package/src/hooks/kiva/use-kiva-pivot-grid.tsx +543 -0
- package/src/hooks/kiva/use-kiva-tenant.tsx +313 -0
- package/src/hooks/kiva/use-parameter-persistence.ts +191 -0
|
@@ -0,0 +1,2255 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
|
|
3
|
+
// @ts-nocheck
|
|
4
|
+
/* eslint-disable */
|
|
5
|
+
import {
|
|
6
|
+
memo,
|
|
7
|
+
useCallback,
|
|
8
|
+
useEffect,
|
|
9
|
+
useMemo,
|
|
10
|
+
useRef,
|
|
11
|
+
useState,
|
|
12
|
+
type ReactNode
|
|
13
|
+
} from 'react';
|
|
14
|
+
|
|
15
|
+
import { renderToString } from 'react-dom/server';
|
|
16
|
+
|
|
17
|
+
import { type DataSourceField } from '@kivacore/app-utils';
|
|
18
|
+
|
|
19
|
+
import { useQuery } from '@tanstack/react-query';
|
|
20
|
+
import {
|
|
21
|
+
APIProvider,
|
|
22
|
+
InfoWindow,
|
|
23
|
+
Map as GoogleMap,
|
|
24
|
+
Marker,
|
|
25
|
+
useMap as useGoogleMap,
|
|
26
|
+
useMarkerRef
|
|
27
|
+
} from '@vis.gl/react-google-maps';
|
|
28
|
+
import { type DivIcon, type Marker as LeafletMarkerType } from 'leaflet';
|
|
29
|
+
import { Layers, MapPin, Pencil } from 'lucide-react';
|
|
30
|
+
import {
|
|
31
|
+
Marker as ReactLeafletMarker,
|
|
32
|
+
Popup as ReactLeafletPopup,
|
|
33
|
+
useMap as useLeafletMap,
|
|
34
|
+
useMapEvents as useLeafletMapEvents
|
|
35
|
+
} from 'react-leaflet';
|
|
36
|
+
|
|
37
|
+
import {
|
|
38
|
+
Map,
|
|
39
|
+
MapFullscreenControl,
|
|
40
|
+
MapLocateControl,
|
|
41
|
+
MapMarkerClusterGroup,
|
|
42
|
+
MapTileLayer,
|
|
43
|
+
MapZoomControl,
|
|
44
|
+
useLeaflet
|
|
45
|
+
} from '@kivacore/ui-pro-shared/components/kiva/map';
|
|
46
|
+
import { cn } from '@kivacore/ui-pro-shared/lib/utils';
|
|
47
|
+
import { useUiTranslation } from '@kivacore/ui-pro-shared/hooks/kiva/use-ui-translation';
|
|
48
|
+
import { resolveColorHex } from '@kivacore/ui-pro-shared/lib/kiva/tailwind-colors';
|
|
49
|
+
|
|
50
|
+
import {
|
|
51
|
+
useKivaDataGrid,
|
|
52
|
+
type KivaDataGridListParams,
|
|
53
|
+
type UseKivaDataGridOptions,
|
|
54
|
+
type UseKivaDataGridResult
|
|
55
|
+
} from './use-kiva-data-grid';
|
|
56
|
+
import {
|
|
57
|
+
buildPersistKey,
|
|
58
|
+
resolvePersistConfig,
|
|
59
|
+
useParameterPersistence
|
|
60
|
+
} from './use-parameter-persistence';
|
|
61
|
+
|
|
62
|
+
const EMPTY_ITEMS: Array<never> = [];
|
|
63
|
+
const DEFAULT_MAP_CENTER = {
|
|
64
|
+
lat: 39.9334,
|
|
65
|
+
lng: 32.8597
|
|
66
|
+
};
|
|
67
|
+
const DEFAULT_MAP_ZOOM = 6;
|
|
68
|
+
const DEFAULT_FOCUSED_ZOOM = 14;
|
|
69
|
+
const DEFAULT_FIT_BOUNDS_PADDING = 48;
|
|
70
|
+
const TITLE_FIELD_CANDIDATES = [
|
|
71
|
+
'name',
|
|
72
|
+
'title',
|
|
73
|
+
'label',
|
|
74
|
+
'subject',
|
|
75
|
+
'display_name',
|
|
76
|
+
'displayName',
|
|
77
|
+
'commercial_title',
|
|
78
|
+
'short_name'
|
|
79
|
+
] as const;
|
|
80
|
+
const DESCRIPTION_FIELD_CANDIDATES = [
|
|
81
|
+
'description',
|
|
82
|
+
'details',
|
|
83
|
+
'address',
|
|
84
|
+
'city',
|
|
85
|
+
'district',
|
|
86
|
+
'country',
|
|
87
|
+
'state',
|
|
88
|
+
'province',
|
|
89
|
+
'status',
|
|
90
|
+
'type'
|
|
91
|
+
] as const;
|
|
92
|
+
const TEXT_LIKE_FIELD_TYPES = new Set([
|
|
93
|
+
'field-text',
|
|
94
|
+
'field-textarea',
|
|
95
|
+
'field-email',
|
|
96
|
+
'field-phone',
|
|
97
|
+
'field-url'
|
|
98
|
+
]);
|
|
99
|
+
|
|
100
|
+
export type KivaMapProvider = 'leaflet' | 'google';
|
|
101
|
+
|
|
102
|
+
export interface KivaLocationValue {
|
|
103
|
+
address?: string | null;
|
|
104
|
+
description?: string | null;
|
|
105
|
+
details?: string | null;
|
|
106
|
+
latitude?: number | string | null;
|
|
107
|
+
longitude?: number | string | null;
|
|
108
|
+
lat?: number | string | null;
|
|
109
|
+
lng?: number | string | null;
|
|
110
|
+
placeId?: string | null;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export interface KivaMapPoint {
|
|
114
|
+
lat: number;
|
|
115
|
+
lng: number;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
export interface KivaMapBounds {
|
|
119
|
+
north: number;
|
|
120
|
+
south: number;
|
|
121
|
+
east: number;
|
|
122
|
+
west: number;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
export interface KivaNormalizedLocation {
|
|
126
|
+
lat: number;
|
|
127
|
+
lng: number;
|
|
128
|
+
address?: string | null;
|
|
129
|
+
description?: string | null;
|
|
130
|
+
details?: string | null;
|
|
131
|
+
placeId?: string | null;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
export interface KivaMapMarker<TData> {
|
|
135
|
+
id: string;
|
|
136
|
+
title: string;
|
|
137
|
+
subtitle?: string;
|
|
138
|
+
description?: string;
|
|
139
|
+
address?: string;
|
|
140
|
+
/** Resolved image URL from the `markerImageFieldSlug` field, if provided. */
|
|
141
|
+
imageUrl?: string;
|
|
142
|
+
/** Resolved Kiva icon SVG URL from the `markerIconFieldSlug` field, if provided. */
|
|
143
|
+
iconUrl?: string;
|
|
144
|
+
/** Resolved CSS color used to tint the icon (Leaflet) or the badge ring (Google). */
|
|
145
|
+
iconColor?: string;
|
|
146
|
+
position: KivaMapPoint;
|
|
147
|
+
location: KivaNormalizedLocation;
|
|
148
|
+
item: TData;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
export interface KivaMapMarkerBuilderContext<TData> {
|
|
152
|
+
item: TData;
|
|
153
|
+
index: number;
|
|
154
|
+
locationField: DataSourceField;
|
|
155
|
+
titleField: DataSourceField | null;
|
|
156
|
+
descriptionFields: Array<DataSourceField>;
|
|
157
|
+
location: KivaNormalizedLocation;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** Serializable snapshot of the map-owned (non-grid) parameters. */
|
|
161
|
+
interface MapViewPersistSnapshot {
|
|
162
|
+
activeBasemapId?: string | null;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
export interface UseKivaMapViewOptions<TData>
|
|
166
|
+
extends Omit<
|
|
167
|
+
UseKivaDataGridOptions<TData>,
|
|
168
|
+
| 'data'
|
|
169
|
+
| 'enableItemsQuery'
|
|
170
|
+
| 'showSelectColumn'
|
|
171
|
+
| 'enableRowMarkers'
|
|
172
|
+
> {
|
|
173
|
+
data?: Array<TData>;
|
|
174
|
+
locationFieldSlug?: string;
|
|
175
|
+
titleFieldSlug?: string;
|
|
176
|
+
descriptionFieldSlugs?: Array<string>;
|
|
177
|
+
/**
|
|
178
|
+
* Field slug whose value is used as the marker icon image.
|
|
179
|
+
* Supports `field-image` / `field-file` payloads (reads `signed_url`).
|
|
180
|
+
*/
|
|
181
|
+
markerImageFieldSlug?: string;
|
|
182
|
+
/**
|
|
183
|
+
* Field slug whose value is a Kiva icon identifier (e.g. `huge building-06`).
|
|
184
|
+
* Auto-detects `field-icon` type or `icon` slug if omitted.
|
|
185
|
+
*/
|
|
186
|
+
markerIconFieldSlug?: string;
|
|
187
|
+
/**
|
|
188
|
+
* Field slug whose value is a CSS color (hex / `rgb()` / Tailwind token like
|
|
189
|
+
* `"emerald-500"`) used to tint the marker icon.
|
|
190
|
+
*/
|
|
191
|
+
markerIconColorFieldSlug?: string;
|
|
192
|
+
/**
|
|
193
|
+
* Static fallback color applied to every icon when
|
|
194
|
+
* `markerIconColorFieldSlug` is empty or absent.
|
|
195
|
+
*/
|
|
196
|
+
markerIconColor?: string;
|
|
197
|
+
/**
|
|
198
|
+
* Which field to prefer when both image and icon are available.
|
|
199
|
+
* - `'image'` (default): show image if present, fall back to icon, then default marker.
|
|
200
|
+
* - `'icon'`: show icon directly when present, ignoring image.
|
|
201
|
+
*/
|
|
202
|
+
markerPriority?: 'image' | 'icon';
|
|
203
|
+
/**
|
|
204
|
+
* Filter the side list / mapped items to records visible inside the
|
|
205
|
+
* current map viewport. The unfiltered `items` array is preserved on the
|
|
206
|
+
* hook result for any code that needs the full set.
|
|
207
|
+
*
|
|
208
|
+
* - `'auto'` (default): re-filters on every pan/zoom.
|
|
209
|
+
* - `'manual'`: filters only when `searchThisArea()` is called — pairs with
|
|
210
|
+
* an Airbnb-style "Search this area" button via `isViewportStale`.
|
|
211
|
+
* - `false` / omitted: disabled.
|
|
212
|
+
*/
|
|
213
|
+
enableViewportFilter?: boolean;
|
|
214
|
+
/** How the viewport filter applies updates. Default `'auto'`. */
|
|
215
|
+
viewportFilterMode?: 'auto' | 'manual';
|
|
216
|
+
/**
|
|
217
|
+
* Enable drag-to-reposition for individual markers. On drop, the hook will
|
|
218
|
+
* either call `onMarkerMove` if provided, or PATCH the resolved location
|
|
219
|
+
* field of the record directly (and refresh the address via reverse
|
|
220
|
+
* geocoding before reloading the items query).
|
|
221
|
+
*/
|
|
222
|
+
enableMarkerDrag?: boolean;
|
|
223
|
+
/**
|
|
224
|
+
* Called after a marker is dropped. When omitted while `enableMarkerDrag`
|
|
225
|
+
* is on, the hook applies a default PATCH using the resolved location
|
|
226
|
+
* field and the active Kiva client.
|
|
227
|
+
*/
|
|
228
|
+
onMarkerMove?: (
|
|
229
|
+
marker: KivaMapMarker<TData>,
|
|
230
|
+
newPosition: KivaMapPoint
|
|
231
|
+
) => void | Promise<void>;
|
|
232
|
+
/**
|
|
233
|
+
* Handlebars-style template string for popup body text.
|
|
234
|
+
* Use `{{field_slug}}` to interpolate field values.
|
|
235
|
+
* Example: `"{{name}} — {{city}}, {{country}}"`
|
|
236
|
+
*/
|
|
237
|
+
markerTemplate?: string;
|
|
238
|
+
getMarker?: (
|
|
239
|
+
item: TData,
|
|
240
|
+
context: KivaMapMarkerBuilderContext<TData>
|
|
241
|
+
) => KivaMapMarker<TData> | null;
|
|
242
|
+
defaultCenter?: KivaMapPoint;
|
|
243
|
+
defaultZoom?: number;
|
|
244
|
+
focusedZoom?: number;
|
|
245
|
+
fitBoundsPadding?: number;
|
|
246
|
+
autoSelectSingleMarker?: boolean;
|
|
247
|
+
googleMapsApiKey?: string | null;
|
|
248
|
+
/** Called when the user clicks on an empty area of the map (not a marker). */
|
|
249
|
+
onMapClick?: (position: KivaMapPoint) => void;
|
|
250
|
+
/**
|
|
251
|
+
* Basemap variants exposed to the picker. Accepts either built-in ids
|
|
252
|
+
* (`'street'`, `'satellite'`, `'hybrid'`, `'terrain'`) or full custom
|
|
253
|
+
* `KivaBasemapDefinition` objects. Omit / pass `false` to hide the
|
|
254
|
+
* picker entirely.
|
|
255
|
+
*/
|
|
256
|
+
basemaps?: Array<KivaBasemapId | KivaBasemapDefinition> | false;
|
|
257
|
+
/** Initially selected basemap id. Defaults to the first entry of `basemaps`. */
|
|
258
|
+
defaultBasemap?: string;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
export interface UseKivaMapViewResult<TData>
|
|
262
|
+
extends Pick<
|
|
263
|
+
UseKivaDataGridResult<TData>,
|
|
264
|
+
| 'table'
|
|
265
|
+
| 'toolbar'
|
|
266
|
+
| 'views'
|
|
267
|
+
| 'fields'
|
|
268
|
+
| 'dataSource'
|
|
269
|
+
| 'activeViewId'
|
|
270
|
+
| 'setActiveViewId'
|
|
271
|
+
> {
|
|
272
|
+
items: Array<TData>;
|
|
273
|
+
markers: Array<KivaMapMarker<TData>>;
|
|
274
|
+
/** All resolved markers before viewport filtering — use for the underlying data set. */
|
|
275
|
+
allMarkers: Array<KivaMapMarker<TData>>;
|
|
276
|
+
mappedItems: Array<TData>;
|
|
277
|
+
unmappedItems: Array<TData>;
|
|
278
|
+
/** Bounds reported by the active map provider on its last `moveend`/`idle`. */
|
|
279
|
+
viewportBounds: KivaMapBounds | null;
|
|
280
|
+
/** Setter wired into provider events. Not for direct use. */
|
|
281
|
+
setViewportBounds: (next: KivaMapBounds | null) => void;
|
|
282
|
+
/** True when the map has moved since the last applied viewport filter (manual mode). */
|
|
283
|
+
isViewportStale: boolean;
|
|
284
|
+
/** Manually apply the current viewport as the active filter (manual mode). */
|
|
285
|
+
searchThisArea: () => void;
|
|
286
|
+
/** Clear any applied viewport filter and show every marker again. */
|
|
287
|
+
clearViewportFilter: () => void;
|
|
288
|
+
/** Whether marker drag is enabled (mirrors the option). */
|
|
289
|
+
enableMarkerDrag: boolean;
|
|
290
|
+
/** Persist a marker's new position. Wire to the map's `onMarkerMove` prop. */
|
|
291
|
+
handleMarkerMove: (
|
|
292
|
+
marker: KivaMapMarker<TData>,
|
|
293
|
+
newPosition: KivaMapPoint
|
|
294
|
+
) => Promise<void>;
|
|
295
|
+
/** Resolved basemap list (after expanding ids). `[]` when the picker is disabled. */
|
|
296
|
+
availableBasemaps: Array<KivaBasemapDefinition>;
|
|
297
|
+
/** Currently active basemap definition, or `null` when no basemaps are configured. */
|
|
298
|
+
activeBasemap: KivaBasemapDefinition | null;
|
|
299
|
+
/** Switch the active basemap by id. Wire to the map's `onBasemapChange` prop. */
|
|
300
|
+
setActiveBasemap: (id: string) => void;
|
|
301
|
+
locationField: DataSourceField | null;
|
|
302
|
+
titleField: DataSourceField | null;
|
|
303
|
+
descriptionFields: Array<DataSourceField>;
|
|
304
|
+
requestedColumns: string;
|
|
305
|
+
resolvedListParams: KivaDataGridListParams;
|
|
306
|
+
hasLocationField: boolean;
|
|
307
|
+
center: KivaMapPoint;
|
|
308
|
+
bounds: KivaMapBounds | null;
|
|
309
|
+
defaultZoom: number;
|
|
310
|
+
focusedZoom: number;
|
|
311
|
+
fitBoundsPadding: number;
|
|
312
|
+
selectedMarkerId: string | null;
|
|
313
|
+
selectedMarker: KivaMapMarker<TData> | null;
|
|
314
|
+
setSelectedMarkerId: (markerId: string | null) => void;
|
|
315
|
+
selectMarker: (markerId: string) => void;
|
|
316
|
+
clearSelectedMarker: () => void;
|
|
317
|
+
counts: {
|
|
318
|
+
total: number;
|
|
319
|
+
mapped: number;
|
|
320
|
+
unmapped: number;
|
|
321
|
+
};
|
|
322
|
+
googleMapsApiKey: string | null;
|
|
323
|
+
isLoading: boolean;
|
|
324
|
+
error: Error | null;
|
|
325
|
+
reload: () => void;
|
|
326
|
+
/** Forwarded from options — pass to map components as `onMapClick`. */
|
|
327
|
+
onMapClick: ((position: KivaMapPoint) => void) | undefined;
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
export interface KivaMapMarkerIcon {
|
|
331
|
+
/** Image URL to use as the marker icon. */
|
|
332
|
+
url: string;
|
|
333
|
+
/** Icon size in pixels. Defaults to 32×32. */
|
|
334
|
+
size?: { width: number; height: number };
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
export interface KivaMapViewProps<TData> {
|
|
338
|
+
markers: Array<KivaMapMarker<TData>>;
|
|
339
|
+
center: KivaMapPoint;
|
|
340
|
+
bounds?: KivaMapBounds | null;
|
|
341
|
+
defaultZoom?: number;
|
|
342
|
+
focusedZoom?: number;
|
|
343
|
+
fitBoundsPadding?: number;
|
|
344
|
+
selectedMarkerId?: string | null;
|
|
345
|
+
onSelectMarker?: (markerId: string | null) => void;
|
|
346
|
+
/** Called when the user clicks an empty area of the map (not a marker). */
|
|
347
|
+
onMapClick?: (position: KivaMapPoint) => void;
|
|
348
|
+
renderPopup?: (marker: KivaMapMarker<TData>) => ReactNode;
|
|
349
|
+
/** Called when the user clicks the edit button inside the default popup. */
|
|
350
|
+
onEditMarker?: (marker: KivaMapMarker<TData>) => void;
|
|
351
|
+
/** Called after the map finishes panning/zooming with the new visible bounds. */
|
|
352
|
+
onViewportChange?: (bounds: KivaMapBounds | null) => void;
|
|
353
|
+
/** When true, each marker is rendered as draggable. */
|
|
354
|
+
draggableMarkers?: boolean;
|
|
355
|
+
/** Called after the user drops a dragged marker. */
|
|
356
|
+
onMarkerMove?: (
|
|
357
|
+
marker: KivaMapMarker<TData>,
|
|
358
|
+
newPosition: KivaMapPoint
|
|
359
|
+
) => void | Promise<void>;
|
|
360
|
+
/**
|
|
361
|
+
* Underlying marker count before viewport / external filtering. When
|
|
362
|
+
* provided and non-zero, the map renders even with an empty `markers`
|
|
363
|
+
* prop — useful for keeping the map mounted while the viewport happens
|
|
364
|
+
* to contain no records.
|
|
365
|
+
*/
|
|
366
|
+
allMarkersCount?: number;
|
|
367
|
+
/** Basemap options to surface in the in-map picker. Pass `mapView.availableBasemaps`. */
|
|
368
|
+
basemaps?: Array<KivaBasemapDefinition>;
|
|
369
|
+
/** Currently selected basemap. Pass `mapView.activeBasemap`. */
|
|
370
|
+
activeBasemap?: KivaBasemapDefinition | null;
|
|
371
|
+
/** Called when the user picks a different basemap. Pass `mapView.setActiveBasemap`. */
|
|
372
|
+
onBasemapChange?: (id: string) => void;
|
|
373
|
+
/**
|
|
374
|
+
* Custom marker icon. Return a ReactNode (Leaflet) to replace the default
|
|
375
|
+
* MapPin, or return `null` to keep the default.
|
|
376
|
+
*/
|
|
377
|
+
renderMarkerIcon?: (
|
|
378
|
+
marker: KivaMapMarker<TData>,
|
|
379
|
+
isSelected: boolean
|
|
380
|
+
) => ReactNode;
|
|
381
|
+
emptyState?: ReactNode;
|
|
382
|
+
className?: string;
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
export interface KivaGoogleMapViewProps<TData>
|
|
386
|
+
extends KivaMapViewProps<TData> {
|
|
387
|
+
apiKey?: string | null;
|
|
388
|
+
/** Map type / basemap style. Defaults to `'roadmap'`. */
|
|
389
|
+
defaultMapType?: KivaGoogleMapType;
|
|
390
|
+
/**
|
|
391
|
+
* Custom marker icon for Google Maps. Return a URL string or an icon
|
|
392
|
+
* descriptor, or `null` to keep the default pin.
|
|
393
|
+
*/
|
|
394
|
+
getMarkerIcon?: (
|
|
395
|
+
marker: KivaMapMarker<TData>,
|
|
396
|
+
isSelected: boolean
|
|
397
|
+
) => string | KivaMapMarkerIcon | null;
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
interface MarkerResolution<TData> {
|
|
401
|
+
markers: Array<KivaMapMarker<TData>>;
|
|
402
|
+
mappedItems: Array<TData>;
|
|
403
|
+
unmappedItems: Array<TData>;
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
export function useKivaMapView<TData>(
|
|
407
|
+
options: UseKivaMapViewOptions<TData>
|
|
408
|
+
): UseKivaMapViewResult<TData> {
|
|
409
|
+
const {
|
|
410
|
+
data,
|
|
411
|
+
collection,
|
|
412
|
+
locationFieldSlug,
|
|
413
|
+
titleFieldSlug,
|
|
414
|
+
descriptionFieldSlugs,
|
|
415
|
+
markerImageFieldSlug,
|
|
416
|
+
markerIconFieldSlug,
|
|
417
|
+
markerIconColorFieldSlug,
|
|
418
|
+
markerIconColor,
|
|
419
|
+
markerPriority = 'image',
|
|
420
|
+
enableViewportFilter = false,
|
|
421
|
+
viewportFilterMode = 'auto',
|
|
422
|
+
enableMarkerDrag = false,
|
|
423
|
+
onMarkerMove,
|
|
424
|
+
basemaps,
|
|
425
|
+
defaultBasemap,
|
|
426
|
+
markerTemplate,
|
|
427
|
+
getMarker,
|
|
428
|
+
defaultCenter = DEFAULT_MAP_CENTER,
|
|
429
|
+
defaultZoom = DEFAULT_MAP_ZOOM,
|
|
430
|
+
focusedZoom = DEFAULT_FOCUSED_ZOOM,
|
|
431
|
+
fitBoundsPadding = DEFAULT_FIT_BOUNDS_PADDING,
|
|
432
|
+
autoSelectSingleMarker = true,
|
|
433
|
+
googleMapsApiKey,
|
|
434
|
+
onMapClick,
|
|
435
|
+
enableGroupMenu = false,
|
|
436
|
+
enableRowHeightMenu = false,
|
|
437
|
+
enableDisplayMenu = false,
|
|
438
|
+
staleTime = 30_000,
|
|
439
|
+
onReload,
|
|
440
|
+
persistState,
|
|
441
|
+
...dataGridOptions
|
|
442
|
+
} = options;
|
|
443
|
+
|
|
444
|
+
const persistConfig = resolvePersistConfig(persistState);
|
|
445
|
+
const persistEnabled = persistConfig !== null;
|
|
446
|
+
const persistStorage = persistConfig?.storage ?? 'session';
|
|
447
|
+
const persistKeyOverride = persistConfig?.key ?? '';
|
|
448
|
+
|
|
449
|
+
const itemsRefetchRef = useRef<(() => void) | null>(null);
|
|
450
|
+
const handleToolbarReload = useCallback(() => {
|
|
451
|
+
itemsRefetchRef.current?.();
|
|
452
|
+
onReload?.();
|
|
453
|
+
}, [onReload]);
|
|
454
|
+
|
|
455
|
+
const tableData = useMemo<Array<TData>>(
|
|
456
|
+
() => data ?? (EMPTY_ITEMS as Array<TData>),
|
|
457
|
+
[data]
|
|
458
|
+
);
|
|
459
|
+
|
|
460
|
+
const dataGrid = useKivaDataGrid<TData>({
|
|
461
|
+
...dataGridOptions,
|
|
462
|
+
collection,
|
|
463
|
+
data: tableData,
|
|
464
|
+
/*
|
|
465
|
+
* Forward `persistState` so the grid persists the core view params
|
|
466
|
+
* (sort, filters) that drive the map's items query. The map adds a
|
|
467
|
+
* sibling layer below for its own basemap choice under a `…:map` key.
|
|
468
|
+
*/
|
|
469
|
+
persistState,
|
|
470
|
+
staleTime,
|
|
471
|
+
onReload: handleToolbarReload,
|
|
472
|
+
enableItemsQuery: false,
|
|
473
|
+
showSelectColumn: false,
|
|
474
|
+
enableRowMarkers: false,
|
|
475
|
+
enableGroupMenu,
|
|
476
|
+
enableRowHeightMenu,
|
|
477
|
+
enableDisplayMenu
|
|
478
|
+
});
|
|
479
|
+
|
|
480
|
+
const locationField = useMemo(
|
|
481
|
+
() => resolveLocationField(dataGrid.dataSource?.fields, locationFieldSlug),
|
|
482
|
+
[dataGrid.dataSource?.fields, locationFieldSlug]
|
|
483
|
+
);
|
|
484
|
+
|
|
485
|
+
const titleField = useMemo(
|
|
486
|
+
() => resolveTitleField(dataGrid.dataSource?.fields, titleFieldSlug, locationField?.slug),
|
|
487
|
+
[dataGrid.dataSource?.fields, titleFieldSlug, locationField?.slug]
|
|
488
|
+
);
|
|
489
|
+
|
|
490
|
+
const descriptionFieldsKey = descriptionFieldSlugs?.join('\0') ?? '';
|
|
491
|
+
/*
|
|
492
|
+
* Slugs array identity is volatile; descriptionFieldsKey is the stable
|
|
493
|
+
* content hash. Pulling slugs from a ref keeps them out of the memo deps
|
|
494
|
+
* while descriptionFieldsKey drives invalidation when content changes.
|
|
495
|
+
*/
|
|
496
|
+
const descriptionFieldSlugsRef = useRef(descriptionFieldSlugs);
|
|
497
|
+
|
|
498
|
+
descriptionFieldSlugsRef.current = descriptionFieldSlugs;
|
|
499
|
+
|
|
500
|
+
const descriptionFields = useMemo(
|
|
501
|
+
() => {
|
|
502
|
+
void descriptionFieldsKey;
|
|
503
|
+
|
|
504
|
+
return resolveDescriptionFields(
|
|
505
|
+
dataGrid.dataSource?.fields,
|
|
506
|
+
descriptionFieldSlugsRef.current,
|
|
507
|
+
titleField?.slug,
|
|
508
|
+
locationField?.slug
|
|
509
|
+
);
|
|
510
|
+
},
|
|
511
|
+
[
|
|
512
|
+
dataGrid.dataSource?.fields,
|
|
513
|
+
descriptionFieldsKey,
|
|
514
|
+
titleField?.slug,
|
|
515
|
+
locationField?.slug
|
|
516
|
+
]
|
|
517
|
+
);
|
|
518
|
+
|
|
519
|
+
const templateSlugs = useMemo(
|
|
520
|
+
() => (markerTemplate ? extractTemplateSlugs(markerTemplate) : []),
|
|
521
|
+
[markerTemplate]
|
|
522
|
+
);
|
|
523
|
+
|
|
524
|
+
const iconField = useMemo(
|
|
525
|
+
() => resolveIconField(dataGrid.dataSource?.fields, markerIconFieldSlug),
|
|
526
|
+
[dataGrid.dataSource?.fields, markerIconFieldSlug]
|
|
527
|
+
);
|
|
528
|
+
|
|
529
|
+
const requiredFieldSlugs = useMemo(() => {
|
|
530
|
+
const knownSlugs = new Set(
|
|
531
|
+
(dataGrid.dataSource?.fields ?? []).map(field => field.slug)
|
|
532
|
+
);
|
|
533
|
+
const validateSlug = (slug: string | undefined) => (
|
|
534
|
+
slug && knownSlugs.has(slug) ? slug : undefined
|
|
535
|
+
);
|
|
536
|
+
|
|
537
|
+
const fieldSlugs = [
|
|
538
|
+
'id',
|
|
539
|
+
locationField?.slug,
|
|
540
|
+
titleField?.slug,
|
|
541
|
+
...descriptionFields.map(field => field.slug),
|
|
542
|
+
...templateSlugs.map(validateSlug),
|
|
543
|
+
validateSlug(markerImageFieldSlug),
|
|
544
|
+
iconField?.slug,
|
|
545
|
+
validateSlug(markerIconColorFieldSlug)
|
|
546
|
+
];
|
|
547
|
+
|
|
548
|
+
return fieldSlugs.filter(
|
|
549
|
+
(slug, index): slug is string => Boolean(slug) && fieldSlugs.indexOf(slug) === index
|
|
550
|
+
);
|
|
551
|
+
}, [
|
|
552
|
+
dataGrid.dataSource?.fields,
|
|
553
|
+
descriptionFields,
|
|
554
|
+
locationField?.slug,
|
|
555
|
+
titleField?.slug,
|
|
556
|
+
templateSlugs,
|
|
557
|
+
markerImageFieldSlug,
|
|
558
|
+
iconField?.slug,
|
|
559
|
+
markerIconColorFieldSlug
|
|
560
|
+
]);
|
|
561
|
+
|
|
562
|
+
const requestedColumns = useMemo(
|
|
563
|
+
() => requiredFieldSlugs.join(', '),
|
|
564
|
+
[requiredFieldSlugs]
|
|
565
|
+
);
|
|
566
|
+
|
|
567
|
+
const resolvedListParams = useMemo<KivaDataGridListParams>(
|
|
568
|
+
() => ({
|
|
569
|
+
filters: dataGrid.resolvedListParams.filters,
|
|
570
|
+
orderBy: dataGrid.resolvedListParams.orderBy,
|
|
571
|
+
limit: dataGrid.resolvedListParams.limit,
|
|
572
|
+
offset: dataGrid.resolvedListParams.offset,
|
|
573
|
+
columns: requestedColumns
|
|
574
|
+
}),
|
|
575
|
+
[dataGrid.resolvedListParams, requestedColumns]
|
|
576
|
+
);
|
|
577
|
+
|
|
578
|
+
const itemsQuery = useQuery<Array<TData>>({
|
|
579
|
+
queryKey: [
|
|
580
|
+
'kiva',
|
|
581
|
+
'kivaMapViewItems',
|
|
582
|
+
dataGridOptions.appSlug,
|
|
583
|
+
dataGridOptions.dataSourceSlug,
|
|
584
|
+
collection ? 'collection' : 'direct',
|
|
585
|
+
resolvedListParams
|
|
586
|
+
],
|
|
587
|
+
queryFn: async () => {
|
|
588
|
+
if (collection) {
|
|
589
|
+
return unwrapItems<TData>(await collection.list(resolvedListParams));
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
const response = await dataGridOptions.client.get<
|
|
593
|
+
Array<TData> | { data: Array<TData> }
|
|
594
|
+
>(
|
|
595
|
+
`/v1/apps/${dataGridOptions.appSlug}/data-sources/${dataGridOptions.dataSourceSlug}/items`,
|
|
596
|
+
resolvedListParams as Parameters<typeof dataGridOptions.client.get>[1]
|
|
597
|
+
);
|
|
598
|
+
|
|
599
|
+
return unwrapItems<TData>(response);
|
|
600
|
+
},
|
|
601
|
+
enabled: data === undefined
|
|
602
|
+
&& Boolean(locationField)
|
|
603
|
+
&& Boolean(dataGrid.dataSource)
|
|
604
|
+
&& !dataGrid.isLoading,
|
|
605
|
+
staleTime
|
|
606
|
+
});
|
|
607
|
+
|
|
608
|
+
itemsRefetchRef.current = () => {
|
|
609
|
+
if (data === undefined) {
|
|
610
|
+
void itemsQuery.refetch();
|
|
611
|
+
}
|
|
612
|
+
};
|
|
613
|
+
|
|
614
|
+
const items = useMemo<Array<TData>>(
|
|
615
|
+
() => data ?? itemsQuery.data ?? [],
|
|
616
|
+
[data, itemsQuery.data]
|
|
617
|
+
);
|
|
618
|
+
|
|
619
|
+
const markerResolution = useMemo<MarkerResolution<TData>>(
|
|
620
|
+
() => resolveMarkers({
|
|
621
|
+
items,
|
|
622
|
+
locationField,
|
|
623
|
+
titleField,
|
|
624
|
+
descriptionFields,
|
|
625
|
+
markerTemplate,
|
|
626
|
+
markerImageFieldSlug,
|
|
627
|
+
markerIconFieldSlug: iconField?.slug,
|
|
628
|
+
markerIconColorFieldSlug,
|
|
629
|
+
markerIconColor,
|
|
630
|
+
markerPriority,
|
|
631
|
+
getMarker
|
|
632
|
+
}),
|
|
633
|
+
[
|
|
634
|
+
items,
|
|
635
|
+
locationField,
|
|
636
|
+
titleField,
|
|
637
|
+
descriptionFields,
|
|
638
|
+
markerTemplate,
|
|
639
|
+
markerImageFieldSlug,
|
|
640
|
+
iconField?.slug,
|
|
641
|
+
markerIconColorFieldSlug,
|
|
642
|
+
markerIconColor,
|
|
643
|
+
markerPriority,
|
|
644
|
+
getMarker
|
|
645
|
+
]
|
|
646
|
+
);
|
|
647
|
+
|
|
648
|
+
const { markers: allMarkers, mappedItems: allMappedItems, unmappedItems } = markerResolution;
|
|
649
|
+
|
|
650
|
+
/* ---- viewport filter -------------------------------------------------- */
|
|
651
|
+
|
|
652
|
+
const [internalViewportBounds, setInternalViewportBounds] = useState<KivaMapBounds | null>(null);
|
|
653
|
+
const viewportBounds = internalViewportBounds;
|
|
654
|
+
const [appliedViewportBounds, setAppliedViewportBounds] = useState<KivaMapBounds | null>(null);
|
|
655
|
+
|
|
656
|
+
/*
|
|
657
|
+
* Wheel-zoom, pinch, and pan can fire moveend/idle continuously. We do
|
|
658
|
+
* absolutely no work during a gesture — every event just stores the
|
|
659
|
+
* latest bounds in a ref and (re)arms a 400ms trailing-edge timer. Only
|
|
660
|
+
* after the user has been still for 400ms do we touch React state. We
|
|
661
|
+
* also skip the state update entirely if the new bounds matches what's
|
|
662
|
+
* already applied — common when the user pans inside the same coarse
|
|
663
|
+
* area or zooms by a tiny amount.
|
|
664
|
+
*/
|
|
665
|
+
const VIEWPORT_DEBOUNCE_MS = 300;
|
|
666
|
+
const applyDebounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
|
667
|
+
const pendingBoundsRef = useRef<KivaMapBounds | null>(null);
|
|
668
|
+
const lastSettledRef = useRef<KivaMapBounds | null>(null);
|
|
669
|
+
|
|
670
|
+
useEffect(() => () => {
|
|
671
|
+
if (applyDebounceRef.current) clearTimeout(applyDebounceRef.current);
|
|
672
|
+
}, []);
|
|
673
|
+
|
|
674
|
+
const setViewportBounds = useCallback((next: KivaMapBounds | null) => {
|
|
675
|
+
if (!enableViewportFilter) {
|
|
676
|
+
setInternalViewportBounds(next);
|
|
677
|
+
|
|
678
|
+
return;
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
pendingBoundsRef.current = next;
|
|
682
|
+
|
|
683
|
+
if (applyDebounceRef.current) clearTimeout(applyDebounceRef.current);
|
|
684
|
+
applyDebounceRef.current = setTimeout(() => {
|
|
685
|
+
const settled = pendingBoundsRef.current;
|
|
686
|
+
|
|
687
|
+
applyDebounceRef.current = null;
|
|
688
|
+
|
|
689
|
+
if (boundsEqual(settled, lastSettledRef.current)) return;
|
|
690
|
+
lastSettledRef.current = settled;
|
|
691
|
+
|
|
692
|
+
setInternalViewportBounds(settled);
|
|
693
|
+
|
|
694
|
+
if (viewportFilterMode === 'auto') {
|
|
695
|
+
setAppliedViewportBounds(settled);
|
|
696
|
+
}
|
|
697
|
+
}, VIEWPORT_DEBOUNCE_MS);
|
|
698
|
+
}, [enableViewportFilter, viewportFilterMode]);
|
|
699
|
+
|
|
700
|
+
const searchThisArea = useCallback(() => {
|
|
701
|
+
setAppliedViewportBounds(viewportBounds);
|
|
702
|
+
}, [viewportBounds]);
|
|
703
|
+
|
|
704
|
+
const clearViewportFilter = useCallback(() => {
|
|
705
|
+
setAppliedViewportBounds(null);
|
|
706
|
+
}, []);
|
|
707
|
+
|
|
708
|
+
const isViewportStale = useMemo(
|
|
709
|
+
() => enableViewportFilter && !boundsEqual(viewportBounds, appliedViewportBounds),
|
|
710
|
+
[enableViewportFilter, viewportBounds, appliedViewportBounds]
|
|
711
|
+
);
|
|
712
|
+
|
|
713
|
+
const markers = useMemo(() => {
|
|
714
|
+
if (!enableViewportFilter || !appliedViewportBounds) return allMarkers;
|
|
715
|
+
|
|
716
|
+
return allMarkers.filter(marker => isPointInBounds(marker.position, appliedViewportBounds));
|
|
717
|
+
}, [allMarkers, enableViewportFilter, appliedViewportBounds]);
|
|
718
|
+
|
|
719
|
+
const mappedItems = useMemo(() => {
|
|
720
|
+
if (markers === allMarkers) return allMappedItems;
|
|
721
|
+
|
|
722
|
+
return markers.map(marker => marker.item);
|
|
723
|
+
}, [markers, allMarkers, allMappedItems]);
|
|
724
|
+
|
|
725
|
+
/*
|
|
726
|
+
* Bounds for the initial `fitBounds` come from the full marker set so the
|
|
727
|
+
* viewport filter (which shrinks `markers`) can't trigger a fit-bounds
|
|
728
|
+
* feedback loop when the user zooms or pans.
|
|
729
|
+
*/
|
|
730
|
+
const bounds = useMemo(() => getBounds(allMarkers), [allMarkers]);
|
|
731
|
+
const center = useMemo(
|
|
732
|
+
() => getCenter(bounds, allMarkers, defaultCenter),
|
|
733
|
+
[bounds, allMarkers, defaultCenter]
|
|
734
|
+
);
|
|
735
|
+
|
|
736
|
+
const [selectedMarkerId, setSelectedMarkerId] = useState<string | null>(null);
|
|
737
|
+
|
|
738
|
+
useEffect(() => {
|
|
739
|
+
if (markers.length === 0) {
|
|
740
|
+
if (selectedMarkerId !== null) {
|
|
741
|
+
queueMicrotask(() => setSelectedMarkerId(null));
|
|
742
|
+
}
|
|
743
|
+
|
|
744
|
+
return;
|
|
745
|
+
}
|
|
746
|
+
|
|
747
|
+
const selectionExists = selectedMarkerId ? markers.some(marker => marker.id === selectedMarkerId) : false;
|
|
748
|
+
|
|
749
|
+
if (selectionExists) {
|
|
750
|
+
return;
|
|
751
|
+
}
|
|
752
|
+
|
|
753
|
+
if (autoSelectSingleMarker && markers.length === 1) {
|
|
754
|
+
const nextId = markers[0]?.id ?? null;
|
|
755
|
+
|
|
756
|
+
queueMicrotask(() => setSelectedMarkerId(nextId));
|
|
757
|
+
|
|
758
|
+
return;
|
|
759
|
+
}
|
|
760
|
+
|
|
761
|
+
if (selectedMarkerId !== null) {
|
|
762
|
+
queueMicrotask(() => setSelectedMarkerId(null));
|
|
763
|
+
}
|
|
764
|
+
}, [autoSelectSingleMarker, markers, selectedMarkerId]);
|
|
765
|
+
|
|
766
|
+
const selectedMarker = useMemo(
|
|
767
|
+
() => markers.find(marker => marker.id === selectedMarkerId) ?? null,
|
|
768
|
+
[markers, selectedMarkerId]
|
|
769
|
+
);
|
|
770
|
+
|
|
771
|
+
const selectMarker = useCallback((markerId: string) => {
|
|
772
|
+
setSelectedMarkerId(markerId);
|
|
773
|
+
}, []);
|
|
774
|
+
|
|
775
|
+
const clearSelectedMarker = useCallback(() => {
|
|
776
|
+
setSelectedMarkerId(null);
|
|
777
|
+
}, []);
|
|
778
|
+
|
|
779
|
+
const reload = useCallback(() => {
|
|
780
|
+
dataGrid.refetch();
|
|
781
|
+
void itemsQuery.refetch();
|
|
782
|
+
}, [dataGrid, itemsQuery]);
|
|
783
|
+
|
|
784
|
+
const { client: kivaClient, appSlug: kivaAppSlug, dataSourceSlug: kivaDataSourceSlug } = dataGridOptions;
|
|
785
|
+
|
|
786
|
+
const counts = useMemo(
|
|
787
|
+
() => ({
|
|
788
|
+
total: items.length,
|
|
789
|
+
mapped: mappedItems.length,
|
|
790
|
+
unmapped: unmappedItems.length
|
|
791
|
+
}),
|
|
792
|
+
[items.length, mappedItems.length, unmappedItems.length]
|
|
793
|
+
);
|
|
794
|
+
|
|
795
|
+
const resolvedGoogleMapsApiKey = useMemo(
|
|
796
|
+
() => normalizeString(googleMapsApiKey) ?? normalizeString(import.meta.env.VITE_GOOGLE_MAPS_API_KEY),
|
|
797
|
+
[googleMapsApiKey]
|
|
798
|
+
);
|
|
799
|
+
|
|
800
|
+
const handleMarkerMove = useCallback(async (
|
|
801
|
+
marker: KivaMapMarker<TData>,
|
|
802
|
+
newPosition: KivaMapPoint
|
|
803
|
+
) => {
|
|
804
|
+
if (onMarkerMove) {
|
|
805
|
+
await onMarkerMove(marker, newPosition);
|
|
806
|
+
|
|
807
|
+
return;
|
|
808
|
+
}
|
|
809
|
+
|
|
810
|
+
if (!locationField) return;
|
|
811
|
+
|
|
812
|
+
const address = await reverseGeocode(newPosition.lat, newPosition.lng, resolvedGoogleMapsApiKey ?? undefined);
|
|
813
|
+
|
|
814
|
+
await kivaClient.patch(
|
|
815
|
+
`/v1/apps/${kivaAppSlug}/data-sources/${kivaDataSourceSlug}/items/${marker.id}`,
|
|
816
|
+
{
|
|
817
|
+
[locationField.slug]: {
|
|
818
|
+
latitude: newPosition.lat,
|
|
819
|
+
longitude: newPosition.lng,
|
|
820
|
+
address: address ?? `${newPosition.lat.toFixed(5)}, ${newPosition.lng.toFixed(5)}`
|
|
821
|
+
}
|
|
822
|
+
} as Parameters<typeof kivaClient.patch>[1]
|
|
823
|
+
);
|
|
824
|
+
|
|
825
|
+
reload();
|
|
826
|
+
}, [
|
|
827
|
+
onMarkerMove,
|
|
828
|
+
locationField,
|
|
829
|
+
resolvedGoogleMapsApiKey,
|
|
830
|
+
kivaClient,
|
|
831
|
+
kivaAppSlug,
|
|
832
|
+
kivaDataSourceSlug,
|
|
833
|
+
reload
|
|
834
|
+
]);
|
|
835
|
+
|
|
836
|
+
const availableBasemaps = useMemo<Array<KivaBasemapDefinition>>(() => {
|
|
837
|
+
if (basemaps === false || basemaps === undefined) return [];
|
|
838
|
+
|
|
839
|
+
return basemaps
|
|
840
|
+
.map((entry) => {
|
|
841
|
+
if (typeof entry === 'string') return DEFAULT_KIVA_BASEMAPS[entry] ?? null;
|
|
842
|
+
|
|
843
|
+
return entry;
|
|
844
|
+
})
|
|
845
|
+
.filter((entry): entry is KivaBasemapDefinition => Boolean(entry));
|
|
846
|
+
}, [basemaps]);
|
|
847
|
+
|
|
848
|
+
const [activeBasemapId, setActiveBasemapId] = useState<string | null>(null);
|
|
849
|
+
/*
|
|
850
|
+
* Read current `activeBasemapId` through a ref so this effect re-runs only
|
|
851
|
+
* when the basemap list/default actually change.
|
|
852
|
+
*/
|
|
853
|
+
const activeBasemapIdRef = useRef(activeBasemapId);
|
|
854
|
+
|
|
855
|
+
activeBasemapIdRef.current = activeBasemapId;
|
|
856
|
+
|
|
857
|
+
useEffect(() => {
|
|
858
|
+
if (availableBasemaps.length === 0) {
|
|
859
|
+
if (activeBasemapIdRef.current !== null) queueMicrotask(() => setActiveBasemapId(null));
|
|
860
|
+
|
|
861
|
+
return;
|
|
862
|
+
}
|
|
863
|
+
|
|
864
|
+
let exists = false;
|
|
865
|
+
const { current } = activeBasemapIdRef;
|
|
866
|
+
|
|
867
|
+
if (current) {
|
|
868
|
+
exists = availableBasemaps.some(b => b.id === current);
|
|
869
|
+
}
|
|
870
|
+
|
|
871
|
+
if (exists) return;
|
|
872
|
+
|
|
873
|
+
let initial = availableBasemaps[0]?.id ?? null;
|
|
874
|
+
|
|
875
|
+
if (defaultBasemap && availableBasemaps.some(b => b.id === defaultBasemap)) {
|
|
876
|
+
initial = defaultBasemap;
|
|
877
|
+
}
|
|
878
|
+
|
|
879
|
+
if (initial) queueMicrotask(() => setActiveBasemapId(initial));
|
|
880
|
+
}, [availableBasemaps, defaultBasemap]);
|
|
881
|
+
|
|
882
|
+
const activeBasemap = useMemo<KivaBasemapDefinition | null>(
|
|
883
|
+
() => availableBasemaps.find(b => b.id === activeBasemapId) ?? null,
|
|
884
|
+
[availableBasemaps, activeBasemapId]
|
|
885
|
+
);
|
|
886
|
+
|
|
887
|
+
const setActiveBasemap = useCallback((id: string) => {
|
|
888
|
+
setActiveBasemapId(id);
|
|
889
|
+
}, []);
|
|
890
|
+
|
|
891
|
+
/*
|
|
892
|
+
* ── View-parameter persistence (map layer) ────────────────────────────
|
|
893
|
+
* The grid (composed above) persists the core view params. This sibling
|
|
894
|
+
* layer remembers the user's basemap choice per active view under a
|
|
895
|
+
* `…:map` key. Viewport center/zoom is intentionally not persisted — it
|
|
896
|
+
* would fight the auto fit-bounds / single-marker auto-select behavior.
|
|
897
|
+
*
|
|
898
|
+
* Restore is queued as a microtask so it lands AFTER the basemap-init
|
|
899
|
+
* effect's own `queueMicrotask` default, which would otherwise overwrite it
|
|
900
|
+
* on the first load.
|
|
901
|
+
*/
|
|
902
|
+
const persistStorageKey = useMemo(() => {
|
|
903
|
+
if (!persistEnabled) return null;
|
|
904
|
+
|
|
905
|
+
const dataSourceSegment = persistKeyOverride
|
|
906
|
+
|| `${dataGridOptions.appSlug}:${dataGridOptions.dataSourceSlug}`;
|
|
907
|
+
|
|
908
|
+
return buildPersistKey([dataSourceSegment, dataGrid.activeViewId ?? 'default', 'map']);
|
|
909
|
+
}, [
|
|
910
|
+
persistEnabled,
|
|
911
|
+
persistKeyOverride,
|
|
912
|
+
dataGridOptions.appSlug,
|
|
913
|
+
dataGridOptions.dataSourceSlug,
|
|
914
|
+
dataGrid.activeViewId
|
|
915
|
+
]);
|
|
916
|
+
|
|
917
|
+
const persistReady = persistEnabled && availableBasemaps.length > 0;
|
|
918
|
+
|
|
919
|
+
const persistSnapshot = useMemo<MapViewPersistSnapshot>(
|
|
920
|
+
() => ({ activeBasemapId }),
|
|
921
|
+
[activeBasemapId]
|
|
922
|
+
);
|
|
923
|
+
|
|
924
|
+
const restorePersistedParams = useCallback((restored: Partial<MapViewPersistSnapshot>) => {
|
|
925
|
+
if (
|
|
926
|
+
typeof restored.activeBasemapId === 'string'
|
|
927
|
+
&& availableBasemaps.some(basemap => basemap.id === restored.activeBasemapId)
|
|
928
|
+
) {
|
|
929
|
+
const id = restored.activeBasemapId;
|
|
930
|
+
|
|
931
|
+
queueMicrotask(() => setActiveBasemapId(id));
|
|
932
|
+
}
|
|
933
|
+
}, [availableBasemaps]);
|
|
934
|
+
|
|
935
|
+
useParameterPersistence<MapViewPersistSnapshot>({
|
|
936
|
+
enabled: persistEnabled,
|
|
937
|
+
storage: persistStorage,
|
|
938
|
+
storageKey: persistStorageKey,
|
|
939
|
+
ready: persistReady,
|
|
940
|
+
snapshot: persistSnapshot,
|
|
941
|
+
onRestore: restorePersistedParams
|
|
942
|
+
});
|
|
943
|
+
|
|
944
|
+
const isLoading = dataGrid.isLoading || (data === undefined && itemsQuery.isLoading);
|
|
945
|
+
const error = (dataGrid.error ?? (itemsQuery.error as Error | null)) ?? null;
|
|
946
|
+
|
|
947
|
+
return {
|
|
948
|
+
table: dataGrid.table,
|
|
949
|
+
toolbar: dataGrid.toolbar,
|
|
950
|
+
views: dataGrid.views,
|
|
951
|
+
fields: dataGrid.fields,
|
|
952
|
+
dataSource: dataGrid.dataSource,
|
|
953
|
+
activeViewId: dataGrid.activeViewId,
|
|
954
|
+
setActiveViewId: dataGrid.setActiveViewId,
|
|
955
|
+
items,
|
|
956
|
+
markers,
|
|
957
|
+
allMarkers,
|
|
958
|
+
mappedItems,
|
|
959
|
+
unmappedItems,
|
|
960
|
+
viewportBounds,
|
|
961
|
+
setViewportBounds,
|
|
962
|
+
isViewportStale,
|
|
963
|
+
searchThisArea,
|
|
964
|
+
clearViewportFilter,
|
|
965
|
+
enableMarkerDrag,
|
|
966
|
+
handleMarkerMove,
|
|
967
|
+
availableBasemaps,
|
|
968
|
+
activeBasemap,
|
|
969
|
+
setActiveBasemap,
|
|
970
|
+
locationField,
|
|
971
|
+
titleField,
|
|
972
|
+
descriptionFields,
|
|
973
|
+
requestedColumns,
|
|
974
|
+
resolvedListParams,
|
|
975
|
+
hasLocationField: Boolean(locationField),
|
|
976
|
+
center,
|
|
977
|
+
bounds,
|
|
978
|
+
defaultZoom,
|
|
979
|
+
focusedZoom,
|
|
980
|
+
fitBoundsPadding,
|
|
981
|
+
selectedMarkerId,
|
|
982
|
+
selectedMarker,
|
|
983
|
+
setSelectedMarkerId,
|
|
984
|
+
selectMarker,
|
|
985
|
+
clearSelectedMarker,
|
|
986
|
+
counts,
|
|
987
|
+
googleMapsApiKey: resolvedGoogleMapsApiKey,
|
|
988
|
+
isLoading,
|
|
989
|
+
error,
|
|
990
|
+
reload,
|
|
991
|
+
onMapClick
|
|
992
|
+
};
|
|
993
|
+
}
|
|
994
|
+
|
|
995
|
+
export function KivaLeafletMapView<TData>({
|
|
996
|
+
markers,
|
|
997
|
+
center,
|
|
998
|
+
bounds,
|
|
999
|
+
defaultZoom = DEFAULT_MAP_ZOOM,
|
|
1000
|
+
focusedZoom = DEFAULT_FOCUSED_ZOOM,
|
|
1001
|
+
fitBoundsPadding = DEFAULT_FIT_BOUNDS_PADDING,
|
|
1002
|
+
onSelectMarker,
|
|
1003
|
+
onMapClick,
|
|
1004
|
+
onViewportChange,
|
|
1005
|
+
draggableMarkers,
|
|
1006
|
+
onMarkerMove,
|
|
1007
|
+
allMarkersCount,
|
|
1008
|
+
basemaps,
|
|
1009
|
+
activeBasemap,
|
|
1010
|
+
onBasemapChange,
|
|
1011
|
+
renderPopup,
|
|
1012
|
+
renderMarkerIcon,
|
|
1013
|
+
onEditMarker,
|
|
1014
|
+
emptyState,
|
|
1015
|
+
className
|
|
1016
|
+
}: KivaMapViewProps<TData>) {
|
|
1017
|
+
const { t } = useUiTranslation();
|
|
1018
|
+
|
|
1019
|
+
const hasAnyData = (allMarkersCount ?? markers.length) > 0;
|
|
1020
|
+
|
|
1021
|
+
if (!hasAnyData) {
|
|
1022
|
+
return (
|
|
1023
|
+
<KivaMapEmptyState className={className}>
|
|
1024
|
+
{emptyState ?? t('ui.mapView.emptyMarkers', 'No mapped records yet.')}
|
|
1025
|
+
</KivaMapEmptyState>
|
|
1026
|
+
);
|
|
1027
|
+
}
|
|
1028
|
+
|
|
1029
|
+
const markerPosition = toLeafletPosition(center);
|
|
1030
|
+
|
|
1031
|
+
return (
|
|
1032
|
+
<div className={cn('relative overflow-hidden rounded-xl border bg-card', className)}>
|
|
1033
|
+
<Map center={markerPosition} zoom={defaultZoom} className="h-full w-full">
|
|
1034
|
+
<MapTileLayer
|
|
1035
|
+
key={activeBasemap?.id ?? 'default'}
|
|
1036
|
+
name={activeBasemap?.label ?? 'Default'}
|
|
1037
|
+
url={activeBasemap?.leafletUrl}
|
|
1038
|
+
darkUrl={activeBasemap?.leafletDarkUrl}
|
|
1039
|
+
attribution={activeBasemap?.leafletAttribution} />
|
|
1040
|
+
<LeafletViewportController
|
|
1041
|
+
center={center}
|
|
1042
|
+
bounds={bounds}
|
|
1043
|
+
defaultZoom={defaultZoom}
|
|
1044
|
+
focusedZoom={focusedZoom}
|
|
1045
|
+
fitBoundsPadding={fitBoundsPadding} />
|
|
1046
|
+
<LeafletMapSelectionReset onSelectMarker={onSelectMarker} onMapClick={onMapClick} />
|
|
1047
|
+
<LeafletViewportReporter onViewportChange={onViewportChange} />
|
|
1048
|
+
<MapZoomControl position="top-2 left-2" />
|
|
1049
|
+
<MapFullscreenControl position="top-2 right-2" />
|
|
1050
|
+
<MapLocateControl position="bottom-2 right-2" />
|
|
1051
|
+
<MapMarkerClusterGroup
|
|
1052
|
+
animate={false}
|
|
1053
|
+
animateAddingMarkers={false}
|
|
1054
|
+
removeOutsideVisibleBounds
|
|
1055
|
+
chunkedLoading>
|
|
1056
|
+
{markers.map(marker => (
|
|
1057
|
+
<LeafletMarkerItem
|
|
1058
|
+
key={marker.id}
|
|
1059
|
+
marker={marker}
|
|
1060
|
+
onSelectMarker={onSelectMarker}
|
|
1061
|
+
onEditMarker={onEditMarker as LeafletMarkerItemProps['onEditMarker']}
|
|
1062
|
+
renderMarkerIcon={renderMarkerIcon as LeafletMarkerItemProps['renderMarkerIcon']}
|
|
1063
|
+
renderPopup={renderPopup as LeafletMarkerItemProps['renderPopup']}
|
|
1064
|
+
draggable={draggableMarkers}
|
|
1065
|
+
onMarkerMove={onMarkerMove as LeafletMarkerItemProps['onMarkerMove']} />
|
|
1066
|
+
))}
|
|
1067
|
+
</MapMarkerClusterGroup>
|
|
1068
|
+
</Map>
|
|
1069
|
+
<BasemapPicker
|
|
1070
|
+
basemaps={basemaps}
|
|
1071
|
+
activeBasemap={activeBasemap ?? null}
|
|
1072
|
+
onChange={onBasemapChange} />
|
|
1073
|
+
</div>
|
|
1074
|
+
);
|
|
1075
|
+
}
|
|
1076
|
+
|
|
1077
|
+
export function KivaGoogleMapView<TData>({
|
|
1078
|
+
apiKey,
|
|
1079
|
+
markers,
|
|
1080
|
+
center,
|
|
1081
|
+
bounds,
|
|
1082
|
+
defaultZoom = DEFAULT_MAP_ZOOM,
|
|
1083
|
+
focusedZoom = DEFAULT_FOCUSED_ZOOM,
|
|
1084
|
+
fitBoundsPadding = DEFAULT_FIT_BOUNDS_PADDING,
|
|
1085
|
+
defaultMapType = 'roadmap',
|
|
1086
|
+
selectedMarkerId,
|
|
1087
|
+
onSelectMarker,
|
|
1088
|
+
onMapClick,
|
|
1089
|
+
onViewportChange,
|
|
1090
|
+
draggableMarkers,
|
|
1091
|
+
onMarkerMove,
|
|
1092
|
+
allMarkersCount,
|
|
1093
|
+
basemaps,
|
|
1094
|
+
activeBasemap,
|
|
1095
|
+
onBasemapChange,
|
|
1096
|
+
renderPopup,
|
|
1097
|
+
getMarkerIcon,
|
|
1098
|
+
emptyState,
|
|
1099
|
+
className
|
|
1100
|
+
}: KivaGoogleMapViewProps<TData>) {
|
|
1101
|
+
const { t } = useUiTranslation();
|
|
1102
|
+
|
|
1103
|
+
if (!apiKey) {
|
|
1104
|
+
return (
|
|
1105
|
+
<KivaMapEmptyState className={className}>
|
|
1106
|
+
{t('ui.mapView.googleMapsUnavailable', 'Google Maps is unavailable in this environment.')}
|
|
1107
|
+
</KivaMapEmptyState>
|
|
1108
|
+
);
|
|
1109
|
+
}
|
|
1110
|
+
|
|
1111
|
+
const hasAnyData = (allMarkersCount ?? markers.length) > 0;
|
|
1112
|
+
|
|
1113
|
+
if (!hasAnyData) {
|
|
1114
|
+
return (
|
|
1115
|
+
<KivaMapEmptyState className={className}>
|
|
1116
|
+
{emptyState ?? t('ui.mapView.emptyMarkers', 'No mapped records yet.')}
|
|
1117
|
+
</KivaMapEmptyState>
|
|
1118
|
+
);
|
|
1119
|
+
}
|
|
1120
|
+
|
|
1121
|
+
return (
|
|
1122
|
+
<div className={cn('relative overflow-hidden rounded-xl border bg-card', className)}>
|
|
1123
|
+
<APIProvider apiKey={apiKey}>
|
|
1124
|
+
<GoogleMap
|
|
1125
|
+
defaultCenter={center}
|
|
1126
|
+
defaultZoom={defaultZoom}
|
|
1127
|
+
className="h-full w-full"
|
|
1128
|
+
mapTypeId={activeBasemap?.googleMapType ?? defaultMapType}
|
|
1129
|
+
mapTypeControl={false}
|
|
1130
|
+
fullscreenControl
|
|
1131
|
+
streetViewControl={false}
|
|
1132
|
+
zoomControl
|
|
1133
|
+
gestureHandling="cooperative"
|
|
1134
|
+
clickableIcons={false}
|
|
1135
|
+
onClick={(e) => {
|
|
1136
|
+
onSelectMarker?.(null);
|
|
1137
|
+
const { latLng } = e.detail;
|
|
1138
|
+
|
|
1139
|
+
if (onMapClick && latLng) {
|
|
1140
|
+
const pos = { lat: latLng.lat, lng: latLng.lng };
|
|
1141
|
+
|
|
1142
|
+
onMapClick(pos);
|
|
1143
|
+
void reverseGeocode(pos.lat, pos.lng, apiKey).then((address) => {
|
|
1144
|
+
if (address) onMapClick({ ...pos, address } as KivaMapPoint);
|
|
1145
|
+
});
|
|
1146
|
+
}
|
|
1147
|
+
}}
|
|
1148
|
+
onIdle={(e) => {
|
|
1149
|
+
if (!onViewportChange) return;
|
|
1150
|
+
const { map } = e;
|
|
1151
|
+
const b = map.getBounds();
|
|
1152
|
+
|
|
1153
|
+
if (!b) return;
|
|
1154
|
+
const ne = b.getNorthEast();
|
|
1155
|
+
const sw = b.getSouthWest();
|
|
1156
|
+
|
|
1157
|
+
onViewportChange({
|
|
1158
|
+
north: ne.lat(),
|
|
1159
|
+
south: sw.lat(),
|
|
1160
|
+
east: ne.lng(),
|
|
1161
|
+
west: sw.lng()
|
|
1162
|
+
});
|
|
1163
|
+
}}>
|
|
1164
|
+
<GoogleViewportController
|
|
1165
|
+
center={center}
|
|
1166
|
+
bounds={bounds}
|
|
1167
|
+
defaultZoom={defaultZoom}
|
|
1168
|
+
focusedZoom={focusedZoom}
|
|
1169
|
+
fitBoundsPadding={fitBoundsPadding} />
|
|
1170
|
+
{markers.map(marker => (
|
|
1171
|
+
<GoogleMarkerWithPopup
|
|
1172
|
+
key={marker.id}
|
|
1173
|
+
marker={marker}
|
|
1174
|
+
selected={marker.id === selectedMarkerId}
|
|
1175
|
+
onSelectMarker={onSelectMarker}
|
|
1176
|
+
renderPopup={renderPopup}
|
|
1177
|
+
getMarkerIcon={getMarkerIcon}
|
|
1178
|
+
draggable={draggableMarkers}
|
|
1179
|
+
onMarkerMove={onMarkerMove} />
|
|
1180
|
+
))}
|
|
1181
|
+
</GoogleMap>
|
|
1182
|
+
</APIProvider>
|
|
1183
|
+
<BasemapPicker
|
|
1184
|
+
basemaps={basemaps}
|
|
1185
|
+
activeBasemap={activeBasemap ?? null}
|
|
1186
|
+
onChange={onBasemapChange} />
|
|
1187
|
+
</div>
|
|
1188
|
+
);
|
|
1189
|
+
}
|
|
1190
|
+
|
|
1191
|
+
function LeafletViewportController({
|
|
1192
|
+
center,
|
|
1193
|
+
bounds,
|
|
1194
|
+
defaultZoom,
|
|
1195
|
+
focusedZoom,
|
|
1196
|
+
fitBoundsPadding
|
|
1197
|
+
}: {
|
|
1198
|
+
center: KivaMapPoint;
|
|
1199
|
+
bounds?: KivaMapBounds | null;
|
|
1200
|
+
defaultZoom: number;
|
|
1201
|
+
focusedZoom: number;
|
|
1202
|
+
fitBoundsPadding: number;
|
|
1203
|
+
}) {
|
|
1204
|
+
const map = useLeafletMap();
|
|
1205
|
+
/*
|
|
1206
|
+
* `fitBounds` is run exactly once — the first time real bounds are
|
|
1207
|
+
* available. Subsequent changes (record edits, drag-to-move, refetch) must
|
|
1208
|
+
* not steal the user's chosen viewport, or it triggers a recenter feedback
|
|
1209
|
+
* loop with the viewport filter.
|
|
1210
|
+
*/
|
|
1211
|
+
const hasFittedRef = useRef(false);
|
|
1212
|
+
|
|
1213
|
+
useEffect(() => {
|
|
1214
|
+
if (hasFittedRef.current) return;
|
|
1215
|
+
|
|
1216
|
+
if (!bounds) {
|
|
1217
|
+
map.setView(toLeafletPosition(center), defaultZoom);
|
|
1218
|
+
|
|
1219
|
+
return;
|
|
1220
|
+
}
|
|
1221
|
+
|
|
1222
|
+
if (isSinglePointBounds(bounds)) {
|
|
1223
|
+
map.setView(toLeafletPosition(center), focusedZoom);
|
|
1224
|
+
hasFittedRef.current = true;
|
|
1225
|
+
|
|
1226
|
+
return;
|
|
1227
|
+
}
|
|
1228
|
+
|
|
1229
|
+
map.fitBounds(
|
|
1230
|
+
[[bounds.south, bounds.west], [bounds.north, bounds.east]],
|
|
1231
|
+
{
|
|
1232
|
+
padding: [fitBoundsPadding, fitBoundsPadding]
|
|
1233
|
+
}
|
|
1234
|
+
);
|
|
1235
|
+
hasFittedRef.current = true;
|
|
1236
|
+
}, [
|
|
1237
|
+
bounds,
|
|
1238
|
+
center,
|
|
1239
|
+
defaultZoom,
|
|
1240
|
+
fitBoundsPadding,
|
|
1241
|
+
focusedZoom,
|
|
1242
|
+
map
|
|
1243
|
+
]);
|
|
1244
|
+
|
|
1245
|
+
return null;
|
|
1246
|
+
}
|
|
1247
|
+
|
|
1248
|
+
function defaultLeafletIcon(marker: KivaMapMarker<unknown>, isSelected: boolean): ReactNode {
|
|
1249
|
+
if (marker.imageUrl || marker.iconUrl) return null;
|
|
1250
|
+
|
|
1251
|
+
return isSelected ? <MapPin className="size-6 fill-primary text-primary drop-shadow-sm" /> : <MapPin className="size-6 text-primary drop-shadow-sm" />;
|
|
1252
|
+
}
|
|
1253
|
+
|
|
1254
|
+
function defaultLeafletIconHtml(marker: KivaMapMarker<unknown>, isSelected: boolean): string | null {
|
|
1255
|
+
if (marker.imageUrl) {
|
|
1256
|
+
const border = isSelected ? '3px solid #6366f1' : '2px solid #ffffff';
|
|
1257
|
+
const url = marker.imageUrl.replace(/'/g, '%27');
|
|
1258
|
+
|
|
1259
|
+
return `<div style="width:36px;height:36px;border-radius:50%;border:${border};overflow:hidden;background:#fff url('${url}') center/cover no-repeat;box-shadow:0 1px 4px rgba(0,0,0,0.4)"></div>`;
|
|
1260
|
+
}
|
|
1261
|
+
|
|
1262
|
+
if (marker.iconUrl) {
|
|
1263
|
+
const url = marker.iconUrl.replace(/'/g, '%27');
|
|
1264
|
+
const ring = isSelected ? 'box-shadow:0 0 0 3px #6366f1,0 1px 4px rgba(0,0,0,0.3)' : 'box-shadow:0 1px 4px rgba(0,0,0,0.25)';
|
|
1265
|
+
let innerStyle: string;
|
|
1266
|
+
|
|
1267
|
+
if (marker.iconColor) {
|
|
1268
|
+
innerStyle = `width:20px;height:20px;background-color:${marker.iconColor};-webkit-mask:url('${url}') center/contain no-repeat;mask:url('${url}') center/contain no-repeat`;
|
|
1269
|
+
} else {
|
|
1270
|
+
innerStyle = `width:20px;height:20px;background:transparent center/contain no-repeat url('${url}')`;
|
|
1271
|
+
}
|
|
1272
|
+
|
|
1273
|
+
return `<div style="width:32px;height:32px;border-radius:50%;background:#fff;border:1.5px solid #fff;display:flex;align-items:center;justify-content:center;${ring}"><div style="${innerStyle}"></div></div>`;
|
|
1274
|
+
}
|
|
1275
|
+
|
|
1276
|
+
return null;
|
|
1277
|
+
}
|
|
1278
|
+
|
|
1279
|
+
type LeafletMarkerItemProps = {
|
|
1280
|
+
marker: KivaMapMarker<unknown>;
|
|
1281
|
+
onSelectMarker?: (markerId: string | null) => void;
|
|
1282
|
+
onEditMarker?: (marker: KivaMapMarker<unknown>) => void;
|
|
1283
|
+
renderMarkerIcon?: (marker: KivaMapMarker<unknown>, isSelected: boolean) => ReactNode;
|
|
1284
|
+
renderPopup?: (marker: KivaMapMarker<unknown>) => ReactNode;
|
|
1285
|
+
draggable?: boolean;
|
|
1286
|
+
onMarkerMove?: (
|
|
1287
|
+
marker: KivaMapMarker<unknown>,
|
|
1288
|
+
newPosition: KivaMapPoint
|
|
1289
|
+
) => void | Promise<void>;
|
|
1290
|
+
};
|
|
1291
|
+
|
|
1292
|
+
const LeafletMarkerItem = memo(
|
|
1293
|
+
({
|
|
1294
|
+
marker,
|
|
1295
|
+
onSelectMarker,
|
|
1296
|
+
onEditMarker,
|
|
1297
|
+
renderMarkerIcon,
|
|
1298
|
+
renderPopup,
|
|
1299
|
+
draggable,
|
|
1300
|
+
onMarkerMove
|
|
1301
|
+
}: LeafletMarkerItemProps) => {
|
|
1302
|
+
const markerRef = useRef<LeafletMarkerType>(null);
|
|
1303
|
+
const { L } = useLeaflet();
|
|
1304
|
+
|
|
1305
|
+
/*
|
|
1306
|
+
* Memoize the divIcon by marker.imageUrl so HMR or imageUrl arriving
|
|
1307
|
+
* later (after initial mount) still rebuilds the icon. react-leaflet
|
|
1308
|
+
* only calls setIcon() when the icon reference changes, so this remains
|
|
1309
|
+
* stable for a given marker and doesn't close open popups on re-render.
|
|
1310
|
+
*/
|
|
1311
|
+
const divIcon = useMemo<DivIcon | null>(() => {
|
|
1312
|
+
if (!L) return null;
|
|
1313
|
+
const customNode = renderMarkerIcon?.(marker, false);
|
|
1314
|
+
const imageHtml = !customNode ? defaultLeafletIconHtml(marker, false) : null;
|
|
1315
|
+
const html = imageHtml ?? renderToString(customNode ?? defaultLeafletIcon(marker, false));
|
|
1316
|
+
let size: [number, number] = [24, 24];
|
|
1317
|
+
let anchor: [number, number] = [12, 12];
|
|
1318
|
+
|
|
1319
|
+
if (marker.imageUrl) {
|
|
1320
|
+
size = [36, 36];
|
|
1321
|
+
anchor = [18, 18];
|
|
1322
|
+
} else if (marker.iconUrl) {
|
|
1323
|
+
size = [32, 32];
|
|
1324
|
+
anchor = [16, 16];
|
|
1325
|
+
}
|
|
1326
|
+
|
|
1327
|
+
return L.divIcon({
|
|
1328
|
+
className: '',
|
|
1329
|
+
html,
|
|
1330
|
+
iconSize: size,
|
|
1331
|
+
iconAnchor: anchor
|
|
1332
|
+
});
|
|
1333
|
+
}, [L, marker, renderMarkerIcon]);
|
|
1334
|
+
|
|
1335
|
+
if (!L || !divIcon) return null;
|
|
1336
|
+
|
|
1337
|
+
/*
|
|
1338
|
+
* Icon appearance and selection state are managed imperatively via
|
|
1339
|
+
* Leaflet's popupopen / popupclose events — no React state involved.
|
|
1340
|
+
* This avoids any re-render cascade that could close the popup.
|
|
1341
|
+
*/
|
|
1342
|
+
return (
|
|
1343
|
+
<ReactLeafletMarker
|
|
1344
|
+
ref={markerRef}
|
|
1345
|
+
position={toLeafletPosition(marker.position)}
|
|
1346
|
+
icon={divIcon}
|
|
1347
|
+
draggable={draggable}
|
|
1348
|
+
riseOnHover
|
|
1349
|
+
eventHandlers={{
|
|
1350
|
+
dragend: () => {
|
|
1351
|
+
if (!onMarkerMove) return;
|
|
1352
|
+
const latLng = markerRef.current?.getLatLng();
|
|
1353
|
+
|
|
1354
|
+
if (!latLng) return;
|
|
1355
|
+
void onMarkerMove(marker, { lat: latLng.lat, lng: latLng.lng });
|
|
1356
|
+
},
|
|
1357
|
+
popupopen: () => {
|
|
1358
|
+
onSelectMarker?.(marker.id);
|
|
1359
|
+
const el = markerRef.current?.getElement();
|
|
1360
|
+
|
|
1361
|
+
if (!el) return;
|
|
1362
|
+
const customNode = renderMarkerIcon?.(marker, true);
|
|
1363
|
+
const imageHtml = !customNode ? defaultLeafletIconHtml(marker, true) : null;
|
|
1364
|
+
|
|
1365
|
+
el.innerHTML = imageHtml ?? renderToString(customNode ?? defaultLeafletIcon(marker, true));
|
|
1366
|
+
},
|
|
1367
|
+
popupclose: () => {
|
|
1368
|
+
onSelectMarker?.(null);
|
|
1369
|
+
const el = markerRef.current?.getElement();
|
|
1370
|
+
|
|
1371
|
+
if (!el) return;
|
|
1372
|
+
const customNode = renderMarkerIcon?.(marker, false);
|
|
1373
|
+
const imageHtml = !customNode ? defaultLeafletIconHtml(marker, false) : null;
|
|
1374
|
+
|
|
1375
|
+
el.innerHTML = imageHtml ?? renderToString(customNode ?? defaultLeafletIcon(marker, false));
|
|
1376
|
+
}
|
|
1377
|
+
}}>
|
|
1378
|
+
<ReactLeafletPopup>
|
|
1379
|
+
{renderPopup ? renderPopup(marker) : <DefaultKivaMapPopup marker={marker} onEdit={onEditMarker ? () => onEditMarker(marker) : undefined} />}
|
|
1380
|
+
</ReactLeafletPopup>
|
|
1381
|
+
</ReactLeafletMarker>
|
|
1382
|
+
);
|
|
1383
|
+
},
|
|
1384
|
+
(prev, next) => prev.marker === next.marker
|
|
1385
|
+
);
|
|
1386
|
+
|
|
1387
|
+
function LeafletMapSelectionReset({
|
|
1388
|
+
onMapClick
|
|
1389
|
+
}: {
|
|
1390
|
+
onSelectMarker?: (markerId: string | null) => void;
|
|
1391
|
+
onMapClick?: (position: KivaMapPoint) => void;
|
|
1392
|
+
}) {
|
|
1393
|
+
useLeafletMapEvents({
|
|
1394
|
+
click: (e) => {
|
|
1395
|
+
if (!onMapClick) return;
|
|
1396
|
+
|
|
1397
|
+
const pos = { lat: e.latlng.lat, lng: e.latlng.lng };
|
|
1398
|
+
|
|
1399
|
+
onMapClick(pos);
|
|
1400
|
+
void reverseGeocode(pos.lat, pos.lng).then((address) => {
|
|
1401
|
+
if (address) onMapClick({ ...pos, address } as KivaMapPoint);
|
|
1402
|
+
});
|
|
1403
|
+
}
|
|
1404
|
+
});
|
|
1405
|
+
|
|
1406
|
+
return null;
|
|
1407
|
+
}
|
|
1408
|
+
|
|
1409
|
+
function LeafletViewportReporter({
|
|
1410
|
+
onViewportChange
|
|
1411
|
+
}: {
|
|
1412
|
+
onViewportChange?: (bounds: KivaMapBounds | null) => void;
|
|
1413
|
+
}) {
|
|
1414
|
+
const map = useLeafletMapEvents({
|
|
1415
|
+
moveend: () => {
|
|
1416
|
+
if (!onViewportChange) return;
|
|
1417
|
+
const b = map.getBounds();
|
|
1418
|
+
|
|
1419
|
+
onViewportChange({
|
|
1420
|
+
north: b.getNorth(),
|
|
1421
|
+
south: b.getSouth(),
|
|
1422
|
+
east: b.getEast(),
|
|
1423
|
+
west: b.getWest()
|
|
1424
|
+
});
|
|
1425
|
+
}
|
|
1426
|
+
});
|
|
1427
|
+
|
|
1428
|
+
return null;
|
|
1429
|
+
}
|
|
1430
|
+
|
|
1431
|
+
function GoogleViewportController({
|
|
1432
|
+
center,
|
|
1433
|
+
bounds,
|
|
1434
|
+
defaultZoom,
|
|
1435
|
+
focusedZoom,
|
|
1436
|
+
fitBoundsPadding
|
|
1437
|
+
}: {
|
|
1438
|
+
center: KivaMapPoint;
|
|
1439
|
+
bounds?: KivaMapBounds | null;
|
|
1440
|
+
defaultZoom: number;
|
|
1441
|
+
focusedZoom: number;
|
|
1442
|
+
fitBoundsPadding: number;
|
|
1443
|
+
}) {
|
|
1444
|
+
const map = useGoogleMap();
|
|
1445
|
+
const hasFittedRef = useRef(false);
|
|
1446
|
+
|
|
1447
|
+
useEffect(() => {
|
|
1448
|
+
if (!map || hasFittedRef.current) return;
|
|
1449
|
+
|
|
1450
|
+
if (!bounds) {
|
|
1451
|
+
map.panTo(center);
|
|
1452
|
+
map.setZoom(defaultZoom);
|
|
1453
|
+
|
|
1454
|
+
return;
|
|
1455
|
+
}
|
|
1456
|
+
|
|
1457
|
+
if (isSinglePointBounds(bounds)) {
|
|
1458
|
+
map.panTo(center);
|
|
1459
|
+
map.setZoom(focusedZoom);
|
|
1460
|
+
hasFittedRef.current = true;
|
|
1461
|
+
|
|
1462
|
+
return;
|
|
1463
|
+
}
|
|
1464
|
+
|
|
1465
|
+
map.fitBounds(bounds, fitBoundsPadding);
|
|
1466
|
+
hasFittedRef.current = true;
|
|
1467
|
+
}, [
|
|
1468
|
+
bounds,
|
|
1469
|
+
center,
|
|
1470
|
+
defaultZoom,
|
|
1471
|
+
fitBoundsPadding,
|
|
1472
|
+
focusedZoom,
|
|
1473
|
+
map
|
|
1474
|
+
]);
|
|
1475
|
+
|
|
1476
|
+
return null;
|
|
1477
|
+
}
|
|
1478
|
+
|
|
1479
|
+
function GoogleMarkerWithPopup<TData>({
|
|
1480
|
+
marker,
|
|
1481
|
+
selected,
|
|
1482
|
+
onSelectMarker,
|
|
1483
|
+
renderPopup,
|
|
1484
|
+
getMarkerIcon,
|
|
1485
|
+
draggable,
|
|
1486
|
+
onMarkerMove
|
|
1487
|
+
}: {
|
|
1488
|
+
marker: KivaMapMarker<TData>;
|
|
1489
|
+
selected: boolean;
|
|
1490
|
+
onSelectMarker?: (markerId: string | null) => void;
|
|
1491
|
+
renderPopup?: (marker: KivaMapMarker<TData>) => ReactNode;
|
|
1492
|
+
getMarkerIcon?: (marker: KivaMapMarker<TData>, isSelected: boolean) => string | KivaMapMarkerIcon | null;
|
|
1493
|
+
draggable?: boolean;
|
|
1494
|
+
onMarkerMove?: (
|
|
1495
|
+
marker: KivaMapMarker<TData>,
|
|
1496
|
+
newPosition: KivaMapPoint
|
|
1497
|
+
) => void | Promise<void>;
|
|
1498
|
+
}) {
|
|
1499
|
+
const [markerRef, markerInstance] = useMarkerRef();
|
|
1500
|
+
|
|
1501
|
+
const iconDescriptor = getMarkerIcon?.(marker, selected)
|
|
1502
|
+
?? (marker.imageUrl ? { url: marker.imageUrl, size: { width: 36, height: 36 } } : null)
|
|
1503
|
+
?? (marker.iconUrl ? { url: marker.iconUrl, size: { width: 28, height: 28 } } : null);
|
|
1504
|
+
|
|
1505
|
+
let googleIcon: any;
|
|
1506
|
+
|
|
1507
|
+
if (iconDescriptor) {
|
|
1508
|
+
const url = typeof iconDescriptor === 'string' ? iconDescriptor : iconDescriptor.url;
|
|
1509
|
+
const sz = typeof iconDescriptor !== 'string' && iconDescriptor.size && typeof window !== 'undefined' ? new (window as any).google.maps.Size(iconDescriptor.size.width, iconDescriptor.size.height) : undefined;
|
|
1510
|
+
|
|
1511
|
+
googleIcon = { url, scaledSize: sz };
|
|
1512
|
+
}
|
|
1513
|
+
|
|
1514
|
+
return (
|
|
1515
|
+
<>
|
|
1516
|
+
<Marker
|
|
1517
|
+
ref={markerRef}
|
|
1518
|
+
position={marker.position}
|
|
1519
|
+
icon={googleIcon}
|
|
1520
|
+
draggable={draggable}
|
|
1521
|
+
onDragEnd={(e) => {
|
|
1522
|
+
if (!onMarkerMove) return;
|
|
1523
|
+
const { latLng } = e;
|
|
1524
|
+
|
|
1525
|
+
if (!latLng) return;
|
|
1526
|
+
void onMarkerMove(marker, { lat: latLng.lat(), lng: latLng.lng() });
|
|
1527
|
+
}}
|
|
1528
|
+
onClick={() => onSelectMarker?.(marker.id)} />
|
|
1529
|
+
{selected && markerInstance ? (
|
|
1530
|
+
<InfoWindow
|
|
1531
|
+
anchor={markerInstance}
|
|
1532
|
+
onCloseClick={() => onSelectMarker?.(null)}>
|
|
1533
|
+
{renderPopup ? renderPopup(marker) : <DefaultKivaMapPopup marker={marker} />}
|
|
1534
|
+
</InfoWindow>
|
|
1535
|
+
) : null}
|
|
1536
|
+
</>
|
|
1537
|
+
);
|
|
1538
|
+
}
|
|
1539
|
+
|
|
1540
|
+
function BasemapPicker({
|
|
1541
|
+
basemaps,
|
|
1542
|
+
activeBasemap,
|
|
1543
|
+
onChange
|
|
1544
|
+
}: {
|
|
1545
|
+
basemaps?: Array<KivaBasemapDefinition>;
|
|
1546
|
+
activeBasemap: KivaBasemapDefinition | null;
|
|
1547
|
+
onChange?: (id: string) => void;
|
|
1548
|
+
}) {
|
|
1549
|
+
const [open, setOpen] = useState(false);
|
|
1550
|
+
|
|
1551
|
+
if (!basemaps || basemaps.length < 2 || !onChange) return null;
|
|
1552
|
+
|
|
1553
|
+
return (
|
|
1554
|
+
<div className="absolute bottom-2 left-2 z-[400]">
|
|
1555
|
+
<button
|
|
1556
|
+
type="button"
|
|
1557
|
+
onClick={() => setOpen(v => !v)}
|
|
1558
|
+
className="flex items-center gap-1.5 rounded-md border border-border bg-popover px-2 py-1.5 text-xs font-medium text-popover-foreground shadow-sm transition hover:bg-accent">
|
|
1559
|
+
<Layers className="size-3.5" />
|
|
1560
|
+
<span>{activeBasemap?.label ?? 'Basemap'}</span>
|
|
1561
|
+
</button>
|
|
1562
|
+
{open ? (
|
|
1563
|
+
<>
|
|
1564
|
+
<div
|
|
1565
|
+
className="fixed inset-0 z-[399]"
|
|
1566
|
+
onClick={() => setOpen(false)} />
|
|
1567
|
+
<div className="absolute bottom-full left-0 z-[401] mb-1.5 w-36 overflow-hidden rounded-md border border-border bg-popover shadow-md">
|
|
1568
|
+
{basemaps.map(b => (
|
|
1569
|
+
<button
|
|
1570
|
+
key={b.id}
|
|
1571
|
+
type="button"
|
|
1572
|
+
onClick={() => {
|
|
1573
|
+
onChange(b.id);
|
|
1574
|
+
setOpen(false);
|
|
1575
|
+
}}
|
|
1576
|
+
className={cn(
|
|
1577
|
+
'flex w-full items-center gap-2 px-2.5 py-1.5 text-left text-xs transition hover:bg-accent',
|
|
1578
|
+
b.id === activeBasemap?.id && 'bg-accent font-medium'
|
|
1579
|
+
)}>
|
|
1580
|
+
{b.label}
|
|
1581
|
+
</button>
|
|
1582
|
+
))}
|
|
1583
|
+
</div>
|
|
1584
|
+
</>
|
|
1585
|
+
) : null}
|
|
1586
|
+
</div>
|
|
1587
|
+
);
|
|
1588
|
+
}
|
|
1589
|
+
|
|
1590
|
+
function DefaultKivaMapPopup<TData>({
|
|
1591
|
+
marker,
|
|
1592
|
+
onEdit
|
|
1593
|
+
}: {
|
|
1594
|
+
marker: KivaMapMarker<TData>;
|
|
1595
|
+
onEdit?: () => void;
|
|
1596
|
+
}) {
|
|
1597
|
+
const secondaryText = marker.description
|
|
1598
|
+
?? marker.subtitle
|
|
1599
|
+
?? marker.address
|
|
1600
|
+
?? formatCoordinates(marker.position);
|
|
1601
|
+
|
|
1602
|
+
return (
|
|
1603
|
+
<div className="min-w-56 space-y-1.5">
|
|
1604
|
+
<div className="flex items-start justify-between gap-2">
|
|
1605
|
+
<p className="text-sm font-semibold text-foreground">{marker.title}</p>
|
|
1606
|
+
{onEdit ? (
|
|
1607
|
+
<button
|
|
1608
|
+
type="button"
|
|
1609
|
+
onClick={onEdit}
|
|
1610
|
+
className="shrink-0 rounded p-0.5 text-muted-foreground hover:bg-muted hover:text-foreground">
|
|
1611
|
+
<Pencil className="size-3.5" />
|
|
1612
|
+
</button>
|
|
1613
|
+
) : null}
|
|
1614
|
+
</div>
|
|
1615
|
+
{secondaryText ? (
|
|
1616
|
+
<p className="text-xs text-muted-foreground">{secondaryText}</p>
|
|
1617
|
+
) : null}
|
|
1618
|
+
</div>
|
|
1619
|
+
);
|
|
1620
|
+
}
|
|
1621
|
+
|
|
1622
|
+
function KivaMapEmptyState({
|
|
1623
|
+
children,
|
|
1624
|
+
className
|
|
1625
|
+
}: {
|
|
1626
|
+
children: ReactNode;
|
|
1627
|
+
className?: string;
|
|
1628
|
+
}) {
|
|
1629
|
+
return (
|
|
1630
|
+
<div
|
|
1631
|
+
className={cn(
|
|
1632
|
+
'flex h-[30rem] items-center justify-center rounded-xl border border-dashed bg-muted/20 px-6 text-center text-sm text-muted-foreground',
|
|
1633
|
+
className
|
|
1634
|
+
)}>
|
|
1635
|
+
<div className="max-w-xs text-balance">{children}</div>
|
|
1636
|
+
</div>
|
|
1637
|
+
);
|
|
1638
|
+
}
|
|
1639
|
+
|
|
1640
|
+
function resolveMarkers<TData>({
|
|
1641
|
+
items,
|
|
1642
|
+
locationField,
|
|
1643
|
+
titleField,
|
|
1644
|
+
descriptionFields,
|
|
1645
|
+
markerTemplate,
|
|
1646
|
+
markerImageFieldSlug,
|
|
1647
|
+
markerIconFieldSlug,
|
|
1648
|
+
markerIconColorFieldSlug,
|
|
1649
|
+
markerIconColor,
|
|
1650
|
+
markerPriority,
|
|
1651
|
+
getMarker
|
|
1652
|
+
}: {
|
|
1653
|
+
items: Array<TData>;
|
|
1654
|
+
locationField: DataSourceField | null;
|
|
1655
|
+
titleField: DataSourceField | null;
|
|
1656
|
+
descriptionFields: Array<DataSourceField>;
|
|
1657
|
+
markerTemplate?: string;
|
|
1658
|
+
markerImageFieldSlug?: string;
|
|
1659
|
+
markerIconFieldSlug?: string;
|
|
1660
|
+
markerIconColorFieldSlug?: string;
|
|
1661
|
+
markerIconColor?: string;
|
|
1662
|
+
markerPriority?: 'image' | 'icon';
|
|
1663
|
+
getMarker?: (
|
|
1664
|
+
item: TData,
|
|
1665
|
+
context: KivaMapMarkerBuilderContext<TData>
|
|
1666
|
+
) => KivaMapMarker<TData> | null;
|
|
1667
|
+
}): MarkerResolution<TData> {
|
|
1668
|
+
if (!locationField) {
|
|
1669
|
+
return {
|
|
1670
|
+
markers: [],
|
|
1671
|
+
mappedItems: [],
|
|
1672
|
+
unmappedItems: items
|
|
1673
|
+
};
|
|
1674
|
+
}
|
|
1675
|
+
|
|
1676
|
+
const markers: Array<KivaMapMarker<TData>> = [];
|
|
1677
|
+
const mappedItems: Array<TData> = [];
|
|
1678
|
+
const unmappedItems: Array<TData> = [];
|
|
1679
|
+
|
|
1680
|
+
items.forEach((item, index) => {
|
|
1681
|
+
const locationValue = readRecordValue(item, locationField.slug);
|
|
1682
|
+
const location = normalizeLocationValue(locationValue);
|
|
1683
|
+
|
|
1684
|
+
if (!location) {
|
|
1685
|
+
unmappedItems.push(item);
|
|
1686
|
+
|
|
1687
|
+
return;
|
|
1688
|
+
}
|
|
1689
|
+
|
|
1690
|
+
const context: KivaMapMarkerBuilderContext<TData> = {
|
|
1691
|
+
item,
|
|
1692
|
+
index,
|
|
1693
|
+
locationField,
|
|
1694
|
+
titleField,
|
|
1695
|
+
descriptionFields,
|
|
1696
|
+
location
|
|
1697
|
+
};
|
|
1698
|
+
|
|
1699
|
+
const marker = getMarker ? getMarker(item, context) : buildDefaultMarker(item, context, markerTemplate, markerImageFieldSlug, markerIconFieldSlug, markerIconColorFieldSlug, markerIconColor, markerPriority ?? 'image');
|
|
1700
|
+
|
|
1701
|
+
if (!marker) {
|
|
1702
|
+
unmappedItems.push(item);
|
|
1703
|
+
|
|
1704
|
+
return;
|
|
1705
|
+
}
|
|
1706
|
+
|
|
1707
|
+
markers.push(marker);
|
|
1708
|
+
mappedItems.push(item);
|
|
1709
|
+
});
|
|
1710
|
+
|
|
1711
|
+
return {
|
|
1712
|
+
markers,
|
|
1713
|
+
mappedItems,
|
|
1714
|
+
unmappedItems
|
|
1715
|
+
};
|
|
1716
|
+
}
|
|
1717
|
+
|
|
1718
|
+
function buildDefaultMarker<TData>(
|
|
1719
|
+
item: TData,
|
|
1720
|
+
context: KivaMapMarkerBuilderContext<TData>,
|
|
1721
|
+
markerTemplate?: string,
|
|
1722
|
+
markerImageFieldSlug?: string,
|
|
1723
|
+
markerIconFieldSlug?: string,
|
|
1724
|
+
markerIconColorFieldSlug?: string,
|
|
1725
|
+
markerIconColor?: string,
|
|
1726
|
+
markerPriority: 'image' | 'icon' = 'image'
|
|
1727
|
+
): KivaMapMarker<TData> {
|
|
1728
|
+
const itemRecord = item as Record<string, unknown>;
|
|
1729
|
+
const title = normalizeString(
|
|
1730
|
+
context.titleField ? stringifyValue(itemRecord[context.titleField.slug]) : undefined
|
|
1731
|
+
)
|
|
1732
|
+
?? normalizeString(context.location.description)
|
|
1733
|
+
?? normalizeString(context.location.address)
|
|
1734
|
+
?? `Record ${context.index + 1}`;
|
|
1735
|
+
|
|
1736
|
+
let description: string | null;
|
|
1737
|
+
|
|
1738
|
+
if (markerTemplate) {
|
|
1739
|
+
description = normalizeString(parseMarkerTemplate(markerTemplate, itemRecord));
|
|
1740
|
+
} else {
|
|
1741
|
+
const descParts = [context.location.details, ...context.descriptionFields.map(field => stringifyValue(itemRecord[field.slug]))];
|
|
1742
|
+
|
|
1743
|
+
description = joinNonEmpty(descParts);
|
|
1744
|
+
}
|
|
1745
|
+
|
|
1746
|
+
const address = normalizeString(context.location.address);
|
|
1747
|
+
const rawImageUrl = markerImageFieldSlug ? extractImageUrl(itemRecord[markerImageFieldSlug]) ?? undefined : undefined;
|
|
1748
|
+
const rawIconId = markerIconFieldSlug ? extractIconIdentifier(itemRecord[markerIconFieldSlug]) ?? undefined : undefined;
|
|
1749
|
+
const rawIconUrl = rawIconId ? buildKivaIconSvgUrl(rawIconId) : undefined;
|
|
1750
|
+
|
|
1751
|
+
let imageUrl: string | undefined;
|
|
1752
|
+
let iconUrl: string | undefined;
|
|
1753
|
+
|
|
1754
|
+
if (markerPriority === 'icon') {
|
|
1755
|
+
iconUrl = rawIconUrl;
|
|
1756
|
+
} else if (rawImageUrl) {
|
|
1757
|
+
imageUrl = rawImageUrl;
|
|
1758
|
+
} else {
|
|
1759
|
+
iconUrl = rawIconUrl;
|
|
1760
|
+
}
|
|
1761
|
+
|
|
1762
|
+
const rawColorValue = markerIconColorFieldSlug ? itemRecord[markerIconColorFieldSlug] : undefined;
|
|
1763
|
+
let colorString: string | undefined = markerIconColor;
|
|
1764
|
+
|
|
1765
|
+
if (typeof rawColorValue === 'string' && rawColorValue.trim().length > 0) {
|
|
1766
|
+
colorString = rawColorValue.trim();
|
|
1767
|
+
}
|
|
1768
|
+
const iconColor = iconUrl && colorString ? resolveColorHex(colorString) : undefined;
|
|
1769
|
+
|
|
1770
|
+
return {
|
|
1771
|
+
id: getMarkerId(itemRecord, context.index, context.location),
|
|
1772
|
+
title,
|
|
1773
|
+
subtitle: normalizeString(context.location.description) ?? undefined,
|
|
1774
|
+
description: description ?? address ?? undefined,
|
|
1775
|
+
address: address ?? undefined,
|
|
1776
|
+
imageUrl,
|
|
1777
|
+
iconUrl,
|
|
1778
|
+
iconColor,
|
|
1779
|
+
position: {
|
|
1780
|
+
lat: context.location.lat,
|
|
1781
|
+
lng: context.location.lng
|
|
1782
|
+
},
|
|
1783
|
+
location: context.location,
|
|
1784
|
+
item
|
|
1785
|
+
};
|
|
1786
|
+
}
|
|
1787
|
+
|
|
1788
|
+
function getMarkerId(
|
|
1789
|
+
item: Record<string, unknown>,
|
|
1790
|
+
index: number,
|
|
1791
|
+
location: KivaNormalizedLocation
|
|
1792
|
+
): string {
|
|
1793
|
+
const rawId = item.id;
|
|
1794
|
+
|
|
1795
|
+
if (typeof rawId === 'string' && rawId.length > 0) {
|
|
1796
|
+
return rawId;
|
|
1797
|
+
}
|
|
1798
|
+
|
|
1799
|
+
return `${index}-${location.lat}-${location.lng}`;
|
|
1800
|
+
}
|
|
1801
|
+
|
|
1802
|
+
function resolveLocationField(
|
|
1803
|
+
fields: Array<DataSourceField> | undefined,
|
|
1804
|
+
requestedSlug?: string
|
|
1805
|
+
): DataSourceField | null {
|
|
1806
|
+
if (!fields || fields.length === 0) {
|
|
1807
|
+
return null;
|
|
1808
|
+
}
|
|
1809
|
+
|
|
1810
|
+
if (requestedSlug) {
|
|
1811
|
+
return fields.find(field => field.slug === requestedSlug) ?? null;
|
|
1812
|
+
}
|
|
1813
|
+
|
|
1814
|
+
return fields.find(field => field.type === 'field-locationSelect') ?? null;
|
|
1815
|
+
}
|
|
1816
|
+
|
|
1817
|
+
function resolveIconField(
|
|
1818
|
+
fields: Array<DataSourceField> | undefined,
|
|
1819
|
+
requestedSlug: string | undefined
|
|
1820
|
+
): DataSourceField | null {
|
|
1821
|
+
if (!fields || fields.length === 0) return null;
|
|
1822
|
+
if (requestedSlug) return fields.find(field => field.slug === requestedSlug) ?? null;
|
|
1823
|
+
|
|
1824
|
+
return fields.find(field => field.type === 'field-icon')
|
|
1825
|
+
?? fields.find(field => field.slug === 'icon')
|
|
1826
|
+
?? null;
|
|
1827
|
+
}
|
|
1828
|
+
|
|
1829
|
+
function resolveTitleField(
|
|
1830
|
+
fields: Array<DataSourceField> | undefined,
|
|
1831
|
+
requestedSlug: string | undefined,
|
|
1832
|
+
locationFieldSlug: string | undefined
|
|
1833
|
+
): DataSourceField | null {
|
|
1834
|
+
if (!fields || fields.length === 0) {
|
|
1835
|
+
return null;
|
|
1836
|
+
}
|
|
1837
|
+
|
|
1838
|
+
if (requestedSlug) {
|
|
1839
|
+
return fields.find(field => field.slug === requestedSlug) ?? null;
|
|
1840
|
+
}
|
|
1841
|
+
|
|
1842
|
+
const excludedSlugs = new Set(['id', locationFieldSlug].filter(Boolean));
|
|
1843
|
+
|
|
1844
|
+
for (const candidate of TITLE_FIELD_CANDIDATES) {
|
|
1845
|
+
const match = fields.find(field => field.slug === candidate && !excludedSlugs.has(field.slug));
|
|
1846
|
+
|
|
1847
|
+
if (match) {
|
|
1848
|
+
return match;
|
|
1849
|
+
}
|
|
1850
|
+
}
|
|
1851
|
+
|
|
1852
|
+
return fields.find(
|
|
1853
|
+
field => TEXT_LIKE_FIELD_TYPES.has(field.type) && !excludedSlugs.has(field.slug)
|
|
1854
|
+
) ?? null;
|
|
1855
|
+
}
|
|
1856
|
+
|
|
1857
|
+
function resolveDescriptionFields(
|
|
1858
|
+
fields: Array<DataSourceField> | undefined,
|
|
1859
|
+
requestedSlugs: Array<string> | undefined,
|
|
1860
|
+
titleFieldSlug: string | undefined,
|
|
1861
|
+
locationFieldSlug: string | undefined
|
|
1862
|
+
): Array<DataSourceField> {
|
|
1863
|
+
if (!fields || fields.length === 0) {
|
|
1864
|
+
return [];
|
|
1865
|
+
}
|
|
1866
|
+
|
|
1867
|
+
const excludedSlugs = new Set(
|
|
1868
|
+
['id', titleFieldSlug, locationFieldSlug].filter(Boolean)
|
|
1869
|
+
);
|
|
1870
|
+
|
|
1871
|
+
const fieldMap = new globalThis.Map(fields.map(field => [field.slug, field]));
|
|
1872
|
+
|
|
1873
|
+
if (requestedSlugs && requestedSlugs.length > 0) {
|
|
1874
|
+
return requestedSlugs
|
|
1875
|
+
.map(slug => fieldMap.get(slug) ?? null)
|
|
1876
|
+
.filter(
|
|
1877
|
+
(field): field is DataSourceField => field !== null && !excludedSlugs.has(field.slug)
|
|
1878
|
+
);
|
|
1879
|
+
}
|
|
1880
|
+
|
|
1881
|
+
return DESCRIPTION_FIELD_CANDIDATES
|
|
1882
|
+
.map(slug => fieldMap.get(slug) ?? null)
|
|
1883
|
+
.filter(
|
|
1884
|
+
(field, index, source): field is DataSourceField => (
|
|
1885
|
+
field !== null
|
|
1886
|
+
&& !excludedSlugs.has(field.slug)
|
|
1887
|
+
&& source.findIndex(candidate => candidate?.slug === field.slug) === index
|
|
1888
|
+
)
|
|
1889
|
+
);
|
|
1890
|
+
}
|
|
1891
|
+
|
|
1892
|
+
function normalizeLocationValue(
|
|
1893
|
+
value: unknown
|
|
1894
|
+
): KivaNormalizedLocation | null {
|
|
1895
|
+
if (!value || typeof value !== 'object') {
|
|
1896
|
+
return null;
|
|
1897
|
+
}
|
|
1898
|
+
|
|
1899
|
+
const location = value as KivaLocationValue;
|
|
1900
|
+
const lat = parseCoordinate(location.lat ?? location.latitude);
|
|
1901
|
+
const lng = parseCoordinate(location.lng ?? location.longitude);
|
|
1902
|
+
|
|
1903
|
+
if (lat == null || lng == null) {
|
|
1904
|
+
return null;
|
|
1905
|
+
}
|
|
1906
|
+
|
|
1907
|
+
return {
|
|
1908
|
+
lat,
|
|
1909
|
+
lng,
|
|
1910
|
+
address: normalizeString(location.address),
|
|
1911
|
+
description: normalizeString(location.description),
|
|
1912
|
+
details: normalizeString(location.details),
|
|
1913
|
+
placeId: normalizeString(location.placeId)
|
|
1914
|
+
};
|
|
1915
|
+
}
|
|
1916
|
+
|
|
1917
|
+
function parseCoordinate(value: unknown): number | null {
|
|
1918
|
+
if (typeof value === 'number' && Number.isFinite(value)) {
|
|
1919
|
+
return value;
|
|
1920
|
+
}
|
|
1921
|
+
|
|
1922
|
+
if (typeof value === 'string' && value.trim() !== '') {
|
|
1923
|
+
const parsed = Number(value);
|
|
1924
|
+
|
|
1925
|
+
return Number.isFinite(parsed) ? parsed : null;
|
|
1926
|
+
}
|
|
1927
|
+
|
|
1928
|
+
return null;
|
|
1929
|
+
}
|
|
1930
|
+
|
|
1931
|
+
function stringifyValue(value: unknown): string | null {
|
|
1932
|
+
if (value == null) {
|
|
1933
|
+
return null;
|
|
1934
|
+
}
|
|
1935
|
+
|
|
1936
|
+
if (typeof value === 'string') {
|
|
1937
|
+
return normalizeString(value);
|
|
1938
|
+
}
|
|
1939
|
+
|
|
1940
|
+
if (typeof value === 'number' || typeof value === 'bigint') {
|
|
1941
|
+
return String(value);
|
|
1942
|
+
}
|
|
1943
|
+
|
|
1944
|
+
if (typeof value === 'boolean') {
|
|
1945
|
+
return value ? 'Yes' : 'No';
|
|
1946
|
+
}
|
|
1947
|
+
|
|
1948
|
+
if (Array.isArray(value)) {
|
|
1949
|
+
return joinNonEmpty(value.map(stringifyValue));
|
|
1950
|
+
}
|
|
1951
|
+
|
|
1952
|
+
if (typeof value === 'object') {
|
|
1953
|
+
const record = value as Record<string, unknown>;
|
|
1954
|
+
|
|
1955
|
+
for (const key of [
|
|
1956
|
+
'name',
|
|
1957
|
+
'label',
|
|
1958
|
+
'title',
|
|
1959
|
+
'description',
|
|
1960
|
+
'address',
|
|
1961
|
+
'value'
|
|
1962
|
+
]) {
|
|
1963
|
+
const resolved = stringifyValue(record[key]);
|
|
1964
|
+
|
|
1965
|
+
if (resolved) {
|
|
1966
|
+
return resolved;
|
|
1967
|
+
}
|
|
1968
|
+
}
|
|
1969
|
+
}
|
|
1970
|
+
|
|
1971
|
+
return null;
|
|
1972
|
+
}
|
|
1973
|
+
|
|
1974
|
+
function readRecordValue<TData>(item: TData, slug: string): unknown {
|
|
1975
|
+
return (item as Record<string, unknown>)[slug];
|
|
1976
|
+
}
|
|
1977
|
+
|
|
1978
|
+
function unwrapItems<TData>(
|
|
1979
|
+
value: Array<TData> | { data: Array<TData> } | unknown
|
|
1980
|
+
): Array<TData> {
|
|
1981
|
+
if (Array.isArray(value)) {
|
|
1982
|
+
return value;
|
|
1983
|
+
}
|
|
1984
|
+
|
|
1985
|
+
if (value && typeof value === 'object' && Array.isArray((value as { data?: unknown }).data)) {
|
|
1986
|
+
return (value as { data: Array<TData> }).data;
|
|
1987
|
+
}
|
|
1988
|
+
|
|
1989
|
+
return [];
|
|
1990
|
+
}
|
|
1991
|
+
|
|
1992
|
+
function boundsEqual(a: KivaMapBounds | null, b: KivaMapBounds | null): boolean {
|
|
1993
|
+
if (a === b) return true;
|
|
1994
|
+
if (!a || !b) return false;
|
|
1995
|
+
|
|
1996
|
+
return a.north === b.north && a.south === b.south && a.east === b.east && a.west === b.west;
|
|
1997
|
+
}
|
|
1998
|
+
|
|
1999
|
+
function isPointInBounds(point: KivaMapPoint, bounds: KivaMapBounds): boolean {
|
|
2000
|
+
if (point.lat < bounds.south || point.lat > bounds.north) return false;
|
|
2001
|
+
|
|
2002
|
+
if (bounds.west <= bounds.east) {
|
|
2003
|
+
return point.lng >= bounds.west && point.lng <= bounds.east;
|
|
2004
|
+
}
|
|
2005
|
+
|
|
2006
|
+
return point.lng >= bounds.west || point.lng <= bounds.east;
|
|
2007
|
+
}
|
|
2008
|
+
|
|
2009
|
+
function getBounds<TData>(markers: Array<KivaMapMarker<TData>>): KivaMapBounds | null {
|
|
2010
|
+
if (markers.length === 0) {
|
|
2011
|
+
return null;
|
|
2012
|
+
}
|
|
2013
|
+
|
|
2014
|
+
let north = markers[0]?.position.lat ?? 0;
|
|
2015
|
+
let south = north;
|
|
2016
|
+
let east = markers[0]?.position.lng ?? 0;
|
|
2017
|
+
let west = east;
|
|
2018
|
+
|
|
2019
|
+
markers.forEach((marker) => {
|
|
2020
|
+
north = Math.max(north, marker.position.lat);
|
|
2021
|
+
south = Math.min(south, marker.position.lat);
|
|
2022
|
+
east = Math.max(east, marker.position.lng);
|
|
2023
|
+
west = Math.min(west, marker.position.lng);
|
|
2024
|
+
});
|
|
2025
|
+
|
|
2026
|
+
return {
|
|
2027
|
+
north,
|
|
2028
|
+
south,
|
|
2029
|
+
east,
|
|
2030
|
+
west
|
|
2031
|
+
};
|
|
2032
|
+
}
|
|
2033
|
+
|
|
2034
|
+
function getCenter<TData>(
|
|
2035
|
+
bounds: KivaMapBounds | null,
|
|
2036
|
+
markers: Array<KivaMapMarker<TData>>,
|
|
2037
|
+
fallback: KivaMapPoint
|
|
2038
|
+
): KivaMapPoint {
|
|
2039
|
+
if (markers.length === 1) {
|
|
2040
|
+
return markers[0]?.position ?? fallback;
|
|
2041
|
+
}
|
|
2042
|
+
|
|
2043
|
+
if (!bounds) {
|
|
2044
|
+
return fallback;
|
|
2045
|
+
}
|
|
2046
|
+
|
|
2047
|
+
return {
|
|
2048
|
+
lat: (bounds.north + bounds.south) / 2,
|
|
2049
|
+
lng: (bounds.east + bounds.west) / 2
|
|
2050
|
+
};
|
|
2051
|
+
}
|
|
2052
|
+
|
|
2053
|
+
function isSinglePointBounds(bounds: KivaMapBounds): boolean {
|
|
2054
|
+
return bounds.north === bounds.south && bounds.east === bounds.west;
|
|
2055
|
+
}
|
|
2056
|
+
|
|
2057
|
+
function toLeafletPosition(point: KivaMapPoint): [number, number] {
|
|
2058
|
+
return [point.lat, point.lng];
|
|
2059
|
+
}
|
|
2060
|
+
|
|
2061
|
+
function formatCoordinates(point: KivaMapPoint): string {
|
|
2062
|
+
return `${point.lat.toFixed(6)}, ${point.lng.toFixed(6)}`;
|
|
2063
|
+
}
|
|
2064
|
+
|
|
2065
|
+
function extractTemplateSlugs(template: string): Array<string> {
|
|
2066
|
+
const matches = [...template.matchAll(/\{\{(\w+)\}\}/g)];
|
|
2067
|
+
|
|
2068
|
+
return [...new Set(matches.map(m => m[1]).filter(Boolean))] as Array<string>;
|
|
2069
|
+
}
|
|
2070
|
+
|
|
2071
|
+
function parseMarkerTemplate(template: string, item: Record<string, unknown>): string {
|
|
2072
|
+
return template.replace(/\{\{(\w+)\}\}/g, (_, slug: string) => stringifyValue(item[slug]) ?? '');
|
|
2073
|
+
}
|
|
2074
|
+
|
|
2075
|
+
const ICON_IDENTIFIER_KEYS = [
|
|
2076
|
+
'name',
|
|
2077
|
+
'value',
|
|
2078
|
+
'icon',
|
|
2079
|
+
'identifier'
|
|
2080
|
+
];
|
|
2081
|
+
|
|
2082
|
+
function extractIconIdentifier(value: unknown): string | null {
|
|
2083
|
+
if (typeof value === 'string' && value.trim().length > 0) return value.trim();
|
|
2084
|
+
|
|
2085
|
+
if (value && typeof value === 'object') {
|
|
2086
|
+
const rec = value as Record<string, unknown>;
|
|
2087
|
+
|
|
2088
|
+
for (const key of ICON_IDENTIFIER_KEYS) {
|
|
2089
|
+
const raw = rec[key];
|
|
2090
|
+
|
|
2091
|
+
if (typeof raw === 'string' && raw.trim().length > 0) return raw.trim();
|
|
2092
|
+
}
|
|
2093
|
+
}
|
|
2094
|
+
|
|
2095
|
+
return null;
|
|
2096
|
+
}
|
|
2097
|
+
|
|
2098
|
+
/**
|
|
2099
|
+
* Builds a Kiva icon SVG URL from a stored identifier such as
|
|
2100
|
+
* `"huge building-06"` or `"fal star"`. Mirrors the parsing logic used by
|
|
2101
|
+
* the `KivaIcon` component (`kiva-icon.tsx`).
|
|
2102
|
+
*/
|
|
2103
|
+
function buildKivaIconSvgUrl(identifier: string): string | undefined {
|
|
2104
|
+
const parts = identifier.trim().split(/\s+/).filter(Boolean);
|
|
2105
|
+
|
|
2106
|
+
if (parts.length === 0) return undefined;
|
|
2107
|
+
|
|
2108
|
+
let lib = 'kv';
|
|
2109
|
+
let group: string | null = null;
|
|
2110
|
+
let name = '';
|
|
2111
|
+
|
|
2112
|
+
if (parts.length === 1) {
|
|
2113
|
+
name = parts[0] ?? '';
|
|
2114
|
+
} else if (parts.length === 2) {
|
|
2115
|
+
lib = parts[0] ?? 'kv';
|
|
2116
|
+
name = parts[1] ?? '';
|
|
2117
|
+
} else {
|
|
2118
|
+
lib = parts[0] ?? 'kv';
|
|
2119
|
+
group = parts[1] ?? null;
|
|
2120
|
+
name = parts.slice(2).join('-');
|
|
2121
|
+
}
|
|
2122
|
+
|
|
2123
|
+
if (!name) return undefined;
|
|
2124
|
+
|
|
2125
|
+
const groupSegment = group ? `/${group}` : '';
|
|
2126
|
+
|
|
2127
|
+
return `https://static.kiva.app/assets/icons/${lib}${groupSegment}/${name}.svg`;
|
|
2128
|
+
}
|
|
2129
|
+
|
|
2130
|
+
function extractImageUrl(value: unknown): string | null {
|
|
2131
|
+
if (!value) return null;
|
|
2132
|
+
|
|
2133
|
+
if (typeof value === 'string' && (value.startsWith('http') || value.startsWith('/'))) {
|
|
2134
|
+
return value;
|
|
2135
|
+
}
|
|
2136
|
+
|
|
2137
|
+
if (Array.isArray(value) && value.length > 0) {
|
|
2138
|
+
return extractImageUrl(value[0]);
|
|
2139
|
+
}
|
|
2140
|
+
|
|
2141
|
+
if (typeof value === 'object') {
|
|
2142
|
+
const rec = value as Record<string, unknown>;
|
|
2143
|
+
|
|
2144
|
+
for (const key of ['signed_url', 'url', 'src']) {
|
|
2145
|
+
if (typeof rec[key] === 'string') return rec[key] as string;
|
|
2146
|
+
}
|
|
2147
|
+
}
|
|
2148
|
+
|
|
2149
|
+
return null;
|
|
2150
|
+
}
|
|
2151
|
+
|
|
2152
|
+
function joinNonEmpty(values: Array<string | null | undefined>): string | null {
|
|
2153
|
+
const parts = values
|
|
2154
|
+
.map(value => normalizeString(value))
|
|
2155
|
+
.filter((value): value is string => Boolean(value));
|
|
2156
|
+
|
|
2157
|
+
return parts.length > 0 ? parts.join(' · ') : null;
|
|
2158
|
+
}
|
|
2159
|
+
|
|
2160
|
+
function normalizeString(value: unknown): string | null {
|
|
2161
|
+
if (typeof value !== 'string') {
|
|
2162
|
+
return null;
|
|
2163
|
+
}
|
|
2164
|
+
|
|
2165
|
+
const normalized = value.trim();
|
|
2166
|
+
|
|
2167
|
+
return normalized.length > 0 ? normalized : null;
|
|
2168
|
+
}
|
|
2169
|
+
|
|
2170
|
+
export type KivaGoogleMapType = 'roadmap' | 'satellite' | 'hybrid' | 'terrain';
|
|
2171
|
+
|
|
2172
|
+
export type KivaBasemapId = 'street' | 'satellite' | 'hybrid' | 'terrain';
|
|
2173
|
+
|
|
2174
|
+
export interface KivaBasemapDefinition {
|
|
2175
|
+
id: string;
|
|
2176
|
+
label: string;
|
|
2177
|
+
/** Leaflet tile-server URL. Required for the Leaflet provider. */
|
|
2178
|
+
leafletUrl: string;
|
|
2179
|
+
/** Optional dark-mode variant for Leaflet. Falls back to `leafletUrl`. */
|
|
2180
|
+
leafletDarkUrl?: string;
|
|
2181
|
+
/** Attribution string injected into the Leaflet tile layer. */
|
|
2182
|
+
leafletAttribution?: string;
|
|
2183
|
+
/** Google Maps `mapTypeId`. Required for the Google provider. */
|
|
2184
|
+
googleMapType: KivaGoogleMapType;
|
|
2185
|
+
}
|
|
2186
|
+
|
|
2187
|
+
export const DEFAULT_KIVA_BASEMAPS: Record<KivaBasemapId, KivaBasemapDefinition> = {
|
|
2188
|
+
street: {
|
|
2189
|
+
id: 'street',
|
|
2190
|
+
label: 'Street',
|
|
2191
|
+
leafletUrl: 'https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png',
|
|
2192
|
+
leafletDarkUrl: 'https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}.png',
|
|
2193
|
+
leafletAttribution: '© <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>, © <a href="https://carto.com/attributions">CARTO</a>',
|
|
2194
|
+
googleMapType: 'roadmap'
|
|
2195
|
+
},
|
|
2196
|
+
satellite: {
|
|
2197
|
+
id: 'satellite',
|
|
2198
|
+
label: 'Satellite',
|
|
2199
|
+
leafletUrl: 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',
|
|
2200
|
+
leafletAttribution: 'Tiles © Esri — Source: Esri, Maxar, Earthstar Geographics',
|
|
2201
|
+
googleMapType: 'satellite'
|
|
2202
|
+
},
|
|
2203
|
+
hybrid: {
|
|
2204
|
+
id: 'hybrid',
|
|
2205
|
+
label: 'Hybrid',
|
|
2206
|
+
leafletUrl: 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',
|
|
2207
|
+
leafletAttribution: 'Tiles © Esri — Source: Esri, Maxar',
|
|
2208
|
+
googleMapType: 'hybrid'
|
|
2209
|
+
},
|
|
2210
|
+
terrain: {
|
|
2211
|
+
id: 'terrain',
|
|
2212
|
+
label: 'Terrain',
|
|
2213
|
+
leafletUrl: 'https://{s}.tile.opentopomap.org/{z}/{x}/{y}.png',
|
|
2214
|
+
leafletAttribution: 'Map data: © OpenStreetMap, SRTM | Style: © OpenTopoMap (CC-BY-SA)',
|
|
2215
|
+
googleMapType: 'terrain'
|
|
2216
|
+
}
|
|
2217
|
+
};
|
|
2218
|
+
|
|
2219
|
+
/**
|
|
2220
|
+
* Reverse-geocodes a coordinate pair into a human-readable address string.
|
|
2221
|
+
*
|
|
2222
|
+
* Uses the Google Maps Geocoder when `apiKey` is provided and
|
|
2223
|
+
* `window.google.maps` is available, otherwise falls back to the
|
|
2224
|
+
* OpenStreetMap Nominatim API (no key required).
|
|
2225
|
+
*/
|
|
2226
|
+
export async function reverseGeocode(
|
|
2227
|
+
lat: number,
|
|
2228
|
+
lng: number,
|
|
2229
|
+
apiKey?: string | null
|
|
2230
|
+
): Promise<string | null> {
|
|
2231
|
+
if (apiKey && typeof window !== 'undefined' && (window as any).google?.maps?.Geocoder) {
|
|
2232
|
+
return new Promise((resolve) => {
|
|
2233
|
+
const geocoder = new (window as any).google.maps.Geocoder();
|
|
2234
|
+
|
|
2235
|
+
geocoder.geocode(
|
|
2236
|
+
{ location: { lat, lng } },
|
|
2237
|
+
(results: Array<{ formatted_address: string }> | null, status: string) => {
|
|
2238
|
+
resolve(status === 'OK' && results?.[0] ? results[0].formatted_address : null);
|
|
2239
|
+
}
|
|
2240
|
+
);
|
|
2241
|
+
});
|
|
2242
|
+
}
|
|
2243
|
+
|
|
2244
|
+
try {
|
|
2245
|
+
const res = await fetch(
|
|
2246
|
+
`https://nominatim.openstreetmap.org/reverse?format=json&lat=${lat}&lon=${lng}`,
|
|
2247
|
+
{ headers: { 'Accept-Language': 'en' } }
|
|
2248
|
+
);
|
|
2249
|
+
const data = await res.json() as { display_name?: string };
|
|
2250
|
+
|
|
2251
|
+
return data?.display_name ?? null;
|
|
2252
|
+
} catch {
|
|
2253
|
+
return null;
|
|
2254
|
+
}
|
|
2255
|
+
}
|