diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 00000000..4d5c99eb --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,18 @@ +# Changelog + +## 2026-09-12 + +- Make screenshot comparisons opt-in and check keyboard reachability without requiring an exact Tab sequence, keeping functional and accessibility checks in CI. +- Changed personal notes and marker edits to save only with Save, preserving recoverable drafts without interrupting typing. +- Aligned personal marker actions with Delete on the left and Save consistently on the right in both note forms, and removed coordinates from the marker card header. +- Show personal marker squares and names from zoom level 2 onward, hiding both below level 2, and limit new or renamed markers to 100 characters. +- Add a copy-link action beside place names, centering shared links on the place at the current zoom and highlighting the selected place with a larger cyan marker and matching label. +- Use a pointer cursor for the copy-link action and dismiss its success or error message after five seconds with a fade-out. +- Raise hovered and selected place labels above other map labels. Show a 30%-transparent background only while hovering the label text or place square, excluding background padding from hover and click targets. +- Extend map zoom to z9 using existing tiles, preserving zoom levels through z8 and adding one 2× magnification step for crowded locations without rerendering maps. Always show all place labels from z8 onward, including overlapping labels. +- Snap map zoom to whole levels after clicks, taps, wheel and pinch gestures, reaching z9 consistently and opening fractional-zoom links at the nearest available scale. +- Hide Filters and Map section controls on compact layouts up to 860px and devices with a primary coarse pointer and no hover, including landscape phones and tablets. +- Add Map settings beside Import/Export with a saved colorblind-friendly status palette based on Okabe–Ito blue and orange. Apply it immediately to markers, labels, results, legends and place cards. +- Add distinct shapes in colorblind-friendly mode: white squares for unvisited places, blue diamonds for active places, orange circles for visited places, and reddish-purple triangles for personal markers, including their labels and previews. +- Give personal marker labels the same translucent hover background and text-only hit bounds as place labels. Keep marker sizes unchanged on hover and show Saved feedback only for note edits, without flicker when changing place status. +- Dismiss the JSON backup download confirmation after five seconds with a fade-out, restarting the timeout on each successful export. diff --git a/apps/web/src/i18n.ts b/apps/web/src/i18n.ts index 5423396a..1598b04b 100644 --- a/apps/web/src/i18n.ts +++ b/apps/web/src/i18n.ts @@ -62,6 +62,9 @@ const resources = { deleteMarker: 'Delete marker', closeMarker: 'Close personal marker card', closeCard: 'Close place card', + copyPlaceLink: 'Copy link to this place', + placeLinkCopied: 'Link copied.', + placeLinkCopyFailed: 'Could not copy the link. Try again.', zoom: 'Map zoom', }, placeType: { diff --git a/apps/web/src/map/DatasetMap.tsx b/apps/web/src/map/DatasetMap.tsx index 9c91f77d..4feea92e 100644 --- a/apps/web/src/map/DatasetMap.tsx +++ b/apps/web/src/map/DatasetMap.tsx @@ -17,7 +17,7 @@ import { type ProgressRecord, type ProgressStatus, } from '@morrowind-map/contracts'; -import Feature from 'ol/Feature.js'; +import Feature, { type FeatureLike } from 'ol/Feature.js'; import Map from 'ol/Map.js'; import View from 'ol/View.js'; import Point from 'ol/geom/Point.js'; @@ -53,11 +53,12 @@ import { } from '../data/placeFilters'; import { buildPlaceViews, PlaceSearch, type PlaceView } from '../data/placeSearch'; import { presentDataset } from '../data/datasetPresentation'; -import type { MapUrlState, MapUrlView } from '../navigation/mapUrlState'; +import { writeMapUrl, type MapUrlState, type MapUrlView } from '../navigation/mapUrlState'; import { normalizeMapUrlState } from '../navigation/normalizeMapUrlState'; import { userDatabase } from '../storage/database'; import { DatasetSnapshotConflictError, + MAX_MARKER_LABEL_LENGTH, ensureDatasetSnapshot, saveCustomMarker, } from '../storage/userData'; @@ -70,6 +71,9 @@ import { } from '../user-data'; import { PixelIcon } from '../ui/PixelIcon'; import { StatusMark } from '../ui/StatusMark'; +import { MapSettings } from '../ui/MapSettings'; +import { MarkerAppearanceContext } from '../ui/MarkerAppearanceContext'; +import { readColorblindPreference, saveColorblindPreference } from '../ui/mapPreferences'; import { createFocusReturnController, isKeyboardActivation, @@ -77,6 +81,8 @@ import { import { MARKER_KINDS, MARKER_SEMANTICS, + markerColor, + markerAppearance, type MarkerKind, } from '../ui/markerSemantics'; import { CurrentBasemapLoadWindow } from './currentBasemapLoadWindow'; @@ -147,40 +153,35 @@ const OLD_EBONHEART_VIEW: MapUrlView = { zoom: 4, }; -const MARKER_ICON_SOURCES = new globalThis.Map( - MARKER_KINDS.map((kind) => { - const semantic = MARKER_SEMANTICS[kind]; - const svg = ``; - return [kind, `data:image/svg+xml,${encodeURIComponent(svg)}`]; - }), -); +const MARKER_STYLE_CACHE = new globalThis.Map(); -function createMarkerStyles(kind: MarkerKind, emphasis: MarkerEmphasis): Style[] { +const SELECTED_PLACE_COLOR = '#6fe7ff'; +const SELECTED_PLACE_ICON_SOURCE = `data:image/svg+xml,${encodeURIComponent( + ``, +)}`; + +function createMarkerStyles(kind: MarkerKind, emphasis: MarkerEmphasis, colorblind = false): Style[] { + const key = `${kind}:${emphasis}:${colorblind}`; + const cached = MARKER_STYLE_CACHE.get(key); + if (cached) { + return cached; + } + const semantic = markerAppearance(kind, colorblind); + const svg = ``; const baseZIndex = emphasis === 'selected' ? 112 : emphasis === 'hovered' ? 102 : 92; - const scale = emphasis === 'selected' ? 0.45 : emphasis === 'hovered' ? 0.4 : 0.35; - return [new Style({ + const selectedPlace = emphasis === 'selected' && kind !== 'custom'; + const scale = selectedPlace ? 0.6 : emphasis === 'selected' ? 0.45 : 0.35; + const styles = [new Style({ image: new Icon({ - src: MARKER_ICON_SOURCES.get(kind) ?? '', + src: selectedPlace && !colorblind ? SELECTED_PLACE_ICON_SOURCE : `data:image/svg+xml,${encodeURIComponent(svg)}`, scale, }), zIndex: baseZIndex, })]; + MARKER_STYLE_CACHE.set(key, styles); + return styles; } -function createProgressMarkerStyles(emphasis: MarkerEmphasis): Record { - return { - unvisited: createMarkerStyles('unvisited', emphasis), - active: createMarkerStyles('active', emphasis), - visited: createMarkerStyles('visited', emphasis), - }; -} - -const PLACE_STYLES = createProgressMarkerStyles('default'); -const HOVERED_PLACE_STYLES = createProgressMarkerStyles('hovered'); -const SELECTED_PLACE_STYLES = createProgressMarkerStyles('selected'); -const CUSTOM_MARKER_STYLES = createMarkerStyles('custom', 'default'); -const HOVERED_CUSTOM_MARKER_STYLES = createMarkerStyles('custom', 'hovered'); -const SELECTED_CUSTOM_MARKER_STYLES = createMarkerStyles('custom', 'selected'); const PLACE_LABEL_STYLE_CACHE = new globalThis.Map(); const BASEMAP_PRESENTATION_STYLE = { '--basemap-brightness': String(BASEMAP_BRIGHTNESS_FACTOR), @@ -191,11 +192,14 @@ function createPlaceLabelStyle( name: string, selected: boolean, searchMatch: boolean, - status: ProgressStatus, + status: MarkerKind, showAll: boolean, + hovered = false, + colorblind = false, ): Style { + const emphasized = selected || hovered; const tone = selected ? 'selected' : searchMatch ? 'match' : 'default'; - const cacheKey = `${tone}\0${status}\0${showAll}\0${name}`; + const cacheKey = `${tone}\0${hovered}\0${status}\0${showAll}\0${colorblind}\0${name}`; const cached = PLACE_LABEL_STYLE_CACHE.get(cacheKey); if (cached) { return cached; @@ -204,17 +208,18 @@ function createPlaceLabelStyle( const style = new Style({ text: new Text({ text: name, - font: selected || searchMatch + font: emphasized || searchMatch ? '600 10px "Atkinson Hyperlegible Next Variable", Arial, sans-serif' : '500 10px "Atkinson Hyperlegible Next Variable", Arial, sans-serif', offsetY: -11, - padding: [1, 2, 1, 2], - fill: new Fill({ color: MARKER_SEMANTICS[status].color }), + padding: hovered ? [3, 5, 3, 5] : [1, 2, 1, 2], + backgroundFill: hovered ? new Fill({ color: 'rgba(23, 19, 13, 0.7)' }) : undefined, + fill: new Fill({ color: selected && status !== 'custom' && !colorblind ? SELECTED_PLACE_COLOR : markerColor(status, colorblind) }), stroke: new Stroke({ color: '#17130d', width: 2 }), - declutterMode: showAll ? 'none' : 'declutter', + declutterMode: emphasized || showAll ? 'none' : 'declutter', overflow: true, }), - zIndex: 0, + zIndex: hovered ? 2 : selected ? 1 : 0, }); PLACE_LABEL_STYLE_CACHE.set(cacheKey, style); return style; @@ -291,10 +296,6 @@ function regionExtent( ]; } -function formatCoordinate(value: number): string { - return Math.round(value).toLocaleString('en-US'); -} - function visibilityZoomFor( thresholds: readonly number[], zoom: number, @@ -518,6 +519,8 @@ function DatasetMapReady({ }: DatasetMapReadyProps) { const { t } = useTranslation(); const locale: Locale = 'en'; + const [colorblind, setColorblind] = useState(readColorblindPreference); + const colorblindRef = useRef(colorblind); const targetRef = useRef(null); const searchRef = useRef(null); const mapRef = useRef(null); @@ -528,7 +531,9 @@ function DatasetMapReady({ const basemapRetryButtonRef = useRef(null); const markerLayerRef = useRef | null>(null); const labelLayerRef = useRef | null>(null); + const focusedLabelLayerRef = useRef | null>(null); const customMarkerLayerRef = useRef | null>(null); + const focusedCustomLabelLayerRef = useRef | null>(null); const visiblePlaceIdsRef = useRef>(new Set()); const labelPriorityContextRef = useRef<{ selectedPlaceId: string | null; @@ -978,6 +983,15 @@ function DatasetMapReady({ return () => window.removeEventListener('keydown', focusSearch); }, []); + useEffect(() => { + colorblindRef.current = colorblind; + markerLayerRef.current?.changed(); + labelLayerRef.current?.changed(); + focusedLabelLayerRef.current?.changed(); + customMarkerLayerRef.current?.changed(); + focusedCustomLabelLayerRef.current?.changed(); + }, [colorblind]); + useEffect(() => { selectedIdRef.current = selectedId; labelPriorityContextRef.current = { @@ -986,11 +1000,13 @@ function DatasetMapReady({ }; markerLayerRef.current?.changed(); labelLayerRef.current?.changed(); + focusedLabelLayerRef.current?.changed(); }, [selectedId]); useEffect(() => { selectedMarkerIdRef.current = selectedMarkerId; customMarkerLayerRef.current?.changed(); + focusedCustomLabelLayerRef.current?.changed(); if (selectedMarkerFocusTargetId === null) { return undefined; } @@ -1008,6 +1024,7 @@ function DatasetMapReady({ }; markerLayerRef.current?.changed(); labelLayerRef.current?.changed(); + focusedLabelLayerRef.current?.changed(); }, [progress.byPlaceId]); useEffect(() => { @@ -1024,6 +1041,9 @@ function DatasetMapReady({ } PLACE_LABEL_STYLE_CACHE.clear(); labelLayerRef.current?.changed(); + focusedLabelLayerRef.current?.changed(); + customMarkerLayerRef.current?.changed(); + focusedCustomLabelLayerRef.current?.changed(); }); return () => { cancelled = true; @@ -1038,6 +1058,7 @@ function DatasetMapReady({ }; markerLayerRef.current?.changed(); labelLayerRef.current?.changed(); + focusedLabelLayerRef.current?.changed(); }, [searchMatchIds, visiblePlaceIds]); useEffect(() => { @@ -1260,11 +1281,13 @@ function DatasetMapReady({ } const status = progressByPlaceIdRef.current.get(placeId)?.status ?? 'unvisited'; if (placeId === selectedIdRef.current) { - return SELECTED_PLACE_STYLES[status]; + return createMarkerStyles(status, 'selected', colorblindRef.current); } - return placeId === hoveredPlaceIdRef.current - ? HOVERED_PLACE_STYLES[status] - : PLACE_STYLES[status]; + return createMarkerStyles( + status, + placeId === hoveredPlaceIdRef.current ? 'hovered' : 'default', + colorblindRef.current, + ); }, updateWhileAnimating: true, updateWhileInteracting: true, @@ -1290,7 +1313,11 @@ function DatasetMapReady({ ), style: (feature, resolution) => { const placeId = feature.get('placeId') as string; - if (!visiblePlaceIdsRef.current.has(placeId)) { + if ( + !visiblePlaceIdsRef.current.has(placeId) || + placeId === selectedIdRef.current || + placeId === hoveredPlaceIdRef.current + ) { return undefined; } const place = feature.get('placeView') as PlaceView; @@ -1299,7 +1326,9 @@ function DatasetMapReady({ placeId === selectedIdRef.current, labelPriorityContextRef.current.searchMatchIds.has(placeId), progressByPlaceIdRef.current.get(placeId)?.status ?? 'unvisited', - resolution <= view.getResolutionForZoom(view.getMaxZoom()) * 1.001, + resolution <= view.getResolutionForZoom(8) * 1.001, + false, + colorblindRef.current, ); }, updateWhileAnimating: true, @@ -1307,22 +1336,92 @@ function DatasetMapReady({ }); labelLayer.setZIndex(11); labelLayerRef.current = labelLayer; + const focusedLabelLayer = new VectorLayer({ + source: labelLayer.getSource()!, + declutter: 'focused-place-labels', + renderBuffer: 180, + style: (feature) => { + const placeId = feature.get('placeId') as string; + const selected = placeId === selectedIdRef.current; + const hovered = placeId === hoveredPlaceIdRef.current; + if (!visiblePlaceIdsRef.current.has(placeId) || (!selected && !hovered)) { + return undefined; + } + const place = feature.get('placeView') as PlaceView; + return createPlaceLabelStyle( + place.name, + selected, + false, + progressByPlaceIdRef.current.get(placeId)?.status ?? 'unvisited', + true, + hovered, + colorblindRef.current, + ); + }, + updateWhileAnimating: true, + updateWhileInteracting: true, + }); + focusedLabelLayer.setZIndex(30); + focusedLabelLayerRef.current = focusedLabelLayer; const customMarkerLayer = new VectorLayer({ source: new VectorSource(), - style: (feature) => { + style: (feature, resolution) => { + if (resolution > view.getResolutionForZoom(2)) { + return undefined; + } const markerId = feature.get('markerId') as string; - if (markerId === selectedMarkerIdRef.current) { - return SELECTED_CUSTOM_MARKER_STYLES; + const selected = markerId === selectedMarkerIdRef.current; + const markerStyles = createMarkerStyles( + 'custom', + selected ? 'selected' : markerId === hoveredMarkerIdRef.current ? 'hovered' : 'default', + colorblindRef.current, + ); + if (selected || markerId === hoveredMarkerIdRef.current) { + return markerStyles; } - return markerId === hoveredMarkerIdRef.current - ? HOVERED_CUSTOM_MARKER_STYLES - : CUSTOM_MARKER_STYLES; + return [ + ...markerStyles, + createPlaceLabelStyle( + Array.from(feature.get('label') as string).slice(0, MAX_MARKER_LABEL_LENGTH).join(''), + selected, + false, + 'custom', + true, + false, + colorblindRef.current, + ), + ]; }, updateWhileAnimating: true, updateWhileInteracting: true, }); customMarkerLayer.setZIndex(20); customMarkerLayerRef.current = customMarkerLayer; + const focusedCustomLabelLayer = new VectorLayer({ + source: customMarkerLayer.getSource()!, + renderBuffer: 180, + style: (feature, resolution) => { + if (resolution > view.getResolutionForZoom(2)) { + return undefined; + } + const markerId = feature.get('markerId') as string; + const selected = markerId === selectedMarkerIdRef.current; + const hovered = markerId === hoveredMarkerIdRef.current; + return selected || hovered ? createPlaceLabelStyle( + Array.from(feature.get('label') as string).slice(0, MAX_MARKER_LABEL_LENGTH).join(''), + selected, + false, + 'custom', + true, + hovered, + colorblindRef.current, + ) : undefined; + }, + updateWhileAnimating: true, + updateWhileInteracting: true, + }); + focusedCustomLabelLayer.setZIndex(29); + focusedCustomLabelLayerRef.current = focusedCustomLabelLayer; const initialNavigation = initialNavigationRef.current; const initialPlace = initialNavigation.placeId === null ? null @@ -1352,6 +1451,8 @@ function DatasetMapReady({ zoom: initialView?.zoom ?? 1, minZoom: minimumZoom, maxZoom: maximumZoom, + constrainResolution: true, + smoothResolutionConstraint: false, enableRotation: false, ...(viewResolutions ? { resolutions: viewResolutions } : {}), extent, @@ -1366,6 +1467,8 @@ function DatasetMapReady({ markerLayer, labelLayer, customMarkerLayer, + focusedLabelLayer, + focusedCustomLabelLayer, ], view, controls: [], @@ -1420,15 +1523,62 @@ function DatasetMapReady({ }; updateCoverageAtCenter(); - // Prefer entrance squares over nearby labels in dense city centers. + const labelHitContext = document.createElement('canvas').getContext('2d'); + // Match text bounds rather than the padded background, so it cannot trap hover or clicks. const featureAtPixel = (pixel: number[]) => { const hitTolerance = (view.getZoom() ?? 0) >= view.getMaxZoom() - 0.01 ? 10 : 6; - return map.forEachFeatureAtPixel(pixel, (candidate) => candidate, { + const labelAtPixel = (candidate: FeatureLike) => { + if (!labelHitContext) { + return undefined; + } + const markerId = candidate.get('markerId') as string | undefined; + const place = candidate.get('placeView') as PlaceView | undefined; + const name = markerId + ? Array.from(candidate.get('label') as string).slice(0, MAX_MARKER_LABEL_LENGTH).join('') + : place!.name; + const text = createPlaceLabelStyle( + name, + markerId ? markerId === selectedMarkerIdRef.current : place!.id === selectedIdRef.current, + markerId ? false : labelPriorityContextRef.current.searchMatchIds.has(place!.id), + markerId ? 'custom' : progressByPlaceIdRef.current.get(place!.id)?.status ?? 'unvisited', + true, + markerId ? markerId === hoveredMarkerIdRef.current : place!.id === hoveredPlaceIdRef.current, + colorblindRef.current, + ).getText()!; + labelHitContext.font = text.getFont()!; + labelHitContext.textAlign = 'center'; + labelHitContext.textBaseline = 'middle'; + const metrics = labelHitContext.measureText(name); + const anchor = map.getPixelFromCoordinate((candidate.getGeometry() as Point).getCoordinates()); + const x = pixel[0]! - anchor[0]! - text.getOffsetX(); + const y = pixel[1]! - anchor[1]! - text.getOffsetY(); + return x >= -metrics.actualBoundingBoxLeft && x <= metrics.actualBoundingBoxRight && + y >= -metrics.actualBoundingBoxAscent && y <= metrics.actualBoundingBoxDescent + ? candidate : undefined; + }; + return map.forEachFeatureAtPixel(pixel, labelAtPixel, { + hitTolerance: 0, + layerFilter: (layer) => layer === focusedLabelLayer || layer === focusedCustomLabelLayer, + }) ?? map.forEachFeatureAtPixel(pixel, (candidate, layer) => { + const styles = (layer as VectorLayer).getStyleFunction()?.(candidate, view.getResolution()!); + const image = (Array.isArray(styles) ? styles[0] : styles)?.getImage(); + const size = image?.getSize(); + const scale = image?.getScaleArray(); + if (!size || !scale) { + return undefined; + } + const anchor = map.getPixelFromCoordinate((candidate.getGeometry() as Point).getCoordinates()); + const [width = 0, height = 0] = size; + const [scaleX = 1, scaleY = 1] = scale; + return Math.abs(pixel[0]! - anchor[0]!) <= width * scaleX / 2 && + Math.abs(pixel[1]! - anchor[1]!) <= height * scaleY / 2 + ? candidate : undefined; + }, { hitTolerance, layerFilter: (layer) => layer === markerLayer || layer === customMarkerLayer, - }) ?? map.forEachFeatureAtPixel(pixel, (candidate) => candidate, { - hitTolerance: 2, - layerFilter: (layer) => layer === labelLayer, + }) ?? map.forEachFeatureAtPixel(pixel, labelAtPixel, { + hitTolerance: 0, + layerFilter: (layer) => layer === labelLayer || layer === customMarkerLayer, }); }; const pointerMoveKey = map.on('pointermove', (event) => { @@ -1443,10 +1593,14 @@ function DatasetMapReady({ if (hoveredMarkerIdRef.current !== markerId) { hoveredMarkerIdRef.current = markerId; customMarkerLayer.changed(); + focusedCustomLabelLayer.setZIndex(markerId === null ? 29 : 31); + focusedCustomLabelLayer.changed(); } if (hoveredPlaceIdRef.current !== placeId) { hoveredPlaceIdRef.current = placeId; markerLayer.changed(); + labelLayer.changed(); + focusedLabelLayer.changed(); } map.getTargetElement().classList.toggle( 'map-canvas--marker-hover', @@ -1551,8 +1705,12 @@ function DatasetMapReady({ hoveredPlaceIdRef.current = null; hoveredMarkerIdRef.current = null; markerLayer.changed(); + labelLayer.changed(); + focusedLabelLayer.changed(); customMarkerLayer.changed(); map.getTargetElement().classList.remove('map-canvas--marker-hover'); + focusedCustomLabelLayer.setZIndex(29); + focusedCustomLabelLayer.changed(); }; viewport.addEventListener('pointerleave', clearCursor); @@ -1575,7 +1733,9 @@ function DatasetMapReady({ basemapRetryInFlightRef.current = false; markerLayerRef.current = null; labelLayerRef.current = null; + focusedLabelLayerRef.current = null; customMarkerLayerRef.current = null; + focusedCustomLabelLayerRef.current = null; }; }, [ bundle, @@ -1721,6 +1881,7 @@ function DatasetMapReady({ new Feature({ geometry: new Point([...marker.position]), markerId: marker.id, + label: marker.label, }), ), ); @@ -1732,7 +1893,7 @@ function DatasetMapReady({ if (!view) { return; } - const current = view.getZoom() ?? 0; + const current = Math.round(view.getZoom() ?? 0); const next = Math.max(view.getMinZoom(), Math.min(view.getMaxZoom(), current + delta)); if (prefersReducedMotion()) { view.setZoom(next); @@ -2045,20 +2206,36 @@ function DatasetMapReady({ }; return ( -
+ +
+ [`--mim-${kind}`, markerColor(kind, colorblind)] + ))} + > + <> + { + setColorblind(enabled); + return saveColorblindPreference(enabled); + }} + /> + + )} /> @@ -2152,7 +2329,7 @@ function DatasetMapReady({ key={place.id} type="button" className={selectedId === place.id ? 'place-result place-result--selected' : 'place-result'} - style={{ '--place-status-color': MARKER_SEMANTICS[status].color } as CSSProperties} + style={{ '--place-status-color': markerColor(status, colorblind) } as CSSProperties} aria-current={selectedId === place.id ? 'location' : undefined} onClick={(event) => selectPlace( place, @@ -2348,6 +2525,20 @@ function DatasetMapReady({ progress={progress.byPlaceId.get(selectedPlace.id)} disabled={userDataDisabled} onClose={closeSelectedPlace} + onCopyLink={() => navigator.clipboard.writeText(writeMapUrl( + new URL(window.location.pathname, window.location.origin), + { + datasetId: dataset.datasetId, + regionId: 'all', + placeId: selectedPlace.id, + view: { + center: selectedPlace.place.mapPosition, + zoom: mapRef.current?.getView().getZoom() ?? zoomRef.current, + }, + typeFilters: [], + statusFilters: [], + }, + ).href)} /> ) : null} {selectedMarker ? ( @@ -2363,6 +2554,7 @@ function DatasetMapReady({
+
); } @@ -2374,6 +2566,7 @@ interface PlaceCardProps { readonly progress: ProgressRecord | undefined; readonly disabled: boolean; readonly onClose: () => void; + readonly onCopyLink: () => Promise; } function PlaceCard({ @@ -2384,8 +2577,39 @@ function PlaceCard({ progress, disabled, onClose, + onCopyLink, }: PlaceCardProps) { const { t } = useTranslation(); + const [copyFeedback, setCopyFeedback] = useState<{ + readonly sequence: number; + readonly placeId: string; + readonly failed: boolean; + } | null>(null); + const copySequenceRef = useRef(0); + const currentCopyFeedback = copyFeedback?.placeId === place.id ? copyFeedback : null; + useEffect(() => { + if (currentCopyFeedback === null) { + return; + } + const timeout = window.setTimeout(() => { + setCopyFeedback((current) => current === currentCopyFeedback ? null : current); + }, 5000); + return () => window.clearTimeout(timeout); + }, [currentCopyFeedback]); + const copyLink = async () => { + const sequence = ++copySequenceRef.current; + setCopyFeedback(null); + try { + await onCopyLink(); + if (sequence === copySequenceRef.current) { + setCopyFeedback({ sequence, placeId: place.id, failed: false }); + } + } catch { + if (sequence === copySequenceRef.current) { + setCopyFeedback({ sequence, placeId: place.id, failed: true }); + } + } + }; return (
-

{place.name}

+
+

{place.name}

+ +
+ {currentCopyFeedback ? ( +

+ {t(currentCopyFeedback.failed ? 'map.placeLinkCopyFailed' : 'map.placeLinkCopied')} +

+ ) : null} {t('map.personalMarker')}

{marker.label}

-

- X {formatCoordinate(marker.position[0])} · Y{' '} - {formatCoordinate(marker.position[1])} -

{ - it('adds one 10% view-only overscale without extending the source tile grid', () => { + it('preserves existing zoom levels and extends the view to z9 using only existing source tiles', () => { const sourcePyramid = pyramid(); const viewResolutions = createOverscaledViewResolutions(sourcePyramid); const sourceGrid = createTes3TileGrid(sourcePyramid); - expect(BASEMAP_MAX_OVERSCALE).toBe(1.1); - expect(viewResolutions).toHaveLength(9); - expect(viewResolutions.at(-1)).toBeCloseTo(16 / 1.1); + expect(viewResolutions).toHaveLength(10); + expect(viewResolutions.slice(0, 8)).toEqual(sourcePyramid.resolutions); + expect(viewResolutions[8]).toBeCloseTo(16 / 1.1); + expect(viewResolutions[9]).toBeCloseTo(16 / 2.2); expect(sourceGrid.getMaxZoom()).toBe(7); - expect(sourceGrid.getZForResolution(16 / 1.1)).toBe(7); + for (const resolution of viewResolutions.slice(8)) { + expect(sourceGrid.getZForResolution(resolution)).toBe(7); + } }); it('uses the conservative visual grade selected for the preview', () => { diff --git a/apps/web/src/map/basemapPresentation.ts b/apps/web/src/map/basemapPresentation.ts index 37dc63b5..0a0beee8 100644 --- a/apps/web/src/map/basemapPresentation.ts +++ b/apps/web/src/map/basemapPresentation.ts @@ -4,7 +4,8 @@ import type Tile from 'ol/Tile.js'; import TileState from 'ol/TileState.js'; import { createTes3Resolutions } from './sparseTiles'; -export const BASEMAP_MAX_OVERSCALE = 1.1; +export const BASEMAP_INITIAL_OVERSCALE = 1.1; +export const BASEMAP_MAX_VIEW_ZOOM = 9; export const BASEMAP_CONTRAST_FACTOR = 102 / 108; export const BASEMAP_BRIGHTNESS_FACTOR = 1.1; @@ -14,7 +15,7 @@ export function requiresRuntimeBasemapAdjustment(pyramid: TilePyramid): boolean export function createOverscaledViewResolutions( pyramid: TilePyramid, - scale = BASEMAP_MAX_OVERSCALE, + scale = BASEMAP_INITIAL_OVERSCALE, ): number[] { const resolutions = createTes3Resolutions(pyramid); const finestResolution = resolutions.at(-1); @@ -23,7 +24,12 @@ export function createOverscaledViewResolutions( return resolutions; } - return [...resolutions, finestResolution / scale]; + // Preserve existing zoom values and shared links, then magnify the finest tiles further. + const viewResolutions = [...resolutions, finestResolution / scale]; + while (viewResolutions.length <= BASEMAP_MAX_VIEW_ZOOM) { + viewResolutions.push(viewResolutions[viewResolutions.length - 1]! / 2); + } + return viewResolutions; } export function makeRenderedPixelsOpaque(pixels: Uint8ClampedArray): void { diff --git a/apps/web/src/storage/userData.test.ts b/apps/web/src/storage/userData.test.ts index daac095f..47b181dd 100644 --- a/apps/web/src/storage/userData.test.ts +++ b/apps/web/src/storage/userData.test.ts @@ -76,10 +76,17 @@ describe('Dexie user data storage', () => { ); await saveCustomMarker( database, - { datasetId, label: 'Supply cache', note: 'Chest', position: [10, 20] }, + { datasetId, label: 'A'.repeat(100), note: 'Chest', position: [10, 20] }, at('2026-08-31T12:00:01.000Z'), () => 'fixture', ); + await expect(saveCustomMarker(database, { + id: `${datasetId}.custom.fixture`, + datasetId, + label: 'B'.repeat(101), + note: 'Rejected rename', + position: [10, 20], + })).rejects.toThrow('1–100 characters'); database.close(); database = new MorrowindMapDatabase(databaseName); @@ -91,10 +98,21 @@ describe('Dexie user data storage', () => { await expect(database.customMarkers.toArray()).resolves.toEqual([ expect.objectContaining({ id: 'original-goty-hd.custom.fixture', - label: 'Supply cache', + label: 'A'.repeat(100), position: [10, 20], }), ]); + + // Existing long names from older backups remain editable without losing the name. + const markerId = `${datasetId}.custom.fixture`; + await database.customMarkers.update(markerId, { label: 'L'.repeat(101) }); + await expect(saveCustomMarker(database, { + id: markerId, + datasetId, + label: 'L'.repeat(101), + note: 'Updated legacy note', + position: [10, 20], + })).resolves.toMatchObject({ label: 'L'.repeat(101), note: 'Updated legacy note' }); }); it('round-trips a manual-only v3 JSON backup without creating duplicates', async () => { diff --git a/apps/web/src/storage/userData.ts b/apps/web/src/storage/userData.ts index dfbd3cad..2ac67ae2 100644 --- a/apps/web/src/storage/userData.ts +++ b/apps/web/src/storage/userData.ts @@ -14,7 +14,7 @@ import type { import { progressKey } from './database'; export const MAX_NOTE_LENGTH = 10_000; -export const MAX_MARKER_LABEL_LENGTH = 512; +export const MAX_MARKER_LABEL_LENGTH = 100; export interface ProgressPatch { readonly status?: ProgressStatus; @@ -221,7 +221,7 @@ export async function saveCustomMarker( if (!id.startsWith(`${input.datasetId}.`)) { throw new Error('Custom marker id must be scoped to its dataset'); } - if (!label || label.length > MAX_MARKER_LABEL_LENGTH) { + if (!label) { throw new Error(`Custom marker label must contain 1–${MAX_MARKER_LABEL_LENGTH} characters`); } if (input.note.length > MAX_NOTE_LENGTH) { @@ -233,6 +233,10 @@ export async function saveCustomMarker( return database.transaction('rw', database.datasetSnapshots, database.customMarkers, async () => { await requireDatasetSnapshotBinding(database, input.datasetId); const existing = await database.customMarkers.get(id); + // Older backups may contain longer names; allow note-only edits without truncating them. + if (label.length > MAX_MARKER_LABEL_LENGTH && label !== existing?.label) { + throw new Error(`Custom marker label must contain 1–${MAX_MARKER_LABEL_LENGTH} characters`); + } if (existing && existing.datasetId !== input.datasetId) { throw new Error('Custom marker belongs to a different dataset'); } diff --git a/apps/web/src/styles.css b/apps/web/src/styles.css index 808ef556..e7a1ebea 100644 --- a/apps/web/src/styles.css +++ b/apps/web/src/styles.css @@ -362,6 +362,101 @@ textarea:focus-visible, gap: 22px; } +.map-settings-trigger { + display: grid; + flex: 0 0 auto; + width: var(--control-compact); + height: var(--control-compact); + place-items: center; + border: 1px solid transparent; + border-radius: 0; + padding: 0; + color: var(--ui-gold); + background: transparent; + cursor: pointer; +} + +.map-settings-trigger:hover, +.map-settings-trigger[aria-expanded="true"] { + border-color: var(--ui-brass); + background: #2a2418; +} + +.map-settings-trigger .pixel-icon { + width: 17px; + height: 17px; +} + +dialog.map-settings-panel { + left: 50%; + right: auto; + width: min(420px, calc(100vw - 32px - var(--safe-left) - var(--safe-right))); + min-height: 0; + margin: 0; + padding: 28px 24px; + gap: 16px; + place-items: stretch; + transform: translate(-50%, -50%); +} + +.map-settings-panel:not([open]) { + display: none; +} + +.map-settings-panel::backdrop { + background: rgba(9, 8, 6, 0.55); +} + +.map-settings-panel h2 { + margin: 0; + padding-right: 32px; + font-family: var(--font-display); + font-size: 24px; +} + +.map-settings-panel p { + margin: 0; + font-size: 13px; + line-height: 1.5; +} + +.map-settings-option { + display: flex; + min-height: 44px; + align-items: center; + gap: 10px; + cursor: pointer; +} + +.map-settings-option input { + width: 18px; + height: 18px; + flex: 0 0 auto; + margin: 0; + accent-color: var(--book-ink); +} + +.map-settings-option input:focus-visible { + outline-color: var(--focus-paper); +} + +.map-settings-preview { + display: flex; + flex-wrap: wrap; + gap: 12px; + border: 1px solid var(--ui-brass); + padding: 12px; + color: var(--text-strong); + background: var(--ui-panel); + font-size: 12px; +} + +.map-settings-preview span { + display: inline-flex; + align-items: center; + gap: 6px; +} + .landing-contact-panel__links a { display: flex; max-width: 100%; @@ -1554,6 +1649,54 @@ textarea:focus-visible, padding-top: 12px; } +.place-card-title { + display: flex; + align-items: center; + gap: 8px; + margin: 0 34px 14px 0; +} + +.place-card-title h2 { + min-width: 0; + max-width: none; + margin: 0; + overflow-wrap: anywhere; +} + +.place-card-copy-link { + display: grid; + flex: 0 0 var(--control-compact); + width: var(--control-compact); + height: var(--control-compact); + place-items: center; + border: 1px solid var(--ui-brass); + padding: 0; + color: var(--book-ink); + background: transparent; + box-shadow: none; + cursor: pointer; +} + +.user-data-tools__feedback--transient { + animation: place-share-feedback-fade 5s ease-in forwards; +} + +.place-share-feedback { + margin: 0; + color: var(--paper-positive); + font-size: 12px; + animation: place-share-feedback-fade 5s ease-in forwards; +} + +@keyframes place-share-feedback-fade { + 0%, 90% { opacity: 1; } + 100% { opacity: 0; } +} + +.place-share-feedback--error { + color: var(--paper-error); +} + .place-progress-editor fieldset { margin: 0; border: 0; @@ -1650,10 +1793,6 @@ textarea:focus-visible, box-shadow: none; } -.place-progress-editor__note button { - display: none; -} - .place-progress-editor > p, .custom-marker-editor > p { margin: 7px 0 0; @@ -1666,19 +1805,22 @@ textarea:focus-visible, color: var(--paper-error); } -.custom-marker-coordinate { - margin: 8px 0 0; - color: var(--paper-muted); - font-family: var(--font-data); - font-size: 10px; -} - .custom-marker-editor form label:not(:first-child) { margin-top: 8px; } -.custom-marker-editor > button { - margin-top: 8px; +.custom-marker-editor__actions { + display: flex; + justify-content: space-between; + align-items: center; + gap: 8px; +} + +.custom-marker-editor__actions button[type="submit"] { + margin-left: auto; +} + +.custom-marker-editor form .custom-marker-editor__delete { border-color: #805845; color: #5b281e; background: #c09a78; @@ -1762,6 +1904,13 @@ textarea:focus-visible, } } +@media (max-width: 860px), (hover: none) and (pointer: coarse) { + .region-filter, + .place-filter-drawer { + display: none; + } +} + @media (max-height: 480px) and (min-width: 561px) { .map-screen { min-height: 100dvh; @@ -1934,6 +2083,11 @@ textarea:focus-visible, } @media (prefers-reduced-motion: reduce) { + .place-share-feedback, + .user-data-tools__feedback--transient { + animation: none; + } + *, *::before, *::after { @@ -1963,13 +2117,19 @@ textarea:focus-visible, } .map-tools button, + .place-card-copy-link, .place-card-close, .landing-contact-trigger, + .map-settings-trigger, .landing-contact-panel__close { width: 44px; height: 44px; } + .place-card-copy-link { + flex-basis: 44px; + } + .user-data-tools--compact button, .user-data-tools--compact label { width: 44px; diff --git a/apps/web/src/ui/MapSettings.tsx b/apps/web/src/ui/MapSettings.tsx new file mode 100644 index 00000000..c4f87864 --- /dev/null +++ b/apps/web/src/ui/MapSettings.tsx @@ -0,0 +1,79 @@ +import { useRef, useState } from 'react'; +import { PixelIcon } from './PixelIcon'; +import { StatusMark } from './StatusMark'; + +interface MapSettingsProps { + readonly colorblind: boolean; + readonly onColorblindChange: (enabled: boolean) => boolean; +} + +export function MapSettings({ colorblind, onColorblindChange }: MapSettingsProps) { + const dialogRef = useRef(null); + const [isOpen, setIsOpen] = useState(false); + const [saveFailed, setSaveFailed] = useState(false); + + return ( + <> + + setIsOpen(false)} + onKeyDown={(event) => { + if (event.key === 'Escape') { + event.stopPropagation(); + } + }} + > + +

Map settings

+ +

+ Distinguish places and personal markers by both color and shape. Applies immediately to all maps. +

+
+ Unvisited + Active + Visited + Personal marker +
+ {saveFailed ? ( +

Colors changed for this session. Your browser could not save the preference.

+ ) : null} +
+ + ); +} diff --git a/apps/web/src/ui/MarkerAppearanceContext.ts b/apps/web/src/ui/MarkerAppearanceContext.ts new file mode 100644 index 00000000..69c551bf --- /dev/null +++ b/apps/web/src/ui/MarkerAppearanceContext.ts @@ -0,0 +1,3 @@ +import { createContext } from 'react'; + +export const MarkerAppearanceContext = createContext(false); diff --git a/apps/web/src/ui/PixelIcon.tsx b/apps/web/src/ui/PixelIcon.tsx index 3bc02551..193aa62e 100644 --- a/apps/web/src/ui/PixelIcon.tsx +++ b/apps/web/src/ui/PixelIcon.tsx @@ -34,6 +34,10 @@ function IconPath({ name }: { readonly name: PixelIconName }) { ); case 'github': return ; + case 'link': + return ; + case 'settings': + return ; } } diff --git a/apps/web/src/ui/StatusMark.tsx b/apps/web/src/ui/StatusMark.tsx index 80180410..1d6490f8 100644 --- a/apps/web/src/ui/StatusMark.tsx +++ b/apps/web/src/ui/StatusMark.tsx @@ -1,4 +1,6 @@ -import { MARKER_SEMANTICS, type MarkerKind } from './markerSemantics'; +import { useContext } from 'react'; +import { markerAppearance, type MarkerKind } from './markerSemantics'; +import { MarkerAppearanceContext } from './MarkerAppearanceContext'; interface StatusMarkProps { readonly kind: MarkerKind; @@ -6,7 +8,8 @@ interface StatusMarkProps { } export function StatusMark({ kind, className = '' }: StatusMarkProps) { - const semantic = MARKER_SEMANTICS[kind]; + const colorblind = useContext(MarkerAppearanceContext); + const semantic = markerAppearance(kind, colorblind); return (
+ {!confirmingDelete ? ( + + ) : null} + +
- {!confirmingDelete ? ( - - ) : ( + {confirmingDelete ? (
- )} + ) : null} {currentFeedback ? (

{ afterEach(() => { cleanup(); + vi.useRealTimers(); vi.clearAllMocks(); }); @@ -121,6 +122,7 @@ describe('DataTools', () => { }); it('keeps only stored-binding export available during a snapshot conflict', async () => { + vi.useFakeTimers(); Object.defineProperty(URL, 'createObjectURL', { configurable: true, value: vi.fn(() => 'blob:conflict-backup'), @@ -130,7 +132,7 @@ describe('DataTools', () => { value: vi.fn(), }); vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => undefined); - vi.mocked(createPortableBackupForStoredDataset).mockResolvedValueOnce({ + vi.mocked(createPortableBackupForStoredDataset).mockResolvedValue({ schemaVersion: 3, kind: 'morrowind-map-backup', exportedAt: '2026-08-31T12:05:00.000Z', @@ -146,15 +148,31 @@ describe('DataTools', () => { expect(exportButton).toBeEnabled(); expect(importInput).toBeDisabled(); - fireEvent.click(exportButton); + await act(async () => { + fireEvent.click(exportButton); + await Promise.resolve(); + }); - expect(await screen.findByRole('status')).toHaveTextContent('JSON backup downloaded'); + const firstFeedback = screen.getByRole('status'); + expect(firstFeedback).toHaveTextContent('JSON backup downloaded'); expect(createPortableBackupForStoredDataset).toHaveBeenCalledWith( expect.anything(), props.datasetId, ); expect(createPortableBackup).not.toHaveBeenCalled(); expect(importPortableBackup).not.toHaveBeenCalled(); + await act(() => vi.advanceTimersByTimeAsync(4000)); + await act(async () => { + fireEvent.click(exportButton); + await Promise.resolve(); + }); + expect(screen.getByRole('status')).not.toBe(firstFeedback); + await act(() => vi.advanceTimersByTimeAsync(1000)); + expect(screen.getByRole('status')).toHaveTextContent('JSON backup downloaded'); + await act(() => vi.advanceTimersByTimeAsync(3999)); + expect(screen.getByRole('status')).toBeInTheDocument(); + await act(() => vi.advanceTimersByTimeAsync(1)); + expect(screen.queryByRole('status')).not.toBeInTheDocument(); }); it('rejects oversized and invalid JSON before any storage write', async () => { diff --git a/apps/web/src/user-data/DataTools.tsx b/apps/web/src/user-data/DataTools.tsx index d03cac4e..8b6e68f5 100644 --- a/apps/web/src/user-data/DataTools.tsx +++ b/apps/web/src/user-data/DataTools.tsx @@ -1,4 +1,4 @@ -import { useId, useRef, useState, type ChangeEvent } from 'react'; +import { useEffect, useId, useRef, useState, type ChangeEvent } from 'react'; import type { Locale } from '@morrowind-map/contracts'; import { userDatabase, @@ -19,7 +19,7 @@ type BusyOperation = 'export' | 'backup' | null; type Feedback = | { readonly tone: 'error'; readonly text: string } - | { readonly tone: 'status'; readonly kind: 'backup-exported' } + | { readonly tone: 'status'; readonly kind: 'backup-exported'; readonly operationId: number } | { readonly tone: 'status'; readonly kind: 'backup-result'; readonly result: BackupImportResult }; export interface DataToolsProps { @@ -74,6 +74,18 @@ export function DataTools({ const compact = variant === 'compact'; const isDisabled = disabled || busy !== null; const importDisabled = isDisabled || mode === 'conflict-export-only'; + const exportFeedback = feedback?.tone === 'status' && feedback.kind === 'backup-exported' + ? feedback : null; + + useEffect(() => { + if (exportFeedback === null) { + return; + } + const timeout = window.setTimeout(() => { + setFeedback((current) => current === exportFeedback ? null : current); + }, 5000); + return () => window.clearTimeout(timeout); + }, [exportFeedback]); const beginOperation = (operation: Exclude) => { if (disabled || activeOperationRef.current !== null) { @@ -116,7 +128,7 @@ export function DataTools({ ? await createPortableBackupForStoredDataset(database, datasetId) : await createPortableBackup(database, datasetSnapshots); downloadBackup(`${JSON.stringify(backup, null, 2)}\n`, backup.exportedAt); - finishOperation(operationId, { tone: 'status', kind: 'backup-exported' }); + finishOperation(operationId, { tone: 'status', kind: 'backup-exported', operationId }); } catch (error: unknown) { failOperation(operationId, error, strings.exportJson); } @@ -216,7 +228,8 @@ export function DataTools({ {feedbackText ? (

{feedbackText} diff --git a/apps/web/src/user-data/EditorDrafts.test.tsx b/apps/web/src/user-data/EditorDrafts.test.tsx index 0d3e92b7..77baeb68 100644 --- a/apps/web/src/user-data/EditorDrafts.test.tsx +++ b/apps/web/src/user-data/EditorDrafts.test.tsx @@ -48,7 +48,7 @@ describe('editor crash-recovery drafts', () => { await database.delete(); }); - it('restores an unsaved place note after an immediate unmount and persists it', async () => { + it('restores an unsaved place note and waits for Save before persisting it', async () => { const first = render( { expect(screen.getByRole('textbox', { name: 'Personal note' })).toHaveValue( 'Recovered after reload', ); + await new Promise((resolve) => window.setTimeout(resolve, 500)); + expect(await database.progress.get(progressKey(datasetId, placeId))).toBeUndefined(); + fireEvent.click(screen.getByRole('button', { name: 'Save' })); await waitFor(async () => { expect(await database.progress.get(progressKey(datasetId, placeId))).toMatchObject({ note: 'Recovered after reload', @@ -80,7 +83,7 @@ describe('editor crash-recovery drafts', () => { }); }); - it('autosaves a place note on blur without exposing a redundant save button', async () => { + it('keeps a place note editable across pauses and blur, saving the exact text only on Save', async () => { render( { ); const note = screen.getByRole('textbox', { name: 'Personal note' }); - fireEvent.change(note, { target: { value: 'Saved on focus out' } }); - expect(screen.queryByRole('button', { name: 'Save note' })).not.toBeInTheDocument(); + fireEvent.focus(note); + fireEvent.change(note, { target: { value: 'First line' } }); + await new Promise((resolve) => window.setTimeout(resolve, 500)); + expect(note).toBeEnabled(); + expect(await database.progress.get(progressKey(datasetId, placeId))).toBeUndefined(); + fireEvent.change(note, { target: { value: ' First line\nSecond line ' } }); fireEvent.blur(note); + await new Promise((resolve) => window.setTimeout(resolve, 500)); + expect(await database.progress.get(progressKey(datasetId, placeId))).toBeUndefined(); + fireEvent.click(screen.getByRole('button', { name: 'Save' })); await waitFor(async () => { expect(await database.progress.get(progressKey(datasetId, placeId))).toMatchObject({ - note: 'Saved on focus out', + note: ' First line\nSecond line ', }); }); expect(screen.getByRole('status')).toHaveTextContent('Saved.'); + const savedFeedback = screen.getByRole('status'); + fireEvent.click(screen.getByRole('button', { name: 'Active' })); + expect(screen.getByRole('status')).toBe(savedFeedback); + await waitFor(async () => { + expect(await database.progress.get(progressKey(datasetId, placeId))).toMatchObject({ + status: 'active', + note: ' First line\nSecond line ', + }); + }); + expect(screen.getByRole('status')).toBe(savedFeedback); }); it('ignores a place-note draft from the retired user-data epoch', async () => { @@ -124,7 +144,7 @@ describe('editor crash-recovery drafts', () => { expect(await database.progress.get(progressKey(datasetId, placeId))).toBeUndefined(); }); - it('restores an unsaved marker edit after an immediate unmount and persists it', async () => { + it('restores marker name and note drafts and saves them together only on Save', async () => { const marker = await saveCustomMarker( database, { datasetId, label: 'Original label', note: '', position: [10, 20] }, @@ -137,13 +157,22 @@ describe('editor crash-recovery drafts', () => { fireEvent.change(screen.getByRole('textbox', { name: 'Marker name' }), { target: { value: 'Recovered marker' }, }); + fireEvent.change(screen.getByRole('textbox', { name: 'Personal note' }), { + target: { value: ' Marker note\nSecond line ' }, + }); + fireEvent.blur(screen.getByRole('textbox', { name: 'Personal note' })); first.unmount(); render(); expect(screen.getByRole('textbox', { name: 'Marker name' })).toHaveValue('Recovered marker'); + expect(screen.getByRole('textbox', { name: 'Personal note' })).toHaveValue(' Marker note\nSecond line '); + await new Promise((resolve) => window.setTimeout(resolve, 500)); + expect(await database.customMarkers.get(marker.id)).toMatchObject({ label: 'Original label', note: '' }); + fireEvent.click(screen.getByRole('button', { name: 'Save' })); await waitFor(async () => { expect(await database.customMarkers.get(marker.id)).toMatchObject({ label: 'Recovered marker', + note: ' Marker note\nSecond line ', }); }); }); @@ -174,7 +203,7 @@ describe('editor crash-recovery drafts', () => { ); render(); - fireEvent.click(screen.getByRole('button', { name: 'Delete marker' })); + fireEvent.click(screen.getByRole('button', { name: 'Delete' })); await waitFor(() => expect(screen.getByRole('button', { name: 'Cancel' })).toHaveFocus(), ); @@ -182,7 +211,7 @@ describe('editor crash-recovery drafts', () => { fireEvent.keyDown(screen.getByRole('group', { name: /Delete this marker/ }), { key: 'Escape' }); await waitFor(() => - expect(screen.getByRole('button', { name: 'Delete marker' })).toHaveFocus(), + expect(screen.getByRole('button', { name: 'Delete' })).toHaveFocus(), ); }); @@ -215,7 +244,7 @@ describe('editor crash-recovery drafts', () => { await waitFor(() => expect(saveProgress).toHaveBeenCalledTimes(2)); }); - it('stops a failed marker autosave until manual retry or a new edit', async () => { + it('keeps failed marker edits for manual retry without saving on subsequent edits', async () => { const marker = await saveCustomMarker( database, { datasetId, label: 'Original label', note: '', position: [10, 20] }, @@ -229,6 +258,7 @@ describe('editor crash-recovery drafts', () => { const labelInput = screen.getByRole('textbox', { name: 'Marker name' }); fireEvent.change(labelInput, { target: { value: 'Unsaved marker' } }); + fireEvent.click(screen.getByRole('button', { name: 'Save' })); await waitFor(() => expect(saveMarker).toHaveBeenCalledTimes(1)); expect(labelInput).toHaveValue('Unsaved marker'); expect(window.localStorage.getItem( @@ -238,17 +268,20 @@ describe('editor crash-recovery drafts', () => { await new Promise((resolve) => window.setTimeout(resolve, 500)); expect(saveMarker).toHaveBeenCalledTimes(1); - fireEvent.click(screen.getByRole('button', { name: 'Save marker' })); + fireEvent.click(screen.getByRole('button', { name: 'Save' })); await waitFor(() => expect(saveMarker).toHaveBeenCalledTimes(2)); await new Promise((resolve) => window.setTimeout(resolve, 500)); expect(saveMarker).toHaveBeenCalledTimes(2); fireEvent.change(labelInput, { target: { value: 'Edited again' } }); + await new Promise((resolve) => window.setTimeout(resolve, 500)); + expect(saveMarker).toHaveBeenCalledTimes(2); + fireEvent.click(screen.getByRole('button', { name: 'Save' })); await waitFor(() => expect(saveMarker).toHaveBeenCalledTimes(3)); const alert = await screen.findByRole('alert'); - expect(alert).toHaveTextContent('Select “Save marker” to try again.'); + expect(alert).toHaveTextContent('Select “Save” to try again.'); expect(alert).not.toHaveAttribute('aria-live'); expect(await database.customMarkers.get(marker.id)).toMatchObject({ label: 'Original label', @@ -270,7 +303,7 @@ describe('editor crash-recovery drafts', () => { const labelInput = screen.getByRole('textbox', { name: 'Marker name' }); fireEvent.change(labelInput, { target: { value: 'Keep this draft' } }); - fireEvent.click(screen.getByRole('button', { name: 'Delete marker' })); + fireEvent.click(screen.getByRole('button', { name: 'Delete' })); const confirmButton = screen.getByRole('button', { name: 'Yes, delete' }); expect(screen.getByRole('group', { name: /Delete this marker/ })).toBeInTheDocument(); clickTwiceBeforeRender(confirmButton); diff --git a/apps/web/src/user-data/PlaceProgressEditor.tsx b/apps/web/src/user-data/PlaceProgressEditor.tsx index 06677c88..393b73fd 100644 --- a/apps/web/src/user-data/PlaceProgressEditor.tsx +++ b/apps/web/src/user-data/PlaceProgressEditor.tsx @@ -1,4 +1,4 @@ -import { useEffect, useId, useRef, useState, type FormEvent } from 'react'; +import { useId, useRef, useState, type FormEvent } from 'react'; import type { Locale, ProgressRecord, @@ -95,55 +95,11 @@ export function PlaceProgressEditor({ const [saving, setSaving] = useState<'status' | 'note' | null>(null); const [feedback, setFeedback] = useState(null); const activeOperationRef = useRef(null); - const noteSaveTimerRef = useRef(null); - const noteFormRef = useRef(null); - const recoveredNoteRef = useRef( - draft?.placeKey === placeKey ? draft.value : null, - ); const note = draft?.placeKey === placeKey ? draft.value : (progress?.note ?? ''); const status = progress?.status ?? 'unvisited'; const currentFeedback = feedback?.placeKey === placeKey ? feedback : null; const isDisabled = disabled || saving !== null; - useEffect( - () => () => { - if (noteSaveTimerRef.current !== null) { - window.clearTimeout(noteSaveTimerRef.current); - } - }, - [], - ); - - useEffect(() => { - const recoveredNote = recoveredNoteRef.current; - if (recoveredNote === null) { - return; - } - if (recoveredNote === (progress?.note ?? '')) { - clearStoredNoteDraft(placeKey, recoveredNote); - recoveredNoteRef.current = null; - return; - } - noteSaveTimerRef.current = window.setTimeout(() => { - noteSaveTimerRef.current = null; - noteFormRef.current?.requestSubmit(); - recoveredNoteRef.current = null; - }, 350); - return () => { - if (noteSaveTimerRef.current !== null) { - window.clearTimeout(noteSaveTimerRef.current); - noteSaveTimerRef.current = null; - } - }; - }, [placeKey, progress?.note]); - - const clearPendingNoteSave = () => { - if (noteSaveTimerRef.current !== null) { - window.clearTimeout(noteSaveTimerRef.current); - noteSaveTimerRef.current = null; - } - }; - const beginSave = (kind: SaveOperation['kind'], revision: string) => { if (disabled || activeOperationRef.current !== null) { return null; @@ -151,7 +107,7 @@ export function PlaceProgressEditor({ const operation: SaveOperation = { kind, revision }; activeOperationRef.current = operation; setSaving(kind); - setFeedback(null); + setFeedback((current) => kind === 'note' || current?.tone === 'error' ? null : current); return operation; }; @@ -172,7 +128,6 @@ export function PlaceProgressEditor({ status: nextStatus, }); onSaved?.(saved); - setFeedback({ placeKey, tone: 'status', text: strings.saved }); } catch (error: unknown) { setFeedback({ placeKey, @@ -219,7 +174,6 @@ export function PlaceProgressEditor({ const saveNote = (event: FormEvent) => { event.preventDefault(); - clearPendingNoteSave(); void persistNote(note); }; @@ -244,7 +198,7 @@ export function PlaceProgressEditor({ -

+