merged in map-marker-customizations

This commit is contained in:
Kenneth Brewer 2026-05-06 01:10:40 -04:00
commit f5b881ac95
12 changed files with 692 additions and 355 deletions

View File

@ -164,33 +164,49 @@ export default class MapsController {
longitude: vine.number().min(-180).max(180),
latitude: vine.number().min(-90).max(90),
color: vine.string().trim().maxLength(20).optional(),
custom_color: vine.string().trim().maxLength(7).nullable().optional(),
icon: vine.string().trim().maxLength(50).nullable().optional(),
icon_color: vine.string().trim().maxLength(7).nullable().optional(),
visible: vine.boolean().optional(),
notes: vine.string().trim().nullable().optional(),
marker_type: vine.string().trim().maxLength(20).optional(),
})
)
)
const marker = await MapMarker.create({
name: payload.name,
longitude: payload.longitude,
latitude: payload.latitude,
color: payload.color ?? 'orange',
custom_color: payload.custom_color ?? null,
icon: payload.icon ?? null,
icon_color: payload.icon_color ?? null,
visible: payload.visible ?? true,
notes: payload.notes ?? null,
marker_type: payload.marker_type ?? 'pin',
})
return marker
}
async updateMarker({ request, response }: HttpContext) {
const { id } = request.params()
const marker = await MapMarker.find(id)
if (!marker) {
return response.status(404).send({ message: 'Marker not found' })
}
const payload = await request.validateUsing(
vine.compile(
vine.object({
name: vine.string().trim().minLength(1).maxLength(255).optional(),
color: vine.string().trim().maxLength(20).optional(),
custom_color: vine.string().trim().maxLength(7).nullable().optional(),
icon: vine.string().trim().maxLength(50).nullable().optional(),
icon_color: vine.string().trim().maxLength(7).nullable().optional(),
visible: vine.boolean().optional(),
longitude: vine.number().min(-180).max(180).optional(),
latitude: vine.number().min(-90).max(90).optional(),
notes: vine.string().trim().nullable().optional(),
@ -198,12 +214,18 @@ export default class MapsController {
})
)
)
if (payload.name !== undefined) marker.name = payload.name
if (payload.color !== undefined) marker.color = payload.color
if (payload.custom_color !== undefined) marker.custom_color = payload.custom_color
if (payload.icon !== undefined) marker.icon = payload.icon
if (payload.icon_color !== undefined) marker.icon_color = payload.icon_color
if (payload.visible !== undefined) marker.visible = payload.visible
if (payload.longitude !== undefined) marker.longitude = payload.longitude
if (payload.latitude !== undefined) marker.latitude = payload.latitude
if (payload.notes !== undefined) marker.notes = payload.notes
if (payload.marker_type !== undefined) marker.marker_type = payload.marker_type
await marker.save()
return marker
}

View File

@ -35,6 +35,18 @@ export default class MapMarker extends BaseModel {
@column()
declare notes: string | null
@column()
declare custom_color: string | null
@column()
declare icon: string | null
@column()
declare icon_color: string | null
@column()
declare visible: boolean
@column.dateTime({ autoCreate: true })
declare created_at: DateTime

View File

@ -9,7 +9,11 @@ export default class extends BaseSchema {
table.string('name').notNullable()
table.double('longitude').notNullable()
table.double('latitude').notNullable()
table.string('color', 20).notNullable().defaultTo('orange')
table.string('color', 20).notNullable().defaultTo('orange') // retaining this for backward compatibility
table.string('custom_color', 7).nullable() // "#aabbcc"
table.string('icon', 50).nullable() // "circle", "star", "flag", etc.
table.string('icon_color', 7).nullable()
table.boolean('visible').notNullable().defaultTo(true)
table.string('marker_type', 20).notNullable().defaultTo('pin')
table.string('route_id').nullable()
table.integer('route_order').nullable()

View File

@ -0,0 +1,23 @@
import { BaseSchema } from '@adonisjs/lucid/schema'
export default class AddVisibilityAndIconFieldsToMapMarkers extends BaseSchema {
protected tableName = 'map_markers'
async up() {
this.schema.alterTable(this.tableName, (table) => {
table.string('custom_color', 7).nullable()
table.string('icon', 50).nullable()
table.string('icon_color', 7).nullable()
table.boolean('visible').notNullable().defaultTo(true)
})
}
async down() {
this.schema.alterTable(this.tableName, (table) => {
table.dropColumn('custom_color')
table.dropColumn('icon')
table.dropColumn('icon_color')
table.dropColumn('visible')
})
}
}

View File

@ -0,0 +1,119 @@
import { useMemo, useState } from 'react'
import * as TablerIcons from '@tabler/icons-react'
import type { IconProps } from '@tabler/icons-react'
import type { ComponentType } from 'react'
const PAGE_SIZE = 48
type IconSelectorPopoverProps = {
selectedIcon?: string | null
onSelect: (iconName: string) => void
onClose: () => void
}
const iconEntries = Object.entries(TablerIcons)
.filter(([name, value]) => {
return (
name.startsWith('Icon') &&
name !== 'Icon' &&
value !== null &&
(typeof value === 'function' || typeof value === 'object')
)
})
.sort(([a], [b]) => a.localeCompare(b)) as Array<[string, ComponentType<IconProps>]>
export default function IconSelectorPopover({
selectedIcon,
onSelect,
onClose,
}: IconSelectorPopoverProps) {
const [query, setQuery] = useState('')
const [page, setPage] = useState(0)
const filteredIcons = useMemo(() => {
const normalizedQuery = query.trim().toLowerCase()
return iconEntries.filter(([name]) => name.toLowerCase().includes(normalizedQuery))
}, [query])
const pageCount = Math.max(1, Math.ceil(filteredIcons.length / PAGE_SIZE))
const pagedIcons = filteredIcons.slice(page * PAGE_SIZE, page * PAGE_SIZE + PAGE_SIZE)
return (
<div
className="absolute left-0 top-7 z-50 w-72 rounded-md border border-border-subtle bg-surface-primary p-2 shadow-lg"
onClick={(e) => e.stopPropagation()}
onMouseDown={(e) => e.stopPropagation()}
onPointerDown={(e) => e.stopPropagation()}
>
<input
autoFocus
type="search"
placeholder="Search icons..."
value={query}
onChange={(e) => {
setQuery(e.target.value)
setPage(0)
}}
className="mb-2 block w-full rounded border border-border-default bg-surface-primary px-2 py-1 text-sm text-text-primary placeholder:text-text-muted focus:border-desert-green focus:outline-none"
/>
<div className="max-h-56 overflow-y-auto themed-scrollbar">
<div className="grid grid-cols-6 gap-1">
{pagedIcons.map(([name, Icon]) => (
<button
key={name}
type="button"
title={name}
aria-label={name}
onClick={() => {
onSelect(name)
onClose()
}}
className={`flex h-8 w-8 items-center justify-center rounded transition-colors hover:bg-surface-secondary ${
selectedIcon === name ? 'bg-desert-green text-white' : 'text-text-secondary'
}`}
>
<Icon size={18} />
</button>
))}
</div>
</div>
<div className="mt-2 flex items-center justify-between gap-2">
<button
type="button"
onClick={() => setPage((prev) => Math.max(0, prev - 1))}
disabled={page === 0}
className="rounded bg-[#424420] px-2 py-1 text-xs text-white hover:bg-[#525530] disabled:opacity-40"
>
Prev
</button>
<span className="text-xs text-text-muted">
{filteredIcons.length === 0 ? 'No icons' : `${page + 1} / ${pageCount}`}
</span>
<button
type="button"
onClick={() => setPage((prev) => Math.min(pageCount - 1, prev + 1))}
disabled={page >= pageCount - 1}
className="rounded bg-[#424420] px-2 py-1 text-xs text-white hover:bg-[#525530] disabled:opacity-40"
>
Next
</button>
</div>
<div className="mt-2 flex justify-end">
<button
type="button"
onClick={onClose}
className="rounded bg-[#424420] px-2 py-1 text-xs text-white hover:bg-[#525530]"
>
Close
</button>
</div>
</div>
)
}

View File

@ -12,7 +12,6 @@ import 'maplibre-gl/dist/maplibre-gl.css'
import { Protocol } from 'pmtiles'
import { useCallback, useEffect, useRef, useState } from 'react'
import { useToast } from '~/hooks/useToast'
import { useMapMarkers } from '~/hooks/useMapMarkers'
import MarkerPin from './MarkerPin'
@ -21,7 +20,6 @@ import CoordinateOverlay from './CoordinateOverlay'
import ViewMapMarkerPopup from './ViewMapMarkerPopup'
import MapMarkerFormPopup from './MapMarkerFormPopup'
import ScaleUnitToggle from './ScaleUnitToggle'
import ToastContainer from '~/components/ToastContainer'
type ScaleUnit = 'imperial' | 'metric'
@ -100,7 +98,6 @@ export default function MapComponent({
const animationFrameRef = useRef<number | null>(null)
const handledMapCommandIdRef = useRef<number | null>(null)
const { toasts, showToast } = useToast()
const { markers, addMarker, updateMarker, deleteMarker } = useMapMarkers()
const [targetIndicator, setTargetIndicator] = useState<{ lng: number; lat: number } | null>(null)
@ -127,26 +124,6 @@ export default function MapComponent({
setCursorLngLat(null)
}, [])
const copyCoordinatesToClipboard = useCallback(
async (lat: number, lng: number) => {
const coordinates = `${lat.toFixed(6)},${lng.toFixed(6)}`
try {
await navigator.clipboard.writeText(coordinates)
showToast(`Copied: ${coordinates}`)
} catch {
window.prompt('Copy coordinates:', coordinates)
showToast('Clipboard blocked — copy manually')
}
},
[showToast]
)
const confirmDiscardMarkerChanges = useCallback(() => {
if (!hasUnsavedMarkerChanges) return true
return window.confirm('Discard unsaved marker changes?')
}, [hasUnsavedMarkerChanges])
const flyToLocationParams = useCallback(() => {
const location = getMapLocationParams()
if (!location) return
@ -158,6 +135,11 @@ export default function MapComponent({
})
}, [])
const confirmDiscardMarkerChanges = useCallback(() => {
if (!hasUnsavedMarkerChanges) return true
return window.confirm('Discard unsaved marker changes?')
}, [hasUnsavedMarkerChanges])
useEffect(() => {
const protocol = new Protocol()
maplibregl.addProtocol('pmtiles', protocol.tile)
@ -245,12 +227,7 @@ export default function MapComponent({
}, [flyToLocationParams])
const handleMapClick = useCallback(
async (e: MapLayerMouseEvent) => {
if (e.originalEvent.shiftKey) {
await copyCoordinatesToClipboard(e.lngLat.lat, e.lngLat.lng)
return
}
(e: MapLayerMouseEvent) => {
if (!confirmDiscardMarkerChanges()) return
setPlacingMarker({ lng: e.lngLat.lng, lat: e.lngLat.lat })
@ -259,7 +236,7 @@ export default function MapComponent({
setHasUnsavedMarkerChanges(false)
setTargetIndicator(null)
},
[confirmDiscardMarkerChanges, copyCoordinatesToClipboard]
[confirmDiscardMarkerChanges]
)
const handleMouseMove = useCallback(
@ -398,21 +375,16 @@ export default function MapComponent({
/>
{markers
.filter((marker) => marker.visible && isValidMarkerCoordinate(marker))
.filter((marker) => marker.visible)
.map((marker) => (
<Marker
key={marker.id}
longitude={marker.longitude}
latitude={marker.latitude}
anchor="bottom"
onClick={async (e) => {
onClick={(e) => {
e.originalEvent.stopPropagation()
if (e.originalEvent.shiftKey) {
await copyCoordinatesToClipboard(marker.latitude, marker.longitude)
return
}
if (!confirmDiscardMarkerChanges()) return
setSelectedMarkerId(marker.id === selectedMarkerId ? null : marker.id)
@ -439,7 +411,7 @@ export default function MapComponent({
latitude={placingMarker.lat}
onDirtyChange={setHasUnsavedMarkerChanges}
onMouseEnter={hideCoordinates}
onSave={async ({ name, notes, color, customColor, icon }) => {
onSave={async ({ name, notes, color, customColor, icon }) => {
await addMarker({
name,
longitude: placingMarker.lng,
@ -481,7 +453,7 @@ export default function MapComponent({
initialMarker={selectedMarker}
onDirtyChange={setHasUnsavedMarkerChanges}
onMouseEnter={hideCoordinates}
onSave={async ({ id, name, notes, color, customColor, icon }) => {
onSave={async ({ id, name, notes, color, customColor, icon }) => {
if (!id) return
await updateMarker(id, {
@ -516,8 +488,6 @@ export default function MapComponent({
onToggleVisibility={(id, visible) => updateMarker(id, { visible })}
/>
</div>
<ToastContainer toasts={toasts} />
</MapProvider>
)
}

View File

@ -1,177 +1,251 @@
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react'
import { Popup } from 'react-map-gl/maplibre'
import {useCallback, useEffect, useLayoutEffect, useRef, useState} from 'react'
import {Popup} from 'react-map-gl/maplibre'
import {IconPalette} from '@tabler/icons-react'
import { PIN_COLORS } from '~/hooks/useMapMarkers'
import type { MapMarker, PinColorId } from '~/hooks/useMapMarkers'
import {IconIcons} from '@tabler/icons-react'
import IconSelectorPopover from './IconSelectorPopover'
import {PIN_COLORS} from '~/hooks/useMapMarkers'
import type {MapMarker, PinColorId} from '~/hooks/useMapMarkers'
const MAX_MARKER_NOTES_LENGTH = 500
const inputClass =
'block w-full rounded border border-gray-300 bg-transparent px-2 py-1 text-sm text-gray-900 leading-normal placeholder:text-gray-400 focus:outline-none focus:border-gray-500'
'block w-full rounded border border-gray-300 bg-transparent px-2 py-1 text-sm text-gray-900 leading-normal placeholder:text-gray-400 focus:outline-none focus:border-gray-500'
type MapMarkerFormPopupProps = {
longitude: number
latitude: number
initialMarker?: MapMarker
onSave: (values: {
id?: number
name: string
notes: string
color: PinColorId
}) => Promise<void> | void
onCancel: () => void
onDirtyChange?: (dirty: boolean) => void
onMouseEnter?: () => void
longitude: number
latitude: number
initialMarker?: MapMarker
onSave: (values: {
id?: number
name: string
notes: string
color: PinColorId
customColor: string | null
icon: string | null
}) => Promise<void> | void
onCancel: () => void
onDirtyChange?: (dirty: boolean) => void
onMouseEnter?: () => void
}
export default function MapMarkerFormPopup({
longitude,
latitude,
initialMarker,
onSave,
onCancel,
onDirtyChange,
onMouseEnter,
longitude,
latitude,
initialMarker,
onSave,
onCancel,
onDirtyChange,
onMouseEnter,
}: MapMarkerFormPopupProps) {
const [name, setName] = useState(initialMarker?.name ?? '')
const [notes, setNotes] = useState(initialMarker?.notes ?? '')
const [color, setColor] = useState<PinColorId>(initialMarker?.color ?? 'orange')
const [isSaving, setIsSaving] = useState(false)
const [name, setName] = useState(initialMarker?.name ?? '')
const [notes, setNotes] = useState(initialMarker?.notes ?? '')
const [color, setColor] = useState<PinColorId>(initialMarker?.color ?? 'orange')
const [customColor, setCustomColor] = useState<string | null>(initialMarker?.customColor ?? null)
const [isSaving, setIsSaving] = useState(false)
const textareaRef = useRef<HTMLTextAreaElement | null>(null)
const textareaRef = useRef<HTMLTextAreaElement | null>(null)
const nameInputRef = useRef<HTMLInputElement | null>(null)
const colorInputRef = useRef<HTMLInputElement | null>(null)
const resizeTextarea = useCallback(() => {
const textarea = textareaRef.current
if (!textarea) return
const resizeTextarea = useCallback(() => {
const textarea = textareaRef.current
if (!textarea) return
textarea.style.height = 'auto'
textarea.style.height = `${textarea.scrollHeight}px`
}, [])
textarea.style.height = 'auto'
textarea.style.height = `${textarea.scrollHeight}px`
}, [])
useLayoutEffect(() => {
resizeTextarea()
}, [resizeTextarea])
const [icon, setIcon] = useState<string | null>(initialMarker?.icon ?? null)
const [showIconSelector, setShowIconSelector] = useState(false)
const nameInputRef = useRef<HTMLInputElement | null>(null)
useLayoutEffect(() => {
resizeTextarea()
}, [resizeTextarea])
useLayoutEffect(() => {
nameInputRef.current?.focus()
nameInputRef.current?.select()
}, [])
useLayoutEffect(() => {
nameInputRef.current?.focus()
nameInputRef.current?.select()
}, [])
const isDirty =
name !== (initialMarker?.name ?? '') ||
notes !== (initialMarker?.notes ?? '') ||
color !== (initialMarker?.color ?? 'orange')
const isDirty =
name !== (initialMarker?.name ?? '') ||
notes !== (initialMarker?.notes ?? '') ||
color !== (initialMarker?.color ?? 'orange') ||
customColor !== (initialMarker?.customColor ?? null) ||
icon !== (initialMarker?.icon ?? null)
useEffect(() => {
onDirtyChange?.(isDirty)
}, [isDirty, onDirtyChange])
useEffect(() => {
onDirtyChange?.(isDirty)
}, [isDirty, onDirtyChange])
const handleSave = async () => {
if (!name.trim() || isSaving) return
const handleSave = async () => {
if (!name.trim() || isSaving) return
try {
setIsSaving(true)
try {
setIsSaving(true)
await onSave({
id: initialMarker?.id,
name: name.trim(),
notes: notes.trim(),
color,
})
} finally {
setIsSaving(false)
await onSave({
id: initialMarker?.id,
name: name.trim(),
notes: notes.trim(),
color,
customColor,
icon,
})
} finally {
setIsSaving(false)
}
}
}
return (
<Popup
longitude={longitude}
latitude={latitude}
anchor="bottom"
offset={[0, -36] as [number, number]}
onClose={onCancel}
closeOnClick={false}
closeButton={false}
>
<div
className="p-1"
onClick={(e) => e.stopPropagation()}
onMouseDown={(e) => e.stopPropagation()}
onPointerDown={(e) => e.stopPropagation()}
onMouseEnter={onMouseEnter}
>
<input
ref={nameInputRef}
autoFocus
type="text"
placeholder="Name this location"
value={name}
onChange={(e) => setName(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') handleSave()
if (e.key === 'Escape') onCancel()
}}
className={inputClass}
/>
<textarea
ref={textareaRef}
placeholder="Add notes (optional)"
value={notes}
rows={2}
maxLength={MAX_MARKER_NOTES_LENGTH}
onChange={(e) => {
setNotes(e.target.value)
requestAnimationFrame(resizeTextarea)
}}
className={`mt-1 min-h-[64px] max-h-[240px] resize-none overflow-y-auto themed-scrollbar ${inputClass}`}
/>
<div className="mt-1 text-[11px] text-gray-400">
{notes.length}/{MAX_MARKER_NOTES_LENGTH}
</div>
<div className="mt-1.5 flex gap-1 items-center">
{PIN_COLORS.map((pinColor) => (
<button
key={pinColor.id}
type="button"
onClick={() => setColor(pinColor.id)}
title={pinColor.label}
className="rounded-full p-0.5 transition-transform"
style={{
outline:
color === pinColor.id ? `2px solid ${pinColor.hex}` : '2px solid transparent',
outlineOffset: '1px',
}}
return (
<Popup
longitude={longitude}
latitude={latitude}
anchor="bottom"
offset={[0, -36] as [number, number]}
onClose={onCancel}
closeOnClick={false}
closeButton={false}
>
<div
className="p-1"
onClick={(e) => e.stopPropagation()}
onMouseDown={(e) => e.stopPropagation()}
onPointerDown={(e) => e.stopPropagation()}
onMouseEnter={onMouseEnter}
>
<div className="w-4 h-4 rounded-full" style={{backgroundColor: pinColor.hex}}/>
</button>
))}
</div>
<input
ref={nameInputRef}
autoFocus
type="text"
placeholder="Name this location"
value={name}
onChange={(e) => setName(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') handleSave()
if (e.key === 'Escape') onCancel()
}}
className={inputClass}
/>
<div className="mt-1.5 flex gap-1.5 justify-end">
<button
type="button"
onClick={onCancel}
disabled={isSaving}
className="text-xs bg-[#424420] text-white rounded px-2.5 py-1 hover:bg-[#525530] disabled:opacity-40 transition-colors"
>
Cancel
</button>
<textarea
ref={textareaRef}
placeholder="Add notes (optional)"
value={notes}
rows={2}
maxLength={MAX_MARKER_NOTES_LENGTH}
onChange={(e) => {
setNotes(e.target.value)
requestAnimationFrame(resizeTextarea)
}}
className={`mt-1 min-h-[64px] max-h-[240px] resize-none overflow-y-auto themed-scrollbar ${inputClass}`}
/>
<button
type="button"
onClick={handleSave}
disabled={!name.trim() || isSaving}
className="text-xs bg-[#424420] text-white rounded px-2.5 py-1 hover:bg-[#525530] disabled:opacity-40 transition-colors"
>
{isSaving ? 'Saving...' : 'Save'}
</button>
</div>
</div>
</Popup>
)
<div className="mt-1 text-[11px] text-gray-400">
{notes.length}/{MAX_MARKER_NOTES_LENGTH}
</div>
<div className="mt-1.5 flex gap-1 items-center">
{PIN_COLORS.map((pinColor) => (
<button
key={pinColor.id}
type="button"
onClick={() => {
setColor(pinColor.id)
setCustomColor(null)
}}
title={pinColor.label}
className="rounded-full p-0.5 transition-transform"
style={{
outline:
!customColor && color === pinColor.id
? `2px solid ${pinColor.hex}`
: '2px solid transparent',
outlineOffset: '1px',
}}
>
<div className="w-4 h-4 rounded-full" style={{backgroundColor: pinColor.hex}}/>
</button>
))}
<button
type="button"
title="Choose custom marker color"
aria-label="Choose custom marker color"
onClick={() => colorInputRef.current?.click()}
className="rounded-full p-0.5 transition-transform"
style={{
outline: customColor ? `2px solid ${customColor}` : '2px solid transparent',
outlineOffset: '1px',
}}
>
<span
className="flex h-5 w-5 items-center justify-center rounded-full border border-border-default"
style={{backgroundColor: customColor ?? '#424420'}}
>
<IconPalette size={16} fill="currentColor" stroke={1.5} className="text-white"/>
</span>
</button>
<div className="relative">
<button
type="button"
title="Choose custom marker icon"
aria-label="Choose custom marker icon"
onClick={() => setShowIconSelector((prev) => !prev)}
className="rounded-full p-0.5 transition-transform"
style={{
outline: icon ? '2px solid #424420' : '2px solid transparent',
outlineOffset: '1px',
}}
>
<span
className="flex h-5 w-5 items-center justify-center rounded-full border border-border-default bg-[#424420] text-white">
<IconIcons size={16} fill="currentColor" stroke={1.5}/>
</span>
</button>
{showIconSelector && (
<IconSelectorPopover
selectedIcon={icon}
onSelect={setIcon}
onClose={() => setShowIconSelector(false)}
/>
)}
</div>
<input
ref={colorInputRef}
type="color"
value={customColor ?? '#a84a12'}
onChange={(e) => setCustomColor(e.target.value)}
className="sr-only"
aria-label="Choose custom marker color"
/>
</div>
<div className="mt-1.5 flex gap-1.5 justify-end">
<button
type="button"
onClick={onCancel}
disabled={isSaving}
className="text-xs bg-[#424420] text-white rounded px-2.5 py-1 hover:bg-[#525530] disabled:opacity-40 transition-colors"
>
Cancel
</button>
<button
type="button"
onClick={handleSave}
disabled={!name.trim() || isSaving}
className="text-xs bg-[#424420] text-white rounded px-2.5 py-1 hover:bg-[#525530] disabled:opacity-40 transition-colors"
>
{isSaving ? 'Saving...' : 'Save'}
</button>
</div>
</div>
</Popup>
)
}

View File

@ -1,6 +1,15 @@
import { useMemo, useState } from 'react'
import { IconMapPinFilled, IconTrash, IconMapPin, IconX } from '@tabler/icons-react'
import {
IconEye,
IconEyeOff,
IconMapPin,
IconMapPinFilled,
IconTrash,
IconX,
} from '@tabler/icons-react'
import * as TablerIcons from '@tabler/icons-react'
import type { IconProps } from '@tabler/icons-react'
import type { ComponentType } from 'react'
import { PIN_COLORS } from '~/hooks/useMapMarkers'
import type { MapMarker } from '~/hooks/useMapMarkers'
@ -9,21 +18,23 @@ interface MarkerPanelProps {
onDelete: (id: number) => void
onFlyTo: (longitude: number, latitude: number) => void
onSelect: (id: number | null) => void
onToggleVisibility: (id: number, visible: boolean) => void
selectedMarkerId: number | null
}
type SortField = 'name' | 'color'
type SortField = 'name' | 'color' | 'visibility' | 'icon'
type SortDirection = 'asc' | 'desc'
const normalizeColorHex = (color: string) => {
const normalizeColorHex = (color: string, customColor?: string | null) => {
if (customColor) return customColor
const preset = PIN_COLORS.find((pinColor) => pinColor.id === color)
return preset?.hex ?? color
}
const getColorSortValue = (color: string) => {
const hex = normalizeColorHex(color).replace('#', '')
const getColorSortValue = (color: string, customColor?: string | null) => {
const hex = normalizeColorHex(color, customColor).replace('#', '')
// Invalid/custom non-hex colors sort after valid colors
if (!/^[0-9a-fA-F]{6}$/.test(hex)) {
return { bucket: 2, hue: 0, lightness: 0 }
}
@ -37,7 +48,6 @@ const getColorSortValue = (color: string) => {
const delta = max - min
const lightness = (max + min) / 2
// Grayscale colors sort separately before hue colors, by lightness
if (delta === 0) {
return { bucket: 0, hue: 0, lightness }
}
@ -59,11 +69,20 @@ const getColorSortValue = (color: string) => {
}
}
const resolveMarkerIcon = (icon?: string | null): ComponentType<IconProps> => {
if (!icon) return IconMapPinFilled
const Icon = (TablerIcons as Record<string, unknown>)[icon]
return Icon ? (Icon as ComponentType<IconProps>) : IconMapPinFilled
}
export default function MarkerPanel({
markers,
onDelete,
onFlyTo,
onSelect,
onToggleVisibility,
selectedMarkerId,
}: MarkerPanelProps) {
const [open, setOpen] = useState(false)
@ -76,9 +95,17 @@ export default function MarkerPanel({
? sortDirection === 'asc'
? 'A → Z'
: 'Z → A'
: sortDirection === 'asc'
? 'Hue ↑'
: 'Hue ↓'
: sortField === 'color'
? sortDirection === 'asc'
? 'Hue ↑'
: 'Hue ↓'
: sortField === 'icon'
? sortDirection === 'asc'
? 'A → Z'
: 'Z → A'
: sortDirection === 'asc'
? 'Hidden first'
: 'Visible first'
const visibleMarkers = useMemo(() => {
const query = searchQuery.trim().toLowerCase()
@ -92,16 +119,24 @@ export default function MarkerPanel({
const result =
sortField === 'name'
? a.name.localeCompare(b.name, undefined, { sensitivity: 'base' })
: (() => {
const aColor = getColorSortValue(a.color)
const bColor = getColorSortValue(b.color)
return (
aColor.bucket - bColor.bucket ||
aColor.hue - bColor.hue ||
aColor.lightness - bColor.lightness
)
})()
: sortField === 'visibility'
? Number(a.visible) - Number(b.visible)
: sortField === 'icon'
? (a.icon ? 1 : 0) - (b.icon ? 1 : 0) ||
(a.icon ?? '').localeCompare(b.icon ?? '')
: (() => {
const aColor = getColorSortValue(a.color, a.customColor)
const bColor = getColorSortValue(b.color, b.customColor)
return (
aColor.bucket - bColor.bucket ||
aColor.hue - bColor.hue ||
aColor.lightness - bColor.lightness
)
})()
return sortDirection === 'asc' ? result : -result
})
@ -169,6 +204,8 @@ export default function MarkerPanel({
>
<option value="name">Sort by name</option>
<option value="color">Sort by hue</option>
<option value="icon">Sort by icon</option>
<option value="visibility">Sort by visibility</option>
</select>
<button
@ -193,45 +230,60 @@ export default function MarkerPanel({
</div>
) : (
<ul>
{visibleMarkers.map((marker) => (
<li
key={marker.id}
className={`group flex items-center gap-2 border-b border-border-subtle px-3 py-2 transition-colors last:border-b-0 ${
marker.id === selectedMarkerId
? 'bg-desert-green/10'
: 'hover:bg-surface-secondary'
}`}
>
<IconMapPinFilled
size={16}
className="shrink-0"
style={{
color: normalizeColorHex(marker.color),
}}
/>
{visibleMarkers.map((marker) => {
const MarkerIcon = resolveMarkerIcon(marker.icon)
<button
type="button"
onClick={() => {
onSelect(marker.id)
onFlyTo(marker.longitude, marker.latitude)
}}
className="min-w-0 flex-1 text-left"
title={marker.name}
return (
<li
key={marker.id}
className={`group flex items-center gap-2 border-b border-border-subtle px-3 py-2 transition-colors last:border-b-0 ${
marker.id === selectedMarkerId ? 'bg-desert-green/10' : 'hover:bg-surface-secondary'
} ${marker.visible ? '' : 'opacity-60'}`}
>
<p className="truncate text-sm font-medium text-text-primary">{marker.name}</p>
</button>
<MarkerIcon
size={16}
className="shrink-0"
style={{
color: normalizeColorHex(marker.color, marker.customColor),
}}
/>
<button
type="button"
onClick={() => onDelete(marker.id)}
className="shrink-0 rounded p-1 text-text-muted opacity-0 transition-all hover:bg-surface-secondary hover:text-desert-red group-hover:opacity-100"
title="Delete pin"
>
<IconTrash size={14} />
</button>
</li>
))}
<button
type="button"
onClick={() => {
onSelect(marker.id)
onFlyTo(marker.longitude, marker.latitude)
}}
className="min-w-0 flex-1 text-left"
title={marker.name}
>
<p className="truncate text-sm font-medium text-text-primary">{marker.name}</p>
</button>
<button
type="button"
onClick={(event) => {
event.stopPropagation()
onToggleVisibility(marker.id, !marker.visible)
}}
className="shrink-0 rounded p-1 text-text-muted transition-colors hover:bg-surface-secondary hover:text-text-primary"
title={marker.visible ? 'Hide pin' : 'Show pin'}
aria-label={marker.visible ? 'Hide pin' : 'Show pin'}
>
{marker.visible ? <IconEye size={14}/> : <IconEyeOff size={14}/>}
</button>
<button
type="button"
onClick={() => onDelete(marker.id)}
className="shrink-0 rounded p-1 text-text-muted opacity-0 transition-all hover:bg-surface-secondary hover:text-desert-red group-hover:opacity-100"
title="Delete pin"
>
<IconTrash size={14}/>
</button>
</li>
)
})}
</ul>
)}
</div>

View File

@ -1,33 +1,78 @@
import {IconCircleFilled} from '@tabler/icons-react'
import type { ComponentType, CSSProperties } from 'react'
import { IconCircleFilled } from '@tabler/icons-react'
import * as TablerIcons from '@tabler/icons-react'
import type { IconProps } from '@tabler/icons-react'
import type { ComponentType } from 'react'
type MarkerIconProps = {
size?: number
color?: string
style?: CSSProperties
className?: string
}
import { PIN_COLORS } from '~/hooks/useMapMarkers'
import type { PinColorId } from '~/hooks/useMapMarkers'
interface MarkerPinProps {
color?: string
color?: PinColorId | string | null
customColor?: string | null
icon?: string | null
iconColor?: string | null
visible?: boolean
active?: boolean
Icon?: ComponentType<MarkerIconProps>
iconColor?: string
}
const resolvePinColor = (color?: PinColorId | string | null, customColor?: string | null) => {
if (customColor) return customColor
if (!color) return '#a84a12'
const preset = PIN_COLORS.find((pinColor) => pinColor.id === color)
return preset?.hex ?? color
}
const getContrastingIconColor = (backgroundColor: string) => {
const hex = backgroundColor.replace('#', '')
if (!/^[0-9a-fA-F]{6}$/.test(hex)) {
return '#ffffff'
}
const r = parseInt(hex.slice(0, 2), 16) / 255
const g = parseInt(hex.slice(2, 4), 16) / 255
const b = parseInt(hex.slice(4, 6), 16) / 255
const luminance =
0.2126 * r +
0.7152 * g +
0.0722 * b
return luminance > 0.55 ? '#111827' : '#ffffff'
}
const resolveIcon = (icon?: string | null): ComponentType<IconProps> => {
if (!icon) return IconCircleFilled
const Icon = (TablerIcons as Record<string, unknown>)[icon]
if (!Icon) return IconCircleFilled
return Icon as ComponentType<IconProps>
}
export default function MarkerPin({
color = '#a84a12',
color = 'orange',
customColor,
icon,
iconColor,
visible = true,
active = false,
Icon = IconCircleFilled,
iconColor = '#ffffff',
}: MarkerPinProps) {
if (!visible) return null
const resolvedColor = resolvePinColor(color, customColor)
const resolvedIconColor = iconColor ?? getContrastingIconColor(resolvedColor)
const Icon = resolveIcon(icon)
const width = active ? 42 : 36
const height = active ? 52 : 46
const iconSize = active ? 18 : 16
return (
<div
className="cursor-pointer"
className="relative cursor-pointer"
style={{
width,
height,
@ -42,15 +87,13 @@ export default function MarkerPin({
xmlns="http://www.w3.org/2000/svg"
aria-hidden="true"
>
{/* Pin body: circular head + precise pointed tip */}
<path
d="M18 45 C18 45 4 27.5 4 16.5 C4 7.4 10.3 1 18 1 C25.7 1 32 7.4 32 16.5 C32 27.5 18 45 18 45 Z"
fill={color}
fill={resolvedColor}
stroke="rgba(0,0,0,0.25)"
strokeWidth="1.5"
/>
{/* Inner icon circle */}
<circle cx="18" cy="16.5" r="10.5" fill="rgba(255,255,255,0.18)" />
</svg>
@ -64,9 +107,8 @@ export default function MarkerPin({
height: iconSize,
}}
>
<Icon size={iconSize} color={iconColor} />
<Icon size={iconSize} color={resolvedIconColor} />
</div>
</div>
)
}

View File

@ -1,6 +1,8 @@
// eslint-disable-next-line @unicorn/filename-case
import { useState, useCallback, useEffect } from 'react'
import { useCallback, useEffect, useState } from 'react'
import api from '~/lib/api'
import type { MapMarkerResponse } from '../../types/maps'
export const PIN_COLORS = [
{ id: 'orange', label: 'Orange', hex: '#a84a12' },
@ -11,7 +13,9 @@ export const PIN_COLORS = [
{ id: 'yellow', label: 'Yellow', hex: '#ca8a04' },
] as const
export type PinColorId = typeof PIN_COLORS[number]['id']
export type PinColorId = (typeof PIN_COLORS)[number]['id']
export type MarkerIcon = 'pin' | 'circle' | 'star'
export interface MapMarker {
id: number
@ -19,10 +23,52 @@ export interface MapMarker {
longitude: number
latitude: number
color: PinColorId
customColor?: string | null
icon?: MarkerIcon | string | null
iconColor?: string | null
visible: boolean
notes?: string | null
createdAt: string
updatedAt?: string
}
type CreateMapMarkerValues = {
name: string
longitude: number
latitude: number
color?: PinColorId
customColor?: string | null
icon?: MarkerIcon | string | null
iconColor?: string | null
visible?: boolean
notes?: string | null
}
type UpdateMapMarkerValues = {
name?: string
color?: PinColorId
customColor?: string | null
icon?: MarkerIcon | string | null
iconColor?: string | null
visible?: boolean
notes?: string | null
}
const mapMarkerResponse = (marker: MapMarkerResponse): MapMarker => ({
id: marker.id,
name: marker.name,
longitude: marker.longitude,
latitude: marker.latitude,
color: marker.color as PinColorId,
customColor: marker.custom_color ?? null,
icon: marker.icon ?? null,
iconColor: marker.icon_color ?? null,
visible: marker.visible ?? true,
notes: marker.notes ?? null,
createdAt: marker.created_at,
updatedAt: marker.updated_at,
})
export function useMapMarkers() {
const [markers, setMarkers] = useState<MapMarker[]>([])
const [loaded, setLoaded] = useState(false)
@ -31,91 +77,58 @@ export function useMapMarkers() {
useEffect(() => {
api.listMapMarkers().then((data) => {
if (data) {
setMarkers(
data.map((m) => ({
id: m.id,
name: m.name,
longitude: m.longitude,
latitude: m.latitude,
color: m.color as PinColorId,
notes: m.notes ?? null,
createdAt: m.created_at,
}))
)
setMarkers(data.map(mapMarkerResponse))
}
setLoaded(true)
})
}, [])
const addMarker = useCallback(
async (
name: string,
longitude: number,
latitude: number,
color: PinColorId = 'orange',
notes?: string
) => {
const result = await api.createMapMarker({
name,
longitude,
latitude,
color,
notes,
})
const addMarker = useCallback(async (values: CreateMapMarkerValues) => {
const result = await api.createMapMarker({
name: values.name,
longitude: values.longitude,
latitude: values.latitude,
color: values.color ?? 'orange',
custom_color: values.customColor ?? null,
icon: values.icon ?? null,
icon_color: values.iconColor ?? null,
visible: values.visible ?? true,
notes: values.notes ?? null,
})
if (result) {
const marker: MapMarker = {
id: result.id,
name: result.name,
longitude: result.longitude,
latitude: result.latitude,
color: result.color as PinColorId,
notes: result.notes ?? null,
createdAt: result.created_at,
}
if (result) {
const marker = mapMarkerResponse(result)
setMarkers((prev) => [...prev, marker])
return marker
}
setMarkers((prev) => [...prev, marker])
return marker
}
return null
}, [])
return null
},
[]
)
const updateMarker = useCallback(async (id: number, updates: UpdateMapMarkerValues) => {
const result = await api.updateMapMarker(id, {
name: updates.name,
color: updates.color,
custom_color: updates.customColor,
icon: updates.icon,
icon_color: updates.iconColor,
visible: updates.visible,
notes: updates.notes,
})
const updateMarker = useCallback(
async (
id: number,
updates: {
name?: string
color?: string
notes?: string | null
}
) => {
const result = await api.updateMapMarker(id, updates)
if (result) {
const marker = mapMarkerResponse(result)
if (result) {
setMarkers((prev) =>
prev.map((m) =>
m.id === id
? {
...m,
name: result.name,
color: result.color as PinColorId,
notes: result.notes ?? null,
}
: m
)
)
}
},
[]
)
setMarkers((prev) =>
prev.map((existingMarker) => (existingMarker.id === id ? marker : existingMarker))
)
}
}, [])
const deleteMarker = useCallback(async (id: number) => {
await api.deleteMapMarker(id)
setMarkers((prev) => prev.filter((m) => m.id !== id))
setMarkers((prev) => prev.filter((marker) => marker.id !== id))
}, [])
return { markers, loaded, addMarker, updateMarker, deleteMarker }

View File

@ -11,7 +11,7 @@ import { catchInternal } from './util'
import { NomadChatResponse, NomadInstalledModel, NomadOllamaModel, OllamaChatRequest } from '../../types/ollama'
import BenchmarkResult from '#models/benchmark_result'
import { BenchmarkType, RunBenchmarkResponse, SubmitBenchmarkResponse, UpdateBuilderTagResponse } from '../../types/benchmark'
import type { MapMarkerResponse } from '../../types/maps'
import type {CreateMapMarkerPayload, MapMarkerResponse, UpdateMapMarkerPayload} from '../../types/maps'
class API {
private client: AxiosInstance
@ -636,23 +636,14 @@ class API {
})()
}
async createMapMarker(data: {
name: string
notes?: string | null
longitude: number
latitude: number
color?: string
}) {
async createMapMarker(data: CreateMapMarkerPayload) {
return catchInternal(async () => {
const response = await this.client.post<MapMarkerResponse>('/maps/markers', data)
return response.data
})()
}
async updateMapMarker(
id: number,
data: { name?: string; notes?: string | null; color?: string }
) {
async updateMapMarker(id: number, data: UpdateMapMarkerPayload) {
return catchInternal(async () => {
const response = await this.client.patch<MapMarkerResponse>(`/maps/markers/${id}`, data)
return response.data

View File

@ -56,16 +56,31 @@ export type MapExtractPreflight = {
}
}
export type CreateMapMarkerPayload = {
name: string
notes?: string | null
longitude: number
latitude: number
color?: string
custom_color?: string | null
icon?: string | null
icon_color?: string | null
visible?: boolean
}
export type UpdateMapMarkerPayload = Partial<CreateMapMarkerPayload>
export type MapMarkerResponse = {
id: number
name: string
longitude: number
latitude: number
color: string
custom_color?: string | null
icon?: string | null
icon_color?: string | null
visible?: boolean
notes?: string | null
marker_type?: string
route_id?: string | null
route_order?: number | null
created_at: string
updated_at?: string
}