feat(hg3): align with the HG3 semester project assignment

- Default "Zadání HG3" mode with exactly the 16 categories of the assignment
  (9 built-up, 7 undeveloped) and its legend colours; replaces the old simple mode
- Whole map coloured: RÚIAN cadastral parcels are fetched and classified from
  land type / land use; built-up parcels take the category of their building
- Field corrections per building or parcel (info panel), saved locally and in a
  project file (save/open JSON) to move between devices
- A4 frame at 1 : 3 780 (300 dpi, landscape/portrait) shown on the map; data
  loading covers the frame
- Built-up territory meter against the 66 % rule (built-up areas + gardens +
  maintained greenery; strict legend share shown too) and area statistics
  per category with CSV export
- Submission print/PDF: 1 map (title, author, scale, source), 2 legend (only
  categories present), 3-4 commentary
- Commentary editor with the assignment's questions and a 3 600-character counter
- Field worksheet: blank A4 base map with house numbers and an empty legend
  to colour with crayons
- Buildings CSV gains HG3 category, correction flag and parcels

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
HangerThem 2026-11-07 12:48:42 +01:00
parent 44bc6207a9
commit bb5ecbcd6d
27 changed files with 2291 additions and 289 deletions

View file

@ -1,8 +1,11 @@
import { batch } from '@preact/signals'
import { fetchArea } from './fetch'
import { D2R } from './geo'
import { bboxOf } from './building'
import { D2R, ll2m, m2ll } from './geo'
import { t } from './i18n'
import { writeHash } from './persist'
import { frameCovered, frameRadius } from './page'
import { renderPrintMap } from './print'
import { fitView } from './render'
import {
base,
@ -14,6 +17,17 @@ import {
progress,
radius,
rawBuildings,
rawParcels,
answered,
commentary,
mapAuthor,
mapTitle,
mixMin,
mode,
orientation,
overrides,
printJob,
showFrame,
S,
sel,
status,
@ -34,23 +48,45 @@ export function showToast(fn: () => string) {
toastTimer = setTimeout(() => (toast.value = null), 2400)
}
export function applyData(d: AreaData, lon: number, lat: number) {
/**
* Show loaded data. r: the load radius (to know which area is covered);
* keepView: centre the view on (lon, lat) and keep the zoom, instead of fitting to the data.
*/
export function applyData(d: AreaData, lon: number, lat: number, r?: number, keepView = false) {
S.center = [lon, lat]
S.K = Math.cos(lat * D2R)
S.loaded = true
if (r) {
const [cx, cy] = ll2m(lon, lat),
h = (1.1 * r * 0.995) / S.K
S.loadedBB = [cx - h, cy - h, cx + h, cy + h]
} else S.loadedBB = bboxOf(d.buildings.flatMap((b) => b.rings))
// fitView inside the batch so the map redraw triggered by the new data uses the new view
batch(() => {
rawBuildings.value = d.buildings
rawParcels.value = d.parcels
base.value = d.base
sel.value = null
hidden.value = new Set()
fitView()
if (!keepView) fitView()
else {
const [cx, cy] = ll2m(lon, lat)
S.view = { ...S.view, cx, cy }
}
})
}
/** Radius to load: in the HG3 mode with the frame on, at least enough for the A4 frame. */
const loadRadius = () =>
mode.value === 'hg3' && showFrame.value ? Math.max(radius.value, frameRadius()) : radius.value
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> {
export async function liveLoad(
p: LatLon,
quietFallback: boolean,
keepView = false,
): Promise<boolean> {
const my = ++loadSeq
const current = () => my === loadSeq
batch(() => {
@ -59,7 +95,7 @@ export async function liveLoad(p: LatLon, quietFallback: boolean): Promise<boole
setStatus(() => t('st_loading'))
})
try {
const r = radius.value
const r = loadRadius()
const d = await fetchArea(p.lon, p.lat, r, (done, total) => {
if (current()) progress.value = { done, total }
})
@ -68,7 +104,7 @@ export async function liveLoad(p: LatLon, quietFallback: boolean): Promise<boole
setStatus(() => t('st_none'), 'err')
return false
}
applyData(d, p.lon, p.lat)
applyData(d, p.lon, p.lat, r, keepView)
writeHash(p, r)
lastLoc.value = { lat: p.lat, lon: p.lon }
const loc = `${p.lat.toFixed(5)}, ${p.lon.toFixed(5)}`,
@ -133,3 +169,86 @@ export async function copyLink() {
window.prompt(t('copyLink'), location.href)
}
}
/** Load data for the A4 frame around the current view centre, keeping the view. */
export function loadFrame() {
const [lon, lat] = m2ll(S.view.cx, S.view.cy)
locText.value = `${lat.toFixed(6)}, ${lon.toFixed(6)}`
return liveLoad({ lat, lon }, false, true)
}
/* ================= printing ================= */
/** Render the A4 map and open the print dialog for the submission PDF or the field worksheet. */
export async function preparePrint(kind: 'submission' | 'worksheet') {
if (!frameCovered()) {
setStatus(() => t('needData'), 'err')
return
}
showToast(() => t('preparing'))
await new Promise((r) => setTimeout(r, 30)) // let the toast paint before the heavy render
const mapUrl = await renderPrintMap(kind === 'worksheet')
printJob.value = { kind, mapUrl }
// wait for PrintView to render and the map image to decode
await new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r)))
await document
.querySelector<HTMLImageElement>('.print-root img')
?.decode()
.catch(() => {})
window.print()
}
/* ================= project file ================= */
const PROJECT_APP = 'building-use-map/hg3'
export function projectData() {
return {
app: PROJECT_APP,
version: 1,
savedAt: new Date().toISOString(),
location: lastLoc.value,
radius: radius.value,
view: lastLoc.value ? m2ll(S.view.cx, S.view.cy) : null,
orientation: orientation.value,
title: mapTitle.value,
author: mapAuthor.value,
mixMin: mixMin.value,
overrides: overrides.value,
commentary: commentary.value,
answered: answered.value,
}
}
/** Restore a project saved with "Save project" and load its area. */
export async function openProject(file: File) {
let d: Partial<ReturnType<typeof projectData>>
try {
d = JSON.parse(await file.text())
} catch {
d = {}
}
if (d.app !== PROJECT_APP) {
setStatus(() => t('projectBad'), 'err')
return
}
batch(() => {
if (d.overrides && typeof d.overrides === 'object') overrides.value = { ...d.overrides }
if (typeof d.commentary === 'string') commentary.value = d.commentary
if (Array.isArray(d.answered)) answered.value = d.answered.filter((n) => typeof n === 'number')
if (typeof d.title === 'string') mapTitle.value = d.title
if (typeof d.author === 'string') mapAuthor.value = d.author
if (d.orientation === 'landscape' || d.orientation === 'portrait')
orientation.value = d.orientation
if (d.mixMin === 0 || d.mixMin === 1 || d.mixMin === 2) mixMin.value = d.mixMin
if (typeof d.radius === 'number' && d.radius >= 100 && d.radius <= 700) radius.value = d.radius
mode.value = 'hg3'
})
showToast(() => t('projectLoaded'))
// load the saved frame position (view centre), else the saved location
const v =
Array.isArray(d.view) && d.view.length === 2 ? { lon: +d.view[0], lat: +d.view[1] } : null
const p = v ?? d.location
if (p && typeof p.lat === 'number' && typeof p.lon === 'number') {
locText.value = `${p.lat.toFixed(6)}, ${p.lon.toFixed(6)}`
await liveLoad(p, false, !!v)
}
}

View file

@ -1,16 +1,8 @@
import type { Building, Ring } from './types'
import type { BBox, Building, Parcel, Ring } from './types'
type Num = number | string | null | undefined
export function mkBuilding(
cp: Num,
use: Num,
flats: Num,
floors: Num,
area: Num,
done: number | null | undefined,
rings: Ring[],
): Building {
export function bboxOf(rings: Ring[]): BBox {
let x0 = 1e18,
y0 = 1e18,
x1 = -1e18,
@ -22,17 +14,60 @@ export function mkBuilding(
if (p[1] < y0) y0 = p[1]
if (p[1] > y1) y1 = p[1]
}
return [x0, y0, x1, y1]
}
const num = (v: Num) => (v == null || v === '' ? null : +v)
export function mkBuilding(
id: Num,
parcel: Num,
cp: Num,
use: Num,
flats: Num,
floors: Num,
area: Num,
done: number | null | undefined,
rings: Ring[],
): Building {
const year = done != null && isFinite(done) ? new Date(done).getUTCFullYear() : null
return {
kind: 'b',
id: String(id ?? ''),
parcel: parcel == null ? null : String(parcel),
cp: (cp || '').toString().trim(),
use: use == null ? 0 : +use,
flats: flats == null ? null : +flats,
floors: floors == null ? null : +floors,
area: area == null ? null : +area,
flats: num(flats),
floors: num(floors),
area: num(area),
year,
rings,
bb: [x0, y0, x1, y1],
cat: 'other',
sc: 'other',
bb: bboxOf(rings),
auto: 'ost',
hg: 'ost',
cat: 'ost',
}
}
export function mkParcel(
id: Num,
numText: Num,
druh: Num,
use: Num,
area: Num,
rings: Ring[],
): Parcel {
return {
kind: 'p',
id: String(id ?? ''),
num: (numText ?? '').toString(),
druh: num(druh),
use: num(use),
area: num(area),
rings,
bb: bboxOf(rings),
auto: 'ostn',
hg: 'ostn',
cat: 'ostn',
}
}

View file

@ -1,71 +1,129 @@
import { t, tKey, ruianUseName } from './i18n'
import { computed } from '@preact/signals'
import { mixMin, mode, rawBuildings } from './state'
import type { Building } from './types'
import { ruianUseName, t, tKey } from './i18n'
import { mixMin, mode, overrides, rawBuildings, rawParcels } from './state'
import type { Building, MapItem } from './types'
/* ================= categories ================= */
// Simple scheme: key, colour, show house number
type SimpleDef = [key: string, color: string, nums: 0 | 1]
export const SIMPLE: SimpleDef[] = [
['res', '#000000', 0],
['unit', '#d62728', 1],
['rec', '#2ca02c', 1],
['mix', '#ff8c00', 1],
['civic', '#1f5fbf', 1],
['assem', '#4fb3e8', 1],
['shop', '#e377c2', 1],
['hotel', '#e8c000', 1],
['office', '#17808a', 1],
['ind', '#7b3294', 1],
['agri', '#8c564b', 0],
['tech', '#4d4d4d', 0],
['garage', '#d9b77e', 0],
['other', '#bdbdbd', 0],
/* ================= HG3 semester project categories =================
* Exactly the 16 categories required by the assignment ("Humánní geografie 3: Zadání
* semestrálního projektu"), in its order. Colours follow the crayon legend in the assignment.
*/
export interface HgCat {
key: string
color: string
built: boolean
/** show house numbers for this category at medium zoom */
nums?: boolean
}
export const HG: HgCat[] = [
// Zastavěné plochy
{ key: 'byt', color: '#f06fc4', built: true, nums: true }, // Bydlení – bytové domy
{ key: 'rd', color: '#e53935', built: true }, // Bydlení – rodinné domy
{ key: 'rek', color: '#f28a1f', built: true, nums: true }, // Objekty individuální rekreace
{ key: 'ver', color: '#7fd0ef', built: true, nums: true }, // Veřejné služby
{ key: 'kom', color: '#9a5bd6', built: true, nums: true }, // Komerční služby
{ key: 'pru', color: '#8d5a2b', built: true, nums: true }, // Průmysl
{ key: 'dop', color: '#a9a9a9', built: true }, // Dopravní sítě a vybavení
{ key: 'smi', color: '#8e2463', built: true, nums: true }, // Smíšené plochy
{ key: 'ost', color: '#4f79a6', built: true }, // Ostatní plochy (zastavěné)
// Nezastavěné plochy
{ key: 'zel', color: '#4caf50', built: false }, // Upravená zeleň
{ key: 'zah', color: '#b5dc63', built: false }, // Zahrady
{ key: 'pole', color: '#f3c74d', built: false }, // Pole
{ key: 'louka', color: '#f6ef8e', built: false }, // Louky
{ key: 'les', color: '#1d7a4c', built: false }, // Lesy
{ key: 'voda', color: '#3b82d9', built: false }, // Vodní plochy
{ key: 'ostn', color: '#d9d4e8', built: false }, // Ostatní plochy (nezastavěné)
]
const SIMPLE_COLOR: Record<string, string> = Object.fromEntries(SIMPLE.map((c) => [c[0], c[1]]))
export const SIMPLE_NUMS: Record<string, boolean> = Object.fromEntries(
SIMPLE.map((c) => [c[0], !!c[2]]),
)
const SIMPLE_ORDER = [
'other',
'garage',
'agri',
'tech',
'ind',
'office',
'hotel',
'shop',
'assem',
'civic',
'res',
'unit',
'rec',
'mix',
]
const USE_CAT: Record<number, string> = {
1: 'ind',
2: 'agri',
4: 'agri',
5: 'civic',
6: 'unit',
7: 'res',
8: 'rec',
9: 'assem',
10: 'shop',
11: 'hotel',
12: 'ind',
13: 'agri',
14: 'office',
15: 'civic',
16: 'tech',
17: 'tech',
18: 'garage',
19: 'other',
20: 'other',
21: 'other',
const HG_BY_KEY = Object.fromEntries(HG.map((c) => [c.key, c]))
export const HG_BUILT = HG.filter((c) => c.built).map((c) => c.key)
export const HG_OPEN = HG.filter((c) => !c.built).map((c) => c.key)
export const isBuilt = (key: string) => !!HG_BY_KEY[key]?.built
export const hgColor = (key: string) => HG_BY_KEY[key]?.color ?? '#bdbdbd'
export const hgLabel = (key: string) => tKey('hg.' + key)
export const isHgKey = (v: unknown): v is string => typeof v === 'string' && v in HG_BY_KEY
/** RÚIAN building use code → HG3 category (before the mixed-use rule). */
const BUILDING_HG: Record<number, string> = {
1: 'pru', // průmyslový objekt
2: 'rd', // zemědělská usedlost (a farmhouse is lived in)
4: 'pru', // objekt lesního hospodářství
5: 'ver', // objekt občanské vybavenosti
6: 'byt', // bytový dům
7: 'rd', // rodinný dům
8: 'rek', // stavba pro rodinnou rekreaci
9: 'ver', // stavba pro shromažďování většího počtu osob
10: 'kom', // stavba pro obchod
11: 'kom', // stavba ubytovacího zařízení
12: 'pru', // stavba pro výrobu a skladování
13: 'pru', // zemědělská stavba
14: 'kom', // stavba pro administrativu
15: 'ver', // stavba občanského vybavení
16: 'ver', // stavba technického vybavení (technické sítě a vybavení)
17: 'dop', // stavba pro dopravu
18: 'dop', // garáž
}
const AGRI = new Set([4, 13])
export function buildingHg(use: number, flats: number | null): string {
const f = flats || 0
if (use === 3) return f >= 4 ? 'byt' : 'rd' // "objekt k bydlení" without a finer type
const base = BUILDING_HG[use] ?? 'ost'
// RÚIAN has no mixed class: a non-residential building with flats counts as mixed use
const mixable =
base === 'ver' || base === 'kom' || base === 'ost' || (base === 'pru' && !AGRI.has(use))
if (mixable && mixMin.value > 0 && f >= mixMin.value) return 'smi'
return base
}
// Detailed scheme: one entry per RÚIAN use code
/** Parcel land type / land use → HG3 category; built-up parcels take their building's category. */
export function parcelHg(druh: number | null, use: number | null, building?: string): string {
switch (druh) {
case 2: // orná půda
case 3: // chmelnice
case 4: // vinice
return 'pole'
case 5: // zahrada
case 6: // ovocný sad
return 'zah'
case 7: // trvalý travní porost
case 8:
return 'louka'
case 10: // lesní pozemek
return 'les'
case 11: // vodní plocha
return 'voda'
case 13: // zastavěná plocha a nádvoří
return building ?? (use === 13 ? 'ostn' : 'ost')
}
switch (use) {
case 14: // dráha
case 15: // dálnice
case 16: // silnice
case 17: // ostatní komunikace
case 18: // ostatní dopravní plocha
return 'dop'
case 19: // zeleň
case 21: // pohřebiště
return 'zel'
case 20: // sportoviště a rekreační plocha
case 22: // kulturní a osvětová plocha
case 29: // fotovoltaická elektrárna (technické vybavení)
return 'ver'
case 12: // společný dvůr
return 'ost'
case 6:
case 7:
case 8:
case 9:
case 10:
case 11:
case 28:
return 'voda'
}
return building ?? 'ostn' // jiná plocha, manipulační plocha, neplodná půda, mez, skládka…
}
/* ================= detailed scheme: one colour per RÚIAN use code ================= */
const DETAIL_COLOR: Record<string, string> = {
u1: '#7b3294',
u2: '#8c564b',
@ -144,57 +202,85 @@ const DETAIL_LIST = [
'uw',
'u0',
]
const DETAIL_NUMS = new Set([
'u6',
'u3',
'u8',
'mix',
'u5',
'u15',
'u9',
'u10',
'u11',
'u14',
'u1',
'u12',
])
export function simpleKey(use: number, flats: number | null): string {
const f = flats || 0
if (use === 3) return f >= 4 ? 'unit' : 'res' // generic dwelling
const base = USE_CAT[use] || 'other'
if (base === 'res' || base === 'unit' || base === 'rec') return base
if (mixMin.value > 0 && f >= mixMin.value && base !== 'garage' && base !== 'agri') return 'mix'
return base
}
export function detailKey(use: number, sk: string): string {
if (sk === 'mix') return 'mix'
function detailKey(use: number, mixed: boolean): string {
if (mixed) return 'mix'
if (use >= 1 && use <= 21) return 'u' + use
if (use >= 22 && use <= 29) return 'uw'
return 'u0'
}
/* ================= classification ================= */
/**
* Buildings with `sc`/`cat` set for the current colour mode and mixed-use rule.
* Categories are written onto the building objects (so a selected building stays the same object);
* Buildings with categories for the current mode, mixed-use rule and field corrections.
* Categories are written onto the objects (so a selected building stays the same object);
* a new array is returned so dependants see a change.
*/
export const buildings = computed(() => {
const list = rawBuildings.value,
m = mode.value
m = mode.value,
ov = overrides.value
for (const b of list) {
b.sc = simpleKey(b.use, b.flats)
b.cat = m === 'simple' ? b.sc : detailKey(b.use, b.sc)
b.auto = buildingHg(b.use, b.flats)
b.hg = ov['b:' + b.id] ?? b.auto
b.cat = m === 'hg3' ? b.hg : detailKey(b.use, b.auto === 'smi')
}
return list.slice()
})
/**
* Category of a building in the current mode. Reading `buildings` first makes sure the
* classification is up to date and subscribes the caller to mode / mixed-use changes.
*/
export function catOf(b: Building): string {
// oxlint-disable-next-line no-unused-expressions
buildings.value
return b.cat
/** Parcels with HG3 categories (only drawn in the HG3 mode). */
export const parcels = computed(() => {
const ov = overrides.value
const onParcel = new Map<string, string>()
for (const b of buildings.value) if (b.parcel) onParcel.set(b.parcel, b.hg)
const list = rawParcels.value
for (const p of list) {
p.auto = parcelHg(p.druh, p.use, onParcel.get(p.id))
p.hg = ov['p:' + p.id] ?? p.auto
p.cat = p.hg
}
return list.slice()
})
/** Category of an item in the current mode; reading the lists keeps it current and subscribed. */
export function catOf(item: MapItem): string {
const list: MapItem[] = item.kind === 'b' ? buildings.value : parcels.value
return list.length >= 0 ? item.cat : item.cat
}
export const catColor = (key: string): string =>
(mode.value === 'simple' ? SIMPLE_COLOR[key] : DETAIL_COLOR[key]) || '#bdbdbd'
(mode.value === 'hg3' ? hgColor(key) : DETAIL_COLOR[key]) || '#bdbdbd'
export function catLabel(key: string): string {
if (mode.value === 'simple') return tKey('cat.' + key)
if (mode.value === 'hg3') return hgLabel(key)
if (key === 'mix') return t('cat.mix')
if (key === 'uw') return ruianUseName('w')
if (key === 'u0') return ruianUseName(0)
return key.slice(1) + ' · ' + ruianUseName(+key.slice(1))
}
export const catList = () => (mode.value === 'simple' ? SIMPLE.map((c) => c[0]) : DETAIL_LIST)
export const catOrder = () => (mode.value === 'simple' ? SIMPLE_ORDER : DETAIL_ORDER)
/** Legend order. */
export const catList = () => (mode.value === 'hg3' ? HG.map((c) => c.key) : DETAIL_LIST)
/** Drawing order for buildings (later on top). */
export const catOrder = () => (mode.value === 'hg3' ? HG.map((c) => c.key) : DETAIL_ORDER)
export const showsNumber = (b: Building) =>
mode.value === 'hg3' ? !!HG_BY_KEY[b.cat]?.nums : DETAIL_NUMS.has(b.cat)
export const overrideKey = (item: MapItem) => (item.kind === 'b' ? 'b:' : 'p:') + item.id
export const isCorrected = (item: MapItem) => overrideKey(item) in overrides.value
export function isDark(hex: string): boolean {
const n = parseInt(hex.slice(1), 16),
r = n >> 16,

54
src/codes.ts Normal file
View file

@ -0,0 +1,54 @@
import { lang } from './i18n'
/* Names of the cadastral code lists used for parcels (ČÚZK VFR domains). */
const DRUH: Record<number, [cs: string, en: string]> = {
2: ['orná půda', 'arable land'],
3: ['chmelnice', 'hop field'],
4: ['vinice', 'vineyard'],
5: ['zahrada', 'garden'],
6: ['ovocný sad', 'orchard'],
7: ['trvalý travní porost', 'permanent grassland'],
8: ['trvalý travní porost', 'permanent grassland'],
10: ['lesní pozemek', 'forest land'],
11: ['vodní plocha', 'water area'],
13: ['zastavěná plocha a nádvoří', 'built-up area and courtyard'],
14: ['ostatní plocha', 'other area'],
}
const USE: Record<number, [cs: string, en: string]> = {
1: ['skleník, pařeniště', 'greenhouse, hotbed'],
2: ['školka', 'plant nursery'],
3: ['plantáž dřevin', 'tree plantation'],
4: ['les jiný než hospodářský', 'non-commercial forest'],
5: ['lesní pozemek, na kterém je budova', 'forest land with a building'],
6: ['rybník', 'fishpond'],
7: ['koryto vodního toku přirozené nebo upravené', 'natural or regulated watercourse'],
8: ['koryto vodního toku umělé', 'artificial watercourse'],
9: ['vodní nádrž přírodní', 'natural reservoir'],
10: ['vodní nádrž umělá', 'artificial reservoir'],
11: ['zamokřená plocha', 'wetland'],
12: ['společný dvůr', 'shared courtyard'],
13: ['zbořeniště', 'demolition site'],
14: ['dráha', 'railway'],
15: ['dálnice', 'motorway'],
16: ['silnice', 'road'],
17: ['ostatní komunikace', 'other road / path'],
18: ['ostatní dopravní plocha', 'other transport area'],
19: ['zeleň', 'greenery'],
20: ['sportoviště a rekreační plocha', 'sports and recreation ground'],
21: ['pohřebiště', 'cemetery'],
22: ['kulturní a osvětová plocha', 'cultural area'],
23: ['manipulační plocha', 'handling area / yard'],
24: ['dobývací prostor', 'mining area'],
25: ['skládka', 'landfill'],
26: ['jiná plocha', 'other area'],
27: ['neplodná půda', 'barren land'],
28: ['vodní plocha, na které je budova', 'water area with a building'],
29: ['fotovoltaická elektrárna', 'photovoltaic power plant'],
30: ['mez, stráň', 'balk, slope'],
}
const pick = (v: [string, string] | undefined) => (v ? v[lang.value === 'cs' ? 0 : 1] : '')
export const druhName = (c: number | null) => (c == null ? '' : pick(DRUH[c]))
export const useLandName = (c: number | null) => (c == null ? '' : pick(USE[c]))

View file

@ -3,7 +3,9 @@ import { useEffect } from 'preact/hooks'
import { lang, t } from '../i18n'
import { attachKeyboard } from '../interaction'
import { toast } from '../state'
import { CommentaryDialog } from './CommentaryDialog'
import { MapView } from './MapView'
import { PrintView } from './PrintView'
import { Sidebar } from './Sidebar'
export function App() {
@ -14,6 +16,7 @@ export function App() {
useEffect(attachKeyboard, [])
const tst = toast.value
return (
<>
<div id="app">
<Sidebar />
<MapView />
@ -23,5 +26,9 @@ export function App() {
</div>
)}
</div>
{/* outside #app: print mode hides the app and shows only the print pages */}
<CommentaryDialog />
<PrintView />
</>
)
}

View file

@ -0,0 +1,91 @@
import { useEffect, useRef } from 'preact/hooks'
import { lang, t, type MsgKey } from '../i18n'
import { answered, commentary, commentaryOpen } from '../state'
import { MIN_CHARS } from './Project'
import { Icon } from './ui/Icon'
const QUESTIONS: MsgKey[] = ['q1', 'q2', 'q3', 'q4', 'q5', 'q6']
/** Editor for the commentary (pages 3–4 of the submission), with the assignment's questions. */
export function CommentaryDialog() {
const area = useRef<HTMLTextAreaElement>(null)
const open = commentaryOpen.value
useEffect(() => {
if (open) area.current?.focus()
}, [open])
if (!open) return null
const text = commentary.value,
n = text.length,
words = text.trim() ? text.trim().split(/\s+/).length : 0,
l = lang.value
const done = new Set(answered.value)
const toggle = (i: number) =>
(answered.value = done.has(i) ? answered.value.filter((x) => x !== i) : [...answered.value, i])
const close = () => (commentaryOpen.value = false)
return (
<div
class="dialog-backdrop"
onClick={(e) => {
if (e.target === e.currentTarget) close()
}}
>
<div
class="dialog card"
role="dialog"
aria-modal="true"
aria-labelledby="cm-title"
onKeyDown={(e) => {
if (e.key === 'Escape') {
e.stopPropagation()
close()
}
}}
>
<div class="dialog-head">
<h3 id="cm-title">{t('cm_title')}</h3>
<button type="button" class="icon-btn" aria-label={t('close')} onClick={close}>
<Icon name="close" />
</button>
</div>
<p class="hint">{t('cm_hint')}</p>
<div class="dialog-body">
<textarea
ref={area}
value={text}
placeholder={t('cm_placeholder')}
spellcheck
lang={l}
onInput={(e) => (commentary.value = e.currentTarget.value)}
/>
<aside class="questions">
<h4>{t('cm_questions')}</h4>
<ol>
{QUESTIONS.map((q, i) => (
<li key={q}>
<label>
<input type="checkbox" checked={done.has(i)} onChange={() => toggle(i)} />
<span>{t(q)}</span>
</label>
</li>
))}
</ol>
</aside>
</div>
<div class="dialog-foot">
<div class={n >= MIN_CHARS ? 'meter ok' : 'meter low'}>
<div class="meter-head">
<span>{t('cm_count', n, words)}</span>
<b>{n >= MIN_CHARS ? t('cm_ok') : t('cm_need', MIN_CHARS - n)}</b>
</div>
<div class="meter-bar">
<span style={{ width: `${Math.min(100, (n / MIN_CHARS) * 100)}%` }} />
</div>
</div>
<button type="button" class="btn primary" onClick={close}>
{t('cm_done')}
</button>
</div>
</div>
</div>
)
}

View file

@ -1,27 +1,46 @@
import { catColor, catLabel, catOf } from '../categories'
import { catColor, catLabel, catOf, HG, hgLabel, isCorrected, overrideKey } from '../categories'
import { druhName, useLandName } from '../codes'
import { m2ll } from '../geo'
import { ruianUseName, t } from '../i18n'
import { sel } from '../state'
import { lang, ruianUseName, t } from '../i18n'
import { mode, overrides, sel } from '../state'
import type { MapItem } from '../types'
import { Icon } from './ui/Icon'
const DASH = '—'
const orDash = (v: number | null, unit = '') => (v == null ? DASH : v + unit)
const orDash = (v: number | null, unit = '') =>
v == null ? DASH : v.toLocaleString(lang.value) + unit
/** Details of the selected building. */
export const itemTitle = (it: MapItem) =>
it.kind === 'p' ? t('parcelNo', it.num) : it.cp ? t('hn', it.cp) : t('nohn')
/** Set or clear (value '') the field correction of an item. */
function correct(it: MapItem, value: string) {
const next = { ...overrides.value },
k = overrideKey(it)
if (!value || value === it.auto) delete next[k]
else next[k] = value
overrides.value = next
}
/** Details of the selected building or parcel, with the field-correction picker (HG3 mode). */
export function InfoPanel() {
const b = sel.value
if (!b) return null
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')
const it = sel.value
if (!it) return null
const cat = catOf(it),
ll = m2ll((it.bb[0] + it.bb[2]) / 2, (it.bb[1] + it.bb[3]) / 2)
const title = itemTitle(it)
const corrected = isCorrected(it)
return (
// 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}>
// key: replay the entry animation when another item is selected
<div id="info" class="card info" key={it.kind + it.id} 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 class="info-cat">
{catLabel(cat)}
{corrected && <span class="tag">{t('corrected')}</span>}
</div>
</div>
<button
type="button"
@ -33,24 +52,73 @@ export function InfoPanel() {
<Icon name="close" />
</button>
</div>
{mode.value === 'hg3' && (
<div class="fix">
<label class="field-label" for="fixcat">
<Icon name="edit" size={14} />
{t('i_fixcat')}
</label>
<div class="select">
<select
id="fixcat"
value={corrected ? it.hg : ''}
onChange={(e) => correct(it, e.currentTarget.value)}
>
<option value="">{t('autoOpt', hgLabel(it.auto))}</option>
<optgroup label={t('g_built')}>
{HG.filter((c) => c.built).map((c) => (
<option key={c.key} value={c.key}>
{hgLabel(c.key)}
</option>
))}
</optgroup>
<optgroup label={t('g_open')}>
{HG.filter((c) => !c.built).map((c) => (
<option key={c.key} value={c.key}>
{hgLabel(c.key)}
</option>
))}
</optgroup>
</select>
<Icon name="chevron" />
</div>
</div>
)}
{it.kind === 'b' ? (
<dl>
<dt>{t('i_use')}</dt>
<dd>
{ruianUseName(b.use) || DASH} <span class="muted">({b.use || '?'})</span>
{ruianUseName(it.use) || DASH} <span class="muted">({it.use || '?'})</span>
</dd>
<dt>{t('i_flats')}</dt>
<dd>{orDash(b.flats)}</dd>
<dd>{orDash(it.flats)}</dd>
<dt>{t('i_floors')}</dt>
<dd>{orDash(b.floors)}</dd>
<dd>{orDash(it.floors)}</dd>
<dt>{t('i_area')}</dt>
<dd>{orDash(b.area, ' m²')}</dd>
<dd>{orDash(it.area, ' m²')}</dd>
<dt>{t('i_done')}</dt>
<dd>{orDash(b.year)}</dd>
<dd>{it.year ?? DASH}</dd>
<dt>{t('i_pos')}</dt>
<dd class="mono">
{ll[1].toFixed(6)}, {ll[0].toFixed(6)}
</dd>
</dl>
) : (
<dl>
<dt>{t('i_druh')}</dt>
<dd>{druhName(it.druh) || DASH}</dd>
<dt>{t('i_landuse')}</dt>
<dd>{useLandName(it.use) || DASH}</dd>
<dt>{t('i_parea')}</dt>
<dd>{orDash(it.area, ' m²')}</dd>
<dt>{t('i_pos')}</dt>
<dd class="mono">
{ll[1].toFixed(6)}, {ll[0].toFixed(6)}
</dd>
</dl>
)}
</div>
)
}

View file

@ -1,7 +1,8 @@
import { catColor, catLabel, catList } from '../categories'
import { t } from '../i18n'
import { catColor, catLabel, catList, HG_BUILT, HG_OPEN } from '../categories'
import { lang, t, tKey } from '../i18n'
import { counts } from '../render'
import { focusCat, hidden } from '../state'
import { focusCat, hidden, mode } from '../state'
import { fmtPct, frameStats } from '../stats'
function toggle(key: string) {
const next = new Set(hidden.value)
@ -17,49 +18,82 @@ function only(key: string) {
}
/**
* Category list with counts; categories absent from the loaded area are not shown.
* Category list. In the HG3 mode it is grouped like the assignment's legend and shows each
* category's share of the A4 frame; otherwise building counts. Empty categories are hidden.
* 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])
const cnt = counts()
if (mode.value !== 'hg3')
return (
<div id="legend" onMouseLeave={() => (focusCat.value = null)}>
{rows.map((key) => {
const on = !hid.has(key)
{catList()
.filter((k) => cnt[k])
.map((k) => (
<Row key={k} k={k} value={String(cnt[k])} />
))}
</div>
)
const st = frameStats.value,
l = lang.value
const value = (k: string) =>
st && st.total ? (st.area[k] > 0 ? fmtPct(st.area[k] / st.total, l) : '–') : String(cnt[k] ?? 0)
const present = (k: string) => (cnt[k] ?? 0) > 0
const group = (title: string, keys: string[]) => {
const ks = keys.filter(present)
if (!ks.length) return null
return (
<>
<div class="leg-group">{title}</div>
{ks.map((k) => (
<Row key={k} k={k} value={value(k)} desc={tKey('hgd.' + k)} />
))}
</>
)
}
return (
<>
<div id="legend" onMouseLeave={() => (focusCat.value = null)}>
{group(t('g_built'), HG_BUILT)}
{group(t('g_open'), HG_OPEN)}
</div>
{Object.keys(cnt).length > 0 && <p class="hint">{t('legendHintHg')}</p>}
</>
)
}
function Row({ k, value, desc }: { k: string; value: string; desc?: string }) {
const on = !hidden.value.has(k)
// tKey returns the key itself when there is no description
const help = desc && !desc.startsWith('hgd.') ? desc : ''
return (
<label
key={key}
class={on ? 'leg' : 'leg off'}
title={t('onlyHint')}
onMouseEnter={() => (focusCat.value = on ? key : null)}
title={(help ? help + '\n' : '') + t('onlyHint')}
onMouseEnter={() => (focusCat.value = on ? k : null)}
onClick={(e) => {
if (!e.altKey) return
e.preventDefault() // keep the checkbox from toggling as well
only(key)
only(k)
}}
onDblClick={(e) => {
e.preventDefault()
only(key)
only(k)
}}
>
<input
type="checkbox"
checked={on}
onChange={() => {
toggle(key)
toggle(k)
focusCat.value = null
}}
onFocus={() => (focusCat.value = on ? key : null)}
onFocus={() => (focusCat.value = on ? k : null)}
onBlur={() => (focusCat.value = null)}
/>
<span class="sw" style={{ background: catColor(key) }} />
<span class="lbl">{catLabel(key)}</span>
<span class="n">{cnt[key]}</span>
<span class="sw" style={{ background: catColor(k) }} />
<span class="lbl">{catLabel(k)}</span>
<span class="n">{value}</span>
</label>
)
})}
</div>
)
}

View file

@ -6,7 +6,7 @@ import { attachPointer, resize, zoomBy, zoomFit } from '../interaction'
import { draw, drawScene, requestDraw, trackScene } from '../render'
import { hover, S, vp } from '../state'
import { LIGHT } from '../theme'
import { InfoPanel } from './InfoPanel'
import { InfoPanel, itemTitle } from './InfoPanel'
import { LoadingOverlay } from './LoadingOverlay'
import { Icon } from './ui/Icon'
@ -106,7 +106,7 @@ function Tooltip() {
}}
>
<span class="sw" style={{ background: catColor(cat) }} />
<b>{h.b.cp ? t('hn', h.b.cp) : t('nohn')}</b> {catLabel(cat)}
<b>{itemTitle(h.b)}</b> {catLabel(cat)}
</div>
)
}

View file

@ -0,0 +1,106 @@
import { useEffect } from 'preact/hooks'
import { HG, hgColor, type HgCat } from '../categories'
import { lang, t, tKey } from '../i18n'
import { mapBoxMM } from '../page'
import { commentary, mapAuthor, mapTitle, orientation, printJob } from '../state'
import { frameStats } from '../stats'
/** Short legend label: "Ostatní plochy" under its group heading, like the assignment's legend. */
const legendLabel = (k: string) => {
const s = tKey('hgs.' + k)
return s.startsWith('hgs.') ? tKey('hg.' + k) : s
}
/**
* Pages for printing / "Save as PDF", shown only while a print job is prepared.
* Submission: 1 map, 2 legend, 3–4 commentary. Worksheet: blank map and a legend to colour in.
*/
export function PrintView() {
const job = printJob.value
useEffect(() => {
const done = () => {
const j = printJob.value
if (!j) return
URL.revokeObjectURL(j.mapUrl)
printJob.value = null
}
window.addEventListener('afterprint', done)
return () => window.removeEventListener('afterprint', done)
}, [])
useEffect(() => {
document.documentElement.classList.toggle('printing', !!job)
}, [job])
if (!job) return null
const ws = job.kind === 'worksheet',
o = orientation.value,
[wmm, hmm] = mapBoxMM(o)
const title = mapTitle.value.trim() || t('title'),
author = mapAuthor.value.trim()
const date = new Date().toLocaleDateString(lang.value, {
day: 'numeric',
month: 'long',
year: 'numeric',
})
const st = frameStats.value
// the legend lists only categories that occur in the frame (the worksheet lists all 16)
const present = (c: HgCat) => ws || !st || (st.area[c.key] ?? 0) > 0
const group = (built: boolean) => HG.filter((c) => c.built === built && present(c))
return (
<div class="print-root">
<section class={`pg pg-map ${o}`}>
<header class="pg-head">
<b>{ws ? `${t('worksheetTitle')} – ${title}` : title}</b>
<span>{author}</span>
</header>
<img src={job.mapUrl} alt="" style={{ width: `${wmm}mm`, height: `${hmm}mm` }} />
<footer class="pg-foot">
<span>{t('scaleText')}</span>
<span>{t('source')}</span>
<span>{date}</span>
</footer>
</section>
<section class="pg pg-legend">
<h1>{ws ? t('worksheetLegend') : t('legendTitle')}</h1>
{[true, false].map((built) => {
const cats = group(built)
if (!cats.length) return null
return (
<div class="pg-group" key={String(built)}>
<h2>{t(built ? 'g_built' : 'g_open')}</h2>
{cats.map((c) => {
const desc = tKey('hgd.' + c.key)
return (
<div class="pg-leg" key={c.key}>
<span
class={ws ? 'pg-sw empty' : 'pg-sw'}
style={ws ? undefined : { background: hgColor(c.key) }}
/>
<span>
{legendLabel(c.key)}
{!desc.startsWith('hgd.') && <small> ({desc})</small>}
</span>
{ws && <span class="pg-crayon">{t('crayonNo')}: ______</span>}
</div>
)
})}
</div>
)
})}
<p class="pg-note">
{title}
{author ? ` · ${author}` : ''} · {t('scaleText')} · {t('source')}
</p>
</section>
{!ws && (
<section class="pg pg-text">
<h1>{t('commentaryTitle')}</h1>
<div class="pg-body">{commentary.value}</div>
</section>
)}
</div>
)
}

238
src/components/Project.tsx Normal file
View file

@ -0,0 +1,238 @@
import { useRef } from 'preact/hooks'
import { loadFrame, openProject, preparePrint } from '../actions'
import { HG, hgColor, hgLabel } from '../categories'
import { exportStatsCsv, saveProject } from '../export'
import { lang, t } from '../i18n'
import { frameCovered } from '../page'
import {
busy,
commentary,
commentaryOpen,
mapAuthor,
mapTitle,
orientation,
overrides,
rawBuildings,
showFrame,
viewVersion,
} from '../state'
import { fmtPct, frameStats, type FrameStats } from '../stats'
import type { Orientation } from '../types'
import { Icon } from './ui/Icon'
import { Segmented } from './ui/Segmented'
import { Switch } from './ui/Switch'
export const MIN_BUILT = 0.66
export const MIN_CHARS = 3600
/** Everything needed for the HG3 submission: frame, built-up check, PDF, commentary, project file. */
export function ProjectSection() {
// re-check frame coverage after the view settles
void viewVersion.value
const st = frameStats.value
const loaded = rawBuildings.value.length > 0
const covered = loaded && frameCovered()
const nCorr = Object.keys(overrides.value).length
const chars = commentary.value.length
const file = useRef<HTMLInputElement>(null)
return (
<section class="card project">
<h2>
<Icon name="flag" />
{t('project')}
</h2>
<div class="grid2">
<div>
<label class="field-label" for="pr-title">
{t('pr_title')}
</label>
<input
id="pr-title"
class="text"
type="text"
value={mapTitle.value}
onInput={(e) => (mapTitle.value = e.currentTarget.value)}
/>
</div>
<div>
<label class="field-label" for="pr-author">
{t('pr_author')}
</label>
<input
id="pr-author"
class="text"
type="text"
value={mapAuthor.value}
onInput={(e) => (mapAuthor.value = e.currentTarget.value)}
/>
</div>
</div>
<div class="row-between">
<span class="field-label">{t('pr_orient')}</span>
<Segmented<Orientation>
size="sm"
label={t('pr_orient')}
value={orientation.value}
onChange={(v) => (orientation.value = v)}
options={[
{ value: 'landscape', label: t('landscape') },
{ value: 'portrait', label: t('portrait') },
]}
/>
</div>
<Switch checked={showFrame.value} onChange={(v) => (showFrame.value = v)}>
{t('pr_frame')}
</Switch>
{showFrame.value && <p class="hint">{t('frameHint')}</p>}
{st && st.total > 0 && <BuiltMeter st={st} />}
{loaded && !covered && (
<div class="status warn">
<Icon name="alert" />
<div class="status-body">
<span class="status-text">{t('frameOut')} </span>
<button type="button" class="link inline" disabled={busy.value} onClick={loadFrame}>
{t('loadFrame')}
</button>
</div>
</div>
)}
<button
type="button"
class="btn primary block"
disabled={!covered || busy.value}
onClick={() => preparePrint('submission')}
>
<Icon name="download" />
{t('pdf')}
</button>
<p class="hint">{t('pdfHint')}</p>
<div class="exp">
<button type="button" class="btn ghost" onClick={() => (commentaryOpen.value = true)}>
<Icon name="text" />
{t('commentaryBtn')}
<span class={chars >= MIN_CHARS ? 'count ok' : 'count'}>
{chars.toLocaleString(lang.value)}
</span>
</button>
<button
type="button"
class="btn ghost"
disabled={!covered || busy.value}
onClick={() => preparePrint('worksheet')}
>
<Icon name="print" />
{t('worksheet')}
</button>
</div>
<div class="row-between project-file">
<span class="muted">{t('corrections', nCorr)}</span>
<div class="sec-actions">
<button type="button" class="link" onClick={saveProject}>
{t('saveProject')}
</button>
<button type="button" class="link" onClick={() => file.current?.click()}>
{t('loadProject')}
</button>
</div>
</div>
<input
ref={file}
type="file"
accept="application/json,.json"
hidden
onChange={(e) => {
const f = e.currentTarget.files?.[0]
if (f) openProject(f)
e.currentTarget.value = ''
}}
/>
</section>
)
}
/** Built-up share of the frame against the assignment's 66 % minimum. */
function BuiltMeter({ st }: { st: FrameStats }) {
const l = lang.value,
ok = st.settlementShare >= MIN_BUILT
return (
<div class={ok ? 'meter ok' : 'meter low'} title={t('builtDef')}>
<div class="meter-head">
<span>{t('builtShare')}</span>
<b>{fmtPct(st.settlementShare, l)}</b>
</div>
<div class="meter-bar" role="img" aria-label={fmtPct(st.settlementShare, l)}>
<span style={{ width: `${Math.min(100, st.settlementShare * 100)}%` }} />
<i style={{ left: `${MIN_BUILT * 100}%` }} />
</div>
<p class="hint">
{st.source === 'buildings' ? t('noParcels') : ok ? t('builtOk') : t('builtLow')}
{st.source === 'parcels' && <> · {t('builtStrict', fmtPct(st.share, l))}</>}
</p>
</div>
)
}
/** Area per category inside the frame – facts for the commentary. */
export function StatsSection() {
const st = frameStats.value
if (!st || !st.total) return null
const l = lang.value
const m2 = (a: number) => Math.round(a).toLocaleString(l)
const rows = (built: boolean) =>
HG.filter((c) => c.built === built && st.area[c.key] > 0).map((c) => (
<tr key={c.key}>
<td>
<span class="sw" style={{ background: hgColor(c.key) }} />
</td>
<td>{hgLabel(c.key)}</td>
<td class="num">{m2(st.area[c.key])}</td>
<td class="num">{fmtPct(st.area[c.key] / st.total, l)}</td>
</tr>
))
return (
<details class="stats">
<summary>
<h2>{t('stats')}</h2>
<Icon name="chevron" class="icon chev" />
</summary>
<table>
<thead>
<tr>
<th />
<th />
<th class="num">{t('areaM2')}</th>
<th class="num">{t('share')}</th>
</tr>
</thead>
<tbody>
<tr class="grp">
<td colSpan={2}>{t('g_built')}</td>
<td class="num">{m2(st.built)}</td>
<td class="num">{fmtPct(st.share, l)}</td>
</tr>
{rows(true)}
<tr class="grp">
<td colSpan={2}>{t('g_open')}</td>
<td class="num">{m2(st.total - st.built)}</td>
<td class="num">{fmtPct(1 - st.share, l)}</td>
</tr>
{rows(false)}
<tr class="grp total">
<td colSpan={2}>{t('total')}</td>
<td class="num">{m2(st.total)}</td>
<td class="num">100 %</td>
</tr>
</tbody>
</table>
<button type="button" class="btn ghost block" onClick={exportStatsCsv}>
<Icon name="table" />
{t('statsCsv')}
</button>
</details>
)
}

View file

@ -21,6 +21,7 @@ import {
} from '../state'
import type { Mode } from '../types'
import { Legend } from './Legend'
import { ProjectSection, StatsSection } from './Project'
import { StatusLine } from './StatusLine'
import { Icon, type IconName } from './ui/Icon'
import { Segmented } from './ui/Segmented'
@ -37,7 +38,9 @@ export function Sidebar() {
<LocationForm />
<StatusLine />
</section>
{mode.value === 'hg3' && <ProjectSection />}
<LayersSection />
{mode.value === 'hg3' && <StatsSection />}
<section>
<h2>{t('display')}</h2>
<DisplayOptions />
@ -248,12 +251,12 @@ function DisplayOptions() {
})
}
options={[
{ value: 'simple', label: t('modeSimple').split(' – ')[0] },
{ value: 'hg3', label: t('modeHg3').split(' – ')[0] },
{ value: 'detailed', label: t('modeDetailed').split(' – ')[0] },
]}
/>
<p class="hint">
{(mode.value === 'simple' ? t('modeSimple') : t('modeDetailed')).split(' – ')[1]}
{(mode.value === 'hg3' ? t('modeHg3') : t('modeDetailed')).split(' – ')[1]}
</p>
</div>
@ -276,9 +279,11 @@ function DisplayOptions() {
</div>
<div class="switches">
{mode.value === 'detailed' && (
<Switch checked={showBase.value} onChange={(v) => (showBase.value = v)}>
{t('optBase')}
</Switch>
)}
<Switch checked={showNums.value} onChange={(v) => (showNums.value = v)}>
{t('optNums')}
</Switch>

View file

@ -67,6 +67,19 @@ const P = {
</>
),
spinner: <path d="M12 3a9 9 0 1 0 9 9" />,
text: <path d="M5 6h14M5 10h14M5 14h14M5 18h9" />,
flag: (
<>
<path d="M5 21V4" />
<path d="M5 4h11l-2 4 2 4H5" />
</>
),
edit: (
<>
<path d="M4 20h4L19 9l-4-4L4 16z" />
<path d="m13.5 6.5 4 4" />
</>
),
}
export type IconName = keyof typeof P

View file

@ -1,14 +1,27 @@
import { BASE } from './basemap'
import { buildings, catColor, catLabel, catOrder } from './categories'
import {
buildings,
catColor,
catLabel,
catList,
catOrder,
HG,
hgLabel,
isCorrected,
parcels,
} from './categories'
import { m2ll } from './geo'
import { ruianUseName } from './i18n'
import { druhName, useLandName } from './codes'
import { lang, ruianUseName, t } from './i18n'
import { projectData } from './actions'
import { frameStats } from './stats'
import { drawLegend, drawScene, legendLayout, pxPerMeter } from './render'
import { base, hidden, S, showBase, vp } from './state'
import { base, hidden, mapTitle, mode, S, showBase, vp } from './state'
import { LIGHT } from './theme'
import type { Ring } from './types'
/* ================= export ================= */
function download(blob: Blob, name: string) {
export function download(blob: Blob, name: string) {
const a = document.createElement('a')
a.href = URL.createObjectURL(blob)
a.download = name
@ -49,7 +62,16 @@ export function exportSvg() {
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="${LIGHT.bg}"/><g clip-path="url(#c)" stroke-linejoin="round" stroke-linecap="round">`
if (showBase.value)
const hg = mode.value === 'hg3'
if (hg) {
for (const key of catList()) {
if (hidden.value.has(key)) continue
const rings: Ring[] = []
for (const p of parcels.value) if (p.cat === key) for (const r of p.rings) rings.push(r)
if (rings.length)
o += `<path d="${d(rings, true)}" fill="${catColor(key)}" fill-rule="evenodd" stroke="#00000052" stroke-width=".5"/>`
}
} else if (showBase.value)
for (const st of BASE) {
const rings = base.value[st.k]
if (!rings || !rings.length) continue
@ -63,7 +85,7 @@ export function exportSvg() {
const rings: Ring[] = []
for (const b of buildings.value) if (b.cat === key) for (const r of b.rings) rings.push(r)
if (rings.length)
o += `<path d="${d(rings, true)}" fill="${catColor(key)}" fill-rule="evenodd" stroke="${key === 'res' || key === 'u7' ? '#ffffff88' : '#00000088'}" stroke-width=".5"/>`
o += `<path d="${d(rings, true)}" fill="${catColor(key)}" fill-rule="evenodd" stroke="${hg ? '#0000009e' : key === 'u7' ? '#ffffff88' : '#00000088'}" stroke-width="${hg ? 0.8 : 0.5}"/>`
}
o += '</g>'
o += `<rect y="${H}" width="${W}" height="${lh}" fill="#fff"/><g font-family="system-ui,sans-serif" font-size="12">`
@ -78,19 +100,26 @@ export function exportSvg() {
download(new Blob([o], { type: 'image/svg+xml' }), 'building-use-map.svg')
}
const q = (s: unknown) => '"' + String(s).replace(/"/g, '""') + '"'
const csvBlob = (o: string) => new Blob(['\ufeff' + o], { type: 'text/csv;charset=utf-8' }) // BOM so Excel reads UTF-8
/** Buildings and, in the HG3 mode, parcels with their categories and field corrections. */
export function exportCsv() {
if (!S.loaded) return
const q = (s: unknown) => '"' + String(s).replace(/"/g, '""') + '"'
const hg = mode.value === 'hg3'
let o =
'house_no,ruian_use_code,ruian_use,category,flats,floors,built_up_area_m2,completed,lat,lon\n'
'type,id,house_or_parcel_no,ruian_code,ruian_name,category,corrected,flats,floors,area_m2,completed,lat,lon\n'
for (const b of buildings.value) {
const ll = m2ll((b.bb[0] + b.bb[2]) / 2, (b.bb[1] + b.bb[3]) / 2)
o +=
[
'building',
b.id,
q(b.cp),
b.use,
q(ruianUseName(b.use)),
q(catLabel(b.cat)),
q(hg ? hgLabel(b.hg) : catLabel(b.cat)),
isCorrected(b) ? 1 : 0,
b.flats ?? '',
b.floors ?? '',
b.area ?? '',
@ -99,5 +128,65 @@ export function exportCsv() {
ll[0].toFixed(6),
].join(',') + '\n'
}
download(new Blob(['' + o], { type: 'text/csv;charset=utf-8' }), 'buildings.csv') // BOM so Excel reads UTF-8
if (hg)
for (const p of parcels.value) {
const ll = m2ll((p.bb[0] + p.bb[2]) / 2, (p.bb[1] + p.bb[3]) / 2)
const code = [p.druh, p.use].filter((x) => x != null).join('/')
const name = [druhName(p.druh), useLandName(p.use)].filter(Boolean).join(' – ')
o +=
[
'parcel',
p.id,
q(p.num),
q(code),
q(name),
q(hgLabel(p.hg)),
isCorrected(p) ? 1 : 0,
'',
'',
p.area ?? '',
'',
ll[1].toFixed(6),
ll[0].toFixed(6),
].join(',') + '\n'
}
download(csvBlob(o), hg ? 'hg3-plochy.csv' : 'buildings.csv')
}
/** Area per HG3 category inside the A4 frame. */
export function exportStatsCsv() {
const st = frameStats.value
if (!st) return
const l = lang.value,
n = (x: number) => x.toFixed(1),
pct = (x: number) => (st.total ? ((x / st.total) * 100).toFixed(2) : '0')
let o = 'group,category,area_m2,share_percent\n'
for (const c of HG) {
const a = st.area[c.key] ?? 0
if (!a) continue
o += [q(t(c.built ? 'g_built' : 'g_open')), q(hgLabel(c.key)), n(a), pct(a)].join(',') + '\n'
}
o += [q(t('g_built')), q(t('total')), n(st.built), pct(st.built)].join(',') + '\n'
o +=
[q(t('g_open')), q(t('total')), n(st.total - st.built), pct(st.total - st.built)].join(',') +
'\n'
o += [q(''), q(t('total')), n(st.total), '100'].join(',') + '\n'
download(csvBlob(o), l === 'cs' ? 'hg3-statistika.csv' : 'hg3-statistics.csv')
}
const slug = (s: string) =>
s
.normalize('NFD')
.replace(/[\u0300-\u036f]/g, '')
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-|-$/g, '')
/** Save corrections, texts and settings to a JSON file (to continue on another device). */
export function saveProject() {
const name = slug(mapTitle.value) || 'projekt'
download(
new Blob([JSON.stringify(projectData(), null, 2)], { type: 'application/json' }),
`hg3-${name}.json`,
)
}

View file

@ -1,11 +1,12 @@
import { ZAB_LAYERS, type BaseKey } from './basemap'
import { mkBuilding } from './building'
import { mkBuilding, mkParcel } from './building'
import { D2R } from './geo'
import type { AreaData, BaseData, Ring } from './types'
import { errMsg, sleep } from './util'
/* ================= fetching from ČÚZK ================= */
const RUIAN = 'https://ags.cuzk.cz/arcgis/rest/services/RUIAN/MapServer/3/query'
const RUIAN = 'https://ags.cuzk.cz/arcgis/rest/services/RUIAN/MapServer/3/query' // stavební objekty
const PARCELS = 'https://ags.cuzk.cz/arcgis/rest/services/RUIAN/MapServer/5/query' // parcely
const ZAB = 'https://ags.cuzk.cz/arcgis/rest/services/ZABAGED_POLOHOPIS/MapServer/'
interface Feature {
@ -121,23 +122,28 @@ export async function fetchArea(
const dLat = (radius * 1.1) / 111320,
dLon = (radius * 1.1) / (111320 * Math.cos(lat * D2R))
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 bFields =
'kod,identifikacniparcela,cisladomovni,zpusobvyuzitikod,pocetbytu,pocetpodlazi,zastavenaplocha,dokonceni'
const pFields = 'id,cisloparcely,druhpozemkukod,zpusobyvyuzitipozemku,vymeraparcely'
const keys = Object.keys(ZAB_LAYERS) as BaseKey[]
const total = keys.length + 1
const total = keys.length + 2
let done = 0
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)
// Buildings, parcels 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 other requests.
const buildingsP = queryAll(RUIAN, bFields, env).finally(tick)
const parcelsP = pool([() => queryAll(PARCELS, pFields, env).finally(tick)], 1)
const basesP = pool(
keys.map((k) => () => baseLayer(ZAB_LAYERS[k], env).finally(tick)),
3,
2,
)
const features = await buildingsP
const [pRes] = await parcelsP
const res = await basesP
const base: BaseData = {},
fails: string[] = []
if (!pRes.ok) fails.push('parcely: ' + errMsg(pRes.e))
keys.forEach((k, i) => {
const r = res[i]
if (r.ok) base[k] = r.v.flatMap(ringsOf)
@ -151,6 +157,8 @@ export async function fetchArea(
.map((f) => {
const a = lowerKeys(f.attributes)
return mkBuilding(
a.kod as N,
a.identifikacniparcela as N,
a.cisladomovni as string | null,
a.zpusobvyuzitikod as N,
a.pocetbytu as N,
@ -161,5 +169,18 @@ export async function fetchArea(
)
})
.filter((b) => b.rings.length)
return { buildings, base, fails }
const parcels = (pRes.ok ? pRes.v : [])
.map((f) => {
const a = lowerKeys(f.attributes)
return mkParcel(
a.id as N,
a.cisloparcely as string | null,
a.druhpozemkukod as N,
a.zpusobyvyuzitipozemku as N,
a.vymeraparcely as N,
ringsOf(f),
)
})
.filter((p) => p.rings.length)
return { buildings, parcels, base, fails }
}

View file

@ -1,4 +1,4 @@
import type { LatLon } from './types'
import type { LatLon, Point, Ring } from './types'
/* ================= geometry helpers ================= */
export const R = 6378137,
@ -8,6 +8,46 @@ export const m2ll = (x: number, y: number): [number, number] => [
x / R / D2R,
(2 * Math.atan(Math.exp(y / R)) - Math.PI / 2) / D2R,
]
/** [lon, lat] → Web Mercator metres */
export const ll2m = (lon: number, lat: number): Point => [
lon * D2R * R,
Math.log(Math.tan(Math.PI / 4 + (lat * D2R) / 2)) * R,
]
/** Signed area of a ring (shoelace), in squared input units. */
export function ringArea(r: Ring): number {
let a = 0
for (let i = 0, j = r.length - 1; i < r.length; j = i++)
a += (r[j][0] - r[i][0]) * (r[j][1] + r[i][1])
return a / 2
}
/** Clip a ring to an axis-aligned rectangle (Sutherland–Hodgman). */
export function clipRing(r: Ring, x0: number, y0: number, x1: number, y1: number): Ring {
let out: Ring = r
const edges: [(p: Point) => boolean, (a: Point, b: Point) => Point][] = [
[(p) => p[0] >= x0, (a, b) => [x0, a[1] + ((b[1] - a[1]) * (x0 - a[0])) / (b[0] - a[0])]],
[(p) => p[0] <= x1, (a, b) => [x1, a[1] + ((b[1] - a[1]) * (x1 - a[0])) / (b[0] - a[0])]],
[(p) => p[1] >= y0, (a, b) => [a[0] + ((b[0] - a[0]) * (y0 - a[1])) / (b[1] - a[1]), y0]],
[(p) => p[1] <= y1, (a, b) => [a[0] + ((b[0] - a[0]) * (y1 - a[1])) / (b[1] - a[1]), y1]],
]
for (const [inside, cut] of edges) {
const input = out
out = []
if (!input.length) break
for (let i = 0; i < input.length; i++) {
const cur = input[i],
prev = input[(i + input.length - 1) % input.length]
const ci = inside(cur),
pi = inside(prev)
if (ci) {
if (!pi) out.push(cut(prev, cur))
out.push(cur)
} else if (pi) out.push(cut(prev, cur))
}
}
return out
}
/* ================= location parsing ================= */
export function parseLoc(text: string): LatLon | null {

View file

@ -12,7 +12,7 @@ const en = {
layers: 'Layers',
display: 'Display',
colorMode: 'Colour scheme',
modeSimple: 'Simple – grouped categories',
modeHg3: 'HG3 assignment – 16 land-use categories',
modeDetailed: 'Detailed – one colour per use code',
mixLabel: 'Mixed-use rule',
mix1: 'Non-residential use with ≥ 1 flat',
@ -23,7 +23,7 @@ const en = {
export: 'Export',
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.',
note: 'In the HG3 mode every building and every cadastral parcel is coloured with one of the 16 categories of the semester project. Buildings are classified from their registered use in RÚIAN (a non-residential building with flats counts as mixed use), parcels from their land type and land use; a built-up parcel takes the category of its building. The registry can be outdated – correct it from your fieldwork by clicking a building or parcel.<br><br>Data © ČÚZK (RÚIAN, ZABAGED). Drag to pan, scroll or pinch to zoom.',
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`,
@ -53,6 +53,97 @@ const en = {
zoomOut: 'Zoom out (−)',
fit: 'Fit area (0)',
close: 'Close',
'hg.byt': 'Housing – apartment buildings',
'hg.rd': 'Housing – family houses',
'hg.rek': 'Individual recreation (cottages, garden houses)',
'hg.ver': 'Public services',
'hg.kom': 'Commercial services',
'hg.pru': 'Industry',
'hg.dop': 'Transport networks and facilities',
'hg.smi': 'Mixed use',
'hg.ost': 'Other areas (built-up)',
'hg.zel': 'Maintained greenery (parks, cemeteries)',
'hg.zah': 'Gardens',
'hg.pole': 'Fields',
'hg.louka': 'Meadows',
'hg.les': 'Forests',
'hg.voda': 'Water areas',
'hg.ostn': 'Other areas (undeveloped)',
'hgs.ost': 'Other areas',
'hgs.ostn': 'Other areas',
'hgd.ver':
'administration, schools, health care, social care, cultural sites, sports grounds, technical networks',
'hgd.dop': 'roads, railways, airports, car parks',
'hgd.smi': 'one building with several functions, e.g. flats above shops',
g_built: 'Built-up areas',
g_open: 'Undeveloped areas',
project: 'HG3 semester project',
pr_title: 'Map title',
pr_author: 'Author',
pr_orient: 'A4 page',
landscape: 'Landscape',
portrait: 'Portrait',
pr_frame: 'Show the A4 frame (1 : 3 780)',
frameHint: 'Pan the map to place the frame – only what is inside is printed.',
builtShare: 'Built-up territory in the frame',
builtStrict: (p: string) => `of which built-up areas of the legend: ${p}`,
builtDef:
'Built-up territory (zastavěné území) = built-up areas of the legend + gardens + maintained greenery. Built-up areas of the legend alone are shown below.',
builtOk: 'meets the assignment (at least 66 %)',
builtLow: 'the assignment asks for at least 66 % – pick a more built-up area',
noParcels: 'No parcels loaded (sample data) – shares are from buildings only.',
frameOut: 'The frame reaches beyond the loaded data.',
loadFrame: 'Load data for the frame',
pdf: 'Submission PDF',
pdfHint: 'Page 1 map · 2 legend · 3–4 commentary. In the print dialog choose “Save as PDF”.',
worksheet: 'Field worksheet',
commentaryBtn: 'Commentary',
chars: (n: number) => `${n.toLocaleString('en')} / 3,600 characters`,
corrections: (n: number) => `Field corrections: ${n}`,
saveProject: 'Save project',
loadProject: 'Open project',
projectLoaded: 'Project loaded',
projectBad: 'This file is not a project of this app.',
stats: 'Areas in the frame',
statsCsv: 'Statistics (CSV)',
total: 'Total',
areaM2: 'Area (m²)',
share: 'Share',
legendHintHg:
'Click a building or parcel on the map to correct its category from your fieldwork.',
i_parcel: 'Parcel',
i_druh: 'Land type',
i_landuse: 'Land use',
i_parea: 'Registered area',
i_fixcat: 'Category (field correction)',
autoOpt: (s: string) => `From the registry: ${s}`,
corrected: 'corrected',
parcelNo: (n: string) => `Parcel no. ${n}`,
legendTitle: 'Legend',
commentaryTitle: 'Commentary',
scaleText: 'Scale 1 : 3 780',
source: 'Data: RÚIAN, © ČÚZK',
worksheetTitle: 'Field worksheet',
worksheetLegend: 'Legend – colour the boxes with your crayons',
crayonNo: 'crayon no.',
needData: 'Load data for the whole frame first.',
preparing: 'Preparing the print…',
cm_title: 'Commentary on the map',
cm_hint:
'At least 2 A4 pages (3,600 characters). Describe the spatial, functional and social structure of your area and answer only the questions of the assignment – no history of the town.',
cm_placeholder: 'Write your commentary…',
cm_questions: 'Questions from the assignment',
cm_done: 'Done',
cm_count: (n: number, w: number) =>
`${n.toLocaleString('en')} characters incl. spaces · ${w} words`,
cm_need: (n: number) => `${n.toLocaleString('en')} more to reach 3,600`,
cm_ok: 'length requirement met',
q1: 'Is the area a separate unit (town, municipality) or only a part of one (district)?',
q2: 'How does the character of the buildings differ between parts of the area?',
q3: 'How does the functional use of land differ between parts of the area?',
q4: 'Are there natural centres in the area? What forms them?',
q5: 'Does the spatial structure cause problems – conflicts or traffic jams?',
q6: 'Could some parts be called: socially excluded localities, declining areas (brownfields), revitalised areas, prestigious residential areas, industrial zones, retail and service zones, leisure zones, near-natural localities?',
lang: 'Language',
area: 'Area',
locate: 'Use my location',
@ -126,7 +217,7 @@ const cs: Dict = {
layers: 'Vrstvy',
display: 'Zobrazení',
colorMode: 'Barevné schéma',
modeSimple: 'Jednoduché – sloučené kategorie',
modeHg3: 'Zadání HG3 – 16 kategorií funkčního využití ploch',
modeDetailed: 'Podrobné – každý druh využití zvlášť',
mixLabel: 'Pravidlo pro smíšené využití',
mix1: 'Nebytové využití s ≥ 1 bytem',
@ -137,7 +228,7 @@ const cs: Dict = {
export: 'Export',
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.',
note: 'V režimu HG3 je každá budova i každá parcela katastru vybarvena jednou z 16 kategorií semestrálního projektu. Budovy se zařazují podle způsobu využití zapsaného v RÚIAN (nebytová budova s byty se počítá jako smíšená), parcely podle druhu pozemku a způsobu využití; zastavěná parcela přebírá kategorii své budovy. Registr může být zastaralý – podle terénního průzkumu kategorii opravíte kliknutím na budovu nebo parcelu.<br><br>Data © ČÚZK (RÚIAN, ZABAGED). Tažením posouváte mapu, kolečkem nebo štípnutím přibližujete.',
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ů`,
@ -167,6 +258,96 @@ const cs: Dict = {
zoomOut: 'Oddálit (−)',
fit: 'Celá oblast (0)',
close: 'Zavřít',
'hg.byt': 'Bydlení – bytové domy',
'hg.rd': 'Bydlení – rodinné domy',
'hg.rek': 'Objekty individuální rekreace (chaty, zahradní domky)',
'hg.ver': 'Veřejné služby',
'hg.kom': 'Komerční služby',
'hg.pru': 'Průmysl',
'hg.dop': 'Dopravní sítě a vybavení',
'hg.smi': 'Smíšené plochy',
'hg.ost': 'Ostatní plochy (zastavěné)',
'hg.zel': 'Upravená zeleň (parky, hřbitovy)',
'hg.zah': 'Zahrady',
'hg.pole': 'Pole',
'hg.louka': 'Louky',
'hg.les': 'Lesy',
'hg.voda': 'Vodní plochy',
'hg.ostn': 'Ostatní plochy (nezastavěné)',
'hgs.ost': 'Ostatní plochy',
'hgs.ostn': 'Ostatní plochy',
'hgd.ver':
'samospráva, školství, zdravotnictví, soc. péče, kulturní památky a zařízení, sportoviště, technické sítě a vybavení',
'hgd.dop': 'silnice, železnice, letiště, parkoviště',
'hgd.smi': 'objekt s více funkcemi, např. bydlení ve vyšších patrech a komerční služby v přízemí',
g_built: 'Zastavěné plochy',
g_open: 'Nezastavěné plochy',
project: 'Semestrální projekt HG3',
pr_title: 'Název mapy',
pr_author: 'Autor',
pr_orient: 'Stránka A4',
landscape: 'Na šířku',
portrait: 'Na výšku',
pr_frame: 'Zobrazit rámec A4 (1 : 3 780)',
frameHint: 'Posunutím mapy umístíte rámec – tiskne se jen to, co je uvnitř.',
builtShare: 'Zastavěné území v rámci',
builtStrict: (p) => `z toho zastavěné plochy dle legendy: ${p}`,
builtDef:
'Zastavěné území = zastavěné plochy z legendy + zahrady + upravená zeleň. Samotné zastavěné plochy z legendy jsou uvedeny pod ukazatelem.',
builtOk: 'splňuje zadání (alespoň 66 %)',
builtLow: 'zadání požaduje alespoň 66 % – zvolte zastavěnější území',
noParcels: 'Parcely nejsou načtené (vzorová data) – podíly jen z budov.',
frameOut: 'Rámec přesahuje načtená data.',
loadFrame: 'Načíst data pro rámec',
pdf: 'PDF k odevzdání',
pdfHint:
'1. strana mapa · 2. legenda · 3.–4. komentář. V dialogu tisku zvolte „Uložit jako PDF“.',
worksheet: 'Pracovní mapa do terénu',
commentaryBtn: 'Komentář',
chars: (n) => `${n.toLocaleString('cs')} / 3 600 znaků`,
corrections: (n) => `Opravy z terénu: ${n}`,
saveProject: 'Uložit projekt',
loadProject: 'Otevřít projekt',
projectLoaded: 'Projekt načten',
projectBad: 'Soubor není projekt této aplikace.',
stats: 'Plochy v rámci',
statsCsv: 'Statistika (CSV)',
total: 'Celkem',
areaM2: 'Plocha (m²)',
share: 'Podíl',
legendHintHg: 'Kliknutím na budovu nebo parcelu v mapě opravíte její kategorii podle terénu.',
i_parcel: 'Parcela',
i_druh: 'Druh pozemku',
i_landuse: 'Způsob využití',
i_parea: 'Výměra',
i_fixcat: 'Kategorie (oprava z terénu)',
autoOpt: (s) => `Podle registru: ${s}`,
corrected: 'opraveno',
parcelNo: (n) => `Parcela č. ${n}`,
legendTitle: 'Legenda',
commentaryTitle: 'Komentář',
scaleText: 'Měřítko 1 : 3 780',
source: 'Podklad: RÚIAN, © ČÚZK',
worksheetTitle: 'Pracovní mapa',
worksheetLegend: 'Legenda – políčka vybarvěte pastelkami',
crayonNo: 'č. pastelky',
needData: 'Nejdřív načtěte data pro celý rámec.',
preparing: 'Připravuji tisk…',
cm_title: 'Komentář k mapě',
cm_hint:
'Alespoň 2 strany A4 (3 600 znaků). Popište prostorovou, funkční a sociální strukturu území a odpovídejte jen na otázky zadání – bez historie obce.',
cm_placeholder: 'Pište komentář…',
cm_questions: 'Otázky ze zadání',
cm_done: 'Hotovo',
cm_count: (n, w) => `${n.toLocaleString('cs')} znaků vč. mezer · ${w} slov`,
cm_need: (n) => `do 3 600 chybí ${n.toLocaleString('cs')}`,
cm_ok: 'délka splněna',
q1: 'Je území samostatným celkem (městem, obcí), nebo jen jeho částí (čtvrtí)?',
q2: 'Jaké jsou rozdíly v charakteru zástavby na jednotlivých částech území?',
q3: 'Jaké jsou rozdíly ve funkčním využití ploch v jednotlivých částech území?',
q4: 'Existují v území nějaká přirozená centra? Co je tvoří?',
q5: 'Existují z hlediska prostorové struktury území problémy, způsobující konflikty nebo dopravní zácpy?',
q6: 'Daly by se některé části území označit jako: sociálně vyloučené lokality, oblasti v úpadku (brownfields apod.), revitalizované oblasti, prestižní lokality pro bydlení, průmyslové zóny, zóny obchodu a služeb, zóny volnočasových aktivit, přírodě blízké lokality?',
lang: 'Jazyk',
area: 'Oblast',
locate: 'Použít moji polohu',

View file

@ -1,7 +1,7 @@
import { buildings } from './categories'
import { buildings, parcels } from './categories'
import { draw, fitTarget, requestDraw } from './render'
import { hidden, hover, S, sel, sheetOpen, vp } from './state'
import type { Building, Point, Ring, View } from './types'
import { commentaryOpen, hidden, hover, mode, S, sel, sheetOpen, vp } from './state'
import type { MapItem, Point, Ring, View } from './types'
const reducedMotion = () =>
typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches
@ -17,27 +17,29 @@ function inRing(x: number, y: number, ring: Ring): boolean {
}
return inside
}
function pick(px: number, py: number): Building | null {
/** Item under a screen point: a building first, else (in the HG3 mode) the parcel. */
function pick(px: number, py: number): MapItem | null {
const v = S.view,
x = (px - vp.W / 2) / v.s + v.cx,
y = (vp.H / 2 - py) / v.s + v.cy,
pad = 2 / v.s
const list = buildings.value,
hid = hidden.value
for (let i = list.length - 1; i >= 0; i--) {
const b = list[i]
const hid = hidden.value
const hit = (it: MapItem) => {
if (
hid.has(b.cat) ||
x < b.bb[0] - pad ||
x > b.bb[2] + pad ||
y < b.bb[1] - pad ||
y > b.bb[3] + pad
hid.has(it.cat) ||
x < it.bb[0] - pad ||
x > it.bb[2] + pad ||
y < it.bb[1] - pad ||
y > it.bb[3] + pad
)
continue
let hit = false
for (const r of b.rings) if (inRing(x, y, r)) hit = !hit
if (hit) return b
return false
let inside = false
for (const r of it.rings) if (inRing(x, y, r)) inside = !inside
return inside
}
const bl = buildings.value
for (let i = bl.length - 1; i >= 0; i--) if (hit(bl[i])) return bl[i]
if (mode.value === 'hg3') for (const p of parcels.value) if (hit(p)) return p
return null
}
@ -132,7 +134,7 @@ export function attachPointer(cv: HTMLCanvasElement): () => void {
// recent pointer positions for pan inertia
let trail: { x: number; y: number; t: number }[] = []
const setHover = (b: Building | null, x: number, y: number) => {
const setHover = (b: MapItem | null, x: number, y: number) => {
hover.value = b ? { b, x, y } : null
cv.classList.toggle('over', !!b)
}
@ -244,6 +246,7 @@ const isTyping = (el: EventTarget | null) =>
function onKey(e: KeyboardEvent) {
if (e.defaultPrevented || e.metaKey || e.ctrlKey || e.altKey) return
if (commentaryOpen.value) return // the commentary dialog handles its own keys
if (e.key === 'Escape') {
if (sel.value) sel.value = null
else if (sheetOpen.value) sheetOpen.value = false

50
src/page.ts Normal file
View file

@ -0,0 +1,50 @@
import { orientation, S } from './state'
import type { BBox, Orientation } from './types'
/* ================= A4 page geometry for the HG3 submission =================
* The assignment prints the ČÚZK base map on A4 at 300 dpi, which gives 1 : 3 780.
*/
export const SCALE = 3780
export const DPI = 300
const PAGE_MM: Record<Orientation, [number, number]> = {
landscape: [297, 210],
portrait: [210, 297],
}
export const MARGIN_MM = 8
export const HEADER_MM = 9
export const FOOTER_MM = 7
export const pageMM = (o: Orientation = orientation.value) => PAGE_MM[o]
/** Size of the map image on the page, in mm. */
export function mapBoxMM(o: Orientation = orientation.value): [number, number] {
const [w, h] = PAGE_MM[o]
return [w - 2 * MARGIN_MM, h - 2 * MARGIN_MM - HEADER_MM - FOOTER_MM]
}
/** Ground size of the printed map in metres. */
export function frameMeters(o?: Orientation): [number, number] {
const [w, h] = mapBoxMM(o)
return [(w * SCALE) / 1000, (h * SCALE) / 1000]
}
/** The print frame in Web Mercator, centred on the current view. */
export function frameRect(o?: Orientation): BBox {
const [w, h] = frameMeters(o)
const hx = w / 2 / S.K,
hy = h / 2 / S.K
return [S.view.cx - hx, S.view.cy - hy, S.view.cx + hx, S.view.cy + hy]
}
/** Load radius (see fetchArea: the query box is ±1.1 × radius) that covers the frame. */
export function frameRadius(o?: Orientation): number {
const [w, h] = frameMeters(o)
return Math.ceil(Math.max(w, h) / 2 / 1.1 / 50) * 50
}
/** Whether the loaded data covers the whole frame. */
export function frameCovered(o?: Orientation): boolean {
const bb = S.loadedBB,
f = frameRect(o)
return !!bb && f[0] >= bb[0] && f[1] >= bb[1] && f[2] <= bb[2] && f[3] <= bb[3]
}

36
src/print.ts Normal file
View file

@ -0,0 +1,36 @@
import { t } from './i18n'
import { DPI, mapBoxMM, SCALE } from './page'
import { drawScene } from './render'
import { S } from './state'
import { LIGHT } from './theme'
const CSS_DPI = 96
/**
* Render the A4 map at 1 : 3 780 and 300 dpi around the current view centre.
* Returns an object URL of a JPEG (the format the assignment uses for the ČÚZK print).
*/
export function renderPrintMap(blank: boolean): Promise<string> {
const [wmm, hmm] = mapBoxMM()
const r = DPI / CSS_DPI
const W = (wmm / 25.4) * CSS_DPI,
H = (hmm / 25.4) * CSS_DPI // in CSS px; r scales to 300 dpi
const canvas = document.createElement('canvas')
canvas.width = Math.round(W * r)
canvas.height = Math.round(H * r)
const ctx = canvas.getContext('2d')!
// CSS px per true metre at 1 : SCALE, then per Mercator metre
const s = ((CSS_DPI / 25.4) * 1000 * S.K) / SCALE
drawScene(ctx, W, H, { cx: S.view.cx, cy: S.view.cy, s }, r, {
pal: LIGHT,
blank,
print: { scale: '1 : 3 780', credit: t('source') },
})
return new Promise((resolve, reject) =>
canvas.toBlob(
(b) => (b ? resolve(URL.createObjectURL(b)) : reject(new Error('canvas export failed'))),
'image/jpeg',
0.92,
),
)
}

View file

@ -1,21 +1,36 @@
import { computed } from '@preact/signals'
import { BASE } from './basemap'
import { buildings, catColor, catLabel, catList, catOrder, isDark, SIMPLE_NUMS } from './categories'
import {
buildings,
catColor,
catLabel,
catList,
catOrder,
isDark,
parcels,
showsNumber,
} from './categories'
import { t } from './i18n'
import { frameMeters } from './page'
import {
base,
focusCat,
hidden,
hover,
mode,
orientation,
rawBuildings,
rawParcels,
S,
sel,
showBase,
showFrame,
showNums,
viewVersion,
vp,
} from './state'
import { LIGHT, palette, type MapPalette } from './theme'
import type { Building, Ring, View } from './types'
import type { MapItem, Ring, View } from './types'
/* ================= view ================= */
/** View that fits all loaded buildings into the canvas, or null if there is nothing to fit. */
@ -56,14 +71,18 @@ function niceScale(v: View) {
return { m: 1000, px: 1000 * pxPerMeter(v) }
}
const hoverBuilding = computed(() => hover.value?.b ?? null)
const hoverItem = computed(() => hover.value?.b ?? null)
interface SceneOpts {
export interface SceneOpts {
pal?: MapPalette
/** draw on-screen-only overlays: selection, hover outline, legend focus dimming */
/** draw on-screen-only overlays: selection, hover outline, legend focus, A4 frame */
live?: boolean
/** px at the bottom covered by UI (mobile sheet); the scale bar sits above it */
insetB?: number
/** uncoloured field worksheet: white areas, grey buildings, all house numbers */
blank?: boolean
/** printed map: scale text next to the scale bar and a data credit */
print?: { scale: string; credit: string }
}
export function drawScene(
@ -72,21 +91,30 @@ export function drawScene(
H: number,
v: View,
r: number,
{ pal = LIGHT, live = false, insetB = 0 }: SceneOpts = {},
{ pal = LIGHT, live = false, insetB = 0, blank = false, print }: SceneOpts = {},
) {
const hg = mode.value === 'hg3'
const list = buildings.value,
hid = hidden.value,
plist = hg ? parcels.value : [],
hid = blank ? new Set<string>() : 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 = pal.bg
ctx.fillStyle = blank ? '#fff' : 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
const ppm = pxPerMeter(v)
// only items whose bounding box touches the canvas are drawn
const vx0 = v.cx - W / 2 / v.s,
vx1 = v.cx + W / 2 / v.s,
vy0 = v.cy - H / 2 / v.s,
vy1 = v.cy + H / 2 / v.s
const visible = (it: MapItem) =>
it.bb[2] >= vx0 && it.bb[0] <= vx1 && it.bb[3] >= vy0 && it.bb[1] <= vy1
const path = (rings: Ring[], close: boolean) => {
ctx.beginPath()
for (const ring of rings) {
@ -98,8 +126,8 @@ export function drawScene(
if (close) ctx.closePath()
}
}
const outline = (b: Building, outer: string, w: number, inner?: string) => {
path(b.rings, true)
const outline = (it: MapItem, outer: string, w: number, inner?: string) => {
path(it.rings, true)
ctx.strokeStyle = outer
ctx.lineWidth = w
ctx.stroke()
@ -109,9 +137,35 @@ export function drawScene(
ctx.stroke()
}
}
/** Fill all items of each category in one path (fast), fading non-focused categories. */
const fillByCat = (items: MapItem[], order: string[], color: (k: string) => string) => {
for (const key of order) {
if (hid.has(key)) continue
const rings: Ring[] = []
for (const it of items)
if (it.cat === key && visible(it)) for (const rg of it.rings) rings.push(rg)
if (!rings.length) continue
ctx.globalAlpha = focus && focus !== key ? 0.18 : 1
path(rings, true)
ctx.fillStyle = color(key)
ctx.fill('evenodd')
}
ctx.globalAlpha = 1
}
ctx.lineJoin = 'round'
ctx.lineCap = 'round'
if (showBase.value) {
if (hg) {
// every parcel is coloured, then the parcel boundaries
fillByCat(plist, catList(), blank ? () => '#fff' : catColor)
const edges: Ring[] = []
for (const p of plist)
if (!hid.has(p.cat) && visible(p)) for (const rg of p.rings) edges.push(rg)
path(edges, true)
ctx.strokeStyle = blank ? '#8a8a8a' : pal.parcelEdge
ctx.lineWidth = blank ? 0.6 : 0.5
ctx.stroke()
} else if (showBase.value) {
const bmap = base.value
for (const st of BASE) {
const rings = bmap[st.k]
@ -135,33 +189,42 @@ export function drawScene(
}
}
}
// buildings
for (const key of catOrder()) {
if (hid.has(key)) continue
const rings: Ring[] = []
for (const b of list) if (b.cat === key) for (const rg of b.rings) rings.push(rg)
for (const b of list) if (b.cat === key && visible(b)) 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.fillStyle = blank ? '#d9d9d9' : catColor(key)
ctx.fill('evenodd')
if (hg) {
ctx.strokeStyle = blank ? '#333' : 'rgba(0,0,0,.62)'
ctx.lineWidth = 0.8
} else {
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
// house numbers
// the field worksheet always gets house numbers (small, for finding your way)
if ((showNums.value && ppm >= 1.5) || (blank && ppm >= 0.6)) {
const all = blank || 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`
ctx.font = `${Math.min(12, Math.max(blank ? 6.5 : 8, ppm * 2.2))}px system-ui,sans-serif`
for (const b of list) {
if (!b.cp || hid.has(b.cat) || (focus && focus !== b.cat) || !(all || SIMPLE_NUMS[b.sc]))
if (!b.cp || hid.has(b.cat) || (focus && focus !== b.cat) || !(all || showsNumber(b)))
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
const dark = isDark(catColor(b.cat)),
const dark = !blank && isDark(catColor(b.cat)),
txt = b.cp.split(',')[0]
if (!dark) {
ctx.lineWidth = 2.5
@ -172,19 +235,23 @@ export function drawScene(
ctx.fillText(txt, cx, cy)
}
}
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)
const hi = hoverItem.value,
si = sel.value
if (hi && hi !== si && !hid.has(hi.cat)) outline(hi, pal.hover, 1.5)
if (si) outline(si, pal.selOuter, 3, pal.selInner)
if (hg && showFrame.value) drawFrame(ctx, W, H, ppm, pal)
}
// scale bar
const sc = niceScale(v),
bx = 16,
by = H - 18 - insetB
ctx.fillStyle = pal.furnitureBg
const scaleW = sc.px + 16 + (print ? 86 : 0)
ctx.fillStyle = print ? 'rgba(255,255,255,.9)' : pal.furnitureBg
ctx.beginPath()
ctx.roundRect(bx - 8, by - 22, sc.px + 16, 32, 6)
ctx.roundRect(bx - 8, by - 22, scaleW, 32, 6)
ctx.fill()
ctx.strokeStyle = pal.furnitureInk
ctx.fillStyle = pal.furnitureInk
@ -199,7 +266,28 @@ export function drawScene(
ctx.textAlign = 'center'
ctx.textBaseline = 'bottom'
ctx.fillText(sc.m >= 1000 ? sc.m / 1000 + ' km' : sc.m + ' m', bx + sc.px / 2, by - 5)
if (print) {
ctx.textAlign = 'left'
ctx.font = '600 11px system-ui,sans-serif'
ctx.fillText(print.scale, bx + sc.px + 12, by + 2)
// credit bottom right
ctx.font = '9px system-ui,sans-serif'
ctx.textAlign = 'right'
const cw = ctx.measureText(print.credit).width
ctx.fillStyle = 'rgba(255,255,255,.85)'
ctx.fillRect(W - cw - 14, H - 18, cw + 10, 14)
ctx.fillStyle = '#222'
ctx.fillText(print.credit, W - 9, H - 6)
ctx.fillStyle = pal.furnitureInk
}
// north arrow
if (print) {
ctx.fillStyle = 'rgba(255,255,255,.85)'
ctx.beginPath()
ctx.roundRect(12, 10, 24, 52, 5)
ctx.fill()
ctx.fillStyle = pal.furnitureInk
}
ctx.beginPath()
ctx.moveTo(24, 44)
ctx.lineTo(24, 16)
@ -209,11 +297,51 @@ export function drawScene(
ctx.lineTo(28, 24)
ctx.lineWidth = 1.5
ctx.stroke()
ctx.textAlign = 'center'
ctx.textBaseline = 'top'
ctx.font = '11px system-ui,sans-serif'
ctx.fillText('N', 24, 46)
ctx.restore()
}
/** The A4 print frame around the centre of the map, with the outside shaded. */
function drawFrame(
ctx: CanvasRenderingContext2D,
W: number,
H: number,
ppm: number,
pal: MapPalette,
) {
const [fw, fh] = frameMeters(),
pw = fw * ppm,
ph = fh * ppm
const x0 = W / 2 - pw / 2,
y0 = H / 2 - ph / 2
ctx.fillStyle = pal.frameShade
ctx.beginPath()
ctx.rect(0, 0, W, H)
ctx.rect(x0, y0, pw, ph)
ctx.fill('evenodd')
ctx.strokeStyle = pal.frameEdge
ctx.lineWidth = 2
ctx.setLineDash([8, 5])
ctx.strokeRect(x0, y0, pw, ph)
ctx.setLineDash([])
const label = 'A4 · 1 : 3 780'
ctx.font = '600 11px system-ui,sans-serif'
const lw = ctx.measureText(label).width + 12
const lx = Math.max(4, x0),
ly = Math.max(4, y0 - 22)
ctx.fillStyle = pal.frameEdge
ctx.beginPath()
ctx.roundRect(lx, ly, lw, 18, 4)
ctx.fill()
ctx.fillStyle = '#fff'
ctx.textAlign = 'left'
ctx.textBaseline = 'middle'
ctx.fillText(label, lx + 6, ly + 9.5)
}
/* ================= export legend ================= */
interface LegendEntry {
color: string
@ -221,17 +349,21 @@ interface LegendEntry {
border?: string
}
/** Number of buildings (and, in the HG3 mode, parcels) per category. */
export function counts(): Record<string, number> {
const c: Record<string, number> = {}
for (const b of buildings.value) c[b.cat] = (c[b.cat] || 0) + 1
if (mode.value === 'hg3') for (const p of parcels.value) c[p.cat] = (c[p.cat] || 0) + 1
return c
}
function legendEntries(): LegendEntry[] {
const cnt = counts(),
hg = mode.value === 'hg3',
e: LegendEntry[] = []
for (const k of catList())
if (cnt[k]) e.push({ color: catColor(k), label: `${catLabel(k)} (${cnt[k]})` })
if (showBase.value)
if (cnt[k])
e.push({ color: catColor(k), label: hg ? catLabel(k) : `${catLabel(k)} (${cnt[k]})` })
if (!hg && showBase.value)
e.push(
{ color: LIGHT.base.water, label: t('b_water') },
{ color: LIGHT.base.green, label: t('b_green') },
@ -272,24 +404,34 @@ export function drawLegend(ctx: CanvasRenderingContext2D, y0: number, W: number,
ctx.restore()
}
/* ================= on-screen redraw ================= */
let settle: ReturnType<typeof setTimeout> | undefined
/** Redraw the on-screen map now. */
export function draw() {
if (vp.W && vp.ctx)
if (!vp.W || !vp.ctx) return
drawScene(vp.ctx, vp.W, vp.H, S.view, vp.DPR, { pal: palette(), live: true, insetB: vp.insetB })
// let frame statistics etc. update once the view has stopped moving
clearTimeout(settle)
settle = setTimeout(() => viewVersion.value++, 220)
}
/**
* 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.
* Every signal the on-screen map depends on. MapView reads these inside an effect so the map
* redraws when any of them changes; the redraw itself happens in requestDraw's frame.
*/
export const trackScene = () => [
mode.value,
buildings.value,
parcels.value,
rawParcels.value,
base.value,
hidden.value,
showBase.value,
showNums.value,
showFrame.value,
orientation.value,
sel.value,
hoverBuilding.value,
hoverItem.value,
focusCat.value,
palette(),
]

View file

@ -823,9 +823,11 @@ function decodeRing(s: string, ox: number, oy: number): Ring {
export function loadSample(): AreaData {
const lines = SAMPLE_B.trim().split('\n')
const [ox, oy] = lines[0].split(',').map(Number)
const buildings = lines.slice(1).map((l) => {
const buildings = lines.slice(1).map((l, i) => {
const [cp, use, flats, floors, geom] = l.split(';')
return mkBuilding(
'sample-' + i,
null,
cp,
+use,
flats === '' ? null : +flats,
@ -847,5 +849,5 @@ export function loadSample(): AreaData {
}
if (cur !== null) base[cur].push(decodeRing(t2, ox, oy))
}
return { buildings, base, fails: [] }
return { buildings, parcels: [], base, fails: [] }
}

View file

@ -1,6 +1,16 @@
import { signal } from '@preact/signals'
import { persisted } from './persist'
import type { BaseData, Building, LatLon, Mode, View } from './types'
import type {
BBox,
BaseData,
Building,
LatLon,
MapItem,
Mode,
Orientation,
Parcel,
View,
} from './types'
/* ================= reactive state =================
* Everything the UI or the map drawing depends on is a signal: components re-render and the
@ -10,10 +20,12 @@ import type { BaseData, Building, LatLon, Mode, View } from './types'
/** Buildings as loaded, before classification. */
export const rawBuildings = signal<Building[]>([])
export const base = signal<BaseData>({})
/** Cadastral parcels as loaded, before classification. */
export const rawParcels = signal<Parcel[]>([])
// 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')
export const mode = persisted<Mode>('mode', 'hg3', (v) => v === 'hg3' || 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')
@ -26,12 +38,40 @@ export const lastLoc = persisted<LatLon | null>(
(v) => !!v && typeof (v as LatLon).lat === 'number' && typeof (v as LatLon).lon === 'number',
)
/**
* Field corrections: 'b:<building code>' or 'p:<parcel id>' → HG3 category.
* The registry data can be outdated; what you find in the field wins.
*/
export const overrides = persisted<Record<string, string>>(
'overrides',
{},
(v) => !!v && typeof v === 'object' && !Array.isArray(v),
)
/* HG3 project: A4 frame at 1:3 780, texts for the submission PDF */
export const orientation = persisted<Orientation>(
'orientation',
'landscape',
(v) => v === 'landscape' || v === 'portrait',
)
export const showFrame = persisted('showFrame', true, (v) => typeof v === 'boolean')
export const mapTitle = persisted('mapTitle', '', (v) => typeof v === 'string')
export const mapAuthor = persisted('mapAuthor', '', (v) => typeof v === 'string')
export const commentary = persisted('commentary', '', (v) => typeof v === 'string')
/** Questions of the assignment the commentary already answers (ticked by the user). */
export const answered = persisted<number[]>('answered', [], (v) => Array.isArray(v))
export const commentaryOpen = signal(false)
/** What is being printed: the submission PDF or the blank field worksheet. */
export const printJob = signal<{ kind: 'submission' | 'worksheet'; mapUrl: string } | null>(null)
/** Bumped (debounced) after the view stops changing, for frame statistics. */
export const viewVersion = signal(0)
export const hidden = signal<ReadonlySet<string>>(new Set())
/** 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)
export const sel = signal<MapItem | 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 hover = signal<{ b: MapItem; x: number; y: number } | null>(null)
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. */
@ -58,6 +98,8 @@ export const S = {
center: [14.9687, 50.8172] as [number, number],
view: { cx: 0, cy: 0, s: 1 } as View,
loaded: false,
/** Mercator bounding box of the loaded data */
loadedBB: null as BBox | null,
}
/**

70
src/stats.ts Normal file
View file

@ -0,0 +1,70 @@
import { computed } from '@preact/signals'
import { buildings, HG, isBuilt, parcels } from './categories'
import { clipRing, ringArea } from './geo'
import { frameRect } from './page'
import { mode, orientation, S, viewVersion } from './state'
import type { MapItem } from './types'
export interface FrameStats {
/** true m² per HG3 category inside the A4 frame */
area: Record<string, number>
/** sum of all category areas */
total: number
/** built-up categories of the legend ("Zastavěné plochy") */
built: number
share: number
/**
* "Zastavěné území" in the planning sense: built-up categories plus gardens and maintained
* greenery inside the settlement. This is what the assignment's 66 % rule is checked against.
*/
settlement: number
settlementShare: number
/** parcels give full coverage; without them (sample data) only building footprints count */
source: 'parcels' | 'buildings'
}
/** Area of an item inside the rectangle, in Mercator m² (holes subtract via ring orientation). */
function clippedArea(it: MapItem, x0: number, y0: number, x1: number, y1: number): number {
if (it.bb[2] < x0 || it.bb[0] > x1 || it.bb[3] < y0 || it.bb[1] > y1) return 0
const inside = it.bb[0] >= x0 && it.bb[2] <= x1 && it.bb[1] >= y0 && it.bb[3] <= y1
let a = 0
for (const r of it.rings) {
const c = inside ? r : clipRing(r, x0, y0, x1, y1)
if (c.length >= 3) a += ringArea(c)
}
return Math.abs(a)
}
/** Land-use statistics for the A4 frame (HG3 mode); recomputed after the view settles. */
export const frameStats = computed<FrameStats | null>(() => {
// recompute when the view settles or the page orientation changes
if (viewVersion.value < 0 || !orientation.value || mode.value !== 'hg3') return null
const [x0, y0, x1, y1] = frameRect(),
k2 = S.K * S.K
const area: Record<string, number> = Object.fromEntries(HG.map((c) => [c.key, 0]))
const pl = parcels.value
const items: MapItem[] = pl.length ? pl : buildings.value
for (const it of items) {
const a = clippedArea(it, x0, y0, x1, y1)
if (a) area[it.hg] = (area[it.hg] ?? 0) + a * k2
}
let total = 0,
built = 0
for (const [k, a] of Object.entries(area)) {
total += a
if (isBuilt(k)) built += a
}
const settlement = built + (area.zah ?? 0) + (area.zel ?? 0)
return {
area,
total,
built,
share: total ? built / total : 0,
settlement,
settlementShare: total ? settlement / total : 0,
source: pl.length ? 'parcels' : 'buildings',
}
})
export const fmtPct = (x: number, lang: string) =>
(x * 100).toLocaleString(lang, { maximumFractionDigits: x < 0.1 ? 1 : 0 }) + ' %'

View file

@ -972,6 +972,317 @@ canvas.drag {
}
}
/* ================= HG3 project ================= */
.project {
display: grid;
gap: var(--sp-3);
}
.project > h2 {
margin: 0;
}
.grid2 {
display: grid;
grid-template-columns: 1fr 1fr;
gap: var(--sp-2);
}
input.text {
width: 100%;
min-width: 0;
padding: 7px 9px;
border: 1px solid var(--border-strong);
border-radius: var(--r-md);
background: var(--surface);
transition:
border-color var(--dur) var(--ease),
box-shadow var(--dur) var(--ease);
}
input.text:focus {
outline: none;
border-color: var(--acc);
box-shadow: 0 0 0 3px var(--acc-soft);
}
.row-between {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--sp-2);
}
.row-between .field-label {
margin: 0;
}
.project .hint {
margin: -6px 0 0;
}
.project .status {
margin: 0;
}
.project-file {
font-size: var(--fs-sm);
border-top: 1px solid var(--border);
padding-top: var(--sp-2);
}
.btn.block {
width: 100%;
}
button.link.inline {
padding: 0;
font-weight: 600;
text-decoration: underline;
}
.count {
margin-left: auto;
font-size: var(--fs-xs);
font-variant-numeric: tabular-nums;
color: var(--muted);
}
.count.ok {
color: var(--ok);
}
.exp .btn {
min-width: 0;
}
.meter {
display: grid;
gap: 5px;
}
.meter-head {
display: flex;
justify-content: space-between;
gap: var(--sp-2);
font-size: var(--fs-sm);
}
.meter.ok b {
color: var(--ok);
}
.meter.low b {
color: var(--warn);
}
.meter-bar {
position: relative;
height: 8px;
border-radius: var(--r-full);
background: var(--surface-2);
overflow: visible;
}
.meter-bar span {
display: block;
height: 100%;
border-radius: inherit;
background: var(--warn);
transition: width var(--dur-slow) var(--ease);
}
.meter.ok .meter-bar span {
background: var(--ok);
}
.meter-bar i {
position: absolute;
top: -3px;
bottom: -3px;
width: 2px;
margin-left: -1px;
background: var(--ink-2);
border-radius: 1px;
}
.meter .hint {
margin: 0;
}
.leg-group {
margin: var(--sp-2) 6px 2px;
font-size: var(--fs-xs);
font-weight: 600;
color: var(--muted);
}
.leg-group:first-child {
margin-top: 0;
}
.tag {
display: inline-block;
margin-left: 6px;
padding: 0 6px;
border-radius: var(--r-full);
font-size: var(--fs-xs);
color: var(--acc);
background: var(--acc-soft);
}
.fix {
margin-top: var(--sp-3);
}
.fix .field-label {
display: flex;
align-items: center;
gap: 5px;
}
.fix select {
font-size: var(--fs-sm);
}
.stats {
margin-top: var(--sp-5);
}
.stats summary {
display: flex;
align-items: center;
cursor: pointer;
list-style: none;
}
.stats summary::-webkit-details-marker {
display: none;
}
.stats summary h2 {
margin: 0;
}
.stats .chev {
margin-left: auto;
color: var(--muted);
transition: transform var(--dur) var(--ease);
}
.stats[open] .chev {
transform: rotate(180deg);
}
.stats table {
width: 100%;
margin: var(--sp-2) 0 var(--sp-3);
border-collapse: collapse;
font-size: var(--fs-sm);
}
.stats th {
font-weight: 500;
color: var(--muted);
font-size: var(--fs-xs);
text-align: left;
padding: 2px 4px;
}
.stats td {
padding: 3px 4px;
border-top: 1px solid var(--border);
}
.stats td:first-child {
width: 22px;
}
.stats .num {
text-align: right;
font-variant-numeric: tabular-nums;
white-space: nowrap;
}
.stats tr.grp td {
font-weight: 600;
background: var(--surface-2);
}
/* ================= commentary dialog ================= */
.dialog-backdrop {
position: fixed;
inset: 0;
z-index: 30;
display: grid;
place-items: center;
padding: var(--sp-4);
background: rgba(10, 12, 16, 0.45);
backdrop-filter: blur(2px);
animation: fade-in var(--dur) var(--ease);
}
.dialog {
width: min(1040px, 100%);
max-height: calc(100dvh - 2 * var(--sp-4));
display: flex;
flex-direction: column;
gap: var(--sp-2);
padding: var(--sp-4);
box-shadow: var(--shadow-lg);
animation: pop-in var(--dur-slow) var(--ease);
}
.dialog-head {
display: flex;
align-items: center;
justify-content: space-between;
}
.dialog-head h3 {
margin: 0;
font-size: var(--fs-lg);
}
.dialog .hint {
margin: 0;
}
.dialog-body {
flex: 1;
min-height: 0;
display: grid;
grid-template-columns: 1fr 300px;
gap: var(--sp-3);
}
.dialog textarea {
min-height: 52vh;
resize: none;
padding: var(--sp-3);
border: 1px solid var(--border-strong);
border-radius: var(--r-md);
background: var(--surface);
color: var(--ink);
font: 15px / 1.6 var(--font);
}
.dialog textarea:focus {
outline: none;
border-color: var(--acc);
box-shadow: 0 0 0 3px var(--acc-soft);
}
.questions {
overflow: auto;
font-size: var(--fs-sm);
}
.questions h4 {
margin: 0 0 var(--sp-2);
font-size: var(--fs-sm);
color: var(--ink-2);
}
.questions ol {
margin: 0;
padding: 0;
list-style: none;
display: grid;
gap: var(--sp-2);
}
.questions label {
display: flex;
gap: var(--sp-2);
align-items: flex-start;
cursor: pointer;
line-height: 1.4;
}
.questions input {
margin-top: 3px;
accent-color: var(--ok);
}
.questions input:checked + span {
color: var(--muted);
text-decoration: line-through;
}
.dialog-foot {
display: flex;
align-items: center;
gap: var(--sp-4);
}
.dialog-foot .meter {
flex: 1;
}
@media (max-width: 820px) {
.dialog-body {
grid-template-columns: 1fr;
}
.dialog textarea {
min-height: 40vh;
}
.questions {
max-height: 22vh;
}
}
/* ================= print pages (submission PDF / worksheet) ================= */
.print-root {
display: none;
}
/* ================= preferences & print ================= */
@media (prefers-reduced-motion: reduce) {
*,
@ -982,17 +1293,33 @@ canvas.drag {
transition-duration: 1ms !important;
}
}
@page {
size: A4 portrait;
margin: 0;
}
@page map-landscape {
size: A4 landscape;
margin: 0;
}
@media print {
:root {
color-scheme: light;
--map-bg: #f5f2ea;
}
html,
body {
background: #fff !important;
color: #111;
height: auto;
}
/* screen map print (Ctrl+P without a prepared job) */
.panel,
.zoom,
#tip,
.info,
.loading,
.toast {
.toast,
.dialog-backdrop {
display: none !important;
}
#app {
@ -1002,4 +1329,109 @@ canvas.drag {
position: relative;
height: 100vh;
}
/* prepared job: only the print pages */
html.printing #app {
display: none !important;
}
html.printing .print-root {
display: block;
}
.print-root {
font: 10.5pt / 1.45 var(--font);
color: #111;
-webkit-print-color-adjust: exact;
print-color-adjust: exact;
}
.pg {
position: relative;
width: 210mm;
height: 297mm;
padding: 8mm;
overflow: hidden;
break-after: page;
}
.pg:last-child {
break-after: auto;
}
.pg-map.landscape {
page: map-landscape;
width: 297mm;
height: 210mm;
}
.pg-head,
.pg-foot {
display: flex;
justify-content: space-between;
align-items: center;
gap: 6mm;
}
.pg-head {
height: 9mm;
font-size: 12pt;
}
.pg-foot {
height: 7mm;
font-size: 8pt;
color: #444;
}
.pg-map img {
display: block;
border: 0.3mm solid #333;
}
.pg h1 {
font-size: 16pt;
margin: 4mm 0 6mm;
}
.pg h2 {
font-size: 11pt;
text-transform: none;
letter-spacing: 0;
color: #111;
margin: 6mm 0 3mm;
}
.pg-leg {
display: flex;
align-items: center;
gap: 4mm;
margin: 0 0 2.2mm;
}
.pg-sw {
flex: none;
width: 16mm;
height: 6.5mm;
border: 0.3mm solid #222;
}
.pg-sw.empty {
background: #fff;
}
.pg-leg small {
color: #555;
}
.pg-crayon {
margin-left: auto;
color: #555;
white-space: nowrap;
}
.pg-note {
position: absolute;
left: 8mm;
right: 8mm;
bottom: 8mm;
font-size: 8pt;
color: #555;
}
.pg-text {
height: auto;
min-height: 297mm;
overflow: visible;
padding: 18mm 20mm;
}
.pg-body {
white-space: pre-wrap;
text-align: justify;
hyphens: auto;
orphans: 3;
widows: 3;
}
}

View file

@ -35,6 +35,11 @@ export interface MapPalette {
/** building outline on dark fills (family houses) and on all other fills */
outlineOnDark: string
outlineOnLight: string
/** cadastral parcel boundaries (HG3 mode) */
parcelEdge: string
/** shade outside the A4 print frame */
frameShade: string
frameEdge: string
hover: string
selOuter: string
selInner: string
@ -65,6 +70,9 @@ export const LIGHT: MapPalette = {
},
outlineOnDark: 'rgba(255,255,255,.55)',
outlineOnLight: 'rgba(0,0,0,.55)',
parcelEdge: 'rgba(40,40,40,.32)',
frameShade: 'rgba(25,25,35,.30)',
frameEdge: '#1f5fbf',
hover: 'rgba(20,20,20,.9)',
selOuter: '#ffcc00',
selInner: '#000',
@ -94,6 +102,9 @@ export const DARK: MapPalette = {
},
outlineOnDark: 'rgba(255,255,255,.7)',
outlineOnLight: 'rgba(0,0,0,.6)',
parcelEdge: 'rgba(0,0,0,.5)',
frameShade: 'rgba(0,0,0,.45)',
frameEdge: '#5b9bff',
hover: 'rgba(255,255,255,.95)',
selOuter: '#ffcc00',
selInner: '#000',

View file

@ -4,9 +4,14 @@ export type Ring = Point[]
/** [minX, minY, maxX, maxY] */
export type BBox = [number, number, number, number]
export type Mode = 'simple' | 'detailed'
/** 'hg3': the 16 categories of the HG3 semester project; 'detailed': one colour per RÚIAN use code */
export type Mode = 'hg3' | 'detailed'
export type Orientation = 'landscape' | 'portrait'
export interface Building {
kind: 'b'
id: string // RÚIAN building code (kód stavebního objektu)
parcel: string | null // id of the parcel the building stands on
cp: string // house number (číslo popisné), may be empty
use: number // RÚIAN use code (způsob využití)
flats: number | null
@ -15,15 +20,37 @@ export interface Building {
year: number | null // year of completion
rings: Ring[]
bb: BBox
cat: string // category key in the current colour mode
sc: string // category key in the simple scheme
/** HG3 category derived from the registry (before field corrections) */
auto: string
/** HG3 category after field corrections */
hg: string
/** category key shown in the current colour mode */
cat: string
}
/** Cadastral land parcel (RÚIAN Parcela). Parcels cover the whole area without gaps. */
export interface Parcel {
kind: 'p'
id: string
num: string // parcel number, e.g. "216/2"
druh: number | null // druh pozemku (land type)
use: number | null // způsob využití pozemku (land use)
area: number | null // registered area in m²
rings: Ring[]
bb: BBox
auto: string
hg: string
cat: string
}
export type MapItem = Building | Parcel
/** Basemap geometries keyed by layer name (road, water, …). */
export type BaseData = Record<string, Ring[]>
export interface AreaData {
buildings: Building[]
parcels: Parcel[]
base: BaseData
fails: string[]
}