refactor: split into TypeScript modules built with Vite

- Move the single-file app into src/ as typed ES modules
- Vite for dev server and minified production build (bun run dev / build)
- oxfmt/oxlint config; rename useName -> ruianUseName (hooks lint false positive)
- Fix horizontal overflow in the sidebar (range input default margin)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
HangerThem 2026-11-07 11:32:26 +01:00
parent 3d75509a6e
commit 4f9c11039b
25 changed files with 2214 additions and 756 deletions

2
.gitignore vendored Normal file
View file

@ -0,0 +1,2 @@
node_modules/
dist/

12
.oxfmtrc.json Normal file
View file

@ -0,0 +1,12 @@
{
"$schema": "./node_modules/oxfmt/configuration_schema.json",
"semi": false,
"singleQuote": true,
"printWidth": 100,
"sortTailwindcss": {
"stylesheet": "./src/index.css"
},
"ignorePatterns": [
"bun.lock"
]
}

32
.oxlintrc.json Normal file
View file

@ -0,0 +1,32 @@
{
"$schema": "./node_modules/oxlint/configuration_schema.json",
"plugins": [
"typescript",
"oxc",
"unicorn",
"import",
"vitest"
],
"categories": {
"correctness": "error",
"suspicious": "warn",
"perf": "warn"
},
"env": {
"browser": true,
"es2024": true
},
"ignorePatterns": [
"dist"
],
"rules": {
"import/no-unassigned-import": [
"warn",
{
"allow": [
"**/*.css"
]
}
]
}
}

222
bun.lock Normal file
View file

@ -0,0 +1,222 @@
{
"lockfileVersion": 1,
"configVersion": 0,
"workspaces": {
"": {
"name": "building-use-map",
"dependencies": {
"oxfmt": "^0.77.0",
"oxlint": "^1.92.0",
},
"devDependencies": {
"typescript": "^7.0.2",
"vite": "^8.3.6",
},
},
},
"packages": {
"@oxc-project/types": ["@oxc-project/types@0.156.0", "", {}, "sha512-1Duyg48TdJNdyhEB8Xn1L36bT9Pv6GUtlKjHxOys8xkaF/rQq3XJE+bAurSK/AgIz5mGFsb77cn9Pb20+WCScw=="],
"@oxfmt/binding-android-arm-eabi": ["@oxfmt/binding-android-arm-eabi@0.77.0", "", { "os": "android", "cpu": "arm" }, "sha512-zmPiuOvkuu0csMx4U3gdMunIFWNcWulzikFMdAPBzLazVAA3LhdHzv9yzgUgAckv/zje5vz4XJcseNQKdSsWMw=="],
"@oxfmt/binding-android-arm64": ["@oxfmt/binding-android-arm64@0.77.0", "", { "os": "android", "cpu": "arm64" }, "sha512-shXOIK9sj3bvt4H6K47qFWNKaYBwEhzj97iUwoLGyyRDrXt1OdAAuCiupCinG1i7ETL81knjEKeB+JmhOOfPew=="],
"@oxfmt/binding-darwin-arm64": ["@oxfmt/binding-darwin-arm64@0.77.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-lrTX0I54buv9CW2leEWchWLdfcrblZ5Rj8uAilKzBEyWif8CTN6zBHdFc12K1b6U2cnlvOFBd1LxdLdqLKX2EA=="],
"@oxfmt/binding-darwin-x64": ["@oxfmt/binding-darwin-x64@0.77.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-SD44K3x/Im8EsOtdHxjVmTBi0cafAaunRpCeq+w91tkD2keqYagR8oAvxkJHUK+KPg5NQk7JZqQnzGHnVEBrDw=="],
"@oxfmt/binding-freebsd-x64": ["@oxfmt/binding-freebsd-x64@0.77.0", "", { "os": "freebsd", "cpu": "x64" }, "sha512-N+gUflsCx3FAVkxi5sxGlL5LwO+7pv5NexHJufBqPyl3BcPv1rXpfwqhL/Vj+XfshfoxMFTBbzrbJgGVaPVkAw=="],
"@oxfmt/binding-linux-arm-gnueabihf": ["@oxfmt/binding-linux-arm-gnueabihf@0.77.0", "", { "os": "linux", "cpu": "arm" }, "sha512-DXGwP8818IUZ4cxcfugg9PXqnI6fVCWIqgCgBoUKdl/QhJF4Po+lucJBrnrX/b5BNKwVMc3xSrvbI9rl8+RrBA=="],
"@oxfmt/binding-linux-arm-musleabihf": ["@oxfmt/binding-linux-arm-musleabihf@0.77.0", "", { "os": "linux", "cpu": "arm" }, "sha512-HUiJTgdV10PkCW41nHqVYYlW8Uc+39YBOoluZLfJE2MBPKVTNElhL+vpdSEuVaCGhGkzOGR6XyxM37gu31L1Qw=="],
"@oxfmt/binding-linux-arm64-gnu": ["@oxfmt/binding-linux-arm64-gnu@0.77.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-+w3V07y6yy8FdACnGtzgDsG/CHgA0Y/W2/bzZuPYgvBAa23Lap/nmvyNQmCiGKkSaChTPlY7QpIShGGAC7IGEQ=="],
"@oxfmt/binding-linux-arm64-musl": ["@oxfmt/binding-linux-arm64-musl@0.77.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-FASxWQAuLW4WXFViDa77ybd3Y1lbkBx5DTtL4OGl+pL64/ymtydTFvJM0xz/0vnCirNzPUDAI6TiTBDGsFbEVg=="],
"@oxfmt/binding-linux-ppc64-gnu": ["@oxfmt/binding-linux-ppc64-gnu@0.77.0", "", { "os": "linux", "cpu": "ppc64" }, "sha512-WRdlgZahG35zCieq7Po7QU8mBgkFAIdEpgS5p3vVZrHt0FXTbFgzqC7xeBCceh9gpFGgr4VWblULNnU8gdw0DA=="],
"@oxfmt/binding-linux-riscv64-gnu": ["@oxfmt/binding-linux-riscv64-gnu@0.77.0", "", { "os": "linux", "cpu": "none" }, "sha512-CVzNO94x/UzQe/INVUu9qt5X1MjLEooqwc/5VcQ88eyLXiEIIsjubpPQgwEMKwfWtAA5hnpFL2GF74zSdCg07Q=="],
"@oxfmt/binding-linux-riscv64-musl": ["@oxfmt/binding-linux-riscv64-musl@0.77.0", "", { "os": "linux", "cpu": "none" }, "sha512-NrCcVheqL0kRUi9gptqjkQhxSFayotM+zycC3lSOSrsf5SroZq49u66ShyuZkHCCzKPHB0AT0pL/s+ET9R3qQQ=="],
"@oxfmt/binding-linux-s390x-gnu": ["@oxfmt/binding-linux-s390x-gnu@0.77.0", "", { "os": "linux", "cpu": "s390x" }, "sha512-LWDQ9T/Bo/kt/q223j9fYLiNTkUYyuMkk7ZrIsIAV7l19MmuKxgd/1tZ8xhoUuVIdsyET7sJrQ6X/vRG6V+bZQ=="],
"@oxfmt/binding-linux-x64-gnu": ["@oxfmt/binding-linux-x64-gnu@0.77.0", "", { "os": "linux", "cpu": "x64" }, "sha512-5JbOT3ucC/2kROUjyyOW06FjXO8trPjYb+kE7E7cLxmpGAnw0jjeU4Tjg4C8H9JR1MZ2oH4fXE1NqLNZ89ISnw=="],
"@oxfmt/binding-linux-x64-musl": ["@oxfmt/binding-linux-x64-musl@0.77.0", "", { "os": "linux", "cpu": "x64" }, "sha512-/q9p495bmmKtxqWlIrNiJ15hoddgk/jPvJwMW6Nh796UgVRMTCKD7yI+AAL7/7xWlC3+2ls5l1RPywuV4lOdlw=="],
"@oxfmt/binding-openharmony-arm64": ["@oxfmt/binding-openharmony-arm64@0.77.0", "", { "os": "none", "cpu": "arm64" }, "sha512-tmN3OEI38xXr48UeAkQMAX1jMHszVHv4I9lzh44DKrMlIFxEU0aBYl3Zs7PzRBuJOLR7h77m6bUlCh0E06MVXw=="],
"@oxfmt/binding-win32-arm64-msvc": ["@oxfmt/binding-win32-arm64-msvc@0.77.0", "", { "os": "win32", "cpu": "arm64" }, "sha512-v//nJMk72xRT+/9QB9mJWEPV3/5XncMvxtYQAYbAsv5VcxLlRcbj2n2srQSERglVcTft4jI3MK30ceCoRcDTJg=="],
"@oxfmt/binding-win32-ia32-msvc": ["@oxfmt/binding-win32-ia32-msvc@0.77.0", "", { "os": "win32", "cpu": "ia32" }, "sha512-D3SMXWBkVogzAlzd3RfMaFuHOTdPpRDFT+jVbtXszWwck9PCK4hYoRoncjuAjWZuWzRFND3/Mk91qFvJyoJbLA=="],
"@oxfmt/binding-win32-x64-msvc": ["@oxfmt/binding-win32-x64-msvc@0.77.0", "", { "os": "win32", "cpu": "x64" }, "sha512-2vyyODjP1Sb830rTVgfFqZoIUYF8uYdGx9S/Usih+Av6gQ9QyxXzwEGXS7poxfsxxQftZW1IbcFlhvQkeDRekQ=="],
"@oxlint/binding-android-arm-eabi": ["@oxlint/binding-android-arm-eabi@1.92.0", "", { "os": "android", "cpu": "arm" }, "sha512-k3Sd4ixQfiOrybv1gT+AMI81HSdtAFsiCFx+xXxWdFkmKW2HNrSiOfwn20o5nl/ggwbzU1oNLDeU/fRPinTVZQ=="],
"@oxlint/binding-android-arm64": ["@oxlint/binding-android-arm64@1.92.0", "", { "os": "android", "cpu": "arm64" }, "sha512-OZzgEuiTSG11QkBWdXEguiLOT6lL09KtfcC/BmvUQWBAjU5eVyBxIAsmWAXv8L85/eT6RE0GBEWTEFBAbYE74g=="],
"@oxlint/binding-darwin-arm64": ["@oxlint/binding-darwin-arm64@1.92.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-We6XS7tIqxgUoany6uyGjj7mNsh/mwf4Gt9gUzhxG65NKo2Ow9s6tDfrVuI0FVg8n3YmpW5PBx80qFxiLwAfsA=="],
"@oxlint/binding-darwin-x64": ["@oxlint/binding-darwin-x64@1.92.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-jKJWijmi6AxAZcXXWA6R/NLVZHxoRTbIMnV8znsHzeiVfuEefYcyR8SJGfbBPmkG+kveLFRcBGw0fBrjLqtGmQ=="],
"@oxlint/binding-freebsd-x64": ["@oxlint/binding-freebsd-x64@1.92.0", "", { "os": "freebsd", "cpu": "x64" }, "sha512-wkw01wvJPM8/4jh+MV3cp11859VuBc94N2q5uOzcBgdGIRAqMCg1O0W/+xsZ1fsInvuUcv2Xo4nd1nzcKhi9kg=="],
"@oxlint/binding-linux-arm-gnueabihf": ["@oxlint/binding-linux-arm-gnueabihf@1.92.0", "", { "os": "linux", "cpu": "arm" }, "sha512-Elm6nW308MzmR8knvk0tPqQ4XE+PGKztjXv7kVZTRLkhBQZRXHUQoBLc4E30fiIuF6gkZO5f3EpJtQc4Ok/fXw=="],
"@oxlint/binding-linux-arm-musleabihf": ["@oxlint/binding-linux-arm-musleabihf@1.92.0", "", { "os": "linux", "cpu": "arm" }, "sha512-oylpBAoeogddjhTlSPsXrzGq/aeJsvaULz/hYXvWtGn/Wt8LPLC7gFhucCicbRnzEKsShrZxIA0KyHmtFNnijQ=="],
"@oxlint/binding-linux-arm64-gnu": ["@oxlint/binding-linux-arm64-gnu@1.92.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-/EWOI0wwY+74UGvC93TldpoNP8moIcidVUPbUSoX16/SEdF7ah209yxSQia4+9JdCRWYA3+yQMofXMgWKk/16Q=="],
"@oxlint/binding-linux-arm64-musl": ["@oxlint/binding-linux-arm64-musl@1.92.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-9Se7Zuazr104yc2PaluriJW2rqvtaN6FSi9MSjQgZGeYb6LKvEcJ586tpjek0l7hNQNoir8MID7OENPH6juN1w=="],
"@oxlint/binding-linux-ppc64-gnu": ["@oxlint/binding-linux-ppc64-gnu@1.92.0", "", { "os": "linux", "cpu": "ppc64" }, "sha512-88IAchs204I/xxAbAo3NRyz1m/29tn8jUAPvc4tK4FzrT2PLwZertd93ANF6231vwbAhYiD5gl0cX8Po5xsjWQ=="],
"@oxlint/binding-linux-riscv64-gnu": ["@oxlint/binding-linux-riscv64-gnu@1.92.0", "", { "os": "linux", "cpu": "none" }, "sha512-KtFdVdkfvBGcsrmnbjYJ9/XTDABnaniiwnptAcAm0pkaR2zhZ3sr/Xy+N1Xbz1Yq5Jegu7SoeNv9caTP0b5OTA=="],
"@oxlint/binding-linux-riscv64-musl": ["@oxlint/binding-linux-riscv64-musl@1.92.0", "", { "os": "linux", "cpu": "none" }, "sha512-V43CO5FPgHtwHup4H5+dIdwzZX2FhREQGsSBZx8V1UyFEAul0Q13qviKqZfSMM6G41CGtCekVpJGGOxW5v1y8Q=="],
"@oxlint/binding-linux-s390x-gnu": ["@oxlint/binding-linux-s390x-gnu@1.92.0", "", { "os": "linux", "cpu": "s390x" }, "sha512-WooxeACzGH5q34olo7JgAk7XbVkTUNfwhR/TzmhwVs/y1p2R7ZWJo14hiyxiGcoYZR1iBnbBFHectADqb/KSog=="],
"@oxlint/binding-linux-x64-gnu": ["@oxlint/binding-linux-x64-gnu@1.92.0", "", { "os": "linux", "cpu": "x64" }, "sha512-lW2pLF1oFvNN780YUCtDyoUm8oFzZGJNcOFe9RtLMX5v5+FcWfAQvHUMMPF8H8kJB0HAi3dFmWDWLa5VPuY9mw=="],
"@oxlint/binding-linux-x64-musl": ["@oxlint/binding-linux-x64-musl@1.92.0", "", { "os": "linux", "cpu": "x64" }, "sha512-2BJAAB/eqPn7iD7mFVfs+1ZVUogAYOMCTaUgjAvbtNGg2ppCDE7gcv/9VSO6GCDybdFUqlcyeyjn9hRpl1ZHog=="],
"@oxlint/binding-openharmony-arm64": ["@oxlint/binding-openharmony-arm64@1.92.0", "", { "os": "none", "cpu": "arm64" }, "sha512-iLtjNqqa/2IV5qu/3rrkpVd42Ia3yeCn4fSZoEr+m5FoGHtZvAV6J6YuU3lewg5Rg5ORGvwhdgN+7gNzwkl7tA=="],
"@oxlint/binding-win32-arm64-msvc": ["@oxlint/binding-win32-arm64-msvc@1.92.0", "", { "os": "win32", "cpu": "arm64" }, "sha512-ryxiR3ZqB0OJzydMu+bVC3R7ZtoU7X1rI8sEgTBCCvQvgVwoCwqSFlfmhgiZ+9wZ4IdTsFeu9tdiF9KtRCbSHQ=="],
"@oxlint/binding-win32-ia32-msvc": ["@oxlint/binding-win32-ia32-msvc@1.92.0", "", { "os": "win32", "cpu": "ia32" }, "sha512-DaE9OChj4nsdEST32BP7saGu8WtjOinTy/eS88dZ0TvTfDV26ebRDhsI1rL9OKXfO+DgehzhAQMqdPr2jgfcFw=="],
"@oxlint/binding-win32-x64-msvc": ["@oxlint/binding-win32-x64-msvc@1.92.0", "", { "os": "win32", "cpu": "x64" }, "sha512-0AyhqX0ciFuEnHIL+B4PIMMX3s/IpGHNEbbUqwsNhSrzWUSlEOPw/q7qFnRsEJfiKedcqVfUE/aXYuSMtpiFyw=="],
"@rolldown/binding-android-arm-eabi": ["@rolldown/binding-android-arm-eabi@1.2.16", "", { "os": "android", "cpu": "arm" }, "sha512-ia3DwAs0OsMGS7+IConptSiyk9pEXkOx/AbJ2n/lAGxH3QkWQus1t8d7gnAT38FCU2sQu8lUbeR6AiZFv4JxaA=="],
"@rolldown/binding-android-arm64": ["@rolldown/binding-android-arm64@1.2.16", "", { "os": "android", "cpu": "arm64" }, "sha512-kx5wBiMB6E7TEvpl2B9gjLU004BkvEm2Dr941BFjx/SontPwSzNuQUIoVKxHHoSjpFIfHMmcguyLOtyn0hObRg=="],
"@rolldown/binding-darwin-arm64": ["@rolldown/binding-darwin-arm64@1.2.16", "", { "os": "darwin", "cpu": "arm64" }, "sha512-qslZrXnKJU4cUpjoAmtAo/KQM9e2IRMlmpig6Zpwj+8KWxW8v+nkAf9216Bsek9lOC1jvg2yCjygCFo2f83msQ=="],
"@rolldown/binding-darwin-x64": ["@rolldown/binding-darwin-x64@1.2.16", "", { "os": "darwin", "cpu": "x64" }, "sha512-FdF+y48ND13eAyM2mQn+85kvAqNlvRWROy2rhgA463X/0Gv4vGtazZtfaF1mRBLscYvtOlh4QnLjOWiFzX69OQ=="],
"@rolldown/binding-freebsd-x64": ["@rolldown/binding-freebsd-x64@1.2.16", "", { "os": "freebsd", "cpu": "x64" }, "sha512-ddjqFM5e95AgLbUPtKIS7V1KTVlA0RUgCVr5mn+/IEhsdy3pr+Vuj/HZ7nlMN2FyxIwUktOH1LEPIQXO1v9y1Q=="],
"@rolldown/binding-linux-arm-gnueabihf": ["@rolldown/binding-linux-arm-gnueabihf@1.2.16", "", { "os": "linux", "cpu": "arm" }, "sha512-tHdKWbFkFBI687iim3LIyIvyL7j66VvQYkDPss5Stn/qyE2tWkR1YD0dXmXPFKKqT/o5ZEJVsaRsWS2meQwGOA=="],
"@rolldown/binding-linux-arm64-gnu": ["@rolldown/binding-linux-arm64-gnu@1.2.16", "", { "os": "linux", "cpu": "arm64" }, "sha512-FJiLGAblPBMlBEdbOqw6kW6QcXDWAf/oJu7gYs9ZJZwmg+K+/zjFLxPTIY9izJUzxzc24FHvmseyA0IvJSl17w=="],
"@rolldown/binding-linux-arm64-musl": ["@rolldown/binding-linux-arm64-musl@1.2.16", "", { "os": "linux", "cpu": "arm64" }, "sha512-hrJpblMsrQ58U9veWpbXzkhV5zStunds6HWLprqq1qauvgBr1E6P+24kLj6lSLI9vjRn/RYpjprhkHQPKGWpNg=="],
"@rolldown/binding-linux-ppc64-gnu": ["@rolldown/binding-linux-ppc64-gnu@1.2.16", "", { "os": "linux", "cpu": "ppc64" }, "sha512-qJd/dC6j6CwLG9/s/RP2nb1RZ0GIgj7Ioj7x/SYa3RzjVrlzrmH0fhIOpfvqQDeIsdP0loi+kHaMhJzY1PBIaA=="],
"@rolldown/binding-linux-s390x-gnu": ["@rolldown/binding-linux-s390x-gnu@1.2.16", "", { "os": "linux", "cpu": "s390x" }, "sha512-Vx7Xg5uUJuNcujJjI70OICaH0EYj80BtOLZTSN7uOYg8QOLlyKnaG0IW7Fn/J0IpJsaKzmDKMhOQv1JBM9m9vg=="],
"@rolldown/binding-linux-x64-gnu": ["@rolldown/binding-linux-x64-gnu@1.2.16", "", { "os": "linux", "cpu": "x64" }, "sha512-TNKhgE3uJTsTzatUSSYt0Kgo+Oa2uSlSjz4r1aEIea7HX6ULBym4fAlYUhG1i6pjNf2njfCUAfKwr6C3E9Xg1w=="],
"@rolldown/binding-linux-x64-musl": ["@rolldown/binding-linux-x64-musl@1.2.16", "", { "os": "linux", "cpu": "x64" }, "sha512-7chXdpjXZ8qG0+mIxECN3cT9kvhZ3/oZhMX6Pp876P7CDrIy8nJswva6Mq357JR7eYXfuskwZxMeV1SzoZdHrA=="],
"@rolldown/binding-openharmony-arm64": ["@rolldown/binding-openharmony-arm64@1.2.16", "", { "os": "none", "cpu": "arm64" }, "sha512-Kwjt+7uNTJK5/MDkGWGVO2KQPnj8yAV75dMpfwyHZrJSXWHrniOB0aUEWlVYf3H1hOqFLIStLdM5QXq6bnKmOQ=="],
"@rolldown/binding-win32-arm64-msvc": ["@rolldown/binding-win32-arm64-msvc@1.2.16", "", { "os": "win32", "cpu": "arm64" }, "sha512-/LH6WfjDRXXJz/p5xl4TmU+jpcnwcxbKEQBW/GZE0JHfN0lGIyTtsUEGaQ/q/GikkGJ2yLKe6pwm7AnEWO8pdw=="],
"@rolldown/binding-win32-x64-msvc": ["@rolldown/binding-win32-x64-msvc@1.2.16", "", { "os": "win32", "cpu": "x64" }, "sha512-1lv1KvX0Z871zfk7vw+dnXMMnHNyDwMzWG8Kv3HxDXMOhzCX4SHc7HK319fInP0i+0p9D8brkfzL7pJOaGl+tw=="],
"@rolldown/pluginutils": ["@rolldown/pluginutils@1.0.1", "", {}, "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw=="],
"@typescript/typescript-aix-ppc64": ["@typescript/typescript-aix-ppc64@7.0.2", "", { "os": "aix", "cpu": "ppc64" }, "sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ=="],
"@typescript/typescript-darwin-arm64": ["@typescript/typescript-darwin-arm64@7.0.2", "", { "os": "darwin", "cpu": "arm64" }, "sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA=="],
"@typescript/typescript-darwin-x64": ["@typescript/typescript-darwin-x64@7.0.2", "", { "os": "darwin", "cpu": "x64" }, "sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA=="],
"@typescript/typescript-freebsd-arm64": ["@typescript/typescript-freebsd-arm64@7.0.2", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ=="],
"@typescript/typescript-freebsd-x64": ["@typescript/typescript-freebsd-x64@7.0.2", "", { "os": "freebsd", "cpu": "x64" }, "sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw=="],
"@typescript/typescript-linux-arm": ["@typescript/typescript-linux-arm@7.0.2", "", { "os": "linux", "cpu": "arm" }, "sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ=="],
"@typescript/typescript-linux-arm64": ["@typescript/typescript-linux-arm64@7.0.2", "", { "os": "linux", "cpu": "arm64" }, "sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ=="],
"@typescript/typescript-linux-loong64": ["@typescript/typescript-linux-loong64@7.0.2", "", { "os": "linux", "cpu": "none" }, "sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ=="],
"@typescript/typescript-linux-mips64el": ["@typescript/typescript-linux-mips64el@7.0.2", "", { "os": "linux", "cpu": "none" }, "sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA=="],
"@typescript/typescript-linux-ppc64": ["@typescript/typescript-linux-ppc64@7.0.2", "", { "os": "linux", "cpu": "ppc64" }, "sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA=="],
"@typescript/typescript-linux-riscv64": ["@typescript/typescript-linux-riscv64@7.0.2", "", { "os": "linux", "cpu": "none" }, "sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ=="],
"@typescript/typescript-linux-s390x": ["@typescript/typescript-linux-s390x@7.0.2", "", { "os": "linux", "cpu": "s390x" }, "sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw=="],
"@typescript/typescript-linux-x64": ["@typescript/typescript-linux-x64@7.0.2", "", { "os": "linux", "cpu": "x64" }, "sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A=="],
"@typescript/typescript-netbsd-arm64": ["@typescript/typescript-netbsd-arm64@7.0.2", "", { "os": "none", "cpu": "arm64" }, "sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA=="],
"@typescript/typescript-netbsd-x64": ["@typescript/typescript-netbsd-x64@7.0.2", "", { "os": "none", "cpu": "x64" }, "sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA=="],
"@typescript/typescript-openbsd-arm64": ["@typescript/typescript-openbsd-arm64@7.0.2", "", { "os": "openbsd", "cpu": "arm64" }, "sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ=="],
"@typescript/typescript-openbsd-x64": ["@typescript/typescript-openbsd-x64@7.0.2", "", { "os": "openbsd", "cpu": "x64" }, "sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg=="],
"@typescript/typescript-sunos-x64": ["@typescript/typescript-sunos-x64@7.0.2", "", { "os": "sunos", "cpu": "x64" }, "sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g=="],
"@typescript/typescript-win32-arm64": ["@typescript/typescript-win32-arm64@7.0.2", "", { "os": "win32", "cpu": "arm64" }, "sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ=="],
"@typescript/typescript-win32-x64": ["@typescript/typescript-win32-x64@7.0.2", "", { "os": "win32", "cpu": "x64" }, "sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g=="],
"detect-libc": ["detect-libc@2.1.2", "", {}, "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ=="],
"fdir": ["fdir@6.5.0", "", { "peerDependencies": { "picomatch": "^3 || ^4" }, "optionalPeers": ["picomatch"] }, "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg=="],
"fsevents": ["fsevents@2.3.3", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="],
"lightningcss": ["lightningcss@1.33.0", "", { "dependencies": { "detect-libc": "^2.0.3" }, "optionalDependencies": { "lightningcss-android-arm64": "1.33.0", "lightningcss-darwin-arm64": "1.33.0", "lightningcss-darwin-x64": "1.33.0", "lightningcss-freebsd-x64": "1.33.0", "lightningcss-linux-arm-gnueabihf": "1.33.0", "lightningcss-linux-arm64-gnu": "1.33.0", "lightningcss-linux-arm64-musl": "1.33.0", "lightningcss-linux-x64-gnu": "1.33.0", "lightningcss-linux-x64-musl": "1.33.0", "lightningcss-win32-arm64-msvc": "1.33.0", "lightningcss-win32-x64-msvc": "1.33.0" } }, "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA=="],
"lightningcss-android-arm64": ["lightningcss-android-arm64@1.33.0", "", { "os": "android", "cpu": "arm64" }, "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg=="],
"lightningcss-darwin-arm64": ["lightningcss-darwin-arm64@1.33.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg=="],
"lightningcss-darwin-x64": ["lightningcss-darwin-x64@1.33.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ=="],
"lightningcss-freebsd-x64": ["lightningcss-freebsd-x64@1.33.0", "", { "os": "freebsd", "cpu": "x64" }, "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg=="],
"lightningcss-linux-arm-gnueabihf": ["lightningcss-linux-arm-gnueabihf@1.33.0", "", { "os": "linux", "cpu": "arm" }, "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ=="],
"lightningcss-linux-arm64-gnu": ["lightningcss-linux-arm64-gnu@1.33.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg=="],
"lightningcss-linux-arm64-musl": ["lightningcss-linux-arm64-musl@1.33.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ=="],
"lightningcss-linux-x64-gnu": ["lightningcss-linux-x64-gnu@1.33.0", "", { "os": "linux", "cpu": "x64" }, "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg=="],
"lightningcss-linux-x64-musl": ["lightningcss-linux-x64-musl@1.33.0", "", { "os": "linux", "cpu": "x64" }, "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw=="],
"lightningcss-win32-arm64-msvc": ["lightningcss-win32-arm64-msvc@1.33.0", "", { "os": "win32", "cpu": "arm64" }, "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA=="],
"lightningcss-win32-x64-msvc": ["lightningcss-win32-x64-msvc@1.33.0", "", { "os": "win32", "cpu": "x64" }, "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA=="],
"nanoid": ["nanoid@3.3.20", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ=="],
"oxfmt": ["oxfmt@0.77.0", "", { "dependencies": { "tinypool": "2.2.0" }, "optionalDependencies": { "@oxfmt/binding-android-arm-eabi": "0.77.0", "@oxfmt/binding-android-arm64": "0.77.0", "@oxfmt/binding-darwin-arm64": "0.77.0", "@oxfmt/binding-darwin-x64": "0.77.0", "@oxfmt/binding-freebsd-x64": "0.77.0", "@oxfmt/binding-linux-arm-gnueabihf": "0.77.0", "@oxfmt/binding-linux-arm-musleabihf": "0.77.0", "@oxfmt/binding-linux-arm64-gnu": "0.77.0", "@oxfmt/binding-linux-arm64-musl": "0.77.0", "@oxfmt/binding-linux-ppc64-gnu": "0.77.0", "@oxfmt/binding-linux-riscv64-gnu": "0.77.0", "@oxfmt/binding-linux-riscv64-musl": "0.77.0", "@oxfmt/binding-linux-s390x-gnu": "0.77.0", "@oxfmt/binding-linux-x64-gnu": "0.77.0", "@oxfmt/binding-linux-x64-musl": "0.77.0", "@oxfmt/binding-openharmony-arm64": "0.77.0", "@oxfmt/binding-win32-arm64-msvc": "0.77.0", "@oxfmt/binding-win32-ia32-msvc": "0.77.0", "@oxfmt/binding-win32-x64-msvc": "0.77.0" }, "peerDependencies": { "@astrojs/compiler-rs": "^0.5.0", "svelte": "^5.0.0", "vite-plus": "*" }, "optionalPeers": ["@astrojs/compiler-rs", "svelte", "vite-plus"], "bin": { "oxfmt": "bin/oxfmt" } }, "sha512-3bPDJwLZf4i6dOaQS+6GOI/YUFTHNif7qw4nknbZyzdB0uws57tD8jA/GLGC9J7kjyf6d/eVWm73b43VeMUqGw=="],
"oxlint": ["oxlint@1.92.0", "", { "optionalDependencies": { "@oxlint/binding-android-arm-eabi": "1.92.0", "@oxlint/binding-android-arm64": "1.92.0", "@oxlint/binding-darwin-arm64": "1.92.0", "@oxlint/binding-darwin-x64": "1.92.0", "@oxlint/binding-freebsd-x64": "1.92.0", "@oxlint/binding-linux-arm-gnueabihf": "1.92.0", "@oxlint/binding-linux-arm-musleabihf": "1.92.0", "@oxlint/binding-linux-arm64-gnu": "1.92.0", "@oxlint/binding-linux-arm64-musl": "1.92.0", "@oxlint/binding-linux-ppc64-gnu": "1.92.0", "@oxlint/binding-linux-riscv64-gnu": "1.92.0", "@oxlint/binding-linux-riscv64-musl": "1.92.0", "@oxlint/binding-linux-s390x-gnu": "1.92.0", "@oxlint/binding-linux-x64-gnu": "1.92.0", "@oxlint/binding-linux-x64-musl": "1.92.0", "@oxlint/binding-openharmony-arm64": "1.92.0", "@oxlint/binding-win32-arm64-msvc": "1.92.0", "@oxlint/binding-win32-ia32-msvc": "1.92.0", "@oxlint/binding-win32-x64-msvc": "1.92.0" }, "peerDependencies": { "oxlint-tsgolint": ">=7.0.2005", "vite-plus": "*" }, "optionalPeers": ["oxlint-tsgolint", "vite-plus"], "bin": { "oxlint": "bin/oxlint" } }, "sha512-y9iRiRwVjVFqzKNXZJ9bT/GYRdf+F9Gy+a1Yju2Aq3xqqa4FJYXHI8VrxlpzxKDvkYRohvJX42m/eH+qkQPOFw=="],
"picocolors": ["picocolors@1.1.1", "", {}, "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA=="],
"picomatch": ["picomatch@4.0.7", "", {}, "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA=="],
"postcss": ["postcss@8.5.32", "", { "dependencies": { "nanoid": "^3.3.20", "picocolors": "^1.1.1", "source-map-js": "^1.2.2" } }, "sha512-LJlKCCAUFKOuZxipUdYw1NzIITEsPcgyOG9LkvRJvuKj/bRzbuRY0ARXvL0pWGpsZvn8jku+LMep2eU0seHp8g=="],
"rolldown": ["rolldown@1.2.16", "", { "dependencies": { "@oxc-project/types": "=0.156.0", "@rolldown/pluginutils": "^1.0.0" }, "optionalDependencies": { "@rolldown/binding-android-arm-eabi": "1.2.16", "@rolldown/binding-android-arm64": "1.2.16", "@rolldown/binding-darwin-arm64": "1.2.16", "@rolldown/binding-darwin-x64": "1.2.16", "@rolldown/binding-freebsd-x64": "1.2.16", "@rolldown/binding-linux-arm-gnueabihf": "1.2.16", "@rolldown/binding-linux-arm64-gnu": "1.2.16", "@rolldown/binding-linux-arm64-musl": "1.2.16", "@rolldown/binding-linux-ppc64-gnu": "1.2.16", "@rolldown/binding-linux-s390x-gnu": "1.2.16", "@rolldown/binding-linux-x64-gnu": "1.2.16", "@rolldown/binding-linux-x64-musl": "1.2.16", "@rolldown/binding-openharmony-arm64": "1.2.16", "@rolldown/binding-win32-arm64-msvc": "1.2.16", "@rolldown/binding-win32-x64-msvc": "1.2.16" }, "bin": { "rolldown": "./bin/cli.mjs" } }, "sha512-bWvlMpFKiTfDKfnK7FC2MPgPeWCf/Kpwsq49ApdW+FQaBZb6O6dZ4MAPbPUjp7hYQrw/RobqCzn64BRrQecGHw=="],
"source-map-js": ["source-map-js@1.2.2", "", {}, "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw=="],
"tinyglobby": ["tinyglobby@0.2.17", "", { "dependencies": { "fdir": "^6.5.0", "picomatch": "^4.0.4" } }, "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g=="],
"tinypool": ["tinypool@2.2.0", "", {}, "sha512-jBrmx4lYmaC9k/mgPbylxs7kBUxHtD8256up+HjLaDFfXScKJQyil+SWXSvhAtT7XHo+yTVlpB81PGmHP8oLSQ=="],
"typescript": ["typescript@7.0.2", "", { "optionalDependencies": { "@typescript/typescript-aix-ppc64": "7.0.2", "@typescript/typescript-darwin-arm64": "7.0.2", "@typescript/typescript-darwin-x64": "7.0.2", "@typescript/typescript-freebsd-arm64": "7.0.2", "@typescript/typescript-freebsd-x64": "7.0.2", "@typescript/typescript-linux-arm": "7.0.2", "@typescript/typescript-linux-arm64": "7.0.2", "@typescript/typescript-linux-loong64": "7.0.2", "@typescript/typescript-linux-mips64el": "7.0.2", "@typescript/typescript-linux-ppc64": "7.0.2", "@typescript/typescript-linux-riscv64": "7.0.2", "@typescript/typescript-linux-s390x": "7.0.2", "@typescript/typescript-linux-x64": "7.0.2", "@typescript/typescript-netbsd-arm64": "7.0.2", "@typescript/typescript-netbsd-x64": "7.0.2", "@typescript/typescript-openbsd-arm64": "7.0.2", "@typescript/typescript-openbsd-x64": "7.0.2", "@typescript/typescript-sunos-x64": "7.0.2", "@typescript/typescript-win32-arm64": "7.0.2", "@typescript/typescript-win32-x64": "7.0.2" }, "bin": { "tsc": "bin/tsc" } }, "sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA=="],
"vite": ["vite@8.3.6", "", { "dependencies": { "lightningcss": "^1.33.0", "picomatch": "^4.0.7", "postcss": "^8.5.32", "rolldown": "~1.2.16", "tinyglobby": "^0.2.17" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", "@vitejs/devtools": "^0.7.1 || ^0.8.0", "esbuild": "^0.27.0 || ^0.28.0", "jiti": ">=1.21.0", "less": "^4.0.0", "sass": "^1.70.0", "sass-embedded": "^1.70.0", "stylus": ">=0.54.8", "sugarss": "^5.0.0", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "@vitejs/devtools", "esbuild", "jiti", "less", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-UI7dK29NnS54Fk+mmo7o+jI6U8Fp7hDl+X5Q1k45WH+d4dSlbLVUETGQ+hfkNgvLQGyoElPj837nZyv4MBc0VA=="],
}
}

24
package.json Normal file
View file

@ -0,0 +1,24 @@
{
"name": "building-use-map",
"version": "1.0.0",
"description": "Building-use map for Czechia (RÚIAN)",
"repository": {
"type": "git",
"url": "https://git.hangerthem.com/HangerThem/building-use-map.git"
},
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc && vite build",
"preview": "vite preview",
"typecheck": "tsc"
},
"dependencies": {},
"devDependencies": {
"oxfmt": "^0.77.0",
"oxlint": "^1.92.0",
"typescript": "^7.0.2",
"vite": "^8.3.6"
},
"private": true
}

50
src/basemap.ts Normal file
View file

@ -0,0 +1,50 @@
/* ================= basemap styles ================= */
/** ZABAGED layer ids on the ČÚZK MapServer. */
export const ZAB_LAYERS = {
road: 79,
street: 84,
track: 83,
path: 82,
rail: 75,
stream: 93,
water: 132,
green: 134,
garden: 135,
cemetery: 116,
parking: 123,
}
export type BaseKey = keyof typeof ZAB_LAYERS
interface PolyStyle {
k: BaseKey
t: 'poly'
fill: string
stroke?: string
}
/** m: width in true metres, min: minimum width in px */
interface LineStyle {
k: BaseKey
t: 'line'
c: string
m: number
min: number
dash?: number[]
}
export type BaseStyle = PolyStyle | LineStyle
// Drawn in this order (later entries on top)
export const BASE: BaseStyle[] = [
{ k: 'garden', t: 'poly', fill: '#e6efd6' },
{ k: 'green', t: 'poly', fill: '#cfe4bd' },
{ k: 'cemetery', t: 'poly', fill: '#c9d9bd', stroke: '#9bb08a' },
{ k: 'parking', t: 'poly', fill: '#e2e2e2', stroke: '#c4c4c4' },
{ k: 'water', t: 'poly', fill: '#a8cfe8', stroke: '#7fb2d6' },
{ k: 'stream', t: 'line', c: '#7fb2d6', m: 2, min: 1.2 },
{ k: 'path', t: 'line', c: '#b58b5a', m: 1, min: 0.8, dash: [2, 3] },
{ k: 'track', t: 'line', c: '#c9a16b', m: 2, min: 1, dash: [6, 4] },
{ k: 'rail', t: 'line', c: '#666666', m: 3, min: 1.2, dash: [8, 4] },
{ k: 'street', t: 'line', c: '#9a9a9a', m: 7, min: 2.4 },
{ k: 'street', t: 'line', c: '#ffffff', m: 5, min: 1.8 },
{ k: 'road', t: 'line', c: '#b8862f', m: 11, min: 3.6 },
{ k: 'road', t: 'line', c: '#ffe08a', m: 8.5, min: 2.8 },
]

38
src/building.ts Normal file
View file

@ -0,0 +1,38 @@
import type { Building, 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 {
let x0 = 1e18,
y0 = 1e18,
x1 = -1e18,
y1 = -1e18
for (const r of rings)
for (const p of r) {
if (p[0] < x0) x0 = p[0]
if (p[0] > x1) x1 = p[0]
if (p[1] < y0) y0 = p[1]
if (p[1] > y1) y1 = p[1]
}
const year = done != null && isFinite(done) ? new Date(done).getUTCFullYear() : null
return {
cp: (cp || '').toString().trim(),
use: use == null ? 0 : +use,
flats: flats == null ? null : +flats,
floors: floors == null ? null : +floors,
area: area == null ? null : +area,
year,
rings,
bb: [x0, y0, x1, y1],
cat: 'other',
sc: 'other',
}
}

184
src/categories.ts Normal file
View file

@ -0,0 +1,184 @@
import { t, tKey, ruianUseName } from './i18n'
import { S } from './state'
/* ================= 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],
]
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',
}
// Detailed scheme: one entry per RÚIAN use code
const DETAIL_COLOR: Record<string, string> = {
u1: '#7b3294',
u2: '#8c564b',
u3: '#ff9896',
u4: '#556b2f',
u5: '#1f5fbf',
u6: '#d62728',
u7: '#000000',
u8: '#2ca02c',
u9: '#4fb3e8',
u10: '#e377c2',
u11: '#e8c000',
u12: '#b39ddb',
u13: '#bc8f6f',
u14: '#17808a',
u15: '#3949ab',
u16: '#4d4d4d',
u17: '#7f7f3f',
u18: '#d9b77e',
u19: '#bdbdbd',
u20: '#26c6da',
u21: '#a5d6a7',
uw: '#607d8b',
u0: '#e3e3e3',
mix: '#ff8c00',
}
const DETAIL_ORDER = [
'u0',
'uw',
'u19',
'u18',
'u21',
'u20',
'u13',
'u2',
'u4',
'u16',
'u17',
'u12',
'u1',
'u14',
'u10',
'u11',
'u9',
'u15',
'u5',
'u7',
'u6',
'u3',
'u8',
'mix',
]
const DETAIL_LIST = [
'u7',
'u6',
'u3',
'u8',
'mix',
'u5',
'u15',
'u9',
'u10',
'u11',
'u14',
'u1',
'u12',
'u2',
'u13',
'u4',
'u16',
'u17',
'u18',
'u20',
'u21',
'u19',
'uw',
'u0',
]
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 (S.mixMin > 0 && f >= S.mixMin && base !== 'garage' && base !== 'agri') return 'mix'
return base
}
export function detailKey(use: number, sk: string): string {
if (sk === 'mix') return 'mix'
if (use >= 1 && use <= 21) return 'u' + use
if (use >= 22 && use <= 29) return 'uw'
return 'u0'
}
export function classifyAll() {
for (const b of S.buildings) {
b.sc = simpleKey(b.use, b.flats)
b.cat = S.mode === 'simple' ? b.sc : detailKey(b.use, b.sc)
}
}
export const catColor = (key: string): string =>
(S.mode === 'simple' ? SIMPLE_COLOR[key] : DETAIL_COLOR[key]) || '#bdbdbd'
export function catLabel(key: string): string {
if (S.mode === 'simple') return tKey('cat.' + 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 = () => (S.mode === 'simple' ? SIMPLE.map((c) => c[0]) : DETAIL_LIST)
export const catOrder = () => (S.mode === 'simple' ? SIMPLE_ORDER : DETAIL_ORDER)
export function isDark(hex: string): boolean {
const n = parseInt(hex.slice(1), 16),
r = n >> 16,
g = (n >> 8) & 255,
b = n & 255
return 0.299 * r + 0.587 * g + 0.114 * b < 140
}

149
src/controls.ts Normal file
View file

@ -0,0 +1,149 @@
import { classifyAll } from './categories'
import { fetchArea } from './fetch'
import { D2R, parseLoc } from './geo'
import { lang, setLang, t, tKey, type Lang } from './i18n'
import { showInfo } from './interaction'
import { draw, fitView } from './render'
import { buildLegend, updateCounts } from './sidebar'
import { $, S } from './state'
import type { AreaData, LatLon, Mode } from './types'
import { errMsg } from './util'
/* ================= status line ================= */
// Status is stored as a function so it can be re-rendered when the language changes.
export function setStatus(fn: () => string, cls?: string) {
S.status = { fn, cls }
renderStatus()
}
function renderStatus() {
const s = $('status')
if (!S.status) {
s.textContent = ''
s.className = ''
return
}
s.textContent = S.status.fn()
s.className = S.status.cls || ''
}
/* ================= language ================= */
export function applyLang() {
document.documentElement.lang = lang
document.querySelectorAll<HTMLElement>('[data-i18n]').forEach((el) => {
el.textContent = tKey(el.dataset.i18n!)
})
$('note').innerHTML = t('note')
$('zin').title = t('zoomIn')
$('zout').title = t('zoomOut')
$('zfit').title = t('fit')
$<HTMLSelectElement>('lang').value = lang
document.title = t('title') + ' – RÚIAN'
buildLegend()
renderStatus()
if (S.sel) showInfo(S.sel)
draw()
}
/* ================= data ================= */
export function applyData(d: AreaData, lon: number, lat: number) {
S.buildings = d.buildings
S.base = d.base
S.center = [lon, lat]
S.K = Math.cos(lat * D2R)
S.sel = null
$('info').style.display = 'none'
classifyAll()
fitView()
S.loaded = true
S.hidden.clear()
buildLegend()
draw()
}
export async function liveLoad(p: LatLon, quietFallback: boolean): Promise<boolean> {
const btn = $<HTMLButtonElement>('load')
btn.disabled = true
setStatus(() => t('st_loading'))
try {
const radius = +$<HTMLInputElement>('radius').value
const d = await fetchArea(p.lon, p.lat, radius, (n, m) =>
setStatus(() => t('st_progress', n, m)),
)
if (!d.buildings.length) {
setStatus(() => t('st_none'), 'err')
return false
}
applyData(d, p.lon, p.lat)
const loc = `${p.lat.toFixed(5)}, ${p.lon.toFixed(5)}`,
n = d.buildings.length,
fails = d.fails
setStatus(
() =>
t('st_loaded', loc, n) +
(fails.length ? '\n' + t('st_baseFail', fails.length) + '\n' + fails.join('\n') : ''),
fails.length ? 'err' : 'ok',
)
return true
} catch (e) {
const msg = errMsg(e)
setStatus(() => (quietFallback ? t('st_fallback', msg) : t('st_err', msg)), 'err')
return false
} finally {
btn.disabled = false
}
}
/* ================= controls ================= */
export function initControls() {
const langSel = $<HTMLSelectElement>('lang')
langSel.onchange = () => {
setLang(langSel.value as Lang)
applyLang()
}
const radius = $<HTMLInputElement>('radius')
radius.oninput = () => {
$('rv').textContent = radius.value + ' m'
}
const optBase = $<HTMLInputElement>('optBase'),
optNums = $<HTMLInputElement>('optNums')
optBase.onchange = () => {
S.showBase = optBase.checked
draw()
}
optNums.onchange = () => {
S.showNums = optNums.checked
draw()
}
const mixrule = $<HTMLSelectElement>('mixrule'),
colormode = $<HTMLSelectElement>('colormode')
mixrule.onchange = () => {
S.mixMin = +mixrule.value
classifyAll()
updateCounts()
buildLegend()
draw()
}
colormode.onchange = () => {
S.mode = colormode.value as Mode
S.hidden.clear()
classifyAll()
buildLegend()
draw()
}
const loc = $<HTMLInputElement>('loc')
$('load').onclick = () => {
const p = parseLoc(loc.value)
if (!p) {
setStatus(() => t('st_badLoc'), 'err')
return
}
liveLoad(p, false)
}
loc.addEventListener('keydown', (e) => {
if (e.key === 'Enter') $('load').click()
})
}

109
src/export.ts Normal file
View file

@ -0,0 +1,109 @@
import { BASE } from './basemap'
import { catColor, catLabel, catOrder } from './categories'
import { m2ll } from './geo'
import { ruianUseName } from './i18n'
import { drawLegend, drawScene, legendLayout, pxPerMeter } from './render'
import { $, S, vp } from './state'
import type { Ring } from './types'
/* ================= export ================= */
function download(blob: Blob, name: string) {
const a = document.createElement('a')
a.href = URL.createObjectURL(blob)
a.download = name
document.body.appendChild(a)
a.click()
a.remove()
setTimeout(() => URL.revokeObjectURL(a.href), 4000)
}
function exportPng() {
if (!S.loaded) return
const { W, H } = vp,
r = 2,
lh = legendLayout(W).h
const oc = document.createElement('canvas')
oc.width = W * r
oc.height = (H + lh) * r
const c = oc.getContext('2d')!
drawScene(c, W, H, S.view, r, {})
drawLegend(c, H, W, r)
oc.toBlob((b) => {
if (b) download(b, 'building-use-map.png')
}, 'image/png')
}
function exportSvg() {
if (!S.loaded) return
const { W, H } = vp,
v = S.view,
ppm = pxPerMeter(v)
const sx = (x: number) => ((x - v.cx) * v.s + W / 2).toFixed(1),
sy = (y: number) => (H / 2 - (y - v.cy) * v.s).toFixed(1)
const d = (rings: Ring[], close: boolean) =>
rings
.map((r) => 'M' + r.map((p) => sx(p[0]) + ' ' + sy(p[1])).join('L') + (close ? 'Z' : ''))
.join('')
const { e, colW, rows, h: lh } = legendLayout(W)
let o = ''
o += `<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${H + lh}" viewBox="0 0 ${W} ${H + lh}"><defs><clipPath id="c"><rect width="${W}" height="${H}"/></clipPath></defs>`
o += `<rect width="${W}" height="${H}" fill="#f5f2ea"/><g clip-path="url(#c)" stroke-linejoin="round" stroke-linecap="round">`
if (S.showBase)
for (const st of BASE) {
const rings = S.base[st.k]
if (!rings || !rings.length) continue
if (st.t === 'poly')
o += `<path d="${d(rings, true)}" fill="${st.fill}" fill-rule="evenodd"${st.stroke ? ` stroke="${st.stroke}" stroke-width="1"` : ''}/>`
else
o += `<path d="${d(rings, false)}" fill="none" stroke="${st.c}" stroke-width="${Math.max(st.min, st.m * ppm).toFixed(1)}"${st.dash ? ` stroke-dasharray="${st.dash.map((x) => x * Math.max(1, ppm / 2)).join(' ')}"` : ''}/>`
}
for (const key of catOrder()) {
if (S.hidden.has(key)) continue
const rings: Ring[] = []
for (const b of S.buildings) 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 += '</g>'
o += `<rect y="${H}" width="${W}" height="${lh}" fill="#fff"/><g font-family="system-ui,sans-serif" font-size="12">`
e.forEach((it, i) => {
const c = Math.floor(i / rows),
rr = i % rows,
x = 14 + c * colW,
y = H + 14 + rr * 20
o += `<rect x="${x}" y="${y - 6}" width="18" height="12" fill="${it.color}" stroke="${it.border || '#555'}"/><text x="${x + 26}" y="${y + 4}">${it.label.replace(/&/g, '&amp;').replace(/</g, '&lt;')}</text>`
})
o += '</g></svg>'
download(new Blob([o], { type: 'image/svg+xml' }), 'building-use-map.svg')
}
function exportCsv() {
if (!S.loaded) return
const q = (s: unknown) => '"' + String(s).replace(/"/g, '""') + '"'
let o =
'house_no,ruian_use_code,ruian_use,category,flats,floors,built_up_area_m2,completed,lat,lon\n'
for (const b of S.buildings) {
const ll = m2ll((b.bb[0] + b.bb[2]) / 2, (b.bb[1] + b.bb[3]) / 2)
o +=
[
q(b.cp),
b.use,
q(ruianUseName(b.use)),
q(catLabel(b.cat)),
b.flats ?? '',
b.floors ?? '',
b.area ?? '',
b.year ?? '',
ll[1].toFixed(6),
ll[0].toFixed(6),
].join(',') + '\n'
}
download(new Blob(['' + o], { type: 'text/csv;charset=utf-8' }), 'buildings.csv') // BOM so Excel reads UTF-8
}
export function initExport() {
$('expPng').onclick = exportPng
$('expSvg').onclick = exportSvg
$('expCsv').onclick = exportCsv
$('expPrint').onclick = () => window.print()
}

169
src/fetch.ts Normal file
View file

@ -0,0 +1,169 @@
import { ZAB_LAYERS, type BaseKey } from './basemap'
import { mkBuilding } 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 ZAB = 'https://ags.cuzk.cz/arcgis/rest/services/ZABAGED_POLOHOPIS/MapServer/'
interface Feature {
attributes?: Record<string, unknown>
geometry?: { rings?: Ring[]; paths?: Ring[] }
}
interface QueryResult {
features?: Feature[]
exceededTransferLimit?: boolean
error?: { message?: string }
}
type Settled<T> = { ok: true; v: T } | { ok: false; e: unknown }
async function query(
url: string,
fields: string,
env: string,
offset?: number,
): Promise<QueryResult> {
const p: Record<string, string> = {
geometry: env,
geometryType: 'esriGeometryEnvelope',
inSR: '4326',
outSR: '3857',
spatialRel: 'esriSpatialRelIntersects',
where: '1=1',
outFields: fields,
returnGeometry: 'true',
geometryPrecision: '1',
maxAllowableOffset: '0.3',
f: 'json',
}
if (offset) {
p.resultOffset = String(offset)
p.resultRecordCount = '1000'
}
// No AbortSignal / fetch options: some embedded viewers proxy fetch through postMessage and cannot clone them.
const url2 = url + '?' + new URLSearchParams(p)
let timer: ReturnType<typeof setTimeout> | undefined
const timeout = new Promise<never>((_, rej) => {
timer = setTimeout(() => rej(new Error('timed out after 45 s')), 45000)
})
try {
const res = await Promise.race([fetch(url2), timeout])
if (!res.ok) throw new Error('HTTP ' + res.status)
const j = (await Promise.race([res.json(), timeout])) as QueryResult
if (j.error) throw new Error(j.error.message || 'service error')
return j
} finally {
clearTimeout(timer)
}
}
async function queryAll(url: string, fields: string, env: string): Promise<Feature[]> {
let out: Feature[] = [],
off = 0
for (let page = 0; page < 12; page++) {
let j: QueryResult
try {
j = await query(url, fields, env, off)
} catch (e) {
if (off > 0) break
throw e
}
const f = j.features || []
out = out.concat(f)
if (!j.exceededTransferLimit || !f.length) break
off += f.length
}
return out
}
const lowerKeys = (o: Record<string, unknown> | undefined): Record<string, unknown> =>
Object.fromEntries(Object.entries(o || {}).map(([k, v]) => [k.toLowerCase(), v]))
const ringsOf = (f: Feature): Ring[] => (f.geometry && (f.geometry.rings || f.geometry.paths)) || []
/** Run async tasks, at most n at a time. */
async function pool<T>(tasks: (() => Promise<T>)[], n: number): Promise<Settled<T>[]> {
const out = Array.from({ length: tasks.length }) as Settled<T>[]
let i = 0
await Promise.all(
Array.from({ length: Math.min(n, tasks.length) }, async () => {
while (i < tasks.length) {
const k = i++
try {
out[k] = { ok: true, v: await tasks[k]() }
} catch (e) {
out[k] = { ok: false, e }
}
}
}),
)
return out
}
/** Retry, then try an explicit field instead of an empty field list. */
async function baseLayer(id: number, env: string): Promise<Feature[]> {
let last: unknown
for (const fields of ['', 'objectid', '']) {
try {
return await queryAll(ZAB + id + '/query', fields, env)
} catch (e) {
last = e
await sleep(500)
}
}
throw last
}
export async function fetchArea(
lon: number,
lat: number,
radius: number,
onProgress?: (done: number, total: number) => void,
): Promise<AreaData> {
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 keys = Object.keys(ZAB_LAYERS) as BaseKey[]
const tasks = [
() => queryAll(RUIAN, fields, env),
...keys.map((k) => () => baseLayer(ZAB_LAYERS[k], env)),
]
let done = 0
const res = await pool(
tasks.map((fn) => async () => {
try {
return await fn()
} finally {
if (onProgress) onProgress(++done, tasks.length)
}
}),
4,
)
const first = res[0]
if (!first.ok) throw first.e
const base: BaseData = {},
fails: string[] = []
keys.forEach((k, i) => {
const r = res[i + 1]
if (r.ok) base[k] = r.v.flatMap(ringsOf)
else {
base[k] = []
fails.push(k + ': ' + errMsg(r.e))
}
})
type N = number | null
const buildings = first.v
.map((f) => {
const a = lowerKeys(f.attributes)
return mkBuilding(
a.cisladomovni as string | null,
a.zpusobvyuzitikod as N,
a.pocetbytu as N,
a.pocetpodlazi as N,
a.zastavenaplocha as N,
a.dokonceni as N,
ringsOf(f),
)
})
.filter((b) => b.rings.length)
return { buildings, base, fails }
}

25
src/geo.ts Normal file
View file

@ -0,0 +1,25 @@
import type { LatLon } from './types'
/* ================= geometry helpers ================= */
export const R = 6378137,
D2R = Math.PI / 180
/** Web Mercator metres → [lon, lat] */
export const m2ll = (x: number, y: number): [number, number] => [
x / R / D2R,
(2 * Math.atan(Math.exp(y / R)) - Math.PI / 2) / D2R,
]
/* ================= location parsing ================= */
export function parseLoc(text: string): LatLon | null {
text = (text || '').trim()
const m = text.match(/[?&]x=(-?\d+(?:\.\d+)?)/),
n = text.match(/[?&]y=(-?\d+(?:\.\d+)?)/)
if (m && n) return { lon: +m[1], lat: +n[1] }
const nums = (text.match(/-?\d+(?:\.\d+)?/g) || []).map(Number)
if (nums.length >= 2) {
const [a, b] = nums
if (a >= 48 && a <= 52 && b >= 12 && b <= 19) return { lat: a, lon: b }
if (b >= 48 && b <= 52 && a >= 12 && a <= 19) return { lat: b, lon: a }
}
return null
}

225
src/i18n.ts Normal file
View file

@ -0,0 +1,225 @@
/* ================= i18n ================= */
export type Lang = 'en' | 'cs'
const en = {
title: 'Building-use map',
subtitle: 'Czechia · RÚIAN buildings over ZABAGED roads & rivers (ČÚZK)',
locLabel: 'Location – Mapy.com link, “lat, lon”, or “lon, lat”',
radius: 'Radius',
load: 'Load area',
layers: 'Layers',
display: 'Display',
colorMode: 'Colour scheme',
modeSimple: 'Simple – grouped categories',
modeDetailed: 'Detailed – one colour per use code',
mixLabel: 'Mixed-use rule',
mix1: 'Non-residential use with ≥ 1 flat',
mix2: 'Non-residential use with ≥ 2 flats',
mix0: 'Off',
optBase: 'Roads, rivers, green areas',
optNums: 'House numbers when zoomed in',
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.',
nBuildings: (n: number) => `· ${n} buildings`,
st_loading: 'Loading buildings and basemap from ČÚZK…',
st_progress: (n: number, m: number) => `Loading from ČÚZK… ${n}/${m} requests done`,
st_loaded: (loc: string, n: number) => `${loc}: ${n} buildings.`,
st_baseFail: (n: number) => `${n} basemap layer(s) failed:`,
st_none: 'No buildings found here (outside Czechia, or an empty area).',
st_badLoc: 'Could not read a location. Paste a Mapy.com link or "50.8171, 14.9687".',
st_err: (e: string) =>
`Could not load data from ČÚZK: ${e}\nThe service may be down, you may be offline, or this page is running somewhere that blocks requests to other sites (some embedded viewers do). Opening the file directly in a browser or hosting it yourself works.`,
st_fallback: (e: string) =>
`Showing the built-in example area (Chrastava centre) because live data could not be loaded: ${e}`,
st_init: 'Loading live data…',
hn: (n: string) => `č.p. ${n}`,
nohn: 'No house number',
i_cat: 'Category',
i_use: 'RÚIAN use',
i_flats: 'Flats',
i_floors: 'Floors',
i_area: 'Built-up area',
i_done: 'Completed',
i_pos: 'Position',
b_water: 'River / water',
b_green: 'Green area / garden',
b_road: 'Main road',
b_street: 'Street',
zoomIn: 'Zoom in',
zoomOut: 'Zoom out',
fit: 'Fit',
close: 'Close',
'cat.res': 'Residential – family house',
'cat.unit': 'Unit housing – apartment building',
'cat.rec': 'Recreational / garden house (chata)',
'cat.mix': 'Mixed – non-residential use + flats',
'cat.civic': 'Public / civic (admin, school, health…)',
'cat.assem': 'Assembly (church, hall, club)',
'cat.shop': 'Commercial – shop',
'cat.hotel': 'Accommodation',
'cat.office': 'Administration / office',
'cat.ind': 'Industrial / production / storage',
'cat.agri': 'Agricultural',
'cat.tech': 'Technical / transport',
'cat.garage': 'Garage',
'cat.other': 'Other / outbuilding / shed',
use: {
1: 'Industrial building',
2: 'Farmstead',
3: 'Dwelling (generic)',
4: 'Forestry building',
5: 'Civic amenity building',
6: 'Apartment building',
7: 'Family house',
8: 'Family recreation building (chata)',
9: 'Assembly building',
10: 'Shop',
11: 'Accommodation building',
12: 'Production & storage',
13: 'Agricultural building',
14: 'Administration building',
15: 'Civic facilities building',
16: 'Technical facilities building',
17: 'Transport building',
18: 'Garage',
19: 'Other building',
20: 'Multi-purpose building',
21: 'Greenhouse',
w: 'Water structures (dams, weirs…)',
0: 'No registered use',
} as Record<string, string>,
}
type Dict = typeof en
export type MsgKey = Exclude<keyof Dict, 'use'>
type Args<K extends MsgKey> = Dict[K] extends (...a: infer P) => string ? P : []
const cs: Dict = {
title: 'Mapa využití budov',
subtitle: 'Česko · budovy z RÚIAN nad silnicemi a vodními toky ZABAGED (ČÚZK)',
locLabel: 'Poloha – odkaz z Mapy.com, „šířka, délka“ nebo „délka, šířka“',
radius: 'Poloměr',
load: 'Načíst oblast',
layers: 'Vrstvy',
display: 'Zobrazení',
colorMode: 'Barevné schéma',
modeSimple: 'Jednoduché – sloučené kategorie',
modeDetailed: 'Podrobné – každý druh využití zvlášť',
mixLabel: 'Pravidlo pro smíšené využití',
mix1: 'Nebytové využití s ≥ 1 bytem',
mix2: 'Nebytové využití s ≥ 2 byty',
mix0: 'Vypnuto',
optBase: 'Silnice, řeky, zeleň',
optNums: 'Čísla popisná při přiblížení',
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.',
nBuildings: (n) => `· ${n} budov`,
st_loading: 'Načítám budovy a podklad z ČÚZK…',
st_progress: (n, m) => `Načítání z ČÚZK… hotovo ${n}/${m} dotazů`,
st_loaded: (loc, n) => `${loc}: ${n} budov.`,
st_baseFail: (n) => `Nepodařilo se načíst vrstev podkladu: ${n}`,
st_none: 'Na tomto místě nejsou žádné budovy (mimo Česko, nebo prázdná oblast).',
st_badLoc: 'Polohu se nepodařilo přečíst. Vložte odkaz z Mapy.com nebo „50.8171, 14.9687“.',
st_err: (e) =>
`Data z ČÚZK se nepodařilo načíst: ${e}\nSlužba může být nedostupná, můžete být offline, nebo stránka běží v prostředí, které blokuje požadavky na jiné weby (některé vestavěné prohlížeče). Otevření souboru přímo v prohlížeči nebo vlastní hosting funguje.`,
st_fallback: (e) =>
`Zobrazen vestavěný příklad (centrum Chrastavy), protože se živá data nepodařilo načíst: ${e}`,
st_init: 'Načítám živá data…',
hn: (n) => `č.p. ${n}`,
nohn: 'Bez čísla popisného',
i_cat: 'Kategorie',
i_use: 'Využití v RÚIAN',
i_flats: 'Byty',
i_floors: 'Podlaží',
i_area: 'Zastavěná plocha',
i_done: 'Dokončeno',
i_pos: 'Poloha',
b_water: 'Řeka / voda',
b_green: 'Zeleň / zahrady',
b_road: 'Silnice',
b_street: 'Ulice',
zoomIn: 'Přiblížit',
zoomOut: 'Oddálit',
fit: 'Celá oblast',
close: 'Zavřít',
'cat.res': 'Bydlení – rodinný dům',
'cat.unit': 'Bytové domy',
'cat.rec': 'Rekreace / zahrádkářské chaty',
'cat.mix': 'Smíšené – nebytové využití + byty',
'cat.civic': 'Veřejné / občanská vybavenost (úřady, školy, zdravotnictví…)',
'cat.assem': 'Shromažďování (kostel, sál, klub)',
'cat.shop': 'Obchod',
'cat.hotel': 'Ubytování',
'cat.office': 'Administrativa / kanceláře',
'cat.ind': 'Průmysl / výroba / sklady',
'cat.agri': 'Zemědělství',
'cat.tech': 'Technické / doprava',
'cat.garage': 'Garáž',
'cat.other': 'Ostatní / hospodářské budovy / kůlny',
use: {
1: 'Průmyslový objekt',
2: 'Zemědělská usedlost',
3: 'Objekt k bydlení',
4: 'Objekt lesního hospodářství',
5: 'Objekt občanské vybavenosti',
6: 'Bytový dům',
7: 'Rodinný dům',
8: 'Stavba pro rodinnou rekreaci',
9: 'Stavba pro shromažďování většího počtu osob',
10: 'Stavba pro obchod',
11: 'Stavba ubytovacího zařízení',
12: 'Stavba pro výrobu a skladování',
13: 'Zemědělská stavba',
14: 'Stavba pro administrativu',
15: 'Stavba občanského vybavení',
16: 'Stavba technického vybavení',
17: 'Stavba pro dopravu',
18: 'Garáž',
19: 'Jiná stavba',
20: 'Víceúčelová stavba',
21: 'Skleník',
w: 'Vodní stavby (přehrady, jezy…)',
0: 'Bez zapsaného využití',
},
}
const L: Record<Lang, Dict> = { en, cs }
function detectLang(): Lang {
let saved: string | null = null
try {
saved = localStorage.getItem('bum-lang')
} catch {}
if (saved === 'cs' || saved === 'en') return saved
const prefs =
navigator.languages && navigator.languages.length
? navigator.languages
: [navigator.language || 'en']
return String(prefs[0] || 'en')
.toLowerCase()
.startsWith('cs')
? 'cs'
: 'en'
}
export let lang: Lang = detectLang()
export function setLang(l: Lang) {
lang = l
try {
localStorage.setItem('bum-lang', l)
} catch {}
}
/** Translate a known message key; function-valued messages take typed arguments. */
export function t<K extends MsgKey>(k: K, ...a: Args<K>): string {
const v = L[lang][k] !== undefined ? L[lang][k] : L.en[k]
return typeof v === 'function' ? (v as (...x: unknown[]) => string)(...a) : (v as string)
}
/** Translate a key built at runtime (e.g. from data-i18n); falls back to the key itself. */
export function tKey(k: string): string {
const get = (d: Dict) => (d as unknown as Record<string, unknown>)[k]
const v = get(L[lang]) !== undefined ? get(L[lang]) : get(L.en)
return typeof v === 'function' ? v() : v === undefined ? k : String(v)
}
export const ruianUseName = (u: number | string): string => L[lang].use[u] || L.en.use[u] || ''

88
src/index.html Normal file
View file

@ -0,0 +1,88 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Building-use map – Czechia (RÚIAN)</title>
<!--
Vite entry page. `bun run dev` for development, `bun run build` writes the minified app to dist/ (serve it as static files).
Data: live queries to the public ČÚZK ArcGIS services (RÚIAN buildings, ZABAGED roads/water/green), © ČÚZK.
A small built-in example area is used as a fallback when the live service cannot be reached.
-->
<link rel="stylesheet" href="./style.css" />
</head>
<body>
<div id="app">
<aside>
<div class="head">
<h1>
<span data-i18n="title">Building-use map</span> <small data-i18n="subtitle"></small>
</h1>
<select id="lang" aria-label="Language">
<option value="cs">CS</option>
<option value="en">EN</option>
</select>
</div>
<label for="loc" data-i18n="locLabel"></label>
<input
id="loc"
type="text"
value="https://mapy.com/en/turisticka?l=0&x=14.9686780&y=50.8171633&z=16.762"
spellcheck="false"
/>
<label for="radius"><span data-i18n="radius"></span> <output id="rv">300 m</output></label>
<input id="radius" type="range" min="100" max="700" step="50" value="300" />
<div class="row"><button id="load" data-i18n="load"></button></div>
<div id="status"></div>
<h2>
<span data-i18n="layers"></span>
<span id="total" style="text-transform: none; letter-spacing: 0"></span>
</h2>
<div id="legend"></div>
<h2 data-i18n="display"></h2>
<label for="colormode" data-i18n="colorMode"></label>
<select id="colormode">
<option value="simple" data-i18n="modeSimple"></option>
<option value="detailed" data-i18n="modeDetailed"></option>
</select>
<label for="mixrule" data-i18n="mixLabel"></label>
<select id="mixrule">
<option value="1" data-i18n="mix1"></option>
<option value="2" data-i18n="mix2"></option>
<option value="0" data-i18n="mix0"></option>
</select>
<label class="chk"
><input type="checkbox" id="optBase" checked /> <span data-i18n="optBase"></span
></label>
<label class="chk"
><input type="checkbox" id="optNums" checked /> <span data-i18n="optNums"></span
></label>
<h2 data-i18n="export"></h2>
<div class="exp">
<button id="expPng" class="ghost">PNG</button>
<button id="expSvg" class="ghost">SVG</button>
<button id="expCsv" class="ghost" data-i18n="csv"></button>
<button id="expPrint" class="ghost" data-i18n="print"></button>
</div>
<p class="note" id="note"></p>
</aside>
<main id="stage">
<canvas id="cv"></canvas>
<div class="zoom">
<button id="zin">+</button><button id="zout">-</button
><button id="zfit" style="font-size: 13px">⤢</button>
</div>
<div id="tip"></div>
<div id="info"></div>
</main>
</div>
<script type="module" src="./main.ts"></script>
</body>
</html>

168
src/interaction.ts Normal file
View file

@ -0,0 +1,168 @@
import { catLabel } from './categories'
import { m2ll } from './geo'
import { t, ruianUseName } from './i18n'
import { draw, fitView } from './render'
import { $, cv, S, vp } from './state'
import type { Building, Point, Ring } from './types'
/* ================= hit testing ================= */
function inRing(x: number, y: number, ring: Ring): boolean {
let inside = false
for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) {
const a = ring[i],
b = ring[j]
if (a[1] > y !== b[1] > y && x < ((b[0] - a[0]) * (y - a[1])) / (b[1] - a[1]) + a[0])
inside = !inside
}
return inside
}
function pick(px: number, py: number): Building | 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
for (let i = S.buildings.length - 1; i >= 0; i--) {
const b = S.buildings[i]
if (
S.hidden.has(b.cat) ||
x < b.bb[0] - pad ||
x > b.bb[2] + pad ||
y < b.bb[1] - pad ||
y > b.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 null
}
/* ================= info panel ================= */
const desc = (b: Building) => `${b.cp ? t('hn', b.cp) : t('nohn')} – ${catLabel(b.cat)}`
export function showInfo(b: Building | null) {
const el = $('info')
if (!b) {
el.style.display = 'none'
return
}
const ll = m2ll((b.bb[0] + b.bb[2]) / 2, (b.bb[1] + b.bb[3]) / 2),
dash = '—'
el.innerHTML = `<span class="x" title="${t('close')}">✕</span><b>${b.cp ? t('hn', b.cp) : t('nohn')}</b>
<dl><dt>${t('i_cat')}</dt><dd>${catLabel(b.cat)}</dd>
<dt>${t('i_use')}</dt><dd>${ruianUseName(b.use) || dash} (${b.use || '?'})</dd>
<dt>${t('i_flats')}</dt><dd>${b.flats == null ? dash : b.flats}</dd>
<dt>${t('i_floors')}</dt><dd>${b.floors == null ? dash : b.floors}</dd>
<dt>${t('i_area')}</dt><dd>${b.area == null ? dash : b.area + ' m²'}</dd>
<dt>${t('i_done')}</dt><dd>${b.year == null ? dash : b.year}</dd>
<dt>${t('i_pos')}</dt><dd>${ll[1].toFixed(6)}, ${ll[0].toFixed(6)}</dd></dl>`
el.style.display = 'block'
el.querySelector<HTMLElement>('.x')!.onclick = () => {
S.sel = null
el.style.display = 'none'
draw()
}
}
/* ================= pan / zoom ================= */
function zoomAt(px: number, py: number, f: number) {
const v = S.view,
ns = Math.min(Math.max(v.s * f, 0.02), 40)
const x = (px - vp.W / 2) / v.s + v.cx,
y = (vp.H / 2 - py) / v.s + v.cy
v.s = ns
v.cx = x - (px - vp.W / 2) / ns
v.cy = y + (py - vp.H / 2) / ns
draw()
}
export function resize() {
const r = $('stage').getBoundingClientRect()
vp.DPR = Math.min(window.devicePixelRatio || 1, 3)
const oldW = vp.W
vp.W = Math.max(1, Math.floor(r.width))
vp.H = Math.max(1, Math.floor(r.height))
cv.width = vp.W * vp.DPR
cv.height = vp.H * vp.DPR
if (S.loaded && !oldW) fitView()
draw()
}
export function initInteraction() {
const ptrs = new Map<number, Point>()
let dragMoved = 0,
lastPinch = 0
const tip = $('tip')
cv.addEventListener('pointerdown', (e) => {
cv.setPointerCapture(e.pointerId)
ptrs.set(e.pointerId, [e.offsetX, e.offsetY])
dragMoved = 0
cv.classList.add('drag')
if (ptrs.size === 2) {
const [a, b] = [...ptrs.values()]
lastPinch = Math.hypot(a[0] - b[0], a[1] - b[1])
}
})
cv.addEventListener('pointermove', (e) => {
const prev = ptrs.get(e.pointerId)
if (prev) {
ptrs.set(e.pointerId, [e.offsetX, e.offsetY])
if (ptrs.size === 1) {
const dx = e.offsetX - prev[0],
dy = e.offsetY - prev[1]
dragMoved += Math.abs(dx) + Math.abs(dy)
S.view.cx -= dx / S.view.s
S.view.cy += dy / S.view.s
draw()
tip.style.display = 'none'
} else if (ptrs.size === 2) {
const [a, b] = [...ptrs.values()],
d = Math.hypot(a[0] - b[0], a[1] - b[1])
if (lastPinch) zoomAt((a[0] + b[0]) / 2, (a[1] + b[1]) / 2, d / lastPinch)
lastPinch = d
dragMoved = 99
}
return
}
const b = pick(e.offsetX, e.offsetY)
if (b) {
tip.textContent = desc(b)
tip.style.left = e.offsetX + 14 + 'px'
tip.style.top = e.offsetY + 14 + 'px'
tip.style.display = 'block'
} else tip.style.display = 'none'
})
const endPtr = (e: PointerEvent) => {
const had = ptrs.delete(e.pointerId)
cv.classList.remove('drag')
lastPinch = 0
if (had && dragMoved < 5 && e.type === 'pointerup') {
S.sel = pick(e.offsetX, e.offsetY)
showInfo(S.sel)
draw()
}
}
cv.addEventListener('pointerup', endPtr)
cv.addEventListener('pointercancel', endPtr)
cv.addEventListener('pointerleave', () => {
tip.style.display = 'none'
})
cv.addEventListener(
'wheel',
(e) => {
e.preventDefault()
zoomAt(e.offsetX, e.offsetY, Math.exp(-e.deltaY * 0.0015))
},
{ passive: false },
)
$('zin').onclick = () => zoomAt(vp.W / 2, vp.H / 2, 1.5)
$('zout').onclick = () => zoomAt(vp.W / 2, vp.H / 2, 1 / 1.5)
$('zfit').onclick = () => {
fitView()
draw()
}
new ResizeObserver(resize).observe($('stage'))
}

20
src/main.ts Normal file
View file

@ -0,0 +1,20 @@
import { applyData, applyLang, initControls, liveLoad, setStatus } from './controls'
import { initExport } from './export'
import { parseLoc } from './geo'
import { t } from './i18n'
import { initInteraction, resize } from './interaction'
import { loadSample } from './sample-data'
import { $ } from './state'
/* ================= start ================= */
initInteraction()
initControls()
initExport()
applyLang()
resize()
// Show the built-in example immediately, then replace it with live data for the default location.
applyData(loadSample(), 14.968678, 50.8171633)
setStatus(() => t('st_init'))
const p = parseLoc($<HTMLInputElement>('loc').value)
if (p) liveLoad(p, true)

223
src/render.ts Normal file
View file

@ -0,0 +1,223 @@
import { BASE } from './basemap'
import { catColor, catLabel, catList, catOrder, isDark, SIMPLE_NUMS } from './categories'
import { t } from './i18n'
import { ctx0, S, vp } from './state'
import type { Ring, View } from './types'
/* ================= view ================= */
export function fitView() {
if (!S.buildings.length) return
let x0 = 1e18,
y0 = 1e18,
x1 = -1e18,
y1 = -1e18
for (const b of S.buildings) {
x0 = Math.min(x0, b.bb[0])
y0 = Math.min(y0, b.bb[1])
x1 = Math.max(x1, b.bb[2])
y1 = Math.max(y1, b.bb[3])
}
const w = Math.max(x1 - x0, 50),
h = Math.max(y1 - y0, 50)
S.view = { cx: (x0 + x1) / 2, cy: (y0 + y1) / 2, s: Math.min(vp.W / w, vp.H / h) * 0.94 }
}
/** Screen px per true metre. */
export const pxPerMeter = (v: View) => v.s / S.K
/* ================= drawing ================= */
function niceScale(v: View) {
for (const m of [5, 10, 20, 50, 100, 200, 500, 1000]) {
const px = m * pxPerMeter(v)
if (px >= 70) return { m, px }
}
return { m: 1000, px: 1000 * pxPerMeter(v) }
}
export function drawScene(
ctx: CanvasRenderingContext2D,
W: number,
H: number,
v: View,
r: number,
opts: { sel?: boolean } = {},
) {
ctx.save()
ctx.setTransform(r, 0, 0, r, 0, 0)
ctx.beginPath()
ctx.rect(0, 0, W, H)
ctx.clip()
ctx.fillStyle = '#f5f2ea'
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)
const path = (rings: Ring[], close: boolean) => {
ctx.beginPath()
for (const ring of rings) {
for (let i = 0; i < ring.length; i++) {
const p = ring[i]
if (i) ctx.lineTo(sx(p[0]), sy(p[1]))
else ctx.moveTo(sx(p[0]), sy(p[1]))
}
if (close) ctx.closePath()
}
}
ctx.lineJoin = 'round'
ctx.lineCap = 'round'
if (S.showBase) {
for (const st of BASE) {
const rings = S.base[st.k]
if (!rings || !rings.length) continue
if (st.t === 'poly') {
path(rings, true)
ctx.fillStyle = st.fill
ctx.fill('evenodd')
if (st.stroke) {
ctx.strokeStyle = st.stroke
ctx.lineWidth = 1
ctx.stroke()
}
} else {
path(rings, false)
ctx.strokeStyle = st.c
ctx.lineWidth = Math.max(st.min, st.m * ppm)
ctx.setLineDash(st.dash ? st.dash.map((d) => d * Math.max(1, ppm / 2)) : [])
ctx.stroke()
ctx.setLineDash([])
}
}
}
for (const key of catOrder()) {
if (S.hidden.has(key)) continue
const rings: Ring[] = []
for (const b of S.buildings) if (b.cat === key) for (const rg of b.rings) rings.push(rg)
if (!rings.length) continue
path(rings, true)
ctx.fillStyle = catColor(key)
ctx.fill('evenodd')
ctx.strokeStyle = key === 'res' || key === 'u7' ? 'rgba(255,255,255,.55)' : 'rgba(0,0,0,.55)'
ctx.lineWidth = 0.5
ctx.stroke()
}
if (S.showNums && ppm >= 1.5) {
const all = ppm >= 3.2
ctx.textAlign = 'center'
ctx.textBaseline = 'middle'
ctx.font = `${Math.min(12, Math.max(8, ppm * 2.2))}px system-ui,sans-serif`
for (const b of S.buildings) {
if (!b.cp || S.hidden.has(b.cat) || !(all || SIMPLE_NUMS[b.sc])) continue
const cx = sx((b.bb[0] + b.bb[2]) / 2),
cy = sy((b.bb[1] + b.bb[3]) / 2)
if (cx < -20 || cy < -20 || cx > W + 20 || cy > H + 20) continue
const dark = isDark(catColor(b.cat)),
txt = b.cp.split(',')[0]
if (!dark) {
ctx.lineWidth = 2.5
ctx.strokeStyle = 'rgba(255,255,255,.8)'
ctx.strokeText(txt, cx, cy)
}
ctx.fillStyle = dark ? '#fff' : '#111'
ctx.fillText(txt, cx, cy)
}
}
if (opts.sel && S.sel) {
path(S.sel.rings, true)
ctx.strokeStyle = '#ffcc00'
ctx.lineWidth = 3
ctx.stroke()
ctx.strokeStyle = '#000'
ctx.lineWidth = 1
ctx.stroke()
}
const sc = niceScale(v),
bx = 16,
by = H - 18
ctx.fillStyle = 'rgba(245,242,234,.85)'
ctx.fillRect(bx - 6, by - 20, sc.px + 12, 30)
ctx.strokeStyle = '#000'
ctx.lineWidth = 2
ctx.beginPath()
ctx.moveTo(bx, by)
ctx.lineTo(bx + sc.px, by)
ctx.stroke()
ctx.fillStyle = '#000'
ctx.font = '11px system-ui,sans-serif'
ctx.textAlign = 'center'
ctx.textBaseline = 'bottom'
ctx.fillText(sc.m >= 1000 ? sc.m / 1000 + ' km' : sc.m + ' m', bx + sc.px / 2, by - 4)
ctx.beginPath()
ctx.moveTo(24, 44)
ctx.lineTo(24, 16)
ctx.moveTo(24, 16)
ctx.lineTo(20, 24)
ctx.moveTo(24, 16)
ctx.lineTo(28, 24)
ctx.lineWidth = 1.5
ctx.stroke()
ctx.textBaseline = 'top'
ctx.fillText('N', 24, 46)
ctx.restore()
}
/* ================= export legend ================= */
interface LegendEntry {
color: string
label: string
border?: string
}
export function counts(): Record<string, number> {
const c: Record<string, number> = {}
for (const b of S.buildings) c[b.cat] = (c[b.cat] || 0) + 1
return c
}
function legendEntries(): LegendEntry[] {
const cnt = counts(),
e: LegendEntry[] = []
for (const k of catList())
if (cnt[k]) e.push({ color: catColor(k), label: `${catLabel(k)} (${cnt[k]})` })
if (S.showBase)
e.push(
{ color: '#a8cfe8', label: t('b_water') },
{ color: '#cfe4bd', label: t('b_green') },
{ color: '#ffe08a', label: t('b_road') },
{ color: '#ffffff', label: t('b_street'), border: '#9a9a9a' },
)
return e
}
export function legendLayout(W: number) {
const e = legendEntries(),
colW = Math.max(240, Math.floor(W / Math.max(1, Math.floor(W / 300))))
const cols = Math.max(1, Math.floor(W / colW)),
rows = Math.ceil(e.length / cols)
return { e, colW, rows, h: rows * 20 + 16 }
}
export function drawLegend(ctx: CanvasRenderingContext2D, y0: number, W: number, r: number) {
const { e, colW, rows, h } = legendLayout(W)
ctx.save()
ctx.setTransform(r, 0, 0, r, 0, 0)
ctx.fillStyle = '#fff'
ctx.fillRect(0, y0, W, h)
ctx.font = '12px system-ui,sans-serif'
ctx.textAlign = 'left'
ctx.textBaseline = 'middle'
e.forEach((it, i) => {
const c = Math.floor(i / rows),
rr = i % rows,
x = 14 + c * colW,
y = y0 + 14 + rr * 20
ctx.fillStyle = it.color
ctx.fillRect(x, y - 6, 18, 12)
ctx.strokeStyle = it.border || '#555'
ctx.lineWidth = 1
ctx.strokeRect(x + 0.5, y - 5.5, 17, 11)
ctx.fillStyle = '#111'
ctx.fillText(it.label, x + 26, y)
})
ctx.restore()
}
/** Redraw the on-screen map. */
export function draw() {
if (vp.W) drawScene(ctx0, vp.W, vp.H, S.view, vp.DPR, { sel: true })
}

View file

@ -1,411 +1,5 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Building-use map – Czechia (RÚIAN)</title>
<!--
Single-file app, no dependencies. Open it locally or host it as a static file.
Data: live queries to the public ČÚZK ArcGIS services (RÚIAN buildings, ZABAGED roads/water/green), © ČÚZK.
A small built-in example area is used as a fallback when the live service cannot be reached.
-->
<style>
:root{--bg:#f5f2ea;--ink:#1d1d1f;--mut:#666;--line:#d8d4c8;--acc:#1f5fbf}
*{box-sizing:border-box}
html,body{height:100%;margin:0}
body{font:14px/1.4 system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;color:var(--ink);background:#fff}
#app{display:grid;grid-template-columns:340px 1fr;height:100%}
aside{overflow:auto;border-right:1px solid var(--line);padding:14px 14px 24px;background:#fbfaf6}
.head{display:flex;gap:8px;align-items:flex-start;justify-content:space-between}
h1{font-size:17px;margin:0 0 2px}
h1 small{display:block;font-weight:400;color:var(--mut);font-size:12px;margin-top:2px}
#lang{width:auto;padding:4px 6px;font-size:12px;flex:none}
h2{font-size:12px;text-transform:uppercase;letter-spacing:.06em;color:var(--mut);margin:18px 0 6px}
label{display:block;font-size:12px;color:var(--mut);margin:10px 0 3px}
input[type=text],select{width:100%;padding:7px 8px;border:1px solid #c9c5b8;border-radius:6px;font:inherit;background:#fff}
input[type=range]{width:100%}
.row{display:flex;gap:8px;margin-top:10px}
button{font:inherit;padding:7px 10px;border-radius:6px;border:1px solid var(--acc);background:var(--acc);color:#fff;cursor:pointer}
button.ghost{background:#fff;color:var(--acc)}
button:disabled{opacity:.5;cursor:default}
.row button{flex:1}
#status{margin-top:10px;font-size:12px;min-height:16px;color:var(--mut);white-space:pre-wrap}
#status.err{color:#b3261e}
#status.ok{color:#1b6e2a}
.leg{display:flex;align-items:center;gap:8px;padding:3px 0;cursor:pointer;user-select:none;color:var(--ink);font-size:14px;margin:0}
.leg input{margin:0}
.sw{width:18px;height:12px;border:1px solid #555;border-radius:2px;flex:none}
.leg .n{margin-left:auto;color:var(--mut);font-variant-numeric:tabular-nums}
.leg.off{opacity:.4}
.chk{display:flex;gap:8px;align-items:center;margin:6px 0;color:var(--ink);font-size:13px}
.chk input{margin:0}
.exp{display:grid;grid-template-columns:1fr 1fr;gap:8px}
.note{font-size:11.5px;color:var(--mut);margin-top:14px}
main{position:relative;min-width:0;min-height:0;background:var(--bg)}
canvas{position:absolute;inset:0;width:100%;height:100%;touch-action:none;cursor:grab}
canvas.drag{cursor:grabbing}
#tip{position:absolute;pointer-events:none;background:rgba(20,20,20,.9);color:#fff;padding:5px 8px;border-radius:5px;font-size:12px;display:none;max-width:260px;z-index:3}
#info{position:absolute;left:12px;bottom:12px;background:#fff;border:1px solid var(--line);border-radius:8px;padding:10px 12px;font-size:13px;max-width:300px;display:none;box-shadow:0 2px 10px rgba(0,0,0,.12);z-index:3}
#info b{font-size:14px}
#info dl{margin:6px 0 0;display:grid;grid-template-columns:auto 1fr;gap:2px 10px}
#info dt{color:var(--mut)}
#info dd{margin:0}
#info .x{position:absolute;top:4px;right:8px;cursor:pointer;color:var(--mut)}
.zoom{position:absolute;right:12px;top:12px;display:flex;flex-direction:column;gap:6px;z-index:3}
.zoom button{width:34px;height:34px;padding:0;background:#fff;color:var(--ink);border:1px solid #bbb;font-size:18px}
@media (max-width:820px){
#app{grid-template-columns:1fr;grid-template-rows:auto 1fr}
aside{max-height:46vh;border-right:0;border-bottom:1px solid var(--line)}
main{min-height:54vh}
}
@media print{
aside,.zoom,#tip,#info{display:none!important}
#app{display:block}
main{height:100vh}
}
</style>
</head>
<body>
<div id="app">
<aside>
<div class="head">
<h1><span data-i18n="title">Building-use map</span> <small data-i18n="subtitle"></small></h1>
<select id="lang" aria-label="Language"><option value="cs">CS</option><option value="en">EN</option></select>
</div>
<label for="loc" data-i18n="locLabel"></label>
<input id="loc" type="text" value="https://mapy.com/en/turisticka?l=0&x=14.9686780&y=50.8171633&z=16.762" spellcheck="false">
<label for="radius"><span data-i18n="radius"></span> <output id="rv">300 m</output></label>
<input id="radius" type="range" min="100" max="700" step="50" value="300">
<div class="row"><button id="load" data-i18n="load"></button></div>
<div id="status"></div>
<h2><span data-i18n="layers"></span> <span id="total" style="text-transform:none;letter-spacing:0"></span></h2>
<div id="legend"></div>
<h2 data-i18n="display"></h2>
<label for="colormode" data-i18n="colorMode"></label>
<select id="colormode">
<option value="simple" data-i18n="modeSimple"></option>
<option value="detailed" data-i18n="modeDetailed"></option>
</select>
<label for="mixrule" data-i18n="mixLabel"></label>
<select id="mixrule">
<option value="1" data-i18n="mix1"></option>
<option value="2" data-i18n="mix2"></option>
<option value="0" data-i18n="mix0"></option>
</select>
<label class="chk"><input type="checkbox" id="optBase" checked> <span data-i18n="optBase"></span></label>
<label class="chk"><input type="checkbox" id="optNums" checked> <span data-i18n="optNums"></span></label>
<h2 data-i18n="export"></h2>
<div class="exp">
<button id="expPng" class="ghost">PNG</button>
<button id="expSvg" class="ghost">SVG</button>
<button id="expCsv" class="ghost" data-i18n="csv"></button>
<button id="expPrint" class="ghost" data-i18n="print"></button>
</div>
<p class="note" id="note"></p>
</aside>
<main id="stage">
<canvas id="cv"></canvas>
<div class="zoom"><button id="zin">+</button><button id="zout">−</button><button id="zfit" style="font-size:13px">⤢</button></div>
<div id="tip"></div>
<div id="info"></div>
</main>
</div>
<script>
(() => {
'use strict';
/* ================= i18n ================= */
const L = {
en: {
title: 'Building-use map',
subtitle: 'Czechia · RÚIAN buildings over ZABAGED roads & rivers (ČÚZK)',
locLabel: 'Location – Mapy.com link, “lat, lon”, or “lon, lat”',
radius: 'Radius', load: 'Load area', layers: 'Layers', display: 'Display',
colorMode: 'Colour scheme', modeSimple: 'Simple – grouped categories', modeDetailed: 'Detailed – one colour per use code',
mixLabel: 'Mixed-use rule', mix1: 'Non-residential use with ≥ 1 flat', mix2: 'Non-residential use with ≥ 2 flats', mix0: 'Off',
optBase: 'Roads, rivers, green areas', optNums: 'House numbers when zoomed in',
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.',
nBuildings: n => `· ${n} buildings`,
st_loading: 'Loading buildings and basemap from ČÚZK…',
st_progress: (n, m) => `Loading from ČÚZK… ${n}/${m} requests done`,
st_loaded: (loc, n) => `${loc}: ${n} buildings.`,
st_baseFail: n => `${n} basemap layer(s) failed:`,
st_none: 'No buildings found here (outside Czechia, or an empty area).',
st_badLoc: 'Could not read a location. Paste a Mapy.com link or "50.8171, 14.9687".',
st_err: e => `Could not load data from ČÚZK: ${e}\nThe service may be down, you may be offline, or this page is running somewhere that blocks requests to other sites (some embedded viewers do). Opening the file directly in a browser or hosting it yourself works.`,
st_fallback: e => `Showing the built-in example area (Chrastava centre) because live data could not be loaded: ${e}`,
st_init: 'Loading live data…',
hn: n => `č.p. ${n}`, nohn: 'No house number',
i_cat: 'Category', i_use: 'RÚIAN use', i_flats: 'Flats', i_floors: 'Floors', i_area: 'Built-up area', i_done: 'Completed', i_pos: 'Position',
b_water: 'River / water', b_green: 'Green area / garden', b_road: 'Main road', b_street: 'Street',
zoomIn: 'Zoom in', zoomOut: 'Zoom out', fit: 'Fit', close: 'Close',
'cat.res': 'Residential – family house', 'cat.unit': 'Unit housing – apartment building',
'cat.rec': 'Recreational / garden house (chata)', 'cat.mix': 'Mixed – non-residential use + flats',
'cat.civic': 'Public / civic (admin, school, health…)', 'cat.assem': 'Assembly (church, hall, club)',
'cat.shop': 'Commercial – shop', 'cat.hotel': 'Accommodation', 'cat.office': 'Administration / office',
'cat.ind': 'Industrial / production / storage', 'cat.agri': 'Agricultural', 'cat.tech': 'Technical / transport',
'cat.garage': 'Garage', 'cat.other': 'Other / outbuilding / shed',
use: { 1:'Industrial building', 2:'Farmstead', 3:'Dwelling (generic)', 4:'Forestry building', 5:'Civic amenity building',
6:'Apartment building', 7:'Family house', 8:'Family recreation building (chata)', 9:'Assembly building',
10:'Shop', 11:'Accommodation building', 12:'Production & storage', 13:'Agricultural building',
14:'Administration building', 15:'Civic facilities building', 16:'Technical facilities building',
17:'Transport building', 18:'Garage', 19:'Other building', 20:'Multi-purpose building', 21:'Greenhouse',
w:'Water structures (dams, weirs…)', 0:'No registered use' },
},
cs: {
title: 'Mapa využití budov',
subtitle: 'Česko · budovy z RÚIAN nad silnicemi a vodními toky ZABAGED (ČÚZK)',
locLabel: 'Poloha – odkaz z Mapy.com, „šířka, délka“ nebo „délka, šířka“',
radius: 'Poloměr', load: 'Načíst oblast', layers: 'Vrstvy', display: 'Zobrazení',
colorMode: 'Barevné schéma', modeSimple: 'Jednoduché – sloučené kategorie', modeDetailed: 'Podrobné – každý druh využití zvlášť',
mixLabel: 'Pravidlo pro smíšené využití', mix1: 'Nebytové využití s ≥ 1 bytem', mix2: 'Nebytové využití s ≥ 2 byty', mix0: 'Vypnuto',
optBase: 'Silnice, řeky, zeleň', optNums: 'Čísla popisná při přiblížení',
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.',
nBuildings: n => `· ${n} budov`,
st_loading: 'Načítám budovy a podklad z ČÚZK…',
st_progress: (n, m) => `Načítání z ČÚZK… hotovo ${n}/${m} dotazů`,
st_loaded: (loc, n) => `${loc}: ${n} budov.`,
st_baseFail: n => `Nepodařilo se načíst vrstev podkladu: ${n}`,
st_none: 'Na tomto místě nejsou žádné budovy (mimo Česko, nebo prázdná oblast).',
st_badLoc: 'Polohu se nepodařilo přečíst. Vložte odkaz z Mapy.com nebo „50.8171, 14.9687“.',
st_err: e => `Data z ČÚZK se nepodařilo načíst: ${e}\nSlužba může být nedostupná, můžete být offline, nebo stránka běží v prostředí, které blokuje požadavky na jiné weby (některé vestavěné prohlížeče). Otevření souboru přímo v prohlížeči nebo vlastní hosting funguje.`,
st_fallback: e => `Zobrazen vestavěný příklad (centrum Chrastavy), protože se živá data nepodařilo načíst: ${e}`,
st_init: 'Načítám živá data…',
hn: n => `č.p. ${n}`, nohn: 'Bez čísla popisného',
i_cat: 'Kategorie', i_use: 'Využití v RÚIAN', i_flats: 'Byty', i_floors: 'Podlaží', i_area: 'Zastavěná plocha', i_done: 'Dokončeno', i_pos: 'Poloha',
b_water: 'Řeka / voda', b_green: 'Zeleň / zahrady', b_road: 'Silnice', b_street: 'Ulice',
zoomIn: 'Přiblížit', zoomOut: 'Oddálit', fit: 'Celá oblast', close: 'Zavřít',
'cat.res': 'Bydlení – rodinný dům', 'cat.unit': 'Bytové domy',
'cat.rec': 'Rekreace / zahrádkářské chaty', 'cat.mix': 'Smíšené – nebytové využití + byty',
'cat.civic': 'Veřejné / občanská vybavenost (úřady, školy, zdravotnictví…)', 'cat.assem': 'Shromažďování (kostel, sál, klub)',
'cat.shop': 'Obchod', 'cat.hotel': 'Ubytování', 'cat.office': 'Administrativa / kanceláře',
'cat.ind': 'Průmysl / výroba / sklady', 'cat.agri': 'Zemědělství', 'cat.tech': 'Technické / doprava',
'cat.garage': 'Garáž', 'cat.other': 'Ostatní / hospodářské budovy / kůlny',
use: { 1:'Průmyslový objekt', 2:'Zemědělská usedlost', 3:'Objekt k bydlení', 4:'Objekt lesního hospodářství',
5:'Objekt občanské vybavenosti', 6:'Bytový dům', 7:'Rodinný dům', 8:'Stavba pro rodinnou rekreaci',
9:'Stavba pro shromažďování většího počtu osob', 10:'Stavba pro obchod', 11:'Stavba ubytovacího zařízení',
12:'Stavba pro výrobu a skladování', 13:'Zemědělská stavba', 14:'Stavba pro administrativu',
15:'Stavba občanského vybavení', 16:'Stavba technického vybavení', 17:'Stavba pro dopravu', 18:'Garáž',
19:'Jiná stavba', 20:'Víceúčelová stavba', 21:'Skleník',
w:'Vodní stavby (přehrady, jezy…)', 0:'Bez zapsaného využití' },
},
};
function detectLang() {
let saved = null;
try { saved = localStorage.getItem('bum-lang'); } catch (e) {}
if (saved === 'cs' || saved === 'en') return saved;
const prefs = (navigator.languages && navigator.languages.length ? navigator.languages : [navigator.language || 'en']);
return String(prefs[0] || 'en').toLowerCase().startsWith('cs') ? 'cs' : 'en';
}
let lang = detectLang();
const t = (k, ...a) => { const v = (L[lang][k] !== undefined ? L[lang][k] : L.en[k]); return typeof v === 'function' ? v(...a) : (v === undefined ? k : v); };
const useName = u => (L[lang].use[u] || L.en.use[u] || '');
/* ================= geometry helpers ================= */
const R = 6378137, D2R = Math.PI / 180;
const m2ll = (x, y) => [x / R / D2R, (2 * Math.atan(Math.exp(y / R)) - Math.PI / 2) / D2R];
/* ================= categories ================= */
// Simple scheme: key, colour, show house number
const SIMPLE = [
['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],
];
const SIMPLE_COLOR = Object.fromEntries(SIMPLE.map(c => [c[0], c[1]]));
const SIMPLE_NUMS = 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 = {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'};
// Detailed scheme: one entry per RÚIAN use code
const DETAIL_COLOR = {
u1:'#7b3294', u2:'#8c564b', u3:'#ff9896', u4:'#556b2f', u5:'#1f5fbf', u6:'#d62728', u7:'#000000', u8:'#2ca02c',
u9:'#4fb3e8', u10:'#e377c2', u11:'#e8c000', u12:'#b39ddb', u13:'#bc8f6f', u14:'#17808a', u15:'#3949ab',
u16:'#4d4d4d', u17:'#7f7f3f', u18:'#d9b77e', u19:'#bdbdbd', u20:'#26c6da', u21:'#a5d6a7', uw:'#607d8b',
u0:'#e3e3e3', mix:'#ff8c00',
};
const DETAIL_ORDER = ['u0', 'uw', 'u19', 'u18', 'u21', 'u20', 'u13', 'u2', 'u4', 'u16', 'u17', 'u12', 'u1', 'u14', 'u10',
'u11', 'u9', 'u15', 'u5', 'u7', 'u6', 'u3', 'u8', 'mix'];
const DETAIL_LIST = ['u7', 'u6', 'u3', 'u8', 'mix', 'u5', 'u15', 'u9', 'u10', 'u11', 'u14', 'u1', 'u12', 'u2', 'u13', 'u4',
'u16', 'u17', 'u18', 'u20', 'u21', 'u19', 'uw', 'u0'];
function simpleKey(use, flats) {
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 (S.mixMin > 0 && f >= S.mixMin && base !== 'garage' && base !== 'agri') return 'mix';
return base;
}
function detailKey(use, sk) {
if (sk === 'mix') return 'mix';
if (use >= 1 && use <= 21) return 'u' + use;
if (use >= 22 && use <= 29) return 'uw';
return 'u0';
}
const catColor = key => (S.mode === 'simple' ? SIMPLE_COLOR[key] : DETAIL_COLOR[key]) || '#bdbdbd';
function catLabel(key) {
if (S.mode === 'simple') return t('cat.' + key);
if (key === 'mix') return t('cat.mix');
if (key === 'uw') return useName('w');
if (key === 'u0') return useName(0);
return key.slice(1) + ' · ' + useName(+key.slice(1));
}
const catList = () => (S.mode === 'simple' ? SIMPLE.map(c => c[0]) : DETAIL_LIST);
const catOrder = () => (S.mode === 'simple' ? SIMPLE_ORDER : DETAIL_ORDER);
function isDark(hex) {
const n = parseInt(hex.slice(1), 16), r = n >> 16, g = (n >> 8) & 255, b = n & 255;
return (0.299 * r + 0.587 * g + 0.114 * b) < 140;
}
/* ================= basemap styles ================= */
const BASE = [
{ k: 'garden', t: 'poly', fill: '#e6efd6' },
{ k: 'green', t: 'poly', fill: '#cfe4bd' },
{ k: 'cemetery', t: 'poly', fill: '#c9d9bd', stroke: '#9bb08a' },
{ k: 'parking', t: 'poly', fill: '#e2e2e2', stroke: '#c4c4c4' },
{ k: 'water', t: 'poly', fill: '#a8cfe8', stroke: '#7fb2d6' },
{ k: 'stream', t: 'line', c: '#7fb2d6', m: 2, min: 1.2 },
{ k: 'path', t: 'line', c: '#b58b5a', m: 1, min: .8, dash: [2, 3] },
{ k: 'track', t: 'line', c: '#c9a16b', m: 2, min: 1, dash: [6, 4] },
{ k: 'rail', t: 'line', c: '#666666', m: 3, min: 1.2, dash: [8, 4] },
{ k: 'street', t: 'line', c: '#9a9a9a', m: 7, min: 2.4 },
{ k: 'street', t: 'line', c: '#ffffff', m: 5, min: 1.8 },
{ k: 'road', t: 'line', c: '#b8862f', m: 11, min: 3.6 },
{ k: 'road', t: 'line', c: '#ffe08a', m: 8.5, min: 2.8 },
];
const ZAB_LAYERS = { road: 79, street: 84, track: 83, path: 82, rail: 75, stream: 93, water: 132,
green: 134, garden: 135, cemetery: 116, parking: 123 };
/* ================= state ================= */
const S = {
buildings: [], base: {}, K: 0.63, center: [14.9687, 50.8172],
view: { cx: 0, cy: 0, s: 1 }, hidden: new Set(), mixMin: 1, mode: 'simple', showBase: true, showNums: true,
sel: null, loaded: false, status: null,
};
const $ = id => document.getElementById(id);
const cv = $('cv'), ctx0 = cv.getContext('2d');
let W = 0, H = 0, DPR = 1;
function classifyAll() {
for (const b of S.buildings) {
b.sc = simpleKey(b.use, b.flats);
b.cat = S.mode === 'simple' ? b.sc : detailKey(b.use, b.sc);
}
}
/* ================= location parsing ================= */
function parseLoc(text) {
text = (text || '').trim();
const m = text.match(/[?&]x=(-?\d+(?:\.\d+)?)/), n = text.match(/[?&]y=(-?\d+(?:\.\d+)?)/);
if (m && n) return { lon: +m[1], lat: +n[1] };
const nums = (text.match(/-?\d+(?:\.\d+)?/g) || []).map(Number);
if (nums.length >= 2) {
const [a, b] = nums;
if (a >= 48 && a <= 52 && b >= 12 && b <= 19) return { lat: a, lon: b };
if (b >= 48 && b <= 52 && a >= 12 && a <= 19) return { lat: b, lon: a };
}
return null;
}
/* ================= fetching from ČÚZK ================= */
const RUIAN = 'https://ags.cuzk.cz/arcgis/rest/services/RUIAN/MapServer/3/query';
const ZAB = 'https://ags.cuzk.cz/arcgis/rest/services/ZABAGED_POLOHOPIS/MapServer/';
async function query(url, fields, env, offset) {
const p = { geometry: env, geometryType: 'esriGeometryEnvelope', inSR: '4326', outSR: '3857',
spatialRel: 'esriSpatialRelIntersects', where: '1=1', outFields: fields, returnGeometry: 'true',
geometryPrecision: '1', maxAllowableOffset: '0.3', f: 'json' };
if (offset) { p.resultOffset = String(offset); p.resultRecordCount = '1000'; }
// No AbortSignal / fetch options: some embedded viewers proxy fetch through postMessage and cannot clone them.
const url2 = url + '?' + new URLSearchParams(p);
let timer;
const timeout = new Promise((_, rej) => { timer = setTimeout(() => rej(new Error('timed out after 45 s')), 45000); });
try {
const res = await Promise.race([fetch(url2), timeout]);
if (!res.ok) throw new Error('HTTP ' + res.status);
const j = await Promise.race([res.json(), timeout]);
if (j.error) throw new Error(j.error.message || 'service error');
return j;
} finally { clearTimeout(timer); }
}
async function queryAll(url, fields, env) {
let out = [], off = 0;
for (let page = 0; page < 12; page++) {
let j;
try { j = await query(url, fields, env, off); }
catch (e) { if (off > 0) break; throw e; }
const f = j.features || [];
out = out.concat(f);
if (!j.exceededTransferLimit || !f.length) break;
off += f.length;
}
return out;
}
const lowerKeys = o => Object.fromEntries(Object.entries(o || {}).map(([k, v]) => [k.toLowerCase(), v]));
const ringsOf = f => (f.geometry && (f.geometry.rings || f.geometry.paths)) || [];
const sleep = ms => new Promise(r => setTimeout(r, ms));
async function pool(tasks, n) { // run async tasks, at most n at a time
const out = new Array(tasks.length); let i = 0;
await Promise.all(Array.from({ length: Math.min(n, tasks.length) }, async () => {
while (i < tasks.length) { const k = i++; try { out[k] = { ok: true, v: await tasks[k]() }; } catch (e) { out[k] = { ok: false, e }; } }
}));
return out;
}
async function baseLayer(id, env) { // retry, then try an explicit field instead of an empty field list
let last;
for (const fields of ['', 'objectid', '']) {
try { return await queryAll(ZAB + id + '/query', fields, env); } catch (e) { last = e; await sleep(500); }
}
throw last;
}
async function fetchArea(lon, lat, radius, onProgress) {
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 keys = Object.keys(ZAB_LAYERS);
const tasks = [() => queryAll(RUIAN, fields, env), ...keys.map(k => () => baseLayer(ZAB_LAYERS[k], env))];
let done = 0;
const res = await pool(tasks.map(fn => async () => { try { return await fn(); } finally { if (onProgress) onProgress(++done, tasks.length); } }), 4);
if (!res[0].ok) throw res[0].e;
const base = {}, fails = [];
keys.forEach((k, i) => {
const r = res[i + 1];
if (r.ok) base[k] = r.v.map(ringsOf).flat();
else { base[k] = []; fails.push(k + ': ' + (r.e && r.e.message ? r.e.message : r.e)); }
});
const buildings = res[0].v.map(f => {
const a = lowerKeys(f.attributes);
return mkBuilding(a.cisladomovni, a.zpusobvyuzitikod, a.pocetbytu, a.pocetpodlazi, a.zastavenaplocha,
a.dokonceni, ringsOf(f));
}).filter(b => b.rings.length);
return { buildings, base, fails };
}
function mkBuilding(cp, use, flats, floors, area, done, rings) {
let x0 = 1e18, y0 = 1e18, x1 = -1e18, y1 = -1e18;
for (const r of rings) for (const p of r) {
if (p[0] < x0) x0 = p[0]; if (p[0] > x1) x1 = p[0];
if (p[1] < y0) y0 = p[1]; if (p[1] > y1) y1 = p[1];
}
const year = (done != null && isFinite(done)) ? new Date(done).getUTCFullYear() : null;
return { cp: (cp || '').toString().trim(), use: use == null ? 0 : +use, flats: flats == null ? null : +flats,
floors: floors == null ? null : +floors, area: area == null ? null : +area, year, rings,
bb: [x0, y0, x1, y1], cat: 'other', sc: 'other' };
}
import { mkBuilding } from './building'
import type { AreaData, BaseData, Ring } from './types'
/* ================= built-in example (offline fallback) ================= */
const SAMPLE_B = String.raw`1665796,6588401
@ -875,7 +469,7 @@ const SAMPLE_B = String.raw`1665796,6588401
47;3;6;4;829,1097 -20,-10 -5,10 -2,-1 -2,4 -10,-5 -3,4 -3,6 -2,4 39,6 8,-18
60;7;1;2;828,849 -8,8 10,11 9,10 8,-7 -1,-1 10,-9 -5,-6 -5,5 -5,-5 0,1 -4,-3 -3,3 -6,-7
56;7;1;2;785,1266 12,2 0,-2 2,-10 0,0 -12,-2 -2,12
53;7;1;2;774,1265 11,1 2,-12 -12,-1 0,0 -1,10 0,2`;
53;7;1;2;774,1265 11,1 2,-12 -12,-1 0,0 -1,10 0,2`
const SAMPLE_BASE = String.raw`#road
568,722 42,-109 106,-196 16,-22 46,-51 7,-10 8,-22 6,-40 9,-39 11,-24 16,-27 67,-76 14,-25 24,-59 11,-46 15,-117 40,-184 99,-157 152,-230 32,-57 47,-105 6,-29 0,-29 -27,-95 -5,-37 5,-28 9,-14 15,-9 66,-21 27,-12 25,-18 19,-18 24,-40 113,-237 19,-32 28,-41 79,-91 27,-35 30,-56 14,-38
93,-20 -25,-18 -16,-7 -30,-5 -21,4 -31,16 -31,23 -62,65
@ -1211,358 +805,47 @@ const SAMPLE_BASE = String.raw`#road
#parking
403,892 5,-8 8,-3 52,4 -2,-18 -50,-5 -2,8 -20,12 9,10
23,80 -21,55 6,2 -9,22 -5,-2 -6,13 -37,-14 -17,46 -1,7 4,5 61,26 21,-5 8,-10 43,-126 -47,-19
1126,625 -93,-61 -13,-16 -15,22 16,0 9,5 -1,10 63,41 28,9 6,-10`;
1126,625 -93,-61 -13,-16 -15,22 16,0 9,5 -1,10 63,41 28,9 6,-10`
function decodeRing(s, ox, oy) {
let px = 0, py = 0; const pts = [];
// Rings are delta-encoded relative to the origin on the first line of SAMPLE_B.
function decodeRing(s: string, ox: number, oy: number): Ring {
let px = 0,
py = 0
const pts: Ring = []
for (const tok of s.split(' ')) {
const [dx, dy] = tok.split(','); px += +dx; py += +dy; pts.push([ox + px, oy + py]);
const [dx, dy] = tok.split(',')
px += +dx
py += +dy
pts.push([ox + px, oy + py])
}
return pts;
return pts
}
function loadSample() {
const lines = SAMPLE_B.trim().split('\n');
const [ox, oy] = lines[0].split(',').map(Number);
const buildings = lines.slice(1).map(l => {
const [cp, use, flats, floors, geom] = l.split(';');
return mkBuilding(cp, +use, flats === '' ? null : +flats, floors === '' ? null : +floors, null, null,
geom.split('|').map(r => decodeRing(r, ox, oy)));
});
const base = {}; let cur = null;
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 [cp, use, flats, floors, geom] = l.split(';')
return mkBuilding(
cp,
+use,
flats === '' ? null : +flats,
floors === '' ? null : +floors,
null,
null,
geom.split('|').map((r) => decodeRing(r, ox, oy)),
)
})
const base: BaseData = {}
let cur: string | null = null
for (const l of SAMPLE_BASE.split('\n')) {
const t2 = l.trim(); if (!t2) continue;
if (t2[0] === '#') { cur = t2.slice(1); base[cur] = []; continue; }
base[cur].push(decodeRing(t2, ox, oy));
const t2 = l.trim()
if (!t2) continue
if (t2[0] === '#') {
cur = t2.slice(1)
base[cur] = []
continue
}
return { buildings, base, fails: [] };
}
/* ================= applying data ================= */
function applyData(d, lon, lat) {
S.buildings = d.buildings; S.base = d.base; S.center = [lon, lat];
S.K = Math.cos(lat * D2R); S.sel = null; $('info').style.display = 'none';
classifyAll(); fitView(); S.loaded = true; S.hidden.clear(); buildLegend(); draw();
}
function fitView() {
if (!S.buildings.length) return;
let x0 = 1e18, y0 = 1e18, x1 = -1e18, y1 = -1e18;
for (const b of S.buildings) { x0 = Math.min(x0, b.bb[0]); y0 = Math.min(y0, b.bb[1]); x1 = Math.max(x1, b.bb[2]); y1 = Math.max(y1, b.bb[3]); }
const w = Math.max(x1 - x0, 50), h = Math.max(y1 - y0, 50);
S.view = { cx: (x0 + x1) / 2, cy: (y0 + y1) / 2, s: Math.min(W / w, H / h) * 0.94 };
}
const pxPerMeter = v => v.s / S.K; // screen px per true metre
/* ================= drawing ================= */
function niceScale(v) {
for (const m of [5, 10, 20, 50, 100, 200, 500, 1000]) { const px = m * pxPerMeter(v); if (px >= 70) return { m, px }; }
return { m: 1000, px: 1000 * pxPerMeter(v) };
}
function drawScene(ctx, W, H, v, r, opts) {
opts = opts || {};
ctx.save();
ctx.setTransform(r, 0, 0, r, 0, 0);
ctx.beginPath(); ctx.rect(0, 0, W, H); ctx.clip();
ctx.fillStyle = '#f5f2ea'; ctx.fillRect(0, 0, W, H);
const sx = x => (x - v.cx) * v.s + W / 2, sy = y => H / 2 - (y - v.cy) * v.s;
const ppm = pxPerMeter(v);
const path = (rings, close) => {
ctx.beginPath();
for (const ring of rings) {
for (let i = 0; i < ring.length; i++) { const p = ring[i]; if (i) ctx.lineTo(sx(p[0]), sy(p[1])); else ctx.moveTo(sx(p[0]), sy(p[1])); }
if (close) ctx.closePath();
if (cur !== null) base[cur].push(decodeRing(t2, ox, oy))
}
};
ctx.lineJoin = 'round'; ctx.lineCap = 'round';
if (S.showBase) {
for (const st of BASE) {
const rings = S.base[st.k]; if (!rings || !rings.length) continue;
if (st.t === 'poly') {
path(rings, true); ctx.fillStyle = st.fill; ctx.fill('evenodd');
if (st.stroke) { ctx.strokeStyle = st.stroke; ctx.lineWidth = 1; ctx.stroke(); }
} else {
path(rings, false); ctx.strokeStyle = st.c; ctx.lineWidth = Math.max(st.min, st.m * ppm);
ctx.setLineDash(st.dash ? st.dash.map(d => d * Math.max(1, ppm / 2)) : []); ctx.stroke(); ctx.setLineDash([]);
}
}
}
for (const key of catOrder()) {
if (S.hidden.has(key)) continue;
const rings = [];
for (const b of S.buildings) if (b.cat === key) for (const rg of b.rings) rings.push(rg);
if (!rings.length) continue;
path(rings, true);
ctx.fillStyle = catColor(key); ctx.fill('evenodd');
ctx.strokeStyle = (key === 'res' || key === 'u7') ? 'rgba(255,255,255,.55)' : 'rgba(0,0,0,.55)'; ctx.lineWidth = .5; ctx.stroke();
}
if (S.showNums && ppm >= 1.5) {
const all = ppm >= 3.2;
ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
ctx.font = `${Math.min(12, Math.max(8, ppm * 2.2))}px system-ui,sans-serif`;
for (const b of S.buildings) {
if (!b.cp || S.hidden.has(b.cat) || !(all || SIMPLE_NUMS[b.sc])) continue;
const cx = sx((b.bb[0] + b.bb[2]) / 2), cy = sy((b.bb[1] + b.bb[3]) / 2);
if (cx < -20 || cy < -20 || cx > W + 20 || cy > H + 20) continue;
const dark = isDark(catColor(b.cat)), txt = b.cp.split(',')[0];
if (!dark) { ctx.lineWidth = 2.5; ctx.strokeStyle = 'rgba(255,255,255,.8)'; ctx.strokeText(txt, cx, cy); }
ctx.fillStyle = dark ? '#fff' : '#111'; ctx.fillText(txt, cx, cy);
}
}
if (opts.sel && S.sel) {
path(S.sel.rings, true); ctx.strokeStyle = '#ffcc00'; ctx.lineWidth = 3; ctx.stroke();
ctx.strokeStyle = '#000'; ctx.lineWidth = 1; ctx.stroke();
}
const sc = niceScale(v), bx = 16, by = H - 18;
ctx.fillStyle = 'rgba(245,242,234,.85)'; ctx.fillRect(bx - 6, by - 20, sc.px + 12, 30);
ctx.strokeStyle = '#000'; ctx.lineWidth = 2; ctx.beginPath(); ctx.moveTo(bx, by); ctx.lineTo(bx + sc.px, by); ctx.stroke();
ctx.fillStyle = '#000'; ctx.font = '11px system-ui,sans-serif'; ctx.textAlign = 'center'; ctx.textBaseline = 'bottom';
ctx.fillText(sc.m >= 1000 ? sc.m / 1000 + ' km' : sc.m + ' m', bx + sc.px / 2, by - 4);
ctx.beginPath(); ctx.moveTo(24, 44); ctx.lineTo(24, 16); ctx.moveTo(24, 16); ctx.lineTo(20, 24); ctx.moveTo(24, 16); ctx.lineTo(28, 24);
ctx.lineWidth = 1.5; ctx.stroke(); ctx.textBaseline = 'top'; ctx.fillText('N', 24, 46);
ctx.restore();
return { buildings, base, fails: [] }
}
function counts() { const c = {}; for (const b of S.buildings) c[b.cat] = (c[b.cat] || 0) + 1; return c; }
function legendEntries() {
const cnt = counts(), e = [];
for (const k of catList()) if (cnt[k]) e.push({ color: catColor(k), label: `${catLabel(k)} (${cnt[k]})` });
if (S.showBase) e.push({ color: '#a8cfe8', label: t('b_water') }, { color: '#cfe4bd', label: t('b_green') },
{ color: '#ffe08a', label: t('b_road') }, { color: '#ffffff', label: t('b_street'), border: '#9a9a9a' });
return e;
}
function legendLayout(W) {
const e = legendEntries(), colW = Math.max(240, Math.floor(W / Math.max(1, Math.floor(W / 300))));
const cols = Math.max(1, Math.floor(W / colW)), rows = Math.ceil(e.length / cols);
return { e, colW, rows, h: rows * 20 + 16 };
}
function drawLegend(ctx, y0, W, r) {
const { e, colW, rows, h } = legendLayout(W);
ctx.save(); ctx.setTransform(r, 0, 0, r, 0, 0);
ctx.fillStyle = '#fff'; ctx.fillRect(0, y0, W, h);
ctx.font = '12px system-ui,sans-serif'; ctx.textAlign = 'left'; ctx.textBaseline = 'middle';
e.forEach((it, i) => {
const c = Math.floor(i / rows), rr = i % rows, x = 14 + c * colW, y = y0 + 14 + rr * 20;
ctx.fillStyle = it.color; ctx.fillRect(x, y - 6, 18, 12);
ctx.strokeStyle = it.border || '#555'; ctx.lineWidth = 1; ctx.strokeRect(x + .5, y - 5.5, 17, 11);
ctx.fillStyle = '#111'; ctx.fillText(it.label, x + 26, y);
});
ctx.restore();
}
function draw() { if (W) drawScene(ctx0, W, H, S.view, DPR, { sel: true }); }
/* ================= sidebar legend ================= */
function buildLegend() {
const box = $('legend'); box.innerHTML = '';
for (const key of catList()) {
const row = document.createElement('label'); row.className = 'leg'; row.dataset.key = key;
row.innerHTML = '<input type="checkbox"><span class="sw"></span><span class="lbl"></span><span class="n">0</span>';
const inp = row.querySelector('input'); inp.checked = !S.hidden.has(key); row.classList.toggle('off', S.hidden.has(key));
row.querySelector('.sw').style.background = catColor(key);
row.querySelector('.lbl').textContent = catLabel(key);
inp.addEventListener('change', e => {
if (e.target.checked) S.hidden.delete(key); else S.hidden.add(key);
row.classList.toggle('off', !e.target.checked); draw();
});
box.appendChild(row);
}
updateCounts();
}
function updateCounts() {
const cnt = counts();
document.querySelectorAll('#legend .leg').forEach(r => {
const n = cnt[r.dataset.key] || 0; r.querySelector('.n').textContent = n; r.style.display = n ? '' : 'none';
});
$('total').textContent = S.buildings.length ? t('nBuildings', S.buildings.length) : '';
}
/* ================= hit testing & interaction ================= */
function inRing(x, y, ring) {
let inside = false;
for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) {
const a = ring[i], b = ring[j];
if ((a[1] > y) !== (b[1] > y) && x < (b[0] - a[0]) * (y - a[1]) / (b[1] - a[1]) + a[0]) inside = !inside;
}
return inside;
}
function pick(px, py) {
const v = S.view, x = (px - W / 2) / v.s + v.cx, y = (H / 2 - py) / v.s + v.cy, pad = 2 / v.s;
for (let i = S.buildings.length - 1; i >= 0; i--) {
const b = S.buildings[i];
if (S.hidden.has(b.cat) || x < b.bb[0] - pad || x > b.bb[2] + pad || y < b.bb[1] - pad || y > b.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 null;
}
const desc = b => `${b.cp ? t('hn', b.cp) : t('nohn')} – ${catLabel(b.cat)}`;
function showInfo(b) {
const el = $('info');
if (!b) { el.style.display = 'none'; return; }
const ll = m2ll((b.bb[0] + b.bb[2]) / 2, (b.bb[1] + b.bb[3]) / 2), dash = '—';
el.innerHTML = `<span class="x" title="${t('close')}">✕</span><b>${b.cp ? t('hn', b.cp) : t('nohn')}</b>
<dl><dt>${t('i_cat')}</dt><dd>${catLabel(b.cat)}</dd>
<dt>${t('i_use')}</dt><dd>${useName(b.use) || dash} (${b.use || '?'})</dd>
<dt>${t('i_flats')}</dt><dd>${b.flats == null ? dash : b.flats}</dd>
<dt>${t('i_floors')}</dt><dd>${b.floors == null ? dash : b.floors}</dd>
<dt>${t('i_area')}</dt><dd>${b.area == null ? dash : b.area + ' m²'}</dd>
<dt>${t('i_done')}</dt><dd>${b.year == null ? dash : b.year}</dd>
<dt>${t('i_pos')}</dt><dd>${ll[1].toFixed(6)}, ${ll[0].toFixed(6)}</dd></dl>`;
el.style.display = 'block';
el.querySelector('.x').onclick = () => { S.sel = null; el.style.display = 'none'; draw(); };
}
const ptrs = new Map(); let dragMoved = 0, lastPinch = 0;
cv.addEventListener('pointerdown', e => {
cv.setPointerCapture(e.pointerId); ptrs.set(e.pointerId, [e.offsetX, e.offsetY]); dragMoved = 0; cv.classList.add('drag');
if (ptrs.size === 2) { const [a, b] = [...ptrs.values()]; lastPinch = Math.hypot(a[0] - b[0], a[1] - b[1]); }
});
cv.addEventListener('pointermove', e => {
const prev = ptrs.get(e.pointerId);
if (prev) {
ptrs.set(e.pointerId, [e.offsetX, e.offsetY]);
if (ptrs.size === 1) {
const dx = e.offsetX - prev[0], dy = e.offsetY - prev[1]; dragMoved += Math.abs(dx) + Math.abs(dy);
S.view.cx -= dx / S.view.s; S.view.cy += dy / S.view.s; draw(); $('tip').style.display = 'none';
} else if (ptrs.size === 2) {
const [a, b] = [...ptrs.values()], d = Math.hypot(a[0] - b[0], a[1] - b[1]);
if (lastPinch) zoomAt((a[0] + b[0]) / 2, (a[1] + b[1]) / 2, d / lastPinch); lastPinch = d; dragMoved = 99;
}
return;
}
const b = pick(e.offsetX, e.offsetY), tip = $('tip');
if (b) { tip.textContent = desc(b); tip.style.left = (e.offsetX + 14) + 'px'; tip.style.top = (e.offsetY + 14) + 'px'; tip.style.display = 'block'; }
else tip.style.display = 'none';
});
const endPtr = e => {
const had = ptrs.delete(e.pointerId); cv.classList.remove('drag'); lastPinch = 0;
if (had && dragMoved < 5 && e.type === 'pointerup') { S.sel = pick(e.offsetX, e.offsetY); showInfo(S.sel); draw(); }
};
cv.addEventListener('pointerup', endPtr); cv.addEventListener('pointercancel', endPtr);
cv.addEventListener('pointerleave', () => { $('tip').style.display = 'none'; });
cv.addEventListener('wheel', e => { e.preventDefault(); zoomAt(e.offsetX, e.offsetY, Math.exp(-e.deltaY * 0.0015)); }, { passive: false });
function zoomAt(px, py, f) {
const v = S.view, ns = Math.min(Math.max(v.s * f, 0.02), 40);
const x = (px - W / 2) / v.s + v.cx, y = (H / 2 - py) / v.s + v.cy;
v.s = ns; v.cx = x - (px - W / 2) / ns; v.cy = y + (py - H / 2) / ns; draw();
}
$('zin').onclick = () => zoomAt(W / 2, H / 2, 1.5);
$('zout').onclick = () => zoomAt(W / 2, H / 2, 1 / 1.5);
$('zfit').onclick = () => { fitView(); draw(); };
function resize() {
const r = $('stage').getBoundingClientRect(); DPR = Math.min(window.devicePixelRatio || 1, 3);
const oldW = W; W = Math.max(1, Math.floor(r.width)); H = Math.max(1, Math.floor(r.height));
cv.width = W * DPR; cv.height = H * DPR;
if (S.loaded && !oldW) fitView();
draw();
}
new ResizeObserver(resize).observe($('stage'));
/* ================= language ================= */
// status is stored as a function so it can be re-rendered when the language changes
function setStatus(fn, cls) { S.status = { fn, cls }; renderStatus(); }
function renderStatus() { const s = $('status'); if (!S.status) { s.textContent = ''; s.className = ''; return; } s.textContent = S.status.fn(); s.className = S.status.cls || ''; }
function applyLang() {
document.documentElement.lang = lang;
document.querySelectorAll('[data-i18n]').forEach(el => { el.textContent = t(el.dataset.i18n); });
$('note').innerHTML = t('note');
$('zin').title = t('zoomIn'); $('zout').title = t('zoomOut'); $('zfit').title = t('fit');
$('lang').value = lang;
document.title = t('title') + ' – RÚIAN';
buildLegend(); renderStatus(); if (S.sel) showInfo(S.sel); draw();
}
$('lang').onchange = e => { lang = e.target.value; try { localStorage.setItem('bum-lang', lang); } catch (x) {} applyLang(); };
/* ================= controls ================= */
$('radius').oninput = e => { $('rv').textContent = e.target.value + ' m'; };
$('optBase').onchange = e => { S.showBase = e.target.checked; draw(); };
$('optNums').onchange = e => { S.showNums = e.target.checked; draw(); };
$('mixrule').onchange = e => { S.mixMin = +e.target.value; classifyAll(); updateCounts(); buildLegend(); draw(); };
$('colormode').onchange = e => { S.mode = e.target.value; S.hidden.clear(); classifyAll(); buildLegend(); draw(); };
async function liveLoad(p, quietFallback) {
const btn = $('load'); btn.disabled = true; setStatus(() => t('st_loading'));
try {
const d = await fetchArea(p.lon, p.lat, +$('radius').value, (n, m) => setStatus(() => t('st_progress', n, m)));
if (!d.buildings.length) { setStatus(() => t('st_none'), 'err'); return false; }
applyData(d, p.lon, p.lat);
const loc = `${p.lat.toFixed(5)}, ${p.lon.toFixed(5)}`, n = d.buildings.length, fails = d.fails;
setStatus(() => t('st_loaded', loc, n) + (fails.length ? '\n' + t('st_baseFail', fails.length) + '\n' + fails.join('\n') : ''),
fails.length ? 'err' : 'ok');
return true;
} catch (e) {
const msg = e && e.message ? e.message : String(e);
setStatus(() => quietFallback ? t('st_fallback', msg) : t('st_err', msg), 'err');
return false;
} finally { btn.disabled = false; }
}
$('load').onclick = () => {
const p = parseLoc($('loc').value);
if (!p) { setStatus(() => t('st_badLoc'), 'err'); return; }
liveLoad(p, false);
};
$('loc').addEventListener('keydown', e => { if (e.key === 'Enter') $('load').click(); });
/* ================= export ================= */
function download(blob, name) {
const a = document.createElement('a'); a.href = URL.createObjectURL(blob); a.download = name;
document.body.appendChild(a); a.click(); a.remove(); setTimeout(() => URL.revokeObjectURL(a.href), 4000);
}
$('expPng').onclick = () => {
if (!S.loaded) return; const r = 2, lh = legendLayout(W).h;
const oc = document.createElement('canvas'); oc.width = W * r; oc.height = (H + lh) * r;
const c = oc.getContext('2d'); drawScene(c, W, H, S.view, r, {}); drawLegend(c, H, W, r);
oc.toBlob(b => download(b, 'building-use-map.png'), 'image/png');
};
$('expSvg').onclick = () => {
if (!S.loaded) return;
const v = S.view, sx = x => ((x - v.cx) * v.s + W / 2).toFixed(1), sy = y => (H / 2 - (y - v.cy) * v.s).toFixed(1), ppm = pxPerMeter(v);
const d = (rings, close) => rings.map(r => 'M' + r.map(p => sx(p[0]) + ' ' + sy(p[1])).join('L') + (close ? 'Z' : '')).join('');
const { e, colW, rows, h: lh } = legendLayout(W); let o = '';
o += `<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${H + lh}" viewBox="0 0 ${W} ${H + lh}"><defs><clipPath id="c"><rect width="${W}" height="${H}"/></clipPath></defs>`;
o += `<rect width="${W}" height="${H}" fill="#f5f2ea"/><g clip-path="url(#c)" stroke-linejoin="round" stroke-linecap="round">`;
if (S.showBase) for (const st of BASE) {
const rings = S.base[st.k]; if (!rings || !rings.length) continue;
if (st.t === 'poly') o += `<path d="${d(rings, true)}" fill="${st.fill}" fill-rule="evenodd"${st.stroke ? ` stroke="${st.stroke}" stroke-width="1"` : ''}/>`;
else o += `<path d="${d(rings, false)}" fill="none" stroke="${st.c}" stroke-width="${Math.max(st.min, st.m * ppm).toFixed(1)}"${st.dash ? ` stroke-dasharray="${st.dash.map(x => x * Math.max(1, ppm / 2)).join(' ')}"` : ''}/>`;
}
for (const key of catOrder()) {
if (S.hidden.has(key)) continue;
const rings = []; for (const b of S.buildings) 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 += '</g>';
o += `<rect y="${H}" width="${W}" height="${lh}" fill="#fff"/><g font-family="system-ui,sans-serif" font-size="12">`;
e.forEach((it, i) => {
const c = Math.floor(i / rows), rr = i % rows, x = 14 + c * colW, y = H + 14 + rr * 20;
o += `<rect x="${x}" y="${y - 6}" width="18" height="12" fill="${it.color}" stroke="${it.border || '#555'}"/><text x="${x + 26}" y="${y + 4}">${it.label.replace(/&/g, '&amp;').replace(/</g, '&lt;')}</text>`;
});
o += '</g></svg>';
download(new Blob([o], { type: 'image/svg+xml' }), 'building-use-map.svg');
};
$('expCsv').onclick = () => {
if (!S.loaded) return;
const q = s => '"' + String(s).replace(/"/g, '""') + '"';
let o = 'house_no,ruian_use_code,ruian_use,category,flats,floors,built_up_area_m2,completed,lat,lon\n';
for (const b of S.buildings) {
const ll = m2ll((b.bb[0] + b.bb[2]) / 2, (b.bb[1] + b.bb[3]) / 2);
o += [q(b.cp), b.use, q(useName(b.use)), q(catLabel(b.cat)), b.flats ?? '', b.floors ?? '', b.area ?? '', b.year ?? '', ll[1].toFixed(6), ll[0].toFixed(6)].join(',') + '\n';
}
download(new Blob(['' + o], { type: 'text/csv;charset=utf-8' }), 'buildings.csv');
};
$('expPrint').onclick = () => window.print();
/* ================= start ================= */
applyLang();
resize();
{ // show the built-in example immediately, then replace it with live data for the default location
const d = loadSample(); applyData(d, 14.968678, 50.8171633);
setStatus(() => t('st_init'));
const p = parseLoc($('loc').value);
if (p) liveLoad(p, true);
}
})();
</script>
</body>
</html>

40
src/sidebar.ts Normal file
View file

@ -0,0 +1,40 @@
import { catColor, catLabel, catList } from './categories'
import { t } from './i18n'
import { counts, draw } from './render'
import { $, S } from './state'
/* ================= sidebar legend ================= */
export function buildLegend() {
const box = $('legend')
box.innerHTML = ''
for (const key of catList()) {
const row = document.createElement('label')
row.className = 'leg'
row.dataset.key = key
row.innerHTML =
'<input type="checkbox"><span class="sw"></span><span class="lbl"></span><span class="n">0</span>'
const inp = row.querySelector('input')!
inp.checked = !S.hidden.has(key)
row.classList.toggle('off', S.hidden.has(key))
row.querySelector<HTMLElement>('.sw')!.style.background = catColor(key)
row.querySelector('.lbl')!.textContent = catLabel(key)
inp.addEventListener('change', () => {
if (inp.checked) S.hidden.delete(key)
else S.hidden.add(key)
row.classList.toggle('off', !inp.checked)
draw()
})
box.appendChild(row)
}
updateCounts()
}
export function updateCounts() {
const cnt = counts()
document.querySelectorAll<HTMLElement>('#legend .leg').forEach((r) => {
const n = cnt[r.dataset.key!] || 0
r.querySelector('.n')!.textContent = String(n)
r.style.display = n ? '' : 'none'
})
$('total').textContent = S.buildings.length ? t('nBuildings', S.buildings.length) : ''
}

31
src/state.ts Normal file
View file

@ -0,0 +1,31 @@
import type { BaseData, Building, Mode, View } from './types'
/* ================= state ================= */
export interface Status {
fn: () => string
cls?: string
}
export const S = {
buildings: [] as Building[],
base: {} as BaseData,
K: 0.63, // cos(latitude): Mercator metres → true metres
center: [14.9687, 50.8172] as [number, number],
view: { cx: 0, cy: 0, s: 1 } as View,
hidden: new Set<string>(),
mixMin: 1,
mode: 'simple' as Mode,
showBase: true,
showNums: true,
sel: null as Building | null,
loaded: false,
status: null as Status | null, // stored as a function so it can be re-rendered on language change
}
/** Canvas size in CSS pixels and the device pixel ratio; updated by resize(). */
export const vp = { W: 0, H: 0, DPR: 1 }
export const $ = <T extends HTMLElement = HTMLElement>(id: string) =>
document.getElementById(id) as T
export const cv = $<HTMLCanvasElement>('cv')
export const ctx0 = cv.getContext('2d')!

287
src/style.css Normal file
View file

@ -0,0 +1,287 @@
:root {
--bg: #f5f2ea;
--ink: #1d1d1f;
--mut: #666;
--line: #d8d4c8;
--acc: #1f5fbf;
}
* {
box-sizing: border-box;
}
html,
body {
height: 100%;
margin: 0;
}
body {
font:
14px/1.4 system-ui,
-apple-system,
'Segoe UI',
Roboto,
sans-serif;
color: var(--ink);
background: #fff;
}
#app {
display: grid;
grid-template-columns: 340px 1fr;
height: 100%;
}
aside {
overflow: auto;
/* break long unspaced text (URLs in error messages) instead of widening the sidebar */
overflow-wrap: anywhere;
border-right: 1px solid var(--line);
padding: 14px 14px 24px;
background: #fbfaf6;
}
.head {
display: flex;
gap: 8px;
align-items: flex-start;
justify-content: space-between;
}
h1 {
font-size: 17px;
margin: 0 0 2px;
}
h1 small {
display: block;
font-weight: 400;
color: var(--mut);
font-size: 12px;
margin-top: 2px;
}
#lang {
width: auto;
padding: 4px 6px;
font-size: 12px;
flex: none;
}
h2 {
font-size: 12px;
text-transform: uppercase;
letter-spacing: 0.06em;
color: var(--mut);
margin: 18px 0 6px;
}
label {
display: block;
font-size: 12px;
color: var(--mut);
margin: 10px 0 3px;
}
input[type='text'],
select {
width: 100%;
padding: 7px 8px;
border: 1px solid #c9c5b8;
border-radius: 6px;
font: inherit;
background: #fff;
}
input[type='range'] {
width: 100%;
/* browsers add a ~2px default margin, which pushed the slider past the sidebar edge */
margin-inline: 0;
}
.row {
display: flex;
gap: 8px;
margin-top: 10px;
}
button {
font: inherit;
padding: 7px 10px;
border-radius: 6px;
border: 1px solid var(--acc);
background: var(--acc);
color: #fff;
cursor: pointer;
}
button.ghost {
background: #fff;
color: var(--acc);
}
button:disabled {
opacity: 0.5;
cursor: default;
}
.row button {
flex: 1;
}
#status {
margin-top: 10px;
font-size: 12px;
min-height: 16px;
color: var(--mut);
white-space: pre-wrap;
}
#status.err {
color: #b3261e;
}
#status.ok {
color: #1b6e2a;
}
.leg {
display: flex;
align-items: center;
gap: 8px;
padding: 3px 0;
cursor: pointer;
user-select: none;
color: var(--ink);
font-size: 14px;
margin: 0;
}
.leg input {
margin: 0;
}
.sw {
width: 18px;
height: 12px;
border: 1px solid #555;
border-radius: 2px;
flex: none;
}
.leg .n {
margin-left: auto;
color: var(--mut);
font-variant-numeric: tabular-nums;
}
.leg.off {
opacity: 0.4;
}
.chk {
display: flex;
gap: 8px;
align-items: center;
margin: 6px 0;
color: var(--ink);
font-size: 13px;
}
.chk input {
margin: 0;
}
.exp {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
.note {
font-size: 11.5px;
color: var(--mut);
margin-top: 14px;
}
main {
position: relative;
min-width: 0;
min-height: 0;
background: var(--bg);
}
canvas {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
canvas.drag {
cursor: grabbing;
}
#tip {
position: absolute;
pointer-events: none;
background: rgba(20, 20, 20, 0.9);
color: #fff;
padding: 5px 8px;
border-radius: 5px;
font-size: 12px;
display: none;
max-width: 260px;
z-index: 3;
}
#info {
position: absolute;
left: 12px;
bottom: 12px;
background: #fff;
border: 1px solid var(--line);
border-radius: 8px;
padding: 10px 12px;
font-size: 13px;
max-width: 300px;
display: none;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.12);
z-index: 3;
}
#info b {
font-size: 14px;
}
#info dl {
margin: 6px 0 0;
display: grid;
grid-template-columns: auto 1fr;
gap: 2px 10px;
}
#info dt {
color: var(--mut);
}
#info dd {
margin: 0;
}
#info .x {
position: absolute;
top: 4px;
right: 8px;
cursor: pointer;
color: var(--mut);
}
.zoom {
position: absolute;
right: 12px;
top: 12px;
display: flex;
flex-direction: column;
gap: 6px;
z-index: 3;
}
.zoom button {
width: 34px;
height: 34px;
padding: 0;
background: #fff;
color: var(--ink);
border: 1px solid #bbb;
font-size: 18px;
}
@media (max-width: 820px) {
#app {
grid-template-columns: 1fr;
grid-template-rows: auto 1fr;
}
aside {
max-height: 46vh;
border-right: 0;
border-bottom: 1px solid var(--line);
}
main {
min-height: 54vh;
}
}
@media print {
aside,
.zoom,
#tip,
#info {
display: none !important;
}
#app {
display: block;
}
main {
height: 100vh;
}
}

40
src/types.ts Normal file
View file

@ -0,0 +1,40 @@
/** Web Mercator (EPSG:3857) coordinates in metres. */
export type Point = [number, number]
export type Ring = Point[]
/** [minX, minY, maxX, maxY] */
export type BBox = [number, number, number, number]
export type Mode = 'simple' | 'detailed'
export interface Building {
cp: string // house number (číslo popisné), may be empty
use: number // RÚIAN use code (způsob využití)
flats: number | null
floors: number | null
area: number | null // built-up area in m²
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
}
/** Basemap geometries keyed by layer name (road, water, …). */
export type BaseData = Record<string, Ring[]>
export interface AreaData {
buildings: Building[]
base: BaseData
fails: string[]
}
export interface View {
cx: number
cy: number
s: number
}
export interface LatLon {
lat: number
lon: number
}

4
src/util.ts Normal file
View file

@ -0,0 +1,4 @@
export const sleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms))
export const errMsg = (e: unknown): string =>
e && (e as Error).message ? (e as Error).message : String(e)

22
tsconfig.json Normal file
View file

@ -0,0 +1,22 @@
{
"compilerOptions": {
"target": "ES2022",
"lib": [
"ES2022",
"DOM",
"DOM.Iterable"
],
"module": "ESNext",
"moduleResolution": "bundler",
"types": [],
"strict": true,
"noEmit": true,
"isolatedModules": true,
"verbatimModuleSyntax": true,
"skipLibCheck": true
},
"include": [
"src",
"vite.config.ts"
]
}

11
vite.config.ts Normal file
View file

@ -0,0 +1,11 @@
import { defineConfig } from 'vite'
export default defineConfig({
root: 'src',
// relative asset URLs so dist/ works from any sub-path
base: './',
build: {
outDir: '../dist',
emptyOutDir: true,
},
})