feat(ui): polish pass - visual refresh, dark mode, smoother map, mobile sheet
Visual - Design tokens (spacing, radius, type, motion) with a dark theme that follows prefers-color-scheme; map palette in theme.ts (exports/print stay light) - Segmented controls (language, colour scheme), switches, styled slider/select, icon buttons, cards, focus rings, hover/active states, reduced-motion support - Info panel card with animation, tooltip that stays on screen, grouped zoom buttons Map - Redraws batched per animation frame; animated zoom/fit, pan inertia, trackpad pinch, pointer cursor and outline for the hovered building - Hovering a legend row highlights that category on the map Loading & feedback - Progress bar + "Loading n/m" pill; status line with icons, collapsible basemap failure details, success messages fade - A newer load supersedes one in flight; a failed buildings query is reported immediately instead of after the basemap retries Convenience - Keyboard: +/- zoom, 0 fit, arrows pan, Esc closes - Legend All/None, double-click or Alt-click to show only one category - Settings and last location remembered; #lat,lon,radius in the URL to share, copy-link button, "my location" button - Mobile: full-screen map with a draggable bottom sheet Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
5a3ee9ab86
commit
44bc6207a9
22 changed files with 2270 additions and 484 deletions
102
src/actions.ts
102
src/actions.ts
|
|
@ -2,13 +2,36 @@ import { batch } from '@preact/signals'
|
|||
import { fetchArea } from './fetch'
|
||||
import { D2R } from './geo'
|
||||
import { t } from './i18n'
|
||||
import { writeHash } from './persist'
|
||||
import { fitView } from './render'
|
||||
import { base, busy, hidden, radius, rawBuildings, S, sel, status, type Status } from './state'
|
||||
import {
|
||||
base,
|
||||
busy,
|
||||
hidden,
|
||||
lastLoc,
|
||||
locating,
|
||||
locText,
|
||||
progress,
|
||||
radius,
|
||||
rawBuildings,
|
||||
S,
|
||||
sel,
|
||||
status,
|
||||
toast,
|
||||
type Status,
|
||||
} from './state'
|
||||
import type { AreaData, LatLon } from './types'
|
||||
import { errMsg } from './util'
|
||||
|
||||
export function setStatus(fn: () => string, cls?: Status['cls']) {
|
||||
status.value = { fn, cls }
|
||||
export function setStatus(fn: () => string, cls?: Status['cls'], details?: string[]) {
|
||||
status.value = { fn, cls, details }
|
||||
}
|
||||
|
||||
let toastTimer: ReturnType<typeof setTimeout> | undefined
|
||||
export function showToast(fn: () => string) {
|
||||
clearTimeout(toastTimer)
|
||||
toast.value = { fn, id: Date.now() }
|
||||
toastTimer = setTimeout(() => (toast.value = null), 2400)
|
||||
}
|
||||
|
||||
export function applyData(d: AreaData, lon: number, lat: number) {
|
||||
|
|
@ -25,33 +48,88 @@ export function applyData(d: AreaData, lon: number, lat: number) {
|
|||
})
|
||||
}
|
||||
|
||||
let loadSeq = 0
|
||||
/** Load an area from ČÚZK. A newer call supersedes one still in flight. */
|
||||
export async function liveLoad(p: LatLon, quietFallback: boolean): Promise<boolean> {
|
||||
const my = ++loadSeq
|
||||
const current = () => my === loadSeq
|
||||
batch(() => {
|
||||
busy.value = true
|
||||
progress.value = { done: 0, total: 0 }
|
||||
setStatus(() => t('st_loading'))
|
||||
})
|
||||
try {
|
||||
const d = await fetchArea(p.lon, p.lat, radius.value, (n, m) =>
|
||||
setStatus(() => t('st_progress', n, m)),
|
||||
)
|
||||
const r = radius.value
|
||||
const d = await fetchArea(p.lon, p.lat, r, (done, total) => {
|
||||
if (current()) progress.value = { done, total }
|
||||
})
|
||||
if (!current()) return false
|
||||
if (!d.buildings.length) {
|
||||
setStatus(() => t('st_none'), 'err')
|
||||
return false
|
||||
}
|
||||
applyData(d, p.lon, p.lat)
|
||||
writeHash(p, r)
|
||||
lastLoc.value = { lat: p.lat, lon: p.lon }
|
||||
const loc = `${p.lat.toFixed(5)}, ${p.lon.toFixed(5)}`,
|
||||
n = d.buildings.length,
|
||||
fails = d.fails
|
||||
setStatus(
|
||||
() =>
|
||||
t('st_loaded', loc, n) +
|
||||
(fails.length ? '\n' + t('st_baseFail', fails.length) + '\n' + fails.join('\n') : ''),
|
||||
fails.length ? 'err' : 'ok',
|
||||
)
|
||||
if (fails.length)
|
||||
setStatus(() => t('st_loaded', loc, n) + ' ' + t('st_baseFail', fails.length), 'warn', fails)
|
||||
else setStatus(() => t('st_loaded', loc, n), 'ok')
|
||||
return true
|
||||
} catch (e) {
|
||||
if (!current()) return false
|
||||
const msg = errMsg(e)
|
||||
setStatus(() => (quietFallback ? t('st_fallback', msg) : t('st_err', msg)), 'err')
|
||||
return false
|
||||
} finally {
|
||||
if (current())
|
||||
batch(() => {
|
||||
busy.value = false
|
||||
progress.value = null
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const inCzechia = (p: LatLon) => p.lat >= 48 && p.lat <= 52 && p.lon >= 12 && p.lon <= 19
|
||||
|
||||
/** Load the area around the device's position. */
|
||||
export function locate() {
|
||||
if (!('geolocation' in navigator)) {
|
||||
setStatus(() => t('geo_unavailable'), 'err')
|
||||
return
|
||||
}
|
||||
locating.value = true
|
||||
setStatus(() => t('locating'))
|
||||
navigator.geolocation.getCurrentPosition(
|
||||
(pos) => {
|
||||
locating.value = false
|
||||
const p = { lat: pos.coords.latitude, lon: pos.coords.longitude }
|
||||
if (!inCzechia(p)) {
|
||||
setStatus(() => t('geo_outside'), 'err')
|
||||
return
|
||||
}
|
||||
locText.value = `${p.lat.toFixed(6)}, ${p.lon.toFixed(6)}`
|
||||
liveLoad(p, false)
|
||||
},
|
||||
(err) => {
|
||||
locating.value = false
|
||||
setStatus(
|
||||
() => t(err.code === err.PERMISSION_DENIED ? 'geo_denied' : 'geo_unavailable'),
|
||||
'err',
|
||||
)
|
||||
},
|
||||
{ enableHighAccuracy: true, timeout: 15000, maximumAge: 60000 },
|
||||
)
|
||||
}
|
||||
|
||||
export async function copyLink() {
|
||||
try {
|
||||
await navigator.clipboard.writeText(location.href)
|
||||
showToast(() => t('linkCopied'))
|
||||
} catch {
|
||||
// clipboard blocked (e.g. insecure context): let the user copy it manually
|
||||
window.prompt(t('copyLink'), location.href)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,3 +1,5 @@
|
|||
import type { BaseColor } from './theme'
|
||||
|
||||
/* ================= basemap styles ================= */
|
||||
/** ZABAGED layer ids on the ČÚZK MapServer. */
|
||||
export const ZAB_LAYERS = {
|
||||
|
|
@ -15,17 +17,18 @@ export const ZAB_LAYERS = {
|
|||
}
|
||||
export type BaseKey = keyof typeof ZAB_LAYERS
|
||||
|
||||
/** Colours are palette keys (theme.ts), so the basemap follows light/dark mode. */
|
||||
interface PolyStyle {
|
||||
k: BaseKey
|
||||
t: 'poly'
|
||||
fill: string
|
||||
stroke?: string
|
||||
fill: BaseColor
|
||||
stroke?: BaseColor
|
||||
}
|
||||
/** m: width in true metres, min: minimum width in px */
|
||||
interface LineStyle {
|
||||
k: BaseKey
|
||||
t: 'line'
|
||||
c: string
|
||||
c: BaseColor
|
||||
m: number
|
||||
min: number
|
||||
dash?: number[]
|
||||
|
|
@ -34,17 +37,17 @@ export type BaseStyle = PolyStyle | LineStyle
|
|||
|
||||
// Drawn in this order (later entries on top)
|
||||
export const BASE: BaseStyle[] = [
|
||||
{ k: 'garden', t: 'poly', fill: '#e6efd6' },
|
||||
{ k: 'green', t: 'poly', fill: '#cfe4bd' },
|
||||
{ k: 'cemetery', t: 'poly', fill: '#c9d9bd', stroke: '#9bb08a' },
|
||||
{ k: 'parking', t: 'poly', fill: '#e2e2e2', stroke: '#c4c4c4' },
|
||||
{ k: 'water', t: 'poly', fill: '#a8cfe8', stroke: '#7fb2d6' },
|
||||
{ k: 'stream', t: 'line', c: '#7fb2d6', m: 2, min: 1.2 },
|
||||
{ k: 'path', t: 'line', c: '#b58b5a', m: 1, min: 0.8, dash: [2, 3] },
|
||||
{ k: 'track', t: 'line', c: '#c9a16b', m: 2, min: 1, dash: [6, 4] },
|
||||
{ k: 'rail', t: 'line', c: '#666666', m: 3, min: 1.2, dash: [8, 4] },
|
||||
{ k: 'street', t: 'line', c: '#9a9a9a', m: 7, min: 2.4 },
|
||||
{ k: 'street', t: 'line', c: '#ffffff', m: 5, min: 1.8 },
|
||||
{ k: 'road', t: 'line', c: '#b8862f', m: 11, min: 3.6 },
|
||||
{ k: 'road', t: 'line', c: '#ffe08a', m: 8.5, min: 2.8 },
|
||||
{ k: 'garden', t: 'poly', fill: 'garden' },
|
||||
{ k: 'green', t: 'poly', fill: 'green' },
|
||||
{ k: 'cemetery', t: 'poly', fill: 'cemetery', stroke: 'cemeteryEdge' },
|
||||
{ k: 'parking', t: 'poly', fill: 'parking', stroke: 'parkingEdge' },
|
||||
{ k: 'water', t: 'poly', fill: 'water', stroke: 'waterEdge' },
|
||||
{ k: 'stream', t: 'line', c: 'stream', m: 2, min: 1.2 },
|
||||
{ k: 'path', t: 'line', c: 'path', m: 1, min: 0.8, dash: [2, 3] },
|
||||
{ k: 'track', t: 'line', c: 'track', m: 2, min: 1, dash: [6, 4] },
|
||||
{ k: 'rail', t: 'line', c: 'rail', m: 3, min: 1.2, dash: [8, 4] },
|
||||
{ k: 'street', t: 'line', c: 'streetCasing', m: 7, min: 2.4 },
|
||||
{ k: 'street', t: 'line', c: 'street', m: 5, min: 1.8 },
|
||||
{ k: 'road', t: 'line', c: 'roadCasing', m: 11, min: 3.6 },
|
||||
{ k: 'road', t: 'line', c: 'road', m: 8.5, min: 2.8 },
|
||||
]
|
||||
|
|
|
|||
|
|
@ -1,5 +1,8 @@
|
|||
import { useSignalEffect } from '@preact/signals'
|
||||
import { useEffect } from 'preact/hooks'
|
||||
import { lang, t } from '../i18n'
|
||||
import { attachKeyboard } from '../interaction'
|
||||
import { toast } from '../state'
|
||||
import { MapView } from './MapView'
|
||||
import { Sidebar } from './Sidebar'
|
||||
|
||||
|
|
@ -8,10 +11,17 @@ export function App() {
|
|||
document.documentElement.lang = lang.value
|
||||
document.title = t('title') + ' – RÚIAN'
|
||||
})
|
||||
useEffect(attachKeyboard, [])
|
||||
const tst = toast.value
|
||||
return (
|
||||
<div id="app">
|
||||
<Sidebar />
|
||||
<MapView />
|
||||
{tst && (
|
||||
<div class="toast" key={tst.id} role="status">
|
||||
{tst.fn()}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,8 @@
|
|||
import { catLabel, catOf } from '../categories'
|
||||
import { catColor, catLabel, catOf } from '../categories'
|
||||
import { m2ll } from '../geo'
|
||||
import { ruianUseName, t } from '../i18n'
|
||||
import { sel } from '../state'
|
||||
import { Icon } from './ui/Icon'
|
||||
|
||||
const DASH = '—'
|
||||
const orDash = (v: number | null, unit = '') => (v == null ? DASH : v + unit)
|
||||
|
|
@ -10,19 +11,32 @@ const orDash = (v: number | null, unit = '') => (v == null ? DASH : v + unit)
|
|||
export function InfoPanel() {
|
||||
const b = sel.value
|
||||
if (!b) return null
|
||||
const ll = m2ll((b.bb[0] + b.bb[2]) / 2, (b.bb[1] + b.bb[3]) / 2)
|
||||
const cat = catOf(b),
|
||||
ll = m2ll((b.bb[0] + b.bb[2]) / 2, (b.bb[1] + b.bb[3]) / 2)
|
||||
const title = b.cp ? t('hn', b.cp) : t('nohn')
|
||||
return (
|
||||
<div id="info">
|
||||
<span class="x" title={t('close')} onClick={() => (sel.value = null)}>
|
||||
✕
|
||||
</span>
|
||||
<b>{b.cp ? t('hn', b.cp) : t('nohn')}</b>
|
||||
// key: replay the entry animation when another building is selected
|
||||
<div id="info" class="card info" key={title + b.bb.join()} role="dialog" aria-label={title}>
|
||||
<div class="info-head">
|
||||
<span class="sw" style={{ background: catColor(cat) }} />
|
||||
<div>
|
||||
<b>{title}</b>
|
||||
<div class="info-cat">{catLabel(cat)}</div>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
class="icon-btn x"
|
||||
title={t('close')}
|
||||
aria-label={t('close')}
|
||||
onClick={() => (sel.value = null)}
|
||||
>
|
||||
<Icon name="close" />
|
||||
</button>
|
||||
</div>
|
||||
<dl>
|
||||
<dt>{t('i_cat')}</dt>
|
||||
<dd>{catLabel(catOf(b))}</dd>
|
||||
<dt>{t('i_use')}</dt>
|
||||
<dd>
|
||||
{ruianUseName(b.use) || DASH} ({b.use || '?'})
|
||||
{ruianUseName(b.use) || DASH} <span class="muted">({b.use || '?'})</span>
|
||||
</dd>
|
||||
<dt>{t('i_flats')}</dt>
|
||||
<dd>{orDash(b.flats)}</dd>
|
||||
|
|
@ -33,7 +47,7 @@ export function InfoPanel() {
|
|||
<dt>{t('i_done')}</dt>
|
||||
<dd>{orDash(b.year)}</dd>
|
||||
<dt>{t('i_pos')}</dt>
|
||||
<dd>
|
||||
<dd class="mono">
|
||||
{ll[1].toFixed(6)}, {ll[0].toFixed(6)}
|
||||
</dd>
|
||||
</dl>
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import { catColor, catLabel, catList } from '../categories'
|
||||
import { t } from '../i18n'
|
||||
import { counts } from '../render'
|
||||
import { hidden } from '../state'
|
||||
import { focusCat, hidden } from '../state'
|
||||
|
||||
function toggle(key: string) {
|
||||
const next = new Set(hidden.value)
|
||||
|
|
@ -8,23 +9,54 @@ function toggle(key: string) {
|
|||
else next.add(key)
|
||||
hidden.value = next
|
||||
}
|
||||
/** Show only `key`; doing it again on the same category shows everything. */
|
||||
function only(key: string) {
|
||||
const others = catList().filter((k) => k !== key)
|
||||
const alreadyOnly = !hidden.value.has(key) && others.every((k) => hidden.value.has(k))
|
||||
hidden.value = alreadyOnly ? new Set() : new Set(others)
|
||||
}
|
||||
|
||||
/** Category list with counts; categories absent from the loaded area are not shown. */
|
||||
/**
|
||||
* Category list with counts; categories absent from the loaded area are not shown.
|
||||
* Hovering a row highlights that category on the map.
|
||||
*/
|
||||
export function Legend() {
|
||||
const cnt = counts(),
|
||||
hid = hidden.value
|
||||
const rows = catList().filter((k) => cnt[k])
|
||||
return (
|
||||
<div id="legend">
|
||||
{catList().map((key) => {
|
||||
const n = cnt[key] || 0
|
||||
if (!n) return null
|
||||
<div id="legend" onMouseLeave={() => (focusCat.value = null)}>
|
||||
{rows.map((key) => {
|
||||
const on = !hid.has(key)
|
||||
return (
|
||||
<label key={key} class={on ? 'leg' : 'leg off'}>
|
||||
<input type="checkbox" checked={on} onChange={() => toggle(key)} />
|
||||
<label
|
||||
key={key}
|
||||
class={on ? 'leg' : 'leg off'}
|
||||
title={t('onlyHint')}
|
||||
onMouseEnter={() => (focusCat.value = on ? key : null)}
|
||||
onClick={(e) => {
|
||||
if (!e.altKey) return
|
||||
e.preventDefault() // keep the checkbox from toggling as well
|
||||
only(key)
|
||||
}}
|
||||
onDblClick={(e) => {
|
||||
e.preventDefault()
|
||||
only(key)
|
||||
}}
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={on}
|
||||
onChange={() => {
|
||||
toggle(key)
|
||||
focusCat.value = null
|
||||
}}
|
||||
onFocus={() => (focusCat.value = on ? key : null)}
|
||||
onBlur={() => (focusCat.value = null)}
|
||||
/>
|
||||
<span class="sw" style={{ background: catColor(key) }} />
|
||||
<span class="lbl">{catLabel(key)}</span>
|
||||
<span class="n">{n}</span>
|
||||
<span class="n">{cnt[key]}</span>
|
||||
</label>
|
||||
)
|
||||
})}
|
||||
|
|
|
|||
25
src/components/LoadingOverlay.tsx
Normal file
25
src/components/LoadingOverlay.tsx
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
import { t } from '../i18n'
|
||||
import { progress } from '../state'
|
||||
import { Icon } from './ui/Icon'
|
||||
|
||||
/** Progress bar along the top of the map and a small pill while data is loading. */
|
||||
export function LoadingOverlay() {
|
||||
const p = progress.value
|
||||
const known = !!p && p.total > 0
|
||||
return (
|
||||
<div class={p ? 'loading on' : 'loading'} aria-hidden={!p}>
|
||||
<div class="bar">
|
||||
<span
|
||||
class={known ? '' : 'indet'}
|
||||
style={known ? { width: `${(p.done / p.total) * 100}%` } : undefined}
|
||||
/>
|
||||
</div>
|
||||
{p && (
|
||||
<div class="pill-float">
|
||||
<Icon name="spinner" />
|
||||
{known ? t('loadingPill', p.done, p.total) : t('loadingStart')}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
|
@ -1,14 +1,18 @@
|
|||
import { effect } from '@preact/signals'
|
||||
import { useEffect, useRef } from 'preact/hooks'
|
||||
import { catLabel, catOf } from '../categories'
|
||||
import { catColor, catLabel, catOf } from '../categories'
|
||||
import { t } from '../i18n'
|
||||
import { attachPointer, resize, zoomBy, zoomFit } from '../interaction'
|
||||
import { draw } from '../render'
|
||||
import { hover, vp } from '../state'
|
||||
import type { Building } from '../types'
|
||||
import { draw, drawScene, requestDraw, trackScene } from '../render'
|
||||
import { hover, S, vp } from '../state'
|
||||
import { LIGHT } from '../theme'
|
||||
import { InfoPanel } from './InfoPanel'
|
||||
import { LoadingOverlay } from './LoadingOverlay'
|
||||
import { Icon } from './ui/Icon'
|
||||
|
||||
const describe = (b: Building) => `${b.cp ? t('hn', b.cp) : t('nohn')} – ${catLabel(catOf(b))}`
|
||||
/** Height of the map covered by the mobile bottom sheet (CSS variable --sheet-cover). */
|
||||
const sheetCover = () =>
|
||||
parseFloat(getComputedStyle(document.documentElement).getPropertyValue('--sheet-cover')) || 0
|
||||
|
||||
export function MapView() {
|
||||
const stage = useRef<HTMLElement>(null),
|
||||
|
|
@ -19,32 +23,63 @@ export function MapView() {
|
|||
cv = canvas.current!
|
||||
vp.ctx = cv.getContext('2d')
|
||||
const detach = attachPointer(cv)
|
||||
const ro = new ResizeObserver(() => resize(s, cv))
|
||||
const onResize = () => resize(s, cv, sheetCover())
|
||||
const ro = new ResizeObserver(onResize)
|
||||
ro.observe(s)
|
||||
resize(s, cv)
|
||||
// Redraw whenever any signal the drawing reads changes (data, layers, mode, selection…).
|
||||
// Pan and zoom are not signals; they call draw() themselves.
|
||||
const stopDrawing = effect(() => draw())
|
||||
onResize()
|
||||
// Redraw (once per frame) whenever a signal the drawing reads changes: data, layers,
|
||||
// mode, selection, hover, legend focus, theme. Pan and zoom request redraws themselves.
|
||||
const stopDrawing = effect(() => {
|
||||
trackScene()
|
||||
requestDraw()
|
||||
})
|
||||
// print the map in the light palette, without hover/selection overlays
|
||||
const beforePrint = () => {
|
||||
if (vp.ctx) drawScene(vp.ctx, vp.W, vp.H, S.view, vp.DPR, { pal: LIGHT })
|
||||
}
|
||||
window.addEventListener('beforeprint', beforePrint)
|
||||
window.addEventListener('afterprint', draw)
|
||||
return () => {
|
||||
stopDrawing()
|
||||
ro.disconnect()
|
||||
detach()
|
||||
window.removeEventListener('beforeprint', beforePrint)
|
||||
window.removeEventListener('afterprint', draw)
|
||||
vp.ctx = null
|
||||
}
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<main id="stage" ref={stage}>
|
||||
<canvas id="cv" ref={canvas} />
|
||||
<div class="zoom">
|
||||
<button title={t('zoomIn')} onClick={() => zoomBy(1.5)}>
|
||||
+
|
||||
<canvas id="cv" ref={canvas} role="img" aria-label={t('mapLabel')} />
|
||||
<LoadingOverlay />
|
||||
<div class="zoom" role="group">
|
||||
<button
|
||||
type="button"
|
||||
class="map-btn"
|
||||
title={t('zoomIn')}
|
||||
aria-label={t('zoomIn')}
|
||||
onClick={() => zoomBy(1.6)}
|
||||
>
|
||||
<Icon name="plus" />
|
||||
</button>
|
||||
<button title={t('zoomOut')} onClick={() => zoomBy(1 / 1.5)}>
|
||||
−
|
||||
<button
|
||||
type="button"
|
||||
class="map-btn"
|
||||
title={t('zoomOut')}
|
||||
aria-label={t('zoomOut')}
|
||||
onClick={() => zoomBy(1 / 1.6)}
|
||||
>
|
||||
<Icon name="minus" />
|
||||
</button>
|
||||
<button title={t('fit')} style={{ fontSize: 13 }} onClick={zoomFit}>
|
||||
⤢
|
||||
<button
|
||||
type="button"
|
||||
class="map-btn"
|
||||
title={t('fit')}
|
||||
aria-label={t('fit')}
|
||||
onClick={zoomFit}
|
||||
>
|
||||
<Icon name="fit" />
|
||||
</button>
|
||||
</div>
|
||||
<Tooltip />
|
||||
|
|
@ -53,12 +88,25 @@ export function MapView() {
|
|||
)
|
||||
}
|
||||
|
||||
/** Hover label; flips to the other side of the cursor near the right/bottom edge. */
|
||||
function Tooltip() {
|
||||
const h = hover.value
|
||||
if (!h) return null
|
||||
const cat = catOf(h.b)
|
||||
const flipX = h.x > vp.W - 240,
|
||||
flipY = h.y > vp.H - 60
|
||||
return (
|
||||
<div id="tip" style={{ left: h.x + 14, top: h.y + 14 }}>
|
||||
{describe(h.b)}
|
||||
<div
|
||||
id="tip"
|
||||
style={{
|
||||
left: flipX ? undefined : h.x + 14,
|
||||
right: flipX ? vp.W - h.x + 14 : undefined,
|
||||
top: flipY ? undefined : h.y + 16,
|
||||
bottom: flipY ? vp.H - h.y + 12 : undefined,
|
||||
}}
|
||||
>
|
||||
<span class="sw" style={{ background: catColor(cat) }} />
|
||||
<b>{h.b.cp ? t('hn', h.b.cp) : t('nohn')}</b> {catLabel(cat)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,144 +1,267 @@
|
|||
import { batch } from '@preact/signals'
|
||||
import { useRef } from 'preact/hooks'
|
||||
import { liveLoad, setStatus } from '../actions'
|
||||
import { buildings } from '../categories'
|
||||
import { useRef, useState } from 'preact/hooks'
|
||||
import { copyLink, liveLoad, locate, setStatus } from '../actions'
|
||||
import { buildings, catList } from '../categories'
|
||||
import { exportCsv, exportPng, exportSvg } from '../export'
|
||||
import { parseLoc } from '../geo'
|
||||
import { lang, setLang, t, type Lang } from '../i18n'
|
||||
import { lang, t } from '../i18n'
|
||||
import {
|
||||
busy,
|
||||
DEFAULT_LOC,
|
||||
hidden,
|
||||
lastLoc,
|
||||
locating,
|
||||
locText,
|
||||
mixMin,
|
||||
mode,
|
||||
radius,
|
||||
rawBuildings,
|
||||
sheetOpen,
|
||||
showBase,
|
||||
showNums,
|
||||
status,
|
||||
} from '../state'
|
||||
import type { Mode } from '../types'
|
||||
import { Legend } from './Legend'
|
||||
import { StatusLine } from './StatusLine'
|
||||
import { Icon, type IconName } from './ui/Icon'
|
||||
import { Segmented } from './ui/Segmented'
|
||||
import { Switch } from './ui/Switch'
|
||||
|
||||
export function Sidebar() {
|
||||
const aside = useRef<HTMLElement>(null)
|
||||
return (
|
||||
<aside>
|
||||
<div class="head">
|
||||
<h1>
|
||||
{t('title')} <small>{t('subtitle')}</small>
|
||||
</h1>
|
||||
<select
|
||||
id="lang"
|
||||
aria-label="Language"
|
||||
value={lang.value}
|
||||
onChange={(e) => setLang(e.currentTarget.value as Lang)}
|
||||
>
|
||||
<option value="cs">CS</option>
|
||||
<option value="en">EN</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<aside ref={aside} class={sheetOpen.value ? 'panel open' : 'panel'}>
|
||||
<SheetHandle aside={aside} />
|
||||
<div class="panel-scroll">
|
||||
<Header />
|
||||
<section class="card">
|
||||
<LocationForm />
|
||||
|
||||
<h2>
|
||||
{t('layers')}{' '}
|
||||
<span style={{ textTransform: 'none', letterSpacing: 0 }}>
|
||||
{buildings.value.length ? t('nBuildings', buildings.value.length) : ''}
|
||||
</span>
|
||||
</h2>
|
||||
<Legend />
|
||||
|
||||
<StatusLine />
|
||||
</section>
|
||||
<LayersSection />
|
||||
<section>
|
||||
<h2>{t('display')}</h2>
|
||||
<DisplayOptions />
|
||||
|
||||
</section>
|
||||
<section>
|
||||
<h2>{t('export')}</h2>
|
||||
<div class="exp">
|
||||
<button class="ghost" onClick={exportPng}>
|
||||
PNG
|
||||
</button>
|
||||
<button class="ghost" onClick={exportSvg}>
|
||||
SVG
|
||||
</button>
|
||||
<button class="ghost" onClick={exportCsv}>
|
||||
{t('csv')}
|
||||
</button>
|
||||
<button class="ghost" onClick={() => window.print()}>
|
||||
{t('print')}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<ExportButtons />
|
||||
</section>
|
||||
<details class="about">
|
||||
<summary>
|
||||
<Icon name="info" />
|
||||
{t('about')}
|
||||
<Icon name="chevron" class="icon chev" />
|
||||
</summary>
|
||||
{/* the note contains <br> line breaks and comes only from our own translations */}
|
||||
<p class="note" dangerouslySetInnerHTML={{ __html: t('note') }} />
|
||||
<p class="note">{t('shortcuts')}</p>
|
||||
</details>
|
||||
</div>
|
||||
</aside>
|
||||
)
|
||||
}
|
||||
|
||||
/** Drag handle of the mobile bottom sheet: tap to toggle, drag to open/close. Hidden on desktop. */
|
||||
function SheetHandle({ aside }: { aside: { current: HTMLElement | null } }) {
|
||||
const start = useRef<{ y: number; open: boolean } | null>(null)
|
||||
const setDrag = (px: number | null) => {
|
||||
const el = aside.current
|
||||
if (!el) return
|
||||
el.classList.toggle('dragging', px !== null)
|
||||
el.style.setProperty('--drag', px === null ? '0px' : px + 'px')
|
||||
}
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
class="sheet-handle"
|
||||
aria-label={t('panel')}
|
||||
aria-expanded={sheetOpen.value}
|
||||
onPointerDown={(e) => {
|
||||
e.currentTarget.setPointerCapture(e.pointerId)
|
||||
start.current = { y: e.clientY, open: sheetOpen.value }
|
||||
}}
|
||||
onPointerMove={(e) => {
|
||||
if (!start.current) return
|
||||
const dy = e.clientY - start.current.y
|
||||
if (Math.abs(dy) > 4) setDrag(dy)
|
||||
}}
|
||||
onPointerUp={(e) => {
|
||||
const s = start.current
|
||||
start.current = null
|
||||
if (!s) return
|
||||
const dy = e.clientY - s.y
|
||||
setDrag(null)
|
||||
if (Math.abs(dy) <= 4) sheetOpen.value = !s.open // a tap
|
||||
else sheetOpen.value = dy < 0
|
||||
}}
|
||||
onPointerCancel={() => {
|
||||
start.current = null
|
||||
setDrag(null)
|
||||
}}
|
||||
>
|
||||
<span />
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
function Header() {
|
||||
return (
|
||||
<header class="head">
|
||||
<div>
|
||||
<h1>{t('title')}</h1>
|
||||
<p class="sub">{t('subtitle')}</p>
|
||||
</div>
|
||||
<Segmented
|
||||
size="sm"
|
||||
label={t('lang')}
|
||||
value={lang.value}
|
||||
onChange={(v) => (lang.value = v)}
|
||||
options={[
|
||||
{ value: 'cs', label: 'CS' },
|
||||
{ value: 'en', label: 'EN' },
|
||||
]}
|
||||
/>
|
||||
</header>
|
||||
)
|
||||
}
|
||||
|
||||
function LocationForm() {
|
||||
const loc = useRef<HTMLInputElement>(null)
|
||||
const load = () => {
|
||||
const p = parseLoc(loc.current?.value ?? '')
|
||||
const p = parseLoc(locText.value)
|
||||
if (!p) setStatus(() => t('st_badLoc'), 'err')
|
||||
else liveLoad(p, false)
|
||||
}
|
||||
const st = status.value
|
||||
const r = radius.value,
|
||||
pct = ((r - 100) / (700 - 100)) * 100
|
||||
return (
|
||||
<>
|
||||
<label for="loc">{t('locLabel')}</label>
|
||||
<label class="field-label" for="loc">
|
||||
{t('locLabel')}
|
||||
</label>
|
||||
<div class="input-group">
|
||||
<input
|
||||
id="loc"
|
||||
ref={loc}
|
||||
type="text"
|
||||
defaultValue={DEFAULT_LOC}
|
||||
value={locText.value}
|
||||
spellcheck={false}
|
||||
autocomplete="off"
|
||||
onInput={(e) => (locText.value = e.currentTarget.value)}
|
||||
onFocus={(e) => {
|
||||
sheetOpen.value = true
|
||||
e.currentTarget.select()
|
||||
}}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' && !busy.value) load()
|
||||
if (e.key === 'Enter') load()
|
||||
}}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
class="icon-btn"
|
||||
title={t('locate')}
|
||||
aria-label={t('locate')}
|
||||
disabled={locating.value}
|
||||
onClick={locate}
|
||||
>
|
||||
<Icon name={locating.value ? 'spinner' : 'locate'} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<label for="radius">
|
||||
{t('radius')} <output>{radius.value} m</output>
|
||||
<div class="range-head">
|
||||
<label class="field-label" for="radius">
|
||||
{t('radius')}
|
||||
</label>
|
||||
<output class="badge" for="radius">
|
||||
{r} m
|
||||
</output>
|
||||
</div>
|
||||
<input
|
||||
id="radius"
|
||||
type="range"
|
||||
min={100}
|
||||
max={700}
|
||||
step={50}
|
||||
value={radius.value}
|
||||
value={r}
|
||||
style={{ '--fill': pct + '%' }}
|
||||
onInput={(e) => (radius.value = +e.currentTarget.value)}
|
||||
/>
|
||||
|
||||
<div class="row">
|
||||
<button disabled={busy.value} onClick={load}>
|
||||
<button type="button" class="btn primary grow" onClick={load}>
|
||||
{busy.value && <Icon name="spinner" />}
|
||||
{t('load')}
|
||||
</button>
|
||||
</div>
|
||||
<div id="status" class={st?.cls}>
|
||||
{st?.fn()}
|
||||
<button
|
||||
type="button"
|
||||
class="btn ghost square"
|
||||
title={t('copyLink')}
|
||||
aria-label={t('copyLink')}
|
||||
disabled={!lastLoc.value}
|
||||
onClick={copyLink}
|
||||
>
|
||||
<Icon name="link" />
|
||||
</button>
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
function LayersSection() {
|
||||
const n = buildings.value.length
|
||||
const setAll = (show: boolean) => (hidden.value = show ? new Set() : new Set(catList()))
|
||||
return (
|
||||
<section>
|
||||
<div class="sec-head">
|
||||
<h2>
|
||||
{t('layers')}
|
||||
{n > 0 && <span class="pill">{t('nBuildings', n)}</span>}
|
||||
</h2>
|
||||
{n > 0 && (
|
||||
<div class="sec-actions">
|
||||
<button type="button" class="link" onClick={() => setAll(true)}>
|
||||
{t('all')}
|
||||
</button>
|
||||
<button type="button" class="link" onClick={() => setAll(false)}>
|
||||
{t('none')}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<Legend />
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
function DisplayOptions() {
|
||||
return (
|
||||
<>
|
||||
<h2>{t('display')}</h2>
|
||||
<label for="colormode">{t('colorMode')}</label>
|
||||
<select
|
||||
id="colormode"
|
||||
<div class="stack">
|
||||
<div>
|
||||
<span class="field-label" id="colormode-label">
|
||||
{t('colorMode')}
|
||||
</span>
|
||||
<Segmented<Mode>
|
||||
label={t('colorMode')}
|
||||
value={mode.value}
|
||||
onChange={(e) => {
|
||||
const m = e.currentTarget.value as Mode
|
||||
onChange={(m) =>
|
||||
batch(() => {
|
||||
mode.value = m
|
||||
hidden.value = new Set() // category keys differ between modes
|
||||
})
|
||||
}}
|
||||
>
|
||||
<option value="simple">{t('modeSimple')}</option>
|
||||
<option value="detailed">{t('modeDetailed')}</option>
|
||||
</select>
|
||||
}
|
||||
options={[
|
||||
{ value: 'simple', label: t('modeSimple').split(' – ')[0] },
|
||||
{ value: 'detailed', label: t('modeDetailed').split(' – ')[0] },
|
||||
]}
|
||||
/>
|
||||
<p class="hint">
|
||||
{(mode.value === 'simple' ? t('modeSimple') : t('modeDetailed')).split(' – ')[1]}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<label for="mixrule">{t('mixLabel')}</label>
|
||||
<div>
|
||||
<label class="field-label" for="mixrule">
|
||||
{t('mixLabel')}
|
||||
</label>
|
||||
<div class="select">
|
||||
<select
|
||||
id="mixrule"
|
||||
value={String(mixMin.value)}
|
||||
|
|
@ -148,23 +271,62 @@ function DisplayOptions() {
|
|||
<option value="2">{t('mix2')}</option>
|
||||
<option value="0">{t('mix0')}</option>
|
||||
</select>
|
||||
<Icon name="chevron" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<label class="chk">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={showBase.value}
|
||||
onChange={(e) => (showBase.value = e.currentTarget.checked)}
|
||||
/>{' '}
|
||||
<div class="switches">
|
||||
<Switch checked={showBase.value} onChange={(v) => (showBase.value = v)}>
|
||||
{t('optBase')}
|
||||
</label>
|
||||
<label class="chk">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={showNums.value}
|
||||
onChange={(e) => (showNums.value = e.currentTarget.checked)}
|
||||
/>{' '}
|
||||
</Switch>
|
||||
<Switch checked={showNums.value} onChange={(v) => (showNums.value = v)}>
|
||||
{t('optNums')}
|
||||
</label>
|
||||
</>
|
||||
</Switch>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function ExportButtons() {
|
||||
const ready = rawBuildings.value.length > 0
|
||||
return (
|
||||
<div class="exp">
|
||||
<ExportButton icon="image" label="PNG" run={exportPng} disabled={!ready} />
|
||||
<ExportButton icon="vector" label="SVG" run={exportSvg} disabled={!ready} />
|
||||
<ExportButton icon="table" label={t('csv')} run={exportCsv} disabled={!ready} />
|
||||
<ExportButton icon="print" label={t('print')} run={() => window.print()} confirm={false} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function ExportButton({
|
||||
icon,
|
||||
label,
|
||||
run,
|
||||
disabled,
|
||||
confirm = true,
|
||||
}: {
|
||||
icon: IconName
|
||||
label: string
|
||||
run: () => void
|
||||
disabled?: boolean
|
||||
confirm?: boolean
|
||||
}) {
|
||||
const [done, setDone] = useState(false)
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
class={done ? 'btn ghost done' : 'btn ghost'}
|
||||
disabled={disabled}
|
||||
onClick={() => {
|
||||
run()
|
||||
if (!confirm) return
|
||||
setDone(true)
|
||||
setTimeout(() => setDone(false), 1600)
|
||||
}}
|
||||
>
|
||||
<Icon name={done ? 'check' : icon} />
|
||||
{done ? t('saved') : label}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
|
|
|||
49
src/components/StatusLine.tsx
Normal file
49
src/components/StatusLine.tsx
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
import { useEffect, useState } from 'preact/hooks'
|
||||
import { t } from '../i18n'
|
||||
import { busy, locating, status } from '../state'
|
||||
import { Icon, type IconName } from './ui/Icon'
|
||||
|
||||
/** Status of the last action; success messages fade to muted after a few seconds. */
|
||||
export function StatusLine() {
|
||||
const st = status.value
|
||||
const [faded, setFaded] = useState(false)
|
||||
useEffect(() => {
|
||||
setFaded(false)
|
||||
if (st?.cls !== 'ok') return
|
||||
const id = setTimeout(() => setFaded(true), 5000)
|
||||
return () => clearTimeout(id)
|
||||
}, [st])
|
||||
if (!st) return null
|
||||
const working = busy.value || locating.value
|
||||
const icon: IconName =
|
||||
st.cls === 'err' || st.cls === 'warn'
|
||||
? 'alert'
|
||||
: st.cls === 'ok'
|
||||
? 'check'
|
||||
: working
|
||||
? 'spinner'
|
||||
: 'info'
|
||||
return (
|
||||
<div
|
||||
id="status"
|
||||
class={`status ${st.cls ?? 'info'}${faded ? ' faded' : ''}`}
|
||||
role="status"
|
||||
aria-live="polite"
|
||||
>
|
||||
<Icon name={icon} />
|
||||
<div class="status-body">
|
||||
<span class="status-text">{st.fn()}</span>
|
||||
{st.details && st.details.length > 0 && (
|
||||
<details>
|
||||
<summary>{t('details')}</summary>
|
||||
<ul>
|
||||
{st.details.map((d) => (
|
||||
<li key={d}>{d}</li>
|
||||
))}
|
||||
</ul>
|
||||
</details>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
95
src/components/ui/Icon.tsx
Normal file
95
src/components/ui/Icon.tsx
Normal file
|
|
@ -0,0 +1,95 @@
|
|||
import type { SVGAttributes } from 'preact'
|
||||
|
||||
/* Small inline icon set (24×24, stroked with currentColor) – no icon font or dependency. */
|
||||
const P = {
|
||||
download: (
|
||||
<>
|
||||
<path d="M12 4v11m0 0-4.5-4.5M12 15l4.5-4.5" />
|
||||
<path d="M5 20h14" />
|
||||
</>
|
||||
),
|
||||
image: (
|
||||
<>
|
||||
<rect x="3" y="4" width="18" height="16" rx="2" />
|
||||
<circle cx="9" cy="10" r="1.6" />
|
||||
<path d="m21 16-5-5-9 9" />
|
||||
</>
|
||||
),
|
||||
vector: (
|
||||
<>
|
||||
<path d="M5 19 12 5l7 14" />
|
||||
<circle cx="12" cy="5" r="1.8" />
|
||||
<circle cx="5" cy="19" r="1.8" />
|
||||
<circle cx="19" cy="19" r="1.8" />
|
||||
</>
|
||||
),
|
||||
table: (
|
||||
<>
|
||||
<rect x="3" y="4" width="18" height="16" rx="2" />
|
||||
<path d="M3 10h18M3 15h18M10 4v16" />
|
||||
</>
|
||||
),
|
||||
print: (
|
||||
<>
|
||||
<path d="M7 9V3h10v6" />
|
||||
<rect x="3" y="9" width="18" height="8" rx="2" />
|
||||
<path d="M7 14h10v7H7z" />
|
||||
</>
|
||||
),
|
||||
locate: (
|
||||
<>
|
||||
<circle cx="12" cy="12" r="4" />
|
||||
<path d="M12 2v3M12 19v3M2 12h3M19 12h3" />
|
||||
</>
|
||||
),
|
||||
link: (
|
||||
<>
|
||||
<path d="M10 14a4.5 4.5 0 0 0 6.4 0l3-3a4.5 4.5 0 0 0-6.4-6.4L11.5 6" />
|
||||
<path d="M14 10a4.5 4.5 0 0 0-6.4 0l-3 3a4.5 4.5 0 0 0 6.4 6.4l1.5-1.4" />
|
||||
</>
|
||||
),
|
||||
plus: <path d="M12 5v14M5 12h14" />,
|
||||
minus: <path d="M5 12h14" />,
|
||||
fit: <path d="M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5" />,
|
||||
close: <path d="m6 6 12 12M18 6 6 18" />,
|
||||
chevron: <path d="m6 9 6 6 6-6" />,
|
||||
check: <path d="m5 12.5 4.5 4.5L19 7" />,
|
||||
alert: (
|
||||
<>
|
||||
<circle cx="12" cy="12" r="9" />
|
||||
<path d="M12 7.5v5.5M12 16.5h.01" />
|
||||
</>
|
||||
),
|
||||
info: (
|
||||
<>
|
||||
<circle cx="12" cy="12" r="9" />
|
||||
<path d="M12 11v5.5M12 7.5h.01" />
|
||||
</>
|
||||
),
|
||||
spinner: <path d="M12 3a9 9 0 1 0 9 9" />,
|
||||
}
|
||||
export type IconName = keyof typeof P
|
||||
|
||||
export function Icon({
|
||||
name,
|
||||
size = 16,
|
||||
...rest
|
||||
}: { name: IconName; size?: number } & SVGAttributes<SVGSVGElement>) {
|
||||
return (
|
||||
<svg
|
||||
class={name === 'spinner' ? 'icon spin' : 'icon'}
|
||||
width={size}
|
||||
height={size}
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width={2}
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
aria-hidden="true"
|
||||
{...rest}
|
||||
>
|
||||
{P[name]}
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
61
src/components/ui/Segmented.tsx
Normal file
61
src/components/ui/Segmented.tsx
Normal file
|
|
@ -0,0 +1,61 @@
|
|||
import { useRef } from 'preact/hooks'
|
||||
|
||||
export interface SegOption<T extends string> {
|
||||
value: T
|
||||
label: string
|
||||
}
|
||||
|
||||
/** Segmented control: a radio group of buttons with roving focus and arrow-key navigation. */
|
||||
export function Segmented<T extends string>({
|
||||
options,
|
||||
value,
|
||||
onChange,
|
||||
label,
|
||||
size = 'md',
|
||||
}: {
|
||||
options: SegOption<T>[]
|
||||
value: T
|
||||
onChange: (v: T) => void
|
||||
label: string
|
||||
size?: 'sm' | 'md'
|
||||
}) {
|
||||
const root = useRef<HTMLDivElement>(null)
|
||||
const idx = Math.max(
|
||||
0,
|
||||
options.findIndex((o) => o.value === value),
|
||||
)
|
||||
const move = (d: number) => {
|
||||
const next = (idx + d + options.length) % options.length
|
||||
onChange(options[next].value)
|
||||
root.current?.querySelectorAll<HTMLButtonElement>('button')[next]?.focus()
|
||||
}
|
||||
return (
|
||||
<div
|
||||
ref={root}
|
||||
class={`seg seg-${size}`}
|
||||
role="radiogroup"
|
||||
aria-label={label}
|
||||
style={{ '--n': options.length, '--i': idx }}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'ArrowRight' || e.key === 'ArrowDown') move(1)
|
||||
else if (e.key === 'ArrowLeft' || e.key === 'ArrowUp') move(-1)
|
||||
else return
|
||||
e.preventDefault()
|
||||
}}
|
||||
>
|
||||
<span class="seg-thumb" aria-hidden="true" />
|
||||
{options.map((o) => (
|
||||
<button
|
||||
key={o.value}
|
||||
type="button"
|
||||
role="radio"
|
||||
aria-checked={o.value === value}
|
||||
tabIndex={o.value === value ? 0 : -1}
|
||||
onClick={() => onChange(o.value)}
|
||||
>
|
||||
{o.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
25
src/components/ui/Switch.tsx
Normal file
25
src/components/ui/Switch.tsx
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
import type { ComponentChildren } from 'preact'
|
||||
|
||||
/** A checkbox presented as an on/off switch. */
|
||||
export function Switch({
|
||||
checked,
|
||||
onChange,
|
||||
children,
|
||||
}: {
|
||||
checked: boolean
|
||||
onChange: (v: boolean) => void
|
||||
children: ComponentChildren
|
||||
}) {
|
||||
return (
|
||||
<label class="switch">
|
||||
<input
|
||||
type="checkbox"
|
||||
role="switch"
|
||||
checked={checked}
|
||||
onChange={(e) => onChange(e.currentTarget.checked)}
|
||||
/>
|
||||
<span class="switch-track" aria-hidden="true" />
|
||||
<span class="switch-label">{children}</span>
|
||||
</label>
|
||||
)
|
||||
}
|
||||
|
|
@ -4,6 +4,7 @@ import { m2ll } from './geo'
|
|||
import { ruianUseName } from './i18n'
|
||||
import { drawLegend, drawScene, legendLayout, pxPerMeter } from './render'
|
||||
import { base, hidden, S, showBase, vp } from './state'
|
||||
import { LIGHT } from './theme'
|
||||
import type { Ring } from './types'
|
||||
|
||||
/* ================= export ================= */
|
||||
|
|
@ -47,15 +48,15 @@ export function exportSvg() {
|
|||
const { e, colW, rows, h: lh } = legendLayout(W)
|
||||
let o = ''
|
||||
o += `<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${H + lh}" viewBox="0 0 ${W} ${H + lh}"><defs><clipPath id="c"><rect width="${W}" height="${H}"/></clipPath></defs>`
|
||||
o += `<rect width="${W}" height="${H}" fill="#f5f2ea"/><g clip-path="url(#c)" stroke-linejoin="round" stroke-linecap="round">`
|
||||
o += `<rect width="${W}" height="${H}" fill="${LIGHT.bg}"/><g clip-path="url(#c)" stroke-linejoin="round" stroke-linecap="round">`
|
||||
if (showBase.value)
|
||||
for (const st of BASE) {
|
||||
const rings = base.value[st.k]
|
||||
if (!rings || !rings.length) continue
|
||||
if (st.t === 'poly')
|
||||
o += `<path d="${d(rings, true)}" fill="${st.fill}" fill-rule="evenodd"${st.stroke ? ` stroke="${st.stroke}" stroke-width="1"` : ''}/>`
|
||||
o += `<path d="${d(rings, true)}" fill="${LIGHT.base[st.fill]}" fill-rule="evenodd"${st.stroke ? ` stroke="${LIGHT.base[st.stroke]}" stroke-width="1"` : ''}/>`
|
||||
else
|
||||
o += `<path d="${d(rings, false)}" fill="none" stroke="${st.c}" stroke-width="${Math.max(st.min, st.m * ppm).toFixed(1)}"${st.dash ? ` stroke-dasharray="${st.dash.map((x) => x * Math.max(1, ppm / 2)).join(' ')}"` : ''}/>`
|
||||
o += `<path d="${d(rings, false)}" fill="none" stroke="${LIGHT.base[st.c]}" stroke-width="${Math.max(st.min, st.m * ppm).toFixed(1)}"${st.dash ? ` stroke-dasharray="${st.dash.map((x) => x * Math.max(1, ppm / 2)).join(' ')}"` : ''}/>`
|
||||
}
|
||||
for (const key of catOrder()) {
|
||||
if (hidden.value.has(key)) continue
|
||||
|
|
|
|||
30
src/fetch.ts
30
src/fetch.ts
|
|
@ -123,27 +123,23 @@ export async function fetchArea(
|
|||
const env = [lon - dLon, lat - dLat, lon + dLon, lat + dLat].map((v) => v.toFixed(6)).join(',')
|
||||
const fields = 'cisladomovni,zpusobvyuzitikod,pocetbytu,pocetpodlazi,zastavenaplocha,dokonceni'
|
||||
const keys = Object.keys(ZAB_LAYERS) as BaseKey[]
|
||||
const tasks = [
|
||||
() => queryAll(RUIAN, fields, env),
|
||||
...keys.map((k) => () => baseLayer(ZAB_LAYERS[k], env)),
|
||||
]
|
||||
const total = keys.length + 1
|
||||
let done = 0
|
||||
const res = await pool(
|
||||
tasks.map((fn) => async () => {
|
||||
try {
|
||||
return await fn()
|
||||
} finally {
|
||||
if (onProgress) onProgress(++done, tasks.length)
|
||||
}
|
||||
}),
|
||||
4,
|
||||
const tick = () => onProgress?.(++done, total)
|
||||
// Buildings and basemap layers load in parallel (4 requests at a time overall). If the
|
||||
// buildings query fails there is nothing to show, so fail right away instead of waiting
|
||||
// for the basemap retries.
|
||||
const buildingsP = queryAll(RUIAN, fields, env).finally(tick)
|
||||
const basesP = pool(
|
||||
keys.map((k) => () => baseLayer(ZAB_LAYERS[k], env).finally(tick)),
|
||||
3,
|
||||
)
|
||||
const first = res[0]
|
||||
if (!first.ok) throw first.e
|
||||
const features = await buildingsP
|
||||
const res = await basesP
|
||||
const base: BaseData = {},
|
||||
fails: string[] = []
|
||||
keys.forEach((k, i) => {
|
||||
const r = res[i + 1]
|
||||
const r = res[i]
|
||||
if (r.ok) base[k] = r.v.flatMap(ringsOf)
|
||||
else {
|
||||
base[k] = []
|
||||
|
|
@ -151,7 +147,7 @@ export async function fetchArea(
|
|||
}
|
||||
})
|
||||
type N = number | null
|
||||
const buildings = first.v
|
||||
const buildings = features
|
||||
.map((f) => {
|
||||
const a = lowerKeys(f.attributes)
|
||||
return mkBuilding(
|
||||
|
|
|
|||
77
src/i18n.ts
77
src/i18n.ts
|
|
@ -1,4 +1,4 @@
|
|||
import { signal } from '@preact/signals'
|
||||
import { persisted } from './persist'
|
||||
|
||||
/* ================= i18n ================= */
|
||||
export type Lang = 'en' | 'cs'
|
||||
|
|
@ -24,11 +24,11 @@ const en = {
|
|||
csv: 'CSV table',
|
||||
print: 'Print / PDF',
|
||||
note: 'Colours come from the registered use (způsob využití) in RÚIAN. RÚIAN has no “mixed” class, so orange marks buildings whose registered use is non-residential (shop, civic, technical…) but which also have flats. Apartment blocks with shops on the ground floor are still registered as apartment buildings and stay red.<br><br>Data © ČÚZK (RÚIAN, ZABAGED). Drag to pan, scroll or pinch to zoom, click a building for details.',
|
||||
nBuildings: (n: number) => `· ${n} buildings`,
|
||||
nBuildings: (n: number) => `${n} buildings`,
|
||||
st_loading: 'Loading buildings and basemap from ČÚZK…',
|
||||
st_progress: (n: number, m: number) => `Loading from ČÚZK… ${n}/${m} requests done`,
|
||||
st_loaded: (loc: string, n: number) => `${loc}: ${n} buildings.`,
|
||||
st_baseFail: (n: number) => `${n} basemap layer(s) failed:`,
|
||||
st_baseFail: (n: number) => `${n} basemap layer(s) could not be loaded`,
|
||||
st_none: 'No buildings found here (outside Czechia, or an empty area).',
|
||||
st_badLoc: 'Could not read a location. Paste a Mapy.com link or "50.8171, 14.9687".',
|
||||
st_err: (e: string) =>
|
||||
|
|
@ -49,10 +49,30 @@ const en = {
|
|||
b_green: 'Green area / garden',
|
||||
b_road: 'Main road',
|
||||
b_street: 'Street',
|
||||
zoomIn: 'Zoom in',
|
||||
zoomOut: 'Zoom out',
|
||||
fit: 'Fit',
|
||||
zoomIn: 'Zoom in (+)',
|
||||
zoomOut: 'Zoom out (−)',
|
||||
fit: 'Fit area (0)',
|
||||
close: 'Close',
|
||||
lang: 'Language',
|
||||
area: 'Area',
|
||||
locate: 'Use my location',
|
||||
locating: 'Finding your location…',
|
||||
geo_denied: 'Location access was denied.',
|
||||
geo_unavailable: 'Your location is not available.',
|
||||
geo_outside: 'Your location is outside Czechia.',
|
||||
copyLink: 'Copy link to this area',
|
||||
linkCopied: 'Link copied to clipboard',
|
||||
details: 'Details',
|
||||
about: 'About the data',
|
||||
all: 'All',
|
||||
none: 'None',
|
||||
onlyHint: 'Alt-click or double-click to show only this category',
|
||||
loadingPill: (n: number, m: number) => `Loading ${n}/${m}`,
|
||||
loadingStart: 'Connecting…',
|
||||
panel: 'Show or hide the panel',
|
||||
saved: 'Saved',
|
||||
shortcuts: 'Shortcuts: + / − zoom · 0 fit · arrow keys pan · Esc close',
|
||||
mapLabel: 'Map of building use',
|
||||
'cat.res': 'Residential – family house',
|
||||
'cat.unit': 'Unit housing – apartment building',
|
||||
'cat.rec': 'Recreational / garden house (chata)',
|
||||
|
|
@ -118,7 +138,7 @@ const cs: Dict = {
|
|||
csv: 'Tabulka CSV',
|
||||
print: 'Tisk / PDF',
|
||||
note: 'Barvy vycházejí ze způsobu využití zapsaného v RÚIAN. RÚIAN nemá třídu „smíšený“, proto oranžová označuje budovy, jejichž zapsané využití je nebytové (obchod, občanská vybavenost, technické…), ale které mají i byty. Bytové domy s obchodem v přízemí jsou v registru vedeny jako bytové domy, a zůstávají proto červené.<br><br>Data © ČÚZK (RÚIAN, ZABAGED). Tažením posouváte mapu, kolečkem nebo štípnutím přibližujete, kliknutím na budovu zobrazíte podrobnosti.',
|
||||
nBuildings: (n) => `· ${n} budov`,
|
||||
nBuildings: (n) => `${n} budov`,
|
||||
st_loading: 'Načítám budovy a podklad z ČÚZK…',
|
||||
st_progress: (n, m) => `Načítání z ČÚZK… hotovo ${n}/${m} dotazů`,
|
||||
st_loaded: (loc, n) => `${loc}: ${n} budov.`,
|
||||
|
|
@ -143,10 +163,30 @@ const cs: Dict = {
|
|||
b_green: 'Zeleň / zahrady',
|
||||
b_road: 'Silnice',
|
||||
b_street: 'Ulice',
|
||||
zoomIn: 'Přiblížit',
|
||||
zoomOut: 'Oddálit',
|
||||
fit: 'Celá oblast',
|
||||
zoomIn: 'Přiblížit (+)',
|
||||
zoomOut: 'Oddálit (−)',
|
||||
fit: 'Celá oblast (0)',
|
||||
close: 'Zavřít',
|
||||
lang: 'Jazyk',
|
||||
area: 'Oblast',
|
||||
locate: 'Použít moji polohu',
|
||||
locating: 'Zjišťuji vaši polohu…',
|
||||
geo_denied: 'Přístup k poloze byl zamítnut.',
|
||||
geo_unavailable: 'Poloha není k dispozici.',
|
||||
geo_outside: 'Vaše poloha je mimo Česko.',
|
||||
copyLink: 'Kopírovat odkaz na tuto oblast',
|
||||
linkCopied: 'Odkaz zkopírován do schránky',
|
||||
details: 'Podrobnosti',
|
||||
about: 'O datech',
|
||||
all: 'Vše',
|
||||
none: 'Nic',
|
||||
onlyHint: 'Alt+kliknutím nebo dvojklikem zobrazíte jen tuto kategorii',
|
||||
loadingPill: (n, m) => `Načítání ${n}/${m}`,
|
||||
loadingStart: 'Připojuji…',
|
||||
panel: 'Zobrazit nebo skrýt panel',
|
||||
saved: 'Uloženo',
|
||||
shortcuts: 'Zkratky: + / − přiblížení · 0 celá oblast · šipky posun · Esc zavřít',
|
||||
mapLabel: 'Mapa využití budov',
|
||||
'cat.res': 'Bydlení – rodinný dům',
|
||||
'cat.unit': 'Bytové domy',
|
||||
'cat.rec': 'Rekreace / zahrádkářské chaty',
|
||||
|
|
@ -190,11 +230,6 @@ const cs: Dict = {
|
|||
|
||||
const L: Record<Lang, Dict> = { en, cs }
|
||||
function detectLang(): Lang {
|
||||
let saved: string | null = null
|
||||
try {
|
||||
saved = localStorage.getItem('bum-lang')
|
||||
} catch {}
|
||||
if (saved === 'cs' || saved === 'en') return saved
|
||||
const prefs =
|
||||
navigator.languages && navigator.languages.length
|
||||
? navigator.languages
|
||||
|
|
@ -205,21 +240,15 @@ function detectLang(): Lang {
|
|||
? 'cs'
|
||||
: 'en'
|
||||
}
|
||||
/** Current UI language. Components that call t() re-render when it changes. */
|
||||
export const lang = signal<Lang>(detectLang())
|
||||
export function setLang(l: Lang) {
|
||||
lang.value = l
|
||||
try {
|
||||
localStorage.setItem('bum-lang', l)
|
||||
} catch {}
|
||||
}
|
||||
/** Current UI language (remembered). Components that call t() re-render when it changes. */
|
||||
export const lang = persisted<Lang>('lang', detectLang(), (v) => v === 'cs' || v === 'en')
|
||||
|
||||
/** Translate a known message key; function-valued messages take typed arguments. */
|
||||
export function t<K extends MsgKey>(k: K, ...a: Args<K>): string {
|
||||
const v = L[lang.value][k] !== undefined ? L[lang.value][k] : L.en[k]
|
||||
return typeof v === 'function' ? (v as (...x: unknown[]) => string)(...a) : (v as string)
|
||||
}
|
||||
/** Translate a key built at runtime (e.g. from data-i18n); falls back to the key itself. */
|
||||
/** Translate a key built at runtime (e.g. 'cat.' + key); falls back to the key itself. */
|
||||
export function tKey(k: string): string {
|
||||
const get = (d: Dict) => (d as unknown as Record<string, unknown>)[k]
|
||||
const v = get(L[lang.value]) !== undefined ? get(L[lang.value]) : get(L.en)
|
||||
|
|
|
|||
|
|
@ -1,7 +1,10 @@
|
|||
import { buildings } from './categories'
|
||||
import { draw, fitView } from './render'
|
||||
import { hidden, hover, S, sel, vp } from './state'
|
||||
import type { Building, Point, Ring } from './types'
|
||||
import { draw, fitTarget, requestDraw } from './render'
|
||||
import { hidden, hover, S, sel, sheetOpen, vp } from './state'
|
||||
import type { Building, Point, Ring, View } from './types'
|
||||
|
||||
const reducedMotion = () =>
|
||||
typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches
|
||||
|
||||
/* ================= hit testing ================= */
|
||||
function inRing(x: number, y: number, ring: Ring): boolean {
|
||||
|
|
@ -38,46 +41,108 @@ function pick(px: number, py: number): Building | null {
|
|||
return null
|
||||
}
|
||||
|
||||
/* ================= pan / zoom ================= */
|
||||
export function zoomAt(px: number, py: number, f: number) {
|
||||
/* ================= view animation ================= */
|
||||
const MIN_S = 0.02,
|
||||
MAX_S = 40
|
||||
const clampS = (s: number) => Math.min(Math.max(s, MIN_S), MAX_S)
|
||||
|
||||
let anim = 0
|
||||
/** Stop any running zoom animation or pan inertia. */
|
||||
function stopMotion() {
|
||||
if (anim) cancelAnimationFrame(anim)
|
||||
anim = 0
|
||||
}
|
||||
|
||||
const easeOutCubic = (k: number) => 1 - (1 - k) ** 3
|
||||
|
||||
/** Animate the view to `to` (scale interpolated logarithmically so zooming feels even). */
|
||||
export function animateTo(to: View, ms = 240) {
|
||||
stopMotion()
|
||||
if (reducedMotion()) {
|
||||
S.view = to
|
||||
requestDraw()
|
||||
return
|
||||
}
|
||||
const from = { ...S.view },
|
||||
t0 = performance.now()
|
||||
const step = (now: number) => {
|
||||
const k = Math.min(1, (now - t0) / ms),
|
||||
e = easeOutCubic(k)
|
||||
S.view = {
|
||||
cx: from.cx + (to.cx - from.cx) * e,
|
||||
cy: from.cy + (to.cy - from.cy) * e,
|
||||
s: from.s * (to.s / from.s) ** e,
|
||||
}
|
||||
draw()
|
||||
anim = k < 1 ? requestAnimationFrame(step) : 0
|
||||
}
|
||||
anim = requestAnimationFrame(step)
|
||||
}
|
||||
|
||||
/** View after zooming by factor f around screen point (px, py). */
|
||||
function zoomedView(px: number, py: number, f: number): View {
|
||||
const v = S.view,
|
||||
ns = Math.min(Math.max(v.s * f, 0.02), 40)
|
||||
ns = clampS(v.s * f)
|
||||
const x = (px - vp.W / 2) / v.s + v.cx,
|
||||
y = (vp.H / 2 - py) / v.s + v.cy
|
||||
v.s = ns
|
||||
v.cx = x - (px - vp.W / 2) / ns
|
||||
v.cy = y + (py - vp.H / 2) / ns
|
||||
draw()
|
||||
return { cx: x - (px - vp.W / 2) / ns, cy: y + (py - vp.H / 2) / ns, s: ns }
|
||||
}
|
||||
export const zoomBy = (f: number) => zoomAt(vp.W / 2, vp.H / 2, f)
|
||||
|
||||
/** Immediate zoom (wheel, pinch). */
|
||||
function zoomAt(px: number, py: number, f: number) {
|
||||
stopMotion()
|
||||
S.view = zoomedView(px, py, f)
|
||||
requestDraw()
|
||||
}
|
||||
/** Animated zoom around the centre of the map (buttons, keyboard). */
|
||||
export const zoomBy = (f: number) => animateTo(zoomedView(vp.W / 2, vp.H / 2, f))
|
||||
export function zoomFit() {
|
||||
fitView()
|
||||
draw()
|
||||
const v = fitTarget()
|
||||
if (v) animateTo(v, 320)
|
||||
}
|
||||
/** Animated pan by a fraction of the canvas size. */
|
||||
function panBy(fx: number, fy: number) {
|
||||
const v = S.view
|
||||
animateTo({ ...v, cx: v.cx + (fx * vp.W) / v.s, cy: v.cy - (fy * vp.H) / v.s }, 200)
|
||||
}
|
||||
|
||||
/** Match the canvas backing store to the stage size and redraw. */
|
||||
export function resize(stage: HTMLElement, cv: HTMLCanvasElement) {
|
||||
export function resize(stage: HTMLElement, cv: HTMLCanvasElement, insetB: number) {
|
||||
const r = stage.getBoundingClientRect()
|
||||
vp.DPR = Math.min(window.devicePixelRatio || 1, 3)
|
||||
const oldW = vp.W
|
||||
vp.W = Math.max(1, Math.floor(r.width))
|
||||
vp.H = Math.max(1, Math.floor(r.height))
|
||||
vp.insetB = insetB
|
||||
cv.width = vp.W * vp.DPR
|
||||
cv.height = vp.H * vp.DPR
|
||||
if (S.loaded && !oldW) fitView() // data arrived before the canvas had a size
|
||||
draw()
|
||||
if (S.loaded && !oldW) {
|
||||
const v = fitTarget() // data arrived before the canvas had a size
|
||||
if (v) S.view = v
|
||||
}
|
||||
draw() // synchronously: resizing the canvas has just cleared it
|
||||
}
|
||||
|
||||
/* ================= pointer ================= */
|
||||
/** Pointer/wheel handling on the map canvas. Returns a cleanup function. */
|
||||
export function attachPointer(cv: HTMLCanvasElement): () => void {
|
||||
const ptrs = new Map<number, Point>()
|
||||
let dragMoved = 0,
|
||||
lastPinch = 0
|
||||
// recent pointer positions for pan inertia
|
||||
let trail: { x: number; y: number; t: number }[] = []
|
||||
|
||||
const setHover = (b: Building | null, x: number, y: number) => {
|
||||
hover.value = b ? { b, x, y } : null
|
||||
cv.classList.toggle('over', !!b)
|
||||
}
|
||||
|
||||
const down = (e: PointerEvent) => {
|
||||
stopMotion()
|
||||
cv.setPointerCapture(e.pointerId)
|
||||
ptrs.set(e.pointerId, [e.offsetX, e.offsetY])
|
||||
dragMoved = 0
|
||||
trail = [{ x: e.offsetX, y: e.offsetY, t: e.timeStamp }]
|
||||
cv.classList.add('drag')
|
||||
if (ptrs.size === 2) {
|
||||
const [a, b] = [...ptrs.values()]
|
||||
|
|
@ -94,32 +159,65 @@ export function attachPointer(cv: HTMLCanvasElement): () => void {
|
|||
dragMoved += Math.abs(dx) + Math.abs(dy)
|
||||
S.view.cx -= dx / S.view.s
|
||||
S.view.cy += dy / S.view.s
|
||||
draw()
|
||||
hover.value = null
|
||||
trail.push({ x: e.offsetX, y: e.offsetY, t: e.timeStamp })
|
||||
if (trail.length > 8) trail.shift()
|
||||
requestDraw()
|
||||
if (dragMoved > 3) setHover(null, 0, 0)
|
||||
} else if (ptrs.size === 2) {
|
||||
const [a, b] = [...ptrs.values()],
|
||||
d = Math.hypot(a[0] - b[0], a[1] - b[1])
|
||||
if (lastPinch) zoomAt((a[0] + b[0]) / 2, (a[1] + b[1]) / 2, d / lastPinch)
|
||||
lastPinch = d
|
||||
dragMoved = 99
|
||||
trail = []
|
||||
}
|
||||
return
|
||||
}
|
||||
const b = pick(e.offsetX, e.offsetY)
|
||||
hover.value = b ? { b, x: e.offsetX, y: e.offsetY } : null
|
||||
if (e.pointerType === 'touch') return // no hover on touch
|
||||
setHover(pick(e.offsetX, e.offsetY), e.offsetX, e.offsetY)
|
||||
}
|
||||
const end = (e: PointerEvent) => {
|
||||
const had = ptrs.delete(e.pointerId)
|
||||
cv.classList.remove('drag')
|
||||
lastPinch = 0
|
||||
if (had && dragMoved < 5 && e.type === 'pointerup') sel.value = pick(e.offsetX, e.offsetY)
|
||||
if (!had || e.type !== 'pointerup') return
|
||||
if (dragMoved < 5) {
|
||||
sel.value = pick(e.offsetX, e.offsetY)
|
||||
return
|
||||
}
|
||||
const leave = () => {
|
||||
hover.value = null
|
||||
if (ptrs.size === 0) fling(e.timeStamp)
|
||||
}
|
||||
/** Keep panning after a quick drag, slowing down with friction. */
|
||||
const fling = (now: number) => {
|
||||
const recent = trail.filter((p) => now - p.t < 80)
|
||||
if (recent.length < 2 || reducedMotion()) return
|
||||
const a = recent[0],
|
||||
b = recent[recent.length - 1],
|
||||
dt = Math.max(1, b.t - a.t)
|
||||
let vx = (b.x - a.x) / dt,
|
||||
vy = (b.y - a.y) / dt // px per ms
|
||||
if (Math.hypot(vx, vy) < 0.15) return
|
||||
let last = performance.now()
|
||||
const step = (t: number) => {
|
||||
const ms = Math.min(32, t - last)
|
||||
last = t
|
||||
S.view.cx -= (vx * ms) / S.view.s
|
||||
S.view.cy += (vy * ms) / S.view.s
|
||||
const decay = 0.994 ** ms
|
||||
vx *= decay
|
||||
vy *= decay
|
||||
draw()
|
||||
anim = Math.hypot(vx, vy) > 0.02 ? requestAnimationFrame(step) : 0
|
||||
}
|
||||
stopMotion()
|
||||
anim = requestAnimationFrame(step)
|
||||
}
|
||||
const leave = () => setHover(null, 0, 0)
|
||||
const wheel = (e: WheelEvent) => {
|
||||
e.preventDefault()
|
||||
zoomAt(e.offsetX, e.offsetY, Math.exp(-e.deltaY * 0.0015))
|
||||
const dy = e.deltaMode === 1 ? e.deltaY * 16 : e.deltaY // Firefox may report lines
|
||||
// trackpad pinch arrives as ctrl+wheel with small deltas
|
||||
zoomAt(e.offsetX, e.offsetY, Math.exp(-dy * (e.ctrlKey ? 0.01 : 0.0015)))
|
||||
}
|
||||
|
||||
cv.addEventListener('pointerdown', down)
|
||||
|
|
@ -129,6 +227,7 @@ export function attachPointer(cv: HTMLCanvasElement): () => void {
|
|||
cv.addEventListener('pointerleave', leave)
|
||||
cv.addEventListener('wheel', wheel, { passive: false })
|
||||
return () => {
|
||||
stopMotion()
|
||||
cv.removeEventListener('pointerdown', down)
|
||||
cv.removeEventListener('pointermove', move)
|
||||
cv.removeEventListener('pointerup', end)
|
||||
|
|
@ -137,3 +236,54 @@ export function attachPointer(cv: HTMLCanvasElement): () => void {
|
|||
cv.removeEventListener('wheel', wheel)
|
||||
}
|
||||
}
|
||||
|
||||
/* ================= keyboard ================= */
|
||||
const isTyping = (el: EventTarget | null) =>
|
||||
el instanceof HTMLElement &&
|
||||
(el.isContentEditable || ['INPUT', 'SELECT', 'TEXTAREA'].includes(el.tagName))
|
||||
|
||||
function onKey(e: KeyboardEvent) {
|
||||
if (e.defaultPrevented || e.metaKey || e.ctrlKey || e.altKey) return
|
||||
if (e.key === 'Escape') {
|
||||
if (sel.value) sel.value = null
|
||||
else if (sheetOpen.value) sheetOpen.value = false
|
||||
else return
|
||||
e.preventDefault()
|
||||
return
|
||||
}
|
||||
if (isTyping(e.target)) return
|
||||
switch (e.key) {
|
||||
case '+':
|
||||
case '=':
|
||||
zoomBy(1.5)
|
||||
break
|
||||
case '-':
|
||||
case '_':
|
||||
zoomBy(1 / 1.5)
|
||||
break
|
||||
case '0':
|
||||
zoomFit()
|
||||
break
|
||||
case 'ArrowLeft':
|
||||
panBy(-0.2, 0)
|
||||
break
|
||||
case 'ArrowRight':
|
||||
panBy(0.2, 0)
|
||||
break
|
||||
case 'ArrowUp':
|
||||
panBy(0, -0.2)
|
||||
break
|
||||
case 'ArrowDown':
|
||||
panBy(0, 0.2)
|
||||
break
|
||||
default:
|
||||
return
|
||||
}
|
||||
e.preventDefault()
|
||||
}
|
||||
|
||||
/** Global map shortcuts (ignored while typing in a form field). Returns a cleanup function. */
|
||||
export function attachKeyboard(): () => void {
|
||||
window.addEventListener('keydown', onKey)
|
||||
return () => window.removeEventListener('keydown', onKey)
|
||||
}
|
||||
|
|
|
|||
28
src/main.tsx
28
src/main.tsx
|
|
@ -3,14 +3,36 @@ import { applyData, liveLoad, setStatus } from './actions'
|
|||
import { App } from './components/App'
|
||||
import { parseLoc } from './geo'
|
||||
import { t } from './i18n'
|
||||
import { isOwnHash, readHash } from './persist'
|
||||
import { loadSample } from './sample-data'
|
||||
import { DEFAULT_LOC } from './state'
|
||||
import { DEFAULT_LOC, lastLoc, locText, radius } from './state'
|
||||
import type { LatLon } from './types'
|
||||
import './style.css'
|
||||
|
||||
const fmt = (p: LatLon) => `${p.lat.toFixed(6)}, ${p.lon.toFixed(6)}`
|
||||
|
||||
/** Load the location in the URL hash (shared link), if any. Returns false if there is none. */
|
||||
function loadFromHash(): boolean {
|
||||
const h = readHash()
|
||||
if (!h) return false
|
||||
if (h.r && h.r >= 100 && h.r <= 700) radius.value = h.r
|
||||
locText.value = fmt(h)
|
||||
liveLoad(h, true)
|
||||
return true
|
||||
}
|
||||
|
||||
render(<App />, document.getElementById('root')!)
|
||||
|
||||
// Show the built-in example immediately, then replace it with live data for the default location.
|
||||
// Show the built-in example immediately, then replace it with live data:
|
||||
// shared link → last visited area → default location.
|
||||
applyData(loadSample(), 14.968678, 50.8171633)
|
||||
setStatus(() => t('st_init'))
|
||||
const p = parseLoc(DEFAULT_LOC)
|
||||
if (!loadFromHash()) {
|
||||
const last = lastLoc.value
|
||||
if (last) locText.value = fmt(last)
|
||||
const p = last ?? parseLoc(DEFAULT_LOC)
|
||||
if (p) liveLoad(p, true)
|
||||
}
|
||||
window.addEventListener('hashchange', () => {
|
||||
if (!isOwnHash()) loadFromHash()
|
||||
})
|
||||
|
|
|
|||
51
src/persist.ts
Normal file
51
src/persist.ts
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
import { effect, signal, type Signal } from '@preact/signals'
|
||||
import type { LatLon } from './types'
|
||||
|
||||
const PREFIX = 'bum-'
|
||||
|
||||
function read(key: string): unknown {
|
||||
try {
|
||||
const raw = localStorage.getItem(PREFIX + key)
|
||||
if (raw == null) return undefined
|
||||
try {
|
||||
return JSON.parse(raw)
|
||||
} catch {
|
||||
return raw // older versions stored plain strings (e.g. the language)
|
||||
}
|
||||
} catch {
|
||||
return undefined // storage blocked
|
||||
}
|
||||
}
|
||||
|
||||
/** A signal whose value is restored from and saved to localStorage. */
|
||||
export function persisted<T>(key: string, initial: T, valid: (v: unknown) => boolean): Signal<T> {
|
||||
const stored = read(key)
|
||||
const s = signal<T>(stored !== undefined && valid(stored) ? (stored as T) : initial)
|
||||
effect(() => {
|
||||
const v = s.value
|
||||
try {
|
||||
localStorage.setItem(PREFIX + key, JSON.stringify(v))
|
||||
} catch {}
|
||||
})
|
||||
return s
|
||||
}
|
||||
|
||||
/* ================= shareable URL: #lat,lon,radius ================= */
|
||||
export function readHash(hash = location.hash): (LatLon & { r?: number }) | null {
|
||||
const m = hash.match(/^#(-?\d+(?:\.\d+)?),(-?\d+(?:\.\d+)?)(?:,(\d+))?$/)
|
||||
if (!m) return null
|
||||
const lat = +m[1],
|
||||
lon = +m[2],
|
||||
r = m[3] ? +m[3] : undefined
|
||||
if (lat < 48 || lat > 52 || lon < 12 || lon > 19) return null
|
||||
return { lat, lon, r }
|
||||
}
|
||||
|
||||
let written = ''
|
||||
export function writeHash(p: LatLon, r: number) {
|
||||
const h = `#${p.lat.toFixed(5)},${p.lon.toFixed(5)},${r}`
|
||||
written = h
|
||||
if (location.hash !== h) history.replaceState(null, '', h)
|
||||
}
|
||||
/** True if the current hash is the one this page wrote itself (not a new link). */
|
||||
export const isOwnHash = () => location.hash === written
|
||||
155
src/render.ts
155
src/render.ts
|
|
@ -1,13 +1,27 @@
|
|||
import { computed } from '@preact/signals'
|
||||
import { BASE } from './basemap'
|
||||
import { buildings, catColor, catLabel, catList, catOrder, isDark, SIMPLE_NUMS } from './categories'
|
||||
import { t } from './i18n'
|
||||
import { base, hidden, rawBuildings, S, sel, showBase, showNums, vp } from './state'
|
||||
import type { Ring, View } from './types'
|
||||
import {
|
||||
base,
|
||||
focusCat,
|
||||
hidden,
|
||||
hover,
|
||||
rawBuildings,
|
||||
S,
|
||||
sel,
|
||||
showBase,
|
||||
showNums,
|
||||
vp,
|
||||
} from './state'
|
||||
import { LIGHT, palette, type MapPalette } from './theme'
|
||||
import type { Building, Ring, View } from './types'
|
||||
|
||||
/* ================= view ================= */
|
||||
export function fitView() {
|
||||
/** View that fits all loaded buildings into the canvas, or null if there is nothing to fit. */
|
||||
export function fitTarget(): View | null {
|
||||
const list = rawBuildings.value // bounding boxes do not depend on classification
|
||||
if (!list.length) return
|
||||
if (!list.length) return null
|
||||
let x0 = 1e18,
|
||||
y0 = 1e18,
|
||||
x1 = -1e18,
|
||||
|
|
@ -20,7 +34,15 @@ export function fitView() {
|
|||
}
|
||||
const w = Math.max(x1 - x0, 50),
|
||||
h = Math.max(y1 - y0, 50)
|
||||
S.view = { cx: (x0 + x1) / 2, cy: (y0 + y1) / 2, s: Math.min(vp.W / w, vp.H / h) * 0.94 }
|
||||
// keep the area clear of the mobile bottom sheet: fit into the visible height and
|
||||
// shift the centre up by half the covered strip
|
||||
const visH = Math.max(1, vp.H - vp.insetB),
|
||||
s = Math.min(vp.W / w, visH / h) * 0.94
|
||||
return { cx: (x0 + x1) / 2, cy: (y0 + y1) / 2 - vp.insetB / 2 / s, s }
|
||||
}
|
||||
export function fitView() {
|
||||
const v = fitTarget()
|
||||
if (v) S.view = v
|
||||
}
|
||||
/** Screen px per true metre. */
|
||||
export const pxPerMeter = (v: View) => v.s / S.K
|
||||
|
|
@ -34,20 +56,33 @@ function niceScale(v: View) {
|
|||
return { m: 1000, px: 1000 * pxPerMeter(v) }
|
||||
}
|
||||
|
||||
const hoverBuilding = computed(() => hover.value?.b ?? null)
|
||||
|
||||
interface SceneOpts {
|
||||
pal?: MapPalette
|
||||
/** draw on-screen-only overlays: selection, hover outline, legend focus dimming */
|
||||
live?: boolean
|
||||
/** px at the bottom covered by UI (mobile sheet); the scale bar sits above it */
|
||||
insetB?: number
|
||||
}
|
||||
|
||||
export function drawScene(
|
||||
ctx: CanvasRenderingContext2D,
|
||||
W: number,
|
||||
H: number,
|
||||
v: View,
|
||||
r: number,
|
||||
opts: { sel?: boolean } = {},
|
||||
{ pal = LIGHT, live = false, insetB = 0 }: SceneOpts = {},
|
||||
) {
|
||||
const list = buildings.value,
|
||||
hid = hidden.value,
|
||||
focus = live ? focusCat.value : null
|
||||
ctx.save()
|
||||
ctx.setTransform(r, 0, 0, r, 0, 0)
|
||||
ctx.beginPath()
|
||||
ctx.rect(0, 0, W, H)
|
||||
ctx.clip()
|
||||
ctx.fillStyle = '#f5f2ea'
|
||||
ctx.fillStyle = pal.bg
|
||||
ctx.fillRect(0, 0, W, H)
|
||||
const sx = (x: number) => (x - v.cx) * v.s + W / 2,
|
||||
sy = (y: number) => H / 2 - (y - v.cy) * v.s
|
||||
|
|
@ -63,24 +98,36 @@ export function drawScene(
|
|||
if (close) ctx.closePath()
|
||||
}
|
||||
}
|
||||
const outline = (b: Building, outer: string, w: number, inner?: string) => {
|
||||
path(b.rings, true)
|
||||
ctx.strokeStyle = outer
|
||||
ctx.lineWidth = w
|
||||
ctx.stroke()
|
||||
if (inner) {
|
||||
ctx.strokeStyle = inner
|
||||
ctx.lineWidth = 1
|
||||
ctx.stroke()
|
||||
}
|
||||
}
|
||||
ctx.lineJoin = 'round'
|
||||
ctx.lineCap = 'round'
|
||||
if (showBase.value) {
|
||||
const bmap = base.value
|
||||
for (const st of BASE) {
|
||||
const rings = base.value[st.k]
|
||||
const rings = bmap[st.k]
|
||||
if (!rings || !rings.length) continue
|
||||
if (st.t === 'poly') {
|
||||
path(rings, true)
|
||||
ctx.fillStyle = st.fill
|
||||
ctx.fillStyle = pal.base[st.fill]
|
||||
ctx.fill('evenodd')
|
||||
if (st.stroke) {
|
||||
ctx.strokeStyle = st.stroke
|
||||
ctx.strokeStyle = pal.base[st.stroke]
|
||||
ctx.lineWidth = 1
|
||||
ctx.stroke()
|
||||
}
|
||||
} else {
|
||||
path(rings, false)
|
||||
ctx.strokeStyle = st.c
|
||||
ctx.strokeStyle = pal.base[st.c]
|
||||
ctx.lineWidth = Math.max(st.min, st.m * ppm)
|
||||
ctx.setLineDash(st.dash ? st.dash.map((d) => d * Math.max(1, ppm / 2)) : [])
|
||||
ctx.stroke()
|
||||
|
|
@ -89,24 +136,28 @@ export function drawScene(
|
|||
}
|
||||
}
|
||||
for (const key of catOrder()) {
|
||||
if (hidden.value.has(key)) continue
|
||||
if (hid.has(key)) continue
|
||||
const rings: Ring[] = []
|
||||
for (const b of buildings.value) if (b.cat === key) for (const rg of b.rings) rings.push(rg)
|
||||
for (const b of list) if (b.cat === key) for (const rg of b.rings) rings.push(rg)
|
||||
if (!rings.length) continue
|
||||
// while a legend row is hovered, other categories fade back
|
||||
ctx.globalAlpha = focus && focus !== key ? 0.18 : 1
|
||||
path(rings, true)
|
||||
ctx.fillStyle = catColor(key)
|
||||
ctx.fill('evenodd')
|
||||
ctx.strokeStyle = key === 'res' || key === 'u7' ? 'rgba(255,255,255,.55)' : 'rgba(0,0,0,.55)'
|
||||
ctx.strokeStyle = key === 'res' || key === 'u7' ? pal.outlineOnDark : pal.outlineOnLight
|
||||
ctx.lineWidth = 0.5
|
||||
ctx.stroke()
|
||||
}
|
||||
ctx.globalAlpha = 1
|
||||
if (showNums.value && ppm >= 1.5) {
|
||||
const all = ppm >= 3.2
|
||||
ctx.textAlign = 'center'
|
||||
ctx.textBaseline = 'middle'
|
||||
ctx.font = `${Math.min(12, Math.max(8, ppm * 2.2))}px system-ui,sans-serif`
|
||||
for (const b of buildings.value) {
|
||||
if (!b.cp || hidden.value.has(b.cat) || !(all || SIMPLE_NUMS[b.sc])) continue
|
||||
for (const b of list) {
|
||||
if (!b.cp || hid.has(b.cat) || (focus && focus !== b.cat) || !(all || SIMPLE_NUMS[b.sc]))
|
||||
continue
|
||||
const cx = sx((b.bb[0] + b.bb[2]) / 2),
|
||||
cy = sy((b.bb[1] + b.bb[3]) / 2)
|
||||
if (cx < -20 || cy < -20 || cx > W + 20 || cy > H + 20) continue
|
||||
|
|
@ -121,31 +172,34 @@ export function drawScene(
|
|||
ctx.fillText(txt, cx, cy)
|
||||
}
|
||||
}
|
||||
if (opts.sel && sel.value) {
|
||||
path(sel.value.rings, true)
|
||||
ctx.strokeStyle = '#ffcc00'
|
||||
ctx.lineWidth = 3
|
||||
ctx.stroke()
|
||||
ctx.strokeStyle = '#000'
|
||||
ctx.lineWidth = 1
|
||||
ctx.stroke()
|
||||
if (live) {
|
||||
const hb = hoverBuilding.value,
|
||||
sb = sel.value
|
||||
if (hb && hb !== sb && !hid.has(hb.cat)) outline(hb, pal.hover, 1.5)
|
||||
if (sb) outline(sb, pal.selOuter, 3, pal.selInner)
|
||||
}
|
||||
// scale bar
|
||||
const sc = niceScale(v),
|
||||
bx = 16,
|
||||
by = H - 18
|
||||
ctx.fillStyle = 'rgba(245,242,234,.85)'
|
||||
ctx.fillRect(bx - 6, by - 20, sc.px + 12, 30)
|
||||
ctx.strokeStyle = '#000'
|
||||
by = H - 18 - insetB
|
||||
ctx.fillStyle = pal.furnitureBg
|
||||
ctx.beginPath()
|
||||
ctx.roundRect(bx - 8, by - 22, sc.px + 16, 32, 6)
|
||||
ctx.fill()
|
||||
ctx.strokeStyle = pal.furnitureInk
|
||||
ctx.fillStyle = pal.furnitureInk
|
||||
ctx.lineWidth = 2
|
||||
ctx.beginPath()
|
||||
ctx.moveTo(bx, by)
|
||||
ctx.moveTo(bx, by - 4)
|
||||
ctx.lineTo(bx, by)
|
||||
ctx.lineTo(bx + sc.px, by)
|
||||
ctx.lineTo(bx + sc.px, by - 4)
|
||||
ctx.stroke()
|
||||
ctx.fillStyle = '#000'
|
||||
ctx.font = '11px system-ui,sans-serif'
|
||||
ctx.textAlign = 'center'
|
||||
ctx.textBaseline = 'bottom'
|
||||
ctx.fillText(sc.m >= 1000 ? sc.m / 1000 + ' km' : sc.m + ' m', bx + sc.px / 2, by - 4)
|
||||
ctx.fillText(sc.m >= 1000 ? sc.m / 1000 + ' km' : sc.m + ' m', bx + sc.px / 2, by - 5)
|
||||
// north arrow
|
||||
ctx.beginPath()
|
||||
ctx.moveTo(24, 44)
|
||||
ctx.lineTo(24, 16)
|
||||
|
|
@ -179,10 +233,10 @@ function legendEntries(): LegendEntry[] {
|
|||
if (cnt[k]) e.push({ color: catColor(k), label: `${catLabel(k)} (${cnt[k]})` })
|
||||
if (showBase.value)
|
||||
e.push(
|
||||
{ color: '#a8cfe8', label: t('b_water') },
|
||||
{ color: '#cfe4bd', label: t('b_green') },
|
||||
{ color: '#ffe08a', label: t('b_road') },
|
||||
{ color: '#ffffff', label: t('b_street'), border: '#9a9a9a' },
|
||||
{ color: LIGHT.base.water, label: t('b_water') },
|
||||
{ color: LIGHT.base.green, label: t('b_green') },
|
||||
{ color: LIGHT.base.road, label: t('b_road') },
|
||||
{ color: LIGHT.base.street, label: t('b_street'), border: LIGHT.base.streetCasing },
|
||||
)
|
||||
return e
|
||||
}
|
||||
|
|
@ -218,7 +272,34 @@ export function drawLegend(ctx: CanvasRenderingContext2D, y0: number, W: number,
|
|||
ctx.restore()
|
||||
}
|
||||
|
||||
/** Redraw the on-screen map. */
|
||||
/** Redraw the on-screen map now. */
|
||||
export function draw() {
|
||||
if (vp.W && vp.ctx) drawScene(vp.ctx, vp.W, vp.H, S.view, vp.DPR, { sel: true })
|
||||
if (vp.W && vp.ctx)
|
||||
drawScene(vp.ctx, vp.W, vp.H, S.view, vp.DPR, { pal: palette(), live: true, insetB: vp.insetB })
|
||||
}
|
||||
|
||||
/**
|
||||
* Read every signal the on-screen map depends on. MapView runs this inside an effect so the
|
||||
* map redraws when any of them changes; the redraw itself happens in requestDraw's frame.
|
||||
*/
|
||||
export const trackScene = () => [
|
||||
buildings.value,
|
||||
base.value,
|
||||
hidden.value,
|
||||
showBase.value,
|
||||
showNums.value,
|
||||
sel.value,
|
||||
hoverBuilding.value,
|
||||
focusCat.value,
|
||||
palette(),
|
||||
]
|
||||
|
||||
let frame = 0
|
||||
/** Schedule a redraw for the next animation frame (at most one per frame). */
|
||||
export function requestDraw() {
|
||||
if (frame) return
|
||||
frame = requestAnimationFrame(() => {
|
||||
frame = 0
|
||||
draw()
|
||||
})
|
||||
}
|
||||
|
|
|
|||
54
src/state.ts
54
src/state.ts
|
|
@ -1,5 +1,6 @@
|
|||
import { signal } from '@preact/signals'
|
||||
import type { BaseData, Building, Mode, View } from './types'
|
||||
import { persisted } from './persist'
|
||||
import type { BaseData, Building, LatLon, Mode, View } from './types'
|
||||
|
||||
/* ================= reactive state =================
|
||||
* Everything the UI or the map drawing depends on is a signal: components re-render and the
|
||||
|
|
@ -9,25 +10,47 @@ import type { BaseData, Building, Mode, View } from './types'
|
|||
/** Buildings as loaded, before classification. */
|
||||
export const rawBuildings = signal<Building[]>([])
|
||||
export const base = signal<BaseData>({})
|
||||
export const mode = signal<Mode>('simple')
|
||||
/** Minimum flats for a non-residential building to count as mixed use (0 = off). */
|
||||
export const mixMin = signal(1)
|
||||
// The classified list is `buildings` in categories.ts.
|
||||
|
||||
/* user settings, remembered between visits */
|
||||
export const mode = persisted<Mode>('mode', 'simple', (v) => v === 'simple' || v === 'detailed')
|
||||
/** Minimum flats for a non-residential building to count as mixed use (0 = off). */
|
||||
export const mixMin = persisted('mixMin', 1, (v) => v === 0 || v === 1 || v === 2)
|
||||
export const showBase = persisted('showBase', true, (v) => typeof v === 'boolean')
|
||||
export const showNums = persisted('showNums', true, (v) => typeof v === 'boolean')
|
||||
export const radius = persisted('radius', 300, (v) => typeof v === 'number' && v >= 100 && v <= 700)
|
||||
/** Last successfully loaded location; restored on the next visit. */
|
||||
export const lastLoc = persisted<LatLon | null>(
|
||||
'lastLoc',
|
||||
null,
|
||||
(v) => !!v && typeof (v as LatLon).lat === 'number' && typeof (v as LatLon).lon === 'number',
|
||||
)
|
||||
|
||||
export const hidden = signal<ReadonlySet<string>>(new Set())
|
||||
export const showBase = signal(true)
|
||||
export const showNums = signal(true)
|
||||
/** Legend category being hovered/focused; the map fades the other categories. */
|
||||
export const focusCat = signal<string | null>(null)
|
||||
export const sel = signal<Building | null>(null)
|
||||
/** Building under the pointer and where to show the tooltip. */
|
||||
export const hover = signal<{ b: Building; x: number; y: number } | null>(null)
|
||||
|
||||
export const radius = signal(300)
|
||||
export const DEFAULT_LOC = 'https://mapy.com/en/turisticka?l=0&x=14.9686780&y=50.8171633&z=16.762'
|
||||
/** Text of the location field. */
|
||||
export const locText = signal(DEFAULT_LOC)
|
||||
export const busy = signal(false)
|
||||
export const locating = signal(false)
|
||||
/** Requests finished / total while loading from ČÚZK; null when idle. */
|
||||
export const progress = signal<{ done: number; total: number } | null>(null)
|
||||
|
||||
export interface Status {
|
||||
fn: () => string // a function so it is re-rendered in the current language
|
||||
cls?: 'ok' | 'err'
|
||||
cls?: 'ok' | 'warn' | 'err'
|
||||
details?: string[]
|
||||
}
|
||||
export const status = signal<Status | null>(null)
|
||||
/** Short confirmation message shown at the bottom of the screen. */
|
||||
export const toast = signal<{ fn: () => string; id: number } | null>(null)
|
||||
/** Mobile bottom sheet expanded. */
|
||||
export const sheetOpen = signal(false)
|
||||
|
||||
/* ================= non-reactive view state ================= */
|
||||
export const S = {
|
||||
|
|
@ -37,7 +60,14 @@ export const S = {
|
|||
loaded: false,
|
||||
}
|
||||
|
||||
/** Canvas size in CSS pixels, device pixel ratio and 2D context; set by MapView. */
|
||||
export const vp = { W: 0, H: 0, DPR: 1, ctx: null as CanvasRenderingContext2D | null }
|
||||
|
||||
export const DEFAULT_LOC = 'https://mapy.com/en/turisticka?l=0&x=14.9686780&y=50.8171633&z=16.762'
|
||||
/**
|
||||
* Canvas size in CSS pixels, device pixel ratio and 2D context; set by MapView.
|
||||
* insetB: height covered by the mobile bottom sheet, kept clear when fitting the view.
|
||||
*/
|
||||
export const vp = {
|
||||
W: 0,
|
||||
H: 0,
|
||||
DPR: 1,
|
||||
insetB: 0,
|
||||
ctx: null as CanvasRenderingContext2D | null,
|
||||
}
|
||||
|
|
|
|||
1067
src/style.css
1067
src/style.css
File diff suppressed because it is too large
Load diff
105
src/theme.ts
Normal file
105
src/theme.ts
Normal file
|
|
@ -0,0 +1,105 @@
|
|||
import { signal } from '@preact/signals'
|
||||
|
||||
/* ================= colour theme =================
|
||||
* The UI chrome follows prefers-color-scheme via CSS variables (style.css). The map canvas
|
||||
* can't read CSS, so its colours live here. Building fill colours are the same in both
|
||||
* themes (they carry meaning); only the basemap and the map furniture change.
|
||||
* Exports (PNG/SVG/print) always use LIGHT so they stay printable.
|
||||
*/
|
||||
|
||||
const mq = typeof matchMedia === 'function' ? matchMedia('(prefers-color-scheme: dark)') : undefined
|
||||
export const dark = signal(!!mq?.matches)
|
||||
mq?.addEventListener('change', (e) => (dark.value = e.matches))
|
||||
|
||||
export type BaseColor =
|
||||
| 'garden'
|
||||
| 'green'
|
||||
| 'cemetery'
|
||||
| 'cemeteryEdge'
|
||||
| 'parking'
|
||||
| 'parkingEdge'
|
||||
| 'water'
|
||||
| 'waterEdge'
|
||||
| 'stream'
|
||||
| 'path'
|
||||
| 'track'
|
||||
| 'rail'
|
||||
| 'streetCasing'
|
||||
| 'street'
|
||||
| 'roadCasing'
|
||||
| 'road'
|
||||
|
||||
export interface MapPalette {
|
||||
bg: string
|
||||
base: Record<BaseColor, string>
|
||||
/** building outline on dark fills (family houses) and on all other fills */
|
||||
outlineOnDark: string
|
||||
outlineOnLight: string
|
||||
hover: string
|
||||
selOuter: string
|
||||
selInner: string
|
||||
/** scale bar and north arrow */
|
||||
furnitureBg: string
|
||||
furnitureInk: string
|
||||
}
|
||||
|
||||
export const LIGHT: MapPalette = {
|
||||
bg: '#f5f2ea',
|
||||
base: {
|
||||
garden: '#e6efd6',
|
||||
green: '#cfe4bd',
|
||||
cemetery: '#c9d9bd',
|
||||
cemeteryEdge: '#9bb08a',
|
||||
parking: '#e2e2e2',
|
||||
parkingEdge: '#c4c4c4',
|
||||
water: '#a8cfe8',
|
||||
waterEdge: '#7fb2d6',
|
||||
stream: '#7fb2d6',
|
||||
path: '#b58b5a',
|
||||
track: '#c9a16b',
|
||||
rail: '#666666',
|
||||
streetCasing: '#9a9a9a',
|
||||
street: '#ffffff',
|
||||
roadCasing: '#b8862f',
|
||||
road: '#ffe08a',
|
||||
},
|
||||
outlineOnDark: 'rgba(255,255,255,.55)',
|
||||
outlineOnLight: 'rgba(0,0,0,.55)',
|
||||
hover: 'rgba(20,20,20,.9)',
|
||||
selOuter: '#ffcc00',
|
||||
selInner: '#000',
|
||||
furnitureBg: 'rgba(245,242,234,.85)',
|
||||
furnitureInk: '#000',
|
||||
}
|
||||
|
||||
export const DARK: MapPalette = {
|
||||
bg: '#1c1e22',
|
||||
base: {
|
||||
garden: '#232d22',
|
||||
green: '#263826',
|
||||
cemetery: '#28332a',
|
||||
cemeteryEdge: '#3f5240',
|
||||
parking: '#2a2c31',
|
||||
parkingEdge: '#3a3d43',
|
||||
water: '#1d3850',
|
||||
waterEdge: '#2c5676',
|
||||
stream: '#3b6e98',
|
||||
path: '#806544',
|
||||
track: '#86704c',
|
||||
rail: '#8b8e94',
|
||||
streetCasing: '#121316',
|
||||
street: '#4b4f57',
|
||||
roadCasing: '#17130a',
|
||||
road: '#a2802f',
|
||||
},
|
||||
outlineOnDark: 'rgba(255,255,255,.7)',
|
||||
outlineOnLight: 'rgba(0,0,0,.6)',
|
||||
hover: 'rgba(255,255,255,.95)',
|
||||
selOuter: '#ffcc00',
|
||||
selInner: '#000',
|
||||
furnitureBg: 'rgba(28,30,34,.85)',
|
||||
furnitureInk: '#e6e6e6',
|
||||
}
|
||||
|
||||
/** Palette for the on-screen map (reads `dark`, so a theme change redraws). */
|
||||
export const palette = () => (dark.value ? DARK : LIGHT)
|
||||
Loading…
Reference in a new issue