{
  "version": 3,
  "sources": ["../../../frontend/maps/utils.js", "../../../frontend/maps/popup-values.js", "../../../frontend/maps/photo-marker.js", "../../../frontend/maps/labels.js", "../../../frontend/maps/basemap-look.js", "../../../frontend/maps/state.js", "../../../node_modules/ol/CollectionEventType.js", "../../../node_modules/ol/ObjectEventType.js", "../../../node_modules/ol/obj.js", "../../../node_modules/ol/events.js", "../../../node_modules/ol/events/EventType.js", "../../../node_modules/ol/Disposable.js", "../../../node_modules/ol/array.js", "../../../node_modules/ol/functions.js", "../../../node_modules/ol/events/Event.js", "../../../node_modules/ol/events/Target.js", "../../../node_modules/ol/Observable.js", "../../../node_modules/ol/util.js", "../../../node_modules/ol/Object.js", "../../../node_modules/ol/Collection.js", "../../../node_modules/ol/MapEvent.js", "../../../node_modules/ol/MapBrowserEvent.js", "../../../node_modules/ol/MapBrowserEventType.js", "../../../node_modules/ol/has.js", "../../../node_modules/ol/pointer/EventType.js", "../../../node_modules/ol/MapBrowserEventHandler.js", "../../../node_modules/ol/MapEventType.js", "../../../node_modules/ol/MapProperty.js", "../../../node_modules/ol/TileState.js", "../../../node_modules/ol/asserts.js", "../../../node_modules/ol/structs/PriorityQueue.js", "../../../node_modules/ol/TileQueue.js", "../../../node_modules/ol/ViewHint.js", "../../../node_modules/ol/ViewProperty.js", "../../../node_modules/ol/math.js", "../../../node_modules/ol/centerconstraint.js", "../../../node_modules/ol/extent/Relationship.js", "../../../node_modules/ol/extent.js", "../../../node_modules/ol/string.js", "../../../node_modules/ol/coordinate.js", "../../../node_modules/ol/easing.js", "../../../node_modules/ol/sphere.js", "../../../node_modules/ol/console.js", "../../../node_modules/ol/proj/Units.js", "../../../node_modules/ol/proj/Projection.js", "../../../node_modules/ol/proj/epsg3857.js", "../../../node_modules/ol/proj/epsg4326.js", "../../../node_modules/ol/proj/projections.js", "../../../node_modules/ol/proj/transforms.js", "../../../node_modules/ol/proj/utm.js", "../../../node_modules/ol/proj.js", "../../../node_modules/ol/transform.js", "../../../node_modules/ol/geom/flat/transform.js", "../../../node_modules/ol/geom/Geometry.js", "../../../node_modules/ol/geom/SimpleGeometry.js", "../../../node_modules/ol/geom/flat/area.js", "../../../node_modules/ol/geom/flat/closest.js", "../../../node_modules/ol/geom/flat/deflate.js", "../../../node_modules/ol/geom/flat/inflate.js", "../../../node_modules/ol/geom/flat/simplify.js", "../../../node_modules/ol/geom/LinearRing.js", "../../../node_modules/ol/geom/Point.js", "../../../node_modules/ol/geom/flat/contains.js", "../../../node_modules/ol/geom/flat/interiorpoint.js", "../../../node_modules/ol/geom/flat/segments.js", "../../../node_modules/ol/geom/flat/intersectsextent.js", "../../../node_modules/ol/geom/flat/reverse.js", "../../../node_modules/ol/geom/flat/orient.js", "../../../node_modules/ol/geom/Polygon.js", "../../../node_modules/ol/resolutionconstraint.js", "../../../node_modules/ol/rotationconstraint.js", "../../../node_modules/ol/View.js", "../../../node_modules/ol/css.js", "../../../node_modules/ol/dom.js", "../../../node_modules/ol/control/Control.js", "../../../node_modules/ol/control/Attribution.js", "../../../node_modules/ol/control/Rotate.js", "../../../node_modules/ol/control/Zoom.js", "../../../node_modules/ol/control/defaults.js", "../../../node_modules/ol/Kinetic.js", "../../../node_modules/ol/interaction/Property.js", "../../../node_modules/ol/interaction/Interaction.js", "../../../node_modules/ol/interaction/DoubleClickZoom.js", "../../../node_modules/ol/events/condition.js", "../../../node_modules/ol/interaction/Pointer.js", "../../../node_modules/ol/interaction/DragPan.js", "../../../node_modules/ol/interaction/DragRotate.js", "../../../node_modules/ol/render/Box.js", "../../../node_modules/ol/interaction/DragBox.js", "../../../node_modules/ol/interaction/DragZoom.js", "../../../node_modules/ol/events/Key.js", "../../../node_modules/ol/interaction/KeyboardPan.js", "../../../node_modules/ol/interaction/KeyboardZoom.js", "../../../node_modules/ol/interaction/MouseWheelZoom.js", "../../../node_modules/ol/interaction/PinchRotate.js", "../../../node_modules/ol/interaction/PinchZoom.js", "../../../node_modules/ol/interaction/defaults.js", "../../../node_modules/ol/layer/Property.js", "../../../node_modules/ol/layer/Base.js", "../../../node_modules/ol/layer/Group.js", "../../../node_modules/ol/render/EventType.js", "../../../node_modules/ol/layer/Layer.js", "../../../node_modules/quickselect/index.js", "../../../node_modules/rbush/index.js", "../../../node_modules/ol/color.js", "../../../node_modules/ol/size.js", "../../../node_modules/ol/expr/expression.js", "../../../node_modules/ol/expr/cpu.js", "../../../node_modules/ol/ImageState.js", "../../../node_modules/ol/Image.js", "../../../node_modules/ol/style/IconImageCache.js", "../../../node_modules/ol/style/IconImage.js", "../../../node_modules/ol/colorlike.js", "../../../node_modules/ol/render/canvas.js", "../../../node_modules/ol/style/Image.js", "../../../node_modules/ol/style/RegularShape.js", "../../../node_modules/ol/style/Circle.js", "../../../node_modules/ol/style/Fill.js", "../../../node_modules/ol/style/Icon.js", "../../../node_modules/ol/style/Stroke.js", "../../../node_modules/ol/style/Style.js", "../../../node_modules/ol/style/Text.js", "../../../node_modules/ol/render/canvas/style.js", "../../../node_modules/ol/layer/BaseVector.js", "../../../node_modules/ol/render/Event.js", "../../../node_modules/ol/renderer/Map.js", "../../../node_modules/ol/renderer/Composite.js", "../../../node_modules/ol/Map.js", "../../../node_modules/ol/Tile.js", "../../../node_modules/ol/DataTile.js", "../../../node_modules/ol/ImageTile.js", "../../../node_modules/ol/TileRange.js", "../../../node_modules/ol/reproj.js", "../../../node_modules/ol/reproj/Triangulation.js", "../../../node_modules/ol/reproj/Tile.js", "../../../node_modules/ol/structs/LRUCache.js", "../../../node_modules/ol/tilecoord.js", "../../../node_modules/ol/render/canvas/ZIndexContext.js", "../../../node_modules/ol/renderer/Layer.js", "../../../node_modules/ol/renderer/canvas/Layer.js", "../../../node_modules/ol/renderer/canvas/TileLayer.js", "../../../node_modules/ol/layer/TileProperty.js", "../../../node_modules/ol/layer/BaseTile.js", "../../../node_modules/ol/layer/Tile.js", "../../../node_modules/ol/tilegrid/TileGrid.js", "../../../node_modules/ol/tilegrid/WMTS.js", "../../../node_modules/ol/tilegrid.js", "../../../node_modules/ol/uri.js", "../../../node_modules/ol/tileurlfunction.js", "../../../node_modules/ol/source/Source.js", "../../../node_modules/ol/source/Tile.js", "../../../node_modules/ol/source/TileEventType.js", "../../../node_modules/ol/source/UrlTile.js", "../../../node_modules/ol/source/TileImage.js", "../../../node_modules/ol/source/XYZ.js", "../../../node_modules/ol/source/OSM.js", "../../../node_modules/ol/control/MousePosition.js", "../../../node_modules/ol/Overlay.js", "../../../node_modules/ol/control/ScaleLine.js", "../../../frontend/maps/map.js", "../../../frontend/maps/sample-maps.js", "../../../node_modules/ol/resolution.js", "../../../node_modules/ol/reproj/Image.js", "../../../node_modules/ol/source/Image.js", "../../../node_modules/ol/source/wms.js", "../../../node_modules/ol/source/ImageWMS.js", "../../../node_modules/ol/renderer/canvas/ImageLayer.js", "../../../node_modules/ol/layer/BaseImage.js", "../../../node_modules/ol/layer/Image.js", "../../../frontend/maps/filter.js", "../../../frontend/maps/sld.js", "../../../node_modules/ol/xml.js", "../../../node_modules/ol/format/XML.js", "../../../node_modules/ol/format/xlink.js", "../../../node_modules/ol/format/xsd.js", "../../../node_modules/ol/format/WMSCapabilities.js", "../../../frontend/maps/hybrid.js", "../../../frontend/maps/image-format.js", "../../../frontend/maps/loading.js", "../../../frontend/maps/wms-params.js", "../../../frontend/maps/wms.js", "../../../node_modules/ol/Feature.js", "../../../node_modules/ol/geom/Circle.js", "../../../node_modules/ol/geom/flat/interpolate.js", "../../../node_modules/ol/geom/flat/length.js", "../../../node_modules/ol/geom/LineString.js", "../../../node_modules/ol/geom/MultiLineString.js", "../../../node_modules/ol/geom/MultiPoint.js", "../../../node_modules/ol/geom/flat/center.js", "../../../node_modules/ol/geom/MultiPolygon.js", "../../../node_modules/ol/render/VectorContext.js", "../../../node_modules/ol/render/canvas/Instruction.js", "../../../node_modules/ol/render/canvas/Builder.js", "../../../node_modules/ol/render/canvas/ImageBuilder.js", "../../../node_modules/ol/render/canvas/LineStringBuilder.js", "../../../node_modules/ol/render/canvas/PolygonBuilder.js", "../../../node_modules/ol/geom/flat/linechunk.js", "../../../node_modules/ol/geom/flat/straightchunk.js", "../../../node_modules/ol/render/canvas/TextBuilder.js", "../../../node_modules/ol/render/canvas/BuilderGroup.js", "../../../node_modules/ol/geom/flat/lineoffset.js", "../../../node_modules/ol/geom/flat/textpath.js", "../../../node_modules/ol/render/canvas/Executor.js", "../../../node_modules/ol/render/canvas/ExecutorGroup.js", "../../../node_modules/ol/render/canvas/Immediate.js", "../../../node_modules/ol/render/canvas/hitdetect.js", "../../../node_modules/ol/renderer/vector.js", "../../../node_modules/ol/renderer/canvas/VectorLayer.js", "../../../node_modules/ol/layer/Vector.js", "../../../node_modules/ol/featureloader.js", "../../../node_modules/ol/loadingstrategy.js", "../../../node_modules/ol/render/Feature.js", "../../../node_modules/ol/structs/RBush.js", "../../../node_modules/ol/source/VectorEventType.js", "../../../node_modules/ol/source/Vector.js", "../../../node_modules/ol/geom/GeometryCollection.js", "../../../node_modules/ol/interaction/tracing.js", "../../../node_modules/ol/interaction/Draw.js", "../../../node_modules/ol/interaction/Modify.js", "../../../node_modules/ol/interaction/Select.js", "../../../node_modules/ol/format/Feature.js", "../../../node_modules/ol/format/JSONFeature.js", "../../../node_modules/ol/format/GeoJSON.js", "../../../frontend/maps/notices.js", "../../../frontend/maps/draw.js", "../../../node_modules/ol/source/WMTS.js", "../../../node_modules/ol/format/OWS.js", "../../../node_modules/ol/format/WMTSCapabilities.js", "../../../node_modules/ol/format/TextFeature.js", "../../../node_modules/ol/format/WKT.js", "../../../frontend/maps/external.js", "../../../frontend/maps/describe.js", "../../../frontend/maps/item-layers.js", "../../../frontend/maps/legend.js", "../../../frontend/maps/layers.js", "../../../node_modules/ol/Geolocation.js", "../../../frontend/maps/locate.js", "../../../frontend/maps/advisor.js", "../../../frontend/maps/style-export.js", "../../../frontend/maps/mobile.js", "../../../frontend/maps/properties.js", "../../../frontend/maps/wfs-values.js", "../../../frontend/maps/wfs.js", "../../../frontend/maps/ramps.js", "../../../frontend/maps/classify.js", "../../../frontend/maps/style-ui.js", "../../../frontend/maps/popup-dom.js", "../../../frontend/maps/gallery.js", "../../../node_modules/dompurify/src/utils.ts", "../../../node_modules/dompurify/src/tags.ts", "../../../node_modules/dompurify/src/attrs.ts", "../../../node_modules/dompurify/src/regexp.ts", "../../../node_modules/dompurify/src/purify.ts", "../../../frontend/maps/safe-html.js", "../../../frontend/maps/raster-popup.js", "../../../frontend/maps/identify.js", "../../../frontend/maps/filter-ui.js", "../../../frontend/maps/attr-table.js", "../../../frontend/maps/measure.js", "../../../frontend/maps/export.js", "../../../frontend/maps/present.js", "../../../frontend/maps/render-spec.js", "../../../frontend/maps/persist.js", "../../../frontend/maps/service.js", "../../../frontend/maps/share.js", "../../../frontend/maps/messaging.js", "../../../frontend/maps/items.js", "../../../frontend/uikit/core/http.js", "../../../frontend/uikit/core/errors.js", "../../../frontend/uikit/core/s3upload.js", "../../../frontend/maps/upload-items.js", "../../../frontend/maps/upload.js", "../../../frontend/maps/external-ui.js", "../../../frontend/maps/unsaved.js", "../../../frontend/maps/open-map.js", "../../../frontend/maps/main.js"],
  "sourcesContent": ["/**\n * utils.js \u2014 sd\u00EDlen\u00E9 drobn\u00E9 pom\u016Fcky pro celou mapovou appku.\n *\n * \u017D\u00E1dn\u00E1 z\u00E1vislost na OpenLayers ani na DOM struktu\u0159e \u0161ablony \u2014 \u010Dist\u00E9\n * utility funkce, kter\u00E9 si p\u016Fj\u010Duj\u00ED ostatn\u00ED moduly.\n */\n\n/** Jednoduch\u00FD pub/sub \u201Eevent bus\" pro volnou komunikaci mezi moduly\n * (bez nutnosti si moduly navz\u00E1jem importovat a vytv\u00E1\u0159et cykly). */\nexport const bus = new EventTarget();\n\n/** Vyd\u00E1 ud\u00E1lost `name` s daty `detail` na sd\u00EDlen\u00E9m busu. */\nexport function emit(name, detail) {\n    bus.dispatchEvent(new CustomEvent(name, { detail }));\n}\n\n/** Zaregistruje listener na ud\u00E1lost `name`, vrac\u00ED funkci pro odhl\u00E1\u0161en\u00ED. */\nexport function on(name, handler) {\n    const listener = (event) => handler(event.detail);\n    bus.addEventListener(name, listener);\n    return () => bus.removeEventListener(name, listener);\n}\n\n/** Vr\u00E1t\u00ED hodnotu cookie podle jm\u00E9na (nap\u0159. CSRF token z \u201Ecsrftoken\"). */\nexport function getCookie(name) {\n    const prefix = `${name}=`;\n    const cookie = document.cookie\n        .split(';')\n        .map((part) => part.trim())\n        .find((part) => part.startsWith(prefix));\n    return cookie ? decodeURIComponent(cookie.slice(prefix.length)) : null;\n}\n\n/** Klasick\u00FD debounce \u2014 zavol\u00E1 `fn` a\u017E `wait` ms po posledn\u00EDm vol\u00E1n\u00ED. */\nexport function debounce(fn, wait) {\n    let timer = null;\n    function debounced(...args) {\n        clearTimeout(timer);\n        timer = setTimeout(() => fn.apply(this, args), wait);\n    }\n    debounced.cancel = () => clearTimeout(timer);\n    return debounced;\n}\n\n/** Omez\u00ED hodnotu `value` do rozsahu [min, max]. */\nexport function clamp(value, min, max) {\n    return Math.min(max, Math.max(min, value));\n}\n\n/** Vygeneruje kr\u00E1tk\u00E9 n\u00E1hodn\u00E9 ID (pro runtime kl\u00ED\u010De, cache-busting apod.). */\nexport function shortId() {\n    return Math.random().toString(36).slice(2, 10);\n}\n\n/** Technick\u00FD atribut se stylem prvku (`OGR_STYLE`) \u2014 Mapserver j\u00EDm kresl\u00ED,\n * u\u017Eivateli se mezi atributy (tabulka, filtr, popup, t\u0159\u00EDd\u011Bn\u00ED) neukazuje. */\nexport function isStyleAttribute(name) {\n    return /^ogr_style$/i.test(String(name || ''));\n}\n\n/** Ov\u011B\u0159\u00ED, \u017Ee \u0159et\u011Bzec vypad\u00E1 jako UUID (v4/v jin\u00E9 variant\u011B \u2014 nekontrolujeme verzi). */\nexport function looksLikeUuid(value) {\n    return typeof value === 'string' && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value);\n}\n\n/** fetch() s automatickou CSRF hlavi\u010Dkou pro nebezpe\u010Dn\u00E9 metody a JSON parsov\u00E1n\u00EDm.\n * P\u0159i chybov\u00E9 odpov\u011Bdi vyhod\u00ED Error s textem t\u011Bla (pokud existuje). */\nexport async function apiFetch(url, options = {}) {\n    const method = (options.method || 'GET').toUpperCase();\n    const headers = new Headers(options.headers || {});\n    if (!['GET', 'HEAD', 'OPTIONS', 'TRACE'].includes(method)) {\n        const csrfToken = getCookie('csrftoken');\n        if (csrfToken) {\n            headers.set('X-CSRFToken', csrfToken);\n        }\n    }\n    if (options.body && !headers.has('Content-Type') && typeof options.body === 'string') {\n        headers.set('Content-Type', 'application/json');\n    }\n    const response = await fetch(url, { ...options, headers, credentials: 'same-origin' });\n    if (!response.ok) {\n        let detail = '';\n        try {\n            detail = await response.text();\n        } catch {\n            /* t\u011Blo se nepoda\u0159ilo p\u0159e\u010D\u00EDst \u2014 ignorujeme, hl\u00E1s\u00EDme jen status */\n        }\n        const error = new Error(`${response.status} ${response.statusText}${detail ? `: ${detail}` : ''}`);\n        error.status = response.status;\n        if (response.status === 402) {\n            // Pl\u00E1tce mapy nem\u00E1 kredity (zad\u00E1n\u00ED 06, R14) \u2014 token se neobnov\u00ED;\n            // main.js zobraz\u00ED upozorn\u011Bn\u00ED s odkazem na dobit\u00ED kredit\u016F.\n            try {\n                error.data = JSON.parse(detail);\n            } catch {\n                error.data = null;\n            }\n            if (error.data?.error === 'insufficient_credits') {\n                emit('credits:insufficient', error.data);\n            }\n        }\n        throw error;\n    }\n    if (response.status === 204) {\n        return null;\n    }\n    const contentType = response.headers.get('Content-Type') || '';\n    return contentType.includes('application/json') ? response.json() : response.text();\n}\n\n/** Naform\u00E1tuje WGS84 sou\u0159adnice pro zobrazen\u00ED v li\u0161t\u011B (MousePosition). */\nexport function formatLonLat([lon, lat]) {\n    const fmt = (v) => v.toFixed(5);\n    return `${fmt(lat)}, ${fmt(lon)}`;\n}\n\n/** Slou\u010D\u00ED v\u00EDce extent\u016F [minx,miny,maxx,maxy] do jednoho obalov\u00E9ho. */\nexport function unionExtents(extents) {\n    const valid = extents.filter((e) => Array.isArray(e) && e.length === 4 && e.every(Number.isFinite));\n    if (valid.length === 0) return null;\n    return valid.reduce((acc, e) => [\n        Math.min(acc[0], e[0]),\n        Math.min(acc[1], e[1]),\n        Math.max(acc[2], e[2]),\n        Math.max(acc[3], e[3]),\n    ]);\n}\n", "/**\n * popup-values.js \u2014 co je v atributech prvku (popup identify.js), bez DOM.\n *\n * Rozhoduje, jak se hodnota uk\u00E1\u017Ee: fotka, HTML, odkaz, \u010D\u00EDslo, dlouh\u00FD text,\n * pr\u00E1zdno. Fotky se sb\u00EDraj\u00ED z adres obr\u00E1zk\u016F, z `gx_media_links` (Google My\n * Maps) a z atributu `photos`, kter\u00FD GCZ p\u0159id\u00E1 placemark\u016Fm KMZ s fotkami\n * v archivu (relativn\u00ED cesty, soubory le\u017E\u00ED u meziv\u00FDsledku polo\u017Eky \u2014 popup je\n * na\u010D\u00EDt\u00E1 p\u0159es `\u2026/items/<id>/media/<cesta>`). Funkce jsou \u010Dist\u00E9 kv\u016Fli test\u016Fm\n * (`popup-values.test.mjs`).\n */\n\nconst IMAGE_EXT_RE = /\\.(jpe?g|png|gif|webp|bmp|avif)(?:[?#]|$)/i;\n// Hostitel\u00E9, jejich\u017E adresy obr\u00E1zk\u016F nemaj\u00ED p\u0159\u00EDponu (Google My Maps, Fotky, Disk).\nconst IMAGE_HOST_RE = /^https?:\\/\\/(?:mymaps\\.usercontent\\.google\\.com\\/hostedimage\\/|lh\\d*\\.googleusercontent\\.com\\/|drive\\.google\\.com\\/(?:uc|thumbnail)\\?)/i;\nconst DATA_IMAGE_RE = /^data:image\\/(?:png|jpe?g|gif|webp);base64,[a-z0-9+/=\\s]+$/i;\nconst HTML_RE = /<\\/?(html|body|table|tr|td|th|br|b|i|u|em|strong|dl|dt|dd|div|p|span|img|a|ul|ol|li|font|h[1-6]|hr|center)\\b[^<>]*>/i;\nconst URL_RE = /^https?:\\/\\/[^\\s<>\"]+$/i;\nconst NUMBER_RE = /^-?\\d+(?:[.,]\\d+)?(?:e[+-]?\\d+)?$/i;\n/** Atributy, jejich\u017E hodnota je seznam fotek (mezerou odd\u011Blen\u00E9 adresy/cesty). */\nconst PHOTO_KEY_RE = /^(?:gx_media_links|photos?|photos_kml|pictures?|images?|img|media|fotos?|fotky|foto|fotografie|bilder?|imagen(?:es)?|immagini)(?:_?(?:url|urls|link|links))?$/i;\n/** Atributy s n\u00E1zvem prvku v po\u0159ad\u00ED p\u0159ednosti (bez ohledu na velikost\n * p\u00EDsmen) \u2014 nadpis okna i v\u00FDchoz\u00ED popisek v map\u011B (labels.js). */\nconst NAME_KEYS = ['name', 'label', 'title', 'nazev', 'n\u00E1zev', 'nombre', 'nom', 'nome', 'naam',\n    'navn', 'namn', 'nimi', 'name_en', 'name_int'];\n// Dal\u0161\u00ED atributy, jejich\u017E jm\u00E9no nese \u201Ename\u201C (STREET_NAME, NAME_1, name:en)\u2026\nconst NAME_PART_RE = /(?:^|[_:\\s.-])(?:name|nazev|nombre|nom|nome|naam|navn|namn|nimi)(?:$|[_:\\s.-]|\\d)|name$/i;\n// \u2026ale ne jm\u00E9na soubor\u016F, u\u017Eivatel\u016F, vrstev a podobn\u011B.\nconst NOT_NAME_RE = /file|user|layer|folder|path|style|font|icon|table|field|host|domain|class|type|login|account/i;\n\n/** Text vypad\u00E1 jako HTML (zna\u010Dky, ne jen `<` v textu). */\nexport function looksLikeHtml(text) {\n    return typeof text === 'string' && HTML_RE.test(text);\n}\n\n/** Adresa obr\u00E1zku: http(s) s p\u0159\u00EDponou obr\u00E1zku, zn\u00E1m\u00FD hostitel fotek, `data:image`. */\nexport function isImageUrl(value) {\n    const text = String(value || '').trim();\n    if (DATA_IMAGE_RE.test(text)) return true;\n    if (!URL_RE.test(text)) return false;\n    return IMAGE_EXT_RE.test(text) || IMAGE_HOST_RE.test(text);\n}\n\n/** Relativn\u00ED cesta obr\u00E1zku (fotka z KMZ), jinak null. Nikdy ven z adres\u00E1\u0159e. */\nexport function relativeImagePath(value) {\n    const text = String(value || '').trim();\n    if (!text || /^[a-z][a-z0-9+.-]*:/i.test(text) || text.startsWith('/') || text.startsWith('\\\\') || text.startsWith('#')) return null;\n    if (!IMAGE_EXT_RE.test(text)) return null;\n    let decoded;\n    try {\n        decoded = decodeURIComponent(text);\n    } catch {\n        return null;\n    }\n    if (decoded.split(/[\\\\/]/).some((part) => part === '..')) return null;\n    return text;\n}\n\n/** Je atribut seznamem fotek (`gx_media_links`, `photos`\u2026)? */\nexport function isPhotoKey(key) {\n    return PHOTO_KEY_RE.test(String(key || ''));\n}\n\n/**\n * Fotky hodnoty atributu: `[{src, relative}]`. `src` je adresa (http/https/data)\n * nebo relativn\u00ED cesta (fotka z KMZ \u2014 adresu z n\u00ED slo\u017E\u00ED `mediaUrl`).\n */\nexport function photosOf(key, value) {\n    if (value === null || value === undefined) return [];\n    const text = String(value).trim();\n    if (!text) return [];\n    if (isPhotoKey(key)) {\n        return text.split(/\\s+/).map((token) => {\n            if (isImageUrl(token) || URL_RE.test(token)) return { src: token, relative: false };\n            const path = relativeImagePath(token);\n            return path ? { src: path, relative: true } : null;\n        }).filter(Boolean);\n    }\n    return isImageUrl(text) ? [{ src: text, relative: false }] : [];\n}\n\n/** Nadpis okna: jm\u00E9no prvku (ne HTML, ne p\u0159\u00EDli\u0161 dlouh\u00E9), jinak null. */\n/** Jm\u00E9na z `keys`, kter\u00E1 nesou n\u00E1zev prvku, v po\u0159ad\u00ED p\u0159ednosti. */\nexport function nameKeysOf(keys) {\n    const names = Array.from(keys || []).filter((key) => typeof key === 'string' && key);\n    const exact = NAME_KEYS.flatMap((wanted) => names.filter((key) => key.toLowerCase() === wanted));\n    const partial = names.filter((key) => !exact.includes(key) && NAME_PART_RE.test(key) && !NOT_NAME_RE.test(key));\n    return [...exact, ...partial];\n}\n\nexport function titleOf(properties) {\n    for (const key of nameKeysOf(Object.keys(properties || {}))) {\n        const value = properties?.[key];\n        if (value === null || value === undefined) continue;\n        const text = String(value).trim();\n        if (text && text.length <= 120 && !looksLikeHtml(text)) return { key, text };\n    }\n    return null;\n}\n\n/** Kr\u00E1tk\u00E1 podoba adresy pro zobrazen\u00ED: `example.com/cesta\u2026` (cel\u00E1 z\u016Fst\u00E1v\u00E1 v odkazu). */\nexport function shortUrl(url, max = 42) {\n    let text = String(url || '');\n    try {\n        const parsed = new URL(text);\n        text = parsed.host.replace(/^www\\./, '') + (parsed.pathname === '/' ? '' : parsed.pathname) + parsed.search;\n    } catch {\n        // ponech\u00E1 text, jak je\n    }\n    return text.length > max ? `${text.slice(0, max - 1)}\u2026` : text;\n}\n\n/** Druh hodnoty: `empty` | `photos` | `html` | `url` | `number` | `long` | `text`. */\nexport function kindOf(key, value) {\n    if (value === null || value === undefined) return 'empty';\n    if (typeof value === 'object') return 'text';\n    const text = String(value).trim();\n    if (!text) return 'empty';\n    if (photosOf(key, text).length) return 'photos';\n    if (looksLikeHtml(text)) return 'html';\n    if (URL_RE.test(text)) return 'url';\n    if (typeof value === 'number' || NUMBER_RE.test(text)) return 'number';\n    if (text.length > 160 || text.includes('\\n')) return 'long';\n    return 'text';\n}\n\n/** Text HTML hodnoty bez zna\u010Dek (bez DOM; jen pro porovn\u00E1n\u00ED s ostatn\u00EDmi hodnotami). */\nexport function htmlText(html) {\n    return String(html || '')\n        .replace(/<(script|style|head)\\b[\\s\\S]*?<\\/\\1\\s*>/gi, ' ')\n        .replace(/<[^>]*>/g, ' ')\n        .replace(/&nbsp;/gi, ' ')\n        .replace(/&amp;/gi, '&')\n        .replace(/&lt;/gi, '<')\n        .replace(/&gt;/gi, '>')\n        .replace(/&quot;/gi, '\"')\n        .replace(/&#39;/gi, \"'\")\n        .replace(/\\s+/g, ' ')\n        .trim();\n}\n\n/**\n * Opakuje HTML jen to, co u\u017E je v ostatn\u00EDch atributech? (Tabulka atribut\u016F\n * exportu z GIS, kterou GCZ rozlo\u017Eil do sloupc\u016F.) Pak se v okn\u011B sbal\u00ED.\n */\nexport function repeatsOtherValues(html, otherValues) {\n    const words = htmlText(html).toLowerCase().match(/[\\p{L}\\p{N}]+/gu) || [];\n    if (!words.length) return true;\n    // (`<Null>` of a GIS export is an empty value)\n    const known = new Set(['null']);\n    for (const value of otherValues) {\n        if (value === null || value === undefined) continue;\n        for (const word of String(value).toLowerCase().match(/[\\p{L}\\p{N}]+/gu) || []) known.add(word);\n    }\n    const missing = words.filter((word) => !known.has(word));\n    return missing.length <= Math.max(1, Math.floor(words.length * 0.1));\n}\n\n/**\n * \u0160\u00ED\u0159ka okna podle obsahu (rem): kr\u00E1tk\u00E9 hodnoty 18, del\u0161\u00ED texty 22, HTML nebo\n * fotky 26, \u0161irok\u00E9 tabulky v HTML 30. U\u017Eivatel ji pak m\u016F\u017Ee ta\u017Een\u00EDm zm\u011Bnit.\n */\nexport function popupWidth({ longest = 0, count = 0, html = false, wideHtml = false, photos = 0 } = {}) {\n    if (wideHtml) return 30;\n    if (html || photos) return 26;\n    if (longest > 60 || count > 14) return 22;\n    return 18;\n}\n\n/** Adresa fotky z KMZ polo\u017Eky (stejn\u00E1 cesta jako WMS payload, viz wms.js). */\nexport function mediaUrl(bootstrap, itemId, mapId, path) {\n    const encoded = String(path).split('/').map((part) => encodeURIComponent(decodeURIComponentSafe(part))).join('/');\n    if (bootstrap?.sharedView) return `${bootstrap.sharedView.wmsBase}${itemId}/media/${encoded}`;\n    const base = `${bootstrap?.apiBase || ''}/items/${itemId}/media/${encoded}`;\n    return mapId ? `${base}?map=${encodeURIComponent(mapId)}` : base;\n}\n\nfunction decodeURIComponentSafe(text) {\n    try {\n        return decodeURIComponent(text);\n    } catch {\n        return text;\n    }\n}\n", "/**\n * photo-marker.js \u2014 bodov\u00FD symbol \u201ECamera\u201C pro prvky s fotkami.\n *\n * Body z KMZ s fotkami (atribut `photos`, kter\u00FD p\u0159id\u00E1 GCZ), z Google My Maps\n * (`gx_media_links`) nebo z dat s adresami fotek maj\u00ED fotky v popupu. V map\u011B\n * je uk\u00E1\u017Ee symbol fotoapar\u00E1tu: krou\u017Eek v barv\u011B v\u00FDpln\u011B, v n\u011Bm fotoapar\u00E1t\n * v barv\u011B obrysu a objektiv v barv\u011B v\u00FDpln\u011B. Prvky vrstvy bez fotky (pr\u00E1zdn\u00E1\n * hodnota atributu) dostanou oby\u010Dejnou te\u010Dku \u2014 gener\u00E1tor SLD pravidlo\n * rozd\u011Bl\u00ED podle atributu s fotkami.\n *\n * Mapserver zn\u00E1 fotoapar\u00E1t jako SLD WellKnownName \u201Ephoto\u201C (symbol `photo`\n * v `conf/symbols.sym` GCZ); `CAMERA_POINTS` jsou jeho body pro legendu.\n * Funkce jsou \u010Dist\u00E9 kv\u016Fli test\u016Fm (`photo-marker.test.mjs`).\n */\nimport { isPhotoKey } from './popup-values.js';\n\n/** Hodnota `rules.point.symbol` pro fotoapar\u00E1t. */\nexport const PHOTO_SYMBOL = 'photo';\n/** V\u00FDchoz\u00ED velikost (pr\u016Fm\u011Br krou\u017Eku v px) \u2014 te\u010Dka m\u00E1 8, fotoapar\u00E1t je v\u011Bt\u0161\u00ED. */\nexport const PHOTO_SIZE = 20;\n/** Velikost, pod kterou se fotoapar\u00E1t v krou\u017Eku ztr\u00E1c\u00ED (volba symbolu ji zv\u011Bt\u0161\u00ED). */\nexport const PHOTO_MIN_SIZE = 14;\n\n/** V\u00FD\u0161ka fotoapar\u00E1tu a objektivu v\u016F\u010Di pr\u016Fm\u011Bru krou\u017Eku. */\nconst CAMERA_RATIO = 0.45;\nconst LENS_RATIO = 0.2;\n\n/** Obrys fotoapar\u00E1tu (x 0\u20131, y 0\u20130,88 dol\u016F) jako v `symbols.sym` GCZ;\n * kotva (st\u0159ed objektivu) le\u017E\u00ED na 0,5 \u00D7 0,57 v\u00FD\u0161ky. */\nexport const CAMERA_POINTS = [\n    [0, 0.18], [0.05, 0.12], [0.30, 0.12], [0.38, 0], [0.62, 0], [0.70, 0.12],\n    [0.95, 0.12], [1, 0.18], [1, 0.82], [0.95, 0.88], [0.05, 0.88], [0, 0.82],\n];\nconst CAMERA_HEIGHT = 0.88;\nconst CAMERA_ANCHOR = [0.5, 0.57 * CAMERA_HEIGHT];\n\n/** Atributy s fotkami v po\u0159ad\u00ED p\u0159ednosti: GCZ, jeho n\u00E1hradn\u00ED jm\u00E9no, My Maps. */\nconst PREFERRED_FIELDS = ['photos', 'photos_kml', 'gx_media_links'];\n\n/** Atribut podvrstvy, kter\u00FD nese fotky prvku (`[{name, type}]`), nebo null. */\nexport function photoFieldOf(attributes) {\n    const names = (attributes || [])\n        .filter((a) => a?.name && (!a.type || /str|text|char/i.test(String(a.type))))\n        .map((a) => a.name);\n    return PREFERRED_FIELDS.find((name) => names.includes(name))\n        || names.find((name) => isPhotoKey(name))\n        || null;\n}\n\n/** \u010C\u00E1sti symbolu pro dan\u00FD pr\u016Fm\u011Br: krou\u017Eek, fotoapar\u00E1t, objektiv (px). */\nexport function photoMarkerSizes(size) {\n    const ring = Number(size) || PHOTO_SIZE;\n    const round = (value) => Math.round(value * 10) / 10;\n    return { ring, camera: round(ring * CAMERA_RATIO), lens: round(ring * LENS_RATIO) };\n}\n\n/** Pr\u016Fm\u011Br te\u010Dky prvku bez fotky vedle fotoapar\u00E1tu dan\u00E9 velikosti. */\nexport function plainDotSize(size) {\n    return Math.max(4, Math.round((Number(size) || PHOTO_SIZE) * 0.4));\n}\n\n/** SVG `points` fotoapar\u00E1tu v\u00FD\u0161ky `height` s objektivem v (cx, cy). */\nexport function cameraPolygonPoints(cx, cy, height) {\n    const scale = height / CAMERA_HEIGHT;\n    return CAMERA_POINTS\n        .map(([x, y]) => `${(cx + (x - CAMERA_ANCHOR[0]) * scale).toFixed(1)},${(cy + (y - CAMERA_ANCHOR[1]) * scale).toFixed(1)}`)\n        .join(' ');\n}\n\n/** Skupina geometrie jako `normalizeGeometryType` ve state.js (bez importu \u2014\n * state.js importuje tento modul). */\nfunction geometryGroup(geometryType) {\n    const t = String(geometryType || '').toLowerCase();\n    if (t.includes('point')) return 'point';\n    if (t.includes('line')) return 'line';\n    if (t.includes('polygon')) return 'polygon';\n    return 'point';\n}\n\n/** N\u00E1vrh stylu popsal styl z dat cel\u00FD: ka\u017Ed\u00E1 geometrie vrstvy m\u00E1 n\u00E1vrh ze\n * stylu dat (`reason: feature-styles`) a u sm\u00ED\u0161en\u00E9 vrstvy jsou v\u0161echny\n * jednoduch\u00E9 \u2014 kategorie jedn\u00E9 geometrie by jinak p\u0159ebarvily ostatn\u00ED. */\nfunction suggestionDescribesNative(sublayers, suggested) {\n    const fromData = (suggested || []).filter((s) => s?.suggested?.reason === 'feature-styles');\n    const groups = new Set(sublayers.flatMap((sub) => (sub.geometry_types || []).map(geometryGroup)));\n    if (!groups.size || ![...groups].every((group) => fromData.some((s) => s.geometry === group))) return false;\n    return groups.size === 1 || fromData.every((s) => s.suggested.kind === 'simple');\n}\n\n/**\n * V\u00FDchoz\u00ED styl nov\u00E9 vrstvy s fotkami: body dostanou fotoapar\u00E1t.\n *\n * Uprav\u00ED `style` (v\u00FDsledek `styleFromSuggestions`, p\u0159\u00EDpadn\u011B s re\u017Eimem\n * `native`) na m\u00EDst\u011B a vr\u00E1t\u00ED ho. Plat\u00ED jen pro vrstvu s body a s atributem\n * fotek. Styl z dat (`native`) se nahrad\u00ED jen tehdy, kdy\u017E ho n\u00E1vrh stylu\n * popsal cel\u00FD (`suggestionDescribesNative`) \u2014 barvy ikon a \u010Dar z KML se tak\n * zachovaj\u00ED; jinak styl z dat z\u016Fst\u00E1v\u00E1.\n */\nexport function applyPhotoMarker(style, sublayers, suggested) {\n    if (!style || !style.rules?.point) return style;\n    const subs = sublayers || [];\n    const pointSubs = subs.filter((sub) => (sub.geometry_types || []).some((g) => geometryGroup(g) === 'point'));\n    if (!pointSubs.some((sub) => photoFieldOf(sub.attributes))) return style;\n    if (style.mode === 'native') {\n        if (!suggestionDescribesNative(subs, suggested)) return style;\n        style.mode = style.categorized?.attribute && style.categorized.categories?.length ? 'categorized' : 'simple';\n    }\n    style.rules.point = { ...style.rules.point, symbol: PHOTO_SYMBOL, size: PHOTO_SIZE };\n    // Velikosti kategori\u00ED pat\u0159ily te\u010Dk\u00E1m (m\u011B\u0159\u00EDtko ikony KML) \u2014 fotoapar\u00E1t m\u00E1 jednu.\n    (style.categorized?.categories || []).forEach((category) => { delete category.size; });\n    if (style.categorized?.other) delete style.categorized.other.size;\n    return style;\n}\n", "/**\n * labels.js \u2014 popisky vektorov\u00E9 vrstvy: model `style.labels`, v\u00FDchoz\u00ED popisky\n * nov\u00E9 vrstvy, p\u0159ibl\u00ED\u017Een\u00ED, od kter\u00E9ho se ukazuj\u00ED, a `<TextSymbolizer>` SLD.\n *\n * Model (`style.labels`):\n * - `enabled`, `attribute`, `size`, `color`, `halo`, `bold`,\n * - `position` \u2014 popisek bodu: `auto` (mapov\u00E1 slu\u017Eba vybere voln\u00E9 m\u00EDsto kolem\n *   bodu) nebo m\u00EDsto v m\u0159\u00ED\u017Ece 3 \u00D7 3 (`tl` \u2026 `br`, `c` = p\u0159es bod),\n * - `rotation` \u2014 nato\u010Den\u00ED popisku bodu: `{mode: none|angle|field, angle,\n *   field, clockwise}`; \u00FAhel ve stupn\u00EDch po sm\u011Bru hodinov\u00FDch ru\u010Di\u010Dek,\n *   u atributu vol\u00ED `clockwise` sm\u011Br hodnot,\n * - `line` \u2014 popisek linie: `horizontal`, `along` (rovn\u011B pod\u00E9l linie),\n *   `follow` (po k\u0159ivce); `repeat` = opakovat na dlouh\u00FDch lini\u00EDch,\n * - `fit` \u2014 popisek linie a plochy jen tam, kde se vejde,\n * - `minZoom` \u2014 od kter\u00E9ho p\u0159ibl\u00ED\u017Een\u00ED: `auto` (podle hustoty dat,\n *   `autoLabelMinZoom`), \u010D\u00EDslo, `null` = v\u017Edy.\n *\n * Mapov\u00E1 slu\u017Eba GCZ zn\u00E1 nav\u00EDc volby `<VendorOption>` (labelPosition,\n * lineLabel, repeat, fitInside, labelMinZoom) a d\u00E1v\u00E1 popisk\u016Fm z\u00E1lo\u017En\u00ED p\u00EDsma\n * pro \u010D\u00EDn\u0161tinu, hind\u0161tinu a dal\u0161\u00ED p\u00EDsma. MapServer \u010Dte `AnchorPoint` jako\n * \u201Ekde popisek le\u017E\u00ED\u201C (x 0 vlevo, 1 vpravo; y 0 pod bodem, 1 nad n\u00EDm)\n * a `Displacement` jako posun od bodu t\u00EDm sm\u011Brem; `Rotation` je proti sm\u011Bru\n * hodinov\u00FDch ru\u010Di\u010Dek.\n *\n * Funkce jsou \u010Dist\u00E9 kv\u016Fli test\u016Fm (`labels.test.mjs`).\n */\nimport { nameKeysOf } from './popup-values.js';\n\n/** M\u00EDsta popisku bodu v m\u0159\u00ED\u017Ece (\u0159\u00E1dky shora). */\nexport const LABEL_POSITIONS = ['tl', 't', 'tr', 'l', 'c', 'r', 'bl', 'b', 'br'];\nconst ANCHORS = {\n    tl: [0, 1], t: [0.5, 1], tr: [1, 1],\n    l: [0, 0.5], c: [0.5, 0.5], r: [1, 0.5],\n    bl: [0, 0], b: [0.5, 0], br: [1, 0],\n};\nexport const LINE_LABEL_MODES = ['horizontal', 'along', 'follow'];\n/** Vzd\u00E1lenost opakovan\u00FDch popisk\u016F na dlouh\u00E9 linii (px). */\nexport const REPEAT_DISTANCE = 300;\n\n/** Rozli\u0161en\u00ED webov\u00E9 mapy v p\u0159ibl\u00ED\u017Een\u00ED 0 (m/px). */\nconst ZOOM0_RESOLUTION = 156543.03392804097;\nconst METRES_PER_DEGREE = 111319.49079327357;\n/** Plocha jednoho popisku (px\u00B2) a pod\u00EDl mapy, kter\u00FD popisky sm\u011Bj\u00ED pokr\u00FDt. */\nconst LABEL_AREA = 1600;\nconst LABEL_COVER = 0.2;\n/** Do kolika prvk\u016F se popisky ukazuj\u00ED v\u017Edy. */\nconst ALWAYS_UP_TO = 30;\n/** P\u0159ibl\u00ED\u017Een\u00ED, kdy\u017E po\u010Det prvk\u016F nebo rozsah vrstvy chyb\u00ED. */\nconst UNKNOWN_DENSITY_ZOOM = 14;\n\nexport function defaultLabels() {\n    return {\n        enabled: false,\n        attribute: null,\n        size: 11,\n        color: '#333333',\n        halo: '#ffffff',\n        bold: false,\n        position: 'auto',\n        rotation: { mode: 'none', angle: 0, field: null, clockwise: true },\n        line: 'follow',\n        repeat: false,\n        fit: true,\n        minZoom: 'auto',\n    };\n}\n\n/** Popisky ulo\u017Een\u00E9 d\u0159\u00EDv, ne\u017E \u0161lo volit um\u00EDst\u011Bn\u00ED: popisek p\u0159es bod, rovn\u011B\n * pod\u00E9l linie, v\u017Edy \u2014 mapa vypad\u00E1 jako d\u0159\u00EDv. */\nconst LEGACY_PLACEMENT = { position: 'c', line: 'along', repeat: false, fit: false, minZoom: null };\n\n/** Dopln\u00ED chyb\u011Bj\u00EDc\u00ED kl\u00ED\u010De popisk\u016F (star\u0161\u00ED ulo\u017Een\u00E9 mapy, viz LEGACY_PLACEMENT). */\nexport function normalizeLabels(labels) {\n    const defaults = defaultLabels();\n    if (!labels) return defaults;\n    const legacy = labels.position === undefined ? LEGACY_PLACEMENT : {};\n    const out = {\n        ...defaults, ...legacy, ...labels,\n        rotation: { ...defaults.rotation, ...labels.rotation },\n    };\n    if (out.position !== 'auto' && !LABEL_POSITIONS.includes(out.position)) out.position = 'auto';\n    if (!LINE_LABEL_MODES.includes(out.line)) out.line = 'follow';\n    if (!(out.minZoom === 'auto' || out.minZoom === null || Number.isFinite(out.minZoom))) out.minZoom = 'auto';\n    return out;\n}\n\nconst isText = (attribute) => !attribute.type || /str|text|char/i.test(String(attribute.type));\n\n/** Atribut s n\u00E1zvem prvku pro v\u00FDchoz\u00ED popisek (textov\u00FD, podle `nameKeysOf`). */\nexport function labelFieldOf(sublayers) {\n    const names = (sublayers || []).flatMap((sub) => (sub.attributes || []).filter(isText).map((a) => a.name));\n    return nameKeysOf(new Set(names))[0] || null;\n}\n\n/** V\u00FDchoz\u00ED popisky nov\u00E9 vrstvy: atribut s n\u00E1zvem prvku, kdy\u017E vrstva n\u011Bjak\u00FD\n * m\u00E1 a popisky je\u0161t\u011B nem\u00E1. Styl z dat (`native`) si popisky nese s\u00E1m. */\nexport function applyDefaultLabels(style, sublayers) {\n    if (!style?.labels || style.mode === 'native' || style.labels.enabled) return style;\n    const field = labelFieldOf(sublayers);\n    if (field) style.labels = { ...style.labels, enabled: true, attribute: field };\n    return style;\n}\n\nfunction mercatorY(lat) {\n    const clamped = Math.max(-85.05, Math.min(85.05, lat));\n    return Math.log(Math.tan(Math.PI / 4 + (clamped * Math.PI) / 360)) * 6378137;\n}\n\n/**\n * P\u0159ibl\u00ED\u017Een\u00ED, od kter\u00E9ho popisky pokryj\u00ED nejv\u00FD\u0161 p\u011Btinu mapy, kdyby byly\n * prvky vrstvy rozlo\u017Een\u00E9 rovnom\u011Brn\u011B (`count` prvk\u016F v `bbox` WGS 84).\n * `null` = v\u017Edy (m\u00E1lo prvk\u016F).\n */\nexport function autoLabelMinZoom(count, bbox) {\n    if (!Number.isFinite(count)) return UNKNOWN_DENSITY_ZOOM;\n    if (count <= ALWAYS_UP_TO) return null;\n    if (!Array.isArray(bbox) || bbox.length !== 4 || !bbox.every(Number.isFinite)) return UNKNOWN_DENSITY_ZOOM;\n    const dx = Math.max((bbox[2] - bbox[0]) * METRES_PER_DEGREE, 1);\n    const dy = Math.max(mercatorY(bbox[3]) - mercatorY(bbox[1]), 1);\n    // Data pod\u00E9l \u00FAzk\u00E9ho pruhu (silnice, veden\u00ED) nezab\u00EDraj\u00ED cel\u00FD obd\u00E9ln\u00EDk.\n    const area = Math.max(dx * dy, Math.max(dx, dy) ** 2 * 0.02);\n    const resolution = Math.sqrt((area * LABEL_COVER) / (count * LABEL_AREA));\n    const zoom = Math.round(Math.log2(ZOOM0_RESOLUTION / resolution));\n    return zoom <= 0 ? null : Math.min(20, zoom);\n}\n\n/** Po\u010Det prvk\u016F vrstvy (sou\u010Det podvrstev, `null` = nezn\u00E1m\u00FD). */\nfunction featureCount(entry) {\n    const counts = (entry.sublayers || []).map((sub) => sub.feature_count);\n    return counts.length && counts.every(Number.isFinite) ? counts.reduce((a, b) => a + b, 0) : null;\n}\n\n/** P\u0159ibl\u00ED\u017Een\u00ED \u201EAuto\u201C dan\u00E9 vrstvy (`null` = v\u017Edy). */\nexport function entryAutoLabelMinZoom(entry) {\n    return autoLabelMinZoom(featureCount(entry), entry?.bbox);\n}\n\n/** P\u0159ibl\u00ED\u017Een\u00ED, od kter\u00E9ho se popisky vrstvy ukazuj\u00ED (`null` = v\u017Edy). */\nexport function labelMinZoom(entry) {\n    const value = entry?.style?.labels?.minZoom;\n    if (value === 'auto') return entryAutoLabelMinZoom(entry);\n    return Number.isFinite(value) ? value : null;\n}\n\nfunction xmlEscape(value) {\n    return String(value)\n        .replace(/&/g, '&amp;')\n        .replace(/</g, '&lt;')\n        .replace(/>/g, '&gt;')\n        .replace(/\"/g, '&quot;');\n}\n\nconst vendor = (name, value) => `<VendorOption name=\"${name}\">${xmlEscape(value)}</VendorOption>`;\n\n/** Posun popisku od bodu: o polom\u011Br zna\u010Dky a kousek. */\nexport function labelDistance(markerSize) {\n    return Math.round((Number(markerSize) || 8) * 0.35 + 2);\n}\n\nfunction rotationXml(rotation) {\n    if (rotation?.mode === 'angle' && Number(rotation.angle)) {\n        return `<Rotation>${-Number(rotation.angle)}</Rotation>`;\n    }\n    if (rotation?.mode === 'field' && rotation.field) {\n        const field = `<ogc:PropertyName>${xmlEscape(rotation.field)}</ogc:PropertyName>`;\n        return rotation.clockwise === false\n            ? `<Rotation>${field}</Rotation>`\n            : `<Rotation><ogc:Mul>${field}<ogc:Literal>-1</ogc:Literal></ogc:Mul></Rotation>`;\n    }\n    return '';\n}\n\nfunction pointPlacementXml(labels, markerSize) {\n    const distance = labelDistance(markerSize);\n    let anchor = '';\n    let dx = distance;\n    let dy = distance;\n    if (labels.position !== 'auto') {\n        const [ax, ay] = ANCHORS[labels.position] || ANCHORS.c;\n        anchor = `<AnchorPoint><AnchorPointX>${ax}</AnchorPointX><AnchorPointY>${ay}</AnchorPointY></AnchorPoint>`;\n        dx = ax === 0.5 ? 0 : distance;\n        dy = ay === 0.5 ? 0 : distance;\n    }\n    const displacement = dx || dy\n        ? `<Displacement><DisplacementX>${dx}</DisplacementX><DisplacementY>${dy}</DisplacementY></Displacement>`\n        : '';\n    const rotation = rotationXml(labels.rotation);\n    if (!anchor && !displacement && !rotation) return '';\n    return `<LabelPlacement><PointPlacement>${anchor}${displacement}${rotation}</PointPlacement></LabelPlacement>`;\n}\n\n/**\n * `<TextSymbolizer>` popisk\u016F podvrstvy ('' bez popisk\u016F).\n * `groups` = skupiny geometrie podvrstvy (point/line/polygon), `markerSize`\n * = velikost zna\u010Dky bodu, `minZoom` = `labelMinZoom(entry)`.\n */\nexport function textSymbolizerXml(labels, { groups, markerSize, minZoom } = {}) {\n    if (!labels?.enabled || !labels.attribute) return '';\n    const kinds = new Set(groups || []);\n    const only = kinds.size === 1 ? [...kinds][0] : null;\n    let placement = '';\n    if (only === 'point') placement = pointPlacementXml(labels, markerSize);\n    else if (only === 'line' && labels.line === 'follow') placement = '<LabelPlacement><LinePlacement/></LabelPlacement>';\n    const options = [];\n    if (kinds.has('point') && labels.position === 'auto') options.push(vendor('labelPosition', 'auto'));\n    if (kinds.has('line')) {\n        options.push(vendor('lineLabel', labels.line));\n        if (labels.repeat) options.push(vendor('repeat', REPEAT_DISTANCE));\n    }\n    if ((kinds.has('line') || kinds.has('polygon')) && labels.fit) options.push(vendor('fitInside', 'true'));\n    if (Number.isFinite(minZoom)) options.push(vendor('labelMinZoom', minZoom));\n    const weight = labels.bold ? '<CssParameter name=\"font-weight\">bold</CssParameter>' : '';\n    return `<TextSymbolizer>\n        <Label><ogc:PropertyName>${xmlEscape(labels.attribute)}</ogc:PropertyName></Label>\n        <Font>\n          <CssParameter name=\"font-family\">dejavu</CssParameter>\n          <CssParameter name=\"font-size\">${labels.size}</CssParameter>\n          ${weight}\n        </Font>\n        ${placement}\n        <Halo>\n          <Radius>1.5</Radius>\n          <Fill><CssParameter name=\"fill\">${xmlEscape(labels.halo)}</CssParameter></Fill>\n        </Halo>\n        <Fill><CssParameter name=\"fill\">${xmlEscape(labels.color)}</CssParameter></Fill>\n        ${options.join('')}\n      </TextSymbolizer>`;\n}\n", "/**\n * basemap-look.js \u2014 vzhled podkladov\u00E9 mapy (n\u00E1vrh C): pr\u016Fhlednost a \u010Dernob\u00EDl\u00E9\n * zobrazen\u00ED, aby vynikla data u\u017Eivatele.\n *\n * Ukl\u00E1d\u00E1 se s mapou v Map.config jako `basemapLook: {opacity, gray}`\n * (state.serializeConfig); v\u00FDchoz\u00ED vzhled \u2014 pln\u00E1 sytost, barevn\u011B \u2014 se do\n * configu nep\u00ED\u0161e, star\u00E9 mapy kl\u00ED\u010D nemaj\u00ED. Na vrstvy podkladu ho p\u0159en\u00E1\u0161\u00ED\n * map.applyBasemapLook, ovl\u00E1d\u00E1n\u00ED v nab\u00EDdce Basemap kresl\u00ED\n * map.renderBasemapSwitcher.\n *\n * Modul je bez OpenLayers (testy: basemap-look.test.mjs).\n */\n\nexport const DEFAULT_BASEMAP_LOOK = Object.freeze({ opacity: 1, gray: false });\n\n/** `{opacity: 0\u20131 na setiny, gray: bool}` z \u010Dehokoli (chyb\u011Bj\u00EDc\u00ED \u2192 v\u00FDchoz\u00ED). */\nexport function normalizeBasemapLook(look) {\n    const raw = look?.opacity;\n    const value = raw === null || raw === undefined || raw === '' ? NaN : Number(raw);\n    const opacity = Number.isFinite(value) ? Math.round(Math.min(1, Math.max(0, value)) * 100) / 100 : 1;\n    return { opacity, gray: look?.gray === true };\n}\n\nexport function isDefaultBasemapLook(look) {\n    const { opacity, gray } = normalizeBasemapLook(look);\n    return opacity === DEFAULT_BASEMAP_LOOK.opacity && gray === DEFAULT_BASEMAP_LOOK.gray;\n}\n\n/** Co ulo\u017Eit do Map.config: vzhled, nebo `undefined`, kdy\u017E je v\u00FDchoz\u00ED. */\nexport function serializeBasemapLook(look) {\n    return isDefaultBasemapLook(look) ? undefined : normalizeBasemapLook(look);\n}\n\n/** CSS filtr kontejneru vrstvy podkladu (export.js ho p\u0159enese i do obr\u00E1zku). */\nexport function basemapFilter(look) {\n    return normalizeBasemapLook(look).gray ? 'grayscale(1)' : '';\n}\n\n/**\n * Ovl\u00E1d\u00E1n\u00ED vzhledu pod miniaturami podklad\u016F: posuvn\u00EDk pr\u016Fhlednosti a vyp\u00EDna\u010D\n * \u010Dernob\u00EDle. Bez podkladu (\u201ENo basemap\u201C) jsou ob\u011B volby vypnut\u00E9.\n */\nexport function basemapLookControlsHtml(look, { disabled = false } = {}) {\n    const { opacity, gray } = normalizeBasemapLook(look);\n    const percent = Math.round(opacity * 100);\n    const off = disabled ? ' disabled' : '';\n    return `\n        <div data-role=\"basemap-look\" class=\"col-span-2 mt-1 border-t border-slate-100 px-1 pt-2.5${disabled ? ' opacity-50' : ''}\">\n            <label class=\"flex items-center justify-between text-xs\">\n                <span class=\"font-medium text-slate-700\">Basemap opacity</span>\n                <span data-role=\"basemap-opacity-value\" class=\"tabular-nums text-slate-500\">${percent} %</span>\n            </label>\n            <input type=\"range\" min=\"0\" max=\"100\" step=\"5\" value=\"${percent}\" data-role=\"basemap-opacity\"\n                aria-label=\"Basemap opacity\" class=\"map-basemap-range mt-1.5 w-full\"${off}>\n            <label class=\"mt-2 flex cursor-pointer items-center justify-between gap-x-3 pb-1 text-xs\">\n                <span class=\"font-medium text-slate-700\">Black &amp; white</span>\n                <input type=\"checkbox\" class=\"switch\" data-role=\"basemap-gray\"${gray ? ' checked' : ''}${off}>\n            </label>\n        </div>`;\n}\n", "/**\n * state.js \u2014 centr\u00E1ln\u00ED stav aplikace (Map.config + b\u011Bhov\u00E1 metadata vrstev).\n *\n * `state.config` je JEDIN\u00DD zdroj pravdy pro perzistenci (p\u0159esn\u011B sch\u00E9ma\n * Map.config ze zad\u00E1n\u00ED). `state.layers` k tomu dr\u017E\u00ED b\u011Bhov\u00E1 data, kter\u00E1 se\n * neukl\u00E1daj\u00ED 1:1 (OL vrstva/zdroj, metadata z /wms/, posledn\u00ED podpis apod.),\n * ale ze kter\u00FDch se `config.layers` p\u0159i ulo\u017Een\u00ED znovu sestav\u00ED.\n */\nimport { emit } from './utils.js';\nimport { applyPhotoMarker } from './photo-marker.js';\nimport { applyDefaultLabels, defaultLabels, normalizeLabels } from './labels.js';\nimport { serializeBasemapLook } from './basemap-look.js';\n\nexport const CONFIG_VERSION = 1;\nexport const STYLE_VERSION = 1;\n\n/** Gener\u00E1tor b\u011Bhov\u00FDch identifik\u00E1tor\u016F z\u00E1znam\u016F stromu vrstev. Na rozd\u00EDl od\n * `itemId` je `uid` unik\u00E1tn\u00ED i pro duplik\u00E1ty t\u00E9\u017Ee workspace polo\u017Eky \u2014\n * v\u0161echny akce v UI (strom, symbologie, tabulka) se kl\u00ED\u010Duj\u00ED p\u0159es n\u011Bj. */\nlet uidCounter = 0;\nexport function newUid() {\n    uidCounter += 1;\n    return `u${uidCounter}`;\n}\n\n/** V\u00FDchoz\u00ED hodnoty per-geometrie rules\u016F \u2014 pou\u017Eit\u00E9 jak v\u00FDchoz\u00EDm stylem, tak\n * normalizac\u00ED (dopln\u011Bn\u00ED chyb\u011Bj\u00EDc\u00EDch kl\u00ED\u010D\u016F u star\u0161\u00EDch ulo\u017Een\u00FDch map). */\nfunction defaultRules() {\n    return {\n        point: { symbol: 'circle', size: 8, fill: '#3388ff', stroke: '#ffffff', strokeWidth: 1.5 },\n        line: { stroke: '#3388ff', strokeWidth: 2, dash: null, casing: null },\n        polygon: { fill: '#3388ff', fillOpacity: 0.4, stroke: '#2266cc', strokeWidth: 1, dash: null },\n    };\n}\n\n/** Re\u017Eimy vektorov\u00E9ho stylu. `native` = vrstva se kresl\u00ED stylem ulo\u017Een\u00FDm\n * p\u0159\u00EDmo v datech (KML, MapInfo, DXF, atribut OGR_STYLE\u2026) \u2014 Mapserver ho \u010Dte\n * s\u00E1m, aplikace k n\u011Bmu \u017E\u00E1dn\u00E9 SLD nepos\u00EDl\u00E1 (viz docs/maps.md \u00A7 18). */\nexport const VECTOR_STYLE_MODES = ['simple', 'categorized', 'graduated', 'native'];\n\n\n/** V\u00FDchoz\u00ED (pr\u00E1zdn\u00FD) kategorizovan\u00FD styl \u2014 `mode: \"categorized\"`, viz docs/maps.md. */\nexport function defaultCategorizedStyle() {\n    return {\n        attribute: null,\n        categories: [],\n        other: { enabled: true, color: '#aaaaaa' },\n    };\n}\n\n/** V\u00FDchoz\u00ED (pr\u00E1zdn\u00FD) odstup\u0148ovan\u00FD styl \u2014 `mode: \"graduated\"`, viz docs/maps.md. */\nexport function defaultGraduatedStyle() {\n    return {\n        attribute: null,\n        method: 'equal',\n        classCount: 5,\n        classes: [],\n    };\n}\n\n/** V\u00FDchoz\u00ED styl pro vektorovou vrstvu \u2014 odpov\u00EDd\u00E1 sch\u00E9matu ze zad\u00E1n\u00ED.\n * `categorized`/`graduated` jsou v\u017Edy p\u0159\u00EDtomn\u00E9 (i v re\u017Eimu \"simple\"), aby si\n * u\u017Eivatel mohl v UI p\u0159ipravit klasifikaci bez ztr\u00E1ty dat p\u0159i p\u0159ep\u00EDn\u00E1n\u00ED Mode. */\nexport function defaultVectorStyle() {\n    return {\n        version: STYLE_VERSION,\n        type: 'vector',\n        mode: 'simple',\n        rules: defaultRules(),\n        labels: defaultLabels(),\n        categorized: defaultCategorizedStyle(),\n        graduated: defaultGraduatedStyle(),\n    };\n}\n\n/** Dopln\u00ED chyb\u011Bj\u00EDc\u00ED \u010D\u00E1sti vektorov\u00E9ho stylu \u2014 zp\u011Btn\u00E1 kompatibilita se star\u00FDmi\n * ulo\u017Een\u00FDmi mapami (Map.config), kter\u00E9 kategorizovan\u00FD/odstup\u0148ovan\u00FD styl je\u0161t\u011B\n * neznaly. `version` sch\u00E9matu z\u016Fst\u00E1v\u00E1 1 (jen bohat\u0161\u00ED obsah `style`). */\nexport function normalizeVectorStyle(style) {\n    const rulesDefaults = defaultRules();\n    const categorizedDefaults = defaultCategorizedStyle();\n    return {\n        version: STYLE_VERSION,\n        type: 'vector',\n        mode: VECTOR_STYLE_MODES.includes(style?.mode) ? style.mode : 'simple',\n        rules: {\n            point: { ...rulesDefaults.point, ...style?.rules?.point },\n            line: { ...rulesDefaults.line, ...style?.rules?.line },\n            polygon: { ...rulesDefaults.polygon, ...style?.rules?.polygon },\n        },\n        labels: normalizeLabels(style?.labels),\n        categorized: {\n            ...categorizedDefaults,\n            ...style?.categorized,\n            other: { ...categorizedDefaults.other, ...style?.categorized?.other },\n        },\n        graduated: { ...defaultGraduatedStyle(), ...style?.graduated },\n    };\n}\n\n/**\n * Pravidlo geometrie pro jednu kategorii / t\u0159\u00EDdu: barva kategorie nahrad\u00ED\n * hlavn\u00ED barvu (v\u00FDpl\u0148 bodu a polygonu, barvu linie) a kategorie m\u016F\u017Ee n\u00E9st\n * vlastn\u00ED odchylky od z\u00E1kladn\u00EDho pravidla \u2014 \u0161\u00ED\u0159ku, \u010D\u00E1rkov\u00E1n\u00ED a obrys linie,\n * velikost a tvar bodu, obrys a pr\u016Fhlednost polygonu (silnice podle t\u0159\u00EDdy,\n * styl p\u0159evzat\u00FD z dat). Sd\u00EDl\u00ED ho gener\u00E1tor SLD i legenda.\n */\nexport function ruleForCategory(geometry, baseRule, category) {\n    if (!baseRule) return baseRule;\n    if (!category) return { ...baseRule };\n    const pick = (value, fallback) => (value !== undefined && value !== null ? value : fallback);\n    if (geometry === 'point') {\n        return {\n            ...baseRule,\n            fill: pick(category.color, baseRule.fill),\n            size: pick(category.size, baseRule.size),\n            symbol: pick(category.symbol, baseRule.symbol),\n        };\n    }\n    if (geometry === 'line') {\n        return {\n            ...baseRule,\n            stroke: pick(category.color, baseRule.stroke),\n            strokeWidth: pick(category.width, baseRule.strokeWidth),\n            // Pr\u00E1zdn\u00FD \u0159et\u011Bzec = kategorie v\u00FDslovn\u011B bez \u010D\u00E1rkov\u00E1n\u00ED / obrysu.\n            dash: category.dash !== undefined ? (category.dash || null) : baseRule.dash,\n            casing: category.casing !== undefined ? (category.casing || null) : baseRule.casing,\n        };\n    }\n    return {\n        ...baseRule,\n        fill: pick(category.color, baseRule.fill),\n        stroke: pick(category.stroke, baseRule.stroke),\n        fillOpacity: pick(category.fillOpacity, baseRule.fillOpacity),\n    };\n}\n\n/* ---------------------------------------------------------------------------\n * Styl rastru\n *\n * {\n *   version: 1, type: 'raster',\n *   mode: 'rgb' | 'gray' | 'ramp' | 'palette',\n *   bands: { r, g, b },          // re\u017Eim rgb\n *   band: 1,                     // re\u017Eimy gray / ramp\n *   stretch: { type: 'percent' | 'minmax' | 'none', clip: [2, 98] },\n *   range: null | [min, max],    // ru\u010Dn\u00ED rozsah hodnot m\u00EDsto stretch\n *   nodata: null | \u010D\u00EDslo,        // hodnota kreslen\u00E1 pr\u016Fhledn\u011B (m\u00EDsto no-data souboru)\n *   colormap: 'terrain',         // re\u017Eim ramp (jm\u00E9na map d\u00E1v\u00E1 Mapserver)\n *   opacity: 1                   // historick\u00E9, nepou\u017E\u00EDv\u00E1 se\n * }\n *\n * Star\u0161\u00ED ulo\u017Een\u00E9 mapy maj\u00ED `bands: {mode: 'rgb'|'gray', r, g, b}` a\n * `stretch: {clip}` \u2014 `normalizeRasterStyle` je p\u0159evede.\n * ------------------------------------------------------------------------- */\n\nexport const RASTER_MODES = ['rgb', 'gray', 'ramp', 'palette'];\n\nconst isByteBand = (band) => String(band?.data_type || band?.dataType || band?.type || '').toLowerCase() === 'byte';\n\n/** \u010C\u00EDsla p\u00E1sem podle jejich v\u00FDznamu (Red/Green/Blue), jinak 1, 2, 3. */\nfunction rgbBandOrder(bands) {\n    const find = (name) => {\n        const band = (bands || []).find((b) => String(b?.colorInterp || b?.colorInterpretation || '').toLowerCase() === name);\n        return band ? Number(band.index) : null;\n    };\n    const order = { r: find('red'), g: find('green'), b: find('blue') };\n    if (order.r && order.g && order.b) return order;\n    return { r: 1, g: 2, b: 3 };\n}\n\n/**\n * V\u00FDchoz\u00ED styl rastru podle jeho p\u00E1sem a druhu dat:\n * - soubor s paletou \u2192 paleta souboru,\n * - 3 a v\u00EDce p\u00E1sem \u2192 RGB (po\u0159ad\u00ED podle v\u00FDznamu p\u00E1sem; p\u00E1sma, kter\u00E1 nejsou\n *   8bitov\u00E1, se rozt\u00E1hnou mezi 2. a 98. percentil \u2014 jinak je sn\u00EDmek \u010Dern\u00FD),\n * - jedno p\u00E1smo \u2192 stupn\u011B \u0161edi rozta\u017Een\u00E9 mezi 2. a 98. percentil; v\u00FD\u0161kov\u00FD model\n *   (`rasterClass: 'elevation'`) barevnou hypsometri\u00ED.\n */\nexport function defaultRasterStyle(bands, info = {}) {\n    const list = Array.isArray(bands) ? bands : [];\n    const style = {\n        version: STYLE_VERSION,\n        type: 'raster',\n        mode: 'gray',\n        bands: rgbBandOrder(list),\n        band: 1,\n        stretch: { type: 'percent', clip: [2, 98] },\n        range: null,\n        nodata: null,\n        colormap: 'viridis',\n        opacity: 1,\n    };\n    if (info.hasPalette) {\n        style.mode = 'palette';\n    } else if (list.length >= 3) {\n        style.mode = 'rgb';\n        // 8bitov\u00FD sn\u00EDmek se kresl\u00ED tak, jak je; ostatn\u00ED pot\u0159ebuj\u00ED rozta\u017Een\u00ED.\n        if (list.slice(0, 3).every(isByteBand)) style.stretch = { type: 'none', clip: [2, 98] };\n    } else if (info.rasterClass === 'elevation') {\n        style.mode = 'ramp';\n        style.colormap = 'terrain';\n    }\n    return style;\n}\n\n/** Dopln\u00ED/p\u0159evede styl rastru (i ze star\u0161\u00EDho tvaru ulo\u017Een\u00FDch map). */\nexport function normalizeRasterStyle(style, bands, info = {}) {\n    const base = defaultRasterStyle(bands, info);\n    if (!style || typeof style !== 'object') return base;\n    const count = Array.isArray(bands) ? bands.length : 0;\n    const legacyMode = style.bands?.mode; // star\u00FD tvar: re\u017Eim uvnit\u0159 `bands`\n    let mode = RASTER_MODES.includes(style.mode) ? style.mode : (legacyMode === 'rgb' ? 'rgb' : legacyMode === 'gray' ? 'gray' : base.mode);\n    if (mode === 'rgb' && count > 0 && count < 3) mode = 'gray';\n    if (mode === 'palette' && !info.hasPalette) mode = base.mode === 'palette' ? 'gray' : base.mode;\n    const clamp = (n) => (count > 0 ? Math.min(Math.max(1, Number(n) || 1), count) : Math.max(1, Number(n) || 1));\n    const clip = Array.isArray(style.stretch?.clip) && style.stretch.clip.length === 2\n        ? [Number(style.stretch.clip[0]), Number(style.stretch.clip[1])]\n        : base.stretch.clip;\n    let stretchType = ['percent', 'minmax', 'none'].includes(style.stretch?.type) ? style.stretch.type : null;\n    if (!stretchType) {\n        // Star\u00FD tvar znal jen percentily v re\u017Eimu \u0161edi; RGB se nestre\u010Dovalo.\n        stretchType = legacyMode === 'rgb' ? base.stretch.type : 'percent';\n    }\n    const range = Array.isArray(style.range) && style.range.length === 2\n        && Number.isFinite(Number(style.range[0])) && Number.isFinite(Number(style.range[1]))\n        && Number(style.range[0]) < Number(style.range[1])\n        ? [Number(style.range[0]), Number(style.range[1])]\n        : null;\n    return {\n        version: STYLE_VERSION,\n        type: 'raster',\n        mode,\n        bands: {\n            r: clamp(style.bands?.r ?? base.bands.r),\n            g: clamp(style.bands?.g ?? base.bands.g),\n            b: clamp(style.bands?.b ?? base.bands.b),\n        },\n        band: clamp(style.band ?? (legacyMode === 'gray' ? style.bands?.r : base.band)),\n        stretch: { type: stretchType, clip },\n        range,\n        nodata: Number.isFinite(style.nodata) ? style.nodata : null,\n        colormap: typeof style.colormap === 'string' && style.colormap ? style.colormap : base.colormap,\n        opacity: 1,\n    };\n}\n\n/* ---------------------------------------------------------------------------\n * N\u00E1vrh stylu z Mapserveru (`suggestedStyle` v DescribeData) \u2192 n\u00E1\u0161 model\n * ------------------------------------------------------------------------- */\n\nconst dashText = (dash) => (Array.isArray(dash) && dash.length ? dash.join(' ') : null);\n\n/** Popis symbolu (slovn\u00EDk legendy Mapserveru) \u2192 pravidlo dan\u00E9 geometrie. */\nfunction ruleFromSymbol(symbol, base) {\n    if (!symbol) return { ...base };\n    if (symbol.type === 'point') {\n        return {\n            ...base,\n            symbol: ['circle', 'square', 'triangle', 'star', 'cross', 'x'].includes(symbol.shape) ? symbol.shape : 'circle',\n            size: Number(symbol.size) || base.size,\n            fill: symbol.fill || symbol.stroke || base.fill,\n            stroke: symbol.fill ? (symbol.stroke || base.stroke) : (symbol.stroke || base.stroke),\n            strokeWidth: Number.isFinite(symbol.strokeWidth) ? symbol.strokeWidth : base.strokeWidth,\n        };\n    }\n    if (symbol.type === 'line') {\n        return {\n            ...base,\n            stroke: symbol.stroke || base.stroke,\n            strokeWidth: Number(symbol.width) || base.strokeWidth,\n            dash: dashText(symbol.dash),\n            casing: symbol.casing || null,\n        };\n    }\n    return {\n        ...base,\n        fill: symbol.fill || base.fill,\n        fillOpacity: Number.isFinite(symbol.fillOpacity) ? symbol.fillOpacity : base.fillOpacity,\n        stroke: symbol.stroke || symbol.fill || base.stroke,\n        strokeWidth: Number.isFinite(symbol.strokeWidth) ? symbol.strokeWidth : base.strokeWidth,\n        dash: dashText(symbol.dash),\n    };\n}\n\n/** Barva a odchylky kategorie od z\u00E1kladn\u00EDho pravidla (\u0161\u00ED\u0159ka, \u010D\u00E1rkov\u00E1n\u00ED\u2026). */\nfunction categoryFromSymbol(symbol, baseRule) {\n    const rule = ruleFromSymbol(symbol, baseRule);\n    if (symbol?.type === 'line') {\n        return {\n            color: rule.stroke,\n            ...(rule.strokeWidth !== baseRule.strokeWidth ? { width: rule.strokeWidth } : {}),\n            ...(rule.dash !== baseRule.dash ? { dash: rule.dash || '' } : {}),\n            ...(rule.casing !== baseRule.casing ? { casing: rule.casing || '' } : {}),\n        };\n    }\n    if (symbol?.type === 'point') {\n        return {\n            color: rule.fill,\n            ...(rule.size !== baseRule.size ? { size: rule.size } : {}),\n            ...(rule.symbol !== baseRule.symbol ? { symbol: rule.symbol } : {}),\n        };\n    }\n    return {\n        color: rule.fill,\n        ...(rule.stroke !== baseRule.stroke ? { stroke: rule.stroke } : {}),\n        ...(rule.fillOpacity !== baseRule.fillOpacity ? { fillOpacity: rule.fillOpacity } : {}),\n    };\n}\n\n/**\n * P\u0159evede n\u00E1vrhy stylu podvrstev (`[{geometry, suggested}]`) na vektorov\u00FD\n * styl. Jednoduch\u00E9 n\u00E1vrhy se slou\u010D\u00ED do pravidel per geometrie; kategorizovan\u00FD\n * se vezme z prvn\u00ED podvrstvy, kter\u00E1 ho m\u00E1 (atribut je spole\u010Dn\u00FD cel\u00E9 vrstv\u011B).\n * Vrac\u00ED null, kdy\u017E nen\u00ED co navrhnout.\n */\nexport function styleFromSuggestions(suggestions) {\n    const usable = (suggestions || []).filter((s) => s?.suggested && s.geometry);\n    if (usable.length === 0) return null;\n    const style = defaultVectorStyle();\n    let labelField = null;\n    usable.forEach(({ geometry, suggested }) => {\n        const base = style.rules[geometry];\n        if (!base) return;\n        if (suggested.kind === 'categorized' && Array.isArray(suggested.categories) && suggested.categories.length) {\n            // Z\u00E1kladn\u00ED pravidlo = symbol prvn\u00ED (nej\u010Dast\u011Bj\u0161\u00ED/nejd\u016Fle\u017Eit\u011Bj\u0161\u00ED) kategorie.\n            style.rules[geometry] = ruleFromSymbol(suggested.categories[0].symbol, base);\n            if (style.mode !== 'categorized') {\n                style.mode = 'categorized';\n                style.categorized = {\n                    attribute: suggested.attribute,\n                    categories: suggested.categories.map((category) => ({\n                        value: String(category.value),\n                        label: String(category.label ?? category.value),\n                        ...categoryFromSymbol(category.symbol, style.rules[geometry]),\n                    })),\n                    other: {\n                        enabled: Boolean(suggested.other),\n                        ...(suggested.other\n                            ? categoryFromSymbol(suggested.other, style.rules[geometry])\n                            : { color: '#aaaaaa' }),\n                    },\n                };\n            }\n        } else if (suggested.symbol) {\n            style.rules[geometry] = ruleFromSymbol(suggested.symbol, base);\n        }\n        if (suggested.labelField && !labelField) labelField = suggested.labelField;\n    });\n    if (labelField) style.labels = { ...style.labels, enabled: true, attribute: labelField };\n    return style;\n}\n\n/** Vytvo\u0159\u00ED b\u011Bhov\u00FD uzel skupiny vrstev (jedna \u00FArove\u0148 zano\u0159en\u00ED \u2014 skupiny ve\n * skupin\u00E1ch nepodporujeme). `saved` je voliteln\u00FD z\u00E1znam `{type:\"group\",...}`\n * z Map.config; `children` pln\u00ED volaj\u00EDc\u00ED (main.js/layers.js).\n * `hybrid: true` = skupina jednoho hybridn\u00EDho souboru (vektor + rastr, viz\n * hybrid.js) \u2014 jin\u00E1 ikona a odebr\u00E1n\u00ED skupiny odebere i jej\u00ED vrstvy. */\nexport function createGroupEntry(saved) {\n    return {\n        uid: newUid(),\n        isGroup: true,\n        dataType: 'group',\n        title: saved?.title || 'New group',\n        visible: saved ? saved.visible !== false : true,\n        collapsed: Boolean(saved?.collapsed),\n        hybrid: Boolean(saved?.hybrid),\n        // Skupina jednoho souboru s v\u00EDce vrstvami (GPKG, KML, FileGDB\u2026):\n        // odebr\u00E1n\u00ED skupiny odebere z mapy i jej\u00ED vrstvy.\n        dataset: Boolean(saved?.dataset || saved?.hybrid),\n        children: [],\n    };\n}\n\n/** Zplo\u0161t\u00ED strom vrstev (skupiny rozbal\u00ED, skupinov\u00E9 uzly vynech\u00E1) \u2014 po\u0159ad\u00ED\n * odpov\u00EDd\u00E1 z-orderu: prvn\u00ED prvek = naho\u0159e v panelu = nejv\u00FD\u0161e na map\u011B. */\nexport function flatLayers(state) {\n    const out = [];\n    state.layers.forEach((entry) => {\n        if (entry.isGroup) {\n            out.push(...entry.children);\n        } else {\n            out.push(entry);\n        }\n    });\n    return out;\n}\n\n/** Najde z\u00E1znam (vrstvu i skupinu) podle `uid`, nebo vr\u00E1t\u00ED null. */\nexport function findEntryByUid(state, uid) {\n    for (const entry of state.layers) {\n        if (entry.uid === uid) return entry;\n        if (entry.isGroup) {\n            const child = entry.children.find((c) => c.uid === uid);\n            if (child) return child;\n        }\n    }\n    return null;\n}\n\n/** Najde kontejner z\u00E1znamu: `{ list, index, group }` \u2014 `group` je nad\u0159azen\u00E1\n * skupina (null pro top-level). Vrac\u00ED null, kdy\u017E z\u00E1znam neexistuje. */\nexport function findEntryContainer(state, uid) {\n    const topIndex = state.layers.findIndex((e) => e.uid === uid);\n    if (topIndex !== -1) return { list: state.layers, index: topIndex, group: null };\n    for (const entry of state.layers) {\n        if (!entry.isGroup) continue;\n        const index = entry.children.findIndex((c) => c.uid === uid);\n        if (index !== -1) return { list: entry.children, index, group: entry };\n    }\n    return null;\n}\n\n/** Efektivn\u00ED viditelnost vrstvy = vlastn\u00ED checkbox AND viditelnost nad\u0159azen\u00E9\n * skupiny (stav d\u011Bt\u00ED se p\u0159i vypnut\u00ED skupiny nep\u0159episuje). */\nexport function isEffectivelyVisible(state, entry) {\n    if (!entry.visible) return false;\n    const container = findEntryContainer(state, entry.uid);\n    return !container?.group || container.group.visible;\n}\n\n/** Vytvo\u0159\u00ED v\u00FDchoz\u00ED (pr\u00E1zdn\u00FD) Map.config pro novou mapu. */\nexport function createDefaultConfig() {\n    return {\n        version: CONFIG_VERSION,\n        // Bez v\u00FD\u0159ezu: nov\u00E1 mapa se nastav\u00ED na zemi u\u017Eivatele (bootstrap\n        // `defaultExtent`, viz map.js), jinak na sv\u011Bt.\n        view: null,\n        basemap: 'osm',\n        layers: [],\n    };\n}\n\n/**\n * Sestav\u00ED hlavn\u00ED runtime stav appky z bootstrap dat ze \u0161ablony.\n * `bootstrap` = obsah JSON script tagu \"map-bootstrap\" (viz main.js).\n */\nexport function createState(bootstrap) {\n    const mapObj = bootstrap.map || null;\n    const state = {\n        mapId: mapObj ? mapObj.id : null,\n        title: mapObj ? mapObj.title : 'Untitled map',\n        description: mapObj && mapObj.description ? mapObj.description : '',\n        config: (mapObj && mapObj.config) || createDefaultConfig(),\n        // B\u011Bhov\u00FD seznam vrstev \u2014 pln\u00ED layers.js p\u0159i hydrataci/p\u0159id\u00E1v\u00E1n\u00ED.\n        layers: [],\n        savedOnce: Boolean(mapObj),\n    };\n    // `dirty` = neulo\u017Een\u00E1 zm\u011Bna OBSAHU mapy (vrstvy, styl, kresba, n\u00E1zev\u2026),\n    // nikoli posun/zoom. Moduly ho d\u00E1l nastavuj\u00ED prost\u00FDm p\u0159i\u0159azen\u00EDm; setter\n    // jen ohl\u00E1s\u00ED zm\u011Bnu (`state:dirty`), aby si hl\u00EDd\u00E1n\u00ED neulo\u017Een\u00FDch zm\u011Bn\n    // (unsaved.js) mohlo zaregistrovat/odregistrovat `beforeunload`.\n    let dirty = false;\n    Object.defineProperty(state, 'dirty', {\n        enumerable: true,\n        get() { return dirty; },\n        set(value) {\n            const next = Boolean(value);\n            if (next === dirty) return;\n            dirty = next;\n            emit('state:dirty', { dirty });\n        },\n    });\n    return state;\n}\n\n/**\n * Vytvo\u0159\u00ED b\u011Bhovou polo\u017Eku vrstvy z detailu /items/<id>/wms/ + voliteln\u00E9ho\n * ulo\u017Een\u00E9ho z\u00E1znamu z Map.config.\n *\n * `itemDetail.layers` jsou podvrstvy JEDN\u00C9 logick\u00E9 vrstvy souboru (vrstva se\n * sm\u00ED\u0161en\u00FDmi geometriemi jich m\u00E1 v\u00EDc: `roads_line`, `roads_point`). Popis vrstvy\n * z Mapserveru (describe.js) dopl\u0148uje:\n * - `layer_key` / `layer_title` \u2014 kter\u00E1 vrstva souboru to je,\n * - `native` \u2014 styl ulo\u017Een\u00FD v datech (`{available, plain, legends, \u2026}`),\n * - `suggested` \u2014 n\u00E1vrh prvn\u00EDho stylu (`[{geometry, suggested}]`),\n * - `raster` \u2014 paleta, p\u00E1sma a jm\u00E9na barevn\u00FDch map rastru.\n *\n * V\u00FDchoz\u00ED styl nov\u00E9 vrstvy: styl z dat (kdy\u017E ho data maj\u00ED a n\u011Bco \u0159\u00EDk\u00E1) \u2192\n * n\u00E1vrh podle druhu dat \u2192 v\u00FDchoz\u00ED modr\u00E1. Body s fotkami dostanou fotoapar\u00E1t\n * (photo-marker.js) \u2014 i m\u00EDsto stylu z dat, kdy\u017E ho n\u00E1vrh popsal cel\u00FD (barvy\n * ikon a \u010Dar KML z\u016Fstanou). Vrstva s atributem n\u00E1zvu prvku dostane popisky,\n * kter\u00E9 se ukazuj\u00ED od p\u0159ibl\u00ED\u017Een\u00ED podle hustoty dat (labels.js).\n */\nexport function createLayerEntry(itemDetail, savedLayer) {\n    const bandInfo = itemDetail.bands || null;\n    const isRaster = itemDetail.data_type === 'raster';\n    const native = itemDetail.native || null;\n    const rasterInfo = itemDetail.raster || null;\n    let style;\n    if (isRaster) {\n        const info = { hasPalette: Boolean(rasterInfo?.palette?.length), rasterClass: itemDetail.raster_class || '' };\n        style = savedLayer?.style\n            ? normalizeRasterStyle(savedLayer.style, bandInfo, info)\n            : defaultRasterStyle(bandInfo, info);\n    } else if (savedLayer?.style) {\n        style = normalizeVectorStyle(savedLayer.style);\n    } else {\n        style = normalizeVectorStyle(styleFromSuggestions(itemDetail.suggested));\n        if (native?.available && !native.plain) style.mode = 'native';\n        // Body s fotkami (KMZ, My Maps, adresy fotek) dostanou fotoapar\u00E1t.\n        applyPhotoMarker(style, itemDetail.layers, itemDetail.suggested);\n        // Vrstva s atributem n\u00E1zvu prvku (name, label\u2026) dostane popisky.\n        applyDefaultLabels(style, itemDetail.layers);\n    }\n    const geometryTypes = new Set();\n    (itemDetail.layers || []).forEach((sub) => {\n        (sub.geometry_types || []).forEach((g) => geometryTypes.add(normalizeGeometryType(g)));\n    });\n    return {\n        uid: newUid(),\n        itemId: itemDetail.id,\n        title: savedLayer?.title || itemDetail.layer_title || itemDetail.title,\n        // Nov\u00E1 vrstva je zapnut\u00E1, pokud ji slu\u017Eba neozna\u010Dila jako vrstvu, kterou\n        // u\u017E ukazuje jin\u00E1 vrstva souboru (vektory hybridn\u00EDho PDF nad str\u00E1nkou).\n        visible: savedLayer ? savedLayer.visible !== false : itemDetail.default_visible !== false,\n        opacity: savedLayer && Number.isFinite(savedLayer.opacity) ? savedLayer.opacity : 1,\n        style,\n        // Atributov\u00FD filtr vrstvy (viz filter.js) \u2014 ukl\u00E1d\u00E1 se do Map.config;\n        // star\u0161\u00ED ulo\u017Een\u00E9 mapy kl\u00ED\u010D nemaj\u00ED \u2192 null (zp\u011Btn\u011B kompatibiln\u00ED).\n        filter: savedLayer?.filter || null,\n        // M\u011B\u0159\u00EDtkov\u00E1 omezen\u00ED viditelnosti (zoom 0\u201328, null = bez limitu).\n        minZoom: Number.isFinite(savedLayer?.minZoom) ? savedLayer.minZoom : null,\n        maxZoom: Number.isFinite(savedLayer?.maxZoom) ? savedLayer.maxZoom : null,\n        // Sbalen\u00E1 legenda (seznam t\u0159\u00EDd) v \u0159\u00E1dku vrstvy.\n        legendCollapsed: Boolean(savedLayer?.legendCollapsed),\n        dataType: itemDetail.data_type,\n        // \u010C\u00E1st hybridn\u00ED polo\u017Eky (\"vector\" | \"raster\", viz hybrid.js), jinak null;\n        // `dataType` je pak typ \u010D\u00E1sti, `itemDataType` typ cel\u00E9 polo\u017Eky.\n        hybridPart: itemDetail.hybrid_part || savedLayer?.hybridPart || null,\n        itemDataType: itemDetail.item_data_type || itemDetail.data_type,\n        // Vrstva souboru (n\u00E1zev zdrojov\u00E9 vrstvy) \u2014 u souboru s v\u00EDce vrstvami\n        // m\u00E1 ka\u017Ed\u00E1 vlastn\u00ED z\u00E1znam stromu; null = soubor s jedinou vrstvou.\n        layerKey: itemDetail.layer_key ?? savedLayer?.layer ?? null,\n        // N\u00E1zev polo\u017Eky workspace (souboru) \u2014 Properties, hl\u00E1\u0161en\u00ED chyb.\n        itemTitle: itemDetail.title,\n        bbox: itemDetail.layer_bbox || itemDetail.bbox || null,\n        sublayers: itemDetail.layers || [],\n        geometryTypes: Array.from(geometryTypes),\n        bands: bandInfo,\n        source: itemDetail.source || null,\n        native,\n        suggested: itemDetail.suggested || null,\n        raster: rasterInfo,\n        rasterClass: itemDetail.raster_class || '',\n        // Odhad rychlosti kreslen\u00ED souboru od Mapserveru (advisor.js) a \u010Dasy\n        // skute\u010Dn\u00FDch vykreslen\u00ED t\u00E9to vrstvy (loading.js) \u2014 neukl\u00E1d\u00E1 se.\n        performance: itemDetail.performance || null,\n        renderTimes: [],\n        wms: {\n            url: itemDetail.wms_url,\n            fileUrl: itemDetail.params?.FILE_URL,\n            sig: itemDetail.params?.sig,\n            // Pl\u00E1tce vykreslen\u00ED (jen p\u0159i \u00FA\u010Dtov\u00E1n\u00ED map, sou\u010D\u00E1st podpisu).\n            payer: itemDetail.params?.PAYER || '',\n            // CRS pro slu\u017Ebu, kdy\u017E ho soubor nem\u00E1 (ru\u010Dn\u011B p\u0159i\u0159azen\u00E9 apod.).\n            fileCrs: itemDetail.params?.FILE_CRS || '',\n            expiresAt: itemDetail.expires_at || 0,\n        },\n        // Dopln\u00ED se v layers.js/wms.js po vytvo\u0159en\u00ED OL vrstvy.\n        olLayer: null,\n        olSource: null,\n    };\n}\n\n/** Normalizuje n\u00E1zev geometrie na jednu ze t\u0159\u00ED skupin point/line/polygon. */\nexport function normalizeGeometryType(geometryType) {\n    const t = (geometryType || '').toLowerCase();\n    if (t.includes('point')) return 'point';\n    if (t.includes('line')) return 'line';\n    if (t.includes('polygon')) return 'polygon';\n    return 'point';\n}\n\n/** Sestav\u00ED serializovateln\u00FD Map.config z aktu\u00E1ln\u00EDho b\u011Bhov\u00E9ho stavu.\n * `view` = { center: [lon, lat], zoom } \u2014 p\u0159epo\u010Det z EPSG:3857 d\u011Bl\u00E1 volaj\u00EDc\u00ED\n * (map.js), aby tento modul z\u016Fstal bez z\u00E1vislosti na OpenLayers. */\nexport function serializeConfig(state, view, basemapKey) {\n    // Serializace JEDN\u00C9 vrstvy nikdy nesm\u00ED shodit ulo\u017Een\u00ED cel\u00E9 mapy. Kdyby\n    // `serializeLayerEntry` (typicky u kresby/extern\u00ED vrstvy p\u0159es `toGeoJSON`/\n    // `toConfig`, nebo u vrstvy v nekonzistentn\u00EDm b\u011Bhov\u00E9m stavu) vyhodila\n    // v\u00FDjimku, vrstvu rad\u0161i vynech\u00E1me a zalogujeme \u2014 jinak by cel\u00E9 \u201ESave\"\n    // skon\u010Dilo chybou (projev hl\u00E1\u0161ky \u201EError saving: \u2026\") p\u0159esto, \u017Ee mapa jinak\n    // ulo\u017Eiteln\u00E1 je. Vrac\u00ED null u vrstvy, kterou se nepoda\u0159ilo serializovat.\n    const serializeSafe = (entry) => {\n        try {\n            return serializeLayerEntry(entry);\n        } catch (error) {\n            // eslint-disable-next-line no-console -- diagnostika vynechan\u00E9 vrstvy\n            console.warn('Skipping a layer that failed to serialize:', entry?.title, error);\n            return null;\n        }\n    };\n    return {\n        version: CONFIG_VERSION,\n        view: view || state.config.view,\n        basemap: basemapKey || state.config.basemap,\n        // Pr\u016Fhlednost a \u010Dernob\u00EDle podkladu (basemap-look.js); v\u00FDchoz\u00ED vzhled\n        // kl\u00ED\u010D nem\u00E1 (JSON.stringify `undefined` vynech\u00E1).\n        basemapLook: serializeBasemapLook(state.config.basemapLook),\n        layers: state.layers.map((entry) => {\n            // Skupina vrstev \u2014 `{type:\"group\", title, visible, collapsed,\n            // children:[\u2026b\u011B\u017En\u00E9 layer configy\u2026]}`; zp\u011Btn\u011B kompatibiln\u00ED (star\u00E9\n            // configy z\u00E1znam s type \"group\" prost\u011B nemaj\u00ED).\n            if (entry.isGroup) {\n                return {\n                    type: 'group',\n                    title: entry.title,\n                    visible: entry.visible,\n                    collapsed: entry.collapsed,\n                    ...(entry.hybrid ? { hybrid: true } : {}),\n                    ...(entry.dataset ? { dataset: true } : {}),\n                    children: entry.children.map(serializeSafe).filter(Boolean),\n                };\n            }\n            return serializeSafe(entry);\n        }).filter(Boolean),\n    };\n}\n\n/** Serializuje jeden b\u011Bhov\u00FD z\u00E1znam vrstvy (bez skupin) do tvaru Map.config.\n * Exportov\u00E1no i pro duplikaci vrstvy (layers.js \u2014 deep copy configu). */\nexport function serializeLayerEntry(layer) {\n    // M\u011B\u0159\u00EDtkov\u00E1 omezen\u00ED jsou spole\u010Dn\u00E1 v\u0161em typ\u016Fm vrstev.\n    const zoomLimits = {\n        minZoom: Number.isFinite(layer.minZoom) ? layer.minZoom : null,\n        maxZoom: Number.isFinite(layer.maxZoom) ? layer.maxZoom : null,\n    };\n    // Kresba (draw.js) \u2014 klientsk\u00E1 vrstva bez itemId; ukl\u00E1d\u00E1 se jako\n    // GeoJSON FeatureCollection v EPSG:4326 (`toGeoJSON` dod\u00E1 draw.js,\n    // aby state.js nez\u00E1visel na OpenLayers). Zp\u011Btn\u011B kompatibiln\u00ED:\n    // star\u0161\u00ED mapy z\u00E1znam s `type: \"drawing\"` prost\u011B nemaj\u00ED.\n    if (layer.dataType === 'drawing') {\n        return {\n            type: 'drawing',\n            title: layer.title,\n            visible: layer.visible,\n            opacity: layer.opacity,\n            geojson: layer.toGeoJSON\n                ? layer.toGeoJSON()\n                : (layer.geojson || { type: 'FeatureCollection', features: [] }),\n            // Sloupce atributov\u00E9 tabulky kresby (po\u0159ad\u00ED + pr\u00E1zdn\u00E9 sloupce).\n            ...(Array.isArray(layer.fields) && layer.fields.length ? { fields: [...layer.fields] } : {}),\n            ...zoomLimits,\n        };\n    }\n    // Extern\u00ED vrstvy (wms/xyz/wmts/local, viz external.js) \u2014 serializaci\n    // dod\u00E1v\u00E1 vrstva sama p\u0159es `toConfig()` (stejn\u00FD princip jako kresba).\n    if (layer.external && typeof layer.toConfig === 'function') {\n        return { ...layer.toConfig(), ...zoomLimits };\n    }\n    return {\n        itemId: layer.itemId,\n        title: layer.title,\n        visible: layer.visible,\n        opacity: layer.opacity,\n        style: layer.style,\n        filter: layer.filter || null,\n        // Vrstva souboru s v\u00EDce vrstvami \u2014 p\u0159i obnov\u011B mapy ur\u010D\u00ED, kterou kreslit.\n        ...(layer.layerKey !== null && layer.layerKey !== undefined ? { layer: layer.layerKey } : {}),\n        // \u010C\u00E1st hybridn\u00ED polo\u017Eky (vektor / rastr).\n        ...(layer.hybridPart ? { hybridPart: layer.hybridPart } : {}),\n        ...(layer.legendCollapsed ? { legendCollapsed: true } : {}),\n        ...zoomLimits,\n    };\n}\n", "/**\n * @module ol/CollectionEventType\n */\n\n/**\n * @enum {string}\n */\nexport default {\n  /**\n   * Triggered when an item is added to the collection.\n   * @event module:ol/Collection.CollectionEvent#add\n   * @api\n   */\n  ADD: 'add',\n  /**\n   * Triggered when an item is removed from the collection.\n   * @event module:ol/Collection.CollectionEvent#remove\n   * @api\n   */\n  REMOVE: 'remove',\n};\n", "/**\n * @module ol/ObjectEventType\n */\n\n/**\n * @enum {string}\n */\nexport default {\n  /**\n   * Triggered when a property is changed.\n   * @event module:ol/Object.ObjectEvent#propertychange\n   * @api\n   */\n  PROPERTYCHANGE: 'propertychange',\n};\n\n/**\n * @typedef {'propertychange'} Types\n */\n", "/**\n * @module ol/obj\n */\n\n/**\n * Removes all properties from an object.\n * @param {Object<string, unknown>} object The object to clear.\n */\nexport function clear(object) {\n  for (const property in object) {\n    delete object[property];\n  }\n}\n\n/**\n * Determine if an object has any properties.\n * @param {Object} object The object to check.\n * @return {boolean} The object is empty.\n */\nexport function isEmpty(object) {\n  let property;\n  for (property in object) {\n    return false;\n  }\n  return !property;\n}\n", "/**\n * @module ol/events\n */\nimport {clear} from './obj.js';\n\n/**\n * Key to use with {@link module:ol/Observable.unByKey}.\n * @typedef {Object} EventsKey\n * @property {ListenerFunction} listener Listener.\n * @property {import(\"./events/Target.js\").EventTargetLike} target Target.\n * @property {string} type Type.\n * @api\n */\n\n/**\n * Listener function. This function is called with an event object as argument.\n * When the function returns `false`, event propagation will stop.\n *\n * @typedef {function((Event|import(\"./events/Event.js\").default)): (void|boolean)} ListenerFunction\n * @api\n */\n\n/**\n * @typedef {Object} ListenerObject\n * @property {ListenerFunction} handleEvent HandleEvent listener function.\n */\n\n/**\n * @typedef {ListenerFunction|ListenerObject} Listener\n */\n\n/**\n * Registers an event listener on an event target. Inspired by\n * https://google.github.io/closure-library/api/source/closure/goog/events/events.js.src.html\n *\n * This function efficiently binds a `listener` to a `this` object, and returns\n * a key for use with {@link module:ol/events.unlistenByKey}.\n *\n * @param {import(\"./events/Target.js\").EventTargetLike} target Event target.\n * @param {string} type Event type.\n * @param {ListenerFunction} listener Listener.\n * @param {Object} [thisArg] Object referenced by the `this` keyword in the\n *     listener. Default is the `target`.\n * @param {boolean} [once] If true, add the listener as one-off listener.\n * @return {EventsKey} Unique key for the listener.\n */\nexport function listen(target, type, listener, thisArg, once) {\n  if (once) {\n    const originalListener = listener;\n    /**\n     * @param {Event|import('./events/Event.js').default} event The event\n     * @return {void|boolean} When the function returns `false`, event propagation will stop.\n     * @this {typeof target}\n     */\n    listener = function (event) {\n      target.removeEventListener(type, listener);\n      return originalListener.call(thisArg ?? this, event);\n    };\n  } else if (thisArg && thisArg !== target) {\n    listener = listener.bind(thisArg);\n  }\n  const eventsKey = {\n    target: target,\n    type: type,\n    listener: listener,\n  };\n  target.addEventListener(type, listener);\n  return eventsKey;\n}\n\n/**\n * Registers a one-off event listener on an event target. Inspired by\n * https://google.github.io/closure-library/api/source/closure/goog/events/events.js.src.html\n *\n * This function efficiently binds a `listener` as self-unregistering listener\n * to a `this` object, and returns a key for use with\n * {@link module:ol/events.unlistenByKey} in case the listener needs to be\n * unregistered before it is called.\n *\n * When {@link module:ol/events.listen} is called with the same arguments after this\n * function, the self-unregistering listener will be turned into a permanent\n * listener.\n *\n * @param {import(\"./events/Target.js\").EventTargetLike} target Event target.\n * @param {string} type Event type.\n * @param {ListenerFunction} listener Listener.\n * @param {Object} [thisArg] Object referenced by the `this` keyword in the\n *     listener. Default is the `target`.\n * @return {EventsKey} Key for unlistenByKey.\n */\nexport function listenOnce(target, type, listener, thisArg) {\n  return listen(target, type, listener, thisArg, true);\n}\n\n/**\n * Unregisters event listeners on an event target. Inspired by\n * https://google.github.io/closure-library/api/source/closure/goog/events/events.js.src.html\n *\n * The argument passed to this function is the key returned from\n * {@link module:ol/events.listen} or {@link module:ol/events.listenOnce}.\n *\n * @param {EventsKey} key The key.\n */\nexport function unlistenByKey(key) {\n  if (key && key.target) {\n    key.target.removeEventListener(key.type, key.listener);\n    clear(key);\n  }\n}\n", "/**\n * @module ol/events/EventType\n */\n\n/**\n * @enum {string}\n * @const\n */\nexport default {\n  /**\n   * Generic change event. Triggered when the revision counter is increased.\n   * @event module:ol/events/Event~BaseEvent#change\n   * @api\n   */\n  CHANGE: 'change',\n\n  /**\n   * Generic error event. Triggered when an error occurs.\n   * @event module:ol/events/Event~BaseEvent#error\n   * @api\n   */\n  ERROR: 'error',\n\n  BLUR: 'blur',\n  CLEAR: 'clear',\n  CONTEXTMENU: 'contextmenu',\n  CLICK: 'click',\n  DBLCLICK: 'dblclick',\n  DRAGENTER: 'dragenter',\n  DRAGOVER: 'dragover',\n  DROP: 'drop',\n  FOCUS: 'focus',\n  KEYDOWN: 'keydown',\n  KEYPRESS: 'keypress',\n  LOAD: 'load',\n  RESIZE: 'resize',\n  TOUCHMOVE: 'touchmove',\n  WHEEL: 'wheel',\n};\n", "/**\n * @module ol/Disposable\n */\n\n/**\n * @classdesc\n * Objects that need to clean up after themselves.\n */\nclass Disposable {\n  constructor() {\n    /**\n     * The object has already been disposed.\n     * @type {boolean}\n     * @protected\n     */\n    this.disposed = false;\n  }\n\n  /**\n   * Clean up.\n   */\n  dispose() {\n    if (!this.disposed) {\n      this.disposed = true;\n      this.disposeInternal();\n    }\n  }\n\n  /**\n   * Extension point for disposable objects.\n   * @protected\n   */\n  disposeInternal() {}\n}\n\nexport default Disposable;\n", "/**\n * @module ol/array\n */\n\n/**\n * Performs a binary search on the provided sorted list and returns the index of the item if found. If it can't be found it'll return -1.\n * https://github.com/darkskyapp/binary-search\n *\n * @param {Array<*>} haystack Items to search through.\n * @param {*} needle The item to look for.\n * @param {Function} [comparator] Comparator function.\n * @return {number} The index of the item if found, -1 if not.\n */\nexport function binarySearch(haystack, needle, comparator) {\n  let mid, cmp;\n  comparator = comparator || ascending;\n  let low = 0;\n  let high = haystack.length;\n  let found = false;\n\n  while (low < high) {\n    /* Note that \"(low + high) >>> 1\" may overflow, and results in a typecast\n     * to double (which gives the wrong results). */\n    mid = low + ((high - low) >> 1);\n    cmp = +comparator(haystack[mid], needle);\n\n    if (cmp < 0.0) {\n      /* Too low. */\n      low = mid + 1;\n    } else {\n      /* Key found or too high */\n      high = mid;\n      found = !cmp;\n    }\n  }\n\n  /* Key not found. */\n  return found ? low : ~low;\n}\n\n/**\n * Compare function sorting arrays in ascending order.  Safe to use for numeric values.\n * @param {*} a The first object to be compared.\n * @param {*} b The second object to be compared.\n * @return {number} A negative number, zero, or a positive number as the first\n *     argument is less than, equal to, or greater than the second.\n */\nexport function ascending(a, b) {\n  return a > b ? 1 : a < b ? -1 : 0;\n}\n\n/**\n * Compare function sorting arrays in descending order.  Safe to use for numeric values.\n * @param {*} a The first object to be compared.\n * @param {*} b The second object to be compared.\n * @return {number} A negative number, zero, or a positive number as the first\n *     argument is greater than, equal to, or less than the second.\n */\nexport function descending(a, b) {\n  return a < b ? 1 : a > b ? -1 : 0;\n}\n\n/**\n * {@link module:ol/tilegrid/TileGrid~TileGrid#getZForResolution} can use a function\n * of this type to determine which nearest resolution to use.\n *\n * This function takes a `{number}` representing a value between two array entries,\n * a `{number}` representing the value of the nearest higher entry and\n * a `{number}` representing the value of the nearest lower entry\n * as arguments and returns a `{number}`. If a negative number or zero is returned\n * the lower value will be used, if a positive number is returned the higher value\n * will be used.\n * @typedef {function(number, number, number): number} NearestDirectionFunction\n * @api\n */\n\n/**\n * @param {Array<number>} arr Array in descending order.\n * @param {number} target Target.\n * @param {number|NearestDirectionFunction} direction\n *    0 means return the nearest,\n *    > 0 means return the largest nearest,\n *    < 0 means return the smallest nearest.\n * @return {number} Index.\n */\nexport function linearFindNearest(arr, target, direction) {\n  if (arr[0] <= target) {\n    return 0;\n  }\n\n  const n = arr.length;\n  if (target <= arr[n - 1]) {\n    return n - 1;\n  }\n\n  if (typeof direction === 'function') {\n    for (let i = 1; i < n; ++i) {\n      const candidate = arr[i];\n      if (candidate === target) {\n        return i;\n      }\n      if (candidate < target) {\n        if (direction(target, arr[i - 1], candidate) > 0) {\n          return i - 1;\n        }\n        return i;\n      }\n    }\n    return n - 1;\n  }\n\n  if (direction > 0) {\n    for (let i = 1; i < n; ++i) {\n      if (arr[i] < target) {\n        return i - 1;\n      }\n    }\n    return n - 1;\n  }\n\n  if (direction < 0) {\n    for (let i = 1; i < n; ++i) {\n      if (arr[i] <= target) {\n        return i;\n      }\n    }\n    return n - 1;\n  }\n\n  for (let i = 1; i < n; ++i) {\n    if (arr[i] == target) {\n      return i;\n    }\n    if (arr[i] < target) {\n      if (arr[i - 1] - target < target - arr[i]) {\n        return i - 1;\n      }\n      return i;\n    }\n  }\n  return n - 1;\n}\n\n/**\n * @param {Array<*>} arr Array.\n * @param {number} begin Begin index.\n * @param {number} end End index.\n */\nexport function reverseSubArray(arr, begin, end) {\n  while (begin < end) {\n    const tmp = arr[begin];\n    arr[begin] = arr[end];\n    arr[end] = tmp;\n    ++begin;\n    --end;\n  }\n}\n\n/**\n * @param {Array<VALUE>} arr The array to modify.\n * @param {!Array<VALUE>|VALUE} data The elements or arrays of elements to add to arr.\n * @template VALUE\n */\nexport function extend(arr, data) {\n  const extension = Array.isArray(data) ? data : [data];\n  const length = extension.length;\n  for (let i = 0; i < length; i++) {\n    arr[arr.length] = extension[i];\n  }\n}\n\n/**\n * @param {Array<VALUE>} arr The array to modify.\n * @param {VALUE} obj The element to remove.\n * @template VALUE\n * @return {boolean} If the element was removed.\n */\nexport function remove(arr, obj) {\n  const i = arr.indexOf(obj);\n  const found = i > -1;\n  if (found) {\n    arr.splice(i, 1);\n  }\n  return found;\n}\n\n/**\n * @param {Array<any>|Uint8ClampedArray} arr1 The first array to compare.\n * @param {Array<any>|Uint8ClampedArray} arr2 The second array to compare.\n * @return {boolean} Whether the two arrays are equal.\n */\nexport function equals(arr1, arr2) {\n  const len1 = arr1.length;\n  if (len1 !== arr2.length) {\n    return false;\n  }\n  for (let i = 0; i < len1; i++) {\n    if (arr1[i] !== arr2[i]) {\n      return false;\n    }\n  }\n  return true;\n}\n\n/**\n * Sort the passed array such that the relative order of equal elements is preserved.\n * See https://en.wikipedia.org/wiki/Sorting_algorithm#Stability for details.\n * @param {Array<*>} arr The array to sort (modifies original).\n * @param {!function(*, *): number} compareFnc Comparison function.\n * @api\n * @deprecated\n */\nexport function stableSort(arr, compareFnc) {\n  const length = arr.length;\n  const tmp = Array(arr.length);\n  let i;\n  for (i = 0; i < length; i++) {\n    tmp[i] = {index: i, value: arr[i]};\n  }\n  tmp.sort(function (a, b) {\n    return compareFnc(a.value, b.value) || a.index - b.index;\n  });\n  for (i = 0; i < arr.length; i++) {\n    arr[i] = tmp[i].value;\n  }\n}\n\n/**\n * @param {Array<*>} arr The array to test.\n * @param {Function} [func] Comparison function.\n * @param {boolean} [strict] Strictly sorted (default false).\n * @return {boolean} Return index.\n */\nexport function isSorted(arr, func, strict) {\n  const compare = func || ascending;\n  return arr.every(function (currentVal, index) {\n    if (index === 0) {\n      return true;\n    }\n    const res = compare(arr[index - 1], currentVal);\n    return !(res > 0 || (strict && res === 0));\n  });\n}\n", "/**\n * @module ol/functions\n */\n\nimport {equals as arrayEquals} from './array.js';\n\n/**\n * Always returns true.\n * @return {boolean} true.\n */\nexport function TRUE() {\n  return true;\n}\n\n/**\n * Always returns false.\n * @return {boolean} false.\n */\nexport function FALSE() {\n  return false;\n}\n\n/**\n * A reusable function, used e.g. as a default for callbacks.\n *\n * @return {void} Nothing.\n */\nexport function VOID() {}\n\n/**\n * Wrap a function in another function that remembers the last return.  If the\n * returned function is called twice in a row with the same arguments and the same\n * this object, it will return the value from the first call in the second call.\n *\n * @param {function(...any): ReturnType} fn The function to memoize.\n * @return {function(...any): ReturnType} The memoized function.\n * @template ReturnType\n */\nexport function memoizeOne(fn) {\n  /** @type {ReturnType} */\n  let lastResult;\n\n  /** @type {Array<any>|undefined} */\n  let lastArgs;\n\n  let lastThis;\n\n  /**\n   * @this {*} Only need to know if `this` changed, don't care what type\n   * @return {ReturnType} Memoized value\n   */\n  return function () {\n    const nextArgs = Array.prototype.slice.call(arguments);\n    if (!lastArgs || this !== lastThis || !arrayEquals(nextArgs, lastArgs)) {\n      lastThis = this;\n      lastArgs = nextArgs;\n      lastResult = fn.apply(this, arguments);\n    }\n    return lastResult;\n  };\n}\n\n/**\n * @template T\n * @param {function(): (T | Promise<T>)} getter A function that returns a value or a promise for a value.\n * @return {Promise<T>} A promise for the value.\n */\nexport function toPromise(getter) {\n  function promiseGetter() {\n    let value;\n    try {\n      value = getter();\n    } catch (err) {\n      return Promise.reject(err);\n    }\n    if (value instanceof Promise) {\n      return value;\n    }\n    return Promise.resolve(value);\n  }\n  return promiseGetter();\n}\n", "/**\n * @module ol/events/Event\n */\n\n/**\n * @classdesc\n * Stripped down implementation of the W3C DOM Level 2 Event interface.\n * See https://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-interface.\n *\n * This implementation only provides `type` and `target` properties, and\n * `stopPropagation` and `preventDefault` methods. It is meant as base class\n * for higher level events defined in the library, and works with\n * {@link module:ol/events/Target~Target}.\n */\nclass BaseEvent {\n  /**\n   * @param {string} type Type.\n   */\n  constructor(type) {\n    /**\n     * @type {boolean}\n     */\n    this.propagationStopped;\n\n    /**\n     * @type {boolean}\n     */\n    this.defaultPrevented;\n\n    /**\n     * The event type.\n     * @type {string}\n     * @api\n     */\n    this.type = type;\n\n    /**\n     * The event target.\n     * @type {Object}\n     * @api\n     */\n    this.target = null;\n  }\n\n  /**\n   * Prevent default. This means that no emulated `click`, `singleclick` or `doubleclick` events\n   * will be fired.\n   * @api\n   */\n  preventDefault() {\n    this.defaultPrevented = true;\n  }\n\n  /**\n   * Stop event propagation.\n   * @api\n   */\n  stopPropagation() {\n    this.propagationStopped = true;\n  }\n}\n\n/**\n * @param {Event|import(\"./Event.js\").default} evt Event\n */\nexport function stopPropagation(evt) {\n  evt.stopPropagation();\n}\n\n/**\n * @param {Event|import(\"./Event.js\").default} evt Event\n */\nexport function preventDefault(evt) {\n  evt.preventDefault();\n}\n\nexport default BaseEvent;\n", "/**\n * @module ol/events/Target\n */\nimport Disposable from '../Disposable.js';\nimport {VOID} from '../functions.js';\nimport {clear} from '../obj.js';\nimport Event from './Event.js';\n\n/**\n * @typedef {EventTarget|Target} EventTargetLike\n */\n\n/**\n * @classdesc\n * A simplified implementation of the W3C DOM Level 2 EventTarget interface.\n * See https://www.w3.org/TR/2000/REC-DOM-Level-2-Events-20001113/events.html#Events-EventTarget.\n *\n * There are two important simplifications compared to the specification:\n *\n * 1. The handling of `useCapture` in `addEventListener` and\n *    `removeEventListener`. There is no real capture model.\n * 2. The handling of `stopPropagation` and `preventDefault` on `dispatchEvent`.\n *    There is no event target hierarchy. When a listener calls\n *    `stopPropagation` or `preventDefault` on an event object, it means that no\n *    more listeners after this one will be called. Same as when the listener\n *    returns false.\n */\nclass Target extends Disposable {\n  /**\n   * @param {*} [target] Default event target for dispatched events.\n   */\n  constructor(target) {\n    super();\n\n    /**\n     * @private\n     * @type {*}\n     */\n    this.eventTarget_ = target;\n\n    /**\n     * @private\n     * @type {Object<string, number>|null}\n     */\n    this.pendingRemovals_ = null;\n\n    /**\n     * @private\n     * @type {Object<string, number>|null}\n     */\n    this.dispatching_ = null;\n\n    /**\n     * @private\n     * @type {Object<string, Array<import(\"../events.js\").Listener>>|null}\n     */\n    this.listeners_ = null;\n  }\n\n  /**\n   * @param {string} type Type.\n   * @param {import(\"../events.js\").Listener} listener Listener.\n   */\n  addEventListener(type, listener) {\n    if (!type || !listener) {\n      return;\n    }\n    const listeners = this.listeners_ || (this.listeners_ = {});\n    const listenersForType = listeners[type] || (listeners[type] = []);\n    if (!listenersForType.includes(listener)) {\n      listenersForType.push(listener);\n    }\n  }\n\n  /**\n   * Dispatches an event and calls all listeners listening for events\n   * of this type. The event parameter can either be a string or an\n   * Object with a `type` property.\n   *\n   * @param {import(\"./Event.js\").default|string} event Event object.\n   * @return {boolean|undefined} `false` if anyone called preventDefault on the\n   *     event object or if any of the listeners returned false.\n   * @api\n   */\n  dispatchEvent(event) {\n    const isString = typeof event === 'string';\n    const type = isString ? event : event.type;\n    const listeners = this.listeners_ && this.listeners_[type];\n    if (!listeners) {\n      return;\n    }\n\n    const evt = isString ? new Event(event) : /** @type {Event} */ (event);\n    if (!evt.target) {\n      evt.target = this.eventTarget_ || this;\n    }\n    const dispatching = this.dispatching_ || (this.dispatching_ = {});\n    const pendingRemovals =\n      this.pendingRemovals_ || (this.pendingRemovals_ = {});\n    if (!(type in dispatching)) {\n      dispatching[type] = 0;\n      pendingRemovals[type] = 0;\n    }\n    ++dispatching[type];\n    let propagate;\n    for (let i = 0, ii = listeners.length; i < ii; ++i) {\n      if ('handleEvent' in listeners[i]) {\n        propagate = /** @type {import(\"../events.js\").ListenerObject} */ (\n          listeners[i]\n        ).handleEvent(evt);\n      } else {\n        propagate = /** @type {import(\"../events.js\").ListenerFunction} */ (\n          listeners[i]\n        ).call(this, evt);\n      }\n      if (propagate === false || evt.propagationStopped) {\n        propagate = false;\n        break;\n      }\n    }\n    if (--dispatching[type] === 0) {\n      let pr = pendingRemovals[type];\n      delete pendingRemovals[type];\n      while (pr--) {\n        this.removeEventListener(type, VOID);\n      }\n      delete dispatching[type];\n    }\n    return propagate;\n  }\n\n  /**\n   * Clean up.\n   * @override\n   */\n  disposeInternal() {\n    this.listeners_ && clear(this.listeners_);\n  }\n\n  /**\n   * Get the listeners for a specified event type. Listeners are returned in the\n   * order that they will be called in.\n   *\n   * @param {string} type Type.\n   * @return {Array<import(\"../events.js\").Listener>|undefined} Listeners.\n   */\n  getListeners(type) {\n    return (this.listeners_ && this.listeners_[type]) || undefined;\n  }\n\n  /**\n   * @param {string} [type] Type. If not provided,\n   *     `true` will be returned if this event target has any listeners.\n   * @return {boolean} Has listeners.\n   */\n  hasListener(type) {\n    if (!this.listeners_) {\n      return false;\n    }\n    return type\n      ? type in this.listeners_\n      : Object.keys(this.listeners_).length > 0;\n  }\n\n  /**\n   * @param {string} type Type.\n   * @param {import(\"../events.js\").Listener} listener Listener.\n   */\n  removeEventListener(type, listener) {\n    if (!this.listeners_) {\n      return;\n    }\n    const listeners = this.listeners_[type];\n    if (!listeners) {\n      return;\n    }\n    const index = listeners.indexOf(listener);\n    if (index !== -1) {\n      if (this.pendingRemovals_ && type in this.pendingRemovals_) {\n        // make listener a no-op, and remove later in #dispatchEvent()\n        listeners[index] = VOID;\n        ++this.pendingRemovals_[type];\n      } else {\n        listeners.splice(index, 1);\n        if (listeners.length === 0) {\n          delete this.listeners_[type];\n        }\n      }\n    }\n  }\n}\n\nexport default Target;\n", "/**\n * @module ol/Observable\n */\nimport {listen, listenOnce, unlistenByKey} from './events.js';\nimport EventType from './events/EventType.js';\nimport EventTarget from './events/Target.js';\n\n/***\n * @template {string} Type\n * @template {Event|import(\"./events/Event.js\").default} EventClass\n * @template Return\n * @typedef {(type: Type, listener: (event: EventClass) => ?) => Return} OnSignature\n */\n\n/***\n * @template {string} Type\n * @template Return\n * @typedef {(type: Type[], listener: (event: Event|import(\"./events/Event.js\").default) => ?) => Return extends void ? void : Return[]} CombinedOnSignature\n */\n\n/**\n * @typedef {'change'|'error'} EventTypes\n */\n\n/***\n * @template Return\n * @typedef {OnSignature<EventTypes, import(\"./events/Event.js\").default, Return> & CombinedOnSignature<EventTypes, Return>} ObservableOnSignature\n */\n\n/**\n * @classdesc\n * Abstract base class; normally only used for creating subclasses and not\n * instantiated in apps.\n * An event target providing convenient methods for listener registration\n * and unregistration. A generic `change` event is always available through\n * {@link module:ol/Observable~Observable#changed}.\n *\n * @fires import(\"./events/Event.js\").default\n * @api\n */\nclass Observable extends EventTarget {\n  constructor() {\n    super();\n\n    this.on =\n      /** @type {ObservableOnSignature<import(\"./events.js\").EventsKey>} */ (\n        this.onInternal\n      );\n\n    this.once =\n      /** @type {ObservableOnSignature<import(\"./events.js\").EventsKey>} */ (\n        this.onceInternal\n      );\n\n    this.un = /** @type {ObservableOnSignature<void>} */ (this.unInternal);\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.revision_ = 0;\n  }\n\n  /**\n   * Increases the revision counter and dispatches a 'change' event.\n   * @api\n   */\n  changed() {\n    ++this.revision_;\n    this.dispatchEvent(EventType.CHANGE);\n  }\n\n  /**\n   * Get the version number for this object.  Each time the object is modified,\n   * its version number will be incremented.\n   * @return {number} Revision.\n   * @api\n   */\n  getRevision() {\n    return this.revision_;\n  }\n\n  /**\n   * @param {string|Array<string>} type Type.\n   * @param {function((Event|import(\"./events/Event.js\").default)): ?} listener Listener.\n   * @return {import(\"./events.js\").EventsKey|Array<import(\"./events.js\").EventsKey>} Event key.\n   * @protected\n   */\n  onInternal(type, listener) {\n    if (Array.isArray(type)) {\n      const len = type.length;\n      const keys = new Array(len);\n      for (let i = 0; i < len; ++i) {\n        keys[i] = listen(this, type[i], listener);\n      }\n      return keys;\n    }\n    return listen(this, /** @type {string} */ (type), listener);\n  }\n\n  /**\n   * @param {string|Array<string>} type Type.\n   * @param {function((Event|import(\"./events/Event.js\").default)): ?} listener Listener.\n   * @return {import(\"./events.js\").EventsKey|Array<import(\"./events.js\").EventsKey>} Event key.\n   * @protected\n   */\n  onceInternal(type, listener) {\n    let key;\n    if (Array.isArray(type)) {\n      const len = type.length;\n      key = new Array(len);\n      for (let i = 0; i < len; ++i) {\n        key[i] = listenOnce(this, type[i], listener);\n      }\n    } else {\n      key = listenOnce(this, /** @type {string} */ (type), listener);\n    }\n    /** @type {Object} */ (listener).ol_key = key;\n    return key;\n  }\n\n  /**\n   * Unlisten for a certain type of event.\n   * @param {string|Array<string>} type Type.\n   * @param {function((Event|import(\"./events/Event.js\").default)): ?} listener Listener.\n   * @protected\n   */\n  unInternal(type, listener) {\n    const key = /** @type {Object} */ (listener).ol_key;\n    if (key) {\n      unByKey(key);\n    } else if (Array.isArray(type)) {\n      for (let i = 0, ii = type.length; i < ii; ++i) {\n        this.removeEventListener(type[i], listener);\n      }\n    } else {\n      this.removeEventListener(type, listener);\n    }\n  }\n}\n\n/**\n * Listen for a certain type of event.\n * @function\n * @param {string|Array<string>} type The event type or array of event types.\n * @param {function((Event|import(\"./events/Event.js\").default)): ?} listener The listener function.\n * @return {import(\"./events.js\").EventsKey|Array<import(\"./events.js\").EventsKey>} Unique key for the listener. If\n *     called with an array of event types as the first argument, the return\n *     will be an array of keys.\n * @api\n */\nObservable.prototype.on;\n\n/**\n * Listen once for a certain type of event.\n * @function\n * @param {string|Array<string>} type The event type or array of event types.\n * @param {function((Event|import(\"./events/Event.js\").default)): ?} listener The listener function.\n * @return {import(\"./events.js\").EventsKey|Array<import(\"./events.js\").EventsKey>} Unique key for the listener. If\n *     called with an array of event types as the first argument, the return\n *     will be an array of keys.\n * @api\n */\nObservable.prototype.once;\n\n/**\n * Unlisten for a certain type of event.\n * @function\n * @param {string|Array<string>} type The event type or array of event types.\n * @param {function((Event|import(\"./events/Event.js\").default)): ?} listener The listener function.\n * @api\n */\nObservable.prototype.un;\n\n/**\n * Removes an event listener using the key returned by `on()` or `once()`.\n * @param {import(\"./events.js\").EventsKey|Array<import(\"./events.js\").EventsKey>} key The key returned by `on()`\n *     or `once()` (or an array of keys).\n * @api\n */\nexport function unByKey(key) {\n  if (Array.isArray(key)) {\n    for (let i = 0, ii = key.length; i < ii; ++i) {\n      unlistenByKey(key[i]);\n    }\n  } else {\n    unlistenByKey(/** @type {import(\"./events.js\").EventsKey} */ (key));\n  }\n}\n\nexport default Observable;\n", "/**\n * @module ol/util\n */\n\n/**\n * @return {never} Any return.\n */\nexport function abstract() {\n  throw new Error('Unimplemented abstract method.');\n}\n\n/**\n * Counter for getUid.\n * @type {number}\n * @private\n */\nlet uidCounter_ = 0;\n\n/**\n * Gets a unique ID for an object. This mutates the object so that further calls\n * with the same object as a parameter returns the same value. Unique IDs are generated\n * as a strictly increasing sequence. Adapted from goog.getUid.\n *\n * @param {Object} obj The object to get the unique ID for.\n * @return {string} The unique ID for the object.\n * @api\n */\nexport function getUid(obj) {\n  return obj.ol_uid || (obj.ol_uid = String(++uidCounter_));\n}\n\n/**\n * OpenLayers version.\n * @type {string}\n */\nexport const VERSION = '10.9.0';\n", "/**\n * @module ol/Object\n */\nimport ObjectEventType from './ObjectEventType.js';\nimport Observable from './Observable.js';\nimport Event from './events/Event.js';\nimport {isEmpty} from './obj.js';\nimport {getUid} from './util.js';\n\n/**\n * @classdesc\n * Events emitted by {@link module:ol/Object~BaseObject} instances are instances of this type.\n */\nexport class ObjectEvent extends Event {\n  /**\n   * @param {string} type The event type.\n   * @param {string} key The property name.\n   * @param {*} oldValue The old value for `key`.\n   */\n  constructor(type, key, oldValue) {\n    super(type);\n\n    /**\n     * The name of the property whose value is changing.\n     * @type {string}\n     * @api\n     */\n    this.key = key;\n\n    /**\n     * The old value. To get the new value use `e.target.get(e.key)` where\n     * `e` is the event object.\n     * @type {*}\n     * @api\n     */\n    this.oldValue = oldValue;\n  }\n}\n\n/***\n * @template Return\n * @typedef {import(\"./Observable.js\").OnSignature<import(\"./Observable.js\").EventTypes, import(\"./events/Event.js\").default, Return> &\n *    import(\"./Observable.js\").OnSignature<import(\"./ObjectEventType.js\").Types, ObjectEvent, Return> &\n *    import(\"./Observable.js\").CombinedOnSignature<import(\"./Observable.js\").EventTypes|import(\"./ObjectEventType.js\").Types, Return>} ObjectOnSignature\n */\n\n/**\n * @classdesc\n * Abstract base class; normally only used for creating subclasses and not\n * instantiated in apps.\n * Most non-trivial classes inherit from this.\n *\n * This extends {@link module:ol/Observable~Observable} with observable\n * properties, where each property is observable as well as the object as a\n * whole.\n *\n * Classes that inherit from this have pre-defined properties, to which you can\n * add your owns. The pre-defined properties are listed in this documentation as\n * 'Observable Properties', and have their own accessors; for example,\n * {@link module:ol/Map~Map} has a `target` property, accessed with\n * `getTarget()` and changed with `setTarget()`. Not all properties are however\n * settable. There are also general-purpose accessors `get()` and `set()`. For\n * example, `get('target')` is equivalent to `getTarget()`.\n *\n * The `set` accessors trigger a change event, and you can monitor this by\n * registering a listener. For example, {@link module:ol/View~View} has a\n * `center` property, so `view.on('change:center', function(evt) {...});` would\n * call the function whenever the value of the center property changes. Within\n * the function, `evt.target` would be the view, so `evt.target.getCenter()`\n * would return the new center.\n *\n * You can add your own observable properties with\n * `object.set('prop', 'value')`, and retrieve that with `object.get('prop')`.\n * You can listen for changes on that property value with\n * `object.on('change:prop', listener)`. You can get a list of all\n * properties with {@link module:ol/Object~BaseObject#getProperties}.\n *\n * Note that the observable properties are separate from standard JS properties.\n * You can, for example, give your map object a title with\n * `map.title='New title'` and with `map.set('title', 'Another title')`. The\n * first will be a `hasOwnProperty`; the second will appear in\n * `getProperties()`. Only the second is observable.\n *\n * Properties can be deleted by using the unset method. E.g.\n * object.unset('foo').\n *\n * @fires ObjectEvent\n * @template {Object<string, *>} [Properties=Object<string, *>]\n * @api\n */\nclass BaseObject extends Observable {\n  /**\n   * @param {NoInfer<Properties>} [values] An object with key-value pairs.\n   */\n  constructor(values) {\n    super();\n\n    /***\n     * @type {ObjectOnSignature<import(\"./events.js\").EventsKey>}\n     */\n    this.on;\n\n    /***\n     * @type {ObjectOnSignature<import(\"./events.js\").EventsKey>}\n     */\n    this.once;\n\n    /***\n     * @type {ObjectOnSignature<void>}\n     */\n    this.un;\n\n    // Call {@link module:ol/util.getUid} to ensure that the order of objects' ids is\n    // the same as the order in which they were created.  This also helps to\n    // ensure that object properties are always added in the same order, which\n    // helps many JavaScript engines generate faster code.\n    getUid(this);\n\n    /**\n     * @private\n     * @type {Partial<NoInfer<Properties>>|null}\n     */\n    this.values_ = null;\n\n    if (values !== undefined) {\n      this.setProperties(values);\n    }\n  }\n\n  /**\n   * Gets a value.\n   * @param {string} key Key name.\n   * @return {*} Value.\n   * @api\n   */\n  get(key) {\n    let value;\n    if (this.values_ && this.values_.hasOwnProperty(key)) {\n      value = this.values_[key];\n    }\n    return value;\n  }\n\n  /**\n   * Get a list of object property names.\n   * @return {Array<string>} List of property names.\n   * @api\n   */\n  getKeys() {\n    return (this.values_ && Object.keys(this.values_)) || [];\n  }\n\n  /**\n   * Get an object of all property names and values.\n   * @return {NoInfer<Properties>} Object.\n   * @api\n   */\n  getProperties() {\n    return /** @type {NoInfer<Properties>} */ (\n      (this.values_ && Object.assign({}, this.values_)) || {}\n    );\n  }\n\n  /**\n   * Get an object of all property names and values.\n   * @return {Partial<NoInfer<Properties>>?} Object.\n   */\n  getPropertiesInternal() {\n    return this.values_;\n  }\n\n  /**\n   * @return {boolean} The object has properties.\n   */\n  hasProperties() {\n    return !!this.values_;\n  }\n\n  /**\n   * @param {string} key Key name.\n   * @param {*} oldValue Old value.\n   */\n  notify(key, oldValue) {\n    let eventType;\n    eventType = `change:${key}`;\n    if (this.hasListener(eventType)) {\n      this.dispatchEvent(new ObjectEvent(eventType, key, oldValue));\n    }\n    eventType = ObjectEventType.PROPERTYCHANGE;\n    if (this.hasListener(eventType)) {\n      this.dispatchEvent(new ObjectEvent(eventType, key, oldValue));\n    }\n  }\n\n  /**\n   * @param {string} key Key name.\n   * @param {import(\"./events.js\").Listener} listener Listener.\n   */\n  addChangeListener(key, listener) {\n    this.addEventListener(`change:${key}`, listener);\n  }\n\n  /**\n   * @param {string} key Key name.\n   * @param {import(\"./events.js\").Listener} listener Listener.\n   */\n  removeChangeListener(key, listener) {\n    this.removeEventListener(`change:${key}`, listener);\n  }\n\n  /**\n   * Sets a value.\n   * @param {string} key Key name.\n   * @param {*} value Value.\n   * @param {boolean} [silent] Update without triggering an event.\n   * @api\n   */\n  set(key, value, silent) {\n    const values = this.values_ || (this.values_ = {});\n    if (silent) {\n      values[key] = value;\n    } else {\n      const oldValue = values[key];\n      values[key] = value;\n      if (oldValue !== value) {\n        this.notify(key, oldValue);\n      }\n    }\n  }\n\n  /**\n   * Sets a collection of key-value pairs.  Note that this changes any existing\n   * properties and adds new ones (it does not remove any existing properties).\n   * @param {Partial<NoInfer<Properties>>} values Values.\n   * @param {boolean} [silent] Update without triggering an event.\n   * @api\n   */\n  setProperties(values, silent) {\n    for (const key in values) {\n      this.set(key, values[key], silent);\n    }\n  }\n\n  /**\n   * Apply any properties from another object without triggering events.\n   * @param {BaseObject} source The source object.\n   * @protected\n   */\n  applyProperties(source) {\n    if (!source.values_) {\n      return;\n    }\n    Object.assign(this.values_ || (this.values_ = {}), source.values_);\n  }\n\n  /**\n   * Unsets a property.\n   * @param {string} key Key name.\n   * @param {boolean} [silent] Unset without triggering an event.\n   * @api\n   */\n  unset(key, silent) {\n    if (this.values_ && key in this.values_) {\n      const oldValue = this.values_[key];\n      delete this.values_[key];\n      if (isEmpty(this.values_)) {\n        this.values_ = null;\n      }\n      if (!silent) {\n        this.notify(key, oldValue);\n      }\n    }\n  }\n}\n\nexport default BaseObject;\n", "/**\n * @module ol/Collection\n */\nimport CollectionEventType from './CollectionEventType.js';\nimport BaseObject from './Object.js';\nimport Event from './events/Event.js';\n\n/**\n * @enum {string}\n * @private\n */\nconst Property = {\n  LENGTH: 'length',\n};\n\n/**\n * @classdesc\n * Events emitted by {@link module:ol/Collection~Collection} instances are instances of this\n * type.\n * @template T\n */\nexport class CollectionEvent extends Event {\n  /**\n   * @param {import(\"./CollectionEventType.js\").default} type Type.\n   * @param {T} element Element.\n   * @param {number} index The index of the added or removed element.\n   */\n  constructor(type, element, index) {\n    super(type);\n\n    /**\n     * The element that is added to or removed from the collection.\n     * @type {T}\n     * @api\n     */\n    this.element = element;\n\n    /**\n     * The index of the added or removed element.\n     * @type {number}\n     * @api\n     */\n    this.index = index;\n  }\n}\n\n/***\n * @template T\n * @template Return\n * @typedef {import(\"./Observable.js\").OnSignature<import(\"./Observable.js\").EventTypes, import(\"./events/Event.js\").default, Return> &\n *   import(\"./Observable.js\").OnSignature<import(\"./ObjectEventType.js\").Types|'change:length', import(\"./Object.js\").ObjectEvent, Return> &\n *   import(\"./Observable.js\").OnSignature<'add'|'remove', CollectionEvent<T>, Return> &\n *   import(\"./Observable.js\").CombinedOnSignature<import(\"./Observable.js\").EventTypes|import(\"./ObjectEventType.js\").Types|\n *     'change:length'|'add'|'remove',Return>} CollectionOnSignature\n */\n\n/**\n * @typedef {Object} Options\n * @property {boolean} [unique=false] Disallow the same item from being added to\n * the collection twice.\n */\n\n/**\n * @classdesc\n * An expanded version of standard JS Array, adding convenience methods for\n * manipulation. Add and remove changes to the Collection trigger a Collection\n * event. Note that this does not cover changes to the objects _within_ the\n * Collection; they trigger events on the appropriate object, not on the\n * Collection as a whole.\n *\n * @fires CollectionEvent\n *\n * @template T\n * @api\n */\nclass Collection extends BaseObject {\n  /**\n   * @param {Array<T>} [array] Array.\n   * @param {Options} [options] Collection options.\n   */\n  constructor(array, options) {\n    super();\n\n    /***\n     * @type {CollectionOnSignature<T, import(\"./events.js\").EventsKey>}\n     */\n    this.on;\n\n    /***\n     * @type {CollectionOnSignature<T, import(\"./events.js\").EventsKey>}\n     */\n    this.once;\n\n    /***\n     * @type {CollectionOnSignature<T, void>}\n     */\n    this.un;\n\n    options = options || {};\n\n    /**\n     * @private\n     * @type {boolean}\n     */\n    this.unique_ = !!options.unique;\n\n    /**\n     * @private\n     * @type {!Array<T>}\n     */\n    this.array_ = array ?? [];\n\n    if (this.unique_) {\n      for (let i = 1, ii = this.array_.length; i < ii; ++i) {\n        this.assertUnique_(this.array_[i], i);\n      }\n    }\n\n    this.updateLength_();\n  }\n\n  /**\n   * Remove all elements from the collection.\n   * @api\n   */\n  clear() {\n    while (this.getLength() > 0) {\n      this.pop();\n    }\n  }\n\n  /**\n   * Add elements to the collection.  This pushes each item in the provided array\n   * to the end of the collection.\n   * @param {!Array<T>} arr Array.\n   * @return {Collection<T>} This collection.\n   * @api\n   */\n  extend(arr) {\n    for (let i = 0, ii = arr.length; i < ii; ++i) {\n      this.push(arr[i]);\n    }\n    return this;\n  }\n\n  /**\n   * Iterate over each element, calling the provided callback.\n   * @param {function(T, number, Array<T>): *} f The function to call\n   *     for every element. This function takes 3 arguments (the element, the\n   *     index and the array). The return value is ignored.\n   * @api\n   */\n  forEach(f) {\n    const array = this.array_;\n    for (let i = 0, ii = array.length; i < ii; ++i) {\n      f(array[i], i, array);\n    }\n  }\n\n  /**\n   * Get a reference to the underlying Array object. Warning: if the array\n   * is mutated, no events will be dispatched by the collection, and the\n   * collection's \"length\" property won't be in sync with the actual length\n   * of the array.\n   * @return {!Array<T>} Array.\n   * @api\n   */\n  getArray() {\n    return this.array_;\n  }\n\n  /**\n   * Get the element at the provided index.\n   * @param {number} index Index.\n   * @return {T} Element.\n   * @api\n   */\n  item(index) {\n    return this.array_[index];\n  }\n\n  /**\n   * Get the length of this collection.\n   * @return {number} The length of the array.\n   * @observable\n   * @api\n   */\n  getLength() {\n    return this.get(Property.LENGTH);\n  }\n\n  /**\n   * Insert an element at the provided index.\n   * @param {number} index Index.\n   * @param {T} elem Element.\n   * @api\n   */\n  insertAt(index, elem) {\n    if (index < 0 || index > this.getLength()) {\n      throw new Error('Index out of bounds: ' + index);\n    }\n    if (this.unique_) {\n      this.assertUnique_(elem);\n    }\n    this.array_.splice(index, 0, elem);\n    this.updateLength_();\n    this.dispatchEvent(\n      new CollectionEvent(CollectionEventType.ADD, elem, index),\n    );\n  }\n\n  /**\n   * Remove the last element of the collection and return it.\n   * Return `undefined` if the collection is empty.\n   * @return {T|undefined} Element.\n   * @api\n   */\n  pop() {\n    return this.removeAt(this.getLength() - 1);\n  }\n\n  /**\n   * Insert the provided element at the end of the collection.\n   * @param {T} elem Element.\n   * @return {number} New length of the collection.\n   * @api\n   */\n  push(elem) {\n    const n = this.getLength();\n    this.insertAt(n, elem);\n    return this.getLength();\n  }\n\n  /**\n   * Remove the first occurrence of an element from the collection.\n   * @param {T} elem Element.\n   * @return {T|undefined} The removed element or undefined if none found.\n   * @api\n   */\n  remove(elem) {\n    const arr = this.array_;\n    for (let i = 0, ii = arr.length; i < ii; ++i) {\n      if (arr[i] === elem) {\n        return this.removeAt(i);\n      }\n    }\n    return undefined;\n  }\n\n  /**\n   * Remove the element at the provided index and return it.\n   * Return `undefined` if the collection does not contain this index.\n   * @param {number} index Index.\n   * @return {T|undefined} Value.\n   * @api\n   */\n  removeAt(index) {\n    if (index < 0 || index >= this.getLength()) {\n      return undefined;\n    }\n    const prev = this.array_[index];\n    this.array_.splice(index, 1);\n    this.updateLength_();\n    this.dispatchEvent(\n      /** @type {CollectionEvent<T>} */ (\n        new CollectionEvent(CollectionEventType.REMOVE, prev, index)\n      ),\n    );\n    return prev;\n  }\n\n  /**\n   * Set the element at the provided index.\n   * @param {number} index Index.\n   * @param {T} elem Element.\n   * @api\n   */\n  setAt(index, elem) {\n    const n = this.getLength();\n    if (index >= n) {\n      this.insertAt(index, elem);\n      return;\n    }\n    if (index < 0) {\n      throw new Error('Index out of bounds: ' + index);\n    }\n    if (this.unique_) {\n      this.assertUnique_(elem, index);\n    }\n    const prev = this.array_[index];\n    this.array_[index] = elem;\n    this.dispatchEvent(\n      /** @type {CollectionEvent<T>} */ (\n        new CollectionEvent(CollectionEventType.REMOVE, prev, index)\n      ),\n    );\n    this.dispatchEvent(\n      /** @type {CollectionEvent<T>} */ (\n        new CollectionEvent(CollectionEventType.ADD, elem, index)\n      ),\n    );\n  }\n\n  /**\n   * @private\n   */\n  updateLength_() {\n    this.set(Property.LENGTH, this.array_.length);\n  }\n\n  /**\n   * @private\n   * @param {T} elem Element.\n   * @param {number} [except] Optional index to ignore.\n   */\n  assertUnique_(elem, except) {\n    const array = this.array_;\n    for (let i = 0, ii = array.length; i < ii; ++i) {\n      if (array[i] === elem && i !== except) {\n        throw new Error('Duplicate item added to a unique collection');\n      }\n    }\n  }\n}\n\nexport default Collection;\n", "/**\n * @module ol/MapEvent\n */\nimport Event from './events/Event.js';\n\n/**\n * @classdesc\n * Events emitted as map events are instances of this type.\n * See {@link module:ol/Map~Map} for which events trigger a map event.\n */\nclass MapEvent extends Event {\n  /**\n   * @param {string} type Event type.\n   * @param {import(\"./Map.js\").default} map Map.\n   * @param {?import(\"./Map.js\").FrameState} [frameState] Frame state.\n   */\n  constructor(type, map, frameState) {\n    super(type);\n\n    /**\n     * The map where the event occurred.\n     * @type {import(\"./Map.js\").default}\n     * @api\n     */\n    this.map = map;\n\n    /**\n     * The frame state at the time of the event.\n     * @type {?import(\"./Map.js\").FrameState}\n     * @api\n     */\n    this.frameState = frameState !== undefined ? frameState : null;\n  }\n}\n\nexport default MapEvent;\n", "/**\n * @module ol/MapBrowserEvent\n */\nimport MapEvent from './MapEvent.js';\n\n/**\n * @classdesc\n * Events emitted as map browser events are instances of this type.\n * See {@link module:ol/Map~Map} for which events trigger a map browser event.\n * @template {PointerEvent|KeyboardEvent|WheelEvent} [EVENT=PointerEvent|KeyboardEvent|WheelEvent]\n */\nclass MapBrowserEvent extends MapEvent {\n  /**\n   * @param {string} type Event type.\n   * @param {import(\"./Map.js\").default} map Map.\n   * @param {EVENT} originalEvent Original event.\n   * @param {boolean} [dragging] Is the map currently being dragged?\n   * @param {import(\"./Map.js\").FrameState} [frameState] Frame state.\n   * @param {Array<PointerEvent>} [activePointers] Active pointers.\n   */\n  constructor(type, map, originalEvent, dragging, frameState, activePointers) {\n    super(type, map, frameState);\n\n    /**\n     * The original browser event.\n     * @const\n     * @type {EVENT}\n     * @api\n     */\n    this.originalEvent = originalEvent;\n\n    /**\n     * The map pixel relative to the viewport corresponding to the original browser event.\n     * @type {?import(\"./pixel.js\").Pixel}\n     * @private\n     */\n    this.pixel_ = null;\n\n    /**\n     * The coordinate in the user projection corresponding to the original browser event.\n     * @type {?import(\"./coordinate.js\").Coordinate}\n     * @private\n     */\n    this.coordinate_ = null;\n\n    /**\n     * Indicates if the map is currently being dragged. Only set for\n     * `POINTERDRAG` and `POINTERMOVE` events. Default is `false`.\n     *\n     * @type {boolean}\n     * @api\n     */\n    this.dragging = dragging !== undefined ? dragging : false;\n\n    /**\n     * @type {Array<PointerEvent>|undefined}\n     */\n    this.activePointers = activePointers;\n  }\n\n  /**\n   * The map pixel relative to the viewport corresponding to the original event.\n   * @type {import(\"./pixel.js\").Pixel}\n   * @api\n   */\n  get pixel() {\n    if (!this.pixel_) {\n      this.pixel_ = this.map.getEventPixel(this.originalEvent);\n    }\n    return this.pixel_;\n  }\n  set pixel(pixel) {\n    this.pixel_ = pixel;\n  }\n\n  /**\n   * The coordinate corresponding to the original browser event.  This will be in the user\n   * projection if one is set.  Otherwise it will be in the view projection.\n   * @type {import(\"./coordinate.js\").Coordinate}\n   * @api\n   */\n  get coordinate() {\n    if (!this.coordinate_) {\n      this.coordinate_ = this.map.getCoordinateFromPixel(this.pixel);\n    }\n    return this.coordinate_;\n  }\n  set coordinate(coordinate) {\n    this.coordinate_ = coordinate;\n  }\n\n  /**\n   * Prevents the default browser action.\n   * See https://developer.mozilla.org/en-US/docs/Web/API/event.preventDefault.\n   * @api\n   * @override\n   */\n  preventDefault() {\n    super.preventDefault();\n    if ('preventDefault' in this.originalEvent) {\n      /** @type {UIEvent} */ (this.originalEvent).preventDefault();\n    }\n  }\n\n  /**\n   * Prevents further propagation of the current event.\n   * See https://developer.mozilla.org/en-US/docs/Web/API/event.stopPropagation.\n   * @api\n   * @override\n   */\n  stopPropagation() {\n    super.stopPropagation();\n    if ('stopPropagation' in this.originalEvent) {\n      /** @type {UIEvent} */ (this.originalEvent).stopPropagation();\n    }\n  }\n}\n\nexport default MapBrowserEvent;\n", "/**\n * @module ol/MapBrowserEventType\n */\nimport EventType from './events/EventType.js';\n\n/**\n * Constants for event names.\n * @enum {string}\n */\nexport default {\n  /**\n   * A true single click with no dragging and no double click. Note that this\n   * event is delayed by 250 ms to ensure that it is not a double click.\n   * @event module:ol/MapBrowserEvent~MapBrowserEvent#singleclick\n   * @api\n   */\n  SINGLECLICK: 'singleclick',\n\n  /**\n   * A click with no dragging. A double click will fire two of this.\n   * @event module:ol/MapBrowserEvent~MapBrowserEvent#click\n   * @api\n   */\n  CLICK: EventType.CLICK,\n\n  /**\n   * A true double click, with no dragging.\n   * @event module:ol/MapBrowserEvent~MapBrowserEvent#dblclick\n   * @api\n   */\n  DBLCLICK: EventType.DBLCLICK,\n\n  /**\n   * Triggered when a pointer is dragged.\n   * @event module:ol/MapBrowserEvent~MapBrowserEvent#pointerdrag\n   * @api\n   */\n  POINTERDRAG: 'pointerdrag',\n\n  /**\n   * Triggered when a pointer is moved. Note that on touch devices this is\n   * triggered when the map is panned, so is not the same as mousemove.\n   * @event module:ol/MapBrowserEvent~MapBrowserEvent#pointermove\n   * @api\n   */\n  POINTERMOVE: 'pointermove',\n\n  POINTERDOWN: 'pointerdown',\n  POINTERUP: 'pointerup',\n  POINTEROVER: 'pointerover',\n  POINTEROUT: 'pointerout',\n  POINTERENTER: 'pointerenter',\n  POINTERLEAVE: 'pointerleave',\n  POINTERCANCEL: 'pointercancel',\n};\n\n/***\n * @typedef {'singleclick'|'click'|'dblclick'|'pointerdrag'|'pointermove'} Types\n */\n", "/**\n * @module ol/has\n */\n\nconst ua =\n  typeof navigator !== 'undefined' && typeof navigator.userAgent !== 'undefined'\n    ? navigator.userAgent.toLowerCase()\n    : '';\n\n/**\n * User agent string says we are dealing with Safari as browser.\n * @type {boolean}\n */\nexport const SAFARI = ua.includes('safari') && !ua.includes('chrom');\n\n/**\n * https://bugs.webkit.org/show_bug.cgi?id=237906\n * @type {boolean}\n */\nexport const SAFARI_BUG_237906 =\n  SAFARI &&\n  (ua.includes('version/15.4') ||\n    /cpu (os|iphone os) 15_4 like mac os x/.test(ua));\n\n/**\n * User agent string says we are dealing with a WebKit engine.\n * @type {boolean}\n */\nexport const WEBKIT = ua.includes('webkit') && !ua.includes('edge');\n\n/**\n * User agent string says we are dealing with a Mac as platform.\n * @type {boolean}\n */\nexport const MAC = ua.includes('macintosh');\n\n/**\n * The ratio between physical pixels and device-independent pixels\n * (dips) on the device (`window.devicePixelRatio`).\n * @const\n * @type {number}\n * @api\n */\nexport const DEVICE_PIXEL_RATIO =\n  typeof devicePixelRatio !== 'undefined' ? devicePixelRatio : 1;\n\n/**\n * The execution context is a worker with OffscreenCanvas available.\n * @const\n * @type {boolean}\n */\nexport const WORKER_OFFSCREEN_CANVAS =\n  typeof WorkerGlobalScope !== 'undefined' &&\n  typeof OffscreenCanvas !== 'undefined' &&\n  self instanceof WorkerGlobalScope; //eslint-disable-line\n\n/**\n * Image.prototype.decode() is supported.\n * @type {boolean}\n */\nexport const IMAGE_DECODE =\n  typeof Image !== 'undefined' && Image.prototype.decode;\n\n/**\n * createImageBitmap() is supported.\n * @type {boolean}\n */\nexport const CREATE_IMAGE_BITMAP = typeof createImageBitmap === 'function';\n\n/**\n * @type {boolean}\n */\nexport const PASSIVE_EVENT_LISTENERS = (function () {\n  let passive = false;\n  try {\n    const options = Object.defineProperty({}, 'passive', {\n      get: function () {\n        passive = true;\n      },\n    });\n\n    // @ts-ignore Ignore invalid event type '_'\n    window.addEventListener('_', null, options);\n    // @ts-ignore Ignore invalid event type '_'\n    window.removeEventListener('_', null, options);\n  } catch {\n    // passive not supported\n  }\n  return passive;\n})();\n", "/**\n * @module ol/pointer/EventType\n */\n\n/**\n * Constants for event names.\n * @enum {string}\n */\nexport default {\n  POINTERMOVE: 'pointermove',\n  POINTERDOWN: 'pointerdown',\n  POINTERUP: 'pointerup',\n  POINTEROVER: 'pointerover',\n  POINTEROUT: 'pointerout',\n  POINTERENTER: 'pointerenter',\n  POINTERLEAVE: 'pointerleave',\n  POINTERCANCEL: 'pointercancel',\n};\n", "/**\n * @module ol/MapBrowserEventHandler\n */\n\nimport MapBrowserEvent from './MapBrowserEvent.js';\nimport MapBrowserEventType from './MapBrowserEventType.js';\nimport {listen, unlistenByKey} from './events.js';\nimport EventType from './events/EventType.js';\nimport Target from './events/Target.js';\nimport {PASSIVE_EVENT_LISTENERS} from './has.js';\nimport PointerEventType from './pointer/EventType.js';\n\nclass MapBrowserEventHandler extends Target {\n  /**\n   * @param {import(\"./Map.js\").default} map The map with the viewport to listen to events on.\n   * @param {number} [moveTolerance] The minimal distance the pointer must travel to trigger a move.\n   */\n  constructor(map, moveTolerance) {\n    super(map);\n\n    /**\n     * This is the element that we will listen to the real events on.\n     * @type {import(\"./Map.js\").default}\n     * @private\n     */\n    this.map_ = map;\n\n    /**\n     * @type {ReturnType<typeof setTimeout>}\n     * @private\n     */\n    this.clickTimeoutId_;\n\n    /**\n     * Emulate dblclick and singleclick. Will be true when only one pointer is active.\n     * @type {boolean}\n     */\n    this.emulateClicks_ = false;\n\n    /**\n     * @type {boolean}\n     * @private\n     */\n    this.dragging_ = false;\n\n    /**\n     * @type {!Array<import(\"./events.js\").EventsKey>}\n     * @private\n     */\n    this.dragListenerKeys_ = [];\n\n    /**\n     * @type {number}\n     * @private\n     */\n    this.moveTolerance_ = moveTolerance === undefined ? 1 : moveTolerance;\n\n    /**\n     * The most recent \"down\" type event (or null if none have occurred).\n     * Set on pointerdown.\n     * @type {PointerEvent|null}\n     * @private\n     */\n    this.down_ = null;\n\n    const element = this.map_.getViewport();\n\n    /**\n     * @type {Array<PointerEvent>}\n     * @private\n     */\n    this.activePointers_ = [];\n\n    /**\n     * @type {!Object<number, Event>}\n     * @private\n     */\n    this.trackedTouches_ = {};\n\n    /**\n     * @private\n     */\n    this.element_ = element;\n\n    /**\n     * @type {?import(\"./events.js\").EventsKey}\n     * @private\n     */\n    this.pointerdownListenerKey_ = listen(\n      element,\n      PointerEventType.POINTERDOWN,\n      this.handlePointerDown_,\n      this,\n    );\n\n    /**\n     * @type {PointerEvent}\n     * @private\n     */\n    this.originalPointerMoveEvent_;\n\n    /**\n     * @type {?import(\"./events.js\").EventsKey}\n     * @private\n     */\n    this.relayedListenerKey_ = listen(\n      element,\n      PointerEventType.POINTERMOVE,\n      this.relayMoveEvent_,\n      this,\n    );\n\n    /**\n     * @private\n     */\n    this.boundHandleTouchMove_ = this.handleTouchMove_.bind(this);\n\n    this.element_.addEventListener(\n      EventType.TOUCHMOVE,\n      this.boundHandleTouchMove_,\n      PASSIVE_EVENT_LISTENERS ? {passive: false} : false,\n    );\n  }\n\n  /**\n   * @param {PointerEvent} pointerEvent Pointer\n   * event.\n   * @private\n   */\n  emulateClick_(pointerEvent) {\n    let newEvent = new MapBrowserEvent(\n      MapBrowserEventType.CLICK,\n      this.map_,\n      pointerEvent,\n    );\n    this.dispatchEvent(newEvent);\n    if (this.clickTimeoutId_ !== undefined) {\n      // double-click\n      clearTimeout(this.clickTimeoutId_);\n      this.clickTimeoutId_ = undefined;\n      newEvent = new MapBrowserEvent(\n        MapBrowserEventType.DBLCLICK,\n        this.map_,\n        pointerEvent,\n      );\n      this.dispatchEvent(newEvent);\n    } else {\n      // click\n      this.clickTimeoutId_ = setTimeout(() => {\n        this.clickTimeoutId_ = undefined;\n        const newEvent = new MapBrowserEvent(\n          MapBrowserEventType.SINGLECLICK,\n          this.map_,\n          pointerEvent,\n        );\n        this.dispatchEvent(newEvent);\n      }, 250);\n    }\n  }\n\n  /**\n   * Keeps track on how many pointers are currently active.\n   *\n   * @param {PointerEvent} pointerEvent Pointer\n   * event.\n   * @private\n   */\n  updateActivePointers_(pointerEvent) {\n    const event = pointerEvent;\n    const id = event.pointerId;\n\n    if (\n      event.type == MapBrowserEventType.POINTERUP ||\n      event.type == MapBrowserEventType.POINTERCANCEL\n    ) {\n      delete this.trackedTouches_[id];\n      for (const pointerId in this.trackedTouches_) {\n        if (this.trackedTouches_[pointerId].target !== event.target) {\n          // Some platforms assign a new pointerId when the target changes.\n          // If this happens, delete one tracked pointer. If there is more\n          // than one tracked pointer for the old target, it will be cleared\n          // by subsequent POINTERUP events from other pointers.\n          delete this.trackedTouches_[pointerId];\n          break;\n        }\n      }\n    } else if (\n      event.type == MapBrowserEventType.POINTERDOWN ||\n      event.type == MapBrowserEventType.POINTERMOVE\n    ) {\n      this.trackedTouches_[id] = event;\n    }\n    this.activePointers_ = Object.values(this.trackedTouches_);\n  }\n\n  /**\n   * @param {PointerEvent} pointerEvent Pointer\n   * event.\n   * @private\n   */\n  handlePointerUp_(pointerEvent) {\n    this.updateActivePointers_(pointerEvent);\n    const newEvent = new MapBrowserEvent(\n      MapBrowserEventType.POINTERUP,\n      this.map_,\n      pointerEvent,\n      undefined,\n      undefined,\n      this.activePointers_,\n    );\n    this.dispatchEvent(newEvent);\n\n    // We emulate click events on left mouse button click, touch contact, and pen\n    // contact. isMouseActionButton returns true in these cases (evt.button is set\n    // to 0).\n    // See http://www.w3.org/TR/pointerevents/#button-states\n    // We only fire click, singleclick, and doubleclick if nobody has called\n    // event.preventDefault().\n    if (\n      this.emulateClicks_ &&\n      !newEvent.defaultPrevented &&\n      !this.dragging_ &&\n      this.isMouseActionButton_(pointerEvent)\n    ) {\n      this.emulateClick_(this.down_);\n    }\n\n    if (this.activePointers_.length === 0) {\n      this.dragListenerKeys_.forEach(unlistenByKey);\n      this.dragListenerKeys_.length = 0;\n      this.dragging_ = false;\n      this.down_ = null;\n    }\n  }\n\n  /**\n   * @param {PointerEvent} pointerEvent Pointer\n   * event.\n   * @return {boolean} If the left mouse button was pressed.\n   * @private\n   */\n  isMouseActionButton_(pointerEvent) {\n    return pointerEvent.button === 0;\n  }\n\n  /**\n   * @param {PointerEvent} pointerEvent Pointer\n   * event.\n   * @private\n   */\n  handlePointerDown_(pointerEvent) {\n    this.emulateClicks_ = this.activePointers_.length === 0;\n    this.updateActivePointers_(pointerEvent);\n    const newEvent = new MapBrowserEvent(\n      MapBrowserEventType.POINTERDOWN,\n      this.map_,\n      pointerEvent,\n      undefined,\n      undefined,\n      this.activePointers_,\n    );\n    this.dispatchEvent(newEvent);\n\n    this.down_ = new PointerEvent(pointerEvent.type, pointerEvent);\n    Object.defineProperty(this.down_, 'target', {\n      writable: false,\n      value: pointerEvent.target,\n    });\n\n    if (this.dragListenerKeys_.length === 0) {\n      const doc = this.map_.getOwnerDocument();\n      this.dragListenerKeys_.push(\n        listen(\n          doc,\n          MapBrowserEventType.POINTERMOVE,\n          this.handlePointerMove_,\n          this,\n        ),\n        listen(doc, MapBrowserEventType.POINTERUP, this.handlePointerUp_, this),\n        /* Note that the listener for `pointercancel is set up on\n         * `pointerEventHandler_` and not `documentPointerEventHandler_` like\n         * the `pointerup` and `pointermove` listeners.\n         *\n         * The reason for this is the following: `TouchSource.vacuumTouches_()`\n         * issues `pointercancel` events, when there was no `touchend` for a\n         * `touchstart`. Now, let's say a first `touchstart` is registered on\n         * `pointerEventHandler_`. The `documentPointerEventHandler_` is set up.\n         * But `documentPointerEventHandler_` doesn't know about the first\n         * `touchstart`. If there is no `touchend` for the `touchstart`, we can\n         * only receive a `touchcancel` from `pointerEventHandler_`, because it is\n         * only registered there.\n         */\n        listen(\n          this.element_,\n          MapBrowserEventType.POINTERCANCEL,\n          this.handlePointerUp_,\n          this,\n        ),\n      );\n      if (this.element_.getRootNode && this.element_.getRootNode() !== doc) {\n        this.dragListenerKeys_.push(\n          listen(\n            this.element_.getRootNode(),\n            MapBrowserEventType.POINTERUP,\n            this.handlePointerUp_,\n            this,\n          ),\n        );\n      }\n    }\n  }\n\n  /**\n   * @param {PointerEvent} pointerEvent Pointer\n   * event.\n   * @private\n   */\n  handlePointerMove_(pointerEvent) {\n    // Between pointerdown and pointerup, pointermove events are triggered.\n    // To avoid a 'false' touchmove event to be dispatched, we test if the pointer\n    // moved a significant distance.\n    if (this.isMoving_(pointerEvent)) {\n      this.updateActivePointers_(pointerEvent);\n      this.dragging_ = true;\n      const newEvent = new MapBrowserEvent(\n        MapBrowserEventType.POINTERDRAG,\n        this.map_,\n        pointerEvent,\n        this.dragging_,\n        undefined,\n        this.activePointers_,\n      );\n      this.dispatchEvent(newEvent);\n    }\n  }\n\n  /**\n   * Wrap and relay a pointermove event.\n   * @param {PointerEvent} pointerEvent Pointer\n   * event.\n   * @private\n   */\n  relayMoveEvent_(pointerEvent) {\n    this.originalPointerMoveEvent_ = pointerEvent;\n    const dragging = !!(this.down_ && this.isMoving_(pointerEvent));\n    this.dispatchEvent(\n      new MapBrowserEvent(\n        MapBrowserEventType.POINTERMOVE,\n        this.map_,\n        pointerEvent,\n        dragging,\n      ),\n    );\n  }\n\n  /**\n   * Flexible handling of a `touch-action: none` css equivalent: because calling\n   * `preventDefault()` on a `pointermove` event does not stop native page scrolling\n   * and zooming, we also listen for `touchmove` and call `preventDefault()` on it\n   * when an interaction (currently `DragPan` handles the event.\n   * @param {TouchEvent} event Event.\n   * @private\n   */\n  handleTouchMove_(event) {\n    // Due to https://github.com/mpizenberg/elm-pep/issues/2, `this.originalPointerMoveEvent_`\n    // may not be initialized yet when we get here on a platform without native pointer events,\n    // when elm-pep is used as pointer events polyfill.\n    const originalEvent = this.originalPointerMoveEvent_;\n    if (\n      (!originalEvent || originalEvent.defaultPrevented) &&\n      (typeof event.cancelable !== 'boolean' || event.cancelable === true)\n    ) {\n      event.preventDefault();\n    }\n  }\n\n  /**\n   * @param {PointerEvent} pointerEvent Pointer\n   * event.\n   * @return {boolean} Is moving.\n   * @private\n   */\n  isMoving_(pointerEvent) {\n    return (\n      this.dragging_ ||\n      Math.abs(pointerEvent.clientX - this.down_.clientX) >\n        this.moveTolerance_ ||\n      Math.abs(pointerEvent.clientY - this.down_.clientY) > this.moveTolerance_\n    );\n  }\n\n  /**\n   * Clean up.\n   * @override\n   */\n  disposeInternal() {\n    if (this.relayedListenerKey_) {\n      unlistenByKey(this.relayedListenerKey_);\n      this.relayedListenerKey_ = null;\n    }\n    this.element_.removeEventListener(\n      EventType.TOUCHMOVE,\n      this.boundHandleTouchMove_,\n    );\n\n    if (this.pointerdownListenerKey_) {\n      unlistenByKey(this.pointerdownListenerKey_);\n      this.pointerdownListenerKey_ = null;\n    }\n\n    this.dragListenerKeys_.forEach(unlistenByKey);\n    this.dragListenerKeys_.length = 0;\n\n    this.element_ = null;\n    super.disposeInternal();\n  }\n}\n\nexport default MapBrowserEventHandler;\n", "/**\n * @module ol/MapEventType\n */\n\n/**\n * @enum {string}\n */\nexport default {\n  /**\n   * Triggered after a map frame is rendered.\n   * @event module:ol/MapEvent~MapEvent#postrender\n   * @api\n   */\n  POSTRENDER: 'postrender',\n\n  /**\n   * Triggered when the map starts moving.\n   * @event module:ol/MapEvent~MapEvent#movestart\n   * @api\n   */\n  MOVESTART: 'movestart',\n\n  /**\n   * Triggered after the map is moved.\n   * @event module:ol/MapEvent~MapEvent#moveend\n   * @api\n   */\n  MOVEEND: 'moveend',\n\n  /**\n   * Triggered when loading of additional map data (tiles, images, features) starts.\n   * @event module:ol/MapEvent~MapEvent#loadstart\n   * @api\n   */\n  LOADSTART: 'loadstart',\n\n  /**\n   * Triggered when loading of additional map data has completed.\n   * @event module:ol/MapEvent~MapEvent#loadend\n   * @api\n   */\n  LOADEND: 'loadend',\n};\n\n/***\n * @typedef {'postrender'|'movestart'|'moveend'|'loadstart'|'loadend'} Types\n */\n", "/**\n * @module ol/MapProperty\n */\n\n/**\n * @enum {string}\n */\nexport default {\n  LAYERGROUP: 'layergroup',\n  SIZE: 'size',\n  TARGET: 'target',\n  VIEW: 'view',\n};\n", "/**\n * @module ol/TileState\n */\n\n/**\n * @enum {number}\n */\nexport default {\n  IDLE: 0,\n  LOADING: 1,\n  LOADED: 2,\n  /**\n   * Indicates that tile loading failed\n   * @type {number}\n   */\n  ERROR: 3,\n  EMPTY: 4,\n};\n", "/**\n * @module ol/asserts\n */\n\n/**\n * @param {*} assertion Assertion we expected to be truthy.\n * @param {string} errorMessage Error message.\n */\nexport function assert(assertion, errorMessage) {\n  if (!assertion) {\n    throw new Error(errorMessage);\n  }\n}\n", "/**\n * @module ol/structs/PriorityQueue\n */\nimport {assert} from '../asserts.js';\nimport {clear} from '../obj.js';\n\n/**\n * @type {number}\n */\nexport const DROP = Infinity;\n\n/**\n * @classdesc\n * Priority queue.\n *\n * The implementation is inspired from the Closure Library's Heap class and\n * Python's heapq module.\n *\n * See https://github.com/google/closure-library/blob/master/closure/goog/structs/heap.js\n * and https://hg.python.org/cpython/file/2.7/Lib/heapq.py.\n *\n * @template T\n */\nclass PriorityQueue {\n  /**\n   * @param {function(T): number} priorityFunction Priority function.\n   * @param {function(T): string} keyFunction Key function.\n   */\n  constructor(priorityFunction, keyFunction) {\n    /**\n     * @type {function(T): number}\n     * @private\n     */\n    this.priorityFunction_ = priorityFunction;\n\n    /**\n     * @type {function(T): string}\n     * @private\n     */\n    this.keyFunction_ = keyFunction;\n\n    /**\n     * @type {Array<T>}\n     * @private\n     */\n    this.elements_ = [];\n\n    /**\n     * @type {Array<number>}\n     * @private\n     */\n    this.priorities_ = [];\n\n    /**\n     * @type {!Object<string, boolean>}\n     * @private\n     */\n    this.queuedElements_ = {};\n  }\n\n  /**\n   * FIXME empty description for jsdoc\n   */\n  clear() {\n    this.elements_.length = 0;\n    this.priorities_.length = 0;\n    clear(this.queuedElements_);\n  }\n\n  /**\n   * Remove and return the highest-priority element. O(log N).\n   * @return {T} Element.\n   */\n  dequeue() {\n    const elements = this.elements_;\n    const priorities = this.priorities_;\n    const element = elements[0];\n    if (elements.length == 1) {\n      elements.length = 0;\n      priorities.length = 0;\n    } else {\n      elements[0] = /** @type {T} */ (elements.pop());\n      priorities[0] = /** @type {number} */ (priorities.pop());\n      this.siftUp_(0);\n    }\n    const elementKey = this.keyFunction_(element);\n    delete this.queuedElements_[elementKey];\n    return element;\n  }\n\n  /**\n   * Enqueue an element. O(log N).\n   * @param {T} element Element.\n   * @return {boolean} The element was added to the queue.\n   */\n  enqueue(element) {\n    assert(\n      !(this.keyFunction_(element) in this.queuedElements_),\n      'Tried to enqueue an `element` that was already added to the queue',\n    );\n    const priority = this.priorityFunction_(element);\n    if (priority != DROP) {\n      this.elements_.push(element);\n      this.priorities_.push(priority);\n      this.queuedElements_[this.keyFunction_(element)] = true;\n      this.siftDown_(0, this.elements_.length - 1);\n      return true;\n    }\n    return false;\n  }\n\n  /**\n   * @return {number} Count.\n   */\n  getCount() {\n    return this.elements_.length;\n  }\n\n  /**\n   * Gets the index of the left child of the node at the given index.\n   * @param {number} index The index of the node to get the left child for.\n   * @return {number} The index of the left child.\n   * @private\n   */\n  getLeftChildIndex_(index) {\n    return index * 2 + 1;\n  }\n\n  /**\n   * Gets the index of the right child of the node at the given index.\n   * @param {number} index The index of the node to get the right child for.\n   * @return {number} The index of the right child.\n   * @private\n   */\n  getRightChildIndex_(index) {\n    return index * 2 + 2;\n  }\n\n  /**\n   * Gets the index of the parent of the node at the given index.\n   * @param {number} index The index of the node to get the parent for.\n   * @return {number} The index of the parent.\n   * @private\n   */\n  getParentIndex_(index) {\n    return (index - 1) >> 1;\n  }\n\n  /**\n   * Make this a heap. O(N).\n   * @private\n   */\n  heapify_() {\n    let i;\n    for (i = (this.elements_.length >> 1) - 1; i >= 0; i--) {\n      this.siftUp_(i);\n    }\n  }\n\n  /**\n   * @return {boolean} Is empty.\n   */\n  isEmpty() {\n    return this.elements_.length === 0;\n  }\n\n  /**\n   * @param {string} key Key.\n   * @return {boolean} Is key queued.\n   */\n  isKeyQueued(key) {\n    return key in this.queuedElements_;\n  }\n\n  /**\n   * @param {T} element Element.\n   * @return {boolean} Is queued.\n   */\n  isQueued(element) {\n    return this.isKeyQueued(this.keyFunction_(element));\n  }\n\n  /**\n   * @param {number} index The index of the node to move down.\n   * @private\n   */\n  siftUp_(index) {\n    const elements = this.elements_;\n    const priorities = this.priorities_;\n    const count = elements.length;\n    const element = elements[index];\n    const priority = priorities[index];\n    const startIndex = index;\n\n    while (index < count >> 1) {\n      const lIndex = this.getLeftChildIndex_(index);\n      const rIndex = this.getRightChildIndex_(index);\n\n      const smallerChildIndex =\n        rIndex < count && priorities[rIndex] < priorities[lIndex]\n          ? rIndex\n          : lIndex;\n\n      elements[index] = elements[smallerChildIndex];\n      priorities[index] = priorities[smallerChildIndex];\n      index = smallerChildIndex;\n    }\n\n    elements[index] = element;\n    priorities[index] = priority;\n    this.siftDown_(startIndex, index);\n  }\n\n  /**\n   * @param {number} startIndex The index of the root.\n   * @param {number} index The index of the node to move up.\n   * @private\n   */\n  siftDown_(startIndex, index) {\n    const elements = this.elements_;\n    const priorities = this.priorities_;\n    const element = elements[index];\n    const priority = priorities[index];\n\n    while (index > startIndex) {\n      const parentIndex = this.getParentIndex_(index);\n      if (priorities[parentIndex] > priority) {\n        elements[index] = elements[parentIndex];\n        priorities[index] = priorities[parentIndex];\n        index = parentIndex;\n      } else {\n        break;\n      }\n    }\n    elements[index] = element;\n    priorities[index] = priority;\n  }\n\n  /**\n   * FIXME empty description for jsdoc\n   */\n  reprioritize() {\n    const priorityFunction = this.priorityFunction_;\n    const elements = this.elements_;\n    const priorities = this.priorities_;\n    let index = 0;\n    const n = elements.length;\n    let element, i, priority;\n    for (i = 0; i < n; ++i) {\n      element = elements[i];\n      priority = priorityFunction(element);\n      if (priority == DROP) {\n        delete this.queuedElements_[this.keyFunction_(element)];\n      } else {\n        priorities[index] = priority;\n        elements[index++] = element;\n      }\n    }\n    elements.length = index;\n    priorities.length = index;\n    this.heapify_();\n  }\n}\n\nexport default PriorityQueue;\n", "/**\n * @module ol/TileQueue\n */\nimport TileState from './TileState.js';\nimport EventType from './events/EventType.js';\nimport PriorityQueue, {DROP} from './structs/PriorityQueue.js';\n\n/**\n * @typedef {function(import(\"./Tile.js\").default, string, import('./tilecoord.js').TileCoord, number): number} PriorityFunction\n */\n\n/**\n * @typedef {[import('./Tile.js').default, string, import('./tilecoord.js').TileCoord, number]} TileQueueElement\n */\n\n/**\n * @extends PriorityQueue<TileQueueElement>}\n */\nclass TileQueue extends PriorityQueue {\n  /**\n   * @param {PriorityFunction} tilePriorityFunction Tile priority function.\n   * @param {function(): ?} tileChangeCallback Function called on each tile change event.\n   */\n  constructor(tilePriorityFunction, tileChangeCallback) {\n    super(\n      (element) => tilePriorityFunction.apply(null, element),\n      (element) => element[0].getKey(),\n    );\n\n    /** @private */\n    this.boundHandleTileChange_ = this.handleTileChange.bind(this);\n\n    /**\n     * @private\n     * @type {function(): ?}\n     */\n    this.tileChangeCallback_ = tileChangeCallback;\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.tilesLoading_ = 0;\n\n    /**\n     * @private\n     * @type {!Object<string,boolean>}\n     */\n    this.tilesLoadingKeys_ = {};\n  }\n\n  /**\n   * @param {TileQueueElement} element Element.\n   * @return {boolean} The element was added to the queue.\n   * @override\n   */\n  enqueue(element) {\n    const added = super.enqueue(element);\n    if (added) {\n      const tile = element[0];\n      tile.addEventListener(EventType.CHANGE, this.boundHandleTileChange_);\n    }\n    return added;\n  }\n\n  /**\n   * @return {number} Number of tiles loading.\n   */\n  getTilesLoading() {\n    return this.tilesLoading_;\n  }\n\n  /**\n   * @param {import(\"./events/Event.js\").default} event Event.\n   * @protected\n   */\n  handleTileChange(event) {\n    const tile = /** @type {import(\"./Tile.js\").default} */ (event.target);\n    const state = tile.getState();\n    if (\n      state === TileState.LOADED ||\n      state === TileState.ERROR ||\n      state === TileState.EMPTY\n    ) {\n      if (state !== TileState.ERROR) {\n        tile.removeEventListener(EventType.CHANGE, this.boundHandleTileChange_);\n      }\n      const tileKey = tile.getKey();\n      if (tileKey in this.tilesLoadingKeys_) {\n        delete this.tilesLoadingKeys_[tileKey];\n        --this.tilesLoading_;\n      }\n      this.tileChangeCallback_();\n    }\n  }\n\n  /**\n   * @param {number} maxTotalLoading Maximum number tiles to load simultaneously.\n   * @param {number} maxNewLoads Maximum number of new tiles to load.\n   */\n  loadMoreTiles(maxTotalLoading, maxNewLoads) {\n    let newLoads = 0;\n    while (\n      this.tilesLoading_ < maxTotalLoading &&\n      newLoads < maxNewLoads &&\n      this.getCount() > 0\n    ) {\n      const tile = this.dequeue()[0];\n      const tileKey = tile.getKey();\n      const state = tile.getState();\n      if (state === TileState.IDLE && !(tileKey in this.tilesLoadingKeys_)) {\n        this.tilesLoadingKeys_[tileKey] = true;\n        ++this.tilesLoading_;\n        ++newLoads;\n        tile.load();\n      }\n    }\n  }\n}\n\nexport default TileQueue;\n\n/**\n * @param {import('./Map.js').FrameState} frameState Frame state.\n * @param {import(\"./Tile.js\").default} tile Tile.\n * @param {string} tileSourceKey Tile source key.\n * @param {import(\"./coordinate.js\").Coordinate} tileCenter Tile center.\n * @param {number} tileResolution Tile resolution.\n * @return {number} Tile priority.\n */\nexport function getTilePriority(\n  frameState,\n  tile,\n  tileSourceKey,\n  tileCenter,\n  tileResolution,\n) {\n  // Filter out tiles at higher zoom levels than the current zoom level, or that\n  // are outside the visible extent.\n  if (!frameState || !(tileSourceKey in frameState.wantedTiles)) {\n    return DROP;\n  }\n  if (!frameState.wantedTiles[tileSourceKey][tile.getKey()]) {\n    return DROP;\n  }\n  // Prioritize the highest zoom level tiles closest to the focus.\n  // Tiles at higher zoom levels are prioritized using Math.log(tileResolution).\n  // Within a zoom level, tiles are prioritized by the distance in pixels between\n  // the center of the tile and the center of the viewport.  The factor of 65536\n  // means that the prioritization should behave as desired for tiles up to\n  // 65536 * Math.log(2) = 45426 pixels from the focus.\n  const center = frameState.viewState.center;\n  const deltaX = tileCenter[0] - center[0];\n  const deltaY = tileCenter[1] - center[1];\n  return (\n    65536 * Math.log(tileResolution) +\n    Math.sqrt(deltaX * deltaX + deltaY * deltaY) / tileResolution\n  );\n}\n", "/**\n * @module ol/ViewHint\n */\n\n/**\n * @enum {number}\n */\nexport default {\n  ANIMATING: 0,\n  INTERACTING: 1,\n};\n", "/**\n * @module ol/ViewProperty\n */\n\n/**\n * @enum {string}\n */\nexport default {\n  CENTER: 'center',\n  RESOLUTION: 'resolution',\n  ROTATION: 'rotation',\n};\n", "/**\n * @module ol/math\n */\n\n/**\n * Takes a number and clamps it to within the provided bounds.\n * @param {number} value The input number.\n * @param {number} min The minimum value to return.\n * @param {number} max The maximum value to return.\n * @return {number} The input number if it is within bounds, or the nearest\n *     number within the bounds.\n */\nexport function clamp(value, min, max) {\n  return Math.min(Math.max(value, min), max);\n}\n\n/**\n * Returns the square of the closest distance between the point (x, y) and the\n * line segment (x1, y1) to (x2, y2).\n * @param {number} x X.\n * @param {number} y Y.\n * @param {number} x1 X1.\n * @param {number} y1 Y1.\n * @param {number} x2 X2.\n * @param {number} y2 Y2.\n * @return {number} Squared distance.\n */\nexport function squaredSegmentDistance(x, y, x1, y1, x2, y2) {\n  const dx = x2 - x1;\n  const dy = y2 - y1;\n  if (dx !== 0 || dy !== 0) {\n    const t = ((x - x1) * dx + (y - y1) * dy) / (dx * dx + dy * dy);\n    if (t > 1) {\n      x1 = x2;\n      y1 = y2;\n    } else if (t > 0) {\n      x1 += dx * t;\n      y1 += dy * t;\n    }\n  }\n  return squaredDistance(x, y, x1, y1);\n}\n\n/**\n * Returns the square of the distance between the points (x1, y1) and (x2, y2).\n * @param {number} x1 X1.\n * @param {number} y1 Y1.\n * @param {number} x2 X2.\n * @param {number} y2 Y2.\n * @return {number} Squared distance.\n */\nexport function squaredDistance(x1, y1, x2, y2) {\n  const dx = x2 - x1;\n  const dy = y2 - y1;\n  return dx * dx + dy * dy;\n}\n\n/**\n * Solves system of linear equations using Gaussian elimination method.\n *\n * @param {Array<Array<number>>} mat Augmented matrix (n x n + 1 column)\n *                                     in row-major order.\n * @return {Array<number>|null} The resulting vector.\n */\nexport function solveLinearSystem(mat) {\n  const n = mat.length;\n\n  for (let i = 0; i < n; i++) {\n    // Find max in the i-th column (ignoring i - 1 first rows)\n    let maxRow = i;\n    let maxEl = Math.abs(mat[i][i]);\n    for (let r = i + 1; r < n; r++) {\n      const absValue = Math.abs(mat[r][i]);\n      if (absValue > maxEl) {\n        maxEl = absValue;\n        maxRow = r;\n      }\n    }\n\n    if (maxEl === 0) {\n      return null; // matrix is singular\n    }\n\n    // Swap max row with i-th (current) row\n    const tmp = mat[maxRow];\n    mat[maxRow] = mat[i];\n    mat[i] = tmp;\n\n    // Subtract the i-th row to make all the remaining rows 0 in the i-th column\n    for (let j = i + 1; j < n; j++) {\n      const coef = -mat[j][i] / mat[i][i];\n      for (let k = i; k < n + 1; k++) {\n        if (i == k) {\n          mat[j][k] = 0;\n        } else {\n          mat[j][k] += coef * mat[i][k];\n        }\n      }\n    }\n  }\n\n  // Solve Ax=b for upper triangular matrix A (mat)\n  const x = new Array(n);\n  for (let l = n - 1; l >= 0; l--) {\n    x[l] = mat[l][n] / mat[l][l];\n    for (let m = l - 1; m >= 0; m--) {\n      mat[m][n] -= mat[m][l] * x[l];\n    }\n  }\n  return x;\n}\n\n/**\n * Converts radians to to degrees.\n *\n * @param {number} angleInRadians Angle in radians.\n * @return {number} Angle in degrees.\n */\nexport function toDegrees(angleInRadians) {\n  return (angleInRadians * 180) / Math.PI;\n}\n\n/**\n * Converts degrees to radians.\n *\n * @param {number} angleInDegrees Angle in degrees.\n * @return {number} Angle in radians.\n */\nexport function toRadians(angleInDegrees) {\n  return (angleInDegrees * Math.PI) / 180;\n}\n\n/**\n * Returns the modulo of a / b, depending on the sign of b.\n *\n * @param {number} a Dividend.\n * @param {number} b Divisor.\n * @return {number} Modulo.\n */\nexport function modulo(a, b) {\n  const r = a % b;\n  return r * b < 0 ? r + b : r;\n}\n\n/**\n * Calculates the linearly interpolated value of x between a and b.\n *\n * @param {number} a Number\n * @param {number} b Number\n * @param {number} x Value to be interpolated.\n * @return {number} Interpolated value.\n */\nexport function lerp(a, b, x) {\n  return a + x * (b - a);\n}\n\n/**\n * Returns a number with a limited number of decimal digits.\n * @param {number} n The input number.\n * @param {number} decimals The maximum number of decimal digits.\n * @return {number} The input number with a limited number of decimal digits.\n */\nexport function toFixed(n, decimals) {\n  const factor = Math.pow(10, decimals);\n  return Math.round(n * factor) / factor;\n}\n\n/**\n * Rounds a number to the nearest integer value considering only the given number\n * of decimal digits (with rounding on the final digit).\n * @param {number} n The input number.\n * @param {number} decimals The maximum number of decimal digits.\n * @return {number} The nearest integer.\n */\nexport function round(n, decimals) {\n  return Math.round(toFixed(n, decimals));\n}\n\n/**\n * Rounds a number to the next smaller integer considering only the given number\n * of decimal digits (with rounding on the final digit).\n * @param {number} n The input number.\n * @param {number} decimals The maximum number of decimal digits.\n * @return {number} The next smaller integer.\n */\nexport function floor(n, decimals) {\n  return Math.floor(toFixed(n, decimals));\n}\n\n/**\n * Rounds a number to the next bigger integer considering only the given number\n * of decimal digits (with rounding on the final digit).\n * @param {number} n The input number.\n * @param {number} decimals The maximum number of decimal digits.\n * @return {number} The next bigger integer.\n */\nexport function ceil(n, decimals) {\n  return Math.ceil(toFixed(n, decimals));\n}\n\n/**\n * Wraps a number between some minimum and maximum values.\n * @param {number} n The number to wrap.\n * @param {number} min The minimum of the range (inclusive).\n * @param {number} max The maximum of the range (exclusive).\n * @return {number} The wrapped number.\n */\nexport function wrap(n, min, max) {\n  if (n >= min && n < max) {\n    return n;\n  }\n  const range = max - min;\n  return ((((n - min) % range) + range) % range) + min;\n}\n", "/**\n * @module ol/centerconstraint\n */\nimport {clamp} from './math.js';\n\n/**\n * @typedef {function((import(\"./coordinate.js\").Coordinate|undefined), number, import(\"./size.js\").Size, boolean=, Array<number>=): (import(\"./coordinate.js\").Coordinate|undefined)} Type\n */\n\n/**\n * @param {import(\"./extent.js\").Extent} extent Extent.\n * @param {boolean} onlyCenter If true, the constraint will only apply to the view center.\n * @param {boolean} smooth If true, the view will be able to go slightly out of the given extent\n * (only during interaction and animation).\n * @return {Type} The constraint.\n */\nexport function createExtent(extent, onlyCenter, smooth) {\n  return (\n    /**\n     * @param {import(\"./coordinate.js\").Coordinate|undefined} center Center.\n     * @param {number|undefined} resolution Resolution.\n     * @param {import(\"./size.js\").Size} size Viewport size; unused if `onlyCenter` was specified.\n     * @param {boolean} [isMoving] True if an interaction or animation is in progress.\n     * @param {Array<number>} [centerShift] Shift between map center and viewport center.\n     * @return {import(\"./coordinate.js\").Coordinate|undefined} Center.\n     */\n    function (center, resolution, size, isMoving, centerShift) {\n      if (!center) {\n        return undefined;\n      }\n      if (!resolution && !onlyCenter) {\n        return center;\n      }\n      const viewWidth = onlyCenter ? 0 : size[0] * resolution;\n      const viewHeight = onlyCenter ? 0 : size[1] * resolution;\n      const shiftX = centerShift ? centerShift[0] : 0;\n      const shiftY = centerShift ? centerShift[1] : 0;\n      let minX = extent[0] + viewWidth / 2 + shiftX;\n      let maxX = extent[2] - viewWidth / 2 + shiftX;\n      let minY = extent[1] + viewHeight / 2 + shiftY;\n      let maxY = extent[3] - viewHeight / 2 + shiftY;\n\n      // note: when zooming out of bounds, min and max values for x and y may\n      // end up inverted (min > max); this has to be accounted for\n      if (minX > maxX) {\n        minX = (maxX + minX) / 2;\n        maxX = minX;\n      }\n      if (minY > maxY) {\n        minY = (maxY + minY) / 2;\n        maxY = minY;\n      }\n\n      let x = clamp(center[0], minX, maxX);\n      let y = clamp(center[1], minY, maxY);\n\n      // during an interaction, allow some overscroll\n      if (isMoving && smooth && resolution) {\n        const ratio = 30 * resolution;\n        x +=\n          -ratio * Math.log(1 + Math.max(0, minX - center[0]) / ratio) +\n          ratio * Math.log(1 + Math.max(0, center[0] - maxX) / ratio);\n        y +=\n          -ratio * Math.log(1 + Math.max(0, minY - center[1]) / ratio) +\n          ratio * Math.log(1 + Math.max(0, center[1] - maxY) / ratio);\n      }\n\n      return [x, y];\n    }\n  );\n}\n\n/**\n * @param {import(\"./coordinate.js\").Coordinate} [center] Center.\n * @return {import(\"./coordinate.js\").Coordinate|undefined} Center.\n */\nexport function none(center) {\n  return center;\n}\n", "/**\n * @module ol/extent/Relationship\n */\n\n/**\n * Relationship to an extent.\n * @enum {number}\n */\nexport default {\n  UNKNOWN: 0,\n  INTERSECTING: 1,\n  ABOVE: 2,\n  RIGHT: 4,\n  BELOW: 8,\n  LEFT: 16,\n};\n", "/**\n * @module ol/extent\n */\nimport Relationship from './extent/Relationship.js';\n\n/**\n * An array of numbers representing an extent: `[minx, miny, maxx, maxy]`.\n * @typedef {Array<number>} Extent\n * @api\n */\n\n/**\n * Extent corner.\n * @typedef {'bottom-left' | 'bottom-right' | 'top-left' | 'top-right'} Corner\n */\n\n/**\n * Build an extent that includes all given coordinates.\n *\n * @param {Array<import(\"./coordinate.js\").Coordinate>} coordinates Coordinates.\n * @return {Extent} Bounding extent.\n * @api\n */\nexport function boundingExtent(coordinates) {\n  const extent = createEmpty();\n  for (let i = 0, ii = coordinates.length; i < ii; ++i) {\n    extendCoordinate(extent, coordinates[i]);\n  }\n  return extent;\n}\n\n/**\n * @param {Array<number>} xs Xs.\n * @param {Array<number>} ys Ys.\n * @param {Extent} [dest] Destination extent.\n * @private\n * @return {Extent} Extent.\n */\nfunction _boundingExtentXYs(xs, ys, dest) {\n  const minX = Math.min.apply(null, xs);\n  const minY = Math.min.apply(null, ys);\n  const maxX = Math.max.apply(null, xs);\n  const maxY = Math.max.apply(null, ys);\n  return createOrUpdate(minX, minY, maxX, maxY, dest);\n}\n\n/**\n * Return extent increased by the provided value.\n * @param {Extent} extent Extent.\n * @param {number} value The amount by which the extent should be buffered.\n * @param {Extent} [dest] Extent.\n * @return {Extent} Extent.\n * @api\n */\nexport function buffer(extent, value, dest) {\n  if (dest) {\n    dest[0] = extent[0] - value;\n    dest[1] = extent[1] - value;\n    dest[2] = extent[2] + value;\n    dest[3] = extent[3] + value;\n    return dest;\n  }\n  return [\n    extent[0] - value,\n    extent[1] - value,\n    extent[2] + value,\n    extent[3] + value,\n  ];\n}\n\n/**\n * Creates a clone of an extent.\n *\n * @param {Extent} extent Extent to clone.\n * @param {Extent} [dest] Extent.\n * @return {Extent} The clone.\n */\nexport function clone(extent, dest) {\n  if (dest) {\n    dest[0] = extent[0];\n    dest[1] = extent[1];\n    dest[2] = extent[2];\n    dest[3] = extent[3];\n    return dest;\n  }\n  return extent.slice();\n}\n\n/**\n * @param {Extent} extent Extent.\n * @param {number} x X.\n * @param {number} y Y.\n * @return {number} Closest squared distance.\n */\nexport function closestSquaredDistanceXY(extent, x, y) {\n  let dx, dy;\n  if (x < extent[0]) {\n    dx = extent[0] - x;\n  } else if (extent[2] < x) {\n    dx = x - extent[2];\n  } else {\n    dx = 0;\n  }\n  if (y < extent[1]) {\n    dy = extent[1] - y;\n  } else if (extent[3] < y) {\n    dy = y - extent[3];\n  } else {\n    dy = 0;\n  }\n  return dx * dx + dy * dy;\n}\n\n/**\n * Check if the passed coordinate is contained or on the edge of the extent.\n *\n * @param {Extent} extent Extent.\n * @param {import(\"./coordinate.js\").Coordinate} coordinate Coordinate.\n * @return {boolean} The coordinate is contained in the extent.\n * @api\n */\nexport function containsCoordinate(extent, coordinate) {\n  return containsXY(extent, coordinate[0], coordinate[1]);\n}\n\n/**\n * Check if one extent contains another.\n *\n * An extent is deemed contained if it lies completely within the other extent,\n * including if they share one or more edges.\n *\n * @param {Extent} extent1 Extent 1.\n * @param {Extent} extent2 Extent 2.\n * @return {boolean} The second extent is contained by or on the edge of the\n *     first.\n * @api\n */\nexport function containsExtent(extent1, extent2) {\n  return (\n    extent1[0] <= extent2[0] &&\n    extent2[2] <= extent1[2] &&\n    extent1[1] <= extent2[1] &&\n    extent2[3] <= extent1[3]\n  );\n}\n\n/**\n * Check if the passed coordinate is contained or on the edge of the extent.\n *\n * @param {Extent} extent Extent.\n * @param {number} x X coordinate.\n * @param {number} y Y coordinate.\n * @return {boolean} The x, y values are contained in the extent.\n * @api\n */\nexport function containsXY(extent, x, y) {\n  return extent[0] <= x && x <= extent[2] && extent[1] <= y && y <= extent[3];\n}\n\n/**\n * Get the relationship between a coordinate and extent.\n * @param {Extent} extent The extent.\n * @param {import(\"./coordinate.js\").Coordinate} coordinate The coordinate.\n * @return {import(\"./extent/Relationship.js\").default} The relationship (bitwise compare with\n *     import(\"./extent/Relationship.js\").Relationship).\n */\nexport function coordinateRelationship(extent, coordinate) {\n  const minX = extent[0];\n  const minY = extent[1];\n  const maxX = extent[2];\n  const maxY = extent[3];\n  const x = coordinate[0];\n  const y = coordinate[1];\n  let relationship = Relationship.UNKNOWN;\n  if (x < minX) {\n    relationship = relationship | Relationship.LEFT;\n  } else if (x > maxX) {\n    relationship = relationship | Relationship.RIGHT;\n  }\n  if (y < minY) {\n    relationship = relationship | Relationship.BELOW;\n  } else if (y > maxY) {\n    relationship = relationship | Relationship.ABOVE;\n  }\n  if (relationship === Relationship.UNKNOWN) {\n    relationship = Relationship.INTERSECTING;\n  }\n  return relationship;\n}\n\n/**\n * Create an empty extent.\n * @return {Extent} Empty extent.\n * @api\n */\nexport function createEmpty() {\n  return [Infinity, Infinity, -Infinity, -Infinity];\n}\n\n/**\n * Create a new extent or update the provided extent.\n * @param {number} minX Minimum X.\n * @param {number} minY Minimum Y.\n * @param {number} maxX Maximum X.\n * @param {number} maxY Maximum Y.\n * @param {Extent} [dest] Destination extent.\n * @return {Extent} Extent.\n */\nexport function createOrUpdate(minX, minY, maxX, maxY, dest) {\n  if (dest) {\n    dest[0] = minX;\n    dest[1] = minY;\n    dest[2] = maxX;\n    dest[3] = maxY;\n    return dest;\n  }\n  return [minX, minY, maxX, maxY];\n}\n\n/**\n * Create a new empty extent or make the provided one empty.\n * @param {Extent} [dest] Extent.\n * @return {Extent} Extent.\n */\nexport function createOrUpdateEmpty(dest) {\n  return createOrUpdate(Infinity, Infinity, -Infinity, -Infinity, dest);\n}\n\n/**\n * @param {import(\"./coordinate.js\").Coordinate} coordinate Coordinate.\n * @param {Extent} [dest] Extent.\n * @return {Extent} Extent.\n */\nexport function createOrUpdateFromCoordinate(coordinate, dest) {\n  const x = coordinate[0];\n  const y = coordinate[1];\n  return createOrUpdate(x, y, x, y, dest);\n}\n\n/**\n * @param {Array<import(\"./coordinate.js\").Coordinate>} coordinates Coordinates.\n * @param {Extent} [dest] Extent.\n * @return {Extent} Extent.\n */\nexport function createOrUpdateFromCoordinates(coordinates, dest) {\n  const extent = createOrUpdateEmpty(dest);\n  return extendCoordinates(extent, coordinates);\n}\n\n/**\n * @param {Array<number>} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {number} end End.\n * @param {number} stride Stride.\n * @param {Extent} [dest] Extent.\n * @return {Extent} Extent.\n */\nexport function createOrUpdateFromFlatCoordinates(\n  flatCoordinates,\n  offset,\n  end,\n  stride,\n  dest,\n) {\n  const extent = createOrUpdateEmpty(dest);\n  return extendFlatCoordinates(extent, flatCoordinates, offset, end, stride);\n}\n\n/**\n * @param {Array<Array<import(\"./coordinate.js\").Coordinate>>} rings Rings.\n * @param {Extent} [dest] Extent.\n * @return {Extent} Extent.\n */\nexport function createOrUpdateFromRings(rings, dest) {\n  const extent = createOrUpdateEmpty(dest);\n  return extendRings(extent, rings);\n}\n\n/**\n * Determine if two extents are equivalent.\n * @param {Extent} extent1 Extent 1.\n * @param {Extent} extent2 Extent 2.\n * @return {boolean} The two extents are equivalent.\n * @api\n */\nexport function equals(extent1, extent2) {\n  return (\n    extent1[0] == extent2[0] &&\n    extent1[2] == extent2[2] &&\n    extent1[1] == extent2[1] &&\n    extent1[3] == extent2[3]\n  );\n}\n\n/**\n * Determine if two extents are approximately equivalent.\n * @param {Extent} extent1 Extent 1.\n * @param {Extent} extent2 Extent 2.\n * @param {number} tolerance Tolerance in extent coordinate units.\n * @return {boolean} The two extents differ by less than the tolerance.\n */\nexport function approximatelyEquals(extent1, extent2, tolerance) {\n  return (\n    Math.abs(extent1[0] - extent2[0]) < tolerance &&\n    Math.abs(extent1[2] - extent2[2]) < tolerance &&\n    Math.abs(extent1[1] - extent2[1]) < tolerance &&\n    Math.abs(extent1[3] - extent2[3]) < tolerance\n  );\n}\n\n/**\n * Modify an extent to include another extent.\n * @param {Extent} extent1 The extent to be modified.\n * @param {Extent} extent2 The extent that will be included in the first.\n * @return {Extent} A reference to the first (extended) extent.\n * @api\n */\nexport function extend(extent1, extent2) {\n  if (extent2[0] < extent1[0]) {\n    extent1[0] = extent2[0];\n  }\n  if (extent2[2] > extent1[2]) {\n    extent1[2] = extent2[2];\n  }\n  if (extent2[1] < extent1[1]) {\n    extent1[1] = extent2[1];\n  }\n  if (extent2[3] > extent1[3]) {\n    extent1[3] = extent2[3];\n  }\n  return extent1;\n}\n\n/**\n * @param {Extent} extent Extent.\n * @param {import(\"./coordinate.js\").Coordinate} coordinate Coordinate.\n */\nexport function extendCoordinate(extent, coordinate) {\n  if (coordinate[0] < extent[0]) {\n    extent[0] = coordinate[0];\n  }\n  if (coordinate[0] > extent[2]) {\n    extent[2] = coordinate[0];\n  }\n  if (coordinate[1] < extent[1]) {\n    extent[1] = coordinate[1];\n  }\n  if (coordinate[1] > extent[3]) {\n    extent[3] = coordinate[1];\n  }\n}\n\n/**\n * @param {Extent} extent Extent.\n * @param {Array<import(\"./coordinate.js\").Coordinate>} coordinates Coordinates.\n * @return {Extent} Extent.\n */\nexport function extendCoordinates(extent, coordinates) {\n  for (let i = 0, ii = coordinates.length; i < ii; ++i) {\n    extendCoordinate(extent, coordinates[i]);\n  }\n  return extent;\n}\n\n/**\n * @param {Extent} extent Extent.\n * @param {Array<number>} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {number} end End.\n * @param {number} stride Stride.\n * @return {Extent} Extent.\n */\nexport function extendFlatCoordinates(\n  extent,\n  flatCoordinates,\n  offset,\n  end,\n  stride,\n) {\n  for (; offset < end; offset += stride) {\n    extendXY(extent, flatCoordinates[offset], flatCoordinates[offset + 1]);\n  }\n  return extent;\n}\n\n/**\n * @param {Extent} extent Extent.\n * @param {Array<Array<import(\"./coordinate.js\").Coordinate>>} rings Rings.\n * @return {Extent} Extent.\n */\nexport function extendRings(extent, rings) {\n  for (let i = 0, ii = rings.length; i < ii; ++i) {\n    extendCoordinates(extent, rings[i]);\n  }\n  return extent;\n}\n\n/**\n * @param {Extent} extent Extent.\n * @param {number} x X.\n * @param {number} y Y.\n */\nexport function extendXY(extent, x, y) {\n  extent[0] = Math.min(extent[0], x);\n  extent[1] = Math.min(extent[1], y);\n  extent[2] = Math.max(extent[2], x);\n  extent[3] = Math.max(extent[3], y);\n}\n\n/**\n * This function calls `callback` for each corner of the extent. If the\n * callback returns a truthy value the function returns that value\n * immediately. Otherwise the function returns `false`.\n * @param {Extent} extent Extent.\n * @param {function(import(\"./coordinate.js\").Coordinate): S} callback Callback.\n * @return {S|boolean} Value.\n * @template S\n */\nexport function forEachCorner(extent, callback) {\n  let val;\n  val = callback(getBottomLeft(extent));\n  if (val) {\n    return val;\n  }\n  val = callback(getBottomRight(extent));\n  if (val) {\n    return val;\n  }\n  val = callback(getTopRight(extent));\n  if (val) {\n    return val;\n  }\n  val = callback(getTopLeft(extent));\n  if (val) {\n    return val;\n  }\n  return false;\n}\n\n/**\n * Get the size of an extent.\n * @param {Extent} extent Extent.\n * @return {number} Area.\n * @api\n */\nexport function getArea(extent) {\n  let area = 0;\n  if (!isEmpty(extent)) {\n    area = getWidth(extent) * getHeight(extent);\n  }\n  return area;\n}\n\n/**\n * Get the bottom left coordinate of an extent.\n * @param {Extent} extent Extent.\n * @return {import(\"./coordinate.js\").Coordinate} Bottom left coordinate.\n * @api\n */\nexport function getBottomLeft(extent) {\n  return [extent[0], extent[1]];\n}\n\n/**\n * Get the bottom right coordinate of an extent.\n * @param {Extent} extent Extent.\n * @return {import(\"./coordinate.js\").Coordinate} Bottom right coordinate.\n * @api\n */\nexport function getBottomRight(extent) {\n  return [extent[2], extent[1]];\n}\n\n/**\n * Get the center coordinate of an extent.\n * @param {Extent} extent Extent.\n * @return {import(\"./coordinate.js\").Coordinate} Center.\n * @api\n */\nexport function getCenter(extent) {\n  return [(extent[0] + extent[2]) / 2, (extent[1] + extent[3]) / 2];\n}\n\n/**\n * Get a corner coordinate of an extent.\n * @param {Extent} extent Extent.\n * @param {Corner} corner Corner.\n * @return {import(\"./coordinate.js\").Coordinate} Corner coordinate.\n */\nexport function getCorner(extent, corner) {\n  let coordinate;\n  if (corner === 'bottom-left') {\n    coordinate = getBottomLeft(extent);\n  } else if (corner === 'bottom-right') {\n    coordinate = getBottomRight(extent);\n  } else if (corner === 'top-left') {\n    coordinate = getTopLeft(extent);\n  } else if (corner === 'top-right') {\n    coordinate = getTopRight(extent);\n  } else {\n    throw new Error('Invalid corner');\n  }\n  return coordinate;\n}\n\n/**\n * @param {Extent} extent1 Extent 1.\n * @param {Extent} extent2 Extent 2.\n * @return {number} Enlarged area.\n */\nexport function getEnlargedArea(extent1, extent2) {\n  const minX = Math.min(extent1[0], extent2[0]);\n  const minY = Math.min(extent1[1], extent2[1]);\n  const maxX = Math.max(extent1[2], extent2[2]);\n  const maxY = Math.max(extent1[3], extent2[3]);\n  return (maxX - minX) * (maxY - minY);\n}\n\n/**\n * @param {import(\"./coordinate.js\").Coordinate} center Center.\n * @param {number} resolution Resolution.\n * @param {number} rotation Rotation.\n * @param {import(\"./size.js\").Size} size Size.\n * @param {Extent} [dest] Destination extent.\n * @return {Extent} Extent.\n */\nexport function getForViewAndSize(center, resolution, rotation, size, dest) {\n  const [x0, y0, x1, y1, x2, y2, x3, y3] = getRotatedViewport(\n    center,\n    resolution,\n    rotation,\n    size,\n  );\n  return createOrUpdate(\n    Math.min(x0, x1, x2, x3),\n    Math.min(y0, y1, y2, y3),\n    Math.max(x0, x1, x2, x3),\n    Math.max(y0, y1, y2, y3),\n    dest,\n  );\n}\n\n/**\n * @param {import(\"./coordinate.js\").Coordinate} center Center.\n * @param {number} resolution Resolution.\n * @param {number} rotation Rotation.\n * @param {import(\"./size.js\").Size} size Size.\n * @return {Array<number>} Linear ring representing the viewport.\n */\nexport function getRotatedViewport(center, resolution, rotation, size) {\n  const dx = (resolution * size[0]) / 2;\n  const dy = (resolution * size[1]) / 2;\n  const cosRotation = Math.cos(rotation);\n  const sinRotation = Math.sin(rotation);\n  const xCos = dx * cosRotation;\n  const xSin = dx * sinRotation;\n  const yCos = dy * cosRotation;\n  const ySin = dy * sinRotation;\n  const x = center[0];\n  const y = center[1];\n  return [\n    x - xCos + ySin,\n    y - xSin - yCos,\n    x - xCos - ySin,\n    y - xSin + yCos,\n    x + xCos - ySin,\n    y + xSin + yCos,\n    x + xCos + ySin,\n    y + xSin - yCos,\n    x - xCos + ySin,\n    y - xSin - yCos,\n  ];\n}\n\n/**\n * Get the height of an extent.\n * @param {Extent} extent Extent.\n * @return {number} Height.\n * @api\n */\nexport function getHeight(extent) {\n  return extent[3] - extent[1];\n}\n\n/**\n * @param {Extent} extent1 Extent 1.\n * @param {Extent} extent2 Extent 2.\n * @return {number} Intersection area.\n */\nexport function getIntersectionArea(extent1, extent2) {\n  const intersection = getIntersection(extent1, extent2);\n  return getArea(intersection);\n}\n\n/**\n * Get the intersection of two extents.\n * @param {Extent} extent1 Extent 1.\n * @param {Extent} extent2 Extent 2.\n * @param {Extent} [dest] Optional extent to populate with intersection.\n * @return {Extent} Intersecting extent.\n * @api\n */\nexport function getIntersection(extent1, extent2, dest) {\n  const intersection = dest ? dest : createEmpty();\n  if (intersects(extent1, extent2)) {\n    if (extent1[0] > extent2[0]) {\n      intersection[0] = extent1[0];\n    } else {\n      intersection[0] = extent2[0];\n    }\n    if (extent1[1] > extent2[1]) {\n      intersection[1] = extent1[1];\n    } else {\n      intersection[1] = extent2[1];\n    }\n    if (extent1[2] < extent2[2]) {\n      intersection[2] = extent1[2];\n    } else {\n      intersection[2] = extent2[2];\n    }\n    if (extent1[3] < extent2[3]) {\n      intersection[3] = extent1[3];\n    } else {\n      intersection[3] = extent2[3];\n    }\n  } else {\n    createOrUpdateEmpty(intersection);\n  }\n  return intersection;\n}\n\n/**\n * @param {Extent} extent Extent.\n * @return {number} Margin.\n */\nexport function getMargin(extent) {\n  return getWidth(extent) + getHeight(extent);\n}\n\n/**\n * Get the size (width, height) of an extent.\n * @param {Extent} extent The extent.\n * @return {import(\"./size.js\").Size} The extent size.\n * @api\n */\nexport function getSize(extent) {\n  return [extent[2] - extent[0], extent[3] - extent[1]];\n}\n\n/**\n * Get the top left coordinate of an extent.\n * @param {Extent} extent Extent.\n * @return {import(\"./coordinate.js\").Coordinate} Top left coordinate.\n * @api\n */\nexport function getTopLeft(extent) {\n  return [extent[0], extent[3]];\n}\n\n/**\n * Get the top right coordinate of an extent.\n * @param {Extent} extent Extent.\n * @return {import(\"./coordinate.js\").Coordinate} Top right coordinate.\n * @api\n */\nexport function getTopRight(extent) {\n  return [extent[2], extent[3]];\n}\n\n/**\n * Get the width of an extent.\n * @param {Extent} extent Extent.\n * @return {number} Width.\n * @api\n */\nexport function getWidth(extent) {\n  return extent[2] - extent[0];\n}\n\n/**\n * Determine if one extent intersects another.\n * @param {Extent} extent1 Extent 1.\n * @param {Extent} extent2 Extent.\n * @return {boolean} The two extents intersect.\n * @api\n */\nexport function intersects(extent1, extent2) {\n  return (\n    extent1[0] <= extent2[2] &&\n    extent1[2] >= extent2[0] &&\n    extent1[1] <= extent2[3] &&\n    extent1[3] >= extent2[1]\n  );\n}\n\n/**\n * Determine if an extent is empty.\n * @param {Extent} extent Extent.\n * @return {boolean} Is empty.\n * @api\n */\nexport function isEmpty(extent) {\n  return extent[2] < extent[0] || extent[3] < extent[1];\n}\n\n/**\n * @param {Extent} extent Extent.\n * @param {Extent} [dest] Extent.\n * @return {Extent} Extent.\n */\nexport function returnOrUpdate(extent, dest) {\n  if (dest) {\n    dest[0] = extent[0];\n    dest[1] = extent[1];\n    dest[2] = extent[2];\n    dest[3] = extent[3];\n    return dest;\n  }\n  return extent;\n}\n\n/**\n * @param {Extent} extent Extent.\n * @param {number} value Value.\n */\nexport function scaleFromCenter(extent, value) {\n  const deltaX = ((extent[2] - extent[0]) / 2) * (value - 1);\n  const deltaY = ((extent[3] - extent[1]) / 2) * (value - 1);\n  extent[0] -= deltaX;\n  extent[2] += deltaX;\n  extent[1] -= deltaY;\n  extent[3] += deltaY;\n}\n\n/**\n * Determine if the segment between two coordinates intersects (crosses,\n * touches, or is contained by) the provided extent.\n * @param {Extent} extent The extent.\n * @param {import(\"./coordinate.js\").Coordinate} start Segment start coordinate.\n * @param {import(\"./coordinate.js\").Coordinate} end Segment end coordinate.\n * @return {boolean} The segment intersects the extent.\n */\nexport function intersectsSegment(extent, start, end) {\n  let intersects = false;\n  const startRel = coordinateRelationship(extent, start);\n  const endRel = coordinateRelationship(extent, end);\n  if (\n    startRel === Relationship.INTERSECTING ||\n    endRel === Relationship.INTERSECTING\n  ) {\n    intersects = true;\n  } else {\n    const minX = extent[0];\n    const minY = extent[1];\n    const maxX = extent[2];\n    const maxY = extent[3];\n    const startX = start[0];\n    const startY = start[1];\n    const endX = end[0];\n    const endY = end[1];\n    const slope = (endY - startY) / (endX - startX);\n    let x, y;\n    if (!!(endRel & Relationship.ABOVE) && !(startRel & Relationship.ABOVE)) {\n      // potentially intersects top\n      x = endX - (endY - maxY) / slope;\n      intersects = x >= minX && x <= maxX;\n    }\n    if (\n      !intersects &&\n      !!(endRel & Relationship.RIGHT) &&\n      !(startRel & Relationship.RIGHT)\n    ) {\n      // potentially intersects right\n      y = endY - (endX - maxX) * slope;\n      intersects = y >= minY && y <= maxY;\n    }\n    if (\n      !intersects &&\n      !!(endRel & Relationship.BELOW) &&\n      !(startRel & Relationship.BELOW)\n    ) {\n      // potentially intersects bottom\n      x = endX - (endY - minY) / slope;\n      intersects = x >= minX && x <= maxX;\n    }\n    if (\n      !intersects &&\n      !!(endRel & Relationship.LEFT) &&\n      !(startRel & Relationship.LEFT)\n    ) {\n      // potentially intersects left\n      y = endY - (endX - minX) * slope;\n      intersects = y >= minY && y <= maxY;\n    }\n  }\n  return intersects;\n}\n\n/**\n * Apply a transform function to the extent.\n * @param {Extent} extent Extent.\n * @param {import(\"./proj.js\").TransformFunction} transformFn Transform function.\n * Called with `[minX, minY, maxX, maxY]` extent coordinates.\n * @param {Extent} [dest] Destination extent.\n * @param {number} [stops] Number of stops per side used for the transform.\n * By default only the corners are used.\n * @return {Extent} Extent.\n * @api\n */\nexport function applyTransform(extent, transformFn, dest, stops) {\n  if (isEmpty(extent)) {\n    return createOrUpdateEmpty(dest);\n  }\n  let coordinates = [];\n  if (stops > 1) {\n    const width = extent[2] - extent[0];\n    const height = extent[3] - extent[1];\n    for (let i = 0; i < stops; ++i) {\n      coordinates.push(\n        extent[0] + (width * i) / stops,\n        extent[1],\n        extent[2],\n        extent[1] + (height * i) / stops,\n        extent[2] - (width * i) / stops,\n        extent[3],\n        extent[0],\n        extent[3] - (height * i) / stops,\n      );\n    }\n  } else {\n    coordinates = [\n      extent[0],\n      extent[1],\n      extent[2],\n      extent[1],\n      extent[2],\n      extent[3],\n      extent[0],\n      extent[3],\n    ];\n  }\n  transformFn(coordinates, coordinates, 2);\n  const xs = [];\n  const ys = [];\n  for (let i = 0, l = coordinates.length; i < l; i += 2) {\n    xs.push(coordinates[i]);\n    ys.push(coordinates[i + 1]);\n  }\n  return _boundingExtentXYs(xs, ys, dest);\n}\n\n/**\n * Modifies the provided extent in-place to be within the real world\n * extent.\n *\n * @param {Extent} extent Extent.\n * @param {import(\"./proj/Projection.js\").default} projection Projection\n * @return {Extent} The extent within the real world extent.\n */\nexport function wrapX(extent, projection) {\n  const projectionExtent = projection.getExtent();\n  const center = getCenter(extent);\n  if (\n    projection.canWrapX() &&\n    (center[0] < projectionExtent[0] || center[0] >= projectionExtent[2])\n  ) {\n    const worldWidth = getWidth(projectionExtent);\n    const worldsAway = Math.floor(\n      (center[0] - projectionExtent[0]) / worldWidth,\n    );\n    const offset = worldsAway * worldWidth;\n    extent[0] -= offset;\n    extent[2] -= offset;\n  }\n  return extent;\n}\n\n/**\n * Fits the extent to the real world\n *\n * If the extent does not cross the anti meridian, this will return the extent in an array\n * If the extent crosses the anti meridian, the extent will be sliced, so each part fits within the\n * real world\n *\n *\n * @param {Extent} extent Extent.\n * @param {import(\"./proj/Projection.js\").default} projection Projection\n * @param {boolean} [multiWorld] Return all worlds\n * @return {Array<Extent>} The extent within the real world extent.\n */\nexport function wrapAndSliceX(extent, projection, multiWorld) {\n  if (projection.canWrapX()) {\n    const projectionExtent = projection.getExtent();\n\n    if (!isFinite(extent[0]) || !isFinite(extent[2])) {\n      return [[projectionExtent[0], extent[1], projectionExtent[2], extent[3]]];\n    }\n\n    wrapX(extent, projection);\n    const worldWidth = getWidth(projectionExtent);\n\n    if (getWidth(extent) > worldWidth && !multiWorld) {\n      // the extent wraps around on itself\n      return [[projectionExtent[0], extent[1], projectionExtent[2], extent[3]]];\n    }\n    if (extent[0] < projectionExtent[0]) {\n      // the extent crosses the anti meridian, so it needs to be sliced\n      return [\n        [extent[0] + worldWidth, extent[1], projectionExtent[2], extent[3]],\n        [projectionExtent[0], extent[1], extent[2], extent[3]],\n      ];\n    }\n    if (extent[2] > projectionExtent[2]) {\n      // the extent crosses the anti meridian, so it needs to be sliced\n      return [\n        [extent[0], extent[1], projectionExtent[2], extent[3]],\n        [projectionExtent[0], extent[1], extent[2] - worldWidth, extent[3]],\n      ];\n    }\n  }\n\n  return [extent];\n}\n", "/**\n * @module ol/string\n */\n\n/**\n * @param {number} number Number to be formatted\n * @param {number} width The desired width\n * @param {number} [precision] Precision of the output string (i.e. number of decimal places)\n * @return {string} Formatted string\n */\nexport function padNumber(number, width, precision) {\n  const numberString =\n    precision !== undefined ? number.toFixed(precision) : '' + number;\n  let decimal = numberString.indexOf('.');\n  decimal = decimal === -1 ? numberString.length : decimal;\n  return decimal > width\n    ? numberString\n    : new Array(1 + width - decimal).join('0') + numberString;\n}\n\n/**\n * Adapted from https://github.com/omichelsen/compare-versions/blob/master/index.js\n * @param {string|number} v1 First version\n * @param {string|number} v2 Second version\n * @return {number} Value\n */\nexport function compareVersions(v1, v2) {\n  const s1 = ('' + v1).split('.');\n  const s2 = ('' + v2).split('.');\n\n  for (let i = 0; i < Math.max(s1.length, s2.length); i++) {\n    const n1 = parseInt(s1[i] || '0', 10);\n    const n2 = parseInt(s2[i] || '0', 10);\n\n    if (n1 > n2) {\n      return 1;\n    }\n    if (n2 > n1) {\n      return -1;\n    }\n  }\n\n  return 0;\n}\n", "/**\n * @module ol/coordinate\n */\nimport {getWidth} from './extent.js';\nimport {clamp, modulo, toFixed} from './math.js';\nimport {padNumber} from './string.js';\n\n/**\n * An array of numbers representing an `xy`, `xyz` or `xyzm` coordinate.\n * Example: `[16, 48]`.\n * @typedef {Array<number>} Coordinate\n * @api\n */\n\n/**\n * A function that takes a {@link module:ol/coordinate~Coordinate} and\n * transforms it into a `{string}`.\n *\n * @typedef {function((Coordinate|undefined)): string} CoordinateFormat\n * @api\n */\n\n/**\n * Add `delta` to `coordinate`. `coordinate` is modified in place and returned\n * by the function.\n *\n * Example:\n *\n *     import {add} from 'ol/coordinate.js';\n *\n *     const coord = [7.85, 47.983333];\n *     add(coord, [-2, 4]);\n *     // coord is now [5.85, 51.983333]\n *\n * @param {Coordinate} coordinate Coordinate.\n * @param {Coordinate} delta Delta.\n * @return {Coordinate} The input coordinate adjusted by\n * the given delta.\n * @api\n */\nexport function add(coordinate, delta) {\n  coordinate[0] += +delta[0];\n  coordinate[1] += +delta[1];\n  return coordinate;\n}\n\n/**\n * Calculates the point closest to the passed coordinate on the passed circle.\n *\n * @param {Coordinate} coordinate The coordinate.\n * @param {import(\"./geom/Circle.js\").default} circle The circle.\n * @return {Coordinate} Closest point on the circumference.\n */\nexport function closestOnCircle(coordinate, circle) {\n  const r = circle.getRadius();\n  const center = circle.getCenter();\n  const x0 = center[0];\n  const y0 = center[1];\n  const x1 = coordinate[0];\n  const y1 = coordinate[1];\n\n  let dx = x1 - x0;\n  const dy = y1 - y0;\n  if (dx === 0 && dy === 0) {\n    dx = 1;\n  }\n  const d = Math.sqrt(dx * dx + dy * dy);\n\n  const x = x0 + (r * dx) / d;\n  const y = y0 + (r * dy) / d;\n\n  return [x, y];\n}\n\n/**\n * Calculates the point closest to the passed coordinate on the passed segment.\n * This is the foot of the perpendicular of the coordinate to the segment when\n * the foot is on the segment, or the closest segment coordinate when the foot\n * is outside the segment.\n *\n * @param {Coordinate} coordinate The coordinate.\n * @param {Array<Coordinate>} segment The two coordinates\n * of the segment.\n * @return {Coordinate} The foot of the perpendicular of\n * the coordinate to the segment.\n */\nexport function closestOnSegment(coordinate, segment) {\n  const x0 = coordinate[0];\n  const y0 = coordinate[1];\n  const start = segment[0];\n  const end = segment[1];\n  const x1 = start[0];\n  const y1 = start[1];\n  const x2 = end[0];\n  const y2 = end[1];\n  const dx = x2 - x1;\n  const dy = y2 - y1;\n  const along =\n    dx === 0 && dy === 0\n      ? 0\n      : (dx * (x0 - x1) + dy * (y0 - y1)) / (dx * dx + dy * dy || 0);\n  let x, y;\n  if (along <= 0) {\n    x = x1;\n    y = y1;\n  } else if (along >= 1) {\n    x = x2;\n    y = y2;\n  } else {\n    x = x1 + along * dx;\n    y = y1 + along * dy;\n  }\n  return [x, y];\n}\n\n/**\n * Returns a {@link module:ol/coordinate~CoordinateFormat} function that can be\n * used to format\n * a {Coordinate} to a string.\n *\n * Example without specifying the fractional digits:\n *\n *     import {createStringXY} from 'ol/coordinate.js';\n *\n *     const coord = [7.85, 47.983333];\n *     const stringifyFunc = createStringXY();\n *     const out = stringifyFunc(coord);\n *     // out is now '8, 48'\n *\n * Example with explicitly specifying 2 fractional digits:\n *\n *     import {createStringXY} from 'ol/coordinate.js';\n *\n *     const coord = [7.85, 47.983333];\n *     const stringifyFunc = createStringXY(2);\n *     const out = stringifyFunc(coord);\n *     // out is now '7.85, 47.98'\n *\n * @param {number} [fractionDigits] The number of digits to include\n *    after the decimal point. Default is `0`.\n * @return {CoordinateFormat} Coordinate format.\n * @api\n */\nexport function createStringXY(fractionDigits) {\n  return (\n    /**\n     * @param {Coordinate} coordinate Coordinate.\n     * @return {string} String XY.\n     */\n    function (coordinate) {\n      return toStringXY(coordinate, fractionDigits);\n    }\n  );\n}\n\n/**\n * @param {string} hemispheres Hemispheres.\n * @param {number} degrees Degrees.\n * @param {number} [fractionDigits] The number of digits to include\n *    after the decimal point. Default is `0`.\n * @return {string} String.\n */\nexport function degreesToStringHDMS(hemispheres, degrees, fractionDigits) {\n  const normalizedDegrees = modulo(degrees + 180, 360) - 180;\n  const x = Math.abs(3600 * normalizedDegrees);\n  const decimals = fractionDigits || 0;\n\n  let deg = Math.floor(x / 3600);\n  let min = Math.floor((x - deg * 3600) / 60);\n  let sec = toFixed(x - deg * 3600 - min * 60, decimals);\n\n  if (sec >= 60) {\n    sec = 0;\n    min += 1;\n  }\n\n  if (min >= 60) {\n    min = 0;\n    deg += 1;\n  }\n\n  let hdms = deg + '\\u00b0';\n  if (min !== 0 || sec !== 0) {\n    hdms += ' ' + padNumber(min, 2) + '\\u2032';\n  }\n  if (sec !== 0) {\n    hdms += ' ' + padNumber(sec, 2, decimals) + '\\u2033';\n  }\n  if (normalizedDegrees !== 0) {\n    hdms += ' ' + hemispheres.charAt(normalizedDegrees < 0 ? 1 : 0);\n  }\n\n  return hdms;\n}\n\n/**\n * Transforms the given {@link module:ol/coordinate~Coordinate} to a string\n * using the given string template. The strings `{x}` and `{y}` in the template\n * will be replaced with the first and second coordinate values respectively.\n *\n * Example without specifying the fractional digits:\n *\n *     import {format} from 'ol/coordinate.js';\n *\n *     const coord = [7.85, 47.983333];\n *     const template = 'Coordinate is ({x}|{y}).';\n *     const out = format(coord, template);\n *     // out is now 'Coordinate is (8|48).'\n *\n * Example explicitly specifying the fractional digits:\n *\n *     import {format} from 'ol/coordinate.js';\n *\n *     const coord = [7.85, 47.983333];\n *     const template = 'Coordinate is ({x}|{y}).';\n *     const out = format(coord, template, 2);\n *     // out is now 'Coordinate is (7.85|47.98).'\n *\n * @param {Coordinate} coordinate Coordinate.\n * @param {string} template A template string with `{x}` and `{y}` placeholders\n *     that will be replaced by first and second coordinate values.\n * @param {number} [fractionDigits] The number of digits to include\n *    after the decimal point. Default is `0`.\n * @return {string} Formatted coordinate.\n * @api\n */\nexport function format(coordinate, template, fractionDigits) {\n  if (coordinate) {\n    return template\n      .replace('{x}', coordinate[0].toFixed(fractionDigits))\n      .replace('{y}', coordinate[1].toFixed(fractionDigits));\n  }\n  return '';\n}\n\n/**\n * @param {Coordinate} coordinate1 First coordinate.\n * @param {Coordinate} coordinate2 Second coordinate.\n * @return {boolean} The two coordinates are equal.\n */\nexport function equals(coordinate1, coordinate2) {\n  let equals = true;\n  for (let i = coordinate1.length - 1; i >= 0; --i) {\n    if (coordinate1[i] != coordinate2[i]) {\n      equals = false;\n      break;\n    }\n  }\n  return equals;\n}\n\n/**\n * Rotate `coordinate` by `angle`. `coordinate` is modified in place and\n * returned by the function.\n *\n * Example:\n *\n *     import {rotate} from 'ol/coordinate.js';\n *\n *     const coord = [7.85, 47.983333];\n *     const rotateRadians = Math.PI / 2; // 90 degrees\n *     rotate(coord, rotateRadians);\n *     // coord is now [-47.983333, 7.85]\n *\n * @param {Coordinate} coordinate Coordinate.\n * @param {number} angle Angle in radian.\n * @return {Coordinate} Coordinate.\n * @api\n */\nexport function rotate(coordinate, angle) {\n  const cosAngle = Math.cos(angle);\n  const sinAngle = Math.sin(angle);\n  const x = coordinate[0] * cosAngle - coordinate[1] * sinAngle;\n  const y = coordinate[1] * cosAngle + coordinate[0] * sinAngle;\n  coordinate[0] = x;\n  coordinate[1] = y;\n  return coordinate;\n}\n\n/**\n * Scale `coordinate` by `scale`. `coordinate` is modified in place and returned\n * by the function.\n *\n * Example:\n *\n *     import {scale as scaleCoordinate} from 'ol/coordinate.js';\n *\n *     const coord = [7.85, 47.983333];\n *     const scale = 1.2;\n *     scaleCoordinate(coord, scale);\n *     // coord is now [9.42, 57.5799996]\n *\n * @param {Coordinate} coordinate Coordinate.\n * @param {number} scale Scale factor.\n * @return {Coordinate} Coordinate.\n */\nexport function scale(coordinate, scale) {\n  coordinate[0] *= scale;\n  coordinate[1] *= scale;\n  return coordinate;\n}\n\n/**\n * @param {Coordinate} coord1 First coordinate.\n * @param {Coordinate} coord2 Second coordinate.\n * @return {number} Squared distance between coord1 and coord2.\n */\nexport function squaredDistance(coord1, coord2) {\n  const dx = coord1[0] - coord2[0];\n  const dy = coord1[1] - coord2[1];\n  return dx * dx + dy * dy;\n}\n\n/**\n * @param {Coordinate} coord1 First coordinate.\n * @param {Coordinate} coord2 Second coordinate.\n * @return {number} Distance between coord1 and coord2.\n */\nexport function distance(coord1, coord2) {\n  return Math.sqrt(squaredDistance(coord1, coord2));\n}\n\n/**\n * Calculate the squared distance from a coordinate to a line segment.\n *\n * @param {Coordinate} coordinate Coordinate of the point.\n * @param {Array<Coordinate>} segment Line segment (2\n * coordinates).\n * @return {number} Squared distance from the point to the line segment.\n */\nexport function squaredDistanceToSegment(coordinate, segment) {\n  return squaredDistance(coordinate, closestOnSegment(coordinate, segment));\n}\n\n/**\n * Format a geographic coordinate with the hemisphere, degrees, minutes, and\n * seconds.\n *\n * Example without specifying fractional digits:\n *\n *     import {toStringHDMS} from 'ol/coordinate.js';\n *\n *     const coord = [7.85, 47.983333];\n *     const out = toStringHDMS(coord);\n *     // out is now '47\u00B0 58\u2032 60\u2033 N 7\u00B0 50\u2032 60\u2033 E'\n *\n * Example explicitly specifying 1 fractional digit:\n *\n *     import {toStringHDMS} from 'ol/coordinate.js';\n *\n *     const coord = [7.85, 47.983333];\n *     const out = toStringHDMS(coord, 1);\n *     // out is now '47\u00B0 58\u2032 60.0\u2033 N 7\u00B0 50\u2032 60.0\u2033 E'\n *\n * @param {Coordinate} coordinate Coordinate.\n * @param {number} [fractionDigits] The number of digits to include\n *    after the decimal point. Default is `0`.\n * @return {string} Hemisphere, degrees, minutes and seconds.\n * @api\n */\nexport function toStringHDMS(coordinate, fractionDigits) {\n  if (coordinate) {\n    return (\n      degreesToStringHDMS('NS', coordinate[1], fractionDigits) +\n      ' ' +\n      degreesToStringHDMS('EW', coordinate[0], fractionDigits)\n    );\n  }\n  return '';\n}\n\n/**\n * Format a coordinate as a comma delimited string.\n *\n * Example without specifying fractional digits:\n *\n *     import {toStringXY} from 'ol/coordinate.js';\n *\n *     const coord = [7.85, 47.983333];\n *     const out = toStringXY(coord);\n *     // out is now '8, 48'\n *\n * Example explicitly specifying 1 fractional digit:\n *\n *     import {toStringXY} from 'ol/coordinate.js';\n *\n *     const coord = [7.85, 47.983333];\n *     const out = toStringXY(coord, 1);\n *     // out is now '7.8, 48.0'\n *\n * @param {Coordinate} coordinate Coordinate.\n * @param {number} [fractionDigits] The number of digits to include\n *    after the decimal point. Default is `0`.\n * @return {string} XY.\n * @api\n */\nexport function toStringXY(coordinate, fractionDigits) {\n  return format(coordinate, '{x}, {y}', fractionDigits);\n}\n\n/**\n * Modifies the provided coordinate in-place to be within the real world\n * extent. The lower projection extent boundary is inclusive, the upper one\n * exclusive.\n *\n * @param {Coordinate} coordinate Coordinate.\n * @param {import(\"./proj/Projection.js\").default} projection Projection.\n * @return {Coordinate} The coordinate within the real world extent.\n */\nexport function wrapX(coordinate, projection) {\n  if (projection.canWrapX()) {\n    const worldWidth = getWidth(projection.getExtent());\n    const worldsAway = getWorldsAway(coordinate, projection, worldWidth);\n    if (worldsAway) {\n      coordinate[0] -= worldsAway * worldWidth;\n    }\n  }\n  return coordinate;\n}\n/**\n * @param {Coordinate} coordinate Coordinate.\n * @param {import(\"./proj/Projection.js\").default} projection Projection.\n * @param {number} [sourceExtentWidth] Width of the source extent.\n * @return {number} Offset in world widths.\n */\nexport function getWorldsAway(coordinate, projection, sourceExtentWidth) {\n  const projectionExtent = projection.getExtent();\n  let worldsAway = 0;\n  if (\n    projection.canWrapX() &&\n    (coordinate[0] < projectionExtent[0] || coordinate[0] > projectionExtent[2])\n  ) {\n    sourceExtentWidth = sourceExtentWidth || getWidth(projectionExtent);\n    worldsAway = Math.floor(\n      (coordinate[0] - projectionExtent[0]) / sourceExtentWidth,\n    );\n  }\n  return worldsAway;\n}\n\n/**\n * Compute the angle between p0pA and p0pB\n * @param {Coordinate} p0 Point 0\n * @param {Coordinate} pA Point A\n * @param {Coordinate} pB Point B\n * @return {number} a value in [0, 2PI]\n */\nexport function angleBetween(p0, pA, pB) {\n  const lenA = Math.sqrt(\n    (pA[0] - p0[0]) * (pA[0] - p0[0]) + (pA[1] - p0[1]) * (pA[1] - p0[1]),\n  );\n  const tangentA = [(pA[0] - p0[0]) / lenA, (pA[1] - p0[1]) / lenA];\n  const orthoA = [-tangentA[1], tangentA[0]];\n  const lenB = Math.sqrt(\n    (pB[0] - p0[0]) * (pB[0] - p0[0]) + (pB[1] - p0[1]) * (pB[1] - p0[1]),\n  );\n  const tangentB = [(pB[0] - p0[0]) / lenB, (pB[1] - p0[1]) / lenB];\n\n  // this angle can be clockwise or anticlockwise; hence the computation afterwards\n  let angle =\n    lenA === 0 || lenB === 0\n      ? 0\n      : Math.acos(\n          clamp(tangentB[0] * tangentA[0] + tangentB[1] * tangentA[1], -1, 1),\n        );\n  angle = Math.max(angle, 0.00001); // avoid a zero angle otherwise this is detected as a line cap\n  const isClockwise = tangentB[0] * orthoA[0] + tangentB[1] * orthoA[1] > 0;\n  return !isClockwise ? Math.PI * 2 - angle : angle;\n}\n", "/**\n * @module ol/easing\n */\n\n/**\n * Start slow and speed up.\n * @param {number} t Input between 0 and 1.\n * @return {number} Output between 0 and 1.\n * @api\n */\nexport function easeIn(t) {\n  return Math.pow(t, 3);\n}\n\n/**\n * Start fast and slow down.\n * @param {number} t Input between 0 and 1.\n * @return {number} Output between 0 and 1.\n * @api\n */\nexport function easeOut(t) {\n  return 1 - easeIn(1 - t);\n}\n\n/**\n * Start slow, speed up, and then slow down again.\n * @param {number} t Input between 0 and 1.\n * @return {number} Output between 0 and 1.\n * @api\n */\nexport function inAndOut(t) {\n  return 3 * t * t - 2 * t * t * t;\n}\n\n/**\n * Maintain a constant speed over time.\n * @param {number} t Input between 0 and 1.\n * @return {number} Output between 0 and 1.\n * @api\n */\nexport function linear(t) {\n  return t;\n}\n\n/**\n * Start slow, speed up, and at the very end slow down again.  This has the\n * same general behavior as {@link module:ol/easing.inAndOut}, but the final\n * slowdown is delayed.\n * @param {number} t Input between 0 and 1.\n * @return {number} Output between 0 and 1.\n * @api\n */\nexport function upAndDown(t) {\n  if (t < 0.5) {\n    return inAndOut(2 * t);\n  }\n  return 1 - inAndOut(2 * (t - 0.5));\n}\n", "/**\n * @module ol/sphere\n */\nimport {toDegrees, toRadians} from './math.js';\n\n/**\n * Object literal with options for the {@link getLength} or {@link getArea}\n * functions.\n * @typedef {Object} SphereMetricOptions\n * @property {import(\"./proj.js\").ProjectionLike} [projection='EPSG:3857']\n * Projection of the  geometry.  By default, the geometry is assumed to be in\n * Web Mercator.\n * @property {number} [radius=6371008.8] Sphere radius.  By default, the\n * [mean Earth radius](https://en.wikipedia.org/wiki/Earth_radius#Mean_radius)\n * for the WGS84 ellipsoid is used.\n */\n\n/**\n * The mean Earth radius (1/3 * (2a + b)) for the WGS84 ellipsoid.\n * https://en.wikipedia.org/wiki/Earth_radius#Mean_radius\n * @type {number}\n */\nexport const DEFAULT_RADIUS = 6371008.8;\n\n/**\n * Get the great circle distance (in meters) between two geographic coordinates.\n * @param {Array} c1 Starting coordinate.\n * @param {Array} c2 Ending coordinate.\n * @param {number} [radius] The sphere radius to use.  Defaults to the Earth's\n *     mean radius using the WGS84 ellipsoid.\n * @return {number} The great circle distance between the points (in meters).\n * @api\n */\nexport function getDistance(c1, c2, radius) {\n  radius = radius || DEFAULT_RADIUS;\n  const lat1 = toRadians(c1[1]);\n  const lat2 = toRadians(c2[1]);\n  const deltaLatBy2 = (lat2 - lat1) / 2;\n  const deltaLonBy2 = toRadians(c2[0] - c1[0]) / 2;\n  const a =\n    Math.sin(deltaLatBy2) * Math.sin(deltaLatBy2) +\n    Math.sin(deltaLonBy2) *\n      Math.sin(deltaLonBy2) *\n      Math.cos(lat1) *\n      Math.cos(lat2);\n  return 2 * radius * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));\n}\n\n/**\n * Get the cumulative great circle length of linestring coordinates (geographic).\n * @param {Array} coordinates Linestring coordinates.\n * @param {number} radius The sphere radius to use.\n * @return {number} The length (in meters).\n */\nfunction getLengthInternal(coordinates, radius) {\n  let length = 0;\n  for (let i = 0, ii = coordinates.length; i < ii - 1; ++i) {\n    length += getDistance(coordinates[i], coordinates[i + 1], radius);\n  }\n  return length;\n}\n\n/**\n * Get the spherical length of a geometry.  This length is the sum of the\n * great circle distances between coordinates.  For polygons, the length is\n * the sum of all rings.  For points, the length is zero.  For multi-part\n * geometries, the length is the sum of the length of each part.\n * @param {import(\"./geom/Geometry.js\").default} geometry A geometry.\n * @param {SphereMetricOptions} [options] Options for the\n * length calculation.  By default, geometries are assumed to be in 'EPSG:3857'.\n * You can change this by providing a `projection` option.\n * @return {number} The spherical length (in meters).\n * @api\n */\nexport function getLength(geometry, options) {\n  options = options || {};\n  const radius = options.radius || DEFAULT_RADIUS;\n  const projection = options.projection || 'EPSG:3857';\n  const type = geometry.getType();\n  if (type !== 'GeometryCollection') {\n    geometry = geometry.clone().transform(projection, 'EPSG:4326');\n  }\n  let length = 0;\n  let coordinates, coords, i, ii, j, jj;\n  switch (type) {\n    case 'Point':\n    case 'MultiPoint': {\n      break;\n    }\n    case 'LineString':\n    case 'LinearRing': {\n      coordinates = /** @type {import(\"./geom/SimpleGeometry.js\").default} */ (\n        geometry\n      ).getCoordinates();\n      length = getLengthInternal(coordinates, radius);\n      break;\n    }\n    case 'MultiLineString':\n    case 'Polygon': {\n      coordinates = /** @type {import(\"./geom/SimpleGeometry.js\").default} */ (\n        geometry\n      ).getCoordinates();\n      for (i = 0, ii = coordinates.length; i < ii; ++i) {\n        length += getLengthInternal(coordinates[i], radius);\n      }\n      break;\n    }\n    case 'MultiPolygon': {\n      coordinates = /** @type {import(\"./geom/SimpleGeometry.js\").default} */ (\n        geometry\n      ).getCoordinates();\n      for (i = 0, ii = coordinates.length; i < ii; ++i) {\n        coords = coordinates[i];\n        for (j = 0, jj = coords.length; j < jj; ++j) {\n          length += getLengthInternal(coords[j], radius);\n        }\n      }\n      break;\n    }\n    case 'GeometryCollection': {\n      const geometries =\n        /** @type {import(\"./geom/GeometryCollection.js\").default} */ (\n          geometry\n        ).getGeometries();\n      for (i = 0, ii = geometries.length; i < ii; ++i) {\n        length += getLength(geometries[i], options);\n      }\n      break;\n    }\n    default: {\n      throw new Error('Unsupported geometry type: ' + type);\n    }\n  }\n  return length;\n}\n\n/**\n * Returns the spherical area for a list of coordinates.\n *\n * [Reference](https://trs.jpl.nasa.gov/handle/2014/40409)\n * Robert. G. Chamberlain and William H. Duquette, \"Some Algorithms for\n * Polygons on a Sphere\", JPL Publication 07-03, Jet Propulsion\n * Laboratory, Pasadena, CA, June 2007\n *\n * @param {Array<import(\"./coordinate.js\").Coordinate>} coordinates List of coordinates of a linear\n * ring. If the ring is oriented clockwise, the area will be positive,\n * otherwise it will be negative.\n * @param {number} radius The sphere radius.\n * @return {number} Area (in square meters).\n */\nfunction getAreaInternal(coordinates, radius) {\n  let area = 0;\n  const len = coordinates.length;\n  let x1 = coordinates[len - 1][0];\n  let y1 = coordinates[len - 1][1];\n  for (let i = 0; i < len; i++) {\n    const x2 = coordinates[i][0];\n    const y2 = coordinates[i][1];\n    area +=\n      toRadians(x2 - x1) *\n      (2 + Math.sin(toRadians(y1)) + Math.sin(toRadians(y2)));\n    x1 = x2;\n    y1 = y2;\n  }\n  return (area * radius * radius) / 2.0;\n}\n\n/**\n * Get the spherical area of a geometry.  This is the area (in meters) assuming\n * that polygon edges are segments of great circles on a sphere.\n * @param {import(\"./geom/Geometry.js\").default} geometry A geometry.\n * @param {SphereMetricOptions} [options] Options for the area\n *     calculation.  By default, geometries are assumed to be in 'EPSG:3857'.\n *     You can change this by providing a `projection` option.\n * @return {number} The spherical area (in square meters).\n * @api\n */\nexport function getArea(geometry, options) {\n  options = options || {};\n  const radius = options.radius || DEFAULT_RADIUS;\n  const projection = options.projection || 'EPSG:3857';\n  const type = geometry.getType();\n  if (type !== 'GeometryCollection') {\n    geometry = geometry.clone().transform(projection, 'EPSG:4326');\n  }\n  let area = 0;\n  let coordinates, coords, i, ii, j, jj;\n  switch (type) {\n    case 'Point':\n    case 'MultiPoint':\n    case 'LineString':\n    case 'MultiLineString':\n    case 'LinearRing': {\n      break;\n    }\n    case 'Polygon': {\n      coordinates = /** @type {import(\"./geom/Polygon.js\").default} */ (\n        geometry\n      ).getCoordinates();\n      area = Math.abs(getAreaInternal(coordinates[0], radius));\n      for (i = 1, ii = coordinates.length; i < ii; ++i) {\n        area -= Math.abs(getAreaInternal(coordinates[i], radius));\n      }\n      break;\n    }\n    case 'MultiPolygon': {\n      coordinates = /** @type {import(\"./geom/SimpleGeometry.js\").default} */ (\n        geometry\n      ).getCoordinates();\n      for (i = 0, ii = coordinates.length; i < ii; ++i) {\n        coords = coordinates[i];\n        area += Math.abs(getAreaInternal(coords[0], radius));\n        for (j = 1, jj = coords.length; j < jj; ++j) {\n          area -= Math.abs(getAreaInternal(coords[j], radius));\n        }\n      }\n      break;\n    }\n    case 'GeometryCollection': {\n      const geometries =\n        /** @type {import(\"./geom/GeometryCollection.js\").default} */ (\n          geometry\n        ).getGeometries();\n      for (i = 0, ii = geometries.length; i < ii; ++i) {\n        area += getArea(geometries[i], options);\n      }\n      break;\n    }\n    default: {\n      throw new Error('Unsupported geometry type: ' + type);\n    }\n  }\n  return area;\n}\n\n/**\n * Returns the coordinate at the given distance and bearing from `c1`.\n *\n * @param {import(\"./coordinate.js\").Coordinate} c1 The origin point (`[lon, lat]` in degrees).\n * @param {number} distance The great-circle distance between the origin\n *     point and the target point.\n * @param {number} bearing The bearing (in radians).\n * @param {number} [radius] The sphere radius to use.  Defaults to the Earth's\n *     mean radius using the WGS84 ellipsoid.\n * @return {import(\"./coordinate.js\").Coordinate} The target point.\n */\nexport function offset(c1, distance, bearing, radius) {\n  radius = radius || DEFAULT_RADIUS;\n  const lat1 = toRadians(c1[1]);\n  const lon1 = toRadians(c1[0]);\n  const dByR = distance / radius;\n  const lat = Math.asin(\n    Math.sin(lat1) * Math.cos(dByR) +\n      Math.cos(lat1) * Math.sin(dByR) * Math.cos(bearing),\n  );\n  const lon =\n    lon1 +\n    Math.atan2(\n      Math.sin(bearing) * Math.sin(dByR) * Math.cos(lat1),\n      Math.cos(dByR) - Math.sin(lat1) * Math.sin(lat),\n    );\n  return [toDegrees(lon), toDegrees(lat)];\n}\n", "/**\n * @module ol/console\n */\n\n/**\n * @typedef {'info'|'warn'|'error'|'none'} Level\n */\n\n/**\n * @type {Object<Level, number>}\n */\nconst levels = {\n  info: 1,\n  warn: 2,\n  error: 3,\n  none: 4,\n};\n\n/**\n * @type {number}\n */\nlet level = levels.info;\n\n/**\n * Set the logging level.  By default, the level is set to 'info' and all\n * messages will be logged.  Set to 'warn' to only display warnings and errors.\n * Set to 'error' to only display errors.  Set to 'none' to silence all messages.\n *\n * @param {Level} l The new level.\n */\nexport function setLevel(l) {\n  level = levels[l];\n}\n\n/**\n * @param  {...any} args Arguments to log\n */\nexport function log(...args) {\n  if (level > levels.info) {\n    return;\n  }\n  console.log(...args); // eslint-disable-line no-console\n}\n\n/**\n * @param  {...any} args Arguments to log\n */\nexport function warn(...args) {\n  if (level > levels.warn) {\n    return;\n  }\n  console.warn(...args); // eslint-disable-line no-console\n}\n\n/**\n * @param  {...any} args Arguments to log\n */\nexport function error(...args) {\n  if (level > levels.error) {\n    return;\n  }\n  console.error(...args); // eslint-disable-line no-console\n}\n", "/**\n * @module ol/proj/Units\n */\n\n/**\n * @typedef {'radians' | 'degrees' | 'ft' | 'm' | 'pixels' | 'tile-pixels' | 'us-ft'} Units\n * Projection units.\n */\n\n/**\n * See http://duff.ess.washington.edu/data/raster/drg/docs/geotiff.txt\n * @type {Object<number, Units>}\n */\nconst unitByCode = {\n  '9001': 'm',\n  '9002': 'ft',\n  '9003': 'us-ft',\n  '9101': 'radians',\n  '9102': 'degrees',\n};\n\n/**\n * @param {number} code Unit code.\n * @return {Units} Units.\n */\nexport function fromCode(code) {\n  return unitByCode[code];\n}\n\n/**\n * @typedef {Object} MetersPerUnitLookup\n * @property {number} radians Radians\n * @property {number} degrees Degrees\n * @property {number} ft  Feet\n * @property {number} m Meters\n * @property {number} us-ft US feet\n */\n\n/**\n * Meters per unit lookup table.\n * @const\n * @type {MetersPerUnitLookup}\n * @api\n */\nexport const METERS_PER_UNIT = {\n  // use the radius of the Normal sphere\n  'radians': 6370997 / (2 * Math.PI),\n  'degrees': (2 * Math.PI * 6370997) / 360,\n  'ft': 0.3048,\n  'm': 1,\n  'us-ft': 1200 / 3937,\n};\n", "/**\n * @module ol/proj/Projection\n */\nimport {METERS_PER_UNIT} from './Units.js';\n\n/**\n * The function is called with a `number` view resolution and a\n * {@link module:ol/coordinate~Coordinate} as arguments, and returns the `number` resolution\n * in projection units at the passed coordinate.\n * @typedef {function(number, import(\"../coordinate.js\").Coordinate):number} GetPointResolution\n * @api\n */\n\n/**\n * @typedef {Object} Options\n * @property {string} code The SRS identifier code, e.g. `EPSG:4326`.\n * @property {import(\"./Units.js\").Units} [units] Units. Required unless a\n * proj4 projection is defined for `code`.\n * @property {import(\"../extent.js\").Extent} [extent] The validity extent for the SRS.\n * @property {string} [axisOrientation='enu'] The axis orientation as specified in Proj4.\n * @property {boolean} [global=false] Whether the projection is valid for the whole globe.\n * @property {number} [metersPerUnit] The meters per unit for the SRS.\n * If not provided, the `units` are used to get the meters per unit from the {@link METERS_PER_UNIT}\n * lookup table.\n * @property {import(\"../extent.js\").Extent} [worldExtent] The world extent for the SRS.\n * @property {GetPointResolution} [getPointResolution]\n * Function to determine resolution at a point. The function is called with a\n * `number` view resolution and a {@link module:ol/coordinate~Coordinate} as arguments, and returns\n * the `number` resolution in projection units at the passed coordinate. If this is `undefined`,\n * the default {@link module:ol/proj.getPointResolution} function will be used.\n */\n\n/**\n * @classdesc\n * In most cases, you should not need to create instances of this class.\n * Instead, where projection information is required, you can use a string\n * projection code or identifier (e.g. `EPSG:4326`) instead of a projection\n * instance.\n *\n * The library includes support for transforming coordinates between the following\n * projections:\n *\n *  WGS 84 / Geographic - Using codes `EPSG:4326`, `CRS:84`, `urn:ogc:def:crs:EPSG:6.6:4326`,\n *    `urn:ogc:def:crs:OGC:1.3:CRS84`, `urn:ogc:def:crs:OGC:2:84`, `http://www.opengis.net/gml/srs/epsg.xml#4326`,\n *    or `urn:x-ogc:def:crs:EPSG:4326`\n *  WGS 84 / Spherical Mercator - Using codes `EPSG:3857`, `EPSG:102100`, `EPSG:102113`, `EPSG:900913`,\n *    `urn:ogc:def:crs:EPSG:6.18:3:3857`, or `http://www.opengis.net/gml/srs/epsg.xml#3857`\n *  WGS 84 / UTM zones - Using codes `EPSG:32601` through `EPSG:32660` for northern zones\n *    and `EPSG:32701` through `EPSG:32760` for southern zones. Note that the built-in UTM transforms\n *    are lower accuracy (with errors on the order of 0.1 m) than those that you might get in a\n *    library like [proj4js](https://github.com/proj4js/proj4js).\n *\n * For additional projection support, or to use higher accuracy transforms than the built-in ones, you can use\n * the [proj4js](https://github.com/proj4js/proj4js) library. With `proj4js`, after adding any new projection\n * definitions, call the {@link module:ol/proj/proj4.register} function.\n *\n * You can use the {@link module:ol/proj.get} function to retrieve a projection instance\n * for one of the registered projections.\n *\n * @api\n */\nclass Projection {\n  /**\n   * @param {Options} options Projection options.\n   */\n  constructor(options) {\n    /**\n     * @private\n     * @type {string}\n     */\n    this.code_ = options.code;\n\n    /**\n     * Units of projected coordinates. When set to `TILE_PIXELS`, a\n     * `this.extent_` and `this.worldExtent_` must be configured properly for each\n     * tile.\n     * @private\n     * @type {import(\"./Units.js\").Units}\n     */\n    this.units_ = /** @type {import(\"./Units.js\").Units} */ (options.units);\n\n    /**\n     * Validity extent of the projection in projected coordinates. For projections\n     * with `TILE_PIXELS` units, this is the extent of the tile in\n     * tile pixel space.\n     * @private\n     * @type {import(\"../extent.js\").Extent}\n     */\n    this.extent_ = options.extent !== undefined ? options.extent : null;\n\n    /**\n     * Extent of the world in EPSG:4326. For projections with\n     * `TILE_PIXELS` units, this is the extent of the tile in\n     * projected coordinate space.\n     * @private\n     * @type {import(\"../extent.js\").Extent}\n     */\n    this.worldExtent_ =\n      options.worldExtent !== undefined ? options.worldExtent : null;\n\n    /**\n     * @private\n     * @type {string}\n     */\n    this.axisOrientation_ =\n      options.axisOrientation !== undefined ? options.axisOrientation : 'enu';\n\n    /**\n     * @private\n     * @type {boolean}\n     */\n    this.global_ = options.global !== undefined ? options.global : false;\n\n    /**\n     * @private\n     * @type {boolean}\n     */\n    this.canWrapX_ = !!(this.global_ && this.extent_);\n\n    /**\n     * @private\n     * @type {GetPointResolution|undefined}\n     */\n    this.getPointResolutionFunc_ = options.getPointResolution;\n\n    /**\n     * @private\n     * @type {import(\"../tilegrid/TileGrid.js\").default}\n     */\n    this.defaultTileGrid_ = null;\n\n    /**\n     * @private\n     * @type {number|undefined}\n     */\n    this.metersPerUnit_ = options.metersPerUnit;\n  }\n\n  /**\n   * @return {boolean} The projection is suitable for wrapping the x-axis\n   */\n  canWrapX() {\n    return this.canWrapX_;\n  }\n\n  /**\n   * Get the code for this projection, e.g. 'EPSG:4326'.\n   * @return {string} Code.\n   * @api\n   */\n  getCode() {\n    return this.code_;\n  }\n\n  /**\n   * Get the validity extent for this projection.\n   * @return {import(\"../extent.js\").Extent} Extent.\n   * @api\n   */\n  getExtent() {\n    return this.extent_;\n  }\n\n  /**\n   * Get the units of this projection.\n   * @return {import(\"./Units.js\").Units} Units.\n   * @api\n   */\n  getUnits() {\n    return this.units_;\n  }\n\n  /**\n   * Get the amount of meters per unit of this projection.  If the projection is\n   * not configured with `metersPerUnit` or a units identifier, the return is\n   * `undefined`.\n   * @return {number|undefined} Meters.\n   * @api\n   */\n  getMetersPerUnit() {\n    return this.metersPerUnit_ || METERS_PER_UNIT[this.units_];\n  }\n\n  /**\n   * Get the world extent for this projection.\n   * @return {import(\"../extent.js\").Extent} Extent.\n   * @api\n   */\n  getWorldExtent() {\n    return this.worldExtent_;\n  }\n\n  /**\n   * Get the axis orientation of this projection.\n   * Example values are:\n   * enu - the default easting, northing, elevation.\n   * neu - northing, easting, up - useful for \"lat/long\" geographic coordinates,\n   *     or south orientated transverse mercator.\n   * wnu - westing, northing, up - some planetary coordinate systems have\n   *     \"west positive\" coordinate systems\n   * @return {string} Axis orientation.\n   * @api\n   */\n  getAxisOrientation() {\n    return this.axisOrientation_;\n  }\n\n  /**\n   * Is this projection a global projection which spans the whole world?\n   * @return {boolean} Whether the projection is global.\n   * @api\n   */\n  isGlobal() {\n    return this.global_;\n  }\n\n  /**\n   * Set if the projection is a global projection which spans the whole world\n   * @param {boolean} global Whether the projection is global.\n   * @api\n   */\n  setGlobal(global) {\n    this.global_ = global;\n    this.canWrapX_ = !!(global && this.extent_);\n  }\n\n  /**\n   * @return {import(\"../tilegrid/TileGrid.js\").default} The default tile grid.\n   */\n  getDefaultTileGrid() {\n    return this.defaultTileGrid_;\n  }\n\n  /**\n   * @param {import(\"../tilegrid/TileGrid.js\").default} tileGrid The default tile grid.\n   */\n  setDefaultTileGrid(tileGrid) {\n    this.defaultTileGrid_ = tileGrid;\n  }\n\n  /**\n   * Set the validity extent for this projection.\n   * @param {import(\"../extent.js\").Extent} extent Extent.\n   * @api\n   */\n  setExtent(extent) {\n    this.extent_ = extent;\n    this.canWrapX_ = !!(this.global_ && extent);\n  }\n\n  /**\n   * Set the world extent for this projection.\n   * @param {import(\"../extent.js\").Extent} worldExtent World extent\n   *     [minlon, minlat, maxlon, maxlat].\n   * @api\n   */\n  setWorldExtent(worldExtent) {\n    this.worldExtent_ = worldExtent;\n  }\n\n  /**\n   * Set the getPointResolution function (see {@link module:ol/proj.getPointResolution}\n   * for this projection.\n   * @param {function(number, import(\"../coordinate.js\").Coordinate):number} func Function\n   * @api\n   */\n  setGetPointResolution(func) {\n    this.getPointResolutionFunc_ = func;\n  }\n\n  /**\n   * Get the custom point resolution function for this projection (if set).\n   * @return {GetPointResolution|undefined} The custom point\n   * resolution function (if set).\n   */\n  getPointResolutionFunc() {\n    return this.getPointResolutionFunc_;\n  }\n}\n\nexport default Projection;\n", "/**\n * @module ol/proj/epsg3857\n */\nimport Projection from './Projection.js';\n\n/**\n * Radius of WGS84 sphere\n *\n * @const\n * @type {number}\n */\nexport const RADIUS = 6378137;\n\n/**\n * @const\n * @type {number}\n */\nexport const HALF_SIZE = Math.PI * RADIUS;\n\n/**\n * @const\n * @type {import(\"../extent.js\").Extent}\n */\nexport const EXTENT = [-HALF_SIZE, -HALF_SIZE, HALF_SIZE, HALF_SIZE];\n\n/**\n * @const\n * @type {import(\"../extent.js\").Extent}\n */\nexport const WORLD_EXTENT = [-180, -85, 180, 85];\n\n/**\n * Maximum safe value in y direction\n * @const\n * @type {number}\n */\nexport const MAX_SAFE_Y = RADIUS * Math.log(Math.tan(Math.PI / 2));\n\n/**\n * @classdesc\n * Projection object for web/spherical Mercator (EPSG:3857).\n */\nclass EPSG3857Projection extends Projection {\n  /**\n   * @param {string} code Code.\n   */\n  constructor(code) {\n    super({\n      code: code,\n      units: 'm',\n      extent: EXTENT,\n      global: true,\n      worldExtent: WORLD_EXTENT,\n      getPointResolution: function (resolution, point) {\n        return resolution / Math.cosh(point[1] / RADIUS);\n      },\n    });\n  }\n}\n\n/**\n * Projections equal to EPSG:3857.\n *\n * @const\n * @type {Array<import(\"./Projection.js\").default>}\n */\nexport const PROJECTIONS = [\n  new EPSG3857Projection('EPSG:3857'),\n  new EPSG3857Projection('EPSG:102100'),\n  new EPSG3857Projection('EPSG:102113'),\n  new EPSG3857Projection('EPSG:900913'),\n  new EPSG3857Projection('http://www.opengis.net/def/crs/EPSG/0/3857'),\n  new EPSG3857Projection('http://www.opengis.net/gml/srs/epsg.xml#3857'),\n];\n\n/**\n * Transformation from EPSG:4326 to EPSG:3857.\n *\n * @param {Array<number>} input Input array of coordinate values.\n * @param {Array<number>} [output] Output array of coordinate values.\n * @param {number} [dimension] Dimension (default is `2`).\n * @param {number} [stride] Stride (default is `dimension`).\n * @return {Array<number>} Output array of coordinate values.\n */\nexport function fromEPSG4326(input, output, dimension, stride) {\n  const length = input.length;\n  dimension = dimension > 1 ? dimension : 2;\n  stride = stride ?? dimension;\n  if (output === undefined) {\n    if (dimension > 2) {\n      // preserve values beyond second dimension\n      output = input.slice();\n    } else {\n      output = new Array(length);\n    }\n  }\n  for (let i = 0; i < length; i += stride) {\n    output[i] = (HALF_SIZE * input[i]) / 180;\n    let y = RADIUS * Math.log(Math.tan((Math.PI * (+input[i + 1] + 90)) / 360));\n    if (y > MAX_SAFE_Y) {\n      y = MAX_SAFE_Y;\n    } else if (y < -MAX_SAFE_Y) {\n      y = -MAX_SAFE_Y;\n    }\n    output[i + 1] = y;\n  }\n  return output;\n}\n\n/**\n * Transformation from EPSG:3857 to EPSG:4326.\n *\n * @param {Array<number>} input Input array of coordinate values.\n * @param {Array<number>} [output] Output array of coordinate values.\n * @param {number} [dimension] Dimension (default is `2`).\n * @param {number} [stride] Stride (default is `dimension`).\n * @return {Array<number>} Output array of coordinate values.\n */\nexport function toEPSG4326(input, output, dimension, stride) {\n  const length = input.length;\n  dimension = dimension > 1 ? dimension : 2;\n  stride = stride ?? dimension;\n  if (output === undefined) {\n    if (dimension > 2) {\n      // preserve values beyond second dimension\n      output = input.slice();\n    } else {\n      output = new Array(length);\n    }\n  }\n  for (let i = 0; i < length; i += stride) {\n    output[i] = (180 * input[i]) / HALF_SIZE;\n    output[i + 1] =\n      (360 * Math.atan(Math.exp(input[i + 1] / RADIUS))) / Math.PI - 90;\n  }\n  return output;\n}\n", "/**\n * @module ol/proj/epsg4326\n */\nimport Projection from './Projection.js';\n\n/**\n * Semi-major radius of the WGS84 ellipsoid.\n *\n * @const\n * @type {number}\n */\nexport const RADIUS = 6378137;\n\n/**\n * Extent of the EPSG:4326 projection which is the whole world.\n *\n * @const\n * @type {import(\"../extent.js\").Extent}\n */\nexport const EXTENT = [-180, -90, 180, 90];\n\n/**\n * @const\n * @type {number}\n */\nexport const METERS_PER_UNIT = (Math.PI * RADIUS) / 180;\n\n/**\n * @classdesc\n * Projection object for WGS84 geographic coordinates (EPSG:4326).\n *\n * Note that OpenLayers does not strictly comply with the EPSG definition.\n * The EPSG registry defines 4326 as a CRS for Latitude,Longitude (y,x).\n * OpenLayers treats EPSG:4326 as a pseudo-projection, with x,y coordinates.\n */\nclass EPSG4326Projection extends Projection {\n  /**\n   * @param {string} code Code.\n   * @param {string} [axisOrientation] Axis orientation.\n   */\n  constructor(code, axisOrientation) {\n    super({\n      code: code,\n      units: 'degrees',\n      extent: EXTENT,\n      axisOrientation: axisOrientation,\n      global: true,\n      metersPerUnit: METERS_PER_UNIT,\n      worldExtent: EXTENT,\n    });\n  }\n}\n\n/**\n * Projections equal to EPSG:4326.\n *\n * @const\n * @type {Array<import(\"./Projection.js\").default>}\n */\nexport const PROJECTIONS = [\n  new EPSG4326Projection('CRS:84'),\n  new EPSG4326Projection('EPSG:4326', 'neu'),\n  new EPSG4326Projection('urn:ogc:def:crs:OGC:1.3:CRS84'),\n  new EPSG4326Projection('urn:ogc:def:crs:OGC:2:84'),\n  new EPSG4326Projection('http://www.opengis.net/def/crs/OGC/1.3/CRS84'),\n  new EPSG4326Projection('http://www.opengis.net/gml/srs/epsg.xml#4326', 'neu'),\n  new EPSG4326Projection('http://www.opengis.net/def/crs/EPSG/0/4326', 'neu'),\n];\n", "/**\n * @module ol/proj/projections\n */\n\n/**\n * @type {Object<string, import(\"./Projection.js\").default>}\n */\nlet cache = {};\n\n/**\n * Clear the projections cache.\n */\nexport function clear() {\n  cache = {};\n}\n\n/**\n * Get a cached projection by code.\n * @param {string} code The code for the projection.\n * @return {import(\"./Projection.js\").default|null} The projection (if cached).\n */\nexport function get(code) {\n  return (\n    cache[code] ||\n    cache[code.replace(/urn:(x-)?ogc:def:crs:EPSG:(.*:)?(\\w+)$/, 'EPSG:$3')] ||\n    null\n  );\n}\n\n/**\n * Add a projection to the cache.\n * @param {string} code The projection code.\n * @param {import(\"./Projection.js\").default} projection The projection to cache.\n */\nexport function add(code, projection) {\n  cache[code] = projection;\n}\n", "/**\n * @module ol/proj/transforms\n */\nimport {isEmpty} from '../obj.js';\n\n/**\n * @private\n * @type {!Object<string, Object<string, import(\"../proj.js\").TransformFunction>>}\n */\nlet transforms = {};\n\n/**\n * Clear the transform cache.\n */\nexport function clear() {\n  transforms = {};\n}\n\n/**\n * Registers a conversion function to convert coordinates from the source\n * projection to the destination projection.\n *\n * @param {import(\"./Projection.js\").default} source Source.\n * @param {import(\"./Projection.js\").default} destination Destination.\n * @param {import(\"../proj.js\").TransformFunction} transformFn Transform.\n */\nexport function add(source, destination, transformFn) {\n  const sourceCode = source.getCode();\n  const destinationCode = destination.getCode();\n  if (!(sourceCode in transforms)) {\n    transforms[sourceCode] = {};\n  }\n  transforms[sourceCode][destinationCode] = transformFn;\n}\n\n/**\n * Unregisters the conversion function to convert coordinates from the source\n * projection to the destination projection.  This method is used to clean up\n * cached transforms during testing.\n *\n * @param {import(\"./Projection.js\").default} source Source projection.\n * @param {import(\"./Projection.js\").default} destination Destination projection.\n * @return {import(\"../proj.js\").TransformFunction} transformFn The unregistered transform.\n */\nexport function remove(source, destination) {\n  const sourceCode = source.getCode();\n  const destinationCode = destination.getCode();\n  const transform = transforms[sourceCode][destinationCode];\n  delete transforms[sourceCode][destinationCode];\n  if (isEmpty(transforms[sourceCode])) {\n    delete transforms[sourceCode];\n  }\n  return transform;\n}\n\n/**\n * Get a transform given a source code and a destination code.\n * @param {string} sourceCode The code for the source projection.\n * @param {string} destinationCode The code for the destination projection.\n * @return {import(\"../proj.js\").TransformFunction|null} The transform function (if found).\n */\nexport function get(sourceCode, destinationCode) {\n  if (sourceCode in transforms && destinationCode in transforms[sourceCode]) {\n    return transforms[sourceCode][destinationCode];\n  }\n  return null;\n}\n", "/**\n * @module ol/proj/utm\n */\n\n/**\n * Adapted from https://github.com/Turbo87/utm\n * Copyright (c) 2012-2017 Tobias Bieniek\n *\n * The functions here provide approximate transforms to and from UTM.\n * They are not appropriate for use beyond the validity extend of a UTM\n * zone, and the accuracy of the transform decreases toward the zone\n * edges.\n */\n\nimport {toDegrees, toRadians, wrap} from '../math.js';\nimport Projection from './Projection.js';\n\n/**\n * @typedef {Object} UTMZone\n * @property {number} number The zone number (1 - 60).\n * @property {boolean} north The northern hemisphere.\n */\n\nconst K0 = 0.9996;\n\nconst E = 0.00669438;\nconst E2 = E * E;\nconst E3 = E2 * E;\nconst E_P2 = E / (1 - E);\n\nconst SQRT_E = Math.sqrt(1 - E);\nconst _E = (1 - SQRT_E) / (1 + SQRT_E);\nconst _E2 = _E * _E;\nconst _E3 = _E2 * _E;\nconst _E4 = _E3 * _E;\nconst _E5 = _E4 * _E;\n\nconst M1 = 1 - E / 4 - (3 * E2) / 64 - (5 * E3) / 256;\nconst M2 = (3 * E) / 8 + (3 * E2) / 32 + (45 * E3) / 1024;\nconst M3 = (15 * E2) / 256 + (45 * E3) / 1024;\nconst M4 = (35 * E3) / 3072;\n\nconst P2 = (3 / 2) * _E - (27 / 32) * _E3 + (269 / 512) * _E5;\nconst P3 = (21 / 16) * _E2 - (55 / 32) * _E4;\nconst P4 = (151 / 96) * _E3 - (417 / 128) * _E5;\nconst P5 = (1097 / 512) * _E4;\n\nconst R = 6378137;\n\n/**\n * @param {number} easting Easting value of coordinate.\n * @param {number} northing Northing value of coordinate.\n * @param {UTMZone} zone The UTM zone.\n * @return {import(\"../coordinate.js\").Coordinate} The transformed coordinate.\n */\nfunction toLonLat(easting, northing, zone) {\n  const x = easting - 500000;\n  const y = zone.north ? northing : northing - 10000000;\n\n  const m = y / K0;\n  const mu = m / (R * M1);\n\n  const pRad =\n    mu +\n    P2 * Math.sin(2 * mu) +\n    P3 * Math.sin(4 * mu) +\n    P4 * Math.sin(6 * mu) +\n    P5 * Math.sin(8 * mu);\n\n  const pSin = Math.sin(pRad);\n  const pSin2 = pSin * pSin;\n\n  const pCos = Math.cos(pRad);\n\n  const pTan = pSin / pCos;\n  const pTan2 = pTan * pTan;\n  const pTan4 = pTan2 * pTan2;\n\n  const epSin = 1 - E * pSin2;\n  const epSinSqrt = Math.sqrt(1 - E * pSin2);\n\n  const n = R / epSinSqrt;\n  const r = (1 - E) / epSin;\n\n  const c = E_P2 * pCos ** 2;\n  const c2 = c * c;\n\n  const d = x / (n * K0);\n  const d2 = d * d;\n  const d3 = d2 * d;\n  const d4 = d3 * d;\n  const d5 = d4 * d;\n  const d6 = d5 * d;\n\n  const latitude =\n    pRad -\n    (pTan / r) *\n      (d2 / 2 - (d4 / 24) * (5 + 3 * pTan2 + 10 * c - 4 * c2 - 9 * E_P2)) +\n    (d6 / 720) * (61 + 90 * pTan2 + 298 * c + 45 * pTan4 - 252 * E_P2 - 3 * c2);\n\n  let longitude =\n    (d -\n      (d3 / 6) * (1 + 2 * pTan2 + c) +\n      (d5 / 120) * (5 - 2 * c + 28 * pTan2 - 3 * c2 + 8 * E_P2 + 24 * pTan4)) /\n    pCos;\n\n  longitude = wrap(\n    longitude + toRadians(zoneToCentralLongitude(zone.number)),\n    -Math.PI,\n    Math.PI,\n  );\n\n  return [toDegrees(longitude), toDegrees(latitude)];\n}\n\nconst MIN_LATITUDE = -80;\nconst MAX_LATITUDE = 84;\nconst MIN_LONGITUDE = -180;\nconst MAX_LONGITUDE = 180;\n\n/**\n * @param {number} longitude The longitude.\n * @param {number} latitude The latitude.\n * @param {UTMZone} zone The UTM zone.\n * @return {import('../coordinate.js').Coordinate} The UTM coordinate.\n */\nfunction fromLonLat(longitude, latitude, zone) {\n  longitude = wrap(longitude, MIN_LONGITUDE, MAX_LONGITUDE);\n\n  if (latitude < MIN_LATITUDE) {\n    latitude = MIN_LATITUDE;\n  } else if (latitude > MAX_LATITUDE) {\n    latitude = MAX_LATITUDE;\n  }\n\n  const latRad = toRadians(latitude);\n  const latSin = Math.sin(latRad);\n  const latCos = Math.cos(latRad);\n\n  const latTan = latSin / latCos;\n  const latTan2 = latTan * latTan;\n  const latTan4 = latTan2 * latTan2;\n\n  const lonRad = toRadians(longitude);\n  const centralLon = zoneToCentralLongitude(zone.number);\n  const centralLonRad = toRadians(centralLon);\n\n  const n = R / Math.sqrt(1 - E * latSin ** 2);\n  const c = E_P2 * latCos ** 2;\n\n  const a = latCos * wrap(lonRad - centralLonRad, -Math.PI, Math.PI);\n  const a2 = a * a;\n  const a3 = a2 * a;\n  const a4 = a3 * a;\n  const a5 = a4 * a;\n  const a6 = a5 * a;\n\n  const m =\n    R *\n    (M1 * latRad -\n      M2 * Math.sin(2 * latRad) +\n      M3 * Math.sin(4 * latRad) -\n      M4 * Math.sin(6 * latRad));\n\n  const easting =\n    K0 *\n      n *\n      (a +\n        (a3 / 6) * (1 - latTan2 + c) +\n        (a5 / 120) * (5 - 18 * latTan2 + latTan4 + 72 * c - 58 * E_P2)) +\n    500000;\n\n  let northing =\n    K0 *\n    (m +\n      n *\n        latTan *\n        (a2 / 2 +\n          (a4 / 24) * (5 - latTan2 + 9 * c + 4 * c ** 2) +\n          (a6 / 720) * (61 - 58 * latTan2 + latTan4 + 600 * c - 330 * E_P2)));\n\n  if (!zone.north) {\n    northing += 10000000;\n  }\n\n  return [easting, northing];\n}\n\n/**\n * @param {number} zone The zone number.\n * @return {number} The central longitude in degrees.\n */\nfunction zoneToCentralLongitude(zone) {\n  return (zone - 1) * 6 - 180 + 3;\n}\n\n/**\n * @type {Array<RegExp>}\n */\nconst epsgRegExes = [\n  /^EPSG:(\\d+)$/,\n  /^urn:ogc:def:crs:EPSG::(\\d+)$/,\n  /^http:\\/\\/www\\.opengis\\.net\\/def\\/crs\\/EPSG\\/0\\/(\\d+)$/,\n];\n\n/**\n * @param {string} code The projection code.\n * @return {UTMZone|null} The UTM zone info (or null if not UTM).\n */\nexport function zoneFromCode(code) {\n  let epsgId = 0;\n  for (const re of epsgRegExes) {\n    const match = code.match(re);\n    if (match) {\n      epsgId = parseInt(match[1]);\n      break;\n    }\n  }\n  if (!epsgId) {\n    return null;\n  }\n\n  let number = 0;\n  let north = false;\n  if (epsgId > 32700 && epsgId < 32761) {\n    number = epsgId - 32700;\n  } else if (epsgId > 32600 && epsgId < 32661) {\n    north = true;\n    number = epsgId - 32600;\n  }\n  if (!number) {\n    return null;\n  }\n\n  return {number, north};\n}\n\n/**\n * @param {function(number, number, UTMZone): import('../coordinate.js').Coordinate} transformer The transformer.\n * @param {UTMZone} zone The UTM zone.\n * @return {import('../proj.js').TransformFunction} The transform function.\n */\nfunction makeTransformFunction(transformer, zone) {\n  return function (input, output, dimension, stride) {\n    const length = input.length;\n    dimension = dimension > 1 ? dimension : 2;\n    stride = stride ?? dimension;\n    if (!output) {\n      if (dimension > 2) {\n        output = input.slice();\n      } else {\n        output = new Array(length);\n      }\n    }\n    for (let i = 0; i < length; i += stride) {\n      const x = input[i];\n      const y = input[i + 1];\n      const coord = transformer(x, y, zone);\n      output[i] = coord[0];\n      output[i + 1] = coord[1];\n    }\n    return output;\n  };\n}\n\n/**\n * @param {string} code The projection code.\n * @return {import('./Projection.js').default|null} A projection or null if unable to create one.\n */\nexport function makeProjection(code) {\n  const zone = zoneFromCode(code);\n  if (!zone) {\n    return null;\n  }\n  return new Projection({code, units: 'm'});\n}\n\n/**\n * @param {import('./Projection.js').default} projection The projection.\n * @return {import('../proj.js').Transforms|null} The transforms lookup or null if unable to handle projection.\n */\nexport function makeTransforms(projection) {\n  const zone = zoneFromCode(projection.getCode());\n  if (!zone) {\n    return null;\n  }\n\n  return {\n    forward: makeTransformFunction(fromLonLat, zone),\n    inverse: makeTransformFunction(toLonLat, zone),\n  };\n}\n", "/**\n * @module ol/proj\n */\n\n/**\n * The ol/proj module stores:\n * a list of {@link module:ol/proj/Projection~Projection}\n * objects, one for each projection supported by the application\n * a list of transform functions needed to convert coordinates in one projection\n * into another.\n *\n * The static functions are the methods used to maintain these.\n * Each transform function can handle not only simple coordinate pairs, but also\n * large arrays of coordinates such as vector geometries.\n *\n * When loaded, the library adds projection objects for EPSG:4326 (WGS84\n * geographic coordinates) and EPSG:3857 (Web or Spherical Mercator, as used\n * for example by Bing Maps or OpenStreetMap), together with the relevant\n * transform functions.\n *\n * Additional transforms may be added by using the http://proj4js.org/\n * library (version 2.2 or later). You can use the full build supplied by\n * Proj4js, or create a custom build to support those projections you need; see\n * the Proj4js website for how to do this. You also need the Proj4js definitions\n * for the required projections. These definitions can be obtained from\n * https://spatialreference.org/, and are a JS function, so can be loaded in a\n * script tag (as in the examples) or pasted into your application.\n *\n * After all required projection definitions are added to proj4's registry (by\n * using `proj4.defs()`), simply call `register(proj4)` from the `ol/proj/proj4`\n * package. Existing transforms are not changed by this function. See\n * examples/wms-image-custom-proj for an example of this.\n *\n * Additional projection definitions can be registered with `proj4.defs()` any\n * time. Just make sure to call `register(proj4)` again; for example, with user-supplied data where you don't\n * know in advance what projections are needed, you can initially load minimal\n * support and then load whichever are requested.\n *\n * Note that Proj4js does not support projection extents. If you want to add\n * one for creating default tile grids, you can add it after the Projection\n * object has been created with `setExtent`, for example,\n * `get('EPSG:1234').setExtent(extent)`.\n *\n * In addition to Proj4js support, any transform functions can be added with\n * {@link module:ol/proj.addCoordinateTransforms}. To use this, you must first create\n * a {@link module:ol/proj/Projection~Projection} object for the new projection and add it with\n * {@link module:ol/proj.addProjection}. You can then add the forward and inverse\n * functions with {@link module:ol/proj.addCoordinateTransforms}. See\n * examples/wms-custom-proj for an example of this.\n *\n * Note that if no transforms are needed and you only need to define the\n * projection, just add a {@link module:ol/proj/Projection~Projection} with\n * {@link module:ol/proj.addProjection}. See examples/wms-no-proj for an example of\n * this.\n */\nimport {warn} from './console.js';\nimport {equals, getWorldsAway} from './coordinate.js';\nimport {applyTransform, getWidth} from './extent.js';\nimport {clamp, modulo} from './math.js';\nimport Projection from './proj/Projection.js';\nimport {METERS_PER_UNIT} from './proj/Units.js';\nimport {\n  PROJECTIONS as EPSG3857_PROJECTIONS,\n  fromEPSG4326,\n  toEPSG4326,\n} from './proj/epsg3857.js';\nimport {PROJECTIONS as EPSG4326_PROJECTIONS} from './proj/epsg4326.js';\nimport {\n  add as addProj,\n  clear as clearProj,\n  get as getProj,\n} from './proj/projections.js';\nimport {\n  add as addTransformFunc,\n  clear as clearTransformFuncs,\n  get as getTransformFunc,\n} from './proj/transforms.js';\nimport {\n  makeProjection as makeUTMProjection,\n  makeTransforms as makeUTMTransforms,\n} from './proj/utm.js';\nimport {getDistance} from './sphere.js';\n\n/**\n * A projection as {@link module:ol/proj/Projection~Projection}, SRS identifier\n * string or undefined.\n * @typedef {Projection|string|undefined} ProjectionLike\n * @api\n */\n\n/**\n * @typedef {Object} Transforms\n * @property {TransformFunction} forward The forward transform (from geographic).\n * @property {TransformFunction} inverse The inverse transform (to geographic).\n */\n\n/**\n * @type {Array<function(Projection): Transforms|null>}\n */\nconst transformFactories = [makeUTMTransforms];\n\n/**\n * @type {Array<function(string): Projection|null>}\n */\nconst projectionFactories = [makeUTMProjection];\n\n/**\n * A transform function accepts an array of input coordinate values, an optional\n * output array, and an optional dimension (default should be 2).  The function\n * transforms the input coordinate values, populates the output array, and\n * returns the output array.\n *\n * @callback TransformFunction\n * @param {Array<number>} input\n * @param {Array<number>} [output]\n * @param {number} [dimension]\n * @param {number} [stride]\n * @return {Array<number>}\n *\n * @api\n */\n\nexport {METERS_PER_UNIT};\n\nexport {Projection};\n\nlet showCoordinateWarning = true;\n\n/**\n * @param {boolean} [disable] Disable console info about `useGeographic()`\n */\nexport function disableCoordinateWarning(disable) {\n  const hide = disable === undefined ? true : disable;\n  showCoordinateWarning = !hide;\n}\n\n/**\n * @param {Array<number>} input Input coordinate array.\n * @param {Array<number>} [output] Output array of coordinate values.\n * @return {Array<number>} Output coordinate array (new array, same coordinate\n *     values).\n */\nexport function cloneTransform(input, output) {\n  if (output !== undefined) {\n    for (let i = 0, ii = input.length; i < ii; ++i) {\n      output[i] = input[i];\n    }\n    output = output;\n  } else {\n    output = input.slice();\n  }\n  return output;\n}\n\n/**\n * @param {Array<number>} input Input coordinate array.\n * @param {Array<number>} [output] Output array of coordinate values.\n * @return {Array<number>} Input coordinate array (same array as input).\n */\nexport function identityTransform(input, output) {\n  if (output !== undefined && input !== output) {\n    for (let i = 0, ii = input.length; i < ii; ++i) {\n      output[i] = input[i];\n    }\n    input = output;\n  }\n  return input;\n}\n\n/**\n * Add a Projection object to the list of supported projections that can be\n * looked up by their code.\n *\n * @param {Projection} projection Projection instance.\n * @api\n */\nexport function addProjection(projection) {\n  addProj(projection.getCode(), projection);\n  addTransformFunc(projection, projection, cloneTransform);\n}\n\n/**\n * @param {Array<Projection>} projections Projections.\n */\nexport function addProjections(projections) {\n  projections.forEach(addProjection);\n}\n\n/**\n * Fetches a Projection object for the code specified.\n *\n * @param {ProjectionLike} projectionLike Either a code string which is\n *     a combination of authority and identifier such as \"EPSG:4326\", or an\n *     existing projection object, or undefined.\n * @return {Projection|null} Projection object, or null if not in list.\n * @api\n */\nexport function get(projectionLike) {\n  if (!(typeof projectionLike === 'string')) {\n    return projectionLike;\n  }\n  const projection = getProj(projectionLike);\n  if (projection) {\n    return projection;\n  }\n  for (const makeProjection of projectionFactories) {\n    const projection = makeProjection(projectionLike);\n    if (projection) {\n      return projection;\n    }\n  }\n  return null;\n}\n\n/**\n * Get the resolution of the point in degrees or distance units.\n * For projections with degrees as the unit this will simply return the\n * provided resolution. For other projections the point resolution is\n * by default estimated by transforming the `point` pixel to EPSG:4326,\n * measuring its width and height on the normal sphere,\n * and taking the average of the width and height.\n * A custom function can be provided for a specific projection, either\n * by setting the `getPointResolution` option in the\n * {@link module:ol/proj/Projection~Projection} constructor or by using\n * {@link module:ol/proj/Projection~Projection#setGetPointResolution} to change an existing\n * projection object.\n * @param {ProjectionLike} projection The projection.\n * @param {number} resolution Nominal resolution in projection units.\n * @param {import(\"./coordinate.js\").Coordinate} point Point to find adjusted resolution at.\n * @param {import(\"./proj/Units.js\").Units} [units] Units to get the point resolution in.\n * Default is the projection's units.\n * @return {number} Point resolution.\n * @api\n */\nexport function getPointResolution(projection, resolution, point, units) {\n  projection = get(projection);\n  let pointResolution;\n  const getter = projection.getPointResolutionFunc();\n  if (getter) {\n    pointResolution = getter(resolution, point);\n    if (units && units !== projection.getUnits()) {\n      const metersPerUnit = projection.getMetersPerUnit();\n      if (metersPerUnit) {\n        pointResolution =\n          (pointResolution * metersPerUnit) / METERS_PER_UNIT[units];\n      }\n    }\n  } else {\n    const projUnits = projection.getUnits();\n    if ((projUnits == 'degrees' && !units) || units == 'degrees') {\n      pointResolution = resolution;\n    } else {\n      // Estimate point resolution by transforming the center pixel to EPSG:4326,\n      // measuring its width and height on the normal sphere, and taking the\n      // average of the width and height.\n      const toEPSG4326 = getTransformFromProjections(\n        projection,\n        get('EPSG:4326'),\n      );\n      if (!toEPSG4326 && projUnits !== 'degrees') {\n        // no transform is available\n        pointResolution = resolution * projection.getMetersPerUnit();\n      } else {\n        let vertices = [\n          point[0] - resolution / 2,\n          point[1],\n          point[0] + resolution / 2,\n          point[1],\n          point[0],\n          point[1] - resolution / 2,\n          point[0],\n          point[1] + resolution / 2,\n        ];\n        vertices = toEPSG4326(vertices, vertices, 2);\n        const width = getDistance(vertices.slice(0, 2), vertices.slice(2, 4));\n        const height = getDistance(vertices.slice(4, 6), vertices.slice(6, 8));\n        pointResolution = (width + height) / 2;\n      }\n      const metersPerUnit = units\n        ? METERS_PER_UNIT[units]\n        : projection.getMetersPerUnit();\n      if (metersPerUnit !== undefined) {\n        pointResolution /= metersPerUnit;\n      }\n    }\n  }\n  return pointResolution;\n}\n\n/**\n * Registers transformation functions that don't alter coordinates. Those allow\n * to transform between projections with equal meaning.\n *\n * @param {Array<Projection>} projections Projections.\n * @api\n */\nexport function addEquivalentProjections(projections) {\n  addProjections(projections);\n  projections.forEach(function (source) {\n    projections.forEach(function (destination) {\n      if (source !== destination) {\n        addTransformFunc(source, destination, cloneTransform);\n      }\n    });\n  });\n}\n\n/**\n * Registers transformation functions to convert coordinates in any projection\n * in projection1 to any projection in projection2.\n *\n * @param {Array<Projection>} projections1 Projections with equal\n *     meaning.\n * @param {Array<Projection>} projections2 Projections with equal\n *     meaning.\n * @param {TransformFunction} forwardTransform Transformation from any\n *   projection in projection1 to any projection in projection2.\n * @param {TransformFunction} inverseTransform Transform from any projection\n *   in projection2 to any projection in projection1..\n */\nexport function addEquivalentTransforms(\n  projections1,\n  projections2,\n  forwardTransform,\n  inverseTransform,\n) {\n  projections1.forEach(function (projection1) {\n    projections2.forEach(function (projection2) {\n      addTransformFunc(projection1, projection2, forwardTransform);\n      addTransformFunc(projection2, projection1, inverseTransform);\n    });\n  });\n}\n\n/**\n * Clear all cached projections and transforms.\n */\nexport function clearAllProjections() {\n  clearProj();\n  clearTransformFuncs();\n}\n\n/**\n * @param {Projection|string|undefined} projection Projection.\n * @param {string} defaultCode Default code.\n * @return {Projection} Projection.\n */\nexport function createProjection(projection, defaultCode) {\n  if (!projection) {\n    return get(defaultCode);\n  }\n  if (typeof projection === 'string') {\n    return get(projection);\n  }\n  return /** @type {Projection} */ (projection);\n}\n\n/**\n * Creates a {@link module:ol/proj~TransformFunction} from a simple 2D coordinate transform\n * function.\n * @param {function(import(\"./coordinate.js\").Coordinate): import(\"./coordinate.js\").Coordinate} coordTransform Coordinate\n *     transform.\n * @return {TransformFunction} Transform function.\n */\nexport function createTransformFromCoordinateTransform(coordTransform) {\n  return (\n    /**\n     * @param {Array<number>} input Input.\n     * @param {Array<number>} [output] Output.\n     * @param {number} [dimension] Dimensions that should be transformed.\n     * @param {number} [stride] Stride.\n     * @return {Array<number>} Output.\n     */\n    function (input, output, dimension, stride) {\n      const length = input.length;\n      dimension = dimension !== undefined ? dimension : 2;\n      stride = stride ?? dimension;\n      output = output !== undefined ? output : new Array(length);\n      for (let i = 0; i < length; i += stride) {\n        const point = coordTransform(input.slice(i, i + dimension));\n        const pointLength = point.length;\n        for (let j = 0, jj = stride; j < jj; ++j) {\n          output[i + j] = j >= pointLength ? input[i + j] : point[j];\n        }\n      }\n      return output;\n    }\n  );\n}\n\n/**\n * Registers coordinate transform functions to convert coordinates between the\n * source projection and the destination projection.\n * The forward and inverse functions convert coordinate pairs; this function\n * converts these into the functions used internally which also handle\n * extents and coordinate arrays.\n *\n * @param {ProjectionLike} source Source projection.\n * @param {ProjectionLike} destination Destination projection.\n * @param {function(import(\"./coordinate.js\").Coordinate): import(\"./coordinate.js\").Coordinate} forward The forward transform\n *     function (that is, from the source projection to the destination\n *     projection) that takes a {@link module:ol/coordinate~Coordinate} as argument and returns\n *     the transformed {@link module:ol/coordinate~Coordinate}.\n * @param {function(import(\"./coordinate.js\").Coordinate): import(\"./coordinate.js\").Coordinate} inverse The inverse transform\n *     function (that is, from the destination projection to the source\n *     projection) that takes a {@link module:ol/coordinate~Coordinate} as argument and returns\n *     the transformed {@link module:ol/coordinate~Coordinate}. If the transform function can only\n *     transform less dimensions than the input coordinate, it is supposeed to return a coordinate\n *     with only the length it can transform. The other dimensions will be taken unchanged from the\n *     source.\n * @api\n */\nexport function addCoordinateTransforms(source, destination, forward, inverse) {\n  const sourceProj = get(source);\n  const destProj = get(destination);\n  addTransformFunc(\n    sourceProj,\n    destProj,\n    createTransformFromCoordinateTransform(forward),\n  );\n  addTransformFunc(\n    destProj,\n    sourceProj,\n    createTransformFromCoordinateTransform(inverse),\n  );\n}\n\n/**\n * Transforms a coordinate from longitude/latitude to a different projection.\n * @param {import(\"./coordinate.js\").Coordinate} coordinate Coordinate as longitude and latitude, i.e.\n *     an array with longitude as 1st and latitude as 2nd element.\n * @param {ProjectionLike} [projection] Target projection. The\n *     default is Web Mercator, i.e. 'EPSG:3857'.\n * @return {import(\"./coordinate.js\").Coordinate} Coordinate projected to the target projection.\n * @api\n */\nexport function fromLonLat(coordinate, projection) {\n  disableCoordinateWarning();\n  return transform(\n    coordinate,\n    'EPSG:4326',\n    projection !== undefined ? projection : 'EPSG:3857',\n  );\n}\n\n/**\n * Transforms a coordinate to longitude/latitude.\n * @param {import(\"./coordinate.js\").Coordinate} coordinate Projected coordinate.\n * @param {ProjectionLike} [projection] Projection of the coordinate.\n *     The default is Web Mercator, i.e. 'EPSG:3857'.\n * @return {import(\"./coordinate.js\").Coordinate} Coordinate as longitude and latitude, i.e. an array\n *     with longitude as 1st and latitude as 2nd element.\n * @api\n */\nexport function toLonLat(coordinate, projection) {\n  const lonLat = transform(\n    coordinate,\n    projection !== undefined ? projection : 'EPSG:3857',\n    'EPSG:4326',\n  );\n  const lon = lonLat[0];\n  if (lon < -180 || lon > 180) {\n    lonLat[0] = modulo(lon + 180, 360) - 180;\n  }\n  return lonLat;\n}\n\n/**\n * Checks if two projections are the same, that is every coordinate in one\n * projection does represent the same geographic point as the same coordinate in\n * the other projection.\n *\n * @param {Projection} projection1 Projection 1.\n * @param {Projection} projection2 Projection 2.\n * @return {boolean} Equivalent.\n * @api\n */\nexport function equivalent(projection1, projection2) {\n  if (projection1 === projection2) {\n    return true;\n  }\n  const equalUnits = projection1.getUnits() === projection2.getUnits();\n  if (projection1.getCode() === projection2.getCode()) {\n    return equalUnits;\n  }\n  const transformFunc = getTransformFromProjections(projection1, projection2);\n  return transformFunc === cloneTransform && equalUnits;\n}\n\n/**\n * Searches in the list of transform functions for the function for converting\n * coordinates from the source projection to the destination projection.\n *\n * @param {Projection} source Source Projection object.\n * @param {Projection} destination Destination Projection\n *     object.\n * @return {TransformFunction|null} Transform function.\n */\nexport function getTransformFromProjections(source, destination) {\n  const sourceCode = source.getCode();\n  const destinationCode = destination.getCode();\n  let transformFunc = getTransformFunc(sourceCode, destinationCode);\n  if (transformFunc) {\n    return transformFunc;\n  }\n\n  /**\n   * @type {Transforms|null}\n   */\n  let sourceTransforms = null;\n\n  /**\n   * @type {Transforms|null}\n   */\n  let destinationTransforms = null;\n\n  // lazily add projections if we have supported transforms\n  for (const makeTransforms of transformFactories) {\n    if (!sourceTransforms) {\n      sourceTransforms = makeTransforms(source);\n    }\n    if (!destinationTransforms) {\n      destinationTransforms = makeTransforms(destination);\n    }\n  }\n\n  if (!sourceTransforms && !destinationTransforms) {\n    return null;\n  }\n\n  const intermediateCode = 'EPSG:4326';\n  if (!destinationTransforms) {\n    const toDestination = getTransformFunc(intermediateCode, destinationCode);\n    if (toDestination) {\n      transformFunc = composeTransformFuncs(\n        sourceTransforms.inverse,\n        toDestination,\n      );\n    }\n  } else if (!sourceTransforms) {\n    const fromSource = getTransformFunc(sourceCode, intermediateCode);\n    if (fromSource) {\n      transformFunc = composeTransformFuncs(\n        fromSource,\n        destinationTransforms.forward,\n      );\n    }\n  } else {\n    transformFunc = composeTransformFuncs(\n      sourceTransforms.inverse,\n      destinationTransforms.forward,\n    );\n  }\n\n  if (transformFunc) {\n    addProjection(source);\n    addProjection(destination);\n    addTransformFunc(source, destination, transformFunc);\n  }\n\n  return transformFunc;\n}\n\n/**\n * @param {TransformFunction} t1 The first transform function.\n * @param {TransformFunction} t2 The second transform function.\n * @return {TransformFunction} The composed transform function.\n */\nfunction composeTransformFuncs(t1, t2) {\n  return function (input, output, dimensions, stride) {\n    output = t1(input, output, dimensions, stride);\n    return t2(output, output, dimensions, stride);\n  };\n}\n\n/**\n * Given the projection-like objects, searches for a transformation\n * function to convert a coordinates array from the source projection to the\n * destination projection.\n *\n * @param {ProjectionLike} source Source.\n * @param {ProjectionLike} destination Destination.\n * @return {TransformFunction} Transform function.\n * @api\n */\nexport function getTransform(source, destination) {\n  const sourceProjection = get(source);\n  const destinationProjection = get(destination);\n  return getTransformFromProjections(sourceProjection, destinationProjection);\n}\n\n/**\n * Transforms a coordinate from source projection to destination projection.\n * This returns a new coordinate (and does not modify the original). If there\n * is no available transform between the two projection, the function will throw\n * an error.\n *\n * See {@link module:ol/proj.transformExtent} for extent transformation.\n * See the transform method of {@link module:ol/geom/Geometry~Geometry} and its\n * subclasses for geometry transforms.\n *\n * @param {import(\"./coordinate.js\").Coordinate} coordinate Coordinate.\n * @param {ProjectionLike} source Source projection-like.\n * @param {ProjectionLike} destination Destination projection-like.\n * @return {import(\"./coordinate.js\").Coordinate} Coordinate.\n * @api\n */\nexport function transform(coordinate, source, destination) {\n  const transformFunc = getTransform(source, destination);\n  if (!transformFunc) {\n    const sourceCode = get(source).getCode();\n    const destinationCode = get(destination).getCode();\n    throw new Error(\n      `No transform available between ${sourceCode} and ${destinationCode}`,\n    );\n  }\n  return transformFunc(coordinate, undefined, coordinate.length);\n}\n\n/**\n * Transforms an extent from source projection to destination projection.  This\n * returns a new extent (and does not modify the original).\n *\n * @param {import(\"./extent.js\").Extent} extent The extent to transform.\n * @param {ProjectionLike} source Source projection-like.\n * @param {ProjectionLike} destination Destination projection-like.\n * @param {number} [stops] Number of stops per side used for the transform.\n * By default only the corners are used.\n * @return {import(\"./extent.js\").Extent} The transformed extent.\n * @api\n */\nexport function transformExtent(extent, source, destination, stops) {\n  const transformFunc = getTransform(source, destination);\n  return applyTransform(extent, transformFunc, undefined, stops);\n}\n\n/**\n * Transforms the given point to the destination projection.\n *\n * @param {import(\"./coordinate.js\").Coordinate} point Point.\n * @param {Projection} sourceProjection Source projection.\n * @param {Projection} destinationProjection Destination projection.\n * @return {import(\"./coordinate.js\").Coordinate} Point.\n */\nexport function transformWithProjections(\n  point,\n  sourceProjection,\n  destinationProjection,\n) {\n  const transformFunc = getTransformFromProjections(\n    sourceProjection,\n    destinationProjection,\n  );\n  return transformFunc(point);\n}\n\n/**\n * @type {Projection|null}\n */\nlet userProjection = null;\n\n/**\n * Set the projection for coordinates supplied from and returned by API methods.\n * This includes all API methods except for those interacting with tile grids,\n * plus {@link import(\"./Map.js\").FrameState} and {@link import(\"./View.js\").State}.\n * @param {ProjectionLike} projection The user projection.\n * @api\n */\nexport function setUserProjection(projection) {\n  userProjection = get(projection);\n}\n\n/**\n * Clear the user projection if set.\n * @api\n */\nexport function clearUserProjection() {\n  userProjection = null;\n}\n\n/**\n * Get the projection for coordinates supplied from and returned by API methods.\n * @return {Projection|null} The user projection (or null if not set).\n * @api\n */\nexport function getUserProjection() {\n  return userProjection;\n}\n\n/**\n * Use geographic coordinates (WGS-84 datum) in API methods.\n * This includes all API methods except for those interacting with tile grids,\n * plus {@link import(\"./Map.js\").FrameState} and {@link import(\"./View.js\").State}.\n * @api\n */\nexport function useGeographic() {\n  setUserProjection('EPSG:4326');\n}\n\n/**\n * Return a coordinate transformed into the user projection.  If no user projection\n * is set, the original coordinate is returned.\n * @param {Array<number>} coordinate Input coordinate.\n * @param {ProjectionLike} sourceProjection The input coordinate projection.\n * @return {Array<number>} The input coordinate in the user projection.\n */\nexport function toUserCoordinate(coordinate, sourceProjection) {\n  if (!userProjection) {\n    return coordinate;\n  }\n  return transform(coordinate, sourceProjection, userProjection);\n}\n\n/**\n * Return a coordinate transformed from the user projection.  If no user projection\n * is set, the original coordinate is returned.\n * @param {Array<number>} coordinate Input coordinate.\n * @param {ProjectionLike} destProjection The destination projection.\n * @return {Array<number>} The input coordinate transformed.\n */\nexport function fromUserCoordinate(coordinate, destProjection) {\n  if (!userProjection) {\n    if (\n      showCoordinateWarning &&\n      !equals(coordinate, [0, 0]) &&\n      coordinate[0] >= -180 &&\n      coordinate[0] <= 180 &&\n      coordinate[1] >= -90 &&\n      coordinate[1] <= 90\n    ) {\n      showCoordinateWarning = false;\n      warn(\n        'Call useGeographic() from ol/proj once to work with [longitude, latitude] coordinates.',\n      );\n    }\n    return coordinate;\n  }\n  return transform(coordinate, userProjection, destProjection);\n}\n\n/**\n * Return an extent transformed into the user projection.  If no user projection\n * is set, the original extent is returned.\n * @param {import(\"./extent.js\").Extent} extent Input extent.\n * @param {ProjectionLike} sourceProjection The input extent projection.\n * @return {import(\"./extent.js\").Extent} The input extent in the user projection.\n */\nexport function toUserExtent(extent, sourceProjection) {\n  if (!userProjection) {\n    return extent;\n  }\n  return transformExtent(extent, sourceProjection, userProjection);\n}\n\n/**\n * Return an extent transformed from the user projection.  If no user projection\n * is set, the original extent is returned.\n * @param {import(\"./extent.js\").Extent} extent Input extent.\n * @param {ProjectionLike} destProjection The destination projection.\n * @return {import(\"./extent.js\").Extent} The input extent transformed.\n */\nexport function fromUserExtent(extent, destProjection) {\n  if (!userProjection) {\n    return extent;\n  }\n  return transformExtent(extent, userProjection, destProjection);\n}\n\n/**\n * Return the resolution in user projection units per pixel. If no user projection\n * is set, or source or user projection are missing units, the original resolution\n * is returned.\n * @param {number} resolution Resolution in input projection units per pixel.\n * @param {ProjectionLike} sourceProjection The input projection.\n * @return {number} Resolution in user projection units per pixel.\n */\nexport function toUserResolution(resolution, sourceProjection) {\n  if (!userProjection) {\n    return resolution;\n  }\n  const sourceMetersPerUnit = get(sourceProjection).getMetersPerUnit();\n  const userMetersPerUnit = userProjection.getMetersPerUnit();\n  return sourceMetersPerUnit && userMetersPerUnit\n    ? (resolution * sourceMetersPerUnit) / userMetersPerUnit\n    : resolution;\n}\n\n/**\n * Return the resolution in user projection units per pixel. If no user projection\n * is set, or source or user projection are missing units, the original resolution\n * is returned.\n * @param {number} resolution Resolution in user projection units per pixel.\n * @param {ProjectionLike} destProjection The destination projection.\n * @return {number} Resolution in destination projection units per pixel.\n */\nexport function fromUserResolution(resolution, destProjection) {\n  if (!userProjection) {\n    return resolution;\n  }\n  const destMetersPerUnit = get(destProjection).getMetersPerUnit();\n  const userMetersPerUnit = userProjection.getMetersPerUnit();\n  return destMetersPerUnit && userMetersPerUnit\n    ? (resolution * userMetersPerUnit) / destMetersPerUnit\n    : resolution;\n}\n\n/**\n * Creates a safe coordinate transform function from a coordinate transform function.\n * \"Safe\" means that it can handle wrapping of x-coordinates for global projections,\n * and that coordinates exceeding the source projection validity extent's range will be\n * clamped to the validity range.\n * @param {Projection} sourceProj Source projection.\n * @param {Projection} destProj Destination projection.\n * @param {function(import(\"./coordinate.js\").Coordinate): import(\"./coordinate.js\").Coordinate} transform Transform function (source to destination).\n * @return {function(import(\"./coordinate.js\").Coordinate): import(\"./coordinate.js\").Coordinate} Safe transform function (source to destination).\n */\nexport function createSafeCoordinateTransform(sourceProj, destProj, transform) {\n  return function (coord) {\n    let transformed, worldsAway;\n    if (sourceProj.canWrapX()) {\n      const sourceExtent = sourceProj.getExtent();\n      const sourceExtentWidth = getWidth(sourceExtent);\n      coord = coord.slice(0);\n      worldsAway = getWorldsAway(coord, sourceProj, sourceExtentWidth);\n      if (worldsAway) {\n        // Move x to the real world\n        coord[0] = coord[0] - worldsAway * sourceExtentWidth;\n      }\n      coord[0] = clamp(coord[0], sourceExtent[0], sourceExtent[2]);\n      coord[1] = clamp(coord[1], sourceExtent[1], sourceExtent[3]);\n      transformed = transform(coord);\n    } else {\n      transformed = transform(coord);\n    }\n    if (worldsAway && destProj.canWrapX()) {\n      // Move transformed coordinate back to the offset world\n      transformed[0] += worldsAway * getWidth(destProj.getExtent());\n    }\n    return transformed;\n  };\n}\n\n/**\n * Add transforms to and from EPSG:4326 and EPSG:3857.  This function is called\n * by when this module is executed and should only need to be called again after\n * `clearAllProjections()` is called (e.g. in tests).\n */\nexport function addCommon() {\n  // Add transformations that don't alter coordinates to convert within set of\n  // projections with equal meaning.\n  addEquivalentProjections(EPSG3857_PROJECTIONS);\n  addEquivalentProjections(EPSG4326_PROJECTIONS);\n  // Add transformations to convert EPSG:4326 like coordinates to EPSG:3857 like\n  // coordinates and back.\n  addEquivalentTransforms(\n    EPSG4326_PROJECTIONS,\n    EPSG3857_PROJECTIONS,\n    fromEPSG4326,\n    toEPSG4326,\n  );\n}\n\naddCommon();\n", "/**\n * @module ol/transform\n */\nimport {assert} from './asserts.js';\n\n/**\n * An array representing an affine 2d transformation for use with\n * {@link module:ol/transform} functions. The array has 6 elements.\n * @typedef {!Array<number>} Transform\n * @api\n */\n\n/**\n * Collection of affine 2d transformation functions. The functions work on an\n * array of 6 elements. The element order is compatible with the [SVGMatrix\n * interface](https://developer.mozilla.org/en-US/docs/Web/API/SVGMatrix) and is\n * a subset (elements a to f) of a 3\u00D73 matrix:\n * ```\n * [ a c e ]\n * [ b d f ]\n * [ 0 0 1 ]\n * ```\n */\n\n/**\n * @private\n * @type {Transform}\n */\nconst tmp_ = new Array(6);\n\n/**\n * Create an identity transform.\n * @return {!Transform} Identity transform.\n */\nexport function create() {\n  return [1, 0, 0, 1, 0, 0];\n}\n\n/**\n * Resets the given transform to an identity transform.\n * @param {!Transform} transform Transform.\n * @return {!Transform} Transform.\n */\nexport function reset(transform) {\n  return set(transform, 1, 0, 0, 1, 0, 0);\n}\n\n/**\n * Multiply the underlying matrices of two transforms and return the result in\n * the first transform.\n * @param {!Transform} transform1 Transform parameters of matrix 1.\n * @param {!Transform} transform2 Transform parameters of matrix 2.\n * @return {!Transform} transform1 multiplied with transform2.\n */\nexport function multiply(transform1, transform2) {\n  const a1 = transform1[0];\n  const b1 = transform1[1];\n  const c1 = transform1[2];\n  const d1 = transform1[3];\n  const e1 = transform1[4];\n  const f1 = transform1[5];\n  const a2 = transform2[0];\n  const b2 = transform2[1];\n  const c2 = transform2[2];\n  const d2 = transform2[3];\n  const e2 = transform2[4];\n  const f2 = transform2[5];\n\n  transform1[0] = a1 * a2 + c1 * b2;\n  transform1[1] = b1 * a2 + d1 * b2;\n  transform1[2] = a1 * c2 + c1 * d2;\n  transform1[3] = b1 * c2 + d1 * d2;\n  transform1[4] = a1 * e2 + c1 * f2 + e1;\n  transform1[5] = b1 * e2 + d1 * f2 + f1;\n\n  return transform1;\n}\n\n/**\n * Set the transform components a-f on a given transform.\n * @param {!Transform} transform Transform.\n * @param {number} a The a component of the transform.\n * @param {number} b The b component of the transform.\n * @param {number} c The c component of the transform.\n * @param {number} d The d component of the transform.\n * @param {number} e The e component of the transform.\n * @param {number} f The f component of the transform.\n * @return {!Transform} Matrix with transform applied.\n */\nexport function set(transform, a, b, c, d, e, f) {\n  transform[0] = a;\n  transform[1] = b;\n  transform[2] = c;\n  transform[3] = d;\n  transform[4] = e;\n  transform[5] = f;\n  return transform;\n}\n\n/**\n * Set transform on one matrix from another matrix.\n * @param {!Transform} transform1 Matrix to set transform to.\n * @param {!Transform} transform2 Matrix to set transform from.\n * @return {!Transform} transform1 with transform from transform2 applied.\n */\nexport function setFromArray(transform1, transform2) {\n  transform1[0] = transform2[0];\n  transform1[1] = transform2[1];\n  transform1[2] = transform2[2];\n  transform1[3] = transform2[3];\n  transform1[4] = transform2[4];\n  transform1[5] = transform2[5];\n  return transform1;\n}\n\n/**\n * Transforms the given coordinate with the given transform returning the\n * resulting, transformed coordinate. The coordinate will be modified in-place.\n *\n * @param {Transform} transform The transformation.\n * @param {import(\"./coordinate.js\").Coordinate|import(\"./pixel.js\").Pixel} coordinate The coordinate to transform.\n * @return {import(\"./coordinate.js\").Coordinate|import(\"./pixel.js\").Pixel} return coordinate so that operations can be\n *     chained together.\n */\nexport function apply(transform, coordinate) {\n  const x = coordinate[0];\n  const y = coordinate[1];\n  coordinate[0] = transform[0] * x + transform[2] * y + transform[4];\n  coordinate[1] = transform[1] * x + transform[3] * y + transform[5];\n  return coordinate;\n}\n\n/**\n * Applies rotation to the given transform.\n * @param {!Transform} transform Transform.\n * @param {number} angle Angle in radians.\n * @return {!Transform} The rotated transform.\n */\nexport function rotate(transform, angle) {\n  const cos = Math.cos(angle);\n  const sin = Math.sin(angle);\n  return multiply(transform, set(tmp_, cos, sin, -sin, cos, 0, 0));\n}\n\n/**\n * Applies scale to a given transform.\n * @param {!Transform} transform Transform.\n * @param {number} x Scale factor x.\n * @param {number} y Scale factor y.\n * @return {!Transform} The scaled transform.\n */\nexport function scale(transform, x, y) {\n  return multiply(transform, set(tmp_, x, 0, 0, y, 0, 0));\n}\n\n/**\n * Creates a scale transform.\n * @param {!Transform} target Transform to overwrite.\n * @param {number} x Scale factor x.\n * @param {number} y Scale factor y.\n * @return {!Transform} The scale transform.\n */\nexport function makeScale(target, x, y) {\n  return set(target, x, 0, 0, y, 0, 0);\n}\n\n/**\n * Applies translation to the given transform.\n * @param {!Transform} transform Transform.\n * @param {number} dx Translation x.\n * @param {number} dy Translation y.\n * @return {!Transform} The translated transform.\n */\nexport function translate(transform, dx, dy) {\n  return multiply(transform, set(tmp_, 1, 0, 0, 1, dx, dy));\n}\n\n/**\n * Creates a composite transform given an initial translation, scale, rotation, and\n * final translation (in that order only, not commutative).\n * @param {!Transform} transform The transform (will be modified in place).\n * @param {number} dx1 Initial translation x.\n * @param {number} dy1 Initial translation y.\n * @param {number} sx Scale factor x.\n * @param {number} sy Scale factor y.\n * @param {number} angle Rotation (in counter-clockwise radians).\n * @param {number} dx2 Final translation x.\n * @param {number} dy2 Final translation y.\n * @return {!Transform} The composite transform.\n */\nexport function compose(transform, dx1, dy1, sx, sy, angle, dx2, dy2) {\n  const sin = Math.sin(angle);\n  const cos = Math.cos(angle);\n  transform[0] = sx * cos;\n  transform[1] = sy * sin;\n  transform[2] = -sx * sin;\n  transform[3] = sy * cos;\n  transform[4] = dx2 * sx * cos - dy2 * sx * sin + dx1;\n  transform[5] = dx2 * sy * sin + dy2 * sy * cos + dy1;\n  return transform;\n}\n\n/**\n * Creates a composite transform given an initial translation, scale, rotation, and\n * final translation (in that order only, not commutative). The resulting transform\n * string can be applied as `transform` property of an HTMLElement's style.\n * @param {number} dx1 Initial translation x.\n * @param {number} dy1 Initial translation y.\n * @param {number} sx Scale factor x.\n * @param {number} sy Scale factor y.\n * @param {number} angle Rotation (in counter-clockwise radians).\n * @param {number} dx2 Final translation x.\n * @param {number} dy2 Final translation y.\n * @return {string} The composite css transform.\n * @api\n */\nexport function composeCssTransform(dx1, dy1, sx, sy, angle, dx2, dy2) {\n  return toString(compose(create(), dx1, dy1, sx, sy, angle, dx2, dy2));\n}\n\n/**\n * Invert the given transform.\n * @param {!Transform} source The source transform to invert.\n * @return {!Transform} The inverted (source) transform.\n */\nexport function invert(source) {\n  return makeInverse(source, source);\n}\n\n/**\n * Invert the given transform.\n * @param {!Transform} target Transform to be set as the inverse of\n *     the source transform.\n * @param {!Transform} source The source transform to invert.\n * @return {!Transform} The inverted (target) transform.\n */\nexport function makeInverse(target, source) {\n  const det = determinant(source);\n  assert(det !== 0, 'Transformation matrix cannot be inverted');\n\n  const a = source[0];\n  const b = source[1];\n  const c = source[2];\n  const d = source[3];\n  const e = source[4];\n  const f = source[5];\n\n  target[0] = d / det;\n  target[1] = -b / det;\n  target[2] = -c / det;\n  target[3] = a / det;\n  target[4] = (c * f - d * e) / det;\n  target[5] = -(a * f - b * e) / det;\n\n  return target;\n}\n\n/**\n * Returns the determinant of the given matrix.\n * @param {!Transform} mat Matrix.\n * @return {number} Determinant.\n */\nexport function determinant(mat) {\n  return mat[0] * mat[3] - mat[1] * mat[2];\n}\n\n/**\n * @type {Array}\n */\nconst matrixPrecision = [1e5, 1e5, 1e5, 1e5, 2, 2];\n\n/**\n * A matrix string version of the transform.  This can be used\n * for CSS transforms.\n * @param {!Transform} mat Matrix.\n * @return {string} The transform as a string.\n */\nexport function toString(mat) {\n  const transformString = 'matrix(' + mat.join(', ') + ')';\n  return transformString;\n}\n\n/**\n * Create a transform from a CSS transform matrix string.\n * @param {string} cssTransform The CSS string to parse.\n * @return {!Transform} The transform.\n */\nexport function fromString(cssTransform) {\n  const values = cssTransform.substring(7, cssTransform.length - 1).split(',');\n  return values.map(parseFloat);\n}\n\n/**\n * Compare two matrices for equality.\n * @param {!string} cssTransform1 A CSS transform matrix string.\n * @param {!string} cssTransform2 A CSS transform matrix string.\n * @return {boolean} The two matrices are equal.\n */\nexport function equivalent(cssTransform1, cssTransform2) {\n  const mat1 = fromString(cssTransform1);\n  const mat2 = fromString(cssTransform2);\n  for (let i = 0; i < 6; ++i) {\n    if (Math.round((mat1[i] - mat2[i]) * matrixPrecision[i]) !== 0) {\n      return false;\n    }\n  }\n  return true;\n}\n", "/**\n * @module ol/geom/flat/transform\n */\n\n/**\n * @param {Array<number>} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {number} end End.\n * @param {number} stride Stride.\n * @param {import(\"../../transform.js\").Transform} transform Transform.\n * @param {Array<number>} [dest] Destination.\n * @param {number} [destinationStride] Stride of destination coordinates; if unspecified, assumed to be 2.\n * @return {Array<number>} Transformed coordinates.\n */\nexport function transform2D(\n  flatCoordinates,\n  offset,\n  end,\n  stride,\n  transform,\n  dest,\n  destinationStride,\n) {\n  dest = dest ? dest : [];\n  destinationStride = destinationStride ? destinationStride : 2;\n  let i = 0;\n  for (let j = offset; j < end; j += stride) {\n    const x = flatCoordinates[j];\n    const y = flatCoordinates[j + 1];\n    dest[i++] = transform[0] * x + transform[2] * y + transform[4];\n    dest[i++] = transform[1] * x + transform[3] * y + transform[5];\n\n    for (let k = 2; k < destinationStride; k++) {\n      dest[i++] = flatCoordinates[j + k];\n    }\n  }\n\n  if (dest && dest.length != i) {\n    dest.length = i;\n  }\n  return dest;\n}\n\n/**\n * @param {Array<number>} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {number} end End.\n * @param {number} stride Stride.\n * @param {number} angle Angle.\n * @param {Array<number>} anchor Rotation anchor point.\n * @param {Array<number>} [dest] Destination.\n * @return {Array<number>} Transformed coordinates.\n */\nexport function rotate(\n  flatCoordinates,\n  offset,\n  end,\n  stride,\n  angle,\n  anchor,\n  dest,\n) {\n  dest = dest ? dest : [];\n  const cos = Math.cos(angle);\n  const sin = Math.sin(angle);\n  const anchorX = anchor[0];\n  const anchorY = anchor[1];\n  let i = 0;\n  for (let j = offset; j < end; j += stride) {\n    const deltaX = flatCoordinates[j] - anchorX;\n    const deltaY = flatCoordinates[j + 1] - anchorY;\n    dest[i++] = anchorX + deltaX * cos - deltaY * sin;\n    dest[i++] = anchorY + deltaX * sin + deltaY * cos;\n    for (let k = j + 2; k < j + stride; ++k) {\n      dest[i++] = flatCoordinates[k];\n    }\n  }\n  if (dest && dest.length != i) {\n    dest.length = i;\n  }\n  return dest;\n}\n\n/**\n * Scale the coordinates.\n * @param {Array<number>} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {number} end End.\n * @param {number} stride Stride.\n * @param {number} sx Scale factor in the x-direction.\n * @param {number} sy Scale factor in the y-direction.\n * @param {Array<number>} anchor Scale anchor point.\n * @param {Array<number>} [dest] Destination.\n * @return {Array<number>} Transformed coordinates.\n */\nexport function scale(\n  flatCoordinates,\n  offset,\n  end,\n  stride,\n  sx,\n  sy,\n  anchor,\n  dest,\n) {\n  dest = dest ? dest : [];\n  const anchorX = anchor[0];\n  const anchorY = anchor[1];\n  let i = 0;\n  for (let j = offset; j < end; j += stride) {\n    const deltaX = flatCoordinates[j] - anchorX;\n    const deltaY = flatCoordinates[j + 1] - anchorY;\n    dest[i++] = anchorX + sx * deltaX;\n    dest[i++] = anchorY + sy * deltaY;\n    for (let k = j + 2; k < j + stride; ++k) {\n      dest[i++] = flatCoordinates[k];\n    }\n  }\n  if (dest && dest.length != i) {\n    dest.length = i;\n  }\n  return dest;\n}\n\n/**\n * @param {Array<number>} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {number} end End.\n * @param {number} stride Stride.\n * @param {number} deltaX Delta X.\n * @param {number} deltaY Delta Y.\n * @param {Array<number>} [dest] Destination.\n * @return {Array<number>} Transformed coordinates.\n */\nexport function translate(\n  flatCoordinates,\n  offset,\n  end,\n  stride,\n  deltaX,\n  deltaY,\n  dest,\n) {\n  dest = dest ? dest : [];\n  let i = 0;\n  for (let j = offset; j < end; j += stride) {\n    dest[i++] = flatCoordinates[j] + deltaX;\n    dest[i++] = flatCoordinates[j + 1] + deltaY;\n    for (let k = j + 2; k < j + stride; ++k) {\n      dest[i++] = flatCoordinates[k];\n    }\n  }\n  if (dest && dest.length != i) {\n    dest.length = i;\n  }\n  return dest;\n}\n", "/**\n * @module ol/geom/Geometry\n */\nimport BaseObject from '../Object.js';\nimport {\n  createEmpty,\n  createOrUpdateEmpty,\n  getHeight,\n  returnOrUpdate,\n} from '../extent.js';\nimport {memoizeOne} from '../functions.js';\nimport {get as getProjection, getTransform} from '../proj.js';\nimport {\n  compose as composeTransform,\n  create as createTransform,\n} from '../transform.js';\nimport {abstract} from '../util.js';\nimport {transform2D} from './flat/transform.js';\n\n/**\n * @typedef {'XY' | 'XYZ' | 'XYM' | 'XYZM'} GeometryLayout\n * The coordinate layout for geometries, indicating whether a 3rd or 4th z ('Z')\n * or measure ('M') coordinate is available.\n */\n\n/**\n * @typedef {'Point' | 'LineString' | 'LinearRing' | 'Polygon' | 'MultiPoint' | 'MultiLineString' | 'MultiPolygon' | 'GeometryCollection' | 'Circle'} Type\n * The geometry type.  One of `'Point'`, `'LineString'`, `'LinearRing'`,\n * `'Polygon'`, `'MultiPoint'`, `'MultiLineString'`, `'MultiPolygon'`,\n * `'GeometryCollection'`, or `'Circle'`.\n */\n\n/**\n * @type {import(\"../transform.js\").Transform}\n */\nconst tmpTransform = createTransform();\n\n/** @type {import('../coordinate.js').Coordinate} */\nconst tmpPoint = [NaN, NaN];\n\n/**\n * @classdesc\n * Abstract base class; normally only used for creating subclasses and not\n * instantiated in apps.\n * Base class for vector geometries.\n *\n * To get notified of changes to the geometry, register a listener for the\n * generic `change` event on your geometry instance.\n *\n * @abstract\n * @api\n */\nclass Geometry extends BaseObject {\n  constructor() {\n    super();\n\n    /**\n     * @private\n     * @type {import(\"../extent.js\").Extent}\n     */\n    this.extent_ = createEmpty();\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.extentRevision_ = -1;\n\n    /**\n     * @protected\n     * @type {number}\n     */\n    this.simplifiedGeometryMaxMinSquaredTolerance = 0;\n\n    /**\n     * @protected\n     * @type {number}\n     */\n    this.simplifiedGeometryRevision = 0;\n\n    /**\n     * Get a transformed and simplified version of the geometry.\n     * @abstract\n     * @param {number} revision The geometry revision.\n     * @param {number} squaredTolerance Squared tolerance.\n     * @param {import(\"../proj.js\").TransformFunction} [transform] Optional transform function.\n     * @return {Geometry} Simplified geometry.\n     */\n    this.simplifyTransformedInternal = memoizeOne(\n      (revision, squaredTolerance, transform) => {\n        if (!transform) {\n          return this.getSimplifiedGeometry(squaredTolerance);\n        }\n        const clone = this.clone();\n        clone.applyTransform(transform);\n        return clone.getSimplifiedGeometry(squaredTolerance);\n      },\n    );\n  }\n\n  /**\n   * Get a transformed and simplified version of the geometry.\n   * @abstract\n   * @param {number} squaredTolerance Squared tolerance.\n   * @param {import(\"../proj.js\").TransformFunction} [transform] Optional transform function.\n   * @return {Geometry} Simplified geometry.\n   */\n  simplifyTransformed(squaredTolerance, transform) {\n    return this.simplifyTransformedInternal(\n      this.getRevision(),\n      squaredTolerance,\n      transform,\n    );\n  }\n\n  /**\n   * Make a complete copy of the geometry.\n   * @abstract\n   * @return {!Geometry} Clone.\n   */\n  clone() {\n    return abstract();\n  }\n\n  /**\n   * @abstract\n   * @param {number} x X.\n   * @param {number} y Y.\n   * @param {import(\"../coordinate.js\").Coordinate} closestPoint Closest point.\n   * @param {number} minSquaredDistance Minimum squared distance.\n   * @return {number} Minimum squared distance.\n   */\n  closestPointXY(x, y, closestPoint, minSquaredDistance) {\n    return abstract();\n  }\n\n  /**\n   * @param {number} x X.\n   * @param {number} y Y.\n   * @return {boolean} Contains (x, y).\n   */\n  containsXY(x, y) {\n    return this.closestPointXY(x, y, tmpPoint, Number.MIN_VALUE) === 0;\n  }\n\n  /**\n   * Return the closest point of the geometry to the passed point as\n   * {@link module:ol/coordinate~Coordinate coordinate}.\n   * @param {import(\"../coordinate.js\").Coordinate} point Point.\n   * @param {import(\"../coordinate.js\").Coordinate} [closestPoint] Closest point.\n   * @return {import(\"../coordinate.js\").Coordinate} Closest point.\n   * @api\n   */\n  getClosestPoint(point, closestPoint) {\n    closestPoint = closestPoint ? closestPoint : [NaN, NaN];\n    this.closestPointXY(point[0], point[1], closestPoint, Infinity);\n    return closestPoint;\n  }\n\n  /**\n   * Returns true if this geometry includes the specified coordinate. If the\n   * coordinate is on the boundary of the geometry, returns false.\n   * @param {import(\"../coordinate.js\").Coordinate} coordinate Coordinate.\n   * @return {boolean} Contains coordinate.\n   * @api\n   */\n  intersectsCoordinate(coordinate) {\n    return this.containsXY(coordinate[0], coordinate[1]);\n  }\n\n  /**\n   * @abstract\n   * @param {import(\"../extent.js\").Extent} extent Extent.\n   * @protected\n   * @return {import(\"../extent.js\").Extent} extent Extent.\n   */\n  computeExtent(extent) {\n    return abstract();\n  }\n\n  /**\n   * Get the extent of the geometry.\n   * @param {import(\"../extent.js\").Extent} [extent] Extent.\n   * @return {import(\"../extent.js\").Extent} extent Extent.\n   * @api\n   */\n  getExtent(extent) {\n    if (this.extentRevision_ != this.getRevision()) {\n      const extent = this.computeExtent(this.extent_);\n      if (isNaN(extent[0]) || isNaN(extent[1])) {\n        createOrUpdateEmpty(extent);\n      }\n      this.extentRevision_ = this.getRevision();\n    }\n    return returnOrUpdate(this.extent_, extent);\n  }\n\n  /**\n   * Rotate the geometry around a given coordinate. This modifies the geometry\n   * coordinates in place.\n   * @abstract\n   * @param {number} angle Rotation angle in radians.\n   * @param {import(\"../coordinate.js\").Coordinate} anchor The rotation center.\n   * @api\n   */\n  rotate(angle, anchor) {\n    abstract();\n  }\n\n  /**\n   * Scale the geometry (with an optional origin).  This modifies the geometry\n   * coordinates in place.\n   * @abstract\n   * @param {number} sx The scaling factor in the x-direction.\n   * @param {number} [sy] The scaling factor in the y-direction (defaults to sx).\n   * @param {import(\"../coordinate.js\").Coordinate} [anchor] The scale origin (defaults to the center\n   *     of the geometry extent).\n   * @api\n   */\n  scale(sx, sy, anchor) {\n    abstract();\n  }\n\n  /**\n   * Create a simplified version of this geometry.  For linestrings, this uses\n   * the [Douglas Peucker](https://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm)\n   * algorithm.  For polygons, a quantization-based\n   * simplification is used to preserve topology.\n   * @param {number} tolerance The tolerance distance for simplification.\n   * @return {Geometry} A new, simplified version of the original geometry.\n   * @api\n   */\n  simplify(tolerance) {\n    return this.getSimplifiedGeometry(tolerance * tolerance);\n  }\n\n  /**\n   * Create a simplified version of this geometry using the Douglas Peucker\n   * algorithm.\n   * See https://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm.\n   * @abstract\n   * @param {number} squaredTolerance Squared tolerance.\n   * @return {Geometry} Simplified geometry.\n   */\n  getSimplifiedGeometry(squaredTolerance) {\n    return abstract();\n  }\n\n  /**\n   * Get the type of this geometry.\n   * @abstract\n   * @return {Type} Geometry type.\n   */\n  getType() {\n    return abstract();\n  }\n\n  /**\n   * Apply a transform function to the coordinates of the geometry.\n   * The geometry is modified in place.\n   * If you do not want the geometry modified in place, first `clone()` it and\n   * then use this function on the clone.\n   * @abstract\n   * @param {import(\"../proj.js\").TransformFunction} transformFn Transform function.\n   * Called with a flat array of geometry coordinates.\n   */\n  applyTransform(transformFn) {\n    abstract();\n  }\n\n  /**\n   * Test if the geometry and the passed extent intersect.\n   * @abstract\n   * @param {import(\"../extent.js\").Extent} extent Extent.\n   * @return {boolean} `true` if the geometry and the extent intersect.\n   */\n  intersectsExtent(extent) {\n    return abstract();\n  }\n\n  /**\n   * Translate the geometry.  This modifies the geometry coordinates in place.  If\n   * instead you want a new geometry, first `clone()` this geometry.\n   * @abstract\n   * @param {number} deltaX Delta X.\n   * @param {number} deltaY Delta Y.\n   * @api\n   */\n  translate(deltaX, deltaY) {\n    abstract();\n  }\n\n  /**\n   * Transform each coordinate of the geometry from one coordinate reference\n   * system to another. The geometry is modified in place.\n   * For example, a line will be transformed to a line and a circle to a circle.\n   * If you do not want the geometry modified in place, first `clone()` it and\n   * then use this function on the clone.\n   *\n   * @param {import(\"../proj.js\").ProjectionLike} source The current projection.  Can be a\n   *     string identifier or a {@link module:ol/proj/Projection~Projection} object.\n   * @param {import(\"../proj.js\").ProjectionLike} destination The desired projection.  Can be a\n   *     string identifier or a {@link module:ol/proj/Projection~Projection} object.\n   * @return {this} This geometry.  Note that original geometry is\n   *     modified in place.\n   * @api\n   */\n  transform(source, destination) {\n    /** @type {import(\"../proj/Projection.js\").default} */\n    const sourceProj = getProjection(source);\n    const transformFn =\n      sourceProj.getUnits() == 'tile-pixels'\n        ? function (inCoordinates, outCoordinates, stride) {\n            const pixelExtent = sourceProj.getExtent();\n            const projectedExtent = sourceProj.getWorldExtent();\n            const scale = getHeight(projectedExtent) / getHeight(pixelExtent);\n            composeTransform(\n              tmpTransform,\n              projectedExtent[0],\n              projectedExtent[3],\n              scale,\n              -scale,\n              0,\n              0,\n              0,\n            );\n            const transformed = transform2D(\n              inCoordinates,\n              0,\n              inCoordinates.length,\n              stride,\n              tmpTransform,\n              outCoordinates,\n            );\n            const projTransform = getTransform(sourceProj, destination);\n            if (projTransform) {\n              return projTransform(transformed, transformed, stride);\n            }\n            return transformed;\n          }\n        : getTransform(sourceProj, destination);\n    this.applyTransform(transformFn);\n    return this;\n  }\n}\n\nexport default Geometry;\n", "/**\n * @module ol/geom/SimpleGeometry\n */\nimport {createOrUpdateFromFlatCoordinates, getCenter} from '../extent.js';\nimport {abstract} from '../util.js';\nimport Geometry from './Geometry.js';\nimport {rotate, scale, transform2D, translate} from './flat/transform.js';\n\n/**\n * @classdesc\n * Abstract base class; only used for creating subclasses; do not instantiate\n * in apps, as cannot be rendered.\n *\n * @abstract\n * @api\n */\nclass SimpleGeometry extends Geometry {\n  constructor() {\n    super();\n\n    /**\n     * @protected\n     * @type {import(\"./Geometry.js\").GeometryLayout}\n     */\n    this.layout = 'XY';\n\n    /**\n     * @protected\n     * @type {number}\n     */\n    this.stride = 2;\n\n    /**\n     * @protected\n     * @type {Array<number>}\n     */\n    this.flatCoordinates;\n  }\n\n  /**\n   * @param {import(\"../extent.js\").Extent} extent Extent.\n   * @protected\n   * @return {import(\"../extent.js\").Extent} extent Extent.\n   * @override\n   */\n  computeExtent(extent) {\n    return createOrUpdateFromFlatCoordinates(\n      this.flatCoordinates,\n      0,\n      this.flatCoordinates.length,\n      this.stride,\n      extent,\n    );\n  }\n\n  /**\n   * @abstract\n   * @return {Array<*> | null} Coordinates.\n   */\n  getCoordinates() {\n    return abstract();\n  }\n\n  /**\n   * Return the first coordinate of the geometry.\n   * @return {import(\"../coordinate.js\").Coordinate} First coordinate.\n   * @api\n   */\n  getFirstCoordinate() {\n    return this.flatCoordinates.slice(0, this.stride);\n  }\n\n  /**\n   * @return {Array<number>} Flat coordinates.\n   */\n  getFlatCoordinates() {\n    return this.flatCoordinates;\n  }\n\n  /**\n   * Return the last coordinate of the geometry.\n   * @return {import(\"../coordinate.js\").Coordinate} Last point.\n   * @api\n   */\n  getLastCoordinate() {\n    return this.flatCoordinates.slice(\n      this.flatCoordinates.length - this.stride,\n    );\n  }\n\n  /**\n   * Return the {@link import(\"./Geometry.js\").GeometryLayout layout} of the geometry.\n   * @return {import(\"./Geometry.js\").GeometryLayout} Layout.\n   * @api\n   */\n  getLayout() {\n    return this.layout;\n  }\n\n  /**\n   * Create a simplified version of this geometry using the Douglas Peucker algorithm.\n   * @param {number} squaredTolerance Squared tolerance.\n   * @return {SimpleGeometry} Simplified geometry.\n   * @override\n   */\n  getSimplifiedGeometry(squaredTolerance) {\n    if (this.simplifiedGeometryRevision !== this.getRevision()) {\n      this.simplifiedGeometryMaxMinSquaredTolerance = 0;\n      this.simplifiedGeometryRevision = this.getRevision();\n    }\n    // If squaredTolerance is negative or if we know that simplification will not\n    // have any effect then just return this.\n    if (\n      squaredTolerance < 0 ||\n      (this.simplifiedGeometryMaxMinSquaredTolerance !== 0 &&\n        squaredTolerance <= this.simplifiedGeometryMaxMinSquaredTolerance)\n    ) {\n      return this;\n    }\n\n    const simplifiedGeometry =\n      this.getSimplifiedGeometryInternal(squaredTolerance);\n    const simplifiedFlatCoordinates = simplifiedGeometry.getFlatCoordinates();\n    if (simplifiedFlatCoordinates.length < this.flatCoordinates.length) {\n      return simplifiedGeometry;\n    }\n    // Simplification did not actually remove any coordinates.  We now know\n    // that any calls to getSimplifiedGeometry with a squaredTolerance less\n    // than or equal to the current squaredTolerance will also not have any\n    // effect.  This allows us to short circuit simplification (saving CPU\n    // cycles) and prevents the cache of simplified geometries from filling\n    // up with useless identical copies of this geometry (saving memory).\n    this.simplifiedGeometryMaxMinSquaredTolerance = squaredTolerance;\n    return this;\n  }\n\n  /**\n   * @param {number} squaredTolerance Squared tolerance.\n   * @return {SimpleGeometry} Simplified geometry.\n   * @protected\n   */\n  getSimplifiedGeometryInternal(squaredTolerance) {\n    return this;\n  }\n\n  /**\n   * @return {number} Stride.\n   */\n  getStride() {\n    return this.stride;\n  }\n\n  /**\n   * @param {import(\"./Geometry.js\").GeometryLayout} layout Layout.\n   * @param {Array<number>} flatCoordinates Flat coordinates.\n   */\n  setFlatCoordinates(layout, flatCoordinates) {\n    this.stride = getStrideForLayout(layout);\n    this.layout = layout;\n    this.flatCoordinates = flatCoordinates;\n  }\n\n  /**\n   * @abstract\n   * @param {!Array<*>} coordinates Coordinates.\n   * @param {import(\"./Geometry.js\").GeometryLayout} [layout] Layout.\n   */\n  setCoordinates(coordinates, layout) {\n    abstract();\n  }\n\n  /**\n   * @param {import(\"./Geometry.js\").GeometryLayout|undefined} layout Layout.\n   * @param {Array<*>} coordinates Coordinates.\n   * @param {number} nesting Nesting.\n   * @protected\n   */\n  setLayout(layout, coordinates, nesting) {\n    let stride;\n    if (layout) {\n      stride = getStrideForLayout(layout);\n    } else {\n      for (let i = 0; i < nesting; ++i) {\n        if (coordinates.length === 0) {\n          this.layout = 'XY';\n          this.stride = 2;\n          return;\n        }\n        coordinates = /** @type {Array<unknown>} */ (coordinates[0]);\n      }\n      stride = coordinates.length;\n      layout = getLayoutForStride(stride);\n    }\n    this.layout = layout;\n    this.stride = stride;\n  }\n\n  /**\n   * Apply a transform function to the coordinates of the geometry.\n   * The geometry is modified in place.\n   * If you do not want the geometry modified in place, first `clone()` it and\n   * then use this function on the clone.\n   * @param {import(\"../proj.js\").TransformFunction} transformFn Transform function.\n   * Called with a flat array of geometry coordinates.\n   * @api\n   * @override\n   */\n  applyTransform(transformFn) {\n    if (this.flatCoordinates) {\n      transformFn(\n        this.flatCoordinates,\n        this.flatCoordinates,\n        this.layout.startsWith('XYZ') ? 3 : 2,\n        this.stride,\n      );\n      this.changed();\n    }\n  }\n\n  /**\n   * Rotate the geometry around a given coordinate. This modifies the geometry\n   * coordinates in place.\n   * @param {number} angle Rotation angle in counter-clockwise radians.\n   * @param {import(\"../coordinate.js\").Coordinate} anchor The rotation center.\n   * @api\n   * @override\n   */\n  rotate(angle, anchor) {\n    const flatCoordinates = this.getFlatCoordinates();\n    if (flatCoordinates) {\n      const stride = this.getStride();\n      rotate(\n        flatCoordinates,\n        0,\n        flatCoordinates.length,\n        stride,\n        angle,\n        anchor,\n        flatCoordinates,\n      );\n      this.changed();\n    }\n  }\n\n  /**\n   * Scale the geometry (with an optional origin).  This modifies the geometry\n   * coordinates in place.\n   * @param {number} sx The scaling factor in the x-direction.\n   * @param {number} [sy] The scaling factor in the y-direction (defaults to sx).\n   * @param {import(\"../coordinate.js\").Coordinate} [anchor] The scale origin (defaults to the center\n   *     of the geometry extent).\n   * @api\n   * @override\n   */\n  scale(sx, sy, anchor) {\n    if (sy === undefined) {\n      sy = sx;\n    }\n    if (!anchor) {\n      anchor = getCenter(this.getExtent());\n    }\n    const flatCoordinates = this.getFlatCoordinates();\n    if (flatCoordinates) {\n      const stride = this.getStride();\n      scale(\n        flatCoordinates,\n        0,\n        flatCoordinates.length,\n        stride,\n        sx,\n        sy,\n        anchor,\n        flatCoordinates,\n      );\n      this.changed();\n    }\n  }\n\n  /**\n   * Translate the geometry.  This modifies the geometry coordinates in place.  If\n   * instead you want a new geometry, first `clone()` this geometry.\n   * @param {number} deltaX Delta X.\n   * @param {number} deltaY Delta Y.\n   * @api\n   * @override\n   */\n  translate(deltaX, deltaY) {\n    const flatCoordinates = this.getFlatCoordinates();\n    if (flatCoordinates) {\n      const stride = this.getStride();\n      translate(\n        flatCoordinates,\n        0,\n        flatCoordinates.length,\n        stride,\n        deltaX,\n        deltaY,\n        flatCoordinates,\n      );\n      this.changed();\n    }\n  }\n}\n\n/**\n * @param {number} stride Stride.\n * @return {import(\"./Geometry.js\").GeometryLayout} layout Layout.\n */\nexport function getLayoutForStride(stride) {\n  let layout;\n  if (stride == 2) {\n    layout = 'XY';\n  } else if (stride == 3) {\n    layout = 'XYZ';\n  } else if (stride == 4) {\n    layout = 'XYZM';\n  }\n  return /** @type {import(\"./Geometry.js\").GeometryLayout} */ (layout);\n}\n\n/**\n * @param {import(\"./Geometry.js\").GeometryLayout} layout Layout.\n * @return {number} Stride.\n */\nexport function getStrideForLayout(layout) {\n  let stride;\n  if (layout == 'XY') {\n    stride = 2;\n  } else if (layout == 'XYZ' || layout == 'XYM') {\n    stride = 3;\n  } else if (layout == 'XYZM') {\n    stride = 4;\n  }\n  return /** @type {number} */ (stride);\n}\n\n/**\n * @param {SimpleGeometry} simpleGeometry Simple geometry.\n * @param {import(\"../transform.js\").Transform} transform Transform.\n * @param {Array<number>} [dest] Destination.\n * @return {Array<number>} Transformed flat coordinates.\n */\nexport function transformGeom2D(simpleGeometry, transform, dest) {\n  const flatCoordinates = simpleGeometry.getFlatCoordinates();\n  if (!flatCoordinates) {\n    return null;\n  }\n  const stride = simpleGeometry.getStride();\n  return transform2D(\n    flatCoordinates,\n    0,\n    flatCoordinates.length,\n    stride,\n    transform,\n    dest,\n  );\n}\n\nexport default SimpleGeometry;\n", "/**\n * @module ol/geom/flat/area\n */\n\n/**\n * @param {Array<number>} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {number} end End.\n * @param {number} stride Stride.\n * @return {number} Area.\n */\nexport function linearRing(flatCoordinates, offset, end, stride) {\n  let twiceArea = 0;\n  const x0 = flatCoordinates[end - stride];\n  const y0 = flatCoordinates[end - stride + 1];\n  let dx1 = 0;\n  let dy1 = 0;\n  for (; offset < end; offset += stride) {\n    const dx2 = flatCoordinates[offset] - x0;\n    const dy2 = flatCoordinates[offset + 1] - y0;\n    twiceArea += dy1 * dx2 - dx1 * dy2;\n    dx1 = dx2;\n    dy1 = dy2;\n  }\n  return twiceArea / 2;\n}\n\n/**\n * @param {Array<number>} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {Array<number>} ends Ends.\n * @param {number} stride Stride.\n * @return {number} Area.\n */\nexport function linearRings(flatCoordinates, offset, ends, stride) {\n  let area = 0;\n  for (let i = 0, ii = ends.length; i < ii; ++i) {\n    const end = ends[i];\n    area += linearRing(flatCoordinates, offset, end, stride);\n    offset = end;\n  }\n  return area;\n}\n\n/**\n * @param {Array<number>} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {Array<Array<number>>} endss Endss.\n * @param {number} stride Stride.\n * @return {number} Area.\n */\nexport function linearRingss(flatCoordinates, offset, endss, stride) {\n  let area = 0;\n  for (let i = 0, ii = endss.length; i < ii; ++i) {\n    const ends = endss[i];\n    area += linearRings(flatCoordinates, offset, ends, stride);\n    offset = ends[ends.length - 1];\n  }\n  return area;\n}\n", "/**\n * @module ol/geom/flat/closest\n */\nimport {lerp, squaredDistance as squaredDx} from '../../math.js';\n\n/**\n * Returns the point on the 2D line segment flatCoordinates[offset1] to\n * flatCoordinates[offset2] that is closest to the point (x, y).  Extra\n * dimensions are linearly interpolated.\n * @param {Array<number>} flatCoordinates Flat coordinates.\n * @param {number} offset1 Offset 1.\n * @param {number} offset2 Offset 2.\n * @param {number} stride Stride.\n * @param {number} x X.\n * @param {number} y Y.\n * @param {Array<number>} closestPoint Closest point.\n */\nfunction assignClosest(\n  flatCoordinates,\n  offset1,\n  offset2,\n  stride,\n  x,\n  y,\n  closestPoint,\n) {\n  const x1 = flatCoordinates[offset1];\n  const y1 = flatCoordinates[offset1 + 1];\n  const dx = flatCoordinates[offset2] - x1;\n  const dy = flatCoordinates[offset2 + 1] - y1;\n  let offset;\n  if (dx === 0 && dy === 0) {\n    offset = offset1;\n  } else {\n    const t = ((x - x1) * dx + (y - y1) * dy) / (dx * dx + dy * dy);\n    if (t > 1) {\n      offset = offset2;\n    } else if (t > 0) {\n      for (let i = 0; i < stride; ++i) {\n        closestPoint[i] = lerp(\n          flatCoordinates[offset1 + i],\n          flatCoordinates[offset2 + i],\n          t,\n        );\n      }\n      closestPoint.length = stride;\n      return;\n    } else {\n      offset = offset1;\n    }\n  }\n  for (let i = 0; i < stride; ++i) {\n    closestPoint[i] = flatCoordinates[offset + i];\n  }\n  closestPoint.length = stride;\n}\n\n/**\n * Return the squared of the largest distance between any pair of consecutive\n * coordinates.\n * @param {Array<number>} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {number} end End.\n * @param {number} stride Stride.\n * @param {number} max Max squared delta.\n * @return {number} Max squared delta.\n */\nexport function maxSquaredDelta(flatCoordinates, offset, end, stride, max) {\n  let x1 = flatCoordinates[offset];\n  let y1 = flatCoordinates[offset + 1];\n  for (offset += stride; offset < end; offset += stride) {\n    const x2 = flatCoordinates[offset];\n    const y2 = flatCoordinates[offset + 1];\n    const squaredDelta = squaredDx(x1, y1, x2, y2);\n    if (squaredDelta > max) {\n      max = squaredDelta;\n    }\n    x1 = x2;\n    y1 = y2;\n  }\n  return max;\n}\n\n/**\n * @param {Array<number>} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {Array<number>} ends Ends.\n * @param {number} stride Stride.\n * @param {number} max Max squared delta.\n * @return {number} Max squared delta.\n */\nexport function arrayMaxSquaredDelta(\n  flatCoordinates,\n  offset,\n  ends,\n  stride,\n  max,\n) {\n  for (let i = 0, ii = ends.length; i < ii; ++i) {\n    const end = ends[i];\n    max = maxSquaredDelta(flatCoordinates, offset, end, stride, max);\n    offset = end;\n  }\n  return max;\n}\n\n/**\n * @param {Array<number>} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {Array<Array<number>>} endss Endss.\n * @param {number} stride Stride.\n * @param {number} max Max squared delta.\n * @return {number} Max squared delta.\n */\nexport function multiArrayMaxSquaredDelta(\n  flatCoordinates,\n  offset,\n  endss,\n  stride,\n  max,\n) {\n  for (let i = 0, ii = endss.length; i < ii; ++i) {\n    const ends = endss[i];\n    max = arrayMaxSquaredDelta(flatCoordinates, offset, ends, stride, max);\n    offset = ends[ends.length - 1];\n  }\n  return max;\n}\n\n/**\n * @param {Array<number>} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {number} end End.\n * @param {number} stride Stride.\n * @param {number} maxDelta Max delta.\n * @param {boolean} isRing Is ring.\n * @param {number} x X.\n * @param {number} y Y.\n * @param {Array<number>} closestPoint Closest point.\n * @param {number} minSquaredDistance Minimum squared distance.\n * @param {Array<number>} [tmpPoint] Temporary point object.\n * @return {number} Minimum squared distance.\n */\nexport function assignClosestPoint(\n  flatCoordinates,\n  offset,\n  end,\n  stride,\n  maxDelta,\n  isRing,\n  x,\n  y,\n  closestPoint,\n  minSquaredDistance,\n  tmpPoint,\n) {\n  if (offset == end) {\n    return minSquaredDistance;\n  }\n  let i, squaredDistance;\n  if (maxDelta === 0) {\n    // All points are identical, so just test the first point.\n    squaredDistance = squaredDx(\n      x,\n      y,\n      flatCoordinates[offset],\n      flatCoordinates[offset + 1],\n    );\n    if (squaredDistance < minSquaredDistance) {\n      for (i = 0; i < stride; ++i) {\n        closestPoint[i] = flatCoordinates[offset + i];\n      }\n      closestPoint.length = stride;\n      return squaredDistance;\n    }\n    return minSquaredDistance;\n  }\n  tmpPoint = tmpPoint ? tmpPoint : [NaN, NaN];\n  let index = offset + stride;\n  while (index < end) {\n    assignClosest(\n      flatCoordinates,\n      index - stride,\n      index,\n      stride,\n      x,\n      y,\n      tmpPoint,\n    );\n    squaredDistance = squaredDx(x, y, tmpPoint[0], tmpPoint[1]);\n    if (squaredDistance < minSquaredDistance) {\n      minSquaredDistance = squaredDistance;\n      for (i = 0; i < stride; ++i) {\n        closestPoint[i] = tmpPoint[i];\n      }\n      closestPoint.length = stride;\n      index += stride;\n    } else {\n      // Skip ahead multiple points, because we know that all the skipped\n      // points cannot be any closer than the closest point we have found so\n      // far.  We know this because we know how close the current point is, how\n      // close the closest point we have found so far is, and the maximum\n      // distance between consecutive points.  For example, if we're currently\n      // at distance 10, the best we've found so far is 3, and that the maximum\n      // distance between consecutive points is 2, then we'll need to skip at\n      // least (10 - 3) / 2 == 3 (rounded down) points to have any chance of\n      // finding a closer point.  We use Math.max(..., 1) to ensure that we\n      // always advance at least one point, to avoid an infinite loop.\n      index +=\n        stride *\n        Math.max(\n          ((Math.sqrt(squaredDistance) - Math.sqrt(minSquaredDistance)) /\n            maxDelta) |\n            0,\n          1,\n        );\n    }\n  }\n  if (isRing) {\n    // Check the closing segment.\n    assignClosest(\n      flatCoordinates,\n      end - stride,\n      offset,\n      stride,\n      x,\n      y,\n      tmpPoint,\n    );\n    squaredDistance = squaredDx(x, y, tmpPoint[0], tmpPoint[1]);\n    if (squaredDistance < minSquaredDistance) {\n      minSquaredDistance = squaredDistance;\n      for (i = 0; i < stride; ++i) {\n        closestPoint[i] = tmpPoint[i];\n      }\n      closestPoint.length = stride;\n    }\n  }\n  return minSquaredDistance;\n}\n\n/**\n * @param {Array<number>} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {Array<number>} ends Ends.\n * @param {number} stride Stride.\n * @param {number} maxDelta Max delta.\n * @param {boolean} isRing Is ring.\n * @param {number} x X.\n * @param {number} y Y.\n * @param {Array<number>} closestPoint Closest point.\n * @param {number} minSquaredDistance Minimum squared distance.\n * @param {Array<number>} [tmpPoint] Temporary point object.\n * @return {number} Minimum squared distance.\n */\nexport function assignClosestArrayPoint(\n  flatCoordinates,\n  offset,\n  ends,\n  stride,\n  maxDelta,\n  isRing,\n  x,\n  y,\n  closestPoint,\n  minSquaredDistance,\n  tmpPoint,\n) {\n  tmpPoint = tmpPoint ? tmpPoint : [NaN, NaN];\n  for (let i = 0, ii = ends.length; i < ii; ++i) {\n    const end = ends[i];\n    minSquaredDistance = assignClosestPoint(\n      flatCoordinates,\n      offset,\n      end,\n      stride,\n      maxDelta,\n      isRing,\n      x,\n      y,\n      closestPoint,\n      minSquaredDistance,\n      tmpPoint,\n    );\n    offset = end;\n  }\n  return minSquaredDistance;\n}\n\n/**\n * @param {Array<number>} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {Array<Array<number>>} endss Endss.\n * @param {number} stride Stride.\n * @param {number} maxDelta Max delta.\n * @param {boolean} isRing Is ring.\n * @param {number} x X.\n * @param {number} y Y.\n * @param {Array<number>} closestPoint Closest point.\n * @param {number} minSquaredDistance Minimum squared distance.\n * @param {Array<number>} [tmpPoint] Temporary point object.\n * @return {number} Minimum squared distance.\n */\nexport function assignClosestMultiArrayPoint(\n  flatCoordinates,\n  offset,\n  endss,\n  stride,\n  maxDelta,\n  isRing,\n  x,\n  y,\n  closestPoint,\n  minSquaredDistance,\n  tmpPoint,\n) {\n  tmpPoint = tmpPoint ? tmpPoint : [NaN, NaN];\n  for (let i = 0, ii = endss.length; i < ii; ++i) {\n    const ends = endss[i];\n    minSquaredDistance = assignClosestArrayPoint(\n      flatCoordinates,\n      offset,\n      ends,\n      stride,\n      maxDelta,\n      isRing,\n      x,\n      y,\n      closestPoint,\n      minSquaredDistance,\n      tmpPoint,\n    );\n    offset = ends[ends.length - 1];\n  }\n  return minSquaredDistance;\n}\n", "/**\n * @module ol/geom/flat/deflate\n */\n\n/**\n * @param {Array<number>} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {import(\"../../coordinate.js\").Coordinate} coordinate Coordinate.\n * @param {number} stride Stride.\n * @return {number} offset Offset.\n */\nexport function deflateCoordinate(flatCoordinates, offset, coordinate, stride) {\n  for (let i = 0, ii = coordinate.length; i < ii; ++i) {\n    flatCoordinates[offset++] = coordinate[i];\n  }\n  return offset;\n}\n\n/**\n * @param {Array<number>} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {Array<import(\"../../coordinate.js\").Coordinate>} coordinates Coordinates.\n * @param {number} stride Stride.\n * @return {number} offset Offset.\n */\nexport function deflateCoordinates(\n  flatCoordinates,\n  offset,\n  coordinates,\n  stride,\n) {\n  for (let i = 0, ii = coordinates.length; i < ii; ++i) {\n    const coordinate = coordinates[i];\n    for (let j = 0; j < stride; ++j) {\n      flatCoordinates[offset++] = coordinate[j];\n    }\n  }\n  return offset;\n}\n\n/**\n * @param {Array<number>} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {Array<Array<import(\"../../coordinate.js\").Coordinate>>} coordinatess Coordinatess.\n * @param {number} stride Stride.\n * @param {Array<number>} [ends] Ends.\n * @return {Array<number>} Ends.\n */\nexport function deflateCoordinatesArray(\n  flatCoordinates,\n  offset,\n  coordinatess,\n  stride,\n  ends,\n) {\n  ends = ends ? ends : [];\n  let i = 0;\n  for (let j = 0, jj = coordinatess.length; j < jj; ++j) {\n    const end = deflateCoordinates(\n      flatCoordinates,\n      offset,\n      coordinatess[j],\n      stride,\n    );\n    ends[i++] = end;\n    offset = end;\n  }\n  ends.length = i;\n  return ends;\n}\n\n/**\n * @param {Array<number>} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {Array<Array<Array<import(\"../../coordinate.js\").Coordinate>>>} coordinatesss Coordinatesss.\n * @param {number} stride Stride.\n * @param {Array<Array<number>>} [endss] Endss.\n * @return {Array<Array<number>>} Endss.\n */\nexport function deflateMultiCoordinatesArray(\n  flatCoordinates,\n  offset,\n  coordinatesss,\n  stride,\n  endss,\n) {\n  endss = endss ? endss : [];\n  let i = 0;\n  for (let j = 0, jj = coordinatesss.length; j < jj; ++j) {\n    const ends = deflateCoordinatesArray(\n      flatCoordinates,\n      offset,\n      coordinatesss[j],\n      stride,\n      endss[i],\n    );\n    if (ends.length === 0) {\n      ends[0] = offset;\n    }\n    endss[i++] = ends;\n    offset = ends[ends.length - 1];\n  }\n  endss.length = i;\n  return endss;\n}\n", "/**\n * @module ol/geom/flat/inflate\n */\n\n/**\n * @param {Array<number>} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {number} end End.\n * @param {number} stride Stride.\n * @param {Array<import(\"../../coordinate.js\").Coordinate>} [coordinates] Coordinates.\n * @return {Array<import(\"../../coordinate.js\").Coordinate>} Coordinates.\n */\nexport function inflateCoordinates(\n  flatCoordinates,\n  offset,\n  end,\n  stride,\n  coordinates,\n) {\n  coordinates = coordinates !== undefined ? coordinates : [];\n  let i = 0;\n  for (let j = offset; j < end; j += stride) {\n    coordinates[i++] = flatCoordinates.slice(j, j + stride);\n  }\n  coordinates.length = i;\n  return coordinates;\n}\n\n/**\n * @param {Array<number>} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {Array<number>} ends Ends.\n * @param {number} stride Stride.\n * @param {Array<Array<import(\"../../coordinate.js\").Coordinate>>} [coordinatess] Coordinatess.\n * @return {Array<Array<import(\"../../coordinate.js\").Coordinate>>} Coordinatess.\n */\nexport function inflateCoordinatesArray(\n  flatCoordinates,\n  offset,\n  ends,\n  stride,\n  coordinatess,\n) {\n  coordinatess = coordinatess !== undefined ? coordinatess : [];\n  let i = 0;\n  for (let j = 0, jj = ends.length; j < jj; ++j) {\n    const end = ends[j];\n    coordinatess[i++] = inflateCoordinates(\n      flatCoordinates,\n      offset,\n      end,\n      stride,\n      coordinatess[i],\n    );\n    offset = end;\n  }\n  coordinatess.length = i;\n  return coordinatess;\n}\n\n/**\n * @param {Array<number>} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {Array<Array<number>>} endss Endss.\n * @param {number} stride Stride.\n * @param {Array<Array<Array<import(\"../../coordinate.js\").Coordinate>>>} [coordinatesss]\n *     Coordinatesss.\n * @return {Array<Array<Array<import(\"../../coordinate.js\").Coordinate>>>} Coordinatesss.\n */\nexport function inflateMultiCoordinatesArray(\n  flatCoordinates,\n  offset,\n  endss,\n  stride,\n  coordinatesss,\n) {\n  coordinatesss = coordinatesss !== undefined ? coordinatesss : [];\n  let i = 0;\n  for (let j = 0, jj = endss.length; j < jj; ++j) {\n    const ends = endss[j];\n    coordinatesss[i++] =\n      ends.length === 1 && ends[0] === offset\n        ? []\n        : inflateCoordinatesArray(\n            flatCoordinates,\n            offset,\n            ends,\n            stride,\n            coordinatesss[i],\n          );\n    offset = ends[ends.length - 1];\n  }\n  coordinatesss.length = i;\n  return coordinatesss;\n}\n", "/**\n * @module ol/geom/flat/simplify\n */\n// Based on simplify-js https://github.com/mourner/simplify-js\n// Copyright (c) 2012, Vladimir Agafonkin\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are met:\n//\n//    1. Redistributions of source code must retain the above copyright notice,\n//       this list of conditions and the following disclaimer.\n//\n//    2. Redistributions in binary form must reproduce the above copyright\n//       notice, this list of conditions and the following disclaimer in the\n//       documentation and/or other materials provided with the distribution.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n// POSSIBILITY OF SUCH DAMAGE.\n\nimport {squaredDistance, squaredSegmentDistance} from '../../math.js';\n\n/**\n * @param {Array<number>} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {number} end End.\n * @param {number} stride Stride.\n * @param {number} squaredTolerance Squared tolerance.\n * @param {boolean} highQuality Highest quality.\n * @param {Array<number>} [simplifiedFlatCoordinates] Simplified flat\n *     coordinates.\n * @return {Array<number>} Simplified line string.\n */\nexport function simplifyLineString(\n  flatCoordinates,\n  offset,\n  end,\n  stride,\n  squaredTolerance,\n  highQuality,\n  simplifiedFlatCoordinates,\n) {\n  simplifiedFlatCoordinates =\n    simplifiedFlatCoordinates !== undefined ? simplifiedFlatCoordinates : [];\n  if (!highQuality) {\n    end = radialDistance(\n      flatCoordinates,\n      offset,\n      end,\n      stride,\n      squaredTolerance,\n      simplifiedFlatCoordinates,\n      0,\n    );\n    flatCoordinates = simplifiedFlatCoordinates;\n    offset = 0;\n    stride = 2;\n  }\n  simplifiedFlatCoordinates.length = douglasPeucker(\n    flatCoordinates,\n    offset,\n    end,\n    stride,\n    squaredTolerance,\n    simplifiedFlatCoordinates,\n    0,\n  );\n  return simplifiedFlatCoordinates;\n}\n\n/**\n * @param {Array<number>} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {number} end End.\n * @param {number} stride Stride.\n * @param {number} squaredTolerance Squared tolerance.\n * @param {Array<number>} simplifiedFlatCoordinates Simplified flat\n *     coordinates.\n * @param {number} simplifiedOffset Simplified offset.\n * @return {number} Simplified offset.\n */\nexport function douglasPeucker(\n  flatCoordinates,\n  offset,\n  end,\n  stride,\n  squaredTolerance,\n  simplifiedFlatCoordinates,\n  simplifiedOffset,\n) {\n  const n = (end - offset) / stride;\n  if (n < 3) {\n    for (; offset < end; offset += stride) {\n      simplifiedFlatCoordinates[simplifiedOffset++] = flatCoordinates[offset];\n      simplifiedFlatCoordinates[simplifiedOffset++] =\n        flatCoordinates[offset + 1];\n    }\n    return simplifiedOffset;\n  }\n  /** @type {Array<number>} */\n  const markers = new Array(n);\n  markers[0] = 1;\n  markers[n - 1] = 1;\n  /** @type {Array<number>} */\n  const stack = [offset, end - stride];\n  let index = 0;\n  while (stack.length > 0) {\n    const last = stack.pop();\n    const first = stack.pop();\n    let maxSquaredDistance = 0;\n    const x1 = flatCoordinates[first];\n    const y1 = flatCoordinates[first + 1];\n    const x2 = flatCoordinates[last];\n    const y2 = flatCoordinates[last + 1];\n    for (let i = first + stride; i < last; i += stride) {\n      const x = flatCoordinates[i];\n      const y = flatCoordinates[i + 1];\n      const squaredDistance = squaredSegmentDistance(x, y, x1, y1, x2, y2);\n      if (squaredDistance > maxSquaredDistance) {\n        index = i;\n        maxSquaredDistance = squaredDistance;\n      }\n    }\n    if (maxSquaredDistance > squaredTolerance) {\n      markers[(index - offset) / stride] = 1;\n      if (first + stride < index) {\n        stack.push(first, index);\n      }\n      if (index + stride < last) {\n        stack.push(index, last);\n      }\n    }\n  }\n  for (let i = 0; i < n; ++i) {\n    if (markers[i]) {\n      simplifiedFlatCoordinates[simplifiedOffset++] =\n        flatCoordinates[offset + i * stride];\n      simplifiedFlatCoordinates[simplifiedOffset++] =\n        flatCoordinates[offset + i * stride + 1];\n    }\n  }\n  return simplifiedOffset;\n}\n\n/**\n * @param {Array<number>} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {Array<number>} ends Ends.\n * @param {number} stride Stride.\n * @param {number} squaredTolerance Squared tolerance.\n * @param {Array<number>} simplifiedFlatCoordinates Simplified flat\n *     coordinates.\n * @param {number} simplifiedOffset Simplified offset.\n * @param {Array<number>} simplifiedEnds Simplified ends.\n * @return {number} Simplified offset.\n */\nexport function douglasPeuckerArray(\n  flatCoordinates,\n  offset,\n  ends,\n  stride,\n  squaredTolerance,\n  simplifiedFlatCoordinates,\n  simplifiedOffset,\n  simplifiedEnds,\n) {\n  for (let i = 0, ii = ends.length; i < ii; ++i) {\n    const end = ends[i];\n    simplifiedOffset = douglasPeucker(\n      flatCoordinates,\n      offset,\n      end,\n      stride,\n      squaredTolerance,\n      simplifiedFlatCoordinates,\n      simplifiedOffset,\n    );\n    simplifiedEnds.push(simplifiedOffset);\n    offset = end;\n  }\n  return simplifiedOffset;\n}\n\n/**\n * @param {Array<number>} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {Array<Array<number>>} endss Endss.\n * @param {number} stride Stride.\n * @param {number} squaredTolerance Squared tolerance.\n * @param {Array<number>} simplifiedFlatCoordinates Simplified flat\n *     coordinates.\n * @param {number} simplifiedOffset Simplified offset.\n * @param {Array<Array<number>>} simplifiedEndss Simplified endss.\n * @return {number} Simplified offset.\n */\nexport function douglasPeuckerMultiArray(\n  flatCoordinates,\n  offset,\n  endss,\n  stride,\n  squaredTolerance,\n  simplifiedFlatCoordinates,\n  simplifiedOffset,\n  simplifiedEndss,\n) {\n  for (let i = 0, ii = endss.length; i < ii; ++i) {\n    const ends = endss[i];\n    /** @type {Array<number>} */\n    const simplifiedEnds = [];\n    simplifiedOffset = douglasPeuckerArray(\n      flatCoordinates,\n      offset,\n      ends,\n      stride,\n      squaredTolerance,\n      simplifiedFlatCoordinates,\n      simplifiedOffset,\n      simplifiedEnds,\n    );\n    simplifiedEndss.push(simplifiedEnds);\n    offset = ends[ends.length - 1];\n  }\n  return simplifiedOffset;\n}\n\n/**\n * @param {Array<number>} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {number} end End.\n * @param {number} stride Stride.\n * @param {number} squaredTolerance Squared tolerance.\n * @param {Array<number>} simplifiedFlatCoordinates Simplified flat\n *     coordinates.\n * @param {number} simplifiedOffset Simplified offset.\n * @return {number} Simplified offset.\n */\nexport function radialDistance(\n  flatCoordinates,\n  offset,\n  end,\n  stride,\n  squaredTolerance,\n  simplifiedFlatCoordinates,\n  simplifiedOffset,\n) {\n  if (end <= offset + stride) {\n    // zero or one point, no simplification possible, so copy and return\n    for (; offset < end; offset += stride) {\n      simplifiedFlatCoordinates[simplifiedOffset++] = flatCoordinates[offset];\n      simplifiedFlatCoordinates[simplifiedOffset++] =\n        flatCoordinates[offset + 1];\n    }\n    return simplifiedOffset;\n  }\n  let x1 = flatCoordinates[offset];\n  let y1 = flatCoordinates[offset + 1];\n  // copy first point\n  simplifiedFlatCoordinates[simplifiedOffset++] = x1;\n  simplifiedFlatCoordinates[simplifiedOffset++] = y1;\n  let x2 = x1;\n  let y2 = y1;\n  for (offset += stride; offset < end; offset += stride) {\n    x2 = flatCoordinates[offset];\n    y2 = flatCoordinates[offset + 1];\n    if (squaredDistance(x1, y1, x2, y2) > squaredTolerance) {\n      // copy point at offset\n      simplifiedFlatCoordinates[simplifiedOffset++] = x2;\n      simplifiedFlatCoordinates[simplifiedOffset++] = y2;\n      x1 = x2;\n      y1 = y2;\n    }\n  }\n  if (x2 != x1 || y2 != y1) {\n    // copy last point\n    simplifiedFlatCoordinates[simplifiedOffset++] = x2;\n    simplifiedFlatCoordinates[simplifiedOffset++] = y2;\n  }\n  return simplifiedOffset;\n}\n\n/**\n * @param {number} value Value.\n * @param {number} tolerance Tolerance.\n * @return {number} Rounded value.\n */\nexport function snap(value, tolerance) {\n  return tolerance * Math.round(value / tolerance);\n}\n\n/**\n * Simplifies a line string using an algorithm designed by Tim Schaub.\n * Coordinates are snapped to the nearest value in a virtual grid and\n * consecutive duplicate coordinates are discarded.  This effectively preserves\n * topology as the simplification of any subsection of a line string is\n * independent of the rest of the line string.  This means that, for examples,\n * the common edge between two polygons will be simplified to the same line\n * string independently in both polygons.  This implementation uses a single\n * pass over the coordinates and eliminates intermediate collinear points.\n * @param {Array<number>} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {number} end End.\n * @param {number} stride Stride.\n * @param {number} tolerance Tolerance.\n * @param {Array<number>} simplifiedFlatCoordinates Simplified flat\n *     coordinates.\n * @param {number} simplifiedOffset Simplified offset.\n * @return {number} Simplified offset.\n */\nexport function quantize(\n  flatCoordinates,\n  offset,\n  end,\n  stride,\n  tolerance,\n  simplifiedFlatCoordinates,\n  simplifiedOffset,\n) {\n  // do nothing if the line is empty\n  if (offset == end) {\n    return simplifiedOffset;\n  }\n  // snap the first coordinate (P1)\n  let x1 = snap(flatCoordinates[offset], tolerance);\n  let y1 = snap(flatCoordinates[offset + 1], tolerance);\n  offset += stride;\n  // add the first coordinate to the output\n  simplifiedFlatCoordinates[simplifiedOffset++] = x1;\n  simplifiedFlatCoordinates[simplifiedOffset++] = y1;\n  // find the next coordinate that does not snap to the same value as the first\n  // coordinate (P2)\n  let x2, y2;\n  do {\n    x2 = snap(flatCoordinates[offset], tolerance);\n    y2 = snap(flatCoordinates[offset + 1], tolerance);\n    offset += stride;\n    if (offset == end) {\n      // all coordinates snap to the same value, the line collapses to a point\n      // push the last snapped value anyway to ensure that the output contains\n      // at least two points\n      // FIXME should we really return at least two points anyway?\n      simplifiedFlatCoordinates[simplifiedOffset++] = x2;\n      simplifiedFlatCoordinates[simplifiedOffset++] = y2;\n      return simplifiedOffset;\n    }\n  } while (x2 == x1 && y2 == y1);\n  while (offset < end) {\n    // snap the next coordinate (P3)\n    const x3 = snap(flatCoordinates[offset], tolerance);\n    const y3 = snap(flatCoordinates[offset + 1], tolerance);\n    offset += stride;\n    // skip P3 if it is equal to P2\n    if (x3 == x2 && y3 == y2) {\n      continue;\n    }\n    // calculate the delta between P1 and P2\n    const dx1 = x2 - x1;\n    const dy1 = y2 - y1;\n    // calculate the delta between P3 and P1\n    const dx2 = x3 - x1;\n    const dy2 = y3 - y1;\n    // if P1, P2, and P3 are colinear and P3 is further from P1 than P2 is from\n    // P1 in the same direction then P2 is on the straight line between P1 and\n    // P3\n    if (\n      dx1 * dy2 == dy1 * dx2 &&\n      ((dx1 < 0 && dx2 < dx1) || dx1 == dx2 || (dx1 > 0 && dx2 > dx1)) &&\n      ((dy1 < 0 && dy2 < dy1) || dy1 == dy2 || (dy1 > 0 && dy2 > dy1))\n    ) {\n      // discard P2 and set P2 = P3\n      x2 = x3;\n      y2 = y3;\n      continue;\n    }\n    // either P1, P2, and P3 are not colinear, or they are colinear but P3 is\n    // between P3 and P1 or on the opposite half of the line to P2.  add P2,\n    // and continue with P1 = P2 and P2 = P3\n    simplifiedFlatCoordinates[simplifiedOffset++] = x2;\n    simplifiedFlatCoordinates[simplifiedOffset++] = y2;\n    x1 = x2;\n    y1 = y2;\n    x2 = x3;\n    y2 = y3;\n  }\n  // add the last point (P2)\n  simplifiedFlatCoordinates[simplifiedOffset++] = x2;\n  simplifiedFlatCoordinates[simplifiedOffset++] = y2;\n  return simplifiedOffset;\n}\n\n/**\n * @param {Array<number>} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {Array<number>} ends Ends.\n * @param {number} stride Stride.\n * @param {number} tolerance Tolerance.\n * @param {Array<number>} simplifiedFlatCoordinates Simplified flat\n *     coordinates.\n * @param {number} simplifiedOffset Simplified offset.\n * @param {Array<number>} simplifiedEnds Simplified ends.\n * @return {number} Simplified offset.\n */\nexport function quantizeArray(\n  flatCoordinates,\n  offset,\n  ends,\n  stride,\n  tolerance,\n  simplifiedFlatCoordinates,\n  simplifiedOffset,\n  simplifiedEnds,\n) {\n  for (let i = 0, ii = ends.length; i < ii; ++i) {\n    const end = ends[i];\n    simplifiedOffset = quantize(\n      flatCoordinates,\n      offset,\n      end,\n      stride,\n      tolerance,\n      simplifiedFlatCoordinates,\n      simplifiedOffset,\n    );\n    simplifiedEnds.push(simplifiedOffset);\n    offset = end;\n  }\n  return simplifiedOffset;\n}\n\n/**\n * @param {Array<number>} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {Array<Array<number>>} endss Endss.\n * @param {number} stride Stride.\n * @param {number} tolerance Tolerance.\n * @param {Array<number>} simplifiedFlatCoordinates Simplified flat\n *     coordinates.\n * @param {number} simplifiedOffset Simplified offset.\n * @param {Array<Array<number>>} simplifiedEndss Simplified endss.\n * @return {number} Simplified offset.\n */\nexport function quantizeMultiArray(\n  flatCoordinates,\n  offset,\n  endss,\n  stride,\n  tolerance,\n  simplifiedFlatCoordinates,\n  simplifiedOffset,\n  simplifiedEndss,\n) {\n  for (let i = 0, ii = endss.length; i < ii; ++i) {\n    const ends = endss[i];\n    /** @type {Array<number>} */\n    const simplifiedEnds = [];\n    simplifiedOffset = quantizeArray(\n      flatCoordinates,\n      offset,\n      ends,\n      stride,\n      tolerance,\n      simplifiedFlatCoordinates,\n      simplifiedOffset,\n      simplifiedEnds,\n    );\n    simplifiedEndss.push(simplifiedEnds);\n    offset = ends[ends.length - 1];\n  }\n  return simplifiedOffset;\n}\n", "/**\n * @module ol/geom/LinearRing\n */\nimport {closestSquaredDistanceXY} from '../extent.js';\nimport SimpleGeometry from './SimpleGeometry.js';\nimport {linearRing as linearRingArea} from './flat/area.js';\nimport {assignClosestPoint, maxSquaredDelta} from './flat/closest.js';\nimport {deflateCoordinates} from './flat/deflate.js';\nimport {inflateCoordinates} from './flat/inflate.js';\nimport {douglasPeucker} from './flat/simplify.js';\n\n/**\n * @classdesc\n * Linear ring geometry. Only used as part of polygon; cannot be rendered\n * on its own.\n *\n * @api\n */\nclass LinearRing extends SimpleGeometry {\n  /**\n   * @param {Array<import(\"../coordinate.js\").Coordinate>|Array<number>} coordinates Coordinates.\n   *     For internal use, flat coordinates in combination with `layout` are also accepted.\n   * @param {import(\"./Geometry.js\").GeometryLayout} [layout] Layout.\n   */\n  constructor(coordinates, layout) {\n    super();\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.maxDelta_ = -1;\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.maxDeltaRevision_ = -1;\n\n    if (layout !== undefined && !Array.isArray(coordinates[0])) {\n      this.setFlatCoordinates(\n        layout,\n        /** @type {Array<number>} */ (coordinates),\n      );\n    } else {\n      this.setCoordinates(\n        /** @type {Array<import(\"../coordinate.js\").Coordinate>} */ (\n          coordinates\n        ),\n        layout,\n      );\n    }\n  }\n\n  /**\n   * Make a complete copy of the geometry.\n   * @return {!LinearRing} Clone.\n   * @api\n   * @override\n   */\n  clone() {\n    return new LinearRing(this.flatCoordinates.slice(), this.layout);\n  }\n\n  /**\n   * @param {number} x X.\n   * @param {number} y Y.\n   * @param {import(\"../coordinate.js\").Coordinate} closestPoint Closest point.\n   * @param {number} minSquaredDistance Minimum squared distance.\n   * @return {number} Minimum squared distance.\n   * @override\n   */\n  closestPointXY(x, y, closestPoint, minSquaredDistance) {\n    if (minSquaredDistance < closestSquaredDistanceXY(this.getExtent(), x, y)) {\n      return minSquaredDistance;\n    }\n    if (this.maxDeltaRevision_ != this.getRevision()) {\n      this.maxDelta_ = Math.sqrt(\n        maxSquaredDelta(\n          this.flatCoordinates,\n          0,\n          this.flatCoordinates.length,\n          this.stride,\n          0,\n        ),\n      );\n      this.maxDeltaRevision_ = this.getRevision();\n    }\n    return assignClosestPoint(\n      this.flatCoordinates,\n      0,\n      this.flatCoordinates.length,\n      this.stride,\n      this.maxDelta_,\n      true,\n      x,\n      y,\n      closestPoint,\n      minSquaredDistance,\n    );\n  }\n\n  /**\n   * Return the area of the linear ring on projected plane.\n   * @return {number} Area (on projected plane).\n   * @api\n   */\n  getArea() {\n    return linearRingArea(\n      this.flatCoordinates,\n      0,\n      this.flatCoordinates.length,\n      this.stride,\n    );\n  }\n\n  /**\n   * Return the coordinates of the linear ring.\n   * @return {Array<import(\"../coordinate.js\").Coordinate>} Coordinates.\n   * @api\n   * @override\n   */\n  getCoordinates() {\n    return inflateCoordinates(\n      this.flatCoordinates,\n      0,\n      this.flatCoordinates.length,\n      this.stride,\n    );\n  }\n\n  /**\n   * @param {number} squaredTolerance Squared tolerance.\n   * @return {LinearRing} Simplified LinearRing.\n   * @protected\n   * @override\n   */\n  getSimplifiedGeometryInternal(squaredTolerance) {\n    /** @type {Array<number>} */\n    const simplifiedFlatCoordinates = [];\n    simplifiedFlatCoordinates.length = douglasPeucker(\n      this.flatCoordinates,\n      0,\n      this.flatCoordinates.length,\n      this.stride,\n      squaredTolerance,\n      simplifiedFlatCoordinates,\n      0,\n    );\n    return new LinearRing(simplifiedFlatCoordinates, 'XY');\n  }\n\n  /**\n   * Get the type of this geometry.\n   * @return {import(\"./Geometry.js\").Type} Geometry type.\n   * @api\n   * @override\n   */\n  getType() {\n    return 'LinearRing';\n  }\n\n  /**\n   * Test if the geometry and the passed extent intersect.\n   * @param {import(\"../extent.js\").Extent} extent Extent.\n   * @return {boolean} `true` if the geometry and the extent intersect.\n   * @api\n   * @override\n   */\n  intersectsExtent(extent) {\n    return false;\n  }\n\n  /**\n   * Set the coordinates of the linear ring.\n   * @param {!Array<import(\"../coordinate.js\").Coordinate>} coordinates Coordinates.\n   * @param {import(\"./Geometry.js\").GeometryLayout} [layout] Layout.\n   * @api\n   * @override\n   */\n  setCoordinates(coordinates, layout) {\n    this.setLayout(layout, coordinates, 1);\n    if (!this.flatCoordinates) {\n      this.flatCoordinates = [];\n    }\n    this.flatCoordinates.length = deflateCoordinates(\n      this.flatCoordinates,\n      0,\n      coordinates,\n      this.stride,\n    );\n    this.changed();\n  }\n}\n\nexport default LinearRing;\n", "/**\n * @module ol/geom/Point\n */\nimport {containsXY, createOrUpdateFromCoordinate} from '../extent.js';\nimport {squaredDistance as squaredDx} from '../math.js';\nimport SimpleGeometry from './SimpleGeometry.js';\nimport {deflateCoordinate} from './flat/deflate.js';\n\n/**\n * @classdesc\n * Point geometry.\n *\n * @api\n */\nclass Point extends SimpleGeometry {\n  /**\n   * @param {import(\"../coordinate.js\").Coordinate} coordinates Coordinates.\n   * @param {import(\"./Geometry.js\").GeometryLayout} [layout] Layout.\n   */\n  constructor(coordinates, layout) {\n    super();\n    this.setCoordinates(coordinates, layout);\n  }\n\n  /**\n   * Make a complete copy of the geometry.\n   * @return {!Point} Clone.\n   * @api\n   * @override\n   */\n  clone() {\n    const point = new Point(this.flatCoordinates.slice(), this.layout);\n    point.applyProperties(this);\n    return point;\n  }\n\n  /**\n   * @param {number} x X.\n   * @param {number} y Y.\n   * @param {import(\"../coordinate.js\").Coordinate} closestPoint Closest point.\n   * @param {number} minSquaredDistance Minimum squared distance.\n   * @return {number} Minimum squared distance.\n   * @override\n   */\n  closestPointXY(x, y, closestPoint, minSquaredDistance) {\n    const flatCoordinates = this.flatCoordinates;\n    const squaredDistance = squaredDx(\n      x,\n      y,\n      flatCoordinates[0],\n      flatCoordinates[1],\n    );\n    if (squaredDistance < minSquaredDistance) {\n      const stride = this.stride;\n      for (let i = 0; i < stride; ++i) {\n        closestPoint[i] = flatCoordinates[i];\n      }\n      closestPoint.length = stride;\n      return squaredDistance;\n    }\n    return minSquaredDistance;\n  }\n\n  /**\n   * Return the coordinate of the point.\n   * @return {import(\"../coordinate.js\").Coordinate} Coordinates.\n   * @api\n   * @override\n   */\n  getCoordinates() {\n    return this.flatCoordinates.slice();\n  }\n\n  /**\n   * @param {import(\"../extent.js\").Extent} extent Extent.\n   * @protected\n   * @return {import(\"../extent.js\").Extent} extent Extent.\n   * @override\n   */\n  computeExtent(extent) {\n    return createOrUpdateFromCoordinate(this.flatCoordinates, extent);\n  }\n\n  /**\n   * Get the type of this geometry.\n   * @return {import(\"./Geometry.js\").Type} Geometry type.\n   * @api\n   * @override\n   */\n  getType() {\n    return 'Point';\n  }\n\n  /**\n   * Test if the geometry and the passed extent intersect.\n   * @param {import(\"../extent.js\").Extent} extent Extent.\n   * @return {boolean} `true` if the geometry and the extent intersect.\n   * @api\n   * @override\n   */\n  intersectsExtent(extent) {\n    return containsXY(extent, this.flatCoordinates[0], this.flatCoordinates[1]);\n  }\n\n  /**\n   * @param {!Array<*>} coordinates Coordinates.\n   * @param {import(\"./Geometry.js\").GeometryLayout} [layout] Layout.\n   * @api\n   * @override\n   */\n  setCoordinates(coordinates, layout) {\n    this.setLayout(layout, coordinates, 0);\n    if (!this.flatCoordinates) {\n      this.flatCoordinates = [];\n    }\n    this.flatCoordinates.length = deflateCoordinate(\n      this.flatCoordinates,\n      0,\n      coordinates,\n      this.stride,\n    );\n    this.changed();\n  }\n}\n\nexport default Point;\n", "/**\n * @module ol/geom/flat/contains\n */\nimport {forEachCorner} from '../../extent.js';\n\n/**\n * @param {Array<number>} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {number} end End.\n * @param {number} stride Stride.\n * @param {import(\"../../extent.js\").Extent} extent Extent.\n * @return {boolean} Contains extent.\n */\nexport function linearRingContainsExtent(\n  flatCoordinates,\n  offset,\n  end,\n  stride,\n  extent,\n) {\n  const outside = forEachCorner(\n    extent,\n    /**\n     * @param {import(\"../../coordinate.js\").Coordinate} coordinate Coordinate.\n     * @return {boolean} Contains (x, y).\n     */\n    function (coordinate) {\n      return !linearRingContainsXY(\n        flatCoordinates,\n        offset,\n        end,\n        stride,\n        coordinate[0],\n        coordinate[1],\n      );\n    },\n  );\n  return !outside;\n}\n\n/**\n * @param {Array<number>} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {number} end End.\n * @param {number} stride Stride.\n * @param {number} x X.\n * @param {number} y Y.\n * @return {boolean} Contains (x, y).\n */\nexport function linearRingContainsXY(\n  flatCoordinates,\n  offset,\n  end,\n  stride,\n  x,\n  y,\n) {\n  // https://web.archive.org/web/20210504233957/http://geomalgorithms.com/a03-_inclusion.html\n  // Copyright 2000 softSurfer, 2012 Dan Sunday\n  // This code may be freely used and modified for any purpose\n  // providing that this copyright notice is included with it.\n  // SoftSurfer makes no warranty for this code, and cannot be held\n  // liable for any real or imagined damage resulting from its use.\n  // Users of this code must verify correctness for their application.\n  let wn = 0;\n  let x1 = flatCoordinates[end - stride];\n  let y1 = flatCoordinates[end - stride + 1];\n  for (; offset < end; offset += stride) {\n    const x2 = flatCoordinates[offset];\n    const y2 = flatCoordinates[offset + 1];\n    if (y1 <= y) {\n      if (y2 > y && (x2 - x1) * (y - y1) - (x - x1) * (y2 - y1) > 0) {\n        wn++;\n      }\n    } else if (y2 <= y && (x2 - x1) * (y - y1) - (x - x1) * (y2 - y1) < 0) {\n      wn--;\n    }\n    x1 = x2;\n    y1 = y2;\n  }\n  return wn !== 0;\n}\n\n/**\n * @param {Array<number>} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {Array<number>} ends Ends.\n * @param {number} stride Stride.\n * @param {number} x X.\n * @param {number} y Y.\n * @return {boolean} Contains (x, y).\n */\nexport function linearRingsContainsXY(\n  flatCoordinates,\n  offset,\n  ends,\n  stride,\n  x,\n  y,\n) {\n  if (ends.length === 0) {\n    return false;\n  }\n  if (!linearRingContainsXY(flatCoordinates, offset, ends[0], stride, x, y)) {\n    return false;\n  }\n  for (let i = 1, ii = ends.length; i < ii; ++i) {\n    if (\n      linearRingContainsXY(flatCoordinates, ends[i - 1], ends[i], stride, x, y)\n    ) {\n      return false;\n    }\n  }\n  return true;\n}\n\n/**\n * @param {Array<number>} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {Array<Array<number>>} endss Endss.\n * @param {number} stride Stride.\n * @param {number} x X.\n * @param {number} y Y.\n * @return {boolean} Contains (x, y).\n */\nexport function linearRingssContainsXY(\n  flatCoordinates,\n  offset,\n  endss,\n  stride,\n  x,\n  y,\n) {\n  if (endss.length === 0) {\n    return false;\n  }\n  for (let i = 0, ii = endss.length; i < ii; ++i) {\n    const ends = endss[i];\n    if (linearRingsContainsXY(flatCoordinates, offset, ends, stride, x, y)) {\n      return true;\n    }\n    offset = ends[ends.length - 1];\n  }\n  return false;\n}\n", "/**\n * @module ol/geom/flat/interiorpoint\n */\nimport {ascending} from '../../array.js';\nimport {linearRingsContainsXY} from './contains.js';\n\n/**\n * Calculates a point that is likely to lie in the interior of the linear rings.\n * Inspired by JTS's com.vividsolutions.jts.geom.Geometry#getInteriorPoint.\n * @param {Array<number>} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {Array<number>} ends Ends.\n * @param {number} stride Stride.\n * @param {Array<number>} flatCenters Flat centers.\n * @param {number} flatCentersOffset Flat center offset.\n * @param {Array<number>} [dest] Destination.\n * @return {Array<number>} Destination point as XYM coordinate, where M is the\n * length of the horizontal intersection that the point belongs to.\n */\nexport function getInteriorPointOfArray(\n  flatCoordinates,\n  offset,\n  ends,\n  stride,\n  flatCenters,\n  flatCentersOffset,\n  dest,\n) {\n  let i, ii, x, x1, x2, y1, y2;\n  const y = flatCenters[flatCentersOffset + 1];\n  /** @type {Array<number>} */\n  const intersections = [];\n  // Calculate intersections with the horizontal line\n  for (let r = 0, rr = ends.length; r < rr; ++r) {\n    const end = ends[r];\n    x1 = flatCoordinates[end - stride];\n    y1 = flatCoordinates[end - stride + 1];\n    for (i = offset; i < end; i += stride) {\n      x2 = flatCoordinates[i];\n      y2 = flatCoordinates[i + 1];\n      if ((y <= y1 && y2 <= y) || (y1 <= y && y <= y2)) {\n        x = ((y - y1) / (y2 - y1)) * (x2 - x1) + x1;\n        intersections.push(x);\n      }\n      x1 = x2;\n      y1 = y2;\n    }\n  }\n  // Find the longest segment of the horizontal line that has its center point\n  // inside the linear ring.\n  let pointX = NaN;\n  let maxSegmentLength = -Infinity;\n  intersections.sort(ascending);\n  x1 = intersections[0];\n  for (i = 1, ii = intersections.length; i < ii; ++i) {\n    x2 = intersections[i];\n    const segmentLength = Math.abs(x2 - x1);\n    if (segmentLength > maxSegmentLength) {\n      x = (x1 + x2) / 2;\n      if (linearRingsContainsXY(flatCoordinates, offset, ends, stride, x, y)) {\n        pointX = x;\n        maxSegmentLength = segmentLength;\n      }\n    }\n    x1 = x2;\n  }\n  if (isNaN(pointX)) {\n    // There is no horizontal line that has its center point inside the linear\n    // ring.  Use the center of the the linear ring's extent.\n    pointX = flatCenters[flatCentersOffset];\n  }\n  if (dest) {\n    dest.push(pointX, y, maxSegmentLength);\n    return dest;\n  }\n  return [pointX, y, maxSegmentLength];\n}\n\n/**\n * @param {Array<number>} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {Array<Array<number>>} endss Endss.\n * @param {number} stride Stride.\n * @param {Array<number>} flatCenters Flat centers.\n * @return {Array<number>} Interior points as XYM coordinates, where M is the\n * length of the horizontal intersection that the point belongs to.\n */\nexport function getInteriorPointsOfMultiArray(\n  flatCoordinates,\n  offset,\n  endss,\n  stride,\n  flatCenters,\n) {\n  /** @type {Array<number>} */\n  let interiorPoints = [];\n  for (let i = 0, ii = endss.length; i < ii; ++i) {\n    const ends = endss[i];\n    interiorPoints = getInteriorPointOfArray(\n      flatCoordinates,\n      offset,\n      ends,\n      stride,\n      flatCenters,\n      2 * i,\n      interiorPoints,\n    );\n    offset = ends[ends.length - 1];\n  }\n  return interiorPoints;\n}\n", "/**\n * @module ol/geom/flat/segments\n */\n\n/**\n * This function calls `callback` for each segment of the flat coordinates\n * array. If the callback returns a truthy value the function returns that\n * value immediately. Otherwise the function returns `false`.\n * @param {Array<number>} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {number} end End.\n * @param {number} stride Stride.\n * @param {function(import(\"../../coordinate.js\").Coordinate, import(\"../../coordinate.js\").Coordinate): T} callback Function\n *     called for each segment.\n * @return {T|boolean} Value.\n * @template T\n */\nexport function forEach(flatCoordinates, offset, end, stride, callback) {\n  let ret;\n  offset += stride;\n  for (; offset < end; offset += stride) {\n    ret = callback(\n      flatCoordinates.slice(offset - stride, offset),\n      flatCoordinates.slice(offset, offset + stride),\n    );\n    if (ret) {\n      return ret;\n    }\n  }\n  return false;\n}\n\n/**\n * Calculate the intersection point of two line segments.\n * Reference: https://stackoverflow.com/a/72474223/2389327\n * @param {Array<import(\"../../coordinate.js\").Coordinate>} segment1 The first line segment as an array of two points.\n * @param {Array<import(\"../../coordinate.js\").Coordinate>} segment2 The second line segment as an array of two points.\n * @return {import(\"../../coordinate.js\").Coordinate|undefined} The intersection point or `undefined` if no intersection.\n */\nexport function getIntersectionPoint(segment1, segment2) {\n  const [a, b] = segment1;\n  const [c, d] = segment2;\n  const t =\n    ((a[0] - c[0]) * (c[1] - d[1]) - (a[1] - c[1]) * (c[0] - d[0])) /\n    ((a[0] - b[0]) * (c[1] - d[1]) - (a[1] - b[1]) * (c[0] - d[0]));\n  const u =\n    ((a[0] - c[0]) * (a[1] - b[1]) - (a[1] - c[1]) * (a[0] - b[0])) /\n    ((a[0] - b[0]) * (c[1] - d[1]) - (a[1] - b[1]) * (c[0] - d[0]));\n\n  // Check if lines actually intersect\n  if (0 <= t && t <= 1 && 0 <= u && u <= 1) {\n    return [a[0] + t * (b[0] - a[0]), a[1] + t * (b[1] - a[1])];\n  }\n  return undefined;\n}\n", "/**\n * @module ol/geom/flat/intersectsextent\n */\nimport {\n  createEmpty,\n  extendFlatCoordinates,\n  intersects,\n  intersectsSegment,\n} from '../../extent.js';\nimport {linearRingContainsExtent, linearRingContainsXY} from './contains.js';\nimport {forEach as forEachSegment} from './segments.js';\n\n/**\n * @param {Array<number>} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {number} end End.\n * @param {number} stride Stride.\n * @param {import(\"../../extent.js\").Extent} extent Extent.\n * @param {import('../../extent.js').Extent} [coordinatesExtent] Coordinates extent\n * @return {boolean} True if the geometry and the extent intersect.\n */\nexport function intersectsLineString(\n  flatCoordinates,\n  offset,\n  end,\n  stride,\n  extent,\n  coordinatesExtent,\n) {\n  coordinatesExtent =\n    coordinatesExtent ??\n    extendFlatCoordinates(createEmpty(), flatCoordinates, offset, end, stride);\n  if (!intersects(extent, coordinatesExtent)) {\n    return false;\n  }\n  if (\n    (coordinatesExtent[0] >= extent[0] && coordinatesExtent[2] <= extent[2]) ||\n    (coordinatesExtent[1] >= extent[1] && coordinatesExtent[3] <= extent[3])\n  ) {\n    return true;\n  }\n  return forEachSegment(\n    flatCoordinates,\n    offset,\n    end,\n    stride,\n    /**\n     * @param {import(\"../../coordinate.js\").Coordinate} point1 Start point.\n     * @param {import(\"../../coordinate.js\").Coordinate} point2 End point.\n     * @return {boolean} `true` if the segment and the extent intersect,\n     *     `false` otherwise.\n     */\n    function (point1, point2) {\n      return intersectsSegment(extent, point1, point2);\n    },\n  );\n}\n\n/**\n * @param {Array<number>} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {Array<number>} ends Ends.\n * @param {number} stride Stride.\n * @param {import(\"../../extent.js\").Extent} extent Extent.\n * @return {boolean} True if the geometry and the extent intersect.\n */\nexport function intersectsLineStringArray(\n  flatCoordinates,\n  offset,\n  ends,\n  stride,\n  extent,\n) {\n  for (let i = 0, ii = ends.length; i < ii; ++i) {\n    if (\n      intersectsLineString(flatCoordinates, offset, ends[i], stride, extent)\n    ) {\n      return true;\n    }\n    offset = ends[i];\n  }\n  return false;\n}\n\n/**\n * @param {Array<number>} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {number} end End.\n * @param {number} stride Stride.\n * @param {import(\"../../extent.js\").Extent} extent Extent.\n * @return {boolean} True if the geometry and the extent intersect.\n */\nexport function intersectsLinearRing(\n  flatCoordinates,\n  offset,\n  end,\n  stride,\n  extent,\n) {\n  if (intersectsLineString(flatCoordinates, offset, end, stride, extent)) {\n    return true;\n  }\n  if (\n    linearRingContainsXY(\n      flatCoordinates,\n      offset,\n      end,\n      stride,\n      extent[0],\n      extent[1],\n    )\n  ) {\n    return true;\n  }\n  if (\n    linearRingContainsXY(\n      flatCoordinates,\n      offset,\n      end,\n      stride,\n      extent[0],\n      extent[3],\n    )\n  ) {\n    return true;\n  }\n  if (\n    linearRingContainsXY(\n      flatCoordinates,\n      offset,\n      end,\n      stride,\n      extent[2],\n      extent[1],\n    )\n  ) {\n    return true;\n  }\n  if (\n    linearRingContainsXY(\n      flatCoordinates,\n      offset,\n      end,\n      stride,\n      extent[2],\n      extent[3],\n    )\n  ) {\n    return true;\n  }\n  return false;\n}\n\n/**\n * @param {Array<number>} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {Array<number>} ends Ends.\n * @param {number} stride Stride.\n * @param {import(\"../../extent.js\").Extent} extent Extent.\n * @return {boolean} True if the geometry and the extent intersect.\n */\nexport function intersectsLinearRingArray(\n  flatCoordinates,\n  offset,\n  ends,\n  stride,\n  extent,\n) {\n  if (!intersectsLinearRing(flatCoordinates, offset, ends[0], stride, extent)) {\n    return false;\n  }\n  if (ends.length === 1) {\n    return true;\n  }\n  for (let i = 1, ii = ends.length; i < ii; ++i) {\n    if (\n      linearRingContainsExtent(\n        flatCoordinates,\n        ends[i - 1],\n        ends[i],\n        stride,\n        extent,\n      )\n    ) {\n      if (\n        !intersectsLineString(\n          flatCoordinates,\n          ends[i - 1],\n          ends[i],\n          stride,\n          extent,\n        )\n      ) {\n        return false;\n      }\n    }\n  }\n  return true;\n}\n\n/**\n * @param {Array<number>} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {Array<Array<number>>} endss Endss.\n * @param {number} stride Stride.\n * @param {import(\"../../extent.js\").Extent} extent Extent.\n * @return {boolean} True if the geometry and the extent intersect.\n */\nexport function intersectsLinearRingMultiArray(\n  flatCoordinates,\n  offset,\n  endss,\n  stride,\n  extent,\n) {\n  for (let i = 0, ii = endss.length; i < ii; ++i) {\n    const ends = endss[i];\n    if (\n      intersectsLinearRingArray(flatCoordinates, offset, ends, stride, extent)\n    ) {\n      return true;\n    }\n    offset = ends[ends.length - 1];\n  }\n  return false;\n}\n", "/**\n * @module ol/geom/flat/reverse\n */\n\n/**\n * @param {Array<number>} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {number} end End.\n * @param {number} stride Stride.\n */\nexport function coordinates(flatCoordinates, offset, end, stride) {\n  while (offset < end - stride) {\n    for (let i = 0; i < stride; ++i) {\n      const tmp = flatCoordinates[offset + i];\n      flatCoordinates[offset + i] = flatCoordinates[end - stride + i];\n      flatCoordinates[end - stride + i] = tmp;\n    }\n    offset += stride;\n    end -= stride;\n  }\n}\n", "/**\n * @module ol/geom/flat/orient\n */\nimport {coordinates as reverseCoordinates} from './reverse.js';\n\n/**\n * Is the linear ring oriented clockwise in a coordinate system with a bottom-left\n * coordinate origin? For a coordinate system with a top-left coordinate origin,\n * the ring's orientation is clockwise when this function returns false.\n * @param {Array<number>} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {number} end End.\n * @param {number} stride Stride.\n * @return {boolean|undefined} Is clockwise.\n */\nexport function linearRingIsClockwise(flatCoordinates, offset, end, stride) {\n  // https://stackoverflow.com/q/1165647/clockwise-method#1165943\n  // https://github.com/OSGeo/gdal/blob/master/gdal/ogr/ogrlinearring.cpp\n  let edge = 0;\n  let x1 = flatCoordinates[end - stride];\n  let y1 = flatCoordinates[end - stride + 1];\n  for (; offset < end; offset += stride) {\n    const x2 = flatCoordinates[offset];\n    const y2 = flatCoordinates[offset + 1];\n    edge += (x2 - x1) * (y2 + y1);\n    x1 = x2;\n    y1 = y2;\n  }\n  return edge === 0 ? undefined : edge > 0;\n}\n\n/**\n * Determines if linear rings are oriented.  By default, left-hand orientation\n * is tested (first ring must be clockwise, remaining rings counter-clockwise).\n * To test for right-hand orientation, use the `right` argument.\n *\n * @param {Array<number>} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {Array<number>} ends Array of end indexes.\n * @param {number} stride Stride.\n * @param {boolean} [right] Test for right-hand orientation\n *     (counter-clockwise exterior ring and clockwise interior rings).\n * @return {boolean} Rings are correctly oriented.\n */\nexport function linearRingsAreOriented(\n  flatCoordinates,\n  offset,\n  ends,\n  stride,\n  right,\n) {\n  right = right !== undefined ? right : false;\n  for (let i = 0, ii = ends.length; i < ii; ++i) {\n    const end = ends[i];\n    const isClockwise = linearRingIsClockwise(\n      flatCoordinates,\n      offset,\n      end,\n      stride,\n    );\n    if (i === 0) {\n      if ((right && isClockwise) || (!right && !isClockwise)) {\n        return false;\n      }\n    } else {\n      if ((right && !isClockwise) || (!right && isClockwise)) {\n        return false;\n      }\n    }\n    offset = end;\n  }\n  return true;\n}\n\n/**\n * Determines if linear rings are oriented.  By default, left-hand orientation\n * is tested (first ring must be clockwise, remaining rings counter-clockwise).\n * To test for right-hand orientation, use the `right` argument.\n *\n * @param {Array<number>} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {Array<Array<number>>} endss Array of array of end indexes.\n * @param {number} stride Stride.\n * @param {boolean} [right] Test for right-hand orientation\n *     (counter-clockwise exterior ring and clockwise interior rings).\n * @return {boolean} Rings are correctly oriented.\n */\nexport function linearRingssAreOriented(\n  flatCoordinates,\n  offset,\n  endss,\n  stride,\n  right,\n) {\n  for (let i = 0, ii = endss.length; i < ii; ++i) {\n    const ends = endss[i];\n    if (!linearRingsAreOriented(flatCoordinates, offset, ends, stride, right)) {\n      return false;\n    }\n    if (ends.length) {\n      offset = ends[ends.length - 1];\n    }\n  }\n  return true;\n}\n\n/**\n * Orient coordinates in a flat array of linear rings.  By default, rings\n * are oriented following the left-hand rule (clockwise for exterior and\n * counter-clockwise for interior rings).  To orient according to the\n * right-hand rule, use the `right` argument.\n *\n * @param {Array<number>} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {Array<number>} ends Ends.\n * @param {number} stride Stride.\n * @param {boolean} [right] Follow the right-hand rule for orientation.\n * @return {number} End.\n */\nexport function orientLinearRings(\n  flatCoordinates,\n  offset,\n  ends,\n  stride,\n  right,\n) {\n  right = right !== undefined ? right : false;\n  for (let i = 0, ii = ends.length; i < ii; ++i) {\n    const end = ends[i];\n    const isClockwise = linearRingIsClockwise(\n      flatCoordinates,\n      offset,\n      end,\n      stride,\n    );\n    const reverse =\n      i === 0\n        ? (right && isClockwise) || (!right && !isClockwise)\n        : (right && !isClockwise) || (!right && isClockwise);\n    if (reverse) {\n      reverseCoordinates(flatCoordinates, offset, end, stride);\n    }\n    offset = end;\n  }\n  return offset;\n}\n\n/**\n * Orient coordinates in a flat array of linear rings.  By default, rings\n * are oriented following the left-hand rule (clockwise for exterior and\n * counter-clockwise for interior rings).  To orient according to the\n * right-hand rule, use the `right` argument.\n *\n * @param {Array<number>} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {Array<Array<number>>} endss Array of array of end indexes.\n * @param {number} stride Stride.\n * @param {boolean} [right] Follow the right-hand rule for orientation.\n * @return {number} End.\n */\nexport function orientLinearRingsArray(\n  flatCoordinates,\n  offset,\n  endss,\n  stride,\n  right,\n) {\n  for (let i = 0, ii = endss.length; i < ii; ++i) {\n    offset = orientLinearRings(\n      flatCoordinates,\n      offset,\n      endss[i],\n      stride,\n      right,\n    );\n  }\n  return offset;\n}\n\n/**\n * Return a two-dimensional endss\n * @param {Array<number>} flatCoordinates Flat coordinates\n * @param {Array<number>} ends Linear ring end indexes\n * @return {Array<Array<number>>} Two dimensional endss array that can\n * be used to construct a MultiPolygon\n */\nexport function inflateEnds(flatCoordinates, ends) {\n  const endss = [];\n  let offset = 0;\n  let prevEndIndex = 0;\n  let startOrientation;\n  for (let i = 0, ii = ends.length; i < ii; ++i) {\n    const end = ends[i];\n    // classifies an array of rings into polygons with outer rings and holes\n    const orientation = linearRingIsClockwise(flatCoordinates, offset, end, 2);\n    if (startOrientation === undefined) {\n      startOrientation = orientation;\n    }\n    if (orientation === startOrientation) {\n      endss.push(ends.slice(prevEndIndex, i + 1));\n    } else {\n      if (endss.length === 0) {\n        continue;\n      }\n      endss[endss.length - 1].push(ends[prevEndIndex]);\n    }\n    prevEndIndex = i + 1;\n    offset = end;\n  }\n  return endss;\n}\n", "/**\n * @module ol/geom/Polygon\n */\nimport {extend} from '../array.js';\nimport {closestSquaredDistanceXY, getCenter, isEmpty} from '../extent.js';\nimport {modulo} from '../math.js';\nimport {offset as sphereOffset} from '../sphere.js';\nimport LinearRing from './LinearRing.js';\nimport Point from './Point.js';\nimport SimpleGeometry from './SimpleGeometry.js';\nimport {linearRings as linearRingsArea} from './flat/area.js';\nimport {arrayMaxSquaredDelta, assignClosestArrayPoint} from './flat/closest.js';\nimport {linearRingsContainsXY} from './flat/contains.js';\nimport {deflateCoordinatesArray} from './flat/deflate.js';\nimport {inflateCoordinatesArray} from './flat/inflate.js';\nimport {getInteriorPointOfArray} from './flat/interiorpoint.js';\nimport {intersectsLinearRingArray} from './flat/intersectsextent.js';\nimport {linearRingsAreOriented, orientLinearRings} from './flat/orient.js';\nimport {quantizeArray} from './flat/simplify.js';\n\n/**\n * @classdesc\n * Polygon geometry.\n *\n * @api\n */\nclass Polygon extends SimpleGeometry {\n  /**\n   * @param {!Array<Array<import(\"../coordinate.js\").Coordinate>>|!Array<number>} coordinates\n   *     Array of linear rings that define the polygon. The first linear ring of the\n   *     array defines the outer-boundary or surface of the polygon. Each subsequent\n   *     linear ring defines a hole in the surface of the polygon. A linear ring is\n   *     an array of vertices' coordinates where the first coordinate and the last are\n   *     equivalent. (For internal use, flat coordinates in combination with\n   *     `layout` and `ends` are also accepted.)\n   * @param {import(\"./Geometry.js\").GeometryLayout} [layout] Layout.\n   * @param {Array<number>} [ends] Ends (for internal use with flat coordinates).\n   */\n  constructor(coordinates, layout, ends) {\n    super();\n\n    /**\n     * @type {Array<number>}\n     * @private\n     */\n    this.ends_ = [];\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.flatInteriorPointRevision_ = -1;\n\n    /**\n     * @private\n     * @type {import(\"../coordinate.js\").Coordinate|null}\n     */\n    this.flatInteriorPoint_ = null;\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.maxDelta_ = -1;\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.maxDeltaRevision_ = -1;\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.orientedRevision_ = -1;\n\n    /**\n     * @private\n     * @type {Array<number>|null}\n     */\n    this.orientedFlatCoordinates_ = null;\n\n    if (layout !== undefined && ends) {\n      this.setFlatCoordinates(\n        layout,\n        /** @type {Array<number>} */ (coordinates),\n      );\n      this.ends_ = ends;\n    } else {\n      this.setCoordinates(\n        /** @type {Array<Array<import(\"../coordinate.js\").Coordinate>>} */ (\n          coordinates\n        ),\n        layout,\n      );\n    }\n  }\n\n  /**\n   * Append the passed linear ring to this polygon.\n   * @param {LinearRing} linearRing Linear ring.\n   * @api\n   */\n  appendLinearRing(linearRing) {\n    if (!this.flatCoordinates) {\n      this.flatCoordinates = linearRing.getFlatCoordinates().slice();\n    } else {\n      extend(this.flatCoordinates, linearRing.getFlatCoordinates());\n    }\n    this.ends_.push(this.flatCoordinates.length);\n    this.changed();\n  }\n\n  /**\n   * Make a complete copy of the geometry.\n   * @return {!Polygon} Clone.\n   * @api\n   * @override\n   */\n  clone() {\n    const polygon = new Polygon(\n      this.flatCoordinates.slice(),\n      this.layout,\n      this.ends_.slice(),\n    );\n    polygon.applyProperties(this);\n    return polygon;\n  }\n\n  /**\n   * @param {number} x X.\n   * @param {number} y Y.\n   * @param {import(\"../coordinate.js\").Coordinate} closestPoint Closest point.\n   * @param {number} minSquaredDistance Minimum squared distance.\n   * @return {number} Minimum squared distance.\n   * @override\n   */\n  closestPointXY(x, y, closestPoint, minSquaredDistance) {\n    if (minSquaredDistance < closestSquaredDistanceXY(this.getExtent(), x, y)) {\n      return minSquaredDistance;\n    }\n    if (this.maxDeltaRevision_ != this.getRevision()) {\n      this.maxDelta_ = Math.sqrt(\n        arrayMaxSquaredDelta(\n          this.flatCoordinates,\n          0,\n          this.ends_,\n          this.stride,\n          0,\n        ),\n      );\n      this.maxDeltaRevision_ = this.getRevision();\n    }\n    return assignClosestArrayPoint(\n      this.flatCoordinates,\n      0,\n      this.ends_,\n      this.stride,\n      this.maxDelta_,\n      true,\n      x,\n      y,\n      closestPoint,\n      minSquaredDistance,\n    );\n  }\n\n  /**\n   * @param {number} x X.\n   * @param {number} y Y.\n   * @return {boolean} Contains (x, y).\n   * @override\n   */\n  containsXY(x, y) {\n    return linearRingsContainsXY(\n      this.getOrientedFlatCoordinates(),\n      0,\n      this.ends_,\n      this.stride,\n      x,\n      y,\n    );\n  }\n\n  /**\n   * Return the area of the polygon on projected plane.\n   * @return {number} Area (on projected plane).\n   * @api\n   */\n  getArea() {\n    return linearRingsArea(\n      this.getOrientedFlatCoordinates(),\n      0,\n      this.ends_,\n      this.stride,\n    );\n  }\n\n  /**\n   * Get the coordinate array for this geometry.  This array has the structure\n   * of a GeoJSON coordinate array for polygons.\n   *\n   * @param {boolean} [right] Orient coordinates according to the right-hand\n   *     rule (counter-clockwise for exterior and clockwise for interior rings).\n   *     If `false`, coordinates will be oriented according to the left-hand rule\n   *     (clockwise for exterior and counter-clockwise for interior rings).\n   *     By default, coordinate orientation will depend on how the geometry was\n   *     constructed.\n   * @return {Array<Array<import(\"../coordinate.js\").Coordinate>>} Coordinates.\n   * @api\n   * @override\n   */\n  getCoordinates(right) {\n    let flatCoordinates;\n    if (right !== undefined) {\n      flatCoordinates = this.getOrientedFlatCoordinates().slice();\n      orientLinearRings(flatCoordinates, 0, this.ends_, this.stride, right);\n    } else {\n      flatCoordinates = this.flatCoordinates;\n    }\n\n    return inflateCoordinatesArray(flatCoordinates, 0, this.ends_, this.stride);\n  }\n\n  /**\n   * @return {Array<number>} Ends.\n   */\n  getEnds() {\n    return this.ends_;\n  }\n\n  /**\n   * @return {Array<number>} Interior point.\n   */\n  getFlatInteriorPoint() {\n    if (this.flatInteriorPointRevision_ != this.getRevision()) {\n      const flatCenter = getCenter(this.getExtent());\n      this.flatInteriorPoint_ = getInteriorPointOfArray(\n        this.getOrientedFlatCoordinates(),\n        0,\n        this.ends_,\n        this.stride,\n        flatCenter,\n        0,\n      );\n      this.flatInteriorPointRevision_ = this.getRevision();\n    }\n    return /** @type {import(\"../coordinate.js\").Coordinate} */ (\n      this.flatInteriorPoint_\n    );\n  }\n\n  /**\n   * Return an interior point of the polygon.\n   * @return {Point} Interior point as XYM coordinate, where M is the\n   * length of the horizontal intersection that the point belongs to.\n   * @api\n   */\n  getInteriorPoint() {\n    return new Point(this.getFlatInteriorPoint(), 'XYM');\n  }\n\n  /**\n   * Return the number of rings of the polygon,  this includes the exterior\n   * ring and any interior rings.\n   *\n   * @return {number} Number of rings.\n   * @api\n   */\n  getLinearRingCount() {\n    return this.ends_.length;\n  }\n\n  /**\n   * Return the Nth linear ring of the polygon geometry. Return `null` if the\n   * given index is out of range.\n   * The exterior linear ring is available at index `0` and the interior rings\n   * at index `1` and beyond.\n   *\n   * @param {number} index Index.\n   * @return {LinearRing|null} Linear ring.\n   * @api\n   */\n  getLinearRing(index) {\n    if (index < 0 || this.ends_.length <= index) {\n      return null;\n    }\n    return new LinearRing(\n      this.flatCoordinates.slice(\n        index === 0 ? 0 : this.ends_[index - 1],\n        this.ends_[index],\n      ),\n      this.layout,\n    );\n  }\n\n  /**\n   * Return the linear rings of the polygon.\n   * @return {Array<LinearRing>} Linear rings.\n   * @api\n   */\n  getLinearRings() {\n    const layout = this.layout;\n    const flatCoordinates = this.flatCoordinates;\n    const ends = this.ends_;\n    const linearRings = [];\n    let offset = 0;\n    for (let i = 0, ii = ends.length; i < ii; ++i) {\n      const end = ends[i];\n      const linearRing = new LinearRing(\n        flatCoordinates.slice(offset, end),\n        layout,\n      );\n      linearRings.push(linearRing);\n      offset = end;\n    }\n    return linearRings;\n  }\n\n  /**\n   * @return {Array<number>} Oriented flat coordinates.\n   */\n  getOrientedFlatCoordinates() {\n    if (this.orientedRevision_ != this.getRevision()) {\n      const flatCoordinates = this.flatCoordinates;\n      if (linearRingsAreOriented(flatCoordinates, 0, this.ends_, this.stride)) {\n        this.orientedFlatCoordinates_ = flatCoordinates;\n      } else {\n        this.orientedFlatCoordinates_ = flatCoordinates.slice();\n        this.orientedFlatCoordinates_.length = orientLinearRings(\n          this.orientedFlatCoordinates_,\n          0,\n          this.ends_,\n          this.stride,\n        );\n      }\n      this.orientedRevision_ = this.getRevision();\n    }\n    return /** @type {Array<number>} */ (this.orientedFlatCoordinates_);\n  }\n\n  /**\n   * @param {number} squaredTolerance Squared tolerance.\n   * @return {Polygon} Simplified Polygon.\n   * @protected\n   * @override\n   */\n  getSimplifiedGeometryInternal(squaredTolerance) {\n    /** @type {Array<number>} */\n    const simplifiedFlatCoordinates = [];\n    /** @type {Array<number>} */\n    const simplifiedEnds = [];\n    simplifiedFlatCoordinates.length = quantizeArray(\n      this.flatCoordinates,\n      0,\n      this.ends_,\n      this.stride,\n      Math.sqrt(squaredTolerance),\n      simplifiedFlatCoordinates,\n      0,\n      simplifiedEnds,\n    );\n    return new Polygon(simplifiedFlatCoordinates, 'XY', simplifiedEnds);\n  }\n\n  /**\n   * Get the type of this geometry.\n   * @return {import(\"./Geometry.js\").Type} Geometry type.\n   * @api\n   * @override\n   */\n  getType() {\n    return 'Polygon';\n  }\n\n  /**\n   * Test if the geometry and the passed extent intersect.\n   * @param {import(\"../extent.js\").Extent} extent Extent.\n   * @return {boolean} `true` if the geometry and the extent intersect.\n   * @api\n   * @override\n   */\n  intersectsExtent(extent) {\n    return intersectsLinearRingArray(\n      this.getOrientedFlatCoordinates(),\n      0,\n      this.ends_,\n      this.stride,\n      extent,\n    );\n  }\n\n  /**\n   * Set the coordinates of the polygon.\n   * @param {!Array<Array<import(\"../coordinate.js\").Coordinate>>} coordinates Coordinates.\n   * @param {import(\"./Geometry.js\").GeometryLayout} [layout] Layout.\n   * @api\n   * @override\n   */\n  setCoordinates(coordinates, layout) {\n    this.setLayout(layout, coordinates, 2);\n    if (!this.flatCoordinates) {\n      this.flatCoordinates = [];\n    }\n    const ends = deflateCoordinatesArray(\n      this.flatCoordinates,\n      0,\n      coordinates,\n      this.stride,\n      this.ends_,\n    );\n    this.flatCoordinates.length = ends.length === 0 ? 0 : ends[ends.length - 1];\n    this.changed();\n  }\n}\n\nexport default Polygon;\n\n/**\n * Create an approximation of a circle on the surface of a sphere.\n * @param {import(\"../coordinate.js\").Coordinate} center Center (`[lon, lat]` in degrees).\n * @param {number} radius The great-circle distance from the center to\n *     the polygon vertices in meters.\n * @param {number} [n] Optional number of vertices for the resulting\n *     polygon. Default is `32`.\n * @param {number} [sphereRadius] Optional radius for the sphere (defaults to\n *     the Earth's mean radius using the WGS84 ellipsoid).\n * @return {Polygon} The \"circular\" polygon.\n * @api\n */\nexport function circular(center, radius, n, sphereRadius) {\n  n = n ? n : 32;\n  /** @type {Array<number>} */\n  const flatCoordinates = [];\n  for (let i = 0; i < n; ++i) {\n    extend(\n      flatCoordinates,\n      sphereOffset(center, radius, (2 * Math.PI * i) / n, sphereRadius),\n    );\n  }\n  flatCoordinates.push(flatCoordinates[0], flatCoordinates[1]);\n  return new Polygon(flatCoordinates, 'XY', [flatCoordinates.length]);\n}\n\n/**\n * Create a polygon from an extent. The layout used is `XY`.\n * @param {import(\"../extent.js\").Extent} extent The extent.\n * @return {Polygon} The polygon.\n * @api\n */\nexport function fromExtent(extent) {\n  if (isEmpty(extent)) {\n    throw new Error('Cannot create polygon from empty extent');\n  }\n  const minX = extent[0];\n  const minY = extent[1];\n  const maxX = extent[2];\n  const maxY = extent[3];\n  const flatCoordinates = [\n    minX,\n    minY,\n    minX,\n    maxY,\n    maxX,\n    maxY,\n    maxX,\n    minY,\n    minX,\n    minY,\n  ];\n  return new Polygon(flatCoordinates, 'XY', [flatCoordinates.length]);\n}\n\n/**\n * Create a regular polygon from a circle.\n * @param {import(\"./Circle.js\").default} circle Circle geometry.\n * @param {number} [sides] Number of sides of the polygon. Default is 32.\n * @param {number} [angle] Start angle for the first vertex of the polygon in\n *     counter-clockwise radians. 0 means East. Default is 0.\n * @return {Polygon} Polygon geometry.\n * @api\n */\nexport function fromCircle(circle, sides, angle) {\n  sides = sides ? sides : 32;\n  const stride = circle.getStride();\n  const layout = circle.getLayout();\n  const center = circle.getCenter();\n  const arrayLength = stride * (sides + 1);\n  const flatCoordinates = new Array(arrayLength);\n  for (let i = 0; i < arrayLength; i += stride) {\n    flatCoordinates[i] = 0;\n    flatCoordinates[i + 1] = 0;\n    for (let j = 2; j < stride; j++) {\n      flatCoordinates[i + j] = center[j];\n    }\n  }\n  const ends = [flatCoordinates.length];\n  const polygon = new Polygon(flatCoordinates, layout, ends);\n  makeRegular(polygon, center, circle.getRadius(), angle);\n  return polygon;\n}\n\n/**\n * Modify the coordinates of a polygon to make it a regular polygon.\n * @param {Polygon} polygon Polygon geometry.\n * @param {import(\"../coordinate.js\").Coordinate} center Center of the regular polygon.\n * @param {number} radius Radius of the regular polygon.\n * @param {number} [angle] Start angle for the first vertex of the polygon in\n *     counter-clockwise radians. 0 means East. Default is 0.\n */\nexport function makeRegular(polygon, center, radius, angle) {\n  const flatCoordinates = polygon.getFlatCoordinates();\n  const stride = polygon.getStride();\n  const sides = flatCoordinates.length / stride - 1;\n  const startAngle = angle ? angle : 0;\n  for (let i = 0; i <= sides; ++i) {\n    const offset = i * stride;\n    const angle = startAngle + (modulo(i, sides) * 2 * Math.PI) / sides;\n    flatCoordinates[offset] = center[0] + radius * Math.cos(angle);\n    flatCoordinates[offset + 1] = center[1] + radius * Math.sin(angle);\n  }\n  polygon.changed();\n}\n", "/**\n * @module ol/resolutionconstraint\n */\nimport {linearFindNearest} from './array.js';\nimport {getHeight, getWidth} from './extent.js';\nimport {clamp} from './math.js';\n\n/**\n * @typedef {function((number|undefined), number, import(\"./size.js\").Size, boolean=): (number|undefined)} Type\n */\n\n/**\n * Returns a modified resolution taking into account the viewport size and maximum\n * allowed extent.\n * @param {number} resolution Resolution\n * @param {import(\"./extent.js\").Extent} maxExtent Maximum allowed extent.\n * @param {import(\"./size.js\").Size} viewportSize Viewport size.\n * @param {boolean} showFullExtent Whether to show the full extent.\n * @return {number} Capped resolution.\n */\nfunction getViewportClampedResolution(\n  resolution,\n  maxExtent,\n  viewportSize,\n  showFullExtent,\n) {\n  const xResolution = getWidth(maxExtent) / viewportSize[0];\n  const yResolution = getHeight(maxExtent) / viewportSize[1];\n\n  if (showFullExtent) {\n    return Math.min(resolution, Math.max(xResolution, yResolution));\n  }\n  return Math.min(resolution, Math.min(xResolution, yResolution));\n}\n\n/**\n * Returns a modified resolution to be between maxResolution and minResolution while\n * still allowing the value to be slightly out of bounds.\n * Note: the computation is based on the logarithm function (ln):\n *  - at 1, ln(x) is 0\n *  - above 1, ln(x) keeps increasing but at a much slower pace than x\n * The final result is clamped to prevent getting too far away from bounds.\n * @param {number} resolution Resolution.\n * @param {number} maxResolution Max resolution.\n * @param {number} minResolution Min resolution.\n * @return {number} Smoothed resolution.\n */\nfunction getSmoothClampedResolution(resolution, maxResolution, minResolution) {\n  let result = Math.min(resolution, maxResolution);\n  const ratio = 50;\n\n  result *=\n    Math.log(1 + ratio * Math.max(0, resolution / maxResolution - 1)) / ratio +\n    1;\n  if (minResolution) {\n    result = Math.max(result, minResolution);\n    result /=\n      Math.log(1 + ratio * Math.max(0, minResolution / resolution - 1)) /\n        ratio +\n      1;\n  }\n  return clamp(result, minResolution / 2, maxResolution * 2);\n}\n\n/**\n * @param {Array<number>} resolutions Resolutions.\n * @param {boolean} [smooth] If true, the view will be able to slightly exceed resolution limits. Default: true.\n * @param {import(\"./extent.js\").Extent} [maxExtent] Maximum allowed extent.\n * @param {boolean} [showFullExtent] If true, allows us to show the full extent. Default: false.\n * @return {Type} Zoom function.\n */\nexport function createSnapToResolutions(\n  resolutions,\n  smooth,\n  maxExtent,\n  showFullExtent,\n) {\n  smooth = smooth !== undefined ? smooth : true;\n  return (\n    /**\n     * @param {number|undefined} resolution Resolution.\n     * @param {number} direction Direction.\n     * @param {import(\"./size.js\").Size} size Viewport size.\n     * @param {boolean} [isMoving] True if an interaction or animation is in progress.\n     * @return {number|undefined} Resolution.\n     */\n    function (resolution, direction, size, isMoving) {\n      if (resolution !== undefined) {\n        const maxResolution = resolutions[0];\n        const minResolution = resolutions[resolutions.length - 1];\n        const cappedMaxRes = maxExtent\n          ? getViewportClampedResolution(\n              maxResolution,\n              maxExtent,\n              size,\n              showFullExtent,\n            )\n          : maxResolution;\n\n        // during interacting or animating, allow intermediary values\n        if (isMoving) {\n          if (!smooth) {\n            return clamp(resolution, minResolution, cappedMaxRes);\n          }\n          return getSmoothClampedResolution(\n            resolution,\n            cappedMaxRes,\n            minResolution,\n          );\n        }\n\n        const capped = Math.min(cappedMaxRes, resolution);\n        const z = Math.floor(linearFindNearest(resolutions, capped, direction));\n        if (resolutions[z] > cappedMaxRes && z < resolutions.length - 1) {\n          return resolutions[z + 1];\n        }\n        return resolutions[z];\n      }\n      return undefined;\n    }\n  );\n}\n\n/**\n * @param {number} power Power.\n * @param {number} maxResolution Maximum resolution.\n * @param {number} [minResolution] Minimum resolution.\n * @param {boolean} [smooth] If true, the view will be able to slightly exceed resolution limits. Default: true.\n * @param {import(\"./extent.js\").Extent} [maxExtent] Maximum allowed extent.\n * @param {boolean} [showFullExtent] If true, allows us to show the full extent. Default: false.\n * @return {Type} Zoom function.\n */\nexport function createSnapToPower(\n  power,\n  maxResolution,\n  minResolution,\n  smooth,\n  maxExtent,\n  showFullExtent,\n) {\n  smooth = smooth !== undefined ? smooth : true;\n  minResolution = minResolution !== undefined ? minResolution : 0;\n\n  return (\n    /**\n     * @param {number|undefined} resolution Resolution.\n     * @param {number} direction Direction.\n     * @param {import(\"./size.js\").Size} size Viewport size.\n     * @param {boolean} [isMoving] True if an interaction or animation is in progress.\n     * @return {number|undefined} Resolution.\n     */\n    function (resolution, direction, size, isMoving) {\n      if (resolution !== undefined) {\n        const cappedMaxRes = maxExtent\n          ? getViewportClampedResolution(\n              maxResolution,\n              maxExtent,\n              size,\n              showFullExtent,\n            )\n          : maxResolution;\n\n        // during interacting or animating, allow intermediary values\n        if (isMoving) {\n          if (!smooth) {\n            return clamp(resolution, minResolution, cappedMaxRes);\n          }\n          return getSmoothClampedResolution(\n            resolution,\n            cappedMaxRes,\n            minResolution,\n          );\n        }\n\n        const tolerance = 1e-9;\n        const minZoomLevel = Math.ceil(\n          Math.log(maxResolution / cappedMaxRes) / Math.log(power) - tolerance,\n        );\n        const offset = -direction * (0.5 - tolerance) + 0.5;\n        const capped = Math.min(cappedMaxRes, resolution);\n        const cappedZoomLevel = Math.floor(\n          Math.log(maxResolution / capped) / Math.log(power) + offset,\n        );\n        const zoomLevel = Math.max(minZoomLevel, cappedZoomLevel);\n        const newResolution = maxResolution / Math.pow(power, zoomLevel);\n        return clamp(newResolution, minResolution, cappedMaxRes);\n      }\n      return undefined;\n    }\n  );\n}\n\n/**\n * @param {number} maxResolution Max resolution.\n * @param {number} minResolution Min resolution.\n * @param {boolean} [smooth] If true, the view will be able to slightly exceed resolution limits. Default: true.\n * @param {import(\"./extent.js\").Extent} [maxExtent] Maximum allowed extent.\n * @param {boolean} [showFullExtent] If true, allows us to show the full extent. Default: false.\n * @return {Type} Zoom function.\n */\nexport function createMinMaxResolution(\n  maxResolution,\n  minResolution,\n  smooth,\n  maxExtent,\n  showFullExtent,\n) {\n  smooth = smooth !== undefined ? smooth : true;\n\n  return (\n    /**\n     * @param {number|undefined} resolution Resolution.\n     * @param {number} direction Direction.\n     * @param {import(\"./size.js\").Size} size Viewport size.\n     * @param {boolean} [isMoving] True if an interaction or animation is in progress.\n     * @return {number|undefined} Resolution.\n     */\n    function (resolution, direction, size, isMoving) {\n      if (resolution !== undefined) {\n        const cappedMaxRes = maxExtent\n          ? getViewportClampedResolution(\n              maxResolution,\n              maxExtent,\n              size,\n              showFullExtent,\n            )\n          : maxResolution;\n\n        if (!smooth || !isMoving) {\n          return clamp(resolution, minResolution, cappedMaxRes);\n        }\n        return getSmoothClampedResolution(\n          resolution,\n          cappedMaxRes,\n          minResolution,\n        );\n      }\n      return undefined;\n    }\n  );\n}\n", "/**\n * @module ol/rotationconstraint\n */\nimport {toRadians} from './math.js';\n\n/**\n * @typedef {function((number|undefined), boolean=): (number|undefined)} Type\n */\n\n/**\n * @param {number|undefined} rotation Rotation.\n * @return {number|undefined} Rotation.\n */\nexport function disable(rotation) {\n  if (rotation !== undefined) {\n    return 0;\n  }\n  return undefined;\n}\n\n/**\n * @param {number|undefined} rotation Rotation.\n * @return {number|undefined} Rotation.\n */\nexport function none(rotation) {\n  if (rotation !== undefined) {\n    return rotation;\n  }\n  return undefined;\n}\n\n/**\n * @param {number} n N.\n * @return {Type} Rotation constraint.\n */\nexport function createSnapToN(n) {\n  const theta = (2 * Math.PI) / n;\n  return (\n    /**\n     * @param {number|undefined} rotation Rotation.\n     * @param {boolean} [isMoving] True if an interaction or animation is in progress.\n     * @return {number|undefined} Rotation.\n     */\n    function (rotation, isMoving) {\n      if (isMoving) {\n        return rotation;\n      }\n\n      if (rotation !== undefined) {\n        rotation = Math.floor(rotation / theta + 0.5) * theta;\n        return rotation;\n      }\n      return undefined;\n    }\n  );\n}\n\n/**\n * @param {number} [tolerance] Tolerance.\n * @return {Type} Rotation constraint.\n */\nexport function createSnapToZero(tolerance) {\n  const t = tolerance === undefined ? toRadians(5) : tolerance;\n  return (\n    /**\n     * @param {number|undefined} rotation Rotation.\n     * @param {boolean} [isMoving] True if an interaction or animation is in progress.\n     * @return {number|undefined} Rotation.\n     */\n    function (rotation, isMoving) {\n      if (isMoving || rotation === undefined) {\n        return rotation;\n      }\n\n      if (Math.abs(rotation) <= t) {\n        return 0;\n      }\n      return rotation;\n    }\n  );\n}\n", "/**\n * @module ol/View\n */\nimport BaseObject from './Object.js';\nimport ViewHint from './ViewHint.js';\nimport ViewProperty from './ViewProperty.js';\nimport {linearFindNearest} from './array.js';\nimport {assert} from './asserts.js';\nimport {none as centerNone, createExtent} from './centerconstraint.js';\nimport {\n  add as addCoordinate,\n  equals as coordinatesEqual,\n  equals,\n  rotate as rotateCoordinate,\n} from './coordinate.js';\nimport {easeOut, inAndOut} from './easing.js';\nimport {\n  getCenter,\n  getForViewAndSize,\n  getHeight,\n  getWidth,\n  isEmpty,\n} from './extent.js';\nimport {VOID} from './functions.js';\nimport {fromExtent as polygonFromExtent} from './geom/Polygon.js';\nimport {clamp, modulo} from './math.js';\nimport {\n  METERS_PER_UNIT,\n  createProjection,\n  disableCoordinateWarning,\n  fromUserCoordinate,\n  fromUserExtent,\n  getUserProjection,\n  toUserCoordinate,\n  toUserExtent,\n} from './proj.js';\nimport {\n  createMinMaxResolution,\n  createSnapToPower,\n  createSnapToResolutions,\n} from './resolutionconstraint.js';\nimport {\n  createSnapToN,\n  createSnapToZero,\n  disable,\n  none as rotationNone,\n} from './rotationconstraint.js';\nimport {DEFAULT_TILE_SIZE} from './tilegrid/common.js';\n\n/**\n * An animation configuration\n *\n * @typedef {Object} Animation\n * @property {import(\"./coordinate.js\").Coordinate} [sourceCenter] Source center.\n * @property {import(\"./coordinate.js\").Coordinate} [targetCenter] Target center.\n * @property {number} [sourceResolution] Source resolution.\n * @property {number} [targetResolution] Target resolution.\n * @property {number} [sourceRotation] Source rotation.\n * @property {number} [targetRotation] Target rotation.\n * @property {import(\"./coordinate.js\").Coordinate} [anchor] Anchor.\n * @property {number} start Start.\n * @property {number} duration Duration.\n * @property {boolean} complete Complete.\n * @property {function(number):number} easing Easing.\n * @property {function(boolean):void} callback Callback.\n */\n\n/**\n * @typedef {Object} Constraints\n * @property {import(\"./centerconstraint.js\").Type} center Center.\n * @property {import(\"./resolutionconstraint.js\").Type} resolution Resolution.\n * @property {import(\"./rotationconstraint.js\").Type} rotation Rotation.\n */\n\n/**\n * @typedef {Object} FitOptions\n * @property {import(\"./size.js\").Size} [size] The size in pixels of the box to\n * fit the extent into. Defaults to the size of the map the view is associated with.\n * If no map or multiple maps are connected to the view, provide the desired box size\n * (e.g. `map.getSize()`).\n * @property {!Array<number>} [padding=[0, 0, 0, 0]] Padding (in pixels) to be\n * cleared inside the view. Values in the array are top, right, bottom and left\n * padding.\n * @property {boolean} [nearest=false] If the view `constrainResolution` option is `true`,\n * get the nearest extent instead of the closest that actually fits the view.\n * @property {number} [minResolution=0] Minimum resolution that we zoom to.\n * @property {number} [maxZoom] Maximum zoom level that we zoom to. If\n * `minResolution` is given, this property is ignored.\n * @property {number} [duration] The duration of the animation in milliseconds.\n * By default, there is no animation to the target extent.\n * @property {function(number):number} [easing] The easing function used during\n * the animation (defaults to {@link module:ol/easing.inAndOut}).\n * The function will be called for each frame with a number representing a\n * fraction of the animation's duration.  The function should return a number\n * between 0 and 1 representing the progress toward the destination state.\n * @property {function(boolean):void} [callback] Function called when the view is in\n * its final position. The callback will be called with `true` if the animation\n * series completed on its own or `false` if it was cancelled.\n */\n\n/**\n * @typedef {Object} ViewOptions\n * @property {import(\"./coordinate.js\").Coordinate} [center] The initial center for\n * the view. If a user projection is not set, the coordinate system for the center is\n * specified with the `projection` option. Layer sources will not be fetched if this\n * is not set, but the center can be set later with {@link #setCenter}.\n * @property {boolean|number} [constrainRotation=true] Rotation constraint.\n * `false` means no constraint. `true` means no constraint, but snap to zero\n * near zero. A number constrains the rotation to that number of values. For\n * example, `4` will constrain the rotation to 0, 90, 180, and 270 degrees.\n * @property {boolean} [enableRotation=true] Enable rotation.\n * If `false`, a rotation constraint that always sets the rotation to zero is\n * used. The `constrainRotation` option has no effect if `enableRotation` is\n * `false`.\n * @property {import(\"./extent.js\").Extent} [extent] The extent that constrains the\n * view, in other words, nothing outside of this extent can be visible on the map.\n * @property {boolean} [constrainOnlyCenter=false] If true, the extent\n * constraint will only apply to the view center and not the whole extent.\n * @property {boolean} [smoothExtentConstraint=true] If true, the extent\n * constraint will be applied smoothly, i.e. allow the view to go slightly outside\n * of the given `extent`.\n * @property {number} [maxResolution] The maximum resolution used to determine\n * the resolution constraint. It is used together with `minResolution` (or\n * `maxZoom`) and `zoomFactor`. If unspecified it is calculated in such a way\n * that the projection's validity extent fits in a 256x256 px tile. If the\n * projection is Spherical Mercator (the default) then `maxResolution` defaults\n * to `40075016.68557849 / 256 = 156543.03392804097`.\n * @property {number} [minResolution] The minimum resolution used to determine\n * the resolution constraint.  It is used together with `maxResolution` (or\n * `minZoom`) and `zoomFactor`.  If unspecified it is calculated assuming 29\n * zoom levels (with a factor of 2). If the projection is Spherical Mercator\n * (the default) then `minResolution` defaults to\n * `40075016.68557849 / 256 / Math.pow(2, 28) = 0.0005831682455839253`.\n * @property {number} [maxZoom=28] The maximum zoom level used to determine the\n * resolution constraint. It is used together with `minZoom` (or\n * `maxResolution`) and `zoomFactor`.  Note that if `minResolution` is also\n * provided, it is given precedence over `maxZoom`.\n * @property {number} [minZoom=0] The minimum zoom level used to determine the\n * resolution constraint. It is used together with `maxZoom` (or\n * `minResolution`) and `zoomFactor`.  Note that if `maxResolution` is also\n * provided, it is given precedence over `minZoom`.\n * @property {boolean} [multiWorld=false] If `false` the view is constrained so\n * only one world is visible, and you cannot pan off the edge.  If `true` the map\n * may show multiple worlds at low zoom levels.  Only used if the `projection` is\n * global.  Note that if `extent` is also provided it is given precedence.\n * @property {boolean} [constrainResolution=false] If true, the view will always\n * animate to the closest zoom level after an interaction; false means\n * intermediary zoom levels are allowed.\n * @property {boolean} [smoothResolutionConstraint=true] If true, the resolution\n * min/max values will be applied smoothly, i. e. allow the view to exceed slightly\n * the given resolution or zoom bounds.\n * @property {boolean} [showFullExtent=false] Allow the view to be zoomed out to\n * show the full configured extent. By default, when a view is configured with an\n * extent, users will not be able to zoom out so the viewport exceeds the extent in\n * either dimension. This means the full extent may not be visible if the viewport\n * is taller or wider than the aspect ratio of the configured extent. If\n * showFullExtent is true, the user will be able to zoom out so that the viewport\n * exceeds the height or width of the configured extent, but not both, allowing the\n * full extent to be shown.\n * @property {import(\"./proj.js\").ProjectionLike} [projection='EPSG:3857'] The\n * projection. The default is Spherical Mercator.\n * @property {number} [resolution] The initial resolution for the view. The\n * units are `projection` units per pixel (e.g. meters per pixel). An\n * alternative to setting this is to set `zoom`. Layer sources will not be\n * fetched if neither this nor `zoom` are defined, but they can be set later\n * with {@link #setZoom} or {@link #setResolution}.\n * @property {Array<number>} [resolutions] Resolutions that determine the\n * zoom levels if specified. The index in the array corresponds to the zoom level,\n * therefore the resolution values have to be in descending order. It also constrains\n * the resolution by the minimum and maximum value. If set the `maxResolution`,\n * `minResolution`, `minZoom`, `maxZoom`, and `zoomFactor` options are ignored.\n * @property {number} [rotation=0] The initial rotation for the view in radians\n * (positive rotation clockwise, 0 means North).\n * @property {number} [zoom] Only used if `resolution` is not defined. Zoom\n * level used to calculate the initial resolution for the view.\n * @property {number} [zoomFactor=2] The zoom factor used to compute the\n * corresponding resolution.\n * @property {!Array<number>} [padding=[0, 0, 0, 0]] Padding (in css pixels).\n * If the map viewport is partially covered with other content (overlays) along\n * its edges, this setting allows to shift the center of the viewport away from\n * that content. The order of the values is top, right, bottom, left.\n */\n\n/**\n * @typedef {Object} AnimationOptions\n * @property {import(\"./coordinate.js\").Coordinate} [center] The center of the view at the end of\n * the animation.\n * @property {number} [zoom] The zoom level of the view at the end of the\n * animation. This takes precedence over `resolution`.\n * @property {number} [resolution] The resolution of the view at the end\n * of the animation.  If `zoom` is also provided, this option will be ignored.\n * @property {number} [rotation] The rotation of the view at the end of\n * the animation.\n * @property {import(\"./coordinate.js\").Coordinate} [anchor] Optional anchor to remain fixed\n * during a rotation or resolution animation.\n * @property {number} [duration=1000] The duration of the animation in milliseconds.\n * @property {function(number):number} [easing] The easing function used\n * during the animation (defaults to {@link module:ol/easing.inAndOut}).\n * The function will be called for each frame with a number representing a\n * fraction of the animation's duration.  The function should return a number\n * between 0 and 1 representing the progress toward the destination state.\n */\n\n/**\n * @typedef {Object} State\n * @property {import(\"./coordinate.js\").Coordinate} center Center (in view projection coordinates).\n * @property {import(\"./proj/Projection.js\").default} projection Projection.\n * @property {number} resolution Resolution.\n * @property {import(\"./coordinate.js\").Coordinate} [nextCenter] The next center during an animation series.\n * @property {number} [nextResolution] The next resolution during an animation series.\n * @property {number} [nextRotation] The next rotation during an animation series.\n * @property {number} rotation Rotation.\n * @property {number} zoom Zoom.\n */\n\n/**\n * Like {@link import(\"./Map.js\").FrameState}, but just `viewState` and `extent`.\n * @typedef {Object} ViewStateLayerStateExtent\n * @property {State} viewState View state.\n * @property {import(\"./extent.js\").Extent} extent Extent (in user projection coordinates).\n * @property {Array<import(\"./layer/Layer.js\").State>} [layerStatesArray] Layer states.\n */\n\n/**\n * Default min zoom level for the map view.\n * @type {number}\n */\nconst DEFAULT_MIN_ZOOM = 0;\n\n/**\n * @typedef {import(\"./ObjectEventType.js\").Types|'change:center'|'change:resolution'|'change:rotation'} ViewObjectEventTypes\n */\n\n/***\n * @template Return\n * @typedef {import(\"./Observable.js\").OnSignature<import(\"./Observable.js\").EventTypes, import(\"./events/Event.js\").default, Return> &\n *   import(\"./Observable.js\").OnSignature<ViewObjectEventTypes, import(\"./Object.js\").ObjectEvent, Return> &\n *   import(\"./Observable.js\").CombinedOnSignature<import(\"./Observable.js\").EventTypes|ViewObjectEventTypes, Return>} ViewOnSignature\n */\n\n/**\n * @classdesc\n * A View object represents a simple 2D view of the map.\n *\n * This is the object to act upon to change the center, resolution,\n * and rotation of the map.\n *\n * A View has a `projection`. The projection determines the\n * coordinate system of the center, and its units determine the units of the\n * resolution (projection units per pixel). The default projection is\n * Web Mercator (EPSG:3857).\n *\n * ### The view states\n *\n * A View is determined by three states: `center`, `resolution`,\n * and `rotation`. Each state has a corresponding getter and setter, e.g.\n * `getCenter` and `setCenter` for the `center` state.\n *\n * The `zoom` state is actually not saved on the view: all computations\n * internally use the `resolution` state. Still, the `setZoom` and `getZoom`\n * methods are available, as well as `getResolutionForZoom` and\n * `getZoomForResolution` to switch from one system to the other.\n *\n * ### The constraints\n *\n * `setCenter`, `setResolution` and `setRotation` can be used to change the\n * states of the view, but any constraint defined in the constructor will\n * be applied along the way.\n *\n * A View object can have a *resolution constraint*, a *rotation constraint*\n * and a *center constraint*.\n *\n * The *resolution constraint* typically restricts min/max values and\n * snaps to specific resolutions. It is determined by the following\n * options: `resolutions`, `maxResolution`, `maxZoom` and `zoomFactor`.\n * If `resolutions` is set, the other three options are ignored. See\n * documentation for each option for more information. By default, the view\n * only has a min/max restriction and allow intermediary zoom levels when\n * pinch-zooming for example.\n *\n * The *rotation constraint* snaps to specific angles. It is determined\n * by the following options: `enableRotation` and `constrainRotation`.\n * By default rotation is allowed and its value is snapped to zero when approaching the\n * horizontal.\n *\n * The *center constraint* is determined by the `extent` option. By\n * default the view center is not constrained at all.\n *\n * ### Changing the view state\n *\n * It is important to note that `setZoom`, `setResolution`, `setCenter` and\n * `setRotation` are subject to the above mentioned constraints. As such, it\n * may sometimes not be possible to know in advance the resulting state of the\n * View. For example, calling `setResolution(10)` does not guarantee that\n * `getResolution()` will return `10`.\n *\n * A consequence of this is that, when applying a delta on the view state, one\n * should use `adjustCenter`, `adjustRotation`, `adjustZoom` and `adjustResolution`\n * rather than the corresponding setters. This will let view do its internal\n * computations. Besides, the `adjust*` methods also take an `anchor`\n * argument which allows specifying an origin for the transformation.\n *\n * ### Interacting with the view\n *\n * View constraints are usually only applied when the view is *at rest*, meaning that\n * no interaction or animation is ongoing. As such, if the user puts the view in a\n * state that is not equivalent to a constrained one (e.g. rotating the view when\n * the snap angle is 0), an animation will be triggered at the interaction end to\n * put back the view to a stable state;\n *\n * @api\n * @extends {BaseObject<ViewOptions>}\n */\nclass View extends BaseObject {\n  /**\n   * @param {ViewOptions} [options] View options.\n   */\n  constructor(options) {\n    super();\n\n    /***\n     * @type {ViewOnSignature<import(\"./events.js\").EventsKey>}\n     */\n    this.on;\n\n    /***\n     * @type {ViewOnSignature<import(\"./events.js\").EventsKey>}\n     */\n    this.once;\n\n    /***\n     * @type {ViewOnSignature<void>}\n     */\n    this.un;\n\n    options = Object.assign({}, options);\n\n    /**\n     * @private\n     * @type {Array<number>}\n     */\n    this.hints_ = [0, 0];\n\n    /**\n     * @private\n     * @type {Array<Array<Animation>>}\n     */\n    this.animations_ = [];\n\n    /**\n     * @private\n     * @type {number|undefined}\n     */\n    this.updateAnimationKey_;\n\n    /**\n     * @private\n     * @const\n     * @type {import(\"./proj/Projection.js\").default}\n     */\n    this.projection_ = createProjection(options.projection, 'EPSG:3857');\n\n    /**\n     * @private\n     * @type {import(\"./size.js\").Size}\n     */\n    this.viewportSize_ = [100, 100];\n\n    /**\n     * @private\n     * @type {import(\"./coordinate.js\").Coordinate|undefined}\n     */\n    this.targetCenter_ = null;\n\n    /**\n     * @private\n     * @type {number|undefined}\n     */\n    this.targetResolution_;\n\n    /**\n     * @private\n     * @type {number|undefined}\n     */\n    this.targetRotation_;\n\n    /**\n     * @private\n     * @type {import(\"./coordinate.js\").Coordinate}\n     */\n    this.nextCenter_ = null;\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.nextResolution_;\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.nextRotation_;\n\n    /**\n     * @private\n     * @type {import(\"./coordinate.js\").Coordinate|undefined}\n     */\n    this.cancelAnchor_ = undefined;\n\n    if (options.projection) {\n      disableCoordinateWarning();\n    }\n    if (options.center) {\n      options.center = fromUserCoordinate(options.center, this.projection_);\n    }\n    if (options.extent) {\n      options.extent = fromUserExtent(options.extent, this.projection_);\n    }\n\n    this.applyOptions_(options);\n  }\n\n  /**\n   * Set up the view with the given options.\n   * @param {ViewOptions} options View options.\n   */\n  applyOptions_(options) {\n    const properties = Object.assign({}, options);\n    for (const key in ViewProperty) {\n      delete properties[key];\n    }\n    this.setProperties(properties, true);\n\n    const resolutionConstraintInfo = createResolutionConstraint(options);\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.maxResolution_ = resolutionConstraintInfo.maxResolution;\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.minResolution_ = resolutionConstraintInfo.minResolution;\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.zoomFactor_ = resolutionConstraintInfo.zoomFactor;\n\n    /**\n     * @private\n     * @type {Array<number>|undefined}\n     */\n    this.resolutions_ = options.resolutions;\n\n    /**\n     * @type {Array<number>|undefined}\n     * @private\n     */\n    this.padding_ = options.padding;\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.minZoom_ = resolutionConstraintInfo.minZoom;\n\n    const centerConstraint = createCenterConstraint(options);\n    const resolutionConstraint = resolutionConstraintInfo.constraint;\n    const rotationConstraint = createRotationConstraint(options);\n\n    /**\n     * @private\n     * @type {Constraints}\n     */\n    this.constraints_ = {\n      center: centerConstraint,\n      resolution: resolutionConstraint,\n      rotation: rotationConstraint,\n    };\n\n    this.setRotation(options.rotation !== undefined ? options.rotation : 0);\n    this.setCenterInternal(\n      options.center !== undefined ? options.center : null,\n    );\n    if (options.resolution !== undefined) {\n      this.setResolution(options.resolution);\n    } else if (options.zoom !== undefined) {\n      this.setZoom(options.zoom);\n    }\n  }\n\n  /**\n   * Padding (in css pixels).\n   * If the map viewport is partially covered with other content (overlays) along\n   * its edges, this setting allows to shift the center of the viewport away from that\n   * content. The order of the values in the array is top, right, bottom, left.\n   * The default is no padding, which is equivalent to `[0, 0, 0, 0]`.\n   * @type {Array<number>|undefined}\n   * @api\n   */\n  get padding() {\n    return this.padding_;\n  }\n  set padding(padding) {\n    let oldPadding = this.padding_;\n    this.padding_ = padding;\n    const center = this.getCenterInternal();\n    if (center) {\n      const newPadding = padding || [0, 0, 0, 0];\n      oldPadding = oldPadding || [0, 0, 0, 0];\n      const resolution = this.getResolution();\n      const offsetX =\n        (resolution / 2) *\n        (newPadding[3] - oldPadding[3] + oldPadding[1] - newPadding[1]);\n      const offsetY =\n        (resolution / 2) *\n        (newPadding[0] - oldPadding[0] + oldPadding[2] - newPadding[2]);\n      this.setCenterInternal([center[0] + offsetX, center[1] - offsetY]);\n    }\n  }\n\n  /**\n   * Get an updated version of the view options used to construct the view.  The\n   * current resolution (or zoom), center, and rotation are applied to any stored\n   * options.  The provided options can be used to apply new min/max zoom or\n   * resolution limits.\n   * @param {ViewOptions} newOptions New options to be applied.\n   * @return {ViewOptions} New options updated with the current view state.\n   */\n  getUpdatedOptions_(newOptions) {\n    const options = this.getProperties();\n\n    // preserve resolution (or zoom)\n    if (options.resolution !== undefined) {\n      options.resolution = this.getResolution();\n    } else {\n      options.zoom = this.getZoom();\n    }\n\n    // preserve center\n    options.center = this.getCenterInternal();\n\n    // preserve rotation\n    options.rotation = this.getRotation();\n\n    return Object.assign({}, options, newOptions);\n  }\n\n  /**\n   * Animate the view.  The view's center, zoom (or resolution), and rotation\n   * can be animated for smooth transitions between view states.  For example,\n   * to animate the view to a new zoom level:\n   *\n   *     view.animate({zoom: view.getZoom() + 1});\n   *\n   * By default, the animation lasts one second and uses in-and-out easing.  You\n   * can customize this behavior by including `duration` (in milliseconds) and\n   * `easing` options (see {@link module:ol/easing}).\n   *\n   * To chain together multiple animations, call the method with multiple\n   * animation objects.  For example, to first zoom and then pan:\n   *\n   *     view.animate({zoom: 10}, {center: [0, 0]});\n   *\n   * If you provide a function as the last argument to the animate method, it\n   * will get called at the end of an animation series.  The callback will be\n   * called with `true` if the animation series completed on its own or `false`\n   * if it was cancelled.\n   *\n   * Animations are cancelled by user interactions (e.g. dragging the map) or by\n   * calling `view.setCenter()`, `view.setResolution()`, or `view.setRotation()`\n   * (or another method that calls one of these).\n   *\n   * @param {...(AnimationOptions|function(boolean): void)} var_args Animation\n   *     options.  Multiple animations can be run in series by passing multiple\n   *     options objects.  To run multiple animations in parallel, call the method\n   *     multiple times.  An optional callback can be provided as a final\n   *     argument.  The callback will be called with a boolean indicating whether\n   *     the animation completed without being cancelled.\n   * @api\n   */\n  animate(var_args) {\n    if (this.isDef() && !this.getAnimating()) {\n      this.resolveConstraints(0);\n    }\n    const args = new Array(arguments.length);\n    for (let i = 0; i < args.length; ++i) {\n      let options = arguments[i];\n      if (options.center) {\n        options = Object.assign({}, options);\n        options.center = fromUserCoordinate(\n          options.center,\n          this.getProjection(),\n        );\n      }\n      if (options.anchor) {\n        options = Object.assign({}, options);\n        options.anchor = fromUserCoordinate(\n          options.anchor,\n          this.getProjection(),\n        );\n      }\n      args[i] = options;\n    }\n    this.animateInternal.apply(this, args);\n  }\n\n  /**\n   * @param {...(AnimationOptions|function(boolean): void)} var_args Animation options.\n   */\n  animateInternal(var_args) {\n    let animationCount = arguments.length;\n    let callback;\n    if (\n      animationCount > 1 &&\n      typeof arguments[animationCount - 1] === 'function'\n    ) {\n      callback = arguments[animationCount - 1];\n      --animationCount;\n    }\n\n    let i = 0;\n    for (; i < animationCount && !this.isDef(); ++i) {\n      // if view properties are not yet set, shortcut to the final state\n      const state = arguments[i];\n      if (state.center) {\n        this.setCenterInternal(state.center);\n      }\n      if (state.zoom !== undefined) {\n        this.setZoom(state.zoom);\n      } else if (state.resolution) {\n        this.setResolution(state.resolution);\n      }\n      if (state.rotation !== undefined) {\n        this.setRotation(state.rotation);\n      }\n    }\n    if (i === animationCount) {\n      if (callback) {\n        animationCallback(callback, true);\n      }\n      return;\n    }\n\n    let start = Date.now();\n    let center = this.targetCenter_.slice();\n    let resolution = this.targetResolution_;\n    let rotation = this.targetRotation_;\n    const series = [];\n    for (; i < animationCount; ++i) {\n      const options = /** @type {AnimationOptions} */ (arguments[i]);\n\n      const animation = {\n        start: start,\n        complete: false,\n        anchor: options.anchor,\n        duration: options.duration !== undefined ? options.duration : 1000,\n        easing: options.easing || inAndOut,\n        callback: callback,\n      };\n\n      if (options.center) {\n        animation.sourceCenter = center;\n        animation.targetCenter = options.center.slice();\n        center = animation.targetCenter;\n      }\n\n      if (options.zoom !== undefined) {\n        animation.sourceResolution = resolution;\n        animation.targetResolution = this.getResolutionForZoom(options.zoom);\n        resolution = animation.targetResolution;\n      } else if (options.resolution) {\n        animation.sourceResolution = resolution;\n        animation.targetResolution = options.resolution;\n        resolution = animation.targetResolution;\n      }\n\n      if (options.rotation !== undefined) {\n        animation.sourceRotation = rotation;\n        const delta =\n          modulo(options.rotation - rotation + Math.PI, 2 * Math.PI) - Math.PI;\n        animation.targetRotation = rotation + delta;\n        rotation = animation.targetRotation;\n      }\n\n      // check if animation is a no-op\n      if (isNoopAnimation(animation)) {\n        animation.complete = true;\n        // we still push it onto the series for callback handling\n      } else {\n        start += animation.duration;\n      }\n      series.push(animation);\n    }\n    this.animations_.push(series);\n    this.setHint(ViewHint.ANIMATING, 1);\n    this.updateAnimations_();\n  }\n\n  /**\n   * Determine if the view is being animated.\n   * @return {boolean} The view is being animated.\n   * @api\n   */\n  getAnimating() {\n    return this.hints_[ViewHint.ANIMATING] > 0;\n  }\n\n  /**\n   * Determine if the user is interacting with the view, such as panning or zooming.\n   * @return {boolean} The view is being interacted with.\n   * @api\n   */\n  getInteracting() {\n    return this.hints_[ViewHint.INTERACTING] > 0;\n  }\n\n  /**\n   * Cancel any ongoing animations.\n   * @api\n   */\n  cancelAnimations() {\n    this.setHint(ViewHint.ANIMATING, -this.hints_[ViewHint.ANIMATING]);\n    let anchor;\n    for (let i = 0, ii = this.animations_.length; i < ii; ++i) {\n      const series = this.animations_[i];\n      if (series[0].callback) {\n        animationCallback(series[0].callback, false);\n      }\n      if (!anchor) {\n        for (let j = 0, jj = series.length; j < jj; ++j) {\n          const animation = series[j];\n          if (!animation.complete) {\n            anchor = animation.anchor;\n            break;\n          }\n        }\n      }\n    }\n    this.animations_.length = 0;\n    this.cancelAnchor_ = anchor;\n    this.nextCenter_ = null;\n    this.nextResolution_ = NaN;\n    this.nextRotation_ = NaN;\n  }\n\n  /**\n   * Update all animations.\n   */\n  updateAnimations_() {\n    if (this.updateAnimationKey_ !== undefined) {\n      cancelAnimationFrame(this.updateAnimationKey_);\n      this.updateAnimationKey_ = undefined;\n    }\n    if (!this.getAnimating()) {\n      return;\n    }\n    const now = Date.now();\n    let more = false;\n    for (let i = this.animations_.length - 1; i >= 0; --i) {\n      const series = this.animations_[i];\n      let seriesComplete = true;\n      for (let j = 0, jj = series.length; j < jj; ++j) {\n        const animation = series[j];\n        if (animation.complete) {\n          continue;\n        }\n        const elapsed = now - animation.start;\n        let fraction =\n          animation.duration > 0 ? elapsed / animation.duration : 1;\n        if (fraction >= 1) {\n          animation.complete = true;\n          fraction = 1;\n        } else {\n          seriesComplete = false;\n        }\n        const progress = animation.easing(fraction);\n        if (animation.sourceCenter) {\n          const x0 = animation.sourceCenter[0];\n          const y0 = animation.sourceCenter[1];\n          const x1 = animation.targetCenter[0];\n          const y1 = animation.targetCenter[1];\n          this.nextCenter_ = animation.targetCenter;\n          const x = x0 + progress * (x1 - x0);\n          const y = y0 + progress * (y1 - y0);\n          this.targetCenter_ = [x, y];\n        }\n        if (animation.sourceResolution && animation.targetResolution) {\n          const resolution =\n            progress === 1\n              ? animation.targetResolution\n              : animation.sourceResolution +\n                progress *\n                  (animation.targetResolution - animation.sourceResolution);\n          if (animation.anchor) {\n            const size = this.getViewportSize_(this.getRotation());\n            const constrainedResolution = this.constraints_.resolution(\n              resolution,\n              0,\n              size,\n              true,\n            );\n            this.targetCenter_ = this.calculateCenterZoom(\n              constrainedResolution,\n              animation.anchor,\n            );\n          }\n          this.nextResolution_ = animation.targetResolution;\n          this.targetResolution_ = resolution;\n          this.applyTargetState_(true);\n        }\n        if (\n          animation.sourceRotation !== undefined &&\n          animation.targetRotation !== undefined\n        ) {\n          const rotation =\n            progress === 1\n              ? modulo(animation.targetRotation + Math.PI, 2 * Math.PI) -\n                Math.PI\n              : animation.sourceRotation +\n                progress *\n                  (animation.targetRotation - animation.sourceRotation);\n          if (animation.anchor) {\n            const constrainedRotation = this.constraints_.rotation(\n              rotation,\n              true,\n            );\n            this.targetCenter_ = this.calculateCenterRotate(\n              constrainedRotation,\n              animation.anchor,\n            );\n          }\n          this.nextRotation_ = animation.targetRotation;\n          this.targetRotation_ = rotation;\n        }\n        this.applyTargetState_(true);\n        more = true;\n        if (!animation.complete) {\n          break;\n        }\n      }\n      if (seriesComplete) {\n        this.animations_[i] = null;\n        this.setHint(ViewHint.ANIMATING, -1);\n        this.nextCenter_ = null;\n        this.nextResolution_ = NaN;\n        this.nextRotation_ = NaN;\n        const callback = series[0].callback;\n        if (callback) {\n          animationCallback(callback, true);\n        }\n      }\n    }\n    // prune completed series\n    this.animations_ = this.animations_.filter(Boolean);\n    if (more && this.updateAnimationKey_ === undefined) {\n      this.updateAnimationKey_ = requestAnimationFrame(\n        this.updateAnimations_.bind(this),\n      );\n    }\n  }\n\n  /**\n   * @param {number} rotation Target rotation.\n   * @param {import(\"./coordinate.js\").Coordinate} anchor Rotation anchor.\n   * @return {import(\"./coordinate.js\").Coordinate|undefined} Center for rotation and anchor.\n   */\n  calculateCenterRotate(rotation, anchor) {\n    let center;\n    const currentCenter = this.getCenterInternal();\n    if (currentCenter !== undefined) {\n      center = [currentCenter[0] - anchor[0], currentCenter[1] - anchor[1]];\n      rotateCoordinate(center, rotation - this.getRotation());\n      addCoordinate(center, anchor);\n    }\n    return center;\n  }\n\n  /**\n   * @param {number} resolution Target resolution.\n   * @param {import(\"./coordinate.js\").Coordinate} anchor Zoom anchor.\n   * @return {import(\"./coordinate.js\").Coordinate|undefined} Center for resolution and anchor.\n   */\n  calculateCenterZoom(resolution, anchor) {\n    let center;\n    const currentCenter = this.getCenterInternal();\n    const currentResolution = this.getResolution();\n    if (currentCenter !== undefined && currentResolution !== undefined) {\n      const x =\n        anchor[0] -\n        (resolution * (anchor[0] - currentCenter[0])) / currentResolution;\n      const y =\n        anchor[1] -\n        (resolution * (anchor[1] - currentCenter[1])) / currentResolution;\n      center = [x, y];\n    }\n    return center;\n  }\n\n  /**\n   * Returns the current viewport size.\n   * @private\n   * @param {number} [rotation] Take into account the rotation of the viewport when giving the size\n   * @return {import(\"./size.js\").Size} Viewport size or `[100, 100]` when no viewport is found.\n   */\n  getViewportSize_(rotation) {\n    const size = this.viewportSize_;\n    if (rotation) {\n      const w = size[0];\n      const h = size[1];\n      return [\n        Math.abs(w * Math.cos(rotation)) + Math.abs(h * Math.sin(rotation)),\n        Math.abs(w * Math.sin(rotation)) + Math.abs(h * Math.cos(rotation)),\n      ];\n    }\n    return size;\n  }\n\n  /**\n   * Stores the viewport size on the view. The viewport size is not read every time from the DOM\n   * to avoid performance hit and layout reflow.\n   * This should be done on map size change.\n   * Note: the constraints are not resolved during an animation to avoid stopping it\n   * @param {import(\"./size.js\").Size} [size] Viewport size; if undefined, [100, 100] is assumed\n   */\n  setViewportSize(size) {\n    this.viewportSize_ = Array.isArray(size) ? size.slice() : [100, 100];\n    if (!this.getAnimating()) {\n      this.resolveConstraints(0);\n    }\n  }\n\n  /**\n   * Get the view center.\n   * @return {import(\"./coordinate.js\").Coordinate|undefined} The center of the view.\n   * @observable\n   * @api\n   */\n  getCenter() {\n    const center = this.getCenterInternal();\n    if (!center) {\n      return center;\n    }\n    return toUserCoordinate(center, this.getProjection());\n  }\n\n  /**\n   * Get the view center without transforming to user projection.\n   * @return {import(\"./coordinate.js\").Coordinate|undefined} The center of the view.\n   */\n  getCenterInternal() {\n    return /** @type {import(\"./coordinate.js\").Coordinate|undefined} */ (\n      this.get(ViewProperty.CENTER)\n    );\n  }\n\n  /**\n   * @return {Constraints} Constraints.\n   */\n  getConstraints() {\n    return this.constraints_;\n  }\n\n  /**\n   * @return {boolean} Resolution constraint is set\n   */\n  getConstrainResolution() {\n    return this.get('constrainResolution');\n  }\n\n  /**\n   * @param {Array<number>} [hints] Destination array.\n   * @return {Array<number>} Hint.\n   */\n  getHints(hints) {\n    if (hints !== undefined) {\n      hints[0] = this.hints_[0];\n      hints[1] = this.hints_[1];\n      return hints;\n    }\n    return this.hints_.slice();\n  }\n\n  /**\n   * Calculate the extent for the current view state and the passed box size.\n   * @param {import(\"./size.js\").Size} [size] The pixel dimensions of the box\n   * into which the calculated extent should fit. Defaults to the size of the\n   * map the view is associated with.\n   * If no map or multiple maps are connected to the view, provide the desired\n   * box size (e.g. `map.getSize()`).\n   * @return {import(\"./extent.js\").Extent} Extent.\n   * @api\n   */\n  calculateExtent(size) {\n    const extent = this.calculateExtentInternal(size);\n    return toUserExtent(extent, this.getProjection());\n  }\n\n  /**\n   * @param {import(\"./size.js\").Size} [size] Box pixel size. If not provided,\n   * the map's last known viewport size will be used.\n   * @return {import(\"./extent.js\").Extent} Extent.\n   */\n  calculateExtentInternal(size) {\n    size = size || this.getViewportSizeMinusPadding_();\n    const center = /** @type {!import(\"./coordinate.js\").Coordinate} */ (\n      this.getCenterInternal()\n    );\n    assert(center, 'The view center is not defined');\n    const resolution = /** @type {!number} */ (this.getResolution());\n    assert(resolution !== undefined, 'The view resolution is not defined');\n    const rotation = /** @type {!number} */ (this.getRotation());\n    assert(rotation !== undefined, 'The view rotation is not defined');\n\n    return getForViewAndSize(center, resolution, rotation, size);\n  }\n\n  /**\n   * Get the maximum resolution of the view.\n   * @return {number} The maximum resolution of the view.\n   * @api\n   */\n  getMaxResolution() {\n    return this.maxResolution_;\n  }\n\n  /**\n   * Get the minimum resolution of the view.\n   * @return {number} The minimum resolution of the view.\n   * @api\n   */\n  getMinResolution() {\n    return this.minResolution_;\n  }\n\n  /**\n   * Get the maximum zoom level for the view.\n   * @return {number} The maximum zoom level.\n   * @api\n   */\n  getMaxZoom() {\n    return /** @type {number} */ (\n      this.getZoomForResolution(this.minResolution_)\n    );\n  }\n\n  /**\n   * Set a new maximum zoom level for the view.\n   * @param {number} zoom The maximum zoom level.\n   * @api\n   */\n  setMaxZoom(zoom) {\n    this.applyOptions_(this.getUpdatedOptions_({maxZoom: zoom}));\n  }\n\n  /**\n   * Get the minimum zoom level for the view.\n   * @return {number} The minimum zoom level.\n   * @api\n   */\n  getMinZoom() {\n    return /** @type {number} */ (\n      this.getZoomForResolution(this.maxResolution_)\n    );\n  }\n\n  /**\n   * Set a new minimum zoom level for the view.\n   * @param {number} zoom The minimum zoom level.\n   * @api\n   */\n  setMinZoom(zoom) {\n    this.applyOptions_(this.getUpdatedOptions_({minZoom: zoom}));\n  }\n\n  /**\n   * Set whether the view should allow intermediary zoom levels.\n   * @param {boolean} enabled Whether the resolution is constrained.\n   * @api\n   */\n  setConstrainResolution(enabled) {\n    this.applyOptions_(this.getUpdatedOptions_({constrainResolution: enabled}));\n  }\n\n  /**\n   * Get the view projection.\n   * @return {import(\"./proj/Projection.js\").default} The projection of the view.\n   * @api\n   */\n  getProjection() {\n    return this.projection_;\n  }\n\n  /**\n   * Get the view resolution.\n   * @return {number|undefined} The resolution of the view.\n   * @observable\n   * @api\n   */\n  getResolution() {\n    return /** @type {number|undefined} */ (this.get(ViewProperty.RESOLUTION));\n  }\n\n  /**\n   * Get the resolutions for the view. This returns the array of resolutions\n   * passed to the constructor of the View, or undefined if none were given.\n   * @return {Array<number>|undefined} The resolutions of the view.\n   * @api\n   */\n  getResolutions() {\n    return this.resolutions_;\n  }\n\n  /**\n   * Get the resolution for a provided extent (in map units) and size (in pixels).\n   * @param {import(\"./extent.js\").Extent} extent Extent.\n   * @param {import(\"./size.js\").Size} [size] Box pixel size.\n   * @return {number} The resolution at which the provided extent will render at\n   *     the given size.\n   * @api\n   */\n  getResolutionForExtent(extent, size) {\n    return this.getResolutionForExtentInternal(\n      fromUserExtent(extent, this.getProjection()),\n      size,\n    );\n  }\n\n  /**\n   * Get the resolution for a provided extent (in map units) and size (in pixels).\n   * @param {import(\"./extent.js\").Extent} extent Extent.\n   * @param {import(\"./size.js\").Size} [size] Box pixel size.\n   * @return {number} The resolution at which the provided extent will render at\n   *     the given size.\n   */\n  getResolutionForExtentInternal(extent, size) {\n    size = size || this.getViewportSizeMinusPadding_();\n    const xResolution = getWidth(extent) / size[0];\n    const yResolution = getHeight(extent) / size[1];\n    return Math.max(xResolution, yResolution);\n  }\n\n  /**\n   * Return a function that returns a value between 0 and 1 for a\n   * resolution. Exponential scaling is assumed.\n   * @param {number} [power] Power.\n   * @return {function(number): number} Resolution for value function.\n   */\n  getResolutionForValueFunction(power) {\n    power = power || 2;\n    const maxResolution = this.getConstrainedResolution(this.maxResolution_);\n    const minResolution = this.minResolution_;\n    const max = Math.log(maxResolution / minResolution) / Math.log(power);\n    return (\n      /**\n       * @param {number} value Value.\n       * @return {number} Resolution.\n       */\n      function (value) {\n        const resolution = maxResolution / Math.pow(power, value * max);\n        return resolution;\n      }\n    );\n  }\n\n  /**\n   * Get the view rotation.\n   * @return {number} The rotation of the view in radians.\n   * @observable\n   * @api\n   */\n  getRotation() {\n    return /** @type {number} */ (this.get(ViewProperty.ROTATION));\n  }\n\n  /**\n   * Return a function that returns a resolution for a value between\n   * 0 and 1. Exponential scaling is assumed.\n   * @param {number} [power] Power.\n   * @return {function(number): number} Value for resolution function.\n   */\n  getValueForResolutionFunction(power) {\n    const logPower = Math.log(power || 2);\n    const maxResolution = this.getConstrainedResolution(this.maxResolution_);\n    const minResolution = this.minResolution_;\n    const max = Math.log(maxResolution / minResolution) / logPower;\n    return (\n      /**\n       * @param {number} resolution Resolution.\n       * @return {number} Value.\n       */\n      function (resolution) {\n        const value = Math.log(maxResolution / resolution) / logPower / max;\n        return value;\n      }\n    );\n  }\n\n  /**\n   * Returns the size of the viewport minus padding.\n   * @private\n   * @param {number} [rotation] Take into account the rotation of the viewport when giving the size\n   * @return {import(\"./size.js\").Size} Viewport size reduced by the padding.\n   */\n  getViewportSizeMinusPadding_(rotation) {\n    let size = this.getViewportSize_(rotation);\n    const padding = this.padding_;\n    if (padding) {\n      size = [\n        size[0] - padding[1] - padding[3],\n        size[1] - padding[0] - padding[2],\n      ];\n    }\n    return size;\n  }\n\n  /**\n   * @return {State} View state.\n   */\n  getState() {\n    const projection = this.getProjection();\n    const resolution = this.getResolution();\n    const rotation = this.getRotation();\n    let center = /** @type {import(\"./coordinate.js\").Coordinate} */ (\n      this.getCenterInternal()\n    );\n    const padding = this.padding_;\n    if (padding) {\n      const reducedSize = this.getViewportSizeMinusPadding_();\n      center = calculateCenterOn(\n        center,\n        this.getViewportSize_(),\n        [reducedSize[0] / 2 + padding[3], reducedSize[1] / 2 + padding[0]],\n        resolution,\n        rotation,\n      );\n    }\n    return {\n      center: center.slice(0),\n      projection: projection !== undefined ? projection : null,\n      resolution: resolution,\n      nextCenter: this.nextCenter_,\n      nextResolution: this.nextResolution_,\n      nextRotation: this.nextRotation_,\n      rotation: rotation,\n      zoom: this.getZoom(),\n    };\n  }\n\n  /**\n   * @return {ViewStateLayerStateExtent} Like `FrameState`, but just `viewState` and `extent`.\n   */\n  getViewStateAndExtent() {\n    return {\n      viewState: this.getState(),\n      extent: this.calculateExtent(),\n    };\n  }\n\n  /**\n   * Get the current zoom level. This method may return non-integer zoom levels\n   * if the view does not constrain the resolution, or if an interaction or\n   * animation is underway.\n   * @return {number|undefined} Zoom.\n   * @api\n   */\n  getZoom() {\n    let zoom;\n    const resolution = this.getResolution();\n    if (resolution !== undefined) {\n      zoom = this.getZoomForResolution(resolution);\n    }\n    return zoom;\n  }\n\n  /**\n   * Get the zoom level for a resolution.\n   * @param {number} resolution The resolution.\n   * @return {number|undefined} The zoom level for the provided resolution.\n   * @api\n   */\n  getZoomForResolution(resolution) {\n    let offset = this.minZoom_ || 0;\n    let max, zoomFactor;\n    if (this.resolutions_) {\n      const nearest = linearFindNearest(this.resolutions_, resolution, 1);\n      offset = nearest;\n      max = this.resolutions_[nearest];\n      if (nearest == this.resolutions_.length - 1) {\n        zoomFactor = 2;\n      } else {\n        zoomFactor = max / this.resolutions_[nearest + 1];\n      }\n    } else {\n      max = this.maxResolution_;\n      zoomFactor = this.zoomFactor_;\n    }\n    return offset + Math.log(max / resolution) / Math.log(zoomFactor);\n  }\n\n  /**\n   * Get the resolution for a zoom level.\n   * @param {number} zoom Zoom level.\n   * @return {number} The view resolution for the provided zoom level.\n   * @api\n   */\n  getResolutionForZoom(zoom) {\n    if (this.resolutions_?.length) {\n      if (this.resolutions_.length === 1) {\n        return this.resolutions_[0];\n      }\n      const baseLevel = clamp(\n        Math.floor(zoom),\n        0,\n        this.resolutions_.length - 2,\n      );\n      const zoomFactor =\n        this.resolutions_[baseLevel] / this.resolutions_[baseLevel + 1];\n      return (\n        this.resolutions_[baseLevel] /\n        Math.pow(zoomFactor, clamp(zoom - baseLevel, 0, 1))\n      );\n    }\n    return (\n      this.maxResolution_ / Math.pow(this.zoomFactor_, zoom - this.minZoom_)\n    );\n  }\n\n  /**\n   * Fit the given geometry or extent based on the given map size and border.\n   * The size is pixel dimensions of the box to fit the extent into.\n   * In most cases you will want to use the map size, that is `map.getSize()`.\n   * Takes care of the map angle.\n   * @param {import(\"./geom/SimpleGeometry.js\").default|import(\"./extent.js\").Extent} geometryOrExtent The geometry or\n   *     extent to fit the view to.\n   * @param {FitOptions} [options] Options.\n   * @api\n   */\n  fit(geometryOrExtent, options) {\n    /** @type {import(\"./geom/SimpleGeometry.js\").default} */\n    let geometry;\n    assert(\n      Array.isArray(geometryOrExtent) ||\n        typeof (/** @type {?} */ (geometryOrExtent).getSimplifiedGeometry) ===\n          'function',\n      'Invalid extent or geometry provided as `geometry`',\n    );\n    if (Array.isArray(geometryOrExtent)) {\n      assert(\n        !isEmpty(geometryOrExtent),\n        'Cannot fit empty extent provided as `geometry`',\n      );\n      const extent = fromUserExtent(geometryOrExtent, this.getProjection());\n      geometry = polygonFromExtent(extent);\n    } else if (geometryOrExtent.getType() === 'Circle') {\n      const extent = fromUserExtent(\n        geometryOrExtent.getExtent(),\n        this.getProjection(),\n      );\n      geometry = polygonFromExtent(extent);\n      geometry.rotate(this.getRotation(), getCenter(extent));\n    } else {\n      const userProjection = getUserProjection();\n      if (userProjection) {\n        geometry = /** @type {import(\"./geom/SimpleGeometry.js\").default} */ (\n          geometryOrExtent\n            .clone()\n            .transform(userProjection, this.getProjection())\n        );\n      } else {\n        geometry = geometryOrExtent;\n      }\n    }\n\n    this.fitInternal(geometry, options);\n  }\n\n  /**\n   * Calculate rotated extent\n   * @param {import(\"./geom/SimpleGeometry.js\").default} geometry The geometry.\n   * @return {import(\"./extent.js\").Extent} The rotated extent for the geometry.\n   */\n  rotatedExtentForGeometry(geometry) {\n    const rotation = this.getRotation();\n    const cosAngle = Math.cos(rotation);\n    const sinAngle = Math.sin(-rotation);\n    const coords = geometry.getFlatCoordinates();\n    const stride = geometry.getStride();\n    let minRotX = +Infinity;\n    let minRotY = +Infinity;\n    let maxRotX = -Infinity;\n    let maxRotY = -Infinity;\n    for (let i = 0, ii = coords.length; i < ii; i += stride) {\n      const rotX = coords[i] * cosAngle - coords[i + 1] * sinAngle;\n      const rotY = coords[i] * sinAngle + coords[i + 1] * cosAngle;\n      minRotX = Math.min(minRotX, rotX);\n      minRotY = Math.min(minRotY, rotY);\n      maxRotX = Math.max(maxRotX, rotX);\n      maxRotY = Math.max(maxRotY, rotY);\n    }\n    return [minRotX, minRotY, maxRotX, maxRotY];\n  }\n\n  /**\n   * @param {import(\"./geom/SimpleGeometry.js\").default} geometry The geometry.\n   * @param {FitOptions} [options] Options.\n   */\n  fitInternal(geometry, options) {\n    options = options || {};\n    let size = options.size;\n    if (!size) {\n      size = this.getViewportSizeMinusPadding_();\n    }\n    const padding =\n      options.padding !== undefined ? options.padding : [0, 0, 0, 0];\n    const nearest = options.nearest !== undefined ? options.nearest : false;\n    let minResolution;\n    if (options.minResolution !== undefined) {\n      minResolution = options.minResolution;\n    } else if (options.maxZoom !== undefined) {\n      minResolution = this.getResolutionForZoom(options.maxZoom);\n    } else {\n      minResolution = 0;\n    }\n\n    const rotatedExtent = this.rotatedExtentForGeometry(geometry);\n\n    // calculate resolution\n    let resolution = this.getResolutionForExtentInternal(rotatedExtent, [\n      size[0] - padding[1] - padding[3],\n      size[1] - padding[0] - padding[2],\n    ]);\n    resolution = isNaN(resolution)\n      ? minResolution\n      : Math.max(resolution, minResolution);\n    resolution = this.getConstrainedResolution(resolution, nearest ? 0 : 1);\n\n    // calculate center\n    const rotation = this.getRotation();\n    const sinAngle = Math.sin(rotation);\n    const cosAngle = Math.cos(rotation);\n    const centerRot = getCenter(rotatedExtent);\n    centerRot[0] += ((padding[1] - padding[3]) / 2) * resolution;\n    centerRot[1] += ((padding[0] - padding[2]) / 2) * resolution;\n    const centerX = centerRot[0] * cosAngle - centerRot[1] * sinAngle;\n    const centerY = centerRot[1] * cosAngle + centerRot[0] * sinAngle;\n    const center = this.getConstrainedCenter([centerX, centerY], resolution);\n    const callback = options.callback ? options.callback : VOID;\n\n    if (options.duration !== undefined) {\n      this.animateInternal(\n        {\n          resolution: resolution,\n          center: center,\n          duration: options.duration,\n          easing: options.easing,\n        },\n        callback,\n      );\n    } else {\n      this.targetResolution_ = resolution;\n      this.targetCenter_ = center;\n      this.applyTargetState_(false, true);\n      animationCallback(callback, true);\n    }\n  }\n\n  /**\n   * Center on coordinate and view position.\n   * @param {import(\"./coordinate.js\").Coordinate} coordinate Coordinate.\n   * @param {import(\"./size.js\").Size} size Box pixel size.\n   * @param {import(\"./pixel.js\").Pixel} position Position on the view to center on.\n   * @api\n   */\n  centerOn(coordinate, size, position) {\n    this.centerOnInternal(\n      fromUserCoordinate(coordinate, this.getProjection()),\n      size,\n      position,\n    );\n  }\n\n  /**\n   * @param {import(\"./coordinate.js\").Coordinate} coordinate Coordinate.\n   * @param {import(\"./size.js\").Size} size Box pixel size.\n   * @param {import(\"./pixel.js\").Pixel} position Position on the view to center on.\n   */\n  centerOnInternal(coordinate, size, position) {\n    this.setCenterInternal(\n      calculateCenterOn(\n        coordinate,\n        size,\n        position,\n        this.getResolution(),\n        this.getRotation(),\n      ),\n    );\n  }\n\n  /**\n   * Calculates the shift between map and viewport center.\n   * @param {import(\"./coordinate.js\").Coordinate} center Center.\n   * @param {number} resolution Resolution.\n   * @param {number} rotation Rotation.\n   * @param {import(\"./size.js\").Size} size Size.\n   * @return {Array<number>|undefined} Center shift.\n   */\n  calculateCenterShift(center, resolution, rotation, size) {\n    let centerShift;\n    const padding = this.padding_;\n    if (padding && center) {\n      const reducedSize = this.getViewportSizeMinusPadding_(-rotation);\n      const shiftedCenter = calculateCenterOn(\n        center,\n        size,\n        [reducedSize[0] / 2 + padding[3], reducedSize[1] / 2 + padding[0]],\n        resolution,\n        rotation,\n      );\n      centerShift = [\n        center[0] - shiftedCenter[0],\n        center[1] - shiftedCenter[1],\n      ];\n    }\n    return centerShift;\n  }\n\n  /**\n   * @return {boolean} Is defined.\n   */\n  isDef() {\n    return !!this.getCenterInternal() && this.getResolution() !== undefined;\n  }\n\n  /**\n   * Adds relative coordinates to the center of the view. Any extent constraint will apply.\n   * @param {import(\"./coordinate.js\").Coordinate} deltaCoordinates Relative value to add.\n   * @api\n   */\n  adjustCenter(deltaCoordinates) {\n    const center = toUserCoordinate(this.targetCenter_, this.getProjection());\n    this.setCenter([\n      center[0] + deltaCoordinates[0],\n      center[1] + deltaCoordinates[1],\n    ]);\n  }\n\n  /**\n   * Adds relative coordinates to the center of the view. Any extent constraint will apply.\n   * @param {import(\"./coordinate.js\").Coordinate} deltaCoordinates Relative value to add.\n   */\n  adjustCenterInternal(deltaCoordinates) {\n    const center = this.targetCenter_;\n    this.setCenterInternal([\n      center[0] + deltaCoordinates[0],\n      center[1] + deltaCoordinates[1],\n    ]);\n  }\n\n  /**\n   * Multiply the view resolution by a ratio, optionally using an anchor. Any resolution\n   * constraint will apply.\n   * @param {number} ratio The ratio to apply on the view resolution.\n   * @param {import(\"./coordinate.js\").Coordinate} [anchor] The origin of the transformation.\n   * @api\n   */\n  adjustResolution(ratio, anchor) {\n    anchor = anchor && fromUserCoordinate(anchor, this.getProjection());\n    this.adjustResolutionInternal(ratio, anchor);\n  }\n\n  /**\n   * Multiply the view resolution by a ratio, optionally using an anchor. Any resolution\n   * constraint will apply.\n   * @param {number} ratio The ratio to apply on the view resolution.\n   * @param {import(\"./coordinate.js\").Coordinate} [anchor] The origin of the transformation.\n   */\n  adjustResolutionInternal(ratio, anchor) {\n    const isMoving = this.getAnimating() || this.getInteracting();\n    const size = this.getViewportSize_(this.getRotation());\n    const newResolution = this.constraints_.resolution(\n      this.targetResolution_ * ratio,\n      0,\n      size,\n      isMoving,\n    );\n\n    if (anchor) {\n      this.targetCenter_ = this.calculateCenterZoom(newResolution, anchor);\n    }\n\n    this.targetResolution_ *= ratio;\n    this.applyTargetState_();\n  }\n\n  /**\n   * Adds a value to the view zoom level, optionally using an anchor. Any resolution\n   * constraint will apply.\n   * @param {number} delta Relative value to add to the zoom level.\n   * @param {import(\"./coordinate.js\").Coordinate} [anchor] The origin of the transformation.\n   * @api\n   */\n  adjustZoom(delta, anchor) {\n    this.adjustResolution(Math.pow(this.zoomFactor_, -delta), anchor);\n  }\n\n  /**\n   * Adds a value to the view rotation, optionally using an anchor. Any rotation\n   * constraint will apply.\n   * @param {number} delta Relative value to add to the zoom rotation, in radians.\n   * @param {import(\"./coordinate.js\").Coordinate} [anchor] The rotation center.\n   * @api\n   */\n  adjustRotation(delta, anchor) {\n    if (anchor) {\n      anchor = fromUserCoordinate(anchor, this.getProjection());\n    }\n    this.adjustRotationInternal(delta, anchor);\n  }\n\n  /**\n   * @param {number} delta Relative value to add to the zoom rotation, in radians.\n   * @param {import(\"./coordinate.js\").Coordinate} [anchor] The rotation center.\n   */\n  adjustRotationInternal(delta, anchor) {\n    const isMoving = this.getAnimating() || this.getInteracting();\n    const newRotation = this.constraints_.rotation(\n      this.targetRotation_ + delta,\n      isMoving,\n    );\n    if (anchor) {\n      this.targetCenter_ = this.calculateCenterRotate(newRotation, anchor);\n    }\n    this.targetRotation_ += delta;\n    this.applyTargetState_();\n  }\n\n  /**\n   * Set the center of the current view. Any extent constraint will apply.\n   * @param {import(\"./coordinate.js\").Coordinate|undefined} center The center of the view.\n   * @observable\n   * @api\n   */\n  setCenter(center) {\n    this.setCenterInternal(\n      center ? fromUserCoordinate(center, this.getProjection()) : center,\n    );\n  }\n\n  /**\n   * Set the center using the view projection (not the user projection).\n   * @param {import(\"./coordinate.js\").Coordinate|undefined} center The center of the view.\n   */\n  setCenterInternal(center) {\n    this.targetCenter_ = center;\n    this.applyTargetState_();\n  }\n\n  /**\n   * @param {import(\"./ViewHint.js\").default} hint Hint.\n   * @param {number} delta Delta.\n   * @return {number} New value.\n   */\n  setHint(hint, delta) {\n    this.hints_[hint] += delta;\n    this.changed();\n    return this.hints_[hint];\n  }\n\n  /**\n   * Set the resolution for this view. Any resolution constraint will apply.\n   * @param {number|undefined} resolution The resolution of the view.\n   * @observable\n   * @api\n   */\n  setResolution(resolution) {\n    this.targetResolution_ = resolution;\n    this.applyTargetState_();\n  }\n\n  /**\n   * Set the rotation for this view. Any rotation constraint will apply.\n   * @param {number} rotation The rotation of the view in radians.\n   * @observable\n   * @api\n   */\n  setRotation(rotation) {\n    this.targetRotation_ = rotation;\n    this.applyTargetState_();\n  }\n\n  /**\n   * Zoom to a specific zoom level. Any resolution constrain will apply.\n   * @param {number} zoom Zoom level.\n   * @api\n   */\n  setZoom(zoom) {\n    this.setResolution(this.getResolutionForZoom(zoom));\n  }\n\n  /**\n   * Recompute rotation/resolution/center based on target values.\n   * Note: we have to compute rotation first, then resolution and center considering that\n   * parameters can influence one another in case a view extent constraint is present.\n   * @param {boolean} [doNotCancelAnims] Do not cancel animations.\n   * @param {boolean} [forceMoving] Apply constraints as if the view is moving.\n   * @private\n   */\n  applyTargetState_(doNotCancelAnims, forceMoving) {\n    const isMoving =\n      this.getAnimating() || this.getInteracting() || forceMoving;\n\n    // compute rotation\n    const newRotation = this.constraints_.rotation(\n      this.targetRotation_,\n      isMoving,\n    );\n    const size = this.getViewportSize_(newRotation);\n    const newResolution = this.constraints_.resolution(\n      this.targetResolution_,\n      0,\n      size,\n      isMoving,\n    );\n    const newCenter = this.constraints_.center(\n      this.targetCenter_,\n      newResolution,\n      size,\n      isMoving,\n      this.calculateCenterShift(\n        this.targetCenter_,\n        newResolution,\n        newRotation,\n        size,\n      ),\n    );\n\n    if (this.get(ViewProperty.ROTATION) !== newRotation) {\n      this.set(ViewProperty.ROTATION, newRotation);\n    }\n    if (this.get(ViewProperty.RESOLUTION) !== newResolution) {\n      this.set(ViewProperty.RESOLUTION, newResolution);\n      this.set('zoom', this.getZoom(), true);\n    }\n    if (\n      !newCenter ||\n      !this.get(ViewProperty.CENTER) ||\n      !equals(this.get(ViewProperty.CENTER), newCenter)\n    ) {\n      this.set(ViewProperty.CENTER, newCenter);\n    }\n\n    if (this.getAnimating() && !doNotCancelAnims) {\n      this.cancelAnimations();\n    }\n    this.cancelAnchor_ = undefined;\n  }\n\n  /**\n   * If any constraints need to be applied, an animation will be triggered.\n   * This is typically done on interaction end.\n   * Note: calling this with a duration of 0 will apply the constrained values straight away,\n   * without animation.\n   * @param {number} [duration] The animation duration in ms.\n   * @param {number} [resolutionDirection] Which direction to zoom.\n   * @param {import(\"./coordinate.js\").Coordinate} [anchor] The origin of the transformation.\n   */\n  resolveConstraints(duration, resolutionDirection, anchor) {\n    duration = duration !== undefined ? duration : 200;\n    const direction = resolutionDirection || 0;\n\n    const newRotation = this.constraints_.rotation(this.targetRotation_);\n    const size = this.getViewportSize_(newRotation);\n    const newResolution = this.constraints_.resolution(\n      this.targetResolution_,\n      direction,\n      size,\n    );\n    const newCenter = this.constraints_.center(\n      this.targetCenter_,\n      newResolution,\n      size,\n      false,\n      this.calculateCenterShift(\n        this.targetCenter_,\n        newResolution,\n        newRotation,\n        size,\n      ),\n    );\n\n    if (duration === 0 && !this.cancelAnchor_) {\n      this.targetResolution_ = newResolution;\n      this.targetRotation_ = newRotation;\n      this.targetCenter_ = newCenter;\n      this.applyTargetState_();\n      return;\n    }\n\n    anchor = anchor || (duration === 0 ? this.cancelAnchor_ : undefined);\n    this.cancelAnchor_ = undefined;\n\n    if (\n      this.getResolution() !== newResolution ||\n      this.getRotation() !== newRotation ||\n      !this.getCenterInternal() ||\n      !equals(this.getCenterInternal(), newCenter)\n    ) {\n      if (this.getAnimating()) {\n        this.cancelAnimations();\n      }\n\n      this.animateInternal({\n        rotation: newRotation,\n        center: newCenter,\n        resolution: newResolution,\n        duration: duration,\n        easing: easeOut,\n        anchor: anchor,\n      });\n    }\n  }\n\n  /**\n   * Notify the View that an interaction has started.\n   * The view state will be resolved to a stable one if needed\n   * (depending on its constraints).\n   * @api\n   */\n  beginInteraction() {\n    this.resolveConstraints(0);\n\n    this.setHint(ViewHint.INTERACTING, 1);\n  }\n\n  /**\n   * Notify the View that an interaction has ended. The view state will be resolved\n   * to a stable one if needed (depending on its constraints).\n   * @param {number} [duration] Animation duration in ms.\n   * @param {number} [resolutionDirection] Which direction to zoom.\n   * @param {import(\"./coordinate.js\").Coordinate} [anchor] The origin of the transformation.\n   * @api\n   */\n  endInteraction(duration, resolutionDirection, anchor) {\n    anchor = anchor && fromUserCoordinate(anchor, this.getProjection());\n    this.endInteractionInternal(duration, resolutionDirection, anchor);\n  }\n\n  /**\n   * Notify the View that an interaction has ended. The view state will be resolved\n   * to a stable one if needed (depending on its constraints).\n   * @param {number} [duration] Animation duration in ms.\n   * @param {number} [resolutionDirection] Which direction to zoom.\n   * @param {import(\"./coordinate.js\").Coordinate} [anchor] The origin of the transformation.\n   */\n  endInteractionInternal(duration, resolutionDirection, anchor) {\n    if (!this.getInteracting()) {\n      return;\n    }\n    this.setHint(ViewHint.INTERACTING, -1);\n    this.resolveConstraints(duration, resolutionDirection, anchor);\n  }\n\n  /**\n   * Get a valid position for the view center according to the current constraints.\n   * @param {import(\"./coordinate.js\").Coordinate|undefined} targetCenter Target center position.\n   * @param {number} [targetResolution] Target resolution. If not supplied, the current one will be used.\n   * This is useful to guess a valid center position at a different zoom level.\n   * @return {import(\"./coordinate.js\").Coordinate|undefined} Valid center position.\n   */\n  getConstrainedCenter(targetCenter, targetResolution) {\n    const size = this.getViewportSize_(this.getRotation());\n    return this.constraints_.center(\n      targetCenter,\n      targetResolution || this.getResolution(),\n      size,\n    );\n  }\n\n  /**\n   * Get a valid zoom level according to the current view constraints.\n   * @param {number|undefined} targetZoom Target zoom.\n   * @param {number} [direction] Indicate which resolution should be used\n   * by a renderer if the view resolution does not match any resolution of the tile source.\n   * If 0, the nearest resolution will be used. If 1, the nearest lower resolution\n   * will be used. If -1, the nearest higher resolution will be used.\n   * @return {number|undefined} Valid zoom level.\n   */\n  getConstrainedZoom(targetZoom, direction) {\n    const targetRes = this.getResolutionForZoom(targetZoom);\n    return this.getZoomForResolution(\n      this.getConstrainedResolution(targetRes, direction),\n    );\n  }\n\n  /**\n   * Get a valid resolution according to the current view constraints.\n   * @param {number|undefined} targetResolution Target resolution.\n   * @param {number} [direction] Indicate which resolution should be used\n   * by a renderer if the view resolution does not match any resolution of the tile source.\n   * If 0, the nearest resolution will be used. If 1, the nearest lower resolution\n   * will be used. If -1, the nearest higher resolution will be used.\n   * @return {number|undefined} Valid resolution.\n   */\n  getConstrainedResolution(targetResolution, direction) {\n    direction = direction || 0;\n    const size = this.getViewportSize_(this.getRotation());\n\n    return this.constraints_.resolution(targetResolution, direction, size);\n  }\n}\n\n/**\n * @param {Function} callback Callback.\n * @param {*} returnValue Return value.\n */\nfunction animationCallback(callback, returnValue) {\n  setTimeout(function () {\n    callback(returnValue);\n  }, 0);\n}\n\n/**\n * @param {ViewOptions} options View options.\n * @return {import(\"./centerconstraint.js\").Type} The constraint.\n */\nexport function createCenterConstraint(options) {\n  if (options.extent !== undefined) {\n    const smooth =\n      options.smoothExtentConstraint !== undefined\n        ? options.smoothExtentConstraint\n        : true;\n    return createExtent(options.extent, options.constrainOnlyCenter, smooth);\n  }\n\n  const projection = createProjection(options.projection, 'EPSG:3857');\n  if (options.multiWorld !== true && projection.isGlobal()) {\n    const extent = projection.getExtent().slice();\n    extent[0] = -Infinity;\n    extent[2] = Infinity;\n    return createExtent(extent, false, false);\n  }\n\n  return centerNone;\n}\n\n/**\n * @param {ViewOptions} options View options.\n * @return {{constraint: import(\"./resolutionconstraint.js\").Type, maxResolution: number,\n *     minResolution: number, minZoom: number, zoomFactor: number}} The constraint.\n */\nexport function createResolutionConstraint(options) {\n  let resolutionConstraint;\n  let maxResolution;\n  let minResolution;\n\n  // TODO: move these to be ol constants\n  // see https://github.com/openlayers/openlayers/issues/2076\n  const defaultMaxZoom = 28;\n  const defaultZoomFactor = 2;\n\n  let minZoom =\n    options.minZoom !== undefined ? options.minZoom : DEFAULT_MIN_ZOOM;\n\n  let maxZoom =\n    options.maxZoom !== undefined ? options.maxZoom : defaultMaxZoom;\n\n  const zoomFactor =\n    options.zoomFactor !== undefined ? options.zoomFactor : defaultZoomFactor;\n\n  const multiWorld =\n    options.multiWorld !== undefined ? options.multiWorld : false;\n\n  const smooth =\n    options.smoothResolutionConstraint !== undefined\n      ? options.smoothResolutionConstraint\n      : true;\n\n  const showFullExtent =\n    options.showFullExtent !== undefined ? options.showFullExtent : false;\n\n  const projection = createProjection(options.projection, 'EPSG:3857');\n  const projExtent = projection.getExtent();\n  let constrainOnlyCenter = options.constrainOnlyCenter;\n  let extent = options.extent;\n  if (!multiWorld && !extent && projection.isGlobal()) {\n    constrainOnlyCenter = false;\n    extent = projExtent;\n  }\n\n  if (options.resolutions !== undefined) {\n    const resolutions = options.resolutions;\n    maxResolution = resolutions[minZoom];\n    minResolution =\n      resolutions[maxZoom] !== undefined\n        ? resolutions[maxZoom]\n        : resolutions[resolutions.length - 1];\n\n    if (options.constrainResolution) {\n      resolutionConstraint = createSnapToResolutions(\n        resolutions,\n        smooth,\n        !constrainOnlyCenter && extent,\n        showFullExtent,\n      );\n    } else {\n      resolutionConstraint = createMinMaxResolution(\n        maxResolution,\n        minResolution,\n        smooth,\n        !constrainOnlyCenter && extent,\n        showFullExtent,\n      );\n    }\n  } else {\n    // calculate the default min and max resolution\n    const size = !projExtent\n      ? // use an extent that can fit the whole world if need be\n        (360 * METERS_PER_UNIT.degrees) / projection.getMetersPerUnit()\n      : Math.max(getWidth(projExtent), getHeight(projExtent));\n\n    const defaultMaxResolution =\n      size / DEFAULT_TILE_SIZE / Math.pow(defaultZoomFactor, DEFAULT_MIN_ZOOM);\n\n    const defaultMinResolution =\n      defaultMaxResolution /\n      Math.pow(defaultZoomFactor, defaultMaxZoom - DEFAULT_MIN_ZOOM);\n\n    // user provided maxResolution takes precedence\n    maxResolution = options.maxResolution;\n    if (maxResolution !== undefined) {\n      minZoom = 0;\n    } else {\n      maxResolution = defaultMaxResolution / Math.pow(zoomFactor, minZoom);\n    }\n\n    // user provided minResolution takes precedence\n    minResolution = options.minResolution;\n    if (minResolution === undefined) {\n      if (options.maxZoom !== undefined) {\n        if (options.maxResolution !== undefined) {\n          minResolution = maxResolution / Math.pow(zoomFactor, maxZoom);\n        } else {\n          minResolution = defaultMaxResolution / Math.pow(zoomFactor, maxZoom);\n        }\n      } else {\n        minResolution = defaultMinResolution;\n      }\n    }\n\n    // given discrete zoom levels, minResolution may be different than provided\n    maxZoom =\n      minZoom +\n      Math.floor(\n        Math.log(maxResolution / minResolution) / Math.log(zoomFactor),\n      );\n    minResolution = maxResolution / Math.pow(zoomFactor, maxZoom - minZoom);\n\n    if (options.constrainResolution) {\n      resolutionConstraint = createSnapToPower(\n        zoomFactor,\n        maxResolution,\n        minResolution,\n        smooth,\n        !constrainOnlyCenter && extent,\n        showFullExtent,\n      );\n    } else {\n      resolutionConstraint = createMinMaxResolution(\n        maxResolution,\n        minResolution,\n        smooth,\n        !constrainOnlyCenter && extent,\n        showFullExtent,\n      );\n    }\n  }\n  return {\n    constraint: resolutionConstraint,\n    maxResolution: maxResolution,\n    minResolution: minResolution,\n    minZoom: minZoom,\n    zoomFactor: zoomFactor,\n  };\n}\n\n/**\n * @param {ViewOptions} options View options.\n * @return {import(\"./rotationconstraint.js\").Type} Rotation constraint.\n */\nexport function createRotationConstraint(options) {\n  const enableRotation =\n    options.enableRotation !== undefined ? options.enableRotation : true;\n  if (enableRotation) {\n    const constrainRotation = options.constrainRotation;\n    if (constrainRotation === undefined || constrainRotation === true) {\n      return createSnapToZero();\n    }\n    if (constrainRotation === false) {\n      return rotationNone;\n    }\n    if (typeof constrainRotation === 'number') {\n      return createSnapToN(constrainRotation);\n    }\n    return rotationNone;\n  }\n  return disable;\n}\n\n/**\n * Determine if an animation involves no view change.\n * @param {Animation} animation The animation.\n * @return {boolean} The animation involves no view change.\n */\nexport function isNoopAnimation(animation) {\n  if (animation.sourceCenter && animation.targetCenter) {\n    if (!coordinatesEqual(animation.sourceCenter, animation.targetCenter)) {\n      return false;\n    }\n  }\n  if (animation.sourceResolution !== animation.targetResolution) {\n    return false;\n  }\n  if (animation.sourceRotation !== animation.targetRotation) {\n    return false;\n  }\n  return true;\n}\n\n/**\n * @param {import(\"./coordinate.js\").Coordinate} coordinate Coordinate.\n * @param {import(\"./size.js\").Size} size Box pixel size.\n * @param {import(\"./pixel.js\").Pixel} position Position on the view to center on.\n * @param {number} resolution Resolution.\n * @param {number} rotation Rotation.\n * @return {import(\"./coordinate.js\").Coordinate} Shifted center.\n */\nfunction calculateCenterOn(coordinate, size, position, resolution, rotation) {\n  // calculate rotated position\n  const cosAngle = Math.cos(-rotation);\n  let sinAngle = Math.sin(-rotation);\n  let rotX = coordinate[0] * cosAngle - coordinate[1] * sinAngle;\n  let rotY = coordinate[1] * cosAngle + coordinate[0] * sinAngle;\n  rotX += (size[0] / 2 - position[0]) * resolution;\n  rotY += (position[1] - size[1] / 2) * resolution;\n\n  // go back to original angle\n  sinAngle = -sinAngle; // go back to original rotation\n  const centerX = rotX * cosAngle - rotY * sinAngle;\n  const centerY = rotY * cosAngle + rotX * sinAngle;\n\n  return [centerX, centerY];\n}\n\nexport default View;\n\n/**\n * @typedef {function(ViewOptions):ViewOptions} ViewTransform\n */\n\n/**\n * Adds higher resolutions.\n * @param {number} num The number of higher resolution levels to use.\n * @return {ViewTransform} A view transform.\n */\nexport function withHigherResolutions(num) {\n  return function (options) {\n    if (!options.resolutions) {\n      return options;\n    }\n    const resolutions = [...options.resolutions];\n    const highest = resolutions[resolutions.length - 1];\n    for (let i = 0; i < num; ++i) {\n      resolutions.push(highest / Math.pow(2, i + 1));\n    }\n    return {\n      ...options,\n      resolutions,\n    };\n  };\n}\n\n/**\n * Adds lower resolutions.\n * @param {number} num The number of lower resolution levels to use.\n * @return {ViewTransform} A view transform.\n * @api\n */\nexport function withLowerResolutions(num) {\n  return function (options) {\n    if (!options.resolutions) {\n      return options;\n    }\n    const resolutions = [...options.resolutions];\n    const lowest = resolutions[0];\n    for (let i = 0; i < num; ++i) {\n      resolutions.unshift(lowest * Math.pow(2, i + 1));\n    }\n    return {\n      ...options,\n      resolutions,\n    };\n  };\n}\n\n/**\n * Applies a center based on the extent.\n * @return {ViewTransform} A view transform.\n * @api\n */\nexport function withExtentCenter() {\n  return function (options) {\n    if (!options.extent) {\n      return options;\n    }\n    const center = getCenter(options.extent);\n    const newOptions = {...options, center};\n    delete newOptions.extent;\n    return newOptions;\n  };\n}\n\n/**\n * Applies a zoom level.\n * @param {number} z The zoom level.\n * @return {ViewTransform} A view transform.\n * @api\n */\nexport function withZoom(z) {\n  return function (options) {\n    return {...options, zoom: z};\n  };\n}\n\n/**\n * Applies a series of transforms to a view that is resolved from a source.\n * @param {import(\"./source/Source.js\").default} source The source.\n * @param {...ViewTransform} transforms The transforms to apply.\n * @return {Promise<ViewOptions>} The view options.\n * @api\n */\nexport async function getView(source, ...transforms) {\n  let config = await source.getView();\n  for (const transform of transforms) {\n    config = transform(config);\n  }\n  return config;\n}\n", "/**\n * @module ol/css\n */\n\n/**\n * @typedef {Object} FontParameters\n * @property {string} style Style.\n * @property {string} variant Variant.\n * @property {string} weight Weight.\n * @property {string} size Size.\n * @property {string} lineHeight LineHeight.\n * @property {string} family Family.\n * @property {Array<string>} families Families.\n */\n\n/**\n * The CSS class for hidden feature.\n *\n * @const\n * @type {string}\n */\nexport const CLASS_HIDDEN = 'ol-hidden';\n\n/**\n * The CSS class that we'll give the DOM elements to have them selectable.\n *\n * @const\n * @type {string}\n */\nexport const CLASS_SELECTABLE = 'ol-selectable';\n\n/**\n * The CSS class that we'll give the DOM elements to have them unselectable.\n *\n * @const\n * @type {string}\n */\nexport const CLASS_UNSELECTABLE = 'ol-unselectable';\n\n/**\n * The CSS class for unsupported feature.\n *\n * @const\n * @type {string}\n */\nexport const CLASS_UNSUPPORTED = 'ol-unsupported';\n\n/**\n * The CSS class for controls.\n *\n * @const\n * @type {string}\n */\nexport const CLASS_CONTROL = 'ol-control';\n\n/**\n * The CSS class that we'll give the DOM elements that are collapsed, i.e.\n * to those elements which usually can be expanded.\n *\n * @const\n * @type {string}\n */\nexport const CLASS_COLLAPSED = 'ol-collapsed';\n\n/**\n * From https://stackoverflow.com/questions/10135697/regex-to-parse-any-css-font\n * @type {RegExp}\n */\nconst fontRegEx = new RegExp(\n  [\n    '^\\\\s*(?=(?:(?:[-a-z]+\\\\s*){0,2}(italic|oblique))?)',\n    '(?=(?:(?:[-a-z]+\\\\s*){0,2}(small-caps))?)',\n    '(?=(?:(?:[-a-z]+\\\\s*){0,2}(bold(?:er)?|lighter|[1-9]00 ))?)',\n    '(?:(?:normal|\\\\1|\\\\2|\\\\3)\\\\s*){0,3}((?:xx?-)?',\n    '(?:small|large)|medium|smaller|larger|[\\\\.\\\\d]+(?:\\\\%|in|[cem]m|ex|p[ctx]))',\n    '(?:\\\\s*\\\\/\\\\s*(normal|[\\\\.\\\\d]+(?:\\\\%|in|[cem]m|ex|p[ctx])?))',\n    '?\\\\s*([-,\\\\\"\\\\\\'\\\\sa-z0-9]+?)\\\\s*$',\n  ].join(''),\n  'i',\n);\n/** @type {Array<'style'|'variant'|'weight'|'size'|'lineHeight'|'family'>} */\nconst fontRegExMatchIndex = [\n  'style',\n  'variant',\n  'weight',\n  'size',\n  'lineHeight',\n  'family',\n];\n\n/** @type {Object<string|number, number>} */\nexport const fontWeights = {\n  normal: 400,\n  bold: 700,\n};\n\n/**\n * Get the list of font families from a font spec.  Note that this doesn't work\n * for font families that have commas in them.\n * @param {string} fontSpec The CSS font property.\n * @return {FontParameters|null} The font parameters (or null if the input spec is invalid).\n */\nexport const getFontParameters = function (fontSpec) {\n  const match = fontSpec.match(fontRegEx);\n  if (!match) {\n    return null;\n  }\n  const style = /** @type {FontParameters} */ ({\n    lineHeight: 'normal',\n    size: '1.2em',\n    style: 'normal',\n    weight: '400',\n    variant: 'normal',\n  });\n  for (let i = 0, ii = fontRegExMatchIndex.length; i < ii; ++i) {\n    const value = match[i + 1];\n    if (value !== undefined) {\n      style[fontRegExMatchIndex[i]] =\n        typeof value === 'string' ? value.trim() : value;\n    }\n  }\n  if (isNaN(Number(style.weight)) && style.weight in fontWeights) {\n    style.weight = fontWeights[style.weight];\n  }\n  style.families = style.family\n    .split(/,\\s?/)\n    .map((f) => f.trim().replace(/^['\"]|['\"]$/g, ''));\n  return style;\n};\n", "import {WORKER_OFFSCREEN_CANVAS} from './has.js';\n\n/**\n * @module ol/dom\n */\n\n/**\n * @typedef {Object} ImageAttributes\n * @property {string|null} [crossOrigin] Cross origin.\n * @property {ReferrerPolicy} [referrerPolicy]  Referrer policy.\n */\n\n//FIXME Move this function to the canvas module\n/**\n * Create an html canvas element and returns its 2d context.\n * @param {number} [width] Canvas width.\n * @param {number} [height] Canvas height.\n * @param {Array<HTMLCanvasElement|OffscreenCanvas>} [canvasPool] Canvas pool to take existing canvas from.\n * @param {CanvasRenderingContext2DSettings} [settings] CanvasRenderingContext2DSettings\n * @return {CanvasRenderingContext2D|OffscreenCanvasRenderingContext2D} The context.\n */\nexport function createCanvasContext2D(width, height, canvasPool, settings) {\n  /** @type {HTMLCanvasElement|OffscreenCanvas} */\n  let canvas;\n  if (canvasPool && canvasPool.length) {\n    canvas = /** @type {HTMLCanvasElement} */ (canvasPool.shift());\n  } else if (WORKER_OFFSCREEN_CANVAS) {\n    canvas = new (class extends OffscreenCanvas {\n      style = {};\n    })(width ?? 300, height ?? 150);\n  } else {\n    canvas = document.createElement('canvas');\n  }\n  if (width) {\n    canvas.width = width;\n  }\n  if (height) {\n    canvas.height = height;\n  }\n  return /** @type {CanvasRenderingContext2D|OffscreenCanvasRenderingContext2D} */ (\n    canvas.getContext('2d', settings)\n  );\n}\n\n/**\n * @type {CanvasRenderingContext2D|OffscreenCanvasRenderingContext2D}\n */\nlet sharedCanvasContext;\n\n/**\n * @return {CanvasRenderingContext2D|OffscreenCanvasRenderingContext2D} Shared canvas context.\n */\nexport function getSharedCanvasContext2D() {\n  if (!sharedCanvasContext) {\n    sharedCanvasContext = createCanvasContext2D(1, 1);\n  }\n  return sharedCanvasContext;\n}\n\n/**\n * Releases canvas memory to avoid exceeding memory limits in Safari.\n * See https://pqina.nl/blog/total-canvas-memory-use-exceeds-the-maximum-limit/\n * @param {CanvasRenderingContext2D|OffscreenCanvasRenderingContext2D} context Context.\n */\nexport function releaseCanvas(context) {\n  const canvas = context.canvas;\n  canvas.width = 1;\n  canvas.height = 1;\n  context.clearRect(0, 0, 1, 1);\n}\n\n/**\n * Get the current computed width for the given element including margin,\n * padding and border.\n * Equivalent to jQuery's `$(el).outerWidth(true)`.\n * @param {!HTMLElement} element Element.\n * @return {number} The width.\n */\nexport function outerWidth(element) {\n  let width = element.offsetWidth;\n  const style = getComputedStyle(element);\n  width += parseInt(style.marginLeft, 10) + parseInt(style.marginRight, 10);\n\n  return width;\n}\n\n/**\n * Get the current computed height for the given element including margin,\n * padding and border.\n * Equivalent to jQuery's `$(el).outerHeight(true)`.\n * @param {!HTMLElement} element Element.\n * @return {number} The height.\n */\nexport function outerHeight(element) {\n  let height = element.offsetHeight;\n  const style = getComputedStyle(element);\n  height += parseInt(style.marginTop, 10) + parseInt(style.marginBottom, 10);\n\n  return height;\n}\n\n/**\n * @param {Node} newNode Node to replace old node\n * @param {Node} oldNode The node to be replaced\n */\nexport function replaceNode(newNode, oldNode) {\n  const parent = oldNode.parentNode;\n  if (parent) {\n    parent.replaceChild(newNode, oldNode);\n  }\n}\n\n/**\n * @param {Node} node The node to remove the children from.\n */\nexport function removeChildren(node) {\n  while (node.lastChild) {\n    node.lastChild.remove();\n  }\n}\n\n/**\n * Transform the children of a parent node so they match the\n * provided list of children.  This function aims to efficiently\n * remove, add, and reorder child nodes while maintaining a simple\n * implementation (it is not guaranteed to minimize DOM operations).\n * @param {Node} node The parent node whose children need reworking.\n * @param {Array<Node>} children The desired children.\n */\nexport function replaceChildren(node, children) {\n  const oldChildren = node.childNodes;\n\n  for (let i = 0; true; ++i) {\n    const oldChild = oldChildren[i];\n    const newChild = children[i];\n\n    // check if our work is done\n    if (!oldChild && !newChild) {\n      break;\n    }\n\n    // check if children match\n    if (oldChild === newChild) {\n      continue;\n    }\n\n    // check if a new child needs to be added\n    if (!oldChild) {\n      node.appendChild(newChild);\n      continue;\n    }\n\n    // check if an old child needs to be removed\n    if (!newChild) {\n      node.removeChild(oldChild);\n      --i;\n      continue;\n    }\n\n    // reorder\n    node.insertBefore(newChild, oldChild);\n  }\n}\n\n/**\n * Creates a minimal structure that mocks a DIV to be used by the composite and\n * layer renderer in a worker environment\n * @return {HTMLDivElement} mocked DIV\n */\nexport function createMockDiv() {\n  const mockedDiv = new Proxy(\n    {\n      /**\n       * @type {Array<HTMLElement>}\n       */\n      childNodes: [],\n      /**\n       * @param {HTMLElement} node html node.\n       * @return {HTMLElement} html node.\n       */\n      appendChild: function (node) {\n        this.childNodes.push(node);\n        return node;\n      },\n      /**\n       * dummy function, as this structure is not supposed to have a parent.\n       */\n      remove: function () {},\n      /**\n       * @param {HTMLElement} node html node.\n       * @return {HTMLElement} html node.\n       */\n      removeChild: function (node) {\n        const index = this.childNodes.indexOf(node);\n        if (index === -1) {\n          throw new Error('Node to remove was not found');\n        }\n        this.childNodes.splice(index, 1);\n        return node;\n      },\n      /**\n       * @param {HTMLElement} newNode new html node.\n       * @param {HTMLElement} referenceNode reference html node.\n       * @return {HTMLElement} new html node.\n       */\n      insertBefore: function (newNode, referenceNode) {\n        const index = this.childNodes.indexOf(referenceNode);\n        if (index === -1) {\n          throw new Error('Reference node not found');\n        }\n        this.childNodes.splice(index, 0, newNode);\n        return newNode;\n      },\n      style: {},\n    },\n    {\n      get(target, prop, receiver) {\n        if (prop === 'firstElementChild') {\n          return target.childNodes.length > 0 ? target.childNodes[0] : null;\n        }\n        return Reflect.get(target, prop, receiver);\n      },\n    },\n  );\n  return /** @type {HTMLDivElement} */ (/** @type {*} */ (mockedDiv));\n}\n\n/***\n * @param {*} obj The object to check.\n * @return {obj is (HTMLCanvasElement | OffscreenCanvas)} The object is a canvas.\n */\nexport function isCanvas(obj) {\n  return (\n    (typeof HTMLCanvasElement !== 'undefined' &&\n      obj instanceof HTMLCanvasElement) ||\n    (typeof OffscreenCanvas !== 'undefined' && obj instanceof OffscreenCanvas)\n  );\n}\n", "/**\n * @module ol/control/Control\n */\nimport MapEventType from '../MapEventType.js';\nimport BaseObject from '../Object.js';\nimport {listen, unlistenByKey} from '../events.js';\nimport {VOID} from '../functions.js';\n\n/**\n * @typedef {Object} Options\n * @property {HTMLElement} [element] The element is the control's\n * container element. This only needs to be specified if you're developing\n * a custom control.\n * @property {function(import(\"../MapEvent.js\").default):void} [render] Function called when\n * the control should be re-rendered. This is called in a `requestAnimationFrame`\n * callback.\n * @property {HTMLElement|string} [target] Specify a target if you want\n * the control to be rendered outside of the map's viewport.\n */\n\n/**\n * @classdesc\n * A control is a visible widget with a DOM element in a fixed position on the\n * screen. They can involve user input (buttons), or be informational only;\n * the position is determined using CSS. By default these are placed in the\n * container with CSS class name `ol-overlaycontainer-stopevent`, but can use\n * any outside DOM element.\n *\n * This is the base class for controls. You can use it for simple custom\n * controls by creating the element with listeners, creating an instance:\n * ```js\n * const myControl = new Control({element: myElement});\n * ```\n * and then adding this to the map.\n *\n * The main advantage of having this as a control rather than a simple separate\n * DOM element is that preventing propagation is handled for you. Controls\n * will also be objects in a {@link module:ol/Collection~Collection}, so you can use their methods.\n *\n * You can also extend this base for your own control class. See\n * examples/custom-controls for an example of how to do this.\n *\n * @api\n */\nclass Control extends BaseObject {\n  /**\n   * @param {Options} options Control options.\n   */\n  constructor(options) {\n    super();\n\n    const element = options.element;\n    if (element && !options.target && !element.style.pointerEvents) {\n      element.style.pointerEvents = 'auto';\n    }\n\n    /**\n     * @protected\n     * @type {HTMLElement}\n     */\n    this.element = element ? element : null;\n\n    /**\n     * @private\n     * @type {HTMLElement}\n     */\n    this.target_ = null;\n\n    /**\n     * @private\n     * @type {import(\"../Map.js\").default|null}\n     */\n    this.map_ = null;\n\n    /**\n     * @protected\n     * @type {!Array<import(\"../events.js\").EventsKey>}\n     */\n    this.listenerKeys = [];\n\n    if (options.render) {\n      this.render = options.render;\n    }\n\n    if (options.target) {\n      this.setTarget(options.target);\n    }\n  }\n\n  /**\n   * Clean up.\n   * @override\n   */\n  disposeInternal() {\n    this.element?.remove();\n    super.disposeInternal();\n  }\n\n  /**\n   * Get the map associated with this control.\n   * @return {import(\"../Map.js\").default|null} Map.\n   * @api\n   */\n  getMap() {\n    return this.map_;\n  }\n\n  /**\n   * Remove the control from its current map and attach it to the new map.\n   * Pass `null` to just remove the control from the current map.\n   * Subclasses may set up event handlers to get notified about changes to\n   * the map here.\n   * @param {import(\"../Map.js\").default|null} map Map.\n   * @api\n   */\n  setMap(map) {\n    if (this.map_) {\n      this.element?.remove();\n    }\n    for (let i = 0, ii = this.listenerKeys.length; i < ii; ++i) {\n      unlistenByKey(this.listenerKeys[i]);\n    }\n    this.listenerKeys.length = 0;\n    this.map_ = map;\n    if (map) {\n      const target = this.target_ ?? map.getOverlayContainerStopEvent();\n      if (this.element) {\n        target.appendChild(this.element);\n      }\n      if (this.render !== VOID) {\n        this.listenerKeys.push(\n          listen(map, MapEventType.POSTRENDER, this.render, this),\n        );\n      }\n      map.render();\n    }\n  }\n\n  /**\n   * Renders the control.\n   * @param {import(\"../MapEvent.js\").default} mapEvent Map event.\n   * @api\n   */\n  render(mapEvent) {}\n\n  /**\n   * This function is used to set a target element for the control. It has no\n   * effect if it is called after the control has been added to the map (i.e.\n   * after `setMap` is called on the control). If no `target` is set in the\n   * options passed to the control constructor and if `setTarget` is not called\n   * then the control is added to the map's overlay container.\n   * @param {HTMLElement|string} target Target.\n   * @api\n   */\n  setTarget(target) {\n    this.target_ =\n      typeof target === 'string' ? document.getElementById(target) : target;\n  }\n}\n\nexport default Control;\n", "/**\n * @module ol/control/Attribution\n */\nimport {equals} from '../array.js';\nimport {CLASS_COLLAPSED, CLASS_CONTROL, CLASS_UNSELECTABLE} from '../css.js';\nimport {removeChildren, replaceNode} from '../dom.js';\nimport EventType from '../events/EventType.js';\nimport {toPromise} from '../functions.js';\nimport Control from './Control.js';\n\n/**\n * @typedef {Object} Options\n * @property {string} [className='ol-attribution'] CSS class name.\n * @property {HTMLElement|string} [target] Specify a target if you\n * want the control to be rendered outside of the map's\n * viewport.\n * @property {boolean} [collapsible] Specify if attributions can\n * be collapsed. If not specified, sources control this behavior with their\n * `attributionsCollapsible` setting.\n * @property {boolean} [collapsed=true] Specify if attributions should\n * be collapsed at startup.\n * @property {string} [tipLabel='Attributions'] Text label to use for the button tip.\n * @property {string|HTMLElement} [label='i'] Text label to use for the\n * collapsed attributions button.\n * Instead of text, also an element (e.g. a `span` element) can be used.\n * @property {string} [expandClassName=className + '-expand'] CSS class name for the\n * collapsed attributions button.\n * @property {string|HTMLElement} [collapseLabel='\u203A'] Text label to use\n * for the expanded attributions button.\n * Instead of text, also an element (e.g. a `span` element) can be used.\n * @property {string} [collapseClassName=className + '-collapse'] CSS class name for the\n * expanded attributions button.\n * @property {function(import(\"../MapEvent.js\").default):void} [render] Function called when\n * the control should be re-rendered. This is called in a `requestAnimationFrame`\n * callback.\n * @property {string|Array<string>|undefined} [attributions] Optional attribution(s) that will always be\n * displayed regardless of the layers rendered.\n * **Caution:** Attributions are rendered dynamically using `innerHTML`, which can lead to potential\n * [**XSS (Cross-Site Scripting)**](https://en.wikipedia.org/wiki/Cross-site_scripting) vulnerabilities.\n * Use this feature only for trusted content\n * or ensure that the content is properly sanitized before inserting it.\n */\n\n/**\n * @classdesc\n * Control to show all the attributions associated with the layer sources\n * in the map. This control is one of the default controls included in maps.\n * By default it will show in the bottom right portion of the map, but this can\n * be changed by using a css selector for `.ol-attribution`.\n *\n * @api\n */\nclass Attribution extends Control {\n  /**\n   * @param {Options} [options] Attribution options.\n   */\n  constructor(options) {\n    options = options ? options : {};\n\n    super({\n      element: document.createElement('div'),\n      render: options.render,\n      target: options.target,\n    });\n\n    /**\n     * @private\n     * @type {HTMLElement}\n     */\n    this.ulElement_ = document.createElement('ul');\n\n    /**\n     * @private\n     * @type {boolean}\n     */\n    this.collapsed_ =\n      options.collapsed !== undefined ? options.collapsed : true;\n\n    /**\n     * @private\n     * @type {boolean}\n     */\n    this.userCollapsed_ = this.collapsed_;\n\n    /**\n     * @private\n     * @type {boolean}\n     */\n    this.overrideCollapsible_ = options.collapsible !== undefined;\n\n    /**\n     * @private\n     * @type {boolean}\n     */\n    this.collapsible_ =\n      options.collapsible !== undefined ? options.collapsible : true;\n\n    if (!this.collapsible_) {\n      this.collapsed_ = false;\n    }\n\n    /**\n     * @private\n     * @type {string | Array<string> | undefined}\n     */\n    this.attributions_ = options.attributions;\n\n    const className =\n      options.className !== undefined ? options.className : 'ol-attribution';\n\n    const tipLabel =\n      options.tipLabel !== undefined ? options.tipLabel : 'Attributions';\n\n    const expandClassName =\n      options.expandClassName !== undefined\n        ? options.expandClassName\n        : className + '-expand';\n\n    const collapseLabel =\n      options.collapseLabel !== undefined ? options.collapseLabel : '\\u203A';\n\n    const collapseClassName =\n      options.collapseClassName !== undefined\n        ? options.collapseClassName\n        : className + '-collapse';\n\n    if (typeof collapseLabel === 'string') {\n      /**\n       * @private\n       * @type {HTMLElement}\n       */\n      this.collapseLabel_ = document.createElement('span');\n      this.collapseLabel_.textContent = collapseLabel;\n      this.collapseLabel_.className = collapseClassName;\n    } else {\n      this.collapseLabel_ = collapseLabel;\n    }\n\n    const label = options.label !== undefined ? options.label : 'i';\n\n    if (typeof label === 'string') {\n      /**\n       * @private\n       * @type {HTMLElement}\n       */\n      this.label_ = document.createElement('span');\n      this.label_.textContent = label;\n      this.label_.className = expandClassName;\n    } else {\n      this.label_ = label;\n    }\n\n    const activeLabel =\n      this.collapsible_ && !this.collapsed_ ? this.collapseLabel_ : this.label_;\n\n    /**\n     * @private\n     * @type {HTMLElement}\n     */\n    this.toggleButton_ = document.createElement('button');\n    this.toggleButton_.setAttribute('type', 'button');\n    this.toggleButton_.setAttribute('aria-expanded', String(!this.collapsed_));\n    this.toggleButton_.title = tipLabel;\n    this.toggleButton_.appendChild(activeLabel);\n\n    this.toggleButton_.addEventListener(\n      EventType.CLICK,\n      this.handleClick_.bind(this),\n      false,\n    );\n\n    const cssClasses =\n      className +\n      ' ' +\n      CLASS_UNSELECTABLE +\n      ' ' +\n      CLASS_CONTROL +\n      (this.collapsed_ && this.collapsible_ ? ' ' + CLASS_COLLAPSED : '') +\n      (this.collapsible_ ? '' : ' ol-uncollapsible');\n    const element = this.element;\n    element.className = cssClasses;\n    element.appendChild(this.toggleButton_);\n    element.appendChild(this.ulElement_);\n\n    /**\n     * A list of currently rendered resolutions.\n     * @type {Array<string>}\n     * @private\n     */\n    this.renderedAttributions_ = [];\n\n    /**\n     * @private\n     * @type {boolean}\n     */\n    this.renderedVisible_ = true;\n  }\n\n  /**\n   * Collect a list of visible attributions and set the collapsible state.\n   * @param {import(\"../Map.js\").FrameState} frameState Frame state.\n   * @return {Array<string>} Attributions.\n   * @private\n   */\n  collectSourceAttributions_(frameState) {\n    const layers = this.getMap().getAllLayers();\n    const visibleAttributions = new Set(\n      layers.flatMap((layer) => layer.getAttributions(frameState)),\n    );\n    if (this.attributions_ !== undefined) {\n      Array.isArray(this.attributions_)\n        ? this.attributions_.forEach((item) => visibleAttributions.add(item))\n        : visibleAttributions.add(this.attributions_);\n    }\n\n    if (!this.overrideCollapsible_) {\n      const collapsible = !layers.some(\n        (layer) => layer.getSource()?.getAttributionsCollapsible() === false,\n      );\n      this.setCollapsible(collapsible);\n    }\n    return Array.from(visibleAttributions);\n  }\n\n  /**\n   * @private\n   * @param {?import(\"../Map.js\").FrameState} frameState Frame state.\n   */\n  async updateElement_(frameState) {\n    if (!frameState) {\n      if (this.renderedVisible_) {\n        this.element.style.display = 'none';\n        this.renderedVisible_ = false;\n      }\n      return;\n    }\n\n    const attributions = await Promise.all(\n      this.collectSourceAttributions_(frameState).map((attribution) =>\n        toPromise(() => attribution),\n      ),\n    );\n\n    const visible = attributions.length > 0;\n    if (this.renderedVisible_ != visible) {\n      this.element.style.display = visible ? '' : 'none';\n      this.renderedVisible_ = visible;\n    }\n\n    if (equals(attributions, this.renderedAttributions_)) {\n      return;\n    }\n\n    removeChildren(this.ulElement_);\n\n    // append the attributions\n    for (let i = 0, ii = attributions.length; i < ii; ++i) {\n      const element = document.createElement('li');\n      element.innerHTML = attributions[i];\n      this.ulElement_.appendChild(element);\n    }\n\n    this.renderedAttributions_ = attributions;\n  }\n\n  /**\n   * @param {MouseEvent} event The event to handle\n   * @private\n   */\n  handleClick_(event) {\n    event.preventDefault();\n    this.handleToggle_();\n    this.userCollapsed_ = this.collapsed_;\n  }\n\n  /**\n   * @private\n   */\n  handleToggle_() {\n    this.element.classList.toggle(CLASS_COLLAPSED);\n    if (this.collapsed_) {\n      replaceNode(this.collapseLabel_, this.label_);\n    } else {\n      replaceNode(this.label_, this.collapseLabel_);\n    }\n    this.collapsed_ = !this.collapsed_;\n    this.toggleButton_.setAttribute('aria-expanded', String(!this.collapsed_));\n  }\n\n  /**\n   * Return `true` if the attribution is collapsible, `false` otherwise.\n   * @return {boolean} True if the widget is collapsible.\n   * @api\n   */\n  getCollapsible() {\n    return this.collapsible_;\n  }\n\n  /**\n   * Set whether the attribution should be collapsible.\n   * @param {boolean} collapsible True if the widget is collapsible.\n   * @api\n   */\n  setCollapsible(collapsible) {\n    if (this.collapsible_ === collapsible) {\n      return;\n    }\n    this.collapsible_ = collapsible;\n    this.element.classList.toggle('ol-uncollapsible');\n    if (this.userCollapsed_) {\n      this.handleToggle_();\n    }\n  }\n\n  /**\n   * Collapse or expand the attribution according to the passed parameter. Will\n   * not do anything if the attribution isn't collapsible or if the current\n   * collapsed state is already the one requested.\n   * @param {boolean} collapsed True if the widget is collapsed.\n   * @api\n   */\n  setCollapsed(collapsed) {\n    this.userCollapsed_ = collapsed;\n    if (!this.collapsible_ || this.collapsed_ === collapsed) {\n      return;\n    }\n    this.handleToggle_();\n  }\n\n  /**\n   * Return `true` when the attribution is currently collapsed or `false`\n   * otherwise.\n   * @return {boolean} True if the widget is collapsed.\n   * @api\n   */\n  getCollapsed() {\n    return this.collapsed_;\n  }\n\n  /**\n   * Update the attribution element.\n   * @param {import(\"../MapEvent.js\").default} mapEvent Map event.\n   * @override\n   */\n  render(mapEvent) {\n    this.updateElement_(mapEvent.frameState);\n  }\n}\n\nexport default Attribution;\n", "/**\n * @module ol/control/Rotate\n */\nimport {CLASS_CONTROL, CLASS_HIDDEN, CLASS_UNSELECTABLE} from '../css.js';\nimport {easeOut} from '../easing.js';\nimport EventType from '../events/EventType.js';\nimport Control from './Control.js';\n\n/**\n * @typedef {Object} Options\n * @property {string} [className='ol-rotate'] CSS class name.\n * @property {string|HTMLElement} [label='\u21E7'] Text label to use for the rotate button.\n * Instead of text, also an element (e.g. a `span` element) can be used.\n * @property {string} [tipLabel='Reset rotation'] Text label to use for the rotate tip.\n * @property {string} [compassClassName='ol-compass'] CSS class name for the compass.\n * @property {number} [duration=250] Animation duration in milliseconds.\n * @property {boolean} [autoHide=true] Hide the control when rotation is 0.\n * @property {function(import(\"../MapEvent.js\").default):void} [render] Function called when the control should\n * be re-rendered. This is called in a `requestAnimationFrame` callback.\n * @property {function():void} [resetNorth] Function called when the control is clicked.\n * This will override the default `resetNorth`.\n * @property {HTMLElement|string} [target] Specify a target if you want the control to be\n * rendered outside of the map's viewport.\n */\n\n/**\n * @classdesc\n * A button control to reset rotation to 0.\n * To style this control use css selector `.ol-rotate`. A `.ol-hidden` css\n * selector is added to the button when the rotation is 0.\n *\n * @api\n */\nclass Rotate extends Control {\n  /**\n   * @param {Options} [options] Rotate options.\n   */\n  constructor(options) {\n    options = options ? options : {};\n\n    super({\n      element: document.createElement('div'),\n      render: options.render,\n      target: options.target,\n    });\n\n    const className =\n      options.className !== undefined ? options.className : 'ol-rotate';\n\n    const label = options.label !== undefined ? options.label : '\\u21E7';\n\n    const compassClassName =\n      options.compassClassName !== undefined\n        ? options.compassClassName\n        : 'ol-compass';\n\n    /**\n     * @type {HTMLElement}\n     * @private\n     */\n    this.label_ = null;\n\n    if (typeof label === 'string') {\n      this.label_ = document.createElement('span');\n      this.label_.className = compassClassName;\n      this.label_.textContent = label;\n    } else {\n      this.label_ = label;\n      this.label_.classList.add(compassClassName);\n    }\n\n    const tipLabel = options.tipLabel ? options.tipLabel : 'Reset rotation';\n\n    const button = document.createElement('button');\n    button.className = className + '-reset';\n    button.setAttribute('type', 'button');\n    button.title = tipLabel;\n    button.appendChild(this.label_);\n\n    button.addEventListener(\n      EventType.CLICK,\n      this.handleClick_.bind(this),\n      false,\n    );\n\n    const cssClasses =\n      className + ' ' + CLASS_UNSELECTABLE + ' ' + CLASS_CONTROL;\n    const element = this.element;\n    element.className = cssClasses;\n    element.appendChild(button);\n\n    /**\n     * @private\n     */\n    this.callResetNorth_ = options.resetNorth ? options.resetNorth : undefined;\n\n    /**\n     * @type {number}\n     * @private\n     */\n    this.duration_ = options.duration !== undefined ? options.duration : 250;\n\n    /**\n     * @type {boolean}\n     * @private\n     */\n    this.autoHide_ = options.autoHide !== undefined ? options.autoHide : true;\n\n    /**\n     * @private\n     * @type {number|undefined}\n     */\n    this.rotation_ = undefined;\n\n    if (this.autoHide_) {\n      this.element.classList.add(CLASS_HIDDEN);\n    }\n  }\n\n  /**\n   * @param {MouseEvent} event The event to handle\n   * @private\n   */\n  handleClick_(event) {\n    event.preventDefault();\n    if (this.callResetNorth_ !== undefined) {\n      this.callResetNorth_();\n    } else {\n      this.resetNorth_();\n    }\n  }\n\n  /**\n   * @private\n   */\n  resetNorth_() {\n    const map = this.getMap();\n    const view = map.getView();\n    if (!view) {\n      // the map does not have a view, so we can't act\n      // upon it\n      return;\n    }\n    const rotation = view.getRotation();\n    if (rotation !== undefined) {\n      if (this.duration_ > 0 && rotation % (2 * Math.PI) !== 0) {\n        view.animate({\n          rotation: 0,\n          duration: this.duration_,\n          easing: easeOut,\n        });\n      } else {\n        view.setRotation(0);\n      }\n    }\n  }\n\n  /**\n   * Update the rotate control element.\n   * @param {import(\"../MapEvent.js\").default} mapEvent Map event.\n   * @override\n   */\n  render(mapEvent) {\n    const frameState = mapEvent.frameState;\n    if (!frameState) {\n      return;\n    }\n    const rotation = frameState.viewState.rotation;\n    if (rotation != this.rotation_) {\n      const transform = 'rotate(' + rotation + 'rad)';\n      if (this.autoHide_) {\n        const contains = this.element.classList.contains(CLASS_HIDDEN);\n        if (!contains && rotation === 0) {\n          this.element.classList.add(CLASS_HIDDEN);\n        } else if (contains && rotation !== 0) {\n          this.element.classList.remove(CLASS_HIDDEN);\n        }\n      }\n      this.label_.style.transform = transform;\n    }\n    this.rotation_ = rotation;\n  }\n}\n\nexport default Rotate;\n", "/**\n * @module ol/control/Zoom\n */\nimport {CLASS_CONTROL, CLASS_UNSELECTABLE} from '../css.js';\nimport {easeOut} from '../easing.js';\nimport EventType from '../events/EventType.js';\nimport Control from './Control.js';\n\n/**\n * @typedef {Object} Options\n * @property {number} [duration=250] Animation duration in milliseconds.\n * @property {string} [className='ol-zoom'] CSS class name.\n * @property {string} [zoomInClassName=className + '-in'] CSS class name for the zoom-in button.\n * @property {string} [zoomOutClassName=className + '-out'] CSS class name for the zoom-out button.\n * @property {string|HTMLElement} [zoomInLabel='+'] Text label to use for the zoom-in\n * button. Instead of text, also an element (e.g. a `span` element) can be used.\n * @property {string|HTMLElement} [zoomOutLabel='\u2013'] Text label to use for the zoom-out button.\n * Instead of text, also an element (e.g. a `span` element) can be used.\n * @property {string} [zoomInTipLabel='Zoom in'] Text label to use for the button tip.\n * @property {string} [zoomOutTipLabel='Zoom out'] Text label to use for the button tip.\n * @property {number} [delta=1] The zoom delta applied on each click.\n * @property {HTMLElement|string} [target] Specify a target if you want the control to be\n * rendered outside of the map's viewport.\n */\n\n/**\n * @classdesc\n * A control with 2 buttons, one for zoom in and one for zoom out.\n * This control is one of the default controls of a map. To style this control\n * use css selectors `.ol-zoom-in` and `.ol-zoom-out`.\n *\n * @api\n */\nclass Zoom extends Control {\n  /**\n   * @param {Options} [options] Zoom options.\n   */\n  constructor(options) {\n    options = options ? options : {};\n\n    super({\n      element: document.createElement('div'),\n      target: options.target,\n    });\n\n    const className =\n      options.className !== undefined ? options.className : 'ol-zoom';\n\n    const delta = options.delta !== undefined ? options.delta : 1;\n\n    const zoomInClassName =\n      options.zoomInClassName !== undefined\n        ? options.zoomInClassName\n        : className + '-in';\n\n    const zoomOutClassName =\n      options.zoomOutClassName !== undefined\n        ? options.zoomOutClassName\n        : className + '-out';\n\n    const zoomInLabel =\n      options.zoomInLabel !== undefined ? options.zoomInLabel : '+';\n    const zoomOutLabel =\n      options.zoomOutLabel !== undefined ? options.zoomOutLabel : '\\u2013';\n\n    const zoomInTipLabel =\n      options.zoomInTipLabel !== undefined ? options.zoomInTipLabel : 'Zoom in';\n    const zoomOutTipLabel =\n      options.zoomOutTipLabel !== undefined\n        ? options.zoomOutTipLabel\n        : 'Zoom out';\n\n    const inElement = document.createElement('button');\n    inElement.className = zoomInClassName;\n    inElement.setAttribute('type', 'button');\n    inElement.title = zoomInTipLabel;\n    inElement.appendChild(\n      typeof zoomInLabel === 'string'\n        ? document.createTextNode(zoomInLabel)\n        : zoomInLabel,\n    );\n\n    inElement.addEventListener(\n      EventType.CLICK,\n      this.handleClick_.bind(this, delta),\n      false,\n    );\n\n    const outElement = document.createElement('button');\n    outElement.className = zoomOutClassName;\n    outElement.setAttribute('type', 'button');\n    outElement.title = zoomOutTipLabel;\n    outElement.appendChild(\n      typeof zoomOutLabel === 'string'\n        ? document.createTextNode(zoomOutLabel)\n        : zoomOutLabel,\n    );\n\n    outElement.addEventListener(\n      EventType.CLICK,\n      this.handleClick_.bind(this, -delta),\n      false,\n    );\n\n    const cssClasses =\n      className + ' ' + CLASS_UNSELECTABLE + ' ' + CLASS_CONTROL;\n    const element = this.element;\n    element.className = cssClasses;\n    element.appendChild(inElement);\n    element.appendChild(outElement);\n\n    /**\n     * @type {number}\n     * @private\n     */\n    this.duration_ = options.duration !== undefined ? options.duration : 250;\n  }\n\n  /**\n   * @param {number} delta Zoom delta.\n   * @param {MouseEvent} event The event to handle\n   * @private\n   */\n  handleClick_(delta, event) {\n    event.preventDefault();\n    this.zoomByDelta_(delta);\n  }\n\n  /**\n   * @param {number} delta Zoom delta.\n   * @private\n   */\n  zoomByDelta_(delta) {\n    const map = this.getMap();\n    const view = map.getView();\n    if (!view) {\n      // the map does not have a view, so we can't act\n      // upon it\n      return;\n    }\n    const currentZoom = view.getZoom();\n    if (currentZoom !== undefined) {\n      const newZoom = view.getConstrainedZoom(currentZoom + delta);\n      if (this.duration_ > 0) {\n        if (view.getAnimating()) {\n          view.cancelAnimations();\n        }\n        view.animate({\n          zoom: newZoom,\n          duration: this.duration_,\n          easing: easeOut,\n        });\n      } else {\n        view.setZoom(newZoom);\n      }\n    }\n  }\n}\n\nexport default Zoom;\n", "/**\n * @module ol/control/defaults\n */\nimport Collection from '../Collection.js';\nimport Attribution from './Attribution.js';\nimport Rotate from './Rotate.js';\nimport Zoom from './Zoom.js';\n\n/**\n * @typedef {Object} DefaultsOptions\n * @property {boolean} [attribution=true] Include\n * {@link module:ol/control/Attribution~Attribution}.\n * @property {import(\"./Attribution.js\").Options} [attributionOptions]\n * Options for {@link module:ol/control/Attribution~Attribution}.\n * @property {boolean} [rotate=true] Include\n * {@link module:ol/control/Rotate~Rotate}.\n * @property {import(\"./Rotate.js\").Options} [rotateOptions] Options\n * for {@link module:ol/control/Rotate~Rotate}.\n * @property {boolean} [zoom] Include {@link module:ol/control/Zoom~Zoom}.\n * @property {import(\"./Zoom.js\").Options} [zoomOptions] Options for\n * {@link module:ol/control/Zoom~Zoom}.\n */\n\n/**\n * Set of controls included in maps by default. Unless configured otherwise,\n * this returns a collection containing an instance of each of the following\n * controls:\n * {@link module:ol/control/Zoom~Zoom}\n * {@link module:ol/control/Rotate~Rotate}\n * {@link module:ol/control/Attribution~Attribution}\n *\n * @param {DefaultsOptions} [options] Options for the default controls.\n * @return {Collection<import(\"./Control.js\").default>} A collection of controls\n * to be used with the {@link module:ol/Map~Map} constructor's `controls` option.\n * @api\n */\nexport function defaults(options) {\n  options = options ? options : {};\n\n  /** @type {Collection<import(\"./Control.js\").default>} */\n  const controls = new Collection();\n\n  const zoomControl = options.zoom !== undefined ? options.zoom : true;\n  if (zoomControl) {\n    controls.push(new Zoom(options.zoomOptions));\n  }\n\n  const rotateControl = options.rotate !== undefined ? options.rotate : true;\n  if (rotateControl) {\n    controls.push(new Rotate(options.rotateOptions));\n  }\n\n  const attributionControl =\n    options.attribution !== undefined ? options.attribution : true;\n  if (attributionControl) {\n    controls.push(new Attribution(options.attributionOptions));\n  }\n\n  return controls;\n}\n", "/**\n * @module ol/Kinetic\n */\n\n/**\n * @classdesc\n * Implementation of inertial deceleration for map movement.\n *\n * @api\n */\nclass Kinetic {\n  /**\n   * @param {number} decay Rate of decay (must be negative).\n   * @param {number} minVelocity Minimum velocity (pixels/millisecond).\n   * @param {number} delay Delay to consider to calculate the kinetic\n   *     initial values (milliseconds).\n   */\n  constructor(decay, minVelocity, delay) {\n    /**\n     * @private\n     * @type {number}\n     */\n    this.decay_ = decay;\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.minVelocity_ = minVelocity;\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.delay_ = delay;\n\n    /**\n     * @private\n     * @type {Array<number>}\n     */\n    this.points_ = [];\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.angle_ = 0;\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.initialVelocity_ = 0;\n  }\n\n  /**\n   * FIXME empty description for jsdoc\n   */\n  begin() {\n    this.points_.length = 0;\n    this.angle_ = 0;\n    this.initialVelocity_ = 0;\n  }\n\n  /**\n   * @param {number} x X.\n   * @param {number} y Y.\n   */\n  update(x, y) {\n    this.points_.push(x, y, Date.now());\n  }\n\n  /**\n   * @return {boolean} Whether we should do kinetic animation.\n   */\n  end() {\n    if (this.points_.length < 6) {\n      // at least 2 points are required (i.e. there must be at least 6 elements\n      // in the array)\n      return false;\n    }\n    const delay = Date.now() - this.delay_;\n    const lastIndex = this.points_.length - 3;\n    if (this.points_[lastIndex + 2] < delay) {\n      // the last tracked point is too old, which means that the user stopped\n      // panning before releasing the map\n      return false;\n    }\n\n    // get the first point which still falls into the delay time\n    let firstIndex = lastIndex - 3;\n    while (firstIndex > 0 && this.points_[firstIndex + 2] > delay) {\n      firstIndex -= 3;\n    }\n\n    const duration = this.points_[lastIndex + 2] - this.points_[firstIndex + 2];\n    // we don't want a duration of 0 (divide by zero)\n    // we also make sure the user panned for a duration of at least one frame\n    // (1/60s) to compute sane displacement values\n    if (duration < 1000 / 60) {\n      return false;\n    }\n\n    const dx = this.points_[lastIndex] - this.points_[firstIndex];\n    const dy = this.points_[lastIndex + 1] - this.points_[firstIndex + 1];\n    this.angle_ = Math.atan2(dy, dx);\n    this.initialVelocity_ = Math.sqrt(dx * dx + dy * dy) / duration;\n    return this.initialVelocity_ > this.minVelocity_;\n  }\n\n  /**\n   * @return {number} Total distance travelled (pixels).\n   */\n  getDistance() {\n    return (this.minVelocity_ - this.initialVelocity_) / this.decay_;\n  }\n\n  /**\n   * @return {number} Angle of the kinetic panning animation (radians).\n   */\n  getAngle() {\n    return this.angle_;\n  }\n}\n\nexport default Kinetic;\n", "/**\n * @module ol/interaction/Property\n */\n\n/**\n * @enum {string}\n */\nexport default {\n  ACTIVE: 'active',\n};\n", "/**\n * @module ol/interaction/Interaction\n */\nimport BaseObject from '../Object.js';\nimport {easeOut, linear} from '../easing.js';\nimport InteractionProperty from './Property.js';\n\n/***\n * @template Return\n * @typedef {import(\"../Observable.js\").OnSignature<import(\"../Observable.js\").EventTypes, import(\"../events/Event.js\").default, Return> &\n *   import(\"../Observable.js\").OnSignature<import(\"../ObjectEventType.js\").Types|\n *     'change:active', import(\"../Object.js\").ObjectEvent, Return> &\n *   import(\"../Observable.js\").CombinedOnSignature<import(\"../Observable.js\").EventTypes|import(\"../ObjectEventType.js\").Types|\n *     'change:active', Return>} InteractionOnSignature\n */\n\n/**\n * Object literal with config options for interactions.\n * @typedef {Object} InteractionOptions\n * @property {function(import(\"../MapBrowserEvent.js\").default):boolean} [handleEvent]\n * Method called by the map to notify the interaction that a browser event was\n * dispatched to the map. If the function returns a falsy value, propagation of\n * the event to other interactions in the map's interactions chain will be\n * prevented (this includes functions with no explicit return). The interactions\n * are traversed in reverse order of the interactions collection of the map.\n */\n\n/**\n * @classdesc\n * Abstract base class; normally only used for creating subclasses and not\n * instantiated in apps.\n * User actions that change the state of the map. Some are similar to controls,\n * but are not associated with a DOM element.\n * For example, {@link module:ol/interaction/KeyboardZoom~KeyboardZoom} is\n * functionally the same as {@link module:ol/control/Zoom~Zoom}, but triggered\n * by a keyboard event not a button element event.\n * Although interactions do not have a DOM element, some of them do render\n * vectors and so are visible on the screen.\n * @api\n */\nclass Interaction extends BaseObject {\n  /**\n   * @param {InteractionOptions} [options] Options.\n   */\n  constructor(options) {\n    super();\n\n    /***\n     * @type {InteractionOnSignature<import(\"../events.js\").EventsKey>}\n     */\n    this.on;\n\n    /***\n     * @type {InteractionOnSignature<import(\"../events.js\").EventsKey>}\n     */\n    this.once;\n\n    /***\n     * @type {InteractionOnSignature<void>}\n     */\n    this.un;\n\n    if (options && options.handleEvent) {\n      this.handleEvent = options.handleEvent;\n    }\n\n    /**\n     * @private\n     * @type {import(\"../Map.js\").default|null}\n     */\n    this.map_ = null;\n\n    this.setActive(true);\n  }\n\n  /**\n   * Return whether the interaction is currently active.\n   * @return {boolean} `true` if the interaction is active, `false` otherwise.\n   * @observable\n   * @api\n   */\n  getActive() {\n    return /** @type {boolean} */ (this.get(InteractionProperty.ACTIVE));\n  }\n\n  /**\n   * Get the map associated with this interaction.\n   * @return {import(\"../Map.js\").default|null} Map.\n   * @api\n   */\n  getMap() {\n    return this.map_;\n  }\n\n  /**\n   * Handles the {@link module:ol/MapBrowserEvent~MapBrowserEvent map browser event}.\n   * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Map browser event.\n   * @return {boolean} `false` to stop event propagation.\n   * @api\n   */\n  handleEvent(mapBrowserEvent) {\n    return true;\n  }\n\n  /**\n   * Activate or deactivate the interaction.\n   * @param {boolean} active Active.\n   * @observable\n   * @api\n   */\n  setActive(active) {\n    this.set(InteractionProperty.ACTIVE, active);\n  }\n\n  /**\n   * Remove the interaction from its current map and attach it to the new map.\n   * Subclasses may set up event handlers to get notified about changes to\n   * the map here.\n   * @param {import(\"../Map.js\").default|null} map Map.\n   */\n  setMap(map) {\n    this.map_ = map;\n  }\n}\n\n/**\n * @param {import(\"../View.js\").default} view View.\n * @param {import(\"../coordinate.js\").Coordinate} delta Delta.\n * @param {number} [duration] Duration.\n */\nexport function pan(view, delta, duration) {\n  const currentCenter = view.getCenterInternal();\n  if (currentCenter) {\n    const center = [currentCenter[0] + delta[0], currentCenter[1] + delta[1]];\n    view.animateInternal({\n      duration: duration !== undefined ? duration : 250,\n      easing: linear,\n      center: view.getConstrainedCenter(center),\n    });\n  }\n}\n\n/**\n * @param {import(\"../View.js\").default} view View.\n * @param {number} delta Delta from previous zoom level.\n * @param {import(\"../coordinate.js\").Coordinate} [anchor] Anchor coordinate in the user projection.\n * @param {number} [duration] Duration.\n */\nexport function zoomByDelta(view, delta, anchor, duration) {\n  const currentZoom = view.getZoom();\n\n  if (currentZoom === undefined) {\n    return;\n  }\n\n  const newZoom = view.getConstrainedZoom(currentZoom + delta);\n  const newResolution = view.getResolutionForZoom(newZoom);\n\n  if (view.getAnimating()) {\n    view.cancelAnimations();\n  }\n  view.animate({\n    resolution: newResolution,\n    anchor: anchor,\n    duration: duration !== undefined ? duration : 250,\n    easing: easeOut,\n  });\n}\n\nexport default Interaction;\n", "/**\n * @module ol/interaction/DoubleClickZoom\n */\nimport MapBrowserEventType from '../MapBrowserEventType.js';\nimport Interaction, {zoomByDelta} from './Interaction.js';\n\n/**\n * @typedef {Object} Options\n * @property {number} [duration=250] Animation duration in milliseconds.\n * @property {number} [delta=1] The zoom delta applied on each double click.\n */\n\n/**\n * @classdesc\n * Allows the user to zoom by double-clicking on the map.\n * @api\n */\nclass DoubleClickZoom extends Interaction {\n  /**\n   * @param {Options} [options] Options.\n   */\n  constructor(options) {\n    super();\n\n    options = options ? options : {};\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.delta_ = options.delta ? options.delta : 1;\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.duration_ = options.duration !== undefined ? options.duration : 250;\n  }\n\n  /**\n   * Handles the {@link module:ol/MapBrowserEvent~MapBrowserEvent map browser event} (if it was a\n   * doubleclick) and eventually zooms the map.\n   * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Map browser event.\n   * @return {boolean} `false` to stop event propagation.\n   * @override\n   */\n  handleEvent(mapBrowserEvent) {\n    let stopEvent = false;\n    if (mapBrowserEvent.type == MapBrowserEventType.DBLCLICK) {\n      const browserEvent = /** @type {MouseEvent} */ (\n        mapBrowserEvent.originalEvent\n      );\n      const map = mapBrowserEvent.map;\n      const anchor = mapBrowserEvent.coordinate;\n      const delta = browserEvent.shiftKey ? -this.delta_ : this.delta_;\n      const view = map.getView();\n      zoomByDelta(view, delta, anchor, this.duration_);\n      browserEvent.preventDefault();\n      stopEvent = true;\n    }\n    return !stopEvent;\n  }\n}\n\nexport default DoubleClickZoom;\n", "/**\n * @module ol/events/condition\n */\nimport MapBrowserEventType from '../MapBrowserEventType.js';\nimport {FALSE, TRUE} from '../functions.js';\nimport {MAC, WEBKIT} from '../has.js';\n\n/**\n * A function that takes a {@link module:ol/MapBrowserEvent~MapBrowserEvent} and returns a\n * `{boolean}`. If the condition is met, true should be returned.\n *\n * @typedef {function(this: ?, import(\"../MapBrowserEvent.js\").default): boolean} Condition\n */\n\n/**\n * Creates a condition function that passes when all provided conditions pass.\n * @param {...Condition} var_args Conditions to check.\n * @return {Condition} Condition function.\n */\nexport function all(var_args) {\n  const conditions = arguments;\n  /**\n   * @param {import(\"../MapBrowserEvent.js\").default} event Event.\n   * @return {boolean} All conditions passed.\n   */\n  return function (event) {\n    let pass = true;\n    for (let i = 0, ii = conditions.length; i < ii; ++i) {\n      pass = pass && conditions[i](event);\n      if (!pass) {\n        break;\n      }\n    }\n    return pass;\n  };\n}\n\n/**\n * Return `true` if only the alt-key is pressed, `false` otherwise (e.g. when\n * additionally the shift-key is pressed).\n *\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Map browser event.\n * @return {boolean} True if only the alt key is pressed.\n * @api\n */\nexport const altKeyOnly = function (mapBrowserEvent) {\n  const originalEvent = mapBrowserEvent.originalEvent;\n  return (\n    originalEvent.altKey &&\n    !(originalEvent.metaKey || originalEvent.ctrlKey) &&\n    !originalEvent.shiftKey\n  );\n};\n\n/**\n * Return `true` if only the alt-key and shift-key is pressed, `false` otherwise\n * (e.g. when additionally the platform-modifier-key is pressed).\n *\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Map browser event.\n * @return {boolean} True if only the alt and shift keys are pressed.\n * @api\n */\nexport const altShiftKeysOnly = function (mapBrowserEvent) {\n  const originalEvent = mapBrowserEvent.originalEvent;\n  return (\n    originalEvent.altKey &&\n    !(originalEvent.metaKey || originalEvent.ctrlKey) &&\n    originalEvent.shiftKey\n  );\n};\n\n/**\n * Return `true` if the map has the focus. This condition requires a map target\n * element with a `tabindex` attribute, e.g. `<div id=\"map\" tabindex=\"1\">`.\n *\n * @param {import(\"../MapBrowserEvent.js\").default} event Map browser event.\n * @return {boolean} The map has the focus.\n * @api\n */\nexport const focus = function (event) {\n  const targetElement = event.map.getTargetElement();\n  const rootNode = targetElement.getRootNode();\n  const activeElement = event.map.getOwnerDocument().activeElement;\n\n  return rootNode instanceof ShadowRoot\n    ? rootNode.host.contains(activeElement)\n    : targetElement.contains(activeElement);\n};\n\n/**\n * Return `true` if the map has the focus or no 'tabindex' attribute set.\n *\n * @param {import(\"../MapBrowserEvent.js\").default} event Map browser event.\n * @return {boolean} The map container has the focus or no 'tabindex' attribute.\n */\nexport const focusWithTabindex = function (event) {\n  const targetElement = event.map.getTargetElement();\n  const rootNode = targetElement.getRootNode();\n  const tabIndexCandidate =\n    rootNode instanceof ShadowRoot ? rootNode.host : targetElement;\n\n  return tabIndexCandidate.hasAttribute('tabindex') ? focus(event) : true;\n};\n\n/**\n * Return always true.\n *\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Map browser event.\n * @return {boolean} True.\n * @api\n */\nexport const always = TRUE;\n\n/**\n * Return `true` if the event is a `click` event, `false` otherwise.\n *\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Map browser event.\n * @return {boolean} True if the event is a map `click` event.\n * @api\n */\nexport const click = function (mapBrowserEvent) {\n  return mapBrowserEvent.type == MapBrowserEventType.CLICK;\n};\n\n/**\n * Return `true` if the event has an \"action\"-producing mouse button.\n *\n * By definition, this includes left-click on windows/linux, and left-click\n * without the ctrl key on Macs.\n *\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Map browser event.\n * @return {boolean} The result.\n */\nexport const mouseActionButton = function (mapBrowserEvent) {\n  const originalEvent = mapBrowserEvent.originalEvent;\n  return (\n    'pointerId' in originalEvent &&\n    originalEvent.button == 0 &&\n    !(WEBKIT && MAC && originalEvent.ctrlKey)\n  );\n};\n\n/**\n * Return always false.\n *\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Map browser event.\n * @return {boolean} False.\n * @api\n */\nexport const never = FALSE;\n\n/**\n * Return `true` if the browser event is a `pointermove` event, `false`\n * otherwise.\n *\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Map browser event.\n * @return {boolean} True if the browser event is a `pointermove` event.\n * @api\n */\nexport const pointerMove = function (mapBrowserEvent) {\n  return mapBrowserEvent.type == 'pointermove';\n};\n\n/**\n * Return `true` if the event is a map `singleclick` event, `false` otherwise.\n *\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Map browser event.\n * @return {boolean} True if the event is a map `singleclick` event.\n * @api\n */\nexport const singleClick = function (mapBrowserEvent) {\n  return mapBrowserEvent.type == MapBrowserEventType.SINGLECLICK;\n};\n\n/**\n * Return `true` if the event is a map `dblclick` event, `false` otherwise.\n *\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Map browser event.\n * @return {boolean} True if the event is a map `dblclick` event.\n * @api\n */\nexport const doubleClick = function (mapBrowserEvent) {\n  return mapBrowserEvent.type == MapBrowserEventType.DBLCLICK;\n};\n\n/**\n * Return `true` if no modifier key (alt-, shift- or platform-modifier-key) is\n * pressed.\n *\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Map browser event.\n * @return {boolean} True only if there no modifier keys are pressed.\n * @api\n */\nexport const noModifierKeys = function (mapBrowserEvent) {\n  const originalEvent = /** @type {KeyboardEvent|MouseEvent|TouchEvent} */ (\n    mapBrowserEvent.originalEvent\n  );\n  return (\n    !originalEvent.altKey &&\n    !(originalEvent.metaKey || originalEvent.ctrlKey) &&\n    !originalEvent.shiftKey\n  );\n};\n\n/**\n * Return `true` if only the platform-modifier-key (the meta-key on Mac,\n * ctrl-key otherwise) is pressed, `false` otherwise (e.g. when additionally\n * the shift-key is pressed).\n *\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Map browser event.\n * @return {boolean} True if only the platform modifier key is pressed.\n * @api\n */\nexport const platformModifierKeyOnly = function (mapBrowserEvent) {\n  const originalEvent = mapBrowserEvent.originalEvent;\n  return (\n    !originalEvent.altKey &&\n    (MAC ? originalEvent.metaKey : originalEvent.ctrlKey) &&\n    !originalEvent.shiftKey\n  );\n};\n\n/**\n * Return `true` if the platform-modifier-key (the meta-key on Mac,\n * ctrl-key otherwise) is pressed.\n *\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Map browser event.\n * @return {boolean} True if the platform modifier key is pressed.\n * @api\n */\nexport const platformModifierKey = function (mapBrowserEvent) {\n  const originalEvent = mapBrowserEvent.originalEvent;\n  return MAC ? originalEvent.metaKey : originalEvent.ctrlKey;\n};\n\n/**\n * Return `true` if only the shift-key is pressed, `false` otherwise (e.g. when\n * additionally the alt-key is pressed).\n *\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Map browser event.\n * @return {boolean} True if only the shift key is pressed.\n * @api\n */\nexport const shiftKeyOnly = function (mapBrowserEvent) {\n  const originalEvent = mapBrowserEvent.originalEvent;\n  return (\n    !originalEvent.altKey &&\n    !(originalEvent.metaKey || originalEvent.ctrlKey) &&\n    originalEvent.shiftKey\n  );\n};\n\n/**\n * Return `true` if the target element is not editable, i.e. not an `input`,\n * `select`, or `textarea` element and no `contenteditable` attribute is\n * set or inherited, `false` otherwise.\n *\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Map browser event.\n * @return {boolean} True only if the target element is not editable.\n * @api\n */\nexport const targetNotEditable = function (mapBrowserEvent) {\n  const originalEvent = mapBrowserEvent.originalEvent;\n  const tagName = /** @type {Element} */ (originalEvent.target).tagName;\n  return (\n    tagName !== 'INPUT' &&\n    tagName !== 'SELECT' &&\n    tagName !== 'TEXTAREA' &&\n    // `isContentEditable` is only available on `HTMLElement`, but it may also be a\n    // different type like `SVGElement`.\n    // @ts-ignore\n    !originalEvent.target.isContentEditable\n  );\n};\n\n/**\n * Return `true` if the event originates from a mouse device.\n *\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Map browser event.\n * @return {boolean} True if the event originates from a mouse device.\n * @api\n */\nexport const mouseOnly = function (mapBrowserEvent) {\n  const pointerEvent = mapBrowserEvent.originalEvent;\n  // see https://www.w3.org/TR/pointerevents/#widl-PointerEvent-pointerType\n  return 'pointerId' in pointerEvent && pointerEvent.pointerType == 'mouse';\n};\n\n/**\n * Return `true` if the event originates from a touchable device.\n *\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Map browser event.\n * @return {boolean} True if the event originates from a touchable device.\n * @api\n */\nexport const touchOnly = function (mapBrowserEvent) {\n  const pointerEvt = mapBrowserEvent.originalEvent;\n  // see https://www.w3.org/TR/pointerevents/#widl-PointerEvent-pointerType\n  return 'pointerId' in pointerEvt && pointerEvt.pointerType === 'touch';\n};\n\n/**\n * Return `true` if the event originates from a digital pen.\n *\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Map browser event.\n * @return {boolean} True if the event originates from a digital pen.\n * @api\n */\nexport const penOnly = function (mapBrowserEvent) {\n  const pointerEvt = mapBrowserEvent.originalEvent;\n  // see https://www.w3.org/TR/pointerevents/#widl-PointerEvent-pointerType\n  return 'pointerId' in pointerEvt && pointerEvt.pointerType === 'pen';\n};\n\n/**\n * Return `true` if the event originates from a primary pointer in\n * contact with the surface or if the left mouse button is pressed.\n * See https://www.w3.org/TR/pointerevents/#button-states.\n *\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Map browser event.\n * @return {boolean} True if the event originates from a primary pointer.\n * @api\n */\nexport const primaryAction = function (mapBrowserEvent) {\n  const pointerEvent = mapBrowserEvent.originalEvent;\n  return (\n    'pointerId' in pointerEvent &&\n    pointerEvent.isPrimary &&\n    pointerEvent.button === 0\n  );\n};\n", "/**\n * @module ol/interaction/Pointer\n */\nimport MapBrowserEventType from '../MapBrowserEventType.js';\nimport Interaction from './Interaction.js';\n\n/**\n * @typedef {Object} Options\n * @property {function(import(\"../MapBrowserEvent.js\").default):boolean} [handleDownEvent]\n * Function handling \"down\" events. If the function returns `true` then a drag\n * sequence is started.\n * @property {function(import(\"../MapBrowserEvent.js\").default):void} [handleDragEvent]\n * Function handling \"drag\" events. This function is called on \"move\" events\n * during a drag sequence.\n * @property {function(import(\"../MapBrowserEvent.js\").default):boolean} [handleEvent]\n * Method called by the map to notify the interaction that a browser event was\n * dispatched to the map. The function may return `false` to prevent the\n * propagation of the event to other interactions in the map's interactions\n * chain.\n * @property {function(import(\"../MapBrowserEvent.js\").default):void} [handleMoveEvent]\n * Function handling \"move\" events. This function is called on \"move\" events.\n * This functions is also called during a drag sequence, so during a drag\n * sequence both the `handleDragEvent` function and this function are called.\n * If `handleDownEvent` is defined and it returns true this function will not\n * be called during a drag sequence.\n * @property {function(import(\"../MapBrowserEvent.js\").default):boolean} [handleUpEvent]\n *  Function handling \"up\" events. If the function returns `false` then the\n * current drag sequence is stopped.\n * @property {function(boolean):boolean} [stopDown]\n * Should the down event be propagated to other interactions, or should be\n * stopped?\n */\n\n/**\n * @classdesc\n * Base class that calls user-defined functions on `down`, `move` and `up`\n * events. This class also manages \"drag sequences\".\n *\n * When the `handleDownEvent` user function returns `true` a drag sequence is\n * started. During a drag sequence the `handleDragEvent` user function is\n * called on `move` events. The drag sequence ends when the `handleUpEvent`\n * user function is called and returns `false`.\n * @api\n */\nclass PointerInteraction extends Interaction {\n  /**\n   * @param {Options} [options] Options.\n   */\n  constructor(options) {\n    options = options ? options : {};\n\n    super(\n      /** @type {import(\"./Interaction.js\").InteractionOptions} */ (options),\n    );\n\n    if (options.handleDownEvent) {\n      this.handleDownEvent = options.handleDownEvent;\n    }\n\n    if (options.handleDragEvent) {\n      this.handleDragEvent = options.handleDragEvent;\n    }\n\n    if (options.handleMoveEvent) {\n      this.handleMoveEvent = options.handleMoveEvent;\n    }\n\n    if (options.handleUpEvent) {\n      this.handleUpEvent = options.handleUpEvent;\n    }\n\n    if (options.stopDown) {\n      this.stopDown = options.stopDown;\n    }\n\n    /**\n     * @type {boolean}\n     * @protected\n     */\n    this.handlingDownUpSequence = false;\n\n    /**\n     * @type {Array<PointerEvent>}\n     * @protected\n     */\n    this.targetPointers = [];\n  }\n\n  /**\n   * Returns the current number of pointers involved in the interaction,\n   * e.g. `2` when two fingers are used.\n   * @return {number} The number of pointers.\n   * @api\n   */\n  getPointerCount() {\n    return this.targetPointers.length;\n  }\n\n  /**\n   * Handle pointer down events.\n   * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Event.\n   * @return {boolean} If the event was consumed.\n   * @protected\n   */\n  handleDownEvent(mapBrowserEvent) {\n    return false;\n  }\n\n  /**\n   * Handle pointer drag events.\n   * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Event.\n   * @protected\n   */\n  handleDragEvent(mapBrowserEvent) {}\n\n  /**\n   * Handles the {@link module:ol/MapBrowserEvent~MapBrowserEvent map browser event} and may call into\n   * other functions, if event sequences like e.g. 'drag' or 'down-up' etc. are\n   * detected.\n   * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Map browser event.\n   * @return {boolean} `false` to stop event propagation.\n   * @api\n   * @override\n   */\n  handleEvent(mapBrowserEvent) {\n    if (!mapBrowserEvent.originalEvent) {\n      return true;\n    }\n\n    let stopEvent = false;\n    this.updateTrackedPointers_(mapBrowserEvent);\n    if (this.handlingDownUpSequence) {\n      if (mapBrowserEvent.type == MapBrowserEventType.POINTERDRAG) {\n        this.handleDragEvent(mapBrowserEvent);\n        // prevent page scrolling during dragging\n        mapBrowserEvent.originalEvent.preventDefault();\n      } else if (mapBrowserEvent.type == MapBrowserEventType.POINTERUP) {\n        const handledUp = this.handleUpEvent(mapBrowserEvent);\n        this.handlingDownUpSequence =\n          handledUp && this.targetPointers.length > 0;\n      }\n    } else {\n      if (mapBrowserEvent.type == MapBrowserEventType.POINTERDOWN) {\n        const handled = this.handleDownEvent(mapBrowserEvent);\n        this.handlingDownUpSequence = handled;\n        stopEvent = this.stopDown(handled);\n      } else if (mapBrowserEvent.type == MapBrowserEventType.POINTERMOVE) {\n        this.handleMoveEvent(mapBrowserEvent);\n      }\n    }\n    return !stopEvent;\n  }\n\n  /**\n   * Handle pointer move events.\n   * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Event.\n   * @protected\n   */\n  handleMoveEvent(mapBrowserEvent) {}\n\n  /**\n   * Handle pointer up events.\n   * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Event.\n   * @return {boolean} If the event was consumed.\n   * @protected\n   */\n  handleUpEvent(mapBrowserEvent) {\n    return false;\n  }\n\n  /**\n   * This function is used to determine if \"down\" events should be propagated\n   * to other interactions or should be stopped.\n   * @param {boolean} handled Was the event handled by the interaction?\n   * @return {boolean} Should the `down` event be stopped?\n   */\n  stopDown(handled) {\n    return handled;\n  }\n\n  /**\n   * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Event.\n   * @private\n   */\n  updateTrackedPointers_(mapBrowserEvent) {\n    if (mapBrowserEvent.activePointers) {\n      this.targetPointers = mapBrowserEvent.activePointers;\n    }\n  }\n}\n\n/**\n * @param {Array<PointerEvent>} pointerEvents List of events.\n * @return {{clientX: number, clientY: number}} Centroid pixel.\n */\nexport function centroid(pointerEvents) {\n  const length = pointerEvents.length;\n  let clientX = 0;\n  let clientY = 0;\n  for (let i = 0; i < length; i++) {\n    clientX += pointerEvents[i].clientX;\n    clientY += pointerEvents[i].clientY;\n  }\n  return {clientX: clientX / length, clientY: clientY / length};\n}\n\nexport default PointerInteraction;\n", "/**\n * @module ol/interaction/DragPan\n */\nimport {\n  rotate as rotateCoordinate,\n  scale as scaleCoordinate,\n} from '../coordinate.js';\nimport {easeOut} from '../easing.js';\nimport {\n  all,\n  focusWithTabindex,\n  noModifierKeys,\n  primaryAction,\n} from '../events/condition.js';\nimport {FALSE} from '../functions.js';\nimport PointerInteraction, {\n  centroid as centroidFromPointers,\n} from './Pointer.js';\n\n/**\n * @typedef {Object} Options\n * @property {import(\"../events/condition.js\").Condition} [condition] A function that takes a {@link module:ol/MapBrowserEvent~MapBrowserEvent} and returns a boolean\n * to indicate whether that event should be handled.\n * Default is {@link module:ol/events/condition.noModifierKeys} and {@link module:ol/events/condition.primaryAction}.\n * @property {boolean} [onFocusOnly=false] When the map's target has a `tabindex` attribute set,\n * the interaction will only handle events when the map has the focus.\n * @property {import(\"../Kinetic.js\").default} [kinetic] Kinetic inertia to apply to the pan.\n */\n\n/**\n * @classdesc\n * Allows the user to pan the map by dragging the map.\n * @api\n */\nclass DragPan extends PointerInteraction {\n  /**\n   * @param {Options} [options] Options.\n   */\n  constructor(options) {\n    super({\n      stopDown: FALSE,\n    });\n\n    options = options ? options : {};\n\n    /**\n     * @private\n     * @type {import(\"../Kinetic.js\").default|undefined}\n     */\n    this.kinetic_ = options.kinetic;\n\n    /**\n     * @type {import(\"../pixel.js\").Pixel}\n     */\n    this.lastCentroid = null;\n\n    /**\n     * @type {number}\n     * @private\n     */\n    this.lastPointersCount_;\n\n    /**\n     * @type {boolean}\n     * @private\n     */\n    this.panning_ = false;\n\n    const condition = options.condition\n      ? options.condition\n      : all(noModifierKeys, primaryAction);\n\n    /**\n     * @private\n     * @type {import(\"../events/condition.js\").Condition}\n     */\n    this.condition_ = options.onFocusOnly\n      ? all(focusWithTabindex, condition)\n      : condition;\n\n    /**\n     * @private\n     * @type {boolean}\n     */\n    this.noKinetic_ = false;\n  }\n\n  /**\n   * Handle pointer drag events.\n   * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Event.\n   * @override\n   */\n  handleDragEvent(mapBrowserEvent) {\n    const map = mapBrowserEvent.map;\n    if (!this.panning_) {\n      this.panning_ = true;\n      map.getView().beginInteraction();\n    }\n    const targetPointers = this.targetPointers;\n    const centroid = map.getEventPixel(centroidFromPointers(targetPointers));\n    if (targetPointers.length == this.lastPointersCount_) {\n      if (this.kinetic_) {\n        this.kinetic_.update(centroid[0], centroid[1]);\n      }\n      if (this.lastCentroid) {\n        const delta = [\n          this.lastCentroid[0] - centroid[0],\n          centroid[1] - this.lastCentroid[1],\n        ];\n        const map = mapBrowserEvent.map;\n        const view = map.getView();\n        scaleCoordinate(delta, view.getResolution());\n        rotateCoordinate(delta, view.getRotation());\n        view.adjustCenterInternal(delta);\n      }\n    } else if (this.kinetic_) {\n      // reset so we don't overestimate the kinetic energy after\n      // after one finger down, tiny drag, second finger down\n      this.kinetic_.begin();\n    }\n    this.lastCentroid = centroid;\n    this.lastPointersCount_ = targetPointers.length;\n    mapBrowserEvent.originalEvent.preventDefault();\n  }\n\n  /**\n   * Handle pointer up events.\n   * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Event.\n   * @return {boolean} If the event was consumed.\n   * @override\n   */\n  handleUpEvent(mapBrowserEvent) {\n    const map = mapBrowserEvent.map;\n    const view = map.getView();\n    if (this.targetPointers.length === 0) {\n      if (!this.noKinetic_ && this.kinetic_ && this.kinetic_.end()) {\n        const distance = this.kinetic_.getDistance();\n        const angle = this.kinetic_.getAngle();\n        const center = view.getCenterInternal();\n        const centerpx = map.getPixelFromCoordinateInternal(center);\n        const dest = map.getCoordinateFromPixelInternal([\n          centerpx[0] - distance * Math.cos(angle),\n          centerpx[1] - distance * Math.sin(angle),\n        ]);\n        view.animateInternal({\n          center: view.getConstrainedCenter(dest),\n          duration: 500,\n          easing: easeOut,\n        });\n      }\n      if (this.panning_) {\n        this.panning_ = false;\n        view.endInteraction();\n      }\n      return false;\n    }\n    if (this.kinetic_) {\n      // reset so we don't overestimate the kinetic energy after\n      // after one finger up, tiny drag, second finger up\n      this.kinetic_.begin();\n    }\n    this.lastCentroid = null;\n    return true;\n  }\n\n  /**\n   * Handle pointer down events.\n   * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Event.\n   * @return {boolean} If the event was consumed.\n   * @override\n   */\n  handleDownEvent(mapBrowserEvent) {\n    if (this.targetPointers.length > 0 && this.condition_(mapBrowserEvent)) {\n      const map = mapBrowserEvent.map;\n      const view = map.getView();\n      this.lastCentroid = null;\n      // stop any current animation\n      if (view.getAnimating()) {\n        view.cancelAnimations();\n      }\n      if (this.kinetic_) {\n        this.kinetic_.begin();\n      }\n      // No kinetic as soon as more than one pointer on the screen is\n      // detected. This is to prevent nasty pans after pinch.\n      this.noKinetic_ = this.targetPointers.length > 1;\n      return true;\n    }\n    return false;\n  }\n}\n\nexport default DragPan;\n", "/**\n * @module ol/interaction/DragRotate\n */\nimport {\n  altShiftKeysOnly,\n  mouseActionButton,\n  mouseOnly,\n} from '../events/condition.js';\nimport {FALSE} from '../functions.js';\nimport {disable} from '../rotationconstraint.js';\nimport PointerInteraction from './Pointer.js';\n\n/**\n * @typedef {Object} Options\n * @property {import(\"../events/condition.js\").Condition} [condition] A function that takes a\n * {@link module:ol/MapBrowserEvent~MapBrowserEvent} and returns a boolean\n * to indicate whether that event should be handled.\n * Default is {@link module:ol/events/condition.altShiftKeysOnly}.\n * @property {number} [duration=250] Animation duration in milliseconds.\n */\n\n/**\n * @classdesc\n * Allows the user to rotate the map by clicking and dragging on the map,\n * normally combined with a {@link module:ol/events/condition} that limits\n * it to when the alt and shift keys are held down.\n *\n * This interaction is only supported for mouse devices.\n * @api\n */\nclass DragRotate extends PointerInteraction {\n  /**\n   * @param {Options} [options] Options.\n   */\n  constructor(options) {\n    options = options ? options : {};\n\n    super({\n      stopDown: FALSE,\n    });\n\n    /**\n     * @private\n     * @type {import(\"../events/condition.js\").Condition}\n     */\n    this.condition_ = options.condition ? options.condition : altShiftKeysOnly;\n\n    /**\n     * @private\n     * @type {number|undefined}\n     */\n    this.lastAngle_ = undefined;\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.duration_ = options.duration !== undefined ? options.duration : 250;\n  }\n\n  /**\n   * Handle pointer drag events.\n   * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Event.\n   * @override\n   */\n  handleDragEvent(mapBrowserEvent) {\n    if (!mouseOnly(mapBrowserEvent)) {\n      return;\n    }\n\n    const map = mapBrowserEvent.map;\n    const view = map.getView();\n    if (view.getConstraints().rotation === disable) {\n      return;\n    }\n    const size = map.getSize();\n    const offset = mapBrowserEvent.pixel;\n    const theta = Math.atan2(size[1] / 2 - offset[1], offset[0] - size[0] / 2);\n    if (this.lastAngle_ !== undefined) {\n      const delta = theta - this.lastAngle_;\n      view.adjustRotationInternal(-delta);\n    }\n    this.lastAngle_ = theta;\n  }\n\n  /**\n   * Handle pointer up events.\n   * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Event.\n   * @return {boolean} If the event was consumed.\n   * @override\n   */\n  handleUpEvent(mapBrowserEvent) {\n    if (!mouseOnly(mapBrowserEvent)) {\n      return true;\n    }\n\n    const map = mapBrowserEvent.map;\n    const view = map.getView();\n    view.endInteraction(this.duration_);\n    return false;\n  }\n\n  /**\n   * Handle pointer down events.\n   * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Event.\n   * @return {boolean} If the event was consumed.\n   * @override\n   */\n  handleDownEvent(mapBrowserEvent) {\n    if (!mouseOnly(mapBrowserEvent)) {\n      return false;\n    }\n\n    if (\n      mouseActionButton(mapBrowserEvent) &&\n      this.condition_(mapBrowserEvent)\n    ) {\n      const map = mapBrowserEvent.map;\n      map.getView().beginInteraction();\n      this.lastAngle_ = undefined;\n      return true;\n    }\n    return false;\n  }\n}\n\nexport default DragRotate;\n", "/**\n * @module ol/render/Box\n */\n\nimport Disposable from '../Disposable.js';\nimport Polygon from '../geom/Polygon.js';\n\nclass RenderBox extends Disposable {\n  /**\n   * @param {string} className CSS class name.\n   */\n  constructor(className) {\n    super();\n\n    /**\n     * @type {import(\"../geom/Polygon.js\").default}\n     * @private\n     */\n    this.geometry_ = null;\n\n    /**\n     * @type {HTMLDivElement}\n     * @private\n     */\n    this.element_ = document.createElement('div');\n    this.element_.style.position = 'absolute';\n    this.element_.style.pointerEvents = 'auto';\n    this.element_.className = 'ol-box ' + className;\n\n    /**\n     * @private\n     * @type {import(\"../Map.js\").default|null}\n     */\n    this.map_ = null;\n\n    /**\n     * @private\n     * @type {import(\"../pixel.js\").Pixel}\n     */\n    this.startPixel_ = null;\n\n    /**\n     * @private\n     * @type {import(\"../pixel.js\").Pixel}\n     */\n    this.endPixel_ = null;\n  }\n\n  /**\n   * Clean up.\n   * @override\n   */\n  disposeInternal() {\n    this.setMap(null);\n  }\n\n  /**\n   * @private\n   */\n  render_() {\n    const startPixel = this.startPixel_;\n    const endPixel = this.endPixel_;\n    const px = 'px';\n    const style = this.element_.style;\n    style.left = Math.min(startPixel[0], endPixel[0]) + px;\n    style.top = Math.min(startPixel[1], endPixel[1]) + px;\n    style.width = Math.abs(endPixel[0] - startPixel[0]) + px;\n    style.height = Math.abs(endPixel[1] - startPixel[1]) + px;\n  }\n\n  /**\n   * @param {import(\"../Map.js\").default|null} map Map.\n   */\n  setMap(map) {\n    if (this.map_) {\n      this.map_.getOverlayContainer().removeChild(this.element_);\n      const style = this.element_.style;\n      style.left = 'inherit';\n      style.top = 'inherit';\n      style.width = 'inherit';\n      style.height = 'inherit';\n    }\n    this.map_ = map;\n    if (this.map_) {\n      this.map_.getOverlayContainer().appendChild(this.element_);\n    }\n  }\n\n  /**\n   * @param {import(\"../pixel.js\").Pixel} startPixel Start pixel.\n   * @param {import(\"../pixel.js\").Pixel} endPixel End pixel.\n   */\n  setPixels(startPixel, endPixel) {\n    this.startPixel_ = startPixel;\n    this.endPixel_ = endPixel;\n    this.createOrUpdateGeometry();\n    this.render_();\n  }\n\n  /**\n   * Creates or updates the cached geometry.\n   */\n  createOrUpdateGeometry() {\n    if (!this.map_) {\n      return;\n    }\n\n    const startPixel = this.startPixel_;\n    const endPixel = this.endPixel_;\n    const pixels = [\n      startPixel,\n      [startPixel[0], endPixel[1]],\n      endPixel,\n      [endPixel[0], startPixel[1]],\n    ];\n    const coordinates = pixels.map(\n      this.map_.getCoordinateFromPixelInternal,\n      this.map_,\n    );\n    // close the polygon\n    coordinates[4] = coordinates[0].slice();\n    if (!this.geometry_) {\n      this.geometry_ = new Polygon([coordinates]);\n    } else {\n      this.geometry_.setCoordinates([coordinates]);\n    }\n  }\n\n  /**\n   * @return {import(\"../geom/Polygon.js\").default} Geometry.\n   */\n  getGeometry() {\n    return this.geometry_;\n  }\n}\n\nexport default RenderBox;\n", "/**\n * @module ol/interaction/DragBox\n */\n// FIXME draw drag box\nimport Event from '../events/Event.js';\nimport {mouseActionButton} from '../events/condition.js';\nimport RenderBox from '../render/Box.js';\nimport PointerInteraction from './Pointer.js';\n\n/**\n * A function that takes a {@link module:ol/MapBrowserEvent~MapBrowserEvent} and two\n * {@link module:ol/pixel~Pixel}s and returns a `{boolean}`. If the condition is met,\n * true should be returned.\n * @typedef {function(this: ?, import(\"../MapBrowserEvent.js\").default, import(\"../pixel.js\").Pixel, import(\"../pixel.js\").Pixel):boolean} EndCondition\n */\n\n/**\n * @typedef {Object} Options\n * @property {string} [className='ol-dragbox'] CSS class name for styling the box.\n * @property {import(\"../events/condition.js\").Condition} [condition] A function that takes a {@link module:ol/MapBrowserEvent~MapBrowserEvent} and returns a boolean\n * to indicate whether that event should be handled.\n * Default is {@link ol/events/condition~mouseActionButton}.\n * @property {number} [minArea=64] The minimum area of the box in pixel, this value is used by the default\n * `boxEndCondition` function.\n * @property {EndCondition} [boxEndCondition] A function that takes a {@link module:ol/MapBrowserEvent~MapBrowserEvent} and two\n * {@link module:ol/pixel~Pixel}s to indicate whether a `boxend` event should be fired.\n * Default is `true` if the area of the box is bigger than the `minArea` option.\n * @property {function(this:DragBox, import(\"../MapBrowserEvent.js\").default):void} [onBoxEnd] Code to execute just\n * before `boxend` is fired.\n */\n\n/**\n * @enum {string}\n */\nconst DragBoxEventType = {\n  /**\n   * Triggered upon drag box start.\n   * @event DragBoxEvent#boxstart\n   * @api\n   */\n  BOXSTART: 'boxstart',\n\n  /**\n   * Triggered on drag when box is active.\n   * @event DragBoxEvent#boxdrag\n   * @api\n   */\n  BOXDRAG: 'boxdrag',\n\n  /**\n   * Triggered upon drag box end.\n   * @event DragBoxEvent#boxend\n   * @api\n   */\n  BOXEND: 'boxend',\n\n  /**\n   * Triggered upon drag box canceled.\n   * @event DragBoxEvent#boxcancel\n   * @api\n   */\n  BOXCANCEL: 'boxcancel',\n};\n\n/**\n * @classdesc\n * Events emitted by {@link module:ol/interaction/DragBox~DragBox} instances are instances of\n * this type.\n */\nexport class DragBoxEvent extends Event {\n  /**\n   * @param {string} type The event type.\n   * @param {import(\"../coordinate.js\").Coordinate} coordinate The event coordinate.\n   * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Originating event.\n   */\n  constructor(type, coordinate, mapBrowserEvent) {\n    super(type);\n\n    /**\n     * The coordinate of the drag event.\n     * @const\n     * @type {import(\"../coordinate.js\").Coordinate}\n     * @api\n     */\n    this.coordinate = coordinate;\n\n    /**\n     * @const\n     * @type {import(\"../MapBrowserEvent.js\").default}\n     * @api\n     */\n    this.mapBrowserEvent = mapBrowserEvent;\n  }\n}\n\n/***\n * @template Return\n * @typedef {import(\"../Observable.js\").OnSignature<import(\"../Observable.js\").EventTypes, import(\"../events/Event.js\").default, Return> &\n *   import(\"../Observable.js\").OnSignature<import(\"../ObjectEventType.js\").Types|\n *     'change:active', import(\"../Object.js\").ObjectEvent, Return> &\n *   import(\"../Observable.js\").OnSignature<'boxcancel'|'boxdrag'|'boxend'|'boxstart', DragBoxEvent, Return> &\n *   import(\"../Observable.js\").CombinedOnSignature<import(\"../Observable.js\").EventTypes|import(\"../ObjectEventType.js\").Types|\n *     'change:active'|'boxcancel'|'boxdrag'|'boxend', Return>} DragBoxOnSignature\n */\n\n/**\n * @classdesc\n * Allows the user to draw a vector box by clicking and dragging on the map,\n * normally combined with a {@link module:ol/events/condition} that limits\n * it to when the shift or other key is held down. This is used, for example,\n * for zooming to a specific area of the map\n * (see {@link module:ol/interaction/DragZoom~DragZoom} and\n * {@link module:ol/interaction/DragRotateAndZoom~DragRotateAndZoom}).\n *\n * @fires DragBoxEvent\n * @api\n */\nclass DragBox extends PointerInteraction {\n  /**\n   * @param {Options} [options] Options.\n   */\n  constructor(options) {\n    super();\n\n    /***\n     * @type {DragBoxOnSignature<import(\"../events.js\").EventsKey>}\n     */\n    this.on;\n\n    /***\n     * @type {DragBoxOnSignature<import(\"../events.js\").EventsKey>}\n     */\n    this.once;\n\n    /***\n     * @type {DragBoxOnSignature<void>}\n     */\n    this.un;\n\n    options = options ?? {};\n\n    /**\n     * @type {import(\"../render/Box.js\").default}\n     * @private\n     */\n    this.box_ = new RenderBox(options.className || 'ol-dragbox');\n\n    /**\n     * @type {number}\n     * @private\n     */\n    this.minArea_ = options.minArea ?? 64;\n\n    if (options.onBoxEnd) {\n      this.onBoxEnd = options.onBoxEnd;\n    }\n\n    /**\n     * @type {import(\"../pixel.js\").Pixel}\n     * @private\n     */\n    this.startPixel_ = null;\n\n    /**\n     * @private\n     * @type {import(\"../events/condition.js\").Condition}\n     */\n    this.condition_ = options.condition ?? mouseActionButton;\n\n    /**\n     * @private\n     * @type {EndCondition}\n     */\n    this.boxEndCondition_ =\n      options.boxEndCondition ?? this.defaultBoxEndCondition;\n  }\n\n  /**\n   * The default condition for determining whether the boxend event\n   * should fire.\n   * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent The originating MapBrowserEvent\n   *     leading to the box end.\n   * @param {import(\"../pixel.js\").Pixel} startPixel The starting pixel of the box.\n   * @param {import(\"../pixel.js\").Pixel} endPixel The end pixel of the box.\n   * @return {boolean} Whether or not the boxend condition should be fired.\n   */\n  defaultBoxEndCondition(mapBrowserEvent, startPixel, endPixel) {\n    const width = endPixel[0] - startPixel[0];\n    const height = endPixel[1] - startPixel[1];\n    return width * width + height * height >= this.minArea_;\n  }\n\n  /**\n   * Returns geometry of last drawn box.\n   * @return {import(\"../geom/Polygon.js\").default} Geometry.\n   * @api\n   */\n  getGeometry() {\n    return this.box_.getGeometry();\n  }\n\n  /**\n   * Handle pointer drag events.\n   * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Event.\n   * @override\n   */\n  handleDragEvent(mapBrowserEvent) {\n    if (!this.startPixel_) {\n      return;\n    }\n\n    this.box_.setPixels(this.startPixel_, mapBrowserEvent.pixel);\n\n    this.dispatchEvent(\n      new DragBoxEvent(\n        DragBoxEventType.BOXDRAG,\n        mapBrowserEvent.coordinate,\n        mapBrowserEvent,\n      ),\n    );\n  }\n\n  /**\n   * Handle pointer up events.\n   * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Event.\n   * @return {boolean} If the event was consumed.\n   * @override\n   */\n  handleUpEvent(mapBrowserEvent) {\n    if (!this.startPixel_) {\n      return false;\n    }\n\n    const completeBox = this.boxEndCondition_(\n      mapBrowserEvent,\n      this.startPixel_,\n      mapBrowserEvent.pixel,\n    );\n    if (completeBox) {\n      this.onBoxEnd(mapBrowserEvent);\n    }\n    this.dispatchEvent(\n      new DragBoxEvent(\n        completeBox ? DragBoxEventType.BOXEND : DragBoxEventType.BOXCANCEL,\n        mapBrowserEvent.coordinate,\n        mapBrowserEvent,\n      ),\n    );\n\n    this.box_.setMap(null);\n    this.startPixel_ = null;\n\n    return false;\n  }\n\n  /**\n   * Handle pointer down events.\n   * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Event.\n   * @return {boolean} If the event was consumed.\n   * @override\n   */\n  handleDownEvent(mapBrowserEvent) {\n    if (this.condition_(mapBrowserEvent)) {\n      this.startPixel_ = mapBrowserEvent.pixel;\n      this.box_.setMap(mapBrowserEvent.map);\n      this.box_.setPixels(this.startPixel_, this.startPixel_);\n      this.dispatchEvent(\n        new DragBoxEvent(\n          DragBoxEventType.BOXSTART,\n          mapBrowserEvent.coordinate,\n          mapBrowserEvent,\n        ),\n      );\n      return true;\n    }\n    return false;\n  }\n\n  /**\n   * Function to execute just before `onboxend` is fired\n   * @param {import(\"../MapBrowserEvent.js\").default} event Event.\n   */\n  onBoxEnd(event) {}\n\n  /**\n   * Activate or deactivate the interaction.\n   * @param {boolean} active Active.\n   * @observable\n   * @api\n   * @override\n   */\n  setActive(active) {\n    if (!active) {\n      this.box_.setMap(null);\n      if (this.startPixel_) {\n        this.dispatchEvent(\n          new DragBoxEvent(DragBoxEventType.BOXCANCEL, this.startPixel_, null),\n        );\n        this.startPixel_ = null;\n      }\n    }\n\n    super.setActive(active);\n  }\n\n  /**\n   * @param {import(\"../Map.js\").default|null} map Map.\n   * @override\n   */\n  setMap(map) {\n    const oldMap = this.getMap();\n\n    if (oldMap) {\n      this.box_.setMap(null);\n\n      if (this.startPixel_) {\n        this.dispatchEvent(\n          new DragBoxEvent(DragBoxEventType.BOXCANCEL, this.startPixel_, null),\n        );\n        this.startPixel_ = null;\n      }\n    }\n\n    super.setMap(map);\n  }\n}\n\nexport default DragBox;\n", "/**\n * @module ol/interaction/DragZoom\n */\nimport {easeOut} from '../easing.js';\nimport {shiftKeyOnly} from '../events/condition.js';\nimport DragBox from './DragBox.js';\n\n/**\n * @typedef {Object} Options\n * @property {string} [className='ol-dragzoom'] CSS class name for styling the\n * box.\n * @property {import(\"../events/condition.js\").Condition} [condition] A function that\n * takes a {@link module:ol/MapBrowserEvent~MapBrowserEvent} and returns a\n * boolean to indicate whether that event should be handled.\n * Default is {@link module:ol/events/condition.shiftKeyOnly}.\n * @property {number} [duration=200] Animation duration in milliseconds.\n * @property {boolean} [out=false] Use interaction for zooming out.\n * @property {number} [minArea=64] The minimum area of the box in pixel, this value is used by the parent default\n * `boxEndCondition` function.\n */\n\n/**\n * @classdesc\n * Allows the user to zoom the map by clicking and dragging on the map,\n * normally combined with a {@link module:ol/events/condition} that limits\n * it to when a key, shift by default, is held down.\n *\n * To change the style of the box, use CSS and the `.ol-dragzoom` selector, or\n * your custom one configured with `className`.\n * @api\n */\nclass DragZoom extends DragBox {\n  /**\n   * @param {Options} [options] Options.\n   */\n  constructor(options) {\n    options = options ? options : {};\n\n    const condition = options.condition ? options.condition : shiftKeyOnly;\n\n    super({\n      condition: condition,\n      className: options.className || 'ol-dragzoom',\n      minArea: options.minArea,\n    });\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.duration_ = options.duration !== undefined ? options.duration : 200;\n\n    /**\n     * @private\n     * @type {boolean}\n     */\n    this.out_ = options.out !== undefined ? options.out : false;\n  }\n\n  /**\n   * Function to execute just before `onboxend` is fired\n   * @param {import(\"../MapBrowserEvent.js\").default} event Event.\n   * @override\n   */\n  onBoxEnd(event) {\n    const map = this.getMap();\n    const view = /** @type {!import(\"../View.js\").default} */ (map.getView());\n    let geometry = this.getGeometry();\n\n    if (this.out_) {\n      const rotatedExtent = view.rotatedExtentForGeometry(geometry);\n      const resolution = view.getResolutionForExtentInternal(rotatedExtent);\n      const factor = view.getResolution() / resolution;\n      geometry = geometry.clone();\n      geometry.scale(factor * factor);\n    }\n\n    view.fitInternal(geometry, {\n      duration: this.duration_,\n      easing: easeOut,\n    });\n  }\n}\n\nexport default DragZoom;\n", "/**\n * @module ol/events/Key\n */\n\n/**\n * @enum {string}\n * @const\n */\nexport default {\n  LEFT: 'ArrowLeft',\n  UP: 'ArrowUp',\n  RIGHT: 'ArrowRight',\n  DOWN: 'ArrowDown',\n};\n", "/**\n * @module ol/interaction/KeyboardPan\n */\nimport {rotate as rotateCoordinate} from '../coordinate.js';\nimport EventType from '../events/EventType.js';\nimport Key from '../events/Key.js';\nimport {noModifierKeys, targetNotEditable} from '../events/condition.js';\nimport Interaction, {pan} from './Interaction.js';\n\n/**\n * @typedef {Object} Options\n * @property {import(\"../events/condition.js\").Condition} [condition] A function that\n * takes a {@link module:ol/MapBrowserEvent~MapBrowserEvent} and returns a\n * boolean to indicate whether that event should be handled. Default is\n * {@link module:ol/events/condition.noModifierKeys} and\n * {@link module:ol/events/condition.targetNotEditable}.\n * @property {number} [duration=100] Animation duration in milliseconds.\n * @property {number} [pixelDelta=128] The amount of pixels to pan on each key\n * press.\n */\n\n/**\n * @classdesc\n * Allows the user to pan the map using keyboard arrows.\n * Note that, although this interaction is by default included in maps,\n * the keys can only be used when browser focus is on the element to which\n * the keyboard events are attached. By default, this is the map div,\n * though you can change this with the `keyboardEventTarget` in\n * {@link module:ol/Map~Map}. `document` never loses focus but, for any other\n * element, focus will have to be on, and returned to, this element if the keys\n * are to function.\n * See also {@link module:ol/interaction/KeyboardZoom~KeyboardZoom}.\n * @api\n */\nclass KeyboardPan extends Interaction {\n  /**\n   * @param {Options} [options] Options.\n   */\n  constructor(options) {\n    super();\n\n    options = options || {};\n\n    /**\n     * @private\n     * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Browser event.\n     * @return {boolean} Combined condition result.\n     */\n    this.defaultCondition_ = function (mapBrowserEvent) {\n      return (\n        noModifierKeys(mapBrowserEvent) && targetNotEditable(mapBrowserEvent)\n      );\n    };\n\n    /**\n     * @private\n     * @type {import(\"../events/condition.js\").Condition}\n     */\n    this.condition_ =\n      options.condition !== undefined\n        ? options.condition\n        : this.defaultCondition_;\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.duration_ = options.duration !== undefined ? options.duration : 100;\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.pixelDelta_ =\n      options.pixelDelta !== undefined ? options.pixelDelta : 128;\n  }\n\n  /**\n   * Handles the {@link module:ol/MapBrowserEvent~MapBrowserEvent map browser event} if it was a\n   * `KeyEvent`, and decides the direction to pan to (if an arrow key was\n   * pressed).\n   * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Map browser event.\n   * @return {boolean} `false` to stop event propagation.\n   * @override\n   */\n  handleEvent(mapBrowserEvent) {\n    let stopEvent = false;\n    if (mapBrowserEvent.type == EventType.KEYDOWN) {\n      const keyEvent = /** @type {KeyboardEvent} */ (\n        mapBrowserEvent.originalEvent\n      );\n      const key = keyEvent.key;\n      if (\n        this.condition_(mapBrowserEvent) &&\n        (key == Key.DOWN ||\n          key == Key.LEFT ||\n          key == Key.RIGHT ||\n          key == Key.UP)\n      ) {\n        const map = mapBrowserEvent.map;\n        const view = map.getView();\n        const mapUnitsDelta = view.getResolution() * this.pixelDelta_;\n        let deltaX = 0,\n          deltaY = 0;\n        if (key == Key.DOWN) {\n          deltaY = -mapUnitsDelta;\n        } else if (key == Key.LEFT) {\n          deltaX = -mapUnitsDelta;\n        } else if (key == Key.RIGHT) {\n          deltaX = mapUnitsDelta;\n        } else {\n          deltaY = mapUnitsDelta;\n        }\n        const delta = [deltaX, deltaY];\n        rotateCoordinate(delta, view.getRotation());\n        pan(view, delta, this.duration_);\n        keyEvent.preventDefault();\n        stopEvent = true;\n      }\n    }\n    return !stopEvent;\n  }\n}\n\nexport default KeyboardPan;\n", "/**\n * @module ol/interaction/KeyboardZoom\n */\nimport EventType from '../events/EventType.js';\nimport {platformModifierKey, targetNotEditable} from '../events/condition.js';\nimport Interaction, {zoomByDelta} from './Interaction.js';\n\n/**\n * @typedef {Object} Options\n * @property {number} [duration=100] Animation duration in milliseconds.\n * @property {import(\"../events/condition.js\").Condition} [condition] A function that\n * takes a {@link module:ol/MapBrowserEvent~MapBrowserEvent} and returns a\n * boolean to indicate whether that event should be handled. The default condition is\n * that {@link module:ol/events/condition.targetNotEditable} is fulfilled and that\n * the platform modifier key isn't pressed\n * (!{@link module:ol/events/condition.platformModifierKey}).\n * @property {number} [delta=1] The zoom level delta on each key press.\n */\n\n/**\n * @classdesc\n * Allows the user to zoom the map using keyboard + and -.\n * Note that, although this interaction is by default included in maps,\n * the keys can only be used when browser focus is on the element to which\n * the keyboard events are attached. By default, this is the map div,\n * though you can change this with the `keyboardEventTarget` in\n * {@link module:ol/Map~Map}. `document` never loses focus but, for any other\n * element, focus will have to be on, and returned to, this element if the keys\n * are to function.\n * See also {@link module:ol/interaction/KeyboardPan~KeyboardPan}.\n * @api\n */\nclass KeyboardZoom extends Interaction {\n  /**\n   * @param {Options} [options] Options.\n   */\n  constructor(options) {\n    super();\n\n    options = options ? options : {};\n\n    /**\n     * @private\n     * @type {import(\"../events/condition.js\").Condition}\n     */\n    this.condition_ = options.condition\n      ? options.condition\n      : function (mapBrowserEvent) {\n          return (\n            !platformModifierKey(mapBrowserEvent) &&\n            targetNotEditable(mapBrowserEvent)\n          );\n        };\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.delta_ = options.delta ? options.delta : 1;\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.duration_ = options.duration !== undefined ? options.duration : 100;\n  }\n\n  /**\n   * Handles the {@link module:ol/MapBrowserEvent~MapBrowserEvent map browser event} if it was a\n   * `KeyEvent`, and decides whether to zoom in or out (depending on whether the\n   * key pressed was '+' or '-').\n   * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Map browser event.\n   * @return {boolean} `false` to stop event propagation.\n   * @override\n   */\n  handleEvent(mapBrowserEvent) {\n    let stopEvent = false;\n    if (\n      mapBrowserEvent.type == EventType.KEYDOWN ||\n      mapBrowserEvent.type == EventType.KEYPRESS\n    ) {\n      const keyEvent = /** @type {KeyboardEvent} */ (\n        mapBrowserEvent.originalEvent\n      );\n      const key = keyEvent.key;\n      if (this.condition_(mapBrowserEvent) && (key === '+' || key === '-')) {\n        const map = mapBrowserEvent.map;\n        const delta = key === '+' ? this.delta_ : -this.delta_;\n        const view = map.getView();\n        zoomByDelta(view, delta, undefined, this.duration_);\n        keyEvent.preventDefault();\n        stopEvent = true;\n      }\n    }\n    return !stopEvent;\n  }\n}\n\nexport default KeyboardZoom;\n", "/**\n * @module ol/interaction/MouseWheelZoom\n */\nimport {listen, unlistenByKey} from '../events.js';\nimport EventType from '../events/EventType.js';\nimport {all, always, focusWithTabindex} from '../events/condition.js';\nimport {clamp} from '../math.js';\nimport Interaction, {zoomByDelta} from './Interaction.js';\n\n/**\n * @typedef {'trackpad' | 'wheel'} Mode\n */\n\n/**\n * @typedef {Object} Options\n * @property {import(\"../events/condition.js\").Condition} [condition] A function that\n * takes a {@link module:ol/MapBrowserEvent~MapBrowserEvent} and returns a\n * boolean to indicate whether that event should be handled. Default is\n * {@link module:ol/events/condition.always}.\n * @property {boolean} [onFocusOnly=false] When the map's target has a `tabindex` attribute set,\n * the interaction will only handle events when the map has the focus.\n * @property {number} [maxDelta=1] Maximum mouse wheel delta.\n * @property {number} [duration=250] Animation duration in milliseconds.\n * @property {number} [timeout=80] Mouse wheel timeout duration in milliseconds.\n * @property {boolean} [useAnchor=true] Enable zooming using the mouse's\n * location as the anchor. When set to `false`, zooming in and out will zoom to\n * the center of the screen instead of zooming on the mouse's location.\n * @property {boolean} [constrainResolution=false] If true, the mouse wheel zoom\n * event will always animate to the closest zoom level after an interaction;\n * false means intermediary zoom levels are allowed.\n */\n\n/**\n * Mutliplier for the DOM_DELTA_LINE delta value.\n * @type {number}\n */\nconst DELTA_LINE_MULTIPLIER = 40;\n\n/**\n * Mutliplier for the DOM_DELTA_PAGE delta value.\n * @type {number}\n */\nconst DELTA_PAGE_MULTIPLIER = 300;\n\n/**\n * Mutliplier for the delta value when using pinch-to-zoom\n * @type {number}\n */\nconst DELTA_TRACKPAD_PINCH_TO_ZOOM_MULTIPLIER = 3; // 5 = google maps. 3 = apple maps, MapLibre.\n/**\n * @classdesc\n * Allows the user to zoom the map by scrolling the mouse wheel.\n * @api\n */\nclass MouseWheelZoom extends Interaction {\n  /**\n   * @param {Options} [options] Options.\n   */\n  constructor(options) {\n    options = options ? options : {};\n\n    super(\n      /** @type {import(\"./Interaction.js\").InteractionOptions} */ (options),\n    );\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.totalDelta_ = 0;\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.lastDelta_ = 0;\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.maxDelta_ = options.maxDelta !== undefined ? options.maxDelta : 1;\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.duration_ = options.duration !== undefined ? options.duration : 250;\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.timeout_ = options.timeout !== undefined ? options.timeout : 80;\n\n    /**\n     * @private\n     * @type {boolean}\n     */\n    this.useAnchor_ =\n      options.useAnchor !== undefined ? options.useAnchor : true;\n\n    /**\n     * @private\n     * @type {boolean}\n     */\n    this.constrainResolution_ =\n      options.constrainResolution !== undefined\n        ? options.constrainResolution\n        : false;\n\n    const condition = options.condition ? options.condition : always;\n\n    /**\n     * @private\n     * @type {import(\"../events/condition.js\").Condition}\n     */\n    this.condition_ = options.onFocusOnly\n      ? all(focusWithTabindex, condition)\n      : condition;\n\n    /**\n     * @private\n     * @type {?import(\"../pixel.js\").Pixel}\n     */\n    this.lastAnchor_ = null;\n\n    /**\n     * @private\n     * @type {number|undefined}\n     */\n    this.startTime_ = undefined;\n\n    /**\n     * @private\n     * @type {ReturnType<typeof setTimeout>}\n     */\n    this.timeoutId_;\n\n    /**\n     * @private\n     * @type {Mode|undefined}\n     */\n    this.mode_ = undefined;\n\n    /**\n     * Trackpad events separated by this delay will be considered separate\n     * interactions.\n     * @private\n     * @type {number}\n     */\n    this.trackpadEventGap_ = 400;\n\n    /**\n     * @private\n     * @type {ReturnType<typeof setTimeout>}\n     */\n    this.trackpadTimeoutId_;\n\n    /**\n     * The number of delta values per zoom level\n     * @private\n     * @type {number}\n     */\n    this.deltaPerZoom_ = 300;\n\n    /**\n     * Tracks whether the Ctrl key is physically held down (as opposed to the\n     * browser synthesizing ctrlKey=true for pinch-to-zoom trackpad gestures).\n     * @private\n     * @type {boolean}\n     */\n    this.ctrlKeyPressed_ = false;\n\n    /**\n     * @private\n     * @type {Array<import('../events.js').EventsKey>}\n     */\n    this.ctrlKeyListenerKeys_ = [];\n  }\n\n  /**\n   * @param {import('../Map.js').default|null} map Map.\n   * @override\n   */\n  setMap(map) {\n    this.ctrlKeyListenerKeys_.forEach(unlistenByKey);\n    this.ctrlKeyListenerKeys_.length = 0;\n    this.ctrlKeyPressed_ = false;\n    super.setMap(map);\n    if (map) {\n      const doc = map.getOwnerDocument();\n      this.ctrlKeyListenerKeys_.push(\n        listen(doc, 'keydown', (/** @type {KeyboardEvent} */ e) => {\n          if (e.key === 'Control') {\n            this.ctrlKeyPressed_ = true;\n          }\n        }),\n        listen(doc, 'keyup', (/** @type {KeyboardEvent} */ e) => {\n          if (e.key === 'Control') {\n            this.ctrlKeyPressed_ = false;\n          }\n        }),\n      );\n    }\n  }\n\n  /**\n   * @private\n   */\n  endInteraction_() {\n    this.trackpadTimeoutId_ = undefined;\n    const map = this.getMap();\n    if (!map) {\n      return;\n    }\n    const view = map.getView();\n    const direction = this.lastDelta_ ? (this.lastDelta_ > 0 ? 1 : -1) : 0;\n    view.endInteraction(\n      this.constrainResolution_ || view.getConstrainResolution()\n        ? 100\n        : undefined,\n      direction,\n      this.lastAnchor_ ? map.getCoordinateFromPixel(this.lastAnchor_) : null,\n    );\n  }\n\n  /**\n   * Handles the {@link module:ol/MapBrowserEvent~MapBrowserEvent map browser event} (if it was a mousewheel-event) and eventually\n   * zooms the map.\n   * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Map browser event.\n   * @return {boolean} `false` to stop event propagation.\n   * @override\n   */\n  handleEvent(mapBrowserEvent) {\n    if (!this.condition_(mapBrowserEvent)) {\n      return true;\n    }\n    const type = mapBrowserEvent.type;\n    if (type !== EventType.WHEEL) {\n      return true;\n    }\n\n    const map = mapBrowserEvent.map;\n    const wheelEvent = /** @type {WheelEvent} */ (\n      mapBrowserEvent.originalEvent\n    );\n    wheelEvent.preventDefault();\n\n    const isPinchToZoom = wheelEvent.ctrlKey && !this.ctrlKeyPressed_;\n    if (!wheelEvent.ctrlKey) {\n      this.ctrlKeyPressed_ = false;\n    }\n\n    if (this.useAnchor_) {\n      this.lastAnchor_ = mapBrowserEvent.pixel;\n    }\n\n    // Delta normalisation inspired by\n    // https://github.com/mapbox/mapbox-gl-js/blob/001c7b9/js/ui/handler/scroll_zoom.js\n    let delta = wheelEvent.deltaY;\n\n    switch (wheelEvent.deltaMode) {\n      case WheelEvent.DOM_DELTA_LINE:\n        delta *= DELTA_LINE_MULTIPLIER;\n        break;\n      case WheelEvent.DOM_DELTA_PAGE:\n        delta *= DELTA_PAGE_MULTIPLIER;\n        break;\n      default:\n      // pass\n    }\n\n    if (delta === 0) {\n      return false;\n    }\n    this.lastDelta_ = delta;\n\n    const now = Date.now();\n\n    if (this.startTime_ === undefined) {\n      this.startTime_ = now;\n    }\n\n    if (!this.mode_ || now - this.startTime_ > this.trackpadEventGap_) {\n      this.mode_ = Math.abs(delta) < 4 ? 'trackpad' : 'wheel';\n    }\n\n    const view = map.getView();\n    if (this.mode_ === 'trackpad') {\n      if (this.trackpadTimeoutId_) {\n        clearTimeout(this.trackpadTimeoutId_);\n      } else {\n        if (view.getAnimating()) {\n          view.cancelAnimations();\n        }\n        view.beginInteraction();\n      }\n      this.trackpadTimeoutId_ = setTimeout(\n        this.endInteraction_.bind(this),\n        this.timeout_,\n      );\n      if (isPinchToZoom) {\n        delta = delta * DELTA_TRACKPAD_PINCH_TO_ZOOM_MULTIPLIER;\n      }\n      view.adjustZoom(\n        -delta / this.deltaPerZoom_,\n        this.lastAnchor_ ? map.getCoordinateFromPixel(this.lastAnchor_) : null,\n      );\n      this.startTime_ = now;\n      return false;\n    }\n\n    this.totalDelta_ += delta;\n\n    const timeLeft = Math.max(this.timeout_ - (now - this.startTime_), 0);\n\n    clearTimeout(this.timeoutId_);\n    this.timeoutId_ = setTimeout(\n      this.handleWheelZoom_.bind(this, map),\n      timeLeft,\n    );\n\n    return false;\n  }\n\n  /**\n   * @private\n   * @param {import(\"../Map.js\").default} map Map.\n   */\n  handleWheelZoom_(map) {\n    const view = map.getView();\n    if (view.getAnimating()) {\n      view.cancelAnimations();\n    }\n    let delta =\n      -clamp(\n        this.totalDelta_,\n        -this.maxDelta_ * this.deltaPerZoom_,\n        this.maxDelta_ * this.deltaPerZoom_,\n      ) / this.deltaPerZoom_;\n    if (view.getConstrainResolution() || this.constrainResolution_) {\n      // view has a zoom constraint, zoom by 1\n      delta = delta ? (delta > 0 ? 1 : -1) : 0;\n    }\n    zoomByDelta(\n      view,\n      delta,\n      this.lastAnchor_ ? map.getCoordinateFromPixel(this.lastAnchor_) : null,\n      this.duration_,\n    );\n\n    this.mode_ = undefined;\n    this.totalDelta_ = 0;\n    this.lastAnchor_ = null;\n    this.startTime_ = undefined;\n    this.timeoutId_ = undefined;\n  }\n\n  /**\n   * Enable or disable using the mouse's location as an anchor when zooming\n   * @param {boolean} useAnchor true to zoom to the mouse's location, false\n   * to zoom to the center of the map\n   * @api\n   */\n  setMouseAnchor(useAnchor) {\n    this.useAnchor_ = useAnchor;\n    if (!useAnchor) {\n      this.lastAnchor_ = null;\n    }\n  }\n}\n\nexport default MouseWheelZoom;\n", "/**\n * @module ol/interaction/PinchRotate\n */\nimport {FALSE} from '../functions.js';\nimport {disable} from '../rotationconstraint.js';\nimport PointerInteraction, {\n  centroid as centroidFromPointers,\n} from './Pointer.js';\n\n/**\n * @typedef {Object} Options\n * @property {number} [duration=250] The duration of the animation in\n * milliseconds.\n * @property {number} [threshold=0.3] Minimal angle in radians to start a rotation.\n */\n\n/**\n * @classdesc\n * Allows the user to rotate the map by twisting with two fingers\n * on a touch screen.\n * @api\n */\nclass PinchRotate extends PointerInteraction {\n  /**\n   * @param {Options} [options] Options.\n   */\n  constructor(options) {\n    options = options ? options : {};\n\n    const pointerOptions = /** @type {import(\"./Pointer.js\").Options} */ (\n      options\n    );\n\n    if (!pointerOptions.stopDown) {\n      pointerOptions.stopDown = FALSE;\n    }\n\n    super(pointerOptions);\n\n    /**\n     * @private\n     * @type {import(\"../coordinate.js\").Coordinate}\n     */\n    this.anchor_ = null;\n\n    /**\n     * @private\n     * @type {number|undefined}\n     */\n    this.lastAngle_ = undefined;\n\n    /**\n     * @private\n     * @type {boolean}\n     */\n    this.rotating_ = false;\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.rotationDelta_ = 0.0;\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.threshold_ = options.threshold !== undefined ? options.threshold : 0.3;\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.duration_ = options.duration !== undefined ? options.duration : 250;\n  }\n\n  /**\n   * Handle pointer drag events.\n   * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Event.\n   * @override\n   */\n  handleDragEvent(mapBrowserEvent) {\n    let rotationDelta = 0.0;\n\n    const touch0 = this.targetPointers[0];\n    const touch1 = this.targetPointers[1];\n\n    // angle between touches\n    const angle = Math.atan2(\n      touch1.clientY - touch0.clientY,\n      touch1.clientX - touch0.clientX,\n    );\n\n    if (this.lastAngle_ !== undefined) {\n      const delta = angle - this.lastAngle_;\n      this.rotationDelta_ += delta;\n      if (!this.rotating_ && Math.abs(this.rotationDelta_) > this.threshold_) {\n        this.rotating_ = true;\n      }\n      rotationDelta = delta;\n    }\n    this.lastAngle_ = angle;\n\n    const map = mapBrowserEvent.map;\n    const view = map.getView();\n    if (view.getConstraints().rotation === disable) {\n      return;\n    }\n\n    // rotate anchor point.\n    // FIXME: should be the intersection point between the lines:\n    //     touch0,touch1 and previousTouch0,previousTouch1\n    this.anchor_ = map.getCoordinateFromPixelInternal(\n      map.getEventPixel(centroidFromPointers(this.targetPointers)),\n    );\n\n    // rotate\n    if (this.rotating_) {\n      map.render();\n      view.adjustRotationInternal(rotationDelta, this.anchor_);\n    }\n  }\n\n  /**\n   * Handle pointer up events.\n   * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Event.\n   * @return {boolean} If the event was consumed.\n   * @override\n   */\n  handleUpEvent(mapBrowserEvent) {\n    if (this.targetPointers.length < 2) {\n      const map = mapBrowserEvent.map;\n      const view = map.getView();\n      view.endInteraction(this.duration_);\n      return false;\n    }\n    return true;\n  }\n\n  /**\n   * Handle pointer down events.\n   * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Event.\n   * @return {boolean} If the event was consumed.\n   * @override\n   */\n  handleDownEvent(mapBrowserEvent) {\n    if (this.targetPointers.length >= 2) {\n      const map = mapBrowserEvent.map;\n      this.anchor_ = null;\n      this.lastAngle_ = undefined;\n      this.rotating_ = false;\n      this.rotationDelta_ = 0.0;\n      if (!this.handlingDownUpSequence) {\n        map.getView().beginInteraction();\n      }\n      return true;\n    }\n    return false;\n  }\n}\n\nexport default PinchRotate;\n", "/**\n * @module ol/interaction/PinchZoom\n */\nimport {FALSE} from '../functions.js';\nimport PointerInteraction, {\n  centroid as centroidFromPointers,\n} from './Pointer.js';\n\n/**\n * @typedef {Object} Options\n * @property {number} [duration=400] Animation duration in milliseconds.\n */\n\n/**\n * @classdesc\n * Allows the user to zoom the map by pinching with two fingers\n * on a touch screen.\n * @api\n */\nclass PinchZoom extends PointerInteraction {\n  /**\n   * @param {Options} [options] Options.\n   */\n  constructor(options) {\n    options = options ? options : {};\n\n    const pointerOptions = /** @type {import(\"./Pointer.js\").Options} */ (\n      options\n    );\n\n    if (!pointerOptions.stopDown) {\n      pointerOptions.stopDown = FALSE;\n    }\n\n    super(pointerOptions);\n\n    /**\n     * @private\n     * @type {import(\"../coordinate.js\").Coordinate}\n     */\n    this.anchor_ = null;\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.duration_ = options.duration !== undefined ? options.duration : 400;\n\n    /**\n     * @private\n     * @type {number|undefined}\n     */\n    this.lastDistance_ = undefined;\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.lastScaleDelta_ = 1;\n  }\n\n  /**\n   * Handle pointer drag events.\n   * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Event.\n   * @override\n   */\n  handleDragEvent(mapBrowserEvent) {\n    let scaleDelta = 1.0;\n\n    const touch0 = this.targetPointers[0];\n    const touch1 = this.targetPointers[1];\n    const dx = touch0.clientX - touch1.clientX;\n    const dy = touch0.clientY - touch1.clientY;\n\n    // distance between touches\n    const distance = Math.sqrt(dx * dx + dy * dy);\n\n    if (this.lastDistance_ !== undefined) {\n      scaleDelta = this.lastDistance_ / distance;\n    }\n    this.lastDistance_ = distance;\n\n    const map = mapBrowserEvent.map;\n    const view = map.getView();\n\n    if (scaleDelta != 1.0) {\n      this.lastScaleDelta_ = scaleDelta;\n    }\n\n    // scale anchor point.\n    this.anchor_ = map.getCoordinateFromPixelInternal(\n      map.getEventPixel(centroidFromPointers(this.targetPointers)),\n    );\n\n    // scale, bypass the resolution constraint\n    map.render();\n    view.adjustResolutionInternal(scaleDelta, this.anchor_);\n  }\n\n  /**\n   * Handle pointer up events.\n   * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Event.\n   * @return {boolean} If the event was consumed.\n   * @override\n   */\n  handleUpEvent(mapBrowserEvent) {\n    if (this.targetPointers.length < 2) {\n      const map = mapBrowserEvent.map;\n      const view = map.getView();\n      const direction = this.lastScaleDelta_ > 1 ? 1 : -1;\n      view.endInteraction(this.duration_, direction);\n      return false;\n    }\n    return true;\n  }\n\n  /**\n   * Handle pointer down events.\n   * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Event.\n   * @return {boolean} If the event was consumed.\n   * @override\n   */\n  handleDownEvent(mapBrowserEvent) {\n    if (this.targetPointers.length >= 2) {\n      const map = mapBrowserEvent.map;\n      this.anchor_ = null;\n      this.lastDistance_ = undefined;\n      this.lastScaleDelta_ = 1;\n      if (!this.handlingDownUpSequence) {\n        map.getView().beginInteraction();\n      }\n      return true;\n    }\n    return false;\n  }\n}\n\nexport default PinchZoom;\n", "/**\n * @module ol/interaction/defaults\n */\nimport Collection from '../Collection.js';\nimport Kinetic from '../Kinetic.js';\nimport DoubleClickZoom from './DoubleClickZoom.js';\nimport DragPan from './DragPan.js';\nimport DragRotate from './DragRotate.js';\nimport DragZoom from './DragZoom.js';\nimport KeyboardPan from './KeyboardPan.js';\nimport KeyboardZoom from './KeyboardZoom.js';\nimport MouseWheelZoom from './MouseWheelZoom.js';\nimport PinchRotate from './PinchRotate.js';\nimport PinchZoom from './PinchZoom.js';\n\n/**\n * @typedef {Object} DefaultsOptions\n * @property {boolean} [altShiftDragRotate=true] Whether Alt-Shift-drag rotate is\n * desired.\n * @property {boolean} [onFocusOnly=false] Interact only when the map has the\n * focus. This affects the `MouseWheelZoom` and `DragPan` interactions and is\n * useful when page scroll is desired for maps that do not have the browser's\n * focus.\n * @property {boolean} [doubleClickZoom=true] Whether double click zoom is\n * desired.\n * @property {boolean} [keyboard=true] Whether keyboard interaction is desired.\n * @property {boolean} [mouseWheelZoom=true] Whether mousewheel zoom is desired.\n * @property {boolean} [shiftDragZoom=true] Whether Shift-drag zoom is desired.\n * @property {boolean} [dragPan=true] Whether drag pan is desired.\n * @property {boolean} [pinchRotate=true] Whether pinch rotate is desired.\n * @property {boolean} [pinchZoom=true] Whether pinch zoom is desired.\n * @property {number} [zoomDelta] Zoom level delta when using keyboard or double click zoom.\n * @property {number} [zoomDuration] Duration of the zoom animation in\n * milliseconds.\n */\n\n/**\n * Set of interactions included in maps by default. Specific interactions can be\n * excluded by setting the appropriate option to false in the constructor\n * options, but the order of the interactions is fixed.  If you want to specify\n * a different order for interactions, you will need to create your own\n * {@link module:ol/interaction/Interaction~Interaction} instances and insert\n * them into a {@link module:ol/Collection~Collection} in the order you want\n * before creating your {@link module:ol/Map~Map} instance. Changing the order can\n * be of interest if the event propagation needs to be stopped at a point.\n * The default set of interactions, in sequence, is:\n * {@link module:ol/interaction/DragRotate~DragRotate}\n * {@link module:ol/interaction/DoubleClickZoom~DoubleClickZoom}\n * {@link module:ol/interaction/DragPan~DragPan}\n * {@link module:ol/interaction/PinchRotate~PinchRotate}\n * {@link module:ol/interaction/PinchZoom~PinchZoom}\n * {@link module:ol/interaction/KeyboardPan~KeyboardPan}\n * {@link module:ol/interaction/KeyboardZoom~KeyboardZoom}\n * {@link module:ol/interaction/MouseWheelZoom~MouseWheelZoom}\n * {@link module:ol/interaction/DragZoom~DragZoom}\n *\n * @param {DefaultsOptions} [options] Defaults options.\n * @return {Collection<import(\"./Interaction.js\").default>}\n * A collection of interactions to be used with the {@link module:ol/Map~Map}\n * constructor's `interactions` option.\n * @api\n */\nexport function defaults(options) {\n  options = options ? options : {};\n\n  /** @type {Collection<import(\"./Interaction.js\").default>} */\n  const interactions = new Collection();\n\n  const kinetic = new Kinetic(-0.005, 0.05, 100);\n\n  const altShiftDragRotate =\n    options.altShiftDragRotate !== undefined\n      ? options.altShiftDragRotate\n      : true;\n  if (altShiftDragRotate) {\n    interactions.push(new DragRotate());\n  }\n\n  const doubleClickZoom =\n    options.doubleClickZoom !== undefined ? options.doubleClickZoom : true;\n  if (doubleClickZoom) {\n    interactions.push(\n      new DoubleClickZoom({\n        delta: options.zoomDelta,\n        duration: options.zoomDuration,\n      }),\n    );\n  }\n\n  const dragPan = options.dragPan !== undefined ? options.dragPan : true;\n  if (dragPan) {\n    interactions.push(\n      new DragPan({\n        onFocusOnly: options.onFocusOnly,\n        kinetic: kinetic,\n      }),\n    );\n  }\n\n  const pinchRotate =\n    options.pinchRotate !== undefined ? options.pinchRotate : true;\n  if (pinchRotate) {\n    interactions.push(new PinchRotate());\n  }\n\n  const pinchZoom = options.pinchZoom !== undefined ? options.pinchZoom : true;\n  if (pinchZoom) {\n    interactions.push(\n      new PinchZoom({\n        duration: options.zoomDuration,\n      }),\n    );\n  }\n\n  const keyboard = options.keyboard !== undefined ? options.keyboard : true;\n  if (keyboard) {\n    interactions.push(new KeyboardPan());\n    interactions.push(\n      new KeyboardZoom({\n        delta: options.zoomDelta,\n        duration: options.zoomDuration,\n      }),\n    );\n  }\n\n  const mouseWheelZoom =\n    options.mouseWheelZoom !== undefined ? options.mouseWheelZoom : true;\n  if (mouseWheelZoom) {\n    interactions.push(\n      new MouseWheelZoom({\n        onFocusOnly: options.onFocusOnly,\n        duration: options.zoomDuration,\n      }),\n    );\n  }\n\n  const shiftDragZoom =\n    options.shiftDragZoom !== undefined ? options.shiftDragZoom : true;\n  if (shiftDragZoom) {\n    interactions.push(\n      new DragZoom({\n        duration: options.zoomDuration,\n      }),\n    );\n  }\n\n  return interactions;\n}\n", "/**\n * @module ol/layer/Property\n */\n\n/**\n * @enum {string}\n */\nexport default {\n  OPACITY: 'opacity',\n  VISIBLE: 'visible',\n  EXTENT: 'extent',\n  Z_INDEX: 'zIndex',\n  MAX_RESOLUTION: 'maxResolution',\n  MIN_RESOLUTION: 'minResolution',\n  MAX_ZOOM: 'maxZoom',\n  MIN_ZOOM: 'minZoom',\n  SOURCE: 'source',\n  MAP: 'map',\n};\n", "/**\n * @module ol/layer/Base\n */\nimport BaseObject from '../Object.js';\nimport {assert} from '../asserts.js';\nimport {clamp} from '../math.js';\nimport {abstract} from '../util.js';\nimport LayerProperty from './Property.js';\n\n/**\n * A css color, or a function called with a view resolution returning a css color.\n *\n * @typedef {string|function(number):string} BackgroundColor\n * @api\n */\n\n/**\n * @typedef {import(\"../ObjectEventType.js\").Types|'change:extent'|'change:maxResolution'|'change:maxZoom'|\n *    'change:minResolution'|'change:minZoom'|'change:opacity'|'change:visible'|'change:zIndex'} BaseLayerObjectEventTypes\n */\n\n/***\n * @template Return\n * @typedef {import(\"../Observable.js\").OnSignature<import(\"../Observable.js\").EventTypes, import(\"../events/Event.js\").default, Return> &\n *   import(\"../Observable.js\").OnSignature<BaseLayerObjectEventTypes, import(\"../Object.js\").ObjectEvent, Return> &\n *   import(\"../Observable.js\").CombinedOnSignature<import(\"../Observable.js\").EventTypes|BaseLayerObjectEventTypes, Return>} BaseLayerOnSignature\n */\n\n/**\n * @template {Object<string, *>} [Properties=Object<string, *>]\n * @typedef {Object} Options\n * @property {string} [className='ol-layer'] A CSS class name to set to the layer element.\n * @property {number} [opacity=1] Opacity (0, 1).\n * @property {boolean} [visible=true] Visibility.\n * @property {import(\"../extent.js\").Extent} [extent] The bounding extent for layer rendering.  The layer will not be\n * rendered outside of this extent.\n * @property {number | undefined} [zIndex] The z-index for layer rendering.  At rendering time, the layers\n * will be ordered, first by Z-index and then by position. When `undefined`, a `zIndex` of 0 is assumed\n * for layers that are added to the map's `layers` collection, or `Infinity` when the layer's `setMap()`\n * method was used.\n * @property {number} [minResolution] The minimum resolution (inclusive) at which this layer will be\n * visible.\n * @property {number} [maxResolution] The maximum resolution (exclusive) below which this layer will\n * be visible.\n * @property {number} [minZoom] The minimum view zoom level (exclusive) above which this layer will be\n * visible.\n * @property {number} [maxZoom] The maximum view zoom level (inclusive) at which this layer will\n * be visible.\n * @property {BackgroundColor} [background] Background color for the layer. If not specified, no background\n * will be rendered.\n * @property {Properties} [properties] Arbitrary observable properties. Can be accessed with `#get()` and `#set()`.\n */\n\n/**\n * @classdesc\n * Abstract base class; normally only used for creating subclasses and not\n * instantiated in apps.\n * Note that with {@link module:ol/layer/Base~BaseLayer} and all its subclasses, any property set in\n * the options is set as a {@link module:ol/Object~BaseObject} property on the layer object, so\n * is observable, and has get/set accessors.\n *\n * @api\n * @template {Object<string, *>} [Properties=Object<string, *>]\n * @extends {BaseObject<NoInfer<Properties> & Object<string, *>>}\n */\nclass BaseLayer extends BaseObject {\n  /**\n   * @param {Options<NoInfer<Properties>>} options Layer options.\n   */\n  constructor(options) {\n    super();\n\n    /***\n     * @type {BaseLayerOnSignature<import(\"../events.js\").EventsKey>}\n     */\n    this.on;\n\n    /***\n     * @type {BaseLayerOnSignature<import(\"../events.js\").EventsKey>}\n     */\n    this.once;\n\n    /***\n     * @type {BaseLayerOnSignature<void>}\n     */\n    this.un;\n\n    /**\n     * @type {BackgroundColor|false}\n     * @private\n     */\n    this.background_ = options.background;\n\n    /**\n     * @type {?}\n     */\n    const properties = Object.assign({}, options);\n    if (typeof options.properties === 'object') {\n      delete properties.properties;\n      Object.assign(properties, options.properties);\n    }\n\n    properties[LayerProperty.OPACITY] =\n      options.opacity !== undefined ? options.opacity : 1;\n    assert(\n      typeof properties[LayerProperty.OPACITY] === 'number',\n      'Layer opacity must be a number',\n    );\n\n    properties[LayerProperty.VISIBLE] =\n      options.visible !== undefined ? options.visible : true;\n    properties[LayerProperty.Z_INDEX] = options.zIndex;\n    properties[LayerProperty.MAX_RESOLUTION] =\n      options.maxResolution !== undefined ? options.maxResolution : Infinity;\n    properties[LayerProperty.MIN_RESOLUTION] =\n      options.minResolution !== undefined ? options.minResolution : 0;\n    properties[LayerProperty.MIN_ZOOM] =\n      options.minZoom !== undefined ? options.minZoom : -Infinity;\n    properties[LayerProperty.MAX_ZOOM] =\n      options.maxZoom !== undefined ? options.maxZoom : Infinity;\n\n    /**\n     * @type {string}\n     * @private\n     */\n    this.className_ =\n      properties.className !== undefined ? properties.className : 'ol-layer';\n    delete properties.className;\n\n    this.setProperties(properties);\n\n    /**\n     * @type {import(\"./Layer.js\").State}\n     * @private\n     */\n    this.state_ = null;\n  }\n\n  /**\n   * Get the background for this layer.\n   * @return {BackgroundColor|false} Layer background.\n   */\n  getBackground() {\n    return this.background_;\n  }\n\n  /**\n   * @return {string} CSS class name.\n   */\n  getClassName() {\n    return this.className_;\n  }\n\n  /**\n   * This method is not meant to be called by layers or layer renderers because the state\n   * is incorrect if the layer is included in a layer group.\n   *\n   * @param {boolean} [managed] Layer is managed.\n   * @return {import(\"./Layer.js\").State} Layer state.\n   */\n  getLayerState(managed) {\n    /** @type {import(\"./Layer.js\").State} */\n    const state =\n      this.state_ ||\n      /** @type {?} */ ({\n        layer: this,\n        managed: managed === undefined ? true : managed,\n      });\n    const zIndex = this.getZIndex();\n    state.opacity = clamp(Math.round(this.getOpacity() * 100) / 100, 0, 1);\n    state.visible = this.getVisible();\n    state.extent = this.getExtent();\n    state.zIndex = zIndex === undefined && !state.managed ? Infinity : zIndex;\n    state.maxResolution = this.getMaxResolution();\n    state.minResolution = Math.max(this.getMinResolution(), 0);\n    state.minZoom = this.getMinZoom();\n    state.maxZoom = this.getMaxZoom();\n    this.state_ = state;\n\n    return state;\n  }\n\n  /**\n   * @abstract\n   * @param {Array<import(\"./Layer.js\").default>} [array] Array of layers (to be\n   *     modified in place).\n   * @return {Array<import(\"./Layer.js\").default>} Array of layers.\n   */\n  getLayersArray(array) {\n    return abstract();\n  }\n\n  /**\n   * @abstract\n   * @param {Array<import(\"./Layer.js\").State>} [states] Optional list of layer\n   *     states (to be modified in place).\n   * @return {Array<import(\"./Layer.js\").State>} List of layer states.\n   */\n  getLayerStatesArray(states) {\n    return abstract();\n  }\n\n  /**\n   * Return the {@link module:ol/extent~Extent extent} of the layer or `undefined` if it\n   * will be visible regardless of extent.\n   * @return {import(\"../extent.js\").Extent|undefined} The layer extent.\n   * @observable\n   * @api\n   */\n  getExtent() {\n    return /** @type {import(\"../extent.js\").Extent|undefined} */ (\n      this.get(LayerProperty.EXTENT)\n    );\n  }\n\n  /**\n   * Return the maximum resolution of the layer. Returns Infinity if\n   * the layer has no maximum resolution set.\n   * @return {number} The maximum resolution of the layer.\n   * @observable\n   * @api\n   */\n  getMaxResolution() {\n    return /** @type {number} */ (this.get(LayerProperty.MAX_RESOLUTION));\n  }\n\n  /**\n   * Return the minimum resolution of the layer. Returns 0 if\n   * the layer has no minimum resolution set.\n   * @return {number} The minimum resolution of the layer.\n   * @observable\n   * @api\n   */\n  getMinResolution() {\n    return /** @type {number} */ (this.get(LayerProperty.MIN_RESOLUTION));\n  }\n\n  /**\n   * Return the minimum zoom level of the layer. Returns -Infinity if\n   * the layer has no minimum zoom set.\n   * @return {number} The minimum zoom level of the layer.\n   * @observable\n   * @api\n   */\n  getMinZoom() {\n    return /** @type {number} */ (this.get(LayerProperty.MIN_ZOOM));\n  }\n\n  /**\n   * Return the maximum zoom level of the layer. Returns Infinity if\n   * the layer has no maximum zoom set.\n   * @return {number} The maximum zoom level of the layer.\n   * @observable\n   * @api\n   */\n  getMaxZoom() {\n    return /** @type {number} */ (this.get(LayerProperty.MAX_ZOOM));\n  }\n\n  /**\n   * Return the opacity of the layer (between 0 and 1).\n   * @return {number} The opacity of the layer.\n   * @observable\n   * @api\n   */\n  getOpacity() {\n    return /** @type {number} */ (this.get(LayerProperty.OPACITY));\n  }\n\n  /**\n   * @abstract\n   * @return {import(\"../source/Source.js\").State} Source state.\n   */\n  getSourceState() {\n    return abstract();\n  }\n\n  /**\n   * Return the value of this layer's `visible` property. To find out whether the layer\n   * is visible on a map, use `isVisible()` instead.\n   * @return {boolean} The value of the `visible` property of the layer.\n   * @observable\n   * @api\n   */\n  getVisible() {\n    return /** @type {boolean} */ (this.get(LayerProperty.VISIBLE));\n  }\n\n  /**\n   * Return the Z-index of the layer, which is used to order layers before\n   * rendering. Returns undefined if the layer is unmanaged.\n   * @return {number|undefined} The Z-index of the layer.\n   * @observable\n   * @api\n   */\n  getZIndex() {\n    return /** @type {number|undefined} */ (this.get(LayerProperty.Z_INDEX));\n  }\n\n  /**\n   * Sets the background color.\n   * @param {BackgroundColor} [background] Background color.\n   */\n  setBackground(background) {\n    this.background_ = background;\n    this.changed();\n  }\n\n  /**\n   * Set the extent at which the layer is visible.  If `undefined`, the layer\n   * will be visible at all extents.\n   * @param {import(\"../extent.js\").Extent|undefined} extent The extent of the layer.\n   * @observable\n   * @api\n   */\n  setExtent(extent) {\n    this.set(LayerProperty.EXTENT, extent);\n  }\n\n  /**\n   * Set the maximum resolution at which the layer is visible.\n   * @param {number} maxResolution The maximum resolution of the layer.\n   * @observable\n   * @api\n   */\n  setMaxResolution(maxResolution) {\n    this.set(LayerProperty.MAX_RESOLUTION, maxResolution);\n  }\n\n  /**\n   * Set the minimum resolution at which the layer is visible.\n   * @param {number} minResolution The minimum resolution of the layer.\n   * @observable\n   * @api\n   */\n  setMinResolution(minResolution) {\n    this.set(LayerProperty.MIN_RESOLUTION, minResolution);\n  }\n\n  /**\n   * Set the maximum zoom (exclusive) at which the layer is visible.\n   * Note that the zoom levels for layer visibility are based on the\n   * view zoom level, which may be different from a tile source zoom level.\n   * @param {number} maxZoom The maximum zoom of the layer.\n   * @observable\n   * @api\n   */\n  setMaxZoom(maxZoom) {\n    this.set(LayerProperty.MAX_ZOOM, maxZoom);\n  }\n\n  /**\n   * Set the minimum zoom (inclusive) at which the layer is visible.\n   * Note that the zoom levels for layer visibility are based on the\n   * view zoom level, which may be different from a tile source zoom level.\n   * @param {number} minZoom The minimum zoom of the layer.\n   * @observable\n   * @api\n   */\n  setMinZoom(minZoom) {\n    this.set(LayerProperty.MIN_ZOOM, minZoom);\n  }\n\n  /**\n   * Set the opacity of the layer, allowed values range from 0 to 1.\n   * @param {number} opacity The opacity of the layer.\n   * @observable\n   * @api\n   */\n  setOpacity(opacity) {\n    assert(typeof opacity === 'number', 'Layer opacity must be a number');\n    this.set(LayerProperty.OPACITY, opacity);\n  }\n\n  /**\n   * Set the visibility of the layer (`true` or `false`).\n   * @param {boolean} visible The visibility of the layer.\n   * @observable\n   * @api\n   */\n  setVisible(visible) {\n    this.set(LayerProperty.VISIBLE, visible);\n  }\n\n  /**\n   * Set Z-index of the layer, which is used to order layers before rendering.\n   * The default Z-index is 0.\n   * @param {number} zindex The z-index of the layer.\n   * @observable\n   * @api\n   */\n  setZIndex(zindex) {\n    this.set(LayerProperty.Z_INDEX, zindex);\n  }\n\n  /**\n   * Clean up.\n   * @override\n   */\n  disposeInternal() {\n    if (this.state_) {\n      this.state_.layer = null;\n      this.state_ = null;\n    }\n    super.disposeInternal();\n  }\n}\n\nexport default BaseLayer;\n", "/**\n * @module ol/layer/Group\n */\nimport Collection from '../Collection.js';\nimport CollectionEventType from '../CollectionEventType.js';\nimport ObjectEventType from '../ObjectEventType.js';\nimport {assert} from '../asserts.js';\nimport {listen, unlistenByKey} from '../events.js';\nimport Event from '../events/Event.js';\nimport EventType from '../events/EventType.js';\nimport {getIntersection} from '../extent.js';\nimport {clear} from '../obj.js';\nimport {getUid} from '../util.js';\nimport BaseLayer from './Base.js';\n\n/**\n * @enum {string}\n */\nconst GroupEventType = {\n  /**\n   * Triggered when a layer is added\n   * @event GroupEvent#addlayer\n   * @api\n   */\n  ADDLAYER: 'addlayer',\n  /**\n   * Triggered when a layer is removed\n   * @event GroupEvent#removelayer\n   * @api\n   */\n  REMOVELAYER: 'removelayer',\n};\n\n/**\n * @classdesc\n * A layer group triggers 'addlayer' and 'removelayer' events when layers are added to or removed from\n * the group or one of its child groups.  When a layer group is added to or removed from another layer group,\n * a single event will be triggered (instead of one per layer in the group added or removed).\n */\nexport class GroupEvent extends Event {\n  /**\n   * @param {GroupEventType} type The event type.\n   * @param {BaseLayer} layer The layer.\n   */\n  constructor(type, layer) {\n    super(type);\n\n    /**\n     * The added or removed layer.\n     * @type {BaseLayer}\n     * @api\n     */\n    this.layer = layer;\n  }\n}\n\n/***\n * @template Return\n * @typedef {import(\"../Observable.js\").OnSignature<import(\"../Observable.js\").EventTypes, import(\"../events/Event.js\").default, Return> &\n *   import(\"../Observable.js\").OnSignature<import(\"./Base.js\").BaseLayerObjectEventTypes|\n *     'change:layers', import(\"../Object.js\").ObjectEvent, Return> &\n *   import(\"../Observable.js\").OnSignature<'addlayer'|'removelayer', GroupEvent, Return> &\n *   import(\"../Observable.js\").CombinedOnSignature<import(\"../Observable.js\").EventTypes|import(\"./Base.js\").BaseLayerObjectEventTypes|'addlayer'|'removelayer'|'change:layers', Return>} GroupOnSignature\n */\n\n/**\n * @typedef {Object} Options\n * @property {number} [opacity=1] Opacity (0, 1).\n * @property {boolean} [visible=true] Visibility.\n * @property {import(\"../extent.js\").Extent} [extent] The bounding extent for layer rendering.  The layer will not be\n * rendered outside of this extent.\n * @property {number} [zIndex] The z-index for layer rendering.  At rendering time, the layers\n * will be ordered, first by Z-index and then by position. When `undefined`, a `zIndex` of 0 is assumed\n * for layers that are added to the map's `layers` collection, or `Infinity` when the layer's `setMap()`\n * method was used.\n * @property {number} [minResolution] The minimum resolution (inclusive) at which this layer will be\n * visible.\n * @property {number} [maxResolution] The maximum resolution (exclusive) below which this layer will\n * be visible.\n * @property {number} [minZoom] The minimum view zoom level (exclusive) above which this layer will be\n * visible.\n * @property {number} [maxZoom] The maximum view zoom level (inclusive) at which this layer will\n * be visible.\n * @property {Array<import(\"./Base.js\").default>|Collection<import(\"./Base.js\").default>} [layers] Child layers.\n * @property {Object<string, *>} [properties] Arbitrary observable properties. Can be accessed with `#get()` and `#set()`.\n */\n\n/**\n * @enum {string}\n * @private\n */\nconst Property = {\n  LAYERS: 'layers',\n};\n\n/**\n * @classdesc\n * A {@link module:ol/Collection~Collection} of layers that are handled together.\n *\n * A generic `change` event is triggered when the group/Collection changes.\n *\n * @fires GroupEvent\n * @api\n */\nclass LayerGroup extends BaseLayer {\n  /**\n   * @param {Options} [options] Layer options.\n   */\n  constructor(options) {\n    options = options || {};\n    const baseOptions = /** @type {Options} */ (Object.assign({}, options));\n    delete baseOptions.layers;\n\n    let layers = options.layers;\n\n    super(baseOptions);\n\n    /***\n     * @type {GroupOnSignature<import(\"../events.js\").EventsKey>}\n     */\n    this.on;\n\n    /***\n     * @type {GroupOnSignature<import(\"../events.js\").EventsKey>}\n     */\n    this.once;\n\n    /***\n     * @type {GroupOnSignature<void>}\n     */\n    this.un;\n\n    /**\n     * @private\n     * @type {Array<import(\"../events.js\").EventsKey>}\n     */\n    this.layersListenerKeys_ = [];\n\n    /**\n     * @private\n     * @type {Object<string, Array<import(\"../events.js\").EventsKey>>}\n     */\n    this.listenerKeys_ = {};\n\n    this.addChangeListener(Property.LAYERS, this.handleLayersChanged_);\n\n    if (layers) {\n      if (Array.isArray(layers)) {\n        layers = new Collection(layers.slice(), {unique: true});\n      } else {\n        assert(\n          typeof (/** @type {?} */ (layers).getArray) === 'function',\n          'Expected `layers` to be an array or a `Collection`',\n        );\n      }\n    } else {\n      layers = new Collection(undefined, {unique: true});\n    }\n\n    this.setLayers(layers);\n  }\n\n  /**\n   * @private\n   */\n  handleLayerChange_() {\n    this.changed();\n  }\n\n  /**\n   * @private\n   */\n  handleLayersChanged_() {\n    this.layersListenerKeys_.forEach(unlistenByKey);\n    this.layersListenerKeys_.length = 0;\n\n    const layers = this.getLayers();\n    this.layersListenerKeys_.push(\n      listen(layers, CollectionEventType.ADD, this.handleLayersAdd_, this),\n      listen(\n        layers,\n        CollectionEventType.REMOVE,\n        this.handleLayersRemove_,\n        this,\n      ),\n    );\n\n    for (const id in this.listenerKeys_) {\n      this.listenerKeys_[id].forEach(unlistenByKey);\n    }\n    clear(this.listenerKeys_);\n\n    const layersArray = layers.getArray();\n    for (let i = 0, ii = layersArray.length; i < ii; i++) {\n      const layer = layersArray[i];\n      this.registerLayerListeners_(layer);\n      this.dispatchEvent(new GroupEvent(GroupEventType.ADDLAYER, layer));\n    }\n    this.changed();\n  }\n\n  /**\n   * @param {BaseLayer} layer The layer.\n   */\n  registerLayerListeners_(layer) {\n    const listenerKeys = [\n      listen(\n        layer,\n        ObjectEventType.PROPERTYCHANGE,\n        this.handleLayerChange_,\n        this,\n      ),\n      listen(layer, EventType.CHANGE, this.handleLayerChange_, this),\n    ];\n\n    if (layer instanceof LayerGroup) {\n      listenerKeys.push(\n        listen(layer, GroupEventType.ADDLAYER, this.handleLayerGroupAdd_, this),\n        listen(\n          layer,\n          GroupEventType.REMOVELAYER,\n          this.handleLayerGroupRemove_,\n          this,\n        ),\n      );\n    }\n\n    this.listenerKeys_[getUid(layer)] = listenerKeys;\n  }\n\n  /**\n   * @param {GroupEvent} event The layer group event.\n   */\n  handleLayerGroupAdd_(event) {\n    this.dispatchEvent(new GroupEvent(GroupEventType.ADDLAYER, event.layer));\n  }\n\n  /**\n   * @param {GroupEvent} event The layer group event.\n   */\n  handleLayerGroupRemove_(event) {\n    this.dispatchEvent(new GroupEvent(GroupEventType.REMOVELAYER, event.layer));\n  }\n\n  /**\n   * @param {import(\"../Collection.js\").CollectionEvent<import(\"./Base.js\").default>} collectionEvent CollectionEvent.\n   * @private\n   */\n  handleLayersAdd_(collectionEvent) {\n    const layer = collectionEvent.element;\n    this.registerLayerListeners_(layer);\n    this.dispatchEvent(new GroupEvent(GroupEventType.ADDLAYER, layer));\n    this.changed();\n  }\n\n  /**\n   * @param {import(\"../Collection.js\").CollectionEvent<import(\"./Base.js\").default>} collectionEvent CollectionEvent.\n   * @private\n   */\n  handleLayersRemove_(collectionEvent) {\n    const layer = collectionEvent.element;\n    const key = getUid(layer);\n    this.listenerKeys_[key].forEach(unlistenByKey);\n    delete this.listenerKeys_[key];\n    this.dispatchEvent(new GroupEvent(GroupEventType.REMOVELAYER, layer));\n    this.changed();\n  }\n\n  /**\n   * Returns the {@link module:ol/Collection~Collection collection} of {@link module:ol/layer/Layer~Layer layers}\n   * in this group.\n   * @return {!Collection<import(\"./Base.js\").default>} Collection of\n   *   {@link module:ol/layer/Base~BaseLayer layers} that are part of this group.\n   * @observable\n   * @api\n   */\n  getLayers() {\n    return /** @type {!Collection<import(\"./Base.js\").default>} */ (\n      this.get(Property.LAYERS)\n    );\n  }\n\n  /**\n   * Set the {@link module:ol/Collection~Collection collection} of {@link module:ol/layer/Layer~Layer layers}\n   * in this group.\n   * @param {!Collection<import(\"./Base.js\").default>} layers Collection of\n   *   {@link module:ol/layer/Base~BaseLayer layers} that are part of this group.\n   * @observable\n   * @api\n   */\n  setLayers(layers) {\n    const collection = this.getLayers();\n    if (collection) {\n      const currentLayers = collection.getArray();\n      for (let i = 0, ii = currentLayers.length; i < ii; ++i) {\n        this.dispatchEvent(\n          new GroupEvent(GroupEventType.REMOVELAYER, currentLayers[i]),\n        );\n      }\n    }\n\n    this.set(Property.LAYERS, layers);\n  }\n\n  /**\n   * @param {Array<import(\"./Layer.js\").default>} [array] Array of layers (to be modified in place).\n   * @return {Array<import(\"./Layer.js\").default>} Array of layers.\n   * @override\n   */\n  getLayersArray(array) {\n    array = array !== undefined ? array : [];\n    this.getLayers().forEach(function (layer) {\n      layer.getLayersArray(array);\n    });\n    return array;\n  }\n\n  /**\n   * Get the layer states list and use this groups z-index as the default\n   * for all layers in this and nested groups, if it is unset at this point.\n   * If dest is not provided and this group's z-index is undefined\n   * 0 is used a the default z-index.\n   * @param {Array<import(\"./Layer.js\").State>} [dest] Optional list\n   * of layer states (to be modified in place).\n   * @return {Array<import(\"./Layer.js\").State>} List of layer states.\n   * @override\n   */\n  getLayerStatesArray(dest) {\n    const states = dest !== undefined ? dest : [];\n    const pos = states.length;\n\n    this.getLayers().forEach(function (layer) {\n      layer.getLayerStatesArray(states);\n    });\n\n    const ownLayerState = this.getLayerState();\n    let defaultZIndex = ownLayerState.zIndex;\n    if (!dest && ownLayerState.zIndex === undefined) {\n      defaultZIndex = 0;\n    }\n    for (let i = pos, ii = states.length; i < ii; i++) {\n      const layerState = states[i];\n      layerState.opacity *= ownLayerState.opacity;\n      layerState.visible = layerState.visible && ownLayerState.visible;\n      layerState.maxResolution = Math.min(\n        layerState.maxResolution,\n        ownLayerState.maxResolution,\n      );\n      layerState.minResolution = Math.max(\n        layerState.minResolution,\n        ownLayerState.minResolution,\n      );\n      layerState.minZoom = Math.max(layerState.minZoom, ownLayerState.minZoom);\n      layerState.maxZoom = Math.min(layerState.maxZoom, ownLayerState.maxZoom);\n      if (ownLayerState.extent !== undefined) {\n        if (layerState.extent !== undefined) {\n          layerState.extent = getIntersection(\n            layerState.extent,\n            ownLayerState.extent,\n          );\n        } else {\n          layerState.extent = ownLayerState.extent;\n        }\n      }\n      if (layerState.zIndex === undefined) {\n        layerState.zIndex = defaultZIndex;\n      }\n    }\n\n    return states;\n  }\n\n  /**\n   * @return {import(\"../source/Source.js\").State} Source state.\n   * @override\n   */\n  getSourceState() {\n    return 'ready';\n  }\n}\n\nexport default LayerGroup;\n", "/**\n * @module ol/render/EventType\n */\n\n/**\n * @enum {string}\n */\nexport default {\n  /**\n   * Triggered before a layer is rendered.\n   * @event module:ol/render/Event~RenderEvent#prerender\n   * @api\n   */\n  PRERENDER: 'prerender',\n\n  /**\n   * Triggered after a layer is rendered.\n   * @event module:ol/render/Event~RenderEvent#postrender\n   * @api\n   */\n  POSTRENDER: 'postrender',\n\n  /**\n   * Triggered before layers are composed.  When dispatched by the map, the event object will not have\n   * a `context` set.  When dispatched by a layer, the event object will have a `context` set.  Only\n   * WebGL layers currently dispatch this event.\n   * @event module:ol/render/Event~RenderEvent#precompose\n   * @api\n   */\n  PRECOMPOSE: 'precompose',\n\n  /**\n   * Triggered after layers are composed.  When dispatched by the map, the event object will not have\n   * a `context` set.  When dispatched by a layer, the event object will have a `context` set.  Only\n   * WebGL layers currently dispatch this event.\n   * @event module:ol/render/Event~RenderEvent#postcompose\n   * @api\n   */\n  POSTCOMPOSE: 'postcompose',\n\n  /**\n   * Triggered when rendering is complete, i.e. all sources and tiles have\n   * finished loading for the current viewport, and all tiles are faded in.\n   * The event object will not have a `context` set.\n   * @event module:ol/render/Event~RenderEvent#rendercomplete\n   * @api\n   */\n  RENDERCOMPLETE: 'rendercomplete',\n};\n\n/**\n * @typedef {'postrender'|'precompose'|'postcompose'|'rendercomplete'} MapRenderEventTypes\n */\n\n/**\n * @typedef {'postrender'|'prerender'} LayerRenderEventTypes\n */\n", "/**\n * @module ol/layer/Layer\n */\nimport View from '../View.js';\nimport {assert} from '../asserts.js';\nimport {listen, unlistenByKey} from '../events.js';\nimport EventType from '../events/EventType.js';\nimport {intersects} from '../extent.js';\nimport RenderEventType from '../render/EventType.js';\nimport BaseLayer from './Base.js';\nimport LayerProperty from './Property.js';\n\n/**\n * @typedef {function(import(\"../Map.js\").FrameState):HTMLElement} RenderFunction\n */\n\n/**\n * @typedef {'sourceready'|'change:source'} LayerEventType\n */\n\n/***\n * @template Return\n * @typedef {import(\"../Observable.js\").OnSignature<import(\"../Observable.js\").EventTypes, import(\"../events/Event.js\").default, Return> &\n *   import(\"../Observable.js\").OnSignature<import(\"./Base.js\").BaseLayerObjectEventTypes|\n *     LayerEventType, import(\"../Object.js\").ObjectEvent, Return> &\n *   import(\"../Observable.js\").OnSignature<import(\"../render/EventType.js\").LayerRenderEventTypes, import(\"../render/Event.js\").default, Return> &\n *   import(\"../Observable.js\").CombinedOnSignature<import(\"../Observable.js\").EventTypes|import(\"./Base.js\").BaseLayerObjectEventTypes|LayerEventType|\n *     import(\"../render/EventType.js\").LayerRenderEventTypes, Return>} LayerOnSignature\n */\n\n/**\n * @template {import(\"../source/Source.js\").default} [SourceType=import(\"../source/Source.js\").default]\n * @template {Object<string, *>} [Properties=Object<string, *>]\n * @typedef {Object} Options\n * @property {string} [className='ol-layer'] A CSS class name to set to the layer element.\n * @property {number} [opacity=1] Opacity (0, 1).\n * @property {boolean} [visible=true] Visibility.\n * @property {import(\"../extent.js\").Extent} [extent] The bounding extent for layer rendering.  The layer will not be\n * rendered outside of this extent.\n * @property {number} [zIndex] The z-index for layer rendering.  At rendering time, the layers\n * will be ordered, first by Z-index and then by position. When `undefined`, a `zIndex` of 0 is assumed\n * for layers that are added to the map's `layers` collection, or `Infinity` when the layer's `setMap()`\n * method was used.\n * @property {number} [minResolution] The minimum resolution (inclusive) at which this layer will be\n * visible.\n * @property {number} [maxResolution] The maximum resolution (exclusive) below which this layer will\n * be visible.\n * @property {number} [minZoom] The minimum view zoom level (exclusive) above which this layer will be\n * visible.\n * @property {number} [maxZoom] The maximum view zoom level (inclusive) at which this layer will\n * be visible.\n * @property {SourceType} [source] Source for this layer.  If not provided to the constructor,\n * the source can be set by calling {@link module:ol/layer/Layer~Layer#setSource layer.setSource(source)} after\n * construction.\n * @property {import(\"../Map.js\").default|null} [map] Map.\n * @property {RenderFunction} [render] Render function. Takes the frame state as input and is expected to return an\n * HTML element. Will overwrite the default rendering for the layer.\n * @property {Properties} [properties] Arbitrary observable properties. Can be accessed with `#get()` and `#set()`.\n */\n\n/**\n * @typedef {Object} State\n * @property {import(\"./Layer.js\").default} layer Layer.\n * @property {number} opacity Opacity, the value is rounded to two digits to appear after the decimal point.\n * @property {boolean} visible Visible.\n * @property {boolean} managed Managed.\n * @property {import(\"../extent.js\").Extent} [extent] Extent.\n * @property {number} zIndex ZIndex.\n * @property {number} maxResolution Maximum resolution.\n * @property {number} minResolution Minimum resolution.\n * @property {number} minZoom Minimum zoom.\n * @property {number} maxZoom Maximum zoom.\n */\n\n/**\n * @classdesc\n * Base class from which all layer types are derived. This should only be instantiated\n * in the case where a custom layer is added to the map with a custom `render` function.\n * Such a function can be specified in the `options` object, and is expected to return an HTML element.\n *\n * A visual representation of raster or vector map data.\n * Layers group together those properties that pertain to how the data is to be\n * displayed, irrespective of the source of that data.\n *\n * Layers are usually added to a map with [map.addLayer()]{@link import(\"../Map.js\").default#addLayer}.\n * Components like {@link module:ol/interaction/Draw~Draw} use unmanaged layers\n * internally. These unmanaged layers are associated with the map using\n * [layer.setMap()]{@link module:ol/layer/Layer~Layer#setMap} instead.\n *\n * A generic `change` event is fired when the state of the source changes.\n * A `sourceready` event is fired when the layer's source is ready.\n *\n * @fires import(\"../render/Event.js\").RenderEvent#prerender\n * @fires import(\"../render/Event.js\").RenderEvent#postrender\n * @fires import(\"../events/Event.js\").BaseEvent#sourceready\n *\n * @template {import(\"../source/Source.js\").default} [SourceType=import(\"../source/Source.js\").default]\n * @template {import(\"../renderer/Layer.js\").default} [RendererType=import(\"../renderer/Layer.js\").default]\n * @template {Object<string, *>} [Properties=Object<string, *>]\n * @extends {BaseLayer<NoInfer<Properties>>}\n * @api\n */\nclass Layer extends BaseLayer {\n  /**\n   * @param {Options<SourceType, NoInfer<Properties>>} options Layer options.\n   */\n  constructor(options) {\n    const baseOptions = Object.assign({}, options);\n    delete baseOptions.source;\n\n    super(baseOptions);\n\n    /***\n     * @type {LayerOnSignature<import(\"../events.js\").EventsKey>}\n     */\n    this.on;\n\n    /***\n     * @type {LayerOnSignature<import(\"../events.js\").EventsKey>}\n     */\n    this.once;\n\n    /***\n     * @type {LayerOnSignature<void>}\n     */\n    this.un;\n\n    /**\n     * @private\n     * @type {?import(\"../events.js\").EventsKey}\n     */\n    this.mapPrecomposeKey_ = null;\n\n    /**\n     * @private\n     * @type {?import(\"../events.js\").EventsKey}\n     */\n    this.mapRenderKey_ = null;\n\n    /**\n     * @private\n     * @type {?import(\"../events.js\").EventsKey}\n     */\n    this.sourceChangeKey_ = null;\n\n    /**\n     * @private\n     * @type {RendererType}\n     */\n    this.renderer_ = null;\n\n    /**\n     * @private\n     * @type {boolean}\n     */\n    this.sourceReady_ = false;\n\n    /**\n     * @protected\n     * @type {boolean}\n     */\n    this.rendered = false;\n\n    // Overwrite default render method with a custom one\n    if (options.render) {\n      this.render = options.render;\n    }\n\n    if (options.map) {\n      this.setMap(options.map);\n    }\n\n    this.addChangeListener(\n      LayerProperty.SOURCE,\n      this.handleSourcePropertyChange_,\n    );\n\n    const source = options.source\n      ? /** @type {SourceType} */ (options.source)\n      : null;\n    this.setSource(source);\n  }\n\n  /**\n   * @param {Array<import(\"./Layer.js\").default>} [array] Array of layers (to be modified in place).\n   * @return {Array<import(\"./Layer.js\").default>} Array of layers.\n   * @override\n   */\n  getLayersArray(array) {\n    array = array ? array : [];\n    array.push(this);\n    return array;\n  }\n\n  /**\n   * @param {Array<import(\"./Layer.js\").State>} [states] Optional list of layer states (to be modified in place).\n   * @return {Array<import(\"./Layer.js\").State>} List of layer states.\n   * @override\n   */\n  getLayerStatesArray(states) {\n    states = states ? states : [];\n    states.push(this.getLayerState());\n    return states;\n  }\n\n  /**\n   * Get the layer source.\n   * @return {SourceType|null} The layer source (or `null` if not yet set).\n   * @observable\n   * @api\n   */\n  getSource() {\n    return /** @type {SourceType} */ (this.get(LayerProperty.SOURCE)) || null;\n  }\n\n  /**\n   * @return {SourceType|null} The source being rendered.\n   */\n  getRenderSource() {\n    return this.getSource();\n  }\n\n  /**\n   * @return {import(\"../source/Source.js\").State} Source state.\n   * @override\n   */\n  getSourceState() {\n    const source = this.getSource();\n    return !source ? 'undefined' : source.getState();\n  }\n\n  /**\n   * @private\n   */\n  handleSourceChange_() {\n    this.changed();\n    if (this.sourceReady_ || this.getSource().getState() !== 'ready') {\n      return;\n    }\n    this.sourceReady_ = true;\n    this.dispatchEvent('sourceready');\n  }\n\n  /**\n   * @private\n   */\n  handleSourcePropertyChange_() {\n    if (this.sourceChangeKey_) {\n      unlistenByKey(this.sourceChangeKey_);\n      this.sourceChangeKey_ = null;\n    }\n    this.sourceReady_ = false;\n    const source = this.getSource();\n    if (source) {\n      this.sourceChangeKey_ = listen(\n        source,\n        EventType.CHANGE,\n        this.handleSourceChange_,\n        this,\n      );\n      if (source.getState() === 'ready') {\n        this.sourceReady_ = true;\n        setTimeout(() => {\n          this.dispatchEvent('sourceready');\n        }, 0);\n      }\n    }\n    this.changed();\n  }\n\n  /**\n   * @param {import(\"../pixel.js\").Pixel} pixel Pixel.\n   * @return {Promise<Array<import(\"../Feature.js\").FeatureLike>>} Promise that resolves with\n   * an array of features.\n   */\n  getFeatures(pixel) {\n    if (!this.renderer_) {\n      return Promise.resolve([]);\n    }\n    return this.renderer_.getFeatures(pixel);\n  }\n\n  /**\n   * @param {import(\"../pixel.js\").Pixel} pixel Pixel.\n   * @return {Uint8ClampedArray|Uint8Array|Float32Array|DataView|null} Pixel data.\n   */\n  getData(pixel) {\n    if (!this.renderer_ || !this.rendered) {\n      return null;\n    }\n    return this.renderer_.getData(pixel);\n  }\n\n  /**\n   * The layer is visible on the map view, i.e. within its min/max resolution or zoom and\n   * extent, not set to `visible: false`, and not inside a layer group that is set\n   * to `visible: false`.\n   * @param {View|import(\"../View.js\").ViewStateLayerStateExtent} [view] View or {@link import(\"../Map.js\").FrameState}.\n   * Only required when the layer is not added to a map.\n   * @return {boolean} The layer is visible in the map view.\n   * @api\n   */\n  isVisible(view) {\n    let frameState;\n    const map = this.getMapInternal();\n    if (!view && map) {\n      view = map.getView();\n    }\n    if (view instanceof View) {\n      frameState = {\n        viewState: view.getState(),\n        extent: view.calculateExtent(),\n      };\n    } else {\n      frameState = view;\n    }\n    if (!frameState.layerStatesArray && map) {\n      frameState.layerStatesArray = map.getLayerGroup().getLayerStatesArray();\n    }\n    let layerState;\n    if (frameState.layerStatesArray) {\n      layerState = frameState.layerStatesArray.find(\n        (layerState) => layerState.layer === this,\n      );\n      if (!layerState) {\n        return false;\n      }\n    } else {\n      layerState = this.getLayerState();\n    }\n\n    const layerExtent = this.getExtent();\n\n    return (\n      inView(layerState, frameState.viewState) &&\n      (!layerExtent || intersects(layerExtent, frameState.extent))\n    );\n  }\n\n  /**\n   * Get the attributions of the source of this layer for the given view.\n   * @param {View|import(\"../View.js\").ViewStateLayerStateExtent} [view] View or {@link import(\"../Map.js\").FrameState}.\n   * Only required when the layer is not added to a map.\n   * @return {Array<string>} Attributions for this layer at the given view.\n   * @api\n   */\n  getAttributions(view) {\n    if (!this.isVisible(view)) {\n      return [];\n    }\n    const getAttributions = this.getSource()?.getAttributions();\n    if (!getAttributions) {\n      return [];\n    }\n    const frameState =\n      view instanceof View ? view.getViewStateAndExtent() : view;\n    let attributions = getAttributions(frameState);\n    if (!Array.isArray(attributions)) {\n      attributions = [attributions];\n    }\n    return attributions;\n  }\n\n  /**\n   * In charge to manage the rendering of the layer. One layer type is\n   * bounded with one layer renderer.\n   * @param {?import(\"../Map.js\").FrameState} frameState Frame state.\n   * @param {HTMLElement} target Target which the renderer may (but need not) use\n   * for rendering its content.\n   * @return {HTMLElement|null} The rendered element.\n   */\n  render(frameState, target) {\n    const layerRenderer = this.getRenderer();\n\n    if (layerRenderer.prepareFrame(frameState)) {\n      this.rendered = true;\n      return layerRenderer.renderFrame(frameState, target);\n    }\n    return null;\n  }\n\n  /**\n   * Called when a layer is not visible during a map render.\n   */\n  unrender() {\n    this.rendered = false;\n  }\n\n  /** @return {string} Declutter */\n  getDeclutter() {\n    return undefined;\n  }\n\n  /**\n   * @param {import(\"../Map.js\").FrameState} frameState Frame state.\n   * @param {import(\"../layer/Layer.js\").State} layerState Layer state.\n   */\n  renderDeclutter(frameState, layerState) {}\n\n  /**\n   * When the renderer follows a layout -> render approach, do the final rendering here.\n   * @param {import('../Map.js').FrameState} frameState Frame state\n   */\n  renderDeferred(frameState) {\n    const layerRenderer = this.getRenderer();\n    if (!layerRenderer) {\n      return;\n    }\n    layerRenderer.renderDeferred(frameState);\n  }\n\n  /**\n   * For use inside the library only.\n   * @param {import(\"../Map.js\").default|null} map Map.\n   */\n  setMapInternal(map) {\n    if (!map) {\n      this.unrender();\n    }\n    this.set(LayerProperty.MAP, map);\n  }\n\n  /**\n   * For use inside the library only.\n   * @return {import(\"../Map.js\").default|null} Map.\n   */\n  getMapInternal() {\n    return this.get(LayerProperty.MAP);\n  }\n\n  /**\n   * Sets the layer to be rendered on top of other layers on a map. The map will\n   * not manage this layer in its layers collection. This\n   * is useful for temporary layers. To remove an unmanaged layer from the map,\n   * use `#setMap(null)`.\n   *\n   * To add the layer to a map and have it managed by the map, use\n   * {@link module:ol/Map~Map#addLayer} instead.\n   * @param {import(\"../Map.js\").default|null} map Map.\n   * @api\n   */\n  setMap(map) {\n    if (this.mapPrecomposeKey_) {\n      unlistenByKey(this.mapPrecomposeKey_);\n      this.mapPrecomposeKey_ = null;\n    }\n    if (!map) {\n      this.changed();\n    }\n    if (this.mapRenderKey_) {\n      unlistenByKey(this.mapRenderKey_);\n      this.mapRenderKey_ = null;\n    }\n    if (map) {\n      this.mapPrecomposeKey_ = listen(\n        map,\n        RenderEventType.PRECOMPOSE,\n        this.handlePrecompose_,\n        this,\n      );\n      this.mapRenderKey_ = listen(this, EventType.CHANGE, map.render, map);\n      this.changed();\n    }\n  }\n\n  /**\n   * @param {import(\"../events/Event.js\").default} renderEvent Render event\n   * @private\n   */\n  handlePrecompose_(renderEvent) {\n    const layerStatesArray =\n      /** @type {import(\"../render/Event.js\").default} */ (renderEvent)\n        .frameState.layerStatesArray;\n    const layerState = this.getLayerState(false);\n    assert(\n      !layerStatesArray.some(\n        (arrayLayerState) => arrayLayerState.layer === layerState.layer,\n      ),\n      'A layer can only be added to the map once. Use either `layer.setMap()` or `map.addLayer()`, not both.',\n    );\n    layerStatesArray.push(layerState);\n  }\n\n  /**\n   * Set the layer source.\n   * @param {SourceType|null} source The layer source.\n   * @observable\n   * @api\n   */\n  setSource(source) {\n    this.set(LayerProperty.SOURCE, source);\n  }\n\n  /**\n   * Get the renderer for this layer.\n   * @return {RendererType|null} The layer renderer.\n   */\n  getRenderer() {\n    if (!this.renderer_) {\n      this.renderer_ = this.createRenderer();\n    }\n    return this.renderer_;\n  }\n\n  /**\n   * @return {boolean} The layer has a renderer.\n   */\n  hasRenderer() {\n    return !!this.renderer_;\n  }\n\n  /**\n   * Create a renderer for this layer.\n   * @return {RendererType} A layer renderer.\n   * @protected\n   */\n  createRenderer() {\n    return null;\n  }\n\n  /**\n   * This will clear the renderer so that a new one can be created next time it is needed\n   */\n  clearRenderer() {\n    if (this.renderer_) {\n      this.renderer_.dispose();\n      delete this.renderer_;\n    }\n  }\n\n  /**\n   * Clean up.\n   * @override\n   */\n  disposeInternal() {\n    this.clearRenderer();\n    this.setSource(null);\n    super.disposeInternal();\n  }\n}\n\n/**\n * Return `true` if the layer is visible and if the provided view state\n * has resolution and zoom levels that are in range of the layer's min/max.\n * @param {State} layerState Layer state.\n * @param {import(\"../View.js\").State} viewState View state.\n * @return {boolean} The layer is visible at the given view state.\n */\nexport function inView(layerState, viewState) {\n  if (!layerState.visible) {\n    return false;\n  }\n  const resolution = viewState.resolution;\n  if (\n    resolution < layerState.minResolution ||\n    resolution >= layerState.maxResolution\n  ) {\n    return false;\n  }\n  const zoom = viewState.zoom;\n  return zoom > layerState.minZoom && zoom <= layerState.maxZoom;\n}\n\nexport default Layer;\n", "\n/**\n * Rearranges items so that all items in the [left, k] are the smallest.\n * The k-th element will have the (k - left + 1)-th smallest value in [left, right].\n *\n * @template T\n * @param {T[]} arr the array to partially sort (in place)\n * @param {number} k middle index for partial sorting (as defined above)\n * @param {number} [left=0] left index of the range to sort\n * @param {number} [right=arr.length-1] right index\n * @param {(a: T, b: T) => number} [compare = (a, b) => a - b] compare function\n */\nexport default function quickselect(arr, k, left = 0, right = arr.length - 1, compare = defaultCompare) {\n\n    while (right > left) {\n        if (right - left > 600) {\n            const n = right - left + 1;\n            const m = k - left + 1;\n            const z = Math.log(n);\n            const s = 0.5 * Math.exp(2 * z / 3);\n            const sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1);\n            const newLeft = Math.max(left, Math.floor(k - m * s / n + sd));\n            const newRight = Math.min(right, Math.floor(k + (n - m) * s / n + sd));\n            quickselect(arr, k, newLeft, newRight, compare);\n        }\n\n        const t = arr[k];\n        let i = left;\n        /** @type {number} */\n        let j = right;\n\n        swap(arr, left, k);\n        if (compare(arr[right], t) > 0) swap(arr, left, right);\n\n        while (i < j) {\n            swap(arr, i, j);\n            i++;\n            j--;\n            while (compare(arr[i], t) < 0) i++;\n            while (compare(arr[j], t) > 0) j--;\n        }\n\n        if (compare(arr[left], t) === 0) swap(arr, left, j);\n        else {\n            j++;\n            swap(arr, j, right);\n        }\n\n        if (j <= k) left = j + 1;\n        if (k <= j) right = j - 1;\n    }\n}\n\n/**\n * @template T\n * @param {T[]} arr\n * @param {number} i\n * @param {number} j\n */\nfunction swap(arr, i, j) {\n    const tmp = arr[i];\n    arr[i] = arr[j];\n    arr[j] = tmp;\n}\n\n/**\n * @template T\n * @param {T} a\n * @param {T} b\n * @returns {number}\n */\nfunction defaultCompare(a, b) {\n    return a < b ? -1 : a > b ? 1 : 0;\n}\n", "import quickselect from 'quickselect';\n\nexport default class RBush {\n    constructor(maxEntries = 9) {\n        // max entries in a node is 9 by default; min node fill is 40% for best performance\n        this._maxEntries = Math.max(4, maxEntries);\n        this._minEntries = Math.max(2, Math.ceil(this._maxEntries * 0.4));\n        this.clear();\n    }\n\n    all() {\n        return this._all(this.data, []);\n    }\n\n    search(bbox) {\n        let node = this.data;\n        const result = [];\n\n        if (!intersects(bbox, node)) return result;\n\n        const toBBox = this.toBBox;\n        const nodesToSearch = [];\n\n        while (node) {\n            for (let i = 0; i < node.children.length; i++) {\n                const child = node.children[i];\n                const childBBox = node.leaf ? toBBox(child) : child;\n\n                if (intersects(bbox, childBBox)) {\n                    if (node.leaf) result.push(child);\n                    else if (contains(bbox, childBBox)) this._all(child, result);\n                    else nodesToSearch.push(child);\n                }\n            }\n            node = nodesToSearch.pop();\n        }\n\n        return result;\n    }\n\n    collides(bbox) {\n        let node = this.data;\n\n        if (!intersects(bbox, node)) return false;\n\n        const nodesToSearch = [];\n        while (node) {\n            for (let i = 0; i < node.children.length; i++) {\n                const child = node.children[i];\n                const childBBox = node.leaf ? this.toBBox(child) : child;\n\n                if (intersects(bbox, childBBox)) {\n                    if (node.leaf || contains(bbox, childBBox)) return true;\n                    nodesToSearch.push(child);\n                }\n            }\n            node = nodesToSearch.pop();\n        }\n\n        return false;\n    }\n\n    load(data) {\n        if (!(data && data.length)) return this;\n\n        if (data.length < this._minEntries) {\n            for (let i = 0; i < data.length; i++) {\n                this.insert(data[i]);\n            }\n            return this;\n        }\n\n        // recursively build the tree with the given data from scratch using OMT algorithm\n        let node = this._build(data.slice(), 0, data.length - 1, 0);\n\n        if (!this.data.children.length) {\n            // save as is if tree is empty\n            this.data = node;\n\n        } else if (this.data.height === node.height) {\n            // split root if trees have the same height\n            this._splitRoot(this.data, node);\n\n        } else {\n            if (this.data.height < node.height) {\n                // swap trees if inserted one is bigger\n                const tmpNode = this.data;\n                this.data = node;\n                node = tmpNode;\n            }\n\n            // insert the small tree into the large tree at appropriate level\n            this._insert(node, this.data.height - node.height - 1, true);\n        }\n\n        return this;\n    }\n\n    insert(item) {\n        if (item) this._insert(item, this.data.height - 1);\n        return this;\n    }\n\n    clear() {\n        this.data = createNode([]);\n        return this;\n    }\n\n    remove(item, equalsFn) {\n        if (!item) return this;\n\n        let node = this.data;\n        const bbox = this.toBBox(item);\n        const path = [];\n        const indexes = [];\n        let i, parent, goingUp;\n\n        // depth-first iterative tree traversal\n        while (node || path.length) {\n\n            if (!node) { // go up\n                node = path.pop();\n                parent = path[path.length - 1];\n                i = indexes.pop();\n                goingUp = true;\n            }\n\n            if (node.leaf) { // check current node\n                const index = findItem(item, node.children, equalsFn);\n\n                if (index !== -1) {\n                    // item found, remove the item and condense tree upwards\n                    node.children.splice(index, 1);\n                    path.push(node);\n                    this._condense(path);\n                    return this;\n                }\n            }\n\n            if (!goingUp && !node.leaf && contains(node, bbox)) { // go down\n                path.push(node);\n                indexes.push(i);\n                i = 0;\n                parent = node;\n                node = node.children[0];\n\n            } else if (parent) { // go right\n                i++;\n                node = parent.children[i];\n                goingUp = false;\n\n            } else node = null; // nothing found\n        }\n\n        return this;\n    }\n\n    toBBox(item) { return item; }\n\n    compareMinX(a, b) { return a.minX - b.minX; }\n    compareMinY(a, b) { return a.minY - b.minY; }\n\n    toJSON() { return this.data; }\n\n    fromJSON(data) {\n        this.data = data;\n        return this;\n    }\n\n    _all(node, result) {\n        const nodesToSearch = [];\n        while (node) {\n            if (node.leaf) result.push(...node.children);\n            else nodesToSearch.push(...node.children);\n\n            node = nodesToSearch.pop();\n        }\n        return result;\n    }\n\n    _build(items, left, right, height) {\n\n        const N = right - left + 1;\n        let M = this._maxEntries;\n        let node;\n\n        if (N <= M) {\n            // reached leaf level; return leaf\n            node = createNode(items.slice(left, right + 1));\n            calcBBox(node, this.toBBox);\n            return node;\n        }\n\n        if (!height) {\n            // target height of the bulk-loaded tree\n            height = Math.ceil(Math.log(N) / Math.log(M));\n\n            // target number of root entries to maximize storage utilization\n            M = Math.ceil(N / Math.pow(M, height - 1));\n        }\n\n        node = createNode([]);\n        node.leaf = false;\n        node.height = height;\n\n        // split the items into M mostly square tiles\n\n        const N2 = Math.ceil(N / M);\n        const N1 = N2 * Math.ceil(Math.sqrt(M));\n\n        multiSelect(items, left, right, N1, this.compareMinX);\n\n        for (let i = left; i <= right; i += N1) {\n\n            const right2 = Math.min(i + N1 - 1, right);\n\n            multiSelect(items, i, right2, N2, this.compareMinY);\n\n            for (let j = i; j <= right2; j += N2) {\n\n                const right3 = Math.min(j + N2 - 1, right2);\n\n                // pack each entry recursively\n                node.children.push(this._build(items, j, right3, height - 1));\n            }\n        }\n\n        calcBBox(node, this.toBBox);\n\n        return node;\n    }\n\n    _chooseSubtree(bbox, node, level, path) {\n        while (true) {\n            path.push(node);\n\n            if (node.leaf || path.length - 1 === level) break;\n\n            let minArea = Infinity;\n            let minEnlargement = Infinity;\n            let targetNode;\n\n            for (let i = 0; i < node.children.length; i++) {\n                const child = node.children[i];\n                const area = bboxArea(child);\n                const enlargement = enlargedArea(bbox, child) - area;\n\n                // choose entry with the least area enlargement\n                if (enlargement < minEnlargement) {\n                    minEnlargement = enlargement;\n                    minArea = area < minArea ? area : minArea;\n                    targetNode = child;\n\n                } else if (enlargement === minEnlargement) {\n                    // otherwise choose one with the smallest area\n                    if (area < minArea) {\n                        minArea = area;\n                        targetNode = child;\n                    }\n                }\n            }\n\n            node = targetNode || node.children[0];\n        }\n\n        return node;\n    }\n\n    _insert(item, level, isNode) {\n        const bbox = isNode ? item : this.toBBox(item);\n        const insertPath = [];\n\n        // find the best node for accommodating the item, saving all nodes along the path too\n        const node = this._chooseSubtree(bbox, this.data, level, insertPath);\n\n        // put the item into the node\n        node.children.push(item);\n        extend(node, bbox);\n\n        // split on node overflow; propagate upwards if necessary\n        while (level >= 0) {\n            if (insertPath[level].children.length > this._maxEntries) {\n                this._split(insertPath, level);\n                level--;\n            } else break;\n        }\n\n        // adjust bboxes along the insertion path\n        this._adjustParentBBoxes(bbox, insertPath, level);\n    }\n\n    // split overflowed node into two\n    _split(insertPath, level) {\n        const node = insertPath[level];\n        const M = node.children.length;\n        const m = this._minEntries;\n\n        this._chooseSplitAxis(node, m, M);\n\n        const splitIndex = this._chooseSplitIndex(node, m, M);\n\n        const newNode = createNode(node.children.splice(splitIndex, node.children.length - splitIndex));\n        newNode.height = node.height;\n        newNode.leaf = node.leaf;\n\n        calcBBox(node, this.toBBox);\n        calcBBox(newNode, this.toBBox);\n\n        if (level) insertPath[level - 1].children.push(newNode);\n        else this._splitRoot(node, newNode);\n    }\n\n    _splitRoot(node, newNode) {\n        // split root node\n        this.data = createNode([node, newNode]);\n        this.data.height = node.height + 1;\n        this.data.leaf = false;\n        calcBBox(this.data, this.toBBox);\n    }\n\n    _chooseSplitIndex(node, m, M) {\n        let index;\n        let minOverlap = Infinity;\n        let minArea = Infinity;\n\n        for (let i = m; i <= M - m; i++) {\n            const bbox1 = distBBox(node, 0, i, this.toBBox);\n            const bbox2 = distBBox(node, i, M, this.toBBox);\n\n            const overlap = intersectionArea(bbox1, bbox2);\n            const area = bboxArea(bbox1) + bboxArea(bbox2);\n\n            // choose distribution with minimum overlap\n            if (overlap < minOverlap) {\n                minOverlap = overlap;\n                index = i;\n\n                minArea = area < minArea ? area : minArea;\n\n            } else if (overlap === minOverlap) {\n                // otherwise choose distribution with minimum area\n                if (area < minArea) {\n                    minArea = area;\n                    index = i;\n                }\n            }\n        }\n\n        return index || M - m;\n    }\n\n    // sorts node children by the best axis for split\n    _chooseSplitAxis(node, m, M) {\n        const compareMinX = node.leaf ? this.compareMinX : compareNodeMinX;\n        const compareMinY = node.leaf ? this.compareMinY : compareNodeMinY;\n        const xMargin = this._allDistMargin(node, m, M, compareMinX);\n        const yMargin = this._allDistMargin(node, m, M, compareMinY);\n\n        // if total distributions margin value is minimal for x, sort by minX,\n        // otherwise it's already sorted by minY\n        if (xMargin < yMargin) node.children.sort(compareMinX);\n    }\n\n    // total margin of all possible split distributions where each node is at least m full\n    _allDistMargin(node, m, M, compare) {\n        node.children.sort(compare);\n\n        const toBBox = this.toBBox;\n        const leftBBox = distBBox(node, 0, m, toBBox);\n        const rightBBox = distBBox(node, M - m, M, toBBox);\n        let margin = bboxMargin(leftBBox) + bboxMargin(rightBBox);\n\n        for (let i = m; i < M - m; i++) {\n            const child = node.children[i];\n            extend(leftBBox, node.leaf ? toBBox(child) : child);\n            margin += bboxMargin(leftBBox);\n        }\n\n        for (let i = M - m - 1; i >= m; i--) {\n            const child = node.children[i];\n            extend(rightBBox, node.leaf ? toBBox(child) : child);\n            margin += bboxMargin(rightBBox);\n        }\n\n        return margin;\n    }\n\n    _adjustParentBBoxes(bbox, path, level) {\n        // adjust bboxes along the given tree path\n        for (let i = level; i >= 0; i--) {\n            extend(path[i], bbox);\n        }\n    }\n\n    _condense(path) {\n        // go through the path, removing empty nodes and updating bboxes\n        for (let i = path.length - 1, siblings; i >= 0; i--) {\n            if (path[i].children.length === 0) {\n                if (i > 0) {\n                    siblings = path[i - 1].children;\n                    siblings.splice(siblings.indexOf(path[i]), 1);\n\n                } else this.clear();\n\n            } else calcBBox(path[i], this.toBBox);\n        }\n    }\n}\n\nfunction findItem(item, items, equalsFn) {\n    if (!equalsFn) return items.indexOf(item);\n\n    for (let i = 0; i < items.length; i++) {\n        if (equalsFn(item, items[i])) return i;\n    }\n    return -1;\n}\n\n// calculate node's bbox from bboxes of its children\nfunction calcBBox(node, toBBox) {\n    distBBox(node, 0, node.children.length, toBBox, node);\n}\n\n// min bounding rectangle of node children from k to p-1\nfunction distBBox(node, k, p, toBBox, destNode) {\n    if (!destNode) destNode = createNode(null);\n    destNode.minX = Infinity;\n    destNode.minY = Infinity;\n    destNode.maxX = -Infinity;\n    destNode.maxY = -Infinity;\n\n    for (let i = k; i < p; i++) {\n        const child = node.children[i];\n        extend(destNode, node.leaf ? toBBox(child) : child);\n    }\n\n    return destNode;\n}\n\nfunction extend(a, b) {\n    a.minX = Math.min(a.minX, b.minX);\n    a.minY = Math.min(a.minY, b.minY);\n    a.maxX = Math.max(a.maxX, b.maxX);\n    a.maxY = Math.max(a.maxY, b.maxY);\n    return a;\n}\n\nfunction compareNodeMinX(a, b) { return a.minX - b.minX; }\nfunction compareNodeMinY(a, b) { return a.minY - b.minY; }\n\nfunction bboxArea(a)   { return (a.maxX - a.minX) * (a.maxY - a.minY); }\nfunction bboxMargin(a) { return (a.maxX - a.minX) + (a.maxY - a.minY); }\n\nfunction enlargedArea(a, b) {\n    return (Math.max(b.maxX, a.maxX) - Math.min(b.minX, a.minX)) *\n           (Math.max(b.maxY, a.maxY) - Math.min(b.minY, a.minY));\n}\n\nfunction intersectionArea(a, b) {\n    const minX = Math.max(a.minX, b.minX);\n    const minY = Math.max(a.minY, b.minY);\n    const maxX = Math.min(a.maxX, b.maxX);\n    const maxY = Math.min(a.maxY, b.maxY);\n\n    return Math.max(0, maxX - minX) *\n           Math.max(0, maxY - minY);\n}\n\nfunction contains(a, b) {\n    return a.minX <= b.minX &&\n           a.minY <= b.minY &&\n           b.maxX <= a.maxX &&\n           b.maxY <= a.maxY;\n}\n\nfunction intersects(a, b) {\n    return b.minX <= a.maxX &&\n           b.minY <= a.maxY &&\n           b.maxX >= a.minX &&\n           b.maxY >= a.minY;\n}\n\nfunction createNode(children) {\n    return {\n        children,\n        height: 1,\n        leaf: true,\n        minX: Infinity,\n        minY: Infinity,\n        maxX: -Infinity,\n        maxY: -Infinity\n    };\n}\n\n// sort an array so that items come in groups of n unsorted items, with groups sorted between each other;\n// combines selection algorithm with binary divide & conquer approach\n\nfunction multiSelect(arr, left, right, n, compare) {\n    const stack = [left, right];\n\n    while (stack.length) {\n        right = stack.pop();\n        left = stack.pop();\n\n        if (right - left <= n) continue;\n\n        const mid = left + Math.ceil((right - left) / n / 2) * n;\n        quickselect(arr, mid, left, right, compare);\n\n        stack.push(left, mid, mid, right);\n    }\n}\n", "/**\n * @module ol/color\n */\nimport {createCanvasContext2D} from './dom.js';\nimport {clamp, toFixed} from './math.js';\n\n/**\n * A color represented as a short array [red, green, blue, alpha].\n * red, green, and blue should be integers in the range 0..255 inclusive.\n * alpha should be a float in the range 0..1 inclusive. If no alpha value is\n * given then `1` will be used.\n * @typedef {Array<number>} Color\n * @api\n */\n\n/**\n * Color to indicate that no color should be rendered. This is meant to be used for per-reference\n * comparisons only.\n * @type {Color}\n */\nexport const NO_COLOR = [NaN, NaN, NaN, 0];\n\nlet colorParseContext;\n/**\n * @return {CanvasRenderingContext2D} The color parse context\n */\nfunction getColorParseContext() {\n  if (!colorParseContext) {\n    colorParseContext = createCanvasContext2D(1, 1, undefined, {\n      willReadFrequently: true,\n      desynchronized: true,\n    });\n  }\n  return colorParseContext;\n}\n\nconst rgbModernRegEx =\n  /^rgba?\\(\\s*(\\d+%?)\\s+(\\d+%?)\\s+(\\d+%?)(?:\\s*\\/\\s*(\\d+%|\\d*\\.\\d+|[01]))?\\s*\\)$/i;\nconst rgbLegacyAbsoluteRegEx =\n  /^rgba?\\(\\s*(\\d+)\\s*,\\s*(\\d+)\\s*,\\s*(\\d+)(?:\\s*,\\s*(\\d+%|\\d*\\.\\d+|[01]))?\\s*\\)$/i;\nconst rgbLegacyPercentageRegEx =\n  /^rgba?\\(\\s*(\\d+%)\\s*,\\s*(\\d+%)\\s*,\\s*(\\d+%)(?:\\s*,\\s*(\\d+%|\\d*\\.\\d+|[01]))?\\s*\\)$/i;\nconst hexRegEx = /^#([\\da-f]{3,4}|[\\da-f]{6}|[\\da-f]{8})$/i;\n\n/**\n * @param {string} s Color component as number or percentage.\n * @param {number} divider Divider for percentage.\n * @return {number} Color component.\n */\nfunction toColorComponent(s, divider) {\n  return s.endsWith('%')\n    ? Number(s.substring(0, s.length - 1)) / divider\n    : Number(s);\n}\n\n/**\n * @param {string} color Color string.\n */\nfunction throwInvalidColor(color) {\n  throw new Error('failed to parse \"' + color + '\" as color');\n}\n\n/**\n * @param {string} color Color string.\n * @return {Color} RGBa color array.\n */\nfunction parseRgba(color) {\n  // Fast lane for rgb(a) colors\n  if (color.toLowerCase().startsWith('rgb')) {\n    const rgb =\n      color.match(rgbLegacyAbsoluteRegEx) ||\n      color.match(rgbModernRegEx) ||\n      color.match(rgbLegacyPercentageRegEx);\n    if (rgb) {\n      const alpha = rgb[4];\n      const rgbDivider = 100 / 255;\n      return [\n        clamp((toColorComponent(rgb[1], rgbDivider) + 0.5) | 0, 0, 255),\n        clamp((toColorComponent(rgb[2], rgbDivider) + 0.5) | 0, 0, 255),\n        clamp((toColorComponent(rgb[3], rgbDivider) + 0.5) | 0, 0, 255),\n        alpha !== undefined ? clamp(toColorComponent(alpha, 100), 0, 1) : 1,\n      ];\n    }\n    throwInvalidColor(color);\n  }\n  // Fast lane for hex colors (also with alpha)\n  if (color.startsWith('#')) {\n    if (hexRegEx.test(color)) {\n      const hex = color.substring(1);\n      const step = hex.length <= 4 ? 1 : 2;\n      const colorFromHex = [0, 0, 0, 255];\n      for (let i = 0, ii = hex.length; i < ii; i += step) {\n        let colorComponent = parseInt(hex.substring(i, i + step), 16);\n        if (step === 1) {\n          colorComponent += colorComponent << 4;\n        }\n        colorFromHex[i / step] = colorComponent;\n      }\n      colorFromHex[3] = colorFromHex[3] / 255;\n      return colorFromHex;\n    }\n    throwInvalidColor(color);\n  }\n  // Use canvas color serialization to parse the color into hex or rgba\n  // See https://www.w3.org/TR/2021/SPSD-2dcontext-20210128/#serialization-of-a-color\n  const context = getColorParseContext();\n  context.fillStyle = '#abcdef';\n  let invalidCheckFillStyle = context.fillStyle;\n  context.fillStyle = color;\n  if (context.fillStyle === invalidCheckFillStyle) {\n    context.fillStyle = '#fedcba';\n    invalidCheckFillStyle = context.fillStyle;\n    context.fillStyle = color;\n    if (context.fillStyle === invalidCheckFillStyle) {\n      throwInvalidColor(color);\n    }\n  }\n  const colorString = context.fillStyle;\n  if (colorString.startsWith('#') || colorString.startsWith('rgba')) {\n    return parseRgba(colorString);\n  }\n  context.clearRect(0, 0, 1, 1);\n  context.fillRect(0, 0, 1, 1);\n  const colorFromImage = Array.from(context.getImageData(0, 0, 1, 1).data);\n  colorFromImage[3] = toFixed(colorFromImage[3] / 255, 3);\n  return colorFromImage;\n}\n\n/**\n * Return the color as an rgba string.\n * @param {Color|string} color Color.\n * @return {string} Rgba string.\n * @api\n */\nexport function asString(color) {\n  if (typeof color === 'string') {\n    return color;\n  }\n  return toString(color);\n}\n\n/**\n * @type {number}\n */\nconst MAX_CACHE_SIZE = 1024;\n\n/**\n * We maintain a small cache of parsed strings.  Whenever the cache grows too large,\n * we delete an arbitrary set of the entries.\n *\n * @type {Object<string, Color>}\n */\nconst cache = {};\n\n/**\n * @type {number}\n */\nlet cacheSize = 0;\n\n/**\n * @param {Color} color A color that may or may not have an alpha channel.\n * @return {Color} The input color with an alpha channel.  If the input color has\n * an alpha channel, the input color will be returned unchanged.  Otherwise, a new\n * array will be returned with the input color and an alpha channel of 1.\n */\nexport function withAlpha(color) {\n  if (color.length === 4) {\n    return color;\n  }\n  const output = color.slice();\n  output[3] = 1;\n  return output;\n}\n\n// The functions b1, b2, a1, a2, rgbaToLcha and lchaToRgba below are adapted from\n// https://stackoverflow.com/a/67219995/2389327\n\n/**\n * @param {number} v Input value.\n * @return {number} Output value.\n */\nfunction b1(v) {\n  return v > 0.0031308 ? Math.pow(v, 1 / 2.4) * 269.025 - 14.025 : v * 3294.6;\n}\n\n/**\n * @param {number} v Input value.\n * @return {number} Output value.\n */\nfunction b2(v) {\n  return v > 0.2068965 ? Math.pow(v, 3) : (v - 4 / 29) * (108 / 841);\n}\n\n/**\n * @param {number} v Input value.\n * @return {number} Output value.\n */\nfunction a1(v) {\n  return v > 10.314724 ? Math.pow((v + 14.025) / 269.025, 2.4) : v / 3294.6;\n}\n\n/**\n * @param {number} v Input value.\n * @return {number} Output value.\n */\nfunction a2(v) {\n  return v > 0.0088564 ? Math.pow(v, 1 / 3) : v / (108 / 841) + 4 / 29;\n}\n\n/**\n * @param {Color} color RGBA color.\n * @return {Color} LCHuv color with alpha.\n */\nexport function rgbaToLcha(color) {\n  const r = a1(color[0]);\n  const g = a1(color[1]);\n  const b = a1(color[2]);\n  const y = a2(r * 0.222488403 + g * 0.716873169 + b * 0.06060791);\n  const l = 500 * (a2(r * 0.452247074 + g * 0.399439023 + b * 0.148375274) - y);\n  const q = 200 * (y - a2(r * 0.016863605 + g * 0.117638439 + b * 0.865350722));\n  const h = Math.atan2(q, l) * (180 / Math.PI);\n  return [\n    116 * y - 16,\n    Math.sqrt(l * l + q * q),\n    h < 0 ? h + 360 : h,\n    color[3],\n  ];\n}\n\n/**\n * @param {Color} color LCHuv color with alpha.\n * @return {Color} RGBA color.\n */\nexport function lchaToRgba(color) {\n  const l = (color[0] + 16) / 116;\n  const c = color[1];\n  const h = (color[2] * Math.PI) / 180;\n  const y = b2(l);\n  const x = b2(l + (c / 500) * Math.cos(h));\n  const z = b2(l - (c / 200) * Math.sin(h));\n  const r = b1(x * 3.021973625 - y * 1.617392459 - z * 0.404875592);\n  const g = b1(x * -0.943766287 + y * 1.916279586 + z * 0.027607165);\n  const b = b1(x * 0.069407491 - y * 0.22898585 + z * 1.159737864);\n  return [\n    clamp((r + 0.5) | 0, 0, 255),\n    clamp((g + 0.5) | 0, 0, 255),\n    clamp((b + 0.5) | 0, 0, 255),\n    color[3],\n  ];\n}\n\n/**\n * @param {string} s String.\n * @return {Color} Color.\n */\nexport function fromString(s) {\n  if (s === 'none') {\n    return NO_COLOR;\n  }\n  if (cache.hasOwnProperty(s)) {\n    return cache[s];\n  }\n  if (cacheSize >= MAX_CACHE_SIZE) {\n    let i = 0;\n    for (const key in cache) {\n      if ((i++ & 3) === 0) {\n        delete cache[key];\n        --cacheSize;\n      }\n    }\n  }\n\n  const color = parseRgba(s);\n  if (color.length !== 4) {\n    throwInvalidColor(s);\n  }\n  for (const c of color) {\n    if (isNaN(c)) {\n      throwInvalidColor(s);\n    }\n  }\n  cache[s] = color;\n  ++cacheSize;\n  return color;\n}\n\n/**\n * Return the color as an array. This function maintains a cache of calculated\n * arrays which means the result should not be modified.\n * @param {Color|string} color Color.\n * @return {Color} Color.\n * @api\n */\nexport function asArray(color) {\n  if (Array.isArray(color)) {\n    return color;\n  }\n  return fromString(color);\n}\n\n/**\n * @param {Color} color Color.\n * @return {string} String.\n */\nexport function toString(color) {\n  let r = color[0];\n  if (r != (r | 0)) {\n    r = (r + 0.5) | 0;\n  }\n  let g = color[1];\n  if (g != (g | 0)) {\n    g = (g + 0.5) | 0;\n  }\n  let b = color[2];\n  if (b != (b | 0)) {\n    b = (b + 0.5) | 0;\n  }\n  const a = color[3] === undefined ? 1 : Math.round(color[3] * 1000) / 1000;\n  return 'rgba(' + r + ',' + g + ',' + b + ',' + a + ')';\n}\n\n/**\n * @param {string} s String.\n * @return {boolean} Whether the string is actually a valid color\n */\nexport function isStringColor(s) {\n  try {\n    fromString(s);\n    return true;\n  } catch {\n    return false;\n  }\n}\n", "/**\n * @module ol/size\n */\n\n/**\n * An array of numbers representing a size: `[width, height]`.\n * @typedef {Array<number>} Size\n * @api\n */\n\n/**\n * Returns a buffered size.\n * @param {Size} size Size.\n * @param {number} num The amount by which to buffer.\n * @param {Size} [dest] Optional reusable size array.\n * @return {Size} The buffered size.\n */\nexport function buffer(size, num, dest) {\n  if (dest === undefined) {\n    dest = [0, 0];\n  }\n  dest[0] = size[0] + 2 * num;\n  dest[1] = size[1] + 2 * num;\n  return dest;\n}\n\n/**\n * Determines if a size has a positive area.\n * @param {Size} size The size to test.\n * @return {boolean} The size has a positive area.\n */\nexport function hasArea(size) {\n  return size[0] > 0 && size[1] > 0;\n}\n\n/**\n * Returns a size scaled by a ratio. The result will be an array of integers.\n * @param {Size} size Size.\n * @param {number} ratio Ratio.\n * @param {Size} [dest] Optional reusable size array.\n * @return {Size} The scaled size.\n */\nexport function scale(size, ratio, dest) {\n  if (dest === undefined) {\n    dest = [0, 0];\n  }\n  dest[0] = (size[0] * ratio + 0.5) | 0;\n  dest[1] = (size[1] * ratio + 0.5) | 0;\n  return dest;\n}\n\n/**\n * Returns an `Size` array for the passed in number (meaning: square) or\n * `Size` array.\n * (meaning: non-square),\n * @param {number|Size} size Width and height.\n * @param {Size} [dest] Optional reusable size array.\n * @return {Size} Size.\n * @api\n */\nexport function toSize(size, dest) {\n  if (Array.isArray(size)) {\n    return size;\n  }\n  if (dest === undefined) {\n    dest = [size, size];\n  } else {\n    dest[0] = size;\n    dest[1] = size;\n  }\n  return dest;\n}\n", "/**\n * @module ol/expr/expression\n */\nimport {ascending} from '../array.js';\nimport {fromString as colorFromString} from '../color.js';\nimport {toSize} from '../size.js';\n\n/**\n * @fileoverview This module includes types and functions for parsing array encoded expressions.\n * The result of parsing an encoded expression is one of the specific expression classes.\n * During parsing, information is added to the parsing context about the data accessed by the\n * expression.\n */\n\n/**\n * Base type used for literal style parameters; can be a number literal or the output of an operator,\n * which in turns takes {@link import(\"./expression.js\").ExpressionValue} arguments.\n *\n * See below for details on the available operators (with notes for those that are WebGL or Canvas only).\n *\n * Reading operators:\n *   * `['band', bandIndex, xOffset, yOffset]` For tile layers only. Fetches pixel values from band\n *     `bandIndex` of the source's data. The first `bandIndex` of the source data is `1`. Fetched values\n *     are in the 0..1 range. {@link import(\"../source/TileImage.js\").default} sources have 4 bands: red,\n *     green, blue and alpha. {@link import(\"../source/DataTile.js\").default} sources can have any number\n *     of bands, depending on the underlying data source and\n *     {@link import(\"../source/GeoTIFF.js\").Options configuration}. `xOffset` and `yOffset` are optional\n *     and allow specifying pixel offsets for x and y. This is used for sampling data from neighboring pixels (WebGL only).\n *   * `['get', attributeName]` fetches a feature property value, similar to `feature.get('attributeName')`.\n *   * `['get', attributeName, keyOrArrayIndex, ...]` (Canvas only) Access nested properties and array items of a\n *     feature property. The result is `undefined` when there is nothing at the specified key or index.\n *   * `['geometry-type']` returns a feature's geometry type as string, either: 'LineString', 'Point' or 'Polygon'\n *     `Multi*` values are returned as their singular equivalent\n *     `Circle` geometries are returned as 'Polygon'\n *     `GeometryCollection` geometries are returned as the type of the first geometry found in the collection (WebGL only).\n *   * `['resolution']` returns the current resolution\n *   * `['time']` The time in seconds since the creation of the layer (WebGL only).\n *   * `['var', 'varName']` fetches a value from the style variables; will throw an error if that variable is undefined\n *   * `['zoom']` The current zoom level (WebGL only).\n *   * `['line-metric']` returns the M component of the current point on a line (WebGL only); in case where the geometry layout of the line\n *      does not contain an M component (e.g. XY or XYZ), 0 is returned; 0 is also returned for geometries other than lines.\n *      Please note that the M component will be linearly interpolated between the two points composing a segment.\n *\n * Math operators:\n *   * `['*', value1, value2, ...]` multiplies the values (either numbers or colors)\n *   * `['/', value1, value2]` divides `value1` by `value2`\n *   * `['+', value1, value2, ...]` adds the values\n *   * `['-', value1, value2]` subtracts `value2` from `value1`\n *   * `['clamp', value, low, high]` clamps `value` between `low` and `high`\n *   * `['%', value1, value2]` returns the result of `value1 % value2` (modulo)\n *   * `['^', value1, value2]` returns the value of `value1` raised to the `value2` power\n *   * `['abs', value1]` returns the absolute value of `value1`\n *   * `['floor', value1]` returns the nearest integer less than or equal to `value1`\n *   * `['round', value1]` returns the nearest integer to `value1`\n *   * `['ceil', value1]` returns the nearest integer greater than or equal to `value1`\n *   * `['sin', value1]` returns the sine of `value1`\n *   * `['cos', value1]` returns the cosine of `value1`\n *   * `['atan', value1, value2]` returns `atan2(value1, value2)`. If `value2` is not provided, returns `atan(value1)`\n *   * `['sqrt', value1]` returns the square root of `value1`\n *\n * * Transform operators:\n *   * `['case', condition1, output1, ...conditionN, outputN, fallback]` selects the first output whose corresponding\n *     condition evaluates to `true`. If no match is found, returns the `fallback` value.\n *     All conditions should be `boolean`, output and fallback can be any kind.\n *   * `['match', input, match1, output1, ...matchN, outputN, fallback]` compares the `input` value against all\n *     provided `matchX` values, returning the output associated with the first valid match. If no match is found,\n *     returns the `fallback` value.\n *     `input` and `matchX` values must all be of the same type, and can be `number` or `string`. `outputX` and\n *     `fallback` values must be of the same type, and can be of any kind.\n *   * `['interpolate', interpolation, input, stop1, output1, ...stopN, outputN]` returns a value by interpolating between\n *     pairs of inputs and outputs; `interpolation` can either be `['linear']` or `['exponential', base]` where `base` is\n *     the rate of increase from stop A to stop B (i.e. power to which the interpolation ratio is raised); a value\n *     of 1 is equivalent to `['linear']`.\n *     `input` and `stopX` values must all be of type `number`. `outputX` values can be `number` or `color` values.\n *     Note: `input` will be clamped between `stop1` and `stopN`, meaning that all output values will be comprised\n *     between `output1` and `outputN`.\n *   * `['string', value1, value2, ...]` returns the first value in the list that evaluates to a string.\n *     An example would be to provide a default value for get: `['string', ['get', 'propertyname'], 'default value']]`\n *     (Canvas only).\n *   * `['number', value1, value2, ...]` returns the first value in the list that evaluates to a number.\n *     An example would be to provide a default value for get: `['string', ['get', 'propertyname'], 42]]`\n *     (Canvas only).\n *   * `['coalesce', value1, value2, ...]` returns the first value in the list which is not null or undefined.\n *     An example would be to provide a default value for get: `['coalesce', ['get','propertyname'], 'default value']]`\n *     (Canvas only).\n *\n * * Logical operators:\n *   * `['<', value1, value2]` returns `true` if `value1` is strictly lower than `value2`, or `false` otherwise.\n *   * `['<=', value1, value2]` returns `true` if `value1` is lower than or equals `value2`, or `false` otherwise.\n *   * `['>', value1, value2]` returns `true` if `value1` is strictly greater than `value2`, or `false` otherwise.\n *   * `['>=', value1, value2]` returns `true` if `value1` is greater than or equals `value2`, or `false` otherwise.\n *   * `['==', value1, value2]` returns `true` if `value1` equals `value2`, or `false` otherwise.\n *   * `['!=', value1, value2]` returns `true` if `value1` does not equal `value2`, or `false` otherwise.\n *   * `['!', value1]` returns `false` if `value1` is `true` or greater than `0`, or `true` otherwise.\n *   * `['all', value1, value2, ...]` returns `true` if all the inputs are `true`, `false` otherwise.\n *   * `['any', value1, value2, ...]` returns `true` if any of the inputs are `true`, `false` otherwise.\n *   * `['has', attributeName, keyOrArrayIndex, ...]` returns `true` if feature properties include the (nested) key `attributeName`,\n *     `false` otherwise.\n *     Note that for WebGL layers, the hardcoded value `-9999999` is used to distinguish when a property is not defined.\n *   * `['between', value1, value2, value3]` returns `true` if `value1` is contained between `value2` and `value3`\n *     (inclusively), or `false` otherwise.\n *   * `['in', needle, haystack]` returns `true` if `needle` is found in `haystack`, and\n *     `false` otherwise.\n *     This operator has the following limitations:\n *     * `haystack` has to be an array of numbers or strings (searching for a substring in a string is not supported yet)\n *     * Only literal arrays are supported as `haystack` for now; this means that `haystack` cannot be the result of an\n *     expression. If `haystack` is an array of strings, use the `literal` operator to disambiguate from an expression:\n *     `['literal', ['abc', 'def', 'ghi']]`\n *     This works as well for number arrays although it is not required. Mixing types (numbers and strings) will produce undefined results.\n *\n * * Conversion operators:\n *   * `['array', value1, ...valueN]` creates a numerical array from `number` values; please note that the amount of\n *     values can currently only be 2, 3 or 4 (WebGL only).\n *   * `['color', red, green, blue, alpha]` or `['color', shade, alpha]` creates a `color` value from `number` values;\n *     the `alpha` parameter is optional; if not specified, it will be set to 1 (WebGL only).\n *     Note: `red`, `green` and `blue` or `shade` components must be values between 0 and 255; `alpha` between 0 and 1.\n *   * `['palette', index, colors]` picks a `color` value from an array of colors using the given index; the `index`\n *     expression must evaluate to a number; the items in the `colors` array must be strings with hex colors\n *     (e.g. `'#86A136'`), colors using the rgba[a] functional notation (e.g. `'rgb(134, 161, 54)'` or `'rgba(134, 161, 54, 1)'`),\n *     named colors (e.g. `'red'`), or array literals with 3 ([r, g, b]) or 4 ([r, g, b, a]) values (with r, g, and b\n *     in the 0-255 range and a in the 0-1 range) (WebGL only).\n *   * `['to-string', value]` converts the input value to a string. If the input is a boolean, the result is \"true\" or \"false\".\n *     If the input is a number, it is converted to a string as specified by the \"NumberToString\" algorithm of the ECMAScript\n *     Language Specification. If the input is a color, it is converted to a string of the form \"rgba(r,g,b,a)\". (Canvas only)\n *\n * Values can either be literals or another operator, as they will be evaluated recursively.\n * Literal values can be of the following types:\n * * `boolean`\n * * `number`\n * * `number[]` (number arrays can only have a length of 2, 3 or 4)\n * * `string`\n * * {@link module:ol/color~Color}\n *\n * @typedef {Array<*>|import(\"../color.js\").Color|string|number|boolean} ExpressionValue\n * @api\n */\n\nlet numTypes = 0;\nexport const NoneType = 0;\nexport const BooleanType = 1 << numTypes++;\nexport const NumberType = 1 << numTypes++;\nexport const StringType = 1 << numTypes++;\nexport const ColorType = 1 << numTypes++;\nexport const NumberArrayType = 1 << numTypes++;\nexport const SizeType = 1 << numTypes++;\nexport const AnyType = Math.pow(2, numTypes) - 1;\n\nconst typeNames = {\n  [BooleanType]: 'boolean',\n  [NumberType]: 'number',\n  [StringType]: 'string',\n  [ColorType]: 'color',\n  [NumberArrayType]: 'number[]',\n  [SizeType]: 'size',\n};\n\nconst namedTypes = Object.keys(typeNames).map(Number).sort(ascending);\n\n/**\n * @param {number} type The type.\n * @return {boolean} The type is one of the specific types (not any or a union type).\n */\nfunction isSpecific(type) {\n  return type in typeNames;\n}\n\n/**\n * Get a string representation for a type.\n * @param {number} type The type.\n * @return {string} The type name.\n */\nexport function typeName(type) {\n  const names = [];\n  for (const namedType of namedTypes) {\n    if (includesType(type, namedType)) {\n      names.push(typeNames[namedType]);\n    }\n  }\n  if (names.length === 0) {\n    return 'untyped';\n  }\n  if (names.length < 3) {\n    return names.join(' or ');\n  }\n  return names.slice(0, -1).join(', ') + ', or ' + names[names.length - 1];\n}\n\n/**\n * @param {number} broad The broad type.\n * @param {number} specific The specific type.\n * @return {boolean} The broad type includes the specific type.\n */\nexport function includesType(broad, specific) {\n  return (broad & specific) === specific;\n}\n\n/**\n * @param {number} oneType One type.\n * @param {number} otherType Another type.\n * @return {boolean} The set of types overlap (share a common specific type)\n */\nexport function overlapsType(oneType, otherType) {\n  return !!(oneType & otherType);\n}\n\n/**\n * @param {number} type The type.\n * @param {number} expected The expected type.\n * @return {boolean} The given type is exactly the expected type.\n */\nexport function isType(type, expected) {\n  return type === expected;\n}\n\n/**\n * @typedef {boolean|number|string|Array<number>} LiteralValue\n */\n\nexport class LiteralExpression {\n  /**\n   * @param {number} type The value type.\n   * @param {LiteralValue} value The literal value.\n   */\n  constructor(type, value) {\n    if (!isSpecific(type)) {\n      throw new Error(\n        `literal expressions must have a specific type, got ${typeName(type)}`,\n      );\n    }\n    this.type = type;\n    this.value = value;\n  }\n}\n\nexport class CallExpression {\n  /**\n   * @param {number} type The return type.\n   * @param {string} operator The operator.\n   * @param {...Expression} args The arguments.\n   */\n  constructor(type, operator, ...args) {\n    this.type = type;\n    this.operator = operator;\n    this.args = args;\n  }\n}\n\n/**\n * @typedef {LiteralExpression|CallExpression} Expression\n */\n\n/**\n * @typedef {Object} ParsingContext\n * @property {Set<string>} variables Variables referenced with the 'var' operator.\n * @property {Set<string>} properties Properties referenced with the 'get' operator.\n * @property {boolean} featureId The style uses the feature id.\n * @property {boolean} geometryType The style uses the feature geometry type.\n * @property {boolean} mCoordinate The style uses the M coordinate of geometries\n * @property {boolean} mapState The style uses the map state (view state or time elapsed).\n */\n\n/**\n * @return {ParsingContext} A new parsing context.\n */\nexport function newParsingContext() {\n  return {\n    variables: new Set(),\n    properties: new Set(),\n    featureId: false,\n    geometryType: false,\n    mCoordinate: false,\n    mapState: false,\n  };\n}\n\n/**\n * @typedef {LiteralValue|Array} EncodedExpression\n */\n\n/**\n * @param {EncodedExpression} encoded The encoded expression.\n * @param {number} expectedType The expected type.\n * @param {ParsingContext} context The parsing context.\n * @return {Expression} The parsed expression result.\n */\nexport function parse(encoded, expectedType, context) {\n  switch (typeof encoded) {\n    case 'boolean': {\n      if (isType(expectedType, StringType)) {\n        return new LiteralExpression(StringType, encoded ? 'true' : 'false');\n      }\n      if (!includesType(expectedType, BooleanType)) {\n        throw new Error(\n          `got a boolean, but expected ${typeName(expectedType)}`,\n        );\n      }\n      return new LiteralExpression(BooleanType, encoded);\n    }\n    case 'number': {\n      if (isType(expectedType, SizeType)) {\n        return new LiteralExpression(SizeType, toSize(encoded));\n      }\n      if (isType(expectedType, BooleanType)) {\n        return new LiteralExpression(BooleanType, !!encoded);\n      }\n      if (isType(expectedType, StringType)) {\n        return new LiteralExpression(StringType, encoded.toString());\n      }\n      if (!includesType(expectedType, NumberType)) {\n        throw new Error(`got a number, but expected ${typeName(expectedType)}`);\n      }\n      return new LiteralExpression(NumberType, encoded);\n    }\n    case 'string': {\n      if (isType(expectedType, ColorType)) {\n        return new LiteralExpression(ColorType, colorFromString(encoded));\n      }\n      if (isType(expectedType, BooleanType)) {\n        return new LiteralExpression(BooleanType, !!encoded);\n      }\n      if (!includesType(expectedType, StringType)) {\n        throw new Error(`got a string, but expected ${typeName(expectedType)}`);\n      }\n      return new LiteralExpression(StringType, encoded);\n    }\n    default: {\n      // pass\n    }\n  }\n\n  if (!Array.isArray(encoded)) {\n    throw new Error('expression must be an array or a primitive value');\n  }\n\n  if (encoded.length === 0) {\n    throw new Error('empty expression');\n  }\n\n  if (typeof encoded[0] === 'string') {\n    return parseCallExpression(encoded, expectedType, context);\n  }\n\n  for (const item of encoded) {\n    if (typeof item !== 'number') {\n      throw new Error('expected an array of numbers');\n    }\n  }\n\n  if (isType(expectedType, SizeType)) {\n    if (encoded.length !== 2) {\n      throw new Error(\n        `expected an array of two values for a size, got ${encoded.length}`,\n      );\n    }\n    return new LiteralExpression(SizeType, encoded);\n  }\n\n  if (isType(expectedType, ColorType)) {\n    if (encoded.length === 3) {\n      return new LiteralExpression(ColorType, [...encoded, 1]);\n    }\n    if (encoded.length === 4) {\n      return new LiteralExpression(ColorType, encoded);\n    }\n    throw new Error(\n      `expected an array of 3 or 4 values for a color, got ${encoded.length}`,\n    );\n  }\n\n  if (!includesType(expectedType, NumberArrayType)) {\n    throw new Error(\n      `got an array of numbers, but expected ${typeName(expectedType)}`,\n    );\n  }\n\n  return new LiteralExpression(NumberArrayType, encoded);\n}\n\n/**\n * @type {Object<string, string>}\n */\nexport const Ops = {\n  Get: 'get',\n  Var: 'var',\n  Concat: 'concat',\n  GeometryType: 'geometry-type',\n  LineMetric: 'line-metric',\n  Any: 'any',\n  All: 'all',\n  Not: '!',\n  Resolution: 'resolution',\n  Zoom: 'zoom',\n  Time: 'time',\n  Equal: '==',\n  NotEqual: '!=',\n  GreaterThan: '>',\n  GreaterThanOrEqualTo: '>=',\n  LessThan: '<',\n  LessThanOrEqualTo: '<=',\n  Multiply: '*',\n  Divide: '/',\n  Add: '+',\n  Subtract: '-',\n  Clamp: 'clamp',\n  Mod: '%',\n  Pow: '^',\n  Abs: 'abs',\n  Floor: 'floor',\n  Ceil: 'ceil',\n  Round: 'round',\n  Sin: 'sin',\n  Cos: 'cos',\n  Atan: 'atan',\n  Sqrt: 'sqrt',\n  Match: 'match',\n  Between: 'between',\n  Interpolate: 'interpolate',\n  Coalesce: 'coalesce',\n  Case: 'case',\n  In: 'in',\n  Number: 'number',\n  String: 'string',\n  Array: 'array',\n  Color: 'color',\n  Id: 'id',\n  Band: 'band',\n  Palette: 'palette',\n  ToString: 'to-string',\n  Has: 'has',\n};\n\n/**\n * @typedef {function(Array, number, ParsingContext):Expression} Parser\n *\n * Second argument is the expected type.\n */\n\n/**\n * @type {Object<string, Parser>}\n */\nconst parsers = {\n  [Ops.Get]: createCallExpressionParser(hasArgsCount(1, Infinity), withGetArgs),\n  [Ops.Var]: createCallExpressionParser(hasArgsCount(1, 1), withVarArgs),\n  [Ops.Has]: createCallExpressionParser(hasArgsCount(1, Infinity), withGetArgs),\n  [Ops.Id]: createCallExpressionParser(usesFeatureId, withNoArgs),\n  [Ops.Concat]: createCallExpressionParser(\n    hasArgsCount(2, Infinity),\n    withArgsOfType(StringType),\n  ),\n  [Ops.GeometryType]: createCallExpressionParser(usesGeometryType, withNoArgs),\n  [Ops.LineMetric]: createCallExpressionParser(usesMCoordinate, withNoArgs),\n  [Ops.Resolution]: createCallExpressionParser(usesMapState, withNoArgs),\n  [Ops.Zoom]: createCallExpressionParser(usesMapState, withNoArgs),\n  [Ops.Time]: createCallExpressionParser(usesMapState, withNoArgs),\n  [Ops.Any]: createCallExpressionParser(\n    hasArgsCount(2, Infinity),\n    withArgsOfType(BooleanType),\n  ),\n  [Ops.All]: createCallExpressionParser(\n    hasArgsCount(2, Infinity),\n    withArgsOfType(BooleanType),\n  ),\n  [Ops.Not]: createCallExpressionParser(\n    hasArgsCount(1, 1),\n    withArgsOfType(BooleanType),\n  ),\n  [Ops.Equal]: createCallExpressionParser(\n    hasArgsCount(2, 2),\n    withArgsOfType(AnyType),\n  ),\n  [Ops.NotEqual]: createCallExpressionParser(\n    hasArgsCount(2, 2),\n    withArgsOfType(AnyType),\n  ),\n  [Ops.GreaterThan]: createCallExpressionParser(\n    hasArgsCount(2, 2),\n    withArgsOfType(NumberType),\n  ),\n  [Ops.GreaterThanOrEqualTo]: createCallExpressionParser(\n    hasArgsCount(2, 2),\n    withArgsOfType(NumberType),\n  ),\n  [Ops.LessThan]: createCallExpressionParser(\n    hasArgsCount(2, 2),\n    withArgsOfType(NumberType),\n  ),\n  [Ops.LessThanOrEqualTo]: createCallExpressionParser(\n    hasArgsCount(2, 2),\n    withArgsOfType(NumberType),\n  ),\n  [Ops.Multiply]: createCallExpressionParser(\n    hasArgsCount(2, Infinity),\n    withArgsOfReturnType,\n  ),\n  [Ops.Coalesce]: createCallExpressionParser(\n    hasArgsCount(2, Infinity),\n    withArgsOfReturnType,\n  ),\n  [Ops.Divide]: createCallExpressionParser(\n    hasArgsCount(2, 2),\n    withArgsOfType(NumberType),\n  ),\n  [Ops.Add]: createCallExpressionParser(\n    hasArgsCount(2, Infinity),\n    withArgsOfType(NumberType),\n  ),\n  [Ops.Subtract]: createCallExpressionParser(\n    hasArgsCount(2, 2),\n    withArgsOfType(NumberType),\n  ),\n  [Ops.Clamp]: createCallExpressionParser(\n    hasArgsCount(3, 3),\n    withArgsOfType(NumberType),\n  ),\n  [Ops.Mod]: createCallExpressionParser(\n    hasArgsCount(2, 2),\n    withArgsOfType(NumberType),\n  ),\n  [Ops.Pow]: createCallExpressionParser(\n    hasArgsCount(2, 2),\n    withArgsOfType(NumberType),\n  ),\n  [Ops.Abs]: createCallExpressionParser(\n    hasArgsCount(1, 1),\n    withArgsOfType(NumberType),\n  ),\n  [Ops.Floor]: createCallExpressionParser(\n    hasArgsCount(1, 1),\n    withArgsOfType(NumberType),\n  ),\n  [Ops.Ceil]: createCallExpressionParser(\n    hasArgsCount(1, 1),\n    withArgsOfType(NumberType),\n  ),\n  [Ops.Round]: createCallExpressionParser(\n    hasArgsCount(1, 1),\n    withArgsOfType(NumberType),\n  ),\n  [Ops.Sin]: createCallExpressionParser(\n    hasArgsCount(1, 1),\n    withArgsOfType(NumberType),\n  ),\n  [Ops.Cos]: createCallExpressionParser(\n    hasArgsCount(1, 1),\n    withArgsOfType(NumberType),\n  ),\n  [Ops.Atan]: createCallExpressionParser(\n    hasArgsCount(1, 2),\n    withArgsOfType(NumberType),\n  ),\n  [Ops.Sqrt]: createCallExpressionParser(\n    hasArgsCount(1, 1),\n    withArgsOfType(NumberType),\n  ),\n  [Ops.Match]: createCallExpressionParser(\n    hasArgsCount(4, Infinity),\n    hasEvenArgs,\n    withMatchArgs,\n  ),\n  [Ops.Between]: createCallExpressionParser(\n    hasArgsCount(3, 3),\n    withArgsOfType(NumberType),\n  ),\n  [Ops.Interpolate]: createCallExpressionParser(\n    hasArgsCount(6, Infinity),\n    hasEvenArgs,\n    withInterpolateArgs,\n  ),\n  [Ops.Case]: createCallExpressionParser(\n    hasArgsCount(3, Infinity),\n    hasOddArgs,\n    withCaseArgs,\n  ),\n  [Ops.In]: createCallExpressionParser(hasArgsCount(2, 2), withInArgs),\n  [Ops.Number]: createCallExpressionParser(\n    hasArgsCount(1, Infinity),\n    withArgsOfType(AnyType),\n  ),\n  [Ops.String]: createCallExpressionParser(\n    hasArgsCount(1, Infinity),\n    withArgsOfType(AnyType),\n  ),\n  [Ops.Array]: createCallExpressionParser(\n    hasArgsCount(1, Infinity),\n    withArgsOfType(NumberType),\n  ),\n  [Ops.Color]: createCallExpressionParser(\n    hasArgsCount(1, 4),\n    withArgsOfType(NumberType),\n  ),\n  [Ops.Band]: createCallExpressionParser(\n    hasArgsCount(1, 3),\n    withArgsOfType(NumberType),\n  ),\n  [Ops.Palette]: createCallExpressionParser(\n    hasArgsCount(2, 2),\n    withPaletteArgs,\n  ),\n  [Ops.ToString]: createCallExpressionParser(\n    hasArgsCount(1, 1),\n    withArgsOfType(BooleanType | NumberType | StringType | ColorType),\n  ),\n};\n\n/**\n * @typedef {function(Array<EncodedExpression>, number, ParsingContext):Array<Expression>|void} ArgValidator\n *\n * An argument validator applies various checks to an encoded expression arguments and\n * returns the parsed arguments if any.  The second argument is the return type of the call expression.\n */\n\n/**\n * @type {ArgValidator}\n */\nfunction withGetArgs(encoded, returnType, context) {\n  const argsCount = encoded.length - 1;\n  const args = new Array(argsCount);\n  for (let i = 0; i < argsCount; ++i) {\n    const key = encoded[i + 1];\n    switch (typeof key) {\n      case 'number': {\n        args[i] = new LiteralExpression(NumberType, key);\n        break;\n      }\n      case 'string': {\n        args[i] = new LiteralExpression(StringType, key);\n        break;\n      }\n      default: {\n        throw new Error(\n          `expected a string key or numeric array index for a get operation, got ${key}`,\n        );\n      }\n    }\n    if (i === 0) {\n      context.properties.add(String(key));\n    }\n  }\n  return args;\n}\n\n/**\n * @type {ArgValidator}\n */\nfunction withVarArgs(encoded, returnType, context) {\n  const name = encoded[1];\n  if (typeof name !== 'string') {\n    throw new Error('expected a string argument for var operation');\n  }\n  context.variables.add(name);\n\n  return [new LiteralExpression(StringType, name)];\n}\n\n/**\n * @type {ArgValidator}\n */\nfunction usesFeatureId(encoded, returnType, context) {\n  context.featureId = true;\n}\n\n/**\n * @type {ArgValidator}\n */\nfunction usesGeometryType(encoded, returnType, context) {\n  context.geometryType = true;\n}\n\n/**\n * @type {ArgValidator}\n */\nfunction usesMCoordinate(encoded, returnType, context) {\n  context.mCoordinate = true;\n}\n\n/**\n * @type {ArgValidator}\n */\nfunction usesMapState(encoded, returnType, context) {\n  context.mapState = true;\n}\n\n/**\n * @type {ArgValidator}\n */\nfunction withNoArgs(encoded, returnType, context) {\n  const operation = encoded[0];\n  if (encoded.length !== 1) {\n    throw new Error(`expected no arguments for ${operation} operation`);\n  }\n  return [];\n}\n\n/**\n * @param {number} minArgs The minimum number of arguments.\n * @param {number} maxArgs The maximum number of arguments.\n * @return {ArgValidator} The argument validator\n */\nfunction hasArgsCount(minArgs, maxArgs) {\n  return function (encoded, returnType, context) {\n    const operation = encoded[0];\n    const argCount = encoded.length - 1;\n    if (minArgs === maxArgs) {\n      if (argCount !== minArgs) {\n        const plural = minArgs === 1 ? '' : 's';\n        throw new Error(\n          `expected ${minArgs} argument${plural} for ${operation}, got ${argCount}`,\n        );\n      }\n    } else if (argCount < minArgs || argCount > maxArgs) {\n      const range =\n        maxArgs === Infinity\n          ? `${minArgs} or more`\n          : `${minArgs} to ${maxArgs}`;\n      throw new Error(\n        `expected ${range} arguments for ${operation}, got ${argCount}`,\n      );\n    }\n  };\n}\n\n/**\n * @type {ArgValidator}\n */\nfunction withArgsOfReturnType(encoded, returnType, context) {\n  const argCount = encoded.length - 1;\n  /**\n   * @type {Array<Expression>}\n   */\n  const args = new Array(argCount);\n  for (let i = 0; i < argCount; ++i) {\n    const expression = parse(encoded[i + 1], returnType, context);\n    args[i] = expression;\n  }\n  return args;\n}\n\n/**\n * @param {number} argType The argument type.\n * @return {ArgValidator} The argument validator\n */\nfunction withArgsOfType(argType) {\n  return function (encoded, returnType, context) {\n    const argCount = encoded.length - 1;\n    /**\n     * @type {Array<Expression>}\n     */\n    const args = new Array(argCount);\n    for (let i = 0; i < argCount; ++i) {\n      const expression = parse(encoded[i + 1], argType, context);\n      args[i] = expression;\n    }\n    return args;\n  };\n}\n\n/**\n * @type {ArgValidator}\n */\nfunction hasOddArgs(encoded, returnType, context) {\n  const operation = encoded[0];\n  const argCount = encoded.length - 1;\n  if (argCount % 2 === 0) {\n    throw new Error(\n      `expected an odd number of arguments for ${operation}, got ${argCount} instead`,\n    );\n  }\n}\n\n/**\n * @type {ArgValidator}\n */\nfunction hasEvenArgs(encoded, returnType, context) {\n  const operation = encoded[0];\n  const argCount = encoded.length - 1;\n  if (argCount % 2 === 1) {\n    throw new Error(\n      `expected an even number of arguments for operation ${operation}, got ${argCount} instead`,\n    );\n  }\n}\n\n/**\n * @type {ArgValidator}\n */\nfunction withMatchArgs(encoded, returnType, context) {\n  const argsCount = encoded.length - 1;\n\n  const inputType = StringType | NumberType | BooleanType;\n\n  const input = parse(encoded[1], inputType, context);\n\n  const fallback = parse(encoded[encoded.length - 1], returnType, context);\n\n  const args = new Array(argsCount - 2);\n  for (let i = 0; i < argsCount - 2; i += 2) {\n    try {\n      const match = parse(encoded[i + 2], input.type, context);\n      args[i] = match;\n    } catch (err) {\n      throw new Error(\n        `failed to parse argument ${i + 1} of match expression: ${err.message}`,\n      );\n    }\n    try {\n      const output = parse(encoded[i + 3], fallback.type, context);\n      args[i + 1] = output;\n    } catch (err) {\n      throw new Error(\n        `failed to parse argument ${i + 2} of match expression: ${err.message}`,\n      );\n    }\n  }\n\n  return [input, ...args, fallback];\n}\n\n/**\n * @type {ArgValidator}\n */\nfunction withInterpolateArgs(encoded, returnType, context) {\n  const interpolationType = encoded[1];\n  /**\n   * @type {number}\n   */\n  let base;\n  switch (interpolationType[0]) {\n    case 'linear':\n      base = 1;\n      break;\n    case 'exponential':\n      const b = interpolationType[1];\n      if (typeof b !== 'number' || b <= 0) {\n        throw new Error(\n          `expected a number base for exponential interpolation` +\n            `, got ${JSON.stringify(b)} instead`,\n        );\n      }\n      base = b;\n      break;\n    default:\n      throw new Error(\n        `invalid interpolation type: ${JSON.stringify(interpolationType)}`,\n      );\n  }\n\n  const interpolation = new LiteralExpression(NumberType, base);\n\n  let input;\n  try {\n    input = parse(encoded[2], NumberType, context);\n  } catch (err) {\n    throw new Error(\n      `failed to parse argument 1 in interpolate expression: ${err.message}`,\n    );\n  }\n\n  const args = new Array(encoded.length - 3);\n  for (let i = 0; i < args.length; i += 2) {\n    try {\n      const stop = parse(encoded[i + 3], NumberType, context);\n      args[i] = stop;\n    } catch (err) {\n      throw new Error(\n        `failed to parse argument ${i + 2} for interpolate expression: ${err.message}`,\n      );\n    }\n    try {\n      const output = parse(encoded[i + 4], returnType, context);\n      args[i + 1] = output;\n    } catch (err) {\n      throw new Error(\n        `failed to parse argument ${i + 3} for interpolate expression: ${err.message}`,\n      );\n    }\n  }\n\n  return [interpolation, input, ...args];\n}\n\n/**\n * @type {ArgValidator}\n */\nfunction withCaseArgs(encoded, returnType, context) {\n  const fallback = parse(encoded[encoded.length - 1], returnType, context);\n\n  const args = new Array(encoded.length - 1);\n  for (let i = 0; i < args.length - 1; i += 2) {\n    try {\n      const condition = parse(encoded[i + 1], BooleanType, context);\n      args[i] = condition;\n    } catch (err) {\n      throw new Error(\n        `failed to parse argument ${i} of case expression: ${err.message}`,\n      );\n    }\n    try {\n      const output = parse(encoded[i + 2], fallback.type, context);\n      args[i + 1] = output;\n    } catch (err) {\n      throw new Error(\n        `failed to parse argument ${i + 1} of case expression: ${err.message}`,\n      );\n    }\n  }\n\n  args[args.length - 1] = fallback;\n  return args;\n}\n\n/**\n * @type {ArgValidator}\n */\nfunction withInArgs(encoded, returnType, context) {\n  let haystack = encoded[2];\n  if (!Array.isArray(haystack)) {\n    throw new Error(\n      `the second argument for the \"in\" operator must be an array`,\n    );\n  }\n  /**\n   * @type {number}\n   */\n  let needleType;\n\n  // check if we're using the 'literal' operator for the haystack\n  if (haystack[0] === 'literal') {\n    haystack = haystack[1];\n    if (!Array.isArray(haystack)) {\n      throw new Error(\n        `failed to parse \"in\" expression: the literal operator must be followed by an array`,\n      );\n    }\n  } else if (typeof haystack[0] === 'string') {\n    throw new Error(\n      `for the \"in\" operator, a string array should be wrapped in a \"literal\" operator to disambiguate from expressions`,\n    );\n  }\n\n  if (typeof haystack[0] === 'string') {\n    needleType = StringType;\n  } else {\n    needleType = NumberType;\n  }\n\n  const args = new Array(haystack.length);\n  for (let i = 0; i < args.length; i++) {\n    try {\n      const arg = parse(haystack[i], needleType, context);\n      args[i] = arg;\n    } catch (err) {\n      throw new Error(\n        `failed to parse haystack item ${i} for \"in\" expression: ${err.message}`,\n      );\n    }\n  }\n\n  const needle = parse(encoded[1], needleType, context);\n  return [needle, ...args];\n}\n\n/**\n * @type {ArgValidator}\n */\nfunction withPaletteArgs(encoded, returnType, context) {\n  let index;\n  try {\n    index = parse(encoded[1], NumberType, context);\n  } catch (err) {\n    throw new Error(\n      `failed to parse first argument in palette expression: ${err.message}`,\n    );\n  }\n  const colors = encoded[2];\n  if (!Array.isArray(colors)) {\n    throw new Error('the second argument of palette must be an array');\n  }\n  const parsedColors = new Array(colors.length);\n  for (let i = 0; i < parsedColors.length; i++) {\n    let color;\n    try {\n      color = parse(colors[i], ColorType, context);\n    } catch (err) {\n      throw new Error(\n        `failed to parse color at index ${i} in palette expression: ${err.message}`,\n      );\n    }\n    if (!(color instanceof LiteralExpression)) {\n      throw new Error(\n        `the palette color at index ${i} must be a literal value`,\n      );\n    }\n    parsedColors[i] = color;\n  }\n  return [index, ...parsedColors];\n}\n\n/**\n * @param {Array<ArgValidator>} validators A chain of argument validators.  The last validator is expected\n * to return the parsed arguments.\n * @return {Parser} The parser.\n */\nfunction createCallExpressionParser(...validators) {\n  return function (encoded, returnType, context) {\n    const operator = encoded[0];\n\n    /**\n     * @type {Array<Expression>}\n     */\n    let args;\n    for (let i = 0; i < validators.length; i++) {\n      const parsed = validators[i](encoded, returnType, context);\n      if (i == validators.length - 1) {\n        if (!parsed) {\n          throw new Error(\n            'expected last argument validator to return the parsed args',\n          );\n        }\n        args = parsed;\n      }\n    }\n    return new CallExpression(returnType, operator, ...args);\n  };\n}\n\n/**\n * @param {Array} encoded The encoded expression.\n * @param {number} returnType The expected return type of the call expression.\n * @param {ParsingContext} context The parsing context.\n * @return {Expression} The parsed expression.\n */\nfunction parseCallExpression(encoded, returnType, context) {\n  const operator = encoded[0];\n\n  const parser = parsers[operator];\n  if (!parser) {\n    throw new Error(`unknown operator: ${operator}`);\n  }\n  return parser(encoded, returnType, context);\n}\n\n/**\n * Returns a simplified geometry type suited for the `geometry-type` operator\n * @param {import('../geom/Geometry.js').default|import('../render/Feature.js').default} geometry Geometry object\n * @return {'Point'|'LineString'|'Polygon'|''} Simplified geometry type; empty string of no geometry found\n */\nexport function computeGeometryType(geometry) {\n  if (!geometry) {\n    return '';\n  }\n  const type = geometry.getType();\n  switch (type) {\n    case 'Point':\n    case 'LineString':\n    case 'Polygon':\n      return type;\n    case 'MultiPoint':\n    case 'MultiLineString':\n    case 'MultiPolygon':\n      return /** @type {'Point'|'LineString'|'Polygon'} */ (type.substring(5));\n    case 'Circle':\n      return 'Polygon';\n    case 'GeometryCollection':\n      return computeGeometryType(\n        /** @type {import(\"../geom/GeometryCollection.js\").default} */ (\n          geometry\n        ).getGeometries()[0],\n      );\n    default:\n      return '';\n  }\n}\n", "/**\n * @module ol/expr/cpu\n */\n\nimport {\n  fromString,\n  lchaToRgba,\n  rgbaToLcha,\n  toString,\n  withAlpha,\n} from '../color.js';\nimport {ColorType, LiteralExpression, Ops, parse} from './expression.js';\n\n/**\n * @fileoverview This module includes functions to build expressions for evaluation on the CPU.\n * Building is composed of two steps: parsing and compiling.  The parsing step takes an encoded\n * expression and returns an instance of one of the expression classes.  The compiling step takes\n * the expression instance and returns a function that can be evaluated in to return a literal\n * value.  The evaluator function should do as little allocation and work as possible.\n */\n\n/**\n * @typedef {Object} EvaluationContext\n * @property {Object} properties The values for properties used in 'get' expressions.\n * @property {Object} variables The values for variables used in 'var' expressions.\n * @property {number} resolution The map resolution.\n * @property {string|number|null} featureId The feature id.\n * @property {string} geometryType Geometry type of the current object.\n */\n\n/**\n * @return {EvaluationContext} A new evaluation context.\n */\nexport function newEvaluationContext() {\n  return {\n    variables: {},\n    properties: {},\n    resolution: NaN,\n    featureId: null,\n    geometryType: '',\n  };\n}\n\n/**\n * @typedef {function(EvaluationContext):import(\"./expression.js\").LiteralValue} ExpressionEvaluator\n */\n\n/**\n * @typedef {function(EvaluationContext):boolean} BooleanEvaluator\n */\n\n/**\n * @typedef {function(EvaluationContext):number} NumberEvaluator\n */\n\n/**\n * @typedef {function(EvaluationContext):string} StringEvaluator\n */\n\n/**\n * @typedef {function(EvaluationContext):(Array<number>|string)} ColorLikeEvaluator\n */\n\n/**\n * @typedef {function(EvaluationContext):Array<number>} NumberArrayEvaluator\n */\n\n/**\n * @typedef {function(EvaluationContext):Array<number>} CoordinateEvaluator\n */\n\n/**\n * @typedef {function(EvaluationContext):(Array<number>)} SizeEvaluator\n */\n\n/**\n * @typedef {function(EvaluationContext):(Array<number>|number)} SizeLikeEvaluator\n */\n\n/**\n * @param {import('./expression.js').EncodedExpression} encoded The encoded expression.\n * @param {number} type The expected type.\n * @param {import('./expression.js').ParsingContext} context The parsing context.\n * @return {ExpressionEvaluator} The expression evaluator.\n */\nexport function buildExpression(encoded, type, context) {\n  const expression = parse(encoded, type, context);\n  return compileExpression(expression, context);\n}\n\n/**\n * @param {import(\"./expression.js\").Expression} expression The expression.\n * @param {import('./expression.js').ParsingContext} context The parsing context.\n * @return {ExpressionEvaluator} The evaluator function.\n */\nfunction compileExpression(expression, context) {\n  if (expression instanceof LiteralExpression) {\n    // convert colors to array if possible\n    if (expression.type === ColorType && typeof expression.value === 'string') {\n      const colorValue = fromString(expression.value);\n      return function () {\n        return colorValue;\n      };\n    }\n    return function () {\n      return expression.value;\n    };\n  }\n  const operator = expression.operator;\n  switch (operator) {\n    case Ops.Number:\n    case Ops.String:\n    case Ops.Coalesce: {\n      return compileAssertionExpression(expression, context);\n    }\n    case Ops.Get:\n    case Ops.Var:\n    case Ops.Has: {\n      return compileAccessorExpression(expression, context);\n    }\n    case Ops.Id: {\n      return (context) => context.featureId;\n    }\n    case Ops.GeometryType: {\n      return (context) => context.geometryType;\n    }\n    case Ops.Concat: {\n      const args = expression.args.map((e) => compileExpression(e, context));\n      return (context) =>\n        ''.concat(...args.map((arg) => arg(context).toString()));\n    }\n    case Ops.Resolution: {\n      return (context) => context.resolution;\n    }\n    case Ops.Any:\n    case Ops.All:\n    case Ops.Between:\n    case Ops.In:\n    case Ops.Not: {\n      return compileLogicalExpression(expression, context);\n    }\n    case Ops.Equal:\n    case Ops.NotEqual:\n    case Ops.LessThan:\n    case Ops.LessThanOrEqualTo:\n    case Ops.GreaterThan:\n    case Ops.GreaterThanOrEqualTo: {\n      return compileComparisonExpression(expression, context);\n    }\n    case Ops.Multiply:\n    case Ops.Divide:\n    case Ops.Add:\n    case Ops.Subtract:\n    case Ops.Clamp:\n    case Ops.Mod:\n    case Ops.Pow:\n    case Ops.Abs:\n    case Ops.Floor:\n    case Ops.Ceil:\n    case Ops.Round:\n    case Ops.Sin:\n    case Ops.Cos:\n    case Ops.Atan:\n    case Ops.Sqrt: {\n      return compileNumericExpression(expression, context);\n    }\n    case Ops.Case: {\n      return compileCaseExpression(expression, context);\n    }\n    case Ops.Match: {\n      return compileMatchExpression(expression, context);\n    }\n    case Ops.Interpolate: {\n      return compileInterpolateExpression(expression, context);\n    }\n    case Ops.ToString: {\n      return compileConvertExpression(expression, context);\n    }\n    default: {\n      throw new Error(`Unsupported operator ${operator}`);\n    }\n    // TODO: unimplemented\n    // Ops.Zoom\n    // Ops.Time\n    // Ops.Array\n    // Ops.Color\n    // Ops.Band\n    // Ops.Palette\n  }\n}\n\n/**\n * @param {import('./expression.js').CallExpression} expression The call expression.\n * @param {import('./expression.js').ParsingContext} context The parsing context.\n * @return {ExpressionEvaluator} The evaluator function.\n */\nfunction compileAssertionExpression(expression, context) {\n  const type = expression.operator;\n  const length = expression.args.length;\n\n  const args = new Array(length);\n  for (let i = 0; i < length; ++i) {\n    args[i] = compileExpression(expression.args[i], context);\n  }\n  switch (type) {\n    case Ops.Coalesce: {\n      return (context) => {\n        for (let i = 0; i < length; ++i) {\n          const value = args[i](context);\n          if (typeof value !== 'undefined' && value !== null) {\n            return value;\n          }\n        }\n        throw new Error('Expected one of the values to be non-null');\n      };\n    }\n    case Ops.Number:\n    case Ops.String: {\n      return (context) => {\n        for (let i = 0; i < length; ++i) {\n          const value = args[i](context);\n          if (typeof value === type) {\n            return value;\n          }\n        }\n        throw new Error(`Expected one of the values to be a ${type}`);\n      };\n    }\n    default: {\n      throw new Error(`Unsupported assertion operator ${type}`);\n    }\n  }\n}\n\n/**\n * @param {import('./expression.js').CallExpression} expression The call expression.\n * @param {import('./expression.js').ParsingContext} context The parsing context.\n * @return {ExpressionEvaluator} The evaluator function.\n */\nfunction compileAccessorExpression(expression, context) {\n  const nameExpression = /** @type {LiteralExpression} */ (expression.args[0]);\n  const name = /** @type {string} */ (nameExpression.value);\n  switch (expression.operator) {\n    case Ops.Get: {\n      return (context) => {\n        const args = expression.args;\n        let value = context.properties[name];\n        for (let i = 1, ii = args.length; i < ii; ++i) {\n          const keyExpression = /** @type {LiteralExpression} */ (args[i]);\n          const key = /** @type {string|number} */ (keyExpression.value);\n          value = value[key];\n        }\n        return value;\n      };\n    }\n    case Ops.Var: {\n      return (context) => context.variables[name];\n    }\n    case Ops.Has: {\n      return (context) => {\n        const args = expression.args;\n        if (!(name in context.properties)) {\n          return false;\n        }\n        let value = context.properties[name];\n        for (let i = 1, ii = args.length; i < ii; ++i) {\n          const keyExpression = /** @type {LiteralExpression} */ (args[i]);\n          const key = /** @type {string|number} */ (keyExpression.value);\n          if (!value || !Object.hasOwn(value, key)) {\n            return false;\n          }\n          value = value[key];\n        }\n        return true;\n      };\n    }\n    default: {\n      throw new Error(`Unsupported accessor operator ${expression.operator}`);\n    }\n  }\n}\n\n/**\n * @param {import('./expression.js').CallExpression} expression The call expression.\n * @param {import('./expression.js').ParsingContext} context The parsing context.\n * @return {BooleanEvaluator} The evaluator function.\n */\nfunction compileComparisonExpression(expression, context) {\n  const op = expression.operator;\n  const left = compileExpression(expression.args[0], context);\n  const right = compileExpression(expression.args[1], context);\n  switch (op) {\n    case Ops.Equal: {\n      return (context) => left(context) === right(context);\n    }\n    case Ops.NotEqual: {\n      return (context) => left(context) !== right(context);\n    }\n    case Ops.LessThan: {\n      return (context) => left(context) < right(context);\n    }\n    case Ops.LessThanOrEqualTo: {\n      return (context) => left(context) <= right(context);\n    }\n    case Ops.GreaterThan: {\n      return (context) => left(context) > right(context);\n    }\n    case Ops.GreaterThanOrEqualTo: {\n      return (context) => left(context) >= right(context);\n    }\n    default: {\n      throw new Error(`Unsupported comparison operator ${op}`);\n    }\n  }\n}\n\n/**\n * @param {import('./expression.js').CallExpression} expression The call expression.\n * @param {import('./expression.js').ParsingContext} context The parsing context.\n * @return {BooleanEvaluator} The evaluator function.\n */\nfunction compileLogicalExpression(expression, context) {\n  const op = expression.operator;\n  const length = expression.args.length;\n\n  const args = new Array(length);\n  for (let i = 0; i < length; ++i) {\n    args[i] = compileExpression(expression.args[i], context);\n  }\n  switch (op) {\n    case Ops.Any: {\n      return (context) => {\n        for (let i = 0; i < length; ++i) {\n          if (args[i](context)) {\n            return true;\n          }\n        }\n        return false;\n      };\n    }\n    case Ops.All: {\n      return (context) => {\n        for (let i = 0; i < length; ++i) {\n          if (!args[i](context)) {\n            return false;\n          }\n        }\n        return true;\n      };\n    }\n    case Ops.Between: {\n      return (context) => {\n        const value = args[0](context);\n        const min = args[1](context);\n        const max = args[2](context);\n        return value >= min && value <= max;\n      };\n    }\n    case Ops.In: {\n      return (context) => {\n        const value = args[0](context);\n        for (let i = 1; i < length; ++i) {\n          if (value === args[i](context)) {\n            return true;\n          }\n        }\n        return false;\n      };\n    }\n    case Ops.Not: {\n      return (context) => !args[0](context);\n    }\n    default: {\n      throw new Error(`Unsupported logical operator ${op}`);\n    }\n  }\n}\n\n/**\n * @param {import('./expression.js').CallExpression} expression The call expression.\n * @param {import('./expression.js').ParsingContext} context The parsing context.\n * @return {NumberEvaluator} The evaluator function.\n */\nfunction compileNumericExpression(expression, context) {\n  const op = expression.operator;\n  const length = expression.args.length;\n\n  const args = new Array(length);\n  for (let i = 0; i < length; ++i) {\n    args[i] = compileExpression(expression.args[i], context);\n  }\n  switch (op) {\n    case Ops.Multiply: {\n      return (context) => {\n        let value = 1;\n        for (let i = 0; i < length; ++i) {\n          value *= args[i](context);\n        }\n        return value;\n      };\n    }\n    case Ops.Divide: {\n      return (context) => args[0](context) / args[1](context);\n    }\n    case Ops.Add: {\n      return (context) => {\n        let value = 0;\n        for (let i = 0; i < length; ++i) {\n          value += args[i](context);\n        }\n        return value;\n      };\n    }\n    case Ops.Subtract: {\n      return (context) => args[0](context) - args[1](context);\n    }\n    case Ops.Clamp: {\n      return (context) => {\n        const value = args[0](context);\n        const min = args[1](context);\n        if (value < min) {\n          return min;\n        }\n        const max = args[2](context);\n        if (value > max) {\n          return max;\n        }\n        return value;\n      };\n    }\n    case Ops.Mod: {\n      return (context) => args[0](context) % args[1](context);\n    }\n    case Ops.Pow: {\n      return (context) => Math.pow(args[0](context), args[1](context));\n    }\n    case Ops.Abs: {\n      return (context) => Math.abs(args[0](context));\n    }\n    case Ops.Floor: {\n      return (context) => Math.floor(args[0](context));\n    }\n    case Ops.Ceil: {\n      return (context) => Math.ceil(args[0](context));\n    }\n    case Ops.Round: {\n      return (context) => Math.round(args[0](context));\n    }\n    case Ops.Sin: {\n      return (context) => Math.sin(args[0](context));\n    }\n    case Ops.Cos: {\n      return (context) => Math.cos(args[0](context));\n    }\n    case Ops.Atan: {\n      if (length === 2) {\n        return (context) => Math.atan2(args[0](context), args[1](context));\n      }\n      return (context) => Math.atan(args[0](context));\n    }\n    case Ops.Sqrt: {\n      return (context) => Math.sqrt(args[0](context));\n    }\n    default: {\n      throw new Error(`Unsupported numeric operator ${op}`);\n    }\n  }\n}\n\n/**\n * @param {import('./expression.js').CallExpression} expression The call expression.\n * @param {import('./expression.js').ParsingContext} context The parsing context.\n * @return {ExpressionEvaluator} The evaluator function.\n */\nfunction compileCaseExpression(expression, context) {\n  const length = expression.args.length;\n  const args = new Array(length);\n  for (let i = 0; i < length; ++i) {\n    args[i] = compileExpression(expression.args[i], context);\n  }\n  return (context) => {\n    for (let i = 0; i < length - 1; i += 2) {\n      const condition = args[i](context);\n      if (condition) {\n        return args[i + 1](context);\n      }\n    }\n    return args[length - 1](context);\n  };\n}\n\n/**\n * @param {import('./expression.js').CallExpression} expression The call expression.\n * @param {import('./expression.js').ParsingContext} context The parsing context.\n * @return {ExpressionEvaluator} The evaluator function.\n */\nfunction compileMatchExpression(expression, context) {\n  const length = expression.args.length;\n  const args = new Array(length);\n  for (let i = 0; i < length; ++i) {\n    args[i] = compileExpression(expression.args[i], context);\n  }\n  return (context) => {\n    const value = args[0](context);\n    for (let i = 1; i < length - 1; i += 2) {\n      if (value === args[i](context)) {\n        return args[i + 1](context);\n      }\n    }\n    return args[length - 1](context);\n  };\n}\n\n/**\n * @param {import('./expression.js').CallExpression} expression The call expression.\n * @param {import('./expression.js').ParsingContext} context The parsing context.\n * @return {ExpressionEvaluator} The evaluator function.\n */\nfunction compileInterpolateExpression(expression, context) {\n  const length = expression.args.length;\n  const args = new Array(length);\n  for (let i = 0; i < length; ++i) {\n    args[i] = compileExpression(expression.args[i], context);\n  }\n  return (context) => {\n    const base = args[0](context);\n    const value = args[1](context);\n\n    let previousInput;\n    let previousOutput;\n    for (let i = 2; i < length; i += 2) {\n      const input = args[i](context);\n      let output = args[i + 1](context);\n      const isColor = Array.isArray(output);\n      if (isColor) {\n        output = withAlpha(output);\n      }\n      if (input >= value) {\n        if (i === 2) {\n          return output;\n        }\n        if (isColor) {\n          return interpolateColor(\n            base,\n            value,\n            previousInput,\n            previousOutput,\n            input,\n            output,\n          );\n        }\n        return interpolateNumber(\n          base,\n          value,\n          previousInput,\n          previousOutput,\n          input,\n          output,\n        );\n      }\n      previousInput = input;\n      previousOutput = output;\n    }\n    return previousOutput;\n  };\n}\n\n/**\n * @param {import('./expression.js').CallExpression} expression The call expression.\n * @param {import('./expression.js').ParsingContext} context The parsing context.\n * @return {ExpressionEvaluator} The evaluator function.\n */\nfunction compileConvertExpression(expression, context) {\n  const op = expression.operator;\n  const length = expression.args.length;\n\n  const args = new Array(length);\n  for (let i = 0; i < length; ++i) {\n    args[i] = compileExpression(expression.args[i], context);\n  }\n  switch (op) {\n    case Ops.ToString: {\n      return (context) => {\n        const value = args[0](context);\n        if (expression.args[0].type === ColorType) {\n          return toString(value);\n        }\n        return value.toString();\n      };\n    }\n    default: {\n      throw new Error(`Unsupported convert operator ${op}`);\n    }\n  }\n}\n\n/**\n * @param {number} base The base.\n * @param {number} value The value.\n * @param {number} input1 The first input value.\n * @param {number} output1 The first output value.\n * @param {number} input2 The second input value.\n * @param {number} output2 The second output value.\n * @return {number} The interpolated value.\n */\nfunction interpolateNumber(base, value, input1, output1, input2, output2) {\n  const delta = input2 - input1;\n  if (delta === 0) {\n    return output1;\n  }\n  const along = value - input1;\n  const factor =\n    base === 1\n      ? along / delta\n      : (Math.pow(base, along) - 1) / (Math.pow(base, delta) - 1);\n  return output1 + factor * (output2 - output1);\n}\n\n/**\n * @param {number} base The base.\n * @param {number} value The value.\n * @param {number} input1 The first input value.\n * @param {import('../color.js').Color} rgba1 The first output value.\n * @param {number} input2 The second input value.\n * @param {import('../color.js').Color} rgba2 The second output value.\n * @return {import('../color.js').Color} The interpolated color.\n */\nfunction interpolateColor(base, value, input1, rgba1, input2, rgba2) {\n  const delta = input2 - input1;\n  if (delta === 0) {\n    return rgba1;\n  }\n  const lcha1 = rgbaToLcha(rgba1);\n  const lcha2 = rgbaToLcha(rgba2);\n  let deltaHue = lcha2[2] - lcha1[2];\n  if (deltaHue > 180) {\n    deltaHue -= 360;\n  } else if (deltaHue < -180) {\n    deltaHue += 360;\n  }\n\n  const lcha = [\n    interpolateNumber(base, value, input1, lcha1[0], input2, lcha2[0]),\n    interpolateNumber(base, value, input1, lcha1[1], input2, lcha2[1]),\n    lcha1[2] + interpolateNumber(base, value, input1, 0, input2, deltaHue),\n    interpolateNumber(base, value, input1, rgba1[3], input2, rgba2[3]),\n  ];\n  return lchaToRgba(lcha);\n}\n", "/**\n * @module ol/ImageState\n */\n\n/**\n * @enum {number}\n */\nexport default {\n  IDLE: 0,\n  LOADING: 1,\n  LOADED: 2,\n  ERROR: 3,\n  EMPTY: 4,\n};\n", "/**\n * @module ol/Image\n */\nimport ImageState from './ImageState.js';\nimport {listenOnce, unlistenByKey} from './events.js';\nimport EventType from './events/EventType.js';\nimport EventTarget from './events/Target.js';\nimport {toPromise} from './functions.js';\nimport {CREATE_IMAGE_BITMAP, IMAGE_DECODE} from './has.js';\n\n/**\n * A function that takes an {@link module:ol/Image~ImageWrapper} for the image and a\n * `{string}` for the src as arguments. It is supposed to make it so the\n * underlying image {@link module:ol/Image~ImageWrapper#getImage} is assigned the\n * content specified by the src. If not specified, the default is\n *\n *     function(image, src) {\n *       image.getImage().src = src;\n *     }\n *\n * Providing a custom `imageLoadFunction` can be useful to load images with\n * post requests or - in general - through XHR requests, where the src of the\n * image element would be set to a data URI when the content is loaded.\n *\n * @typedef {function(import(\"./Image.js\").default, string): void} LoadFunction\n * @api\n */\n\n/**\n * @typedef {Object} ImageObject\n * @property {import(\"./extent.js\").Extent} [extent] Extent, if different from the requested one.\n * @property {import(\"./resolution.js\").ResolutionLike} [resolution] Resolution, if different from the requested one.\n * When x and y resolution are different, use the array type (`[xResolution, yResolution]`).\n * @property {number} [pixelRatio] Pixel ratio, if different from the requested one.\n * @property {import('./DataTile.js').ImageLike} image Image.\n */\n\n/**\n * Loader function used for image sources. Receives extent, resolution and pixel ratio as arguments.\n * For images that cover any extent and resolution (static images), the loader function should not accept\n * any arguments. The function returns an {@link import(\"./DataTile.js\").ImageLike image}, an\n * {@link import(\"./Image.js\").ImageObject image object}, or a promise for the same.\n * For loaders that generate images, the promise should not resolve until the image is loaded.\n * If the returned image does not match the extent, resolution or pixel ratio passed to the loader,\n * it has to return an {@link import(\"./Image.js\").ImageObject image object} with the `image` and the\n * correct `extent`, `resolution` and `pixelRatio`.\n *\n * @typedef {function(import(\"./extent.js\").Extent, number, number, (function(HTMLImageElement, string): void)=): import(\"./DataTile.js\").ImageLike|ImageObject|Promise<import(\"./DataTile.js\").ImageLike|ImageObject>} Loader\n * @api\n */\n\n/**\n * Loader function used for image sources. Receives extent, resolution and pixel ratio as arguments.\n * The function returns a promise for an  {@link import(\"./Image.js\").ImageObject image object}.\n *\n * @typedef {function(import(\"./extent.js\").Extent, number, number, (function(HTMLImageElement, string): void)=): Promise<import(\"./DataTile.js\").ImageLike|ImageObject>} ImageObjectPromiseLoader\n */\n\nclass ImageWrapper extends EventTarget {\n  /**\n   * @param {import(\"./extent.js\").Extent} extent Extent.\n   * @param {number|Array<number>|undefined} resolution Resolution. If provided as array, x and y\n   * resolution will be assumed.\n   * @param {number} pixelRatio Pixel ratio.\n   * @param {import(\"./ImageState.js\").default|Loader} stateOrLoader State.\n   */\n  constructor(extent, resolution, pixelRatio, stateOrLoader) {\n    super();\n\n    /**\n     * @protected\n     * @type {import(\"./extent.js\").Extent}\n     */\n    this.extent = extent;\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.pixelRatio_ = pixelRatio;\n\n    /**\n     * @protected\n     * @type {number|Array<number>|undefined}\n     */\n    this.resolution = resolution;\n\n    /**\n     * @protected\n     * @type {import(\"./ImageState.js\").default}\n     */\n    this.state =\n      typeof stateOrLoader === 'function' ? ImageState.IDLE : stateOrLoader;\n\n    /**\n     * @private\n     * @type {import('./DataTile.js').ImageLike|null}\n     */\n    this.image_ = null;\n\n    /**\n     * @protected\n     * @type {Loader|null}\n     */\n    this.loader = typeof stateOrLoader === 'function' ? stateOrLoader : null;\n  }\n\n  /**\n   * @protected\n   */\n  changed() {\n    this.dispatchEvent(EventType.CHANGE);\n  }\n\n  /**\n   * @return {import(\"./extent.js\").Extent} Extent.\n   */\n  getExtent() {\n    return this.extent;\n  }\n\n  /**\n   * @return {import('./DataTile.js').ImageLike} Image.\n   */\n  getImage() {\n    return this.image_;\n  }\n\n  /**\n   * @return {number} PixelRatio.\n   */\n  getPixelRatio() {\n    return this.pixelRatio_;\n  }\n\n  /**\n   * @return {number|Array<number>} Resolution.\n   */\n  getResolution() {\n    return /** @type {number} */ (this.resolution);\n  }\n\n  /**\n   * @return {import(\"./ImageState.js\").default} State.\n   */\n  getState() {\n    return this.state;\n  }\n\n  /**\n   * Load not yet loaded URI.\n   */\n  load() {\n    if (this.state == ImageState.IDLE) {\n      if (this.loader) {\n        this.state = ImageState.LOADING;\n        this.changed();\n        const resolution = this.getResolution();\n        const requestResolution = Array.isArray(resolution)\n          ? resolution[0]\n          : resolution;\n        toPromise(() =>\n          this.loader(\n            this.getExtent(),\n            requestResolution,\n            this.getPixelRatio(),\n          ),\n        )\n          .then((image) => {\n            if ('image' in image) {\n              this.image_ = image.image;\n            }\n            if ('extent' in image) {\n              this.extent = image.extent;\n            }\n            if ('resolution' in image) {\n              this.resolution = image.resolution;\n            }\n            if ('pixelRatio' in image) {\n              this.pixelRatio_ = image.pixelRatio;\n            }\n            if (\n              image instanceof HTMLImageElement ||\n              (CREATE_IMAGE_BITMAP && image instanceof ImageBitmap) ||\n              image instanceof HTMLCanvasElement ||\n              image instanceof HTMLVideoElement\n            ) {\n              this.image_ = image;\n            }\n            this.state = ImageState.LOADED;\n          })\n          .catch((error) => {\n            this.state = ImageState.ERROR;\n            console.error(error); // eslint-disable-line no-console\n          })\n          .finally(() => this.changed());\n      }\n    }\n  }\n\n  /**\n   * @param {import('./DataTile.js').ImageLike} image The image.\n   */\n  setImage(image) {\n    this.image_ = image;\n  }\n\n  /**\n   * @param {number|Array<number>} resolution Resolution.\n   */\n  setResolution(resolution) {\n    this.resolution = resolution;\n  }\n}\n\n/**\n * @param {import('./DataTile.js').ImageLike} image Image element.\n * @param {function():any} loadHandler Load callback function.\n * @param {function():any} errorHandler Error callback function.\n * @return {function():void} Callback to stop listening.\n */\nexport function listenImage(image, loadHandler, errorHandler) {\n  const img = /** @type {HTMLImageElement} */ (image);\n  let listening = true;\n  let decoding = false;\n  let loaded = false;\n\n  const listenerKeys = [\n    listenOnce(img, EventType.LOAD, function () {\n      loaded = true;\n      if (!decoding) {\n        loadHandler();\n      }\n    }),\n  ];\n\n  if (img.src && IMAGE_DECODE) {\n    decoding = true;\n    img\n      .decode()\n      .then(function () {\n        if (listening) {\n          loadHandler();\n        }\n      })\n      .catch(function (error) {\n        if (listening) {\n          if (loaded) {\n            loadHandler();\n          } else {\n            errorHandler();\n          }\n        }\n      });\n  } else {\n    listenerKeys.push(listenOnce(img, EventType.ERROR, errorHandler));\n  }\n\n  return function unlisten() {\n    listening = false;\n    listenerKeys.forEach(unlistenByKey);\n  };\n}\n\n/**\n * Loads an image.\n * @param {HTMLImageElement} image Image, not yet loaded.\n * @param {string} [src] `src` attribute of the image. Optional, not required if already present.\n * @return {Promise<HTMLImageElement>} Promise resolving to an `HTMLImageElement`.\n * @api\n */\nexport function load(image, src) {\n  return new Promise((resolve, reject) => {\n    function handleLoad() {\n      unlisten();\n      resolve(image);\n    }\n    function handleError() {\n      unlisten();\n      reject(new Error('Image load error'));\n    }\n    function unlisten() {\n      image.removeEventListener('load', handleLoad);\n      image.removeEventListener('error', handleError);\n    }\n    image.addEventListener('load', handleLoad);\n    image.addEventListener('error', handleError);\n    if (src) {\n      image.src = src;\n    }\n  });\n}\n\n/**\n * @param {HTMLImageElement} image Image, not yet loaded.\n * @param {string} [src] `src` attribute of the image. Optional, not required if already present.\n * @return {Promise<HTMLImageElement>} Promise resolving to an `HTMLImageElement`.\n */\nexport function decodeFallback(image, src) {\n  if (src) {\n    image.src = src;\n  }\n  return image.src && IMAGE_DECODE\n    ? new Promise((resolve, reject) =>\n        image\n          .decode()\n          .then(() => resolve(image))\n          .catch((e) =>\n            image.complete && image.width ? resolve(image) : reject(e),\n          ),\n      )\n    : load(image);\n}\n\n/**\n * Loads an image and decodes it to an `ImageBitmap` if `createImageBitmap()` is supported. Returns\n * the loaded image otherwise.\n * @param {HTMLImageElement} image Image, not yet loaded.\n * @param {string} [src] `src` attribute of the image. Optional, not required if already present.\n * @return {Promise<ImageBitmap|HTMLImageElement>} Promise resolving to an `ImageBitmap` or an\n * `HTMLImageElement` if `createImageBitmap()` is not supported.\n * @api\n */\nexport function decode(image, src) {\n  if (src) {\n    image.src = src;\n  }\n  return image.src && IMAGE_DECODE && CREATE_IMAGE_BITMAP\n    ? image\n        .decode()\n        .then(() => createImageBitmap(image))\n        .catch((e) => {\n          if (image.complete && image.width) {\n            return image;\n          }\n          throw e;\n        })\n    : decodeFallback(image);\n}\n\nexport default ImageWrapper;\n", "/**\n * @module ol/style/IconImageCache\n */\nimport ImageState from '../ImageState.js';\nimport {asArray} from '../color.js';\nimport {getSharedCanvasContext2D} from '../dom.js';\n\n/**\n * @classdesc\n * Singleton class. Available through {@link module:ol/style/IconImageCache.shared}.\n */\nclass IconImageCache {\n  constructor() {\n    /**\n     * @type {!Object<string, import(\"./IconImage.js\").default>}\n     * @private\n     */\n    this.cache_ = {};\n\n    /**\n     * @type {!Object<string, CanvasPattern>}\n     * @private\n     */\n    this.patternCache_ = {};\n\n    /**\n     * @type {number}\n     * @private\n     */\n    this.cacheSize_ = 0;\n\n    /**\n     * @type {number}\n     * @private\n     */\n    this.maxCacheSize_ = 1024;\n  }\n\n  /**\n   * FIXME empty description for jsdoc\n   */\n  clear() {\n    this.cache_ = {};\n    this.patternCache_ = {};\n    this.cacheSize_ = 0;\n  }\n\n  /**\n   * @return {boolean} Can expire cache.\n   */\n  canExpireCache() {\n    return this.cacheSize_ > this.maxCacheSize_;\n  }\n\n  /**\n   * FIXME empty description for jsdoc\n   */\n  expire() {\n    if (this.canExpireCache()) {\n      let i = 0;\n      for (const key in this.cache_) {\n        const iconImage = this.cache_[key];\n        if ((i++ & 3) === 0 && !iconImage.hasListener()) {\n          delete this.cache_[key];\n          delete this.patternCache_[key];\n          --this.cacheSize_;\n        }\n      }\n    }\n  }\n\n  /**\n   * @param {string} src Src.\n   * @param {import(\"../color.js\").Color|string|null} color Color.\n   * @return {import(\"./IconImage.js\").default} Icon image.\n   */\n  get(src, color) {\n    const key = getCacheKey(src, color);\n\n    const icon = key in this.cache_ ? this.cache_[key] : null;\n    return icon;\n  }\n\n  /**\n   * @param {string} src Src.\n   * @param {import(\"../color.js\").Color|string|null} color Color.\n   * @return {CanvasPattern} Icon image.\n   */\n  getPattern(src, color) {\n    const key = getCacheKey(src, color);\n    return key in this.patternCache_ ? this.patternCache_[key] : null;\n  }\n\n  /**\n   * @param {string} src Src.\n   * @param {import(\"../color.js\").Color|string|null} color Color.\n   * @param {import(\"./IconImage.js\").default|null} iconImage Icon image.\n   * @param {boolean} [pattern] Also cache a `'repeat'` pattern with this `iconImage`.\n   */\n  set(src, color, iconImage, pattern) {\n    const key = getCacheKey(src, color);\n    const update = key in this.cache_;\n    this.cache_[key] = iconImage;\n    if (pattern) {\n      if (iconImage.getImageState() === ImageState.IDLE) {\n        iconImage.load();\n      }\n      if (iconImage.getImageState() === ImageState.LOADING) {\n        iconImage.ready().then(() => {\n          this.patternCache_[key] = getSharedCanvasContext2D().createPattern(\n            iconImage.getImage(1),\n            'repeat',\n          );\n        });\n      } else {\n        this.patternCache_[key] = getSharedCanvasContext2D().createPattern(\n          iconImage.getImage(1),\n          'repeat',\n        );\n      }\n    }\n    if (!update) {\n      ++this.cacheSize_;\n    }\n  }\n\n  /**\n   * Set the cache size of the icon cache. Default is `1024`. Change this value when\n   * your map uses more than 1024 different icon images and you are not caching icon\n   * styles on the application level.\n   * @param {number} maxCacheSize Cache max size.\n   * @api\n   */\n  setSize(maxCacheSize) {\n    this.maxCacheSize_ = maxCacheSize;\n    this.expire();\n  }\n}\n\n/**\n * @param {string} src Src.\n * @param {import(\"../color.js\").Color|string|null} color Color.\n * @return {string} Cache key.\n */\nexport function getCacheKey(src, color) {\n  const colorString = color ? asArray(color) : 'null';\n  return src + ':' + colorString;\n}\n\nexport default IconImageCache;\n\n/**\n * The {@link module:ol/style/IconImageCache~IconImageCache} for\n * {@link module:ol/style/Icon~Icon} images.\n * @api\n */\nexport const shared = new IconImageCache();\n", "/**\n * @module ol/style/IconImage\n */\n\nimport {decodeFallback} from '../Image.js';\nimport ImageState from '../ImageState.js';\nimport {asString} from '../color.js';\nimport {createCanvasContext2D} from '../dom.js';\nimport EventType from '../events/EventType.js';\nimport EventTarget from '../events/Target.js';\nimport {shared as iconImageCache} from './IconImageCache.js';\n\n/**\n * @type {CanvasRenderingContext2D|OffscreenCanvasRenderingContext2D}\n */\nlet taintedTestContext = null;\n\nclass IconImage extends EventTarget {\n  /**\n   * @param {HTMLImageElement|HTMLCanvasElement|OffscreenCanvas|ImageBitmap|null} image Image.\n   * @param {string|undefined} src Src.\n   * @param {import('../dom.js').ImageAttributes} imageAttributes Image attributes options.\n   * @param {import(\"../ImageState.js\").default|undefined} imageState Image state.\n   * @param {import(\"../color.js\").Color|string|null} color Color.\n   */\n  constructor(image, src, imageAttributes, imageState, color) {\n    super();\n\n    /**\n     * @private\n     * @type {HTMLImageElement|OffscreenCanvas|HTMLCanvasElement|ImageBitmap}\n     */\n    this.hitDetectionImage_ = null;\n\n    /**\n     * @private\n     * @type {HTMLImageElement|HTMLCanvasElement|OffscreenCanvas|ImageBitmap|null}\n     */\n    this.image_ = image;\n\n    /**\n     * @private\n     * @type {string|null}\n     */\n    this.crossOrigin_ = imageAttributes?.crossOrigin;\n\n    /**\n     * @private\n     * @type {ReferrerPolicy}\n     */\n    this.referrerPolicy_ = imageAttributes?.referrerPolicy;\n\n    /**\n     * @private\n     * @type {Object<number, HTMLCanvasElement|OffscreenCanvas>}\n     */\n    this.canvas_ = {};\n\n    /**\n     * @private\n     * @type {import(\"../color.js\").Color|string|null}\n     */\n    this.color_ = color;\n\n    /**\n     * @private\n     * @type {import(\"../ImageState.js\").default}\n     */\n    this.imageState_ = imageState === undefined ? ImageState.IDLE : imageState;\n\n    /**\n     * @private\n     * @type {import(\"../size.js\").Size|null}\n     */\n    this.size_ =\n      image && image.width && image.height ? [image.width, image.height] : null;\n\n    /**\n     * @private\n     * @type {string|undefined}\n     */\n    this.src_ = src;\n\n    /**\n     * @private\n     */\n    this.tainted_;\n\n    /**\n     * @private\n     * @type {Promise<void>|null}\n     */\n    this.ready_ = null;\n  }\n\n  /**\n   * @private\n   */\n  initializeImage_() {\n    this.image_ = new Image();\n    if (this.crossOrigin_ !== null) {\n      this.image_.crossOrigin = this.crossOrigin_;\n    }\n    if (this.referrerPolicy_ !== undefined) {\n      this.image_.referrerPolicy = this.referrerPolicy_;\n    }\n  }\n\n  /**\n   * @private\n   * @return {boolean} The image canvas is tainted.\n   */\n  isTainted_() {\n    if (this.tainted_ === undefined && this.imageState_ === ImageState.LOADED) {\n      if (!taintedTestContext) {\n        taintedTestContext = createCanvasContext2D(1, 1, undefined, {\n          willReadFrequently: true,\n        });\n      }\n      taintedTestContext.drawImage(this.image_, 0, 0);\n      try {\n        taintedTestContext.getImageData(0, 0, 1, 1);\n        this.tainted_ = false;\n      } catch {\n        taintedTestContext = null;\n        this.tainted_ = true;\n      }\n    }\n    return this.tainted_ === true;\n  }\n\n  /**\n   * @private\n   */\n  dispatchChangeEvent_() {\n    this.dispatchEvent(EventType.CHANGE);\n  }\n\n  /**\n   * @private\n   */\n  handleImageError_() {\n    this.imageState_ = ImageState.ERROR;\n    this.dispatchChangeEvent_();\n  }\n\n  /**\n   * @private\n   */\n  handleImageLoad_() {\n    this.imageState_ = ImageState.LOADED;\n    this.size_ = [this.image_.width, this.image_.height];\n    this.dispatchChangeEvent_();\n  }\n\n  /**\n   * @param {number} pixelRatio Pixel ratio.\n   * @return {HTMLImageElement|HTMLCanvasElement|OffscreenCanvas|ImageBitmap} Image or Canvas element or image bitmap.\n   */\n  getImage(pixelRatio) {\n    if (!this.image_) {\n      this.initializeImage_();\n    }\n    this.replaceColor_(pixelRatio);\n    return this.canvas_[pixelRatio] ? this.canvas_[pixelRatio] : this.image_;\n  }\n\n  /**\n   * @param {HTMLImageElement|HTMLCanvasElement|OffscreenCanvas|ImageBitmap} image Image.\n   */\n  setImage(image) {\n    this.image_ = image;\n  }\n\n  /**\n   * @param {number} pixelRatio Pixel ratio.\n   * @return {number} Image or Canvas element.\n   */\n  getPixelRatio(pixelRatio) {\n    this.replaceColor_(pixelRatio);\n    return this.canvas_[pixelRatio] ? pixelRatio : 1;\n  }\n\n  /**\n   * @return {import(\"../ImageState.js\").default} Image state.\n   */\n  getImageState() {\n    return this.imageState_;\n  }\n\n  /**\n   * @return {HTMLImageElement|HTMLCanvasElement|OffscreenCanvas|ImageBitmap} Image element.\n   */\n  getHitDetectionImage() {\n    if (!this.image_) {\n      this.initializeImage_();\n    }\n    if (!this.hitDetectionImage_) {\n      if (this.isTainted_()) {\n        const width = this.size_[0];\n        const height = this.size_[1];\n        const context = createCanvasContext2D(width, height);\n        context.fillRect(0, 0, width, height);\n        this.hitDetectionImage_ = context.canvas;\n      } else {\n        this.hitDetectionImage_ = this.image_;\n      }\n    }\n    return this.hitDetectionImage_;\n  }\n\n  /**\n   * Get the size of the icon (in pixels).\n   * @return {import(\"../size.js\").Size} Image size.\n   */\n  getSize() {\n    return this.size_;\n  }\n\n  /**\n   * @return {string|undefined} Image src.\n   */\n  getSrc() {\n    return this.src_;\n  }\n\n  /**\n   * Load not yet loaded URI.\n   */\n  load() {\n    if (this.imageState_ !== ImageState.IDLE) {\n      return;\n    }\n    if (!this.image_) {\n      this.initializeImage_();\n    }\n\n    this.imageState_ = ImageState.LOADING;\n    try {\n      if (this.src_ !== undefined) {\n        /** @type {HTMLImageElement} */ (this.image_).src = this.src_;\n      }\n    } catch {\n      this.handleImageError_();\n    }\n    if (this.image_ instanceof HTMLImageElement) {\n      decodeFallback(this.image_, this.src_)\n        .then((image) => {\n          this.image_ = image;\n          this.handleImageLoad_();\n        })\n        .catch(this.handleImageError_.bind(this));\n    }\n  }\n\n  /**\n   * @param {number} pixelRatio Pixel ratio.\n   * @private\n   */\n  replaceColor_(pixelRatio) {\n    if (\n      !this.color_ ||\n      this.canvas_[pixelRatio] ||\n      this.imageState_ !== ImageState.LOADED\n    ) {\n      return;\n    }\n\n    const image = this.image_;\n    const ctx = createCanvasContext2D(\n      Math.ceil(image.width * pixelRatio),\n      Math.ceil(image.height * pixelRatio),\n    );\n    const canvas = ctx.canvas;\n\n    ctx.scale(pixelRatio, pixelRatio);\n    ctx.drawImage(image, 0, 0);\n\n    ctx.globalCompositeOperation = 'multiply';\n    ctx.fillStyle = asString(this.color_);\n    ctx.fillRect(0, 0, canvas.width / pixelRatio, canvas.height / pixelRatio);\n\n    ctx.globalCompositeOperation = 'destination-in';\n    ctx.drawImage(image, 0, 0);\n\n    this.canvas_[pixelRatio] = canvas;\n  }\n\n  /**\n   * @return {Promise<void>} Promise that resolves when the image is loaded.\n   */\n  ready() {\n    if (!this.ready_) {\n      this.ready_ = new Promise((resolve) => {\n        if (\n          this.imageState_ === ImageState.LOADED ||\n          this.imageState_ === ImageState.ERROR\n        ) {\n          resolve();\n        } else {\n          const onChange = () => {\n            if (\n              this.imageState_ === ImageState.LOADED ||\n              this.imageState_ === ImageState.ERROR\n            ) {\n              this.removeEventListener(EventType.CHANGE, onChange);\n              resolve();\n            }\n          };\n          this.addEventListener(EventType.CHANGE, onChange);\n        }\n      });\n    }\n    return this.ready_;\n  }\n}\n\n/**\n * @param {HTMLImageElement|HTMLCanvasElement|OffscreenCanvas|ImageBitmap|null} image Image.\n * @param {string|undefined} src Src.\n * @param {import('../dom.js').ImageAttributes} imageAttributes Image attributes options.\n * @param {import(\"../ImageState.js\").default|undefined} imageState Image state.\n * @param {import(\"../color.js\").Color|string|null} color Color.\n * @param {boolean} [pattern] Also cache a `repeat` pattern with the icon image.\n * @return {IconImage} Icon image.\n */\nexport function get(image, src, imageAttributes, imageState, color, pattern) {\n  let iconImage =\n    src === undefined ? undefined : iconImageCache.get(src, color);\n  if (!iconImage) {\n    iconImage = new IconImage(\n      image,\n      image && 'src' in image ? image.src || undefined : src,\n      imageAttributes,\n      imageState,\n      color,\n    );\n    iconImageCache.set(src, color, iconImage, pattern);\n  }\n  if (pattern && iconImage && !iconImageCache.getPattern(src, color)) {\n    iconImageCache.set(src, color, iconImage, pattern);\n  }\n  return iconImage;\n}\n\nexport default IconImage;\n", "/**\n * @module ol/colorlike\n */\nimport ImageState from './ImageState.js';\nimport {toString} from './color.js';\nimport {createCanvasContext2D} from './dom.js';\nimport {get as getIconImage} from './style/IconImage.js';\nimport {shared as iconCache} from './style/IconImageCache.js';\n\n/**\n * @typedef {Object} PatternDescriptor\n * @property {string} src Pattern image URL\n * @property {import(\"./color.js\").Color|string} [color] Color to tint the pattern with.\n * @property {import(\"./size.js\").Size} [size] Size of the desired slice from the pattern image.\n * Use this together with `offset` when the pattern image is a sprite sheet.\n * @property {import(\"./size.js\").Size} [offset] Offset of the desired slice from the pattern image.\n * Use this together with `size` when the pattern image is a sprite sheet.\n */\n\n/**\n * A type accepted by CanvasRenderingContext2D.fillStyle\n * or CanvasRenderingContext2D.strokeStyle.\n * Represents a color, [CanvasPattern](https://developer.mozilla.org/en-US/docs/Web/API/CanvasPattern),\n * or [CanvasGradient](https://developer.mozilla.org/en-US/docs/Web/API/CanvasGradient). The origin for\n * patterns and gradients as fill style is an increment of 512 css pixels from map coordinate\n * `[0, 0]`. For seamless repeat patterns, width and height of the pattern image\n * must be a factor of two (2, 4, 8, ..., 512).\n *\n * @typedef {string|CanvasPattern|CanvasGradient} ColorLike\n * @api\n */\n\n/**\n * @param {import(\"./color.js\").Color|ColorLike|PatternDescriptor|null} color Color.\n * @return {ColorLike|null} The color as an {@link ol/colorlike~ColorLike}.\n * @api\n */\nexport function asColorLike(color) {\n  if (!color) {\n    return null;\n  }\n  if (Array.isArray(color)) {\n    return toString(color);\n  }\n  if (typeof color === 'object' && 'src' in color) {\n    return asCanvasPattern(color);\n  }\n  return color;\n}\n\n/**\n * @param {PatternDescriptor} pattern Pattern descriptor.\n * @return {CanvasPattern|null} Canvas pattern or null if the pattern referenced in the\n * PatternDescriptor was not found in the icon image cache.\n */\nfunction asCanvasPattern(pattern) {\n  if (!pattern.offset || !pattern.size) {\n    return iconCache.getPattern(pattern.src, pattern.color);\n  }\n\n  const cacheKey = pattern.src + ':' + pattern.offset;\n\n  const canvasPattern = iconCache.getPattern(cacheKey, pattern.color);\n  if (canvasPattern) {\n    return canvasPattern;\n  }\n\n  const iconImage = iconCache.get(pattern.src, null);\n  if (iconImage.getImageState() !== ImageState.LOADED) {\n    return null;\n  }\n  const patternCanvasContext = createCanvasContext2D(\n    pattern.size[0],\n    pattern.size[1],\n  );\n  patternCanvasContext.drawImage(\n    iconImage.getImage(1),\n    pattern.offset[0],\n    pattern.offset[1],\n    pattern.size[0],\n    pattern.size[1],\n    0,\n    0,\n    pattern.size[0],\n    pattern.size[1],\n  );\n  getIconImage(\n    patternCanvasContext.canvas,\n    cacheKey,\n    undefined,\n    ImageState.LOADED,\n    pattern.color,\n    true,\n  );\n  return iconCache.getPattern(cacheKey, pattern.color);\n}\n", "/**\n * @module ol/render/canvas\n */\nimport BaseObject from '../Object.js';\nimport {fontWeights, getFontParameters} from '../css.js';\nimport {createCanvasContext2D} from '../dom.js';\nimport {WORKER_OFFSCREEN_CANVAS} from '../has.js';\nimport {clear} from '../obj.js';\n\n/**\n * @typedef {'Circle' | 'Image' | 'LineString' | 'Polygon' | 'Text' | 'Default'} BuilderType\n */\n\n/**\n * @typedef {Object} FillState\n * @property {import(\"../colorlike.js\").ColorLike} fillStyle FillStyle.\n */\n\n/**\n * @typedef Label\n * @property {number} width Width.\n * @property {number} height Height.\n * @property {Array<string|number>} contextInstructions ContextInstructions.\n */\n\n/**\n * @typedef {Object} FillStrokeState\n * @property {import(\"../colorlike.js\").ColorLike} [currentFillStyle] Current FillStyle.\n * @property {import(\"../colorlike.js\").ColorLike} [currentStrokeStyle] Current StrokeStyle.\n * @property {CanvasLineCap} [currentLineCap] Current LineCap.\n * @property {Array<number>} currentLineDash Current LineDash.\n * @property {number} [currentLineDashOffset] Current LineDashOffset.\n * @property {CanvasLineJoin} [currentLineJoin] Current LineJoin.\n * @property {number} [currentLineWidth] Current LineWidth.\n * @property {number} [currentMiterLimit] Current MiterLimit.\n * @property {number} [currentStrokeOffset] Current StrokeOffset.\n * @property {number} [lastStroke] Last stroke.\n * @property {import(\"../colorlike.js\").ColorLike} [fillStyle] FillStyle.\n * @property {import(\"../colorlike.js\").ColorLike} [strokeStyle] StrokeStyle.\n * @property {CanvasLineCap} [lineCap] LineCap.\n * @property {Array<number>} lineDash LineDash.\n * @property {number} [lineDashOffset] LineDashOffset.\n * @property {CanvasLineJoin} [lineJoin] LineJoin.\n * @property {number} [lineWidth] LineWidth.\n * @property {number} [miterLimit] MiterLimit.\n * @property {number} [strokeOffset] StrokeOffset.\n * @property {number} [fillPatternScale] Fill pattern scale.\n */\n\n/**\n * @typedef {Object} StrokeState\n * @property {CanvasLineCap} lineCap LineCap.\n * @property {Array<number>} lineDash LineDash.\n * @property {number} lineDashOffset LineDashOffset.\n * @property {CanvasLineJoin} lineJoin LineJoin.\n * @property {number} lineWidth LineWidth.\n * @property {number} miterLimit MiterLimit.\n * @property {number} [strokeOffset] StrokeOffset.\n * @property {import(\"../colorlike.js\").ColorLike} strokeStyle StrokeStyle.\n */\n\n/**\n * @typedef {Object} TextState\n * @property {string} font Font.\n * @property {CanvasTextAlign} [textAlign] TextAlign.\n * @property {number} [repeat] Repeat.\n * @property {import(\"../style/Text.js\").TextJustify} [justify] Justify.\n * @property {CanvasTextBaseline} textBaseline TextBaseline.\n * @property {import(\"../style/Text.js\").TextPlacement} [placement] Placement.\n * @property {number} [maxAngle] MaxAngle.\n * @property {boolean} [overflow] Overflow.\n * @property {import(\"../style/Fill.js\").default} [backgroundFill] BackgroundFill.\n * @property {import(\"../style/Stroke.js\").default} [backgroundStroke] BackgroundStroke.\n * @property {import(\"../size.js\").Size} [scale] Scale.\n * @property {Array<number>} [padding] Padding.\n */\n\n/**\n * @typedef {Object} SerializableInstructions\n * @property {Array<*>} instructions The rendering instructions.\n * @property {Array<*>} hitDetectionInstructions The rendering hit detection instructions.\n * @property {Array<number>} coordinates The array of all coordinates.\n * @property {!Object<string, TextState>} [textStates] The text states (decluttering).\n * @property {!Object<string, FillState>} [fillStates] The fill states (decluttering).\n * @property {!Object<string, StrokeState>} [strokeStates] The stroke states (decluttering).\n */\n\n/**\n * @typedef {Object<number, import(\"./canvas/Executor.js\").ReplayImageOrLabelArgs>} DeclutterImageWithText\n */\n\n/**\n * @const\n * @type {string}\n */\nexport const defaultFont = '10px sans-serif';\n\n/**\n * @const\n * @type {string}\n */\nexport const defaultFillStyle = '#000';\n\n/**\n * @const\n * @type {CanvasLineCap}\n */\nexport const defaultLineCap = 'round';\n\n/**\n * @const\n * @type {Array<number>}\n */\nexport const defaultLineDash = [];\n\n/**\n * @const\n * @type {number}\n */\nexport const defaultLineDashOffset = 0;\n\n/**\n * @const\n * @type {CanvasLineJoin}\n */\nexport const defaultLineJoin = 'round';\n\n/**\n * @const\n * @type {number}\n */\nexport const defaultMiterLimit = 10;\n\n/**\n * @const\n * @type {number}\n */\nexport const defaultStrokeOffset = 0;\n\n/**\n * @const\n * @type {import(\"../colorlike.js\").ColorLike}\n */\nexport const defaultStrokeStyle = '#000';\n\n/**\n * @const\n * @type {CanvasTextAlign}\n */\nexport const defaultTextAlign = 'center';\n\n/**\n * @const\n * @type {CanvasTextBaseline}\n */\nexport const defaultTextBaseline = 'middle';\n\n/**\n * @const\n * @type {Array<number>}\n */\nexport const defaultPadding = [0, 0, 0, 0];\n\n/**\n * @const\n * @type {number}\n */\nexport const defaultLineWidth = 1;\n\n/**\n * @type {BaseObject}\n */\nexport const checkedFonts = new BaseObject();\n\n/**\n * @type {CanvasRenderingContext2D|OffscreenCanvasRenderingContext2D}\n */\nlet measureContext = null;\n\n/**\n * @type {string}\n */\nlet measureFont;\n\n/**\n * @type {!Object<string, number>}\n */\nexport const textHeights = {};\n\nconst genericFontFamilies = new Set([\n  'serif',\n  'sans-serif',\n  'monospace',\n  'cursive',\n  'fantasy',\n  'system-ui',\n  'ui-serif',\n  'ui-sans-serif',\n  'ui-monospace',\n  'ui-rounded',\n  'emoji',\n  'math',\n  'fangsong',\n]);\n\n/**\n * @param {string} style Css font-style\n * @param {string} weight Css font-weight\n * @param {string} family Css font-family\n * @return {string} Font key.\n */\nfunction getFontKey(style, weight, family) {\n  return `${style} ${weight} 16px \"${family}\"`;\n}\n\n/**\n * Clears the label cache when a font becomes available.\n * @param {string} fontSpec CSS font spec.\n */\nexport const registerFont = (function () {\n  const retries = 100;\n  let timeout, fontFaceSet;\n\n  /**\n   * @param {string} fontSpec Css font spec\n   * @return {Promise<boolean>} Font with style and weight is available\n   */\n  async function isAvailable(fontSpec) {\n    await fontFaceSet.ready;\n    const fontFaces = await fontFaceSet.load(fontSpec);\n    if (fontFaces.length === 0) {\n      return false;\n    }\n    const font = getFontParameters(fontSpec);\n    const checkFamily = font.families[0].toLowerCase();\n    const checkWeight = font.weight;\n    return fontFaces.some(\n      /**\n       * @param {import('../css.js').FontParameters} f Font.\n       * @return {boolean} Font matches.\n       */\n      (f) => {\n        const family = f.family.replace(/^['\"]|['\"]$/g, '').toLowerCase();\n        const weight = fontWeights[f.weight] || f.weight;\n        return (\n          family === checkFamily &&\n          f.style === font.style &&\n          weight == checkWeight\n        );\n      },\n    );\n  }\n\n  async function check() {\n    await fontFaceSet.ready;\n    let done = true;\n    const checkedFontsProperties = checkedFonts.getProperties();\n    const fonts = Object.keys(checkedFontsProperties).filter(\n      (key) => checkedFontsProperties[key] < retries,\n    );\n    for (let i = fonts.length - 1; i >= 0; --i) {\n      const font = fonts[i];\n      let currentRetries = checkedFontsProperties[font];\n      if (currentRetries < retries) {\n        if (await isAvailable(font)) {\n          clear(textHeights);\n          checkedFonts.set(font, retries);\n        } else {\n          currentRetries += 10;\n          checkedFonts.set(font, currentRetries, true);\n          if (currentRetries < retries) {\n            done = false;\n          }\n        }\n      }\n    }\n    timeout = undefined;\n    if (!done) {\n      timeout = setTimeout(check, 100);\n    }\n  }\n\n  return async function (fontSpec) {\n    if (!fontFaceSet) {\n      fontFaceSet = WORKER_OFFSCREEN_CANVAS ? self.fonts : document.fonts;\n    }\n    const font = getFontParameters(fontSpec);\n    if (!font) {\n      return;\n    }\n    const families = font.families;\n    let needCheck = false;\n    for (const family of families) {\n      if (genericFontFamilies.has(family)) {\n        continue;\n      }\n      const key = getFontKey(font.style, font.weight, family);\n      if (checkedFonts.get(key) !== undefined) {\n        continue;\n      }\n      checkedFonts.set(key, 0, true);\n      needCheck = true;\n    }\n    if (needCheck) {\n      clearTimeout(timeout);\n      timeout = setTimeout(check, 100);\n    }\n  };\n})();\n\n/**\n * @param {string} font Font to use for measuring.\n * @return {import(\"../size.js\").Size} Measurement.\n */\nexport const measureTextHeight = (function () {\n  /**\n   * @type {HTMLDivElement}\n   */\n  let measureElement;\n  return function (fontSpec) {\n    let height = textHeights[fontSpec];\n    if (height == undefined) {\n      if (WORKER_OFFSCREEN_CANVAS) {\n        const font = getFontParameters(fontSpec);\n        const metrics = measureText(fontSpec, '\u017Dg');\n        const lineHeight = isNaN(Number(font.lineHeight))\n          ? 1.2\n          : Number(font.lineHeight);\n        height =\n          lineHeight *\n          (metrics.actualBoundingBoxAscent + metrics.actualBoundingBoxDescent);\n      } else {\n        if (!measureElement) {\n          measureElement = document.createElement('div');\n          measureElement.innerHTML = 'M';\n          measureElement.style.minHeight = '0';\n          measureElement.style.maxHeight = 'none';\n          measureElement.style.height = 'auto';\n          measureElement.style.padding = '0';\n          measureElement.style.border = 'none';\n          measureElement.style.position = 'absolute';\n          measureElement.style.display = 'block';\n          measureElement.style.left = '-99999px';\n        }\n        measureElement.style.font = fontSpec;\n        document.body.appendChild(measureElement);\n        height = measureElement.offsetHeight;\n        document.body.removeChild(measureElement);\n      }\n      textHeights[fontSpec] = height;\n    }\n    return height;\n  };\n})();\n\n/**\n * @param {string} font Font.\n * @param {string} text Text.\n * @return {TextMetrics} Text metrics.\n */\nfunction measureText(font, text) {\n  if (!measureContext) {\n    measureContext = createCanvasContext2D(1, 1);\n  }\n  if (font != measureFont) {\n    measureContext.font = font;\n    measureFont = measureContext.font;\n  }\n  return measureContext.measureText(text);\n}\n\n/**\n * @param {string} font Font.\n * @param {string} text Text.\n * @return {number} Width.\n */\nexport function measureTextWidth(font, text) {\n  return measureText(font, text).width;\n}\n\n/**\n * Measure text width using a cache.\n * @param {string} font The font.\n * @param {string} text The text to measure.\n * @param {Object<string, number>} cache A lookup of cached widths by text.\n * @return {number} The text width.\n */\nexport function measureAndCacheTextWidth(font, text, cache) {\n  if (text in cache) {\n    return cache[text];\n  }\n  const width = text\n    .split('\\n')\n    .reduce((prev, curr) => Math.max(prev, measureTextWidth(font, curr)), 0);\n  cache[text] = width;\n  return width;\n}\n\n/**\n * @param {TextState} baseStyle Base style.\n * @param {Array<string>} chunks Text chunks to measure.\n * @return {{width: number, height: number, widths: Array<number>, heights: Array<number>, lineWidths: Array<number>}}} Text metrics.\n */\nexport function getTextDimensions(baseStyle, chunks) {\n  const widths = [];\n  const heights = [];\n  const lineWidths = [];\n  let width = 0;\n  let lineWidth = 0;\n  let height = 0;\n  let lineHeight = 0;\n  for (let i = 0, ii = chunks.length; i <= ii; i += 2) {\n    const text = chunks[i];\n    if (text === '\\n' || i === ii) {\n      width = Math.max(width, lineWidth);\n      lineWidths.push(lineWidth);\n      lineWidth = 0;\n      height += lineHeight;\n      lineHeight = 0;\n      continue;\n    }\n    const font = chunks[i + 1] || baseStyle.font;\n    const currentWidth = measureTextWidth(font, text);\n    widths.push(currentWidth);\n    lineWidth += currentWidth;\n    const currentHeight = measureTextHeight(font);\n    heights.push(currentHeight);\n    lineHeight = Math.max(lineHeight, currentHeight);\n  }\n  return {width, height, widths, heights, lineWidths};\n}\n\n/**\n * @param {CanvasRenderingContext2D} context Context.\n * @param {number} rotation Rotation.\n * @param {number} offsetX X offset.\n * @param {number} offsetY Y offset.\n */\nexport function rotateAtOffset(context, rotation, offsetX, offsetY) {\n  if (rotation !== 0) {\n    context.translate(offsetX, offsetY);\n    context.rotate(rotation);\n    context.translate(-offsetX, -offsetY);\n  }\n}\n\n/**\n * @param {CanvasRenderingContext2D|import(\"../render/canvas/ZIndexContext.js\").ZIndexContextProxy} context Context.\n * @param {import(\"../transform.js\").Transform|null} transform Transform.\n * @param {number} opacity Opacity.\n * @param {Label|HTMLCanvasElement|HTMLImageElement|HTMLVideoElement} labelOrImage Label.\n * @param {number} originX Origin X.\n * @param {number} originY Origin Y.\n * @param {number} w Width.\n * @param {number} h Height.\n * @param {number} x X.\n * @param {number} y Y.\n * @param {import(\"../size.js\").Size} scale Scale.\n */\nexport function drawImageOrLabel(\n  context,\n  transform,\n  opacity,\n  labelOrImage,\n  originX,\n  originY,\n  w,\n  h,\n  x,\n  y,\n  scale,\n) {\n  context.save();\n\n  if (opacity !== 1) {\n    if (context.globalAlpha === undefined) {\n      context.globalAlpha = (context) => (context.globalAlpha *= opacity);\n    } else {\n      context.globalAlpha *= opacity;\n    }\n  }\n  if (transform) {\n    context.transform.apply(context, transform);\n  }\n\n  if (/** @type {*} */ (labelOrImage).contextInstructions) {\n    // label\n    context.translate(x, y);\n    context.scale(scale[0], scale[1]);\n    executeLabelInstructions(/** @type {Label} */ (labelOrImage), context);\n  } else if (scale[0] < 0 || scale[1] < 0) {\n    // flipped image\n    context.translate(x, y);\n    context.scale(scale[0], scale[1]);\n    context.drawImage(\n      /** @type {HTMLCanvasElement|HTMLImageElement|HTMLVideoElement} */ (\n        labelOrImage\n      ),\n      originX,\n      originY,\n      w,\n      h,\n      0,\n      0,\n      w,\n      h,\n    );\n  } else {\n    // if image not flipped translate and scale can be avoided\n    context.drawImage(\n      /** @type {HTMLCanvasElement|HTMLImageElement|HTMLVideoElement} */ (\n        labelOrImage\n      ),\n      originX,\n      originY,\n      w,\n      h,\n      x,\n      y,\n      w * scale[0],\n      h * scale[1],\n    );\n  }\n\n  context.restore();\n}\n\n/**\n * @param {Label} label Label.\n * @param {CanvasRenderingContext2D|OffscreenCanvasRenderingContext2D} context Context.\n */\nfunction executeLabelInstructions(label, context) {\n  const contextInstructions = label.contextInstructions;\n  for (let i = 0, ii = contextInstructions.length; i < ii; i += 2) {\n    if (Array.isArray(contextInstructions[i + 1])) {\n      context[contextInstructions[i]].apply(\n        context,\n        contextInstructions[i + 1],\n      );\n    } else {\n      context[contextInstructions[i]] = contextInstructions[i + 1];\n    }\n  }\n}\n", "/**\n * @module ol/style/Image\n */\nimport {toSize} from '../size.js';\nimport {abstract} from '../util.js';\n\n/**\n * @typedef {Object} Options\n * @property {number} opacity Opacity.\n * @property {boolean} rotateWithView If the image should get rotated with the view.\n * @property {number} rotation Rotation.\n * @property {number|import(\"../size.js\").Size} scale Scale.\n * @property {Array<number>} displacement Displacement.\n * @property {import('../style/Style.js').DeclutterMode} declutterMode Declutter mode: `declutter`, `obstacle`, `none`.\n */\n\n/**\n * @classdesc\n * A base class used for creating subclasses and not instantiated in\n * apps. Base class for {@link module:ol/style/Icon~Icon}, {@link module:ol/style/Circle~CircleStyle} and\n * {@link module:ol/style/RegularShape~RegularShape}.\n * @abstract\n * @api\n */\nclass ImageStyle {\n  /**\n   * @param {Options} options Options.\n   */\n  constructor(options) {\n    /**\n     * @private\n     * @type {number}\n     */\n    this.opacity_ = options.opacity;\n\n    /**\n     * @private\n     * @type {boolean}\n     */\n    this.rotateWithView_ = options.rotateWithView;\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.rotation_ = options.rotation;\n\n    /**\n     * @private\n     * @type {number|import(\"../size.js\").Size}\n     */\n    this.scale_ = options.scale;\n\n    /**\n     * @private\n     * @type {import(\"../size.js\").Size}\n     */\n    this.scaleArray_ = toSize(options.scale);\n\n    /**\n     * @private\n     * @type {Array<number>}\n     */\n    this.displacement_ = options.displacement;\n\n    /**\n     * @private\n     * @type {import('../style/Style.js').DeclutterMode}\n     */\n    this.declutterMode_ = options.declutterMode;\n  }\n\n  /**\n   * Clones the style.\n   * @return {ImageStyle} The cloned style.\n   * @api\n   */\n  clone() {\n    const scale = this.getScale();\n    return new ImageStyle({\n      opacity: this.getOpacity(),\n      scale: Array.isArray(scale) ? scale.slice() : scale,\n      rotation: this.getRotation(),\n      rotateWithView: this.getRotateWithView(),\n      displacement: this.getDisplacement().slice(),\n      declutterMode: this.getDeclutterMode(),\n    });\n  }\n\n  /**\n   * Get the symbolizer opacity.\n   * @return {number} Opacity.\n   * @api\n   */\n  getOpacity() {\n    return this.opacity_;\n  }\n\n  /**\n   * Determine whether the symbolizer rotates with the map.\n   * @return {boolean} Rotate with map.\n   * @api\n   */\n  getRotateWithView() {\n    return this.rotateWithView_;\n  }\n\n  /**\n   * Get the symoblizer rotation.\n   * @return {number} Rotation.\n   * @api\n   */\n  getRotation() {\n    return this.rotation_;\n  }\n\n  /**\n   * Get the symbolizer scale.\n   * @return {number|import(\"../size.js\").Size} Scale.\n   * @api\n   */\n  getScale() {\n    return this.scale_;\n  }\n\n  /**\n   * Get the symbolizer scale array.\n   * @return {import(\"../size.js\").Size} Scale array.\n   */\n  getScaleArray() {\n    return this.scaleArray_;\n  }\n\n  /**\n   * Get the displacement of the shape\n   * @return {Array<number>} Shape's center displacement\n   * @api\n   */\n  getDisplacement() {\n    return this.displacement_;\n  }\n\n  /**\n   * Get the declutter mode of the shape\n   * @return {import(\"./Style.js\").DeclutterMode} Shape's declutter mode\n   * @api\n   */\n  getDeclutterMode() {\n    return this.declutterMode_;\n  }\n\n  /**\n   * Get the anchor point in pixels. The anchor determines the center point for the\n   * symbolizer.\n   * @abstract\n   * @return {Array<number>} Anchor.\n   */\n  getAnchor() {\n    return abstract();\n  }\n\n  /**\n   * Get the image element for the symbolizer.\n   * @abstract\n   * @param {number} pixelRatio Pixel ratio.\n   * @return {import('../DataTile.js').ImageLike} Image element.\n   */\n  getImage(pixelRatio) {\n    return abstract();\n  }\n\n  /**\n   * @abstract\n   * @return {import('../DataTile.js').ImageLike} Image element.\n   */\n  getHitDetectionImage() {\n    return abstract();\n  }\n\n  /**\n   * Get the image pixel ratio.\n   * @param {number} pixelRatio Pixel ratio.\n   * @return {number} Pixel ratio.\n   */\n  getPixelRatio(pixelRatio) {\n    return 1;\n  }\n\n  /**\n   * @abstract\n   * @return {import(\"../ImageState.js\").default} Image state.\n   */\n  getImageState() {\n    return abstract();\n  }\n\n  /**\n   * @abstract\n   * @return {import(\"../size.js\").Size} Image size.\n   */\n  getImageSize() {\n    return abstract();\n  }\n\n  /**\n   * Get the origin of the symbolizer.\n   * @abstract\n   * @return {Array<number>} Origin.\n   */\n  getOrigin() {\n    return abstract();\n  }\n\n  /**\n   * Get the size of the symbolizer (in pixels).\n   * @abstract\n   * @return {import(\"../size.js\").Size} Size.\n   */\n  getSize() {\n    return abstract();\n  }\n\n  /**\n   * Set the displacement.\n   *\n   * @param {Array<number>} displacement Displacement.\n   * @api\n   */\n  setDisplacement(displacement) {\n    this.displacement_ = displacement;\n  }\n\n  /**\n   * Set the opacity.\n   *\n   * @param {number} opacity Opacity.\n   * @api\n   */\n  setOpacity(opacity) {\n    this.opacity_ = opacity;\n  }\n\n  /**\n   * Set whether to rotate the style with the view.\n   *\n   * @param {boolean} rotateWithView Rotate with map.\n   * @api\n   */\n  setRotateWithView(rotateWithView) {\n    this.rotateWithView_ = rotateWithView;\n  }\n\n  /**\n   * Set the rotation.\n   *\n   * @param {number} rotation Rotation.\n   * @api\n   */\n  setRotation(rotation) {\n    this.rotation_ = rotation;\n  }\n\n  /**\n   * Set the scale.\n   *\n   * @param {number|import(\"../size.js\").Size} scale Scale.\n   * @api\n   */\n  setScale(scale) {\n    this.scale_ = scale;\n    this.scaleArray_ = toSize(scale);\n  }\n\n  /**\n   * @abstract\n   * @param {function(import(\"../events/Event.js\").default): void} listener Listener function.\n   */\n  listenImageChange(listener) {\n    abstract();\n  }\n\n  /**\n   * Load not yet loaded URI.\n   * @abstract\n   */\n  load() {\n    abstract();\n  }\n\n  /**\n   * @abstract\n   * @param {function(import(\"../events/Event.js\").default): void} listener Listener function.\n   */\n  unlistenImageChange(listener) {\n    abstract();\n  }\n\n  /**\n   * @return {Promise<void>} `false` or Promise that resolves when the style is ready to use.\n   */\n  ready() {\n    return Promise.resolve();\n  }\n}\n\nexport default ImageStyle;\n", "/**\n * @module ol/style/RegularShape\n */\n\nimport ImageState from '../ImageState.js';\nimport {asArray} from '../color.js';\nimport {asColorLike} from '../colorlike.js';\nimport {createCanvasContext2D} from '../dom.js';\nimport {\n  defaultFillStyle,\n  defaultLineCap,\n  defaultLineJoin,\n  defaultLineWidth,\n  defaultMiterLimit,\n  defaultStrokeStyle,\n} from '../render/canvas.js';\nimport IconImage from './IconImage.js';\nimport {shared as iconImageCache} from './IconImageCache.js';\nimport ImageStyle from './Image.js';\n\n/**\n * Specify radius for regular polygons, or both radius and radius2 for stars.\n * @typedef {Object} Options\n * @property {import(\"./Fill.js\").default} [fill] Fill style.\n * @property {number} points Number of points for stars and regular polygons. In case of a polygon, the number of points\n * is the number of sides.\n * @property {number} radius Radius of a regular polygon.\n * @property {number} [radius2] Second radius to make a star instead of a regular polygon.\n * @property {number} [angle=0] Shape's angle in radians. A value of 0 will have one of the shape's points facing up.\n * @property {Array<number>} [displacement=[0, 0]] Displacement of the shape in pixels.\n * Positive values will shift the shape right and up.\n * @property {import(\"./Stroke.js\").default} [stroke] Stroke style.\n * @property {number} [rotation=0] Rotation in radians (positive rotation clockwise).\n * @property {boolean} [rotateWithView=false] Whether to rotate the shape with the view.\n * @property {number|import(\"../size.js\").Size} [scale=1] Scale. Unless two dimensional scaling is required a better\n * result may be obtained with appropriate settings for `radius` and `radius2`.\n * @property {import('./Style.js').DeclutterMode} [declutterMode] Declutter mode.\n */\n\n/**\n * @typedef {Object} RenderOptions\n * @property {import(\"../colorlike.js\").ColorLike|undefined} strokeStyle StrokeStyle.\n * @property {number} strokeWidth StrokeWidth.\n * @property {number} size Size.\n * @property {CanvasLineCap} lineCap LineCap.\n * @property {Array<number>|null} lineDash LineDash.\n * @property {number} lineDashOffset LineDashOffset.\n * @property {CanvasLineJoin} lineJoin LineJoin.\n * @property {number} miterLimit MiterLimit.\n */\n\n/**\n * @classdesc\n * Set regular shape style for vector features. The resulting shape will be\n * a regular polygon when `radius` is provided, or a star when both `radius` and\n * `radius2` are provided.\n * @api\n */\nclass RegularShape extends ImageStyle {\n  /**\n   * @param {Options} options Options.\n   */\n  constructor(options) {\n    super({\n      opacity: 1,\n      rotateWithView:\n        options.rotateWithView !== undefined ? options.rotateWithView : false,\n      rotation: options.rotation !== undefined ? options.rotation : 0,\n      scale: options.scale !== undefined ? options.scale : 1,\n      displacement:\n        options.displacement !== undefined ? options.displacement : [0, 0],\n      declutterMode: options.declutterMode,\n    });\n\n    /**\n     * @private\n     * @type {HTMLCanvasElement|OffscreenCanvas|null}\n     */\n    this.hitDetectionCanvas_ = null;\n\n    /**\n     * @private\n     * @type {import(\"./Fill.js\").default|null}\n     */\n    this.fill_ = options.fill !== undefined ? options.fill : null;\n\n    /**\n     * @private\n     * @type {Array<number>}\n     */\n    this.origin_ = [0, 0];\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.points_ = options.points;\n\n    /**\n     * @protected\n     * @type {number}\n     */\n    this.radius = options.radius;\n\n    /**\n     * @private\n     * @type {number|undefined}\n     */\n    this.radius2_ = options.radius2;\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.angle_ = options.angle !== undefined ? options.angle : 0;\n\n    /**\n     * @private\n     * @type {import(\"./Stroke.js\").default|null}\n     */\n    this.stroke_ = options.stroke !== undefined ? options.stroke : null;\n\n    /**\n     * @private\n     * @type {import(\"../size.js\").Size}\n     */\n    this.size_;\n\n    /**\n     * @private\n     * @type {RenderOptions}\n     */\n    this.renderOptions_;\n\n    /**\n     * @private\n     */\n    this.imageState_ =\n      this.fill_ && this.fill_.loading()\n        ? ImageState.LOADING\n        : ImageState.LOADED;\n    if (this.imageState_ === ImageState.LOADING) {\n      this.ready().then(() => (this.imageState_ = ImageState.LOADED));\n    }\n    this.render();\n  }\n\n  /**\n   * Clones the style.\n   * @return {RegularShape} The cloned style.\n   * @api\n   * @override\n   */\n  clone() {\n    const scale = this.getScale();\n    const style = new RegularShape({\n      fill: this.getFill() ? this.getFill().clone() : undefined,\n      points: this.getPoints(),\n      radius: this.getRadius(),\n      radius2: this.getRadius2(),\n      angle: this.getAngle(),\n      stroke: this.getStroke() ? this.getStroke().clone() : undefined,\n      rotation: this.getRotation(),\n      rotateWithView: this.getRotateWithView(),\n      scale: Array.isArray(scale) ? scale.slice() : scale,\n      displacement: this.getDisplacement().slice(),\n      declutterMode: this.getDeclutterMode(),\n    });\n    style.setOpacity(this.getOpacity());\n    return style;\n  }\n\n  /**\n   * Get the anchor point in pixels. The anchor determines the center point for the\n   * symbolizer.\n   * @return {Array<number>} Anchor.\n   * @api\n   * @override\n   */\n  getAnchor() {\n    const size = this.size_;\n    const displacement = this.getDisplacement();\n    const scale = this.getScaleArray();\n    // anchor is scaled by renderer but displacement should not be scaled\n    // so divide by scale here\n    return [\n      size[0] / 2 - displacement[0] / scale[0],\n      size[1] / 2 + displacement[1] / scale[1],\n    ];\n  }\n\n  /**\n   * Get the angle used in generating the shape.\n   * @return {number} Shape's rotation in radians.\n   * @api\n   */\n  getAngle() {\n    return this.angle_;\n  }\n\n  /**\n   * Get the fill style for the shape.\n   * @return {import(\"./Fill.js\").default|null} Fill style.\n   * @api\n   */\n  getFill() {\n    return this.fill_;\n  }\n\n  /**\n   * Set the fill style.\n   * @param {import(\"./Fill.js\").default|null} fill Fill style.\n   * @api\n   */\n  setFill(fill) {\n    this.fill_ = fill;\n    this.render();\n  }\n\n  /**\n   * @return {HTMLCanvasElement|OffscreenCanvas} Image element.\n   * @override\n   */\n  getHitDetectionImage() {\n    if (!this.hitDetectionCanvas_) {\n      this.hitDetectionCanvas_ = this.createHitDetectionCanvas_(\n        this.renderOptions_,\n      );\n    }\n    return this.hitDetectionCanvas_;\n  }\n\n  /**\n   * Get the image icon.\n   * @param {number} pixelRatio Pixel ratio.\n   * @return {HTMLCanvasElement|OffscreenCanvas} Image or Canvas element.\n   * @api\n   * @override\n   */\n  getImage(pixelRatio) {\n    const fillKey = this.fill_?.getKey();\n    const cacheKey =\n      `${pixelRatio},${this.angle_},${this.radius},${this.radius2_},${this.points_},${fillKey}` +\n      Object.values(this.renderOptions_).join(',');\n    let image = /** @type {HTMLCanvasElement|OffscreenCanvas} */ (\n      iconImageCache.get(cacheKey, null)?.getImage(1)\n    );\n    if (!image) {\n      const renderOptions = this.renderOptions_;\n      const size = Math.ceil(renderOptions.size * pixelRatio);\n      const context = createCanvasContext2D(size, size);\n      this.draw_(renderOptions, context, pixelRatio);\n\n      image = context.canvas;\n      const iconImage = new IconImage(\n        image,\n        undefined,\n        null,\n        ImageState.LOADED,\n        null,\n      );\n      iconImageCache.set(cacheKey, null, iconImage);\n      // Update the image in place to an ImageBitmap for better performance and lower memory usage\n      createImageBitmap(image).then((imageBitmap) => {\n        iconImage.setImage(imageBitmap);\n      });\n    }\n    return image;\n  }\n\n  /**\n   * Get the image pixel ratio.\n   * @param {number} pixelRatio Pixel ratio.\n   * @return {number} Pixel ratio.\n   * @override\n   */\n  getPixelRatio(pixelRatio) {\n    return pixelRatio;\n  }\n\n  /**\n   * @return {import(\"../size.js\").Size} Image size.\n   * @override\n   */\n  getImageSize() {\n    return this.size_;\n  }\n\n  /**\n   * @return {import(\"../ImageState.js\").default} Image state.\n   * @override\n   */\n  getImageState() {\n    return this.imageState_;\n  }\n\n  /**\n   * Get the origin of the symbolizer.\n   * @return {Array<number>} Origin.\n   * @api\n   * @override\n   */\n  getOrigin() {\n    return this.origin_;\n  }\n\n  /**\n   * Get the number of points for generating the shape.\n   * @return {number} Number of points for stars and regular polygons.\n   * @api\n   */\n  getPoints() {\n    return this.points_;\n  }\n\n  /**\n   * Get the (primary) radius for the shape.\n   * @return {number} Radius.\n   * @api\n   */\n  getRadius() {\n    return this.radius;\n  }\n\n  /**\n   * Set the (primary) radius for the shape.\n   * @param {number} radius Radius.\n   * @api\n   */\n  setRadius(radius) {\n    if (this.radius === radius) {\n      return;\n    }\n    this.radius = radius;\n    this.render();\n  }\n\n  /**\n   * Get the secondary radius for the shape.\n   * @return {number|undefined} Radius2.\n   * @api\n   */\n  getRadius2() {\n    return this.radius2_;\n  }\n\n  /**\n   * Set the secondary radius for the shape.\n   * @param {number|undefined} radius2 Radius2.\n   * @api\n   */\n  setRadius2(radius2) {\n    if (this.radius2_ === radius2) {\n      return;\n    }\n    this.radius2_ = radius2;\n    this.render();\n  }\n\n  /**\n   * Get the size of the symbolizer (in pixels).\n   * @return {import(\"../size.js\").Size} Size.\n   * @api\n   * @override\n   */\n  getSize() {\n    return this.size_;\n  }\n\n  /**\n   * Get the stroke style for the shape.\n   * @return {import(\"./Stroke.js\").default|null} Stroke style.\n   * @api\n   */\n  getStroke() {\n    return this.stroke_;\n  }\n\n  /**\n   * Set the stroke style.\n   * @param {import(\"./Stroke.js\").default|null} stroke Stroke style.\n   * @api\n   */\n  setStroke(stroke) {\n    this.stroke_ = stroke;\n    this.render();\n  }\n\n  /**\n   * @param {function(import(\"../events/Event.js\").default): void} listener Listener function.\n   * @override\n   */\n  listenImageChange(listener) {}\n\n  /**\n   * Load not yet loaded URI.\n   * @override\n   */\n  load() {}\n\n  /**\n   * @param {function(import(\"../events/Event.js\").default): void} listener Listener function.\n   * @override\n   */\n  unlistenImageChange(listener) {}\n\n  /**\n   * Calculate additional canvas size needed for the miter.\n   * @param {string} lineJoin Line join\n   * @param {number} strokeWidth Stroke width\n   * @param {number} miterLimit Miter limit\n   * @return {number} Additional canvas size needed\n   * @private\n   */\n  calculateLineJoinSize_(lineJoin, strokeWidth, miterLimit) {\n    if (\n      strokeWidth === 0 ||\n      this.points_ === Infinity ||\n      (lineJoin !== 'bevel' && lineJoin !== 'miter')\n    ) {\n      return strokeWidth;\n    }\n    // m  | ^\n    // i  | |\\                  .\n    // t >|  #\\\n    // e  | |\\ \\              .\n    // r      \\s\\\n    //      |  \\t\\          .                 .\n    //          \\r\\                      .   .\n    //      |    \\o\\      .          .  . . .\n    //          e \\k\\            .  .    . .\n    //      |      \\e\\  .    .  .       . .\n    //       d      \\ \\  .  .          . .\n    //      | _ _a_ _\\#  .            . .\n    //   r1          / `             . .\n    //      |                       . .\n    //       b     /               . .\n    //      |                     . .\n    //           / r2            . .\n    //      |                        .   .\n    //         /                           .   .\n    //      |\u03B1                                   .   .\n    //       /                                         .   .\n    //      \u00B0 center\n    let r1 = this.radius;\n    let r2 = this.radius2_ === undefined ? r1 : this.radius2_;\n    if (r1 < r2) {\n      const tmp = r1;\n      r1 = r2;\n      r2 = tmp;\n    }\n    const points =\n      this.radius2_ === undefined ? this.points_ : this.points_ * 2;\n    const alpha = (2 * Math.PI) / points;\n    const a = r2 * Math.sin(alpha);\n    const b = Math.sqrt(r2 * r2 - a * a);\n    const d = r1 - b;\n    const e = Math.sqrt(a * a + d * d);\n    const miterRatio = e / a;\n    if (lineJoin === 'miter' && miterRatio <= miterLimit) {\n      return miterRatio * strokeWidth;\n    }\n    // Calculate the distance from center to the stroke corner where\n    // it was cut short because of the miter limit.\n    //              l\n    //        ----+---- <= distance from center to here is maxr\n    //       /####|k ##\\\n    //      /#####^#####\\\n    //     /#### /+\\# s #\\\n    //    /### h/+++\\# t #\\\n    //   /### t/+++++\\# r #\\\n    //  /### a/+++++++\\# o #\\\n    // /### p/++ fill +\\# k #\\\n    ///#### /+++++^+++++\\# e #\\\n    //#####/+++++/+\\+++++\\#####\\\n    const k = strokeWidth / 2 / miterRatio;\n    const l = (strokeWidth / 2) * (d / e);\n    const maxr = Math.sqrt((r1 + k) * (r1 + k) + l * l);\n    const bevelAdd = maxr - r1;\n    if (this.radius2_ === undefined || lineJoin === 'bevel') {\n      return bevelAdd * 2;\n    }\n    // If outer miter is over the miter limit the inner miter may reach through the\n    // center and be longer than the bevel, same calculation as above but swap r1 / r2.\n    const aa = r1 * Math.sin(alpha);\n    const bb = Math.sqrt(r1 * r1 - aa * aa);\n    const dd = r2 - bb;\n    const ee = Math.sqrt(aa * aa + dd * dd);\n    const innerMiterRatio = ee / aa;\n    if (innerMiterRatio <= miterLimit) {\n      const innerLength = (innerMiterRatio * strokeWidth) / 2 - r2 - r1;\n      return 2 * Math.max(bevelAdd, innerLength);\n    }\n    return bevelAdd * 2;\n  }\n\n  /**\n   * @return {RenderOptions}  The render options\n   * @protected\n   */\n  createRenderOptions() {\n    let lineCap = defaultLineCap;\n    let lineJoin = defaultLineJoin;\n    let miterLimit = 0;\n    let lineDash = null;\n    let lineDashOffset = 0;\n    let strokeStyle;\n    let strokeWidth = 0;\n\n    if (this.stroke_) {\n      strokeStyle = asColorLike(this.stroke_.getColor() ?? defaultStrokeStyle);\n      strokeWidth = this.stroke_.getWidth() ?? defaultLineWidth;\n      lineDash = this.stroke_.getLineDash();\n      lineDashOffset = this.stroke_.getLineDashOffset() ?? 0;\n      lineJoin = this.stroke_.getLineJoin() ?? defaultLineJoin;\n      lineCap = this.stroke_.getLineCap() ?? defaultLineCap;\n      miterLimit = this.stroke_.getMiterLimit() ?? defaultMiterLimit;\n    }\n\n    const add = this.calculateLineJoinSize_(lineJoin, strokeWidth, miterLimit);\n    const maxRadius = Math.max(this.radius, this.radius2_ || 0);\n    const size = Math.ceil(2 * maxRadius + add);\n\n    return {\n      strokeStyle: strokeStyle,\n      strokeWidth: strokeWidth,\n      size: size,\n      lineCap: lineCap,\n      lineDash: lineDash,\n      lineDashOffset: lineDashOffset,\n      lineJoin: lineJoin,\n      miterLimit: miterLimit,\n    };\n  }\n\n  /**\n   * @protected\n   */\n  render() {\n    this.renderOptions_ = this.createRenderOptions();\n    const size = this.renderOptions_.size;\n    this.hitDetectionCanvas_ = null;\n    this.size_ = [size, size];\n  }\n\n  /**\n   * @private\n   * @param {RenderOptions} renderOptions Render options.\n   * @param {CanvasRenderingContext2D|OffscreenCanvasRenderingContext2D} context The rendering context.\n   * @param {number} pixelRatio The pixel ratio.\n   */\n  draw_(renderOptions, context, pixelRatio) {\n    context.scale(pixelRatio, pixelRatio);\n    // set origin to canvas center\n    context.translate(renderOptions.size / 2, renderOptions.size / 2);\n\n    this.createPath_(context);\n\n    if (this.fill_) {\n      let color = this.fill_.getColor();\n      if (color === null) {\n        color = defaultFillStyle;\n      }\n      context.fillStyle = asColorLike(color);\n      context.fill();\n    }\n    if (renderOptions.strokeStyle) {\n      context.strokeStyle = renderOptions.strokeStyle;\n      context.lineWidth = renderOptions.strokeWidth;\n      if (renderOptions.lineDash) {\n        context.setLineDash(renderOptions.lineDash);\n        context.lineDashOffset = renderOptions.lineDashOffset;\n      }\n      context.lineCap = renderOptions.lineCap;\n      context.lineJoin = renderOptions.lineJoin;\n      context.miterLimit = renderOptions.miterLimit;\n      context.stroke();\n    }\n  }\n\n  /**\n   * @private\n   * @param {RenderOptions} renderOptions Render options.\n   * @return {HTMLCanvasElement|OffscreenCanvas} Canvas containing the icon\n   */\n  createHitDetectionCanvas_(renderOptions) {\n    let context;\n    if (this.fill_) {\n      let color = this.fill_.getColor();\n\n      // determine if fill is transparent (or pattern or gradient)\n      let opacity = 0;\n      if (typeof color === 'string') {\n        color = asArray(color);\n      }\n      if (color === null) {\n        opacity = 1;\n      } else if (Array.isArray(color)) {\n        opacity = color.length === 4 ? color[3] : 1;\n      }\n      if (opacity === 0) {\n        // if a transparent fill style is set, create an extra hit-detection image\n        // with a default fill style\n        context = createCanvasContext2D(renderOptions.size, renderOptions.size);\n        this.drawHitDetectionCanvas_(renderOptions, context);\n      }\n    }\n    return context ? context.canvas : this.getImage(1);\n  }\n\n  /**\n   * @private\n   * @param {CanvasRenderingContext2D|OffscreenCanvasRenderingContext2D} context The context to draw in.\n   */\n  createPath_(context) {\n    let points = this.points_;\n    const radius = this.radius;\n    if (points === Infinity) {\n      context.arc(0, 0, radius, 0, 2 * Math.PI);\n    } else {\n      const radius2 = this.radius2_ === undefined ? radius : this.radius2_;\n      if (this.radius2_ !== undefined) {\n        points *= 2;\n      }\n      const startAngle = this.angle_ - Math.PI / 2;\n      const step = (2 * Math.PI) / points;\n      for (let i = 0; i < points; i++) {\n        const angle0 = startAngle + i * step;\n        const radiusC = i % 2 === 0 ? radius : radius2;\n        context.lineTo(radiusC * Math.cos(angle0), radiusC * Math.sin(angle0));\n      }\n      context.closePath();\n    }\n  }\n\n  /**\n   * @private\n   * @param {RenderOptions} renderOptions Render options.\n   * @param {CanvasRenderingContext2D|OffscreenCanvasRenderingContext2D} context The context.\n   */\n  drawHitDetectionCanvas_(renderOptions, context) {\n    // set origin to canvas center\n    context.translate(renderOptions.size / 2, renderOptions.size / 2);\n\n    this.createPath_(context);\n\n    context.fillStyle = defaultFillStyle;\n    context.fill();\n    if (renderOptions.strokeStyle) {\n      context.strokeStyle = renderOptions.strokeStyle;\n      context.lineWidth = renderOptions.strokeWidth;\n      if (renderOptions.lineDash) {\n        context.setLineDash(renderOptions.lineDash);\n        context.lineDashOffset = renderOptions.lineDashOffset;\n      }\n      context.lineJoin = renderOptions.lineJoin;\n      context.miterLimit = renderOptions.miterLimit;\n      context.stroke();\n    }\n  }\n\n  /**\n   * @override\n   */\n  ready() {\n    return this.fill_ ? this.fill_.ready() : Promise.resolve();\n  }\n}\n\nexport default RegularShape;\n", "/**\n * @module ol/style/Circle\n */\n\nimport RegularShape from './RegularShape.js';\n\n/**\n * @typedef {Object} Options\n * @property {import(\"./Fill.js\").default} [fill] Fill style.\n * @property {number} radius Circle radius.\n * @property {import(\"./Stroke.js\").default} [stroke] Stroke style.\n * @property {Array<number>} [displacement=[0,0]] displacement\n * @property {number|import(\"../size.js\").Size} [scale=1] Scale. A two dimensional scale will produce an ellipse.\n * Unless two dimensional scaling is required a better result may be obtained with an appropriate setting for `radius`.\n * @property {number} [rotation=0] Rotation in radians\n * (positive rotation clockwise, meaningful only when used in conjunction with a two dimensional scale).\n * @property {boolean} [rotateWithView=false] Whether to rotate the shape with the view\n * (meaningful only when used in conjunction with a two dimensional scale).\n * @property {import('./Style.js').DeclutterMode} [declutterMode] Declutter mode\n */\n\n/**\n * @classdesc\n * Set circle style for vector features.\n * @api\n */\nclass CircleStyle extends RegularShape {\n  /**\n   * @param {Options} [options] Options.\n   */\n  constructor(options) {\n    options = options ? options : {radius: 5};\n\n    super({\n      points: Infinity,\n      fill: options.fill,\n      radius: options.radius,\n      stroke: options.stroke,\n      scale: options.scale !== undefined ? options.scale : 1,\n      rotation: options.rotation !== undefined ? options.rotation : 0,\n      rotateWithView:\n        options.rotateWithView !== undefined ? options.rotateWithView : false,\n      displacement:\n        options.displacement !== undefined ? options.displacement : [0, 0],\n      declutterMode: options.declutterMode,\n    });\n  }\n\n  /**\n   * Clones the style.\n   * @return {CircleStyle} The cloned style.\n   * @api\n   * @override\n   */\n  clone() {\n    const scale = this.getScale();\n    const style = new CircleStyle({\n      fill: this.getFill() ? this.getFill().clone() : undefined,\n      stroke: this.getStroke() ? this.getStroke().clone() : undefined,\n      radius: this.getRadius(),\n      scale: Array.isArray(scale) ? scale.slice() : scale,\n      rotation: this.getRotation(),\n      rotateWithView: this.getRotateWithView(),\n      displacement: this.getDisplacement().slice(),\n      declutterMode: this.getDeclutterMode(),\n    });\n    style.setOpacity(this.getOpacity());\n    return style;\n  }\n}\n\nexport default CircleStyle;\n", "/**\n * @module ol/style/Fill\n */\n\nimport ImageState from '../ImageState.js';\nimport {asArray} from '../color.js';\nimport {getUid} from '../util.js';\nimport {get as getIconImage} from './IconImage.js';\n\n/**\n * @typedef {Object} Options\n * @property {import(\"../color.js\").Color|import(\"../colorlike.js\").ColorLike|import('../colorlike.js').PatternDescriptor|null} [color=null] A color,\n * gradient or pattern.\n * See {@link module:ol/color~Color} and {@link module:ol/colorlike~ColorLike} for possible formats. For polygon fills (not for {@link import(\"./RegularShape.js\").default} fills),\n * a pattern can also be provided as {@link module:ol/colorlike~PatternDescriptor}.\n * Default null; if null, the Canvas/renderer default black will be used.\n */\n\n/**\n * @classdesc\n * Set fill style for vector features.\n * @api\n */\nclass Fill {\n  /**\n   * @param {Options} [options] Options.\n   */\n  constructor(options) {\n    options = options || {};\n\n    /**\n     * @private\n     * @type {import(\"./IconImage.js\").default|null}\n     */\n    this.patternImage_ = null;\n\n    /**\n     * @private\n     * @type {import(\"../color.js\").Color|import(\"../colorlike.js\").ColorLike|import('../colorlike.js').PatternDescriptor|null}\n     */\n    this.color_ = null;\n    if (options.color !== undefined) {\n      this.setColor(options.color);\n    }\n  }\n\n  /**\n   * Clones the style. The color is not cloned if it is a {@link module:ol/colorlike~ColorLike}.\n   * @return {Fill} The cloned style.\n   * @api\n   */\n  clone() {\n    const color = this.getColor();\n    return new Fill({\n      color: Array.isArray(color) ? color.slice() : color || undefined,\n    });\n  }\n\n  /**\n   * Get the fill color.\n   * @return {import(\"../color.js\").Color|import(\"../colorlike.js\").ColorLike|import('../colorlike.js').PatternDescriptor|null} Color.\n   * @api\n   */\n  getColor() {\n    return this.color_;\n  }\n\n  /**\n   * Set the color.\n   *\n   * @param {import(\"../color.js\").Color|import(\"../colorlike.js\").ColorLike|import('../colorlike.js').PatternDescriptor|null} color Color.\n   * @api\n   */\n  setColor(color) {\n    if (color !== null && typeof color === 'object' && 'src' in color) {\n      const patternImage = getIconImage(\n        null,\n        color.src,\n        {crossOrigin: 'anonymous'},\n        undefined,\n        color.offset ? null : color.color ? color.color : null,\n        !(color.offset && color.size),\n      );\n      patternImage.ready().then(() => {\n        this.patternImage_ = null;\n      });\n      if (patternImage.getImageState() === ImageState.IDLE) {\n        patternImage.load();\n      }\n      if (patternImage.getImageState() === ImageState.LOADING) {\n        this.patternImage_ = patternImage;\n      }\n    }\n    this.color_ = color;\n  }\n\n  /**\n   * @return {string} Key of the fill for cache lookup.\n   */\n  getKey() {\n    const fill = this.getColor();\n    if (!fill) {\n      return '';\n    }\n    return fill instanceof CanvasPattern || fill instanceof CanvasGradient\n      ? getUid(fill)\n      : typeof fill === 'object' && 'src' in fill\n        ? fill.src + ':' + fill.offset\n        : asArray(fill).toString();\n  }\n\n  /**\n   * @return {boolean} The fill style is loading an image pattern.\n   */\n  loading() {\n    return !!this.patternImage_;\n  }\n\n  /**\n   * @return {Promise<void>} `false` or a promise that resolves when the style is ready to use.\n   */\n  ready() {\n    return this.patternImage_ ? this.patternImage_.ready() : Promise.resolve();\n  }\n}\n\nexport default Fill;\n", "/**\n * @module ol/style/Icon\n */\nimport ImageState from '../ImageState.js';\nimport {assert} from '../asserts.js';\nimport {asArray} from '../color.js';\nimport EventType from '../events/EventType.js';\nimport {getUid} from '../util.js';\nimport {get as getIconImage} from './IconImage.js';\nimport ImageStyle from './Image.js';\n\n/**\n * @typedef {'fraction' | 'pixels'} IconAnchorUnits\n * Anchor unit can be either a fraction of the icon size or in pixels.\n */\n\n/**\n * @typedef {'bottom-left' | 'bottom-right' | 'top-left' | 'top-right'} IconOrigin\n * Icon origin. One of 'bottom-left', 'bottom-right', 'top-left', 'top-right'.\n */\n\n/**\n * @typedef {Object} Options\n * @property {Array<number>} [anchor=[0.5, 0.5]] Anchor. Default value is the icon center.\n * @property {IconOrigin} [anchorOrigin='top-left'] Origin of the anchor: `bottom-left`, `bottom-right`,\n * `top-left` or `top-right`.\n * @property {IconAnchorUnits} [anchorXUnits='fraction'] Units in which the anchor x value is\n * specified. A value of `'fraction'` indicates the x value is a fraction of the icon. A value of `'pixels'` indicates\n * the x value in pixels.\n * @property {IconAnchorUnits} [anchorYUnits='fraction'] Units in which the anchor y value is\n * specified. A value of `'fraction'` indicates the y value is a fraction of the icon. A value of `'pixels'` indicates\n * the y value in pixels.\n * @property {import(\"../color.js\").Color|string} [color] Color to tint the icon. If not specified,\n * the icon will be left as is.\n * @property {null|string} [crossOrigin] The `crossOrigin` attribute for loaded images. Note that you must provide a\n * `crossOrigin` value if you want to access pixel data with the Canvas renderer.\n * See https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image for more detail.\n * @property {ReferrerPolicy} [referrerPolicy] The `referrerPolicy` property for loaded images.\n * @property {HTMLImageElement|HTMLCanvasElement|OffscreenCanvas|ImageBitmap} [img] Image object for the icon.\n * @property {Array<number>} [displacement=[0, 0]] Displacement of the icon in pixels.\n * Positive values will shift the icon right and up.\n * @property {number} [opacity=1] Opacity of the icon.\n * @property {number} [width] The width of the icon in pixels. This can't be used together with `scale`.\n * @property {number} [height] The height of the icon in pixels. This can't be used together with `scale`.\n * @property {number|import(\"../size.js\").Size} [scale=1] Scale.\n * @property {boolean} [rotateWithView=false] Whether to rotate the icon with the view.\n * @property {number} [rotation=0] Rotation in radians (positive rotation clockwise).\n * @property {Array<number>} [offset=[0, 0]] Offset which, together with `size` and `offsetOrigin`, defines the\n * sub-rectangle to use from the original (sprite) image.\n * @property {IconOrigin} [offsetOrigin='top-left'] Origin of the offset: `bottom-left`, `bottom-right`,\n * `top-left` or `top-right`.\n * @property {import(\"../size.js\").Size} [size] Icon size in pixels. Used together with `offset` to define the\n * sub-rectangle to use from the original (sprite) image.\n * @property {string} [src] Image source URI.\n * @property {import(\"./Style.js\").DeclutterMode} [declutterMode] Declutter mode.\n */\n\n/**\n * @param {number} width The width.\n * @param {number} height The height.\n * @param {number|undefined} wantedWidth The wanted width.\n * @param {number|undefined} wantedHeight The wanted height.\n * @return {number|Array<number>} The scale.\n */\nfunction calculateScale(width, height, wantedWidth, wantedHeight) {\n  if (wantedWidth !== undefined && wantedHeight !== undefined) {\n    return [wantedWidth / width, wantedHeight / height];\n  }\n  if (wantedWidth !== undefined) {\n    return wantedWidth / width;\n  }\n  if (wantedHeight !== undefined) {\n    return wantedHeight / height;\n  }\n  return 1;\n}\n\n/**\n * @classdesc\n * Set icon style for vector features.\n * @api\n */\nclass Icon extends ImageStyle {\n  /**\n   * @param {Options} [options] Options.\n   */\n  constructor(options) {\n    options = options || {};\n\n    /**\n     * @type {number}\n     */\n    const opacity = options.opacity !== undefined ? options.opacity : 1;\n\n    /**\n     * @type {number}\n     */\n    const rotation = options.rotation !== undefined ? options.rotation : 0;\n\n    /**\n     * @type {number|import(\"../size.js\").Size}\n     */\n    const scale = options.scale !== undefined ? options.scale : 1;\n\n    /**\n     * @type {boolean}\n     */\n    const rotateWithView =\n      options.rotateWithView !== undefined ? options.rotateWithView : false;\n\n    super({\n      opacity: opacity,\n      rotation: rotation,\n      scale: scale,\n      displacement:\n        options.displacement !== undefined ? options.displacement : [0, 0],\n      rotateWithView: rotateWithView,\n      declutterMode: options.declutterMode,\n    });\n\n    /**\n     * @private\n     * @type {Array<number>}\n     */\n    this.anchor_ = options.anchor !== undefined ? options.anchor : [0.5, 0.5];\n\n    /**\n     * @private\n     * @type {Array<number>}\n     */\n    this.normalizedAnchor_ = null;\n\n    /**\n     * @private\n     * @type {IconOrigin}\n     */\n    this.anchorOrigin_ =\n      options.anchorOrigin !== undefined ? options.anchorOrigin : 'top-left';\n\n    /**\n     * @private\n     * @type {IconAnchorUnits}\n     */\n    this.anchorXUnits_ =\n      options.anchorXUnits !== undefined ? options.anchorXUnits : 'fraction';\n\n    /**\n     * @private\n     * @type {IconAnchorUnits}\n     */\n    this.anchorYUnits_ =\n      options.anchorYUnits !== undefined ? options.anchorYUnits : 'fraction';\n\n    /**\n     * @private\n     * @type {?string}\n     */\n    this.crossOrigin_ =\n      options.crossOrigin !== undefined ? options.crossOrigin : null;\n\n    /**\n     * @private\n     * @type {ReferrerPolicy}\n     */\n    this.referrerPolicy_ = options.referrerPolicy;\n\n    const image = options.img !== undefined ? options.img : null;\n\n    let cacheKey = options.src;\n\n    assert(\n      !(cacheKey !== undefined && image),\n      '`image` and `src` cannot be provided at the same time',\n    );\n\n    if ((cacheKey === undefined || cacheKey.length === 0) && image) {\n      cacheKey = /** @type {HTMLImageElement} */ (image).src || getUid(image);\n    }\n    assert(\n      cacheKey !== undefined && cacheKey.length > 0,\n      'A defined and non-empty `src` or `image` must be provided',\n    );\n\n    assert(\n      !(\n        (options.width !== undefined || options.height !== undefined) &&\n        options.scale !== undefined\n      ),\n      '`width` or `height` cannot be provided together with `scale`',\n    );\n\n    let imageState;\n    if (options.src !== undefined) {\n      imageState = ImageState.IDLE;\n    } else if (image !== undefined) {\n      if ('complete' in image) {\n        if (image.complete) {\n          imageState = image.src ? ImageState.LOADED : ImageState.IDLE;\n        } else {\n          imageState = ImageState.LOADING;\n        }\n      } else {\n        imageState = ImageState.LOADED;\n      }\n    }\n\n    /**\n     * @private\n     * @type {import(\"../color.js\").Color}\n     */\n    this.color_ = options.color !== undefined ? asArray(options.color) : null;\n\n    /**\n     * @private\n     * @type {import(\"./IconImage.js\").default}\n     */\n    this.iconImage_ = getIconImage(\n      image,\n      /** @type {string} */ (cacheKey),\n      {\n        crossOrigin: this.crossOrigin_,\n        referrerPolicy: this.referrerPolicy_,\n      },\n      imageState,\n      this.color_,\n    );\n\n    /**\n     * @private\n     * @type {Array<number>}\n     */\n    this.offset_ = options.offset !== undefined ? options.offset : [0, 0];\n    /**\n     * @private\n     * @type {IconOrigin}\n     */\n    this.offsetOrigin_ =\n      options.offsetOrigin !== undefined ? options.offsetOrigin : 'top-left';\n\n    /**\n     * @private\n     * @type {Array<number>}\n     */\n    this.origin_ = null;\n\n    /**\n     * @private\n     * @type {import(\"../size.js\").Size}\n     */\n    this.size_ = options.size !== undefined ? options.size : null;\n\n    /**\n     * @private\n     */\n    this.initialOptions_;\n\n    /**\n     * Calculate the scale if width or height were given.\n     */\n    if (options.width !== undefined || options.height !== undefined) {\n      let width, height;\n      if (options.size) {\n        [width, height] = options.size;\n      } else {\n        const image = this.getImage(1);\n        if (image.width && image.height) {\n          width = image.width;\n          height = image.height;\n        } else if (image instanceof HTMLImageElement) {\n          this.initialOptions_ = options;\n          const onload = () => {\n            this.unlistenImageChange(onload);\n            if (!this.initialOptions_) {\n              return;\n            }\n            const imageSize = this.iconImage_.getSize();\n            this.setScale(\n              calculateScale(\n                imageSize[0],\n                imageSize[1],\n                options.width,\n                options.height,\n              ),\n            );\n          };\n          this.listenImageChange(onload);\n          return;\n        }\n      }\n      if (width !== undefined) {\n        this.setScale(\n          calculateScale(width, height, options.width, options.height),\n        );\n      }\n    }\n  }\n\n  /**\n   * Clones the style. The underlying Image/HTMLCanvasElement is not cloned.\n   * @return {Icon} The cloned style.\n   * @api\n   * @override\n   */\n  clone() {\n    let scale, width, height;\n    if (this.initialOptions_) {\n      width = this.initialOptions_.width;\n      height = this.initialOptions_.height;\n    } else {\n      scale = this.getScale();\n      scale = Array.isArray(scale) ? scale.slice() : scale;\n    }\n    return new Icon({\n      anchor: this.anchor_.slice(),\n      anchorOrigin: this.anchorOrigin_,\n      anchorXUnits: this.anchorXUnits_,\n      anchorYUnits: this.anchorYUnits_,\n      color:\n        this.color_ && this.color_.slice\n          ? this.color_.slice()\n          : this.color_ || undefined,\n      crossOrigin: this.crossOrigin_,\n      referrerPolicy: this.referrerPolicy_,\n      offset: this.offset_.slice(),\n      offsetOrigin: this.offsetOrigin_,\n      opacity: this.getOpacity(),\n      rotateWithView: this.getRotateWithView(),\n      rotation: this.getRotation(),\n      scale,\n      width,\n      height,\n      size: this.size_ !== null ? this.size_.slice() : undefined,\n      src: this.getSrc(),\n      displacement: this.getDisplacement().slice(),\n      declutterMode: this.getDeclutterMode(),\n    });\n  }\n\n  /**\n   * Get the anchor point in pixels. The anchor determines the center point for the\n   * symbolizer.\n   * @return {Array<number>} Anchor.\n   * @api\n   * @override\n   */\n  getAnchor() {\n    let anchor = this.normalizedAnchor_;\n    if (!anchor) {\n      anchor = this.anchor_;\n      const size = this.getSize();\n      if (\n        this.anchorXUnits_ == 'fraction' ||\n        this.anchorYUnits_ == 'fraction'\n      ) {\n        if (!size) {\n          return null;\n        }\n        anchor = this.anchor_.slice();\n        if (this.anchorXUnits_ == 'fraction') {\n          anchor[0] *= size[0];\n        }\n        if (this.anchorYUnits_ == 'fraction') {\n          anchor[1] *= size[1];\n        }\n      }\n\n      if (this.anchorOrigin_ != 'top-left') {\n        if (!size) {\n          return null;\n        }\n        if (anchor === this.anchor_) {\n          anchor = this.anchor_.slice();\n        }\n        if (\n          this.anchorOrigin_ == 'top-right' ||\n          this.anchorOrigin_ == 'bottom-right'\n        ) {\n          anchor[0] = -anchor[0] + size[0];\n        }\n        if (\n          this.anchorOrigin_ == 'bottom-left' ||\n          this.anchorOrigin_ == 'bottom-right'\n        ) {\n          anchor[1] = -anchor[1] + size[1];\n        }\n      }\n      this.normalizedAnchor_ = anchor;\n    }\n    const displacement = this.getDisplacement();\n    const scale = this.getScaleArray();\n    // anchor is scaled by renderer but displacement should not be scaled\n    // so divide by scale here\n    return [\n      anchor[0] - displacement[0] / scale[0],\n      anchor[1] + displacement[1] / scale[1],\n    ];\n  }\n\n  /**\n   * Set the anchor point. The anchor determines the center point for the\n   * symbolizer.\n   *\n   * @param {Array<number>} anchor Anchor.\n   * @api\n   */\n  setAnchor(anchor) {\n    this.anchor_ = anchor;\n    this.normalizedAnchor_ = null;\n  }\n\n  /**\n   * Get the icon color.\n   * @return {import(\"../color.js\").Color} Color.\n   * @api\n   */\n  getColor() {\n    return this.color_;\n  }\n\n  /**\n   * Set the icon color.\n   *\n   * Warning: Repeatedly setting the color on an icon style\n   * causes the icon image to be re-created each time. This can have a\n   * severe performance impact.\n   *\n   * @param {import(\"../color.js\").Color|string|null|undefined} color Color.\n   */\n  setColor(color) {\n    const nextColor = color ? asArray(color) : null;\n    if (\n      this.color_ === nextColor ||\n      (this.color_ &&\n        nextColor &&\n        this.color_.length === nextColor.length &&\n        this.color_.every((value, index) => value === nextColor[index]))\n    ) {\n      // Discard if the color hasn't changed.\n      return;\n    }\n\n    this.color_ = nextColor;\n    const src = this.getSrc();\n    const image = src !== undefined ? null : this.getHitDetectionImage();\n    const imageState =\n      src !== undefined ? ImageState.IDLE : this.iconImage_.getImageState();\n    this.iconImage_ = getIconImage(\n      image,\n      src,\n      {\n        crossOrigin: this.crossOrigin_,\n        referrerPolicy: this.referrerPolicy_,\n      },\n      imageState,\n      this.color_,\n    );\n  }\n\n  /**\n   * Get the image icon.\n   * @param {number} pixelRatio Pixel ratio.\n   * @return {HTMLImageElement|HTMLCanvasElement|OffscreenCanvas|ImageBitmap} Image or Canvas element. If the Icon\n   * style was configured with `src` or with a not let loaded `img`, an `ImageBitmap` will be returned.\n   * @api\n   * @override\n   */\n  getImage(pixelRatio) {\n    return this.iconImage_.getImage(pixelRatio);\n  }\n\n  /**\n   * Get the pixel ratio.\n   * @param {number} pixelRatio Pixel ratio.\n   * @return {number} The pixel ratio of the image.\n   * @api\n   * @override\n   */\n  getPixelRatio(pixelRatio) {\n    return this.iconImage_.getPixelRatio(pixelRatio);\n  }\n\n  /**\n   * @return {import(\"../size.js\").Size} Image size.\n   * @override\n   */\n  getImageSize() {\n    return this.iconImage_.getSize();\n  }\n\n  /**\n   * @return {import(\"../ImageState.js\").default} Image state.\n   * @override\n   */\n  getImageState() {\n    return this.iconImage_.getImageState();\n  }\n\n  /**\n   * @return {HTMLImageElement|HTMLCanvasElement|OffscreenCanvas|ImageBitmap} Image element.\n   * @override\n   */\n  getHitDetectionImage() {\n    return this.iconImage_.getHitDetectionImage();\n  }\n\n  /**\n   * Get the origin of the symbolizer.\n   * @return {Array<number>} Origin.\n   * @api\n   * @override\n   */\n  getOrigin() {\n    if (this.origin_) {\n      return this.origin_;\n    }\n    let offset = this.offset_;\n\n    if (this.offsetOrigin_ != 'top-left') {\n      const size = this.getSize();\n      const iconImageSize = this.iconImage_.getSize();\n      if (!size || !iconImageSize) {\n        return null;\n      }\n      offset = offset.slice();\n      if (\n        this.offsetOrigin_ == 'top-right' ||\n        this.offsetOrigin_ == 'bottom-right'\n      ) {\n        offset[0] = iconImageSize[0] - size[0] - offset[0];\n      }\n      if (\n        this.offsetOrigin_ == 'bottom-left' ||\n        this.offsetOrigin_ == 'bottom-right'\n      ) {\n        offset[1] = iconImageSize[1] - size[1] - offset[1];\n      }\n    }\n    this.origin_ = offset;\n    return this.origin_;\n  }\n\n  /**\n   * Get the image URL.\n   * @return {string|undefined} Image src.\n   * @api\n   */\n  getSrc() {\n    return this.iconImage_.getSrc();\n  }\n\n  /**\n   * Set the image URI\n   * @param {string} src Image source URI\n   * @api\n   */\n  setSrc(src) {\n    this.iconImage_ = getIconImage(\n      null,\n      src,\n      {\n        crossOrigin: this.crossOrigin_,\n        referrerPolicy: this.referrerPolicy_,\n      },\n      ImageState.IDLE,\n      this.color_,\n    );\n  }\n\n  /**\n   * Get the size of the icon (in pixels).\n   * @return {import(\"../size.js\").Size} Image size.\n   * @api\n   * @override\n   */\n  getSize() {\n    return !this.size_ ? this.iconImage_.getSize() : this.size_;\n  }\n\n  /**\n   * Get the width of the icon (in pixels). Will return undefined when the icon image is not yet loaded.\n   * @return {number} Icon width (in pixels).\n   * @api\n   */\n  getWidth() {\n    const scale = this.getScaleArray();\n    if (this.size_) {\n      return this.size_[0] * scale[0];\n    }\n    if (this.iconImage_.getImageState() == ImageState.LOADED) {\n      return this.iconImage_.getSize()[0] * scale[0];\n    }\n    return undefined;\n  }\n\n  /**\n   * Get the height of the icon (in pixels). Will return undefined when the icon image is not yet loaded.\n   * @return {number} Icon height (in pixels).\n   * @api\n   */\n  getHeight() {\n    const scale = this.getScaleArray();\n    if (this.size_) {\n      return this.size_[1] * scale[1];\n    }\n    if (this.iconImage_.getImageState() == ImageState.LOADED) {\n      return this.iconImage_.getSize()[1] * scale[1];\n    }\n    return undefined;\n  }\n\n  /**\n   * Set the scale.\n   *\n   * @param {number|import(\"../size.js\").Size} scale Scale.\n   * @api\n   * @override\n   */\n  setScale(scale) {\n    delete this.initialOptions_;\n    super.setScale(scale);\n  }\n\n  /**\n   * @param {function(import(\"../events/Event.js\").default): void} listener Listener function.\n   * @override\n   */\n  listenImageChange(listener) {\n    this.iconImage_.addEventListener(EventType.CHANGE, listener);\n  }\n\n  /**\n   * Load not yet loaded URI.\n   * When rendering a feature with an icon style, the vector renderer will\n   * automatically call this method. However, you might want to call this\n   * method yourself for preloading or other purposes.\n   * @api\n   * @override\n   */\n  load() {\n    this.iconImage_.load();\n  }\n\n  /**\n   * @param {function(import(\"../events/Event.js\").default): void} listener Listener function.\n   * @override\n   */\n  unlistenImageChange(listener) {\n    this.iconImage_.removeEventListener(EventType.CHANGE, listener);\n  }\n\n  /**\n   * @override\n   */\n  ready() {\n    return this.iconImage_.ready();\n  }\n}\n\nexport default Icon;\n", "/**\n * @module ol/style/Stroke\n */\n\n/**\n * @typedef {Object} Options\n * @property {import(\"../color.js\").Color|import(\"../colorlike.js\").ColorLike} [color] A color, gradient or pattern.\n * See {@link module:ol/color~Color} and {@link module:ol/colorlike~ColorLike} for possible formats.\n * Default null; if null, the Canvas/renderer default black will be used.\n * @property {CanvasLineCap} [lineCap='round'] Line cap style: `butt`, `round`, or `square`.\n * @property {CanvasLineJoin} [lineJoin='round'] Line join style: `bevel`, `round`, or `miter`.\n * @property {Array<number>} [lineDash] Line dash pattern. Default is `null` (no dash).\n * @property {number} [lineDashOffset=0] Line dash offset.\n * @property {number} [miterLimit=10] Miter limit.\n * @property {number} [offset] Line offset in pixels along the normal. A positive value offsets the line to the right,\n * relative to the direction of the line. Default is `undefined` (no offset).\n * @property {number} [width] Width.\n */\n\n/**\n * @classdesc\n * Set stroke style for vector features.\n * Note that the defaults given are the Canvas defaults, which will be used if\n * option is not defined. The `get` functions return whatever was entered in\n * the options; they will not return the default.\n * @api\n */\nclass Stroke {\n  /**\n   * @param {Options} [options] Options.\n   */\n  constructor(options) {\n    options = options || {};\n\n    /**\n     * @private\n     * @type {import(\"../color.js\").Color|import(\"../colorlike.js\").ColorLike}\n     */\n    this.color_ = options.color !== undefined ? options.color : null;\n\n    /**\n     * @private\n     * @type {CanvasLineCap|undefined}\n     */\n    this.lineCap_ = options.lineCap;\n\n    /**\n     * @private\n     * @type {Array<number>|null}\n     */\n    this.lineDash_ = options.lineDash !== undefined ? options.lineDash : null;\n\n    /**\n     * @private\n     * @type {number|undefined}\n     */\n    this.lineDashOffset_ = options.lineDashOffset;\n\n    /**\n     * @private\n     * @type {CanvasLineJoin|undefined}\n     */\n    this.lineJoin_ = options.lineJoin;\n\n    /**\n     * @private\n     * @type {number|undefined}\n     */\n    this.miterLimit_ = options.miterLimit;\n\n    /**\n     * @private\n     * @type {number|undefined}\n     */\n    this.offset_ = options.offset;\n\n    /**\n     * @private\n     * @type {number|undefined}\n     */\n    this.width_ = options.width;\n  }\n\n  /**\n   * Clones the style.\n   * @return {Stroke} The cloned style.\n   * @api\n   */\n  clone() {\n    const color = this.getColor();\n    return new Stroke({\n      color: Array.isArray(color) ? color.slice() : color || undefined,\n      lineCap: this.getLineCap(),\n      lineDash: this.getLineDash() ? this.getLineDash().slice() : undefined,\n      lineDashOffset: this.getLineDashOffset(),\n      lineJoin: this.getLineJoin(),\n      miterLimit: this.getMiterLimit(),\n      offset: this.getOffset(),\n      width: this.getWidth(),\n    });\n  }\n\n  /**\n   * Get the stroke color.\n   * @return {import(\"../color.js\").Color|import(\"../colorlike.js\").ColorLike} Color.\n   * @api\n   */\n  getColor() {\n    return this.color_;\n  }\n\n  /**\n   * Get the line cap type for the stroke.\n   * @return {CanvasLineCap|undefined} Line cap.\n   * @api\n   */\n  getLineCap() {\n    return this.lineCap_;\n  }\n\n  /**\n   * Get the line dash style for the stroke.\n   * @return {Array<number>|null} Line dash.\n   * @api\n   */\n  getLineDash() {\n    return this.lineDash_;\n  }\n\n  /**\n   * Get the line dash offset for the stroke.\n   * @return {number|undefined} Line dash offset.\n   * @api\n   */\n  getLineDashOffset() {\n    return this.lineDashOffset_;\n  }\n\n  /**\n   * Get the line join type for the stroke.\n   * @return {CanvasLineJoin|undefined} Line join.\n   * @api\n   */\n  getLineJoin() {\n    return this.lineJoin_;\n  }\n\n  /**\n   * Get the miter limit for the stroke.\n   * @return {number|undefined} Miter limit.\n   * @api\n   */\n  getMiterLimit() {\n    return this.miterLimit_;\n  }\n\n  /**\n   * Get the line offset in pixels.\n   * @return {number|undefined} Offset.\n   * @api\n   */\n  getOffset() {\n    return this.offset_;\n  }\n\n  /**\n   * Get the stroke width.\n   * @return {number|undefined} Width.\n   * @api\n   */\n  getWidth() {\n    return this.width_;\n  }\n\n  /**\n   * Set the color.\n   *\n   * @param {import(\"../color.js\").Color|import(\"../colorlike.js\").ColorLike} color Color.\n   * @api\n   */\n  setColor(color) {\n    this.color_ = color;\n  }\n\n  /**\n   * Set the line cap.\n   *\n   * @param {CanvasLineCap|undefined} lineCap Line cap.\n   * @api\n   */\n  setLineCap(lineCap) {\n    this.lineCap_ = lineCap;\n  }\n\n  /**\n   * Set the line dash.\n   *\n   * @param {Array<number>|null} lineDash Line dash.\n   * @api\n   */\n  setLineDash(lineDash) {\n    this.lineDash_ = lineDash;\n  }\n\n  /**\n   * Set the line dash offset.\n   *\n   * @param {number|undefined} lineDashOffset Line dash offset.\n   * @api\n   */\n  setLineDashOffset(lineDashOffset) {\n    this.lineDashOffset_ = lineDashOffset;\n  }\n\n  /**\n   * Set the line join.\n   *\n   * @param {CanvasLineJoin|undefined} lineJoin Line join.\n   * @api\n   */\n  setLineJoin(lineJoin) {\n    this.lineJoin_ = lineJoin;\n  }\n\n  /**\n   * Set the miter limit.\n   *\n   * @param {number|undefined} miterLimit Miter limit.\n   * @api\n   */\n  setMiterLimit(miterLimit) {\n    this.miterLimit_ = miterLimit;\n  }\n\n  /**\n   * Set the line offset in pixels.\n   *\n   * @param {number|undefined} offset Offset.\n   * @api\n   */\n  setOffset(offset) {\n    this.offset_ = offset;\n  }\n\n  /**\n   * Set the width.\n   *\n   * @param {number|undefined} width Width.\n   * @api\n   */\n  setWidth(width) {\n    this.width_ = width;\n  }\n}\n\nexport default Stroke;\n", "/**\n * @module ol/style/Style\n */\n\nimport {assert} from '../asserts.js';\nimport CircleStyle from './Circle.js';\nimport Fill from './Fill.js';\nimport Stroke from './Stroke.js';\n\n/**\n * Defines how symbols and text are decluttered on layers ith `declutter` set to `true`\n * **declutter**: Overlapping symbols and text are decluttered.\n * **obstacle**: Symbols and text are rendered, but serve as obstacle for subsequent attempts\n *   to place a symbol or text at the same location.\n * **none**: No decluttering is done.\n *\n * @typedef {\"declutter\"|\"obstacle\"|\"none\"} DeclutterMode\n */\n\n/**\n * A function that takes a {@link module:ol/Feature~Feature} and a `{number}`\n * representing the view's resolution. The function should return a\n * {@link module:ol/style/Style~Style} or an array of them. This way e.g. a\n * vector layer can be styled. If the function returns `undefined`, the\n * feature will not be rendered.\n *\n * @typedef {function(import(\"../Feature.js\").FeatureLike, number):(Style|Array<Style>|void)} StyleFunction\n */\n\n/**\n * A {@link Style}, an array of {@link Style}, or a {@link StyleFunction}.\n * @typedef {Style|Array<Style>|StyleFunction} StyleLike\n */\n\n/**\n * A function that takes a {@link module:ol/Feature~Feature} as argument and returns an\n * {@link module:ol/geom/Geometry~Geometry} that will be rendered and styled for the feature.\n *\n * @typedef {function(import(\"../Feature.js\").FeatureLike):\n *     (import(\"../geom/Geometry.js\").default|import(\"../render/Feature.js\").default|undefined)} GeometryFunction\n */\n\n/**\n * Custom renderer function. Takes two arguments:\n *\n * 1. The pixel coordinates of the geometry in GeoJSON notation.\n * 2. The {@link module:ol/render~State} of the layer renderer.\n *\n * @typedef {function((import(\"../coordinate.js\").Coordinate|Array<import(\"../coordinate.js\").Coordinate>|Array<Array<import(\"../coordinate.js\").Coordinate>>|Array<Array<Array<import(\"../coordinate.js\").Coordinate>>>),import(\"../render.js\").State): void} RenderFunction\n */\n\n/**\n * @typedef {Object} Options\n * @property {string|import(\"../geom/Geometry.js\").default|GeometryFunction} [geometry] Feature property or geometry\n * or function returning a geometry to render for this style.\n * @property {import(\"./Fill.js\").default} [fill] Fill style.\n * @property {import(\"./Image.js\").default} [image] Image style.\n * @property {RenderFunction} [renderer] Custom renderer. When configured, `fill`, `stroke` and `image` will be\n * ignored, and the provided function will be called with each render frame for each geometry.\n * @property {RenderFunction} [hitDetectionRenderer] Custom renderer for hit detection. If provided will be used\n * in hit detection rendering.\n * @property {import(\"./Stroke.js\").default} [stroke] Stroke style.\n * @property {import(\"./Text.js\").default} [text] Text style.\n * @property {number} [zIndex] Z index.\n */\n\n/**\n * @classdesc\n * Container for vector feature rendering styles. Any changes made to the style\n * or its children through `set*()` methods will not take effect until the\n * feature or layer that uses the style is re-rendered.\n *\n * ## Feature styles\n *\n * If no style is defined, the following default style is used:\n * ```js\n *  import {Circle, Fill, Stroke, Style} from 'ol/style.js';\n *\n *  const fill = new Fill({\n *    color: 'rgba(255,255,255,0.4)',\n *  });\n *  const stroke = new Stroke({\n *    color: '#3399CC',\n *    width: 1.25,\n *  });\n *  const styles = [\n *    new Style({\n *      image: new Circle({\n *        fill: fill,\n *        stroke: stroke,\n *        radius: 5,\n *      }),\n *      fill: fill,\n *      stroke: stroke,\n *    }),\n *  ];\n * ```\n *\n * A separate editing style has the following defaults:\n * ```js\n *  import {Circle, Fill, Stroke, Style} from 'ol/style.js';\n *\n *  const styles = {};\n *  const white = [255, 255, 255, 1];\n *  const blue = [0, 153, 255, 1];\n *  const width = 3;\n *  styles['Polygon'] = [\n *    new Style({\n *      fill: new Fill({\n *        color: [255, 255, 255, 0.5],\n *      }),\n *    }),\n *  ];\n *  styles['MultiPolygon'] =\n *      styles['Polygon'];\n *  styles['LineString'] = [\n *    new Style({\n *      stroke: new Stroke({\n *        color: white,\n *        width: width + 2,\n *      }),\n *    }),\n *    new Style({\n *      stroke: new Stroke({\n *        color: blue,\n *        width: width,\n *      }),\n *    }),\n *  ];\n *  styles['MultiLineString'] = styles['LineString'];\n *\n *  styles['Circle'] = styles['Polygon'].concat(\n *    styles['LineString']\n *  );\n *\n *  styles['Point'] = [\n *    new Style({\n *      image: new Circle({\n *        radius: width * 2,\n *        fill: new Fill({\n *          color: blue,\n *        }),\n *        stroke: new Stroke({\n *          color: white,\n *          width: width / 2,\n *        }),\n *      }),\n *      zIndex: Infinity,\n *    }),\n *  ];\n *  styles['MultiPoint'] =\n *      styles['Point'];\n *  styles['GeometryCollection'] =\n *      styles['Polygon'].concat(\n *          styles['LineString'],\n *          styles['Point']\n *      );\n * ```\n *\n * @api\n */\nclass Style {\n  /**\n   * @param {Options} [options] Style options.\n   */\n  constructor(options) {\n    options = options || {};\n\n    /**\n     * @private\n     * @type {string|import(\"../geom/Geometry.js\").default|GeometryFunction|null}\n     */\n    this.geometry_ = null;\n\n    /**\n     * @private\n     * @type {!GeometryFunction}\n     */\n    this.geometryFunction_ = defaultGeometryFunction;\n\n    if (options.geometry !== undefined) {\n      this.setGeometry(options.geometry);\n    }\n\n    /**\n     * @private\n     * @type {import(\"./Fill.js\").default|null}\n     */\n    this.fill_ = options.fill !== undefined ? options.fill : null;\n\n    /**\n     * @private\n     * @type {import(\"./Image.js\").default|null}\n     */\n    this.image_ = options.image !== undefined ? options.image : null;\n\n    /**\n     * @private\n     * @type {RenderFunction|null}\n     */\n    this.renderer_ = options.renderer !== undefined ? options.renderer : null;\n\n    /**\n     * @private\n     * @type {RenderFunction|null}\n     */\n    this.hitDetectionRenderer_ =\n      options.hitDetectionRenderer !== undefined\n        ? options.hitDetectionRenderer\n        : null;\n\n    /**\n     * @private\n     * @type {import(\"./Stroke.js\").default|null}\n     */\n    this.stroke_ = options.stroke !== undefined ? options.stroke : null;\n\n    /**\n     * @private\n     * @type {import(\"./Text.js\").default|null}\n     */\n    this.text_ = options.text !== undefined ? options.text : null;\n\n    /**\n     * @private\n     * @type {number|undefined}\n     */\n    this.zIndex_ = options.zIndex;\n  }\n\n  /**\n   * Clones the style.\n   * @return {Style} The cloned style.\n   * @api\n   */\n  clone() {\n    let geometry = this.getGeometry();\n    if (geometry && typeof geometry === 'object') {\n      geometry = /** @type {import(\"../geom/Geometry.js\").default} */ (\n        geometry\n      ).clone();\n    }\n    return new Style({\n      geometry: geometry ?? undefined,\n      fill: this.getFill() ? this.getFill().clone() : undefined,\n      image: this.getImage() ? this.getImage().clone() : undefined,\n      renderer: this.getRenderer() ?? undefined,\n      stroke: this.getStroke() ? this.getStroke().clone() : undefined,\n      text: this.getText() ? this.getText().clone() : undefined,\n      zIndex: this.getZIndex(),\n    });\n  }\n\n  /**\n   * Get the custom renderer function that was configured with\n   * {@link #setRenderer} or the `renderer` constructor option.\n   * @return {RenderFunction|null} Custom renderer function.\n   * @api\n   */\n  getRenderer() {\n    return this.renderer_;\n  }\n\n  /**\n   * Sets a custom renderer function for this style. When set, `fill`, `stroke`\n   * and `image` options of the style will be ignored.\n   * @param {RenderFunction|null} renderer Custom renderer function.\n   * @api\n   */\n  setRenderer(renderer) {\n    this.renderer_ = renderer;\n  }\n\n  /**\n   * Sets a custom renderer function for this style used\n   * in hit detection.\n   * @param {RenderFunction|null} renderer Custom renderer function.\n   * @api\n   */\n  setHitDetectionRenderer(renderer) {\n    this.hitDetectionRenderer_ = renderer;\n  }\n\n  /**\n   * Get the custom renderer function that was configured with\n   * {@link #setHitDetectionRenderer} or the `hitDetectionRenderer` constructor option.\n   * @return {RenderFunction|null} Custom renderer function.\n   * @api\n   */\n  getHitDetectionRenderer() {\n    return this.hitDetectionRenderer_;\n  }\n\n  /**\n   * Get the geometry to be rendered.\n   * @return {string|import(\"../geom/Geometry.js\").default|GeometryFunction|null}\n   * Feature property or geometry or function that returns the geometry that will\n   * be rendered with this style.\n   * @api\n   */\n  getGeometry() {\n    return this.geometry_;\n  }\n\n  /**\n   * Get the function used to generate a geometry for rendering.\n   * @return {!GeometryFunction} Function that is called with a feature\n   * and returns the geometry to render instead of the feature's geometry.\n   * @api\n   */\n  getGeometryFunction() {\n    return this.geometryFunction_;\n  }\n\n  /**\n   * Get the fill style.\n   * @return {import(\"./Fill.js\").default|null} Fill style.\n   * @api\n   */\n  getFill() {\n    return this.fill_;\n  }\n\n  /**\n   * Set the fill style.\n   * @param {import(\"./Fill.js\").default|null} fill Fill style.\n   * @api\n   */\n  setFill(fill) {\n    this.fill_ = fill;\n  }\n\n  /**\n   * Get the image style.\n   * @return {import(\"./Image.js\").default|null} Image style.\n   * @api\n   */\n  getImage() {\n    return this.image_;\n  }\n\n  /**\n   * Set the image style.\n   * @param {import(\"./Image.js\").default} image Image style.\n   * @api\n   */\n  setImage(image) {\n    this.image_ = image;\n  }\n\n  /**\n   * Get the stroke style.\n   * @return {import(\"./Stroke.js\").default|null} Stroke style.\n   * @api\n   */\n  getStroke() {\n    return this.stroke_;\n  }\n\n  /**\n   * Set the stroke style.\n   * @param {import(\"./Stroke.js\").default|null} stroke Stroke style.\n   * @api\n   */\n  setStroke(stroke) {\n    this.stroke_ = stroke;\n  }\n\n  /**\n   * Get the text style.\n   * @return {import(\"./Text.js\").default|null} Text style.\n   * @api\n   */\n  getText() {\n    return this.text_;\n  }\n\n  /**\n   * Set the text style.\n   * @param {import(\"./Text.js\").default} text Text style.\n   * @api\n   */\n  setText(text) {\n    this.text_ = text;\n  }\n\n  /**\n   * Get the z-index for the style.\n   * @return {number|undefined} ZIndex.\n   * @api\n   */\n  getZIndex() {\n    return this.zIndex_;\n  }\n\n  /**\n   * Set a geometry that is rendered instead of the feature's geometry.\n   *\n   * @param {string|import(\"../geom/Geometry.js\").default|GeometryFunction|null} geometry\n   *     Feature property or geometry or function returning a geometry to render\n   *     for this style.\n   * @api\n   */\n  setGeometry(geometry) {\n    if (typeof geometry === 'function') {\n      this.geometryFunction_ = geometry;\n    } else if (typeof geometry === 'string') {\n      this.geometryFunction_ = function (feature) {\n        return /** @type {import(\"../geom/Geometry.js\").default} */ (\n          feature.get(geometry)\n        );\n      };\n    } else if (!geometry) {\n      this.geometryFunction_ = defaultGeometryFunction;\n    } else if (geometry !== undefined) {\n      this.geometryFunction_ = function () {\n        return /** @type {import(\"../geom/Geometry.js\").default} */ (geometry);\n      };\n    }\n    this.geometry_ = geometry;\n  }\n\n  /**\n   * Set the z-index.\n   *\n   * @param {number|undefined} zIndex ZIndex.\n   * @api\n   */\n  setZIndex(zIndex) {\n    this.zIndex_ = zIndex;\n  }\n}\n\n/**\n * Convert the provided object into a style function.  Functions passed through\n * unchanged.  Arrays of Style or single style objects wrapped in a\n * new style function.\n * @param {StyleFunction|Array<Style>|Style} obj\n *     A style function, a single style, or an array of styles.\n * @return {StyleFunction} A style function.\n */\nexport function toFunction(obj) {\n  let styleFunction;\n\n  if (typeof obj === 'function') {\n    styleFunction = obj;\n  } else {\n    /**\n     * @type {Array<Style>}\n     */\n    let styles;\n    if (Array.isArray(obj)) {\n      styles = obj;\n    } else {\n      assert(\n        typeof (/** @type {?} */ (obj).getZIndex) === 'function',\n        'Expected an `Style` or an array of `Style`',\n      );\n      const style = /** @type {Style} */ (obj);\n      styles = [style];\n    }\n    styleFunction = function () {\n      return styles;\n    };\n  }\n  return styleFunction;\n}\n\n/**\n * @type {Array<Style>|null}\n */\nlet defaultStyles = null;\n\n/**\n * @param {import(\"../Feature.js\").FeatureLike} feature Feature.\n * @param {number} resolution Resolution.\n * @return {Array<Style>} Style.\n */\nexport function createDefaultStyle(feature, resolution) {\n  // We don't use an immediately-invoked function\n  // and a closure so we don't get an error at script evaluation time in\n  // browsers that do not support Canvas. (import(\"./Circle.js\").CircleStyle does\n  // canvas.getContext('2d') at construction time, which will cause an.error\n  // in such browsers.)\n  if (!defaultStyles) {\n    const fill = new Fill({\n      color: 'rgba(255,255,255,0.4)',\n    });\n    const stroke = new Stroke({\n      color: '#3399CC',\n      width: 1.25,\n    });\n    defaultStyles = [\n      new Style({\n        image: new CircleStyle({\n          fill: fill,\n          stroke: stroke,\n          radius: 5,\n        }),\n        fill: fill,\n        stroke: stroke,\n      }),\n    ];\n  }\n  return defaultStyles;\n}\n\n/**\n * Default styles for editing features.\n * @return {Object<import(\"../geom/Geometry.js\").Type, Array<Style>>} Styles\n */\nexport function createEditingStyle() {\n  /** @type {Object<import(\"../geom/Geometry.js\").Type, Array<Style>>} */\n  const styles = {};\n  const white = [255, 255, 255, 1];\n  const blue = [0, 153, 255, 1];\n  const width = 3;\n  styles['Polygon'] = [\n    new Style({\n      fill: new Fill({\n        color: [255, 255, 255, 0.5],\n      }),\n    }),\n  ];\n  styles['MultiPolygon'] = styles['Polygon'];\n\n  styles['LineString'] = [\n    new Style({\n      stroke: new Stroke({\n        color: white,\n        width: width + 2,\n      }),\n    }),\n    new Style({\n      stroke: new Stroke({\n        color: blue,\n        width: width,\n      }),\n    }),\n  ];\n  styles['MultiLineString'] = styles['LineString'];\n\n  styles['Circle'] = styles['Polygon'].concat(styles['LineString']);\n\n  styles['Point'] = [\n    new Style({\n      image: new CircleStyle({\n        radius: width * 2,\n        fill: new Fill({\n          color: blue,\n        }),\n        stroke: new Stroke({\n          color: white,\n          width: width / 2,\n        }),\n      }),\n      zIndex: Infinity,\n    }),\n  ];\n  styles['MultiPoint'] = styles['Point'];\n\n  styles['GeometryCollection'] = styles['Polygon'].concat(\n    styles['LineString'],\n    styles['Point'],\n  );\n\n  return styles;\n}\n\n/**\n * Function that is called with a feature and returns its default geometry.\n * @param {import(\"../Feature.js\").FeatureLike} feature Feature to get the geometry for.\n * @return {import(\"../geom/Geometry.js\").default|import(\"../render/Feature.js\").default|undefined} Geometry to render.\n */\nfunction defaultGeometryFunction(feature) {\n  return feature.getGeometry();\n}\n\nexport default Style;\n", "/**\n * @module ol/style/Text\n */\nimport {toSize} from '../size.js';\nimport Fill from './Fill.js';\n\n/**\n * @typedef {'point' | 'line'} TextPlacement\n * Default text placement is `'point'`. Note that\n * `'line'` requires the underlying geometry to be a {@link module:ol/geom/LineString~LineString},\n * {@link module:ol/geom/Polygon~Polygon}, {@link module:ol/geom/MultiLineString~MultiLineString} or\n * {@link module:ol/geom/MultiPolygon~MultiPolygon}.\n */\n\n/**\n * @typedef {'left' | 'center' | 'right'} TextJustify\n */\n\n/**\n * The default fill color to use if no fill was set at construction time; a\n * blackish `#333`.\n *\n * @const {string}\n */\nconst DEFAULT_FILL_COLOR = '#333';\n\n/**\n * @typedef {Object} Options\n * @property {string} [font] Font style as CSS `font` value, see:\n * https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/font. Default is `'10px sans-serif'`\n * @property {number} [maxAngle=Math.PI/4] When `placement` is set to `'line'`, allow a maximum angle between adjacent characters.\n * The expected value is in radians, and the default is 45\u00B0 (`Math.PI / 4`).\n * @property {number} [offsetX=0] Horizontal text offset in pixels. A positive will shift the text right.\n * @property {number} [offsetY=0] Vertical text offset in pixels. A positive will shift the text down.\n * @property {boolean} [overflow=false] For polygon labels or when `placement` is set to `'line'`, allow text to exceed\n * the width of the polygon at the label position or the length of the path that it follows.\n * @property {TextPlacement} [placement='point'] Text placement.\n * @property {number} [repeat] Repeat interval. When set, the text will be repeated at this interval, which specifies\n * the distance between two text anchors in pixels. Only available when `placement` is set to `'line'`. Overrides 'textAlign'.\n * @property {number|import(\"../size.js\").Size} [scale] Scale.\n * @property {boolean} [rotateWithView=false] Whether to rotate the text with the view.\n * @property {boolean} [keepUpright=true] Whether the text can be rotated 180\u00B0 to prevent being rendered upside down.\n * @property {number} [rotation=0] Rotation in radians (positive rotation clockwise).\n * @property {string|Array<string>} [text] Text content or rich text content. For plain text provide a string, which can\n * contain line breaks (`\\n`). For rich text provide an array of text/font tuples. A tuple consists of the text to\n * render and the font to use (or `''` to use the text style's font). A line break has to be a separate tuple (i.e. `'\\n', ''`).\n * **Example:** `['foo', 'bold 10px sans-serif', ' bar', 'italic 10px sans-serif', ' baz', '']` will yield \"**foo** *bar* baz\".\n * **Note:** Rich text is not supported for `placement: 'line'` or the immediate rendering API.\n * @property {CanvasTextAlign} [textAlign] Text alignment. Possible values: `'left'`, `'right'`, `'center'`, `'end'` or `'start'`.\n * Default is `'center'` for `placement: 'point'`. For `placement: 'line'`, the default is to let the renderer choose a\n * placement where `maxAngle` is not exceeded.\n * @property {TextJustify} [justify] Text justification within the text box.\n * If not set, text is justified towards the `textAlign` anchor.\n * Otherwise, use options `'left'`, `'center'`, or `'right'` to justify the text within the text box.\n * **Note:** `justify` is ignored for immediate rendering and also for `placement: 'line'`.\n * @property {CanvasTextBaseline} [textBaseline='middle'] Text base line. Possible values: `'bottom'`, `'top'`, `'middle'`, `'alphabetic'`,\n * `'hanging'`, `'ideographic'`.\n * @property {import(\"./Fill.js\").default|null} [fill] Fill style. If none is provided, we'll use a dark fill-style (#333). Specify `null` for no fill.\n * @property {import(\"./Stroke.js\").default} [stroke] Stroke style.\n * @property {import(\"./Fill.js\").default} [backgroundFill] Fill style for the text background when `placement` is\n * `'point'`. Default is no fill.\n * @property {import(\"./Stroke.js\").default} [backgroundStroke] Stroke style for the text background  when `placement`\n * is `'point'`. Default is no stroke.\n * @property {Array<number>} [padding=[0, 0, 0, 0]] Padding in pixels around the text for decluttering and background. The order of\n * values in the array is `[top, right, bottom, left]`.\n * @property {import('../style/Style.js').DeclutterMode} [declutterMode] Declutter mode: `declutter`, `obstacle`, `none`\n */\n\n/**\n * @classdesc\n * Set text style for vector features.\n * @api\n */\nclass Text {\n  /**\n   * @param {Options} [options] Options.\n   */\n  constructor(options) {\n    options = options || {};\n\n    /**\n     * @private\n     * @type {string|undefined}\n     */\n    this.font_ = options.font;\n\n    /**\n     * @private\n     * @type {number|undefined}\n     */\n    this.rotation_ = options.rotation;\n\n    /**\n     * @private\n     * @type {boolean|undefined}\n     */\n    this.rotateWithView_ = options.rotateWithView;\n\n    /**\n     * @private\n     * @type {boolean|undefined}\n     */\n    this.keepUpright_ = options.keepUpright;\n\n    /**\n     * @private\n     * @type {number|import(\"../size.js\").Size|undefined}\n     */\n    this.scale_ = options.scale;\n\n    /**\n     * @private\n     * @type {import(\"../size.js\").Size}\n     */\n    this.scaleArray_ = toSize(options.scale !== undefined ? options.scale : 1);\n\n    /**\n     * @private\n     * @type {string|Array<string>|undefined}\n     */\n    this.text_ = options.text;\n\n    /**\n     * @private\n     * @type {CanvasTextAlign|undefined}\n     */\n    this.textAlign_ = options.textAlign;\n\n    /**\n     * @private\n     * @type {TextJustify|undefined}\n     */\n    this.justify_ = options.justify;\n\n    /**\n     * @private\n     * @type {number|undefined}\n     */\n    this.repeat_ = options.repeat;\n\n    /**\n     * @private\n     * @type {CanvasTextBaseline|undefined}\n     */\n    this.textBaseline_ = options.textBaseline;\n\n    /**\n     * @private\n     * @type {import(\"./Fill.js\").default|null}\n     */\n    this.fill_ =\n      options.fill !== undefined\n        ? options.fill\n        : new Fill({color: DEFAULT_FILL_COLOR});\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.maxAngle_ =\n      options.maxAngle !== undefined ? options.maxAngle : Math.PI / 4;\n\n    /**\n     * @private\n     * @type {TextPlacement}\n     */\n    this.placement_ =\n      options.placement !== undefined ? options.placement : 'point';\n\n    /**\n     * @private\n     * @type {boolean}\n     */\n    this.overflow_ = !!options.overflow;\n\n    /**\n     * @private\n     * @type {import(\"./Stroke.js\").default|null}\n     */\n    this.stroke_ = options.stroke !== undefined ? options.stroke : null;\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.offsetX_ = options.offsetX !== undefined ? options.offsetX : 0;\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.offsetY_ = options.offsetY !== undefined ? options.offsetY : 0;\n\n    /**\n     * @private\n     * @type {import(\"./Fill.js\").default|null}\n     */\n    this.backgroundFill_ = options.backgroundFill\n      ? options.backgroundFill\n      : null;\n\n    /**\n     * @private\n     * @type {import(\"./Stroke.js\").default|null}\n     */\n    this.backgroundStroke_ = options.backgroundStroke\n      ? options.backgroundStroke\n      : null;\n\n    /**\n     * @private\n     * @type {Array<number>|null}\n     */\n    this.padding_ = options.padding === undefined ? null : options.padding;\n\n    /**\n     * @private\n     * @type {import('../style/Style.js').DeclutterMode}\n     */\n    this.declutterMode_ = options.declutterMode;\n  }\n\n  /**\n   * Clones the style.\n   * @return {Text} The cloned style.\n   * @api\n   */\n  clone() {\n    const scale = this.getScale();\n    return new Text({\n      font: this.getFont(),\n      placement: this.getPlacement(),\n      repeat: this.getRepeat(),\n      maxAngle: this.getMaxAngle(),\n      overflow: this.getOverflow(),\n      rotation: this.getRotation(),\n      rotateWithView: this.getRotateWithView(),\n      keepUpright: this.getKeepUpright(),\n      scale: Array.isArray(scale) ? scale.slice() : scale,\n      text: this.getText(),\n      textAlign: this.getTextAlign(),\n      justify: this.getJustify(),\n      textBaseline: this.getTextBaseline(),\n      fill:\n        this.getFill() instanceof Fill\n          ? this.getFill().clone()\n          : this.getFill(),\n      stroke: this.getStroke() ? this.getStroke().clone() : undefined,\n      offsetX: this.getOffsetX(),\n      offsetY: this.getOffsetY(),\n      backgroundFill: this.getBackgroundFill()\n        ? this.getBackgroundFill().clone()\n        : undefined,\n      backgroundStroke: this.getBackgroundStroke()\n        ? this.getBackgroundStroke().clone()\n        : undefined,\n      padding: this.getPadding() || undefined,\n      declutterMode: this.getDeclutterMode(),\n    });\n  }\n\n  /**\n   * Get the `overflow` configuration.\n   * @return {boolean} Let text overflow the length of the path they follow.\n   * @api\n   */\n  getOverflow() {\n    return this.overflow_;\n  }\n\n  /**\n   * Get the font name.\n   * @return {string|undefined} Font.\n   * @api\n   */\n  getFont() {\n    return this.font_;\n  }\n\n  /**\n   * Get the maximum angle between adjacent characters.\n   * @return {number} Angle in radians.\n   * @api\n   */\n  getMaxAngle() {\n    return this.maxAngle_;\n  }\n\n  /**\n   * Get the label placement.\n   * @return {TextPlacement} Text placement.\n   * @api\n   */\n  getPlacement() {\n    return this.placement_;\n  }\n\n  /**\n   * Get the repeat interval of the text.\n   * @return {number|undefined} Repeat interval in pixels.\n   * @api\n   */\n  getRepeat() {\n    return this.repeat_;\n  }\n\n  /**\n   * Get the x-offset for the text.\n   * @return {number} Horizontal text offset.\n   * @api\n   */\n  getOffsetX() {\n    return this.offsetX_;\n  }\n\n  /**\n   * Get the y-offset for the text.\n   * @return {number} Vertical text offset.\n   * @api\n   */\n  getOffsetY() {\n    return this.offsetY_;\n  }\n\n  /**\n   * Get the fill style for the text.\n   * @return {import(\"./Fill.js\").default|null} Fill style.\n   * @api\n   */\n  getFill() {\n    return this.fill_;\n  }\n\n  /**\n   * Determine whether the text rotates with the map.\n   * @return {boolean|undefined} Rotate with map.\n   * @api\n   */\n  getRotateWithView() {\n    return this.rotateWithView_;\n  }\n\n  /**\n   * Determine whether the text can be rendered upside down.\n   * @return {boolean|undefined} Keep text upright.\n   * @api\n   */\n  getKeepUpright() {\n    return this.keepUpright_;\n  }\n\n  /**\n   * Get the text rotation.\n   * @return {number|undefined} Rotation.\n   * @api\n   */\n  getRotation() {\n    return this.rotation_;\n  }\n\n  /**\n   * Get the text scale.\n   * @return {number|import(\"../size.js\").Size|undefined} Scale.\n   * @api\n   */\n  getScale() {\n    return this.scale_;\n  }\n\n  /**\n   * Get the symbolizer scale array.\n   * @return {import(\"../size.js\").Size} Scale array.\n   */\n  getScaleArray() {\n    return this.scaleArray_;\n  }\n\n  /**\n   * Get the stroke style for the text.\n   * @return {import(\"./Stroke.js\").default|null} Stroke style.\n   * @api\n   */\n  getStroke() {\n    return this.stroke_;\n  }\n\n  /**\n   * Get the text to be rendered.\n   * @return {string|Array<string>|undefined} Text.\n   * @api\n   */\n  getText() {\n    return this.text_;\n  }\n\n  /**\n   * Get the text alignment.\n   * @return {CanvasTextAlign|undefined} Text align.\n   * @api\n   */\n  getTextAlign() {\n    return this.textAlign_;\n  }\n\n  /**\n   * Get the justification.\n   * @return {TextJustify|undefined} Justification.\n   * @api\n   */\n  getJustify() {\n    return this.justify_;\n  }\n\n  /**\n   * Get the text baseline.\n   * @return {CanvasTextBaseline|undefined} Text baseline.\n   * @api\n   */\n  getTextBaseline() {\n    return this.textBaseline_;\n  }\n\n  /**\n   * Get the background fill style for the text.\n   * @return {import(\"./Fill.js\").default|null} Fill style.\n   * @api\n   */\n  getBackgroundFill() {\n    return this.backgroundFill_;\n  }\n\n  /**\n   * Get the background stroke style for the text.\n   * @return {import(\"./Stroke.js\").default|null} Stroke style.\n   * @api\n   */\n  getBackgroundStroke() {\n    return this.backgroundStroke_;\n  }\n\n  /**\n   * Get the padding for the text.\n   * @return {Array<number>|null} Padding.\n   * @api\n   */\n  getPadding() {\n    return this.padding_;\n  }\n\n  /**\n   * Get the declutter mode of the shape\n   * @return {import(\"./Style.js\").DeclutterMode} Shape's declutter mode\n   * @api\n   */\n  getDeclutterMode() {\n    return this.declutterMode_;\n  }\n\n  /**\n   * Set the `overflow` property.\n   *\n   * @param {boolean} overflow Let text overflow the path that it follows.\n   * @api\n   */\n  setOverflow(overflow) {\n    this.overflow_ = overflow;\n  }\n\n  /**\n   * Set the font.\n   *\n   * @param {string|undefined} font Font.\n   * @api\n   */\n  setFont(font) {\n    this.font_ = font;\n  }\n\n  /**\n   * Set the maximum angle between adjacent characters.\n   *\n   * @param {number} maxAngle Angle in radians.\n   * @api\n   */\n  setMaxAngle(maxAngle) {\n    this.maxAngle_ = maxAngle;\n  }\n\n  /**\n   * Set the x offset.\n   *\n   * @param {number} offsetX Horizontal text offset.\n   * @api\n   */\n  setOffsetX(offsetX) {\n    this.offsetX_ = offsetX;\n  }\n\n  /**\n   * Set the y offset.\n   *\n   * @param {number} offsetY Vertical text offset.\n   * @api\n   */\n  setOffsetY(offsetY) {\n    this.offsetY_ = offsetY;\n  }\n\n  /**\n   * Set the text placement.\n   *\n   * @param {TextPlacement} placement Placement.\n   * @api\n   */\n  setPlacement(placement) {\n    this.placement_ = placement;\n  }\n\n  /**\n   * Set the repeat interval of the text.\n   * @param {number|undefined} [repeat] Repeat interval in pixels.\n   * @api\n   */\n  setRepeat(repeat) {\n    this.repeat_ = repeat;\n  }\n\n  /**\n   * Set whether to rotate the text with the view.\n   *\n   * @param {boolean} rotateWithView Rotate with map.\n   * @api\n   */\n  setRotateWithView(rotateWithView) {\n    this.rotateWithView_ = rotateWithView;\n  }\n\n  /**\n   * Set whether the text can be rendered upside down.\n   *\n   * @param {boolean} keepUpright Keep text upright.\n   * @api\n   */\n  setKeepUpright(keepUpright) {\n    this.keepUpright_ = keepUpright;\n  }\n\n  /**\n   * Set the fill.\n   *\n   * @param {import(\"./Fill.js\").default|null} fill Fill style.\n   * @api\n   */\n  setFill(fill) {\n    this.fill_ = fill;\n  }\n\n  /**\n   * Set the rotation.\n   *\n   * @param {number|undefined} rotation Rotation.\n   * @api\n   */\n  setRotation(rotation) {\n    this.rotation_ = rotation;\n  }\n\n  /**\n   * Set the scale.\n   *\n   * @param {number|import(\"../size.js\").Size|undefined} scale Scale.\n   * @api\n   */\n  setScale(scale) {\n    this.scale_ = scale;\n    this.scaleArray_ = toSize(scale !== undefined ? scale : 1);\n  }\n\n  /**\n   * Set the stroke.\n   *\n   * @param {import(\"./Stroke.js\").default|null} stroke Stroke style.\n   * @api\n   */\n  setStroke(stroke) {\n    this.stroke_ = stroke;\n  }\n\n  /**\n   * Set the text.\n   *\n   * @param {string|Array<string>|undefined} text Text.\n   * @api\n   */\n  setText(text) {\n    this.text_ = text;\n  }\n\n  /**\n   * Set the text alignment.\n   *\n   * @param {CanvasTextAlign|undefined} textAlign Text align.\n   * @api\n   */\n  setTextAlign(textAlign) {\n    this.textAlign_ = textAlign;\n  }\n\n  /**\n   * Set the justification.\n   *\n   * @param {TextJustify|undefined} justify Justification.\n   * @api\n   */\n  setJustify(justify) {\n    this.justify_ = justify;\n  }\n\n  /**\n   * Set the text baseline.\n   *\n   * @param {CanvasTextBaseline|undefined} textBaseline Text baseline.\n   * @api\n   */\n  setTextBaseline(textBaseline) {\n    this.textBaseline_ = textBaseline;\n  }\n\n  /**\n   * Set the background fill.\n   *\n   * @param {import(\"./Fill.js\").default|null} fill Fill style.\n   * @api\n   */\n  setBackgroundFill(fill) {\n    this.backgroundFill_ = fill;\n  }\n\n  /**\n   * Set the background stroke.\n   *\n   * @param {import(\"./Stroke.js\").default|null} stroke Stroke style.\n   * @api\n   */\n  setBackgroundStroke(stroke) {\n    this.backgroundStroke_ = stroke;\n  }\n\n  /**\n   * Set the padding (`[top, right, bottom, left]`).\n   *\n   * @param {Array<number>|null} padding Padding.\n   * @api\n   */\n  setPadding(padding) {\n    this.padding_ = padding;\n  }\n}\n\nexport default Text;\n", "/**\n * @module ol/render/canvas/style\n */\n\nimport {NO_COLOR} from '../../color.js';\nimport {buildExpression, newEvaluationContext} from '../../expr/cpu.js';\nimport {\n  BooleanType,\n  ColorType,\n  NumberArrayType,\n  NumberType,\n  StringType,\n  computeGeometryType,\n  newParsingContext,\n} from '../../expr/expression.js';\nimport {isEmpty} from '../../obj.js';\nimport {toSize} from '../../size.js';\nimport Circle from '../../style/Circle.js';\nimport Fill from '../../style/Fill.js';\nimport Icon from '../../style/Icon.js';\nimport RegularShape from '../../style/RegularShape.js';\nimport Stroke from '../../style/Stroke.js';\nimport Style from '../../style/Style.js';\nimport Text from '../../style/Text.js';\n\n/**\n * @fileoverview This module includes functions to build styles for the canvas renderer.  Building\n * is composed of two steps: parsing and compiling.  The parsing step takes an encoded expression\n * and returns an instance of one of the expression classes.  The compiling step takes the\n * expression instance and returns a function that can be evaluated to return a literal value.  The\n * evaluator function should do as little allocation and work as possible.\n */\n\n/**\n * @typedef {import(\"../../style/flat.js\").FlatStyle} FlatStyle\n */\n\n/**\n * @typedef {import(\"../../expr/expression.js\").EncodedExpression} EncodedExpression\n */\n\n/**\n * @typedef {import(\"../../expr/expression.js\").ParsingContext} ParsingContext\n */\n\n/**\n * @typedef {import(\"../../expr/expression.js\").CallExpression} CallExpression\n */\n\n/**\n * @typedef {import(\"../../expr/cpu.js\").EvaluationContext} EvaluationContext\n */\n\n/**\n * @typedef {import(\"../../expr/cpu.js\").ExpressionEvaluator} ExpressionEvaluator\n */\n\n/**\n * @param {EvaluationContext} context The evaluation context.\n * @return {boolean} Always true.\n */\nfunction always(context) {\n  return true;\n}\n\n/**\n * This function adapts a rule evaluator to the existing style function interface.\n * After we have deprecated the style function, we can use the compiled rules directly\n * and pass a more complete evaluation context (variables, zoom, time, etc.).\n *\n * @param {Array<import('../../style/flat.js').Rule>} rules The rules.\n * @return {import('../../style/Style.js').StyleFunction} A style function.\n */\nexport function rulesToStyleFunction(rules) {\n  const parsingContext = newParsingContext();\n  const evaluator = buildRuleSet(rules, parsingContext);\n  const evaluationContext = newEvaluationContext();\n  return function (feature, resolution) {\n    evaluationContext.properties = feature.getPropertiesInternal();\n    evaluationContext.resolution = resolution;\n    if (parsingContext.featureId) {\n      const id = feature.getId();\n      if (id !== undefined) {\n        evaluationContext.featureId = id;\n      } else {\n        evaluationContext.featureId = null;\n      }\n    }\n    if (parsingContext.geometryType) {\n      evaluationContext.geometryType = computeGeometryType(\n        feature.getGeometry(),\n      );\n    }\n    return evaluator(evaluationContext);\n  };\n}\n\n/**\n * This function adapts a style evaluator to the existing style function interface.\n * After we have deprecated the style function, we can use the compiled rules directly\n * and pass a more complete evaluation context (variables, zoom, time, etc.).\n *\n * @param {Array<import('../../style/flat.js').FlatStyle>} flatStyles The flat styles.\n * @return {import('../../style/Style.js').StyleFunction} A style function.\n */\nexport function flatStylesToStyleFunction(flatStyles) {\n  const parsingContext = newParsingContext();\n  const length = flatStyles.length;\n\n  /**\n   * @type {Array<StyleEvaluator>}\n   */\n  const evaluators = new Array(length);\n  for (let i = 0; i < length; ++i) {\n    evaluators[i] = buildStyle(flatStyles[i], parsingContext);\n  }\n  const evaluationContext = newEvaluationContext();\n\n  /**\n   * @type {Array<Style>}\n   */\n  const styles = new Array(length);\n\n  return function (feature, resolution) {\n    evaluationContext.properties = feature.getPropertiesInternal();\n    evaluationContext.resolution = resolution;\n    if (parsingContext.featureId) {\n      const id = feature.getId();\n      if (id !== undefined) {\n        evaluationContext.featureId = id;\n      } else {\n        evaluationContext.featureId = null;\n      }\n    }\n    let nonNullCount = 0;\n    for (let i = 0; i < length; ++i) {\n      const style = evaluators[i](evaluationContext);\n      if (style) {\n        styles[nonNullCount] = style;\n        nonNullCount += 1;\n      }\n    }\n    styles.length = nonNullCount;\n    return styles;\n  };\n}\n\n/**\n * @typedef {function(EvaluationContext):Array<Style>} RuleSetEvaluator\n */\n\n/**\n * @typedef {Object} CompiledRule\n * @property {ExpressionEvaluator} filter The compiled filter evaluator.\n * @property {Array<StyleEvaluator>} styles The list of compiled style evaluators.\n */\n\n/**\n * @param {Array<import('../../style/flat.js').Rule>} rules The rules.\n * @param {ParsingContext} context The parsing context.\n * @return {RuleSetEvaluator} The evaluator function.\n */\nexport function buildRuleSet(rules, context) {\n  const length = rules.length;\n\n  /**\n   * @type {Array<CompiledRule>}\n   */\n  const compiledRules = new Array(length);\n\n  for (let i = 0; i < length; ++i) {\n    const rule = rules[i];\n    const filter =\n      'filter' in rule\n        ? buildExpression(rule.filter, BooleanType, context)\n        : always;\n\n    /**\n     * @type {Array<StyleEvaluator>}\n     */\n    let styles;\n    if (Array.isArray(rule.style)) {\n      const styleLength = rule.style.length;\n      styles = new Array(styleLength);\n      for (let j = 0; j < styleLength; ++j) {\n        styles[j] = buildStyle(rule.style[j], context);\n      }\n    } else {\n      styles = [buildStyle(rule.style, context)];\n    }\n\n    compiledRules[i] = {filter, styles};\n  }\n\n  return function (context) {\n    /**\n     * @type {Array<Style>}\n     */\n    const styles = [];\n\n    let someMatched = false;\n    for (let i = 0; i < length; ++i) {\n      const filterEvaluator = compiledRules[i].filter;\n      if (!filterEvaluator(context)) {\n        continue;\n      }\n      if (rules[i].else && someMatched) {\n        continue;\n      }\n      someMatched = true;\n      for (const styleEvaluator of compiledRules[i].styles) {\n        const style = styleEvaluator(context);\n        if (!style) {\n          continue;\n        }\n        styles.push(style);\n      }\n    }\n\n    return styles;\n  };\n}\n\n/**\n * @typedef {function(EvaluationContext):Style|null} StyleEvaluator\n */\n\n/**\n * @param {FlatStyle} flatStyle A flat style literal.\n * @param {ParsingContext} context The parsing context.\n * @return {StyleEvaluator} A function that evaluates to a style.  The style returned by\n * this function will be reused between invocations.\n */\nexport function buildStyle(flatStyle, context) {\n  const evaluateFill = buildFill(flatStyle, '', context);\n  const evaluateStroke = buildStroke(flatStyle, '', context);\n  const evaluateText = buildText(flatStyle, context);\n  const evaluateImage = buildImage(flatStyle, context);\n  const evaluateZIndex = numberEvaluator(flatStyle, 'z-index', context);\n\n  if (\n    !evaluateFill &&\n    !evaluateStroke &&\n    !evaluateText &&\n    !evaluateImage &&\n    !isEmpty(flatStyle)\n  ) {\n    // assume this is a user error\n    // would be nice to check the properties and suggest \"did you mean...\"\n    throw new Error(\n      'No fill, stroke, point, or text symbolizer properties in style: ' +\n        JSON.stringify(flatStyle),\n    );\n  }\n\n  const style = new Style();\n  return function (context) {\n    let empty = true;\n    if (evaluateFill) {\n      const fill = evaluateFill(context);\n      if (fill) {\n        empty = false;\n      }\n      style.setFill(fill);\n    }\n    if (evaluateStroke) {\n      const stroke = evaluateStroke(context);\n      if (stroke) {\n        empty = false;\n      }\n      style.setStroke(stroke);\n    }\n    if (evaluateText) {\n      const text = evaluateText(context);\n      if (text) {\n        empty = false;\n      }\n      style.setText(text);\n    }\n    if (evaluateImage) {\n      const image = evaluateImage(context);\n      if (image) {\n        empty = false;\n      }\n      style.setImage(image);\n    }\n    if (evaluateZIndex) {\n      style.setZIndex(evaluateZIndex(context));\n    }\n    if (empty) {\n      return null;\n    }\n    return style;\n  };\n}\n\n/**\n * @typedef {function(EvaluationContext):Fill|null} FillEvaluator\n */\n\n/**\n * @param {FlatStyle} flatStyle The flat style.\n * @param {string} prefix The property prefix.\n * @param {ParsingContext} context The parsing context.\n * @return {FillEvaluator?} A function that evaluates to a fill.\n */\nfunction buildFill(flatStyle, prefix, context) {\n  let evaluateColor;\n  if (prefix + 'fill-pattern-src' in flatStyle) {\n    evaluateColor = patternEvaluator(flatStyle, prefix + 'fill-', context);\n  } else {\n    if (flatStyle[prefix + 'fill-color'] === 'none') {\n      // avoids hit detection\n      return (context) => null;\n    }\n\n    evaluateColor = colorLikeEvaluator(\n      flatStyle,\n      prefix + 'fill-color',\n      context,\n    );\n  }\n  if (!evaluateColor) {\n    return null;\n  }\n\n  const fill = new Fill();\n  return function (context) {\n    const color = evaluateColor(context);\n    if (color === NO_COLOR) {\n      return null;\n    }\n    fill.setColor(color);\n    return fill;\n  };\n}\n\n/**\n * @typedef {function(EvaluationContext):Stroke|null} StrokeEvaluator\n */\n\n/**\n * @param {FlatStyle} flatStyle The flat style.\n * @param {string} prefix The property prefix.\n * @param {ParsingContext} context The parsing context.\n * @return {StrokeEvaluator?} A function the evaluates to a stroke.\n */\nfunction buildStroke(flatStyle, prefix, context) {\n  const evaluateWidth = numberEvaluator(\n    flatStyle,\n    prefix + 'stroke-width',\n    context,\n  );\n\n  const evaluateColor = colorLikeEvaluator(\n    flatStyle,\n    prefix + 'stroke-color',\n    context,\n  );\n\n  if (!evaluateWidth && !evaluateColor) {\n    return null;\n  }\n\n  const evaluateLineCap = stringEvaluator(\n    flatStyle,\n    prefix + 'stroke-line-cap',\n    context,\n  );\n\n  const evaluateLineJoin = stringEvaluator(\n    flatStyle,\n    prefix + 'stroke-line-join',\n    context,\n  );\n\n  const evaluateLineDash = numberArrayEvaluator(\n    flatStyle,\n    prefix + 'stroke-line-dash',\n    context,\n  );\n\n  const evaluateLineDashOffset = numberEvaluator(\n    flatStyle,\n    prefix + 'stroke-line-dash-offset',\n    context,\n  );\n\n  const evaluateMiterLimit = numberEvaluator(\n    flatStyle,\n    prefix + 'stroke-miter-limit',\n    context,\n  );\n\n  const evaluateOffset = numberEvaluator(\n    flatStyle,\n    prefix + 'stroke-offset',\n    context,\n  );\n\n  const stroke = new Stroke();\n  return function (context) {\n    if (evaluateColor) {\n      const color = evaluateColor(context);\n      if (color === NO_COLOR) {\n        return null;\n      }\n      stroke.setColor(color);\n    }\n\n    if (evaluateWidth) {\n      stroke.setWidth(evaluateWidth(context));\n    }\n\n    if (evaluateLineCap) {\n      const lineCap = evaluateLineCap(context);\n      if (lineCap !== 'butt' && lineCap !== 'round' && lineCap !== 'square') {\n        throw new Error('Expected butt, round, or square line cap');\n      }\n      stroke.setLineCap(lineCap);\n    }\n\n    if (evaluateLineJoin) {\n      const lineJoin = evaluateLineJoin(context);\n      if (\n        lineJoin !== 'bevel' &&\n        lineJoin !== 'round' &&\n        lineJoin !== 'miter'\n      ) {\n        throw new Error('Expected bevel, round, or miter line join');\n      }\n      stroke.setLineJoin(lineJoin);\n    }\n\n    if (evaluateLineDash) {\n      stroke.setLineDash(evaluateLineDash(context));\n    }\n\n    if (evaluateLineDashOffset) {\n      stroke.setLineDashOffset(evaluateLineDashOffset(context));\n    }\n\n    if (evaluateMiterLimit) {\n      stroke.setMiterLimit(evaluateMiterLimit(context));\n    }\n\n    if (evaluateOffset) {\n      stroke.setOffset(evaluateOffset(context));\n    }\n\n    return stroke;\n  };\n}\n\n/**\n * @typedef {function(EvaluationContext):Text} TextEvaluator\n */\n\n/**\n * @param {FlatStyle} flatStyle The flat style.\n * @param {ParsingContext} context The parsing context.\n * @return {TextEvaluator?} A function that evaluates to a text symbolizer.\n */\nfunction buildText(flatStyle, context) {\n  const prefix = 'text-';\n\n  // Currently, an Array<string> may be used for rich text support.  This doesn't\n  // work with our expression syntax where arrays of strings are interpreted as\n  // call expressions.  To support rich text, we could add a 'strings' operator\n  // where all the following arguments would be string values.\n  const evaluateValue = stringEvaluator(flatStyle, prefix + 'value', context);\n  if (!evaluateValue) {\n    return null;\n  }\n\n  const evaluateFill = buildFill(flatStyle, prefix, context);\n\n  const evaluateBackgroundFill = buildFill(\n    flatStyle,\n    prefix + 'background-',\n    context,\n  );\n\n  const evaluateStroke = buildStroke(flatStyle, prefix, context);\n\n  const evaluateBackgroundStroke = buildStroke(\n    flatStyle,\n    prefix + 'background-',\n    context,\n  );\n\n  const evaluateFont = stringEvaluator(flatStyle, prefix + 'font', context);\n\n  const evaluateMaxAngle = numberEvaluator(\n    flatStyle,\n    prefix + 'max-angle',\n    context,\n  );\n\n  const evaluateOffsetX = numberEvaluator(\n    flatStyle,\n    prefix + 'offset-x',\n    context,\n  );\n\n  const evaluateOffsetY = numberEvaluator(\n    flatStyle,\n    prefix + 'offset-y',\n    context,\n  );\n\n  const evaluateOverflow = booleanEvaluator(\n    flatStyle,\n    prefix + 'overflow',\n    context,\n  );\n\n  const evaluatePlacement = stringEvaluator(\n    flatStyle,\n    prefix + 'placement',\n    context,\n  );\n\n  const evaluateRepeat = numberEvaluator(flatStyle, prefix + 'repeat', context);\n\n  const evaluateScale = sizeLikeEvaluator(flatStyle, prefix + 'scale', context);\n\n  const evaluateRotateWithView = booleanEvaluator(\n    flatStyle,\n    prefix + 'rotate-with-view',\n    context,\n  );\n\n  const evaluateRotation = numberEvaluator(\n    flatStyle,\n    prefix + 'rotation',\n    context,\n  );\n\n  const evaluateAlign = stringEvaluator(flatStyle, prefix + 'align', context);\n\n  const evaluateJustify = stringEvaluator(\n    flatStyle,\n    prefix + 'justify',\n    context,\n  );\n\n  const evaluateBaseline = stringEvaluator(\n    flatStyle,\n    prefix + 'baseline',\n    context,\n  );\n\n  const evaluateKeepUpright = booleanEvaluator(\n    flatStyle,\n    prefix + 'keep-upright',\n    context,\n  );\n\n  const evaluatePadding = numberArrayEvaluator(\n    flatStyle,\n    prefix + 'padding',\n    context,\n  );\n\n  // The following properties are not currently settable\n  const declutterMode = optionalDeclutterMode(\n    flatStyle,\n    prefix + 'declutter-mode',\n  );\n\n  const text = new Text({declutterMode});\n\n  return function (context) {\n    text.setText(evaluateValue(context));\n\n    if (evaluateFill) {\n      text.setFill(evaluateFill(context));\n    }\n\n    if (evaluateBackgroundFill) {\n      text.setBackgroundFill(evaluateBackgroundFill(context));\n    }\n\n    if (evaluateStroke) {\n      text.setStroke(evaluateStroke(context));\n    }\n\n    if (evaluateBackgroundStroke) {\n      text.setBackgroundStroke(evaluateBackgroundStroke(context));\n    }\n\n    if (evaluateFont) {\n      text.setFont(evaluateFont(context));\n    }\n\n    if (evaluateMaxAngle) {\n      text.setMaxAngle(evaluateMaxAngle(context));\n    }\n\n    if (evaluateOffsetX) {\n      text.setOffsetX(evaluateOffsetX(context));\n    }\n\n    if (evaluateOffsetY) {\n      text.setOffsetY(evaluateOffsetY(context));\n    }\n\n    if (evaluateOverflow) {\n      text.setOverflow(evaluateOverflow(context));\n    }\n\n    if (evaluatePlacement) {\n      const placement = evaluatePlacement(context);\n      if (placement !== 'point' && placement !== 'line') {\n        throw new Error('Expected point or line for text-placement');\n      }\n      text.setPlacement(placement);\n    }\n\n    if (evaluateRepeat) {\n      text.setRepeat(evaluateRepeat(context));\n    }\n\n    if (evaluateScale) {\n      text.setScale(evaluateScale(context));\n    }\n\n    if (evaluateRotateWithView) {\n      text.setRotateWithView(evaluateRotateWithView(context));\n    }\n\n    if (evaluateRotation) {\n      text.setRotation(evaluateRotation(context));\n    }\n\n    if (evaluateAlign) {\n      const textAlign = evaluateAlign(context);\n      if (\n        textAlign !== 'left' &&\n        textAlign !== 'center' &&\n        textAlign !== 'right' &&\n        textAlign !== 'end' &&\n        textAlign !== 'start'\n      ) {\n        throw new Error(\n          'Expected left, right, center, start, or end for text-align',\n        );\n      }\n      text.setTextAlign(textAlign);\n    }\n\n    if (evaluateJustify) {\n      const justify = evaluateJustify(context);\n      if (justify !== 'left' && justify !== 'right' && justify !== 'center') {\n        throw new Error('Expected left, right, or center for text-justify');\n      }\n      text.setJustify(justify);\n    }\n\n    if (evaluateBaseline) {\n      const textBaseline = evaluateBaseline(context);\n      if (\n        textBaseline !== 'bottom' &&\n        textBaseline !== 'top' &&\n        textBaseline !== 'middle' &&\n        textBaseline !== 'alphabetic' &&\n        textBaseline !== 'hanging'\n      ) {\n        throw new Error(\n          'Expected bottom, top, middle, alphabetic, or hanging for text-baseline',\n        );\n      }\n      text.setTextBaseline(textBaseline);\n    }\n\n    if (evaluatePadding) {\n      text.setPadding(evaluatePadding(context));\n    }\n\n    if (evaluateKeepUpright) {\n      text.setKeepUpright(evaluateKeepUpright(context));\n    }\n\n    return text;\n  };\n}\n\n/**\n * @typedef {function(EvaluationContext):import(\"../../style/Image.js\").default} ImageEvaluator\n */\n\n/**\n * @param {FlatStyle} flatStyle The flat style.\n * @param {ParsingContext} context The parsing context.\n * @return {ImageEvaluator?} A function that evaluates to an image symbolizer.\n */\nfunction buildImage(flatStyle, context) {\n  if ('icon-src' in flatStyle) {\n    return buildIcon(flatStyle, context);\n  }\n\n  if ('shape-points' in flatStyle) {\n    return buildShape(flatStyle, context);\n  }\n\n  if ('circle-radius' in flatStyle) {\n    return buildCircle(flatStyle, context);\n  }\n\n  return null;\n}\n\n/**\n * @param {FlatStyle} flatStyle The flat style.\n * @param {ParsingContext} context The parsing context.\n * @return {ImageEvaluator} A function that evaluates to an image symbolizer.\n */\nfunction buildIcon(flatStyle, context) {\n  const prefix = 'icon-';\n\n  // required property\n  const srcName = prefix + 'src';\n  const src = requireString(flatStyle[srcName], srcName);\n\n  // settable properties\n  const evaluateAnchor = coordinateEvaluator(\n    flatStyle,\n    prefix + 'anchor',\n    context,\n  );\n\n  const evaluateScale = sizeLikeEvaluator(flatStyle, prefix + 'scale', context);\n\n  const evaluateOpacity = numberEvaluator(\n    flatStyle,\n    prefix + 'opacity',\n    context,\n  );\n\n  const evaluateDisplacement = coordinateEvaluator(\n    flatStyle,\n    prefix + 'displacement',\n    context,\n  );\n\n  const evaluateRotation = numberEvaluator(\n    flatStyle,\n    prefix + 'rotation',\n    context,\n  );\n\n  const evaluateRotateWithView = booleanEvaluator(\n    flatStyle,\n    prefix + 'rotate-with-view',\n    context,\n  );\n\n  // the remaining symbolizer properties are not currently settable\n  const anchorOrigin = optionalIconOrigin(flatStyle, prefix + 'anchor-origin');\n  const anchorXUnits = optionalIconAnchorUnits(\n    flatStyle,\n    prefix + 'anchor-x-units',\n  );\n  const anchorYUnits = optionalIconAnchorUnits(\n    flatStyle,\n    prefix + 'anchor-y-units',\n  );\n  const colorValue = getExpressionValue(flatStyle, prefix + 'color');\n  let color;\n  let evaluateColor = null;\n  if (colorValue !== undefined) {\n    const isColorExpression =\n      Array.isArray(colorValue) &&\n      colorValue.length > 0 &&\n      typeof colorValue[0] === 'string';\n    if (isColorExpression) {\n      evaluateColor = colorLikeEvaluator(flatStyle, prefix + 'color', context);\n    } else {\n      color = requireColorLike(colorValue, prefix + 'color');\n    }\n  }\n  const crossOrigin = optionalString(flatStyle, prefix + 'cross-origin');\n  const offset = optionalNumberArray(flatStyle, prefix + 'offset');\n  const offsetOrigin = optionalIconOrigin(flatStyle, prefix + 'offset-origin');\n  const width = optionalNumber(flatStyle, prefix + 'width');\n  const height = optionalNumber(flatStyle, prefix + 'height');\n  const size = optionalSize(flatStyle, prefix + 'size');\n  const declutterMode = optionalDeclutterMode(\n    flatStyle,\n    prefix + 'declutter-mode',\n  );\n\n  const iconOptions = {\n    src,\n    anchorOrigin,\n    anchorXUnits,\n    anchorYUnits,\n    crossOrigin,\n    offset,\n    offsetOrigin,\n    height,\n    width,\n    size,\n    declutterMode,\n  };\n\n  let icon = null;\n\n  return function (context) {\n    if (!icon) {\n      // lazily create the icon to allow for expression evaluation\n      const initialColor = evaluateColor ? evaluateColor(context) : color;\n      icon = new Icon(\n        initialColor !== undefined\n          ? Object.assign({}, iconOptions, {color: initialColor})\n          : Object.assign({}, iconOptions),\n      );\n    } else if (evaluateColor) {\n      icon.setColor(evaluateColor(context));\n    }\n    if (evaluateOpacity) {\n      icon.setOpacity(evaluateOpacity(context));\n    }\n\n    if (evaluateDisplacement) {\n      icon.setDisplacement(evaluateDisplacement(context));\n    }\n\n    if (evaluateRotation) {\n      icon.setRotation(evaluateRotation(context));\n    }\n\n    if (evaluateRotateWithView) {\n      icon.setRotateWithView(evaluateRotateWithView(context));\n    }\n\n    if (evaluateScale) {\n      icon.setScale(evaluateScale(context));\n    }\n\n    if (evaluateAnchor) {\n      icon.setAnchor(evaluateAnchor(context));\n    }\n    return icon;\n  };\n}\n\n/**\n * @param {FlatStyle} flatStyle The flat style.\n * @param {ParsingContext} context The parsing context.\n * @return {ImageEvaluator} A function that evaluates to an icon symbolizer.\n */\nfunction buildShape(flatStyle, context) {\n  const prefix = 'shape-';\n\n  // required property\n  const pointsName = prefix + 'points';\n  const radiusName = prefix + 'radius';\n  const points = requireNumber(flatStyle[pointsName], pointsName);\n  if (!(radiusName in flatStyle)) {\n    throw new Error(`Expected a number for ${radiusName}`);\n  }\n  const evaluateRadius = numberEvaluator(flatStyle, radiusName, context);\n  const initialRadius =\n    typeof flatStyle[radiusName] === 'number' ? flatStyle[radiusName] : 5;\n  const radius2Name = prefix + 'radius2';\n  const evaluateRadius2 = numberEvaluator(flatStyle, radius2Name, context);\n  const initialRadius2 =\n    typeof flatStyle[radius2Name] === 'number'\n      ? flatStyle[radius2Name]\n      : undefined;\n\n  // settable properties\n  const evaluateFill = buildFill(flatStyle, prefix, context);\n  const evaluateStroke = buildStroke(flatStyle, prefix, context);\n  const evaluateScale = sizeLikeEvaluator(flatStyle, prefix + 'scale', context);\n  const evaluateDisplacement = coordinateEvaluator(\n    flatStyle,\n    prefix + 'displacement',\n    context,\n  );\n  const evaluateRotation = numberEvaluator(\n    flatStyle,\n    prefix + 'rotation',\n    context,\n  );\n  const evaluateRotateWithView = booleanEvaluator(\n    flatStyle,\n    prefix + 'rotate-with-view',\n    context,\n  );\n\n  // the remaining properties are not currently settable\n  const angle = optionalNumber(flatStyle, prefix + 'angle');\n  const declutterMode = optionalDeclutterMode(\n    flatStyle,\n    prefix + 'declutter-mode',\n  );\n\n  const shape = new RegularShape({\n    points,\n    radius: initialRadius,\n    radius2: initialRadius2,\n    angle,\n    declutterMode,\n  });\n\n  return function (context) {\n    if (evaluateRadius) {\n      shape.setRadius(evaluateRadius(context));\n    }\n    if (evaluateRadius2) {\n      shape.setRadius2(evaluateRadius2(context));\n    }\n    if (evaluateFill) {\n      shape.setFill(evaluateFill(context));\n    }\n    if (evaluateStroke) {\n      shape.setStroke(evaluateStroke(context));\n    }\n    if (evaluateDisplacement) {\n      shape.setDisplacement(evaluateDisplacement(context));\n    }\n    if (evaluateRotation) {\n      shape.setRotation(evaluateRotation(context));\n    }\n    if (evaluateRotateWithView) {\n      shape.setRotateWithView(evaluateRotateWithView(context));\n    }\n    if (evaluateScale) {\n      shape.setScale(evaluateScale(context));\n    }\n\n    return shape;\n  };\n}\n\n/**\n * @param {FlatStyle} flatStyle The flat style.\n * @param {ParsingContext} context The parsing context.\n * @return {ImageEvaluator} A function that evaluates to a circle symbolizer.\n */\nfunction buildCircle(flatStyle, context) {\n  const prefix = 'circle-';\n\n  // settable properties\n  const evaluateFill = buildFill(flatStyle, prefix, context);\n  const evaluateStroke = buildStroke(flatStyle, prefix, context);\n  const evaluateRadius = numberEvaluator(flatStyle, prefix + 'radius', context);\n  const evaluateScale = sizeLikeEvaluator(flatStyle, prefix + 'scale', context);\n  const evaluateDisplacement = coordinateEvaluator(\n    flatStyle,\n    prefix + 'displacement',\n    context,\n  );\n  const evaluateRotation = numberEvaluator(\n    flatStyle,\n    prefix + 'rotation',\n    context,\n  );\n  const evaluateRotateWithView = booleanEvaluator(\n    flatStyle,\n    prefix + 'rotate-with-view',\n    context,\n  );\n\n  // the remaining properties are not currently settable\n  const declutterMode = optionalDeclutterMode(\n    flatStyle,\n    prefix + 'declutter-mode',\n  );\n\n  const circle = new Circle({\n    radius: 5, // this is arbitrary, but required - the evaluated radius is used below\n    declutterMode,\n  });\n\n  return function (context) {\n    if (evaluateRadius) {\n      circle.setRadius(evaluateRadius(context));\n    }\n    if (evaluateFill) {\n      circle.setFill(evaluateFill(context));\n    }\n    if (evaluateStroke) {\n      circle.setStroke(evaluateStroke(context));\n    }\n    if (evaluateDisplacement) {\n      circle.setDisplacement(evaluateDisplacement(context));\n    }\n    if (evaluateRotation) {\n      circle.setRotation(evaluateRotation(context));\n    }\n    if (evaluateRotateWithView) {\n      circle.setRotateWithView(evaluateRotateWithView(context));\n    }\n    if (evaluateScale) {\n      circle.setScale(evaluateScale(context));\n    }\n\n    return circle;\n  };\n}\n\n/**\n * @param {FlatStyle} flatStyle The flat style.\n * @param {string} name The property name.\n * @return {any|undefined} The encoded value, or undefined if not provided.\n */\nfunction getExpressionValue(flatStyle, name) {\n  if (!(name in flatStyle)) {\n    return undefined;\n  }\n  const value = flatStyle[name];\n  return value === undefined ? undefined : value;\n}\n\n/**\n * @param {FlatStyle} flatStyle The flat style.\n * @param {string} name The property name.\n * @param {ParsingContext} context The parsing context.\n * @return {import('../../expr/cpu.js').NumberEvaluator|undefined} The expression evaluator or undefined.\n */\nfunction numberEvaluator(flatStyle, name, context) {\n  const encoded = getExpressionValue(flatStyle, name);\n  if (encoded === undefined) {\n    return undefined;\n  }\n  const evaluator = buildExpression(encoded, NumberType, context);\n  return function (context) {\n    return requireNumber(evaluator(context), name);\n  };\n}\n\n/**\n * @param {FlatStyle} flatStyle The flat style.\n * @param {string} name The property name.\n * @param {ParsingContext} context The parsing context.\n * @return {import('../../expr/cpu.js').StringEvaluator?} The expression evaluator.\n */\nfunction stringEvaluator(flatStyle, name, context) {\n  const encoded = getExpressionValue(flatStyle, name);\n  if (encoded === undefined) {\n    return null;\n  }\n  const evaluator = buildExpression(encoded, StringType, context);\n  return function (context) {\n    return requireString(evaluator(context), name);\n  };\n}\n\nfunction patternEvaluator(flatStyle, prefix, context) {\n  const srcEvaluator = stringEvaluator(\n    flatStyle,\n    prefix + 'pattern-src',\n    context,\n  );\n  const offsetEvaluator = sizeEvaluator(\n    flatStyle,\n    prefix + 'pattern-offset',\n    context,\n  );\n  const patternSizeEvaluator = sizeEvaluator(\n    flatStyle,\n    prefix + 'pattern-size',\n    context,\n  );\n  const colorEvaluator = colorLikeEvaluator(\n    flatStyle,\n    prefix + 'color',\n    context,\n  );\n  return function (context) {\n    return {\n      src: srcEvaluator(context),\n      offset: offsetEvaluator && offsetEvaluator(context),\n      size: patternSizeEvaluator && patternSizeEvaluator(context),\n      color: colorEvaluator && colorEvaluator(context),\n    };\n  };\n}\n\n/**\n * @param {FlatStyle} flatStyle The flat style.\n * @param {string} name The property name.\n * @param {ParsingContext} context The parsing context.\n * @return {import('../../expr/cpu.js').BooleanEvaluator?} The expression evaluator.\n */\nfunction booleanEvaluator(flatStyle, name, context) {\n  const encoded = getExpressionValue(flatStyle, name);\n  if (encoded === undefined) {\n    return null;\n  }\n  const evaluator = buildExpression(encoded, BooleanType, context);\n  return function (context) {\n    const value = evaluator(context);\n    if (typeof value !== 'boolean') {\n      throw new Error(`Expected a boolean for ${name}`);\n    }\n    return value;\n  };\n}\n\n/**\n * @param {FlatStyle} flatStyle The flat style.\n * @param {string} name The property name.\n * @param {ParsingContext} context The parsing context.\n * @return {import('../../expr/cpu.js').ColorLikeEvaluator?} The expression evaluator.\n */\nfunction colorLikeEvaluator(flatStyle, name, context) {\n  const encoded = getExpressionValue(flatStyle, name);\n  if (encoded === undefined) {\n    return null;\n  }\n  const evaluator = buildExpression(encoded, ColorType, context);\n  return function (context) {\n    return requireColorLike(evaluator(context), name);\n  };\n}\n\n/**\n * @param {FlatStyle} flatStyle The flat style.\n * @param {string} name The property name.\n * @param {ParsingContext} context The parsing context.\n * @return {import('../../expr/cpu.js').NumberArrayEvaluator?} The expression evaluator.\n */\nfunction numberArrayEvaluator(flatStyle, name, context) {\n  const encoded = getExpressionValue(flatStyle, name);\n  if (encoded === undefined) {\n    return null;\n  }\n  if (\n    Array.isArray(encoded) &&\n    (encoded.length === 0 || typeof encoded[0] !== 'string')\n  ) {\n    /** @type {Array<import('../../expr/cpu.js').NumberEvaluator>} */\n    const evaluators = encoded.map((value, index) => {\n      if (typeof value === 'number') {\n        return () => value;\n      }\n      const evaluator = buildExpression(value, NumberType, context);\n      return function (context) {\n        return requireNumber(evaluator(context), `${name}[${index}]`);\n      };\n    });\n    return function (context) {\n      const array = new Array(evaluators.length);\n      for (let i = 0; i < evaluators.length; ++i) {\n        array[i] = evaluators[i](context);\n      }\n      return array;\n    };\n  }\n  const evaluator = buildExpression(encoded, NumberArrayType, context);\n  return function (context) {\n    return requireNumberArray(evaluator(context), name);\n  };\n}\n\n/**\n * @param {FlatStyle} flatStyle The flat style.\n * @param {string} name The property name.\n * @param {ParsingContext} context The parsing context.\n * @return {import('../../expr/cpu.js').CoordinateEvaluator?} The expression evaluator.\n */\nfunction coordinateEvaluator(flatStyle, name, context) {\n  const encoded = getExpressionValue(flatStyle, name);\n  if (encoded === undefined) {\n    return null;\n  }\n  const evaluator = buildExpression(encoded, NumberArrayType, context);\n  return function (context) {\n    const array = requireNumberArray(evaluator(context), name);\n    if (array.length !== 2) {\n      throw new Error(`Expected two numbers for ${name}`);\n    }\n    return array;\n  };\n}\n\n/**\n * @param {FlatStyle} flatStyle The flat style.\n * @param {string} name The property name.\n * @param {ParsingContext} context The parsing context.\n * @return {import('../../expr/cpu.js').SizeEvaluator?} The expression evaluator.\n */\nfunction sizeEvaluator(flatStyle, name, context) {\n  const encoded = getExpressionValue(flatStyle, name);\n  if (encoded === undefined) {\n    return null;\n  }\n  const evaluator = buildExpression(encoded, NumberArrayType, context);\n  return function (context) {\n    return requireSize(evaluator(context), name);\n  };\n}\n\n/**\n * @param {FlatStyle} flatStyle The flat style.\n * @param {string} name The property name.\n * @param {ParsingContext} context The parsing context.\n * @return {import('../../expr/cpu.js').SizeLikeEvaluator?} The expression evaluator.\n */\nfunction sizeLikeEvaluator(flatStyle, name, context) {\n  const encoded = getExpressionValue(flatStyle, name);\n  if (encoded === undefined) {\n    return null;\n  }\n  const evaluator = buildExpression(\n    encoded,\n    NumberArrayType | NumberType,\n    context,\n  );\n  return function (context) {\n    return requireSizeLike(evaluator(context), name);\n  };\n}\n\n/**\n * @param {FlatStyle} flatStyle The flat style.\n * @param {string} property The symbolizer property.\n * @return {number|undefined} A number or undefined.\n */\nfunction optionalNumber(flatStyle, property) {\n  const value = flatStyle[property];\n  if (value === undefined) {\n    return undefined;\n  }\n  if (typeof value !== 'number') {\n    throw new Error(`Expected a number for ${property}`);\n  }\n  return value;\n}\n\n/**\n * @param {FlatStyle} flatStyle The flat style.\n * @param {string} property The symbolizer property.\n * @return {import(\"../../size.js\").Size|undefined} A size or undefined.\n */\nfunction optionalSize(flatStyle, property) {\n  const encoded = flatStyle[property];\n  if (encoded === undefined) {\n    return undefined;\n  }\n  if (typeof encoded === 'number') {\n    return toSize(encoded);\n  }\n  if (!Array.isArray(encoded)) {\n    throw new Error(`Expected a number or size array for ${property}`);\n  }\n  if (\n    encoded.length !== 2 ||\n    typeof encoded[0] !== 'number' ||\n    typeof encoded[1] !== 'number'\n  ) {\n    throw new Error(`Expected a number or size array for ${property}`);\n  }\n  return encoded;\n}\n\n/**\n * @param {FlatStyle} flatStyle The flat style.\n * @param {string} property The symbolizer property.\n * @return {string|undefined} A string or undefined.\n */\nfunction optionalString(flatStyle, property) {\n  const encoded = flatStyle[property];\n  if (encoded === undefined) {\n    return undefined;\n  }\n  if (typeof encoded !== 'string') {\n    throw new Error(`Expected a string for ${property}`);\n  }\n  return encoded;\n}\n\n/**\n * @param {FlatStyle} flatStyle The flat style.\n * @param {string} property The symbolizer property.\n * @return {import(\"../../style/Icon.js\").IconOrigin|undefined} An icon origin or undefined.\n */\nfunction optionalIconOrigin(flatStyle, property) {\n  const encoded = flatStyle[property];\n  if (encoded === undefined) {\n    return undefined;\n  }\n  if (\n    encoded !== 'bottom-left' &&\n    encoded !== 'bottom-right' &&\n    encoded !== 'top-left' &&\n    encoded !== 'top-right'\n  ) {\n    throw new Error(\n      `Expected bottom-left, bottom-right, top-left, or top-right for ${property}`,\n    );\n  }\n  return encoded;\n}\n\n/**\n * @param {FlatStyle} flatStyle The flat style.\n * @param {string} property The symbolizer property.\n * @return {import(\"../../style/Icon.js\").IconAnchorUnits|undefined} Icon anchor units or undefined.\n */\nfunction optionalIconAnchorUnits(flatStyle, property) {\n  const encoded = flatStyle[property];\n  if (encoded === undefined) {\n    return undefined;\n  }\n  if (encoded !== 'pixels' && encoded !== 'fraction') {\n    throw new Error(`Expected pixels or fraction for ${property}`);\n  }\n  return encoded;\n}\n\n/**\n * @param {FlatStyle} flatStyle The flat style.\n * @param {string} property The symbolizer property.\n * @return {Array<number>|undefined} An array of numbers or undefined.\n */\nfunction optionalNumberArray(flatStyle, property) {\n  const encoded = flatStyle[property];\n  if (encoded === undefined) {\n    return undefined;\n  }\n  return requireNumberArray(encoded, property);\n}\n\n/**\n * @param {FlatStyle} flatStyle The flat style.\n * @param {string} property The symbolizer property.\n * @return {import('../../style/Style.js').DeclutterMode} Icon declutter mode.\n */\nfunction optionalDeclutterMode(flatStyle, property) {\n  const encoded = flatStyle[property];\n  if (encoded === undefined) {\n    return undefined;\n  }\n  if (typeof encoded !== 'string') {\n    throw new Error(`Expected a string for ${property}`);\n  }\n  if (encoded !== 'declutter' && encoded !== 'obstacle' && encoded !== 'none') {\n    throw new Error(`Expected declutter, obstacle, or none for ${property}`);\n  }\n  return encoded;\n}\n\n/**\n * @param {any} value The value.\n * @param {string} property The property.\n * @return {Array<number>} An array of numbers.\n */\nfunction requireNumberArray(value, property) {\n  if (!Array.isArray(value)) {\n    throw new Error(`Expected an array for ${property}`);\n  }\n  const length = value.length;\n  for (let i = 0; i < length; ++i) {\n    if (typeof value[i] !== 'number') {\n      throw new Error(`Expected an array of numbers for ${property}`);\n    }\n  }\n  return value;\n}\n\n/**\n * @param {any} value The value.\n * @param {string} property The property.\n * @return {string} A string.\n */\nfunction requireString(value, property) {\n  if (typeof value !== 'string') {\n    throw new Error(`Expected a string for ${property}`);\n  }\n  return value;\n}\n\n/**\n * @param {any} value The value.\n * @param {string} property The property.\n * @return {number} A number.\n */\nfunction requireNumber(value, property) {\n  if (typeof value !== 'number') {\n    throw new Error(`Expected a number for ${property}`);\n  }\n  return value;\n}\n\n/**\n * @param {any} value The value.\n * @param {string} property The property.\n * @return {Array<number>|string} A color.\n */\nfunction requireColorLike(value, property) {\n  if (typeof value === 'string') {\n    return value;\n  }\n  const array = requireNumberArray(value, property);\n  const length = array.length;\n  if (length < 3 || length > 4) {\n    throw new Error(`Expected a color with 3 or 4 values for ${property}`);\n  }\n  return array;\n}\n\n/**\n * @param {any} value The value.\n * @param {string} property The property.\n * @return {Array<number>} A number or an array of two numbers.\n */\nfunction requireSize(value, property) {\n  const size = requireNumberArray(value, property);\n  if (size.length !== 2) {\n    throw new Error(`Expected an array of two numbers for ${property}`);\n  }\n  return size;\n}\n\n/**\n * @param {any} value The value.\n * @param {string} property The property.\n * @return {number|Array<number>} A number or an array of two numbers.\n */\nfunction requireSizeLike(value, property) {\n  if (typeof value === 'number') {\n    return value;\n  }\n  return requireSize(value, property);\n}\n", "/**\n * @module ol/layer/BaseVector\n */\nimport RBush from 'rbush';\nimport {\n  flatStylesToStyleFunction,\n  rulesToStyleFunction,\n} from '../render/canvas/style.js';\nimport Style, {\n  createDefaultStyle,\n  toFunction as toStyleFunction,\n} from '../style/Style.js';\nimport Layer from './Layer.js';\n\n/***\n * @template T\n * @typedef {T extends import(\"../source/Vector.js\").default<infer U extends import(\"../Feature.js\").FeatureLike> ? U : never} ExtractedFeatureType\n */\n\n/**\n * @template {import('../Feature.js').FeatureLike} FeatureType\n * @template {import(\"../source/Vector.js\").default<FeatureType>|import(\"../source/VectorTile.js\").default<FeatureType>} VectorSourceType<FeatureType>\n * @typedef {Object} Options\n * @property {string} [className='ol-layer'] A CSS class name to set to the layer element.\n * @property {number} [opacity=1] Opacity (0, 1).\n * @property {boolean} [visible=true] Visibility.\n * @property {import(\"../extent.js\").Extent} [extent] The bounding extent for layer rendering.  The layer will not be\n * rendered outside of this extent.\n * @property {number} [zIndex] The z-index for layer rendering.  At rendering time, the layers\n * will be ordered, first by Z-index and then by position. When `undefined`, a `zIndex` of 0 is assumed\n * for layers that are added to the map's `layers` collection, or `Infinity` when the layer's `setMap()`\n * method was used.\n * @property {number} [minResolution] The minimum resolution (inclusive) at which this layer will be\n * visible.\n * @property {number} [maxResolution] The maximum resolution (exclusive) below which this layer will\n * be visible.\n * @property {number} [minZoom] The minimum view zoom level (exclusive) above which this layer will be\n * visible.\n * @property {number} [maxZoom] The maximum view zoom level (inclusive) at which this layer will\n * be visible.\n * @property {import(\"../render.js\").OrderFunction} [renderOrder] Render order. Function to be used when sorting\n * features before rendering. By default features are drawn in the order that they are created. Use\n * `null` to avoid the sort, but get an undefined draw order.\n * @property {number} [renderBuffer=100] The buffer in pixels around the viewport extent used by the\n * renderer when getting features from the vector source for the rendering or hit-detection.\n * Recommended value: the size of the largest symbol, line width or label.\n * @property {VectorSourceType} [source] Source.\n * @property {import(\"../Map.js\").default} [map] Sets the layer as overlay on a map. The map will not manage\n * this layer in its layers collection, and the layer will be rendered on top. This is useful for\n * temporary layers. The standard way to add a layer to a map and have it managed by the map is to\n * use [map.addLayer()]{@link import(\"../Map.js\").default#addLayer}.\n * @property {boolean|string|number} [declutter=false] Declutter images and text. Any truthy value will enable\n * decluttering. Within a layer, a feature rendered before another has higher priority. All layers with the\n * same `declutter` value will be decluttered together. The priority is determined by the drawing order of the\n * layers with the same `declutter` value. Higher in the layer stack means higher priority. To declutter distinct\n * layers or groups of layers separately, use different truthy values for `declutter`.\n * @property {import(\"../style/Style.js\").StyleLike|import(\"../style/flat.js\").FlatStyleLike|null} [style] Layer style. When set to `null`, only\n * features that have their own style will be rendered. See {@link module:ol/style/Style~Style} for the default style\n * which will be used if this is not set.\n * @property {import(\"./Base.js\").BackgroundColor} [background] Background color for the layer. If not specified, no background\n * will be rendered.\n * @property {boolean} [updateWhileAnimating=false] When set to `true`, feature batches will\n * be recreated during animations. This means that no vectors will be shown clipped, but the\n * setting will have a performance impact for large amounts of vector data. When set to `false`,\n * batches will be recreated when no animation is active.\n * @property {boolean} [updateWhileInteracting=false] When set to `true`, feature batches will\n * be recreated during interactions. See also `updateWhileAnimating`.\n * @property {Object<string, *>} [properties] Arbitrary observable properties. Can be accessed with `#get()` and `#set()`.\n */\n\n/**\n * @enum {string}\n * @private\n */\nconst Property = {\n  RENDER_ORDER: 'renderOrder',\n};\n\n/**\n * @classdesc\n * Vector data that is rendered client-side.\n * Note that any property set in the options is set as a {@link module:ol/Object~BaseObject}\n * property on the layer object; for example, setting `title: 'My Title'` in the\n * options means that `title` is observable, and has get/set accessors.\n *\n * @template {import('../Feature.js').FeatureLike} FeatureType\n * @template {import(\"../source/Vector.js\").default<FeatureType>|import(\"../source/VectorTile.js\").default<FeatureType>} VectorSourceType<FeatureType>\n * @extends {Layer<VectorSourceType, RendererType>}\n * @template {import(\"../renderer/canvas/VectorLayer.js\").default|import(\"../renderer/canvas/VectorTileLayer.js\").default|import(\"../renderer/canvas/VectorImageLayer.js\").default|import(\"../renderer/webgl/VectorLayer.js\").default|import(\"../renderer/webgl/PointsLayer.js\").default} RendererType\n * @api\n */\nclass BaseVectorLayer extends Layer {\n  /**\n   * @param {Options<FeatureType, VectorSourceType>} [options] Options.\n   */\n  constructor(options) {\n    options = options ? options : {};\n\n    const baseOptions = Object.assign({}, options);\n\n    delete baseOptions.style;\n    delete baseOptions.renderBuffer;\n    delete baseOptions.updateWhileAnimating;\n    delete baseOptions.updateWhileInteracting;\n    super(baseOptions);\n\n    /**\n     * @private\n     * @type {string}\n     */\n    this.declutter_ = options.declutter ? String(options.declutter) : undefined;\n\n    /**\n     * @type {number}\n     * @private\n     */\n    this.renderBuffer_ =\n      options.renderBuffer !== undefined ? options.renderBuffer : 100;\n\n    /**\n     * User provided style.\n     * @type {import(\"../style/Style.js\").StyleLike|import(\"../style/flat.js\").FlatStyleLike}\n     * @private\n     */\n    this.style_ = null;\n\n    /**\n     * Style function for use within the library.\n     * @type {import(\"../style/Style.js\").StyleFunction|undefined}\n     * @private\n     */\n    this.styleFunction_ = undefined;\n\n    this.setStyle(options.style);\n\n    /**\n     * @type {boolean}\n     * @private\n     */\n    this.updateWhileAnimating_ =\n      options.updateWhileAnimating !== undefined\n        ? options.updateWhileAnimating\n        : false;\n\n    /**\n     * @type {boolean}\n     * @private\n     */\n    this.updateWhileInteracting_ =\n      options.updateWhileInteracting !== undefined\n        ? options.updateWhileInteracting\n        : false;\n  }\n\n  /**\n   * @return {string} Declutter group.\n   * @override\n   */\n  getDeclutter() {\n    return this.declutter_;\n  }\n\n  /**\n   * Get the topmost feature that intersects the given pixel on the viewport. Returns a promise\n   * that resolves with an array of features. The array will either contain the topmost feature\n   * when a hit was detected, or it will be empty.\n   *\n   * The hit detection algorithm used for this method is optimized for performance, but is less\n   * accurate than the one used in [map.getFeaturesAtPixel()]{@link import(\"../Map.js\").default#getFeaturesAtPixel}.\n   * Text is not considered, and icons are only represented by their bounding box instead of the exact\n   * image.\n   *\n   * @param {import(\"../pixel.js\").Pixel} pixel Pixel.\n   * @return {Promise<Array<import(\"../Feature.js\").FeatureLike>>} Promise that resolves with an array of features.\n   * @api\n   * @override\n   */\n  getFeatures(pixel) {\n    return super.getFeatures(pixel);\n  }\n\n  /**\n   * @return {number|undefined} Render buffer.\n   */\n  getRenderBuffer() {\n    return this.renderBuffer_;\n  }\n\n  /**\n   * @return {import(\"../render.js\").OrderFunction|null|undefined} Render order.\n   */\n  getRenderOrder() {\n    return /** @type {import(\"../render.js\").OrderFunction|null|undefined} */ (\n      this.get(Property.RENDER_ORDER)\n    );\n  }\n\n  /**\n   * Get the style for features.  This returns whatever was passed to the `style`\n   * option at construction or to the `setStyle` method.\n   * @return {import(\"../style/Style.js\").StyleLike|import(\"../style/flat.js\").FlatStyleLike|null|undefined} Layer style.\n   * @api\n   */\n  getStyle() {\n    return this.style_;\n  }\n\n  /**\n   * Get the style function.\n   * @return {import(\"../style/Style.js\").StyleFunction|undefined} Layer style function.\n   * @api\n   */\n  getStyleFunction() {\n    return this.styleFunction_;\n  }\n\n  /**\n   * @return {boolean} Whether the rendered layer should be updated while\n   *     animating.\n   */\n  getUpdateWhileAnimating() {\n    return this.updateWhileAnimating_;\n  }\n\n  /**\n   * @return {boolean} Whether the rendered layer should be updated while\n   *     interacting.\n   */\n  getUpdateWhileInteracting() {\n    return this.updateWhileInteracting_;\n  }\n\n  /**\n   * Render declutter items for this layer\n   * @param {import(\"../Map.js\").FrameState} frameState Frame state.\n   * @param {import(\"../layer/Layer.js\").State} layerState Layer state.\n   * @override\n   */\n  renderDeclutter(frameState, layerState) {\n    const declutterGroup = this.getDeclutter();\n    if (declutterGroup in frameState.declutter === false) {\n      frameState.declutter[declutterGroup] = new RBush(9);\n    }\n    this.getRenderer().renderDeclutter(frameState, layerState);\n  }\n\n  /**\n   * @param {import(\"../render.js\").OrderFunction|null|undefined} renderOrder\n   *     Render order.\n   */\n  setRenderOrder(renderOrder) {\n    this.set(Property.RENDER_ORDER, renderOrder);\n  }\n\n  /**\n   * Set the style for features.  This can be a single style object, an array\n   * of styles, or a function that takes a feature and resolution and returns\n   * an array of styles. If set to `null`, the layer has no style (a `null` style),\n   * so only features that have their own styles will be rendered in the layer. Call\n   * `setStyle()` without arguments to reset to the default style. See\n   * [the ol/style/Style module]{@link module:ol/style/Style~Style} for information on the default style.\n   *\n   * If your layer has a static style, you can use [flat style]{@link module:ol/style/flat~FlatStyle} object\n   * literals instead of using the `Style` and symbolizer constructors (`Fill`, `Stroke`, etc.):\n   * ```js\n   * vectorLayer.setStyle({\n   *   \"fill-color\": \"yellow\",\n   *   \"stroke-color\": \"black\",\n   *   \"stroke-width\": 4\n   * })\n   * ```\n   *\n   * @param {import(\"../style/Style.js\").StyleLike|import(\"../style/flat.js\").FlatStyleLike|null} [style] Layer style.\n   * @api\n   */\n  setStyle(style) {\n    this.style_ = style === undefined ? createDefaultStyle : style;\n    const styleLike = toStyleLike(style);\n    this.styleFunction_ =\n      style === null ? undefined : toStyleFunction(styleLike);\n    this.changed();\n  }\n\n  /**\n   * @param {boolean|string|number} declutter Declutter images and text.\n   * @api\n   */\n  setDeclutter(declutter) {\n    this.declutter_ = declutter ? String(declutter) : undefined;\n    this.changed();\n  }\n}\n\n/**\n * Coerce the allowed style types into a shorter list of types.  Flat styles, arrays of flat\n * styles, and arrays of rules are converted into style functions.\n *\n * @param {import(\"../style/Style.js\").StyleLike|import(\"../style/flat.js\").FlatStyleLike|null} [style] Layer style.\n * @return {import(\"../style/Style.js\").StyleLike|null} The style.\n */\nfunction toStyleLike(style) {\n  if (style === undefined) {\n    return createDefaultStyle;\n  }\n  if (!style) {\n    return null;\n  }\n  if (typeof style === 'function') {\n    return style;\n  }\n  if (style instanceof Style) {\n    return style;\n  }\n  if (!Array.isArray(style)) {\n    return flatStylesToStyleFunction([style]);\n  }\n  if (style.length === 0) {\n    return [];\n  }\n\n  const length = style.length;\n  const first = style[0];\n\n  if (first instanceof Style) {\n    /**\n     * @type {Array<Style>}\n     */\n    const styles = new Array(length);\n    for (let i = 0; i < length; ++i) {\n      const candidate = style[i];\n      if (!(candidate instanceof Style)) {\n        throw new Error('Expected a list of style instances');\n      }\n      styles[i] = candidate;\n    }\n    return styles;\n  }\n\n  if ('style' in first) {\n    /**\n     * @type {Array<import(\"../style/flat.js\").Rule>}\n     */\n    const rules = new Array(length);\n    for (let i = 0; i < length; ++i) {\n      const candidate = style[i];\n      if (!('style' in candidate)) {\n        throw new Error('Expected a list of rules with a style property');\n      }\n      rules[i] = candidate;\n    }\n    return rulesToStyleFunction(rules);\n  }\n\n  const flatStyles =\n    /** @type {Array<import(\"../style/flat.js\").FlatStyle>} */ (style);\n  return flatStylesToStyleFunction(flatStyles);\n}\n\nexport default BaseVectorLayer;\n", "/**\n * @module ol/render/Event\n */\n\nimport Event from '../events/Event.js';\n\nclass RenderEvent extends Event {\n  /**\n   * @param {import(\"./EventType.js\").default} type Type.\n   * @param {import(\"../transform.js\").Transform} [inversePixelTransform] Transform for\n   *     CSS pixels to rendered pixels.\n   * @param {import(\"../Map.js\").FrameState} [frameState] Frame state.\n   * @param {?(CanvasRenderingContext2D|OffscreenCanvasRenderingContext2D|WebGLRenderingContext)} [context] Context.\n   */\n  constructor(type, inversePixelTransform, frameState, context) {\n    super(type);\n\n    /**\n     * Transform from CSS pixels (relative to the top-left corner of the map viewport)\n     * to rendered pixels on this event's `context`. Only available when a Canvas renderer is used, null otherwise.\n     * @type {import(\"../transform.js\").Transform|undefined}\n     * @api\n     */\n    this.inversePixelTransform = inversePixelTransform;\n\n    /**\n     * An object representing the current render frame state.\n     * @type {import(\"../Map.js\").FrameState|undefined}\n     * @api\n     */\n    this.frameState = frameState;\n\n    /**\n     * Canvas context. Not available when the event is dispatched by the map. For Canvas 2D layers,\n     * the context will be the 2D rendering context.  For WebGL layers, the context will be the WebGL\n     * context.\n     * @type {CanvasRenderingContext2D|OffscreenCanvasRenderingContext2D|WebGLRenderingContext|undefined}\n     * @api\n     */\n    this.context = context;\n  }\n}\n\nexport default RenderEvent;\n", "/**\n * @module ol/renderer/Map\n */\nimport Disposable from '../Disposable.js';\nimport {wrapX} from '../coordinate.js';\nimport {getWidth} from '../extent.js';\nimport {TRUE} from '../functions.js';\nimport {inView} from '../layer/Layer.js';\nimport {shared as iconImageCache} from '../style/IconImageCache.js';\nimport {compose as composeTransform, makeInverse} from '../transform.js';\nimport {abstract} from '../util.js';\n\n/**\n * @template T\n * @typedef HitMatch\n * @property {import(\"../Feature.js\").FeatureLike} feature Feature.\n * @property {import(\"../layer/Layer.js\").default} layer Layer.\n * @property {import(\"../geom/SimpleGeometry.js\").default} geometry Geometry.\n * @property {number} distanceSq Squared distance.\n * @property {import(\"./vector.js\").FeatureCallback<T>} callback Callback.\n */\n\n/**\n * @abstract\n */\nclass MapRenderer extends Disposable {\n  /**\n   * @param {import(\"../Map.js\").default} map Map.\n   */\n  constructor(map) {\n    super();\n\n    /**\n     * @private\n     * @type {import(\"../Map.js\").default}\n     */\n    this.map_ = map;\n  }\n\n  /**\n   * @abstract\n   * @param {import(\"../render/EventType.js\").default} type Event type.\n   * @param {import(\"../Map.js\").FrameState} frameState Frame state.\n   */\n  dispatchRenderEvent(type, frameState) {\n    abstract();\n  }\n\n  /**\n   * @param {import(\"../Map.js\").FrameState} frameState FrameState.\n   * @protected\n   */\n  calculateMatrices2D(frameState) {\n    const viewState = frameState.viewState;\n    const coordinateToPixelTransform = frameState.coordinateToPixelTransform;\n    const pixelToCoordinateTransform = frameState.pixelToCoordinateTransform;\n\n    composeTransform(\n      coordinateToPixelTransform,\n      frameState.size[0] / 2,\n      frameState.size[1] / 2,\n      1 / viewState.resolution,\n      -1 / viewState.resolution,\n      -viewState.rotation,\n      -viewState.center[0],\n      -viewState.center[1],\n    );\n\n    makeInverse(pixelToCoordinateTransform, coordinateToPixelTransform);\n  }\n\n  /**\n   * @param {import(\"../coordinate.js\").Coordinate} coordinate Coordinate.\n   * @param {import(\"../Map.js\").FrameState} frameState FrameState.\n   * @param {number} hitTolerance Hit tolerance in pixels.\n   * @param {boolean} checkWrapped Check for wrapped geometries.\n   * @param {import(\"./vector.js\").FeatureCallback<T>} callback Feature callback.\n   * @param {S} thisArg Value to use as `this` when executing `callback`.\n   * @param {function(this: U, import(\"../layer/Layer.js\").default): boolean} layerFilter Layer filter\n   *     function, only layers which are visible and for which this function\n   *     returns `true` will be tested for features.  By default, all visible\n   *     layers will be tested.\n   * @param {U} thisArg2 Value to use as `this` when executing `layerFilter`.\n   * @return {T|undefined} Callback result.\n   * @template S,T,U\n   */\n  forEachFeatureAtCoordinate(\n    coordinate,\n    frameState,\n    hitTolerance,\n    checkWrapped,\n    callback,\n    thisArg,\n    layerFilter,\n    thisArg2,\n  ) {\n    let result;\n    const viewState = frameState.viewState;\n\n    /**\n     * @param {boolean} managed Managed layer.\n     * @param {import(\"../Feature.js\").FeatureLike} feature Feature.\n     * @param {import(\"../layer/Layer.js\").default} layer Layer.\n     * @param {import(\"../geom/Geometry.js\").default} geometry Geometry.\n     * @return {T|undefined} Callback result.\n     */\n    function forEachFeatureAtCoordinate(managed, feature, layer, geometry) {\n      return callback.call(thisArg, feature, managed ? layer : null, geometry);\n    }\n\n    const projection = viewState.projection;\n\n    const translatedCoordinate = wrapX(coordinate.slice(), projection);\n    const offsets = [[0, 0]];\n    if (projection.canWrapX() && checkWrapped) {\n      const projectionExtent = projection.getExtent();\n      const worldWidth = getWidth(projectionExtent);\n      offsets.push([-worldWidth, 0], [worldWidth, 0]);\n    }\n\n    const layerStates = frameState.layerStatesArray;\n    const numLayers = layerStates.length;\n\n    const matches = /** @type {Array<HitMatch<T>>} */ ([]);\n    const tmpCoord = [];\n    for (let i = 0; i < offsets.length; i++) {\n      for (let j = numLayers - 1; j >= 0; --j) {\n        const layerState = layerStates[j];\n        const layer = layerState.layer;\n        if (\n          layer.hasRenderer() &&\n          inView(layerState, viewState) &&\n          layerFilter.call(thisArg2, layer)\n        ) {\n          const layerRenderer = layer.getRenderer();\n          const source = layer.getSource();\n          if (layerRenderer && source) {\n            const coordinates = source.getWrapX()\n              ? translatedCoordinate\n              : coordinate;\n            const callback = forEachFeatureAtCoordinate.bind(\n              null,\n              layerState.managed,\n            );\n            tmpCoord[0] = coordinates[0] + offsets[i][0];\n            tmpCoord[1] = coordinates[1] + offsets[i][1];\n            result = layerRenderer.forEachFeatureAtCoordinate(\n              tmpCoord,\n              frameState,\n              hitTolerance,\n              callback,\n              matches,\n            );\n          }\n          if (result) {\n            return result;\n          }\n        }\n      }\n    }\n    if (matches.length === 0) {\n      return undefined;\n    }\n    const order = 1 / matches.length;\n    matches.forEach((m, i) => (m.distanceSq += i * order));\n    matches.sort((a, b) => a.distanceSq - b.distanceSq);\n    matches.some((m) => {\n      return (result = m.callback(m.feature, m.layer, m.geometry));\n    });\n    return result;\n  }\n\n  /**\n   * @param {import(\"../coordinate.js\").Coordinate} coordinate Coordinate.\n   * @param {import(\"../Map.js\").FrameState} frameState FrameState.\n   * @param {number} hitTolerance Hit tolerance in pixels.\n   * @param {boolean} checkWrapped Check for wrapped geometries.\n   * @param {function(this: U, import(\"../layer/Layer.js\").default): boolean} layerFilter Layer filter\n   *     function, only layers which are visible and for which this function\n   *     returns `true` will be tested for features.  By default, all visible\n   *     layers will be tested.\n   * @param {U} thisArg Value to use as `this` when executing `layerFilter`.\n   * @return {boolean} Is there a feature at the given coordinate?\n   * @template U\n   */\n  hasFeatureAtCoordinate(\n    coordinate,\n    frameState,\n    hitTolerance,\n    checkWrapped,\n    layerFilter,\n    thisArg,\n  ) {\n    const hasFeature = this.forEachFeatureAtCoordinate(\n      coordinate,\n      frameState,\n      hitTolerance,\n      checkWrapped,\n      TRUE,\n      this,\n      layerFilter,\n      thisArg,\n    );\n\n    return hasFeature !== undefined;\n  }\n\n  /**\n   * @return {import(\"../Map.js\").default} Map.\n   */\n  getMap() {\n    return this.map_;\n  }\n\n  /**\n   * Render.\n   * @abstract\n   * @param {?import(\"../Map.js\").FrameState} frameState Frame state.\n   */\n  renderFrame(frameState) {\n    abstract();\n  }\n\n  /**\n   * @param {import(\"../Map.js\").FrameState} frameState Frame state.\n   * @protected\n   */\n  scheduleExpireIconCache(frameState) {\n    if (iconImageCache.canExpireCache()) {\n      frameState.postRenderFunctions.push(expireIconCache);\n    }\n  }\n}\n\n/**\n * @param {import(\"../Map.js\").default} map Map.\n * @param {import(\"../Map.js\").FrameState} frameState Frame state.\n */\nfunction expireIconCache(map, frameState) {\n  iconImageCache.expire();\n}\n\nexport default MapRenderer;\n", "/**\n * @module ol/renderer/Composite\n */\nimport ObjectEventType from '../ObjectEventType.js';\nimport {CLASS_UNSELECTABLE} from '../css.js';\nimport {createMockDiv, isCanvas, replaceChildren} from '../dom.js';\nimport {listen, unlistenByKey} from '../events.js';\nimport {WORKER_OFFSCREEN_CANVAS} from '../has.js';\nimport BaseVectorLayer from '../layer/BaseVector.js';\nimport {inView} from '../layer/Layer.js';\nimport RenderEvent from '../render/Event.js';\nimport RenderEventType from '../render/EventType.js';\nimport {checkedFonts} from '../render/canvas.js';\nimport {fromString} from '../transform.js';\nimport MapRenderer from './Map.js';\n\n/**\n * @classdesc\n * Canvas map renderer.\n * @api\n */\nclass CompositeMapRenderer extends MapRenderer {\n  /**\n   * @param {import(\"../Map.js\").default} map Map.\n   */\n  constructor(map) {\n    super(map);\n\n    /**\n     * @private\n     * @type {import(\"../events.js\").EventsKey}\n     */\n    this.fontChangeListenerKey_ = listen(\n      checkedFonts,\n      ObjectEventType.PROPERTYCHANGE,\n      map.redrawText,\n      map,\n    );\n\n    /**\n     * @private\n     * @type {HTMLDivElement}\n     */\n    this.element_ = WORKER_OFFSCREEN_CANVAS\n      ? createMockDiv()\n      : document.createElement('div');\n    const style = this.element_.style;\n    style.position = 'absolute';\n    style.width = '100%';\n    style.height = '100%';\n    style.zIndex = '0';\n\n    this.element_.className = CLASS_UNSELECTABLE + ' ol-layers';\n\n    const container = map.getViewport();\n    if (container) {\n      // maps in a worker do not have a viewport.\n      container.insertBefore(this.element_, container.firstChild || null);\n    }\n\n    /**\n     * @private\n     * @type {Array<HTMLElement>}\n     */\n    this.children_ = [];\n\n    /**\n     * @private\n     * @type {boolean}\n     */\n    this.renderedVisible_ = true;\n  }\n\n  /**\n   * @param {import(\"../render/EventType.js\").default} type Event type.\n   * @param {import(\"../Map.js\").FrameState} frameState Frame state.\n   * @override\n   */\n  dispatchRenderEvent(type, frameState) {\n    const map = this.getMap();\n    if (map.hasListener(type)) {\n      const event = new RenderEvent(type, undefined, frameState);\n      map.dispatchEvent(event);\n    }\n  }\n\n  /**\n   * @override\n   */\n  disposeInternal() {\n    unlistenByKey(this.fontChangeListenerKey_);\n    this.element_.remove();\n    super.disposeInternal();\n  }\n\n  /**\n   * Render.\n   * @param {?import(\"../Map.js\").FrameState} frameState Frame state.\n   * @override\n   */\n  renderFrame(frameState) {\n    if (!frameState) {\n      if (this.renderedVisible_) {\n        this.element_.style.display = 'none';\n        this.renderedVisible_ = false;\n      }\n      return;\n    }\n\n    this.calculateMatrices2D(frameState);\n    this.dispatchRenderEvent(RenderEventType.PRECOMPOSE, frameState);\n\n    const layerStatesArray = frameState.layerStatesArray.sort(\n      (a, b) => a.zIndex - b.zIndex,\n    );\n    const declutter = layerStatesArray.some(\n      (layerState) =>\n        layerState.layer instanceof BaseVectorLayer &&\n        layerState.layer.getDeclutter(),\n    );\n    if (declutter) {\n      // Some layers need decluttering, turn on deferred rendering hint\n      frameState.declutter = {};\n    }\n    const viewState = frameState.viewState;\n\n    this.children_.length = 0;\n\n    const renderedLayerStates = [];\n    let previousElement = null;\n    for (let i = 0, ii = layerStatesArray.length; i < ii; ++i) {\n      const layerState = layerStatesArray[i];\n      frameState.layerIndex = i;\n\n      const layer = layerState.layer;\n      const sourceState = layer.getSourceState();\n      if (\n        !inView(layerState, viewState) ||\n        (sourceState != 'ready' && sourceState != 'undefined')\n      ) {\n        layer.unrender();\n        continue;\n      }\n\n      const element = layer.render(frameState, previousElement);\n      if (!element) {\n        continue;\n      }\n      if (element !== previousElement) {\n        this.children_.push(element);\n        previousElement = element;\n      }\n\n      renderedLayerStates.push(layerState);\n    }\n\n    this.declutter(frameState, renderedLayerStates);\n\n    replaceChildren(this.element_, this.children_);\n\n    const map = this.getMap();\n    const mapCanvas = map.getTargetElement();\n    if (isCanvas(mapCanvas)) {\n      // Canvas composition when container is a canvas\n      const mapContext = mapCanvas.getContext('2d');\n      for (const container of this.children_) {\n        const canvas = container.firstElementChild || container;\n        const backgroundColor = container.style.backgroundColor;\n        if (backgroundColor && (!isCanvas(canvas) || canvas.width > 0)) {\n          mapContext.fillStyle = backgroundColor;\n          mapContext.fillRect(0, 0, mapCanvas.width, mapCanvas.height);\n        }\n        if (isCanvas(canvas) && canvas.width > 0) {\n          mapContext.save();\n          const opacity = container.style.opacity || canvas.style.opacity;\n          mapContext.globalAlpha = opacity === '' ? 1 : Number(opacity);\n          const transform = canvas.style.transform;\n          if (transform) {\n            // Get the transform parameters from the style's transform matrix\n            mapContext.transform(\n              .../** @type {[number, number, number, number, number, number]} */ (\n                fromString(transform)\n              ),\n            );\n          } else {\n            const w = parseFloat(canvas.style.width) / canvas.width;\n            const h = parseFloat(canvas.style.height) / canvas.height;\n            mapContext.transform(w, 0, 0, h, 0, 0);\n          }\n          mapContext.drawImage(canvas, 0, 0);\n          mapContext.restore();\n        }\n      }\n    }\n\n    this.dispatchRenderEvent(RenderEventType.POSTCOMPOSE, frameState);\n\n    if (!this.renderedVisible_) {\n      this.element_.style.display = '';\n      this.renderedVisible_ = true;\n    }\n\n    this.scheduleExpireIconCache(frameState);\n  }\n\n  /**\n   * @param {import(\"../Map.js\").FrameState} frameState Frame state.\n   * @param {Array<import('../layer/Layer.js').State>} layerStates Layers.\n   */\n  declutter(frameState, layerStates) {\n    if (!frameState.declutter) {\n      return;\n    }\n    for (let i = layerStates.length - 1; i >= 0; --i) {\n      const layerState = layerStates[i];\n      const layer = layerState.layer;\n      if (layer.getDeclutter()) {\n        layer.renderDeclutter(frameState, layerState);\n      }\n    }\n    layerStates.forEach((layerState) =>\n      layerState.layer.renderDeferred(frameState),\n    );\n  }\n}\n\nexport default CompositeMapRenderer;\n", "/**\n * @module ol/Map\n */\nimport Collection from './Collection.js';\nimport CollectionEventType from './CollectionEventType.js';\nimport MapBrowserEvent from './MapBrowserEvent.js';\nimport MapBrowserEventHandler from './MapBrowserEventHandler.js';\nimport MapBrowserEventType from './MapBrowserEventType.js';\nimport MapEvent from './MapEvent.js';\nimport MapEventType from './MapEventType.js';\nimport MapProperty from './MapProperty.js';\nimport BaseObject from './Object.js';\nimport ObjectEventType from './ObjectEventType.js';\nimport TileQueue, {getTilePriority} from './TileQueue.js';\nimport View from './View.js';\nimport ViewHint from './ViewHint.js';\nimport {equals} from './array.js';\nimport {assert} from './asserts.js';\nimport {warn} from './console.js';\nimport {defaults as defaultControls} from './control/defaults.js';\nimport {isCanvas} from './dom.js';\nimport {listen, unlistenByKey} from './events.js';\nimport EventType from './events/EventType.js';\nimport {\n  clone,\n  createOrUpdateEmpty,\n  equals as equalsExtent,\n  getForViewAndSize,\n  isEmpty,\n} from './extent.js';\nimport {TRUE} from './functions.js';\nimport {\n  DEVICE_PIXEL_RATIO,\n  PASSIVE_EVENT_LISTENERS,\n  WORKER_OFFSCREEN_CANVAS,\n} from './has.js';\nimport {defaults as defaultInteractions} from './interaction/defaults.js';\nimport LayerGroup, {GroupEvent} from './layer/Group.js';\nimport Layer from './layer/Layer.js';\nimport PointerEventType from './pointer/EventType.js';\nimport {fromUserCoordinate, toUserCoordinate} from './proj.js';\nimport RenderEventType from './render/EventType.js';\nimport CompositeMapRenderer from './renderer/Composite.js';\nimport {hasArea} from './size.js';\nimport {\n  apply as applyTransform,\n  create as createTransform,\n} from './transform.js';\nimport {getUid} from './util.js';\n\n/**\n * State of the current frame. Only `pixelRatio`, `time` and `viewState` should\n * be used in applications.\n * @typedef {Object} FrameState\n * @property {number} pixelRatio The pixel ratio of the frame.\n * @property {number} time The time when rendering of the frame was requested.\n * @property {import(\"./View.js\").State} viewState The state of the current view.\n * @property {boolean} animate Animate.\n * @property {import(\"./transform.js\").Transform} coordinateToPixelTransform CoordinateToPixelTransform.\n * @property {Object<string, import(\"rbush\").default<import('./render/canvas/Executor.js').DeclutterEntry>>|null} declutter\n * Declutter trees by declutter group.\n * When null, no decluttering is needed because no layers have decluttering enabled.\n * @property {null|import(\"./extent.js\").Extent} extent Extent (in view projection coordinates).\n * @property {import(\"./extent.js\").Extent} [nextExtent] Next extent during an animation series.\n * @property {number} index Index.\n * @property {Array<import(\"./layer/Layer.js\").State>} layerStatesArray LayerStatesArray.\n * @property {number} layerIndex LayerIndex.\n * @property {import(\"./transform.js\").Transform} pixelToCoordinateTransform PixelToCoordinateTransform.\n * @property {Array<PostRenderFunction>} postRenderFunctions PostRenderFunctions.\n * @property {import(\"./size.js\").Size} size Size.\n * @property {TileQueue} tileQueue TileQueue.\n * @property {!Object<string, Object<string, boolean>>} usedTiles UsedTiles.\n * @property {Array<number>} viewHints ViewHints.\n * @property {!Object<string, Object<string, boolean>>} wantedTiles WantedTiles.\n * @property {string} mapId The id of the map.\n * @property {Object<string, boolean>} renderTargets Identifiers of previously rendered elements.\n */\n\n/**\n * @typedef {function(Map, FrameState): any} PostRenderFunction\n */\n\n/**\n * @typedef {Object} AtPixelOptions\n * @property {undefined|function(import(\"./layer/Layer.js\").default<import(\"./source/Source.js\").default>): boolean} [layerFilter] Layer filter\n * function. The filter function will receive one argument, the\n * {@link module:ol/layer/Layer~Layer layer-candidate} and it should return a boolean value.\n * Only layers which are visible and for which this function returns `true`\n * will be tested for features. By default, all visible layers will be tested.\n * @property {number} [hitTolerance=0] Hit-detection tolerance in css pixels. Pixels\n * inside the radius around the given position will be checked for features.\n * @property {boolean} [checkWrapped=true] Check-Wrapped Will check for wrapped geometries inside the range of\n *   +/- 1 world width. Works only if a projection is used that can be wrapped.\n */\n\n/**\n * @typedef {Object} MapOptionsInternal\n * @property {Collection<import(\"./control/Control.js\").default>} [controls] Controls.\n * @property {Collection<import(\"./interaction/Interaction.js\").default>} [interactions] Interactions.\n * @property {HTMLElement|Document} keyboardEventTarget KeyboardEventTarget.\n * @property {Collection<import(\"./Overlay.js\").default>} overlays Overlays.\n * @property {Object<string, *>} values Values.\n */\n\n/**\n * @typedef {import(\"./ObjectEventType.js\").Types|'change:layergroup'|'change:size'|'change:target'|'change:view'} MapObjectEventTypes\n */\n\n/***\n * @template Return\n * @typedef {import(\"./Observable.js\").OnSignature<import(\"./Observable.js\").EventTypes, import(\"./events/Event.js\").default, Return> &\n *    import(\"./Observable.js\").OnSignature<MapObjectEventTypes, import(\"./Object.js\").ObjectEvent, Return> &\n *    import(\"./Observable.js\").OnSignature<import(\"./MapBrowserEventType.js\").Types, import(\"./MapBrowserEvent.js\").default, Return> &\n *    import(\"./Observable.js\").OnSignature<import(\"./MapEventType.js\").Types, import(\"./MapEvent.js\").default, Return> &\n *    import(\"./Observable.js\").OnSignature<import(\"./render/EventType.js\").MapRenderEventTypes, import(\"./render/Event.js\").default, Return> &\n *    import(\"./Observable.js\").CombinedOnSignature<import(\"./Observable.js\").EventTypes|MapObjectEventTypes|\n *      import(\"./MapBrowserEventType.js\").Types|import(\"./MapEventType.js\").Types|\n *      import(\"./render/EventType.js\").MapRenderEventTypes, Return>} MapEventHandler\n */\n\n/**\n * Object literal with config options for the map.\n * @typedef {Object} MapOptions\n * @property {Collection<import(\"./control/Control.js\").default>|Array<import(\"./control/Control.js\").default>} [controls]\n * Controls initially added to the map. If not specified,\n * {@link module:ol/control/defaults.defaults} is used. In a worker, no controls are added by default.\n * @property {number} [pixelRatio=window.devicePixelRatio] The ratio between\n * physical pixels and device-independent pixels (dips) on the device.\n * @property {Collection<import(\"./interaction/Interaction.js\").default>|Array<import(\"./interaction/Interaction.js\").default>} [interactions]\n * Interactions that are initially added to the map. If not specified,\n * {@link module:ol/interaction/defaults.defaults} is used. In a worker, no interactions are added by default.\n * @property {HTMLElement|Document|string} [keyboardEventTarget] The element to\n * listen to keyboard events on. This determines when the `KeyboardPan` and\n * `KeyboardZoom` interactions trigger. For example, if this option is set to\n * `document` the keyboard interactions will always trigger. If this option is\n * not specified, the element the library listens to keyboard events on is the\n * map target (i.e. the user-provided div for the map). If this is not\n * `document`, the target element needs to be focused for key events to be\n * emitted, requiring that the target element has a `tabindex` attribute.\n * @property {Array<import(\"./layer/Base.js\").default>|Collection<import(\"./layer/Base.js\").default>|LayerGroup} [layers]\n * Layers. If this is not defined, a map with no layers will be rendered. Note\n * that layers are rendered in the order supplied, so if you want, for example,\n * a vector layer to appear on top of a tile layer, it must come after the tile\n * layer.\n * @property {number} [maxTilesLoading=16] Maximum number tiles to load\n * simultaneously.\n * @property {number} [moveTolerance=1] The minimum distance in pixels the\n * cursor must move to be detected as a map move event instead of a click.\n * Increasing this value can make it easier to click on the map.\n * @property {Collection<import(\"./Overlay.js\").default>|Array<import(\"./Overlay.js\").default>} [overlays]\n * Overlays initially added to the map. By default, no overlays are added.\n * @property {HTMLElement|string|HTMLCanvasElement|OffscreenCanvas} [target] The container for the map, either the\n * element itself or the `id` of the element. If not specified at construction\n * time, {@link module:ol/Map~Map#setTarget} must be called for the map to be\n * rendered. If passed by element, the container can be in a secondary document.\n * For use in workers or when exporting a map, use an `OffscreenCanvas` or `HTMLCanvasElement` as target,\n * with a width and height in physical pixels, optionally multiplied by and a scale transform matching\n * the map's pixel ratio.\n * For accessibility (focus and keyboard events for map navigation), the `target` element must have a\n *  properly configured `tabindex` attribute. If the `target` element is inside a Shadow DOM, the\n *  `tabindex` atribute must be set on the custom element's host element.\n * **Note:** CSS `transform` support for the target element is limited to `scale`.\n * @property {View|Promise<import(\"./View.js\").ViewOptions>} [view] The map's view.  No layer sources will be\n * fetched unless this is specified at construction time or through\n * {@link module:ol/Map~Map#setView}.\n */\n\n/**\n * @param {import(\"./layer/Base.js\").default} layer Layer.\n */\nfunction removeLayerMapProperty(layer) {\n  if (layer instanceof Layer) {\n    layer.setMapInternal(null);\n    return;\n  }\n  if (layer instanceof LayerGroup) {\n    layer.getLayers().forEach(removeLayerMapProperty);\n  }\n}\n\n/**\n * @param {import(\"./layer/Base.js\").default} layer Layer.\n * @param {Map} map Map.\n */\nfunction setLayerMapProperty(layer, map) {\n  if (layer instanceof Layer) {\n    layer.setMapInternal(map);\n    return;\n  }\n  if (layer instanceof LayerGroup) {\n    const layers = layer.getLayers().getArray();\n    for (let i = 0, ii = layers.length; i < ii; ++i) {\n      setLayerMapProperty(layers[i], map);\n    }\n  }\n}\n\n/**\n * @classdesc\n * The map is the core component of OpenLayers. For a map to render, a view,\n * one or more layers, and a target container are needed:\n *\n *     import Map from 'ol/Map.js';\n *     import View from 'ol/View.js';\n *     import TileLayer from 'ol/layer/Tile.js';\n *     import OSM from 'ol/source/OSM.js';\n *\n *     const map = new Map({\n *       view: new View({\n *         center: [0, 0],\n *         zoom: 1,\n *       }),\n *       layers: [\n *         new TileLayer({\n *           source: new OSM(),\n *         }),\n *       ],\n *       target: 'map',\n *     });\n *\n * The above snippet creates a map using a {@link module:ol/layer/Tile~TileLayer} to\n * display {@link module:ol/source/OSM~OSM} OSM data and render it to a DOM\n * element with the id `map`.\n *\n * The constructor places a viewport container (with CSS class name\n * `ol-viewport`) in the target element (see `getViewport()`), and then two\n * further elements within the viewport: one with CSS class name\n * `ol-overlaycontainer-stopevent` for controls and some overlays, and one with\n * CSS class name `ol-overlaycontainer` for other overlays (see the `stopEvent`\n * option of {@link module:ol/Overlay~Overlay} for the difference). The map\n * itself is placed in a further element within the viewport.\n *\n * Layers are stored as a {@link module:ol/Collection~Collection} in\n * layerGroups. A top-level group is provided by the library. This is what is\n * accessed by `getLayerGroup` and `setLayerGroup`. Layers entered in the\n * options are added to this group, and `addLayer` and `removeLayer` change the\n * layer collection in the group. `getLayers` is a convenience function for\n * `getLayerGroup().getLayers()`. Note that {@link module:ol/layer/Group~LayerGroup}\n * is a subclass of {@link module:ol/layer/Base~BaseLayer}, so layers entered in the\n * options or added with `addLayer` can be groups, which can contain further\n * groups, and so on.\n *\n * @fires import(\"./MapBrowserEvent.js\").MapBrowserEvent\n * @fires import(\"./MapEvent.js\").MapEvent\n * @fires import(\"./render/Event.js\").default#precompose\n * @fires import(\"./render/Event.js\").default#postcompose\n * @fires import(\"./render/Event.js\").default#rendercomplete\n * @api\n */\nclass Map extends BaseObject {\n  /**\n   * @param {MapOptions} [options] Map options.\n   */\n  constructor(options) {\n    super();\n\n    options = options || {};\n\n    /***\n     * @type {MapEventHandler<import(\"./events.js\").EventsKey>}\n     */\n    this.on;\n\n    /***\n     * @type {MapEventHandler<import(\"./events.js\").EventsKey>}\n     */\n    this.once;\n\n    /***\n     * @type {MapEventHandler<void>}\n     */\n    this.un;\n\n    const optionsInternal = createOptionsInternal(options);\n\n    /**\n     * @private\n     * @type {boolean}\n     */\n    this.renderComplete_ = false;\n\n    /**\n     * @private\n     * @type {boolean}\n     */\n    this.loaded_ = true;\n\n    /** @private */\n    this.boundHandleBrowserEvent_ = this.handleBrowserEvent.bind(this);\n\n    /**\n     * @type {number}\n     * @private\n     */\n    this.maxTilesLoading_ =\n      options.maxTilesLoading !== undefined ? options.maxTilesLoading : 16;\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.pixelRatio_ =\n      options.pixelRatio !== undefined\n        ? options.pixelRatio\n        : DEVICE_PIXEL_RATIO;\n\n    /**\n     * @private\n     * @type {ReturnType<typeof setTimeout>}\n     */\n    this.postRenderTimeoutHandle_;\n\n    /**\n     * @private\n     * @type {number|undefined}\n     */\n    this.animationDelayKey_;\n\n    /**\n     * @private\n     */\n    this.animationDelay_ = this.animationDelay_.bind(this);\n\n    /**\n     * @private\n     * @type {import(\"./transform.js\").Transform}\n     */\n    this.coordinateToPixelTransform_ = createTransform();\n\n    /**\n     * @private\n     * @type {import(\"./transform.js\").Transform}\n     */\n    this.pixelToCoordinateTransform_ = createTransform();\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.frameIndex_ = 0;\n\n    /**\n     * @private\n     * @type {?FrameState}\n     */\n    this.frameState_ = null;\n\n    /**\n     * The extent at the previous 'moveend' event.\n     * @private\n     * @type {import(\"./extent.js\").Extent}\n     */\n    this.previousExtent_ = null;\n\n    /**\n     * @private\n     * @type {?import(\"./events.js\").EventsKey}\n     */\n    this.viewPropertyListenerKey_ = null;\n\n    /**\n     * @private\n     * @type {?import(\"./events.js\").EventsKey}\n     */\n    this.viewChangeListenerKey_ = null;\n\n    /**\n     * @private\n     * @type {?Array<import(\"./events.js\").EventsKey>}\n     */\n    this.layerGroupPropertyListenerKeys_ = null;\n\n    /**\n     * @private\n     * @type {!HTMLElement}\n     */\n    if (!WORKER_OFFSCREEN_CANVAS) {\n      this.viewport_ = document.createElement('div');\n      this.viewport_.className =\n        'ol-viewport' + ('ontouchstart' in window ? ' ol-touch' : '');\n      this.viewport_.style.position = 'relative';\n      this.viewport_.style.overflow = 'hidden';\n      this.viewport_.style.width = '100%';\n      this.viewport_.style.height = '100%';\n\n      /**\n       * @private\n       * @type {!HTMLElement}\n       */\n      this.overlayContainer_ = document.createElement('div');\n      this.overlayContainer_.style.position = 'absolute';\n      this.overlayContainer_.style.zIndex = '0';\n      this.overlayContainer_.style.width = '100%';\n      this.overlayContainer_.style.height = '100%';\n      this.overlayContainer_.style.pointerEvents = 'none';\n      this.overlayContainer_.className = 'ol-overlaycontainer';\n      this.viewport_.appendChild(this.overlayContainer_);\n\n      /**\n       * @private\n       * @type {!HTMLElement}\n       */\n      this.overlayContainerStopEvent_ = document.createElement('div');\n      this.overlayContainerStopEvent_.style.position = 'absolute';\n      this.overlayContainerStopEvent_.style.zIndex = '0';\n      this.overlayContainerStopEvent_.style.width = '100%';\n      this.overlayContainerStopEvent_.style.height = '100%';\n      this.overlayContainerStopEvent_.style.pointerEvents = 'none';\n      this.overlayContainerStopEvent_.className =\n        'ol-overlaycontainer-stopevent';\n      this.viewport_.appendChild(this.overlayContainerStopEvent_);\n    }\n\n    /**\n     * @private\n     * @type {MapBrowserEventHandler}\n     */\n    this.mapBrowserEventHandler_ = null;\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.moveTolerance_ = options.moveTolerance;\n\n    /**\n     * @private\n     * @type {HTMLElement|Document}\n     */\n    this.keyboardEventTarget_ = optionsInternal.keyboardEventTarget;\n\n    /**\n     * @private\n     * @type {?Array<import(\"./events.js\").EventsKey>}\n     */\n    this.targetChangeHandlerKeys_ = null;\n\n    /**\n     * @private\n     * @type {HTMLElement|null}\n     */\n    this.targetElement_ = null;\n\n    if (!WORKER_OFFSCREEN_CANVAS) {\n      /**\n       * @private\n       * @type {ResizeObserver}\n       */\n      this.resizeObserver_ = new ResizeObserver(() => this.updateSize());\n    }\n\n    /**\n     * @type {Collection<import(\"./control/Control.js\").default>}\n     * @protected\n     */\n    this.controls =\n      optionsInternal.controls ||\n      (WORKER_OFFSCREEN_CANVAS ? new Collection() : defaultControls());\n\n    /**\n     * @type {Collection<import(\"./interaction/Interaction.js\").default>}\n     * @protected\n     */\n    this.interactions =\n      optionsInternal.interactions ||\n      (WORKER_OFFSCREEN_CANVAS\n        ? new Collection()\n        : defaultInteractions({\n            onFocusOnly: true,\n          }));\n\n    /**\n     * @type {Collection<import(\"./Overlay.js\").default>}\n     * @private\n     */\n    this.overlays_ = optionsInternal.overlays;\n\n    /**\n     * A lookup of overlays by id.\n     * @private\n     * @type {Object<string, import(\"./Overlay.js\").default>}\n     */\n    this.overlayIdIndex_ = {};\n\n    /**\n     * @type {import(\"./renderer/Map.js\").default|null}\n     * @private\n     */\n    this.renderer_ = null;\n\n    /**\n     * @private\n     * @type {!Array<PostRenderFunction>}\n     */\n    this.postRenderFunctions_ = [];\n\n    /**\n     * @private\n     * @type {TileQueue}\n     */\n    this.tileQueue_ = new TileQueue(\n      this.getTilePriority.bind(this),\n      this.handleTileChange_.bind(this),\n    );\n\n    this.addChangeListener(\n      MapProperty.LAYERGROUP,\n      this.handleLayerGroupChanged_,\n    );\n    this.addChangeListener(MapProperty.VIEW, this.handleViewChanged_);\n    this.addChangeListener(MapProperty.SIZE, this.handleSizeChanged_);\n    this.addChangeListener(MapProperty.TARGET, this.handleTargetChanged_);\n\n    // setProperties will trigger the rendering of the map if the map\n    // is \"defined\" already.\n    this.setProperties(optionsInternal.values);\n\n    const map = this;\n    if (options.view && !(options.view instanceof View)) {\n      options.view.then(function (viewOptions) {\n        map.setView(new View(viewOptions));\n      });\n    }\n\n    this.controls.addEventListener(\n      CollectionEventType.ADD,\n      /**\n       * @param {import(\"./Collection.js\").CollectionEvent<import(\"./control/Control.js\").default>} event CollectionEvent\n       */\n      (event) => {\n        event.element.setMap(this);\n      },\n    );\n\n    this.controls.addEventListener(\n      CollectionEventType.REMOVE,\n      /**\n       * @param {import(\"./Collection.js\").CollectionEvent<import(\"./control/Control.js\").default>} event CollectionEvent.\n       */\n      (event) => {\n        event.element.setMap(null);\n      },\n    );\n\n    this.interactions.addEventListener(\n      CollectionEventType.ADD,\n      /**\n       * @param {import(\"./Collection.js\").CollectionEvent<import(\"./interaction/Interaction.js\").default>} event CollectionEvent.\n       */\n      (event) => {\n        event.element.setMap(this);\n      },\n    );\n\n    this.interactions.addEventListener(\n      CollectionEventType.REMOVE,\n      /**\n       * @param {import(\"./Collection.js\").CollectionEvent<import(\"./interaction/Interaction.js\").default>} event CollectionEvent.\n       */\n      (event) => {\n        event.element.setMap(null);\n      },\n    );\n\n    this.overlays_.addEventListener(\n      CollectionEventType.ADD,\n      /**\n       * @param {import(\"./Collection.js\").CollectionEvent<import(\"./Overlay.js\").default>} event CollectionEvent.\n       */\n      (event) => {\n        this.addOverlayInternal_(event.element);\n      },\n    );\n\n    this.overlays_.addEventListener(\n      CollectionEventType.REMOVE,\n      /**\n       * @param {import(\"./Collection.js\").CollectionEvent<import(\"./Overlay.js\").default>} event CollectionEvent.\n       */\n      (event) => {\n        const id = event.element.getId();\n        if (id !== undefined) {\n          delete this.overlayIdIndex_[id.toString()];\n        }\n        event.element.setMap(null);\n      },\n    );\n\n    this.controls.forEach(\n      /**\n       * @param {import(\"./control/Control.js\").default} control Control.\n       */\n      (control) => {\n        control.setMap(this);\n      },\n    );\n\n    this.interactions.forEach(\n      /**\n       * @param {import(\"./interaction/Interaction.js\").default} interaction Interaction.\n       */\n      (interaction) => {\n        interaction.setMap(this);\n      },\n    );\n\n    this.overlays_.forEach(this.addOverlayInternal_.bind(this));\n  }\n\n  /**\n   * Add the given control to the map.\n   * @param {import(\"./control/Control.js\").default} control Control.\n   * @api\n   */\n  addControl(control) {\n    this.getControls().push(control);\n  }\n\n  /**\n   * Add the given interaction to the map. If you want to add an interaction\n   * at another point of the collection use `getInteractions()` and the methods\n   * available on {@link module:ol/Collection~Collection}. This can be used to\n   * stop the event propagation from the handleEvent function. The interactions\n   * get to handle the events in the reverse order of this collection.\n   * @param {import(\"./interaction/Interaction.js\").default} interaction Interaction to add.\n   * @api\n   */\n  addInteraction(interaction) {\n    this.getInteractions().push(interaction);\n  }\n\n  /**\n   * Adds the given layer to the top of this map. If you want to add a layer\n   * elsewhere in the stack, use `getLayers()` and the methods available on\n   * {@link module:ol/Collection~Collection}.\n   * @param {import(\"./layer/Base.js\").default} layer Layer.\n   * @api\n   */\n  addLayer(layer) {\n    const layers = this.getLayerGroup().getLayers();\n    layers.push(layer);\n  }\n\n  /**\n   * @param {import(\"./layer/Group.js\").GroupEvent} event The layer add event.\n   * @private\n   */\n  handleLayerAdd_(event) {\n    setLayerMapProperty(event.layer, this);\n  }\n\n  /**\n   * Add the given overlay to the map.\n   * @param {import(\"./Overlay.js\").default} overlay Overlay.\n   * @api\n   */\n  addOverlay(overlay) {\n    this.getOverlays().push(overlay);\n  }\n\n  /**\n   * This deals with map's overlay collection changes.\n   * @param {import(\"./Overlay.js\").default} overlay Overlay.\n   * @private\n   */\n  addOverlayInternal_(overlay) {\n    const id = overlay.getId();\n    if (id !== undefined) {\n      this.overlayIdIndex_[id.toString()] = overlay;\n    }\n    overlay.setMap(this);\n  }\n\n  /**\n   *\n   * Clean up.\n   * @override\n   */\n  disposeInternal() {\n    this.controls.clear();\n    this.interactions.clear();\n    this.overlays_.clear();\n    this.resizeObserver_?.disconnect();\n    this.setTarget(null);\n    super.disposeInternal();\n  }\n\n  /**\n   * Detect features that intersect a pixel on the viewport, and execute a\n   * callback with each intersecting feature. Layers included in the detection can\n   * be configured through the `layerFilter` option in `options`.\n   * For polygons without a fill, only the stroke will be used for hit detection.\n   * Polygons must have a fill style applied to ensure that pixels inside a polygon are detected.\n   * The fill can be transparent.\n   * @param {import(\"./pixel.js\").Pixel} pixel Pixel.\n   * @param {function(import(\"./Feature.js\").FeatureLike, import(\"./layer/Layer.js\").default<import(\"./source/Source.js\").default>, import(\"./geom/SimpleGeometry.js\").default): T} callback Feature callback. The callback will be\n   *     called with two arguments. The first argument is one\n   *     {@link module:ol/Feature~Feature feature} or\n   *     {@link module:ol/render/Feature~RenderFeature render feature} at the pixel, the second is\n   *     the {@link module:ol/layer/Layer~Layer layer} of the feature and will be null for\n   *     unmanaged layers. To stop detection, callback functions can return a\n   *     truthy value.\n   * @param {AtPixelOptions} [options] Optional options.\n   * @return {T|undefined} Callback result, i.e. the return value of last\n   * callback execution, or the first truthy callback return value.\n   * @template T\n   * @api\n   */\n  forEachFeatureAtPixel(pixel, callback, options) {\n    if (!this.frameState_ || !this.renderer_) {\n      return;\n    }\n    const coordinate = this.getCoordinateFromPixelInternal(pixel);\n    options = options !== undefined ? options : {};\n    const hitTolerance =\n      options.hitTolerance !== undefined ? options.hitTolerance : 0;\n    const layerFilter =\n      options.layerFilter !== undefined ? options.layerFilter : TRUE;\n    const checkWrapped = options.checkWrapped !== false;\n    return this.renderer_.forEachFeatureAtCoordinate(\n      coordinate,\n      this.frameState_,\n      hitTolerance,\n      checkWrapped,\n      callback,\n      null,\n      layerFilter,\n      null,\n    );\n  }\n\n  /**\n   * Get all features that intersect a pixel on the viewport.\n   * For polygons without a fill, only the stroke will be used for hit detection.\n   * Polygons must have a fill style applied to ensure that pixels inside a polygon are detected.\n   * The fill can be transparent.\n   * @param {import(\"./pixel.js\").Pixel} pixel Pixel.\n   * @param {AtPixelOptions} [options] Optional options.\n   * @return {Array<import(\"./Feature.js\").FeatureLike>} The detected features or\n   * an empty array if none were found.\n   * @api\n   */\n  getFeaturesAtPixel(pixel, options) {\n    const features = [];\n    this.forEachFeatureAtPixel(\n      pixel,\n      function (feature) {\n        features.push(feature);\n      },\n      options,\n    );\n    return features;\n  }\n\n  /**\n   * Get all layers from all layer groups.\n   * @return {Array<import(\"./layer/Layer.js\").default>} Layers.\n   * @api\n   */\n  getAllLayers() {\n    const layers = [];\n    function addLayersFrom(layerGroup) {\n      layerGroup.forEach(function (layer) {\n        if (layer instanceof LayerGroup) {\n          addLayersFrom(layer.getLayers());\n        } else {\n          layers.push(layer);\n        }\n      });\n    }\n    addLayersFrom(this.getLayers());\n    return layers;\n  }\n\n  /**\n   * Detect if features intersect a pixel on the viewport. Layers included in the\n   * detection can be configured through the `layerFilter` option.\n   * For polygons without a fill, only the stroke will be used for hit detection.\n   * Polygons must have a fill style applied to ensure that pixels inside a polygon are detected.\n   * The fill can be transparent.\n   * @param {import(\"./pixel.js\").Pixel} pixel Pixel.\n   * @param {AtPixelOptions} [options] Optional options.\n   * @return {boolean} Is there a feature at the given pixel?\n   * @api\n   */\n  hasFeatureAtPixel(pixel, options) {\n    if (!this.frameState_ || !this.renderer_) {\n      return false;\n    }\n    const coordinate = this.getCoordinateFromPixelInternal(pixel);\n    options = options !== undefined ? options : {};\n    const layerFilter =\n      options.layerFilter !== undefined ? options.layerFilter : TRUE;\n    const hitTolerance =\n      options.hitTolerance !== undefined ? options.hitTolerance : 0;\n    const checkWrapped = options.checkWrapped !== false;\n    return this.renderer_.hasFeatureAtCoordinate(\n      coordinate,\n      this.frameState_,\n      hitTolerance,\n      checkWrapped,\n      layerFilter,\n      null,\n    );\n  }\n\n  /**\n   * Returns the coordinate in user projection for a browser event.\n   * @param {MouseEvent} event Event.\n   * @return {import(\"./coordinate.js\").Coordinate} Coordinate.\n   * @api\n   */\n  getEventCoordinate(event) {\n    return this.getCoordinateFromPixel(this.getEventPixel(event));\n  }\n\n  /**\n   * Returns the coordinate in view projection for a browser event.\n   * @param {MouseEvent} event Event.\n   * @return {import(\"./coordinate.js\").Coordinate} Coordinate.\n   */\n  getEventCoordinateInternal(event) {\n    return this.getCoordinateFromPixelInternal(this.getEventPixel(event));\n  }\n\n  /**\n   * Returns the map pixel position for a browser event relative to the viewport.\n   * @param {UIEvent|{clientX: number, clientY: number}} event Event.\n   * @return {import(\"./pixel.js\").Pixel} Pixel.\n   * @api\n   */\n  getEventPixel(event) {\n    const viewport = this.viewport_;\n    const viewportPosition = viewport.getBoundingClientRect();\n    const viewportSize = this.getSize();\n    const scaleX = viewportPosition.width / viewportSize[0];\n    const scaleY = viewportPosition.height / viewportSize[1];\n    const eventPosition =\n      //FIXME Are we really calling this with a TouchEvent anywhere?\n      'changedTouches' in event\n        ? /** @type {TouchEvent} */ (event).changedTouches[0]\n        : /** @type {MouseEvent} */ (event);\n\n    return [\n      (eventPosition.clientX - viewportPosition.left) / scaleX,\n      (eventPosition.clientY - viewportPosition.top) / scaleY,\n    ];\n  }\n\n  /**\n   * Get the target in which this map is rendered.\n   * Note that this returns what is entered as an option or in setTarget:\n   * if that was an element, it returns an element; if a string, it returns that.\n   * @return {HTMLElement|string|undefined} The Element or id of the Element that the\n   *     map is rendered in.\n   * @observable\n   * @api\n   */\n  getTarget() {\n    return /** @type {HTMLElement|string|undefined} */ (\n      this.get(MapProperty.TARGET)\n    );\n  }\n\n  /**\n   * Get the DOM element into which this map is rendered. In contrast to\n   * `getTarget` this method always return an `Element`, or `null` if the\n   * map has no target.\n   * @return {HTMLElement} The element that the map is rendered in.\n   * @api\n   */\n  getTargetElement() {\n    return this.targetElement_;\n  }\n\n  /**\n   * Get the coordinate for a given pixel.  This returns a coordinate in the\n   * user projection.\n   * @param {import(\"./pixel.js\").Pixel} pixel Pixel position in the map viewport.\n   * @return {import(\"./coordinate.js\").Coordinate} The coordinate for the pixel position.\n   * @api\n   */\n  getCoordinateFromPixel(pixel) {\n    return toUserCoordinate(\n      this.getCoordinateFromPixelInternal(pixel),\n      this.getView().getProjection(),\n    );\n  }\n\n  /**\n   * Get the coordinate for a given pixel.  This returns a coordinate in the\n   * map view projection.\n   * @param {import(\"./pixel.js\").Pixel} pixel Pixel position in the map viewport.\n   * @return {import(\"./coordinate.js\").Coordinate} The coordinate for the pixel position.\n   */\n  getCoordinateFromPixelInternal(pixel) {\n    const frameState = this.frameState_;\n    if (!frameState) {\n      return null;\n    }\n    return applyTransform(frameState.pixelToCoordinateTransform, pixel.slice());\n  }\n\n  /**\n   * Get the map controls. Modifying this collection changes the controls\n   * associated with the map.\n   * @return {Collection<import(\"./control/Control.js\").default>} Controls.\n   * @api\n   */\n  getControls() {\n    return this.controls;\n  }\n\n  /**\n   * Get the map overlays. Modifying this collection changes the overlays\n   * associated with the map.\n   * @return {Collection<import(\"./Overlay.js\").default>} Overlays.\n   * @api\n   */\n  getOverlays() {\n    return this.overlays_;\n  }\n\n  /**\n   * Get an overlay by its identifier (the value returned by overlay.getId()).\n   * Note that the index treats string and numeric identifiers as the same. So\n   * `map.getOverlayById(2)` will return an overlay with id `'2'` or `2`.\n   * @param {string|number} id Overlay identifier.\n   * @return {import(\"./Overlay.js\").default|null} Overlay.\n   * @api\n   */\n  getOverlayById(id) {\n    const overlay = this.overlayIdIndex_[id.toString()];\n    return overlay !== undefined ? overlay : null;\n  }\n\n  /**\n   * Get the map interactions. Modifying this collection changes the interactions\n   * associated with the map.\n   *\n   * Interactions are used for e.g. pan, zoom and rotate.\n   * @return {Collection<import(\"./interaction/Interaction.js\").default>} Interactions.\n   * @api\n   */\n  getInteractions() {\n    return this.interactions;\n  }\n\n  /**\n   * Get the layergroup associated with this map.\n   * @return {LayerGroup} A layer group containing the layers in this map.\n   * @observable\n   * @api\n   */\n  getLayerGroup() {\n    return /** @type {LayerGroup} */ (this.get(MapProperty.LAYERGROUP));\n  }\n\n  /**\n   * Clear any existing layers and add layers to the map.\n   * @param {Array<import(\"./layer/Base.js\").default>|Collection<import(\"./layer/Base.js\").default>} layers The layers to be added to the map.\n   * @api\n   */\n  setLayers(layers) {\n    const group = this.getLayerGroup();\n    if (layers instanceof Collection) {\n      group.setLayers(layers);\n      return;\n    }\n\n    const collection = group.getLayers();\n    collection.clear();\n    collection.extend(layers);\n  }\n\n  /**\n   * Get the collection of layers associated with this map.\n   * @return {!Collection<import(\"./layer/Base.js\").default>} Layers.\n   * @api\n   */\n  getLayers() {\n    const layers = this.getLayerGroup().getLayers();\n    return layers;\n  }\n\n  /**\n   * @return {boolean} Layers have sources that are still loading.\n   */\n  getLoadingOrNotReady() {\n    const layerStatesArray = this.getLayerGroup().getLayerStatesArray();\n    for (let i = 0, ii = layerStatesArray.length; i < ii; ++i) {\n      const state = layerStatesArray[i];\n      if (!state.visible) {\n        continue;\n      }\n      const renderer = state.layer.getRenderer();\n      if (renderer && !renderer.ready) {\n        return true;\n      }\n      const source = state.layer.getSource();\n      if (source && source.loading) {\n        return true;\n      }\n    }\n    return false;\n  }\n\n  /**\n   * Get the pixel for a coordinate.  This takes a coordinate in the user\n   * projection and returns the corresponding pixel.\n   * @param {import(\"./coordinate.js\").Coordinate} coordinate A map coordinate.\n   * @return {import(\"./pixel.js\").Pixel} A pixel position in the map viewport.\n   * @api\n   */\n  getPixelFromCoordinate(coordinate) {\n    const viewCoordinate = fromUserCoordinate(\n      coordinate,\n      this.getView().getProjection(),\n    );\n    return this.getPixelFromCoordinateInternal(viewCoordinate);\n  }\n\n  /**\n   * Get the pixel for a coordinate.  This takes a coordinate in the map view\n   * projection and returns the corresponding pixel.\n   * @param {import(\"./coordinate.js\").Coordinate} coordinate A map coordinate.\n   * @return {import(\"./pixel.js\").Pixel} A pixel position in the map viewport.\n   */\n  getPixelFromCoordinateInternal(coordinate) {\n    const frameState = this.frameState_;\n    if (!frameState) {\n      return null;\n    }\n    return applyTransform(\n      frameState.coordinateToPixelTransform,\n      coordinate.slice(0, 2),\n    );\n  }\n\n  /**\n   * Get the pixel ratio of the rendered map.\n   * @return {number} Pixel ratio.\n   * @api\n   */\n  getPixelRatio() {\n    return this.pixelRatio_;\n  }\n\n  /**\n   * Set the pixel ratio of the rendered map.\n   * @param {number} pixelRatio Pixel ratio.\n   * @api\n   */\n  setPixelRatio(pixelRatio) {\n    if (this.pixelRatio_ === pixelRatio) {\n      return;\n    }\n    this.pixelRatio_ = pixelRatio;\n    this.render();\n  }\n\n  /**\n   * Get the map renderer.\n   * @return {import(\"./renderer/Map.js\").default|null} Renderer\n   */\n  getRenderer() {\n    return this.renderer_;\n  }\n\n  /**\n   * Get the size of this map.\n   * @return {import(\"./size.js\").Size|undefined} The size in pixels of the map in the DOM.\n   * @observable\n   * @api\n   */\n  getSize() {\n    return /** @type {import(\"./size.js\").Size|undefined} */ (\n      this.get(MapProperty.SIZE)\n    );\n  }\n\n  /**\n   * Get the view associated with this map. A view manages properties such as\n   * center and resolution.\n   * @return {View} The view that controls this map.\n   * @observable\n   * @api\n   */\n  getView() {\n    return /** @type {View} */ (this.get(MapProperty.VIEW));\n  }\n\n  /**\n   * Get the element that serves as the map viewport.\n   * @return {HTMLElement} Viewport.\n   * @api\n   */\n  getViewport() {\n    return this.viewport_;\n  }\n\n  /**\n   * Get the element that serves as the container for overlays.  Elements added to\n   * this container will let mousedown and touchstart events through to the map,\n   * so clicks and gestures on an overlay will trigger {@link module:ol/MapBrowserEvent~MapBrowserEvent}\n   * events.\n   * @return {!HTMLElement} The map's overlay container.\n   */\n  getOverlayContainer() {\n    return this.overlayContainer_;\n  }\n\n  /**\n   * Get the element that serves as a container for overlays that don't allow\n   * event propagation. Elements added to this container won't let mousedown and\n   * touchstart events through to the map, so clicks and gestures on an overlay\n   * don't trigger any {@link module:ol/MapBrowserEvent~MapBrowserEvent}.\n   * @return {!HTMLElement} The map's overlay container that stops events.\n   */\n  getOverlayContainerStopEvent() {\n    return this.overlayContainerStopEvent_;\n  }\n\n  /**\n   * @return {!Document} The document where the map is displayed.\n   */\n  getOwnerDocument() {\n    const targetElement = this.getTargetElement();\n    return targetElement ? targetElement.ownerDocument : document;\n  }\n\n  /**\n   * @param {import(\"./Tile.js\").default} tile Tile.\n   * @param {string} tileSourceKey Tile source key.\n   * @param {import(\"./coordinate.js\").Coordinate} tileCenter Tile center.\n   * @param {number} tileResolution Tile resolution.\n   * @return {number} Tile priority.\n   */\n  getTilePriority(tile, tileSourceKey, tileCenter, tileResolution) {\n    return getTilePriority(\n      this.frameState_,\n      tile,\n      tileSourceKey,\n      tileCenter,\n      tileResolution,\n    );\n  }\n\n  /**\n   * @param {PointerEvent|KeyboardEvent|WheelEvent} browserEvent Browser event.\n   * @param {string} [type] Type.\n   */\n  handleBrowserEvent(browserEvent, type) {\n    type = type || browserEvent.type;\n    const mapBrowserEvent = new MapBrowserEvent(type, this, browserEvent);\n    this.handleMapBrowserEvent(mapBrowserEvent);\n  }\n\n  /**\n   * @param {MapBrowserEvent} mapBrowserEvent The event to handle.\n   */\n  handleMapBrowserEvent(mapBrowserEvent) {\n    if (!this.frameState_) {\n      // With no view defined, we cannot translate pixels into geographical\n      // coordinates so interactions cannot be used.\n      return;\n    }\n    const originalEvent = mapBrowserEvent.originalEvent;\n    const eventType = originalEvent.type;\n    if (\n      eventType === PointerEventType.POINTERDOWN ||\n      eventType === EventType.WHEEL ||\n      eventType === EventType.KEYDOWN\n    ) {\n      const doc = this.getOwnerDocument();\n      const rootNode = this.viewport_.getRootNode\n        ? this.viewport_.getRootNode()\n        : doc;\n      const target = /** @type {Node} */ (originalEvent.target);\n\n      const currentDoc =\n        rootNode instanceof ShadowRoot\n          ? rootNode.host === target\n            ? rootNode.host.ownerDocument\n            : rootNode\n          : rootNode === doc\n            ? doc.documentElement\n            : rootNode;\n      if (\n        // Abort if the target is a child of the container for elements whose events are not meant\n        // to be handled by map interactions.\n        this.overlayContainerStopEvent_.contains(target) ||\n        // Abort if the event target is a child of the container that is no longer in the page.\n        // It's possible for the target to no longer be in the page if it has been removed in an\n        // event listener, this might happen in a Control that recreates it's content based on\n        // user interaction either manually or via a render in something like https://reactjs.org/\n        !currentDoc.contains(target)\n      ) {\n        return;\n      }\n    }\n    mapBrowserEvent.frameState = this.frameState_;\n    if (this.dispatchEvent(mapBrowserEvent) !== false) {\n      const interactionsArray = this.getInteractions().getArray().slice();\n      for (let i = interactionsArray.length - 1; i >= 0; i--) {\n        const interaction = interactionsArray[i];\n        if (\n          interaction.getMap() !== this ||\n          !interaction.getActive() ||\n          !this.getTargetElement()\n        ) {\n          continue;\n        }\n        const cont = interaction.handleEvent(mapBrowserEvent);\n        if (!cont || mapBrowserEvent.propagationStopped) {\n          break;\n        }\n      }\n    }\n  }\n\n  /**\n   * @protected\n   */\n  handlePostRender() {\n    const frameState = this.frameState_;\n\n    // Manage the tile queue\n    // Image loads are expensive and a limited resource, so try to use them\n    // efficiently:\n    // * When the view is static we allow a large number of parallel tile loads\n    //   to complete the frame as quickly as possible.\n    // * When animating or interacting, image loads can cause janks, so we reduce\n    //   the maximum number of loads per frame and limit the number of parallel\n    //   tile loads to remain reactive to view changes and to reduce the chance of\n    //   loading tiles that will quickly disappear from view.\n    const tileQueue = this.tileQueue_;\n    if (!tileQueue.isEmpty()) {\n      let maxTotalLoading = this.maxTilesLoading_;\n      let maxNewLoads = maxTotalLoading;\n      const hints = frameState ? frameState.viewHints : undefined;\n      const animatingOrInteracting = hints\n        ? hints[ViewHint.ANIMATING] || hints[ViewHint.INTERACTING]\n        : false;\n      if (animatingOrInteracting) {\n        const lowOnFrameBudget = Date.now() - frameState.time > 8;\n        maxTotalLoading = lowOnFrameBudget ? 0 : 8;\n        maxNewLoads = lowOnFrameBudget ? 0 : 2;\n      }\n      if (tileQueue.getTilesLoading() < maxTotalLoading) {\n        if (animatingOrInteracting) {\n          tileQueue.reprioritize();\n        }\n        tileQueue.loadMoreTiles(maxTotalLoading, maxNewLoads);\n      }\n    }\n\n    if (frameState && this.renderer_ && !frameState.animate) {\n      if (this.renderComplete_) {\n        if (this.hasListener(RenderEventType.RENDERCOMPLETE)) {\n          this.renderer_.dispatchRenderEvent(\n            RenderEventType.RENDERCOMPLETE,\n            frameState,\n          );\n        }\n        if (this.loaded_ === false) {\n          this.loaded_ = true;\n          this.dispatchEvent(\n            new MapEvent(MapEventType.LOADEND, this, frameState),\n          );\n        }\n      } else if (this.loaded_ === true) {\n        this.loaded_ = false;\n        this.dispatchEvent(\n          new MapEvent(MapEventType.LOADSTART, this, frameState),\n        );\n      }\n    }\n\n    const postRenderFunctions = this.postRenderFunctions_;\n    if (frameState) {\n      for (let i = 0, ii = postRenderFunctions.length; i < ii; ++i) {\n        postRenderFunctions[i](this, frameState);\n      }\n    }\n    postRenderFunctions.length = 0;\n  }\n\n  /**\n   * @private\n   */\n  handleSizeChanged_() {\n    if (this.getView() && !this.getView().getAnimating()) {\n      this.getView().resolveConstraints(0);\n    }\n\n    this.render();\n  }\n\n  /**\n   * @private\n   */\n  handleTargetChanged_() {\n    if (this.mapBrowserEventHandler_) {\n      for (let i = 0, ii = this.targetChangeHandlerKeys_.length; i < ii; ++i) {\n        unlistenByKey(this.targetChangeHandlerKeys_[i]);\n      }\n      this.targetChangeHandlerKeys_ = null;\n      this.viewport_.removeEventListener(\n        EventType.CONTEXTMENU,\n        this.boundHandleBrowserEvent_,\n      );\n      this.viewport_.removeEventListener(\n        EventType.WHEEL,\n        this.boundHandleBrowserEvent_,\n      );\n      this.mapBrowserEventHandler_.dispose();\n      this.mapBrowserEventHandler_ = null;\n      this.viewport_.remove();\n    }\n\n    if (this.targetElement_ && !isCanvas(this.targetElement_)) {\n      this.resizeObserver_?.unobserve(this.targetElement_);\n      const rootNode = this.targetElement_.getRootNode();\n      if (rootNode instanceof ShadowRoot) {\n        this.resizeObserver_.unobserve(rootNode.host);\n      }\n      this.setSize(undefined);\n    }\n\n    // target may be undefined, null, a string or an Element.\n    // If it's a string we convert it to an Element before proceeding.\n    // If it's not now an Element we remove the viewport from the DOM.\n    // If it's an Element we append the viewport element to it.\n\n    const target = this.getTarget();\n    const targetElement =\n      typeof target === 'string' ? document.getElementById(target) : target;\n    this.targetElement_ = targetElement;\n    if (!targetElement) {\n      if (this.renderer_) {\n        clearTimeout(this.postRenderTimeoutHandle_);\n        this.postRenderTimeoutHandle_ = undefined;\n        this.postRenderFunctions_.length = 0;\n        this.renderer_.dispose();\n        this.renderer_ = null;\n      }\n      if (this.animationDelayKey_) {\n        cancelAnimationFrame(this.animationDelayKey_);\n        this.animationDelayKey_ = undefined;\n      }\n    } else {\n      if (!isCanvas(targetElement)) {\n        targetElement.appendChild(this.viewport_);\n      }\n      if (!this.renderer_) {\n        this.renderer_ = new CompositeMapRenderer(this);\n      }\n\n      if (!isCanvas(targetElement)) {\n        this.mapBrowserEventHandler_ = new MapBrowserEventHandler(\n          this,\n          this.moveTolerance_,\n        );\n        for (const key in MapBrowserEventType) {\n          this.mapBrowserEventHandler_.addEventListener(\n            MapBrowserEventType[key],\n            this.handleMapBrowserEvent.bind(this),\n          );\n        }\n        this.viewport_.addEventListener(\n          EventType.CONTEXTMENU,\n          this.boundHandleBrowserEvent_,\n          false,\n        );\n        this.viewport_.addEventListener(\n          EventType.WHEEL,\n          this.boundHandleBrowserEvent_,\n          PASSIVE_EVENT_LISTENERS ? {passive: false} : false,\n        );\n\n        let keyboardEventTarget;\n        if (!this.keyboardEventTarget_) {\n          // check if map target is in shadowDOM, if yes use host element as target\n          const targetRoot = targetElement.getRootNode();\n          const targetCandidate =\n            targetRoot instanceof ShadowRoot ? targetRoot.host : targetElement;\n          keyboardEventTarget = targetCandidate;\n        } else {\n          keyboardEventTarget = this.keyboardEventTarget_;\n        }\n\n        this.targetChangeHandlerKeys_ = [\n          listen(\n            keyboardEventTarget,\n            EventType.KEYDOWN,\n            this.handleBrowserEvent,\n            this,\n          ),\n          listen(\n            keyboardEventTarget,\n            EventType.KEYPRESS,\n            this.handleBrowserEvent,\n            this,\n          ),\n        ];\n        if (targetElement instanceof HTMLElement) {\n          const rootNode = targetElement.getRootNode();\n          if (rootNode instanceof ShadowRoot) {\n            this.resizeObserver_.observe(rootNode.host);\n          }\n          this.resizeObserver_?.observe(targetElement);\n        }\n      }\n\n      this.updateSize();\n    }\n    // updateSize calls setSize, so no need to call this.render\n    // ourselves here.\n  }\n\n  /**\n   * @private\n   */\n  handleTileChange_() {\n    this.render();\n  }\n\n  /**\n   * @private\n   */\n  handleViewPropertyChanged_() {\n    this.render();\n  }\n\n  /**\n   * @private\n   */\n  handleViewChanged_() {\n    if (this.viewPropertyListenerKey_) {\n      unlistenByKey(this.viewPropertyListenerKey_);\n      this.viewPropertyListenerKey_ = null;\n    }\n    if (this.viewChangeListenerKey_) {\n      unlistenByKey(this.viewChangeListenerKey_);\n      this.viewChangeListenerKey_ = null;\n    }\n    const view = this.getView();\n    if (view) {\n      this.updateViewportSize_(this.getSize());\n\n      this.viewPropertyListenerKey_ = listen(\n        view,\n        ObjectEventType.PROPERTYCHANGE,\n        this.handleViewPropertyChanged_,\n        this,\n      );\n      this.viewChangeListenerKey_ = listen(\n        view,\n        EventType.CHANGE,\n        this.handleViewPropertyChanged_,\n        this,\n      );\n\n      view.resolveConstraints(0);\n    }\n    this.render();\n  }\n\n  /**\n   * @private\n   */\n  handleLayerGroupChanged_() {\n    if (this.layerGroupPropertyListenerKeys_) {\n      this.layerGroupPropertyListenerKeys_.forEach(unlistenByKey);\n      this.layerGroupPropertyListenerKeys_ = null;\n    }\n    const layerGroup = this.getLayerGroup();\n    if (layerGroup) {\n      this.handleLayerAdd_(new GroupEvent('addlayer', layerGroup));\n      this.layerGroupPropertyListenerKeys_ = [\n        listen(layerGroup, ObjectEventType.PROPERTYCHANGE, this.render, this),\n        listen(layerGroup, EventType.CHANGE, this.render, this),\n        listen(layerGroup, 'addlayer', this.handleLayerAdd_, this),\n        listen(layerGroup, 'removelayer', this.handleLayerRemove_, this),\n      ];\n    }\n    this.render();\n  }\n\n  /**\n   * @return {boolean} Is rendered.\n   */\n  isRendered() {\n    return !!this.frameState_;\n  }\n\n  /**\n   * @private\n   */\n  animationDelay_() {\n    this.animationDelayKey_ = undefined;\n    this.renderFrame_(Date.now());\n  }\n\n  /**\n   * Requests an immediate render in a synchronous manner.\n   * @api\n   */\n  renderSync() {\n    if (this.animationDelayKey_) {\n      cancelAnimationFrame(this.animationDelayKey_);\n    }\n    this.animationDelay_();\n  }\n\n  /**\n   * Redraws all text after new fonts have loaded\n   */\n  redrawText() {\n    if (!this.frameState_) {\n      return;\n    }\n    const layerStates = this.frameState_.layerStatesArray;\n    for (let i = 0, ii = layerStates.length; i < ii; ++i) {\n      const layer = layerStates[i].layer;\n      if (layer.hasRenderer()) {\n        layer.getRenderer().handleFontsChanged();\n      }\n    }\n  }\n\n  /**\n   * Request a map rendering (at the next animation frame).\n   * @api\n   */\n  render() {\n    if (this.renderer_ && this.animationDelayKey_ === undefined) {\n      this.animationDelayKey_ = requestAnimationFrame(this.animationDelay_);\n    }\n  }\n\n  /**\n   * Remove the given control from the map.\n   * @param {import(\"./control/Control.js\").default} control Control.\n   * @return {import(\"./control/Control.js\").default|undefined} The removed control (or undefined\n   *     if the control was not found).\n   * @api\n   */\n  removeControl(control) {\n    return this.getControls().remove(control);\n  }\n\n  /**\n   * Remove the given interaction from the map.\n   * @param {import(\"./interaction/Interaction.js\").default} interaction Interaction to remove.\n   * @return {import(\"./interaction/Interaction.js\").default|undefined} The removed interaction (or\n   *     undefined if the interaction was not found).\n   * @api\n   */\n  removeInteraction(interaction) {\n    return this.getInteractions().remove(interaction);\n  }\n\n  /**\n   * Removes the given layer from the map.\n   * @param {import(\"./layer/Base.js\").default} layer Layer.\n   * @return {import(\"./layer/Base.js\").default|undefined} The removed layer (or undefined if the\n   *     layer was not found).\n   * @api\n   */\n  removeLayer(layer) {\n    const layers = this.getLayerGroup().getLayers();\n    return layers.remove(layer);\n  }\n\n  /**\n   * @param {import(\"./layer/Group.js\").GroupEvent} event The layer remove event.\n   * @private\n   */\n  handleLayerRemove_(event) {\n    removeLayerMapProperty(event.layer);\n  }\n\n  /**\n   * Remove the given overlay from the map.\n   * @param {import(\"./Overlay.js\").default} overlay Overlay.\n   * @return {import(\"./Overlay.js\").default|undefined} The removed overlay (or undefined\n   *     if the overlay was not found).\n   * @api\n   */\n  removeOverlay(overlay) {\n    return this.getOverlays().remove(overlay);\n  }\n\n  /**\n   * @param {number} time Time.\n   * @private\n   */\n  renderFrame_(time) {\n    const size = this.getSize();\n    const view = this.getView();\n    const previousFrameState = this.frameState_;\n    /** @type {?FrameState} */\n    let frameState = null;\n    if (size !== undefined && hasArea(size) && view && view.isDef()) {\n      const viewHints = view.getHints(\n        this.frameState_ ? this.frameState_.viewHints : undefined,\n      );\n      const viewState = view.getState();\n      frameState = {\n        animate: false,\n        coordinateToPixelTransform: this.coordinateToPixelTransform_,\n        declutter: null,\n        extent: getForViewAndSize(\n          viewState.center,\n          viewState.resolution,\n          viewState.rotation,\n          size,\n        ),\n        index: this.frameIndex_++,\n        layerIndex: 0,\n        layerStatesArray: this.getLayerGroup().getLayerStatesArray(),\n        pixelRatio: this.pixelRatio_,\n        pixelToCoordinateTransform: this.pixelToCoordinateTransform_,\n        postRenderFunctions: [],\n        size: size,\n        tileQueue: this.tileQueue_,\n        time: time,\n        usedTiles: {},\n        viewState: viewState,\n        viewHints: viewHints,\n        wantedTiles: {},\n        mapId: getUid(this),\n        renderTargets: {},\n      };\n      if (viewState.nextCenter && viewState.nextResolution) {\n        const rotation = isNaN(viewState.nextRotation)\n          ? viewState.rotation\n          : viewState.nextRotation;\n\n        frameState.nextExtent = getForViewAndSize(\n          viewState.nextCenter,\n          viewState.nextResolution,\n          rotation,\n          size,\n        );\n      }\n    }\n\n    this.frameState_ = frameState;\n    this.renderer_.renderFrame(frameState);\n\n    if (frameState) {\n      if (frameState.animate) {\n        this.render();\n      }\n      Array.prototype.push.apply(\n        this.postRenderFunctions_,\n        frameState.postRenderFunctions,\n      );\n\n      if (previousFrameState) {\n        const moveStart =\n          !this.previousExtent_ ||\n          (!isEmpty(this.previousExtent_) &&\n            !equalsExtent(frameState.extent, this.previousExtent_));\n        if (moveStart) {\n          this.dispatchEvent(\n            new MapEvent(MapEventType.MOVESTART, this, previousFrameState),\n          );\n          this.previousExtent_ = createOrUpdateEmpty(this.previousExtent_);\n        }\n      }\n\n      const idle =\n        this.previousExtent_ &&\n        !frameState.viewHints[ViewHint.ANIMATING] &&\n        !frameState.viewHints[ViewHint.INTERACTING] &&\n        !equalsExtent(frameState.extent, this.previousExtent_);\n\n      if (idle) {\n        this.dispatchEvent(\n          new MapEvent(MapEventType.MOVEEND, this, frameState),\n        );\n        clone(frameState.extent, this.previousExtent_);\n      }\n    }\n\n    this.dispatchEvent(new MapEvent(MapEventType.POSTRENDER, this, frameState));\n\n    this.renderComplete_ =\n      (this.hasListener(MapEventType.LOADSTART) ||\n        this.hasListener(MapEventType.LOADEND) ||\n        this.hasListener(RenderEventType.RENDERCOMPLETE)) &&\n      !this.tileQueue_.getTilesLoading() &&\n      !this.tileQueue_.getCount() &&\n      !this.getLoadingOrNotReady();\n\n    if (!this.postRenderTimeoutHandle_) {\n      this.postRenderTimeoutHandle_ = setTimeout(() => {\n        this.postRenderTimeoutHandle_ = undefined;\n        this.handlePostRender();\n      }, 0);\n    }\n  }\n\n  /**\n   * Sets the layergroup of this map.\n   * @param {LayerGroup} layerGroup A layer group containing the layers in this map.\n   * @observable\n   * @api\n   */\n  setLayerGroup(layerGroup) {\n    const oldLayerGroup = this.getLayerGroup();\n    if (oldLayerGroup) {\n      this.handleLayerRemove_(new GroupEvent('removelayer', oldLayerGroup));\n    }\n    this.set(MapProperty.LAYERGROUP, layerGroup);\n  }\n\n  /**\n   * Set the size of this map.\n   * @param {import(\"./size.js\").Size|undefined} size The size in pixels of the map in the DOM.\n   * @observable\n   * @api\n   */\n  setSize(size) {\n    this.set(MapProperty.SIZE, size);\n  }\n\n  /**\n   * Set the target element to render this map into.\n   * For accessibility (focus and keyboard events for map navigation), the `target` element must have a\n   *  properly configured `tabindex` attribute. If the `target` element is inside a Shadow DOM, the\n   *  `tabindex` atribute must be set on the custom element's host element.\n   * @param {HTMLElement|string} [target] The Element or id of the Element\n   *     that the map is rendered in.\n   * @observable\n   * @api\n   */\n  setTarget(target) {\n    this.set(MapProperty.TARGET, target);\n  }\n\n  /**\n   * Set the view for this map.\n   * @param {View|Promise<import(\"./View.js\").ViewOptions>|null} view The view that controls this map.\n   * It is also possible to pass a promise that resolves to options for constructing a view.  This\n   * alternative allows view properties to be resolved by sources or other components that load\n   * view-related metadata.\n   * @observable\n   * @api\n   */\n  setView(view) {\n    if (!view || view instanceof View) {\n      this.set(MapProperty.VIEW, view);\n      return;\n    }\n    this.set(MapProperty.VIEW, new View());\n\n    const map = this;\n    view.then(function (viewOptions) {\n      map.setView(new View(viewOptions));\n    });\n  }\n\n  /**\n   * Force a recalculation of the map viewport size.  This should be called when\n   * third-party code changes the size of the map viewport.\n   * @api\n   */\n  updateSize() {\n    const targetElement = this.getTargetElement();\n\n    let size = undefined;\n    if (targetElement) {\n      let width, height;\n      if (isCanvas(targetElement)) {\n        const transform = targetElement.getContext('2d').getTransform();\n        // Use scale components of the transform to calculate the size in CSS pixels\n        width = targetElement.width / transform.a;\n        height = targetElement.height / transform.d;\n      } else {\n        const computedStyle = getComputedStyle(targetElement);\n        width =\n          targetElement.offsetWidth -\n          parseFloat(computedStyle['borderLeftWidth']) -\n          parseFloat(computedStyle['paddingLeft']) -\n          parseFloat(computedStyle['paddingRight']) -\n          parseFloat(computedStyle['borderRightWidth']);\n        height =\n          targetElement.offsetHeight -\n          parseFloat(computedStyle['borderTopWidth']) -\n          parseFloat(computedStyle['paddingTop']) -\n          parseFloat(computedStyle['paddingBottom']) -\n          parseFloat(computedStyle['borderBottomWidth']);\n      }\n      if (!isNaN(width) && !isNaN(height)) {\n        size = [Math.max(0, width), Math.max(0, height)];\n        if (\n          !hasArea(size) &&\n          !!(\n            targetElement.offsetWidth ||\n            targetElement.offsetHeight ||\n            targetElement.getClientRects().length\n          )\n        ) {\n          warn(\n            \"No map visible because the map container's width or height are 0.\",\n          );\n        }\n      }\n    }\n\n    const oldSize = this.getSize();\n    if (size && (!oldSize || !equals(size, oldSize))) {\n      this.updateViewportSize_(size);\n      this.setSize(size);\n    }\n  }\n\n  /**\n   * Recomputes the viewport size and save it on the view object (if any)\n   * @param {import(\"./size.js\").Size|undefined} size The size.\n   * @private\n   */\n  updateViewportSize_(size) {\n    const view = this.getView();\n    if (view) {\n      view.setViewportSize(size);\n    }\n  }\n}\n\n/**\n * @param {MapOptions} options Map options.\n * @return {MapOptionsInternal} Internal map options.\n */\nfunction createOptionsInternal(options) {\n  /**\n   * @type {HTMLElement|Document}\n   */\n  let keyboardEventTarget = null;\n  if (options.keyboardEventTarget !== undefined) {\n    keyboardEventTarget =\n      typeof options.keyboardEventTarget === 'string'\n        ? document.getElementById(options.keyboardEventTarget)\n        : options.keyboardEventTarget;\n  }\n\n  /**\n   * @type {Object<string, *>}\n   */\n  const values = {};\n\n  const layerGroup =\n    options.layers &&\n    typeof (/** @type {?} */ (options.layers).getLayers) === 'function'\n      ? /** @type {LayerGroup} */ (options.layers)\n      : new LayerGroup({\n          layers:\n            /** @type {Collection<import(\"./layer/Base.js\").default>|Array<import(\"./layer/Base.js\").default>} */ (\n              options.layers\n            ),\n        });\n  values[MapProperty.LAYERGROUP] = layerGroup;\n\n  values[MapProperty.TARGET] = options.target;\n\n  values[MapProperty.VIEW] =\n    options.view instanceof View ? options.view : new View();\n\n  /** @type {Collection<import(\"./control/Control.js\").default>} */\n  let controls;\n  if (options.controls !== undefined) {\n    if (Array.isArray(options.controls)) {\n      controls = new Collection(options.controls.slice());\n    } else {\n      assert(\n        typeof (/** @type {?} */ (options.controls).getArray) === 'function',\n        'Expected `controls` to be an array or an `ol/Collection.js`',\n      );\n      controls = options.controls;\n    }\n  }\n\n  /** @type {Collection<import(\"./interaction/Interaction.js\").default>} */\n  let interactions;\n  if (options.interactions !== undefined) {\n    if (Array.isArray(options.interactions)) {\n      interactions = new Collection(options.interactions.slice());\n    } else {\n      assert(\n        typeof (/** @type {?} */ (options.interactions).getArray) ===\n          'function',\n        'Expected `interactions` to be an array or an `ol/Collection.js`',\n      );\n      interactions = options.interactions;\n    }\n  }\n\n  /** @type {Collection<import(\"./Overlay.js\").default>} */\n  let overlays;\n  if (options.overlays !== undefined) {\n    if (Array.isArray(options.overlays)) {\n      overlays = new Collection(options.overlays.slice());\n    } else {\n      assert(\n        typeof (/** @type {?} */ (options.overlays).getArray) === 'function',\n        'Expected `overlays` to be an array or an `ol/Collection.js`',\n      );\n      overlays = options.overlays;\n    }\n  } else {\n    overlays = new Collection();\n  }\n\n  return {\n    controls: controls,\n    interactions: interactions,\n    keyboardEventTarget: keyboardEventTarget,\n    overlays: overlays,\n    values: values,\n  };\n}\nexport default Map;\n", "/**\n * @module ol/Tile\n */\nimport TileState from './TileState.js';\nimport {easeIn} from './easing.js';\nimport EventType from './events/EventType.js';\nimport EventTarget from './events/Target.js';\nimport {abstract} from './util.js';\n\n/**\n * A function that takes a {@link module:ol/Tile~Tile} for the tile and a\n * `{string}` for the url as arguments. The default is\n * ```js\n * source.setTileLoadFunction(function(tile, src) {\n *   tile.getImage().src = src;\n * });\n * ```\n * For more fine grained control, the load function can use fetch or XMLHttpRequest and involve\n * error handling:\n *\n * ```js\n * import TileState from 'ol/TileState.js';\n *\n * source.setTileLoadFunction(function(tile, src) {\n *   const xhr = new XMLHttpRequest();\n *   xhr.responseType = 'blob';\n *   xhr.addEventListener('loadend', function (evt) {\n *     const data = this.response;\n *     if (data !== undefined) {\n *       tile.getImage().src = URL.createObjectURL(data);\n *     } else {\n *       tile.setState(TileState.ERROR);\n *     }\n *   });\n *   xhr.addEventListener('error', function () {\n *     tile.setState(TileState.ERROR);\n *   });\n *   xhr.open('GET', src);\n *   xhr.send();\n * });\n * ```\n *\n * @typedef {function(Tile, string): void} LoadFunction\n * @api\n */\n\n/**\n * {@link module:ol/source/Tile~TileSource} sources use a function of this type to get\n * the url that provides a tile for a given tile coordinate.\n *\n * This function takes a {@link module:ol/tilecoord~TileCoord} for the tile\n * coordinate, a `{number}` representing the pixel ratio and a\n * {@link module:ol/proj/Projection~Projection} for the projection  as arguments\n * and returns a `{string}` representing the tile URL, or undefined if no tile\n * should be requested for the passed tile coordinate.\n *\n * @typedef {function(import(\"./tilecoord.js\").TileCoord, number,\n *           import(\"./proj/Projection.js\").default): (string|undefined)} UrlFunction\n * @api\n */\n\n/**\n * @typedef {Object} Options\n * @property {number} [transition=250] A duration for tile opacity\n * transitions in milliseconds. A duration of 0 disables the opacity transition.\n * @property {boolean} [interpolate=false] Use interpolated values when resampling.  By default,\n * the nearest neighbor is used when resampling.\n * @api\n */\n\n/**\n * @classdesc\n * Base class for tiles.\n *\n * @abstract\n */\nclass Tile extends EventTarget {\n  /**\n   * @param {import(\"./tilecoord.js\").TileCoord} tileCoord Tile coordinate.\n   * @param {import(\"./TileState.js\").default} state State.\n   * @param {Options} [options] Tile options.\n   */\n  constructor(tileCoord, state, options) {\n    super();\n\n    options = options ? options : {};\n\n    /**\n     * @type {import(\"./tilecoord.js\").TileCoord}\n     */\n    this.tileCoord = tileCoord;\n\n    /**\n     * @protected\n     * @type {import(\"./TileState.js\").default}\n     */\n    this.state = state;\n\n    /**\n     * A key assigned to the tile. This is used in conjunction with a source key\n     * to determine if a cached version of this tile may be used by the renderer.\n     * @type {string}\n     */\n    this.key = '';\n\n    /**\n     * The duration for the opacity transition.\n     * @private\n     * @type {number}\n     */\n    this.transition_ =\n      options.transition === undefined ? 250 : options.transition;\n\n    /**\n     * Lookup of start times for rendering transitions.  If the start time is\n     * equal to -1, the transition is complete.\n     * @private\n     * @type {Object<string, number>}\n     */\n    this.transitionStarts_ = {};\n\n    /**\n     * @type {boolean}\n     */\n    this.interpolate = !!options.interpolate;\n  }\n\n  /**\n   * @protected\n   */\n  changed() {\n    this.dispatchEvent(EventType.CHANGE);\n  }\n\n  /**\n   * Called by the tile cache when the tile is removed from the cache due to expiry\n   */\n  release() {\n    // to remove the `change` listener on this tile in `ol/TileQueue#handleTileChange`\n    this.setState(TileState.EMPTY);\n  }\n\n  /**\n   * @return {string} Key.\n   */\n  getKey() {\n    return this.key + '/' + this.tileCoord;\n  }\n\n  /**\n   * Get the tile coordinate for this tile.\n   * @return {import(\"./tilecoord.js\").TileCoord} The tile coordinate.\n   * @api\n   */\n  getTileCoord() {\n    return this.tileCoord;\n  }\n\n  /**\n   * @return {import(\"./TileState.js\").default} State.\n   */\n  getState() {\n    return this.state;\n  }\n\n  /**\n   * Sets the state of this tile. If you write your own {@link module:ol/Tile~LoadFunction tileLoadFunction} ,\n   * it is important to set the state correctly to {@link module:ol/TileState~ERROR}\n   * when the tile cannot be loaded. Otherwise the tile cannot be removed from\n   * the tile queue and will block other requests.\n   * @param {import(\"./TileState.js\").default} state State.\n   * @api\n   */\n  setState(state) {\n    if (this.state === TileState.EMPTY) {\n      // no more state changes\n      return;\n    }\n    if (this.state !== TileState.ERROR && this.state > state) {\n      throw new Error('Tile load sequence violation');\n    }\n    this.state = state;\n    this.changed();\n  }\n\n  /**\n   * Load the image or retry if loading previously failed.\n   * Loading is taken care of by the tile queue, and calling this method is\n   * only needed for preloading or for reloading in case of an error.\n   * @abstract\n   * @api\n   */\n  load() {\n    abstract();\n  }\n\n  /**\n   * Get the alpha value for rendering.\n   * @param {string} id An id for the renderer.\n   * @param {number} time The render frame time.\n   * @return {number} A number between 0 and 1.\n   */\n  getAlpha(id, time) {\n    if (!this.transition_) {\n      return 1;\n    }\n\n    let start = this.transitionStarts_[id];\n    if (!start) {\n      start = time;\n      this.transitionStarts_[id] = start;\n    } else if (start === -1) {\n      return 1;\n    }\n\n    const delta = time - start + 1000 / 60; // avoid rendering at 0\n    if (delta >= this.transition_) {\n      return 1;\n    }\n    return easeIn(delta / this.transition_);\n  }\n\n  /**\n   * Determine if a tile is in an alpha transition.  A tile is considered in\n   * transition if tile.getAlpha() has not yet been called or has been called\n   * and returned 1.\n   * @param {string} id An id for the renderer.\n   * @return {boolean} The tile is in transition.\n   */\n  inTransition(id) {\n    if (!this.transition_) {\n      return false;\n    }\n    return this.transitionStarts_[id] !== -1;\n  }\n\n  /**\n   * Mark a transition as complete.\n   * @param {string} id An id for the renderer.\n   */\n  endTransition(id) {\n    if (this.transition_) {\n      this.transitionStarts_[id] = -1;\n    }\n  }\n\n  /**\n   * @override\n   */\n  disposeInternal() {\n    this.release();\n    super.disposeInternal();\n  }\n}\n\nexport default Tile;\n", "/**\n * @module ol/DataTile\n */\nimport Tile from './Tile.js';\nimport TileState from './TileState.js';\nimport {createCanvasContext2D} from './dom.js';\n\n/**\n * @typedef {HTMLImageElement|HTMLCanvasElement|OffscreenCanvas|HTMLVideoElement|ImageBitmap} ImageLike\n */\n\n/**\n * @typedef {Uint8Array|Uint8ClampedArray|Float32Array|DataView} ArrayLike\n */\n\n/**\n * Data that can be used with a DataTile.\n * @typedef {ArrayLike|ImageLike} Data\n */\n\n/**\n * @param {Data} data Tile data.\n * @return {ImageLike|null} The image-like data.\n */\nexport function asImageLike(data) {\n  return data instanceof Image ||\n    data instanceof HTMLCanvasElement ||\n    data instanceof HTMLVideoElement ||\n    data instanceof ImageBitmap\n    ? data\n    : null;\n}\n\n/**\n * @param {Data} data Tile data.\n * @return {ArrayLike|null} The array-like data.\n */\nexport function asArrayLike(data) {\n  return data instanceof Uint8Array ||\n    data instanceof Uint8ClampedArray ||\n    data instanceof Float32Array ||\n    data instanceof DataView\n    ? data\n    : null;\n}\n\n/**\n * This is set as the cancellation reason when a tile is disposed.\n */\nexport const disposedError = new Error('disposed');\n\n/**\n * @type {CanvasRenderingContext2D|OffscreenCanvasRenderingContext2D|null}\n */\nlet sharedContext = null;\n\n/**\n * @param {ImageLike} image The image.\n * @return {Uint8ClampedArray} The data.\n */\nexport function toArray(image) {\n  if (!sharedContext) {\n    sharedContext = createCanvasContext2D(\n      image.width,\n      image.height,\n      undefined,\n      {willReadFrequently: true},\n    );\n  }\n  const canvas = sharedContext.canvas;\n  const width = image.width;\n  if (canvas.width !== width) {\n    canvas.width = width;\n  }\n  const height = image.height;\n  if (canvas.height !== height) {\n    canvas.height = height;\n  }\n  sharedContext.clearRect(0, 0, width, height);\n  sharedContext.drawImage(image, 0, 0);\n  return sharedContext.getImageData(0, 0, width, height).data;\n}\n\n/**\n * @type {import('./size.js').Size}\n */\nconst defaultSize = [256, 256];\n\n/**\n * @typedef {Object} Options\n * @property {import(\"./tilecoord.js\").TileCoord} tileCoord Tile coordinate.\n * @property {function(): Promise<Data>} loader Data loader.  For loaders that generate images,\n * the promise should not resolve until the image is loaded.\n * @property {number} [transition=250] A duration for tile opacity\n * transitions in milliseconds. A duration of 0 disables the opacity transition.\n * @property {boolean} [interpolate=false] Use interpolated values when resampling.  By default,\n * the nearest neighbor is used when resampling.\n * @property {import('./size.js').Size} [size=[256, 256]] Tile size.\n * @property {AbortController} [controller] An abort controller.\n * @api\n */\n\nclass DataTile extends Tile {\n  /**\n   * @param {Options} options Tile options.\n   */\n  constructor(options) {\n    const state = TileState.IDLE;\n\n    super(options.tileCoord, state, {\n      transition: options.transition,\n      interpolate: options.interpolate,\n    });\n\n    /**\n     * @type {function(): Promise<Data>}\n     * @private\n     */\n    this.loader_ = options.loader;\n\n    /**\n     * @type {Data}\n     * @private\n     */\n    this.data_ = null;\n\n    /**\n     * @type {Error}\n     * @private\n     */\n    this.error_ = null;\n\n    /**\n     * @type {import('./size.js').Size|null}\n     * @private\n     */\n    this.size_ = options.size || null;\n\n    /**\n     * @type {AbortController|null}\n     * @private\n     */\n    this.controller_ = options.controller || null;\n  }\n\n  /**\n   * Get the tile size.\n   * @return {import('./size.js').Size} Tile size.\n   */\n  getSize() {\n    if (this.size_) {\n      return this.size_;\n    }\n    const imageData = asImageLike(this.data_);\n    if (imageData) {\n      return [imageData.width, imageData.height];\n    }\n    return defaultSize;\n  }\n\n  /**\n   * Get the data for the tile.\n   * @return {Data} Tile data.\n   * @api\n   */\n  getData() {\n    return this.data_;\n  }\n\n  /**\n   * Get any loading error.\n   * @return {Error} Loading error.\n   * @api\n   */\n  getError() {\n    return this.error_;\n  }\n\n  /**\n   * Load the tile data.\n   * @api\n   * @override\n   */\n  load() {\n    if (this.state !== TileState.IDLE && this.state !== TileState.ERROR) {\n      return;\n    }\n    this.state = TileState.LOADING;\n    this.changed();\n\n    const self = this;\n    this.loader_()\n      .then(function (data) {\n        self.data_ = data;\n        self.state = TileState.LOADED;\n        self.changed();\n      })\n      .catch(function (error) {\n        self.error_ = error;\n        self.state = TileState.ERROR;\n        self.changed();\n      });\n  }\n\n  /**\n   * Clean up.\n   * @override\n   */\n  disposeInternal() {\n    if (this.controller_) {\n      this.controller_.abort(disposedError);\n      this.controller_ = null;\n    }\n    super.disposeInternal();\n  }\n}\n\nexport default DataTile;\n", "/**\n * @module ol/ImageTile\n */\nimport {listenImage} from './Image.js';\nimport Tile from './Tile.js';\nimport TileState from './TileState.js';\nimport {createCanvasContext2D} from './dom.js';\nimport {WORKER_OFFSCREEN_CANVAS} from './has.js';\n\nclass ImageTile extends Tile {\n  /**\n   * @param {import(\"./tilecoord.js\").TileCoord} tileCoord Tile coordinate.\n   * @param {import(\"./TileState.js\").default} state State.\n   * @param {string} src Image source URI.\n   * @param {import('./dom.js').ImageAttributes} imageAttributes Image attributes options.\n   * @param {import(\"./Tile.js\").LoadFunction} tileLoadFunction Tile load function.\n   * @param {import(\"./Tile.js\").Options} [options] Tile options.\n   */\n  constructor(\n    tileCoord,\n    state,\n    src,\n    imageAttributes,\n    tileLoadFunction,\n    options,\n  ) {\n    super(tileCoord, state, options);\n\n    /**\n     * @private\n     * @type {?string}\n     */\n    this.crossOrigin_ = imageAttributes?.crossOrigin;\n\n    /**\n     * @private\n     * @type {ReferrerPolicy}\n     */\n    this.referrerPolicy_ = imageAttributes?.referrerPolicy;\n\n    /**\n     * Image URI\n     *\n     * @private\n     * @type {string}\n     */\n    this.src_ = src;\n\n    this.key = src;\n\n    /**\n     * @private\n     * @type {HTMLImageElement|HTMLCanvasElement|OffscreenCanvas}\n     */\n    this.image_;\n\n    if (WORKER_OFFSCREEN_CANVAS) {\n      this.image_ = new OffscreenCanvas(1, 1);\n    } else {\n      this.image_ = new Image();\n      if (this.crossOrigin_ !== null) {\n        this.image_.crossOrigin = this.crossOrigin_;\n      }\n      if (this.referrerPolicy_ !== undefined) {\n        this.image_.referrerPolicy = this.referrerPolicy_;\n      }\n    }\n\n    /**\n     * @private\n     * @type {?function():void}\n     */\n    this.unlisten_ = null;\n\n    /**\n     * @private\n     * @type {import(\"./Tile.js\").LoadFunction}\n     */\n    this.tileLoadFunction_ = tileLoadFunction;\n  }\n\n  /**\n   * Get the HTML image element for this tile (may be a Canvas, OffscreenCanvas, Image, or Video).\n   * @return {HTMLCanvasElement|OffscreenCanvas|HTMLImageElement|HTMLVideoElement} Image.\n   * @api\n   */\n  getImage() {\n    return this.image_;\n  }\n\n  /**\n   * Sets an HTML image element for this tile (may be a Canvas or preloaded Image).\n   * @param {HTMLCanvasElement|OffscreenCanvas|HTMLImageElement} element Element.\n   */\n  setImage(element) {\n    this.image_ = element;\n    this.state = TileState.LOADED;\n    this.unlistenImage_();\n    this.changed();\n  }\n\n  /**\n   * Get the cross origin of the ImageTile.\n   * @return {string} Cross origin.\n   */\n  getCrossOrigin() {\n    return this.crossOrigin_;\n  }\n\n  /**\n   * Get the referrer policy of the ImageTile.\n   * @return {ReferrerPolicy} Referrer policy.\n   */\n  getReferrerPolicy() {\n    return this.referrerPolicy_;\n  }\n\n  /**\n   * Tracks loading or read errors.\n   *\n   * @private\n   */\n  handleImageError_() {\n    this.state = TileState.ERROR;\n    this.unlistenImage_();\n    this.image_ = getBlankImage();\n    this.changed();\n  }\n\n  /**\n   * Tracks successful image load.\n   *\n   * @private\n   */\n  handleImageLoad_() {\n    if (WORKER_OFFSCREEN_CANVAS) {\n      // OffscreenCanvas does not have naturalWidth and naturalHeight\n      this.state = TileState.LOADED;\n    } else {\n      const image = /** @type {HTMLImageElement} */ (this.image_);\n      if (image.naturalWidth && image.naturalHeight) {\n        this.state = TileState.LOADED;\n      } else {\n        this.state = TileState.EMPTY;\n      }\n    }\n    this.unlistenImage_();\n    this.changed();\n  }\n\n  /**\n   * Load the image or retry if loading previously failed.\n   * Loading is taken care of by the tile queue, and calling this method is\n   * only needed for preloading or for reloading in case of an error.\n   *\n   * To retry loading tiles on failed requests, use a custom `tileLoadFunction`\n   * that checks for error status codes and reloads only when the status code is\n   * 408, 429, 500, 502, 503 and 504, and only when not too many retries have been\n   * made already:\n   *\n   * ```js\n   * const retryCodes = [408, 429, 500, 502, 503, 504];\n   * const retries = {};\n   * source.setTileLoadFunction((tile, src) => {\n   *   const image = tile.getImage();\n   *   fetch(src)\n   *     .then((response) => {\n   *       if (retryCodes.includes(response.status)) {\n   *         retries[src] = (retries[src] || 0) + 1;\n   *         if (retries[src] <= 3) {\n   *           setTimeout(() => tile.load(), retries[src] * 1000);\n   *         }\n   *         return Promise.reject();\n   *       }\n   *       return response.blob();\n   *     })\n   *     .then((blob) => {\n   *       const imageUrl = URL.createObjectURL(blob);\n   *       image.src = imageUrl;\n   *       setTimeout(() => URL.revokeObjectURL(imageUrl), 5000);\n   *     })\n   *     .catch(() => tile.setState(3)); // error\n   * });\n   * ```\n   * @api\n   * @override\n   */\n  load() {\n    if (this.state == TileState.ERROR) {\n      this.state = TileState.IDLE;\n      this.image_ = new Image();\n      if (this.crossOrigin_ !== null) {\n        this.image_.crossOrigin = this.crossOrigin_;\n      }\n      if (this.referrerPolicy_ !== undefined) {\n        this.image_.referrerPolicy = this.referrerPolicy_;\n      }\n    }\n    if (this.state == TileState.IDLE) {\n      this.state = TileState.LOADING;\n      this.changed();\n      this.tileLoadFunction_(this, this.src_);\n      this.unlisten_ = listenImage(\n        this.image_,\n        this.handleImageLoad_.bind(this),\n        this.handleImageError_.bind(this),\n      );\n    }\n  }\n\n  /**\n   * Discards event handlers which listen for load completion or errors.\n   *\n   * @private\n   */\n  unlistenImage_() {\n    if (this.unlisten_) {\n      this.unlisten_();\n      this.unlisten_ = null;\n    }\n  }\n\n  /**\n   * @override\n   */\n  disposeInternal() {\n    this.unlistenImage_();\n    this.image_ = null;\n    super.disposeInternal();\n  }\n}\n\n/**\n * Get a 1-pixel blank image.\n * @return {HTMLCanvasElement|OffscreenCanvas} Blank image.\n */\nfunction getBlankImage() {\n  const ctx = createCanvasContext2D(1, 1);\n  ctx.fillStyle = 'rgba(0,0,0,0)';\n  ctx.fillRect(0, 0, 1, 1);\n  return ctx.canvas;\n}\n\nexport default ImageTile;\n", "/**\n * @module ol/TileRange\n */\n\n/**\n * A representation of a contiguous block of tiles.  A tile range is specified\n * by its min/max tile coordinates and is inclusive of coordinates.\n */\nclass TileRange {\n  /**\n   * @param {number} minX Minimum X.\n   * @param {number} maxX Maximum X.\n   * @param {number} minY Minimum Y.\n   * @param {number} maxY Maximum Y.\n   */\n  constructor(minX, maxX, minY, maxY) {\n    /**\n     * @type {number}\n     */\n    this.minX = minX;\n\n    /**\n     * @type {number}\n     */\n    this.maxX = maxX;\n\n    /**\n     * @type {number}\n     */\n    this.minY = minY;\n\n    /**\n     * @type {number}\n     */\n    this.maxY = maxY;\n  }\n\n  /**\n   * @param {import(\"./tilecoord.js\").TileCoord} tileCoord Tile coordinate.\n   * @return {boolean} Contains tile coordinate.\n   */\n  contains(tileCoord) {\n    return this.containsXY(tileCoord[1], tileCoord[2]);\n  }\n\n  /**\n   * @param {TileRange} tileRange Tile range.\n   * @return {boolean} Contains.\n   */\n  containsTileRange(tileRange) {\n    return (\n      this.minX <= tileRange.minX &&\n      tileRange.maxX <= this.maxX &&\n      this.minY <= tileRange.minY &&\n      tileRange.maxY <= this.maxY\n    );\n  }\n\n  /**\n   * @param {number} x Tile coordinate x.\n   * @param {number} y Tile coordinate y.\n   * @return {boolean} Contains coordinate.\n   */\n  containsXY(x, y) {\n    return this.minX <= x && x <= this.maxX && this.minY <= y && y <= this.maxY;\n  }\n\n  /**\n   * @param {TileRange} tileRange Tile range.\n   * @return {boolean} Equals.\n   */\n  equals(tileRange) {\n    return (\n      this.minX == tileRange.minX &&\n      this.minY == tileRange.minY &&\n      this.maxX == tileRange.maxX &&\n      this.maxY == tileRange.maxY\n    );\n  }\n\n  /**\n   * @param {TileRange} tileRange Tile range.\n   */\n  extend(tileRange) {\n    if (tileRange.minX < this.minX) {\n      this.minX = tileRange.minX;\n    }\n    if (tileRange.maxX > this.maxX) {\n      this.maxX = tileRange.maxX;\n    }\n    if (tileRange.minY < this.minY) {\n      this.minY = tileRange.minY;\n    }\n    if (tileRange.maxY > this.maxY) {\n      this.maxY = tileRange.maxY;\n    }\n  }\n\n  /**\n   * @return {number} Height.\n   */\n  getHeight() {\n    return this.maxY - this.minY + 1;\n  }\n\n  /**\n   * @return {import(\"./size.js\").Size} Size.\n   */\n  getSize() {\n    return [this.getWidth(), this.getHeight()];\n  }\n\n  /**\n   * @return {number} Width.\n   */\n  getWidth() {\n    return this.maxX - this.minX + 1;\n  }\n\n  /**\n   * @param {TileRange} tileRange Tile range.\n   * @return {boolean} Intersects.\n   */\n  intersects(tileRange) {\n    return (\n      this.minX <= tileRange.maxX &&\n      this.maxX >= tileRange.minX &&\n      this.minY <= tileRange.maxY &&\n      this.maxY >= tileRange.minY\n    );\n  }\n}\n\n/**\n * @param {number} minX Minimum X.\n * @param {number} maxX Maximum X.\n * @param {number} minY Minimum Y.\n * @param {number} maxY Maximum Y.\n * @param {TileRange} [tileRange] TileRange.\n * @return {TileRange} Tile range.\n */\nexport function createOrUpdate(minX, maxX, minY, maxY, tileRange) {\n  if (tileRange !== undefined) {\n    tileRange.minX = minX;\n    tileRange.maxX = maxX;\n    tileRange.minY = minY;\n    tileRange.maxY = maxY;\n    return tileRange;\n  }\n  return new TileRange(minX, maxX, minY, maxY);\n}\n\nexport default TileRange;\n", "/**\n * @module ol/reproj\n */\nimport {createCanvasContext2D, releaseCanvas} from './dom.js';\nimport {\n  containsCoordinate,\n  createEmpty,\n  extend,\n  forEachCorner,\n  getCenter,\n  getHeight,\n  getTopLeft,\n  getWidth,\n} from './extent.js';\nimport {solveLinearSystem} from './math.js';\nimport {getPointResolution, transform} from './proj.js';\n\nlet brokenDiagonalRendering_;\n\n/**\n * @type {Array<HTMLCanvasElement|OffscreenCanvas>}\n */\nexport const canvasPool = [];\n\n/**\n * This draws a small triangle into a canvas by setting the triangle as the clip region\n * and then drawing a (too large) rectangle\n *\n * @param {CanvasRenderingContext2D|OffscreenCanvasRenderingContext2D} ctx The context in which to draw the triangle\n * @param {number} u1 The x-coordinate of the second point. The first point is 0,0.\n * @param {number} v1 The y-coordinate of the second point.\n * @param {number} u2 The x-coordinate of the third point.\n * @param {number} v2 The y-coordinate of the third point.\n */\nfunction drawTestTriangle(ctx, u1, v1, u2, v2) {\n  ctx.beginPath();\n  ctx.moveTo(0, 0);\n  ctx.lineTo(u1, v1);\n  ctx.lineTo(u2, v2);\n  ctx.closePath();\n  ctx.save();\n  ctx.clip();\n  ctx.fillRect(0, 0, Math.max(u1, u2) + 1, Math.max(v1, v2));\n  ctx.restore();\n}\n\n/**\n * Given the data from getImageData, see if the right values appear at the provided offset.\n * Returns true if either the color or transparency is off\n *\n * @param {Uint8ClampedArray} data The data returned from getImageData\n * @param {number} offset The pixel offset from the start of data.\n * @return {boolean} true if the diagonal rendering is broken\n */\nfunction verifyBrokenDiagonalRendering(data, offset) {\n  // the values ought to be close to the rgba(210, 0, 0, 0.75)\n  return (\n    Math.abs(data[offset * 4] - 210) > 2 ||\n    Math.abs(data[offset * 4 + 3] - 0.75 * 255) > 2\n  );\n}\n\n/**\n * Determines if the current browser configuration can render triangular clip regions correctly.\n * This value is cached so the function is only expensive the first time called.\n * Firefox on Windows (as of now) does not if HWA is enabled. See https://bugzilla.mozilla.org/show_bug.cgi?id=1606976\n * Chrome works, and everything seems to work on OSX and Android. This function caches the\n * result. I suppose that it is conceivably possible that a browser might flip modes while the app is\n * running, but lets hope not.\n *\n * @return {boolean} true if the Diagonal Rendering is broken.\n */\nfunction isBrokenDiagonalRendering() {\n  if (brokenDiagonalRendering_ === undefined) {\n    const ctx = createCanvasContext2D(6, 6, canvasPool);\n    ctx.globalCompositeOperation = 'lighter';\n    ctx.fillStyle = 'rgba(210, 0, 0, 0.75)';\n    drawTestTriangle(ctx, 4, 5, 4, 0);\n    drawTestTriangle(ctx, 4, 5, 0, 5);\n    const data = ctx.getImageData(0, 0, 3, 3).data;\n    brokenDiagonalRendering_ =\n      verifyBrokenDiagonalRendering(data, 0) ||\n      verifyBrokenDiagonalRendering(data, 4) ||\n      verifyBrokenDiagonalRendering(data, 8);\n    releaseCanvas(ctx);\n    canvasPool.push(ctx.canvas);\n  }\n\n  return brokenDiagonalRendering_;\n}\n\n/**\n * Calculates ideal resolution to use from the source in order to achieve\n * pixel mapping as close as possible to 1:1 during reprojection.\n * The resolution is calculated regardless of what resolutions\n * are actually available in the dataset (TileGrid, Image, ...).\n *\n * @param {import(\"./proj/Projection.js\").default} sourceProj Source projection.\n * @param {import(\"./proj/Projection.js\").default} targetProj Target projection.\n * @param {import(\"./coordinate.js\").Coordinate} targetCenter Target center.\n * @param {number} targetResolution Target resolution.\n * @return {number} The best resolution to use. Can be +-Infinity, NaN or 0.\n */\nexport function calculateSourceResolution(\n  sourceProj,\n  targetProj,\n  targetCenter,\n  targetResolution,\n) {\n  const sourceCenter = transform(targetCenter, targetProj, sourceProj);\n\n  // calculate the ideal resolution of the source data\n  let sourceResolution = getPointResolution(\n    targetProj,\n    targetResolution,\n    targetCenter,\n  );\n\n  const targetMetersPerUnit = targetProj.getMetersPerUnit();\n  if (targetMetersPerUnit !== undefined) {\n    sourceResolution *= targetMetersPerUnit;\n  }\n  const sourceMetersPerUnit = sourceProj.getMetersPerUnit();\n  if (sourceMetersPerUnit !== undefined) {\n    sourceResolution /= sourceMetersPerUnit;\n  }\n\n  // Based on the projection properties, the point resolution at the specified\n  // coordinates may be slightly different. We need to reverse-compensate this\n  // in order to achieve optimal results.\n\n  const sourceExtent = sourceProj.getExtent();\n  if (!sourceExtent || containsCoordinate(sourceExtent, sourceCenter)) {\n    const compensationFactor =\n      getPointResolution(sourceProj, sourceResolution, sourceCenter) /\n      sourceResolution;\n    if (isFinite(compensationFactor) && compensationFactor > 0) {\n      sourceResolution /= compensationFactor;\n    }\n  }\n\n  return sourceResolution;\n}\n\n/**\n * Calculates ideal resolution to use from the source in order to achieve\n * pixel mapping as close as possible to 1:1 during reprojection.\n * The resolution is calculated regardless of what resolutions\n * are actually available in the dataset (TileGrid, Image, ...).\n *\n * @param {import(\"./proj/Projection.js\").default} sourceProj Source projection.\n * @param {import(\"./proj/Projection.js\").default} targetProj Target projection.\n * @param {import(\"./extent.js\").Extent} targetExtent Target extent\n * @param {number} targetResolution Target resolution.\n * @return {number} The best resolution to use. Can be +-Infinity, NaN or 0.\n */\nexport function calculateSourceExtentResolution(\n  sourceProj,\n  targetProj,\n  targetExtent,\n  targetResolution,\n) {\n  const targetCenter = getCenter(targetExtent);\n  let sourceResolution = calculateSourceResolution(\n    sourceProj,\n    targetProj,\n    targetCenter,\n    targetResolution,\n  );\n\n  if (!isFinite(sourceResolution) || sourceResolution <= 0) {\n    forEachCorner(targetExtent, function (corner) {\n      sourceResolution = calculateSourceResolution(\n        sourceProj,\n        targetProj,\n        corner,\n        targetResolution,\n      );\n      return isFinite(sourceResolution) && sourceResolution > 0;\n    });\n  }\n\n  return sourceResolution;\n}\n\n/**\n * @typedef {Object} ImageExtent\n * @property {import(\"./extent.js\").Extent} extent Extent.\n * @property {import(\"./extent.js\").Extent} [clipExtent] Clip extent.\n * @property {import('./DataTile.js').ImageLike} image Image.\n */\n\n/**\n * Renders the source data into new canvas based on the triangulation.\n *\n * @param {number} width Width of the canvas.\n * @param {number} height Height of the canvas.\n * @param {number} pixelRatio Pixel ratio.\n * @param {number} sourceResolution Source resolution.\n * @param {import(\"./extent.js\").Extent} sourceExtent Extent of the data source.\n * @param {number} targetResolution Target resolution.\n * @param {import(\"./extent.js\").Extent} targetExtent Target extent.\n * @param {import(\"./reproj/Triangulation.js\").default} triangulation Calculated triangulation.\n * @param {Array<ImageExtent>} sources Array of sources.\n * @param {number} gutter Gutter of the sources.\n * @param {boolean} [renderEdges] Render reprojection edges.\n * @param {boolean} [interpolate] Use linear interpolation when resampling.\n * @param {boolean} [drawSingle] Draw single source images directly without stitchContext.\n * @param {boolean} [clipExtent] Clip stitchContext to sourceExtent.\n * @return {HTMLCanvasElement|OffscreenCanvas} Canvas with reprojected data.\n */\nexport function render(\n  width,\n  height,\n  pixelRatio,\n  sourceResolution,\n  sourceExtent,\n  targetResolution,\n  targetExtent,\n  triangulation,\n  sources,\n  gutter,\n  renderEdges,\n  interpolate,\n  drawSingle,\n  clipExtent,\n) {\n  const context = createCanvasContext2D(\n    Math.round(pixelRatio * width),\n    Math.round(pixelRatio * height),\n    canvasPool,\n  );\n\n  if (!interpolate) {\n    context.imageSmoothingEnabled = false;\n  }\n\n  if (sources.length === 0) {\n    return context.canvas;\n  }\n\n  context.scale(pixelRatio, pixelRatio);\n\n  function pixelRound(value) {\n    return Math.round(value * pixelRatio) / pixelRatio;\n  }\n\n  context.globalCompositeOperation = 'lighter';\n\n  const sourceDataExtent = createEmpty();\n  sources.forEach(function (src, i, arr) {\n    extend(sourceDataExtent, src.extent);\n  });\n\n  let stitchContext;\n  const stitchScale = pixelRatio / sourceResolution;\n  // Round up Float32 scale values to prevent interpolation in Firefox.\n  const inverseScale = (interpolate ? 1 : 1 + Math.pow(2, -24)) / stitchScale;\n\n  if (!drawSingle || sources.length !== 1 || gutter !== 0) {\n    stitchContext = createCanvasContext2D(\n      Math.round(getWidth(sourceDataExtent) * stitchScale),\n      Math.round(getHeight(sourceDataExtent) * stitchScale),\n      canvasPool,\n    );\n\n    if (!interpolate) {\n      stitchContext.imageSmoothingEnabled = false;\n    }\n    if (sourceExtent && clipExtent) {\n      const xPos = (sourceExtent[0] - sourceDataExtent[0]) * stitchScale;\n      const yPos = -(sourceExtent[3] - sourceDataExtent[3]) * stitchScale;\n      const width = getWidth(sourceExtent) * stitchScale;\n      const height = getHeight(sourceExtent) * stitchScale;\n      stitchContext.rect(xPos, yPos, width, height);\n      stitchContext.clip();\n    }\n\n    sources.forEach(function (src, i, arr) {\n      // This test should never fail -- but it does. Need to find a fix the upstream condition\n      if (src.image.width > 0 && src.image.height > 0) {\n        if (src.clipExtent) {\n          stitchContext.save();\n          const xPos = (src.clipExtent[0] - sourceDataExtent[0]) * stitchScale;\n          const yPos = -(src.clipExtent[3] - sourceDataExtent[3]) * stitchScale;\n          const width = getWidth(src.clipExtent) * stitchScale;\n          const height = getHeight(src.clipExtent) * stitchScale;\n          stitchContext.rect(\n            interpolate ? xPos : Math.round(xPos),\n            interpolate ? yPos : Math.round(yPos),\n            interpolate ? width : Math.round(xPos + width) - Math.round(xPos),\n            interpolate ? height : Math.round(yPos + height) - Math.round(yPos),\n          );\n          stitchContext.clip();\n        }\n\n        const xPos = (src.extent[0] - sourceDataExtent[0]) * stitchScale;\n        const yPos = -(src.extent[3] - sourceDataExtent[3]) * stitchScale;\n        const srcWidth = getWidth(src.extent) * stitchScale;\n        const srcHeight = getHeight(src.extent) * stitchScale;\n        stitchContext.drawImage(\n          src.image,\n          gutter,\n          gutter,\n          src.image.width - 2 * gutter,\n          src.image.height - 2 * gutter,\n          interpolate ? xPos : Math.round(xPos),\n          interpolate ? yPos : Math.round(yPos),\n          interpolate\n            ? srcWidth\n            : Math.round(xPos + srcWidth) - Math.round(xPos),\n          interpolate\n            ? srcHeight\n            : Math.round(yPos + srcHeight) - Math.round(yPos),\n        );\n\n        if (src.clipExtent) {\n          stitchContext.restore();\n        }\n      }\n    });\n  }\n  const targetTopLeft = getTopLeft(targetExtent);\n\n  triangulation.getTriangles().forEach(function (triangle, i, arr) {\n    /* Calculate affine transform (src -> dst)\n     * Resulting matrix can be used to transform coordinate\n     * from `sourceProjection` to destination pixels.\n     *\n     * To optimize number of context calls and increase numerical stability,\n     * we also do the following operations:\n     * trans(-topLeftExtentCorner), scale(1 / targetResolution), scale(1, -1)\n     * here before solving the linear system so [ui, vi] are pixel coordinates.\n     *\n     * Src points: xi, yi\n     * Dst points: ui, vi\n     * Affine coefficients: aij\n     *\n     * | x0 y0 1  0  0 0 |   |a00|   |u0|\n     * | x1 y1 1  0  0 0 |   |a01|   |u1|\n     * | x2 y2 1  0  0 0 | x |a02| = |u2|\n     * |  0  0 0 x0 y0 1 |   |a10|   |v0|\n     * |  0  0 0 x1 y1 1 |   |a11|   |v1|\n     * |  0  0 0 x2 y2 1 |   |a12|   |v2|\n     */\n    const source = triangle.source;\n    const target = triangle.target;\n    let x0 = source[0][0],\n      y0 = source[0][1];\n    let x1 = source[1][0],\n      y1 = source[1][1];\n    let x2 = source[2][0],\n      y2 = source[2][1];\n    // Make sure that everything is on pixel boundaries\n    const u0 = pixelRound((target[0][0] - targetTopLeft[0]) / targetResolution);\n    const v0 = pixelRound(\n      -(target[0][1] - targetTopLeft[1]) / targetResolution,\n    );\n    const u1 = pixelRound((target[1][0] - targetTopLeft[0]) / targetResolution);\n    const v1 = pixelRound(\n      -(target[1][1] - targetTopLeft[1]) / targetResolution,\n    );\n    const u2 = pixelRound((target[2][0] - targetTopLeft[0]) / targetResolution);\n    const v2 = pixelRound(\n      -(target[2][1] - targetTopLeft[1]) / targetResolution,\n    );\n\n    // Shift all the source points to improve numerical stability\n    // of all the subsequent calculations. The [x0, y0] is used here.\n    // This is also used to simplify the linear system.\n    const sourceNumericalShiftX = x0;\n    const sourceNumericalShiftY = y0;\n    x0 = 0;\n    y0 = 0;\n    x1 -= sourceNumericalShiftX;\n    y1 -= sourceNumericalShiftY;\n    x2 -= sourceNumericalShiftX;\n    y2 -= sourceNumericalShiftY;\n\n    const augmentedMatrix = [\n      [x1, y1, 0, 0, u1 - u0],\n      [x2, y2, 0, 0, u2 - u0],\n      [0, 0, x1, y1, v1 - v0],\n      [0, 0, x2, y2, v2 - v0],\n    ];\n    const affineCoefs = solveLinearSystem(augmentedMatrix);\n    if (!affineCoefs) {\n      return;\n    }\n\n    context.save();\n    context.beginPath();\n\n    if (isBrokenDiagonalRendering() || !interpolate) {\n      // Make sure that all lines are horizontal or vertical\n      context.moveTo(u1, v1);\n      // This is the diagonal line. Do it in 4 steps\n      const steps = 4;\n      const ud = u0 - u1;\n      const vd = v0 - v1;\n      for (let step = 0; step < steps; step++) {\n        // Go horizontally\n        context.lineTo(\n          u1 + pixelRound(((step + 1) * ud) / steps),\n          v1 + pixelRound((step * vd) / (steps - 1)),\n        );\n        // Go vertically\n        if (step != steps - 1) {\n          context.lineTo(\n            u1 + pixelRound(((step + 1) * ud) / steps),\n            v1 + pixelRound(((step + 1) * vd) / (steps - 1)),\n          );\n        }\n      }\n      // We are almost at u0r, v0r\n      context.lineTo(u2, v2);\n    } else {\n      context.moveTo(u1, v1);\n      context.lineTo(u0, v0);\n      context.lineTo(u2, v2);\n    }\n\n    context.clip();\n\n    context.transform(\n      affineCoefs[0],\n      affineCoefs[2],\n      affineCoefs[1],\n      affineCoefs[3],\n      u0,\n      v0,\n    );\n\n    context.translate(\n      sourceDataExtent[0] - sourceNumericalShiftX,\n      sourceDataExtent[3] - sourceNumericalShiftY,\n    );\n\n    let image;\n    if (stitchContext) {\n      image = stitchContext.canvas;\n      context.scale(inverseScale, -inverseScale);\n    } else {\n      const source = sources[0];\n      const extent = source.extent;\n      image = source.image;\n      context.scale(\n        getWidth(extent) / image.width,\n        -getHeight(extent) / image.height,\n      );\n    }\n\n    context.drawImage(image, 0, 0);\n    context.restore();\n  });\n\n  if (stitchContext) {\n    releaseCanvas(stitchContext);\n    canvasPool.push(stitchContext.canvas);\n  }\n\n  if (renderEdges) {\n    context.save();\n\n    context.globalCompositeOperation = 'source-over';\n    context.strokeStyle = 'black';\n    context.lineWidth = 1;\n\n    triangulation.getTriangles().forEach(function (triangle, i, arr) {\n      const target = triangle.target;\n      const u0 = (target[0][0] - targetTopLeft[0]) / targetResolution;\n      const v0 = -(target[0][1] - targetTopLeft[1]) / targetResolution;\n      const u1 = (target[1][0] - targetTopLeft[0]) / targetResolution;\n      const v1 = -(target[1][1] - targetTopLeft[1]) / targetResolution;\n      const u2 = (target[2][0] - targetTopLeft[0]) / targetResolution;\n      const v2 = -(target[2][1] - targetTopLeft[1]) / targetResolution;\n\n      context.beginPath();\n      context.moveTo(u1, v1);\n      context.lineTo(u0, v0);\n      context.lineTo(u2, v2);\n      context.closePath();\n      context.stroke();\n    });\n\n    context.restore();\n  }\n  return context.canvas;\n}\n", "/**\n * @module ol/reproj/Triangulation\n */\nimport {\n  boundingExtent,\n  createEmpty,\n  extendCoordinate,\n  getArea,\n  getBottomLeft,\n  getBottomRight,\n  getTopLeft,\n  getTopRight,\n  getWidth,\n  intersects,\n} from '../extent.js';\nimport {modulo} from '../math.js';\nimport {\n  createTransformFromCoordinateTransform,\n  getTransform,\n  transform,\n} from '../proj.js';\nimport {apply as applyMatrix} from '../transform.js';\n\n/**\n * Single triangle; consists of 3 source points and 3 target points.\n * @typedef {Object} Triangle\n * @property {Array<import(\"../coordinate.js\").Coordinate>} source Source.\n * @property {Array<import(\"../coordinate.js\").Coordinate>} target Target.\n */\n\n/**\n * Maximum number of subdivision steps during raster reprojection triangulation.\n * Prevents high memory usage and large number of proj4 calls (for certain\n * transformations and areas). At most `2*(2^this)` triangles are created for\n * each triangulated extent (tile/image).\n * @type {number}\n */\nconst MAX_SUBDIVISION = 10;\n\n/**\n * Maximum allowed size of triangle relative to world width. When transforming\n * corners of world extent between certain projections, the resulting\n * triangulation seems to have zero error and no subdivision is performed. If\n * the triangle width is more than this (relative to world width; 0-1),\n * subdivison is forced (up to `MAX_SUBDIVISION`). Default is `0.25`.\n * @type {number}\n */\nconst MAX_TRIANGLE_WIDTH = 0.25;\n\n/**\n * @classdesc\n * Class containing triangulation of the given target extent.\n * Used for determining source data and the reprojection itself.\n */\nclass Triangulation {\n  /**\n   * @param {import(\"../proj/Projection.js\").default} sourceProj Source projection.\n   * @param {import(\"../proj/Projection.js\").default} targetProj Target projection.\n   * @param {import(\"../extent.js\").Extent} targetExtent Target extent to triangulate.\n   * @param {import(\"../extent.js\").Extent} maxSourceExtent Maximal source extent that can be used.\n   * @param {number} errorThreshold Acceptable error (in source units).\n   * @param {?number} destinationResolution The (optional) resolution of the destination.\n   * @param {import(\"../transform.js\").Transform} [sourceMatrix] Source transform matrix.\n   */\n  constructor(\n    sourceProj,\n    targetProj,\n    targetExtent,\n    maxSourceExtent,\n    errorThreshold,\n    destinationResolution,\n    sourceMatrix,\n  ) {\n    /**\n     * @type {import(\"../proj/Projection.js\").default}\n     * @private\n     */\n    this.sourceProj_ = sourceProj;\n\n    /**\n     * @type {import(\"../proj/Projection.js\").default}\n     * @private\n     */\n    this.targetProj_ = targetProj;\n\n    /** @type {!Object<string, import(\"../coordinate.js\").Coordinate>} */\n    let transformInvCache = {};\n    const transformInv = sourceMatrix\n      ? createTransformFromCoordinateTransform((input) =>\n          applyMatrix(\n            sourceMatrix,\n            transform(input, this.targetProj_, this.sourceProj_),\n          ),\n        )\n      : getTransform(this.targetProj_, this.sourceProj_);\n\n    /**\n     * @param {import(\"../coordinate.js\").Coordinate} c A coordinate.\n     * @return {import(\"../coordinate.js\").Coordinate} Transformed coordinate.\n     * @private\n     */\n    this.transformInv_ = function (c) {\n      const key = c[0] + '/' + c[1];\n      if (!transformInvCache[key]) {\n        transformInvCache[key] = transformInv(c);\n      }\n      return transformInvCache[key];\n    };\n\n    /**\n     * @type {import(\"../extent.js\").Extent}\n     * @private\n     */\n    this.maxSourceExtent_ = maxSourceExtent;\n\n    /**\n     * @type {number}\n     * @private\n     */\n    this.errorThresholdSquared_ = errorThreshold * errorThreshold;\n\n    /**\n     * @type {Array<Triangle>}\n     * @private\n     */\n    this.triangles_ = [];\n\n    /**\n     * Indicates that the triangulation crosses edge of the source projection.\n     * @type {boolean}\n     * @private\n     */\n    this.wrapsXInSource_ = false;\n\n    /**\n     * @type {boolean}\n     * @private\n     */\n    this.canWrapXInSource_ =\n      this.sourceProj_.canWrapX() &&\n      !!maxSourceExtent &&\n      !!this.sourceProj_.getExtent() &&\n      getWidth(maxSourceExtent) >= getWidth(this.sourceProj_.getExtent());\n\n    /**\n     * @type {?number}\n     * @private\n     */\n    this.sourceWorldWidth_ = this.sourceProj_.getExtent()\n      ? getWidth(this.sourceProj_.getExtent())\n      : null;\n\n    /**\n     * @type {?number}\n     * @private\n     */\n    this.targetWorldWidth_ = this.targetProj_.getExtent()\n      ? getWidth(this.targetProj_.getExtent())\n      : null;\n\n    const destinationTopLeft = getTopLeft(targetExtent);\n    const destinationTopRight = getTopRight(targetExtent);\n    const destinationBottomRight = getBottomRight(targetExtent);\n    const destinationBottomLeft = getBottomLeft(targetExtent);\n    const sourceTopLeft = this.transformInv_(destinationTopLeft);\n    const sourceTopRight = this.transformInv_(destinationTopRight);\n    const sourceBottomRight = this.transformInv_(destinationBottomRight);\n    const sourceBottomLeft = this.transformInv_(destinationBottomLeft);\n\n    /*\n     * The maxSubdivision controls how many splittings of the target area can\n     * be done. The idea here is to do a linear mapping of the target areas\n     * but the actual overall reprojection (can be) extremely non-linear. The\n     * default value of MAX_SUBDIVISION was chosen based on mapping a 256x256\n     * tile size. However this function is also called to remap canvas rendered\n     * layers which can be much larger. This calculation increases the maxSubdivision\n     * value by the right factor so that each 256x256 pixel area has\n     * MAX_SUBDIVISION divisions.\n     */\n    const maxSubdivision =\n      MAX_SUBDIVISION +\n      (destinationResolution\n        ? Math.max(\n            0,\n            Math.ceil(\n              Math.log2(\n                getArea(targetExtent) /\n                  (destinationResolution * destinationResolution * 256 * 256),\n              ),\n            ),\n          )\n        : 0);\n\n    this.addQuad_(\n      destinationTopLeft,\n      destinationTopRight,\n      destinationBottomRight,\n      destinationBottomLeft,\n      sourceTopLeft,\n      sourceTopRight,\n      sourceBottomRight,\n      sourceBottomLeft,\n      maxSubdivision,\n    );\n\n    if (this.wrapsXInSource_) {\n      let leftBound = Infinity;\n      this.triangles_.forEach(function (triangle, i, arr) {\n        leftBound = Math.min(\n          leftBound,\n          triangle.source[0][0],\n          triangle.source[1][0],\n          triangle.source[2][0],\n        );\n      });\n\n      // Shift triangles to be as close to `leftBound` as possible\n      // (if the distance is more than `worldWidth / 2` it can be closer.\n      this.triangles_.forEach((triangle) => {\n        if (\n          Math.max(\n            triangle.source[0][0],\n            triangle.source[1][0],\n            triangle.source[2][0],\n          ) -\n            leftBound >\n          this.sourceWorldWidth_ / 2\n        ) {\n          const newTriangle = [\n            [triangle.source[0][0], triangle.source[0][1]],\n            [triangle.source[1][0], triangle.source[1][1]],\n            [triangle.source[2][0], triangle.source[2][1]],\n          ];\n          if (newTriangle[0][0] - leftBound > this.sourceWorldWidth_ / 2) {\n            newTriangle[0][0] -= this.sourceWorldWidth_;\n          }\n          if (newTriangle[1][0] - leftBound > this.sourceWorldWidth_ / 2) {\n            newTriangle[1][0] -= this.sourceWorldWidth_;\n          }\n          if (newTriangle[2][0] - leftBound > this.sourceWorldWidth_ / 2) {\n            newTriangle[2][0] -= this.sourceWorldWidth_;\n          }\n\n          // Rarely (if the extent contains both the dateline and prime meridian)\n          // the shift can in turn break some triangles.\n          // Detect this here and don't shift in such cases.\n          const minX = Math.min(\n            newTriangle[0][0],\n            newTriangle[1][0],\n            newTriangle[2][0],\n          );\n          const maxX = Math.max(\n            newTriangle[0][0],\n            newTriangle[1][0],\n            newTriangle[2][0],\n          );\n          if (maxX - minX < this.sourceWorldWidth_ / 2) {\n            triangle.source = newTriangle;\n          }\n        }\n      });\n    }\n\n    transformInvCache = {};\n  }\n\n  /**\n   * Adds triangle to the triangulation.\n   * @param {import(\"../coordinate.js\").Coordinate} a The target a coordinate.\n   * @param {import(\"../coordinate.js\").Coordinate} b The target b coordinate.\n   * @param {import(\"../coordinate.js\").Coordinate} c The target c coordinate.\n   * @param {import(\"../coordinate.js\").Coordinate} aSrc The source a coordinate.\n   * @param {import(\"../coordinate.js\").Coordinate} bSrc The source b coordinate.\n   * @param {import(\"../coordinate.js\").Coordinate} cSrc The source c coordinate.\n   * @private\n   */\n  addTriangle_(a, b, c, aSrc, bSrc, cSrc) {\n    this.triangles_.push({\n      source: [aSrc, bSrc, cSrc],\n      target: [a, b, c],\n    });\n  }\n\n  /**\n   * Adds quad (points in clock-wise order) to the triangulation\n   * (and reprojects the vertices) if valid.\n   * Performs quad subdivision if needed to increase precision.\n   *\n   * @param {import(\"../coordinate.js\").Coordinate} a The target a coordinate.\n   * @param {import(\"../coordinate.js\").Coordinate} b The target b coordinate.\n   * @param {import(\"../coordinate.js\").Coordinate} c The target c coordinate.\n   * @param {import(\"../coordinate.js\").Coordinate} d The target d coordinate.\n   * @param {import(\"../coordinate.js\").Coordinate} aSrc The source a coordinate.\n   * @param {import(\"../coordinate.js\").Coordinate} bSrc The source b coordinate.\n   * @param {import(\"../coordinate.js\").Coordinate} cSrc The source c coordinate.\n   * @param {import(\"../coordinate.js\").Coordinate} dSrc The source d coordinate.\n   * @param {number} maxSubdivision Maximal allowed subdivision of the quad.\n   * @private\n   */\n  addQuad_(a, b, c, d, aSrc, bSrc, cSrc, dSrc, maxSubdivision) {\n    const sourceQuadExtent = boundingExtent([aSrc, bSrc, cSrc, dSrc]);\n    const sourceCoverageX = this.sourceWorldWidth_\n      ? getWidth(sourceQuadExtent) / this.sourceWorldWidth_\n      : null;\n    const sourceWorldWidth = /** @type {number} */ (this.sourceWorldWidth_);\n\n    // when the quad is wrapped in the source projection\n    // it covers most of the projection extent, but not fully\n    const wrapsX =\n      this.sourceProj_.canWrapX() &&\n      sourceCoverageX > 0.5 &&\n      sourceCoverageX < 1;\n\n    let needsSubdivision = false;\n\n    if (maxSubdivision > 0) {\n      if (this.targetProj_.isGlobal() && this.targetWorldWidth_) {\n        const targetQuadExtent = boundingExtent([a, b, c, d]);\n        const targetCoverageX =\n          getWidth(targetQuadExtent) / this.targetWorldWidth_;\n        needsSubdivision =\n          targetCoverageX > MAX_TRIANGLE_WIDTH || needsSubdivision;\n      }\n      if (!wrapsX && this.sourceProj_.isGlobal() && sourceCoverageX) {\n        needsSubdivision =\n          sourceCoverageX > MAX_TRIANGLE_WIDTH || needsSubdivision;\n      }\n    }\n\n    if (!needsSubdivision && this.maxSourceExtent_) {\n      if (\n        isFinite(sourceQuadExtent[0]) &&\n        isFinite(sourceQuadExtent[1]) &&\n        isFinite(sourceQuadExtent[2]) &&\n        isFinite(sourceQuadExtent[3])\n      ) {\n        if (!intersects(sourceQuadExtent, this.maxSourceExtent_)) {\n          // whole quad outside source projection extent -> ignore\n          return;\n        }\n      }\n    }\n\n    let isNotFinite = 0;\n\n    if (!needsSubdivision) {\n      if (\n        !isFinite(aSrc[0]) ||\n        !isFinite(aSrc[1]) ||\n        !isFinite(bSrc[0]) ||\n        !isFinite(bSrc[1]) ||\n        !isFinite(cSrc[0]) ||\n        !isFinite(cSrc[1]) ||\n        !isFinite(dSrc[0]) ||\n        !isFinite(dSrc[1])\n      ) {\n        if (maxSubdivision > 0) {\n          needsSubdivision = true;\n        } else {\n          // It might be the case that only 1 of the points is infinite. In this case\n          // we can draw a single triangle with the other three points\n          isNotFinite =\n            (!isFinite(aSrc[0]) || !isFinite(aSrc[1]) ? 8 : 0) +\n            (!isFinite(bSrc[0]) || !isFinite(bSrc[1]) ? 4 : 0) +\n            (!isFinite(cSrc[0]) || !isFinite(cSrc[1]) ? 2 : 0) +\n            (!isFinite(dSrc[0]) || !isFinite(dSrc[1]) ? 1 : 0);\n          if (\n            isNotFinite != 1 &&\n            isNotFinite != 2 &&\n            isNotFinite != 4 &&\n            isNotFinite != 8\n          ) {\n            return;\n          }\n        }\n      }\n    }\n\n    if (maxSubdivision > 0) {\n      if (!needsSubdivision) {\n        const center = [(a[0] + c[0]) / 2, (a[1] + c[1]) / 2];\n        const centerSrc = this.transformInv_(center);\n\n        let dx;\n        if (wrapsX) {\n          const centerSrcEstimX =\n            (modulo(aSrc[0], sourceWorldWidth) +\n              modulo(cSrc[0], sourceWorldWidth)) /\n            2;\n          dx = centerSrcEstimX - modulo(centerSrc[0], sourceWorldWidth);\n        } else {\n          dx = (aSrc[0] + cSrc[0]) / 2 - centerSrc[0];\n        }\n        const dy = (aSrc[1] + cSrc[1]) / 2 - centerSrc[1];\n        const centerSrcErrorSquared = dx * dx + dy * dy;\n        needsSubdivision = centerSrcErrorSquared > this.errorThresholdSquared_;\n      }\n      if (needsSubdivision) {\n        if (Math.abs(a[0] - c[0]) <= Math.abs(a[1] - c[1])) {\n          // split horizontally (top & bottom)\n          const bc = [(b[0] + c[0]) / 2, (b[1] + c[1]) / 2];\n          const bcSrc = this.transformInv_(bc);\n          const da = [(d[0] + a[0]) / 2, (d[1] + a[1]) / 2];\n          const daSrc = this.transformInv_(da);\n\n          this.addQuad_(\n            a,\n            b,\n            bc,\n            da,\n            aSrc,\n            bSrc,\n            bcSrc,\n            daSrc,\n            maxSubdivision - 1,\n          );\n          this.addQuad_(\n            da,\n            bc,\n            c,\n            d,\n            daSrc,\n            bcSrc,\n            cSrc,\n            dSrc,\n            maxSubdivision - 1,\n          );\n        } else {\n          // split vertically (left & right)\n          const ab = [(a[0] + b[0]) / 2, (a[1] + b[1]) / 2];\n          const abSrc = this.transformInv_(ab);\n          const cd = [(c[0] + d[0]) / 2, (c[1] + d[1]) / 2];\n          const cdSrc = this.transformInv_(cd);\n\n          this.addQuad_(\n            a,\n            ab,\n            cd,\n            d,\n            aSrc,\n            abSrc,\n            cdSrc,\n            dSrc,\n            maxSubdivision - 1,\n          );\n          this.addQuad_(\n            ab,\n            b,\n            c,\n            cd,\n            abSrc,\n            bSrc,\n            cSrc,\n            cdSrc,\n            maxSubdivision - 1,\n          );\n        }\n        return;\n      }\n    }\n\n    if (wrapsX) {\n      if (!this.canWrapXInSource_) {\n        return;\n      }\n      this.wrapsXInSource_ = true;\n    }\n\n    // Exactly zero or one of *Src is not finite\n    // The triangles must have the diagonal line as the first side\n    // This is to allow easy code in reproj.s to make it straight for broken\n    // browsers that can't handle diagonal clipping\n    if ((isNotFinite & 0xb) == 0) {\n      this.addTriangle_(a, c, d, aSrc, cSrc, dSrc);\n    }\n    if ((isNotFinite & 0xe) == 0) {\n      this.addTriangle_(a, c, b, aSrc, cSrc, bSrc);\n    }\n    if (isNotFinite) {\n      // Try the other two triangles\n      if ((isNotFinite & 0xd) == 0) {\n        this.addTriangle_(b, d, a, bSrc, dSrc, aSrc);\n      }\n      if ((isNotFinite & 0x7) == 0) {\n        this.addTriangle_(b, d, c, bSrc, dSrc, cSrc);\n      }\n    }\n  }\n\n  /**\n   * Calculates extent of the `source` coordinates from all the triangles.\n   *\n   * @return {import(\"../extent.js\").Extent} Calculated extent.\n   */\n  calculateSourceExtent() {\n    const extent = createEmpty();\n\n    this.triangles_.forEach(function (triangle, i, arr) {\n      const src = triangle.source;\n      extendCoordinate(extent, src[0]);\n      extendCoordinate(extent, src[1]);\n      extendCoordinate(extent, src[2]);\n    });\n\n    return extent;\n  }\n\n  /**\n   * @return {Array<Triangle>} Array of the calculated triangles.\n   */\n  getTriangles() {\n    return this.triangles_;\n  }\n}\n\nexport default Triangulation;\n", "/**\n * @module ol/reproj/Tile\n */\n\nimport Tile from '../Tile.js';\nimport TileState from '../TileState.js';\nimport {releaseCanvas} from '../dom.js';\nimport {listen, unlistenByKey} from '../events.js';\nimport EventType from '../events/EventType.js';\nimport {getArea, getIntersection, getWidth, wrapAndSliceX} from '../extent.js';\nimport {clamp} from '../math.js';\nimport {\n  calculateSourceExtentResolution,\n  canvasPool,\n  render as renderReprojected,\n} from '../reproj.js';\nimport Triangulation from './Triangulation.js';\nimport {ERROR_THRESHOLD} from './common.js';\n\n/**\n * @typedef {function(number, number, number, number) : (import(\"../ImageTile.js\").default)} FunctionType\n */\n\n/**\n * @typedef {Object} TileOffset\n * @property {import(\"../ImageTile.js\").default} [tile] Tile.\n * @property {function(): import(\"../ImageTile.js\").default} getTile Tile getter.\n * @property {number} offset Offset.\n */\n\n/**\n * @classdesc\n * Class encapsulating single reprojected tile.\n * See {@link module:ol/source/TileImage~TileImage}.\n *\n */\nclass ReprojTile extends Tile {\n  /**\n   * @param {import(\"../proj/Projection.js\").default} sourceProj Source projection.\n   * @param {import(\"../tilegrid/TileGrid.js\").default} sourceTileGrid Source tile grid.\n   * @param {import(\"../proj/Projection.js\").default} targetProj Target projection.\n   * @param {import(\"../tilegrid/TileGrid.js\").default} targetTileGrid Target tile grid.\n   * @param {import(\"../tilecoord.js\").TileCoord} tileCoord Coordinate of the tile.\n   * @param {import(\"../tilecoord.js\").TileCoord} wrappedTileCoord Coordinate of the tile wrapped in X.\n   * @param {number} pixelRatio Pixel ratio.\n   * @param {number} gutter Gutter of the source tiles.\n   * @param {FunctionType} getTileFunction\n   *     Function returning source tiles (z, x, y, pixelRatio).\n   * @param {number} [errorThreshold] Acceptable reprojection error (in px).\n   * @param {boolean} [renderEdges] Render reprojection edges.\n   * @param {import(\"../Tile.js\").Options} [options] Tile options.\n   */\n  constructor(\n    sourceProj,\n    sourceTileGrid,\n    targetProj,\n    targetTileGrid,\n    tileCoord,\n    wrappedTileCoord,\n    pixelRatio,\n    gutter,\n    getTileFunction,\n    errorThreshold,\n    renderEdges,\n    options,\n  ) {\n    super(tileCoord, TileState.IDLE, options);\n\n    /**\n     * @private\n     * @type {boolean}\n     */\n    this.renderEdges_ = renderEdges !== undefined ? renderEdges : false;\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.pixelRatio_ = pixelRatio;\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.gutter_ = gutter;\n\n    /**\n     * @private\n     * @type {HTMLCanvasElement|OffscreenCanvas}\n     */\n    this.canvas_ = null;\n\n    /**\n     * @private\n     * @type {import(\"../tilegrid/TileGrid.js\").default}\n     */\n    this.sourceTileGrid_ = sourceTileGrid;\n\n    /**\n     * @private\n     * @type {import(\"../tilegrid/TileGrid.js\").default}\n     */\n    this.targetTileGrid_ = targetTileGrid;\n\n    /**\n     * @private\n     * @type {import(\"../tilecoord.js\").TileCoord}\n     */\n    this.wrappedTileCoord_ = wrappedTileCoord ? wrappedTileCoord : tileCoord;\n\n    /**\n     * @private\n     * @type {!Array<TileOffset>}\n     */\n    this.sourceTiles_ = [];\n\n    /**\n     * @private\n     * @type {?Array<import(\"../events.js\").EventsKey>}\n     */\n    this.sourcesListenerKeys_ = null;\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.sourceZ_ = 0;\n\n    /**\n     * @private\n     * @type {import(\"../extent.js\").Extent}\n     */\n    this.clipExtent_ = sourceProj.canWrapX()\n      ? sourceProj.getExtent()\n      : undefined;\n\n    const targetExtent = targetTileGrid.getTileCoordExtent(\n      this.wrappedTileCoord_,\n    );\n    const maxTargetExtent = this.targetTileGrid_.getExtent();\n    let maxSourceExtent = this.sourceTileGrid_.getExtent();\n\n    const limitedTargetExtent = maxTargetExtent\n      ? getIntersection(targetExtent, maxTargetExtent)\n      : targetExtent;\n\n    if (getArea(limitedTargetExtent) === 0) {\n      // Tile is completely outside range -> EMPTY\n      // TODO: is it actually correct that the source even creates the tile ?\n      this.state = TileState.EMPTY;\n      return;\n    }\n\n    const sourceProjExtent = sourceProj.getExtent();\n    if (sourceProjExtent) {\n      if (!maxSourceExtent) {\n        maxSourceExtent = sourceProjExtent;\n      } else {\n        maxSourceExtent = getIntersection(maxSourceExtent, sourceProjExtent);\n      }\n    }\n\n    const targetResolution = targetTileGrid.getResolution(\n      this.wrappedTileCoord_[0],\n    );\n\n    const sourceResolution = calculateSourceExtentResolution(\n      sourceProj,\n      targetProj,\n      limitedTargetExtent,\n      targetResolution,\n    );\n\n    if (!isFinite(sourceResolution) || sourceResolution <= 0) {\n      // invalid sourceResolution -> EMPTY\n      // probably edges of the projections when no extent is defined\n      this.state = TileState.EMPTY;\n      return;\n    }\n\n    const errorThresholdInPixels =\n      errorThreshold !== undefined ? errorThreshold : ERROR_THRESHOLD;\n\n    /**\n     * @private\n     * @type {!import(\"./Triangulation.js\").default}\n     */\n    this.triangulation_ = new Triangulation(\n      sourceProj,\n      targetProj,\n      limitedTargetExtent,\n      maxSourceExtent,\n      sourceResolution * errorThresholdInPixels,\n      targetResolution,\n    );\n\n    if (this.triangulation_.getTriangles().length === 0) {\n      // no valid triangles -> EMPTY\n      this.state = TileState.EMPTY;\n      return;\n    }\n\n    this.sourceZ_ = sourceTileGrid.getZForResolution(sourceResolution);\n    let sourceExtent = this.triangulation_.calculateSourceExtent();\n\n    if (maxSourceExtent) {\n      if (sourceProj.canWrapX()) {\n        sourceExtent[1] = clamp(\n          sourceExtent[1],\n          maxSourceExtent[1],\n          maxSourceExtent[3],\n        );\n        sourceExtent[3] = clamp(\n          sourceExtent[3],\n          maxSourceExtent[1],\n          maxSourceExtent[3],\n        );\n      } else {\n        sourceExtent = getIntersection(sourceExtent, maxSourceExtent);\n      }\n    }\n\n    if (!getArea(sourceExtent)) {\n      this.state = TileState.EMPTY;\n    } else {\n      let worldWidth = 0;\n      let worldsAway = 0;\n      if (sourceProj.canWrapX()) {\n        worldWidth = getWidth(sourceProjExtent);\n        worldsAway = Math.floor(\n          (sourceExtent[0] - sourceProjExtent[0]) / worldWidth,\n        );\n      }\n\n      const sourceExtents = wrapAndSliceX(\n        sourceExtent.slice(),\n        sourceProj,\n        true,\n      );\n      sourceExtents.forEach((extent) => {\n        const sourceRange = sourceTileGrid.getTileRangeForExtentAndZ(\n          extent,\n          this.sourceZ_,\n        );\n\n        for (let srcX = sourceRange.minX; srcX <= sourceRange.maxX; srcX++) {\n          for (let srcY = sourceRange.minY; srcY <= sourceRange.maxY; srcY++) {\n            const offset = worldsAway * worldWidth;\n            this.sourceTiles_.push({\n              getTile: () =>\n                getTileFunction(this.sourceZ_, srcX, srcY, pixelRatio),\n              offset,\n            });\n          }\n        }\n        ++worldsAway;\n      });\n\n      if (this.sourceTiles_.length === 0) {\n        this.state = TileState.EMPTY;\n      }\n    }\n  }\n\n  /**\n   * Get the HTML Canvas element for this tile.\n   * @return {HTMLCanvasElement|OffscreenCanvas} Canvas.\n   */\n  getImage() {\n    return this.canvas_;\n  }\n\n  /**\n   * @private\n   */\n  reproject_() {\n    const sources = [];\n    this.sourceTiles_.forEach((source) => {\n      const tile = source.tile;\n      if (tile && tile.getState() == TileState.LOADED) {\n        const extent = this.sourceTileGrid_.getTileCoordExtent(tile.tileCoord);\n        extent[0] += source.offset;\n        extent[2] += source.offset;\n        const clipExtent = this.clipExtent_?.slice();\n        if (clipExtent) {\n          clipExtent[0] += source.offset;\n          clipExtent[2] += source.offset;\n        }\n        sources.push({\n          extent: extent,\n          clipExtent: clipExtent,\n          image: tile.getImage(),\n        });\n      }\n    });\n    this.sourceTiles_.length = 0;\n\n    if (sources.length === 0) {\n      this.state = TileState.ERROR;\n    } else {\n      const z = this.wrappedTileCoord_[0];\n      const size = this.targetTileGrid_.getTileSize(z);\n      const width = typeof size === 'number' ? size : size[0];\n      const height = typeof size === 'number' ? size : size[1];\n      const targetResolution = this.targetTileGrid_.getResolution(z);\n      const sourceResolution = this.sourceTileGrid_.getResolution(\n        this.sourceZ_,\n      );\n\n      const targetExtent = this.targetTileGrid_.getTileCoordExtent(\n        this.wrappedTileCoord_,\n      );\n\n      this.canvas_ = renderReprojected(\n        width,\n        height,\n        this.pixelRatio_,\n        sourceResolution,\n        this.sourceTileGrid_.getExtent(),\n        targetResolution,\n        targetExtent,\n        this.triangulation_,\n        sources,\n        this.gutter_,\n        this.renderEdges_,\n        this.interpolate,\n      );\n\n      this.state = TileState.LOADED;\n    }\n    this.changed();\n  }\n\n  /**\n   * Load not yet loaded URI.\n   * @override\n   */\n  load() {\n    for (const sourceTile of this.sourceTiles_) {\n      sourceTile.tile = sourceTile.getTile();\n    }\n    if (this.state == TileState.IDLE) {\n      this.state = TileState.LOADING;\n      this.changed();\n\n      let leftToLoad = 0;\n\n      this.sourcesListenerKeys_ = [];\n      this.sourceTiles_.forEach(({tile}) => {\n        const state = tile.getState();\n        if (state == TileState.IDLE || state == TileState.LOADING) {\n          leftToLoad++;\n\n          const sourceListenKey = listen(tile, EventType.CHANGE, (e) => {\n            const state = tile.getState();\n            if (\n              state == TileState.LOADED ||\n              state == TileState.ERROR ||\n              state == TileState.EMPTY\n            ) {\n              unlistenByKey(sourceListenKey);\n              leftToLoad--;\n              if (leftToLoad === 0) {\n                this.unlistenSources_();\n                this.reproject_();\n              }\n            }\n          });\n          this.sourcesListenerKeys_.push(sourceListenKey);\n        }\n      });\n\n      if (leftToLoad === 0) {\n        setTimeout(this.reproject_.bind(this), 0);\n      } else {\n        this.sourceTiles_.forEach(function ({tile}, i, arr) {\n          const state = tile.getState();\n          if (state == TileState.IDLE) {\n            tile.load();\n          }\n        });\n      }\n    }\n  }\n\n  /**\n   * @private\n   */\n  unlistenSources_() {\n    this.sourcesListenerKeys_.forEach(unlistenByKey);\n    this.sourcesListenerKeys_ = null;\n  }\n\n  /**\n   * Remove from the cache due to expiry\n   * @override\n   */\n  release() {\n    if (this.canvas_) {\n      releaseCanvas(\n        /** @type {CanvasRenderingContext2D|OffscreenCanvasRenderingContext2D} */ (\n          this.canvas_.getContext('2d')\n        ),\n      );\n      canvasPool.push(this.canvas_);\n      this.canvas_ = null;\n    }\n    this.sourceTiles_.length = 0;\n    super.release();\n  }\n}\n\nexport default ReprojTile;\n", "/**\n * @module ol/structs/LRUCache\n */\n\nimport Disposable from '../Disposable.js';\nimport {assert} from '../asserts.js';\n\n/**\n * @typedef {Object} Entry\n * @property {string} key_ Key.\n * @property {Entry|null} newer Newer.\n * @property {Entry|null} older Older.\n * @property {*} value_ Value.\n */\n\n/**\n * @classdesc\n * Implements a Least-Recently-Used cache where the keys do not conflict with\n * Object's properties (e.g. 'hasOwnProperty' is not allowed as a key). Expiring\n * items from the cache is the responsibility of the user.\n *\n * @fires import(\"../events/Event.js\").default\n * @template T\n */\nclass LRUCache {\n  /**\n   * @param {number} [highWaterMark] High water mark.\n   */\n  constructor(highWaterMark) {\n    /**\n     * Desired max cache size after expireCache(). If set to 0, no cache entries\n     * will be pruned at all.\n     * @type {number}\n     */\n    this.highWaterMark = highWaterMark !== undefined ? highWaterMark : 2048;\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.count_ = 0;\n\n    /**\n     * @private\n     * @type {!Object<string, Entry>}\n     */\n    this.entries_ = {};\n\n    /**\n     * @private\n     * @type {?Entry}\n     */\n    this.oldest_ = null;\n\n    /**\n     * @private\n     * @type {?Entry}\n     */\n    this.newest_ = null;\n  }\n\n  deleteOldest() {\n    const entry = this.pop();\n    if (entry instanceof Disposable) {\n      entry.dispose();\n    }\n  }\n\n  /**\n   * @return {boolean} Can expire cache.\n   */\n  canExpireCache() {\n    return this.highWaterMark > 0 && this.getCount() > this.highWaterMark;\n  }\n\n  /**\n   * Expire the cache. When the cache entry is a {@link module:ol/Disposable~Disposable},\n   * the entry will be disposed.\n   * @param {!Object<string, boolean>} [keep] Keys to keep. To be implemented by subclasses.\n   */\n  expireCache(keep) {\n    while (this.canExpireCache()) {\n      this.deleteOldest();\n    }\n  }\n\n  /**\n   * FIXME empty description for jsdoc\n   */\n  clear() {\n    while (this.oldest_) {\n      this.deleteOldest();\n    }\n  }\n\n  /**\n   * @param {string} key Key.\n   * @return {boolean} Contains key.\n   */\n  containsKey(key) {\n    return this.entries_.hasOwnProperty(key);\n  }\n\n  /**\n   * @param {function(T, string, LRUCache<T>): ?} f The function\n   *     to call for every entry from the oldest to the newer. This function takes\n   *     3 arguments (the entry value, the entry key and the LRUCache object).\n   *     The return value is ignored.\n   */\n  forEach(f) {\n    let entry = this.oldest_;\n    while (entry) {\n      f(entry.value_, entry.key_, this);\n      entry = entry.newer;\n    }\n  }\n\n  /**\n   * @param {string} key Key.\n   * @param {*} [options] Options (reserved for subclasses).\n   * @return {T} Value.\n   */\n  get(key, options) {\n    const entry = this.entries_[key];\n    assert(\n      entry !== undefined,\n      'Tried to get a value for a key that does not exist in the cache',\n    );\n    if (entry === this.newest_) {\n      return entry.value_;\n    }\n    if (entry === this.oldest_) {\n      this.oldest_ = /** @type {Entry} */ (this.oldest_.newer);\n      this.oldest_.older = null;\n    } else {\n      entry.newer.older = entry.older;\n      entry.older.newer = entry.newer;\n    }\n    entry.newer = null;\n    entry.older = this.newest_;\n    this.newest_.newer = entry;\n    this.newest_ = entry;\n    return entry.value_;\n  }\n\n  /**\n   * Remove an entry from the cache.\n   * @param {string} key The entry key.\n   * @return {T} The removed entry.\n   */\n  remove(key) {\n    const entry = this.entries_[key];\n    assert(\n      entry !== undefined,\n      'Tried to get a value for a key that does not exist in the cache',\n    );\n    if (entry === this.newest_) {\n      this.newest_ = /** @type {Entry} */ (entry.older);\n      if (this.newest_) {\n        this.newest_.newer = null;\n      }\n    } else if (entry === this.oldest_) {\n      this.oldest_ = /** @type {Entry} */ (entry.newer);\n      if (this.oldest_) {\n        this.oldest_.older = null;\n      }\n    } else {\n      entry.newer.older = entry.older;\n      entry.older.newer = entry.newer;\n    }\n    delete this.entries_[key];\n    --this.count_;\n    return entry.value_;\n  }\n\n  /**\n   * @return {number} Count.\n   */\n  getCount() {\n    return this.count_;\n  }\n\n  /**\n   * @return {Array<string>} Keys.\n   */\n  getKeys() {\n    const keys = new Array(this.count_);\n    let i = 0;\n    let entry;\n    for (entry = this.newest_; entry; entry = entry.older) {\n      keys[i++] = entry.key_;\n    }\n    return keys;\n  }\n\n  /**\n   * @return {Array<T>} Values.\n   */\n  getValues() {\n    const values = new Array(this.count_);\n    let i = 0;\n    let entry;\n    for (entry = this.newest_; entry; entry = entry.older) {\n      values[i++] = entry.value_;\n    }\n    return values;\n  }\n\n  /**\n   * @return {T} Last value.\n   */\n  peekLast() {\n    return this.oldest_.value_;\n  }\n\n  /**\n   * @return {string} Last key.\n   */\n  peekLastKey() {\n    return this.oldest_.key_;\n  }\n\n  /**\n   * Get the key of the newest item in the cache.  Throws if the cache is empty.\n   * @return {string} The newest key.\n   */\n  peekFirstKey() {\n    return this.newest_.key_;\n  }\n\n  /**\n   * Return an entry without updating least recently used time.\n   * @param {string} key Key.\n   * @return {T|undefined} Value.\n   */\n  peek(key) {\n    return this.entries_[key]?.value_;\n  }\n\n  /**\n   * @return {T} value Value.\n   */\n  pop() {\n    const entry = this.oldest_;\n    delete this.entries_[entry.key_];\n    if (entry.newer) {\n      entry.newer.older = null;\n    }\n    this.oldest_ = /** @type {Entry} */ (entry.newer);\n    if (!this.oldest_) {\n      this.newest_ = null;\n    }\n    --this.count_;\n    return entry.value_;\n  }\n\n  /**\n   * @param {string} key Key.\n   * @param {T} value Value.\n   */\n  replace(key, value) {\n    this.get(key); // update `newest_`\n    this.entries_[key].value_ = value;\n  }\n\n  /**\n   * @param {string} key Key.\n   * @param {T} value Value.\n   */\n  set(key, value) {\n    assert(\n      !(key in this.entries_),\n      'Tried to set a value for a key that is used already',\n    );\n    const entry = {\n      key_: key,\n      newer: null,\n      older: this.newest_,\n      value_: value,\n    };\n    if (!this.newest_) {\n      this.oldest_ = entry;\n    } else {\n      this.newest_.newer = entry;\n    }\n    this.newest_ = entry;\n    this.entries_[key] = entry;\n    ++this.count_;\n  }\n\n  /**\n   * Set a maximum number of entries for the cache.\n   * @param {number} size Cache size.\n   * @api\n   */\n  setSize(size) {\n    this.highWaterMark = size;\n  }\n}\n\nexport default LRUCache;\n", "/**\n * @module ol/tilecoord\n */\n\nimport {getUid} from './util.js';\n\n/**\n * An array of three numbers representing the location of a tile in a tile\n * grid. The order is `z` (zoom level), `x` (column), and `y` (row).\n * @typedef {Array<number>} TileCoord\n * @api\n */\n\n/**\n * @param {number} z Z.\n * @param {number} x X.\n * @param {number} y Y.\n * @param {TileCoord} [tileCoord] Tile coordinate.\n * @return {TileCoord} Tile coordinate.\n */\nexport function createOrUpdate(z, x, y, tileCoord) {\n  if (tileCoord !== undefined) {\n    tileCoord[0] = z;\n    tileCoord[1] = x;\n    tileCoord[2] = y;\n    return tileCoord;\n  }\n  return [z, x, y];\n}\n\n/**\n * @param {number} z Z.\n * @param {number} x X.\n * @param {number} y Y.\n * @return {string} Key.\n */\nexport function getKeyZXY(z, x, y) {\n  return z + '/' + x + '/' + y;\n}\n\n/**\n * Get the key for a tile coord.\n * @param {TileCoord} tileCoord The tile coord.\n * @return {string} Key.\n */\nexport function getKey(tileCoord) {\n  return getKeyZXY(tileCoord[0], tileCoord[1], tileCoord[2]);\n}\n\n/**\n * Get the tile cache key for a tile key obtained through `tile.getKey()`.\n * @param {string} tileKey The tile key.\n * @return {string} The cache key.\n */\nexport function getCacheKeyForTileKey(tileKey) {\n  const [z, x, y] = tileKey\n    .substring(tileKey.lastIndexOf('/') + 1, tileKey.length)\n    .split(',')\n    .map(Number);\n  return getKeyZXY(z, x, y);\n}\n\n/**\n * @param {import(\"./source/Tile.js\").default} source The tile source.\n * @param {string} sourceKey The source key.\n * @param {number} z The tile z level.\n * @param {number} x The tile x level.\n * @param {number} y The tile y level.\n * @return {string} The cache key.\n */\nexport function getCacheKey(source, sourceKey, z, x, y) {\n  return `${getUid(source)},${sourceKey},${getKeyZXY(z, x, y)}`;\n}\n\n/**\n * Get a tile coord given a key.\n * @param {string} key The tile coord key.\n * @return {TileCoord} The tile coord.\n */\nexport function fromKey(key) {\n  return key.split('/').map(Number);\n}\n\n/**\n * @param {TileCoord} tileCoord Tile coord.\n * @return {number} Hash.\n */\nexport function hash(tileCoord) {\n  return hashZXY(tileCoord[0], tileCoord[1], tileCoord[2]);\n}\n\n/**\n * @param {number} z The tile z coordinate.\n * @param {number} x The tile x coordinate.\n * @param {number} y The tile y coordinate.\n * @return {number} Hash.\n */\nexport function hashZXY(z, x, y) {\n  return (x << z) + y;\n}\n\n/**\n * @param {TileCoord} tileCoord Tile coordinate.\n * @param {!import(\"./tilegrid/TileGrid.js\").default} tileGrid Tile grid.\n * @return {boolean} Tile coordinate is within extent and zoom level range.\n */\nexport function withinExtentAndZ(tileCoord, tileGrid) {\n  const z = tileCoord[0];\n  const x = tileCoord[1];\n  const y = tileCoord[2];\n\n  if (tileGrid.getMinZoom() > z || z > tileGrid.getMaxZoom()) {\n    return false;\n  }\n  const tileRange = tileGrid.getFullTileRange(z);\n  if (!tileRange) {\n    return true;\n  }\n  return tileRange.containsXY(x, y);\n}\n", "/**\n * @module ol/render/canvas/ZIndexContext\n */\n\nimport {getSharedCanvasContext2D} from '../../dom.js';\n\n/** @typedef {CanvasRenderingContext2D|OffscreenCanvasRenderingContext2D & {globalAlpha: any}} ZIndexContextProxy */\n\n/**\n * @extends {CanvasRenderingContext2D}\n */\nclass ZIndexContext {\n  constructor() {\n    /**\n     * @private\n     * @type {Array<Array<*>>}\n     */\n    this.instructions_ = [];\n    /**\n     * @type {number}\n     */\n    this.zIndex = 0;\n    /**\n     * @private\n     * @type {number}\n     */\n    this.offset_ = 0;\n\n    /**\n     * @private\n     * @type {ZIndexContextProxy}\n     */\n    this.context_ = /** @type {ZIndexContextProxy} */ (\n      new Proxy(getSharedCanvasContext2D(), {\n        get: (target, property) => {\n          if (\n            typeof (/** @type {*} */ (getSharedCanvasContext2D())[property]) !==\n            'function'\n          ) {\n            // we only accept calling functions on the proxy, not accessing properties\n            return undefined;\n          }\n          this.push_(property);\n          return this.pushMethodArgs_;\n        },\n        set: (target, property, value) => {\n          this.push_(property, value);\n          return true;\n        },\n      })\n    );\n  }\n\n  /**\n   * @param {...*} args Arguments to push to the instructions array.\n   * @private\n   */\n  push_(...args) {\n    const instructions = this.instructions_;\n    const index = this.zIndex + this.offset_;\n    if (!instructions[index]) {\n      instructions[index] = [];\n    }\n    instructions[index].push(...args);\n  }\n\n  /**\n   * @private\n   * @param {...*} args Args.\n   * @return {ZIndexContext} This.\n   */\n  pushMethodArgs_ = (...args) => {\n    this.push_(args);\n    return this;\n  };\n\n  /**\n   * Push a function that renders to the context directly.\n   * @param {function(CanvasRenderingContext2D): void} render Function.\n   */\n  pushFunction(render) {\n    this.push_(render);\n  }\n\n  /**\n   * Get a proxy for CanvasRenderingContext2D which does not support getting state\n   * (e.g. `context.globalAlpha`, which will return `undefined`). To set state, if it relies on a\n   * previous state (e.g. `context.globalAlpha = context.globalAlpha / 2`), set a function,\n   * e.g. `context.globalAlpha = (context) => context.globalAlpha / 2`.\n   * @return {ZIndexContextProxy} Context.\n   */\n  getContext() {\n    return this.context_;\n  }\n\n  /**\n   * @param {CanvasRenderingContext2D|OffscreenCanvasRenderingContext2D} context Context.\n   */\n  draw(context) {\n    this.instructions_.forEach((instructionsAtIndex) => {\n      for (let i = 0, ii = instructionsAtIndex.length; i < ii; ++i) {\n        const property = instructionsAtIndex[i];\n        if (typeof property === 'function') {\n          property(context);\n          continue;\n        }\n        const instructionAtIndex = instructionsAtIndex[++i];\n        if (typeof (/** @type {*} */ (context)[property]) === 'function') {\n          /** @type {*} */ (context)[property](...instructionAtIndex);\n        } else {\n          if (typeof instructionAtIndex === 'function') {\n            /** @type {*} */ (context)[property] = instructionAtIndex(context);\n            continue;\n          }\n          /** @type {*} */ (context)[property] = instructionAtIndex;\n        }\n      }\n    });\n  }\n\n  clear() {\n    this.instructions_.length = 0;\n    this.zIndex = 0;\n    this.offset_ = 0;\n  }\n\n  /**\n   * Offsets the zIndex by the highest current zIndex. Useful for rendering multiple worlds or tiles, to\n   * avoid conflicting context.clip() or context.save()/restore() calls.\n   */\n  offset() {\n    this.offset_ = this.instructions_.length;\n    this.zIndex = 0;\n  }\n}\n\nexport default ZIndexContext;\n", "/**\n * @module ol/renderer/Layer\n */\nimport ImageState from '../ImageState.js';\nimport Observable from '../Observable.js';\nimport EventType from '../events/EventType.js';\nimport {abstract} from '../util.js';\n\nconst maxStaleKeys = 5;\n\n/**\n * @template {import(\"../layer/Layer.js\").default} LayerType\n */\nclass LayerRenderer extends Observable {\n  /**\n   * @param {LayerType} layer Layer.\n   */\n  constructor(layer) {\n    super();\n\n    /**\n     * The renderer is initialized and ready to render.\n     * @type {boolean}\n     */\n    this.ready = true;\n\n    /** @private */\n    this.boundHandleImageChange_ = this.handleImageChange_.bind(this);\n\n    /**\n     * @private\n     * @type {LayerType}\n     */\n    this.layer_ = layer;\n\n    /**\n     * @type {Array<string>}\n     * @private\n     */\n    this.staleKeys_ = new Array();\n\n    /**\n     * @type {number}\n     * @protected\n     */\n    this.maxStaleKeys = maxStaleKeys;\n  }\n\n  /**\n   * @return {Array<string>} Get the list of stale keys.\n   */\n  getStaleKeys() {\n    return this.staleKeys_;\n  }\n\n  /**\n   * @param {string} key The new stale key.\n   */\n  prependStaleKey(key) {\n    this.staleKeys_.unshift(key);\n    if (this.staleKeys_.length > this.maxStaleKeys) {\n      this.staleKeys_.length = this.maxStaleKeys;\n    }\n  }\n\n  /**\n   * Asynchronous layer level hit detection.\n   * @param {import(\"../pixel.js\").Pixel} pixel Pixel.\n   * @return {Promise<Array<import(\"../Feature.js\").FeatureLike>>} Promise that resolves with\n   * an array of features.\n   */\n  getFeatures(pixel) {\n    return abstract();\n  }\n\n  /**\n   * @param {import(\"../pixel.js\").Pixel} pixel Pixel.\n   * @return {Uint8ClampedArray|Uint8Array|Float32Array|DataView|null} Pixel data.\n   */\n  getData(pixel) {\n    return null;\n  }\n\n  /**\n   * Determine whether render should be called.\n   * @abstract\n   * @param {import(\"../Map.js\").FrameState} frameState Frame state.\n   * @return {boolean} Layer is ready to be rendered.\n   */\n  prepareFrame(frameState) {\n    return abstract();\n  }\n\n  /**\n   * Render the layer.\n   * @abstract\n   * @param {import(\"../Map.js\").FrameState} frameState Frame state.\n   * @param {HTMLElement|null} target Target that may be used to render content to.\n   * @return {HTMLElement} The rendered element.\n   */\n  renderFrame(frameState, target) {\n    return abstract();\n  }\n\n  /**\n   * @abstract\n   * @param {import(\"../coordinate.js\").Coordinate} coordinate Coordinate.\n   * @param {import(\"../Map.js\").FrameState} frameState Frame state.\n   * @param {number} hitTolerance Hit tolerance in pixels.\n   * @param {import(\"./vector.js\").FeatureCallback<T>} callback Feature callback.\n   * @param {Array<import(\"./Map.js\").HitMatch<T>>} matches The hit detected matches with tolerance.\n   * @return {T|undefined} Callback result.\n   * @template T\n   */\n  forEachFeatureAtCoordinate(\n    coordinate,\n    frameState,\n    hitTolerance,\n    callback,\n    matches,\n  ) {\n    return undefined;\n  }\n\n  /**\n   * @return {LayerType} Layer.\n   */\n  getLayer() {\n    return this.layer_;\n  }\n\n  /**\n   * Perform action necessary to get the layer rendered after new fonts have loaded\n   * @abstract\n   */\n  handleFontsChanged() {}\n\n  /**\n   * Handle changes in image state.\n   * @param {import(\"../events/Event.js\").default} event Image change event.\n   * @private\n   */\n  handleImageChange_(event) {\n    const image = /** @type {import(\"../Image.js\").default} */ (event.target);\n    if (\n      image.getState() === ImageState.LOADED ||\n      image.getState() === ImageState.ERROR\n    ) {\n      this.renderIfReadyAndVisible();\n    }\n  }\n\n  /**\n   * Load the image if not already loaded, and register the image change\n   * listener if needed.\n   * @param {import(\"../Image.js\").default} image Image.\n   * @return {boolean} `true` if the image is already loaded, `false` otherwise.\n   * @protected\n   */\n  loadImage(image) {\n    let imageState = image.getState();\n    if (imageState != ImageState.LOADED && imageState != ImageState.ERROR) {\n      image.addEventListener(EventType.CHANGE, this.boundHandleImageChange_);\n    }\n    if (imageState == ImageState.IDLE) {\n      image.load();\n      imageState = image.getState();\n    }\n    return imageState == ImageState.LOADED;\n  }\n\n  /**\n   * @protected\n   */\n  renderIfReadyAndVisible() {\n    const layer = this.getLayer();\n    if (layer && layer.getVisible() && layer.getSourceState() === 'ready') {\n      layer.changed();\n    }\n  }\n\n  /**\n   * @param {import(\"../Map.js\").FrameState} frameState Frame state.\n   */\n  renderDeferred(frameState) {}\n\n  /**\n   * Clean up.\n   * @override\n   */\n  disposeInternal() {\n    delete this.layer_;\n    super.disposeInternal();\n  }\n}\n\nexport default LayerRenderer;\n", "/**\n * @module ol/renderer/canvas/Layer\n */\nimport {equals} from '../../array.js';\nimport {asArray} from '../../color.js';\nimport {createCanvasContext2D, createMockDiv, isCanvas} from '../../dom.js';\nimport {\n  getBottomLeft,\n  getBottomRight,\n  getHeight,\n  getTopLeft,\n  getTopRight,\n  getWidth,\n} from '../../extent.js';\nimport {WORKER_OFFSCREEN_CANVAS} from '../../has.js';\nimport RenderEvent from '../../render/Event.js';\nimport RenderEventType from '../../render/EventType.js';\nimport ZIndexContext from '../../render/canvas/ZIndexContext.js';\nimport {\n  apply as applyTransform,\n  compose as composeTransform,\n  create as createTransform,\n  equivalent,\n  makeInverse,\n  toString as toTransformString,\n} from '../../transform.js';\nimport LayerRenderer from '../Layer.js';\n\n/**\n * @type {Array<HTMLCanvasElement|OffscreenCanvas>}\n */\nexport const canvasPool = [];\n\n/**\n * @type {CanvasRenderingContext2D|OffscreenCanvasRenderingContext2D}\n */\nlet pixelContext = null;\n\nfunction createPixelContext() {\n  pixelContext = createCanvasContext2D(1, 1, undefined, {\n    willReadFrequently: true,\n  });\n}\n\n/**\n * @abstract\n * @template {import(\"../../layer/Layer.js\").default} LayerType\n * @extends {LayerRenderer<LayerType>}\n */\nclass CanvasLayerRenderer extends LayerRenderer {\n  /**\n   * @param {LayerType} layer Layer.\n   */\n  constructor(layer) {\n    super(layer);\n\n    /**\n     * HTMLElement container for the layer to be rendered in.\n     * @protected\n     * @type {HTMLElement}\n     */\n    this.container = null;\n\n    /**\n     * @protected\n     * @type {number}\n     */\n    this.renderedResolution;\n\n    /**\n     * A temporary transform.  The values in this transform should only be used in a\n     * function that sets the values.\n     * @protected\n     * @type {import(\"../../transform.js\").Transform}\n     */\n    this.tempTransform = createTransform();\n\n    /**\n     * The transform for rendered pixels to viewport CSS pixels.  This transform must\n     * be set when rendering a frame and may be used by other functions after rendering.\n     * @protected\n     * @type {import(\"../../transform.js\").Transform}\n     */\n    this.pixelTransform = createTransform();\n\n    /**\n     * The transform for viewport CSS pixels to rendered pixels.  This transform must\n     * be set when rendering a frame and may be used by other functions after rendering.\n     * @protected\n     * @type {import(\"../../transform.js\").Transform}\n     */\n    this.inversePixelTransform = createTransform();\n\n    /**\n     * @type {CanvasRenderingContext2D|OffscreenCanvasRenderingContext2D}\n     */\n    this.context = null;\n\n    /**\n     * @private\n     * @type {ZIndexContext}\n     */\n    this.deferredContext_ = null;\n\n    /**\n     * true if the container has been reused from the previous renderer\n     * @type {boolean}\n     */\n    this.containerReused = false;\n\n    /**\n     * @protected\n     * @type {import(\"../../Map.js\").FrameState|null}\n     */\n    this.frameState = null;\n  }\n\n  /**\n   * @param {import('../../DataTile.js').ImageLike} image Image.\n   * @param {number} col The column index.\n   * @param {number} row The row index.\n   * @return {Uint8ClampedArray|null} The image data.\n   */\n  getImageData(image, col, row) {\n    if (!pixelContext) {\n      createPixelContext();\n    }\n    pixelContext.clearRect(0, 0, 1, 1);\n\n    let data;\n    try {\n      pixelContext.drawImage(image, col, row, 1, 1, 0, 0, 1, 1);\n      data = pixelContext.getImageData(0, 0, 1, 1).data;\n    } catch {\n      pixelContext = null;\n      return null;\n    }\n    return data;\n  }\n\n  /**\n   * @param {import('../../Map.js').FrameState} frameState Frame state.\n   * @return {string} Background color.\n   */\n  getBackground(frameState) {\n    const layer = this.getLayer();\n    let background = layer.getBackground();\n    if (typeof background === 'function') {\n      background = background(frameState.viewState.resolution);\n    }\n    return background || undefined;\n  }\n\n  /**\n   * Get a rendering container from an existing target, if compatible.\n   * @param {HTMLElement} target Potential render target.\n   * @param {string} transform CSS transform matrix.\n   * @param {string} [backgroundColor] Background color.\n   */\n  useContainer(target, transform, backgroundColor) {\n    // renderer canvas to target canvas\n    const layerClassName = this.getLayer().getClassName();\n    let container, context;\n    if (\n      target &&\n      target.className === layerClassName &&\n      (!backgroundColor ||\n        (target &&\n          target.style.backgroundColor &&\n          equals(\n            asArray(target.style.backgroundColor),\n            asArray(backgroundColor),\n          )))\n    ) {\n      const canvas = target.firstElementChild;\n      if (isCanvas(canvas)) {\n        context = canvas.getContext('2d');\n      }\n    }\n    if (context && equivalent(context.canvas.style.transform, transform)) {\n      // Container of the previous layer renderer can be used.\n      this.container = target;\n      this.context = context;\n      this.containerReused = true;\n    } else if (this.containerReused) {\n      // Previously reused container cannot be used any more.\n      this.container = null;\n      this.context = null;\n      this.containerReused = false;\n    } else if (this.container) {\n      this.container.style.backgroundColor = null;\n    }\n    if (!this.container) {\n      container = WORKER_OFFSCREEN_CANVAS\n        ? createMockDiv()\n        : document.createElement('div');\n      container.className = layerClassName;\n      let style = container.style;\n      style.position = 'absolute';\n      style.width = '100%';\n      style.height = '100%';\n      context = createCanvasContext2D();\n      const canvas = /** @type {HTMLCanvasElement} */ (context.canvas);\n      container.appendChild(canvas);\n      style = canvas.style;\n      style.position = 'absolute';\n      style.left = '0';\n      style.transformOrigin = 'top left';\n      this.container = container;\n      this.context = context;\n    }\n    if (\n      !this.containerReused &&\n      backgroundColor &&\n      !this.container.style.backgroundColor\n    ) {\n      this.container.style.backgroundColor = backgroundColor;\n    }\n  }\n\n  /**\n   * @param {CanvasRenderingContext2D|OffscreenCanvasRenderingContext2D} context Context.\n   * @param {import(\"../../Map.js\").FrameState} frameState Frame state.\n   * @param {import(\"../../extent.js\").Extent} extent Clip extent.\n   * @protected\n   */\n  clipUnrotated(context, frameState, extent) {\n    const topLeft = getTopLeft(extent);\n    const topRight = getTopRight(extent);\n    const bottomRight = getBottomRight(extent);\n    const bottomLeft = getBottomLeft(extent);\n\n    applyTransform(frameState.coordinateToPixelTransform, topLeft);\n    applyTransform(frameState.coordinateToPixelTransform, topRight);\n    applyTransform(frameState.coordinateToPixelTransform, bottomRight);\n    applyTransform(frameState.coordinateToPixelTransform, bottomLeft);\n\n    const inverted = this.inversePixelTransform;\n    applyTransform(inverted, topLeft);\n    applyTransform(inverted, topRight);\n    applyTransform(inverted, bottomRight);\n    applyTransform(inverted, bottomLeft);\n\n    context.save();\n    context.beginPath();\n    context.moveTo(Math.round(topLeft[0]), Math.round(topLeft[1]));\n    context.lineTo(Math.round(topRight[0]), Math.round(topRight[1]));\n    context.lineTo(Math.round(bottomRight[0]), Math.round(bottomRight[1]));\n    context.lineTo(Math.round(bottomLeft[0]), Math.round(bottomLeft[1]));\n    context.clip();\n  }\n\n  /**\n   * @param {import(\"../../Map.js\").FrameState} frameState Frame state.\n   * @param {HTMLElement} target Target that may be used to render content to.\n   * @protected\n   */\n  prepareContainer(frameState, target) {\n    const extent = frameState.extent;\n    const resolution = frameState.viewState.resolution;\n    const rotation = frameState.viewState.rotation;\n    const pixelRatio = frameState.pixelRatio;\n    const width = Math.round((getWidth(extent) / resolution) * pixelRatio);\n    const height = Math.round((getHeight(extent) / resolution) * pixelRatio);\n    // set forward and inverse pixel transforms\n    composeTransform(\n      this.pixelTransform,\n      frameState.size[0] / 2,\n      frameState.size[1] / 2,\n      1 / pixelRatio,\n      1 / pixelRatio,\n      rotation,\n      -width / 2,\n      -height / 2,\n    );\n    makeInverse(this.inversePixelTransform, this.pixelTransform);\n\n    const canvasTransform = toTransformString(this.pixelTransform);\n    this.useContainer(target, canvasTransform, this.getBackground(frameState));\n    if (!this.containerReused) {\n      const canvas = this.context.canvas;\n      if (canvas.width != width || canvas.height != height) {\n        canvas.width = width;\n        canvas.height = height;\n      } else {\n        this.context.clearRect(0, 0, width, height);\n      }\n      if (\n        canvasTransform !==\n        /** @type {HTMLCanvasElement} */ (canvas).style.transform\n      ) {\n        /** @type {HTMLCanvasElement} */ (canvas).style.transform =\n          canvasTransform;\n      }\n    }\n  }\n\n  /**\n   * @param {import(\"../../render/EventType.js\").default} type Event type.\n   * @param {CanvasRenderingContext2D|OffscreenCanvasRenderingContext2D} context Context.\n   * @param {import(\"../../Map.js\").FrameState} frameState Frame state.\n   * @private\n   */\n  dispatchRenderEvent_(type, context, frameState) {\n    const layer = this.getLayer();\n    if (layer.hasListener(type)) {\n      const event = new RenderEvent(\n        type,\n        this.inversePixelTransform,\n        frameState,\n        context,\n      );\n      layer.dispatchEvent(event);\n    }\n  }\n\n  /**\n   * @param {CanvasRenderingContext2D|OffscreenCanvasRenderingContext2D} context Context.\n   * @param {import(\"../../Map.js\").FrameState} frameState Frame state.\n   * @protected\n   */\n  preRender(context, frameState) {\n    this.frameState = frameState;\n    if (frameState.declutter) {\n      return;\n    }\n    this.dispatchRenderEvent_(RenderEventType.PRERENDER, context, frameState);\n  }\n\n  /**\n   * @param {CanvasRenderingContext2D|OffscreenCanvasRenderingContext2D} context Context.\n   * @param {import(\"../../Map.js\").FrameState} frameState Frame state.\n   * @protected\n   */\n  postRender(context, frameState) {\n    if (frameState.declutter) {\n      return;\n    }\n    this.dispatchRenderEvent_(RenderEventType.POSTRENDER, context, frameState);\n  }\n\n  /**\n   * @param {import(\"../../Map.js\").FrameState} frameState Frame state.\n   */\n  renderDeferredInternal(frameState) {}\n\n  /**\n   * @param {import(\"../../Map.js\").FrameState} frameState Frame state.\n   * @return {import('../../render/canvas/ZIndexContext.js').ZIndexContextProxy} Context.\n   */\n  getRenderContext(frameState) {\n    if (frameState.declutter && !this.deferredContext_) {\n      this.deferredContext_ = new ZIndexContext();\n    }\n    return frameState.declutter\n      ? this.deferredContext_.getContext()\n      : this.context;\n  }\n\n  /**\n   * @param {import(\"../../Map.js\").FrameState} frameState Frame state.\n   * @override\n   */\n  renderDeferred(frameState) {\n    if (!frameState.declutter) {\n      return;\n    }\n    this.dispatchRenderEvent_(\n      RenderEventType.PRERENDER,\n      this.context,\n      frameState,\n    );\n    if (frameState.declutter && this.deferredContext_) {\n      this.deferredContext_.draw(this.context);\n      this.deferredContext_.clear();\n    }\n    this.renderDeferredInternal(frameState);\n    this.dispatchRenderEvent_(\n      RenderEventType.POSTRENDER,\n      this.context,\n      frameState,\n    );\n  }\n\n  /**\n   * Creates a transform for rendering to an element that will be rotated after rendering.\n   * @param {import(\"../../coordinate.js\").Coordinate} center Center.\n   * @param {number} resolution Resolution.\n   * @param {number} rotation Rotation.\n   * @param {number} pixelRatio Pixel ratio.\n   * @param {number} width Width of the rendered element (in pixels).\n   * @param {number} height Height of the rendered element (in pixels).\n   * @param {number} offsetX Offset on the x-axis in view coordinates.\n   * @protected\n   * @return {!import(\"../../transform.js\").Transform} Transform.\n   */\n  getRenderTransform(\n    center,\n    resolution,\n    rotation,\n    pixelRatio,\n    width,\n    height,\n    offsetX,\n  ) {\n    const dx1 = width / 2;\n    const dy1 = height / 2;\n    const sx = pixelRatio / resolution;\n    const sy = -sx;\n    const dx2 = -center[0] + offsetX;\n    const dy2 = -center[1];\n    return composeTransform(\n      this.tempTransform,\n      dx1,\n      dy1,\n      sx,\n      sy,\n      -rotation,\n      dx2,\n      dy2,\n    );\n  }\n\n  /**\n   * Clean up.\n   * @override\n   */\n  disposeInternal() {\n    delete this.frameState;\n    super.disposeInternal();\n  }\n}\n\nexport default CanvasLayerRenderer;\n", "/**\n * @module ol/renderer/canvas/TileLayer\n */\nimport DataTile, {asImageLike} from '../../DataTile.js';\nimport ImageTile from '../../ImageTile.js';\nimport TileRange from '../../TileRange.js';\nimport TileState from '../../TileState.js';\nimport {ascending} from '../../array.js';\nimport {\n  containsCoordinate,\n  createEmpty,\n  equals,\n  getIntersection,\n  getRotatedViewport,\n  getTopLeft,\n  intersects,\n} from '../../extent.js';\nimport {equivalent, fromUserExtent} from '../../proj.js';\nimport ReprojTile from '../../reproj/Tile.js';\nimport {toSize} from '../../size.js';\nimport LRUCache from '../../structs/LRUCache.js';\nimport {\n  createOrUpdate as createTileCoord,\n  getCacheKey,\n} from '../../tilecoord.js';\nimport {\n  apply as applyTransform,\n  compose as composeTransform,\n} from '../../transform.js';\nimport {getUid} from '../../util.js';\nimport CanvasLayerRenderer from './Layer.js';\n\n/**\n * @typedef {Object<number, Set<import(\"../../Tile.js\").default>>} TileLookup\n */\n\n/**\n * Add a tile to the lookup.\n * @param {TileLookup} tilesByZ Lookup of tiles by zoom level.\n * @param {import(\"../../Tile.js\").default} tile A tile.\n * @param {number} z The zoom level.\n * @return {boolean} The tile was added to the lookup.\n */\nfunction addTileToLookup(tilesByZ, tile, z) {\n  if (!(z in tilesByZ)) {\n    tilesByZ[z] = new Set([tile]);\n    return true;\n  }\n  const set = tilesByZ[z];\n  const existing = set.has(tile);\n  if (!existing) {\n    set.add(tile);\n  }\n  return !existing;\n}\n\n/**\n * Remove a tile from the lookup.\n * @param {TileLookup} tilesByZ Lookup of tiles by zoom level.\n * @param {import(\"../../Tile.js\").default} tile A tile.\n * @param {number} z The zoom level.\n * @return {boolean} The tile was removed from the lookup.\n */\nfunction removeTileFromLookup(tilesByZ, tile, z) {\n  const set = tilesByZ[z];\n  if (set) {\n    return set.delete(tile);\n  }\n  return false;\n}\n\n/**\n * @param {import(\"../../Map.js\").FrameState} frameState Frame state.\n * @param {import(\"../../extent.js\").Extent} extent The frame extent.\n * @return {import(\"../../extent.js\").Extent} Frame extent intersected with layer extents.\n */\nfunction getRenderExtent(frameState, extent) {\n  const layerState = frameState.layerStatesArray[frameState.layerIndex];\n  if (layerState.extent) {\n    extent = getIntersection(\n      extent,\n      fromUserExtent(layerState.extent, frameState.viewState.projection),\n    );\n  }\n  const source = /** @type {import(\"../../source/Tile.js\").default} */ (\n    layerState.layer.getRenderSource()\n  );\n  if (!source.getWrapX()) {\n    const gridExtent = source\n      .getTileGridForProjection(frameState.viewState.projection)\n      .getExtent();\n    if (gridExtent) {\n      extent = getIntersection(extent, gridExtent);\n    }\n  }\n  return extent;\n}\n\n/**\n * @typedef {Object} Options\n * @property {number} [cacheSize=512] The cache size.\n */\n\n/**\n * @classdesc\n * Canvas renderer for tile layers.\n * @api\n * @template {import(\"../../layer/Tile.js\").default|import(\"../../layer/VectorTile.js\").default} [LayerType=import(\"../../layer/Tile.js\").default<import(\"../../source/Tile.js\").default>|import(\"../../layer/VectorTile.js\").default]\n * @extends {CanvasLayerRenderer<LayerType>}\n */\nclass CanvasTileLayerRenderer extends CanvasLayerRenderer {\n  /**\n   * @param {LayerType} tileLayer Tile layer.\n   * @param {Options} [options] Options.\n   */\n  constructor(tileLayer, options) {\n    super(tileLayer);\n\n    options = options || {};\n\n    /**\n     * Rendered extent has changed since the previous `renderFrame()` call\n     * @type {boolean}\n     */\n    this.extentChanged = true;\n\n    /**\n     * The last call to `renderFrame` was completed with all tiles loaded\n     * @type {boolean}\n     */\n    this.renderComplete = false;\n\n    /**\n     * @private\n     * @type {?import(\"../../extent.js\").Extent}\n     */\n    this.renderedExtent_ = null;\n\n    /**\n     * @protected\n     * @type {number}\n     */\n    this.renderedPixelRatio;\n\n    /**\n     * @protected\n     * @type {import(\"../../proj/Projection.js\").default|null}\n     */\n    this.renderedProjection = null;\n\n    /**\n     * @protected\n     * @type {!Array<import(\"../../Tile.js\").default>}\n     */\n    this.renderedTiles = [];\n\n    /**\n     * @private\n     * @type {string}\n     */\n    this.renderedSourceKey_;\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.renderedSourceRevision_;\n\n    /**\n     * @protected\n     * @type {import(\"../../extent.js\").Extent}\n     */\n    this.tempExtent = createEmpty();\n\n    /**\n     * @private\n     * @type {import(\"../../TileRange.js\").default}\n     */\n    this.tempTileRange_ = new TileRange(0, 0, 0, 0);\n\n    /**\n     * @type {import(\"../../tilecoord.js\").TileCoord}\n     * @private\n     */\n    this.tempTileCoord_ = createTileCoord(0, 0, 0);\n\n    const cacheSize = options.cacheSize !== undefined ? options.cacheSize : 512;\n\n    /**\n     * @type {import(\"../../structs/LRUCache.js\").default<import(\"../../Tile.js\").default>}\n     * @private\n     */\n    this.tileCache_ = new LRUCache(cacheSize);\n\n    /**\n     * @type {import(\"../../structs/LRUCache.js\").default<import(\"../../Tile.js\").default|null>}\n     * @private\n     */\n    this.sourceTileCache_ = null;\n\n    /**\n     * @protected\n     * @type {import(\"../../extent.js\").Extent|null}\n     */\n    this.layerExtent = null;\n\n    this.maxStaleKeys = cacheSize * 0.5;\n  }\n\n  /**\n   * @return {LRUCache} Tile cache.\n   */\n  getTileCache() {\n    return this.tileCache_;\n  }\n\n  /**\n   * @return {LRUCache} Tile cache.\n   */\n  getSourceTileCache() {\n    if (!this.sourceTileCache_) {\n      this.sourceTileCache_ = new LRUCache(512);\n    }\n    return this.sourceTileCache_;\n  }\n\n  /**\n   * Get a tile from the cache or create one if needed.\n   *\n   * @param {number} z Tile coordinate z.\n   * @param {number} x Tile coordinate x.\n   * @param {number} y Tile coordinate y.\n   * @param {import(\"../../Map.js\").FrameState} frameState Frame state.\n   * @return {import(\"../../Tile.js\").default|null} Tile (or null if outside source extent).\n   * @protected\n   */\n  getOrCreateTile(z, x, y, frameState) {\n    const tileCache = this.tileCache_;\n    const tileLayer = this.getLayer();\n    const tileSource = tileLayer.getSource();\n    const cacheKey = getCacheKey(tileSource, tileSource.getKey(), z, x, y);\n\n    /** @type {import(\"../../Tile.js\").default} */\n    let tile;\n\n    if (tileCache.containsKey(cacheKey)) {\n      tile = tileCache.get(cacheKey);\n    } else {\n      const projection = frameState.viewState.projection;\n      const sourceProjection = tileSource.getProjection();\n      tile = tileSource.getTile(\n        z,\n        x,\n        y,\n        frameState.pixelRatio,\n        projection,\n        !sourceProjection || equivalent(sourceProjection, projection)\n          ? undefined\n          : this.getSourceTileCache(),\n      );\n      if (!tile) {\n        return null;\n      }\n      tileCache.set(cacheKey, tile);\n    }\n    return tile;\n  }\n\n  /**\n   * @param {number} z Tile coordinate z.\n   * @param {number} x Tile coordinate x.\n   * @param {number} y Tile coordinate y.\n   * @param {import(\"../../Map.js\").FrameState} frameState Frame state.\n   * @return {import(\"../../Tile.js\").default|null} Tile (or null if outside source extent).\n   * @protected\n   */\n  getTile(z, x, y, frameState) {\n    const tile = this.getOrCreateTile(z, x, y, frameState);\n    if (!tile) {\n      return null;\n    }\n    return tile;\n  }\n\n  /**\n   * @param {import(\"../../pixel.js\").Pixel} pixel Pixel.\n   * @return {Uint8ClampedArray} Data at the pixel location.\n   * @override\n   */\n  getData(pixel) {\n    const frameState = this.frameState;\n    if (!frameState) {\n      return null;\n    }\n\n    const layer = this.getLayer();\n    const coordinate = applyTransform(\n      frameState.pixelToCoordinateTransform,\n      pixel.slice(),\n    );\n\n    const layerExtent = layer.getExtent();\n    if (layerExtent) {\n      if (!containsCoordinate(layerExtent, coordinate)) {\n        return null;\n      }\n    }\n\n    const viewState = frameState.viewState;\n    const source = layer.getRenderSource();\n    const tileGrid = source.getTileGridForProjection(viewState.projection);\n    const tilePixelRatio = source.getTilePixelRatio(frameState.pixelRatio);\n\n    for (\n      let z = tileGrid.getZForResolution(viewState.resolution);\n      z >= tileGrid.getMinZoom();\n      --z\n    ) {\n      const tileCoord = tileGrid.getTileCoordForCoordAndZ(coordinate, z);\n      const tile = this.getTile(z, tileCoord[1], tileCoord[2], frameState);\n      if (!tile || tile.getState() !== TileState.LOADED) {\n        continue;\n      }\n\n      const tileOrigin = tileGrid.getOrigin(z);\n      const tileSize = toSize(tileGrid.getTileSize(z));\n      const tileResolution = tileGrid.getResolution(z);\n\n      /**\n       * @type {import('../../DataTile.js').ImageLike}\n       */\n      let image;\n      if (tile instanceof ImageTile || tile instanceof ReprojTile) {\n        image = tile.getImage();\n      } else if (tile instanceof DataTile) {\n        image = asImageLike(tile.getData());\n        if (!image) {\n          continue;\n        }\n      } else {\n        continue;\n      }\n\n      const col = Math.floor(\n        tilePixelRatio *\n          ((coordinate[0] - tileOrigin[0]) / tileResolution -\n            tileCoord[1] * tileSize[0]),\n      );\n\n      const row = Math.floor(\n        tilePixelRatio *\n          ((tileOrigin[1] - coordinate[1]) / tileResolution -\n            tileCoord[2] * tileSize[1]),\n      );\n\n      const gutter = Math.round(\n        tilePixelRatio * source.getGutterForProjection(viewState.projection),\n      );\n\n      return this.getImageData(image, col + gutter, row + gutter);\n    }\n\n    return null;\n  }\n\n  /**\n   * Determine whether render should be called.\n   * @param {import(\"../../Map.js\").FrameState} frameState Frame state.\n   * @return {boolean} Layer is ready to be rendered.\n   * @override\n   */\n  prepareFrame(frameState) {\n    if (!this.renderedProjection) {\n      this.renderedProjection = frameState.viewState.projection;\n    } else if (frameState.viewState.projection !== this.renderedProjection) {\n      this.tileCache_.clear();\n      this.renderedProjection = frameState.viewState.projection;\n    }\n\n    const source = this.getLayer().getSource();\n    if (!source) {\n      return false;\n    }\n    const sourceRevision = source.getRevision();\n    if (!this.renderedSourceRevision_) {\n      this.renderedSourceRevision_ = sourceRevision;\n    } else if (this.renderedSourceRevision_ !== sourceRevision) {\n      this.renderedSourceRevision_ = sourceRevision;\n      if (this.renderedSourceKey_ === source.getKey()) {\n        this.tileCache_.clear();\n        this.sourceTileCache_?.clear();\n      }\n    }\n    return true;\n  }\n\n  /**\n   * Determine whether tiles for next extent should be enqueued for rendering.\n   * @return {boolean} Rendering tiles for next extent is supported.\n   * @protected\n   */\n  enqueueTilesForNextExtent() {\n    return true;\n  }\n\n  /**\n   * @param {import(\"../../Map.js\").FrameState} frameState Frame state.\n   * @param {import(\"../../extent.js\").Extent} extent The extent to be rendered.\n   * @param {number} initialZ The zoom level.\n   * @param {TileLookup} tilesByZ Lookup of tiles by zoom level.\n   * @param {number} preload Number of additional levels to load.\n   */\n  enqueueTiles(frameState, extent, initialZ, tilesByZ, preload) {\n    const viewState = frameState.viewState;\n    const tileLayer = this.getLayer();\n    const tileSource = tileLayer.getRenderSource();\n    const tileGrid = tileSource.getTileGridForProjection(viewState.projection);\n\n    const tileSourceKey = getUid(tileSource);\n    if (!(tileSourceKey in frameState.wantedTiles)) {\n      frameState.wantedTiles[tileSourceKey] = {};\n    }\n\n    const wantedTiles = frameState.wantedTiles[tileSourceKey];\n\n    const map = tileLayer.getMapInternal();\n    const minZ = Math.max(\n      initialZ - preload,\n      tileGrid.getMinZoom(),\n      tileGrid.getZForResolution(\n        Math.min(\n          tileLayer.getMaxResolution(),\n          map\n            ? map\n                .getView()\n                .getResolutionForZoom(Math.max(tileLayer.getMinZoom(), 0))\n            : tileGrid.getResolution(0),\n        ),\n        tileSource.zDirection,\n      ),\n    );\n    const rotation = viewState.rotation;\n    const viewport = rotation\n      ? getRotatedViewport(\n          viewState.center,\n          viewState.resolution,\n          rotation,\n          frameState.size,\n        )\n      : undefined;\n    for (let z = initialZ; z >= minZ; --z) {\n      const tileRange = tileGrid.getTileRangeForExtentAndZ(\n        extent,\n        z,\n        this.tempTileRange_,\n      );\n\n      const tileResolution = tileGrid.getResolution(z);\n\n      for (let x = tileRange.minX; x <= tileRange.maxX; ++x) {\n        for (let y = tileRange.minY; y <= tileRange.maxY; ++y) {\n          if (\n            rotation &&\n            !tileGrid.tileCoordIntersectsViewport([z, x, y], viewport)\n          ) {\n            continue;\n          }\n          const tile = this.getTile(z, x, y, frameState);\n          if (!tile) {\n            continue;\n          }\n          const added = addTileToLookup(tilesByZ, tile, z);\n          if (!added) {\n            continue;\n          }\n\n          const tileQueueKey = tile.getKey();\n          wantedTiles[tileQueueKey] = true;\n\n          if (tile.getState() === TileState.IDLE) {\n            if (!frameState.tileQueue.isKeyQueued(tileQueueKey)) {\n              const tileCoord = createTileCoord(z, x, y, this.tempTileCoord_);\n              frameState.tileQueue.enqueue([\n                tile,\n                tileSourceKey,\n                tileGrid.getTileCoordCenter(tileCoord),\n                tileResolution,\n              ]);\n            }\n          }\n        }\n      }\n    }\n  }\n\n  /**\n   * Look for tiles covering the provided tile coordinate at an alternate\n   * zoom level.  Loaded tiles will be added to the provided tile texture lookup.\n   * @param {import(\"../../tilecoord.js\").TileCoord} tileCoord The target tile coordinate.\n   * @param {TileLookup} tilesByZ Lookup of tiles by zoom level.\n   * @return {boolean} The tile coordinate is covered by loaded tiles at the alternate zoom level.\n   * @private\n   */\n  findStaleTile_(tileCoord, tilesByZ) {\n    const tileCache = this.tileCache_;\n    const z = tileCoord[0];\n    const x = tileCoord[1];\n    const y = tileCoord[2];\n    const staleKeys = this.getStaleKeys();\n    for (let i = 0; i < staleKeys.length; ++i) {\n      const cacheKey = getCacheKey(\n        this.getLayer().getSource(),\n        staleKeys[i],\n        z,\n        x,\n        y,\n      );\n      if (tileCache.containsKey(cacheKey)) {\n        const tile = tileCache.peek(cacheKey);\n        if (tile.getState() === TileState.LOADED) {\n          tile.endTransition(getUid(this));\n          addTileToLookup(tilesByZ, tile, z);\n          return true;\n        }\n      }\n    }\n    return false;\n  }\n\n  /**\n   * Look for tiles covering the provided tile coordinate at an alternate\n   * zoom level.  Loaded tiles will be added to the provided tile texture lookup.\n   * @param {import(\"../../tilegrid/TileGrid.js\").default} tileGrid The tile grid.\n   * @param {import(\"../../tilecoord.js\").TileCoord} tileCoord The target tile coordinate.\n   * @param {number} altZ The alternate zoom level.\n   * @param {TileLookup} tilesByZ Lookup of tiles by zoom level.\n   * @return {boolean} The tile coordinate is covered by loaded tiles at the alternate zoom level.\n   * @private\n   */\n  findAltTiles_(tileGrid, tileCoord, altZ, tilesByZ) {\n    const tileRange = tileGrid.getTileRangeForTileCoordAndZ(\n      tileCoord,\n      altZ,\n      this.tempTileRange_,\n    );\n\n    if (!tileRange) {\n      return false;\n    }\n\n    let covered = true;\n    const tileCache = this.tileCache_;\n    const source = this.getLayer().getRenderSource();\n    const sourceKey = source.getKey();\n    for (let x = tileRange.minX; x <= tileRange.maxX; ++x) {\n      for (let y = tileRange.minY; y <= tileRange.maxY; ++y) {\n        const cacheKey = getCacheKey(source, sourceKey, altZ, x, y);\n        let loaded = false;\n        if (tileCache.containsKey(cacheKey)) {\n          const tile = tileCache.peek(cacheKey);\n          if (tile.getState() === TileState.LOADED) {\n            addTileToLookup(tilesByZ, tile, altZ);\n            loaded = true;\n          }\n        }\n        if (!loaded) {\n          covered = false;\n        }\n      }\n    }\n    return covered;\n  }\n\n  /**\n   * Render the layer.\n   *\n   * The frame rendering logic has three parts:\n   *\n   *  1. Enqueue tiles\n   *  2. Find alt tiles for those that are not yet loaded\n   *  3. Render loaded tiles\n   *\n   * @param {import(\"../../Map.js\").FrameState} frameState Frame state.\n   * @param {HTMLElement} target Target that may be used to render content to.\n   * @return {HTMLElement} The rendered element.\n   * @override\n   */\n  renderFrame(frameState, target) {\n    this.renderComplete = true;\n    /**\n     * TODO:\n     *  maybe skip transition when not fully opaque\n     *  decide if this.renderComplete is useful\n     */\n\n    const layerState = frameState.layerStatesArray[frameState.layerIndex];\n    const viewState = frameState.viewState;\n    const projection = viewState.projection;\n    const viewResolution = viewState.resolution;\n    const viewCenter = viewState.center;\n    const pixelRatio = frameState.pixelRatio;\n\n    const tileLayer = this.getLayer();\n    const tileSource = tileLayer.getSource();\n    const tileGrid = tileSource.getTileGridForProjection(projection);\n    const z = tileGrid.getZForResolution(viewResolution, tileSource.zDirection);\n    const tileResolution = tileGrid.getResolution(z);\n\n    const sourceKey = tileSource.getKey();\n    if (!this.renderedSourceKey_) {\n      this.renderedSourceKey_ = sourceKey;\n    } else if (this.renderedSourceKey_ !== sourceKey) {\n      this.prependStaleKey(this.renderedSourceKey_);\n      this.renderedSourceKey_ = sourceKey;\n    }\n\n    let frameExtent = frameState.extent;\n    const tilePixelRatio = tileSource.getTilePixelRatio(pixelRatio);\n\n    this.prepareContainer(frameState, target);\n\n    // desired dimensions of the canvas in pixels\n    const width = this.context.canvas.width;\n    const height = this.context.canvas.height;\n\n    this.layerExtent = layerState.extent\n      ? fromUserExtent(layerState.extent, projection)\n      : null;\n    if (this.layerExtent) {\n      frameExtent = getIntersection(frameExtent, this.layerExtent);\n    }\n\n    const dx = (tileResolution * width) / 2 / tilePixelRatio;\n    const dy = (tileResolution * height) / 2 / tilePixelRatio;\n    const canvasExtent = [\n      viewCenter[0] - dx,\n      viewCenter[1] - dy,\n      viewCenter[0] + dx,\n      viewCenter[1] + dy,\n    ];\n\n    /**\n     * @type {TileLookup}\n     */\n    const tilesByZ = {};\n\n    this.renderedTiles.length = 0;\n\n    /**\n     * Part 1: Enqueue tiles\n     */\n\n    const preload = tileLayer.getPreload();\n    if (frameState.nextExtent && this.enqueueTilesForNextExtent()) {\n      const targetZ = tileGrid.getZForResolution(\n        viewState.nextResolution,\n        tileSource.zDirection,\n      );\n      const nextExtent = getRenderExtent(frameState, frameState.nextExtent);\n      this.enqueueTiles(frameState, nextExtent, targetZ, tilesByZ, preload);\n    }\n\n    const renderExtent = getRenderExtent(frameState, frameExtent);\n    this.enqueueTiles(frameState, renderExtent, z, tilesByZ, 0);\n    if (preload > 0) {\n      setTimeout(() => {\n        this.enqueueTiles(\n          frameState,\n          renderExtent,\n          z - 1,\n          tilesByZ,\n          preload - 1,\n        );\n      }, 0);\n    }\n\n    if (!(z in tilesByZ)) {\n      return this.container;\n    }\n\n    /**\n     * Part 2: Find alt tiles for those that are not yet loaded\n     */\n\n    const uid = getUid(this);\n    const time = frameState.time;\n\n    // look for cached tiles to use if a target tile is not ready\n    for (const tile of tilesByZ[z]) {\n      const tileState = tile.getState();\n      if (tileState === TileState.EMPTY) {\n        continue;\n      }\n      const tileCoord = tile.tileCoord;\n\n      if (tileState === TileState.LOADED) {\n        const alpha = tile.getAlpha(uid, time);\n        if (alpha === 1) {\n          // no need to look for alt tiles\n          tile.endTransition(uid);\n          continue;\n        }\n      }\n      if (tileState !== TileState.ERROR) {\n        this.renderComplete = false;\n      }\n\n      const hasStaleTile = this.findStaleTile_(tileCoord, tilesByZ);\n      if (hasStaleTile) {\n        // use the stale tile before the new tile's transition has completed\n        removeTileFromLookup(tilesByZ, tile, z);\n        frameState.animate = true;\n        continue;\n      }\n\n      // first look for child tiles (at z + 1)\n      const coveredByChildren = this.findAltTiles_(\n        tileGrid,\n        tileCoord,\n        z + 1,\n        tilesByZ,\n      );\n\n      if (coveredByChildren) {\n        continue;\n      }\n\n      // next look for parent tiles\n      const minZoom = tileGrid.getMinZoom();\n      for (let parentZ = z - 1; parentZ >= minZoom; --parentZ) {\n        const coveredByParent = this.findAltTiles_(\n          tileGrid,\n          tileCoord,\n          parentZ,\n          tilesByZ,\n        );\n\n        if (coveredByParent) {\n          break;\n        }\n      }\n    }\n\n    /**\n     * Part 3: Render loaded tiles\n     */\n\n    const canvasScale =\n      ((tileResolution / viewResolution) * pixelRatio) / tilePixelRatio;\n\n    const context = this.getRenderContext(frameState);\n\n    // set scale transform for calculating tile positions on the canvas\n    composeTransform(\n      this.tempTransform,\n      width / 2,\n      height / 2,\n      canvasScale,\n      canvasScale,\n      0,\n      -width / 2,\n      -height / 2,\n    );\n\n    if (this.layerExtent) {\n      this.clipUnrotated(context, frameState, this.layerExtent);\n    }\n\n    if (!tileSource.getInterpolate()) {\n      context.imageSmoothingEnabled = false;\n    }\n\n    this.preRender(context, frameState);\n\n    /** @type {Array<number>} */\n    const zs = Object.keys(tilesByZ).map(Number);\n    zs.sort(ascending);\n\n    let currentClip;\n    const clips = [];\n    const clipZs = [];\n    for (let i = zs.length - 1; i >= 0; --i) {\n      const currentZ = zs[i];\n      const currentTilePixelSize = tileSource.getTilePixelSize(\n        currentZ,\n        pixelRatio,\n        projection,\n      );\n      const currentResolution = tileGrid.getResolution(currentZ);\n      const currentScale = currentResolution / tileResolution;\n      const dx = currentTilePixelSize[0] * currentScale * canvasScale;\n      const dy = currentTilePixelSize[1] * currentScale * canvasScale;\n      const originTileCoord = tileGrid.getTileCoordForCoordAndZ(\n        getTopLeft(canvasExtent),\n        currentZ,\n      );\n      const originTileExtent = tileGrid.getTileCoordExtent(originTileCoord);\n      const origin = applyTransform(this.tempTransform, [\n        (tilePixelRatio * (originTileExtent[0] - canvasExtent[0])) /\n          tileResolution,\n        (tilePixelRatio * (canvasExtent[3] - originTileExtent[3])) /\n          tileResolution,\n      ]);\n      const tileGutter =\n        tilePixelRatio * tileSource.getGutterForProjection(projection);\n      for (const tile of tilesByZ[currentZ]) {\n        if (tile.getState() !== TileState.LOADED) {\n          continue;\n        }\n        const tileCoord = tile.tileCoord;\n\n        // Calculate integer positions and sizes so that tiles align\n        const xIndex = originTileCoord[1] - tileCoord[1];\n        const nextX = Math.round(origin[0] - (xIndex - 1) * dx);\n        const yIndex = originTileCoord[2] - tileCoord[2];\n        const nextY = Math.round(origin[1] - (yIndex - 1) * dy);\n        const x = Math.round(origin[0] - xIndex * dx);\n        const y = Math.round(origin[1] - yIndex * dy);\n        const w = nextX - x;\n        const h = nextY - y;\n        const transition = zs.length === 1;\n\n        let contextSaved = false;\n\n        // Clip mask for regions in this tile that already filled by a higher z tile\n        currentClip = [x, y, x + w, y, x + w, y + h, x, y + h];\n        for (let i = 0, ii = clips.length; i < ii; ++i) {\n          if (!transition && currentZ < clipZs[i]) {\n            const clip = clips[i];\n            if (\n              intersects(\n                [x, y, x + w, y + h],\n                [clip[0], clip[3], clip[4], clip[7]],\n              )\n            ) {\n              if (!contextSaved) {\n                context.save();\n                contextSaved = true;\n              }\n              context.beginPath();\n              // counter-clockwise (outer ring) for current tile\n              context.moveTo(currentClip[0], currentClip[1]);\n              context.lineTo(currentClip[2], currentClip[3]);\n              context.lineTo(currentClip[4], currentClip[5]);\n              context.lineTo(currentClip[6], currentClip[7]);\n              // clockwise (inner ring) for higher z tile\n              context.moveTo(clip[6], clip[7]);\n              context.lineTo(clip[4], clip[5]);\n              context.lineTo(clip[2], clip[3]);\n              context.lineTo(clip[0], clip[1]);\n              context.clip();\n            }\n          }\n        }\n        clips.push(currentClip);\n        clipZs.push(currentZ);\n\n        this.drawTile(tile, frameState, x, y, w, h, tileGutter, transition);\n        if (contextSaved) {\n          context.restore();\n        }\n        this.renderedTiles.unshift(tile);\n\n        // TODO: decide if this is necessary\n        this.updateUsedTiles(frameState.usedTiles, tileSource, tile);\n      }\n    }\n\n    this.renderedResolution = tileResolution;\n    this.extentChanged =\n      !this.renderedExtent_ || !equals(this.renderedExtent_, canvasExtent);\n    this.renderedExtent_ = canvasExtent;\n    this.renderedPixelRatio = pixelRatio;\n\n    this.postRender(this.context, frameState);\n\n    if (this.layerExtent) {\n      context.restore();\n    }\n    context.imageSmoothingEnabled = true;\n\n    if (this.renderComplete) {\n      /**\n       * @param {import(\"../../Map.js\").default} map Map.\n       * @param {import(\"../../Map.js\").FrameState} frameState Frame state.\n       */\n      const postRenderFunction = (map, frameState) => {\n        const tileSourceKey = getUid(tileSource);\n        const wantedTiles = frameState.wantedTiles[tileSourceKey];\n        const tilesCount = wantedTiles ? Object.keys(wantedTiles).length : 0;\n        this.updateCacheSize(tilesCount);\n        this.tileCache_.expireCache();\n        this.sourceTileCache_?.expireCache();\n      };\n\n      frameState.postRenderFunctions.push(postRenderFunction);\n    }\n\n    // this normally is `div.ol-layer` and is a mocked div in worker\n    return this.container;\n  }\n\n  /**\n   * Increases the cache size if needed\n   * @param {number} tileCount Minimum number of tiles needed.\n   */\n  updateCacheSize(tileCount) {\n    this.tileCache_.highWaterMark = Math.max(\n      this.tileCache_.highWaterMark,\n      tileCount * 2,\n    );\n  }\n\n  /**\n   * @param {import(\"../../Tile.js\").default} tile Tile.\n   * @param {import(\"../../Map.js\").FrameState} frameState Frame state.\n   * @param {number} x Left of the tile.\n   * @param {number} y Top of the tile.\n   * @param {number} w Width of the tile.\n   * @param {number} h Height of the tile.\n   * @param {number} gutter Tile gutter.\n   * @param {boolean} transition Apply an alpha transition.\n   * @protected\n   */\n  drawTile(tile, frameState, x, y, w, h, gutter, transition) {\n    let image;\n    if (tile instanceof DataTile) {\n      image = asImageLike(tile.getData());\n      if (!image) {\n        throw new Error('Rendering array data is not yet supported');\n      }\n    } else {\n      image = this.getTileImage(\n        /** @type {import(\"../../ImageTile.js\").default} */ (tile),\n      );\n    }\n\n    if (!image) {\n      return;\n    }\n    const context = this.getRenderContext(frameState);\n    const uid = getUid(this);\n    const layerState = frameState.layerStatesArray[frameState.layerIndex];\n    const alpha =\n      layerState.opacity *\n      (transition ? tile.getAlpha(uid, frameState.time) : 1);\n    const alphaChanged = alpha !== context.globalAlpha;\n    if (alphaChanged) {\n      context.save();\n      context.globalAlpha = alpha;\n    }\n    context.drawImage(\n      image,\n      gutter,\n      gutter,\n      image.width - 2 * gutter,\n      image.height - 2 * gutter,\n      x,\n      y,\n      w,\n      h,\n    );\n\n    if (alphaChanged) {\n      context.restore();\n    }\n    if (alpha !== layerState.opacity) {\n      frameState.animate = true;\n    } else if (transition) {\n      tile.endTransition(uid);\n    }\n  }\n\n  /**\n   * @return {HTMLCanvasElement|OffscreenCanvas} Image\n   */\n  getImage() {\n    const context = this.context;\n    return context ? context.canvas : null;\n  }\n\n  /**\n   * Get the image from a tile.\n   * @param {import(\"../../ImageTile.js\").default} tile Tile.\n   * @return {HTMLCanvasElement|OffscreenCanvas|HTMLImageElement|HTMLVideoElement} Image.\n   * @protected\n   */\n  getTileImage(tile) {\n    return tile.getImage();\n  }\n\n  /**\n   * @param {!Object<string, !Object<string, boolean>>} usedTiles Used tiles.\n   * @param {import(\"../../source/Tile.js\").default} tileSource Tile source.\n   * @param {import('../../Tile.js').default} tile Tile.\n   * @protected\n   */\n  updateUsedTiles(usedTiles, tileSource, tile) {\n    // FIXME should we use tilesToDrawByZ instead?\n    const tileSourceKey = getUid(tileSource);\n    if (!(tileSourceKey in usedTiles)) {\n      usedTiles[tileSourceKey] = {};\n    }\n    usedTiles[tileSourceKey][tile.getKey()] = true;\n  }\n}\n\nexport default CanvasTileLayerRenderer;\n", "/**\n * @module ol/layer/TileProperty\n */\n\n/**\n * @enum {string}\n */\nexport default {\n  PRELOAD: 'preload',\n  USE_INTERIM_TILES_ON_ERROR: 'useInterimTilesOnError',\n};\n", "/**\n * @module ol/layer/BaseTile\n */\nimport Layer from './Layer.js';\nimport TileProperty from './TileProperty.js';\n\n/***\n * @template Return\n * @typedef {import(\"../Observable.js\").OnSignature<import(\"../Observable.js\").EventTypes, import(\"../events/Event.js\").default, Return> &\n *   import(\"../Observable.js\").OnSignature<import(\"./Base.js\").BaseLayerObjectEventTypes|\n *     import(\"./Layer.js\").LayerEventType|'change:preload'|'change:useInterimTilesOnError', import(\"../Object.js\").ObjectEvent, Return> &\n *   import(\"../Observable.js\").OnSignature<import(\"../render/EventType.js\").LayerRenderEventTypes, import(\"../render/Event.js\").default, Return> &\n *   import(\"../Observable.js\").CombinedOnSignature<import(\"../Observable.js\").EventTypes|import(\"./Base.js\").BaseLayerObjectEventTypes|\n *   import(\"./Layer.js\").LayerEventType|'change:preload'|'change:useInterimTilesOnError'|import(\"../render/EventType.js\").LayerRenderEventTypes, Return>} BaseTileLayerOnSignature\n */\n\n/**\n * @template {import(\"../source/Tile.js\").default} TileSourceType\n * @typedef {Object} Options\n * @property {string} [className='ol-layer'] A CSS class name to set to the layer element.\n * @property {number} [opacity=1] Opacity (0, 1).\n * @property {boolean} [visible=true] Visibility.\n * @property {import(\"../extent.js\").Extent} [extent] The bounding extent for layer rendering.  The layer will not be\n * rendered outside of this extent.\n * @property {number} [zIndex] The z-index for layer rendering.  At rendering time, the layers\n * will be ordered, first by Z-index and then by position. When `undefined`, a `zIndex` of 0 is assumed\n * for layers that are added to the map's `layers` collection, or `Infinity` when the layer's `setMap()`\n * method was used.\n * @property {number} [minResolution] The minimum resolution (inclusive) at which this layer will be\n * visible.\n * @property {number} [maxResolution] The maximum resolution (exclusive) below which this layer will\n * be visible.\n * @property {number} [minZoom] The minimum view zoom level (exclusive) above which this layer will be\n * visible.\n * @property {number} [maxZoom] The maximum view zoom level (inclusive) at which this layer will\n * be visible.\n * @property {number} [preload=0] Preload. Load low-resolution tiles up to `preload` levels. `0`\n * means no preloading.\n * @property {TileSourceType} [source] Source for this layer.\n * @property {import(\"../Map.js\").default} [map] Sets the layer as overlay on a map. The map will not manage\n * this layer in its layers collection, and the layer will be rendered on top. This is useful for\n * temporary layers. The standard way to add a layer to a map and have it managed by the map is to\n * use {@link import(\"../Map.js\").default#addLayer map.addLayer()}.\n * @property {import(\"./Base.js\").BackgroundColor} [background] Background color for the layer. If not specified, no background\n * will be rendered.\n * @property {boolean} [useInterimTilesOnError=true] Deprecated.  Use interim tiles on error.\n * @property {Object<string, *>} [properties] Arbitrary observable properties. Can be accessed with `#get()` and `#set()`.\n * @property {number} [cacheSize=512] The internal tile cache size.  This needs to be large enough to render\n * two zoom levels worth of tiles.\n */\n\n/**\n * @classdesc\n * For layer sources that provide pre-rendered, tiled images in grids that are\n * organized by zoom levels for specific resolutions.\n * Note that any property set in the options is set as a {@link module:ol/Object~BaseObject}\n * property on the layer object; for example, setting `title: 'My Title'` in the\n * options means that `title` is observable, and has get/set accessors.\n *\n * @template {import(\"../source/Tile.js\").default} TileSourceType\n * @template {import(\"../renderer/Layer.js\").default} RendererType\n * @extends {Layer<TileSourceType, RendererType>}\n * @api\n */\nclass BaseTileLayer extends Layer {\n  /**\n   * @param {Options<TileSourceType>} [options] Tile layer options.\n   */\n  constructor(options) {\n    options = options ? options : {};\n\n    const baseOptions = Object.assign({}, options);\n\n    const cacheSize = options.cacheSize;\n    delete options.cacheSize;\n\n    delete baseOptions.preload;\n    delete baseOptions.useInterimTilesOnError;\n    super(baseOptions);\n\n    /***\n     * @type {BaseTileLayerOnSignature<import(\"../events.js\").EventsKey>}\n     */\n    this.on;\n\n    /***\n     * @type {BaseTileLayerOnSignature<import(\"../events.js\").EventsKey>}\n     */\n    this.once;\n\n    /***\n     * @type {BaseTileLayerOnSignature<void>}\n     */\n    this.un;\n\n    /**\n     * @type {number|undefined}\n     * @private\n     */\n    this.cacheSize_ = cacheSize;\n\n    this.setPreload(options.preload !== undefined ? options.preload : 0);\n    this.setUseInterimTilesOnError(\n      options.useInterimTilesOnError !== undefined\n        ? options.useInterimTilesOnError\n        : true,\n    );\n  }\n\n  /**\n   * @return {number|undefined} The suggested cache size\n   * @protected\n   */\n  getCacheSize() {\n    return this.cacheSize_;\n  }\n\n  /**\n   * Return the level as number to which we will preload tiles up to.\n   * @return {number} The level to preload tiles up to.\n   * @observable\n   * @api\n   */\n  getPreload() {\n    return /** @type {number} */ (this.get(TileProperty.PRELOAD));\n  }\n\n  /**\n   * Set the level as number to which we will preload tiles up to.\n   * @param {number} preload The level to preload tiles up to.\n   * @observable\n   * @api\n   */\n  setPreload(preload) {\n    this.set(TileProperty.PRELOAD, preload);\n  }\n\n  /**\n   * Deprecated.  Whether we use interim tiles on error.\n   * @return {boolean} Use interim tiles on error.\n   * @observable\n   * @api\n   */\n  getUseInterimTilesOnError() {\n    return /** @type {boolean} */ (\n      this.get(TileProperty.USE_INTERIM_TILES_ON_ERROR)\n    );\n  }\n\n  /**\n   * Deprecated.  Set whether we use interim tiles on error.\n   * @param {boolean} useInterimTilesOnError Use interim tiles on error.\n   * @observable\n   * @api\n   */\n  setUseInterimTilesOnError(useInterimTilesOnError) {\n    this.set(TileProperty.USE_INTERIM_TILES_ON_ERROR, useInterimTilesOnError);\n  }\n\n  /**\n   * Get data for a pixel location.  The return type depends on the source data.  For image tiles,\n   * a four element RGBA array will be returned.  For data tiles, the array length will match the\n   * number of bands in the dataset.  For requests outside the layer extent, `null` will be returned.\n   * Data for a image tiles can only be retrieved if the source's `crossOrigin` property is set.\n   *\n   * ```js\n   * // display layer data on every pointer move\n   * map.on('pointermove', (event) => {\n   *   console.log(layer.getData(event.pixel));\n   * });\n   * ```\n   * @param {import(\"../pixel.js\").Pixel} pixel Pixel.\n   * @return {Uint8ClampedArray|Uint8Array|Float32Array|DataView|null} Pixel data.\n   * @api\n   * @override\n   */\n  getData(pixel) {\n    return super.getData(pixel);\n  }\n}\n\nexport default BaseTileLayer;\n", "/**\n * @module ol/layer/Tile\n */\nimport CanvasTileLayerRenderer from '../renderer/canvas/TileLayer.js';\nimport BaseTileLayer from './BaseTile.js';\n\n/**\n * @classdesc\n * For layer sources that provide pre-rendered, tiled images in grids that are\n * organized by zoom levels for specific resolutions.\n * Note that any property set in the options is set as a {@link module:ol/Object~BaseObject}\n * property on the layer object; for example, setting `title: 'My Title'` in the\n * options means that `title` is observable, and has get/set accessors.\n *\n * @template {import(\"../source/Tile.js\").default} [TileSourceType=import(\"../source/Tile.js\").default]\n * @extends BaseTileLayer<TileSourceType, CanvasTileLayerRenderer>\n * @api\n */\nclass TileLayer extends BaseTileLayer {\n  /**\n   * @param {import(\"./BaseTile.js\").Options<TileSourceType>} [options] Tile layer options.\n   */\n  constructor(options) {\n    super(options);\n  }\n\n  /**\n   * @override\n   */\n  createRenderer() {\n    return new CanvasTileLayerRenderer(this, {\n      cacheSize: this.getCacheSize(),\n    });\n  }\n}\n\nexport default TileLayer;\n", "/**\n * @module ol/tilegrid/TileGrid\n */\nimport TileRange, {\n  createOrUpdate as createOrUpdateTileRange,\n} from '../TileRange.js';\nimport {isSorted, linearFindNearest} from '../array.js';\nimport {assert} from '../asserts.js';\nimport {createOrUpdate, getTopLeft} from '../extent.js';\nimport {intersectsLinearRing} from '../geom/flat/intersectsextent.js';\nimport {ceil, clamp, floor} from '../math.js';\nimport {toSize} from '../size.js';\nimport {createOrUpdate as createOrUpdateTileCoord} from '../tilecoord.js';\nimport {DEFAULT_TILE_SIZE} from './common.js';\n\n/**\n * @private\n * @type {import(\"../tilecoord.js\").TileCoord}\n */\nconst tmpTileCoord = [0, 0, 0];\n\n/**\n * Number of decimal digits to consider in integer values when rounding.\n * @type {number}\n */\nconst DECIMALS = 5;\n\n/**\n * @typedef {Object} Options\n * @property {import(\"../extent.js\").Extent} [extent] Extent for the tile grid. No tiles outside this\n * extent will be requested by {@link module:ol/source/Tile~TileSource} sources. When no `origin` or\n * `origins` are configured, the `origin` will be set to the top-left corner of the extent.\n * @property {number} [minZoom=0] Minimum zoom.\n * @property {import(\"../coordinate.js\").Coordinate} [origin] The tile grid origin, i.e. where the `x`\n * and `y` axes meet (`[z, 0, 0]`). Tile coordinates increase left to right and downwards. If not\n * specified, `extent` or `origins` must be provided.\n * @property {Array<import(\"../coordinate.js\").Coordinate>} [origins] Tile grid origins, i.e. where\n * the `x` and `y` axes meet (`[z, 0, 0]`), for each zoom level. If given, the array length\n * should match the length of the `resolutions` array, i.e. each resolution can have a different\n * origin. Tile coordinates increase left to right and downwards. If not specified, `extent` or\n * `origin` must be provided.\n * @property {!Array<number>} resolutions Resolutions. The array index of each resolution needs\n * to match the zoom level. This means that even if a `minZoom` is configured, the resolutions\n * array will have a length of `maxZoom + 1`.\n * @property {Array<import(\"../size.js\").Size>} [sizes] Number of tile rows and columns\n * of the grid for each zoom level. If specified the values\n * define each zoom level's extent together with the `origin` or `origins`.\n * A grid `extent` can be configured in addition, and will further limit the extent\n * for which tile requests are made by sources. If the bottom-left corner of\n * an extent is used as `origin` or `origins`, then the `y` value must be\n * negative because OpenLayers tile coordinates use the top left as the origin.\n * @property {number|import(\"../size.js\").Size} [tileSize] Tile size.\n * Default is `[256, 256]`.\n * @property {Array<number|import(\"../size.js\").Size>} [tileSizes] Tile sizes. If given, the array length\n * should match the length of the `resolutions` array, i.e. each resolution can have a different\n * tile size.\n */\n\n/**\n * @classdesc\n * Base class for setting the grid pattern for sources accessing tiled-image\n * servers.\n * @api\n */\nclass TileGrid {\n  /**\n   * @param {Options} options Tile grid options.\n   */\n  constructor(options) {\n    /**\n     * @protected\n     * @type {number}\n     */\n    this.minZoom = options.minZoom !== undefined ? options.minZoom : 0;\n\n    /**\n     * @private\n     * @type {!Array<number>}\n     */\n    this.resolutions_ = options.resolutions;\n    assert(\n      isSorted(\n        this.resolutions_,\n        /**\n         * @param {number} a First resolution\n         * @param {number} b Second resolution\n         * @return {number} Comparison result\n         */\n        (a, b) => b - a,\n        true,\n      ),\n      '`resolutions` must be sorted in descending order',\n    );\n\n    // check if we've got a consistent zoom factor and origin\n    let zoomFactor;\n    if (!options.origins) {\n      for (let i = 0, ii = this.resolutions_.length - 1; i < ii; ++i) {\n        if (!zoomFactor) {\n          zoomFactor = this.resolutions_[i] / this.resolutions_[i + 1];\n        } else {\n          if (this.resolutions_[i] / this.resolutions_[i + 1] !== zoomFactor) {\n            zoomFactor = undefined;\n            break;\n          }\n        }\n      }\n    }\n\n    /**\n     * @private\n     * @type {number|undefined}\n     */\n    this.zoomFactor_ = zoomFactor;\n\n    /**\n     * @protected\n     * @type {number}\n     */\n    this.maxZoom = this.resolutions_.length - 1;\n\n    /**\n     * @private\n     * @type {import(\"../coordinate.js\").Coordinate|null}\n     */\n    this.origin_ = options.origin !== undefined ? options.origin : null;\n\n    /**\n     * @private\n     * @type {Array<import(\"../coordinate.js\").Coordinate>}\n     */\n    this.origins_ = null;\n    if (options.origins !== undefined) {\n      this.origins_ = options.origins;\n      assert(\n        this.origins_.length == this.resolutions_.length,\n        'Number of `origins` and `resolutions` must be equal',\n      );\n    }\n\n    const extent = options.extent;\n\n    if (extent !== undefined && !this.origin_ && !this.origins_) {\n      this.origin_ = getTopLeft(extent);\n    }\n\n    assert(\n      (!this.origin_ && this.origins_) || (this.origin_ && !this.origins_),\n      'Either `origin` or `origins` must be configured, never both',\n    );\n\n    /**\n     * @private\n     * @type {Array<number|import(\"../size.js\").Size>}\n     */\n    this.tileSizes_ = null;\n    if (options.tileSizes !== undefined) {\n      this.tileSizes_ = options.tileSizes;\n      assert(\n        this.tileSizes_.length == this.resolutions_.length,\n        'Number of `tileSizes` and `resolutions` must be equal',\n      );\n    }\n\n    /**\n     * @private\n     * @type {number|import(\"../size.js\").Size}\n     */\n    this.tileSize_ =\n      options.tileSize !== undefined\n        ? options.tileSize\n        : !this.tileSizes_\n          ? DEFAULT_TILE_SIZE\n          : null;\n    assert(\n      (!this.tileSize_ && this.tileSizes_) ||\n        (this.tileSize_ && !this.tileSizes_),\n      'Either `tileSize` or `tileSizes` must be configured, never both',\n    );\n\n    /**\n     * @private\n     * @type {import(\"../extent.js\").Extent}\n     */\n    this.extent_ = extent !== undefined ? extent : null;\n\n    /**\n     * @private\n     * @type {Array<import(\"../TileRange.js\").default>}\n     */\n    this.fullTileRanges_ = null;\n\n    /**\n     * @private\n     * @type {import(\"../size.js\").Size}\n     */\n    this.tmpSize_ = [0, 0];\n\n    /**\n     * @private\n     * @type {import(\"../extent.js\").Extent}\n     */\n    this.tmpExtent_ = [0, 0, 0, 0];\n\n    if (options.sizes !== undefined) {\n      this.fullTileRanges_ = options.sizes.map((size, z) => {\n        const tileRange = new TileRange(\n          Math.min(0, size[0]),\n          Math.max(size[0] - 1, -1),\n          Math.min(0, size[1]),\n          Math.max(size[1] - 1, -1),\n        );\n        if (extent) {\n          const restrictedTileRange = this.getTileRangeForExtentAndZ(extent, z);\n          tileRange.minX = Math.max(restrictedTileRange.minX, tileRange.minX);\n          tileRange.maxX = Math.min(restrictedTileRange.maxX, tileRange.maxX);\n          tileRange.minY = Math.max(restrictedTileRange.minY, tileRange.minY);\n          tileRange.maxY = Math.min(restrictedTileRange.maxY, tileRange.maxY);\n        }\n        return tileRange;\n      });\n    } else if (extent) {\n      this.calculateTileRanges_(extent);\n    }\n  }\n\n  /**\n   * Call a function with each tile coordinate for a given extent and zoom level.\n   *\n   * @param {import(\"../extent.js\").Extent} extent Extent.\n   * @param {number} zoom Integer zoom level.\n   * @param {function(import(\"../tilecoord.js\").TileCoord): void} callback Function called with each tile coordinate.\n   * @api\n   */\n  forEachTileCoord(extent, zoom, callback) {\n    const tileRange = this.getTileRangeForExtentAndZ(extent, zoom);\n    for (let i = tileRange.minX, ii = tileRange.maxX; i <= ii; ++i) {\n      for (let j = tileRange.minY, jj = tileRange.maxY; j <= jj; ++j) {\n        callback([zoom, i, j]);\n      }\n    }\n  }\n\n  /**\n   * @param {import(\"../tilecoord.js\").TileCoord} tileCoord Tile coordinate.\n   * @param {function(number, import(\"../TileRange.js\").default): boolean} callback Callback.\n   * @param {import(\"../TileRange.js\").default} [tempTileRange] Temporary import(\"../TileRange.js\").default object.\n   * @param {import(\"../extent.js\").Extent} [tempExtent] Temporary import(\"../extent.js\").Extent object.\n   * @return {boolean} Callback succeeded.\n   */\n  forEachTileCoordParentTileRange(\n    tileCoord,\n    callback,\n    tempTileRange,\n    tempExtent,\n  ) {\n    let tileRange, x, y;\n    let tileCoordExtent = null;\n    let z = tileCoord[0] - 1;\n    if (this.zoomFactor_ === 2) {\n      x = tileCoord[1];\n      y = tileCoord[2];\n    } else {\n      tileCoordExtent = this.getTileCoordExtent(tileCoord, tempExtent);\n    }\n    while (z >= this.minZoom) {\n      if (x !== undefined && y !== undefined) {\n        x = Math.floor(x / 2);\n        y = Math.floor(y / 2);\n        tileRange = createOrUpdateTileRange(x, x, y, y, tempTileRange);\n      } else {\n        tileRange = this.getTileRangeForExtentAndZ(\n          tileCoordExtent,\n          z,\n          tempTileRange,\n        );\n      }\n      if (callback(z, tileRange)) {\n        return true;\n      }\n      --z;\n    }\n    return false;\n  }\n\n  /**\n   * Get the extent for this tile grid, if it was configured.\n   * @return {import(\"../extent.js\").Extent} Extent.\n   * @api\n   */\n  getExtent() {\n    return this.extent_;\n  }\n\n  /**\n   * Get the maximum zoom level for the grid.\n   * @return {number} Max zoom.\n   * @api\n   */\n  getMaxZoom() {\n    return this.maxZoom;\n  }\n\n  /**\n   * Get the minimum zoom level for the grid.\n   * @return {number} Min zoom.\n   * @api\n   */\n  getMinZoom() {\n    return this.minZoom;\n  }\n\n  /**\n   * Get the origin for the grid at the given zoom level.\n   * @param {number} z Integer zoom level.\n   * @return {import(\"../coordinate.js\").Coordinate} Origin.\n   * @api\n   */\n  getOrigin(z) {\n    if (this.origin_) {\n      return this.origin_;\n    }\n    return this.origins_[z];\n  }\n\n  /**\n   * Get the list of origins for the grid.\n   * @return {Array<import(\"../coordinate.js\").Coordinate>|null} Origin.\n   */\n  getOrigins() {\n    return this.origins_;\n  }\n\n  /**\n   * Get the resolution for the given zoom level.\n   * @param {number} z Integer zoom level.\n   * @return {number} Resolution.\n   * @api\n   */\n  getResolution(z) {\n    return this.resolutions_[z];\n  }\n\n  /**\n   * Get the list of resolutions for the tile grid.\n   * @return {Array<number>} Resolutions.\n   * @api\n   */\n  getResolutions() {\n    return this.resolutions_;\n  }\n\n  /**\n   * @param {import(\"../tilecoord.js\").TileCoord} tileCoord Tile coordinate.\n   * @param {import(\"../TileRange.js\").default} [tempTileRange] Temporary import(\"../TileRange.js\").default object.\n   * @param {import(\"../extent.js\").Extent} [tempExtent] Temporary import(\"../extent.js\").Extent object.\n   * @return {import(\"../TileRange.js\").default|null} Tile range.\n   */\n  getTileCoordChildTileRange(tileCoord, tempTileRange, tempExtent) {\n    if (tileCoord[0] < this.maxZoom) {\n      if (this.zoomFactor_ === 2) {\n        const minX = tileCoord[1] * 2;\n        const minY = tileCoord[2] * 2;\n        return createOrUpdateTileRange(\n          minX,\n          minX + 1,\n          minY,\n          minY + 1,\n          tempTileRange,\n        );\n      }\n      const tileCoordExtent = this.getTileCoordExtent(\n        tileCoord,\n        tempExtent || this.tmpExtent_,\n      );\n      return this.getTileRangeForExtentAndZ(\n        tileCoordExtent,\n        tileCoord[0] + 1,\n        tempTileRange,\n      );\n    }\n    return null;\n  }\n\n  /**\n   * @param {import(\"../tilecoord.js\").TileCoord} tileCoord Tile coordinate.\n   * @param {number} z Integer zoom level.\n   * @param {import(\"../TileRange.js\").default} [tempTileRange] Temporary import(\"../TileRange.js\").default object.\n   * @return {import(\"../TileRange.js\").default|null} Tile range.\n   */\n  getTileRangeForTileCoordAndZ(tileCoord, z, tempTileRange) {\n    if (z > this.maxZoom || z < this.minZoom) {\n      return null;\n    }\n\n    const tileCoordZ = tileCoord[0];\n    const tileCoordX = tileCoord[1];\n    const tileCoordY = tileCoord[2];\n\n    if (z === tileCoordZ) {\n      return createOrUpdateTileRange(\n        tileCoordX,\n        tileCoordY,\n        tileCoordX,\n        tileCoordY,\n        tempTileRange,\n      );\n    }\n\n    if (this.zoomFactor_) {\n      const factor = Math.pow(this.zoomFactor_, z - tileCoordZ);\n      const minX = Math.floor(tileCoordX * factor);\n      const minY = Math.floor(tileCoordY * factor);\n      if (z < tileCoordZ) {\n        return createOrUpdateTileRange(minX, minX, minY, minY, tempTileRange);\n      }\n\n      const maxX = Math.floor(factor * (tileCoordX + 1)) - 1;\n      const maxY = Math.floor(factor * (tileCoordY + 1)) - 1;\n      return createOrUpdateTileRange(minX, maxX, minY, maxY, tempTileRange);\n    }\n\n    const tileCoordExtent = this.getTileCoordExtent(tileCoord, this.tmpExtent_);\n    return this.getTileRangeForExtentAndZ(tileCoordExtent, z, tempTileRange);\n  }\n\n  /**\n   * Get a tile range for the given extent and integer zoom level.\n   * @param {import(\"../extent.js\").Extent} extent Extent.\n   * @param {number} z Integer zoom level.\n   * @param {import(\"../TileRange.js\").default} [tempTileRange] Temporary tile range object.\n   * @return {import(\"../TileRange.js\").default} Tile range.\n   */\n  getTileRangeForExtentAndZ(extent, z, tempTileRange) {\n    this.getTileCoordForXYAndZ_(extent[0], extent[3], z, false, tmpTileCoord);\n    const minX = tmpTileCoord[1];\n    const minY = tmpTileCoord[2];\n    this.getTileCoordForXYAndZ_(extent[2], extent[1], z, true, tmpTileCoord);\n    const maxX = tmpTileCoord[1];\n    const maxY = tmpTileCoord[2];\n    return createOrUpdateTileRange(minX, maxX, minY, maxY, tempTileRange);\n  }\n\n  /**\n   * @param {import(\"../tilecoord.js\").TileCoord} tileCoord Tile coordinate.\n   * @return {import(\"../coordinate.js\").Coordinate} Tile center.\n   */\n  getTileCoordCenter(tileCoord) {\n    const origin = this.getOrigin(tileCoord[0]);\n    const resolution = this.getResolution(tileCoord[0]);\n    const tileSize = toSize(this.getTileSize(tileCoord[0]), this.tmpSize_);\n    return [\n      origin[0] + (tileCoord[1] + 0.5) * tileSize[0] * resolution,\n      origin[1] - (tileCoord[2] + 0.5) * tileSize[1] * resolution,\n    ];\n  }\n\n  /**\n   * Get the extent of a tile coordinate.\n   *\n   * @param {import(\"../tilecoord.js\").TileCoord} tileCoord Tile coordinate.\n   * @param {import(\"../extent.js\").Extent} [tempExtent] Temporary extent object.\n   * @return {import(\"../extent.js\").Extent} Extent.\n   * @api\n   */\n  getTileCoordExtent(tileCoord, tempExtent) {\n    const origin = this.getOrigin(tileCoord[0]);\n    const resolution = this.getResolution(tileCoord[0]);\n    const tileSize = toSize(this.getTileSize(tileCoord[0]), this.tmpSize_);\n    const minX = origin[0] + tileCoord[1] * tileSize[0] * resolution;\n    const minY = origin[1] - (tileCoord[2] + 1) * tileSize[1] * resolution;\n    const maxX = minX + tileSize[0] * resolution;\n    const maxY = minY + tileSize[1] * resolution;\n    return createOrUpdate(minX, minY, maxX, maxY, tempExtent);\n  }\n\n  /**\n   * Get the tile coordinate for the given map coordinate and resolution.  This\n   * method considers that coordinates that intersect tile boundaries should be\n   * assigned the higher tile coordinate.\n   *\n   * @param {import(\"../coordinate.js\").Coordinate} coordinate Coordinate.\n   * @param {number} resolution Resolution.\n   * @param {import(\"../tilecoord.js\").TileCoord} [opt_tileCoord] Destination import(\"../tilecoord.js\").TileCoord object.\n   * @return {import(\"../tilecoord.js\").TileCoord} Tile coordinate.\n   * @api\n   */\n  getTileCoordForCoordAndResolution(coordinate, resolution, opt_tileCoord) {\n    return this.getTileCoordForXYAndResolution_(\n      coordinate[0],\n      coordinate[1],\n      resolution,\n      false,\n      opt_tileCoord,\n    );\n  }\n\n  /**\n   * Note that this method should not be called for resolutions that correspond\n   * to an integer zoom level.  Instead call the `getTileCoordForXYAndZ_` method.\n   * @param {number} x X.\n   * @param {number} y Y.\n   * @param {number} resolution Resolution (for a non-integer zoom level).\n   * @param {boolean} reverseIntersectionPolicy Instead of letting edge\n   *     intersections go to the higher tile coordinate, let edge intersections\n   *     go to the lower tile coordinate.\n   * @param {import(\"../tilecoord.js\").TileCoord} [opt_tileCoord] Temporary import(\"../tilecoord.js\").TileCoord object.\n   * @return {import(\"../tilecoord.js\").TileCoord} Tile coordinate.\n   * @private\n   */\n  getTileCoordForXYAndResolution_(\n    x,\n    y,\n    resolution,\n    reverseIntersectionPolicy,\n    opt_tileCoord,\n  ) {\n    const z = this.getZForResolution(resolution);\n    const scale = resolution / this.getResolution(z);\n    const origin = this.getOrigin(z);\n    const tileSize = toSize(this.getTileSize(z), this.tmpSize_);\n\n    let tileCoordX = (scale * (x - origin[0])) / resolution / tileSize[0];\n    let tileCoordY = (scale * (origin[1] - y)) / resolution / tileSize[1];\n\n    if (reverseIntersectionPolicy) {\n      tileCoordX = ceil(tileCoordX, DECIMALS) - 1;\n      tileCoordY = ceil(tileCoordY, DECIMALS) - 1;\n    } else {\n      tileCoordX = floor(tileCoordX, DECIMALS);\n      tileCoordY = floor(tileCoordY, DECIMALS);\n    }\n\n    return createOrUpdateTileCoord(z, tileCoordX, tileCoordY, opt_tileCoord);\n  }\n\n  /**\n   * Although there is repetition between this method and `getTileCoordForXYAndResolution_`,\n   * they should have separate implementations.  This method is for integer zoom\n   * levels.  The other method should only be called for resolutions corresponding\n   * to non-integer zoom levels.\n   * @param {number} x Map x coordinate.\n   * @param {number} y Map y coordinate.\n   * @param {number} z Integer zoom level.\n   * @param {boolean} reverseIntersectionPolicy Instead of letting edge\n   *     intersections go to the higher tile coordinate, let edge intersections\n   *     go to the lower tile coordinate.\n   * @param {import(\"../tilecoord.js\").TileCoord} [opt_tileCoord] Temporary import(\"../tilecoord.js\").TileCoord object.\n   * @return {import(\"../tilecoord.js\").TileCoord} Tile coordinate.\n   * @private\n   */\n  getTileCoordForXYAndZ_(x, y, z, reverseIntersectionPolicy, opt_tileCoord) {\n    const origin = this.getOrigin(z);\n    const resolution = this.getResolution(z);\n    const tileSize = toSize(this.getTileSize(z), this.tmpSize_);\n\n    let tileCoordX = (x - origin[0]) / resolution / tileSize[0];\n    let tileCoordY = (origin[1] - y) / resolution / tileSize[1];\n\n    if (reverseIntersectionPolicy) {\n      tileCoordX = ceil(tileCoordX, DECIMALS) - 1;\n      tileCoordY = ceil(tileCoordY, DECIMALS) - 1;\n    } else {\n      tileCoordX = floor(tileCoordX, DECIMALS);\n      tileCoordY = floor(tileCoordY, DECIMALS);\n    }\n\n    return createOrUpdateTileCoord(z, tileCoordX, tileCoordY, opt_tileCoord);\n  }\n\n  /**\n   * Get a tile coordinate given a map coordinate and zoom level.\n   * @param {import(\"../coordinate.js\").Coordinate} coordinate Coordinate.\n   * @param {number} z Integer zoom level, e.g. the result of a `getZForResolution()` method call\n   * @param {import(\"../tilecoord.js\").TileCoord} [opt_tileCoord] Destination import(\"../tilecoord.js\").TileCoord object.\n   * @return {import(\"../tilecoord.js\").TileCoord} Tile coordinate.\n   * @api\n   */\n  getTileCoordForCoordAndZ(coordinate, z, opt_tileCoord) {\n    return this.getTileCoordForXYAndZ_(\n      coordinate[0],\n      coordinate[1],\n      z,\n      false,\n      opt_tileCoord,\n    );\n  }\n\n  /**\n   * @param {import(\"../tilecoord.js\").TileCoord} tileCoord Tile coordinate.\n   * @return {number} Tile resolution.\n   */\n  getTileCoordResolution(tileCoord) {\n    return this.resolutions_[tileCoord[0]];\n  }\n\n  /**\n   * Get the tile size for a zoom level. The type of the return value matches the\n   * `tileSize` or `tileSizes` that the tile grid was configured with. To always\n   * get an {@link import(\"../size.js\").Size}, run the result through {@link module:ol/size.toSize}.\n   * @param {number} z Z.\n   * @return {number|import(\"../size.js\").Size} Tile size.\n   * @api\n   */\n  getTileSize(z) {\n    if (this.tileSize_) {\n      return this.tileSize_;\n    }\n    return this.tileSizes_[z];\n  }\n\n  /**\n   * @param {number} z Zoom level.\n   * @return {import(\"../TileRange.js\").default|null} Extent tile range for the specified zoom level.\n   */\n  getFullTileRange(z) {\n    if (!this.fullTileRanges_) {\n      return this.extent_\n        ? this.getTileRangeForExtentAndZ(this.extent_, z)\n        : null;\n    }\n    return this.fullTileRanges_[z];\n  }\n\n  /**\n   * @param {number} resolution Resolution.\n   * @param {number|import(\"../array.js\").NearestDirectionFunction} [opt_direction]\n   *     If 0, the nearest resolution will be used.\n   *     If 1, the nearest higher resolution (lower Z) will be used. If -1, the\n   *     nearest lower resolution (higher Z) will be used. Default is 0.\n   *     Use a {@link module:ol/array~NearestDirectionFunction} for more precise control.\n   *\n   * For example to change tile Z at the midpoint of zoom levels\n   * ```js\n   * function(value, high, low) {\n   *   return value - low * Math.sqrt(high / low);\n   * }\n   * ```\n   * @return {number} Z.\n   * @api\n   */\n  getZForResolution(resolution, opt_direction) {\n    const z = linearFindNearest(\n      this.resolutions_,\n      resolution,\n      opt_direction || 0,\n    );\n    return clamp(z, this.minZoom, this.maxZoom);\n  }\n\n  /**\n   * The tile with the provided tile coordinate intersects the given viewport.\n   * @param {import('../tilecoord.js').TileCoord} tileCoord Tile coordinate.\n   * @param {Array<number>} viewport Viewport as returned from {@link module:ol/extent.getRotatedViewport}.\n   * @return {boolean} The tile with the provided tile coordinate intersects the given viewport.\n   */\n  tileCoordIntersectsViewport(tileCoord, viewport) {\n    return intersectsLinearRing(\n      viewport,\n      0,\n      viewport.length,\n      2,\n      this.getTileCoordExtent(tileCoord),\n    );\n  }\n\n  /**\n   * @param {!import(\"../extent.js\").Extent} extent Extent for this tile grid.\n   * @private\n   */\n  calculateTileRanges_(extent) {\n    const length = this.resolutions_.length;\n    const fullTileRanges = new Array(length);\n    for (let z = this.minZoom; z < length; ++z) {\n      fullTileRanges[z] = this.getTileRangeForExtentAndZ(extent, z);\n    }\n    this.fullTileRanges_ = fullTileRanges;\n  }\n}\n\nexport default TileGrid;\n", "/**\n * @module ol/tilegrid/WMTS\n */\n\nimport {get as getProjection} from '../proj.js';\nimport TileGrid from './TileGrid.js';\n\n/**\n * @typedef {Object} Options\n * @property {import(\"../extent.js\").Extent} [extent] Extent for the tile grid. No tiles\n * outside this extent will be requested by {@link module:ol/source/Tile~TileSource} sources.\n * When no `origin` or `origins` are configured, the `origin` will be set to the\n * top-left corner of the extent.\n * @property {import(\"../coordinate.js\").Coordinate} [origin] The tile grid origin, i.e.\n * where the `x` and `y` axes meet (`[z, 0, 0]`). Tile coordinates increase left\n * to right and downwards. If not specified, `extent` or `origins` must be provided.\n * @property {Array<import(\"../coordinate.js\").Coordinate>} [origins] Tile grid origins,\n * i.e. where the `x` and `y` axes meet (`[z, 0, 0]`), for each zoom level. If\n * given, the array length should match the length of the `resolutions` array, i.e.\n * each resolution can have a different origin. Tile coordinates increase left to\n * right and downwards. If not specified, `extent` or `origin` must be provided.\n * @property {!Array<number>} resolutions Resolutions. The array index of each\n * resolution needs to match the zoom level. This means that even if a `minZoom`\n * is configured, the resolutions array will have a length of `maxZoom + 1`\n * @property {!Array<string>} matrixIds matrix IDs. The length of this array needs\n * to match the length of the `resolutions` array.\n * @property {Array<import(\"../size.js\").Size>} [sizes] Number of tile rows and columns\n * of the grid for each zoom level. The values here are the `TileMatrixWidth` and\n * `TileMatrixHeight` advertised in the GetCapabilities response of the WMTS, and\n * define each zoom level's extent together with the `origin` or `origins`.\n * A grid `extent` can be configured in addition, and will further limit the extent for\n * which tile requests are made by sources. If the bottom-left corner of\n * an extent is used as `origin` or `origins`, then the `y` value must be\n * negative because OpenLayers tile coordinates use the top left as the origin.\n * @property {number|import(\"../size.js\").Size} [tileSize] Tile size.\n * @property {Array<number|import(\"../size.js\").Size>} [tileSizes] Tile sizes. The length of\n * this array needs to match the length of the `resolutions` array.\n */\n\n/**\n * @classdesc\n * Set the grid pattern for sources accessing WMTS tiled-image servers.\n * @api\n */\nclass WMTSTileGrid extends TileGrid {\n  /**\n   * @param {Options} options WMTS options.\n   */\n  constructor(options) {\n    super({\n      extent: options.extent,\n      origin: options.origin,\n      origins: options.origins,\n      resolutions: options.resolutions,\n      tileSize: options.tileSize,\n      tileSizes: options.tileSizes,\n      sizes: options.sizes,\n    });\n\n    /**\n     * @private\n     * @type {!Array<string>}\n     */\n    this.matrixIds_ = options.matrixIds;\n  }\n\n  /**\n   * @param {number} z Z.\n   * @return {string} MatrixId..\n   */\n  getMatrixId(z) {\n    return this.matrixIds_[z];\n  }\n\n  /**\n   * Get the list of matrix identifiers.\n   * @return {Array<string>} MatrixIds.\n   * @api\n   */\n  getMatrixIds() {\n    return this.matrixIds_;\n  }\n}\n\nexport default WMTSTileGrid;\n\n/**\n * Create a tile grid from a WMTS capabilities matrix set and an\n * optional TileMatrixSetLimits.\n * @param {Object} matrixSet An object representing a matrixSet in the\n *     capabilities document.\n * @param {import(\"../extent.js\").Extent} [extent] An optional extent to restrict the tile\n *     ranges the server provides.\n * @param {Array<Object>} [matrixLimits] An optional object representing\n *     the available matrices for tileGrid.\n * @return {WMTSTileGrid} WMTS tileGrid instance.\n * @api\n */\nexport function createFromCapabilitiesMatrixSet(\n  matrixSet,\n  extent,\n  matrixLimits,\n) {\n  /** @type {!Array<number>} */\n  const resolutions = [];\n  /** @type {!Array<string>} */\n  const matrixIds = [];\n  /** @type {!Array<import(\"../coordinate.js\").Coordinate>} */\n  const origins = [];\n  /** @type {!Array<number|import(\"../size.js\").Size>} */\n  const tileSizes = [];\n  /** @type {!Array<import(\"../size.js\").Size>} */\n  const sizes = [];\n\n  matrixLimits = matrixLimits !== undefined ? matrixLimits : [];\n\n  const supportedCRSPropName = 'SupportedCRS';\n  const matrixIdsPropName = 'TileMatrix';\n  const identifierPropName = 'Identifier';\n  const scaleDenominatorPropName = 'ScaleDenominator';\n  const topLeftCornerPropName = 'TopLeftCorner';\n  const tileWidthPropName = 'TileWidth';\n  const tileHeightPropName = 'TileHeight';\n\n  const code = matrixSet[supportedCRSPropName];\n  const projection = getProjection(code);\n  const metersPerUnit = projection.getMetersPerUnit();\n  // swap origin x and y coordinates if axis orientation is lat/long\n  const switchOriginXY = projection.getAxisOrientation().startsWith('ne');\n\n  matrixSet[matrixIdsPropName].sort(function (a, b) {\n    return b[scaleDenominatorPropName] - a[scaleDenominatorPropName];\n  });\n\n  matrixSet[matrixIdsPropName].forEach(function (elt) {\n    let matrixAvailable;\n    // use of matrixLimits to filter TileMatrices from GetCapabilities\n    // TileMatrixSet from unavailable matrix levels.\n    if (matrixLimits.length > 0) {\n      matrixAvailable = matrixLimits.find(function (elt_ml) {\n        if (elt[identifierPropName] == elt_ml[matrixIdsPropName]) {\n          return true;\n        }\n        // Fallback for tileMatrix identifiers that don't get prefixed\n        // by their tileMatrixSet identifiers.\n        if (!elt[identifierPropName].includes(':')) {\n          return (\n            matrixSet[identifierPropName] + ':' + elt[identifierPropName] ===\n            elt_ml[matrixIdsPropName]\n          );\n        }\n        return false;\n      });\n    } else {\n      matrixAvailable = true;\n    }\n\n    if (matrixAvailable) {\n      matrixIds.push(elt[identifierPropName]);\n      const resolution =\n        (elt[scaleDenominatorPropName] * 0.28e-3) / metersPerUnit;\n      const tileWidth = elt[tileWidthPropName];\n      const tileHeight = elt[tileHeightPropName];\n      if (switchOriginXY) {\n        origins.push([\n          elt[topLeftCornerPropName][1],\n          elt[topLeftCornerPropName][0],\n        ]);\n      } else {\n        origins.push(elt[topLeftCornerPropName]);\n      }\n      resolutions.push(resolution);\n      tileSizes.push(\n        tileWidth == tileHeight ? tileWidth : [tileWidth, tileHeight],\n      );\n      sizes.push([elt['MatrixWidth'], elt['MatrixHeight']]);\n    }\n  });\n\n  return new WMTSTileGrid({\n    extent: extent,\n    origins: origins,\n    resolutions: resolutions,\n    matrixIds: matrixIds,\n    tileSizes: tileSizes,\n    sizes: sizes,\n  });\n}\n", "/**\n * @module ol/tilegrid\n */\nimport {\n  containsCoordinate,\n  createOrUpdate,\n  getCorner,\n  getHeight,\n  getWidth,\n} from './extent.js';\nimport {METERS_PER_UNIT, get as getProjection} from './proj.js';\nimport {toSize} from './size.js';\nimport TileGrid from './tilegrid/TileGrid.js';\nimport {DEFAULT_MAX_ZOOM, DEFAULT_TILE_SIZE} from './tilegrid/common.js';\n\nexport {default as WMTS} from './tilegrid/WMTS.js';\nexport {TileGrid};\n\n/**\n * @param {import(\"./proj/Projection.js\").default} projection Projection.\n * @return {!TileGrid} Default tile grid for the\n * passed projection.\n */\nexport function getForProjection(projection) {\n  let tileGrid = projection.getDefaultTileGrid();\n  if (!tileGrid) {\n    tileGrid = createForProjection(projection);\n    projection.setDefaultTileGrid(tileGrid);\n  }\n  return tileGrid;\n}\n\n/**\n * @param {TileGrid} tileGrid Tile grid.\n * @param {import(\"./tilecoord.js\").TileCoord} tileCoord Tile coordinate.\n * @param {import(\"./proj/Projection.js\").default} projection Projection.\n * @return {import(\"./tilecoord.js\").TileCoord} Tile coordinate.\n */\nexport function wrapX(tileGrid, tileCoord, projection) {\n  const z = tileCoord[0];\n  const center = tileGrid.getTileCoordCenter(tileCoord);\n  const projectionExtent = extentFromProjection(projection);\n  if (!containsCoordinate(projectionExtent, center)) {\n    const worldWidth = getWidth(projectionExtent);\n    const worldsAway = Math.ceil(\n      (projectionExtent[0] - center[0]) / worldWidth,\n    );\n    center[0] += worldWidth * worldsAway;\n    return tileGrid.getTileCoordForCoordAndZ(center, z);\n  }\n  return tileCoord;\n}\n\n/**\n * @param {import(\"./extent.js\").Extent} extent Extent.\n * @param {number} [maxZoom] Maximum zoom level (default is\n *     DEFAULT_MAX_ZOOM).\n * @param {number|import(\"./size.js\").Size} [tileSize] Tile size (default uses\n *     DEFAULT_TILE_SIZE).\n * @param {import(\"./extent.js\").Corner} [corner] Extent corner (default is `'top-left'`).\n * @return {!TileGrid} TileGrid instance.\n */\nexport function createForExtent(extent, maxZoom, tileSize, corner) {\n  corner = corner !== undefined ? corner : 'top-left';\n\n  const resolutions = resolutionsFromExtent(extent, maxZoom, tileSize);\n\n  return new TileGrid({\n    extent: extent,\n    origin: getCorner(extent, corner),\n    resolutions: resolutions,\n    tileSize: tileSize,\n  });\n}\n\n/**\n * @typedef {Object} XYZOptions\n * @property {import(\"./extent.js\").Extent} [extent] Extent for the tile grid. The origin for an XYZ tile grid is the\n * top-left corner of the extent. If `maxResolution` is not provided the zero level of the grid is defined by the resolution\n * at which one tile fits in the provided extent. If not provided, the extent of the EPSG:3857 projection is used.\n * @property {number} [maxResolution] Resolution at level zero.\n * @property {number} [maxZoom] Maximum zoom. The default is `42`. This determines the number of levels\n * in the grid set. For example, a `maxZoom` of 21 means there are 22 levels in the grid set.\n * @property {number} [minZoom=0] Minimum zoom.\n * @property {number|import(\"./size.js\").Size} [tileSize=[256, 256]] Tile size in pixels.\n */\n\n/**\n * Creates a tile grid with a standard XYZ tiling scheme.\n * @param {XYZOptions} [options] Tile grid options.\n * @return {!TileGrid} Tile grid instance.\n * @api\n */\nexport function createXYZ(options) {\n  const xyzOptions = options || {};\n\n  const extent = xyzOptions.extent || getProjection('EPSG:3857').getExtent();\n\n  const gridOptions = {\n    extent: extent,\n    minZoom: xyzOptions.minZoom,\n    tileSize: xyzOptions.tileSize,\n    resolutions: resolutionsFromExtent(\n      extent,\n      xyzOptions.maxZoom,\n      xyzOptions.tileSize,\n      xyzOptions.maxResolution,\n    ),\n  };\n  return new TileGrid(gridOptions);\n}\n\n/**\n * Create a resolutions array from an extent.  A zoom factor of 2 is assumed.\n * @param {import(\"./extent.js\").Extent} extent Extent.\n * @param {number} [maxZoom] Maximum zoom level (default is\n *     DEFAULT_MAX_ZOOM).\n * @param {number|import(\"./size.js\").Size} [tileSize] Tile size (default uses\n *     DEFAULT_TILE_SIZE).\n * @param {number} [maxResolution] Resolution at level zero.\n * @return {!Array<number>} Resolutions array.\n */\nfunction resolutionsFromExtent(extent, maxZoom, tileSize, maxResolution) {\n  maxZoom = maxZoom !== undefined ? maxZoom : DEFAULT_MAX_ZOOM;\n  tileSize = toSize(tileSize !== undefined ? tileSize : DEFAULT_TILE_SIZE);\n\n  const height = getHeight(extent);\n  const width = getWidth(extent);\n\n  maxResolution =\n    maxResolution > 0\n      ? maxResolution\n      : Math.max(width / tileSize[0], height / tileSize[1]);\n\n  const length = maxZoom + 1;\n  const resolutions = new Array(length);\n  for (let z = 0; z < length; ++z) {\n    resolutions[z] = maxResolution / Math.pow(2, z);\n  }\n  return resolutions;\n}\n\n/**\n * @param {import(\"./proj.js\").ProjectionLike} projection Projection.\n * @param {number} [maxZoom] Maximum zoom level (default is\n *     DEFAULT_MAX_ZOOM).\n * @param {number|import(\"./size.js\").Size} [tileSize] Tile size (default uses\n *     DEFAULT_TILE_SIZE).\n * @param {import(\"./extent.js\").Corner} [corner] Extent corner (default is `'top-left'`).\n * @return {!TileGrid} TileGrid instance.\n */\nexport function createForProjection(projection, maxZoom, tileSize, corner) {\n  const extent = extentFromProjection(projection);\n  return createForExtent(extent, maxZoom, tileSize, corner);\n}\n\n/**\n * Generate a tile grid extent from a projection.  If the projection has an\n * extent, it is used.  If not, a global extent is assumed.\n * @param {import(\"./proj.js\").ProjectionLike} projection Projection.\n * @return {import(\"./extent.js\").Extent} Extent.\n */\nexport function extentFromProjection(projection) {\n  projection = getProjection(projection);\n  let extent = projection.getExtent();\n  if (!extent) {\n    const half =\n      (180 * METERS_PER_UNIT.degrees) / projection.getMetersPerUnit();\n    extent = createOrUpdate(-half, -half, half, half);\n  }\n  return extent;\n}\n", "/**\n * @module ol/uri\n */\n\nimport {modulo} from './math.js';\nimport {hashZXY} from './tilecoord.js';\n\n/**\n * Appends query parameters to a URI.\n *\n * @param {string} uri The original URI, which may already have query data.\n * @param {!Object} params An object where keys are URI-encoded parameter keys,\n *     and the values are arbitrary types or arrays.\n * @return {string} The new URI.\n */\nexport function appendParams(uri, params) {\n  /** @type {Array<string>} */\n  const keyParams = [];\n  // Skip any null or undefined parameter values\n  Object.keys(params).forEach(function (k) {\n    if (params[k] !== null && params[k] !== undefined) {\n      keyParams.push(k + '=' + encodeURIComponent(params[k]));\n    }\n  });\n  const qs = keyParams.join('&');\n  // remove any trailing ? or &\n  uri = uri.replace(/[?&]$/, '');\n  // append ? or & depending on whether uri has existing parameters\n  uri += uri.includes('?') ? '&' : '?';\n  return uri + qs;\n}\n\nconst zRegEx = /\\{z\\}/g;\nconst xRegEx = /\\{x\\}/g;\nconst yRegEx = /\\{y\\}/g;\nconst dashYRegEx = /\\{-y\\}/g;\n\n/**\n * @param {string} template The URL template.  Should have `{x}`, `{y}`, and `{z}` placeholders.  If\n * the template has a `{-y}` placeholder, the `maxY` parameter must be supplied.\n * @param {number} z The tile z coordinate.\n * @param {number} x The tile x coordinate.\n * @param {number} y The tile y coordinate.\n * @param {number} [maxY] The maximum y coordinate at the given z level.\n * @return {string} The URL.\n */\nexport function renderXYZTemplate(template, z, x, y, maxY) {\n  return template\n    .replace(zRegEx, z.toString())\n    .replace(xRegEx, x.toString())\n    .replace(yRegEx, y.toString())\n    .replace(dashYRegEx, function () {\n      if (maxY === undefined) {\n        throw new Error(\n          'If the URL template has a {-y} placeholder, the grid extent must be known',\n        );\n      }\n      return (maxY - y).toString();\n    });\n}\n\n/**\n * @param {Array<string>} urls List of URLs.\n * @param {number} z The tile z coordinate.\n * @param {number} x The tile x coordinate.\n * @param {number} y The tile y coordinate.\n * @return {string} The chosen URL.\n */\nexport function pickUrl(urls, z, x, y) {\n  const hash = hashZXY(z, x, y);\n  const index = modulo(hash, urls.length);\n  return urls[index];\n}\n\n/**\n * @param {string} url URL.\n * @return {Array<string>} Array of urls.\n */\nexport function expandUrl(url) {\n  const urls = [];\n  let match = /\\{([a-z])-([a-z])\\}/.exec(url);\n  if (match) {\n    // char range\n    const startCharCode = match[1].charCodeAt(0);\n    const stopCharCode = match[2].charCodeAt(0);\n    let charCode;\n    for (charCode = startCharCode; charCode <= stopCharCode; ++charCode) {\n      urls.push(url.replace(match[0], String.fromCharCode(charCode)));\n    }\n    return urls;\n  }\n  match = /\\{(\\d+)-(\\d+)\\}/.exec(url);\n  if (match) {\n    // number range\n    const stop = parseInt(match[2], 10);\n    for (let i = parseInt(match[1], 10); i <= stop; i++) {\n      urls.push(url.replace(match[0], i.toString()));\n    }\n    return urls;\n  }\n  urls.push(url);\n  return urls;\n}\n", "/**\n * @module ol/tileurlfunction\n */\nimport {modulo} from './math.js';\nimport {hash as tileCoordHash} from './tilecoord.js';\nimport {renderXYZTemplate} from './uri.js';\n\n/**\n * @param {string} template Template.\n * @param {import(\"./tilegrid/TileGrid.js\").default|null} tileGrid Tile grid.\n * @return {import(\"./Tile.js\").UrlFunction} Tile URL function.\n */\nexport function createFromTemplate(template, tileGrid) {\n  return (\n    /**\n     * @param {import(\"./tilecoord.js\").TileCoord} tileCoord Tile Coordinate.\n     * @param {number} pixelRatio Pixel ratio.\n     * @param {import(\"./proj/Projection.js\").default} projection Projection.\n     * @return {string|undefined} Tile URL.\n     */\n    function (tileCoord, pixelRatio, projection) {\n      if (!tileCoord) {\n        return undefined;\n      }\n      let maxY;\n      const z = tileCoord[0];\n      if (tileGrid) {\n        // The `{-y}` placeholder only works for sources that have a tile grid at construction\n        const range = tileGrid.getFullTileRange(z);\n        if (range) {\n          maxY = range.getHeight() - 1;\n        }\n      }\n      return renderXYZTemplate(template, z, tileCoord[1], tileCoord[2], maxY);\n    }\n  );\n}\n\n/**\n * @param {Array<string>} templates Templates.\n * @param {import(\"./tilegrid/TileGrid.js\").default} tileGrid Tile grid.\n * @return {import(\"./Tile.js\").UrlFunction} Tile URL function.\n */\nexport function createFromTemplates(templates, tileGrid) {\n  const len = templates.length;\n  const tileUrlFunctions = new Array(len);\n  for (let i = 0; i < len; ++i) {\n    tileUrlFunctions[i] = createFromTemplate(templates[i], tileGrid);\n  }\n  return createFromTileUrlFunctions(tileUrlFunctions);\n}\n\n/**\n * @param {Array<import(\"./Tile.js\").UrlFunction>} tileUrlFunctions Tile URL Functions.\n * @return {import(\"./Tile.js\").UrlFunction} Tile URL function.\n */\nexport function createFromTileUrlFunctions(tileUrlFunctions) {\n  if (tileUrlFunctions.length === 1) {\n    return tileUrlFunctions[0];\n  }\n  return (\n    /**\n     * @param {import(\"./tilecoord.js\").TileCoord} tileCoord Tile Coordinate.\n     * @param {number} pixelRatio Pixel ratio.\n     * @param {import(\"./proj/Projection.js\").default} projection Projection.\n     * @return {string|undefined} Tile URL.\n     */\n    function (tileCoord, pixelRatio, projection) {\n      if (!tileCoord) {\n        return undefined;\n      }\n      const h = tileCoordHash(tileCoord);\n      const index = modulo(h, tileUrlFunctions.length);\n      return tileUrlFunctions[index](tileCoord, pixelRatio, projection);\n    }\n  );\n}\n\n/**\n * @param {import(\"./tilecoord.js\").TileCoord} tileCoord Tile coordinate.\n * @param {number} pixelRatio Pixel ratio.\n * @param {import(\"./proj/Projection.js\").default} projection Projection.\n * @return {string|undefined} Tile URL.\n */\nexport function nullTileUrlFunction(tileCoord, pixelRatio, projection) {\n  return undefined;\n}\n", "/**\n * @module ol/source/Source\n */\nimport BaseObject from '../Object.js';\nimport {get as getProjection} from '../proj.js';\n\n/**\n * @typedef {'undefined' | 'loading' | 'ready' | 'error'} State\n * State of the source, one of 'undefined', 'loading', 'ready' or 'error'.\n */\n\n/**\n * A function that takes a {@link import(\"../View.js\").ViewStateLayerStateExtent} and returns a string or\n * an array of strings representing source attributions.\n *\n * @typedef {function(import(\"../View.js\").ViewStateLayerStateExtent): (string|Array<string>)} Attribution\n */\n\n/**\n * A type that can be used to provide attribution information for data sources.\n *\n * It represents either\n * a simple string (e.g. `'\u00A9 Acme Inc.'`)\n * an array of simple strings (e.g. `['\u00A9 Acme Inc.', '\u00A9 Bacme Inc.']`)\n * a function that returns a string or array of strings ({@link module:ol/source/Source~Attribution})\n *\n * @typedef {string|Array<string>|Attribution} AttributionLike\n */\n\n/**\n * @typedef {Object} Options\n * @property {AttributionLike} [attributions] Attributions.\n * @property {boolean} [attributionsCollapsible=true] Attributions are collapsible.\n * @property {import(\"../proj.js\").ProjectionLike} [projection] Projection. Default is the view projection.\n * @property {import(\"./Source.js\").State} [state='ready'] State.\n * @property {boolean} [wrapX=false] WrapX.\n * @property {boolean} [interpolate=false] Use interpolated values when resampling.  By default,\n * the nearest neighbor is used when resampling.\n */\n\n/**\n * @classdesc\n * Abstract base class; normally only used for creating subclasses and not\n * instantiated in apps.\n * Base class for {@link module:ol/layer/Layer~Layer} sources.\n *\n * A generic `change` event is triggered when the state of the source changes.\n * @abstract\n * @api\n */\nclass Source extends BaseObject {\n  /**\n   * @param {Options} options Source options.\n   */\n  constructor(options) {\n    super();\n\n    /**\n     * @protected\n     * @type {import(\"../proj/Projection.js\").default|null}\n     */\n    this.projection = getProjection(options.projection);\n\n    /**\n     * @private\n     * @type {?Attribution}\n     */\n    this.attributions_ = adaptAttributions(options.attributions);\n\n    /**\n     * @private\n     * @type {boolean}\n     */\n    this.attributionsCollapsible_ = options.attributionsCollapsible ?? true;\n\n    /**\n     * This source is currently loading data. Sources that defer loading to the\n     * map's tile queue never set this to a `truthy` value.\n     * @type {boolean|number}\n     */\n    this.loading = false;\n\n    /**\n     * @private\n     * @type {import(\"./Source.js\").State}\n     */\n    this.state_ = options.state !== undefined ? options.state : 'ready';\n\n    /**\n     * @private\n     * @type {boolean}\n     */\n    this.wrapX_ = options.wrapX !== undefined ? options.wrapX : false;\n\n    /**\n     * @private\n     * @type {boolean}\n     */\n    this.interpolate_ = !!options.interpolate;\n\n    /**\n     * @protected\n     * @type {function(import(\"../View.js\").ViewOptions):void}\n     */\n    this.viewResolver = null;\n\n    /**\n     * @protected\n     * @type {function(Error):void}\n     */\n    this.viewRejector = null;\n\n    const self = this;\n    /**\n     * @private\n     * @type {Promise<import(\"../View.js\").ViewOptions>}\n     */\n    this.viewPromise_ = new Promise(function (resolve, reject) {\n      self.viewResolver = resolve;\n      self.viewRejector = reject;\n    });\n  }\n\n  /**\n   * Get the attribution function for the source.\n   * @return {?Attribution} Attribution function.\n   * @api\n   */\n  getAttributions() {\n    return this.attributions_;\n  }\n\n  /**\n   * @return {boolean} Attributions are collapsible.\n   * @api\n   */\n  getAttributionsCollapsible() {\n    return this.attributionsCollapsible_;\n  }\n\n  /**\n   * Get the projection of the source.\n   * @return {import(\"../proj/Projection.js\").default|null} Projection.\n   * @api\n   */\n  getProjection() {\n    return this.projection;\n  }\n\n  /**\n   * @param {import(\"../proj/Projection.js\").default} [projection] Projection.\n   * @return {Array<number>|null} Resolutions.\n   */\n  getResolutions(projection) {\n    return null;\n  }\n\n  /**\n   * @return {Promise<import(\"../View.js\").ViewOptions>} A promise for view-related properties.\n   */\n  getView() {\n    return this.viewPromise_;\n  }\n\n  /**\n   * Get the state of the source, see {@link import(\"./Source.js\").State} for possible states.\n   * @return {import(\"./Source.js\").State} State.\n   * @api\n   */\n  getState() {\n    return this.state_;\n  }\n\n  /**\n   * @return {boolean|undefined} Wrap X.\n   */\n  getWrapX() {\n    return this.wrapX_;\n  }\n\n  /**\n   * @return {boolean} Use linear interpolation when resampling.\n   */\n  getInterpolate() {\n    return this.interpolate_;\n  }\n\n  /**\n   * Refreshes the source. The source will be cleared, and data from the server will be reloaded.\n   * @api\n   */\n  refresh() {\n    this.changed();\n  }\n\n  /**\n   * Set the attributions of the source.\n   * @param {AttributionLike|undefined} attributions Attributions.\n   *     Can be passed as `string`, `Array<string>`, {@link module:ol/source/Source~Attribution},\n   *     or `undefined`.\n   * @api\n   */\n  setAttributions(attributions) {\n    this.attributions_ = adaptAttributions(attributions);\n    this.changed();\n  }\n\n  /**\n   * Set the state of the source.\n   * @param {import(\"./Source.js\").State} state State.\n   */\n  setState(state) {\n    this.state_ = state;\n    this.changed();\n  }\n}\n\n/**\n * Turns the attributions option into an attributions function.\n * @param {AttributionLike|undefined} attributionLike The attribution option.\n * @return {Attribution|null} An attribution function (or null).\n */\nfunction adaptAttributions(attributionLike) {\n  if (!attributionLike) {\n    return null;\n  }\n  if (typeof attributionLike === 'function') {\n    return attributionLike;\n  }\n  if (!Array.isArray(attributionLike)) {\n    attributionLike = [attributionLike];\n  }\n  return (frameState) => attributionLike;\n}\n\nexport default Source;\n", "/**\n * @module ol/source/Tile\n */\nimport Event from '../events/Event.js';\nimport {scale as scaleSize, toSize} from '../size.js';\nimport {withinExtentAndZ} from '../tilecoord.js';\nimport {\n  getForProjection as getTileGridForProjection,\n  wrapX,\n} from '../tilegrid.js';\nimport {abstract, getUid} from '../util.js';\nimport Source from './Source.js';\n\n/***\n * @template Return\n * @typedef {import(\"../Observable.js\").OnSignature<import(\"../Observable.js\").EventTypes, import(\"../events/Event.js\").default, Return> &\n *   import(\"../Observable.js\").OnSignature<import(\"../ObjectEventType.js\").Types, import(\"../Object.js\").ObjectEvent, Return> &\n *   import(\"../Observable.js\").OnSignature<import(\"./TileEventType.js\").TileSourceEventTypes, TileSourceEvent, Return> &\n *   import(\"../Observable.js\").CombinedOnSignature<import(\"../Observable.js\").EventTypes|import(\"../ObjectEventType.js\").Types|\n *     import(\"./TileEventType.js\").TileSourceEventTypes, Return>} TileSourceOnSignature\n */\n\n/**\n * @typedef {Object} Options\n * @property {import(\"./Source.js\").AttributionLike} [attributions] Attributions.\n * @property {boolean} [attributionsCollapsible=true] Attributions are collapsible.\n * @property {number} [cacheSize] Deprecated.  Use the cacheSize option on the layer instead.\n * @property {number} [tilePixelRatio] TilePixelRatio.\n * @property {import(\"../proj.js\").ProjectionLike} [projection] Projection.\n * @property {import(\"./Source.js\").State} [state] State.\n * @property {import(\"../tilegrid/TileGrid.js\").default} [tileGrid] TileGrid.\n * @property {boolean} [wrapX=false] WrapX.\n * @property {number} [transition] Transition.\n * @property {string} [key] Key.\n * @property {number|import(\"../array.js\").NearestDirectionFunction} [zDirection=0] ZDirection.\n * @property {boolean} [interpolate=false] Use interpolated values when resampling.  By default,\n * the nearest neighbor is used when resampling.\n */\n\n/**\n * @classdesc\n * Abstract base class; normally only used for creating subclasses and not\n * instantiated in apps.\n * Base class for sources providing images divided into a tile grid.\n *\n * @template {import(\"../Tile.js\").default} [TileType=import(\"../Tile.js\").default]\n * @abstract\n * @api\n */\nclass TileSource extends Source {\n  /**\n   * @param {Options} options SourceTile source options.\n   */\n  constructor(options) {\n    super({\n      attributions: options.attributions,\n      attributionsCollapsible: options.attributionsCollapsible,\n      projection: options.projection,\n      state: options.state,\n      wrapX: options.wrapX,\n      interpolate: options.interpolate,\n    });\n\n    /***\n     * @type {TileSourceOnSignature<import(\"../events.js\").EventsKey>}\n     */\n    this.on;\n\n    /***\n     * @type {TileSourceOnSignature<import(\"../events.js\").EventsKey>}\n     */\n    this.once;\n\n    /***\n     * @type {TileSourceOnSignature<void>}\n     */\n    this.un;\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.tilePixelRatio_ =\n      options.tilePixelRatio !== undefined ? options.tilePixelRatio : 1;\n\n    /**\n     * @type {import(\"../tilegrid/TileGrid.js\").default|null}\n     * @protected\n     */\n    this.tileGrid = options.tileGrid !== undefined ? options.tileGrid : null;\n\n    const tileSize = [256, 256];\n    if (this.tileGrid) {\n      toSize(this.tileGrid.getTileSize(this.tileGrid.getMinZoom()), tileSize);\n    }\n\n    /**\n     * @protected\n     * @type {import(\"../size.js\").Size}\n     */\n    this.tmpSize = [0, 0];\n\n    /**\n     * @private\n     * @type {string}\n     */\n    this.key_ = options.key || getUid(this);\n\n    /**\n     * @protected\n     * @type {import(\"../Tile.js\").Options}\n     */\n    this.tileOptions = {\n      transition: options.transition,\n      interpolate: options.interpolate,\n    };\n\n    /**\n     * zDirection hint, read by the renderer. Indicates which resolution should be used\n     * by a renderer if the views resolution does not match any resolution of the tile source.\n     * If 0, the nearest resolution will be used. If 1, the nearest lower resolution\n     * will be used. If -1, the nearest higher resolution will be used.\n     * @type {number|import(\"../array.js\").NearestDirectionFunction}\n     */\n    this.zDirection = options.zDirection ? options.zDirection : 0;\n  }\n\n  /**\n   * @param {import(\"../proj/Projection.js\").default} projection Projection.\n   * @return {number} Gutter.\n   */\n  getGutterForProjection(projection) {\n    return 0;\n  }\n\n  /**\n   * Return the key to be used for all tiles in the source.\n   * @return {string} The key for all tiles.\n   */\n  getKey() {\n    return this.key_;\n  }\n\n  /**\n   * Set the value to be used as the key for all tiles in the source.\n   * @param {string} key The key for tiles.\n   * @protected\n   */\n  setKey(key) {\n    if (this.key_ !== key) {\n      this.key_ = key;\n      this.changed();\n    }\n  }\n\n  /**\n   * @param {import(\"../proj/Projection.js\").default} [projection] Projection.\n   * @return {Array<number>|null} Resolutions.\n   * @override\n   */\n  getResolutions(projection) {\n    const tileGrid = projection\n      ? this.getTileGridForProjection(projection)\n      : this.tileGrid;\n    if (!tileGrid) {\n      return null;\n    }\n    return tileGrid.getResolutions();\n  }\n\n  /**\n   * @abstract\n   * @param {number} z Tile coordinate z.\n   * @param {number} x Tile coordinate x.\n   * @param {number} y Tile coordinate y.\n   * @param {number} pixelRatio Pixel ratio.\n   * @param {import(\"../proj/Projection.js\").default} projection Projection.\n   * @param {import(\"../structs/LRUCache.js\").default<import(\"../Tile.js\").default>} [tileCache] Tile cache.\n   * @return {TileType|null} Tile.\n   */\n  getTile(z, x, y, pixelRatio, projection, tileCache) {\n    return abstract();\n  }\n\n  /**\n   * Return the tile grid of the tile source.\n   * @return {import(\"../tilegrid/TileGrid.js\").default|null} Tile grid.\n   * @api\n   */\n  getTileGrid() {\n    return this.tileGrid;\n  }\n\n  /**\n   * @param {import(\"../proj/Projection.js\").default} projection Projection.\n   * @return {!import(\"../tilegrid/TileGrid.js\").default} Tile grid.\n   */\n  getTileGridForProjection(projection) {\n    if (!this.tileGrid) {\n      return getTileGridForProjection(projection);\n    }\n    return this.tileGrid;\n  }\n\n  /**\n   * Get the tile pixel ratio for this source. Subclasses may override this\n   * method, which is meant to return a supported pixel ratio that matches the\n   * provided `pixelRatio` as close as possible.\n   * @param {number} pixelRatio Pixel ratio.\n   * @return {number} Tile pixel ratio.\n   */\n  getTilePixelRatio(pixelRatio) {\n    return this.tilePixelRatio_;\n  }\n\n  /**\n   * @param {number} z Z.\n   * @param {number} pixelRatio Pixel ratio.\n   * @param {import(\"../proj/Projection.js\").default} projection Projection.\n   * @return {import(\"../size.js\").Size} Tile size.\n   */\n  getTilePixelSize(z, pixelRatio, projection) {\n    const tileGrid = this.getTileGridForProjection(projection);\n    const tilePixelRatio = this.getTilePixelRatio(pixelRatio);\n    const tileSize = toSize(tileGrid.getTileSize(z), this.tmpSize);\n    if (tilePixelRatio == 1) {\n      return tileSize;\n    }\n    return scaleSize(tileSize, tilePixelRatio, this.tmpSize);\n  }\n\n  /**\n   * Returns a tile coordinate wrapped around the x-axis. When the tile coordinate\n   * is outside the resolution and extent range of the tile grid, `null` will be\n   * returned.\n   * @param {import(\"../tilecoord.js\").TileCoord} tileCoord Tile coordinate.\n   * @param {import(\"../proj/Projection.js\").default} [projection] Projection.\n   * @return {import(\"../tilecoord.js\").TileCoord} Tile coordinate to be passed to the tileUrlFunction or\n   *     null if no tile URL should be created for the passed `tileCoord`.\n   */\n  getTileCoordForTileUrlFunction(tileCoord, projection) {\n    const gridProjection =\n      projection !== undefined ? projection : this.getProjection();\n    const tileGrid =\n      projection !== undefined\n        ? this.getTileGridForProjection(gridProjection)\n        : this.tileGrid || this.getTileGridForProjection(gridProjection);\n    if (this.getWrapX() && gridProjection.isGlobal()) {\n      tileCoord = wrapX(tileGrid, tileCoord, gridProjection);\n    }\n    return withinExtentAndZ(tileCoord, tileGrid) ? tileCoord : null;\n  }\n\n  /**\n   * Remove all cached reprojected tiles from the source. The next render cycle will create new tiles.\n   * @api\n   */\n  clear() {}\n\n  /**\n   * @override\n   */\n  refresh() {\n    this.clear();\n    super.refresh();\n  }\n}\n\n/**\n * @classdesc\n * Events emitted by {@link module:ol/source/Tile~TileSource} instances are instances of this\n * type.\n */\nexport class TileSourceEvent extends Event {\n  /**\n   * @param {string} type Type.\n   * @param {import(\"../Tile.js\").default} tile The tile.\n   */\n  constructor(type, tile) {\n    super(type);\n\n    /**\n     * The tile related to the event.\n     * @type {import(\"../Tile.js\").default}\n     * @api\n     */\n    this.tile = tile;\n  }\n}\n\nexport default TileSource;\n", "/**\n * @module ol/source/TileEventType\n */\n\n/**\n * @enum {string}\n */\nexport default {\n  /**\n   * Triggered when a tile starts loading.\n   * @event module:ol/source/Tile.TileSourceEvent#tileloadstart\n   * @api\n   */\n  TILELOADSTART: 'tileloadstart',\n\n  /**\n   * Triggered when a tile finishes loading, either when its data is loaded,\n   * or when loading was aborted because the tile is no longer needed.\n   * @event module:ol/source/Tile.TileSourceEvent#tileloadend\n   * @api\n   */\n  TILELOADEND: 'tileloadend',\n\n  /**\n   * Triggered if tile loading results in an error. Note that this is not the\n   * right place to re-fetch tiles. See {@link module:ol/ImageTile~ImageTile#load}\n   * for details.\n   * @event module:ol/source/Tile.TileSourceEvent#tileloaderror\n   * @api\n   */\n  TILELOADERROR: 'tileloaderror',\n};\n\n/**\n * @typedef {'tileloadstart'|'tileloadend'|'tileloaderror'} TileSourceEventTypes\n */\n", "/**\n * @module ol/source/UrlTile\n */\nimport TileState from '../TileState.js';\nimport {createFromTemplates} from '../tileurlfunction.js';\nimport {expandUrl} from '../uri.js';\nimport {getUid} from '../util.js';\nimport TileSource, {TileSourceEvent} from './Tile.js';\nimport TileEventType from './TileEventType.js';\n\n/**\n * @typedef {Object} Options\n * @property {import(\"./Source.js\").AttributionLike} [attributions] Attributions.\n * @property {boolean} [attributionsCollapsible=true] Attributions are collapsible.\n * @property {number} [cacheSize] Deprecated.  Use the cacheSize option on the layer instead.\n * @property {import(\"../proj.js\").ProjectionLike} [projection] Projection.\n * @property {import(\"./Source.js\").State} [state] State.\n * @property {import(\"../tilegrid/TileGrid.js\").default} [tileGrid] TileGrid.\n * @property {import(\"../Tile.js\").LoadFunction} tileLoadFunction TileLoadFunction.\n * @property {number} [tilePixelRatio] TilePixelRatio.\n * @property {import(\"../Tile.js\").UrlFunction} [tileUrlFunction] Deprecated.  Use an ImageTile source and provide a function\n * for the url option instead.\n * @property {string} [url] Url.\n * @property {Array<string>} [urls] Urls.\n * @property {boolean} [wrapX=true] WrapX.\n * @property {number} [transition] Transition.\n * @property {string} [key] Key.\n * @property {number|import(\"../array.js\").NearestDirectionFunction} [zDirection=0] ZDirection.\n * @property {boolean} [interpolate=false] Use interpolated values when resampling.  By default,\n * the nearest neighbor is used when resampling.\n */\n\n/**\n * @deprecated Use the ol/source/ImageTile.js instead.\n *\n * @fires import(\"./Tile.js\").TileSourceEvent\n */\nclass UrlTile extends TileSource {\n  /**\n   * @param {Options} options Image tile options.\n   */\n  constructor(options) {\n    super({\n      attributions: options.attributions,\n      cacheSize: options.cacheSize,\n      projection: options.projection,\n      state: options.state,\n      tileGrid: options.tileGrid,\n      tilePixelRatio: options.tilePixelRatio,\n      wrapX: options.wrapX,\n      transition: options.transition,\n      interpolate: options.interpolate,\n      key: options.key,\n      attributionsCollapsible: options.attributionsCollapsible,\n      zDirection: options.zDirection,\n    });\n\n    /**\n     * @private\n     * @type {boolean}\n     */\n    this.generateTileUrlFunction_ =\n      this.tileUrlFunction === UrlTile.prototype.tileUrlFunction;\n\n    /**\n     * @protected\n     * @type {import(\"../Tile.js\").LoadFunction}\n     */\n    this.tileLoadFunction = options.tileLoadFunction;\n\n    if (options.tileUrlFunction) {\n      this.tileUrlFunction = options.tileUrlFunction;\n    }\n\n    /**\n     * @protected\n     * @type {!Array<string>|null}\n     */\n    this.urls = null;\n\n    if (options.urls) {\n      this.setUrls(options.urls);\n    } else if (options.url) {\n      this.setUrl(options.url);\n    }\n\n    /**\n     * @private\n     * @type {!Object<string, boolean>}\n     */\n    this.tileLoadingKeys_ = {};\n  }\n\n  /**\n   * Deprecated.  Use an ImageTile source instead.\n   * Return the tile load function of the source.\n   * @return {import(\"../Tile.js\").LoadFunction} TileLoadFunction\n   * @api\n   */\n  getTileLoadFunction() {\n    return this.tileLoadFunction;\n  }\n\n  /**\n   * Deprecated.  Use an ImageTile source instead.\n   * Return the tile URL function of the source.\n   * @return {import(\"../Tile.js\").UrlFunction} TileUrlFunction\n   * @api\n   */\n  getTileUrlFunction() {\n    return Object.getPrototypeOf(this).tileUrlFunction === this.tileUrlFunction\n      ? this.tileUrlFunction.bind(this)\n      : this.tileUrlFunction;\n  }\n\n  /**\n   * Deprecated.  Use an ImageTile source instead.\n   * Return the URLs used for this source.\n   * When a tileUrlFunction is used instead of url or urls,\n   * null will be returned.\n   * @return {!Array<string>|null} URLs.\n   * @api\n   */\n  getUrls() {\n    return this.urls;\n  }\n\n  /**\n   * Handle tile change events.\n   * @param {import(\"../events/Event.js\").default} event Event.\n   * @protected\n   */\n  handleTileChange(event) {\n    const tile = /** @type {import(\"../Tile.js\").default} */ (event.target);\n    const uid = getUid(tile);\n    const tileState = tile.getState();\n    let type;\n    if (tileState == TileState.LOADING) {\n      this.tileLoadingKeys_[uid] = true;\n      type = TileEventType.TILELOADSTART;\n    } else if (uid in this.tileLoadingKeys_) {\n      delete this.tileLoadingKeys_[uid];\n      type =\n        tileState == TileState.ERROR\n          ? TileEventType.TILELOADERROR\n          : tileState == TileState.LOADED\n            ? TileEventType.TILELOADEND\n            : undefined;\n    }\n    if (type != undefined) {\n      this.dispatchEvent(new TileSourceEvent(type, tile));\n    }\n  }\n\n  /**\n   * Deprecated.  Use an ImageTile source instead.\n   * Set the tile load function of the source.\n   * @param {import(\"../Tile.js\").LoadFunction} tileLoadFunction Tile load function.\n   * @api\n   */\n  setTileLoadFunction(tileLoadFunction) {\n    this.tileLoadFunction = tileLoadFunction;\n    this.changed();\n  }\n\n  /**\n   * Deprecated.  Use an ImageTile source instead.\n   * Set the tile URL function of the source.\n   * @param {import(\"../Tile.js\").UrlFunction} tileUrlFunction Tile URL function.\n   * @param {string} [key] Optional new tile key for the source.\n   * @api\n   */\n  setTileUrlFunction(tileUrlFunction, key) {\n    this.tileUrlFunction = tileUrlFunction;\n    if (typeof key !== 'undefined') {\n      this.setKey(key);\n    } else {\n      this.changed();\n    }\n  }\n\n  /**\n   * Set the URL to use for requests.\n   * @param {string} url URL.\n   * @api\n   */\n  setUrl(url) {\n    const urls = expandUrl(url);\n    this.urls = urls;\n    this.setUrls(urls);\n  }\n\n  /**\n   * Deprecated.  Use an ImageTile source instead.\n   * Set the URLs to use for requests.\n   * @param {Array<string>} urls URLs.\n   * @api\n   */\n  setUrls(urls) {\n    this.urls = urls;\n    const key = urls.join('\\n');\n    if (this.generateTileUrlFunction_) {\n      this.setTileUrlFunction(createFromTemplates(urls, this.tileGrid), key);\n    } else {\n      this.setKey(key);\n    }\n  }\n\n  /**\n   * @param {import(\"../tilecoord.js\").TileCoord} tileCoord Tile coordinate.\n   * @param {number} pixelRatio Pixel ratio.\n   * @param {import(\"../proj/Projection.js\").default} projection Projection.\n   * @return {string|undefined} Tile URL.\n   */\n  tileUrlFunction(tileCoord, pixelRatio, projection) {\n    return undefined;\n  }\n}\n\nexport default UrlTile;\n", "/**\n * @module ol/source/TileImage\n */\nimport ImageTile from '../ImageTile.js';\nimport TileState from '../TileState.js';\nimport EventType from '../events/EventType.js';\nimport {WORKER_OFFSCREEN_CANVAS} from '../has.js';\nimport {equivalent, get as getProjection} from '../proj.js';\nimport ReprojTile from '../reproj/Tile.js';\nimport {getCacheKey} from '../tilecoord.js';\nimport {getForProjection as getTileGridForProjection} from '../tilegrid.js';\nimport {getUid} from '../util.js';\nimport UrlTile from './UrlTile.js';\n\n/**\n * @typedef {Object} Options\n * @property {import(\"./Source.js\").AttributionLike} [attributions] Attributions.\n * @property {boolean} [attributionsCollapsible=true] Attributions are collapsible.\n * @property {number} [cacheSize] Deprecated.  Use the cacheSize option on the layer instead.\n * @property {null|string} [crossOrigin] The `crossOrigin` attribute for loaded images.  Note that\n * you must provide a `crossOrigin` value if you want to access pixel data with the Canvas renderer.\n * See https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image for more detail.\n * @property {ReferrerPolicy} [referrerPolicy] The `referrerPolicy` property for loaded images.\n * @property {boolean} [interpolate=true] Use interpolated values when resampling.  By default,\n * linear interpolation is used when resampling.  Set to false to use the nearest neighbor instead.\n * @property {import(\"../proj.js\").ProjectionLike} [projection] Projection. Default is the view projection.\n * @property {number} [reprojectionErrorThreshold=0.5] Maximum allowed reprojection error (in pixels).\n * Higher values can increase reprojection performance, but decrease precision.\n * @property {import(\"./Source.js\").State} [state] Source state.\n * @property {typeof import(\"../ImageTile.js\").default} [tileClass] Class used to instantiate image tiles.\n * Default is {@link module:ol/ImageTile~ImageTile}.\n * @property {import(\"../tilegrid/TileGrid.js\").default} [tileGrid] Tile grid.\n * @property {import(\"../Tile.js\").LoadFunction} [tileLoadFunction] Optional function to load a tile given a URL. The default is\n * ```js\n * function(imageTile, src) {\n *   imageTile.getImage().src = src;\n * };\n * ```\n * @property {number} [tilePixelRatio=1] The pixel ratio used by the tile service. For example, if the tile\n * service advertizes 256px by 256px tiles but actually sends 512px\n * by 512px images (for retina/hidpi devices) then `tilePixelRatio`\n * should be set to `2`.\n * @property {import(\"../Tile.js\").UrlFunction} [tileUrlFunction] Deprecated.  Use an ImageTile source and provide a function\n * for the url option instead.\n * @property {string} [url] URL template. Must include `{x}`, `{y}` or `{-y}`, and `{z}` placeholders.\n * A `{?-?}` template pattern, for example `subdomain{a-f}.domain.com`, may be\n * used instead of defining each one separately in the `urls` option.\n * @property {Array<string>} [urls] An array of URL templates.\n * @property {boolean} [wrapX] Whether to wrap the world horizontally. The default, is to\n * request out-of-bounds tiles from the server. When set to `false`, only one\n * world will be rendered. When set to `true`, tiles will be requested for one\n * world only, but they will be wrapped horizontally to render multiple worlds.\n * @property {number} [transition] Duration of the opacity transition for rendering.\n * To disable the opacity transition, pass `transition: 0`.\n * @property {string} [key] Optional tile key for proper cache fetching\n * @property {number|import(\"../array.js\").NearestDirectionFunction} [zDirection=0]\n * Choose whether to use tiles with a higher or lower zoom level when between integer\n * zoom levels. See {@link module:ol/tilegrid/TileGrid~TileGrid#getZForResolution}.\n */\n\n/**\n * @deprecated Use the ol/source/ImageTile.js instead.\n *\n * @fires import(\"./Tile.js\").TileSourceEvent\n * @api\n */\nclass TileImage extends UrlTile {\n  /**\n   * @param {!Options} options Image tile options.\n   */\n  constructor(options) {\n    super({\n      attributions: options.attributions,\n      cacheSize: options.cacheSize,\n      projection: options.projection,\n      state: options.state,\n      tileGrid: options.tileGrid,\n      tileLoadFunction: options.tileLoadFunction\n        ? options.tileLoadFunction\n        : defaultTileLoadFunction,\n      tilePixelRatio: options.tilePixelRatio,\n      tileUrlFunction: options.tileUrlFunction,\n      url: options.url,\n      urls: options.urls,\n      wrapX: options.wrapX,\n      transition: options.transition,\n      interpolate:\n        options.interpolate !== undefined ? options.interpolate : true,\n      key: options.key,\n      attributionsCollapsible: options.attributionsCollapsible,\n      zDirection: options.zDirection,\n    });\n\n    /**\n     * @protected\n     * @type {?string}\n     */\n    this.crossOrigin =\n      options.crossOrigin !== undefined ? options.crossOrigin : null;\n\n    /**\n     * @protected\n     * @type {ReferrerPolicy}\n     */\n    this.referrerPolicy = options.referrerPolicy;\n\n    /**\n     * @protected\n     * @type {typeof ImageTile}\n     */\n    this.tileClass =\n      options.tileClass !== undefined ? options.tileClass : ImageTile;\n\n    /**\n     * @protected\n     * @type {!Object<string, import(\"../tilegrid/TileGrid.js\").default>}\n     */\n    this.tileGridForProjection = {};\n\n    /**\n     * @private\n     * @type {number|undefined}\n     */\n    this.reprojectionErrorThreshold_ = options.reprojectionErrorThreshold;\n\n    /**\n     * @private\n     * @type {boolean}\n     */\n    this.renderReprojectionEdges_ = false;\n  }\n\n  /**\n   * @param {import(\"../proj/Projection.js\").default} projection Projection.\n   * @return {number} Gutter.\n   * @override\n   */\n  getGutterForProjection(projection) {\n    if (\n      this.getProjection() &&\n      projection &&\n      !equivalent(this.getProjection(), projection)\n    ) {\n      return 0;\n    }\n    return this.getGutter();\n  }\n\n  /**\n   * @return {number} Gutter.\n   */\n  getGutter() {\n    return 0;\n  }\n\n  /**\n   * Return the key to be used for all tiles in the source.\n   * @return {string} The key for all tiles.\n   * @override\n   */\n  getKey() {\n    let key = super.getKey();\n    if (!this.getInterpolate()) {\n      key += ':disable-interpolation';\n    }\n    return key;\n  }\n\n  /**\n   * @param {import(\"../proj/Projection.js\").default} projection Projection.\n   * @return {!import(\"../tilegrid/TileGrid.js\").default} Tile grid.\n   * @override\n   */\n  getTileGridForProjection(projection) {\n    const thisProj = this.getProjection();\n    if (this.tileGrid && (!thisProj || equivalent(thisProj, projection))) {\n      return this.tileGrid;\n    }\n    const projKey = getUid(projection);\n    if (!(projKey in this.tileGridForProjection)) {\n      this.tileGridForProjection[projKey] =\n        getTileGridForProjection(projection);\n    }\n    return this.tileGridForProjection[projKey];\n  }\n\n  /**\n   * @param {number} z Tile coordinate z.\n   * @param {number} x Tile coordinate x.\n   * @param {number} y Tile coordinate y.\n   * @param {number} pixelRatio Pixel ratio.\n   * @param {import(\"../proj/Projection.js\").default} projection Projection.\n   * @param {string} key The key set on the tile.\n   * @return {!ImageTile} Tile.\n   * @private\n   */\n  createTile_(z, x, y, pixelRatio, projection, key) {\n    const tileCoord = [z, x, y];\n    const urlTileCoord = this.getTileCoordForTileUrlFunction(\n      tileCoord,\n      projection,\n    );\n    const tileUrl = urlTileCoord\n      ? this.tileUrlFunction(urlTileCoord, pixelRatio, projection)\n      : undefined;\n    const tile = new this.tileClass(\n      tileCoord,\n      tileUrl !== undefined ? TileState.IDLE : TileState.EMPTY,\n      tileUrl !== undefined ? tileUrl : '',\n      {\n        crossOrigin: this.crossOrigin,\n        referrerPolicy: this.referrerPolicy,\n      },\n      this.tileLoadFunction,\n      this.tileOptions,\n    );\n    tile.key = key;\n    tile.addEventListener(EventType.CHANGE, this.handleTileChange.bind(this));\n    return tile;\n  }\n\n  /**\n   * @param {number} z Tile coordinate z.\n   * @param {number} x Tile coordinate x.\n   * @param {number} y Tile coordinate y.\n   * @param {number} pixelRatio Pixel ratio.\n   * @param {import(\"../proj/Projection.js\").default} projection Projection.\n   * @param {import(\"../structs/LRUCache.js\").default<import(\"../Tile.js\").default>} [tileCache] Tile cache.\n   * @return {!(ImageTile|ReprojTile)} Tile.\n   * @override\n   */\n  getTile(z, x, y, pixelRatio, projection, tileCache) {\n    const sourceProjection = this.getProjection();\n    if (\n      !sourceProjection ||\n      !projection ||\n      equivalent(sourceProjection, projection)\n    ) {\n      return this.getTileInternal(\n        z,\n        x,\n        y,\n        pixelRatio,\n        sourceProjection || projection,\n      );\n    }\n    const tileCoord = [z, x, y];\n    const key = this.getKey();\n    const sourceTileGrid = this.getTileGridForProjection(sourceProjection);\n    const targetTileGrid = this.getTileGridForProjection(projection);\n    const wrappedTileCoord = this.getTileCoordForTileUrlFunction(\n      tileCoord,\n      projection,\n    );\n    const tile = new ReprojTile(\n      sourceProjection,\n      sourceTileGrid,\n      projection,\n      targetTileGrid,\n      tileCoord,\n      wrappedTileCoord,\n      this.getTilePixelRatio(pixelRatio),\n      this.getGutter(),\n      (z, x, y, pixelRatio) =>\n        this.getTileInternal(z, x, y, pixelRatio, sourceProjection, tileCache),\n      this.reprojectionErrorThreshold_,\n      this.renderReprojectionEdges_,\n      this.tileOptions,\n    );\n    tile.key = key;\n    return tile;\n  }\n\n  /**\n   * @param {number} z Tile coordinate z.\n   * @param {number} x Tile coordinate x.\n   * @param {number} y Tile coordinate y.\n   * @param {number} pixelRatio Pixel ratio.\n   * @param {!import(\"../proj/Projection.js\").default} projection Projection.\n   * @param {import(\"../structs/LRUCache.js\").default<import(\"../Tile.js\").default>} [tileCache] Tile cache.\n   * @return {!ImageTile} Tile.\n   * @protected\n   */\n  getTileInternal(z, x, y, pixelRatio, projection, tileCache) {\n    const key = this.getKey();\n    const cacheKey = getCacheKey(this, key, z, x, y);\n    if (tileCache && tileCache.containsKey(cacheKey)) {\n      const tile = /** @type {!ImageTile} */ (tileCache.get(cacheKey));\n      return tile;\n    }\n    const tile = this.createTile_(z, x, y, pixelRatio, projection, key);\n    tileCache?.set(cacheKey, tile);\n    return tile;\n  }\n\n  /**\n   * Sets whether to render reprojection edges or not (usually for debugging).\n   * @param {boolean} render Render the edges.\n   * @api\n   */\n  setRenderReprojectionEdges(render) {\n    if (this.renderReprojectionEdges_ == render) {\n      return;\n    }\n    this.renderReprojectionEdges_ = render;\n    this.changed();\n  }\n\n  /**\n   * Sets the tile grid to use when reprojecting the tiles to the given\n   * projection instead of the default tile grid for the projection.\n   *\n   * This can be useful when the default tile grid cannot be created\n   * (e.g. projection has no extent defined) or\n   * for optimization reasons (custom tile size, resolutions, ...).\n   *\n   * @param {import(\"../proj.js\").ProjectionLike} projection Projection.\n   * @param {import(\"../tilegrid/TileGrid.js\").default} tilegrid Tile grid to use for the projection.\n   * @api\n   */\n  setTileGridForProjection(projection, tilegrid) {\n    const proj = getProjection(projection);\n    if (proj) {\n      const projKey = getUid(proj);\n      if (!(projKey in this.tileGridForProjection)) {\n        this.tileGridForProjection[projKey] = tilegrid;\n      }\n    }\n  }\n}\n\n/**\n * @param {ImageTile} imageTile Image tile.\n * @param {string} src Source.\n */\nexport function defaultTileLoadFunction(imageTile, src) {\n  if (WORKER_OFFSCREEN_CANVAS) {\n    // special treatment for offscreen canvas\n    const crossOrigin = imageTile.getCrossOrigin();\n\n    /** @type {RequestMode} */\n    let mode = 'same-origin';\n    /** @type {RequestCredentials} */\n    let credentials = 'same-origin';\n    if (crossOrigin === 'anonymous' || crossOrigin === '') {\n      mode = 'cors';\n      credentials = 'omit';\n    } else if (crossOrigin === 'use-credentials') {\n      mode = 'cors';\n      credentials = 'include';\n    }\n\n    const options = {\n      mode,\n      credentials,\n      referrerPolicy: imageTile.getReferrerPolicy(),\n    };\n\n    fetch(src, options)\n      .then((response) => {\n        if (!response.ok) {\n          throw new Error(`HTTP ${response.status}`);\n        }\n        return response.blob();\n      })\n      .then((blob) => {\n        return createImageBitmap(blob);\n      })\n      .then((imageBitmap) => {\n        const canvas = imageTile.getImage();\n        canvas.width = imageBitmap.width;\n        canvas.height = imageBitmap.height;\n        const ctx = /** @type {OffscreenCanvas} */ (canvas).getContext('2d');\n        ctx.drawImage(imageBitmap, 0, 0);\n        imageBitmap.close?.();\n        // mock the image 'load' event\n        canvas.dispatchEvent(new Event('load'));\n      })\n      .catch(() => {\n        const canvas = imageTile.getImage();\n        canvas.dispatchEvent(new Event('error'));\n      });\n    return;\n  }\n\n  /** @type {HTMLImageElement|HTMLVideoElement} */ (imageTile.getImage()).src =\n    src;\n}\n\nexport default TileImage;\n", "/**\n * @module ol/source/XYZ\n */\n\nimport {createXYZ, extentFromProjection} from '../tilegrid.js';\nimport TileImage from './TileImage.js';\n\n/**\n * @typedef {Object} Options\n * @property {import(\"./Source.js\").AttributionLike} [attributions] Attributions.\n * @property {boolean} [attributionsCollapsible=true] Attributions are collapsible.\n * @property {number} [cacheSize] Deprecated.  Use the cacheSize option on the layer instead.\n * @property {null|string} [crossOrigin] The `crossOrigin` attribute for loaded images.  Note that\n * you must provide a `crossOrigin` value if you want to access pixel data with the Canvas renderer.\n * See https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image for more detail.\n * @property {ReferrerPolicy} [referrerPolicy] The `referrerPolicy` property for loaded images.\n * @property {boolean} [interpolate=true] Use interpolated values when resampling.  By default,\n * linear interpolation is used when resampling.  Set to false to use the nearest neighbor instead.\n * @property {import(\"../proj.js\").ProjectionLike} [projection='EPSG:3857'] Projection.\n * @property {number} [reprojectionErrorThreshold=0.5] Maximum allowed reprojection error (in pixels).\n * Higher values can increase reprojection performance, but decrease precision.\n * @property {number} [maxZoom=42] Optional max zoom level. Not used if `tileGrid` is provided.\n * @property {number} [minZoom=0] Optional min zoom level. Not used if `tileGrid` is provided.\n * @property {number} [maxResolution] Optional tile grid resolution at level zero. Not used if `tileGrid` is provided.\n * @property {import(\"../tilegrid/TileGrid.js\").default} [tileGrid] Tile grid.\n * @property {import(\"../Tile.js\").LoadFunction} [tileLoadFunction] Deprecated.  Use an ImageTile source with a loader\n * instead.  Optional function to load a tile given a URL. The default is\n * ```js\n * function(imageTile, src) {\n *   imageTile.getImage().src = src;\n * };\n * ```\n * @property {number} [tilePixelRatio=1] The pixel ratio used by the tile service.\n * For example, if the tile service advertizes 256px by 256px tiles but actually sends 512px\n * by 512px images (for retina/hidpi devices) then `tilePixelRatio`\n * should be set to `2`.\n * @property {number|import(\"../size.js\").Size} [tileSize=[256, 256]] The tile size used by the tile service.\n * Not used if `tileGrid` is provided.\n * @property {number} [gutter=0] The size in pixels of the gutter around image tiles to ignore.\n * This allows artifacts of rendering at tile edges to be ignored.\n * Supported images should be wider and taller than the tile size by a value of `2 x gutter`.\n * @property {import(\"../Tile.js\").UrlFunction} [tileUrlFunction] Deprecated.  Use an ImageTile source and provide a function\n * for the url option instead.\n * @property {string} [url] URL template. Must include `{x}`, `{y}` or `{-y}`,\n * and `{z}` placeholders. A `{?-?}` template pattern, for example `subdomain{a-f}.domain.com`,\n * may be used instead of defining each one separately in the `urls` option.\n * @property {Array<string>} [urls] Deprecated.  Use an ImageTile source and provide an array of URLs for the\n * url option instead.\n * @property {boolean} [wrapX=true] Whether to wrap the world horizontally.\n * @property {number} [transition=250] Duration of the opacity transition for rendering.\n * To disable the opacity transition, pass `transition: 0`.\n * @property {number|import(\"../array.js\").NearestDirectionFunction} [zDirection=0]\n * Choose whether to use tiles with a higher or lower zoom level when between integer\n * zoom levels. See {@link module:ol/tilegrid/TileGrid~TileGrid#getZForResolution}.\n */\n\n/**\n * @classdesc\n * Layer source for tile data with URLs in a set XYZ format that are\n * defined in a URL template. By default, this follows the widely-used\n * Google grid where `x` 0 and `y` 0 are in the top left. Grids like\n * TMS where `x` 0 and `y` 0 are in the bottom left can be used by\n * using the `{-y}` placeholder in the URL template, so long as the\n * source does not have a custom tile grid. In this case\n * a `tileUrlFunction` can be used, such as:\n * ```js\n *  tileUrlFunction: function(coordinate) {\n *    return 'http://mapserver.com/' + coordinate[0] + '/' +\n *      coordinate[1] + '/' + (-coordinate[2] - 1) + '.png';\n *  }\n * ```\n * @api\n */\nclass XYZ extends TileImage {\n  /**\n   * @param {Options} [options] XYZ options.\n   */\n  constructor(options) {\n    options = options || {};\n\n    const projection =\n      options.projection !== undefined ? options.projection : 'EPSG:3857';\n\n    const tileGrid =\n      options.tileGrid !== undefined\n        ? options.tileGrid\n        : createXYZ({\n            extent: extentFromProjection(projection),\n            maxResolution: options.maxResolution,\n            maxZoom: options.maxZoom,\n            minZoom: options.minZoom,\n            tileSize: options.tileSize,\n          });\n\n    super({\n      attributions: options.attributions,\n      cacheSize: options.cacheSize,\n      crossOrigin: options.crossOrigin,\n      referrerPolicy: options.referrerPolicy,\n      interpolate: options.interpolate,\n      projection: projection,\n      reprojectionErrorThreshold: options.reprojectionErrorThreshold,\n      tileGrid: tileGrid,\n      tileLoadFunction: options.tileLoadFunction,\n      tilePixelRatio: options.tilePixelRatio,\n      tileUrlFunction: options.tileUrlFunction,\n      url: options.url,\n      urls: options.urls,\n      wrapX: options.wrapX !== undefined ? options.wrapX : true,\n      transition: options.transition,\n      attributionsCollapsible: options.attributionsCollapsible,\n      zDirection: options.zDirection,\n    });\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.gutter_ = options.gutter !== undefined ? options.gutter : 0;\n  }\n\n  /**\n   * @return {number} Gutter.\n   * @override\n   */\n  getGutter() {\n    return this.gutter_;\n  }\n}\n\nexport default XYZ;\n", "/**\n * @module ol/source/OSM\n */\n\nimport XYZ from './XYZ.js';\n\n/**\n * The attribution containing a link to the OpenStreetMap Copyright and License\n * page.\n * @const\n * @type {string}\n * @api\n */\nexport const ATTRIBUTION =\n  '&#169; ' +\n  '<a href=\"https://www.openstreetmap.org/copyright\" target=\"_blank\">OpenStreetMap</a> ' +\n  'contributors.';\n\n/**\n * @typedef {Object} Options\n * @property {import(\"./Source.js\").AttributionLike} [attributions] Attributions.\n * @property {number} [cacheSize] Deprecated.  Use the cacheSize option on the layer instead.\n * @property {null|string} [crossOrigin='anonymous'] The `crossOrigin` attribute for loaded images.  Note that\n * you must provide a `crossOrigin` value if you want to access pixel data with the Canvas renderer.\n * See https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image for more detail.\n * @property {ReferrerPolicy} [referrerPolicy='origin-when-cross-origin'] The `referrerPolicy` property for loaded images.\n * @property {boolean} [interpolate=true] Use interpolated values when resampling.  By default,\n * linear interpolation is used when resampling.  Set to false to use the nearest neighbor instead.\n * @property {number} [maxZoom=19] Max zoom.\n * @property {number} [reprojectionErrorThreshold=0.5] Maximum allowed reprojection error (in pixels).\n * Higher values can increase reprojection performance, but decrease precision.\n * @property {import(\"../Tile.js\").LoadFunction} [tileLoadFunction] Optional function to load a tile given a URL. The default is\n * ```js\n * function(imageTile, src) {\n *   imageTile.getImage().src = src;\n * };\n * ```\n * @property {number} [transition=250] Duration of the opacity transition for rendering.\n * To disable the opacity transition, pass `transition: 0`.\n * @property {string} [url='https://tile.openstreetmap.org/{z}/{x}/{y}.png'] URL template.\n * Must include `{x}`, `{y}` or `{-y}`, and `{z}` placeholders.\n * @property {boolean} [wrapX=true] Whether to wrap the world horizontally.\n * @property {number|import(\"../array.js\").NearestDirectionFunction} [zDirection=0]\n * Choose whether to use tiles with a higher or lower zoom level when between integer\n * zoom levels. See {@link module:ol/tilegrid/TileGrid~TileGrid#getZForResolution}.\n */\n\n/**\n * @classdesc\n * Layer source for the OpenStreetMap tile server.\n * @api\n */\nclass OSM extends XYZ {\n  /**\n   * @param {Options} [options] Open Street Map options.\n   */\n  constructor(options) {\n    options = options || {};\n\n    let attributions;\n    if (options.attributions !== undefined) {\n      attributions = options.attributions;\n    } else {\n      attributions = [ATTRIBUTION];\n    }\n\n    const url =\n      options.url !== undefined\n        ? options.url\n        : 'https://tile.openstreetmap.org/{z}/{x}/{y}.png';\n\n    super({\n      attributions: attributions,\n      attributionsCollapsible: false,\n      cacheSize: options.cacheSize,\n      crossOrigin:\n        options.crossOrigin !== undefined ? options.crossOrigin : 'anonymous',\n      referrerPolicy: options.referrerPolicy || 'origin-when-cross-origin',\n      interpolate: options.interpolate,\n      maxZoom: options.maxZoom !== undefined ? options.maxZoom : 19,\n      reprojectionErrorThreshold: options.reprojectionErrorThreshold,\n      tileLoadFunction: options.tileLoadFunction,\n      transition: options.transition,\n      url: url,\n      wrapX: options.wrapX,\n      zDirection: options.zDirection,\n    });\n  }\n}\n\nexport default OSM;\n", "/**\n * @module ol/control/MousePosition\n */\n\nimport {wrapX} from '../coordinate.js';\nimport {listen} from '../events.js';\nimport EventType from '../pointer/EventType.js';\nimport {\n  get as getProjection,\n  getTransformFromProjections,\n  getUserProjection,\n  identityTransform,\n} from '../proj.js';\nimport Control from './Control.js';\n\n/**\n * @type {string}\n */\nconst PROJECTION = 'projection';\n\n/**\n * @type {string}\n */\nconst COORDINATE_FORMAT = 'coordinateFormat';\n\n/***\n * @template Return\n * @typedef {import(\"../Observable.js\").OnSignature<import(\"../Observable.js\").EventTypes, import(\"../events/Event.js\").default, Return> &\n *   import(\"../Observable.js\").OnSignature<import(\"../ObjectEventType.js\").Types|\n *     'change:coordinateFormat'|'change:projection', import(\"../Object.js\").ObjectEvent, Return> &\n *   import(\"../Observable.js\").CombinedOnSignature<import(\"../Observable.js\").EventTypes|import(\"../ObjectEventType.js\").Types|\n *     'change:coordinateFormat'|'change:projection', Return>} MousePositionOnSignature\n */\n\n/**\n * @typedef {Object} Options\n * @property {string} [className='ol-mouse-position'] CSS class name.\n * @property {import(\"../coordinate.js\").CoordinateFormat} [coordinateFormat] Coordinate format.\n * @property {import(\"../proj.js\").ProjectionLike} [projection] Projection. Default is the view projection.\n * @property {function(import(\"../MapEvent.js\").default):void} [render] Function called when the\n * control should be re-rendered. This is called in a `requestAnimationFrame`\n * callback.\n * @property {HTMLElement|string} [target] Specify a target if you want the\n * control to be rendered outside of the map's viewport.\n * @property {string} [placeholder] Markup to show when the mouse position is not\n * available (e.g. when the pointer leaves the map viewport).  By default, a non-breaking space is rendered\n * initially and the last position is retained when the mouse leaves the viewport.\n * When a string is provided (e.g. `'no position'` or `''` for an empty string) it is used as a\n * placeholder.\n * @property {boolean} [wrapX=true] Wrap the world horizontally on the projection's antimeridian, if it\n * is a global projection.\n */\n\n/**\n * @classdesc\n * A control to show the 2D coordinates of the mouse cursor. By default, these\n * are in the view projection, but can be in any supported projection.\n * By default the control is shown in the top right corner of the map, but this\n * can be changed by using the css selector `.ol-mouse-position`.\n *\n * On touch devices, which usually do not have a mouse cursor, the coordinates\n * of the currently touched position are shown.\n *\n * @api\n */\nclass MousePosition extends Control {\n  /**\n   * @param {Options} [options] Mouse position options.\n   */\n  constructor(options) {\n    options = options ? options : {};\n\n    const element = document.createElement('div');\n    element.className =\n      options.className !== undefined ? options.className : 'ol-mouse-position';\n\n    super({\n      element: element,\n      render: options.render,\n      target: options.target,\n    });\n\n    /***\n     * @type {MousePositionOnSignature<import(\"../events.js\").EventsKey>}\n     */\n    this.on;\n\n    /***\n     * @type {MousePositionOnSignature<import(\"../events.js\").EventsKey>}\n     */\n    this.once;\n\n    /***\n     * @type {MousePositionOnSignature<void>}\n     */\n    this.un;\n\n    this.addChangeListener(PROJECTION, this.handleProjectionChanged_);\n\n    if (options.coordinateFormat) {\n      this.setCoordinateFormat(options.coordinateFormat);\n    }\n    if (options.projection) {\n      this.setProjection(options.projection);\n    }\n\n    /**\n     * @private\n     * @type {boolean}\n     */\n    this.renderOnMouseOut_ = options.placeholder !== undefined;\n\n    /**\n     * @private\n     * @type {string}\n     */\n    this.placeholder_ = this.renderOnMouseOut_ ? options.placeholder : '&#160;';\n\n    /**\n     * @private\n     * @type {string}\n     */\n    this.renderedHTML_ = element.innerHTML;\n\n    /**\n     * @private\n     * @type {?import(\"../proj/Projection.js\").default}\n     */\n    this.mapProjection_ = null;\n\n    /**\n     * @private\n     * @type {?import(\"../proj.js\").TransformFunction}\n     */\n    this.transform_ = null;\n\n    /**\n     * @private\n     * @type {boolean}\n     */\n    this.wrapX_ = options.wrapX === false ? false : true;\n  }\n\n  /**\n   * @private\n   */\n  handleProjectionChanged_() {\n    this.transform_ = null;\n  }\n\n  /**\n   * Return the coordinate format type used to render the current position or\n   * undefined.\n   * @return {import(\"../coordinate.js\").CoordinateFormat|undefined} The format to render the current\n   *     position in.\n   * @observable\n   * @api\n   */\n  getCoordinateFormat() {\n    return /** @type {import(\"../coordinate.js\").CoordinateFormat|undefined} */ (\n      this.get(COORDINATE_FORMAT)\n    );\n  }\n\n  /**\n   * Return the projection that is used to report the mouse position.\n   * @return {import(\"../proj/Projection.js\").default|undefined} The projection to report mouse\n   *     position in.\n   * @observable\n   * @api\n   */\n  getProjection() {\n    return /** @type {import(\"../proj/Projection.js\").default|undefined} */ (\n      this.get(PROJECTION)\n    );\n  }\n\n  /**\n   * @param {MouseEvent} event Browser event.\n   * @protected\n   */\n  handleMouseMove(event) {\n    const map = this.getMap();\n    this.updateHTML_(map.getEventPixel(event));\n  }\n\n  /**\n   * @param {Event} event Browser event.\n   * @protected\n   */\n  handleMouseOut(event) {\n    this.updateHTML_(null);\n  }\n\n  /**\n   * Remove the control from its current map and attach it to the new map.\n   * Pass `null` to just remove the control from the current map.\n   * Subclasses may set up event handlers to get notified about changes to\n   * the map here.\n   * @param {import(\"../Map.js\").default|null} map Map.\n   * @api\n   * @override\n   */\n  setMap(map) {\n    super.setMap(map);\n    if (map) {\n      const viewport = map.getViewport();\n      this.listenerKeys.push(\n        listen(viewport, EventType.POINTERMOVE, this.handleMouseMove, this),\n      );\n      if (this.renderOnMouseOut_) {\n        this.listenerKeys.push(\n          listen(viewport, EventType.POINTEROUT, this.handleMouseOut, this),\n        );\n      }\n      this.updateHTML_(null);\n    }\n  }\n\n  /**\n   * Set the coordinate format type used to render the current position.\n   * @param {import(\"../coordinate.js\").CoordinateFormat} format The format to render the current\n   *     position in.\n   * @observable\n   * @api\n   */\n  setCoordinateFormat(format) {\n    this.set(COORDINATE_FORMAT, format);\n  }\n\n  /**\n   * Set the projection that is used to report the mouse position.\n   * @param {import(\"../proj.js\").ProjectionLike} projection The projection to report mouse\n   *     position in.\n   * @observable\n   * @api\n   */\n  setProjection(projection) {\n    this.set(PROJECTION, getProjection(projection));\n  }\n\n  /**\n   * @param {?import(\"../pixel.js\").Pixel} pixel Pixel.\n   * @private\n   */\n  updateHTML_(pixel) {\n    let html = this.placeholder_;\n    if (pixel && this.mapProjection_) {\n      if (!this.transform_) {\n        const projection = this.getProjection();\n        if (projection) {\n          this.transform_ = getTransformFromProjections(\n            this.mapProjection_,\n            projection,\n          );\n        } else {\n          this.transform_ = identityTransform;\n        }\n      }\n      const map = this.getMap();\n      const coordinate = map.getCoordinateFromPixelInternal(pixel);\n      if (coordinate) {\n        const userProjection = getUserProjection();\n        if (userProjection) {\n          this.transform_ = getTransformFromProjections(\n            this.mapProjection_,\n            userProjection,\n          );\n        }\n        this.transform_(coordinate, coordinate);\n        if (this.wrapX_) {\n          const projection =\n            userProjection || this.getProjection() || this.mapProjection_;\n          wrapX(coordinate, projection);\n        }\n        const coordinateFormat = this.getCoordinateFormat();\n        if (coordinateFormat) {\n          html = coordinateFormat(coordinate);\n        } else {\n          html = coordinate.toString();\n        }\n      }\n    }\n    if (!this.renderedHTML_ || html !== this.renderedHTML_) {\n      this.element.innerHTML = html;\n      this.renderedHTML_ = html;\n    }\n  }\n\n  /**\n   * Update the projection. Rendering of the coordinates is done in\n   * `handleMouseMove` and `handleMouseUp`.\n   * @param {import(\"../MapEvent.js\").default} mapEvent Map event.\n   * @override\n   */\n  render(mapEvent) {\n    const frameState = mapEvent.frameState;\n    if (!frameState) {\n      this.mapProjection_ = null;\n    } else {\n      if (this.mapProjection_ != frameState.viewState.projection) {\n        this.mapProjection_ = frameState.viewState.projection;\n        this.transform_ = null;\n      }\n    }\n  }\n}\n\nexport default MousePosition;\n", "/**\n * @module ol/Overlay\n */\nimport MapEventType from './MapEventType.js';\nimport BaseObject from './Object.js';\nimport {CLASS_SELECTABLE} from './css.js';\nimport {outerHeight, outerWidth, removeChildren} from './dom.js';\nimport {listen, unlistenByKey} from './events.js';\nimport {containsExtent} from './extent.js';\n\n/**\n * @typedef {'bottom-left' | 'bottom-center' | 'bottom-right' | 'center-left' | 'center-center' | 'center-right' | 'top-left' | 'top-center' | 'top-right'} Positioning\n * The overlay position: `'bottom-left'`, `'bottom-center'`,  `'bottom-right'`,\n * `'center-left'`, `'center-center'`, `'center-right'`, `'top-left'`,\n * `'top-center'`, or `'top-right'`.\n */\n\n/**\n * @typedef {Object} Options\n * @property {number|string} [id] Set the overlay id. The overlay id can be used\n * with the {@link module:ol/Map~Map#getOverlayById} method.\n * @property {HTMLElement} [element] The overlay element.\n * @property {Array<number>} [offset=[0, 0]] Offsets in pixels used when positioning\n * the overlay. The first element in the\n * array is the horizontal offset. A positive value shifts the overlay right.\n * The second element in the array is the vertical offset. A positive value\n * shifts the overlay down.\n * @property {import(\"./coordinate.js\").Coordinate} [position] The overlay position\n * in map projection.\n * @property {Positioning} [positioning='top-left'] Defines how\n * the overlay is actually positioned with respect to its `position` property.\n * Possible values are `'bottom-left'`, `'bottom-center'`, `'bottom-right'`,\n * `'center-left'`, `'center-center'`, `'center-right'`, `'top-left'`,\n * `'top-center'`, and `'top-right'`.\n * @property {boolean} [stopEvent=true] Whether event propagation to the map\n * viewport should be stopped. If `true` the overlay is placed in the same\n * container as that of the controls (CSS class name\n * `ol-overlaycontainer-stopevent`); if `false` it is placed in the container\n * with CSS class name specified by the `className` property.\n * @property {boolean} [insertFirst=true] Whether the overlay is inserted first\n * in the overlay container, or appended. If the overlay is placed in the same\n * container as that of the controls (see the `stopEvent` option) you will\n * probably set `insertFirst` to `true` so the overlay is displayed below the\n * controls.\n * @property {PanIntoViewOptions|boolean} [autoPan=false] Pan the map when calling\n * `setPosition`, so that the overlay is entirely visible in the current viewport.\n * @property {string} [className='ol-overlay-container ol-selectable'] CSS class\n * name.\n */\n\n/**\n * @typedef {Object} PanOptions\n * @property {number} [duration=1000] The duration of the animation in\n * milliseconds.\n * @property {function(number):number} [easing] The easing function to use. Can\n * be one from {@link module:ol/easing} or a custom function.\n * Default is {@link module:ol/easing.inAndOut}.\n */\n\n/**\n * @typedef {Object} PanIntoViewOptions\n * @property {PanOptions} [animation={}] The animation parameters for the pan\n * @property {number} [margin=20] The margin (in pixels) between the\n * overlay and the borders of the map when panning into view.\n */\n\n/**\n * @enum {string}\n * @protected\n */\nconst Property = {\n  ELEMENT: 'element',\n  MAP: 'map',\n  OFFSET: 'offset',\n  POSITION: 'position',\n  POSITIONING: 'positioning',\n};\n\n/**\n * @typedef {import(\"./ObjectEventType.js\").Types|'change:element'|'change:map'|'change:offset'|'change:position'|\n *   'change:positioning'} OverlayObjectEventTypes\n */\n\n/***\n * @template Return\n * @typedef {import(\"./Observable.js\").OnSignature<import(\"./Observable.js\").EventTypes, import(\"./events/Event.js\").default, Return> &\n *   import(\"./Observable.js\").OnSignature<OverlayObjectEventTypes, import(\"./Object.js\").ObjectEvent, Return> &\n *   import(\"./Observable.js\").CombinedOnSignature<import(\"./Observable.js\").EventTypes|OverlayObjectEventTypes, Return>} OverlayOnSignature\n */\n\n/**\n * @classdesc\n * An element to be displayed over the map and attached to a single map\n * location.  Like {@link module:ol/control/Control~Control}, Overlays are\n * visible widgets. Unlike Controls, they are not in a fixed position on the\n * screen, but are tied to a geographical coordinate, so panning the map will\n * move an Overlay but not a Control.\n *\n * Example:\n *\n *     import Overlay from 'ol/Overlay.js';\n *\n *     // ...\n *     const popup = new Overlay({\n *       element: document.getElementById('popup'),\n *     });\n *     popup.setPosition(coordinate);\n *     map.addOverlay(popup);\n *\n * @api\n */\nclass Overlay extends BaseObject {\n  /**\n   * @param {Options} options Overlay options.\n   */\n  constructor(options) {\n    super();\n\n    /***\n     * @type {OverlayOnSignature<import(\"./events.js\").EventsKey>}\n     */\n    this.on;\n\n    /***\n     * @type {OverlayOnSignature<import(\"./events.js\").EventsKey>}\n     */\n    this.once;\n\n    /***\n     * @type {OverlayOnSignature<void>}\n     */\n    this.un;\n\n    /**\n     * @protected\n     * @type {Options}\n     */\n    this.options = options;\n\n    /**\n     * @protected\n     * @type {number|string|undefined}\n     */\n    this.id = options.id;\n\n    /**\n     * @protected\n     * @type {boolean}\n     */\n    this.insertFirst =\n      options.insertFirst !== undefined ? options.insertFirst : true;\n\n    /**\n     * @protected\n     * @type {boolean}\n     */\n    this.stopEvent = options.stopEvent !== undefined ? options.stopEvent : true;\n\n    /**\n     * @protected\n     * @type {HTMLElement}\n     */\n    this.element = document.createElement('div');\n    this.element.className =\n      options.className !== undefined\n        ? options.className\n        : 'ol-overlay-container ' + CLASS_SELECTABLE;\n    this.element.style.position = 'absolute';\n    this.element.style.pointerEvents = 'auto';\n\n    /**\n     * @protected\n     * @type {PanIntoViewOptions|undefined}\n     */\n    this.autoPan = options.autoPan === true ? {} : options.autoPan || undefined;\n\n    /**\n     * @protected\n     * @type {{transform_: string,\n     *         visible: boolean}}\n     */\n    this.rendered = {\n      transform_: '',\n      visible: true,\n    };\n\n    /**\n     * @protected\n     * @type {?import(\"./events.js\").EventsKey}\n     */\n    this.mapPostrenderListenerKey = null;\n\n    this.addChangeListener(Property.ELEMENT, this.handleElementChanged);\n    this.addChangeListener(Property.MAP, this.handleMapChanged);\n    this.addChangeListener(Property.OFFSET, this.handleOffsetChanged);\n    this.addChangeListener(Property.POSITION, this.handlePositionChanged);\n    this.addChangeListener(Property.POSITIONING, this.handlePositioningChanged);\n\n    if (options.element !== undefined) {\n      this.setElement(options.element);\n    }\n\n    this.setOffset(options.offset !== undefined ? options.offset : [0, 0]);\n\n    this.setPositioning(options.positioning || 'top-left');\n\n    if (options.position !== undefined) {\n      this.setPosition(options.position);\n    }\n  }\n\n  /**\n   * Get the DOM element of this overlay.\n   * @return {HTMLElement|undefined} The Element containing the overlay.\n   * @observable\n   * @api\n   */\n  getElement() {\n    return /** @type {HTMLElement|undefined} */ (this.get(Property.ELEMENT));\n  }\n\n  /**\n   * Get the overlay identifier which is set on constructor.\n   * @return {number|string|undefined} Id.\n   * @api\n   */\n  getId() {\n    return this.id;\n  }\n\n  /**\n   * Get the map associated with this overlay.\n   * @return {import(\"./Map.js\").default|null} The map that the\n   * overlay is part of.\n   * @observable\n   * @api\n   */\n  getMap() {\n    return /** @type {import(\"./Map.js\").default|null} */ (\n      this.get(Property.MAP) || null\n    );\n  }\n\n  /**\n   * Get the offset of this overlay.\n   * @return {Array<number>} The offset.\n   * @observable\n   * @api\n   */\n  getOffset() {\n    return /** @type {Array<number>} */ (this.get(Property.OFFSET));\n  }\n\n  /**\n   * Get the current position of this overlay.\n   * @return {import(\"./coordinate.js\").Coordinate|undefined} The spatial point that the overlay is\n   *     anchored at.\n   * @observable\n   * @api\n   */\n  getPosition() {\n    return /** @type {import(\"./coordinate.js\").Coordinate|undefined} */ (\n      this.get(Property.POSITION)\n    );\n  }\n\n  /**\n   * Get the current positioning of this overlay.\n   * @return {Positioning} How the overlay is positioned\n   *     relative to its point on the map.\n   * @observable\n   * @api\n   */\n  getPositioning() {\n    return /** @type {Positioning} */ (this.get(Property.POSITIONING));\n  }\n\n  /**\n   * @protected\n   */\n  handleElementChanged() {\n    removeChildren(this.element);\n    const element = this.getElement();\n    if (element) {\n      this.element.appendChild(element);\n    }\n  }\n\n  /**\n   * @protected\n   */\n  handleMapChanged() {\n    if (this.mapPostrenderListenerKey) {\n      this.element?.remove();\n      unlistenByKey(this.mapPostrenderListenerKey);\n      this.mapPostrenderListenerKey = null;\n    }\n    const map = this.getMap();\n    if (map) {\n      this.mapPostrenderListenerKey = listen(\n        map,\n        MapEventType.POSTRENDER,\n        this.render,\n        this,\n      );\n      this.updatePixelPosition();\n      const container = this.stopEvent\n        ? map.getOverlayContainerStopEvent()\n        : map.getOverlayContainer();\n      if (this.insertFirst) {\n        container.insertBefore(this.element, container.childNodes[0] || null);\n      } else {\n        container.appendChild(this.element);\n      }\n      this.performAutoPan();\n    }\n  }\n\n  /**\n   * @protected\n   */\n  render() {\n    this.updatePixelPosition();\n  }\n\n  /**\n   * @protected\n   */\n  handleOffsetChanged() {\n    this.updatePixelPosition();\n  }\n\n  /**\n   * @protected\n   */\n  handlePositionChanged() {\n    this.updatePixelPosition();\n    this.performAutoPan();\n  }\n\n  /**\n   * @protected\n   */\n  handlePositioningChanged() {\n    this.updatePixelPosition();\n  }\n\n  /**\n   * Set the DOM element to be associated with this overlay.\n   * @param {HTMLElement|undefined} element The Element containing the overlay.\n   * @observable\n   * @api\n   */\n  setElement(element) {\n    this.set(Property.ELEMENT, element);\n  }\n\n  /**\n   * Set the map to be associated with this overlay.\n   * @param {import(\"./Map.js\").default|null} map The map that the\n   * overlay is part of. Pass `null` to just remove the overlay from the current map.\n   * @observable\n   * @api\n   */\n  setMap(map) {\n    this.set(Property.MAP, map);\n  }\n\n  /**\n   * Set the offset for this overlay.\n   * @param {Array<number>} offset Offset.\n   * @observable\n   * @api\n   */\n  setOffset(offset) {\n    this.set(Property.OFFSET, offset);\n  }\n\n  /**\n   * Set the position for this overlay. If the position is `undefined` the\n   * overlay is hidden.\n   * @param {import(\"./coordinate.js\").Coordinate|undefined} position The spatial point that the overlay\n   *     is anchored at.\n   * @observable\n   * @api\n   */\n  setPosition(position) {\n    this.set(Property.POSITION, position);\n  }\n\n  /**\n   * Pan the map so that the overlay is entirely visible in the current viewport\n   * (if necessary) using the configured autoPan parameters\n   * @protected\n   */\n  performAutoPan() {\n    if (this.autoPan) {\n      this.panIntoView(this.autoPan);\n    }\n  }\n\n  /**\n   * Pan the map so that the overlay is entirely visible in the current viewport\n   * (if necessary).\n   * @param {PanIntoViewOptions} [panIntoViewOptions] Options for the pan action\n   * @api\n   */\n  panIntoView(panIntoViewOptions) {\n    const map = this.getMap();\n\n    if (!map || !map.getTargetElement() || !this.get(Property.POSITION)) {\n      return;\n    }\n\n    const mapRect = this.getRect(map.getTargetElement(), map.getSize());\n    const element = this.getElement();\n    const overlayRect = this.getRect(element, [\n      outerWidth(element),\n      outerHeight(element),\n    ]);\n\n    panIntoViewOptions = panIntoViewOptions || {};\n\n    const myMargin =\n      panIntoViewOptions.margin === undefined ? 20 : panIntoViewOptions.margin;\n    if (!containsExtent(mapRect, overlayRect)) {\n      // the overlay is not completely inside the viewport, so pan the map\n      const offsetLeft = overlayRect[0] - mapRect[0];\n      const offsetRight = mapRect[2] - overlayRect[2];\n      const offsetTop = overlayRect[1] - mapRect[1];\n      const offsetBottom = mapRect[3] - overlayRect[3];\n\n      const delta = [0, 0];\n      if (offsetLeft < 0) {\n        // move map to the left\n        delta[0] = offsetLeft - myMargin;\n      } else if (offsetRight < 0) {\n        // move map to the right\n        delta[0] = Math.abs(offsetRight) + myMargin;\n      }\n      if (offsetTop < 0) {\n        // move map up\n        delta[1] = offsetTop - myMargin;\n      } else if (offsetBottom < 0) {\n        // move map down\n        delta[1] = Math.abs(offsetBottom) + myMargin;\n      }\n\n      if (delta[0] !== 0 || delta[1] !== 0) {\n        const center = /** @type {import(\"./coordinate.js\").Coordinate} */ (\n          map.getView().getCenterInternal()\n        );\n        const centerPx = map.getPixelFromCoordinateInternal(center);\n        if (!centerPx) {\n          return;\n        }\n        const newCenterPx = [centerPx[0] + delta[0], centerPx[1] + delta[1]];\n\n        const panOptions = panIntoViewOptions.animation || {};\n        map.getView().animateInternal({\n          center: map.getCoordinateFromPixelInternal(newCenterPx),\n          duration: panOptions.duration,\n          easing: panOptions.easing,\n        });\n      }\n    }\n  }\n\n  /**\n   * Get the extent of an element relative to the document\n   * @param {HTMLElement} element The element.\n   * @param {import(\"./size.js\").Size} size The size of the element.\n   * @return {import(\"./extent.js\").Extent} The extent.\n   * @protected\n   */\n  getRect(element, size) {\n    const box = element.getBoundingClientRect();\n    const offsetX = box.left + window.pageXOffset;\n    const offsetY = box.top + window.pageYOffset;\n    return [offsetX, offsetY, offsetX + size[0], offsetY + size[1]];\n  }\n\n  /**\n   * Set the positioning for this overlay.\n   * @param {Positioning} positioning how the overlay is\n   *     positioned relative to its point on the map.\n   * @observable\n   * @api\n   */\n  setPositioning(positioning) {\n    this.set(Property.POSITIONING, positioning);\n  }\n\n  /**\n   * Modify the visibility of the element.\n   * @param {boolean} visible Element visibility.\n   * @protected\n   */\n  setVisible(visible) {\n    if (this.rendered.visible !== visible) {\n      this.element.style.display = visible ? '' : 'none';\n      this.rendered.visible = visible;\n    }\n  }\n\n  /**\n   * Update pixel position.\n   * @protected\n   */\n  updatePixelPosition() {\n    const map = this.getMap();\n    const position = this.getPosition();\n    if (!map || !map.isRendered() || !position) {\n      this.setVisible(false);\n      return;\n    }\n\n    const pixel = map.getPixelFromCoordinate(position);\n    const mapSize = map.getSize();\n    this.updateRenderedPosition(pixel, mapSize);\n  }\n\n  /**\n   * @param {import(\"./pixel.js\").Pixel} pixel The pixel location.\n   * @param {import(\"./size.js\").Size|undefined} mapSize The map size.\n   * @protected\n   */\n  updateRenderedPosition(pixel, mapSize) {\n    const style = this.element.style;\n    const offset = this.getOffset();\n\n    const positioning = this.getPositioning();\n\n    this.setVisible(true);\n\n    const x = `${pixel[0] + offset[0]}px`;\n    const y = `${pixel[1] + offset[1]}px`;\n    let posX = '0%';\n    let posY = '0%';\n    if (\n      positioning == 'bottom-right' ||\n      positioning == 'center-right' ||\n      positioning == 'top-right'\n    ) {\n      posX = '-100%';\n    } else if (\n      positioning == 'bottom-center' ||\n      positioning == 'center-center' ||\n      positioning == 'top-center'\n    ) {\n      posX = '-50%';\n    }\n    if (\n      positioning == 'bottom-left' ||\n      positioning == 'bottom-center' ||\n      positioning == 'bottom-right'\n    ) {\n      posY = '-100%';\n    } else if (\n      positioning == 'center-left' ||\n      positioning == 'center-center' ||\n      positioning == 'center-right'\n    ) {\n      posY = '-50%';\n    }\n    const transform = `translate(${posX}, ${posY}) translate(${x}, ${y})`;\n    if (this.rendered.transform_ != transform) {\n      this.rendered.transform_ = transform;\n      style.transform = transform;\n    }\n  }\n\n  /**\n   * returns the options this Overlay has been created with\n   * @return {Options} overlay options\n   */\n  getOptions() {\n    return this.options;\n  }\n}\n\nexport default Overlay;\n", "/**\n * @module ol/control/ScaleLine\n */\nimport {CLASS_UNSELECTABLE} from '../css.js';\nimport {METERS_PER_UNIT, getPointResolution} from '../proj.js';\nimport Control from './Control.js';\n\n/**\n * @type {string}\n */\nconst UNITS_PROP = 'units';\n\n/**\n * @typedef {'degrees' | 'imperial' | 'nautical' | 'metric' | 'us'} Units\n * Units for the scale line.\n */\n\n/**\n * @const\n * @type {Array<number>}\n */\nconst LEADING_DIGITS = [1, 2, 5];\n\n/**\n * @const\n * @type {number}\n */\nconst DEFAULT_DPI = 25.4 / 0.28;\n\n/***\n * @template Return\n * @typedef {import(\"../Observable.js\").OnSignature<import(\"../Observable.js\").EventTypes, import(\"../events/Event.js\").default, Return> &\n *   import(\"../Observable.js\").OnSignature<import(\"../ObjectEventType.js\").Types|\n *     'change:units', import(\"../Object.js\").ObjectEvent, Return> &\n *   import(\"../Observable.js\").CombinedOnSignature<import(\"../Observable.js\").EventTypes|import(\"../ObjectEventType.js\").Types\n *     |'change:units', Return>} ScaleLineOnSignature\n */\n\n/**\n * @typedef {Object} Options\n * @property {string} [className] CSS class name. The default is `ol-scale-bar` when configured with\n * `bar: true`. Otherwise the default is `ol-scale-line`.\n * @property {number} [minWidth=64] Minimum width in pixels at the OGC default dpi. The width will be\n * adjusted to match the dpi used.\n * @property {number} [maxWidth] Maximum width in pixels at the OGC default dpi. The width will be\n * adjusted to match the dpi used.\n * @property {function(import(\"../MapEvent.js\").default):void} [render] Function called when the control\n * should be re-rendered. This is called in a `requestAnimationFrame` callback.\n * @property {HTMLElement|string} [target] Specify a target if you want the control\n * to be rendered outside of the map's viewport.\n * @property {Units} [units='metric'] Units.\n * @property {boolean} [bar=false] Render scalebars instead of a line.\n * @property {number} [steps=4] Number of steps the scalebar should use. Use even numbers\n * for best results. Only applies when `bar` is `true`.\n * @property {boolean} [text=false] Render the text scale above of the scalebar. Only applies\n * when `bar` is `true`.\n * @property {number|undefined} [dpi=undefined] dpi of output device such as printer. Only applies\n * when `bar` is `true`. If undefined the OGC default screen pixel size of 0.28mm will be assumed.\n */\n\n/**\n * @classdesc\n * A control displaying rough y-axis distances, calculated for the center of the\n * viewport. For conformal projections (e.g. EPSG:3857, the default view\n * projection in OpenLayers), the scale is valid for all directions.\n * No scale line will be shown when the y-axis distance of a pixel at the\n * viewport center cannot be calculated in the view projection.\n * By default the scale line will show in the bottom left portion of the map,\n * but this can be changed by using the css selector `.ol-scale-line`.\n * When specifying `bar` as `true`, a scalebar will be rendered instead\n * of a scaleline.\n * For cartesian measurements of the scaleline, you need to set the\n * `getPointResolution` method of your projection to simply return the input\n * value, e.g. `projection.setGetPointResolution(r => r);`\n *\n * @api\n */\nclass ScaleLine extends Control {\n  /**\n   * @param {Options} [options] Scale line options.\n   */\n  constructor(options) {\n    options = options ? options : {};\n\n    const element = document.createElement('div');\n    element.style.pointerEvents = 'none';\n\n    super({\n      element: element,\n      render: options.render,\n      target: options.target,\n    });\n\n    /***\n     * @type {ScaleLineOnSignature<import(\"../events.js\").EventsKey>}\n     */\n    this.on;\n\n    /***\n     * @type {ScaleLineOnSignature<import(\"../events.js\").EventsKey>}\n     */\n    this.once;\n\n    /***\n     * @type {ScaleLineOnSignature<void>}\n     */\n    this.un;\n\n    const className =\n      options.className !== undefined\n        ? options.className\n        : options.bar\n          ? 'ol-scale-bar'\n          : 'ol-scale-line';\n\n    /**\n     * @private\n     * @type {HTMLElement}\n     */\n    this.innerElement_ = document.createElement('div');\n    this.innerElement_.className = className + '-inner';\n\n    this.element.className = className + ' ' + CLASS_UNSELECTABLE;\n    this.element.appendChild(this.innerElement_);\n\n    /**\n     * @private\n     * @type {?import(\"../View.js\").State}\n     */\n    this.viewState_ = null;\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.minWidth_ = options.minWidth !== undefined ? options.minWidth : 64;\n\n    /**\n     * @private\n     * @type {number|undefined}\n     */\n    this.maxWidth_ = options.maxWidth;\n\n    /**\n     * @private\n     * @type {boolean}\n     */\n    this.renderedVisible_ = false;\n\n    /**\n     * @private\n     * @type {number|undefined}\n     */\n    this.renderedWidth_ = undefined;\n\n    /**\n     * @private\n     * @type {string}\n     */\n    this.renderedHTML_ = '';\n\n    this.addChangeListener(UNITS_PROP, this.handleUnitsChanged_);\n\n    this.setUnits(options.units || 'metric');\n\n    /**\n     * @private\n     * @type {boolean}\n     */\n    this.scaleBar_ = options.bar || false;\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.scaleBarSteps_ = options.steps || 4;\n\n    /**\n     * @private\n     * @type {boolean}\n     */\n    this.scaleBarText_ = options.text || false;\n\n    /**\n     * @private\n     * @type {number|undefined}\n     */\n    this.dpi_ = options.dpi || undefined;\n  }\n\n  /**\n   * Return the units to use in the scale line.\n   * @return {Units} The units\n   * to use in the scale line.\n   * @observable\n   * @api\n   */\n  getUnits() {\n    return this.get(UNITS_PROP);\n  }\n\n  /**\n   * @private\n   */\n  handleUnitsChanged_() {\n    this.updateElement_();\n  }\n\n  /**\n   * Set the units to use in the scale line.\n   * @param {Units} units The units to use in the scale line.\n   * @observable\n   * @api\n   */\n  setUnits(units) {\n    this.set(UNITS_PROP, units);\n  }\n\n  /**\n   * Specify the dpi of output device such as printer.\n   * @param {number|undefined} dpi The dpi of output device.\n   * @api\n   */\n  setDpi(dpi) {\n    this.dpi_ = dpi;\n  }\n\n  /**\n   * @private\n   */\n  updateElement_() {\n    const viewState = this.viewState_;\n\n    if (!viewState) {\n      if (this.renderedVisible_) {\n        this.element.style.display = 'none';\n        this.renderedVisible_ = false;\n      }\n      return;\n    }\n\n    const center = viewState.center;\n    const projection = viewState.projection;\n    const units = this.getUnits();\n    const pointResolutionUnits = units == 'degrees' ? 'degrees' : 'm';\n    let pointResolution = getPointResolution(\n      projection,\n      viewState.resolution,\n      center,\n      pointResolutionUnits,\n    );\n\n    const minWidth =\n      (this.minWidth_ * (this.dpi_ || DEFAULT_DPI)) / DEFAULT_DPI;\n\n    const maxWidth =\n      this.maxWidth_ !== undefined\n        ? (this.maxWidth_ * (this.dpi_ || DEFAULT_DPI)) / DEFAULT_DPI\n        : undefined;\n\n    let nominalCount = minWidth * pointResolution;\n    let suffix = '';\n    if (units == 'degrees') {\n      const metersPerDegree = METERS_PER_UNIT.degrees;\n      nominalCount *= metersPerDegree;\n      if (nominalCount < metersPerDegree / 60) {\n        suffix = '\\u2033'; // seconds\n        pointResolution *= 3600;\n      } else if (nominalCount < metersPerDegree) {\n        suffix = '\\u2032'; // minutes\n        pointResolution *= 60;\n      } else {\n        suffix = '\\u00b0'; // degrees\n      }\n    } else if (units == 'imperial') {\n      if (nominalCount < 0.9144) {\n        suffix = 'in';\n        pointResolution /= 0.0254;\n      } else if (nominalCount < 1609.344) {\n        suffix = 'ft';\n        pointResolution /= 0.3048;\n      } else {\n        suffix = 'mi';\n        pointResolution /= 1609.344;\n      }\n    } else if (units == 'nautical') {\n      pointResolution /= 1852;\n      suffix = 'NM';\n    } else if (units == 'metric') {\n      if (nominalCount < 1e-6) {\n        suffix = 'nm';\n        pointResolution *= 1e9;\n      } else if (nominalCount < 0.001) {\n        suffix = '\u03BCm';\n        pointResolution *= 1000000;\n      } else if (nominalCount < 1) {\n        suffix = 'mm';\n        pointResolution *= 1000;\n      } else if (nominalCount < 1000) {\n        suffix = 'm';\n      } else {\n        suffix = 'km';\n        pointResolution /= 1000;\n      }\n    } else if (units == 'us') {\n      if (nominalCount < 0.9144) {\n        suffix = 'in';\n        pointResolution *= 39.37;\n      } else if (nominalCount < 1609.344) {\n        suffix = 'ft';\n        pointResolution /= 0.30480061;\n      } else {\n        suffix = 'mi';\n        pointResolution /= 1609.3472;\n      }\n    } else {\n      throw new Error('Invalid units');\n    }\n\n    let i = 3 * Math.floor(Math.log(minWidth * pointResolution) / Math.log(10));\n    let count, width, decimalCount;\n    let previousCount = 0;\n    let previousWidth, previousDecimalCount;\n    while (true) {\n      decimalCount = Math.floor(i / 3);\n      const decimal = Math.pow(10, decimalCount);\n      count = LEADING_DIGITS[((i % 3) + 3) % 3] * decimal;\n      width = Math.round(count / pointResolution);\n      if (isNaN(width)) {\n        this.element.style.display = 'none';\n        this.renderedVisible_ = false;\n        return;\n      }\n      if (maxWidth !== undefined && width >= maxWidth) {\n        count = previousCount;\n        width = previousWidth;\n        decimalCount = previousDecimalCount;\n        break;\n      } else if (width >= minWidth) {\n        break;\n      }\n      previousCount = count;\n      previousWidth = width;\n      previousDecimalCount = decimalCount;\n      ++i;\n    }\n    const html = this.scaleBar_\n      ? this.createScaleBar(width, count, suffix)\n      : count.toFixed(decimalCount < 0 ? -decimalCount : 0) + ' ' + suffix;\n\n    if (this.renderedHTML_ != html) {\n      this.innerElement_.innerHTML = html;\n      this.renderedHTML_ = html;\n    }\n\n    if (this.renderedWidth_ != width) {\n      this.innerElement_.style.width = width + 'px';\n      this.renderedWidth_ = width;\n    }\n\n    if (!this.renderedVisible_) {\n      this.element.style.display = '';\n      this.renderedVisible_ = true;\n    }\n  }\n\n  /**\n   * @private\n   * @param {number} width The current width of the scalebar.\n   * @param {number} scale The current scale.\n   * @param {string} suffix The suffix to append to the scale text.\n   * @return {string} The stringified HTML of the scalebar.\n   */\n  createScaleBar(width, scale, suffix) {\n    const resolutionScale = this.getScaleForResolution();\n    const mapScale =\n      resolutionScale < 1\n        ? Math.round(1 / resolutionScale).toLocaleString() + ' : 1'\n        : '1 : ' + Math.round(resolutionScale).toLocaleString();\n    const steps = this.scaleBarSteps_;\n    const stepWidth = width / steps;\n    const scaleSteps = [this.createMarker('absolute')];\n    for (let i = 0; i < steps; ++i) {\n      const cls =\n        i % 2 === 0 ? 'ol-scale-singlebar-odd' : 'ol-scale-singlebar-even';\n      scaleSteps.push(\n        '<div>' +\n          '<div ' +\n          `class=\"ol-scale-singlebar ${cls}\" ` +\n          `style=\"width: ${stepWidth}px;\"` +\n          '>' +\n          '</div>' +\n          this.createMarker('relative') +\n          // render text every second step, except when only 2 steps\n          (i % 2 === 0 || steps === 2\n            ? this.createStepText(i, width, false, scale, suffix)\n            : '') +\n          '</div>',\n      );\n    }\n    // render text at the end\n    scaleSteps.push(this.createStepText(steps, width, true, scale, suffix));\n\n    const scaleBarText = this.scaleBarText_\n      ? `<div class=\"ol-scale-text\" style=\"width: ${width}px;\">` +\n        mapScale +\n        '</div>'\n      : '';\n    return scaleBarText + scaleSteps.join('');\n  }\n\n  /**\n   * Creates a marker at given position\n   * @param {'absolute'|'relative'} position The position, absolute or relative\n   * @return {string} The stringified div containing the marker\n   */\n  createMarker(position) {\n    const top = position === 'absolute' ? 3 : -10;\n    return (\n      '<div ' +\n      'class=\"ol-scale-step-marker\" ' +\n      `style=\"position: ${position}; top: ${top}px;\"` +\n      '></div>'\n    );\n  }\n\n  /**\n   * Creates the label for a marker marker at given position\n   * @param {number} i The iterator\n   * @param {number} width The width the scalebar will currently use\n   * @param {boolean} isLast Flag indicating if we add the last step text\n   * @param {number} scale The current scale for the whole scalebar\n   * @param {string} suffix The suffix for the scale\n   * @return {string} The stringified div containing the step text\n   */\n  createStepText(i, width, isLast, scale, suffix) {\n    const length =\n      i === 0 ? 0 : Math.round((scale / this.scaleBarSteps_) * i * 100) / 100;\n    const lengthString = length + (i === 0 ? '' : ' ' + suffix);\n    const margin = i === 0 ? -3 : (width / this.scaleBarSteps_) * -1;\n    const minWidth = i === 0 ? 0 : (width / this.scaleBarSteps_) * 2;\n    return (\n      '<div ' +\n      'class=\"ol-scale-step-text\" ' +\n      'style=\"' +\n      `margin-left: ${margin}px;` +\n      `text-align: ${i === 0 ? 'left' : 'center'};` +\n      `min-width: ${minWidth}px;` +\n      `left: ${isLast ? width + 'px' : 'unset'};` +\n      '\">' +\n      lengthString +\n      '</div>'\n    );\n  }\n\n  /**\n   * Returns the appropriate scale for the given resolution and units.\n   * @return {number} The appropriate scale.\n   */\n  getScaleForResolution() {\n    const resolution = getPointResolution(\n      this.viewState_.projection,\n      this.viewState_.resolution,\n      this.viewState_.center,\n      'm',\n    );\n    const dpi = this.dpi_ || DEFAULT_DPI;\n    const inchesPerMeter = 1000 / 25.4;\n    return resolution * inchesPerMeter * dpi;\n  }\n\n  /**\n   * Update the scale line element.\n   * @param {import(\"../MapEvent.js\").default} mapEvent Map event.\n   * @override\n   */\n  render(mapEvent) {\n    const frameState = mapEvent.frameState;\n    if (!frameState) {\n      this.viewState_ = null;\n    } else {\n      this.viewState_ = frameState.viewState;\n    }\n    this.updateElement_();\n  }\n}\n\nexport default ScaleLine;\n", "/**\n * map.js \u2014 inicializace OpenLayers mapy: view (EPSG:3857), basemapy,\n * ovl\u00E1dac\u00ED prvky (zoom, m\u011B\u0159\u00EDtko, sou\u0159adnice kurzoru) a \"Zoom to all\".\n */\nimport Map from 'ol/Map.js';\nimport View from 'ol/View.js';\nimport TileLayer from 'ol/layer/Tile.js';\nimport OSM from 'ol/source/OSM.js';\nimport XYZ from 'ol/source/XYZ.js';\nimport { defaults as defaultControls, ScaleLine, MousePosition, Zoom } from 'ol/control.js';\nimport { createStringXY } from 'ol/coordinate.js';\nimport { fromLonLat, toLonLat, transformExtent } from 'ol/proj.js';\n\nimport { basemapFilter, basemapLookControlsHtml, normalizeBasemapLook } from './basemap-look.js';\n\n/** Satelitn\u00ED podklad bez kl\u00ED\u010De \u2014 jen z\u00E1loha, kdy\u017E bootstrap nic nepo\u0161le. */\nconst IMAGERY_FALLBACK = {\n    url: 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',\n    attribution: 'Tiles &copy; Esri \u2014 Source: Esri, Vantor, Earthstar Geographics, and the GIS User Community',\n};\n\n/** T\u0159\u00EDda kontejneru vrstev podkladu. Vlastn\u00ED t\u0159\u00EDda = vlastn\u00ED canvas: OL\n * jinak kresl\u00ED dal\u0161\u00ED vrstvu stejn\u00E9 t\u0159\u00EDdy do t\u00E9ho\u017E canvasu a filtr \u010Dernob\u00EDle\n * by zas\u00E1hl i data nad podkladem. */\nconst BASEMAP_CLASS = 'ol-layer map-basemap';\n\n/** Definice dostupn\u00FDch podkladov\u00FDch map. Kl\u00ED\u010D odpov\u00EDd\u00E1 `basemap` v Map.config.\n * `options.imagery` = `{url, attribution}` satelitu z bootstrapu (s kl\u00ED\u010Dem Esri\n * podle prost\u0159ed\u00ED, `apps.maps.services.imagery_basemap`). */\nexport function createBasemaps({ imagery } = {}) {\n    const satellite = imagery?.url ? imagery : IMAGERY_FALLBACK;\n    const basemaps = {\n        osm: new TileLayer({\n            className: BASEMAP_CLASS,\n            source: new OSM(),\n            visible: true,\n            properties: { basemapKey: 'osm', basemapTitle: 'OpenStreetMap' },\n        }),\n        satellite: new TileLayer({\n            className: BASEMAP_CLASS,\n            source: new XYZ({\n                url: satellite.url,\n                // Text podle slu\u017Eby (Copyright Text vrstvy World_Imagery, 11/2026).\n                attributions: satellite.attribution,\n                maxZoom: 19,\n                // P\u016Fvod str\u00E1nky (ne cel\u00E1 adresa) i ciz\u00EDm dla\u017Edic\u00EDm \u2014 dokument m\u00E1\n                // `Referrer-Policy: same-origin`; poskytovatel\u00E9 s kl\u00ED\u010Dem omezen\u00FDm\n                // na dom\u00E9nu podle n\u011Bj po\u017Eadavek poznaj\u00ED. OSM to m\u00E1 v\u00FDchoz\u00ED.\n                referrerPolicy: 'strict-origin-when-cross-origin',\n                // Kv\u016Fli exportu mapy do PNG/JPG (export.js) \u2014 bez CORS by byl\n                // canvas \"tainted\" a toDataURL by selhal. OSM to m\u00E1 v\u00FDchoz\u00ED.\n                crossOrigin: 'anonymous',\n            }),\n            visible: false,\n            properties: { basemapKey: 'satellite', basemapTitle: 'Esri World Imagery' },\n        }),\n        topo: new TileLayer({\n            className: BASEMAP_CLASS,\n            source: new XYZ({\n                url: 'https://{a-c}.tile.opentopomap.org/{z}/{x}/{y}.png',\n                attributions: 'Map data: &copy; OpenStreetMap contributors, SRTM | Map style: &copy; OpenTopoMap (CC-BY-SA)',\n                maxZoom: 17,\n                crossOrigin: 'anonymous',\n                referrerPolicy: 'strict-origin-when-cross-origin',\n            }),\n            visible: false,\n            properties: { basemapKey: 'topo', basemapTitle: 'OpenTopoMap' },\n        }),\n        none: new TileLayer({\n            className: BASEMAP_CLASS,\n            source: null,\n            visible: false,\n            properties: { basemapKey: 'none', basemapTitle: 'No basemap' },\n        }),\n    };\n    Object.values(basemaps).forEach((layer) => {\n        layer.on('prerender', applyBasemapFilter);\n    });\n    return basemaps;\n}\n\n/** \u010Cernob\u00EDle jako CSS filtr kontejneru vrstvy \u2014 export.js ho p\u0159enese do\n * obr\u00E1zku (PNG/JPG, miniatura mapy). Pr\u016Fhlednost \u0159e\u0161\u00ED OL s\u00E1m (opacity). */\nfunction applyBasemapFilter(event) {\n    const container = event.context?.canvas?.parentElement;\n    if (!container) return;\n    const filter = basemapFilter({ gray: event.target.get('basemapGray') === true });\n    if (container.style.filter !== filter) container.style.filter = filter;\n}\n\n/** Nastav\u00ED vzhled podkladu (`{opacity, gray}`, viz basemap-look.js) v\u0161em podklad\u016Fm. */\nexport function applyBasemapLook(basemaps, look) {\n    const { opacity, gray } = normalizeBasemapLook(look);\n    Object.values(basemaps).forEach((layer) => {\n        layer.setOpacity(opacity);\n        if (layer.get('basemapGray') !== gray) {\n            layer.set('basemapGray', gray);\n            layer.changed();\n        }\n    });\n}\n\n/** Nastav\u00ED viditelnost p\u0159esn\u011B jednoho basemapu podle kl\u00ED\u010De. */\nexport function setBasemap(basemaps, key) {\n    Object.entries(basemaps).forEach(([basemapKey, layer]) => layer.setVisible(basemapKey === key));\n}\n\n/** Pohled bez ulo\u017Een\u00E9ho v\u00FD\u0159ezu a bez zn\u00E1m\u00E9 zem\u011B: cel\u00FD sv\u011Bt. */\nconst WORLD_VIEW = { center: [10, 25], zoom: 2.4 };\n\n/**\n * Vytvo\u0159\u00ED OL mapu a view v EPSG:3857 podle ulo\u017Een\u00E9ho `config.view`. Nov\u00E1 mapa\n * v\u00FD\u0159ez nem\u00E1 \u2014 nastav\u00ED se na `defaultExtent` (`[west, south, east, north]` ve\n * WGS 84: zem\u011B, kde u\u017Eivatel s daty pracuje), jinak na sv\u011Bt.\n */\nexport function createMap(target, config, basemaps, { defaultExtent = null } = {}) {\n    const view = new View({\n        center: fromLonLat(config.view?.center || WORLD_VIEW.center),\n        zoom: config.view?.zoom ?? WORLD_VIEW.zoom,\n        multiWorld: false,\n    });\n\n    const map = new Map({\n        target,\n        view,\n        layers: Object.values(basemaps),\n        controls: defaultControls({ zoom: false, attribution: true }),\n    });\n\n    setBasemap(basemaps, config.basemap || 'osm');\n    applyBasemapLook(basemaps, config.basemapLook);\n\n    if (!config.view && Array.isArray(defaultExtent) && defaultExtent.length === 4) {\n        const size = map.getSize();\n        if (size && size[0] > 0 && size[1] > 0) {\n            view.fit(transformExtent(defaultExtent, 'EPSG:4326', 'EPSG:3857'), {\n                size, padding: [24, 24, 24, 24], maxZoom: 12,\n            });\n        }\n    }\n\n    return map;\n}\n\n/** P\u0159id\u00E1 vlastn\u00ED ovl\u00E1dac\u00ED prvky: zoom, ScaleLine, MousePosition (WGS84). */\nexport function addStandardControls(map, mousePositionEl) {\n    map.addControl(new Zoom());\n    map.addControl(new ScaleLine({ units: 'metric' }));\n    map.addControl(\n        new MousePosition({\n            coordinateFormat: createStringXY(5),\n            projection: 'EPSG:4326',\n            target: mousePositionEl || undefined,\n            className: 'map-mouse-position',\n            // Kurzor mimo mapu: pr\u00E1zdn\u00FD obsah (r\u00E1me\u010Dek se pak skryje stylem).\n            placeholder: '',\n        }),\n    );\n}\n\n/** P\u0159ibl\u00ED\u017E\u00ED mapu na sjednocen\u00FD extent (v sou\u0159adnic\u00EDch mapy, tj. EPSG:3857). */\nexport function zoomToExtent(map, extent, options = {}) {\n    if (!extent) return;\n    map.getView().fit(extent, {\n        padding: options.padding || [40, 40, 40, 40],\n        duration: options.duration ?? 400,\n        maxZoom: options.maxZoom ?? 19,\n    });\n}\n\n/** Vr\u00E1t\u00ED aktu\u00E1ln\u00ED pohled mapy ve form\u00E1tu Map.config.view (lon/lat st\u0159ed). */\nexport function readViewConfig(map) {\n    const view = map.getView();\n    const center = view.getCenter();\n    return {\n        center: center ? toLonLat(center) : WORLD_VIEW.center,\n        zoom: view.getZoom(),\n    };\n}\n\n/** Jednoduch\u00E1 \"miniatura\" podkladu \u2014 barevn\u00FD SVG n\u00E1hled bez z\u00E1vislosti na\n * extern\u00EDch obr\u00E1zkov\u00FDch assetech (d\u00E1 se kdykoliv nahradit skute\u010Dn\u00FDm sn\u00EDmkem). */\nfunction basemapThumbnail(key) {\n    const gradients = {\n        osm: 'from-slate-200 to-slate-400',\n        satellite: 'from-emerald-800 to-emerald-950',\n        topo: 'from-amber-200 to-amber-500',\n        none: 'from-white to-slate-100',\n    };\n    return `<span class=\"block h-8 w-12 rounded-md bg-gradient-to-br ${gradients[key] || gradients.osm} ring-1 ring-inset ring-slate-200\"></span>`;\n}\n\n/**\n * Vykresl\u00ED p\u0159ep\u00EDna\u010D podkladov\u00FDch map (miniatury + n\u00E1zev) a pod n\u00EDm vzhled\n * podkladu (pr\u016Fhlednost, \u010Dernob\u00EDle) do dan\u00E9ho kontejneru. `onLookChange`\n * dostane cel\u00FD nov\u00FD vzhled `{opacity, gray}` p\u0159i ka\u017Ed\u00E9m posunu posuvn\u00EDku.\n */\nexport function renderBasemapSwitcher(container, basemaps, activeKey, onChange, { look = null, onLookChange = null } = {}) {\n    container.innerHTML = '';\n    Object.entries(basemaps).forEach(([key, layer]) => {\n        const title = layer.get('basemapTitle');\n        const btn = document.createElement('button');\n        btn.type = 'button';\n        btn.className = `flex flex-col items-center gap-y-1 rounded-lg p-1.5 text-[11px] font-medium transition-colors ${key === activeKey ? 'bg-brand-50 text-brand-700 ring-1 ring-inset ring-brand-200' : 'text-slate-600 hover:bg-slate-100'}`;\n        btn.innerHTML = `${basemapThumbnail(key)}<span>${title}</span>`;\n        btn.addEventListener('click', () => onChange(key));\n        container.appendChild(btn);\n    });\n    if (!onLookChange) return;\n    container.insertAdjacentHTML('beforeend', basemapLookControlsHtml(look, { disabled: activeKey === 'none' }));\n    const controls = container.querySelector('[data-role=\"basemap-look\"]');\n    const range = controls.querySelector('[data-role=\"basemap-opacity\"]');\n    const gray = controls.querySelector('[data-role=\"basemap-gray\"]');\n    const emit = () => onLookChange({ opacity: Number(range.value) / 100, gray: gray.checked });\n    range.addEventListener('input', emit);\n    gray.addEventListener('change', emit);\n    // Klik do ovl\u00E1d\u00E1n\u00ED nab\u00EDdku nezav\u0159e: Preline (desktop) i nab\u00EDdka \u201EMore\u201C\n    // (telefon) zav\u00EDraj\u00ED na kliknut\u00ED kamkoli; miniatura podkladu ji zav\u0159e d\u00E1l.\n    controls.addEventListener('click', (event) => event.stopPropagation());\n}\n\n/** Srovn\u00E1 ovl\u00E1d\u00E1n\u00ED vzhledu v kontejneru s `look` (druh\u00FD p\u0159ep\u00EDna\u010D \u2014 desktop/telefon). */\nexport function syncBasemapLookControls(container, look) {\n    const { opacity, gray } = normalizeBasemapLook(look);\n    const percent = Math.round(opacity * 100);\n    const range = container.querySelector('[data-role=\"basemap-opacity\"]');\n    if (range && Number(range.value) !== percent) range.value = String(percent);\n    const label = container.querySelector('[data-role=\"basemap-opacity-value\"]');\n    if (label) label.textContent = `${percent} %`;\n    const toggle = container.querySelector('[data-role=\"basemap-gray\"]');\n    if (toggle && toggle.checked !== gray) toggle.checked = gray;\n}\n", "/**\n * sample-maps.js \u2014 nab\u00EDdka uk\u00E1zkov\u00FDch map v pr\u00E1zdn\u00E9m panelu vrstev.\n *\n * Nov\u00E1 (neulo\u017Een\u00E1) mapa bez vrstev uk\u00E1\u017Ee pod \u201ENo layers yet\u201C uk\u00E1zkov\u00E9 mapy\n * (GET /map/api/samples/, apps.maps.samples): jedn\u00EDm klikem se otev\u0159e hotov\u00E1\n * kompozice, kterou si u\u017Eivatel prohl\u00E9dne a m\u016F\u017Ee ulo\u017Eit jako svou kopii.\n * Nab\u00EDdku vyp\u00EDn\u00E1 p\u0159edvolba `show_samples` (`bootstrap.showSamples`); sd\u00EDlen\u00FD\n * odkaz a ulo\u017Een\u00E1 mapa ji nemaj\u00ED. Seznam se na\u010Dte jednou (m\u011Bn\u00ED se jen s nasazen\u00EDm).\n */\nimport { apiFetch } from './utils.js';\n\nlet samplesPromise = null;\n\n/** Uk\u00E1zkov\u00E9 mapy z API (jednou za b\u011Bh str\u00E1nky; chyba = pr\u00E1zdn\u00E1 nab\u00EDdka). */\nexport function loadSampleMaps(ctx) {\n    if (!samplesPromise) {\n        samplesPromise = apiFetch(`${ctx.bootstrap.apiBase}/samples/`)\n            .then((result) => result?.samples || [])\n            .catch(() => []);\n    }\n    return samplesPromise;\n}\n\nfunction escapeHtml(value) {\n    return String(value ?? '')\n        .replaceAll('&', '&amp;')\n        .replaceAll('<', '&lt;')\n        .replaceAll('>', '&gt;')\n        .replaceAll('\"', '&quot;');\n}\n\n/** M\u00E1 pr\u00E1zdn\u00FD panel vrstev nab\u00EDdnout uk\u00E1zkov\u00E9 mapy? */\nexport function offersSampleMaps(ctx) {\n    return Boolean(ctx.bootstrap.showSamples) && !ctx.state.mapId && !ctx.bootstrap.sharedView;\n}\n\n/** Dopln\u00ED do `container` (pr\u00E1zdn\u00FD panel vrstev) seznam uk\u00E1zkov\u00FDch map. */\nexport async function renderSampleMapsHint(ctx, container) {\n    const maps = await loadSampleMaps(ctx);\n    // Mezit\u00EDm mohla p\u0159ib\u00FDt vrstva (panel se p\u0159ekreslil) \u2014 nab\u00EDdka u\u017E nepat\u0159\u00ED.\n    if (!maps.length || !container.isConnected || ctx.state.layers.length > 0 || !offersSampleMaps(ctx)) return;\n    if (container.querySelector('[data-role=\"sample-maps-hint\"]')) return;\n    const box = document.createElement('div');\n    box.dataset.role = 'sample-maps-hint';\n    box.className = 'mx-1 mt-2 border-t border-slate-100 pt-5';\n    box.innerHTML = `\n        <p class=\"px-1 text-xs font-semibold uppercase tracking-wide text-slate-500\">Or explore a sample map</p>\n        <div class=\"mt-2 space-y-1.5\">\n            ${maps.map((m) => `\n            <a href=\"${escapeHtml(m.url)}\" data-sample-url=\"${escapeHtml(m.url)}\"\n               class=\"flex w-full items-center gap-x-3 rounded-lg border border-slate-200 bg-white p-2 text-left hover:border-brand-300 hover:bg-brand-50/40\">\n                <span class=\"flex h-12 w-16 flex-none items-center justify-center overflow-hidden rounded-md bg-slate-100\">\n                    ${m.image_url ? `<img src=\"${escapeHtml(m.image_url)}\" alt=\"\" class=\"h-full w-full object-cover\" loading=\"lazy\">` : ''}\n                </span>\n                <span class=\"min-w-0 flex-1\">\n                    <span class=\"block truncate text-sm font-medium text-slate-800\">${escapeHtml(m.title)}</span>\n                    <span class=\"block truncate text-xs text-slate-400\">${escapeHtml(m.teaser || m.description)}</span>\n                </span>\n            </a>`).join('')}\n        </div>`;\n    box.addEventListener('click', (event) => {\n        const link = event.target.closest('[data-sample-url]');\n        if (!link) return;\n        event.preventDefault();\n        const go = () => window.location.assign(link.dataset.sampleUrl);\n        // Rozkreslen\u00E1 mapa bez vrstev (kresby, podklad) \u2014 hl\u00EDd\u00E1n\u00ED neulo\u017Een\u00FDch zm\u011Bn.\n        if (ctx.guard?.needsGuard()) {\n            ctx.guard.guardNavigation(go);\n        } else {\n            go();\n        }\n    });\n    container.appendChild(box);\n}\n", "/**\n * @module ol/resolution\n */\n\n/**\n * @typedef {number|Array<number>} ResolutionLike\n */\n\n/**\n * @param {ResolutionLike} resolution Resolution.\n * @return {number} Resolution.\n */\nexport function fromResolutionLike(resolution) {\n  if (Array.isArray(resolution)) {\n    return Math.min(...resolution);\n  }\n  return resolution;\n}\n", "/**\n * @module ol/reproj/Image\n */\n\nimport ImageWrapper from '../Image.js';\nimport ImageState from '../ImageState.js';\nimport {listen, unlistenByKey} from '../events.js';\nimport EventType from '../events/EventType.js';\nimport {\n  getCenter,\n  getHeight,\n  getIntersection,\n  getWidth,\n  isEmpty,\n} from '../extent.js';\nimport {\n  calculateSourceResolution,\n  render as renderReprojected,\n} from '../reproj.js';\nimport {fromResolutionLike} from '../resolution.js';\nimport Triangulation from './Triangulation.js';\nimport {ERROR_THRESHOLD} from './common.js';\n\n/**\n * @typedef {function(import(\"../extent.js\").Extent, number, number) : import(\"../Image.js\").default} FunctionType\n */\n\n/**\n * @classdesc\n * Class encapsulating single reprojected image.\n * See {@link module:ol/source/Image~ImageSource}.\n */\nclass ReprojImage extends ImageWrapper {\n  /**\n   * @param {import(\"../proj/Projection.js\").default} sourceProj Source projection (of the data).\n   * @param {import(\"../proj/Projection.js\").default} targetProj Target projection.\n   * @param {import(\"../extent.js\").Extent} targetExtent Target extent.\n   * @param {number} targetResolution Target resolution.\n   * @param {number} pixelRatio Pixel ratio.\n   * @param {FunctionType} getImageFunction\n   *     Function returning source images (extent, resolution, pixelRatio).\n   * @param {boolean} interpolate Use linear interpolation when resampling.\n   */\n  constructor(\n    sourceProj,\n    targetProj,\n    targetExtent,\n    targetResolution,\n    pixelRatio,\n    getImageFunction,\n    interpolate,\n  ) {\n    let maxSourceExtent = sourceProj.getExtent();\n    if (maxSourceExtent && sourceProj.canWrapX()) {\n      maxSourceExtent = maxSourceExtent.slice();\n      maxSourceExtent[0] = -Infinity;\n      maxSourceExtent[2] = Infinity;\n    }\n    let maxTargetExtent = targetProj.getExtent();\n    if (maxTargetExtent && targetProj.canWrapX()) {\n      maxTargetExtent = maxTargetExtent.slice();\n      maxTargetExtent[0] = -Infinity;\n      maxTargetExtent[2] = Infinity;\n    }\n\n    const limitedTargetExtent = maxTargetExtent\n      ? getIntersection(targetExtent, maxTargetExtent)\n      : targetExtent;\n\n    const targetCenter = getCenter(limitedTargetExtent);\n    const sourceResolution = calculateSourceResolution(\n      sourceProj,\n      targetProj,\n      targetCenter,\n      targetResolution,\n    );\n\n    const errorThresholdInPixels = ERROR_THRESHOLD;\n\n    const triangulation = new Triangulation(\n      sourceProj,\n      targetProj,\n      limitedTargetExtent,\n      maxSourceExtent,\n      sourceResolution * errorThresholdInPixels,\n      targetResolution,\n    );\n\n    const sourceExtent = triangulation.calculateSourceExtent();\n    const sourceImage = isEmpty(sourceExtent)\n      ? null\n      : getImageFunction(sourceExtent, sourceResolution, pixelRatio);\n    const state = sourceImage ? ImageState.IDLE : ImageState.EMPTY;\n    const sourcePixelRatio = sourceImage ? sourceImage.getPixelRatio() : 1;\n\n    super(targetExtent, targetResolution, sourcePixelRatio, state);\n\n    /**\n     * @private\n     * @type {import(\"../proj/Projection.js\").default}\n     */\n    this.targetProj_ = targetProj;\n\n    /**\n     * @private\n     * @type {import(\"../extent.js\").Extent}\n     */\n    this.maxSourceExtent_ = maxSourceExtent;\n\n    /**\n     * @private\n     * @type {!import(\"./Triangulation.js\").default}\n     */\n    this.triangulation_ = triangulation;\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.targetResolution_ = targetResolution;\n\n    /**\n     * @private\n     * @type {import(\"../extent.js\").Extent}\n     */\n    this.targetExtent_ = targetExtent;\n\n    /**\n     * @private\n     * @type {import(\"../Image.js\").default}\n     */\n    this.sourceImage_ = sourceImage;\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.sourcePixelRatio_ = sourcePixelRatio;\n\n    /**\n     * @private\n     * @type {boolean}\n     */\n    this.interpolate_ = interpolate;\n\n    /**\n     * @private\n     * @type {HTMLCanvasElement|OffscreenCanvas}\n     */\n    this.canvas_ = null;\n\n    /**\n     * @private\n     * @type {?import(\"../events.js\").EventsKey}\n     */\n    this.sourceListenerKey_ = null;\n  }\n\n  /**\n   * Clean up.\n   * @override\n   */\n  disposeInternal() {\n    if (this.state == ImageState.LOADING) {\n      this.unlistenSource_();\n    }\n    super.disposeInternal();\n  }\n\n  /**\n   * @return {HTMLCanvasElement|OffscreenCanvas} Image.\n   * @override\n   */\n  getImage() {\n    return this.canvas_;\n  }\n\n  /**\n   * @return {import(\"../proj/Projection.js\").default} Projection.\n   */\n  getProjection() {\n    return this.targetProj_;\n  }\n\n  /**\n   * @private\n   */\n  reproject_() {\n    const sourceState = this.sourceImage_.getState();\n    if (sourceState == ImageState.LOADED) {\n      const width = getWidth(this.targetExtent_) / this.targetResolution_;\n      const height = getHeight(this.targetExtent_) / this.targetResolution_;\n      this.canvas_ = renderReprojected(\n        width,\n        height,\n        this.sourcePixelRatio_,\n        fromResolutionLike(this.sourceImage_.getResolution()),\n        this.maxSourceExtent_,\n        this.targetResolution_,\n        this.targetExtent_,\n        this.triangulation_,\n        [\n          {\n            extent: this.sourceImage_.getExtent(),\n            image: this.sourceImage_.getImage(),\n          },\n        ],\n        0,\n        undefined,\n        this.interpolate_,\n        true,\n      );\n    }\n    this.state = sourceState;\n    this.changed();\n  }\n\n  /**\n   * Load not yet loaded URI.\n   * @override\n   */\n  load() {\n    if (this.state == ImageState.IDLE) {\n      this.state = ImageState.LOADING;\n      this.changed();\n\n      const sourceState = this.sourceImage_.getState();\n      if (sourceState == ImageState.LOADED || sourceState == ImageState.ERROR) {\n        this.reproject_();\n      } else {\n        this.sourceListenerKey_ = listen(\n          this.sourceImage_,\n          EventType.CHANGE,\n          (e) => {\n            const sourceState = this.sourceImage_.getState();\n            if (\n              sourceState == ImageState.LOADED ||\n              sourceState == ImageState.ERROR\n            ) {\n              this.unlistenSource_();\n              this.reproject_();\n            }\n          },\n        );\n        this.sourceImage_.load();\n      }\n    }\n  }\n\n  /**\n   * @private\n   */\n  unlistenSource_() {\n    unlistenByKey(\n      /** @type {!import(\"../events.js\").EventsKey} */ (\n        this.sourceListenerKey_\n      ),\n    );\n    this.sourceListenerKey_ = null;\n  }\n}\n\nexport default ReprojImage;\n", "/**\n * @module ol/source/Image\n */\nimport ImageWrapper from '../Image.js';\nimport ImageState from '../ImageState.js';\nimport {linearFindNearest} from '../array.js';\nimport Event from '../events/Event.js';\nimport EventType from '../events/EventType.js';\nimport {\n  containsExtent,\n  equals,\n  getCenter,\n  getForViewAndSize,\n  getHeight,\n  getWidth,\n} from '../extent.js';\nimport {ceil} from '../math.js';\nimport {equivalent} from '../proj.js';\nimport ReprojImage from '../reproj/Image.js';\nimport {fromResolutionLike} from '../resolution.js';\nimport Source from './Source.js';\nimport {DECIMALS} from './common.js';\n\n/**\n * @enum {string}\n */\nexport const ImageSourceEventType = {\n  /**\n   * Triggered when an image starts loading.\n   * @event module:ol/source/Image.ImageSourceEvent#imageloadstart\n   * @api\n   */\n  IMAGELOADSTART: 'imageloadstart',\n\n  /**\n   * Triggered when an image finishes loading.\n   * @event module:ol/source/Image.ImageSourceEvent#imageloadend\n   * @api\n   */\n  IMAGELOADEND: 'imageloadend',\n\n  /**\n   * Triggered if image loading results in an error.\n   * @event module:ol/source/Image.ImageSourceEvent#imageloaderror\n   * @api\n   */\n  IMAGELOADERROR: 'imageloaderror',\n};\n\n/**\n * @typedef {'imageloadend'|'imageloaderror'|'imageloadstart'} ImageSourceEventTypes\n */\n\n/**\n * @classdesc\n * Events emitted by {@link module:ol/source/Image~ImageSource} instances are instances of this\n * type.\n */\nexport class ImageSourceEvent extends Event {\n  /**\n   * @param {string} type Type.\n   * @param {import(\"../Image.js\").default} image The image.\n   */\n  constructor(type, image) {\n    super(type);\n\n    /**\n     * The image related to the event.\n     * @type {import(\"../Image.js\").default}\n     * @api\n     */\n    this.image = image;\n  }\n}\n\n/***\n * @template Return\n * @typedef {import(\"../Observable.js\").OnSignature<import(\"../Observable.js\").EventTypes, import(\"../events/Event.js\").default, Return> &\n *   import(\"../Observable.js\").OnSignature<import(\"../ObjectEventType.js\").Types, import(\"../Object.js\").ObjectEvent, Return> &\n *   import(\"../Observable.js\").OnSignature<ImageSourceEventTypes, ImageSourceEvent, Return> &\n *   import(\"../Observable.js\").CombinedOnSignature<import(\"../Observable.js\").EventTypes|import(\"../ObjectEventType.js\").Types\n *     |ImageSourceEventTypes, Return>} ImageSourceOnSignature\n */\n\n/**\n * @typedef {Object} Options\n * @property {import(\"./Source.js\").AttributionLike} [attributions] Attributions.\n * @property {boolean} [interpolate=true] Use interpolated values when resampling.  By default,\n * linear interpolation is used when resampling.  Set to false to use the nearest neighbor instead.\n * @property {import(\"../Image.js\").Loader} [loader] Loader. Can either be a custom loader, or one of the\n * loaders created with a `createLoader()` function ({@link module:ol/source/wms.createLoader wms},\n * {@link module:ol/source/arcgisRest.createLoader arcgisRest}, {@link module:ol/source/mapguide.createLoader mapguide},\n * {@link module:ol/source/static.createLoader static}).\n * @property {import(\"../proj.js\").ProjectionLike} [projection] Projection.\n * @property {Array<number>} [resolutions] Resolutions.\n * @property {import(\"./Source.js\").State} [state] State.\n */\n\n/**\n * @classdesc\n * Base class for sources providing a single image.\n * @fires module:ol/source/Image.ImageSourceEvent\n * @api\n */\nclass ImageSource extends Source {\n  /**\n   * @param {Options} options Single image source options.\n   */\n  constructor(options) {\n    super({\n      attributions: options.attributions,\n      projection: options.projection,\n      state: options.state,\n      interpolate:\n        options.interpolate !== undefined ? options.interpolate : true,\n    });\n\n    /***\n     * @type {ImageSourceOnSignature<import(\"../events.js\").EventsKey>}\n     */\n    this.on;\n\n    /***\n     * @type {ImageSourceOnSignature<import(\"../events.js\").EventsKey>}\n     */\n    this.once;\n\n    /***\n     * @type {ImageSourceOnSignature<void>}\n     */\n    this.un;\n\n    /**\n     * @protected\n     * @type {import(\"../Image.js\").Loader}\n     */\n    this.loader = options.loader || null;\n\n    /**\n     * @private\n     * @type {Array<number>|null}\n     */\n    this.resolutions_ =\n      options.resolutions !== undefined ? options.resolutions : null;\n\n    /**\n     * @private\n     * @type {import(\"../reproj/Image.js\").default}\n     */\n    this.reprojectedImage_ = null;\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.reprojectedRevision_ = 0;\n\n    /**\n     * @protected\n     * @type {import(\"../Image.js\").default}\n     */\n    this.image = null;\n\n    /**\n     * @private\n     * @type {import(\"../extent.js\").Extent}\n     */\n    this.wantedExtent_;\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.wantedResolution_;\n\n    /**\n     * @private\n     * @type {boolean}\n     */\n    this.static_ = options.loader ? options.loader.length === 0 : false;\n\n    /**\n     * @private\n     * @type {import(\"../proj/Projection.js\").default}\n     */\n    this.wantedProjection_ = null;\n  }\n\n  /**\n   * @return {Array<number>|null} Resolutions.\n   * @override\n   */\n  getResolutions() {\n    return this.resolutions_;\n  }\n\n  /**\n   * @param {Array<number>|null} resolutions Resolutions.\n   */\n  setResolutions(resolutions) {\n    this.resolutions_ = resolutions;\n  }\n\n  /**\n   * @protected\n   * @param {number} resolution Resolution.\n   * @return {number} Resolution.\n   */\n  findNearestResolution(resolution) {\n    const resolutions = this.getResolutions();\n    if (resolutions) {\n      const idx = linearFindNearest(resolutions, resolution, 0);\n      resolution = resolutions[idx];\n    }\n    return resolution;\n  }\n\n  /**\n   * @param {import(\"../extent.js\").Extent} extent Extent.\n   * @param {number} resolution Resolution.\n   * @param {number} pixelRatio Pixel ratio.\n   * @param {import(\"../proj/Projection.js\").default} projection Projection.\n   * @return {import(\"../Image.js\").default} Single image.\n   */\n  getImage(extent, resolution, pixelRatio, projection) {\n    const sourceProjection = this.getProjection();\n    if (\n      !sourceProjection ||\n      !projection ||\n      equivalent(sourceProjection, projection)\n    ) {\n      if (sourceProjection) {\n        projection = sourceProjection;\n      }\n\n      return this.getImageInternal(extent, resolution, pixelRatio, projection);\n    }\n    if (this.reprojectedImage_) {\n      if (\n        this.reprojectedRevision_ == this.getRevision() &&\n        equivalent(this.reprojectedImage_.getProjection(), projection) &&\n        this.reprojectedImage_.getResolution() == resolution &&\n        equals(this.reprojectedImage_.getExtent(), extent)\n      ) {\n        return this.reprojectedImage_;\n      }\n      this.reprojectedImage_.dispose();\n      this.reprojectedImage_ = null;\n    }\n\n    this.reprojectedImage_ = new ReprojImage(\n      sourceProjection,\n      projection,\n      extent,\n      resolution,\n      pixelRatio,\n      (extent, resolution, pixelRatio) =>\n        this.getImageInternal(extent, resolution, pixelRatio, sourceProjection),\n      this.getInterpolate(),\n    );\n    this.reprojectedRevision_ = this.getRevision();\n\n    return this.reprojectedImage_;\n  }\n\n  /**\n   * @abstract\n   * @param {import(\"../extent.js\").Extent} extent Extent.\n   * @param {number} resolution Resolution.\n   * @param {number} pixelRatio Pixel ratio.\n   * @param {import(\"../proj/Projection.js\").default} projection Projection.\n   * @return {import(\"../Image.js\").default} Single image.\n   * @protected\n   */\n  getImageInternal(extent, resolution, pixelRatio, projection) {\n    if (this.loader) {\n      const requestExtent = getRequestExtent(extent, resolution, pixelRatio, 1);\n      const requestResolution = this.findNearestResolution(resolution);\n      if (\n        this.image &&\n        (this.static_ ||\n          (this.wantedProjection_ === projection &&\n            ((this.wantedExtent_ &&\n              containsExtent(this.wantedExtent_, requestExtent)) ||\n              containsExtent(this.image.getExtent(), requestExtent)) &&\n            ((this.wantedResolution_ &&\n              fromResolutionLike(this.wantedResolution_) ===\n                requestResolution) ||\n              fromResolutionLike(this.image.getResolution()) ===\n                requestResolution)))\n      ) {\n        return this.image;\n      }\n      this.wantedProjection_ = projection;\n      this.wantedExtent_ = requestExtent;\n      this.wantedResolution_ = requestResolution;\n      this.image = new ImageWrapper(\n        requestExtent,\n        requestResolution,\n        pixelRatio,\n        this.loader,\n      );\n      this.image.addEventListener(\n        EventType.CHANGE,\n        this.handleImageChange.bind(this),\n      );\n    }\n    return this.image;\n  }\n\n  /**\n   * Handle image change events.\n   * @param {import(\"../events/Event.js\").default} event Event.\n   * @protected\n   */\n  handleImageChange(event) {\n    const image = /** @type {import(\"../Image.js\").default} */ (event.target);\n    let type;\n    switch (image.getState()) {\n      case ImageState.LOADING:\n        this.loading = true;\n        type = ImageSourceEventType.IMAGELOADSTART;\n        break;\n      case ImageState.LOADED:\n        this.loading = false;\n        type = ImageSourceEventType.IMAGELOADEND;\n        break;\n      case ImageState.ERROR:\n        this.loading = false;\n        type = ImageSourceEventType.IMAGELOADERROR;\n        break;\n      default:\n        return;\n    }\n    if (this.hasListener(type)) {\n      this.dispatchEvent(new ImageSourceEvent(type, image));\n    }\n  }\n}\n\n/**\n * Default image load function for image sources that use import(\"../Image.js\").Image image\n * instances.\n * @param {import(\"../Image.js\").default} image Image.\n * @param {string} src Source.\n */\nexport function defaultImageLoadFunction(image, src) {\n  /** @type {HTMLImageElement|HTMLVideoElement} */ (image.getImage()).src = src;\n}\n\n/**\n * Adjusts the extent so it aligns with pixel boundaries.\n * @param {import(\"../extent.js\").Extent} extent Extent.\n * @param {number} resolution Reolution.\n * @param {number} pixelRatio Pixel ratio.\n * @param {number} ratio Ratio between request size and view size.\n * @return {import(\"../extent.js\").Extent} Request extent.\n */\nexport function getRequestExtent(extent, resolution, pixelRatio, ratio) {\n  const imageResolution = resolution / pixelRatio;\n  const center = getCenter(extent);\n  const viewWidth = ceil(getWidth(extent) / imageResolution, DECIMALS);\n  const viewHeight = ceil(getHeight(extent) / imageResolution, DECIMALS);\n  const marginWidth = ceil(((ratio - 1) * viewWidth) / 2, DECIMALS);\n  const requestWidth = viewWidth + 2 * marginWidth;\n  const marginHeight = ceil(((ratio - 1) * viewHeight) / 2, DECIMALS);\n  const requestHeight = viewHeight + 2 * marginHeight;\n  return getForViewAndSize(center, imageResolution, 0, [\n    requestWidth,\n    requestHeight,\n  ]);\n}\n\nexport default ImageSource;\n", "/**\n * @module ol/source/wms\n */\n\nimport {decode} from '../Image.js';\nimport {getForViewAndSize, getHeight, getWidth} from '../extent.js';\nimport {floor, round} from '../math.js';\nimport {get as getProjection} from '../proj.js';\nimport {compareVersions} from '../string.js';\nimport {appendParams} from '../uri.js';\nimport {getRequestExtent} from './Image.js';\nimport {DECIMALS} from './common.js';\n\n/**\n * Default WMS version.\n * @type {string}\n */\nexport const DEFAULT_VERSION = '1.3.0';\n\n/**\n * @const\n * @type {import(\"../size.js\").Size}\n */\nconst GETFEATUREINFO_IMAGE_SIZE = [101, 101];\n\n/**\n * @api\n * @typedef {'carmentaserver' | 'geoserver' | 'mapserver' | 'qgis'} ServerType\n * Set the server type to use implementation-specific parameters beyond the WMS specification.\n *  - `'carmentaserver'`: HiDPI support for [Carmenta Server](https://www.carmenta.com/en/products/carmenta-server)\n *  - `'geoserver'`: HiDPI support for [GeoServer](https://geoserver.org/)\n *  - `'mapserver'`: HiDPI support for [MapServer](https://mapserver.org/)\n *  - `'qgis'`: HiDPI support for [QGIS](https://qgis.org/)\n */\n\n/**\n * @param {string} baseUrl Base URL.\n * @param {import(\"../extent.js\").Extent} extent Extent.\n * @param {import(\"../size.js\").Size} size Size.\n * @param {import(\"../proj/Projection.js\").default} projection Projection.\n * @param {Object} params WMS params. Will be modified in place.\n * @return {string} Request URL.\n */\nexport function getRequestUrl(baseUrl, extent, size, projection, params) {\n  params['WIDTH'] = size[0];\n  params['HEIGHT'] = size[1];\n\n  const axisOrientation = projection.getAxisOrientation();\n  const v13 = compareVersions(params['VERSION'], '1.3') >= 0;\n  params[v13 ? 'CRS' : 'SRS'] = projection.getCode();\n  const bbox =\n    v13 && axisOrientation.startsWith('ne')\n      ? [extent[1], extent[0], extent[3], extent[2]]\n      : extent;\n  params['BBOX'] = bbox.join(',');\n\n  return appendParams(baseUrl, params);\n}\n\n/**\n * @param {import(\"../extent.js\").Extent} extent Extent.\n * @param {number} resolution Resolution.\n * @param {number} pixelRatio pixel ratio.\n * @param {import(\"../proj.js\").Projection} projection Projection.\n * @param {string} url WMS service url.\n * @param {Object} params WMS params.\n * @param {import(\"./wms.js\").ServerType} serverType The type of the remote WMS server.\n * @return {string} Image src.\n */\nexport function getImageSrc(\n  extent,\n  resolution,\n  pixelRatio,\n  projection,\n  url,\n  params,\n  serverType,\n) {\n  params = Object.assign({REQUEST: 'GetMap'}, params);\n\n  const imageResolution = resolution / pixelRatio;\n\n  const imageSize = [\n    round(getWidth(extent) / imageResolution, DECIMALS),\n    round(getHeight(extent) / imageResolution, DECIMALS),\n  ];\n\n  if (pixelRatio != 1) {\n    switch (serverType) {\n      case 'geoserver':\n        const dpi = (90 * pixelRatio + 0.5) | 0;\n        if ('FORMAT_OPTIONS' in params) {\n          params['FORMAT_OPTIONS'] += ';dpi:' + dpi;\n        } else {\n          params['FORMAT_OPTIONS'] = 'dpi:' + dpi;\n        }\n        break;\n      case 'mapserver':\n        params['MAP_RESOLUTION'] = 90 * pixelRatio;\n        break;\n      case 'carmentaserver':\n      case 'qgis':\n        params['DPI'] = 90 * pixelRatio;\n        break;\n      default:\n        throw new Error('Unknown `serverType` configured');\n    }\n  }\n\n  const src = getRequestUrl(url, extent, imageSize, projection, params);\n  return src;\n}\n\n/**\n * @param {Object} params WMS params.\n * @param {string} request WMS `REQUEST`.\n * @return {Object} WMS params with required properties set.\n */\nexport function getRequestParams(params, request) {\n  return Object.assign(\n    {\n      'REQUEST': request,\n      'SERVICE': 'WMS',\n      'VERSION': DEFAULT_VERSION,\n      'FORMAT': 'image/png',\n      'STYLES': '',\n      'TRANSPARENT': 'TRUE',\n    },\n    params,\n  );\n}\n\n/**\n * @typedef {Object} LoaderOptions\n * @property {null|string} [crossOrigin] The `crossOrigin` attribute for loaded images.  Note that\n * you must provide a `crossOrigin` value if you want to access pixel data with the Canvas renderer.\n * See https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image for more detail.\n * @property {ReferrerPolicy} [referrerPolicy] The `referrerPolicy` property for loaded images.\n * @property {boolean} [hidpi=true] Use the `ol/Map#pixelRatio` value when requesting\n * the image from the remote server.\n * @property {Object<string,*>} [params] WMS request parameters.\n * At least a `LAYERS` param is required. `STYLES` is\n * `''` by default. `VERSION` is `1.3.0` by default. `WIDTH`, `HEIGHT` and `BBOX` will be set\n * dynamically. `CRS` (`SRS` for WMS version < 1.3.0) will is derived from the `proection` config.\n * @property {import(\"../proj.js\").ProjectionLike} [projection] Projection. Default is 'EPSG:3857'.\n * @property {number} [ratio=1.5] Ratio. `1` means image requests are the size of the map viewport, `2` means\n * twice the width and height of the map viewport, and so on. Must be `1` or higher.\n * @property {import(\"./wms.js\").ServerType} [serverType] The type of\n * the remote WMS server: `mapserver`, `geoserver`, `carmentaserver`, or `qgis`.\n * Only needed if `hidpi` is `true`.\n * @property {string} url WMS service URL.\n * @property {function(HTMLImageElement, string): Promise<import('../DataTile.js').ImageLike>} [load] Function\n * to perform loading of the image. Receives the created `HTMLImageElement` and the desired `src` as argument and\n * returns a promise resolving to the loaded or decoded image. Default is {@link module:ol/Image.decode}.\n */\n\n/**\n * Creates a loader for WMS images.\n * @param {LoaderOptions} options Loader options.\n * @return {import(\"../Image.js\").ImageObjectPromiseLoader} Loader.\n * @api\n */\nexport function createLoader(options) {\n  const hidpi = options.hidpi === undefined ? true : options.hidpi;\n  const projection = getProjection(options.projection || 'EPSG:3857');\n  const ratio = options.ratio || 1.5;\n  const load = options.load || decode;\n  const crossOrigin = options.crossOrigin ?? null;\n  const referrerPolicy = options.referrerPolicy;\n\n  return (extent, resolution, pixelRatio) => {\n    extent = getRequestExtent(extent, resolution, pixelRatio, ratio);\n    if (pixelRatio != 1 && (!hidpi || options.serverType === undefined)) {\n      pixelRatio = 1;\n    }\n    const src = getImageSrc(\n      extent,\n      resolution,\n      pixelRatio,\n      projection,\n      options.url,\n      getRequestParams(options.params, 'GetMap'),\n      options.serverType,\n    );\n    const image = new Image();\n    image.crossOrigin = crossOrigin;\n    if (referrerPolicy !== undefined) {\n      image.referrerPolicy = referrerPolicy;\n    }\n    return load(image, src).then((image) => ({image, extent, pixelRatio}));\n  };\n}\n\n/**\n * Get the GetFeatureInfo URL for the passed coordinate and resolution. Returns `undefined` if the\n * GetFeatureInfo URL cannot be constructed.\n * @param {LoaderOptions} options Options passed the `createWMSLoader()` function. In addition to\n * the params required by the loader, `INFO_FORMAT` should be specified, it defaults to\n * `application/json`. If `QUERY_LAYERS` is not provided, then the layers specified in the `LAYERS`\n * parameter will be used.\n * @param {import(\"../coordinate.js\").Coordinate} coordinate Coordinate.\n * @param {number} resolution Resolution.\n * @return {string|undefined} GetFeatureInfo URL.\n * @api\n */\nexport function getFeatureInfoUrl(options, coordinate, resolution) {\n  if (options.url === undefined) {\n    return undefined;\n  }\n\n  const projectionObj = getProjection(options.projection || 'EPSG:3857');\n\n  const extent = getForViewAndSize(\n    coordinate,\n    resolution,\n    0,\n    GETFEATUREINFO_IMAGE_SIZE,\n  );\n\n  const baseParams = {\n    'QUERY_LAYERS': options.params['LAYERS'],\n    'INFO_FORMAT': 'application/json',\n  };\n  Object.assign(\n    baseParams,\n    getRequestParams(options.params, 'GetFeatureInfo'),\n    options.params,\n  );\n\n  const x = floor((coordinate[0] - extent[0]) / resolution, DECIMALS);\n  const y = floor((extent[3] - coordinate[1]) / resolution, DECIMALS);\n  const v13 = compareVersions(baseParams['VERSION'], '1.3') >= 0;\n  baseParams[v13 ? 'I' : 'X'] = x;\n  baseParams[v13 ? 'J' : 'Y'] = y;\n\n  return getRequestUrl(\n    options.url,\n    extent,\n    GETFEATUREINFO_IMAGE_SIZE,\n    projectionObj,\n    baseParams,\n  );\n}\n\n/**\n * Get the GetLegendGraphic URL, optionally optimized for the passed resolution and possibly\n * including any passed specific parameters. Returns `undefined` if the GetLegendGraphic URL\n * cannot be constructed.\n *\n * @param {LoaderOptions} options Options passed the `createWMSLoader()` function.\n * @param {number} [resolution] Resolution. If not provided, `SCALE` will not be calculated and\n * included in URL.\n * @return {string|undefined} GetLegendGraphic URL.\n * @api\n */\nexport function getLegendUrl(options, resolution) {\n  if (options.url === undefined) {\n    return undefined;\n  }\n\n  const baseParams = {\n    'SERVICE': 'WMS',\n    'VERSION': DEFAULT_VERSION,\n    'REQUEST': 'GetLegendGraphic',\n    'FORMAT': 'image/png',\n  };\n\n  if (resolution !== undefined) {\n    const mpu =\n      getProjection(options.projection || 'EPSG:3857').getMetersPerUnit() || 1;\n    const pixelSize = 0.00028;\n    baseParams['SCALE'] = (resolution * mpu) / pixelSize;\n  }\n\n  Object.assign(baseParams, options.params);\n\n  if (options.params !== undefined && baseParams['LAYER'] === undefined) {\n    const layers = baseParams['LAYERS'];\n    const isSingleLayer = !Array.isArray(layers) || layers.length !== 1;\n    if (!isSingleLayer) {\n      return undefined;\n    }\n    baseParams['LAYER'] = layers;\n  }\n\n  return appendParams(options.url, baseParams);\n}\n", "/**\n * @module ol/source/ImageWMS\n */\n\nimport {decode} from '../Image.js';\nimport {get as getProjection, transform} from '../proj.js';\nimport {calculateSourceResolution} from '../reproj.js';\nimport ImageSource, {defaultImageLoadFunction} from './Image.js';\nimport {createLoader, getFeatureInfoUrl, getLegendUrl} from './wms.js';\n\n/**\n * @typedef {Object} Options\n * @property {import(\"./Source.js\").AttributionLike} [attributions] Attributions.\n * @property {null|string} [crossOrigin] The `crossOrigin` attribute for loaded images.  Note that\n * you must provide a `crossOrigin` value if you want to access pixel data with the Canvas renderer.\n * See https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image for more detail.\n * @property {ReferrerPolicy} [referrerPolicy] The `referrerPolicy` property for loaded images.\n * @property {boolean} [hidpi=true] Use the `ol/Map#pixelRatio` value when requesting\n * the image from the remote server.\n * @property {import(\"./wms.js\").ServerType} [serverType] The type of\n * the remote WMS server: `mapserver`, `geoserver`, `carmentaserver`, or `qgis`.\n * Only needed if `hidpi` is `true`.\n * @property {import(\"../Image.js\").LoadFunction} [imageLoadFunction] Optional function to load an image given a URL.\n * @property {boolean} [interpolate=true] Use interpolated values when resampling.  By default,\n * linear interpolation is used when resampling.  Set to false to use the nearest neighbor instead.\n * @property {Object<string,*>} [params] WMS request parameters.\n * At least a `LAYERS` param is required. `STYLES` is\n * `''` by default. `VERSION` is `1.3.0` by default. `WIDTH`, `HEIGHT`, `BBOX`\n * and `CRS` (`SRS` for WMS version < 1.3.0) will be set dynamically.\n * @property {import(\"../proj.js\").ProjectionLike} [projection] Projection. Default is the view projection.\n * @property {number} [ratio=1.5] Ratio. `1` means image requests are the size of the map viewport, `2` means\n * twice the width and height of the map viewport, and so on. Must be `1` or higher.\n * @property {Array<number>} [resolutions] Resolutions.\n * If specified, requests will be made for these resolutions only.\n * @property {string} [url] WMS service URL.\n */\n\n/**\n * @classdesc\n * Source for WMS servers providing single, untiled images.\n *\n * @fires module:ol/source/Image.ImageSourceEvent\n * @api\n */\nclass ImageWMS extends ImageSource {\n  /**\n   * @param {Options} [options] ImageWMS options.\n   */\n  constructor(options) {\n    options = options ? options : {};\n\n    super({\n      attributions: options.attributions,\n      interpolate: options.interpolate,\n      projection: options.projection,\n      resolutions: options.resolutions,\n    });\n\n    /**\n     * @private\n     * @type {?string}\n     */\n    this.crossOrigin_ =\n      options.crossOrigin !== undefined ? options.crossOrigin : null;\n\n    /**\n     * @private\n     * @type {ReferrerPolicy}\n     */\n    this.referrerPolicy_ = options.referrerPolicy;\n\n    /**\n     * @private\n     * @type {string|undefined}\n     */\n    this.url_ = options.url;\n\n    /**\n     * @private\n     * @type {import(\"../Image.js\").LoadFunction}\n     */\n    this.imageLoadFunction_ =\n      options.imageLoadFunction !== undefined\n        ? options.imageLoadFunction\n        : defaultImageLoadFunction;\n\n    /**\n     * @private\n     * @type {!Object}\n     */\n    this.params_ = Object.assign({}, options.params);\n\n    /**\n     * @private\n     * @type {import(\"./wms.js\").ServerType}\n     */\n    this.serverType_ = options.serverType;\n\n    /**\n     * @private\n     * @type {boolean}\n     */\n    this.hidpi_ = options.hidpi !== undefined ? options.hidpi : true;\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.renderedRevision_ = 0;\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.ratio_ = options.ratio !== undefined ? options.ratio : 1.5;\n\n    /**\n     * @private\n     * @type {import(\"../proj/Projection.js\").default}\n     */\n    this.loaderProjection_ = null;\n  }\n\n  /**\n   * Return the GetFeatureInfo URL for the passed coordinate, resolution, and\n   * projection. Return `undefined` if the GetFeatureInfo URL cannot be\n   * constructed.\n   * @param {import(\"../coordinate.js\").Coordinate} coordinate Coordinate.\n   * @param {number} resolution Resolution.\n   * @param {import(\"../proj.js\").ProjectionLike} projection Projection.\n   * @param {!Object} params GetFeatureInfo params. `INFO_FORMAT` at least should\n   *     be provided. If `QUERY_LAYERS` is not provided then the layers specified\n   *     in the `LAYERS` parameter will be used. `VERSION` should not be\n   *     specified here.\n   * @return {string|undefined} GetFeatureInfo URL.\n   * @api\n   */\n  getFeatureInfoUrl(coordinate, resolution, projection, params) {\n    const projectionObj = getProjection(projection);\n    const sourceProjectionObj = this.getProjection();\n\n    if (sourceProjectionObj && sourceProjectionObj !== projectionObj) {\n      resolution = calculateSourceResolution(\n        sourceProjectionObj,\n        projectionObj,\n        coordinate,\n        resolution,\n      );\n      coordinate = transform(coordinate, projectionObj, sourceProjectionObj);\n    }\n\n    const options = {\n      url: this.url_,\n      params: {\n        ...this.params_,\n        ...params,\n      },\n      projection: sourceProjectionObj || projectionObj,\n    };\n    return getFeatureInfoUrl(options, coordinate, resolution);\n  }\n\n  /**\n   * Return the GetLegendGraphic URL, optionally optimized for the passed\n   * resolution and possibly including any passed specific parameters. Returns\n   * `undefined` if the GetLegendGraphic URL cannot be constructed.\n   *\n   * @param {number} [resolution] Resolution. If set to undefined, `SCALE`\n   *     will not be calculated and included in URL.\n   * @param {Object} [params] GetLegendGraphic params. If `LAYER` is set, the\n   *     request is generated for this wms layer, else it will try to use the\n   *     configured wms layer. Default `FORMAT` is `image/png`.\n   *     `VERSION` should not be specified here.\n   * @return {string|undefined} GetLegendGraphic URL.\n   * @api\n   */\n  getLegendUrl(resolution, params) {\n    return getLegendUrl(\n      {\n        url: this.url_,\n        params: {\n          ...this.params_,\n          ...params,\n        },\n      },\n      resolution,\n    );\n  }\n\n  /**\n   * Get the user-provided params, i.e. those passed to the constructor through\n   * the \"params\" option, and possibly updated using the updateParams method.\n   * @return {Object} Params.\n   * @api\n   */\n  getParams() {\n    return this.params_;\n  }\n\n  /**\n   * @param {import(\"../extent.js\").Extent} extent Extent.\n   * @param {number} resolution Resolution.\n   * @param {number} pixelRatio Pixel ratio.\n   * @param {import(\"../proj/Projection.js\").default} projection Projection.\n   * @return {import(\"../Image.js\").default} Single image.\n   * @override\n   */\n  getImageInternal(extent, resolution, pixelRatio, projection) {\n    if (this.url_ === undefined) {\n      return null;\n    }\n    if (!this.loader || this.loaderProjection_ !== projection) {\n      // Lazily create loader to pick up the view projection and to allow `params` updates\n      this.loaderProjection_ = projection;\n      this.loader = createLoader({\n        crossOrigin: this.crossOrigin_,\n        referrerPolicy: this.referrerPolicy_,\n        params: this.params_,\n        projection: projection,\n        serverType: this.serverType_,\n        hidpi: this.hidpi_,\n        url: this.url_,\n        ratio: this.ratio_,\n        load: (image, src) => {\n          this.image.setImage(image);\n          this.imageLoadFunction_(this.image, src);\n          return decode(image);\n        },\n      });\n    }\n\n    return super.getImageInternal(extent, resolution, pixelRatio, projection);\n  }\n\n  /**\n   * Return the image load function of the source.\n   * @return {import(\"../Image.js\").LoadFunction} The image load function.\n   * @api\n   */\n  getImageLoadFunction() {\n    return this.imageLoadFunction_;\n  }\n\n  /**\n   * Return the URL used for this WMS source.\n   * @return {string|undefined} URL.\n   * @api\n   */\n  getUrl() {\n    return this.url_;\n  }\n\n  /**\n   * Set the image load function of the source.\n   * @param {import(\"../Image.js\").LoadFunction} imageLoadFunction Image load function.\n   * @api\n   */\n  setImageLoadFunction(imageLoadFunction) {\n    this.imageLoadFunction_ = imageLoadFunction;\n    this.changed();\n  }\n\n  /**\n   * Set the URL to use for requests.\n   * @param {string|undefined} url URL.\n   * @api\n   */\n  setUrl(url) {\n    if (url != this.url_) {\n      this.url_ = url;\n      this.loader = null;\n      this.changed();\n    }\n  }\n\n  /**\n   * Set the user-provided params.\n   * @param {Object} params Params.\n   * @api\n   */\n  setParams(params) {\n    this.params_ = Object.assign({}, params);\n    // Reset loader to pick up new params\n    this.loader = null;\n    this.changed();\n  }\n\n  /**\n   * Update the user-provided params.\n   * @param {Object} params Params.\n   * @api\n   */\n  updateParams(params) {\n    Object.assign(this.params_, params);\n    this.changed();\n  }\n\n  /**\n   * @override\n   */\n  changed() {\n    this.image = null;\n    super.changed();\n  }\n}\n\nexport default ImageWMS;\n", "/**\n * @module ol/renderer/canvas/ImageLayer\n */\nimport ImageState from '../../ImageState.js';\nimport ViewHint from '../../ViewHint.js';\nimport {\n  containsCoordinate,\n  containsExtent,\n  getHeight,\n  getIntersection,\n  getWidth,\n  intersects as intersectsExtent,\n  isEmpty,\n} from '../../extent.js';\nimport {fromUserExtent} from '../../proj.js';\nimport {\n  apply as applyTransform,\n  compose as composeTransform,\n} from '../../transform.js';\nimport CanvasLayerRenderer from './Layer.js';\n\n/**\n * @classdesc\n * Canvas renderer for image layers.\n * @api\n */\nclass CanvasImageLayerRenderer extends CanvasLayerRenderer {\n  /**\n   * @param {import(\"../../layer/Image.js\").default} imageLayer Image layer.\n   */\n  constructor(imageLayer) {\n    super(imageLayer);\n\n    /**\n     * @protected\n     * @type {?import(\"../../Image.js\").default}\n     */\n    this.image = null;\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.renderedSourceRevision_ = 0;\n  }\n\n  /**\n   * @return {import('../../DataTile.js').ImageLike} Image.\n   */\n  getImage() {\n    return !this.image ? null : this.image.getImage();\n  }\n\n  /**\n   * Determine whether render should be called.\n   * @param {import(\"../../Map.js\").FrameState} frameState Frame state.\n   * @return {boolean} Layer is ready to be rendered.\n   * @override\n   */\n  prepareFrame(frameState) {\n    const layerState = frameState.layerStatesArray[frameState.layerIndex];\n    const pixelRatio = frameState.pixelRatio;\n    const viewState = frameState.viewState;\n    const viewResolution = viewState.resolution;\n\n    const imageSource = this.getLayer().getSource();\n\n    const hints = frameState.viewHints;\n\n    let renderedExtent = frameState.extent;\n    if (layerState.extent !== undefined) {\n      renderedExtent = getIntersection(\n        renderedExtent,\n        fromUserExtent(layerState.extent, viewState.projection),\n      );\n    }\n\n    if (\n      !hints[ViewHint.ANIMATING] &&\n      !hints[ViewHint.INTERACTING] &&\n      !isEmpty(renderedExtent)\n    ) {\n      if (imageSource) {\n        if (\n          !this.getLayer().rendered &&\n          this.renderedSourceRevision_ !== imageSource.getRevision()\n        ) {\n          this.image = null;\n        }\n        this.renderedSourceRevision_ = imageSource.getRevision();\n\n        const projection = viewState.projection;\n        const image = imageSource.getImage(\n          renderedExtent,\n          viewResolution,\n          pixelRatio,\n          projection,\n        );\n        if (image) {\n          if (this.loadImage(image)) {\n            this.image = image;\n          } else if (image.getState() === ImageState.EMPTY) {\n            this.image = null;\n          }\n        }\n      } else {\n        this.image = null;\n      }\n    }\n\n    return !!this.image;\n  }\n\n  /**\n   * @param {import(\"../../pixel.js\").Pixel} pixel Pixel.\n   * @return {Uint8ClampedArray} Data at the pixel location.\n   * @override\n   */\n  getData(pixel) {\n    const frameState = this.frameState;\n    if (!frameState) {\n      return null;\n    }\n\n    const layer = this.getLayer();\n    const coordinate = applyTransform(\n      frameState.pixelToCoordinateTransform,\n      pixel.slice(),\n    );\n\n    const layerExtent = layer.getExtent();\n    if (layerExtent) {\n      if (!containsCoordinate(layerExtent, coordinate)) {\n        return null;\n      }\n    }\n\n    const imageExtent = this.image.getExtent();\n    const img = this.image.getImage();\n\n    const imageMapWidth = getWidth(imageExtent);\n    const col = Math.floor(\n      img.width * ((coordinate[0] - imageExtent[0]) / imageMapWidth),\n    );\n    if (col < 0 || col >= img.width) {\n      return null;\n    }\n\n    const imageMapHeight = getHeight(imageExtent);\n    const row = Math.floor(\n      img.height * ((imageExtent[3] - coordinate[1]) / imageMapHeight),\n    );\n    if (row < 0 || row >= img.height) {\n      return null;\n    }\n\n    return this.getImageData(img, col, row);\n  }\n\n  /**\n   * Render the layer.\n   * @param {import(\"../../Map.js\").FrameState} frameState Frame state.\n   * @param {HTMLElement} target Target that may be used to render content to.\n   * @return {HTMLElement} The rendered element.\n   * @override\n   */\n  renderFrame(frameState, target) {\n    const image = this.image;\n    const imageExtent = image.getExtent();\n    const imageResolution = image.getResolution();\n    const [imageResolutionX, imageResolutionY] = Array.isArray(imageResolution)\n      ? imageResolution\n      : [imageResolution, imageResolution];\n    const imagePixelRatio = image.getPixelRatio();\n    const layerState = frameState.layerStatesArray[frameState.layerIndex];\n    const pixelRatio = frameState.pixelRatio;\n    const viewState = frameState.viewState;\n    const viewCenter = viewState.center;\n    const viewResolution = viewState.resolution;\n    const scaleX =\n      (pixelRatio * imageResolutionX) / (viewResolution * imagePixelRatio);\n    const scaleY =\n      (pixelRatio * imageResolutionY) / (viewResolution * imagePixelRatio);\n\n    this.prepareContainer(frameState, target);\n\n    // desired dimensions of the canvas in pixels\n    const width = this.context.canvas.width;\n    const height = this.context.canvas.height;\n\n    const context = this.getRenderContext(frameState);\n\n    // clipped rendering if layer extent is set\n    let clipped = false;\n    let render = true;\n    if (layerState.extent) {\n      const layerExtent = fromUserExtent(\n        layerState.extent,\n        viewState.projection,\n      );\n      render = intersectsExtent(layerExtent, frameState.extent);\n      clipped = render && !containsExtent(layerExtent, frameState.extent);\n      if (clipped) {\n        this.clipUnrotated(context, frameState, layerExtent);\n      }\n    }\n\n    const img = image.getImage();\n\n    const transform = composeTransform(\n      this.tempTransform,\n      width / 2,\n      height / 2,\n      scaleX,\n      scaleY,\n      0,\n      (imagePixelRatio * (imageExtent[0] - viewCenter[0])) / imageResolutionX,\n      (imagePixelRatio * (viewCenter[1] - imageExtent[3])) / imageResolutionY,\n    );\n\n    this.renderedResolution = (imageResolutionY * pixelRatio) / imagePixelRatio;\n\n    const dw = img.width * transform[0];\n    const dh = img.height * transform[3];\n\n    if (!this.getLayer().getSource().getInterpolate()) {\n      context.imageSmoothingEnabled = false;\n    }\n\n    this.preRender(context, frameState);\n    if (render && dw >= 0.5 && dh >= 0.5) {\n      const dx = transform[4];\n      const dy = transform[5];\n      const opacity = layerState.opacity;\n      if (opacity !== 1) {\n        context.save();\n        context.globalAlpha = opacity;\n      }\n      context.drawImage(img, 0, 0, +img.width, +img.height, dx, dy, dw, dh);\n      if (opacity !== 1) {\n        context.restore();\n      }\n    }\n    this.postRender(this.context, frameState);\n\n    if (clipped) {\n      context.restore();\n    }\n    context.imageSmoothingEnabled = true;\n    return this.container;\n  }\n}\n\nexport default CanvasImageLayerRenderer;\n", "/**\n * @module ol/layer/BaseImage\n */\nimport Layer from './Layer.js';\n\n/**\n * @template {import(\"../source/Image.js\").default} ImageSourceType\n * @typedef {Object} Options\n * @property {string} [className='ol-layer'] A CSS class name to set to the layer element.\n * @property {number} [opacity=1] Opacity (0, 1).\n * @property {boolean} [visible=true] Visibility.\n * @property {import(\"../extent.js\").Extent} [extent] The bounding extent for layer rendering.  The layer will not be\n * rendered outside of this extent.\n * @property {number} [zIndex] The z-index for layer rendering.  At rendering time, the layers\n * will be ordered, first by Z-index and then by position. When `undefined`, a `zIndex` of 0 is assumed\n * for layers that are added to the map's `layers` collection, or `Infinity` when the layer's `setMap()`\n * method was used.\n * @property {number} [minResolution] The minimum resolution (inclusive) at which this layer will be\n * visible.\n * @property {number} [maxResolution] The maximum resolution (exclusive) below which this layer will\n * be visible.\n * @property {number} [minZoom] The minimum view zoom level (exclusive) above which this layer will be\n * visible.\n * @property {number} [maxZoom] The maximum view zoom level (inclusive) at which this layer will\n * be visible.\n * @property {import(\"../Map.js\").default} [map] Sets the layer as overlay on a map. The map will not manage\n * this layer in its layers collection, and the layer will be rendered on top. This is useful for\n * temporary layers. The standard way to add a layer to a map and have it managed by the map is to\n * use {@link import(\"../Map.js\").default#addLayer map.addLayer()}.\n * @property {ImageSourceType} [source] Source for this layer.\n * @property {import('./Base.js').BackgroundColor} [background] Background color for the layer. If not specified, no background\n * will be rendered.\n * @property {Object<string, *>} [properties] Arbitrary observable properties. Can be accessed with `#get()` and `#set()`.\n */\n\n/**\n * @classdesc\n * Server-rendered images that are available for arbitrary extents and\n * resolutions.\n * Note that any property set in the options is set as a {@link module:ol/Object~BaseObject}\n * property on the layer object; for example, setting `title: 'My Title'` in the\n * options means that `title` is observable, and has get/set accessors.\n *\n * @template {import(\"../source/Image.js\").default} ImageSourceType\n * @template {import(\"../renderer/Layer.js\").default} RendererType\n * @extends {Layer<ImageSourceType, RendererType>}\n * @api\n */\nclass BaseImageLayer extends Layer {\n  /**\n   * @param {Options<ImageSourceType>} [options] Layer options.\n   */\n  constructor(options) {\n    options = options ? options : {};\n    super(options);\n  }\n}\n\nexport default BaseImageLayer;\n", "/**\n * @module ol/layer/Image\n */\nimport CanvasImageLayerRenderer from '../renderer/canvas/ImageLayer.js';\nimport BaseImageLayer from './BaseImage.js';\n\n/**\n * @classdesc\n * Server-rendered images that are available for arbitrary extents and\n * resolutions.\n * Note that any property set in the options is set as a {@link module:ol/Object~BaseObject}\n * property on the layer object; for example, setting `title: 'My Title'` in the\n * options means that `title` is observable, and has get/set accessors.\n *\n * @template {import(\"../source/Image.js\").default} ImageSourceType\n * @extends {BaseImageLayer<ImageSourceType, CanvasImageLayerRenderer>}\n * @api\n */\nclass ImageLayer extends BaseImageLayer {\n  /**\n   * @param {import(\"./BaseImage.js\").Options<ImageSourceType>} [options] Layer options.\n   */\n  constructor(options) {\n    super(options);\n  }\n\n  /**\n   * @override\n   */\n  createRenderer() {\n    return new CanvasImageLayerRenderer(this);\n  }\n\n  /**\n   * Get data for a pixel location.  A four element RGBA array will be returned.  For requests outside the\n   * layer extent, `null` will be returned.  Data for an image can only be retrieved if the\n   * source's `crossOrigin` property is set.\n   *\n   * ```js\n   * // display layer data on every pointer move\n   * map.on('pointermove', (event) => {\n   *   console.log(layer.getData(event.pixel));\n   * });\n   * ```\n   * @param {import(\"../pixel.js\").Pixel} pixel Pixel.\n   * @return {Uint8ClampedArray|Uint8Array|Float32Array|DataView|null} Pixel data.\n   * @api\n   * @override\n   */\n  getData(pixel) {\n    return super.getData(pixel);\n  }\n}\n\nexport default ImageLayer;\n", "/**\n * filter.js \u2014 atributov\u00FD filtr vrstvy: datov\u00FD model + p\u0159eklad na OGC Filter\n * XML. Stejn\u00FD `<ogc:Filter>` dialekt funguje jak ve WFS GetFeature (FES \u2014\n * Mapserver akceptuje ogc: namespace i u WFS 2.0), tak v SLD Rules pro WMS\n * GetMap, tak\u017Ee sta\u010D\u00ED jedin\u00FD gener\u00E1tor XML fragment\u016F.\n *\n * Model (ukl\u00E1d\u00E1 se do `entry.filter` \u2192 Map.config, zp\u011Btn\u011B kompatibiln\u011B \u2014\n * star\u0161\u00ED mapy kl\u00ED\u010D `filter` prost\u011B nemaj\u00ED):\n * {\n *   \"logic\": \"and\" | \"or\",\n *   \"conditions\": [{ \"attribute\": \"...\", \"operator\": \"eq\", \"value\": \"...\",\n *                    \"value2\": \"...\" }]   // value2 jen pro \"between\"\n * }\n */\n\n/** Definice oper\u00E1tor\u016F: label pro UI + po\u010Det hodnot (0/1/2). */\nexport const FILTER_OPERATORS = [\n    { value: 'eq', label: '=', values: 1 },\n    { value: 'ne', label: '\u2260', values: 1 },\n    { value: 'gt', label: '>', values: 1 },\n    { value: 'ge', label: '\u2265', values: 1 },\n    { value: 'lt', label: '<', values: 1 },\n    { value: 'le', label: '\u2264', values: 1 },\n    { value: 'contains', label: 'contains', values: 1 },\n    { value: 'starts', label: 'starts with', values: 1 },\n    { value: 'null', label: 'is null', values: 0 },\n    { value: 'between', label: 'between', values: 2 },\n];\n\nfunction xmlEscape(value) {\n    return String(value)\n        .replace(/&/g, '&amp;')\n        .replace(/</g, '&lt;')\n        .replace(/>/g, '&gt;')\n        .replace(/\"/g, '&quot;');\n}\n\n/** Pr\u00E1zdn\u00FD (neaktivn\u00ED) filtr \u2014 v\u00FDchoz\u00ED stav builderu. */\nexport function emptyFilter() {\n    return { logic: 'and', conditions: [] };\n}\n\n/** Pr\u00E1zdn\u00E1 podm\u00EDnka pro \"+ Add condition\" (prvn\u00ED atribut dopln\u00ED UI). */\nexport function emptyCondition(attribute) {\n    return { attribute: attribute || '', operator: 'eq', value: '', value2: '' };\n}\n\n/** Podm\u00EDnka je kompletn\u00ED (m\u00E1 atribut a v\u0161echny po\u017Eadovan\u00E9 hodnoty). */\nexport function isConditionComplete(condition) {\n    if (!condition?.attribute) return false;\n    const op = FILTER_OPERATORS.find((o) => o.value === condition.operator);\n    if (!op) return false;\n    if (op.values >= 1 && String(condition.value ?? '') === '') return false;\n    if (op.values >= 2 && String(condition.value2 ?? '') === '') return false;\n    return true;\n}\n\n/** Filtr je aktivn\u00ED = m\u00E1 aspo\u0148 jednu kompletn\u00ED podm\u00EDnku. */\nexport function isFilterActive(filter) {\n    return Boolean(filter?.conditions?.some(isConditionComplete));\n}\n\n/** Bin\u00E1rn\u00ED porovn\u00E1n\u00ED `<ogc:PropertyIs...>` s jedn\u00EDm liter\u00E1lem. */\nfunction binaryOp(tag, attribute, value) {\n    return `<ogc:${tag}><ogc:PropertyName>${xmlEscape(attribute)}</ogc:PropertyName><ogc:Literal>${xmlEscape(value)}</ogc:Literal></ogc:${tag}>`;\n}\n\n/** `<ogc:PropertyIsLike>` \u2014 `pattern` u\u017E obsahuje wildcard znaky `*`. */\nfunction likeOp(attribute, pattern) {\n    return `<ogc:PropertyIsLike wildCard=\"*\" singleChar=\"?\" escapeChar=\"\\\\\" matchCase=\"false\">`\n        + `<ogc:PropertyName>${xmlEscape(attribute)}</ogc:PropertyName>`\n        + `<ogc:Literal>${xmlEscape(pattern)}</ogc:Literal></ogc:PropertyIsLike>`;\n}\n\n/** P\u0159elo\u017E\u00ED jednu podm\u00EDnku na XML fragment (bez obalu `<ogc:Filter>`).\n * Nekompletn\u00ED podm\u00EDnky vrac\u00ED null (v UI se ignoruj\u00ED). */\nexport function conditionToXml(condition) {\n    if (!isConditionComplete(condition)) return null;\n    const { attribute, operator, value, value2 } = condition;\n    switch (operator) {\n        case 'eq': return binaryOp('PropertyIsEqualTo', attribute, value);\n        case 'ne': return binaryOp('PropertyIsNotEqualTo', attribute, value);\n        case 'gt': return binaryOp('PropertyIsGreaterThan', attribute, value);\n        case 'ge': return binaryOp('PropertyIsGreaterThanOrEqualTo', attribute, value);\n        case 'lt': return binaryOp('PropertyIsLessThan', attribute, value);\n        case 'le': return binaryOp('PropertyIsLessThanOrEqualTo', attribute, value);\n        case 'contains': return likeOp(attribute, `*${value}*`);\n        case 'starts': return likeOp(attribute, `${value}*`);\n        case 'null': return `<ogc:PropertyIsNull><ogc:PropertyName>${xmlEscape(attribute)}</ogc:PropertyName></ogc:PropertyIsNull>`;\n        case 'between': return `<ogc:PropertyIsBetween><ogc:PropertyName>${xmlEscape(attribute)}</ogc:PropertyName>`\n            + `<ogc:LowerBoundary><ogc:Literal>${xmlEscape(value)}</ogc:Literal></ogc:LowerBoundary>`\n            + `<ogc:UpperBoundary><ogc:Literal>${xmlEscape(value2)}</ogc:Literal></ogc:UpperBoundary></ogc:PropertyIsBetween>`;\n        default: return null;\n    }\n}\n\n/** Spoj\u00ED XML fragmenty logickou spojkou (And/Or); jeden fragment vrac\u00ED bez\n * obalu, pr\u00E1zdn\u00FD seznam \u2192 null. */\nexport function combineXml(fragments, logic) {\n    const parts = fragments.filter(Boolean);\n    if (parts.length === 0) return null;\n    if (parts.length === 1) return parts[0];\n    const tag = logic === 'or' ? 'Or' : 'And';\n    return `<ogc:${tag}>${parts.join('')}</ogc:${tag}>`;\n}\n\n/** P\u0159elo\u017E\u00ED builder filtr na vnit\u0159ek `<ogc:Filter>` (bez obalu) \u2014 vr\u00E1t\u00ED null,\n * kdy\u017E filtr nen\u00ED aktivn\u00ED. */\nexport function filterToXml(filter) {\n    if (!filter) return null;\n    const fragments = (filter.conditions || []).map(conditionToXml);\n    return combineXml(fragments, filter.logic);\n}\n\n/** Fulltextov\u00FD filtr \u2014 `PropertyIsLike *text*` p\u0159es v\u0161echny textov\u00E9 atributy,\n * spojen\u00FD `<ogc:Or>`. Vrac\u00ED null pro pr\u00E1zdn\u00FD text nebo \u017E\u00E1dn\u00E9 atributy. */\nexport function searchToXml(searchText, textAttributes) {\n    const text = (searchText || '').trim();\n    if (!text || !(textAttributes || []).length) return null;\n    return combineXml(textAttributes.map((attr) => likeOp(attr, `*${text}*`)), 'or');\n}\n\n/** Zkombinuje builder filtr a fulltext AND spojkou a vr\u00E1t\u00ED hotov\u00FD\n * `<ogc:Filter>...</ogc:Filter>` element (nebo null, kdy\u017E nic nen\u00ED aktivn\u00ED). */\nexport function buildFilterXml(filter, searchText, textAttributes) {\n    const combined = combineXml([filterToXml(filter), searchToXml(searchText, textAttributes)], 'and');\n    return combined ? `<ogc:Filter>${combined}</ogc:Filter>` : null;\n}\n", "/**\n * sld.js \u2014 gener\u00E1tor SLD 1.1 XML z intern\u00EDho JSON style modelu (viz Map.config\n * ve specifikaci). Pro ka\u017Edou podvrstvu (sublayer) vygeneruje vlastn\u00ED\n * <NamedLayer>, proto\u017Ee jedna polo\u017Eka workspace se sm\u00ED\u0161en\u00FDmi geometriemi m\u016F\u017Ee\n * m\u00EDt v\u00EDc sublayers (nap\u0159. \"roads\" \u2192 \"roads_line\").\n *\n * Inspirov\u00E1no star\u00FDm gener\u00E1torem `generateSLD` z v2 (map_app.js), ale ps\u00E1no\n * \u010Dist\u011B nov\u011B a napojeno na nov\u00E9 sch\u00E9ma stylu.\n */\nimport { normalizeGeometryType, ruleForCategory } from './state.js';\nimport { filterToXml, combineXml } from './filter.js';\nimport {\n    PHOTO_SYMBOL, photoFieldOf, photoMarkerSizes, plainDotSize,\n} from './photo-marker.js';\nimport { labelMinZoom, textSymbolizerXml } from './labels.js';\n\n/** Escapuje text pro pou\u017Eit\u00ED v XML (atributy jmen apod.). */\nfunction xmlEscape(value) {\n    return String(value)\n        .replace(/&/g, '&amp;')\n        .replace(/</g, '&lt;')\n        .replace(/>/g, '&gt;')\n        .replace(/\"/g, '&quot;');\n}\n\n/** Tvary bodov\u00E9ho symbolu, kter\u00E9 Mapserver zn\u00E1 jako SLD WellKnownName. */\nconst POINT_SHAPES = ['circle', 'square', 'triangle', 'star', 'cross', 'x'];\n\nfunction pointSymbolizer(rule) {\n    const wkn = POINT_SHAPES.includes(rule.symbol) ? rule.symbol : 'circle';\n    // K\u0159\u00ED\u017Eky jsou jen \u010D\u00E1ry \u2014 kresl\u00ED se barvou v\u00FDpln\u011B (obrys by je zdvojil).\n    const lineOnly = wkn === 'cross' || wkn === 'x';\n    const stroke = lineOnly\n        ? `<Stroke>\n              <CssParameter name=\"stroke\">${xmlEscape(rule.fill)}</CssParameter>\n              <CssParameter name=\"stroke-width\">${Math.max(1.5, Number(rule.strokeWidth) || 1.5)}</CssParameter>\n            </Stroke>`\n        : `<Stroke>\n              <CssParameter name=\"stroke\">${xmlEscape(rule.stroke)}</CssParameter>\n              <CssParameter name=\"stroke-width\">${rule.strokeWidth}</CssParameter>\n            </Stroke>`;\n    return markSymbolizer(wkn, rule.size, rule.fill, stroke);\n}\n\nfunction markSymbolizer(wellKnownName, size, fill, stroke = '') {\n    return `<PointSymbolizer>\n        <Graphic>\n          <Mark>\n            <WellKnownName>${wellKnownName}</WellKnownName>\n            <Fill><CssParameter name=\"fill\">${xmlEscape(fill)}</CssParameter></Fill>\n            ${stroke}\n          </Mark>\n          <Size>${size}</Size>\n        </Graphic>\n      </PointSymbolizer>`;\n}\n\n/** Fotoapar\u00E1t (photo-marker.js): krou\u017Eek v barv\u011B v\u00FDpln\u011B s obrysem, na n\u011Bm\n * fotoapar\u00E1t v barv\u011B obrysu a objektiv v barv\u011B v\u00FDpln\u011B \u2014 t\u0159i symbolizery\n * nad sebou se stejnou kotvou. */\nfunction photoSymbolizer(rule) {\n    const { ring, camera, lens } = photoMarkerSizes(rule.size);\n    const ink = rule.stroke || '#ffffff';\n    const outline = Number(rule.strokeWidth) > 0\n        ? `<Stroke>\n              <CssParameter name=\"stroke\">${xmlEscape(ink)}</CssParameter>\n              <CssParameter name=\"stroke-width\">${rule.strokeWidth}</CssParameter>\n            </Stroke>`\n        : '';\n    return [\n        markSymbolizer('circle', ring, rule.fill, outline),\n        markSymbolizer(PHOTO_SYMBOL, camera, ink),\n        markSymbolizer('circle', lens, rule.fill),\n    ].join('\\n');\n}\n\n/** Symbol bodu podle pravidla. `photo`: 'with' / 'without' = pravidlo pro\n * prvky s fotkou / bez n\u00ED (fotoapar\u00E1t / te\u010Dka), null = fotoapar\u00E1t v\u0161em. */\nfunction pointSymbolizerFor(rule, photo) {\n    if (rule.symbol !== PHOTO_SYMBOL) return pointSymbolizer(rule);\n    if (photo === 'without') return pointSymbolizer({ ...rule, symbol: 'circle', size: plainDotSize(rule.size) });\n    return photoSymbolizer(rule);\n}\n\nfunction lineSymbolizer(rule) {\n    const dash = rule.dash ? `<CssParameter name=\"stroke-dasharray\">${rule.dash}</CssParameter>` : '';\n    const casing = rule.casing\n        ? `<LineSymbolizer>\n        <Stroke>\n          <CssParameter name=\"stroke\">${xmlEscape(rule.casing)}</CssParameter>\n          <CssParameter name=\"stroke-width\">${(rule.strokeWidth || 2) + 2}</CssParameter>\n        </Stroke>\n      </LineSymbolizer>`\n        : '';\n    return `${casing}\n      <LineSymbolizer>\n        <Stroke>\n          <CssParameter name=\"stroke\">${xmlEscape(rule.stroke)}</CssParameter>\n          <CssParameter name=\"stroke-width\">${rule.strokeWidth}</CssParameter>\n          ${dash}\n        </Stroke>\n      </LineSymbolizer>`;\n}\n\nfunction polygonSymbolizer(rule) {\n    const dash = rule.dash ? `<CssParameter name=\"stroke-dasharray\">${rule.dash}</CssParameter>` : '';\n    // Obrys nulov\u00E9 \u0161\u00ED\u0159ky se nekresl\u00ED v\u016Fbec (Mapserver by ho jinak nakreslil vlasov\u011B).\n    const stroke = Number(rule.strokeWidth) > 0\n        ? `<Stroke>\n          <CssParameter name=\"stroke\">${xmlEscape(rule.stroke)}</CssParameter>\n          <CssParameter name=\"stroke-width\">${rule.strokeWidth}</CssParameter>\n          ${dash}\n        </Stroke>`\n        : '';\n    return `<PolygonSymbolizer>\n        <Fill>\n          <CssParameter name=\"fill\">${xmlEscape(rule.fill)}</CssParameter>\n          <CssParameter name=\"fill-opacity\">${rule.fillOpacity}</CssParameter>\n        </Fill>\n        ${stroke}\n      </PolygonSymbolizer>`;\n}\n\n/** Popisky podvrstvy (labels.js) \u2014 um\u00EDst\u011Bn\u00ED podle jej\u00ED geometrie. */\nfunction textSymbolizer(ctx) {\n    return textSymbolizerXml(ctx.style.labels, {\n        groups: ctx.geometryGroups,\n        markerSize: ctx.style.rules?.point?.size,\n        minZoom: ctx.labelMinZoom,\n    });\n}\n\n/** Vr\u00E1t\u00ED XML symbolizer\u016F (bez obalu Rule) pro danou skupinu geometrie.\n * `category` (kategorie / t\u0159\u00EDda, voliteln\u00E1) p\u0159ebije hlavn\u00ED barvu \u2014 fill u\n * bodu/polygonu, stroke u linie \u2014 a m\u016F\u017Ee n\u00E9st vlastn\u00ED \u0161\u00ED\u0159ku, \u010D\u00E1rkov\u00E1n\u00ED, obrys,\n * velikost \u010Di tvar (`ruleForCategory`); ostatn\u00ED se p\u0159eb\u00EDr\u00E1 ze `style.rules`. */\nfunction symbolizersFor(geometryGroup, style, category, photo) {\n    const baseRule = style.rules[geometryGroup];\n    if (!baseRule) return '';\n    const rule = category ? ruleForCategory(geometryGroup, baseRule, category) : baseRule;\n    if (geometryGroup === 'point') return pointSymbolizerFor(rule, photo);\n    if (geometryGroup === 'line') return lineSymbolizer(rule);\n    return polygonSymbolizer(rule);\n}\n\n/** Symbolizery pro V\u0160ECHNY geometrie podvrstvy (typicky jedna, u nerozd\u011Blen\u00FDch\n * smi\u0161en\u00FDch geometri\u00ED v\u00EDc) pro danou kategorii / t\u0159\u00EDdu \u2014 pou\u017E\u00EDv\u00E1 se v jednom\n * <Rule> pro categorized/graduated. */\nfunction symbolizersForGroups(geometryGroups, style, category, photo) {\n    return Array.from(geometryGroups).map((group) => symbolizersFor(group, style, category, photo)).join('\\n');\n}\n\n/** Vnit\u0159ek filtru pro rovnost atributu (kategorie) \u2014 bez obalu `<ogc:Filter>`,\n * aby \u0161el zkombinovat s atributov\u00FDm filtrem vrstvy (AND). */\nfunction equalFragment(attribute, value) {\n    return `<ogc:PropertyIsEqualTo>\n        <ogc:PropertyName>${xmlEscape(attribute)}</ogc:PropertyName>\n        <ogc:Literal>${xmlEscape(value)}</ogc:Literal>\n      </ogc:PropertyIsEqualTo>`;\n}\n\n/** Vnit\u0159ek filtru pro interval [min, max) \u2014 posledn\u00ED t\u0159\u00EDda odstup\u0148ovan\u00E9ho\n * stylu je uzav\u0159en\u00E1 (\u2264 max), aby maxim\u00E1ln\u00ED hodnota nevypadla ze v\u0161ech t\u0159\u00EDd. */\nfunction rangeFragment(attribute, min, max, isLast) {\n    const upperOp = isLast ? 'PropertyIsLessThanOrEqualTo' : 'PropertyIsLessThan';\n    return `<ogc:And>\n        <ogc:PropertyIsGreaterThanOrEqualTo>\n          <ogc:PropertyName>${xmlEscape(attribute)}</ogc:PropertyName>\n          <ogc:Literal>${xmlEscape(min)}</ogc:Literal>\n        </ogc:PropertyIsGreaterThanOrEqualTo>\n        <ogc:${upperOp}>\n          <ogc:PropertyName>${xmlEscape(attribute)}</ogc:PropertyName>\n          <ogc:Literal>${xmlEscape(max)}</ogc:Literal>\n        </ogc:${upperOp}>\n      </ogc:And>`;\n}\n\n/** Obal\u00ED fragment(y) do `<ogc:Filter>` a p\u0159ipoj\u00ED AND spojkou atributov\u00FD\n * filtr vrstvy (`filterFragment` m\u016F\u017Ee b\u00FDt null). Vrac\u00ED '' pro pr\u00E1zdno. */\nfunction wrapFilter(ruleFragment, filterFragment) {\n    const combined = combineXml([ruleFragment, filterFragment], 'and');\n    return combined ? `<ogc:Filter>${combined}</ogc:Filter>` : '';\n}\n\n/** Prvek m\u00E1 fotku: atribut s fotkami nen\u00ED pr\u00E1zdn\u00FD (NULL Mapserver bere jako ''). */\nfunction hasPhotoFragment(field) {\n    return `<ogc:PropertyIsNotEqualTo>\n        <ogc:PropertyName>${xmlEscape(field)}</ogc:PropertyName>\n        <ogc:Literal></ogc:Literal>\n      </ogc:PropertyIsNotEqualTo>`;\n}\n\n/**\n * Element(y) <Rule> jednoho pravidla stylu (cel\u00E1 vrstva, kategorie, t\u0159\u00EDda).\n *\n * - `fragment` \u2014 vnit\u0159ek filtru pravidla (null = bez vlastn\u00EDho filtru),\n * - `elseFallback` \u2014 pravidlo \u201EOther\u201C: bez filtru vrstvy a bez d\u011Blen\u00ED podle\n *   fotek sta\u010D\u00ED `<ElseFilter/>` (jinak se pou\u017Eije explicitn\u00ED `fragment`),\n * - `title` \u2014 popisek pro GetLegendGraphic.\n *\n * Fotoapar\u00E1t na vrstv\u011B s atributem fotek pravidlo rozd\u011Bl\u00ED: prvky s fotkou ho\n * dostanou, ostatn\u00ED te\u010Dku (photo-marker.js).\n */\nfunction ruleElements(ctx, { fragment = null, elseFallback = false, title = null, category = null }) {\n    const { geometryGroups, style, filterFragment, photoField } = ctx;\n    const head = title !== null ? `<Title>${xmlEscape(title)}</Title>` : '';\n    const label = textSymbolizer(ctx);\n    const basePoint = geometryGroups.has('point') ? style.rules.point : null;\n    const point = basePoint && category ? ruleForCategory('point', basePoint, category) : basePoint;\n    if (!(photoField && point?.symbol === PHOTO_SYMBOL)) {\n        const filter = elseFallback && !filterFragment ? '<ElseFilter/>' : wrapFilter(fragment, filterFragment);\n        return `<Rule>\n      ${head}\n      ${filter}\n      ${symbolizersForGroups(geometryGroups, style, category)}\n      ${label}\n    </Rule>`;\n    }\n    const hasPhoto = hasPhotoFragment(photoField);\n    return [\n        ['with', hasPhoto],\n        ['without', `<ogc:Not>${hasPhoto}</ogc:Not>`],\n    ].map(([photo, photoFragment]) => `<Rule>\n      ${head}\n      ${wrapFilter(combineXml([fragment, photoFragment], 'and'), filterFragment)}\n      ${symbolizersForGroups(geometryGroups, style, category, photo)}\n      ${label}\n    </Rule>`).join('\\n');\n}\n\n/** Jedno pravidlo pro re\u017Eim \"simple\" \u2014 v\u0161echny symbolizery, filtr jen kdy\u017E je\n * aktivn\u00ED atributov\u00FD filtr vrstvy (nebo kdy\u017E se d\u011Bl\u00ED podle fotek). */\nfunction simpleRule(ctx) {\n    return ruleElements(ctx, {});\n}\n\n/** <Rule> na kategorii (`ogc:PropertyIsEqualTo`) + voliteln\u00E9 pravidlo \"Other\"\n * (`<ElseFilter/>`) pro hodnoty nepokryt\u00E9 \u017E\u00E1dnou kategori\u00ED. `<Title>` = popisek\n * kategorie, aby ho GetLegendGraphic vypsal v legend\u011B. */\nfunction categorizedRules(ctx) {\n    const { attribute, categories, other } = ctx.style.categorized || {};\n    if (!attribute || !(categories || []).length) return simpleRule(ctx);\n    const rules = categories.map((cat) => ruleElements(ctx, {\n        title: cat.label || cat.value, fragment: equalFragment(attribute, cat.value), category: cat,\n    }));\n    if (other?.enabled) {\n        // Bez filtru vrstvy sta\u010D\u00ED <ElseFilter/>; s aktivn\u00EDm filtrem by ale\n        // ElseFilter zachytil i prvky filtrem vy\u0159azen\u00E9 (\u201Enepro\u0161ly \u017E\u00E1dn\u00FDm\n        // pravidlem\u201C) \u2014 proto explicitn\u00ED negace v\u0161ech kategori\u00ED AND filtr.\n        rules.push(ruleElements(ctx, {\n            title: 'Other',\n            fragment: `<ogc:Not>${combineXml(categories.map((cat) => equalFragment(attribute, cat.value)), 'or')}</ogc:Not>`,\n            elseFallback: true,\n            category: other,\n        }));\n    }\n    return rules.join('\\n');\n}\n\n/** <Rule> na t\u0159\u00EDdu (`ogc:And` z GreaterThanOrEqualTo + LessThan/LessThanOrEqualTo).\n * `<Title>` = popisek t\u0159\u00EDdy pro GetLegendGraphic. */\nfunction graduatedRules(ctx) {\n    const { attribute, classes } = ctx.style.graduated || {};\n    if (!attribute || !(classes || []).length) return simpleRule(ctx);\n    return classes.map((cls, index) => ruleElements(ctx, {\n        title: cls.label || `${cls.min} \u2013 ${cls.max}`,\n        fragment: rangeFragment(attribute, cls.min, cls.max, index === classes.length - 1),\n        category: cls,\n    })).join('\\n');\n}\n\n/** Vr\u00E1t\u00ED XML v\u0161ech <Rule> element\u016F podvrstvy podle `style.mode`. */\nfunction rulesFor(ctx) {\n    // Re\u017Eim \"native\" SLD b\u011B\u017En\u011B nepos\u00EDl\u00E1 (kresl\u00ED Mapserver stylem z dat); kdy\u017E\n    // ho data nemaj\u00ED (soubor se zm\u011Bnil), vrstva spadne na jednoduch\u00FD styl.\n    if (ctx.style.mode === 'categorized') return categorizedRules(ctx);\n    if (ctx.style.mode === 'graduated') return graduatedRules(ctx);\n    return simpleRule(ctx);\n}\n\n/** Vytvo\u0159\u00ED jeden <NamedLayer> pro danou podvrstvu (sublayer).\n * `filterFragment` = vnit\u0159ek atributov\u00E9ho filtru vrstvy (nebo null). */\nfunction namedLayer(sublayer, style, filterFragment, minZoom) {\n    const geometryGroups = new Set((sublayer.geometry_types || []).map(normalizeGeometryType));\n    if (geometryGroups.size === 0) geometryGroups.add('point');\n    const rules = rulesFor({\n        geometryGroups, style, filterFragment, photoField: photoFieldOf(sublayer.attributes), labelMinZoom: minZoom,\n    });\n    return `<NamedLayer>\n    <Name>${xmlEscape(sublayer.name)}</Name>\n    <UserStyle>\n      <Title>${xmlEscape(sublayer.name)}</Title>\n      <FeatureTypeStyle>\n        ${rules}\n      </FeatureTypeStyle>\n    </UserStyle>\n  </NamedLayer>`;\n}\n\n/** <NamedLayer> v\u0161ech podvrstev vrstvy (bez obalu dokumentu). */\nfunction namedLayers(entry) {\n    const sublayers = entry.sublayers && entry.sublayers.length ? entry.sublayers : [{ name: entry.itemId, geometry_types: entry.geometryTypes }];\n    // Atributov\u00FD filtr vrstvy (filter.js) se kombinuje AND s pravidly stylu \u2014\n    // mapa tak vykresl\u00ED jen prvky odpov\u00EDdaj\u00EDc\u00ED filtru.\n    const filterFragment = filterToXml(entry.filter);\n    const minZoom = labelMinZoom(entry);\n    return sublayers.map((sub) => namedLayer(sub, entry.style, filterFragment, minZoom)).join('\\n');\n}\n\n/** Sestav\u00ED SLD 1.1 dokument pro podvrstvy jedn\u00E9 nebo v\u00EDc vrstev. V\u00EDc vrstev\n * v jednom dokumentu kresl\u00ED n\u00E1hled dat (item-layers.js): jeden GetMap za cel\u00FD\n * soubor, ka\u017Ed\u00E1 vrstva sv\u00FDm stylem. */\nexport function buildSldForEntries(entries) {\n    const layers = entries.map(namedLayers).join('\\n');\n    return `<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<StyledLayerDescriptor version=\"1.1.0\"\n    xmlns=\"http://www.opengis.net/sld\"\n    xmlns:ogc=\"http://www.opengis.net/ogc\"\n    xmlns:xlink=\"http://www.w3.org/1999/xlink\"\n    xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n    xsi:schemaLocation=\"http://www.opengis.net/sld http://schemas.opengis.net/sld/1.1.0/StyledLayerDescriptor.xsd\">\n${layers}\n</StyledLayerDescriptor>`;\n}\n\n/** Sestav\u00ED cel\u00FD SLD 1.1 dokument pro v\u0161echny (zapnut\u00E9) podvrstvy vrstvy. */\nexport function buildSld(entry) {\n    return buildSldForEntries([entry]);\n}\n", "/**\n * @module ol/xml\n */\nimport {extend} from './array.js';\n\n/**\n * When using {@link module:ol/xml.makeChildAppender} or\n * {@link module:ol/xml.makeSimpleNodeFactory}, the top `objectStack` item needs\n * to have this structure.\n * @typedef {Object} NodeStackItem\n * @property {Element} node Node.\n */\n\n/**\n * @typedef {function(Element, Array<*>): void} Parser\n */\n\n/**\n * @typedef {function(Element, *, Array<*>): void} Serializer\n */\n\n/**\n * @type {string}\n */\nexport const XML_SCHEMA_INSTANCE_URI =\n  'http://www.w3.org/2001/XMLSchema-instance';\n\n/**\n * @param {string} namespaceURI Namespace URI.\n * @param {string} qualifiedName Qualified name.\n * @return {Element} Node.\n */\nexport function createElementNS(namespaceURI, qualifiedName) {\n  return getDocument().createElementNS(namespaceURI, qualifiedName);\n}\n\n/**\n * Recursively grab all text content of child nodes into a single string.\n * @param {Node} node Node.\n * @param {boolean} normalizeWhitespace Normalize whitespace: remove all line\n * breaks.\n * @return {string} All text content.\n * @api\n */\nexport function getAllTextContent(node, normalizeWhitespace) {\n  return getAllTextContent_(node, normalizeWhitespace, []).join('');\n}\n\n/**\n * Recursively grab all text content of child nodes into a single string.\n * @param {Node} node Node.\n * @param {boolean} normalizeWhitespace Normalize whitespace: remove all line\n * breaks.\n * @param {Array<string>} accumulator Accumulator.\n * @private\n * @return {Array<string>} Accumulator.\n */\nexport function getAllTextContent_(node, normalizeWhitespace, accumulator) {\n  if (\n    node.nodeType == Node.CDATA_SECTION_NODE ||\n    node.nodeType == Node.TEXT_NODE\n  ) {\n    if (normalizeWhitespace) {\n      accumulator.push(String(node.nodeValue).replace(/(\\r\\n|\\r|\\n)/g, ''));\n    } else {\n      accumulator.push(node.nodeValue);\n    }\n  } else {\n    let n;\n    for (n = node.firstChild; n; n = n.nextSibling) {\n      getAllTextContent_(n, normalizeWhitespace, accumulator);\n    }\n  }\n  return accumulator;\n}\n\n/**\n * @param {Object} object Object.\n * @return {boolean} Is a document.\n */\nexport function isDocument(object) {\n  return 'documentElement' in object;\n}\n\n/**\n * @param {Element} node Node.\n * @param {?string} namespaceURI Namespace URI.\n * @param {string} name Attribute name.\n * @return {string} Value\n */\nexport function getAttributeNS(node, namespaceURI, name) {\n  return node.getAttributeNS(namespaceURI, name) || '';\n}\n\n/**\n * Parse an XML string to an XML Document.\n * @param {string} xml XML.\n * @return {Document} Document.\n * @api\n */\nexport function parse(xml) {\n  return new DOMParser().parseFromString(xml, 'application/xml');\n}\n\n/**\n * Make an array extender function for extending the array at the top of the\n * object stack.\n * @param {function(this: T, Node, Array<*>): (Array<*>|undefined)} valueReader Value reader.\n * @param {T} [thisArg] The object to use as `this` in `valueReader`.\n * @return {Parser} Parser.\n * @template T\n */\nexport function makeArrayExtender(valueReader, thisArg) {\n  return (\n    /**\n     * @param {Node} node Node.\n     * @param {Array<*>} objectStack Object stack.\n     * @this {*}\n     */\n    function (node, objectStack) {\n      const value = valueReader.call(thisArg ?? this, node, objectStack);\n      if (value !== undefined) {\n        const array = /** @type {Array<*>} */ (\n          objectStack[objectStack.length - 1]\n        );\n        extend(array, value);\n      }\n    }\n  );\n}\n\n/**\n * Make an array pusher function for pushing to the array at the top of the\n * object stack.\n * @param {function(this: T, Element, Array<*>): *} valueReader Value reader.\n * @param {T} [thisArg] The object to use as `this` in `valueReader`.\n * @return {Parser} Parser.\n * @template T\n */\nexport function makeArrayPusher(valueReader, thisArg) {\n  return (\n    /**\n     * @param {Element} node Node.\n     * @param {Array<*>} objectStack Object stack.\n     * @this {*}\n     */\n    function (node, objectStack) {\n      const value = valueReader.call(thisArg ?? this, node, objectStack);\n      if (value !== undefined) {\n        const array = /** @type {Array<*>} */ (\n          objectStack[objectStack.length - 1]\n        );\n        array.push(value);\n      }\n    }\n  );\n}\n\n/**\n * Make an object stack replacer function for replacing the object at the\n * top of the stack.\n * @param {function(this: T, Node, Array<*>): *} valueReader Value reader.\n * @param {T} [thisArg] The object to use as `this` in `valueReader`.\n * @return {Parser} Parser.\n * @template T\n */\nexport function makeReplacer(valueReader, thisArg) {\n  return (\n    /**\n     * @param {Node} node Node.\n     * @param {Array<*>} objectStack Object stack.\n     * @this {*}\n     */\n    function (node, objectStack) {\n      const value = valueReader.call(thisArg ?? this, node, objectStack);\n      if (value !== undefined) {\n        objectStack[objectStack.length - 1] = value;\n      }\n    }\n  );\n}\n\n/**\n * Make an object property pusher function for adding a property to the\n * object at the top of the stack.\n * @param {function(this: T, Element, Array<*>): *} valueReader Value reader.\n * @param {string} [property] Property.\n * @param {T} [thisArg] The object to use as `this` in `valueReader`.\n * @return {Parser} Parser.\n * @template T\n */\nexport function makeObjectPropertyPusher(valueReader, property, thisArg) {\n  return (\n    /**\n     * @param {Element} node Node.\n     * @param {Array<*>} objectStack Object stack.\n     * @this {*}\n     */\n    function (node, objectStack) {\n      const value = valueReader.call(thisArg ?? this, node, objectStack);\n      if (value !== undefined) {\n        const object = /** @type {!Object} */ (\n          objectStack[objectStack.length - 1]\n        );\n        const name = property !== undefined ? property : node.localName;\n        let array;\n        if (name in object) {\n          array = object[name];\n        } else {\n          array = [];\n          object[name] = array;\n        }\n        array.push(value);\n      }\n    }\n  );\n}\n\n/**\n * Make an object property setter function.\n * @param {function(this: T, Element, Array<*>): *} valueReader Value reader.\n * @param {string} [property] Property.\n * @param {T} [thisArg] The object to use as `this` in `valueReader`.\n * @return {Parser} Parser.\n * @template T\n */\nexport function makeObjectPropertySetter(valueReader, property, thisArg) {\n  return (\n    /**\n     * @param {Element} node Node.\n     * @param {Array<*>} objectStack Object stack.\n     * @this {*}\n     */\n    function (node, objectStack) {\n      const value = valueReader.call(thisArg ?? this, node, objectStack);\n      if (value !== undefined) {\n        const object = /** @type {!Object} */ (\n          objectStack[objectStack.length - 1]\n        );\n        const name = property !== undefined ? property : node.localName;\n        object[name] = value;\n      }\n    }\n  );\n}\n\n/**\n * Create a serializer that appends nodes written by its `nodeWriter` to its\n * designated parent. The parent is the `node` of the\n * {@link module:ol/xml~NodeStackItem} at the top of the `objectStack`.\n * @param {function(this: T, Node, V, Array<*>): void} nodeWriter Node writer.\n * @param {T} [thisArg] The object to use as `this` in `nodeWriter`.\n * @return {Serializer} Serializer.\n * @template T, V\n */\nexport function makeChildAppender(nodeWriter, thisArg) {\n  return (\n    /**\n     * @param {Element} node Node.\n     * @param {*} value Value to be written.\n     * @param {Array<*>} objectStack Object stack.\n     * @this {*}\n     */\n    function (node, value, objectStack) {\n      nodeWriter.call(thisArg ?? this, node, value, objectStack);\n      const parent = /** @type {NodeStackItem} */ (\n        objectStack[objectStack.length - 1]\n      );\n      const parentNode = parent.node;\n      parentNode.appendChild(node);\n    }\n  );\n}\n\n/**\n * Create a serializer that calls the provided `nodeWriter` from\n * {@link module:ol/xml.serialize}. This can be used by the parent writer to have the\n * `nodeWriter` called with an array of values when the `nodeWriter` was\n * designed to serialize a single item. An example would be a LineString\n * geometry writer, which could be reused for writing MultiLineString\n * geometries.\n * @param {function(this: T, Element, V, Array<*>): void} nodeWriter Node writer.\n * @param {T} [thisArg] The object to use as `this` in `nodeWriter`.\n * @return {Serializer} Serializer.\n * @template T, V\n */\nexport function makeArraySerializer(nodeWriter, thisArg) {\n  let serializersNS, nodeFactory;\n  return function (node, value, objectStack) {\n    if (serializersNS === undefined) {\n      serializersNS = {};\n      const serializers = {};\n      serializers[node.localName] = nodeWriter;\n      serializersNS[node.namespaceURI] = serializers;\n      nodeFactory = makeSimpleNodeFactory(node.localName);\n    }\n    serialize(serializersNS, nodeFactory, value, objectStack);\n  };\n}\n\n/**\n * Create a node factory which can use the `keys` passed to\n * {@link module:ol/xml.serialize} or {@link module:ol/xml.pushSerializeAndPop} as node names,\n * or a fixed node name. The namespace of the created nodes can either be fixed,\n * or the parent namespace will be used.\n * @param {string} [fixedNodeName] Fixed node name which will be used for all\n *     created nodes. If not provided, the 3rd argument to the resulting node\n *     factory needs to be provided and will be the nodeName.\n * @param {string} [fixedNamespaceURI] Fixed namespace URI which will be used for\n *     all created nodes. If not provided, the namespace of the parent node will\n *     be used.\n * @return {function(*, Array<*>, string=): (Node|undefined)} Node factory.\n */\nexport function makeSimpleNodeFactory(fixedNodeName, fixedNamespaceURI) {\n  return (\n    /**\n     * @param {*} value Value.\n     * @param {Array<*>} objectStack Object stack.\n     * @param {string} [newNodeName] Node name.\n     * @return {Node} Node.\n     */\n    function (value, objectStack, newNodeName) {\n      const context = /** @type {NodeStackItem} */ (\n        objectStack[objectStack.length - 1]\n      );\n      const node = context.node;\n      let nodeName = fixedNodeName;\n      if (nodeName === undefined) {\n        nodeName = newNodeName;\n      }\n\n      const namespaceURI =\n        fixedNamespaceURI !== undefined ? fixedNamespaceURI : node.namespaceURI;\n      return createElementNS(namespaceURI, /** @type {string} */ (nodeName));\n    }\n  );\n}\n\n/**\n * A node factory that creates a node using the parent's `namespaceURI` and the\n * `nodeName` passed by {@link module:ol/xml.serialize} or\n * {@link module:ol/xml.pushSerializeAndPop} to the node factory.\n * @const\n * @type {function(*, Array<*>, string=): (Node|undefined)}\n */\nexport const OBJECT_PROPERTY_NODE_FACTORY = makeSimpleNodeFactory();\n\n/**\n * Create an array of `values` to be used with {@link module:ol/xml.serialize} or\n * {@link module:ol/xml.pushSerializeAndPop}, where `orderedKeys` has to be provided as\n * `key` argument.\n * @param {Object<string, *>} object Key-value pairs for the sequence. Keys can\n *     be a subset of the `orderedKeys`.\n * @param {Array<string>} orderedKeys Keys in the order of the sequence.\n * @return {Array<*>} Values in the order of the sequence. The resulting array\n *     has the same length as the `orderedKeys` array. Values that are not\n *     present in `object` will be `undefined` in the resulting array.\n */\nexport function makeSequence(object, orderedKeys) {\n  const length = orderedKeys.length;\n  const sequence = new Array(length);\n  for (let i = 0; i < length; ++i) {\n    sequence[i] = object[orderedKeys[i]];\n  }\n  return sequence;\n}\n\n/**\n * Create a namespaced structure, using the same values for each namespace.\n * This can be used as a starting point for versioned parsers, when only a few\n * values are version specific.\n * @param {Array<string>} namespaceURIs Namespace URIs.\n * @param {T} structure Structure.\n * @param {Object<string, T>} [structureNS] Namespaced structure to add to.\n * @return {Object<string, T>} Namespaced structure.\n * @template T\n */\nexport function makeStructureNS(namespaceURIs, structure, structureNS) {\n  structureNS = structureNS !== undefined ? structureNS : {};\n  let i, ii;\n  for (i = 0, ii = namespaceURIs.length; i < ii; ++i) {\n    structureNS[namespaceURIs[i]] = structure;\n  }\n  return structureNS;\n}\n\n/**\n * Parse a node using the parsers and object stack.\n * @param {Object<string, Object<string, Parser>>} parsersNS\n *     Parsers by namespace.\n * @param {Element} node Node.\n * @param {Array<*>} objectStack Object stack.\n * @param {*} [thisArg] The object to use as `this`.\n */\nexport function parseNode(parsersNS, node, objectStack, thisArg) {\n  let n;\n  for (n = node.firstElementChild; n; n = n.nextElementSibling) {\n    const parsers = parsersNS[n.namespaceURI];\n    if (parsers !== undefined) {\n      const parser = parsers[n.localName];\n      if (parser !== undefined) {\n        parser.call(thisArg, n, objectStack);\n      }\n    }\n  }\n}\n\n/**\n * Push an object on top of the stack, parse and return the popped object.\n * @param {T} object Object.\n * @param {Object<string, Object<string, Parser>>} parsersNS\n *     Parsers by namespace.\n * @param {Element} node Node.\n * @param {Array<*>} objectStack Object stack.\n * @param {*} [thisArg] The object to use as `this`.\n * @return {T} Object.\n * @template T\n */\nexport function pushParseAndPop(object, parsersNS, node, objectStack, thisArg) {\n  objectStack.push(object);\n  parseNode(parsersNS, node, objectStack, thisArg);\n  return /** @type {T} */ (objectStack.pop());\n}\n\n/**\n * Walk through an array of `values` and call a serializer for each value.\n * @param {Object<string, Object<string, Serializer>>} serializersNS\n *     Namespaced serializers.\n * @param {function(this: T, *, Array<*>, (string|undefined)): (Node|undefined)} nodeFactory\n *     Node factory. The `nodeFactory` creates the node whose namespace and name\n *     will be used to choose a node writer from `serializersNS`. This\n *     separation allows us to decide what kind of node to create, depending on\n *     the value we want to serialize. An example for this would be different\n *     geometry writers based on the geometry type.\n * @param {Array<*>} values Values to serialize. An example would be an array\n *     of {@link module:ol/Feature~Feature} instances.\n * @param {Array<*>} objectStack Node stack.\n * @param {Array<string>} [keys] Keys of the `values`. Will be passed to the\n *     `nodeFactory`. This is used for serializing object literals where the\n *     node name relates to the property key. The array length of `keys` has\n *     to match the length of `values`. For serializing a sequence, `keys`\n *     determines the order of the sequence.\n * @param {T} [thisArg] The object to use as `this` for the node factory and\n *     serializers.\n * @template T\n */\nexport function serialize(\n  serializersNS,\n  nodeFactory,\n  values,\n  objectStack,\n  keys,\n  thisArg,\n) {\n  const length = (keys !== undefined ? keys : values).length;\n  let value, node;\n  for (let i = 0; i < length; ++i) {\n    value = values[i];\n    if (value !== undefined) {\n      node = nodeFactory.call(\n        thisArg,\n        value,\n        objectStack,\n        keys !== undefined ? keys[i] : undefined,\n      );\n      if (node !== undefined) {\n        serializersNS[node.namespaceURI][node.localName].call(\n          thisArg,\n          node,\n          value,\n          objectStack,\n        );\n      }\n    }\n  }\n}\n\n/**\n * @param {O} object Object.\n * @param {Object<string, Object<string, Serializer>>} serializersNS\n *     Namespaced serializers.\n * @param {function(this: T, *, Array<*>, (string|undefined)): (Node|undefined)} nodeFactory\n *     Node factory. The `nodeFactory` creates the node whose namespace and name\n *     will be used to choose a node writer from `serializersNS`. This\n *     separation allows us to decide what kind of node to create, depending on\n *     the value we want to serialize. An example for this would be different\n *     geometry writers based on the geometry type.\n * @param {Array<*>} values Values to serialize. An example would be an array\n *     of {@link module:ol/Feature~Feature} instances.\n * @param {Array<*>} objectStack Node stack.\n * @param {Array<string>} [keys] Keys of the `values`. Will be passed to the\n *     `nodeFactory`. This is used for serializing object literals where the\n *     node name relates to the property key. The array length of `keys` has\n *     to match the length of `values`. For serializing a sequence, `keys`\n *     determines the order of the sequence.\n * @param {T} [thisArg] The object to use as `this` for the node factory and\n *     serializers.\n * @return {O|undefined} Object.\n * @template O, T\n */\nexport function pushSerializeAndPop(\n  object,\n  serializersNS,\n  nodeFactory,\n  values,\n  objectStack,\n  keys,\n  thisArg,\n) {\n  objectStack.push(object);\n  serialize(serializersNS, nodeFactory, values, objectStack, keys, thisArg);\n  return /** @type {O|undefined} */ (objectStack.pop());\n}\n\nlet xmlSerializer_ = undefined;\n\n/**\n * Register a XMLSerializer. Can be used  to inject a XMLSerializer\n * where there is no globally available implementation.\n *\n * @param {XMLSerializer} xmlSerializer A XMLSerializer.\n * @api\n */\nexport function registerXMLSerializer(xmlSerializer) {\n  xmlSerializer_ = xmlSerializer;\n}\n\n/**\n * @return {XMLSerializer} The XMLSerializer.\n */\nexport function getXMLSerializer() {\n  if (xmlSerializer_ === undefined && typeof XMLSerializer !== 'undefined') {\n    xmlSerializer_ = new XMLSerializer();\n  }\n  return xmlSerializer_;\n}\n\nlet document_ = undefined;\n\n/**\n * Register a Document to use when creating nodes for XML serializations. Can be used\n * to inject a Document where there is no globally available implementation.\n *\n * @param {Document} document A Document.\n * @api\n */\nexport function registerDocument(document) {\n  document_ = document;\n}\n\n/**\n * Get a document that should be used when creating nodes for XML serializations.\n * @return {Document} The document.\n */\nexport function getDocument() {\n  if (document_ === undefined && typeof document !== 'undefined') {\n    document_ = document.implementation.createDocument('', '', null);\n  }\n  return document_;\n}\n", "/**\n * @module ol/format/XML\n */\nimport {abstract} from '../util.js';\nimport {isDocument, parse} from '../xml.js';\n\n/**\n * @classdesc\n * Generic format for reading non-feature XML data\n *\n * @abstract\n */\nclass XML {\n  /**\n   * Read the source document.\n   *\n   * @param {Document|Element|string} source The XML source.\n   * @return {Object|null} An object representing the source.\n   * @api\n   */\n  read(source) {\n    if (!source) {\n      return null;\n    }\n    if (typeof source === 'string') {\n      const doc = parse(source);\n      return this.readFromDocument(doc);\n    }\n    if (isDocument(source)) {\n      return this.readFromDocument(/** @type {Document} */ (source));\n    }\n    return this.readFromNode(/** @type {Element} */ (source));\n  }\n\n  /**\n   * @param {Document} doc Document.\n   * @return {Object|null} Object\n   */\n  readFromDocument(doc) {\n    for (let n = doc.firstChild; n; n = n.nextSibling) {\n      if (n.nodeType == Node.ELEMENT_NODE) {\n        return this.readFromNode(/** @type {Element} */ (n));\n      }\n    }\n    return null;\n  }\n\n  /**\n   * @abstract\n   * @param {Element} node Node.\n   * @return {Object|null} Object\n   */\n  readFromNode(node) {\n    abstract();\n  }\n}\n\nexport default XML;\n", "/**\n * @module ol/format/xlink\n */\n\n/**\n * @const\n * @type {string}\n */\nconst NAMESPACE_URI = 'http://www.w3.org/1999/xlink';\n\n/**\n * @param {Element} node Node.\n * @return {string|null} href.\n */\nexport function readHref(node) {\n  return node.getAttributeNS(NAMESPACE_URI, 'href');\n}\n", "/**\n * @module ol/format/xsd\n */\nimport {padNumber} from '../string.js';\nimport {getAllTextContent, getDocument} from '../xml.js';\n\n/**\n * @param {Node} node Node.\n * @return {boolean|undefined} Boolean.\n */\nexport function readBoolean(node) {\n  const s = getAllTextContent(node, false);\n  return readBooleanString(s);\n}\n\n/**\n * @param {string} string String.\n * @return {boolean|undefined} Boolean.\n */\nexport function readBooleanString(string) {\n  const m = /^\\s*(true|1)|(false|0)\\s*$/.exec(string);\n  if (m) {\n    return m[1] !== undefined || false;\n  }\n  return undefined;\n}\n\n/**\n * @param {Node} node Node.\n * @return {number|undefined} DateTime in seconds.\n */\nexport function readDateTime(node) {\n  const s = getAllTextContent(node, false);\n  const dateTime = Date.parse(s);\n  return isNaN(dateTime) ? undefined : dateTime / 1000;\n}\n\n/**\n * @param {Node} node Node.\n * @return {number|undefined} Decimal.\n */\nexport function readDecimal(node) {\n  const s = getAllTextContent(node, false);\n  return readDecimalString(s);\n}\n\n/**\n * @param {string} string String.\n * @return {number|undefined} Decimal.\n */\nexport function readDecimalString(string) {\n  // FIXME check spec\n  const m = /^\\s*([+\\-]?\\d*\\.?\\d+(?:e[+\\-]?\\d+)?)\\s*$/i.exec(string);\n  if (m) {\n    return parseFloat(m[1]);\n  }\n  return undefined;\n}\n\n/**\n * @param {Node} node Node.\n * @return {number|undefined} Non negative integer.\n */\nexport function readPositiveInteger(node) {\n  const s = getAllTextContent(node, false);\n  return readNonNegativeIntegerString(s);\n}\n\n/**\n * @param {string} string String.\n * @return {number|undefined} Non negative integer.\n */\nexport function readNonNegativeIntegerString(string) {\n  const m = /^\\s*(\\d+)\\s*$/.exec(string);\n  if (m) {\n    return parseInt(m[1], 10);\n  }\n  return undefined;\n}\n\n/**\n * @param {Node} node Node.\n * @return {string|undefined} String.\n */\nexport function readString(node) {\n  return getAllTextContent(node, false).trim();\n}\n\n/**\n * @param {Node} node Node to append a TextNode with the boolean to.\n * @param {boolean} bool Boolean.\n */\nexport function writeBooleanTextNode(node, bool) {\n  writeStringTextNode(node, bool ? '1' : '0');\n}\n\n/**\n * @param {Node} node Node to append a CDATA Section with the string to.\n * @param {string} string String.\n */\nexport function writeCDATASection(node, string) {\n  node.appendChild(getDocument().createCDATASection(string));\n}\n\n/**\n * @param {Node} node Node to append a TextNode with the dateTime to.\n * @param {number} dateTime DateTime in seconds.\n */\nexport function writeDateTimeTextNode(node, dateTime) {\n  const date = new Date(dateTime * 1000);\n  const string =\n    date.getUTCFullYear() +\n    '-' +\n    padNumber(date.getUTCMonth() + 1, 2) +\n    '-' +\n    padNumber(date.getUTCDate(), 2) +\n    'T' +\n    padNumber(date.getUTCHours(), 2) +\n    ':' +\n    padNumber(date.getUTCMinutes(), 2) +\n    ':' +\n    padNumber(date.getUTCSeconds(), 2) +\n    'Z';\n  node.appendChild(getDocument().createTextNode(string));\n}\n\n/**\n * @param {Node} node Node to append a TextNode with the decimal to.\n * @param {number} decimal Decimal.\n */\nexport function writeDecimalTextNode(node, decimal) {\n  const string = decimal.toPrecision();\n  node.appendChild(getDocument().createTextNode(string));\n}\n\n/**\n * @param {Node} node Node to append a TextNode with the decimal to.\n * @param {number} nonNegativeInteger Non negative integer.\n */\nexport function writeNonNegativeIntegerTextNode(node, nonNegativeInteger) {\n  const string = nonNegativeInteger.toString();\n  node.appendChild(getDocument().createTextNode(string));\n}\n\nconst whiteSpaceStart = /^\\s/;\nconst whiteSpaceEnd = /\\s$/;\nconst cdataCharacters = /(\\n|\\t|\\r|<|&| {2})/;\n\n/**\n * @param {Node} node Node to append a TextNode with the string to.\n * @param {string} string String.\n */\nexport function writeStringTextNode(node, string) {\n  if (\n    typeof string === 'string' &&\n    (whiteSpaceStart.test(string) ||\n      whiteSpaceEnd.test(string) ||\n      cdataCharacters.test(string))\n  ) {\n    string.split(']]>').forEach((part, i, a) => {\n      if (i < a.length - 1) {\n        part += ']]';\n      }\n      if (i > 0) {\n        part = '>' + part;\n      }\n      writeCDATASection(node, part);\n    });\n  } else {\n    node.appendChild(getDocument().createTextNode(string));\n  }\n}\n", "/**\n * @module ol/format/WMSCapabilities\n */\nimport {compareVersions} from '../string.js';\nimport {\n  makeArrayPusher,\n  makeObjectPropertyPusher,\n  makeObjectPropertySetter,\n  makeStructureNS,\n  pushParseAndPop,\n} from '../xml.js';\nimport XML from './XML.js';\nimport {readHref} from './xlink.js';\nimport {\n  readBooleanString,\n  readDecimal,\n  readDecimalString,\n  readNonNegativeIntegerString,\n  readPositiveInteger,\n  readString,\n} from './xsd.js';\n\n/**\n * @const\n * @type {Array<null|string>}\n */\nconst NAMESPACE_URIS = [\n  null,\n  'http://www.opengis.net/wms',\n  'http://www.opengis.net/sld',\n];\n\nfunction isV13(objectStack) {\n  return compareVersions(objectStack[0].version, '1.3') >= 0;\n}\n\n/**\n * @const\n * @type {Object<string, Object<string, import(\"../xml.js\").Parser>>}\n */\n// @ts-ignore\nconst PARSERS = makeStructureNS(NAMESPACE_URIS, {\n  'Service': makeObjectPropertySetter(readService),\n  'Capability': makeObjectPropertySetter(readCapability),\n});\n\n/**\n * @const\n * @type {Object<string, Object<string, import(\"../xml.js\").Parser>>}\n */\n// @ts-ignore\nconst CAPABILITY_PARSERS = makeStructureNS(NAMESPACE_URIS, {\n  'Request': makeObjectPropertySetter(readRequest),\n  'Exception': makeObjectPropertySetter(readException),\n  'Layer': makeObjectPropertySetter(readCapabilityLayer),\n  'UserDefinedSymbolization': makeObjectPropertySetter(\n    readUserDefinedSymbolization,\n  ),\n});\n\n/**\n * @typedef {Object} RootObject\n * @property {string} version Version\n * @property {boolean} v13 Whether version is 1.3 or higher\n */\n\n/**\n * @classdesc\n * Format for reading WMS capabilities data\n *\n * @api\n */\nclass WMSCapabilities extends XML {\n  constructor() {\n    super();\n\n    /**\n     * @type {string|undefined}\n     */\n    this.version = undefined;\n  }\n\n  /**\n   * @param {Element} node Node.\n   * @return {Object|null} Object\n   * @override\n   */\n  readFromNode(node) {\n    this.version = node.getAttribute('version').trim();\n    const wmsCapabilityObject = pushParseAndPop(\n      {\n        'version': this.version,\n      },\n      PARSERS,\n      node,\n      [],\n    );\n    return wmsCapabilityObject ? wmsCapabilityObject : null;\n  }\n}\n\nconst COMMON_SERVICE_PARSERS = {\n  'Name': makeObjectPropertySetter(readString),\n  'Title': makeObjectPropertySetter(readString),\n  'Abstract': makeObjectPropertySetter(readString),\n  'KeywordList': makeObjectPropertySetter(readKeywordList),\n  'OnlineResource': makeObjectPropertySetter(readHref),\n  'ContactInformation': makeObjectPropertySetter(readContactInformation),\n  'Fees': makeObjectPropertySetter(readString),\n  'AccessConstraints': makeObjectPropertySetter(readString),\n};\n\n/**\n * @const\n * @type {Object<string, Object<string, import(\"../xml.js\").Parser>>}\n */\n// @ts-ignore\nconst SERVICE_PARSERS = makeStructureNS(NAMESPACE_URIS, COMMON_SERVICE_PARSERS);\n\n/**\n * @const\n * @type {Object<string, Object<string, import(\"../xml.js\").Parser>>}\n */\n// @ts-ignore\nconst SERVICE_PARSERS_V13 = makeStructureNS(NAMESPACE_URIS, {\n  ...COMMON_SERVICE_PARSERS,\n  'LayerLimit': makeObjectPropertySetter(readPositiveInteger),\n  'MaxWidth': makeObjectPropertySetter(readPositiveInteger),\n  'MaxHeight': makeObjectPropertySetter(readPositiveInteger),\n});\n\n/**\n * @const\n * @type {Object<string, Object<string, import(\"../xml.js\").Parser>>}\n */\n// @ts-ignore\nconst CONTACT_INFORMATION_PARSERS = makeStructureNS(NAMESPACE_URIS, {\n  'ContactPersonPrimary': makeObjectPropertySetter(readContactPersonPrimary),\n  'ContactPosition': makeObjectPropertySetter(readString),\n  'ContactAddress': makeObjectPropertySetter(readContactAddress),\n  'ContactVoiceTelephone': makeObjectPropertySetter(readString),\n  'ContactFacsimileTelephone': makeObjectPropertySetter(readString),\n  'ContactElectronicMailAddress': makeObjectPropertySetter(readString),\n});\n\n/**\n * @const\n * @type {Object<string, Object<string, import(\"../xml.js\").Parser>>}\n */\n// @ts-ignore\nconst CONTACT_PERSON_PARSERS = makeStructureNS(NAMESPACE_URIS, {\n  'ContactPerson': makeObjectPropertySetter(readString),\n  'ContactOrganization': makeObjectPropertySetter(readString),\n});\n\n/**\n * @const\n * @type {Object<string, Object<string, import(\"../xml.js\").Parser>>}\n */\n// @ts-ignore\nconst CONTACT_ADDRESS_PARSERS = makeStructureNS(NAMESPACE_URIS, {\n  'AddressType': makeObjectPropertySetter(readString),\n  'Address': makeObjectPropertySetter(readString),\n  'City': makeObjectPropertySetter(readString),\n  'StateOrProvince': makeObjectPropertySetter(readString),\n  'PostCode': makeObjectPropertySetter(readString),\n  'Country': makeObjectPropertySetter(readString),\n});\n\n/**\n * @const\n * @type {Object<string, Object<string, import(\"../xml.js\").Parser>>}\n */\n// @ts-ignore\nconst EXCEPTION_PARSERS = makeStructureNS(NAMESPACE_URIS, {\n  'Format': makeArrayPusher(readString),\n});\n\nconst COMMON_LAYER_PARSERS = {\n  'Name': makeObjectPropertySetter(readString),\n  'Title': makeObjectPropertySetter(readString),\n  'Abstract': makeObjectPropertySetter(readString),\n  'KeywordList': makeObjectPropertySetter(readKeywordList),\n  'BoundingBox': makeObjectPropertyPusher(readBoundingBox),\n  'Dimension': makeObjectPropertyPusher(readDimension),\n  'Attribution': makeObjectPropertySetter(readAttribution),\n  'AuthorityURL': makeObjectPropertyPusher(readAuthorityURL),\n  'Identifier': makeObjectPropertyPusher(readString),\n  'MetadataURL': makeObjectPropertyPusher(readMetadataURL),\n  'DataURL': makeObjectPropertyPusher(readFormatOnlineresource),\n  'FeatureListURL': makeObjectPropertyPusher(readFormatOnlineresource),\n  'Style': makeObjectPropertyPusher(readStyle),\n  'Layer': makeObjectPropertyPusher(readLayer),\n};\n\n/**\n * @const\n * @type {Object<string, Object<string, import(\"../xml.js\").Parser>>}\n */\n// @ts-ignore\nconst LAYER_PARSERS = makeStructureNS(NAMESPACE_URIS, {\n  ...COMMON_LAYER_PARSERS,\n  'SRS': makeObjectPropertyPusher(readString),\n  'Extent': makeObjectPropertySetter(readExtent),\n  'ScaleHint': makeObjectPropertyPusher(readScaleHint),\n  'LatLonBoundingBox': makeObjectPropertySetter((node, objectStack) =>\n    readBoundingBox(node, objectStack, false),\n  ),\n  'Layer': makeObjectPropertyPusher(readLayer),\n});\n\n/**\n * @const\n * @type {Object<string, Object<string, import(\"../xml.js\").Parser>>}\n */\n// @ts-ignore\nconst LAYER_PARSERS_V13 = makeStructureNS(NAMESPACE_URIS, {\n  ...COMMON_LAYER_PARSERS,\n  'CRS': makeObjectPropertyPusher(readString),\n  'EX_GeographicBoundingBox': makeObjectPropertySetter(\n    readEXGeographicBoundingBox,\n  ),\n  'MinScaleDenominator': makeObjectPropertySetter(readDecimal),\n  'MaxScaleDenominator': makeObjectPropertySetter(readDecimal),\n  'Layer': makeObjectPropertyPusher(readLayer),\n});\n\n/**\n * @const\n * @type {Object<string, Object<string, import(\"../xml.js\").Parser>>}\n */\n// @ts-ignore\nconst ATTRIBUTION_PARSERS = makeStructureNS(NAMESPACE_URIS, {\n  'Title': makeObjectPropertySetter(readString),\n  'OnlineResource': makeObjectPropertySetter(readHref),\n  'LogoURL': makeObjectPropertySetter(readSizedFormatOnlineresource),\n});\n\n/**\n * @const\n * @type {Object<string, Object<string, import(\"../xml.js\").Parser>>}\n */\n// @ts-ignore\nconst EX_GEOGRAPHIC_BOUNDING_BOX_PARSERS = makeStructureNS(NAMESPACE_URIS, {\n  'westBoundLongitude': makeObjectPropertySetter(readDecimal),\n  'eastBoundLongitude': makeObjectPropertySetter(readDecimal),\n  'southBoundLatitude': makeObjectPropertySetter(readDecimal),\n  'northBoundLatitude': makeObjectPropertySetter(readDecimal),\n});\n\n/**\n * @const\n * @type {Object<string, Object<string, import(\"../xml.js\").Parser>>}\n */\n// @ts-ignore\nconst REQUEST_PARSERS = makeStructureNS(NAMESPACE_URIS, {\n  'GetCapabilities': makeObjectPropertySetter(readOperationType),\n  'GetMap': makeObjectPropertySetter(readOperationType),\n  'GetFeatureInfo': makeObjectPropertySetter(readOperationType),\n  'DescribeLayer': makeObjectPropertySetter(readOperationType),\n  'GetLegendGraphic': makeObjectPropertySetter(readOperationType),\n});\n\n/**\n * @const\n * @type {Object<string, Object<string, import(\"../xml.js\").Parser>>}\n */\n// @ts-ignore\nconst OPERATIONTYPE_PARSERS = makeStructureNS(NAMESPACE_URIS, {\n  'Format': makeObjectPropertyPusher(readString),\n  'DCPType': makeObjectPropertyPusher(readDCPType),\n});\n\n/**\n * @const\n * @type {Object<string, Object<string, import(\"../xml.js\").Parser>>}\n */\n// @ts-ignore\nconst DCPTYPE_PARSERS = makeStructureNS(NAMESPACE_URIS, {\n  'HTTP': makeObjectPropertySetter(readHTTP),\n});\n\n/**\n * @const\n * @type {Object<string, Object<string, import(\"../xml.js\").Parser>>}\n */\n// @ts-ignore\nconst HTTP_PARSERS = makeStructureNS(NAMESPACE_URIS, {\n  'Get': makeObjectPropertySetter(readFormatOnlineresource),\n  'Post': makeObjectPropertySetter(readFormatOnlineresource),\n});\n\n/**\n * @const\n * @type {Object<string, Object<string, import(\"../xml.js\").Parser>>}\n */\n// @ts-ignore\nconst STYLE_PARSERS = makeStructureNS(NAMESPACE_URIS, {\n  'Name': makeObjectPropertySetter(readString),\n  'Title': makeObjectPropertySetter(readString),\n  'Abstract': makeObjectPropertySetter(readString),\n  'LegendURL': makeObjectPropertyPusher(readSizedFormatOnlineresource),\n  'StyleSheetURL': makeObjectPropertySetter(readFormatOnlineresource),\n  'StyleURL': makeObjectPropertySetter(readFormatOnlineresource),\n});\n\n/**\n * @const\n * @type {Object<string, Object<string, import(\"../xml.js\").Parser>>}\n */\n// @ts-ignore\nconst FORMAT_ONLINERESOURCE_PARSERS = makeStructureNS(NAMESPACE_URIS, {\n  'Format': makeObjectPropertySetter(readString),\n  'OnlineResource': makeObjectPropertySetter(readHref),\n});\n\n/**\n * @const\n * @type {Object<string, Object<string, import(\"../xml.js\").Parser>>}\n */\n// @ts-ignore\nconst KEYWORDLIST_PARSERS = makeStructureNS(NAMESPACE_URIS, {\n  'Keyword': makeArrayPusher(readString),\n});\n\n/**\n * @param {Element} node Node.\n * @param {Array<*>} objectStack Object stack.\n * @return {Object|undefined} Attribution object.\n */\nfunction readAttribution(node, objectStack) {\n  return pushParseAndPop({}, ATTRIBUTION_PARSERS, node, objectStack);\n}\n\nfunction readUserDefinedSymbolization(node, objectStack) {\n  return {\n    'SupportSLD': !!readBooleanString(node.getAttribute('SupportSLD')),\n    'UserLayer': !!readBooleanString(node.getAttribute('UserLayer')),\n    'UserStyle': !!readBooleanString(node.getAttribute('UserStyle')),\n    'RemoteWFS': !!readBooleanString(node.getAttribute('RemoteWFS')),\n    'InlineFeatureData': !!readBooleanString(\n      node.getAttribute('InlineFeatureData'),\n    ),\n    'RemoteWCS': !!readBooleanString(node.getAttribute('RemoteWCS')),\n  };\n}\n\n/**\n * @param {Element} node Node.\n * @param {Array<*>} objectStack Object stack.\n * @param {boolean} withCrs Whether to include the CRS attribute.\n * @return {Object} Bounding box object.\n */\nfunction readBoundingBox(node, objectStack, withCrs = true) {\n  const extent = [\n    readDecimalString(node.getAttribute('minx')),\n    readDecimalString(node.getAttribute('miny')),\n    readDecimalString(node.getAttribute('maxx')),\n    readDecimalString(node.getAttribute('maxy')),\n  ];\n\n  const resolutions = [\n    readDecimalString(node.getAttribute('resx')),\n    readDecimalString(node.getAttribute('resy')),\n  ];\n\n  const result = {\n    extent,\n    res: resolutions,\n  };\n  if (!withCrs) {\n    return result;\n  }\n\n  /** @type {RootObject} */\n  if (isV13(objectStack)) {\n    result.crs = node.getAttribute('CRS');\n  } else {\n    result.srs = node.getAttribute('SRS');\n  }\n\n  return result;\n}\n\n/**\n * @param {Element} node Node.\n * @param {Array<*>} objectStack Object stack.\n * @return {import(\"../extent.js\").Extent|undefined} Bounding box object.\n */\nfunction readEXGeographicBoundingBox(node, objectStack) {\n  const geographicBoundingBox = pushParseAndPop(\n    {},\n    EX_GEOGRAPHIC_BOUNDING_BOX_PARSERS,\n    node,\n    objectStack,\n  );\n  if (!geographicBoundingBox) {\n    return undefined;\n  }\n  const westBoundLongitude =\n    /** @type {number|undefined} */\n    (geographicBoundingBox['westBoundLongitude']);\n  const southBoundLatitude =\n    /** @type {number|undefined} */\n    (geographicBoundingBox['southBoundLatitude']);\n  const eastBoundLongitude =\n    /** @type {number|undefined} */\n    (geographicBoundingBox['eastBoundLongitude']);\n  const northBoundLatitude =\n    /** @type {number|undefined} */\n    (geographicBoundingBox['northBoundLatitude']);\n  if (\n    westBoundLongitude === undefined ||\n    southBoundLatitude === undefined ||\n    eastBoundLongitude === undefined ||\n    northBoundLatitude === undefined\n  ) {\n    return undefined;\n  }\n  return [\n    westBoundLongitude,\n    southBoundLatitude,\n    eastBoundLongitude,\n    northBoundLatitude,\n  ];\n}\n\n/**\n * @param {Element} node Node.\n * @param {Array<*>} objectStack Object stack.\n * @return {Object|undefined} Capability object.\n */\n//ts-ignore\nfunction readCapability(node, objectStack) {\n  return pushParseAndPop({}, CAPABILITY_PARSERS, node, objectStack);\n}\n\n/**\n * @param {Element} node Node.\n * @param {Array<*>} objectStack Object stack.\n * @return {Object|undefined} Service object.\n */\nfunction readService(node, objectStack) {\n  return pushParseAndPop(\n    {},\n    isV13(objectStack) ? SERVICE_PARSERS_V13 : SERVICE_PARSERS,\n    node,\n    objectStack,\n  );\n}\n\n/**\n * @param {Element} node Node.\n * @param {Array<*>} objectStack Object stack.\n * @return {Object|undefined} Contact information object.\n */\nfunction readContactInformation(node, objectStack) {\n  return pushParseAndPop({}, CONTACT_INFORMATION_PARSERS, node, objectStack);\n}\n\n/**\n * @param {Element} node Node.\n * @param {Array<*>} objectStack Object stack.\n * @return {Object|undefined} Contact person object.\n */\nfunction readContactPersonPrimary(node, objectStack) {\n  return pushParseAndPop({}, CONTACT_PERSON_PARSERS, node, objectStack);\n}\n\n/**\n * @param {Element} node Node.\n * @param {Array<*>} objectStack Object stack.\n * @return {Object|undefined} Contact address object.\n */\nfunction readContactAddress(node, objectStack) {\n  return pushParseAndPop({}, CONTACT_ADDRESS_PARSERS, node, objectStack);\n}\n\n/**\n * @param {Element} node Node.\n * @param {Array<*>} objectStack Object stack.\n * @return {Array<string>|undefined} Format array.\n */\nfunction readException(node, objectStack) {\n  return pushParseAndPop([], EXCEPTION_PARSERS, node, objectStack);\n}\n\n/**\n * @param {Element} node Node.\n * @param {Array<*>} objectStack Object stack.\n * @return {Object|undefined} Layer object.\n */\nfunction readCapabilityLayer(node, objectStack) {\n  const layerObject = pushParseAndPop(\n    {},\n    isV13(objectStack) ? LAYER_PARSERS_V13 : LAYER_PARSERS,\n    node,\n    objectStack,\n  );\n\n  if (layerObject['Layer'] === undefined) {\n    return Object.assign(layerObject, readLayer(node, objectStack));\n  }\n\n  return layerObject;\n}\n\n/**\n * @param {Element} node Node.\n * @param {Array<*>} objectStack Object stack.\n * @return {Object|undefined} Layer object.\n */\nfunction readLayer(node, objectStack) {\n  const v13 = isV13(objectStack);\n\n  const parentLayerObject = /**  @type {!Object<string,*>} */ (\n    objectStack[objectStack.length - 1]\n  );\n\n  const layerObject = pushParseAndPop(\n    {},\n    v13 ? LAYER_PARSERS_V13 : LAYER_PARSERS,\n    node,\n    objectStack,\n  );\n\n  if (!layerObject) {\n    return undefined;\n  }\n  let queryable = readBooleanString(node.getAttribute('queryable'));\n  if (queryable === undefined) {\n    queryable = parentLayerObject['queryable'];\n  }\n  layerObject['queryable'] = queryable !== undefined ? queryable : false;\n\n  let cascaded = readNonNegativeIntegerString(node.getAttribute('cascaded'));\n  if (cascaded === undefined) {\n    cascaded = parentLayerObject['cascaded'];\n  }\n  layerObject['cascaded'] = cascaded;\n\n  let opaque = readBooleanString(node.getAttribute('opaque'));\n  if (opaque === undefined) {\n    opaque = parentLayerObject['opaque'];\n  }\n  layerObject['opaque'] = opaque !== undefined ? opaque : false;\n\n  let noSubsets = readBooleanString(node.getAttribute('noSubsets'));\n  if (noSubsets === undefined) {\n    noSubsets = parentLayerObject['noSubsets'];\n  }\n  layerObject['noSubsets'] = noSubsets !== undefined ? noSubsets : false;\n\n  let fixedWidth = readDecimalString(node.getAttribute('fixedWidth'));\n  if (!fixedWidth) {\n    fixedWidth = parentLayerObject['fixedWidth'];\n  }\n  layerObject['fixedWidth'] = fixedWidth;\n\n  let fixedHeight = readDecimalString(node.getAttribute('fixedHeight'));\n  if (!fixedHeight) {\n    fixedHeight = parentLayerObject['fixedHeight'];\n  }\n  layerObject['fixedHeight'] = fixedHeight;\n\n  // See 7.2.4.8\n  const addKeys = ['Style', 'AuthorityURL'];\n  if (v13) {\n    addKeys.push('CRS');\n  } else {\n    addKeys.push('SRS', 'Dimension');\n  }\n  addKeys.forEach(function (key) {\n    if (key in parentLayerObject) {\n      const childValue = layerObject[key] || [];\n      layerObject[key] = childValue.concat(parentLayerObject[key]);\n    }\n  });\n\n  const replaceKeys = ['BoundingBox', 'Attribution'];\n  if (v13) {\n    replaceKeys.push(\n      'Dimension',\n      'EX_GeographicBoundingBox',\n      'MinScaleDenominator',\n      'MaxScaleDenominator',\n    );\n  } else {\n    replaceKeys.push('LatLonBoundingBox', 'ScaleHint', 'Extent');\n  }\n  replaceKeys.forEach(function (key) {\n    if (!(key in layerObject)) {\n      const parentValue = parentLayerObject[key];\n      layerObject[key] = parentValue;\n    }\n  });\n\n  return layerObject;\n}\n\n/**\n * @param {Element} node Node.\n * @param {Array<*>} objectStack Object stack.\n * @return {Object} Dimension object.\n */\nfunction readDimension(node, objectStack) {\n  const dimensionObject = {\n    'name': node.getAttribute('name'),\n    'units': node.getAttribute('units'),\n    'unitSymbol': node.getAttribute('unitSymbol'),\n  };\n\n  if (isV13(objectStack)) {\n    Object.assign(dimensionObject, {\n      'default': node.getAttribute('default'),\n      'multipleValues': readBooleanString(node.getAttribute('multipleValues')),\n      'nearestValue': readBooleanString(node.getAttribute('nearestValue')),\n      'current': readBooleanString(node.getAttribute('current')),\n      'values': readString(node),\n    });\n  }\n  return dimensionObject;\n}\n\n/**\n * @param {Element} node Node.\n * @param {Array<*>} objectStack Object stack.\n * @return {Object} Extent object.\n */\nfunction readExtent(node, objectStack) {\n  return {\n    'name': node.getAttribute('name'),\n    'default': node.getAttribute('default'),\n    'nearestValue': readBooleanString(node.getAttribute('nearestValue')),\n  };\n}\n\n/**\n * @param {Element} node Node.\n * @param {Array<*>} objectStack Object stack.\n * @return {Object} ScaleHint object.\n */\nfunction readScaleHint(node, objectStack) {\n  return {\n    'min': readDecimalString(node.getAttribute('min')),\n    'max': readDecimalString(node.getAttribute('max')),\n  };\n}\n\n/**\n * @param {Element} node Node.\n * @param {Array<*>} objectStack Object stack.\n * @return {Object|undefined} Online resource object.\n */\nfunction readFormatOnlineresource(node, objectStack) {\n  return pushParseAndPop({}, FORMAT_ONLINERESOURCE_PARSERS, node, objectStack);\n}\n\n/**\n * @param {Element} node Node.\n * @param {Array<*>} objectStack Object stack.\n * @return {Object|undefined} Request object.\n */\nfunction readRequest(node, objectStack) {\n  return pushParseAndPop({}, REQUEST_PARSERS, node, objectStack);\n}\n\n/**\n * @param {Element} node Node.\n * @param {Array<*>} objectStack Object stack.\n * @return {Object|undefined} DCP type object.\n */\nfunction readDCPType(node, objectStack) {\n  return pushParseAndPop({}, DCPTYPE_PARSERS, node, objectStack);\n}\n\n/**\n * @param {Element} node Node.\n * @param {Array<*>} objectStack Object stack.\n * @return {Object|undefined} HTTP object.\n */\nfunction readHTTP(node, objectStack) {\n  return pushParseAndPop({}, HTTP_PARSERS, node, objectStack);\n}\n\n/**\n * @param {Element} node Node.\n * @param {Array<*>} objectStack Object stack.\n * @return {Object|undefined} Operation type object.\n */\nfunction readOperationType(node, objectStack) {\n  return pushParseAndPop({}, OPERATIONTYPE_PARSERS, node, objectStack);\n}\n\n/**\n * @param {Element} node Node.\n * @param {Array<*>} objectStack Object stack.\n * @return {Object|undefined} Online resource object.\n */\nfunction readSizedFormatOnlineresource(node, objectStack) {\n  const formatOnlineresource = readFormatOnlineresource(node, objectStack);\n  if (formatOnlineresource) {\n    const size = [\n      readNonNegativeIntegerString(node.getAttribute('width')),\n      readNonNegativeIntegerString(node.getAttribute('height')),\n    ];\n    formatOnlineresource['size'] = size;\n    return formatOnlineresource;\n  }\n  return undefined;\n}\n\n/**\n * @param {Element} node Node.\n * @param {Array<*>} objectStack Object stack.\n * @return {Object|undefined} Authority URL object.\n */\nfunction readAuthorityURL(node, objectStack) {\n  const authorityObject = readFormatOnlineresource(node, objectStack);\n  if (authorityObject) {\n    authorityObject['name'] = node.getAttribute('name');\n    return authorityObject;\n  }\n  return undefined;\n}\n\n/**\n * @param {Element} node Node.\n * @param {Array<*>} objectStack Object stack.\n * @return {Object|undefined} Metadata URL object.\n */\nfunction readMetadataURL(node, objectStack) {\n  const metadataObject = readFormatOnlineresource(node, objectStack);\n  if (metadataObject) {\n    metadataObject['type'] = node.getAttribute('type');\n    return metadataObject;\n  }\n  return undefined;\n}\n\n/**\n * @param {Element} node Node.\n * @param {Array<*>} objectStack Object stack.\n * @return {Object|undefined} Style object.\n */\nfunction readStyle(node, objectStack) {\n  return pushParseAndPop({}, STYLE_PARSERS, node, objectStack);\n}\n\n/**\n * @param {Element} node Node.\n * @param {Array<*>} objectStack Object stack.\n * @return {Array<string>|undefined} Keyword list.\n */\nfunction readKeywordList(node, objectStack) {\n  return pushParseAndPop([], KEYWORDLIST_PARSERS, node, objectStack);\n}\n\nexport default WMSCapabilities;\n", "/**\n * hybrid.js \u2014 hybridn\u00ED polo\u017Eky workspace (vektor + rastr v jednom souboru,\n * `data_type: \"hybrid\"`, nap\u0159. GeoPDF s ortofotem pod vektory) a diagnostick\u00E9\n * hlavi\u010Dky MapServeru (GCZ).\n *\n * Hybrid je ve workspace JEDNA polo\u017Eka, ale na map\u011B se kresl\u00ED ze dvou \u010D\u00E1st\u00ED:\n * rastrov\u00E1 vrstva dole, vektorov\u00E9 vrstvy nad n\u00ED. Ve stromu vrstev z n\u00ED proto\n * vznikne jedna skupina (n\u00E1zev souboru) se dv\u011Bma b\u011Bhov\u00FDmi z\u00E1znamy \u2014 vektor\n * (`hybridPart: \"vector\"`) a rastr (`hybridPart: \"raster\"`), ka\u017Ed\u00FD s vlastn\u00EDm\n * GetMap (SLD styl vektoru, BANDS/GRAY_CLIP rastru).\n *\n * N\u00E1zvy vrstev obou \u010D\u00E1st\u00ED p\u0159edpov\u00EDd\u00E1 backend (`layers` / `raster_layers`\n * z /items/<id>/wms/); skute\u010Dn\u00E9 si ov\u011B\u0159\u00EDme u slu\u017Eby \u2014 z hlavi\u010Dky\n * `X-GCZ-Hybrid-Layers` (`[{group, source, raster[], vector[]}]`), p\u0159\u00EDpadn\u011B\n * z GetCapabilities (`<KeywordList>`: `kind=raster|vector`, `hybrid=<group>`).\n *\n * `X-GCZ-Skipped-Layers` (`[{name, kind, reason, code}]`) \u0159\u00EDk\u00E1, kterou \u010D\u00E1st\n * souboru slu\u017Eba nevykreslila a pro\u010D; text pro u\u017Eivatele podle `code` dod\u00E1v\u00E1\n * backend v bootstrapu (`skipReasons`). Ob\u011B hlavi\u010Dky maj\u00ED limit ~6 kB \u2014 co se\n * nevejde, nahrad\u00ED koncov\u00FD prvek `{\"omitted\": n}`.\n */\nimport WMSCapabilities from 'ol/format/WMSCapabilities.js';\n\nexport const SKIPPED_LAYERS_HEADER = 'X-GCZ-Skipped-Layers';\nexport const HYBRID_LAYERS_HEADER = 'X-GCZ-Hybrid-Layers';\n\n/** Ikona hybridu (SVG cesty pro viewBox 24\u00D724): vektorov\u00E1 linie nad rastrovou\n * m\u0159\u00ED\u017Ekou \u2014 stejn\u00FD motiv jako v Data workspace (`_type_icon.html`). */\nexport const HYBRID_ICON_PATHS = '<path d=\"m2 15 10 5 10-5-10-5z\"/><path d=\"m7 12.5 10 5\"/><path d=\"m17 12.5-10 5\"/><path d=\"m4 9 5-5 5 3 6-4\"/>';\n\n/** V\u00FDchoz\u00ED vysv\u011Btlen\u00ED, kdy\u017E slu\u017Eba nepo\u0161le k\u00F3d ani d\u016Fvod. */\nconst DEFAULT_SKIP_REASON = 'This part of the file cannot be drawn on the map.';\n\n/** Omezen\u00E1 JSON hlavi\u010Dka GCZ \u2192 `{ records, omitted }` (tolerantn\u00ED k chyb\u00E1m). */\nfunction headerRecords(raw, wrapperKeys) {\n    const empty = { records: [], omitted: 0 };\n    if (typeof raw !== 'string' || !raw.trim()) return empty;\n    let data;\n    try {\n        data = JSON.parse(raw);\n    } catch {\n        return empty;\n    }\n    if (data && typeof data === 'object' && !Array.isArray(data)) {\n        const key = wrapperKeys.find((k) => data[k]);\n        data = key ? data[key] : [data];\n    }\n    if (!Array.isArray(data)) return empty;\n    const records = [];\n    let omitted = 0;\n    data.forEach((entry) => {\n        const isObject = entry && typeof entry === 'object' && !Array.isArray(entry);\n        if (isObject && 'omitted' in entry && Object.keys(entry).length === 1) {\n            omitted += Math.max(Number(entry.omitted) || 0, 0);\n            return;\n        }\n        records.push(entry);\n    });\n    return { records, omitted };\n}\n\n/** `X-GCZ-Skipped-Layers` \u2192 `{ layers: [{name, kind, reason, code}], omitted }`. */\nexport function parseSkippedLayers(raw) {\n    const { records, omitted } = headerRecords(raw, ['layers', 'skipped']);\n    const layers = [];\n    records.forEach((entry) => {\n        if (typeof entry === 'string' && entry) layers.push({ name: entry });\n        else if (entry && typeof entry === 'object' && !Array.isArray(entry)) layers.push({ ...entry });\n    });\n    return { layers, omitted };\n}\n\nconst names = (value) => (Array.isArray(value) ? value.filter((v) => typeof v === 'string' && v) : []);\n\n/** `X-GCZ-Hybrid-Layers` \u2192 `{ groups: [{group, source, raster[], vector[], rasterOpenOptions}], omitted }`. */\nexport function parseHybridLayers(raw) {\n    const { records, omitted } = headerRecords(raw, ['hybrid', 'groups']);\n    const groups = [];\n    records.forEach((entry) => {\n        if (!entry || typeof entry !== 'object' || Array.isArray(entry) || !entry.group) return;\n        groups.push({\n            group: String(entry.group),\n            source: String(entry.source || ''),\n            raster: names(entry.raster),\n            vector: names(entry.vector),\n            rasterOpenOptions: entry.rasterOpenOptions && typeof entry.rasterOpenOptions === 'object'\n                ? { ...entry.rasterOpenOptions }\n                : {},\n        });\n    });\n    return { groups, omitted };\n}\n\n/** Ob\u011B diagnostick\u00E9 hlavi\u010Dky z odpov\u011Bdi slu\u017Eby (`Headers` z fetch). */\nexport function readDiagnostics(headers) {\n    const get = (name) => (headers && typeof headers.get === 'function' ? headers.get(name) : null);\n    return {\n        skipped: parseSkippedLayers(get(SKIPPED_LAYERS_HEADER)),\n        hybrid: parseHybridLayers(get(HYBRID_LAYERS_HEADER)),\n    };\n}\n\n/** Lidsk\u00E9 vysv\u011Btlen\u00ED p\u0159esko\u010Den\u00E9 \u010D\u00E1sti: text podle `code` z bootstrapu, jinak `reason` slu\u017Eby. */\nexport function skippedReasonText(layer, reasons) {\n    return (layer?.code && reasons?.[layer.code]) || layer?.reason || DEFAULT_SKIP_REASON;\n}\n\n/* ---------------------------------------------------------------------------\n * Rozlo\u017Een\u00ED hybridu na vektorovou a rastrovou \u010D\u00E1st\n * ------------------------------------------------------------------------- */\n\n/** Rozlo\u017Een\u00ED podle predikce backendu (bez dotazu na slu\u017Ebu). */\nfunction predictedLayout(detail) {\n    return {\n        vector: detail.layers || [],\n        raster: detail.raster_layers || [],\n        verified: false,\n        diagnostics: null,\n    };\n}\n\n/** Z\u00E1znam hlavi\u010Dky pat\u0159\u00EDc\u00ED k polo\u017Ece: podle `group`, pak `source`, pak jedin\u00FD z\u00E1znam. */\nfunction matchGroup(groups, detail) {\n    if (!groups.length) return null;\n    const expected = detail.hybrid?.group;\n    const source = detail.hybrid?.source;\n    return groups.find((g) => expected && g.group === expected)\n        || groups.find((g) => source && g.source === source)\n        || (groups.length === 1 ? groups[0] : null);\n}\n\n/** Zplo\u0161t\u00ED strom vrstev z GetCapabilities (jen vrstvy s `Name`). */\nfunction flattenCapsLayers(layer, out = []) {\n    if (!layer) return out;\n    if (layer.Name) out.push(layer);\n    (layer.Layer || []).forEach((child) => flattenCapsLayers(child, out));\n    return out;\n}\n\n/** Kl\u00ED\u010Dov\u00E1 slova vrstvy (`kind=\u2026`, `hybrid=\u2026`) \u2014 tolerantn\u00ED i k \u201Ea,b\" v jednom slov\u011B. */\nfunction keywords(layer) {\n    return (layer.KeywordList || [])\n        .flatMap((k) => String(k?.value ?? k ?? '').split(','))\n        .map((k) => k.trim())\n        .filter(Boolean);\n}\n\n/** Skupina hybridu z GetCapabilities: `{ raster: [names], vector: [names] }`, jinak null. */\nexport function groupFromCapabilities(text, detail) {\n    let caps;\n    try {\n        caps = new WMSCapabilities().read(text);\n    } catch {\n        return null;\n    }\n    const groups = new Map();\n    flattenCapsLayers(caps?.Capability?.Layer).forEach((layer) => {\n        const words = keywords(layer);\n        const group = words.find((w) => w.startsWith('hybrid='))?.slice('hybrid='.length);\n        if (!group) return;\n        const kind = words.find((w) => w.startsWith('kind='))?.slice('kind='.length);\n        if (!groups.has(group)) groups.set(group, { group, source: '', raster: [], vector: [] });\n        groups.get(group)[kind === 'raster' ? 'raster' : 'vector'].push(layer.Name);\n    });\n    return matchGroup(Array.from(groups.values()), detail);\n}\n\n/** P\u0159ejmenuje podvrstvy podle n\u00E1zv\u016F ze slu\u017Eby. Metadata (geometrie, atributy)\n * bere z predikce podle jm\u00E9na, p\u0159i shodn\u00E9m po\u010Dtu podle po\u0159ad\u00ED. */\nfunction applyNames(predicted, wanted) {\n    if (!wanted?.length) return predicted;\n    const byName = new Map(predicted.map((layer) => [layer.name, layer]));\n    const samePositions = predicted.length === wanted.length;\n    return wanted.map((name, index) => byName.get(name)\n        || (samePositions ? { ...predicted[index], name } : {\n            name, source_layer: name, geometry_types: [], attributes: [], feature_count: null,\n        }));\n}\n\n/** GetCapabilities URL slu\u017Eby s podepsan\u00FDmi parametry polo\u017Eky. */\nfunction capabilitiesUrl(serviceUrl, params) {\n    const url = new URL(serviceUrl, window.location.href);\n    url.searchParams.set('SERVICE', 'WMS');\n    url.searchParams.set('VERSION', '1.3.0');\n    url.searchParams.set('REQUEST', 'GetCapabilities');\n    ['FILE_URL', 'sig', 'PAYER', 'FILE_CRS'].forEach((key) => {\n        if (params?.[key]) url.searchParams.set(key, params[key]);\n    });\n    return url.toString();\n}\n\nasync function loadLayout(detail, serviceUrl) {\n    const predicted = predictedLayout(detail);\n    const response = await fetch(capabilitiesUrl(serviceUrl, detail.params));\n    if (!response.ok) return predicted;\n    const diagnostics = readDiagnostics(response.headers);\n    let group = matchGroup(diagnostics.hybrid.groups, detail);\n    if (!group) group = groupFromCapabilities(await response.text(), detail);\n    if (!group) return { ...predicted, diagnostics };\n    return {\n        vector: applyNames(predicted.vector, group.vector),\n        raster: applyNames(predicted.raster, group.raster),\n        verified: true,\n        diagnostics,\n    };\n}\n\n/** Sd\u00EDlen\u00E9 rozlo\u017Een\u00ED na polo\u017Eku \u2014 ob\u011B \u010D\u00E1sti (vektor i rastr) obnovovan\u00E9\n * z ulo\u017Een\u00E9 mapy se tak ptaj\u00ED slu\u017Eby jen jednou. */\nconst layoutCache = new Map();\n\n/**\n * Rozlo\u017Een\u00ED hybridu `{ vector: [sublayers], raster: [sublayers], verified,\n * diagnostics }`. Kdy\u017E se dotaz na slu\u017Ebu nepovede (s\u00ED\u0165, CORS, chyba), vr\u00E1t\u00ED\n * predikci backendu \u2014 hybrid se tak vykresl\u00ED i se star\u0161\u00EDmi verzemi slu\u017Eby.\n */\nexport function resolveHybridLayout(detail, serviceUrl) {\n    const key = `${detail.id}|${detail.params?.FILE_URL || ''}`;\n    if (!layoutCache.has(key)) {\n        const promise = serviceUrl\n            ? loadLayout(detail, serviceUrl).catch(() => predictedLayout(detail))\n            : Promise.resolve(predictedLayout(detail));\n        layoutCache.set(key, promise);\n    }\n    return layoutCache.get(key);\n}\n\n/** Detail jedn\u00E9 \u010D\u00E1sti hybridu ve tvaru b\u011B\u017En\u00E9 vektorov\u00E9/rastrov\u00E9 polo\u017Eky\n * (vstup pro `createLayerEntry`). */\nexport function hybridPartDetail(detail, part, layout) {\n    const raster = part === 'raster';\n    return {\n        ...detail,\n        data_type: raster ? 'raster' : 'vector',\n        item_data_type: 'hybrid',\n        hybrid_part: raster ? 'raster' : 'vector',\n        layers: raster ? layout.raster : layout.vector,\n        bands: raster ? (detail.bands || []) : null,\n    };\n}\n\n/** V\u00FDchoz\u00ED n\u00E1zvy \u010D\u00E1st\u00ED hybridu ve stromu vrstev. */\nexport function hybridPartTitle(part) {\n    return part === 'raster' ? 'Raster image' : 'Vector layers';\n}\n", "/**\n * image-format.js \u2014 form\u00E1t obr\u00E1zku, kter\u00FD si vrstva \u017E\u00E1d\u00E1 od mapov\u00E9 slu\u017Eby.\n *\n * Barevn\u00FD sn\u00EDmek (RGB) se \u017E\u00E1d\u00E1 ve sm\u00ED\u0161en\u00E9m form\u00E1tu `image/vnd.jpeg-webp`: JPEG\n * tam, kde je obr\u00E1zek cel\u00FD nepr\u016Fhledn\u00FD, jinak WebP s pr\u016Fhlednost\u00ED. Na\n * pr\u016Fhlednosti se t\u00EDm nic nem\u011Bn\u00ED (okraj rastru, nato\u010Den\u00FD nebo p\u0159epo\u010D\u00EDtan\u00FD\n * obr\u00E1zek a nodata), obr\u00E1zek je ale n\u011Bkolikr\u00E1t men\u0161\u00ED. Fotka s pr\u016Fhledn\u00FDm\n * okrajem jako PNG \u010Dasto p\u0159es\u00E1hne, co mapov\u00E1 slu\u017Eba na Lambd\u011B sm\u00ED poslat\n * (6 MB po base64; pohled ortofota 2304 \u00D7 1378 px m\u00E1 6,7 MB jako PNG a 0,9 MB\n * jako WebP) \u2014 prohl\u00ED\u017Ee\u010D pak hl\u00E1s\u00ED chybu CORS a vrstva se p\u0159estane kreslit.\n * Vektory, jednop\u00E1smov\u00E9 rastry a rastry s paletou maj\u00ED ostr\u00E9 hrany a z\u016Fst\u00E1vaj\u00ED\n * v PNG.\n *\n * `mixedImages` z nastaven\u00ED mapy (`MAPS_RASTER_MIXED_FORMAT`): `'webp'` nebo\n * `true` = JPEG/WebP, `'png'` = JPEG/PNG (mapov\u00E1 slu\u017Eba bez WebP), `false` =\n * v\u017Edy PNG.\n */\nexport const PNG_FORMAT = 'image/png';\nexport const MIXED_FORMAT = 'image/vnd.jpeg-webp';\nexport const MIXED_PNG_FORMAT = 'image/vnd.jpeg-png';\n\nlet mixedFormat = MIXED_FORMAT;\n\nexport function setMixedImages(setting) {\n    if (setting === false) mixedFormat = null;\n    else if (setting === 'png') mixedFormat = MIXED_PNG_FORMAT;\n    else mixedFormat = MIXED_FORMAT;\n}\n\nexport function imageFormat(entry) {\n    if (mixedFormat && entry?.dataType === 'raster' && entry.style?.mode === 'rgb') return mixedFormat;\n    return PNG_FORMAT;\n}\n", "/**\n * loading.js \u2014 indikace, \u017Ee se \u010Dek\u00E1 na vykreslen\u00ED mapy.\n *\n * V\u011Bt\u0161\u00ED vrstvu Mapserver kresl\u00ED i n\u011Bkolik sekund (prvn\u00ED na\u010Dten\u00ED, posun, zoom,\n * zm\u011Bna stylu) a mapa mezit\u00EDm vypad\u00E1 \u201Ehotov\u00E1, ale pr\u00E1zdn\u00E1\u201C. U\u017Eivatel proto\n * dostane t\u0159i nen\u00E1siln\u00E9 sign\u00E1ly \u2014 \u017E\u00E1dn\u00FD z nich neblokuje pr\u00E1ci s mapou:\n *\n *  1. tenk\u00FD b\u011B\u017E\u00EDc\u00ED pruh u horn\u00EDho okraje mapy + kurzor \u201Epracuji\u201C nad mapou,\n *  2. \u0161t\u00EDtek v rohu mapy se jm\u00E9nem vrstvy, na kterou se \u010Dek\u00E1 (\u201ERendering\n *     Roads\u2026\u201C), po del\u0161\u00ED dob\u011B dopln\u011Bn\u00FD o vysv\u011Btlen\u00ED,\n *  3. to\u010D\u00EDc\u00ED se kole\u010Dko u vrstvy ve stromu vrstev (a v\u00FDstra\u017En\u00E1 ikona s\n *     mo\u017Enost\u00ED \u201Ezkusit znovu\u201C, kdy\u017E se vykreslen\u00ED nepovede).\n *\n * Kr\u00E1tk\u00E1 na\u010Dten\u00ED (do `SHOW_DELAY` ms) se neindikuj\u00ED v\u016Fbec, aby mapa p\u0159i\n * b\u011B\u017En\u00E9m posunu neblikala.\n *\n * Zdroje vrstev hl\u00E1s\u00ED stav p\u0159es `trackSourceLoading` (wms.js, external.js),\n * kter\u00FD po\u010D\u00EDt\u00E1 rozpracovan\u00E9 po\u017Eadavky na vrstvu (`entry.pending`) a vys\u00EDl\u00E1\n * ud\u00E1lost `layer:loading`.\n */\nimport { emit, on } from './utils.js';\nimport { flatLayers, isEffectivelyVisible } from './state.js';\n\n/** Krat\u0161\u00ED na\u010D\u00EDt\u00E1n\u00ED neindikujeme (ms). */\nconst SHOW_DELAY = 350;\n/** Po t\u00E9to dob\u011B (ms) \u0161t\u00EDtek dopln\u00ED vysv\u011Btlen\u00ED, \u017Ee velk\u00E1 data trvaj\u00ED d\u00E9le. */\nconst SLOW_AFTER = 6000;\n\n/**\n * Napoj\u00ED zdroj vrstvy na indikaci na\u010D\u00EDt\u00E1n\u00ED. `kind` = 'image' (ImageWMS \u2014 jeden\n * obr\u00E1zek na v\u00FD\u0159ez) nebo 'tile' (dla\u017Edice). Po\u010D\u00EDt\u00E1 rozpracovan\u00E9 po\u017Eadavky do\n * `entry.pending`, chybu posledn\u00EDho po\u017Eadavku dr\u017E\u00ED v `entry.loadError`.\n */\nexport function trackSourceLoading(entry, source, kind = 'image') {\n    if (!entry || !source?.on) return;\n    entry.pending = 0;\n    entry.loadError = false;\n    const prefix = kind === 'tile' ? 'tile' : 'image';\n    source.on(`${prefix}loadstart`, () => {\n        if (entry.pending === 0) entry.loadStartedAt = performance.now();\n        entry.pending += 1;\n        emit('layer:loading', { entry });\n    });\n    source.on(`${prefix}loadend`, () => {\n        entry.pending = Math.max(0, entry.pending - 1);\n        // Doba jednoho vykreslen\u00ED (jen jeden obr\u00E1zek na v\u00FD\u0159ez \u2014 u dla\u017Edic by\n        // \u010D\u00EDslo nic ne\u0159\u00EDkalo). Posledn\u00EDch p\u011Bt si vrstva pamatuje; podle nich\n        // advisor.js pozn\u00E1 data, kter\u00E1 se kresl\u00ED pomalu.\n        if (kind !== 'tile' && entry.pending === 0 && entry.loadStartedAt) {\n            const seconds = (performance.now() - entry.loadStartedAt) / 1000;\n            entry.loadStartedAt = 0;\n            entry.renderTimes = [...(entry.renderTimes || []), seconds].slice(-5);\n            emit('layer:render-time', { entry, seconds });\n        }\n        // Dla\u017Edice: jedna \u00FAsp\u011B\u0161n\u00E1 chybu ostatn\u00EDch nema\u017Ee; obr\u00E1zek ano.\n        if (kind !== 'tile') entry.loadError = false;\n        emit('layer:loading', { entry });\n    });\n    source.on(`${prefix}loaderror`, () => {\n        entry.pending = Math.max(0, entry.pending - 1);\n        // Ojedin\u011Bl\u00E1 chyb\u011Bj\u00EDc\u00ED dla\u017Edice nen\u00ED chyba vrstvy (okraj pokryt\u00ED slu\u017Eby).\n        if (kind !== 'tile') entry.loadError = true;\n        emit('layer:loading', { entry, error: kind !== 'tile' });\n    });\n}\n\n/* ---------------------------------------------------------------------------\n * P\u0159\u00EDprava vrstvy\n *\n * Ne\u017E se vrstva objev\u00ED ve stromu, aplikace se pt\u00E1 na jej\u00ED detail a na popis\n * dat u Mapserveru. U velk\u00E9ho textov\u00E9ho souboru to trv\u00E1 i des\u00EDtky sekund\n * (prvn\u00ED \u010Dten\u00ED souboru) a mapa by mezit\u00EDm ml\u010Dela. Proto se o p\u0159ipravovan\u00E9\n * vrstv\u011B v\u00ED hned: \u0159\u00E1dek ve stromu vrstev a \u0161t\u00EDtek nad mapou.\n * ------------------------------------------------------------------------- */\n\nlet preparingSeq = 0;\n\n/** Ohl\u00E1s\u00ED, \u017Ee se p\u0159ipravuje vrstva. Vrac\u00ED z\u00E1znam pro `updatePreparing` /\n * `endPreparing`. `note` = up\u0159esn\u011Bn\u00ED do z\u00E1vorky (velikost a form\u00E1t). */\nexport function beginPreparing(ctx, title, note = '') {\n    preparingSeq += 1;\n    const item = { key: `prep-${preparingSeq}`, title: title || 'data', note };\n    ctx.state.preparing = [...(ctx.state.preparing || []), item];\n    emit('layer:preparing', { item });\n    return item;\n}\n\nexport function updatePreparing(ctx, item, changes) {\n    if (!item) return;\n    Object.assign(item, changes);\n    emit('layer:preparing', { item });\n}\n\nexport function endPreparing(ctx, item) {\n    if (!item) return;\n    ctx.state.preparing = (ctx.state.preparing || []).filter((other) => other !== item);\n    emit('layer:preparing', { item, done: true });\n}\n\n/** \u201E152 MB GeoJSON\u201C \u2014 jen u dat, u kter\u00FDch m\u00E1 smysl varovat, \u017Ee to potrv\u00E1. */\nexport function sizeNote(source) {\n    const bytes = Number(source?.size_bytes) || 0;\n    if (bytes < 5 * 1048576) return '';\n    const size = bytes >= 1048576 * 1024 ? `${(bytes / 1073741824).toFixed(1)} GB` : `${Math.round(bytes / 1048576)} MB`;\n    return [size, source.format || source.driver || ''].filter(Boolean).join(' ');\n}\n\n/** Vrstvy, na jejich\u017E vykreslen\u00ED se pr\u00E1v\u011B \u010Dek\u00E1 (jen viditeln\u00E9). */\nfunction loadingEntries(ctx) {\n    return flatLayers(ctx.state)\n        .filter((entry) => entry.pending > 0 && isEffectivelyVisible(ctx.state, entry));\n}\n\n/**\n * Inicializuje indikaci nad mapou. Vrac\u00ED `{ isLoading() }`.\n */\nexport function initLoadingIndicator(ctx) {\n    const host = ctx.elements.mapTarget?.parentElement;\n    if (!host) return { isLoading: () => false };\n\n    const bar = document.createElement('div');\n    bar.className = 'map-loading-bar';\n    bar.setAttribute('aria-hidden', 'true');\n    bar.innerHTML = '<span></span>';\n    bar.hidden = true;\n\n    const pill = document.createElement('div');\n    pill.className = 'map-loading-pill';\n    pill.setAttribute('role', 'status');\n    pill.setAttribute('aria-live', 'polite');\n    pill.hidden = true;\n\n    host.append(bar, pill);\n\n    let showTimer = null;\n    let slowTimer = null;\n    let visible = false;\n    let slow = false;\n\n    function pillText(entries) {\n        const preparing = ctx.state.preparing || [];\n        if (preparing.length) {\n            // P\u0159\u00EDprava m\u00E1 p\u0159ednost: dokud nen\u00ED popis dat, nen\u00ED co kreslit.\n            const [first] = preparing;\n            // Soubor nahr\u00E1van\u00FD z mapy (upload.js) \u2014 pr\u016Fb\u011Bh m\u00EDsto \u201EOpening\u201C.\n            if (preparing.length === 1 && first.status) return `\u201C${first.title}\u201D \u2014 ${first.status}`;\n            const what = preparing.length === 1\n                ? `Opening \u201C${first.title}\u201D${first.note ? ` (${first.note})` : ''}\u2026`\n                : `Opening ${preparing.length} layers\u2026`;\n            return slow ? `${what} Reading large data for the first time takes a while.` : what;\n        }\n        const what = entries.length === 1\n            ? `Rendering \u201C${entries[0].title}\u201D\u2026`\n            : `Rendering ${entries.length} layers\u2026`;\n        return slow ? `${what} Large data can take a while.` : what;\n    }\n\n    function renderPill(entries) {\n        pill.innerHTML = '<span class=\"map-spinner flex-none\" aria-hidden=\"true\"></span><span class=\"min-w-0 truncate\"></span>';\n        pill.lastElementChild.textContent = pillText(entries);\n    }\n\n    function show(entries) {\n        visible = true;\n        bar.hidden = false;\n        pill.hidden = false;\n        ctx.elements.mapTarget.classList.add('is-rendering');\n        renderPill(entries);\n        clearTimeout(slowTimer);\n        slowTimer = setTimeout(() => {\n            slow = true;\n            const current = loadingEntries(ctx);\n            if (current.length || busy()) renderPill(current);\n        }, SLOW_AFTER);\n    }\n\n    function hide() {\n        clearTimeout(showTimer);\n        clearTimeout(slowTimer);\n        showTimer = null;\n        slow = false;\n        if (!visible) return;\n        visible = false;\n        bar.hidden = true;\n        pill.hidden = true;\n        ctx.elements.mapTarget.classList.remove('is-rendering');\n    }\n\n    /** P\u0159ipravuje se n\u011Bjak\u00E1 vrstva (\u010Dek\u00E1 se na popis dat)? */\n    function busy() {\n        return (ctx.state.preparing || []).length > 0;\n    }\n\n    function update() {\n        const entries = loadingEntries(ctx);\n        if (entries.length === 0 && !busy()) {\n            hide();\n            return;\n        }\n        if (visible) {\n            renderPill(entries);\n        } else if (!showTimer) {\n            showTimer = setTimeout(() => {\n                showTimer = null;\n                const current = loadingEntries(ctx);\n                if (current.length || busy()) show(current);\n            }, SHOW_DELAY);\n        }\n    }\n\n    on('layer:loading', update);\n    on('layer:preparing', update);\n    // Skryt\u00ED/odebr\u00E1n\u00ED vrstvy uprost\u0159ed na\u010D\u00EDt\u00E1n\u00ED \u2014 p\u0159epo\u010D\u00EDtat, na co se \u010Dek\u00E1.\n    on('layers:changed', ({ reason } = {}) => {\n        if (reason === 'visibility' || reason === 'remove' || reason === 'remove-group') update();\n    });\n\n    return { isLoading: () => loadingEntries(ctx).length > 0 || busy() };\n}\n", "/**\n * wms-params.js \u2014 parametry GetMap jedn\u00E9 vrstvy mapy (LAYERS, SLD_BODY,\n * volby rastru, podpis zdroje dat) podle jej\u00EDho stylu.\n *\n * Modul je bez OpenLayers a bez DOM: krom\u011B mapy (wms.js, persist.js) ho\n * pou\u017E\u00EDv\u00E1 i n\u00E1hled dat v Data workspace, kter\u00FD si parametry v\u00FDchoz\u00EDho stylu\n * nech\u00E1 na serveru spo\u010D\u00EDtat stejn\u00FDm k\u00F3dem (item-layers.js, preview-cli.mjs).\n */\nimport { buildSld } from './sld.js';\nimport { filterToXml } from './filter.js';\nimport { imageFormat } from './image-format.js';\n\n/** Podepsan\u00E9 parametry zdroje dat pro Mapserver: FILE_URL + sig, p\u0159i \u00FA\u010Dtov\u00E1n\u00ED\n * map (zad\u00E1n\u00ED 06, R14) i PAYER \u2014 pl\u00E1tce je sou\u010D\u00E1st\u00ED podpisu, GeoCzech m\u011B\u0159\u00ED\n * dobu vykreslen\u00ED jen pro ov\u011B\u0159en\u00E9ho pl\u00E1tce. */\nexport function signedParams(entry) {\n    const params = {\n        FILE_URL: entry.wms?.fileUrl || '',\n        sig: entry.wms?.sig || '',\n    };\n    if (entry.wms?.payer) params.PAYER = entry.wms.payer;\n    // Ru\u010Dn\u011B p\u0159i\u0159azen\u00E9 / nenativn\u00ED CRS polo\u017Eky (nen\u00ED sou\u010D\u00E1st\u00ED podpisu).\n    if (entry.wms?.fileCrs) params.FILE_CRS = entry.wms.fileCrs;\n    return params;\n}\n\n/** Kresl\u00ED se vrstva stylem ulo\u017Een\u00FDm v datech (re\u017Eim \"native\" a data ho maj\u00ED)? */\nexport function usesNativeStyle(entry) {\n    return entry.dataType === 'vector' && entry.style?.mode === 'native' && Boolean(entry.native?.available);\n}\n\n/** Volby vykreslen\u00ED rastru pro Mapserver (`BANDS`, `STRETCH`, `RANGE`,\n * `COLORMAP`) podle stylu vrstvy \u2014 stejn\u00E9 pos\u00EDl\u00E1 GetMap i dotaz na legendu. */\nexport function rasterParams(entry) {\n    const style = entry.style || {};\n    const params = {};\n    // Hodnota kreslen\u00E1 pr\u016Fhledn\u011B (\u010Dern\u00FD okraj skenu, mo\u0159e u st\u00EDnovan\u00E9ho reli\u00E9fu\u2026).\n    if (Number.isFinite(style.nodata)) params.NODATA = String(style.nodata);\n    if (style.mode === 'palette') return params; // paleta souboru = v\u00FDchoz\u00ED chov\u00E1n\u00ED slu\u017Eby\n    const bandCount = (entry.bands || []).length;\n    if (style.mode === 'rgb') {\n        params.BANDS = `${style.bands.r},${style.bands.g},${style.bands.b}`;\n    } else {\n        // Jedno p\u00E1smo; u jednop\u00E1smov\u00E9ho rastru s paletou je BANDS nutn\u00E9, aby\n        // slu\u017Eba paletu nepou\u017Eila.\n        if (bandCount > 1 || entry.raster?.palette?.length) params.BANDS = String(style.band || 1);\n        if (style.mode === 'ramp') params.COLORMAP = style.colormap || 'viridis';\n    }\n    if (style.range) {\n        params.RANGE = `${style.range[0]},${style.range[1]}`;\n    } else if (style.stretch?.type === 'percent') {\n        const [lo, hi] = style.stretch.clip || [2, 98];\n        params.STRETCH = `${lo},${hi}`;\n    } else if (style.stretch?.type === 'minmax') {\n        params.STRETCH = 'minmax';\n    } else if (style.mode === 'rgb') {\n        params.STRETCH = 'none';\n    } else {\n        // Jedno p\u00E1smo bez rozta\u017Een\u00ED ned\u00E1v\u00E1 smysl u dat mimo 0\u2013255 \u2192 min\u2013max.\n        params.STRETCH = 'minmax';\n    }\n    return params;\n}\n\n/** Atributov\u00FD filtr vrstvy stylem z dat (`FILTER`, jeden na ka\u017Edou vrstvu\n * v `LAYERS`, ka\u017Ed\u00FD v z\u00E1vork\u00E1ch), nebo undefined. */\nfunction nativeFilter(entry, sublayerNames) {\n    const fragment = filterToXml(entry.filter);\n    if (!fragment) return undefined;\n    const filter = `(<Filter xmlns=\"http://www.opengis.net/ogc\" xmlns:ogc=\"http://www.opengis.net/ogc\">${fragment}</Filter>)`;\n    return sublayerNames.map(() => filter).join('');\n}\n\n/** Sestav\u00ED WMS parametry (LAYERS, SLD_BODY, FILE_URL, sig, ...) pro danou vrstvu. */\nexport function buildWmsParams(entry) {\n    const sublayerNames = (entry.sublayers || []).map((s) => s.name);\n    const params = {\n        LAYERS: sublayerNames.join(','),\n        TRANSPARENT: 'true',\n        FORMAT: imageFormat(entry),\n        ...signedParams(entry),\n        // Parametry, kter\u00E9 p\u0159edchoz\u00ED styl mohl nastavit, se mus\u00ED um\u011Bt i zru\u0161it\n        // (`updateParams` jinak star\u00E9 hodnoty ponech\u00E1).\n        SLD_BODY: undefined,\n        FILTER: undefined,\n        BANDS: undefined,\n        STRETCH: undefined,\n        RANGE: undefined,\n        COLORMAP: undefined,\n        NODATA: undefined,\n    };\n    if (entry.dataType === 'raster') {\n        Object.assign(params, rasterParams(entry));\n    } else if (usesNativeStyle(entry)) {\n        // Styl z dat kresl\u00ED Mapserver s\u00E1m (\u017E\u00E1dn\u00E9 SLD).\n        params.FILTER = nativeFilter(entry, sublayerNames);\n    } else {\n        params.SLD_BODY = buildSld(entry);\n    }\n    return params;\n}\n", "/**\n * wms.js \u2014 ImageWMS zdroj napojen\u00FD na Lambda mapserver (jeden WMS request na\n * jednu vrstvu workspace, i kdy\u017E m\u00E1 v\u00EDc podvrstev \u2014 LAYERS je jejich seznam).\n *\n * - `ratio: 1.5` \u2192 single-image s ~50% p\u0159esahem (m\u00E9n\u011B \"blik\u00E1n\u00ED\" p\u0159i posunu).\n * - Zm\u011Bny stylu/viditelnosti podvrstev jsou debounced (~300 ms), aby rychl\u00E9\n *   \u00FApravy v panelu symbologie nezahltily server GetMap po\u017Eadavky.\n * - Kdy\u017E je v\u00FDsledn\u00E1 URL p\u0159\u00EDli\u0161 dlouh\u00E1 (SLD_BODY), p\u0159epneme na POST p\u0159es\n *   vlastn\u00ED `imageLoadFunction` (form-encoded t\u011Blo \u2192 blob \u2192 object URL).\n * - Star\u00FD obr\u00E1zek z\u016Fst\u00E1v\u00E1 vykreslen\u00FD, dokud nedoraz\u00ED nov\u00FD (v\u00FDchoz\u00ED chov\u00E1n\u00ED\n *   ol/source/ImageWMS + <img>, \u017E\u00E1dn\u00E9 manu\u00E1ln\u00ED schov\u00E1v\u00E1n\u00ED/blik\u00E1n\u00ED).\n * - Prvn\u00ED obr\u00E1zek vrstvy se na\u010Dte p\u0159es fetch, aby \u0161ly p\u0159e\u010D\u00EDst diagnostick\u00E9\n *   hlavi\u010Dky slu\u017Eby (`X-GCZ-Skipped-Layers`, `X-GCZ-Hybrid-Layers`, viz\n *   hybrid.js) \u2014 `<img>` k hlavi\u010Dk\u00E1m odpov\u011Bdi p\u0159\u00EDstup nem\u00E1. V\u00FDsledek se\n *   ohl\u00E1s\u00ED ud\u00E1lost\u00ED `wms:diagnostics`.\n */\nimport ImageWMS from 'ol/source/ImageWMS.js';\nimport ImageLayer from 'ol/layer/Image.js';\nimport { apiFetch, debounce, emit } from './utils.js';\nimport { buildSld } from './sld.js';\nimport { readDiagnostics } from './hybrid.js';\nimport { setMixedImages } from './image-format.js';\nimport { trackSourceLoading } from './loading.js';\nimport {\n    buildWmsParams, rasterParams, signedParams, usesNativeStyle,\n} from './wms-params.js';\n\n// Parametry vrstvy (bez OpenLayers) jsou v wms-params.js; ostatn\u00ED moduly je\n// berou i odsud.\nexport {\n    buildWmsParams, rasterParams, signedParams, usesNativeStyle,\n};\n\n/** Nad jakou d\u00E9lkou URL p\u0159ep\u00EDn\u00E1me GetMap z GET na POST (rezerva pod ~8000). */\nconst URL_LENGTH_LIMIT = 7500;\n/** Pr\u016Fhledn\u00FD obr\u00E1zek 1\u00D71 px \u2014 vrstva, kter\u00E1 se nekresl\u00ED (`performance.tooSlow`). */\nconst BLANK_IMAGE = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=';\n\n/** Detail polo\u017Eky (/items/<id>/wms/) s kr\u00E1tkou pam\u011Bt\u00ED: soubor s v\u00EDce vrstvami\n * m\u00E1 ve stromu v\u00EDc z\u00E1znam\u016F a p\u0159i obnov\u011B ulo\u017Een\u00E9 mapy by se na tent\u00FD\u017E detail\n * ptal ka\u017Ed\u00FD z nich. Chyba se nepamatuje. */\nconst DETAIL_TTL_MS = 60000;\nconst detailCache = new Map();\n\nexport function fetchItemDetail(bootstrap, itemId, mapId) {\n    const url = wmsDetailUrl(bootstrap, itemId, mapId);\n    const cached = detailCache.get(url);\n    if (cached && Date.now() - cached.at < DETAIL_TTL_MS) return cached.promise;\n    const promise = apiFetch(url);\n    detailCache.set(url, { at: Date.now(), promise });\n    promise.catch(() => detailCache.delete(url));\n    return promise;\n}\n\n/** Zapomene detail polo\u017Eky (zm\u011Bnil se soubor, ze kter\u00E9ho se kresl\u00ED). */\nexport function forgetItemDetail(itemId) {\n    Array.from(detailCache.keys())\n        .filter((url) => url.includes(`/${itemId}/wms/`))\n        .forEach((url) => detailCache.delete(url));\n}\n\n/** URL detailu vrstvy (/items/<id>/wms/). `mapId` ur\u010D\u00ED, kdo za vykreslen\u00ED\n * plat\u00ED (vlastn\u00EDk mapy); bez n\u011Bj plat\u00ED vlastn\u00EDk dat. Data ze sd\u00EDlen\u00E9ho odkazu\n * jdou p\u0159es cestu odkazu (p\u0159\u00EDstup kon\u010D\u00ED s n\u00EDm). */\nexport function wmsDetailUrl(bootstrap, itemId, mapId) {\n    if (bootstrap.sharedView) return `${bootstrap.sharedView.wmsBase}${itemId}/wms/`;\n    const base = `${bootstrap.apiBase}/items/${itemId}/wms/`;\n    return mapId ? `${base}?map=${encodeURIComponent(mapId)}` : base;\n}\n\n/** P\u0159e\u010Dte diagnostick\u00E9 hlavi\u010Dky odpov\u011Bdi GetMap a ohl\u00E1s\u00ED je (jednou na vrstvu). */\nfunction reportDiagnostics(entry, response) {\n    if (!entry || entry.diagnosticsRead) return;\n    entry.diagnosticsRead = true;\n    const diagnostics = readDiagnostics(response.headers);\n    if (diagnostics.skipped.layers.length || diagnostics.skipped.omitted || diagnostics.hybrid.groups.length) {\n        emit('wms:diagnostics', { entry, ...diagnostics });\n    }\n}\n\n/** Vlastn\u00ED imageLoadFunction: GET, nebo POST kdy\u017E je URL p\u0159\u00EDli\u0161 dlouh\u00E1 (SLD_BODY).\n * Prvn\u00ED GET vrstvy jde p\u0159es fetch kv\u016Fli diagnostick\u00FDm hlavi\u010Dk\u00E1m; kdy\u017E fetch\n * sel\u017Ee (s\u00ED\u0165, CORS), obr\u00E1zek se na\u010Dte postaru p\u0159es `<img>`. */\nfunction createImageLoadFunction(entry) {\n    let lastObjectUrl = null;\n    return function imageLoadFunction(imageWrapper, src) {\n        const img = imageWrapper.getImage();\n        const cleanup = () => {\n            if (lastObjectUrl) {\n                URL.revokeObjectURL(lastObjectUrl);\n                lastObjectUrl = null;\n            }\n        };\n        if (entry?.performance?.tooSlow) {\n            // \u010Cten\u00ED souboru by trvalo des\u00EDtky sekund na ka\u017Ed\u00E9 p\u0159ekreslen\u00ED (odhad\n            // backendu): slu\u017Eba se nept\u00E1, vrstva z\u016Fstane pr\u00E1zdn\u00E1 a advisor.js\n            // nab\u00EDdne p\u0159evod do form\u00E1tu pro mapy.\n            cleanup();\n            img.src = BLANK_IMAGE;\n            return;\n        }\n        const isGet = src.length <= URL_LENGTH_LIMIT;\n        if (isGet && (!entry || entry.diagnosticsRead)) {\n            cleanup();\n            img.src = src;\n            return;\n        }\n        let request;\n        if (isGet) {\n            request = fetch(src);\n        } else {\n            const queryIndex = src.indexOf('?');\n            const base = queryIndex === -1 ? src : src.slice(0, queryIndex);\n            const body = queryIndex === -1 ? '' : src.slice(queryIndex + 1);\n            request = fetch(base, {\n                method: 'POST',\n                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n                body,\n            });\n        }\n        request\n            .then((response) => {\n                if (!response.ok) throw new Error(`GetMap failed: ${response.status}`);\n                reportDiagnostics(entry, response);\n                return response.blob();\n            })\n            .then((blob) => {\n                cleanup();\n                lastObjectUrl = URL.createObjectURL(blob);\n                img.src = lastObjectUrl;\n            })\n            .catch(() => {\n                if (isGet) {\n                    // Diagnostika se nepovedla \u2014 dal\u0161\u00ED obr\u00E1zky u\u017E jen p\u0159es `<img>`.\n                    if (entry) entry.diagnosticsRead = true;\n                    cleanup();\n                    img.src = src;\n                    return;\n                }\n                // POST: chyba p\u0159i vykreslen\u00ED vrstvy \u2014 posledn\u00ED platn\u00FD obr\u00E1zek\n                // na map\u011B z\u016Fst\u00E1v\u00E1 (mapa \"neproblikne\" do pr\u00E1zdna). Obr\u00E1zku ale\n                // mus\u00EDme ozn\u00E1mit konec na\u010D\u00EDt\u00E1n\u00ED, jinak by OpenLayers \u010Dekal\n                // donekone\u010Dna (a s n\u00EDm i indikace vykreslov\u00E1n\u00ED, loading.js).\n                img.dispatchEvent(new Event('error'));\n            });\n    };\n}\n\n/** Vytvo\u0159\u00ED ImageWMS zdroj + Image vrstvu pro danou b\u011Bhovou polo\u017Eku vrstvy. */\nexport function createWmsLayer(entry, bootstrap) {\n    setMixedImages(bootstrap.mixedImages);\n    const source = new ImageWMS({\n        url: bootstrap.mapserverUrl,\n        params: buildWmsParams(entry),\n        ratio: 1.5,\n        imageLoadFunction: createImageLoadFunction(entry),\n        crossOrigin: 'anonymous',\n    });\n    const layer = new ImageLayer({\n        source,\n        visible: entry.visible,\n        opacity: entry.opacity,\n        properties: { itemId: entry.itemId },\n    });\n    entry.olSource = source;\n    entry.olLayer = layer;\n    trackSourceLoading(entry, source, 'image');\n    return layer;\n}\n\n/** Debounced \u201Ep\u0159egenerovat SLD/parametry a poslat nov\u00FD GetMap\" \u2014 kl\u00ED\u010Dov\u00E1no podle\n * uid (unik\u00E1tn\u00ED i pro duplik\u00E1ty t\u00E9\u017Ee polo\u017Eky), aby rychl\u00E9 po sob\u011B jdouc\u00ED zm\u011Bny\n * (nap\u0159. ta\u017Een\u00ED slideru) spustily jen jeden request po ~300 ms klidu. */\nconst debouncedRefreshers = new Map();\n\nexport function scheduleWmsRefresh(entry, delay = 300) {\n    const key = entry.uid || entry.itemId;\n    let refresh = debouncedRefreshers.get(key);\n    if (!refresh) {\n        refresh = debounce(() => {\n            if (entry.olSource) {\n                entry.olSource.updateParams(buildWmsParams(entry));\n            }\n        }, delay);\n        debouncedRefreshers.set(key, refresh);\n    }\n    refresh();\n}\n\n/** Sestav\u00ED URL pro GetLegendGraphic dan\u00E9 podvrstvy (stejn\u00E1 slu\u017Eba jako GetMap). */\nexport function buildLegendUrl(entry, sublayerName, bootstrap) {\n    const params = new URLSearchParams({\n        SERVICE: 'WMS',\n        VERSION: '1.1.1',\n        REQUEST: 'GetLegendGraphic',\n        FORMAT: 'image/png',\n        LAYER: sublayerName,\n        ...signedParams(entry),\n    });\n    if (entry.dataType !== 'raster' && !usesNativeStyle(entry)) {\n        params.set('SLD_BODY', buildSld(entry));\n    }\n    return `${bootstrap.mapserverUrl}?${params.toString()}`;\n}\n\n/** Refreshne podpis (FILE_URL/sig/PAYER), pokud se bl\u00ED\u017E\u00ED expirace `expires_at`.\n * Vol\u00E1no periodicky z main.js pro ka\u017Edou vrstvu na map\u011B. Kdy\u017E pl\u00E1tce nem\u00E1\n * kredity, server vr\u00E1t\u00ED 402 (token se neobnov\u00ED) \u2014 viz `apiFetch`. */\nexport async function refreshSignatureIfNeeded(entry, bootstrap, marginSeconds = 60, mapId = null) {\n    const { expiresAt } = entry.wms;\n    if (!expiresAt) return false;\n    const now = Math.floor(Date.now() / 1000);\n    if (expiresAt - now > marginSeconds) return false;\n    // Sd\u00EDlen\u00E1 pam\u011B\u0165 detailu: vrstvy t\u00E9ho\u017E souboru se ptaj\u00ED jedn\u00EDm dotazem.\n    const detail = await fetchItemDetail(bootstrap, entry.itemId, mapId);\n    entry.wms.fileUrl = detail.params?.FILE_URL;\n    entry.wms.sig = detail.params?.sig;\n    entry.wms.payer = detail.params?.PAYER || '';\n    entry.wms.fileCrs = detail.params?.FILE_CRS || '';\n    entry.wms.expiresAt = detail.expires_at || 0;\n    if (entry.olSource) {\n        entry.olSource.updateParams(buildWmsParams(entry));\n    }\n    return true;\n}\n", "/**\n * @module ol/Feature\n */\nimport BaseObject from './Object.js';\nimport {assert} from './asserts.js';\nimport {listen, unlistenByKey} from './events.js';\nimport EventType from './events/EventType.js';\n\n/**\n * @typedef {typeof Feature|typeof import(\"./render/Feature.js\").default} FeatureClass\n */\n\n/**\n * @typedef {Feature|import(\"./render/Feature.js\").default} FeatureLike\n */\n\n/***\n * @template Return\n * @typedef {import(\"./Observable.js\").OnSignature<import(\"./Observable.js\").EventTypes, import(\"./events/Event.js\").default, Return> &\n *   import(\"./Observable.js\").OnSignature<import(\"./ObjectEventType.js\").Types|'change:geometry', import(\"./Object.js\").ObjectEvent, Return> &\n *   import(\"./Observable.js\").CombinedOnSignature<import(\"./Observable.js\").EventTypes|import(\"./ObjectEventType.js\").Types\n *     |'change:geometry', Return>} FeatureOnSignature\n */\n\n/***\n * @template {import(\"./geom/Geometry.js\").default} [Geometry=import(\"./geom/Geometry.js\").default]\n * @template {Object<string, *>} [Properties=Object<string, *>]\n * @typedef {Properties & { geometry?: Geometry }} ObjectWithGeometry\n */\n\n/**\n * @classdesc\n * A vector object for geographic features with a geometry and other\n * attribute properties, similar to the features in vector file formats like\n * GeoJSON.\n *\n * Features can be styled individually with `setStyle`; otherwise they use the\n * style of their vector layer.\n *\n * Note that attribute properties are set as {@link module:ol/Object~BaseObject} properties on\n * the feature object, so they are observable, and have get/set accessors.\n *\n * Typically, a feature has a single geometry property. You can set the\n * geometry using the `setGeometry` method and get it with `getGeometry`.\n * It is possible to store more than one geometry on a feature using attribute\n * properties. By default, the geometry used for rendering is identified by\n * the property name `geometry`. If you want to use another geometry property\n * for rendering, use the `setGeometryName` method to change the attribute\n * property associated with the geometry for the feature.  For example:\n *\n * ```js\n *\n * import Feature from 'ol/Feature.js';\n * import Polygon from 'ol/geom/Polygon.js';\n * import Point from 'ol/geom/Point.js';\n *\n * const feature = new Feature({\n *   geometry: new Polygon(polyCoords),\n *   labelPoint: new Point(labelCoords),\n *   name: 'My Polygon',\n * });\n *\n * // get the polygon geometry\n * const poly = feature.getGeometry();\n *\n * // Render the feature as a point using the coordinates from labelPoint\n * feature.setGeometryName('labelPoint');\n *\n * // get the point geometry\n * const point = feature.getGeometry();\n * ```\n *\n * @api\n * @template {import(\"./geom/Geometry.js\").default} [Geometry=import(\"./geom/Geometry.js\").default]\n * @template {Object<string, *>} [Properties=Object<string, *>]\n * @extends {BaseObject<NoInfer<Properties>>}\n */\nclass Feature extends BaseObject {\n  /**\n   * @param {Geometry|ObjectWithGeometry<Geometry, NoInfer<Properties>>} [geometryOrProperties]\n   *     You may pass a Geometry object directly, or an object literal containing\n   *     properties. If you pass an object literal, you may include a Geometry\n   *     associated with a `geometry` key.\n   */\n  constructor(geometryOrProperties) {\n    super();\n\n    /***\n     * @type {FeatureOnSignature<import(\"./events.js\").EventsKey>}\n     */\n    this.on;\n\n    /***\n     * @type {FeatureOnSignature<import(\"./events.js\").EventsKey>}\n     */\n    this.once;\n\n    /***\n     * @type {FeatureOnSignature<void>}\n     */\n    this.un;\n\n    /**\n     * @private\n     * @type {number|string|undefined}\n     */\n    this.id_ = undefined;\n\n    /**\n     * @type {string}\n     * @private\n     */\n    this.geometryName_ = 'geometry';\n\n    /**\n     * User provided style.\n     * @private\n     * @type {import(\"./style/Style.js\").StyleLike}\n     */\n    this.style_ = null;\n\n    /**\n     * @private\n     * @type {import(\"./style/Style.js\").StyleFunction|undefined}\n     */\n    this.styleFunction_ = undefined;\n\n    /**\n     * @private\n     * @type {?import(\"./events.js\").EventsKey}\n     */\n    this.geometryChangeKey_ = null;\n\n    this.addChangeListener(this.geometryName_, this.handleGeometryChanged_);\n\n    if (geometryOrProperties) {\n      if (\n        typeof (\n          /** @type {?} */ (geometryOrProperties).getSimplifiedGeometry\n        ) === 'function'\n      ) {\n        const geometry = /** @type {Geometry} */ (geometryOrProperties);\n        this.setGeometry(geometry);\n      } else {\n        /** @type {?} */\n        const properties = geometryOrProperties;\n        this.setProperties(properties);\n      }\n    }\n  }\n\n  /**\n   * Clone this feature. If the original feature has a geometry it\n   * is also cloned. The feature id is not set in the clone.\n   * @return {Feature<Geometry>} The clone.\n   * @api\n   */\n  clone() {\n    const clone = /** @type {Feature<Geometry>} */ (new Feature());\n    const geometryName = this.geometryName_;\n    clone.setGeometryName(geometryName);\n\n    const properties = this.getPropertiesInternal();\n    if (properties) {\n      const geometry = this.getGeometry();\n      for (const key in properties) {\n        if (key === geometryName && geometry) {\n          clone.set(key, geometry.clone());\n        } else {\n          clone.set(key, properties[key], true);\n        }\n      }\n    }\n\n    const style = this.getStyle();\n    if (style) {\n      clone.setStyle(style);\n    }\n    return clone;\n  }\n\n  /**\n   * Get the feature's default geometry.  A feature may have any number of named\n   * geometries.  The \"default\" geometry (the one that is rendered by default) is\n   * set when calling {@link module:ol/Feature~Feature#setGeometry}.\n   * @return {Geometry|undefined} The default geometry for the feature.\n   * @api\n   * @observable\n   */\n  getGeometry() {\n    return /** @type {Geometry|undefined} */ (this.get(this.geometryName_));\n  }\n\n  /**\n   * Get the feature identifier.  This is a stable identifier for the feature and\n   * is either set when reading data from a remote source or set explicitly by\n   * calling {@link module:ol/Feature~Feature#setId}.\n   * @return {number|string|undefined} Id.\n   * @api\n   */\n  getId() {\n    return this.id_;\n  }\n\n  /**\n   * Get the name of the feature's default geometry.  By default, the default\n   * geometry is named `geometry`.\n   * @return {string} Get the property name associated with the default geometry\n   *     for this feature.\n   * @api\n   */\n  getGeometryName() {\n    return this.geometryName_;\n  }\n\n  /**\n   * Get the feature's style. Will return what was provided to the\n   * {@link module:ol/Feature~Feature#setStyle} method.\n   * @return {import(\"./style/Style.js\").StyleLike|undefined} The feature style.\n   * @api\n   */\n  getStyle() {\n    return this.style_;\n  }\n\n  /**\n   * Get the feature's style function.\n   * @return {import(\"./style/Style.js\").StyleFunction|undefined} Return a function\n   * representing the current style of this feature.\n   * @api\n   */\n  getStyleFunction() {\n    return this.styleFunction_;\n  }\n\n  /**\n   * @private\n   */\n  handleGeometryChange_() {\n    this.changed();\n  }\n\n  /**\n   * @private\n   */\n  handleGeometryChanged_() {\n    if (this.geometryChangeKey_) {\n      unlistenByKey(this.geometryChangeKey_);\n      this.geometryChangeKey_ = null;\n    }\n    const geometry = this.getGeometry();\n    if (geometry) {\n      this.geometryChangeKey_ = listen(\n        geometry,\n        EventType.CHANGE,\n        this.handleGeometryChange_,\n        this,\n      );\n    }\n    this.changed();\n  }\n\n  /**\n   * Set the default geometry for the feature.  This will update the property\n   * with the name returned by {@link module:ol/Feature~Feature#getGeometryName}.\n   * @param {Geometry|undefined} geometry The new geometry.\n   * @api\n   * @observable\n   */\n  setGeometry(geometry) {\n    this.set(this.geometryName_, geometry);\n  }\n\n  /**\n   * Set the style for the feature to override the layer style.  This can be a\n   * single style object, an array of styles, or a function that takes a\n   * resolution and returns an array of styles. To unset the feature style, call\n   * `setStyle()` without arguments or a falsey value.\n   * @param {import(\"./style/Style.js\").StyleLike} [style] Style for this feature.\n   * @api\n   * @fires module:ol/events/Event~BaseEvent#event:change\n   */\n  setStyle(style) {\n    this.style_ = style;\n    this.styleFunction_ = !style ? undefined : createStyleFunction(style);\n    this.changed();\n  }\n\n  /**\n   * Set the feature id.  The feature id is considered stable and may be used when\n   * requesting features or comparing identifiers returned from a remote source.\n   * The feature id can be used with the\n   * {@link module:ol/source/Vector~VectorSource#getFeatureById} method.\n   * @param {number|string|undefined} id The feature id.\n   * @api\n   * @fires module:ol/events/Event~BaseEvent#event:change\n   */\n  setId(id) {\n    this.id_ = id;\n    this.changed();\n  }\n\n  /**\n   * Set the property name to be used when getting the feature's default geometry.\n   * When calling {@link module:ol/Feature~Feature#getGeometry}, the value of the property with\n   * this name will be returned.\n   * @param {string} name The property name of the default geometry.\n   * @api\n   */\n  setGeometryName(name) {\n    if (name === this.geometryName_) {\n      return;\n    }\n    this.removeChangeListener(this.geometryName_, this.handleGeometryChanged_);\n    this.geometryName_ = name;\n    this.addChangeListener(this.geometryName_, this.handleGeometryChanged_);\n    this.handleGeometryChanged_();\n  }\n}\n\n/**\n * Convert the provided object into a feature style function.  Functions passed\n * through unchanged.  Arrays of Style or single style objects wrapped\n * in a new feature style function.\n * @param {!import(\"./style/Style.js\").StyleFunction|!Array<import(\"./style/Style.js\").default>|!import(\"./style/Style.js\").default} obj\n *     A feature style function, a single style, or an array of styles.\n * @return {import(\"./style/Style.js\").StyleFunction} A style function.\n */\nexport function createStyleFunction(obj) {\n  if (typeof obj === 'function') {\n    return obj;\n  }\n  /**\n   * @type {Array<import(\"./style/Style.js\").default>}\n   */\n  let styles;\n  if (Array.isArray(obj)) {\n    styles = obj;\n  } else {\n    assert(\n      typeof (/** @type {?} */ (obj).getZIndex) === 'function',\n      'Expected an `ol/style/Style` or an array of `ol/style/Style.js`',\n    );\n    const style = /** @type {import(\"./style/Style.js\").default} */ (obj);\n    styles = [style];\n  }\n  return function () {\n    return styles;\n  };\n}\nexport default Feature;\n", "/**\n * @module ol/geom/Circle\n */\nimport {createOrUpdate, forEachCorner, intersects} from '../extent.js';\nimport SimpleGeometry from './SimpleGeometry.js';\nimport {deflateCoordinate} from './flat/deflate.js';\nimport {rotate} from './flat/transform.js';\n\n/**\n * @classdesc\n * Circle geometry.\n *\n * @api\n */\nclass Circle extends SimpleGeometry {\n  /**\n   * @param {!import(\"../coordinate.js\").Coordinate} center Center.\n   *     For internal use, flat coordinates in combination with `layout` and no\n   *     `radius` are also accepted.\n   * @param {number} [radius] Radius in units of the projection.\n   * @param {import(\"./Geometry.js\").GeometryLayout} [layout] Layout.\n   */\n  constructor(center, radius, layout) {\n    super();\n    if (layout !== undefined && radius === undefined) {\n      this.setFlatCoordinates(layout, center);\n    } else {\n      radius = radius ? radius : 0;\n      this.setCenterAndRadius(center, radius, layout);\n    }\n  }\n\n  /**\n   * Make a complete copy of the geometry.\n   * @return {!Circle} Clone.\n   * @api\n   * @override\n   */\n  clone() {\n    const circle = new Circle(\n      this.flatCoordinates.slice(),\n      undefined,\n      this.layout,\n    );\n    circle.applyProperties(this);\n    return circle;\n  }\n\n  /**\n   * @param {number} x X.\n   * @param {number} y Y.\n   * @param {import(\"../coordinate.js\").Coordinate} closestPoint Closest point.\n   * @param {number} minSquaredDistance Minimum squared distance.\n   * @return {number} Minimum squared distance.\n   * @override\n   */\n  closestPointXY(x, y, closestPoint, minSquaredDistance) {\n    const flatCoordinates = this.flatCoordinates;\n    const dx = x - flatCoordinates[0];\n    const dy = y - flatCoordinates[1];\n    const squaredDistance = dx * dx + dy * dy;\n    if (squaredDistance < minSquaredDistance) {\n      if (squaredDistance === 0) {\n        for (let i = 0; i < this.stride; ++i) {\n          closestPoint[i] = flatCoordinates[i];\n        }\n      } else {\n        const delta = this.getRadius() / Math.sqrt(squaredDistance);\n        closestPoint[0] = flatCoordinates[0] + delta * dx;\n        closestPoint[1] = flatCoordinates[1] + delta * dy;\n        for (let i = 2; i < this.stride; ++i) {\n          closestPoint[i] = flatCoordinates[i];\n        }\n      }\n      closestPoint.length = this.stride;\n      return squaredDistance;\n    }\n    return minSquaredDistance;\n  }\n\n  /**\n   * @param {number} x X.\n   * @param {number} y Y.\n   * @return {boolean} Contains (x, y).\n   * @override\n   */\n  containsXY(x, y) {\n    const flatCoordinates = this.flatCoordinates;\n    const dx = x - flatCoordinates[0];\n    const dy = y - flatCoordinates[1];\n    return dx * dx + dy * dy <= this.getRadiusSquared_();\n  }\n\n  /**\n   * Return the center of the circle as {@link module:ol/coordinate~Coordinate coordinate}.\n   * @return {import(\"../coordinate.js\").Coordinate} Center.\n   * @api\n   */\n  getCenter() {\n    return this.flatCoordinates.slice(0, this.stride);\n  }\n\n  /**\n   * @param {import(\"../extent.js\").Extent} extent Extent.\n   * @protected\n   * @return {import(\"../extent.js\").Extent} extent Extent.\n   * @override\n   */\n  computeExtent(extent) {\n    const flatCoordinates = this.flatCoordinates;\n    const radius = flatCoordinates[this.stride] - flatCoordinates[0];\n    return createOrUpdate(\n      flatCoordinates[0] - radius,\n      flatCoordinates[1] - radius,\n      flatCoordinates[0] + radius,\n      flatCoordinates[1] + radius,\n      extent,\n    );\n  }\n\n  /**\n   * Return the radius of the circle.\n   * @return {number} Radius.\n   * @api\n   */\n  getRadius() {\n    return Math.sqrt(this.getRadiusSquared_());\n  }\n\n  /**\n   * @private\n   * @return {number} Radius squared.\n   */\n  getRadiusSquared_() {\n    const dx = this.flatCoordinates[this.stride] - this.flatCoordinates[0];\n    const dy = this.flatCoordinates[this.stride + 1] - this.flatCoordinates[1];\n    return dx * dx + dy * dy;\n  }\n\n  /**\n   * Get the type of this geometry.\n   * @return {import(\"./Geometry.js\").Type} Geometry type.\n   * @api\n   * @override\n   */\n  getType() {\n    return 'Circle';\n  }\n\n  /**\n   * Test if the geometry and the passed extent intersect.\n   * @param {import(\"../extent.js\").Extent} extent Extent.\n   * @return {boolean} `true` if the geometry and the extent intersect.\n   * @api\n   * @override\n   */\n  intersectsExtent(extent) {\n    const circleExtent = this.getExtent();\n    if (intersects(extent, circleExtent)) {\n      const center = this.getCenter();\n\n      if (extent[0] <= center[0] && extent[2] >= center[0]) {\n        return true;\n      }\n      if (extent[1] <= center[1] && extent[3] >= center[1]) {\n        return true;\n      }\n\n      return forEachCorner(extent, this.intersectsCoordinate.bind(this));\n    }\n    return false;\n  }\n\n  /**\n   * Set the center of the circle as {@link module:ol/coordinate~Coordinate coordinate}.\n   * @param {import(\"../coordinate.js\").Coordinate} center Center.\n   * @api\n   */\n  setCenter(center) {\n    const stride = this.stride;\n    const radius = this.flatCoordinates[stride] - this.flatCoordinates[0];\n    const flatCoordinates = center.slice();\n    flatCoordinates[stride] = flatCoordinates[0] + radius;\n    for (let i = 1; i < stride; ++i) {\n      flatCoordinates[stride + i] = center[i];\n    }\n    this.setFlatCoordinates(this.layout, flatCoordinates);\n    this.changed();\n  }\n\n  /**\n   * Set the center (as {@link module:ol/coordinate~Coordinate coordinate}) and the radius (as\n   * number) of the circle.\n   * @param {!import(\"../coordinate.js\").Coordinate} center Center.\n   * @param {number} radius Radius.\n   * @param {import(\"./Geometry.js\").GeometryLayout} [layout] Layout.\n   * @api\n   */\n  setCenterAndRadius(center, radius, layout) {\n    this.setLayout(layout, center, 0);\n    if (!this.flatCoordinates) {\n      this.flatCoordinates = [];\n    }\n    /** @type {Array<number>} */\n    const flatCoordinates = this.flatCoordinates;\n    let offset = deflateCoordinate(flatCoordinates, 0, center, this.stride);\n    flatCoordinates[offset++] = flatCoordinates[0] + radius;\n    for (let i = 1, ii = this.stride; i < ii; ++i) {\n      flatCoordinates[offset++] = flatCoordinates[i];\n    }\n    flatCoordinates.length = offset;\n    this.changed();\n  }\n\n  /**\n   * @override\n   */\n  getCoordinates() {\n    return null;\n  }\n\n  /**\n   * @override\n   */\n  setCoordinates(coordinates, layout) {}\n\n  /**\n   * Set the radius of the circle. The radius is in the units of the projection.\n   * @param {number} radius Radius.\n   * @api\n   */\n  setRadius(radius) {\n    this.flatCoordinates[this.stride] = this.flatCoordinates[0] + radius;\n    this.changed();\n  }\n\n  /**\n   * Rotate the geometry around a given coordinate. This modifies the geometry\n   * coordinates in place.\n   * @param {number} angle Rotation angle in counter-clockwise radians.\n   * @param {import(\"../coordinate.js\").Coordinate} anchor The rotation center.\n   * @api\n   * @override\n   */\n  rotate(angle, anchor) {\n    const center = this.getCenter();\n    const stride = this.getStride();\n    this.setCenter(\n      rotate(center, 0, center.length, stride, angle, anchor, center),\n    );\n    this.changed();\n  }\n}\n\n/**\n * Transform each coordinate of the circle from one coordinate reference system\n * to another. The geometry is modified in place.\n * If you do not want the geometry modified in place, first clone() it and\n * then use this function on the clone.\n *\n * Internally a circle is currently represented by two points: the center of\n * the circle `[cx, cy]`, and the point to the right of the circle\n * `[cx + r, cy]`. This `transform` function just transforms these two points.\n * So the resulting geometry is also a circle, and that circle does not\n * correspond to the shape that would be obtained by transforming every point\n * of the original circle.\n *\n * @param {import(\"../proj.js\").ProjectionLike} source The current projection.  Can be a\n *     string identifier or a {@link module:ol/proj/Projection~Projection} object.\n * @param {import(\"../proj.js\").ProjectionLike} destination The desired projection.  Can be a\n *     string identifier or a {@link module:ol/proj/Projection~Projection} object.\n * @return {Circle} This geometry.  Note that original geometry is\n *     modified in place.\n * @function\n * @api\n */\nCircle.prototype.transform;\nexport default Circle;\n", "/**\n * @module ol/geom/flat/interpolate\n */\nimport {binarySearch} from '../../array.js';\nimport {lerp} from '../../math.js';\n\n/**\n * @param {Array<number>} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {number} end End.\n * @param {number} stride Stride.\n * @param {number} fraction Fraction.\n * @param {Array<number>} [dest] Destination.\n * @param {number} [dimension] Destination dimension (default is `2`)\n * @return {Array<number>} Destination.\n */\nexport function interpolatePoint(\n  flatCoordinates,\n  offset,\n  end,\n  stride,\n  fraction,\n  dest,\n  dimension,\n) {\n  let o, t;\n  const n = (end - offset) / stride;\n  if (n === 1) {\n    o = offset;\n  } else if (n === 2) {\n    o = offset;\n    t = fraction;\n  } else if (n !== 0) {\n    let x1 = flatCoordinates[offset];\n    let y1 = flatCoordinates[offset + 1];\n    let length = 0;\n    const cumulativeLengths = [0];\n    for (let i = offset + stride; i < end; i += stride) {\n      const x2 = flatCoordinates[i];\n      const y2 = flatCoordinates[i + 1];\n      length += Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));\n      cumulativeLengths.push(length);\n      x1 = x2;\n      y1 = y2;\n    }\n    const target = fraction * length;\n    const index = binarySearch(cumulativeLengths, target);\n    if (index < 0) {\n      t =\n        (target - cumulativeLengths[-index - 2]) /\n        (cumulativeLengths[-index - 1] - cumulativeLengths[-index - 2]);\n      o = offset + (-index - 2) * stride;\n    } else {\n      o = offset + index * stride;\n    }\n  }\n  dimension = dimension > 1 ? dimension : 2;\n  dest = dest ? dest : new Array(dimension);\n  for (let i = 0; i < dimension; ++i) {\n    dest[i] =\n      o === undefined\n        ? NaN\n        : t === undefined\n          ? flatCoordinates[o + i]\n          : lerp(flatCoordinates[o + i], flatCoordinates[o + stride + i], t);\n  }\n  return dest;\n}\n\n/**\n * @param {Array<number>} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {number} end End.\n * @param {number} stride Stride.\n * @param {number} m M.\n * @param {boolean} extrapolate Extrapolate.\n * @return {import(\"../../coordinate.js\").Coordinate|null} Coordinate.\n */\nexport function lineStringCoordinateAtM(\n  flatCoordinates,\n  offset,\n  end,\n  stride,\n  m,\n  extrapolate,\n) {\n  if (end == offset) {\n    return null;\n  }\n  let coordinate;\n  if (m < flatCoordinates[offset + stride - 1]) {\n    if (extrapolate) {\n      coordinate = flatCoordinates.slice(offset, offset + stride);\n      coordinate[stride - 1] = m;\n      return coordinate;\n    }\n    return null;\n  }\n  if (flatCoordinates[end - 1] < m) {\n    if (extrapolate) {\n      coordinate = flatCoordinates.slice(end - stride, end);\n      coordinate[stride - 1] = m;\n      return coordinate;\n    }\n    return null;\n  }\n  // FIXME use O(1) search\n  if (m == flatCoordinates[offset + stride - 1]) {\n    return flatCoordinates.slice(offset, offset + stride);\n  }\n  let lo = offset / stride;\n  let hi = end / stride;\n  while (lo < hi) {\n    const mid = (lo + hi) >> 1;\n    if (m < flatCoordinates[(mid + 1) * stride - 1]) {\n      hi = mid;\n    } else {\n      lo = mid + 1;\n    }\n  }\n  const m0 = flatCoordinates[lo * stride - 1];\n  if (m == m0) {\n    return flatCoordinates.slice((lo - 1) * stride, (lo - 1) * stride + stride);\n  }\n  const m1 = flatCoordinates[(lo + 1) * stride - 1];\n  const t = (m - m0) / (m1 - m0);\n  coordinate = [];\n  for (let i = 0; i < stride - 1; ++i) {\n    coordinate.push(\n      lerp(\n        flatCoordinates[(lo - 1) * stride + i],\n        flatCoordinates[lo * stride + i],\n        t,\n      ),\n    );\n  }\n  coordinate.push(m);\n  return coordinate;\n}\n\n/**\n * @param {Array<number>} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {Array<number>} ends Ends.\n * @param {number} stride Stride.\n * @param {number} m M.\n * @param {boolean} extrapolate Extrapolate.\n * @param {boolean} interpolate Interpolate.\n * @return {import(\"../../coordinate.js\").Coordinate|null} Coordinate.\n */\nexport function lineStringsCoordinateAtM(\n  flatCoordinates,\n  offset,\n  ends,\n  stride,\n  m,\n  extrapolate,\n  interpolate,\n) {\n  if (interpolate) {\n    return lineStringCoordinateAtM(\n      flatCoordinates,\n      offset,\n      ends[ends.length - 1],\n      stride,\n      m,\n      extrapolate,\n    );\n  }\n  let coordinate;\n  if (m < flatCoordinates[stride - 1]) {\n    if (extrapolate) {\n      coordinate = flatCoordinates.slice(0, stride);\n      coordinate[stride - 1] = m;\n      return coordinate;\n    }\n    return null;\n  }\n  if (flatCoordinates[flatCoordinates.length - 1] < m) {\n    if (extrapolate) {\n      coordinate = flatCoordinates.slice(flatCoordinates.length - stride);\n      coordinate[stride - 1] = m;\n      return coordinate;\n    }\n    return null;\n  }\n  for (let i = 0, ii = ends.length; i < ii; ++i) {\n    const end = ends[i];\n    if (offset == end) {\n      continue;\n    }\n    if (m < flatCoordinates[offset + stride - 1]) {\n      return null;\n    }\n    if (m <= flatCoordinates[end - 1]) {\n      return lineStringCoordinateAtM(\n        flatCoordinates,\n        offset,\n        end,\n        stride,\n        m,\n        false,\n      );\n    }\n    offset = end;\n  }\n  return null;\n}\n", "/**\n * @module ol/geom/flat/length\n */\n\n/**\n * @param {Array<number>} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {number} end End.\n * @param {number} stride Stride.\n * @return {number} Length.\n */\nexport function lineStringLength(flatCoordinates, offset, end, stride) {\n  let x1 = flatCoordinates[offset];\n  let y1 = flatCoordinates[offset + 1];\n  let length = 0;\n  for (let i = offset + stride; i < end; i += stride) {\n    const x2 = flatCoordinates[i];\n    const y2 = flatCoordinates[i + 1];\n    length += Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));\n    x1 = x2;\n    y1 = y2;\n  }\n  return length;\n}\n\n/**\n * @param {Array<number>} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {number} end End.\n * @param {number} stride Stride.\n * @return {number} Perimeter.\n */\nexport function linearRingLength(flatCoordinates, offset, end, stride) {\n  let perimeter = lineStringLength(flatCoordinates, offset, end, stride);\n  const dx = flatCoordinates[end - stride] - flatCoordinates[offset];\n  const dy = flatCoordinates[end - stride + 1] - flatCoordinates[offset + 1];\n  perimeter += Math.sqrt(dx * dx + dy * dy);\n  return perimeter;\n}\n", "/**\n * @module ol/geom/LineString\n */\nimport {extend} from '../array.js';\nimport {closestSquaredDistanceXY} from '../extent.js';\nimport SimpleGeometry from './SimpleGeometry.js';\nimport {assignClosestPoint, maxSquaredDelta} from './flat/closest.js';\nimport {deflateCoordinates} from './flat/deflate.js';\nimport {inflateCoordinates} from './flat/inflate.js';\nimport {interpolatePoint, lineStringCoordinateAtM} from './flat/interpolate.js';\nimport {intersectsLineString} from './flat/intersectsextent.js';\nimport {lineStringLength} from './flat/length.js';\nimport {forEach as forEachSegment} from './flat/segments.js';\nimport {douglasPeucker} from './flat/simplify.js';\n\n/**\n * @classdesc\n * Linestring geometry.\n *\n * @api\n */\nclass LineString extends SimpleGeometry {\n  /**\n   * @param {Array<import(\"../coordinate.js\").Coordinate>|Array<number>} coordinates Coordinates.\n   *     For internal use, flat coordinates in combination with `layout` are also accepted.\n   * @param {import(\"./Geometry.js\").GeometryLayout} [layout] Layout.\n   */\n  constructor(coordinates, layout) {\n    super();\n\n    /**\n     * @private\n     * @type {import(\"../coordinate.js\").Coordinate|null}\n     */\n    this.flatMidpoint_ = null;\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.flatMidpointRevision_ = -1;\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.maxDelta_ = -1;\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.maxDeltaRevision_ = -1;\n\n    if (layout !== undefined && !Array.isArray(coordinates[0])) {\n      this.setFlatCoordinates(\n        layout,\n        /** @type {Array<number>} */ (coordinates),\n      );\n    } else {\n      this.setCoordinates(\n        /** @type {Array<import(\"../coordinate.js\").Coordinate>} */ (\n          coordinates\n        ),\n        layout,\n      );\n    }\n  }\n\n  /**\n   * Append the passed coordinate to the coordinates of the linestring.\n   * @param {import(\"../coordinate.js\").Coordinate} coordinate Coordinate.\n   * @api\n   */\n  appendCoordinate(coordinate) {\n    extend(this.flatCoordinates, coordinate);\n    this.changed();\n  }\n\n  /**\n   * Make a complete copy of the geometry.\n   * @return {!LineString} Clone.\n   * @api\n   * @override\n   */\n  clone() {\n    const lineString = new LineString(\n      this.flatCoordinates.slice(),\n      this.layout,\n    );\n    lineString.applyProperties(this);\n    return lineString;\n  }\n\n  /**\n   * @param {number} x X.\n   * @param {number} y Y.\n   * @param {import(\"../coordinate.js\").Coordinate} closestPoint Closest point.\n   * @param {number} minSquaredDistance Minimum squared distance.\n   * @return {number} Minimum squared distance.\n   * @override\n   */\n  closestPointXY(x, y, closestPoint, minSquaredDistance) {\n    if (minSquaredDistance < closestSquaredDistanceXY(this.getExtent(), x, y)) {\n      return minSquaredDistance;\n    }\n    if (this.maxDeltaRevision_ != this.getRevision()) {\n      this.maxDelta_ = Math.sqrt(\n        maxSquaredDelta(\n          this.flatCoordinates,\n          0,\n          this.flatCoordinates.length,\n          this.stride,\n          0,\n        ),\n      );\n      this.maxDeltaRevision_ = this.getRevision();\n    }\n    return assignClosestPoint(\n      this.flatCoordinates,\n      0,\n      this.flatCoordinates.length,\n      this.stride,\n      this.maxDelta_,\n      false,\n      x,\n      y,\n      closestPoint,\n      minSquaredDistance,\n    );\n  }\n\n  /**\n   * Iterate over each segment, calling the provided callback.\n   * If the callback returns a truthy value the function returns that\n   * value immediately. Otherwise the function returns `false`.\n   *\n   * @param {function(this: S, import(\"../coordinate.js\").Coordinate, import(\"../coordinate.js\").Coordinate): T} callback Function\n   *     called for each segment. The function will receive two arguments, the start and end coordinates of the segment.\n   * @return {T|boolean} Value.\n   * @template T,S\n   * @api\n   */\n  forEachSegment(callback) {\n    return forEachSegment(\n      this.flatCoordinates,\n      0,\n      this.flatCoordinates.length,\n      this.stride,\n      callback,\n    );\n  }\n\n  /**\n   * Returns the coordinate at `m` using linear interpolation, or `null` if no\n   * such coordinate exists.\n   *\n   * `extrapolate` controls extrapolation beyond the range of Ms in the\n   * MultiLineString. If `extrapolate` is `true` then Ms less than the first\n   * M will return the first coordinate and Ms greater than the last M will\n   * return the last coordinate.\n   *\n   * @param {number} m M.\n   * @param {boolean} [extrapolate] Extrapolate. Default is `false`.\n   * @return {import(\"../coordinate.js\").Coordinate|null} Coordinate.\n   * @api\n   */\n  getCoordinateAtM(m, extrapolate) {\n    if (this.layout != 'XYM' && this.layout != 'XYZM') {\n      return null;\n    }\n    extrapolate = extrapolate !== undefined ? extrapolate : false;\n    return lineStringCoordinateAtM(\n      this.flatCoordinates,\n      0,\n      this.flatCoordinates.length,\n      this.stride,\n      m,\n      extrapolate,\n    );\n  }\n\n  /**\n   * Return the coordinates of the linestring.\n   * @return {Array<import(\"../coordinate.js\").Coordinate>} Coordinates.\n   * @api\n   * @override\n   */\n  getCoordinates() {\n    return inflateCoordinates(\n      this.flatCoordinates,\n      0,\n      this.flatCoordinates.length,\n      this.stride,\n    );\n  }\n\n  /**\n   * Return the coordinate at the provided fraction along the linestring.\n   * The `fraction` is a number between 0 and 1, where 0 is the start of the\n   * linestring and 1 is the end.\n   * @param {number} fraction Fraction.\n   * @param {import(\"../coordinate.js\").Coordinate} [dest] Optional coordinate whose values will\n   *     be modified. If not provided, a new coordinate will be returned.\n   * @return {import(\"../coordinate.js\").Coordinate} Coordinate of the interpolated point.\n   * @api\n   */\n  getCoordinateAt(fraction, dest) {\n    return interpolatePoint(\n      this.flatCoordinates,\n      0,\n      this.flatCoordinates.length,\n      this.stride,\n      fraction,\n      dest,\n      this.stride,\n    );\n  }\n\n  /**\n   * Return the length of the linestring on projected plane.\n   * @return {number} Length (on projected plane).\n   * @api\n   */\n  getLength() {\n    return lineStringLength(\n      this.flatCoordinates,\n      0,\n      this.flatCoordinates.length,\n      this.stride,\n    );\n  }\n\n  /**\n   * @return {Array<number>} Flat midpoint.\n   */\n  getFlatMidpoint() {\n    if (this.flatMidpointRevision_ != this.getRevision()) {\n      this.flatMidpoint_ = this.getCoordinateAt(\n        0.5,\n        this.flatMidpoint_ ?? undefined,\n      );\n      this.flatMidpointRevision_ = this.getRevision();\n    }\n    return /** @type {Array<number>} */ (this.flatMidpoint_);\n  }\n\n  /**\n   * @param {number} squaredTolerance Squared tolerance.\n   * @return {LineString} Simplified LineString.\n   * @protected\n   * @override\n   */\n  getSimplifiedGeometryInternal(squaredTolerance) {\n    /** @type {Array<number>} */\n    const simplifiedFlatCoordinates = [];\n    simplifiedFlatCoordinates.length = douglasPeucker(\n      this.flatCoordinates,\n      0,\n      this.flatCoordinates.length,\n      this.stride,\n      squaredTolerance,\n      simplifiedFlatCoordinates,\n      0,\n    );\n    return new LineString(simplifiedFlatCoordinates, 'XY');\n  }\n\n  /**\n   * Get the type of this geometry.\n   * @return {import(\"./Geometry.js\").Type} Geometry type.\n   * @api\n   * @override\n   */\n  getType() {\n    return 'LineString';\n  }\n\n  /**\n   * Test if the geometry and the passed extent intersect.\n   * @param {import(\"../extent.js\").Extent} extent Extent.\n   * @return {boolean} `true` if the geometry and the extent intersect.\n   * @api\n   * @override\n   */\n  intersectsExtent(extent) {\n    return intersectsLineString(\n      this.flatCoordinates,\n      0,\n      this.flatCoordinates.length,\n      this.stride,\n      extent,\n      this.getExtent(),\n    );\n  }\n\n  /**\n   * Set the coordinates of the linestring.\n   * @param {!Array<import(\"../coordinate.js\").Coordinate>} coordinates Coordinates.\n   * @param {import(\"./Geometry.js\").GeometryLayout} [layout] Layout.\n   * @api\n   * @override\n   */\n  setCoordinates(coordinates, layout) {\n    this.setLayout(layout, coordinates, 1);\n    if (!this.flatCoordinates) {\n      this.flatCoordinates = [];\n    }\n    this.flatCoordinates.length = deflateCoordinates(\n      this.flatCoordinates,\n      0,\n      coordinates,\n      this.stride,\n    );\n    this.changed();\n  }\n}\n\nexport default LineString;\n", "/**\n * @module ol/geom/MultiLineString\n */\nimport {extend} from '../array.js';\nimport {closestSquaredDistanceXY} from '../extent.js';\nimport LineString from './LineString.js';\nimport SimpleGeometry from './SimpleGeometry.js';\nimport {arrayMaxSquaredDelta, assignClosestArrayPoint} from './flat/closest.js';\nimport {deflateCoordinatesArray} from './flat/deflate.js';\nimport {inflateCoordinatesArray} from './flat/inflate.js';\nimport {\n  interpolatePoint,\n  lineStringsCoordinateAtM,\n} from './flat/interpolate.js';\nimport {intersectsLineStringArray} from './flat/intersectsextent.js';\nimport {lineStringLength} from './flat/length.js';\nimport {douglasPeuckerArray} from './flat/simplify.js';\n\n/**\n * @classdesc\n * Multi-linestring geometry.\n *\n * @api\n */\nclass MultiLineString extends SimpleGeometry {\n  /**\n   * @param {Array<Array<import(\"../coordinate.js\").Coordinate>|LineString>|Array<number>} coordinates\n   *     Coordinates or LineString geometries. (For internal use, flat coordinates in\n   *     combination with `layout` and `ends` are also accepted.)\n   * @param {import(\"./Geometry.js\").GeometryLayout} [layout] Layout.\n   * @param {Array<number>} [ends] Flat coordinate ends for internal use.\n   */\n  constructor(coordinates, layout, ends) {\n    super();\n\n    /**\n     * @type {Array<number>}\n     * @private\n     */\n    this.ends_ = [];\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.maxDelta_ = -1;\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.maxDeltaRevision_ = -1;\n\n    if (Array.isArray(coordinates[0])) {\n      this.setCoordinates(\n        /** @type {Array<Array<import(\"../coordinate.js\").Coordinate>>} */ (\n          coordinates\n        ),\n        layout,\n      );\n    } else if (layout !== undefined && ends) {\n      this.setFlatCoordinates(\n        layout,\n        /** @type {Array<number>} */ (coordinates),\n      );\n      this.ends_ = ends;\n    } else {\n      const lineStrings = /** @type {Array<LineString>} */ (coordinates);\n      /** @type {Array<number>} */\n      const flatCoordinates = [];\n      const ends = [];\n      for (let i = 0, ii = lineStrings.length; i < ii; ++i) {\n        const lineString = lineStrings[i];\n        extend(flatCoordinates, lineString.getFlatCoordinates());\n        ends.push(flatCoordinates.length);\n      }\n      const layout =\n        lineStrings.length === 0\n          ? this.getLayout()\n          : lineStrings[0].getLayout();\n      this.setFlatCoordinates(layout, flatCoordinates);\n      this.ends_ = ends;\n    }\n  }\n\n  /**\n   * Append the passed linestring to the multilinestring.\n   * @param {LineString} lineString LineString.\n   * @api\n   */\n  appendLineString(lineString) {\n    extend(this.flatCoordinates, lineString.getFlatCoordinates().slice());\n    this.ends_.push(this.flatCoordinates.length);\n    this.changed();\n  }\n\n  /**\n   * Make a complete copy of the geometry.\n   * @return {!MultiLineString} Clone.\n   * @api\n   * @override\n   */\n  clone() {\n    const multiLineString = new MultiLineString(\n      this.flatCoordinates.slice(),\n      this.layout,\n      this.ends_.slice(),\n    );\n    multiLineString.applyProperties(this);\n    return multiLineString;\n  }\n\n  /**\n   * @param {number} x X.\n   * @param {number} y Y.\n   * @param {import(\"../coordinate.js\").Coordinate} closestPoint Closest point.\n   * @param {number} minSquaredDistance Minimum squared distance.\n   * @return {number} Minimum squared distance.\n   * @override\n   */\n  closestPointXY(x, y, closestPoint, minSquaredDistance) {\n    if (minSquaredDistance < closestSquaredDistanceXY(this.getExtent(), x, y)) {\n      return minSquaredDistance;\n    }\n    if (this.maxDeltaRevision_ != this.getRevision()) {\n      this.maxDelta_ = Math.sqrt(\n        arrayMaxSquaredDelta(\n          this.flatCoordinates,\n          0,\n          this.ends_,\n          this.stride,\n          0,\n        ),\n      );\n      this.maxDeltaRevision_ = this.getRevision();\n    }\n    return assignClosestArrayPoint(\n      this.flatCoordinates,\n      0,\n      this.ends_,\n      this.stride,\n      this.maxDelta_,\n      false,\n      x,\n      y,\n      closestPoint,\n      minSquaredDistance,\n    );\n  }\n\n  /**\n   * Returns the coordinate at `m` using linear interpolation, or `null` if no\n   * such coordinate exists.\n   *\n   * `extrapolate` controls extrapolation beyond the range of Ms in the\n   * MultiLineString. If `extrapolate` is `true` then Ms less than the first\n   * M will return the first coordinate and Ms greater than the last M will\n   * return the last coordinate.\n   *\n   * `interpolate` controls interpolation between consecutive LineStrings\n   * within the MultiLineString. If `interpolate` is `true` the coordinates\n   * will be linearly interpolated between the last coordinate of one LineString\n   * and the first coordinate of the next LineString.  If `interpolate` is\n   * `false` then the function will return `null` for Ms falling between\n   * LineStrings.\n   *\n   * @param {number} m M.\n   * @param {boolean} [extrapolate] Extrapolate. Default is `false`.\n   * @param {boolean} [interpolate] Interpolate. Default is `false`.\n   * @return {import(\"../coordinate.js\").Coordinate|null} Coordinate.\n   * @api\n   */\n  getCoordinateAtM(m, extrapolate, interpolate) {\n    if (\n      (this.layout != 'XYM' && this.layout != 'XYZM') ||\n      this.flatCoordinates.length === 0\n    ) {\n      return null;\n    }\n    extrapolate = extrapolate !== undefined ? extrapolate : false;\n    interpolate = interpolate !== undefined ? interpolate : false;\n    return lineStringsCoordinateAtM(\n      this.flatCoordinates,\n      0,\n      this.ends_,\n      this.stride,\n      m,\n      extrapolate,\n      interpolate,\n    );\n  }\n\n  /**\n   * Return the coordinates of the multilinestring.\n   * @return {Array<Array<import(\"../coordinate.js\").Coordinate>>} Coordinates.\n   * @api\n   * @override\n   */\n  getCoordinates() {\n    return inflateCoordinatesArray(\n      this.flatCoordinates,\n      0,\n      this.ends_,\n      this.stride,\n    );\n  }\n\n  /**\n   * @return {Array<number>} Ends.\n   */\n  getEnds() {\n    return this.ends_;\n  }\n\n  /**\n   * Return the linestring at the specified index.\n   * @param {number} index Index.\n   * @return {LineString} LineString.\n   * @api\n   */\n  getLineString(index) {\n    if (index < 0 || this.ends_.length <= index) {\n      return null;\n    }\n    return new LineString(\n      this.flatCoordinates.slice(\n        index === 0 ? 0 : this.ends_[index - 1],\n        this.ends_[index],\n      ),\n      this.layout,\n    );\n  }\n\n  /**\n   * Return the linestrings of this multilinestring.\n   * @return {Array<LineString>} LineStrings.\n   * @api\n   */\n  getLineStrings() {\n    const flatCoordinates = this.flatCoordinates;\n    const ends = this.ends_;\n    const layout = this.layout;\n    /** @type {Array<LineString>} */\n    const lineStrings = [];\n    let offset = 0;\n    for (let i = 0, ii = ends.length; i < ii; ++i) {\n      const end = ends[i];\n      const lineString = new LineString(\n        flatCoordinates.slice(offset, end),\n        layout,\n      );\n      lineStrings.push(lineString);\n      offset = end;\n    }\n    return lineStrings;\n  }\n\n  /**\n   * Return the sum of all line string lengths\n   * @return {number} Length (on projected plane).\n   * @api\n   */\n  getLength() {\n    const ends = this.ends_;\n    let start = 0;\n    let length = 0;\n    for (let i = 0, ii = ends.length; i < ii; ++i) {\n      length += lineStringLength(\n        this.flatCoordinates,\n        start,\n        ends[i],\n        this.stride,\n      );\n      start = ends[i];\n    }\n    return length;\n  }\n\n  /**\n   * @return {Array<number>} Flat midpoints.\n   */\n  getFlatMidpoints() {\n    /** @type {Array<number>} */\n    const midpoints = [];\n    const flatCoordinates = this.flatCoordinates;\n    let offset = 0;\n    const ends = this.ends_;\n    const stride = this.stride;\n    for (let i = 0, ii = ends.length; i < ii; ++i) {\n      const end = ends[i];\n      const midpoint = interpolatePoint(\n        flatCoordinates,\n        offset,\n        end,\n        stride,\n        0.5,\n      );\n      extend(midpoints, midpoint);\n      offset = end;\n    }\n    return midpoints;\n  }\n\n  /**\n   * @param {number} squaredTolerance Squared tolerance.\n   * @return {MultiLineString} Simplified MultiLineString.\n   * @protected\n   * @override\n   */\n  getSimplifiedGeometryInternal(squaredTolerance) {\n    /** @type {Array<number>} */\n    const simplifiedFlatCoordinates = [];\n    /** @type {Array<number>} */\n    const simplifiedEnds = [];\n    simplifiedFlatCoordinates.length = douglasPeuckerArray(\n      this.flatCoordinates,\n      0,\n      this.ends_,\n      this.stride,\n      squaredTolerance,\n      simplifiedFlatCoordinates,\n      0,\n      simplifiedEnds,\n    );\n    return new MultiLineString(simplifiedFlatCoordinates, 'XY', simplifiedEnds);\n  }\n\n  /**\n   * Get the type of this geometry.\n   * @return {import(\"./Geometry.js\").Type} Geometry type.\n   * @api\n   * @override\n   */\n  getType() {\n    return 'MultiLineString';\n  }\n\n  /**\n   * Test if the geometry and the passed extent intersect.\n   * @param {import(\"../extent.js\").Extent} extent Extent.\n   * @return {boolean} `true` if the geometry and the extent intersect.\n   * @api\n   * @override\n   */\n  intersectsExtent(extent) {\n    return intersectsLineStringArray(\n      this.flatCoordinates,\n      0,\n      this.ends_,\n      this.stride,\n      extent,\n    );\n  }\n\n  /**\n   * Set the coordinates of the multilinestring.\n   * @param {!Array<Array<import(\"../coordinate.js\").Coordinate>>} coordinates Coordinates.\n   * @param {import(\"./Geometry.js\").GeometryLayout} [layout] Layout.\n   * @api\n   * @override\n   */\n  setCoordinates(coordinates, layout) {\n    this.setLayout(layout, coordinates, 2);\n    if (!this.flatCoordinates) {\n      this.flatCoordinates = [];\n    }\n    const ends = deflateCoordinatesArray(\n      this.flatCoordinates,\n      0,\n      coordinates,\n      this.stride,\n      this.ends_,\n    );\n    this.flatCoordinates.length = ends.length === 0 ? 0 : ends[ends.length - 1];\n    this.changed();\n  }\n}\n\nexport default MultiLineString;\n", "/**\n * @module ol/geom/MultiPoint\n */\nimport {extend} from '../array.js';\nimport {closestSquaredDistanceXY, containsXY} from '../extent.js';\nimport {squaredDistance as squaredDx} from '../math.js';\nimport Point from './Point.js';\nimport SimpleGeometry from './SimpleGeometry.js';\nimport {deflateCoordinates} from './flat/deflate.js';\nimport {inflateCoordinates} from './flat/inflate.js';\n\n/**\n * @classdesc\n * Multi-point geometry.\n *\n * @api\n */\nclass MultiPoint extends SimpleGeometry {\n  /**\n   * @param {Array<import(\"../coordinate.js\").Coordinate>|Array<number>} coordinates Coordinates.\n   *     For internal use, flat coordinates in combination with `layout` are also accepted.\n   * @param {import(\"./Geometry.js\").GeometryLayout} [layout] Layout.\n   */\n  constructor(coordinates, layout) {\n    super();\n    if (layout && !Array.isArray(coordinates[0])) {\n      this.setFlatCoordinates(\n        layout,\n        /** @type {Array<number>} */ (coordinates),\n      );\n    } else {\n      this.setCoordinates(\n        /** @type {Array<import(\"../coordinate.js\").Coordinate>} */ (\n          coordinates\n        ),\n        layout,\n      );\n    }\n  }\n\n  /**\n   * Append the passed point to this multipoint.\n   * @param {Point} point Point.\n   * @api\n   */\n  appendPoint(point) {\n    extend(this.flatCoordinates, point.getFlatCoordinates());\n    this.changed();\n  }\n\n  /**\n   * Make a complete copy of the geometry.\n   * @return {!MultiPoint} Clone.\n   * @api\n   * @override\n   */\n  clone() {\n    const multiPoint = new MultiPoint(\n      this.flatCoordinates.slice(),\n      this.layout,\n    );\n    multiPoint.applyProperties(this);\n    return multiPoint;\n  }\n\n  /**\n   * @param {number} x X.\n   * @param {number} y Y.\n   * @param {import(\"../coordinate.js\").Coordinate} closestPoint Closest point.\n   * @param {number} minSquaredDistance Minimum squared distance.\n   * @return {number} Minimum squared distance.\n   * @override\n   */\n  closestPointXY(x, y, closestPoint, minSquaredDistance) {\n    if (minSquaredDistance < closestSquaredDistanceXY(this.getExtent(), x, y)) {\n      return minSquaredDistance;\n    }\n    const flatCoordinates = this.flatCoordinates;\n    const stride = this.stride;\n    for (let i = 0, ii = flatCoordinates.length; i < ii; i += stride) {\n      const squaredDistance = squaredDx(\n        x,\n        y,\n        flatCoordinates[i],\n        flatCoordinates[i + 1],\n      );\n      if (squaredDistance < minSquaredDistance) {\n        minSquaredDistance = squaredDistance;\n        for (let j = 0; j < stride; ++j) {\n          closestPoint[j] = flatCoordinates[i + j];\n        }\n        closestPoint.length = stride;\n      }\n    }\n    return minSquaredDistance;\n  }\n\n  /**\n   * Return the coordinates of the multipoint.\n   * @return {Array<import(\"../coordinate.js\").Coordinate>} Coordinates.\n   * @api\n   * @override\n   */\n  getCoordinates() {\n    return inflateCoordinates(\n      this.flatCoordinates,\n      0,\n      this.flatCoordinates.length,\n      this.stride,\n    );\n  }\n\n  /**\n   * Return the point at the specified index.\n   * @param {number} index Index.\n   * @return {Point} Point.\n   * @api\n   */\n  getPoint(index) {\n    const n = this.flatCoordinates.length / this.stride;\n    if (index < 0 || n <= index) {\n      return null;\n    }\n    return new Point(\n      this.flatCoordinates.slice(\n        index * this.stride,\n        (index + 1) * this.stride,\n      ),\n      this.layout,\n    );\n  }\n\n  /**\n   * Return the points of this multipoint.\n   * @return {Array<Point>} Points.\n   * @api\n   */\n  getPoints() {\n    const flatCoordinates = this.flatCoordinates;\n    const layout = this.layout;\n    const stride = this.stride;\n    /** @type {Array<Point>} */\n    const points = [];\n    for (let i = 0, ii = flatCoordinates.length; i < ii; i += stride) {\n      const point = new Point(flatCoordinates.slice(i, i + stride), layout);\n      points.push(point);\n    }\n    return points;\n  }\n\n  /**\n   * Get the type of this geometry.\n   * @return {import(\"./Geometry.js\").Type} Geometry type.\n   * @api\n   * @override\n   */\n  getType() {\n    return 'MultiPoint';\n  }\n\n  /**\n   * Test if the geometry and the passed extent intersect.\n   * @param {import(\"../extent.js\").Extent} extent Extent.\n   * @return {boolean} `true` if the geometry and the extent intersect.\n   * @api\n   * @override\n   */\n  intersectsExtent(extent) {\n    const flatCoordinates = this.flatCoordinates;\n    const stride = this.stride;\n    for (let i = 0, ii = flatCoordinates.length; i < ii; i += stride) {\n      const x = flatCoordinates[i];\n      const y = flatCoordinates[i + 1];\n      if (containsXY(extent, x, y)) {\n        return true;\n      }\n    }\n    return false;\n  }\n\n  /**\n   * Set the coordinates of the multipoint.\n   * @param {!Array<import(\"../coordinate.js\").Coordinate>} coordinates Coordinates.\n   * @param {import(\"./Geometry.js\").GeometryLayout} [layout] Layout.\n   * @api\n   * @override\n   */\n  setCoordinates(coordinates, layout) {\n    this.setLayout(layout, coordinates, 1);\n    if (!this.flatCoordinates) {\n      this.flatCoordinates = [];\n    }\n    this.flatCoordinates.length = deflateCoordinates(\n      this.flatCoordinates,\n      0,\n      coordinates,\n      this.stride,\n    );\n    this.changed();\n  }\n}\n\nexport default MultiPoint;\n", "/**\n * @module ol/geom/flat/center\n */\nimport {createEmpty, createOrUpdateFromFlatCoordinates} from '../../extent.js';\n\n/**\n * @param {Array<number>} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {Array<Array<number>>} endss Endss.\n * @param {number} stride Stride.\n * @return {Array<number>} Flat centers.\n */\nexport function linearRingss(flatCoordinates, offset, endss, stride) {\n  const flatCenters = [];\n  let extent = createEmpty();\n  for (let i = 0, ii = endss.length; i < ii; ++i) {\n    const ends = endss[i];\n    extent = createOrUpdateFromFlatCoordinates(\n      flatCoordinates,\n      offset,\n      ends[0],\n      stride,\n    );\n    flatCenters.push((extent[0] + extent[2]) / 2, (extent[1] + extent[3]) / 2);\n    offset = ends[ends.length - 1];\n  }\n  return flatCenters;\n}\n", "/**\n * @module ol/geom/MultiPolygon\n */\nimport {extend} from '../array.js';\nimport {closestSquaredDistanceXY} from '../extent.js';\nimport MultiPoint from './MultiPoint.js';\nimport Polygon from './Polygon.js';\nimport SimpleGeometry from './SimpleGeometry.js';\nimport {linearRingss as linearRingssArea} from './flat/area.js';\nimport {linearRingss as linearRingssCenter} from './flat/center.js';\nimport {\n  assignClosestMultiArrayPoint,\n  multiArrayMaxSquaredDelta,\n} from './flat/closest.js';\nimport {linearRingssContainsXY} from './flat/contains.js';\nimport {deflateMultiCoordinatesArray} from './flat/deflate.js';\nimport {inflateMultiCoordinatesArray} from './flat/inflate.js';\nimport {getInteriorPointsOfMultiArray} from './flat/interiorpoint.js';\nimport {intersectsLinearRingMultiArray} from './flat/intersectsextent.js';\nimport {\n  linearRingssAreOriented,\n  orientLinearRingsArray,\n} from './flat/orient.js';\nimport {quantizeMultiArray} from './flat/simplify.js';\n\n/**\n * @classdesc\n * Multi-polygon geometry.\n *\n * @api\n */\nclass MultiPolygon extends SimpleGeometry {\n  /**\n   * @param {Array<Array<Array<import(\"../coordinate.js\").Coordinate>>|Polygon>|Array<number>} coordinates Coordinates.\n   *     For internal use, flat coordinates in combination with `layout` and `endss` are also accepted.\n   * @param {import(\"./Geometry.js\").GeometryLayout} [layout] Layout.\n   * @param {Array<Array<number>>} [endss] Array of ends for internal use with flat coordinates.\n   */\n  constructor(coordinates, layout, endss) {\n    super();\n\n    /**\n     * @type {Array<Array<number>>}\n     * @private\n     */\n    this.endss_ = [];\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.flatInteriorPointsRevision_ = -1;\n\n    /**\n     * @private\n     * @type {Array<number>|null}\n     */\n    this.flatInteriorPoints_ = null;\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.maxDelta_ = -1;\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.maxDeltaRevision_ = -1;\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.orientedRevision_ = -1;\n\n    /**\n     * @private\n     * @type {Array<number>|null}\n     */\n    this.orientedFlatCoordinates_ = null;\n\n    if (!endss && !Array.isArray(coordinates[0])) {\n      const polygons = /** @type {Array<Polygon>} */ (coordinates);\n      /** @type {Array<number>} */\n      const flatCoordinates = [];\n      const thisEndss = [];\n      for (let i = 0, ii = polygons.length; i < ii; ++i) {\n        const polygon = polygons[i];\n        const offset = flatCoordinates.length;\n        const ends = polygon.getEnds();\n        for (let j = 0, jj = ends.length; j < jj; ++j) {\n          ends[j] += offset;\n        }\n        extend(flatCoordinates, polygon.getFlatCoordinates());\n        thisEndss.push(ends);\n      }\n      layout =\n        polygons.length === 0 ? this.getLayout() : polygons[0].getLayout();\n      coordinates = flatCoordinates;\n      endss = thisEndss;\n    }\n    if (layout !== undefined && endss) {\n      this.setFlatCoordinates(\n        layout,\n        /** @type {Array<number>} */ (coordinates),\n      );\n      this.endss_ = endss;\n    } else {\n      this.setCoordinates(\n        /** @type {Array<Array<Array<import(\"../coordinate.js\").Coordinate>>>} */ (\n          coordinates\n        ),\n        layout,\n      );\n    }\n  }\n\n  /**\n   * Append the passed polygon to this multipolygon.\n   * @param {Polygon} polygon Polygon.\n   * @api\n   */\n  appendPolygon(polygon) {\n    /** @type {Array<number>} */\n    let ends;\n    if (!this.flatCoordinates) {\n      this.flatCoordinates = polygon.getFlatCoordinates().slice();\n      ends = polygon.getEnds().slice();\n      this.endss_.push();\n    } else {\n      const offset = this.flatCoordinates.length;\n      extend(this.flatCoordinates, polygon.getFlatCoordinates());\n      ends = polygon.getEnds().slice();\n      for (let i = 0, ii = ends.length; i < ii; ++i) {\n        ends[i] += offset;\n      }\n    }\n    this.endss_.push(ends);\n    this.changed();\n  }\n\n  /**\n   * Make a complete copy of the geometry.\n   * @return {!MultiPolygon} Clone.\n   * @api\n   * @override\n   */\n  clone() {\n    const len = this.endss_.length;\n    const newEndss = new Array(len);\n    for (let i = 0; i < len; ++i) {\n      newEndss[i] = this.endss_[i].slice();\n    }\n\n    const multiPolygon = new MultiPolygon(\n      this.flatCoordinates.slice(),\n      this.layout,\n      newEndss,\n    );\n    multiPolygon.applyProperties(this);\n\n    return multiPolygon;\n  }\n\n  /**\n   * @param {number} x X.\n   * @param {number} y Y.\n   * @param {import(\"../coordinate.js\").Coordinate} closestPoint Closest point.\n   * @param {number} minSquaredDistance Minimum squared distance.\n   * @return {number} Minimum squared distance.\n   * @override\n   */\n  closestPointXY(x, y, closestPoint, minSquaredDistance) {\n    if (minSquaredDistance < closestSquaredDistanceXY(this.getExtent(), x, y)) {\n      return minSquaredDistance;\n    }\n    if (this.maxDeltaRevision_ != this.getRevision()) {\n      this.maxDelta_ = Math.sqrt(\n        multiArrayMaxSquaredDelta(\n          this.flatCoordinates,\n          0,\n          this.endss_,\n          this.stride,\n          0,\n        ),\n      );\n      this.maxDeltaRevision_ = this.getRevision();\n    }\n    return assignClosestMultiArrayPoint(\n      this.getOrientedFlatCoordinates(),\n      0,\n      this.endss_,\n      this.stride,\n      this.maxDelta_,\n      true,\n      x,\n      y,\n      closestPoint,\n      minSquaredDistance,\n    );\n  }\n\n  /**\n   * @param {number} x X.\n   * @param {number} y Y.\n   * @return {boolean} Contains (x, y).\n   * @override\n   */\n  containsXY(x, y) {\n    return linearRingssContainsXY(\n      this.getOrientedFlatCoordinates(),\n      0,\n      this.endss_,\n      this.stride,\n      x,\n      y,\n    );\n  }\n\n  /**\n   * Return the area of the multipolygon on projected plane.\n   * @return {number} Area (on projected plane).\n   * @api\n   */\n  getArea() {\n    return linearRingssArea(\n      this.getOrientedFlatCoordinates(),\n      0,\n      this.endss_,\n      this.stride,\n    );\n  }\n\n  /**\n   * Get the coordinate array for this geometry.  This array has the structure\n   * of a GeoJSON coordinate array for multi-polygons.\n   *\n   * @param {boolean} [right] Orient coordinates according to the right-hand\n   *     rule (counter-clockwise for exterior and clockwise for interior rings).\n   *     If `false`, coordinates will be oriented according to the left-hand rule\n   *     (clockwise for exterior and counter-clockwise for interior rings).\n   *     By default, coordinate orientation will depend on how the geometry was\n   *     constructed.\n   * @return {Array<Array<Array<import(\"../coordinate.js\").Coordinate>>>} Coordinates.\n   * @api\n   * @override\n   */\n  getCoordinates(right) {\n    let flatCoordinates;\n    if (right !== undefined) {\n      flatCoordinates = this.getOrientedFlatCoordinates().slice();\n      orientLinearRingsArray(\n        flatCoordinates,\n        0,\n        this.endss_,\n        this.stride,\n        right,\n      );\n    } else {\n      flatCoordinates = this.flatCoordinates;\n    }\n\n    return inflateMultiCoordinatesArray(\n      flatCoordinates,\n      0,\n      this.endss_,\n      this.stride,\n    );\n  }\n\n  /**\n   * @return {Array<Array<number>>} Endss.\n   */\n  getEndss() {\n    return this.endss_;\n  }\n\n  /**\n   * @return {Array<number>} Flat interior points.\n   */\n  getFlatInteriorPoints() {\n    if (this.flatInteriorPointsRevision_ != this.getRevision()) {\n      const flatCenters = linearRingssCenter(\n        this.flatCoordinates,\n        0,\n        this.endss_,\n        this.stride,\n      );\n      this.flatInteriorPoints_ = getInteriorPointsOfMultiArray(\n        this.getOrientedFlatCoordinates(),\n        0,\n        this.endss_,\n        this.stride,\n        flatCenters,\n      );\n      this.flatInteriorPointsRevision_ = this.getRevision();\n    }\n    return /** @type {Array<number>} */ (this.flatInteriorPoints_);\n  }\n\n  /**\n   * Return the interior points as {@link module:ol/geom/MultiPoint~MultiPoint multipoint}.\n   * @return {MultiPoint} Interior points as XYM coordinates, where M is\n   * the length of the horizontal intersection that the point belongs to.\n   * @api\n   */\n  getInteriorPoints() {\n    return new MultiPoint(this.getFlatInteriorPoints().slice(), 'XYM');\n  }\n\n  /**\n   * @return {Array<number>} Oriented flat coordinates.\n   */\n  getOrientedFlatCoordinates() {\n    if (this.orientedRevision_ != this.getRevision()) {\n      const flatCoordinates = this.flatCoordinates;\n      if (\n        linearRingssAreOriented(flatCoordinates, 0, this.endss_, this.stride)\n      ) {\n        this.orientedFlatCoordinates_ = flatCoordinates;\n      } else {\n        this.orientedFlatCoordinates_ = flatCoordinates.slice();\n        this.orientedFlatCoordinates_.length = orientLinearRingsArray(\n          this.orientedFlatCoordinates_,\n          0,\n          this.endss_,\n          this.stride,\n        );\n      }\n      this.orientedRevision_ = this.getRevision();\n    }\n    return /** @type {Array<number>} */ (this.orientedFlatCoordinates_);\n  }\n\n  /**\n   * @param {number} squaredTolerance Squared tolerance.\n   * @return {MultiPolygon} Simplified MultiPolygon.\n   * @protected\n   * @override\n   */\n  getSimplifiedGeometryInternal(squaredTolerance) {\n    /** @type {Array<number>} */\n    const simplifiedFlatCoordinates = [];\n    /** @type {Array<Array<number>>} */\n    const simplifiedEndss = [];\n    simplifiedFlatCoordinates.length = quantizeMultiArray(\n      this.flatCoordinates,\n      0,\n      this.endss_,\n      this.stride,\n      Math.sqrt(squaredTolerance),\n      simplifiedFlatCoordinates,\n      0,\n      simplifiedEndss,\n    );\n    return new MultiPolygon(simplifiedFlatCoordinates, 'XY', simplifiedEndss);\n  }\n\n  /**\n   * Return the polygon at the specified index.\n   * @param {number} index Index.\n   * @return {Polygon} Polygon.\n   * @api\n   */\n  getPolygon(index) {\n    if (index < 0 || this.endss_.length <= index) {\n      return null;\n    }\n    let offset;\n    if (index === 0) {\n      offset = 0;\n    } else {\n      const prevEnds = this.endss_[index - 1];\n      offset = prevEnds[prevEnds.length - 1];\n    }\n    const ends = this.endss_[index].slice();\n    const end = ends[ends.length - 1];\n    if (offset !== 0) {\n      for (let i = 0, ii = ends.length; i < ii; ++i) {\n        ends[i] -= offset;\n      }\n    }\n    return new Polygon(\n      this.flatCoordinates.slice(offset, end),\n      this.layout,\n      ends,\n    );\n  }\n\n  /**\n   * Return the polygons of this multipolygon.\n   * @return {Array<Polygon>} Polygons.\n   * @api\n   */\n  getPolygons() {\n    const layout = this.layout;\n    const flatCoordinates = this.flatCoordinates;\n    const endss = this.endss_;\n    const polygons = [];\n    let offset = 0;\n    for (let i = 0, ii = endss.length; i < ii; ++i) {\n      const ends = endss[i].slice();\n      const end = ends[ends.length - 1];\n      if (offset !== 0) {\n        for (let j = 0, jj = ends.length; j < jj; ++j) {\n          ends[j] -= offset;\n        }\n      }\n      const polygon = new Polygon(\n        flatCoordinates.slice(offset, end),\n        layout,\n        ends,\n      );\n      polygons.push(polygon);\n      offset = end;\n    }\n    return polygons;\n  }\n\n  /**\n   * Get the type of this geometry.\n   * @return {import(\"./Geometry.js\").Type} Geometry type.\n   * @api\n   * @override\n   */\n  getType() {\n    return 'MultiPolygon';\n  }\n\n  /**\n   * Test if the geometry and the passed extent intersect.\n   * @param {import(\"../extent.js\").Extent} extent Extent.\n   * @return {boolean} `true` if the geometry and the extent intersect.\n   * @api\n   * @override\n   */\n  intersectsExtent(extent) {\n    return intersectsLinearRingMultiArray(\n      this.getOrientedFlatCoordinates(),\n      0,\n      this.endss_,\n      this.stride,\n      extent,\n    );\n  }\n\n  /**\n   * Set the coordinates of the multipolygon.\n   * @param {!Array<Array<Array<import(\"../coordinate.js\").Coordinate>>>} coordinates Coordinates.\n   * @param {import(\"./Geometry.js\").GeometryLayout} [layout] Layout.\n   * @api\n   * @override\n   */\n  setCoordinates(coordinates, layout) {\n    this.setLayout(layout, coordinates, 3);\n    if (!this.flatCoordinates) {\n      this.flatCoordinates = [];\n    }\n    const endss = deflateMultiCoordinatesArray(\n      this.flatCoordinates,\n      0,\n      coordinates,\n      this.stride,\n      this.endss_,\n    );\n    if (endss.length === 0) {\n      this.flatCoordinates.length = 0;\n    } else {\n      const lastEnds = endss[endss.length - 1];\n      this.flatCoordinates.length =\n        lastEnds.length === 0 ? 0 : lastEnds[lastEnds.length - 1];\n    }\n    this.changed();\n  }\n}\n\nexport default MultiPolygon;\n", "/**\n * @module ol/render/VectorContext\n */\n\n/**\n * @classdesc\n * Context for drawing geometries.  A vector context is available on render\n * events and does not need to be constructed directly.\n * @api\n */\nclass VectorContext {\n  /**\n   * Render a geometry with a custom renderer.\n   *\n   * @param {import(\"../geom/SimpleGeometry.js\").default} geometry Geometry.\n   * @param {import(\"../Feature.js\").FeatureLike} feature Feature.\n   * @param {Function} renderer Renderer.\n   * @param {Function} hitDetectionRenderer Renderer.\n   * @param {number} [index] Render order index.\n   */\n  drawCustom(geometry, feature, renderer, hitDetectionRenderer, index) {}\n\n  /**\n   * Render a geometry.\n   *\n   * @param {import(\"../geom/Geometry.js\").default} geometry The geometry to render.\n   */\n  drawGeometry(geometry) {}\n\n  /**\n   * Set the rendering style.\n   *\n   * @param {import(\"../style/Style.js\").default} style The rendering style.\n   */\n  setStyle(style) {}\n\n  /**\n   * @param {import(\"../geom/Circle.js\").default} circleGeometry Circle geometry.\n   * @param {import(\"../Feature.js\").default} feature Feature.\n   * @param {number} [index] Render order index.\n   */\n  drawCircle(circleGeometry, feature, index) {}\n\n  /**\n   * @param {import(\"../Feature.js\").default} feature Feature.\n   * @param {import(\"../style/Style.js\").default} style Style.\n   * @param {number} [index] Render order index.\n   */\n  drawFeature(feature, style, index) {}\n\n  /**\n   * @param {import(\"../geom/GeometryCollection.js\").default} geometryCollectionGeometry Geometry collection.\n   * @param {import(\"../Feature.js\").default} feature Feature.\n   * @param {number} [index] Render order index.\n   */\n  drawGeometryCollection(geometryCollectionGeometry, feature, index) {}\n\n  /**\n   * @param {import(\"../geom/LineString.js\").default|import(\"./Feature.js\").default} lineStringGeometry Line string geometry.\n   * @param {import(\"../Feature.js\").FeatureLike} feature Feature.\n   * @param {number} [index] Render order index.\n   */\n  drawLineString(lineStringGeometry, feature, index) {}\n\n  /**\n   * @param {import(\"../geom/MultiLineString.js\").default|import(\"./Feature.js\").default} multiLineStringGeometry MultiLineString geometry.\n   * @param {import(\"../Feature.js\").FeatureLike} feature Feature.\n   * @param {number} [index] Render order index.\n   */\n  drawMultiLineString(multiLineStringGeometry, feature, index) {}\n\n  /**\n   * @param {import(\"../geom/MultiPoint.js\").default|import(\"./Feature.js\").default} multiPointGeometry MultiPoint geometry.\n   * @param {import(\"../Feature.js\").FeatureLike} feature Feature.\n   * @param {number} [index] Render order index.\n   */\n  drawMultiPoint(multiPointGeometry, feature, index) {}\n\n  /**\n   * @param {import(\"../geom/MultiPolygon.js\").default} multiPolygonGeometry MultiPolygon geometry.\n   * @param {import(\"../Feature.js\").FeatureLike} feature Feature.\n   * @param {number} [index] Render order index.\n   */\n  drawMultiPolygon(multiPolygonGeometry, feature, index) {}\n\n  /**\n   * @param {import(\"../geom/Point.js\").default|import(\"./Feature.js\").default} pointGeometry Point geometry.\n   * @param {import(\"../Feature.js\").FeatureLike} feature Feature.\n   * @param {number} [index] Render order index.\n   */\n  drawPoint(pointGeometry, feature, index) {}\n\n  /**\n   * @param {import(\"../geom/Polygon.js\").default|import(\"./Feature.js\").default} polygonGeometry Polygon geometry.\n   * @param {import(\"../Feature.js\").FeatureLike} feature Feature.\n   * @param {number} [index] Render order index.\n   */\n  drawPolygon(polygonGeometry, feature, index) {}\n\n  /**\n   * @param {import(\"../geom/SimpleGeometry.js\").default|import(\"./Feature.js\").default} geometry Geometry.\n   * @param {import(\"../Feature.js\").FeatureLike} feature Feature.\n   * @param {number} [index] Render order index.\n   */\n  drawText(geometry, feature, index) {}\n\n  /**\n   * @param {import(\"../style/Fill.js\").default} fillStyle Fill style.\n   * @param {import(\"../style/Stroke.js\").default} strokeStyle Stroke style.\n   */\n  setFillStrokeStyle(fillStyle, strokeStyle) {}\n\n  /**\n   * @param {import(\"../style/Image.js\").default} imageStyle Image style.\n   * @param {import(\"../render/canvas.js\").DeclutterImageWithText} [declutterImageWithText] Shared data for combined decluttering with a text style.\n   */\n  setImageStyle(imageStyle, declutterImageWithText) {}\n\n  /**\n   * @param {import(\"../style/Text.js\").default} textStyle Text style.\n   * @param {import(\"../render/canvas.js\").DeclutterImageWithText} [declutterImageWithText] Shared data for combined decluttering with an image style.\n   */\n  setTextStyle(textStyle, declutterImageWithText) {}\n}\n\nexport default VectorContext;\n", "/**\n * @module ol/render/canvas/Instruction\n */\n\n/**\n * @enum {number}\n */\nconst Instruction = {\n  BEGIN_GEOMETRY: 0,\n  BEGIN_PATH: 1,\n  CIRCLE: 2,\n  CLOSE_PATH: 3,\n  CUSTOM: 4,\n  DRAW_CHARS: 5,\n  DRAW_IMAGE: 6,\n  END_GEOMETRY: 7,\n  FILL: 8,\n  MOVE_TO_LINE_TO: 9,\n  SET_FILL_STYLE: 10,\n  SET_STROKE_STYLE: 11,\n  STROKE: 12,\n};\n\n/**\n * @type {Array<Instruction>}\n */\nexport const fillInstruction = [Instruction.FILL];\n\n/**\n * @type {Array<Instruction>}\n */\nexport const strokeInstruction = [Instruction.STROKE];\n\n/**\n * @type {Array<Instruction>}\n */\nexport const beginPathInstruction = [Instruction.BEGIN_PATH];\n\n/**\n * @type {Array<Instruction>}\n */\nexport const closePathInstruction = [Instruction.CLOSE_PATH];\n\nexport default Instruction;\n", "/**\n * @module ol/render/canvas/Builder\n */\nimport {equals, reverseSubArray} from '../../array.js';\nimport {asColorLike} from '../../colorlike.js';\nimport {\n  buffer,\n  clone,\n  containsCoordinate,\n  coordinateRelationship,\n} from '../../extent.js';\nimport Relationship from '../../extent/Relationship.js';\nimport {\n  inflateCoordinates,\n  inflateCoordinatesArray,\n  inflateMultiCoordinatesArray,\n} from '../../geom/flat/inflate.js';\nimport VectorContext from '../VectorContext.js';\nimport {\n  defaultFillStyle,\n  defaultLineCap,\n  defaultLineDash,\n  defaultLineDashOffset,\n  defaultLineJoin,\n  defaultLineWidth,\n  defaultMiterLimit,\n  defaultStrokeOffset,\n  defaultStrokeStyle,\n} from '../canvas.js';\nimport CanvasInstruction from './Instruction.js';\n\nclass CanvasBuilder extends VectorContext {\n  /**\n   * @param {number} tolerance Tolerance.\n   * @param {import(\"../../extent.js\").Extent} maxExtent Maximum extent.\n   * @param {number} resolution Resolution.\n   * @param {number} pixelRatio Pixel ratio.\n   */\n  constructor(tolerance, maxExtent, resolution, pixelRatio) {\n    super();\n\n    /**\n     * @protected\n     * @type {number}\n     */\n    this.tolerance = tolerance;\n\n    /**\n     * @protected\n     * @const\n     * @type {import(\"../../extent.js\").Extent}\n     */\n    this.maxExtent = maxExtent;\n\n    /**\n     * @protected\n     * @type {number}\n     */\n    this.pixelRatio = pixelRatio;\n\n    /**\n     * @protected\n     * @type {number}\n     */\n    this.maxLineWidth = 0;\n\n    /**\n     * @protected\n     * @const\n     * @type {number}\n     */\n    this.resolution = resolution;\n\n    /**\n     * @private\n     * @type {Array<*>}\n     */\n    this.beginGeometryInstruction1_ = null;\n\n    /**\n     * @private\n     * @type {Array<*>}\n     */\n    this.beginGeometryInstruction2_ = null;\n\n    /**\n     * @private\n     * @type {import(\"../../extent.js\").Extent}\n     */\n    this.bufferedMaxExtent_ = null;\n\n    /**\n     * @protected\n     * @type {Array<*>}\n     */\n    this.instructions = [];\n\n    /**\n     * @protected\n     * @type {Array<number>}\n     */\n    this.coordinates = [];\n\n    /**\n     * @private\n     * @type {import(\"../../coordinate.js\").Coordinate}\n     */\n    this.tmpCoordinate_ = [];\n\n    /**\n     * @protected\n     * @type {Array<*>}\n     */\n    this.hitDetectionInstructions = [];\n\n    /**\n     * @protected\n     * @type {import(\"../canvas.js\").FillStrokeState}\n     */\n    this.state = /** @type {import(\"../canvas.js\").FillStrokeState} */ ({});\n  }\n\n  /**\n   * @protected\n   * @param {Array<number>} dashArray Dash array.\n   * @return {Array<number>} Dash array with pixel ratio applied\n   */\n  applyPixelRatio(dashArray) {\n    const pixelRatio = this.pixelRatio;\n    return pixelRatio == 1\n      ? dashArray\n      : dashArray.map(function (dash) {\n          return dash * pixelRatio;\n        });\n  }\n\n  /**\n   * @param {Array<number>} flatCoordinates Flat coordinates.\n   * @param {number} stride Stride.\n   * @protected\n   * @return {number} My end\n   */\n  appendFlatPointCoordinates(flatCoordinates, stride) {\n    const extent = this.getBufferedMaxExtent();\n    const tmpCoord = this.tmpCoordinate_;\n    const coordinates = this.coordinates;\n    let myEnd = coordinates.length;\n    for (let i = 0, ii = flatCoordinates.length; i < ii; i += stride) {\n      tmpCoord[0] = flatCoordinates[i];\n      tmpCoord[1] = flatCoordinates[i + 1];\n      if (containsCoordinate(extent, tmpCoord)) {\n        coordinates[myEnd++] = tmpCoord[0];\n        coordinates[myEnd++] = tmpCoord[1];\n      }\n    }\n    return myEnd;\n  }\n\n  /**\n   * @param {Array<number>} flatCoordinates Flat coordinates.\n   * @param {number} offset Offset.\n   * @param {number} end End.\n   * @param {number} stride Stride.\n   * @param {boolean} closed Last input coordinate equals first.\n   * @param {boolean} skipFirst Skip first coordinate.\n   * @protected\n   * @return {number} My end.\n   */\n  appendFlatLineCoordinates(\n    flatCoordinates,\n    offset,\n    end,\n    stride,\n    closed,\n    skipFirst,\n  ) {\n    const coordinates = this.coordinates;\n    let myEnd = coordinates.length;\n    const extent = this.getBufferedMaxExtent();\n    if (skipFirst) {\n      offset += stride;\n    }\n    let lastXCoord = flatCoordinates[offset];\n    let lastYCoord = flatCoordinates[offset + 1];\n    const nextCoord = this.tmpCoordinate_;\n    let skipped = true;\n\n    let i, lastRel, nextRel;\n    for (i = offset + stride; i < end; i += stride) {\n      nextCoord[0] = flatCoordinates[i];\n      nextCoord[1] = flatCoordinates[i + 1];\n      nextRel = coordinateRelationship(extent, nextCoord);\n      if (nextRel !== lastRel) {\n        if (skipped) {\n          coordinates[myEnd++] = lastXCoord;\n          coordinates[myEnd++] = lastYCoord;\n          skipped = false;\n        }\n        coordinates[myEnd++] = nextCoord[0];\n        coordinates[myEnd++] = nextCoord[1];\n      } else if (nextRel === Relationship.INTERSECTING) {\n        coordinates[myEnd++] = nextCoord[0];\n        coordinates[myEnd++] = nextCoord[1];\n        skipped = false;\n      } else {\n        skipped = true;\n      }\n      lastXCoord = nextCoord[0];\n      lastYCoord = nextCoord[1];\n      lastRel = nextRel;\n    }\n\n    // Last coordinate equals first or only one point to append:\n    if ((closed && skipped) || i === offset + stride) {\n      coordinates[myEnd++] = lastXCoord;\n      coordinates[myEnd++] = lastYCoord;\n    }\n    return myEnd;\n  }\n\n  /**\n   * @param {Array<number>} flatCoordinates Flat coordinates.\n   * @param {number} offset Offset.\n   * @param {Array<number>} ends Ends.\n   * @param {number} stride Stride.\n   * @param {Array<number>} builderEnds Builder ends.\n   * @return {number} Offset.\n   */\n  drawCustomCoordinates_(flatCoordinates, offset, ends, stride, builderEnds) {\n    for (let i = 0, ii = ends.length; i < ii; ++i) {\n      const end = ends[i];\n      const builderEnd = this.appendFlatLineCoordinates(\n        flatCoordinates,\n        offset,\n        end,\n        stride,\n        false,\n        false,\n      );\n      builderEnds.push(builderEnd);\n      offset = end;\n    }\n    return offset;\n  }\n\n  /**\n   * @param {import(\"../../geom/SimpleGeometry.js\").default} geometry Geometry.\n   * @param {import(\"../../Feature.js\").FeatureLike} feature Feature.\n   * @param {Function} renderer Renderer.\n   * @param {Function} hitDetectionRenderer Renderer.\n   * @param {number} [index] Render order index.\n   * @override\n   */\n  drawCustom(geometry, feature, renderer, hitDetectionRenderer, index) {\n    this.beginGeometry(geometry, feature, index);\n\n    const type = geometry.getType();\n    const stride = geometry.getStride();\n    const builderBegin = this.coordinates.length;\n\n    let flatCoordinates, builderEnd, builderEnds, builderEndss;\n    let offset;\n\n    switch (type) {\n      case 'MultiPolygon':\n        flatCoordinates =\n          /** @type {import(\"../../geom/MultiPolygon.js\").default} */ (\n            geometry\n          ).getOrientedFlatCoordinates();\n        builderEndss = [];\n        const endss =\n          /** @type {import(\"../../geom/MultiPolygon.js\").default} */ (\n            geometry\n          ).getEndss();\n        offset = 0;\n        for (let i = 0, ii = endss.length; i < ii; ++i) {\n          const myEnds = [];\n          offset = this.drawCustomCoordinates_(\n            flatCoordinates,\n            offset,\n            endss[i],\n            stride,\n            myEnds,\n          );\n          builderEndss.push(myEnds);\n        }\n        this.instructions.push([\n          CanvasInstruction.CUSTOM,\n          builderBegin,\n          builderEndss,\n          geometry,\n          renderer,\n          inflateMultiCoordinatesArray,\n          index,\n        ]);\n        this.hitDetectionInstructions.push([\n          CanvasInstruction.CUSTOM,\n          builderBegin,\n          builderEndss,\n          geometry,\n          hitDetectionRenderer || renderer,\n          inflateMultiCoordinatesArray,\n          index,\n        ]);\n        break;\n      case 'Polygon':\n      case 'MultiLineString':\n        builderEnds = [];\n        flatCoordinates =\n          type == 'Polygon'\n            ? /** @type {import(\"../../geom/Polygon.js\").default} */ (\n                geometry\n              ).getOrientedFlatCoordinates()\n            : geometry.getFlatCoordinates();\n        offset = this.drawCustomCoordinates_(\n          flatCoordinates,\n          0,\n          /** @type {import(\"../../geom/Polygon.js\").default|import(\"../../geom/MultiLineString.js\").default} */ (\n            geometry\n          ).getEnds(),\n          stride,\n          builderEnds,\n        );\n        this.instructions.push([\n          CanvasInstruction.CUSTOM,\n          builderBegin,\n          builderEnds,\n          geometry,\n          renderer,\n          inflateCoordinatesArray,\n          index,\n        ]);\n        this.hitDetectionInstructions.push([\n          CanvasInstruction.CUSTOM,\n          builderBegin,\n          builderEnds,\n          geometry,\n          hitDetectionRenderer || renderer,\n          inflateCoordinatesArray,\n          index,\n        ]);\n        break;\n      case 'LineString':\n      case 'Circle':\n        flatCoordinates = geometry.getFlatCoordinates();\n        builderEnd = this.appendFlatLineCoordinates(\n          flatCoordinates,\n          0,\n          flatCoordinates.length,\n          stride,\n          false,\n          false,\n        );\n        this.instructions.push([\n          CanvasInstruction.CUSTOM,\n          builderBegin,\n          builderEnd,\n          geometry,\n          renderer,\n          inflateCoordinates,\n          index,\n        ]);\n        this.hitDetectionInstructions.push([\n          CanvasInstruction.CUSTOM,\n          builderBegin,\n          builderEnd,\n          geometry,\n          hitDetectionRenderer || renderer,\n          inflateCoordinates,\n          index,\n        ]);\n        break;\n      case 'MultiPoint':\n        flatCoordinates = geometry.getFlatCoordinates();\n        builderEnd = this.appendFlatPointCoordinates(flatCoordinates, stride);\n\n        if (builderEnd > builderBegin) {\n          this.instructions.push([\n            CanvasInstruction.CUSTOM,\n            builderBegin,\n            builderEnd,\n            geometry,\n            renderer,\n            inflateCoordinates,\n            index,\n          ]);\n          this.hitDetectionInstructions.push([\n            CanvasInstruction.CUSTOM,\n            builderBegin,\n            builderEnd,\n            geometry,\n            hitDetectionRenderer || renderer,\n            inflateCoordinates,\n            index,\n          ]);\n        }\n        break;\n      case 'Point':\n        flatCoordinates = geometry.getFlatCoordinates();\n        this.coordinates.push(flatCoordinates[0], flatCoordinates[1]);\n        builderEnd = this.coordinates.length;\n\n        this.instructions.push([\n          CanvasInstruction.CUSTOM,\n          builderBegin,\n          builderEnd,\n          geometry,\n          renderer,\n          undefined,\n          index,\n        ]);\n        this.hitDetectionInstructions.push([\n          CanvasInstruction.CUSTOM,\n          builderBegin,\n          builderEnd,\n          geometry,\n          hitDetectionRenderer || renderer,\n          undefined,\n          index,\n        ]);\n        break;\n      default:\n    }\n    this.endGeometry(feature);\n  }\n\n  /**\n   * @protected\n   * @param {import(\"../../geom/Geometry.js\").default|import(\"../Feature.js\").default} geometry The geometry.\n   * @param {import(\"../../Feature.js\").FeatureLike} feature Feature.\n   * @param {number} index Render order index\n   */\n  beginGeometry(geometry, feature, index) {\n    this.beginGeometryInstruction1_ = [\n      CanvasInstruction.BEGIN_GEOMETRY,\n      feature,\n      0,\n      geometry,\n      index,\n    ];\n    this.instructions.push(this.beginGeometryInstruction1_);\n    this.beginGeometryInstruction2_ = [\n      CanvasInstruction.BEGIN_GEOMETRY,\n      feature,\n      0,\n      geometry,\n      index,\n    ];\n    this.hitDetectionInstructions.push(this.beginGeometryInstruction2_);\n  }\n\n  /**\n   * @return {import(\"../canvas.js\").SerializableInstructions} the serializable instructions.\n   */\n  finish() {\n    return {\n      instructions: this.instructions,\n      hitDetectionInstructions: this.hitDetectionInstructions,\n      coordinates: this.coordinates,\n    };\n  }\n\n  /**\n   * Reverse the hit detection instructions.\n   */\n  reverseHitDetectionInstructions() {\n    const hitDetectionInstructions = this.hitDetectionInstructions;\n    // step 1 - reverse array\n    hitDetectionInstructions.reverse();\n    // step 2 - reverse instructions within geometry blocks\n    let i;\n    const n = hitDetectionInstructions.length;\n    let instruction;\n    let type;\n    let begin = -1;\n    for (i = 0; i < n; ++i) {\n      instruction = hitDetectionInstructions[i];\n      type = /** @type {import(\"./Instruction.js\").default} */ (instruction[0]);\n      if (type == CanvasInstruction.END_GEOMETRY) {\n        begin = i;\n      } else if (type == CanvasInstruction.BEGIN_GEOMETRY) {\n        instruction[2] = i;\n        reverseSubArray(this.hitDetectionInstructions, begin, i);\n        begin = -1;\n      }\n    }\n  }\n\n  /**\n   * @param {import(\"../../style/Fill.js\").default} fillStyle Fill style.\n   * @param {import('../canvas.js').FillStrokeState} [state] State.\n   * @return {import('../canvas.js').FillStrokeState} State.\n   */\n  fillStyleToState(\n    fillStyle,\n    state = /** @type {import('../canvas.js').FillStrokeState} */ ({}),\n  ) {\n    if (fillStyle) {\n      const fillStyleColor = fillStyle.getColor();\n      state.fillPatternScale =\n        fillStyleColor &&\n        typeof fillStyleColor === 'object' &&\n        'src' in fillStyleColor\n          ? this.pixelRatio\n          : 1;\n      state.fillStyle =\n        asColorLike(fillStyleColor ? fillStyleColor : defaultFillStyle) ??\n        undefined;\n    } else {\n      state.fillStyle = undefined;\n    }\n    return state;\n  }\n\n  /**\n   * @param {import(\"../../style/Stroke.js\").default} strokeStyle Stroke style.\n   * @param {import(\"../canvas.js\").FillStrokeState} state State.\n   * @return {import(\"../canvas.js\").FillStrokeState} State.\n   */\n  strokeStyleToState(\n    strokeStyle,\n    state = /** @type {import('../canvas.js').FillStrokeState} */ ({}),\n  ) {\n    if (strokeStyle) {\n      const strokeStyleColor = strokeStyle.getColor();\n      state.strokeStyle = asColorLike(\n        strokeStyleColor ? strokeStyleColor : defaultStrokeStyle,\n      );\n      const strokeStyleLineCap = strokeStyle.getLineCap();\n      state.lineCap =\n        strokeStyleLineCap !== undefined ? strokeStyleLineCap : defaultLineCap;\n      const strokeStyleLineDash = strokeStyle.getLineDash();\n      state.lineDash = strokeStyleLineDash\n        ? strokeStyleLineDash.slice()\n        : defaultLineDash;\n      const strokeStyleLineDashOffset = strokeStyle.getLineDashOffset();\n      state.lineDashOffset = strokeStyleLineDashOffset\n        ? strokeStyleLineDashOffset\n        : defaultLineDashOffset;\n      const strokeStyleLineJoin = strokeStyle.getLineJoin();\n      state.lineJoin =\n        strokeStyleLineJoin !== undefined\n          ? strokeStyleLineJoin\n          : defaultLineJoin;\n      const strokeStyleWidth = strokeStyle.getWidth();\n      state.lineWidth =\n        strokeStyleWidth !== undefined ? strokeStyleWidth : defaultLineWidth;\n      const strokeStyleMiterLimit = strokeStyle.getMiterLimit();\n      state.miterLimit =\n        strokeStyleMiterLimit !== undefined\n          ? strokeStyleMiterLimit\n          : defaultMiterLimit;\n      const strokeStyleOffset = strokeStyle.getOffset();\n      state.strokeOffset = strokeStyleOffset ?? defaultStrokeOffset;\n\n      if (state.lineWidth > this.maxLineWidth) {\n        this.maxLineWidth = state.lineWidth;\n        // invalidate the buffered max extent cache\n        this.bufferedMaxExtent_ = null;\n      }\n    } else {\n      state.strokeStyle = undefined;\n      state.lineCap = undefined;\n      state.lineDash = null;\n      state.lineDashOffset = undefined;\n      state.lineJoin = undefined;\n      state.lineWidth = undefined;\n      state.miterLimit = undefined;\n      state.strokeOffset = undefined;\n    }\n    return state;\n  }\n\n  /**\n   * @param {import(\"../../style/Fill.js\").default} fillStyle Fill style.\n   * @param {import(\"../../style/Stroke.js\").default} strokeStyle Stroke style.\n   * @override\n   */\n  setFillStrokeStyle(fillStyle, strokeStyle) {\n    const state = this.state;\n    this.fillStyleToState(fillStyle, state);\n    this.strokeStyleToState(strokeStyle, state);\n  }\n\n  /**\n   * @param {import(\"../canvas.js\").FillStrokeState} state State.\n   * @return {Array<*>} Fill instruction.\n   */\n  createFill(state) {\n    const fillStyle = state.fillStyle;\n    /** @type {Array<*>} */\n    const fillInstruction = [CanvasInstruction.SET_FILL_STYLE, fillStyle];\n    if (typeof fillStyle !== 'string') {\n      // Fill is a pattern or gradient - align and scale it!\n      fillInstruction.push(state.fillPatternScale);\n    }\n    return fillInstruction;\n  }\n\n  /**\n   * @param {import(\"../canvas.js\").FillStrokeState} state State.\n   */\n  applyStroke(state) {\n    this.instructions.push(this.createStroke(state));\n  }\n\n  /**\n   * @param {import(\"../canvas.js\").FillStrokeState} state State.\n   * @return {Array<*>} Stroke instruction.\n   */\n  createStroke(state) {\n    return [\n      CanvasInstruction.SET_STROKE_STYLE,\n      state.strokeStyle,\n      state.lineWidth * this.pixelRatio,\n      state.lineCap,\n      state.lineJoin,\n      state.miterLimit,\n      state.lineDash ? this.applyPixelRatio(state.lineDash) : null,\n      state.lineDashOffset * this.pixelRatio,\n    ];\n  }\n\n  /**\n   * @param {import(\"../canvas.js\").FillStrokeState} state State.\n   * @param {function(this:CanvasBuilder, import(\"../canvas.js\").FillStrokeState):Array<*>} createFill Create fill.\n   */\n  updateFillStyle(state, createFill) {\n    const fillStyle = state.fillStyle;\n    if (\n      (fillStyle !== undefined && typeof fillStyle !== 'string') ||\n      state.currentFillStyle != fillStyle\n    ) {\n      this.instructions.push(createFill.call(this, state));\n      state.currentFillStyle = fillStyle;\n    }\n  }\n\n  /**\n   * @param {import(\"../canvas.js\").FillStrokeState} state State.\n   * @param {function(this:CanvasBuilder, import(\"../canvas.js\").FillStrokeState): void} applyStroke Apply stroke.\n   */\n  updateStrokeStyle(state, applyStroke) {\n    const strokeStyle = state.strokeStyle;\n    const lineCap = state.lineCap;\n    const lineDash = state.lineDash;\n    const lineDashOffset = state.lineDashOffset;\n    const lineJoin = state.lineJoin;\n    const lineWidth = state.lineWidth;\n    const miterLimit = state.miterLimit;\n    const strokeOffset = state.strokeOffset;\n    if (\n      state.currentStrokeStyle != strokeStyle ||\n      state.currentLineCap != lineCap ||\n      (lineDash != state.currentLineDash &&\n        !equals(state.currentLineDash, lineDash)) ||\n      state.currentLineDashOffset != lineDashOffset ||\n      state.currentLineJoin != lineJoin ||\n      state.currentLineWidth != lineWidth ||\n      state.currentMiterLimit != miterLimit ||\n      state.currentStrokeOffset != strokeOffset\n    ) {\n      applyStroke.call(this, state);\n      state.currentStrokeStyle = strokeStyle;\n      state.currentLineCap = lineCap;\n      state.currentLineDash = lineDash;\n      state.currentLineDashOffset = lineDashOffset;\n      state.currentLineJoin = lineJoin;\n      state.currentLineWidth = lineWidth;\n      state.currentMiterLimit = miterLimit;\n      state.currentStrokeOffset = strokeOffset;\n    }\n  }\n\n  /**\n   * @param {import(\"../../Feature.js\").FeatureLike} feature Feature.\n   */\n  endGeometry(feature) {\n    this.beginGeometryInstruction1_[2] = this.instructions.length;\n    this.beginGeometryInstruction1_ = null;\n    this.beginGeometryInstruction2_[2] = this.hitDetectionInstructions.length;\n    this.beginGeometryInstruction2_ = null;\n    const endGeometryInstruction = [CanvasInstruction.END_GEOMETRY, feature];\n    this.instructions.push(endGeometryInstruction);\n    this.hitDetectionInstructions.push(endGeometryInstruction);\n  }\n\n  /**\n   * Get the buffered rendering extent.  Rendering will be clipped to the extent\n   * provided to the constructor.  To account for symbolizers that may intersect\n   * this extent, we calculate a buffered extent (e.g. based on stroke width).\n   * @return {import(\"../../extent.js\").Extent} The buffered rendering extent.\n   * @protected\n   */\n  getBufferedMaxExtent() {\n    if (!this.bufferedMaxExtent_) {\n      this.bufferedMaxExtent_ = clone(this.maxExtent);\n      if (this.maxLineWidth > 0) {\n        const width = (this.resolution * (this.maxLineWidth + 1)) / 2;\n        buffer(this.bufferedMaxExtent_, width, this.bufferedMaxExtent_);\n      }\n    }\n    return this.bufferedMaxExtent_;\n  }\n}\n\nexport default CanvasBuilder;\n", "/**\n * @module ol/render/canvas/ImageBuilder\n */\nimport {containsCoordinate} from '../../extent.js';\nimport CanvasBuilder from './Builder.js';\nimport CanvasInstruction from './Instruction.js';\n\nclass CanvasImageBuilder extends CanvasBuilder {\n  /**\n   * @param {number} tolerance Tolerance.\n   * @param {import(\"../../extent.js\").Extent} maxExtent Maximum extent.\n   * @param {number} resolution Resolution.\n   * @param {number} pixelRatio Pixel ratio.\n   */\n  constructor(tolerance, maxExtent, resolution, pixelRatio) {\n    super(tolerance, maxExtent, resolution, pixelRatio);\n\n    /**\n     * @private\n     * @type {import('../../DataTile.js').ImageLike}\n     */\n    this.hitDetectionImage_ = null;\n\n    /**\n     * @private\n     * @type {import('../../DataTile.js').ImageLike}\n     */\n    this.image_ = null;\n\n    /**\n     * @private\n     * @type {number|undefined}\n     */\n    this.imagePixelRatio_ = undefined;\n\n    /**\n     * @private\n     * @type {number|undefined}\n     */\n    this.anchorX_ = undefined;\n\n    /**\n     * @private\n     * @type {number|undefined}\n     */\n    this.anchorY_ = undefined;\n\n    /**\n     * @private\n     * @type {number|undefined}\n     */\n    this.height_ = undefined;\n\n    /**\n     * @private\n     * @type {number|undefined}\n     */\n    this.opacity_ = undefined;\n\n    /**\n     * @private\n     * @type {number|undefined}\n     */\n    this.originX_ = undefined;\n\n    /**\n     * @private\n     * @type {number|undefined}\n     */\n    this.originY_ = undefined;\n\n    /**\n     * @private\n     * @type {boolean|undefined}\n     */\n    this.rotateWithView_ = undefined;\n\n    /**\n     * @private\n     * @type {number|undefined}\n     */\n    this.rotation_ = undefined;\n\n    /**\n     * @private\n     * @type {import(\"../../size.js\").Size|undefined}\n     */\n    this.scale_ = undefined;\n\n    /**\n     * @private\n     * @type {number|undefined}\n     */\n    this.width_ = undefined;\n\n    /**\n     * @private\n     * @type {import('../../style/Style.js').DeclutterMode}\n     */\n    this.declutterMode_ = undefined;\n\n    /**\n     * Data shared with a text builder for combined decluttering.\n     * @private\n     * @type {import(\"../canvas.js\").DeclutterImageWithText}\n     */\n    this.declutterImageWithText_ = undefined;\n  }\n\n  /**\n   * @param {import(\"../../geom/Point.js\").default|import(\"../Feature.js\").default} pointGeometry Point geometry.\n   * @param {import(\"../../Feature.js\").FeatureLike} feature Feature.\n   * @param {number} [index] Render order index.\n   * @override\n   */\n  drawPoint(pointGeometry, feature, index) {\n    if (\n      !this.image_ ||\n      (this.maxExtent &&\n        !containsCoordinate(this.maxExtent, pointGeometry.getFlatCoordinates()))\n    ) {\n      return;\n    }\n    this.beginGeometry(pointGeometry, feature, index);\n    const flatCoordinates = pointGeometry.getFlatCoordinates();\n    const stride = pointGeometry.getStride();\n    const myBegin = this.coordinates.length;\n    const myEnd = this.appendFlatPointCoordinates(flatCoordinates, stride);\n    this.instructions.push([\n      CanvasInstruction.DRAW_IMAGE,\n      myBegin,\n      myEnd,\n      this.image_,\n      // Remaining arguments to DRAW_IMAGE are in alphabetical order\n      this.anchorX_ * this.imagePixelRatio_,\n      this.anchorY_ * this.imagePixelRatio_,\n      Math.ceil(this.height_ * this.imagePixelRatio_),\n      this.opacity_,\n      this.originX_ * this.imagePixelRatio_,\n      this.originY_ * this.imagePixelRatio_,\n      this.rotateWithView_,\n      this.rotation_,\n      [\n        (this.scale_[0] * this.pixelRatio) / this.imagePixelRatio_,\n        (this.scale_[1] * this.pixelRatio) / this.imagePixelRatio_,\n      ],\n      Math.ceil(this.width_ * this.imagePixelRatio_),\n      this.declutterMode_,\n      this.declutterImageWithText_,\n    ]);\n    this.hitDetectionInstructions.push([\n      CanvasInstruction.DRAW_IMAGE,\n      myBegin,\n      myEnd,\n      this.hitDetectionImage_,\n      // Remaining arguments to DRAW_IMAGE are in alphabetical order\n      this.anchorX_,\n      this.anchorY_,\n      this.height_,\n      1,\n      this.originX_,\n      this.originY_,\n      this.rotateWithView_,\n      this.rotation_,\n      this.scale_,\n      this.width_,\n      this.declutterMode_,\n      this.declutterImageWithText_,\n    ]);\n    this.endGeometry(feature);\n  }\n\n  /**\n   * @param {import(\"../../geom/MultiPoint.js\").default|import(\"../Feature.js\").default} multiPointGeometry MultiPoint geometry.\n   * @param {import(\"../../Feature.js\").FeatureLike} feature Feature.\n   * @param {number} [index] Render order index.\n   * @override\n   */\n  drawMultiPoint(multiPointGeometry, feature, index) {\n    if (!this.image_) {\n      return;\n    }\n    this.beginGeometry(multiPointGeometry, feature, index);\n    const flatCoordinates = multiPointGeometry.getFlatCoordinates();\n    const filteredFlatCoordinates = [];\n    for (\n      let i = 0, ii = flatCoordinates.length;\n      i < ii;\n      i += multiPointGeometry.getStride()\n    ) {\n      if (\n        !this.maxExtent ||\n        containsCoordinate(this.maxExtent, flatCoordinates.slice(i, i + 2))\n      ) {\n        filteredFlatCoordinates.push(\n          flatCoordinates[i],\n          flatCoordinates[i + 1],\n        );\n      }\n    }\n    const myBegin = this.coordinates.length;\n    const myEnd = this.appendFlatPointCoordinates(filteredFlatCoordinates, 2);\n    this.instructions.push([\n      CanvasInstruction.DRAW_IMAGE,\n      myBegin,\n      myEnd,\n      this.image_,\n      // Remaining arguments to DRAW_IMAGE are in alphabetical order\n      this.anchorX_ * this.imagePixelRatio_,\n      this.anchorY_ * this.imagePixelRatio_,\n      Math.ceil(this.height_ * this.imagePixelRatio_),\n      this.opacity_,\n      this.originX_ * this.imagePixelRatio_,\n      this.originY_ * this.imagePixelRatio_,\n      this.rotateWithView_,\n      this.rotation_,\n      [\n        (this.scale_[0] * this.pixelRatio) / this.imagePixelRatio_,\n        (this.scale_[1] * this.pixelRatio) / this.imagePixelRatio_,\n      ],\n      Math.ceil(this.width_ * this.imagePixelRatio_),\n      this.declutterMode_,\n      this.declutterImageWithText_,\n    ]);\n    this.hitDetectionInstructions.push([\n      CanvasInstruction.DRAW_IMAGE,\n      myBegin,\n      myEnd,\n      this.hitDetectionImage_,\n      // Remaining arguments to DRAW_IMAGE are in alphabetical order\n      this.anchorX_,\n      this.anchorY_,\n      this.height_,\n      1,\n      this.originX_,\n      this.originY_,\n      this.rotateWithView_,\n      this.rotation_,\n      this.scale_,\n      this.width_,\n      this.declutterMode_,\n      this.declutterImageWithText_,\n    ]);\n    this.endGeometry(feature);\n  }\n\n  /**\n   * @return {import(\"../canvas.js\").SerializableInstructions} the serializable instructions.\n   * @override\n   */\n  finish() {\n    this.reverseHitDetectionInstructions();\n    // FIXME this doesn't really protect us against further calls to draw*Geometry\n    this.anchorX_ = undefined;\n    this.anchorY_ = undefined;\n    this.hitDetectionImage_ = null;\n    this.image_ = null;\n    this.imagePixelRatio_ = undefined;\n    this.height_ = undefined;\n    this.scale_ = undefined;\n    this.opacity_ = undefined;\n    this.originX_ = undefined;\n    this.originY_ = undefined;\n    this.rotateWithView_ = undefined;\n    this.rotation_ = undefined;\n    this.width_ = undefined;\n    return super.finish();\n  }\n\n  /**\n   * @param {import(\"../../style/Image.js\").default} imageStyle Image style.\n   * @param {Object} [sharedData] Shared data.\n   * @override\n   */\n  setImageStyle(imageStyle, sharedData) {\n    const anchor = imageStyle.getAnchor();\n    const size = imageStyle.getSize();\n    const origin = imageStyle.getOrigin();\n    this.imagePixelRatio_ = imageStyle.getPixelRatio(this.pixelRatio);\n    this.anchorX_ = anchor[0];\n    this.anchorY_ = anchor[1];\n    this.hitDetectionImage_ = imageStyle.getHitDetectionImage();\n    this.image_ = imageStyle.getImage(this.pixelRatio);\n    this.height_ = size[1];\n    this.opacity_ = imageStyle.getOpacity();\n    this.originX_ = origin[0];\n    this.originY_ = origin[1];\n    this.rotateWithView_ = imageStyle.getRotateWithView();\n    this.rotation_ = imageStyle.getRotation();\n    this.scale_ = imageStyle.getScaleArray();\n    this.width_ = size[0];\n    this.declutterMode_ = imageStyle.getDeclutterMode();\n    this.declutterImageWithText_ = sharedData;\n  }\n}\n\nexport default CanvasImageBuilder;\n", "/**\n * @module ol/render/canvas/LineStringBuilder\n */\nimport {\n  defaultLineDash,\n  defaultLineDashOffset,\n  defaultStrokeStyle,\n} from '../canvas.js';\nimport CanvasBuilder from './Builder.js';\nimport CanvasInstruction, {\n  beginPathInstruction,\n  strokeInstruction,\n} from './Instruction.js';\n\nclass CanvasLineStringBuilder extends CanvasBuilder {\n  /**\n   * @param {number} tolerance Tolerance.\n   * @param {import(\"../../extent.js\").Extent} maxExtent Maximum extent.\n   * @param {number} resolution Resolution.\n   * @param {number} pixelRatio Pixel ratio.\n   */\n  constructor(tolerance, maxExtent, resolution, pixelRatio) {\n    super(tolerance, maxExtent, resolution, pixelRatio);\n  }\n\n  /**\n   * @param {Array<number>} flatCoordinates Flat coordinates.\n   * @param {number} offset Offset.\n   * @param {number} end End.\n   * @param {number} stride Stride.\n   * @param {number} [strokeOffset] Stroke Offset in pixels.\n   * @private\n   * @return {number} end.\n   */\n  drawFlatCoordinates_(flatCoordinates, offset, end, stride, strokeOffset) {\n    const myBegin = this.coordinates.length;\n    const myEnd = this.appendFlatLineCoordinates(\n      flatCoordinates,\n      offset,\n      end,\n      stride,\n      false,\n      false,\n    );\n    this.instructions.push([\n      CanvasInstruction.MOVE_TO_LINE_TO,\n      myBegin,\n      myEnd,\n      strokeOffset * this.pixelRatio,\n    ]);\n    this.hitDetectionInstructions.push([\n      CanvasInstruction.MOVE_TO_LINE_TO,\n      myBegin,\n      myEnd,\n      strokeOffset,\n    ]);\n    return end;\n  }\n\n  /**\n   * @param {import(\"../../geom/LineString.js\").default|import(\"../Feature.js\").default} lineStringGeometry Line string geometry.\n   * @param {import(\"../../Feature.js\").FeatureLike} feature Feature.\n   * @param {number} [index] Render order index.\n   * @override\n   */\n  drawLineString(lineStringGeometry, feature, index) {\n    const state = this.state;\n    const strokeStyle = state.strokeStyle;\n    const lineWidth = state.lineWidth;\n    const strokeOffset = state.strokeOffset;\n    if (strokeStyle === undefined || lineWidth === undefined) {\n      return;\n    }\n    this.updateStrokeStyle(state, this.applyStroke);\n    this.beginGeometry(lineStringGeometry, feature, index);\n    this.hitDetectionInstructions.push(\n      [\n        CanvasInstruction.SET_STROKE_STYLE,\n        defaultStrokeStyle,\n        state.lineWidth,\n        state.lineCap,\n        state.lineJoin,\n        state.miterLimit,\n        defaultLineDash,\n        defaultLineDashOffset,\n      ],\n      beginPathInstruction,\n    );\n    const flatCoordinates = lineStringGeometry.getFlatCoordinates();\n    const stride = lineStringGeometry.getStride();\n    this.drawFlatCoordinates_(\n      flatCoordinates,\n      0,\n      flatCoordinates.length,\n      stride,\n      strokeOffset,\n    );\n    this.hitDetectionInstructions.push(strokeInstruction);\n    this.endGeometry(feature);\n  }\n\n  /**\n   * @param {import(\"../../geom/MultiLineString.js\").default|import(\"../Feature.js\").default} multiLineStringGeometry MultiLineString geometry.\n   * @param {import(\"../../Feature.js\").FeatureLike} feature Feature.\n   * @param {number} [index] Render order index.\n   * @override\n   */\n  drawMultiLineString(multiLineStringGeometry, feature, index) {\n    const state = this.state;\n    const strokeStyle = state.strokeStyle;\n    const lineWidth = state.lineWidth;\n    const strokeOffset = state.strokeOffset;\n    if (strokeStyle === undefined || lineWidth === undefined) {\n      return;\n    }\n    this.updateStrokeStyle(state, this.applyStroke);\n    this.beginGeometry(multiLineStringGeometry, feature, index);\n    this.hitDetectionInstructions.push(\n      [\n        CanvasInstruction.SET_STROKE_STYLE,\n        defaultStrokeStyle,\n        state.lineWidth,\n        state.lineCap,\n        state.lineJoin,\n        state.miterLimit,\n        defaultLineDash,\n        defaultLineDashOffset,\n      ],\n      beginPathInstruction,\n    );\n    const ends = multiLineStringGeometry.getEnds();\n    const flatCoordinates = multiLineStringGeometry.getFlatCoordinates();\n    const stride = multiLineStringGeometry.getStride();\n    let offset = 0;\n    for (let i = 0, ii = ends.length; i < ii; ++i) {\n      offset = this.drawFlatCoordinates_(\n        flatCoordinates,\n        offset,\n        /** @type {number} */ (ends[i]),\n        stride,\n        strokeOffset,\n      );\n    }\n    this.hitDetectionInstructions.push(strokeInstruction);\n    this.endGeometry(feature);\n  }\n\n  /**\n   * @return {import(\"../canvas.js\").SerializableInstructions} the serializable instructions.\n   * @override\n   */\n  finish() {\n    const state = this.state;\n    if (\n      state.lastStroke != undefined &&\n      state.lastStroke != this.coordinates.length\n    ) {\n      this.instructions.push(strokeInstruction);\n    }\n    this.reverseHitDetectionInstructions();\n    this.state = null;\n    return super.finish();\n  }\n\n  /**\n   * @param {import(\"../canvas.js\").FillStrokeState} state State.\n   * @override\n   */\n  applyStroke(state) {\n    if (\n      state.lastStroke != undefined &&\n      state.lastStroke != this.coordinates.length\n    ) {\n      this.instructions.push(strokeInstruction);\n      state.lastStroke = this.coordinates.length;\n    }\n    state.lastStroke = 0;\n    super.applyStroke(state);\n    this.instructions.push(beginPathInstruction);\n  }\n}\n\nexport default CanvasLineStringBuilder;\n", "/**\n * @module ol/render/canvas/PolygonBuilder\n */\nimport {snap} from '../../geom/flat/simplify.js';\nimport {\n  defaultFillStyle,\n  defaultLineDash,\n  defaultLineDashOffset,\n  defaultStrokeStyle,\n} from '../canvas.js';\nimport CanvasBuilder from './Builder.js';\nimport CanvasInstruction, {\n  beginPathInstruction,\n  closePathInstruction,\n  fillInstruction,\n  strokeInstruction,\n} from './Instruction.js';\n\nclass CanvasPolygonBuilder extends CanvasBuilder {\n  /**\n   * @param {number} tolerance Tolerance.\n   * @param {import(\"../../extent.js\").Extent} maxExtent Maximum extent.\n   * @param {number} resolution Resolution.\n   * @param {number} pixelRatio Pixel ratio.\n   */\n  constructor(tolerance, maxExtent, resolution, pixelRatio) {\n    super(tolerance, maxExtent, resolution, pixelRatio);\n  }\n\n  /**\n   * @param {Array<number>} flatCoordinates Flat coordinates.\n   * @param {number} offset Offset.\n   * @param {Array<number>} ends Ends.\n   * @param {number} stride Stride.\n   * @param {number} [strokeOffset] Stroke Offset in pixels.\n   * @private\n   * @return {number} End.\n   */\n  drawFlatCoordinatess_(flatCoordinates, offset, ends, stride, strokeOffset) {\n    const state = this.state;\n    const fill = state.fillStyle !== undefined;\n    const stroke = state.strokeStyle !== undefined;\n    const numEnds = ends.length;\n    this.instructions.push(beginPathInstruction);\n    this.hitDetectionInstructions.push(beginPathInstruction);\n    for (let i = 0; i < numEnds; ++i) {\n      const end = ends[i];\n      const myBegin = this.coordinates.length;\n      const myEnd = this.appendFlatLineCoordinates(\n        flatCoordinates,\n        offset,\n        end,\n        stride,\n        true,\n        !stroke,\n      );\n      this.instructions.push([\n        CanvasInstruction.MOVE_TO_LINE_TO,\n        myBegin,\n        myEnd,\n        strokeOffset * this.pixelRatio,\n        true,\n      ]);\n      this.hitDetectionInstructions.push([\n        CanvasInstruction.MOVE_TO_LINE_TO,\n        myBegin,\n        myEnd,\n        strokeOffset,\n        true,\n      ]);\n      if (stroke) {\n        // Performance optimization: only call closePath() when we have a stroke.\n        // Otherwise the ring is closed already (see appendFlatLineCoordinates above).\n        this.instructions.push(closePathInstruction);\n        this.hitDetectionInstructions.push(closePathInstruction);\n      }\n      offset = end;\n    }\n    if (fill) {\n      this.instructions.push(fillInstruction);\n      this.hitDetectionInstructions.push(fillInstruction);\n    }\n    if (stroke) {\n      this.instructions.push(strokeInstruction);\n      this.hitDetectionInstructions.push(strokeInstruction);\n    }\n    return offset;\n  }\n\n  /**\n   * @param {import(\"../../geom/Circle.js\").default} circleGeometry Circle geometry.\n   * @param {import(\"../../Feature.js\").default} feature Feature.\n   * @param {number} [index] Render order index.\n   * @override\n   */\n  drawCircle(circleGeometry, feature, index) {\n    const state = this.state;\n    const fillStyle = state.fillStyle;\n    const strokeStyle = state.strokeStyle;\n    const strokeOffset = state.strokeOffset;\n    if (fillStyle === undefined && strokeStyle === undefined) {\n      return;\n    }\n\n    if (\n      this.handleStrokeOffset_(() =>\n        this.drawCircle(circleGeometry, feature, index),\n      )\n    ) {\n      return;\n    }\n    this.setFillStrokeStyles_();\n    this.beginGeometry(circleGeometry, feature, index);\n    if (state.fillStyle !== undefined) {\n      this.hitDetectionInstructions.push([\n        CanvasInstruction.SET_FILL_STYLE,\n        defaultFillStyle,\n      ]);\n    }\n    if (state.strokeStyle !== undefined) {\n      this.hitDetectionInstructions.push([\n        CanvasInstruction.SET_STROKE_STYLE,\n        defaultStrokeStyle,\n        state.lineWidth,\n        state.lineCap,\n        state.lineJoin,\n        state.miterLimit,\n        defaultLineDash,\n        defaultLineDashOffset,\n      ]);\n    }\n    const flatCoordinates = circleGeometry.getFlatCoordinates();\n    const stride = circleGeometry.getStride();\n    const myBegin = this.coordinates.length;\n    this.appendFlatLineCoordinates(\n      flatCoordinates,\n      0,\n      flatCoordinates.length,\n      stride,\n      false,\n      false,\n    );\n    const circleInstruction = [CanvasInstruction.CIRCLE, myBegin, strokeOffset];\n    this.instructions.push(beginPathInstruction, circleInstruction);\n    this.hitDetectionInstructions.push(beginPathInstruction, circleInstruction);\n    if (state.fillStyle !== undefined) {\n      this.instructions.push(fillInstruction);\n      this.hitDetectionInstructions.push(fillInstruction);\n    }\n    if (state.strokeStyle !== undefined) {\n      this.instructions.push(strokeInstruction);\n      this.hitDetectionInstructions.push(strokeInstruction);\n    }\n    this.endGeometry(feature);\n  }\n\n  /**\n   * @param {import(\"../../geom/Polygon.js\").default|import(\"../Feature.js\").default} polygonGeometry Polygon geometry.\n   * @param {import(\"../../Feature.js\").FeatureLike} feature Feature.\n   * @param {number} [index] Render order index.\n   * @override\n   */\n  drawPolygon(polygonGeometry, feature, index) {\n    const state = this.state;\n    const fillStyle = state.fillStyle;\n    const strokeStyle = state.strokeStyle;\n    const strokeOffset = state.strokeOffset;\n    if (fillStyle === undefined && strokeStyle === undefined) {\n      return;\n    }\n    if (\n      this.handleStrokeOffset_(() =>\n        this.drawPolygon(polygonGeometry, feature, index),\n      )\n    ) {\n      return;\n    }\n\n    this.setFillStrokeStyles_();\n    this.beginGeometry(polygonGeometry, feature, index);\n    if (state.fillStyle !== undefined) {\n      this.hitDetectionInstructions.push([\n        CanvasInstruction.SET_FILL_STYLE,\n        defaultFillStyle,\n      ]);\n    }\n    if (state.strokeStyle !== undefined) {\n      this.hitDetectionInstructions.push([\n        CanvasInstruction.SET_STROKE_STYLE,\n        defaultStrokeStyle,\n        state.lineWidth,\n        state.lineCap,\n        state.lineJoin,\n        state.miterLimit,\n        defaultLineDash,\n        defaultLineDashOffset,\n      ]);\n    }\n    const ends = polygonGeometry.getEnds();\n    const flatCoordinates = polygonGeometry.getOrientedFlatCoordinates();\n    const stride = polygonGeometry.getStride();\n    this.drawFlatCoordinatess_(\n      flatCoordinates,\n      0,\n      /** @type {Array<number>} */ (ends),\n      stride,\n      strokeOffset,\n    );\n    this.endGeometry(feature);\n  }\n\n  /**\n   * @param {import(\"../../geom/MultiPolygon.js\").default} multiPolygonGeometry MultiPolygon geometry.\n   * @param {import(\"../../Feature.js\").FeatureLike} feature Feature.\n   * @param {number} [index] Render order index.\n   * @override\n   */\n  drawMultiPolygon(multiPolygonGeometry, feature, index) {\n    const state = this.state;\n    const fillStyle = state.fillStyle;\n    const strokeStyle = state.strokeStyle;\n    const strokeOffset = state.strokeOffset;\n    if (fillStyle === undefined && strokeStyle === undefined) {\n      return;\n    }\n    if (\n      this.handleStrokeOffset_(() =>\n        this.drawMultiPolygon(multiPolygonGeometry, feature, index),\n      )\n    ) {\n      return;\n    }\n    this.setFillStrokeStyles_();\n    this.beginGeometry(multiPolygonGeometry, feature, index);\n    if (state.fillStyle !== undefined) {\n      this.hitDetectionInstructions.push([\n        CanvasInstruction.SET_FILL_STYLE,\n        defaultFillStyle,\n      ]);\n    }\n    if (state.strokeStyle !== undefined) {\n      this.hitDetectionInstructions.push([\n        CanvasInstruction.SET_STROKE_STYLE,\n        defaultStrokeStyle,\n        state.lineWidth,\n        state.lineCap,\n        state.lineJoin,\n        state.miterLimit,\n        defaultLineDash,\n        defaultLineDashOffset,\n      ]);\n    }\n    const endss = multiPolygonGeometry.getEndss();\n    const flatCoordinates = multiPolygonGeometry.getOrientedFlatCoordinates();\n    const stride = multiPolygonGeometry.getStride();\n    let offset = 0;\n    for (let i = 0, ii = endss.length; i < ii; ++i) {\n      offset = this.drawFlatCoordinatess_(\n        flatCoordinates,\n        offset,\n        endss[i],\n        stride,\n        strokeOffset,\n      );\n    }\n    this.endGeometry(feature);\n  }\n\n  /**\n   * @return {import(\"../canvas.js\").SerializableInstructions} the serializable instructions.\n   * @override\n   */\n  finish() {\n    this.reverseHitDetectionInstructions();\n    this.state = null;\n    // We want to preserve topology when drawing polygons.  Polygons are\n    // simplified using quantization and point elimination. However, we might\n    // have received a mix of quantized and non-quantized geometries, so ensure\n    // that all are quantized by quantizing all coordinates in the batch.\n    const tolerance = this.tolerance;\n    if (tolerance !== 0) {\n      const coordinates = this.coordinates;\n      for (let i = 0, ii = coordinates.length; i < ii; ++i) {\n        coordinates[i] = snap(coordinates[i], tolerance);\n      }\n    }\n    return super.finish();\n  }\n\n  /**\n   * @private\n   */\n  setFillStrokeStyles_() {\n    const state = this.state;\n    this.updateFillStyle(state, this.createFill);\n    this.updateStrokeStyle(state, this.applyStroke);\n  }\n\n  handleStrokeOffset_(drawGeometryCallback) {\n    const state = this.state;\n    const fillStyle = state.fillStyle;\n    const strokeStyle = state.strokeStyle;\n    const strokeOffset = state.strokeOffset;\n\n    // In case both fill style and stroke style are defined and the stroke style has an offset,\n    // the stroke and fill should be done in separate steps, because offset stroke shape will\n    // be different from the original shape used for the fill.\n    if (\n      Math.abs(strokeOffset) > 0 &&\n      fillStyle !== undefined &&\n      strokeStyle !== undefined\n    ) {\n      // First do only fill\n      state.strokeStyle = undefined;\n      state.strokeOffset = 0;\n      drawGeometryCallback();\n      // Now separately do the stroke\n      state.fillStyle = undefined;\n      state.strokeStyle = strokeStyle;\n      state.strokeOffset = strokeOffset;\n      drawGeometryCallback();\n      // Reset the state to the original\n      state.fillStyle = fillStyle;\n      return true;\n    }\n    return false;\n  }\n}\n\nexport default CanvasPolygonBuilder;\n", "import {lerp} from '../../math.js';\n\n/**\n * Creates chunks of equal length from a linestring\n * @param {number} chunkLength Length of each chunk.\n * @param {Array<number>} flatCoordinates Flat coordinates.\n * @param {number} offset Start offset of the `flatCoordinates`.\n * @param {number} end End offset of the `flatCoordinates`.\n * @param {number} stride Stride.\n * @return {Array<Array<number>>} Chunks of linestrings with stride 2.\n */\nexport function lineChunk(chunkLength, flatCoordinates, offset, end, stride) {\n  const chunks = [];\n  let cursor = offset;\n  let chunkM = 0;\n  let currentChunk = flatCoordinates.slice(offset, 2);\n  while (chunkM < chunkLength && cursor + stride < end) {\n    const [x1, y1] = currentChunk.slice(-2);\n    const x2 = flatCoordinates[cursor + stride];\n    const y2 = flatCoordinates[cursor + stride + 1];\n    const segmentLength = Math.sqrt(\n      (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1),\n    );\n    chunkM += segmentLength;\n    if (chunkM >= chunkLength) {\n      const m = (chunkLength - chunkM + segmentLength) / segmentLength;\n      const x = lerp(x1, x2, m);\n      const y = lerp(y1, y2, m);\n      currentChunk.push(x, y);\n      chunks.push(currentChunk);\n      currentChunk = [x, y];\n      if (chunkM == chunkLength) {\n        cursor += stride;\n      }\n      chunkM = 0;\n    } else if (chunkM < chunkLength) {\n      currentChunk.push(\n        flatCoordinates[cursor + stride],\n        flatCoordinates[cursor + stride + 1],\n      );\n      cursor += stride;\n    } else {\n      const missing = segmentLength - chunkM;\n      const x = lerp(x1, x2, missing / segmentLength);\n      const y = lerp(y1, y2, missing / segmentLength);\n      currentChunk.push(x, y);\n      chunks.push(currentChunk);\n      currentChunk = [x, y];\n      chunkM = 0;\n      cursor += stride;\n    }\n  }\n  if (chunkM > 0) {\n    chunks.push(currentChunk);\n  }\n  return chunks;\n}\n", "/**\n * @module ol/geom/flat/straightchunk\n */\n\n/**\n * @param {number} maxAngle Maximum acceptable angle delta between segments.\n * @param {Array<number>} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {number} end End.\n * @param {number} stride Stride.\n * @return {Array<number>} Start and end of the first suitable chunk of the\n * given `flatCoordinates`.\n */\nexport function matchingChunk(maxAngle, flatCoordinates, offset, end, stride) {\n  let chunkStart = offset;\n  let chunkEnd = offset;\n  let chunkM = 0;\n  let m = 0;\n  let start = offset;\n  let acos, i, m12, m23, x1, y1, x12, y12, x23, y23;\n  for (i = offset; i < end; i += stride) {\n    const x2 = flatCoordinates[i];\n    const y2 = flatCoordinates[i + 1];\n    if (x1 !== undefined) {\n      x23 = x2 - x1;\n      y23 = y2 - y1;\n      m23 = Math.sqrt(x23 * x23 + y23 * y23);\n      if (x12 !== undefined) {\n        m += m12;\n        acos = Math.acos((x12 * x23 + y12 * y23) / (m12 * m23));\n        if (acos > maxAngle) {\n          if (m > chunkM) {\n            chunkM = m;\n            chunkStart = start;\n            chunkEnd = i;\n          }\n          m = 0;\n          start = i - stride;\n        }\n      }\n      m12 = m23;\n      x12 = x23;\n      y12 = y23;\n    }\n    x1 = x2;\n    y1 = y2;\n  }\n  m += m23;\n  return m > chunkM ? [start, i] : [chunkStart, chunkEnd];\n}\n", "/**\n * @module ol/render/canvas/TextBuilder\n */\nimport {asColorLike} from '../../colorlike.js';\nimport {intersects} from '../../extent.js';\nimport {lineChunk} from '../../geom/flat/linechunk.js';\nimport {matchingChunk} from '../../geom/flat/straightchunk.js';\nimport {getUid} from '../../util.js';\nimport {\n  defaultFillStyle,\n  defaultFont,\n  defaultLineCap,\n  defaultLineDash,\n  defaultLineDashOffset,\n  defaultLineJoin,\n  defaultLineWidth,\n  defaultMiterLimit,\n  defaultPadding,\n  defaultStrokeStyle,\n  defaultTextAlign,\n  defaultTextBaseline,\n  registerFont,\n} from '../canvas.js';\nimport CanvasBuilder from './Builder.js';\nimport CanvasInstruction from './Instruction.js';\n/**\n * @const\n * @type {{left: 0, center: 0.5, right: 1, top: 0, middle: 0.5, hanging: 0.2, alphabetic: 0.8, ideographic: 0.8, bottom: 1}}\n */\nexport const TEXT_ALIGN = {\n  'left': 0,\n  'center': 0.5,\n  'right': 1,\n  'top': 0,\n  'middle': 0.5,\n  'hanging': 0.2,\n  'alphabetic': 0.8,\n  'ideographic': 0.8,\n  'bottom': 1,\n};\n\nclass CanvasTextBuilder extends CanvasBuilder {\n  /**\n   * @param {number} tolerance Tolerance.\n   * @param {import(\"../../extent.js\").Extent} maxExtent Maximum extent.\n   * @param {number} resolution Resolution.\n   * @param {number} pixelRatio Pixel ratio.\n   */\n  constructor(tolerance, maxExtent, resolution, pixelRatio) {\n    super(tolerance, maxExtent, resolution, pixelRatio);\n\n    /**\n     * @private\n     * @type {Array<HTMLCanvasElement>}\n     */\n    this.labels_ = null;\n\n    /**\n     * @private\n     * @type {string|Array<string>}\n     */\n    this.text_ = '';\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.textOffsetX_ = 0;\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.textOffsetY_ = 0;\n\n    /**\n     * @private\n     * @type {boolean|undefined}\n     */\n    this.textRotateWithView_ = undefined;\n\n    /**\n     * @private\n     * @type {boolean|undefined}\n     */\n    this.textKeepUpright_ = undefined;\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.textRotation_ = 0;\n\n    /**\n     * @private\n     * @type {?import(\"../canvas.js\").FillState}\n     */\n    this.textFillState_ = null;\n\n    /**\n     * @type {!Object<string, import(\"../canvas.js\").FillState>}\n     */\n    this.fillStates = {};\n    this.fillStates[defaultFillStyle] = {fillStyle: defaultFillStyle};\n\n    /**\n     * @private\n     * @type {?import(\"../canvas.js\").StrokeState}\n     */\n    this.textStrokeState_ = null;\n\n    /**\n     * @type {!Object<string, import(\"../canvas.js\").StrokeState>}\n     */\n    this.strokeStates = {};\n\n    /**\n     * @private\n     * @type {import(\"../canvas.js\").TextState}\n     */\n    this.textState_ = /** @type {import(\"../canvas.js\").TextState} */ ({});\n\n    /**\n     * @type {!Object<string, import(\"../canvas.js\").TextState>}\n     */\n    this.textStates = {};\n\n    /**\n     * @private\n     * @type {string}\n     */\n    this.textKey_ = '';\n\n    /**\n     * @private\n     * @type {string}\n     */\n    this.fillKey_ = '';\n\n    /**\n     * @private\n     * @type {string}\n     */\n    this.strokeKey_ = '';\n\n    /**\n     * @private\n     * @type {import('../../style/Style.js').DeclutterMode}\n     */\n    this.declutterMode_ = undefined;\n\n    /**\n     * Data shared with an image builder for combined decluttering.\n     * @private\n     * @type {import(\"../canvas.js\").DeclutterImageWithText}\n     */\n    this.declutterImageWithText_ = undefined;\n  }\n\n  /**\n   * @return {import(\"../canvas.js\").SerializableInstructions} the serializable instructions.\n   * @override\n   */\n  finish() {\n    const instructions = super.finish();\n    instructions.textStates = this.textStates;\n    instructions.fillStates = this.fillStates;\n    instructions.strokeStates = this.strokeStates;\n    return instructions;\n  }\n\n  /**\n   * @param {import(\"../../geom/SimpleGeometry.js\").default|import(\"../Feature.js\").default} geometry Geometry.\n   * @param {import(\"../../Feature.js\").FeatureLike} feature Feature.\n   * @param {number} [index] Render order index.\n   * @override\n   */\n  drawText(geometry, feature, index) {\n    const fillState = this.textFillState_;\n    const strokeState = this.textStrokeState_;\n    const textState = this.textState_;\n    if (this.text_ === '' || !textState || (!fillState && !strokeState)) {\n      return;\n    }\n\n    const coordinates = this.coordinates;\n    let begin = coordinates.length;\n\n    const geometryType = geometry.getType();\n    let flatCoordinates = null;\n    let stride = geometry.getStride();\n\n    if (\n      textState.placement === 'line' &&\n      (geometryType == 'LineString' ||\n        geometryType == 'MultiLineString' ||\n        geometryType == 'Polygon' ||\n        geometryType == 'MultiPolygon')\n    ) {\n      if (!intersects(this.maxExtent, geometry.getExtent())) {\n        return;\n      }\n      let ends;\n      flatCoordinates = geometry.getFlatCoordinates();\n      if (geometryType == 'LineString') {\n        ends = [flatCoordinates.length];\n      } else if (geometryType == 'MultiLineString') {\n        ends = /** @type {import(\"../../geom/MultiLineString.js\").default} */ (\n          geometry\n        ).getEnds();\n      } else if (geometryType == 'Polygon') {\n        ends = /** @type {import(\"../../geom/Polygon.js\").default} */ (geometry)\n          .getEnds()\n          .slice(0, 1);\n      } else if (geometryType == 'MultiPolygon') {\n        const endss =\n          /** @type {import(\"../../geom/MultiPolygon.js\").default} */ (\n            geometry\n          ).getEndss();\n        ends = [];\n        for (let i = 0, ii = endss.length; i < ii; ++i) {\n          ends.push(endss[i][0]);\n        }\n      }\n      this.beginGeometry(geometry, feature, index);\n      const repeat = textState.repeat;\n      const textAlign = repeat ? undefined : textState.textAlign;\n      // No `justify` support for line placement.\n      let flatOffset = 0;\n      for (let o = 0, oo = ends.length; o < oo; ++o) {\n        let chunks;\n        if (repeat) {\n          chunks = lineChunk(\n            repeat * this.resolution,\n            flatCoordinates,\n            flatOffset,\n            ends[o],\n            stride,\n          );\n        } else {\n          chunks = [flatCoordinates.slice(flatOffset, ends[o])];\n        }\n        for (let c = 0, cc = chunks.length; c < cc; ++c) {\n          const chunk = chunks[c];\n          let chunkBegin = 0;\n          let chunkEnd = chunk.length;\n          if (textAlign == undefined) {\n            const range = matchingChunk(\n              textState.maxAngle,\n              chunk,\n              0,\n              chunk.length,\n              2,\n            );\n            chunkBegin = range[0];\n            chunkEnd = range[1];\n          }\n          for (let i = chunkBegin; i < chunkEnd; i += stride) {\n            coordinates.push(chunk[i], chunk[i + 1]);\n          }\n          const end = coordinates.length;\n          flatOffset = ends[o];\n          this.drawChars_(begin, end);\n          begin = end;\n        }\n      }\n      this.endGeometry(feature);\n    } else {\n      let geometryWidths = textState.overflow ? null : [];\n      switch (geometryType) {\n        case 'Point':\n        case 'MultiPoint':\n          flatCoordinates =\n            /** @type {import(\"../../geom/MultiPoint.js\").default} */ (\n              geometry\n            ).getFlatCoordinates();\n          break;\n        case 'LineString':\n          flatCoordinates =\n            /** @type {import(\"../../geom/LineString.js\").default} */ (\n              geometry\n            ).getFlatMidpoint();\n          break;\n        case 'Circle':\n          flatCoordinates =\n            /** @type {import(\"../../geom/Circle.js\").default} */ (\n              geometry\n            ).getCenter();\n          break;\n        case 'MultiLineString':\n          flatCoordinates =\n            /** @type {import(\"../../geom/MultiLineString.js\").default} */ (\n              geometry\n            ).getFlatMidpoints();\n          stride = 2;\n          break;\n        case 'Polygon':\n          flatCoordinates =\n            /** @type {import(\"../../geom/Polygon.js\").default} */ (\n              geometry\n            ).getFlatInteriorPoint();\n          if (!textState.overflow) {\n            geometryWidths.push(flatCoordinates[2] / this.resolution);\n          }\n          stride = 3;\n          break;\n        case 'MultiPolygon':\n          const interiorPoints =\n            /** @type {import(\"../../geom/MultiPolygon.js\").default} */ (\n              geometry\n            ).getFlatInteriorPoints();\n          flatCoordinates = [];\n          for (let i = 0, ii = interiorPoints.length; i < ii; i += 3) {\n            if (!textState.overflow) {\n              geometryWidths.push(interiorPoints[i + 2] / this.resolution);\n            }\n            flatCoordinates.push(interiorPoints[i], interiorPoints[i + 1]);\n          }\n          if (flatCoordinates.length === 0) {\n            return;\n          }\n          stride = 2;\n          break;\n        default:\n      }\n      const end = this.appendFlatPointCoordinates(flatCoordinates, stride);\n      if (end === begin) {\n        return;\n      }\n      if (\n        geometryWidths &&\n        (end - begin) / 2 !== flatCoordinates.length / stride\n      ) {\n        let beg = begin / 2;\n        geometryWidths = geometryWidths.filter((w, i) => {\n          const keep =\n            coordinates[(beg + i) * 2] === flatCoordinates[i * stride] &&\n            coordinates[(beg + i) * 2 + 1] === flatCoordinates[i * stride + 1];\n          if (!keep) {\n            --beg;\n          }\n          return keep;\n        });\n      }\n\n      this.saveTextStates_();\n\n      const backgroundFill = textState.backgroundFill\n        ? this.createFill(this.fillStyleToState(textState.backgroundFill))\n        : null;\n      const backgroundStroke = textState.backgroundStroke\n        ? this.createStroke(this.strokeStyleToState(textState.backgroundStroke))\n        : null;\n\n      this.beginGeometry(geometry, feature, index);\n\n      // adjust padding for negative scale\n      let padding = textState.padding;\n      if (\n        padding != defaultPadding &&\n        (textState.scale[0] < 0 || textState.scale[1] < 0)\n      ) {\n        let p0 = textState.padding[0];\n        let p1 = textState.padding[1];\n        let p2 = textState.padding[2];\n        let p3 = textState.padding[3];\n        if (textState.scale[0] < 0) {\n          p1 = -p1;\n          p3 = -p3;\n        }\n        if (textState.scale[1] < 0) {\n          p0 = -p0;\n          p2 = -p2;\n        }\n        padding = [p0, p1, p2, p3];\n      }\n\n      // The image is unknown at this stage so we pass null; it will be computed at render time.\n      // For clarity, we pass NaN for offsetX, offsetY, width and height, which will be computed at\n      // render time.\n      const pixelRatio = this.pixelRatio;\n      this.instructions.push([\n        CanvasInstruction.DRAW_IMAGE,\n        begin,\n        end,\n        null,\n        NaN,\n        NaN,\n        NaN,\n        1,\n        0,\n        0,\n        this.textRotateWithView_,\n        this.textRotation_,\n        [1, 1],\n        NaN,\n        this.declutterMode_,\n        this.declutterImageWithText_,\n        padding == defaultPadding\n          ? defaultPadding\n          : padding.map(function (p) {\n              return p * pixelRatio;\n            }),\n        backgroundFill,\n        backgroundStroke,\n        this.text_,\n        this.textKey_,\n        this.strokeKey_,\n        this.fillKey_,\n        this.textOffsetX_,\n        this.textOffsetY_,\n        geometryWidths,\n      ]);\n      const scale = 1 / pixelRatio;\n      // Set default fill for hit detection background\n      const hitDetectionBackgroundFill = backgroundFill\n        ? backgroundFill.slice(0)\n        : null;\n      if (hitDetectionBackgroundFill) {\n        hitDetectionBackgroundFill[1] = defaultFillStyle;\n      }\n      this.hitDetectionInstructions.push([\n        CanvasInstruction.DRAW_IMAGE,\n        begin,\n        end,\n        null,\n        NaN,\n        NaN,\n        NaN,\n        1,\n        0,\n        0,\n        this.textRotateWithView_,\n        this.textRotation_,\n        [scale, scale],\n        NaN,\n        this.declutterMode_,\n        this.declutterImageWithText_,\n        padding,\n        hitDetectionBackgroundFill,\n        backgroundStroke,\n        this.text_,\n        this.textKey_,\n        this.strokeKey_,\n        this.fillKey_ ? defaultFillStyle : this.fillKey_,\n        this.textOffsetX_,\n        this.textOffsetY_,\n        geometryWidths,\n      ]);\n\n      this.endGeometry(feature);\n    }\n  }\n\n  /**\n   * @private\n   */\n  saveTextStates_() {\n    const strokeState = this.textStrokeState_;\n    const textState = this.textState_;\n    const fillState = this.textFillState_;\n\n    const strokeKey = this.strokeKey_;\n    if (strokeState) {\n      if (!(strokeKey in this.strokeStates)) {\n        this.strokeStates[strokeKey] = {\n          strokeStyle: strokeState.strokeStyle,\n          lineCap: strokeState.lineCap,\n          lineDashOffset: strokeState.lineDashOffset,\n          lineWidth: strokeState.lineWidth,\n          lineJoin: strokeState.lineJoin,\n          miterLimit: strokeState.miterLimit,\n          lineDash: strokeState.lineDash,\n        };\n      }\n    }\n    const textKey = this.textKey_;\n    if (!(textKey in this.textStates)) {\n      this.textStates[textKey] = {\n        font: textState.font,\n        textAlign: textState.textAlign || defaultTextAlign,\n        justify: textState.justify,\n        textBaseline: textState.textBaseline || defaultTextBaseline,\n        scale: textState.scale,\n      };\n    }\n    const fillKey = this.fillKey_;\n    if (fillState) {\n      if (!(fillKey in this.fillStates)) {\n        this.fillStates[fillKey] = {\n          fillStyle: fillState.fillStyle,\n        };\n      }\n    }\n  }\n\n  /**\n   * @private\n   * @param {number} begin Begin.\n   * @param {number} end End.\n   */\n  drawChars_(begin, end) {\n    const strokeState = this.textStrokeState_;\n    const textState = this.textState_;\n\n    const strokeKey = this.strokeKey_;\n    const textKey = this.textKey_;\n    const fillKey = this.fillKey_;\n    this.saveTextStates_();\n\n    const pixelRatio = this.pixelRatio;\n    const baseline = TEXT_ALIGN[textState.textBaseline];\n\n    const offsetY = this.textOffsetY_ * pixelRatio;\n    const text = this.text_;\n    const strokeWidth = strokeState\n      ? (strokeState.lineWidth * Math.abs(textState.scale[0])) / 2\n      : 0;\n\n    this.instructions.push([\n      CanvasInstruction.DRAW_CHARS,\n      begin,\n      end,\n      baseline,\n      textState.overflow,\n      fillKey,\n      textState.maxAngle,\n      pixelRatio,\n      offsetY,\n      strokeKey,\n      strokeWidth * pixelRatio,\n      text,\n      textKey,\n      1,\n      this.declutterMode_,\n      this.textKeepUpright_,\n    ]);\n    this.hitDetectionInstructions.push([\n      CanvasInstruction.DRAW_CHARS,\n      begin,\n      end,\n      baseline,\n      textState.overflow,\n      fillKey ? defaultFillStyle : fillKey,\n      textState.maxAngle,\n      pixelRatio,\n      offsetY,\n      strokeKey,\n      strokeWidth * pixelRatio,\n      text,\n      textKey,\n      1 / pixelRatio,\n      this.declutterMode_,\n      this.textKeepUpright_,\n    ]);\n  }\n\n  /**\n   * @param {import(\"../../style/Text.js\").default} textStyle Text style.\n   * @param {Object} [sharedData] Shared data.\n   * @override\n   */\n  setTextStyle(textStyle, sharedData) {\n    let textState, fillState, strokeState;\n    if (!textStyle) {\n      this.text_ = '';\n    } else {\n      const textFillStyle = textStyle.getFill();\n      if (!textFillStyle) {\n        fillState = null;\n        this.textFillState_ = fillState;\n      } else {\n        fillState = this.textFillState_;\n        if (!fillState) {\n          fillState = /** @type {import(\"../canvas.js\").FillState} */ ({});\n          this.textFillState_ = fillState;\n        }\n        fillState.fillStyle = asColorLike(\n          textFillStyle.getColor() || defaultFillStyle,\n        );\n      }\n\n      const textStrokeStyle = textStyle.getStroke();\n      if (!textStrokeStyle) {\n        strokeState = null;\n        this.textStrokeState_ = strokeState;\n      } else {\n        strokeState = this.textStrokeState_;\n        if (!strokeState) {\n          strokeState = /** @type {import(\"../canvas.js\").StrokeState} */ ({});\n          this.textStrokeState_ = strokeState;\n        }\n        const lineDash = textStrokeStyle.getLineDash();\n        const lineDashOffset = textStrokeStyle.getLineDashOffset();\n        const lineWidth = textStrokeStyle.getWidth();\n        const miterLimit = textStrokeStyle.getMiterLimit();\n        strokeState.lineCap = textStrokeStyle.getLineCap() || defaultLineCap;\n        strokeState.lineDash = lineDash ? lineDash.slice() : defaultLineDash;\n        strokeState.lineDashOffset =\n          lineDashOffset === undefined ? defaultLineDashOffset : lineDashOffset;\n        strokeState.lineJoin = textStrokeStyle.getLineJoin() || defaultLineJoin;\n        strokeState.lineWidth =\n          lineWidth === undefined ? defaultLineWidth : lineWidth;\n        strokeState.miterLimit =\n          miterLimit === undefined ? defaultMiterLimit : miterLimit;\n        strokeState.strokeStyle = asColorLike(\n          textStrokeStyle.getColor() || defaultStrokeStyle,\n        );\n      }\n\n      textState = this.textState_;\n      const font = textStyle.getFont() || defaultFont;\n      registerFont(font);\n      const textScale = textStyle.getScaleArray();\n      textState.overflow = textStyle.getOverflow();\n      textState.font = font;\n      textState.maxAngle = textStyle.getMaxAngle();\n      textState.placement = textStyle.getPlacement();\n      textState.textAlign = textStyle.getTextAlign();\n      textState.repeat = textStyle.getRepeat();\n      textState.justify = textStyle.getJustify();\n      textState.textBaseline =\n        textStyle.getTextBaseline() || defaultTextBaseline;\n      textState.backgroundFill = textStyle.getBackgroundFill();\n      textState.backgroundStroke = textStyle.getBackgroundStroke();\n      textState.padding = textStyle.getPadding() || defaultPadding;\n      textState.scale = textScale === undefined ? [1, 1] : textScale;\n\n      const textOffsetX = textStyle.getOffsetX();\n      const textOffsetY = textStyle.getOffsetY();\n      const textRotateWithView = textStyle.getRotateWithView();\n      const textKeepUpright = textStyle.getKeepUpright();\n      const textRotation = textStyle.getRotation();\n      this.text_ = textStyle.getText() || '';\n      this.textOffsetX_ = textOffsetX === undefined ? 0 : textOffsetX;\n      this.textOffsetY_ = textOffsetY === undefined ? 0 : textOffsetY;\n      this.textRotateWithView_ =\n        textRotateWithView === undefined ? false : textRotateWithView;\n      this.textKeepUpright_ =\n        textKeepUpright === undefined ? true : textKeepUpright;\n      this.textRotation_ = textRotation === undefined ? 0 : textRotation;\n\n      this.strokeKey_ = strokeState\n        ? (typeof strokeState.strokeStyle == 'string'\n            ? strokeState.strokeStyle\n            : getUid(strokeState.strokeStyle)) +\n          strokeState.lineCap +\n          strokeState.lineDashOffset +\n          '|' +\n          strokeState.lineWidth +\n          strokeState.lineJoin +\n          strokeState.miterLimit +\n          '[' +\n          strokeState.lineDash.join() +\n          ']'\n        : '';\n      this.textKey_ =\n        textState.font +\n        textState.scale +\n        (textState.textAlign || '?') +\n        (textState.repeat || '?') +\n        (textState.justify || '?') +\n        (textState.textBaseline || '?');\n      this.fillKey_ =\n        fillState && fillState.fillStyle\n          ? typeof fillState.fillStyle == 'string'\n            ? fillState.fillStyle\n            : '|' + getUid(fillState.fillStyle)\n          : '';\n    }\n    this.declutterMode_ = textStyle.getDeclutterMode();\n    this.declutterImageWithText_ = sharedData;\n  }\n}\n\nexport default CanvasTextBuilder;\n", "/**\n * @module ol/render/canvas/BuilderGroup\n */\n\nimport Builder from './Builder.js';\nimport ImageBuilder from './ImageBuilder.js';\nimport LineStringBuilder from './LineStringBuilder.js';\nimport PolygonBuilder from './PolygonBuilder.js';\nimport TextBuilder from './TextBuilder.js';\n\n/**\n * @type {Object<import(\"../canvas.js\").BuilderType, typeof Builder>}\n */\nconst BATCH_CONSTRUCTORS = {\n  'Circle': PolygonBuilder,\n  'Default': Builder,\n  'Image': ImageBuilder,\n  'LineString': LineStringBuilder,\n  'Polygon': PolygonBuilder,\n  'Text': TextBuilder,\n};\n\nclass BuilderGroup {\n  /**\n   * @param {number} tolerance Tolerance.\n   * @param {import(\"../../extent.js\").Extent} maxExtent Max extent.\n   * @param {number} resolution Resolution.\n   * @param {number} pixelRatio Pixel ratio.\n   */\n  constructor(tolerance, maxExtent, resolution, pixelRatio) {\n    /**\n     * @private\n     * @type {number}\n     */\n    this.tolerance_ = tolerance;\n\n    /**\n     * @private\n     * @type {import(\"../../extent.js\").Extent}\n     */\n    this.maxExtent_ = maxExtent;\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.pixelRatio_ = pixelRatio;\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.resolution_ = resolution;\n\n    /**\n     * @private\n     * @type {!Object<string, !Object<import(\"../canvas.js\").BuilderType, Builder>>}\n     */\n    this.buildersByZIndex_ = {};\n  }\n\n  /**\n   * @return {!Object<string, !Object<import(\"../canvas.js\").BuilderType, import(\"./Builder.js\").SerializableInstructions>>} The serializable instructions\n   */\n  finish() {\n    const builderInstructions = {};\n    for (const zKey in this.buildersByZIndex_) {\n      builderInstructions[zKey] = builderInstructions[zKey] || {};\n      const builders = this.buildersByZIndex_[zKey];\n      for (const builderKey in builders) {\n        const builderInstruction = builders[builderKey].finish();\n        builderInstructions[zKey][builderKey] = builderInstruction;\n      }\n    }\n    return builderInstructions;\n  }\n\n  /**\n   * @param {number|undefined} zIndex Z index.\n   * @param {import(\"../canvas.js\").BuilderType} builderType Replay type.\n   * @return {import(\"../VectorContext.js\").default} Replay.\n   */\n  getBuilder(zIndex, builderType) {\n    const zIndexKey = zIndex !== undefined ? zIndex.toString() : '0';\n    let replays = this.buildersByZIndex_[zIndexKey];\n    if (replays === undefined) {\n      replays = {};\n      this.buildersByZIndex_[zIndexKey] = replays;\n    }\n    let replay = replays[builderType];\n    if (replay === undefined) {\n      const Constructor = BATCH_CONSTRUCTORS[builderType];\n      replay = new Constructor(\n        this.tolerance_,\n        this.maxExtent_,\n        this.resolution_,\n        this.pixelRatio_,\n      );\n      replays[builderType] = replay;\n    }\n    return replay;\n  }\n}\n\nexport default BuilderGroup;\n", "import {angleBetween} from '../../coordinate.js';\n\n/**\n * Offsets a line string to the left / right along its segments direction.\n * Offset is applied to each segment of the line in the direciton of the segment normal (positive offset goes \"right\" relative to the line direction).\n * For very sharp angles between segments, the function falls back to offsetting along the segment normal direction to avoid excessively long miters.\n *\n * Coordinates and the offset should be in the same units \u2014 either pixels or the same spatial reference system as the input line coordinates.\n *\n * @param {Array<number>} flatCoordinates Flat coordinates.\n * @param {number} start Start index.\n * @param {number} end End index.\n * @param {number} stride Stride.\n * @param {number} offset Offset distance along the segment normal direction.\n *   Positive values offset to the right relative to the direction of the line.\n *   Negative values offset to the left.\n * @param {boolean} isClosedRing If coordinates build a closed circle (in this the first and the last coordinate offsets will consider previous / next ring coordinate)\n * @param {Array<number>} [dest] Destination coordinate array. If not provided a new one will be created\n * @param {number} [destinationStride] Stride of destination coordinates. If unspecified, assumed to be same as the source coordinates stride.\n * @return {Array<number>} Result flat coordinates of the offset line.\n */\nexport function offsetLineString(\n  flatCoordinates,\n  start,\n  end,\n  stride,\n  offset,\n  isClosedRing,\n  dest,\n  destinationStride,\n) {\n  dest = dest ?? [];\n  destinationStride = destinationStride ?? stride;\n\n  const secondPointX = flatCoordinates[start + stride];\n  const secondPointY = flatCoordinates[start + stride + 1];\n  const secondToLastPointX = flatCoordinates[end - 2 * stride];\n  const secondToLastPointY = flatCoordinates[end - 2 * stride + 1];\n  let x, y, prevX, prevY, nextX, nextY, offsetX, offsetY;\n\n  let i = 0;\n  for (let j = start; j < end; j += stride) {\n    // 1. Detect previous and next coordinates of a current vertex\n    prevX = x;\n    prevY = y;\n    nextX = undefined;\n    nextY = undefined;\n    if (j + stride < end) {\n      nextX = flatCoordinates[j + stride];\n      nextY = flatCoordinates[j + stride + 1];\n    }\n    // First coordinate of a closed ring -> previous coordinate is the second to last one\n    if (isClosedRing && j === start) {\n      prevX = secondToLastPointX;\n      prevY = secondToLastPointY;\n    }\n    // Last coordinate of a closed ring -> next coordinate is the second vertex of a line string (the last one is same as the first one for a closed ring)\n    if (isClosedRing && j === end - stride) {\n      nextX = secondPointX;\n      nextY = secondPointY;\n    }\n\n    // 2. Current vertex to offset\n    x = flatCoordinates[j];\n    y = flatCoordinates[j + 1];\n\n    // 3. Offset the vertex\n    [offsetX, offsetY] = offsetLineVertex(\n      x,\n      y,\n      prevX,\n      prevY,\n      nextX,\n      nextY,\n      offset,\n    );\n    dest[i++] = offsetX;\n    dest[i++] = offsetY;\n\n    // 4. Copy over other dimension values if any\n    for (let k = 2; k < destinationStride; k++) {\n      dest[i++] = flatCoordinates[j + k];\n    }\n  }\n\n  if (dest.length != i) {\n    dest.length = i;\n  }\n  return dest;\n}\n\n/**\n * Computes the offset of a single vertex of a line string.\n *\n * The function calculates a new vertex coordinate offset along the normal/miter direction of the line at this vertex.\n * Offset is applied along the segment normal (positive offset goes \"right\" relative to the line direction).\n * It handles first and last vertices (caps) as well as joins between two segments (mitering).\n * For very sharp angles, the function falls back to offsetting along the segment normal direction to avoid excessively long miters.\n *\n * Coordinates and the offset should be in the same units \u2014 either pixels or the same spatial reference system as the input line coordinates.\n *\n * @param {number} x Vertex x-coordinate.\n * @param {number} y Vertex y-coordinate.\n * @param {number|undefined} prevX Previous vertex x-coordinate.\n *   Pass undefined if computing the offset for the first vertex (no previous vertex).\n * @param {number|undefined} prevY Previous vertex y-coordinate.\n *   Pass undefined if computing the offset for the first vertex (no previous vertex).\n * @param {number|undefined} nextX Next vertex x-coordinate.\n *   Pass undefined if computing the offset for the last vertex (no next vertex).\n * @param {number|undefined} nextY Next vertex y-coordinate.\n *   Pass undefined if computing the offset for the last vertex (no next vertex).\n * @param {number} offset Offset distance along the segment normal direction.\n *   Positive values offset to the right relative to the direction from previous to next vertex.\n *   Negative values offset to the left.\n * @return {import(\"../../coordinate.js\").Coordinate} Offset vertex coordinate as `[x, y]`.\n */\nfunction offsetLineVertex(x, y, prevX, prevY, nextX, nextY, offset) {\n  // Compute segment direction\n  let nx, ny;\n  if (prevX !== undefined && prevY !== undefined) {\n    nx = x - prevX;\n    ny = y - prevY;\n  } else if (nextX !== undefined && nextY !== undefined) {\n    nx = nextX - x;\n    ny = nextY - y;\n  } else {\n    // no next, no previous point given -> just assume some default (horizontal) direction\n    nx = 1;\n    ny = 0;\n  }\n\n  // Normalize -> tangent\n  const len = Math.hypot(nx, ny);\n  const tx = nx / len;\n  const ty = ny / len;\n\n  // Rotate tangent 90\u00B0 -> normal\n  nx = -ty;\n  ny = tx;\n\n  // First / last vertex -> offset the point in the direction of the normal vector\n  if (prevX === undefined || prevY === undefined) {\n    return [x + nx * offset, y + ny * offset];\n  }\n  if (nextX === undefined || nextY === undefined) {\n    return [x + nx * offset, y + ny * offset];\n  }\n\n  // Compute join angle - angle between 2 segments of the vertex.\n  const joinAngle = angleBetween([x, y], [prevX, prevY], [nextX, nextY]);\n\n  // Avoid huge or infinite miter joins for very sharp angles, offset in the segment direction in this case.\n  if (Math.cos(joinAngle) > 0.998) {\n    return [x + tx * offset, y + ty * offset];\n  }\n\n  // Compute join offset direction.\n  // We rotate the normal vector by half of the join angle.\n  // This gives the direction of the miter at the vertex.\n  const cos = Math.cos(joinAngle / 2);\n  const sin = Math.sin(joinAngle / 2);\n\n  // Rotate the normal vector (nx, ny) by half of the join angle.\n  // bx/by = bisector direction before normalization\n  const bx = sin * nx + cos * ny;\n  const by = -cos * nx + sin * ny;\n\n  // Scale the bisector so that moving along it preserves the correct offset distance.\n  // Dividing by sin(half of angle) converts the bisector into the true miter vector.\n  // (This expands the miter for sharp angles and shortens it for wide ones.)\n  const dx = bx * (1 / sin);\n  const dy = by * (1 / sin);\n\n  // Offset final vertex along miter direction\n  return [x + dx * offset, y + dy * offset];\n}\n\n/**\n * Removes self-intersection loops (cycles) from an offset line.\n * When a polyline is offset, sharp turns can create self-intersecting loops.\n * This function detects those crossings and splices out the looped portions,\n * replacing them with the intersection point.\n *\n * @param {Array<number>} coords Flat offset coordinates (modified in-place).\n * @param {number} stride Coordinate stride (typically 2).\n * @return {Array<number>} The cleaned coordinate array.\n */\nexport function removeOffsetCycles(coords, stride) {\n  for (let i = 0, ii = coords.length - 2; i < ii; i += stride) {\n    for (let j = coords.length - 2 * stride; j > i + stride; j -= stride) {\n      const p1x = coords[i];\n      const p1y = coords[i + 1];\n      const p2x = coords[i + stride];\n      const p2y = coords[i + stride + 1];\n      const p3x = coords[j];\n      const p3y = coords[j + 1];\n      const p4x = coords[j + stride];\n      const p4y = coords[j + stride + 1];\n      const d = (p4y - p3y) * (p2x - p1x) - (p4x - p3x) * (p2y - p1y);\n      if (d === 0) {\n        continue;\n      }\n      const t = ((p4x - p3x) * (p1y - p3y) - (p4y - p3y) * (p1x - p3x)) / d;\n      const u = ((p2x - p1x) * (p1y - p3y) - (p2y - p1y) * (p1x - p3x)) / d;\n      if (t > 0 && t < 1 && u > 0 && u < 1) {\n        const ix = p1x + t * (p2x - p1x);\n        const iy = p1y + t * (p2y - p1y);\n        coords[i + stride] = ix;\n        coords[i + stride + 1] = iy;\n        coords.splice(i + 2 * stride, j - i - stride);\n        break;\n      }\n    }\n  }\n  return coords;\n}\n", "/**\n * @module ol/geom/flat/textpath\n */\nimport {lerp} from '../../math.js';\nimport {rotate} from './transform.js';\n\n/**\n * @param {Array<number>} flatCoordinates Path to put text on.\n * @param {number} offset Start offset of the `flatCoordinates`.\n * @param {number} end End offset of the `flatCoordinates`.\n * @param {number} stride Stride.\n * @param {string} text Text to place on the path.\n * @param {number} startM m along the path where the text starts.\n * @param {number} maxAngle Max angle between adjacent chars in radians.\n * @param {number} scale The product of the text scale and the device pixel ratio.\n * @param {function(string, string, Object<string, number>):number} measureAndCacheTextWidth Measure and cache text width.\n * @param {string} font The font.\n * @param {Object<string, number>} cache A cache of measured widths.\n * @param {number} rotation Rotation to apply to the flatCoordinates to determine whether text needs to be reversed.\n * @param {boolean} keepUpright Whether the text needs to be kept upright\n * @return {Array<Array<*>>|null} The result array (or null if `maxAngle` was\n * exceeded). Entries of the array are x, y, anchorX, angle, chunk.\n */\nexport function drawTextOnPath(\n  flatCoordinates,\n  offset,\n  end,\n  stride,\n  text,\n  startM,\n  maxAngle,\n  scale,\n  measureAndCacheTextWidth,\n  font,\n  cache,\n  rotation,\n  keepUpright = true,\n) {\n  let x2 = flatCoordinates[offset];\n  let y2 = flatCoordinates[offset + 1];\n  let x1 = 0;\n  let y1 = 0;\n  let segmentLength = 0;\n  let segmentM = 0;\n\n  function advance() {\n    x1 = x2;\n    y1 = y2;\n    offset += stride;\n    x2 = flatCoordinates[offset];\n    y2 = flatCoordinates[offset + 1];\n    segmentM += segmentLength;\n    segmentLength = Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));\n  }\n  do {\n    advance();\n  } while (offset < end - stride && segmentM + segmentLength < startM);\n\n  let interpolate =\n    segmentLength === 0 ? 0 : (startM - segmentM) / segmentLength;\n  const beginX = lerp(x1, x2, interpolate);\n  const beginY = lerp(y1, y2, interpolate);\n\n  const startOffset = offset - stride;\n  const startLength = segmentM;\n  const endM = startM + scale * measureAndCacheTextWidth(font, text, cache);\n  while (offset < end - stride && segmentM + segmentLength < endM) {\n    advance();\n  }\n  interpolate = segmentLength === 0 ? 0 : (endM - segmentM) / segmentLength;\n  const endX = lerp(x1, x2, interpolate);\n  const endY = lerp(y1, y2, interpolate);\n\n  // Keep text upright if the option is selected\n  let reverse = false;\n  if (keepUpright) {\n    if (rotation) {\n      const flat = [beginX, beginY, endX, endY];\n      rotate(flat, 0, 4, 2, rotation, flat, flat);\n      reverse = flat[0] > flat[2];\n    } else {\n      reverse = beginX > endX;\n    }\n  }\n\n  const PI = Math.PI;\n  const result = [];\n  const singleSegment = startOffset + stride === offset;\n\n  offset = startOffset;\n  segmentLength = 0;\n  segmentM = startLength;\n  x2 = flatCoordinates[offset];\n  y2 = flatCoordinates[offset + 1];\n\n  let previousAngle;\n  // All on the same segment\n  if (singleSegment) {\n    advance();\n\n    previousAngle = Math.atan2(y2 - y1, x2 - x1);\n    if (reverse) {\n      previousAngle += previousAngle > 0 ? -PI : PI;\n    }\n    const x = (endX + beginX) / 2;\n    const y = (endY + beginY) / 2;\n    result[0] = [x, y, (endM - startM) / 2, previousAngle, text];\n    return result;\n  }\n\n  // rendering across line segments\n  text = text.replace(/\\n/g, ' '); // ensure rendering in single-line as all calculations below don't handle multi-lines\n\n  for (let i = 0, ii = text.length; i < ii; ) {\n    advance();\n    let angle = Math.atan2(y2 - y1, x2 - x1);\n    if (reverse) {\n      angle += angle > 0 ? -PI : PI;\n    }\n    if (previousAngle !== undefined) {\n      let delta = angle - previousAngle;\n      delta += delta > PI ? -2 * PI : delta < -PI ? 2 * PI : 0;\n      if (Math.abs(delta) > maxAngle) {\n        return null;\n      }\n    }\n    previousAngle = angle;\n\n    const iStart = i;\n    let charLength = 0;\n    for (; i < ii; ++i) {\n      const index = reverse ? ii - i - 1 : i;\n      const len = scale * measureAndCacheTextWidth(font, text[index], cache);\n      if (\n        offset + stride < end &&\n        segmentM + segmentLength < startM + charLength + len / 2\n      ) {\n        break;\n      }\n      charLength += len;\n    }\n    if (i === iStart) {\n      continue;\n    }\n    const chars = reverse\n      ? text.substring(ii - iStart, ii - i)\n      : text.substring(iStart, i);\n    interpolate =\n      segmentLength === 0\n        ? 0\n        : (startM + charLength / 2 - segmentM) / segmentLength;\n    const x = lerp(x1, x2, interpolate);\n    const y = lerp(y1, y2, interpolate);\n    result.push([x, y, charLength / 2, angle, chars]);\n    startM += charLength;\n  }\n  return result;\n}\n", "/**\n * @module ol/render/canvas/Executor\n */\nimport {equals} from '../../array.js';\nimport {createEmpty, createOrUpdate, intersects} from '../../extent.js';\nimport {lineStringLength} from '../../geom/flat/length.js';\nimport {\n  offsetLineString,\n  removeOffsetCycles,\n} from '../../geom/flat/lineoffset.js';\nimport {drawTextOnPath} from '../../geom/flat/textpath.js';\nimport {transform2D} from '../../geom/flat/transform.js';\nimport {\n  apply as applyTransform,\n  compose as composeTransform,\n  create as createTransform,\n  setFromArray as transformSetFromArray,\n} from '../../transform.js';\nimport {\n  defaultPadding,\n  defaultTextAlign,\n  defaultTextBaseline,\n  drawImageOrLabel,\n  getTextDimensions,\n  measureAndCacheTextWidth,\n} from '../canvas.js';\nimport ZIndexContext from '../canvas/ZIndexContext.js';\nimport CanvasInstruction from './Instruction.js';\nimport {TEXT_ALIGN} from './TextBuilder.js';\n\n/**\n * @typedef {import('../../structs/RBush.js').Entry<import('../../Feature.js').FeatureLike>} DeclutterEntry\n */\n\n/**\n * @typedef {Object} ImageOrLabelDimensions\n * @property {number} drawImageX DrawImageX.\n * @property {number} drawImageY DrawImageY.\n * @property {number} drawImageW DrawImageW.\n * @property {number} drawImageH DrawImageH.\n * @property {number} originX OriginX.\n * @property {number} originY OriginY.\n * @property {Array<number>} scale Scale.\n * @property {DeclutterEntry} declutterBox DeclutterBox.\n * @property {import(\"../../transform.js\").Transform} canvasTransform CanvasTransform.\n */\n\n/**\n * @typedef {{0: CanvasRenderingContext2D|OffscreenCanvasRenderingContext2D, 1: import('../../size.js').Size, 2: import(\"../canvas.js\").Label|HTMLImageElement|HTMLCanvasElement|HTMLVideoElement, 3: ImageOrLabelDimensions, 4: number, 5: Array<*>, 6: Array<*>}} ReplayImageOrLabelArgs\n */\n\n/**\n * @template T\n * @typedef {function(import(\"../../Feature.js\").FeatureLike, import(\"../../geom/SimpleGeometry.js\").default, import(\"../../style/Style.js\").DeclutterMode): T} FeatureCallback\n */\n\n/**\n * @type {import(\"../../extent.js\").Extent}\n */\nconst tmpExtent = createEmpty();\n\n/** @type {import(\"../../coordinate.js\").Coordinate} */\nconst p1 = [];\n/** @type {import(\"../../coordinate.js\").Coordinate} */\nconst p2 = [];\n/** @type {import(\"../../coordinate.js\").Coordinate} */\nconst p3 = [];\n/** @type {import(\"../../coordinate.js\").Coordinate} */\nconst p4 = [];\n\n/**\n * @param {ReplayImageOrLabelArgs} replayImageOrLabelArgs Arguments to replayImageOrLabel\n * @return {DeclutterEntry} Declutter rbush entry.\n */\nfunction getDeclutterBox(replayImageOrLabelArgs) {\n  return replayImageOrLabelArgs[3].declutterBox;\n}\n\nconst rtlRegEx = new RegExp(\n  /* eslint-disable prettier/prettier */\n  '[' +\n    String.fromCharCode(0x00591) + '-' + String.fromCharCode(0x008ff) +\n    String.fromCharCode(0x0fb1d) + '-' + String.fromCharCode(0x0fdff) +\n    String.fromCharCode(0x0fe70) + '-' + String.fromCharCode(0x0fefc) +\n    String.fromCharCode(0x10800) + '-' + String.fromCharCode(0x10fff) +\n    String.fromCharCode(0x1e800) + '-' + String.fromCharCode(0x1efff) +\n  ']'\n  /* eslint-enable prettier/prettier */\n);\n\n/**\n * @param {string} text Text.\n * @param {CanvasTextAlign} align Alignment.\n * @return {number} Text alignment.\n */\nfunction horizontalTextAlign(text, align) {\n  if (align === 'start') {\n    align = rtlRegEx.test(text) ? 'right' : 'left';\n  } else if (align === 'end') {\n    align = rtlRegEx.test(text) ? 'left' : 'right';\n  }\n  return TEXT_ALIGN[align];\n}\n\n/**\n * @param {Array<string>} acc Accumulator.\n * @param {string} line Line of text.\n * @param {number} i Index\n * @return {Array<string>} Accumulator.\n */\nfunction createTextChunks(acc, line, i) {\n  if (i > 0) {\n    acc.push('\\n', '');\n  }\n  acc.push(line, '');\n  return acc;\n}\n\n/**\n * Converts rich text to plain text for text along lines.\n * @param {string} result The resulting plain text.\n * @param {string} part Item of the rich text array.\n * @param {number} index Index of the item in the rich text array.\n * @return {string} The resulting plain text.\n */\nfunction richTextToPlainText(result, part, index) {\n  if (index % 2 === 0) {\n    result += part;\n  }\n  return result;\n}\n\nclass Executor {\n  /**\n   * @param {number} resolution Resolution.\n   * @param {number} pixelRatio Pixel ratio.\n   * @param {boolean} overlaps The replay can have overlapping geometries.\n   * @param {import(\"../canvas.js\").SerializableInstructions} instructions The serializable instructions.\n   * @param {boolean} [deferredRendering] Enable deferred rendering.\n   */\n  constructor(\n    resolution,\n    pixelRatio,\n    overlaps,\n    instructions,\n    deferredRendering,\n  ) {\n    /**\n     * @protected\n     * @type {boolean}\n     */\n    this.overlaps = overlaps;\n\n    /**\n     * @protected\n     * @type {number}\n     */\n    this.pixelRatio = pixelRatio;\n\n    /**\n     * @protected\n     * @const\n     * @type {number}\n     */\n    this.resolution = resolution;\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.alignAndScaleFill_;\n\n    /**\n     * @protected\n     * @type {Array<*>}\n     */\n    this.instructions = instructions.instructions;\n\n    /**\n     * @protected\n     * @type {Array<number>}\n     */\n    this.coordinates = instructions.coordinates;\n\n    /**\n     * @private\n     * @type {!Object<number,import(\"../../coordinate.js\").Coordinate|Array<import(\"../../coordinate.js\").Coordinate>|Array<Array<import(\"../../coordinate.js\").Coordinate>>>}\n     */\n    this.coordinateCache_ = {};\n\n    /**\n     * @private\n     * @type {!import(\"../../transform.js\").Transform}\n     */\n    this.renderedTransform_ = createTransform();\n\n    /**\n     * @protected\n     * @type {Array<*>}\n     */\n    this.hitDetectionInstructions = instructions.hitDetectionInstructions;\n\n    /**\n     * @private\n     * @type {Array<number>}\n     */\n    this.pixelCoordinates_ = null;\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.viewRotation_ = 0;\n\n    /**\n     * @type {!Object<string, import(\"../canvas.js\").FillState>}\n     */\n    this.fillStates = instructions.fillStates || {};\n\n    /**\n     * @type {!Object<string, import(\"../canvas.js\").StrokeState>}\n     */\n    this.strokeStates = instructions.strokeStates || {};\n\n    /**\n     * @type {!Object<string, import(\"../canvas.js\").TextState>}\n     */\n    this.textStates = instructions.textStates || {};\n\n    /**\n     * @private\n     * @type {Object<string, Object<string, number>>}\n     */\n    this.widths_ = {};\n\n    /**\n     * @private\n     * @type {Object<string, import(\"../canvas.js\").Label>}\n     */\n    this.labels_ = {};\n\n    /**\n     * @private\n     * @type {import(\"../canvas/ZIndexContext.js\").default}\n     */\n    this.zIndexContext_ = deferredRendering ? new ZIndexContext() : null;\n  }\n\n  /**\n   * @return {ZIndexContext} ZIndex context.\n   */\n  getZIndexContext() {\n    return this.zIndexContext_;\n  }\n\n  /**\n   * @param {string|Array<string>} text Text.\n   * @param {string} textKey Text style key.\n   * @param {string} fillKey Fill style key.\n   * @param {string} strokeKey Stroke style key.\n   * @return {import(\"../canvas.js\").Label} Label.\n   */\n  createLabel(text, textKey, fillKey, strokeKey) {\n    const key = text + textKey + fillKey + strokeKey;\n    if (this.labels_[key]) {\n      return this.labels_[key];\n    }\n    const strokeState = strokeKey ? this.strokeStates[strokeKey] : null;\n    const fillState = fillKey ? this.fillStates[fillKey] : null;\n    const textState = this.textStates[textKey];\n    const pixelRatio = this.pixelRatio;\n    const scale = [\n      textState.scale[0] * pixelRatio,\n      textState.scale[1] * pixelRatio,\n    ];\n    const align = textState.justify\n      ? TEXT_ALIGN[textState.justify]\n      : horizontalTextAlign(\n          Array.isArray(text) ? text[0] : text,\n          textState.textAlign || defaultTextAlign,\n        );\n    const strokeWidth =\n      strokeKey && strokeState.lineWidth ? strokeState.lineWidth : 0;\n\n    const chunks = Array.isArray(text)\n      ? text\n      : String(text).split('\\n').reduce(createTextChunks, []);\n\n    const {width, height, widths, heights, lineWidths} = getTextDimensions(\n      textState,\n      chunks,\n    );\n    const renderWidth = width + strokeWidth;\n    const contextInstructions = [];\n    // make canvas 2 pixels wider to account for italic text width measurement errors\n    const w = (renderWidth + 2) * scale[0];\n    const h = (height + strokeWidth) * scale[1];\n    /** @type {import(\"../canvas.js\").Label} */\n    const label = {\n      width: w < 0 ? Math.floor(w) : Math.ceil(w),\n      height: h < 0 ? Math.floor(h) : Math.ceil(h),\n      contextInstructions: contextInstructions,\n    };\n    if (scale[0] != 1 || scale[1] != 1) {\n      contextInstructions.push('scale', scale);\n    }\n    if (strokeKey) {\n      contextInstructions.push('strokeStyle', strokeState.strokeStyle);\n      contextInstructions.push('lineWidth', strokeWidth);\n      contextInstructions.push('lineCap', strokeState.lineCap);\n      contextInstructions.push('lineJoin', strokeState.lineJoin);\n      contextInstructions.push('miterLimit', strokeState.miterLimit);\n      contextInstructions.push('setLineDash', [strokeState.lineDash]);\n      contextInstructions.push('lineDashOffset', strokeState.lineDashOffset);\n    }\n    if (fillKey) {\n      contextInstructions.push('fillStyle', fillState.fillStyle);\n    }\n    contextInstructions.push('textBaseline', 'middle');\n    contextInstructions.push('textAlign', 'center');\n    const leftRight = 0.5 - align;\n    let x = align * renderWidth + leftRight * strokeWidth;\n    const strokeInstructions = [];\n    const fillInstructions = [];\n    let lineHeight = 0;\n    let lineOffset = 0;\n    let widthHeightIndex = 0;\n    let lineWidthIndex = 0;\n    let previousFont;\n    for (let i = 0, ii = chunks.length; i < ii; i += 2) {\n      const text = chunks[i];\n      if (text === '\\n') {\n        lineOffset += lineHeight;\n        lineHeight = 0;\n        x = align * renderWidth + leftRight * strokeWidth;\n        ++lineWidthIndex;\n        continue;\n      }\n      const font = chunks[i + 1] || textState.font;\n      if (font !== previousFont) {\n        if (strokeKey) {\n          strokeInstructions.push('font', font);\n        }\n        if (fillKey) {\n          fillInstructions.push('font', font);\n        }\n        previousFont = font;\n      }\n      lineHeight = Math.max(lineHeight, heights[widthHeightIndex]);\n      const fillStrokeArgs = [\n        text,\n        x +\n          leftRight * widths[widthHeightIndex] +\n          align * (widths[widthHeightIndex] - lineWidths[lineWidthIndex]),\n        0.5 * (strokeWidth + lineHeight) + lineOffset,\n      ];\n      x += widths[widthHeightIndex];\n      if (strokeKey) {\n        strokeInstructions.push('strokeText', fillStrokeArgs);\n      }\n      if (fillKey) {\n        fillInstructions.push('fillText', fillStrokeArgs);\n      }\n      ++widthHeightIndex;\n    }\n    Array.prototype.push.apply(contextInstructions, strokeInstructions);\n    Array.prototype.push.apply(contextInstructions, fillInstructions);\n    this.labels_[key] = label;\n    return label;\n  }\n\n  /**\n   * @param {CanvasRenderingContext2D} context Context.\n   * @param {import(\"../../coordinate.js\").Coordinate} p1 1st point of the background box.\n   * @param {import(\"../../coordinate.js\").Coordinate} p2 2nd point of the background box.\n   * @param {import(\"../../coordinate.js\").Coordinate} p3 3rd point of the background box.\n   * @param {import(\"../../coordinate.js\").Coordinate} p4 4th point of the background box.\n   * @param {Array<*>} fillInstruction Fill instruction.\n   * @param {Array<*>} strokeInstruction Stroke instruction.\n   */\n  replayTextBackground_(\n    context,\n    p1,\n    p2,\n    p3,\n    p4,\n    fillInstruction,\n    strokeInstruction,\n  ) {\n    context.beginPath();\n    context.moveTo.apply(context, p1);\n    context.lineTo.apply(context, p2);\n    context.lineTo.apply(context, p3);\n    context.lineTo.apply(context, p4);\n    context.lineTo.apply(context, p1);\n    if (fillInstruction) {\n      this.alignAndScaleFill_ = /** @type {number} */ (fillInstruction[2]);\n      context.fillStyle = /** @type {string} */ (fillInstruction[1]);\n      this.fill_(context);\n    }\n    if (strokeInstruction) {\n      this.setStrokeStyle_(\n        context,\n        /** @type {Array<*>} */ (strokeInstruction),\n      );\n      context.stroke();\n    }\n  }\n\n  /**\n   * @private\n   * @param {number} sheetWidth Width of the sprite sheet.\n   * @param {number} sheetHeight Height of the sprite sheet.\n   * @param {number} centerX X.\n   * @param {number} centerY Y.\n   * @param {number} width Width.\n   * @param {number} height Height.\n   * @param {number} anchorX Anchor X.\n   * @param {number} anchorY Anchor Y.\n   * @param {number} originX Origin X.\n   * @param {number} originY Origin Y.\n   * @param {number} rotation Rotation.\n   * @param {import(\"../../size.js\").Size} scale Scale.\n   * @param {boolean} snapToPixel Snap to pixel.\n   * @param {Array<number>} padding Padding.\n   * @param {boolean} fillStroke Background fill or stroke.\n   * @param {import(\"../../Feature.js\").FeatureLike} feature Feature.\n   * @return {ImageOrLabelDimensions} Dimensions for positioning and decluttering the image or label.\n   */\n  calculateImageOrLabelDimensions_(\n    sheetWidth,\n    sheetHeight,\n    centerX,\n    centerY,\n    width,\n    height,\n    anchorX,\n    anchorY,\n    originX,\n    originY,\n    rotation,\n    scale,\n    snapToPixel,\n    padding,\n    fillStroke,\n    feature,\n  ) {\n    anchorX *= scale[0];\n    anchorY *= scale[1];\n    let x = centerX - anchorX;\n    let y = centerY - anchorY;\n\n    const w = width + originX > sheetWidth ? sheetWidth - originX : width;\n    const h = height + originY > sheetHeight ? sheetHeight - originY : height;\n    const boxW = padding[3] + w * scale[0] + padding[1];\n    const boxH = padding[0] + h * scale[1] + padding[2];\n    const boxX = x - padding[3];\n    const boxY = y - padding[0];\n\n    if (fillStroke || rotation !== 0) {\n      p1[0] = boxX;\n      p4[0] = boxX;\n      p1[1] = boxY;\n      p2[1] = boxY;\n      p2[0] = boxX + boxW;\n      p3[0] = p2[0];\n      p3[1] = boxY + boxH;\n      p4[1] = p3[1];\n    }\n\n    let transform;\n    if (rotation !== 0) {\n      transform = composeTransform(\n        createTransform(),\n        centerX,\n        centerY,\n        1,\n        1,\n        rotation,\n        -centerX,\n        -centerY,\n      );\n\n      applyTransform(transform, p1);\n      applyTransform(transform, p2);\n      applyTransform(transform, p3);\n      applyTransform(transform, p4);\n      createOrUpdate(\n        Math.min(p1[0], p2[0], p3[0], p4[0]),\n        Math.min(p1[1], p2[1], p3[1], p4[1]),\n        Math.max(p1[0], p2[0], p3[0], p4[0]),\n        Math.max(p1[1], p2[1], p3[1], p4[1]),\n        tmpExtent,\n      );\n    } else {\n      createOrUpdate(\n        Math.min(boxX, boxX + boxW),\n        Math.min(boxY, boxY + boxH),\n        Math.max(boxX, boxX + boxW),\n        Math.max(boxY, boxY + boxH),\n        tmpExtent,\n      );\n    }\n    if (snapToPixel) {\n      x = Math.round(x);\n      y = Math.round(y);\n    }\n    return {\n      drawImageX: x,\n      drawImageY: y,\n      drawImageW: w,\n      drawImageH: h,\n      originX: originX,\n      originY: originY,\n      declutterBox: {\n        minX: tmpExtent[0],\n        minY: tmpExtent[1],\n        maxX: tmpExtent[2],\n        maxY: tmpExtent[3],\n        value: feature,\n      },\n      canvasTransform: transform,\n      scale: scale,\n    };\n  }\n\n  /**\n   * @private\n   * @param {CanvasRenderingContext2D} context Context.\n   * @param {import('../../size.js').Size} scaledCanvasSize Scaled canvas size.\n   * @param {import(\"../canvas.js\").Label|HTMLImageElement|HTMLCanvasElement|HTMLVideoElement} imageOrLabel Image.\n   * @param {ImageOrLabelDimensions} dimensions Dimensions.\n   * @param {number} opacity Opacity.\n   * @param {Array<*>} fillInstruction Fill instruction.\n   * @param {Array<*>} strokeInstruction Stroke instruction.\n   * @return {boolean} The image or label was rendered.\n   */\n  replayImageOrLabel_(\n    context,\n    scaledCanvasSize,\n    imageOrLabel,\n    dimensions,\n    opacity,\n    fillInstruction,\n    strokeInstruction,\n  ) {\n    const fillStroke = !!(fillInstruction || strokeInstruction);\n\n    const box = dimensions.declutterBox;\n    const strokePadding = strokeInstruction\n      ? (strokeInstruction[2] * dimensions.scale[0]) / 2\n      : 0;\n    const intersects =\n      box.minX - strokePadding <= scaledCanvasSize[0] &&\n      box.maxX + strokePadding >= 0 &&\n      box.minY - strokePadding <= scaledCanvasSize[1] &&\n      box.maxY + strokePadding >= 0;\n\n    if (intersects) {\n      if (fillStroke) {\n        this.replayTextBackground_(\n          context,\n          p1,\n          p2,\n          p3,\n          p4,\n          /** @type {Array<*>} */ (fillInstruction),\n          /** @type {Array<*>} */ (strokeInstruction),\n        );\n      }\n      drawImageOrLabel(\n        context,\n        dimensions.canvasTransform,\n        opacity,\n        imageOrLabel,\n        dimensions.originX,\n        dimensions.originY,\n        dimensions.drawImageW,\n        dimensions.drawImageH,\n        dimensions.drawImageX,\n        dimensions.drawImageY,\n        dimensions.scale,\n      );\n    }\n    return true;\n  }\n\n  /**\n   * @private\n   * @param {CanvasRenderingContext2D|OffscreenCanvasRenderingContext2D} context Context.\n   */\n  fill_(context) {\n    const alignAndScale = this.alignAndScaleFill_;\n    if (alignAndScale) {\n      const origin = applyTransform(this.renderedTransform_, [0, 0]);\n      const repeatSize = 512 * this.pixelRatio;\n      context.save();\n      context.translate(origin[0] % repeatSize, origin[1] % repeatSize);\n      if (alignAndScale !== 1) {\n        context.scale(alignAndScale, alignAndScale);\n      }\n    }\n    context.fill();\n    if (alignAndScale) {\n      context.restore();\n    }\n  }\n\n  /**\n   * @private\n   * @param {CanvasRenderingContext2D|OffscreenCanvasRenderingContext2D} context Context.\n   * @param {Array<*>} instruction Instruction.\n   */\n  setStrokeStyle_(context, instruction) {\n    context.strokeStyle =\n      /** @type {import(\"../../colorlike.js\").ColorLike} */ (instruction[1]);\n    if (!instruction[1]) {\n      return;\n    }\n    context.lineWidth = /** @type {number} */ (instruction[2]);\n    context.lineCap = /** @type {CanvasLineCap} */ (instruction[3]);\n    context.lineJoin = /** @type {CanvasLineJoin} */ (instruction[4]);\n    context.miterLimit = /** @type {number} */ (instruction[5]);\n    context.lineDashOffset = /** @type {number} */ (instruction[7]);\n    context.setLineDash(/** @type {Array<number>} */ (instruction[6]));\n  }\n\n  /**\n   * @private\n   * @param {string|Array<string>} text The text to draw.\n   * @param {string} textKey The key of the text state.\n   * @param {string} strokeKey The key for the stroke state.\n   * @param {string} fillKey The key for the fill state.\n   * @return {{label: import(\"../canvas.js\").Label, anchorX: number, anchorY: number}} The text image and its anchor.\n   */\n  drawLabelWithPointPlacement_(text, textKey, strokeKey, fillKey) {\n    const textState = this.textStates[textKey];\n\n    const label = this.createLabel(text, textKey, fillKey, strokeKey);\n\n    const strokeState = this.strokeStates[strokeKey];\n    const pixelRatio = this.pixelRatio;\n    const align = horizontalTextAlign(\n      Array.isArray(text) ? text[0] : text,\n      textState.textAlign || defaultTextAlign,\n    );\n    const baseline = TEXT_ALIGN[textState.textBaseline || defaultTextBaseline];\n    const strokeWidth =\n      strokeState && strokeState.lineWidth ? strokeState.lineWidth : 0;\n\n    // Remove the 2 pixels we added in createLabel() for the anchor\n    const width = label.width / pixelRatio - 2 * textState.scale[0];\n    const anchorX = align * width + 2 * (0.5 - align) * strokeWidth;\n    const anchorY =\n      (baseline * label.height) / pixelRatio +\n      2 * (0.5 - baseline) * strokeWidth;\n\n    return {\n      label: label,\n      anchorX: anchorX,\n      anchorY: anchorY,\n    };\n  }\n\n  /**\n   * @private\n   * @param {CanvasRenderingContext2D|OffscreenCanvasRenderingContext2D} context Context.\n   * @param {import('../../size.js').Size} scaledCanvasSize Scaled canvas size\n   * @param {import(\"../../transform.js\").Transform} transform Transform.\n   * @param {Array<*>} instructions Instructions array.\n   * @param {boolean} snapToPixel Snap point symbols and text to integer pixels.\n   * @param {FeatureCallback<T>} [featureCallback] Feature callback.\n   * @param {import(\"../../extent.js\").Extent} [hitExtent] Only check\n   *     features that intersect this extent.\n   * @param {import(\"rbush\").default<DeclutterEntry>} [declutterTree] Declutter tree.\n   * @return {T|undefined} Callback result.\n   * @template T\n   */\n  execute_(\n    context,\n    scaledCanvasSize,\n    transform,\n    instructions,\n    snapToPixel,\n    featureCallback,\n    hitExtent,\n    declutterTree,\n  ) {\n    const zIndexContext = this.zIndexContext_;\n    /** @type {Array<number>} */\n    let pixelCoordinates;\n    if (this.pixelCoordinates_ && equals(transform, this.renderedTransform_)) {\n      pixelCoordinates = this.pixelCoordinates_;\n    } else {\n      if (!this.pixelCoordinates_) {\n        this.pixelCoordinates_ = [];\n      }\n      pixelCoordinates = transform2D(\n        this.coordinates,\n        0,\n        this.coordinates.length,\n        2,\n        transform,\n        this.pixelCoordinates_,\n      );\n      transformSetFromArray(this.renderedTransform_, transform);\n    }\n    let i = 0; // instruction index\n    const ii = instructions.length; // end of instructions\n    let d = 0; // data index\n    let dd; // end of per-instruction data\n    const offsetCoords = [];\n    let anchorX,\n      anchorY,\n      lineOffsetPx,\n      /** @type {import('../../style/Style.js').DeclutterMode} */\n      declutterMode,\n      prevX,\n      prevY,\n      roundX,\n      roundY,\n      image,\n      text,\n      textKey,\n      strokeKey,\n      fillKey;\n    let pendingFill = 0;\n    let pendingStroke = 0;\n    const coordinateCache = this.coordinateCache_;\n    const viewRotation = this.viewRotation_;\n    const viewRotationFromTransform =\n      Math.round(Math.atan2(-transform[1], transform[0]) * 1e12) / 1e12;\n\n    const state = /** @type {import(\"../../render.js\").State} */ ({\n      context: context,\n      pixelRatio: this.pixelRatio,\n      resolution: this.resolution,\n      rotation: viewRotation,\n    });\n\n    // When the batch size gets too big, performance decreases. 200 is a good\n    // balance between batch size and number of fill/stroke instructions.\n    const batchSize =\n      this.instructions != instructions || this.overlaps ? 0 : 200;\n    let /** @type {import(\"../../Feature.js\").FeatureLike} */ feature;\n    let x, y, currentGeometry;\n    while (i < ii) {\n      const instruction = instructions[i];\n      const type = /** @type {import(\"./Instruction.js\").default} */ (\n        instruction[0]\n      );\n      switch (type) {\n        case CanvasInstruction.BEGIN_GEOMETRY:\n          feature = /** @type {import(\"../../Feature.js\").FeatureLike} */ (\n            instruction[1]\n          );\n          currentGeometry = instruction[3];\n          if (!feature.getGeometry()) {\n            i = /** @type {number} */ (instruction[2]);\n          } else if (\n            hitExtent !== undefined &&\n            !intersects(hitExtent, currentGeometry.getExtent())\n          ) {\n            i = /** @type {number} */ (instruction[2]) + 1;\n          } else {\n            ++i;\n          }\n          if (zIndexContext) {\n            zIndexContext.zIndex = instruction[4];\n          }\n          break;\n        case CanvasInstruction.BEGIN_PATH:\n          if (pendingFill > batchSize) {\n            this.fill_(context);\n            pendingFill = 0;\n          }\n          if (pendingStroke > batchSize) {\n            context.stroke();\n            pendingStroke = 0;\n          }\n          if (!pendingFill && !pendingStroke) {\n            context.beginPath();\n            prevX = NaN;\n            prevY = NaN;\n          }\n          ++i;\n          break;\n        case CanvasInstruction.CIRCLE:\n          d = /** @type {number} */ (instruction[1]);\n          lineOffsetPx = /** @type {number} */ instruction[2] ?? 0;\n          const x1 = pixelCoordinates[d];\n          const y1 = pixelCoordinates[d + 1];\n          const x2 = pixelCoordinates[d + 2] - lineOffsetPx;\n          const y2 = pixelCoordinates[d + 3] - lineOffsetPx;\n          const dx = x2 - x1;\n          const dy = y2 - y1;\n          const r = Math.sqrt(dx * dx + dy * dy);\n          context.moveTo(x1 + r, y1);\n          context.arc(x1, y1, r, 0, 2 * Math.PI, true);\n          ++i;\n          break;\n        case CanvasInstruction.CLOSE_PATH:\n          context.closePath();\n          ++i;\n          break;\n        case CanvasInstruction.CUSTOM:\n          d = /** @type {number} */ (instruction[1]);\n          dd = instruction[2];\n          const geometry =\n            /** @type {import(\"../../geom/SimpleGeometry.js\").default} */ (\n              instruction[3]\n            );\n          const renderer = instruction[4];\n          const fn = instruction[5];\n          state.geometry = geometry;\n          state.feature = feature;\n          if (!(i in coordinateCache)) {\n            coordinateCache[i] = [];\n          }\n          const coords = coordinateCache[i];\n          if (fn) {\n            fn(pixelCoordinates, d, dd, 2, coords);\n          } else {\n            coords[0] = pixelCoordinates[d];\n            coords[1] = pixelCoordinates[d + 1];\n            coords.length = 2;\n          }\n          if (zIndexContext) {\n            zIndexContext.zIndex = instruction[6];\n          }\n          renderer(coords, state);\n          ++i;\n          break;\n        case CanvasInstruction.DRAW_IMAGE:\n          d = /** @type {number} */ (instruction[1]);\n          dd = /** @type {number} */ (instruction[2]);\n          image =\n            /** @type {HTMLCanvasElement|HTMLVideoElement|HTMLImageElement} */ (\n              instruction[3]\n            );\n\n          // Remaining arguments in DRAW_IMAGE are in alphabetical order\n          anchorX = /** @type {number} */ (instruction[4]);\n          anchorY = /** @type {number} */ (instruction[5]);\n          let height = /** @type {number} */ (instruction[6]);\n          const opacity = /** @type {number} */ (instruction[7]);\n          const originX = /** @type {number} */ (instruction[8]);\n          const originY = /** @type {number} */ (instruction[9]);\n          const rotateWithView = /** @type {boolean} */ (instruction[10]);\n          let rotation = /** @type {number} */ (instruction[11]);\n          const scale = /** @type {import(\"../../size.js\").Size} */ (\n            instruction[12]\n          );\n          let width = /** @type {number} */ (instruction[13]);\n          declutterMode = instruction[14] || 'declutter';\n          const declutterImageWithText =\n            /** @type {{args: import(\"../canvas.js\").DeclutterImageWithText, declutterMode: import('../../style/Style.js').DeclutterMode}} */ (\n              instruction[15]\n            );\n\n          if (!image && instruction.length >= 20) {\n            // create label images\n            text = /** @type {string} */ (instruction[19]);\n            textKey = /** @type {string} */ (instruction[20]);\n            strokeKey = /** @type {string} */ (instruction[21]);\n            fillKey = /** @type {string} */ (instruction[22]);\n            const labelWithAnchor = this.drawLabelWithPointPlacement_(\n              text,\n              textKey,\n              strokeKey,\n              fillKey,\n            );\n            image = labelWithAnchor.label;\n            instruction[3] = image;\n            const textOffsetX = /** @type {number} */ (instruction[23]);\n            anchorX = (labelWithAnchor.anchorX - textOffsetX) * this.pixelRatio;\n            instruction[4] = anchorX;\n            const textOffsetY = /** @type {number} */ (instruction[24]);\n            anchorY = (labelWithAnchor.anchorY - textOffsetY) * this.pixelRatio;\n            instruction[5] = anchorY;\n            height = image.height;\n            instruction[6] = height;\n            width = image.width;\n            instruction[13] = width;\n          }\n\n          let geometryWidths;\n          if (instruction.length > 25) {\n            geometryWidths = /** @type {number} */ (instruction[25]);\n          }\n\n          let padding, backgroundFillInstruction, backgroundStrokeInstruction;\n          if (instruction.length > 17) {\n            padding = /** @type {Array<number>} */ (instruction[16]);\n            backgroundFillInstruction = /** @type {Array<*>} */ (\n              instruction[17]\n            );\n            backgroundStrokeInstruction = /** @type {Array<*>} */ (\n              instruction[18]\n            );\n          } else {\n            padding = defaultPadding;\n            backgroundFillInstruction = null;\n            backgroundStrokeInstruction = null;\n          }\n\n          if (rotateWithView && viewRotationFromTransform) {\n            // Canvas is expected to be rotated to reverse view rotation.\n            rotation += viewRotation;\n          } else if (!rotateWithView && !viewRotationFromTransform) {\n            // Canvas is not rotated, images need to be rotated back to be north-up.\n            rotation -= viewRotation;\n          }\n          let widthIndex = 0;\n          for (; d < dd; d += 2) {\n            if (\n              geometryWidths &&\n              geometryWidths[widthIndex++] < width / this.pixelRatio\n            ) {\n              continue;\n            }\n            const dimensions = this.calculateImageOrLabelDimensions_(\n              image.width,\n              image.height,\n              pixelCoordinates[d],\n              pixelCoordinates[d + 1],\n              width,\n              height,\n              anchorX,\n              anchorY,\n              originX,\n              originY,\n              rotation,\n              scale,\n              snapToPixel,\n              padding,\n              !!backgroundFillInstruction || !!backgroundStrokeInstruction,\n              feature,\n            );\n            /** @type {ReplayImageOrLabelArgs} */\n            const args = [\n              context,\n              scaledCanvasSize,\n              image,\n              dimensions,\n              opacity,\n              backgroundFillInstruction,\n              backgroundStrokeInstruction,\n            ];\n            if (declutterTree) {\n              let imageArgs, imageDeclutterMode, imageDeclutterBox;\n              if (declutterImageWithText) {\n                const index = dd - d;\n                if (!declutterImageWithText[index]) {\n                  // We now have the image for an image+text combination.\n                  declutterImageWithText[index] = {args, declutterMode};\n                  // Don't render anything for now, wait for the text.\n                  continue;\n                }\n                const imageDeclutter = declutterImageWithText[index];\n                imageArgs = imageDeclutter.args;\n                imageDeclutterMode = imageDeclutter.declutterMode;\n                delete declutterImageWithText[index];\n                imageDeclutterBox = getDeclutterBox(imageArgs);\n              }\n              // We now have image and text for an image+text combination.\n              let renderImage, renderText;\n              if (\n                imageArgs &&\n                (imageDeclutterMode !== 'declutter' ||\n                  !declutterTree.collides(imageDeclutterBox))\n              ) {\n                renderImage = true;\n              }\n              if (\n                declutterMode !== 'declutter' ||\n                !declutterTree.collides(dimensions.declutterBox)\n              ) {\n                renderText = true;\n              }\n              if (\n                imageDeclutterMode === 'declutter' &&\n                declutterMode === 'declutter'\n              ) {\n                const render = renderImage && renderText;\n                renderImage = render;\n                renderText = render;\n              }\n              if (renderImage) {\n                if (imageDeclutterMode !== 'none') {\n                  declutterTree.insert(imageDeclutterBox);\n                }\n                this.replayImageOrLabel_.apply(this, imageArgs);\n              }\n              if (renderText) {\n                if (declutterMode !== 'none') {\n                  declutterTree.insert(dimensions.declutterBox);\n                }\n                this.replayImageOrLabel_.apply(this, args);\n              }\n            } else {\n              this.replayImageOrLabel_.apply(this, args);\n            }\n          }\n          ++i;\n          break;\n        case CanvasInstruction.DRAW_CHARS:\n          const begin = /** @type {number} */ (instruction[1]);\n          const end = /** @type {number} */ (instruction[2]);\n          const baseline = /** @type {number} */ (instruction[3]);\n          const overflow = /** @type {number} */ (instruction[4]);\n          fillKey = /** @type {string} */ (instruction[5]);\n          const maxAngle = /** @type {number} */ (instruction[6]);\n          const measurePixelRatio = /** @type {number} */ (instruction[7]);\n          const offsetY = /** @type {number} */ (instruction[8]);\n          strokeKey = /** @type {string} */ (instruction[9]);\n          const strokeWidth = /** @type {number} */ (instruction[10]);\n          text = /** @type {string|Array<string>} */ (instruction[11]);\n          if (Array.isArray(text)) {\n            //FIXME Add support for rich text along lines\n            text = text.reduce(richTextToPlainText, '');\n          }\n          textKey = /** @type {string} */ (instruction[12]);\n          const pixelRatioScale = [\n            /** @type {number} */ (instruction[13]),\n            /** @type {number} */ (instruction[13]),\n          ];\n          declutterMode = instruction[14] || 'declutter';\n\n          const textKeepUpright = /** @type {boolean} */ (instruction[15]);\n          const textState = this.textStates[textKey];\n          const font = textState.font;\n          const textScale = [\n            textState.scale[0] * measurePixelRatio,\n            textState.scale[1] * measurePixelRatio,\n          ];\n\n          let cachedWidths;\n          if (font in this.widths_) {\n            cachedWidths = this.widths_[font];\n          } else {\n            cachedWidths = {};\n            this.widths_[font] = cachedWidths;\n          }\n\n          const pathLength = lineStringLength(pixelCoordinates, begin, end, 2);\n          const textLength =\n            Math.abs(textScale[0]) *\n            measureAndCacheTextWidth(font, text, cachedWidths);\n          if (overflow || textLength <= pathLength) {\n            const textAlign = this.textStates[textKey].textAlign;\n            const startM =\n              (pathLength - textLength) * horizontalTextAlign(text, textAlign);\n            const parts = drawTextOnPath(\n              pixelCoordinates,\n              begin,\n              end,\n              2,\n              text,\n              startM,\n              maxAngle,\n              Math.abs(textScale[0]),\n              measureAndCacheTextWidth,\n              font,\n              cachedWidths,\n              viewRotationFromTransform ? 0 : this.viewRotation_,\n              textKeepUpright,\n            );\n            drawChars: if (parts) {\n              /** @type {Array<ReplayImageOrLabelArgs>} */\n              const replayImageOrLabelArgs = [];\n              let c, cc, chars, label, part;\n              if (strokeKey) {\n                for (c = 0, cc = parts.length; c < cc; ++c) {\n                  part = parts[c]; // x, y, anchorX, rotation, chunk\n                  chars = /** @type {string} */ (part[4]);\n                  label = this.createLabel(chars, textKey, '', strokeKey);\n                  anchorX =\n                    /** @type {number} */ (part[2]) +\n                    (textScale[0] < 0 ? -strokeWidth : strokeWidth);\n                  anchorY =\n                    baseline * label.height +\n                    ((0.5 - baseline) * 2 * strokeWidth * textScale[1]) /\n                      textScale[0] -\n                    offsetY;\n                  const dimensions = this.calculateImageOrLabelDimensions_(\n                    label.width,\n                    label.height,\n                    part[0],\n                    part[1],\n                    label.width,\n                    label.height,\n                    anchorX,\n                    anchorY,\n                    0,\n                    0,\n                    part[3],\n                    pixelRatioScale,\n                    false,\n                    defaultPadding,\n                    false,\n                    feature,\n                  );\n                  if (\n                    declutterTree &&\n                    declutterMode === 'declutter' &&\n                    declutterTree.collides(dimensions.declutterBox)\n                  ) {\n                    break drawChars;\n                  }\n                  replayImageOrLabelArgs.push([\n                    context,\n                    scaledCanvasSize,\n                    label,\n                    dimensions,\n                    1,\n                    null,\n                    null,\n                  ]);\n                }\n              }\n              if (fillKey) {\n                for (c = 0, cc = parts.length; c < cc; ++c) {\n                  part = parts[c]; // x, y, anchorX, rotation, chunk\n                  chars = /** @type {string} */ (part[4]);\n                  label = this.createLabel(chars, textKey, fillKey, '');\n                  anchorX = /** @type {number} */ (part[2]);\n                  anchorY = baseline * label.height - offsetY;\n                  const dimensions = this.calculateImageOrLabelDimensions_(\n                    label.width,\n                    label.height,\n                    part[0],\n                    part[1],\n                    label.width,\n                    label.height,\n                    anchorX,\n                    anchorY,\n                    0,\n                    0,\n                    part[3],\n                    pixelRatioScale,\n                    false,\n                    defaultPadding,\n                    false,\n                    feature,\n                  );\n                  if (\n                    declutterTree &&\n                    declutterMode === 'declutter' &&\n                    declutterTree.collides(dimensions.declutterBox)\n                  ) {\n                    break drawChars;\n                  }\n                  replayImageOrLabelArgs.push([\n                    context,\n                    scaledCanvasSize,\n                    label,\n                    dimensions,\n                    1,\n                    null,\n                    null,\n                  ]);\n                }\n              }\n              if (declutterTree && declutterMode !== 'none') {\n                declutterTree.load(replayImageOrLabelArgs.map(getDeclutterBox));\n              }\n              for (let i = 0, ii = replayImageOrLabelArgs.length; i < ii; ++i) {\n                this.replayImageOrLabel_.apply(this, replayImageOrLabelArgs[i]);\n              }\n            }\n          }\n          ++i;\n          break;\n        case CanvasInstruction.END_GEOMETRY:\n          if (featureCallback !== undefined) {\n            feature = /** @type {import(\"../../Feature.js\").FeatureLike} */ (\n              instruction[1]\n            );\n            const result = featureCallback(\n              feature,\n              currentGeometry,\n              declutterMode,\n            );\n            if (result) {\n              return result;\n            }\n          }\n          ++i;\n          break;\n        case CanvasInstruction.FILL:\n          if (batchSize) {\n            pendingFill++;\n          } else {\n            this.fill_(context);\n          }\n          ++i;\n          break;\n        case CanvasInstruction.MOVE_TO_LINE_TO:\n          d = /** @type {number} */ (instruction[1]);\n          dd = /** @type {number} */ (instruction[2]);\n          lineOffsetPx = /** @type {number|undefined} */ (instruction[3]);\n\n          let lineCoords, lineStart, lineEnd;\n          if (lineOffsetPx) {\n            const isClosedRing =\n              /** @type {boolean|undefined} */ (instruction[4]) ?? false;\n            offsetLineString(\n              pixelCoordinates,\n              d,\n              dd,\n              2,\n              lineOffsetPx,\n              isClosedRing,\n              offsetCoords,\n            );\n            removeOffsetCycles(offsetCoords, 2);\n            lineCoords = offsetCoords;\n            lineStart = 0;\n            lineEnd = lineCoords.length;\n          } else {\n            lineCoords = pixelCoordinates;\n            lineStart = d;\n            lineEnd = dd;\n          }\n          x = lineCoords[lineStart];\n          y = lineCoords[lineStart + 1];\n          context.moveTo(x, y);\n          prevX = (x + 0.5) | 0;\n          prevY = (y + 0.5) | 0;\n          for (let k = lineStart + 2; k < lineEnd; k += 2) {\n            x = lineCoords[k];\n            y = lineCoords[k + 1];\n            roundX = (x + 0.5) | 0;\n            roundY = (y + 0.5) | 0;\n            if (k == lineEnd - 2 || roundX !== prevX || roundY !== prevY) {\n              context.lineTo(x, y);\n              prevX = roundX;\n              prevY = roundY;\n            }\n          }\n          ++i;\n          break;\n        case CanvasInstruction.SET_FILL_STYLE:\n          this.alignAndScaleFill_ = instruction[2];\n\n          if (pendingFill) {\n            this.fill_(context);\n            pendingFill = 0;\n            if (pendingStroke) {\n              context.stroke();\n              pendingStroke = 0;\n            }\n          } else if (pendingStroke && instruction[1]) {\n            context.stroke();\n            pendingStroke = 0;\n          }\n\n          /** @type {import(\"../../colorlike.js\").ColorLike} */\n          context.fillStyle = instruction[1];\n          ++i;\n          break;\n        case CanvasInstruction.SET_STROKE_STYLE:\n          if (pendingFill && instruction[1]) {\n            this.fill_(context);\n            pendingFill = 0;\n          }\n          if (pendingStroke) {\n            context.stroke();\n            pendingStroke = 0;\n          }\n          this.setStrokeStyle_(context, /** @type {Array<*>} */ (instruction));\n          ++i;\n          break;\n        case CanvasInstruction.STROKE:\n          if (batchSize) {\n            pendingStroke++;\n          } else {\n            context.stroke();\n          }\n          ++i;\n          break;\n        default: // consume the instruction anyway, to avoid an infinite loop\n          ++i;\n          break;\n      }\n    }\n    if (pendingFill) {\n      this.fill_(context);\n    }\n    if (pendingStroke) {\n      context.stroke();\n    }\n    return undefined;\n  }\n\n  /**\n   * @param {CanvasRenderingContext2D|OffscreenCanvasRenderingContext2D} context Context.\n   * @param {import('../../size.js').Size} scaledCanvasSize Scaled canvas size.\n   * @param {import(\"../../transform.js\").Transform} transform Transform.\n   * @param {number} viewRotation View rotation.\n   * @param {boolean} snapToPixel Snap point symbols and text to integer pixels.\n   * @param {import(\"rbush\").default<DeclutterEntry>} [declutterTree] Declutter tree.\n   */\n  execute(\n    context,\n    scaledCanvasSize,\n    transform,\n    viewRotation,\n    snapToPixel,\n    declutterTree,\n  ) {\n    this.viewRotation_ = viewRotation;\n    this.execute_(\n      context,\n      scaledCanvasSize,\n      transform,\n      this.instructions,\n      snapToPixel,\n      undefined,\n      undefined,\n      declutterTree,\n    );\n  }\n\n  /**\n   * @param {CanvasRenderingContext2D|OffscreenCanvasRenderingContext2D} context Context.\n   * @param {import(\"../../transform.js\").Transform} transform Transform.\n   * @param {number} viewRotation View rotation.\n   * @param {FeatureCallback<T>} [featureCallback] Feature callback.\n   * @param {import(\"../../extent.js\").Extent} [hitExtent] Only check\n   *     features that intersect this extent.\n   * @return {T|undefined} Callback result.\n   * @template T\n   */\n  executeHitDetection(\n    context,\n    transform,\n    viewRotation,\n    featureCallback,\n    hitExtent,\n  ) {\n    this.viewRotation_ = viewRotation;\n    return this.execute_(\n      context,\n      [context.canvas.width, context.canvas.height],\n      transform,\n      this.hitDetectionInstructions,\n      true,\n      featureCallback,\n      hitExtent,\n    );\n  }\n}\n\nexport default Executor;\n", "/**\n * @module ol/render/canvas/ExecutorGroup\n */\n\nimport {ascending, descending} from '../../array.js';\nimport {createCanvasContext2D} from '../../dom.js';\nimport {buffer, createEmpty, extendCoordinate} from '../../extent.js';\nimport {transform2D} from '../../geom/flat/transform.js';\nimport {isEmpty} from '../../obj.js';\nimport {\n  compose as composeTransform,\n  create as createTransform,\n} from '../../transform.js';\nimport Executor from './Executor.js';\n\n/**\n * @const\n * @type {Array<import(\"../canvas.js\").BuilderType>}\n */\nexport const ALL = [\n  'Polygon',\n  'Circle',\n  'LineString',\n  'Image',\n  'Text',\n  'Default',\n];\n\n/**\n * @const\n * @type {Array<import(\"../canvas.js\").BuilderType>}\n */\nexport const DECLUTTER = ['Image', 'Text'];\n\n/**\n * @const\n * @type {Array<import(\"../canvas.js\").BuilderType>}\n */\nexport const NON_DECLUTTER = ALL.filter(\n  (builderType) => !DECLUTTER.includes(builderType),\n);\n\n/** @type {boolean|undefined} */\nlet willReadFrequently = false;\n\n/** @type {boolean|undefined} */\nlet canvasReadsBenchmarked = false;\n\n/** Determine if canvas read operations are faster with willReadFrequently set to true or false */\nfunction benchmarkCanvasReads() {\n  let bestResult = 0;\n  /**\n   * @param {boolean} willReadFrequently Will read frequently.\n   * @return {number} Operation count.\n   */\n  const measure = (willReadFrequently) => {\n    const context = createCanvasContext2D(1, 1, null, {willReadFrequently});\n    let count = 0;\n    const start = performance.now();\n    for (; performance.now() - start < 50; ++count) {\n      context.fillStyle = `rgba(255,0,${count % 256},1)`;\n      context.fillRect(0, 0, 1, 1);\n      context.getImageData(0, 0, 1, 1);\n    }\n    bestResult = count > bestResult ? count : bestResult;\n    return count;\n  };\n\n  const measures = {\n    [measure(true)]: true,\n    [measure(false)]: false,\n    [measure(undefined)]: undefined,\n  };\n  willReadFrequently = measures[bestResult];\n  canvasReadsBenchmarked = true;\n}\n\nclass ExecutorGroup {\n  /**\n   * @param {import(\"../../extent.js\").Extent} maxExtent Max extent for clipping. When a\n   * `maxExtent` was set on the Builder for this executor group, the same `maxExtent`\n   * should be set here, unless the target context does not exceed that extent (which\n   * can be the case when rendering to tiles).\n   * @param {number} resolution Resolution.\n   * @param {number} pixelRatio Pixel ratio.\n   * @param {boolean} overlaps The executor group can have overlapping geometries.\n   * @param {!Object<string, !Object<import(\"../canvas.js\").BuilderType, import(\"../canvas.js\").SerializableInstructions>>} allInstructions\n   * The serializable instructions.\n   * @param {number} [renderBuffer] Optional rendering buffer.\n   * @param {boolean} [deferredRendering] Enable deferred rendering with renderDeferred().\n   */\n  constructor(\n    maxExtent,\n    resolution,\n    pixelRatio,\n    overlaps,\n    allInstructions,\n    renderBuffer,\n    deferredRendering,\n  ) {\n    /**\n     * @private\n     * @type {import(\"../../extent.js\").Extent}\n     */\n    this.maxExtent_ = maxExtent;\n\n    /**\n     * @private\n     * @type {boolean}\n     */\n    this.overlaps_ = overlaps;\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.pixelRatio_ = pixelRatio;\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.resolution_ = resolution;\n\n    /**\n     * @private\n     * @type {number|undefined}\n     */\n    this.renderBuffer_ = renderBuffer;\n\n    /**\n     * @private\n     * @type {!Object<string, !Object<string, import(\"./Executor.js\").default>>}\n     */\n    this.executorsByZIndex_ = {};\n\n    /**\n     * @private\n     * @type {CanvasRenderingContext2D|OffscreenCanvasRenderingContext2D}\n     */\n    this.hitDetectionContext_ = null;\n\n    /**\n     * @private\n     * @type {import(\"../../transform.js\").Transform}\n     */\n    this.hitDetectionTransform_ = createTransform();\n\n    /**\n     * @private\n     * @type {CanvasRenderingContext2D|OffscreenCanvasRenderingContext2D}\n     */\n    this.renderedContext_ = null;\n\n    /**\n     * @private\n     * @type {Object<number, Array<import(\"./ZIndexContext.js\").default>>}\n     */\n    this.deferredZIndexContexts_ = {};\n\n    this.createExecutors_(allInstructions, deferredRendering);\n  }\n\n  /**\n   * @param {CanvasRenderingContext2D|OffscreenCanvasRenderingContext2D} context Context.\n   * @param {import(\"../../transform.js\").Transform} transform Transform.\n   */\n  clip(context, transform) {\n    const flatClipCoords = this.getClipCoords(transform);\n    context.beginPath();\n    context.moveTo(flatClipCoords[0], flatClipCoords[1]);\n    context.lineTo(flatClipCoords[2], flatClipCoords[3]);\n    context.lineTo(flatClipCoords[4], flatClipCoords[5]);\n    context.lineTo(flatClipCoords[6], flatClipCoords[7]);\n    context.clip();\n  }\n\n  /**\n   * Create executors and populate them using the provided instructions.\n   * @private\n   * @param {!Object<string, !Object<string, import(\"../canvas.js\").SerializableInstructions>>} allInstructions The serializable instructions\n   * @param {boolean} deferredRendering Enable deferred rendering.\n   */\n  createExecutors_(allInstructions, deferredRendering) {\n    for (const zIndex in allInstructions) {\n      let executors = this.executorsByZIndex_[zIndex];\n      if (executors === undefined) {\n        executors = {};\n        this.executorsByZIndex_[zIndex] = executors;\n      }\n      const instructionByZindex = allInstructions[zIndex];\n      for (const builderType in instructionByZindex) {\n        const instructions = instructionByZindex[builderType];\n        executors[builderType] = new Executor(\n          this.resolution_,\n          this.pixelRatio_,\n          this.overlaps_,\n          instructions,\n          deferredRendering,\n        );\n      }\n    }\n  }\n\n  /**\n   * @param {Array<import(\"../canvas.js\").BuilderType>} executors Executors.\n   * @return {boolean} Has executors of the provided types.\n   */\n  hasExecutors(executors) {\n    for (const zIndex in this.executorsByZIndex_) {\n      const candidates = this.executorsByZIndex_[zIndex];\n      for (let i = 0, ii = executors.length; i < ii; ++i) {\n        if (executors[i] in candidates) {\n          return true;\n        }\n      }\n    }\n    return false;\n  }\n\n  /**\n   * @param {import(\"../../coordinate.js\").Coordinate} coordinate Coordinate.\n   * @param {number} resolution Resolution.\n   * @param {number} rotation Rotation.\n   * @param {number} hitTolerance Hit tolerance in pixels.\n   * @param {function(import(\"../../Feature.js\").FeatureLike, import(\"../../geom/SimpleGeometry.js\").default, number): T} callback Feature callback.\n   * @param {Array<import(\"../../Feature.js\").FeatureLike>} declutteredFeatures Decluttered features.\n   * @return {T|undefined} Callback result.\n   * @template T\n   */\n  forEachFeatureAtCoordinate(\n    coordinate,\n    resolution,\n    rotation,\n    hitTolerance,\n    callback,\n    declutteredFeatures,\n  ) {\n    if (canvasReadsBenchmarked === false) {\n      benchmarkCanvasReads();\n    }\n\n    hitTolerance = Math.round(hitTolerance);\n    const contextSize = hitTolerance * 2 + 1;\n    const transform = composeTransform(\n      this.hitDetectionTransform_,\n      hitTolerance + 0.5,\n      hitTolerance + 0.5,\n      1 / resolution,\n      -1 / resolution,\n      -rotation,\n      -coordinate[0],\n      -coordinate[1],\n    );\n\n    const newContext = !this.hitDetectionContext_;\n    if (newContext) {\n      this.hitDetectionContext_ = createCanvasContext2D(\n        contextSize,\n        contextSize,\n        null,\n        {willReadFrequently},\n      );\n    }\n    const context = this.hitDetectionContext_;\n\n    if (\n      context.canvas.width !== contextSize ||\n      context.canvas.height !== contextSize\n    ) {\n      context.canvas.width = contextSize;\n      context.canvas.height = contextSize;\n    } else if (!newContext) {\n      context.clearRect(0, 0, contextSize, contextSize);\n    }\n\n    /** @type {import(\"../../extent.js\").Extent|undefined} */\n    let hitExtent;\n    if (this.renderBuffer_ !== undefined) {\n      hitExtent = createEmpty();\n      extendCoordinate(hitExtent, coordinate);\n      buffer(\n        hitExtent,\n        resolution * (this.renderBuffer_ + hitTolerance),\n        hitExtent,\n      );\n    }\n\n    const indexes = getPixelIndexArray(hitTolerance);\n\n    /** @type {import(\"../canvas.js\").BuilderType} */\n    let builderType;\n\n    /**\n     * @param {import(\"../../Feature.js\").FeatureLike} feature Feature.\n     * @param {import(\"../../geom/SimpleGeometry.js\").default} geometry Geometry.\n     * @param {import('../../style/Style.js').DeclutterMode} declutterMode Declutter mode.\n     * @return {T|undefined} Callback result.\n     */\n    function featureCallback(feature, geometry, declutterMode) {\n      const imageData = context.getImageData(\n        0,\n        0,\n        contextSize,\n        contextSize,\n      ).data;\n      for (let i = 0, ii = indexes.length; i < ii; i++) {\n        if (imageData[indexes[i]] > 0) {\n          if (\n            !declutteredFeatures ||\n            declutterMode === 'none' ||\n            (builderType !== 'Image' && builderType !== 'Text') ||\n            declutteredFeatures.includes(feature)\n          ) {\n            const idx = (indexes[i] - 3) / 4;\n            const x = hitTolerance - (idx % contextSize);\n            const y = hitTolerance - ((idx / contextSize) | 0);\n            const result = callback(feature, geometry, x * x + y * y);\n            if (result) {\n              return result;\n            }\n          }\n          context.clearRect(0, 0, contextSize, contextSize);\n          break;\n        }\n      }\n      return undefined;\n    }\n\n    /** @type {Array<number>} */\n    const zs = Object.keys(this.executorsByZIndex_).map(Number);\n    zs.sort(ascending);\n\n    let i, j, executors, executor, result;\n    for (i = zs.length - 1; i >= 0; --i) {\n      const zIndexKey = zs[i].toString();\n      executors = this.executorsByZIndex_[zIndexKey];\n      for (j = ALL.length - 1; j >= 0; --j) {\n        builderType = ALL[j];\n        executor = executors[builderType];\n        if (executor !== undefined) {\n          result = executor.executeHitDetection(\n            context,\n            transform,\n            rotation,\n            featureCallback,\n            hitExtent,\n          );\n          if (result) {\n            return result;\n          }\n        }\n      }\n    }\n    return undefined;\n  }\n\n  /**\n   * @param {import(\"../../transform.js\").Transform} transform Transform.\n   * @return {Array<number>|null} Clip coordinates.\n   */\n  getClipCoords(transform) {\n    const maxExtent = this.maxExtent_;\n    if (!maxExtent) {\n      return null;\n    }\n    const minX = maxExtent[0];\n    const minY = maxExtent[1];\n    const maxX = maxExtent[2];\n    const maxY = maxExtent[3];\n    const flatClipCoords = [minX, minY, minX, maxY, maxX, maxY, maxX, minY];\n    transform2D(flatClipCoords, 0, 8, 2, transform, flatClipCoords);\n    return flatClipCoords;\n  }\n\n  /**\n   * @return {boolean} Is empty.\n   */\n  isEmpty() {\n    return isEmpty(this.executorsByZIndex_);\n  }\n\n  /**\n   * @param {CanvasRenderingContext2D|OffscreenCanvasRenderingContext2D} targetContext Context.\n   * @param {import('../../size.js').Size} scaledCanvasSize Scale of the context.\n   * @param {import(\"../../transform.js\").Transform} transform Transform.\n   * @param {number} viewRotation View rotation.\n   * @param {boolean} snapToPixel Snap point symbols and test to integer pixel.\n   * @param {Array<import(\"../canvas.js\").BuilderType>} [builderTypes] Ordered replay types to replay.\n   *     Default is {@link module:ol/render/replay~ALL}\n   * @param {import(\"rbush\").default<import('./Executor.js').DeclutterEntry>|null} [declutterTree] Declutter tree.\n   *     When set to null, no decluttering is done, even when the executor group has a `ZIndexContext`.\n   */\n  execute(\n    targetContext,\n    scaledCanvasSize,\n    transform,\n    viewRotation,\n    snapToPixel,\n    builderTypes,\n    declutterTree,\n  ) {\n    const zs = Object.keys(this.executorsByZIndex_).map(Number);\n    zs.sort(declutterTree ? descending : ascending);\n\n    builderTypes = builderTypes ? builderTypes : ALL;\n    const maxBuilderTypes = ALL.length;\n    for (let i = 0, ii = zs.length; i < ii; ++i) {\n      const zIndexKey = zs[i].toString();\n      const replays = this.executorsByZIndex_[zIndexKey];\n      for (let j = 0, jj = builderTypes.length; j < jj; ++j) {\n        const builderType = builderTypes[j];\n        const replay = replays[builderType];\n        if (replay !== undefined) {\n          const zIndexContext =\n            declutterTree === null ? undefined : replay.getZIndexContext();\n          const context = zIndexContext\n            ? zIndexContext.getContext()\n            : targetContext;\n          const requireClip =\n            this.maxExtent_ &&\n            builderType !== 'Image' &&\n            builderType !== 'Text';\n          if (requireClip) {\n            context.save();\n            // setup clipping so that the parts of over-simplified geometries are not\n            // visible outside the current extent when panning\n            this.clip(context, transform);\n          }\n          if (\n            !zIndexContext ||\n            builderType === 'Text' ||\n            builderType === 'Image'\n          ) {\n            replay.execute(\n              context,\n              scaledCanvasSize,\n              transform,\n              viewRotation,\n              snapToPixel,\n              declutterTree,\n            );\n          } else {\n            zIndexContext.pushFunction((context) =>\n              replay.execute(\n                context,\n                scaledCanvasSize,\n                transform,\n                viewRotation,\n                snapToPixel,\n                declutterTree,\n              ),\n            );\n          }\n          if (requireClip) {\n            context.restore();\n          }\n          if (zIndexContext) {\n            zIndexContext.offset();\n            const index = zs[i] * maxBuilderTypes + ALL.indexOf(builderType);\n            if (!this.deferredZIndexContexts_[index]) {\n              this.deferredZIndexContexts_[index] = [];\n            }\n            this.deferredZIndexContexts_[index].push(zIndexContext);\n          }\n        }\n      }\n    }\n\n    this.renderedContext_ = targetContext;\n  }\n\n  getDeferredZIndexContexts() {\n    return this.deferredZIndexContexts_;\n  }\n\n  getRenderedContext() {\n    return this.renderedContext_;\n  }\n\n  renderDeferred() {\n    const deferredZIndexContexts = this.deferredZIndexContexts_;\n    const zs = Object.keys(deferredZIndexContexts).map(Number).sort(ascending);\n    for (let i = 0, ii = zs.length; i < ii; ++i) {\n      deferredZIndexContexts[zs[i]].forEach((zIndexContext) => {\n        zIndexContext.draw(this.renderedContext_); // FIXME Pass clip to replay for temporarily enabling clip\n        zIndexContext.clear();\n      });\n      deferredZIndexContexts[zs[i]].length = 0;\n    }\n  }\n}\n\n/**\n * This cache is used to store arrays of indexes for calculated pixel circles\n * to increase performance.\n * It is a static property to allow each Replaygroup to access it.\n * @type {Object<number, Array<number>>}\n */\nconst circlePixelIndexArrayCache = {};\n\n/**\n * This methods creates an array with indexes of all pixels within a circle,\n * ordered by how close they are to the center.\n * A cache is used to increase performance.\n * @param {number} radius Radius.\n * @return {Array<number>} An array with indexes within a circle.\n */\nexport function getPixelIndexArray(radius) {\n  if (circlePixelIndexArrayCache[radius] !== undefined) {\n    return circlePixelIndexArrayCache[radius];\n  }\n\n  const size = radius * 2 + 1;\n  const maxDistanceSq = radius * radius;\n  const distances = new Array(maxDistanceSq + 1);\n  for (let i = 0; i <= radius; ++i) {\n    for (let j = 0; j <= radius; ++j) {\n      const distanceSq = i * i + j * j;\n      if (distanceSq > maxDistanceSq) {\n        break;\n      }\n      let distance = distances[distanceSq];\n      if (!distance) {\n        distance = [];\n        distances[distanceSq] = distance;\n      }\n      distance.push(((radius + i) * size + (radius + j)) * 4 + 3);\n      if (i > 0) {\n        distance.push(((radius - i) * size + (radius + j)) * 4 + 3);\n      }\n      if (j > 0) {\n        distance.push(((radius + i) * size + (radius - j)) * 4 + 3);\n        if (i > 0) {\n          distance.push(((radius - i) * size + (radius - j)) * 4 + 3);\n        }\n      }\n    }\n  }\n\n  const pixelIndex = [];\n  for (let i = 0, ii = distances.length; i < ii; ++i) {\n    if (distances[i]) {\n      pixelIndex.push(...distances[i]);\n    }\n  }\n\n  circlePixelIndexArrayCache[radius] = pixelIndex;\n  return pixelIndex;\n}\n\nexport default ExecutorGroup;\n", "/**\n * @module ol/render/canvas/Immediate\n */\n// FIXME test, especially polygons with holes and multipolygons\n// FIXME need to handle large thick features (where pixel size matters)\n// FIXME add offset and end to ol/geom/flat/transform~transform2D?\n\nimport {equals} from '../../array.js';\nimport {asColorLike} from '../../colorlike.js';\nimport {intersects} from '../../extent.js';\nimport {transformGeom2D} from '../../geom/SimpleGeometry.js';\nimport {\n  offsetLineString,\n  removeOffsetCycles,\n} from '../../geom/flat/lineoffset.js';\nimport {transform2D} from '../../geom/flat/transform.js';\nimport {toFixed} from '../../math.js';\nimport {\n  compose as composeTransform,\n  create as createTransform,\n} from '../../transform.js';\nimport VectorContext from '../VectorContext.js';\nimport {\n  defaultFillStyle,\n  defaultFont,\n  defaultLineCap,\n  defaultLineDash,\n  defaultLineDashOffset,\n  defaultLineJoin,\n  defaultLineWidth,\n  defaultMiterLimit,\n  defaultStrokeStyle,\n  defaultTextAlign,\n  defaultTextBaseline,\n} from '../canvas.js';\n\n/**\n * @classdesc\n * A concrete subclass of {@link module:ol/render/VectorContext~VectorContext} that implements\n * direct rendering of features and geometries to an HTML5 Canvas context.\n * Instances of this class are created internally by the library and\n * provided to application code as vectorContext member of the\n * {@link module:ol/render/Event~RenderEvent} object associated with postcompose, precompose and\n * render events emitted by layers and maps.\n */\nclass CanvasImmediateRenderer extends VectorContext {\n  /**\n   * @param {CanvasRenderingContext2D|OffscreenCanvasRenderingContext2D} context Context.\n   * @param {number} pixelRatio Pixel ratio.\n   * @param {import(\"../../extent.js\").Extent} extent Extent.\n   * @param {import(\"../../transform.js\").Transform} transform Transform.\n   * @param {number} viewRotation View rotation.\n   * @param {number} [squaredTolerance] Optional squared tolerance for simplification.\n   * @param {import(\"../../proj.js\").TransformFunction} [userTransform] Transform from user to view projection.\n   */\n  constructor(\n    context,\n    pixelRatio,\n    extent,\n    transform,\n    viewRotation,\n    squaredTolerance,\n    userTransform,\n  ) {\n    super();\n\n    /**\n     * @private\n     * @type {CanvasRenderingContext2D|OffscreenCanvasRenderingContext2D}\n     */\n    this.context_ = context;\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.pixelRatio_ = pixelRatio;\n\n    /**\n     * @private\n     * @type {import(\"../../extent.js\").Extent}\n     */\n    this.extent_ = extent;\n\n    /**\n     * @private\n     * @type {import(\"../../transform.js\").Transform}\n     */\n    this.transform_ = transform;\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.transformRotation_ = transform\n      ? toFixed(Math.atan2(transform[1], transform[0]), 10)\n      : 0;\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.viewRotation_ = viewRotation;\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.squaredTolerance_ = squaredTolerance;\n\n    /**\n     * @private\n     * @type {import(\"../../proj.js\").TransformFunction}\n     */\n    this.userTransform_ = userTransform;\n\n    /**\n     * @private\n     * @type {?import(\"../canvas.js\").FillState}\n     */\n    this.contextFillState_ = null;\n\n    /**\n     * @private\n     * @type {?import(\"../canvas.js\").StrokeState}\n     */\n    this.contextStrokeState_ = null;\n\n    /**\n     * @private\n     * @type {?import(\"../canvas.js\").TextState}\n     */\n    this.contextTextState_ = null;\n\n    /**\n     * @private\n     * @type {?import(\"../canvas.js\").FillState}\n     */\n    this.fillState_ = null;\n\n    /**\n     * @private\n     * @type {?import(\"../canvas.js\").StrokeState}\n     */\n    this.strokeState_ = null;\n\n    /**\n     * @private\n     * @type {import('../../DataTile.js').ImageLike}\n     */\n    this.image_ = null;\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.imageAnchorX_ = 0;\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.imageAnchorY_ = 0;\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.imageHeight_ = 0;\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.imageOpacity_ = 0;\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.imageOriginX_ = 0;\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.imageOriginY_ = 0;\n\n    /**\n     * @private\n     * @type {boolean}\n     */\n    this.imageRotateWithView_ = false;\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.imageRotation_ = 0;\n\n    /**\n     * @private\n     * @type {import(\"../../size.js\").Size}\n     */\n    this.imageScale_ = [0, 0];\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.imageWidth_ = 0;\n\n    /**\n     * @private\n     * @type {string}\n     */\n    this.text_ = '';\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.textOffsetX_ = 0;\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.textOffsetY_ = 0;\n\n    /**\n     * @private\n     * @type {boolean}\n     */\n    this.textRotateWithView_ = false;\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.textRotation_ = 0;\n\n    /**\n     * @private\n     * @type {import(\"../../size.js\").Size}\n     */\n    this.textScale_ = [0, 0];\n\n    /**\n     * @private\n     * @type {?import(\"../canvas.js\").FillState}\n     */\n    this.textFillState_ = null;\n\n    /**\n     * @private\n     * @type {?import(\"../canvas.js\").StrokeState}\n     */\n    this.textStrokeState_ = null;\n\n    /**\n     * @private\n     * @type {?import(\"../canvas.js\").TextState}\n     */\n    this.textState_ = null;\n\n    /**\n     * @private\n     * @type {Array<number>}\n     */\n    this.pixelCoordinates_ = [];\n\n    /**\n     * @private\n     * @type {import(\"../../transform.js\").Transform}\n     */\n    this.tmpLocalTransform_ = createTransform();\n  }\n\n  /**\n   * @param {Array<number>} flatCoordinates Flat coordinates.\n   * @param {number} offset Offset.\n   * @param {number} end End.\n   * @param {number} stride Stride.\n   * @private\n   */\n  drawImages_(flatCoordinates, offset, end, stride) {\n    if (!this.image_) {\n      return;\n    }\n    const pixelCoordinates = transform2D(\n      flatCoordinates,\n      offset,\n      end,\n      stride,\n      this.transform_,\n      this.pixelCoordinates_,\n    );\n    const context = this.context_;\n    const localTransform = this.tmpLocalTransform_;\n    const alpha = context.globalAlpha;\n    if (this.imageOpacity_ != 1) {\n      context.globalAlpha = alpha * this.imageOpacity_;\n    }\n    let rotation = this.imageRotation_;\n    if (this.transformRotation_ === 0) {\n      rotation -= this.viewRotation_;\n    }\n    if (this.imageRotateWithView_) {\n      rotation += this.viewRotation_;\n    }\n    for (let i = 0, ii = pixelCoordinates.length; i < ii; i += 2) {\n      const x = pixelCoordinates[i] - this.imageAnchorX_;\n      const y = pixelCoordinates[i + 1] - this.imageAnchorY_;\n      if (\n        rotation !== 0 ||\n        this.imageScale_[0] != 1 ||\n        this.imageScale_[1] != 1\n      ) {\n        const centerX = x + this.imageAnchorX_;\n        const centerY = y + this.imageAnchorY_;\n        composeTransform(\n          localTransform,\n          centerX,\n          centerY,\n          1,\n          1,\n          rotation,\n          -centerX,\n          -centerY,\n        );\n        context.save();\n        context.transform.apply(context, localTransform);\n        context.translate(centerX, centerY);\n        context.scale(this.imageScale_[0], this.imageScale_[1]);\n        context.drawImage(\n          this.image_,\n          this.imageOriginX_,\n          this.imageOriginY_,\n          this.imageWidth_,\n          this.imageHeight_,\n          -this.imageAnchorX_,\n          -this.imageAnchorY_,\n          this.imageWidth_,\n          this.imageHeight_,\n        );\n        context.restore();\n      } else {\n        context.drawImage(\n          this.image_,\n          this.imageOriginX_,\n          this.imageOriginY_,\n          this.imageWidth_,\n          this.imageHeight_,\n          x,\n          y,\n          this.imageWidth_,\n          this.imageHeight_,\n        );\n      }\n    }\n    if (this.imageOpacity_ != 1) {\n      context.globalAlpha = alpha;\n    }\n  }\n\n  /**\n   * @param {Array<number>} flatCoordinates Flat coordinates.\n   * @param {number} offset Offset.\n   * @param {number} end End.\n   * @param {number} stride Stride.\n   * @private\n   */\n  drawText_(flatCoordinates, offset, end, stride) {\n    if (!this.textState_ || this.text_ === '') {\n      return;\n    }\n    if (this.textFillState_) {\n      this.setContextFillState_(this.textFillState_);\n    }\n    if (this.textStrokeState_) {\n      this.setContextStrokeState_(this.textStrokeState_);\n    }\n    this.setContextTextState_(this.textState_);\n    const pixelCoordinates = transform2D(\n      flatCoordinates,\n      offset,\n      end,\n      stride,\n      this.transform_,\n      this.pixelCoordinates_,\n    );\n    const context = this.context_;\n    let rotation = this.textRotation_;\n    if (this.transformRotation_ === 0) {\n      rotation -= this.viewRotation_;\n    }\n    if (this.textRotateWithView_) {\n      rotation += this.viewRotation_;\n    }\n    for (; offset < end; offset += stride) {\n      const x = pixelCoordinates[offset] + this.textOffsetX_;\n      const y = pixelCoordinates[offset + 1] + this.textOffsetY_;\n      if (\n        rotation !== 0 ||\n        this.textScale_[0] != 1 ||\n        this.textScale_[1] != 1\n      ) {\n        context.save();\n        context.translate(x - this.textOffsetX_, y - this.textOffsetY_);\n        context.rotate(rotation);\n        context.translate(this.textOffsetX_, this.textOffsetY_);\n        context.scale(this.textScale_[0], this.textScale_[1]);\n        if (this.textStrokeState_) {\n          context.strokeText(this.text_, 0, 0);\n        }\n        if (this.textFillState_) {\n          context.fillText(this.text_, 0, 0);\n        }\n        context.restore();\n      } else {\n        if (this.textStrokeState_) {\n          context.strokeText(this.text_, x, y);\n        }\n        if (this.textFillState_) {\n          context.fillText(this.text_, x, y);\n        }\n      }\n    }\n  }\n\n  /**\n   * @param {Array<number>} flatCoordinates Flat coordinates.\n   * @param {number} offset Offset.\n   * @param {number} end End.\n   * @param {number} stride Stride.\n   * @param {boolean} close Close.\n   * @param {number} [strokeOffset] Stroke Offset.\n   * @private\n   * @return {number} end End.\n   */\n  moveToLineTo_(flatCoordinates, offset, end, stride, close, strokeOffset) {\n    const context = this.context_;\n    let pixelCoordinates = transform2D(\n      flatCoordinates,\n      offset,\n      end,\n      stride,\n      this.transform_,\n      this.pixelCoordinates_,\n    );\n    if (Math.abs(strokeOffset) > 0) {\n      pixelCoordinates = offsetLineString(\n        pixelCoordinates,\n        0,\n        pixelCoordinates.length,\n        2,\n        strokeOffset,\n        close,\n        pixelCoordinates,\n      );\n      removeOffsetCycles(pixelCoordinates, 2);\n    }\n    context.moveTo(pixelCoordinates[0], pixelCoordinates[1]);\n    let length = pixelCoordinates.length;\n    if (close) {\n      length -= 2;\n    }\n    for (let i = 2; i < length; i += 2) {\n      context.lineTo(pixelCoordinates[i], pixelCoordinates[i + 1]);\n    }\n    if (close) {\n      context.closePath();\n    }\n    return end;\n  }\n\n  /**\n   * @param {Array<number>} flatCoordinates Flat coordinates.\n   * @param {number} offset Offset.\n   * @param {Array<number>} ends Ends.\n   * @param {number} stride Stride.\n   * @param {number} [strokeOffset] Stroke Offset.\n   * @private\n   * @return {number} End.\n   */\n  drawRings_(flatCoordinates, offset, ends, stride, strokeOffset) {\n    for (let i = 0, ii = ends.length; i < ii; ++i) {\n      offset = this.moveToLineTo_(\n        flatCoordinates,\n        offset,\n        ends[i],\n        stride,\n        true,\n        strokeOffset,\n      );\n    }\n    return offset;\n  }\n\n  /**\n   * Render a circle geometry into the canvas.  Rendering is immediate and uses\n   * the current fill and stroke styles.\n   *\n   * @param {import(\"../../geom/Circle.js\").default} geometry Circle geometry.\n   * @api\n   * @override\n   */\n  drawCircle(geometry) {\n    if (this.squaredTolerance_) {\n      geometry = /** @type {import(\"../../geom/Circle.js\").default} */ (\n        geometry.simplifyTransformed(\n          this.squaredTolerance_,\n          this.userTransform_,\n        )\n      );\n    }\n    if (!intersects(this.extent_, geometry.getExtent())) {\n      return;\n    }\n    if (this.fillState_ || this.strokeState_) {\n      if (this.fillState_) {\n        this.setContextFillState_(this.fillState_);\n      }\n      if (this.strokeState_) {\n        this.setContextStrokeState_(this.strokeState_);\n      }\n      const pixelCoordinates = transformGeom2D(\n        geometry,\n        this.transform_,\n        this.pixelCoordinates_,\n      );\n      const dx = pixelCoordinates[2] - pixelCoordinates[0];\n      const dy = pixelCoordinates[3] - pixelCoordinates[1];\n      const radius = Math.sqrt(dx * dx + dy * dy);\n      const context = this.context_;\n      context.beginPath();\n      context.arc(\n        pixelCoordinates[0],\n        pixelCoordinates[1],\n        radius,\n        0,\n        2 * Math.PI,\n      );\n      if (this.fillState_) {\n        context.fill();\n      }\n      if (this.strokeState_) {\n        context.stroke();\n      }\n    }\n    if (this.text_ !== '') {\n      this.drawText_(geometry.getCenter(), 0, 2, 2);\n    }\n  }\n\n  /**\n   * Set the rendering style.  Note that since this is an immediate rendering API,\n   * any `zIndex` on the provided style will be ignored.\n   *\n   * @param {import(\"../../style/Style.js\").default} style The rendering style.\n   * @api\n   * @override\n   */\n  setStyle(style) {\n    this.setFillStrokeStyle(style.getFill(), style.getStroke());\n    this.setImageStyle(style.getImage());\n    this.setTextStyle(style.getText());\n  }\n\n  /**\n   * @param {import(\"../../transform.js\").Transform} transform Transform.\n   */\n  setTransform(transform) {\n    this.transform_ = transform;\n  }\n\n  /**\n   * Render a geometry into the canvas.  Call\n   * {@link module:ol/render/canvas/Immediate~CanvasImmediateRenderer#setStyle renderer.setStyle()} first to set the rendering style.\n   *\n   * @param {import(\"../../geom/Geometry.js\").default|import(\"../Feature.js\").default} geometry The geometry to render.\n   * @api\n   * @override\n   */\n  drawGeometry(geometry) {\n    const type = geometry.getType();\n    switch (type) {\n      case 'Point':\n        this.drawPoint(\n          /** @type {import(\"../../geom/Point.js\").default} */ (geometry),\n        );\n        break;\n      case 'LineString':\n        this.drawLineString(\n          /** @type {import(\"../../geom/LineString.js\").default} */ (geometry),\n        );\n        break;\n      case 'Polygon':\n        this.drawPolygon(\n          /** @type {import(\"../../geom/Polygon.js\").default} */ (geometry),\n        );\n        break;\n      case 'MultiPoint':\n        this.drawMultiPoint(\n          /** @type {import(\"../../geom/MultiPoint.js\").default} */ (geometry),\n        );\n        break;\n      case 'MultiLineString':\n        this.drawMultiLineString(\n          /** @type {import(\"../../geom/MultiLineString.js\").default} */ (\n            geometry\n          ),\n        );\n        break;\n      case 'MultiPolygon':\n        this.drawMultiPolygon(\n          /** @type {import(\"../../geom/MultiPolygon.js\").default} */ (\n            geometry\n          ),\n        );\n        break;\n      case 'GeometryCollection':\n        this.drawGeometryCollection(\n          /** @type {import(\"../../geom/GeometryCollection.js\").default} */ (\n            geometry\n          ),\n        );\n        break;\n      case 'Circle':\n        this.drawCircle(\n          /** @type {import(\"../../geom/Circle.js\").default} */ (geometry),\n        );\n        break;\n      default:\n    }\n  }\n\n  /**\n   * Render a feature into the canvas.  Note that any `zIndex` on the provided\n   * style will be ignored - features are rendered immediately in the order that\n   * this method is called.  If you need `zIndex` support, you should be using an\n   * {@link module:ol/layer/Vector~VectorLayer} instead.\n   *\n   * @param {import(\"../../Feature.js\").default} feature Feature.\n   * @param {import(\"../../style/Style.js\").default} style Style.\n   * @api\n   * @override\n   */\n  drawFeature(feature, style) {\n    const geometry = style.getGeometryFunction()(feature);\n    if (!geometry) {\n      return;\n    }\n    this.setStyle(style);\n    this.drawGeometry(geometry);\n  }\n\n  /**\n   * Render a GeometryCollection to the canvas.  Rendering is immediate and\n   * uses the current styles appropriate for each geometry in the collection.\n   *\n   * @param {import(\"../../geom/GeometryCollection.js\").default} geometry Geometry collection.\n   * @override\n   */\n  drawGeometryCollection(geometry) {\n    const geometries = geometry.getGeometriesArray();\n    for (let i = 0, ii = geometries.length; i < ii; ++i) {\n      this.drawGeometry(geometries[i]);\n    }\n  }\n\n  /**\n   * Render a Point geometry into the canvas.  Rendering is immediate and uses\n   * the current style.\n   *\n   * @param {import(\"../../geom/Point.js\").default|import(\"../Feature.js\").default} geometry Point geometry.\n   * @override\n   */\n  drawPoint(geometry) {\n    if (this.squaredTolerance_) {\n      geometry = /** @type {import(\"../../geom/Point.js\").default} */ (\n        geometry.simplifyTransformed(\n          this.squaredTolerance_,\n          this.userTransform_,\n        )\n      );\n    }\n    const flatCoordinates = geometry.getFlatCoordinates();\n    const stride = geometry.getStride();\n    if (this.image_) {\n      this.drawImages_(flatCoordinates, 0, flatCoordinates.length, stride);\n    }\n    if (this.text_ !== '') {\n      this.drawText_(flatCoordinates, 0, flatCoordinates.length, stride);\n    }\n  }\n\n  /**\n   * Render a MultiPoint geometry  into the canvas.  Rendering is immediate and\n   * uses the current style.\n   *\n   * @param {import(\"../../geom/MultiPoint.js\").default|import(\"../Feature.js\").default} geometry MultiPoint geometry.\n   * @override\n   */\n  drawMultiPoint(geometry) {\n    if (this.squaredTolerance_) {\n      geometry = /** @type {import(\"../../geom/MultiPoint.js\").default} */ (\n        geometry.simplifyTransformed(\n          this.squaredTolerance_,\n          this.userTransform_,\n        )\n      );\n    }\n    const flatCoordinates = geometry.getFlatCoordinates();\n    const stride = geometry.getStride();\n    if (this.image_) {\n      this.drawImages_(flatCoordinates, 0, flatCoordinates.length, stride);\n    }\n    if (this.text_ !== '') {\n      this.drawText_(flatCoordinates, 0, flatCoordinates.length, stride);\n    }\n  }\n\n  /**\n   * Render a LineString into the canvas.  Rendering is immediate and uses\n   * the current style.\n   *\n   * @param {import(\"../../geom/LineString.js\").default|import(\"../Feature.js\").default} geometry LineString geometry.\n   * @override\n   */\n  drawLineString(geometry) {\n    if (this.squaredTolerance_) {\n      geometry = /** @type {import(\"../../geom/LineString.js\").default} */ (\n        geometry.simplifyTransformed(\n          this.squaredTolerance_,\n          this.userTransform_,\n        )\n      );\n    }\n    if (!intersects(this.extent_, geometry.getExtent())) {\n      return;\n    }\n    if (this.strokeState_) {\n      this.setContextStrokeState_(this.strokeState_);\n      const context = this.context_;\n      const flatCoordinates = geometry.getFlatCoordinates();\n      context.beginPath();\n      this.moveToLineTo_(\n        flatCoordinates,\n        0,\n        flatCoordinates.length,\n        geometry.getStride(),\n        false,\n        this.strokeState_.strokeOffset,\n      );\n      context.stroke();\n    }\n    if (this.text_ !== '') {\n      const flatMidpoint = geometry.getFlatMidpoint();\n      this.drawText_(flatMidpoint, 0, 2, 2);\n    }\n  }\n\n  /**\n   * Render a MultiLineString geometry into the canvas.  Rendering is immediate\n   * and uses the current style.\n   *\n   * @param {import(\"../../geom/MultiLineString.js\").default|import(\"../Feature.js\").default} geometry MultiLineString geometry.\n   * @override\n   */\n  drawMultiLineString(geometry) {\n    if (this.squaredTolerance_) {\n      geometry =\n        /** @type {import(\"../../geom/MultiLineString.js\").default} */ (\n          geometry.simplifyTransformed(\n            this.squaredTolerance_,\n            this.userTransform_,\n          )\n        );\n    }\n    const geometryExtent = geometry.getExtent();\n    if (!intersects(this.extent_, geometryExtent)) {\n      return;\n    }\n    if (this.strokeState_) {\n      this.setContextStrokeState_(this.strokeState_);\n      const context = this.context_;\n      const flatCoordinates = geometry.getFlatCoordinates();\n      let offset = 0;\n      const ends = /** @type {Array<number>} */ (geometry.getEnds());\n      const stride = geometry.getStride();\n      context.beginPath();\n      for (let i = 0, ii = ends.length; i < ii; ++i) {\n        offset = this.moveToLineTo_(\n          flatCoordinates,\n          offset,\n          ends[i],\n          stride,\n          false,\n          this.strokeState_.strokeOffset,\n        );\n      }\n      context.stroke();\n    }\n    if (this.text_ !== '') {\n      const flatMidpoints = geometry.getFlatMidpoints();\n      this.drawText_(flatMidpoints, 0, flatMidpoints.length, 2);\n    }\n  }\n\n  /**\n   * Render a Polygon geometry into the canvas.  Rendering is immediate and uses\n   * the current style.\n   *\n   * @param {import(\"../../geom/Polygon.js\").default|import(\"../Feature.js\").default} geometry Polygon geometry.\n   * @override\n   */\n  drawPolygon(geometry) {\n    if (this.squaredTolerance_) {\n      geometry = /** @type {import(\"../../geom/Polygon.js\").default} */ (\n        geometry.simplifyTransformed(\n          this.squaredTolerance_,\n          this.userTransform_,\n        )\n      );\n    }\n    if (!intersects(this.extent_, geometry.getExtent())) {\n      return;\n    }\n    if (this.strokeState_ || this.fillState_) {\n      if (this.fillState_) {\n        this.setContextFillState_(this.fillState_);\n      }\n      if (this.strokeState_) {\n        this.setContextStrokeState_(this.strokeState_);\n      }\n      const context = this.context_;\n      context.beginPath();\n      this.drawRings_(\n        geometry.getOrientedFlatCoordinates(),\n        0,\n        /** @type {Array<number>} */ (geometry.getEnds()),\n        geometry.getStride(),\n        this.strokeState_?.strokeOffset,\n      );\n      if (this.fillState_) {\n        context.fill();\n      }\n      if (this.strokeState_) {\n        context.stroke();\n      }\n    }\n    if (this.text_ !== '') {\n      const flatInteriorPoint = geometry.getFlatInteriorPoint();\n      this.drawText_(flatInteriorPoint, 0, 2, 2);\n    }\n  }\n\n  /**\n   * Render MultiPolygon geometry into the canvas.  Rendering is immediate and\n   * uses the current style.\n   * @param {import(\"../../geom/MultiPolygon.js\").default} geometry MultiPolygon geometry.\n   * @override\n   */\n  drawMultiPolygon(geometry) {\n    if (this.squaredTolerance_) {\n      geometry = /** @type {import(\"../../geom/MultiPolygon.js\").default} */ (\n        geometry.simplifyTransformed(\n          this.squaredTolerance_,\n          this.userTransform_,\n        )\n      );\n    }\n    if (!intersects(this.extent_, geometry.getExtent())) {\n      return;\n    }\n    if (this.strokeState_ || this.fillState_) {\n      if (this.fillState_) {\n        this.setContextFillState_(this.fillState_);\n      }\n      if (this.strokeState_) {\n        this.setContextStrokeState_(this.strokeState_);\n      }\n      const context = this.context_;\n      const flatCoordinates = geometry.getOrientedFlatCoordinates();\n      let offset = 0;\n      const endss = geometry.getEndss();\n      const stride = geometry.getStride();\n      context.beginPath();\n      for (let i = 0, ii = endss.length; i < ii; ++i) {\n        const ends = endss[i];\n        offset = this.drawRings_(\n          flatCoordinates,\n          offset,\n          ends,\n          stride,\n          this.strokeState_?.strokeOffset,\n        );\n      }\n      if (this.fillState_) {\n        context.fill();\n      }\n      if (this.strokeState_) {\n        context.stroke();\n      }\n    }\n    if (this.text_ !== '') {\n      const flatInteriorPoints = geometry.getFlatInteriorPoints();\n      this.drawText_(flatInteriorPoints, 0, flatInteriorPoints.length, 2);\n    }\n  }\n\n  /**\n   * @param {import(\"../canvas.js\").FillState} fillState Fill state.\n   * @private\n   */\n  setContextFillState_(fillState) {\n    const context = this.context_;\n    const contextFillState = this.contextFillState_;\n    if (!contextFillState) {\n      context.fillStyle = fillState.fillStyle;\n      this.contextFillState_ = {\n        fillStyle: fillState.fillStyle,\n      };\n    } else {\n      if (contextFillState.fillStyle != fillState.fillStyle) {\n        contextFillState.fillStyle = fillState.fillStyle;\n        context.fillStyle = fillState.fillStyle;\n      }\n    }\n  }\n\n  /**\n   * @param {import(\"../canvas.js\").StrokeState} strokeState Stroke state.\n   * @private\n   */\n  setContextStrokeState_(strokeState) {\n    const context = this.context_;\n    const contextStrokeState = this.contextStrokeState_;\n    if (!contextStrokeState) {\n      context.lineCap = strokeState.lineCap;\n      context.setLineDash(strokeState.lineDash);\n      context.lineDashOffset = strokeState.lineDashOffset;\n      context.lineJoin = strokeState.lineJoin;\n      context.lineWidth = strokeState.lineWidth;\n      context.miterLimit = strokeState.miterLimit;\n      context.strokeStyle = strokeState.strokeStyle;\n      this.contextStrokeState_ = {\n        lineCap: strokeState.lineCap,\n        lineDash: strokeState.lineDash,\n        lineDashOffset: strokeState.lineDashOffset,\n        lineJoin: strokeState.lineJoin,\n        lineWidth: strokeState.lineWidth,\n        miterLimit: strokeState.miterLimit,\n        strokeStyle: strokeState.strokeStyle,\n      };\n    } else {\n      if (contextStrokeState.lineCap != strokeState.lineCap) {\n        contextStrokeState.lineCap = strokeState.lineCap;\n        context.lineCap = strokeState.lineCap;\n      }\n      if (!equals(contextStrokeState.lineDash, strokeState.lineDash)) {\n        context.setLineDash(\n          (contextStrokeState.lineDash = strokeState.lineDash),\n        );\n      }\n      if (contextStrokeState.lineDashOffset != strokeState.lineDashOffset) {\n        contextStrokeState.lineDashOffset = strokeState.lineDashOffset;\n        context.lineDashOffset = strokeState.lineDashOffset;\n      }\n      if (contextStrokeState.lineJoin != strokeState.lineJoin) {\n        contextStrokeState.lineJoin = strokeState.lineJoin;\n        context.lineJoin = strokeState.lineJoin;\n      }\n      if (contextStrokeState.lineWidth != strokeState.lineWidth) {\n        contextStrokeState.lineWidth = strokeState.lineWidth;\n        context.lineWidth = strokeState.lineWidth;\n      }\n      if (contextStrokeState.miterLimit != strokeState.miterLimit) {\n        contextStrokeState.miterLimit = strokeState.miterLimit;\n        context.miterLimit = strokeState.miterLimit;\n      }\n      if (contextStrokeState.strokeStyle != strokeState.strokeStyle) {\n        contextStrokeState.strokeStyle = strokeState.strokeStyle;\n        context.strokeStyle = strokeState.strokeStyle;\n      }\n    }\n  }\n\n  /**\n   * @param {import(\"../canvas.js\").TextState} textState Text state.\n   * @private\n   */\n  setContextTextState_(textState) {\n    const context = this.context_;\n    const contextTextState = this.contextTextState_;\n    const textAlign = textState.textAlign\n      ? textState.textAlign\n      : defaultTextAlign;\n    if (!contextTextState) {\n      context.font = textState.font;\n      context.textAlign = textAlign;\n      context.textBaseline = textState.textBaseline;\n      this.contextTextState_ = {\n        font: textState.font,\n        textAlign: textAlign,\n        textBaseline: textState.textBaseline,\n      };\n    } else {\n      if (contextTextState.font != textState.font) {\n        contextTextState.font = textState.font;\n        context.font = textState.font;\n      }\n      if (contextTextState.textAlign != textAlign) {\n        contextTextState.textAlign = textAlign;\n        context.textAlign = textAlign;\n      }\n      if (contextTextState.textBaseline != textState.textBaseline) {\n        contextTextState.textBaseline = textState.textBaseline;\n        context.textBaseline = textState.textBaseline;\n      }\n    }\n  }\n\n  /**\n   * Set the fill and stroke style for subsequent draw operations.  To clear\n   * either fill or stroke styles, pass null for the appropriate parameter.\n   *\n   * @param {import(\"../../style/Fill.js\").default} fillStyle Fill style.\n   * @param {import(\"../../style/Stroke.js\").default} strokeStyle Stroke style.\n   * @override\n   */\n  setFillStrokeStyle(fillStyle, strokeStyle) {\n    if (!fillStyle) {\n      this.fillState_ = null;\n    } else {\n      const fillStyleColor = fillStyle.getColor();\n      this.fillState_ = {\n        fillStyle: asColorLike(\n          fillStyleColor ? fillStyleColor : defaultFillStyle,\n        ),\n      };\n    }\n    if (!strokeStyle) {\n      this.strokeState_ = null;\n    } else {\n      const strokeStyleColor = strokeStyle.getColor();\n      const strokeStyleLineCap = strokeStyle.getLineCap();\n      const strokeStyleLineDash = strokeStyle.getLineDash();\n      const strokeStyleLineDashOffset = strokeStyle.getLineDashOffset();\n      const strokeStyleLineJoin = strokeStyle.getLineJoin();\n      const strokeStyleWidth = strokeStyle.getWidth();\n      const strokeStyleMiterLimit = strokeStyle.getMiterLimit();\n      const lineDash = strokeStyleLineDash\n        ? strokeStyleLineDash\n        : defaultLineDash;\n      const strokeOffset = strokeStyle.getOffset();\n      this.strokeState_ = {\n        lineCap:\n          strokeStyleLineCap !== undefined\n            ? strokeStyleLineCap\n            : defaultLineCap,\n        lineDash:\n          this.pixelRatio_ === 1\n            ? lineDash\n            : lineDash.map((n) => n * this.pixelRatio_),\n        lineDashOffset:\n          (strokeStyleLineDashOffset\n            ? strokeStyleLineDashOffset\n            : defaultLineDashOffset) * this.pixelRatio_,\n        lineJoin:\n          strokeStyleLineJoin !== undefined\n            ? strokeStyleLineJoin\n            : defaultLineJoin,\n        lineWidth:\n          (strokeStyleWidth !== undefined\n            ? strokeStyleWidth\n            : defaultLineWidth) * this.pixelRatio_,\n        miterLimit:\n          strokeStyleMiterLimit !== undefined\n            ? strokeStyleMiterLimit\n            : defaultMiterLimit,\n        strokeStyle: asColorLike(\n          strokeStyleColor ? strokeStyleColor : defaultStrokeStyle,\n        ),\n        strokeOffset: (strokeOffset ?? 0) * this.pixelRatio_,\n      };\n    }\n  }\n\n  /**\n   * Set the image style for subsequent draw operations.  Pass null to remove\n   * the image style.\n   *\n   * @param {import(\"../../style/Image.js\").default} imageStyle Image style.\n   * @override\n   */\n  setImageStyle(imageStyle) {\n    let imageSize;\n    if (!imageStyle || !(imageSize = imageStyle.getSize())) {\n      this.image_ = null;\n      return;\n    }\n    const imagePixelRatio = imageStyle.getPixelRatio(this.pixelRatio_);\n    const imageAnchor = imageStyle.getAnchor();\n    const imageOrigin = imageStyle.getOrigin();\n    this.image_ = imageStyle.getImage(this.pixelRatio_);\n    this.imageAnchorX_ = imageAnchor[0] * imagePixelRatio;\n    this.imageAnchorY_ = imageAnchor[1] * imagePixelRatio;\n    this.imageHeight_ = imageSize[1] * imagePixelRatio;\n    this.imageOpacity_ = imageStyle.getOpacity();\n    this.imageOriginX_ = imageOrigin[0];\n    this.imageOriginY_ = imageOrigin[1];\n    this.imageRotateWithView_ = imageStyle.getRotateWithView();\n    this.imageRotation_ = imageStyle.getRotation();\n    const imageScale = imageStyle.getScaleArray();\n    this.imageScale_ = [\n      (imageScale[0] * this.pixelRatio_) / imagePixelRatio,\n      (imageScale[1] * this.pixelRatio_) / imagePixelRatio,\n    ];\n    this.imageWidth_ = imageSize[0] * imagePixelRatio;\n  }\n\n  /**\n   * Set the text style for subsequent draw operations.  Pass null to\n   * remove the text style.\n   *\n   * @param {import(\"../../style/Text.js\").default} textStyle Text style.\n   * @override\n   */\n  setTextStyle(textStyle) {\n    if (!textStyle) {\n      this.text_ = '';\n    } else {\n      const textFillStyle = textStyle.getFill();\n      if (!textFillStyle) {\n        this.textFillState_ = null;\n      } else {\n        const textFillStyleColor = textFillStyle.getColor();\n        this.textFillState_ = {\n          fillStyle: asColorLike(\n            textFillStyleColor ? textFillStyleColor : defaultFillStyle,\n          ),\n        };\n      }\n      const textStrokeStyle = textStyle.getStroke();\n      if (!textStrokeStyle) {\n        this.textStrokeState_ = null;\n      } else {\n        const textStrokeStyleColor = textStrokeStyle.getColor();\n        const textStrokeStyleLineCap = textStrokeStyle.getLineCap();\n        const textStrokeStyleLineDash = textStrokeStyle.getLineDash();\n        const textStrokeStyleLineDashOffset =\n          textStrokeStyle.getLineDashOffset();\n        const textStrokeStyleLineJoin = textStrokeStyle.getLineJoin();\n        const textStrokeStyleWidth = textStrokeStyle.getWidth();\n        const textStrokeStyleMiterLimit = textStrokeStyle.getMiterLimit();\n        this.textStrokeState_ = {\n          lineCap:\n            textStrokeStyleLineCap !== undefined\n              ? textStrokeStyleLineCap\n              : defaultLineCap,\n          lineDash: textStrokeStyleLineDash\n            ? textStrokeStyleLineDash\n            : defaultLineDash,\n          lineDashOffset: textStrokeStyleLineDashOffset\n            ? textStrokeStyleLineDashOffset\n            : defaultLineDashOffset,\n          lineJoin:\n            textStrokeStyleLineJoin !== undefined\n              ? textStrokeStyleLineJoin\n              : defaultLineJoin,\n          lineWidth:\n            textStrokeStyleWidth !== undefined\n              ? textStrokeStyleWidth\n              : defaultLineWidth,\n          miterLimit:\n            textStrokeStyleMiterLimit !== undefined\n              ? textStrokeStyleMiterLimit\n              : defaultMiterLimit,\n          strokeStyle: asColorLike(\n            textStrokeStyleColor ? textStrokeStyleColor : defaultStrokeStyle,\n          ),\n        };\n      }\n      const textFont = textStyle.getFont();\n      const textOffsetX = textStyle.getOffsetX();\n      const textOffsetY = textStyle.getOffsetY();\n      const textRotateWithView = textStyle.getRotateWithView();\n      const textRotation = textStyle.getRotation();\n      const textScale = textStyle.getScaleArray();\n      const textText = textStyle.getText();\n      const textTextAlign = textStyle.getTextAlign();\n      const textTextBaseline = textStyle.getTextBaseline();\n      this.textState_ = {\n        font: textFont !== undefined ? textFont : defaultFont,\n        textAlign:\n          textTextAlign !== undefined ? textTextAlign : defaultTextAlign,\n        textBaseline:\n          textTextBaseline !== undefined\n            ? textTextBaseline\n            : defaultTextBaseline,\n      };\n      this.text_ =\n        textText !== undefined\n          ? Array.isArray(textText)\n            ? textText.reduce((acc, t, i) => (acc += i % 2 ? ' ' : t), '')\n            : textText\n          : '';\n      this.textOffsetX_ =\n        textOffsetX !== undefined ? this.pixelRatio_ * textOffsetX : 0;\n      this.textOffsetY_ =\n        textOffsetY !== undefined ? this.pixelRatio_ * textOffsetY : 0;\n      this.textRotateWithView_ =\n        textRotateWithView !== undefined ? textRotateWithView : false;\n      this.textRotation_ = textRotation !== undefined ? textRotation : 0;\n      this.textScale_ = [\n        this.pixelRatio_ * textScale[0],\n        this.pixelRatio_ * textScale[1],\n      ];\n    }\n  }\n}\n\nexport default CanvasImmediateRenderer;\n", "/**\n * @module ol/render/canvas/hitdetect\n */\n\nimport {ascending} from '../../array.js';\nimport {createCanvasContext2D} from '../../dom.js';\nimport {intersects} from '../../extent.js';\nimport {clamp} from '../../math.js';\nimport {\n  getTransformFromProjections,\n  getUserProjection,\n  toUserExtent,\n} from '../../proj.js';\nimport Icon from '../../style/Icon.js';\nimport CanvasImmediateRenderer from './Immediate.js';\n\nexport const HIT_DETECT_RESOLUTION = 0.5;\n\n/**\n * @param {import(\"../../size.js\").Size} size Canvas size in css pixels.\n * @param {Array<import(\"../../transform.js\").Transform>} transforms Transforms\n * for rendering features to all worlds of the viewport, from coordinates to css\n * pixels.\n * @param {Array<import(\"../../Feature.js\").FeatureLike>} features\n * Features to consider for hit detection.\n * @param {import(\"../../style/Style.js\").StyleFunction|undefined} styleFunction\n * Layer style function.\n * @param {import(\"../../extent.js\").Extent} extent Extent in render projection.\n * @param {number} resolution Resolution.\n * @param {number} rotation Rotation.\n * @param {number} [squaredTolerance] Squared tolerance.\n * @param {import(\"../../proj/Projection.js\").default} [projection] Render projection.\n * @return {ImageData} Hit detection image data.\n */\nexport function createHitDetectionImageData(\n  size,\n  transforms,\n  features,\n  styleFunction,\n  extent,\n  resolution,\n  rotation,\n  squaredTolerance,\n  projection,\n) {\n  const userExtent = projection ? toUserExtent(extent, projection) : extent;\n  const width = size[0] * HIT_DETECT_RESOLUTION;\n  const height = size[1] * HIT_DETECT_RESOLUTION;\n  const context = createCanvasContext2D(width, height);\n  context.imageSmoothingEnabled = false;\n  const canvas = context.canvas;\n  const renderer = new CanvasImmediateRenderer(\n    context,\n    HIT_DETECT_RESOLUTION,\n    extent,\n    null,\n    rotation,\n    squaredTolerance,\n    projection\n      ? getTransformFromProjections(getUserProjection(), projection)\n      : null,\n  );\n  const featureCount = features.length;\n  // Stretch hit detection index to use the whole available color range\n  const indexFactor = Math.floor((256 * 256 * 256 - 1) / featureCount);\n  const featuresByZIndex = {};\n  for (let i = 1; i <= featureCount; ++i) {\n    const feature = features[i - 1];\n    const featureStyleFunction = feature.getStyleFunction() || styleFunction;\n    if (!featureStyleFunction) {\n      continue;\n    }\n    let styles = featureStyleFunction(feature, resolution);\n    if (!styles) {\n      continue;\n    }\n    if (!Array.isArray(styles)) {\n      styles = [styles];\n    }\n    const index = i * indexFactor;\n    const color = index.toString(16).padStart(7, '#00000');\n    for (let j = 0, jj = styles.length; j < jj; ++j) {\n      const originalStyle = styles[j];\n      const geometry = originalStyle.getGeometryFunction()(feature);\n      if (!geometry || !intersects(userExtent, geometry.getExtent())) {\n        continue;\n      }\n      const style = originalStyle.clone();\n      const fill = style.getFill();\n      if (fill) {\n        fill.setColor(color);\n      }\n      const stroke = style.getStroke();\n      if (stroke) {\n        stroke.setColor(color);\n        stroke.setLineDash(null);\n      }\n      style.setText(undefined);\n      const image = originalStyle.getImage();\n      if (image) {\n        const imgSize = image.getImageSize();\n        if (!imgSize) {\n          continue;\n        }\n\n        const imgContext = createCanvasContext2D(\n          imgSize[0],\n          imgSize[1],\n          undefined,\n          {alpha: false},\n        );\n        const img = imgContext.canvas;\n        imgContext.fillStyle = color;\n        imgContext.fillRect(0, 0, img.width, img.height);\n        style.setImage(\n          new Icon({\n            img: img,\n            anchor: image.getAnchor(),\n            anchorXUnits: 'pixels',\n            anchorYUnits: 'pixels',\n            offset: image.getOrigin(),\n            opacity: 1,\n            size: image.getSize(),\n            scale: image.getScale(),\n            rotation: image.getRotation(),\n            rotateWithView: image.getRotateWithView(),\n          }),\n        );\n      }\n      const zIndex = style.getZIndex() || 0;\n      let byGeometryType = featuresByZIndex[zIndex];\n      if (!byGeometryType) {\n        byGeometryType = {};\n        featuresByZIndex[zIndex] = byGeometryType;\n        byGeometryType['Polygon'] = [];\n        byGeometryType['Circle'] = [];\n        byGeometryType['LineString'] = [];\n        byGeometryType['Point'] = [];\n      }\n      const type = geometry.getType();\n      if (type === 'GeometryCollection') {\n        const geometries =\n          /** @type {import(\"../../geom/GeometryCollection.js\").default} */ (\n            geometry\n          ).getGeometriesArrayRecursive();\n        for (let i = 0, ii = geometries.length; i < ii; ++i) {\n          const geometry = geometries[i];\n          byGeometryType[geometry.getType().replace('Multi', '')].push(\n            geometry,\n            style,\n          );\n        }\n      } else {\n        byGeometryType[type.replace('Multi', '')].push(geometry, style);\n      }\n    }\n  }\n\n  const zIndexKeys = Object.keys(featuresByZIndex).map(Number).sort(ascending);\n  for (let i = 0, ii = zIndexKeys.length; i < ii; ++i) {\n    const byGeometryType = featuresByZIndex[zIndexKeys[i]];\n    for (const type in byGeometryType) {\n      const geomAndStyle = byGeometryType[type];\n      for (let j = 0, jj = geomAndStyle.length; j < jj; j += 2) {\n        renderer.setStyle(geomAndStyle[j + 1]);\n        for (let k = 0, kk = transforms.length; k < kk; ++k) {\n          renderer.setTransform(transforms[k]);\n          renderer.drawGeometry(geomAndStyle[j]);\n        }\n      }\n    }\n  }\n  return context.getImageData(0, 0, canvas.width, canvas.height);\n}\n\n/**\n * @param {import(\"../../pixel.js\").Pixel} pixel Pixel coordinate on the hit\n * detection canvas in css pixels.\n * @param {Array<F>} features Features. Has to\n * match the `features` array that was passed to `createHitDetectionImageData()`.\n * @param {ImageData} imageData Hit detection image data generated by\n * `createHitDetectionImageData()`.\n * @return {Array<F>} Features.\n * @template {import(\"../../Feature.js\").FeatureLike} F\n */\nexport function hitDetect(pixel, features, imageData) {\n  /** @type {Array<F>} */\n  const resultFeatures = [];\n  if (imageData) {\n    const x = Math.floor(Math.round(pixel[0]) * HIT_DETECT_RESOLUTION);\n    const y = Math.floor(Math.round(pixel[1]) * HIT_DETECT_RESOLUTION);\n    // The pixel coordinate is clamped down to the hit-detect canvas' size to account\n    // for browsers returning coordinates slightly larger than the actual canvas size\n    // due to a non-integer pixel ratio.\n    const index =\n      (clamp(x, 0, imageData.width - 1) +\n        clamp(y, 0, imageData.height - 1) * imageData.width) *\n      4;\n    const r = imageData.data[index];\n    const g = imageData.data[index + 1];\n    const b = imageData.data[index + 2];\n    const i = b + 256 * (g + 256 * r);\n    const indexFactor = Math.floor((256 * 256 * 256 - 1) / features.length);\n    if (i && i % indexFactor === 0) {\n      resultFeatures.push(features[i / indexFactor - 1]);\n    }\n  }\n  return resultFeatures;\n}\n", "/**\n * @module ol/renderer/vector\n */\nimport ImageState from '../ImageState.js';\nimport {getUid} from '../util.js';\n\n/**\n * Feature callback. The callback will be called with three arguments. The first\n * argument is one {@link module:ol/Feature~Feature feature} or {@link module:ol/render/Feature~RenderFeature render feature}\n * at the pixel, the second is the {@link module:ol/layer/Layer~Layer layer} of the feature and will be null for\n * unmanaged layers. The third is the {@link module:ol/geom/SimpleGeometry~SimpleGeometry} of the feature. For features\n * with a GeometryCollection geometry, it will be the first detected geometry from the collection.\n * @template T\n * @typedef {function(import(\"../Feature.js\").FeatureLike, import(\"../layer/Layer.js\").default<import(\"../source/Source.js\").default>, import(\"../geom/SimpleGeometry.js\").default): T} FeatureCallback\n */\n\n/**\n * Tolerance for geometry simplification in device pixels.\n * @type {number}\n */\nconst SIMPLIFY_TOLERANCE = 0.5;\n\n/**\n * @const\n * @type {Object<import(\"../geom/Geometry.js\").Type,\n *                function(import(\"../render/canvas/BuilderGroup.js\").default, import(\"../geom/Geometry.js\").default,\n *                         import(\"../style/Style.js\").default, Object): void>}\n */\nconst GEOMETRY_RENDERERS = {\n  'Point': renderPointGeometry,\n  'LineString': renderLineStringGeometry,\n  'Polygon': renderPolygonGeometry,\n  'MultiPoint': renderMultiPointGeometry,\n  'MultiLineString': renderMultiLineStringGeometry,\n  'MultiPolygon': renderMultiPolygonGeometry,\n  'GeometryCollection': renderGeometryCollectionGeometry,\n  'Circle': renderCircleGeometry,\n};\n\n/**\n * @param {import(\"../Feature.js\").FeatureLike} feature1 Feature 1.\n * @param {import(\"../Feature.js\").FeatureLike} feature2 Feature 2.\n * @return {number} Order.\n */\nexport function defaultOrder(feature1, feature2) {\n  return parseInt(getUid(feature1), 10) - parseInt(getUid(feature2), 10);\n}\n\n/**\n * @param {number} resolution Resolution.\n * @param {number} pixelRatio Pixel ratio.\n * @return {number} Squared pixel tolerance.\n */\nexport function getSquaredTolerance(resolution, pixelRatio) {\n  const tolerance = getTolerance(resolution, pixelRatio);\n  return tolerance * tolerance;\n}\n\n/**\n * @param {number} resolution Resolution.\n * @param {number} pixelRatio Pixel ratio.\n * @return {number} Pixel tolerance.\n */\nexport function getTolerance(resolution, pixelRatio) {\n  return (SIMPLIFY_TOLERANCE * resolution) / pixelRatio;\n}\n\n/**\n * @param {import(\"../render/canvas/BuilderGroup.js\").default} builderGroup Builder group.\n * @param {import(\"../geom/Circle.js\").default} geometry Geometry.\n * @param {import(\"../style/Style.js\").default} style Style.\n * @param {import(\"../Feature.js\").default} feature Feature.\n * @param {number} [index] Render order index.\n */\nfunction renderCircleGeometry(builderGroup, geometry, style, feature, index) {\n  const fillStyle = style.getFill();\n  const strokeStyle = style.getStroke();\n  if (fillStyle || strokeStyle) {\n    const circleReplay = builderGroup.getBuilder(style.getZIndex(), 'Circle');\n    circleReplay.setFillStrokeStyle(fillStyle, strokeStyle);\n    circleReplay.drawCircle(geometry, feature, index);\n  }\n  const textStyle = style.getText();\n  if (textStyle && textStyle.getText()) {\n    const textReplay = builderGroup.getBuilder(style.getZIndex(), 'Text');\n    textReplay.setTextStyle(textStyle);\n    textReplay.drawText(geometry, feature, index);\n  }\n}\n\n/**\n * @param {import(\"../render/canvas/BuilderGroup.js\").default} replayGroup Replay group.\n * @param {import(\"../Feature.js\").FeatureLike} feature Feature.\n * @param {import(\"../style/Style.js\").default} style Style.\n * @param {number} squaredTolerance Squared tolerance.\n * @param {function(import(\"../events/Event.js\").default): void} listener Listener function.\n * @param {import(\"../proj.js\").TransformFunction} [transform] Transform from user to view projection.\n * @param {boolean} [declutter] Enable decluttering.\n * @param {number} [index] Render order index..\n * @return {boolean} `true` if style is loading.\n */\nexport function renderFeature(\n  replayGroup,\n  feature,\n  style,\n  squaredTolerance,\n  listener,\n  transform,\n  declutter,\n  index,\n) {\n  const loadingPromises = [];\n  const imageStyle = style.getImage();\n  if (imageStyle) {\n    let loading = true;\n    const imageState = imageStyle.getImageState();\n    if (imageState == ImageState.LOADED || imageState == ImageState.ERROR) {\n      loading = false;\n    } else {\n      if (imageState == ImageState.IDLE) {\n        imageStyle.load();\n      }\n    }\n    if (loading) {\n      loadingPromises.push(imageStyle.ready());\n    }\n  }\n  const fillStyle = style.getFill();\n  if (fillStyle && fillStyle.loading()) {\n    loadingPromises.push(fillStyle.ready());\n  }\n  const loading = loadingPromises.length > 0;\n  if (loading) {\n    Promise.all(loadingPromises).then(() => listener(null));\n  }\n  renderFeatureInternal(\n    replayGroup,\n    feature,\n    style,\n    squaredTolerance,\n    transform,\n    declutter,\n    index,\n  );\n\n  return loading;\n}\n\n/**\n * @param {import(\"../render/canvas/BuilderGroup.js\").default} replayGroup Replay group.\n * @param {import(\"../Feature.js\").FeatureLike} feature Feature.\n * @param {import(\"../style/Style.js\").default} style Style.\n * @param {number} squaredTolerance Squared tolerance.\n * @param {import(\"../proj.js\").TransformFunction} [transform] Optional transform function.\n * @param {boolean} [declutter] Enable decluttering.\n * @param {number} [index] Render order index..\n */\nfunction renderFeatureInternal(\n  replayGroup,\n  feature,\n  style,\n  squaredTolerance,\n  transform,\n  declutter,\n  index,\n) {\n  const geometry = style.getGeometryFunction()(feature);\n  if (!geometry) {\n    return;\n  }\n  const simplifiedGeometry = geometry.simplifyTransformed(\n    squaredTolerance,\n    transform,\n  );\n  const renderer = style.getRenderer();\n  if (renderer) {\n    renderGeometry(replayGroup, simplifiedGeometry, style, feature, index);\n  } else {\n    const geometryRenderer = GEOMETRY_RENDERERS[simplifiedGeometry.getType()];\n    geometryRenderer(\n      replayGroup,\n      simplifiedGeometry,\n      style,\n      feature,\n      index,\n      declutter,\n    );\n  }\n}\n\n/**\n * @param {import(\"../render/canvas/BuilderGroup.js\").default} replayGroup Replay group.\n * @param {import(\"../geom/Geometry.js\").default|import(\"../render/Feature.js\").default} geometry Geometry.\n * @param {import(\"../style/Style.js\").default} style Style.\n * @param {import(\"../Feature.js\").FeatureLike} feature Feature.\n * @param {number} [index] Render order index.\n */\nfunction renderGeometry(replayGroup, geometry, style, feature, index) {\n  if (geometry.getType() == 'GeometryCollection') {\n    const geometries =\n      /** @type {import(\"../geom/GeometryCollection.js\").default} */ (\n        geometry\n      ).getGeometries();\n    for (let i = 0, ii = geometries.length; i < ii; ++i) {\n      renderGeometry(replayGroup, geometries[i], style, feature, index);\n    }\n    return;\n  }\n  const replay = replayGroup.getBuilder(style.getZIndex(), 'Default');\n  replay.drawCustom(\n    /** @type {import(\"../geom/SimpleGeometry.js\").default} */ (geometry),\n    feature,\n    style.getRenderer(),\n    style.getHitDetectionRenderer(),\n    index,\n  );\n}\n\n/**\n * @param {import(\"../render/canvas/BuilderGroup.js\").default} replayGroup Replay group.\n * @param {import(\"../geom/GeometryCollection.js\").default} geometry Geometry.\n * @param {import(\"../style/Style.js\").default} style Style.\n * @param {import(\"../Feature.js\").default} feature Feature.\n * @param {import(\"../render/canvas/BuilderGroup.js\").default} [declutterBuilderGroup] Builder for decluttering.\n * @param {number} [index] Render order index.\n */\nfunction renderGeometryCollectionGeometry(\n  replayGroup,\n  geometry,\n  style,\n  feature,\n  declutterBuilderGroup,\n  index,\n) {\n  const geometries = geometry.getGeometriesArray();\n  let i, ii;\n  for (i = 0, ii = geometries.length; i < ii; ++i) {\n    const geometryRenderer = GEOMETRY_RENDERERS[geometries[i].getType()];\n    geometryRenderer(\n      replayGroup,\n      geometries[i],\n      style,\n      feature,\n      declutterBuilderGroup,\n      index,\n    );\n  }\n}\n\n/**\n * @param {import(\"../render/canvas/BuilderGroup.js\").default} builderGroup Replay group.\n * @param {import(\"../geom/LineString.js\").default|import(\"../render/Feature.js\").default} geometry Geometry.\n * @param {import(\"../style/Style.js\").default} style Style.\n * @param {import(\"../Feature.js\").FeatureLike} feature Feature.\n * @param {number} [index] Render order index.\n */\nfunction renderLineStringGeometry(\n  builderGroup,\n  geometry,\n  style,\n  feature,\n  index,\n) {\n  const strokeStyle = style.getStroke();\n  if (strokeStyle) {\n    const lineStringReplay = builderGroup.getBuilder(\n      style.getZIndex(),\n      'LineString',\n    );\n    lineStringReplay.setFillStrokeStyle(null, strokeStyle);\n    lineStringReplay.drawLineString(geometry, feature, index);\n  }\n  const textStyle = style.getText();\n  if (textStyle && textStyle.getText()) {\n    const textReplay = builderGroup.getBuilder(style.getZIndex(), 'Text');\n    textReplay.setTextStyle(textStyle);\n    textReplay.drawText(geometry, feature, index);\n  }\n}\n\n/**\n * @param {import(\"../render/canvas/BuilderGroup.js\").default} builderGroup Replay group.\n * @param {import(\"../geom/MultiLineString.js\").default|import(\"../render/Feature.js\").default} geometry Geometry.\n * @param {import(\"../style/Style.js\").default} style Style.\n * @param {import(\"../Feature.js\").FeatureLike} feature Feature.\n * @param {number} [index] Render order index.\n */\nfunction renderMultiLineStringGeometry(\n  builderGroup,\n  geometry,\n  style,\n  feature,\n  index,\n) {\n  const strokeStyle = style.getStroke();\n  if (strokeStyle) {\n    const lineStringReplay = builderGroup.getBuilder(\n      style.getZIndex(),\n      'LineString',\n    );\n    lineStringReplay.setFillStrokeStyle(null, strokeStyle);\n    lineStringReplay.drawMultiLineString(geometry, feature, index);\n  }\n  const textStyle = style.getText();\n  if (textStyle && textStyle.getText()) {\n    const textReplay = builderGroup.getBuilder(style.getZIndex(), 'Text');\n    textReplay.setTextStyle(textStyle);\n    textReplay.drawText(geometry, feature, index);\n  }\n}\n\n/**\n * @param {import(\"../render/canvas/BuilderGroup.js\").default} builderGroup Replay group.\n * @param {import(\"../geom/MultiPolygon.js\").default} geometry Geometry.\n * @param {import(\"../style/Style.js\").default} style Style.\n * @param {import(\"../Feature.js\").default} feature Feature.\n * @param {number} [index] Render order index.\n */\nfunction renderMultiPolygonGeometry(\n  builderGroup,\n  geometry,\n  style,\n  feature,\n  index,\n) {\n  const fillStyle = style.getFill();\n  const strokeStyle = style.getStroke();\n  if (strokeStyle || fillStyle) {\n    const polygonReplay = builderGroup.getBuilder(style.getZIndex(), 'Polygon');\n    polygonReplay.setFillStrokeStyle(fillStyle, strokeStyle);\n    polygonReplay.drawMultiPolygon(geometry, feature, index);\n  }\n  const textStyle = style.getText();\n  if (textStyle && textStyle.getText()) {\n    const textReplay = builderGroup.getBuilder(style.getZIndex(), 'Text');\n    textReplay.setTextStyle(textStyle);\n    textReplay.drawText(geometry, feature, index);\n  }\n}\n\n/**\n * @param {import(\"../render/canvas/BuilderGroup.js\").default} builderGroup Replay group.\n * @param {import(\"../geom/Point.js\").default|import(\"../render/Feature.js\").default} geometry Geometry.\n * @param {import(\"../style/Style.js\").default} style Style.\n * @param {import(\"../Feature.js\").FeatureLike} feature Feature.\n * @param {number} [index] Render order index.\n * @param {boolean} [declutter] Enable decluttering.\n */\nfunction renderPointGeometry(\n  builderGroup,\n  geometry,\n  style,\n  feature,\n  index,\n  declutter,\n) {\n  const imageStyle = style.getImage();\n  const textStyle = style.getText();\n  const hasText = textStyle && textStyle.getText();\n  /** @type {import(\"../render/canvas.js\").DeclutterImageWithText} */\n  const declutterImageWithText =\n    declutter && imageStyle && hasText ? {} : undefined;\n  if (imageStyle) {\n    if (imageStyle.getImageState() != ImageState.LOADED) {\n      return;\n    }\n    const imageReplay = builderGroup.getBuilder(style.getZIndex(), 'Image');\n    imageReplay.setImageStyle(imageStyle, declutterImageWithText);\n    imageReplay.drawPoint(geometry, feature, index);\n  }\n  if (hasText) {\n    const textReplay = builderGroup.getBuilder(style.getZIndex(), 'Text');\n    textReplay.setTextStyle(textStyle, declutterImageWithText);\n    textReplay.drawText(geometry, feature, index);\n  }\n}\n\n/**\n * @param {import(\"../render/canvas/BuilderGroup.js\").default} builderGroup Replay group.\n * @param {import(\"../geom/MultiPoint.js\").default|import(\"../render/Feature.js\").default} geometry Geometry.\n * @param {import(\"../style/Style.js\").default} style Style.\n * @param {import(\"../Feature.js\").FeatureLike} feature Feature.\n * @param {number} [index] Render order index.\n * @param {boolean} [declutter] Enable decluttering.\n */\nfunction renderMultiPointGeometry(\n  builderGroup,\n  geometry,\n  style,\n  feature,\n  index,\n  declutter,\n) {\n  const imageStyle = style.getImage();\n  const hasImage = imageStyle && imageStyle.getOpacity() !== 0;\n  const textStyle = style.getText();\n  const hasText = textStyle && textStyle.getText();\n  /** @type {import(\"../render/canvas.js\").DeclutterImageWithText} */\n  const declutterImageWithText =\n    declutter && hasImage && hasText ? {} : undefined;\n  if (hasImage) {\n    if (imageStyle.getImageState() != ImageState.LOADED) {\n      return;\n    }\n    const imageReplay = builderGroup.getBuilder(style.getZIndex(), 'Image');\n    imageReplay.setImageStyle(imageStyle, declutterImageWithText);\n    imageReplay.drawMultiPoint(geometry, feature, index);\n  }\n  if (hasText) {\n    const textReplay = builderGroup.getBuilder(style.getZIndex(), 'Text');\n    textReplay.setTextStyle(textStyle, declutterImageWithText);\n    textReplay.drawText(geometry, feature, index);\n  }\n}\n\n/**\n * @param {import(\"../render/canvas/BuilderGroup.js\").default} builderGroup Replay group.\n * @param {import(\"../geom/Polygon.js\").default|import(\"../render/Feature.js\").default} geometry Geometry.\n * @param {import(\"../style/Style.js\").default} style Style.\n * @param {import(\"../Feature.js\").FeatureLike} feature Feature.\n * @param {number} [index] Render order index.\n */\nfunction renderPolygonGeometry(builderGroup, geometry, style, feature, index) {\n  const fillStyle = style.getFill();\n  const strokeStyle = style.getStroke();\n  if (fillStyle || strokeStyle) {\n    const polygonReplay = builderGroup.getBuilder(style.getZIndex(), 'Polygon');\n    polygonReplay.setFillStrokeStyle(fillStyle, strokeStyle);\n    polygonReplay.drawPolygon(geometry, feature, index);\n  }\n  const textStyle = style.getText();\n  if (textStyle && textStyle.getText()) {\n    const textReplay = builderGroup.getBuilder(style.getZIndex(), 'Text');\n    textReplay.setTextStyle(textStyle);\n    textReplay.drawText(geometry, feature, index);\n  }\n}\n", "/**\n * @module ol/renderer/canvas/VectorLayer\n */\nimport ViewHint from '../../ViewHint.js';\nimport {equals} from '../../array.js';\nimport {wrapX as wrapCoordinateX} from '../../coordinate.js';\nimport {createCanvasContext2D, releaseCanvas} from '../../dom.js';\nimport {\n  buffer,\n  containsExtent,\n  createEmpty,\n  getHeight,\n  getWidth,\n  intersects as intersectsExtent,\n  isEmpty,\n  wrapX as wrapExtentX,\n} from '../../extent.js';\nimport {\n  fromUserExtent,\n  getTransformFromProjections,\n  getUserProjection,\n  toUserExtent,\n  toUserResolution,\n} from '../../proj.js';\nimport RenderEventType from '../../render/EventType.js';\nimport CanvasBuilderGroup from '../../render/canvas/BuilderGroup.js';\nimport ExecutorGroup, {\n  ALL,\n  DECLUTTER,\n  NON_DECLUTTER,\n} from '../../render/canvas/ExecutorGroup.js';\nimport {\n  HIT_DETECT_RESOLUTION,\n  createHitDetectionImageData,\n  hitDetect,\n} from '../../render/canvas/hitdetect.js';\nimport {getUid} from '../../util.js';\nimport {\n  defaultOrder as defaultRenderOrder,\n  getTolerance as getRenderTolerance,\n  getSquaredTolerance as getSquaredRenderTolerance,\n  renderFeature,\n} from '../vector.js';\nimport CanvasLayerRenderer, {canvasPool} from './Layer.js';\n\n/**\n * @classdesc\n * Canvas renderer for vector layers.\n * @api\n */\nclass CanvasVectorLayerRenderer extends CanvasLayerRenderer {\n  /**\n   * @param {import(\"../../layer/BaseVector.js\").default} vectorLayer Vector layer.\n   */\n  constructor(vectorLayer) {\n    super(vectorLayer);\n\n    /** @private */\n    this.boundHandleStyleImageChange_ = this.handleStyleImageChange_.bind(this);\n\n    /**\n     * @private\n     * @type {boolean}\n     */\n    this.animatingOrInteracting_;\n\n    /**\n     * @private\n     * @type {ImageData|null}\n     */\n    this.hitDetectionImageData_ = null;\n\n    /**\n     * @private\n     * @type {import(\"../../extent.js\").Extent}\n     */\n    this.clipExtent_ = null;\n\n    /**\n     * Do we need to extend the rendered area on the x-axis to handle\n     * features that cross the antimeridian?\n     * @private\n     * @type {boolean}\n     */\n    this.extendX_ = false;\n\n    /**\n     * @private\n     * @type {Array<import(\"../../Feature.js\").default>}\n     */\n    this.renderedFeatures_ = null;\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.renderedRevision_ = -1;\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.renderedResolution_ = NaN;\n\n    /**\n     * @private\n     * @type {import(\"../../extent.js\").Extent}\n     */\n    this.renderedExtent_ = createEmpty();\n\n    /**\n     * @private\n     * @type {import(\"../../extent.js\").Extent}\n     */\n    this.wrappedRenderedExtent_ = createEmpty();\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.renderedRotation_;\n\n    /**\n     * @private\n     * @type {import(\"../../coordinate.js\").Coordinate}\n     */\n    this.renderedCenter_ = null;\n\n    /**\n     * @private\n     * @type {import(\"../../proj/Projection.js\").default}\n     */\n    this.renderedProjection_ = null;\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.renderedPixelRatio_ = 1;\n\n    /**\n     * @private\n     * @type {import(\"../../render.js\").OrderFunction|null}\n     */\n    this.renderedRenderOrder_ = null;\n\n    /**\n     * @private\n     * @type {boolean}\n     */\n    this.renderedFrameDeclutter_;\n\n    /**\n     * @private\n     * @type {import(\"../../render/canvas/ExecutorGroup.js\").default}\n     */\n    this.replayGroup_ = null;\n\n    /**\n     * A new replay group had to be created by `prepareFrame()`\n     * @type {boolean}\n     */\n    this.replayGroupChanged = true;\n\n    /**\n     * Clipping to be performed by `renderFrame()`\n     * @type {boolean}\n     */\n    this.clipping = true;\n\n    /**\n     * @private\n     * @type {CanvasRenderingContext2D|OffscreenCanvasRenderingContext2D}\n     */\n    this.targetContext_ = null;\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.opacity_ = 1;\n  }\n\n  /**\n   * @param {ExecutorGroup} executorGroup Executor group.\n   * @param {import(\"../../Map.js\").FrameState} frameState Frame state.\n   * @param {boolean} [declutterable] `true` to only render declutterable items,\n   *     `false` to only render non-declutterable items, `undefined` to render all.\n   */\n  renderWorlds(executorGroup, frameState, declutterable) {\n    const extent = frameState.extent;\n    const viewState = frameState.viewState;\n    const center = viewState.center;\n    const resolution = viewState.resolution;\n    const projection = viewState.projection;\n    const rotation = viewState.rotation;\n    const projectionExtent = projection.getExtent();\n    const vectorSource = this.getLayer().getSource();\n    const declutter = this.getLayer().getDeclutter();\n    const pixelRatio = frameState.pixelRatio;\n    const viewHints = frameState.viewHints;\n    const snapToPixel = !(\n      viewHints[ViewHint.ANIMATING] || viewHints[ViewHint.INTERACTING]\n    );\n    const context = this.context;\n    const width = Math.round((getWidth(extent) / resolution) * pixelRatio);\n    const height = Math.round((getHeight(extent) / resolution) * pixelRatio);\n\n    const multiWorld = vectorSource.getWrapX() && projection.canWrapX();\n    const worldWidth = multiWorld ? getWidth(projectionExtent) : null;\n    const endWorld = multiWorld\n      ? Math.ceil((extent[2] - projectionExtent[2]) / worldWidth) +\n        (this.extendX_ ? 2 : 1)\n      : 1;\n    let world = multiWorld\n      ? Math.floor((extent[0] - projectionExtent[0]) / worldWidth) -\n        (this.extendX_ ? 1 : 0)\n      : 0;\n    do {\n      let transform = this.getRenderTransform(\n        center,\n        resolution,\n        0,\n        pixelRatio,\n        width,\n        height,\n        world * worldWidth,\n      );\n      if (frameState.declutter) {\n        transform = transform.slice(0);\n      }\n      executorGroup.execute(\n        context,\n        [context.canvas.width, context.canvas.height],\n        transform,\n        rotation,\n        snapToPixel,\n        declutterable === undefined\n          ? ALL\n          : declutterable\n            ? DECLUTTER\n            : NON_DECLUTTER,\n        declutterable\n          ? declutter && frameState.declutter[declutter]\n          : undefined,\n      );\n    } while (++world < endWorld);\n  }\n\n  /**\n   * @private\n   */\n  setDrawContext_() {\n    if (this.opacity_ !== 1) {\n      this.targetContext_ = this.context;\n      this.context = createCanvasContext2D(\n        this.context.canvas.width,\n        this.context.canvas.height,\n        canvasPool,\n      );\n    }\n  }\n\n  /**\n   * @private\n   */\n  resetDrawContext_() {\n    if (this.opacity_ !== 1 && this.targetContext_) {\n      const alpha = this.targetContext_.globalAlpha;\n      this.targetContext_.globalAlpha = this.opacity_;\n      this.targetContext_.drawImage(this.context.canvas, 0, 0);\n      this.targetContext_.globalAlpha = alpha;\n      releaseCanvas(this.context);\n      canvasPool.push(this.context.canvas);\n      this.context = this.targetContext_;\n      this.targetContext_ = null;\n    }\n  }\n\n  /**\n   * Render declutter items for this layer\n   * @param {import(\"../../Map.js\").FrameState} frameState Frame state.\n   */\n  renderDeclutter(frameState) {\n    if (!this.replayGroup_ || !this.getLayer().getDeclutter()) {\n      return;\n    }\n    this.renderWorlds(this.replayGroup_, frameState, true);\n  }\n\n  /**\n   * Render deferred instructions.\n   * @param {import(\"../../Map.js\").FrameState} frameState Frame state.\n   * @override\n   */\n  renderDeferredInternal(frameState) {\n    if (!this.replayGroup_) {\n      return;\n    }\n    if (this.clipExtent_) {\n      this.clipUnrotated(this.context, frameState, this.clipExtent_);\n    }\n    this.replayGroup_.renderDeferred();\n    if (this.clipExtent_) {\n      this.context.restore();\n      this.clipExtent_ = null;\n    }\n    this.resetDrawContext_();\n  }\n\n  /**\n   * Render the layer.\n   * @param {import(\"../../Map.js\").FrameState} frameState Frame state.\n   * @param {HTMLElement|null} target Target that may be used to render content to.\n   * @return {HTMLElement} The rendered element.\n   * @override\n   */\n  renderFrame(frameState, target) {\n    const layerState = frameState.layerStatesArray[frameState.layerIndex];\n    this.opacity_ = layerState.opacity;\n    const viewState = frameState.viewState;\n\n    this.prepareContainer(frameState, target);\n    const context = this.context;\n\n    const replayGroup = this.replayGroup_;\n    let render = replayGroup && !replayGroup.isEmpty();\n    if (!render) {\n      const hasRenderListeners =\n        this.getLayer().hasListener(RenderEventType.PRERENDER) ||\n        this.getLayer().hasListener(RenderEventType.POSTRENDER);\n      if (!hasRenderListeners) {\n        return this.container;\n      }\n    }\n\n    this.setDrawContext_();\n\n    this.preRender(context, frameState);\n\n    const projection = viewState.projection;\n\n    // clipped rendering if layer extent is set\n    this.clipExtent_ = null;\n    let clipped = false;\n    if (render && layerState.extent && this.clipping) {\n      const layerExtent = fromUserExtent(layerState.extent, projection);\n      render = intersectsExtent(layerExtent, frameState.extent);\n      const needsClip =\n        render && !containsExtent(layerExtent, frameState.extent);\n      if (needsClip) {\n        if (frameState.declutter) {\n          // Store extent for deferred clipping\n          this.clipExtent_ = layerExtent;\n        } else {\n          // Apply clipping immediately for non-declutter rendering\n          this.clipUnrotated(context, frameState, layerExtent);\n          clipped = true;\n        }\n      }\n    }\n\n    if (render) {\n      this.renderWorlds(\n        replayGroup,\n        frameState,\n        this.getLayer().getDeclutter() ? false : undefined,\n      );\n    }\n\n    if (clipped) {\n      context.restore();\n    }\n\n    this.postRender(context, frameState);\n\n    if (this.renderedRotation_ !== viewState.rotation) {\n      this.renderedRotation_ = viewState.rotation;\n      this.hitDetectionImageData_ = null;\n    }\n    if (!frameState.declutter) {\n      this.resetDrawContext_();\n    }\n    return this.container;\n  }\n\n  /**\n   * Asynchronous layer level hit detection.\n   * @param {import(\"../../pixel.js\").Pixel} pixel Pixel.\n   * @return {Promise<Array<import(\"../../Feature.js\").default>>} Promise\n   * that resolves with an array of features.\n   * @override\n   */\n  getFeatures(pixel) {\n    return new Promise((resolve) => {\n      if (\n        this.frameState &&\n        !this.hitDetectionImageData_ &&\n        !this.animatingOrInteracting_\n      ) {\n        const size = this.frameState.size.slice();\n        const center = this.renderedCenter_;\n        const resolution = this.renderedResolution_;\n        const rotation = this.renderedRotation_;\n        const projection = this.renderedProjection_;\n        const extent = this.wrappedRenderedExtent_;\n        const layer = this.getLayer();\n        const transforms = [];\n        const width = size[0] * HIT_DETECT_RESOLUTION;\n        const height = size[1] * HIT_DETECT_RESOLUTION;\n        transforms.push(\n          this.getRenderTransform(\n            center,\n            resolution,\n            rotation,\n            HIT_DETECT_RESOLUTION,\n            width,\n            height,\n            0,\n          ).slice(),\n        );\n        const source = layer.getSource();\n        const projectionExtent = projection.getExtent();\n        if (\n          source.getWrapX() &&\n          projection.canWrapX() &&\n          !containsExtent(projectionExtent, extent)\n        ) {\n          let startX = extent[0];\n          const worldWidth = getWidth(projectionExtent);\n          let world = 0;\n          let offsetX;\n          while (startX < projectionExtent[0]) {\n            --world;\n            offsetX = worldWidth * world;\n            transforms.push(\n              this.getRenderTransform(\n                center,\n                resolution,\n                rotation,\n                HIT_DETECT_RESOLUTION,\n                width,\n                height,\n                offsetX,\n              ).slice(),\n            );\n            startX += worldWidth;\n          }\n          world = 0;\n          startX = extent[2];\n          while (startX > projectionExtent[2]) {\n            ++world;\n            offsetX = worldWidth * world;\n            transforms.push(\n              this.getRenderTransform(\n                center,\n                resolution,\n                rotation,\n                HIT_DETECT_RESOLUTION,\n                width,\n                height,\n                offsetX,\n              ).slice(),\n            );\n            startX -= worldWidth;\n          }\n        }\n        const userProjection = getUserProjection();\n        this.hitDetectionImageData_ = createHitDetectionImageData(\n          size,\n          transforms,\n          this.renderedFeatures_,\n          layer.getStyleFunction(),\n          extent,\n          resolution,\n          rotation,\n          getSquaredRenderTolerance(resolution, this.renderedPixelRatio_),\n          userProjection ? projection : null,\n        );\n      }\n      resolve(\n        hitDetect(pixel, this.renderedFeatures_, this.hitDetectionImageData_),\n      );\n    });\n  }\n\n  /**\n   * @param {import(\"../../coordinate.js\").Coordinate} coordinate Coordinate.\n   * @param {import(\"../../Map.js\").FrameState} frameState Frame state.\n   * @param {number} hitTolerance Hit tolerance in pixels.\n   * @param {import(\"../vector.js\").FeatureCallback<T>} callback Feature callback.\n   * @param {Array<import(\"../Map.js\").HitMatch<T>>} matches The hit detected matches with tolerance.\n   * @return {T|undefined} Callback result.\n   * @template T\n   * @override\n   */\n  forEachFeatureAtCoordinate(\n    coordinate,\n    frameState,\n    hitTolerance,\n    callback,\n    matches,\n  ) {\n    if (!this.replayGroup_) {\n      return undefined;\n    }\n    const resolution = frameState.viewState.resolution;\n    const rotation = frameState.viewState.rotation;\n    const layer = this.getLayer();\n\n    /** @type {!Object<string, import(\"../Map.js\").HitMatch<T>|true>} */\n    const features = {};\n\n    /**\n     * @param {import(\"../../Feature.js\").FeatureLike} feature Feature.\n     * @param {import(\"../../geom/SimpleGeometry.js\").default} geometry Geometry.\n     * @param {number} distanceSq The squared distance to the click position\n     * @return {T|undefined} Callback result.\n     */\n    const featureCallback = function (feature, geometry, distanceSq) {\n      const key = getUid(feature);\n      const match = features[key];\n      if (!match) {\n        if (distanceSq === 0) {\n          features[key] = true;\n          return callback(feature, layer, geometry);\n        }\n        matches.push(\n          (features[key] = {\n            feature: feature,\n            layer: layer,\n            geometry: geometry,\n            distanceSq: distanceSq,\n            callback: callback,\n          }),\n        );\n      } else if (match !== true && distanceSq < match.distanceSq) {\n        if (distanceSq === 0) {\n          features[key] = true;\n          matches.splice(matches.lastIndexOf(match), 1);\n          return callback(feature, layer, geometry);\n        }\n        match.geometry = geometry;\n        match.distanceSq = distanceSq;\n      }\n      return undefined;\n    };\n\n    const declutter = this.getLayer().getDeclutter();\n    return this.replayGroup_.forEachFeatureAtCoordinate(\n      coordinate,\n      resolution,\n      rotation,\n      hitTolerance,\n      featureCallback,\n      declutter\n        ? frameState.declutter?.[declutter]?.all().map((item) => item.value)\n        : null,\n    );\n  }\n\n  /**\n   * Perform action necessary to get the layer rendered after new fonts have loaded\n   * @override\n   */\n  handleFontsChanged() {\n    const layer = this.getLayer();\n    if (layer.getVisible() && this.replayGroup_) {\n      layer.changed();\n    }\n  }\n\n  /**\n   * Handle changes in image style state.\n   * @param {import(\"../../events/Event.js\").default} event Image style change event.\n   * @private\n   */\n  handleStyleImageChange_(event) {\n    this.renderIfReadyAndVisible();\n  }\n\n  /**\n   * Determine whether render should be called.\n   * @param {import(\"../../Map.js\").FrameState} frameState Frame state.\n   * @return {boolean} Layer is ready to be rendered.\n   * @override\n   */\n  prepareFrame(frameState) {\n    const vectorLayer = this.getLayer();\n    const vectorSource = vectorLayer.getSource();\n    if (!vectorSource) {\n      return false;\n    }\n\n    const animating = frameState.viewHints[ViewHint.ANIMATING];\n    const interacting = frameState.viewHints[ViewHint.INTERACTING];\n    const updateWhileAnimating = vectorLayer.getUpdateWhileAnimating();\n    const updateWhileInteracting = vectorLayer.getUpdateWhileInteracting();\n\n    if (\n      (this.ready && !updateWhileAnimating && animating) ||\n      (!updateWhileInteracting && interacting)\n    ) {\n      this.animatingOrInteracting_ = true;\n      return true;\n    }\n    this.animatingOrInteracting_ = false;\n\n    const frameStateExtent = frameState.extent;\n    const viewState = frameState.viewState;\n    const projection = viewState.projection;\n    const resolution = viewState.resolution;\n    const pixelRatio = frameState.pixelRatio;\n    const vectorLayerRevision = vectorLayer.getRevision();\n    const vectorLayerRenderBuffer = vectorLayer.getRenderBuffer();\n    let vectorLayerRenderOrder = vectorLayer.getRenderOrder();\n\n    if (vectorLayerRenderOrder === undefined) {\n      vectorLayerRenderOrder = defaultRenderOrder;\n    }\n\n    const center = viewState.center.slice();\n    const extent = buffer(\n      frameStateExtent,\n      vectorLayerRenderBuffer * resolution,\n    );\n    const renderedExtent = extent.slice();\n    const loadExtents = [extent.slice()];\n    const projectionExtent = projection.getExtent();\n\n    const canWrapX = vectorSource.getWrapX() && projection.canWrapX();\n    this.extendX_ = false;\n    if (canWrapX) {\n      const sourceExtent = vectorSource.getExtent();\n      if (sourceExtent && !isEmpty(sourceExtent)) {\n        this.extendX_ =\n          sourceExtent[0] < projectionExtent[0] ||\n          sourceExtent[2] > projectionExtent[2];\n      }\n    }\n\n    if (\n      canWrapX &&\n      (!containsExtent(projectionExtent, frameState.extent) || this.extendX_)\n    ) {\n      // For the replay group, we need an extent that intersects the real world\n      // (-180\u00B0 to +180\u00B0). To support geometries in a coordinate range from -540\u00B0\n      // to +540\u00B0, we add at least 1 world width on each side of the projection\n      // extent. If the viewport is wider than the world, we need to add half of\n      // the viewport width to make sure we cover the whole viewport.\n      const worldWidth = getWidth(projectionExtent);\n      const gutter = Math.max(getWidth(extent) / 2, worldWidth);\n      let projMinX = projectionExtent[0];\n      let projMaxX = projectionExtent[2];\n      if (this.extendX_) {\n        projMinX -= worldWidth;\n        projMaxX += worldWidth;\n      }\n      extent[0] = projMinX - gutter;\n      extent[2] = projMaxX + gutter;\n      wrapCoordinateX(center, projection);\n      const loadExtent = wrapExtentX(loadExtents[0], projection);\n      // If the extent crosses the date line, we load data for both edges of the worlds\n      if (\n        loadExtent[0] < projectionExtent[0] &&\n        loadExtent[2] < projectionExtent[2]\n      ) {\n        loadExtents.push([\n          loadExtent[0] + worldWidth,\n          loadExtent[1],\n          loadExtent[2] + worldWidth,\n          loadExtent[3],\n        ]);\n      } else if (\n        loadExtent[0] > projectionExtent[0] &&\n        loadExtent[2] > projectionExtent[2]\n      ) {\n        loadExtents.push([\n          loadExtent[0] - worldWidth,\n          loadExtent[1],\n          loadExtent[2] - worldWidth,\n          loadExtent[3],\n        ]);\n      }\n    }\n\n    if (\n      this.ready &&\n      this.renderedResolution_ == resolution &&\n      this.renderedPixelRatio_ === pixelRatio &&\n      this.renderedRevision_ == vectorLayerRevision &&\n      this.renderedRenderOrder_ == vectorLayerRenderOrder &&\n      this.renderedFrameDeclutter_ === !!frameState.declutter &&\n      containsExtent(this.wrappedRenderedExtent_, extent)\n    ) {\n      if (!equals(this.renderedExtent_, renderedExtent)) {\n        this.hitDetectionImageData_ = null;\n        this.renderedExtent_ = renderedExtent;\n      }\n      this.renderedCenter_ = center;\n      this.replayGroupChanged = false;\n      return true;\n    }\n\n    this.replayGroup_ = null;\n\n    const replayGroup = new CanvasBuilderGroup(\n      getRenderTolerance(resolution, pixelRatio),\n      extent,\n      resolution,\n      pixelRatio,\n    );\n\n    const userProjection = getUserProjection();\n    let userTransform;\n    if (userProjection) {\n      for (let i = 0, ii = loadExtents.length; i < ii; ++i) {\n        const extent = loadExtents[i];\n        const userExtent = toUserExtent(extent, projection);\n        vectorSource.loadFeatures(\n          userExtent,\n          toUserResolution(resolution, projection),\n          userProjection,\n        );\n      }\n      userTransform = getTransformFromProjections(userProjection, projection);\n    } else {\n      for (let i = 0, ii = loadExtents.length; i < ii; ++i) {\n        vectorSource.loadFeatures(loadExtents[i], resolution, projection);\n      }\n    }\n\n    const squaredTolerance = getSquaredRenderTolerance(resolution, pixelRatio);\n    let ready = true;\n    const render =\n      /**\n       * @param {import(\"../../Feature.js\").default} feature Feature.\n       * @param {number} index Index.\n       */\n      (feature, index) => {\n        let styles;\n        const styleFunction =\n          feature.getStyleFunction() || vectorLayer.getStyleFunction();\n        if (styleFunction) {\n          styles = styleFunction(feature, resolution);\n        }\n        if (styles) {\n          const dirty = this.renderFeature(\n            feature,\n            squaredTolerance,\n            styles,\n            replayGroup,\n            userTransform,\n            this.getLayer().getDeclutter(),\n            index,\n          );\n          ready = ready && !dirty;\n        }\n      };\n\n    const userExtent = toUserExtent(extent, projection);\n    /** @type {Array<import(\"../../Feature.js\").default>} */\n    const features = vectorSource.getFeaturesInExtent(userExtent);\n    if (vectorLayerRenderOrder) {\n      features.sort(vectorLayerRenderOrder);\n    }\n    for (let i = 0, ii = features.length; i < ii; ++i) {\n      render(features[i], i);\n    }\n    this.renderedFeatures_ = features;\n    this.ready = ready;\n\n    const replayGroupInstructions = replayGroup.finish();\n    const executorGroup = new ExecutorGroup(\n      extent,\n      resolution,\n      pixelRatio,\n      vectorSource.getOverlaps(),\n      replayGroupInstructions,\n      vectorLayer.getRenderBuffer(),\n      !!frameState.declutter,\n    );\n\n    this.renderedResolution_ = resolution;\n    this.renderedRevision_ = vectorLayerRevision;\n    this.renderedRenderOrder_ = vectorLayerRenderOrder;\n    this.renderedFrameDeclutter_ = !!frameState.declutter;\n    this.renderedExtent_ = renderedExtent;\n    this.wrappedRenderedExtent_ = extent;\n    this.renderedCenter_ = center;\n    this.renderedProjection_ = projection;\n    this.renderedPixelRatio_ = pixelRatio;\n    this.replayGroup_ = executorGroup;\n    this.hitDetectionImageData_ = null;\n\n    this.replayGroupChanged = true;\n    return true;\n  }\n\n  /**\n   * @param {import(\"../../Feature.js\").default} feature Feature.\n   * @param {number} squaredTolerance Squared render tolerance.\n   * @param {import(\"../../style/Style.js\").default|Array<import(\"../../style/Style.js\").default>} styles The style or array of styles.\n   * @param {import(\"../../render/canvas/BuilderGroup.js\").default} builderGroup Builder group.\n   * @param {import(\"../../proj.js\").TransformFunction} [transform] Transform from user to view projection.\n   * @param {boolean} [declutter] Enable decluttering.\n   * @param {number} [index] Render order index.\n   * @return {boolean} `true` if an image is loading.\n   */\n  renderFeature(\n    feature,\n    squaredTolerance,\n    styles,\n    builderGroup,\n    transform,\n    declutter,\n    index,\n  ) {\n    if (!styles) {\n      return false;\n    }\n    let loading = false;\n    if (Array.isArray(styles)) {\n      for (let i = 0, ii = styles.length; i < ii; ++i) {\n        loading =\n          renderFeature(\n            builderGroup,\n            feature,\n            styles[i],\n            squaredTolerance,\n            this.boundHandleStyleImageChange_,\n            transform,\n            declutter,\n            index,\n          ) || loading;\n      }\n    } else {\n      loading = renderFeature(\n        builderGroup,\n        feature,\n        styles,\n        squaredTolerance,\n        this.boundHandleStyleImageChange_,\n        transform,\n        declutter,\n        index,\n      );\n    }\n    return loading;\n  }\n}\n\nexport default CanvasVectorLayerRenderer;\n", "/**\n * @module ol/layer/Vector\n */\nimport CanvasVectorLayerRenderer from '../renderer/canvas/VectorLayer.js';\nimport BaseVectorLayer from './BaseVector.js';\n\n/**\n * @template {import(\"../source/Vector.js\").default<FeatureType>} [VectorSourceType=import(\"../source/Vector.js\").default<*>]\n * @template {import('../Feature.js').FeatureLike} [FeatureType=import(\"./BaseVector.js\").ExtractedFeatureType<VectorSourceType>]\n * @typedef {Object} Options\n * @property {string} [className='ol-layer'] A CSS class name to set to the layer element.\n * @property {number} [opacity=1] Opacity (0, 1).\n * @property {boolean} [visible=true] Visibility.\n * @property {import(\"../extent.js\").Extent} [extent] The bounding extent for layer rendering.  The layer will not be\n * rendered outside of this extent.\n * @property {number} [zIndex] The z-index for layer rendering.  At rendering time, the layers\n * will be ordered, first by Z-index and then by position. When `undefined`, a `zIndex` of 0 is assumed\n * for layers that are added to the map's `layers` collection, or `Infinity` when the layer's `setMap()`\n * method was used.\n * @property {number} [minResolution] The minimum resolution (inclusive) at which this layer will be\n * visible.\n * @property {number} [maxResolution] The maximum resolution (exclusive) below which this layer will\n * be visible.\n * @property {number} [minZoom] The minimum view zoom level (exclusive) above which this layer will be\n * visible.\n * @property {number} [maxZoom] The maximum view zoom level (inclusive) at which this layer will\n * be visible.\n * @property {import(\"../render.js\").OrderFunction} [renderOrder] Render order. Function to be used when sorting\n * features before rendering. By default features are drawn in the order that they are created. Use\n * `null` to avoid the sort, but get an undefined draw order.\n * @property {number} [renderBuffer=100] The buffer in pixels around the viewport extent used by the\n * renderer when getting features from the vector source for the rendering or hit-detection.\n * Recommended value: the size of the largest symbol, line width or label.\n * @property {VectorSourceType} [source] Source.\n * @property {import(\"../Map.js\").default} [map] Sets the layer as overlay on a map. The map will not manage\n * this layer in its layers collection, and the layer will be rendered on top. This is useful for\n * temporary layers. The standard way to add a layer to a map and have it managed by the map is to\n * use [map.addLayer()]{@link import(\"../Map.js\").default#addLayer}.\n * @property {boolean|string|number} [declutter=false] Declutter images and text. Any truthy value will enable\n * decluttering. Within a layer, a feature rendered before another has higher priority. All layers with the\n * same `declutter` value will be decluttered together. The priority is determined by the drawing order of the\n * layers with the same `declutter` value. Higher in the layer stack means higher priority. To declutter distinct\n * layers or groups of layers separately, use different truthy values for `declutter`.\n * @property {import(\"../style/Style.js\").StyleLike|import(\"../style/flat.js\").FlatStyleLike|null} [style] Layer style. When set to `null`, only\n * features that have their own style will be rendered. See {@link module:ol/style/Style~Style} for the default style\n * which will be used if this is not set.\n * @property {import(\"./Base.js\").BackgroundColor} [background] Background color for the layer. If not specified, no background\n * will be rendered.\n * @property {boolean} [updateWhileAnimating=false] When set to `true`, feature batches will\n * be recreated during animations. This means that no vectors will be shown clipped, but the\n * setting will have a performance impact for large amounts of vector data. When set to `false`,\n * batches will be recreated when no animation is active.\n * @property {boolean} [updateWhileInteracting=false] When set to `true`, feature batches will\n * be recreated during interactions. See also `updateWhileAnimating`.\n * @property {Object<string, *>} [properties] Arbitrary observable properties. Can be accessed with `#get()` and `#set()`.\n */\n\n/**\n * @classdesc\n * Vector data is rendered client-side, as vectors. This layer type provides most accurate rendering\n * even during animations. Points and labels stay upright on rotated views. For very large\n * amounts of vector data, performance may suffer during pan and zoom animations. In this case,\n * try {@link module:ol/layer/VectorImage~VectorImageLayer}.\n *\n * Note that any property set in the options is set as a {@link module:ol/Object~BaseObject}\n * property on the layer object; for example, setting `title: 'My Title'` in the\n * options means that `title` is observable, and has get/set accessors.\n *\n * @template {import(\"../source/Vector.js\").default<FeatureType>} [VectorSourceType=import(\"../source/Vector.js\").default<*>]\n * @template {import('../Feature.js').FeatureLike} [FeatureType=import(\"./BaseVector.js\").ExtractedFeatureType<VectorSourceType>]\n * @extends {BaseVectorLayer<FeatureType, VectorSourceType, CanvasVectorLayerRenderer>}\n * @api\n */\nclass VectorLayer extends BaseVectorLayer {\n  /**\n   * @param {Options<VectorSourceType, FeatureType>} [options] Options.\n   */\n  constructor(options) {\n    super(options);\n  }\n\n  /**\n   * @override\n   */\n  createRenderer() {\n    return new CanvasVectorLayerRenderer(this);\n  }\n}\n\nexport default VectorLayer;\n", "/**\n * @module ol/featureloader\n */\n\n/**\n *\n * @type {boolean}\n * @private\n */\nlet withCredentials = false;\n\n/**\n * {@link module:ol/source/Vector~VectorSource} sources use a function of this type to\n * load features.\n *\n * This function takes 3 arguments: an {@link module:ol/extent~Extent} representing\n * the area to be loaded, a `{number}` representing the resolution (map units per pixel), and a\n * {@link module:ol/proj/Projection~Projection} for the projection. The function is expeced to return\n * a promise that resolves to an array of features.\n *\n * There are also a deprecated signature, with `void` as\n * return, and two additional arguments: an optional success callback that should get\n * the loaded features passed as an argument and an optional failure callback with no arguments.\n *\n * The function is responsible for loading the features and adding them to the\n * source.\n *\n * @template {import(\"./Feature.js\").FeatureLike} [FeatureType=import(\"./Feature.js\").FeatureLike]\n * @typedef {(\n *           extent: import(\"./extent.js\").Extent,\n *           resolution: number,\n *           projection: import(\"./proj/Projection.js\").default,\n *           success?: (features: Array<FeatureType>) => void,\n *           failure?: () => void) => void|Promise<Array<FeatureType>>} FeatureLoader\n * @api\n */\n\n/**\n * {@link module:ol/source/Vector~VectorSource} sources use a function of this type to\n * get the url to load features from.\n *\n * This function takes an {@link module:ol/extent~Extent} representing the area\n * to be loaded, a `{number}` representing the resolution (map units per pixel)\n * and an {@link module:ol/proj/Projection~Projection} for the projection  as\n * arguments and returns a `{string}` representing the URL.\n * @typedef {function(import(\"./extent.js\").Extent, number, import(\"./proj/Projection.js\").default): string} FeatureUrlFunction\n * @api\n */\n\n/**\n * @template {import(\"./Feature.js\").FeatureLike} [FeatureType=import(\"./Feature.js\").default]\n * @param {string|FeatureUrlFunction} url Feature URL service.\n * @param {import(\"./format/Feature.js\").default<FeatureType>} format Feature format.\n * @param {import(\"./extent.js\").Extent} extent Extent.\n * @param {number} resolution Resolution.\n * @param {import(\"./proj/Projection.js\").default} projection Projection.\n * @param {function(Array<FeatureType>, import(\"./proj/Projection.js\").default): void} success Success\n *      Function called with the loaded features and optionally with the data projection.\n * @param {function(): void} failure Failure\n *      Function called when loading failed.\n */\nexport function loadFeaturesXhr(\n  url,\n  format,\n  extent,\n  resolution,\n  projection,\n  success,\n  failure,\n) {\n  const xhr = new XMLHttpRequest();\n  xhr.open(\n    'GET',\n    typeof url === 'function' ? url(extent, resolution, projection) : url,\n    true,\n  );\n  if (format.getType() == 'arraybuffer') {\n    xhr.responseType = 'arraybuffer';\n  }\n  xhr.withCredentials = withCredentials;\n  /**\n   * @param {Event} event Event.\n   * @private\n   */\n  xhr.onload = function (event) {\n    // status will be 0 for file:// urls\n    if (!xhr.status || (xhr.status >= 200 && xhr.status < 300)) {\n      const type = format.getType();\n      try {\n        /** @type {Document|Node|Object|string|undefined} */\n        let source;\n        if (type == 'text' || type == 'json') {\n          source = xhr.responseText;\n        } else if (type == 'xml') {\n          source = xhr.responseXML || xhr.responseText;\n        } else if (type == 'arraybuffer') {\n          source = /** @type {ArrayBuffer} */ (xhr.response);\n        }\n        if (source) {\n          success(\n            /** @type {Array<FeatureType>} */\n            (\n              format.readFeatures(source, {\n                extent: extent,\n                featureProjection: projection,\n              })\n            ),\n            format.readProjection(source),\n          );\n        } else {\n          failure();\n        }\n      } catch {\n        failure();\n      }\n    } else {\n      failure();\n    }\n  };\n  /**\n   * @private\n   */\n  xhr.onerror = failure;\n  xhr.send();\n}\n\n/**\n * Create an XHR feature loader for a `url` and `format`. The feature loader\n * loads features (with XHR), parses the features, and adds them to the\n * vector source.\n *\n * @template {import(\"./Feature.js\").FeatureLike} [FeatureType=import(\"./Feature.js\").default]\n * @param {string|FeatureUrlFunction} url Feature URL service.\n * @param {import(\"./format/Feature.js\").default<FeatureType>} format Feature format.\n * @return {FeatureLoader<FeatureType>} The feature loader.\n * @api\n */\nexport function xhr(url, format) {\n  /**\n   * @param {import(\"./extent.js\").Extent} extent Extent.\n   * @param {number} resolution Resolution.\n   * @param {import(\"./proj/Projection.js\").default} projection Projection.\n   * @param {function(Array<FeatureType>): void} [success] Success\n   *      Function called when loading succeeded.\n   * @param {function(): void} [failure] Failure\n   *      Function called when loading failed.\n   * @this {import(\"./source/Vector.js\").default<FeatureType>}\n   */\n  return function (extent, resolution, projection, success, failure) {\n    loadFeaturesXhr(\n      url,\n      format,\n      extent,\n      resolution,\n      projection,\n      /**\n       * @param {Array<FeatureType>} features The loaded features.\n       * @param {import(\"./proj/Projection.js\").default} dataProjection Data\n       * projection.\n       */\n      (features, dataProjection) => {\n        this.addFeatures(features);\n        if (success !== undefined) {\n          success(features);\n        }\n      },\n      () => {\n        this.changed();\n        if (failure !== undefined) {\n          failure();\n        }\n      },\n    );\n  };\n}\n\n/**\n * Setter for the withCredentials configuration for the XHR.\n *\n * @param {boolean} xhrWithCredentials The value of withCredentials to set.\n * Compare https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/\n * @api\n */\nexport function setWithCredentials(xhrWithCredentials) {\n  withCredentials = xhrWithCredentials;\n}\n", "/**\n * @module ol/loadingstrategy\n */\n\nimport {fromUserExtent, fromUserResolution, toUserExtent} from './proj.js';\n\n/**\n * Strategy function for loading all features with a single request.\n * @param {import(\"./extent.js\").Extent} extent Extent.\n * @param {number} resolution Resolution.\n * @return {Array<import(\"./extent.js\").Extent>} Extents.\n * @api\n */\nexport function all(extent, resolution) {\n  return [[-Infinity, -Infinity, Infinity, Infinity]];\n}\n\n/**\n * Strategy function for loading features based on the view's extent and\n * resolution.\n * @param {import(\"./extent.js\").Extent} extent Extent.\n * @param {number} resolution Resolution.\n * @return {Array<import(\"./extent.js\").Extent>} Extents.\n * @api\n */\nexport function bbox(extent, resolution) {\n  return [extent];\n}\n\n/**\n * Creates a strategy function for loading features based on a tile grid.\n * @param {import(\"./tilegrid/TileGrid.js\").default} tileGrid Tile grid.\n * @return {function(import(\"./extent.js\").Extent, number, import(\"./proj.js\").Projection): Array<import(\"./extent.js\").Extent>} Loading strategy.\n * @api\n */\nexport function tile(tileGrid) {\n  return (\n    /**\n     * @param {import(\"./extent.js\").Extent} extent Extent.\n     * @param {number} resolution Resolution.\n     * @param {import(\"./proj.js\").Projection} projection Projection.\n     * @return {Array<import(\"./extent.js\").Extent>} Extents.\n     */\n    function (extent, resolution, projection) {\n      const z = tileGrid.getZForResolution(\n        fromUserResolution(resolution, projection),\n      );\n      const tileRange = tileGrid.getTileRangeForExtentAndZ(\n        fromUserExtent(extent, projection),\n        z,\n      );\n      /** @type {Array<import(\"./extent.js\").Extent>} */\n      const extents = [];\n      /** @type {import(\"./tilecoord.js\").TileCoord} */\n      const tileCoord = [z, 0, 0];\n      for (\n        tileCoord[1] = tileRange.minX;\n        tileCoord[1] <= tileRange.maxX;\n        ++tileCoord[1]\n      ) {\n        for (\n          tileCoord[2] = tileRange.minY;\n          tileCoord[2] <= tileRange.maxY;\n          ++tileCoord[2]\n        ) {\n          extents.push(\n            toUserExtent(tileGrid.getTileCoordExtent(tileCoord), projection),\n          );\n        }\n      }\n      return extents;\n    }\n  );\n}\n", "/**\n * @module ol/render/Feature\n */\nimport Feature from '../Feature.js';\nimport {extend} from '../array.js';\nimport {\n  createOrUpdateFromCoordinate,\n  createOrUpdateFromFlatCoordinates,\n  getCenter,\n  getHeight,\n} from '../extent.js';\nimport {memoizeOne} from '../functions.js';\nimport LineString from '../geom/LineString.js';\nimport MultiLineString from '../geom/MultiLineString.js';\nimport MultiPoint from '../geom/MultiPoint.js';\nimport MultiPolygon from '../geom/MultiPolygon.js';\nimport Point from '../geom/Point.js';\nimport Polygon from '../geom/Polygon.js';\nimport {linearRingss as linearRingssCenter} from '../geom/flat/center.js';\nimport {\n  getInteriorPointOfArray,\n  getInteriorPointsOfMultiArray,\n} from '../geom/flat/interiorpoint.js';\nimport {interpolatePoint} from '../geom/flat/interpolate.js';\nimport {inflateEnds} from '../geom/flat/orient.js';\nimport {\n  douglasPeucker,\n  douglasPeuckerArray,\n  quantizeArray,\n} from '../geom/flat/simplify.js';\nimport {transform2D} from '../geom/flat/transform.js';\nimport {get as getProjection} from '../proj.js';\nimport {\n  compose as composeTransform,\n  create as createTransform,\n} from '../transform.js';\n\n/**\n * @typedef {'Point' | 'LineString' | 'LinearRing' | 'Polygon' | 'MultiPoint' | 'MultiLineString'} Type\n * The geometry type.  One of `'Point'`, `'LineString'`, `'LinearRing'`,\n * `'Polygon'`, `'MultiPoint'` or 'MultiLineString'`.\n */\n\n/**\n * @type {import(\"../transform.js\").Transform}\n */\nconst tmpTransform = createTransform();\n\n/**\n * Lightweight, read-only, {@link module:ol/Feature~Feature} and {@link module:ol/geom/Geometry~Geometry} like\n * structure, optimized for vector tile rendering and styling. Geometry access\n * through the API is limited to getting the type and extent of the geometry.\n */\nclass RenderFeature {\n  /**\n   * @param {Type} type Geometry type.\n   * @param {Array<number>} flatCoordinates Flat coordinates. These always need\n   *     to be right-handed for polygons.\n   * @param {Array<number>} ends Ends.\n   * @param {number} stride Stride.\n   * @param {Object<string, *>} properties Properties.\n   * @param {number|string|undefined} id Feature id.\n   */\n  constructor(type, flatCoordinates, ends, stride, properties, id) {\n    /**\n     * @type {import(\"../style/Style.js\").StyleFunction|undefined}\n     */\n    this.styleFunction;\n\n    /**\n     * @private\n     * @type {import(\"../extent.js\").Extent|undefined}\n     */\n    this.extent_;\n\n    /**\n     * @private\n     * @type {number|string|undefined}\n     */\n    this.id_ = id;\n\n    /**\n     * @private\n     * @type {Type}\n     */\n    this.type_ = type;\n\n    /**\n     * @private\n     * @type {Array<number>}\n     */\n    this.flatCoordinates_ = flatCoordinates;\n\n    /**\n     * @private\n     * @type {Array<number>}\n     */\n    this.flatInteriorPoints_ = null;\n\n    /**\n     * @private\n     * @type {Array<number>}\n     */\n    this.flatMidpoints_ = null;\n\n    /**\n     * @private\n     * @type {Array<number>|null}\n     */\n    this.ends_ = ends || null;\n\n    /**\n     * @private\n     * @type {Object<string, *>}\n     */\n    this.properties_ = properties;\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.squaredTolerance_;\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.stride_ = stride;\n\n    /**\n     * @private\n     * @type {RenderFeature}\n     */\n    this.simplifiedGeometry_;\n  }\n\n  /**\n   * Get a feature property by its key.\n   * @param {string} key Key\n   * @return {*} Value for the requested key.\n   * @api\n   */\n  get(key) {\n    return this.properties_[key];\n  }\n\n  /**\n   * Get the extent of this feature's geometry.\n   * @return {import(\"../extent.js\").Extent} Extent.\n   * @api\n   */\n  getExtent() {\n    if (!this.extent_) {\n      this.extent_ =\n        this.type_ === 'Point'\n          ? createOrUpdateFromCoordinate(this.flatCoordinates_)\n          : createOrUpdateFromFlatCoordinates(\n              this.flatCoordinates_,\n              0,\n              this.flatCoordinates_.length,\n              this.stride_,\n            );\n    }\n    return this.extent_;\n  }\n\n  /**\n   * @return {Array<number>} Flat interior points.\n   */\n  getFlatInteriorPoint() {\n    if (!this.flatInteriorPoints_) {\n      const flatCenter = getCenter(this.getExtent());\n      this.flatInteriorPoints_ = getInteriorPointOfArray(\n        this.flatCoordinates_,\n        0,\n        this.ends_,\n        this.stride_,\n        flatCenter,\n        0,\n      );\n    }\n    return this.flatInteriorPoints_;\n  }\n\n  /**\n   * @return {Array<number>} Flat interior points.\n   */\n  getFlatInteriorPoints() {\n    if (!this.flatInteriorPoints_) {\n      const ends = inflateEnds(this.flatCoordinates_, this.ends_);\n      const flatCenters = linearRingssCenter(\n        this.flatCoordinates_,\n        0,\n        ends,\n        this.stride_,\n      );\n      this.flatInteriorPoints_ = getInteriorPointsOfMultiArray(\n        this.flatCoordinates_,\n        0,\n        ends,\n        this.stride_,\n        flatCenters,\n      );\n    }\n    return this.flatInteriorPoints_;\n  }\n\n  /**\n   * @return {Array<number>} Flat midpoint.\n   */\n  getFlatMidpoint() {\n    if (!this.flatMidpoints_) {\n      this.flatMidpoints_ = interpolatePoint(\n        this.flatCoordinates_,\n        0,\n        this.flatCoordinates_.length,\n        this.stride_,\n        0.5,\n      );\n    }\n    return this.flatMidpoints_;\n  }\n\n  /**\n   * @return {Array<number>} Flat midpoints.\n   */\n  getFlatMidpoints() {\n    if (!this.flatMidpoints_) {\n      this.flatMidpoints_ = [];\n      const flatCoordinates = this.flatCoordinates_;\n      let offset = 0;\n      const ends = /** @type {Array<number>} */ (this.ends_);\n      for (let i = 0, ii = ends.length; i < ii; ++i) {\n        const end = ends[i];\n        const midpoint = interpolatePoint(\n          flatCoordinates,\n          offset,\n          end,\n          this.stride_,\n          0.5,\n        );\n        extend(this.flatMidpoints_, midpoint);\n        offset = end;\n      }\n    }\n    return this.flatMidpoints_;\n  }\n\n  /**\n   * Get the feature identifier.  This is a stable identifier for the feature and\n   * is set when reading data from a remote source.\n   * @return {number|string|undefined} Id.\n   * @api\n   */\n  getId() {\n    return this.id_;\n  }\n\n  /**\n   * @return {Array<number>} Flat coordinates.\n   */\n  getOrientedFlatCoordinates() {\n    return this.flatCoordinates_;\n  }\n\n  /**\n   * For API compatibility with {@link module:ol/Feature~Feature}, this method is useful when\n   * determining the geometry type in style function (see {@link #getType}).\n   * @return {RenderFeature} Feature.\n   * @api\n   */\n  getGeometry() {\n    return this;\n  }\n\n  /**\n   * @param {number} squaredTolerance Squared tolerance.\n   * @return {RenderFeature} Simplified geometry.\n   */\n  getSimplifiedGeometry(squaredTolerance) {\n    return this;\n  }\n\n  /**\n   * Get a transformed and simplified version of the geometry.\n   * @param {number} squaredTolerance Squared tolerance.\n   * @param {import(\"../proj.js\").TransformFunction} [transform] Optional transform function.\n   * @return {RenderFeature} Simplified geometry.\n   */\n  simplifyTransformed(squaredTolerance, transform) {\n    return this;\n  }\n\n  /**\n   * Get the feature properties.\n   * @return {Object<string, *>} Feature properties.\n   * @api\n   */\n  getProperties() {\n    return this.properties_;\n  }\n\n  /**\n   * Get an object of all property names and values.  This has the same behavior as getProperties,\n   * but is here to conform with the {@link module:ol/Feature~Feature} interface.\n   * @return {Object<string, *>?} Object.\n   */\n  getPropertiesInternal() {\n    return this.properties_;\n  }\n\n  /**\n   * @return {number} Stride.\n   */\n  getStride() {\n    return this.stride_;\n  }\n\n  /**\n   * @return {import('../style/Style.js').StyleFunction|undefined} Style\n   */\n  getStyleFunction() {\n    return this.styleFunction;\n  }\n\n  /**\n   * Get the type of this feature's geometry.\n   * @return {Type} Geometry type.\n   * @api\n   */\n  getType() {\n    return this.type_;\n  }\n\n  /**\n   * Transform geometry coordinates from tile pixel space to projected.\n   *\n   * @param {import(\"../proj.js\").ProjectionLike} projection The data projection\n   */\n  transform(projection) {\n    projection = getProjection(projection);\n    const pixelExtent = projection.getExtent();\n    const projectedExtent = projection.getWorldExtent();\n    if (pixelExtent && projectedExtent) {\n      const scale = getHeight(projectedExtent) / getHeight(pixelExtent);\n      composeTransform(\n        tmpTransform,\n        projectedExtent[0],\n        projectedExtent[3],\n        scale,\n        -scale,\n        0,\n        0,\n        0,\n      );\n      transform2D(\n        this.flatCoordinates_,\n        0,\n        this.flatCoordinates_.length,\n        this.stride_,\n        tmpTransform,\n        this.flatCoordinates_,\n      );\n    }\n  }\n\n  /**\n   * Apply a transform function to the coordinates of the geometry.\n   * The geometry is modified in place.\n   * If you do not want the geometry modified in place, first `clone()` it and\n   * then use this function on the clone.\n   * @param {import(\"../proj.js\").TransformFunction} transformFn Transform function.\n   */\n  applyTransform(transformFn) {\n    transformFn(this.flatCoordinates_, this.flatCoordinates_, this.stride_);\n  }\n\n  /**\n   * @return {RenderFeature} A cloned render feature.\n   */\n  clone() {\n    return new RenderFeature(\n      this.type_,\n      this.flatCoordinates_.slice(),\n      this.ends_?.slice(),\n      this.stride_,\n      Object.assign({}, this.properties_),\n      this.id_,\n    );\n  }\n\n  /**\n   * @return {Array<number>|null} Ends.\n   */\n  getEnds() {\n    return this.ends_;\n  }\n\n  /**\n   * Add transform and resolution based geometry simplification to this instance.\n   * @return {RenderFeature} This render feature.\n   */\n  enableSimplifyTransformed() {\n    this.simplifyTransformed = memoizeOne((squaredTolerance, transform) => {\n      if (squaredTolerance === this.squaredTolerance_) {\n        return this.simplifiedGeometry_;\n      }\n      this.simplifiedGeometry_ = this.clone();\n      if (transform) {\n        this.simplifiedGeometry_.applyTransform(transform);\n      }\n      const simplifiedFlatCoordinates =\n        this.simplifiedGeometry_.getFlatCoordinates();\n      let simplifiedEnds;\n      switch (this.type_) {\n        case 'LineString':\n          simplifiedFlatCoordinates.length = douglasPeucker(\n            simplifiedFlatCoordinates,\n            0,\n            this.simplifiedGeometry_.flatCoordinates_.length,\n            this.simplifiedGeometry_.stride_,\n            squaredTolerance,\n            simplifiedFlatCoordinates,\n            0,\n          );\n          simplifiedEnds = [simplifiedFlatCoordinates.length];\n          break;\n        case 'MultiLineString':\n          simplifiedEnds = [];\n          simplifiedFlatCoordinates.length = douglasPeuckerArray(\n            simplifiedFlatCoordinates,\n            0,\n            this.simplifiedGeometry_.ends_,\n            this.simplifiedGeometry_.stride_,\n            squaredTolerance,\n            simplifiedFlatCoordinates,\n            0,\n            simplifiedEnds,\n          );\n          break;\n        case 'Polygon':\n          simplifiedEnds = [];\n          simplifiedFlatCoordinates.length = quantizeArray(\n            simplifiedFlatCoordinates,\n            0,\n            this.simplifiedGeometry_.ends_,\n            this.simplifiedGeometry_.stride_,\n            Math.sqrt(squaredTolerance),\n            simplifiedFlatCoordinates,\n            0,\n            simplifiedEnds,\n          );\n          break;\n        default:\n      }\n      if (simplifiedEnds) {\n        this.simplifiedGeometry_ = new RenderFeature(\n          this.type_,\n          simplifiedFlatCoordinates,\n          simplifiedEnds,\n          this.stride_,\n          this.properties_,\n          this.id_,\n        );\n      }\n      this.squaredTolerance_ = squaredTolerance;\n      return this.simplifiedGeometry_;\n    });\n    return this;\n  }\n}\n\n/**\n * @return {Array<number>} Flat coordinates.\n */\nRenderFeature.prototype.getFlatCoordinates =\n  RenderFeature.prototype.getOrientedFlatCoordinates;\n\n/**\n * Create a geometry from an `ol/render/Feature`\n * @param {RenderFeature} renderFeature\n * Render Feature\n * @return {Point|MultiPoint|LineString|MultiLineString|Polygon|MultiPolygon}\n * New geometry instance.\n * @api\n */\nexport function toGeometry(renderFeature) {\n  const geometryType = renderFeature.getType();\n  switch (geometryType) {\n    case 'Point':\n      return new Point(renderFeature.getFlatCoordinates());\n    case 'MultiPoint':\n      return new MultiPoint(renderFeature.getFlatCoordinates(), 'XY');\n    case 'LineString':\n      return new LineString(renderFeature.getFlatCoordinates(), 'XY');\n    case 'MultiLineString':\n      return new MultiLineString(\n        renderFeature.getFlatCoordinates(),\n        'XY',\n        /** @type {Array<number>} */ (renderFeature.getEnds()),\n      );\n    case 'Polygon':\n      const flatCoordinates = renderFeature.getFlatCoordinates();\n      const ends = renderFeature.getEnds();\n      const endss = inflateEnds(flatCoordinates, ends);\n      return endss.length > 1\n        ? new MultiPolygon(flatCoordinates, 'XY', endss)\n        : new Polygon(flatCoordinates, 'XY', ends);\n    default:\n      throw new Error('Invalid geometry type:' + geometryType);\n  }\n}\n\n/**\n * Create an `ol/Feature` from an `ol/render/Feature`\n * @param {RenderFeature} renderFeature RenderFeature\n * @param {string} [geometryName] Geometry name to use\n * when creating the Feature.\n * @return {Feature} Newly constructed `ol/Feature` with properties,\n * geometry, and id copied over.\n * @api\n */\nexport function toFeature(renderFeature, geometryName) {\n  const id = renderFeature.getId();\n  const geometry = toGeometry(renderFeature);\n  const properties = renderFeature.getProperties();\n  const feature = new Feature();\n  if (geometryName !== undefined) {\n    feature.setGeometryName(geometryName);\n  }\n  feature.setGeometry(geometry);\n  if (id !== undefined) {\n    feature.setId(id);\n  }\n  feature.setProperties(properties, true);\n  return feature;\n}\n\nexport default RenderFeature;\n", "/**\n * @module ol/structs/RBush\n */\nimport RBush_ from 'rbush';\nimport {createOrUpdate, equals} from '../extent.js';\nimport {isEmpty} from '../obj.js';\nimport {getUid} from '../util.js';\n\n/**\n * @typedef {import(\"rbush\").BBox & {value: T}} Entry\n * @template T\n */\n\n/**\n * @classdesc\n * Wrapper around the RBush by Vladimir Agafonkin.\n * See https://github.com/mourner/rbush.\n *\n * @template {Object} T\n */\nclass RBush {\n  /**\n   * @param {number} [maxEntries] Max entries.\n   */\n  constructor(maxEntries) {\n    /**\n     * @private\n     * @type {RBush_<Entry<T>>}\n     */\n    this.rbush_ = new RBush_(maxEntries);\n\n    /**\n     * A mapping between the objects added to this rbush wrapper\n     * and the objects that are actually added to the internal rbush.\n     * @private\n     * @type {Object<string, Entry<T>>}\n     */\n    this.items_ = {};\n  }\n\n  /**\n   * Insert a value into the RBush.\n   * @param {import(\"../extent.js\").Extent} extent Extent.\n   * @param {T} value Value.\n   */\n  insert(extent, value) {\n    /** @type {Entry<T>} */\n    const item = {\n      minX: extent[0],\n      minY: extent[1],\n      maxX: extent[2],\n      maxY: extent[3],\n      value: value,\n    };\n\n    this.rbush_.insert(item);\n    this.items_[getUid(value)] = item;\n  }\n\n  /**\n   * Bulk-insert values into the RBush.\n   * @param {Array<import(\"../extent.js\").Extent>} extents Extents.\n   * @param {Array<T>} values Values.\n   */\n  load(extents, values) {\n    const items = new Array(values.length);\n    for (let i = 0, l = values.length; i < l; i++) {\n      const extent = extents[i];\n      const value = values[i];\n\n      /** @type {Entry<T>} */\n      const item = {\n        minX: extent[0],\n        minY: extent[1],\n        maxX: extent[2],\n        maxY: extent[3],\n        value: value,\n      };\n      items[i] = item;\n      this.items_[getUid(value)] = item;\n    }\n    this.rbush_.load(items);\n  }\n\n  /**\n   * Remove a value from the RBush.\n   * @param {T} value Value.\n   * @return {boolean} Removed.\n   */\n  remove(value) {\n    const uid = getUid(value);\n\n    // get the object in which the value was wrapped when adding to the\n    // internal rbush. then use that object to do the removal.\n    const item = this.items_[uid];\n    delete this.items_[uid];\n    return this.rbush_.remove(item) !== null;\n  }\n\n  /**\n   * Update the extent of a value in the RBush.\n   * @param {import(\"../extent.js\").Extent} extent Extent.\n   * @param {T} value Value.\n   */\n  update(extent, value) {\n    const item = this.items_[getUid(value)];\n    const bbox = [item.minX, item.minY, item.maxX, item.maxY];\n    if (!equals(bbox, extent)) {\n      this.remove(value);\n      this.insert(extent, value);\n    }\n  }\n\n  /**\n   * Return all values in the RBush.\n   * @return {Array<T>} All.\n   */\n  getAll() {\n    const items = this.rbush_.all();\n    return items.map(function (item) {\n      return item.value;\n    });\n  }\n\n  /**\n   * Return all values in the given extent.\n   * @param {import(\"../extent.js\").Extent} extent Extent.\n   * @return {Array<T>} All in extent.\n   */\n  getInExtent(extent) {\n    /** @type {import(\"rbush\").BBox} */\n    const bbox = {\n      minX: extent[0],\n      minY: extent[1],\n      maxX: extent[2],\n      maxY: extent[3],\n    };\n    const items = this.rbush_.search(bbox);\n    return items.map(function (item) {\n      return item.value;\n    });\n  }\n\n  /**\n   * Calls a callback function with each value in the tree.\n   * If the callback returns a truthy value, this value is returned without\n   * checking the rest of the tree.\n   * @param {function(T): R} callback Callback.\n   * @return {R|undefined} Callback return value.\n   * @template R\n   */\n  forEach(callback) {\n    return this.forEach_(this.getAll(), callback);\n  }\n\n  /**\n   * Calls a callback function with each value in the provided extent.\n   * @param {import(\"../extent.js\").Extent} extent Extent.\n   * @param {function(T): R} callback Callback.\n   * @return {R|undefined} Callback return value.\n   * @template R\n   */\n  forEachInExtent(extent, callback) {\n    return this.forEach_(this.getInExtent(extent), callback);\n  }\n\n  /**\n   * @param {Array<T>} values Values.\n   * @param {function(T): R} callback Callback.\n   * @return {R|undefined} Callback return value.\n   * @template R\n   * @private\n   */\n  forEach_(values, callback) {\n    let result;\n    for (let i = 0, l = values.length; i < l; i++) {\n      result = callback(values[i]);\n      if (result) {\n        return result;\n      }\n    }\n    return result;\n  }\n\n  /**\n   * @return {boolean} Is empty.\n   */\n  isEmpty() {\n    return isEmpty(this.items_);\n  }\n\n  /**\n   * Remove all values from the RBush.\n   */\n  clear() {\n    this.rbush_.clear();\n    this.items_ = {};\n  }\n\n  /**\n   * @param {import(\"../extent.js\").Extent} [extent] Extent.\n   * @return {import(\"../extent.js\").Extent} Extent.\n   */\n  getExtent(extent) {\n    const data = this.rbush_.toJSON();\n    return createOrUpdate(data.minX, data.minY, data.maxX, data.maxY, extent);\n  }\n\n  /**\n   * @param {RBush<T>} rbush R-Tree.\n   */\n  concat(rbush) {\n    this.rbush_.load(rbush.rbush_.all());\n    for (const i in rbush.items_) {\n      this.items_[i] = rbush.items_[i];\n    }\n  }\n}\n\nexport default RBush;\n", "/**\n * @module ol/source/VectorEventType\n */\n\n/**\n * @enum {string}\n */\nexport default {\n  /**\n   * Triggered when a feature is added to the source.\n   * @event module:ol/source/Vector.VectorSourceEvent#addfeature\n   * @api\n   */\n  ADDFEATURE: 'addfeature',\n\n  /**\n   * Triggered when a feature is updated.\n   * @event module:ol/source/Vector.VectorSourceEvent#changefeature\n   * @api\n   */\n  CHANGEFEATURE: 'changefeature',\n\n  /**\n   * Triggered when the clear method is called on the source.\n   * @event module:ol/source/Vector.VectorSourceEvent#clear\n   * @api\n   */\n  CLEAR: 'clear',\n\n  /**\n   * Triggered when a feature is removed from the source.\n   * See {@link module:ol/source/Vector~VectorSource#clear source.clear()} for exceptions.\n   * @event module:ol/source/Vector.VectorSourceEvent#removefeature\n   * @api\n   */\n  REMOVEFEATURE: 'removefeature',\n\n  /**\n   * Triggered when features starts loading.\n   * @event module:ol/source/Vector.VectorSourceEvent#featuresloadstart\n   * @api\n   */\n  FEATURESLOADSTART: 'featuresloadstart',\n\n  /**\n   * Triggered when features finishes loading.\n   * @event module:ol/source/Vector.VectorSourceEvent#featuresloadend\n   * @api\n   */\n  FEATURESLOADEND: 'featuresloadend',\n\n  /**\n   * Triggered if feature loading results in an error.\n   * @event module:ol/source/Vector.VectorSourceEvent#featuresloaderror\n   * @api\n   */\n  FEATURESLOADERROR: 'featuresloaderror',\n};\n\n/**\n * @typedef {'addfeature'|'changefeature'|'clear'|'removefeature'|'featuresloadstart'|'featuresloadend'|'featuresloaderror'} VectorSourceEventTypes\n */\n", "/**\n * @module ol/source/Vector\n */\n\nimport Collection from '../Collection.js';\nimport CollectionEventType from '../CollectionEventType.js';\nimport ObjectEventType from '../ObjectEventType.js';\nimport {extend} from '../array.js';\nimport {assert} from '../asserts.js';\nimport {listen, unlistenByKey} from '../events.js';\nimport Event from '../events/Event.js';\nimport EventType from '../events/EventType.js';\nimport {containsExtent, equals, wrapAndSliceX} from '../extent.js';\nimport {xhr} from '../featureloader.js';\nimport {TRUE, VOID} from '../functions.js';\nimport {all as allStrategy} from '../loadingstrategy.js';\nimport {isEmpty} from '../obj.js';\nimport RenderFeature from '../render/Feature.js';\nimport RBush from '../structs/RBush.js';\nimport {getUid} from '../util.js';\nimport Source from './Source.js';\nimport VectorEventType from './VectorEventType.js';\n\n/**\n * A function that takes an {@link module:ol/extent~Extent} and a resolution as arguments, and\n * returns an array of {@link module:ol/extent~Extent} with the extents to load. Usually this\n * is one of the standard {@link module:ol/loadingstrategy} strategies.\n *\n * @typedef {function(import(\"../extent.js\").Extent, number, import(\"../proj/Projection.js\").default): Array<import(\"../extent.js\").Extent>} LoadingStrategy\n * @api\n */\n\n/**\n * @classdesc\n * Events emitted by {@link module:ol/source/Vector~VectorSource} instances are instances of this\n * type.\n * @template {import(\"../Feature.js\").FeatureLike} [FeatureType=import(\"../Feature.js\").default]\n */\nexport class VectorSourceEvent extends Event {\n  /**\n   * @param {string} type Type.\n   * @param {FeatureType} [feature] Feature.\n   * @param {Array<FeatureType>} [features] Features.\n   */\n  constructor(type, feature, features) {\n    super(type);\n\n    /**\n     * The added or removed feature for the `ADDFEATURE` and `REMOVEFEATURE` events, `undefined` otherwise.\n     * @type {FeatureType|undefined}\n     * @api\n     */\n    this.feature = feature;\n\n    /**\n     * The loaded features for the `FEATURESLOADED` event, `undefined` otherwise.\n     * @type {Array<FeatureType>|undefined}\n     * @api\n     */\n    this.features = features;\n  }\n}\n\n/***\n * @template {import(\"../Feature.js\").FeatureLike} [T=import(\"../Feature.js\").default]\n * @typedef {T extends RenderFeature ? T|Array<T> : T} FeatureClassOrArrayOfRenderFeatures\n */\n\n/***\n * @template Return\n * @template {import(\"../Feature.js\").FeatureLike} [FeatureType=import(\"../Feature.js\").default]\n * @typedef {import(\"../Observable.js\").OnSignature<import(\"../Observable.js\").EventTypes, import(\"../events/Event.js\").default, Return> &\n *   import(\"../Observable.js\").OnSignature<import(\"../ObjectEventType.js\").Types, import(\"../Object.js\").ObjectEvent, Return> &\n *   import(\"../Observable.js\").OnSignature<import(\"./VectorEventType.js\").VectorSourceEventTypes, VectorSourceEvent<FeatureType>, Return> &\n *   import(\"../Observable.js\").CombinedOnSignature<import(\"../Observable.js\").EventTypes|import(\"../ObjectEventType.js\").Types|\n *     import(\"./VectorEventType.js\").VectorSourceEventTypes, Return>} VectorSourceOnSignature\n */\n\n/**\n * @template {import(\"../Feature.js\").FeatureLike} [FeatureType=import(\"../Feature.js\").default]\n * @typedef {Object} Options\n * @property {import(\"./Source.js\").AttributionLike} [attributions] Attributions.\n * @property {Array<FeatureType>|Collection<FeatureType>} [features]\n * Features. If provided as {@link module:ol/Collection~Collection}, the features in the source\n * and the collection will stay in sync.\n * @property {import(\"../format/Feature.js\").default<FeatureType>} [format] The feature format used by the XHR\n * feature loader when `url` is set. Required if `url` is set, otherwise ignored.\n * @property {import(\"../featureloader.js\").FeatureLoader<FeatureType>} [loader]\n * The loader function used to load features, from a remote source for example.\n * If this is not set and `url` is set, the source will create and use an XHR\n * feature loader. The `'featuresloadend'` and `'featuresloaderror'` events\n * will only fire if the `success` and `failure` callbacks are used.\n *\n * Example:\n *\n * ```js\n * import Vector from 'ol/source/Vector.js';\n * import GeoJSON from 'ol/format/GeoJSON.js';\n * import {bbox} from 'ol/loadingstrategy.js';\n *\n * const vectorSource = new Vector({\n *   loader: async (extent, resolution, projection) => {\n *      const url = 'https://ahocevar.com/geoserver/wfs?service=WFS&' +\n *          'version=1.1.0&request=GetFeature&typename=osm:water_areas&' +\n *          'outputFormat=application/json' +\n *          'bbox=' + extent.join(',') + ',' + projection.getCode();\n *      const response = await fetch(url);\n *      if (!response.ok) {\n *        throw new Error('Network response was not ok');\n *      }\n *      const json = await response.json();\n *      const features = new GeoJSON().readFeatures(json, {\n *        featureProjection: projection,\n *      });\n *      return features;\n *    },\n *    strategy: bbox,\n *  });\n * ```\n *\n * When you want to retry a failed request, use\n * ```js\n * vectorSource.removeLoadedExtent(extent);\n * vectorSource.changed();\n * ```\n *\n * @property {boolean} [overlaps=true] This source may have overlapping geometries.\n * Setting this to `false` (e.g. for sources with polygons that represent administrative\n * boundaries or TopoJSON sources) allows the renderer to optimise fill and\n * stroke operations.\n * @property {LoadingStrategy} [strategy] The loading strategy to use.\n * By default an {@link module:ol/loadingstrategy.all}\n * strategy is used, a one-off strategy which loads all features at once.\n * @property {string|import(\"../featureloader.js\").FeatureUrlFunction} [url]\n * Setting this option instructs the source to load features using an XHR loader\n * (see {@link module:ol/featureloader.xhr}). Use a `string` and an\n * {@link module:ol/loadingstrategy.all} for a one-off download of all features from\n * the given URL. Use a {@link module:ol/featureloader~FeatureUrlFunction} to generate the url with\n * other loading strategies.\n * Requires `format` to be set as well.\n * When default XHR feature loader is provided, the features will\n * be transformed from the data projection to the view projection\n * during parsing. If your remote data source does not advertise its projection\n * properly, this transformation will be incorrect. For some formats, the\n * default projection (usually EPSG:4326) can be overridden by setting the\n * dataProjection constructor option on the format.\n * Note that if a source contains non-feature data, such as a GeoJSON geometry\n * or a KML NetworkLink, these will be ignored. Use a custom loader to load these.\n * @property {boolean} [useSpatialIndex=true]\n * By default, an RTree is used as spatial index. When features are removed and\n * added frequently, and the total number of features is low, setting this to\n * `false` may improve performance.\n *\n * Note that\n * {@link module:ol/source/Vector~VectorSource#getFeaturesInExtent},\n * {@link module:ol/source/Vector~VectorSource#getClosestFeatureToCoordinate} and\n * {@link module:ol/source/Vector~VectorSource#getExtent} cannot be used when `useSpatialIndex` is\n * set to `false`, and {@link module:ol/source/Vector~VectorSource#forEachFeatureInExtent} will loop\n * through all features.\n *\n * When set to `false`, the features will be maintained in an\n * {@link module:ol/Collection~Collection}, which can be retrieved through\n * {@link module:ol/source/Vector~VectorSource#getFeaturesCollection}.\n * @property {boolean} [wrapX=true] Wrap the world horizontally. For vector editing across the\n * -180\u00B0 and 180\u00B0 meridians to work properly, this should be set to `false`. The\n * resulting geometry coordinates will then exceed the world bounds.\n */\n\n/**\n * @classdesc\n * Provides a source of features for vector layers. Vector features provided\n * by this source are suitable for editing. See {@link module:ol/source/VectorTile~VectorTile} for\n * vector data that is optimized for rendering.\n *\n * @fires VectorSourceEvent\n * @api\n * @template {import(\"../Feature.js\").FeatureLike} [FeatureType=import(\"../Feature.js\").default]\n */\nclass VectorSource extends Source {\n  /**\n   * @param {Options<FeatureType>} [options] Vector source options.\n   */\n  constructor(options) {\n    options = options || {};\n\n    super({\n      attributions: options.attributions,\n      interpolate: true,\n      projection: undefined,\n      state: 'ready',\n      wrapX: options.wrapX !== undefined ? options.wrapX : true,\n    });\n\n    /***\n     * @type {VectorSourceOnSignature<import(\"../events.js\").EventsKey, FeatureType>}\n     */\n    this.on;\n\n    /***\n     * @type {VectorSourceOnSignature<import(\"../events.js\").EventsKey, FeatureType>}\n     */\n    this.once;\n\n    /***\n     * @type {VectorSourceOnSignature<void>}\n     */\n    this.un;\n\n    /**\n     * @private\n     * @type {import(\"../featureloader.js\").FeatureLoader<import(\"../Feature.js\").FeatureLike>}\n     */\n    this.loader_ = VOID;\n\n    /**\n     * @private\n     * @type {import(\"../format/Feature.js\").default<FeatureType>|null}\n     */\n    this.format_ = options.format || null;\n\n    /**\n     * @private\n     * @type {boolean}\n     */\n    this.overlaps_ = options.overlaps === undefined ? true : options.overlaps;\n\n    /**\n     * @private\n     * @type {string|import(\"../featureloader.js\").FeatureUrlFunction|undefined}\n     */\n    this.url_ = options.url;\n\n    if (options.loader !== undefined) {\n      this.loader_ = options.loader;\n    } else if (this.url_ !== undefined) {\n      assert(this.format_, '`format` must be set when `url` is set');\n      // create a XHR feature loader for \"url\" and \"format\"\n      this.loader_ = xhr(this.url_, this.format_);\n    }\n\n    /**\n     * @private\n     * @type {LoadingStrategy}\n     */\n    this.strategy_ =\n      options.strategy !== undefined ? options.strategy : allStrategy;\n\n    const useSpatialIndex =\n      options.useSpatialIndex !== undefined ? options.useSpatialIndex : true;\n\n    /**\n     * @private\n     * @type {RBush<FeatureType>}\n     */\n    this.featuresRtree_ = useSpatialIndex ? new RBush() : null;\n\n    /**\n     * @private\n     * @type {RBush<{extent: import(\"../extent.js\").Extent}>}\n     */\n    this.loadedExtentsRtree_ = new RBush();\n\n    /**\n     * @private\n     * @type {!Object<string, FeatureType>}\n     */\n    this.nullGeometryFeatures_ = {};\n\n    /**\n     * A lookup of features by id (the return from feature.getId()).\n     * @private\n     * @type {!Object<string, import('../Feature.js').FeatureLike|Array<import('../Feature.js').FeatureLike>>}\n     */\n    this.idIndex_ = {};\n\n    /**\n     * A lookup of features by uid (using getUid(feature)).\n     * @private\n     * @type {!Object<string, FeatureType>}\n     */\n    this.uidIndex_ = {};\n\n    /**\n     * @private\n     * @type {Object<string, Array<import(\"../events.js\").EventsKey>>}\n     */\n    this.featureChangeKeys_ = {};\n\n    /**\n     * @private\n     * @type {Collection<FeatureType>|null}\n     */\n    this.featuresCollection_ = null;\n\n    /** @type {Collection<FeatureType>} */\n    let collection;\n    /** @type {Array<FeatureType>} */\n    let features;\n    if (Array.isArray(options.features)) {\n      features = options.features;\n    } else if (options.features) {\n      collection = options.features;\n      features = collection.getArray();\n    }\n    if (!useSpatialIndex && collection === undefined) {\n      collection = new Collection(features);\n    }\n    if (features !== undefined) {\n      this.addFeaturesInternal(features);\n    }\n    if (collection !== undefined) {\n      this.bindFeaturesCollection_(collection);\n    }\n  }\n\n  /**\n   * Add a single feature to the source.  If you want to add a batch of features\n   * at once, call {@link module:ol/source/Vector~VectorSource#addFeatures #addFeatures()}\n   * instead. A feature will not be added to the source if feature with\n   * the same id is already there. The reason for this behavior is to avoid\n   * feature duplication when using bbox or tile loading strategies.\n   * Note: this also applies if a {@link module:ol/Collection~Collection} is used for features,\n   * meaning that if a feature with a duplicate id is added in the collection, it will\n   * be removed from it right away.\n   * @param {FeatureType} feature Feature to add.\n   * @api\n   */\n  addFeature(feature) {\n    this.addFeatureInternal(feature);\n    this.changed();\n  }\n\n  /**\n   * Add a feature without firing a `change` event.\n   * @param {FeatureType} feature Feature.\n   * @protected\n   */\n  addFeatureInternal(feature) {\n    const featureKey = getUid(feature);\n\n    if (!this.addToIndex_(featureKey, feature)) {\n      if (this.featuresCollection_) {\n        this.featuresCollection_.remove(feature);\n      }\n      return;\n    }\n\n    this.setupChangeEvents_(featureKey, feature);\n\n    const geometry = feature.getGeometry();\n    if (geometry) {\n      const extent = geometry.getExtent();\n      if (this.featuresRtree_) {\n        this.featuresRtree_.insert(extent, feature);\n      }\n    } else {\n      this.nullGeometryFeatures_[featureKey] = feature;\n    }\n\n    this.dispatchEvent(\n      new VectorSourceEvent(VectorEventType.ADDFEATURE, feature),\n    );\n  }\n\n  /**\n   * @param {string} featureKey Unique identifier for the feature.\n   * @param {FeatureType} feature The feature.\n   * @private\n   */\n  setupChangeEvents_(featureKey, feature) {\n    if (feature instanceof RenderFeature) {\n      return;\n    }\n    this.featureChangeKeys_[featureKey] = [\n      listen(feature, EventType.CHANGE, this.handleFeatureChange_, this),\n      listen(\n        feature,\n        ObjectEventType.PROPERTYCHANGE,\n        this.handleFeatureChange_,\n        this,\n      ),\n    ];\n  }\n\n  /**\n   * @param {string} featureKey Unique identifier for the feature.\n   * @param {FeatureType} feature The feature.\n   * @return {boolean} The feature is \"valid\", in the sense that it is also a\n   *     candidate for insertion into the Rtree.\n   * @private\n   */\n  addToIndex_(featureKey, feature) {\n    let valid = true;\n    if (feature.getId() !== undefined) {\n      const id = String(feature.getId());\n      if (!(id in this.idIndex_)) {\n        this.idIndex_[id] = feature;\n      } else if (feature instanceof RenderFeature) {\n        const indexedFeature = this.idIndex_[id];\n        if (!(indexedFeature instanceof RenderFeature)) {\n          valid = false;\n        } else if (!Array.isArray(indexedFeature)) {\n          this.idIndex_[id] = [indexedFeature, feature];\n        } else {\n          indexedFeature.push(feature);\n        }\n      } else {\n        valid = false;\n      }\n    }\n    if (valid) {\n      assert(\n        !(featureKey in this.uidIndex_),\n        'The passed `feature` was already added to the source',\n      );\n      this.uidIndex_[featureKey] = feature;\n    }\n    return valid;\n  }\n\n  /**\n   * Add a batch of features to the source.\n   * @param {Array<FeatureType>} features Features to add.\n   * @api\n   */\n  addFeatures(features) {\n    this.addFeaturesInternal(features);\n    this.changed();\n  }\n\n  /**\n   * Add features without firing a `change` event.\n   * @param {Array<FeatureType>} features Features.\n   * @protected\n   */\n  addFeaturesInternal(features) {\n    const extents = [];\n    /** @type {Array<FeatureType>} */\n    const newFeatures = [];\n    /** @type {Array<FeatureType>} */\n    const geometryFeatures = [];\n\n    for (let i = 0, length = features.length; i < length; i++) {\n      const feature = features[i];\n      const featureKey = getUid(feature);\n      if (this.addToIndex_(featureKey, feature)) {\n        newFeatures.push(feature);\n      }\n    }\n\n    for (let i = 0, length = newFeatures.length; i < length; i++) {\n      const feature = newFeatures[i];\n      const featureKey = getUid(feature);\n      this.setupChangeEvents_(featureKey, feature);\n\n      const geometry = feature.getGeometry();\n      if (geometry) {\n        const extent = geometry.getExtent();\n        extents.push(extent);\n        geometryFeatures.push(feature);\n      } else {\n        this.nullGeometryFeatures_[featureKey] = feature;\n      }\n    }\n    if (this.featuresRtree_) {\n      this.featuresRtree_.load(extents, geometryFeatures);\n    }\n\n    if (this.hasListener(VectorEventType.ADDFEATURE)) {\n      for (let i = 0, length = newFeatures.length; i < length; i++) {\n        this.dispatchEvent(\n          new VectorSourceEvent(VectorEventType.ADDFEATURE, newFeatures[i]),\n        );\n      }\n    }\n  }\n\n  /**\n   * @param {!Collection<FeatureType>} collection Collection.\n   * @private\n   */\n  bindFeaturesCollection_(collection) {\n    let modifyingCollection = false;\n    this.addEventListener(\n      VectorEventType.ADDFEATURE,\n      /**\n       * @param {VectorSourceEvent<FeatureType>} evt The vector source event\n       */\n      function (evt) {\n        if (!modifyingCollection) {\n          modifyingCollection = true;\n          collection.push(evt.feature);\n          modifyingCollection = false;\n        }\n      },\n    );\n    this.addEventListener(\n      VectorEventType.REMOVEFEATURE,\n      /**\n       * @param {VectorSourceEvent<FeatureType>} evt The vector source event\n       */\n      function (evt) {\n        if (!modifyingCollection) {\n          modifyingCollection = true;\n          collection.remove(evt.feature);\n          modifyingCollection = false;\n        }\n      },\n    );\n    collection.addEventListener(\n      CollectionEventType.ADD,\n      /**\n       * @param {import(\"../Collection.js\").CollectionEvent<FeatureType>} evt The collection event\n       */\n      (evt) => {\n        if (!modifyingCollection) {\n          modifyingCollection = true;\n          this.addFeature(evt.element);\n          modifyingCollection = false;\n        }\n      },\n    );\n    collection.addEventListener(\n      CollectionEventType.REMOVE,\n      /**\n       * @param {import(\"../Collection.js\").CollectionEvent<FeatureType>} evt The collection event\n       */\n      (evt) => {\n        if (!modifyingCollection) {\n          modifyingCollection = true;\n          this.removeFeature(evt.element);\n          modifyingCollection = false;\n        }\n      },\n    );\n    this.featuresCollection_ = collection;\n  }\n\n  /**\n   * Remove all features from the source.\n   * @param {boolean} [fast] Skip dispatching of {@link module:ol/source/Vector.VectorSourceEvent#event:removefeature} events.\n   * @api\n   */\n  clear(fast) {\n    if (fast) {\n      for (const featureId in this.featureChangeKeys_) {\n        const keys = this.featureChangeKeys_[featureId];\n        keys.forEach(unlistenByKey);\n      }\n      if (!this.featuresCollection_) {\n        this.featureChangeKeys_ = {};\n        this.idIndex_ = {};\n        this.uidIndex_ = {};\n      }\n    } else {\n      if (this.featuresRtree_) {\n        this.featuresRtree_.forEach((feature) => {\n          this.removeFeatureInternal(feature);\n        });\n        for (const id in this.nullGeometryFeatures_) {\n          this.removeFeatureInternal(this.nullGeometryFeatures_[id]);\n        }\n      }\n    }\n    if (this.featuresCollection_) {\n      this.featuresCollection_.clear();\n    }\n\n    if (this.featuresRtree_) {\n      this.featuresRtree_.clear();\n    }\n    this.nullGeometryFeatures_ = {};\n\n    const clearEvent = new VectorSourceEvent(VectorEventType.CLEAR);\n    this.dispatchEvent(clearEvent);\n    this.changed();\n  }\n\n  /**\n   * Iterate through all features on the source, calling the provided callback\n   * with each one.  If the callback returns any \"truthy\" value, iteration will\n   * stop and the function will return the same value.\n   * Note: this function only iterate through the feature that have a defined geometry.\n   *\n   * @param {function(FeatureType): T} callback Called with each feature\n   *     on the source.  Return a truthy value to stop iteration.\n   * @return {T|undefined} The return value from the last call to the callback.\n   * @template T\n   * @api\n   */\n  forEachFeature(callback) {\n    if (this.featuresRtree_) {\n      return this.featuresRtree_.forEach(callback);\n    }\n    if (this.featuresCollection_) {\n      this.featuresCollection_.forEach(callback);\n    }\n  }\n\n  /**\n   * Iterate through all features whose geometries contain the provided\n   * coordinate, calling the callback with each feature.  If the callback returns\n   * a \"truthy\" value, iteration will stop and the function will return the same\n   * value.\n   *\n   * For {@link module:ol/render/Feature~RenderFeature} features, the callback will be\n   * called for all features.\n   *\n   * @param {import(\"../coordinate.js\").Coordinate} coordinate Coordinate.\n   * @param {function(FeatureType): T} callback Called with each feature\n   *     whose goemetry contains the provided coordinate.\n   * @return {T|undefined} The return value from the last call to the callback.\n   * @template T\n   */\n  forEachFeatureAtCoordinateDirect(coordinate, callback) {\n    const extent = [coordinate[0], coordinate[1], coordinate[0], coordinate[1]];\n    return this.forEachFeatureInExtent(extent, function (feature) {\n      const geometry = feature.getGeometry();\n      if (\n        geometry instanceof RenderFeature ||\n        geometry.intersectsCoordinate(coordinate)\n      ) {\n        return callback(feature);\n      }\n      return undefined;\n    });\n  }\n\n  /**\n   * Iterate through all features whose bounding box intersects the provided\n   * extent (note that the feature's geometry may not intersect the extent),\n   * calling the callback with each feature.  If the callback returns a \"truthy\"\n   * value, iteration will stop and the function will return the same value.\n   *\n   * If you are interested in features whose geometry intersects an extent, call\n   * the {@link module:ol/source/Vector~VectorSource#forEachFeatureIntersectingExtent #forEachFeatureIntersectingExtent()} method instead.\n   *\n   * When `useSpatialIndex` is set to false, this method will loop through all\n   * features, equivalent to {@link module:ol/source/Vector~VectorSource#forEachFeature #forEachFeature()}.\n   *\n   * @param {import(\"../extent.js\").Extent} extent Extent.\n   * @param {function(FeatureType): T} callback Called with each feature\n   *     whose bounding box intersects the provided extent.\n   * @return {T|undefined} The return value from the last call to the callback.\n   * @template T\n   * @api\n   */\n  forEachFeatureInExtent(extent, callback) {\n    if (this.featuresRtree_) {\n      return this.featuresRtree_.forEachInExtent(extent, callback);\n    }\n    if (this.featuresCollection_) {\n      this.featuresCollection_.forEach(callback);\n    }\n  }\n\n  /**\n   * Iterate through all features whose geometry intersects the provided extent,\n   * calling the callback with each feature.  If the callback returns a \"truthy\"\n   * value, iteration will stop and the function will return the same value.\n   *\n   * If you only want to test for bounding box intersection, call the\n   * {@link module:ol/source/Vector~VectorSource#forEachFeatureInExtent #forEachFeatureInExtent()} method instead.\n   *\n   * @param {import(\"../extent.js\").Extent} extent Extent.\n   * @param {function(FeatureType): T} callback Called with each feature\n   *     whose geometry intersects the provided extent.\n   * @return {T|undefined} The return value from the last call to the callback.\n   * @template T\n   * @api\n   */\n  forEachFeatureIntersectingExtent(extent, callback) {\n    return this.forEachFeatureInExtent(\n      extent,\n      /**\n       * @param {FeatureType} feature Feature.\n       * @return {T|undefined} The return value from the last call to the callback.\n       */\n      function (feature) {\n        const geometry = feature.getGeometry();\n        if (\n          geometry instanceof RenderFeature ||\n          geometry.intersectsExtent(extent)\n        ) {\n          const result = callback(feature);\n          if (result) {\n            return result;\n          }\n        }\n      },\n    );\n  }\n\n  /**\n   * Get the features collection associated with this source. Will be `null`\n   * unless the source was configured with `useSpatialIndex` set to `false`, or\n   * with a {@link module:ol/Collection~Collection} as `features`.\n   * @return {Collection<FeatureType>|null} The collection of features.\n   * @api\n   */\n  getFeaturesCollection() {\n    return this.featuresCollection_;\n  }\n\n  /**\n   * Get a snapshot of the features currently on the source in random order. The returned array\n   * is a copy, the features are references to the features in the source.\n   * @return {Array<FeatureType>} Features.\n   * @api\n   */\n  getFeatures() {\n    let features;\n    if (this.featuresCollection_) {\n      features = this.featuresCollection_.getArray().slice(0);\n    } else if (this.featuresRtree_) {\n      features = this.featuresRtree_.getAll();\n      if (!isEmpty(this.nullGeometryFeatures_)) {\n        extend(features, Object.values(this.nullGeometryFeatures_));\n      }\n    }\n    return features;\n  }\n\n  /**\n   * Get all features whose geometry intersects the provided coordinate.\n   * @param {import(\"../coordinate.js\").Coordinate} coordinate Coordinate.\n   * @return {Array<FeatureType>} Features.\n   * @api\n   */\n  getFeaturesAtCoordinate(coordinate) {\n    /** @type {Array<FeatureType>} */\n    const features = [];\n    this.forEachFeatureAtCoordinateDirect(coordinate, function (feature) {\n      features.push(feature);\n    });\n    return features;\n  }\n\n  /**\n   * Get all features whose bounding box intersects the provided extent.  Note that this returns an array of\n   * all features intersecting the given extent in random order (so it may include\n   * features whose geometries do not intersect the extent).\n   *\n   * When `useSpatialIndex` is set to false, this method will return all\n   * features.\n   *\n   * @param {import(\"../extent.js\").Extent} extent Extent.\n   * @param {import(\"../proj/Projection.js\").default} [projection] Include features\n   * where `extent` exceeds the x-axis bounds of `projection` and wraps around the world.\n   * @return {Array<FeatureType>} Features.\n   * @api\n   */\n  getFeaturesInExtent(extent, projection) {\n    if (this.featuresRtree_) {\n      const multiWorld = projection && projection.canWrapX() && this.getWrapX();\n\n      if (!multiWorld) {\n        return this.featuresRtree_.getInExtent(extent);\n      }\n\n      const extents = wrapAndSliceX(extent, projection);\n\n      return [].concat(\n        ...extents.map((anExtent) => this.featuresRtree_.getInExtent(anExtent)),\n      );\n    }\n    if (this.featuresCollection_) {\n      return this.featuresCollection_.getArray().slice(0);\n    }\n    return [];\n  }\n\n  /**\n   * Get the closest feature to the provided coordinate.\n   *\n   * This method is not available when the source is configured with\n   * `useSpatialIndex` set to `false` and the features in this source are of type\n   * {@link module:ol/Feature~Feature}.\n   * @param {import(\"../coordinate.js\").Coordinate} coordinate Coordinate.\n   * @param {function(FeatureType):boolean} [filter] Feature filter function.\n   *     The filter function will receive one argument, the {@link module:ol/Feature~Feature feature}\n   *     and it should return a boolean value. By default, no filtering is made.\n   * @return {FeatureType|null} Closest feature (or `null` if none found).\n   * @api\n   */\n  getClosestFeatureToCoordinate(coordinate, filter) {\n    // Find the closest feature using branch and bound.  We start searching an\n    // infinite extent, and find the distance from the first feature found.  This\n    // becomes the closest feature.  We then compute a smaller extent which any\n    // closer feature must intersect.  We continue searching with this smaller\n    // extent, trying to find a closer feature.  Every time we find a closer\n    // feature, we update the extent being searched so that any even closer\n    // feature must intersect it.  We continue until we run out of features.\n    const x = coordinate[0];\n    const y = coordinate[1];\n    let closestFeature = null;\n    const closestPoint = [NaN, NaN];\n    let minSquaredDistance = Infinity;\n    const extent = [-Infinity, -Infinity, Infinity, Infinity];\n    filter = filter ? filter : TRUE;\n    this.featuresRtree_.forEachInExtent(\n      extent,\n      /**\n       * @param {FeatureType} feature Feature.\n       */\n      function (feature) {\n        if (filter(feature)) {\n          const geometry = feature.getGeometry();\n          const previousMinSquaredDistance = minSquaredDistance;\n          minSquaredDistance =\n            geometry instanceof RenderFeature\n              ? 0\n              : geometry.closestPointXY(x, y, closestPoint, minSquaredDistance);\n          if (minSquaredDistance < previousMinSquaredDistance) {\n            closestFeature = feature;\n            // This is sneaky.  Reduce the extent that it is currently being\n            // searched while the R-Tree traversal using this same extent object\n            // is still in progress.  This is safe because the new extent is\n            // strictly contained by the old extent.\n            const minDistance = Math.sqrt(minSquaredDistance);\n            extent[0] = x - minDistance;\n            extent[1] = y - minDistance;\n            extent[2] = x + minDistance;\n            extent[3] = y + minDistance;\n          }\n        }\n      },\n    );\n    return closestFeature;\n  }\n\n  /**\n   * Get the extent of the features currently in the source.\n   *\n   * This will return `null` when the source is configured with\n   * `useSpatialIndex` set to `false`.\n   * @param {import(\"../extent.js\").Extent} [extent] Destination extent. If provided, no new extent\n   *     will be created. Instead, that extent's coordinates will be overwritten.\n   * @return {import(\"../extent.js\").Extent | null} Extent.\n   * @api\n   */\n  getExtent(extent) {\n    return this.featuresRtree_?.getExtent(extent) ?? null;\n  }\n\n  /**\n   * Get a feature by its identifier (the value returned by feature.getId()). When `RenderFeature`s\n   * are used, `getFeatureById()` can return an array of `RenderFeature`s. This allows for handling\n   * of `GeometryCollection` geometries, where format readers create one `RenderFeature` per\n   * `GeometryCollection` member.\n   * Note that the index treats string and numeric identifiers as the same.  So\n   * `source.getFeatureById(2)` will return a feature with id `'2'` or `2`.\n   *\n   * @param {string|number} id Feature identifier.\n   * @return {FeatureClassOrArrayOfRenderFeatures<FeatureType>|null} The feature (or `null` if not found).\n   * @api\n   */\n  getFeatureById(id) {\n    const feature = this.idIndex_[id.toString()];\n    return feature !== undefined\n      ? /** @type {FeatureClassOrArrayOfRenderFeatures<FeatureType>} */ (\n          feature\n        )\n      : null;\n  }\n\n  /**\n   * Get a feature by its internal unique identifier (using `getUid`).\n   *\n   * @param {string} uid Feature identifier.\n   * @return {FeatureType|null} The feature (or `null` if not found).\n   */\n  getFeatureByUid(uid) {\n    const feature = this.uidIndex_[uid];\n    return feature !== undefined ? feature : null;\n  }\n\n  /**\n   * Get the format associated with this source.\n   *\n   * @return {import(\"../format/Feature.js\").default<FeatureType>|null}} The feature format.\n   * @api\n   */\n  getFormat() {\n    return this.format_;\n  }\n\n  /**\n   * @return {boolean} The source can have overlapping geometries.\n   */\n  getOverlaps() {\n    return this.overlaps_;\n  }\n\n  /**\n   * Get the url associated with this source.\n   *\n   * @return {string|import(\"../featureloader.js\").FeatureUrlFunction|undefined} The url.\n   * @api\n   */\n  getUrl() {\n    return this.url_;\n  }\n\n  /**\n   * @param {Event} event Event.\n   * @private\n   */\n  handleFeatureChange_(event) {\n    const feature = /** @type {FeatureType} */ (event.target);\n    const featureKey = getUid(feature);\n    const geometry = feature.getGeometry();\n    if (!geometry) {\n      if (!(featureKey in this.nullGeometryFeatures_)) {\n        if (this.featuresRtree_) {\n          this.featuresRtree_.remove(feature);\n        }\n        this.nullGeometryFeatures_[featureKey] = feature;\n      }\n    } else {\n      const extent = geometry.getExtent();\n      if (featureKey in this.nullGeometryFeatures_) {\n        delete this.nullGeometryFeatures_[featureKey];\n        if (this.featuresRtree_) {\n          this.featuresRtree_.insert(extent, feature);\n        }\n      } else {\n        if (this.featuresRtree_) {\n          this.featuresRtree_.update(extent, feature);\n        }\n      }\n    }\n    const id = feature.getId();\n    if (id !== undefined) {\n      const sid = id.toString();\n      if (this.idIndex_[sid] !== feature) {\n        this.removeFromIdIndex_(feature);\n        this.idIndex_[sid] = feature;\n      }\n    } else {\n      this.removeFromIdIndex_(feature);\n      this.uidIndex_[featureKey] = feature;\n    }\n    this.changed();\n    this.dispatchEvent(\n      new VectorSourceEvent(VectorEventType.CHANGEFEATURE, feature),\n    );\n  }\n\n  /**\n   * Returns true if the feature is contained within the source.\n   * @param {FeatureType} feature Feature.\n   * @return {boolean} Has feature.\n   * @api\n   */\n  hasFeature(feature) {\n    const id = feature.getId();\n    if (id !== undefined) {\n      return id in this.idIndex_;\n    }\n    return getUid(feature) in this.uidIndex_;\n  }\n\n  /**\n   * @return {boolean} Is empty.\n   */\n  isEmpty() {\n    if (this.featuresRtree_) {\n      return (\n        this.featuresRtree_.isEmpty() && isEmpty(this.nullGeometryFeatures_)\n      );\n    }\n    if (this.featuresCollection_) {\n      return this.featuresCollection_.getLength() === 0;\n    }\n    return true;\n  }\n\n  /**\n   * @param {import(\"../extent.js\").Extent} extent Extent.\n   * @param {number} resolution Resolution.\n   * @param {import(\"../proj/Projection.js\").default} projection Projection.\n   */\n  loadFeatures(extent, resolution, projection) {\n    const loadedExtentsRtree = this.loadedExtentsRtree_;\n    const extentsToLoad = this.strategy_(extent, resolution, projection);\n    for (let i = 0, ii = extentsToLoad.length; i < ii; ++i) {\n      const extentToLoad = extentsToLoad[i];\n      const alreadyLoaded = loadedExtentsRtree.forEachInExtent(\n        extentToLoad,\n        /**\n         * @param {{extent: import(\"../extent.js\").Extent}} object Object.\n         * @return {boolean} Contains.\n         */\n        function (object) {\n          return containsExtent(object.extent, extentToLoad);\n        },\n      );\n      if (!alreadyLoaded) {\n        this.loading = Number(this.loading) + 1;\n        this.dispatchEvent(\n          new VectorSourceEvent(VectorEventType.FEATURESLOADSTART),\n        );\n\n        /**\n         * @param {Array<FeatureType>} features Loaded features\n         */\n        const success = (features) => {\n          this.loading = Number(this.loading) - 1;\n          this.dispatchEvent(\n            new VectorSourceEvent(\n              VectorEventType.FEATURESLOADEND,\n              undefined,\n              features,\n            ),\n          );\n        };\n\n        const failure = () => {\n          this.changed();\n          this.loading = Number(this.loading) - 1;\n          this.dispatchEvent(\n            new VectorSourceEvent(VectorEventType.FEATURESLOADERROR),\n          );\n        };\n\n        //TODO Remove this when the deprecatedsuccess and failure arguments are removed\n        let disableCallbacks = false;\n\n        const loaded = this.loader_.call(\n          this,\n          extentToLoad,\n          resolution,\n          projection,\n          (features) => disableCallbacks || success(features),\n          () => disableCallbacks || failure(),\n        );\n        if (loaded instanceof Promise) {\n          //TODO Remove this when the deprecatedsuccess and failure arguments are removed\n          disableCallbacks = true;\n          loaded\n            .then((features) => {\n              this.addFeatures(features);\n              success(features);\n            })\n            .catch(failure);\n        } else if (this.loader_.length < 4) {\n          this.loading = false;\n        }\n        loadedExtentsRtree.insert(extentToLoad, {extent: extentToLoad.slice()});\n      }\n    }\n  }\n\n  /**\n   * @override\n   */\n  refresh() {\n    this.clear(true);\n    this.loadedExtentsRtree_.clear();\n    super.refresh();\n  }\n\n  /**\n   * Remove an extent from the list of loaded extents.\n   * @param {import(\"../extent.js\").Extent} extent Extent.\n   * @api\n   */\n  removeLoadedExtent(extent) {\n    const loadedExtentsRtree = this.loadedExtentsRtree_;\n    const obj = loadedExtentsRtree.forEachInExtent(extent, function (object) {\n      if (equals(object.extent, extent)) {\n        return object;\n      }\n    });\n    if (obj) {\n      loadedExtentsRtree.remove(obj);\n    }\n  }\n\n  /**\n   * Batch remove features from the source.  If you want to remove all features\n   * at once, use the {@link module:ol/source/Vector~VectorSource#clear #clear()} method\n   * instead.\n   * @param {Array<FeatureType>} features Features to remove.\n   * @api\n   */\n  removeFeatures(features) {\n    let removed = false;\n    for (let i = 0, ii = features.length; i < ii; ++i) {\n      removed = this.removeFeatureInternal(features[i]) || removed;\n    }\n    if (removed) {\n      this.changed();\n    }\n  }\n\n  /**\n   * Remove a single feature from the source. If you want to batch remove\n   * features, use the {@link module:ol/source/Vector~VectorSource#removeFeatures #removeFeatures()} method\n   * instead.\n   * @param {FeatureType} feature Feature to remove.\n   * @api\n   */\n  removeFeature(feature) {\n    if (!feature) {\n      return;\n    }\n    const removed = this.removeFeatureInternal(feature);\n    if (removed) {\n      this.changed();\n    }\n  }\n\n  /**\n   * Remove feature without firing a `change` event.\n   * @param {FeatureType} feature Feature.\n   * @return {boolean} True if the feature was removed, false if it was not found.\n   * @protected\n   */\n  removeFeatureInternal(feature) {\n    const featureKey = getUid(feature);\n    if (!(featureKey in this.uidIndex_)) {\n      return false;\n    }\n\n    if (featureKey in this.nullGeometryFeatures_) {\n      delete this.nullGeometryFeatures_[featureKey];\n    } else {\n      if (this.featuresRtree_) {\n        this.featuresRtree_.remove(feature);\n      }\n    }\n\n    const featureChangeKeys = this.featureChangeKeys_[featureKey];\n    featureChangeKeys?.forEach(unlistenByKey);\n    delete this.featureChangeKeys_[featureKey];\n\n    const id = feature.getId();\n    if (id !== undefined) {\n      const idString = id.toString();\n      const indexedFeature = this.idIndex_[idString];\n      if (indexedFeature === feature) {\n        delete this.idIndex_[idString];\n      } else if (Array.isArray(indexedFeature)) {\n        indexedFeature.splice(indexedFeature.indexOf(feature), 1);\n        if (indexedFeature.length === 1) {\n          this.idIndex_[idString] = indexedFeature[0];\n        }\n      }\n    }\n    delete this.uidIndex_[featureKey];\n    if (this.hasListener(VectorEventType.REMOVEFEATURE)) {\n      this.dispatchEvent(\n        new VectorSourceEvent(VectorEventType.REMOVEFEATURE, feature),\n      );\n    }\n    return true;\n  }\n\n  /**\n   * Remove a feature from the id index.  Called internally when the feature id\n   * may have changed.\n   * @param {FeatureType} feature The feature.\n   * @private\n   */\n  removeFromIdIndex_(feature) {\n    for (const id in this.idIndex_) {\n      if (this.idIndex_[id] === feature) {\n        delete this.idIndex_[id];\n        break;\n      }\n    }\n  }\n\n  /**\n   * Set the new loader of the source. The next render cycle will use the\n   * new loader.\n   * @param {import(\"../featureloader.js\").FeatureLoader} loader The loader to set.\n   * @api\n   */\n  setLoader(loader) {\n    this.loader_ = loader;\n  }\n\n  /**\n   * Points the source to a new url. The next render cycle will use the new url.\n   * @param {string|import(\"../featureloader.js\").FeatureUrlFunction} url Url.\n   * @api\n   */\n  setUrl(url) {\n    assert(this.format_, '`format` must be set when `url` is set');\n    this.url_ = url;\n    this.setLoader(xhr(url, this.format_));\n  }\n\n  /**\n   * @param {boolean} overlaps The source can have overlapping geometries.\n   */\n  setOverlaps(overlaps) {\n    this.overlaps_ = overlaps;\n    this.changed();\n  }\n}\n\nexport default VectorSource;\n", "/**\n * @module ol/geom/GeometryCollection\n */\nimport {listen, unlistenByKey} from '../events.js';\nimport EventType from '../events/EventType.js';\nimport {\n  closestSquaredDistanceXY,\n  createOrUpdateEmpty,\n  extend,\n  getCenter,\n} from '../extent.js';\nimport Geometry from './Geometry.js';\n\n/**\n * @classdesc\n * An array of {@link module:ol/geom/Geometry~Geometry} objects.\n *\n * @api\n */\nclass GeometryCollection extends Geometry {\n  /**\n   * @param {Array<Geometry>} geometries Geometries.\n   */\n  constructor(geometries) {\n    super();\n\n    /**\n     * @private\n     * @type {Array<Geometry>}\n     */\n    this.geometries_ = geometries;\n\n    /**\n     * @private\n     * @type {Array<import(\"../events.js\").EventsKey>}\n     */\n    this.changeEventsKeys_ = [];\n\n    this.listenGeometriesChange_();\n  }\n\n  /**\n   * @private\n   */\n  unlistenGeometriesChange_() {\n    this.changeEventsKeys_.forEach(unlistenByKey);\n    this.changeEventsKeys_.length = 0;\n  }\n\n  /**\n   * @private\n   */\n  listenGeometriesChange_() {\n    const geometries = this.geometries_;\n    for (let i = 0, ii = geometries.length; i < ii; ++i) {\n      this.changeEventsKeys_.push(\n        listen(geometries[i], EventType.CHANGE, this.changed, this),\n      );\n    }\n  }\n\n  /**\n   * Make a complete copy of the geometry.\n   * @return {!GeometryCollection} Clone.\n   * @api\n   * @override\n   */\n  clone() {\n    const geometryCollection = new GeometryCollection(\n      cloneGeometries(this.geometries_),\n    );\n    geometryCollection.applyProperties(this);\n    return geometryCollection;\n  }\n\n  /**\n   * @param {number} x X.\n   * @param {number} y Y.\n   * @param {import(\"../coordinate.js\").Coordinate} closestPoint Closest point.\n   * @param {number} minSquaredDistance Minimum squared distance.\n   * @return {number} Minimum squared distance.\n   * @override\n   */\n  closestPointXY(x, y, closestPoint, minSquaredDistance) {\n    if (minSquaredDistance < closestSquaredDistanceXY(this.getExtent(), x, y)) {\n      return minSquaredDistance;\n    }\n    const geometries = this.geometries_;\n    for (let i = 0, ii = geometries.length; i < ii; ++i) {\n      minSquaredDistance = geometries[i].closestPointXY(\n        x,\n        y,\n        closestPoint,\n        minSquaredDistance,\n      );\n    }\n    return minSquaredDistance;\n  }\n\n  /**\n   * @param {number} x X.\n   * @param {number} y Y.\n   * @return {boolean} Contains (x, y).\n   * @override\n   */\n  containsXY(x, y) {\n    const geometries = this.geometries_;\n    for (let i = 0, ii = geometries.length; i < ii; ++i) {\n      if (geometries[i].containsXY(x, y)) {\n        return true;\n      }\n    }\n    return false;\n  }\n\n  /**\n   * @param {import(\"../extent.js\").Extent} extent Extent.\n   * @protected\n   * @return {import(\"../extent.js\").Extent} extent Extent.\n   * @override\n   */\n  computeExtent(extent) {\n    createOrUpdateEmpty(extent);\n    const geometries = this.geometries_;\n    for (let i = 0, ii = geometries.length; i < ii; ++i) {\n      extend(extent, geometries[i].getExtent());\n    }\n    return extent;\n  }\n\n  /**\n   * Return the geometries that make up this geometry collection.\n   * @return {Array<Geometry>} Geometries.\n   * @api\n   */\n  getGeometries() {\n    return cloneGeometries(this.geometries_);\n  }\n\n  /**\n   * @return {Array<Geometry>} Geometries.\n   */\n  getGeometriesArray() {\n    return this.geometries_;\n  }\n\n  /**\n   * @return {Array<Geometry>} Geometries.\n   */\n  getGeometriesArrayRecursive() {\n    /** @type {Array<Geometry>} */\n    let geometriesArray = [];\n    const geometries = this.geometries_;\n    for (let i = 0, ii = geometries.length; i < ii; ++i) {\n      if (geometries[i].getType() === this.getType()) {\n        geometriesArray = geometriesArray.concat(\n          /** @type {GeometryCollection} */ (\n            geometries[i]\n          ).getGeometriesArrayRecursive(),\n        );\n      } else {\n        geometriesArray.push(geometries[i]);\n      }\n    }\n    return geometriesArray;\n  }\n\n  /**\n   * Create a simplified version of this geometry using the Douglas Peucker algorithm.\n   * @param {number} squaredTolerance Squared tolerance.\n   * @return {GeometryCollection} Simplified GeometryCollection.\n   * @override\n   */\n  getSimplifiedGeometry(squaredTolerance) {\n    if (this.simplifiedGeometryRevision !== this.getRevision()) {\n      this.simplifiedGeometryMaxMinSquaredTolerance = 0;\n      this.simplifiedGeometryRevision = this.getRevision();\n    }\n    if (\n      squaredTolerance < 0 ||\n      (this.simplifiedGeometryMaxMinSquaredTolerance !== 0 &&\n        squaredTolerance < this.simplifiedGeometryMaxMinSquaredTolerance)\n    ) {\n      return this;\n    }\n\n    const simplifiedGeometries = [];\n    const geometries = this.geometries_;\n    let simplified = false;\n    for (let i = 0, ii = geometries.length; i < ii; ++i) {\n      const geometry = geometries[i];\n      const simplifiedGeometry =\n        geometry.getSimplifiedGeometry(squaredTolerance);\n      simplifiedGeometries.push(simplifiedGeometry);\n      if (simplifiedGeometry !== geometry) {\n        simplified = true;\n      }\n    }\n    if (simplified) {\n      const simplifiedGeometryCollection = new GeometryCollection(\n        simplifiedGeometries,\n      );\n      return simplifiedGeometryCollection;\n    }\n    this.simplifiedGeometryMaxMinSquaredTolerance = squaredTolerance;\n    return this;\n  }\n\n  /**\n   * Get the type of this geometry.\n   * @return {import(\"./Geometry.js\").Type} Geometry type.\n   * @api\n   * @override\n   */\n  getType() {\n    return 'GeometryCollection';\n  }\n\n  /**\n   * Test if the geometry and the passed extent intersect.\n   * @param {import(\"../extent.js\").Extent} extent Extent.\n   * @return {boolean} `true` if the geometry and the extent intersect.\n   * @api\n   * @override\n   */\n  intersectsExtent(extent) {\n    const geometries = this.geometries_;\n    for (let i = 0, ii = geometries.length; i < ii; ++i) {\n      if (geometries[i].intersectsExtent(extent)) {\n        return true;\n      }\n    }\n    return false;\n  }\n\n  /**\n   * @return {boolean} Is empty.\n   */\n  isEmpty() {\n    return this.geometries_.length === 0;\n  }\n\n  /**\n   * Rotate the geometry around a given coordinate. This modifies the geometry\n   * coordinates in place.\n   * @param {number} angle Rotation angle in radians.\n   * @param {import(\"../coordinate.js\").Coordinate} anchor The rotation center.\n   * @api\n   * @override\n   */\n  rotate(angle, anchor) {\n    const geometries = this.geometries_;\n    for (let i = 0, ii = geometries.length; i < ii; ++i) {\n      geometries[i].rotate(angle, anchor);\n    }\n    this.changed();\n  }\n\n  /**\n   * Scale the geometry (with an optional origin).  This modifies the geometry\n   * coordinates in place.\n   * @abstract\n   * @param {number} sx The scaling factor in the x-direction.\n   * @param {number} [sy] The scaling factor in the y-direction (defaults to sx).\n   * @param {import(\"../coordinate.js\").Coordinate} [anchor] The scale origin (defaults to the center\n   *     of the geometry extent).\n   * @api\n   * @override\n   */\n  scale(sx, sy, anchor) {\n    if (!anchor) {\n      anchor = getCenter(this.getExtent());\n    }\n    const geometries = this.geometries_;\n    for (let i = 0, ii = geometries.length; i < ii; ++i) {\n      geometries[i].scale(sx, sy, anchor);\n    }\n    this.changed();\n  }\n\n  /**\n   * Set the geometries that make up this geometry collection.\n   * @param {Array<Geometry>} geometries Geometries.\n   * @api\n   */\n  setGeometries(geometries) {\n    this.setGeometriesArray(cloneGeometries(geometries));\n  }\n\n  /**\n   * @param {Array<Geometry>} geometries Geometries.\n   */\n  setGeometriesArray(geometries) {\n    this.unlistenGeometriesChange_();\n    this.geometries_ = geometries;\n    this.listenGeometriesChange_();\n    this.changed();\n  }\n\n  /**\n   * Apply a transform function to the coordinates of the geometry.\n   * The geometry is modified in place.\n   * If you do not want the geometry modified in place, first `clone()` it and\n   * then use this function on the clone.\n   * @param {import(\"../proj.js\").TransformFunction} transformFn Transform function.\n   * Called with a flat array of geometry coordinates.\n   * @api\n   * @override\n   */\n  applyTransform(transformFn) {\n    const geometries = this.geometries_;\n    for (let i = 0, ii = geometries.length; i < ii; ++i) {\n      geometries[i].applyTransform(transformFn);\n    }\n    this.changed();\n  }\n\n  /**\n   * Translate the geometry.  This modifies the geometry coordinates in place.  If\n   * instead you want a new geometry, first `clone()` this geometry.\n   * @param {number} deltaX Delta X.\n   * @param {number} deltaY Delta Y.\n   * @api\n   * @override\n   */\n  translate(deltaX, deltaY) {\n    const geometries = this.geometries_;\n    for (let i = 0, ii = geometries.length; i < ii; ++i) {\n      geometries[i].translate(deltaX, deltaY);\n    }\n    this.changed();\n  }\n\n  /**\n   * Clean up.\n   * @override\n   */\n  disposeInternal() {\n    this.unlistenGeometriesChange_();\n    super.disposeInternal();\n  }\n}\n\n/**\n * @param {Array<Geometry>} geometries Geometries.\n * @return {Array<Geometry>} Cloned geometries.\n */\nfunction cloneGeometries(geometries) {\n  return geometries.map((geometry) => geometry.clone());\n}\n\nexport default GeometryCollection;\n", "/**\n * Coordinate type when drawing lines.\n * @typedef {Array<import(\"../coordinate.js\").Coordinate>} LineCoordType\n */\n\nimport {distance} from '../coordinate.js';\nimport GeometryCollection from '../geom/GeometryCollection.js';\nimport LineString from '../geom/LineString.js';\nimport MultiLineString from '../geom/MultiLineString.js';\nimport MultiPolygon from '../geom/MultiPolygon.js';\nimport Polygon from '../geom/Polygon.js';\nimport {clamp, squaredDistance, toFixed} from '../math.js';\n\n/**\n * @param {LineCoordType} coordinates The ring coordinates.\n * @param {number} index The index.  May be wrapped.\n * @return {import(\"../coordinate.js\").Coordinate} The coordinate.\n */\nexport function getCoordinate(coordinates, index) {\n  const count = coordinates.length;\n  if (index < 0) {\n    return coordinates[index + count];\n  }\n  if (index >= count) {\n    return coordinates[index - count];\n  }\n  return coordinates[index];\n}\n\n/**\n * @param {LineCoordType} coordinates The coordinates.\n * @param {number} index The index.  May be fractional and may wrap.\n * @return {import(\"../coordinate.js\").Coordinate} The interpolated coordinate.\n */\nexport function interpolateCoordinate(coordinates, index) {\n  const count = coordinates.length;\n\n  let startIndex = Math.floor(index);\n  const along = index - startIndex;\n  if (startIndex >= count) {\n    startIndex -= count;\n  } else if (startIndex < 0) {\n    startIndex += count;\n  }\n\n  let endIndex = startIndex + 1;\n  if (endIndex >= count) {\n    endIndex -= count;\n  }\n\n  const start = coordinates[startIndex];\n  const x0 = start[0];\n  const y0 = start[1];\n  const end = coordinates[endIndex];\n  const dx = end[0] - x0;\n  const dy = end[1] - y0;\n\n  return [x0 + dx * along, y0 + dy * along];\n}\n\n/**\n * @typedef {Object} TraceTarget\n * @property {Array<import(\"../coordinate.js\").Coordinate>} coordinates Target coordinates.\n * @property {boolean} ring The target coordinates are a linear ring.\n * @property {number} startIndex The index of first traced coordinate.  A fractional index represents an\n * edge intersection.  Index values for rings will wrap (may be negative or larger than coordinates length).\n * @property {number} endIndex The index of last traced coordinate.  Details from startIndex also apply here.\n */\n\n/**\n * @typedef {Object} TraceState\n * @property {boolean} active Tracing active.\n * @property {import(\"../coordinate.js\").Coordinate} [startCoord] The initially clicked coordinate.\n * @property {Array<TraceTarget>} [targets] Targets available for tracing.\n * @property {number} [targetIndex] The index of the currently traced target.  A value of -1 indicates\n * that no trace target is active.\n */\n\n/**\n * @typedef {Object} TraceTargetUpdateInfo\n * @property {number} index The new target index.\n * @property {number} endIndex The new segment end index.\n * @property {number} closestTargetDistance The squared distance to the closest target.\n */\n\n/**\n * @type {TraceTargetUpdateInfo}\n */\nconst sharedUpdateInfo = {\n  index: -1,\n  endIndex: NaN,\n  closestTargetDistance: Infinity,\n};\n\n/**\n * @param {import(\"../coordinate.js\").Coordinate} coordinate The coordinate.\n * @param {TraceState} traceState The trace state.\n * @param {import(\"../Map.js\").default} map The map.\n * @param {number} snapTolerance The snap tolerance.\n * @return {TraceTargetUpdateInfo} Information about the new trace target.  The returned\n * object is reused between calls and must not be modified by the caller.\n */\nexport function getTraceTargetUpdate(\n  coordinate,\n  traceState,\n  map,\n  snapTolerance,\n) {\n  const x = coordinate[0];\n  const y = coordinate[1];\n\n  let closestTargetDistance = Infinity;\n\n  let newTargetIndex = -1;\n  let newEndIndex = NaN;\n\n  for (\n    let targetIndex = 0;\n    targetIndex < traceState.targets.length;\n    ++targetIndex\n  ) {\n    const target = traceState.targets[targetIndex];\n    const coordinates = target.coordinates;\n\n    let minSegmentDistance = Infinity;\n    let endIndex;\n    for (\n      let coordinateIndex = 0;\n      coordinateIndex < coordinates.length - 1;\n      ++coordinateIndex\n    ) {\n      const start = coordinates[coordinateIndex];\n      const end = coordinates[coordinateIndex + 1];\n      const rel = getPointSegmentRelationship(x, y, start, end);\n      if (rel.squaredDistance < minSegmentDistance) {\n        minSegmentDistance = rel.squaredDistance;\n        endIndex = coordinateIndex + rel.along;\n      }\n    }\n\n    if (minSegmentDistance < closestTargetDistance) {\n      closestTargetDistance = minSegmentDistance;\n      if (target.ring && traceState.targetIndex === targetIndex) {\n        // same target, maintain the same trace direction\n        if (target.endIndex > target.startIndex) {\n          // forward trace\n          if (endIndex < target.startIndex) {\n            endIndex += coordinates.length;\n          }\n        } else if (target.endIndex < target.startIndex) {\n          // reverse trace\n          if (endIndex > target.startIndex) {\n            endIndex -= coordinates.length;\n          }\n        }\n      }\n      newEndIndex = endIndex;\n      newTargetIndex = targetIndex;\n    }\n  }\n\n  const newTarget = traceState.targets[newTargetIndex];\n  let considerBothDirections = newTarget.ring;\n  if (traceState.targetIndex === newTargetIndex && considerBothDirections) {\n    // only consider switching trace direction if close to the start\n    const newCoordinate = interpolateCoordinate(\n      newTarget.coordinates,\n      newEndIndex,\n    );\n    const pixel = map.getPixelFromCoordinate(newCoordinate);\n    const startPx = map.getPixelFromCoordinate(traceState.startCoord);\n    if (distance(pixel, startPx) > snapTolerance) {\n      considerBothDirections = false;\n    }\n  }\n\n  if (considerBothDirections) {\n    const coordinates = newTarget.coordinates;\n    const count = coordinates.length;\n    const startIndex = newTarget.startIndex;\n    const endIndex = newEndIndex;\n    if (startIndex < endIndex) {\n      const forwardDistance = getCumulativeSquaredDistance(\n        coordinates,\n        startIndex,\n        endIndex,\n      );\n      const reverseDistance = getCumulativeSquaredDistance(\n        coordinates,\n        startIndex,\n        endIndex - count,\n      );\n      if (reverseDistance < forwardDistance) {\n        newEndIndex -= count;\n      }\n    } else {\n      const reverseDistance = getCumulativeSquaredDistance(\n        coordinates,\n        startIndex,\n        endIndex,\n      );\n      const forwardDistance = getCumulativeSquaredDistance(\n        coordinates,\n        startIndex,\n        endIndex + count,\n      );\n      if (forwardDistance < reverseDistance) {\n        newEndIndex += count;\n      }\n    }\n  }\n\n  sharedUpdateInfo.index = newTargetIndex;\n  sharedUpdateInfo.endIndex = newEndIndex;\n  sharedUpdateInfo.closestTargetDistance = closestTargetDistance;\n  return sharedUpdateInfo;\n}\n\n/**\n * @param {import(\"../coordinate.js\").Coordinate} coordinate The coordinate.\n * @param {Array<import(\"../Feature.js\").default>} features The candidate features.\n * @return {Array<TraceTarget>} The trace targets.\n */\nexport function getTraceTargets(coordinate, features) {\n  /**\n   * @type {Array<TraceTarget>}\n   */\n  const targets = [];\n\n  for (let i = 0; i < features.length; ++i) {\n    const feature = features[i];\n    const geometry = feature.getGeometry();\n    appendGeometryTraceTargets(coordinate, geometry, targets);\n  }\n\n  return targets;\n}\n\n/**\n * @param {import(\"../coordinate.js\").Coordinate} coordinate The coordinate.\n * @param {import(\"../geom/Geometry.js\").default} geometry The candidate geometry.\n * @param {Array<TraceTarget>} targets The trace targets.\n */\nfunction appendGeometryTraceTargets(coordinate, geometry, targets) {\n  if (geometry instanceof LineString) {\n    appendTraceTarget(coordinate, geometry.getCoordinates(), false, targets);\n    return;\n  }\n  if (geometry instanceof MultiLineString) {\n    const coordinates = geometry.getCoordinates();\n    for (let i = 0, ii = coordinates.length; i < ii; ++i) {\n      appendTraceTarget(coordinate, coordinates[i], false, targets);\n    }\n    return;\n  }\n  if (geometry instanceof Polygon) {\n    const coordinates = geometry.getCoordinates();\n    for (let i = 0, ii = coordinates.length; i < ii; ++i) {\n      appendTraceTarget(coordinate, coordinates[i], true, targets);\n    }\n    return;\n  }\n  if (geometry instanceof MultiPolygon) {\n    const polys = geometry.getCoordinates();\n    for (let i = 0, ii = polys.length; i < ii; ++i) {\n      const coordinates = polys[i];\n      for (let j = 0, jj = coordinates.length; j < jj; ++j) {\n        appendTraceTarget(coordinate, coordinates[j], true, targets);\n      }\n    }\n    return;\n  }\n  if (geometry instanceof GeometryCollection) {\n    const geometries = geometry.getGeometries();\n    for (let i = 0; i < geometries.length; ++i) {\n      appendGeometryTraceTargets(coordinate, geometries[i], targets);\n    }\n    return;\n  }\n  // other types cannot be traced\n}\n\n/**\n * @param {import(\"../coordinate.js\").Coordinate} coordinate The clicked coordinate.\n * @param {Array<import(\"../coordinate.js\").Coordinate>} coordinates The geometry component coordinates.\n * @param {boolean} ring The coordinates represent a linear ring.\n * @param {Array<TraceTarget>} targets The trace targets.\n */\nfunction appendTraceTarget(coordinate, coordinates, ring, targets) {\n  const x = coordinate[0];\n  const y = coordinate[1];\n  for (let i = 0, ii = coordinates.length - 1; i < ii; ++i) {\n    const start = coordinates[i];\n    const end = coordinates[i + 1];\n    const rel = getPointSegmentRelationship(x, y, start, end);\n    if (rel.squaredDistance === 0) {\n      const index = i + rel.along;\n      targets.push({\n        coordinates: coordinates,\n        ring: ring,\n        startIndex: index,\n        endIndex: index,\n      });\n      return;\n    }\n  }\n}\n\n/**\n * @param {import(\"../coordinate.js\").Coordinate} a One coordinate.\n * @param {import(\"../coordinate.js\").Coordinate} b Another coordinate.\n * @return {number} The squared distance between the two coordinates.\n */\nfunction getSquaredDistance(a, b) {\n  return squaredDistance(a[0], a[1], b[0], b[1]);\n}\n\n/**\n * Get the cumulative squared distance along a ring path.  The end index index may be \"wrapped\" and it may\n * be less than the start index to indicate the direction of travel.  The start and end index may have\n * a fractional part to indicate a point between two coordinates.\n * @param {LineCoordType} coordinates Ring coordinates.\n * @param {number} startIndex The start index.\n * @param {number} endIndex The end index.\n * @return {number} The cumulative squared distance along the ring path.\n */\nfunction getCumulativeSquaredDistance(coordinates, startIndex, endIndex) {\n  let lowIndex, highIndex;\n  if (startIndex < endIndex) {\n    lowIndex = startIndex;\n    highIndex = endIndex;\n  } else {\n    lowIndex = endIndex;\n    highIndex = startIndex;\n  }\n  const lowWholeIndex = Math.ceil(lowIndex);\n  const highWholeIndex = Math.floor(highIndex);\n\n  if (lowWholeIndex > highWholeIndex) {\n    // both start and end are on the same segment\n    const start = interpolateCoordinate(coordinates, lowIndex);\n    const end = interpolateCoordinate(coordinates, highIndex);\n    return getSquaredDistance(start, end);\n  }\n\n  let sd = 0;\n\n  if (lowIndex < lowWholeIndex) {\n    const start = interpolateCoordinate(coordinates, lowIndex);\n    const end = getCoordinate(coordinates, lowWholeIndex);\n    sd += getSquaredDistance(start, end);\n  }\n\n  if (highWholeIndex < highIndex) {\n    const start = getCoordinate(coordinates, highWholeIndex);\n    const end = interpolateCoordinate(coordinates, highIndex);\n    sd += getSquaredDistance(start, end);\n  }\n\n  for (let i = lowWholeIndex; i < highWholeIndex - 1; ++i) {\n    const start = getCoordinate(coordinates, i);\n    const end = getCoordinate(coordinates, i + 1);\n    sd += getSquaredDistance(start, end);\n  }\n\n  return sd;\n}\n\n/**\n * @typedef {Object} PointSegmentRelationship\n * @property {number} along The closest point expressed as a fraction along the segment length.\n * @property {number} squaredDistance The squared distance of the point to the segment.\n */\n\n/**\n * @type {PointSegmentRelationship}\n */\nconst sharedRel = {along: 0, squaredDistance: 0};\n\n/**\n * @param {number} x The point x.\n * @param {number} y The point y.\n * @param {import(\"../coordinate.js\").Coordinate} start The segment start.\n * @param {import(\"../coordinate.js\").Coordinate} end The segment end.\n * @return {PointSegmentRelationship} The point segment relationship.  The returned object is\n * shared between calls and must not be modified by the caller.\n */\nexport function getPointSegmentRelationship(x, y, start, end) {\n  const x1 = start[0];\n  const y1 = start[1];\n  const x2 = end[0];\n  const y2 = end[1];\n  const dx = x2 - x1;\n  const dy = y2 - y1;\n  let along = 0;\n  let px = x1;\n  let py = y1;\n  if (dx !== 0 || dy !== 0) {\n    along = clamp(((x - x1) * dx + (y - y1) * dy) / (dx * dx + dy * dy), 0, 1);\n    px += dx * along;\n    py += dy * along;\n  }\n\n  sharedRel.along = along;\n  sharedRel.squaredDistance = toFixed(squaredDistance(x, y, px, py), 10);\n  return sharedRel;\n}\n", "/**\n * @module ol/interaction/Draw\n */\nimport Feature from '../Feature.js';\nimport MapBrowserEvent from '../MapBrowserEvent.js';\nimport MapBrowserEventType from '../MapBrowserEventType.js';\nimport {\n  distance,\n  squaredDistance as squaredCoordinateDistance,\n} from '../coordinate.js';\nimport Event from '../events/Event.js';\nimport EventType from '../events/EventType.js';\nimport {\n  always,\n  never,\n  noModifierKeys,\n  shiftKeyOnly,\n} from '../events/condition.js';\nimport {\n  boundingExtent,\n  getBottomLeft,\n  getBottomRight,\n  getTopLeft,\n  getTopRight,\n} from '../extent.js';\nimport {FALSE, TRUE} from '../functions.js';\nimport Circle from '../geom/Circle.js';\nimport LineString from '../geom/LineString.js';\nimport MultiLineString from '../geom/MultiLineString.js';\nimport MultiPoint from '../geom/MultiPoint.js';\nimport MultiPolygon from '../geom/MultiPolygon.js';\nimport Point from '../geom/Point.js';\nimport Polygon, {fromCircle, makeRegular} from '../geom/Polygon.js';\nimport {getStrideForLayout} from '../geom/SimpleGeometry.js';\nimport VectorLayer from '../layer/Vector.js';\nimport {fromUserCoordinate, getUserProjection} from '../proj.js';\nimport VectorSource from '../source/Vector.js';\nimport {createEditingStyle} from '../style/Style.js';\nimport PointerInteraction from './Pointer.js';\nimport InteractionProperty from './Property.js';\nimport {\n  getCoordinate,\n  getTraceTargetUpdate,\n  getTraceTargets,\n  interpolateCoordinate,\n} from './tracing.js';\n\n/**\n * @typedef {Object} Options\n * @property {import(\"../geom/Geometry.js\").Type} type Geometry type of\n * the geometries being drawn with this instance.\n * @property {number} [clickTolerance=6] The maximum distance in pixels between\n * \"down\" and \"up\" for a \"up\" event to be considered a \"click\" event and\n * actually add a point/vertex to the geometry being drawn.  The default of `6`\n * was chosen for the draw interaction to behave correctly on mouse as well as\n * on touch devices.\n * @property {import(\"../Collection.js\").default<Feature>} [features]\n * Destination collection for the drawn features.\n * @property {VectorSource} [source] Destination source for\n * the drawn features.\n * @property {number} [dragVertexDelay=500] Delay in milliseconds after pointerdown\n * before the current vertex can be dragged to its exact position.\n * @property {number} [snapTolerance=12] Pixel distance for snapping to the\n * drawing finish. Must be greater than `0`.\n * @property {boolean} [stopClick=false] Stop click, singleclick, and\n * doubleclick events from firing during drawing.\n * @property {number} [maxPoints] The number of points that can be drawn before\n * a polygon ring or line string is finished. By default there is no\n * restriction.\n * @property {number} [minPoints] The number of points that must be drawn\n * before a polygon ring or line string can be finished. Default is `3` for\n * polygon rings and `2` for line strings.\n * @property {import(\"../events/condition.js\").Condition} [finishCondition] A function\n * that takes a {@link module:ol/MapBrowserEvent~MapBrowserEvent} and returns a\n * boolean to indicate whether the drawing can be finished. Not used when drawing\n * POINT or MULTI_POINT geometries.\n * @property {import(\"../style/Style.js\").StyleLike|import(\"../style/flat.js\").FlatStyleLike} [style]\n * Style for sketch features. The draw interaction can have up to three sketch features, depending on the mode.\n * It will always contain a feature with a `Point` geometry that corresponds to the current cursor position.\n * If the mode is `LineString` or `Polygon`, and there is at least one drawn point, it will also contain a feature with\n * a `LineString` geometry that corresponds to the line between the already drawn points and the current cursor position.\n * If the mode is `Polygon`, and there is at least one drawn point, it will also contain a feature with a `Polygon`\n * geometry that corresponds to the polygon between the already drawn points and the current cursor position\n * (note that this polygon has only two points if only one point is drawn).\n * If the mode is `Circle`, and there is one point drawn, it will also contain a feature with a `Circle` geometry whose\n * center is the drawn point and the radius is determined by the distance between the drawn point and the cursor.\n * @property {GeometryFunction} [geometryFunction]\n * Function that is called when a geometry's coordinates are updated.\n * @property {string} [geometryName] Geometry name to use for features created\n * by the draw interaction.\n * @property {import(\"../events/condition.js\").Condition} [condition] A function that\n * takes a {@link module:ol/MapBrowserEvent~MapBrowserEvent} and returns a\n * boolean to indicate whether that event should be handled.\n * By default {@link module:ol/events/condition.noModifierKeys}, i.e. a click,\n * adds a vertex or deactivates freehand drawing.\n * @property {boolean} [freehand=false] Operate in freehand mode for lines,\n * polygons, and circles.  This makes the interaction always operate in freehand\n * mode and takes precedence over any `freehandCondition` option.\n * @property {import(\"../events/condition.js\").Condition} [freehandCondition]\n * Condition that activates freehand drawing for lines and polygons. This\n * function takes a {@link module:ol/MapBrowserEvent~MapBrowserEvent} and\n * returns a boolean to indicate whether that event should be handled. The\n * default is {@link module:ol/events/condition.shiftKeyOnly}, meaning that the\n * Shift key activates freehand drawing.\n * @property {boolean|import(\"../events/condition.js\").Condition} [trace=false] Trace a portion of another geometry.\n * Ignored when in freehand mode.\n * @property {VectorSource} [traceSource] Source for features to trace.  If tracing is active and a `traceSource` is\n * not provided, the interaction's `source` will be used.  Tracing requires that the interaction is configured with\n * either a `traceSource` or a `source`.\n * @property {boolean} [wrapX=false] Wrap the world horizontally on the sketch\n * overlay.\n * @property {import(\"../geom/Geometry.js\").GeometryLayout} [geometryLayout='XY'] Layout of the\n * feature geometries created by the draw interaction.\n */\n\n/**\n * Coordinate type when drawing points.\n * @typedef {import(\"../coordinate.js\").Coordinate} PointCoordType\n */\n\n/**\n * @typedef {import('./tracing.js').LineCoordType} LineCoordType\n */\n\n/**\n * Coordinate type when drawing polygons.\n * @typedef {Array<Array<import(\"../coordinate.js\").Coordinate>>} PolyCoordType\n */\n\n/**\n * Types used for drawing coordinates.\n * @typedef {PointCoordType|LineCoordType|PolyCoordType} SketchCoordType\n */\n\n/** @typedef {import('./tracing.js').TraceState} TraceState */\n\n/** @typedef {import('./tracing.js').TraceTarget} TraceTarget */\n\n/**\n * Function that takes an array of coordinates and an optional existing geometry\n * and a projection as arguments, and returns a geometry. The optional existing\n * geometry is the geometry that is returned when the function is called without\n * a second argument.\n * @typedef {function(!SketchCoordType, import(\"../geom/SimpleGeometry.js\").default,\n *     import(\"../proj/Projection.js\").default):\n *     import(\"../geom/SimpleGeometry.js\").default} GeometryFunction\n */\n\n/**\n * @typedef {'Point' | 'LineString' | 'Polygon' | 'Circle'} Mode\n * Draw mode.  This collapses multi-part geometry types with their single-part\n * cousins.\n */\n\n/**\n * @enum {string}\n */\nconst DrawEventType = {\n  /**\n   * Triggered upon feature draw start\n   * @event DrawEvent#drawstart\n   * @api\n   */\n  DRAWSTART: 'drawstart',\n  /**\n   * Triggered upon feature draw end\n   * @event DrawEvent#drawend\n   * @api\n   */\n  DRAWEND: 'drawend',\n  /**\n   * Triggered upon feature draw abortion\n   * @event DrawEvent#drawabort\n   * @api\n   */\n  DRAWABORT: 'drawabort',\n};\n\n/**\n * @classdesc\n * Events emitted by {@link module:ol/interaction/Draw~Draw} instances are\n * instances of this type.\n */\nexport class DrawEvent extends Event {\n  /**\n   * @param {DrawEventType} type Type.\n   * @param {Feature} feature The feature drawn.\n   */\n  constructor(type, feature) {\n    super(type);\n\n    /**\n     * The feature being drawn.\n     * @type {Feature}\n     * @api\n     */\n    this.feature = feature;\n  }\n}\n\n/***\n * @template Return\n * @typedef {import(\"../Observable.js\").OnSignature<import(\"../Observable.js\").EventTypes, import(\"../events/Event.js\").default, Return> &\n *   import(\"../Observable.js\").OnSignature<import(\"../ObjectEventType.js\").Types|\n *     'change:active', import(\"../Object.js\").ObjectEvent, Return> &\n *   import(\"../Observable.js\").OnSignature<'drawabort'|'drawend'|'drawstart', DrawEvent, Return> &\n *   import(\"../Observable.js\").CombinedOnSignature<import(\"../Observable.js\").EventTypes|import(\"../ObjectEventType.js\").Types|\n *     'change:active'|'drawabort'|'drawend'|'drawstart', Return>} DrawOnSignature\n */\n\n/**\n * @classdesc\n * Interaction for drawing feature geometries.\n *\n * @fires DrawEvent\n * @api\n */\nclass Draw extends PointerInteraction {\n  /**\n   * @param {Options} options Options.\n   */\n  constructor(options) {\n    const pointerOptions = /** @type {import(\"./Pointer.js\").Options} */ (\n      options\n    );\n    if (!pointerOptions.stopDown) {\n      pointerOptions.stopDown = FALSE;\n    }\n\n    super(pointerOptions);\n\n    /***\n     * @type {DrawOnSignature<import(\"../events.js\").EventsKey>}\n     */\n    this.on;\n\n    /***\n     * @type {DrawOnSignature<import(\"../events.js\").EventsKey>}\n     */\n    this.once;\n\n    /***\n     * @type {DrawOnSignature<void>}\n     */\n    this.un;\n\n    /**\n     * @type {Options}\n     * @private\n     */\n    this.options_ = options;\n\n    /**\n     * @type {boolean}\n     * @private\n     */\n    this.shouldHandle_ = false;\n\n    /**\n     * @type {import(\"../pixel.js\").Pixel}\n     * @private\n     */\n    this.downPx_ = null;\n\n    /**\n     * @type {ReturnType<typeof setTimeout>}\n     * @private\n     */\n    this.downTimeout_;\n\n    /**\n     * @type {number|undefined}\n     * @private\n     */\n    this.lastDragTime_;\n\n    /**\n     * Pointer type of the last pointermove event\n     * @type {string}\n     * @private\n     */\n    this.pointerType_;\n\n    /**\n     * @type {boolean}\n     * @private\n     */\n    this.freehand_ = false;\n\n    /**\n     * Target source for drawn features.\n     * @type {VectorSource|null}\n     * @private\n     */\n    this.source_ = options.source ? options.source : null;\n\n    /**\n     * Target collection for drawn features.\n     * @type {import(\"../Collection.js\").default<Feature>|null}\n     * @private\n     */\n    this.features_ = options.features ? options.features : null;\n\n    /**\n     * Pixel distance for snapping.\n     * @type {number}\n     * @private\n     */\n    this.snapTolerance_ = options.snapTolerance ? options.snapTolerance : 12;\n\n    /**\n     * Geometry type.\n     * @type {import(\"../geom/Geometry.js\").Type}\n     * @private\n     */\n    this.type_ = /** @type {import(\"../geom/Geometry.js\").Type} */ (\n      options.type\n    );\n\n    /**\n     * Drawing mode (derived from geometry type.\n     * @type {Mode}\n     * @private\n     */\n    this.mode_ = getMode(this.type_);\n\n    /**\n     * Stop click, singleclick, and doubleclick events from firing during drawing.\n     * Default is `false`.\n     * @type {boolean}\n     * @private\n     */\n    this.stopClick_ = !!options.stopClick;\n\n    /**\n     * Ignore the next up event. This is set to `true` when a drag event is encountered,\n     * e.g. when the user pans the map while drawing. In this case, we do not want to bail\n     * out of tracing.\n     * @type {boolean}\n     * @private\n     */\n    this.ignoreNextUpEvent_ = false;\n\n    /**\n     * The number of points that must be drawn before a polygon ring or line\n     * string can be finished.  The default is 3 for polygon rings and 2 for\n     * line strings.\n     * @type {number}\n     * @private\n     */\n    this.minPoints_ = options.minPoints\n      ? options.minPoints\n      : this.mode_ === 'Polygon'\n        ? 3\n        : 2;\n\n    /**\n     * The number of points that can be drawn before a polygon ring or line string\n     * is finished. The default is no restriction.\n     * @type {number}\n     * @private\n     */\n    this.maxPoints_ =\n      this.mode_ === 'Circle'\n        ? 2\n        : options.maxPoints\n          ? options.maxPoints\n          : Infinity;\n\n    /**\n     * A function to decide if a potential finish coordinate is permissible\n     * @private\n     * @type {import(\"../events/condition.js\").Condition}\n     */\n    this.finishCondition_ = options.finishCondition\n      ? options.finishCondition\n      : TRUE;\n\n    /**\n     * @private\n     * @type {import(\"../geom/Geometry.js\").GeometryLayout}\n     */\n    this.geometryLayout_ = options.geometryLayout\n      ? options.geometryLayout\n      : 'XY';\n\n    let geometryFunction = options.geometryFunction;\n    if (!geometryFunction) {\n      const mode = this.mode_;\n      if (mode === 'Circle') {\n        /**\n         * @param {!LineCoordType} coordinates The coordinates.\n         * @param {import(\"../geom/SimpleGeometry.js\").default|undefined} geometry Optional geometry.\n         * @param {import(\"../proj/Projection.js\").default} projection The view projection.\n         * @return {import(\"../geom/SimpleGeometry.js\").default} A geometry.\n         */\n        geometryFunction = (coordinates, geometry, projection) => {\n          const circle = geometry\n            ? /** @type {Circle} */ (geometry)\n            : new Circle([NaN, NaN]);\n          const center = fromUserCoordinate(coordinates[0], projection);\n          const squaredLength = squaredCoordinateDistance(\n            center,\n            fromUserCoordinate(coordinates[coordinates.length - 1], projection),\n          );\n          circle.setCenterAndRadius(\n            center,\n            Math.sqrt(squaredLength),\n            this.geometryLayout_,\n          );\n          const userProjection = getUserProjection();\n          if (userProjection) {\n            circle.transform(projection, userProjection);\n          }\n          return circle;\n        };\n      } else {\n        let Constructor;\n        if (mode === 'Point') {\n          Constructor = Point;\n        } else if (mode === 'LineString') {\n          Constructor = LineString;\n        } else if (mode === 'Polygon') {\n          Constructor = Polygon;\n        }\n        /**\n         * @param {!LineCoordType} coordinates The coordinates.\n         * @param {import(\"../geom/SimpleGeometry.js\").default|undefined} geometry Optional geometry.\n         * @param {import(\"../proj/Projection.js\").default} projection The view projection.\n         * @return {import(\"../geom/SimpleGeometry.js\").default} A geometry.\n         */\n        geometryFunction = (coordinates, geometry, projection) => {\n          if (geometry) {\n            if (mode === 'Polygon') {\n              if (coordinates[0].length) {\n                // Add a closing coordinate to match the first\n                geometry.setCoordinates(\n                  [coordinates[0].concat([coordinates[0][0]])],\n                  this.geometryLayout_,\n                );\n              } else {\n                geometry.setCoordinates([], this.geometryLayout_);\n              }\n            } else {\n              geometry.setCoordinates(coordinates, this.geometryLayout_);\n            }\n          } else {\n            geometry = new Constructor(coordinates, this.geometryLayout_);\n          }\n          return geometry;\n        };\n      }\n    }\n\n    /**\n     * @type {GeometryFunction}\n     * @private\n     */\n    this.geometryFunction_ = geometryFunction;\n\n    /**\n     * @type {number}\n     * @private\n     */\n    this.dragVertexDelay_ =\n      options.dragVertexDelay !== undefined ? options.dragVertexDelay : 500;\n\n    /**\n     * Finish coordinate for the feature (first point for polygons, last point for\n     * linestrings).\n     * @type {import(\"../coordinate.js\").Coordinate}\n     * @private\n     */\n    this.finishCoordinate_ = null;\n\n    /**\n     * Sketch feature.\n     * @type {Feature<import('../geom/SimpleGeometry.js').default>}\n     * @private\n     */\n    this.sketchFeature_ = null;\n\n    /**\n     * Sketch point.\n     * @type {Feature<Point>}\n     * @private\n     */\n    this.sketchPoint_ = null;\n\n    /**\n     * Sketch coordinates. Used when drawing a line or polygon.\n     * @type {SketchCoordType}\n     * @private\n     */\n    this.sketchCoords_ = null;\n\n    /**\n     * Sketch line. Used when drawing polygon.\n     * @type {Feature<LineString>}\n     * @private\n     */\n    this.sketchLine_ = null;\n\n    /**\n     * Sketch line coordinates. Used when drawing a polygon or circle.\n     * @type {LineCoordType}\n     * @private\n     */\n    this.sketchLineCoords_ = null;\n\n    /**\n     * Squared tolerance for handling up events.  If the squared distance\n     * between a down and up event is greater than this tolerance, up events\n     * will not be handled.\n     * @type {number}\n     * @private\n     */\n    this.squaredClickTolerance_ = options.clickTolerance\n      ? options.clickTolerance * options.clickTolerance\n      : 36;\n\n    /**\n     * Draw overlay where our sketch features are drawn.\n     * @type {VectorLayer}\n     * @private\n     */\n    this.overlay_ = new VectorLayer({\n      source: new VectorSource({\n        useSpatialIndex: false,\n        wrapX: options.wrapX ? options.wrapX : false,\n      }),\n      style: options.style ? options.style : getDefaultStyleFunction(),\n      updateWhileInteracting: true,\n    });\n\n    /**\n     * Name of the geometry attribute for newly created features.\n     * @type {string|undefined}\n     * @private\n     */\n    this.geometryName_ = options.geometryName;\n\n    /**\n     * @private\n     * @type {import(\"../events/condition.js\").Condition}\n     */\n    this.condition_ = options.condition ? options.condition : noModifierKeys;\n\n    /**\n     * @private\n     * @type {import(\"../events/condition.js\").Condition}\n     */\n    this.freehandCondition_;\n    if (options.freehand) {\n      this.freehandCondition_ = always;\n    } else {\n      this.freehandCondition_ = options.freehandCondition\n        ? options.freehandCondition\n        : shiftKeyOnly;\n    }\n\n    /**\n     * @type {import(\"../events/condition.js\").Condition}\n     * @private\n     */\n    this.traceCondition_;\n    this.setTrace(options.trace || false);\n\n    /**\n     * @type {TraceState}\n     * @private\n     */\n    this.traceState_ = {active: false};\n\n    /**\n     * @type {VectorSource|null}\n     * @private\n     */\n    this.traceSource_ = options.traceSource || options.source || null;\n\n    this.addChangeListener(InteractionProperty.ACTIVE, this.updateState_);\n  }\n\n  /**\n   * Toggle tracing mode or set a tracing condition.\n   *\n   * @param {boolean|import(\"../events/condition.js\").Condition} trace A boolean to toggle tracing mode or an event\n   *     condition that will be checked when a feature is clicked to determine if tracing should be active.\n   */\n  setTrace(trace) {\n    let condition;\n    if (!trace) {\n      condition = never;\n    } else if (trace === true) {\n      condition = always;\n    } else {\n      condition = trace;\n    }\n    this.traceCondition_ = condition;\n  }\n\n  /**\n   * Remove the interaction from its current map and attach it to the new map.\n   * Subclasses may set up event handlers to get notified about changes to\n   * the map here.\n   * @param {import(\"../Map.js\").default} map Map.\n   * @override\n   */\n  setMap(map) {\n    super.setMap(map);\n    this.updateState_();\n  }\n\n  /**\n   * Set whether the drawing is done in freehand mode.\n   *\n   * @param {boolean} freehand Freehand drawing.\n   * @api\n   */\n  setFreehand(freehand) {\n    this.freehand_ = freehand;\n    if (this.freehand_) {\n      this.freehandCondition_ = always;\n    } else {\n      this.freehandCondition_ =\n        this.options_ && this.options_.freehandCondition\n          ? this.options_.freehandCondition\n          : shiftKeyOnly;\n    }\n  }\n\n  /**\n   * Get the overlay layer that this interaction renders sketch features to.\n   * @return {VectorLayer} Overlay layer.\n   * @api\n   */\n  getOverlay() {\n    return this.overlay_;\n  }\n\n  /**\n   * Get if this interaction is in freehand mode.\n   * @return {boolean} Freehand drawing.\n   * @api\n   */\n  getFreehand() {\n    return this.freehand_;\n  }\n\n  /**\n   * Handles the {@link module:ol/MapBrowserEvent~MapBrowserEvent map browser event} and may actually draw or finish the drawing.\n   * @param {import(\"../MapBrowserEvent.js\").default<PointerEvent>} event Map browser event.\n   * @return {boolean} `false` to stop event propagation.\n   * @api\n   * @override\n   */\n  handleEvent(event) {\n    if (event.originalEvent.type === EventType.CONTEXTMENU) {\n      // Avoid context menu for long taps when drawing on mobile\n      event.originalEvent.preventDefault();\n    }\n    this.freehand_ = this.mode_ !== 'Point' && this.freehandCondition_(event);\n    let move = event.type === MapBrowserEventType.POINTERMOVE;\n    let pass = true;\n    if (\n      !this.freehand_ &&\n      this.lastDragTime_ &&\n      event.type === MapBrowserEventType.POINTERDRAG\n    ) {\n      const now = Date.now();\n      if (now - this.lastDragTime_ >= this.dragVertexDelay_) {\n        this.downPx_ = event.pixel;\n        this.shouldHandle_ = !this.freehand_;\n        move = true;\n      } else {\n        this.lastDragTime_ = undefined;\n      }\n      if (this.shouldHandle_ && this.downTimeout_ !== undefined) {\n        clearTimeout(this.downTimeout_);\n        this.downTimeout_ = undefined;\n      }\n    }\n    if (\n      this.freehand_ &&\n      event.type === MapBrowserEventType.POINTERDRAG &&\n      this.sketchFeature_ !== null\n    ) {\n      this.addToDrawing_(event.coordinate);\n      pass = false;\n    } else if (\n      this.freehand_ &&\n      event.type === MapBrowserEventType.POINTERDOWN\n    ) {\n      pass = false;\n    } else if (move && this.getPointerCount() < 2) {\n      pass = event.type === MapBrowserEventType.POINTERMOVE;\n      if (pass && this.freehand_) {\n        this.handlePointerMove_(event);\n        if (this.shouldHandle_) {\n          // Avoid page scrolling when freehand drawing on mobile\n          event.originalEvent.preventDefault();\n        }\n      } else if (\n        event.originalEvent.pointerType === 'mouse' ||\n        (event.type === MapBrowserEventType.POINTERDRAG &&\n          this.downTimeout_ === undefined)\n      ) {\n        this.handlePointerMove_(event);\n      }\n    } else if (event.type === MapBrowserEventType.DBLCLICK) {\n      pass = false;\n    }\n\n    return super.handleEvent(event) && pass;\n  }\n\n  /**\n   * Handle pointer down events.\n   * @param {import(\"../MapBrowserEvent.js\").default<PointerEvent>} event Event.\n   * @return {boolean} If the event was consumed.\n   * @override\n   */\n  handleDownEvent(event) {\n    this.shouldHandle_ = !this.freehand_;\n\n    if (this.freehand_) {\n      this.downPx_ = event.pixel;\n      if (!this.finishCoordinate_) {\n        this.startDrawing_(event.coordinate);\n      }\n      return true;\n    }\n\n    if (!this.condition_(event)) {\n      this.lastDragTime_ = undefined;\n      return false;\n    }\n\n    this.lastDragTime_ = Date.now();\n    this.downTimeout_ = setTimeout(() => {\n      this.handlePointerMove_(\n        new MapBrowserEvent(\n          MapBrowserEventType.POINTERMOVE,\n          event.map,\n          event.originalEvent,\n          false,\n          event.frameState,\n        ),\n      );\n    }, this.dragVertexDelay_);\n    this.downPx_ = event.pixel;\n    return true;\n  }\n\n  /**\n   * @private\n   */\n  deactivateTrace_() {\n    this.traceState_ = {active: false};\n  }\n\n  /**\n   * Activate or deactivate trace state based on a browser event.\n   * @param {import(\"../MapBrowserEvent.js\").default} event Event.\n   * @private\n   */\n  toggleTraceState_(event) {\n    if (!this.traceSource_ || !this.traceCondition_(event)) {\n      return;\n    }\n\n    if (this.traceState_.active) {\n      this.deactivateTrace_();\n      return;\n    }\n\n    const map = this.getMap();\n    const lowerLeft = map.getCoordinateFromPixel([\n      event.pixel[0] - this.snapTolerance_,\n      event.pixel[1] + this.snapTolerance_,\n    ]);\n    const upperRight = map.getCoordinateFromPixel([\n      event.pixel[0] + this.snapTolerance_,\n      event.pixel[1] - this.snapTolerance_,\n    ]);\n    const extent = boundingExtent([lowerLeft, upperRight]);\n    const features = this.traceSource_.getFeaturesInExtent(extent);\n    if (features.length === 0) {\n      return;\n    }\n\n    const targets = getTraceTargets(event.coordinate, features);\n    if (targets.length) {\n      this.traceState_ = {\n        active: true,\n        startCoord: event.coordinate.slice(),\n        targets: targets,\n        targetIndex: -1,\n      };\n    }\n  }\n\n  /**\n   * @param {TraceTarget} target The trace target.\n   * @param {number} endIndex The new end index of the trace.\n   * @private\n   */\n  addOrRemoveTracedCoordinates_(target, endIndex) {\n    // three cases to handle:\n    //  1. traced in the same direction and points need adding\n    //  2. traced in the same direction and points need removing\n    //  3. traced in a new direction\n    const previouslyForward = target.startIndex <= target.endIndex;\n    const currentlyForward = target.startIndex <= endIndex;\n    if (previouslyForward === currentlyForward) {\n      // same direction\n      if (\n        (previouslyForward && endIndex > target.endIndex) ||\n        (!previouslyForward && endIndex < target.endIndex)\n      ) {\n        // case 1 - add new points\n        this.addTracedCoordinates_(target, target.endIndex, endIndex);\n      } else if (\n        (previouslyForward && endIndex < target.endIndex) ||\n        (!previouslyForward && endIndex > target.endIndex)\n      ) {\n        // case 2 - remove old points\n        this.removeTracedCoordinates_(endIndex, target.endIndex);\n      }\n    } else {\n      // case 3 - remove old points, add new points\n      this.removeTracedCoordinates_(target.startIndex, target.endIndex);\n      this.addTracedCoordinates_(target, target.startIndex, endIndex);\n    }\n  }\n\n  /**\n   * @param {number} fromIndex The start index.\n   * @param {number} toIndex The end index.\n   * @private\n   */\n  removeTracedCoordinates_(fromIndex, toIndex) {\n    if (fromIndex === toIndex) {\n      return;\n    }\n\n    let remove = 0;\n    if (fromIndex < toIndex) {\n      const start = Math.ceil(fromIndex);\n      let end = Math.floor(toIndex);\n      if (end === toIndex) {\n        end -= 1;\n      }\n      remove = end - start + 1;\n    } else {\n      const start = Math.floor(fromIndex);\n      let end = Math.ceil(toIndex);\n      if (end === toIndex) {\n        end += 1;\n      }\n      remove = start - end + 1;\n    }\n\n    if (remove > 0) {\n      this.removeLastPoints_(remove);\n    }\n  }\n\n  /**\n   * @param {TraceTarget} target The trace target.\n   * @param {number} fromIndex The start index.\n   * @param {number} toIndex The end index.\n   * @private\n   */\n  addTracedCoordinates_(target, fromIndex, toIndex) {\n    if (fromIndex === toIndex) {\n      return;\n    }\n\n    const coordinates = [];\n    if (fromIndex < toIndex) {\n      // forward trace\n      const start = Math.ceil(fromIndex);\n      let end = Math.floor(toIndex);\n      if (end === toIndex) {\n        // if end is snapped to a vertex, it will be added later\n        end -= 1;\n      }\n      for (let i = start; i <= end; ++i) {\n        coordinates.push(getCoordinate(target.coordinates, i));\n      }\n    } else {\n      // reverse trace\n      const start = Math.floor(fromIndex);\n      let end = Math.ceil(toIndex);\n      if (end === toIndex) {\n        end += 1;\n      }\n      for (let i = start; i >= end; --i) {\n        coordinates.push(getCoordinate(target.coordinates, i));\n      }\n    }\n    if (coordinates.length) {\n      this.appendCoordinates(coordinates);\n    }\n  }\n\n  /**\n   * Update the trace.\n   * @param {import(\"../MapBrowserEvent.js\").default} event Event.\n   * @private\n   */\n  updateTrace_(event) {\n    const traceState = this.traceState_;\n    if (!traceState.active) {\n      return;\n    }\n\n    if (traceState.targetIndex === -1) {\n      // check if we are ready to pick a target\n      const startPx = event.map.getPixelFromCoordinate(traceState.startCoord);\n      if (distance(startPx, event.pixel) < this.snapTolerance_) {\n        return;\n      }\n    }\n\n    const updatedTraceTarget = getTraceTargetUpdate(\n      event.coordinate,\n      traceState,\n      this.getMap(),\n      this.snapTolerance_,\n    );\n\n    if (traceState.targetIndex !== updatedTraceTarget.index) {\n      // target changed\n      if (traceState.targetIndex !== -1) {\n        // remove points added during previous trace\n        const oldTarget = traceState.targets[traceState.targetIndex];\n        this.removeTracedCoordinates_(oldTarget.startIndex, oldTarget.endIndex);\n      }\n      // add points for the new target\n      const newTarget = traceState.targets[updatedTraceTarget.index];\n      this.addTracedCoordinates_(\n        newTarget,\n        newTarget.startIndex,\n        updatedTraceTarget.endIndex,\n      );\n    } else {\n      // target stayed the same\n      const target = traceState.targets[traceState.targetIndex];\n      this.addOrRemoveTracedCoordinates_(target, updatedTraceTarget.endIndex);\n    }\n\n    // modify the state with updated info\n    traceState.targetIndex = updatedTraceTarget.index;\n    const target = traceState.targets[traceState.targetIndex];\n    target.endIndex = updatedTraceTarget.endIndex;\n\n    // update event coordinate and pixel to match end point of final segment\n    const coordinate = interpolateCoordinate(\n      target.coordinates,\n      target.endIndex,\n    );\n    const pixel = this.getMap().getPixelFromCoordinate(coordinate);\n    event.coordinate = coordinate;\n    event.pixel = [Math.round(pixel[0]), Math.round(pixel[1])];\n  }\n\n  /**\n   * Handle drag events.\n   * @param {import(\"../MapBrowserEvent.js\").default<PointerEvent>} event Event.\n   * @override\n   */\n  handleDragEvent(event) {\n    this.ignoreNextUpEvent_ = true;\n    super.handleDragEvent(event);\n  }\n\n  /**\n   * Handle pointer up events.\n   * @param {import(\"../MapBrowserEvent.js\").default<PointerEvent>} event Event.\n   * @return {boolean} If the event was consumed.\n   * @override\n   */\n  handleUpEvent(event) {\n    let pass = true;\n\n    if (this.getPointerCount() === 0) {\n      if (this.downTimeout_) {\n        clearTimeout(this.downTimeout_);\n        this.downTimeout_ = undefined;\n      }\n\n      this.handlePointerMove_(event);\n      const tracing = this.traceState_.active;\n      if (!this.ignoreNextUpEvent_) {\n        this.toggleTraceState_(event);\n      }\n\n      if (this.shouldHandle_) {\n        const startingToDraw = !this.finishCoordinate_;\n        if (startingToDraw) {\n          this.startDrawing_(event.coordinate);\n        }\n        if (!startingToDraw && this.freehand_) {\n          this.finishDrawing();\n        } else if (\n          !this.freehand_ &&\n          (!startingToDraw || this.mode_ === 'Point')\n        ) {\n          if (this.atFinish_(event.pixel, tracing)) {\n            if (this.finishCondition_(event)) {\n              this.finishDrawing();\n            }\n          } else {\n            this.addToDrawing_(event.coordinate);\n          }\n        }\n        pass = false;\n      } else if (this.freehand_) {\n        this.abortDrawing();\n      }\n    }\n    this.ignoreNextUpEvent_ = false;\n\n    if (!pass && this.stopClick_) {\n      event.preventDefault();\n    }\n    return pass;\n  }\n\n  /**\n   * Handle move events.\n   * @param {import(\"../MapBrowserEvent.js\").default<PointerEvent>} event A move event.\n   * @private\n   */\n  handlePointerMove_(event) {\n    this.pointerType_ = event.originalEvent.pointerType;\n    if (\n      this.downPx_ &&\n      ((!this.freehand_ && this.shouldHandle_) ||\n        (this.freehand_ && !this.shouldHandle_))\n    ) {\n      const downPx = this.downPx_;\n      const clickPx = event.pixel;\n      const dx = downPx[0] - clickPx[0];\n      const dy = downPx[1] - clickPx[1];\n      const squaredDistance = dx * dx + dy * dy;\n      this.shouldHandle_ = this.freehand_\n        ? squaredDistance > this.squaredClickTolerance_\n        : squaredDistance <= this.squaredClickTolerance_;\n      if (!this.shouldHandle_) {\n        return;\n      }\n    }\n\n    if (!this.finishCoordinate_) {\n      this.createOrUpdateSketchPoint_(event.coordinate.slice());\n      return;\n    }\n\n    this.updateTrace_(event);\n    this.modifyDrawing_(event.coordinate);\n  }\n\n  /**\n   * Determine if an event is within the snapping tolerance of the start coord.\n   * @param {import(\"../pixel.js\").Pixel} pixel Pixel.\n   * @param {boolean} [tracing] Drawing in trace mode (only stop if at the starting point).\n   * @return {boolean} The event is within the snapping tolerance of the start.\n   * @private\n   */\n  atFinish_(pixel, tracing) {\n    let at = false;\n    if (this.sketchFeature_) {\n      let potentiallyDone = false;\n      let potentiallyFinishCoordinates = [this.finishCoordinate_];\n      const mode = this.mode_;\n      if (mode === 'Point') {\n        at = true;\n      } else if (mode === 'Circle') {\n        at = this.sketchCoords_.length === 2;\n      } else if (mode === 'LineString') {\n        potentiallyDone =\n          !tracing && this.sketchCoords_.length > this.minPoints_;\n      } else if (mode === 'Polygon') {\n        const sketchCoords = /** @type {PolyCoordType} */ (this.sketchCoords_);\n        potentiallyDone = sketchCoords[0].length > this.minPoints_;\n        potentiallyFinishCoordinates = [\n          sketchCoords[0][0],\n          sketchCoords[0][sketchCoords[0].length - 2],\n        ];\n        if (tracing) {\n          potentiallyFinishCoordinates = [sketchCoords[0][0]];\n        } else {\n          potentiallyFinishCoordinates = [\n            sketchCoords[0][0],\n            sketchCoords[0][sketchCoords[0].length - 2],\n          ];\n        }\n      }\n      if (potentiallyDone) {\n        const map = this.getMap();\n        for (let i = 0, ii = potentiallyFinishCoordinates.length; i < ii; i++) {\n          const finishCoordinate = potentiallyFinishCoordinates[i];\n          const finishPixel = map.getPixelFromCoordinate(finishCoordinate);\n          const dx = pixel[0] - finishPixel[0];\n          const dy = pixel[1] - finishPixel[1];\n          const snapTolerance = this.freehand_ ? 1 : this.snapTolerance_;\n          at = Math.sqrt(dx * dx + dy * dy) <= snapTolerance;\n          if (at) {\n            this.finishCoordinate_ = finishCoordinate;\n            break;\n          }\n        }\n      }\n    }\n    return at;\n  }\n\n  /**\n   * @param {import(\"../coordinate.js\").Coordinate} coordinates Coordinate.\n   * @private\n   */\n  createOrUpdateSketchPoint_(coordinates) {\n    if (!this.sketchPoint_) {\n      this.sketchPoint_ = new Feature(new Point(coordinates));\n      this.updateSketchFeatures_();\n    } else {\n      const sketchPointGeom = this.sketchPoint_.getGeometry();\n      sketchPointGeom.setCoordinates(coordinates);\n    }\n  }\n\n  /**\n   * @param {import(\"../geom/Polygon.js\").default} geometry Polygon geometry.\n   * @private\n   */\n  createOrUpdateCustomSketchLine_(geometry) {\n    if (!this.sketchLine_) {\n      this.sketchLine_ = new Feature();\n    }\n    const ring = geometry.getLinearRing(0);\n    let sketchLineGeom = this.sketchLine_.getGeometry();\n    if (!sketchLineGeom) {\n      sketchLineGeom = new LineString(\n        ring.getFlatCoordinates(),\n        ring.getLayout(),\n      );\n      this.sketchLine_.setGeometry(sketchLineGeom);\n    } else {\n      sketchLineGeom.setFlatCoordinates(\n        ring.getLayout(),\n        ring.getFlatCoordinates(),\n      );\n      sketchLineGeom.changed();\n    }\n  }\n\n  /**\n   * Start the drawing.\n   * @param {import(\"../coordinate.js\").Coordinate} start Start coordinate.\n   * @private\n   */\n  startDrawing_(start) {\n    const projection = this.getMap().getView().getProjection();\n    const stride = getStrideForLayout(this.geometryLayout_);\n    while (start.length < stride) {\n      start.push(0);\n    }\n    this.finishCoordinate_ = start;\n    if (this.mode_ === 'Point') {\n      this.sketchCoords_ = start.slice();\n    } else if (this.mode_ === 'Polygon') {\n      this.sketchCoords_ = [[start.slice(), start.slice()]];\n      this.sketchLineCoords_ = this.sketchCoords_[0];\n    } else {\n      this.sketchCoords_ = [start.slice(), start.slice()];\n    }\n    if (this.sketchLineCoords_) {\n      this.sketchLine_ = new Feature(new LineString(this.sketchLineCoords_));\n    }\n    const geometry = this.geometryFunction_(\n      this.sketchCoords_,\n      undefined,\n      projection,\n    );\n    this.sketchFeature_ = new Feature();\n    if (this.geometryName_) {\n      this.sketchFeature_.setGeometryName(this.geometryName_);\n    }\n    this.sketchFeature_.setGeometry(geometry);\n    this.updateSketchFeatures_();\n    this.dispatchEvent(\n      new DrawEvent(DrawEventType.DRAWSTART, this.sketchFeature_),\n    );\n  }\n\n  /**\n   * Modify the drawing.\n   * @param {import(\"../coordinate.js\").Coordinate} coordinate Coordinate.\n   * @private\n   */\n  modifyDrawing_(coordinate) {\n    const map = this.getMap();\n    const geometry = this.sketchFeature_.getGeometry();\n    const projection = map.getView().getProjection();\n    const stride = getStrideForLayout(this.geometryLayout_);\n    let coordinates, last;\n    while (coordinate.length < stride) {\n      coordinate.push(0);\n    }\n    if (this.mode_ === 'Point') {\n      last = this.sketchCoords_;\n    } else if (this.mode_ === 'Polygon') {\n      coordinates = /** @type {PolyCoordType} */ (this.sketchCoords_)[0];\n      last = coordinates[coordinates.length - 1];\n      if (this.atFinish_(map.getPixelFromCoordinate(coordinate))) {\n        // snap to finish\n        coordinate = this.finishCoordinate_.slice();\n      }\n    } else {\n      coordinates = this.sketchCoords_;\n      last = coordinates[coordinates.length - 1];\n    }\n    last[0] = coordinate[0];\n    last[1] = coordinate[1];\n    this.geometryFunction_(\n      /** @type {!LineCoordType} */ (this.sketchCoords_),\n      geometry,\n      projection,\n    );\n    if (this.sketchPoint_) {\n      const sketchPointGeom = this.sketchPoint_.getGeometry();\n      sketchPointGeom.setCoordinates(coordinate);\n    }\n    if (geometry.getType() === 'Polygon' && this.mode_ !== 'Polygon') {\n      this.createOrUpdateCustomSketchLine_(/** @type {Polygon} */ (geometry));\n    } else if (this.sketchLineCoords_) {\n      const sketchLineGeom = this.sketchLine_.getGeometry();\n      sketchLineGeom.setCoordinates(this.sketchLineCoords_);\n    }\n    this.updateSketchFeatures_();\n  }\n\n  /**\n   * Add a new coordinate to the drawing.\n   * @param {!PointCoordType} coordinate Coordinate\n   * @return {Feature<import(\"../geom/SimpleGeometry.js\").default>} The sketch feature.\n   * @private\n   */\n  addToDrawing_(coordinate) {\n    const geometry = this.sketchFeature_.getGeometry();\n    const projection = this.getMap().getView().getProjection();\n    let done;\n    let coordinates;\n    const mode = this.mode_;\n    if (mode === 'LineString' || mode === 'Circle') {\n      this.finishCoordinate_ = coordinate.slice();\n      coordinates = /** @type {LineCoordType} */ (this.sketchCoords_);\n      if (coordinates.length >= this.maxPoints_) {\n        if (this.freehand_) {\n          coordinates.pop();\n        } else {\n          done = true;\n        }\n      }\n      coordinates.push(coordinate.slice());\n      this.geometryFunction_(coordinates, geometry, projection);\n    } else if (mode === 'Polygon') {\n      coordinates = /** @type {PolyCoordType} */ (this.sketchCoords_)[0];\n      if (coordinates.length >= this.maxPoints_) {\n        if (this.freehand_) {\n          coordinates.pop();\n        } else {\n          done = true;\n        }\n      }\n      coordinates.push(coordinate.slice());\n      if (done) {\n        this.finishCoordinate_ = coordinates[0];\n      }\n      this.geometryFunction_(this.sketchCoords_, geometry, projection);\n    }\n    this.createOrUpdateSketchPoint_(coordinate.slice());\n    this.updateSketchFeatures_();\n    if (done) {\n      return this.finishDrawing();\n    }\n    return this.sketchFeature_;\n  }\n\n  /**\n   * @param {number} n The number of points to remove.\n   */\n  removeLastPoints_(n) {\n    if (!this.sketchFeature_) {\n      return;\n    }\n    const geometry = this.sketchFeature_.getGeometry();\n    const projection = this.getMap().getView().getProjection();\n    const mode = this.mode_;\n    for (let i = 0; i < n; ++i) {\n      let coordinates;\n      if (mode === 'LineString' || mode === 'Circle') {\n        coordinates = /** @type {LineCoordType} */ (this.sketchCoords_);\n        coordinates.splice(-2, 1);\n        if (coordinates.length >= 2) {\n          this.finishCoordinate_ = coordinates[coordinates.length - 2].slice();\n          const finishCoordinate = this.finishCoordinate_.slice();\n          coordinates[coordinates.length - 1] = finishCoordinate;\n          this.createOrUpdateSketchPoint_(finishCoordinate);\n        }\n        this.geometryFunction_(coordinates, geometry, projection);\n        if (geometry.getType() === 'Polygon' && this.sketchLine_) {\n          this.createOrUpdateCustomSketchLine_(\n            /** @type {Polygon} */ (geometry),\n          );\n        }\n      } else if (mode === 'Polygon') {\n        coordinates = /** @type {PolyCoordType} */ (this.sketchCoords_)[0];\n        coordinates.splice(-2, 1);\n        const sketchLineGeom = this.sketchLine_.getGeometry();\n        if (coordinates.length >= 2) {\n          const finishCoordinate = coordinates[coordinates.length - 2].slice();\n          coordinates[coordinates.length - 1] = finishCoordinate;\n          this.createOrUpdateSketchPoint_(finishCoordinate);\n        }\n        sketchLineGeom.setCoordinates(coordinates);\n        this.geometryFunction_(this.sketchCoords_, geometry, projection);\n      }\n\n      if (coordinates.length === 1) {\n        this.abortDrawing();\n        break;\n      }\n    }\n\n    this.updateSketchFeatures_();\n  }\n\n  /**\n   * Remove last point of the feature currently being drawn. Does not do anything when\n   * drawing POINT or MULTI_POINT geometries.\n   * @api\n   */\n  removeLastPoint() {\n    this.removeLastPoints_(1);\n  }\n\n  /**\n   * Stop drawing and add the sketch feature to the target layer.\n   * The {@link module:ol/interaction/Draw~DrawEventType.DRAWEND} event is\n   * dispatched before inserting the feature.\n   * @return {Feature<import(\"../geom/SimpleGeometry.js\").default>|null} The drawn feature.\n   * @api\n   */\n  finishDrawing() {\n    const sketchFeature = this.abortDrawing_();\n    if (!sketchFeature) {\n      return null;\n    }\n    let coordinates = this.sketchCoords_;\n    const geometry = sketchFeature.getGeometry();\n    const projection = this.getMap().getView().getProjection();\n    if (this.mode_ === 'LineString') {\n      // remove the redundant last point\n      coordinates.pop();\n      this.geometryFunction_(coordinates, geometry, projection);\n    } else if (this.mode_ === 'Polygon') {\n      // remove the redundant last point in ring\n      /** @type {PolyCoordType} */ (coordinates)[0].pop();\n      this.geometryFunction_(coordinates, geometry, projection);\n      coordinates = geometry.getCoordinates();\n    }\n\n    // cast multi-part geometries\n    if (this.type_ === 'MultiPoint') {\n      sketchFeature.setGeometry(\n        new MultiPoint([/** @type {PointCoordType} */ (coordinates)]),\n      );\n    } else if (this.type_ === 'MultiLineString') {\n      sketchFeature.setGeometry(\n        new MultiLineString([/** @type {LineCoordType} */ (coordinates)]),\n      );\n    } else if (this.type_ === 'MultiPolygon') {\n      sketchFeature.setGeometry(\n        new MultiPolygon([/** @type {PolyCoordType} */ (coordinates)]),\n      );\n    }\n\n    // First dispatch event to allow full set up of feature\n    this.dispatchEvent(new DrawEvent(DrawEventType.DRAWEND, sketchFeature));\n\n    // Then insert feature\n    if (this.features_) {\n      this.features_.push(sketchFeature);\n    }\n    if (this.source_) {\n      this.source_.addFeature(sketchFeature);\n    }\n    return sketchFeature;\n  }\n\n  /**\n   * Stop drawing without adding the sketch feature to the target layer.\n   * @return {Feature<import(\"../geom/SimpleGeometry.js\").default>|null} The sketch feature (or null if none).\n   * @private\n   */\n  abortDrawing_() {\n    this.finishCoordinate_ = null;\n    const sketchFeature = this.sketchFeature_;\n    this.sketchFeature_ = null;\n    this.sketchPoint_ = null;\n    this.sketchLine_ = null;\n    this.overlay_.getSource().clear(true);\n    this.deactivateTrace_();\n    return sketchFeature;\n  }\n\n  /**\n   * Stop drawing without adding the sketch feature to the target layer.\n   * @api\n   */\n  abortDrawing() {\n    const sketchFeature = this.abortDrawing_();\n    if (sketchFeature) {\n      this.dispatchEvent(new DrawEvent(DrawEventType.DRAWABORT, sketchFeature));\n    }\n  }\n\n  /**\n   * Append coordinates to the end of the geometry that is currently being drawn.\n   * This can be used when drawing LineStrings or Polygons. Coordinates will\n   * either be appended to the current LineString or the outer ring of the current\n   * Polygon. If no geometry is being drawn, a new one will be created.\n   * @param {!LineCoordType} coordinates Linear coordinates to be appended to\n   * the coordinate array.\n   * @api\n   */\n  appendCoordinates(coordinates) {\n    const mode = this.mode_;\n    const newDrawing = !this.sketchFeature_;\n    if (newDrawing) {\n      this.startDrawing_(coordinates[0]);\n    }\n    /** @type {LineCoordType} */\n    let sketchCoords;\n    if (mode === 'LineString' || mode === 'Circle') {\n      sketchCoords = /** @type {LineCoordType} */ (this.sketchCoords_);\n    } else if (mode === 'Polygon') {\n      sketchCoords =\n        this.sketchCoords_ && this.sketchCoords_.length\n          ? /** @type {PolyCoordType} */ (this.sketchCoords_)[0]\n          : [];\n    } else {\n      return;\n    }\n\n    if (newDrawing) {\n      sketchCoords.shift();\n    }\n\n    // Remove last coordinate from sketch drawing (this coordinate follows cursor position)\n    sketchCoords.pop();\n\n    // Append coordinate list\n    for (let i = 0; i < coordinates.length; i++) {\n      this.addToDrawing_(coordinates[i]);\n    }\n\n    const ending = coordinates[coordinates.length - 1];\n    // Duplicate last coordinate for sketch drawing (cursor position)\n    this.sketchFeature_ = this.addToDrawing_(ending);\n    this.modifyDrawing_(ending);\n  }\n\n  /**\n   * Initiate draw mode by starting from an existing geometry which will\n   * receive new additional points. This only works on features with\n   * `LineString` geometries, where the interaction will extend lines by adding\n   * points to the end of the coordinates array.\n   * This will change the original feature, instead of drawing a copy.\n   *\n   * The function will dispatch a `drawstart` event.\n   *\n   * @param {!Feature<LineString>} feature Feature to be extended.\n   * @api\n   */\n  extend(feature) {\n    const geometry = feature.getGeometry();\n    const lineString = geometry;\n    this.sketchFeature_ = feature;\n    this.sketchCoords_ = lineString.getCoordinates();\n    const last = this.sketchCoords_[this.sketchCoords_.length - 1];\n    this.finishCoordinate_ = last.slice();\n    this.sketchCoords_.push(last.slice());\n    this.sketchPoint_ = new Feature(new Point(last));\n    this.updateSketchFeatures_();\n    this.dispatchEvent(\n      new DrawEvent(DrawEventType.DRAWSTART, this.sketchFeature_),\n    );\n  }\n\n  /**\n   * Redraw the sketch features.\n   * @private\n   */\n  updateSketchFeatures_() {\n    const sketchFeatures = [];\n    if (this.sketchFeature_) {\n      sketchFeatures.push(this.sketchFeature_);\n    }\n    if (this.sketchLine_) {\n      sketchFeatures.push(this.sketchLine_);\n    }\n    if (this.sketchPoint_) {\n      sketchFeatures.push(this.sketchPoint_);\n    }\n    const overlaySource = this.overlay_.getSource();\n    overlaySource.clear(true);\n    overlaySource.addFeatures(sketchFeatures);\n  }\n\n  /**\n   * @private\n   */\n  updateState_() {\n    const map = this.getMap();\n    const active = this.getActive();\n    if (!map || !active) {\n      this.abortDrawing();\n    }\n    this.overlay_.setMap(active ? map : null);\n  }\n}\n\n/**\n * @return {import(\"../style/Style.js\").StyleFunction} Styles.\n */\nfunction getDefaultStyleFunction() {\n  const styles = createEditingStyle();\n  return function (feature, resolution) {\n    return styles[feature.getGeometry().getType()];\n  };\n}\n\n/**\n * Create a `geometryFunction` for `type: 'Circle'` that will create a regular\n * polygon with a user specified number of sides and start angle instead of a\n * {@link import(\"../geom/Circle.js\").Circle} geometry.\n * @param {number} [sides] Number of sides of the regular polygon.\n *     Default is 32.\n * @param {number} [angle] Angle of the first point in counter-clockwise\n *     radians. 0 means East.\n *     Default is the angle defined by the heading from the center of the\n *     regular polygon to the current pointer position.\n * @return {GeometryFunction} Function that draws a polygon.\n * @api\n */\nexport function createRegularPolygon(sides, angle) {\n  return function (coordinates, geometry, projection) {\n    const center = fromUserCoordinate(\n      /** @type {LineCoordType} */ (coordinates)[0],\n      projection,\n    );\n    const end = fromUserCoordinate(\n      /** @type {LineCoordType} */ (coordinates)[coordinates.length - 1],\n      projection,\n    );\n    const radius = Math.sqrt(squaredCoordinateDistance(center, end));\n    geometry = geometry || fromCircle(new Circle(center), sides);\n\n    let internalAngle = angle;\n    if (!angle && angle !== 0) {\n      const x = end[0] - center[0];\n      const y = end[1] - center[1];\n      internalAngle = Math.atan2(y, x);\n    }\n    makeRegular(\n      /** @type {Polygon} */ (geometry),\n      center,\n      radius,\n      internalAngle,\n    );\n\n    const userProjection = getUserProjection();\n    if (userProjection) {\n      geometry.transform(projection, userProjection);\n    }\n    return geometry;\n  };\n}\n\n/**\n * Create a `geometryFunction` that will create a box-shaped polygon (aligned\n * with the coordinate system axes).  Use this with the draw interaction and\n * `type: 'Circle'` to return a box instead of a circle geometry.\n * @return {GeometryFunction} Function that draws a box-shaped polygon.\n * @api\n */\nexport function createBox() {\n  return function (coordinates, geometry, projection) {\n    const extent = boundingExtent(\n      /** @type {LineCoordType} */ ([\n        coordinates[0],\n        coordinates[coordinates.length - 1],\n      ]).map(function (coordinate) {\n        return fromUserCoordinate(coordinate, projection);\n      }),\n    );\n    const boxCoordinates = [\n      [\n        getBottomLeft(extent),\n        getBottomRight(extent),\n        getTopRight(extent),\n        getTopLeft(extent),\n        getBottomLeft(extent),\n      ],\n    ];\n    if (geometry) {\n      geometry.setCoordinates(boxCoordinates);\n    } else {\n      geometry = new Polygon(boxCoordinates);\n    }\n    const userProjection = getUserProjection();\n    if (userProjection) {\n      geometry.transform(projection, userProjection);\n    }\n    return geometry;\n  };\n}\n\n/**\n * Get the drawing mode.  The mode for multi-part geometries is the same as for\n * their single-part cousins.\n * @param {import(\"../geom/Geometry.js\").Type} type Geometry type.\n * @return {Mode} Drawing mode.\n */\nfunction getMode(type) {\n  switch (type) {\n    case 'Point':\n    case 'MultiPoint':\n      return 'Point';\n    case 'LineString':\n    case 'MultiLineString':\n      return 'LineString';\n    case 'Polygon':\n    case 'MultiPolygon':\n      return 'Polygon';\n    case 'Circle':\n      return 'Circle';\n    default:\n      throw new Error('Invalid type: ' + type);\n  }\n}\n\nexport default Draw;\n", "/**\n * @module ol/interaction/Modify\n */\nimport Collection from '../Collection.js';\nimport CollectionEventType from '../CollectionEventType.js';\nimport Feature from '../Feature.js';\nimport MapBrowserEventType from '../MapBrowserEventType.js';\nimport ObjectEventType from '../ObjectEventType.js';\nimport {equals} from '../array.js';\nimport {\n  closestOnSegment,\n  distance as coordinateDistance,\n  equals as coordinatesEqual,\n  squaredDistance as squaredCoordinateDistance,\n  squaredDistanceToSegment,\n} from '../coordinate.js';\nimport Event from '../events/Event.js';\nimport EventType from '../events/EventType.js';\nimport {\n  altKeyOnly,\n  always,\n  never,\n  primaryAction,\n  singleClick,\n} from '../events/condition.js';\nimport {\n  boundingExtent,\n  buffer as bufferExtent,\n  createOrUpdateFromCoordinate as createExtent,\n} from '../extent.js';\nimport Point from '../geom/Point.js';\nimport {fromCircle} from '../geom/Polygon.js';\nimport VectorLayer from '../layer/Vector.js';\nimport {\n  fromUserCoordinate,\n  fromUserExtent,\n  getUserProjection,\n  toUserCoordinate,\n  toUserExtent,\n} from '../proj.js';\nimport VectorSource from '../source/Vector.js';\nimport VectorEventType from '../source/VectorEventType.js';\nimport RBush from '../structs/RBush.js';\nimport {createEditingStyle} from '../style/Style.js';\nimport {getUid} from '../util.js';\nimport PointerInteraction from './Pointer.js';\nimport {\n  getCoordinate,\n  getTraceTargetUpdate,\n  getTraceTargets,\n} from './tracing.js';\n\n/**\n * The segment index assigned to a circle's center when\n * breaking up a circle into ModifySegmentDataType segments.\n * @type {number}\n */\nconst CIRCLE_CENTER_INDEX = 0;\n\n/**\n * The segment index assigned to a circle's circumference when\n * breaking up a circle into ModifySegmentDataType segments.\n * @type {number}\n */\nconst CIRCLE_CIRCUMFERENCE_INDEX = 1;\n\nconst tempExtent = [0, 0, 0, 0];\nconst tempSegment = [];\n\n/**\n * @enum {string}\n */\nconst ModifyEventType = {\n  /**\n   * Triggered upon feature modification start\n   * @event ModifyEvent#modifystart\n   * @api\n   */\n  MODIFYSTART: 'modifystart',\n  /**\n   * Triggered upon feature modification end\n   * @event ModifyEvent#modifyend\n   * @api\n   */\n  MODIFYEND: 'modifyend',\n};\n\n/**\n * @typedef {Object} SegmentData\n * @property {Array<number>} [depth] Depth.\n * @property {Feature} feature Feature.\n * @property {import(\"../geom/SimpleGeometry.js\").default} geometry Geometry.\n * @property {number} [index] Index.\n * @property {Array<Array<number>>} segment Segment.\n * @property {Array<SegmentData>} [featureSegments] FeatureSegments.\n */\n\n/**\n * A function that takes a {@link module:ol/Feature~Feature} and  returns `true` if\n * the feature may be modified or `false` otherwise.\n * @typedef {function(Feature):boolean} FilterFunction\n */\n\n/**\n * @typedef {[SegmentData, number]} DragSegment\n */\n\n/**\n * @typedef {Object} Options\n * @property {import(\"../events/condition.js\").Condition} [condition] A function that\n * takes a {@link module:ol/MapBrowserEvent~MapBrowserEvent} and returns a\n * boolean to indicate whether that event will be considered to add or move a\n * vertex to the sketch. Default is\n * {@link module:ol/events/condition.primaryAction}.\n * @property {import(\"../events/condition.js\").Condition} [deleteCondition] A function\n * that takes a {@link module:ol/MapBrowserEvent~MapBrowserEvent} and returns a\n * boolean to indicate whether that event should be handled. By default,\n * {@link module:ol/events/condition.singleClick} with\n * {@link module:ol/events/condition.altKeyOnly} results in a vertex deletion.\n * This combination is handled by wrapping the two condition checks in a single function:\n * ```js\n * import { altKeyOnly, singleClick } from 'ol/events/condition.js';\n *\n * function (event) {\n *   return altKeyOnly(event) && singleClick(event)\n * }\n * ```\n * @property {import(\"../events/condition.js\").Condition} [insertVertexCondition] A\n * function that takes a {@link module:ol/MapBrowserEvent~MapBrowserEvent} and\n * returns a boolean to indicate whether a new vertex should be added to the sketch\n * features. Default is {@link module:ol/events/condition.always}.\n * @property {number} [pixelTolerance=10] Pixel tolerance for considering the\n * pointer close enough to a segment or vertex for editing.\n * @property {import(\"../style/Style.js\").StyleLike|import(\"../style/flat.js\").FlatStyleLike} [style]\n * Style used for the modification point or vertex. For linestrings and polygons, this will\n * be the affected vertex, for circles a point along the circle, and for points the actual\n * point. If not configured, the default edit style is used (see {@link module:ol/style/Style~Style}).\n * When using a style function, the point feature passed to the function will have an `existing` property -\n * indicating whether there is an existing vertex underneath or not, a `features`\n * property - an array whose entries are the features that are being modified, and a `geometries`\n * property - an array whose entries are the geometries that are being modified. Both arrays are\n * in the same order. The `geometries` are only useful when modifying geometry collections, where\n * the geometry will be the particular geometry from the collection that is being modified.\n * @property {VectorSource} [source] The vector source with\n * features to modify.  If a vector source is not provided, a feature collection\n * must be provided with the `features` option.\n * @property {boolean|import(\"../layer/BaseVector.js\").default} [hitDetection] When configured, point\n * features will be considered for modification based on their visual appearance, instead of being within\n * the `pixelTolerance` from the pointer location. When a {@link module:ol/layer/BaseVector~BaseVectorLayer} is\n * provided, only the rendered representation of the features on that layer will be considered.\n * @property {Collection<Feature>} [features]\n * The features the interaction works on.  If a feature collection is not\n * provided, a vector source must be provided with the `source` option.\n * @property {FilterFunction} [filter] A function that takes a {@link module:ol/Feature~Feature}\n * and returns `true` if the feature may be modified or `false` otherwise.\n * @property {boolean|import(\"../events/condition.js\").Condition} [trace=false] Trace a portion of another geometry.\n * Tracing starts when two neighboring vertices are dragged onto a trace target, without any other modification in between..\n * @property {VectorSource} [traceSource] Source for features to trace.  If tracing is active and a `traceSource` is\n * not provided, the interaction's `source` will be used.  Tracing requires that the interaction is configured with\n * either a `traceSource` or a `source`.\n * @property {boolean} [wrapX=false] Wrap the world horizontally on the sketch\n * overlay.\n * @property {boolean} [snapToPointer=!hitDetection] The vertex, point or segment being modified snaps to the\n * pointer coordinate when clicked within the `pixelTolerance`.\n * @property {function(import(\"../coordinate.js\").Coordinate, import(\"../coordinate.js\").Coordinate): boolean} [sharedVerticesEqual]\n * A function that takes two coordinates and returns whether they should be\n * considered equal for vertex matching purposes. By default, all coordinate\n * dimensions are compared. This is useful when features have mixed coordinate\n * dimensions (e.g., XY and XYZ) but should still be treated as sharing vertices\n * at the same 2D position.\n */\n\nfunction getCoordinatesArray(coordinates, geometryType, depth) {\n  let coordinatesArray;\n  switch (geometryType) {\n    case 'LineString':\n      coordinatesArray = coordinates;\n      break;\n    case 'MultiLineString':\n    case 'Polygon':\n      coordinatesArray = coordinates[depth[0]];\n      break;\n    case 'MultiPolygon':\n      coordinatesArray = coordinates[depth[1]][depth[0]];\n      break;\n    default:\n    // pass\n  }\n  return coordinatesArray;\n}\n\n/**\n * @classdesc\n * Events emitted by {@link module:ol/interaction/Modify~Modify} instances are\n * instances of this type.\n */\nexport class ModifyEvent extends Event {\n  /**\n   * @param {ModifyEventType} type Type.\n   * @param {Collection<Feature>} features\n   * The features modified.\n   * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent\n   * Associated {@link module:ol/MapBrowserEvent~MapBrowserEvent}.\n   */\n  constructor(type, features, mapBrowserEvent) {\n    super(type);\n\n    /**\n     * The features being modified.\n     * @type {Collection<Feature>}\n     * @api\n     */\n    this.features = features;\n\n    /**\n     * Associated {@link module:ol/MapBrowserEvent~MapBrowserEvent}.\n     * @type {import(\"../MapBrowserEvent.js\").default}\n     * @api\n     */\n    this.mapBrowserEvent = mapBrowserEvent;\n  }\n}\n\n/***\n * @template Return\n * @typedef {import(\"../Observable.js\").OnSignature<import(\"../Observable.js\").EventTypes, import(\"../events/Event.js\").default, Return> &\n *   import(\"../Observable.js\").OnSignature<import(\"../ObjectEventType.js\").Types|\n *     'change:active', import(\"../Object.js\").ObjectEvent, Return> &\n *   import(\"../Observable.js\").OnSignature<'modifyend'|'modifystart', ModifyEvent, Return> &\n *   import(\"../Observable.js\").CombinedOnSignature<import(\"../Observable.js\").EventTypes|import(\"../ObjectEventType.js\").Types|\n *     'change:active'|'modifyend'|'modifystart', Return>} ModifyOnSignature\n */\n\n/**\n * @classdesc\n * Interaction for modifying feature geometries.  To modify features that have\n * been added to an existing source, construct the modify interaction with the\n * `source` option.  If you want to modify features in a collection (for example,\n * the collection used by a select interaction), construct the interaction with\n * the `features` option.  The interaction must be constructed with either a\n * `source` or `features` option.\n *\n * Cartesian distance from the pointer is used to determine the features that\n * will be modified. This means that geometries will only be considered for\n * modification when they are within the configured `pixelTolerance`. For point\n * geometries, the `hitDetection` option can be used to match their visual\n * appearance.\n *\n * By default, the interaction will allow deletion of vertices when the `alt`\n * key is pressed.  To configure the interaction with a different condition\n * for deletion, use the `deleteCondition` option.\n * @fires ModifyEvent\n * @api\n */\nclass Modify extends PointerInteraction {\n  /**\n   * @param {Options} options Options.\n   */\n  constructor(options) {\n    super(/** @type {import(\"./Pointer.js\").Options} */ (options));\n\n    //Maintain a ref to event handlers for later unregistering\n    /** @private */\n    this.handleSourceAdd_ = this.handleSourceAdd_.bind(this);\n\n    /** @private */\n    this.handleSourceRemove_ = this.handleSourceRemove_.bind(this);\n\n    /** @private */\n    this.handleExternalCollectionAdd_ =\n      this.handleExternalCollectionAdd_.bind(this);\n\n    /** @private */\n    this.handleExternalCollectionRemove_ =\n      this.handleExternalCollectionRemove_.bind(this);\n\n    /** @private */\n    this.handleFeatureChange_ = this.handleFeatureChange_.bind(this);\n\n    /***\n     * @type {ModifyOnSignature<import(\"../events.js\").EventsKey>}\n     */\n    this.on;\n\n    /***\n     * @type {ModifyOnSignature<import(\"../events.js\").EventsKey>}\n     */\n    this.once;\n\n    /***\n     * @type {ModifyOnSignature<void>}\n     */\n    this.un;\n\n    /**\n     * @private\n     * @type {import(\"../events/condition.js\").Condition}\n     */\n    this.condition_ = options.condition ? options.condition : primaryAction;\n\n    /**\n     * @private\n     * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Browser event.\n     * @return {boolean} Combined condition result.\n     */\n    this.defaultDeleteCondition_ = function (mapBrowserEvent) {\n      return altKeyOnly(mapBrowserEvent) && singleClick(mapBrowserEvent);\n    };\n\n    /**\n     * @type {import(\"../events/condition.js\").Condition}\n     * @private\n     */\n    this.deleteCondition_ = options.deleteCondition\n      ? options.deleteCondition\n      : this.defaultDeleteCondition_;\n\n    /**\n     * @type {import(\"../events/condition.js\").Condition}\n     * @private\n     */\n    this.insertVertexCondition_ = options.insertVertexCondition\n      ? options.insertVertexCondition\n      : always;\n\n    /**\n     * Editing vertex.\n     * @type {Feature<Point>}\n     * @private\n     */\n    this.vertexFeature_ = null;\n\n    /**\n     * Segments intersecting {@link this.vertexFeature_} by segment uid.\n     * @type {Object<string, boolean>}\n     * @private\n     */\n    this.vertexSegments_ = null;\n\n    /**\n     * @type {import(\"../coordinate.js\").Coordinate}\n     * @private\n     */\n    this.lastCoordinate_ = [0, 0];\n\n    /**\n     * Tracks if the next `singleclick` event should be ignored to prevent\n     * accidental deletion right after vertex creation.\n     * @type {boolean}\n     * @private\n     */\n    this.ignoreNextSingleClick_ = false;\n\n    /**\n     * @type {Collection<Feature>}\n     * @private\n     */\n    this.featuresBeingModified_ = null;\n\n    /**\n     * Segment RTree for each layer\n     * @type {RBush<SegmentData>}\n     * @private\n     */\n    this.rBush_ = new RBush();\n\n    /**\n     * @type {number}\n     * @private\n     */\n    this.pixelTolerance_ =\n      options.pixelTolerance !== undefined ? options.pixelTolerance : 10;\n\n    /**\n     * @type {boolean}\n     * @private\n     */\n    this.snappedToVertex_ = false;\n\n    /**\n     * Indicate whether the interaction is currently changing a feature's\n     * coordinates.\n     * @type {boolean}\n     * @private\n     */\n    this.changingFeature_ = false;\n\n    /**\n     * @type {Array<DragSegment>}\n     * @private\n     */\n    this.dragSegments_ = [];\n\n    /**\n     * Draw overlay where sketch features are drawn.\n     * @type {VectorLayer}\n     * @private\n     */\n    this.overlay_ = new VectorLayer({\n      source: new VectorSource({\n        useSpatialIndex: false,\n        wrapX: !!options.wrapX,\n      }),\n      style: options.style ? options.style : getDefaultStyleFunction(),\n      updateWhileAnimating: true,\n      updateWhileInteracting: true,\n    });\n\n    /**\n     * @const\n     * @private\n     * @type {!Object<string, function(Feature, import(\"../geom/Geometry.js\").default): void>}\n     */\n    this.SEGMENT_WRITERS_ = {\n      Point: this.writePointGeometry_.bind(this),\n      LineString: this.writeLineStringGeometry_.bind(this),\n      LinearRing: this.writeLineStringGeometry_.bind(this),\n      Polygon: this.writePolygonGeometry_.bind(this),\n      MultiPoint: this.writeMultiPointGeometry_.bind(this),\n      MultiLineString: this.writeMultiLineStringGeometry_.bind(this),\n      MultiPolygon: this.writeMultiPolygonGeometry_.bind(this),\n      Circle: this.writeCircleGeometry_.bind(this),\n      GeometryCollection: this.writeGeometryCollectionGeometry_.bind(this),\n    };\n\n    /**\n     * @type {VectorSource}\n     * @private\n     */\n    this.source_ = null;\n\n    /**\n     * @type {VectorSource|null}\n     * @private\n     */\n    this.traceSource_ = options.traceSource || options.source || null;\n\n    /**\n     * @type {import(\"../events/condition.js\").Condition}\n     * @private\n     */\n    this.traceCondition_;\n    this.setTrace(options.trace || false);\n\n    /**\n     * @type {import('./tracing.js').TraceState}\n     * @private\n     */\n    this.traceState_ = {active: false};\n\n    /**\n     * @type {Array<DragSegment>|null}\n     * @private\n     */\n    this.traceSegments_ = null;\n\n    /**\n     * @type {boolean|import(\"../layer/BaseVector.js\").default}\n     * @private\n     */\n    this.hitDetection_ = null;\n\n    /**\n     * Useful for performance optimization\n     * @private\n     * @type boolean\n     */\n    this.filterFunctionWasSupplied_ =\n      options.filter != undefined ? true : false;\n\n    /**\n     * @private\n     * @type {FilterFunction}\n     */\n    this.filter_ = options.filter ? options.filter : () => true;\n\n    /**\n     * @private\n     * @type {function(import(\"../coordinate.js\").Coordinate, import(\"../coordinate.js\").Coordinate): boolean}\n     */\n    this.coordinatesEqual_ = options.sharedVerticesEqual\n      ? options.sharedVerticesEqual\n      : coordinatesEqual;\n\n    if (!(options.features || options.source)) {\n      throw new Error(\n        'The modify interaction requires features collection or a source',\n      );\n    }\n    /** @type {Array<Feature>} */\n    let features;\n    if (options.features) {\n      features = options.features.getArray();\n      //setup listeners on external features collection and features\n      options.features.addEventListener(\n        CollectionEventType.ADD,\n        this.handleExternalCollectionAdd_,\n      );\n      options.features.addEventListener(\n        CollectionEventType.REMOVE,\n        this.handleExternalCollectionRemove_,\n      );\n      //keep ref for unsubscribe on dispose\n      this.featuresCollection_ = options.features;\n    } else if (options.source) {\n      features = options.source.getFeatures();\n      //setup listeners on external source and features\n      options.source.addEventListener(\n        VectorEventType.ADDFEATURE,\n        this.handleSourceAdd_,\n      );\n      options.source.addEventListener(\n        VectorEventType.REMOVEFEATURE,\n        this.handleSourceRemove_,\n      );\n      //keep ref for unsubscribe on dispose\n      this.source_ = options.source;\n    }\n    features.forEach((feature) => {\n      //any modification to the feature requires filter to be re-run\n      feature.addEventListener(EventType.CHANGE, this.handleFeatureChange_);\n      //prop change handler is only to re-run the filter\n      if (this.filterFunctionWasSupplied_) {\n        feature.addEventListener(\n          ObjectEventType.PROPERTYCHANGE,\n          this.handleFeatureChange_,\n        );\n      }\n    });\n\n    if (options.hitDetection) {\n      this.hitDetection_ = options.hitDetection;\n    }\n\n    /**\n     * Internal features array.  When adding or removing features, be sure to use\n     * addFeature_()/removeFeature_() so that the the segment index is adjusted.\n     * @type {Array<Feature>}\n     * @private\n     */\n    this.features_ = [];\n    features\n      .filter(this.filter_)\n      .forEach((feature) => this.addFeature_(feature));\n\n    /**\n     * @type {import(\"../MapBrowserEvent.js\").default}\n     * @private\n     */\n    this.lastPointerEvent_ = null;\n\n    /**\n     * Delta (x, y in map units) between matched rtree vertex and pointer vertex.\n     * @type {Array<number>}\n     * @private\n     */\n    this.delta_ = [0, 0];\n\n    /**\n     * @private\n     */\n    this.snapToPointer_ =\n      options.snapToPointer === undefined\n        ? !this.hitDetection_\n        : options.snapToPointer;\n  }\n\n  /**\n   * Toggle tracing mode or set a tracing condition.\n   *\n   * @param {boolean|import(\"../events/condition.js\").Condition} trace A boolean to toggle tracing mode or an event\n   *     condition that will be checked when a feature is clicked to determine if tracing should be active.\n   */\n  setTrace(trace) {\n    let condition;\n    if (!trace) {\n      condition = never;\n    } else if (trace === true) {\n      condition = always;\n    } else {\n      condition = trace;\n    }\n    this.traceCondition_ = condition;\n  }\n\n  /**\n   * Called when a feature is added to the internal features collection\n   * @param {Feature} feature Feature.\n   * @private\n   */\n  addFeature_(feature) {\n    this.features_.push(feature);\n    const geometry = feature.getGeometry();\n    if (geometry) {\n      const writer = this.SEGMENT_WRITERS_[geometry.getType()];\n      if (writer) {\n        writer(feature, geometry);\n      }\n    }\n    const map = this.getMap();\n    if (map && map.isRendered() && this.getActive()) {\n      this.handlePointerAtPixel_(this.lastCoordinate_);\n    }\n  }\n\n  /**\n   * @param {import(\"../MapBrowserEvent.js\").default} evt Map browser event.\n   * @param {Array<SegmentData>} segments The segments subject to modification.\n   * @private\n   */\n  willModifyFeatures_(evt, segments) {\n    if (!this.featuresBeingModified_) {\n      this.featuresBeingModified_ = new Collection();\n      const features = this.featuresBeingModified_.getArray();\n      for (let i = 0, ii = segments.length; i < ii; ++i) {\n        const feature = segments[i].feature;\n        if (feature && !features.includes(feature)) {\n          this.featuresBeingModified_.push(feature);\n        }\n      }\n      if (this.featuresBeingModified_.getLength() === 0) {\n        this.featuresBeingModified_ = null;\n      } else {\n        this.dispatchEvent(\n          new ModifyEvent(\n            ModifyEventType.MODIFYSTART,\n            this.featuresBeingModified_,\n            evt,\n          ),\n        );\n      }\n    }\n  }\n\n  /**\n   * Removes a feature from the internal features collection and updates internal state\n   * accordingly.\n   * @param {Feature} feature Feature.\n   * @private\n   */\n  removeFeature_(feature) {\n    const itemIndex = this.features_.indexOf(feature);\n    this.features_.splice(itemIndex, 1);\n    this.removeFeatureSegmentData_(feature);\n    // Remove the vertex feature if the collection of candidate features is empty.\n    if (this.vertexFeature_ && this.features_.length === 0) {\n      this.overlay_.getSource().removeFeature(this.vertexFeature_);\n      this.vertexFeature_ = null;\n    }\n  }\n\n  /**\n   * @param {Feature} feature Feature.\n   * @private\n   */\n  removeFeatureSegmentData_(feature) {\n    const rBush = this.rBush_;\n    /** @type {Array<SegmentData>} */\n    const nodesToRemove = [];\n    rBush.forEach(\n      /**\n       * @param {SegmentData} node RTree node.\n       */\n      function (node) {\n        if (feature === node.feature) {\n          nodesToRemove.push(node);\n        }\n      },\n    );\n    for (let i = nodesToRemove.length - 1; i >= 0; --i) {\n      const nodeToRemove = nodesToRemove[i];\n      for (let j = this.dragSegments_.length - 1; j >= 0; --j) {\n        if (this.dragSegments_[j][0] === nodeToRemove) {\n          this.dragSegments_.splice(j, 1);\n        }\n      }\n      rBush.remove(nodeToRemove);\n    }\n  }\n\n  /**\n   * Activate or deactivate the interaction.\n   * @param {boolean} active Active.\n   * @observable\n   * @api\n   * @override\n   */\n  setActive(active) {\n    if (this.vertexFeature_ && !active) {\n      this.overlay_.getSource().removeFeature(this.vertexFeature_);\n      this.vertexFeature_ = null;\n    }\n    super.setActive(active);\n  }\n\n  /**\n   * Remove the interaction from its current map and attach it to the new map.\n   * Subclasses may set up event handlers to get notified about changes to\n   * the map here.\n   * @param {import(\"../Map.js\").default} map Map.\n   * @override\n   */\n  setMap(map) {\n    this.overlay_.setMap(map);\n    super.setMap(map);\n  }\n\n  /**\n   * Get the overlay layer that this interaction renders the modification point or vertex to.\n   * @return {VectorLayer} Overlay layer.\n   * @api\n   */\n  getOverlay() {\n    return this.overlay_;\n  }\n\n  /**\n   * @param {import(\"../source/Vector.js\").VectorSourceEvent} event Event.\n   * @private\n   */\n  handleSourceAdd_(event) {\n    const feature = event.feature;\n    if (feature) {\n      this.externalAddFeatureHandler_(feature);\n    }\n  }\n\n  /**\n   * @param {import(\"../source/Vector.js\").VectorSourceEvent} event Event.\n   * @private\n   */\n  handleSourceRemove_(event) {\n    const feature = event.feature;\n    if (feature) {\n      this.externalRemoveFeatureHandler_(feature);\n    }\n  }\n\n  /**\n   * @param {import(\"../Collection.js\").CollectionEvent} event Event.\n   * @private\n   */\n  handleExternalCollectionAdd_(event) {\n    const feature = event.element;\n    if (feature) {\n      this.externalAddFeatureHandler_(feature);\n    }\n  }\n\n  /**\n   * @param {import(\"../Collection.js\").CollectionEvent} event Event.\n   * @private\n   */\n  handleExternalCollectionRemove_(event) {\n    const feature = event.element;\n    if (feature) {\n      this.externalRemoveFeatureHandler_(feature);\n    }\n  }\n\n  /**\n   * Common handler for event signaling addition of feature to the supplied features source\n   * or collection.\n   * @param {Feature} feature Feature.\n   */\n  externalAddFeatureHandler_(feature) {\n    feature.addEventListener(EventType.CHANGE, this.handleFeatureChange_);\n    //prop change handler is only for reapplying the filter\n    if (this.filterFunctionWasSupplied_) {\n      feature.addEventListener(\n        ObjectEventType.PROPERTYCHANGE,\n        this.handleFeatureChange_,\n      );\n    }\n    if (this.filter_(feature)) {\n      this.addFeature_(feature);\n    }\n  }\n\n  /**\n   * Common handler for event signaling removal of feature from the supplied features source\n   * or collection.\n   * @param {Feature} feature Feature.\n   */\n  externalRemoveFeatureHandler_(feature) {\n    feature.removeEventListener(EventType.CHANGE, this.handleFeatureChange_);\n    if (this.filterFunctionWasSupplied_) {\n      feature.removeEventListener(\n        ObjectEventType.PROPERTYCHANGE,\n        this.handleFeatureChange_,\n      );\n    }\n    this.removeFeature_(feature);\n  }\n\n  /**\n   * Listener for features in external source or features collection.  Ensures the feature filter\n   * is re-run and segment data is updated.\n   * @param {import(\"../events/Event.js\").default | import(\"../Object.js\").ObjectEvent} evt Event.\n   * @private\n   */\n  handleFeatureChange_(evt) {\n    if (!this.changingFeature_) {\n      const feature = /** @type {Feature} */ (evt.target);\n      this.removeFeature_(feature);\n      //safe to remove handler on a feature if there isn't one, but need to apply the filter\n      // before adding the feature.\n      this.filter_(feature) && this.addFeature_(feature);\n    }\n  }\n\n  /**\n   * @param {Feature} feature Feature\n   * @param {Point} geometry Geometry.\n   * @private\n   */\n  writePointGeometry_(feature, geometry) {\n    const coordinates = geometry.getCoordinates();\n\n    /** @type {SegmentData} */\n    const segmentData = {\n      feature: feature,\n      geometry: geometry,\n      segment: [coordinates, coordinates],\n    };\n\n    this.rBush_.insert(geometry.getExtent(), segmentData);\n  }\n\n  /**\n   * @param {Feature} feature Feature\n   * @param {import(\"../geom/MultiPoint.js\").default} geometry Geometry.\n   * @private\n   */\n  writeMultiPointGeometry_(feature, geometry) {\n    const points = geometry.getCoordinates();\n    for (let i = 0, ii = points.length; i < ii; ++i) {\n      const coordinates = points[i];\n\n      /** @type {SegmentData} */\n      const segmentData = {\n        feature: feature,\n        geometry: geometry,\n        depth: [i],\n        index: i,\n        segment: [coordinates, coordinates],\n      };\n\n      this.rBush_.insert(geometry.getExtent(), segmentData);\n    }\n  }\n\n  /**\n   * @param {Feature} feature Feature\n   * @param {import(\"../geom/LineString.js\").default} geometry Geometry.\n   * @private\n   */\n  writeLineStringGeometry_(feature, geometry) {\n    const coordinates = geometry.getCoordinates();\n    for (let i = 0, ii = coordinates.length - 1; i < ii; ++i) {\n      const segment = coordinates.slice(i, i + 2);\n\n      /** @type {SegmentData} */\n      const segmentData = {\n        feature: feature,\n        geometry: geometry,\n        index: i,\n        segment: segment,\n      };\n\n      this.rBush_.insert(boundingExtent(segment), segmentData);\n    }\n  }\n\n  /**\n   * @param {Feature} feature Feature\n   * @param {import(\"../geom/MultiLineString.js\").default} geometry Geometry.\n   * @private\n   */\n  writeMultiLineStringGeometry_(feature, geometry) {\n    const lines = geometry.getCoordinates();\n    for (let j = 0, jj = lines.length; j < jj; ++j) {\n      const coordinates = lines[j];\n      for (let i = 0, ii = coordinates.length - 1; i < ii; ++i) {\n        const segment = coordinates.slice(i, i + 2);\n\n        /** @type {SegmentData} */\n        const segmentData = {\n          feature: feature,\n          geometry: geometry,\n          depth: [j],\n          index: i,\n          segment: segment,\n        };\n\n        this.rBush_.insert(boundingExtent(segment), segmentData);\n      }\n    }\n  }\n\n  /**\n   * @param {Feature} feature Feature\n   * @param {import(\"../geom/Polygon.js\").default} geometry Geometry.\n   * @private\n   */\n  writePolygonGeometry_(feature, geometry) {\n    const rings = geometry.getCoordinates();\n    for (let j = 0, jj = rings.length; j < jj; ++j) {\n      const coordinates = rings[j];\n      for (let i = 0, ii = coordinates.length - 1; i < ii; ++i) {\n        const segment = coordinates.slice(i, i + 2);\n\n        /** @type {SegmentData} */\n        const segmentData = {\n          feature: feature,\n          geometry: geometry,\n          depth: [j],\n          index: i,\n          segment: segment,\n        };\n\n        this.rBush_.insert(boundingExtent(segment), segmentData);\n      }\n    }\n  }\n\n  /**\n   * @param {Feature} feature Feature\n   * @param {import(\"../geom/MultiPolygon.js\").default} geometry Geometry.\n   * @private\n   */\n  writeMultiPolygonGeometry_(feature, geometry) {\n    const polygons = geometry.getCoordinates();\n    for (let k = 0, kk = polygons.length; k < kk; ++k) {\n      const rings = polygons[k];\n      for (let j = 0, jj = rings.length; j < jj; ++j) {\n        const coordinates = rings[j];\n        for (let i = 0, ii = coordinates.length - 1; i < ii; ++i) {\n          const segment = coordinates.slice(i, i + 2);\n\n          /** @type {SegmentData} */\n          const segmentData = {\n            feature: feature,\n            geometry: geometry,\n            depth: [j, k],\n            index: i,\n            segment: segment,\n          };\n\n          this.rBush_.insert(boundingExtent(segment), segmentData);\n        }\n      }\n    }\n  }\n\n  /**\n   * We convert a circle into two segments.  The segment at index\n   * {@link CIRCLE_CENTER_INDEX} is the\n   * circle's center (a point).  The segment at index\n   * {@link CIRCLE_CIRCUMFERENCE_INDEX} is\n   * the circumference, and is not a line segment.\n   *\n   * @param {Feature} feature Feature.\n   * @param {import(\"../geom/Circle.js\").default} geometry Geometry.\n   * @private\n   */\n  writeCircleGeometry_(feature, geometry) {\n    const coordinates = geometry.getCenter();\n\n    /** @type {SegmentData} */\n    const centerSegmentData = {\n      feature: feature,\n      geometry: geometry,\n      index: CIRCLE_CENTER_INDEX,\n      segment: [coordinates, coordinates],\n    };\n\n    /** @type {SegmentData} */\n    const circumferenceSegmentData = {\n      feature: feature,\n      geometry: geometry,\n      index: CIRCLE_CIRCUMFERENCE_INDEX,\n      segment: [coordinates, coordinates],\n    };\n\n    const featureSegments = [centerSegmentData, circumferenceSegmentData];\n    centerSegmentData.featureSegments = featureSegments;\n    circumferenceSegmentData.featureSegments = featureSegments;\n    this.rBush_.insert(createExtent(coordinates), centerSegmentData);\n    let circleGeometry = /** @type {import(\"../geom/Geometry.js\").default} */ (\n      geometry\n    );\n    const userProjection = getUserProjection();\n    if (userProjection && this.getMap()) {\n      const projection = this.getMap().getView().getProjection();\n      circleGeometry = circleGeometry\n        .clone()\n        .transform(userProjection, projection);\n      circleGeometry = fromCircle(\n        /** @type {import(\"../geom/Circle.js\").default} */ (circleGeometry),\n      ).transform(projection, userProjection);\n    }\n    this.rBush_.insert(circleGeometry.getExtent(), circumferenceSegmentData);\n  }\n\n  /**\n   * @param {Feature} feature Feature\n   * @param {import(\"../geom/GeometryCollection.js\").default} geometry Geometry.\n   * @private\n   */\n  writeGeometryCollectionGeometry_(feature, geometry) {\n    const geometries = geometry.getGeometriesArray();\n    for (let i = 0; i < geometries.length; ++i) {\n      const geometry = geometries[i];\n      const writer = this.SEGMENT_WRITERS_[geometry.getType()];\n      writer(feature, geometry);\n    }\n  }\n\n  /**\n   * @param {import(\"../coordinate.js\").Coordinate} coordinates Coordinates.\n   * @param {Array<Feature>} features The features being modified.\n   * @param {Array<import(\"../geom/SimpleGeometry.js\").default>} geometries The geometries being modified.\n   * @param {boolean} existing The vertex represents an existing vertex.\n   * @return {Feature} Vertex feature.\n   * @private\n   */\n  createOrUpdateVertexFeature_(coordinates, features, geometries, existing) {\n    let vertexFeature = this.vertexFeature_;\n    if (!vertexFeature) {\n      vertexFeature = new Feature(new Point(coordinates));\n      this.vertexFeature_ = vertexFeature;\n      this.overlay_.getSource().addFeature(vertexFeature);\n    } else {\n      const geometry = vertexFeature.getGeometry();\n      geometry.setCoordinates(coordinates);\n    }\n    vertexFeature.set('features', features);\n    vertexFeature.set('geometries', geometries);\n    vertexFeature.set('existing', existing);\n    return vertexFeature;\n  }\n\n  /**\n   * Handles the {@link module:ol/MapBrowserEvent~MapBrowserEvent map browser event} and may modify the geometry.\n   * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Map browser event.\n   * @return {boolean} `false` to stop event propagation.\n   * @override\n   */\n  handleEvent(mapBrowserEvent) {\n    if (!mapBrowserEvent.originalEvent) {\n      return true;\n    }\n    this.lastPointerEvent_ = mapBrowserEvent;\n\n    let handled;\n    if (\n      !mapBrowserEvent.map.getView().getInteracting() &&\n      mapBrowserEvent.type == MapBrowserEventType.POINTERMOVE &&\n      !this.handlingDownUpSequence\n    ) {\n      this.handlePointerMove_(mapBrowserEvent);\n    }\n    if (this.vertexFeature_ && this.deleteCondition_(mapBrowserEvent)) {\n      if (\n        mapBrowserEvent.type != MapBrowserEventType.SINGLECLICK ||\n        !this.ignoreNextSingleClick_\n      ) {\n        handled = this.removePoint();\n      } else {\n        handled = true;\n      }\n    }\n\n    if (mapBrowserEvent.type == MapBrowserEventType.SINGLECLICK) {\n      this.ignoreNextSingleClick_ = false;\n    }\n\n    return super.handleEvent(mapBrowserEvent) && !handled;\n  }\n\n  /**\n   * @param {import(\"../coordinate.js\").Coordinate} pixelCoordinate Pixel coordinate.\n   * @return {Array<SegmentData>|undefined} Insert vertices and update drag segments.\n   * @private\n   */\n  findInsertVerticesAndUpdateDragSegments_(pixelCoordinate) {\n    this.handlePointerAtPixel_(pixelCoordinate);\n    this.dragSegments_.length = 0;\n    this.featuresBeingModified_ = null;\n    const vertexFeature = this.vertexFeature_;\n    if (!vertexFeature) {\n      return;\n    }\n\n    const projection = this.getMap().getView().getProjection();\n    /** @type {Array<SegmentData>} */\n    const insertVertices = [];\n    const vertex = this.vertexFeature_.getGeometry().getCoordinates();\n    const vertexExtent = boundingExtent([vertex]);\n    const segmentDataMatches = this.rBush_.getInExtent(vertexExtent);\n    const componentSegments = {};\n    segmentDataMatches.sort(compareIndexes);\n    for (let i = 0, ii = segmentDataMatches.length; i < ii; ++i) {\n      const segmentDataMatch = segmentDataMatches[i];\n      const segment = segmentDataMatch.segment;\n      let uid = getUid(segmentDataMatch.geometry);\n      const depth = segmentDataMatch.depth;\n      if (depth) {\n        uid += '-' + depth.join('-'); // separate feature components\n      }\n      if (!componentSegments[uid]) {\n        componentSegments[uid] = new Array(2);\n      }\n\n      if (\n        segmentDataMatch.geometry.getType() === 'Circle' &&\n        segmentDataMatch.index === CIRCLE_CIRCUMFERENCE_INDEX\n      ) {\n        const closestVertex = closestOnSegmentData(\n          pixelCoordinate,\n          segmentDataMatch,\n          projection,\n        );\n        if (\n          this.coordinatesEqual_(closestVertex, vertex) &&\n          !componentSegments[uid][0]\n        ) {\n          this.dragSegments_.push([segmentDataMatch, 0]);\n          componentSegments[uid][0] = segmentDataMatch;\n        }\n        continue;\n      }\n\n      if (\n        this.coordinatesEqual_(segment[0], vertex) &&\n        !componentSegments[uid][0]\n      ) {\n        this.dragSegments_.push([segmentDataMatch, 0]);\n        componentSegments[uid][0] = segmentDataMatch;\n        continue;\n      }\n\n      if (\n        this.coordinatesEqual_(segment[1], vertex) &&\n        !componentSegments[uid][1]\n      ) {\n        if (\n          componentSegments[uid][0] &&\n          componentSegments[uid][0].index === 0\n        ) {\n          let coordinates = segmentDataMatch.geometry.getCoordinates();\n          switch (segmentDataMatch.geometry.getType()) {\n            // prevent dragging closed linestrings by the connecting node\n            case 'LineString':\n            case 'MultiLineString':\n              continue;\n            // if dragging the first vertex of a polygon, ensure the other segment\n            // belongs to the closing vertex of the linear ring\n            case 'MultiPolygon':\n              coordinates = coordinates[depth[1]];\n            /* falls through */\n            case 'Polygon':\n              if (segmentDataMatch.index !== coordinates[depth[0]].length - 2) {\n                continue;\n              }\n              break;\n            default:\n            // pass\n          }\n        }\n\n        this.dragSegments_.push([segmentDataMatch, 1]);\n        componentSegments[uid][1] = segmentDataMatch;\n        continue;\n      }\n\n      if (\n        getUid(segment) in this.vertexSegments_ &&\n        !componentSegments[uid][0] &&\n        !componentSegments[uid][1]\n      ) {\n        insertVertices.push(segmentDataMatch);\n      }\n    }\n\n    return insertVertices;\n  }\n\n  /**\n   * @private\n   */\n  deactivateTrace_() {\n    this.traceState_ = {active: false};\n  }\n\n  /**\n   * Update the trace.\n   * @param {import(\"../MapBrowserEvent.js\").default} event Event.\n   * @private\n   */\n  updateTrace_(event) {\n    const traceState = this.traceState_;\n    if (!traceState.active) {\n      return;\n    }\n\n    if (traceState.targetIndex === -1) {\n      // check if we are ready to pick a target\n      const startPx = event.map.getPixelFromCoordinate(traceState.startCoord);\n      if (coordinateDistance(startPx, event.pixel) < this.pixelTolerance_) {\n        return;\n      }\n    }\n\n    const updatedTraceTarget = getTraceTargetUpdate(\n      event.coordinate,\n      traceState,\n      event.map,\n      this.pixelTolerance_,\n    );\n\n    if (\n      traceState.targetIndex === -1 &&\n      Math.sqrt(updatedTraceTarget.closestTargetDistance) /\n        event.map.getView().getResolution() >\n        this.pixelTolerance_\n    ) {\n      return;\n    }\n\n    if (traceState.targetIndex !== updatedTraceTarget.index) {\n      // target changed\n      if (traceState.targetIndex !== -1) {\n        // remove points added during previous trace\n        const oldTarget = traceState.targets[traceState.targetIndex];\n        this.removeTracedCoordinates_(oldTarget.startIndex, oldTarget.endIndex);\n      } else {\n        for (const traceSegment of this.traceSegments_) {\n          const segmentData = traceSegment[0];\n          const geometry = segmentData.geometry;\n          const index = traceSegment[1];\n          const coordinates = geometry.getCoordinates();\n          const coordinatesArray = getCoordinatesArray(\n            coordinates,\n            geometry.getType(),\n            segmentData.depth,\n          );\n          coordinatesArray.splice(segmentData.index + index, 1);\n          geometry.setCoordinates(coordinates);\n          if (index === 0) {\n            segmentData.index -= 1;\n          }\n        }\n      }\n      // add points for the new target\n      const newTarget = traceState.targets[updatedTraceTarget.index];\n      this.addTracedCoordinates_(\n        newTarget,\n        newTarget.startIndex,\n        updatedTraceTarget.endIndex,\n      );\n    } else {\n      // target stayed the same\n      const target = traceState.targets[traceState.targetIndex];\n      this.addOrRemoveTracedCoordinates_(target, updatedTraceTarget.endIndex);\n    }\n\n    // modify the state with updated info\n    traceState.targetIndex = updatedTraceTarget.index;\n    const target = traceState.targets[traceState.targetIndex];\n    target.endIndex = updatedTraceTarget.endIndex;\n  }\n\n  getTraceCandidates_(event) {\n    const map = this.getMap();\n    const tolerance = this.pixelTolerance_;\n    const lowerLeft = map.getCoordinateFromPixel([\n      event.pixel[0] - tolerance,\n      event.pixel[1] + tolerance,\n    ]);\n    const upperRight = map.getCoordinateFromPixel([\n      event.pixel[0] + tolerance,\n      event.pixel[1] - tolerance,\n    ]);\n    const extent = boundingExtent([lowerLeft, upperRight]);\n    const features = this.traceSource_.getFeaturesInExtent(extent);\n    return features;\n  }\n\n  /**\n   * Activate or deactivate trace state based on a browser event.\n   * @param {import(\"../MapBrowserEvent.js\").default} event Event.\n   * @private\n   */\n  toggleTraceState_(event) {\n    if (!this.traceSource_ || !this.traceCondition_(event)) {\n      return;\n    }\n\n    if (this.traceState_.active) {\n      this.deactivateTrace_();\n      this.traceSegments_ = null;\n      return;\n    }\n\n    const features = this.getTraceCandidates_(event);\n    if (features.length === 0) {\n      return;\n    }\n\n    const targets = getTraceTargets(event.coordinate, features);\n    if (targets.length) {\n      this.traceState_ = {\n        active: true,\n        startCoord: event.coordinate.slice(),\n        targets: targets,\n        targetIndex: -1,\n      };\n    }\n  }\n\n  /**\n   * @param {import('./tracing.js').TraceTarget} target The trace target.\n   * @param {number} endIndex The new end index of the trace.\n   * @private\n   */\n  addOrRemoveTracedCoordinates_(target, endIndex) {\n    // three cases to handle:\n    //  1. traced in the same direction and points need adding\n    //  2. traced in the same direction and points need removing\n    //  3. traced in a new direction\n    const previouslyForward = target.startIndex <= target.endIndex;\n    const currentlyForward = target.startIndex <= endIndex;\n    if (previouslyForward === currentlyForward) {\n      // same direction\n      if (\n        (previouslyForward && endIndex > target.endIndex) ||\n        (!previouslyForward && endIndex < target.endIndex)\n      ) {\n        // case 1 - add new points\n        this.addTracedCoordinates_(target, target.endIndex, endIndex);\n      } else if (\n        (previouslyForward && endIndex < target.endIndex) ||\n        (!previouslyForward && endIndex > target.endIndex)\n      ) {\n        // case 2 - remove old points\n        this.removeTracedCoordinates_(endIndex, target.endIndex);\n      }\n    } else {\n      // case 3 - remove old points, add new points\n      this.removeTracedCoordinates_(target.startIndex, target.endIndex);\n      this.addTracedCoordinates_(target, target.startIndex, endIndex);\n    }\n  }\n\n  /**\n   * @param {number} fromIndex The start index.\n   * @param {number} toIndex The end index.\n   * @private\n   */\n  removeTracedCoordinates_(fromIndex, toIndex) {\n    if (fromIndex === toIndex) {\n      return;\n    }\n\n    let remove = 0;\n    if (fromIndex < toIndex) {\n      const start = Math.ceil(fromIndex);\n      let end = Math.floor(toIndex);\n      if (end === toIndex) {\n        end -= 1;\n      }\n      remove = end - start + 1;\n    } else {\n      const start = Math.floor(fromIndex);\n      let end = Math.ceil(toIndex);\n      if (end === toIndex) {\n        end += 1;\n      }\n      remove = start - end + 1;\n    }\n\n    if (remove > 0) {\n      for (const traceSegment of this.traceSegments_) {\n        const segmentData = traceSegment[0];\n        const geometry = segmentData.geometry;\n        const index = traceSegment[1];\n        let removeIndex = traceSegment[0].index + 1;\n        if (index === 1) {\n          removeIndex -= remove;\n        }\n        const coordinates = geometry.getCoordinates();\n        const coordinatesArray = getCoordinatesArray(\n          coordinates,\n          geometry.getType(),\n          segmentData.depth,\n        );\n        coordinatesArray.splice(removeIndex, remove);\n        geometry.setCoordinates(coordinates);\n        if (index === 1) {\n          segmentData.index -= remove;\n        }\n      }\n    }\n  }\n\n  /**\n   * @param {import('./tracing.js').TraceTarget} target The trace target.\n   * @param {number} fromIndex The start index.\n   * @param {number} toIndex The end index.\n   * @private\n   */\n  addTracedCoordinates_(target, fromIndex, toIndex) {\n    if (fromIndex === toIndex) {\n      return;\n    }\n\n    const newCoordinates = [];\n    if (fromIndex < toIndex) {\n      // forward trace\n      const start = Math.ceil(fromIndex);\n      let end = Math.floor(toIndex);\n      if (end === toIndex) {\n        // if end is snapped to a vertex, it will be added later\n        end -= 1;\n      }\n      for (let i = start; i <= end; ++i) {\n        newCoordinates.push(getCoordinate(target.coordinates, i));\n      }\n    } else {\n      // reverse trace\n      const start = Math.floor(fromIndex);\n      let end = Math.ceil(toIndex);\n      if (end === toIndex) {\n        end += 1;\n      }\n      for (let i = start; i >= end; --i) {\n        newCoordinates.push(getCoordinate(target.coordinates, i));\n      }\n    }\n\n    if (newCoordinates.length) {\n      for (const traceSegment of this.traceSegments_) {\n        const segmentData = traceSegment[0];\n        const geometry = segmentData.geometry;\n        const index = traceSegment[1];\n        const insertIndex = segmentData.index + 1;\n        if (index === 0) {\n          newCoordinates.reverse();\n        }\n        const coordinates = geometry.getCoordinates();\n        const coordinatesArray = getCoordinatesArray(\n          coordinates,\n          geometry.getType(),\n          segmentData.depth,\n        );\n        coordinatesArray.splice(insertIndex, 0, ...newCoordinates);\n        geometry.setCoordinates(coordinates);\n        if (index === 1) {\n          segmentData.index += newCoordinates.length;\n        }\n      }\n    }\n  }\n\n  /**\n   * @param {import('../coordinate.js').Coordinate} vertex Vertex.\n   * @param {DragSegment} dragSegment Drag segment.\n   */\n  updateGeometry_(vertex, dragSegment) {\n    const segmentData = dragSegment[0];\n    const depth = segmentData.depth;\n    let coordinates;\n    const segment = segmentData.segment;\n    const geometry = segmentData.geometry;\n    const index = dragSegment[1];\n\n    const stride = geometry.getStride();\n    for (let i = 2; i < stride; ++i) {\n      vertex[i] = segment[index][i];\n    }\n    vertex.length = stride;\n    switch (geometry.getType()) {\n      case 'Point':\n        coordinates = vertex;\n        segment[0] = vertex;\n        segment[1] = vertex;\n        break;\n      case 'MultiPoint':\n        coordinates = geometry.getCoordinates();\n        coordinates[segmentData.index] = vertex;\n        segment[0] = vertex;\n        segment[1] = vertex;\n        break;\n      case 'LineString':\n        coordinates = geometry.getCoordinates();\n        coordinates[segmentData.index + index] = vertex;\n        segment[index] = vertex;\n        break;\n      case 'MultiLineString':\n        coordinates = geometry.getCoordinates();\n        coordinates[depth[0]][segmentData.index + index] = vertex;\n        segment[index] = vertex;\n        break;\n      case 'Polygon': {\n        coordinates = geometry.getCoordinates();\n        const ring = coordinates[depth[0]];\n        const targetIndex = segmentData.index + index;\n\n        // Prevent duplicate change events when vertex already at position\n        if (\n          ring[targetIndex][0] === vertex[0] &&\n          ring[targetIndex][1] === vertex[1]\n        ) {\n          coordinates = null;\n        } else {\n          ring[targetIndex] = vertex;\n          if (targetIndex === 0) {\n            ring[ring.length - 1] = vertex;\n          } else if (targetIndex === ring.length - 1) {\n            ring[0] = vertex;\n          }\n        }\n        segment[index] = vertex;\n        break;\n      }\n      case 'MultiPolygon': {\n        coordinates = geometry.getCoordinates();\n        const mRing = coordinates[depth[1]][depth[0]];\n        const mTargetIndex = segmentData.index + index;\n\n        // Prevent duplicate change events when vertex already at position\n        if (\n          mRing[mTargetIndex][0] === vertex[0] &&\n          mRing[mTargetIndex][1] === vertex[1]\n        ) {\n          coordinates = null;\n        } else {\n          mRing[mTargetIndex] = vertex;\n          if (mTargetIndex === 0) {\n            mRing[mRing.length - 1] = vertex;\n          } else if (mTargetIndex === mRing.length - 1) {\n            mRing[0] = vertex;\n          }\n        }\n        segment[index] = vertex;\n        break;\n      }\n      case 'Circle':\n        const circle = /** @type {import(\"../geom/Circle.js\").default} */ (\n          geometry\n        );\n        segment[0] = vertex;\n        segment[1] = vertex;\n        if (segmentData.index === CIRCLE_CENTER_INDEX) {\n          this.changingFeature_ = true;\n          circle.setCenter(vertex);\n          this.changingFeature_ = false;\n        } else {\n          // We're dragging the circle's circumference:\n          this.changingFeature_ = true;\n          const projection = this.getMap().getView().getProjection();\n          let radius = coordinateDistance(\n            fromUserCoordinate(circle.getCenter(), projection),\n            fromUserCoordinate(vertex, projection),\n          );\n          const userProjection = getUserProjection();\n          if (userProjection) {\n            const circleGeometry = circle\n              .clone()\n              .transform(userProjection, projection);\n            circleGeometry.setRadius(radius);\n            radius = circleGeometry\n              .transform(projection, userProjection)\n              .getRadius();\n          }\n          circle.setRadius(radius);\n          this.changingFeature_ = false;\n        }\n        break;\n      default:\n      // pass\n    }\n    if (coordinates) {\n      this.setGeometryCoordinates_(geometry, coordinates);\n    }\n  }\n\n  /**\n   * Handle pointer drag events.\n   * @param {import(\"../MapBrowserEvent.js\").default} evt Event.\n   * @override\n   */\n  handleDragEvent(evt) {\n    this.ignoreNextSingleClick_ = false;\n    this.willModifyFeatures_(\n      evt,\n      this.dragSegments_.map(([segment]) => segment),\n    );\n\n    const vertex = [\n      evt.coordinate[0] + this.delta_[0],\n      evt.coordinate[1] + this.delta_[1],\n    ];\n    const features = [];\n    const geometries = [];\n    const startTraceCoord =\n      this.traceState_.active && !this.traceSegments_\n        ? this.traceState_.startCoord\n        : null;\n    if (startTraceCoord) {\n      this.traceSegments_ = [];\n      for (const dragSegment of this.dragSegments_) {\n        const segmentData = dragSegment[0];\n        const eligibleForTracing =\n          coordinateDistance(\n            closestOnSegment(startTraceCoord, segmentData.segment),\n            startTraceCoord,\n          ) /\n            evt.map.getView().getResolution() <\n          1;\n        if (eligibleForTracing) {\n          this.traceSegments_.push(dragSegment);\n        }\n      }\n    }\n    for (let i = 0, ii = this.dragSegments_.length; i < ii; ++i) {\n      const dragSegment = this.dragSegments_[i];\n      const segmentData = dragSegment[0];\n      const feature = segmentData.feature;\n      if (!features.includes(feature)) {\n        features.push(feature);\n      }\n      const geometry = segmentData.geometry;\n      if (!geometries.includes(geometry)) {\n        geometries.push(geometry);\n      }\n\n      this.updateGeometry_(vertex, dragSegment);\n    }\n    this.updateTrace_(evt);\n    this.createOrUpdateVertexFeature_(vertex, features, geometries, true);\n  }\n\n  /**\n   * Handle pointer down events.\n   * @param {import(\"../MapBrowserEvent.js\").default} evt Event.\n   * @return {boolean} If the event was consumed.\n   * @override\n   */\n  handleDownEvent(evt) {\n    if (!this.condition_(evt)) {\n      return false;\n    }\n    const pixelCoordinate = evt.coordinate;\n    const insertVertices =\n      this.findInsertVerticesAndUpdateDragSegments_(pixelCoordinate);\n\n    if (insertVertices?.length && this.insertVertexCondition_(evt)) {\n      this.willModifyFeatures_(evt, insertVertices);\n\n      if (this.vertexFeature_) {\n        const vertex = this.vertexFeature_.getGeometry().getCoordinates();\n        for (let j = insertVertices.length - 1; j >= 0; --j) {\n          this.insertVertex_(insertVertices[j], vertex);\n        }\n        this.ignoreNextSingleClick_ = true;\n      }\n    }\n\n    return !!this.vertexFeature_;\n  }\n\n  /**\n   * Handle pointer up events.\n   * @param {import(\"../MapBrowserEvent.js\").default} evt Event.\n   * @return {boolean} If the event was consumed.\n   * @override\n   */\n  handleUpEvent(evt) {\n    for (let i = this.dragSegments_.length - 1; i >= 0; --i) {\n      const segmentData = this.dragSegments_[i][0];\n      const geometry = segmentData.geometry;\n      if (geometry.getType() === 'Circle') {\n        const circle = /** @type {import(\"../geom/Circle.js\").default} */ (\n          geometry\n        );\n        // Update a circle object in the R* bush:\n        const coordinates = circle.getCenter();\n        const centerSegmentData = segmentData.featureSegments[0];\n        const circumferenceSegmentData = segmentData.featureSegments[1];\n        centerSegmentData.segment[0] = coordinates;\n        centerSegmentData.segment[1] = coordinates;\n        circumferenceSegmentData.segment[0] = coordinates;\n        circumferenceSegmentData.segment[1] = coordinates;\n        this.rBush_.update(createExtent(coordinates), centerSegmentData);\n        /** @type {import(\"../geom/Circle.js\").default | import(\"../geom/Polygon.js\").default} */\n        let circleGeometry = circle;\n        const userProjection = getUserProjection();\n        if (userProjection) {\n          const projection = evt.map.getView().getProjection();\n          circleGeometry = circleGeometry\n            .clone()\n            .transform(userProjection, projection);\n          circleGeometry = fromCircle(circleGeometry).transform(\n            projection,\n            userProjection,\n          );\n        }\n        this.rBush_.update(\n          circleGeometry.getExtent(),\n          circumferenceSegmentData,\n        );\n      } else {\n        this.rBush_.update(boundingExtent(segmentData.segment), segmentData);\n      }\n    }\n    if (this.featuresBeingModified_) {\n      this.toggleTraceState_(evt);\n      this.dispatchEvent(\n        new ModifyEvent(\n          ModifyEventType.MODIFYEND,\n          this.featuresBeingModified_,\n          evt,\n        ),\n      );\n      this.featuresBeingModified_ = null;\n    }\n    return false;\n  }\n\n  /**\n   * @param {import(\"../MapBrowserEvent.js\").default} evt Event.\n   * @private\n   */\n  handlePointerMove_(evt) {\n    this.lastCoordinate_ = evt.coordinate;\n    this.handlePointerAtPixel_(this.lastCoordinate_);\n  }\n\n  /**\n   * @param {import(\"../coordinate.js\").Coordinate} pixelCoordinate The pixel Coordinate.\n   * @private\n   */\n  handlePointerAtPixel_(pixelCoordinate) {\n    const map = this.getMap();\n    const pixel = map.getPixelFromCoordinate(pixelCoordinate);\n    const projection = map.getView().getProjection();\n    const sortByDistance = function (a, b) {\n      return (\n        projectedDistanceToSegmentDataSquared(pixelCoordinate, a, projection) -\n        projectedDistanceToSegmentDataSquared(pixelCoordinate, b, projection)\n      );\n    };\n\n    /** @type {Array<SegmentData>|undefined} */\n    let nodes;\n    /** @type {Point|undefined} */\n    let hitPointGeometry;\n    if (this.hitDetection_) {\n      const layerFilter =\n        typeof this.hitDetection_ === 'object'\n          ? (layer) => layer === this.hitDetection_\n          : undefined;\n      map.forEachFeatureAtPixel(\n        pixel,\n        (feature, layer, geometry) => {\n          if (geometry && geometry.getType() === 'Point') {\n            geometry = new Point(\n              toUserCoordinate(geometry.getCoordinates(), projection),\n            );\n          }\n          const geom = geometry || feature.getGeometry();\n\n          if (\n            geom &&\n            geom.getType() === 'Point' &&\n            feature instanceof Feature &&\n            this.features_.includes(feature)\n          ) {\n            hitPointGeometry = /** @type {Point} */ (geom);\n            const coordinate = /** @type {Point} */ (feature.getGeometry())\n              .getFlatCoordinates()\n              .slice(0, 2);\n            nodes = [\n              {\n                feature,\n                geometry: hitPointGeometry,\n                segment: [coordinate, coordinate],\n              },\n            ];\n          }\n          return true;\n        },\n        {layerFilter},\n      );\n    }\n    if (!nodes) {\n      const viewExtent = fromUserExtent(\n        createExtent(pixelCoordinate, tempExtent),\n        projection,\n      );\n      const buffer = map.getView().getResolution() * this.pixelTolerance_;\n      const box = toUserExtent(\n        bufferExtent(viewExtent, buffer, tempExtent),\n        projection,\n      );\n      nodes = this.rBush_.getInExtent(box);\n    }\n\n    if (nodes && nodes.length > 0) {\n      const node = nodes.sort(sortByDistance)[0];\n      const closestSegment = node.segment;\n      let vertex = closestOnSegmentData(pixelCoordinate, node, projection);\n      const vertexPixel = map.getPixelFromCoordinate(vertex);\n      let dist = coordinateDistance(pixel, vertexPixel);\n      if (hitPointGeometry || dist <= this.pixelTolerance_) {\n        /** @type {Object<string, boolean>} */\n        const vertexSegments = {};\n        vertexSegments[getUid(closestSegment)] = true;\n\n        if (!this.snapToPointer_) {\n          this.delta_[0] = vertex[0] - pixelCoordinate[0];\n          this.delta_[1] = vertex[1] - pixelCoordinate[1];\n        }\n        if (\n          node.geometry.getType() === 'Circle' &&\n          node.index === CIRCLE_CIRCUMFERENCE_INDEX\n        ) {\n          this.snappedToVertex_ = true;\n          this.createOrUpdateVertexFeature_(\n            vertex,\n            [node.feature],\n            [node.geometry],\n            this.snappedToVertex_,\n          );\n        } else {\n          const pixel1 = map.getPixelFromCoordinate(closestSegment[0]);\n          const pixel2 = map.getPixelFromCoordinate(closestSegment[1]);\n          const squaredDist1 = squaredCoordinateDistance(vertexPixel, pixel1);\n          const squaredDist2 = squaredCoordinateDistance(vertexPixel, pixel2);\n          dist = Math.sqrt(Math.min(squaredDist1, squaredDist2));\n          this.snappedToVertex_ = dist <= this.pixelTolerance_;\n          // Stop and cleanup overlay vertex feature if a segment was hit and new vertex creation is not allowed by the insertVertexCondition\n          if (\n            !this.snappedToVertex_ &&\n            !this.insertVertexCondition_(this.lastPointerEvent_)\n          ) {\n            if (this.vertexFeature_) {\n              this.overlay_.getSource().removeFeature(this.vertexFeature_);\n              this.vertexFeature_ = null;\n            }\n            return;\n          }\n          if (this.snappedToVertex_) {\n            vertex =\n              squaredDist1 > squaredDist2\n                ? closestSegment[1]\n                : closestSegment[0];\n          }\n          this.createOrUpdateVertexFeature_(\n            vertex,\n            [node.feature],\n            [node.geometry],\n            this.snappedToVertex_,\n          );\n          const geometries = {};\n          geometries[getUid(node.geometry)] = true;\n          for (let i = 1, ii = nodes.length; i < ii; ++i) {\n            const segment = nodes[i].segment;\n            if (\n              (this.coordinatesEqual_(closestSegment[0], segment[0]) &&\n                this.coordinatesEqual_(closestSegment[1], segment[1])) ||\n              (this.coordinatesEqual_(closestSegment[0], segment[1]) &&\n                this.coordinatesEqual_(closestSegment[1], segment[0]))\n            ) {\n              const geometryUid = getUid(nodes[i].geometry);\n              if (!(geometryUid in geometries)) {\n                geometries[geometryUid] = true;\n                vertexSegments[getUid(segment)] = true;\n              }\n            } else {\n              break;\n            }\n          }\n        }\n\n        this.vertexSegments_ = vertexSegments;\n        return;\n      }\n    }\n    if (this.vertexFeature_) {\n      this.overlay_.getSource().removeFeature(this.vertexFeature_);\n      this.vertexFeature_ = null;\n    }\n  }\n\n  /**\n   * @param {SegmentData} segmentData Segment data.\n   * @param {import(\"../coordinate.js\").Coordinate} vertex Vertex.\n   * @return {boolean} A vertex was inserted.\n   * @private\n   */\n  insertVertex_(segmentData, vertex) {\n    const segment = segmentData.segment;\n    const feature = segmentData.feature;\n    const geometry = segmentData.geometry;\n    const depth = segmentData.depth;\n    const index = segmentData.index;\n    let coordinates;\n\n    while (vertex.length < geometry.getStride()) {\n      vertex.push(0);\n    }\n\n    switch (geometry.getType()) {\n      case 'MultiLineString':\n        coordinates = geometry.getCoordinates();\n        coordinates[depth[0]].splice(index + 1, 0, vertex);\n        break;\n      case 'Polygon':\n        coordinates = geometry.getCoordinates();\n        coordinates[depth[0]].splice(index + 1, 0, vertex);\n        break;\n      case 'MultiPolygon':\n        coordinates = geometry.getCoordinates();\n        coordinates[depth[1]][depth[0]].splice(index + 1, 0, vertex);\n        break;\n      case 'LineString':\n        coordinates = geometry.getCoordinates();\n        coordinates.splice(index + 1, 0, vertex);\n        break;\n      default:\n        return false;\n    }\n\n    this.setGeometryCoordinates_(geometry, coordinates);\n    const rTree = this.rBush_;\n    rTree.remove(segmentData);\n    this.updateSegmentIndices_(geometry, index, depth, 1);\n\n    /** @type {SegmentData} */\n    const newSegmentData = {\n      segment: [segment[0], vertex],\n      feature: feature,\n      geometry: geometry,\n      depth: depth,\n      index: index,\n    };\n\n    rTree.insert(boundingExtent(newSegmentData.segment), newSegmentData);\n    this.dragSegments_.push([newSegmentData, 1]);\n\n    /** @type {SegmentData} */\n    const newSegmentData2 = {\n      segment: [vertex, segment[1]],\n      feature: feature,\n      geometry: geometry,\n      depth: depth,\n      index: index + 1,\n    };\n\n    rTree.insert(boundingExtent(newSegmentData2.segment), newSegmentData2);\n    this.dragSegments_.push([newSegmentData2, 0]);\n    return true;\n  }\n\n  /**\n   * @param {import(\"../coordinate.js\").Coordinate} coordinate The coordinate.\n   * @return {import(\"../coordinate.js\").Coordinate} The updated pointer coordinate.\n   * @private\n   */\n  updatePointer_(coordinate) {\n    if (coordinate) {\n      this.findInsertVerticesAndUpdateDragSegments_(coordinate);\n    }\n    return this.vertexFeature_?.getGeometry().getCoordinates();\n  }\n\n  /**\n   * Get the current pointer position.\n   * @return {import(\"../coordinate.js\").Coordinate | null} The current pointer coordinate.\n   */\n  getPoint() {\n    const coordinate = this.vertexFeature_?.getGeometry().getCoordinates();\n    if (!coordinate) {\n      return null;\n    }\n    return toUserCoordinate(\n      coordinate,\n      this.getMap().getView().getProjection(),\n    );\n  }\n\n  /**\n   * Check if a point can be removed from the current linestring or polygon at the current\n   * pointer position.\n   * @return {boolean} A point can be deleted at the current pointer position.\n   * @api\n   */\n  canRemovePoint() {\n    if (!this.vertexFeature_) {\n      return false;\n    }\n    if (\n      this.vertexFeature_\n        .get('geometries')\n        .every(\n          (geometry) =>\n            geometry.getType() === 'Circle' ||\n            geometry.getType().endsWith('Point'),\n        )\n    ) {\n      return false;\n    }\n    const coordinate = this.vertexFeature_.getGeometry().getCoordinates();\n    const segments = this.rBush_.getInExtent(boundingExtent([coordinate]));\n    return segments.some(\n      ({segment}) =>\n        this.coordinatesEqual_(segment[0], coordinate) ||\n        this.coordinatesEqual_(segment[1], coordinate),\n    );\n  }\n\n  /**\n   * Removes the vertex currently being pointed from the current linestring or polygon.\n   * @param {import('../coordinate.js').Coordinate} [coordinate] If provided, the pointer\n   * will be set to the provided coordinate. If not, the current pointer coordinate will be used.\n   * @return {boolean} True when a vertex was removed.\n   * @api\n   */\n  removePoint(coordinate) {\n    if (coordinate) {\n      coordinate = fromUserCoordinate(\n        coordinate,\n        this.getMap().getView().getProjection(),\n      );\n      this.updatePointer_(coordinate);\n    }\n    if (\n      !this.lastPointerEvent_ ||\n      (this.lastPointerEvent_ &&\n        this.lastPointerEvent_.type != MapBrowserEventType.POINTERDRAG)\n    ) {\n      const evt = this.lastPointerEvent_;\n      this.willModifyFeatures_(\n        evt,\n        this.dragSegments_.map(([segment]) => segment),\n      );\n      const removed = this.removeVertex_();\n      if (this.featuresBeingModified_) {\n        this.dispatchEvent(\n          new ModifyEvent(\n            ModifyEventType.MODIFYEND,\n            this.featuresBeingModified_,\n            evt,\n          ),\n        );\n      }\n\n      this.featuresBeingModified_ = null;\n      return removed;\n    }\n    return false;\n  }\n\n  /**\n   * Removes a vertex from all matching features.\n   * @return {boolean} True when a vertex was removed.\n   * @private\n   */\n  removeVertex_() {\n    const dragSegments = this.dragSegments_;\n    const segmentsByFeature = {};\n    let deleted = false;\n    let component, coordinates, dragSegment, geometry, i, index, left;\n    let newIndex, right, segmentData, uid;\n    for (i = dragSegments.length - 1; i >= 0; --i) {\n      dragSegment = dragSegments[i];\n      segmentData = dragSegment[0];\n      uid = getUid(segmentData.feature);\n      if (segmentData.depth) {\n        // separate feature components\n        uid += '-' + segmentData.depth.join('-');\n      }\n      if (!(uid in segmentsByFeature)) {\n        segmentsByFeature[uid] = {};\n      }\n      if (dragSegment[1] === 0) {\n        segmentsByFeature[uid].right = segmentData;\n        segmentsByFeature[uid].index = segmentData.index;\n      } else if (dragSegment[1] == 1) {\n        segmentsByFeature[uid].left = segmentData;\n        segmentsByFeature[uid].index = segmentData.index + 1;\n      }\n    }\n    for (uid in segmentsByFeature) {\n      right = segmentsByFeature[uid].right;\n      left = segmentsByFeature[uid].left;\n      index = segmentsByFeature[uid].index;\n      newIndex = index - 1;\n      if (left !== undefined) {\n        segmentData = left;\n      } else {\n        segmentData = right;\n      }\n      if (newIndex < 0) {\n        newIndex = 0;\n      }\n      geometry = segmentData.geometry;\n      coordinates = geometry.getCoordinates();\n      component = coordinates;\n      deleted = false;\n      switch (geometry.getType()) {\n        case 'MultiLineString':\n          if (coordinates[segmentData.depth[0]].length > 2) {\n            coordinates[segmentData.depth[0]].splice(index, 1);\n            deleted = true;\n          }\n          break;\n        case 'LineString':\n          if (coordinates.length > 2) {\n            coordinates.splice(index, 1);\n            deleted = true;\n          }\n          break;\n        case 'MultiPolygon':\n          component = component[segmentData.depth[1]];\n        /* falls through */\n        case 'Polygon':\n          component = component[segmentData.depth[0]];\n          if (component.length > 4) {\n            if (index == component.length - 1) {\n              index = 0;\n            }\n            component.splice(index, 1);\n            deleted = true;\n            if (index === 0) {\n              // close the ring again\n              component.pop();\n              component.push(component[0]);\n              newIndex = component.length - 1;\n            }\n          }\n          break;\n        default:\n        // pass\n      }\n\n      if (deleted) {\n        this.setGeometryCoordinates_(geometry, coordinates);\n        const segments = [];\n        if (left !== undefined) {\n          this.rBush_.remove(left);\n          segments.push(left.segment[0]);\n        }\n        if (right !== undefined) {\n          this.rBush_.remove(right);\n          segments.push(right.segment[1]);\n        }\n        if (left !== undefined && right !== undefined) {\n          /** @type {SegmentData} */\n          const newSegmentData = {\n            depth: segmentData.depth,\n            feature: segmentData.feature,\n            geometry: segmentData.geometry,\n            index: newIndex,\n            segment: segments,\n          };\n\n          this.rBush_.insert(\n            boundingExtent(newSegmentData.segment),\n            newSegmentData,\n          );\n        }\n        this.updateSegmentIndices_(geometry, index, segmentData.depth, -1);\n        if (this.vertexFeature_) {\n          this.overlay_.getSource().removeFeature(this.vertexFeature_);\n          this.vertexFeature_ = null;\n        }\n        dragSegments.length = 0;\n      }\n    }\n    return deleted;\n  }\n\n  /**\n   * Check if a point can be inserted to the current linestring or polygon at the current\n   * pointer position.\n   * @return {boolean} A point can be inserted at the current pointer position.\n   * @api\n   */\n  canInsertPoint() {\n    if (!this.vertexFeature_) {\n      return false;\n    }\n    if (\n      this.vertexFeature_\n        .get('geometries')\n        .every(\n          (geometry) =>\n            geometry.getType() === 'Circle' ||\n            geometry.getType().endsWith('Point'),\n        )\n    ) {\n      return false;\n    }\n    const coordinate = this.vertexFeature_.getGeometry().getCoordinates();\n    const segments = this.rBush_.getInExtent(boundingExtent([coordinate]));\n    return segments.some(\n      ({segment}) =>\n        !(\n          this.coordinatesEqual_(segment[0], coordinate) ||\n          this.coordinatesEqual_(segment[1], coordinate)\n        ),\n    );\n  }\n\n  /**\n   * Inserts the vertex currently being pointed to the current linestring or polygon.\n   * @param {import('../coordinate.js').Coordinate} [coordinate] If provided, the pointer\n   * will be set to the provided coordinate. If not, the current pointer coordinate will be used.\n   * @return {boolean} A vertex was inserted.\n   * @api\n   */\n  insertPoint(coordinate) {\n    const pixelCoordinate = coordinate\n      ? fromUserCoordinate(coordinate, this.getMap().getView().getProjection())\n      : this.vertexFeature_?.getGeometry().getCoordinates();\n    if (!pixelCoordinate) {\n      return false;\n    }\n    const insertVertices =\n      this.findInsertVerticesAndUpdateDragSegments_(pixelCoordinate);\n    return insertVertices.reduce(\n      (prev, segmentData) =>\n        prev || this.insertVertex_(segmentData, pixelCoordinate),\n      false,\n    );\n  }\n\n  /**\n   * @param {import(\"../geom/SimpleGeometry.js\").default} geometry Geometry.\n   * @param {Array} coordinates Coordinates.\n   * @private\n   */\n  setGeometryCoordinates_(geometry, coordinates) {\n    this.changingFeature_ = true;\n    geometry.setCoordinates(coordinates);\n    this.changingFeature_ = false;\n  }\n\n  /**\n   * @param {import(\"../geom/SimpleGeometry.js\").default} geometry Geometry.\n   * @param {number} index Index.\n   * @param {Array<number>|undefined} depth Depth.\n   * @param {number} delta Delta (1 or -1).\n   * @private\n   */\n  updateSegmentIndices_(geometry, index, depth, delta) {\n    this.rBush_.forEachInExtent(\n      geometry.getExtent(),\n      function (segmentDataMatch) {\n        if (\n          segmentDataMatch.geometry === geometry &&\n          (depth === undefined ||\n            segmentDataMatch.depth === undefined ||\n            equals(segmentDataMatch.depth, depth)) &&\n          segmentDataMatch.index > index\n        ) {\n          segmentDataMatch.index += delta;\n        }\n      },\n    );\n  }\n\n  /**\n   * @override\n   */\n  disposeInternal() {\n    super.disposeInternal();\n    if (this.featuresCollection_) {\n      this.featuresCollection_.removeEventListener(\n        CollectionEventType.ADD,\n        this.handleExternalCollectionAdd_,\n      );\n      this.featuresCollection_.removeEventListener(\n        CollectionEventType.REMOVE,\n        this.handleExternalCollectionRemove_,\n      );\n      //change and propertychange event handlers were placed on all features in the external\n      // collection, not just the ones that passed the filter.  Remove these too.\n      for (const feature of this.featuresCollection_.getArray()) {\n        feature.removeEventListener(\n          EventType.CHANGE,\n          this.handleFeatureChange_,\n        );\n        if (this.filterFunctionWasSupplied_) {\n          feature.removeEventListener(\n            ObjectEventType.PROPERTYCHANGE,\n            this.handleFeatureChange_,\n          );\n        }\n      }\n    } else if (this.source_) {\n      this.source_.removeEventListener(\n        VectorEventType.ADDFEATURE,\n        this.handleSourceAdd_,\n      );\n      this.source_.removeEventListener(\n        VectorEventType.REMOVEFEATURE,\n        this.handleSourceRemove_,\n      );\n      //change and propertychange event handlers were placed on all features in the source, not\n      // just the ones that passed the filter.  Remove these too.\n      for (const feature of this.source_.getFeatures()) {\n        feature.removeEventListener(\n          EventType.CHANGE,\n          this.handleFeatureChange_,\n        );\n        if (this.filterFunctionWasSupplied_) {\n          feature.removeEventListener(\n            ObjectEventType.PROPERTYCHANGE,\n            this.handleFeatureChange_,\n          );\n        }\n      }\n    }\n  }\n}\n\n/**\n * @param {SegmentData} a The first segment data.\n * @param {SegmentData} b The second segment data.\n * @return {number} The difference in indexes.\n */\nfunction compareIndexes(a, b) {\n  return a.index - b.index;\n}\n\n/**\n * Returns the distance from a point to a line segment.\n *\n * @param {import(\"../coordinate.js\").Coordinate} pointCoordinates The coordinates of the point from\n *        which to calculate the distance.\n * @param {SegmentData} segmentData The object describing the line\n *        segment we are calculating the distance to.\n * @param {import(\"../proj/Projection.js\").default} projection The view projection.\n * @return {number} The square of the distance between a point and a line segment.\n */\nfunction projectedDistanceToSegmentDataSquared(\n  pointCoordinates,\n  segmentData,\n  projection,\n) {\n  const geometry = segmentData.geometry;\n\n  if (geometry.getType() === 'Circle') {\n    let circleGeometry = /** @type {import(\"../geom/Circle.js\").default} */ (\n      geometry\n    );\n\n    if (segmentData.index === CIRCLE_CIRCUMFERENCE_INDEX) {\n      const userProjection = getUserProjection();\n      if (userProjection) {\n        circleGeometry = circleGeometry\n          .clone()\n          .transform(userProjection, projection);\n      }\n      const distanceToCenterSquared = squaredCoordinateDistance(\n        circleGeometry.getCenter(),\n        fromUserCoordinate(pointCoordinates, projection),\n      );\n      const distanceToCircumference =\n        Math.sqrt(distanceToCenterSquared) - circleGeometry.getRadius();\n      return distanceToCircumference * distanceToCircumference;\n    }\n  }\n\n  const coordinate = fromUserCoordinate(pointCoordinates, projection);\n  tempSegment[0] = fromUserCoordinate(segmentData.segment[0], projection);\n  tempSegment[1] = fromUserCoordinate(segmentData.segment[1], projection);\n  return squaredDistanceToSegment(coordinate, tempSegment);\n}\n\n/**\n * Returns the point closest to a given line segment.\n *\n * @param {import(\"../coordinate.js\").Coordinate} pointCoordinates The point to which a closest point\n *        should be found.\n * @param {SegmentData} segmentData The object describing the line\n *        segment which should contain the closest point.\n * @param {import(\"../proj/Projection.js\").default} projection The view projection.\n * @return {import(\"../coordinate.js\").Coordinate} The point closest to the specified line segment.\n */\nfunction closestOnSegmentData(pointCoordinates, segmentData, projection) {\n  const geometry = segmentData.geometry;\n\n  if (\n    geometry.getType() === 'Circle' &&\n    segmentData.index === CIRCLE_CIRCUMFERENCE_INDEX\n  ) {\n    let circleGeometry = /** @type {import(\"../geom/Circle.js\").default} */ (\n      geometry\n    );\n    const userProjection = getUserProjection();\n    if (userProjection) {\n      circleGeometry = circleGeometry\n        .clone()\n        .transform(userProjection, projection);\n    }\n    return toUserCoordinate(\n      circleGeometry.getClosestPoint(\n        fromUserCoordinate(pointCoordinates, projection),\n      ),\n      projection,\n    );\n  }\n  const coordinate = fromUserCoordinate(pointCoordinates, projection);\n  tempSegment[0] = fromUserCoordinate(segmentData.segment[0], projection);\n  tempSegment[1] = fromUserCoordinate(segmentData.segment[1], projection);\n  return toUserCoordinate(\n    closestOnSegment(coordinate, tempSegment),\n    projection,\n  );\n}\n\n/**\n * @return {import(\"../style/Style.js\").StyleFunction} Styles.\n */\nfunction getDefaultStyleFunction() {\n  const style = createEditingStyle();\n  return function (feature, resolution) {\n    return style['Point'];\n  };\n}\n\nexport default Modify;\n", "/**\n * @module ol/interaction/Select\n */\nimport Collection from '../Collection.js';\nimport CollectionEventType from '../CollectionEventType.js';\nimport Feature from '../Feature.js';\nimport {extend} from '../array.js';\nimport Event from '../events/Event.js';\nimport {never, shiftKeyOnly, singleClick} from '../events/condition.js';\nimport {TRUE} from '../functions.js';\nimport VectorLayer from '../layer/Vector.js';\nimport {createEditingStyle} from '../style/Style.js';\nimport {getUid} from '../util.js';\nimport Interaction from './Interaction.js';\n\n/**\n * @enum {string}\n */\nconst SelectEventType = {\n  /**\n   * Triggered when feature(s) has been (de)selected.\n   * @event SelectEvent#select\n   * @api\n   */\n  SELECT: 'select',\n};\n\n/**\n * A function that takes a {@link module:ol/Feature~Feature} and returns `true` if the feature may be\n * selected or `false` otherwise.\n * @typedef {function(import(\"../Feature.js\").default, import(\"../layer/Layer.js\").default<import(\"../source/Source.js\").default>):boolean} FilterFunction\n */\n\n/**\n * @typedef {Object} Options\n * @property {import(\"../events/condition.js\").Condition} [addCondition] A function\n * that takes a {@link module:ol/MapBrowserEvent~MapBrowserEvent} and returns a\n * boolean to indicate whether that event should be handled.\n * By default, this is {@link module:ol/events/condition.never}. Use this if you\n * want to use different events for add and remove instead of `toggle`.\n * @property {import(\"../events/condition.js\").Condition} [condition] A function that\n * takes a {@link module:ol/MapBrowserEvent~MapBrowserEvent} and returns a\n * boolean to indicate whether that event should be handled. This is the event\n * for the selected features as a whole. By default, this is\n * {@link module:ol/events/condition.singleClick}. Clicking on a feature selects that\n * feature and removes any that were in the selection. Clicking outside any\n * feature removes all from the selection.\n * See `toggle`, `add`, `remove` options for adding/removing extra features to/\n * from the selection.\n * @property {Array<import(\"../layer/Layer.js\").default>|function(import(\"../layer/Layer.js\").default<import(\"../source/Source.js\").default>): boolean} [layers]\n * A list of layers from which features should be selected. Alternatively, a\n * filter function can be provided. The function will be called for each layer\n * in the map and should return `true` for layers that you want to be\n * selectable. If the option is absent, all visible layers will be considered\n * selectable.\n * @property {import(\"../style/Style.js\").StyleLike|null} [style]\n * Style for the selected features. By default the default edit style is used\n * (see {@link module:ol/style/Style~Style}). Set to `null` if this interaction should not apply\n * any style changes for selected features.\n * If set to a falsey value, the selected feature's style will not change.\n * @property {import(\"../events/condition.js\").Condition} [removeCondition] A function\n * that takes a {@link module:ol/MapBrowserEvent~MapBrowserEvent} and returns a\n * boolean to indicate whether that event should be handled.\n * By default, this is {@link module:ol/events/condition.never}. Use this if you\n * want to use different events for add and remove instead of `toggle`.\n * @property {import(\"../events/condition.js\").Condition} [toggleCondition] A function\n * that takes a {@link module:ol/MapBrowserEvent~MapBrowserEvent} and returns a\n * boolean to indicate whether that event should be handled. This is in addition\n * to the `condition` event. By default,\n * {@link module:ol/events/condition.shiftKeyOnly}, i.e. pressing `shift` as\n * well as the `condition` event, adds that feature to the current selection if\n * it is not currently selected, and removes it if it is. See `add` and `remove`\n * if you want to use different events instead of a toggle.\n * @property {boolean} [multi=false] A boolean that determines if the default\n * behaviour should select only single features or all (overlapping) features at\n * the clicked map position. The default of `false` means single select.\n * @property {Collection<Feature>} [features]\n * Collection where the interaction will place selected features. Optional. If\n * not set the interaction will create a collection. In any case the collection\n * used by the interaction is returned by\n * {@link module:ol/interaction/Select~Select#getFeatures}.\n * @property {FilterFunction} [filter] A function\n * that takes a {@link module:ol/Feature~Feature} and a\n * {@link module:ol/layer/Layer~Layer} and returns `true` if the feature may be\n * selected or `false` otherwise.\n * @property {number} [hitTolerance=0] Hit-detection tolerance. Pixels inside\n * the radius around the given position will be checked for features.\n */\n\n/**\n * @classdesc\n * Events emitted by {@link module:ol/interaction/Select~Select} instances are instances of\n * this type.\n */\nexport class SelectEvent extends Event {\n  /**\n   * @param {SelectEventType} type The event type.\n   * @param {Array<import(\"../Feature.js\").default>} selected Selected features.\n   * @param {Array<import(\"../Feature.js\").default>} deselected Deselected features.\n   * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Associated\n   *     {@link module:ol/MapBrowserEvent~MapBrowserEvent}.\n   */\n  constructor(type, selected, deselected, mapBrowserEvent) {\n    super(type);\n\n    /**\n     * Selected features array.\n     * @type {Array<import(\"../Feature.js\").default>}\n     * @api\n     */\n    this.selected = selected;\n\n    /**\n     * Deselected features array.\n     * @type {Array<import(\"../Feature.js\").default>}\n     * @api\n     */\n    this.deselected = deselected;\n\n    /**\n     * Associated {@link module:ol/MapBrowserEvent~MapBrowserEvent}.\n     * @type {import(\"../MapBrowserEvent.js\").default}\n     * @api\n     */\n    this.mapBrowserEvent = mapBrowserEvent;\n  }\n}\n\n/**\n * Original feature styles to reset to when features are no longer selected.\n * @type {Object<number, import(\"../style/Style.js\").default|Array<import(\"../style/Style.js\").default>|import(\"../style/Style.js\").StyleFunction>}\n */\nconst originalFeatureStyles = {};\n\n/***\n * @template Return\n * @typedef {import(\"../Observable.js\").OnSignature<import(\"../Observable.js\").EventTypes, import(\"../events/Event.js\").default, Return> &\n *   import(\"../Observable.js\").OnSignature<import(\"../ObjectEventType.js\").Types|\n *     'change:active', import(\"../Object.js\").ObjectEvent, Return> &\n *   import(\"../Observable.js\").OnSignature<'select', SelectEvent, Return> &\n *   import(\"../Observable.js\").CombinedOnSignature<import(\"../Observable.js\").EventTypes|import(\"../ObjectEventType.js\").Types|\n *     'change:active'|'select', Return>} SelectOnSignature\n */\n\n/**\n * @classdesc\n * Interaction for selecting vector features. By default, selected features are\n * styled differently, so this interaction can be used for visual highlighting,\n * as well as selecting features for other actions, such as modification or\n * output. There are three ways of controlling which features are selected:\n * using the browser event as defined by the `condition` and optionally the\n * `toggle`, `add`/`remove`, and `multi` options; a `layers` filter; and a\n * further feature filter using the `filter` option.\n *\n * @fires SelectEvent\n * @api\n */\nclass Select extends Interaction {\n  /**\n   * @param {Options} [options] Options.\n   */\n  constructor(options) {\n    super();\n\n    /***\n     * @type {SelectOnSignature<import(\"../events.js\").EventsKey>}\n     */\n    this.on;\n\n    /***\n     * @type {SelectOnSignature<import(\"../events.js\").EventsKey>}\n     */\n    this.once;\n\n    /***\n     * @type {SelectOnSignature<void>}\n     */\n    this.un;\n\n    options = options ? options : {};\n\n    /**\n     * @private\n     */\n    this.boundAddFeature_ = this.addFeature_.bind(this);\n\n    /**\n     * @private\n     */\n    this.boundRemoveFeature_ = this.removeFeature_.bind(this);\n\n    /**\n     * @private\n     * @type {import(\"../events/condition.js\").Condition}\n     */\n    this.condition_ = options.condition ? options.condition : singleClick;\n\n    /**\n     * @private\n     * @type {import(\"../events/condition.js\").Condition}\n     */\n    this.addCondition_ = options.addCondition ? options.addCondition : never;\n\n    /**\n     * @private\n     * @type {import(\"../events/condition.js\").Condition}\n     */\n    this.removeCondition_ = options.removeCondition\n      ? options.removeCondition\n      : never;\n\n    /**\n     * @private\n     * @type {import(\"../events/condition.js\").Condition}\n     */\n    this.toggleCondition_ = options.toggleCondition\n      ? options.toggleCondition\n      : shiftKeyOnly;\n\n    /**\n     * @private\n     * @type {boolean}\n     */\n    this.multi_ = options.multi ? options.multi : false;\n\n    /**\n     * @private\n     * @type {FilterFunction}\n     */\n    this.filter_ = options.filter ? options.filter : TRUE;\n\n    /**\n     * @private\n     * @type {number}\n     */\n    this.hitTolerance_ = options.hitTolerance ? options.hitTolerance : 0;\n\n    /**\n     * @private\n     * @type {import(\"../style/Style.js\").default|Array<import(\"../style/Style.js\").default>|import(\"../style/Style.js\").StyleFunction|null}\n     */\n    this.style_ =\n      options.style !== undefined ? options.style : getDefaultStyleFunction();\n\n    /**\n     * @private\n     * @type {Collection<Feature>}\n     */\n    this.features_ = options.features || new Collection();\n\n    /** @type {function(import(\"../layer/Layer.js\").default<import(\"../source/Source.js\").default>): boolean} */\n    let layerFilter;\n    if (options.layers) {\n      if (typeof options.layers === 'function') {\n        layerFilter = options.layers;\n      } else {\n        const layers = options.layers;\n        layerFilter = function (layer) {\n          return layers.includes(layer);\n        };\n      }\n    } else {\n      layerFilter = TRUE;\n    }\n\n    /**\n     * @private\n     * @type {function(import(\"../layer/Layer.js\").default<import(\"../source/Source.js\").default>): boolean}\n     */\n    this.layerFilter_ = layerFilter;\n\n    /**\n     * An association between selected feature (key)\n     * and layer (value)\n     * @private\n     * @type {Object<string, import(\"../layer/Layer.js\").default>}\n     */\n    this.featureLayerAssociation_ = {};\n  }\n\n  /**\n   * @param {import(\"../Feature.js\").default} feature Feature.\n   * @param {import(\"../layer/Layer.js\").default} layer Layer.\n   * @private\n   */\n  addFeatureLayerAssociation_(feature, layer) {\n    this.featureLayerAssociation_[getUid(feature)] = layer;\n  }\n\n  /**\n   * Get the selected features.\n   * @return {Collection<Feature>} Features collection.\n   * @api\n   */\n  getFeatures() {\n    return this.features_;\n  }\n\n  /**\n   * Returns the Hit-detection tolerance.\n   * @return {number} Hit tolerance in pixels.\n   * @api\n   */\n  getHitTolerance() {\n    return this.hitTolerance_;\n  }\n\n  /**\n   * Returns the associated {@link module:ol/layer/Vector~VectorLayer vector layer} of\n   * a selected feature.\n   * @param {import(\"../Feature.js\").default} feature Feature\n   * @return {import('../layer/Vector.js').default} Layer.\n   * @api\n   */\n  getLayer(feature) {\n    return /** @type {import('../layer/Vector.js').default} */ (\n      this.featureLayerAssociation_[getUid(feature)]\n    );\n  }\n\n  /**\n   * Hit-detection tolerance. Pixels inside the radius around the given position\n   * will be checked for features.\n   * @param {number} hitTolerance Hit tolerance in pixels.\n   * @api\n   */\n  setHitTolerance(hitTolerance) {\n    this.hitTolerance_ = hitTolerance;\n  }\n\n  /**\n   * Remove the interaction from its current map, if any,  and attach it to a new\n   * map, if any. Pass `null` to just remove the interaction from the current map.\n   * @param {import(\"../Map.js\").default|null} map Map.\n   * @api\n   * @override\n   */\n  setMap(map) {\n    const currentMap = this.getMap();\n    if (currentMap && this.style_) {\n      this.features_.forEach(this.restorePreviousStyle_.bind(this));\n    }\n    super.setMap(map);\n    if (map) {\n      this.features_.addEventListener(\n        CollectionEventType.ADD,\n        this.boundAddFeature_,\n      );\n      this.features_.addEventListener(\n        CollectionEventType.REMOVE,\n        this.boundRemoveFeature_,\n      );\n\n      if (this.style_) {\n        this.features_.forEach(this.applySelectedStyle_.bind(this));\n      }\n    } else {\n      this.features_.removeEventListener(\n        CollectionEventType.ADD,\n        this.boundAddFeature_,\n      );\n      this.features_.removeEventListener(\n        CollectionEventType.REMOVE,\n        this.boundRemoveFeature_,\n      );\n    }\n  }\n\n  /**\n   * @param {import(\"../Collection.js\").CollectionEvent<Feature>} evt Event.\n   * @private\n   */\n  addFeature_(evt) {\n    const feature = evt.element;\n    if (this.style_) {\n      this.applySelectedStyle_(feature);\n    }\n    if (!this.getLayer(feature)) {\n      const layer = this.findLayerOfFeature_(feature);\n      if (layer) {\n        this.addFeatureLayerAssociation_(feature, layer);\n      }\n    }\n  }\n\n  /**\n   * @param {import(\"../Collection.js\").CollectionEvent<Feature>} evt Event.\n   * @private\n   */\n  removeFeature_(evt) {\n    if (this.style_) {\n      this.restorePreviousStyle_(evt.element);\n    }\n    this.removeFeatureLayerAssociation_(evt.element);\n  }\n\n  /**\n   * @param {Feature} feature Feature of which to get the layer\n   * @return {VectorLayer} layer, if one was found.\n   * @private\n   */\n  findLayerOfFeature_(feature) {\n    const layer = /** @type {VectorLayer} */ (\n      this.getMap()\n        .getAllLayers()\n        .find(function (layer) {\n          if (\n            layer instanceof VectorLayer &&\n            layer.getSource() &&\n            layer.getSource().hasFeature(feature)\n          ) {\n            return layer;\n          }\n        })\n    );\n    return layer;\n  }\n\n  /**\n   * @return {import(\"../style/Style.js\").StyleLike|null} Select style.\n   */\n  getStyle() {\n    return this.style_;\n  }\n\n  /**\n   * @param {Feature} feature Feature\n   * @private\n   */\n  applySelectedStyle_(feature) {\n    const key = getUid(feature);\n    if (!(key in originalFeatureStyles)) {\n      originalFeatureStyles[key] = feature.getStyle();\n    }\n    feature.setStyle(this.style_);\n  }\n\n  /**\n   * @param {Feature} feature Feature\n   * @private\n   */\n  restorePreviousStyle_(feature) {\n    const interactions = this.getMap().getInteractions().getArray();\n    for (let i = interactions.length - 1; i >= 0; --i) {\n      const interaction = interactions[i];\n      if (\n        interaction !== this &&\n        interaction instanceof Select &&\n        interaction.getStyle() &&\n        interaction.getFeatures().getArray().lastIndexOf(feature) !== -1\n      ) {\n        feature.setStyle(interaction.getStyle());\n        return;\n      }\n    }\n\n    const key = getUid(feature);\n    feature.setStyle(originalFeatureStyles[key]);\n    delete originalFeatureStyles[key];\n  }\n\n  /**\n   * @param {Feature} feature Feature.\n   * @private\n   */\n  removeFeatureLayerAssociation_(feature) {\n    delete this.featureLayerAssociation_[getUid(feature)];\n  }\n\n  /**\n   * Try to select a feature as if it was clicked and `addCondition` evaluated to True.\n   * Unlike modifying `select.getFeatures()` directly, this respects the `filter` and `layers` options (except `multi`, which is ignored).\n   * The {@link module:ol/interaction/Select~SelectEvent} fired by this won't have a mapBrowserEvent property\n   * @param {Feature} feature The feature to select\n   * @return {boolean} True if the feature was selected\n   * @api\n   */\n  selectFeature(feature) {\n    const layer = this.findLayerOfFeature_(feature);\n    if (!this.layerFilter_(layer) || !this.filter_(feature, layer)) {\n      return false;\n    }\n    const features = this.getFeatures();\n    if (features.getArray().includes(feature)) {\n      return false;\n    }\n    this.addFeatureLayerAssociation_(feature, layer);\n    features.push(feature);\n    this.dispatchEvent(\n      new SelectEvent(SelectEventType.SELECT, [feature], [], undefined),\n    );\n    return true;\n  }\n\n  /**\n   * Try to deselect a feature as if it was clicked.\n   * Compared to `select.getFeatures().remove(feature)` this causes a SelectEvent.\n   * The {@link module:ol/interaction/Select~SelectEvent} fired by this won't have a mapBrowserEvent property\n   * @param {Feature} feature The feature to deselect\n   * @return {boolean} True if the feature was deselected\n   * @api\n   */\n  deselectFeature(feature) {\n    const features = this.getFeatures();\n    const index = features.getArray().indexOf(feature);\n    if (index === -1) {\n      return false;\n    }\n    features.removeAt(index);\n    this.dispatchEvent(\n      new SelectEvent(SelectEventType.SELECT, [], [feature], undefined),\n    );\n    return true;\n  }\n\n  /**\n   * Try to toggle a feature as if it was clicked and `toggleCondition` was True.\n   * Unlike modifying `select.getFeatures()` directly, this respects the `filter` and `layers` options (except `multi`, which is ignored).\n   * The {@link module:ol/interaction/Select~SelectEvent} fired by this won't have a mapBrowserEvent property\n   * @param {Feature} feature The feature to deselect\n   * @api\n   */\n  toggleFeature(feature) {\n    if (!this.deselectFeature(feature)) {\n      this.selectFeature(feature);\n    }\n  }\n\n  /**\n   * Deselect all features as if a user deselected them.\n   * Compared to `select.getFeatures().clear()` this causes a SelectEvent.\n   * The {@link module:ol/interaction/Select~SelectEvent} fired by this won't have a mapBrowserEvent property\n   * @api\n   */\n  clearSelection() {\n    const features = this.getFeatures();\n    if (features.getLength() !== 0) {\n      const deselected = features.getArray().slice(); // shallow copy\n      features.clear();\n      this.dispatchEvent(\n        new SelectEvent(SelectEventType.SELECT, [], deselected, undefined),\n      );\n    }\n  }\n\n  /**\n   * Handles the {@link module:ol/MapBrowserEvent~MapBrowserEvent map browser event} and may change the\n   * selected state of features.\n   * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Map browser event.\n   * @return {boolean} `false` to stop event propagation.\n   * @override\n   */\n  handleEvent(mapBrowserEvent) {\n    if (!this.condition_(mapBrowserEvent)) {\n      return true;\n    }\n    const add = this.addCondition_(mapBrowserEvent);\n    const remove = this.removeCondition_(mapBrowserEvent);\n    const toggle = this.toggleCondition_(mapBrowserEvent);\n    const set = !add && !remove && !toggle;\n    const map = mapBrowserEvent.map;\n    const features = this.getFeatures();\n\n    /**\n     * @type {Array<Feature>}\n     */\n    const deselected = [];\n\n    /**\n     * @type {Array<Feature>}\n     */\n    const selected = [];\n\n    if (set) {\n      // Replace the currently selected feature(s) with the feature(s) at the\n      // pixel, or clear the selected feature(s) if there is no feature at\n      // the pixel.\n      map.forEachFeatureAtPixel(\n        mapBrowserEvent.pixel,\n        (feature, layer) => {\n          if (!(feature instanceof Feature) || !this.filter_(feature, layer)) {\n            return;\n          }\n          this.addFeatureLayerAssociation_(feature, layer);\n          selected.push(feature);\n          return !this.multi_;\n        },\n        {\n          layerFilter: this.layerFilter_,\n          hitTolerance: this.hitTolerance_,\n        },\n      );\n\n      for (let i = features.getLength() - 1; i >= 0; --i) {\n        const feature = features.item(i);\n        const index = selected.indexOf(feature);\n        if (index === -1) {\n          features.removeAt(i);\n          deselected.push(feature);\n        } else {\n          // feature is already selected\n          selected.splice(index, 1);\n        }\n      }\n      if (selected.length !== 0) {\n        features.extend(selected);\n      }\n    } else {\n      // Modify the currently selected feature(s).\n      map.forEachFeatureAtPixel(\n        mapBrowserEvent.pixel,\n        (feature, layer) => {\n          if (!(feature instanceof Feature) || !this.filter_(feature, layer)) {\n            return;\n          }\n          const hasFeature = features.getArray().includes(feature);\n          if (hasFeature && (remove || toggle)) {\n            deselected.push(feature);\n          } else if (!hasFeature && (add || toggle)) {\n            this.addFeatureLayerAssociation_(feature, layer);\n            selected.push(feature);\n          }\n          return !this.multi_; // stop if not multi\n        },\n        {\n          layerFilter: this.layerFilter_,\n          hitTolerance: this.hitTolerance_,\n        },\n      );\n      for (let j = deselected.length - 1; j >= 0; --j) {\n        features.remove(deselected[j]);\n      }\n      features.extend(selected);\n    }\n    if (selected.length > 0 || deselected.length > 0) {\n      this.dispatchEvent(\n        new SelectEvent(\n          SelectEventType.SELECT,\n          selected,\n          deselected,\n          mapBrowserEvent,\n        ),\n      );\n    }\n    return true;\n  }\n}\n\n/**\n * @return {import(\"../style/Style.js\").StyleFunction} Styles.\n */\nfunction getDefaultStyleFunction() {\n  const styles = createEditingStyle();\n  extend(styles['Polygon'], styles['LineString']);\n  extend(styles['GeometryCollection'], styles['LineString']);\n\n  return function (feature) {\n    if (!feature.getGeometry()) {\n      return null;\n    }\n    return styles[feature.getGeometry().getType()];\n  };\n}\n\nexport default Select;\n", "/**\n * @module ol/format/Feature\n */\nimport Feature from '../Feature.js';\nimport GeometryCollection from '../geom/GeometryCollection.js';\nimport LineString from '../geom/LineString.js';\nimport MultiLineString from '../geom/MultiLineString.js';\nimport MultiPoint from '../geom/MultiPoint.js';\nimport MultiPolygon from '../geom/MultiPolygon.js';\nimport Point from '../geom/Point.js';\nimport Polygon from '../geom/Polygon.js';\nimport {\n  linearRingsAreOriented,\n  linearRingssAreOriented,\n  orientLinearRings,\n  orientLinearRingsArray,\n} from '../geom/flat/orient.js';\nimport {\n  equivalent as equivalentProjection,\n  get as getProjection,\n  getTransform,\n  transformExtent,\n} from '../proj.js';\nimport RenderFeature from '../render/Feature.js';\nimport {abstract} from '../util.js';\n\n/**\n * @typedef {Object} ReadOptions\n * @property {import(\"../proj.js\").ProjectionLike} [dataProjection] Projection of the data we are reading.\n * If not provided, the projection will be derived from the data (where possible) or\n * the `dataProjection` of the format is assigned (where set). If the projection\n * can not be derived from the data and if no `dataProjection` is set for a format,\n * the features will not be reprojected.\n * @property {import(\"../extent.js\").Extent} [extent] Tile extent in map units of the tile being read.\n * This is only required when reading data with tile pixels as geometry units. When configured,\n * a `dataProjection` with `TILE_PIXELS` as `units` and the tile's pixel extent as `extent` needs to be\n * provided.\n * @property {import(\"../proj.js\").ProjectionLike} [featureProjection] Projection of the feature geometries\n * created by the format reader. If not provided, features will be returned in the\n * `dataProjection`.\n */\n\n/**\n * @typedef {Object} WriteOptions\n * @property {import(\"../proj.js\").ProjectionLike} [dataProjection] Projection of the data we are writing.\n * If not provided, the `dataProjection` of the format is assigned (where set).\n * If no `dataProjection` is set for a format, the features will be returned\n * in the `featureProjection`.\n * @property {import(\"../proj.js\").ProjectionLike} [featureProjection] Projection of the feature geometries\n * that will be serialized by the format writer. If not provided, geometries are assumed\n * to be in the `dataProjection` if that is set; in other words, they are not transformed.\n * @property {boolean} [rightHanded] When writing geometries, follow the right-hand\n * rule for linear ring orientation.  This means that polygons will have counter-clockwise\n * exterior rings and clockwise interior rings.  By default, coordinates are serialized\n * as they are provided at construction.  If `true`, the right-hand rule will\n * be applied.  If `false`, the left-hand rule will be applied (clockwise for\n * exterior and counter-clockwise for interior rings).  Note that not all\n * formats support this.  The GeoJSON format does use this property when writing\n * geometries.\n * @property {number} [decimals] Maximum number of decimal places for coordinates.\n * Coordinates are stored internally as floats, but floating-point arithmetic can create\n * coordinates with a large number of decimal places, not generally wanted on output.\n * Set a number here to round coordinates. Can also be used to ensure that\n * coordinates read in can be written back out with the same number of decimals.\n * Default is no rounding.\n */\n\n/**\n * @typedef {'arraybuffer' | 'json' | 'text' | 'xml'} Type\n */\n\n/**\n * @typedef {Object} SimpleGeometryObject\n * @property {import('../geom/Geometry.js').Type} type Type.\n * @property {Array<number>} flatCoordinates Flat coordinates.\n * @property {Array<number>|Array<Array<number>>} [ends] Ends or endss.\n * @property {import('../geom/Geometry.js').GeometryLayout} [layout] Layout.\n */\n\n/**\n * @typedef {Array<GeometryObject>} GeometryCollectionObject\n */\n\n/**\n * @typedef {SimpleGeometryObject|GeometryCollectionObject} GeometryObject\n */\n\n/**\n * @typedef {Object} FeatureObject\n * @property {string|number} [id] Id.\n * @property {GeometryObject} [geometry] Geometry.\n * @property {Object<string, *>} [properties] Properties.\n */\n\n/***\n * @template {import('../Feature.js').FeatureLike} T\n * @typedef {T extends RenderFeature ? typeof RenderFeature : typeof Feature} FeatureToFeatureClass\n */\n\n/***\n * @template {import(\"../Feature.js\").FeatureClass} T\n * @typedef {T[keyof T] extends RenderFeature ? RenderFeature : Feature} FeatureClassToFeature\n */\n\n/**\n * @classdesc\n * Abstract base class; normally only used for creating subclasses and not\n * instantiated in apps.\n * Base class for feature formats.\n * {@link module:ol/format/Feature~FeatureFormat} subclasses provide the ability to decode and encode\n * {@link module:ol/Feature~Feature} objects from a variety of commonly used geospatial\n * file formats.  See the documentation for each format for more details.\n *\n * @template {import('../Feature.js').FeatureLike} [FeatureType=import(\"../Feature.js\").default]\n * @abstract\n * @api\n */\nclass FeatureFormat {\n  constructor() {\n    /**\n     * @protected\n     * @type {import(\"../proj/Projection.js\").default|undefined}\n     */\n    this.dataProjection = undefined;\n\n    /**\n     * @protected\n     * @type {import(\"../proj/Projection.js\").default|undefined}\n     */\n    this.defaultFeatureProjection = undefined;\n\n    /**\n     * @protected\n     * @type {FeatureToFeatureClass<FeatureType>}\n     */\n    this.featureClass = /** @type {FeatureToFeatureClass<FeatureType>} */ (\n      Feature\n    );\n\n    /**\n     * A list media types supported by the format in descending order of preference.\n     * @type {Array<string>}\n     */\n    this.supportedMediaTypes = null;\n  }\n\n  /**\n   * Adds the data projection to the read options.\n   * @param {Document|Element|Object|string} source Source.\n   * @param {ReadOptions} [options] Options.\n   * @return {ReadOptions|undefined} Options.\n   * @protected\n   */\n  getReadOptions(source, options) {\n    if (options) {\n      let dataProjection = options.dataProjection\n        ? getProjection(options.dataProjection)\n        : this.readProjection(source);\n      if (\n        options.extent &&\n        dataProjection &&\n        dataProjection.getUnits() === 'tile-pixels'\n      ) {\n        dataProjection = getProjection(dataProjection);\n        dataProjection.setWorldExtent(options.extent);\n      }\n      options = {\n        dataProjection: dataProjection,\n        featureProjection: options.featureProjection,\n      };\n    }\n    return this.adaptOptions(options);\n  }\n\n  /**\n   * Sets the `dataProjection` on the options, if no `dataProjection`\n   * is set.\n   * @param {WriteOptions|ReadOptions|undefined} options\n   *     Options.\n   * @protected\n   * @return {WriteOptions|ReadOptions|undefined}\n   *     Updated options.\n   */\n  adaptOptions(options) {\n    return Object.assign(\n      {\n        dataProjection: this.dataProjection,\n        featureProjection: this.defaultFeatureProjection,\n        featureClass: this.featureClass,\n      },\n      options,\n    );\n  }\n\n  /**\n   * @abstract\n   * @return {Type} The format type.\n   */\n  getType() {\n    return abstract();\n  }\n\n  /**\n   * Read a single feature from a source.\n   *\n   * @abstract\n   * @param {Document|Element|Object|string} source Source.\n   * @param {ReadOptions} [options] Read options.\n   * @return {FeatureType|Array<FeatureType>} Feature.\n   */\n  readFeature(source, options) {\n    return abstract();\n  }\n\n  /**\n   * Read all features from a source.\n   *\n   * @abstract\n   * @param {Document|Element|ArrayBuffer|Object|string} source Source.\n   * @param {ReadOptions} [options] Read options.\n   * @return {Array<FeatureType>} Features.\n   */\n  readFeatures(source, options) {\n    return abstract();\n  }\n\n  /**\n   * Read a single geometry from a source.\n   *\n   * @abstract\n   * @param {Document|Element|Object|string} source Source.\n   * @param {ReadOptions} [options] Read options.\n   * @return {import(\"../geom/Geometry.js\").default} Geometry.\n   */\n  readGeometry(source, options) {\n    return abstract();\n  }\n\n  /**\n   * Read the projection from a source.\n   *\n   * @abstract\n   * @param {Document|Element|Object|string} source Source.\n   * @return {import(\"../proj/Projection.js\").default|undefined} Projection.\n   */\n  readProjection(source) {\n    return abstract();\n  }\n\n  /**\n   * Encode a feature in this format.\n   *\n   * @abstract\n   * @param {Feature} feature Feature.\n   * @param {WriteOptions} [options] Write options.\n   * @return {string|ArrayBuffer} Result.\n   */\n  writeFeature(feature, options) {\n    return abstract();\n  }\n\n  /**\n   * Encode an array of features in this format.\n   *\n   * @abstract\n   * @param {Array<Feature>} features Features.\n   * @param {WriteOptions} [options] Write options.\n   * @return {string|ArrayBuffer} Result.\n   */\n  writeFeatures(features, options) {\n    return abstract();\n  }\n\n  /**\n   * Write a single geometry in this format.\n   *\n   * @abstract\n   * @param {import(\"../geom/Geometry.js\").default} geometry Geometry.\n   * @param {WriteOptions} [options] Write options.\n   * @return {string|ArrayBuffer} Result.\n   */\n  writeGeometry(geometry, options) {\n    return abstract();\n  }\n}\n\nexport default FeatureFormat;\n\n/**\n * @template {import(\"../geom/Geometry.js\").default|RenderFeature} T\n * @param {T} geometry Geometry.\n * @param {boolean} write Set to true for writing, false for reading.\n * @param {WriteOptions|ReadOptions} [options] Options.\n * @return {T} Transformed geometry.\n */\nexport function transformGeometryWithOptions(geometry, write, options) {\n  const featureProjection = options\n    ? getProjection(options.featureProjection)\n    : null;\n  const dataProjection = options ? getProjection(options.dataProjection) : null;\n\n  let transformed = geometry;\n  if (\n    featureProjection &&\n    dataProjection &&\n    !equivalentProjection(featureProjection, dataProjection)\n  ) {\n    if (write) {\n      transformed = /** @type {T} */ (geometry.clone());\n    }\n    const fromProjection = write ? featureProjection : dataProjection;\n    const toProjection = write ? dataProjection : featureProjection;\n    if (fromProjection.getUnits() === 'tile-pixels') {\n      transformed.transform(fromProjection, toProjection);\n    } else {\n      transformed.applyTransform(getTransform(fromProjection, toProjection));\n    }\n  }\n  if (\n    write &&\n    options &&\n    /** @type {WriteOptions} */ (options).decimals !== undefined\n  ) {\n    const power = Math.pow(10, /** @type {WriteOptions} */ (options).decimals);\n    // if decimals option on write, round each coordinate appropriately\n    /**\n     * @param {Array<number>} coordinates Coordinates.\n     * @return {Array<number>} Transformed coordinates.\n     */\n    const transform = function (coordinates) {\n      for (let i = 0, ii = coordinates.length; i < ii; ++i) {\n        coordinates[i] = Math.round(coordinates[i] * power) / power;\n      }\n      return coordinates;\n    };\n    if (transformed === geometry) {\n      transformed = /** @type {T} */ (geometry.clone());\n    }\n    transformed.applyTransform(transform);\n  }\n  return transformed;\n}\n\n/**\n * @param {import(\"../extent.js\").Extent} extent Extent.\n * @param {ReadOptions} [options] Read options.\n * @return {import(\"../extent.js\").Extent} Transformed extent.\n */\nexport function transformExtentWithOptions(extent, options) {\n  const featureProjection = options\n    ? getProjection(options.featureProjection)\n    : null;\n  const dataProjection = options ? getProjection(options.dataProjection) : null;\n\n  if (\n    featureProjection &&\n    dataProjection &&\n    !equivalentProjection(featureProjection, dataProjection)\n  ) {\n    return transformExtent(extent, dataProjection, featureProjection);\n  }\n  return extent;\n}\n\nconst GeometryConstructor = {\n  Point: Point,\n  LineString: LineString,\n  Polygon: Polygon,\n  MultiPoint: MultiPoint,\n  MultiLineString: MultiLineString,\n  MultiPolygon: MultiPolygon,\n};\n\nfunction orientFlatCoordinates(flatCoordinates, ends, stride) {\n  if (Array.isArray(ends[0])) {\n    // MultiPolagon\n    if (!linearRingssAreOriented(flatCoordinates, 0, ends, stride)) {\n      flatCoordinates = flatCoordinates.slice();\n      orientLinearRingsArray(flatCoordinates, 0, ends, stride);\n    }\n    return flatCoordinates;\n  }\n  if (!linearRingsAreOriented(flatCoordinates, 0, ends, stride)) {\n    flatCoordinates = flatCoordinates.slice();\n    orientLinearRings(flatCoordinates, 0, ends, stride);\n  }\n  return flatCoordinates;\n}\n\n/**\n * @param {FeatureObject} object Feature object.\n * @param {WriteOptions|ReadOptions} [options] Options.\n * @return {RenderFeature|Array<RenderFeature>} Render feature.\n */\nexport function createRenderFeature(object, options) {\n  const geometry = object.geometry;\n  if (!geometry) {\n    return [];\n  }\n  if (Array.isArray(geometry)) {\n    return geometry\n      .map((geometry) => createRenderFeature({...object, geometry}))\n      .flat();\n  }\n\n  const geometryType =\n    geometry.type === 'MultiPolygon' ? 'Polygon' : geometry.type;\n  if (geometryType === 'GeometryCollection' || geometryType === 'Circle') {\n    throw new Error('Unsupported geometry type: ' + geometryType);\n  }\n\n  const stride = geometry.layout.length;\n  return transformGeometryWithOptions(\n    new RenderFeature(\n      geometryType,\n      geometryType === 'Polygon'\n        ? orientFlatCoordinates(geometry.flatCoordinates, geometry.ends, stride)\n        : geometry.flatCoordinates,\n      geometry.ends?.flat(),\n      stride,\n      object.properties || {},\n      object.id,\n    ).enableSimplifyTransformed(),\n    false,\n    options,\n  );\n}\n\n/**\n * @param {GeometryObject|null} object Geometry object.\n * @param {WriteOptions|ReadOptions} [options] Options.\n * @return {import(\"../geom/Geometry.js\").default} Geometry.\n */\nexport function createGeometry(object, options) {\n  if (!object) {\n    return null;\n  }\n  if (Array.isArray(object)) {\n    const geometries = object.map((geometry) =>\n      createGeometry(geometry, options),\n    );\n    return new GeometryCollection(geometries);\n  }\n  const Geometry = GeometryConstructor[object.type];\n  return transformGeometryWithOptions(\n    new Geometry(object.flatCoordinates, object.layout || 'XY', object.ends),\n    false,\n    options,\n  );\n}\n", "/**\n * @module ol/format/JSONFeature\n */\nimport {abstract} from '../util.js';\nimport FeatureFormat from './Feature.js';\n\n/**\n * @classdesc\n * Abstract base class; normally only used for creating subclasses and not\n * instantiated in apps.\n * Base class for JSON feature formats.\n *\n * @template {import('../Feature.js').FeatureLike} [FeatureType=import(\"../Feature.js\").default]\n * @extends {FeatureFormat<FeatureType>}\n * @abstract\n */\nclass JSONFeature extends FeatureFormat {\n  constructor() {\n    super();\n  }\n\n  /**\n   * @return {import(\"./Feature.js\").Type} Format.\n   * @override\n   */\n  getType() {\n    return 'json';\n  }\n\n  /**\n   * Read a feature.  Only works for a single feature. Use `readFeatures` to\n   * read a feature collection.\n   *\n   * @param {ArrayBuffer|Document|Element|Object|string} source Source.\n   * @param {import(\"./Feature.js\").ReadOptions} [options] Read options.\n   * @return {FeatureType|Array<FeatureType>} Feature.\n   * @api\n   * @override\n   */\n  readFeature(source, options) {\n    return this.readFeatureFromObject(\n      getObject(source),\n      this.getReadOptions(source, options),\n    );\n  }\n\n  /**\n   * Read all features.  Works with both a single feature and a feature\n   * collection.\n   *\n   * @param {ArrayBuffer|Document|Element|Object|string} source Source.\n   * @param {import(\"./Feature.js\").ReadOptions} [options] Read options.\n   * @return {Array<FeatureType>} Features.\n   * @api\n   * @override\n   */\n  readFeatures(source, options) {\n    return this.readFeaturesFromObject(\n      getObject(source),\n      this.getReadOptions(source, options),\n    );\n  }\n\n  /**\n   * @abstract\n   * @param {Object} object Object.\n   * @param {import(\"./Feature.js\").ReadOptions} [options] Read options.\n   * @protected\n   * @return {FeatureType|Array<FeatureType>} Feature.\n   */\n  readFeatureFromObject(object, options) {\n    return abstract();\n  }\n\n  /**\n   * @abstract\n   * @param {Object} object Object.\n   * @param {import(\"./Feature.js\").ReadOptions} [options] Read options.\n   * @protected\n   * @return {Array<FeatureType>} Features.\n   */\n  readFeaturesFromObject(object, options) {\n    return abstract();\n  }\n\n  /**\n   * Read a geometry.\n   *\n   * @param {ArrayBuffer|Document|Element|Object|string} source Source.\n   * @param {import(\"./Feature.js\").ReadOptions} [options] Read options.\n   * @return {import(\"../geom/Geometry.js\").default} Geometry.\n   * @api\n   * @override\n   */\n  readGeometry(source, options) {\n    return this.readGeometryFromObject(\n      getObject(source),\n      this.getReadOptions(source, options),\n    );\n  }\n\n  /**\n   * @abstract\n   * @param {Object} object Object.\n   * @param {import(\"./Feature.js\").ReadOptions} [options] Read options.\n   * @protected\n   * @return {import(\"../geom/Geometry.js\").default} Geometry.\n   */\n  readGeometryFromObject(object, options) {\n    return abstract();\n  }\n\n  /**\n   * Read the projection.\n   *\n   * @param {ArrayBuffer|Document|Element|Object|string} source Source.\n   * @return {import(\"../proj/Projection.js\").default} Projection.\n   * @api\n   * @override\n   */\n  readProjection(source) {\n    return this.readProjectionFromObject(getObject(source));\n  }\n\n  /**\n   * @abstract\n   * @param {Object} object Object.\n   * @protected\n   * @return {import(\"../proj/Projection.js\").default} Projection.\n   */\n  readProjectionFromObject(object) {\n    return abstract();\n  }\n\n  /**\n   * Encode a feature as string.\n   *\n   * @param {import(\"../Feature.js\").default} feature Feature.\n   * @param {import(\"./Feature.js\").WriteOptions} [options] Write options.\n   * @return {string} Encoded feature.\n   * @api\n   * @override\n   */\n  writeFeature(feature, options) {\n    return JSON.stringify(this.writeFeatureObject(feature, options));\n  }\n\n  /**\n   * @abstract\n   * @param {import(\"../Feature.js\").default} feature Feature.\n   * @param {import(\"./Feature.js\").WriteOptions} [options] Write options.\n   * @return {Object} Object.\n   */\n  writeFeatureObject(feature, options) {\n    return abstract();\n  }\n\n  /**\n   * Encode an array of features as string.\n   *\n   * @param {Array<import(\"../Feature.js\").default>} features Features.\n   * @param {import(\"./Feature.js\").WriteOptions} [options] Write options.\n   * @return {string} Encoded features.\n   * @api\n   * @override\n   */\n  writeFeatures(features, options) {\n    return JSON.stringify(this.writeFeaturesObject(features, options));\n  }\n\n  /**\n   * @abstract\n   * @param {Array<import(\"../Feature.js\").default>} features Features.\n   * @param {import(\"./Feature.js\").WriteOptions} [options] Write options.\n   * @return {Object} Object.\n   */\n  writeFeaturesObject(features, options) {\n    return abstract();\n  }\n\n  /**\n   * Encode a geometry as string.\n   *\n   * @param {import(\"../geom/Geometry.js\").default} geometry Geometry.\n   * @param {import(\"./Feature.js\").WriteOptions} [options] Write options.\n   * @return {string} Encoded geometry.\n   * @api\n   * @override\n   */\n  writeGeometry(geometry, options) {\n    return JSON.stringify(this.writeGeometryObject(geometry, options));\n  }\n\n  /**\n   * @abstract\n   * @param {import(\"../geom/Geometry.js\").default} geometry Geometry.\n   * @param {import(\"./Feature.js\").WriteOptions} [options] Write options.\n   * @return {Object} Object.\n   */\n  writeGeometryObject(geometry, options) {\n    return abstract();\n  }\n}\n\n/**\n * @param {Document|Element|Object|string} source Source.\n * @return {Object} Object.\n */\nfunction getObject(source) {\n  if (typeof source === 'string') {\n    const object = JSON.parse(source);\n    return object ? /** @type {Object} */ (object) : null;\n  }\n  if (source !== null) {\n    return source;\n  }\n  return null;\n}\n\nexport default JSONFeature;\n", "/**\n * @module ol/format/GeoJSON\n */\n\nimport Feature from '../Feature.js';\nimport {getLayoutForStride} from '../geom/SimpleGeometry.js';\nimport {\n  deflateCoordinatesArray,\n  deflateMultiCoordinatesArray,\n} from '../geom/flat/deflate.js';\nimport {isEmpty} from '../obj.js';\nimport {get as getProjection} from '../proj.js';\nimport RenderFeature from '../render/Feature.js';\nimport {\n  createGeometry,\n  createRenderFeature,\n  transformGeometryWithOptions,\n} from './Feature.js';\nimport JSONFeature from './JSONFeature.js';\n\n/**\n * @typedef {import(\"geojson\").GeoJSON} GeoJSONObject\n * @typedef {import(\"geojson\").Feature} GeoJSONFeature\n * @typedef {import(\"geojson\").FeatureCollection} GeoJSONFeatureCollection\n * @typedef {import(\"geojson\").Geometry} GeoJSONGeometry\n * @typedef {import(\"geojson\").Point} GeoJSONPoint\n * @typedef {import(\"geojson\").LineString} GeoJSONLineString\n * @typedef {import(\"geojson\").Polygon} GeoJSONPolygon\n * @typedef {import(\"geojson\").MultiPoint} GeoJSONMultiPoint\n * @typedef {import(\"geojson\").MultiLineString} GeoJSONMultiLineString\n * @typedef {import(\"geojson\").MultiPolygon} GeoJSONMultiPolygon\n * @typedef {import(\"geojson\").GeometryCollection} GeoJSONGeometryCollection\n */\n\n/**\n * @template {import(\"../Feature.js\").FeatureLike} [FeatureType=import(\"../Feature.js\").default]\n * @typedef {Object} Options\n *\n * @property {import(\"../proj.js\").ProjectionLike} [dataProjection='EPSG:4326'] Default data projection.\n * @property {import(\"../proj.js\").ProjectionLike} [featureProjection] Projection for features read or\n * written by the format.  Options passed to read or write methods will take precedence.\n * @property {string} [geometryName] Geometry name to use when creating features.\n * @property {boolean} [extractGeometryName=false] Certain GeoJSON providers include\n * the geometry_name field in the feature GeoJSON. If set to `true` the GeoJSON reader\n * will look for that field to set the geometry name. If both this field is set to `true`\n * and a `geometryName` is provided, the `geometryName` will take precedence.\n * @property {import('./Feature.js').FeatureToFeatureClass<FeatureType>} [featureClass] Feature class\n * to be used when reading features. The default is {@link module:ol/Feature~Feature}. If performance is\n * the primary concern, and features are not going to be modified or round-tripped through the format,\n * consider using {@link module:ol/render/Feature~RenderFeature}\n */\n\n/**\n * @classdesc\n * Feature format for reading and writing data in the GeoJSON format.\n *\n * @template {import('../Feature.js').FeatureLike} [FeatureType=import(\"../Feature.js\").default]\n * @extends {JSONFeature<FeatureType>}\n * @api\n */\nclass GeoJSON extends JSONFeature {\n  /**\n   * @param {Options<FeatureType>} [options] Options.\n   */\n  constructor(options) {\n    options = options ? options : {};\n\n    super();\n\n    /**\n     * @type {import(\"../proj/Projection.js\").default}\n     */\n    this.dataProjection = getProjection(\n      options.dataProjection ? options.dataProjection : 'EPSG:4326',\n    );\n\n    if (options.featureProjection) {\n      /**\n       * @type {import(\"../proj/Projection.js\").default}\n       */\n      this.defaultFeatureProjection = getProjection(options.featureProjection);\n    }\n\n    if (options.featureClass) {\n      this.featureClass = options.featureClass;\n    }\n\n    /**\n     * Name of the geometry attribute for features.\n     * @type {string|undefined}\n     * @private\n     */\n    this.geometryName_ = options.geometryName;\n\n    /**\n     * Look for the `geometry_name` in the feature GeoJSON\n     * @type {boolean|undefined}\n     * @private\n     */\n    this.extractGeometryName_ = options.extractGeometryName;\n\n    this.supportedMediaTypes = [\n      'application/geo+json',\n      'application/vnd.geo+json',\n    ];\n  }\n\n  /**\n   * @param {Object} object Object.\n   * @param {import(\"./Feature.js\").ReadOptions} [options] Read options.\n   * @protected\n   * @return {FeatureType|Array<FeatureType>} Feature.\n   * @override\n   */\n  readFeatureFromObject(object, options) {\n    /**\n     * @type {GeoJSONFeature}\n     */\n    let geoJSONFeature = null;\n    if (object['type'] === 'Feature') {\n      geoJSONFeature = /** @type {GeoJSONFeature} */ (object);\n    } else {\n      geoJSONFeature = {\n        'type': 'Feature',\n        'geometry': /** @type {GeoJSONGeometry} */ (object),\n        'properties': null,\n      };\n    }\n\n    const geometry = readGeometryInternal(geoJSONFeature['geometry'], options);\n    if (this.featureClass === RenderFeature) {\n      return /** @type {FeatureType|Array<FeatureType>} */ (\n        createRenderFeature(\n          {\n            geometry,\n            id: geoJSONFeature['id'],\n            properties: geoJSONFeature['properties'],\n          },\n          options,\n        )\n      );\n    }\n\n    const feature = new Feature();\n    if (this.geometryName_) {\n      feature.setGeometryName(this.geometryName_);\n    } else if (this.extractGeometryName_ && geoJSONFeature['geometry_name']) {\n      feature.setGeometryName(geoJSONFeature['geometry_name']);\n    }\n    feature.setGeometry(createGeometry(geometry, options));\n\n    if ('id' in geoJSONFeature) {\n      feature.setId(geoJSONFeature['id']);\n    }\n\n    if (geoJSONFeature['properties']) {\n      feature.setProperties(geoJSONFeature['properties'], true);\n    }\n    return /** @type {FeatureType|Array<FeatureType>} */ (feature);\n  }\n\n  /**\n   * @param {Object} object Object.\n   * @param {import(\"./Feature.js\").ReadOptions} [options] Read options.\n   * @protected\n   * @return {Array<FeatureType>} Features.\n   * @override\n   */\n  readFeaturesFromObject(object, options) {\n    const geoJSONObject = /** @type {GeoJSONObject} */ (object);\n    let features = null;\n    if (geoJSONObject['type'] === 'FeatureCollection') {\n      const geoJSONFeatureCollection = /** @type {GeoJSONFeatureCollection} */ (\n        object\n      );\n      features = [];\n      const geoJSONFeatures = geoJSONFeatureCollection['features'];\n      for (let i = 0, ii = geoJSONFeatures.length; i < ii; ++i) {\n        const featureObject = this.readFeatureFromObject(\n          geoJSONFeatures[i],\n          options,\n        );\n        if (!featureObject) {\n          continue;\n        }\n        features.push(featureObject);\n      }\n    } else {\n      features = [this.readFeatureFromObject(object, options)];\n    }\n    return /** @type {Array<FeatureType>} */ (features.flat());\n  }\n\n  /**\n   * @param {GeoJSONGeometry} object Object.\n   * @param {import(\"./Feature.js\").ReadOptions} [options] Read options.\n   * @protected\n   * @return {import(\"../geom/Geometry.js\").default} Geometry.\n   * @override\n   */\n  readGeometryFromObject(object, options) {\n    return readGeometry(object, options);\n  }\n\n  /**\n   * @param {Object} object Object.\n   * @protected\n   * @return {import(\"../proj/Projection.js\").default} Projection.\n   * @override\n   */\n  readProjectionFromObject(object) {\n    const crs = object['crs'];\n    let projection;\n    if (crs) {\n      if (crs['type'] == 'name') {\n        projection = getProjection(crs['properties']['name']);\n      } else if (crs['type'] === 'EPSG') {\n        projection = getProjection('EPSG:' + crs['properties']['code']);\n      } else {\n        throw new Error('Unknown SRS type');\n      }\n    } else {\n      projection = this.dataProjection;\n    }\n    return /** @type {import(\"../proj/Projection.js\").default} */ (projection);\n  }\n\n  /**\n   * Encode a feature as a GeoJSON Feature object.\n   *\n   * @param {import(\"../Feature.js\").default} feature Feature.\n   * @param {import(\"./Feature.js\").WriteOptions} [options] Write options.\n   * @return {GeoJSONFeature} Object.\n   * @api\n   * @override\n   */\n  writeFeatureObject(feature, options) {\n    options = this.adaptOptions(options);\n\n    /** @type {GeoJSONFeature} */\n    const object = {\n      'type': 'Feature',\n      geometry: null,\n      properties: null,\n    };\n\n    const id = feature.getId();\n    if (id !== undefined) {\n      object.id = id;\n    }\n\n    if (!feature.hasProperties()) {\n      return object;\n    }\n\n    const properties = feature.getProperties();\n    const geometry = feature.getGeometry();\n    if (geometry) {\n      object.geometry = writeGeometry(geometry, options);\n\n      delete properties[feature.getGeometryName()];\n    }\n\n    if (!isEmpty(properties)) {\n      object.properties = properties;\n    }\n\n    return object;\n  }\n\n  /**\n   * Encode an array of features as a GeoJSON object.\n   *\n   * @param {Array<import(\"../Feature.js\").default>} features Features.\n   * @param {import(\"./Feature.js\").WriteOptions} [options] Write options.\n   * @return {GeoJSONFeatureCollection} GeoJSON Object.\n   * @api\n   * @override\n   */\n  writeFeaturesObject(features, options) {\n    options = this.adaptOptions(options);\n    const objects = [];\n    for (let i = 0, ii = features.length; i < ii; ++i) {\n      objects.push(this.writeFeatureObject(features[i], options));\n    }\n    return {\n      type: 'FeatureCollection',\n      features: objects,\n    };\n  }\n\n  /**\n   * Encode a geometry as a GeoJSON object.\n   *\n   * @param {import(\"../geom/Geometry.js\").default} geometry Geometry.\n   * @param {import(\"./Feature.js\").WriteOptions} [options] Write options.\n   * @return {GeoJSONGeometry|GeoJSONGeometryCollection} Object.\n   * @api\n   * @override\n   */\n  writeGeometryObject(geometry, options) {\n    return writeGeometry(geometry, this.adaptOptions(options));\n  }\n}\n\n/**\n * @param {GeoJSONGeometry|GeoJSONGeometryCollection} object Object.\n * @param {import(\"./Feature.js\").ReadOptions} [options] Read options.\n * @return {import(\"./Feature.js\").GeometryObject} Geometry.\n */\nfunction readGeometryInternal(object, options) {\n  if (!object) {\n    return null;\n  }\n\n  /** @type {import(\"./Feature.js\").GeometryObject} */\n  let geometry;\n  switch (object['type']) {\n    case 'Point': {\n      geometry = readPointGeometry(/** @type {GeoJSONPoint} */ (object));\n      break;\n    }\n    case 'LineString': {\n      geometry = readLineStringGeometry(\n        /** @type {GeoJSONLineString} */ (object),\n      );\n      break;\n    }\n    case 'Polygon': {\n      geometry = readPolygonGeometry(/** @type {GeoJSONPolygon} */ (object));\n      break;\n    }\n    case 'MultiPoint': {\n      geometry = readMultiPointGeometry(\n        /** @type {GeoJSONMultiPoint} */ (object),\n      );\n      break;\n    }\n    case 'MultiLineString': {\n      geometry = readMultiLineStringGeometry(\n        /** @type {GeoJSONMultiLineString} */ (object),\n      );\n      break;\n    }\n    case 'MultiPolygon': {\n      geometry = readMultiPolygonGeometry(\n        /** @type {GeoJSONMultiPolygon} */ (object),\n      );\n      break;\n    }\n    case 'GeometryCollection': {\n      geometry = readGeometryCollectionGeometry(\n        /** @type {GeoJSONGeometryCollection} */ (object),\n      );\n      break;\n    }\n    default: {\n      throw new Error('Unsupported GeoJSON type: ' + object['type']);\n    }\n  }\n  return geometry;\n}\n\n/**\n * @param {GeoJSONGeometry|GeoJSONGeometryCollection} object Object.\n * @param {import(\"./Feature.js\").ReadOptions} [options] Read options.\n * @return {import(\"../geom/Geometry.js\").default} Geometry.\n */\nfunction readGeometry(object, options) {\n  const geometryObject = readGeometryInternal(object, options);\n  return createGeometry(geometryObject, options);\n}\n\n/**\n * @param {GeoJSONGeometryCollection} object Object.\n * @param {import(\"./Feature.js\").ReadOptions} [options] Read options.\n * @return {import(\"./Feature.js\").GeometryCollectionObject} Geometry collection.\n */\nfunction readGeometryCollectionGeometry(object, options) {\n  const geometries = object['geometries'].map(\n    /**\n     * @param {GeoJSONGeometry} geometry Geometry.\n     * @return {import(\"./Feature.js\").GeometryObject} geometry Geometry.\n     */\n    function (geometry) {\n      return readGeometryInternal(geometry, options);\n    },\n  );\n  return geometries;\n}\n\n/**\n * @param {GeoJSONPoint} object Input object.\n * @return {import(\"./Feature.js\").GeometryObject} Point geometry.\n */\nfunction readPointGeometry(object) {\n  const flatCoordinates = object['coordinates'];\n  return {\n    type: 'Point',\n    flatCoordinates,\n    layout: getLayoutForStride(flatCoordinates.length),\n  };\n}\n\n/**\n * @param {GeoJSONLineString} object Object.\n * @return {import(\"./Feature.js\").GeometryObject} LineString geometry.\n */\nfunction readLineStringGeometry(object) {\n  const coordinates = object['coordinates'];\n  const flatCoordinates = coordinates.flat();\n  return {\n    type: 'LineString',\n    flatCoordinates,\n    ends: [flatCoordinates.length],\n    layout: getLayoutForStride(coordinates[0]?.length || 2),\n  };\n}\n\n/**\n * @param {GeoJSONMultiLineString} object Object.\n * @return {import(\"./Feature.js\").GeometryObject} MultiLineString geometry.\n */\nfunction readMultiLineStringGeometry(object) {\n  const coordinates = object['coordinates'];\n  const stride = coordinates[0]?.[0]?.length || 2;\n  const flatCoordinates = [];\n  const ends = deflateCoordinatesArray(flatCoordinates, 0, coordinates, stride);\n  return {\n    type: 'MultiLineString',\n    flatCoordinates,\n    ends,\n    layout: getLayoutForStride(stride),\n  };\n}\n\n/**\n * @param {GeoJSONMultiPoint} object Object.\n * @return {import(\"./Feature.js\").GeometryObject} MultiPoint geometry.\n */\nfunction readMultiPointGeometry(object) {\n  const coordinates = object['coordinates'];\n  return {\n    type: 'MultiPoint',\n    flatCoordinates: coordinates.flat(),\n    layout: getLayoutForStride(coordinates[0]?.length || 2),\n  };\n}\n\n/**\n * @param {GeoJSONMultiPolygon} object Object.\n * @return {import(\"./Feature.js\").GeometryObject} MultiPolygon geometry.\n */\nfunction readMultiPolygonGeometry(object) {\n  const coordinates = object['coordinates'];\n  const flatCoordinates = [];\n  const stride = coordinates[0]?.[0]?.[0].length || 2;\n  const endss = deflateMultiCoordinatesArray(\n    flatCoordinates,\n    0,\n    coordinates,\n    stride,\n  );\n  return {\n    type: 'MultiPolygon',\n    flatCoordinates,\n    ends: endss,\n    layout: getLayoutForStride(stride),\n  };\n}\n\n/**\n * @param {GeoJSONPolygon} object Object.\n * @return {import(\"./Feature.js\").GeometryObject} Polygon.\n */\nfunction readPolygonGeometry(object) {\n  const coordinates = object['coordinates'];\n  const flatCoordinates = [];\n  const stride = coordinates[0]?.[0]?.length;\n  const ends = deflateCoordinatesArray(flatCoordinates, 0, coordinates, stride);\n  return {\n    type: 'Polygon',\n    flatCoordinates,\n    ends,\n    layout: getLayoutForStride(stride),\n  };\n}\n\n/**\n * @param {import(\"../geom/Geometry.js\").default} geometry Geometry.\n * @param {import(\"./Feature.js\").WriteOptions} [options] Write options.\n * @return {GeoJSONGeometry} GeoJSON geometry.\n */\nfunction writeGeometry(geometry, options) {\n  geometry = transformGeometryWithOptions(geometry, true, options);\n\n  const type = geometry.getType();\n\n  /** @type {GeoJSONGeometry} */\n  let geoJSON;\n  switch (type) {\n    case 'Point': {\n      geoJSON = writePointGeometry(\n        /** @type {import(\"../geom/Point.js\").default} */ (geometry),\n        options,\n      );\n      break;\n    }\n    case 'LineString': {\n      geoJSON = writeLineStringGeometry(\n        /** @type {import(\"../geom/LineString.js\").default} */ (geometry),\n        options,\n      );\n      break;\n    }\n    case 'Polygon': {\n      geoJSON = writePolygonGeometry(\n        /** @type {import(\"../geom/Polygon.js\").default} */ (geometry),\n        options,\n      );\n      break;\n    }\n    case 'MultiPoint': {\n      geoJSON = writeMultiPointGeometry(\n        /** @type {import(\"../geom/MultiPoint.js\").default} */ (geometry),\n        options,\n      );\n      break;\n    }\n    case 'MultiLineString': {\n      geoJSON = writeMultiLineStringGeometry(\n        /** @type {import(\"../geom/MultiLineString.js\").default} */ (geometry),\n        options,\n      );\n      break;\n    }\n    case 'MultiPolygon': {\n      geoJSON = writeMultiPolygonGeometry(\n        /** @type {import(\"../geom/MultiPolygon.js\").default} */ (geometry),\n        options,\n      );\n      break;\n    }\n    case 'GeometryCollection': {\n      geoJSON = writeGeometryCollectionGeometry(\n        /** @type {import(\"../geom/GeometryCollection.js\").default} */ (\n          geometry\n        ),\n        options,\n      );\n      break;\n    }\n    case 'Circle': {\n      geoJSON = {\n        type: 'GeometryCollection',\n        geometries: [],\n      };\n      break;\n    }\n    default: {\n      throw new Error('Unsupported geometry type: ' + type);\n    }\n  }\n  return geoJSON;\n}\n\n/**\n * @param {import(\"../geom/GeometryCollection.js\").default} geometry Geometry.\n * @param {import(\"./Feature.js\").WriteOptions} [options] Write options.\n * @return {GeoJSONGeometryCollection} GeoJSON geometry collection.\n */\nfunction writeGeometryCollectionGeometry(geometry, options) {\n  options = Object.assign({}, options);\n  delete options.featureProjection;\n  const geometries = geometry.getGeometriesArray().map(function (geometry) {\n    return writeGeometry(geometry, options);\n  });\n  return {\n    type: 'GeometryCollection',\n    geometries: geometries,\n  };\n}\n\n/**\n * @param {import(\"../geom/LineString.js\").default} geometry Geometry.\n * @param {import(\"./Feature.js\").WriteOptions} [options] Write options.\n * @return {GeoJSONGeometry} GeoJSON geometry.\n */\nfunction writeLineStringGeometry(geometry, options) {\n  return {\n    type: 'LineString',\n    coordinates: geometry.getCoordinates(),\n  };\n}\n\n/**\n * @param {import(\"../geom/MultiLineString.js\").default} geometry Geometry.\n * @param {import(\"./Feature.js\").WriteOptions} [options] Write options.\n * @return {GeoJSONGeometry} GeoJSON geometry.\n */\nfunction writeMultiLineStringGeometry(geometry, options) {\n  return {\n    type: 'MultiLineString',\n    coordinates: geometry.getCoordinates(),\n  };\n}\n\n/**\n * @param {import(\"../geom/MultiPoint.js\").default} geometry Geometry.\n * @param {import(\"./Feature.js\").WriteOptions} [options] Write options.\n * @return {GeoJSONGeometry} GeoJSON geometry.\n */\nfunction writeMultiPointGeometry(geometry, options) {\n  return {\n    type: 'MultiPoint',\n    coordinates: geometry.getCoordinates(),\n  };\n}\n\n/**\n * @param {import(\"../geom/MultiPolygon.js\").default} geometry Geometry.\n * @param {import(\"./Feature.js\").WriteOptions} [options] Write options.\n * @return {GeoJSONGeometry} GeoJSON geometry.\n */\nfunction writeMultiPolygonGeometry(geometry, options) {\n  let right;\n  if (options) {\n    right = options.rightHanded;\n  }\n  return {\n    type: 'MultiPolygon',\n    coordinates: geometry.getCoordinates(right),\n  };\n}\n\n/**\n * @param {import(\"../geom/Point.js\").default} geometry Geometry.\n * @param {import(\"./Feature.js\").WriteOptions} [options] Write options.\n * @return {GeoJSONGeometry} GeoJSON geometry.\n */\nfunction writePointGeometry(geometry, options) {\n  return {\n    type: 'Point',\n    coordinates: geometry.getCoordinates(),\n  };\n}\n\n/**\n * @param {import(\"../geom/Polygon.js\").default} geometry Geometry.\n * @param {import(\"./Feature.js\").WriteOptions} [options] Write options.\n * @return {GeoJSONGeometry} GeoJSON geometry.\n */\nfunction writePolygonGeometry(geometry, options) {\n  let right;\n  if (options) {\n    right = options.rightHanded;\n  }\n  return {\n    type: 'Polygon',\n    coordinates: geometry.getCoordinates(right),\n  };\n}\n\nexport default GeoJSON;\n", "/**\n * notices.js \u2014 srozumiteln\u00E1 hl\u00E1\u0161en\u00ED pro u\u017Eivatele mapy m\u00EDsto tich\u00E9ho\n * `console.warn`:\n *\n *  1. Modal \u201Edo\u0161ly kredity\u201C (HTTP 402 z /items/<id>/wms/) \u2014 vykreslov\u00E1n\u00ED mapy\n *     plat\u00ED jej\u00ED vlastn\u00EDk z kredit\u016F (R14 = A). Vlastn\u00EDk dostane odkazy na\n *     n\u00E1kup kredit\u016F / pl\u00E1ny v Console, ostatn\u00ED div\u00E1ci vysv\u011Btlen\u00ED a tla\u010D\u00EDtko\n *     \u201ELet the owner know\u201C (POST /maps/<uuid>/notify-owner/, 1\u00D7/24 h na mapu).\n *  2. Panel \u201En\u011Bkter\u00E9 vrstvy nejdou na\u010D\u00EDst\u201C (403/404/jin\u00E1 chyba) \u2014 souhrnn\u011B\n *     po na\u010Dten\u00ED mapy, jednotliv\u011B p\u0159i p\u0159id\u00E1n\u00ED vrstvy \u010Di obnov\u011B podpisu.\n *     Stejn\u00FD panel vysv\u011Btl\u00ED i \u010D\u00E1sti souboru, kter\u00E9 MapServer nevykreslil\n *     (`X-GCZ-Skipped-Layers`, nap\u0159. obr\u00E1zek vektorov\u00E9ho PDF) \u2014 text podle\n *     k\u00F3du d\u016Fvodu (`reportSkippedParts`).\n */\nimport { apiFetch } from './utils.js';\nimport { skippedReasonText } from './hybrid.js';\n\nfunction escapeHtml(value) {\n    return String(value ?? '')\n        .replaceAll('&', '&amp;')\n        .replaceAll('<', '&lt;')\n        .replaceAll('>', '&gt;')\n        .replaceAll('\"', '&quot;');\n}\n\n/** Lidsk\u00FD popis d\u016Fvodu selh\u00E1n\u00ED vrstvy podle HTTP statusu. */\nexport function layerProblemReason(status) {\n    if (status === 404) return 'The data no longer exists or you don\u2019t have access to it.';\n    if (status === 403) return 'Hidden \u2014 the owner of this data hasn\u2019t shared it with you.';\n    if (status === 402) return 'The map owner has run out of credits for displaying this map.';\n    // \u201ESave as\u201C kopie ciz\u00ED mapy: vrstva bez vlastn\u00EDho p\u0159\u00EDstupu k dat\u016Fm se nekop\u00EDruje.\n    if (status === 'omitted') return 'Not included in your copy \u2014 you don\u2019t have access to this data yourself.';\n    return 'The layer couldn\u2019t be loaded right now. Try reloading the page.';\n}\n\n/* ---------------------------------------------------------------------------\n * Modal \u201Edo\u0161ly kredity\u201C (402)\n * ------------------------------------------------------------------------- */\n\n/** Propoj\u00ED modal `#map-credits-modal`. Vrac\u00ED `show(payload)` \u2014 modal se uk\u00E1\u017Ee\n * jen jednou za na\u010Dten\u00ED str\u00E1nky (402 p\u0159ich\u00E1z\u00ED pro ka\u017Edou vrstvu zvl\u00E1\u0161\u0165). */\nexport function initCreditsModal(ctx, { openOverlay, closeOverlay }) {\n    const modal = document.getElementById('map-credits-modal');\n    if (!modal) return () => {};\n    const q = (role) => modal.querySelector(`[data-role=\"${role}\"]`);\n    const els = {\n        what: q('credits-what'),\n        why: q('credits-why'),\n        fix: q('credits-fix'),\n        status: q('credits-status'),\n        buy: q('credits-buy'),\n        plans: q('credits-plans'),\n        notify: q('credits-notify'),\n        close: q('credits-close'),\n    };\n    let shown = false;\n    let current = null;\n\n    function setStatus(text, tone = 'info') {\n        if (!els.status) return;\n        els.status.textContent = text;\n        els.status.classList.remove('hidden', 'text-emerald-700', 'text-red-600', 'text-slate-600');\n        els.status.classList.add(tone === 'ok' ? 'text-emerald-700' : tone === 'error' ? 'text-red-600' : 'text-slate-600');\n    }\n\n    const labels = { buy: els.buy?.textContent || 'Get credits', plans: els.plans?.textContent || 'See plans' };\n\n    function render(payload) {\n        const info = payload?.map_credits || {};\n        const isPayer = Boolean(info.payer_is_you);\n        els.status?.classList.add('hidden');\n        if (els.buy) els.buy.textContent = labels.buy;\n        if (els.plans) els.plans.textContent = labels.plans;\n        if (isPayer && payload?.reason === 'payment_overdue') {\n            // Platba p\u0159edplatn\u00E9ho po splatnosti: kredity jsou pozastaven\u00E9, bal\u00ED\u010Dek by nepomohl.\n            const plan = payload?.hold?.plan || 'your';\n            els.what.textContent = `Your map layers can\u2019t be displayed \u2014 your payment for the ${plan} plan didn\u2019t go through, `\n                + 'so your credits are paused.';\n            els.why.textContent = 'Rendering a map is paid from your credits. They are available again as soon as the payment goes through.';\n            els.fix.textContent = 'Pay the open invoice, or add a working card and we\u2019ll retry the payment.';\n            const payUrl = payload?.options?.pay_url || '';\n            const cardUrl = payload?.options?.payment_methods_url || '';\n            if (payUrl) { els.buy.href = payUrl; els.buy.textContent = 'Pay now'; els.buy.classList.remove('hidden'); } else { els.buy.classList.add('hidden'); }\n            if (cardUrl) { els.plans.href = cardUrl; els.plans.textContent = 'Update card'; els.plans.classList.remove('hidden'); } else { els.plans.classList.add('hidden'); }\n            els.notify.classList.add('hidden');\n        } else if (isPayer) {\n            els.what.textContent = 'Your map layers can\u2019t be displayed \u2014 you have run out of credits.';\n            els.why.textContent = info.payer_role === 'map_owner'\n                ? 'Rendering a map is paid by the person who made it. You own this map, so every view of it \u2014 '\n                    + 'yours and everyone you share it with \u2014 uses your credits.'\n                : 'Data you open on a new map is rendered from your credits. In a saved map, its owner pays.';\n            els.fix.textContent = info.signed_in === false\n                ? 'Sign in or create a free account to get more credits.'\n                : 'Add credits or upgrade your plan in the Console. The map then works again for everyone '\n                    + 'right away \u2014 there is no need to share it again.';\n            const billing = ctx.bootstrap.billing || {};\n            const buyUrl = billing.creditsUrl || payload?.options?.credits_url || payload?.options?.pricing_url || '';\n            const plansUrl = billing.plansUrl || billing.pricingUrl || payload?.options?.pricing_url || '';\n            if (buyUrl) { els.buy.href = buyUrl; els.buy.classList.remove('hidden'); } else { els.buy.classList.add('hidden'); }\n            if (plansUrl) { els.plans.href = plansUrl; els.plans.classList.remove('hidden'); } else { els.plans.classList.add('hidden'); }\n            els.notify.classList.add('hidden');\n        } else {\n            const ownerLabel = ctx.bootstrap.ownerLabel ? ` (${ctx.bootstrap.ownerLabel})` : '';\n            els.what.textContent = `The owner of this map${ownerLabel} has run out of credits for displaying it, `\n                + 'so its layers can\u2019t be shown right now.';\n            els.why.textContent = 'Rendering a shared map is paid by its owner from their credits \u2014 not by you. '\n                + 'Viewing a shared map never costs you anything.';\n            // Vlastn\u00EDkovi p\u0159ijde e-mail s\u00E1m (nejv\u00FD\u0161 jednou denn\u011B), viz `maps.views._map_credits_payload`.\n            els.fix.textContent = info.owner_notified\n                ? 'We\u2019ve let the owner know by e-mail. The map works again as soon as they add credits.'\n                : 'Only the owner can fix this by adding credits. Please let them know.';\n            els.buy.classList.add('hidden');\n            els.plans.classList.add('hidden');\n            els.notify.classList.toggle('hidden', !info.can_notify);\n            els.notify.disabled = false;\n        }\n    }\n\n    els.notify?.addEventListener('click', async () => {\n        const url = current?.map_credits?.notify_url;\n        if (!url) return;\n        els.notify.disabled = true;\n        setStatus('Sending\u2026');\n        try {\n            await apiFetch(url, { method: 'POST', body: '{}' });\n            setStatus('Thanks \u2014 the owner has been notified by e-mail.', 'ok');\n        } catch (error) {\n            let message = 'The e-mail couldn\u2019t be sent. Please try again later.';\n            try {\n                const raw = String(error?.message || '');\n                const data = JSON.parse(raw.slice(raw.indexOf('{')));\n                if (data?.error) message = data.error;\n            } catch {\n                /* t\u011Blo nen\u00ED JSON \u2014 pou\u017Eije se obecn\u00E1 hl\u00E1\u0161ka */\n            }\n            // 429 = u\u017E upozorn\u011Bn (nen\u00ED to chyba u\u017Eivatele), 409 = kredity zase jsou.\n            const tone = error?.status === 429 ? 'info' : 'error';\n            setStatus(message, tone);\n            if (error?.status !== 429 && error?.status !== 409) els.notify.disabled = false;\n        }\n    });\n    els.close?.addEventListener('click', () => closeOverlay(modal));\n\n    return function show(payload) {\n        if (shown) return;\n        shown = true;\n        current = payload;\n        render(payload);\n        // 402 typicky p\u0159ijde u\u017E p\u0159i na\u010D\u00EDt\u00E1n\u00ED vrstev \u2014 Preline overlay je\n        // spolehliv\u011B p\u0159ipraven\u00FD a\u017E po `load`.\n        if (document.readyState === 'complete') {\n            openOverlay(modal);\n        } else {\n            window.addEventListener('load', () => openOverlay(modal), { once: true });\n        }\n    };\n}\n\n/* ---------------------------------------------------------------------------\n * Panel \u201En\u011Bkter\u00E9 vrstvy nejdou na\u010D\u00EDst\u201C\n * ------------------------------------------------------------------------- */\n\nconst reported = [];\n\nfunction renderLayerNotice() {\n    let box = document.getElementById('map-layer-notice');\n    if (reported.length === 0) {\n        box?.remove();\n        return;\n    }\n    if (!box) {\n        box = document.createElement('div');\n        box.id = 'map-layer-notice';\n        box.setAttribute('role', 'alert');\n        box.className = 'absolute bottom-12 left-1/2 z-30 w-[min(32rem,calc(100%-1rem))] -translate-x-1/2 rounded-xl border border-amber-200 bg-amber-50 p-3 text-sm text-amber-900 shadow-lg';\n        (document.getElementById('map-view')?.parentElement || document.body).appendChild(box);\n        box.addEventListener('click', (event) => {\n            if (event.target.closest('[data-role=\"layer-notice-close\"]')) {\n                reported.length = 0;\n                renderLayerNotice();\n            }\n        });\n    }\n    const onlyParts = reported.every((p) => p.status === 'skipped');\n    let heading;\n    if (onlyParts) {\n        heading = reported.length === 1\n            ? 'Part of your data isn\u2019t drawn'\n            : 'Some parts of your data aren\u2019t drawn';\n    } else {\n        heading = reported.length === 1\n            ? 'A layer isn\u2019t shown'\n            : `${reported.length} layers aren\u2019t shown`;\n    }\n    box.innerHTML = `\n        <div class=\"flex items-start gap-x-2\">\n            <svg class=\"mt-0.5 h-4 w-4 flex-none text-amber-600\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" aria-hidden=\"true\"><path d=\"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3\"/><path d=\"M12 9v4\"/><path d=\"M12 17h.01\"/></svg>\n            <div class=\"min-w-0 flex-1\">\n                <p class=\"font-semibold\">${heading}</p>\n                <ul class=\"mt-1 max-h-32 space-y-0.5 overflow-y-auto text-xs text-amber-800\">\n                    ${reported.map((p) => `<li><span class=\"font-medium\">${escapeHtml(p.title)}</span> \u2014 ${escapeHtml(p.reason || layerProblemReason(p.status))}</li>`).join('')}\n                </ul>\n            </div>\n            <button type=\"button\" data-role=\"layer-notice-close\" aria-label=\"Close\"\n                    class=\"flex-none rounded p-0.5 text-amber-700 hover:bg-amber-100\">\n                <svg class=\"h-4 w-4\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\"><path d=\"M18 6 6 18M6 6l12 12\"/></svg>\n            </button>\n        </div>`;\n}\n\n/**\n * Ohl\u00E1s\u00ED \u010D\u00E1sti souboru, kter\u00E9 MapServer nevykreslil (`X-GCZ-Skipped-Layers`).\n * `title` = n\u00E1zev vrstvy na map\u011B, `skipped` = `{ layers, omitted }` z hlavi\u010Dky,\n * `reasons` = texty podle k\u00F3du (bootstrap `skipReasons`). Kl\u00ED\u010Dem je polo\u017Eka\n * (`itemId`) + n\u00E1zev \u010D\u00E1sti \u2014 ob\u011B \u010D\u00E1sti hybridu tak hl\u00E1\u0161en\u00ED neopakuj\u00ED.\n */\nexport function reportSkippedParts({ itemId, title, skipped, reasons }) {\n    const problems = (skipped?.layers || []).map((layer) => ({\n        key: `skipped:${itemId}:${layer.name || layer.kind || ''}`,\n        title: layer.name ? `${title} \u2014 ${layer.name}` : title,\n        status: 'skipped',\n        reason: skippedReasonText(layer, reasons),\n    }));\n    if (skipped?.omitted) {\n        problems.push({\n            key: `skipped:${itemId}:omitted`,\n            title,\n            status: 'skipped',\n            reason: `\u2026and ${skipped.omitted} more part${skipped.omitted === 1 ? '' : 's'} of this file can\u2019t be drawn.`,\n        });\n    }\n    reportLayerProblems(problems);\n}\n\n/** Ohl\u00E1s\u00ED vrstvy, kter\u00E9 se nepoda\u0159ilo na\u010D\u00EDst: `[{ title, status, reason? }]`.\n * 402 se tady nevypisuje \u2014 tu vysv\u011Btluje modal kredit\u016F. */\nexport function reportLayerProblems(problems) {\n    (problems || []).forEach((problem) => {\n        if (problem.status === 402) return;\n        const key = `${problem.key || problem.title}`;\n        if (reported.some((p) => `${p.key || p.title}` === key)) return;\n        reported.push(problem);\n    });\n    renderLayerNotice();\n}\n\n/* ---------------------------------------------------------------------------\n * Toasty \u2014 kr\u00E1tk\u00E1 neblokuj\u00EDc\u00ED zpr\u00E1va nad mapou (v\u00FDsledek akce, pr\u016Fb\u011Bh)\n * ------------------------------------------------------------------------- */\n\nconst TOAST_TONES = {\n    info: 'border-slate-200 bg-white text-slate-700',\n    ok: 'border-emerald-200 bg-emerald-50 text-emerald-800',\n    error: 'border-red-200 bg-red-50 text-red-800',\n    busy: 'border-slate-200 bg-white text-slate-700',\n};\n\nfunction toastContainer() {\n    let box = document.getElementById('map-toasts');\n    if (!box) {\n        box = document.createElement('div');\n        box.id = 'map-toasts';\n        box.className = 'pointer-events-none absolute bottom-12 left-1/2 z-40 flex w-[min(28rem,calc(100%-1rem))] -translate-x-1/2 flex-col items-center gap-y-2';\n        (document.getElementById('map-view')?.parentElement || document.body).appendChild(box);\n    }\n    return box;\n}\n\n/**\n * Zobraz\u00ED toast. `options`: `tone` ('info' | 'ok' | 'error' | 'busy' \u2014 busy m\u00E1\n * spinner a s\u00E1m nezmiz\u00ED), `timeout` (ms; 0 = nezmiz\u00ED s\u00E1m), `action`\n * (`{ label, href }` nebo `{ label, onClick }`).\n * Vrac\u00ED `{ update(message, options), close() }` \u2014 pro pr\u016Fb\u011Bh d\u00E9le trvaj\u00EDc\u00ED akce.\n */\nexport function showToast(message, options = {}) {\n    const el = document.createElement('div');\n    el.setAttribute('role', 'status');\n    let timer = null;\n\n    function close() {\n        clearTimeout(timer);\n        el.remove();\n    }\n\n    function render(text, opts) {\n        const tone = opts.tone || 'info';\n        const { action } = opts;\n        el.className = `pointer-events-auto flex max-w-full items-center gap-x-2.5 rounded-xl border px-3 py-2 text-sm shadow-lg ${TOAST_TONES[tone] || TOAST_TONES.info}`;\n        el.innerHTML = `\n            ${tone === 'busy' ? '<span class=\"map-spinner flex-none\" aria-hidden=\"true\"></span>' : ''}\n            ${tone === 'ok' ? '<svg class=\"h-4 w-4 flex-none\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" aria-hidden=\"true\"><path d=\"m5 12 5 5L20 7\"/></svg>' : ''}\n            <span class=\"min-w-0 flex-1\">${escapeHtml(text)}</span>\n            ${action ? `<${action.href ? `a href=\"${escapeHtml(action.href)}\" target=\"_blank\" rel=\"noopener\"` : 'button type=\"button\"'} data-role=\"toast-action\" class=\"flex-none font-semibold underline underline-offset-2 hover:no-underline\">${escapeHtml(action.label)}</${action.href ? 'a' : 'button'}>` : ''}\n            <button type=\"button\" data-role=\"toast-close\" aria-label=\"Dismiss\" class=\"flex-none rounded p-0.5 opacity-60 hover:opacity-100\">\n                <svg class=\"h-4 w-4\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\"><path d=\"M18 6 6 18M6 6l12 12\"/></svg>\n            </button>`;\n        el.querySelector('[data-role=\"toast-close\"]').addEventListener('click', close);\n        if (action?.onClick) {\n            el.querySelector('[data-role=\"toast-action\"]')?.addEventListener('click', () => {\n                close();\n                action.onClick();\n            });\n        }\n        clearTimeout(timer);\n        const timeout = opts.timeout ?? (tone === 'busy' ? 0 : tone === 'error' ? 9000 : 6000);\n        if (timeout > 0) timer = setTimeout(close, timeout);\n    }\n\n    render(message, options);\n    toastContainer().appendChild(el);\n    return {\n        update: (text, opts = {}) => {\n            if (!el.isConnected) toastContainer().appendChild(el);\n            render(text, opts);\n        },\n        close,\n    };\n}\n", "/**\n * draw.js \u2014 kreslen\u00ED do mapy: n\u00E1stroje Point/Line/Polygon/Rectangle/Circle/Text,\n * editace (Modify), v\u00FDb\u011Br + maz\u00E1n\u00ED prvk\u016F, barva a \u0161\u00ED\u0159ka/velikost.\n *\n * Kresba je speci\u00E1ln\u00ED vrstva \"Drawing\" ve stromu vrstev (klientsk\u00E1 OL Vector,\n * `dataType: 'drawing'`, syntetick\u00E9 `itemId: 'drawing'`) \u2014 viditelnost,\n * pr\u016Fhlednost i odebr\u00E1n\u00ED funguj\u00ED standardn\u011B (layers.js). Do Map.config se\n * ukl\u00E1d\u00E1 jako GeoJSON FeatureCollection v EPSG:4326 + per-feature style\n * vlastnosti (`color`, `width`, `size`, `label`) \u2014 viz docs/maps.md.\n */\nimport Draw, { createBox } from 'ol/interaction/Draw.js';\nimport Modify from 'ol/interaction/Modify.js';\nimport Select from 'ol/interaction/Select.js';\nimport { click } from 'ol/events/condition.js';\nimport VectorLayer from 'ol/layer/Vector.js';\nimport VectorSource from 'ol/source/Vector.js';\nimport GeoJSON from 'ol/format/GeoJSON.js';\nimport { fromCircle } from 'ol/geom/Polygon.js';\nimport Style from 'ol/style/Style.js';\nimport Stroke from 'ol/style/Stroke.js';\nimport Fill from 'ol/style/Fill.js';\nimport CircleStyle from 'ol/style/Circle.js';\nimport Text from 'ol/style/Text.js';\nimport { apiFetch, emit, on } from './utils.js';\nimport { newUid, flatLayers, findEntryByUid } from './state.js';\nimport { renderLayerTree, applyZoomLimits } from './layers.js';\nimport { showToast } from './notices.js';\n\n/** Syntetick\u00E9 id drawing vrstvy \u2014 v map\u011B je nejv\u00FD\u0161 jedna kresba. */\nexport const DRAWING_ITEM_ID = 'drawing';\n\nconst DEFAULT_COLOR = '#e11d48';\nconst DEFAULT_WIDTH = 2;\nconst DEFAULT_SIZE = 6;\n\n/** Vlastnosti prvku kresby, kter\u00E9 nesou jeho STYL \u2014 nejsou to atributy, tak\u017Ee\n * se nezobrazuj\u00ED v popupu ani v atributov\u00E9 tabulce a nejde je pou\u017E\u00EDt jako\n * n\u00E1zev sloupce. `label` naopak atribut je (jeho hodnota se kresl\u00ED jako\n * popisek prvku). */\nexport const DRAWING_STYLE_KEYS = ['color', 'width', 'size'];\n\n/** N\u00E1zev atributu, jeho\u017E hodnota se kresl\u00ED jako popisek prvku. */\nexport const DRAWING_LABEL_FIELD = 'label';\n\nconst MAX_FIELD_NAME = 64;\n\nconst geojsonFormat = new GeoJSON();\n\n/** P\u0159evede hex barvu na rgba s danou pr\u016Fhlednost\u00ED (v\u00FDpln\u011B polygon\u016F/bod\u016F). */\nfunction hexToRgba(hex, alpha) {\n    const match = /^#?([0-9a-f]{6})$/i.exec(hex || '');\n    if (!match) return `rgba(225, 29, 72, ${alpha})`;\n    const num = parseInt(match[1], 16);\n    /* eslint-disable no-bitwise -- rozklad hex barvy na RGB kan\u00E1ly */\n    const r = (num >> 16) & 255;\n    const g = (num >> 8) & 255;\n    const b = num & 255;\n    /* eslint-enable no-bitwise */\n    return `rgba(${r}, ${g}, ${b}, ${alpha})`;\n}\n\n/** OL styl prvku kresby podle jeho vlastnost\u00ED (color/width/size/label). */\nfunction featureStyle(feature) {\n    const color = feature.get('color') || DEFAULT_COLOR;\n    const width = Number(feature.get('width')) || DEFAULT_WIDTH;\n    const size = Number(feature.get('size')) || DEFAULT_SIZE;\n    const label = feature.get('label');\n    const isText = Boolean(label) && feature.getGeometry()?.getType() === 'Point';\n    return new Style({\n        stroke: new Stroke({ color, width }),\n        fill: new Fill({ color: hexToRgba(color, 0.25) }),\n        // Textov\u00FD prvek se kresl\u00ED jen jako popisek (bez kole\u010Dka).\n        image: isText ? undefined : new CircleStyle({\n            radius: size,\n            fill: new Fill({ color }),\n            stroke: new Stroke({ color: '#ffffff', width: 1.5 }),\n        }),\n        text: label ? new Text({\n            text: String(label),\n            font: `${10 + size}px sans-serif`,\n            fill: new Fill({ color }),\n            stroke: new Stroke({ color: '#ffffff', width: 3 }),\n            offsetY: isText ? 0 : -size - 10,\n        }) : undefined,\n    });\n}\n\n/** Styl vybran\u00E9ho prvku \u2014 modr\u00FD p\u0159eliv p\u0159es vlastn\u00ED styl prvku. */\nfunction selectedStyle(feature) {\n    const base = featureStyle(feature);\n    base.setStroke(new Stroke({ color: '#2563eb', width: (Number(feature.get('width')) || DEFAULT_WIDTH) + 1, lineDash: [5, 5] }));\n    return base;\n}\n\n/** Serializuje prvky kresby do GeoJSON FeatureCollection (EPSG:4326). */\nfunction sourceToGeoJSON(source) {\n    return geojsonFormat.writeFeaturesObject(source.getFeatures(), {\n        dataProjection: 'EPSG:4326',\n        featureProjection: 'EPSG:3857',\n        decimals: 7,\n    });\n}\n\n/** Najde b\u011Bhovou polo\u017Eku drawing vrstvy (nebo null). P\u0159i v\u00EDce kresb\u00E1ch\n * (duplik\u00E1t) vrac\u00ED prvn\u00ED v po\u0159ad\u00ED stromu \u2014 tu edituj\u00ED kreslic\u00ED n\u00E1stroje. */\nexport function findDrawingEntry(ctx) {\n    return flatLayers(ctx.state).find((l) => l.dataType === 'drawing') || null;\n}\n\n/** Vytvo\u0159\u00ED b\u011Bhovou polo\u017Eku drawing vrstvy + OL vrstvu a vlo\u017E\u00ED ji do mapy\n * i stromu vrstev. `saved` je voliteln\u00FD ulo\u017Een\u00FD z\u00E1znam z Map.config.\n * `forceNew` obejde singleton \u2014 pou\u017E\u00EDv\u00E1 duplikace vrstvy (layers.js). */\nexport function createDrawingLayer(ctx, saved, { forceNew = false } = {}) {\n    const existing = findDrawingEntry(ctx);\n    if (existing && !forceNew) return existing;\n\n    const source = new VectorSource();\n    if (saved?.geojson?.features?.length) {\n        source.addFeatures(geojsonFormat.readFeatures(saved.geojson, {\n            dataProjection: 'EPSG:4326',\n            featureProjection: 'EPSG:3857',\n        }));\n    }\n    const layer = new VectorLayer({\n        source,\n        style: featureStyle,\n        visible: saved ? saved.visible !== false : true,\n        opacity: saved && Number.isFinite(saved.opacity) ? saved.opacity : 1,\n        // Bez zIndexu \u2014 po\u0159ad\u00ED \u0159\u00EDd\u00ED kolekce vrstev mapy (drag&drop ve stromu\n        // vrstev funguje pro kresbu stejn\u011B jako pro WMS vrstvy).\n        properties: { role: 'drawing' },\n    });\n    ctx.map.addLayer(layer);\n\n    const entry = {\n        uid: newUid(),\n        itemId: DRAWING_ITEM_ID,\n        title: saved?.title || 'Drawing',\n        visible: saved ? saved.visible !== false : true,\n        opacity: saved && Number.isFinite(saved.opacity) ? saved.opacity : 1,\n        minZoom: Number.isFinite(saved?.minZoom) ? saved.minZoom : null,\n        maxZoom: Number.isFinite(saved?.maxZoom) ? saved.maxZoom : null,\n        dataType: 'drawing',\n        style: null,\n        filter: null,\n        bbox: null,\n        sublayers: [],\n        geometryTypes: [],\n        bands: null,\n        wms: null,\n        olLayer: layer,\n        olSource: source,\n        // Atributy (sloupce) kresby v po\u0159ad\u00ED, v jak\u00E9m je vid\u00ED tabulka. Dr\u017E\u00ED se\n        // zvl\u00E1\u0161\u0165, aby pr\u00E1zdn\u00FD sloupec nezmizel a po\u0159ad\u00ED bylo stabiln\u00ED.\n        fields: [],\n        // Serializace pro Map.config (viz state.serializeConfig) \u2014 funkce,\n        // aby state.js nemusel z\u00E1viset na OpenLayers.\n        toGeoJSON: () => sourceToGeoJSON(source),\n    };\n    entry.fields = initialFields(saved, source);\n    ctx.state.layers.unshift(entry);\n    applyZoomLimits(entry);\n    renderLayerTree(ctx);\n\n    // Ka\u017Ed\u00E1 zm\u011Bna prvk\u016F = neulo\u017Een\u00E1 zm\u011Bna mapy (+ obnova otev\u0159en\u00E9 tabulky).\n    ['addfeature', 'removefeature', 'changefeature'].forEach((type) => {\n        source.on(type, (event) => {\n            ctx.state.dirty = true;\n            if (type === 'addfeature') adoptFeatureFields(entry, event.feature);\n            emit('drawing:changed', { entry, type });\n        });\n    });\n    return entry;\n}\n\n/* ---------------------------------------------------------------------------\n * Atributy prvk\u016F kresby (sloupce atributov\u00E9 tabulky)\n * ------------------------------------------------------------------------- */\n\n/** U\u017Eivatelsk\u00E9 atributy prvku \u2014 bez geometrie a stylov\u00FDch vlastnost\u00ED. */\nexport function drawingAttributes(feature) {\n    const out = {};\n    const geometryName = feature.getGeometryName();\n    Object.entries(feature.getProperties()).forEach(([key, value]) => {\n        if (key === geometryName || DRAWING_STYLE_KEYS.includes(key)) return;\n        out[key] = value;\n    });\n    return out;\n}\n\n/** Sloupce p\u0159i vytvo\u0159en\u00ED vrstvy: ulo\u017Een\u00E9 po\u0159ad\u00ED + atributy nalezen\u00E9 v prvc\u00EDch. */\nfunction initialFields(saved, source) {\n    const fields = [];\n    const add = (name) => {\n        if (typeof name === 'string' && name && !DRAWING_STYLE_KEYS.includes(name) && !fields.includes(name)) {\n            fields.push(name);\n        }\n    };\n    (Array.isArray(saved?.fields) ? saved.fields : []).forEach(add);\n    source.getFeatures().forEach((feature) => Object.keys(drawingAttributes(feature)).forEach(add));\n    return fields;\n}\n\n/** Nov\u00FD prvek m\u016F\u017Ee p\u0159in\u00E9st atribut, kter\u00FD kresba je\u0161t\u011B nezn\u00E1 (popisek textu). */\nfunction adoptFeatureFields(entry, feature) {\n    Object.keys(drawingAttributes(feature)).forEach((name) => {\n        if (!entry.fields.includes(name)) entry.fields.push(name);\n    });\n}\n\n/** Ov\u011B\u0159\u00ED n\u00E1zev nov\u00E9ho sloupce; vrac\u00ED text chyby, nebo null. */\nexport function drawingFieldError(entry, name, currentName = null) {\n    const trimmed = String(name || '').trim();\n    if (!trimmed) return 'Enter a column name.';\n    if (trimmed.length > MAX_FIELD_NAME) return `The name can have at most ${MAX_FIELD_NAME} characters.`;\n    const lower = trimmed.toLowerCase();\n    if (lower === 'geometry' || DRAWING_STYLE_KEYS.includes(lower)) {\n        return `\u201C${trimmed}\u201D is reserved \u2014 choose another name.`;\n    }\n    const clash = entry.fields.some((f) => f.toLowerCase() === lower && f !== currentName);\n    if (clash) return `A column named \u201C${trimmed}\u201D already exists.`;\n    return null;\n}\n\n/** P\u0159id\u00E1 sloupec (pr\u00E1zdn\u00FD u v\u0161ech prvk\u016F). Vrac\u00ED n\u00E1zev, nebo vyhod\u00ED chybu. */\nexport function addDrawingField(ctx, entry, name) {\n    const error = drawingFieldError(entry, name);\n    if (error) throw new Error(error);\n    const field = String(name).trim();\n    entry.fields.push(field);\n    ctx.state.dirty = true;\n    emit('drawing:changed', { entry, type: 'fields' });\n    return field;\n}\n\n/** P\u0159ejmenuje sloupec v\u010Detn\u011B hodnot u v\u0161ech prvk\u016F. */\nexport function renameDrawingField(ctx, entry, oldName, newName) {\n    const error = drawingFieldError(entry, newName, oldName);\n    if (error) throw new Error(error);\n    const field = String(newName).trim();\n    if (field === oldName) return field;\n    const index = entry.fields.indexOf(oldName);\n    if (index === -1) throw new Error('Column not found.');\n    entry.fields[index] = field;\n    entry.olSource.getFeatures().forEach((feature) => {\n        const value = feature.get(oldName);\n        feature.unset(oldName, true);\n        if (value !== undefined) feature.set(field, value, true);\n    });\n    entry.olLayer.changed(); // popisek se mohl p\u0159est\u011Bhovat z/do sloupce `label`\n    ctx.state.dirty = true;\n    emit('drawing:changed', { entry, type: 'fields' });\n    return field;\n}\n\n/** Odebere sloupec i s hodnotami u v\u0161ech prvk\u016F. */\nexport function removeDrawingField(ctx, entry, name) {\n    const index = entry.fields.indexOf(name);\n    if (index === -1) return;\n    entry.fields.splice(index, 1);\n    entry.olSource.getFeatures().forEach((feature) => feature.unset(name, true));\n    entry.olLayer.changed();\n    ctx.state.dirty = true;\n    emit('drawing:changed', { entry, type: 'fields' });\n}\n\n/** Text z bu\u0148ky tabulky \u2192 hodnota atributu: pr\u00E1zdno = bez hodnoty, z\u00E1pis\n * \u010D\u00EDsla (bez \u00FAvodn\u00EDch nul) = \u010D\u00EDslo, jinak text. */\nexport function parseDrawingValue(text) {\n    const raw = String(text ?? '').trim();\n    if (raw === '') return null;\n    if (/^-?(0|[1-9]\\d*)(\\.\\d+)?$/.test(raw) && raw.length <= 15) return Number(raw);\n    return raw;\n}\n\n/** Nastav\u00ED hodnotu atributu jednoho prvku (z tabulky / popupu). */\nexport function setDrawingValue(ctx, entry, feature, name, text) {\n    const value = parseDrawingValue(text);\n    if (value === null) {\n        feature.unset(name);\n    } else {\n        feature.set(name, value);\n    }\n    ctx.state.dirty = true;\n}\n\n/** Odstran\u00ED jeden prvek kresby (\u0159\u00E1dek tabulky). */\nexport function removeDrawingFeature(ctx, entry, feature) {\n    if (entry.olSource.hasFeature(feature)) entry.olSource.removeFeature(feature);\n    ctx.state.dirty = true;\n}\n\n/** Obnov\u00ED drawing vrstvu z ulo\u017Een\u00E9ho Map.config z\u00E1znamu (main.js bootstrap). */\nexport function restoreDrawingLayer(ctx, saved) {\n    return createDrawingLayer(ctx, saved);\n}\n\n/** Drawing vrstva podle `uid`; bez n\u011Bj (nebo kdy\u017E u\u017E neexistuje) ta, kterou\n * edituj\u00ED kreslic\u00ED n\u00E1stroje. */\nfunction drawingEntryFor(ctx, uid) {\n    const entry = uid ? findEntryByUid(ctx.state, uid) : null;\n    return entry?.dataType === 'drawing' ? entry : findDrawingEntry(ctx);\n}\n\n/** Bezpe\u010Dn\u00FD n\u00E1zev souboru z n\u00E1zvu vrstvy (zachov\u00E1 diakritiku). */\nfunction drawingFilename(entry) {\n    const base = (entry.title || 'drawing')\n        .normalize('NFC')\n        .replace(/[\\\\/:*?\"<>|\\u0000-\\u001f]+/g, '_')\n        .replace(/\\s+/g, ' ')\n        .trim()\n        .replace(/^\\.+|\\.+$/g, '')\n        .slice(0, 100) || 'drawing';\n    return `${base}.geojson`;\n}\n\n/** St\u00E1hne kresbu jako GeoJSON soubor (FeatureCollection, EPSG:4326). */\nexport function exportDrawingGeoJSON(ctx, uid) {\n    const entry = drawingEntryFor(ctx, uid);\n    if (!entry) return;\n    const collection = entry.toGeoJSON();\n    const blob = new Blob([JSON.stringify(collection, null, 2)], { type: 'application/geo+json' });\n    const link = document.createElement('a');\n    link.href = URL.createObjectURL(blob);\n    link.download = drawingFilename(entry);\n    link.click();\n    setTimeout(() => URL.revokeObjectURL(link.href), 5000);\n}\n\n/** \"Save to workspace\" pot\u0159ebuje p\u0159ihl\u00E1\u0161en\u00E9ho u\u017Eivatele. Upload i spu\u0161t\u011Bn\u00ED\n * anal\u00FDzy jdou p\u0159es hostitele, na kter\u00E9m viewer b\u011B\u017E\u00ED (`/storage/\u2026` je na\n * hlavn\u00EDm webu i v Console, d\u00E1vku dokon\u010Duje `<apiBase>/workspace/\u2026`), tak\u017Ee\n * funguje stejn\u011B na `/map` hlavn\u00EDho webu i v Console. D\u0159\u00EDv se nab\u00EDdka\n * zobrazovala jen na hostiteli Console (podle n\u011Bj se \u201En\u011Bkdy objevila\u201C). */\nexport function canSaveDrawingToWorkspace(ctx) {\n    return Boolean(ctx.bootstrap.isAuthenticated);\n}\n\n/** Ulo\u017E\u00ED kresbu do Data workspace p\u0159es existuj\u00EDc\u00ED upload flow:\n * begin (presigned PUT) \u2192 PUT na S3 \u2192 complete \u2192 finalize d\u00E1vky (anal\u00FDza).\n * Vrac\u00ED promise; pr\u016Fb\u011Bh hl\u00E1s\u00ED p\u0159es `onStatus(text)`. */\nexport async function saveDrawingToWorkspace(ctx, uid, onStatus = () => {}) {\n    const entry = drawingEntryFor(ctx, uid);\n    if (!entry) throw new Error('No drawing layer.');\n    const collection = entry.toGeoJSON();\n    if (!collection.features?.length) throw new Error('The drawing is empty \u2014 draw something first.');\n    const filename = drawingFilename(entry);\n    const blob = new Blob([JSON.stringify(collection)], { type: 'application/geo+json' });\n    const workspaceApi = `${ctx.bootstrap.apiBase}/workspace`;\n\n    onStatus('Uploading the drawing\u2026');\n    const plan = await apiFetch('/storage/uploads/begin/', {\n        method: 'POST',\n        body: JSON.stringify({\n            purpose: 'workspace',\n            filename,\n            size: blob.size,\n            content_type: 'application/geo+json',\n        }),\n    });\n    if (plan.multipart || !plan.put_url) {\n        // Kresba je mal\u00FD soubor \u2014 multipart pl\u00E1n by znamenal ne\u010Dekan\u011B velk\u00E1 data.\n        throw new Error('Unexpected upload plan for a small file.');\n    }\n    const putResponse = await fetch(plan.put_url, {\n        method: 'PUT',\n        body: blob,\n        headers: { 'Content-Type': 'application/geo+json' },\n    });\n    if (!putResponse.ok) throw new Error(`Upload failed (${putResponse.status}).`);\n    await apiFetch(`/storage/uploads/${plan.upload_id}/complete/`, {\n        method: 'POST',\n        body: JSON.stringify({ parts: [] }),\n    });\n    onStatus('Reading the data\u2026');\n    const job = await apiFetch(`${workspaceApi}/finalize/`, {\n        method: 'POST',\n        body: JSON.stringify({ batch: plan.batch }),\n    });\n    // Aktivn\u011B dot\u00E1hni stav anal\u00FDzy (stejn\u011B jako str\u00E1nka nahr\u00E1v\u00E1n\u00ED workspace).\n    // Bez pollingu by d\u00E1vka, u kter\u00E9 nedoraz\u00ED callback z geoczech-v2, z\u016Fstala\n    // trvale ve stavu \u201Eanalyzing\" a kresba by se v Data workspace nikdy\n    // neobjevila (viz report). `batch_status` na serveru spou\u0161t\u00ED fallback\n    // polling (`poll_job`), kter\u00FD anal\u00FDzu dokon\u010D\u00ED a polo\u017Eky zmaterializuje.\n    if (job?.job_id) {\n        await pollBatchStatus(`${workspaceApi}/batch/${job.job_id}/status/`);\n    }\n}\n\n/** Dotazuje stav anal\u00FDzy d\u00E1vky, dokud neskon\u010D\u00ED (max ~2 min, \u00E0 2 s). */\nasync function pollBatchStatus(url) {\n    for (let tries = 0; tries < 60; tries += 1) {\n        let data;\n        try {\n            data = await apiFetch(url);\n        } catch {\n            // Do\u010Dasn\u00E1 chyba dotazu \u2014 nech\u00E1me dokon\u010Den\u00ED na serverov\u00E9m\n            // pollingu/webhooku a nezdr\u017Eujeme u\u017Eivatele d\u00E9le.\n            return;\n        }\n        if (!data || !data.active) return;\n        await new Promise((resolve) => { setTimeout(resolve, 2000); });\n    }\n}\n\n/** Srozumiteln\u00FD text chyby ulo\u017Een\u00ED (`apiFetch` h\u00E1z\u00ED \u201E<status> <text>: <t\u011Blo>\u201C). */\nfunction saveErrorText(error) {\n    const raw = String(error?.message || '');\n    const jsonStart = raw.indexOf('{');\n    if (jsonStart !== -1) {\n        try {\n            const data = JSON.parse(raw.slice(jsonStart));\n            if (data?.error) return String(data.error);\n            if (data?.detail) return String(data.detail);\n        } catch {\n            /* t\u011Blo nen\u00ED JSON */\n        }\n    }\n    if (error?.status === 413) return 'Your storage is full.';\n    return raw.replace(/<[^>]*>/g, ' ').slice(0, 200) || 'Unknown error.';\n}\n\n/* ---------------------------------------------------------------------------\n * Toolbar kreslen\u00ED (plovouc\u00ED panel na map\u011B)\n * ------------------------------------------------------------------------- */\n\nconst TOOLS = [\n    { key: 'point', label: 'Point', icon: '<circle cx=\"12\" cy=\"12\" r=\"3.5\"/>' },\n    { key: 'line', label: 'Line', icon: '<path d=\"M4 19 19 4\"/><circle cx=\"4\" cy=\"19\" r=\"2\"/><circle cx=\"19\" cy=\"4\" r=\"2\"/>' },\n    { key: 'polygon', label: 'Polygon', icon: '<path d=\"M12 3 21 9l-3.5 11h-11L3 9z\"/>' },\n    { key: 'rectangle', label: 'Rectangle', icon: '<rect x=\"4\" y=\"6\" width=\"16\" height=\"12\" rx=\"1\"/>' },\n    { key: 'circle', label: 'Circle', icon: '<circle cx=\"12\" cy=\"12\" r=\"8\"/>' },\n    { key: 'text', label: 'Text', icon: '<path d=\"M5 6V4h14v2M12 4v16m-3 0h6\"/>' },\n];\n\n/**\n * Inicializuje kreslen\u00ED: toolbar (skryt\u00FD), interakce a ud\u00E1losti stromu vrstev.\n * Vrac\u00ED API `{ open(), close(), isOpen() }` pro tla\u010D\u00EDtko \"Draw\" v horn\u00ED li\u0161t\u011B.\n */\nexport function initDraw(ctx, toolbarContainer) {\n    let isOpen = false;\n    let activeTool = null;     // kl\u00ED\u010D aktivn\u00EDho n\u00E1stroje (TOOLS), nebo null\n    let drawInteraction = null;\n    let selectInteraction = null;\n    let modifyInteraction = null;\n    let currentColor = DEFAULT_COLOR;\n    let currentWidth = DEFAULT_WIDTH;\n    let currentSize = DEFAULT_SIZE;\n\n    function entrySource() {\n        return createDrawingLayer(ctx).olSource;\n    }\n\n    function removeDrawInteraction() {\n        if (drawInteraction) {\n            ctx.map.removeInteraction(drawInteraction);\n            drawInteraction = null;\n        }\n        activeTool = null;\n    }\n\n    /** Select + Modify \u2014 aktivn\u00ED po celou dobu otev\u0159en\u00E9ho toolbaru. */\n    function addEditInteractions() {\n        const source = entrySource();\n        selectInteraction = new Select({\n            condition: click,\n            style: selectedStyle,\n            // Vyb\u00EDrat lze jen prvky kresby (ne m\u011B\u0159en\u00ED/zv\u00FDrazn\u011Bn\u00ED).\n            layers: (layer) => layer.get('role') === 'drawing',\n        });\n        modifyInteraction = new Modify({ source });\n        modifyInteraction.on('modifyend', () => { ctx.state.dirty = true; });\n        ctx.map.addInteraction(selectInteraction);\n        ctx.map.addInteraction(modifyInteraction);\n    }\n\n    function removeEditInteractions() {\n        if (selectInteraction) {\n            ctx.map.removeInteraction(selectInteraction);\n            selectInteraction = null;\n        }\n        if (modifyInteraction) {\n            ctx.map.removeInteraction(modifyInteraction);\n            modifyInteraction = null;\n        }\n    }\n\n    /** Aktivuje kreslic\u00ED n\u00E1stroj; opakovan\u00FD klik na stejn\u00FD n\u00E1stroj ho vypne. */\n    function activateTool(toolKey) {\n        if (activeTool === toolKey) {\n            removeDrawInteraction();\n            renderToolbar();\n            return;\n        }\n        removeDrawInteraction();\n        activeTool = toolKey;\n\n        const source = entrySource();\n        const options = { source, style: featureStyle };\n        if (toolKey === 'point' || toolKey === 'text') {\n            options.type = 'Point';\n        } else if (toolKey === 'line') {\n            options.type = 'LineString';\n        } else if (toolKey === 'polygon') {\n            options.type = 'Polygon';\n        } else if (toolKey === 'rectangle') {\n            options.type = 'Circle';\n            options.geometryFunction = createBox();\n        } else if (toolKey === 'circle') {\n            options.type = 'Circle';\n        }\n        drawInteraction = new Draw(options);\n        ctx.map.addInteraction(drawInteraction);\n\n        drawInteraction.on('drawend', (event) => {\n            const feature = event.feature;\n            // GeoJSON kruh neum\u00ED \u2014 p\u0159evod na polygon hned p\u0159i dokreslen\u00ED.\n            if (toolKey === 'circle' || toolKey === 'rectangle') {\n                const geometry = feature.getGeometry();\n                if (geometry.getType() === 'Circle') {\n                    feature.setGeometry(fromCircle(geometry, 64));\n                }\n            }\n            feature.set('color', currentColor);\n            feature.set('width', currentWidth);\n            feature.set('size', currentSize);\n            if (toolKey === 'text') {\n                // eslint-disable-next-line no-alert -- jednoduch\u00FD vstup textu bez extra UI\n                const label = window.prompt('Label text:', '');\n                if (!label || !label.trim()) {\n                    // Bez textu prvek nevznik\u00E1 \u2014 odstran\u00ED se po vlo\u017Een\u00ED do zdroje.\n                    setTimeout(() => entrySource().removeFeature(feature), 0);\n                    return;\n                }\n                feature.set('label', label.trim());\n            }\n            ctx.state.dirty = true;\n        });\n        renderToolbar();\n    }\n\n    /** Sma\u017Ee vybran\u00E9 prvky (tla\u010D\u00EDtko i kl\u00E1vesa Delete). */\n    function deleteSelected() {\n        const selected = selectInteraction?.getFeatures();\n        if (!selected || selected.getLength() === 0) return;\n        const source = entrySource();\n        selected.forEach((feature) => source.removeFeature(feature));\n        selected.clear();\n        ctx.state.dirty = true;\n    }\n\n    function clearAll() {\n        selectInteraction?.getFeatures().clear();\n        entrySource().clear();\n        ctx.state.dirty = true;\n    }\n\n    function toolButtonClass(active) {\n        return active\n            ? 'rounded-lg bg-brand-100 p-1.5 text-brand-700 ring-1 ring-inset ring-brand-300'\n            : 'rounded-lg p-1.5 text-slate-500 hover:bg-slate-100 hover:text-slate-700';\n    }\n\n    function renderToolbar() {\n        toolbarContainer.innerHTML = `\n            <div class=\"flex items-center gap-x-1 rounded-xl border border-slate-200 bg-white p-1.5 shadow-lg\">\n                ${TOOLS.map((tool) => `\n                <button type=\"button\" data-tool=\"${tool.key}\" title=\"${tool.label}\" class=\"${toolButtonClass(activeTool === tool.key)}\">\n                    <svg class=\"h-4 w-4\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\">${tool.icon}</svg>\n                </button>`).join('')}\n                <span class=\"mx-1 h-5 w-px bg-slate-200\"></span>\n                <input type=\"color\" data-role=\"color\" value=\"${currentColor}\" title=\"Color\"\n                       class=\"h-7 w-8 cursor-pointer rounded border border-slate-200\">\n                <input type=\"number\" data-role=\"width\" value=\"${currentWidth}\" min=\"1\" max=\"10\" step=\"0.5\" title=\"Line width / point size\"\n                       class=\"w-14 rounded-lg border-slate-200 px-1.5 py-1 text-xs\">\n                <span class=\"mx-1 h-5 w-px bg-slate-200\"></span>\n                <button type=\"button\" data-role=\"delete\" title=\"Delete selected\" class=\"rounded-lg p-1.5 text-slate-500 hover:bg-red-50 hover:text-red-600\">\n                    <svg class=\"h-4 w-4\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\"><path d=\"M3 6h18M8 6V4h8v2m-9 0 1 14h8l1-14\"/></svg>\n                </button>\n                <button type=\"button\" data-role=\"clear\" title=\"Clear drawing\" class=\"rounded-lg p-1.5 text-slate-500 hover:bg-red-50 hover:text-red-600\">\n                    <svg class=\"h-4 w-4\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\"><path d=\"M4 7h16M4 12h16M4 17h10\"/><path d=\"m17 15 5 5m0-5-5 5\"/></svg>\n                </button>\n                <button type=\"button\" data-role=\"close\" title=\"Close drawing toolbar\" class=\"rounded-lg p-1.5 text-slate-500 hover:bg-slate-100 hover:text-slate-700\">\n                    <svg class=\"h-4 w-4\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\"><path d=\"M18 6L6 18M6 6l12 12\"/></svg>\n                </button>\n            </div>\n        `;\n        toolbarContainer.querySelectorAll('[data-tool]').forEach((btn) => {\n            btn.addEventListener('click', () => activateTool(btn.dataset.tool));\n        });\n        toolbarContainer.querySelector('[data-role=\"color\"]').addEventListener('input', (e) => {\n            currentColor = e.target.value;\n            applyToSelected('color', currentColor);\n        });\n        toolbarContainer.querySelector('[data-role=\"width\"]').addEventListener('input', (e) => {\n            const value = Number(e.target.value) || DEFAULT_WIDTH;\n            currentWidth = value;\n            currentSize = Math.max(3, value * 3); // velikost bod\u016F odvozen\u00E1 od \u0161\u00ED\u0159ky\n            applyToSelected('width', currentWidth);\n            applyToSelected('size', currentSize);\n        });\n        toolbarContainer.querySelector('[data-role=\"delete\"]').addEventListener('click', deleteSelected);\n        toolbarContainer.querySelector('[data-role=\"clear\"]').addEventListener('click', clearAll);\n        toolbarContainer.querySelector('[data-role=\"close\"]').addEventListener('click', close);\n    }\n\n    /** Zm\u011Bna barvy/\u0161\u00ED\u0159ky se prom\u00EDtne i do pr\u00E1v\u011B vybran\u00FDch prvk\u016F. */\n    function applyToSelected(key, value) {\n        const selected = selectInteraction?.getFeatures();\n        if (!selected || selected.getLength() === 0) return;\n        selected.forEach((feature) => feature.set(key, value));\n        ctx.state.dirty = true;\n    }\n\n    function open() {\n        if (isOpen) return;\n        isOpen = true;\n        ctx.mapToolActive = true; // potla\u010D\u00ED identify klik po dobu kreslen\u00ED\n        createDrawingLayer(ctx);\n        addEditInteractions();\n        renderToolbar();\n        toolbarContainer.classList.remove('hidden');\n    }\n\n    function close() {\n        if (!isOpen) return;\n        isOpen = false;\n        removeDrawInteraction();\n        removeEditInteractions();\n        toolbarContainer.classList.add('hidden');\n        toolbarContainer.innerHTML = '';\n        ctx.mapToolActive = false;\n    }\n\n    // Kl\u00E1vesy: Delete = sma\u017E vybran\u00E9, Escape = vypni n\u00E1stroj (toolbar z\u016Fst\u00E1v\u00E1).\n    document.addEventListener('keydown', (event) => {\n        if (!isOpen) return;\n        const tag = document.activeElement?.tagName;\n        if (tag === 'INPUT' || tag === 'TEXTAREA') return;\n        if (event.key === 'Delete' || event.key === 'Backspace') {\n            deleteSelected();\n        } else if (event.key === 'Escape') {\n            if (drawInteraction) {\n                try {\n                    drawInteraction.abortDrawing();\n                } catch {\n                    /* \u017E\u00E1dn\u00FD rozkreslen\u00FD prvek */\n                }\n            }\n            removeDrawInteraction();\n            renderToolbar();\n        }\n    });\n\n    // Odebr\u00E1n\u00ED drawing vrstvy ze stromu zav\u0159e toolbar (vrstva u\u017E neexistuje).\n    on('layers:changed', ({ reason, entry }) => {\n        if (reason === 'remove' && entry?.dataType === 'drawing') close();\n    });\n\n    // Export/Save akce ze stromu vrstev (layers.js jen emituje ud\u00E1losti).\n    on('drawing:export', ({ uid } = {}) => exportDrawingGeoJSON(ctx, uid));\n    on('drawing:save-workspace', ({ uid } = {}) => {\n        if (!canSaveDrawingToWorkspace(ctx)) {\n            showToast('Sign in to save drawings to your Data workspace.', {\n                action: ctx.bootstrap.loginUrl ? { label: 'Sign in', href: ctx.bootstrap.loginUrl } : null,\n            });\n            return;\n        }\n        const toast = showToast('Saving to your Data workspace\u2026', { tone: 'busy' });\n        saveDrawingToWorkspace(ctx, uid, (text) => toast.update(text, { tone: 'busy' }))\n            .then(() => {\n                toast.update('Saved to your Data workspace.', {\n                    tone: 'ok',\n                    action: ctx.bootstrap.consoleUploadUrl\n                        ? { label: 'Open workspace', href: ctx.bootstrap.consoleUploadUrl }\n                        : null,\n                });\n            })\n            .catch((error) => {\n                toast.update(`Saving failed: ${saveErrorText(error)}`, { tone: 'error' });\n            });\n    });\n\n    return { open, close, isOpen: () => isOpen };\n}\n", "/**\n * @module ol/source/WMTS\n */\n\nimport {containsExtent} from '../extent.js';\nimport {equivalent, get as getProjection, transformExtent} from '../proj.js';\nimport {createFromCapabilitiesMatrixSet} from '../tilegrid/WMTS.js';\nimport {createFromTileUrlFunctions} from '../tileurlfunction.js';\nimport {appendParams, expandUrl} from '../uri.js';\nimport TileImage from './TileImage.js';\n\n/**\n * Request encoding. One of 'KVP', 'REST'.\n * @typedef {'KVP' | 'REST'} RequestEncoding\n */\n\n/**\n * @typedef {Object} Options\n * @property {import(\"./Source.js\").AttributionLike} [attributions] Attributions.\n * @property {boolean} [attributionsCollapsible=true] Attributions are collapsible.\n * @property {number} [cacheSize] Deprecated.  Use the cacheSize option on the layer instead.\n * @property {null|string} [crossOrigin] The `crossOrigin` attribute for loaded images.  Note that\n * you must provide a `crossOrigin` value if you want to access pixel data with the Canvas renderer.\n * See https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image for more detail.\n * @property {ReferrerPolicy} [referrerPolicy] The `referrerPolicy` property for loaded images.\n * @property {boolean} [interpolate=true] Use interpolated values when resampling.  By default,\n * linear interpolation is used when resampling.  Set to false to use the nearest neighbor instead.\n * @property {import(\"../tilegrid/WMTS.js\").default} tileGrid Tile grid.\n * @property {import(\"../proj.js\").ProjectionLike} [projection] Projection. Default is the view projection.\n * @property {number} [reprojectionErrorThreshold=0.5] Maximum allowed reprojection error (in pixels).\n * Higher values can increase reprojection performance, but decrease precision.\n * @property {RequestEncoding} [requestEncoding='KVP'] Request encoding.\n * @property {string} layer Layer name as advertised in the WMTS capabilities.\n * @property {string} style Style name as advertised in the WMTS capabilities.\n * @property {typeof import(\"../ImageTile.js\").default} [tileClass]  Class used to instantiate image tiles. Default is {@link module:ol/ImageTile~ImageTile}.\n * @property {number} [tilePixelRatio=1] The pixel ratio used by the tile service.\n * For example, if the tile service advertizes 256px by 256px tiles but actually sends 512px\n * by 512px images (for retina/hidpi devices) then `tilePixelRatio`\n * should be set to `2`.\n * @property {string} [format='image/jpeg'] Image format. Only used when `requestEncoding` is `'KVP'`.\n * @property {string} [version='1.0.0'] WMTS version.\n * @property {string} matrixSet Matrix set.\n * @property {!Object} [dimensions] Additional \"dimensions\" for tile requests.\n * This is an object with properties named like the advertised WMTS dimensions.\n * @property {string} [url]  A URL for the service.\n * For the RESTful request encoding, this is a URL\n * template.  For KVP encoding, it is normal URL. A `{?-?}` template pattern,\n * for example `subdomain{a-f}.domain.com`, may be used instead of defining\n * each one separately in the `urls` option.\n * @property {import(\"../Tile.js\").LoadFunction} [tileLoadFunction] Optional function to load a tile given a URL. The default is\n * ```js\n * function(imageTile, src) {\n *   imageTile.getImage().src = src;\n * };\n * ```\n * @property {Array<string>} [urls] An array of URLs.\n * Requests will be distributed among the URLs in this array.\n * @property {boolean} [wrapX=false] Whether to wrap the world horizontally.\n * @property {number} [transition] Duration of the opacity transition for rendering.\n * To disable the opacity transition, pass `transition: 0`.\n * @property {number|import(\"../array.js\").NearestDirectionFunction} [zDirection=0]\n * Choose whether to use tiles with a higher or lower zoom level when between integer\n * zoom levels. See {@link module:ol/tilegrid/TileGrid~TileGrid#getZForResolution}.\n */\n\n/**\n * @classdesc\n * Layer source for tile data from WMTS servers.\n * @api\n */\nclass WMTS extends TileImage {\n  /**\n   * @param {Options} options WMTS options.\n   */\n  constructor(options) {\n    // TODO: add support for TileMatrixLimits\n\n    const requestEncoding =\n      options.requestEncoding !== undefined ? options.requestEncoding : 'KVP';\n\n    // FIXME: should we create a default tileGrid?\n    // we could issue a getCapabilities xhr to retrieve missing configuration\n    const tileGrid = options.tileGrid;\n\n    let urls = options.urls;\n    if (urls === undefined && options.url !== undefined) {\n      urls = expandUrl(options.url);\n    }\n\n    super({\n      attributions: options.attributions,\n      attributionsCollapsible: options.attributionsCollapsible,\n      cacheSize: options.cacheSize,\n      crossOrigin: options.crossOrigin,\n      referrerPolicy: options.referrerPolicy,\n      interpolate: options.interpolate,\n      projection: options.projection,\n      reprojectionErrorThreshold: options.reprojectionErrorThreshold,\n      tileClass: options.tileClass,\n      tileGrid: tileGrid,\n      tileLoadFunction: options.tileLoadFunction,\n      tilePixelRatio: options.tilePixelRatio,\n      urls: urls,\n      wrapX: options.wrapX !== undefined ? options.wrapX : false,\n      transition: options.transition,\n      zDirection: options.zDirection,\n    });\n\n    /**\n     * @private\n     * @type {string}\n     */\n    this.version_ = options.version !== undefined ? options.version : '1.0.0';\n\n    /**\n     * @private\n     * @type {string}\n     */\n    this.format_ = options.format !== undefined ? options.format : 'image/jpeg';\n\n    /**\n     * @private\n     * @type {!Object}\n     */\n    this.dimensions_ =\n      options.dimensions !== undefined ? options.dimensions : {};\n\n    /**\n     * @private\n     * @type {string}\n     */\n    this.layer_ = options.layer;\n\n    /**\n     * @private\n     * @type {string}\n     */\n    this.matrixSet_ = options.matrixSet;\n\n    /**\n     * @private\n     * @type {string}\n     */\n    this.style_ = options.style;\n\n    // FIXME: should we guess this requestEncoding from options.url(s)\n    //        structure? that would mean KVP only if a template is not provided.\n\n    /**\n     * @private\n     * @type {RequestEncoding}\n     */\n    this.requestEncoding_ = requestEncoding;\n\n    this.setKey(this.getKeyForDimensions_());\n\n    if (urls && urls.length > 0) {\n      this.tileUrlFunction = createFromTileUrlFunctions(\n        urls.map(this.createFromWMTSTemplate.bind(this)),\n      );\n    }\n  }\n\n  /**\n   * Set the URLs to use for requests.\n   * URLs may contain OGC conform URL Template Variables: {TileMatrix}, {TileRow}, {TileCol}.\n   * @param {Array<string>} urls URLs.\n   * @override\n   */\n  setUrls(urls) {\n    this.urls = urls;\n    const key = urls.join('\\n');\n    this.setTileUrlFunction(\n      createFromTileUrlFunctions(\n        urls.map(this.createFromWMTSTemplate.bind(this)),\n      ),\n      key,\n    );\n  }\n\n  /**\n   * Get the dimensions, i.e. those passed to the constructor through the\n   * \"dimensions\" option, and possibly updated using the updateDimensions\n   * method.\n   * @return {!Object} Dimensions.\n   * @api\n   */\n  getDimensions() {\n    return this.dimensions_;\n  }\n\n  /**\n   * Return the image format of the WMTS source.\n   * @return {string} Format.\n   * @api\n   */\n  getFormat() {\n    return this.format_;\n  }\n\n  /**\n   * Return the layer of the WMTS source.\n   * @return {string} Layer.\n   * @api\n   */\n  getLayer() {\n    return this.layer_;\n  }\n\n  /**\n   * Return the matrix set of the WMTS source.\n   * @return {string} MatrixSet.\n   * @api\n   */\n  getMatrixSet() {\n    return this.matrixSet_;\n  }\n\n  /**\n   * Return the request encoding, either \"KVP\" or \"REST\".\n   * @return {RequestEncoding} Request encoding.\n   * @api\n   */\n  getRequestEncoding() {\n    return this.requestEncoding_;\n  }\n\n  /**\n   * Return the style of the WMTS source.\n   * @return {string} Style.\n   * @api\n   */\n  getStyle() {\n    return this.style_;\n  }\n\n  /**\n   * Return the version of the WMTS source.\n   * @return {string} Version.\n   * @api\n   */\n  getVersion() {\n    return this.version_;\n  }\n\n  /**\n   * @private\n   * @return {string} The key for the current dimensions.\n   */\n  getKeyForDimensions_() {\n    const res = this.urls ? this.urls.slice(0) : [];\n    for (const key in this.dimensions_) {\n      res.push(key + '-' + this.dimensions_[key]);\n    }\n    return res.join('/');\n  }\n\n  /**\n   * Update the dimensions.\n   * @param {Object} dimensions Dimensions.\n   * @api\n   */\n  updateDimensions(dimensions) {\n    Object.assign(this.dimensions_, dimensions);\n    this.setKey(this.getKeyForDimensions_());\n  }\n\n  /**\n   * @param {string} template Template.\n   * @return {import(\"../Tile.js\").UrlFunction} Tile URL function.\n   */\n  createFromWMTSTemplate(template) {\n    const requestEncoding = this.requestEncoding_;\n\n    // context property names are lower case to allow for a case insensitive\n    // replacement as some services use different naming conventions\n    const context = {\n      'layer': this.layer_,\n      'style': this.style_,\n      'tilematrixset': this.matrixSet_,\n    };\n\n    if (requestEncoding == 'KVP') {\n      Object.assign(context, {\n        'Service': 'WMTS',\n        'Request': 'GetTile',\n        'Version': this.version_,\n        'Format': this.format_,\n      });\n    }\n\n    // TODO: we may want to create our own appendParams function so that params\n    // order conforms to wmts spec guidance, and so that we can avoid to escape\n    // special template params\n\n    template =\n      requestEncoding == 'KVP'\n        ? appendParams(template, context)\n        : template.replace(/\\{(\\w+?)\\}/g, function (m, p) {\n            return p.toLowerCase() in context ? context[p.toLowerCase()] : m;\n          });\n\n    const tileGrid = /** @type {import(\"../tilegrid/WMTS.js\").default} */ (\n      this.tileGrid\n    );\n    const dimensions = this.dimensions_;\n\n    return (\n      /**\n       * @param {import(\"../tilecoord.js\").TileCoord} tileCoord Tile coordinate.\n       * @param {number} pixelRatio Pixel ratio.\n       * @param {import(\"../proj/Projection.js\").default} projection Projection.\n       * @return {string|undefined} Tile URL.\n       */\n      function (tileCoord, pixelRatio, projection) {\n        if (!tileCoord) {\n          return undefined;\n        }\n        const localContext = {\n          'TileMatrix': tileGrid.getMatrixId(tileCoord[0]),\n          'TileCol': tileCoord[1],\n          'TileRow': tileCoord[2],\n        };\n        Object.assign(localContext, dimensions);\n        let url = template;\n        if (requestEncoding == 'KVP') {\n          url = appendParams(url, localContext);\n        } else {\n          url = url.replace(/\\{(\\w+?)\\}/g, function (m, p) {\n            return encodeURIComponent(localContext[p]);\n          });\n        }\n        return url;\n      }\n    );\n  }\n}\n\nexport default WMTS;\n\n/**\n * Generate source options from a capabilities object.\n * @param {Object} wmtsCap An object representing the capabilities document.\n * @param {!Object} config Configuration properties for the layer.  Defaults for\n *                  the layer will apply if not provided.\n *\n * Required config properties:\n *  - layer - {string} The layer identifier.\n *\n * Optional config properties:\n *  - matrixSet - {string} The matrix set identifier, required if there is\n *       more than one matrix set in the layer capabilities.\n *  - projection - {string} The desired CRS when no matrixSet is specified.\n *       eg: \"EPSG:3857\". If the desired projection is not available,\n *       an error is thrown.\n *  - requestEncoding - {string} url encoding format for the layer. Default is\n *       the first tile url format found in the GetCapabilities response.\n *  - style - {string} The name of the style\n *  - format - {string} Image format for the layer. Default is the first\n *       format returned in the GetCapabilities response.\n *  - crossOrigin - {string|null|undefined} Cross origin. Default is `undefined`.\n * @return {Options|null} WMTS source options object or `null` if the layer was not found.\n * @api\n */\nexport function optionsFromCapabilities(wmtsCap, config) {\n  const layers = wmtsCap['Contents']['Layer'];\n  const l = layers?.find(function (elt) {\n    return elt['Identifier'] == config['layer'];\n  });\n  if (!l) {\n    return null;\n  }\n  const tileMatrixSets = wmtsCap['Contents']['TileMatrixSet'];\n  let idx;\n  if (l['TileMatrixSetLink'].length > 1) {\n    if ('projection' in config) {\n      idx = l['TileMatrixSetLink'].findIndex(function (elt) {\n        const tileMatrixSet = tileMatrixSets.find(function (el) {\n          return el['Identifier'] == elt['TileMatrixSet'];\n        });\n        const supportedCRS = tileMatrixSet['SupportedCRS'];\n        const proj1 = getProjection(supportedCRS);\n        const proj2 = getProjection(config['projection']);\n        if (proj1 && proj2) {\n          return equivalent(proj1, proj2);\n        }\n        return supportedCRS == config['projection'];\n      });\n    } else {\n      idx = l['TileMatrixSetLink'].findIndex(function (elt) {\n        return elt['TileMatrixSet'] == config['matrixSet'];\n      });\n    }\n  } else {\n    idx = 0;\n  }\n  if (idx < 0) {\n    idx = 0;\n  }\n  const matrixSet =\n    /** @type {string} */\n    (l['TileMatrixSetLink'][idx]['TileMatrixSet']);\n  const matrixLimits =\n    /** @type {Array<Object>} */\n    (l['TileMatrixSetLink'][idx]['TileMatrixSetLimits']);\n\n  let format = /** @type {string} */ (l['Format'][0]);\n  if ('format' in config) {\n    format = config['format'];\n  }\n  idx = l['Style'].findIndex(function (elt) {\n    if ('style' in config) {\n      return elt['Title'] == config['style'];\n    }\n    return elt['isDefault'];\n  });\n  if (idx < 0) {\n    idx = 0;\n  }\n  const style = /** @type {string} */ (l['Style'][idx]['Identifier']);\n\n  const dimensions = {};\n  if ('Dimension' in l) {\n    l['Dimension'].forEach(function (elt, index, array) {\n      const key = elt['Identifier'];\n      let value = elt['Default'];\n      if (value === undefined) {\n        value = elt['Value'][0];\n      }\n      dimensions[key] = value;\n    });\n  }\n\n  const matrixSets = wmtsCap['Contents']['TileMatrixSet'];\n  const matrixSetObj = matrixSets.find(function (elt) {\n    return elt['Identifier'] == matrixSet;\n  });\n\n  let projection;\n  const code = matrixSetObj['SupportedCRS'];\n  if (code) {\n    projection = getProjection(code);\n  }\n  if ('projection' in config) {\n    const projConfig = getProjection(config['projection']);\n    if (projConfig) {\n      if (!projection || equivalent(projConfig, projection)) {\n        projection = projConfig;\n      }\n    }\n  }\n\n  let wrapX = false;\n  const switchXY = projection.getAxisOrientation().startsWith('ne');\n\n  let matrix = matrixSetObj.TileMatrix[0];\n\n  // create default matrixLimit\n  let selectedMatrixLimit = {\n    MinTileCol: 0,\n    MinTileRow: 0,\n    // subtract one to end up at tile top left\n    MaxTileCol: matrix.MatrixWidth - 1,\n    MaxTileRow: matrix.MatrixHeight - 1,\n  };\n\n  //in case of matrix limits, use matrix limits to calculate extent\n  if (matrixLimits) {\n    selectedMatrixLimit = matrixLimits[matrixLimits.length - 1];\n    const m = matrixSetObj.TileMatrix.find(\n      (tileMatrixValue) =>\n        tileMatrixValue.Identifier === selectedMatrixLimit.TileMatrix ||\n        matrixSetObj.Identifier + ':' + tileMatrixValue.Identifier ===\n          selectedMatrixLimit.TileMatrix,\n    );\n    if (m) {\n      matrix = m;\n    }\n  }\n\n  const layerExtent = l['BoundingBox']?.find(\n    (bbox) =>\n      getProjection(bbox.crs) &&\n      equivalent(getProjection(bbox.crs), projection),\n  );\n\n  const resolution =\n    (matrix.ScaleDenominator * 0.00028) / projection.getMetersPerUnit(); // WMTS 1.0.0: standardized rendering pixel size\n  const origin = switchXY\n    ? [matrix.TopLeftCorner[1], matrix.TopLeftCorner[0]]\n    : matrix.TopLeftCorner;\n  const tileSpanX = matrix.TileWidth * resolution;\n  const tileSpanY = matrix.TileHeight * resolution;\n  let matrixSetExtent = layerExtent?.extent ?? matrixSetObj['BoundingBox'];\n  if (matrixSetExtent && switchXY) {\n    matrixSetExtent = [\n      matrixSetExtent[1],\n      matrixSetExtent[0],\n      matrixSetExtent[3],\n      matrixSetExtent[2],\n    ];\n  }\n  let extent = [\n    origin[0] + tileSpanX * selectedMatrixLimit.MinTileCol,\n    // add one to get proper bottom/right coordinate\n    origin[1] - tileSpanY * (1 + selectedMatrixLimit.MaxTileRow),\n    origin[0] + tileSpanX * (1 + selectedMatrixLimit.MaxTileCol),\n    origin[1] - tileSpanY * selectedMatrixLimit.MinTileRow,\n  ];\n\n  if (\n    matrixSetExtent !== undefined &&\n    !containsExtent(matrixSetExtent, extent)\n  ) {\n    const wgs84BoundingBox = l['WGS84BoundingBox'];\n    const wgs84ProjectionExtent = getProjection('EPSG:4326').getExtent();\n    extent = matrixSetExtent;\n    if (wgs84BoundingBox) {\n      wrapX =\n        wgs84BoundingBox[0] === wgs84ProjectionExtent[0] &&\n        wgs84BoundingBox[2] === wgs84ProjectionExtent[2];\n    } else {\n      const wgs84MatrixSetExtent = transformExtent(\n        matrixSetExtent,\n        matrixSetObj['SupportedCRS'],\n        'EPSG:4326',\n      );\n      // Ignore slight deviation from the correct x limits\n      wrapX =\n        wgs84MatrixSetExtent[0] - 1e-10 <= wgs84ProjectionExtent[0] &&\n        wgs84MatrixSetExtent[2] + 1e-10 >= wgs84ProjectionExtent[2];\n    }\n  }\n\n  const tileGrid = createFromCapabilitiesMatrixSet(\n    matrixSetObj,\n    extent,\n    matrixLimits,\n  );\n\n  /** @type {!Array<string>} */\n  const urls = [];\n  let requestEncoding = config['requestEncoding'];\n  requestEncoding = requestEncoding !== undefined ? requestEncoding : '';\n\n  if (\n    'OperationsMetadata' in wmtsCap &&\n    'GetTile' in wmtsCap['OperationsMetadata']\n  ) {\n    const gets = wmtsCap['OperationsMetadata']['GetTile']['DCP']['HTTP']['Get'];\n\n    for (let i = 0, ii = gets.length; i < ii; ++i) {\n      if (gets[i]['Constraint']) {\n        const constraint = gets[i]['Constraint'].find(function (element) {\n          return element['name'] == 'GetEncoding';\n        });\n        const encodings = constraint['AllowedValues']['Value'];\n\n        if (requestEncoding === '') {\n          // requestEncoding not provided, use the first encoding from the list\n          requestEncoding = encodings[0];\n        }\n        if (requestEncoding === 'KVP') {\n          if (encodings.includes('KVP')) {\n            urls.push(/** @type {string} */ (gets[i]['href']));\n          }\n        } else {\n          break;\n        }\n      } else if (gets[i]['href']) {\n        requestEncoding = 'KVP';\n        urls.push(/** @type {string} */ (gets[i]['href']));\n      }\n    }\n  }\n  if (urls.length === 0) {\n    requestEncoding = 'REST';\n    l['ResourceURL'].forEach(function (element) {\n      if (element['resourceType'] === 'tile') {\n        format = element['format'];\n        urls.push(/** @type {string} */ (element['template']));\n      }\n    });\n  }\n\n  return {\n    urls: urls,\n    layer: config['layer'],\n    matrixSet: matrixSet,\n    format: format,\n    projection: projection,\n    requestEncoding: requestEncoding,\n    tileGrid: tileGrid,\n    style: style,\n    dimensions: dimensions,\n    wrapX: wrapX,\n    crossOrigin: config['crossOrigin'],\n  };\n}\n", "/**\n * @module ol/format/OWS\n */\nimport {\n  makeObjectPropertyPusher,\n  makeObjectPropertySetter,\n  makeStructureNS,\n  pushParseAndPop,\n} from '../xml.js';\nimport XML from './XML.js';\nimport {readHref} from './xlink.js';\nimport {readString} from './xsd.js';\n\n/**\n * @const\n * @type {Array<null|string>}\n */\nconst NAMESPACE_URIS = [null, 'http://www.opengis.net/ows/1.1'];\n\n/**\n * @const\n * @type {Object<string, Object<string, import(\"../xml.js\").Parser>>}\n */\n// @ts-ignore\nconst PARSERS = makeStructureNS(NAMESPACE_URIS, {\n  'ServiceIdentification': makeObjectPropertySetter(readServiceIdentification),\n  'ServiceProvider': makeObjectPropertySetter(readServiceProvider),\n  'OperationsMetadata': makeObjectPropertySetter(readOperationsMetadata),\n});\n\nclass OWS extends XML {\n  constructor() {\n    super();\n  }\n\n  /**\n   * @param {Element} node Node.\n   * @return {Object|null} Object\n   * @override\n   */\n  readFromNode(node) {\n    const owsObject = pushParseAndPop({}, PARSERS, node, []);\n    return owsObject ? owsObject : null;\n  }\n}\n\n/**\n * @const\n * @type {Object<string, Object<string, import(\"../xml.js\").Parser>>}\n */\n// @ts-ignore\nconst ADDRESS_PARSERS = makeStructureNS(NAMESPACE_URIS, {\n  'DeliveryPoint': makeObjectPropertySetter(readString),\n  'City': makeObjectPropertySetter(readString),\n  'AdministrativeArea': makeObjectPropertySetter(readString),\n  'PostalCode': makeObjectPropertySetter(readString),\n  'Country': makeObjectPropertySetter(readString),\n  'ElectronicMailAddress': makeObjectPropertySetter(readString),\n});\n\n/**\n * @const\n * @type {Object<string, Object<string, import(\"../xml.js\").Parser>>}\n */\n// @ts-ignore\nconst ALLOWED_VALUES_PARSERS = makeStructureNS(NAMESPACE_URIS, {\n  'Value': makeObjectPropertyPusher(readValue),\n});\n\n/**\n * @const\n * @type {Object<string, Object<string, import(\"../xml.js\").Parser>>}\n */\n// @ts-ignore\nconst CONSTRAINT_PARSERS = makeStructureNS(NAMESPACE_URIS, {\n  'AllowedValues': makeObjectPropertySetter(readAllowedValues),\n});\n\n/**\n * @const\n * @type {Object<string, Object<string, import(\"../xml.js\").Parser>>}\n */\n// @ts-ignore\nconst CONTACT_INFO_PARSERS = makeStructureNS(NAMESPACE_URIS, {\n  'Phone': makeObjectPropertySetter(readPhone),\n  'Address': makeObjectPropertySetter(readAddress),\n});\n\n/**\n * @const\n * @type {Object<string, Object<string, import(\"../xml.js\").Parser>>}\n */\n// @ts-ignore\nconst DCP_PARSERS = makeStructureNS(NAMESPACE_URIS, {\n  'HTTP': makeObjectPropertySetter(readHttp),\n});\n\n/**\n * @const\n * @type {Object<string, Object<string, import(\"../xml.js\").Parser>>}\n */\n// @ts-ignore\nconst HTTP_PARSERS = makeStructureNS(NAMESPACE_URIS, {\n  'Get': makeObjectPropertyPusher(readGet),\n  'Post': undefined, // TODO\n});\n\n/**\n * @const\n * @type {Object<string, Object<string, import(\"../xml.js\").Parser>>}\n */\n// @ts-ignore\nconst OPERATION_PARSERS = makeStructureNS(NAMESPACE_URIS, {\n  'DCP': makeObjectPropertySetter(readDcp),\n});\n\n/**\n * @const\n * @type {Object<string, Object<string, import(\"../xml.js\").Parser>>}\n */\n// @ts-ignore\nconst OPERATIONS_METADATA_PARSERS = makeStructureNS(NAMESPACE_URIS, {\n  'Operation': readOperation,\n});\n\n/**\n * @const\n * @type {Object<string, Object<string, import(\"../xml.js\").Parser>>}\n */\n// @ts-ignore\nconst PHONE_PARSERS = makeStructureNS(NAMESPACE_URIS, {\n  'Voice': makeObjectPropertySetter(readString),\n  'Facsimile': makeObjectPropertySetter(readString),\n});\n\n/**\n * @const\n * @type {Object<string, Object<string, import(\"../xml.js\").Parser>>}\n */\n// @ts-ignore\nconst REQUEST_METHOD_PARSERS = makeStructureNS(NAMESPACE_URIS, {\n  'Constraint': makeObjectPropertyPusher(readConstraint),\n});\n\n/**\n * @const\n * @type {Object<string, Object<string, import(\"../xml.js\").Parser>>}\n */\n// @ts-ignore\nconst SERVICE_CONTACT_PARSERS = makeStructureNS(NAMESPACE_URIS, {\n  'IndividualName': makeObjectPropertySetter(readString),\n  'PositionName': makeObjectPropertySetter(readString),\n  'ContactInfo': makeObjectPropertySetter(readContactInfo),\n});\n\n/**\n * @const\n * @type {Object<string, Object<string, import(\"../xml.js\").Parser>>}\n */\n// @ts-ignore\nconst SERVICE_IDENTIFICATION_PARSERS = makeStructureNS(NAMESPACE_URIS, {\n  'Abstract': makeObjectPropertySetter(readString),\n  'AccessConstraints': makeObjectPropertySetter(readString),\n  'Fees': makeObjectPropertySetter(readString),\n  'Title': makeObjectPropertySetter(readString),\n  'ServiceTypeVersion': makeObjectPropertySetter(readString),\n  'ServiceType': makeObjectPropertySetter(readString),\n});\n\n/**\n * @const\n * @type {Object<string, Object<string, import(\"../xml.js\").Parser>>}\n */\n// @ts-ignore\nconst SERVICE_PROVIDER_PARSERS = makeStructureNS(NAMESPACE_URIS, {\n  'ProviderName': makeObjectPropertySetter(readString),\n  'ProviderSite': makeObjectPropertySetter(readHref),\n  'ServiceContact': makeObjectPropertySetter(readServiceContact),\n});\n\n/**\n * @param {Element} node Node.\n * @param {Array<*>} objectStack Object stack.\n * @return {Object|undefined} The address.\n */\nfunction readAddress(node, objectStack) {\n  return pushParseAndPop({}, ADDRESS_PARSERS, node, objectStack);\n}\n\n/**\n * @param {Element} node Node.\n * @param {Array<*>} objectStack Object stack.\n * @return {Object|undefined} The values.\n */\nfunction readAllowedValues(node, objectStack) {\n  return pushParseAndPop({}, ALLOWED_VALUES_PARSERS, node, objectStack);\n}\n\n/**\n * @param {Element} node Node.\n * @param {Array<*>} objectStack Object stack.\n * @return {Object|undefined} The constraint.\n */\nfunction readConstraint(node, objectStack) {\n  const name = node.getAttribute('name');\n  if (!name) {\n    return undefined;\n  }\n  return pushParseAndPop({'name': name}, CONSTRAINT_PARSERS, node, objectStack);\n}\n\n/**\n * @param {Element} node Node.\n * @param {Array<*>} objectStack Object stack.\n * @return {Object|undefined} The contact info.\n */\nfunction readContactInfo(node, objectStack) {\n  return pushParseAndPop({}, CONTACT_INFO_PARSERS, node, objectStack);\n}\n\n/**\n * @param {Element} node Node.\n * @param {Array<*>} objectStack Object stack.\n * @return {Object|undefined} The DCP.\n */\nfunction readDcp(node, objectStack) {\n  return pushParseAndPop({}, DCP_PARSERS, node, objectStack);\n}\n\n/**\n * @param {Element} node Node.\n * @param {Array<*>} objectStack Object stack.\n * @return {Object|undefined} The GET object.\n */\nfunction readGet(node, objectStack) {\n  const href = readHref(node);\n  if (!href) {\n    return undefined;\n  }\n  return pushParseAndPop(\n    {'href': href},\n    REQUEST_METHOD_PARSERS,\n    node,\n    objectStack,\n  );\n}\n\n/**\n * @param {Element} node Node.\n * @param {Array<*>} objectStack Object stack.\n * @return {Object|undefined} The HTTP object.\n */\nfunction readHttp(node, objectStack) {\n  return pushParseAndPop({}, HTTP_PARSERS, node, objectStack);\n}\n\n/**\n * @param {Element} node Node.\n * @param {Array<*>} objectStack Object stack.\n * @return {Object|undefined} The operation.\n */\nfunction readOperation(node, objectStack) {\n  const name = node.getAttribute('name');\n  const value = pushParseAndPop({}, OPERATION_PARSERS, node, objectStack);\n  if (!value) {\n    return undefined;\n  }\n  const object = /** @type {Object} */ (objectStack[objectStack.length - 1]);\n  object[name] = value;\n}\n\n/**\n * @param {Element} node Node.\n * @param {Array<*>} objectStack Object stack.\n * @return {Object|undefined} The operations metadata.\n */\nfunction readOperationsMetadata(node, objectStack) {\n  return pushParseAndPop({}, OPERATIONS_METADATA_PARSERS, node, objectStack);\n}\n\n/**\n * @param {Element} node Node.\n * @param {Array<*>} objectStack Object stack.\n * @return {Object|undefined} The phone.\n */\nfunction readPhone(node, objectStack) {\n  return pushParseAndPop({}, PHONE_PARSERS, node, objectStack);\n}\n\n/**\n * @param {Element} node Node.\n * @param {Array<*>} objectStack Object stack.\n * @return {Object|undefined} The service identification.\n */\nfunction readServiceIdentification(node, objectStack) {\n  return pushParseAndPop({}, SERVICE_IDENTIFICATION_PARSERS, node, objectStack);\n}\n\n/**\n * @param {Element} node Node.\n * @param {Array<*>} objectStack Object stack.\n * @return {Object|undefined} The service contact.\n */\nfunction readServiceContact(node, objectStack) {\n  return pushParseAndPop({}, SERVICE_CONTACT_PARSERS, node, objectStack);\n}\n\n/**\n * @param {Element} node Node.\n * @param {Array<*>} objectStack Object stack.\n * @return {Object|undefined} The service provider.\n */\nfunction readServiceProvider(node, objectStack) {\n  return pushParseAndPop({}, SERVICE_PROVIDER_PARSERS, node, objectStack);\n}\n\n/**\n * @param {Node} node Node.\n * @param {Array<*>} objectStack Object stack.\n * @return {string|undefined} The value.\n */\nfunction readValue(node, objectStack) {\n  return readString(node);\n}\n\nexport default OWS;\n", "/**\n * @module ol/format/WMTSCapabilities\n */\nimport {boundingExtent} from '../extent.js';\nimport {\n  makeArrayPusher,\n  makeObjectPropertyPusher,\n  makeObjectPropertySetter,\n  makeStructureNS,\n  pushParseAndPop,\n} from '../xml.js';\nimport OWS from './OWS.js';\nimport XML from './XML.js';\nimport {readHref} from './xlink.js';\nimport {readDecimal, readPositiveInteger, readString} from './xsd.js';\n\n/**\n * @const\n * @type {Array<null|string>}\n */\nconst NAMESPACE_URIS = [null, 'http://www.opengis.net/wmts/1.0'];\n\n/**\n * @const\n * @type {Array<null|string>}\n */\nconst OWS_NAMESPACE_URIS = [null, 'http://www.opengis.net/ows/1.1'];\n\n/**\n * @const\n * @type {Object<string, Object<string, import(\"../xml.js\").Parser>>}\n */\n// @ts-ignore\nconst PARSERS = makeStructureNS(NAMESPACE_URIS, {\n  'Contents': makeObjectPropertySetter(readContents),\n});\n\n/**\n * @classdesc\n * Format for reading WMTS capabilities data.\n *\n * @api\n */\nclass WMTSCapabilities extends XML {\n  constructor() {\n    super();\n\n    /**\n     * @type {OWS}\n     * @private\n     */\n    this.owsParser_ = new OWS();\n  }\n\n  /**\n   * @param {Element} node Node.\n   * @return {Object|null} Object\n   * @override\n   */\n  readFromNode(node) {\n    let version = node.getAttribute('version');\n    if (version) {\n      version = version.trim();\n    }\n    let WMTSCapabilityObject = this.owsParser_.readFromNode(node);\n    if (!WMTSCapabilityObject) {\n      return null;\n    }\n    WMTSCapabilityObject['version'] = version;\n    WMTSCapabilityObject = pushParseAndPop(\n      WMTSCapabilityObject,\n      PARSERS,\n      node,\n      [],\n    );\n    return WMTSCapabilityObject ? WMTSCapabilityObject : null;\n  }\n}\n\n/**\n * @const\n * @type {Object<string, Object<string, import(\"../xml.js\").Parser>>}\n */\n// @ts-ignore\nconst CONTENTS_PARSERS = makeStructureNS(NAMESPACE_URIS, {\n  'Layer': makeObjectPropertyPusher(readLayer),\n  'TileMatrixSet': makeObjectPropertyPusher(readTileMatrixSet),\n});\n\n/**\n * @const\n * @type {Object<string, Object<string, import(\"../xml.js\").Parser>>}\n */\n// @ts-ignore\nconst LAYER_PARSERS = makeStructureNS(\n  NAMESPACE_URIS,\n  {\n    'Style': makeObjectPropertyPusher(readStyle),\n    'Format': makeObjectPropertyPusher(readString),\n    'TileMatrixSetLink': makeObjectPropertyPusher(readTileMatrixSetLink),\n    'Dimension': makeObjectPropertyPusher(readDimensions),\n    'ResourceURL': makeObjectPropertyPusher(readResourceUrl),\n  },\n  makeStructureNS(OWS_NAMESPACE_URIS, {\n    'Title': makeObjectPropertySetter(readString),\n    'Abstract': makeObjectPropertySetter(readString),\n    'WGS84BoundingBox': makeObjectPropertySetter(readBoundingBox),\n    'BoundingBox': makeObjectPropertyPusher(readBoundingBoxWithCrs),\n    'Identifier': makeObjectPropertySetter(readString),\n  }),\n);\n\n/**\n * @const\n * @type {Object<string, Object<string, import(\"../xml.js\").Parser>>}\n */\n// @ts-ignore\nconst STYLE_PARSERS = makeStructureNS(\n  NAMESPACE_URIS,\n  {\n    'LegendURL': makeObjectPropertyPusher(readLegendUrl),\n  },\n  makeStructureNS(OWS_NAMESPACE_URIS, {\n    'Title': makeObjectPropertySetter(readString),\n    'Identifier': makeObjectPropertySetter(readString),\n  }),\n);\n\n/**\n * @const\n * @type {Object<string, Object<string, import(\"../xml.js\").Parser>>}\n */\n// @ts-ignore\nconst TMS_LINKS_PARSERS = makeStructureNS(NAMESPACE_URIS, {\n  'TileMatrixSet': makeObjectPropertySetter(readString),\n  'TileMatrixSetLimits': makeObjectPropertySetter(readTileMatrixLimitsList),\n});\n\n/**\n * @const\n * @type {Object<string, Object<string, import(\"../xml.js\").Parser>>}\n */\n// @ts-ignore\nconst TMS_LIMITS_LIST_PARSERS = makeStructureNS(NAMESPACE_URIS, {\n  'TileMatrixLimits': makeArrayPusher(readTileMatrixLimits),\n});\n\n/**\n * @const\n * @type {Object<string, Object<string, import(\"../xml.js\").Parser>>}\n */\n// @ts-ignore\nconst TMS_LIMITS_PARSERS = makeStructureNS(NAMESPACE_URIS, {\n  'TileMatrix': makeObjectPropertySetter(readString),\n  'MinTileRow': makeObjectPropertySetter(readPositiveInteger),\n  'MaxTileRow': makeObjectPropertySetter(readPositiveInteger),\n  'MinTileCol': makeObjectPropertySetter(readPositiveInteger),\n  'MaxTileCol': makeObjectPropertySetter(readPositiveInteger),\n});\n\n/**\n * @const\n * @type {Object<string, Object<string, import(\"../xml.js\").Parser>>}\n */\n// @ts-ignore\nconst DIMENSION_PARSERS = makeStructureNS(\n  NAMESPACE_URIS,\n  {\n    'Default': makeObjectPropertySetter(readString),\n    'Value': makeObjectPropertyPusher(readString),\n  },\n  makeStructureNS(OWS_NAMESPACE_URIS, {\n    'Identifier': makeObjectPropertySetter(readString),\n  }),\n);\n\n/**\n * @const\n * @type {Object<string, Object<string, import(\"../xml.js\").Parser>>}\n */\n// @ts-ignore\nconst WGS84_BBOX_READERS = makeStructureNS(OWS_NAMESPACE_URIS, {\n  'LowerCorner': makeArrayPusher(readCoordinates),\n  'UpperCorner': makeArrayPusher(readCoordinates),\n});\n\n/**\n * @const\n * @type {Object<string, Object<string, import(\"../xml.js\").Parser>>}\n */\n// @ts-ignore\nconst TMS_PARSERS = makeStructureNS(\n  NAMESPACE_URIS,\n  {\n    'WellKnownScaleSet': makeObjectPropertySetter(readString),\n    'TileMatrix': makeObjectPropertyPusher(readTileMatrix),\n  },\n  makeStructureNS(OWS_NAMESPACE_URIS, {\n    'SupportedCRS': makeObjectPropertySetter(readString),\n    'Identifier': makeObjectPropertySetter(readString),\n    'BoundingBox': makeObjectPropertySetter(readBoundingBox),\n  }),\n);\n\n/**\n * @const\n * @type {Object<string, Object<string, import(\"../xml.js\").Parser>>}\n */\n// @ts-ignore\nconst TM_PARSERS = makeStructureNS(\n  NAMESPACE_URIS,\n  {\n    'TopLeftCorner': makeObjectPropertySetter(readCoordinates),\n    'ScaleDenominator': makeObjectPropertySetter(readDecimal),\n    'TileWidth': makeObjectPropertySetter(readPositiveInteger),\n    'TileHeight': makeObjectPropertySetter(readPositiveInteger),\n    'MatrixWidth': makeObjectPropertySetter(readPositiveInteger),\n    'MatrixHeight': makeObjectPropertySetter(readPositiveInteger),\n  },\n  makeStructureNS(OWS_NAMESPACE_URIS, {\n    'Identifier': makeObjectPropertySetter(readString),\n  }),\n);\n\n/**\n * @param {Element} node Node.\n * @param {Array<*>} objectStack Object stack.\n * @return {Object|undefined} Attribution object.\n */\nfunction readContents(node, objectStack) {\n  return pushParseAndPop({}, CONTENTS_PARSERS, node, objectStack);\n}\n\n/**\n * @param {Element} node Node.\n * @param {Array<*>} objectStack Object stack.\n * @return {Object|undefined} Layers object.\n */\nfunction readLayer(node, objectStack) {\n  return pushParseAndPop({}, LAYER_PARSERS, node, objectStack);\n}\n\n/**\n * @param {Element} node Node.\n * @param {Array<*>} objectStack Object stack.\n * @return {Object|undefined} Tile Matrix Set object.\n */\nfunction readTileMatrixSet(node, objectStack) {\n  return pushParseAndPop({}, TMS_PARSERS, node, objectStack);\n}\n\n/**\n * @param {Element} node Node.\n * @param {Array<*>} objectStack Object stack.\n * @return {Object|undefined} Style object.\n */\nfunction readStyle(node, objectStack) {\n  const style = pushParseAndPop({}, STYLE_PARSERS, node, objectStack);\n  if (!style) {\n    return undefined;\n  }\n  const isDefault = node.getAttribute('isDefault') === 'true';\n  style['isDefault'] = isDefault;\n  return style;\n}\n\n/**\n * @param {Element} node Node.\n * @param {Array<*>} objectStack Object stack.\n * @return {Object|undefined} Tile Matrix Set Link object.\n */\nfunction readTileMatrixSetLink(node, objectStack) {\n  return pushParseAndPop({}, TMS_LINKS_PARSERS, node, objectStack);\n}\n\n/**\n * @param {Element} node Node.\n * @param {Array<*>} objectStack Object stack.\n * @return {Object|undefined} Dimension object.\n */\nfunction readDimensions(node, objectStack) {\n  return pushParseAndPop({}, DIMENSION_PARSERS, node, objectStack);\n}\n\n/**\n * @param {Element} node Node.\n * @param {Array<*>} objectStack Object stack.\n * @return {Object|undefined} Resource URL object.\n */\nfunction readResourceUrl(node, objectStack) {\n  const format = node.getAttribute('format');\n  const template = node.getAttribute('template');\n  const resourceType = node.getAttribute('resourceType');\n  const resource = {};\n  if (format) {\n    resource['format'] = format;\n  }\n  if (template) {\n    resource['template'] = template;\n  }\n  if (resourceType) {\n    resource['resourceType'] = resourceType;\n  }\n  return resource;\n}\n\n/**\n * @param {Element} node Node.\n * @param {Array<*>} objectStack Object stack.\n * @return {Object|undefined} BBox object.\n */\nfunction readBoundingBox(node, objectStack) {\n  const coordinates = pushParseAndPop(\n    [],\n    WGS84_BBOX_READERS,\n    node,\n    objectStack,\n  );\n  if (coordinates.length != 2) {\n    return undefined;\n  }\n  return boundingExtent(coordinates);\n}\n\n/**\n * @param {Element} node Node.\n * @param {Array<*>} objectStack Object stack.\n * @return {Object|undefined} BBox object.\n */\nfunction readBoundingBoxWithCrs(node, objectStack) {\n  const crs = node.getAttribute('crs');\n  const coordinates = pushParseAndPop(\n    [],\n    WGS84_BBOX_READERS,\n    node,\n    objectStack,\n  );\n  if (coordinates.length != 2) {\n    return undefined;\n  }\n  return {extent: boundingExtent(coordinates), crs: crs};\n}\n\n/**\n * @param {Element} node Node.\n * @param {Array<*>} objectStack Object stack.\n * @return {Object|undefined} Legend object.\n */\nfunction readLegendUrl(node, objectStack) {\n  const legend = {};\n  legend['format'] = node.getAttribute('format');\n  legend['href'] = readHref(node);\n  return legend;\n}\n\n/**\n * @param {Node} node Node.\n * @param {Array<*>} objectStack Object stack.\n * @return {Object|undefined} Coordinates object.\n */\nfunction readCoordinates(node, objectStack) {\n  const coordinates = readString(node).split(/\\s+/);\n  if (!coordinates || coordinates.length != 2) {\n    return undefined;\n  }\n  const x = +coordinates[0];\n  const y = +coordinates[1];\n  if (isNaN(x) || isNaN(y)) {\n    return undefined;\n  }\n  return [x, y];\n}\n\n/**\n * @param {Element} node Node.\n * @param {Array<*>} objectStack Object stack.\n * @return {Object|undefined} TileMatrix object.\n */\nfunction readTileMatrix(node, objectStack) {\n  return pushParseAndPop({}, TM_PARSERS, node, objectStack);\n}\n\n/**\n * @param {Element} node Node.\n * @param {Array<*>} objectStack Object stack.\n * @return {Object|undefined} TileMatrixSetLimits Object.\n */\nfunction readTileMatrixLimitsList(node, objectStack) {\n  return pushParseAndPop([], TMS_LIMITS_LIST_PARSERS, node, objectStack);\n}\n\n/**\n * @param {Element} node Node.\n * @param {Array<*>} objectStack Object stack.\n * @return {Object|undefined} TileMatrixLimits Array.\n */\nfunction readTileMatrixLimits(node, objectStack) {\n  return pushParseAndPop({}, TMS_LIMITS_PARSERS, node, objectStack);\n}\n\nexport default WMTSCapabilities;\n", "/**\n * @module ol/format/TextFeature\n */\nimport FeatureFormat from '../format/Feature.js';\nimport {abstract} from '../util.js';\n\n/**\n * @classdesc\n * Abstract base class; normally only used for creating subclasses and not\n * instantiated in apps.\n * Base class for text feature formats.\n *\n * @abstract\n */\nclass TextFeature extends FeatureFormat {\n  constructor() {\n    super();\n  }\n\n  /**\n   * @return {import(\"./Feature.js\").Type} Format.\n   * @override\n   */\n  getType() {\n    return 'text';\n  }\n\n  /**\n   * Read the feature from the source.\n   *\n   * @param {Document|Element|Object|string} source Source.\n   * @param {import(\"./Feature.js\").ReadOptions} [options] Read options.\n   * @return {import(\"../Feature.js\").default} Feature.\n   * @api\n   * @override\n   */\n  readFeature(source, options) {\n    return this.readFeatureFromText(\n      getText(source),\n      this.adaptOptions(options),\n    );\n  }\n\n  /**\n   * @abstract\n   * @param {string} text Text.\n   * @param {import(\"./Feature.js\").ReadOptions} [options] Read options.\n   * @protected\n   * @return {import(\"../Feature.js\").default} Feature.\n   */\n  readFeatureFromText(text, options) {\n    return abstract();\n  }\n\n  /**\n   * Read the features from the source.\n   *\n   * @param {Document|Element|Object|string} source Source.\n   * @param {import(\"./Feature.js\").ReadOptions} [options] Read options.\n   * @return {Array<import(\"../Feature.js\").default>} Features.\n   * @api\n   * @override\n   */\n  readFeatures(source, options) {\n    return this.readFeaturesFromText(\n      getText(source),\n      this.adaptOptions(options),\n    );\n  }\n\n  /**\n   * @abstract\n   * @param {string} text Text.\n   * @param {import(\"./Feature.js\").ReadOptions} [options] Read options.\n   * @protected\n   * @return {Array<import(\"../Feature.js\").default>} Features.\n   */\n  readFeaturesFromText(text, options) {\n    return abstract();\n  }\n\n  /**\n   * Read the geometry from the source.\n   *\n   * @param {Document|Element|Object|string} source Source.\n   * @param {import(\"./Feature.js\").ReadOptions} [options] Read options.\n   * @return {import(\"../geom/Geometry.js\").default} Geometry.\n   * @api\n   * @override\n   */\n  readGeometry(source, options) {\n    return this.readGeometryFromText(\n      getText(source),\n      this.adaptOptions(options),\n    );\n  }\n\n  /**\n   * @abstract\n   * @param {string} text Text.\n   * @param {import(\"./Feature.js\").ReadOptions} [options] Read options.\n   * @protected\n   * @return {import(\"../geom/Geometry.js\").default} Geometry.\n   */\n  readGeometryFromText(text, options) {\n    return abstract();\n  }\n\n  /**\n   * Read the projection from the source.\n   *\n   * @param {Document|Element|Object|string} source Source.\n   * @return {import(\"../proj/Projection.js\").default|undefined} Projection.\n   * @api\n   * @override\n   */\n  readProjection(source) {\n    return this.readProjectionFromText(getText(source));\n  }\n\n  /**\n   * @param {string} text Text.\n   * @protected\n   * @return {import(\"../proj/Projection.js\").default|undefined} Projection.\n   */\n  readProjectionFromText(text) {\n    return this.dataProjection;\n  }\n\n  /**\n   * Encode a feature as a string.\n   *\n   * @param {import(\"../Feature.js\").default} feature Feature.\n   * @param {import(\"./Feature.js\").WriteOptions} [options] Write options.\n   * @return {string} Encoded feature.\n   * @api\n   * @override\n   */\n  writeFeature(feature, options) {\n    return this.writeFeatureText(feature, this.adaptOptions(options));\n  }\n\n  /**\n   * @abstract\n   * @param {import(\"../Feature.js\").default} feature Features.\n   * @param {import(\"./Feature.js\").WriteOptions} [options] Write options.\n   * @protected\n   * @return {string} Text.\n   */\n  writeFeatureText(feature, options) {\n    return abstract();\n  }\n\n  /**\n   * Encode an array of features as string.\n   *\n   * @param {Array<import(\"../Feature.js\").default>} features Features.\n   * @param {import(\"./Feature.js\").WriteOptions} [options] Write options.\n   * @return {string} Encoded features.\n   * @api\n   * @override\n   */\n  writeFeatures(features, options) {\n    return this.writeFeaturesText(features, this.adaptOptions(options));\n  }\n\n  /**\n   * @abstract\n   * @param {Array<import(\"../Feature.js\").default>} features Features.\n   * @param {import(\"./Feature.js\").WriteOptions} [options] Write options.\n   * @protected\n   * @return {string} Text.\n   */\n  writeFeaturesText(features, options) {\n    return abstract();\n  }\n\n  /**\n   * Write a single geometry.\n   *\n   * @param {import(\"../geom/Geometry.js\").default} geometry Geometry.\n   * @param {import(\"./Feature.js\").WriteOptions} [options] Write options.\n   * @return {string} Geometry.\n   * @api\n   * @override\n   */\n  writeGeometry(geometry, options) {\n    return this.writeGeometryText(geometry, this.adaptOptions(options));\n  }\n\n  /**\n   * @abstract\n   * @param {import(\"../geom/Geometry.js\").default} geometry Geometry.\n   * @param {import(\"./Feature.js\").WriteOptions} [options] Write options.\n   * @protected\n   * @return {string} Text.\n   */\n  writeGeometryText(geometry, options) {\n    return abstract();\n  }\n}\n\n/**\n * @param {Document|Element|Object|string} source Source.\n * @return {string} Text.\n */\nfunction getText(source) {\n  if (typeof source === 'string') {\n    return source;\n  }\n  return '';\n}\n\nexport default TextFeature;\n", "/**\n * @module ol/format/WKT\n */\nimport Feature from '../Feature.js';\nimport GeometryCollection from '../geom/GeometryCollection.js';\nimport LineString from '../geom/LineString.js';\nimport MultiLineString from '../geom/MultiLineString.js';\nimport MultiPoint from '../geom/MultiPoint.js';\nimport MultiPolygon from '../geom/MultiPolygon.js';\nimport Point from '../geom/Point.js';\nimport Polygon from '../geom/Polygon.js';\nimport {transformGeometryWithOptions} from './Feature.js';\nimport TextFeature from './TextFeature.js';\n\n/**\n * Geometry constructors\n * @enum {function (new:import(\"../geom/Geometry.js\").default, Array, import(\"../geom/Geometry.js\").GeometryLayout)}\n */\nconst GeometryConstructor = {\n  'POINT': Point,\n  'LINESTRING': LineString,\n  'POLYGON': Polygon,\n  'MULTIPOINT': MultiPoint,\n  'MULTILINESTRING': MultiLineString,\n  'MULTIPOLYGON': MultiPolygon,\n};\n\n/**\n * @typedef {Object} Options\n * @property {boolean} [splitCollection=false] Whether to split GeometryCollections into\n * multiple features on reading.\n */\n\n/**\n * @typedef {Object} Token\n * @property {number} type Type.\n * @property {number|string} [value] Value.\n * @property {number} position Position.\n */\n\n/**\n * @const\n * @type {string}\n */\nconst EMPTY = 'EMPTY';\n\n/**\n * @const\n * @type {string}\n */\nconst Z = 'Z';\n\n/**\n * @const\n * @type {string}\n */\nconst M = 'M';\n\n/**\n * @const\n * @type {string}\n */\nconst ZM = 'ZM';\n\n/**\n * @const\n * @enum {number}\n */\nconst TokenType = {\n  START: 0,\n  TEXT: 1,\n  LEFT_PAREN: 2,\n  RIGHT_PAREN: 3,\n  NUMBER: 4,\n  COMMA: 5,\n  EOF: 6,\n};\n\n/**\n * @type {Object<import(\"../geom/Geometry.js\").Type, string>}\n */\nconst wktTypeLookup = {\n  Point: 'POINT',\n  LineString: 'LINESTRING',\n  Polygon: 'POLYGON',\n  MultiPoint: 'MULTIPOINT',\n  MultiLineString: 'MULTILINESTRING',\n  MultiPolygon: 'MULTIPOLYGON',\n  GeometryCollection: 'GEOMETRYCOLLECTION',\n  Circle: 'CIRCLE',\n};\n\n/**\n * Class to tokenize a WKT string.\n */\nclass Lexer {\n  /**\n   * @param {string} wkt WKT string.\n   */\n  constructor(wkt) {\n    /**\n     * @type {string}\n     */\n    this.wkt = wkt;\n\n    /**\n     * @type {number}\n     * @private\n     */\n    this.index_ = -1;\n  }\n\n  /**\n   * @param {string} c Character.\n   * @return {boolean} Whether the character is alphabetic.\n   * @private\n   */\n  isAlpha_(c) {\n    return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');\n  }\n\n  /**\n   * @param {string} c Character.\n   * @param {boolean} [decimal] Whether the string number\n   *     contains a dot, i.e. is a decimal number.\n   * @return {boolean} Whether the character is numeric.\n   * @private\n   */\n  isNumeric_(c, decimal) {\n    decimal = decimal !== undefined ? decimal : false;\n    return (c >= '0' && c <= '9') || (c == '.' && !decimal);\n  }\n\n  /**\n   * @param {string} c Character.\n   * @return {boolean} Whether the character is whitespace.\n   * @private\n   */\n  isWhiteSpace_(c) {\n    return c == ' ' || c == '\\t' || c == '\\r' || c == '\\n';\n  }\n\n  /**\n   * @return {string} Next string character.\n   * @private\n   */\n  nextChar_() {\n    return this.wkt.charAt(++this.index_);\n  }\n\n  /**\n   * Fetch and return the next token.\n   * @return {Token} Next string token.\n   */\n  nextToken() {\n    const c = this.nextChar_();\n    const position = this.index_;\n    /** @type {number|string} */\n    let value = c;\n    let type;\n\n    if (c == '(') {\n      type = TokenType.LEFT_PAREN;\n    } else if (c == ',') {\n      type = TokenType.COMMA;\n    } else if (c == ')') {\n      type = TokenType.RIGHT_PAREN;\n    } else if (this.isNumeric_(c) || c == '-') {\n      type = TokenType.NUMBER;\n      value = this.readNumber_();\n    } else if (this.isAlpha_(c)) {\n      type = TokenType.TEXT;\n      value = this.readText_();\n    } else if (this.isWhiteSpace_(c)) {\n      return this.nextToken();\n    } else if (c === '') {\n      type = TokenType.EOF;\n    } else {\n      throw new Error('Unexpected character: ' + c);\n    }\n\n    return {position: position, value: value, type: type};\n  }\n\n  /**\n   * @return {number} Numeric token value.\n   * @private\n   */\n  readNumber_() {\n    let c;\n    const index = this.index_;\n    let decimal = false;\n    let scientificNotation = false;\n    do {\n      if (c == '.') {\n        decimal = true;\n      } else if (c == 'e' || c == 'E') {\n        scientificNotation = true;\n      }\n      c = this.nextChar_();\n    } while (\n      this.isNumeric_(c, decimal) ||\n      // if we haven't detected a scientific number before, 'e' or 'E'\n      // hint that we should continue to read\n      (!scientificNotation && (c == 'e' || c == 'E')) ||\n      // once we know that we have a scientific number, both '-' and '+'\n      // are allowed\n      (scientificNotation && (c == '-' || c == '+'))\n    );\n    return parseFloat(this.wkt.substring(index, this.index_--));\n  }\n\n  /**\n   * @return {string} String token value.\n   * @private\n   */\n  readText_() {\n    let c;\n    const index = this.index_;\n    do {\n      c = this.nextChar_();\n    } while (this.isAlpha_(c));\n    return this.wkt.substring(index, this.index_--).toUpperCase();\n  }\n}\n\n/**\n * Class to parse the tokens from the WKT string.\n */\nclass Parser {\n  /**\n   * @param {Lexer} lexer The lexer.\n   */\n  constructor(lexer) {\n    /**\n     * @type {Lexer}\n     * @private\n     */\n    this.lexer_ = lexer;\n\n    /**\n     * @type {Token}\n     * @private\n     */\n    this.token_ = {\n      position: 0,\n      type: TokenType.START,\n    };\n\n    /**\n     * @type {import(\"../geom/Geometry.js\").GeometryLayout}\n     * @private\n     */\n    this.layout_ = 'XY';\n  }\n\n  /**\n   * Fetch the next token form the lexer and replace the active token.\n   * @private\n   */\n  consume_() {\n    this.token_ = this.lexer_.nextToken();\n  }\n\n  /**\n   * Tests if the given type matches the type of the current token.\n   * @param {TokenType} type Token type.\n   * @return {boolean} Whether the token matches the given type.\n   */\n  isTokenType(type) {\n    return this.token_.type == type;\n  }\n\n  /**\n   * If the given type matches the current token, consume it.\n   * @param {TokenType} type Token type.\n   * @return {boolean} Whether the token matches the given type.\n   */\n  match(type) {\n    const isMatch = this.isTokenType(type);\n    if (isMatch) {\n      this.consume_();\n    }\n    return isMatch;\n  }\n\n  /**\n   * Try to parse the tokens provided by the lexer.\n   * @return {import(\"../geom/Geometry.js\").default} The geometry.\n   */\n  parse() {\n    this.consume_();\n    return this.parseGeometry_();\n  }\n\n  /**\n   * Try to parse the dimensional info.\n   * @return {import(\"../geom/Geometry.js\").GeometryLayout} The layout.\n   * @private\n   */\n  parseGeometryLayout_() {\n    /** @type {import(\"../geom/Geometry.js\").GeometryLayout} */\n    let layout = 'XY';\n    const dimToken = this.token_;\n    if (this.isTokenType(TokenType.TEXT)) {\n      const dimInfo = dimToken.value;\n      if (dimInfo === Z) {\n        layout = 'XYZ';\n      } else if (dimInfo === M) {\n        layout = 'XYM';\n      } else if (dimInfo === ZM) {\n        layout = 'XYZM';\n      }\n      if (layout !== 'XY') {\n        this.consume_();\n      }\n    }\n    return layout;\n  }\n\n  /**\n   * @return {Array<import(\"../geom/Geometry.js\").default>} A collection of geometries.\n   * @private\n   */\n  parseGeometryCollectionText_() {\n    if (this.match(TokenType.LEFT_PAREN)) {\n      const geometries = [];\n      do {\n        geometries.push(this.parseGeometry_());\n      } while (this.match(TokenType.COMMA));\n      if (this.match(TokenType.RIGHT_PAREN)) {\n        return geometries;\n      }\n    }\n    throw new Error(this.formatErrorMessage_());\n  }\n\n  /**\n   * @return {Array<number>} All values in a point.\n   * @private\n   */\n  parsePointText_() {\n    if (this.match(TokenType.LEFT_PAREN)) {\n      const coordinates = this.parsePoint_();\n      if (this.match(TokenType.RIGHT_PAREN)) {\n        return coordinates;\n      }\n    }\n    throw new Error(this.formatErrorMessage_());\n  }\n\n  /**\n   * @return {Array<Array<number>>} All points in a linestring.\n   * @private\n   */\n  parseLineStringText_() {\n    if (this.match(TokenType.LEFT_PAREN)) {\n      const coordinates = this.parsePointList_();\n      if (this.match(TokenType.RIGHT_PAREN)) {\n        return coordinates;\n      }\n    }\n    throw new Error(this.formatErrorMessage_());\n  }\n\n  /**\n   * @return {Array<Array<Array<number>>>} All points in a polygon.\n   * @private\n   */\n  parsePolygonText_() {\n    if (this.match(TokenType.LEFT_PAREN)) {\n      const coordinates = this.parseLineStringTextList_();\n      if (this.match(TokenType.RIGHT_PAREN)) {\n        return coordinates;\n      }\n    }\n    throw new Error(this.formatErrorMessage_());\n  }\n\n  /**\n   * @return {Array<Array<number>>} All points in a multipoint.\n   * @private\n   */\n  parseMultiPointText_() {\n    if (this.match(TokenType.LEFT_PAREN)) {\n      let coordinates;\n      if (this.token_.type == TokenType.LEFT_PAREN) {\n        coordinates = this.parsePointTextList_();\n      } else {\n        coordinates = this.parsePointList_();\n      }\n      if (this.match(TokenType.RIGHT_PAREN)) {\n        return coordinates;\n      }\n    }\n    throw new Error(this.formatErrorMessage_());\n  }\n\n  /**\n   * @return {Array<Array<Array<number>>>} All linestring points\n   *                                          in a multilinestring.\n   * @private\n   */\n  parseMultiLineStringText_() {\n    if (this.match(TokenType.LEFT_PAREN)) {\n      const coordinates = this.parseLineStringTextList_();\n      if (this.match(TokenType.RIGHT_PAREN)) {\n        return coordinates;\n      }\n    }\n    throw new Error(this.formatErrorMessage_());\n  }\n\n  /**\n   * @return {Array<Array<Array<Array<number>>>>} All polygon points in a multipolygon.\n   * @private\n   */\n  parseMultiPolygonText_() {\n    if (this.match(TokenType.LEFT_PAREN)) {\n      const coordinates = this.parsePolygonTextList_();\n      if (this.match(TokenType.RIGHT_PAREN)) {\n        return coordinates;\n      }\n    }\n    throw new Error(this.formatErrorMessage_());\n  }\n\n  /**\n   * @return {Array<number>} A point.\n   * @private\n   */\n  parsePoint_() {\n    const coordinates = [];\n    const dimensions = this.layout_.length;\n    for (let i = 0; i < dimensions; ++i) {\n      const token = this.token_;\n      if (this.match(TokenType.NUMBER)) {\n        coordinates.push(/** @type {number} */ (token.value));\n      } else {\n        break;\n      }\n    }\n    if (coordinates.length == dimensions) {\n      return coordinates;\n    }\n    throw new Error(this.formatErrorMessage_());\n  }\n\n  /**\n   * @return {Array<Array<number>>} An array of points.\n   * @private\n   */\n  parsePointList_() {\n    const coordinates = [this.parsePoint_()];\n    while (this.match(TokenType.COMMA)) {\n      coordinates.push(this.parsePoint_());\n    }\n    return coordinates;\n  }\n\n  /**\n   * @return {Array<Array<number>>} An array of points.\n   * @private\n   */\n  parsePointTextList_() {\n    const coordinates = [this.parsePointText_()];\n    while (this.match(TokenType.COMMA)) {\n      coordinates.push(this.parsePointText_());\n    }\n    return coordinates;\n  }\n\n  /**\n   * @return {Array<Array<Array<number>>>} An array of points.\n   * @private\n   */\n  parseLineStringTextList_() {\n    const coordinates = [this.parseLineStringText_()];\n    while (this.match(TokenType.COMMA)) {\n      coordinates.push(this.parseLineStringText_());\n    }\n    return coordinates;\n  }\n\n  /**\n   * @return {Array<Array<Array<Array<number>>>>} An array of points.\n   * @private\n   */\n  parsePolygonTextList_() {\n    const coordinates = [this.parsePolygonText_()];\n    while (this.match(TokenType.COMMA)) {\n      coordinates.push(this.parsePolygonText_());\n    }\n    return coordinates;\n  }\n\n  /**\n   * @return {boolean} Whether the token implies an empty geometry.\n   * @private\n   */\n  isEmptyGeometry_() {\n    const isEmpty =\n      this.isTokenType(TokenType.TEXT) && this.token_.value == EMPTY;\n    if (isEmpty) {\n      this.consume_();\n    }\n    return isEmpty;\n  }\n\n  /**\n   * Create an error message for an unexpected token error.\n   * @return {string} Error message.\n   * @private\n   */\n  formatErrorMessage_() {\n    return (\n      'Unexpected `' +\n      this.token_.value +\n      '` at position ' +\n      this.token_.position +\n      ' in `' +\n      this.lexer_.wkt +\n      '`'\n    );\n  }\n\n  /**\n   * @return {import(\"../geom/Geometry.js\").default} The geometry.\n   * @private\n   */\n  parseGeometry_() {\n    const token = this.token_;\n    if (this.match(TokenType.TEXT)) {\n      const geomType = /** @type {string} */ (token.value);\n      this.layout_ = this.parseGeometryLayout_();\n      const isEmpty = this.isEmptyGeometry_();\n      if (geomType == 'GEOMETRYCOLLECTION') {\n        if (isEmpty) {\n          return new GeometryCollection([]);\n        }\n        const geometries = this.parseGeometryCollectionText_();\n        return new GeometryCollection(geometries);\n      }\n      const ctor = GeometryConstructor[geomType];\n      if (!ctor) {\n        throw new Error('Invalid geometry type: ' + geomType);\n      }\n\n      let coordinates;\n\n      if (isEmpty) {\n        if (geomType == 'POINT') {\n          coordinates = [NaN, NaN];\n        } else {\n          coordinates = [];\n        }\n      } else {\n        switch (geomType) {\n          case 'POINT': {\n            coordinates = this.parsePointText_();\n            break;\n          }\n          case 'LINESTRING': {\n            coordinates = this.parseLineStringText_();\n            break;\n          }\n          case 'POLYGON': {\n            coordinates = this.parsePolygonText_();\n            break;\n          }\n          case 'MULTIPOINT': {\n            coordinates = this.parseMultiPointText_();\n            break;\n          }\n          case 'MULTILINESTRING': {\n            coordinates = this.parseMultiLineStringText_();\n            break;\n          }\n          case 'MULTIPOLYGON': {\n            coordinates = this.parseMultiPolygonText_();\n            break;\n          }\n          default:\n            break;\n        }\n      }\n\n      return new ctor(coordinates, this.layout_);\n    }\n    throw new Error(this.formatErrorMessage_());\n  }\n}\n\n/**\n * @classdesc\n * Geometry format for reading and writing data in the `WellKnownText` (WKT)\n * format.\n *\n * @api\n */\nclass WKT extends TextFeature {\n  /**\n   * @param {Options} [options] Options.\n   */\n  constructor(options) {\n    super();\n\n    options = options ? options : {};\n\n    /**\n     * Split GeometryCollection into multiple features.\n     * @type {boolean}\n     * @private\n     */\n    this.splitCollection_ =\n      options.splitCollection !== undefined ? options.splitCollection : false;\n  }\n\n  /**\n   * Parse a WKT string.\n   * @param {string} wkt WKT string.\n   * @return {import(\"../geom/Geometry.js\").default}\n   *     The geometry created.\n   * @private\n   */\n  parse_(wkt) {\n    const lexer = new Lexer(wkt);\n    const parser = new Parser(lexer);\n    return parser.parse();\n  }\n\n  /**\n   * @protected\n   * @param {string} text Text.\n   * @param {import(\"./Feature.js\").ReadOptions} [options] Read options.\n   * @return {import(\"../Feature.js\").default} Feature.\n   * @override\n   */\n  readFeatureFromText(text, options) {\n    const geom = this.readGeometryFromText(text, options);\n    const feature = new Feature();\n    feature.setGeometry(geom);\n    return feature;\n  }\n\n  /**\n   * @param {string} text Text.\n   * @param {import(\"./Feature.js\").ReadOptions} [options] Read options.\n   * @protected\n   * @return {Array<Feature>} Features.\n   * @override\n   */\n  readFeaturesFromText(text, options) {\n    let geometries = [];\n    const geometry = this.readGeometryFromText(text, options);\n    if (this.splitCollection_ && geometry.getType() == 'GeometryCollection') {\n      geometries = /** @type {GeometryCollection} */ (\n        geometry\n      ).getGeometriesArray();\n    } else {\n      geometries = [geometry];\n    }\n    const features = [];\n    for (let i = 0, ii = geometries.length; i < ii; ++i) {\n      const feature = new Feature();\n      feature.setGeometry(geometries[i]);\n      features.push(feature);\n    }\n    return features;\n  }\n\n  /**\n   * @param {string} text Text.\n   * @param {import(\"./Feature.js\").ReadOptions} [options] Read options.\n   * @protected\n   * @return {import(\"../geom/Geometry.js\").default} Geometry.\n   * @override\n   */\n  readGeometryFromText(text, options) {\n    const geometry = this.parse_(text);\n    return transformGeometryWithOptions(geometry, false, options);\n  }\n\n  /**\n   * @param {import(\"../Feature.js\").default} feature Features.\n   * @param {import(\"./Feature.js\").WriteOptions} [options] Write options.\n   * @protected\n   * @return {string} Text.\n   * @override\n   */\n  writeFeatureText(feature, options) {\n    const geometry = feature.getGeometry();\n    if (geometry) {\n      return this.writeGeometryText(geometry, options);\n    }\n    return '';\n  }\n\n  /**\n   * @param {Array<import(\"../Feature.js\").default>} features Features.\n   * @param {import(\"./Feature.js\").WriteOptions} [options] Write options.\n   * @protected\n   * @return {string} Text.\n   * @override\n   */\n  writeFeaturesText(features, options) {\n    if (features.length == 1) {\n      return this.writeFeatureText(features[0], options);\n    }\n    const geometries = [];\n    for (let i = 0, ii = features.length; i < ii; ++i) {\n      geometries.push(features[i].getGeometry());\n    }\n    const collection = new GeometryCollection(geometries);\n    return this.writeGeometryText(collection, options);\n  }\n\n  /**\n   * @param {import(\"../geom/Geometry.js\").default} geometry Geometry.\n   * @param {import(\"./Feature.js\").WriteOptions} [options] Write options.\n   * @protected\n   * @return {string} Text.\n   * @override\n   */\n  writeGeometryText(geometry, options) {\n    return encode(transformGeometryWithOptions(geometry, true, options));\n  }\n}\n\n/**\n * @param {Point} geom Point geometry.\n * @return {string} Coordinates part of Point as WKT.\n */\nfunction encodePointGeometry(geom) {\n  const coordinates = geom.getCoordinates();\n  if (coordinates.length === 0) {\n    return '';\n  }\n  return coordinates.join(' ');\n}\n\n/**\n * @param {MultiPoint} geom MultiPoint geometry.\n * @return {string} Coordinates part of MultiPoint as WKT.\n */\nfunction encodeMultiPointGeometry(geom) {\n  const array = [];\n  const components = geom.getPoints();\n  for (let i = 0, ii = components.length; i < ii; ++i) {\n    array.push('(' + encodePointGeometry(components[i]) + ')');\n  }\n  return array.join(',');\n}\n\n/**\n * @param {GeometryCollection} geom GeometryCollection geometry.\n * @return {string} Coordinates part of GeometryCollection as WKT.\n */\nfunction encodeGeometryCollectionGeometry(geom) {\n  const array = [];\n  const geoms = geom.getGeometries();\n  for (let i = 0, ii = geoms.length; i < ii; ++i) {\n    array.push(encode(geoms[i]));\n  }\n  return array.join(',');\n}\n\n/**\n * @param {LineString|import(\"../geom/LinearRing.js\").default} geom LineString geometry.\n * @return {string} Coordinates part of LineString as WKT.\n */\nfunction encodeLineStringGeometry(geom) {\n  const coordinates = geom.getCoordinates();\n  const array = [];\n  for (let i = 0, ii = coordinates.length; i < ii; ++i) {\n    array.push(coordinates[i].join(' '));\n  }\n  return array.join(',');\n}\n\n/**\n * @param {MultiLineString} geom MultiLineString geometry.\n * @return {string} Coordinates part of MultiLineString as WKT.\n */\nfunction encodeMultiLineStringGeometry(geom) {\n  const array = [];\n  const components = geom.getLineStrings();\n  for (let i = 0, ii = components.length; i < ii; ++i) {\n    array.push('(' + encodeLineStringGeometry(components[i]) + ')');\n  }\n  return array.join(',');\n}\n\n/**\n * @param {Polygon} geom Polygon geometry.\n * @return {string} Coordinates part of Polygon as WKT.\n */\nfunction encodePolygonGeometry(geom) {\n  const array = [];\n  const rings = geom.getLinearRings();\n  for (let i = 0, ii = rings.length; i < ii; ++i) {\n    array.push('(' + encodeLineStringGeometry(rings[i]) + ')');\n  }\n  return array.join(',');\n}\n\n/**\n * @param {MultiPolygon} geom MultiPolygon geometry.\n * @return {string} Coordinates part of MultiPolygon as WKT.\n */\nfunction encodeMultiPolygonGeometry(geom) {\n  const array = [];\n  const components = geom.getPolygons();\n  for (let i = 0, ii = components.length; i < ii; ++i) {\n    array.push('(' + encodePolygonGeometry(components[i]) + ')');\n  }\n  return array.join(',');\n}\n\n/**\n * @param {import(\"../geom/SimpleGeometry.js\").default} geom SimpleGeometry geometry.\n * @return {string} Potential dimensional information for WKT type.\n */\nfunction encodeGeometryLayout(geom) {\n  const layout = geom.getLayout();\n  let dimInfo = '';\n  if (layout === 'XYZ' || layout === 'XYZM') {\n    dimInfo += Z;\n  }\n  if (layout === 'XYM' || layout === 'XYZM') {\n    dimInfo += M;\n  }\n  return dimInfo;\n}\n\n/**\n * @const\n * @type {Object<string, function(import(\"../geom/Geometry.js\").default): string>}\n */\nconst GeometryEncoder = {\n  'Point': encodePointGeometry,\n  'LineString': encodeLineStringGeometry,\n  'Polygon': encodePolygonGeometry,\n  'MultiPoint': encodeMultiPointGeometry,\n  'MultiLineString': encodeMultiLineStringGeometry,\n  'MultiPolygon': encodeMultiPolygonGeometry,\n  'GeometryCollection': encodeGeometryCollectionGeometry,\n};\n\n/**\n * Encode a geometry as WKT.\n * @param {import(\"../geom/Geometry.js\").default} geom The geometry to encode.\n * @return {string} WKT string for the geometry.\n */\nfunction encode(geom) {\n  const type = geom.getType();\n  const geometryEncoder = GeometryEncoder[type];\n  const enc = geometryEncoder(geom);\n  let wktType = wktTypeLookup[type];\n  if (typeof (/** @type {?} */ (geom).getFlatCoordinates) === 'function') {\n    const dimInfo = encodeGeometryLayout(\n      /** @type {import(\"../geom/SimpleGeometry.js\").default} */ (geom),\n    );\n    if (dimInfo.length > 0) {\n      wktType += ' ' + dimInfo;\n    }\n  }\n  if (enc.length === 0) {\n    return wktType + ' ' + EMPTY;\n  }\n  return wktType + '(' + enc + ')';\n}\n\nexport default WKT;\n", "/**\n * external.js \u2014 extern\u00ED zdroje dat: vrstvy typu `wms` (extern\u00ED WMS slu\u017Eba),\n * `xyz` (dla\u017Edicov\u00E1 \u0161ablona), `wmts` a `local` (vlo\u017Een\u00FD/sta\u017Een\u00FD GeoJSON/WKT).\n *\n * Ka\u017Ed\u00E1 extern\u00ED vrstva je b\u011Bhov\u00E1 polo\u017Eka se syntetick\u00FDm `itemId` a funkc\u00ED\n * `toConfig()` \u2014 serializaci do Map.config d\u011Bl\u00E1 state.serializeConfig stejn\u00FDm\n * principem jako u kresby (drawing). Obnova p\u0159i na\u010Dten\u00ED mapy: restoreExternalLayer.\n */\nimport ImageWMS from 'ol/source/ImageWMS.js';\nimport ImageLayer from 'ol/layer/Image.js';\nimport TileLayer from 'ol/layer/Tile.js';\nimport XYZ from 'ol/source/XYZ.js';\nimport WMTS, { optionsFromCapabilities } from 'ol/source/WMTS.js';\nimport WMSCapabilities from 'ol/format/WMSCapabilities.js';\nimport WMTSCapabilities from 'ol/format/WMTSCapabilities.js';\nimport VectorLayer from 'ol/layer/Vector.js';\nimport VectorSource from 'ol/source/Vector.js';\nimport GeoJSON from 'ol/format/GeoJSON.js';\nimport WKT from 'ol/format/WKT.js';\nimport Style from 'ol/style/Style.js';\nimport Stroke from 'ol/style/Stroke.js';\nimport Fill from 'ol/style/Fill.js';\nimport CircleStyle from 'ol/style/Circle.js';\nimport { emit } from './utils.js';\nimport { newUid } from './state.js';\nimport { renderLayerTree, applyZoomLimits } from './layers.js';\nimport { trackSourceLoading } from './loading.js';\n\n/** Typy extern\u00EDch vrstev (hodnota `type` v Map.config i b\u011Bhov\u00FD `dataType`). */\nexport const EXTERNAL_TYPES = ['wms', 'xyz', 'wmts', 'local'];\n\nexport function isExternalType(dataType) {\n    return EXTERNAL_TYPES.includes(dataType);\n}\n\n/** V\u00FDchoz\u00ED barva lok\u00E1ln\u00ED vektorov\u00E9 vrstvy. */\nconst LOCAL_DEFAULT_COLOR = '#7c3aed';\n\nconst geojsonFormat = new GeoJSON();\n\n/** Gener\u00E1tor syntetick\u00FDch itemId extern\u00EDch vrstev (unik\u00E1tn\u00ED v r\u00E1mci session). */\nlet externalCounter = 0;\nfunction nextExternalId(type) {\n    externalCounter += 1;\n    return `ext-${type}-${Date.now()}-${externalCounter}`;\n}\n\n/** Sjednocen\u00E1 chybov\u00E1 hl\u00E1\u0161ka pro fetch selh\u00E1n\u00ED (typicky CORS). */\nfunction corsAwareError(error) {\n    if (error instanceof TypeError) {\n        return new Error('The service does not allow cross-origin requests (CORS) or is unreachable.');\n    }\n    return error;\n}\n\n/* ---------------------------------------------------------------------------\n * GetCapabilities (WMS + WMTS)\n * ------------------------------------------------------------------------- */\n\n/** Dopln\u00ED do URL slu\u017Eby parametry GetCapabilities (zachov\u00E1 existuj\u00EDc\u00ED query). */\nfunction capabilitiesUrl(serviceUrl, service) {\n    const url = new URL(serviceUrl, window.location.href);\n    // Parametry nastavujeme case-insensitive \u2014 kdy\u017E u\u017E v URL jsou, nep\u0159id\u00E1v\u00E1me.\n    const has = (name) => Array.from(url.searchParams.keys()).some((k) => k.toLowerCase() === name.toLowerCase());\n    if (!has('SERVICE')) url.searchParams.set('SERVICE', service);\n    if (!has('REQUEST')) url.searchParams.set('REQUEST', 'GetCapabilities');\n    return url.toString();\n}\n\n/** Zplo\u0161t\u00ED strom vrstev z WMS capabilities na seznam pojmenovan\u00FDch vrstev. */\nfunction flattenWmsLayers(layerNode, acc) {\n    if (!layerNode) return acc;\n    const list = Array.isArray(layerNode) ? layerNode : [layerNode];\n    list.forEach((node) => {\n        if (node.Name) {\n            acc.push(node);\n        }\n        if (node.Layer) flattenWmsLayers(node.Layer, acc);\n    });\n    return acc;\n}\n\n/**\n * Na\u010Dte a rozparsuje WMS GetCapabilities. Vrac\u00ED\n * `{ url, version, formats, layers: [{ name, title, bbox, queryable, legendUrl, infoFormats }] }`.\n */\nexport async function loadWmsCapabilities(serviceUrl) {\n    let response;\n    try {\n        response = await fetch(capabilitiesUrl(serviceUrl, 'WMS'));\n    } catch (error) {\n        throw corsAwareError(error);\n    }\n    if (!response.ok) throw new Error(`GetCapabilities failed (${response.status}).`);\n    const text = await response.text();\n    let caps;\n    try {\n        caps = new WMSCapabilities().read(text);\n    } catch {\n        throw new Error('The response is not a valid WMS GetCapabilities document.');\n    }\n    if (!caps?.Capability) throw new Error('The response is not a valid WMS GetCapabilities document.');\n    const formats = caps.Capability.Request?.GetMap?.Format || [];\n    const infoFormats = caps.Capability.Request?.GetFeatureInfo?.Format || [];\n    const layers = flattenWmsLayers(caps.Capability.Layer, []).map((node) => ({\n        name: node.Name,\n        title: node.Title || node.Name,\n        // EX_GeographicBoundingBox = [minx, miny, maxx, maxy] ve WGS84 \u2014\n        // stejn\u00FD tvar jako bbox na\u0161ich workspace vrstev.\n        bbox: node.EX_GeographicBoundingBox || null,\n        queryable: Boolean(node.queryable),\n        legendUrl: node.Style?.[0]?.LegendURL?.[0]?.OnlineResource || null,\n    }));\n    if (layers.length === 0) throw new Error('The service does not list any named layers.');\n    return {\n        url: serviceUrl,\n        version: caps.version || '1.3.0',\n        format: formats.includes('image/png') ? 'image/png' : (formats[0] || 'image/png'),\n        infoFormats,\n        layers,\n    };\n}\n\n/** Na\u010Dte a rozparsuje WMTS GetCapabilities. Vrac\u00ED `{ url, caps, layers }`. */\nexport async function loadWmtsCapabilities(capsUrl) {\n    let response;\n    try {\n        response = await fetch(capabilitiesUrl(capsUrl, 'WMTS'));\n    } catch (error) {\n        throw corsAwareError(error);\n    }\n    if (!response.ok) throw new Error(`GetCapabilities failed (${response.status}).`);\n    const text = await response.text();\n    let caps;\n    try {\n        caps = new WMTSCapabilities().read(text);\n    } catch {\n        throw new Error('The response is not a valid WMTS GetCapabilities document.');\n    }\n    const layers = (caps?.Contents?.Layer || []).map((node) => ({\n        name: node.Identifier,\n        title: node.Title || node.Identifier,\n        bbox: node.WGS84BoundingBox || null,\n    }));\n    if (layers.length === 0) throw new Error('The capabilities document does not list any layers.');\n    return { url: capsUrl, caps, layers };\n}\n\n/* ---------------------------------------------------------------------------\n * Vytv\u00E1\u0159en\u00ED b\u011Bhov\u00FDch polo\u017Eek vrstev\n * ------------------------------------------------------------------------- */\n\n/** Spole\u010Dn\u00E9 vlo\u017Een\u00ED entry do stavu + mapy (navrch, stejn\u011B jako addLayerByItemId). */\nfunction insertEntry(ctx, entry) {\n    ctx.state.layers.unshift(entry);\n    ctx.map.addLayer(entry.olLayer);\n    // Indikace vykreslov\u00E1n\u00ED (loading.js): WMS = jeden obr\u00E1zek, XYZ/WMTS = dla\u017Edice.\n    if (entry.dataType === 'wms') trackSourceLoading(entry, entry.olSource, 'image');\n    if (entry.dataType === 'xyz' || entry.dataType === 'wmts') trackSourceLoading(entry, entry.olSource, 'tile');\n    applyZoomLimits(entry);\n    renderLayerTree(ctx);\n    ctx.state.dirty = true;\n    emit('layers:changed', { reason: 'add', entry });\n    return entry;\n}\n\n/** Z\u00E1klad b\u011Bhov\u00E9 polo\u017Eky extern\u00ED vrstvy (dopln\u00ED se olLayer/olSource + toConfig). */\nfunction baseEntry(type, title, saved) {\n    return {\n        uid: newUid(),\n        itemId: nextExternalId(type),\n        title: saved?.title || title,\n        visible: saved ? saved.visible !== false : true,\n        opacity: saved && Number.isFinite(saved.opacity) ? saved.opacity : 1,\n        minZoom: Number.isFinite(saved?.minZoom) ? saved.minZoom : null,\n        maxZoom: Number.isFinite(saved?.maxZoom) ? saved.maxZoom : null,\n        dataType: type,\n        external: true,\n        style: null,\n        filter: null,\n        bbox: null,\n        sublayers: [],\n        geometryTypes: [],\n        bands: null,\n        wms: null,\n        olLayer: null,\n        olSource: null,\n    };\n}\n\n/**\n * P\u0159id\u00E1 extern\u00ED WMS vrstvu (jedna vrstva capabilities = jedna polo\u017Eka stromu).\n * `def` = { url, version, format, layerName, title, bbox, queryable, legendUrl, infoFormat }.\n */\nexport function addExternalWmsLayer(ctx, def, saved) {\n    const entry = baseEntry('wms', def.title || def.layerName, saved);\n    const source = new ImageWMS({\n        url: def.url,\n        params: {\n            LAYERS: def.layerName,\n            VERSION: def.version || '1.3.0',\n            FORMAT: def.format || 'image/png',\n            TRANSPARENT: 'true',\n        },\n        ratio: 1.5,\n        crossOrigin: 'anonymous',\n    });\n    entry.olSource = source;\n    entry.olLayer = new ImageLayer({\n        source,\n        visible: entry.visible,\n        opacity: entry.opacity,\n        properties: { itemId: entry.itemId },\n    });\n    entry.bbox = def.bbox || null;\n    entry.externalWms = {\n        url: def.url,\n        layerName: def.layerName,\n        version: def.version || '1.3.0',\n        format: def.format || 'image/png',\n        queryable: Boolean(def.queryable),\n        legendUrl: def.legendUrl || null,\n        infoFormat: def.infoFormat || null,\n    };\n    entry.legendUrl = def.legendUrl || null;\n    entry.toConfig = () => ({\n        type: 'wms',\n        title: entry.title,\n        visible: entry.visible,\n        opacity: entry.opacity,\n        url: def.url,\n        layerName: def.layerName,\n        version: entry.externalWms.version,\n        format: entry.externalWms.format,\n        bbox: entry.bbox,\n        queryable: entry.externalWms.queryable,\n        legendUrl: entry.externalWms.legendUrl,\n        infoFormat: entry.externalWms.infoFormat,\n    });\n    return insertEntry(ctx, entry);\n}\n\n/** P\u0159id\u00E1 XYZ dla\u017Edicovou vrstvu z \u0161ablony URL s {z}/{x}/{y}. */\nexport function addXyzLayer(ctx, def, saved) {\n    const entry = baseEntry('xyz', def.title || 'XYZ layer', saved);\n    const source = new XYZ({ url: def.url, crossOrigin: 'anonymous' });\n    entry.olSource = source;\n    entry.olLayer = new TileLayer({\n        source,\n        visible: entry.visible,\n        opacity: entry.opacity,\n        properties: { itemId: entry.itemId },\n    });\n    entry.toConfig = () => ({\n        type: 'xyz',\n        title: entry.title,\n        visible: entry.visible,\n        opacity: entry.opacity,\n        url: def.url,\n    });\n    return insertEntry(ctx, entry);\n}\n\n/**\n * P\u0159id\u00E1 WMTS vrstvu z rozparsovan\u00FDch capabilities (`caps`) a n\u00E1zvu vrstvy.\n * `def` = { url (capabilities URL), caps, layerName, title, bbox }.\n */\nexport function addWmtsLayer(ctx, def, saved) {\n    const options = optionsFromCapabilities(def.caps, { layer: def.layerName });\n    if (!options) throw new Error(`Layer \"${def.layerName}\" was not found in the capabilities document.`);\n    options.crossOrigin = 'anonymous';\n    const entry = baseEntry('wmts', def.title || def.layerName, saved);\n    const source = new WMTS(options);\n    entry.olSource = source;\n    entry.olLayer = new TileLayer({\n        source,\n        visible: entry.visible,\n        opacity: entry.opacity,\n        properties: { itemId: entry.itemId },\n    });\n    entry.bbox = def.bbox || null;\n    entry.toConfig = () => ({\n        type: 'wmts',\n        title: entry.title,\n        visible: entry.visible,\n        opacity: entry.opacity,\n        url: def.url,\n        layerName: def.layerName,\n        bbox: entry.bbox,\n    });\n    return insertEntry(ctx, entry);\n}\n\n/* ---------------------------------------------------------------------------\n * Lok\u00E1ln\u00ED vektorov\u00E1 vrstva (paste / from URL)\n * ------------------------------------------------------------------------- */\n\n/** P\u0159evod hex barvy na rgba (v\u00FDpl\u0148 polygon\u016F lok\u00E1ln\u00ED vrstvy). */\nfunction hexToRgba(hex, alpha) {\n    const match = /^#?([0-9a-f]{6})$/i.exec(hex || '');\n    if (!match) return `rgba(124, 58, 237, ${alpha})`;\n    const num = parseInt(match[1], 16);\n    /* eslint-disable no-bitwise -- rozklad hex barvy na RGB kan\u00E1ly */\n    const r = (num >> 16) & 255;\n    const g = (num >> 8) & 255;\n    const b = num & 255;\n    /* eslint-enable no-bitwise */\n    return `rgba(${r}, ${g}, ${b}, ${alpha})`;\n}\n\n/** OL styl lok\u00E1ln\u00ED vrstvy \u2014 jednotn\u00E1 barva (bod/linie/polygon). */\nfunction localLayerStyle(color) {\n    return new Style({\n        stroke: new Stroke({ color, width: 2 }),\n        fill: new Fill({ color: hexToRgba(color, 0.3) }),\n        image: new CircleStyle({\n            radius: 6,\n            fill: new Fill({ color }),\n            stroke: new Stroke({ color: '#ffffff', width: 1.5 }),\n        }),\n    });\n}\n\n/**\n * Autodetekce vlo\u017Een\u00E9ho textu: JSON \u2192 GeoJSON (Feature/FeatureCollection/geometrie),\n * jinak WKT (i v\u00EDce geometri\u00ED na \u0159\u00E1dc\u00EDch). Vrac\u00ED GeoJSON FeatureCollection\n * v EPSG:4326 (dataProjection dle `crs` \u2014 jen u WKT d\u00E1v\u00E1 smysl 3857).\n */\nexport function parsePastedData(text, crs = 'EPSG:4326') {\n    const trimmed = (text || '').trim();\n    if (!trimmed) throw new Error('No data to parse.');\n    // 1) Pokus o GeoJSON\n    let json = null;\n    try {\n        json = JSON.parse(trimmed);\n    } catch {\n        json = null;\n    }\n    if (json) {\n        let collection;\n        if (json.type === 'FeatureCollection') {\n            collection = json;\n        } else if (json.type === 'Feature') {\n            collection = { type: 'FeatureCollection', features: [json] };\n        } else if (json.type && json.coordinates) {\n            collection = { type: 'FeatureCollection', features: [{ type: 'Feature', properties: {}, geometry: json }] };\n        } else {\n            throw new Error('The JSON is not a valid GeoJSON object.');\n        }\n        if (!Array.isArray(collection.features) || collection.features.length === 0) {\n            throw new Error('The GeoJSON does not contain any features.');\n        }\n        return collection;\n    }\n    // 2) WKT \u2014 ka\u017Ed\u00FD nepr\u00E1zdn\u00FD \u0159\u00E1dek je jedna geometrie.\n    const wktFormat = new WKT();\n    const lines = trimmed.split('\\n').map((l) => l.trim()).filter(Boolean);\n    const features = [];\n    lines.forEach((line) => {\n        let geometry;\n        try {\n            geometry = wktFormat.readGeometry(line, {\n                dataProjection: crs,\n                featureProjection: 'EPSG:4326',\n            });\n        } catch {\n            throw new Error('The input is neither valid GeoJSON nor WKT.');\n        }\n        features.push({\n            type: 'Feature',\n            properties: {},\n            geometry: JSON.parse(new GeoJSON().writeGeometry(geometry)),\n        });\n    });\n    return { type: 'FeatureCollection', features };\n}\n\n/**\n * P\u0159id\u00E1 lok\u00E1ln\u00ED vektorovou vrstvu z GeoJSON FeatureCollection (EPSG:4326).\n * `def` = { title, geojson, color?, sourceUrl? }.\n */\nexport function addLocalLayer(ctx, def, saved) {\n    const entry = baseEntry('local', def.title || 'Local layer', saved);\n    const source = new VectorSource({\n        features: geojsonFormat.readFeatures(def.geojson, {\n            dataProjection: 'EPSG:4326',\n            featureProjection: 'EPSG:3857',\n        }),\n    });\n    entry.localColor = def.color || LOCAL_DEFAULT_COLOR;\n    entry.olSource = source;\n    entry.olLayer = new VectorLayer({\n        source,\n        style: () => localLayerStyle(entry.localColor),\n        visible: entry.visible,\n        opacity: entry.opacity,\n        properties: { itemId: entry.itemId },\n    });\n    entry.sourceUrl = def.sourceUrl || null;\n    entry.toConfig = () => ({\n        type: 'local',\n        title: entry.title,\n        visible: entry.visible,\n        opacity: entry.opacity,\n        color: entry.localColor,\n        sourceUrl: entry.sourceUrl,\n        geojson: def.geojson,\n    });\n    return insertEntry(ctx, entry);\n}\n\n/** P\u0159ekresl\u00ED lok\u00E1ln\u00ED vrstvu po zm\u011Bn\u011B barvy (style-ui mini panel). */\nexport function setLocalLayerColor(ctx, entry, color) {\n    entry.localColor = color;\n    entry.olLayer?.changed();\n    ctx.state.dirty = true;\n}\n\n/* ---------------------------------------------------------------------------\n * Obnova z Map.config\n * ------------------------------------------------------------------------- */\n\n/**\n * Obnov\u00ED extern\u00ED vrstvu z ulo\u017Een\u00E9ho z\u00E1znamu Map.config (main.js bootstrap).\n * WMTS znovu na\u010D\u00EDt\u00E1 capabilities \u2014 p\u0159i selh\u00E1n\u00ED vyhod\u00ED chybu (volaj\u00EDc\u00ED vrstvu\n * p\u0159esko\u010D\u00ED s varov\u00E1n\u00EDm).\n */\nexport async function restoreExternalLayer(ctx, saved) {\n    if (saved.type === 'wms') {\n        return addExternalWmsLayer(ctx, {\n            url: saved.url,\n            layerName: saved.layerName,\n            version: saved.version,\n            format: saved.format,\n            title: saved.title,\n            bbox: saved.bbox,\n            queryable: saved.queryable,\n            legendUrl: saved.legendUrl,\n            infoFormat: saved.infoFormat,\n        }, saved);\n    }\n    if (saved.type === 'xyz') {\n        return addXyzLayer(ctx, { url: saved.url, title: saved.title }, saved);\n    }\n    if (saved.type === 'wmts') {\n        const { caps } = await loadWmtsCapabilities(saved.url);\n        return addWmtsLayer(ctx, {\n            url: saved.url,\n            caps,\n            layerName: saved.layerName,\n            title: saved.title,\n            bbox: saved.bbox,\n        }, saved);\n    }\n    if (saved.type === 'local') {\n        return addLocalLayer(ctx, {\n            title: saved.title,\n            geojson: saved.geojson,\n            color: saved.color,\n            sourceUrl: saved.sourceUrl,\n        }, saved);\n    }\n    throw new Error(`Unknown external layer type: ${saved.type}`);\n}\n", "/**\n * describe.js \u2014 popis dat od Mapserveru (`REQUEST=DescribeData`).\n *\n * Mapserver zn\u00E1 data nejl\u00E9pe: pod jak\u00FDmi n\u00E1zvy vrstvy souboru opravdu\n * publikuje, jakou maj\u00ED geometrii a atributy, jestli v sob\u011B nesou styl\n * vykreslen\u00ED (KML, MapInfo, DXF, atribut OGR_STYLE\u2026) a jak vypad\u00E1 jeho\n * legenda, jak\u00E1 p\u00E1sma m\u00E1 rastr a jak se s dan\u00FDmi volbami kresl\u00ED. Mapov\u00E1\n * aplikace se ho proto zept\u00E1 jednou na polo\u017Eku (odpov\u011B\u010F se pamatuje) a z n\u00ED\n * poskl\u00E1d\u00E1:\n *\n * - **logick\u00E9 vrstvy** souboru (`logicalLayers`) \u2014 soubor s v\u00EDce vrstvami\n *   (GPKG, KML, FileGDB\u2026) dostane ve stromu skupinu a ka\u017Ed\u00E1 vrstva vlastn\u00ED\n *   z\u00E1znam se stylem, filtrem a tabulkou; podvrstvy, na kter\u00E9 slu\u017Eba vrstvu\n *   rozd\u011Blila podle geometrie (`roads_line`, `roads_point`), z\u016Fst\u00E1vaj\u00ED pod\n *   jedn\u00EDm z\u00E1znamem,\n * - v\u00FDchoz\u00ED styl (styl z dat / n\u00E1vrh podle druhu dat),\n * - legendu rastru pro aktu\u00E1ln\u00ED volby (`describeRaster`).\n *\n * Kdy\u017E se dotaz nepovede (star\u0161\u00ED slu\u017Eba, s\u00ED\u0165), pou\u017Eije se p\u0159edpov\u011B\u010F vrstev od\n * backendu (`detail.layers`) \u2014 mapa funguje d\u00E1l, jen bez styl\u016F z dat a n\u00E1vrh\u016F.\n */\nimport { normalizeGeometryType } from './state.js';\nimport { isStyleAttribute } from './utils.js';\n\n/** Parametry zdroje dat podepsan\u00E9 backendem (stejn\u00E9 jako u GetMap). */\nfunction signedQuery(params) {\n    const query = new URLSearchParams();\n    ['FILE_URL', 'sig', 'PAYER', 'FILE_CRS'].forEach((key) => {\n        if (params?.[key]) query.set(key, params[key]);\n    });\n    return query;\n}\n\nasync function requestDescribe(serviceUrl, params, extra = {}) {\n    const query = signedQuery(params);\n    query.set('REQUEST', 'DescribeData');\n    Object.entries(extra).forEach(([key, value]) => {\n        if (value !== undefined && value !== null && value !== '') query.set(key, value);\n    });\n    const response = await fetch(`${serviceUrl}?${query.toString()}`);\n    if (!response.ok) throw new Error(`DescribeData failed: ${response.status}`);\n    const data = await response.json();\n    if (!data || !Array.isArray(data.layers)) throw new Error('DescribeData: unexpected answer');\n    return data;\n}\n\n/** Popis polo\u017Eky \u2014 jeden dotaz na polo\u017Eku a verzi dat (sd\u00EDl\u00ED ho v\u0161echny jej\u00ED\n * vrstvy obnovovan\u00E9 z ulo\u017Een\u00E9 mapy). */\nconst describeCache = new Map();\nconst renderingCache = new Map();\n\n/**\n * Popis dat polo\u017Eky (`detail` z /items/<id>/wms/), nebo null, kdy\u017E ho slu\u017Eba\n * nedod\u00E1. Nikdy nevyhazuje.\n */\nexport function describeItem(bootstrap, detail) {\n    const serviceUrl = bootstrap.mapserverUrl;\n    if (!serviceUrl || !detail?.params?.FILE_URL) return Promise.resolve(null);\n    // Soubor, kter\u00FD by slu\u017Eba \u010Detla des\u00EDtky sekund (odhad backendu, `tooSlow`), se\n    // nepopisuje: dotaz by po minut\u011B skon\u010Dil chybou a vrstva by se \u201Ep\u0159ipravovala\u201C.\n    if (detail.performance?.tooSlow) return Promise.resolve(null);\n    const key = `${detail.id}|${detail.params.FILE_URL}|${detail.params.FILE_CRS || ''}`;\n    if (!describeCache.has(key)) {\n        const promise = requestDescribe(serviceUrl, detail.params).catch((error) => {\n            // eslint-disable-next-line no-console -- diagnostika; mapa jede d\u00E1l z p\u0159edpov\u011Bdi backendu\n            console.warn('Layer description is not available, using the predicted layers:', error);\n            // Nepoveden\u00FD dotaz se nepamatuje \u2014 dal\u0161\u00ED p\u0159id\u00E1n\u00ED to zkus\u00ED znovu.\n            describeCache.delete(key);\n            return null;\n        });\n        describeCache.set(key, promise);\n    }\n    return describeCache.get(key);\n}\n\n/** Zapomene popis polo\u017Eky (data se zm\u011Bnila \u2014 nap\u0159. p\u0159ibyla kopie pro rychl\u00E9\n * kreslen\u00ED), dal\u0161\u00ED dotaz se zept\u00E1 slu\u017Eby znovu. */\nexport function forgetDescription(itemId) {\n    [describeCache, renderingCache].forEach((cache) => {\n        Array.from(cache.keys()).filter((key) => key.startsWith(`${itemId}|`)).forEach((key) => cache.delete(key));\n    });\n}\n\n/** Jak se rastr vrstvy kresl\u00ED s dan\u00FDmi volbami (`BANDS`, `STRETCH`, \u2026) \u2014\n * pro legendu. Vrac\u00ED `rendering` z popisu, nebo null. */\nexport function describeRaster(bootstrap, entry, rasterParams) {\n    const serviceUrl = bootstrap.mapserverUrl;\n    if (!serviceUrl || !entry?.wms?.fileUrl) return Promise.resolve(null);\n    const params = {\n        FILE_URL: entry.wms.fileUrl, sig: entry.wms.sig, PAYER: entry.wms.payer, FILE_CRS: entry.wms.fileCrs,\n    };\n    const key = `${entry.itemId}|${entry.wms.fileUrl}|${JSON.stringify(rasterParams)}`;\n    if (!renderingCache.has(key)) {\n        const name = entry.sublayers?.[0]?.name;\n        const promise = requestDescribe(serviceUrl, params, rasterParams)\n            .then((data) => {\n                const layer = data.layers.find((l) => l.kind === 'raster' && (!name || l.name === name))\n                    || data.layers.find((l) => l.kind === 'raster');\n                return layer?.rendering || null;\n            })\n            .catch(() => {\n                renderingCache.delete(key);\n                return null;\n            });\n        renderingCache.set(key, promise);\n        // Pam\u011B\u0165 jen na posledn\u00ED volby \u2014 ta\u017Een\u00ED posuvn\u00EDku by ji jinak plnilo.\n        if (renderingCache.size > 60) renderingCache.delete(renderingCache.keys().next().value);\n    }\n    return renderingCache.get(key);\n}\n\n/* ---------------------------------------------------------------------------\n * Logick\u00E9 vrstvy souboru\n * ------------------------------------------------------------------------- */\n\n/** Podvrstva ve tvaru, se kter\u00FDm pracuje zbytek aplikace (jako od backendu). */\nfunction sublayerFromDescribed(layer, predicted) {\n    return {\n        name: layer.name,\n        source_layer: layer.sourceLayer ?? layer.title,\n        geometry_types: layer.geometryTypes?.length ? layer.geometryTypes : [layer.geometry],\n        attributes: (layer.fields || []).filter((f) => !isStyleAttribute(f.name))\n            .map((f) => ({ name: f.name, type: f.type })),\n        feature_count: Number.isFinite(layer.featureCount) ? layer.featureCount : (predicted?.feature_count ?? null),\n        geometry: layer.geometry,\n    };\n}\n\n/** Styl z dat za celou logickou vrstvu (slou\u010Den\u00ED podvrstev). */\nfunction nativeOf(layers) {\n    const styled = layers.filter((l) => l.featureStyles);\n    if (styled.length === 0) return null;\n    return {\n        available: true,\n        // \u201EPlain\u201C = jedin\u00FD \u010Dernob\u00EDl\u00FD styl na v\u0161ech prvc\u00EDch (v\u00FDchoz\u00ED styl\n        // zapisova\u010De souboru) \u2014 nekresl\u00ED se j\u00EDm, dokud o to u\u017Eivatel nestoj\u00ED.\n        plain: styled.every((l) => l.featureStyles.plain),\n        source: styled[0].featureStyles.source,\n        field: styled[0].featureStyles.field || null,\n        categoryField: styled.find((l) => l.featureStyles.categoryField)?.featureStyles.categoryField || null,\n        legends: styled.map((l) => ({\n            geometry: l.geometry,\n            entries: l.featureStyles.legend?.entries || [],\n            more: l.featureStyles.legend?.more || 0,\n        })),\n    };\n}\n\nfunction unionExtent(extents) {\n    const valid = extents.filter((e) => Array.isArray(e) && e.length === 4 && e.every(Number.isFinite));\n    if (valid.length === 0) return null;\n    return valid.reduce((acc, e) => [\n        Math.min(acc[0], e[0]), Math.min(acc[1], e[1]), Math.max(acc[2], e[2]), Math.max(acc[3], e[3]),\n    ]);\n}\n\n/** Logick\u00E9 vrstvy z popisu slu\u017Eby. */\nfunction fromDescribed(detail, described) {\n    const predicted = new Map([...(detail.layers || []), ...(detail.raster_layers || [])].map((l) => [l.name, l]));\n    const out = [];\n    const vectors = new Map(); // sourceLayer -> logick\u00E1 vrstva\n    described.layers.forEach((layer) => {\n        if (layer.kind === 'raster') {\n            out.push({\n                key: layer.name,\n                kind: 'raster',\n                title: layer.title || layer.name,\n                bbox: layer.extent || null,\n                sublayers: [{\n                    name: layer.name, source_layer: layer.title, geometry_types: [], attributes: [], feature_count: null,\n                }],\n                bands: (layer.bands || []).map((b) => ({\n                    index: b.index,\n                    data_type: b.type,\n                    colorInterp: b.colorInterpretation,\n                    min: b.min,\n                    max: b.max,\n                    nodata: b.nodata,\n                })),\n                raster: {\n                    palette: layer.palette || [],\n                    rendering: layer.rendering || null,\n                    colormaps: described.colormaps || {},\n                    size: layer.size || null,\n                    crs: layer.crs || null,\n                    driver: layer.driver || null,\n                },\n                hybrid: layer.hybrid || null,\n                _layers: [layer],\n            });\n            return;\n        }\n        const key = layer.sourceLayer ?? layer.name;\n        let logical = vectors.get(key);\n        if (!logical) {\n            logical = {\n                key, kind: 'vector', title: key, sublayers: [], hybrid: layer.hybrid || null, _layers: [],\n            };\n            vectors.set(key, logical);\n            out.push(logical);\n        }\n        logical.sublayers.push(sublayerFromDescribed(layer, predicted.get(layer.name)));\n        logical._layers.push(layer);\n    });\n    out.filter((l) => l.kind === 'vector').forEach((logical) => {\n        const layers = logical._layers;\n        // Nerozd\u011Blen\u00E1 vrstva nese sv\u016Fj p\u016Fvodn\u00ED n\u00E1zev (i s diakritikou).\n        if (layers.length === 1) logical.title = layers[0].title || logical.key;\n        logical.bbox = unionExtent(layers.map((l) => l.extent));\n        logical.native = nativeOf(layers);\n        logical.suggested = layers\n            .filter((l) => l.suggestedStyle)\n            .sort((a, b) => (b.featureCount || 0) - (a.featureCount || 0))\n            .map((l) => ({ geometry: normalizeGeometryType(l.geometry), suggested: l.suggestedStyle }));\n        logical.crs = layers[0].crs || null;\n        logical.driver = layers[0].driver || null;\n        // Vrstva, kterou u\u017E ukazuje rastr t\u00E9ho\u017E souboru (vektory hybridn\u00EDho\n        // PDF nad jeho str\u00E1nkou) \u2014 slu\u017Eba ji ozna\u010D\u00ED a strom ji p\u0159id\u00E1 vypnutou.\n        logical.defaultVisible = !layers.every((l) => l.defaultVisible === false);\n    });\n    out.forEach((logical) => { delete logical._layers; });\n    return out;\n}\n\n/** Logick\u00E9 vrstvy z p\u0159edpov\u011Bdi backendu (bez popisu slu\u017Eby). */\nfunction fromPredicted(detail) {\n    const out = [];\n    const raster = detail.data_type === 'raster' ? (detail.layers || []) : (detail.raster_layers || []);\n    raster.forEach((layer) => {\n        out.push({\n            key: layer.name, kind: 'raster', title: layer.source_layer || layer.name, bbox: null,\n            sublayers: [layer], bands: detail.bands || [], raster: null, hybrid: null,\n        });\n    });\n    if (detail.data_type !== 'raster') {\n        const vectors = new Map();\n        (detail.layers || []).forEach((layer) => {\n            const key = layer.source_layer ?? layer.name;\n            let logical = vectors.get(key);\n            if (!logical) {\n                logical = {\n                    key, kind: 'vector', title: key, sublayers: [], bbox: null, native: null, suggested: [], hybrid: null,\n                };\n                vectors.set(key, logical);\n                out.push(logical);\n            }\n            logical.sublayers.push(layer);\n        });\n    }\n    return out;\n}\n\n/**\n * Logick\u00E9 vrstvy polo\u017Eky v po\u0159ad\u00ED VYKRESLOV\u00C1N\u00CD (prvn\u00ED = vespod): rastr(y)\n * a potom vektorov\u00E9 vrstvy v po\u0159ad\u00ED souboru. `described` je odpov\u011B\u010F\n * `describeItem` (nebo null \u2192 p\u0159edpov\u011B\u010F backendu).\n *\n * Vrstva: `{ key, kind: 'vector'|'raster', title, bbox, sublayers, native,\n * suggested, bands, raster, hybrid, defaultVisible }`.\n */\nexport function logicalLayers(detail, described) {\n    if (described?.layers?.length) {\n        try {\n            const layers = fromDescribed(detail, described);\n            // Odhad rychlosti kreslen\u00ED plat\u00ED pro cel\u00FD soubor (advisor.js); slu\u017Eba\n            // ho zn\u00E1 nejl\u00E9pe, jinak plat\u00ED odhad backendu.\n            layers.forEach((layer) => { layer.performance = described.performance || detail.performance || null; });\n            if (layers.length) return layers;\n        } catch (error) {\n            // eslint-disable-next-line no-console -- ne\u010Dekan\u00FD tvar popisu; pou\u017Eije se p\u0159edpov\u011B\u010F\n            console.warn('Unexpected layer description:', error);\n        }\n    }\n    const predicted = fromPredicted(detail);\n    predicted.forEach((layer) => {\n        if (layer.kind === 'vector') layer.performance = detail.performance || null;\n    });\n    return predicted;\n}\n\n/** Detail jedn\u00E9 logick\u00E9 vrstvy ve tvaru pro `createLayerEntry`. `single` =\n * polo\u017Eka m\u00E1 jedinou vrstvu (ta nese n\u00E1zev polo\u017Eky a nepot\u0159ebuje `layer_key`). */\nexport function layerDetail(detail, logical, { single = false } = {}) {\n    const raster = logical.kind === 'raster';\n    return {\n        ...detail,\n        data_type: raster ? 'raster' : 'vector',\n        item_data_type: detail.data_type,\n        hybrid_part: detail.data_type === 'hybrid' ? logical.kind : null,\n        layers: logical.sublayers,\n        layer_key: single ? null : logical.key,\n        layer_title: single ? detail.title : logical.title,\n        layer_bbox: logical.bbox || null,\n        bands: raster ? (logical.bands?.length ? logical.bands : (detail.bands || [])) : null,\n        native: raster ? null : (logical.native || null),\n        suggested: raster ? null : (logical.suggested || null),\n        raster: raster ? (logical.raster || null) : null,\n        performance: logical.performance || null,\n        // false = nov\u00E1 vrstva se do stromu p\u0159id\u00E1 vypnut\u00E1 (viz `fromDescribed`).\n        default_visible: logical.defaultVisible !== false,\n    };\n}\n", "/**\n * item-layers.js \u2014 vrstvy, kter\u00E9 z polo\u017Eky Data workspace vzniknou na map\u011B,\n * a jejich v\u00FDchoz\u00ED vzhled. Jedno m\u00EDsto pro mapu i pro n\u00E1hled dat.\n *\n * - Mapa (layers.js) z nich p\u0159i p\u0159id\u00E1n\u00ED polo\u017Eky skl\u00E1d\u00E1 strom vrstev.\n * - N\u00E1hled dat v Data workspace (`apps/workspace/preview_style.py`) si p\u0159es\n *   preview-cli.mjs nech\u00E1 spo\u010D\u00EDtat parametry jednoho GetMap za cel\u00FD soubor\n *   (`previewParams`) \u2014 stejn\u00E9 vrstvy, stejn\u00FD v\u00FDchoz\u00ED styl (`createLayerEntry`)\n *   a stejn\u00E9 SLD / volby rastru (`buildWmsParams`) jako prvn\u00ED zobrazen\u00ED mapy.\n *\n * Modul je bez OpenLayers a bez DOM (b\u011B\u017E\u00ED i v Node).\n */\nimport { createLayerEntry } from './state.js';\nimport { layerDetail, logicalLayers } from './describe.js';\nimport { buildSldForEntries } from './sld.js';\nimport { buildWmsParams } from './wms-params.js';\n\n/**\n * Po\u0159ad\u00ED vykreslov\u00E1n\u00ED vrstev nov\u011B p\u0159idan\u00E9ho souboru: rastr vespod, nad n\u00EDm\n * plochy, linie a naho\u0159e body \u2014 jinak by plochy p\u0159ikryly body a linie\n * (soubor vrstvy v tomto po\u0159ad\u00ED m\u00EDt nemus\u00ED, u adres\u00E1\u0159e vrstev je abecedn\u00ED).\n * V r\u00E1mci stejn\u00E9 geometrie z\u016Fst\u00E1v\u00E1 po\u0159ad\u00ED ze souboru. Po\u0159ad\u00ED jde kdykoli\n * zm\u011Bnit p\u0159eta\u017Een\u00EDm vrstev.\n */\nexport function drawingOrder(logical) {\n    const rank = (layer) => {\n        if (layer.kind === 'raster') return 0;\n        const geometries = new Set(layer.sublayers.map((sub) => sub.geometry\n            || (sub.geometry_types || []).join(' ').toLowerCase()));\n        const has = (word) => Array.from(geometries).some((g) => String(g).toLowerCase().includes(word));\n        if (has('polygon')) return 1;\n        if (has('line')) return 2;\n        return 3;\n    };\n    return logical\n        .map((layer, index) => ({ layer, index, rank: rank(layer) }))\n        .sort((a, b) => a.rank - b.rank || a.index - b.index)\n        .map((item) => item.layer);\n}\n\n/**\n * B\u011Bhov\u00E9 z\u00E1znamy vrstev nov\u011B p\u0159idan\u00E9 polo\u017Eky (bez ulo\u017Een\u00E9ho stylu) v po\u0159ad\u00ED\n * vykreslov\u00E1n\u00ED \u2014 prvn\u00ED = vespod. Soubor s jedinou vrstvou d\u00E1 jeden z\u00E1znam\n * s n\u00E1zvem polo\u017Eky, soubor s v\u00EDce vrstvami jeden z\u00E1znam na vrstvu\n * (`drawingOrder`). `logical` = `logicalLayers(detail, described)`.\n */\nexport function itemLayerEntries(detail, logical) {\n    if (logical.length === 1) {\n        return [createLayerEntry(layerDetail(detail, logical[0], { single: true }))];\n    }\n    return drawingOrder(logical).map((layer) => createLayerEntry(layerDetail(detail, layer)));\n}\n\n/** Volby rastru, kter\u00E9 jdou do GetMap za v\u0161echny rastrov\u00E9 vrstvy najednou. */\nconst RASTER_KEYS = ['BANDS', 'STRETCH', 'RANGE', 'COLORMAP', 'NODATA'];\n\n/**\n * Parametry jednoho GetMap, kter\u00FD nakresl\u00ED polo\u017Eku tak, jak ji mapa uk\u00E1\u017Ee\n * poprv\u00E9: zapnut\u00E9 vrstvy v po\u0159ad\u00ED vykreslov\u00E1n\u00ED (`LAYERS`), jedno SLD se styly\n * v\u0161ech vrstev, kter\u00E9 mapa kresl\u00ED podle SLD, a volby rastru. Vrstvy stylem\n * z dat (KML, OGR_STYLE\u2026) jsou bez SLD stejn\u011B jako v map\u011B \u2014 kresl\u00ED je slu\u017Eba.\n *\n * Bez podpisu, souboru a form\u00E1tu obr\u00E1zku (dopln\u00ED server). Volbu rastru, ve\n * kter\u00E9 se rastrov\u00E9 vrstvy souboru li\u0161\u00ED (v\u00EDc rastr\u016F v jednom souboru), GetMap\n * za v\u0161echny nastavit neum\u00ED \u2014 vynech\u00E1 se a plat\u00ED v\u00FDchoz\u00ED chov\u00E1n\u00ED slu\u017Eby.\n *\n * `described` = odpov\u011B\u010F `DescribeData` (nebo null \u2192 p\u0159edpov\u011B\u010F backendu,\n * stejn\u011B jako v map\u011B). Vrac\u00ED null, kdy\u017E nen\u00ED co nakreslit.\n */\nexport function previewParams(detail, described) {\n    const entries = itemLayerEntries(detail, logicalLayers(detail, described))\n        .filter((entry) => entry.visible && (entry.sublayers || []).length);\n    if (entries.length === 0) return null;\n    const drawn = entries.map((entry) => ({ entry, params: buildWmsParams(entry) }));\n    const params = { LAYERS: drawn.map((d) => d.params.LAYERS).filter(Boolean).join(',') };\n    const styled = drawn.filter((d) => d.params.SLD_BODY).map((d) => d.entry);\n    if (styled.length) params.SLD_BODY = buildSldForEntries(styled);\n    const rasters = drawn.filter((d) => d.entry.dataType === 'raster');\n    RASTER_KEYS.forEach((key) => {\n        const values = new Set(rasters.map((d) => d.params[key]));\n        const [value] = values;\n        if (values.size === 1 && value !== undefined) params[key] = value;\n    });\n    return params;\n}\n", "/**\n * legend.js \u2014 legenda vrstvy kreslen\u00E1 p\u0159\u00EDmo v aplikaci (SVG), ne obr\u00E1zek\n * z Mapserveru.\n *\n * Aplikace styl vrstvy zn\u00E1 (sama z n\u011Bj generuje SLD), tak\u017Ee symboly um\u00ED\n * nakreslit sama: ost\u0159e, ve stejn\u00E9 velikosti pro v\u0161echny vrstvy a s popisky,\n * kter\u00E9 se vejdou do panelu. Obr\u00E1zek z `GetLegendGraphic` m\u00EDval dlouh\u00E9 n\u00E1zvy\n * a technick\u00E9 p\u0159\u00EDpony t\u0159\u00EDd a zmen\u0161oval ostatn\u00ED prvky karty vrstvy.\n *\n * `legendModel(entry)` vrac\u00ED popis legendy:\n *\n *   { swatch,            // HTML mal\u00E9ho symbolu do \u0159\u00E1dku vrstvy\n *     items: [{ symbol, label }],   // t\u0159\u00EDdy (kategorie, intervaly, paleta\u2026)\n *     more,              // kolik polo\u017Eek se do seznamu neve\u0161lo\n *     gradient,          // { colors, min, max } \u2014 spojit\u00E1 \u0161k\u00E1la rastru\n *     channels,          // [{ name, band }] \u2014 slo\u017Een\u00ED RGB\n *     image,             // URL obr\u00E1zku legendy (extern\u00ED WMS)\n *     note }             // kr\u00E1tk\u00E1 pozn\u00E1mka pod legendou\n *\n * Symbol je popsan\u00FD slovn\u00EDkem spole\u010Dn\u00FDm s Mapserverem (`type` point / line /\n * polygon / text + fill, stroke, width, dash, shape, size), tak\u017Ee stejn\u011B se\n * kresl\u00ED i legenda stylu ulo\u017Een\u00E9ho v datech (`entry.native.legends`).\n */\nimport { ruleForCategory } from './state.js';\nimport { PHOTO_SYMBOL, cameraPolygonPoints } from './photo-marker.js';\n\nconst SWATCH_W = 22;\nconst SWATCH_H = 16;\n\nfunction esc(value) {\n    return String(value ?? '')\n        .replace(/&/g, '&amp;')\n        .replace(/</g, '&lt;')\n        .replace(/>/g, '&gt;')\n        .replace(/\"/g, '&quot;');\n}\n\nconst clamp = (value, min, max) => Math.min(max, Math.max(min, value));\n\n/** Je barva tak sv\u011Btl\u00E1, \u017Ee by na b\u00EDl\u00E9 kart\u011B vrstvy nebyla vid\u011Bt? */\nfunction isVeryLight(color) {\n    const match = /^#?([0-9a-f]{6})/i.exec(String(color || ''));\n    if (!match) return false;\n    const n = parseInt(match[1], 16);\n    /* eslint-disable no-bitwise -- rozklad hex barvy na RGB kan\u00E1ly */\n    const luminance = (0.299 * ((n >> 16) & 255) + 0.587 * ((n >> 8) & 255) + 0.114 * (n & 255)) / 255;\n    /* eslint-enable no-bitwise */\n    return luminance > 0.88;\n}\n\n/** Tenk\u00FD \u0161ed\u00FD podklad pod sv\u011Btl\u00FD symbol (b\u00EDl\u00E1 silnice, sv\u011Btl\u00E1 plocha). */\nconst CONTRAST = '#94a3b8'; // slate-400\n\nfunction dashArray(dash) {\n    if (!dash) return '';\n    const parts = Array.isArray(dash) ? dash : String(dash).trim().split(/[\\s,]+/).map(Number);\n    const valid = parts.filter((n) => Number.isFinite(n) && n > 0);\n    if (valid.length < 2) return '';\n    // V mal\u00E9m symbolu se dlouh\u00E9 \u010D\u00E1rky zkr\u00E1t\u00ED, aby byl vzor poznat.\n    const scale = Math.min(1, 5 / Math.max(...valid));\n    return ` stroke-dasharray=\"${valid.map((n) => (n * scale).toFixed(1)).join(' ')}\"`;\n}\n\n/** Obrys tvaru bodov\u00E9ho symbolu se st\u0159edem (cx, cy) a \u201Epolom\u011Brem\u201C r. */\nfunction pointShape(shape, cx, cy, r) {\n    switch (shape) {\n        case 'square':\n            return `<rect x=\"${cx - r}\" y=\"${cy - r}\" width=\"${2 * r}\" height=\"${2 * r}\"`;\n        case 'triangle':\n            return `<polygon points=\"${cx},${cy - r} ${cx + r},${cy + r} ${cx - r},${cy + r}\"`;\n        case 'star': {\n            const points = [];\n            for (let i = 0; i < 10; i += 1) {\n                const radius = i % 2 === 0 ? r * 1.15 : r * 0.5;\n                const angle = (Math.PI / 5) * i - Math.PI / 2;\n                points.push(`${(cx + radius * Math.cos(angle)).toFixed(1)},${(cy + radius * Math.sin(angle)).toFixed(1)}`);\n            }\n            return `<polygon points=\"${points.join(' ')}\"`;\n        }\n        case 'cross':\n            return `<path d=\"M${cx} ${cy - r}V${cy + r}M${cx - r} ${cy}H${cx + r}\" fill=\"none\"`;\n        case 'x':\n            return `<path d=\"M${cx - r} ${cy - r}L${cx + r} ${cy + r}M${cx - r} ${cy + r}L${cx + r} ${cy - r}\" fill=\"none\"`;\n        case 'bar':\n            return `<path d=\"M${cx} ${cy - r}V${cy + r}\" fill=\"none\"`;\n        default:\n            return `<circle cx=\"${cx}\" cy=\"${cy}\" r=\"${r}\"`;\n    }\n}\n\n/** SVG symbolu legendy (22 \u00D7 16 px) podle popisu `symbol`. */\nexport function symbolSvg(symbol, { width = SWATCH_W, height = SWATCH_H } = {}) {\n    const open = `<svg class=\"map-legend-symbol\" width=\"${width}\" height=\"${height}\" viewBox=\"0 0 ${width} ${height}\" aria-hidden=\"true\">`;\n    const cx = width / 2;\n    const cy = height / 2;\n    if (!symbol) return `${open}</svg>`;\n    if (symbol.type === 'text') {\n        return `${open}<text x=\"${cx}\" y=\"${cy + 4}\" text-anchor=\"middle\" font-size=\"11\" font-weight=\"600\" fill=\"${esc(symbol.color || '#334155')}\">Aa</text></svg>`;\n    }\n    if (symbol.type === 'line') {\n        const lineWidth = clamp(Number(symbol.width) || 1.5, 1, 5);\n        // Sv\u011Btl\u00E1 linie bez vlastn\u00EDho obrysu dostane v legend\u011B \u0161ed\u00FD, aby byla vid\u011Bt.\n        const casingColor = symbol.casing || (isVeryLight(symbol.stroke) ? CONTRAST : null);\n        const casing = casingColor\n            ? `<path d=\"M2 ${cy}H${width - 2}\" stroke=\"${esc(casingColor)}\" stroke-width=\"${lineWidth + (symbol.casing ? 2 : 1.2)}\" stroke-linecap=\"round\" fill=\"none\"/>`\n            : '';\n        const opacity = Number.isFinite(symbol.strokeOpacity) && symbol.strokeOpacity < 1 ? ` stroke-opacity=\"${symbol.strokeOpacity}\"` : '';\n        return `${open}${casing}<path d=\"M2 ${cy}H${width - 2}\" stroke=\"${esc(symbol.stroke || '#64748b')}\" stroke-width=\"${lineWidth}\"${opacity} stroke-linecap=\"${symbol.dash ? 'butt' : 'round'}\" fill=\"none\"${dashArray(symbol.dash)}/></svg>`;\n    }\n    if (symbol.type === 'point' && symbol.shape === PHOTO_SYMBOL) {\n        // Fotoapar\u00E1t (photo-marker.js) \u2014 v legend\u011B v\u017Edy v pln\u00E9 velikosti.\n        const r = Math.min(width, height) / 2 - 0.75;\n        const ink = symbol.stroke || '#ffffff';\n        const outline = isVeryLight(ink) && isVeryLight(symbol.fill) ? ` stroke=\"${CONTRAST}\" stroke-width=\"0.75\"` : '';\n        return `${open}<circle cx=\"${cx}\" cy=\"${cy}\" r=\"${r}\" fill=\"${esc(symbol.fill || '#3388ff')}\"${outline}/>`\n            + `<polygon points=\"${cameraPolygonPoints(cx, cy, r * 0.95)}\" fill=\"${esc(ink)}\"/>`\n            + `<circle cx=\"${cx}\" cy=\"${cy}\" r=\"${(r * 0.21).toFixed(2)}\" fill=\"${esc(symbol.fill || '#3388ff')}\"/></svg>`;\n    }\n    if (symbol.type === 'point') {\n        const r = clamp((Number(symbol.size) || 8) / 2, 2.5, 6.5);\n        const hollow = !symbol.fill;\n        const strokeWidth = hollow ? 1.5 : clamp(Number(symbol.strokeWidth) || 0, 0, 2);\n        const fill = hollow ? 'none' : esc(symbol.fill);\n        const fillOpacity = !hollow && Number.isFinite(symbol.fillOpacity) && symbol.fillOpacity < 1 ? ` fill-opacity=\"${symbol.fillOpacity}\"` : '';\n        // B\u00EDl\u00FD obrys (b\u011B\u017En\u00FD u te\u010Dek) je na b\u00EDl\u00E9 kart\u011B neviditeln\u00FD \u2014 v legend\u011B \u0161ed\u00FD.\n        const outline = symbol.stroke && isVeryLight(symbol.stroke) && (hollow || isVeryLight(symbol.fill))\n            ? CONTRAST : symbol.stroke;\n        const stroke = outline ? ` stroke=\"${esc(outline)}\" stroke-width=\"${strokeWidth || 1}\"` : '';\n        const shape = pointShape(symbol.shape, cx, cy, r);\n        // K\u0159\u00ED\u017Eky jsou jen \u010D\u00E1ry \u2014 kresl\u00ED se barvou obrysu (nebo v\u00FDpln\u011B).\n        if (['cross', 'x', 'bar'].includes(symbol.shape)) {\n            return `${open}${shape} stroke=\"${esc(symbol.stroke || symbol.fill || '#334155')}\" stroke-width=\"1.6\" stroke-linecap=\"round\"/></svg>`;\n        }\n        return `${open}${shape} fill=\"${fill}\"${fillOpacity}${stroke}/></svg>`;\n    }\n    // polygon\n    const hasFill = Boolean(symbol.fill) && symbol.fillOpacity !== 0;\n    const fillOpacity = Number.isFinite(symbol.fillOpacity) ? clamp(symbol.fillOpacity, 0, 1) : 1;\n    const strokeWidth = clamp(Number(symbol.strokeWidth) || 1, 0.75, 2.5);\n    // Sv\u011Btl\u00E1 plocha se sv\u011Btl\u00FDm (nebo \u017E\u00E1dn\u00FDm) obrysem dostane \u0161ed\u00FD r\u00E1me\u010Dek.\n    const lightFill = !hasFill || isVeryLight(symbol.fill) || fillOpacity < 0.25;\n    const outline = symbol.stroke && !(lightFill && isVeryLight(symbol.stroke))\n        ? symbol.stroke\n        : (lightFill ? CONTRAST : null);\n    const stroke = outline\n        ? ` stroke=\"${esc(outline)}\" stroke-width=\"${outline === symbol.stroke ? strokeWidth : 0.75}\"${outline === symbol.stroke ? dashArray(symbol.dash) : ''}`\n        : '';\n    let hatch = '';\n    if (hasFill && Array.isArray(symbol.hatch) && symbol.hatch.length) {\n        // \u0160rafa: p\u00E1r \u0161ikm\u00FDch \u010Dar v barv\u011B v\u00FDpln\u011B m\u00EDsto pln\u00E9 plochy.\n        hatch = `<path d=\"M4 13 13 3M9 13 18 3M14 13 20 6\" stroke=\"${esc(symbol.fill)}\" stroke-width=\"1\" fill=\"none\"/>`;\n    }\n    const fill = hasFill && !hatch ? `fill=\"${esc(symbol.fill)}\" fill-opacity=\"${fillOpacity}\"` : 'fill=\"none\"';\n    return `${open}<rect x=\"2\" y=\"2.5\" width=\"${width - 4}\" height=\"${height - 5}\" rx=\"2\" ${fill}${stroke}/>${hatch}</svg>`;\n}\n\n/* ---------------------------------------------------------------------------\n * Pravidla stylu \u2192 popis symbolu\n * ------------------------------------------------------------------------- */\n\n/** Pravidlo dan\u00E9 geometrie (`style.rules[...]`) jako popis symbolu. */\nexport function symbolFromRule(geometry, rule) {\n    if (!rule) return null;\n    if (geometry === 'point') {\n        return {\n            type: 'point', shape: rule.symbol, size: rule.size, fill: rule.fill, stroke: rule.stroke, strokeWidth: rule.strokeWidth,\n        };\n    }\n    if (geometry === 'line') {\n        return {\n            type: 'line', stroke: rule.stroke, width: rule.strokeWidth, dash: rule.dash, casing: rule.casing,\n        };\n    }\n    return {\n        type: 'polygon', fill: rule.fill, fillOpacity: rule.fillOpacity, stroke: rule.stroke, strokeWidth: rule.strokeWidth, dash: rule.dash,\n    };\n}\n\n/** Geometrie vrstvy v po\u0159ad\u00ED, v jak\u00E9m je nejl\u00E9pe reprezentuje symbol. */\nfunction primaryGeometries(entry) {\n    const order = ['polygon', 'line', 'point'];\n    const present = order.filter((g) => (entry.geometryTypes || []).includes(g));\n    return present.length ? present : ['point'];\n}\n\n/** V\u00EDce symbol\u016F (sm\u00ED\u0161en\u00E9 geometrie) vedle sebe jako jeden \u201Esymbol\u201C. */\nfunction combinedSvg(symbols) {\n    return symbols.map((symbol) => symbolSvg(symbol)).join('');\n}\n\nfunction formatNumber(value) {\n    if (!Number.isFinite(value)) return '';\n    const abs = Math.abs(value);\n    if (abs !== 0 && (abs < 0.01 || abs >= 1e6)) return value.toExponential(1);\n    if (abs >= 100) return String(Math.round(value));\n    return String(Number(value.toPrecision(3)));\n}\n\n/* ---------------------------------------------------------------------------\n * Legenda podle typu vrstvy\n * ------------------------------------------------------------------------- */\n\nconst MAX_ITEMS = 60;\n\nfunction vectorLegend(entry) {\n    const { style } = entry;\n    const geometries = primaryGeometries(entry);\n    const model = { items: [], more: 0 };\n\n    if (style.mode === 'native' && entry.native?.available) {\n        // Styl ulo\u017Een\u00FD v datech \u2014 legendu dodal Mapserver.\n        const items = [];\n        let more = 0;\n        (entry.native.legends || []).forEach((legend) => {\n            (legend.entries || []).forEach((item) => items.push({ symbol: item.symbol, label: item.label || '' }));\n            more += legend.more || 0;\n        });\n        model.swatch = items.length === 1 ? symbolSvg(items[0].symbol) : null;\n        model.items = items.length > 1 ? items.slice(0, MAX_ITEMS) : [];\n        model.more = more + Math.max(0, items.length - MAX_ITEMS);\n        model.note = 'Style from the file';\n        // Bez popisk\u016F (styl nesleduje \u017E\u00E1dn\u00FD atribut) sta\u010D\u00ED \u0159ada symbol\u016F.\n        model.strip = model.items.length > 0 && model.items.every((item) => !item.label);\n        return model;\n    }\n\n    const symbolsFor = (category) => geometries.map((geometry) => symbolFromRule(\n        geometry,\n        category ? ruleForCategory(geometry, style.rules[geometry], category) : style.rules[geometry],\n    ));\n\n    if (style.mode === 'categorized' && style.categorized?.attribute && style.categorized.categories?.length) {\n        const { categories, other } = style.categorized;\n        model.items = categories.slice(0, MAX_ITEMS).map((category) => ({\n            symbol: null, html: combinedSvg(symbolsFor(category)), label: category.label || category.value,\n        }));\n        model.more = Math.max(0, categories.length - MAX_ITEMS);\n        if (other?.enabled) {\n            model.items.push({ symbol: null, html: combinedSvg(symbolsFor(other)), label: 'Other' });\n        }\n        model.title = style.categorized.attribute;\n        return model;\n    }\n    if (style.mode === 'graduated' && style.graduated?.attribute && style.graduated.classes?.length) {\n        model.items = style.graduated.classes.map((cls) => ({\n            symbol: null, html: combinedSvg(symbolsFor(cls)), label: cls.label || `${cls.min} \u2013 ${cls.max}`,\n        }));\n        model.title = style.graduated.attribute;\n        return model;\n    }\n    model.swatch = combinedSvg(symbolsFor(null));\n    return model;\n}\n\n/** Barvy spojit\u00E9 \u0161k\u00E1ly rastru (\u0161ed\u00E1 / barevn\u00E1 mapa). */\nfunction rampColors(entry, rendering) {\n    if (rendering?.ramp?.length) return rendering.ramp.map((stop) => stop[1]);\n    const maps = entry.raster?.colormaps || {};\n    return maps[entry.style.colormap] || ['#000000', '#ffffff'];\n}\n\nfunction rasterLegend(entry) {\n    const { style } = entry;\n    const rendering = entry.rasterRendering || entry.raster?.rendering || null;\n    const model = { items: [], more: 0 };\n    if (style.mode === 'palette') {\n        const palette = entry.raster?.palette || [];\n        model.items = palette.slice(0, MAX_ITEMS).map((item) => ({\n            symbol: { type: 'polygon', fill: item.color, fillOpacity: item.opacity ?? 1, stroke: '#cbd5e1', strokeWidth: 0.75 },\n            label: item.label || `Value ${item.value}`,\n        }));\n        model.more = Math.max(0, palette.length - MAX_ITEMS);\n        model.swatch = paletteSwatch(palette.map((item) => item.color));\n        return model;\n    }\n    if (style.mode === 'rgb') {\n        const names = { r: 'R', g: 'G', b: 'B' };\n        model.channels = ['r', 'g', 'b'].map((key) => ({ name: names[key], band: style.bands[key] }));\n        model.swatch = rgbSwatch();\n        return model;\n    }\n    const colors = style.mode === 'ramp' ? rampColors(entry, rendering) : ['#000000', '#ffffff'];\n    // Hodnoty na konc\u00EDch \u0161k\u00E1ly zn\u00E1 Mapserver (podle zvolen\u00E9ho rozta\u017Een\u00ED).\n    const scale = rendering && rendering.mode === (style.mode === 'ramp' ? 'ramp' : 'gray') ? rendering.scales?.[0] : null;\n    model.gradient = {\n        colors,\n        min: scale ? formatNumber(scale[0]) : '',\n        max: scale ? formatNumber(scale[1]) : '',\n    };\n    model.swatch = gradientSwatch(colors);\n    return model;\n}\n\nfunction gradientCss(colors) {\n    return `linear-gradient(to right, ${colors.join(', ')})`;\n}\n\nfunction gradientSwatch(colors) {\n    return `<span class=\"map-legend-chip\" style=\"background:${esc(gradientCss(colors))}\"></span>`;\n}\n\nfunction rgbSwatch() {\n    return '<span class=\"map-legend-chip\" style=\"background:linear-gradient(to right,#ef4444 0 33%,#22c55e 33% 66%,#3b82f6 66%)\"></span>';\n}\n\nfunction paletteSwatch(colors) {\n    const picked = colors.slice(0, 4);\n    if (picked.length === 0) return '<span class=\"map-legend-chip\" style=\"background:#e2e8f0\"></span>';\n    const step = 100 / picked.length;\n    const stops = picked.map((color, i) => `${color} ${(i * step).toFixed(0)}% ${((i + 1) * step).toFixed(0)}%`);\n    return `<span class=\"map-legend-chip\" style=\"background:linear-gradient(to right, ${esc(stops.join(', '))})\"></span>`;\n}\n\n/**\n * Popis legendy vrstvy (viz hlavi\u010Dka souboru). Vrac\u00ED null pro typy, kter\u00E9\n * legendu nemaj\u00ED (dla\u017Edicov\u00E9 slu\u017Eby, kresba).\n */\nexport function legendModel(entry) {\n    if (!entry || entry.isGroup) return null;\n    if (entry.dataType === 'raster') return rasterLegend(entry);\n    if (entry.dataType === 'vector' && !entry.external) return vectorLegend(entry);\n    if (entry.dataType === 'local') {\n        const color = entry.localColor || '#7c3aed';\n        return {\n            items: [],\n            more: 0,\n            swatch: combinedSvg(primaryGeometries(entry).slice(0, 1).map((geometry) => symbolFromRule(geometry, {\n                symbol: 'circle', size: 8, fill: color, fillOpacity: 0.3, stroke: color, strokeWidth: 1.5,\n            }))),\n        };\n    }\n    if (entry.dataType === 'wms' && entry.legendUrl) {\n        return { items: [], more: 0, image: entry.legendUrl };\n    }\n    return null;\n}\n\n/** M\u00E1 legenda rozbalovac\u00ED \u010D\u00E1st (seznam t\u0159\u00EDd, \u0161k\u00E1lu, obr\u00E1zek\u2026)? */\nexport function legendHasBody(model) {\n    return Boolean(model && (model.items?.length || model.gradient || model.channels || model.image));\n}\n\n/** HTML t\u011Bla legendy (pod n\u00E1zvem vrstvy). `limit` = kolik polo\u017Eek seznamu\n * uk\u00E1zat, ne\u017E se nab\u00EDdne \u201E+ N more\u201C. */\nexport function legendBodyHtml(model, { limit = 8, expanded = false } = {}) {\n    if (!legendHasBody(model)) return '';\n    const parts = [];\n    if (model.title) {\n        parts.push(`<p class=\"map-legend-title\" title=\"Styled by attribute \u201C${esc(model.title)}\u201D\">${esc(model.title)}</p>`);\n    }\n    if (model.items?.length) {\n        const shown = expanded ? model.items : model.items.slice(0, limit);\n        const hidden = model.items.length - shown.length + (expanded ? model.more || 0 : model.more || 0);\n        if (model.strip) {\n            parts.push(`<div class=\"map-legend-strip\">${shown.map((item) => (item.html || symbolSvg(item.symbol))).join('')}</div>`);\n        } else {\n            parts.push(`<ul class=\"map-legend-list\">${shown.map((item) => `\n                <li><span class=\"map-legend-key\">${item.html || symbolSvg(item.symbol)}</span><span class=\"map-legend-label\" title=\"${esc(item.label)}\">${esc(item.label) || '&nbsp;'}</span></li>`).join('')}</ul>`);\n        }\n        if (hidden > 0) {\n            const canExpand = !expanded && model.items.length > shown.length;\n            parts.push(canExpand\n                ? `<button type=\"button\" data-role=\"legend-more\" class=\"map-legend-more\">+ ${hidden} more\u2026</button>`\n                : `<p class=\"map-legend-more-note\">+ ${hidden} more</p>`);\n        } else if (expanded && model.items.length > limit) {\n            parts.push('<button type=\"button\" data-role=\"legend-less\" class=\"map-legend-more\">Show less</button>');\n        }\n    }\n    if (model.gradient) {\n        parts.push(`\n            <div class=\"map-legend-gradient\" style=\"background:${esc(gradientCss(model.gradient.colors))}\"></div>\n            <div class=\"map-legend-range\"><span>${esc(model.gradient.min)}</span><span>${esc(model.gradient.max)}</span></div>`);\n    }\n    if (model.channels) {\n        const colors = { R: '#ef4444', G: '#22c55e', B: '#3b82f6' };\n        parts.push(`<div class=\"map-legend-channels\">${model.channels.map((channel) => `\n            <span><i style=\"background:${colors[channel.name]}\"></i>${channel.name} \u00B7 band ${esc(channel.band)}</span>`).join('')}</div>`);\n    }\n    if (model.image) {\n        parts.push(`<img src=\"${esc(model.image)}\" alt=\"Legend\" class=\"map-legend-image\" loading=\"lazy\">`);\n    }\n    if (model.note) {\n        parts.push(`<p class=\"map-legend-note\">${esc(model.note)}</p>`);\n    }\n    return parts.join('');\n}\n", "/**\n * layers.js \u2014 spr\u00E1va b\u011Bhov\u00E9ho seznamu vrstev + vykreslen\u00ED stromu vrstev\n * v lev\u00E9m panelu (viditelnost, po\u0159ad\u00ED drag&drop, zoom na vrstvu, odebr\u00E1n\u00ED,\n * p\u0159ejmenov\u00E1n\u00ED inline, legenda kreslen\u00E1 v aplikaci \u2014 legend.js).\n *\n * Karta vrstvy je kompaktn\u00ED: \u00FAchyt, viditelnost, symbol vrstvy (resp. \u0161ipka\n * rozbalen\u00ED legendy u klasifikovan\u00FDch vrstev), n\u00E1zev, stav vykreslov\u00E1n\u00ED,\n * tla\u010D\u00EDtko stylu a menu. Pr\u016Fhlednost je prvn\u00ED polo\u017Ekou panelu stylu (a v\n * Properties); kdy\u017E nen\u00ED 100 %, ukazuje ji \u0161t\u00EDtek u n\u00E1zvu.\n */\nimport { offersSampleMaps, renderSampleMapsHint } from './sample-maps.js';\nimport { clamp, debounce, emit } from './utils.js';\nimport {\n    createLayerEntry,\n    createGroupEntry,\n    flatLayers,\n    findEntryByUid,\n    findEntryContainer,\n    isEffectivelyVisible,\n    serializeLayerEntry,\n} from './state.js';\nimport {\n    createWmsLayer, fetchItemDetail, forgetItemDetail, rasterParams, scheduleWmsRefresh,\n} from './wms.js';\nimport { isFilterActive } from './filter.js';\nimport { zoomToExtent } from './map.js';\nimport { createDrawingLayer } from './draw.js';\nimport { restoreExternalLayer } from './external.js';\nimport { HYBRID_ICON_PATHS } from './hybrid.js';\nimport {\n    describeItem, describeRaster, forgetDescription, layerDetail, logicalLayers,\n} from './describe.js';\nimport { itemLayerEntries } from './item-layers.js';\nimport { legendBodyHtml, legendHasBody, legendModel } from './legend.js';\nimport {\n    beginPreparing, endPreparing, sizeNote, updatePreparing,\n} from './loading.js';\nimport { fromLonLat } from 'ol/proj.js';\n\n/** Od kolika vrstev se skupina souboru vytvo\u0159\u00ED sbalen\u00E1. */\nconst COLLAPSE_GROUP_FROM = 20;\n\n/** Vlo\u017E\u00ED b\u011Bhov\u00FD z\u00E1znam vrstvy navrch stromu i mapy (OpenLayers kresl\u00ED vrstvy\n * v po\u0159ad\u00ED kolekce \u2014 posledn\u00ED je naho\u0159e). */\nfunction mountEntry(ctx, entry, list = ctx.state.layers) {\n    const olLayer = createWmsLayer(entry, ctx.bootstrap);\n    list.unshift(entry);\n    ctx.map.addLayer(olLayer);\n    applyZoomLimits(entry);\n    if (entry.dataType === 'raster') updateRasterLegend(ctx, entry);\n    return entry;\n}\n\n/** Chyba \u201Evrstva souboru u\u017E neexistuje\u201C ve tvaru chyb API (hl\u00E1s\u00ED se jako 404). */\nfunction missingLayerError(title) {\n    const error = new Error(`Layer \"${title}\" is no longer in the file.`);\n    error.status = 404;\n    return error;\n}\n\n/** Ulo\u017Een\u00FD z\u00E1znam pro jednu vrstvu souboru p\u0159i p\u0159evodu star\u0161\u00EDho z\u00E1znamu,\n * kter\u00FD kreslil v\u0161echny vrstvy souboru najednou: p\u0159evezme viditelnost,\n * pr\u016Fhlednost, m\u011B\u0159\u00EDtka i styl; filtr jen kdy\u017E vrstva jeho atributy m\u00E1. */\nfunction legacyConfigFor(saved, logical) {\n    const attributes = new Set(logical.sublayers.flatMap((sub) => (sub.attributes || []).map((a) => a.name)));\n    const conditions = saved.filter?.conditions || [];\n    const filterFits = conditions.length > 0 && conditions.every((c) => !c.attribute || attributes.has(c.attribute));\n    return {\n        ...saved,\n        title: logical.title,\n        layer: logical.key,\n        style: saved.style ? JSON.parse(JSON.stringify(saved.style)) : undefined,\n        filter: filterFits ? saved.filter : null,\n    };\n}\n\n/**\n * Vytvo\u0159\u00ED (nebo znovu pou\u017Eije) vrstvy polo\u017Eky workspace a vlo\u017E\u00ED je na mapu\n * i do stromu.\n *\n * Soubor s jedinou vrstvou = jeden z\u00E1znam stromu. Soubor s v\u00EDce vrstvami\n * (GPKG, KML, FileGDB\u2026, i soubor s vektory a rastrem z\u00E1rove\u0148) = **skupina**\n * pojmenovan\u00E1 podle souboru a v n\u00ED ka\u017Ed\u00E1 vrstva zvl\u00E1\u0161\u0165 \u2014 s vlastn\u00EDm stylem,\n * filtrem, tabulkou a viditelnost\u00ED. Vrstvy a jejich skute\u010Dn\u00E9 n\u00E1zvy dod\u00E1\n * Mapserver (describe.js), p\u0159i jeho nedostupnosti p\u0159edpov\u011B\u010F backendu.\n *\n * Vrac\u00ED vytvo\u0159en\u00FD z\u00E1znam (vrstvu \u010Di skupinu); p\u0159i obnov\u011B star\u0161\u00EDho ulo\u017Een\u00E9ho\n * z\u00E1znamu, kter\u00FD kreslil cel\u00FD v\u00EDcevrstv\u00FD soubor najednou, **pole** z\u00E1znam\u016F\n * (volaj\u00EDc\u00ED je vlo\u017E\u00ED do skupiny \u2014 main.js). Deduplikace podle `itemId` plat\u00ED\n * jen pro interaktivn\u00ED p\u0159id\u00E1n\u00ED (\"Add data\").\n */\nexport async function addLayerByItemId(ctx, itemId, savedLayer, options = {}) {\n    if (!savedLayer) {\n        const existing = flatLayers(ctx.state).find((l) => l.itemId === itemId);\n        if (existing) return findEntryContainer(ctx.state, existing.uid)?.group || existing;\n    }\n    // Hned d\u00E1t v\u011Bd\u011Bt, \u017Ee se vrstva p\u0159ipravuje: detail je rychl\u00FD, ale popis\n    // dat u Mapserveru \u010Dte u velk\u00E9ho souboru cel\u00FD soubor.\n    const pending = options.pending || beginPreparing(ctx, savedLayer?.title || options.title || 'New layer');\n    if (!options.pending) renderLayerTree(ctx);\n    try {\n        return await addPreparedLayer(ctx, itemId, savedLayer, pending);\n    } finally {\n        endPreparing(ctx, pending);\n        renderLayerTree(ctx);\n    }\n}\n\n/** Nachyst\u00E1 si detail a popis polo\u017Eky dop\u0159edu (ulo\u017Een\u00E1 mapa: v\u0161echny vrstvy\n * nar\u00E1z, i kdy\u017E se pak do stromu vkl\u00E1daj\u00ED po jedn\u00E9). Chyby se tady ne\u0159e\u0161\u00ED \u2014\n * ohl\u00E1s\u00ED je a\u017E samotn\u00E9 p\u0159id\u00E1n\u00ED vrstvy. */\nexport function prefetchItem(ctx, itemId) {\n    fetchItemDetail(ctx.bootstrap, itemId, ctx.state.mapId)\n        .then((detail) => describeItem(ctx.bootstrap, detail))\n        .catch(() => {});\n}\n\nasync function addPreparedLayer(ctx, itemId, savedLayer, pending) {\n    const detail = await fetchItemDetail(ctx.bootstrap, itemId, ctx.state.mapId);\n    updatePreparing(ctx, pending, {\n        title: savedLayer?.title || detail.title || pending.title,\n        note: sizeNote(detail.source),\n    });\n    refreshPreparingRow(ctx, pending);\n    const described = await describeItem(ctx.bootstrap, detail);\n    const logical = logicalLayers(detail, described);\n    if (logical.length === 0) throw missingLayerError(detail.title);\n    const single = logical.length === 1;\n\n    if (savedLayer) {\n        const restored = restoreItemLayers(ctx, detail, logical, savedLayer);\n        renderLayerTree(ctx);\n        (Array.isArray(restored) ? restored : [restored]).forEach((entry) => emit('layers:changed', { reason: 'add', entry }));\n        return restored;\n    }\n\n    // Vrstvy a jejich v\u00FDchoz\u00ED styl \u2014 stejn\u00E9 kresl\u00ED i n\u00E1hled dat (item-layers.js).\n    const entries = itemLayerEntries(detail, logical);\n    let result;\n    if (single) {\n        result = mountEntry(ctx, entries[0]);\n    } else {\n        const group = createGroupEntry({\n            title: detail.title,\n            hybrid: detail.data_type === 'hybrid',\n            dataset: true,\n            collapsed: logical.length > COLLAPSE_GROUP_FROM,\n        });\n        ctx.state.layers.unshift(group);\n        // Ka\u017Ed\u00E1 dal\u0161\u00ED vrstva jde navrch skupiny i mapy \u2192 z\u00E1znamy za\u010D\u00EDnaj\u00ED\n        // t\u00EDm, co m\u00E1 b\u00FDt vespod (`drawingOrder`).\n        entries.forEach((entry) => mountEntry(ctx, entry, group.children));\n        result = group;\n    }\n    renderLayerTree(ctx);\n    emit('layers:changed', { reason: 'add', entry: result });\n    reportSkipped(ctx, detail, described, result);\n    return result;\n}\n\n/** Obnov\u00ED ulo\u017Een\u00FD z\u00E1znam polo\u017Eky (viz `addLayerByItemId`). */\nfunction restoreItemLayers(ctx, detail, logical, saved) {\n    const single = logical.length === 1;\n    const byKind = (kind) => logical.filter((layer) => layer.kind === kind);\n    let target = null;\n    if (saved.layer !== undefined && saved.layer !== null) {\n        const wantedKind = saved.hybridPart === 'raster' ? 'raster' : (saved.hybridPart === 'vector' ? 'vector' : null);\n        target = logical.find((layer) => layer.key === saved.layer && (!wantedKind || layer.kind === wantedKind))\n            || logical.find((layer) => layer.key === saved.layer);\n        if (!target) throw missingLayerError(saved.title || saved.layer);\n    } else if (saved.hybridPart === 'raster') {\n        [target] = byKind('raster');\n        if (!target) throw missingLayerError(saved.title || 'Raster image');\n    } else if (single) {\n        [target] = logical;\n    }\n    if (target) {\n        return mountEntry(ctx, createLayerEntry(layerDetail(detail, target, { single }), saved));\n    }\n    // Star\u0161\u00ED z\u00E1znam za cel\u00FD v\u00EDcevrstv\u00FD soubor (resp. za vektorovou \u010D\u00E1st\n    // hybridu) \u2192 jeden z\u00E1znam na vrstvu, se stejn\u00FDm nastaven\u00EDm.\n    const layers = saved.hybridPart === 'vector' ? byKind('vector') : logical;\n    if (layers.length === 0) throw missingLayerError(saved.title || detail.title);\n    const entries = layers.map((layer) => mountEntry(\n        ctx,\n        createLayerEntry(layerDetail(detail, layer), legacyConfigFor(saved, layer)),\n    ));\n    entries.reverse(); // prvn\u00ED = naho\u0159e ve stromu\n    entries.legacyTitle = saved.title || detail.title;\n    return entries;\n}\n\n/**\n * Znovu na\u010Dte vrstvy polo\u017Eky ze slu\u017Eby \u2014 po zm\u011Bn\u011B souboru, ze kter\u00E9ho se kresl\u00ED\n * (kopie pro rychl\u00E9 kreslen\u00ED, advisor.js). Z\u00E1znamy z\u016Fstanou na sv\u00E9m m\u00EDst\u011B ve\n * stromu se stejn\u00FDm stylem, filtrem, n\u00E1zvem i `uid`; m\u011Bn\u00ED se jen zdroj dat\n * a n\u00E1zvy vrstev slu\u017Eby.\n */\nexport async function reloadItemLayers(ctx, itemId) {\n    const entries = flatLayers(ctx.state).filter((entry) => entry.itemId === itemId && entry.wms);\n    if (entries.length === 0) return 0;\n    forgetItemDetail(itemId);\n    forgetDescription(itemId);\n    const detail = await fetchItemDetail(ctx.bootstrap, itemId, ctx.state.mapId);\n    const described = await describeItem(ctx.bootstrap, detail);\n    const logical = logicalLayers(detail, described);\n    const single = logical.length === 1;\n    let reloaded = 0;\n    entries.forEach((entry) => {\n        const sameKind = logical.filter((layer) => layer.kind === (entry.dataType === 'raster' ? 'raster' : 'vector'));\n        const target = sameKind.find((layer) => layer.key === entry.layerKey)\n            || sameKind.find((layer) => layer.title === entry.layerKey)\n            || (sameKind.length === 1 ? sameKind[0] : null);\n        const container = findEntryContainer(ctx.state, entry.uid);\n        if (!target || !container) return;\n        const fresh = createLayerEntry(layerDetail(detail, target, { single }), serializeLayerEntry(entry));\n        fresh.uid = entry.uid;\n        // Vrstva souboru si dr\u017E\u00ED sv\u016Fj kl\u00ED\u010D (ulo\u017Een\u00E9 mapy ho maj\u00ED v configu).\n        if (entry.layerKey !== null && entry.layerKey !== undefined) fresh.layerKey = entry.layerKey;\n        if (entry.olLayer) ctx.map.removeLayer(entry.olLayer);\n        ctx.map.addLayer(createWmsLayer(fresh, ctx.bootstrap));\n        container.list[container.index] = fresh;\n        applyZoomLimits(fresh);\n        if (fresh.dataType === 'raster') updateRasterLegend(ctx, fresh);\n        reloaded += 1;\n    });\n    syncMapLayerOrder(ctx);\n    applyEffectiveVisibility(ctx);\n    renderLayerTree(ctx);\n    flatLayers(ctx.state).filter((entry) => entry.itemId === itemId)\n        .forEach((entry) => emit('layers:changed', { reason: 'reload', entry }));\n    return reloaded;\n}\n\n/** \u010C\u00E1sti souboru, kter\u00E9 Mapserver nevykresl\u00ED (vrstva bez polohy, text bez\n * geometrie\u2026) \u2014 ohl\u00E1s\u00ED se hned p\u0159i p\u0159id\u00E1n\u00ED podle popisu dat. */\nfunction reportSkipped(ctx, detail, described, result) {\n    const layers = (described?.skipped || []).map((item) => ({\n        name: item.name, kind: item.kind, reason: item.reason, code: item.code,\n    }));\n    if (layers.length === 0) return;\n    const entry = result.isGroup ? result.children[0] : result;\n    if (entry) emit('wms:diagnostics', { entry, skipped: { layers, omitted: 0 }, hybrid: { groups: [], omitted: 0 } });\n}\n\n/** Zjist\u00ED u Mapserveru, jak se rastr kresl\u00ED s aktu\u00E1ln\u00EDm stylem (hodnoty na\n * konc\u00EDch \u0161k\u00E1ly\u2026), a p\u0159ekresl\u00ED legendu vrstvy. Vol\u00E1 se po p\u0159id\u00E1n\u00ED vrstvy\n * a po zm\u011Bn\u011B stylu rastru (s prodlevou \u2014 ta\u017Een\u00ED posuvn\u00EDku). */\nconst rasterLegendTimers = new Map();\n\nexport function updateRasterLegend(ctx, entry) {\n    if (!entry || entry.dataType !== 'raster') return;\n    clearTimeout(rasterLegendTimers.get(entry.uid));\n    rasterLegendTimers.set(entry.uid, setTimeout(async () => {\n        rasterLegendTimers.delete(entry.uid);\n        const rendering = await describeRaster(ctx.bootstrap, entry, rasterParams(entry));\n        if (!rendering) return;\n        entry.rasterRendering = rendering;\n        refreshLayerRow(ctx, entry);\n    }, 350));\n}\n\n/** P\u0159esune OL vrstvy tak, aby odpov\u00EDdalo po\u0159ad\u00ED stromu (zplo\u0161t\u011Bn\u00E9 skupiny;\n * prvn\u00ED prvek = naho\u0159e v panelu = kresl\u00ED se jako posledn\u00ED, tedy nejv\u00FD\u0161e na\n * map\u011B). Vrstva dole v panelu se vykresl\u00ED jako prvn\u00ED (hned nad podklady). */\nfunction syncMapLayerOrder(ctx) {\n    const collection = ctx.map.getLayers();\n    const entries = flatLayers(ctx.state);\n    entries.forEach((entry) => {\n        if (!entry.olLayer) return;\n        collection.remove(entry.olLayer);\n    });\n    // Podklady jsou prvn\u00ED 4 (osm/satellite/topo/none) \u2014 data vkl\u00E1d\u00E1me za n\u011B.\n    // Ka\u017Edou vrstvu vlo\u017E\u00EDme na index 4: posledn\u00ED vlo\u017Een\u00E1 (spodek panelu)\n    // skon\u010D\u00ED hned nad podklady, prvn\u00ED prvek pole skon\u010D\u00ED nejv\u00FD\u0161e.\n    entries.forEach((entry) => {\n        if (entry.olLayer) collection.insertAt(4, entry.olLayer);\n    });\n}\n\n/** Prom\u00EDtne efektivn\u00ED viditelnost (checkbox vrstvy AND checkbox skupiny) do\n * OL vrstev \u2014 stavy d\u011Bt\u00ED se p\u0159i vypnut\u00ED skupiny nep\u0159episuj\u00ED. */\nfunction applyEffectiveVisibility(ctx) {\n    flatLayers(ctx.state).forEach((entry) => {\n        entry.olLayer?.setVisible(isEffectivelyVisible(ctx.state, entry));\n    });\n}\n\n/** Aplikuje m\u011B\u0159\u00EDtkov\u00E1 omezen\u00ED na OL vrstvu. OL s\u00E9mantika: vrstva je vid\u011Bt p\u0159i\n * zoomu > minZoom a <= maxZoom \u2014 aby byl `entry.minZoom` inkluzivn\u00ED, pos\u00EDl\u00E1\n * se s mal\u00FDm z\u00E1porn\u00FDm posunem. */\nexport function applyZoomLimits(entry) {\n    if (!entry.olLayer) return;\n    entry.olLayer.setMinZoom(Number.isFinite(entry.minZoom) ? entry.minZoom - 0.001 : -Infinity);\n    entry.olLayer.setMaxZoom(Number.isFinite(entry.maxZoom) ? entry.maxZoom : Infinity);\n}\n\n/** Nastav\u00ED min/max zoom vrstvy (null = bez limitu) \u2014 Properties modal. */\nexport function setLayerZoomLimits(ctx, uid, minZoom, maxZoom) {\n    const entry = findEntryByUid(ctx.state, uid);\n    if (!entry || entry.isGroup) return;\n    entry.minZoom = Number.isFinite(minZoom) ? clamp(minZoom, 0, 28) : null;\n    entry.maxZoom = Number.isFinite(maxZoom) ? clamp(maxZoom, 0, 28) : null;\n    applyZoomLimits(entry);\n    ctx.state.dirty = true;\n    updateScaleDimming(ctx);\n    emit('layers:changed', { reason: 'zoom-limits', entry });\n}\n\nexport function removeLayer(ctx, uid) {\n    // Odebr\u00E1n\u00ED skupiny m\u00E1 vlastn\u00ED cestu \u2014 d\u011Bti se p\u0159esouvaj\u00ED o \u00FArove\u0148 v\u00FD\u0161.\n    const found = findEntryByUid(ctx.state, uid);\n    if (found?.isGroup) {\n        removeGroup(ctx, uid);\n        return;\n    }\n    const container = findEntryContainer(ctx.state, uid);\n    if (!container) return;\n    const [entry] = container.list.splice(container.index, 1);\n    if (entry.olLayer) ctx.map.removeLayer(entry.olLayer);\n    renderLayerTree(ctx);\n    emit('layers:changed', { reason: 'remove', entry });\n}\n\nexport function setLayerVisibility(ctx, uid, visible) {\n    const entry = findEntryByUid(ctx.state, uid);\n    if (!entry) return;\n    entry.visible = visible;\n    applyEffectiveVisibility(ctx);\n    // Vypnut\u00ED/zapnut\u00ED skupiny m\u011Bn\u00ED efektivn\u00ED viditelnost d\u011Bt\u00ED \u2014 p\u0159ekreslit strom.\n    if (entry.isGroup) renderLayerTree(ctx);\n    emit('layers:changed', { reason: 'visibility', entry });\n}\n\nexport function setLayerOpacity(ctx, uid, opacity) {\n    const entry = findEntryByUid(ctx.state, uid);\n    if (!entry || entry.isGroup) return;\n    entry.opacity = clamp(opacity, 0, 1);\n    // Pr\u016Fhlednost = OL layer.setOpacity, \u017E\u00E1dn\u00FD nov\u00FD GetMap request.\n    entry.olLayer?.setOpacity(entry.opacity);\n    refreshOpacityBadge(ctx, entry);\n    emit('layers:changed', { reason: 'opacity', entry });\n}\n\n/** \u0160t\u00EDtek pr\u016Fhlednosti v \u0159\u00E1dku vrstvy (bez z\u00E1sahu do zbytku \u0159\u00E1dku). */\nfunction refreshOpacityBadge(ctx, entry) {\n    const row = ctx.elements.layerTree?.querySelector(`[data-uid=\"${entry.uid}\"]`);\n    const slot = row?.querySelector('[data-role=\"opacity-slot\"]');\n    if (!slot) return;\n    slot.innerHTML = opacityBadgeHtml(entry);\n    wireOpacityBadge(ctx, row, entry);\n}\n\nexport function renameLayer(ctx, uid, title) {\n    const entry = findEntryByUid(ctx.state, uid);\n    if (!entry) return;\n    entry.title = title || entry.title;\n    emit('layers:changed', { reason: 'rename', entry });\n}\n\n/** P\u0159esune z\u00E1znam do c\u00EDlov\u00E9ho kontejneru (`groupUid` = uid skupiny, null =\n * top-level) na dan\u00FD index. Skupinu lze p\u0159esouvat jen v top-level. */\nexport function moveEntry(ctx, uid, groupUid, newIndex) {\n    const entry = findEntryByUid(ctx.state, uid);\n    const source = findEntryContainer(ctx.state, uid);\n    if (!entry || !source) return;\n    const group = groupUid ? findEntryByUid(ctx.state, groupUid) : null;\n    if (groupUid && (!group || !group.isGroup)) return;\n    if (entry.isGroup && group) return; // skupiny ve skupin\u00E1ch nepodporujeme\n    const targetList = group ? group.children : ctx.state.layers;\n    source.list.splice(source.index, 1);\n    targetList.splice(clamp(newIndex, 0, targetList.length), 0, entry);\n    syncMapLayerOrder(ctx);\n    applyEffectiveVisibility(ctx);\n    renderLayerTree(ctx);\n    emit('layers:changed', { reason: 'reorder', entry });\n}\n\n/** Posune vrstvu (nebo skupinu) o `step` m\u00EDst v r\u00E1mci jej\u00EDho kontejneru \u2014\n * -1 = v\u00FD\u0161 ve stromu (v map\u011B nad sousedn\u00ED vrstvu), +1 = n\u00ED\u017E. */\nexport function reorderEntry(ctx, uid, step) {\n    const source = findEntryContainer(ctx.state, uid);\n    if (!source) return;\n    const index = source.index + step;\n    if (index < 0 || index >= source.list.length) return;\n    moveEntry(ctx, uid, source.group?.uid || null, index);\n    ctx.state.dirty = true;\n}\n\n/** Vytvo\u0159\u00ED pr\u00E1zdnou skupinu navrchu stromu (tla\u010D\u00EDtko \"New group\"). */\nexport function createGroup(ctx) {\n    const group = createGroupEntry();\n    ctx.state.layers.unshift(group);\n    ctx.state.dirty = true;\n    renderLayerTree(ctx);\n    emit('layers:changed', { reason: 'add-group', entry: group });\n    return group;\n}\n\n/** Odebere skupinu i s jej\u00EDmi vrstvami (skupina jednoho souboru s v\u00EDce\n * vrstvami = jedna polo\u017Eka dat). */\nexport function removeGroupWithLayers(ctx, uid) {\n    const index = ctx.state.layers.findIndex((e) => e.uid === uid && e.isGroup);\n    if (index === -1) return;\n    const [group] = ctx.state.layers.splice(index, 1);\n    group.children.forEach((entry) => {\n        if (entry.olLayer) ctx.map.removeLayer(entry.olLayer);\n        emit('layers:changed', { reason: 'remove', entry });\n    });\n    ctx.state.dirty = true;\n    renderLayerTree(ctx);\n    emit('layers:changed', { reason: 'remove-group', entry: group });\n}\n\n/** Sma\u017Ee skupinu \u2014 d\u011Bti se p\u0159esunou o \u00FArove\u0148 v\u00FD\u0161 na m\u00EDsto skupiny. */\nexport function removeGroup(ctx, uid) {\n    const index = ctx.state.layers.findIndex((e) => e.uid === uid && e.isGroup);\n    if (index === -1) return;\n    const [group] = ctx.state.layers.splice(index, 1);\n    ctx.state.layers.splice(index, 0, ...group.children);\n    ctx.state.dirty = true;\n    applyEffectiveVisibility(ctx);\n    renderLayerTree(ctx);\n    emit('layers:changed', { reason: 'remove-group', entry: group });\n}\n\n/** Duplikuje vrstvu: hlubok\u00E1 kopie configu (styl, filtr, opacity, scale limity,\n * u kresby/lok\u00E1ln\u00EDch dat i geojson), titulek \"<title> (copy)\", vlo\u017E\u00ED se hned\n * pod origin\u00E1l do t\u00E9ho\u017E kontejneru. Workspace vrstvy se vytv\u00E1\u0159ej\u00ED z b\u011Bhov\u00FDch\n * dat origin\u00E1lu (WMS detail u\u017E m\u00E1me \u2014 bez dal\u0161\u00EDho vol\u00E1n\u00ED API). */\nexport async function duplicateLayer(ctx, uid) {\n    const entry = findEntryByUid(ctx.state, uid);\n    const container = findEntryContainer(ctx.state, uid);\n    if (!entry || entry.isGroup || !container) return null;\n    const savedConfig = JSON.parse(JSON.stringify(serializeLayerEntry(entry)));\n    savedConfig.title = `${entry.title} (copy)`;\n\n    let copy = null;\n    if (entry.dataType === 'drawing') {\n        // Kresba: druh\u00E1 drawing vrstva (forceNew) \u2014 kreslic\u00ED n\u00E1stroje edituj\u00ED\n        // v\u017Edy nejv\u00FD\u0161e polo\u017Eenou kresbu (viz draw.js findDrawingEntry).\n        copy = createDrawingLayer(ctx, savedConfig, { forceNew: true });\n    } else if (entry.external) {\n        copy = await restoreExternalLayer(ctx, savedConfig);\n    } else {\n        // Workspace vrstva: nov\u00FD z\u00E1znam z klonu configu + b\u011Bhov\u00FDch metadat\n        // origin\u00E1lu (podvrstvy, podpis, styl z dat\u2026) \u2014 bez dal\u0161\u00EDho dotazu.\n        copy = createLayerEntry({\n            id: entry.itemId,\n            title: entry.itemTitle || entry.title,\n            layer_title: entry.title,\n            layer_key: entry.layerKey,\n            layer_bbox: entry.bbox,\n            data_type: entry.dataType,\n            item_data_type: entry.itemDataType,\n            hybrid_part: entry.hybridPart,\n            layers: entry.sublayers,\n            bands: entry.bands,\n            source: entry.source,\n            native: entry.native,\n            suggested: entry.suggested,\n            raster: entry.raster,\n            raster_class: entry.rasterClass,\n            wms_url: entry.wms?.url,\n            params: {\n                FILE_URL: entry.wms?.fileUrl,\n                sig: entry.wms?.sig,\n                PAYER: entry.wms?.payer,\n                FILE_CRS: entry.wms?.fileCrs,\n            },\n            expires_at: entry.wms?.expiresAt,\n        }, savedConfig);\n        copy.rasterRendering = entry.rasterRendering || null;\n        const olLayer = createWmsLayer(copy, ctx.bootstrap);\n        ctx.state.layers.unshift(copy);\n        ctx.map.addLayer(olLayer);\n    }\n    if (!copy) return null;\n    copy.minZoom = savedConfig.minZoom ?? null;\n    copy.maxZoom = savedConfig.maxZoom ?? null;\n    applyZoomLimits(copy);\n    // Kopie vznikla navrchu stromu \u2014 p\u0159esun hned pod origin\u00E1l.\n    const originalPos = findEntryContainer(ctx.state, uid);\n    moveEntry(ctx, copy.uid, originalPos.group?.uid || null, originalPos.index + 1);\n    ctx.state.dirty = true;\n    return copy;\n}\n\n/** Zru\u0161\u00ED atributov\u00FD filtr vrstvy \u2014 obnov\u00ED mapu (SLD), strom i p\u0159\u00EDpadnou\n * otev\u0159enou atributovou tabulku (p\u0159es ud\u00E1lost `layers:filter-cleared`). */\nexport function clearLayerFilter(ctx, uid) {\n    const entry = findEntryByUid(ctx.state, uid);\n    if (!entry) return;\n    entry.filter = null;\n    ctx.state.dirty = true;\n    scheduleWmsRefresh(entry);\n    renderLayerTree(ctx);\n    emit('layers:filter-cleared', { entry });\n}\n\n/** P\u0159ibl\u00ED\u017E\u00ED mapu na extent jedn\u00E9 vrstvy (bbox z /wms/ odpov\u011Bdi, WGS84 \u2192 3857).\n * Kresba a lok\u00E1ln\u00ED vrstva bbox nemaj\u00ED \u2014 extent se spo\u010D\u00EDt\u00E1 z geometri\u00ED\n * klientsk\u00E9ho zdroje. Extern\u00ED WMS/WMTS pou\u017E\u00EDvaj\u00ED bbox z capabilities. */\nexport function zoomToLayer(ctx, uid) {\n    const entry = findEntryByUid(ctx.state, uid);\n    if (!entry) return;\n    if (entry.isGroup) {\n        const extents = entry.children.map(entryExtent).filter(Boolean);\n        if (extents.length === 0) return;\n        zoomToExtent(ctx.map, extents.reduce((acc, e) => [\n            Math.min(acc[0], e[0]), Math.min(acc[1], e[1]), Math.max(acc[2], e[2]), Math.max(acc[3], e[3]),\n        ]));\n        return;\n    }\n    const extent = entryExtent(entry);\n    if (extent) zoomToExtent(ctx.map, extent);\n}\n\n/** Rozsah vrstvy v sou\u0159adnic\u00EDch mapy (EPSG:3857), nebo null, kdy\u017E ho nezn\u00E1me. */\nfunction entryExtent(entry) {\n    if (entry.dataType === 'drawing' || entry.dataType === 'local') {\n        const extent = entry.olSource?.getExtent();\n        return extent && extent.every(Number.isFinite) ? extent : null;\n    }\n    if (!entry.bbox) return null;\n    const [minx, miny, maxx, maxy] = entry.bbox;\n    return [...fromLonLat([minx, miny]), ...fromLonLat([maxx, maxy])];\n}\n\n/** P\u0159ibl\u00ED\u017E\u00ED na sjednocen\u00FD extent v\u0161ech vrstev (\"Zoom to all\"). */\nexport function zoomToAllLayers(ctx) {\n    const entries = flatLayers(ctx.state);\n    const extents = entries\n        .map((l) => l.bbox)\n        .filter(Boolean)\n        .map(([minx, miny, maxx, maxy]) => [...fromLonLat([minx, miny]), ...fromLonLat([maxx, maxy])]);\n    // Kresba a lok\u00E1ln\u00ED vrstvy: extent z geometri\u00ED (u\u017E v EPSG:3857).\n    entries\n        .filter((l) => (l.dataType === 'drawing' || l.dataType === 'local') && l.olSource)\n        .forEach((l) => {\n            const extent = l.olSource.getExtent();\n            if (extent && extent.every(Number.isFinite)) extents.push(extent);\n        });\n    if (extents.length === 0) return;\n    const merged = extents.reduce((acc, e) => [\n        Math.min(acc[0], e[0]),\n        Math.min(acc[1], e[1]),\n        Math.max(acc[2], e[2]),\n        Math.max(acc[3], e[3]),\n    ]);\n    zoomToExtent(ctx.map, merged);\n}\n\n/* ---------------------------------------------------------------------------\n * Vykreslen\u00ED stromu vrstev v lev\u00E9m panelu\n * ------------------------------------------------------------------------- */\n\n/** Otev\u0159en\u00E9 kebab menu (\u22EE) \u2014 nejv\u00FD\u0161e jedno, zav\u00EDr\u00E1 se klikem mimo/akc\u00ED. */\nlet openMenuEl = null;\n\nfunction closeKebabMenu() {\n    if (openMenuEl) {\n        openMenuEl.remove();\n        openMenuEl = null;\n    }\n}\n\ndocument.addEventListener('click', (event) => {\n    if (openMenuEl && !openMenuEl.contains(event.target)) closeKebabMenu();\n});\n\n/** Otev\u0159e kebab menu u tla\u010D\u00EDtka. `items` = [{label, danger?, onClick}]. */\nfunction openKebabMenu(button, items) {\n    closeKebabMenu();\n    const menu = document.createElement('div');\n    menu.className = 'fixed z-50 w-48 rounded-lg border border-slate-200 bg-white py-1 shadow-lg';\n    items.forEach((item) => {\n        const btn = document.createElement('button');\n        btn.type = 'button';\n        btn.className = item.danger\n            ? 'block w-full px-3 py-1.5 text-left text-sm text-red-600 hover:bg-red-50'\n            : 'block w-full px-3 py-1.5 text-left text-sm text-slate-700 hover:bg-slate-100';\n        btn.textContent = item.label;\n        btn.addEventListener('click', (event) => {\n            event.stopPropagation();\n            closeKebabMenu();\n            item.onClick();\n        });\n        menu.appendChild(btn);\n    });\n    document.body.appendChild(menu);\n    // Pozice: pod tla\u010D\u00EDtkem, zarovnan\u00E9 doprava; nesm\u00ED p\u0159et\u00E9ct spodn\u00ED okraj okna.\n    const rect = button.getBoundingClientRect();\n    const menuRect = menu.getBoundingClientRect();\n    menu.style.left = `${Math.max(8, rect.right - menuRect.width)}px`;\n    menu.style.top = `${Math.min(rect.bottom + 4, window.innerHeight - menuRect.height - 8)}px`;\n    openMenuEl = menu;\n}\n\nfunction typeIcon(dataType) {\n    if (dataType === 'hybrid') {\n        return `<svg class=\"h-4 w-4 text-violet-600\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\">${HYBRID_ICON_PATHS}</svg>`;\n    }\n    if (dataType === 'raster') {\n        return '<svg class=\"h-4 w-4 text-accent-600\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\"><rect x=\"3\" y=\"3\" width=\"18\" height=\"18\" rx=\"2\"/><path d=\"m3 15 4-4 4 4 5-5 5 5\"/></svg>';\n    }\n    if (dataType === 'drawing') {\n        return '<svg class=\"h-4 w-4 text-rose-600\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\"><path d=\"M17 3a2.8 2.8 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z\"/></svg>';\n    }\n    // Extern\u00ED slu\u017Eby (WMS/XYZ/WMTS) \u2014 ikona gl\u00F3bu; lok\u00E1ln\u00ED data \u2014 sponka.\n    if (dataType === 'wms' || dataType === 'xyz' || dataType === 'wmts') {\n        return '<svg class=\"h-4 w-4 text-sky-600\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\"><circle cx=\"12\" cy=\"12\" r=\"9\"/><path d=\"M3 12h18M12 3c2.5 2.5 3.8 5.6 3.8 9S14.5 18.5 12 21c-2.5-2.5-3.8-5.6-3.8-9S9.5 5.5 12 3z\"/></svg>';\n    }\n    if (dataType === 'local') {\n        return '<svg class=\"h-4 w-4 text-violet-600\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\"><path d=\"M9 4h9a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2H9a2 2 0 0 1-2-2v-2\"/><path d=\"M4 8h8M4 12h8m-8 4h5M8 4l-4 4\"/></svg>';\n    }\n    return '<svg class=\"h-4 w-4 text-brand-600\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\"><circle cx=\"12\" cy=\"12\" r=\"3\"/><path d=\"M12 2v4M12 18v4M2 12h4M18 12h4\"/></svg>';\n}\n\n/** Mal\u00FD badge typu extern\u00ED vrstvy vedle n\u00E1zvu (WMS/XYZ/WMTS/Local). */\nfunction externalBadge(entry) {\n    if (!entry.external) return '';\n    const labels = { wms: 'WMS', xyz: 'XYZ', wmts: 'WMTS', local: 'Local' };\n    return `<span class=\"flex-none rounded bg-slate-100 px-1.5 py-0.5 text-[10px] font-semibold uppercase tracking-wide text-slate-500\">${labels[entry.dataType] || 'EXT'}</span>`;\n}\n\n/** M\u00E1 vrstva atributovou tabulku? (rastr a extern\u00ED slu\u017Eby ne) */\nexport function hasAttributeTable(entry) {\n    if (!entry || entry.isGroup) return false;\n    if (entry.dataType === 'drawing' || entry.dataType === 'local') return true;\n    return entry.dataType === 'vector' && !entry.external;\n}\n\n/** Polo\u017Eky kebab menu (\u22EE) pro danou vrstvu \u2014 akce dle typu vrstvy. */\nfunction buildLayerMenuItems(ctx, entry) {\n    const canZoom = Boolean(entry.bbox)\n        || entry.dataType === 'drawing'\n        || entry.dataType === 'local';\n    const items = [];\n    if (canZoom) {\n        items.push({ label: 'Zoom to layer', onClick: () => { zoomToLayer(ctx, entry.uid); emit('ui:show-map'); } });\n    }\n    // Atributov\u00E1 tabulka: workspace vektory (WFS), kresba (editovateln\u00E1)\n    // a lok\u00E1ln\u00ED vektorov\u00E1 data (jen pro \u010Dten\u00ED).\n    if (hasAttributeTable(entry)) {\n        items.push({\n            label: 'Attribute table',\n            onClick: () => { emit('layers:open-attr-table', { uid: entry.uid }); emit('ui:show-map'); },\n        });\n    }\n    if (entry.dataType === 'drawing') {\n        items.push({ label: 'Export as GeoJSON', onClick: () => emit('drawing:export', { uid: entry.uid }) });\n        // Nab\u00EDdka je vid\u011Bt v\u017Edy \u2014 nep\u0159ihl\u00E1\u0161en\u00E9mu \u0159ekne, \u017Ee je pot\u0159eba se p\u0159ihl\u00E1sit.\n        items.push({ label: 'Save to workspace', onClick: () => emit('drawing:save-workspace', { uid: entry.uid }) });\n    }\n    // Styl \u017Eije v map\u011B; do dat se zap\u00ED\u0161e jen na v\u00FDslovn\u00E9 p\u0159\u00E1n\u00ED (style-export.js)\n    // \u2014 jako kopie vrstvy ulo\u017Een\u00E1 do workspace, ve form\u00E1tu p\u016Fvodn\u00EDch dat.\n    if (ctx.bootstrap.isAuthenticated && !ctx.readOnly && entry.wms && entry.itemId\n        && entry.dataType === 'vector' && entry.style?.mode !== 'native') {\n        items.push({ label: 'Save style into the data\u2026', onClick: () => emit('layers:save-style-to-data', { uid: entry.uid }) });\n    }\n    items.push({ label: 'Rename', onClick: () => renameFromMenu(ctx, entry) });\n    items.push({ label: 'Duplicate', onClick: () => { duplicateLayer(ctx, entry.uid); } });\n    // Po\u0159ad\u00ED vrstev bez ta\u017Een\u00ED my\u0161\u00ED \u2014 na dotykov\u00E9 obrazovce (a z kl\u00E1vesnice)\n    // jedin\u00E1 cesta, jinde zkratka. Naho\u0159e ve stromu = naho\u0159e v map\u011B.\n    const container = findEntryContainer(ctx.state, entry.uid);\n    const parent = container?.group || null;\n    if (container && container.index > 0) {\n        items.push({ label: 'Move up', onClick: () => reorderEntry(ctx, entry.uid, -1) });\n    }\n    if (container && container.index < container.list.length - 1) {\n        items.push({ label: 'Move down', onClick: () => reorderEntry(ctx, entry.uid, 1) });\n    }\n    // \"Move to group\" \u2014 jen kdy\u017E existuj\u00ED skupiny (a vrstva do nich m\u016F\u017Ee).\n    const groups = ctx.state.layers.filter((e) => e.isGroup);\n    groups.filter((g) => g !== parent).forEach((g) => {\n        items.push({ label: `Move to \u201C${g.title}\u201D`, onClick: () => moveEntry(ctx, entry.uid, g.uid, 0) });\n    });\n    if (parent) {\n        items.push({ label: 'Remove from group', onClick: () => moveEntry(ctx, entry.uid, null, 0) });\n    }\n    items.push({ label: 'Properties', onClick: () => emit('layers:open-properties', { uid: entry.uid }) });\n    items.push({ label: 'Remove', danger: true, onClick: () => removeLayer(ctx, entry.uid) });\n    return items;\n}\n\n/** Spust\u00ED p\u0159ejmenov\u00E1n\u00ED v \u0159\u00E1dku vrstvy/skupiny \u2014 tot\u00E9\u017E co dvojklik na n\u00E1zev\n * (ten na dotykov\u00E9 obrazovce spolehliv\u011B nefunguje). */\nfunction renameFromMenu(ctx, entry) {\n    const row = Array.from(ctx.elements.layerTree?.querySelectorAll('[data-uid]') || [])\n        .find((el) => el.dataset.uid === entry.uid);\n    const titleEl = row?.querySelector('[data-role=\"title\"]');\n    if (titleEl) startInlineRename(ctx, entry, titleEl);\n}\n\n/** Polo\u017Eky menu (\u22EE) skupiny vrstev. */\nfunction buildGroupMenuItems(ctx, group) {\n    const items = [];\n    if (group.children.some((child) => entryExtent(child))) {\n        items.push({ label: 'Zoom to group', onClick: () => { zoomToLayer(ctx, group.uid); emit('ui:show-map'); } });\n    }\n    items.push({ label: 'Rename', onClick: () => renameFromMenu(ctx, group) });\n    const index = ctx.state.layers.indexOf(group);\n    if (index > 0) items.push({ label: 'Move up', onClick: () => reorderEntry(ctx, group.uid, -1) });\n    if (index < ctx.state.layers.length - 1) {\n        items.push({ label: 'Move down', onClick: () => reorderEntry(ctx, group.uid, 1) });\n    }\n    if (group.dataset) {\n        // Skupina jednoho souboru (v\u00EDce vrstev) je jedna polo\u017Eka dat \u2014 odebere\n        // se i s vrstvami.\n        items.push({\n            label: 'Remove from map',\n            danger: true,\n            onClick: () => {\n                const count = group.children.length;\n                // eslint-disable-next-line no-alert -- jednoduch\u00E9 potvrzen\u00ED bez extra UI komponenty\n                if (count === 0 || window.confirm(`Remove \"${group.title}\" and its ${count} layer${count === 1 ? '' : 's'} from the map?`)) {\n                    removeGroupWithLayers(ctx, group.uid);\n                }\n            },\n        });\n    } else {\n        items.push({\n            label: 'Ungroup (keep layers)',\n            onClick: () => {\n                if (group.children.length === 0) { removeGroup(ctx, group.uid); return; }\n                // eslint-disable-next-line no-alert -- jednoduch\u00E9 potvrzen\u00ED bez extra UI komponenty\n                if (window.confirm(`Delete group \"${group.title}\"? Its layers will be kept and moved out of the group.`)) {\n                    removeGroup(ctx, group.uid);\n                }\n            },\n        });\n        if (group.children.length > 0) {\n            items.push({\n                label: 'Remove with layers',\n                danger: true,\n                onClick: () => {\n                    const count = group.children.length;\n                    // eslint-disable-next-line no-alert -- jednoduch\u00E9 potvrzen\u00ED bez extra UI komponenty\n                    if (window.confirm(`Remove \"${group.title}\" and its ${count} layer${count === 1 ? '' : 's'} from the map?`)) {\n                        removeGroupWithLayers(ctx, group.uid);\n                    }\n                },\n            });\n        }\n    }\n    return items;\n}\n\nconst ICON_CARET = '<svg class=\"h-4 w-4\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" aria-hidden=\"true\"><path d=\"m6 9 6 6 6-6\"/></svg>';\nconst ICON_BRUSH = '<svg class=\"h-4 w-4\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" aria-hidden=\"true\"><path d=\"M18.37 2.63 14 7l-1.59-1.59a2 2 0 0 0-2.82 0L8 7l9 9 1.59-1.59a2 2 0 0 0 0-2.82L17 10l4.37-4.37a2.12 2.12 0 1 0-3-3Z\"/><path d=\"M9 8c-2 3-4 3.5-7 4l8 10c2-1 6-5 6-7\"/><path d=\"M14.5 17.5 4.5 15\"/></svg>';\nconst ICON_KEBAB = '<svg class=\"h-4 w-4\" viewBox=\"0 0 24 24\" fill=\"currentColor\" aria-hidden=\"true\"><circle cx=\"12\" cy=\"5\" r=\"1.6\"/><circle cx=\"12\" cy=\"12\" r=\"1.6\"/><circle cx=\"12\" cy=\"19\" r=\"1.6\"/></svg>';\nconst ICON_GRIP = '<svg class=\"h-4 w-4\" viewBox=\"0 0 24 24\" fill=\"currentColor\" aria-hidden=\"true\"><circle cx=\"9\" cy=\"6\" r=\"1.4\"/><circle cx=\"9\" cy=\"12\" r=\"1.4\"/><circle cx=\"9\" cy=\"18\" r=\"1.4\"/><circle cx=\"15\" cy=\"6\" r=\"1.4\"/><circle cx=\"15\" cy=\"12\" r=\"1.4\"/><circle cx=\"15\" cy=\"18\" r=\"1.4\"/></svg>';\nconst ICON_FILTER = '<svg class=\"h-3 w-3\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" aria-hidden=\"true\"><path d=\"M22 3H2l8 9.5V19l4 2v-8.5L22 3z\"/></svg>';\n\nfunction htmlEscape(value) {\n    return String(value ?? '')\n        .replace(/&/g, '&amp;')\n        .replace(/</g, '&lt;')\n        .replace(/>/g, '&gt;')\n        .replace(/\"/g, '&quot;');\n}\n\n/** \u0160t\u00EDtek pr\u016Fhlednosti u n\u00E1zvu (jen kdy\u017E vrstva nen\u00ED pln\u011B kryt\u00E1). */\nfunction opacityBadgeHtml(entry) {\n    const percent = Math.round((entry.opacity ?? 1) * 100);\n    if (percent >= 100) return '';\n    return `<button type=\"button\" data-role=\"opacity-badge\" title=\"Opacity ${percent}% \u2014 click to change\"\n        class=\"flex-none rounded bg-slate-100 px-1 py-0.5 text-[10px] font-semibold tabular-nums text-slate-500 hover:bg-slate-200\">${percent}%</button>`;\n}\n\n/**\n * Vykresl\u00ED symbol vrstvy a t\u011Blo legendy do \u0159\u00E1dku. Symbol jednoduch\u00E9 vrstvy\n * stoj\u00ED m\u00EDsto ikony typu; klasifikovan\u00E1 vrstva (kategorie, intervaly, paleta,\n * styl z dat s v\u00EDce symboly) m\u00E1 m\u00EDsto n\u011Bj \u0161ipku, kterou se seznam t\u0159\u00EDd sbal\u00ED.\n */\nfunction renderLegend(ctx, row, entry) {\n    const slot = row.querySelector('[data-role=\"swatch\"]');\n    const body = row.querySelector('[data-role=\"legend\"]');\n    if (!slot || !body) return;\n    const model = legendModel(entry);\n    const hasBody = legendHasBody(model);\n    const collapsed = Boolean(entry.legendCollapsed);\n\n    if (hasBody) {\n        const label = collapsed ? 'Show legend' : 'Hide legend';\n        // \u0160k\u00E1la rastru m\u00E1 i mal\u00FD symbol; seznam t\u0159\u00EDd jen \u0161ipku.\n        const inner = model.swatch && !model.items?.length\n            ? model.swatch\n            : `<span class=\"map-layer-caret ${collapsed ? 'is-collapsed' : ''}\">${ICON_CARET}</span>`;\n        slot.innerHTML = `<button type=\"button\" data-role=\"legend-toggle\" title=\"${label}\" aria-label=\"${label}\" aria-expanded=\"${!collapsed}\"\n            class=\"map-layer-swatch is-toggle\">${inner}</button>`;\n        slot.querySelector('[data-role=\"legend-toggle\"]').addEventListener('click', () => {\n            entry.legendCollapsed = !entry.legendCollapsed;\n            if (!ctx.readOnly) ctx.state.dirty = true;\n            renderLegend(ctx, row, entry);\n        });\n    } else {\n        slot.innerHTML = `<span class=\"map-layer-swatch\">${model?.swatch || typeIcon(entry.dataType)}</span>`;\n    }\n\n    if (!hasBody || collapsed) {\n        body.classList.add('hidden');\n        body.innerHTML = '';\n        return;\n    }\n    body.classList.remove('hidden');\n    body.innerHTML = legendBodyHtml(model, { expanded: Boolean(entry.legendExpanded) });\n    body.querySelector('[data-role=\"legend-more\"]')?.addEventListener('click', () => {\n        entry.legendExpanded = true;\n        renderLegend(ctx, row, entry);\n    });\n    body.querySelector('[data-role=\"legend-less\"]')?.addEventListener('click', () => {\n        entry.legendExpanded = false;\n        renderLegend(ctx, row, entry);\n    });\n}\n\n/** P\u0159ekresl\u00ED symbol, legendu a \u0161t\u00EDtek pr\u016Fhlednosti jedn\u00E9 vrstvy (po zm\u011Bn\u011B\n * stylu) \u2014 bez p\u0159ekreslen\u00ED cel\u00E9ho stromu, aby se nezav\u0159el panel stylu. */\nexport function refreshLayerRow(ctx, entry) {\n    const row = ctx.elements.layerTree?.querySelector(`[data-uid=\"${entry.uid}\"]`);\n    if (!row) return;\n    renderLegend(ctx, row, entry);\n    const badgeSlot = row.querySelector('[data-role=\"opacity-slot\"]');\n    if (badgeSlot) {\n        badgeSlot.innerHTML = opacityBadgeHtml(entry);\n        wireOpacityBadge(ctx, row, entry);\n    }\n}\n\nfunction wireOpacityBadge(ctx, row, entry) {\n    row.querySelector('[data-role=\"opacity-badge\"]')?.addEventListener('click', () => {\n        emit('layers:toggle-style-panel', { uid: entry.uid, row, open: true });\n    });\n}\n\nfunction layerRow(ctx, entry, parentGroup) {\n    const row = document.createElement('div');\n    row.className = 'map-layer group rounded-lg border border-slate-200 bg-white px-1.5 py-1.5 shadow-sm';\n    row.draggable = false;\n    row.dataset.uid = entry.uid;\n\n    // Ze\u0161ednut\u00ED n\u00E1zvu, kdy\u017E je aktu\u00E1ln\u00ED zoom mimo min/max rozsah vrstvy.\n    const dimmed = !isEntryInZoomRange(ctx, entry);\n    const title = htmlEscape(entry.title);\n\n    row.innerHTML = `\n        <div class=\"flex items-center gap-x-1.5\">\n            <span class=\"flex-none cursor-move text-slate-300 hover:text-slate-400\" data-role=\"drag-handle\" title=\"Drag to reorder\">${ICON_GRIP}</span>\n            <input type=\"checkbox\" data-role=\"visible\" ${entry.visible ? 'checked' : ''} aria-label=\"Show layer ${title}\"\n                   class=\"h-4 w-4 flex-none rounded border-slate-300 text-brand-600 focus:ring-brand-500\">\n            <span data-role=\"swatch\" class=\"flex flex-none items-center\"></span>\n            <span data-role=\"title\" class=\"min-w-0 flex-1 truncate text-sm font-medium ${dimmed ? 'text-slate-400' : 'text-slate-800'}\" title=\"${title}\">${title}</span>\n            ${externalBadge(entry)}\n            ${isFilterActive(entry.filter) ? `<span class=\"flex-none text-brand-600\" title=\"Attribute filter is active\">${ICON_FILTER}</span>` : ''}\n            <span data-role=\"opacity-slot\" class=\"flex flex-none items-center\">${opacityBadgeHtml(entry)}</span>\n            <span data-role=\"status\" class=\"flex flex-none items-center\">${layerStatusHtml(entry)}</span>\n            <button type=\"button\" data-role=\"style\" title=\"Style and opacity\" aria-label=\"Style and opacity of ${title}\" class=\"flex-none rounded p-1 text-slate-400 hover:bg-slate-100 hover:text-slate-700\">${ICON_BRUSH}</button>\n            <button type=\"button\" data-role=\"menu\" title=\"Layer actions\" aria-label=\"Actions for ${title}\" class=\"flex-none rounded p-1 text-slate-400 hover:bg-slate-100 hover:text-slate-700\">${ICON_KEBAB}</button>\n        </div>\n        ${isFilterActive(entry.filter) ? `\n        <div class=\"mt-1 flex items-center gap-x-1.5 pl-[3.25rem]\">\n            <span class=\"inline-flex items-center gap-x-1 rounded-full bg-brand-50 px-2 py-0.5 text-[11px] font-medium text-brand-700\">${ICON_FILTER} Filter active</span>\n            <button type=\"button\" data-role=\"clear-filter\" class=\"text-[11px] text-slate-400 underline-offset-2 hover:text-red-600 hover:underline\">Clear filter</button>\n        </div>` : ''}\n        <div data-role=\"legend\" class=\"map-layer-legend hidden\"></div>\n        <div data-role=\"style-panel\" class=\"mt-2 hidden border-t border-slate-100 pt-2\"></div>\n    `;\n\n    row.querySelector('[data-role=\"visible\"]').addEventListener('change', (e) => {\n        setLayerVisibility(ctx, entry.uid, e.target.checked);\n    });\n    wireLayerStatus(row, entry);\n    wireOpacityBadge(ctx, row, entry);\n    row.querySelector('[data-role=\"style\"]').addEventListener('click', () => {\n        emit('layers:toggle-style-panel', { uid: entry.uid, row });\n    });\n    row.querySelector('[data-role=\"menu\"]').addEventListener('click', (e) => {\n        e.stopPropagation();\n        openKebabMenu(e.currentTarget, buildLayerMenuItems(ctx, entry));\n    });\n    row.querySelector('[data-role=\"clear-filter\"]')?.addEventListener('click', () => {\n        clearLayerFilter(ctx, entry.uid);\n    });\n\n    const titleEl = row.querySelector('[data-role=\"title\"]');\n    titleEl.addEventListener('dblclick', () => startInlineRename(ctx, entry, titleEl));\n\n    renderLegend(ctx, row, entry);\n    wireRowDrag(ctx, row, entry, parentGroup);\n    return row;\n}\n\n/** Stav vykreslov\u00E1n\u00ED vrstvy v \u0159\u00E1dku stromu: kole\u010Dko p\u0159i \u010Dek\u00E1n\u00ED na Mapserver,\n * v\u00FDstra\u017En\u00E1 ikona (klik = zkusit znovu), kdy\u017E se vykreslen\u00ED nepovedlo. */\nfunction layerStatusHtml(entry) {\n    if (entry.pending > 0) {\n        return '<span class=\"map-spinner\" role=\"img\" aria-label=\"Rendering\u2026\" title=\"Rendering\u2026\"></span>';\n    }\n    if (entry.slowHint && !entry.loadError && entry.performance?.tooSlow) {\n        return `<button type=\"button\" data-role=\"slow\" title=\"This layer is too large to draw in its format \u2014 click to convert it.\" aria-label=\"This layer is too large to draw \u2014 how to show it\"\n            class=\"rounded p-0.5 text-amber-500 hover:bg-amber-50 hover:text-amber-600\">\n            <svg class=\"h-4 w-4\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" aria-hidden=\"true\"><path d=\"M13 2 4 14h7l-1 8 9-12h-7l1-8z\"/></svg>\n        </button>`;\n    }\n    if (entry.slowHint && !entry.loadError) {\n        return `<button type=\"button\" data-role=\"slow\" title=\"This layer draws slowly \u2014 click to see how to speed it up.\" aria-label=\"This layer draws slowly \u2014 how to speed it up\"\n            class=\"rounded p-0.5 text-amber-500 hover:bg-amber-50 hover:text-amber-600\">\n            <svg class=\"h-4 w-4\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" aria-hidden=\"true\"><path d=\"M13 2 4 14h7l-1 8 9-12h-7l1-8z\"/></svg>\n        </button>`;\n    }\n    if (entry.loadError) {\n        return `<button type=\"button\" data-role=\"retry\" title=\"This layer couldn\u2019t be rendered. Click to try again.\" aria-label=\"Rendering failed \u2014 try again\"\n            class=\"rounded p-0.5 text-amber-500 hover:bg-amber-50 hover:text-amber-600\">\n            <svg class=\"h-4 w-4\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" aria-hidden=\"true\"><path d=\"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3\"/><path d=\"M12 9v4\"/><path d=\"M12 17h.01\"/></svg>\n        </button>`;\n    }\n    return '';\n}\n\nfunction wireLayerStatus(row, entry) {\n    row.querySelector('[data-role=\"status\"] [data-role=\"retry\"]')?.addEventListener('click', () => {\n        entry.loadError = false;\n        entry.olSource?.refresh();\n    });\n    row.querySelector('[data-role=\"status\"] [data-role=\"slow\"]')?.addEventListener('click', () => {\n        emit('advisor:open', { uid: entry.uid });\n    });\n}\n\n/** Aktualizuje stav vykreslov\u00E1n\u00ED v \u0159\u00E1dku vrstvy (bez p\u0159ekreslen\u00ED stromu) \u2014\n * vol\u00E1no p\u0159i ud\u00E1losti `layer:loading` (main.js). */\nexport function updateLayerStatus(ctx, entry) {\n    const container = ctx.elements.layerTree;\n    if (!container || !entry) return;\n    const row = container.querySelector(`[data-uid=\"${entry.uid}\"]`);\n    const slot = row?.querySelector('[data-role=\"status\"]');\n    if (!slot) return;\n    // Stejn\u00FD stav = \u017E\u00E1dn\u00FD z\u00E1sah do DOM (animace kole\u010Dka by se restartovala).\n    const state = entry.pending > 0 ? 'loading' : (entry.loadError ? 'error' : (entry.slowHint ? 'slow' : ''));\n    if (slot.dataset.state === state) return;\n    slot.dataset.state = state;\n    slot.innerHTML = layerStatusHtml(entry);\n    wireLayerStatus(row, entry);\n}\n\n/** Je vrstva v rozsahu aktu\u00E1ln\u00EDho zoomu mapy (minZoom/maxZoom)? */\nfunction isEntryInZoomRange(ctx, entry) {\n    const zoom = ctx.map?.getView()?.getZoom();\n    if (!Number.isFinite(zoom)) return true;\n    if (Number.isFinite(entry.minZoom) && zoom < entry.minZoom) return false;\n    if (Number.isFinite(entry.maxZoom) && zoom > entry.maxZoom) return false;\n    return true;\n}\n\n/** Aktualizuje ze\u0161ednut\u00ED n\u00E1zv\u016F vrstev mimo rozsah zoomu (bez p\u0159ekreslen\u00ED\n * cel\u00E9ho stromu) \u2014 vol\u00E1no p\u0159i zm\u011Bn\u011B rozli\u0161en\u00ED pohledu (main.js). */\nexport function updateScaleDimming(ctx) {\n    const container = ctx.elements.layerTree;\n    if (!container) return;\n    container.querySelectorAll('[data-uid]').forEach((row) => {\n        const entry = findEntryByUid(ctx.state, row.dataset.uid);\n        if (!entry || entry.isGroup) return;\n        const titleEl = row.querySelector('[data-role=\"title\"]');\n        if (!titleEl) return;\n        const dimmed = !isEntryInZoomRange(ctx, entry);\n        titleEl.classList.toggle('text-slate-400', dimmed);\n        titleEl.classList.toggle('text-slate-800', !dimmed);\n    });\n}\n\n/* ---------------------------------------------------------------------------\n * Drag & drop \u2014 \u0159azen\u00ED + p\u0159esun do/ze skupiny\n *\n * Vrstvu lze t\u00E1hnout za \u00FAchyt: pu\u0161t\u011Bn\u00ED nad jin\u00FDm \u0159\u00E1dkem ji za\u0159ad\u00ED na jeho\n * pozici (v r\u00E1mci kontejneru c\u00EDlov\u00E9ho \u0159\u00E1dku \u2014 top-level nebo skupina),\n * pu\u0161t\u011Bn\u00ED na hlavi\u010Dku skupiny ji vlo\u017E\u00ED do skupiny. Skupina se p\u0159etahuje jako\n * celek, jen v top-level. Jako dopln\u011Bk (robustn\u00ED fallback pro p\u0159esuny mezi\n * skupinami) slou\u017E\u00ED polo\u017Eky \"Move to group\" v kebab menu.\n * ------------------------------------------------------------------------- */\n\nfunction wireRowDrag(ctx, row, entry, parentGroup) {\n    const handle = row.querySelector('[data-role=\"drag-handle\"]');\n    handle.addEventListener('mousedown', () => { row.draggable = true; });\n    handle.addEventListener('mouseup', () => { row.draggable = false; });\n\n    row.addEventListener('dragstart', (e) => {\n        e.stopPropagation();\n        e.dataTransfer.setData('text/plain', entry.uid);\n        row.classList.add('opacity-50');\n    });\n    row.addEventListener('dragend', () => {\n        row.classList.remove('opacity-50');\n        row.draggable = false;\n    });\n    row.addEventListener('dragover', (e) => {\n        e.preventDefault();\n        e.stopPropagation();\n    });\n    row.addEventListener('drop', (e) => {\n        e.preventDefault();\n        e.stopPropagation();\n        const draggedUid = e.dataTransfer.getData('text/plain');\n        if (!draggedUid || draggedUid === entry.uid) return;\n        const dragged = findEntryByUid(ctx.state, draggedUid);\n        if (!dragged) return;\n        // Skupinu lze pustit jen v top-level (\u017E\u00E1dn\u00E9 skupiny ve skupin\u00E1ch).\n        if (dragged.isGroup && parentGroup) return;\n        const target = findEntryContainer(ctx.state, entry.uid);\n        const source = findEntryContainer(ctx.state, draggedUid);\n        if (!target || !source) return;\n        // Vkl\u00E1d\u00E1 se na pozici c\u00EDlov\u00E9ho \u0159\u00E1dku; p\u0159i p\u0159esunu dol\u016F v t\u00E9m\u017Ee\n        // kontejneru se index po odebr\u00E1n\u00ED zdroje posune o 1 \u2014 kompenzace.\n        let toIndex = target.index;\n        if (source.list === target.list && source.index < target.index) {\n            toIndex = target.index;\n        }\n        moveEntry(ctx, draggedUid, parentGroup?.uid || null, toIndex);\n        ctx.state.dirty = true;\n    });\n}\n\nfunction startInlineRename(ctx, entry, titleEl) {\n    const input = document.createElement('input');\n    input.type = 'text';\n    input.value = entry.title;\n    input.className = 'flex-1 rounded border border-brand-300 px-1 text-sm focus:outline-none focus:ring-1 focus:ring-brand-500';\n    titleEl.replaceWith(input);\n    input.focus();\n    input.select();\n    const commit = () => {\n        renameLayer(ctx, entry.uid, input.value.trim() || entry.title);\n        renderLayerTree(ctx);\n    };\n    input.addEventListener('blur', commit);\n    input.addEventListener('keydown', (e) => {\n        if (e.key === 'Enter') input.blur();\n        if (e.key === 'Escape') { input.value = entry.title; input.blur(); }\n    });\n}\n\n/** Ikona skupiny: soubor s v\u00EDce vrstvami (list pap\u00EDru s vrstvami), soubor\n * s vektory i rastrem, nebo oby\u010Dejn\u00E1 u\u017Eivatelsk\u00E1 skupina (slo\u017Eka). */\nfunction groupIcon(group) {\n    if (group.hybrid) {\n        return `<span class=\"flex-none\" title=\"Vector and raster layers of one file\">${typeIcon('hybrid')}</span>`;\n    }\n    if (group.dataset) {\n        return '<span class=\"flex-none\" title=\"Layers of one file\"><svg class=\"h-4 w-4 text-brand-600\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" aria-hidden=\"true\"><path d=\"m12 3 9 5-9 5-9-5 9-5Z\"/><path d=\"m3 13 9 5 9-5\"/></svg></span>';\n    }\n    return '<svg class=\"h-4 w-4 flex-none text-amber-500\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" aria-hidden=\"true\"><path d=\"M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z\"/></svg>';\n}\n\n/** Vykresl\u00ED \u0159\u00E1dek skupiny vrstev: \u0161ipka sbalit/rozbalit, checkbox viditelnosti\n * (AND s viditelnost\u00ED d\u011Bt\u00ED), inline rename, smaz\u00E1n\u00ED (d\u011Bti se p\u0159esunou v\u00FD\u0161)\n * a kontejner d\u011Bt\u00ED. Pu\u0161t\u011Bn\u00ED ta\u017Een\u00E9 vrstvy na hlavi\u010Dku ji vlo\u017E\u00ED do skupiny. */\nfunction groupRow(ctx, group) {\n    const wrapper = document.createElement('div');\n    wrapper.className = 'rounded-lg border border-slate-300 bg-slate-100/70 p-1.5';\n    wrapper.dataset.uid = group.uid;\n\n    const header = document.createElement('div');\n    header.className = 'flex items-center gap-x-2 rounded-md px-0.5 py-1';\n    header.innerHTML = `\n        <span class=\"cursor-move text-slate-300\" data-role=\"drag-handle\" title=\"Move group\">\n            <svg class=\"h-4 w-4\" viewBox=\"0 0 24 24\" fill=\"currentColor\"><circle cx=\"8\" cy=\"6\" r=\"1.4\"/><circle cx=\"8\" cy=\"12\" r=\"1.4\"/><circle cx=\"8\" cy=\"18\" r=\"1.4\"/><circle cx=\"16\" cy=\"6\" r=\"1.4\"/><circle cx=\"16\" cy=\"12\" r=\"1.4\"/><circle cx=\"16\" cy=\"18\" r=\"1.4\"/></svg>\n        </span>\n        <button type=\"button\" data-role=\"collapse\" title=\"${group.collapsed ? 'Expand group' : 'Collapse group'}\"\n                class=\"rounded p-0.5 text-slate-500 hover:bg-slate-200\">\n            <svg class=\"h-4 w-4 transition-transform ${group.collapsed ? '-rotate-90' : ''}\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\"><path d=\"m6 9 6 6 6-6\"/></svg>\n        </button>\n        <input type=\"checkbox\" data-role=\"visible\" ${group.visible ? 'checked' : ''}\n               class=\"h-4 w-4 rounded border-slate-300 text-brand-600 focus:ring-brand-500\">\n        ${groupIcon(group)}\n        <span data-role=\"title\" class=\"min-w-0 flex-1 truncate text-sm font-semibold text-slate-700\" title=\"${htmlEscape(group.title)}\">${htmlEscape(group.title)}</span>\n        <span class=\"flex-none text-[11px] tabular-nums text-slate-400\" title=\"${group.children.length} layer${group.children.length === 1 ? '' : 's'}\">${group.children.length}</span>\n        <button type=\"button\" data-role=\"menu\" title=\"Group actions\" aria-label=\"Actions for ${htmlEscape(group.title)}\" class=\"flex-none rounded p-1 text-slate-400 hover:bg-slate-200 hover:text-slate-700\">${ICON_KEBAB}</button>\n    `;\n    wrapper.appendChild(header);\n\n    header.querySelector('[data-role=\"collapse\"]').addEventListener('click', () => {\n        group.collapsed = !group.collapsed;\n        if (!ctx.readOnly) ctx.state.dirty = true;\n        renderLayerTree(ctx);\n    });\n    header.querySelector('[data-role=\"visible\"]').addEventListener('change', (e) => {\n        setLayerVisibility(ctx, group.uid, e.target.checked);\n        if (!ctx.readOnly) ctx.state.dirty = true;\n    });\n    header.querySelector('[data-role=\"menu\"]').addEventListener('click', (e) => {\n        e.stopPropagation();\n        openKebabMenu(e.currentTarget, buildGroupMenuItems(ctx, group));\n    });\n    const titleEl = header.querySelector('[data-role=\"title\"]');\n    titleEl.addEventListener('dblclick', () => startInlineRename(ctx, group, titleEl));\n\n    // Drag&drop skupiny (jen top-level) + drop vrstvy na hlavi\u010Dku = vlo\u017Een\u00ED do skupiny.\n    wireRowDrag(ctx, wrapper, group, null);\n    header.addEventListener('drop', (e) => {\n        const draggedUid = e.dataTransfer.getData('text/plain');\n        const dragged = draggedUid ? findEntryByUid(ctx.state, draggedUid) : null;\n        if (dragged && !dragged.isGroup && dragged.uid !== group.uid) {\n            e.preventDefault();\n            e.stopPropagation();\n            moveEntry(ctx, dragged.uid, group.uid, 0);\n            ctx.state.dirty = true;\n        }\n    });\n\n    if (!group.collapsed) {\n        const childrenBox = document.createElement('div');\n        childrenBox.className = 'mt-1.5 space-y-1.5 border-l-2 border-slate-200 pl-2';\n        if (group.children.length === 0) {\n            childrenBox.innerHTML = '<p class=\"px-1 py-2 text-center text-xs text-slate-400\">Empty group \u2014 drag layers here or use \"Move to group\".</p>';\n        }\n        group.children.forEach((child) => {\n            childrenBox.appendChild(layerRow(ctx, child, group));\n        });\n        wrapper.appendChild(childrenBox);\n    }\n    return wrapper;\n}\n\n/** P\u0159ep\u00ED\u0161e text p\u0159ipravovan\u00E9ho \u0159\u00E1dku (zn\u00E1me u\u017E n\u00E1zev a velikost dat, nebo\n * se posunulo nahr\u00E1v\u00E1n\u00ED souboru z mapy \u2014 upload.js). */\nexport function refreshPreparingRow(ctx, item) {\n    const row = ctx.elements.layerTree?.querySelector(`[data-preparing=\"${item.key}\"]`);\n    if (row) row.replaceWith(preparingRow(item));\n}\n\n/** \u0158\u00E1dek vrstvy, kter\u00E1 se teprve p\u0159ipravuje. `status` nahrad\u00ED v\u00FDchoz\u00ED\n * \u201EReading the data\u2026\u201C (pr\u016Fb\u011Bh nahr\u00E1v\u00E1n\u00ED souboru z mapy). */\nfunction preparingRow(item) {\n    const row = document.createElement('div');\n    row.className = 'flex items-center gap-x-2.5 rounded-lg border border-dashed border-slate-300 bg-white/70 px-3 py-2 text-sm text-slate-500';\n    row.dataset.preparing = item.key;\n    const status = item.status || (item.note ? `Reading the data (${item.note})\u2026` : 'Reading the data\u2026');\n    row.innerHTML = `\n        <span class=\"map-spinner flex-none\" aria-hidden=\"true\"></span>\n        <span class=\"min-w-0 flex-1\">\n            <span class=\"block truncate font-medium text-slate-700\">${htmlEscape(item.title)}</span>\n            <span class=\"block truncate text-xs text-slate-400\">${htmlEscape(status)}</span>\n        </span>`;\n    return row;\n}\n\n/** Pr\u00E1zdn\u00E1 mapa: kde za\u010D\u00EDt. Tla\u010D\u00EDtko otev\u0159e \u201EAdd data\u201C (main.js poslouch\u00E1\n * `ui:add-data`); u p\u0159ihl\u00E1\u0161en\u00E9ho i n\u00E1pov\u011Bda, \u017Ee soubory jde pustit na mapu. */\nfunction emptyLayersHint(ctx) {\n    const box = document.createElement('div');\n    box.className = 'px-2 pb-2 pt-6 text-center';\n    if (ctx.bootstrap.sharedView) {\n        // Data ze sd\u00EDlen\u00E9ho odkazu \u2014 p\u0159id\u00E1vat tu nic nejde.\n        box.innerHTML = '<p class=\"text-sm text-slate-400\">No layers</p>';\n        return box;\n    }\n    const canUpload = ctx.bootstrap.isAuthenticated;\n    box.innerHTML = `\n        <p class=\"text-sm text-slate-500\">No layers yet</p>\n        <button type=\"button\" data-role=\"empty-add-data\" class=\"btn-accent mt-3 !px-3 !py-1.5\">\n            <svg class=\"h-4 w-4\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" aria-hidden=\"true\"><path d=\"M12 5v14M5 12h14\"/></svg>\n            Add data\n        </button>\n        ${canUpload ? '<p class=\"mt-2 text-xs text-slate-400\">or drop files on the map</p>' : ''}`;\n    box.querySelector('[data-role=\"empty-add-data\"]').addEventListener('click', () => emit('ui:add-data'));\n    return box;\n}\n\n/** Znovu vykresl\u00ED cel\u00FD strom vrstev v panelu podle `ctx.state.layers`\n * (top-level z\u00E1znamy \u2014 vrstvy i skupiny s d\u011Btmi). */\nexport function renderLayerTree(ctx) {\n    const container = ctx.elements.layerTree;\n    if (!container) return;\n    closeKebabMenu();\n    container.innerHTML = '';\n    const preparing = ctx.state.preparing || [];\n    if (ctx.state.layers.length === 0 && preparing.length === 0) {\n        container.appendChild(emptyLayersHint(ctx));\n        // Nov\u00E1 pr\u00E1zdn\u00E1 mapa: pod t\u00EDm nab\u00EDdka uk\u00E1zkov\u00FDch map (sample-maps.js).\n        if (offersSampleMaps(ctx)) renderSampleMapsHint(ctx, container);\n        return;\n    }\n    // Vrstvy, kter\u00E9 se teprve p\u0159ipravuj\u00ED (\u010Dek\u00E1 se na popis dat) \u2014 navrchu,\n    // aby bylo hned vid\u011Bt, \u017Ee se n\u011Bco d\u011Bje (loading.js).\n    preparing.forEach((item) => container.appendChild(preparingRow(item)));\n    ctx.state.layers.forEach((entry) => {\n        container.appendChild(entry.isGroup ? groupRow(ctx, entry) : layerRow(ctx, entry, null));\n    });\n}\n\n/** Nahrad\u00ED obsah stylovac\u00EDho panelu pro danou vrstvu (vol\u00E1no ze style-ui.js). */\nexport function getStylePanelContainer(row) {\n    return row.querySelector('[data-role=\"style-panel\"]');\n}\n", "/**\n * @module ol/Geolocation\n */\nimport BaseObject from './Object.js';\nimport BaseEvent from './events/Event.js';\nimport {circular as circularPolygon} from './geom/Polygon.js';\nimport {toRadians} from './math.js';\nimport {\n  get as getProjection,\n  getTransformFromProjections,\n  identityTransform,\n} from './proj.js';\n\n/**\n * @enum {string}\n */\nconst Property = {\n  ACCURACY: 'accuracy',\n  ACCURACY_GEOMETRY: 'accuracyGeometry',\n  ALTITUDE: 'altitude',\n  ALTITUDE_ACCURACY: 'altitudeAccuracy',\n  HEADING: 'heading',\n  POSITION: 'position',\n  PROJECTION: 'projection',\n  SPEED: 'speed',\n  TRACKING: 'tracking',\n  TRACKING_OPTIONS: 'trackingOptions',\n};\n\n/**\n * @enum string\n */\nconst GeolocationErrorType = {\n  /**\n   * Triggered when a `GeolocationPositionError` occurs.\n   * @event module:ol/Geolocation.GeolocationError#error\n   * @api\n   */\n  ERROR: 'error',\n};\n\n/**\n * @classdesc\n * Events emitted on [GeolocationPositionError](https://developer.mozilla.org/en-US/docs/Web/API/GeolocationPositionError).\n */\nexport class GeolocationError extends BaseEvent {\n  /**\n   * @param {GeolocationPositionError} error error object.\n   */\n  constructor(error) {\n    super(GeolocationErrorType.ERROR);\n\n    /**\n     * Code of the underlying `GeolocationPositionError`.\n     * @type {number}\n     * @api\n     */\n    this.code = error.code;\n\n    /**\n     * Message of the underlying `GeolocationPositionError`.\n     * @type {string}\n     * @api\n     */\n    this.message = error.message;\n  }\n}\n\n/**\n * @typedef {Object} Options\n * @property {boolean} [tracking=false] Start Tracking right after\n * instantiation.\n * @property {PositionOptions} [trackingOptions] Tracking options.\n * See https://www.w3.org/TR/geolocation-API/#position_options_interface.\n * @property {import(\"./proj.js\").ProjectionLike} [projection] The projection the position\n * is reported in.\n */\n\n/**\n * @typedef {import(\"./ObjectEventType.js\").Types|'change:accuracy'|'change:accuracyGeometry'|'change:altitude'|\n *    'change:altitudeAccuracy'|'change:heading'|'change:position'|'change:projection'|'change:speed'|'change:tracking'|\n *    'change:trackingOptions'} GeolocationObjectEventTypes\n */\n\n/***\n * @template Return\n * @typedef {import(\"./Observable.js\").OnSignature<GeolocationObjectEventTypes, import(\"./Object.js\").ObjectEvent, Return> &\n *   import(\"./Observable.js\").OnSignature<'error', GeolocationError, Return> &\n *   import(\"./Observable.js\").CombinedOnSignature<import(\"./Observable.js\").EventTypes|GeolocationObjectEventTypes, Return> &\n *   import(\"./Observable.js\").OnSignature<import(\"./Observable.js\").EventTypes, import(\"./events/Event.js\").default, Return>} GeolocationOnSignature\n */\n\n/**\n * @classdesc\n * Helper class for providing HTML5 Geolocation capabilities.\n * The [Geolocation API](https://www.w3.org/TR/geolocation-API/)\n * is used to locate a user's position.\n *\n * To get notified of position changes and errors, register listeners for the generic\n * `change` event and the `error` event on your instance of {@link module:ol/Geolocation~Geolocation}.\n *\n * Example:\n *\n *     const geolocation = new Geolocation({\n *       // take the projection to use from the map's view\n *       projection: view.getProjection()\n *     });\n *     // listen to changes in position\n *     geolocation.on('change', function(evt) {\n *       console.log(geolocation.getPosition());\n *     });\n *     // listen to error\n *     geolocation.on('error', function(evt) {\n *       window.console.log(evt.message);\n *     });\n *\n * @fires GeolocationError\n * @api\n */\nclass Geolocation extends BaseObject {\n  /**\n   * @param {Options} [options] Options.\n   */\n  constructor(options) {\n    super();\n\n    /***\n     * @type {GeolocationOnSignature<import(\"./events.js\").EventsKey>}\n     */\n    this.on;\n\n    /***\n     * @type {GeolocationOnSignature<import(\"./events.js\").EventsKey>}\n     */\n    this.once;\n\n    /***\n     * @type {GeolocationOnSignature<void>}\n     */\n    this.un;\n\n    options = options || {};\n\n    /**\n     * The unprojected (EPSG:4326) device position.\n     * @private\n     * @type {?import(\"./coordinate.js\").Coordinate}\n     */\n    this.position_ = null;\n\n    /**\n     * @private\n     * @type {import(\"./proj.js\").TransformFunction}\n     */\n    this.transform_ = identityTransform;\n\n    /**\n     * @private\n     * @type {number|undefined}\n     */\n    this.watchId_ = undefined;\n\n    this.addChangeListener(Property.PROJECTION, this.handleProjectionChanged_);\n    this.addChangeListener(Property.TRACKING, this.handleTrackingChanged_);\n\n    if (options.projection !== undefined) {\n      this.setProjection(options.projection);\n    }\n    if (options.trackingOptions !== undefined) {\n      this.setTrackingOptions(options.trackingOptions);\n    }\n\n    this.setTracking(options.tracking !== undefined ? options.tracking : false);\n  }\n\n  /**\n   * Clean up.\n   * @override\n   */\n  disposeInternal() {\n    this.setTracking(false);\n    super.disposeInternal();\n  }\n\n  /**\n   * @private\n   */\n  handleProjectionChanged_() {\n    const projection = this.getProjection();\n    if (projection) {\n      this.transform_ = getTransformFromProjections(\n        getProjection('EPSG:4326'),\n        projection,\n      );\n      if (this.position_) {\n        this.set(Property.POSITION, this.transform_(this.position_));\n      }\n    }\n  }\n\n  /**\n   * @private\n   */\n  handleTrackingChanged_() {\n    if ('geolocation' in navigator) {\n      const tracking = this.getTracking();\n      if (tracking && this.watchId_ === undefined) {\n        this.watchId_ = navigator.geolocation.watchPosition(\n          this.positionChange_.bind(this),\n          this.positionError_.bind(this),\n          this.getTrackingOptions(),\n        );\n      } else if (!tracking && this.watchId_ !== undefined) {\n        navigator.geolocation.clearWatch(this.watchId_);\n        this.watchId_ = undefined;\n      }\n    }\n  }\n\n  /**\n   * @private\n   * @param {GeolocationPosition} position position event.\n   */\n  positionChange_(position) {\n    const coords = position.coords;\n    this.set(Property.ACCURACY, coords.accuracy);\n    this.set(\n      Property.ALTITUDE,\n      coords.altitude === null ? undefined : coords.altitude,\n    );\n    this.set(\n      Property.ALTITUDE_ACCURACY,\n      coords.altitudeAccuracy === null ? undefined : coords.altitudeAccuracy,\n    );\n    this.set(\n      Property.HEADING,\n      coords.heading === null ? undefined : toRadians(coords.heading),\n    );\n    if (!this.position_) {\n      this.position_ = [coords.longitude, coords.latitude];\n    } else {\n      this.position_[0] = coords.longitude;\n      this.position_[1] = coords.latitude;\n    }\n    const projectedPosition = this.transform_(this.position_);\n    this.set(Property.POSITION, projectedPosition.slice());\n    this.set(Property.SPEED, coords.speed === null ? undefined : coords.speed);\n    const geometry = circularPolygon(this.position_, coords.accuracy);\n    geometry.applyTransform(this.transform_);\n    this.set(Property.ACCURACY_GEOMETRY, geometry);\n    this.changed();\n  }\n\n  /**\n   * @private\n   * @param {GeolocationPositionError} error error object.\n   */\n  positionError_(error) {\n    this.dispatchEvent(new GeolocationError(error));\n  }\n\n  /**\n   * Get the accuracy of the position in meters.\n   * @return {number|undefined} The accuracy of the position measurement in\n   *     meters.\n   * @observable\n   * @api\n   */\n  getAccuracy() {\n    return /** @type {number|undefined} */ (this.get(Property.ACCURACY));\n  }\n\n  /**\n   * Get a geometry of the position accuracy.\n   * @return {?import(\"./geom/Polygon.js\").default} A geometry of the position accuracy.\n   * @observable\n   * @api\n   */\n  getAccuracyGeometry() {\n    return /** @type {?import(\"./geom/Polygon.js\").default} */ (\n      this.get(Property.ACCURACY_GEOMETRY) || null\n    );\n  }\n\n  /**\n   * Get the altitude associated with the position.\n   * @return {number|undefined} The altitude of the position in meters above mean\n   *     sea level.\n   * @observable\n   * @api\n   */\n  getAltitude() {\n    return /** @type {number|undefined} */ (this.get(Property.ALTITUDE));\n  }\n\n  /**\n   * Get the altitude accuracy of the position.\n   * @return {number|undefined} The accuracy of the altitude measurement in\n   *     meters.\n   * @observable\n   * @api\n   */\n  getAltitudeAccuracy() {\n    return /** @type {number|undefined} */ (\n      this.get(Property.ALTITUDE_ACCURACY)\n    );\n  }\n\n  /**\n   * Get the heading as radians clockwise from North.\n   * Note: depending on the browser, the heading is only defined if the `enableHighAccuracy`\n   * is set to `true` in the tracking options.\n   * @return {number|undefined} The heading of the device in radians from north.\n   * @observable\n   * @api\n   */\n  getHeading() {\n    return /** @type {number|undefined} */ (this.get(Property.HEADING));\n  }\n\n  /**\n   * Get the position of the device.\n   * @return {import(\"./coordinate.js\").Coordinate|undefined} The current position of the device reported\n   *     in the current projection.\n   * @observable\n   * @api\n   */\n  getPosition() {\n    return /** @type {import(\"./coordinate.js\").Coordinate|undefined} */ (\n      this.get(Property.POSITION)\n    );\n  }\n\n  /**\n   * Get the projection associated with the position.\n   * @return {import(\"./proj/Projection.js\").default|undefined} The projection the position is\n   *     reported in.\n   * @observable\n   * @api\n   */\n  getProjection() {\n    return /** @type {import(\"./proj/Projection.js\").default|undefined} */ (\n      this.get(Property.PROJECTION)\n    );\n  }\n\n  /**\n   * Get the speed in meters per second.\n   * @return {number|undefined} The instantaneous speed of the device in meters\n   *     per second.\n   * @observable\n   * @api\n   */\n  getSpeed() {\n    return /** @type {number|undefined} */ (this.get(Property.SPEED));\n  }\n\n  /**\n   * Determine if the device location is being tracked.\n   * @return {boolean} The device location is being tracked.\n   * @observable\n   * @api\n   */\n  getTracking() {\n    return /** @type {boolean} */ (this.get(Property.TRACKING));\n  }\n\n  /**\n   * Get the tracking options.\n   * See https://www.w3.org/TR/geolocation-API/#position-options.\n   * @return {PositionOptions|undefined} PositionOptions as defined by\n   *     the [HTML5 Geolocation spec\n   *     ](https://www.w3.org/TR/geolocation-API/#position_options_interface).\n   * @observable\n   * @api\n   */\n  getTrackingOptions() {\n    return /** @type {PositionOptions|undefined} */ (\n      this.get(Property.TRACKING_OPTIONS)\n    );\n  }\n\n  /**\n   * Set the projection to use for transforming the coordinates.\n   * @param {import(\"./proj.js\").ProjectionLike} projection The projection the position is\n   *     reported in.\n   * @observable\n   * @api\n   */\n  setProjection(projection) {\n    this.set(Property.PROJECTION, getProjection(projection));\n  }\n\n  /**\n   * Enable or disable tracking.\n   * @param {boolean} tracking Enable tracking.\n   * @observable\n   * @api\n   */\n  setTracking(tracking) {\n    this.set(Property.TRACKING, tracking);\n  }\n\n  /**\n   * Set the tracking options.\n   * See http://www.w3.org/TR/geolocation-API/#position-options.\n   * @param {PositionOptions} options PositionOptions as defined by the\n   *     [HTML5 Geolocation spec\n   *     ](http://www.w3.org/TR/geolocation-API/#position_options_interface).\n   * @observable\n   * @api\n   */\n  setTrackingOptions(options) {\n    this.set(Property.TRACKING_OPTIONS, options);\n  }\n}\n\nexport default Geolocation;\n", "/**\n * locate.js \u2014 tla\u010D\u00EDtko \u201Emoje poloha\u201C pod tla\u010D\u00EDtky zoomu.\n *\n * Hlavn\u011B pro telefon v ter\u00E9nu: prvn\u00ED klik zapne sledov\u00E1n\u00ED polohy (prohl\u00ED\u017Ee\u010D\n * se zept\u00E1 na svolen\u00ED), mapa se na polohu p\u0159ibl\u00ED\u017E\u00ED a ukazuje modrou te\u010Dku\n * s kruhem p\u0159esnosti; dal\u0161\u00ED klik sledov\u00E1n\u00ED vypne a te\u010Dku odebere. Poloha se\n * nikam nepos\u00EDl\u00E1 ani neukl\u00E1d\u00E1 \u2014 z\u016Fst\u00E1v\u00E1 jen v prohl\u00ED\u017Ee\u010Di.\n *\n * Tla\u010D\u00EDtko se nep\u0159id\u00E1, kdy\u017E prohl\u00ED\u017Ee\u010D polohu neum\u00ED (nebo str\u00E1nka neb\u011B\u017E\u00ED\n * p\u0159es HTTPS).\n */\nimport Control from 'ol/control/Control.js';\nimport Geolocation from 'ol/Geolocation.js';\nimport Feature from 'ol/Feature.js';\nimport Point from 'ol/geom/Point.js';\nimport VectorLayer from 'ol/layer/Vector.js';\nimport VectorSource from 'ol/source/Vector.js';\nimport {\n    Circle as CircleStyle, Fill, Stroke, Style,\n} from 'ol/style.js';\nimport { showToast } from './notices.js';\n\nconst ICON = '<svg viewBox=\"0 0 24 24\" width=\"16\" height=\"16\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" aria-hidden=\"true\"><circle cx=\"12\" cy=\"12\" r=\"7\"/><circle cx=\"12\" cy=\"12\" r=\"2.5\" fill=\"currentColor\" stroke=\"none\"/><path d=\"M12 2v3M12 19v3M2 12h3M19 12h3\"/></svg>';\n\n/** Srozumiteln\u00E1 hl\u00E1\u0161ka k chyb\u011B geolokace (k\u00F3dy dle Geolocation API). */\nfunction errorMessage(error) {\n    if (error?.code === 1) return 'Location access was denied. Allow it in the browser settings to see your position.';\n    if (error?.code === 3) return 'Finding your location took too long. Try again.';\n    return 'Your location is not available right now.';\n}\n\nexport function initLocate(ctx) {\n    if (!('geolocation' in navigator) || window.isSecureContext === false) return null;\n\n    const position = new Feature();\n    position.setStyle(new Style({\n        image: new CircleStyle({\n            radius: 7,\n            fill: new Fill({ color: '#027fbe' }),\n            stroke: new Stroke({ color: '#ffffff', width: 2.5 }),\n        }),\n    }));\n    const accuracy = new Feature();\n    accuracy.setStyle(new Style({\n        fill: new Fill({ color: 'rgba(2, 127, 190, 0.12)' }),\n        stroke: new Stroke({ color: 'rgba(2, 127, 190, 0.5)', width: 1 }),\n    }));\n    // Vrstva nen\u00ED ve stromu vrstev ani v ulo\u017Een\u00E9 map\u011B \u2014 je to jen ukazatel.\n    const layer = new VectorLayer({\n        source: new VectorSource({ features: [accuracy, position] }),\n        zIndex: 9000,\n        properties: { locateLayer: true },\n    });\n\n    const geolocation = new Geolocation({\n        projection: ctx.map.getView().getProjection(),\n        trackingOptions: { enableHighAccuracy: true, maximumAge: 10000, timeout: 20000 },\n    });\n\n    const element = document.createElement('div');\n    element.className = 'map-locate ol-unselectable ol-control';\n    const button = document.createElement('button');\n    button.type = 'button';\n    button.title = 'Show my location';\n    button.setAttribute('aria-label', 'Show my location');\n    button.setAttribute('aria-pressed', 'false');\n    button.innerHTML = ICON;\n    element.appendChild(button);\n\n    let active = false;\n    let centred = false;\n\n    function stop() {\n        active = false;\n        centred = false;\n        geolocation.setTracking(false);\n        ctx.map.removeLayer(layer);\n        position.setGeometry(undefined);\n        accuracy.setGeometry(undefined);\n        button.classList.remove('is-active', 'is-busy');\n        button.title = 'Show my location';\n        button.setAttribute('aria-pressed', 'false');\n    }\n\n    function start() {\n        active = true;\n        ctx.map.addLayer(layer);\n        geolocation.setTracking(true);\n        button.classList.add('is-active', 'is-busy');\n        button.title = 'Hide my location';\n        button.setAttribute('aria-pressed', 'true');\n    }\n\n    geolocation.on('change:position', () => {\n        const coordinate = geolocation.getPosition();\n        if (!active || !coordinate) return;\n        position.setGeometry(new Point(coordinate));\n        button.classList.remove('is-busy');\n        if (!centred) {\n            // Jen poprv\u00E9 \u2014 pak u\u017E mapu u\u017Eivateli pod rukama neposouv\u00E1me.\n            centred = true;\n            const view = ctx.map.getView();\n            view.animate({ center: coordinate, zoom: Math.max(view.getZoom() || 0, 15), duration: 500 });\n        }\n    });\n    geolocation.on('change:accuracyGeometry', () => {\n        if (active) accuracy.setGeometry(geolocation.getAccuracyGeometry() || undefined);\n    });\n    geolocation.on('error', (error) => {\n        stop();\n        showToast(errorMessage(error), { tone: 'error' });\n    });\n\n    button.addEventListener('click', () => (active ? stop() : start()));\n\n    ctx.map.addControl(new Control({ element }));\n    return { stop };\n}\n", "/**\n * advisor.js \u2014 upozorn\u011Bn\u00ED na data, kter\u00E1 se kresl\u00ED pomalu, a jejich p\u0159evod.\n *\n * Textov\u00E9 form\u00E1ty bez prostorov\u00E9ho indexu (GeoJSON, GML, GPX, CSV, DXF\u2026) \u010Dte\n * Mapserver p\u0159i ka\u017Ed\u00E9m p\u0159ekreslen\u00ED cel\u00E9; od des\u00EDtek tis\u00EDc prvk\u016F to jsou\n * sekundy na ka\u017Ed\u00FD posun mapy. Tat\u00E1\u017E data ve FlatGeobuf / GeoPackage se kresl\u00ED\n * n\u011Bkolikan\u00E1sobn\u011B rychleji. Mapa to pozn\u00E1 dv\u011Bma zp\u016Fsoby:\n *\n *  - **odhadem** od Mapserveru (`performance` v popisu dat \u2014 z velikosti\n *    souboru, po\u010Dtu prvk\u016F a zm\u011B\u0159en\u00E9 rychlosti \u010Dten\u00ED form\u00E1tu),\n *  - **m\u011B\u0159en\u00EDm**: vrstva se opakovan\u011B kreslila d\u00E9le ne\u017E `SLOW_SECONDS`\n *    a \u010Dten\u00ED souboru je podstatn\u00E1 \u010D\u00E1st t\u00E9 doby (loading.js m\u011B\u0159\u00ED ka\u017Ed\u00E9\n *    vykreslen\u00ED).\n *\n * Pomal\u00E1 vrstva dostane ve stromu ikonu blesku a jednou za sezen\u00ED nen\u00E1siln\u00FD\n * toast. Oboj\u00ED otev\u0159e dialog: pro\u010D je vrstva pomal\u00E1, kolik p\u0159evod stoj\u00ED\n * (stejn\u00FD odhad a kredity jako Converter), volba \u201Eulo\u017Eit p\u0159eveden\u00FD soubor i do\n * workspace\u201C a \u201Eu\u017E neukazovat\u201C. P\u0159evod b\u011B\u017E\u00ED na pozad\u00ED (`/render-copy/`), mapa\n * z\u016Fst\u00E1v\u00E1 pou\u017Eiteln\u00E1; po dokon\u010Den\u00ED se vrstvy polo\u017Eky na\u010Dtou znovu \u2014 kresl\u00ED se\n * z p\u0159eveden\u00E9 kopie, u\u017Eivatel\u016Fv soubor ve workspace z\u016Fst\u00E1v\u00E1, jak byl.\n *\n * P\u0159ev\u00E9st m\u016F\u017Ee jen vlastn\u00EDk dat. Div\u00E1k ciz\u00ED mapy dostane jen vysv\u011Btlen\u00ED.\n */\nimport { apiFetch, emit, getCookie, on } from './utils.js';\nimport { findEntryByUid, flatLayers } from './state.js';\nimport { reloadItemLayers, updateLayerStatus } from './layers.js';\nimport { showToast } from './notices.js';\n\n/** Vykreslen\u00ED del\u0161\u00ED ne\u017E tohle (s) u\u017E u\u017Eivatele zdr\u017Euje (zad\u00E1n\u00ED: 3\u20134 s). */\nexport const SLOW_SECONDS = 4;\n/** Kolik pomal\u00FDch vykreslen\u00ED po sob\u011B je pot\u0159eba (jedno m\u016F\u017Ee b\u00FDt n\u00E1hoda). */\nconst SLOW_RENDERS = 2;\n/** \u010Cten\u00ED souboru mus\u00ED d\u011Blat aspo\u0148 tuhle \u010D\u00E1st doby, aby p\u0159evod pomohl. */\nconst READ_SHARE = 0.4;\nconst STORAGE_KEY = 'mg-map-slow-data';\nconst POLL_MS = 2500;\n\n/* ---------------------------------------------------------------------------\n * \u201EU\u017E neukazovat\u201C \u2014 v prohl\u00ED\u017Ee\u010Di (pro jednotliv\u00E1 data, nebo \u00FApln\u011B)\n * ------------------------------------------------------------------------- */\n\nfunction readStore() {\n    try {\n        const value = JSON.parse(window.localStorage.getItem(STORAGE_KEY) || '{}');\n        return { all: Boolean(value.all), items: value.items && typeof value.items === 'object' ? value.items : {} };\n    } catch {\n        return { all: false, items: {} };\n    }\n}\n\nfunction writeStore(store) {\n    try {\n        window.localStorage.setItem(STORAGE_KEY, JSON.stringify(store));\n    } catch {\n        /* soukrom\u00E9 okno / pln\u00E9 \u00FAlo\u017Ei\u0161t\u011B \u2014 volba plat\u00ED jen do zav\u0159en\u00ED str\u00E1nky */\n    }\n}\n\n/** Data, kter\u00E1 u\u017Eivatel odm\u00EDtl jen pro toto sezen\u00ED (\u00FAlo\u017Ei\u0161t\u011B nedostupn\u00E9). */\nconst sessionDismissed = new Set();\n\nfunction isDismissed(itemId) {\n    const store = readStore();\n    return store.all || Boolean(store.items[itemId]) || sessionDismissed.has(itemId);\n}\n\nfunction dismiss(itemId) {\n    const store = readStore();\n    store.items[itemId] = Date.now();\n    // Seznam nenech\u00E1me r\u016Fst donekone\u010Dna.\n    const ids = Object.keys(store.items);\n    if (ids.length > 200) ids.sort((a, b) => store.items[a] - store.items[b]).slice(0, ids.length - 200).forEach((id) => delete store.items[id]);\n    writeStore(store);\n    sessionDismissed.add(itemId);\n}\n\n/* ---------------------------------------------------------------------------\n * Je vrstva pomal\u00E1 a pomohl by p\u0159evod?\n * ------------------------------------------------------------------------- */\n\nfunction median(values) {\n    const sorted = [...values].sort((a, b) => a - b);\n    return sorted.length ? sorted[Math.floor(sorted.length / 2)] : 0;\n}\n\n/**\n * Posudek vrstvy: `{ slow, seconds, measured, performance }` nebo null, kdy\u017E\n * p\u0159evod nepom\u016F\u017Ee (rychl\u00FD form\u00E1t, rastr, extern\u00ED slu\u017Eba, mal\u00E1 data).\n */\nexport function assessEntry(entry) {\n    const perf = entry?.performance;\n    if (!entry || entry.isGroup || !entry.wms || entry.dataType !== 'vector' || !perf) return null;\n    const readShare = perf.expectedSeconds > 0 ? (perf.readSeconds || 0) / perf.expectedSeconds : 0;\n    if (!(perf.readSeconds > 0) || readShare < READ_SHARE) return null;\n    const times = entry.renderTimes || [];\n    const recent = times.slice(-SLOW_RENDERS);\n    const measuredSlow = recent.length >= SLOW_RENDERS && recent.every((t) => t >= SLOW_SECONDS);\n    if (perf.advice) {\n        return { slow: true, seconds: measuredSlow ? median(times) : perf.expectedSeconds, measured: measuredSlow, performance: perf };\n    }\n    if (measuredSlow) return { slow: true, seconds: median(times), measured: true, performance: perf };\n    return null;\n}\n\n/** Polo\u017Eky mapy, kter\u00E9 se kresl\u00ED pomalu \u2014 pro dialog sd\u00EDlen\u00ED (share.js). */\nexport function slowItems(ctx) {\n    const seen = new Map();\n    flatLayers(ctx.state).forEach((entry) => {\n        const verdict = assessEntry(entry);\n        if (verdict && !seen.has(entry.itemId)) seen.set(entry.itemId, { entry, verdict });\n    });\n    return Array.from(seen.values());\n}\n\n/* ---------------------------------------------------------------------------\n * Texty\n * ------------------------------------------------------------------------- */\n\nfunction esc(value) {\n    return String(value ?? '').replace(/[&<>\"']/g, (c) => ({\n        '&': '&amp;', '<': '&lt;', '>': '&gt;', '\"': '&quot;', \"'\": '&#39;',\n    })[c]);\n}\n\nfunction formatSize(bytes) {\n    if (!bytes) return '';\n    if (bytes >= 1048576) return `${(bytes / 1048576).toFixed(bytes >= 104857600 ? 0 : 1)} MB`;\n    return `${Math.max(1, Math.round(bytes / 1024))} kB`;\n}\n\nfunction formatSeconds(seconds) {\n    if (seconds >= 10) return `${Math.round(seconds)} s`;\n    return `${seconds.toFixed(1)} s`;\n}\n\nfunction formatCredits(credits) {\n    if (!credits) return '';\n    const fmt = (v) => (Math.round(v * 10) / 10).toLocaleString('en-US');\n    const { expected, low, high } = credits;\n    const text = high - low >= 0.5 ? `${fmt(low)}\u2013${fmt(high)}` : fmt(expected);\n    return `${text} credit${expected === 1 && high - low < 0.5 ? '' : 's'}`;\n}\n\nfunction fileName(entry) {\n    return entry.source?.name || entry.itemTitle || entry.title;\n}\n\nfunction formatName(entry, perf) {\n    return entry.source?.format || perf.driver || 'this format';\n}\n\nfunction whyText(entry, verdict) {\n    const perf = verdict.performance;\n    // Jedin\u00FD \u201Eprvek\u201C ob\u0159\u00EDho souboru je kolekce v\u0161ech geometri\u00ED \u2014 po\u010Det by m\u00E1tl.\n    const facts = [formatSize(perf.sizeBytes), perf.features > 1 ? `${perf.features.toLocaleString('en-US')} features` : '']\n        .filter(Boolean).join(', ');\n    const after = perf.advice?.expectedSeconds ?? Math.max(0.1, perf.expectedSeconds - perf.readSeconds);\n    if (perf.tooSlow) {\n        return `${esc(formatName(entry, perf))} has no spatial index, so the whole file${facts ? ` (${esc(facts)})` : ''} `\n            + `would be read every time the map is redrawn \u2014 about <b>${formatSeconds(verdict.seconds)}</b> per redraw. `\n            + 'That is too slow for a map, so the layer is not drawn. '\n            + `The same data in a format made for maps (FlatGeobuf, GeoPackage) draw in about <b>${formatSeconds(Math.max(after, 0.1))}</b> `\n            + 'for the whole extent and much faster when zoomed in.';\n    }\n    return `${esc(formatName(entry, perf))} has no spatial index, so the whole file${facts ? ` (${esc(facts)})` : ''} `\n        + `is read every time the map is redrawn \u2014 about <b>${formatSeconds(verdict.seconds)}</b> per redraw, however far you zoom in. `\n        + `The same data in a format made for maps (FlatGeobuf, GeoPackage) draw in about <b>${formatSeconds(Math.max(after, 0.1))}</b> `\n        + 'for the whole extent and much faster when zoomed in.';\n}\n\n/* ---------------------------------------------------------------------------\n * Dialog\n * ------------------------------------------------------------------------- */\n\nlet dialogEl = null;\n\nfunction closeDialog() {\n    if (dialogEl) {\n        dialogEl.remove();\n        dialogEl = null;\n    }\n}\n\ndocument.addEventListener('keydown', (event) => {\n    if (event.key === 'Escape' && dialogEl) closeDialog();\n});\n\n/** P\u0159evody, kter\u00E9 pr\u00E1v\u011B b\u011B\u017E\u00ED: itemId -> { toast }. */\nconst running = new Map();\n\nfunction openDialog(ctx, entry) {\n    const verdict = assessEntry(entry);\n    if (!verdict) return;\n    closeDialog();\n    const itemId = entry.itemId;\n    const overlay = document.createElement('div');\n    overlay.className = 'fixed inset-0 z-50 flex items-center justify-center bg-slate-900/50 p-4';\n    overlay.innerHTML = `\n        <div class=\"w-full max-w-md rounded-xl border border-slate-200 bg-white shadow-xl\" role=\"dialog\" aria-modal=\"true\" aria-labelledby=\"map-advisor-title\">\n            <div class=\"flex items-center justify-between border-b border-slate-100 px-4 py-3\">\n                <h3 id=\"map-advisor-title\" class=\"text-sm font-semibold text-slate-800\">${verdict.performance.tooSlow ? 'This layer is too large to draw' : 'This layer draws slowly'}</h3>\n                <button type=\"button\" data-role=\"close\" aria-label=\"Close\" class=\"rounded p-1 text-slate-400 hover:bg-slate-100 hover:text-slate-600\">\u2715</button>\n            </div>\n            <div class=\"max-h-[70vh] space-y-3 overflow-y-auto px-4 py-4 text-sm text-slate-700\">\n                <p class=\"font-medium text-slate-900\">${esc(fileName(entry))}</p>\n                <p class=\"leading-relaxed\">${whyText(entry, verdict)}</p>\n                <div data-role=\"offer\" class=\"rounded-lg bg-slate-50 px-3 py-2.5 text-xs leading-relaxed text-slate-600\">\n                    <span class=\"map-spinner mr-1.5 align-[-2px]\" aria-hidden=\"true\"></span>Checking what the conversion would cost\u2026\n                </div>\n                <p data-role=\"error\" class=\"hidden text-xs text-red-600\"></p>\n                <label class=\"flex items-center gap-x-2 text-xs text-slate-500\">\n                    <input type=\"checkbox\" data-role=\"never\" class=\"h-3.5 w-3.5 rounded border-slate-300 text-brand-600 focus:ring-brand-500\">\n                    Don\u2019t remind me about these data again\n                </label>\n            </div>\n            <div class=\"flex items-center justify-end gap-x-2 border-t border-slate-100 px-4 py-3\">\n                <button type=\"button\" data-role=\"later\" class=\"rounded-lg border border-slate-200 bg-white px-3 py-1.5 text-sm font-medium text-slate-700 hover:bg-slate-50\">Keep as it is</button>\n                <button type=\"button\" data-role=\"convert\" disabled class=\"btn-primary !px-3 !py-1.5 text-sm disabled:cursor-not-allowed disabled:opacity-50\">Convert</button>\n            </div>\n        </div>`;\n    document.body.appendChild(overlay);\n    dialogEl = overlay;\n    const q = (role) => overlay.querySelector(`[data-role=\"${role}\"]`);\n    const offer = q('offer');\n    const errorEl = q('error');\n    const convert = q('convert');\n\n    function showError(text, linkHtml = '') {\n        errorEl.innerHTML = `${esc(text)}${linkHtml}`;\n        errorEl.classList.remove('hidden');\n    }\n\n    function close() {\n        // \u201EKeep as it is\u201C jen zav\u0159e (v tomto sezen\u00ED u\u017E toast nevysko\u010D\u00ED);\n        // se za\u0161krtnut\u00EDm se tato data u\u017E nep\u0159ipom\u00EDnaj\u00ED v\u016Fbec \u2014 ani ikonou.\n        if (q('never').checked) {\n            dismiss(itemId);\n            refreshHints(ctx);\n        }\n        closeDialog();\n    }\n    q('close').addEventListener('click', () => close());\n    q('later').addEventListener('click', () => close());\n    overlay.addEventListener('mousedown', (event) => { if (event.target === overlay) close(); });\n\n    if (running.has(itemId)) {\n        offer.textContent = 'The conversion of these data is running \u2014 the layer will switch to the faster copy when it finishes.';\n        return;\n    }\n\n    let target = '';\n\n    function loadOffer() {\n        const query = target ? `?target=${encodeURIComponent(target)}` : '';\n        return apiFetch(`${ctx.bootstrap.apiBase}/items/${itemId}/render-copy/${query}`).then(showOffer).catch(() => {\n            if (dialogEl !== overlay) return;\n            offer.textContent = 'The cost of the conversion could not be checked right now. Please try again later.';\n        });\n    }\n\n    function showOffer(info) {\n        if (dialogEl !== overlay) return;\n        if (info.job_id) {\n            offer.textContent = 'The conversion of these data is already running.';\n            watch(ctx, itemId, info.job_id, fileName(entry));\n            return;\n        }\n        if (!info.eligible) {\n            offer.textContent = info.reason === 'not_owner'\n                ? 'Only the owner of these data can convert them. If the map is slow for you, let the owner know.'\n                : (info.message || 'These data cannot be converted here.');\n            q('later').textContent = 'Close';\n            return;\n        }\n        const cost = info.cost || {};\n        const price = formatCredits(info.credits);\n        target = info.target_key || target;\n        const targets = info.targets || [];\n        // V\u00EDc vhodn\u00FDch form\u00E1t\u016F = volba (oba se kresl\u00ED stejn\u011B rychle).\n        const formatHtml = targets.length > 1\n            ? `<label class=\"mt-1.5 flex items-center gap-x-2\">Format\n                 <select data-role=\"target\" class=\"rounded-lg border-slate-200 py-1 pl-2 pr-7 text-xs focus:border-brand-500 focus:ring-brand-500\">\n                   ${targets.map((t, i) => `<option value=\"${esc(t.key)}\"${t.key === target ? ' selected' : ''}>${esc(t.label)}${i === 0 ? ' (recommended)' : ''}</option>`).join('')}\n                 </select></label>`\n            : '';\n        errorEl.classList.add('hidden');\n        // Zm\u011Bna form\u00E1tu nab\u00EDdku p\u0159ekresl\u00ED \u2014 za\u0161krtnut\u00ED \u201Eulo\u017Eit i do workspace\u201C z\u016Fstane.\n        const saveCopy = Boolean(q('save-copy')?.checked);\n        offer.innerHTML = `\n            <p><b>Convert to ${esc(info.target)}</b> \u2014 in the background, you can keep working with the map.\n               The map will then draw from the converted copy; your file in the workspace stays as it is\n               and the look of the layer does not change.</p>\n            ${formatHtml}\n            <p class=\"mt-1.5\">Cost: <b>${esc(price)}</b>${cost.note ? ` <span class=\"text-slate-500\">(${esc(cost.note)})</span>` : ''}</p>\n            <label class=\"mt-2 flex items-start gap-x-2\">\n                <input type=\"checkbox\" data-role=\"save-copy\"${saveCopy ? ' checked' : ''} class=\"mt-0.5 h-3.5 w-3.5 rounded border-slate-300 text-brand-600 focus:ring-brand-500\">\n                <span>Also save the converted file to my workspace <span class=\"text-slate-500\">(as a new item, counts towards storage)</span></span>\n            </label>`;\n        // Bez kredit\u016F p\u0159evod spustit nejde \u2014 cena je ale vid\u011Bt i tak.\n        const affordable = cost.covered !== false;\n        if (!affordable) {\n            showError('You don\u2019t have enough credits for this conversion. ', creditsLink(ctx));\n        }\n        q('target')?.addEventListener('change', (event) => {\n            target = event.target.value;\n            convert.disabled = true;\n            loadOffer();\n        });\n        convert.disabled = !affordable;\n        convert.onclick = async () => {\n            convert.disabled = true;\n            errorEl.classList.add('hidden');\n            try {\n                const job = await startConversion(ctx, itemId, Boolean(q('save-copy')?.checked), target);\n                closeDialog();\n                watch(ctx, itemId, job.job_id, fileName(entry));\n            } catch (error) {\n                convert.disabled = false;\n                showError(error.message, error.linkHtml || '');\n            }\n        };\n    }\n\n    loadOffer();\n}\n\nfunction creditsLink(ctx, url) {\n    const href = url || ctx.bootstrap.billing?.creditsUrl || ctx.bootstrap.billing?.pricingUrl;\n    return href ? `<a class=\"font-semibold underline\" href=\"${esc(href)}\" target=\"_blank\" rel=\"noopener\">Get credits</a>` : '';\n}\n\n/** POST bez `apiFetch`: nedostatek kredit\u016F (402) tady nen\u00ED \u201Emapa nejde\n * zobrazit\u201C, ale hl\u00E1\u0161ka v dialogu. */\nasync function startConversion(ctx, itemId, saveCopy, target) {\n    const response = await fetch(`${ctx.bootstrap.apiBase}/items/${itemId}/render-copy/`, {\n        method: 'POST',\n        credentials: 'same-origin',\n        headers: { 'Content-Type': 'application/json', 'X-CSRFToken': getCookie('csrftoken') || '' },\n        body: JSON.stringify({ save_copy: saveCopy, target: target || undefined }),\n    });\n    let data = null;\n    try {\n        data = await response.json();\n    } catch {\n        data = null;\n    }\n    if (response.ok && data?.job_id) return data;\n    const error = new Error(data?.detail || data?.error || data?.message || 'The conversion could not be started. Please try again later.');\n    if (response.status === 402) {\n        error.message = `${data?.detail || 'You don\u2019t have enough credits.'} `;\n        error.linkHtml = creditsLink(ctx, data?.plans?.[0]?.subscribe_url);\n    }\n    throw error;\n}\n\n/* ---------------------------------------------------------------------------\n * Pr\u016Fb\u011Bh p\u0159evodu\n * ------------------------------------------------------------------------- */\n\nfunction watch(ctx, itemId, jobId, name) {\n    if (running.has(itemId)) return;\n    const toast = showToast(`Converting \u201C${name}\u201D for faster drawing\u2026`, { tone: 'busy' });\n    running.set(itemId, { toast });\n    refreshHints(ctx);\n    let failures = 0;\n\n    async function tick() {\n        let status;\n        try {\n            status = await apiFetch(`${ctx.bootstrap.apiBase}/render-copy/${jobId}/`);\n            failures = 0;\n        } catch {\n            failures += 1;\n            if (failures >= 8) {\n                running.delete(itemId);\n                toast.update(`The conversion of \u201C${name}\u201D could not be followed. It may still finish \u2014 reload the map later.`, { tone: 'error' });\n                refreshHints(ctx);\n                return;\n            }\n            setTimeout(tick, POLL_MS * 2);\n            return;\n        }\n        if (!status.done) {\n            toast.update(`Converting \u201C${name}\u201D for faster drawing\u2026 ${status.elapsed_s} s`, { tone: 'busy' });\n            setTimeout(tick, POLL_MS);\n            return;\n        }\n        running.delete(itemId);\n        if (!status.ok) {\n            toast.update(`\u201C${name}\u201D could not be converted: ${status.error || 'unknown error'}`, { tone: 'error' });\n            refreshHints(ctx);\n            return;\n        }\n        try {\n            await reloadItemLayers(ctx, itemId);\n        } catch {\n            /* vrstva se p\u0159epne p\u0159i p\u0159\u00ED\u0161t\u00EDm na\u010Dten\u00ED mapy */\n        }\n        const saved = status.saved ? ' The converted file was also saved to your workspace.'\n            : (status.save_error ? ` It could not be saved to the workspace: ${status.save_error}` : '');\n        toast.update(`\u201C${name}\u201D now draws from a faster copy.${saved}`, { tone: 'ok', timeout: 9000 });\n        refreshHints(ctx);\n    }\n    setTimeout(tick, POLL_MS);\n}\n\n/* ---------------------------------------------------------------------------\n * Ikona u vrstvy + toast\n * ------------------------------------------------------------------------- */\n\nconst toasted = new Set();\n\nfunction refreshHints(ctx) {\n    flatLayers(ctx.state).forEach((entry) => {\n        const hint = !isDismissed(entry.itemId) && !running.has(entry.itemId) && Boolean(assessEntry(entry));\n        if (Boolean(entry.slowHint) === hint) return;\n        entry.slowHint = hint;\n        updateLayerStatus(ctx, entry);\n    });\n}\n\n/** Jednou za sezen\u00ED a polo\u017Eku: hned p\u0159i p\u0159id\u00E1n\u00ED vrstvy / otev\u0159en\u00ED mapy\n * (podle odhadu slu\u017Eby \u2014 u\u017Eivatel v\u00ED p\u0159edem, pro\u010D \u010Dek\u00E1), nebo a\u017E kdy\u017E se\n * pomalost uk\u00E1\u017Ee m\u011B\u0159en\u00EDm. */\nfunction maybeToast(ctx, entry) {\n    const verdict = assessEntry(entry);\n    if (!verdict || toasted.has(entry.itemId) || isDismissed(entry.itemId) || running.has(entry.itemId)) return;\n    toasted.add(entry.itemId);\n    const perf = verdict.performance;\n    const what = [formatSize(perf.sizeBytes), formatName(entry, perf)].filter(Boolean).join(' ');\n    let text = verdict.measured\n        ? `\u201C${fileName(entry)}\u201D takes about ${formatSeconds(verdict.seconds)} to draw. It can be much faster.`\n        : `\u201C${fileName(entry)}\u201D (${what}) needs about ${formatSeconds(verdict.seconds)} for every redraw of the map. It can be much faster.`;\n    if (perf.tooSlow) {\n        text = `\u201C${fileName(entry)}\u201D (${what}) would need about ${formatSeconds(verdict.seconds)} for every redraw, `\n            + 'so it is not drawn. Convert it to a format made for maps to show it.';\n    }\n    showToast(text, {\n        timeout: perf.tooSlow ? 30000 : 20000,\n        action: { label: perf.tooSlow ? 'Convert\u2026' : 'Speed up\u2026', onClick: () => openDialog(ctx, entry) },\n    });\n}\n\nexport function initAdvisor(ctx) {\n    on('layers:changed', ({ reason }) => {\n        if (reason !== 'add' && reason !== 'reload') return;\n        refreshHints(ctx);\n        if (reason === 'add') flatLayers(ctx.state).forEach((entry) => maybeToast(ctx, entry));\n    });\n    on('layer:render-time', ({ entry }) => {\n        refreshHints(ctx);\n        maybeToast(ctx, entry);\n    });\n    on('advisor:open', ({ uid, itemId }) => {\n        const entry = uid ? findEntryByUid(ctx.state, uid)\n            : flatLayers(ctx.state).find((e) => e.itemId === itemId && assessEntry(e));\n        if (entry) openDialog(ctx, entry);\n    });\n    return { slowItems: () => slowItems(ctx) };\n}\n\n// Pro testy / lad\u011Bn\u00ED v konzoli.\nexport const _internals = { readStore, dismiss, emit };\n", "/**\n * style-export.js \u2014 \u201ESave the style into the data\u201C (zad\u00E1n\u00ED 16, bod 2).\n *\n * Styl vrstvy \u017Eije v map\u011B (ukl\u00E1d\u00E1 se s n\u00ED). Na v\u00FDslovn\u00E9 p\u0159\u00E1n\u00ED u\u017Eivatele ho\n * jde zapsat p\u0159\u00EDmo do dat: vznikne **kopie vrstvy jako nov\u00E1 polo\u017Eka\n * workspace**, p\u016Fvodn\u00ED soubor se nem\u011Bn\u00ED. Kopie z\u016Fst\u00E1v\u00E1 ve form\u00E1tu p\u016Fvodn\u00EDch\n * dat a styl se ulo\u017E\u00ED tak, jak to ten form\u00E1t um\u00ED:\n *\n * 1. nativn\u011B (KML, KMZ, DXF, MapInfo) \u2014 jako styly form\u00E1tu samotn\u00E9ho, bez\n *    atributu `OGR_STYLE`,\n * 2. atributem `OGR_STYLE` (Shapefile, GeoPackage, GeoJSON\u2026) \u2014 form\u00E1t styly\n *    nem\u00E1, ale unese libovoln\u00FD atribut,\n * 3. v GeoJSON s atributem `OGR_STYLE` \u2014 kdy\u017E form\u00E1t nejde zapsat nebo nem\u00E1\n *    ani voln\u00E9 atributy (GPX, DGN, OSM\u2026).\n *\n * Kopii zapisuje \u00FAloha Converteru nad p\u016Fvodn\u00EDmi daty (`apps/maps/\n * styled_copy.py`, stoj\u00ED kredity jako ka\u017Ed\u00FD p\u0159evod). Mapa j\u00ED po\u0161le **pravidla\n * stylu** \u2014 symbol pro bod, linii a plochu, jeden pro celou vrstvu nebo po\n * kategori\u00EDch \u010Di intervalech (`styleRules`) \u2014 a p\u0159evodn\u00EDk podle nich ur\u010D\u00ED styl\n * ka\u017Ed\u00E9ho prvku. Symboly se zapisuj\u00ED jako OGR feature styles (`PEN`, `BRUSH`,\n * `SYMBOL`, `LABEL`) stejn\u00FDmi pravidly jako SLD a legenda (`ruleForCategory`).\n */\nimport { apiFetch, getCookie, on } from './utils.js';\nimport { findEntryByUid, findEntryContainer, ruleForCategory } from './state.js';\nimport { addLayerByItemId, moveEntry, removeLayer, renameLayer, renderLayerTree } from './layers.js';\nimport { showToast } from './notices.js';\n\nexport const STYLE_FIELD = 'OGR_STYLE';\nconst GEOMETRIES = ['point', 'line', 'polygon'];\nconst POLL_MS = 2000;\n\n/** Tvary bodu \u2192 \u010D\u00EDsla standardn\u00EDch symbol\u016F OGR (`ogr-sym-N`). */\nconst OGR_SYMBOLS = {\n    circle: 3, square: 5, triangle: 7, star: 9, cross: 0, x: 1,\n};\n\n/* ---------------------------------------------------------------------------\n * Styl vrstvy \u2192 \u0159et\u011Bzec stylu OGR\n * ------------------------------------------------------------------------- */\n\nfunction hex(color, opacity) {\n    const value = String(color || '#000000').trim();\n    const base = /^#[0-9a-f]{6}$/i.test(value) ? value\n        : (/^#[0-9a-f]{3}$/i.test(value) ? `#${value[1]}${value[1]}${value[2]}${value[2]}${value[3]}${value[3]}` : '#000000');\n    if (opacity === undefined || opacity === null || opacity >= 1) return base.toUpperCase();\n    const alpha = Math.max(0, Math.min(255, Math.round(opacity * 255)));\n    return `${base}${alpha.toString(16).padStart(2, '0')}`.toUpperCase();\n}\n\nfunction px(value, fallback) {\n    const number = Number(value);\n    return `${Number.isFinite(number) ? Math.round(number * 100) / 100 : fallback}px`;\n}\n\nfunction dashPattern(dash) {\n    const parts = String(dash || '').split(/[\\s,]+/).map(Number).filter((n) => Number.isFinite(n) && n > 0);\n    return parts.length >= 2 ? `,p:\"${parts.map((n) => `${n}px`).join(' ')}\"` : '';\n}\n\n/** Symbol jedn\u00E9 geometrie (`point` | `line` | `polygon`) podle pravidla stylu. */\nexport function ogrSymbol(geometry, rule) {\n    if (!rule) return '';\n    if (geometry === 'point') {\n        const id = OGR_SYMBOLS[rule.symbol] ?? OGR_SYMBOLS.circle;\n        const outline = Number(rule.strokeWidth) > 0 ? `,o:${hex(rule.stroke)}` : '';\n        return `SYMBOL(id:\"ogr-sym-${id}\",c:${hex(rule.fill)}${outline},s:${px(rule.size, 8)})`;\n    }\n    if (geometry === 'line') {\n        const width = Number(rule.strokeWidth) || 1;\n        const pen = `PEN(c:${hex(rule.stroke)},w:${px(width, 1)}${dashPattern(rule.dash)})`;\n        // Obrys linie (casing) = \u0161ir\u0161\u00ED pero pod hlavn\u00EDm.\n        return rule.casing ? `PEN(c:${hex(rule.casing)},w:${px(width + 2, 3)});${pen}` : pen;\n    }\n    const brush = `BRUSH(fc:${hex(rule.fill, rule.fillOpacity ?? 1)})`;\n    const width = Number(rule.strokeWidth);\n    return width > 0 ? `${brush};PEN(c:${hex(rule.stroke)},w:${px(width, 1)}${dashPattern(rule.dash)})` : brush;\n}\n\n/** M\u00EDsto popisku bodu (labels.js) \u2192 kotva popisku OGR `p:` (1 = bod le\u017E\u00ED\n * vlevo dole od popisku, tj. popisek vpravo naho\u0159e; 5 = p\u0159es bod). */\nconst OGR_LABEL_ANCHORS = { tr: 1, t: 2, tl: 3, r: 4, c: 5, l: 6, br: 7, b: 8, bl: 9 };\n\nfunction labelTool(labels, geometry) {\n    if (!labels?.enabled || !labels.attribute) return '';\n    // `{atribut}` = text popisku se \u010Dte z atributu prvku (konvence OGR).\n    const halo = labels.halo ? `,o:${hex(labels.halo)}` : '';\n    const bold = labels.bold ? ',bo:1' : '';\n    let place = '';\n    if (geometry === 'point') {\n        const anchor = OGR_LABEL_ANCHORS[labels.position];\n        if (anchor) place += `,p:${anchor}`;\n        // \u00DAhel OGR je proti sm\u011Bru hodinov\u00FDch ru\u010Di\u010Dek; nato\u010Den\u00ED podle\n        // atributu styl OGR nezap\u00ED\u0161e.\n        const angle = Number(labels.rotation?.angle);\n        if (labels.rotation?.mode === 'angle' && angle) place += `,a:${-angle}`;\n    }\n    return `LABEL(t:{${labels.attribute}},s:${px(labels.size, 11)},c:${hex(labels.color)}${halo}${bold}${place})`;\n}\n\n/**\n * Symboly jedn\u00E9 t\u0159\u00EDdy stylu pro v\u0161echny druhy geometrie:\n * `{ point, line, polygon }` (\u0159et\u011Bzce stylu OGR; druh, pro kter\u00FD vrstva\n * pravidlo nem\u00E1, chyb\u00ED). `category` = kategorie / interval, null = z\u00E1klad.\n */\nexport function styleSet(style, category = null) {\n    const out = {};\n    GEOMETRIES.forEach((geometry) => {\n        const symbol = ogrSymbol(geometry, ruleForCategory(geometry, style.rules?.[geometry], category));\n        const label = labelTool(style.labels, geometry);\n        if (symbol) out[geometry] = [symbol, label].filter(Boolean).join(';');\n    });\n    return out;\n}\n\n/**\n * Pravidla stylu vrstvy pro p\u0159evodn\u00EDk: `{ attribute, classes, default }`.\n *\n * - jednoduch\u00FD styl: `default` = symboly cel\u00E9 vrstvy,\n * - kategorie: `classes[].value` + symboly; `default` jen s \u201EOther\u201C (prvek\n *   mimo kategorie se jinak v map\u011B nekresl\u00ED a styl nedostane),\n * - intervaly: `classes[].min/max` + symboly (posledn\u00ED interval v\u010Detn\u011B horn\u00ED\n *   meze, stejn\u011B jako v map\u011B).\n */\nexport function styleRules(style) {\n    if (style.mode === 'categorized') {\n        const { attribute, categories, other } = style.categorized || {};\n        if (attribute && (categories || []).length) {\n            return {\n                attribute,\n                classes: categories.map((cat) => ({ value: String(cat.value ?? ''), style: styleSet(style, cat) })),\n                default: other?.enabled ? styleSet(style, other) : null,\n            };\n        }\n    }\n    if (style.mode === 'graduated') {\n        const { attribute, classes } = style.graduated || {};\n        if (attribute && (classes || []).length) {\n            return {\n                attribute,\n                classes: classes.map((cls) => ({ min: Number(cls.min), max: Number(cls.max), style: styleSet(style, cls) })),\n                default: null,\n            };\n        }\n    }\n    return { attribute: null, classes: [], default: styleSet(style) };\n}\n\n/** Vrstvy souboru, ze kter\u00FDch se vrstva mapy kresl\u00ED (n\u00E1zvy ve zdrojov\u00FDch datech). */\nexport function sourceLayers(entry) {\n    const names = (entry.sublayers || []).map((sub) => sub.source_layer).filter(Boolean);\n    if (!names.length && entry.layerKey) names.push(entry.layerKey);\n    return Array.from(new Set(names));\n}\n\n/** Lze styl vrstvy ulo\u017Eit do dat? (vektor z workspace s vlastn\u00EDm stylem;\n * stejn\u00E1 podm\u00EDnka je u polo\u017Eky menu v layers.js) */\nexport function canSaveStyleToData(ctx, entry) {\n    return Boolean(ctx.bootstrap.isAuthenticated && !ctx.readOnly && entry && !entry.isGroup && entry.wms\n        && entry.itemId && entry.dataType === 'vector' && entry.style?.mode !== 'native');\n}\n\n/* ---------------------------------------------------------------------------\n * Text okna: co se s daty stane (podle odpov\u011Bdi serveru)\n * ------------------------------------------------------------------------- */\n\n/** Co form\u00E1t z nastaven\u00E9ho vzhledu neunese \u2014 kr\u00E1tce, jen to podstatn\u00E9. */\nconst NATIVE_LIMITS = {\n    kml: 'KML keeps the color and size of point symbols, the color and width of lines and the fill and outline of areas. Dashes, line casings and symbol outlines are left out, and labels always show the name of the feature.',\n    dxf: 'DXF keeps the colors, the width of lines and the fill of areas. Points are drawn as colored points, filled areas have no outline, and dashes, line casings and labels are left out.',\n    mapinfo: 'MapInfo keeps point symbols, the color and width of lines and the fill and outline of areas. Fill transparency, dashes, line casings and labels are left out.',\n};\nconst LIMITS_BY_FORMAT = {\n    kml: 'kml', kmz: 'kml', dxf: 'dxf', tab: 'mapinfo', mif_mid: 'mapinfo',\n};\n\n/**\n * Odstavce okna podle toho, kam se styl ulo\u017E\u00ED: `{ lead, note }` (prost\u00FD text).\n * `info` = odpov\u011B\u010F `GET \u2026/styled-copy/` (`storage`, `fallback`, `format`,\n * `format_label`, `original_label`).\n */\nexport function storageText(info) {\n    const format = info.format_label || 'the format of the data';\n    if (info.storage === 'native') {\n        const converted = info.fallback && info.original_label\n            ? `${info.original_label} cannot be written, so the copy is saved as ${format}. ` : '';\n        return {\n            lead: `${converted}The symbols this layer has in the map now are written as ${format} styles, `\n                + `so other programs that read ${format} draw it the same way. No extra attribute is added.`,\n            note: NATIVE_LIMITS[LIMITS_BY_FORMAT[info.format]] || '',\n        };\n    }\n    const attribute = `every feature gets an ${STYLE_FIELD} attribute with the symbol it has in the map now. `\n        + 'This map draws the copy from it, and so can other software that reads feature styles from such an attribute.';\n    if (info.fallback) {\n        const original = info.original_label || 'The format of these data';\n        return {\n            lead: `${original} can store neither styles nor extra attributes, so the copy is saved as ${format}: ${attribute}`,\n            note: '',\n        };\n    }\n    return {\n        lead: `The copy stays in ${format}. This format has no styles of its own, so ${attribute}`,\n        note: '',\n    };\n}\n\nfunction formatCredits(credits) {\n    if (!credits) return '';\n    const fmt = (v) => (Math.round(v * 10) / 10).toLocaleString('en-US');\n    const { expected, low, high } = credits;\n    const text = high - low >= 0.5 ? `${fmt(low)}\u2013${fmt(high)}` : fmt(expected);\n    return `${text} credit${expected === 1 && high - low < 0.5 ? '' : 's'}`;\n}\n\n/* ---------------------------------------------------------------------------\n * P\u0159evod, ulo\u017Een\u00ED do workspace, v\u00FDm\u011Bna vrstvy v map\u011B\n * ------------------------------------------------------------------------- */\n\nfunction creditsLink(ctx, url) {\n    const href = url || ctx.bootstrap.billing?.creditsUrl || ctx.bootstrap.billing?.pricingUrl;\n    return href ? `<a class=\"font-semibold underline\" href=\"${esc(href)}\" target=\"_blank\" rel=\"noopener\">Get credits</a>` : '';\n}\n\n/** POST bez `apiFetch`: nedostatek kredit\u016F (402) tady nen\u00ED \u201Emapa nejde\n * zobrazit\u201C, ale hl\u00E1\u0161ka v okn\u011B. */\nasync function startCopy(ctx, entry) {\n    const response = await fetch(`${ctx.bootstrap.apiBase}/items/${entry.itemId}/styled-copy/`, {\n        method: 'POST',\n        credentials: 'same-origin',\n        headers: { 'Content-Type': 'application/json', 'X-CSRFToken': getCookie('csrftoken') || '' },\n        body: JSON.stringify({ layers: sourceLayers(entry), rules: styleRules(entry.style), title: entry.title }),\n    });\n    let data = null;\n    try {\n        data = await response.json();\n    } catch {\n        data = null;\n    }\n    if (response.ok && data?.job_id) return data;\n    const error = new Error(data?.detail || data?.error || data?.message || 'The styled copy could not be started. Please try again later.');\n    if (response.status === 402) {\n        error.message = `${data?.detail || 'You don\u2019t have enough credits.'} `;\n        error.linkHtml = creditsLink(ctx, data?.plans?.[0]?.subscribe_url);\n    }\n    throw error;\n}\n\nasync function waitForItems(url) {\n    for (let tries = 0; tries < 90; tries += 1) {\n        // eslint-disable-next-line no-await-in-loop -- dotazov\u00E1n\u00ED na stav\n        const data = await apiFetch(url);\n        if (!data?.active) {\n            if (data?.error) throw new Error(data.error);\n            return data?.items || [];\n        }\n        // eslint-disable-next-line no-await-in-loop\n        await new Promise((resolve) => { setTimeout(resolve, POLL_MS); });\n    }\n    return [];\n}\n\n/** Nahrad\u00ED vrstvu v map\u011B jinou polo\u017Ekou workspace \u2014 na stejn\u00E9m m\u00EDst\u011B stromu,\n * se stejn\u00FDm n\u00E1zvem, viditelnost\u00ED, pr\u016Fhlednost\u00ED a m\u011B\u0159\u00EDtkov\u00FDm omezen\u00EDm. */\nexport async function replaceLayerItem(ctx, entry, itemId) {\n    const place = findEntryContainer(ctx.state, entry.uid);\n    const added = await addLayerByItemId(ctx, itemId);\n    if (!added || added.isGroup || !place) return added;\n    added.visible = entry.visible;\n    added.opacity = entry.opacity;\n    added.minZoom = entry.minZoom;\n    added.maxZoom = entry.maxZoom;\n    added.olLayer?.setOpacity(entry.opacity ?? 1);\n    renameLayer(ctx, added.uid, entry.title);\n    moveEntry(ctx, added.uid, place.group?.uid || null, place.index);\n    removeLayer(ctx, entry.uid);\n    ctx.state.dirty = true;\n    renderLayerTree(ctx);\n    return added;\n}\n\nconst running = new Set();\n\n/** Sleduje p\u0159evod, po n\u011Bm ulo\u017Een\u00ED do workspace, a nakonec vrstvu vym\u011Bn\u00ED. */\nfunction watch(ctx, uid, jobId, name, replace) {\n    running.add(uid);\n    const toast = showToast(`Saving a styled copy of \u201C${name}\u201D\u2026`, { tone: 'busy' });\n    let failures = 0;\n\n    function fail(text) {\n        running.delete(uid);\n        toast.update(text, { tone: 'error', timeout: 12000 });\n    }\n\n    async function finish(status) {\n        let items = [];\n        try {\n            toast.update('Reading the saved copy\u2026', { tone: 'busy' });\n            items = await waitForItems(`${ctx.bootstrap.apiBase}/workspace/batch/${status.batch_id}/status/`);\n        } catch (error) {\n            fail(`The styled copy of \u201C${name}\u201D was saved, but it could not be opened: ${saveErrorText(error)}`);\n            return;\n        }\n        running.delete(uid);\n        const item = items[0];\n        const current = findEntryByUid(ctx.state, uid);\n        if (!item?.id) {\n            toast.update(`The styled copy of \u201C${name}\u201D was saved \u2014 it will appear in your workspace in a moment.`, { tone: 'ok', timeout: 9000 });\n            return;\n        }\n        const title = item.title || name;\n        if (replace && current) {\n            try {\n                await replaceLayerItem(ctx, current, item.id);\n                toast.update(`Saved as \u201C${title}\u201D \u2014 the map now draws the copy with the style stored in the data.`, { tone: 'ok', timeout: 9000 });\n                return;\n            } catch {\n                /* kopie je ulo\u017Een\u00E1; vrstvu jde vym\u011Bnit ru\u010Dn\u011B */\n            }\n        }\n        toast.update(`Saved to your workspace as \u201C${title}\u201D.`, {\n            tone: 'ok',\n            timeout: 12000,\n            action: current ? { label: 'Use in this map', onClick: () => replaceLayerItem(ctx, current, item.id) } : undefined,\n        });\n    }\n\n    async function tick() {\n        let status;\n        try {\n            status = await apiFetch(`${ctx.bootstrap.apiBase}/styled-copy/${jobId}/`);\n            failures = 0;\n        } catch {\n            failures += 1;\n            if (failures >= 8) {\n                fail(`The styled copy of \u201C${name}\u201D could not be followed. It may still finish \u2014 look into your workspace later.`);\n                return;\n            }\n            setTimeout(tick, POLL_MS * 2);\n            return;\n        }\n        if (!status.done) {\n            toast.update(`Saving a styled copy of \u201C${name}\u201D\u2026 ${status.elapsed_s} s`, { tone: 'busy' });\n            setTimeout(tick, POLL_MS);\n            return;\n        }\n        if (!status.ok) {\n            fail(`The styled copy of \u201C${name}\u201D could not be saved: ${status.error || 'unknown error'}`);\n            return;\n        }\n        await finish(status);\n    }\n    setTimeout(tick, POLL_MS);\n}\n\n/* ---------------------------------------------------------------------------\n * Okno (potvrzen\u00ED \u2014 do dat se zapisuje jen na v\u00FDslovn\u00E9 p\u0159\u00E1n\u00ED)\n * ------------------------------------------------------------------------- */\n\nlet dialogEl = null;\n\nfunction closeDialog() {\n    if (dialogEl) {\n        dialogEl.remove();\n        dialogEl = null;\n    }\n}\n\ndocument.addEventListener('keydown', (event) => {\n    if (event.key === 'Escape' && dialogEl) closeDialog();\n});\n\nfunction esc(value) {\n    return String(value ?? '').replace(/[&<>\"']/g, (c) => ({\n        '&': '&amp;', '<': '&lt;', '>': '&gt;', '\"': '&quot;', \"'\": '&#39;',\n    })[c]);\n}\n\nfunction saveErrorText(error) {\n    const raw = String(error?.message || '');\n    const jsonStart = raw.indexOf('{');\n    if (jsonStart !== -1) {\n        try {\n            const data = JSON.parse(raw.slice(jsonStart));\n            if (data?.error) return String(data.error);\n            if (data?.detail) return String(data.detail);\n        } catch {\n            /* t\u011Blo nen\u00ED JSON */\n        }\n    }\n    if (error?.status === 413) return 'Your storage is full.';\n    return raw.replace(/<[^>]*>/g, ' ').slice(0, 260) || 'Unknown error.';\n}\n\nfunction openDialog(ctx, entry) {\n    closeDialog();\n    const overlay = document.createElement('div');\n    overlay.className = 'fixed inset-0 z-50 flex items-center justify-center bg-slate-900/50 p-4';\n    overlay.innerHTML = `\n        <div class=\"w-full max-w-md rounded-xl border border-slate-200 bg-white shadow-xl\" role=\"dialog\" aria-modal=\"true\" aria-labelledby=\"map-style-export-title\">\n            <div class=\"flex items-center justify-between border-b border-slate-100 px-4 py-3\">\n                <h3 id=\"map-style-export-title\" class=\"text-sm font-semibold text-slate-800\">Save the style into the data</h3>\n                <button type=\"button\" data-role=\"close\" aria-label=\"Close\" class=\"rounded p-1 text-slate-400 hover:bg-slate-100 hover:text-slate-600\">\u2715</button>\n            </div>\n            <div class=\"max-h-[70vh] space-y-3 overflow-y-auto px-4 py-4 text-sm leading-relaxed text-slate-700\">\n                <div data-role=\"offer\">\n                    <span class=\"map-spinner mr-1.5 align-[-2px]\" aria-hidden=\"true\"></span>Checking how the style can be stored in these data\u2026\n                </div>\n                <label data-role=\"replace-row\" class=\"hidden items-start gap-x-2\">\n                    <input type=\"checkbox\" data-role=\"replace\" checked class=\"mt-0.5 h-3.5 w-3.5 rounded border-slate-300 text-brand-600 focus:ring-brand-500\">\n                    <span>Use the saved copy in this map instead of the current layer</span>\n                </label>\n                <p data-role=\"error\" class=\"hidden text-xs text-red-600\"></p>\n            </div>\n            <div class=\"flex items-center justify-end gap-x-2 border-t border-slate-100 px-4 py-3\">\n                <button type=\"button\" data-role=\"cancel\" class=\"rounded-lg border border-slate-200 bg-white px-3 py-1.5 text-sm font-medium text-slate-700 hover:bg-slate-50\">Cancel</button>\n                <button type=\"button\" data-role=\"save\" disabled class=\"btn-primary !px-3 !py-1.5 text-sm disabled:cursor-not-allowed disabled:opacity-50\">Save a styled copy</button>\n            </div>\n        </div>`;\n    document.body.appendChild(overlay);\n    dialogEl = overlay;\n    const q = (role) => overlay.querySelector(`[data-role=\"${role}\"]`);\n    const offer = q('offer');\n    const errorEl = q('error');\n    const save = q('save');\n    q('close').addEventListener('click', closeDialog);\n    q('cancel').addEventListener('click', closeDialog);\n    overlay.addEventListener('mousedown', (event) => { if (event.target === overlay) closeDialog(); });\n\n    function showError(text, linkHtml = '') {\n        errorEl.innerHTML = `${esc(text)}${linkHtml}`;\n        errorEl.classList.remove('hidden');\n    }\n\n    if (running.has(entry.uid)) {\n        offer.textContent = 'A styled copy of this layer is being saved \u2014 it will appear in your workspace when it is ready.';\n        q('cancel').textContent = 'Close';\n        return;\n    }\n\n    function showOffer(info) {\n        if (dialogEl !== overlay) return;\n        if (!info.eligible) {\n            offer.textContent = info.message || 'The style cannot be saved into these data.';\n            q('cancel').textContent = 'Close';\n            return;\n        }\n        const text = storageText(info);\n        const cost = info.cost || {};\n        const price = formatCredits(info.credits);\n        offer.innerHTML = `\n            <div class=\"space-y-3\">\n                <p>A copy of <b>${esc(entry.title)}</b> will be saved to your workspace as\n                   <span class=\"font-mono text-xs\">${esc(info.filename)}</span>. Your original file is not changed.</p>\n                <p>${esc(text.lead)}</p>\n                ${text.note ? `<p class=\"text-xs text-slate-500\">${esc(text.note)}</p>` : ''}\n                <p class=\"text-xs text-slate-500\">The copy is written by the Converter${price ? ` \u2014 cost: <b class=\"text-slate-700\">${esc(price)}</b>` : ''}${cost.note ? ` (${esc(cost.note)})` : ''}.</p>\n            </div>`;\n        q('replace-row').classList.replace('hidden', 'flex');\n        // Bez kredit\u016F kopii spustit nejde \u2014 cena je ale vid\u011Bt i tak.\n        const affordable = cost.covered !== false;\n        if (!affordable) showError('You don\u2019t have enough credits for this copy. ', creditsLink(ctx));\n        save.disabled = !affordable;\n        save.onclick = async () => {\n            save.disabled = true;\n            errorEl.classList.add('hidden');\n            const replace = q('replace').checked;\n            try {\n                const job = await startCopy(ctx, entry);\n                closeDialog();\n                watch(ctx, entry.uid, job.job_id, entry.title, replace);\n            } catch (error) {\n                save.disabled = false;\n                showError(error.message, error.linkHtml || '');\n            }\n        };\n    }\n\n    apiFetch(`${ctx.bootstrap.apiBase}/items/${entry.itemId}/styled-copy/?title=${encodeURIComponent(entry.title || '')}`)\n        .then(showOffer)\n        .catch(() => {\n            if (dialogEl !== overlay) return;\n            offer.textContent = 'It could not be checked right now how the style can be stored. Please try again later.';\n            q('cancel').textContent = 'Close';\n        });\n}\n\nexport function initStyleExport(ctx) {\n    on('layers:save-style-to-data', ({ uid }) => {\n        const entry = findEntryByUid(ctx.state, uid);\n        if (canSaveStyleToData(ctx, entry)) openDialog(ctx, entry);\n    });\n}\n", "/**\n * mobile.js \u2014 ovl\u00E1d\u00E1n\u00ED mapy na telefonu.\n *\n * Do li\u0161ty mapy se na telefon vejde jen n\u00E1zev, Add data a Save; v\u0161echno\n * ostatn\u00ED (Open, Save as, Share, m\u011B\u0159en\u00ED, kreslen\u00ED, obr\u00E1zek mapy, podkladov\u00E1\n * mapa, odkazy webu) je v nab\u00EDdce \u201EMore\u201C (`#map-mobile-menu`). Polo\u017Eky nab\u00EDdky\n * ned\u011Blaj\u00ED nic vlastn\u00EDho \u2014 kliknou na tla\u010D\u00EDtko z desktopov\u00E9 li\u0161ty\n * (`data-proxy=\"#id\"`), tak\u017Ee se ob\u011B cesty nem\u016F\u017Eou rozej\u00EDt. Polo\u017Eka, jej\u00ED\u017E\n * tla\u010D\u00EDtko je zrovna skryt\u00E9 nebo vypnut\u00E9 (Share u neulo\u017Een\u00E9 mapy, Save as\n * bez p\u0159ihl\u00E1\u0161en\u00ED\u2026), se v nab\u00EDdce neuk\u00E1\u017Ee.\n *\n * Na telefonu se nav\u00EDc po akci, kter\u00E1 m\u00E1 b\u00FDt vid\u011Bt v map\u011B (Zoom to layer,\n * tabulka atribut\u016F\u2026), zav\u0159e v\u00FDsuvn\u00FD panel vrstev \u2014 viz `ui:show-map`.\n */\n\n/** \u0160\u00ED\u0159ka, pod kterou plat\u00ED telefonn\u00ED rozlo\u017Een\u00ED (Tailwind `md`). */\nconst MOBILE_QUERY = '(max-width: 767px)';\n\nexport function isMobileLayout() {\n    return window.matchMedia(MOBILE_QUERY).matches;\n}\n\n/** D\u00E1 se na c\u00EDlov\u00E9 tla\u010D\u00EDtko pr\u00E1v\u011B kliknout? Tla\u010D\u00EDtka desktopov\u00E9 li\u0161ty jsou na\n * telefonu skryt\u00E1 obalem (`.map-desktop-only`), proto se nehodnot\u00ED viditelnost\n * na obrazovce, ale stav samotn\u00E9ho tla\u010D\u00EDtka. */\nfunction isAvailable(target) {\n    if (!target || target.disabled) return false;\n    return !target.classList.contains('hidden') && !target.hidden;\n}\n\nexport function initMobileMenu() {\n    const button = document.getElementById('map-btn-mobile-menu');\n    const menu = document.getElementById('map-mobile-menu');\n    if (!button || !menu) return;\n\n    function close() {\n        menu.classList.add('hidden');\n        button.setAttribute('aria-expanded', 'false');\n    }\n\n    function open() {\n        menu.querySelectorAll('[data-proxy]').forEach((item) => {\n            item.hidden = !isAvailable(document.querySelector(item.dataset.proxy));\n        });\n        menu.classList.remove('hidden');\n        button.setAttribute('aria-expanded', 'true');\n    }\n\n    button.addEventListener('click', (event) => {\n        event.stopPropagation();\n        if (menu.classList.contains('hidden')) open(); else close();\n    });\n\n    menu.addEventListener('click', (event) => {\n        const item = event.target.closest('[data-proxy]');\n        if (item) {\n            close();\n            document.querySelector(item.dataset.proxy)?.click();\n            return;\n        }\n        // Volba podkladov\u00E9 mapy nebo odkaz \u2014 nab\u00EDdka se taky zav\u0159e.\n        if (event.target.closest('button, a')) close();\n    });\n\n    document.addEventListener('click', (event) => {\n        if (!menu.classList.contains('hidden') && !menu.contains(event.target)) close();\n    });\n    document.addEventListener('keydown', (event) => {\n        if (event.key === 'Escape') close();\n    });\n    // Oto\u010Den\u00ED telefonu / zv\u011Bt\u0161en\u00ED okna nad telefonn\u00ED \u0161\u00ED\u0159ku.\n    window.matchMedia(MOBILE_QUERY).addEventListener('change', close);\n}\n", "/**\n * properties.js \u2014 modal \"Layer properties\" (kebab menu vrstvy ve stromu).\n * Zobrazuje titulek (editace), informace o datech vrstvy, kter\u00E9 u\u017Eivateli\n * n\u011Bco \u0159eknou (p\u016Fvodn\u00ED soubor, form\u00E1t, velikost, po\u010Det prvk\u016F, atributy,\n * sou\u0159adnicov\u00FD syst\u00E9m, rozsah \u2014 ne technick\u00E9 ID polo\u017Eky), pr\u016Fhlednost\n * a m\u011B\u0159\u00EDtkov\u00E1 omezen\u00ED minZoom/maxZoom. Zm\u011Bny se aplikuj\u00ED pr\u016Fb\u011B\u017En\u011B;\n * zav\u0159en\u00ED = OK.\n *\n * Modal se stav\u00ED dynamicky v JS (stejn\u00FD princip jako kebab menu v layers.js) \u2014\n * nez\u00E1vis\u00ED na Preline overlay, zav\u00EDr\u00E1 se tla\u010D\u00EDtkem, klikem na pozad\u00ED i Escape.\n */\nimport { on } from './utils.js';\nimport { findEntryByUid } from './state.js';\nimport {\n    renameLayer,\n    setLayerOpacity,\n    setLayerZoomLimits,\n    renderLayerTree,\n} from './layers.js';\n\n/** Pr\u00E1v\u011B otev\u0159en\u00FD modal (nejv\u00FD\u0161e jeden). */\nlet openModalEl = null;\n\nfunction closeModal() {\n    if (openModalEl) {\n        openModalEl.remove();\n        openModalEl = null;\n    }\n}\n\ndocument.addEventListener('keydown', (event) => {\n    if (event.key === 'Escape' && openModalEl) closeModal();\n});\n\nfunction esc(value) {\n    return String(value ?? '')\n        .replace(/&/g, '&amp;')\n        .replace(/</g, '&lt;')\n        .replace(/>/g, '&gt;')\n        .replace(/\"/g, '&quot;');\n}\n\n/** Velikost souboru \u010Diteln\u011B (1 536 \u2192 \"1.5 kB\"). */\nfunction formatBytes(bytes) {\n    const value = Number(bytes);\n    if (!Number.isFinite(value) || value <= 0) return '';\n    const units = ['B', 'kB', 'MB', 'GB', 'TB'];\n    const exponent = Math.min(units.length - 1, Math.floor(Math.log(value) / Math.log(1024)));\n    const scaled = value / (1024 ** exponent);\n    return `${scaled >= 100 || exponent === 0 ? Math.round(scaled) : scaled.toFixed(1)} ${units[exponent]}`;\n}\n\nfunction formatCount(value) {\n    return Number.isFinite(value) ? Number(value).toLocaleString('en-US') : '';\n}\n\nfunction formatDate(iso) {\n    const date = iso ? new Date(iso) : null;\n    if (!date || Number.isNaN(date.getTime())) return '';\n    return date.toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' });\n}\n\n/** \u010Citeln\u00FD n\u00E1zev geometrie vrstvy (\"Polygons\", \"Lines and points\"\u2026). */\nfunction geometryLabel(entry) {\n    const names = { point: 'points', line: 'lines', polygon: 'polygons' };\n    const list = (entry.geometryTypes || []).map((g) => names[g]).filter(Boolean);\n    if (list.length === 0) return '';\n    const text = list.length === 1 ? list[0] : `${list.slice(0, -1).join(', ')} and ${list[list.length - 1]}`;\n    return text.charAt(0).toUpperCase() + text.slice(1);\n}\n\n/** Druh vrstvy jednou v\u011Btou. */\nfunction typeLabel(entry) {\n    const labels = {\n        drawing: 'Drawing made in this map',\n        wms: 'WMS service',\n        xyz: 'XYZ tile service',\n        wmts: 'WMTS tile service',\n        local: 'Pasted or linked data',\n    };\n    if (labels[entry.dataType]) return labels[entry.dataType];\n    if (entry.dataType === 'raster') return 'Raster';\n    return `Vector${geometryLabel(entry) ? ` \u00B7 ${geometryLabel(entry).toLowerCase()}` : ''}`;\n}\n\n/** HTML \u0159\u00E1dek \"\u0161t\u00EDtek: hodnota\"; pr\u00E1zdn\u00E1 hodnota \u0159\u00E1dek vynech\u00E1. */\nfunction metaRow(label, value, { html = false, title = '' } = {}) {\n    if (value === null || value === undefined || value === '') return '';\n    const text = html ? value : esc(value);\n    return `<div class=\"flex justify-between gap-x-3 py-0.5\">\n        <dt class=\"flex-none text-slate-500\">${esc(label)}</dt>\n        <dd class=\"min-w-0 break-words text-right font-medium text-slate-700\" title=\"${esc(title || (html ? '' : value))}\">${text}</dd>\n    </div>`;\n}\n\n/** P\u00E1sma rastru stru\u010Dn\u011B: \"3 \u00D7 Byte\" / \"6 \u00D7 UInt16\" / \"Float32\". */\nfunction bandsLabel(entry) {\n    const bands = entry.bands || [];\n    if (bands.length === 0) return '';\n    const types = Array.from(new Set(bands.map((b) => b.data_type || b.dataType).filter(Boolean)));\n    const type = types.length === 1 ? types[0] : (types.length ? 'mixed types' : '');\n    return bands.length === 1 ? (type || '1 band') : `${bands.length} bands${type ? ` \u00D7 ${type}` : ''}`;\n}\n\n/** Sou\u0159adnicov\u00FD syst\u00E9m dat (k\u00F3d + n\u00E1zev), jak ho zn\u00E1 workspace / Mapserver. */\nfunction crsLabel(entry) {\n    const crs = entry.source?.crs?.[0];\n    if (crs?.code) return crs.name && crs.name !== crs.code ? `${crs.code} \u2014 ${crs.name}` : crs.code;\n    return entry.raster?.crs || '';\n}\n\n/** Sekce \"Data\" \u2014 co u\u017Eivatel o datech vrstvy pot\u0159ebuje v\u011Bd\u011Bt: p\u016Fvodn\u00ED soubor,\n * form\u00E1t, velikost, po\u010Dty, sou\u0159adnicov\u00FD syst\u00E9m, rozsah. Technick\u00E9 ID polo\u017Eky\n * workspace sem nepat\u0159\u00ED; k polo\u017Ece vede odkaz. */\nfunction dataRows(entry) {\n    const rows = [];\n    const { source } = entry;\n    if (entry.dataType === 'vector' || entry.dataType === 'raster') {\n        if (source) {\n            rows.push(metaRow('File', source.name));\n            // Vrstva souboru s v\u00EDce vrstvami (GPKG, KML\u2026).\n            if (entry.layerKey !== null && entry.layerKey !== undefined && entry.dataType === 'vector') {\n                rows.push(metaRow('Layer in the file', entry.layerKey));\n            }\n            if (source.archive) rows.push(metaRow('From archive', source.archive));\n            rows.push(metaRow('Format', source.format));\n            rows.push(metaRow('File size', formatBytes(source.size_bytes)));\n        }\n        if (entry.dataType === 'vector') {\n            const sublayers = entry.sublayers || [];\n            const counts = sublayers.map((sub) => sub.feature_count).filter(Number.isFinite);\n            if (counts.length) rows.push(metaRow('Features', formatCount(counts.reduce((a, b) => a + b, 0))));\n            rows.push(metaRow('Geometry', geometryLabel(entry)));\n            const attributes = Array.from(new Set(sublayers.flatMap((sub) => (sub.attributes || []).map((a) => a.name))));\n            if (attributes.length) {\n                const shown = attributes.slice(0, 12).join(', ');\n                const more = attributes.length > 12 ? ` +${attributes.length - 12} more` : '';\n                rows.push(metaRow(`Attributes (${attributes.length})`, `${shown}${more}`, { title: attributes.join(', ') }));\n            }\n        } else {\n            const size = entry.raster?.size;\n            if (Array.isArray(size) && size.length === 2) rows.push(metaRow('Size', `${formatCount(size[0])} \u00D7 ${formatCount(size[1])} px`));\n            rows.push(metaRow('Bands', bandsLabel(entry)));\n        }\n        rows.push(metaRow('Coordinate system', crsLabel(entry)));\n        if (source?.created_at) rows.push(metaRow('Uploaded', formatDate(source.created_at)));\n    } else if (entry.dataType === 'wms') {\n        rows.push(metaRow('Service', entry.externalWms?.url));\n        rows.push(metaRow('Layer', entry.externalWms?.layerName));\n        rows.push(metaRow('Feature info', entry.externalWms?.queryable ? 'Available' : 'Not available'));\n    } else if (entry.dataType === 'xyz' || entry.dataType === 'wmts') {\n        rows.push(metaRow('Address', typeof entry.toConfig === 'function' ? entry.toConfig().url : ''));\n    } else if (entry.dataType === 'local') {\n        rows.push(metaRow('Source', entry.sourceUrl || 'Pasted into the map'));\n    }\n    if (entry.dataType === 'local' || entry.dataType === 'drawing') {\n        const count = entry.olSource?.getFeatures?.().length;\n        if (Number.isFinite(count)) rows.push(metaRow('Features', formatCount(count)));\n    }\n    if (entry.bbox) {\n        const [minx, miny, maxx, maxy] = entry.bbox.map((v) => Number(v).toFixed(4));\n        rows.push(metaRow('Extent (lon, lat)', `${minx}, ${miny} \u2013 ${maxx}, ${maxy}`));\n    }\n    return rows.join('');\n}\n\n/** Otev\u0159e modal vlastnost\u00ED pro danou vrstvu. */\nfunction openProperties(ctx, uid) {\n    const entry = findEntryByUid(ctx.state, uid);\n    if (!entry || entry.isGroup) return;\n    closeModal();\n\n    const overlay = document.createElement('div');\n    overlay.className = 'fixed inset-0 z-50 flex items-center justify-center bg-slate-900/50 p-4';\n    overlay.innerHTML = `\n        <div class=\"w-full max-w-md rounded-xl border border-slate-200 bg-white shadow-xl\">\n            <div class=\"flex items-center justify-between border-b border-slate-100 px-4 py-3\">\n                <h3 class=\"text-sm font-semibold text-slate-800\">Layer properties</h3>\n                <button type=\"button\" data-role=\"close\" class=\"rounded p-1 text-slate-400 hover:bg-slate-100 hover:text-slate-600\">\u2715</button>\n            </div>\n            <div class=\"max-h-[70vh] space-y-4 overflow-y-auto px-4 py-4 text-sm\">\n                <label class=\"block\">\n                    <span class=\"mb-1 block text-xs font-medium text-slate-500\">Title</span>\n                    <input type=\"text\" data-role=\"title\" value=\"${esc(entry.title)}\"\n                           class=\"w-full rounded-lg border-slate-200 text-sm focus:border-brand-500 focus:ring-brand-500\">\n                </label>\n                <dl class=\"rounded-lg bg-slate-50 px-3 py-2 text-xs\">\n                    ${metaRow('Type', typeLabel(entry))}\n                    ${dataRows(entry)}\n                </dl>\n                ${entry.source?.url && ctx.bootstrap.isAuthenticated ? `\n                <a href=\"${esc(entry.source.url)}\" target=\"_blank\" rel=\"noopener\"\n                   class=\"-mt-2 inline-flex items-center gap-x-1 text-xs font-medium text-brand-600 hover:underline\">\n                    Open in Data workspace\n                    <svg class=\"h-3 w-3\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" aria-hidden=\"true\"><path d=\"M15 3h6v6M10 14 21 3M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6\"/></svg>\n                </a>` : ''}\n                <label class=\"block\">\n                    <span class=\"mb-1 block text-xs font-medium text-slate-500\">Opacity</span>\n                    <div class=\"flex items-center gap-x-2\">\n                        <input type=\"range\" min=\"0\" max=\"100\" value=\"${Math.round(entry.opacity * 100)}\"\n                               data-role=\"opacity\" class=\"h-1.5 flex-1 cursor-pointer accent-brand-600\">\n                        <span data-role=\"opacity-value\" class=\"w-10 text-right text-xs tabular-nums text-slate-500\">${Math.round(entry.opacity * 100)}%</span>\n                    </div>\n                </label>\n                <div>\n                    <span class=\"mb-1 block text-xs font-medium text-slate-500\">Show only between zoom levels (0\u201328, empty = always)</span>\n                    <div class=\"flex items-center gap-x-2\">\n                        <input type=\"number\" min=\"0\" max=\"28\" step=\"1\" placeholder=\"No limit\"\n                               value=\"${Number.isFinite(entry.minZoom) ? entry.minZoom : ''}\"\n                               data-role=\"min-zoom\" class=\"w-24 rounded-lg border-slate-200 text-sm focus:border-brand-500 focus:ring-brand-500\">\n                        <span class=\"text-xs text-slate-400\">Min zoom</span>\n                        <input type=\"number\" min=\"0\" max=\"28\" step=\"1\" placeholder=\"No limit\"\n                               value=\"${Number.isFinite(entry.maxZoom) ? entry.maxZoom : ''}\"\n                               data-role=\"max-zoom\" class=\"w-24 rounded-lg border-slate-200 text-sm focus:border-brand-500 focus:ring-brand-500\">\n                        <span class=\"text-xs text-slate-400\">Max zoom</span>\n                    </div>\n                </div>\n            </div>\n            <div class=\"flex justify-end border-t border-slate-100 px-4 py-3\">\n                <button type=\"button\" data-role=\"ok\" class=\"rounded-lg bg-brand-600 px-4 py-1.5 text-sm font-medium text-white hover:bg-brand-700\">OK</button>\n            </div>\n        </div>\n    `;\n\n    // Zav\u0159en\u00ED: OK, k\u0159\u00ED\u017Eek, klik na pozad\u00ED (zm\u011Bny u\u017E jsou aplikovan\u00E9 pr\u016Fb\u011B\u017En\u011B).\n    const finish = () => {\n        renderLayerTree(ctx); // prom\u00EDtne p\u0159\u00EDpadn\u00E9 p\u0159ejmenov\u00E1n\u00ED do stromu\n        closeModal();\n    };\n    overlay.addEventListener('click', (e) => {\n        if (e.target === overlay) finish();\n    });\n    overlay.querySelector('[data-role=\"close\"]').addEventListener('click', finish);\n    overlay.querySelector('[data-role=\"ok\"]').addEventListener('click', finish);\n\n    overlay.querySelector('[data-role=\"title\"]').addEventListener('input', (e) => {\n        renameLayer(ctx, entry.uid, e.target.value.trim() || entry.title);\n        ctx.state.dirty = true;\n    });\n    const opacityValue = overlay.querySelector('[data-role=\"opacity-value\"]');\n    overlay.querySelector('[data-role=\"opacity\"]').addEventListener('input', (e) => {\n        const value = Number(e.target.value);\n        opacityValue.textContent = `${value}%`;\n        setLayerOpacity(ctx, entry.uid, value / 100);\n        ctx.state.dirty = true;\n    });\n\n    // Min/max zoom \u2014 pr\u00E1zdn\u00E9 pole = bez limitu (null).\n    const minInput = overlay.querySelector('[data-role=\"min-zoom\"]');\n    const maxInput = overlay.querySelector('[data-role=\"max-zoom\"]');\n    const applyZoomInputs = () => {\n        const minVal = minInput.value === '' ? null : Number(minInput.value);\n        const maxVal = maxInput.value === '' ? null : Number(maxInput.value);\n        setLayerZoomLimits(\n            ctx,\n            entry.uid,\n            Number.isFinite(minVal) ? minVal : null,\n            Number.isFinite(maxVal) ? maxVal : null,\n        );\n    };\n    minInput.addEventListener('input', applyZoomInputs);\n    maxInput.addEventListener('input', applyZoomInputs);\n\n    document.body.appendChild(overlay);\n    openModalEl = overlay;\n}\n\n/** Jednor\u00E1zov\u00E1 inicializace (main.js) \u2014 poslouch\u00E1 ud\u00E1lost z kebab menu. */\nexport function initProperties(ctx) {\n    on('layers:open-properties', ({ uid }) => openProperties(ctx, uid));\n    // Odebr\u00E1n\u00ED vrstvy s otev\u0159en\u00FDm modalem \u2014 zav\u0159\u00EDt (vrstva u\u017E neexistuje).\n    on('layers:changed', ({ reason }) => {\n        if ((reason === 'remove' || reason === 'remove-group') && openModalEl) closeModal();\n    });\n}\n", "/**\n * wfs-values.js \u2014 XML mapov\u00E9 slu\u017Eby bez DOM (testy v Node): t\u011Blo WFS 2.0\n * GetFeature pro POST, hodnoty z GetPropertyValue (`wfs:ValueCollection`),\n * prvky z GetFeature v GML (`wfs:FeatureCollection`) a text v\u00FDjimky OWS\n * (`ows:ExceptionText`).\n *\n * GetPropertyValue vrac\u00ED jen hodnoty jednoho atributu \u2014 na rozd\u00EDl od\n * GetFeature bez geometrie. Pro klasifikaci tak sta\u010D\u00ED des\u00EDtky kB i u souboru,\n * kde by GetFeature s cel\u00FDmi polygony p\u0159ekro\u010Dil limit odpov\u011Bdi slu\u017Eby\n * (6 MB, HTTP 413 `response_too_large`).\n */\n\nexport function xmlEscape(value) {\n    return String(value)\n        .replace(/&/g, '&amp;')\n        .replace(/</g, '&lt;')\n        .replace(/>/g, '&gt;')\n        .replace(/\"/g, '&quot;');\n}\n\n/** Sestav\u00ED WFS 2.0 GetFeature XML t\u011Blo (POST varianta) \u2014 `filterXml` je\n * hotov\u00FD fragment `<ogc:Filter>...</ogc:Filter>` (nebo `<ogc:And>`/apod.).\n * `params` je stejn\u00FD objekt jako pro GET (TYPENAMES/COUNT/STARTINDEX/\n * SRSNAME/PROPERTYNAME/RESULTTYPE/OUTPUTFORMAT/SORTBY), aby volaj\u00EDc\u00ED k\u00F3d\n * nemusel udr\u017Eovat dv\u011B sady n\u00E1zv\u016F parametr\u016F. */\nexport function buildGetFeatureXml(params, filterXml) {\n    const {\n        TYPENAMES: typenames, COUNT: count, STARTINDEX: startIndex, SRSNAME: srsName, PROPERTYNAME: propertyName, RESULTTYPE: resultType,\n        OUTPUTFORMAT: outputFormat, SORTBY: sortBy,\n    } = params;\n    const attrs = [\n        'service=\"WFS\"',\n        'version=\"2.0.0\"',\n        resultType ? `resultType=\"${resultType}\"` : `outputFormat=\"${xmlEscape(outputFormat || 'geojson')}\"`,\n        count != null ? `count=\"${count}\"` : '',\n        startIndex != null ? `startIndex=\"${startIndex}\"` : '',\n    ].filter(Boolean).join(' ');\n    const propertyNames = (propertyName ? String(propertyName).split(',') : [])\n        .map((p) => `<wfs:PropertyName>${xmlEscape(p)}</wfs:PropertyName>`)\n        .join('');\n    // \u0158azen\u00ED mus\u00ED b\u00FDt v t\u011Ble: SORTBY v URL slu\u017Eba u POST ne\u010Dte (tabulka\n    // s filtrem nebo hled\u00E1n\u00EDm se d\u0159\u00EDv ne\u0159adila).\n    const sortProperties = (sortBy ? String(sortBy).split(',') : [])\n        .map((part) => /^\\s*(.+?)(?:\\s+(ASC|DESC))?\\s*$/i.exec(part))\n        .filter(Boolean)\n        .map(([, name, dir]) => `<fes:SortProperty><fes:ValueReference>${xmlEscape(name)}</fes:ValueReference>`\n            + `<fes:SortOrder>${(dir || 'ASC').toUpperCase()}</fes:SortOrder></fes:SortProperty>`)\n        .join('');\n    const sortXml = sortProperties\n        ? `<fes:SortBy xmlns:fes=\"http://www.opengis.net/fes/2.0\">${sortProperties}</fes:SortBy>`\n        : '';\n    return `<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<wfs:GetFeature ${attrs}\n    xmlns:wfs=\"http://www.opengis.net/wfs/2.0\"\n    xmlns:ogc=\"http://www.opengis.net/ogc\">\n  <wfs:Query typeNames=\"${xmlEscape(typenames)}\"${srsName ? ` srsName=\"${xmlEscape(srsName)}\"` : ''}>\n    ${propertyNames}\n    ${filterXml || ''}\n    ${sortXml}\n  </wfs:Query>\n</wfs:GetFeature>`;\n}\n\nconst ENTITIES = { amp: '&', lt: '<', gt: '>', quot: '\"', apos: \"'\" };\n\nfunction decodeXml(text) {\n    return text.replace(/&(#x[0-9a-f]+|#\\d+|[a-z]+);/gi, (match, code) => {\n        if (code[0] === '#') {\n            const point = code[1] === 'x' || code[1] === 'X' ? parseInt(code.slice(2), 16) : parseInt(code.slice(1), 10);\n            return Number.isFinite(point) ? String.fromCodePoint(point) : match;\n        }\n        return ENTITIES[code.toLowerCase()] ?? match;\n    });\n}\n\n/**\n * Hodnoty z `wfs:ValueCollection` v po\u0159ad\u00ED odpov\u011Bdi \u2014 jedna na `wfs:member`.\n * Pr\u00E1zdn\u00FD element (NULL i pr\u00E1zdn\u00FD text \u2014 slu\u017Eba je nerozli\u0161uje) je `null`.\n * Hodnoty jsou text, i u \u010D\u00EDseln\u00FDch atribut\u016F (\u201E2\u201C, \u201E1e-07\u201C).\n */\nexport function parseValueCollection(xmlText) {\n    const values = [];\n    const text = String(xmlText || '');\n    const memberRe = /<wfs:member\\b[^>]*>([\\s\\S]*?)<\\/wfs:member>/g;\n    let member;\n    while ((member = memberRe.exec(text)) !== null) {\n        const inner = member[1].replace(/<!--[\\s\\S]*?-->/g, '');\n        const element = /<([\\w.:-]+)\\b[^>]*?(\\/>|>([\\s\\S]*?)<\\/\\1>)/.exec(inner);\n        if (!element || element[2] === '/>') {\n            values.push(null);\n            continue;\n        }\n        const raw = element[3] ?? '';\n        const cdata = /^<!\\[CDATA\\[([\\s\\S]*)\\]\\]>$/.exec(raw);\n        const value = cdata ? cdata[1] : decodeXml(raw);\n        values.push(value === '' ? null : value);\n    }\n    return values;\n}\n\n/** Text v\u00FDjimky OWS z odpov\u011Bdi slu\u017Eby (`ows:ExceptionText`), jinak `null`. */\nexport function owsExceptionText(xmlText) {\n    const match = /<(?:ows:)?ExceptionText>([\\s\\S]*?)<\\/(?:ows:)?ExceptionText>/.exec(String(xmlText || ''));\n    return match ? decodeXml(match[1]).trim() || null : null;\n}\n\n/**\n * Prvky z odpov\u011Bdi GetFeature v GML (`wfs:FeatureCollection`) jako objekty\n * atribut\u016F `{n\u00E1zev: text | null}` v po\u0159ad\u00ED odpov\u011Bdi. \u010Cte se tolerantn\u011B, bez\n * XML parseru: MapServer jm\u00E9na atribut\u016F do zna\u010Dek p\u00ED\u0161e tak, jak jsou, i kdy\u017E\n * nejsou platn\u00FDm XML (`<ms:Shape Leng>`, `<ms:n\u00E1zev>` \u2014 s varov\u00E1n\u00EDm\n * v koment\u00E1\u0159i), a DOMParser by takovou odpov\u011B\u010F odm\u00EDtl. Geometrie (pokud by\n * v odpov\u011Bdi byla) se p\u0159esko\u010D\u00ED.\n */\nexport function parseFeatureCollection(xmlText) {\n    const features = [];\n    const text = String(xmlText || '');\n    const memberRe = /<wfs:member\\b[^>]*>([\\s\\S]*?)<\\/wfs:member>/g;\n    let member;\n    while ((member = memberRe.exec(text)) !== null) {\n        const inner = member[1].replace(/<!--[\\s\\S]*?-->/g, '').trim();\n        // Obal prvku: <ms:<typename>> \u2026 </ms:<typename>>.\n        const wrapper = /^<([^<>\\s/]+)[^<>]*>([\\s\\S]*)<\\/\\1>$/.exec(inner);\n        const body = wrapper ? wrapper[2] : inner;\n        const properties = {};\n        const itemRe = /<([^<>/]+?)\\s*\\/>|<([^<>/]+?)>([\\s\\S]*?)<\\/\\2>/g;\n        let item;\n        while ((item = itemRe.exec(body)) !== null) {\n            const tag = item[1] ?? item[2];\n            const name = tag.includes(':') ? tag.slice(tag.indexOf(':') + 1) : tag;\n            if (name === 'msGeometry' || name === 'boundedBy') continue;\n            const raw = item[1] !== undefined ? '' : item[3];\n            const cdata = /^<!\\[CDATA\\[([\\s\\S]*)\\]\\]>$/.exec(raw);\n            const value = cdata ? cdata[1] : decodeXml(raw);\n            properties[name] = value === '' ? null : value;\n        }\n        features.push({ properties });\n    }\n    return features;\n}\n", "/**\n * wfs.js \u2014 klient WFS 2.0 pro slu\u017Ebu Mapserver (stejn\u00FD endpoint jako WMS,\n * `bootstrap.mapserverUrl`, v\u017Edy s FILE_URL + sig v query).\n *\n * Server nepodporuje DISTINCT ani agregace (min/max, count):\n * - hodnoty atributu pro klasifikaci \u2192 GetPropertyValue (`fetchValueCounts`,\n *   `fetchNumericValues`): vrac\u00ED jen hodnoty, bez geometrie. GetFeature\n *   s PROPERTYNAME geometrii pos\u00EDl\u00E1 d\u00E1l, tak\u017Ee u velk\u00FDch polygon\u016F (14 kraj\u016F\n *   \u010CR = 6,7 MB) narazil na limit odpov\u011Bdi slu\u017Eby (413);\n * - min/max atributu \u2192 dva po\u017Eadavky s COUNT=1 a SORTBY ASC/DESC a filtrem,\n *   kter\u00FD vynech\u00E1 pr\u00E1zdn\u00E9 hodnoty (slu\u017Eba je \u0159ad\u00ED na za\u010D\u00E1tek) \u2014 `fetchMinMax`;\n * - celkov\u00FD po\u010Det prvk\u016F \u2192 RESULTTYPE=hits, po\u010Det je v atributu\n *   `numberMatched` XML odpov\u011Bdi (`fetchHits`).\n * Server COUNT s\u00E1m nelimituje \u2014 proto ho pos\u00EDl\u00E1me v\u017Edy.\n *\n * Dlouh\u00FD `<ogc:Filter>` se pos\u00EDl\u00E1 p\u0159es POST (WFS GetFeature XML t\u011Blo),\n * FILE_URL/sig z\u016Fst\u00E1vaj\u00ED v URL query i u POST po\u017Eadavk\u016F. N\u00EDzko\u00FArov\u0148ov\u00E9\n * `fetchFeaturesPage`/`fetchHits` jsou navr\u017Een\u00E9 tak, aby je \u0161lo znovu pou\u017E\u00EDt\n * i pro atributovou tabulku (dal\u0161\u00ED d\u00E1vka).\n */\nimport { signedParams } from './wms.js';\nimport {\n    buildGetFeatureXml, owsExceptionText, parseFeatureCollection, parseValueCollection, xmlEscape,\n} from './wfs-values.js';\n\nconst DEFAULT_PAGE_SIZE = 1000;\n/** Hodnot na jeden GetPropertyValue: i u text\u016F o 254 znac\u00EDch kolem 3 MB. */\nconst VALUE_PAGE_SIZE = 10000;\n/** Kolik hodnot nejv\u00FD\u0161 p\u0159e\u010D\u00EDst pro klasifikaci (5 po\u017Eadavk\u016F). */\nexport const VALUE_READ_LIMIT = 50000;\n\n/** Z\u00E1kladn\u00ED parametry spole\u010Dn\u00E9 pro v\u0161echny WFS po\u017Eadavky dan\u00E9 vrstvy. */\nfunction baseParams(entry) {\n    return {\n        SERVICE: 'WFS',\n        VERSION: '2.0.0',\n        ...signedParams(entry),\n    };\n}\n\nfunction buildUrl(bootstrap, entry, params) {\n    const usp = new URLSearchParams({ ...baseParams(entry), ...params });\n    return `${bootstrap.mapserverUrl}?${usp.toString()}`;\n}\n\n/** Chyba ne\u00FAsp\u011B\u0161n\u00E9 odpov\u011Bdi \u2014 s textem v\u00FDjimky slu\u017Eby, kdy\u017E ho poslala\n * (\u201EThe answer \u2026 is larger than the service can send\u201C), jinak se statusem. */\nasync function failure(response, what) {\n    let detail = null;\n    try {\n        detail = owsExceptionText(await response.text());\n    } catch {\n        /* t\u011Blo se nepoda\u0159ilo p\u0159e\u010D\u00EDst */\n    }\n    const error = new Error(detail || `${what} failed: ${response.status}`);\n    error.status = response.status;\n    return error;\n}\n\nasync function requestGeoJson(bootstrap, entry, params, filterXml) {\n    const url = buildUrl(bootstrap, entry, params);\n    const response = filterXml\n        ? await fetch(url, {\n            method: 'POST',\n            headers: { 'Content-Type': 'application/xml' },\n            body: buildGetFeatureXml(params, filterXml),\n        })\n        : await fetch(url);\n    if (!response.ok) throw await failure(response, 'WFS GetFeature');\n    return response.json();\n}\n\n/** P\u0159e\u010Dte `numberMatched` z XML odpov\u011Bdi RESULTTYPE=hits (bez pln\u00E9ho XML\n * parseru \u2014 atribut je v\u017Edy na ko\u0159enov\u00E9m elementu, regex je dost robustn\u00ED). */\nfunction parseNumberMatched(xmlText) {\n    const match = /numberMatched=\"(\\d+)\"/.exec(xmlText) || /numberMatched='(\\d+)'/.exec(xmlText);\n    return match ? Number(match[1]) : null;\n}\n\n/**\n * Str\u00E1nkovan\u011B na\u010Dte prvky jedn\u00E9 podvrstvy jako GeoJSON.\n * `options`: { count, startIndex, propertyName (string|string[]), sortBy,\n * srsName='EPSG:4326', filterXml }.\n */\nexport async function fetchFeaturesPage(bootstrap, entry, typename, options = {}) {\n    const {\n        count = DEFAULT_PAGE_SIZE,\n        startIndex = 0,\n        propertyName,\n        sortBy,\n        srsName = 'EPSG:4326',\n        filterXml,\n    } = options;\n    const params = {\n        REQUEST: 'GetFeature',\n        TYPENAMES: typename,\n        OUTPUTFORMAT: 'geojson',\n        COUNT: count,\n        STARTINDEX: startIndex,\n        SRSNAME: srsName,\n    };\n    if (propertyName) params.PROPERTYNAME = Array.isArray(propertyName) ? propertyName.join(',') : propertyName;\n    if (sortBy) params.SORTBY = sortBy;\n    return requestGeoJson(bootstrap, entry, params, filterXml);\n}\n\n/** GML 3.2 \u2014 jedin\u00FD v\u00FDstup slu\u017Eby, kter\u00FD vynech\u00E1 geometrii, kdy\u017E ji\n * PROPERTYNAME nejmenuje (GeoJSON ji pos\u00EDl\u00E1 v\u017Edy). */\nconst GML_FORMAT = 'application/gml+xml; version=3.2';\n\n/**\n * Str\u00E1nka prvk\u016F jen s atributy, bez geometrie (atributov\u00E1 tabulka u dat\n * s velk\u00FDmi geometriemi \u2014 str\u00E1nka GeoJSON by p\u0159ekro\u010Dila limit odpov\u011Bdi\n * slu\u017Eby). `options`: { attributes (n\u00E1zvy, povinn\u00E9), count, startIndex,\n * sortBy, filterXml }. Vrac\u00ED `[{ properties }]`, hodnoty jako text.\n */\nexport async function fetchAttributesPage(bootstrap, entry, typename, options = {}) {\n    const {\n        attributes, count = DEFAULT_PAGE_SIZE, startIndex = 0, sortBy, filterXml,\n    } = options;\n    const params = {\n        REQUEST: 'GetFeature',\n        TYPENAMES: typename,\n        OUTPUTFORMAT: GML_FORMAT,\n        COUNT: count,\n        STARTINDEX: startIndex,\n        PROPERTYNAME: attributes.join(','),\n    };\n    if (sortBy) params.SORTBY = sortBy;\n    const url = buildUrl(bootstrap, entry, params);\n    const response = filterXml\n        ? await fetch(url, {\n            method: 'POST',\n            headers: { 'Content-Type': 'application/xml' },\n            body: buildGetFeatureXml(params, filterXml),\n        })\n        : await fetch(url);\n    if (!response.ok) throw await failure(response, 'WFS GetFeature');\n    const text = await response.text();\n    const exception = owsExceptionText(text);\n    if (exception) throw new Error(exception);\n    return parseFeatureCollection(text);\n}\n\n/** Celkov\u00FD po\u010Det prvk\u016F podvrstvy (RESULTTYPE=hits \u2192 `numberMatched`). */\nexport async function fetchHits(bootstrap, entry, typename, options = {}) {\n    const { filterXml } = options;\n    const params = { REQUEST: 'GetFeature', TYPENAMES: typename, RESULTTYPE: 'hits' };\n    const url = buildUrl(bootstrap, entry, params);\n    const response = filterXml\n        ? await fetch(url, {\n            method: 'POST',\n            headers: { 'Content-Type': 'application/xml' },\n            body: buildGetFeatureXml(params, filterXml),\n        })\n        : await fetch(url);\n    if (!response.ok) throw await failure(response, 'WFS hits request');\n    return parseNumberMatched(await response.text());\n}\n\n/**\n * Jedna str\u00E1nka hodnot atributu (WFS 2.0 GetPropertyValue) \u2014 text, pr\u00E1zdn\u00E9\n * jako `null`. `options`: { count, startIndex, sortBy, filterXml (FES 2.0\n * `<fes:Filter>`, jde v URL jako FILTER) }.\n */\nexport async function fetchPropertyValues(bootstrap, entry, typename, attribute, options = {}) {\n    const { count = VALUE_PAGE_SIZE, startIndex = 0, sortBy, filterXml } = options;\n    const params = {\n        REQUEST: 'GetPropertyValue',\n        TYPENAMES: typename,\n        VALUEREFERENCE: attribute,\n        COUNT: count,\n        STARTINDEX: startIndex,\n    };\n    if (sortBy) params.SORTBY = sortBy;\n    if (filterXml) params.FILTER = filterXml;\n    const response = await fetch(buildUrl(bootstrap, entry, params));\n    if (!response.ok) throw await failure(response, 'WFS GetPropertyValue');\n    const text = await response.text();\n    const exception = owsExceptionText(text);\n    if (exception) throw new Error(exception);\n    return parseValueCollection(text);\n}\n\n/** Projde hodnoty atributu po str\u00E1nk\u00E1ch v po\u0159ad\u00ED souboru (bez \u0159azen\u00ED \u2014 slu\u017Eba\n * nemus\u00ED t\u0159\u00EDdit cel\u00FD soubor), nejv\u00FD\u0161 `limit`. `onValue(value)` dostane ka\u017Edou\n * nepr\u00E1zdnou hodnotu; vrac\u00ED `{ read, truncated }`. */\nasync function scanValues(bootstrap, entry, typename, attribute, limit, onValue) {\n    let read = 0;\n    for (;;) {\n        // eslint-disable-next-line no-await-in-loop -- str\u00E1nky mus\u00ED j\u00EDt za sebou (STARTINDEX)\n        const count = Math.min(VALUE_PAGE_SIZE, limit - read);\n        const page = await fetchPropertyValues(bootstrap, entry, typename, attribute, { count, startIndex: read });\n        page.forEach((value) => { if (value !== null) onValue(value); });\n        read += page.length;\n        if (page.length < count) return { read, truncated: false };\n        if (read >= limit) return { read, truncated: true };\n    }\n}\n\n/**\n * \u010Cetnosti hodnot atributu jedn\u00E9 podvrstvy (`Map<text, po\u010Det>`) pro\n * kategorie \u2014 z nejv\u00FD\u0161 `limit` prvk\u016F. `truncated` = prvk\u016F je v\u00EDc a \u010Detnosti\n * jsou z prvn\u00EDch `limit`.\n */\nexport async function fetchValueCounts(bootstrap, entry, typename, attribute, options = {}) {\n    const { limit = VALUE_READ_LIMIT } = options;\n    const counts = new Map();\n    const { truncated } = await scanValues(bootstrap, entry, typename, attribute, limit, (value) => {\n        counts.set(value, (counts.get(value) || 0) + 1);\n    });\n    return { counts, truncated };\n}\n\n/** Filtr \u201Eatribut \u2265 nejmen\u0161\u00ED \u010D\u00EDslo\u201C \u2014 vynech\u00E1 pr\u00E1zdn\u00E9 hodnoty (porovn\u00E1n\u00ED\n * s NULL neplat\u00ED), kter\u00E9 slu\u017Eba p\u0159i \u0159azen\u00ED d\u00E1v\u00E1 na za\u010D\u00E1tek. */\nfunction notNullNumberFilter(attribute) {\n    const name = xmlEscape(attribute);\n    return '<fes:Filter xmlns:fes=\"http://www.opengis.net/fes/2.0\"><fes:PropertyIsGreaterThanOrEqualTo>'\n        + `<fes:ValueReference>${name}</fes:ValueReference><fes:Literal>-1e308</fes:Literal>`\n        + '</fes:PropertyIsGreaterThanOrEqualTo></fes:Filter>';\n}\n\nfunction toNumber(value) {\n    if (value === null || value === undefined || String(value).trim() === '') return null;\n    const number = Number(value);\n    return Number.isFinite(number) ? number : null;\n}\n\n/**\n * Min/max hodnota \u010D\u00EDseln\u00E9ho atributu jedn\u00E9 podvrstvy \u2014 dva po\u017Eadavky\n * s COUNT=1 a SORTBY ASC/DESC (server neum\u00ED agrega\u010Dn\u00ED funkce). Pr\u00E1zdn\u00E9\n * hodnoty vynech\u00E1 filtr; kdyby ho zdroj dat nezvl\u00E1dl, spo\u010D\u00EDt\u00E1 se min/max\n * z prvn\u00EDch hodnot (`fetchNumericValues`).\n */\nexport async function fetchMinMax(bootstrap, entry, typename, attribute) {\n    const filterXml = notNullNumberFilter(attribute);\n    try {\n        const [minPage, maxPage] = await Promise.all([\n            fetchPropertyValues(bootstrap, entry, typename, attribute, { count: 1, sortBy: `${attribute} ASC`, filterXml }),\n            fetchPropertyValues(bootstrap, entry, typename, attribute, { count: 1, sortBy: `${attribute} DESC`, filterXml }),\n        ]);\n        const min = toNumber(minPage[0]);\n        const max = toNumber(maxPage[0]);\n        if (min !== null && max !== null) return { min, max };\n    } catch (error) {\n        if (error?.status === 413) throw error;\n    }\n    const { values } = await fetchNumericValues(bootstrap, entry, typename, attribute);\n    if (!values.length) return { min: null, max: null };\n    return { min: values.reduce((a, b) => Math.min(a, b)), max: values.reduce((a, b) => Math.max(a, b)) };\n}\n\n/**\n * Hodnoty \u010D\u00EDseln\u00E9ho atributu (bez deduplikace \u2014 pot\u0159ebn\u00E9 pro kvantily/Jenks)\n * z nejv\u00FD\u0161 `limit` prvk\u016F; `truncated: true`, kdy\u017E jich je v\u00EDc.\n */\nexport async function fetchNumericValues(bootstrap, entry, typename, attribute, options = {}) {\n    const { limit = VALUE_READ_LIMIT } = options;\n    const values = [];\n    const { truncated } = await scanValues(bootstrap, entry, typename, attribute, limit, (value) => {\n        const number = toNumber(value);\n        if (number !== null) values.push(number);\n    });\n    return { values, truncated };\n}\n", "/**\n * ramps.js \u2014 pevn\u011B definovan\u00E9 barevn\u00E9 rampy (\u017E\u00E1dn\u00E1 nov\u00E1 npm z\u00E1vislost).\n *\n * Kategorick\u00E9 rampy (ColorBrewer Set1/Set2/Paired, matplotlib Tab10) se\n * pou\u017E\u00EDvaj\u00ED pro kategorizovan\u00FD styl \u2014 barvy se cyklicky opakuj\u00ED, pokud je\n * kategori\u00ED v\u00EDc ne\u017E barev v palet\u011B. Sekven\u010Dn\u00ED (viridis, YlOrRd, Blues) a\n * divergentn\u00ED (RdYlBu) rampy jsou ur\u010Den\u00E9 pro odstup\u0148ovan\u00FD styl \u2014 barvy pro\n * N t\u0159\u00EDd se rovnom\u011Brn\u011B interpoluj\u00ED po d\u00E9lce rampy.\n */\n\nexport const COLOR_RAMPS = [\n    {\n        key: 'set1',\n        label: 'Set1',\n        kind: 'categorical',\n        colors: ['#e41a1c', '#377eb8', '#4daf4a', '#984ea3', '#ff7f00', '#ffff33', '#a65628', '#f781bf', '#999999'],\n    },\n    {\n        key: 'set2',\n        label: 'Set2',\n        kind: 'categorical',\n        colors: ['#66c2a5', '#fc8d62', '#8da0cb', '#e78ac3', '#a6d854', '#ffd92f', '#e5c494', '#b3b3b3'],\n    },\n    {\n        key: 'paired',\n        label: 'Paired',\n        kind: 'categorical',\n        colors: ['#a6cee3', '#1f78b4', '#b2df8a', '#33a02c', '#fb9a99', '#e31a1c', '#fdbf6f', '#ff7f00', '#cab2d6', '#6a3d9a', '#ffff99', '#b15928'],\n    },\n    {\n        key: 'tab10',\n        label: 'Tab10',\n        kind: 'categorical',\n        colors: ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf'],\n    },\n    {\n        key: 'viridis',\n        label: 'Viridis',\n        kind: 'sequential',\n        colors: ['#440154', '#46327e', '#365c8d', '#277f8e', '#1fa187', '#4ac16d', '#a0da39', '#fde725'],\n    },\n    {\n        key: 'ylorrd',\n        label: 'YlOrRd',\n        kind: 'sequential',\n        colors: ['#ffffcc', '#ffeda0', '#fed976', '#feb24c', '#fd8d3c', '#fc4e2a', '#e31a1c', '#bd0026', '#800026'],\n    },\n    {\n        key: 'blues',\n        label: 'Blues',\n        kind: 'sequential',\n        colors: ['#f7fbff', '#deebf7', '#c6dbef', '#9ecae1', '#6baed6', '#4292c6', '#2171b5', '#08519c', '#08306b'],\n    },\n    {\n        key: 'rdylbu',\n        label: 'RdYlBu',\n        kind: 'diverging',\n        colors: ['#a50026', '#d73027', '#f46d43', '#fdae61', '#fee090', '#ffffbf', '#e0f3f8', '#abd9e9', '#74add1', '#4575b4', '#313695'],\n    },\n];\n\n/** Vr\u00E1t\u00ED definici rampy podle kl\u00ED\u010De (fallback na prvn\u00ED rampu, pokud kl\u00ED\u010D neexistuje). */\nexport function getRamp(key) {\n    return COLOR_RAMPS.find((r) => r.key === key) || COLOR_RAMPS[0];\n}\n\n/** Vr\u00E1t\u00ED rampy dan\u00E9ho druhu ('categorical' | 'sequential' | 'diverging'), nebo v\u0161echny. */\nexport function listRamps(kind) {\n    return kind ? COLOR_RAMPS.filter((r) => r.kind === kind) : COLOR_RAMPS;\n}\n\nfunction hexToRgb(hex) {\n    const clean = hex.replace('#', '');\n    return [0, 2, 4].map((i) => parseInt(clean.slice(i, i + 2), 16));\n}\n\nfunction rgbToHex([r, g, b]) {\n    return `#${[r, g, b]\n        .map((v) => Math.max(0, Math.min(255, Math.round(v))).toString(16).padStart(2, '0'))\n        .join('')}`;\n}\n\nfunction clamp01(value) {\n    return Math.min(1, Math.max(0, value));\n}\n\n/** Interpoluje barvu na pozici `t` (0\u20131) v kontinu\u00E1ln\u00ED sad\u011B barevn\u00FDch zar\u00E1\u017Eek. */\nfunction interpolate(stops, t) {\n    const scaled = clamp01(t) * (stops.length - 1);\n    const i0 = Math.floor(scaled);\n    const i1 = Math.min(stops.length - 1, i0 + 1);\n    const frac = scaled - i0;\n    const c0 = hexToRgb(stops[i0]);\n    const c1 = hexToRgb(stops[i1]);\n    return rgbToHex(c0.map((c, i) => c + (c1[i] - c) * frac));\n}\n\n/** Vr\u00E1t\u00ED `count` barev z rampy \u2014 kategorick\u00E1 paleta se cyklicky opakuje,\n * kontinu\u00E1ln\u00ED (sequential/diverging) rampy se rovnom\u011Brn\u011B interpoluj\u00ED. */\nexport function getRampColors(rampKey, count) {\n    const ramp = getRamp(rampKey);\n    if (!Number.isFinite(count) || count <= 0) return [];\n    if (ramp.kind === 'categorical') {\n        return Array.from({ length: count }, (_, i) => ramp.colors[i % ramp.colors.length]);\n    }\n    if (count === 1) return [interpolate(ramp.colors, 0.5)];\n    return Array.from({ length: count }, (_, i) => interpolate(ramp.colors, i / (count - 1)));\n}\n\n/** CSS `linear-gradient` pro mal\u00FD n\u00E1hled rampy (barevn\u00FD pruh) v UI. */\nexport function rampPreviewGradient(rampKey) {\n    const ramp = getRamp(rampKey);\n    return `linear-gradient(to right, ${ramp.colors.join(', ')})`;\n}\n", "/**\n * classify.js \u2014 klasifika\u010Dn\u00ED metody pro odstup\u0148ovan\u00FD (graduated) styl.\n * Vstupem je pole \u010D\u00EDseln\u00FDch hodnot (typicky sta\u017Eeno p\u0159es wfs.js), v\u00FDstupem\n * seznam t\u0159\u00EDd `{min, max}` v po\u0159ad\u00ED od nejmen\u0161\u00ED k nejv\u011Bt\u0161\u00ED hodnot\u011B.\n *\n * Bez nov\u00FDch npm z\u00E1vislost\u00ED \u2014 Jenks natural breaks je napsan\u00FD p\u0159\u00EDmo zde\n * (klasick\u00E1 dynamic-programming implementace, O(k\u00B7n\u00B2)). Nad v\u00EDc ne\u017E\n * `JENKS_MAX_SAMPLE` hodnotami po\u010D\u00EDt\u00E1 z rovnom\u011Brn\u00E9ho vzorku se\u0159azen\u00FDch\n * hodnot: 20 000 hodnot by prohl\u00ED\u017Ee\u010D zamrazilo na n\u011Bkolik sekund.\n *\n * T\u0159\u00EDdy se kresl\u00ED jako [min, max), posledn\u00ED [min, max] (sld.js) \u2014 t\u0159\u00EDda\n * s min = max by tedy nic nezachytila; `classify` takov\u00E9 vynech\u00E1.\n *\n * Kategorie (categorized): `pickCategories` z \u010Detnost\u00ED hodnot vybere\n * nej\u010Dast\u011Bj\u0161\u00ED a se\u0159ad\u00ED je p\u0159irozen\u011B (\u010D\u00EDsla \u010D\u00EDseln\u011B, text podle abecedy).\n */\n\n/** Nad kolika hodnotami Jenks po\u010D\u00EDt\u00E1 ze vzorku. */\nexport const JENKS_MAX_SAMPLE = 3000;\n\nexport const CLASSIFICATION_METHODS = [\n    { value: 'equal', label: 'Equal interval' },\n    { value: 'quantile', label: 'Quantile' },\n    { value: 'jenks', label: 'Natural breaks (Jenks)' },\n];\n\nfunction sortedNumbers(values) {\n    return values\n        .map(Number)\n        .filter((v) => Number.isFinite(v))\n        .sort((a, b) => a - b);\n}\n\nfunction breaksToClasses(breaks) {\n    const classes = [];\n    for (let i = 0; i < breaks.length - 1; i++) {\n        classes.push({ min: breaks[i], max: breaks[i + 1] });\n    }\n    return classes;\n}\n\n/** Rovnom\u011Brn\u00E9 intervaly \u2014 ka\u017Ed\u00E1 t\u0159\u00EDda m\u00E1 stejnou \u0161\u00ED\u0159ku (max - min) / N. */\nexport function equalIntervalClasses(values, classCount) {\n    const sorted = sortedNumbers(values);\n    if (sorted.length === 0 || classCount < 1) return [];\n    const min = sorted[0];\n    const max = sorted[sorted.length - 1];\n    const step = (max - min) / classCount;\n    const breaks = Array.from(\n        { length: classCount + 1 },\n        (_, i) => (i === classCount ? max : min + i * step),\n    );\n    return breaksToClasses(breaks);\n}\n\n/** Kvantily \u2014 ka\u017Ed\u00E1 t\u0159\u00EDda obsahuje (p\u0159ibli\u017En\u011B) stejn\u00FD po\u010Det prvk\u016F. */\nexport function quantileClasses(values, classCount) {\n    const sorted = sortedNumbers(values);\n    if (sorted.length === 0 || classCount < 1) return [];\n    const percentile = (p) => {\n        const idx = p * (sorted.length - 1);\n        const lo = Math.floor(idx);\n        const hi = Math.ceil(idx);\n        if (lo === hi) return sorted[lo];\n        return sorted[lo] + (sorted[hi] - sorted[lo]) * (idx - lo);\n    };\n    const breaks = Array.from({ length: classCount + 1 }, (_, i) => percentile(i / classCount));\n    return breaksToClasses(breaks);\n}\n\n/** Rovnom\u011Brn\u00FD vzorek se\u0159azen\u00E9ho pole o `size` prvc\u00EDch (v\u017Edy s minimem\n * i maximem), aby v\u00FDsledek pokryl cel\u00E9 rozp\u011Bt\u00ED. */\nfunction sampleSorted(sorted, size) {\n    if (sorted.length <= size) return sorted;\n    const step = (sorted.length - 1) / (size - 1);\n    return Array.from({ length: size }, (_, i) => sorted[Math.round(i * step)]);\n}\n\n/** Fisher-Jenks algoritmus p\u0159irozen\u00FDch hranic \u2014 vrac\u00ED `classCount + 1`\n * hranic (v\u010Detn\u011B min/max) jako klasickou dynamic-programming variantu. */\nfunction jenksBreaks(data, classCount) {\n    const n = data.length;\n    const lowerClassLimits = Array.from({ length: n + 1 }, () => new Array(classCount + 1).fill(0));\n    const varianceCombinations = Array.from({ length: n + 1 }, () => new Array(classCount + 1).fill(Infinity));\n\n    for (let i = 1; i <= classCount; i++) {\n        lowerClassLimits[1][i] = 1;\n        varianceCombinations[1][i] = 0;\n        for (let j = 2; j <= n; j++) varianceCombinations[j][i] = Infinity;\n    }\n\n    let variance = 0;\n    for (let l = 2; l <= n; l++) {\n        let sum = 0;\n        let sumSquares = 0;\n        let w = 0;\n        for (let m = 1; m <= l; m++) {\n            const lowerClassLimit = l - m + 1;\n            const value = data[lowerClassLimit - 1];\n            w += 1;\n            sum += value;\n            sumSquares += value * value;\n            variance = sumSquares - (sum * sum) / w;\n            const i4 = lowerClassLimit - 1;\n            if (i4 !== 0) {\n                for (let j = 2; j <= classCount; j++) {\n                    if (varianceCombinations[l][j] >= variance + varianceCombinations[i4][j - 1]) {\n                        lowerClassLimits[l][j] = lowerClassLimit;\n                        varianceCombinations[l][j] = variance + varianceCombinations[i4][j - 1];\n                    }\n                }\n            }\n        }\n        lowerClassLimits[l][1] = 1;\n        varianceCombinations[l][1] = variance;\n    }\n\n    const breaks = new Array(classCount + 1);\n    breaks[classCount] = data[n - 1];\n    breaks[0] = data[0];\n    let k = n;\n    for (let countNum = classCount; countNum > 1; countNum--) {\n        // Hranice = PRVN\u00CD hodnota t\u0159\u00EDdy `countNum` (index lowerClassLimit - 1).\n        // Mapa kresl\u00ED t\u0159\u00EDdy jako [min, max) (sld.js); s posledn\u00ED hodnotou\n        // p\u0159edchoz\u00ED t\u0159\u00EDdy (klasick\u00FD v\u00FDstup Jenks) by maximum ka\u017Ed\u00E9 skupiny\n        // spadlo do t\u0159\u00EDdy nad n\u00ED.\n        const firstOfClass = lowerClassLimits[k][countNum] - 1;\n        breaks[countNum - 1] = data[firstOfClass];\n        k = lowerClassLimits[k][countNum] - 1;\n    }\n    return breaks;\n}\n\n/** P\u0159irozen\u00E9 hranice (Jenks natural breaks). M\u00E1-li atribut nejv\u00FD\u0161 tolik\n * r\u016Fzn\u00FDch hodnot, kolik je t\u0159\u00EDd, dostane ka\u017Ed\u00E1 hodnota vlastn\u00ED t\u0159\u00EDdu. */\nexport function jenksClasses(values, classCount) {\n    const sorted = sortedNumbers(values);\n    const unique = Array.from(new Set(sorted));\n    if (unique.length === 0 || classCount < 1) return [];\n    if (unique.length <= classCount) {\n        // [1, 2), [2, 3), [3, 3] \u2014 posledn\u00ED t\u0159\u00EDda je uzav\u0159en\u00E1 (sld.js).\n        return breaksToClasses([...unique, unique[unique.length - 1]]);\n    }\n    return breaksToClasses(jenksBreaks(sampleSorted(sorted, JENKS_MAX_SAMPLE), classCount));\n}\n\n/** Vynech\u00E1 t\u0159\u00EDdy nulov\u00E9 \u0161\u00ED\u0159ky (kvantily nad opakuj\u00EDc\u00EDmi se hodnotami, stejn\u00E9\n * minimum a maximum): [v, v) by nezachytila nic. Posledn\u00ED, uzav\u0159en\u00E1 t\u0159\u00EDda\n * z\u016Fstane v\u017Edy, tak\u017Ee data se stejnou hodnotou maj\u00ED jednu t\u0159\u00EDdu [v, v]. */\nexport function dropEmptyClasses(classes) {\n    // Posledn\u00ED t\u0159\u00EDda [v, v] je smyslupln\u00E1 i za jinou: zachyt\u00ED p\u0159esn\u011B hodnotu v,\n    // kterou p\u0159edchoz\u00ED [min, v) vynech\u00E1 (nap\u0159. t\u0159etina prvk\u016F m\u00E1 maximum).\n    return classes.filter((cls, i) => cls.max > cls.min || i === classes.length - 1);\n}\n\n/** Spust\u00ED klasifikaci podle metody (`'equal' | 'quantile' | 'jenks'`). */\nexport function classify(values, method, classCount) {\n    let classes;\n    if (method === 'quantile') classes = quantileClasses(values, classCount);\n    else if (method === 'jenks') classes = jenksClasses(values, classCount);\n    else classes = equalIntervalClasses(values, classCount);\n    return dropEmptyClasses(classes);\n}\n\nfunction isNumeric(value) {\n    return String(value).trim() !== '' && Number.isFinite(Number(value));\n}\n\n/** P\u0159irozen\u00E9 po\u0159ad\u00ED hodnot kategori\u00ED: \u010D\u00EDsla \u010D\u00EDseln\u011B, jinak abecedn\u011B podle\n * jazyka (\u010C za C, \u201Eitem 2\u201C p\u0159ed \u201Eitem 10\u201C). */\nexport function sortCategoryValues(values) {\n    const list = Array.from(values);\n    if (list.length && list.every(isNumeric)) return list.sort((a, b) => Number(a) - Number(b));\n    const collator = new Intl.Collator(undefined, { numeric: true });\n    return list.sort((a, b) => collator.compare(String(a), String(b)));\n}\n\n/** Kategorie z \u010Detnost\u00ED hodnot (`Map<hodnota, po\u010Det>`): p\u0159i v\u00EDc ne\u017E `max`\n * r\u016Fzn\u00FDch hodnot\u00E1ch ty nej\u010Dast\u011Bj\u0161\u00ED. Vrac\u00ED `{ values, distinct, truncated }`,\n * `values` v p\u0159irozen\u00E9m po\u0159ad\u00ED. */\nexport function pickCategories(counts, max) {\n    const entries = Array.from(counts.entries());\n    let chosen = entries.map(([value]) => value);\n    if (entries.length > max) {\n        chosen = entries\n            .sort((a, b) => b[1] - a[1])\n            .slice(0, max)\n            .map(([value]) => value);\n    }\n    return { values: sortCategoryValues(chosen), distinct: entries.length, truncated: entries.length > max };\n}\n\n/** V\u00FDchoz\u00ED popisek t\u0159\u00EDdy odvozen\u00FD z min/max (cel\u00E1 \u010D\u00EDsla bez desetin). */\nexport function formatClassLabel(min, max) {\n    const fmt = (v) => (Number.isInteger(v) ? String(v) : v.toFixed(2));\n    return `${fmt(min)} \u2013 ${fmt(max)}`;\n}\n", "/**\n * style-ui.js \u2014 panel symbologie pro jednu vrstvu. Zobrazuje jen sekce podle\n * `entry.geometryTypes` (point/line/polygon) pro vektor, nebo panel p\u00E1sem pro\n * rastr. Ka\u017Ed\u00E1 zm\u011Bna aktualizuje `entry.style`, p\u0159egeneruje SLD/parametry\n * (debounced) a obnov\u00ED legendu.\n */\nimport { emit } from './utils.js';\nimport { findEntryByUid, normalizeVectorStyle, styleFromSuggestions } from './state.js';\nimport {\n    PHOTO_MIN_SIZE, PHOTO_SIZE, PHOTO_SYMBOL, applyPhotoMarker, photoFieldOf,\n} from './photo-marker.js';\nimport {\n    LABEL_POSITIONS, applyDefaultLabels, entryAutoLabelMinZoom, labelFieldOf,\n} from './labels.js';\nimport { scheduleWmsRefresh } from './wms.js';\nimport { setLocalLayerColor } from './external.js';\nimport {\n    getStylePanelContainer, refreshLayerRow, setLayerOpacity, updateRasterLegend,\n} from './layers.js';\nimport { fetchValueCounts, fetchMinMax, fetchNumericValues, VALUE_READ_LIMIT } from './wfs.js';\nimport { listRamps, getRampColors, rampPreviewGradient } from './ramps.js';\nimport { classify, formatClassLabel, pickCategories, CLASSIFICATION_METHODS } from './classify.js';\n\n/** Maxim\u00E1ln\u00ED po\u010Det kategori\u00ED, kter\u00E9 Classify vygeneruje z unik\u00E1tn\u00EDch hodnot\n * (viz zad\u00E1n\u00ED \u2014 nad t\u00EDmto po\u010Dtem u\u017E je kategorizace nep\u0159ehledn\u00E1). */\nconst MAX_CATEGORIES = 50;\n\nfunction colorInput(label, value, onInput) {\n    const wrap = document.createElement('label');\n    wrap.className = label\n        ? 'flex items-center justify-between gap-x-2 text-xs text-slate-600'\n        : 'flex flex-none items-center';\n    wrap.innerHTML = `${label ? `<span>${label}</span>` : ''}<input type=\"color\" value=\"${value}\" aria-label=\"${label || 'Colour'}\" class=\"h-6 w-8 flex-none cursor-pointer rounded border border-slate-200\">`;\n    wrap.querySelector('input').addEventListener('input', (e) => onInput(e.target.value));\n    return wrap;\n}\n\nfunction rangeInput(label, value, min, max, step, onInput, formatter) {\n    const wrap = document.createElement('label');\n    wrap.className = 'flex items-center justify-between gap-x-2 text-xs text-slate-600';\n    const fmt = formatter || ((v) => v);\n    wrap.innerHTML = `<span>${label}</span>\n        <span class=\"flex items-center gap-x-2\">\n            <input type=\"range\" min=\"${min}\" max=\"${max}\" step=\"${step}\" value=\"${value}\" class=\"h-1.5 w-24 cursor-pointer accent-brand-600\">\n            <span data-role=\"value\" class=\"w-9 text-right tabular-nums\">${fmt(value)}</span>\n        </span>`;\n    const input = wrap.querySelector('input');\n    const valueEl = wrap.querySelector('[data-role=\"value\"]');\n    input.addEventListener('input', (e) => {\n        const v = Number(e.target.value);\n        valueEl.textContent = fmt(v);\n        onInput(v);\n    });\n    return wrap;\n}\n\nfunction selectInput(label, value, options, onChange) {\n    const wrap = document.createElement('label');\n    wrap.className = 'flex items-center justify-between gap-x-2 text-xs text-slate-600';\n    const optionsHtml = options.map((o) => `<option value=\"${o.value}\" ${o.value === value ? 'selected' : ''}>${o.label}</option>`).join('');\n    wrap.innerHTML = `<span class=\"flex-none\">${label}</span><select class=\"min-w-0 max-w-[65%] truncate rounded border-slate-200 py-1 text-xs focus:border-brand-500 focus:ring-brand-500\">${optionsHtml}</select>`;\n    wrap.querySelector('select').addEventListener('change', (e) => onChange(e.target.value));\n    return wrap;\n}\n\nfunction checkboxInput(label, checked, onChange) {\n    const wrap = document.createElement('label');\n    wrap.className = 'flex items-center gap-x-2 text-xs text-slate-600';\n    wrap.innerHTML = `<input type=\"checkbox\" ${checked ? 'checked' : ''} class=\"h-3.5 w-3.5 rounded border-slate-300 text-brand-600 focus:ring-brand-500\"><span>${label}</span>`;\n    wrap.querySelector('input').addEventListener('change', (e) => onChange(e.target.checked));\n    return wrap;\n}\n\nfunction textInput(placeholder, value, onInput, extraClass) {\n    const input = document.createElement('input');\n    input.type = 'text';\n    input.value = value ?? '';\n    input.placeholder = placeholder || '';\n    // `min-w-0 w-0` + flex: pole se smr\u0161t\u00ED do \u0161\u00ED\u0159ky karty (i ve skupin\u011B),\n    // m\u00EDsto aby \u0159\u00E1dek p\u0159etekl a panel dostal vodorovn\u00FD posuvn\u00EDk.\n    input.className = `min-w-0 rounded border-slate-200 px-1.5 py-1 text-xs focus:border-brand-500 focus:ring-brand-500 ${extraClass || 'w-0 flex-1'}`;\n    input.addEventListener('input', (e) => onInput(e.target.value));\n    return input;\n}\n\nfunction numberInput(placeholder, value, onInput, extraClass) {\n    const input = document.createElement('input');\n    input.type = 'number';\n    input.step = 'any';\n    input.value = value ?? '';\n    input.placeholder = placeholder || '';\n    input.className = `min-w-0 rounded border-slate-200 px-1.5 py-1 text-xs focus:border-brand-500 focus:ring-brand-500 ${extraClass || 'w-16 flex-none'}`;\n    input.addEventListener('input', (e) => onInput(Number(e.target.value)));\n    return input;\n}\n\nfunction removeButton(onClick) {\n    const button = document.createElement('button');\n    button.type = 'button';\n    button.title = 'Remove';\n    button.className = 'flex-none rounded p-1 text-slate-400 hover:bg-red-50 hover:text-red-600';\n    button.textContent = '\\u2715';\n    button.addEventListener('click', onClick);\n    return button;\n}\n\nfunction sectionTitle(text) {\n    const el = document.createElement('p');\n    el.className = 'mb-1 mt-3 text-[11px] font-semibold uppercase tracking-wide text-slate-400';\n    el.textContent = text;\n    return el;\n}\n\n/** V\u0161echny atributy podvrstev vrstvy, sjednocen\u00E9 podle jm\u00E9na (jedna vrstva\n * workspace m\u016F\u017Ee m\u00EDt v\u00EDc podvrstev se stejn\u00FDm sch\u00E9matem atribut\u016F). */\nfunction uniqueAttributes(entry) {\n    const attributes = (entry.sublayers || []).flatMap((s) => s.attributes || []);\n    return Array.from(new Map(attributes.map((a) => [a.name, a])).values());\n}\n\nconst NUMERIC_TYPE_HINTS = ['int', 'real', 'float', 'double', 'long', 'short', 'numeric', 'decimal'];\n\n/** Jen \u010D\u00EDseln\u00E9 atributy (pro v\u00FDb\u011Br atributu odstup\u0148ovan\u00E9ho stylu). */\nfunction numericAttributes(entry) {\n    return uniqueAttributes(entry).filter((a) => NUMERIC_TYPE_HINTS.some((hint) => (a.type || '').toLowerCase().includes(hint)));\n}\n\n/** N\u00E1zvy podvrstev, kter\u00E9 dan\u00FD atribut skute\u010Dn\u011B maj\u00ED (WFS dotazy se pos\u00EDlaj\u00ED\n * jen na n\u011B, aby zbyte\u010Dn\u011B neselh\u00E1valy na podvrstv\u00E1ch bez tohoto atributu). */\nfunction sublayersWithAttribute(entry, attribute) {\n    return (entry.sublayers || [])\n        .filter((s) => (s.attributes || []).some((a) => a.name === attribute))\n        .map((s) => s.name);\n}\n\n/** Nab\u00EDdka \u010D\u00E1rkov\u00E1n\u00ED; vzor p\u0159evzat\u00FD z dat \u010Di n\u00E1vrhu, kter\u00FD v nab\u00EDdce nen\u00ED,\n * se dopln\u00ED jako \"Custom\", aby ho otev\u0159en\u00ED panelu nep\u0159epsalo. */\nfunction dashOptions(current) {\n    const options = [\n        { value: '', label: 'Solid' },\n        { value: '6 4', label: 'Dashed' },\n        { value: '2 3', label: 'Dotted' },\n        { value: '8 3 2 3', label: 'Dash-dot' },\n    ];\n    // Star\u0161\u00ED mapy pou\u017E\u00EDvaly \"4 2\" / \"1 3\".\n    if (current && !options.some((o) => o.value === current)) {\n        options.push({ value: current, label: 'Custom' });\n    }\n    return options;\n}\n\n/** Vytvo\u0159\u00ED sekci \"Point\". `isClassified` = true skryje \"Fill\" (barvu p\u0159eb\u00EDr\u00E1\n * kategorie/t\u0159\u00EDda) \u2014 ostatn\u00ED vlastnosti (symbol, velikost, obrys) z\u016Fst\u00E1vaj\u00ED. */\nfunction pointSection(ctx, entry, onAnyChange, isClassified) {\n    const rule = entry.style.rules.point;\n    const box = document.createElement('div');\n    box.appendChild(sectionTitle('Point'));\n    box.appendChild(selectInput('Symbol', rule.symbol, [\n        { value: 'circle', label: 'Circle' },\n        { value: 'square', label: 'Square' },\n        { value: 'triangle', label: 'Triangle' },\n        { value: 'star', label: 'Star' },\n        { value: 'cross', label: 'Cross' },\n        { value: 'x', label: 'X' },\n        { value: PHOTO_SYMBOL, label: 'Camera' },\n    ], (v) => {\n        // Fotoapar\u00E1t se do mal\u00E9 te\u010Dky nevejde \u2014 a velk\u00FD krou\u017Eek nen\u00ED te\u010Dka.\n        if (v === PHOTO_SYMBOL && rule.size < PHOTO_MIN_SIZE) rule.size = PHOTO_SIZE;\n        else if (rule.symbol === PHOTO_SYMBOL && v !== PHOTO_SYMBOL && rule.size === PHOTO_SIZE) rule.size = 8;\n        rule.symbol = v;\n        onAnyChange();\n        renderStylePanel(ctx, entry);\n    }));\n    if (rule.symbol === PHOTO_SYMBOL) {\n        const note = document.createElement('p');\n        note.className = 'mt-1 text-xs text-slate-500';\n        note.textContent = (entry.sublayers || []).some((sub) => photoFieldOf(sub.attributes))\n            ? 'Features without photos are drawn as small dots. Stroke sets the color of the camera.'\n            : 'Stroke sets the color of the camera.';\n        box.appendChild(note);\n    }\n    box.appendChild(rangeInput('Size', rule.size, 2, 32, 1, (v) => { rule.size = v; onAnyChange(); }));\n    if (!isClassified) box.appendChild(colorInput('Fill', rule.fill, (v) => { rule.fill = v; onAnyChange(); }));\n    box.appendChild(colorInput('Stroke', rule.stroke, (v) => { rule.stroke = v; onAnyChange(); }));\n    box.appendChild(rangeInput('Stroke width', rule.strokeWidth, 0, 8, 0.5, (v) => { rule.strokeWidth = v; onAnyChange(); }));\n    return box;\n}\n\n/** Vytvo\u0159\u00ED sekci \"Line\". `isClassified` = true skryje hlavn\u00ED barvu \u010D\u00E1ry\n * (p\u0159eb\u00EDr\u00E1 ji kategorie/t\u0159\u00EDda) \u2014 \u0161\u00ED\u0159ka, \u010D\u00E1rkov\u00E1n\u00ED a obrys z\u016Fst\u00E1vaj\u00ED. */\nfunction lineSection(ctx, entry, onAnyChange, isClassified) {\n    const rule = entry.style.rules.line;\n    const box = document.createElement('div');\n    box.appendChild(sectionTitle('Line'));\n    if (!isClassified) box.appendChild(colorInput('Color', rule.stroke, (v) => { rule.stroke = v; onAnyChange(); }));\n    box.appendChild(rangeInput('Width', rule.strokeWidth, 0.5, 12, 0.5, (v) => { rule.strokeWidth = v; onAnyChange(); }));\n    box.appendChild(selectInput('Dashing', rule.dash || '', dashOptions(rule.dash), (v) => { rule.dash = v || null; onAnyChange(); }));\n    box.appendChild(checkboxInput('Outline (casing)', Boolean(rule.casing), (checked) => {\n        rule.casing = checked ? '#1f2937' : null;\n        onAnyChange();\n        renderStylePanel(ctx, entry); // zm\u011Bna p\u0159\u00EDtomnosti color pickeru\n    }));\n    if (rule.casing) {\n        box.appendChild(colorInput('Casing color', rule.casing, (v) => { rule.casing = v; onAnyChange(); }));\n    }\n    return box;\n}\n\n/** Vytvo\u0159\u00ED sekci \"Polygon\". `isClassified` = true skryje \"Fill\" (barvu\n * p\u0159eb\u00EDr\u00E1 kategorie/t\u0159\u00EDda) \u2014 pr\u016Fhlednost v\u00FDpln\u011B a obrys z\u016Fst\u00E1vaj\u00ED. */\nfunction polygonSection(ctx, entry, onAnyChange, isClassified) {\n    const rule = entry.style.rules.polygon;\n    const box = document.createElement('div');\n    box.appendChild(sectionTitle('Polygon'));\n    if (!isClassified) box.appendChild(colorInput('Fill', rule.fill, (v) => { rule.fill = v; onAnyChange(); }));\n    box.appendChild(rangeInput('Fill opacity', rule.fillOpacity, 0, 1, 0.05, (v) => { rule.fillOpacity = v; onAnyChange(); }, (v) => v.toFixed(2)));\n    box.appendChild(colorInput('Outline', rule.stroke, (v) => { rule.stroke = v; onAnyChange(); }));\n    box.appendChild(rangeInput('Outline width', rule.strokeWidth, 0, 8, 0.5, (v) => { rule.strokeWidth = v; onAnyChange(); }));\n    box.appendChild(selectInput('Outline dashing', rule.dash || '', dashOptions(rule.dash), (v) => { rule.dash = v || null; onAnyChange(); }));\n    return box;\n}\n\n/** Vytvo\u0159\u00ED p\u0159ep\u00EDna\u010D Mode (Simple / Categorized / Graduated) pro vektorovou vrstvu. */\nfunction modeSwitcher(ctx, entry, onAnyChange) {\n    const box = document.createElement('div');\n    const options = [\n        { value: 'simple', label: 'Single symbol' },\n        { value: 'categorized', label: 'By category' },\n        { value: 'graduated', label: 'By value (graduated)' },\n    ];\n    // Styl ulo\u017Een\u00FD v datech (KML, MapInfo, DXF, atribut OGR_STYLE\u2026) \u2014 jen\n    // kdy\u017E ho data opravdu maj\u00ED.\n    if (entry.native?.available) {\n        options.unshift({ value: 'native', label: 'Original (from the file)' });\n    }\n    const current = options.some((o) => o.value === entry.style.mode) ? entry.style.mode : 'simple';\n    box.appendChild(selectInput('Style', current, options, (v) => {\n        entry.style.mode = v;\n        onAnyChange();\n        renderStylePanel(ctx, entry); // zm\u011Bna re\u017Eimu p\u0159ekresl\u00ED cel\u00FD panel\n    }));\n    return box;\n}\n\n/** Re\u017Eim \"Original\": vysv\u011Btlen\u00ED m\u00EDsto ovl\u00E1dac\u00EDch prvk\u016F (styl je v datech). */\nfunction nativeSection(entry) {\n    const box = document.createElement('div');\n    const fromAttribute = entry.native?.source === 'attribute';\n    box.innerHTML = `\n        <p class=\"mt-2 rounded-lg bg-slate-50 px-2.5 py-2 text-xs leading-relaxed text-slate-600\">\n            This layer is drawn with the style stored ${fromAttribute\n        ? `in its <span class=\"font-mono\">${entry.native?.field || 'OGR_STYLE'}</span> attribute`\n        : 'in the file'}. Choose another style above to restyle it \u2014 you can switch back to the original at any time.\n        </p>`;\n    return box;\n}\n\n/** Pr\u016Fhlednost vrstvy \u2014 prvn\u00ED polo\u017Eka panelu stylu u ka\u017Ed\u00E9ho typu vrstvy. */\nfunction opacitySection(ctx, entry) {\n    const box = document.createElement('div');\n    box.appendChild(rangeInput('Opacity', Math.round((entry.opacity ?? 1) * 100), 0, 100, 5, (v) => {\n        setLayerOpacity(ctx, entry.uid, v / 100);\n        if (!ctx.readOnly) ctx.state.dirty = true;\n    }, (v) => `${v}%`));\n    return box;\n}\n\n/** Jeden \u0159\u00E1dek editovateln\u00E9ho seznamu kategori\u00ED (barva, hodnota, popisek, smaz\u00E1n\u00ED). */\nfunction categoryRow(category, categories, index, ctx, entry, onAnyChange) {\n    const row = document.createElement('div');\n    row.className = 'flex items-center gap-x-1.5';\n    row.appendChild(colorInput('', category.color, (v) => { category.color = v; onAnyChange(); }));\n    row.appendChild(textInput('Value', category.value, (v) => { category.value = v; onAnyChange(); }, 'w-0 flex-1'));\n    row.appendChild(textInput('Label', category.label, (v) => { category.label = v; onAnyChange(); }, 'w-0 flex-[1.4]'));\n    row.appendChild(removeButton(() => {\n        categories.splice(index, 1);\n        onAnyChange();\n        renderStylePanel(ctx, entry);\n    }));\n    return row;\n}\n\n/** Editovateln\u00FD seznam kategori\u00ED (categorized) + tla\u010D\u00EDtko \"+ Add category\". */\nfunction categoriesList(cat, ctx, entry, onAnyChange) {\n    const wrap = document.createElement('div');\n    wrap.className = 'mt-2 space-y-1';\n    (cat.categories || []).forEach((category, index) => {\n        wrap.appendChild(categoryRow(category, cat.categories, index, ctx, entry, onAnyChange));\n    });\n    const addBtn = document.createElement('button');\n    addBtn.type = 'button';\n    addBtn.className = 'mt-1 w-full rounded-lg border border-dashed border-slate-300 px-2 py-1 text-xs text-slate-500 hover:border-brand-300 hover:text-brand-600';\n    addBtn.textContent = '+ Add category';\n    addBtn.addEventListener('click', () => {\n        cat.categories = cat.categories || [];\n        cat.categories.push({ value: '', label: '', color: '#999999' });\n        onAnyChange();\n        renderStylePanel(ctx, entry);\n    });\n    wrap.appendChild(addBtn);\n    return wrap;\n}\n\n/** V\u00FDsledek \u201EClassify\u201C (po\u010Det kategori\u00ED/t\u0159\u00EDd, v\u00FDb\u011Br z mnoha hodnot) \u2014 panel\n * se po klasifikaci p\u0159ekresl\u00ED, proto hl\u00E1\u0161ka \u017Eije ve stavu vrstvy. */\nfunction rememberClassifyNote(entry, section, text, warn) {\n    entry.uiState.classifyNote = { section, text, warn: Boolean(warn) };\n}\n\nfunction classifyNoteElement(entry, section) {\n    const status = document.createElement('p');\n    const note = entry.uiState?.classifyNote;\n    const shown = note && note.section === section;\n    status.className = `mt-1 text-xs ${shown && note.warn ? 'text-amber-600' : shown ? 'text-slate-500' : 'text-slate-400'}`;\n    status.textContent = shown ? note.text : '';\n    return status;\n}\n\n/** Vytvo\u0159\u00ED \"Classify\" tla\u010D\u00EDtko se stavovou hl\u00E1\u0161kou (loading/error/v\u00FDsledek). */\nfunction classifyButton(label, statusEl, onClick) {\n    const button = document.createElement('button');\n    button.type = 'button';\n    button.className = 'mt-2 w-full rounded-lg border border-brand-300 bg-brand-50 px-2 py-1 text-xs font-medium text-brand-700 hover:bg-brand-100 disabled:cursor-not-allowed disabled:opacity-50';\n    button.textContent = label;\n    button.addEventListener('click', async () => {\n        button.disabled = true;\n        statusEl.className = 'mt-1 text-xs text-slate-400';\n        statusEl.textContent = 'Loading\u2026';\n        try {\n            await onClick();\n        } catch (error) {\n            statusEl.className = 'mt-1 text-xs text-red-500';\n            statusEl.textContent = `Failed to load values: ${error.message}`;\n        } finally {\n            button.disabled = false;\n        }\n    });\n    return button;\n}\n\n/** Vytvo\u0159\u00ED sekci \"Categorized\" \u2014 v\u00FDb\u011Br atributu, rampa, Classify (WFS unik\u00E1tn\u00ED\n * hodnoty \u2192 kategorie) a editovateln\u00FD seznam kategori\u00ED + \"Other values\". */\nfunction categorizedSection(ctx, entry, onAnyChange) {\n    const cat = entry.style.categorized;\n    const attributes = uniqueAttributes(entry);\n    let classifyBtn = null;\n    entry.uiState = entry.uiState || {};\n    entry.uiState.categorizedRamp = entry.uiState.categorizedRamp || 'set1';\n\n    const box = document.createElement('div');\n    box.appendChild(sectionTitle('Categorized'));\n    box.appendChild(selectInput('Attribute', cat.attribute || '', [\n        { value: '', label: '\u2014 select attribute \u2014' },\n        ...attributes.map((a) => ({ value: a.name, label: a.name })),\n    ], (v) => {\n        cat.attribute = v || null;\n        delete entry.uiState.classifyNote;\n        // Panel se po v\u00FDb\u011Bru nep\u0159ekresluje \u2014 \u201EClassify\u201C odemknout hned.\n        if (classifyBtn) classifyBtn.disabled = !cat.attribute;\n        onAnyChange();\n    }));\n\n    const preview = document.createElement('span');\n    preview.className = 'h-4 w-10 flex-none rounded border border-slate-200';\n    preview.style.background = rampPreviewGradient(entry.uiState.categorizedRamp);\n    const rampRow = document.createElement('div');\n    rampRow.className = 'flex items-center gap-x-2';\n    rampRow.appendChild(selectInput('Ramp', entry.uiState.categorizedRamp, listRamps('categorical').map((r) => ({ value: r.key, label: r.label })), (v) => {\n        entry.uiState.categorizedRamp = v;\n        preview.style.background = rampPreviewGradient(v);\n    }));\n    rampRow.appendChild(preview);\n    box.appendChild(rampRow);\n\n    const status = classifyNoteElement(entry, 'categorized');\n\n    classifyBtn = classifyButton('Classify', status, async () => {\n        if (!cat.attribute) throw new Error('Select an attribute first.');\n        const typenames = sublayersWithAttribute(entry, cat.attribute);\n        if (typenames.length === 0) throw new Error('Attribute not found in any sublayer.');\n        const results = await Promise.all(\n            typenames.map((name) => fetchValueCounts(ctx.bootstrap, entry, name, cat.attribute)),\n        );\n        const counts = new Map();\n        results.forEach((r) => r.counts.forEach((n, value) => counts.set(value, (counts.get(value) || 0) + n)));\n        const sampled = results.some((r) => r.truncated);\n        if (counts.size === 0) throw new Error('The attribute has no values.');\n        // V\u00EDc hodnot, ne\u017E kolik kategori\u00ED m\u00E1 smysl: ty nej\u010Dast\u011Bj\u0161\u00ED, zbytek\n        // nakresl\u00ED \u201EOther values\u201C (jinak by z mapy zmizel).\n        const picked = pickCategories(counts, MAX_CATEGORIES);\n        const colors = getRampColors(entry.uiState.categorizedRamp, picked.values.length);\n        cat.categories = picked.values.map((value, i) => ({ value: String(value), label: String(value), color: colors[i] }));\n        if (picked.truncated && cat.other) cat.other.enabled = true;\n        const from = sampled ? ` (counted in the first ${VALUE_READ_LIMIT.toLocaleString('en')} features)` : '';\n        rememberClassifyNote(entry, 'categorized', picked.truncated\n            ? `Showing the ${picked.values.length} most common of ${picked.distinct.toLocaleString('en')} values${from} \u2014 the rest are drawn as \u201COther values\u201D.`\n            : `Loaded ${cat.categories.length} categories${from}.`, picked.truncated || sampled);\n        onAnyChange();\n        renderStylePanel(ctx, entry);\n    });\n    classifyBtn.disabled = !cat.attribute;\n    box.appendChild(classifyBtn);\n    box.appendChild(status);\n\n    box.appendChild(categoriesList(cat, ctx, entry, onAnyChange));\n\n    box.appendChild(checkboxInput('Other values', Boolean(cat.other?.enabled), (checked) => {\n        cat.other.enabled = checked;\n        onAnyChange();\n        renderStylePanel(ctx, entry);\n    }));\n    if (cat.other?.enabled) {\n        box.appendChild(colorInput('Other color', cat.other.color, (v) => { cat.other.color = v; onAnyChange(); }));\n    }\n    return box;\n}\n\n/** Jeden \u0159\u00E1dek editovateln\u00E9ho seznamu t\u0159\u00EDd (barva, min, max, popisek, smaz\u00E1n\u00ED). */\nfunction classRow(cls, classes, index, ctx, entry, onAnyChange) {\n    const row = document.createElement('div');\n    row.className = 'flex items-center gap-x-1.5';\n    row.appendChild(colorInput('', cls.color, (v) => { cls.color = v; onAnyChange(); }));\n    row.appendChild(numberInput('Min', cls.min, (v) => { cls.min = v; onAnyChange(); }));\n    row.appendChild(numberInput('Max', cls.max, (v) => { cls.max = v; onAnyChange(); }));\n    row.appendChild(textInput('Label', cls.label, (v) => { cls.label = v; onAnyChange(); }));\n    row.appendChild(removeButton(() => {\n        classes.splice(index, 1);\n        onAnyChange();\n        renderStylePanel(ctx, entry);\n    }));\n    return row;\n}\n\n/** Editovateln\u00FD seznam t\u0159\u00EDd (graduated) + tla\u010D\u00EDtko \"+ Add class\". */\nfunction classesList(grad, ctx, entry, onAnyChange) {\n    const wrap = document.createElement('div');\n    wrap.className = 'mt-2 space-y-1';\n    (grad.classes || []).forEach((cls, index) => {\n        wrap.appendChild(classRow(cls, grad.classes, index, ctx, entry, onAnyChange));\n    });\n    const addBtn = document.createElement('button');\n    addBtn.type = 'button';\n    addBtn.className = 'mt-1 w-full rounded-lg border border-dashed border-slate-300 px-2 py-1 text-xs text-slate-500 hover:border-brand-300 hover:text-brand-600';\n    addBtn.textContent = '+ Add class';\n    addBtn.addEventListener('click', () => {\n        grad.classes = grad.classes || [];\n        const last = grad.classes[grad.classes.length - 1];\n        const min = last ? last.max : 0;\n        const max = min + 1;\n        grad.classes.push({ min, max, label: formatClassLabel(min, max), color: '#999999' });\n        onAnyChange();\n        renderStylePanel(ctx, entry);\n    });\n    wrap.appendChild(addBtn);\n    return wrap;\n}\n\n/** Vytvo\u0159\u00ED sekci \"Graduated\" \u2014 v\u00FDb\u011Br \u010D\u00EDseln\u00E9ho atributu, metoda klasifikace,\n * po\u010Det t\u0159\u00EDd, rampa, Classify (WFS hodnoty \u2192 t\u0159\u00EDdy) a editovateln\u00FD seznam t\u0159\u00EDd. */\nfunction graduatedSection(ctx, entry, onAnyChange) {\n    const grad = entry.style.graduated;\n    const attributes = numericAttributes(entry);\n    let classifyBtn = null;\n    entry.uiState = entry.uiState || {};\n    entry.uiState.graduatedRamp = entry.uiState.graduatedRamp || 'blues';\n\n    const box = document.createElement('div');\n    box.appendChild(sectionTitle('Graduated'));\n    box.appendChild(selectInput('Attribute', grad.attribute || '', [\n        { value: '', label: '\u2014 select attribute \u2014' },\n        ...attributes.map((a) => ({ value: a.name, label: a.name })),\n    ], (v) => {\n        grad.attribute = v || null;\n        delete entry.uiState.classifyNote;\n        if (classifyBtn) classifyBtn.disabled = !grad.attribute;\n        onAnyChange();\n    }));\n    box.appendChild(selectInput('Method', grad.method, CLASSIFICATION_METHODS, (v) => { grad.method = v; onAnyChange(); }));\n    box.appendChild(rangeInput('Classes', grad.classCount, 2, 9, 1, (v) => { grad.classCount = v; onAnyChange(); }));\n\n    const preview = document.createElement('span');\n    preview.className = 'h-4 w-10 flex-none rounded border border-slate-200';\n    preview.style.background = rampPreviewGradient(entry.uiState.graduatedRamp);\n    const rampRow = document.createElement('div');\n    rampRow.className = 'flex items-center gap-x-2';\n    rampRow.appendChild(selectInput('Ramp', entry.uiState.graduatedRamp, [\n        ...listRamps('sequential').map((r) => ({ value: r.key, label: r.label })),\n        ...listRamps('diverging').map((r) => ({ value: r.key, label: r.label })),\n    ], (v) => {\n        entry.uiState.graduatedRamp = v;\n        preview.style.background = rampPreviewGradient(v);\n    }));\n    rampRow.appendChild(preview);\n    box.appendChild(rampRow);\n\n    const status = classifyNoteElement(entry, 'graduated');\n\n    classifyBtn = classifyButton('Classify', status, async () => {\n        if (!grad.attribute) throw new Error('Select a numeric attribute first.');\n        const typenames = sublayersWithAttribute(entry, grad.attribute);\n        if (typenames.length === 0) throw new Error('Attribute not found in any sublayer.');\n        let classes;\n        let truncated = false;\n        if (grad.method === 'equal') {\n            // Equal interval pot\u0159ebuje jen min/max \u2014 sta\u010D\u00ED dva rychl\u00E9 po\u017Eadavky.\n            const minMax = await Promise.all(\n                typenames.map((name) => fetchMinMax(ctx.bootstrap, entry, name, grad.attribute)),\n            );\n            const mins = minMax.map((r) => r.min).filter((v) => v !== null);\n            const maxs = minMax.map((r) => r.max).filter((v) => v !== null);\n            if (mins.length === 0 || maxs.length === 0) throw new Error('No numeric values found.');\n            classes = classify([Math.min(...mins), Math.max(...maxs)], 'equal', grad.classCount);\n        } else {\n            // Quantile/Jenks pot\u0159ebuj\u00ED celou distribuci \u2014 hodnoty atributu\n            // z nejv\u00FD\u0161 VALUE_READ_LIMIT prvk\u016F (Jenks po\u010D\u00EDt\u00E1 ze vzorku, classify.js).\n            const results = await Promise.all(\n                typenames.map((name) => fetchNumericValues(ctx.bootstrap, entry, name, grad.attribute)),\n            );\n            const values = results.flatMap((r) => r.values);\n            truncated = results.some((r) => r.truncated);\n            if (values.length === 0) throw new Error('No numeric values found.');\n            classes = classify(values, grad.method, grad.classCount);\n        }\n        const colors = getRampColors(entry.uiState.graduatedRamp, classes.length);\n        grad.classes = classes.map((c, i) => ({\n            min: c.min, max: c.max, label: formatClassLabel(c.min, c.max), color: colors[i],\n        }));\n        const fewer = grad.classes.length < grad.classCount\n            ? ` \u2014 the data have too few distinct values for ${grad.classCount}`\n            : '';\n        rememberClassifyNote(entry, 'graduated', truncated\n            ? `Loaded ${grad.classes.length} classes${fewer} (computed from the first ${VALUE_READ_LIMIT.toLocaleString('en')} features).`\n            : `Loaded ${grad.classes.length} classes${fewer}.`, truncated);\n        onAnyChange();\n        renderStylePanel(ctx, entry);\n    });\n    classifyBtn.disabled = !grad.attribute;\n    box.appendChild(classifyBtn);\n    box.appendChild(status);\n\n    box.appendChild(classesList(grad, ctx, entry, onAnyChange));\n    return box;\n}\n\n/** Vytvo\u0159\u00ED sekci \"Labels\" (labels) \u2014 atribut se vyb\u00EDr\u00E1 z `entry.attributes`. */\n/** Tla\u010D\u00EDtka jedn\u00E9 volby vedle sebe (`[{value, label, title}]`, label sm\u00ED b\u00FDt\n * SVG). Zm\u011Bna se neukl\u00E1d\u00E1 sama \u2014 `onChange(value)`. */\nfunction segmented(options, value, onChange) {\n    const wrap = document.createElement('span');\n    wrap.className = 'inline-flex flex-none overflow-hidden rounded border border-slate-200';\n    options.forEach((option, index) => {\n        const button = document.createElement('button');\n        button.type = 'button';\n        const active = option.value === value;\n        button.className = `flex items-center px-1.5 py-0.5 text-xs ${index ? 'border-l border-slate-200' : ''} ${active ? 'bg-brand-50 text-brand-700' : 'text-slate-600 hover:bg-slate-50'}`;\n        button.setAttribute('aria-pressed', active ? 'true' : 'false');\n        if (option.title) {\n            button.title = option.title;\n            button.setAttribute('aria-label', option.title);\n        }\n        button.innerHTML = option.label;\n        button.addEventListener('click', () => onChange(option.value));\n        wrap.appendChild(button);\n    });\n    return wrap;\n}\n\nfunction labeledRow(label, control) {\n    const row = document.createElement('div');\n    row.className = 'flex items-center justify-between gap-x-2 text-xs text-slate-600';\n    const name = document.createElement('span');\n    name.className = 'flex-none';\n    name.textContent = label;\n    row.append(name, control);\n    return row;\n}\n\nconst POSITION_TITLES = {\n    tl: 'Top left', t: 'Above', tr: 'Top right', l: 'Left', c: 'On the point',\n    r: 'Right', bl: 'Bottom left', b: 'Below', br: 'Bottom right',\n};\n\n/** M\u0159\u00ED\u017Eka 3 \u00D7 3 s bodem uprost\u0159ed: kam popisek bodu pat\u0159\u00ED; vedle \u201EAuto\u201C. */\nfunction positionPicker(value, onChange) {\n    const wrap = document.createElement('span');\n    wrap.className = 'flex items-center gap-x-1.5';\n    const grid = document.createElement('span');\n    grid.className = 'grid grid-cols-3 gap-px overflow-hidden rounded border border-slate-300 bg-slate-300';\n    grid.setAttribute('role', 'group');\n    grid.setAttribute('aria-label', 'Label position');\n    LABEL_POSITIONS.forEach((position) => {\n        const cell = document.createElement('button');\n        cell.type = 'button';\n        const active = position === value;\n        cell.className = `flex h-4 w-6 items-center justify-center ${active ? 'bg-brand-50' : 'bg-white hover:bg-slate-50'}`;\n        cell.title = POSITION_TITLES[position];\n        cell.setAttribute('aria-label', POSITION_TITLES[position]);\n        cell.setAttribute('aria-pressed', active ? 'true' : 'false');\n        // Bod uprost\u0159ed, v ostatn\u00EDch pol\u00ED\u010Dk\u00E1ch \u010D\u00E1rka \u201Etextu\u201C (vybran\u00E1 mod\u0159e).\n        cell.innerHTML = position === 'c'\n            ? `<span class=\"h-2 w-2 rounded-full ${active ? 'bg-brand-600' : 'bg-slate-500'}\"></span>`\n            : `<span class=\"h-1 w-3.5 rounded-sm ${active ? 'bg-brand-600' : 'bg-slate-200'}\"></span>`;\n        cell.addEventListener('click', () => onChange(position));\n        grid.appendChild(cell);\n    });\n    wrap.append(grid, segmented([{ value: 'auto', label: 'Auto', title: 'Free place around the point' }], value, onChange));\n    return wrap;\n}\n\n/** Mal\u00E9 obr\u00E1zky re\u017Eim\u016F popisku linie (vodorovn\u011B, pod\u00E9l, po k\u0159ivce). */\nconst WAVE = 'M1 9 C6 1 10 1 13 6 S20 11 25 3';\nconst LINE_ICON = (inner) => `<svg width=\"34\" height=\"16\" viewBox=\"0 0 26 12\" aria-hidden=\"true\"><path d=\"${WAVE}\" fill=\"none\" stroke=\"#64748b\" stroke-width=\"1.1\"/>${inner}</svg>`;\nconst LINE_MODE_OPTIONS = [\n    { value: 'horizontal', title: 'Horizontal', label: LINE_ICON('<text x=\"13\" y=\"4.6\" font-size=\"5\" font-weight=\"600\" text-anchor=\"middle\" fill=\"currentColor\">Abc</text>') },\n    { value: 'along', title: 'Straight along the line', label: LINE_ICON('<text x=\"16.5\" y=\"9.5\" font-size=\"5\" font-weight=\"600\" transform=\"rotate(-38 18 8)\" fill=\"currentColor\">Abc</text>') },\n    { value: 'follow', title: 'Follow the curve', label: LINE_ICON('<path id=\"lbl-wave\" d=\"M1 7.5 C6 -0.5 10 -0.5 13 4.5 S20 9.5 25 1.5\" fill=\"none\"/><text font-size=\"5\" font-weight=\"600\" fill=\"currentColor\"><textPath href=\"#lbl-wave\" startOffset=\"8%\">Abcdef</textPath></text>') },\n];\n\n/** Sekce \"Labels\" (varianta B): text, p\u00EDsmo, um\u00EDst\u011Bn\u00ED podle geometrie vrstvy,\n * p\u0159ibl\u00ED\u017Een\u00ED. Popis modelu v labels.js. */\nfunction labelsSection(ctx, entry, onAnyChange) {\n    const labels = entry.style.labels;\n    const change = (rerender = false) => {\n        onAnyChange();\n        if (rerender) renderStylePanel(ctx, entry);\n    };\n    const box = document.createElement('div');\n    box.className = 'space-y-1.5';\n    box.appendChild(sectionTitle('Labels'));\n    const head = document.createElement('div');\n    head.className = 'flex items-center justify-between gap-x-2';\n    head.appendChild(checkboxInput('Show labels', labels.enabled, (checked) => {\n        labels.enabled = checked;\n        if (checked && !labels.attribute) labels.attribute = labelFieldOf(entry.sublayers);\n        change(true);\n    }));\n    if (labels.enabled) {\n        const options = [\n            { value: '', label: '\u2014 attribute \u2014' },\n            ...uniqueAttributes(entry).map((a) => ({ value: a.name, label: a.name })),\n        ];\n        const select = selectInput('', labels.attribute || '', options, (v) => { labels.attribute = v || null; change(); });\n        select.querySelector('span').remove();\n        select.className = 'flex min-w-0 justify-end';\n        select.querySelector('select').setAttribute('aria-label', 'Label attribute');\n        head.appendChild(select);\n    }\n    box.appendChild(head);\n    if (!labels.enabled) return box;\n\n    const font = document.createElement('span');\n    font.className = 'flex items-center gap-x-1.5';\n    const sizes = [8, 9, 10, 11, 12, 13, 14, 16, 18, 20, 24];\n    if (!sizes.includes(labels.size)) sizes.push(labels.size);\n    const size = selectInput('', String(labels.size), sizes.sort((a, b) => a - b).map((n) => ({ value: String(n), label: String(n) })),\n        (v) => { labels.size = Number(v); change(); });\n    size.querySelector('span').remove();\n    size.className = 'flex flex-none';\n    const sizeSelect = size.querySelector('select');\n    sizeSelect.classList.remove('max-w-[65%]', 'min-w-0');\n    sizeSelect.classList.add('w-14', 'pr-6');\n    sizeSelect.setAttribute('aria-label', 'Font size');\n    font.append(\n        size,\n        segmented([{ value: true, label: '<b>B</b>', title: 'Bold' }], labels.bold === true, () => { labels.bold = !labels.bold; change(true); }),\n        colorInput('', labels.color, (v) => { labels.color = v; change(); }),\n        colorInput('', labels.halo, (v) => { labels.halo = v; change(); }),\n    );\n    font.querySelectorAll('input[type=\"color\"]').forEach((input, index) => {\n        input.title = index ? 'Halo' : 'Text color';\n        input.setAttribute('aria-label', input.title);\n    });\n    box.appendChild(labeledRow('Font', font));\n\n    const geometries = entry.geometryTypes || [];\n    if (geometries.includes('point')) {\n        box.appendChild(labeledRow(geometries.length > 1 ? 'Points' : 'Position',\n            positionPicker(labels.position, (v) => { labels.position = v; change(true); })));\n        const rotation = labels.rotation;\n        box.appendChild(labeledRow('Rotation', segmented([\n            { value: 'none', label: 'None' }, { value: 'angle', label: 'Angle' }, { value: 'field', label: 'Attribute' },\n        ], rotation.mode, (v) => {\n            rotation.mode = v;\n            if (v === 'field' && !rotation.field) rotation.field = numericAttributes(entry)[0]?.name || null;\n            change(true);\n        })));\n        if (rotation.mode === 'angle') {\n            box.appendChild(rangeInput('Angle (clockwise)', rotation.angle || 0, -180, 180, 5,\n                (v) => { rotation.angle = v; change(); }, (v) => `${v}\u00B0`));\n        } else if (rotation.mode === 'field') {\n            box.appendChild(selectInput('Angle from', rotation.field || '', [\n                { value: '', label: '\u2014 attribute \u2014' },\n                ...numericAttributes(entry).map((a) => ({ value: a.name, label: a.name })),\n            ], (v) => { rotation.field = v || null; change(); }));\n            box.appendChild(selectInput('Direction', rotation.clockwise === false ? 'ccw' : 'cw', [\n                { value: 'cw', label: 'Clockwise' }, { value: 'ccw', label: 'Counter-clockwise' },\n            ], (v) => { rotation.clockwise = v === 'cw'; change(); }));\n        }\n    }\n    if (geometries.includes('line')) {\n        box.appendChild(labeledRow(geometries.length > 1 ? 'Lines' : 'Along lines',\n            segmented(LINE_MODE_OPTIONS, labels.line, (v) => { labels.line = v; change(true); })));\n        box.appendChild(checkboxInput('Repeat on long lines', labels.repeat, (checked) => { labels.repeat = checked; change(); }));\n    }\n    if (geometries.includes('line') || geometries.includes('polygon')) {\n        box.appendChild(checkboxInput('Only where the label fits', labels.fit, (checked) => { labels.fit = checked; change(); }));\n    }\n    const auto = entryAutoLabelMinZoom(entry);\n    const zoomValue = labels.minZoom === 'auto' ? 'auto' : (Number.isFinite(labels.minZoom) ? String(labels.minZoom) : 'always');\n    box.appendChild(selectInput('From zoom', zoomValue, [\n        { value: 'auto', label: `Auto (${auto === null ? 'always' : auto})` },\n        { value: 'always', label: 'Always' },\n        ...Array.from({ length: 20 }, (_, i) => ({ value: String(i + 1), label: String(i + 1) })),\n    ], (v) => {\n        labels.minZoom = v === 'auto' ? 'auto' : (v === 'always' ? null : Number(v));\n        change();\n    }));\n    return box;\n}\n\n/** Popisek p\u00E1sma v nab\u00EDdce: \u010D\u00EDslo, v\u00FDznam (Red/NIR\u2026) a datov\u00FD typ. */\nfunction bandLabel(band) {\n    const interp = band.colorInterp && !['undefined', 'gray'].includes(String(band.colorInterp).toLowerCase())\n        ? ` \u00B7 ${band.colorInterp}` : '';\n    const type = band.data_type || band.dataType || '';\n    return `Band ${band.index}${interp}${type ? ` (${type})` : ''}`;\n}\n\n/** Mal\u00FD n\u00E1hled barevn\u00E9 mapy vedle jej\u00EDho v\u00FDb\u011Bru. */\nfunction colormapPreview(colors) {\n    const preview = document.createElement('span');\n    preview.className = 'h-4 w-12 flex-none rounded border border-slate-200';\n    preview.style.background = `linear-gradient(to right, ${(colors || ['#000', '#fff']).join(', ')})`;\n    return preview;\n}\n\nconst COLORMAP_LABELS = {\n    gray: 'Greys', terrain: 'Terrain (elevation)', viridis: 'Viridis', magma: 'Magma', turbo: 'Turbo',\n    blues: 'Blues', greens: 'Greens', ylorrd: 'Yellow\u2013red', rdylgn: 'Red\u2013yellow\u2013green (NDVI)', spectral: 'Spectral',\n};\n\n/**\n * Panel stylu rastru:\n * - **Rendering**: paleta souboru / RGB kompozice / jedno p\u00E1smo \u0161ed\u011B / jedno\n *   p\u00E1smo barevnou mapou (nab\u00EDz\u00ED se jen to, co pro dan\u00FD rastr d\u00E1v\u00E1 smysl),\n * - v\u00FDb\u011Br p\u00E1sem,\n * - **Contrast**: rozta\u017Een\u00ED mezi percentily (od\u0159\u00EDzne odlehl\u00E9 hodnoty),\n *   min\u2013max, nebo bez rozta\u017Een\u00ED (jen 8bitov\u00E9 RGB); p\u0159\u00EDpadn\u011B ru\u010Dn\u00ED rozsah.\n */\nfunction rasterSection(ctx, entry, onAnyChange) {\n    const { style } = entry;\n    const bandList = entry.bands || [];\n    const bandOptions = bandList.map((b) => ({ value: String(b.index), label: bandLabel(b) }));\n    const hasPalette = Boolean(entry.raster?.palette?.length);\n    const colormaps = entry.raster?.colormaps || {};\n    const rerender = () => { onAnyChange(); renderStylePanel(ctx, entry); };\n\n    const box = document.createElement('div');\n    box.appendChild(sectionTitle('Rendering'));\n    const modes = [];\n    if (hasPalette) modes.push({ value: 'palette', label: 'Colours of the file (palette)' });\n    if (bandList.length >= 3) modes.push({ value: 'rgb', label: 'Colour composite (RGB)' });\n    modes.push({ value: 'gray', label: 'Single band \u2014 greyscale' });\n    modes.push({ value: 'ramp', label: 'Single band \u2014 colour map' });\n    if (!modes.some((m) => m.value === style.mode)) style.mode = modes[0].value;\n    box.appendChild(selectInput('Mode', style.mode, modes, (v) => {\n        style.mode = v;\n        // 8bitov\u00E1 kompozice se kresl\u00ED tak, jak je; jedno p\u00E1smo pot\u0159ebuje rozta\u017Een\u00ED.\n        if (v !== 'rgb' && style.stretch.type === 'none') style.stretch.type = 'percent';\n        rerender();\n    }));\n\n    if (style.mode === 'palette') {\n        const note = document.createElement('p');\n        note.className = 'mt-2 text-xs text-slate-500';\n        note.textContent = 'The file defines a colour for each value.';\n        box.appendChild(note);\n        return box;\n    }\n\n    if (style.mode === 'rgb') {\n        box.appendChild(selectInput('Red', String(style.bands.r), bandOptions, (v) => { style.bands.r = Number(v); onAnyChange(); }));\n        box.appendChild(selectInput('Green', String(style.bands.g), bandOptions, (v) => { style.bands.g = Number(v); onAnyChange(); }));\n        box.appendChild(selectInput('Blue', String(style.bands.b), bandOptions, (v) => { style.bands.b = Number(v); onAnyChange(); }));\n    } else {\n        // V\u00FDb\u011Br konkr\u00E9tn\u00EDho p\u00E1sma m\u00E1 smysl jen u v\u00EDcep\u00E1smov\u00FDch rastr\u016F.\n        if (bandList.length > 1) {\n            box.appendChild(selectInput('Band', String(style.band), bandOptions, (v) => { style.band = Number(v); onAnyChange(); }));\n        }\n        if (style.mode === 'ramp') {\n            const names = Object.keys(colormaps).length ? Object.keys(colormaps) : Object.keys(COLORMAP_LABELS);\n            if (!names.includes(style.colormap)) [style.colormap] = names;\n            const row = document.createElement('div');\n            row.className = 'flex items-center gap-x-2';\n            const preview = colormapPreview(colormaps[style.colormap]);\n            row.appendChild(selectInput('Colours', style.colormap, names.map((name) => ({\n                value: name, label: COLORMAP_LABELS[name] || name,\n            })), (v) => {\n                style.colormap = v;\n                preview.style.background = `linear-gradient(to right, ${(colormaps[v] || ['#000', '#fff']).join(', ')})`;\n                onAnyChange();\n            }));\n            row.appendChild(preview);\n            box.appendChild(row);\n        }\n    }\n\n    box.appendChild(sectionTitle('Contrast'));\n    const allByte = bandList.length > 0 && bandList.every((b) => String(b.data_type || '').toLowerCase() === 'byte');\n    const stretchOptions = [\n        { value: 'percent', label: 'Stretch, ignore outliers' },\n        { value: 'minmax', label: 'Stretch, minimum to maximum' },\n    ];\n    // \u201EBez rozta\u017Een\u00ED\u201C jen u 8bitov\u00E9 kompozice \u2014 jin\u00E1 data by byla \u010Dern\u00E1.\n    if (style.mode === 'rgb' && allByte) stretchOptions.push({ value: 'none', label: 'As stored (no stretch)' });\n    if (style.range) stretchOptions.push({ value: 'range', label: 'Fixed range of values' });\n    else stretchOptions.push({ value: 'range', label: 'Fixed range of values\u2026' });\n    const stretchValue = style.range ? 'range' : (stretchOptions.some((o) => o.value === style.stretch.type) ? style.stretch.type : 'percent');\n    box.appendChild(selectInput('Method', stretchValue, stretchOptions, (v) => {\n        if (v === 'range') {\n            // V\u00FDchoz\u00ED ru\u010Dn\u00ED rozsah = to, co je pr\u00E1v\u011B vid\u011Bt (\u0161k\u00E1la z Mapserveru).\n            const scale = (entry.rasterRendering || entry.raster?.rendering)?.scales?.[0];\n            const band = bandList.find((b) => b.index === (style.mode === 'rgb' ? style.bands.r : style.band)) || bandList[0];\n            const min = Number.isFinite(scale?.[0]) ? scale[0] : (band?.min ?? 0);\n            const max = Number.isFinite(scale?.[1]) ? scale[1] : (band?.max ?? 255);\n            style.range = [Number(Number(min).toPrecision(4)), Number(Number(max).toPrecision(4))];\n        } else {\n            style.range = null;\n            style.stretch.type = v;\n        }\n        rerender();\n    }));\n    if (style.range) {\n        const row = document.createElement('div');\n        row.className = 'flex items-center justify-between gap-x-2 text-xs text-slate-600';\n        const label = document.createElement('span');\n        label.textContent = 'From \u2013 to';\n        const inputs = document.createElement('span');\n        inputs.className = 'flex items-center gap-x-1';\n        const apply = () => {\n            const [min, max] = [Number(minInput.value), Number(maxInput.value)];\n            if (Number.isFinite(min) && Number.isFinite(max) && min < max) {\n                style.range = [min, max];\n                onAnyChange();\n            }\n        };\n        const minInput = numberInput('Min', style.range[0], apply, 'w-20 flex-none');\n        const maxInput = numberInput('Max', style.range[1], apply, 'w-20 flex-none');\n        inputs.append(minInput, maxInput);\n        row.append(label, inputs);\n        box.appendChild(row);\n    } else if (style.stretch.type === 'percent') {\n        box.appendChild(rangeInput('Cut dark', style.stretch.clip[0], 0, 20, 0.5, (v) => { style.stretch.clip[0] = v; onAnyChange(); }, (v) => `${v}%`));\n        box.appendChild(rangeInput('Cut bright', 100 - style.stretch.clip[1], 0, 20, 0.5, (v) => { style.stretch.clip[1] = 100 - v; onAnyChange(); }, (v) => `${v}%`));\n    }\n    box.appendChild(transparentValueRow(style, onAnyChange));\n    return box;\n}\n\n/** \u201ETransparent value\u201C: hodnota bu\u0148ky, kter\u00E1 se nekresl\u00ED \u2014 \u010Dern\u00FD okraj skenu\n * (0), konstantn\u00ED mo\u0159e u st\u00EDnovan\u00E9ho reli\u00E9fu\u2026 Pr\u00E1zdn\u00E9 pole = no-data ze souboru. */\nfunction transparentValueRow(style, onAnyChange) {\n    const row = document.createElement('label');\n    row.className = 'mt-1 flex items-center justify-between gap-x-2 text-xs text-slate-600';\n    row.title = 'Cells with this value are not drawn \u2014 e.g. 0 for the black border of a scan. Leave empty to use the no-data value stored in the file.';\n    const label = document.createElement('span');\n    label.textContent = 'Transparent value';\n    const input = numberInput('from the file', Number.isFinite(style.nodata) ? style.nodata : '', () => {\n        const text = input.value.trim();\n        const value = Number(text);\n        style.nodata = text !== '' && Number.isFinite(value) ? value : null;\n        onAnyChange();\n    }, 'w-24 flex-none');\n    row.append(label, input);\n    return row;\n}\n\n/** Znovu vykresl\u00ED stylovac\u00ED panel pro vrstvu (vol\u00E1no i po struktur\u00E1ln\u00EDch\n * zm\u011Bn\u00E1ch, nap\u0159. zapnut\u00ED/vypnut\u00ED popisk\u016F nebo casingu). */\nexport function renderStylePanel(ctx, entry) {\n    const row = ctx.elements.layerTree?.querySelector(`[data-uid=\"${entry.uid}\"]`);\n    if (!row) return;\n    const container = getStylePanelContainer(row);\n    container.innerHTML = '';\n\n    // Pr\u016Fhlednost je prvn\u00ED polo\u017Ekou panelu u ka\u017Ed\u00E9ho typu vrstvy.\n    container.appendChild(opacitySection(ctx, entry));\n\n    // Kresba a dla\u017Edicov\u00E9/WMS slu\u017Eby vlastn\u00ED styl nemaj\u00ED.\n    const styleable = entry.dataType === 'raster' || entry.dataType === 'local'\n        || (entry.dataType === 'vector' && !entry.external);\n    if (!styleable) return;\n\n    const onAnyChange = () => {\n        ctx.state.dirty = true;\n        scheduleWmsRefresh(entry);\n        refreshLayerRow(ctx, entry);\n        if (entry.dataType === 'raster') updateRasterLegend(ctx, entry);\n        emit('style:changed', { entry });\n    };\n\n    if (entry.dataType === 'raster') {\n        container.appendChild(rasterSection(ctx, entry, onAnyChange));\n        return;\n    }\n\n    // Lok\u00E1ln\u00ED vrstva (vlo\u017Een\u00E1/sta\u017Een\u00E1 data, external.js) \u2014 klientsk\u00E9 OL\n    // stylov\u00E1n\u00ED s jedinou barvou, bez SLD (viz docs/maps.md).\n    if (entry.dataType === 'local') {\n        const box = document.createElement('div');\n        box.appendChild(colorInput('Color', entry.localColor || '#7c3aed', (v) => {\n            setLocalLayerColor(ctx, entry, v);\n            refreshLayerRow(ctx, entry);\n        }));\n        container.appendChild(box);\n        return;\n    }\n\n    container.appendChild(modeSwitcher(ctx, entry, onAnyChange));\n\n    if (entry.style.mode === 'native' && entry.native?.available) {\n        container.appendChild(nativeSection(entry));\n        return;\n    }\n\n    if (entry.style.mode === 'categorized') {\n        container.appendChild(categorizedSection(ctx, entry, onAnyChange));\n    } else if (entry.style.mode === 'graduated') {\n        container.appendChild(graduatedSection(ctx, entry, onAnyChange));\n    }\n\n    // Vlastnosti symbolu per geometrie z\u016Fst\u00E1vaj\u00ED editovateln\u00E9 i v categorized/\n    // graduated re\u017Eimu (velikost, obrys, tvar\u2026) \u2014 jen barvu p\u0159eb\u00EDr\u00E1 kategorie/t\u0159\u00EDda.\n    const isClassified = entry.style.mode === 'categorized' || entry.style.mode === 'graduated';\n    if (entry.geometryTypes.includes('polygon')) container.appendChild(polygonSection(ctx, entry, onAnyChange, isClassified));\n    if (entry.geometryTypes.includes('line')) container.appendChild(lineSection(ctx, entry, onAnyChange, isClassified));\n    if (entry.geometryTypes.includes('point')) container.appendChild(pointSection(ctx, entry, onAnyChange, isClassified));\n    container.appendChild(labelsSection(ctx, entry, onAnyChange));\n\n    // N\u00E1vrat k n\u00E1vrhu podle druhu dat (silnice, vodstvo\u2026), pokud n\u011Bjak\u00FD je.\n    if (entry.suggested?.length) {\n        const reset = document.createElement('button');\n        reset.type = 'button';\n        reset.className = 'mt-3 text-xs text-slate-400 underline-offset-2 hover:text-brand-600 hover:underline';\n        reset.textContent = 'Reset to the suggested style';\n        reset.addEventListener('click', () => {\n            entry.style = applyDefaultLabels(applyPhotoMarker(normalizeVectorStyle(styleFromSuggestions(entry.suggested)), entry.sublayers, entry.suggested), entry.sublayers);\n            onAnyChange();\n            renderStylePanel(ctx, entry);\n        });\n        container.appendChild(reset);\n    }\n}\n\n/** Zap\u00EDn\u00E1/vyp\u00EDn\u00E1 viditelnost panelu (tla\u010D\u00EDtko stylu v \u0159\u00E1dku vrstvy).\n * `open: true` panel jen otev\u0159e (klik na \u0161t\u00EDtek pr\u016Fhlednosti). */\nexport function toggleStylePanel(ctx, uid, row, { open = false } = {}) {\n    const entry = findEntryByUid(ctx.state, uid);\n    if (!entry || entry.isGroup) return;\n    const container = getStylePanelContainer(row);\n    const isHidden = container.classList.contains('hidden');\n    if (isHidden) {\n        renderStylePanel(ctx, entry);\n        container.classList.remove('hidden');\n    } else if (!open) {\n        container.classList.add('hidden');\n    }\n}\n", "/** popup-dom.js \u2014 drobnosti pro HTML \u0161ablony popupu (data jsou v\u017Edy escapovan\u00E1). */\n\n/** Text jako bezpe\u010Dn\u00FD obsah HTML / hodnota atributu v uvozovk\u00E1ch. */\nexport function escapeHtml(value) {\n    return String(value)\n        .replace(/&/g, '&amp;')\n        .replace(/</g, '&lt;')\n        .replace(/>/g, '&gt;')\n        .replace(/\"/g, '&quot;')\n        .replace(/'/g, '&#39;');\n}\n", "/**\n * gallery.js \u2014 fotky prvku p\u0159es cel\u00E9 okno (klik na fotku v popupu).\n *\n * Nativn\u00ED `<dialog>` (mod\u00E1ln\u00ED: zachyt\u00ED fokus, Esc zav\u0159e), tmav\u00E9 pozad\u00ED,\n * fotka p\u0159izp\u016Fsoben\u00E1 oknu, \u0161ipky a kl\u00E1vesy \u2190/\u2192 mezi fotkami prvku, n\u00E1hledy\n * dole a odkaz \u201EOriginal\u201C (nov\u00E9 okno bez p\u0159\u00EDstupu k map\u011B). Obr\u00E1zky se na\u010D\u00EDtaj\u00ED\n * bez hlavi\u010Dky Referer, jako v popupu.\n */\nimport { escapeHtml } from './popup-dom.js';\n\nlet dialog = null;\nlet photos = [];\nlet index = 0;\n\nfunction ensureDialog() {\n    if (dialog) return dialog;\n    dialog = document.createElement('dialog');\n    dialog.className = 'map-gallery';\n    dialog.setAttribute('aria-label', 'Photos');\n    dialog.innerHTML = `\n        <div class=\"map-gallery-bar\">\n            <span class=\"map-gallery-title\" data-role=\"title\"></span>\n            <span class=\"map-gallery-count\" data-role=\"count\"></span>\n            <a class=\"map-gallery-original\" data-role=\"original\" target=\"_blank\" rel=\"noopener noreferrer nofollow\">\n                <svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" aria-hidden=\"true\"><path d=\"M14 4h6v6M10 14 20 4M19 14v5a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V6a1 1 0 0 1 1-1h5\"/></svg>\n                Original\n            </a>\n            <button type=\"button\" class=\"map-gallery-close\" data-role=\"close\" aria-label=\"Close\">\n                <svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" aria-hidden=\"true\"><path d=\"M18 6 6 18M6 6l12 12\"/></svg>\n            </button>\n        </div>\n        <div class=\"map-gallery-stage\">\n            <button type=\"button\" class=\"map-gallery-nav\" data-role=\"prev\" aria-label=\"Previous photo\">\n                <svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" aria-hidden=\"true\"><path d=\"m15 6-6 6 6 6\"/></svg>\n            </button>\n            <img data-role=\"image\" alt=\"\" referrerpolicy=\"no-referrer\" decoding=\"async\">\n            <p class=\"map-gallery-error\" data-role=\"error\" hidden>The photo could not be loaded.</p>\n            <button type=\"button\" class=\"map-gallery-nav\" data-role=\"next\" aria-label=\"Next photo\">\n                <svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" aria-hidden=\"true\"><path d=\"m9 6 6 6-6 6\"/></svg>\n            </button>\n        </div>\n        <div class=\"map-gallery-thumbs\" data-role=\"thumbs\"></div>`;\n    document.body.appendChild(dialog);\n    const image = dialog.querySelector('[data-role=\"image\"]');\n    image.addEventListener('error', () => {\n        image.hidden = true;\n        dialog.querySelector('[data-role=\"error\"]').hidden = false;\n    });\n    image.addEventListener('load', () => {\n        image.hidden = false;\n        dialog.querySelector('[data-role=\"error\"]').hidden = true;\n    });\n    dialog.querySelector('[data-role=\"close\"]').addEventListener('click', () => dialog.close());\n    dialog.querySelector('[data-role=\"prev\"]').addEventListener('click', () => show(index - 1));\n    dialog.querySelector('[data-role=\"next\"]').addEventListener('click', () => show(index + 1));\n    dialog.addEventListener('keydown', (event) => {\n        if (event.key === 'ArrowLeft') {\n            event.preventDefault();\n            show(index - 1);\n        } else if (event.key === 'ArrowRight') {\n            event.preventDefault();\n            show(index + 1);\n        }\n    });\n    // Klik mimo fotku a ovl\u00E1d\u00E1n\u00ED (na tmav\u00E9 pozad\u00ED) okno zav\u0159e.\n    dialog.addEventListener('click', (event) => {\n        if (event.target === dialog || event.target.classList.contains('map-gallery-stage')) dialog.close();\n    });\n    dialog.querySelector('[data-role=\"thumbs\"]').addEventListener('click', (event) => {\n        const button = event.target.closest('[data-index]');\n        if (button) show(Number(button.dataset.index));\n    });\n    return dialog;\n}\n\nfunction show(next) {\n    if (!photos.length) return;\n    index = (next + photos.length) % photos.length;\n    const photo = photos[index];\n    const image = dialog.querySelector('[data-role=\"image\"]');\n    image.src = photo.src;\n    image.alt = photo.title || `Photo ${index + 1}`;\n    dialog.querySelector('[data-role=\"title\"]').textContent = photo.title || '';\n    dialog.querySelector('[data-role=\"count\"]').textContent = photos.length > 1 ? `${index + 1} / ${photos.length}` : '';\n    const original = dialog.querySelector('[data-role=\"original\"]');\n    original.href = photo.src;\n    original.hidden = photo.src.startsWith('data:');\n    const many = photos.length > 1;\n    dialog.querySelectorAll('.map-gallery-nav').forEach((button) => { button.hidden = !many; });\n    dialog.querySelectorAll('[data-index]').forEach((button) => {\n        button.classList.toggle('is-current', Number(button.dataset.index) === index);\n    });\n}\n\n/** Otev\u0159e galerii `items` (`[{src, title}]`) na fotce `start`. */\nexport function openGallery(items, start = 0) {\n    if (!items?.length) return;\n    ensureDialog();\n    photos = items;\n    const thumbs = dialog.querySelector('[data-role=\"thumbs\"]');\n    thumbs.hidden = items.length < 2;\n    thumbs.innerHTML = items.map((photo, i) => `\n        <button type=\"button\" data-index=\"${i}\" aria-label=\"Photo ${i + 1}\">\n            <img src=\"${escapeHtml(photo.src)}\" alt=\"\" loading=\"lazy\" referrerpolicy=\"no-referrer\">\n        </button>`).join('');\n    show(start);\n    if (!dialog.open) dialog.showModal();\n}\n", "const {\n  entries,\n  keys: objectKeys,\n  setPrototypeOf,\n  isFrozen,\n  getPrototypeOf,\n  getOwnPropertyDescriptor,\n} = Object;\n\nlet { freeze, seal, create } = Object; // eslint-disable-line import/no-mutable-exports\nlet { apply, construct } = typeof Reflect !== 'undefined' && Reflect;\n\nif (!freeze) {\n  freeze = function <T>(x: T): T {\n    return x;\n  };\n}\n\nif (!seal) {\n  seal = function <T>(x: T): T {\n    return x;\n  };\n}\n\nif (!apply) {\n  apply = function <T>(\n    func: (thisArg: any, ...args: any[]) => T,\n    thisArg: any,\n    ...args: any[]\n  ): T {\n    return func.apply(thisArg, args);\n  };\n}\n\nif (!construct) {\n  construct = function <T>(Func: new (...args: any[]) => T, ...args: any[]): T {\n    return new Func(...args);\n  };\n}\n\nconst arrayForEach = unapply(Array.prototype.forEach);\nconst arrayLastIndexOf = unapply(Array.prototype.lastIndexOf);\nconst arrayPop = unapply(Array.prototype.pop);\nconst arrayPush = unapply(Array.prototype.push);\nconst arraySlice = unapply(Array.prototype.slice);\nconst arraySplice = unapply(Array.prototype.splice);\nconst arrayIsArray = Array.isArray;\n\nconst setCreate = unconstruct(Set) as () => Set<unknown>;\nconst setAdd = unapply(Set.prototype.add);\nconst setHas = unapply(Set.prototype.has);\n\nconst stringToLowerCase = unapply(String.prototype.toLowerCase);\nconst stringToString = unapply(String.prototype.toString);\nconst stringMatch = unapply(String.prototype.match);\nconst stringReplace = unapply(String.prototype.replace);\nconst stringIndexOf = unapply(String.prototype.indexOf);\nconst stringTrim = unapply(String.prototype.trim);\n\nconst numberToString = unapply(Number.prototype.toString);\nconst booleanToString = unapply(Boolean.prototype.toString);\nconst bigintToString =\n  typeof BigInt === 'undefined' ? null : unapply(BigInt.prototype.toString);\nconst symbolToString =\n  typeof Symbol === 'undefined' ? null : unapply(Symbol.prototype.toString);\n\nconst objectHasOwnProperty = unapply(Object.prototype.hasOwnProperty);\nconst objectToString = unapply(Object.prototype.toString);\n\nconst regExpTestRaw = RegExp.prototype.test;\n/* Shared /g regexes keep state in lastIndex, so reset it before each test */\nconst regExpTest = function (regExp: RegExp, value: string): boolean {\n  if (regExp instanceof RegExp) {\n    regExp.lastIndex = 0;\n  }\n\n  return apply(regExpTestRaw, regExp, [value]);\n};\n\nconst typeErrorCreate = unconstruct(TypeError);\n\n/**\n * Creates a new function that calls the given function with a specified thisArg and arguments.\n *\n * @param func - The function to be wrapped and called.\n * @returns A new function that calls the given function with a specified thisArg and arguments.\n */\nfunction unapply<T>(\n  func: (thisArg: any, ...args: any[]) => T\n): (thisArg: any, ...args: any[]) => T {\n  return (thisArg: any, ...args: any[]): T => apply(func, thisArg, args);\n}\n\n/**\n * Creates a new function that constructs an instance of the given constructor function with the provided arguments.\n *\n * @param func - The constructor function to be wrapped and called.\n * @returns A new function that constructs an instance of the given constructor function with the provided arguments.\n */\nfunction unconstruct<T>(\n  Func: new (...args: any[]) => T\n): (...args: any[]) => T {\n  return (...args: any[]): T => construct(Func, args);\n}\n\n/**\n * Add properties to a lookup table\n *\n * @param set - The set to which elements will be added.\n * @param array - The array containing elements to be added to the set.\n * @param transformCaseFunc - An optional function to transform the case of each element before adding to the set.\n * @returns The modified set with added elements.\n */\nfunction addToSet(\n  set: Record<string, boolean>,\n  array: readonly unknown[],\n  transformCaseFunc: ReturnType<typeof unapply<string>> = stringToLowerCase\n): Record<string, boolean> {\n  if (setPrototypeOf) {\n    // Make 'in' and truthy checks like Boolean(set.constructor)\n    // independent of any properties defined on Object.prototype.\n    // Prevent prototype setters from intercepting set as a this value.\n    setPrototypeOf(set, null);\n  }\n\n  if (!arrayIsArray(array)) {\n    return set;\n  }\n\n  let l = array.length;\n  while (l--) {\n    let element = array[l];\n\n    if (typeof element === 'string') {\n      const lcElement = transformCaseFunc(element);\n\n      if (lcElement !== element) {\n        // Config presets (e.g. tags.js, attrs.js) are immutable.\n        if (!isFrozen(array)) {\n          (array as unknown[])[l] = lcElement;\n        }\n\n        element = lcElement;\n      }\n    }\n\n    set[element as string] = true;\n  }\n\n  return set;\n}\n\n/**\n * Clean up an array to harden against CSPP\n *\n * @param array - The array to be cleaned.\n * @returns The cleaned version of the array\n */\nfunction cleanArray<T>(array: T[]): Array<T | null> {\n  for (let index = 0; index < array.length; index++) {\n    const isPropertyExist = objectHasOwnProperty(array, index);\n\n    if (!isPropertyExist) {\n      array[index] = null;\n    }\n  }\n\n  return array;\n}\n\n/**\n * Shallow clone an object\n *\n * @param object - The object to be cloned.\n * @returns A new object that copies the original.\n */\nfunction clone<T extends Record<string, any>>(object: T): T {\n  const newObject = create(null);\n\n  for (const [property, value] of entries(object)) {\n    const isPropertyExist = objectHasOwnProperty(object, property);\n\n    if (isPropertyExist) {\n      if (arrayIsArray(value)) {\n        newObject[property] = cleanArray(value);\n      } else if (\n        value &&\n        typeof value === 'object' &&\n        value.constructor === Object\n      ) {\n        newObject[property] = clone(value);\n      } else {\n        newObject[property] = value;\n      }\n    }\n  }\n\n  return newObject;\n}\n\n/**\n * Copy a flat lookup table\n *\n * @param set - The set to copy.\n * @returns A new prototype-free set with the same entries.\n */\nfunction cloneSet<T extends Record<string, any>>(set: T): T {\n  const newSet = create(null);\n  const keys = objectKeys(set);\n  let l = keys.length;\n  while (l--) {\n    newSet[keys[l]] = set[keys[l]];\n  }\n\n  return newSet;\n}\n\n/**\n * Convert non-node values into strings without depending on direct property access.\n *\n * @param value - The value to stringify.\n * @returns A string representation of the provided value.\n */\nfunction stringifyValue(value: unknown): string {\n  switch (typeof value) {\n    case 'string': {\n      return value;\n    }\n\n    case 'number': {\n      return numberToString(value);\n    }\n\n    case 'boolean': {\n      return booleanToString(value);\n    }\n\n    case 'bigint': {\n      return bigintToString ? bigintToString(value) : '0';\n    }\n\n    case 'symbol': {\n      return symbolToString ? symbolToString(value) : 'Symbol()';\n    }\n\n    case 'undefined': {\n      return objectToString(value);\n    }\n\n    case 'function':\n    case 'object': {\n      if (value === null) {\n        return objectToString(value);\n      }\n\n      const valueAsRecord = value as Record<string, any>;\n      const valueToString = lookupGetter(valueAsRecord, 'toString');\n\n      if (typeof valueToString === 'function') {\n        const stringified = valueToString(valueAsRecord);\n\n        return typeof stringified === 'string'\n          ? stringified\n          : objectToString(stringified);\n      }\n\n      return objectToString(value);\n    }\n\n    default: {\n      return objectToString(value);\n    }\n  }\n}\n\n/**\n * This method automatically checks if the prop is function or getter and behaves accordingly.\n *\n * @param object - The object to look up the getter function in its prototype chain.\n * @param prop - The property name for which to find the getter function.\n * @returns The getter function found in the prototype chain or a fallback function.\n */\nfunction lookupGetter<T extends Record<string, any>>(\n  object: T,\n  prop: string\n): ReturnType<typeof unapply<any>> | (() => null) {\n  while (object !== null) {\n    const desc = getOwnPropertyDescriptor(object, prop);\n\n    if (desc) {\n      if (desc.get) {\n        return unapply(desc.get);\n      }\n\n      if (typeof desc.value === 'function') {\n        return unapply(desc.value);\n      }\n    }\n\n    object = getPrototypeOf(object);\n  }\n\n  function fallbackValue(): null {\n    return null;\n  }\n\n  return fallbackValue;\n}\n\n/**\n * Like lookupGetter, but for accessor properties only, and returns null\n * instead of a null-returning fallback when no getter exists on the chain.\n * Lets a caller fall back to a direct property read in environments that\n * lack the getter, where a fallback returning null would be indistinguishable\n * from a legitimate null value (e.g. namespaceURI of a no-namespace element).\n *\n * @param object - The object (usually a prototype) to start the lookup at.\n * @param prop - The accessor property name.\n * @returns The unapplied getter, or null if none was found.\n */\nfunction lookupAccessor<T extends Record<string, any>>(\n  object: T,\n  prop: string\n): ReturnType<typeof unapply<any>> | null {\n  while (object !== null) {\n    const desc = getOwnPropertyDescriptor(object, prop);\n\n    if (desc) {\n      return desc.get ? unapply(desc.get) : null;\n    }\n\n    object = getPrototypeOf(object);\n  }\n\n  return null;\n}\n\nfunction isRegex(value: unknown): value is RegExp {\n  // Skip the try for absent values: a thrown TypeError is slow\n  if (!value) {\n    return false;\n  }\n\n  try {\n    regExpTest(value as RegExp, '');\n    return true;\n  } catch {\n    return false;\n  }\n}\n\nexport {\n  // Array\n  arrayForEach,\n  arrayIsArray,\n  arrayLastIndexOf,\n  arrayPop,\n  arrayPush,\n  arraySlice,\n  arraySplice,\n  // Object\n  entries,\n  freeze,\n  seal,\n  clone,\n  cloneSet,\n  create,\n  objectHasOwnProperty,\n  // RegExp\n  regExpTest,\n  setAdd,\n  setCreate,\n  setHas,\n  isRegex,\n  // String\n  stringIndexOf,\n  stringMatch,\n  stringReplace,\n  stringToLowerCase,\n  stringToString,\n  stringTrim,\n  // Other conversion\n  stringifyValue,\n  // Errors\n  typeErrorCreate,\n  // Other\n  lookupAccessor,\n  lookupGetter,\n  addToSet,\n};\n", "import { freeze } from './utils.js';\n\nexport const html = freeze([\n  'a',\n  'abbr',\n  'acronym',\n  'address',\n  'area',\n  'article',\n  'aside',\n  'audio',\n  'b',\n  'bdi',\n  'bdo',\n  'big',\n  'blink',\n  'blockquote',\n  'body',\n  'br',\n  'button',\n  'canvas',\n  'caption',\n  'center',\n  'cite',\n  'code',\n  'col',\n  'colgroup',\n  'content',\n  'data',\n  'datalist',\n  'dd',\n  'decorator',\n  'del',\n  'details',\n  'dfn',\n  'dialog',\n  'dir',\n  'div',\n  'dl',\n  'dt',\n  'element',\n  'em',\n  'fieldset',\n  'figcaption',\n  'figure',\n  'font',\n  'footer',\n  'form',\n  'h1',\n  'h2',\n  'h3',\n  'h4',\n  'h5',\n  'h6',\n  'head',\n  'header',\n  'hgroup',\n  'hr',\n  'html',\n  'i',\n  'img',\n  'input',\n  'ins',\n  'kbd',\n  'label',\n  'legend',\n  'li',\n  'main',\n  'map',\n  'mark',\n  'marquee',\n  'menu',\n  'menuitem',\n  'meter',\n  'nav',\n  'nobr',\n  'ol',\n  'optgroup',\n  'option',\n  'output',\n  'p',\n  'picture',\n  'pre',\n  'progress',\n  'q',\n  'rp',\n  'rt',\n  'ruby',\n  's',\n  'samp',\n  'search',\n  'section',\n  'select',\n  'shadow',\n  'slot',\n  'small',\n  'source',\n  'spacer',\n  'span',\n  'strike',\n  'strong',\n  'style',\n  'sub',\n  'summary',\n  'sup',\n  'table',\n  'tbody',\n  'td',\n  'template',\n  'textarea',\n  'tfoot',\n  'th',\n  'thead',\n  'time',\n  'tr',\n  'track',\n  'tt',\n  'u',\n  'ul',\n  'var',\n  'video',\n  'wbr',\n] as const);\n\nexport const svg = freeze([\n  'svg',\n  'a',\n  'altglyph',\n  'altglyphdef',\n  'altglyphitem',\n  'animatecolor',\n  'animatemotion',\n  'animatetransform',\n  'circle',\n  'clippath',\n  'defs',\n  'desc',\n  'ellipse',\n  'filter',\n  'font',\n  'g',\n  'glyph',\n  'glyphref',\n  'hkern',\n  'image',\n  'line',\n  'lineargradient',\n  'marker',\n  'mask',\n  'metadata',\n  'mpath',\n  'path',\n  'pattern',\n  'polygon',\n  'polyline',\n  'radialgradient',\n  'rect',\n  'stop',\n  'style',\n  'switch',\n  'symbol',\n  'text',\n  'textpath',\n  'title',\n  'tref',\n  'tspan',\n  'view',\n  'vkern',\n] as const);\n\nexport const svgFilters = freeze([\n  'feBlend',\n  'feColorMatrix',\n  'feComponentTransfer',\n  'feComposite',\n  'feConvolveMatrix',\n  'feDiffuseLighting',\n  'feDisplacementMap',\n  'feDistantLight',\n  'feDropShadow',\n  'feFlood',\n  'feFuncA',\n  'feFuncB',\n  'feFuncG',\n  'feFuncR',\n  'feGaussianBlur',\n  'feImage',\n  'feMerge',\n  'feMergeNode',\n  'feMorphology',\n  'feOffset',\n  'fePointLight',\n  'feSpecularLighting',\n  'feSpotLight',\n  'feTile',\n  'feTurbulence',\n] as const);\n\n// List of SVG elements that are disallowed by default.\n// We still need to know them so that we can do namespace\n// checks properly in case one wants to add them to\n// allow-list.\nexport const svgDisallowed = freeze([\n  'animate',\n  'color-profile',\n  'cursor',\n  'discard',\n  'font-face',\n  'font-face-format',\n  'font-face-name',\n  'font-face-src',\n  'font-face-uri',\n  'foreignobject',\n  'hatch',\n  'hatchpath',\n  'mesh',\n  'meshgradient',\n  'meshpatch',\n  'meshrow',\n  'missing-glyph',\n  'script',\n  'set',\n  'solidcolor',\n  'unknown',\n  'use',\n] as const);\n\nexport const mathMl = freeze([\n  'math',\n  'menclose',\n  'merror',\n  'mfenced',\n  'mfrac',\n  'mglyph',\n  'mi',\n  'mlabeledtr',\n  'mmultiscripts',\n  'mn',\n  'mo',\n  'mover',\n  'mpadded',\n  'mphantom',\n  'mroot',\n  'mrow',\n  'ms',\n  'mspace',\n  'msqrt',\n  'mstyle',\n  'msub',\n  'msup',\n  'msubsup',\n  'mtable',\n  'mtd',\n  'mtext',\n  'mtr',\n  'munder',\n  'munderover',\n  'mprescripts',\n] as const);\n\n// Similarly to SVG, we want to know all MathML elements,\n// even those that we disallow by default.\nexport const mathMlDisallowed = freeze([\n  'maction',\n  'maligngroup',\n  'malignmark',\n  'mlongdiv',\n  'mscarries',\n  'mscarry',\n  'msgroup',\n  'mstack',\n  'msline',\n  'msrow',\n  'semantics',\n  'annotation',\n  'annotation-xml',\n  'mprescripts',\n  'none',\n] as const);\n\nexport const text = freeze(['#text'] as const);\n", "import { freeze } from './utils.js';\n\nexport const html = freeze([\n  'accept',\n  'action',\n  'align',\n  'alt',\n  'autocapitalize',\n  'autocomplete',\n  'autopictureinpicture',\n  'autoplay',\n  'background',\n  'bgcolor',\n  'border',\n  'capture',\n  'cellpadding',\n  'cellspacing',\n  'checked',\n  'cite',\n  'class',\n  'clear',\n  'color',\n  'cols',\n  'colspan',\n  'command',\n  'commandfor',\n  'controls',\n  'controlslist',\n  'coords',\n  'crossorigin',\n  'datetime',\n  'decoding',\n  'default',\n  'dir',\n  'disabled',\n  'disablepictureinpicture',\n  'disableremoteplayback',\n  'download',\n  'draggable',\n  'enctype',\n  'enterkeyhint',\n  'exportparts',\n  'face',\n  'for',\n  'headers',\n  'height',\n  'hidden',\n  'high',\n  'href',\n  'hreflang',\n  'id',\n  'inert',\n  'inputmode',\n  'integrity',\n  'ismap',\n  'kind',\n  'label',\n  'lang',\n  'list',\n  'loading',\n  'loop',\n  'low',\n  'max',\n  'maxlength',\n  'media',\n  'method',\n  'min',\n  'minlength',\n  'multiple',\n  'muted',\n  'name',\n  'nonce',\n  'noshade',\n  'novalidate',\n  'nowrap',\n  'open',\n  'optimum',\n  'part',\n  'pattern',\n  'placeholder',\n  'playsinline',\n  'popover',\n  'popovertarget',\n  'popovertargetaction',\n  'poster',\n  'preload',\n  'pubdate',\n  'radiogroup',\n  'readonly',\n  'rel',\n  'required',\n  'rev',\n  'reversed',\n  'role',\n  'rows',\n  'rowspan',\n  'spellcheck',\n  'scope',\n  'selected',\n  'shape',\n  'size',\n  'sizes',\n  'slot',\n  'span',\n  'srclang',\n  'start',\n  'src',\n  'srcset',\n  'step',\n  'style',\n  'summary',\n  'tabindex',\n  'title',\n  'translate',\n  'type',\n  'usemap',\n  'valign',\n  'value',\n  'width',\n  'wrap',\n  'xmlns',\n] as const);\n\nexport const svg = freeze([\n  'accent-height',\n  'accumulate',\n  'additive',\n  'alignment-baseline',\n  'amplitude',\n  'ascent',\n  'attributename',\n  'attributetype',\n  'azimuth',\n  'basefrequency',\n  'baseline-shift',\n  'begin',\n  'bias',\n  'by',\n  'class',\n  'clip',\n  'clippathunits',\n  'clip-path',\n  'clip-rule',\n  'color',\n  'color-interpolation',\n  'color-interpolation-filters',\n  'color-profile',\n  'color-rendering',\n  'cx',\n  'cy',\n  'd',\n  'dx',\n  'dy',\n  'diffuseconstant',\n  'direction',\n  'display',\n  'divisor',\n  'dominant-baseline',\n  'dur',\n  'edgemode',\n  'elevation',\n  'end',\n  'exponent',\n  'fill',\n  'fill-opacity',\n  'fill-rule',\n  'filter',\n  'filterunits',\n  'flood-color',\n  'flood-opacity',\n  'font-family',\n  'font-size',\n  'font-size-adjust',\n  'font-stretch',\n  'font-style',\n  'font-variant',\n  'font-weight',\n  'fx',\n  'fy',\n  'g1',\n  'g2',\n  'glyph-name',\n  'glyphref',\n  'gradientunits',\n  'gradienttransform',\n  'height',\n  'href',\n  'id',\n  'image-rendering',\n  'in',\n  'in2',\n  'intercept',\n  'k',\n  'k1',\n  'k2',\n  'k3',\n  'k4',\n  'kerning',\n  'keypoints',\n  'keysplines',\n  'keytimes',\n  'lang',\n  'lengthadjust',\n  'letter-spacing',\n  'kernelmatrix',\n  'kernelunitlength',\n  'lighting-color',\n  'local',\n  'marker-end',\n  'marker-mid',\n  'marker-start',\n  'markerheight',\n  'markerunits',\n  'markerwidth',\n  'maskcontentunits',\n  'maskunits',\n  'max',\n  'mask',\n  'mask-type',\n  'media',\n  'method',\n  'mode',\n  'min',\n  'name',\n  'numoctaves',\n  'offset',\n  'operator',\n  'opacity',\n  'order',\n  'orient',\n  'orientation',\n  'origin',\n  'overflow',\n  'paint-order',\n  'path',\n  'pathlength',\n  'patterncontentunits',\n  'patterntransform',\n  'patternunits',\n  'pointer-events',\n  'points',\n  'preservealpha',\n  'preserveaspectratio',\n  'primitiveunits',\n  'r',\n  'rx',\n  'ry',\n  'radius',\n  'refx',\n  'refy',\n  'repeatcount',\n  'repeatdur',\n  'restart',\n  'result',\n  'rotate',\n  'scale',\n  'seed',\n  'shape-rendering',\n  'slope',\n  'specularconstant',\n  'specularexponent',\n  'spreadmethod',\n  'startoffset',\n  'stddeviation',\n  'stitchtiles',\n  'stop-color',\n  'stop-opacity',\n  'stroke-dasharray',\n  'stroke-dashoffset',\n  'stroke-linecap',\n  'stroke-linejoin',\n  'stroke-miterlimit',\n  'stroke-opacity',\n  'stroke',\n  'stroke-width',\n  'style',\n  'surfacescale',\n  'systemlanguage',\n  'tabindex',\n  'tablevalues',\n  'targetx',\n  'targety',\n  'transform',\n  'transform-origin',\n  'text-anchor',\n  'text-decoration',\n  'text-orientation',\n  'text-rendering',\n  'textlength',\n  'type',\n  'u1',\n  'u2',\n  'unicode',\n  'values',\n  'vector-effect',\n  'viewbox',\n  'visibility',\n  'version',\n  'vert-adv-y',\n  'vert-origin-x',\n  'vert-origin-y',\n  'width',\n  'word-spacing',\n  'wrap',\n  'writing-mode',\n  'xchannelselector',\n  'ychannelselector',\n  'x',\n  'x1',\n  'x2',\n  'xmlns',\n  'y',\n  'y1',\n  'y2',\n  'z',\n  'zoomandpan',\n] as const);\n\nexport const mathMl = freeze([\n  'accent',\n  'accentunder',\n  'align',\n  'bevelled',\n  'close',\n  'columnalign',\n  'columnlines',\n  'columnspacing',\n  'columnspan',\n  'denomalign',\n  'depth',\n  'dir',\n  'display',\n  'displaystyle',\n  'encoding',\n  'fence',\n  'frame',\n  'height',\n  'href',\n  'id',\n  'largeop',\n  'length',\n  'linethickness',\n  'lquote',\n  'lspace',\n  'mathbackground',\n  'mathcolor',\n  'mathsize',\n  'mathvariant',\n  'maxsize',\n  'minsize',\n  'movablelimits',\n  'notation',\n  'numalign',\n  'open',\n  'rowalign',\n  'rowlines',\n  'rowspacing',\n  'rowspan',\n  'rspace',\n  'rquote',\n  'scriptlevel',\n  'scriptminsize',\n  'scriptsizemultiplier',\n  'selection',\n  'separator',\n  'separators',\n  'stretchy',\n  'subscriptshift',\n  'supscriptshift',\n  'symmetric',\n  'voffset',\n  'width',\n  'xmlns',\n]);\n\nexport const xml = freeze([\n  'xlink:href',\n  'xml:id',\n  'xlink:title',\n  'xml:space',\n  'xmlns:xlink',\n] as const);\n", "import { seal } from './utils.js';\n\nexport const MUSTACHE_EXPR = seal(/{{[\\w\\W]*|^[\\w\\W]*}}/g);\nexport const ERB_EXPR = seal(/<%[\\w\\W]*|^[\\w\\W]*%>/g);\nexport const TMPLIT_EXPR = seal(/\\${[\\w\\W]*/g);\n// A template marker pair as it appears in serialized output\nexport const TMPL_MARKER_SERIALIZED = seal(/{{|}}|\\${|<%|%>|&lt;%|%&gt;/);\nexport const DATA_ATTR = seal(/^data-[\\-\\w.\\u00B7-\\uFFFF]+$/); // eslint-disable-line no-useless-escape\nexport const ARIA_ATTR = seal(/^aria-[\\-\\w]+$/); // eslint-disable-line no-useless-escape\nexport const IS_ALLOWED_URI = seal(\n  /^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\\-]+(?:[^a-z+.\\-:]|$))/i // eslint-disable-line no-useless-escape\n);\nexport const IS_SCRIPT_OR_DATA = seal(/^(?:\\w+script|data):/i);\nexport const ATTR_WHITESPACE = seal(\n  /[\\u0000-\\u0020\\u00A0\\u1680\\u180E\\u2000-\\u2029\\u205F\\u3000]/g // eslint-disable-line no-control-regex\n);\nexport const DOCTYPE_NAME = seal(/^html$/i);\nexport const CUSTOM_ELEMENT = seal(/^[a-z][.\\w]*(-[.\\w]+)+$/i);\n\n// Markup-significant character probes used by _sanitizeElements.\n// Shared module-level instances are safe despite the sticky /g flags:\n// regExpTest() resets lastIndex before every call.\nexport const ELEMENT_MARKUP_PROBE = seal(/<[/\\w!]/g);\nexport const COMMENT_MARKUP_PROBE = seal(/<[/\\w]/g);\nexport const FALLBACK_TAG_CLOSE = seal(/<\\/no(script|embed|frames)/i);\nexport const SELF_CLOSING_TAG = seal(/\\/>/i);\n// Comment closers and raw-text end tags inside an attribute value\nexport const ATTR_VALUE_BREAKOUT = seal(\n  /((--!?|])>)|<\\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i\n);\nexport const LEADING_WHITESPACE = seal(/^[\\r\\n\\t ]+/);\n", "import type { Config, UseProfilesConfig } from './config';\nimport type { DOMPurify, HooksMap, HookFunction, WindowLike } from './types';\nimport * as TAGS from './tags.js';\nimport * as ATTRS from './attrs.js';\nimport * as EXPRESSIONS from './regexp.js';\nimport {\n  addToSet,\n  clone,\n  cloneSet,\n  entries,\n  freeze,\n  seal,\n  arrayForEach,\n  arrayIsArray,\n  arrayLastIndexOf,\n  arrayPop,\n  arrayPush,\n  arraySlice,\n  arraySplice,\n  stringMatch,\n  stringReplace,\n  stringToLowerCase,\n  stringToString,\n  stringIndexOf,\n  stringTrim,\n  regExpTest,\n  setAdd,\n  setCreate,\n  setHas,\n  isRegex,\n  typeErrorCreate,\n  lookupAccessor,\n  lookupGetter,\n  create,\n  objectHasOwnProperty,\n  stringifyValue,\n} from './utils.js';\n\nexport type { Config } from './config';\n\nexport type {\n  DOMPurify,\n  RemovedElement,\n  RemovedAttribute,\n  HookName,\n  NodeHook,\n  ElementHook,\n  DocumentFragmentHook,\n  UponSanitizeElementHook,\n  UponSanitizeAttributeHook,\n  UponSanitizeElementHookEvent,\n  UponSanitizeAttributeHookEvent,\n  WindowLike,\n} from './types';\n\ndeclare const VERSION: string;\n\n// https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType\nconst NODE_TYPE = {\n  element: 1,\n  text: 3,\n  processingInstruction: 7,\n  comment: 8,\n  document: 9,\n  documentFragment: 11,\n};\n\n/* HTML elements whose text children are serialized unescaped. A node built\n   via the DOM API or an XML parse can hold an element child, or text with\n   markup such as the element's own end tag, and both break out on an HTML\n   reparse. _isUnsafeNode checks them via textContent, because an XML\n   document escapes `<` in innerHTML. `script` is never allowed, it is listed\n   to match the serializer's list. */\nconst LITERAL_TEXT_ELEMENT_NAMES = [\n  'style',\n  'script',\n  'xmp',\n  'iframe',\n  'noembed',\n  'noframes',\n  'plaintext',\n  'noscript',\n];\nconst LITERAL_TEXT_ELEMENTS = freeze(addToSet({}, LITERAL_TEXT_ELEMENT_NAMES));\n\nconst getGlobal = function (): WindowLike {\n  return typeof window === 'undefined' ? null : window;\n};\n\n/**\n * Creates a no-op policy for internal use only.\n * Don't export this function outside this module!\n * @param trustedTypes The policy factory.\n * @param purifyHostElement The Script element used to load DOMPurify (to determine policy name suffix).\n * @return The policy created (or null, if Trusted Types\n * are not supported or creating the policy failed).\n */\nconst _createTrustedTypesPolicy = function (\n  trustedTypes: TrustedTypePolicyFactory,\n  purifyHostElement: HTMLScriptElement\n) {\n  if (\n    typeof trustedTypes !== 'object' ||\n    typeof trustedTypes.createPolicy !== 'function'\n  ) {\n    return null;\n  }\n\n  // Allow the callers to control the unique policy name\n  // by adding a data-tt-policy-suffix to the script element with the DOMPurify.\n  // Policy creation with duplicate names throws in Trusted Types.\n  let suffix = null;\n  const ATTR_NAME = 'data-tt-policy-suffix';\n  if (purifyHostElement && purifyHostElement.hasAttribute(ATTR_NAME)) {\n    suffix = purifyHostElement.getAttribute(ATTR_NAME);\n  }\n\n  const policyName = 'dompurify' + (suffix ? '#' + suffix : '');\n\n  try {\n    return trustedTypes.createPolicy(policyName, {\n      createHTML(html) {\n        return html;\n      },\n      createScriptURL(scriptUrl) {\n        return scriptUrl;\n      },\n    });\n  } catch (_) {\n    // Policy creation failed (most likely another DOMPurify script has\n    // already run). Skip creating the policy, as this will only cause errors\n    // if TT are enforced.\n    console.warn(\n      'TrustedTypes policy ' + policyName + ' could not be created.'\n    );\n    return null;\n  }\n};\n\nconst _createHooksMap = function (): HooksMap {\n  return {\n    afterSanitizeAttributes: [],\n    afterSanitizeElements: [],\n    afterSanitizeShadowDOM: [],\n    beforeSanitizeAttributes: [],\n    beforeSanitizeElements: [],\n    beforeSanitizeShadowDOM: [],\n    uponSanitizeAttribute: [],\n    uponSanitizeElement: [],\n    uponSanitizeShadowNode: [],\n  };\n};\n\n/**\n * Resolve a set-valued configuration option.\n *\n * @param cfg the cloned, prototype-free configuration object\n * @param key the configuration property to read\n * @param fallback the set to use when the option is absent or not an array\n * @param options case transform, and an optional base set to extend a copy of\n * @returns a fresh set built from cfg[key], or the fallback\n */\nconst _resolveSetOption = function (\n  cfg: Config,\n  key: keyof Config,\n  fallback: Record<string, boolean>,\n  options: {\n    transform: Parameters<typeof addToSet>[2];\n    base?: Record<string, boolean>;\n  }\n): Record<string, boolean> {\n  return objectHasOwnProperty(cfg, key) && arrayIsArray(cfg[key])\n    ? addToSet(\n        options.base ? cloneSet(options.base) : {},\n        cfg[key] as readonly unknown[],\n        options.transform\n      )\n    : fallback;\n};\n\n/**\n * Resolve an object-valued configuration option.\n *\n * @param cfg the cloned, prototype-free configuration object\n * @param key the configuration property to read\n * @param fallback the read-only value to use when the option is absent\n * @returns a prototype-free clone of cfg[key], or the fallback\n */\nconst _resolveObjectOption = function <T extends Record<string, any>>(\n  cfg: Config,\n  key: keyof Config,\n  fallback: T\n): T {\n  const value = objectHasOwnProperty(cfg, key) ? cfg[key] : undefined;\n  return value && typeof value === 'object' ? clone(value as T) : fallback;\n};\n\nfunction createDOMPurify(window: WindowLike = getGlobal()): DOMPurify {\n  const DOMPurify: DOMPurify = (root: WindowLike) => createDOMPurify(root);\n\n  DOMPurify.version = VERSION;\n\n  DOMPurify.removed = [];\n\n  if (\n    !window ||\n    !window.document ||\n    window.document.nodeType !== NODE_TYPE.document ||\n    !window.Element\n  ) {\n    // Not running in a browser, provide a factory function\n    // so that you can pass your own Window\n    DOMPurify.isSupported = false;\n\n    return DOMPurify;\n  }\n\n  let { document } = window;\n\n  const originalDocument = document;\n  const currentScript: HTMLScriptElement =\n    originalDocument.currentScript as HTMLScriptElement;\n  const {\n    HTMLTemplateElement,\n    Node,\n    Element,\n    NodeFilter,\n    DOMParser,\n    trustedTypes,\n  } = window;\n\n  const ElementPrototype = Element.prototype;\n\n  const cloneNode = lookupGetter(ElementPrototype, 'cloneNode');\n  const remove = lookupGetter(ElementPrototype, 'remove');\n  // Cached, as a form child named \"removeAttributeNode\" shadows the method\n  const removeAttributeNode = lookupGetter(\n    ElementPrototype,\n    'removeAttributeNode'\n  );\n  const getNextSibling = lookupGetter(ElementPrototype, 'nextSibling');\n  const getChildNodes = lookupGetter(ElementPrototype, 'childNodes');\n  const getParentNode = lookupGetter(ElementPrototype, 'parentNode');\n  const getShadowRoot = lookupGetter(ElementPrototype, 'shadowRoot');\n  const getAttributes = lookupGetter(ElementPrototype, 'attributes');\n  const getNodeType =\n    Node && Node.prototype ? lookupGetter(Node.prototype, 'nodeType') : null;\n  const getNodeName =\n    Node && Node.prototype ? lookupGetter(Node.prototype, 'nodeName') : null;\n  const getOwnerDocument =\n    Node && Node.prototype\n      ? lookupGetter(Node.prototype, 'ownerDocument')\n      : null;\n\n  /* Clobber-safe nodeType / nodeName reads through the cached Node.prototype\n     getters, with a direct-property fallback for environments that lack\n     Node.prototype. Sites that need a different fallback (e.g. _isClobbered\n     returns early on a null name) intentionally keep their own reads. */\n  const _readNodeType = function (node: Node): number {\n    return getNodeType ? getNodeType(node) : (node as any).nodeType;\n  };\n\n  const _readNodeName = function (node: Node): string {\n    return getNodeName ? getNodeName(node) : (node as any).nodeName;\n  };\n\n  /* Element namespace through the cached Element.prototype getter, so a live\n     node's own-property override (Object.defineProperty) cannot steer\n     namespace decisions; direct read where the getter does not exist. Only\n     call this on Elements - the getter throws on other node types. */\n  const getNamespaceURI = lookupAccessor(ElementPrototype, 'namespaceURI');\n  const _readNamespaceURI = function (element: Element): string | null {\n    return getNamespaceURI\n      ? getNamespaceURI(element)\n      : (element as any).namespaceURI;\n  };\n\n  // As per issue #47, the web-components registry is inherited by a\n  // new document created via createHTMLDocument. As per the spec\n  // (http://w3c.github.io/webcomponents/spec/custom/#creating-and-passing-registries)\n  // a new empty registry is used when creating a template contents owner\n  // document, so we use that as our parent document to ensure nothing\n  // is inherited.\n  if (typeof HTMLTemplateElement === 'function') {\n    const template = document.createElement('template');\n    if (template.content && template.content.ownerDocument) {\n      document = template.content.ownerDocument;\n    }\n  }\n\n  let trustedTypesPolicy;\n  let emptyHTML = '';\n\n  // The instance's own Trusted Types policy. Created at most once, as Trusted\n  // Types throws on duplicate names, and the only one to survive clearConfig().\n  let defaultTrustedTypesPolicy;\n  let defaultTrustedTypesPolicyResolved = false;\n\n  // Depth of running policy callbacks. A policy whose createHTML or\n  // createScriptURL calls DOMPurify.sanitize would recurse forever (#1422),\n  // so re-entry throws instead.\n  let IN_TRUSTED_TYPES_POLICY = 0;\n  const _assertNotInTrustedTypesPolicy = function (): void {\n    if (IN_TRUSTED_TYPES_POLICY > 0) {\n      throw typeErrorCreate(\n        'A configured TRUSTED_TYPES_POLICY callback (createHTML or ' +\n          'createScriptURL) must not call DOMPurify.sanitize, as that causes ' +\n          'infinite recursion. Do not pass a policy whose callbacks wrap ' +\n          'DOMPurify as TRUSTED_TYPES_POLICY; see the \"DOMPurify and Trusted ' +\n          'Types\" section of the README.'\n      );\n    }\n  };\n\n  const _createTrustedHTML = function (html: string): string {\n    _assertNotInTrustedTypesPolicy();\n\n    IN_TRUSTED_TYPES_POLICY++;\n    try {\n      return trustedTypesPolicy.createHTML(html);\n    } finally {\n      IN_TRUSTED_TYPES_POLICY--;\n    }\n  };\n\n  /* Sign string output when a policy is active and the caller asked for it */\n  const _signOutput = function (html: string): string {\n    return trustedTypesPolicy && RETURN_TRUSTED_TYPE\n      ? _createTrustedHTML(html)\n      : html;\n  };\n\n  const _createTrustedScriptURL = function (scriptUrl: string): string {\n    _assertNotInTrustedTypesPolicy();\n\n    IN_TRUSTED_TYPES_POLICY++;\n    try {\n      return trustedTypesPolicy.createScriptURL(scriptUrl);\n    } finally {\n      IN_TRUSTED_TYPES_POLICY--;\n    }\n  };\n\n  // Resolve the default policy once; neither success nor failure is retried\n  const _getDefaultTrustedTypesPolicy = function () {\n    if (!defaultTrustedTypesPolicyResolved) {\n      defaultTrustedTypesPolicy = _createTrustedTypesPolicy(\n        trustedTypes,\n        currentScript\n      );\n      defaultTrustedTypesPolicyResolved = true;\n    }\n\n    return defaultTrustedTypesPolicy;\n  };\n\n  const {\n    implementation,\n    createNodeIterator,\n    createDocumentFragment,\n    getElementsByTagName,\n  } = document;\n  const { importNode } = originalDocument;\n\n  let hooks = _createHooksMap();\n\n  /**\n   * Expose whether this browser supports running the full DOMPurify.\n   */\n  DOMPurify.isSupported =\n    typeof entries === 'function' &&\n    typeof getParentNode === 'function' &&\n    implementation &&\n    implementation.createHTMLDocument !== undefined;\n\n  const {\n    MUSTACHE_EXPR,\n    ERB_EXPR,\n    TMPLIT_EXPR,\n    DATA_ATTR,\n    ARIA_ATTR,\n    IS_SCRIPT_OR_DATA,\n    ATTR_WHITESPACE,\n    CUSTOM_ELEMENT,\n  } = EXPRESSIONS;\n\n  let { IS_ALLOWED_URI } = EXPRESSIONS;\n\n  /**\n   * We consider the elements and attributes below to be safe. Ideally\n   * don't add any new ones but feel free to remove unwanted ones.\n   */\n\n  /* allowed element names */\n  let ALLOWED_TAGS = null;\n  const DEFAULT_ALLOWED_TAGS = addToSet({}, [\n    ...TAGS.html,\n    ...TAGS.svg,\n    ...TAGS.svgFilters,\n    ...TAGS.mathMl,\n    ...TAGS.text,\n  ]);\n\n  /* Allowed attribute names */\n  let ALLOWED_ATTR = null;\n  const DEFAULT_ALLOWED_ATTR = addToSet({}, [\n    ...ATTRS.html,\n    ...ATTRS.svg,\n    ...ATTRS.mathMl,\n    ...ATTRS.xml,\n  ]);\n\n  /*\n   * Configure how DOMPurify should handle custom elements and their attributes as well as customized built-in elements.\n   * @property {RegExp|Function|null} tagNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any custom elements)\n   * @property {RegExp|Function|null} attributeNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any attributes not on the allow list)\n   * @property {boolean} allowCustomizedBuiltInElements allow custom elements derived from built-ins if they pass CUSTOM_ELEMENT_HANDLING.tagNameCheck. Default: `false`.\n   */\n  let CUSTOM_ELEMENT_HANDLING = null;\n\n  /* Explicitly forbidden tags (overrides ALLOWED_TAGS/ADD_TAGS) */\n  let FORBID_TAGS = null;\n\n  /* Explicitly forbidden attributes (overrides ALLOWED_ATTR/ADD_ATTR) */\n  let FORBID_ATTR = null;\n\n  /* Config object to store ADD_TAGS/ADD_ATTR functions (when used as functions) */\n  const EXTRA_ELEMENT_HANDLING = Object.seal(\n    create(null, {\n      tagCheck: {\n        writable: true,\n        configurable: false,\n        enumerable: true,\n        value: null,\n      },\n      attributeCheck: {\n        writable: true,\n        configurable: false,\n        enumerable: true,\n        value: null,\n      },\n    })\n  );\n\n  /* Decide if ARIA attributes are okay */\n  let ALLOW_ARIA_ATTR = true;\n\n  /* Decide if custom data attributes are okay */\n  let ALLOW_DATA_ATTR = true;\n\n  /* Decide if unknown protocols are okay */\n  let ALLOW_UNKNOWN_PROTOCOLS = false;\n\n  /* Decide if self-closing tags in attributes are allowed.\n   * Usually removed due to a mXSS issue in jQuery 3.0 */\n  let ALLOW_SELF_CLOSE_IN_ATTR = true;\n\n  /* Output should be safe for common template engines.\n   * This means, DOMPurify removes data attributes, mustaches and ERB\n   */\n  let SAFE_FOR_TEMPLATES = false;\n\n  /* Output should be safe even for XML used within HTML and alike.\n   * This means, DOMPurify removes comments when containing risky content.\n   */\n  let SAFE_FOR_XML = true;\n\n  /* Decide if document with <html>... should be returned */\n  let WHOLE_DOCUMENT = false;\n\n  /* Track whether config is already set on this instance of DOMPurify. */\n  let SET_CONFIG = false;\n\n  /* Allowlists as captured by setConfig(). sanitize() restores the sets from\n   * these on every call, so a hook's widening cannot carry across calls. */\n  let SET_CONFIG_ALLOWED_TAGS = null;\n  let SET_CONFIG_ALLOWED_ATTR = null;\n\n  /* Decide if all elements (e.g. style, script) must be children of\n   * document.body. By default, browsers might move them to document.head */\n  let FORCE_BODY = false;\n\n  /* Decide if a DOM `HTMLBodyElement` should be returned, instead of a html\n   * string (or a TrustedHTML object if Trusted Types are supported).\n   * If `WHOLE_DOCUMENT` is enabled a `HTMLHtmlElement` will be returned instead\n   */\n  let RETURN_DOM = false;\n\n  /* Decide if a DOM `DocumentFragment` should be returned, instead of a html\n   * string  (or a TrustedHTML object if Trusted Types are supported) */\n  let RETURN_DOM_FRAGMENT = false;\n\n  /* Try to return a Trusted Type object instead of a string, return a string in\n   * case Trusted Types are not supported  */\n  let RETURN_TRUSTED_TYPE = false;\n\n  /* Output should be free from DOM clobbering attacks?\n   * This sanitizes markups named with colliding, clobberable built-in DOM APIs.\n   */\n  let SANITIZE_DOM = true;\n\n  /* Achieve full DOM Clobbering protection by isolating the namespace of named\n   * properties and JS variables, mitigating attacks that abuse the HTML/DOM spec rules.\n   *\n   * HTML/DOM spec rules that enable DOM Clobbering:\n   *   - Named Access on Window (\u00A77.3.3)\n   *   - DOM Tree Accessors (\u00A73.1.5)\n   *   - Form Element Parent-Child Relations (\u00A74.10.3)\n   *   - Iframe srcdoc / Nested WindowProxies (\u00A74.8.5)\n   *   - HTMLCollection (\u00A74.2.10.2)\n   *\n   * Namespace isolation is implemented by prefixing `id` and `name` attributes\n   * with a constant string, i.e., `user-content-`\n   */\n  let SANITIZE_NAMED_PROPS = false;\n  const SANITIZE_NAMED_PROPS_PREFIX = 'user-content-';\n\n  /* Keep element content when removing element? */\n  let KEEP_CONTENT = true;\n\n  /* If a `Node` is passed to sanitize(), then performs sanitization in-place instead\n   * of importing it into a new Document and returning a sanitized copy */\n  let IN_PLACE = false;\n\n  /* IN_PLACE: nodes processed during the current call */\n  let IN_PLACE_VISITED: Set<unknown> | null = null;\n\n  /* Allow usage of profiles like html, svg and mathMl */\n  let USE_PROFILES: UseProfilesConfig | false = false;\n\n  /* Tags to ignore content of when KEEP_CONTENT is true */\n  let FORBID_CONTENTS = null;\n  const DEFAULT_FORBID_CONTENTS = addToSet({}, [\n    'annotation-xml',\n    'audio',\n    'colgroup',\n    'desc',\n    'foreignobject',\n    'head',\n    'iframe',\n    'math',\n    'mi',\n    'mn',\n    'mo',\n    'ms',\n    'mtext',\n    'noembed',\n    'noframes',\n    'noscript',\n    'plaintext',\n    'script',\n    // The engine mirrors the selected <option> into <selectedcontent> and\n    // re-mirrors on removal, even in our inert document. Hoisting its\n    // children would loop forever, so the content is dropped instead; it\n    // duplicates the option, which is sanitized on its own.\n    'selectedcontent',\n    'style',\n    'svg',\n    'template',\n    'thead',\n    'title',\n    'video',\n    'xmp',\n  ]);\n\n  /* Tags that are safe for data: URIs */\n  let DATA_URI_TAGS = null;\n  const DEFAULT_DATA_URI_TAGS = addToSet({}, [\n    'audio',\n    'video',\n    'img',\n    'source',\n    'image',\n    'track',\n  ]);\n\n  /* Attributes safe for values like \"javascript:\" */\n  let URI_SAFE_ATTRIBUTES = null;\n  const DEFAULT_URI_SAFE_ATTRIBUTES = addToSet({}, [\n    'alt',\n    'class',\n    'for',\n    'id',\n    'label',\n    'name',\n    'pattern',\n    'placeholder',\n    'role',\n    'summary',\n    'title',\n    'value',\n    'style',\n    'xmlns',\n  ]);\n\n  const MATHML_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';\n  const SVG_NAMESPACE = 'http://www.w3.org/2000/svg';\n  const HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';\n  /* Document namespace */\n  let NAMESPACE = HTML_NAMESPACE;\n  let IS_EMPTY_INPUT = false;\n\n  /* Allowed XHTML+XML namespaces */\n  let ALLOWED_NAMESPACES = null;\n  const DEFAULT_ALLOWED_NAMESPACES = addToSet(\n    {},\n    [MATHML_NAMESPACE, SVG_NAMESPACE, HTML_NAMESPACE],\n    stringToString\n  );\n\n  /* Read-only defaults, shared across parses */\n  const DEFAULT_MATHML_TEXT_INTEGRATION_POINTS = freeze(\n    addToSet({}, ['mi', 'mo', 'mn', 'ms', 'mtext'])\n  );\n  let MATHML_TEXT_INTEGRATION_POINTS = null;\n\n  const DEFAULT_HTML_INTEGRATION_POINTS = freeze(\n    addToSet({}, ['annotation-xml'])\n  );\n  let HTML_INTEGRATION_POINTS = null;\n\n  const DEFAULT_CUSTOM_ELEMENT_HANDLING = freeze(create(null));\n\n  // Certain elements are allowed in both SVG and HTML\n  // namespace. We need to specify them explicitly\n  // so that they don't get erroneously deleted from\n  // HTML namespace.\n  const COMMON_SVG_AND_HTML_ELEMENTS = addToSet({}, [\n    'title',\n    'style',\n    'font',\n    'a',\n    'script',\n  ]);\n\n  /* Parsing of strict XHTML documents */\n  let PARSER_MEDIA_TYPE: null | DOMParserSupportedType = null;\n  const SUPPORTED_PARSER_MEDIA_TYPES = ['application/xhtml+xml', 'text/html'];\n  const DEFAULT_PARSER_MEDIA_TYPE = 'text/html';\n  let transformCaseFunc: null | Parameters<typeof addToSet>[2] = null;\n\n  /* Keep a reference to config to pass to hooks */\n  let CONFIG: Config | null = null;\n\n  /* Ideally, do not touch anything below this line */\n  /* ______________________________________________ */\n\n  const formElement = document.createElement('form');\n\n  const isRegexOrFunction = function (\n    testValue: unknown\n  ): testValue is Function | RegExp {\n    return testValue instanceof RegExp || testValue instanceof Function;\n  };\n\n  /**\n   * _parseConfig\n   *\n   * @param cfg optional config literal\n   */\n  // eslint-disable-next-line complexity\n  const _parseConfig = function (cfg: Config = {}): void {\n    /* Shield configuration object from tampering */\n    if (!cfg || typeof cfg !== 'object') {\n      cfg = {};\n    }\n\n    /* Shield configuration object from prototype pollution */\n    cfg = clone(cfg);\n\n    PARSER_MEDIA_TYPE =\n      // eslint-disable-next-line unicorn/prefer-includes\n      SUPPORTED_PARSER_MEDIA_TYPES.indexOf(cfg.PARSER_MEDIA_TYPE) === -1\n        ? DEFAULT_PARSER_MEDIA_TYPE\n        : cfg.PARSER_MEDIA_TYPE;\n\n    // HTML tags and attributes are not case-sensitive, converting to lowercase. Keeping XHTML as is.\n    transformCaseFunc =\n      PARSER_MEDIA_TYPE === 'application/xhtml+xml'\n        ? stringToString\n        : stringToLowerCase;\n\n    /* Set configuration parameters */\n    ALLOWED_TAGS = _resolveSetOption(\n      cfg,\n      'ALLOWED_TAGS',\n      DEFAULT_ALLOWED_TAGS,\n      { transform: transformCaseFunc }\n    );\n    ALLOWED_ATTR = _resolveSetOption(\n      cfg,\n      'ALLOWED_ATTR',\n      DEFAULT_ALLOWED_ATTR,\n      { transform: transformCaseFunc }\n    );\n    ALLOWED_NAMESPACES = _resolveSetOption(\n      cfg,\n      'ALLOWED_NAMESPACES',\n      DEFAULT_ALLOWED_NAMESPACES,\n      { transform: stringToString }\n    );\n    URI_SAFE_ATTRIBUTES = _resolveSetOption(\n      cfg,\n      'ADD_URI_SAFE_ATTR',\n      DEFAULT_URI_SAFE_ATTRIBUTES,\n      { transform: transformCaseFunc, base: DEFAULT_URI_SAFE_ATTRIBUTES }\n    );\n    DATA_URI_TAGS = _resolveSetOption(\n      cfg,\n      'ADD_DATA_URI_TAGS',\n      DEFAULT_DATA_URI_TAGS,\n      { transform: transformCaseFunc, base: DEFAULT_DATA_URI_TAGS }\n    );\n    FORBID_CONTENTS = _resolveSetOption(\n      cfg,\n      'FORBID_CONTENTS',\n      DEFAULT_FORBID_CONTENTS,\n      { transform: transformCaseFunc }\n    );\n    FORBID_TAGS = _resolveSetOption(cfg, 'FORBID_TAGS', create(null), {\n      transform: transformCaseFunc,\n    });\n    FORBID_ATTR = _resolveSetOption(cfg, 'FORBID_ATTR', create(null), {\n      transform: transformCaseFunc,\n    });\n    USE_PROFILES = objectHasOwnProperty(cfg, 'USE_PROFILES')\n      ? cfg.USE_PROFILES && typeof cfg.USE_PROFILES === 'object'\n        ? clone(cfg.USE_PROFILES)\n        : cfg.USE_PROFILES\n      : false;\n\n    ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false; // Default true\n    ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false; // Default true\n    ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false; // Default false\n    ALLOW_SELF_CLOSE_IN_ATTR = cfg.ALLOW_SELF_CLOSE_IN_ATTR !== false; // Default true\n    SAFE_FOR_TEMPLATES = cfg.SAFE_FOR_TEMPLATES || false; // Default false\n    SAFE_FOR_XML = cfg.SAFE_FOR_XML !== false; // Default true\n    WHOLE_DOCUMENT = cfg.WHOLE_DOCUMENT || false; // Default false\n    RETURN_DOM = cfg.RETURN_DOM || false; // Default false\n    RETURN_DOM_FRAGMENT = cfg.RETURN_DOM_FRAGMENT || false; // Default false\n    RETURN_TRUSTED_TYPE = cfg.RETURN_TRUSTED_TYPE || false; // Default false\n    FORCE_BODY = cfg.FORCE_BODY || false; // Default false\n    SANITIZE_DOM = cfg.SANITIZE_DOM !== false; // Default true\n    SANITIZE_NAMED_PROPS = cfg.SANITIZE_NAMED_PROPS || false; // Default false\n    KEEP_CONTENT = cfg.KEEP_CONTENT !== false; // Default true\n    IN_PLACE = cfg.IN_PLACE || false; // Default false\n    IS_ALLOWED_URI = isRegex(cfg.ALLOWED_URI_REGEXP)\n      ? cfg.ALLOWED_URI_REGEXP\n      : EXPRESSIONS.IS_ALLOWED_URI; // Default regexp\n\n    NAMESPACE =\n      typeof cfg.NAMESPACE === 'string' ? cfg.NAMESPACE : HTML_NAMESPACE; // Default HTML namespace\n\n    MATHML_TEXT_INTEGRATION_POINTS = _resolveObjectOption(\n      cfg,\n      'MATHML_TEXT_INTEGRATION_POINTS',\n      DEFAULT_MATHML_TEXT_INTEGRATION_POINTS\n    );\n\n    HTML_INTEGRATION_POINTS = _resolveObjectOption(\n      cfg,\n      'HTML_INTEGRATION_POINTS',\n      DEFAULT_HTML_INTEGRATION_POINTS\n    );\n\n    const customElementHandling = _resolveObjectOption(\n      cfg,\n      'CUSTOM_ELEMENT_HANDLING',\n      DEFAULT_CUSTOM_ELEMENT_HANDLING\n    );\n\n    CUSTOM_ELEMENT_HANDLING = create(null);\n\n    if (\n      objectHasOwnProperty(customElementHandling, 'tagNameCheck') &&\n      isRegexOrFunction(customElementHandling.tagNameCheck)\n    ) {\n      CUSTOM_ELEMENT_HANDLING.tagNameCheck = customElementHandling.tagNameCheck; // Default undefined\n    }\n\n    if (\n      objectHasOwnProperty(customElementHandling, 'attributeNameCheck') &&\n      isRegexOrFunction(customElementHandling.attributeNameCheck)\n    ) {\n      CUSTOM_ELEMENT_HANDLING.attributeNameCheck =\n        customElementHandling.attributeNameCheck; // Default undefined\n    }\n\n    if (\n      objectHasOwnProperty(\n        customElementHandling,\n        'allowCustomizedBuiltInElements'\n      ) &&\n      typeof customElementHandling.allowCustomizedBuiltInElements === 'boolean'\n    ) {\n      CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements =\n        customElementHandling.allowCustomizedBuiltInElements; // Default undefined\n    }\n\n    seal(CUSTOM_ELEMENT_HANDLING);\n\n    if (SAFE_FOR_TEMPLATES) {\n      ALLOW_DATA_ATTR = false;\n    }\n\n    if (RETURN_DOM_FRAGMENT) {\n      RETURN_DOM = true;\n    }\n\n    /* Parse profile info */\n    if (USE_PROFILES) {\n      if (\n        (objectHasOwnProperty(cfg, 'ALLOWED_TAGS') ||\n          objectHasOwnProperty(cfg, 'ALLOWED_ATTR')) &&\n        typeof console !== 'undefined' &&\n        typeof console.warn === 'function'\n      ) {\n        console.warn(\n          'DOMPurify: USE_PROFILES overrides ALLOWED_TAGS and ALLOWED_ATTR. ' +\n            'Do not use these options together.'\n        );\n      }\n\n      ALLOWED_TAGS = addToSet({}, TAGS.text);\n      ALLOWED_ATTR = create(null);\n      if (USE_PROFILES.html === true) {\n        addToSet(ALLOWED_TAGS, TAGS.html);\n        addToSet(ALLOWED_ATTR, ATTRS.html);\n      }\n\n      if (USE_PROFILES.svg === true) {\n        addToSet(ALLOWED_TAGS, TAGS.svg);\n        addToSet(ALLOWED_ATTR, ATTRS.svg);\n        addToSet(ALLOWED_ATTR, ATTRS.xml);\n      }\n\n      if (USE_PROFILES.svgFilters === true) {\n        addToSet(ALLOWED_TAGS, TAGS.svgFilters);\n        addToSet(ALLOWED_ATTR, ATTRS.svg);\n        addToSet(ALLOWED_ATTR, ATTRS.xml);\n      }\n\n      if (USE_PROFILES.mathMl === true) {\n        addToSet(ALLOWED_TAGS, TAGS.mathMl);\n        addToSet(ALLOWED_ATTR, ATTRS.mathMl);\n        addToSet(ALLOWED_ATTR, ATTRS.xml);\n      }\n    }\n\n    /* Always reset function-based ADD_TAGS / ADD_ATTR checks to prevent\n     * leaking across calls when switching from function to array config */\n    EXTRA_ELEMENT_HANDLING.tagCheck = null;\n    EXTRA_ELEMENT_HANDLING.attributeCheck = null;\n\n    /* Merge configuration parameters */\n    if (objectHasOwnProperty(cfg, 'ADD_TAGS')) {\n      if (typeof cfg.ADD_TAGS === 'function') {\n        EXTRA_ELEMENT_HANDLING.tagCheck = cfg.ADD_TAGS;\n      } else if (arrayIsArray(cfg.ADD_TAGS)) {\n        if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) {\n          ALLOWED_TAGS = cloneSet(ALLOWED_TAGS);\n        }\n\n        addToSet(ALLOWED_TAGS, cfg.ADD_TAGS, transformCaseFunc);\n      }\n    }\n\n    if (objectHasOwnProperty(cfg, 'ADD_ATTR')) {\n      if (typeof cfg.ADD_ATTR === 'function') {\n        EXTRA_ELEMENT_HANDLING.attributeCheck = cfg.ADD_ATTR;\n      } else if (arrayIsArray(cfg.ADD_ATTR)) {\n        if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) {\n          ALLOWED_ATTR = cloneSet(ALLOWED_ATTR);\n        }\n\n        addToSet(ALLOWED_ATTR, cfg.ADD_ATTR, transformCaseFunc);\n      }\n    }\n\n    if (\n      objectHasOwnProperty(cfg, 'ADD_FORBID_CONTENTS') &&\n      arrayIsArray(cfg.ADD_FORBID_CONTENTS)\n    ) {\n      if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {\n        FORBID_CONTENTS = cloneSet(FORBID_CONTENTS);\n      }\n\n      addToSet(FORBID_CONTENTS, cfg.ADD_FORBID_CONTENTS, transformCaseFunc);\n    }\n\n    /* Add #text in case KEEP_CONTENT is set to true */\n    if (KEEP_CONTENT) {\n      ALLOWED_TAGS['#text'] = true;\n    }\n\n    /* Add html, head and body to ALLOWED_TAGS in case WHOLE_DOCUMENT is true */\n    if (WHOLE_DOCUMENT) {\n      addToSet(ALLOWED_TAGS, ['html', 'head', 'body']);\n    }\n\n    /* Add tbody to ALLOWED_TAGS in case tables are permitted, see #286, #365 */\n    if (ALLOWED_TAGS.table) {\n      ALLOWED_TAGS.tbody = true;\n      delete FORBID_TAGS.tbody;\n    }\n\n    // The active Trusted Types policy is re-derived on every parse, so a\n    // caller-supplied policy cannot outlive its configuration and sign later\n    // output. See GHSA-vxr8-fq34-vvx9.\n    if (cfg.TRUSTED_TYPES_POLICY) {\n      if (typeof cfg.TRUSTED_TYPES_POLICY.createHTML !== 'function') {\n        throw typeErrorCreate(\n          'TRUSTED_TYPES_POLICY configuration option must provide a \"createHTML\" hook.'\n        );\n      }\n\n      if (typeof cfg.TRUSTED_TYPES_POLICY.createScriptURL !== 'function') {\n        throw typeErrorCreate(\n          'TRUSTED_TYPES_POLICY configuration option must provide a \"createScriptURL\" hook.'\n        );\n      }\n\n      // A caller-supplied policy applies to this configuration only.\n      const previousTrustedTypesPolicy = trustedTypesPolicy;\n      trustedTypesPolicy = cfg.TRUSTED_TYPES_POLICY;\n\n      // Sign local variables required by `sanitize`. If the supplied policy's\n      // `createHTML` is circular (i.e. it calls `DOMPurify.sanitize`), this\n      // throws via the re-entrancy guard. Restore the previous policy first so\n      // the instance is not left in a poisoned state. See #1422.\n      try {\n        emptyHTML = _createTrustedHTML('');\n      } catch (error) {\n        trustedTypesPolicy = previousTrustedTypesPolicy;\n        throw error;\n      }\n    } else if (cfg.TRUSTED_TYPES_POLICY === null) {\n      // Explicit opt-out: sign nothing and create no policy, so sanitize()\n      // can be called from inside a caller's own policy (#1422). This also\n      // drops a previously supplied policy.\n      trustedTypesPolicy = undefined;\n      emptyHTML = '';\n    } else {\n      // No policy supplied: a previously supplied one stays active until\n      // clearConfig(), otherwise the instance's own policy is used.\n      if (trustedTypesPolicy === undefined) {\n        trustedTypesPolicy = _getDefaultTrustedTypesPolicy();\n      }\n\n      // Sign internal variables only when a policy is active. A falsy policy\n      // (Trusted Types unsupported, creation failed, or an explicit opt-out)\n      // leaves `emptyHTML` as a plain string, so we never call `.createHTML` on\n      // a non-policy and throw. See #1422.\n      if (trustedTypesPolicy && typeof emptyHTML === 'string') {\n        emptyHTML = _createTrustedHTML('');\n      }\n    }\n\n    // Prevent further manipulation of configuration\n    CONFIG = freeze(cfg);\n  };\n\n  /* Keep track of all possible SVG and MathML tags\n   * so that we can perform the namespace checks\n   * correctly. */\n  const ALL_SVG_TAGS = addToSet({}, [\n    ...TAGS.svg,\n    ...TAGS.svgFilters,\n    ...TAGS.svgDisallowed,\n  ]);\n  const ALL_MATHML_TAGS = addToSet({}, [\n    ...TAGS.mathMl,\n    ...TAGS.mathMlDisallowed,\n  ]);\n\n  /**\n   * Namespace rules for an element in the SVG namespace.\n   *\n   * @param tagName the element's lowercase tag name\n   * @param parentNamespace the (possibly simulated) parent's namespace\n   * @param parentTagName the parent's lowercase tag name\n   * @returns true if a spec-compliant parser could produce this element\n   */\n  const _checkSvgNamespace = function (\n    tagName: string,\n    parentNamespace: string | null,\n    parentTagName: string\n  ): boolean {\n    // The only way to switch from HTML namespace to SVG\n    // is via <svg>. If it happens via any other tag, then\n    // it should be killed.\n    if (parentNamespace === HTML_NAMESPACE) {\n      return tagName === 'svg';\n    }\n\n    // The only way to switch from MathML to SVG is via <svg>\n    // if the parent is either <annotation-xml> or a MathML\n    // text integration point.\n    if (parentNamespace === MATHML_NAMESPACE) {\n      return (\n        tagName === 'svg' &&\n        (parentTagName === 'annotation-xml' ||\n          MATHML_TEXT_INTEGRATION_POINTS[parentTagName])\n      );\n    }\n\n    // We only allow elements that are defined in SVG\n    // spec. All others are disallowed in SVG namespace.\n    return Boolean(ALL_SVG_TAGS[tagName]);\n  };\n\n  /**\n   * Namespace rules for an element in the MathML namespace.\n   *\n   * @param tagName the element's lowercase tag name\n   * @param parentNamespace the (possibly simulated) parent's namespace\n   * @param parentTagName the parent's lowercase tag name\n   * @returns true if a spec-compliant parser could produce this element\n   */\n  const _checkMathMlNamespace = function (\n    tagName: string,\n    parentNamespace: string | null,\n    parentTagName: string\n  ): boolean {\n    // The only way to switch from HTML namespace to MathML\n    // is via <math>. If it happens via any other tag, then\n    // it should be killed.\n    if (parentNamespace === HTML_NAMESPACE) {\n      return tagName === 'math';\n    }\n\n    // The only way to switch from SVG to MathML is via\n    // <math> and HTML integration points\n    if (parentNamespace === SVG_NAMESPACE) {\n      return tagName === 'math' && HTML_INTEGRATION_POINTS[parentTagName];\n    }\n\n    // We only allow elements that are defined in MathML\n    // spec. All others are disallowed in MathML namespace.\n    return Boolean(ALL_MATHML_TAGS[tagName]);\n  };\n\n  /**\n   * Namespace rules for an element in the HTML namespace.\n   *\n   * @param tagName the element's lowercase tag name\n   * @param parentNamespace the (possibly simulated) parent's namespace\n   * @param parentTagName the parent's lowercase tag name\n   * @returns true if a spec-compliant parser could produce this element\n   */\n  const _checkHtmlNamespace = function (\n    tagName: string,\n    parentNamespace: string | null,\n    parentTagName: string\n  ): boolean {\n    // The only way to switch from SVG to HTML is via\n    // HTML integration points, and from MathML to HTML\n    // is via MathML text integration points\n    if (\n      parentNamespace === SVG_NAMESPACE &&\n      !HTML_INTEGRATION_POINTS[parentTagName]\n    ) {\n      return false;\n    }\n\n    if (\n      parentNamespace === MATHML_NAMESPACE &&\n      !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]\n    ) {\n      return false;\n    }\n\n    // We disallow tags that are specific for MathML\n    // or SVG and should never appear in HTML namespace\n    return (\n      !ALL_MATHML_TAGS[tagName] &&\n      (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName])\n    );\n  };\n\n  /**\n   * @param element a DOM element whose namespace is being checked\n   * @returns Return false if the element has a\n   *  namespace that a spec-compliant parser would never\n   *  return. Return true otherwise.\n   */\n  const _checkValidNamespace = function (element: Element): boolean {\n    /* Cached getters only: a live node may carry own-property overrides of\n       tagName or namespaceURI (GHSA-x4vx-rjvf-j5p4). */\n    const elementNamespace = _readNamespaceURI(element);\n    const tagName = stringToLowerCase(_readNodeName(element));\n\n    // A missing parent (JSDOM inside shadow DOM) or a non-element parent\n    // (DocumentFragment, ShadowRoot, Document) is simulated as a <template>\n    // in the configured namespace, as before.\n    const parentNode = getParentNode(element);\n    let parentNamespace: string | null = NAMESPACE;\n    let parentTagName = 'template';\n    if (parentNode && _readNodeType(parentNode) === NODE_TYPE.element) {\n      parentNamespace = _readNamespaceURI(parentNode);\n      parentTagName = stringToLowerCase(_readNodeName(parentNode));\n    }\n\n    if (!ALLOWED_NAMESPACES[elementNamespace]) {\n      return false;\n    }\n\n    if (elementNamespace === SVG_NAMESPACE) {\n      return _checkSvgNamespace(tagName, parentNamespace, parentTagName);\n    }\n\n    if (elementNamespace === MATHML_NAMESPACE) {\n      return _checkMathMlNamespace(tagName, parentNamespace, parentTagName);\n    }\n\n    if (elementNamespace === HTML_NAMESPACE) {\n      return _checkHtmlNamespace(tagName, parentNamespace, parentTagName);\n    }\n\n    // An allowed custom namespace is only valid in XHTML and XML documents\n    return PARSER_MEDIA_TYPE === 'application/xhtml+xml';\n  };\n\n  /**\n   * _forceRemove\n   *\n   * @param node a DOM node\n   */\n  const _forceRemove = function (node: Node): void {\n    arrayPush(DOMPurify.removed, { element: node });\n\n    try {\n      // eslint-disable-next-line unicorn/prefer-dom-node-remove\n      getParentNode(node).removeChild(node);\n    } catch (_) {\n      /* Only a parentless node gets here, e.g. a detached in-place root.\n         remove() is a no-op on it, so the node would be handed back intact.\n         Fail closed by throwing rather than neutralizing it through its own,\n         clobberable methods (GHSA-r47g-fvhr-h676). */\n      remove(node);\n\n      if (!getParentNode(node)) {\n        throw typeErrorCreate(\n          'a node selected for removal could not be detached from its tree ' +\n            'and cannot be safely returned; refusing to sanitize in place'\n        );\n      }\n    }\n  };\n\n  /**\n   * Removes an Attr node as that exact node, without book-keeping. Name-based\n   * removal lowercases the name in HTML documents and would miss a\n   * case-preserved one such as `ONERROR`, so it is only the fallback for\n   * clobbered or detached nodes.\n   *\n   * @param element the element to strip the attribute from\n   * @param attribute the Attr node to remove\n   * @param name the attribute's name, for the fallback path\n   */\n  const _stripAttributeNode = function (\n    element: Element,\n    attribute: Attr,\n    name: string\n  ): void {\n    try {\n      removeAttributeNode(element, attribute);\n    } catch (_) {\n      try {\n        element.removeAttribute(name);\n      } catch (_) {}\n    }\n  };\n\n  /**\n   * Fail-closed teardown of an in-place root: strip every disallowed attribute\n   * in the subtree first, so nothing armed is left behind, then remove all\n   * children and the root's own attributes.\n   *\n   * @param root the in-place root to empty\n   */\n  const _neutralizeRoot = function (root: Node): void {\n    _neutralizeSubtree(root);\n\n    const childNodes = getChildNodes(root);\n    if (childNodes) {\n      arrayForEach(arraySlice(childNodes), (child: Node) => {\n        try {\n          remove(child);\n        } catch (_) {\n          /* Best effort */\n        }\n      });\n    }\n\n    // Only elements have attributes; the root may be a rejected fragment\n    if (_readNodeType(root) === NODE_TYPE.element) {\n      _stripAttributes(root as Element, false);\n    }\n  };\n\n  /**\n   * Removes an attribute, preferably as its exact Attr node: name-based\n   * removal lowercases the name in HTML documents and misses case-preserved\n   * names, e.g. from imported XHTML.\n   *\n   * @param name an Attribute name\n   * @param element a DOM node\n   * @param attr the exact Attr node to remove, when the caller has it\n   */\n  const _removeAttribute = function (\n    name: string,\n    element: Element,\n    attr?: Attr | null\n  ): void {\n    if (!attr) {\n      try {\n        attr = element.getAttributeNode(name);\n      } catch (_) {\n        attr = null;\n      }\n    }\n\n    arrayPush(DOMPurify.removed, {\n      attribute: attr || null,\n      from: element,\n    });\n\n    if (attr) {\n      _stripAttributeNode(element, attr, name);\n    } else {\n      try {\n        element.removeAttribute(name);\n      } catch (_) {}\n    }\n\n    // We void attribute values for unremovable \"is\" attributes\n    if (name === 'is') {\n      if (RETURN_DOM || RETURN_DOM_FRAGMENT) {\n        try {\n          _forceRemove(element);\n        } catch (_) {}\n      } else {\n        try {\n          element.setAttribute(name, '');\n        } catch (_) {}\n      }\n    }\n  };\n\n  /**\n   * Removes an element's attributes without book-keeping. Used to neutralize\n   * nodes discarded from an in-place tree.\n   *\n   * @param element the element to strip\n   * @param keepAllowed whether attributes on the allowlist stay\n   */\n  const _stripAttributes = function (\n    element: Element,\n    keepAllowed: boolean\n  ): void {\n    const attributes = getAttributes(element);\n    if (!attributes) {\n      return;\n    }\n\n    for (let i = attributes.length - 1; i >= 0; --i) {\n      const attribute = attributes[i];\n      const name = attribute && attribute.name;\n      if (\n        typeof name === 'string' &&\n        !(keepAllowed && ALLOWED_ATTR[transformCaseFunc(name)])\n      ) {\n        _stripAttributeNode(element, attribute, name);\n      }\n    }\n  };\n\n  /**\n   * Iterative depth-first walk, so deep trees cannot overflow the call stack,\n   * reading through the cached getters, so clobbering cannot hide children.\n   * When `visit` returns false, the node's children are skipped. With\n   * `intoShadow`, open shadow roots are walked after their host's children.\n   *\n   * @param root where to start\n   * @param visit called for every node\n   * @param intoShadow whether to enter open shadow roots\n   */\n  const _walkTree = function (\n    root: Node,\n    visit: (node: Node) => boolean | void,\n    intoShadow = false\n  ): void {\n    const stack: Node[] = [root];\n\n    while (stack.length > 0) {\n      const node = stack.pop();\n      if (visit(node) === false) {\n        continue;\n      }\n\n      if (intoShadow && _readNodeType(node) === NODE_TYPE.element) {\n        const shadowRoot = getShadowRoot(node);\n        if (_isDocumentFragment(shadowRoot)) {\n          stack.push(shadowRoot);\n        }\n      }\n\n      const childNodes = getChildNodes(node);\n      if (childNodes) {\n        for (let i = childNodes.length - 1; i >= 0; --i) {\n          stack.push(childNodes[i]);\n        }\n      }\n    }\n  };\n\n  /**\n   * Strips disallowed attributes from every element of a discarded subtree,\n   * so a handler that is already queued (a loading image) cannot fire.\n   *\n   * @param root the root of a removed subtree\n   */\n  const _neutralizeSubtree = function (root: Node): void {\n    _walkTree(root, (node) => {\n      if (_readNodeType(node) === NODE_TYPE.element) {\n        _stripAttributes(node as Element, true);\n      }\n    });\n  };\n\n  /**\n   * All nodes under `root`, root first, including open shadow roots. Template\n   * content is not entered, it is inert.\n   *\n   * @param root the in-place root\n   * @return the nodes\n   */\n  const _collectLiveNodes = function (root: Node): Node[] {\n    const nodes: Node[] = [];\n    _walkTree(\n      root,\n      (node) => {\n        nodes.push(node);\n      },\n      true\n    );\n    return nodes;\n  };\n\n  /**\n   * Strips disallowed attributes from every element that was under the\n   * in-place root when the call started and no longer is, whatever removed\n   * or moved it.\n   *\n   * @param root the in-place root\n   * @param before the root's nodes, collected before the walk\n   */\n  const _neutralizeEscapedElements = function (\n    root: Node,\n    before: Node[]\n  ): void {\n    const reachable = setCreate();\n    arrayForEach(_collectLiveNodes(root), (node: Node) => {\n      if (_readNodeType(node) === NODE_TYPE.element) {\n        setAdd(reachable, node);\n      }\n    });\n    arrayForEach(before, (node: Node) => {\n      if (\n        _readNodeType(node) === NODE_TYPE.element &&\n        !setHas(reachable, node)\n      ) {\n        _stripAttributes(node as Element, true);\n      }\n    });\n  };\n\n  /**\n   * Neutralizes everything that left the in-place tree during the call: what\n   * DOMPurify removed, and what hooks or custom elements removed or moved out.\n   *\n   * @param root the in-place root\n   * @param before the root's nodes, collected before the walk\n   * @return true if the root itself was removed\n   */\n  const _neutralizeDiscarded = function (root: Node, before: Node[]): boolean {\n    let rootRemoved = false;\n    arrayForEach(DOMPurify.removed, (entry) => {\n      if (entry.element) {\n        rootRemoved = rootRemoved || entry.element === root;\n        _neutralizeSubtree(entry.element as Node);\n      }\n    });\n    _neutralizeEscapedElements(root, before);\n    return rootRemoved;\n  };\n\n  const MAX_UNVISITED_ROUNDS = 8;\n\n  /**\n   * The walk only moves forward, so a node moved to a position it already\n   * passed is never visited. Give every original node that is still in the\n   * tree but unvisited the normal treatment, hooks included. Nodes created\n   * during the call are left alone. Fails closed if the tree keeps changing.\n   *\n   * @param root the in-place root\n   * @param before the root's nodes, collected before the walk\n   */\n  const _sanitizeUnvisitedNodes = function (root: Node, before: Node[]): void {\n    const visited = IN_PLACE_VISITED;\n    /* Built lazily: usually every live node was visited */\n    let original: Set<unknown> | null = null;\n    const getOriginal = (): Set<unknown> => {\n      if (!original) {\n        original = setCreate();\n        arrayForEach(before, (beforeNode: Node) => {\n          setAdd(original, beforeNode);\n        });\n      }\n\n      return original;\n    };\n\n    for (let round = 0; ; round++) {\n      const live = _collectLiveNodes(root);\n      const containers: Node[] = [root];\n      let pending = false;\n\n      arrayForEach(live, (node: Node) => {\n        if (_readNodeType(node) === NODE_TYPE.documentFragment) {\n          /* An open shadow root under the root */\n          arrayPush(containers, node);\n        } else if (!pending && !setHas(visited, node)) {\n          pending = setHas(getOriginal(), node);\n        }\n      });\n\n      if (!pending) {\n        return;\n      }\n\n      if (round >= MAX_UNVISITED_ROUNDS) {\n        throw typeErrorCreate(\n          'the tree kept changing during in-place sanitization; ' +\n            'refusing to return it'\n        );\n      }\n\n      arrayForEach(containers, (container: Node, index: number) => {\n        _sanitizeUnvisitedIn(container, index > 0, root, getOriginal());\n      });\n    }\n  };\n\n  /**\n   * One _sanitizeUnvisitedNodes pass over the root or an open shadow root.\n   *\n   * @param container the root or an open shadow root\n   * @param inShadow whether container is a shadow root\n   * @param root the in-place root\n   * @param original the root's nodes collected before the walk, as a set\n   */\n  const _sanitizeUnvisitedIn = function (\n    container: Node,\n    inShadow: boolean,\n    root: Node,\n    original: Set<unknown>\n  ): void {\n    const iterator = _createNodeIterator(container);\n    let node: Node | null;\n    while ((node = iterator.nextNode())) {\n      if (!setHas(original, node) || setHas(IN_PLACE_VISITED, node)) {\n        continue;\n      }\n\n      if (inShadow) {\n        _executeHooks(hooks.uponSanitizeShadowNode, node, null);\n      }\n\n      _sanitizeNode(node, root);\n    }\n  };\n\n  /**\n   * Records that _sanitizeElements processed `node`. No-op outside IN_PLACE.\n   *\n   * @param node the node being processed\n   */\n  const _markVisited = function (node: Node): void {\n    if (IN_PLACE_VISITED) {\n      setAdd(IN_PLACE_VISITED, node);\n    }\n  };\n\n  /**\n   * Patch-linkage attributes (declarative partial updates): `patchsrc`\n   * always, `for` everywhere except on <label> and <output>. Gated on\n   * SAFE_FOR_XML. Shared by the IN_PLACE pre-pass and _isValidAttribute.\n   *\n   * @param lcName the transformCaseFunc'd attribute name\n   * @param lcTag the transformCaseFunc'd tag name of the carrying element\n   * @return true if the attribute is patch linkage and must be dropped\n   */\n  const _isPatchLinkageAttribute = function (\n    lcName: string,\n    lcTag: string\n  ): boolean {\n    if (!SAFE_FOR_XML) {\n      return false;\n    }\n\n    if (lcName === 'patchsrc') {\n      return true;\n    }\n\n    return lcName === 'for' && lcTag !== 'label' && lcTag !== 'output';\n  };\n\n  /**\n   * IN_PLACE pre-pass: sever all patch linkage before the walk, so no patch\n   * can fire mid-walk into a part of the tree the walker already passed.\n   * Removes range markers (processing instructions, comments with markup)\n   * and strips linkage attributes. It cannot undo a patch that already fired.\n   *\n   * TODO: if the shipped feature can patch through `for` on <label>/<output>,\n   * drop that pair here too.\n   *\n   * @param root the in-place root to sweep\n   */\n  const _neutralizePatchLinkage = function (root: Node): void {\n    if (!SAFE_FOR_XML) {\n      return;\n    }\n\n    _walkTree(root, (node) => {\n      const nodeType = _readNodeType(node);\n\n      // Range markers: processing instructions, comments with markup\n      if (\n        nodeType === NODE_TYPE.processingInstruction ||\n        (nodeType === NODE_TYPE.comment &&\n          regExpTest(EXPRESSIONS.COMMENT_MARKUP_PROBE, (node as any).data))\n      ) {\n        try {\n          remove(node);\n        } catch (_) {\n          /* Best effort */\n        }\n\n        return false;\n      }\n\n      // Linkage attributes\n      if (nodeType === NODE_TYPE.element) {\n        const element = node as Element;\n        const lcTag = transformCaseFunc(_readNodeName(node));\n        try {\n          if (element.hasAttribute && element.hasAttribute('patchsrc')) {\n            element.removeAttribute('patchsrc');\n          }\n\n          if (\n            element.hasAttribute &&\n            element.hasAttribute('for') &&\n            _isPatchLinkageAttribute('for', lcTag)\n          ) {\n            element.removeAttribute('for');\n          }\n        } catch (_) {\n          /* Clobbered methods on a doomed node */\n        }\n      }\n\n      return true;\n    });\n  };\n\n  /**\n   * _initDocument\n   *\n   * @param dirty - a string of dirty markup\n   * @return a DOM, filled with the dirty markup\n   */\n  const _initDocument = function (dirty: string): Document {\n    /* Create a HTML document */\n    let doc = null;\n    let leadingWhitespace = null;\n\n    if (FORCE_BODY) {\n      dirty = '<remove></remove>' + dirty;\n    } else {\n      /* If FORCE_BODY isn't used, leading whitespace needs to be preserved manually */\n      const matches = stringMatch(dirty, EXPRESSIONS.LEADING_WHITESPACE);\n      leadingWhitespace = matches && matches[0];\n    }\n\n    if (\n      PARSER_MEDIA_TYPE === 'application/xhtml+xml' &&\n      NAMESPACE === HTML_NAMESPACE\n    ) {\n      // Root of XHTML doc must contain xmlns declaration (see https://www.w3.org/TR/xhtml1/normative.html#strict)\n      dirty =\n        '<html xmlns=\"http://www.w3.org/1999/xhtml\"><head></head><body>' +\n        dirty +\n        '</body></html>';\n    }\n\n    const dirtyPayload = trustedTypesPolicy ? _createTrustedHTML(dirty) : dirty;\n    /*\n     * Use the DOMParser API by default, fallback later if needs be\n     * DOMParser not work for svg when has multiple root element.\n     */\n    if (NAMESPACE === HTML_NAMESPACE) {\n      try {\n        doc = new DOMParser().parseFromString(dirtyPayload, PARSER_MEDIA_TYPE);\n      } catch (_) {}\n    }\n\n    /* Use createHTMLDocument in case DOMParser is not available */\n    if (!doc || !doc.documentElement) {\n      doc = implementation.createDocument(NAMESPACE, 'template', null);\n      try {\n        doc.documentElement.innerHTML = IS_EMPTY_INPUT\n          ? emptyHTML\n          : dirtyPayload;\n      } catch (_) {\n        // Syntax error if dirtyPayload is invalid xml\n      }\n    }\n\n    const body = doc.body || doc.documentElement;\n\n    if (dirty && leadingWhitespace) {\n      body.insertBefore(\n        document.createTextNode(leadingWhitespace),\n        body.childNodes[0] || null\n      );\n    }\n\n    /* Work on whole document or just its body */\n    if (NAMESPACE === HTML_NAMESPACE) {\n      return getElementsByTagName.call(\n        doc,\n        WHOLE_DOCUMENT ? 'html' : 'body'\n      )[0];\n    }\n\n    return WHOLE_DOCUMENT ? doc.documentElement : body;\n  };\n\n  /**\n   * Creates a NodeIterator over `root`. ownerDocument is read through the\n   * cached getter: a form child named \"ownerDocument\" shadows the direct\n   * read and would make createNodeIterator throw.\n   *\n   * @param root The node to start traversing on.\n   * @param characterDataOnly whether to skip elements\n   * @return The created NodeIterator\n   */\n  const _createNodeIterator = function (\n    root: Node,\n    characterDataOnly = false\n  ): NodeIterator {\n    const doc = getOwnerDocument ? getOwnerDocument(root) : root.ownerDocument;\n    return createNodeIterator.call(\n      doc || root,\n      root,\n      // eslint-disable-next-line no-bitwise\n      (characterDataOnly ? 0 : NodeFilter.SHOW_ELEMENT) |\n        NodeFilter.SHOW_COMMENT |\n        NodeFilter.SHOW_TEXT |\n        NodeFilter.SHOW_PROCESSING_INSTRUCTION |\n        NodeFilter.SHOW_CDATA_SECTION,\n      null\n    );\n  };\n\n  /**\n   * Replace template expression syntax (mustache, ERB, template\n   * literal) with a space; shared by all SAFE_FOR_TEMPLATES scrub\n   * sites. Order matters: mustache, then ERB, then template literal.\n   *\n   * @param value the string to scrub\n   * @returns the scrubbed string\n   */\n  const _stripTemplateExpressions = function (value: string): string {\n    value = stringReplace(value, MUSTACHE_EXPR, ' ');\n    value = stringReplace(value, ERB_EXPR, ' ');\n    value = stringReplace(value, TMPLIT_EXPR, ' ');\n    return value;\n  };\n\n  /**\n   * Strips template expressions from the character data under `node`,\n   * template contents included. Runs after the walk, since an expression can\n   * also form when a removed element leaves two text nodes adjacent. Works on\n   * the nodes rather than on markup, which keeps node references intact and\n   * sees `<%` unescaped. Attribute values are handled in _sanitizeAttributes.\n   *\n   * @param node The root element whose character data should be scrubbed.\n   */\n  const _scrubTemplateExpressions = function (node: Element): void {\n    _scrubOwnCharacterData(node);\n\n    // NodeIterator does not descend into <template>.content per the DOM spec,\n    // so we must explicitly recurse into each template's content fragment,\n    // mirroring the approach used by _sanitizeShadowDOM.\n    const templates = node.querySelectorAll?.('template');\n    if (templates) {\n      arrayForEach(templates, (tmpl: HTMLTemplateElement) => {\n        if (_isDocumentFragment(tmpl.content)) {\n          _scrubTemplateExpressions(tmpl.content as unknown as Element);\n        }\n      });\n    }\n  };\n\n  /**\n   * Normalizes `node` and strips template expressions from its own character\n   * data. Template contents and shadow roots are not entered, their own\n   * _sanitizeShadowDOM call scrubs them.\n   *\n   * @param node The root whose own character data should be scrubbed.\n   */\n  const _scrubOwnCharacterData = function (node: Element): void {\n    node.normalize();\n    const walker = _createNodeIterator(node, true);\n\n    let currentNode = walker.nextNode() as CharacterData | null;\n    while (currentNode) {\n      currentNode.data = _stripTemplateExpressions(currentNode.data);\n      currentNode = walker.nextNode() as CharacterData | null;\n    }\n  };\n\n  /**\n   * Detects DOM clobbering on a form, the only element whose named children\n   * shadow its own properties. Each probe compares a direct read with what\n   * the property has to be.\n   *\n   * @param element element to check for clobbering attacks\n   * @return true if clobbered, false if safe\n   */\n  const _isClobbered = function (element: Element): boolean {\n    // Without a readable tag name there is nothing to check here; the\n    // caller's other defences still apply\n    const realTagName = getNodeName ? getNodeName(element) : null;\n    if (typeof realTagName !== 'string') {\n      return false;\n    }\n\n    if (transformCaseFunc(realTagName) !== 'form') {\n      return false;\n    }\n\n    return (\n      typeof element.nodeName !== 'string' ||\n      typeof element.textContent !== 'string' ||\n      typeof element.removeChild !== 'function' ||\n      // Direct and cached reads differ when a child is named \"attributes\"\n      element.attributes !== getAttributes(element) ||\n      typeof element.removeAttribute !== 'function' ||\n      // Without these two, attribute removal falls back to removal by name,\n      // which misses case-preserved names\n      typeof element.removeAttributeNode !== 'function' ||\n      typeof element.getAttributeNode !== 'function' ||\n      typeof element.setAttribute !== 'function' ||\n      typeof element.namespaceURI !== 'string' ||\n      typeof element.insertBefore !== 'function' ||\n      typeof element.hasChildNodes !== 'function' ||\n      // Same comparison as for attributes\n      element.nodeType !== getNodeType(element) ||\n      element.childNodes !== getChildNodes(element)\n    );\n  };\n\n  /**\n   * Reads nodeType through the cached getter, so the result holds for nodes\n   * from any realm (GHSA-4w3q-35jp-p934) and cannot be clobbered.\n   *\n   * @param value anything\n   * @return the node type, or null if value is not a DOM node\n   */\n  const _nodeTypeOf = function (value: unknown): number | null {\n    if (!getNodeType || typeof value !== 'object' || value === null) {\n      return null;\n    }\n\n    try {\n      const nodeType = getNodeType(value as Node);\n      return typeof nodeType === 'number' ? nodeType : null;\n    } catch (_) {\n      return null;\n    }\n  };\n\n  const _isDocumentFragment = function (value: unknown): boolean {\n    return _nodeTypeOf(value) === NODE_TYPE.documentFragment;\n  };\n\n  const _isNode = function (value: unknown): value is Node {\n    return _nodeTypeOf(value) !== null;\n  };\n\n  function _executeHooks<T extends HookFunction>(\n    hooks: HookFunction[],\n    currentNode: Parameters<T>[0],\n    data: Parameters<T>[1]\n  ): void {\n    if (hooks.length === 0) {\n      return;\n    }\n\n    arrayForEach(hooks, (hook: T) => {\n      hook.call(DOMPurify, currentNode, data, CONFIG);\n    });\n  }\n\n  /**\n   * Structural-threat checks that condemn a node regardless of the\n   * allowlists: mXSS via namespace confusion, risky CSS construction,\n   * processing instructions, markup-bearing comments. Pure predicate;\n   * the caller removes. Check order is load-bearing.\n   *\n   * @param currentNode the node to inspect\n   * @param tagName the node's transformCaseFunc'd tag name\n   * @param nodeType the node's type, read through the cached getter\n   * @return true if the node must be removed\n   */\n  const _isUnsafeNode = function (\n    currentNode: any,\n    tagName: string,\n    nodeType: number\n  ): boolean {\n    /* Detect mXSS attempts abusing namespace confusion */\n    if (\n      SAFE_FOR_XML &&\n      nodeType === NODE_TYPE.element &&\n      currentNode.hasChildNodes() &&\n      !_isNode(currentNode.firstElementChild) &&\n      regExpTest(EXPRESSIONS.ELEMENT_MARKUP_PROBE, currentNode.textContent) &&\n      regExpTest(EXPRESSIONS.ELEMENT_MARKUP_PROBE, currentNode.innerHTML)\n    ) {\n      return true;\n    }\n\n    /* Literal-text elements holding an element child or markup-like text,\n       see LITERAL_TEXT_ELEMENTS. Reads textContent, as an XML document\n       escapes innerHTML. Elements only: a processing instruction's nodeName\n       is its target and can collide with these names. */\n    if (\n      SAFE_FOR_XML &&\n      LITERAL_TEXT_ELEMENTS[tagName] &&\n      nodeType === NODE_TYPE.element &&\n      _readNamespaceURI(currentNode) === HTML_NAMESPACE &&\n      (_isNode(currentNode.firstElementChild) ||\n        (typeof currentNode.textContent === 'string' &&\n          regExpTest(\n            EXPRESSIONS.ELEMENT_MARKUP_PROBE,\n            currentNode.textContent\n          )))\n    ) {\n      return true;\n    }\n\n    /* Remove any occurrence of processing instructions */\n    if (nodeType === NODE_TYPE.processingInstruction) {\n      return true;\n    }\n\n    /* Remove any kind of possibly harmful comments */\n    if (\n      SAFE_FOR_XML &&\n      nodeType === NODE_TYPE.comment &&\n      regExpTest(EXPRESSIONS.COMMENT_MARKUP_PROBE, currentNode.data)\n    ) {\n      return true;\n    }\n\n    return false;\n  };\n\n  /**\n   * Evaluate a CUSTOM_ELEMENT_HANDLING check (a RegExp or a predicate\n   * function, per the validation in _parseConfig) against a name.\n   * Additional arguments are forwarded to predicate functions - the\n   * attributeNameCheck predicate receives the tag name as its second\n   * argument. A null/absent check never matches.\n   *\n   * @param check the configured tagNameCheck / attributeNameCheck value\n   * @param name the name to test\n   * @param args extra arguments forwarded to a predicate function\n   * @return true if the check matches the name\n   */\n  const _matchesNameCheck = function (\n    check: unknown,\n    name: string,\n    ...args: unknown[]\n  ): boolean {\n    if (check instanceof RegExp) {\n      return regExpTest(check, name);\n    }\n\n    if (check instanceof Function) {\n      return Boolean(check(name, ...args));\n    }\n\n    return false;\n  };\n\n  /**\n   * Handles a node whose tag is forbidden or not allowlisted: hoists its\n   * content per KEEP_CONTENT and removes it. The one exception is a custom\n   * element allowed via CUSTOM_ELEMENT_HANDLING, which is kept.\n   *\n   * @param currentNode the disallowed node\n   * @param tagName the node's transformCaseFunc'd tag name\n   * @return true if the node was removed, false if kept\n   */\n  const _sanitizeDisallowedNode = function (\n    currentNode: any,\n    tagName: string,\n    root: Node\n  ): boolean {\n    /* Check if we have a custom element to handle */\n    if (\n      !FORBID_TAGS[tagName] &&\n      _isBasicCustomElement(tagName) &&\n      _matchesNameCheck(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName)\n    ) {\n      return false;\n    }\n\n    /* Keep content except for bad-listed elements */\n    if (\n      KEEP_CONTENT &&\n      !FORBID_CONTENTS[tagName] &&\n      /* XHTML keeps the tag's case, the default list is lowercase */\n      !FORBID_CONTENTS[stringToLowerCase(tagName)]\n    ) {\n      const parentNode = getParentNode(currentNode);\n      const childNodes = getChildNodes(currentNode);\n\n      if (childNodes && parentNode) {\n        const childCount = childNodes.length;\n\n        /* Move the children up rather than cloning them: linear for nested\n           disallowed elements, and a child with a queued event (a loading\n           image) gets sanitized instead of staying detached and armed. Only\n           the walk root's children are cloned, as the result is serialized\n           from inside the root. Tail to head, as childNodes is live. */\n        for (let i = childCount - 1; i >= 0; --i) {\n          const hoisted =\n            currentNode === root\n              ? cloneNode(childNodes[i], true)\n              : childNodes[i];\n          parentNode.insertBefore(hoisted, getNextSibling(currentNode));\n        }\n      }\n    }\n\n    _forceRemove(currentNode);\n    return true;\n  };\n\n  /**\n   * Forks an allowlist off its shared binding (the instance default or the\n   * setConfig() capture) before a hook sees it, so a hook's widening stays\n   * within the call. A set that is already call-local is returned as is.\n   *\n   * @param hookList the uponSanitize* hook array for this event\n   * @param set the current ALLOWED_TAGS / ALLOWED_ATTR binding\n   * @param defaultSet the per-instance DEFAULT_ALLOWED_* constant\n   * @param setConfigSet the captured setConfig() binding, or null\n   * @return a call-local clone if a hook is present and set is still shared,\n   *   else set unchanged\n   */\n  const _forkSharedAllowlist = function <T extends Record<string, any>>(\n    hookList: unknown[],\n    set: T,\n    defaultSet: T,\n    setConfigSet: T | null\n  ): T {\n    if (hookList.length === 0) {\n      return set;\n    }\n\n    return set === defaultSet || set === setConfigSet ? cloneSet(set) : set;\n  };\n\n  /**\n   * A hook may have detached the node it was called for. If so, treat it as\n   * removed and stop processing it; the walk root is exempt. On the IN_PLACE\n   * path the detached subtree is neutralized right away.\n   *\n   * @param currentNode the node a hook may have detached\n   * @param root the current walk root\n   * @return true if the node was detached\n   */\n  const _handleHookDetachedNode = function (\n    currentNode: Node,\n    root: Node\n  ): boolean {\n    if (currentNode === root || getParentNode(currentNode) !== null) {\n      return false;\n    }\n\n    if (IN_PLACE) {\n      _neutralizeSubtree(currentNode);\n    }\n\n    return true;\n  };\n\n  /**\n   * _sanitizeElements\n   *\n   * @protect nodeName\n   * @protect textContent\n   * @protect removeChild\n   * @param currentNode to check for permission to exist\n   * @return true if node was killed, false if left alive\n   */\n  const _sanitizeElements = function (currentNode: any, root: Node): boolean {\n    /* IN_PLACE: remember the node was processed (see _sanitizeUnvisitedNodes). */\n    _markVisited(currentNode);\n\n    /* Execute a hook if present */\n    _executeHooks(hooks.beforeSanitizeElements, currentNode, null);\n\n    /* A hook may have detached the node - treat it as removed (see\n       _handleHookDetachedNode for the full rationale). */\n    if (_handleHookDetachedNode(currentNode, root)) {\n      return true;\n    }\n\n    /* Check if element is clobbered or can clobber */\n    if (_isClobbered(currentNode)) {\n      _forceRemove(currentNode);\n      return true;\n    }\n\n    /* Now let's check the element's type and name */\n    const tagName = transformCaseFunc(_readNodeName(currentNode));\n    const nodeType = _readNodeType(currentNode);\n\n    /* The hook gets ALLOWED_TAGS by reference; fork it off a shared binding\n       first, so widening stays scoped to this call. */\n    ALLOWED_TAGS = _forkSharedAllowlist(\n      hooks.uponSanitizeElement,\n      ALLOWED_TAGS,\n      DEFAULT_ALLOWED_TAGS,\n      SET_CONFIG_ALLOWED_TAGS\n    );\n\n    /* Execute a hook if present */\n    _executeHooks(hooks.uponSanitizeElement, currentNode, {\n      tagName,\n      allowedTags: ALLOWED_TAGS,\n    });\n\n    /* The uponSanitizeElement hook may have detached the node, exactly as\n       above (see _handleHookDetachedNode for the full rationale). */\n    if (_handleHookDetachedNode(currentNode, root)) {\n      return true;\n    }\n\n    /* Remove mXSS vectors, processing instructions and risky comments */\n    if (_isUnsafeNode(currentNode, tagName, nodeType)) {\n      _forceRemove(currentNode);\n      return true;\n    }\n\n    /* Remove element if anything forbids its presence */\n    if (\n      FORBID_TAGS[tagName] ||\n      (!(\n        EXTRA_ELEMENT_HANDLING.tagCheck instanceof Function &&\n        EXTRA_ELEMENT_HANDLING.tagCheck(tagName)\n      ) &&\n        !ALLOWED_TAGS[tagName])\n    ) {\n      const removed = _sanitizeDisallowedNode(currentNode, tagName, root);\n\n      /* A kept custom element still gets afterSanitizeElements, like any\n         allowed element (GHSA-c2j3-45gr-mqc4). */\n      if (removed === false) {\n        _executeHooks(hooks.afterSanitizeElements, currentNode, null);\n\n        /* The hook may have detached the kept custom element. Same\n           IN_PLACE hazard as the before/upon sites: neutralize the\n           detached subtree before the walker skips past it (see\n           _handleHookDetachedNode). */\n        if (_handleHookDetachedNode(currentNode, root)) {\n          return true;\n        }\n      }\n\n      return removed;\n    }\n\n    /* Check whether element has a valid namespace. nodeType comes from the\n       cached getter, which also holds for foreign-realm nodes\n       (GHSA-hpcv-96wg-7vj8). */\n    if (nodeType === NODE_TYPE.element && !_checkValidNamespace(currentNode)) {\n      _forceRemove(currentNode);\n      return true;\n    }\n\n    /* Make sure that older browsers don't get fallback-tag mXSS */\n    if (\n      (tagName === 'noscript' ||\n        tagName === 'noembed' ||\n        tagName === 'noframes') &&\n      regExpTest(EXPRESSIONS.FALLBACK_TAG_CLOSE, currentNode.innerHTML)\n    ) {\n      _forceRemove(currentNode);\n      return true;\n    }\n\n    /* Sanitize element content to be template-safe */\n    if (SAFE_FOR_TEMPLATES && nodeType === NODE_TYPE.text) {\n      const text = currentNode.textContent;\n      const content = _stripTemplateExpressions(text);\n\n      if (text !== content) {\n        arrayPush(DOMPurify.removed, { element: currentNode.cloneNode() });\n        currentNode.textContent = content;\n      }\n    }\n\n    /* Execute a hook if present */\n    _executeHooks(hooks.afterSanitizeElements, currentNode, null);\n\n    /* A node detached by this hook is not visited again, so report it as\n       removed. */\n    return _handleHookDetachedNode(currentNode, root);\n  };\n\n  /**\n   * _isValidAttribute\n   *\n   * @param lcTag Lowercase tag name of containing element.\n   * @param lcName Lowercase attribute name.\n   * @param value Attribute value.\n   * @return Returns true if `value` is valid, otherwise false.\n   */\n  // eslint-disable-next-line complexity\n  const _isValidAttribute = function (\n    lcTag: string,\n    lcName: string,\n    value: string\n  ): boolean {\n    /* FORBID_ATTR must always win, even if ADD_ATTR predicate would allow it */\n    if (FORBID_ATTR[lcName]) {\n      return false;\n    }\n\n    /* Patch-linkage attributes of declarative partial updates\n       (https://github.com/WICG/declarative-partial-updates). The patch itself\n       is applied at parse or connection time, so the walk already sees the\n       expanded tree. Dropping the linkage keeps it from expanding again in\n       the caller's context. */\n    if (_isPatchLinkageAttribute(lcName, lcTag)) {\n      return false;\n    }\n\n    /* Make sure attribute cannot clobber */\n    if (\n      SANITIZE_DOM &&\n      (lcName === 'id' || lcName === 'name') &&\n      (value in document || value in formElement)\n    ) {\n      return false;\n    }\n\n    const nameIsPermitted =\n      ALLOWED_ATTR[lcName] ||\n      (EXTRA_ELEMENT_HANDLING.attributeCheck instanceof Function &&\n        EXTRA_ELEMENT_HANDLING.attributeCheck(lcName, lcTag));\n\n    /* Allow valid data-* attributes: At least one character after \"-\"\n        (https://html.spec.whatwg.org/multipage/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes)\n        XML-compatible (https://html.spec.whatwg.org/multipage/infrastructure.html#xml-compatible and http://www.w3.org/TR/xml/#d0e804)\n        We don't need to check the value; it's always URI safe. */\n    if (ALLOW_DATA_ATTR && regExpTest(DATA_ATTR, lcName)) {\n      return true;\n    }\n\n    /* Allow valid aria-* attributes, the value is always URI safe */\n    if (ALLOW_ARIA_ATTR && regExpTest(ARIA_ATTR, lcName)) {\n      return true;\n    }\n\n    /* A name outside the allowlist is only acceptable on custom-element\n       terms. The value checks below are skipped then, as custom elements\n       define their attributes at their own discretion. */\n    if (!nameIsPermitted) {\n      return (\n        // Condition a) covers a basically valid custom element tag name whose\n        // tag passes the configured tagNameCheck and whose attribute name\n        // passes the configured attributeNameCheck ...\n        (_isBasicCustomElement(lcTag) &&\n          _matchesNameCheck(CUSTOM_ELEMENT_HANDLING.tagNameCheck, lcTag) &&\n          _matchesNameCheck(\n            CUSTOM_ELEMENT_HANDLING.attributeNameCheck,\n            lcName,\n            lcTag\n          )) ||\n        // Condition b) covers an `is` attribute whose value passes the\n        // configured tagNameCheck while customized built-in elements are\n        // allowed.\n        (lcName === 'is' &&\n          CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements &&\n          _matchesNameCheck(CUSTOM_ELEMENT_HANDLING.tagNameCheck, value))\n      );\n    }\n\n    /* Check value is safe. First, is attr inert? If so, is safe */\n    if (URI_SAFE_ATTRIBUTES[lcName]) {\n      return true;\n    }\n\n    /* Check no script, data or unknown possibly unsafe URI\n        unless we know URI values are safe for that attribute */\n    const compactValue = stringReplace(value, ATTR_WHITESPACE, '');\n    if (regExpTest(IS_ALLOWED_URI, compactValue)) {\n      return true;\n    }\n\n    /* Keep image data URIs alive if src/xlink:href is allowed */\n    /* Further prevent gadget XSS for dynamically built script tags */\n    if (\n      (lcName === 'src' || lcName === 'xlink:href' || lcName === 'href') &&\n      lcTag !== 'script' &&\n      stringIndexOf(value, 'data:') === 0 &&\n      DATA_URI_TAGS[lcTag]\n    ) {\n      return true;\n    }\n\n    /* Allow unknown protocols: This provides support for links that\n        are handled by protocol handlers which may be unknown ahead of\n        time, e.g. fb:, spotify: */\n    if (\n      ALLOW_UNKNOWN_PROTOCOLS &&\n      !regExpTest(IS_SCRIPT_OR_DATA, compactValue)\n    ) {\n      return true;\n    }\n\n    /* Only an empty (binary) value remains safe at this point;\n       anything else is presumed unsafe, do not add it back */\n    return !value;\n  };\n\n  /* Names the HTML spec reserves from valid-custom-element-name; these must\n   * never be treated as basic custom elements even when a permissive\n   * CUSTOM_ELEMENT_HANDLING.tagNameCheck is configured. */\n  const RESERVED_CUSTOM_ELEMENT_NAMES = addToSet({}, [\n    'annotation-xml',\n    'color-profile',\n    'font-face',\n    'font-face-format',\n    'font-face-name',\n    'font-face-src',\n    'font-face-uri',\n    'missing-glyph',\n  ]);\n\n  /**\n   * _isBasicCustomElement\n   * checks if at least one dash is included in tagName, and it's not the first char\n   * for more sophisticated checking see https://github.com/sindresorhus/validate-element-name\n   *\n   * @param tagName name of the tag of the node to sanitize\n   * @returns Returns true if the tag name meets the basic criteria for a custom element, otherwise false.\n   */\n  const _isBasicCustomElement = function (tagName: string): boolean {\n    return (\n      !RESERVED_CUSTOM_ELEMENT_NAMES[stringToLowerCase(tagName)] &&\n      regExpTest(CUSTOM_ELEMENT, tagName)\n    );\n  };\n\n  /**\n   * Wrap an attribute value in the matching Trusted Types object when\n   * the active policy requires it. Namespaced attributes pass through\n   * unchanged (no TT support yet, see\n   * https://bugs.chromium.org/p/chromium/issues/detail?id=1305293).\n   *\n   * @param lcTag lowercase tag name of the containing element\n   * @param lcName lowercase attribute name\n   * @param namespaceURI the attribute's namespace, if any\n   * @param value the attribute value to wrap\n   * @return the value, wrapped when Trusted Types demand it\n   */\n  const _applyTrustedTypesToAttribute = function (\n    lcTag: string,\n    lcName: string,\n    namespaceURI: string | null,\n    value: string\n  ): string {\n    if (\n      trustedTypesPolicy &&\n      typeof trustedTypes === 'object' &&\n      typeof trustedTypes.getAttributeType === 'function' &&\n      !namespaceURI\n    ) {\n      switch (trustedTypes.getAttributeType(lcTag, lcName)) {\n        case 'TrustedHTML': {\n          return _createTrustedHTML(value);\n        }\n\n        case 'TrustedScriptURL': {\n          return _createTrustedScriptURL(value);\n        }\n\n        default: {\n          break;\n        }\n      }\n    }\n\n    return value;\n  };\n\n  /**\n   * Writes a changed attribute value back. If the new value clobbers, the\n   * element is removed; if the write fails, the attribute is.\n   *\n   * @param currentNode the element carrying the attribute\n   * @param name the attribute name as present on the element\n   * @param namespaceURI the attribute's namespace, if any\n   * @param value the new attribute value\n   * @return true if the value was written without introducing clobbering\n   */\n  const _setAttributeValue = function (\n    currentNode: Element,\n    name: string,\n    namespaceURI: string | null,\n    value: string\n  ): boolean {\n    try {\n      if (namespaceURI) {\n        currentNode.setAttributeNS(namespaceURI, name, value);\n      } else {\n        /* Fallback to setAttribute() for browser-unrecognized namespaces e.g. \"x-schema\". */\n        currentNode.setAttribute(name, value);\n      }\n\n      if (_isClobbered(currentNode)) {\n        _forceRemove(currentNode);\n        return false;\n      }\n\n      return true;\n    } catch (_) {\n      _removeAttribute(name, currentNode);\n      return false;\n    }\n  };\n\n  /**\n   * Value checks that apply before a hook can force-keep an attribute. Also\n   * used by isValidAttribute(), so it never approves a value that sanitize()\n   * would strip.\n   *\n   * @param name the attribute name as found on the node (case preserved)\n   * @param value the attribute value\n   * @returns true if the attribute must be removed because of its value\n   */\n  const _isUnsafeAttributeValue = function (\n    name: string,\n    value: string\n  ): boolean {\n    /* Work around a security issue with comments inside attributes, and\n       raw-text closers that re-contextualize the value on a later reparse */\n    if (SAFE_FOR_XML && regExpTest(EXPRESSIONS.ATTR_VALUE_BREAKOUT, value)) {\n      return true;\n    }\n\n    /* Make sure we cannot easily use animated hrefs, even if animations are\n       allowed. Case-insensitive, as XHTML keeps the attributeName spelling\n       (GHSA-c6gr-qvv4-5v3f). */\n    return (\n      stringToLowerCase(name) === 'attributename' &&\n      stringIndexOf(value, 'href') !== -1\n    );\n  };\n\n  /**\n   * _sanitizeAttributes\n   *\n   * @protect attributes\n   * @protect nodeName\n   * @protect removeAttribute\n   * @protect setAttribute\n   *\n   * @param currentNode to sanitize\n   * @param root the current walk root\n   */\n  const _sanitizeAttributes = function (\n    currentNode: Element,\n    root: Node\n  ): void {\n    /* Execute a hook if present */\n    _executeHooks(hooks.beforeSanitizeAttributes, currentNode, null);\n\n    /* A hook may have detached the node, see _handleHookDetachedNode */\n    if (_handleHookDetachedNode(currentNode, root)) {\n      return;\n    }\n\n    const { attributes } = currentNode;\n\n    /* Check if we have attributes; if not we might have a text node */\n    if (!attributes || _isClobbered(currentNode)) {\n      return;\n    }\n\n    /* Same as for uponSanitizeElement: fork before a hook can see it. */\n    ALLOWED_ATTR = _forkSharedAllowlist(\n      hooks.uponSanitizeAttribute,\n      ALLOWED_ATTR,\n      DEFAULT_ALLOWED_ATTR,\n      SET_CONFIG_ALLOWED_ATTR\n    );\n\n    const hookEvent = {\n      attrName: '',\n      attrValue: '',\n      keepAttr: true,\n      allowedAttributes: ALLOWED_ATTR,\n      forceKeepAttr: undefined,\n    };\n    let l = attributes.length;\n    const lcTag = transformCaseFunc(_readNodeName(currentNode));\n\n    /* Go backwards over all attributes; safely remove bad ones */\n    while (l--) {\n      const attr = attributes[l];\n      const { name, namespaceURI, value: attrValue } = attr;\n      const lcName = transformCaseFunc(name);\n\n      const initValue = attrValue;\n      let value = name === 'value' ? initValue : stringTrim(initValue);\n\n      /* Set when this attribute pushed a DOMPurify.removed record that the\n         write-back below takes off again. Only the SANITIZE_NAMED_PROPS\n         remove-and-recreate does; any other write-back must not pop, or it\n         would drop an unrelated removal record. */\n      let recreatedNamedProp = false;\n\n      /* Execute a hook if present */\n      hookEvent.attrName = lcName;\n      hookEvent.attrValue = value;\n      hookEvent.keepAttr = true;\n      hookEvent.forceKeepAttr = undefined; // Allows developers to see this is a property they can set\n      _executeHooks(hooks.uponSanitizeAttribute, currentNode, hookEvent);\n      value = hookEvent.attrValue;\n\n      /* Full DOM Clobbering protection via namespace isolation,\n       * Prefix id and name attributes with `user-content-`\n       */\n      if (\n        SANITIZE_NAMED_PROPS &&\n        (lcName === 'id' || lcName === 'name') &&\n        stringIndexOf(value, SANITIZE_NAMED_PROPS_PREFIX) !== 0\n      ) {\n        // Remove the attribute with this value\n        _removeAttribute(name, currentNode, attr);\n        // Prefix the value and later re-create the attribute with the sanitized value\n        value = SANITIZE_NAMED_PROPS_PREFIX + value;\n        // This attribute owns the record just pushed; its recreate writeback\n        // is the one allowed to pop it back off.\n        recreatedNamedProp = true;\n      }\n      // Else: already prefixed, and the prefix is the protection\n\n      /* Value checks that apply regardless of hooks (comment / raw-text\n         closers in the value, animated hrefs); see _isUnsafeAttributeValue. */\n      if (_isUnsafeAttributeValue(name, value)) {\n        _removeAttribute(name, currentNode, attr);\n        continue;\n      }\n\n      /* Did the hooks force-keep the attribute? */\n      if (hookEvent.forceKeepAttr) {\n        continue;\n      }\n\n      /* Did the hooks approve of the attribute? */\n      if (!hookEvent.keepAttr) {\n        _removeAttribute(name, currentNode, attr);\n        continue;\n      }\n\n      /* Work around a security issue in jQuery 3.0 */\n      if (\n        !ALLOW_SELF_CLOSE_IN_ATTR &&\n        regExpTest(EXPRESSIONS.SELF_CLOSING_TAG, value)\n      ) {\n        _removeAttribute(name, currentNode, attr);\n        continue;\n      }\n\n      /* Sanitize attribute content to be template-safe */\n      if (SAFE_FOR_TEMPLATES) {\n        value = _stripTemplateExpressions(value);\n      }\n\n      /* Is `value` valid for this attribute? */\n      if (!_isValidAttribute(lcTag, lcName, value)) {\n        _removeAttribute(name, currentNode, attr);\n        continue;\n      }\n\n      /* Handle attributes that require Trusted Types */\n      value = _applyTrustedTypesToAttribute(lcTag, lcName, namespaceURI, value);\n\n      /* Handle invalid data-* attribute set by try-catching it */\n      if (value !== initValue) {\n        const cleanWrite = _setAttributeValue(\n          currentNode,\n          name,\n          namespaceURI,\n          value\n        );\n\n        if (cleanWrite && recreatedNamedProp) {\n          arrayPop(DOMPurify.removed);\n        }\n      }\n    }\n\n    /* Execute a hook if present */\n    _executeHooks(hooks.afterSanitizeAttributes, currentNode, null);\n\n    /* Same detach re-check as after beforeSanitizeAttributes: this is the\n       last hook that runs for the node, so a detach here would otherwise\n       hand the caller a live, handler-bearing subtree. */\n    _handleHookDetachedNode(currentNode, root);\n  };\n\n  /**\n   * Sanitizes one node: the node itself, its attributes and, for a\n   * template, its content.\n   *\n   * @param node the node to sanitize\n   * @param root the current walk root\n   */\n  const _sanitizeNode = function (node: any, root: Node): void {\n    _sanitizeElements(node, root);\n    _sanitizeAttributes(node, root);\n\n    if (_isDocumentFragment(node.content)) {\n      _sanitizeShadowDOM(node.content);\n    }\n  };\n\n  /**\n   * _sanitizeShadowDOM\n   *\n   * @param fragment to iterate over recursively\n   */\n  const _sanitizeShadowDOM = function (fragment: DocumentFragment): void {\n    let shadowNode = null;\n    const shadowIterator = _createNodeIterator(fragment);\n\n    /* Execute a hook if present */\n    _executeHooks(hooks.beforeSanitizeShadowDOM, fragment, null);\n\n    while ((shadowNode = shadowIterator.nextNode())) {\n      /* Execute a hook if present */\n      _executeHooks(hooks.uponSanitizeShadowNode, shadowNode, null);\n\n      _sanitizeNode(shadowNode, fragment);\n\n      /* NodeIterator does not enter shadow trees, so walk a shadow root\n         hosted inside this fragment explicitly */\n      if (_readNodeType(shadowNode) === NODE_TYPE.element) {\n        const innerSr = getShadowRoot(shadowNode);\n        if (_isDocumentFragment(innerSr)) {\n          _sanitizeAttachedShadowRoots(innerSr);\n          _sanitizeShadowDOM(innerSr);\n        }\n      }\n    }\n\n    /* An expression can form across text nodes once a separating element is\n       removed, so scrub the fragment as a whole. Own data only: nested\n       template contents and shadow roots are scrubbed by their own call.\n       Runs before the hook, which should see the final fragment. */\n    if (SAFE_FOR_TEMPLATES) {\n      _scrubOwnCharacterData(fragment as unknown as Element);\n    }\n\n    /* Execute a hook if present */\n    _executeHooks(hooks.afterSanitizeShadowDOM, fragment, null);\n  };\n\n  /**\n   * Sanitizes every attached shadow root under `root`, since the node\n   * iterator does not enter shadow trees. Needed for IN_PLACE input and for\n   * DOM input whose clonable shadow roots were copied by importNode().\n   *\n   * @param root the subtree root to walk for attached shadow roots\n   */\n  const _sanitizeAttachedShadowRoots = function (root: Node): void {\n    /* Explicit stack, so deep trees cannot overflow the call stack. An item is\n       a node to walk or a shadow root to sanitize. Items are processed in\n       reverse push order: a shadow root is walked first (finding nested\n       roots), then sanitized, then template content, then the children. */\n    const stack: Array<{ node: Node | null; shadow: DocumentFragment | null }> =\n      [{ node: root, shadow: null }];\n\n    while (stack.length > 0) {\n      const item = stack.pop();\n\n      if (item.shadow) {\n        _sanitizeShadowDOM(item.shadow);\n        continue;\n      }\n\n      const node = item.node;\n      const nodeType = _readNodeType(node);\n      const isElement = nodeType === NODE_TYPE.element;\n\n      // Children, copied now since hooks may detach siblings mid-walk\n      const childNodes = getChildNodes(node);\n      if (childNodes) {\n        for (let i = childNodes.length - 1; i >= 0; --i) {\n          stack.push({ node: childNodes[i], shadow: null });\n        }\n      }\n\n      // Template content\n      if (isElement) {\n        const rootName = getNodeName ? getNodeName(node) : null;\n        if (\n          typeof rootName === 'string' &&\n          transformCaseFunc(rootName) === 'template'\n        ) {\n          const content = (node as HTMLTemplateElement).content;\n          if (_isDocumentFragment(content)) {\n            stack.push({ node: content, shadow: null });\n          }\n        }\n      }\n\n      // Shadow root: walk it, then sanitize it (realm-safe nodeType check)\n      if (isElement) {\n        const sr = getShadowRoot(node);\n        if (_isDocumentFragment(sr)) {\n          stack.push({ node: null, shadow: sr }, { node: sr, shadow: null });\n        }\n      }\n    }\n  };\n\n  // eslint-disable-next-line complexity\n  DOMPurify.sanitize = function (dirty, cfg = {}) {\n    let body = null;\n    let importedNode = null;\n    let currentNode = null;\n    let returnNode = null;\n    /* Make sure we have a string to sanitize.\n      DO NOT return early, as this will return the wrong type if\n      the user has requested a DOM object rather than a string */\n    IS_EMPTY_INPUT = !dirty;\n    if (IS_EMPTY_INPUT) {\n      dirty = '<!-->';\n    }\n\n    /* Stringify, in case dirty is an object */\n    if (typeof dirty !== 'string' && !_isNode(dirty)) {\n      dirty = stringifyValue(dirty);\n\n      if (typeof dirty !== 'string') {\n        throw typeErrorCreate('dirty is not a string, aborting');\n      }\n    }\n\n    /* Return dirty HTML if DOMPurify cannot run */\n    if (!DOMPurify.isSupported) {\n      return dirty;\n    }\n\n    /* Assign config vars */\n    if (SET_CONFIG) {\n      /* Persistent setConfig() path: _parseConfig is skipped, so restore the\n       * sets captured at setConfig() time. A hook's fork from a previous\n       * call must not carry over. */\n      ALLOWED_TAGS = SET_CONFIG_ALLOWED_TAGS;\n      ALLOWED_ATTR = SET_CONFIG_ALLOWED_ATTR;\n    } else {\n      _parseConfig(cfg);\n    }\n\n    /* Clean up removed elements */\n    DOMPurify.removed = [];\n\n    /* Resolved per call: setConfig() skips _parseConfig, so writing IN_PLACE\n       here would leak into later calls */\n    const inPlace = IN_PLACE && typeof dirty !== 'string' && _isNode(dirty);\n    /* IN_PLACE: the caller's nodes before any hook or custom element can run,\n       and the visit tracking of an outer call this one may be nested in */\n    let inPlaceNodes: Node[] = [];\n    const outerVisited = IN_PLACE_VISITED;\n\n    if (inPlace) {\n      _neutralizePatchLinkage(dirty as Node);\n\n      /* The root must be an allowed tag and not clobbered: a parentless root\n         cannot be removed, so it would come back unsanitized. Its name is read\n         through the cached getter, a clobbering child could shadow it. */\n      const nn = _readNodeName(dirty as Node);\n      if (typeof nn === 'string') {\n        const tagName = transformCaseFunc(nn);\n        if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {\n          _neutralizeRoot(dirty as Node);\n          throw typeErrorCreate(\n            'root node is forbidden and cannot be sanitized in-place'\n          );\n        }\n      }\n\n      if (_isClobbered(dirty as Element)) {\n        _neutralizeRoot(dirty as Node);\n        throw typeErrorCreate(\n          'root node is clobbered and cannot be sanitized in-place'\n        );\n      }\n\n      inPlaceNodes = _collectLiveNodes(dirty as Node);\n      IN_PLACE_VISITED = setCreate();\n    } else if (_isNode(dirty)) {\n      /* If dirty is a DOM element, append to an empty document to avoid\n         elements being stripped by the parser */\n      body = _initDocument('<!---->');\n      importedNode = body.ownerDocument.importNode(dirty, true);\n      if (\n        importedNode.nodeType === NODE_TYPE.element &&\n        importedNode.nodeName === 'BODY'\n      ) {\n        /* Node is already a body, use as is */\n        body = importedNode;\n      } else if (importedNode.nodeName === 'HTML') {\n        body = importedNode;\n      } else {\n        // eslint-disable-next-line unicorn/prefer-dom-node-append\n        body.appendChild(importedNode);\n      }\n\n      /* Clonable shadow roots are copied by importNode(), and the iterator\n         does not enter them. Walk from `body`: an imported fragment was\n         emptied into it by the appendChild() above. */\n      _sanitizeAttachedShadowRoots(body);\n    } else {\n      /* Exit directly if we have nothing to do */\n      if (\n        !RETURN_DOM &&\n        !SAFE_FOR_TEMPLATES &&\n        !WHOLE_DOCUMENT &&\n        // eslint-disable-next-line unicorn/prefer-includes\n        dirty.indexOf('<') === -1\n      ) {\n        return _signOutput(dirty);\n      }\n\n      /* Initialize the document to work on */\n      body = _initDocument(dirty);\n\n      /* Check we have a DOM node from the data */\n      if (!body) {\n        return RETURN_DOM ? null : RETURN_TRUSTED_TYPE ? emptyHTML : '';\n      }\n    }\n\n    /* Remove first element node (ours) if FORCE_BODY is set */\n    if (body && FORCE_BODY) {\n      _forceRemove(body.firstChild);\n    }\n\n    /* Get node iterator */\n    const walkRoot: Node = inPlace ? (dirty as Node) : body;\n\n    /* If anything throws, an in-place tree is stripped bare before the error\n       propagates, never left half-sanitized. */\n    try {\n      if (inPlace) {\n        _sanitizeAttachedShadowRoots(dirty as Node);\n      }\n\n      const nodeIterator = _createNodeIterator(walkRoot);\n      while ((currentNode = nodeIterator.nextNode())) {\n        _sanitizeNode(currentNode, walkRoot);\n      }\n\n      if (inPlace) {\n        _sanitizeUnvisitedNodes(dirty as Node, inPlaceNodes);\n      }\n    } catch (error) {\n      if (inPlace) {\n        _neutralizeRoot(dirty as Node);\n        _neutralizeDiscarded(dirty as Node, inPlaceNodes);\n      }\n\n      throw error;\n    } finally {\n      IN_PLACE_VISITED = outerVisited;\n    }\n\n    if (inPlace) {\n      // A removed root has no safe state to return\n      if (_neutralizeDiscarded(dirty as Node, inPlaceNodes)) {\n        throw typeErrorCreate(\n          'a node selected for removal could not be safely returned; ' +\n            'refusing to sanitize in place'\n        );\n      }\n\n      if (SAFE_FOR_TEMPLATES) {\n        _scrubTemplateExpressions(dirty as Element);\n      }\n\n      return dirty;\n    }\n\n    /* Return sanitized string or DOM */\n    if (RETURN_DOM) {\n      if (SAFE_FOR_TEMPLATES) {\n        _scrubTemplateExpressions(body);\n      }\n\n      if (RETURN_DOM_FRAGMENT) {\n        returnNode = createDocumentFragment.call(body.ownerDocument);\n\n        while (body.firstChild) {\n          // eslint-disable-next-line unicorn/prefer-dom-node-append\n          returnNode.appendChild(body.firstChild);\n        }\n      } else {\n        returnNode = body;\n      }\n\n      if (ALLOWED_ATTR.shadowroot || ALLOWED_ATTR.shadowrootmode) {\n        /*\n          AdoptNode() is not used because internal state is not reset\n          (e.g. the past names map of a HTMLFormElement), this is safe\n          in theory but we would rather not risk another attack vector.\n          The state that is cloned by importNode() is explicitly defined\n          by the specs.\n        */\n        returnNode = importNode.call(originalDocument, returnNode, true);\n      }\n\n      return returnNode;\n    }\n\n    const serialize = (): string =>\n      WHOLE_DOCUMENT ? body.outerHTML : body.innerHTML;\n    let serializedHTML = serialize();\n\n    /* Scrub our tree, not the markup: a regex over markup cuts through\n       tags. Only needed if the output holds a marker pair. Template\n       content was already scrubbed by _sanitizeShadowDOM. */\n    if (\n      SAFE_FOR_TEMPLATES &&\n      regExpTest(EXPRESSIONS.TMPL_MARKER_SERIALIZED, serializedHTML)\n    ) {\n      _scrubOwnCharacterData(body);\n      serializedHTML = serialize();\n    }\n\n    /* Serialize doctype if allowed */\n    if (\n      WHOLE_DOCUMENT &&\n      ALLOWED_TAGS['!doctype'] &&\n      body.ownerDocument &&\n      body.ownerDocument.doctype &&\n      body.ownerDocument.doctype.name &&\n      regExpTest(EXPRESSIONS.DOCTYPE_NAME, body.ownerDocument.doctype.name)\n    ) {\n      serializedHTML =\n        '<!DOCTYPE ' + body.ownerDocument.doctype.name + '>\\n' + serializedHTML;\n    }\n\n    return _signOutput(serializedHTML);\n  };\n\n  DOMPurify.setConfig = function (cfg = {}) {\n    _parseConfig(cfg);\n    SET_CONFIG = true;\n    SET_CONFIG_ALLOWED_TAGS = ALLOWED_TAGS;\n    SET_CONFIG_ALLOWED_ATTR = ALLOWED_ATTR;\n  };\n\n  DOMPurify.clearConfig = function () {\n    CONFIG = null;\n    SET_CONFIG = false;\n    SET_CONFIG_ALLOWED_TAGS = null;\n    SET_CONFIG_ALLOWED_ATTR = null;\n\n    // Drop a caller-supplied Trusted Types policy; the next _parseConfig\n    // restores the instance's own. See GHSA-vxr8-fq34-vvx9.\n    trustedTypesPolicy = defaultTrustedTypesPolicy;\n    emptyHTML = '';\n  };\n\n  DOMPurify.isValidAttribute = function (tag, attr, value) {\n    /* Initialize shared config vars if necessary. */\n    if (!CONFIG) {\n      _parseConfig({});\n    }\n\n    const lcTag = transformCaseFunc(tag);\n    const lcName = transformCaseFunc(attr);\n\n    /* Apply the same value checks sanitize() applies to an attribute when no\n       hook intervenes, so a value approved here is one sanitize() would also\n       keep: comment / raw-text closers, animated hrefs, and the jQuery 3.0\n       self-closing-tag pattern. */\n    if (\n      typeof value === 'string' &&\n      (_isUnsafeAttributeValue(attr, value) ||\n        (!ALLOW_SELF_CLOSE_IN_ATTR &&\n          regExpTest(EXPRESSIONS.SELF_CLOSING_TAG, value)))\n    ) {\n      return false;\n    }\n\n    return _isValidAttribute(lcTag, lcName, value);\n  };\n\n  DOMPurify.addHook = function (\n    entryPoint: keyof HooksMap,\n    hookFunction: HookFunction\n  ) {\n    if (typeof hookFunction !== 'function') {\n      return;\n    }\n\n    /* Reject unknown entry points. Without this, a non-hook key (e.g.\n     * '__proto__') indexes off the prototype chain rather than a real\n     * hook array, and arrayPush then writes to Object.prototype. Guard\n     * with an own-property check against the known hook names. */\n    if (!objectHasOwnProperty(hooks, entryPoint)) {\n      return;\n    }\n\n    arrayPush(hooks[entryPoint], hookFunction);\n  };\n\n  DOMPurify.removeHook = function (\n    entryPoint: keyof HooksMap,\n    hookFunction: HookFunction\n  ) {\n    if (!objectHasOwnProperty(hooks, entryPoint)) {\n      return undefined;\n    }\n\n    if (hookFunction !== undefined) {\n      const index = arrayLastIndexOf(hooks[entryPoint], hookFunction);\n\n      return index === -1\n        ? undefined\n        : arraySplice(hooks[entryPoint], index, 1)[0];\n    }\n\n    return arrayPop(hooks[entryPoint]);\n  };\n\n  DOMPurify.removeHooks = function (entryPoint: keyof HooksMap) {\n    if (!objectHasOwnProperty(hooks, entryPoint)) {\n      return;\n    }\n\n    hooks[entryPoint] = [];\n  };\n\n  DOMPurify.removeAllHooks = function () {\n    hooks = _createHooksMap();\n  };\n\n  return DOMPurify;\n}\n\nexport default createDOMPurify();\n", "/**\n * safe-html.js \u2014 HTML z atributu prvku (popis KML, popup exportu z GIS) jako\n * bezpe\u010Dn\u00FD fragment DOM.\n *\n * Data jsou ciz\u00ED vstup a mapa b\u011B\u017E\u00ED i jako ve\u0159ejn\u00E1 / sd\u00EDlen\u00E1 str\u00E1nka na na\u0161\u00ED\n * dom\u00E9n\u011B: skript v nich by jednal za p\u0159ihl\u00E1\u0161en\u00E9ho div\u00E1ka. Proto:\n *\n * - HTML \u010Dist\u00ED DOMPurify (zafixovan\u00E1 verze v package.json) se seznamem\n *   povolen\u00FDch zna\u010Dek: text, tabulky, seznamy, nadpisy, odkazy, obr\u00E1zky.\n *   \u017D\u00E1dn\u00E9 skripty, styly, formul\u00E1\u0159e, r\u00E1mce, SVG/MathML, `style`/`class`/`id`\n *   ani obslu\u017En\u00E9 atributy (`on\u2026`).\n * - Odkaz sm\u00ED v\u00E9st jen na `http(s):` nebo `mailto:`; otev\u0159e se v nov\u00E9m okn\u011B\n *   bez p\u0159\u00EDstupu k na\u0161\u00ED str\u00E1nce (`rel=\"noopener noreferrer nofollow\"`).\n * - Obr\u00E1zek sm\u00ED m\u00EDt jen `http(s):`, rastrov\u00E9 `data:image/\u2026` nebo relativn\u00ED cestu\n *   fotky polo\u017Eky (adresu dod\u00E1 volaj\u00EDc\u00ED, `resolveImage`); na\u010D\u00EDt\u00E1 se l\u00EDn\u011B a bez\n *   hlavi\u010Dky Referer (ciz\u00ED server se nedozv\u00ED, kdo mapu prohl\u00ED\u017E\u00ED).\n * - V\u00FDsledek je `DocumentFragment` (DOMPurify `RETURN_DOM_FRAGMENT`), do str\u00E1nky\n *   se nikdy nevkl\u00E1d\u00E1 jako text p\u0159es `innerHTML`.\n */\nimport createDOMPurify from 'dompurify';\n\nconst ALLOWED_TAGS = [\n    'a', 'b', 'strong', 'i', 'em', 'u', 's', 'small', 'sub', 'sup', 'br', 'p', 'div', 'span',\n    'table', 'thead', 'tbody', 'tfoot', 'tr', 'td', 'th', 'caption', 'ul', 'ol', 'li', 'dl', 'dt',\n    'dd', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'img', 'font', 'center', 'blockquote', 'pre', 'code',\n];\nconst ALLOWED_ATTR = ['href', 'src', 'alt', 'title', 'colspan', 'rowspan'];\nconst SAFE_LINK_RE = /^(?:https?:|mailto:)/i;\nconst SAFE_IMAGE_RE = /^(?:https?:\\/\\/|data:image\\/(?:png|jpe?g|gif|webp);base64,)/i;\n\nlet purifier = null;\n// Vol\u00E1n\u00ED je synchronn\u00ED: h\u00E1k \u010Dte, \u010D\u00EDm se m\u00E1 relativn\u00ED obr\u00E1zek nahradit.\nlet currentResolveImage = null;\n// Obr\u00E1zky posledn\u00EDho \u010Di\u0161t\u011Bn\u00ED (pro galerii).\nlet currentImages = [];\n\nfunction getPurifier() {\n    if (purifier) return purifier;\n    purifier = createDOMPurify(window);\n    purifier.addHook('afterSanitizeAttributes', (node) => {\n        const tag = node.nodeName.toLowerCase();\n        if (tag === 'a') {\n            const href = (node.getAttribute('href') || '').trim();\n            if (SAFE_LINK_RE.test(href)) {\n                node.setAttribute('target', '_blank');\n                node.setAttribute('rel', 'noopener noreferrer nofollow');\n            } else {\n                const resolved = href && currentResolveImage ? currentResolveImage(href) : null;\n                if (resolved) {\n                    node.setAttribute('href', resolved);\n                    node.setAttribute('target', '_blank');\n                    node.setAttribute('rel', 'noopener noreferrer nofollow');\n                } else {\n                    node.removeAttribute('href');\n                }\n            }\n        } else if (tag === 'img') {\n            const src = (node.getAttribute('src') || '').trim();\n            let safe = SAFE_IMAGE_RE.test(src) ? src : null;\n            if (!safe && src && currentResolveImage) safe = currentResolveImage(src);\n            if (!safe) {\n                node.remove();\n                return;\n            }\n            node.setAttribute('src', safe);\n            node.setAttribute('loading', 'lazy');\n            node.setAttribute('decoding', 'async');\n            node.setAttribute('referrerpolicy', 'no-referrer');\n            node.setAttribute('data-gallery-index', String(currentImages.length));\n            currentImages.push({ src: safe, title: node.getAttribute('alt') || '' });\n        }\n    });\n    return purifier;\n}\n\n/**\n * HTML jako bezpe\u010Dn\u00FD fragment: `{ fragment, images }`. `resolveImage(path)`\n * vr\u00E1t\u00ED adresu relativn\u00ED fotky (nebo null \u2014 obr\u00E1zek se vynech\u00E1).\n */\nexport function sanitizeHtml(html, { resolveImage = null } = {}) {\n    const purify = getPurifier();\n    currentResolveImage = resolveImage;\n    currentImages = [];\n    try {\n        const fragment = purify.sanitize(String(html || ''), {\n            ALLOWED_TAGS,\n            ALLOWED_ATTR,\n            ALLOW_DATA_ATTR: false,\n            ALLOW_ARIA_ATTR: false,\n            RETURN_DOM_FRAGMENT: true,\n        });\n        return { fragment, images: currentImages };\n    } finally {\n        currentResolveImage = null;\n        currentImages = [];\n    }\n}\n", "/**\n * raster-popup.js \u2014 karta hodnoty rastru po kliknut\u00ED do mapy (n\u00E1vrh V1).\n *\n * Mapov\u00E1 slu\u017Eba vrac\u00ED u rastru v JSON GetFeatureInfo jeden prvek s\n * `properties.kind === 'raster'`: hodnoty v\u0161ech p\u00E1sem v kliknut\u00E9m bod\u011B\n * (`bands: [{band, name, value, unit, type, class, color, nodata}]`), velikost\n * pixelu a bod v WGS 84 (GCZ `raster_info.py`). Karta je uk\u00E1\u017Ee srozumiteln\u011B\n * podle toho, jak vrstvu kresl\u00ED mapa:\n *\n * - t\u0159\u00EDda (paleta souboru, kategorie) \u2192 n\u00E1zev t\u0159\u00EDdy s barvou,\n * - barevn\u00FD sn\u00EDmek (p\u00E1sma Red/Green/Blue) \u2192 barva, hex a hodnoty R, G, B,\n * - jedno p\u00E1smo \u2192 hodnota s jednotkou a poloha na barevn\u00E9 \u0161k\u00E1le vrstvy,\n * - v\u00EDc p\u00E1sem \u2192 v\u0161echna p\u00E1sma s pruhy, p\u00E1sma zobrazen\u00E1 jako R/G/B ozna\u010Den\u00E1.\n *\n * Modul je bez OpenLayers (testy: raster-popup.test.mjs).\n */\n\nfunction esc(value) {\n    return String(value ?? '')\n        .replaceAll('&', '&amp;')\n        .replaceAll('<', '&lt;')\n        .replaceAll('>', '&gt;')\n        .replaceAll('\"', '&quot;');\n}\n\n/** \u010C\u00EDslo rastru \u010Diteln\u011B: cel\u00E1 \u010D\u00EDsla s odd\u011Blova\u010Di, desetinn\u00E1 na 5 platn\u00FDch m\u00EDst. */\nexport function formatRasterNumber(value) {\n    if (value === null || value === undefined || value === '') return '\u2014';\n    const number = Number(value);\n    if (!Number.isFinite(number)) return String(value);\n    if (Number.isInteger(number)) return number.toLocaleString('en-US');\n    const rounded = Number(number.toPrecision(5));\n    return rounded.toLocaleString('en-US', { maximumFractionDigits: 6 });\n}\n\n/** \u201E15.9657\u00B0 S, 5.7121\u00B0 W\u201C z bodu [lon, lat]. */\nexport function formatLonLat(coordinates) {\n    if (!Array.isArray(coordinates) || coordinates.length < 2) return '';\n    const [lon, lat] = coordinates.map(Number);\n    if (!Number.isFinite(lon) || !Number.isFinite(lat)) return '';\n    const ns = `${Math.abs(lat).toFixed(4)}\u00B0 ${lat < 0 ? 'S' : 'N'}`;\n    const ew = `${Math.abs(lon).toFixed(4)}\u00B0 ${lon < 0 ? 'W' : 'E'}`;\n    return `${ns}, ${ew}`;\n}\n\nfunction formatPixel(props) {\n    const [x, y] = props.pixel_size || [];\n    if (!Number.isFinite(x) || !Number.isFinite(y)) return '';\n    const unit = props.pixel_unit || '';\n    if (unit === '\u00B0') {\n        const degrees = `${formatRasterNumber(x)}\u00B0 \u00D7 ${formatRasterNumber(y)}\u00B0`;\n        // Ve stupn\u00EDch je pixel t\u011B\u017Eko p\u0159edstaviteln\u00FD \u2014 p\u0159ibli\u017En\u011B v metrech na m\u00EDst\u011B kliknut\u00ED.\n        const lat = Number(props.location?.[1]);\n        if (!Number.isFinite(lat)) return degrees;\n        const mx = Math.round(x * 111320 * Math.cos((lat * Math.PI) / 180));\n        const my = Math.round(y * 110574);\n        return mx > 0 && my > 0 ? `${degrees} (\u2248 ${formatRasterNumber(mx)} \u00D7 ${formatRasterNumber(my)} m)` : degrees;\n    }\n    return `${formatRasterNumber(x)} \u00D7 ${formatRasterNumber(y)}${unit ? ` ${unit}` : ''}`;\n}\n\nconst RGB_NAMES = { red: 'r', green: 'g', blue: 'b' };\n\nfunction hex(value) {\n    return Math.max(0, Math.min(255, Math.round(Number(value) || 0))).toString(16).padStart(2, '0');\n}\n\n/** P\u00E1sma Red/Green/Blue (podle n\u00E1zvu z barevn\u00E9 interpretace) \u2192 {r, g, b}, jinak null. */\nfunction rgbBands(bands) {\n    const found = {};\n    bands.forEach((band) => {\n        const key = RGB_NAMES[String(band.name || '').trim().toLowerCase()];\n        if (key && band.type === 'Byte' && !band.nodata) found[key] = band;\n    });\n    return found.r && found.g && found.b ? found : null;\n}\n\n/** Barevn\u00E1 \u0161k\u00E1la vrstvy: barvy a krajn\u00ED hodnoty (jako legenda), jinak null. */\nfunction scaleOf(entry) {\n    const style = entry?.style || {};\n    if (style.mode !== 'ramp' && style.mode !== 'gray') return null;\n    const rendering = entry.rasterRendering || entry.raster?.rendering || null;\n    const scale = rendering && rendering.mode === style.mode ? rendering.scales?.[0] : null;\n    if (!Array.isArray(scale) || scale.length < 2) return null;\n    let colors = ['#000000', '#ffffff'];\n    if (style.mode === 'ramp') {\n        if (rendering?.ramp?.length) colors = rendering.ramp.map((stop) => stop[1]);\n        else colors = (entry.raster?.colormaps || {})[style.colormap] || colors;\n    }\n    return { colors, min: Number(scale[0]), max: Number(scale[1]) };\n}\n\n/** T\u0159\u00EDda hodnoty z palety vrstvy (`entry.raster.palette`), jinak null. */\nfunction paletteClass(entry, value) {\n    if (entry?.style?.mode !== 'palette') return null;\n    const item = (entry.raster?.palette || []).find((p) => Number(p.value) === Number(value));\n    return item ? { label: item.label || null, color: item.color || null } : null;\n}\n\n/**\n * Model karty: `{title, subtitle, swatch, scale, bands, rows}`.\n * `entry` je b\u011Bhov\u00E1 vrstva (styl, paleta, \u0161k\u00E1la); sm\u00ED chyb\u011Bt.\n */\nexport function rasterCardModel(props, entry = null) {\n    const bands = (props?.bands || []).filter((band) => band && !band.nodata);\n    const rows = [];\n    const model = { title: '', subtitle: '', swatch: null, scale: null, bands: null, rows };\n    if (!bands.length) {\n        model.title = 'No data';\n        model.subtitle = 'The raster has no value at this point.';\n    } else if (bands.length === 1) {\n        const band = bands[0];\n        const palette = paletteClass(entry, band.value);\n        const className = band.class || palette?.label;\n        if (className) {\n            model.title = className;\n            model.swatch = band.color || palette?.color || null;\n            rows.push(['Value', formatRasterNumber(band.value)]);\n        } else {\n            model.title = `${formatRasterNumber(band.value)}${band.unit ? ` ${band.unit}` : ''}`;\n            const scale = scaleOf(entry);\n            if (scale && Number.isFinite(scale.min) && Number.isFinite(scale.max) && scale.max > scale.min) {\n                const position = Math.max(0, Math.min(1, (Number(band.value) - scale.min) / (scale.max - scale.min)));\n                model.scale = { ...scale, position };\n            }\n        }\n        if (band.name && !/^Band \\d+$/.test(band.name)) model.subtitle = band.name;\n    } else {\n        const rgb = rgbBands(bands);\n        if (rgb) {\n            const color = `#${hex(rgb.r.value)}${hex(rgb.g.value)}${hex(rgb.b.value)}`;\n            model.title = color.toUpperCase();\n            model.swatch = color;\n            bands.forEach((band) => rows.push([band.name, formatRasterNumber(band.value)]));\n        } else {\n            model.title = `${bands.length} bands`;\n            const shown = entry?.style?.mode === 'rgb' ? entry.style.bands || {} : {};\n            const chipOf = (number) => (['r', 'g', 'b'].find((key) => Number(shown[key]) === number) || '').toUpperCase() || null;\n            const largest = Math.max(...bands.map((band) => Math.abs(Number(band.value) || 0)), 0);\n            model.bands = bands.map((band) => ({\n                name: band.name,\n                value: formatRasterNumber(band.value),\n                unit: band.unit || '',\n                chip: chipOf(band.band),\n                share: largest > 0 ? Math.abs(Number(band.value) || 0) / largest : 0,\n            }));\n        }\n    }\n    const where = formatLonLat(props?.location);\n    if (where) rows.push(['Location', where]);\n    const pixel = formatPixel(props || {});\n    if (pixel) rows.push(['Pixel', pixel]);\n    return model;\n}\n\nconst CHIP_CLASS = { R: 'bg-red-100 text-red-700', G: 'bg-green-100 text-green-700', B: 'bg-blue-100 text-blue-700' };\n\n/** T\u011Blo karty (obsah `.map-popup-body`). */\nexport function rasterCardBodyHtml(model) {\n    const parts = [];\n    if (model.subtitle) parts.push(`<p class=\"text-xs text-slate-500\">${esc(model.subtitle)}</p>`);\n    if (model.scale) {\n        const { colors, min, max, position } = model.scale;\n        parts.push(`\n            <div class=\"map-raster-ramp mt-2\" style=\"background:linear-gradient(to right, ${esc(colors.join(', '))})\">\n                <span class=\"map-raster-marker\" style=\"left:${(position * 100).toFixed(1)}%\"></span>\n            </div>\n            <div class=\"mt-1 flex justify-between text-[11px] text-slate-400\"><span>${esc(formatRasterNumber(min))}</span><span>${esc(formatRasterNumber(max))}</span></div>`);\n    }\n    if (model.bands) {\n        const rows = model.bands.map((band) => `\n            <div class=\"map-raster-band\">\n                <span class=\"flex min-w-0 items-center gap-x-1\"><span class=\"min-w-0 truncate text-slate-600\" title=\"${esc(band.name)}\">${esc(band.name)}</span>${band.chip ? `<b class=\"flex-none rounded px-1 text-[10px] ${CHIP_CLASS[band.chip]}\">${band.chip}</b>` : ''}</span>\n                <span class=\"map-raster-bar\"><span style=\"width:${(band.share * 100).toFixed(1)}%\"></span></span>\n                <span class=\"text-right tabular-nums text-slate-800\">${esc(band.value)}${band.unit ? ` ${esc(band.unit)}` : ''}</span>\n            </div>`).join('');\n        const chips = model.bands.some((band) => band.chip);\n        parts.push(`<div class=\"mt-1 space-y-1.5 text-xs\">${rows}</div>`);\n        if (chips) parts.push('<p class=\"mt-2 text-[11px] text-slate-400\">R G B = bands shown on the map</p>');\n    }\n    if (model.rows.length) {\n        parts.push(`<dl class=\"map-popup-attrs${parts.length ? ' mt-3' : ''}\">${model.rows.map(([key, value]) => `\n            <div class=\"map-popup-row\"><dt title=\"${esc(key)}\">${esc(key)}</dt><dd>${esc(value)}</dd></div>`).join('')}</dl>`);\n    }\n    return parts.join('');\n}\n", "/**\n * identify.js \u2014 klik do mapy \u2192 informace o prvc\u00EDch pod kurzorem.\n *\n * - Workspace vektory: GetFeatureInfo na Mapserveru (v\u0161echny viditeln\u00E9 vrstvy\n *   paraleln\u011B).\n * - Kresba a lok\u00E1ln\u00ED vektorov\u00E1 data (klientsk\u00E9 OL vrstvy): prvky se hledaj\u00ED\n *   p\u0159\u00EDmo v map\u011B (`forEachFeatureAtPixel`) \u2014 u pr\u00E1v\u011B nakreslen\u00E9 vrstvy tak\n *   popup funguje hned, bez ukl\u00E1d\u00E1n\u00ED. U kresby popup nab\u00EDz\u00ED \u201EEdit attributes\u201C\n *   (otev\u0159e atributovou tabulku na dan\u00E9m prvku).\n * - Extern\u00ED WMS: GetFeatureInfo (text/html) v sandbox iframe.\n *\n * V\u00FDsledky se slou\u010D\u00ED do jednoho seznamu a zobraz\u00ED v popupu se str\u00E1nkov\u00E1n\u00EDm.\n */\nimport Overlay from 'ol/Overlay.js';\nimport GeoJSON from 'ol/format/GeoJSON.js';\nimport { getUid } from 'ol/util.js';\nimport { emit, isStyleAttribute } from './utils.js';\nimport { escapeHtml } from './popup-dom.js';\nimport { openGallery } from './gallery.js';\nimport {\n    htmlText, kindOf, mediaUrl, photosOf, popupWidth, relativeImagePath, repeatsOtherValues, shortUrl,\n    titleOf,\n} from './popup-values.js';\nimport { sanitizeHtml } from './safe-html.js';\nimport { flatLayers, isEffectivelyVisible } from './state.js';\nimport { drawingAttributes } from './draw.js';\nimport { rasterCardBodyHtml, rasterCardModel } from './raster-popup.js';\n\nconst INFO_FORMAT = 'application/json';\n\n/** Vr\u00E1t\u00ED seznam b\u011Bhov\u00FDch vrstev, kter\u00E9 maj\u00ED smysl dotazovat (vektor + viditeln\u00E9).\n * Kresba (dataType 'drawing') a extern\u00ED/lok\u00E1ln\u00ED vrstvy (external.js) maj\u00ED\n * vlastn\u00ED cesty \u2014 sem pat\u0159\u00ED jen workspace vektor s na\u0161\u00EDm Mapserverem. */\nfunction queryableLayers(state) {\n    // Efektivn\u00ED viditelnost \u2014 vrstva ve vypnut\u00E9 skupin\u011B se nedotazuje.\n    // Vrstva, kter\u00E1 se kv\u016Fli velikosti nekresl\u00ED (`performance.tooSlow`), se ani nedotazuje.\n    // Rastry vrac\u00ED mapov\u00E1 slu\u017Eba v JSON jako hodnoty p\u00E1sem v bod\u011B (raster-popup.js).\n    return flatLayers(state).filter((l) => (l.dataType === 'vector' || l.dataType === 'raster')\n        && isEffectivelyVisible(state, l) && l.olSource && !l.performance?.tooSlow);\n}\n\n/** Extern\u00ED WMS vrstvy s queryable=\"1\" a slu\u017Ebou podporuj\u00EDc\u00EDm text/html. */\nfunction externalQueryableLayers(state) {\n    return flatLayers(state).filter((l) => l.dataType === 'wms' && isEffectivelyVisible(state, l) && l.olSource\n        && l.externalWms?.queryable && l.externalWms?.infoFormat);\n}\n\n/** Odstran\u00ED z GetFeatureInfo URL parametry, kter\u00E9 dotaz nepot\u0159ebuje.\n * SLD_BODY (klientsk\u00E9 stylov\u00E1n\u00ED) m\u016F\u017Ee m\u00EDt i mnoho kB \u2014 u vrstev s v\u00EDce\n * podvrstvami pak GET URL p\u0159ekro\u010D\u00ED limit a slu\u017Eba dotaz odm\u00EDtne, co\u017E se\n * projevovalo jako \"nefunk\u010Dn\u00ED identify\" (mj. u v\u00EDcevrstv\u00FDch GPKG). */\nfunction stripUnneededParams(url) {\n    const parsed = new URL(url, window.location.href);\n    parsed.searchParams.delete('SLD_BODY');\n    return parsed.toString();\n}\n\n/** Provede GetFeatureInfo pro JEDNU podvrstvu (n\u00E1zev vrstvy Mapserveru).\n * MapServer s GeoJSON v\u00FDstupem um\u00ED v jednom dotazu obslou\u017Eit jen jedinou\n * vrstvu \u2014 p\u0159i v\u00EDce n\u00E1zvech v QUERY_LAYERS sel\u017Ee OGR GEOJSON driver chybou\n * \u201EOGR_DS_CreateLayer failed\u201C (GeoJSON = jedna FeatureCollection = jedna\n * vrstva). Proto se ka\u017Ed\u00E1 podvrstva dotazuje samostatn\u011B. */\nasync function fetchSublayerFeatureInfo(entry, sublayerName, map, coordinate) {\n    const view = map.getView();\n    const url = entry.olSource.getFeatureInfoUrl(\n        coordinate,\n        view.getResolution(),\n        view.getProjection(),\n        {\n            INFO_FORMAT,\n            QUERY_LAYERS: sublayerName,\n            FEATURE_COUNT: 10,\n        },\n    );\n    if (!url) return [];\n    const response = await fetch(stripUnneededParams(url));\n    if (!response.ok) return [];\n    const data = await response.json();\n    return (data.features || []).filter((feature) => !(feature.properties?.kind === 'raster'\n        && feature.properties.nodata)).map((feature) => (feature.properties?.kind === 'raster' ? {\n        // Hodnota rastru v bod\u011B: karta podle stylu vrstvy (raster-popup.js).\n        layerTitle: entry.title,\n        itemId: entry.itemId,\n        uid: entry.uid,\n        id: null,\n        geometry: null,\n        properties: {},\n        raster: { ...feature.properties, location: feature.geometry?.coordinates || null },\n        rasterEntry: entry,\n    } : {\n        layerTitle: entry.title,\n        itemId: entry.itemId,\n        uid: entry.uid,\n        // id + geometrie (v projekci mapy) \u2014 pou\u017E\u00EDv\u00E1 atributov\u00E1 tabulka pro\n        // zv\u00FDrazn\u011Bn\u00ED odpov\u00EDdaj\u00EDc\u00EDho \u0159\u00E1dku/prvku (viz attr-table.js).\n        id: feature.id ?? null,\n        geometry: feature.geometry || null,\n        properties: feature.properties || {},\n    }));\n}\n\n/** Provede GetFeatureInfo pro celou vrstvu polo\u017Eky: dot\u00E1\u017Ee v\u0161echny jej\u00ED\n * podvrstvy paraleln\u011B (viz omezen\u00ED GeoJSON v\u00FDstupu v\u00FD\u0161e) a v\u00FDsledky slou\u010D\u00ED.\n * Chyba jedn\u00E9 podvrstvy nesm\u00ED zahodit v\u00FDsledky ostatn\u00EDch. */\nasync function fetchFeatureInfo(entry, map, coordinate) {\n    const names = (entry.sublayers || []).map((s) => s.name).filter(Boolean);\n    if (names.length === 0) return [];\n    const results = await Promise.allSettled(\n        names.map((name) => fetchSublayerFeatureInfo(entry, name, map, coordinate)),\n    );\n    return results\n        .filter((r) => r.status === 'fulfilled')\n        .flatMap((r) => r.value);\n}\n\n/** GetFeatureInfo na extern\u00ED WMS slu\u017Eb\u011B \u2014 INFO_FORMAT text/html, v\u00FDsledek se\n * zobrazuje jako HTML v sandbox iframe. Pr\u00E1zdn\u00E1/b\u00EDl\u00E1 odpov\u011B\u010F (jen zna\u010Dky bez\n * textu) se pova\u017Euje za \u201E\u017E\u00E1dn\u00FD prvek\u201C. Selh\u00E1n\u00ED (v\u010D. CORS) vrac\u00ED []. */\nasync function fetchExternalFeatureInfo(entry, map, coordinate) {\n    const view = map.getView();\n    const url = entry.olSource.getFeatureInfoUrl(\n        coordinate,\n        view.getResolution(),\n        view.getProjection(),\n        { INFO_FORMAT: entry.externalWms.infoFormat, FEATURE_COUNT: 10 },\n    );\n    if (!url) return [];\n    let response;\n    try {\n        response = await fetch(url);\n    } catch {\n        return []; // CORS/s\u00ED\u0165ov\u00E1 chyba \u2014 extern\u00ED slu\u017Ebu neum\u00EDme dotazovat\n    }\n    if (!response.ok) return [];\n    const html = await response.text();\n    // Heuristika pr\u00E1zdn\u00E9 odpov\u011Bdi: po odstran\u011Bn\u00ED zna\u010Dek nezbyl \u017E\u00E1dn\u00FD text.\n    const textOnly = html.replace(/<[^>]*>/g, '').trim();\n    if (!textOnly) return [];\n    return [{\n        layerTitle: entry.title,\n        itemId: entry.itemId,\n        uid: entry.uid,\n        id: null,\n        geometry: null,\n        properties: {},\n        html,\n    }];\n}\n\nconst geojsonFormat = new GeoJSON();\n\n/** Tolerance z\u00E1sahu (px) pro klientsk\u00E9 vrstvy \u2014 tenk\u00E9 linie a mal\u00E9 body. */\nconst HIT_TOLERANCE = window.matchMedia?.('(pointer: coarse)').matches ? 14 : 6; // prst je m\u00E9n\u011B p\u0159esn\u00FD ne\u017E my\u0161\n\n/** Prvky klientsk\u00FDch vektorov\u00FDch vrstev (kresba, lok\u00E1ln\u00ED data) pod kurzorem.\n * Po\u0159ad\u00ED odpov\u00EDd\u00E1 vykreslen\u00ED: nejv\u00FD\u0161e polo\u017Een\u00FD prvek prvn\u00ED. */\nfunction clientFeaturesAtPixel(ctx, pixel) {\n    const entries = flatLayers(ctx.state).filter((l) => (l.dataType === 'drawing' || l.dataType === 'local')\n        && isEffectivelyVisible(ctx.state, l) && l.olLayer);\n    if (entries.length === 0) return [];\n    const byLayer = new Map(entries.map((entry) => [entry.olLayer, entry]));\n    const found = [];\n    const seen = new Set();\n    ctx.map.forEachFeatureAtPixel(pixel, (feature, layer) => {\n        const entry = byLayer.get(layer);\n        if (!entry || seen.has(feature)) return;\n        seen.add(feature);\n        const isDrawing = entry.dataType === 'drawing';\n        let properties;\n        if (isDrawing) {\n            properties = drawingAttributes(feature);\n        } else {\n            properties = { ...feature.getProperties() };\n            delete properties[feature.getGeometryName()];\n        }\n        const geometry = feature.getGeometry();\n        found.push({\n            layerTitle: entry.title,\n            itemId: entry.itemId,\n            uid: entry.uid,\n            id: getUid(feature),\n            // Geometrie v projekci mapy \u2014 pro zv\u00FDrazn\u011Bn\u00ED prvku (attr-table.js).\n            geometry: geometry ? geojsonFormat.writeGeometryObject(geometry) : null,\n            properties,\n            editable: isDrawing,\n        });\n    }, { layerFilter: (layer) => byLayer.has(layer), hitTolerance: HIT_TOLERANCE });\n    return found;\n}\n\n/** Hodnota atributu jako bezpe\u010Dn\u00E9 HTML (text, \u010D\u00EDslo, odkaz). Data jsou ciz\u00ED\n * vstup \u2014 v\u0161e se escapuje; HTML hodnoty jdou p\u0159es `safe-html.js`. */\nfunction valueHtml(key, value, kind) {\n    const text = typeof value === 'object' ? JSON.stringify(value) : String(value);\n    if (kind === 'url') {\n        return `<a href=\"${escapeHtml(text)}\" target=\"_blank\" rel=\"noopener noreferrer nofollow\" class=\"map-popup-link\" title=\"${escapeHtml(text)}\">${escapeHtml(shortUrl(text))}<svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" aria-hidden=\"true\"><path d=\"M14 4h6v6M10 14 20 4\"/></svg></a>`;\n    }\n    if (kind === 'number') return `<span class=\"tabular-nums\">${escapeHtml(text)}</span>`;\n    if (kind === 'long') {\n        return `<span class=\"map-popup-clamp\" data-role=\"clamp\">${escapeHtml(text)}</span><button type=\"button\" class=\"map-popup-more\" data-role=\"more\" hidden>more</button>`;\n    }\n    return escapeHtml(text);\n}\n\n/** Vytvo\u0159\u00ED OL Overlay popup a vr\u00E1t\u00ED objekt s metodami show/hide. */\nfunction createPopup(map, element) {\n    const overlay = new Overlay({\n        element,\n        autoPan: { animation: { duration: 250 } },\n        positioning: 'bottom-center',\n        offset: [0, -12],\n    });\n    map.addOverlay(overlay);\n    return overlay;\n}\n\nconst ICON_CLOSE = '<svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" aria-hidden=\"true\"><path d=\"M18 6 6 18M6 6l12 12\"/></svg>';\nconst ICON_PHOTO = '<svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" aria-hidden=\"true\"><rect x=\"3\" y=\"5\" width=\"18\" height=\"14\" rx=\"2\"/><circle cx=\"9\" cy=\"10\" r=\"1.6\"/><path d=\"m21 16-5-5-8 8\"/></svg>';\nconst ICON_ZOOM = '<svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" aria-hidden=\"true\"><circle cx=\"11\" cy=\"11\" r=\"6\"/><path d=\"m20 20-4.3-4.3M11 8v6M8 11h6\"/></svg>';\nconst ICON_EXPAND = '<svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" aria-hidden=\"true\"><path d=\"M15 3h6v6M9 21H3v-6M21 3l-7 7M3 21l7-7\"/></svg>';\nconst ICON_CHEVRON = '<svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" aria-hidden=\"true\"><path d=\"m9 6 6 6-6 6\"/></svg>';\n\n/** Pati\u010Dka popupu: p\u0159ibl\u00ED\u017Eit na prvek, str\u00E1nkov\u00E1n\u00ED, zv\u011Bt\u0161it okno. */\nfunction footerHtml(features, index, feature) {\n    const pager = features.length > 1 ? `\n        <div class=\"map-popup-pager\">\n            <button type=\"button\" data-role=\"prev\" aria-label=\"Previous feature\">\u2039</button>\n            <span class=\"tabular-nums\">${index + 1} / ${features.length}</span>\n            <button type=\"button\" data-role=\"next\" aria-label=\"Next feature\">\u203A</button>\n        </div>` : '<span></span>';\n    const zoom = feature.geometry\n        ? `<button type=\"button\" class=\"map-popup-tool\" data-role=\"zoom\" title=\"Zoom to the feature\">${ICON_ZOOM}<span>Zoom to</span></button>`\n        : '<span></span>';\n    return `\n        <div class=\"map-popup-foot\">\n            ${zoom}\n            ${pager}\n            <button type=\"button\" class=\"map-popup-tool\" data-role=\"expand\" aria-label=\"Larger window\" title=\"Larger window\">${ICON_EXPAND}</button>\n        </div>`;\n}\n\nconst POPUP_BOX = 'class=\"map-popup-box flex flex-col rounded-xl border border-slate-200 bg-white shadow-xl\"';\n\n/**\n * Obsah okna jednoho prvku. Vrac\u00ED fotky prvku (pro galerii). Fotky: hodnoty\n * atribut\u016F s adresou obr\u00E1zku, `gx_media_links`/`photos` (relativn\u00ED cesty =\n * fotky z KMZ polo\u017Eky) a obr\u00E1zky v HTML popisu. HTML hodnoty (popis KML) se\n * vykresl\u00ED p\u0159es `safe-html.js`; popis, kter\u00FD jen opakuje ostatn\u00ED atributy, se\n * sbal\u00ED.\n */\nfunction renderFeature(container, ctx, features, index) {\n    const feature = features[index];\n    const mapId = ctx.state?.mapId || null;\n    const resolveImage = (path) => {\n        const relative = relativeImagePath(path);\n        return relative && feature.itemId ? mediaUrl(ctx.bootstrap, feature.itemId, mapId, relative) : null;\n    };\n    const entries = Object.entries(feature.properties || {}).filter(([key]) => !isStyleAttribute(key));\n    const title = titleOf(feature.properties || {});\n    const photos = [];\n    const seenPhotos = new Set();\n    const addPhoto = (src, caption) => {\n        if (!src || seenPhotos.has(src)) return;\n        seenPhotos.add(src);\n        photos.push({ src, title: caption || title?.text || '' });\n    };\n    const rows = [];\n    const empty = [];\n    const rich = [];\n    let longest = 0;\n    for (const [key, value] of entries) {\n        if (title && key === title.key) continue;\n        const kind = kindOf(key, value);\n        if (kind === 'empty') {\n            empty.push(key);\n            continue;\n        }\n        if (kind === 'photos') {\n            for (const photo of photosOf(key, value)) {\n                addPhoto(photo.relative ? resolveImage(photo.src) : photo.src);\n            }\n            continue;\n        }\n        if (kind === 'html') {\n            rich.push({ key, value: String(value) });\n            continue;\n        }\n        longest = Math.max(longest, String(value).length);\n        rows.push({ key, value, kind });\n    }\n    // Obr\u00E1zky v HTML (popis KML): sanitizace je z\u00E1rove\u0148 najde. HTML, kter\u00E9 je\n    // jen obr\u00E1zky (`<img src=\"files/\u2026\">` atributu \u201Epictures\u201C ze sb\u011Brn\u00E9 aplikace),\n    // se jako sekce neukazuje \u2014 jeho fotky jsou naho\u0159e a v galerii.\n    const sanitized = rich.map((item) => {\n        const { fragment, images } = sanitizeHtml(item.value, { resolveImage });\n        images.forEach((image) => addPhoto(image.src));\n        // (a table of the attributes holds their names and values)\n        const others = entries.filter(([key]) => key !== item.key).flatMap(([k, v]) => [k, v]);\n        return { ...item, fragment, images, collapsed: repeatsOtherValues(item.value, others) };\n    }).filter((item) => !(item.images.length && !htmlText(item.value)));\n    const wideHtml = sanitized.some((item) => /<table\\b/i.test(item.value) && /<tr\\b[\\s\\S]*<td\\b[\\s\\S]*<td\\b[\\s\\S]*<td\\b/i.test(item.value));\n    const width = popupWidth({ longest, count: rows.length, html: sanitized.some((i) => !i.collapsed),\n        wideHtml, photos: photos.length });\n\n    const close = `<button type=\"button\" data-role=\"close\" aria-label=\"Close\" class=\"map-popup-close\">${ICON_CLOSE}</button>`;\n    const hero = photos.length ? `\n        <div class=\"map-popup-hero\">\n            <button type=\"button\" class=\"map-popup-hero-image\" data-role=\"photo\" data-index=\"0\" aria-label=\"Show the photo\">\n                <img src=\"${escapeHtml(photos[0].src)}\" alt=\"\" loading=\"lazy\" decoding=\"async\" referrerpolicy=\"no-referrer\" data-role=\"hero-image\">\n            </button>\n            ${photos.length > 1 ? `<button type=\"button\" class=\"map-popup-badge\" data-role=\"photo\" data-index=\"0\">${ICON_PHOTO}<span>1 / ${photos.length}</span></button>` : ''}\n            ${close}\n        </div>` : '';\n    const head = `\n        <div class=\"map-popup-head${hero ? ' map-popup-head-under' : ''}\">\n            <div class=\"min-w-0\">\n                ${title ? `<div class=\"map-popup-title\" title=\"${escapeHtml(title.text)}\">${escapeHtml(title.text)}</div>` : ''}\n                <div class=\"map-popup-layer\" title=\"${escapeHtml(feature.layerTitle)}\">${escapeHtml(feature.layerTitle)}</div>\n            </div>\n            ${hero ? '' : close}\n        </div>`;\n    const attrRows = rows.map(({ key, value, kind }) => `\n        <div class=\"map-popup-row\">\n            <dt title=\"${escapeHtml(key)}\">${escapeHtml(key)}</dt>\n            <dd class=\"${kind === 'number' ? 'is-number' : ''}\">${valueHtml(key, value, kind)}</dd>\n        </div>`).join('');\n    const emptyRows = empty.map((key) => `\n        <div class=\"map-popup-row\" data-role=\"empty-row\" hidden>\n            <dt title=\"${escapeHtml(key)}\">${escapeHtml(key)}</dt>\n            <dd class=\"text-slate-300\">\u2014</dd>\n        </div>`).join('');\n    const nothing = !rows.length && !sanitized.length && !photos.length;\n    const emptyToggle = empty.length ? `<button type=\"button\" class=\"map-popup-more\" data-role=\"show-empty\">${empty.length} empty ${empty.length === 1 ? 'attribute' : 'attributes'}</button>` : '';\n    const richSections = sanitized.map((item, i) => `\n        <details class=\"map-popup-rich\"${item.collapsed ? '' : ' open'}>\n            <summary>${ICON_CHEVRON}<span>${escapeHtml(sectionTitle(item))}</span></summary>\n            <div class=\"map-rich\" data-rich-slot=\"${i}\"></div>\n        </details>`).join('');\n    // Kresba: zkratka do atributov\u00E9 tabulky na tento prvek (editace hodnot).\n    const editBar = feature.editable ? `\n            <div class=\"flex flex-none justify-end border-t border-slate-100 px-2 py-1.5\">\n                <button type=\"button\" data-role=\"edit-attributes\"\n                        class=\"inline-flex items-center gap-x-1.5 rounded-md px-2 py-1 text-xs font-medium text-brand-700 hover:bg-brand-50\">\n                    <svg class=\"h-3.5 w-3.5\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" aria-hidden=\"true\"><path d=\"M17 3a2.8 2.8 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z\"/></svg>\n                    ${rows.length ? 'Edit attributes' : 'Add attributes'}\n                </button>\n            </div>` : '';\n    // Okno je zv\u011Bt\u0161iteln\u00E9 ta\u017Een\u00EDm za prav\u00FD doln\u00ED roh (CSS resize) \u2014 vnit\u0159n\u00ED\n    // obsah je flex sloupec, t\u011Blo vypl\u0148uje dostupnou v\u00FD\u0161ku (v\u00FDchoz\u00ED v\u00FD\u0161ku podle\n    // obsahu nastav\u00ED `fitPopupHeight`).\n    container.innerHTML = `\n        <div ${POPUP_BOX} style=\"width: ${width}rem;\" data-width=\"${width}\">\n            ${hero}\n            ${head}\n            <div class=\"map-popup-body\">\n                ${nothing ? `<p class=\"text-xs text-slate-400\">${feature.editable ? 'This feature has no attributes yet.' : 'This feature has no attributes.'}</p>` : ''}\n                ${rows.length || empty.length ? `<dl class=\"map-popup-attrs\">${attrRows}${emptyRows}</dl>` : ''}\n                ${emptyToggle}\n                ${richSections}\n            </div>\n            ${editBar}\n            ${footerHtml(features, index, feature)}\n        </div>`;\n    sanitized.forEach((item, i) => {\n        container.querySelector(`[data-rich-slot=\"${i}\"]`)?.appendChild(item.fragment);\n    });\n    // Obr\u00E1zek v HTML popisu otev\u0159e galerii na sob\u011B.\n    container.querySelectorAll('.map-rich img').forEach((img) => {\n        const at = photos.findIndex((photo) => photo.src === img.getAttribute('src'));\n        if (at >= 0) img.dataset.photoIndex = String(at);\n    });\n    // Fotka, kter\u00E1 se nena\u010Dte: v hlavi\u010Dce se schov\u00E1, v popisu zmiz\u00ED.\n    container.querySelector('[data-role=\"hero-image\"]')?.addEventListener('error', (event) => {\n        event.target.closest('.map-popup-hero')?.classList.add('is-broken');\n    });\n    container.querySelectorAll('.map-rich img').forEach((img) => {\n        img.addEventListener('error', () => img.remove(), { once: true });\n    });\n    return photos;\n}\n\n/** Nadpis sekce HTML hodnoty: popis KML \u010Desky \u201EDescription\u201C, sbalen\u00FD \u201EOriginal description\u201C. */\nfunction sectionTitle(item) {\n    if (/^description$/i.test(item.key)) return item.collapsed ? 'Original description' : 'Description';\n    return item.key;\n}\n\nfunction renderPopupContent(container, ctx, features, index) {\n    if (features.length === 0) {\n        container.innerHTML = '<p class=\"rounded-xl border border-slate-200 bg-white p-3 text-sm text-slate-500 shadow-xl\">No features found at this location.</p>';\n        return [];\n    }\n    const feature = features[index];\n    // Extern\u00ED WMS vrac\u00ED HTML \u2014 zobrazen\u00ED v sandbox iframe (bez skript\u016F).\n    if (feature.html) {\n        container.innerHTML = `\n            <div ${POPUP_BOX} style=\"width: 20rem; height: 15rem;\">\n                <div class=\"map-popup-head\">\n                    <div class=\"min-w-0\"><div class=\"map-popup-layer\" title=\"${escapeHtml(feature.layerTitle)}\">${escapeHtml(feature.layerTitle)}</div></div>\n                    <button type=\"button\" data-role=\"close\" aria-label=\"Close\" class=\"map-popup-close\">${ICON_CLOSE}</button>\n                </div>\n                <iframe data-role=\"info-frame\" sandbox=\"\" class=\"h-full w-full flex-1 border-0\"></iframe>\n                ${footerHtml(features, index, feature)}\n            </div>`;\n        container.querySelector('[data-role=\"info-frame\"]').srcdoc = feature.html;\n        return [];\n    }\n    if (feature.raster) return renderRaster(container, features, index);\n    return renderFeature(container, ctx, features, index);\n}\n\n/** Karta hodnoty rastru v bod\u011B (n\u00E1vrh V1, raster-popup.js). */\nfunction renderRaster(container, features, index) {\n    const feature = features[index];\n    const model = rasterCardModel(feature.raster, feature.rasterEntry);\n    const swatch = model.swatch\n        ? `<span class=\"h-7 w-7 flex-none rounded-md ring-1 ring-inset ring-black/10\" style=\"background:${escapeHtml(model.swatch)}\"></span>`\n        : '';\n    container.innerHTML = `\n        <div ${POPUP_BOX} style=\"width: 18rem;\" data-width=\"18\">\n            <div class=\"map-popup-head\">\n                <div class=\"flex min-w-0 items-center gap-x-2.5\">\n                    ${swatch}\n                    <div class=\"min-w-0\">\n                        <div class=\"map-popup-title\" title=\"${escapeHtml(model.title)}\">${escapeHtml(model.title)}</div>\n                        <div class=\"map-popup-layer\" title=\"${escapeHtml(feature.layerTitle)}\">${escapeHtml(feature.layerTitle)}</div>\n                    </div>\n                </div>\n                <button type=\"button\" data-role=\"close\" aria-label=\"Close\" class=\"map-popup-close\">${ICON_CLOSE}</button>\n            </div>\n            <div class=\"map-popup-body\">${rasterCardBodyHtml(model)}</div>\n            ${footerHtml(features, index, feature)}\n        </div>`;\n    return [];\n}\n\n/** V\u00FDchoz\u00ED v\u00FD\u0161ka okna podle obsahu (p\u00E1r atribut\u016F = mal\u00E9 okno, dlouh\u00FD seznam =\n * nejv\u00FD\u0161 `popupMaxHeight` se svisl\u00FDm posuvn\u00EDkem). Pevn\u00E1 v\u00FD\u0161ka je pot\u0159eba,\n * aby \u0161lo okno ta\u017Een\u00EDm zv\u011Bt\u0161it a obsah se mu p\u0159izp\u016Fsobil. */\nfunction popupMaxHeight(box) {\n    const viewport = window.innerHeight || 800;\n    const base = box?.classList.contains('is-expanded') ? 0.75 : 0.5;\n    return Math.max(260, Math.round(viewport * base));\n}\n\nfunction fitPopupHeight(container) {\n    const box = container.querySelector('.map-popup-box');\n    if (!box || box.querySelector('iframe')) return;\n    box.style.height = '';\n    const natural = box.scrollHeight;\n    if (natural > 0) box.style.height = `${Math.min(natural + 2, popupMaxHeight(box))}px`;\n    // Dlouh\u00FD text: \u201Emore\u201C jen tam, kde se opravdu nevejde.\n    box.querySelectorAll('[data-role=\"clamp\"]').forEach((clamp) => {\n        const more = clamp.nextElementSibling;\n        if (more) more.hidden = clamp.scrollHeight <= clamp.clientHeight + 1;\n    });\n}\n\n/** Zaregistruje identify handler na map\u011B. `getElement()` mus\u00ED vr\u00E1tit DOM prvek\n * pou\u017Eit\u00FD jako popup container (nap\u0159. skryt\u00FD <div>, ktere\u00FD si vytvo\u0159\u00ED main.js). */\nexport function initIdentify(ctx, popupElement) {\n    const overlay = createPopup(ctx.map, popupElement);\n    let features = [];\n    let index = 0;\n    let dismissTimer = null;\n\n    function clearDismissTimer() {\n        if (dismissTimer) {\n            clearTimeout(dismissTimer);\n            dismissTimer = null;\n        }\n    }\n\n    function hidePopup() {\n        clearDismissTimer();\n        overlay.setPosition(undefined);\n    }\n\n    // Zv\u011Bt\u0161en\u00E9 okno (tla\u010D\u00EDtko v pati\u010Dce) z\u016Fst\u00E1v\u00E1 zv\u011Bt\u0161en\u00E9 i pro dal\u0161\u00ED prvky.\n    let expanded = false;\n\n    function wireFeatureControls(photos) {\n        const box = popupElement.querySelector('.map-popup-box');\n        if (!box) return;\n        if (expanded) box.classList.add('is-expanded');\n        popupElement.querySelectorAll('[data-role=\"photo\"]').forEach((button) => {\n            button.addEventListener('click', () => openGallery(photos, Number(button.dataset.index) || 0));\n        });\n        popupElement.querySelectorAll('.map-rich img[data-photo-index]').forEach((img) => {\n            img.addEventListener('click', () => openGallery(photos, Number(img.dataset.photoIndex) || 0));\n        });\n        popupElement.querySelector('[data-role=\"show-empty\"]')?.addEventListener('click', (event) => {\n            popupElement.querySelectorAll('[data-role=\"empty-row\"]').forEach((row) => { row.hidden = false; });\n            event.currentTarget.remove();\n            fitPopupHeight(popupElement);\n        });\n        popupElement.querySelectorAll('[data-role=\"more\"]').forEach((button) => {\n            button.addEventListener('click', () => {\n                button.previousElementSibling?.classList.add('is-open');\n                button.remove();\n                fitPopupHeight(popupElement);\n            });\n        });\n        popupElement.querySelectorAll('.map-popup-rich').forEach((details) => {\n            details.addEventListener('toggle', () => fitPopupHeight(popupElement));\n        });\n        popupElement.querySelector('[data-role=\"expand\"]')?.addEventListener('click', () => {\n            expanded = !box.classList.contains('is-expanded');\n            box.classList.toggle('is-expanded', expanded);\n            box.style.width = expanded ? '' : `${box.dataset.width || 18}rem`;\n            fitPopupHeight(popupElement);\n            overlay.panIntoView({ animation: { duration: 200 }, margin: 16 });\n        });\n        popupElement.querySelector('[data-role=\"zoom\"]')?.addEventListener('click', () => {\n            const current = features[index];\n            if (!current?.geometry) return;\n            let geometry;\n            try {\n                geometry = geojsonFormat.readGeometry(current.geometry);\n            } catch {\n                return;\n            }\n            const view = ctx.map.getView();\n            view.fit(geometry.getExtent(), { padding: [80, 80, 80, 80], maxZoom: 18, duration: 300 });\n        });\n    }\n\n    function rerender() {\n        const photos = renderPopupContent(popupElement, ctx, features, index);\n        wireFeatureControls(photos);\n        fitPopupHeight(popupElement);\n        // Obsah (a t\u00EDm i velikost okna) je zn\u00E1m\u00FD a\u017E te\u010F \u2014 dorovnat v\u00FD\u0159ez, aby\n        // bylo okno cel\u00E9 vid\u011Bt. Rozb\u011Bhnut\u00FD posun z ukotven\u00ED okna (po\u010D\u00EDtan\u00FD\n        // je\u0161t\u011B pro jeho starou velikost) se nejd\u0159\u00EDv zastav\u00ED, jinak by se nov\u00FD\n        // v\u00FDpo\u010Det odrazil od rozpracovan\u00E9 polohy mapy.\n        if (features.length && overlay.getPosition()) {\n            ctx.map.getView().cancelAnimations();\n            overlay.panIntoView({ animation: { duration: 250 }, margin: 16 });\n        }\n        // Ozn\u00E1m\u00ED zobrazen\u00FD prvek atributov\u00E9 tabulce (obousm\u011Brn\u00E9 zv\u00FDraz\u0148ov\u00E1n\u00ED).\n        const current = features[index];\n        if (current) {\n            emit('identify:feature', {\n                itemId: current.itemId,\n                uid: current.uid,\n                featureId: current.id,\n                feature: { type: 'Feature', id: current.id, geometry: current.geometry, properties: current.properties },\n            });\n        }\n        popupElement.querySelector('[data-role=\"close\"]')?.addEventListener('click', hidePopup);\n        popupElement.querySelector('[data-role=\"edit-attributes\"]')?.addEventListener('click', () => {\n            emit('layers:open-attr-table', { uid: current.uid, focusFeatureId: current.id, keepOpen: true });\n            hidePopup();\n        });\n        popupElement.querySelector('[data-role=\"prev\"]')?.addEventListener('click', () => {\n            index = (index - 1 + features.length) % features.length;\n            rerender();\n        });\n        popupElement.querySelector('[data-role=\"next\"]')?.addEventListener('click', () => {\n            index = (index + 1) % features.length;\n            rerender();\n        });\n        if (features.length === 0) {\n            // Hl\u00E1\u0161ka \u201Enic nenalezeno\u201C zmiz\u00ED sama po 5 sekund\u00E1ch (nebo d\u0159\u00EDve p\u0159i\n            // posunu mapy \u2014 viz handler `movestart` n\u00ED\u017Ee).\n            dismissTimer = setTimeout(hidePopup, 5000);\n        }\n    }\n\n    // Posun/zoom mapy zav\u0159e informa\u010Dn\u00ED hl\u00E1\u0161ku bez v\u00FDsledk\u016F; okno s nalezen\u00FDmi\n    // prvky nech\u00E1v\u00E1me otev\u0159en\u00E9 (je ukotven\u00E9 k sou\u0159adnici a posouv\u00E1 se s mapou).\n    ctx.map.on('movestart', () => {\n        if (features.length === 0) hidePopup();\n    });\n\n    // Ka\u017Ed\u00FD klik m\u00E1 po\u0159adov\u00E9 \u010D\u00EDslo \u2014 odpov\u011B\u010F star\u0161\u00EDho (pomalej\u0161\u00EDho) dotazu\n    // nesm\u00ED p\u0159epsat popup nov\u011Bj\u0161\u00EDho kliknut\u00ED.\n    let clickSeq = 0;\n\n    ctx.map.on('singleclick', async (event) => {\n        // B\u011Bhem m\u011B\u0159en\u00ED/kreslen\u00ED (measure.js/draw.js) identify ml\u010D\u00ED \u2014 klik\n        // pat\u0159\u00ED aktivn\u00EDmu n\u00E1stroji.\n        if (ctx.mapToolActive) return;\n        const clientFeatures = clientFeaturesAtPixel(ctx, event.pixel);\n        const layers = queryableLayers(ctx.state);\n        const externalLayers = externalQueryableLayers(ctx.state);\n        if (clientFeatures.length === 0 && layers.length === 0 && externalLayers.length === 0) return;\n        const seq = ++clickSeq;\n        clearDismissTimer();\n        overlay.setPosition(event.coordinate);\n        // Prvky klientsk\u00FDch vrstev jsou hned; na server se \u010Dek\u00E1 jen tehdy,\n        // kdy\u017E je koho se pt\u00E1t.\n        const remote = layers.length > 0 || externalLayers.length > 0;\n        if (remote) {\n            popupElement.innerHTML = '<div class=\"flex w-56 items-center gap-x-2 rounded-xl border border-slate-200 bg-white p-3 text-sm text-slate-500 shadow-xl\"><span class=\"map-spinner flex-none\" aria-hidden=\"true\"></span>Identifying\u2026</div>';\n        }\n\n        const results = await Promise.allSettled([\n            ...layers.map((entry) => fetchFeatureInfo(entry, ctx.map, event.coordinate)),\n            ...externalLayers.map((entry) => fetchExternalFeatureInfo(entry, ctx.map, event.coordinate)),\n        ]);\n        if (seq !== clickSeq) return;\n        features = [\n            ...clientFeatures,\n            ...results.filter((r) => r.status === 'fulfilled').flatMap((r) => r.value),\n        ];\n        index = 0;\n        rerender();\n    });\n}\n", "/**\n * filter-ui.js \u2014 builder atributov\u00E9ho filtru (UI) pou\u017E\u00EDvan\u00FD atributovou\n * tabulkou (attr-table.js). Edituje pracovn\u00ED kopii filtru a commit d\u011Bl\u00E1 a\u017E\n * tla\u010D\u00EDtko \"Apply\" (aby rozpracovan\u00FD filtr nepos\u00EDlal WFS/WMS po\u017Eadavky).\n */\nimport { FILTER_OPERATORS, emptyFilter, emptyCondition } from './filter.js';\n\nconst INPUT_CLASS = 'rounded border-slate-200 py-1 text-xs focus:border-brand-500 focus:ring-brand-500';\n\n/** Jeden \u0159\u00E1dek podm\u00EDnky: atribut, oper\u00E1tor, hodnota (0/1/2 input\u016F), smaz\u00E1n\u00ED. */\nfunction conditionRow(condition, index, working, attributes, rerender) {\n    const row = document.createElement('div');\n    row.className = 'flex flex-wrap items-center gap-1.5';\n\n    const attrSelect = document.createElement('select');\n    attrSelect.className = INPUT_CLASS;\n    attrSelect.innerHTML = attributes\n        .map((name) => `<option value=\"${name}\" ${name === condition.attribute ? 'selected' : ''}>${name}</option>`)\n        .join('');\n    attrSelect.addEventListener('change', (e) => { condition.attribute = e.target.value; });\n    row.appendChild(attrSelect);\n\n    const opDef = FILTER_OPERATORS.find((o) => o.value === condition.operator) || FILTER_OPERATORS[0];\n    const opSelect = document.createElement('select');\n    opSelect.className = INPUT_CLASS;\n    opSelect.innerHTML = FILTER_OPERATORS\n        .map((o) => `<option value=\"${o.value}\" ${o.value === condition.operator ? 'selected' : ''}>${o.label}</option>`)\n        .join('');\n    opSelect.addEventListener('change', (e) => {\n        condition.operator = e.target.value;\n        rerender(); // po\u010Det value input\u016F se m\u016F\u017Ee zm\u011Bnit (is null/between)\n    });\n    row.appendChild(opSelect);\n\n    if (opDef.values >= 1) {\n        const valueInput = document.createElement('input');\n        valueInput.type = 'text';\n        valueInput.placeholder = 'Value';\n        valueInput.value = condition.value ?? '';\n        valueInput.className = `${INPUT_CLASS} w-28`;\n        valueInput.addEventListener('input', (e) => { condition.value = e.target.value; });\n        row.appendChild(valueInput);\n    }\n    if (opDef.values >= 2) {\n        const andLabel = document.createElement('span');\n        andLabel.className = 'text-xs text-slate-400';\n        andLabel.textContent = 'and';\n        row.appendChild(andLabel);\n        const value2Input = document.createElement('input');\n        value2Input.type = 'text';\n        value2Input.placeholder = 'Value';\n        value2Input.value = condition.value2 ?? '';\n        value2Input.className = `${INPUT_CLASS} w-28`;\n        value2Input.addEventListener('input', (e) => { condition.value2 = e.target.value; });\n        row.appendChild(value2Input);\n    }\n\n    const removeBtn = document.createElement('button');\n    removeBtn.type = 'button';\n    removeBtn.title = 'Remove condition';\n    removeBtn.className = 'flex-none rounded p-1 text-slate-400 hover:bg-red-50 hover:text-red-600';\n    removeBtn.textContent = '\\u2715';\n    removeBtn.addEventListener('click', () => {\n        working.conditions.splice(index, 1);\n        rerender();\n    });\n    row.appendChild(removeBtn);\n\n    return row;\n}\n\n/**\n * Vykresl\u00ED builder filtru do `container`.\n * `options`: { attributes: string[], filter: model|null,\n *              onApply(filter), onClear() }.\n */\nexport function renderFilterBuilder(container, options) {\n    const { attributes, filter, onApply, onClear } = options;\n    // Pracovn\u00ED kopie \u2014 \u00FApravy se projev\u00ED a\u017E po \"Apply\".\n    const working = filter\n        ? JSON.parse(JSON.stringify(filter))\n        : emptyFilter();\n\n    function rerender() {\n        container.innerHTML = '';\n        const wrap = document.createElement('div');\n        wrap.className = 'space-y-1.5';\n\n        // Spojka podm\u00EDnek: All (AND) / Any (OR).\n        const logicRow = document.createElement('div');\n        logicRow.className = 'flex items-center gap-x-2 text-xs text-slate-600';\n        const logicSelect = document.createElement('select');\n        logicSelect.className = INPUT_CLASS;\n        logicSelect.innerHTML = `\n            <option value=\"and\" ${working.logic !== 'or' ? 'selected' : ''}>All conditions (AND)</option>\n            <option value=\"or\" ${working.logic === 'or' ? 'selected' : ''}>Any condition (OR)</option>`;\n        logicSelect.addEventListener('change', (e) => { working.logic = e.target.value; });\n        logicRow.appendChild(document.createTextNode('Match'));\n        logicRow.appendChild(logicSelect);\n        wrap.appendChild(logicRow);\n\n        (working.conditions || []).forEach((condition, index) => {\n            wrap.appendChild(conditionRow(condition, index, working, attributes, rerender));\n        });\n\n        const buttonsRow = document.createElement('div');\n        buttonsRow.className = 'flex items-center gap-x-2 pt-1';\n\n        const addBtn = document.createElement('button');\n        addBtn.type = 'button';\n        addBtn.className = 'rounded-lg border border-dashed border-slate-300 px-2 py-1 text-xs text-slate-500 hover:border-brand-300 hover:text-brand-600';\n        addBtn.textContent = '+ Add condition';\n        addBtn.addEventListener('click', () => {\n            working.conditions.push(emptyCondition(attributes[0]));\n            rerender();\n        });\n        buttonsRow.appendChild(addBtn);\n\n        const spacer = document.createElement('div');\n        spacer.className = 'flex-1';\n        buttonsRow.appendChild(spacer);\n\n        const clearBtn = document.createElement('button');\n        clearBtn.type = 'button';\n        clearBtn.className = 'rounded-lg border border-slate-200 bg-white px-2 py-1 text-xs font-medium text-slate-600 shadow-sm hover:bg-slate-50';\n        clearBtn.textContent = 'Clear filter';\n        clearBtn.addEventListener('click', () => onClear());\n        buttonsRow.appendChild(clearBtn);\n\n        const applyBtn = document.createElement('button');\n        applyBtn.type = 'button';\n        applyBtn.className = 'rounded-lg border border-brand-300 bg-brand-50 px-2 py-1 text-xs font-medium text-brand-700 hover:bg-brand-100';\n        applyBtn.textContent = 'Apply';\n        applyBtn.addEventListener('click', () => onApply(working));\n        buttonsRow.appendChild(applyBtn);\n\n        wrap.appendChild(buttonsRow);\n        container.appendChild(wrap);\n    }\n\n    rerender();\n}\n", "/**\n * attr-table.js \u2014 dokovan\u00FD panel atributov\u00E9 tabulky u spodn\u00EDho okraje mapy.\n *\n * Dva zdroje \u0159\u00E1dk\u016F (`panel.mode`):\n *\n * - `wfs` \u2014 workspace vektory. Data p\u0159es WFS (wfs.js): str\u00E1nkov\u00E1n\u00ED\n *   Previous/Next (COUNT=200, STARTINDEX), celkov\u00FD po\u010Det p\u0159es\n *   RESULTTYPE=hits, \u0159azen\u00ED SORTBY, filter builder (filter.js) a fulltext\n *   (PropertyIsLike p\u0159es textov\u00E9 atributy) \u2014 filtr se prom\u00EDt\u00E1 i do mapy (SLD).\n *   Str\u00E1nka s geometriemi (GeoJSON) nesm\u00ED p\u0159ekro\u010Dit limit odpov\u011Bdi slu\u017Eby\n *   (6 MB, HTTP 413): u dat s velk\u00FDmi geometriemi (`heavyGeometries`, nebo\n *   po 413) se na\u010D\u00EDtaj\u00ED jen atributy (GML bez geometrie) a geometrie \u0159\u00E1dku\n *   se dot\u00E1hne a\u017E pro zv\u00FDrazn\u011Bn\u00ED \u010Di p\u0159ibl\u00ED\u017Een\u00ED (`ensureRowGeometry`).\n * - `local` \u2014 klientsk\u00E9 vrstvy: kresba (`drawing`, EDITOVATELN\u00C1 \u2014 hodnoty se\n *   p\u00ED\u0161\u00ED p\u0159\u00EDmo do bun\u011Bk, sloupce jde p\u0159id\u00E1vat, p\u0159ejmenov\u00E1vat a odeb\u00EDrat,\n *   \u0159\u00E1dek = prvek jde smazat) a lok\u00E1ln\u00ED vektorov\u00E1 data (`local`, jen \u010Dten\u00ED).\n *   \u0158azen\u00ED, hled\u00E1n\u00ED i str\u00E1nkov\u00E1n\u00ED b\u011B\u017E\u00ED v prohl\u00ED\u017Ee\u010Di nad prvky OL zdroje.\n *\n * Klik na \u0159\u00E1dek zv\u00FDrazn\u00ED prvek na map\u011B (klientsk\u00E1 OL Vector vrstva), dvojklik\n * nebo tla\u010D\u00EDtko lupy p\u0159ibl\u00ED\u017E\u00ED na prvek. Otev\u0159en\u00FD panel se NEukl\u00E1d\u00E1 do\n * Map.config (jen filtr a sloupce kresby, viz state.js).\n */\nimport VectorLayer from 'ol/layer/Vector.js';\nimport VectorSource from 'ol/source/Vector.js';\nimport Feature from 'ol/Feature.js';\nimport GeoJSON from 'ol/format/GeoJSON.js';\nimport Style from 'ol/style/Style.js';\nimport Stroke from 'ol/style/Stroke.js';\nimport Fill from 'ol/style/Fill.js';\nimport CircleStyle from 'ol/style/Circle.js';\nimport { getUid } from 'ol/util.js';\nimport { on, debounce } from './utils.js';\nimport { fetchAttributesPage, fetchFeaturesPage, fetchHits } from './wfs.js';\nimport { findEntryByUid } from './state.js';\nimport { buildFilterXml } from './filter.js';\nimport { scheduleWmsRefresh } from './wms.js';\nimport { hasAttributeTable, renderLayerTree } from './layers.js';\nimport { zoomToExtent } from './map.js';\nimport { renderFilterBuilder } from './filter-ui.js';\nimport {\n    addDrawingField,\n    drawingAttributes,\n    drawingFieldError,\n    removeDrawingFeature,\n    removeDrawingField,\n    renameDrawingField,\n    setDrawingValue,\n} from './draw.js';\n\nconst PAGE_SIZE = 200;\n\n/** Kolik sm\u00ED m\u00EDt str\u00E1nka s geometriemi podle odhadu (limit slu\u017Eby je 6 MB;\n * GeoJSON v EPSG:3857 b\u00FDv\u00E1 v\u011Bt\u0161\u00ED ne\u017E zdrojov\u00FD soubor). */\nconst PAGE_BYTES_BUDGET = 3 * 1024 * 1024;\n\n/** Typov\u00E9 hinty textov\u00FDch atribut\u016F (pro fulltext PropertyIsLike). */\nconst TEXT_TYPE_HINTS = ['string', 'char', 'text'];\n\n/** Jedin\u00FD b\u011Bhov\u00FD stav panelu \u2014 otev\u0159en\u00E1 m\u016F\u017Ee b\u00FDt max. jedna tabulka. */\nconst panel = {\n    ctx: null,\n    entry: null,          // b\u011Bhov\u00E1 vrstva, jej\u00ED\u017E tabulka je otev\u0159en\u00E1\n    mode: 'wfs',          // 'wfs' | 'local'\n    editable: false,      // kresba \u2014 hodnoty a sloupce jdou m\u011Bnit\n    typename: null,       // aktivn\u00ED podvrstva (jen wfs)\n    page: 0,              // str\u00E1nka (0-based)\n    total: null,          // celkov\u00FD po\u010Det prvk\u016F (po filtru)\n    features: [],         // \u0159\u00E1dky aktu\u00E1ln\u00ED str\u00E1nky: { id, index?, properties, geometry?, olFeature? }\n                          // (geometry undefined = je\u0161t\u011B nena\u010Dten\u00E1, null = \u017E\u00E1dn\u00E1)\n    columns: [],          // n\u00E1zvy sloupc\u016F\n    sort: null,           // { attribute, dir: 'ASC'|'DESC' }\n    searchText: '',\n    filterOpen: false,\n    addingColumn: false,  // otev\u0159en\u00FD formul\u00E1\u0159 nov\u00E9ho sloupce\n    loading: false,\n    error: null,\n    highlightId: null,    // id zv\u00FDrazn\u011Bn\u00E9ho prvku (\u0159\u00E1dek + mapa)\n    focusId: null,        // prvek, na kter\u00FD se m\u00E1 tabulka po na\u010Dten\u00ED zam\u011B\u0159it\n    requestSeq: 0,        // ochrana proti z\u00E1vod\u016Fm odpov\u011Bd\u00ED\n    query: null,          // { sortBy, filterXml } na\u010Dten\u00E9 str\u00E1nky (geometrie \u0159\u00E1dku)\n    attributesOnly: new Set(), // podvrstvy, kter\u00E9 se \u010Dtou bez geometrie (po 413)\n    geometryNote: null,   // pro\u010D se prvek ned\u00E1 uk\u00E1zat na map\u011B\n    selfEdit: false,      // pr\u00E1v\u011B zapisujeme hodnotu z bu\u0148ky (bez p\u0159ekreslen\u00ED)\n};\n\nconst geojsonFormat = new GeoJSON();\n\n/* ---------------------------------------------------------------------------\n * Zv\u00FDrazn\u011Bn\u00ED prvku na map\u011B (klientsk\u00E1 vektorov\u00E1 vrstva)\n * ------------------------------------------------------------------------- */\n\nconst HIGHLIGHT_COLOR = '#e11d48'; // rose-600 \u2014 v\u00FDrazn\u00E1 barva nad b\u011B\u017En\u00FDmi styly\n\nlet highlightLayer = null;\n\nfunction getHighlightLayer(ctx) {\n    if (highlightLayer) return highlightLayer;\n    const stroke = new Stroke({ color: HIGHLIGHT_COLOR, width: 3 });\n    const fill = new Fill({ color: 'rgba(225, 29, 72, 0.25)' });\n    highlightLayer = new VectorLayer({\n        source: new VectorSource(),\n        style: new Style({\n            stroke,\n            fill,\n            image: new CircleStyle({ radius: 8, stroke, fill }),\n        }),\n        zIndex: 1000, // v\u017Edy nad WMS vrstvami\n    });\n    ctx.map.addLayer(highlightLayer);\n    return highlightLayer;\n}\n\n/** OL geometrie \u0159\u00E1dku v projekci mapy (kopie \u2014 zv\u00FDrazn\u011Bn\u00ED ji nesm\u00ED sd\u00EDlet). */\nfunction rowGeometry(row) {\n    if (row?.olFeature) return row.olFeature.getGeometry()?.clone() || null;\n    if (!row?.geometry) return null;\n    // Geometrie z WFS/GetFeatureInfo u\u017E je v EPSG:3857.\n    return geojsonFormat.readGeometry(row.geometry, {\n        featureProjection: 'EPSG:3857',\n        dataProjection: 'EPSG:3857',\n    });\n}\n\n/** Zv\u00FDrazn\u00ED prvek \u0159\u00E1dku na map\u011B (\u0159\u00E1dek bez na\u010Dten\u00E9 geometrie zat\u00EDm nic). */\nfunction highlightOnMap(ctx, row) {\n    const layer = getHighlightLayer(ctx);\n    layer.getSource().clear();\n    const geometry = rowGeometry(row);\n    if (geometry) layer.getSource().addFeature(new Feature(geometry));\n}\n\n/** Str\u00E1nka bez geometri\u00ED: geometrie jednoho \u0159\u00E1dku \u2014 tent\u00FD\u017E dotaz (\u0159azen\u00ED,\n * filtr) s COUNT=1 na pozici \u0159\u00E1dku. Jedin\u00FD ob\u0159\u00ED prvek m\u016F\u017Ee i tak p\u0159ekro\u010Dit\n * limit slu\u017Eby; pak se to nap\u00ED\u0161e ve stavov\u00E9 li\u0161t\u011B. */\nasync function ensureRowGeometry(row) {\n    if (!row || row.olFeature || row.geometry !== undefined) return;\n    if (!row.geometryRequest) {\n        const { ctx, entry, typename, query } = panel;\n        row.geometryRequest = fetchFeaturesPage(ctx.bootstrap, entry, typename, {\n            count: 1,\n            startIndex: row.index,\n            sortBy: query?.sortBy,\n            filterXml: query?.filterXml,\n            srsName: 'EPSG:3857',\n            propertyName: panel.columns[0],\n        }).then((page) => {\n            row.geometry = page.features?.[0]?.geometry || null;\n        }).catch((error) => {\n            panel.geometryNote = error?.status === 413\n                ? 'This feature is too large to show on the map.'\n                : `The feature's shape could not be loaded: ${error.message}`;\n            renderStatus();\n        }).finally(() => {\n            row.geometryRequest = null;\n        });\n    }\n    await row.geometryRequest;\n}\n\n/** Odhad: p\u0159ekro\u010Dila by str\u00E1nka s geometriemi limit odpov\u011Bdi slu\u017Eby?\n * Velikost souboru na prvek \u00D7 prvk\u016F na str\u00E1nce (14 kraj\u016F \u010CR = 7,9 MB). */\nfunction heavyGeometries(entry, typename) {\n    const size = Number(entry?.source?.size_bytes) || 0;\n    const layers = entry?.sublayers || [];\n    const features = layers.reduce((sum, layer) => sum + (Number(layer.feature_count) || 0), 0);\n    if (!size || !features) return false;\n    const own = Number(layers.find((layer) => layer.name === typename)?.feature_count) || PAGE_SIZE;\n    return (size / features) * Math.min(PAGE_SIZE, own) > PAGE_BYTES_BUDGET;\n}\n\n/** Zru\u0161\u00ED zv\u00FDrazn\u011Bn\u00ED na map\u011B i v tabulce. */\nexport function clearHighlight() {\n    panel.highlightId = null;\n    highlightLayer?.getSource().clear();\n    updateRowHighlight();\n}\n\n/** P\u0159ibl\u00ED\u017E\u00ED mapu na geometrii dan\u00E9ho \u0159\u00E1dku (u str\u00E1nky bez geometri\u00ED ji\n * nejd\u0159\u00EDv dot\u00E1hne). */\nasync function zoomToRow(ctx, row) {\n    await ensureRowGeometry(row);\n    const geometry = rowGeometry(row);\n    if (geometry) zoomToExtent(ctx.map, geometry.getExtent());\n}\n\n/* ---------------------------------------------------------------------------\n * Na\u010D\u00EDt\u00E1n\u00ED dat \u2014 WFS (str\u00E1nkov\u00E1n\u00ED + hits)\n * ------------------------------------------------------------------------- */\n\n/** Aktivn\u00ED podvrstva (objekt z entry.sublayers) podle panel.typename. */\nfunction activeSublayer() {\n    return (panel.entry?.sublayers || []).find((s) => s.name === panel.typename) || null;\n}\n\n/** Textov\u00E9 atributy aktivn\u00ED podvrstvy (fulltext PropertyIsLike). */\nfunction textAttributeNames() {\n    return (activeSublayer()?.attributes || [])\n        .filter((a) => TEXT_TYPE_HINTS.some((hint) => (a.type || '').toLowerCase().includes(hint)))\n        .map((a) => a.name);\n}\n\n/** Hotov\u00FD `<ogc:Filter>` pro WFS = builder filtr AND fulltext (nebo null). */\nfunction currentFilterXml() {\n    return buildFilterXml(panel.entry?.filter, panel.searchText, textAttributeNames());\n}\n\n/** Na\u010Dte aktu\u00E1ln\u00ED str\u00E1nku z WFS + celkov\u00FD po\u010Det. `requestSeq` zahazuje\n * odpov\u011Bdi zastaral\u00FDch po\u017Eadavk\u016F (rychl\u00E9 p\u0159ep\u00EDn\u00E1n\u00ED). */\nasync function loadWfsPage() {\n    const { ctx, entry, typename } = panel;\n    if (!typename) return;\n    const seq = ++panel.requestSeq;\n    panel.loading = true;\n    panel.error = null;\n    panel.columns = (activeSublayer()?.attributes || []).map((a) => a.name);\n    renderStatus();\n    panel.geometryNote = null;\n    const filterXml = currentFilterXml();\n    const sortBy = panel.sort ? `${panel.sort.attribute} ${panel.sort.dir}` : undefined;\n    const startIndex = panel.page * PAGE_SIZE;\n    const attributesOnly = panel.columns.length > 0\n        && (panel.attributesOnly.has(typename) || heavyGeometries(entry, typename));\n    // SRSNAME=EPSG:3857 \u2192 geometrie rovnou v projekci mapy (zv\u00FDrazn\u011Bn\u00ED).\n    const withGeometry = () => fetchFeaturesPage(ctx.bootstrap, entry, typename, {\n        count: PAGE_SIZE, startIndex, sortBy, srsName: 'EPSG:3857', filterXml,\n    }).then((page) => (page.features || []).map((feature) => ({\n        id: feature.id, properties: feature.properties || {}, geometry: feature.geometry || null,\n    })));\n    const attributes = () => fetchAttributesPage(ctx.bootstrap, entry, typename, {\n        attributes: panel.columns, count: PAGE_SIZE, startIndex, sortBy, filterXml,\n    }).then((features) => features.map((feature) => ({ properties: feature.properties, geometry: undefined })));\n    try {\n        const [rows, total] = await Promise.all([\n            (attributesOnly ? attributes() : withGeometry()).catch((error) => {\n                // Odhad nevy\u0161el a str\u00E1nka s geometriemi je p\u0159es limit slu\u017Eby.\n                if (attributesOnly || error?.status !== 413 || !panel.columns.length) throw error;\n                panel.attributesOnly.add(typename);\n                return attributes();\n            }),\n            fetchHits(ctx.bootstrap, entry, typename, { filterXml }),\n        ]);\n        if (seq !== panel.requestSeq) return; // mezit\u00EDm ode\u0161el nov\u011Bj\u0161\u00ED po\u017Eadavek\n        panel.query = { sortBy, filterXml };\n        // Prvek bez id (n\u011Bkter\u00E9 zdroje ho nemaj\u00ED) dostane po\u0159adov\u00E9, aby \u0161el\n        // \u0159\u00E1dek jednozna\u010Dn\u011B vybrat.\n        panel.features = rows.map((row, position) => ({\n            id: String(row.id ?? `row-${startIndex + position}`),\n            index: startIndex + position,\n            properties: row.properties,\n            geometry: row.geometry,\n        }));\n        panel.total = total;\n        panel.loading = false;\n        renderTable();\n    } catch (error) {\n        if (seq !== panel.requestSeq) return;\n        panel.loading = false;\n        panel.error = error.message;\n        panel.features = [];\n        renderTable();\n    }\n    renderStatus();\n}\n\n/* ---------------------------------------------------------------------------\n * Na\u010D\u00EDt\u00E1n\u00ED dat \u2014 klientsk\u00E9 vrstvy (kresba, lok\u00E1ln\u00ED data)\n * ------------------------------------------------------------------------- */\n\n/** Atributy prvku klientsk\u00E9 vrstvy (kresba: bez stylov\u00FDch vlastnost\u00ED). */\nfunction localProperties(entry, feature) {\n    if (entry.dataType === 'drawing') return drawingAttributes(feature);\n    const properties = { ...feature.getProperties() };\n    delete properties[feature.getGeometryName()];\n    return properties;\n}\n\n/** Porovn\u00E1n\u00ED hodnot pro \u0159azen\u00ED: \u010D\u00EDsla \u010D\u00EDseln\u011B, texty podle abecedy, pr\u00E1zdn\u00E9\n * hodnoty v\u017Edy na konec. */\nfunction compareValues(a, b, dir) {\n    const emptyA = a === null || a === undefined || a === '';\n    const emptyB = b === null || b === undefined || b === '';\n    if (emptyA || emptyB) return emptyA === emptyB ? 0 : (emptyA ? 1 : -1);\n    const numA = typeof a === 'number' ? a : Number(a);\n    const numB = typeof b === 'number' ? b : Number(b);\n    const result = Number.isFinite(numA) && Number.isFinite(numB)\n        ? numA - numB\n        : String(a).localeCompare(String(b), undefined, { numeric: true, sensitivity: 'base' });\n    return dir === 'DESC' ? -result : result;\n}\n\n/** Sestav\u00ED \u0159\u00E1dky klientsk\u00E9 vrstvy: hled\u00E1n\u00ED, \u0159azen\u00ED a v\u00FD\u0159ez str\u00E1nky. */\nfunction loadLocalPage() {\n    const { entry } = panel;\n    const source = entry?.olSource;\n    if (!source) return;\n    // Po\u0159ad\u00ED vzniku prvk\u016F (OL uid roste) \u2014 `getFeatures()` ho nezaru\u010Duje.\n    let rows = source.getFeatures()\n        .map((feature) => ({\n            id: String(getUid(feature)),\n            order: Number(getUid(feature)),\n            properties: localProperties(entry, feature),\n            olFeature: feature,\n        }))\n        .sort((a, b) => a.order - b.order);\n\n    if (entry.dataType === 'drawing') {\n        panel.columns = [...(entry.fields || [])];\n    } else {\n        const names = new Set();\n        rows.forEach((row) => Object.keys(row.properties).forEach((name) => names.add(name)));\n        panel.columns = Array.from(names);\n    }\n\n    const needle = panel.searchText.trim().toLowerCase();\n    if (needle) {\n        rows = rows.filter((row) => Object.values(row.properties)\n            .some((value) => value !== null && value !== undefined && String(value).toLowerCase().includes(needle)));\n    }\n    if (panel.sort) {\n        const { attribute, dir } = panel.sort;\n        rows.sort((a, b) => compareValues(a.properties[attribute], b.properties[attribute], dir));\n    }\n    panel.total = rows.length;\n    // Zam\u011B\u0159en\u00ED na prvek (z popupu) \u2014 p\u0159ej\u00EDt na str\u00E1nku, kde le\u017E\u00ED.\n    if (panel.focusId !== null) {\n        const position = rows.findIndex((row) => row.id === String(panel.focusId));\n        if (position !== -1) panel.page = Math.floor(position / PAGE_SIZE);\n    }\n    const lastPage = Math.max(0, Math.ceil(rows.length / PAGE_SIZE) - 1);\n    panel.page = Math.min(panel.page, lastPage);\n    panel.features = rows.slice(panel.page * PAGE_SIZE, (panel.page + 1) * PAGE_SIZE);\n    panel.loading = false;\n    panel.error = null;\n    renderTable();\n    renderStatus();\n}\n\n/** Na\u010Dte (wfs), resp. sestav\u00ED (local) aktu\u00E1ln\u00ED str\u00E1nku a p\u0159ekresl\u00ED tabulku. */\nfunction loadPage() {\n    if (!panel.ctx || !panel.entry) return;\n    if (panel.mode === 'local') {\n        loadLocalPage();\n    } else {\n        loadWfsPage();\n    }\n}\n\n/* ---------------------------------------------------------------------------\n * Vykreslen\u00ED panelu\n * ------------------------------------------------------------------------- */\n\nfunction panelElement() {\n    return panel.ctx?.elements.attrTable || document.getElementById('map-attr-table');\n}\n\nfunction htmlEscape(value) {\n    return String(value)\n        .replace(/&/g, '&amp;')\n        .replace(/</g, '&lt;')\n        .replace(/>/g, '&gt;')\n        .replace(/\"/g, '&quot;');\n}\n\n/** Text hodnoty v bu\u0148ce (objekty/pole jako JSON). */\nfunction cellText(value) {\n    if (value === null || value === undefined) return '';\n    return typeof value === 'object' ? JSON.stringify(value) : String(value);\n}\n\n/** Aktualizuje zv\u00FDrazn\u011Bn\u00ED \u0159\u00E1dku podle panel.highlightId (bez p\u0159ekreslen\u00ED). */\nfunction updateRowHighlight() {\n    const el = panelElement();\n    if (!el) return;\n    el.querySelectorAll('tbody tr[data-feature-id]').forEach((tr) => {\n        tr.classList.toggle('is-highlighted', tr.dataset.featureId === String(panel.highlightId ?? ''));\n    });\n}\n\n/** Zv\u00FDrazn\u00ED \u0159\u00E1dek i prvek na map\u011B; `scroll` = odscrollovat na \u0159\u00E1dek. */\nfunction selectRow(row, { scroll = false } = {}) {\n    panel.highlightId = row.id;\n    highlightOnMap(panel.ctx, row);\n    updateRowHighlight();\n    if (row.geometry === undefined && !row.olFeature) {\n        // Str\u00E1nka bez geometri\u00ED: tvar prvku a\u017E te\u010F (a jen kdy\u017E je \u0159\u00E1dek po\u0159\u00E1d vybran\u00FD).\n        ensureRowGeometry(row).then(() => {\n            if (String(panel.highlightId) === row.id) highlightOnMap(panel.ctx, row);\n        });\n    }\n    if (scroll) {\n        const tr = panelElement()?.querySelector(`tbody tr[data-feature-id=\"${CSS.escape(row.id)}\"]`);\n        tr?.scrollIntoView({ block: 'nearest' });\n    }\n}\n\n/** Stavov\u00E1 li\u0161ta: \u201EShowing X\u2013Y of Z features\" + str\u00E1nkov\u00E1n\u00ED + loading/chyba. */\nfunction renderStatus() {\n    const el = panelElement()?.querySelector('[data-role=\"table-status\"]');\n    if (!el) return;\n    if (panel.loading) {\n        el.innerHTML = '<span class=\"flex items-center gap-x-2 text-slate-400\"><span class=\"map-spinner\" aria-hidden=\"true\"></span>Loading\u2026</span>';\n        return;\n    }\n    if (panel.error) {\n        el.innerHTML = `<span class=\"text-red-500\">Failed to load features: ${htmlEscape(panel.error)}</span>`;\n        return;\n    }\n    const total = panel.total ?? panel.features.length;\n    const from = panel.features.length === 0 ? 0 : panel.page * PAGE_SIZE + 1;\n    const to = panel.page * PAGE_SIZE + panel.features.length;\n    const lastPage = Math.max(0, Math.ceil(total / PAGE_SIZE) - 1);\n    const summary = total === 0\n        ? 'No features'\n        : `Showing ${from}\u2013${to} of ${total} feature${total === 1 ? '' : 's'}`;\n    const note = panel.geometryNote ? `<span class=\"text-amber-600\">${htmlEscape(panel.geometryNote)}</span>` : '';\n    // Jedna str\u00E1nka = str\u00E1nkov\u00E1n\u00ED je zbyte\u010Dn\u00E9.\n    const pager = lastPage === 0 ? '' : `\n        <span class=\"flex items-center gap-x-1\">\n            <button type=\"button\" data-role=\"page-prev\" ${panel.page === 0 ? 'disabled' : ''}\n                    class=\"rounded px-2 py-0.5 hover:bg-slate-100 disabled:cursor-not-allowed disabled:opacity-40\">\u2039 Previous</button>\n            <span class=\"tabular-nums text-slate-500\">Page ${panel.page + 1} / ${lastPage + 1}</span>\n            <button type=\"button\" data-role=\"page-next\" ${panel.page >= lastPage ? 'disabled' : ''}\n                    class=\"rounded px-2 py-0.5 hover:bg-slate-100 disabled:cursor-not-allowed disabled:opacity-40\">Next \u203A</button>\n        </span>`;\n    el.innerHTML = `<span class=\"text-slate-500\">${summary}</span>${note}${pager}`;\n    el.querySelector('[data-role=\"page-prev\"]')?.addEventListener('click', () => {\n        panel.page -= 1;\n        loadPage();\n    });\n    el.querySelector('[data-role=\"page-next\"]')?.addEventListener('click', () => {\n        panel.page += 1;\n        loadPage();\n    });\n}\n\n/** \u0160ipka indikuj\u00EDc\u00ED sm\u011Br \u0159azen\u00ED ve zvolen\u00E9 hlavi\u010Dce. */\nfunction sortIndicator(attribute) {\n    if (panel.sort?.attribute !== attribute) return '';\n    return panel.sort.dir === 'ASC' ? ' \u25B2' : ' \u25BC';\n}\n\nconst ICON_ZOOM = '<svg class=\"h-3.5 w-3.5\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\"><circle cx=\"11\" cy=\"11\" r=\"7\"/><path d=\"m21 21-4.3-4.3\"/></svg>';\nconst ICON_TRASH = '<svg class=\"h-3.5 w-3.5\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M3 6h18M8 6V4h8v2m-9 0 1 14h8l1-14\"/></svg>';\nconst ICON_PENCIL = '<svg class=\"h-3 w-3\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M17 3a2.8 2.8 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z\"/></svg>';\nconst ICON_X = '<svg class=\"h-3 w-3\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2.5\" stroke-linecap=\"round\"><path d=\"M18 6 6 18M6 6l12 12\"/></svg>';\n\nconst TH_CLASS = 'whitespace-nowrap border-b border-slate-200 bg-slate-50 px-2 py-1.5 text-left font-semibold text-slate-600';\n\n/** V\u00FDpl\u0148ov\u00FD sloupec na konci \u0159\u00E1dku \u2014 pohlt\u00ED volnou \u0161\u00ED\u0159ku, aby datov\u00E9 sloupce\n * z\u016Fstaly \u00FAzk\u00E9 a zarovnan\u00E9 vlevo (m\u00EDsto rozta\u017Een\u00ED p\u0159es cel\u00FD panel). */\nconst FILLER_CELL = '<td class=\"w-full border-b border-slate-100\"></td>';\n\n/** Kr\u00E1tk\u00FD popis geometrie prvku klientsk\u00E9 vrstvy (sloupec \u201EShape\u201C). */\nfunction shapeLabel(row) {\n    const type = row.olFeature?.getGeometry()?.getType() || '';\n    if (type.includes('Point')) return 'Point';\n    if (type.includes('Line')) return 'Line';\n    if (type.includes('Polygon')) return 'Polygon';\n    return type || '\u2014';\n}\n\n/** Hlavi\u010Dka jednoho sloupce; u kresby s tla\u010D\u00EDtky p\u0159ejmenovat/odebrat. */\nfunction headerCell(name) {\n    const label = `<button type=\"button\" data-role=\"sort\" data-attribute=\"${htmlEscape(name)}\" title=\"Sort by ${htmlEscape(name)}\"\n            class=\"font-semibold hover:text-slate-900\">${htmlEscape(name)}${sortIndicator(name)}</button>`;\n    if (!panel.editable) {\n        return `<th class=\"${TH_CLASS}\">${label}</th>`;\n    }\n    return `<th class=\"${TH_CLASS}\" data-column=\"${htmlEscape(name)}\">\n        <span class=\"flex items-center gap-x-1\">\n            ${label}\n            <button type=\"button\" data-role=\"column-rename\" data-attribute=\"${htmlEscape(name)}\" title=\"Rename column\" aria-label=\"Rename column ${htmlEscape(name)}\"\n                    class=\"map-attr-col-action rounded p-0.5 text-slate-400 hover:bg-slate-200 hover:text-slate-700\">${ICON_PENCIL}</button>\n            <button type=\"button\" data-role=\"column-remove\" data-attribute=\"${htmlEscape(name)}\" title=\"Remove column\" aria-label=\"Remove column ${htmlEscape(name)}\"\n                    class=\"map-attr-col-action rounded p-0.5 text-slate-400 hover:bg-red-50 hover:text-red-600\">${ICON_X}</button>\n        </span>\n    </th>`;\n}\n\n/** Bu\u0148ka s hodnotou; u kresby editovateln\u00E9 pole. */\nfunction valueCell(row, name) {\n    const text = cellText(row.properties?.[name]);\n    if (panel.editable) {\n        return `<td class=\"border-b border-slate-100 p-0\">\n            <input type=\"text\" data-role=\"cell\" data-attribute=\"${htmlEscape(name)}\" value=\"${htmlEscape(text)}\"\n                   aria-label=\"${htmlEscape(name)}\" class=\"map-attr-cell\">\n        </td>`;\n    }\n    return `<td class=\"max-w-[24rem] truncate border-b border-slate-100 px-2 py-1 text-slate-700\" title=\"${htmlEscape(text)}\">${text === '' ? '<span class=\"text-slate-300\">\u2014</span>' : htmlEscape(text)}</td>`;\n}\n\n/** \u00DAvodn\u00ED sloupec \u0159\u00E1dku: lupa (p\u0159ibl\u00ED\u017Eit) a u kresby ko\u0161 (smazat prvek). */\nfunction actionCell() {\n    return `<td class=\"whitespace-nowrap border-b border-slate-100 px-1 py-0.5\">\n        <button type=\"button\" data-role=\"row-zoom\" title=\"Zoom to feature\" aria-label=\"Zoom to feature\"\n                class=\"rounded p-1 text-slate-400 hover:bg-slate-100 hover:text-slate-700\">${ICON_ZOOM}</button>\n        ${panel.editable ? `<button type=\"button\" data-role=\"row-delete\" title=\"Delete feature\" aria-label=\"Delete feature\"\n                class=\"rounded p-1 text-slate-400 hover:bg-red-50 hover:text-red-600\">${ICON_TRASH}</button>` : ''}\n    </td>`;\n}\n\n/** Text pr\u00E1zdn\u00E9ho stavu tabulky. */\nfunction emptyStateText() {\n    if (panel.searchText.trim()) return 'No features match your search.';\n    if (panel.editable) return 'Nothing drawn yet \u2014 use Tools \u2192 Draw to add features.';\n    return 'No features found.';\n}\n\n/** P\u0159ekresl\u00ED vlastn\u00ED tabulku (hlavi\u010Dky + \u0159\u00E1dky aktu\u00E1ln\u00ED str\u00E1nky). */\nfunction renderTable() {\n    const container = panelElement()?.querySelector('[data-role=\"table-body\"]');\n    if (!container) return;\n    const { columns } = panel;\n    const local = panel.mode === 'local';\n    const leadHeaders = `<th class=\"${TH_CLASS} w-px\"></th>${local ? `<th class=\"${TH_CLASS} w-px font-normal text-slate-400\">Shape</th>` : ''}`;\n    const headers = columns.map(headerCell).join('');\n    const rows = panel.features.map((row) => {\n        const cells = columns.map((name) => valueCell(row, name)).join('');\n        const shape = local ? `<td class=\"whitespace-nowrap border-b border-slate-100 px-2 py-1 text-slate-400\">${htmlEscape(shapeLabel(row))}</td>` : '';\n        return `<tr data-feature-id=\"${htmlEscape(row.id)}\" class=\"map-attr-row\">${actionCell()}${shape}${cells}${FILLER_CELL}</tr>`;\n    }).join('');\n    const columnCount = columns.length + (local ? 3 : 2);\n    // Kresba bez sloupc\u016F: vysv\u011Btlit, k \u010Demu sloupce jsou, m\u00EDsto pr\u00E1zdn\u00E9 m\u0159\u00ED\u017Eky.\n    const noColumnsHint = panel.editable && columns.length === 0 && panel.features.length > 0\n        ? `<p class=\"border-b border-slate-100 bg-brand-50/50 px-3 py-2 text-xs text-slate-600\">\n               This layer has no attribute columns yet. Use <span class=\"font-semibold\">Add column</span> to store values (a name, a note, a number\u2026) for each feature.\n           </p>`\n        : '';\n    container.innerHTML = `\n        ${noColumnsHint}\n        <table class=\"min-w-full text-xs\">\n            <thead class=\"sticky top-0 z-[1]\"><tr>${leadHeaders}${headers}<th class=\"${TH_CLASS} w-full\"></th></tr></thead>\n            <tbody>${rows || `<tr><td colspan=\"${columnCount}\" class=\"px-3 py-6 text-center text-slate-400\">${emptyStateText()}</td></tr>`}</tbody>\n        </table>`;\n\n    container.querySelectorAll('[data-role=\"sort\"]').forEach((button) => {\n        button.addEventListener('click', () => {\n            const attribute = button.dataset.attribute;\n            // Klik: ASC \u2192 DESC \u2192 ASC\u2026; jin\u00FD sloupec za\u010D\u00EDn\u00E1 od ASC. Reset na 1. str\u00E1nku.\n            const dir = panel.sort?.attribute === attribute && panel.sort.dir === 'ASC' ? 'DESC' : 'ASC';\n            panel.sort = { attribute, dir };\n            panel.page = 0;\n            loadPage();\n        });\n    });\n    container.querySelectorAll('[data-role=\"column-rename\"]').forEach((button) => {\n        button.addEventListener('click', () => startColumnRename(button.dataset.attribute));\n    });\n    container.querySelectorAll('[data-role=\"column-remove\"]').forEach((button) => {\n        button.addEventListener('click', () => removeColumn(button.dataset.attribute));\n    });\n\n    container.querySelectorAll('tbody tr[data-feature-id]').forEach((tr) => {\n        const findRow = () => panel.features.find((f) => f.id === tr.dataset.featureId);\n        tr.addEventListener('click', (event) => {\n            if (event.target.closest('button')) return;\n            const row = findRow();\n            if (!row) return;\n            // Druh\u00FD klik na stejn\u00FD \u0159\u00E1dek zv\u00FDrazn\u011Bn\u00ED zru\u0161\u00ED (ne p\u0159i psan\u00ED do bu\u0148ky).\n            if (String(panel.highlightId) === row.id && !event.target.closest('input')) {\n                clearHighlight();\n                return;\n            }\n            selectRow(row);\n        });\n        tr.addEventListener('dblclick', (event) => {\n            if (event.target.closest('input, button')) return;\n            const row = findRow();\n            if (row) zoomToRow(panel.ctx, row);\n        });\n        tr.querySelector('[data-role=\"row-zoom\"]')?.addEventListener('click', () => {\n            const row = findRow();\n            if (!row) return;\n            selectRow(row);\n            zoomToRow(panel.ctx, row);\n        });\n        tr.querySelector('[data-role=\"row-delete\"]')?.addEventListener('click', () => {\n            const row = findRow();\n            if (!row?.olFeature) return;\n            if (String(panel.highlightId) === row.id) clearHighlight();\n            removeDrawingFeature(panel.ctx, panel.entry, row.olFeature);\n        });\n        tr.querySelectorAll('[data-role=\"cell\"]').forEach((input) => {\n            input.addEventListener('focus', () => {\n                const row = findRow();\n                if (row && String(panel.highlightId) !== row.id) selectRow(row);\n            });\n            input.addEventListener('change', () => commitCell(findRow(), input));\n            input.addEventListener('keydown', (event) => {\n                if (event.key === 'Enter') {\n                    event.preventDefault();\n                    input.blur();\n                    // Enter = o \u0159\u00E1dek n\u00ED\u017E ve stejn\u00E9m sloupci (jako v tabulkov\u00E9m editoru).\n                    const next = tr.nextElementSibling?.querySelector(`[data-role=\"cell\"][data-attribute=\"${CSS.escape(input.dataset.attribute)}\"]`);\n                    next?.focus();\n                } else if (event.key === 'Escape') {\n                    const row = findRow();\n                    input.value = cellText(row?.properties?.[input.dataset.attribute]);\n                    input.blur();\n                    event.stopPropagation();\n                }\n            });\n        });\n    });\n\n    updateRowHighlight();\n    applyFocus();\n}\n\n/** Zap\u00ED\u0161e hodnotu z bu\u0148ky do prvku kresby (bez p\u0159ekreslen\u00ED tabulky, aby\n * nezmizel kurzor p\u0159i p\u0159echodu do dal\u0161\u00ED bu\u0148ky). */\nfunction commitCell(row, input) {\n    if (!row?.olFeature) return;\n    const name = input.dataset.attribute;\n    panel.selfEdit = true;\n    try {\n        setDrawingValue(panel.ctx, panel.entry, row.olFeature, name, input.value);\n    } finally {\n        panel.selfEdit = false;\n    }\n    row.properties = drawingAttributes(row.olFeature);\n    // Zobrazit ulo\u017Eenou podobu hodnoty (o\u0159\u00EDznut\u00E9 mezery, \u010D\u00EDslo\u2026).\n    input.value = cellText(row.properties[name]);\n}\n\n/** Po na\u010Dten\u00ED zam\u011B\u0159\u00ED \u0159\u00E1dek vy\u017E\u00E1dan\u00FD z popupu (zv\u00FDrazn\u011Bn\u00ED + kurzor do bu\u0148ky). */\nfunction applyFocus() {\n    if (panel.focusId === null) return;\n    const row = panel.features.find((f) => f.id === String(panel.focusId));\n    panel.focusId = null;\n    if (!row) return;\n    selectRow(row, { scroll: true });\n    if (panel.editable) {\n        const tr = panelElement()?.querySelector(`tbody tr[data-feature-id=\"${CSS.escape(row.id)}\"]`);\n        tr?.querySelector('[data-role=\"cell\"]')?.focus({ preventScroll: true });\n    }\n}\n\n/* ---------------------------------------------------------------------------\n * Sloupce kresby: p\u0159idat, p\u0159ejmenovat, odebrat\n * ------------------------------------------------------------------------- */\n\nfunction setColumnError(text) {\n    const el = panelElement()?.querySelector('[data-role=\"column-error\"]');\n    if (!el) return;\n    el.textContent = text || '';\n    el.classList.toggle('hidden', !text);\n}\n\n/** Formul\u00E1\u0159 nov\u00E9ho sloupce v hlavi\u010Dce panelu (n\u00E1zev + Add/Cancel). */\nfunction renderAddColumn() {\n    const area = panelElement()?.querySelector('[data-role=\"add-column-area\"]');\n    if (!area) return;\n    if (!panel.editable) {\n        area.innerHTML = '';\n        return;\n    }\n    if (!panel.addingColumn) {\n        area.innerHTML = `\n            <button type=\"button\" data-role=\"add-column\"\n                    class=\"inline-flex items-center gap-x-1 rounded-lg border border-slate-200 bg-white px-2 py-1 text-xs font-medium text-slate-700 shadow-sm hover:bg-slate-50\">\n                <svg class=\"h-3.5 w-3.5\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\"><path d=\"M12 5v14M5 12h14\"/></svg>\n                Add column\n            </button>`;\n        area.querySelector('[data-role=\"add-column\"]').addEventListener('click', () => {\n            panel.addingColumn = true;\n            renderAddColumn();\n        });\n        setColumnError('');\n        return;\n    }\n    area.innerHTML = `\n        <form data-role=\"add-column-form\" class=\"flex items-center gap-x-1\">\n            <input type=\"text\" data-role=\"add-column-name\" placeholder=\"Column name\" maxlength=\"64\"\n                   class=\"w-36 rounded-lg border-slate-200 py-1 text-xs focus:border-brand-500 focus:ring-brand-500\">\n            <button type=\"submit\" class=\"rounded-lg bg-brand-600 px-2 py-1 text-xs font-medium text-white hover:bg-brand-700\">Add</button>\n            <button type=\"button\" data-role=\"add-column-cancel\" class=\"rounded-lg px-2 py-1 text-xs font-medium text-slate-600 hover:bg-slate-100\">Cancel</button>\n        </form>`;\n    const form = area.querySelector('[data-role=\"add-column-form\"]');\n    const input = area.querySelector('[data-role=\"add-column-name\"]');\n    const cancel = () => {\n        panel.addingColumn = false;\n        renderAddColumn();\n    };\n    form.addEventListener('submit', (event) => {\n        event.preventDefault();\n        try {\n            addDrawingField(panel.ctx, panel.entry, input.value);\n            panel.addingColumn = false;\n            renderAddColumn();\n        } catch (error) {\n            setColumnError(error.message);\n            input.focus();\n        }\n    });\n    input.addEventListener('input', () => setColumnError(''));\n    input.addEventListener('keydown', (event) => {\n        if (event.key === 'Escape') {\n            event.stopPropagation();\n            cancel();\n        }\n    });\n    area.querySelector('[data-role=\"add-column-cancel\"]').addEventListener('click', cancel);\n    input.focus();\n}\n\n/** P\u0159ejmenov\u00E1n\u00ED sloupce p\u0159\u00EDmo v hlavi\u010Dce (Enter potvrd\u00ED, Escape zru\u0161\u00ED). */\nfunction startColumnRename(name) {\n    const th = panelElement()?.querySelector(`th[data-column=\"${CSS.escape(name)}\"]`);\n    if (!th) return;\n    th.innerHTML = `<input type=\"text\" value=\"${htmlEscape(name)}\" maxlength=\"64\" aria-label=\"Column name\"\n        class=\"w-32 rounded border-brand-300 px-1 py-0.5 text-xs font-normal focus:border-brand-500 focus:ring-brand-500\">`;\n    const input = th.querySelector('input');\n    let done = false;\n    const finish = (commit) => {\n        if (done) return;\n        done = true;\n        if (commit && input.value.trim() !== name) {\n            const error = drawingFieldError(panel.entry, input.value, name);\n            if (error) {\n                setColumnError(error);\n            } else {\n                setColumnError('');\n                if (panel.sort?.attribute === name) panel.sort.attribute = input.value.trim();\n                renameDrawingField(panel.ctx, panel.entry, name, input.value);\n                return; // `drawing:changed` tabulku p\u0159ekresl\u00ED\n            }\n        }\n        loadPage();\n    };\n    input.addEventListener('blur', () => finish(true));\n    input.addEventListener('keydown', (event) => {\n        if (event.key === 'Enter') {\n            event.preventDefault();\n            finish(true);\n        } else if (event.key === 'Escape') {\n            event.stopPropagation();\n            finish(false);\n        }\n    });\n    input.focus();\n    input.select();\n}\n\n/** Odebere sloupec; kdy\u017E u\u017E nese hodnoty, zept\u00E1 se. */\nfunction removeColumn(name) {\n    const { entry, ctx } = panel;\n    const used = entry.olSource.getFeatures().filter((feature) => {\n        const value = feature.get(name);\n        return value !== undefined && value !== null && value !== '';\n    }).length;\n    if (used > 0) {\n        // eslint-disable-next-line no-alert -- jednoduch\u00E9 potvrzen\u00ED nevratn\u00E9 akce\n        const confirmed = window.confirm(`Remove the column \u201C${name}\u201D? Its values in ${used} feature${used === 1 ? '' : 's'} will be deleted.`);\n        if (!confirmed) return;\n    }\n    if (panel.sort?.attribute === name) panel.sort = null;\n    removeDrawingField(ctx, entry, name);\n}\n\n/* ---------------------------------------------------------------------------\n * Filtr (jen WFS)\n * ------------------------------------------------------------------------- */\n\n/** P\u0159ekresl\u00ED (schov\u00E1/zobraz\u00ED) oblast filter builderu. */\nfunction renderFilterArea() {\n    const area = panelElement()?.querySelector('[data-role=\"filter-area\"]');\n    if (!area) return;\n    const open = panel.filterOpen && panel.mode === 'wfs';\n    area.classList.toggle('hidden', !open);\n    if (!open) {\n        area.innerHTML = '';\n        return;\n    }\n    renderFilterBuilder(area, {\n        attributes: (activeSublayer()?.attributes || []).map((a) => a.name),\n        filter: panel.entry.filter,\n        onApply: (filter) => {\n            panel.entry.filter = filter;\n            onFilterChanged();\n        },\n        onClear: () => {\n            panel.entry.filter = null;\n            onFilterChanged();\n        },\n    });\n}\n\n/** Po zm\u011Bn\u011B filtru: obnovit mapu (SLD), badge ve stromu vrstev a tabulku. */\nfunction onFilterChanged() {\n    const { ctx, entry } = panel;\n    ctx.state.dirty = true;\n    scheduleWmsRefresh(entry);\n    renderLayerTree(ctx); // indikace aktivn\u00EDho filtru (badge) ve stromu\n    panel.page = 0;\n    renderFilterArea();\n    loadPage();\n}\n\n/* ---------------------------------------------------------------------------\n * Kostra panelu\n * ------------------------------------------------------------------------- */\n\n/** Postav\u00ED statickou kostru panelu (jednou p\u0159i otev\u0159en\u00ED) \u2014 hlavi\u010Dka s v\u00FDb\u011Brem\n * podvrstvy, hled\u00E1n\u00EDm a tla\u010D\u00EDtky, oblast filtru, t\u011Blo tabulky, stavov\u00E1 li\u0161ta. */\nfunction renderShell() {\n    const el = panelElement();\n    const { entry } = panel;\n    const wfs = panel.mode === 'wfs';\n    const sublayers = wfs ? (entry.sublayers || []) : [];\n    const sublayerSwitcher = sublayers.length > 1\n        ? `<select data-role=\"sublayer\" aria-label=\"Layer\" class=\"max-w-[12rem] rounded border-slate-200 py-1 text-xs focus:border-brand-500 focus:ring-brand-500\">\n            ${sublayers.map((s) => `<option value=\"${htmlEscape(s.name)}\" ${s.name === panel.typename ? 'selected' : ''}>${htmlEscape(s.name)}</option>`).join('')}\n           </select>`\n        : '';\n    const editableBadge = panel.editable\n        ? '<span class=\"rounded-full bg-emerald-50 px-2 py-0.5 text-[11px] font-medium text-emerald-700 ring-1 ring-inset ring-emerald-200\" title=\"Type into the cells to change values\">Editable</span>'\n        : '';\n    el.innerHTML = `\n        <div data-role=\"resize-handle\" class=\"absolute -top-1 left-0 z-10 h-2 w-full cursor-row-resize hover:bg-brand-500/30\"></div>\n        <div class=\"flex flex-none flex-wrap items-center gap-2 border-b border-slate-100 px-3 py-2\">\n            <span class=\"max-w-[16rem] truncate text-sm font-semibold text-slate-800\" title=\"${htmlEscape(entry.title)}\">${htmlEscape(entry.title)}</span>\n            ${editableBadge}\n            ${sublayerSwitcher}\n            <input type=\"search\" data-role=\"search\" placeholder=\"Search\u2026\" value=\"${htmlEscape(panel.searchText)}\"\n                   class=\"w-44 rounded-lg border-slate-200 py-1 text-xs focus:border-brand-500 focus:ring-brand-500\">\n            ${wfs ? `<button type=\"button\" data-role=\"toggle-filter\"\n                    class=\"inline-flex items-center gap-x-1 rounded-lg border border-slate-200 bg-white px-2 py-1 text-xs font-medium text-slate-700 shadow-sm hover:bg-slate-50\">\n                <svg class=\"h-3.5 w-3.5\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\"><path d=\"M22 3H2l8 9.5V19l4 2v-8.5L22 3z\"/></svg>\n                Filter\n            </button>` : ''}\n            <span data-role=\"add-column-area\"></span>\n            <div class=\"flex-1\"></div>\n            <button type=\"button\" data-role=\"close\" title=\"Close\" aria-label=\"Close attribute table\" class=\"rounded p-1 text-slate-400 hover:bg-slate-100 hover:text-slate-700\">\n                <svg class=\"h-4 w-4\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\"><path d=\"M18 6L6 18M6 6l12 12\"/></svg>\n            </button>\n        </div>\n        <p data-role=\"column-error\" class=\"hidden flex-none border-b border-red-100 bg-red-50 px-3 py-1.5 text-xs text-red-700\" role=\"alert\"></p>\n        <div data-role=\"filter-area\" class=\"hidden flex-none border-b border-slate-100 px-3 py-2\"></div>\n        <div data-role=\"table-body\" class=\"min-h-0 flex-1 overflow-auto\"></div>\n        <div data-role=\"table-status\" class=\"flex flex-none items-center justify-between gap-x-2 border-t border-slate-100 px-3 py-1.5 text-xs\"></div>`;\n\n    el.querySelector('[data-role=\"close\"]').addEventListener('click', () => closeAttrTable());\n    el.querySelector('[data-role=\"sublayer\"]')?.addEventListener('change', (e) => {\n        panel.typename = e.target.value;\n        panel.page = 0;\n        panel.sort = null;\n        clearHighlight();\n        renderFilterArea();\n        loadPage();\n    });\n    el.querySelector('[data-role=\"toggle-filter\"]')?.addEventListener('click', () => {\n        panel.filterOpen = !panel.filterOpen;\n        renderFilterArea();\n    });\n    // Debounce ~400 ms \u2014 u WFS se fulltext kombinuje AND s builder filtrem\n    // (jen tabulka, do mapy/SLD se hled\u00E1n\u00ED neprom\u00EDt\u00E1).\n    const onSearch = debounce(() => {\n        panel.page = 0;\n        loadPage();\n    }, panel.mode === 'local' ? 150 : 400);\n    el.querySelector('[data-role=\"search\"]').addEventListener('input', (e) => {\n        panel.searchText = e.target.value;\n        onSearch();\n    });\n\n    wireResizeHandle(el);\n    renderAddColumn();\n    renderFilterArea();\n}\n\n/** Ta\u017Een\u00ED za horn\u00ED hranu panelu m\u011Bn\u00ED jeho v\u00FD\u0161ku (mapa se p\u0159izp\u016Fsob\u00ED). */\nfunction wireResizeHandle(el) {\n    const handle = el.querySelector('[data-role=\"resize-handle\"]');\n    let startY = 0;\n    let startHeight = 0;\n    const onMove = (e) => {\n        const height = Math.max(120, Math.min(window.innerHeight * 0.8, startHeight + (startY - e.clientY)));\n        el.style.height = `${height}px`;\n        panel.ctx.map.updateSize();\n    };\n    const onUp = () => {\n        document.removeEventListener('pointermove', onMove);\n        document.removeEventListener('pointerup', onUp);\n        document.body.classList.remove('cursor-row-resize', 'select-none');\n    };\n    // Pointer ud\u00E1losti \u2014 ta\u017Een\u00ED funguje my\u0161\u00ED i prstem.\n    handle.addEventListener('pointerdown', (e) => {\n        e.preventDefault();\n        startY = e.clientY;\n        startHeight = el.offsetHeight;\n        document.addEventListener('pointermove', onMove);\n        document.addEventListener('pointerup', onUp);\n        document.body.classList.add('cursor-row-resize', 'select-none');\n    });\n}\n\n/* ---------------------------------------------------------------------------\n * Otev\u0159en\u00ED/zav\u0159en\u00ED + integrace (identify, odebr\u00E1n\u00ED vrstvy, Escape)\n * ------------------------------------------------------------------------- */\n\nfunction isOpenFor(uid) {\n    return panel.entry?.uid === uid && !panelElement()?.classList.contains('hidden');\n}\n\n/** Otev\u0159e panel tabulky pro danou vrstvu (existuj\u00EDc\u00ED panel nahrad\u00ED).\n * `focusFeatureId` = prvek, na kter\u00FD se m\u00E1 tabulka zam\u011B\u0159it (z popupu). */\nexport function openAttrTable(ctx, uid, { focusFeatureId = null } = {}) {\n    const entry = findEntryByUid(ctx.state, uid);\n    if (!hasAttributeTable(entry)) return;\n    clearHighlight();\n    const local = entry.dataType === 'drawing' || entry.dataType === 'local';\n    panel.ctx = ctx;\n    panel.entry = entry;\n    panel.mode = local ? 'local' : 'wfs';\n    panel.editable = entry.dataType === 'drawing';\n    panel.typename = local ? null : (entry.sublayers?.[0]?.name || null);\n    panel.page = 0;\n    panel.total = null;\n    panel.features = [];\n    panel.columns = [];\n    panel.sort = null;\n    panel.searchText = '';\n    panel.filterOpen = false;\n    panel.addingColumn = false;\n    panel.error = null;\n    panel.focusId = focusFeatureId;\n    panel.query = null;\n    panel.attributesOnly = new Set();\n    panel.geometryNote = null;\n\n    const el = panelElement();\n    el.style.height = '40vh'; // v\u00FDchoz\u00ED v\u00FD\u0161ka ~40 % okna\n    el.classList.remove('hidden');\n    el.classList.add('flex');\n    renderShell();\n    ctx.map.updateSize();\n    loadPage();\n}\n\n/** Zav\u0159e panel tabulky a uklid\u00ED zv\u00FDrazn\u011Bn\u00ED. */\nexport function closeAttrTable() {\n    clearHighlight();\n    const el = panelElement();\n    if (el) {\n        el.classList.add('hidden');\n        el.classList.remove('flex');\n        el.innerHTML = '';\n    }\n    panel.ctx?.map.updateSize();\n    panel.entry = null;\n    panel.typename = null;\n    panel.features = [];\n}\n\n/** Reakce na identify klik do mapy: pokud je otev\u0159en\u00E1 tabulka t\u00E9\u017Ee vrstvy a\n * prvek je na aktu\u00E1ln\u00ED str\u00E1nce, zv\u00FDrazn\u00ED \u0159\u00E1dek a odscrolluje na n\u011Bj; jinak\n * jen zv\u00FDrazn\u00ED prvek na map\u011B (dal\u0161\u00ED str\u00E1nky se nena\u010D\u00EDtaj\u00ED). */\nfunction onIdentifyFeature({ itemId, uid, featureId, feature }) {\n    if (!panel.entry) return;\n    const sameLayer = uid ? panel.entry.uid === uid : panel.entry.itemId === itemId;\n    if (!sameLayer) return;\n    const row = panel.features.find((f) => f.id === String(featureId));\n    if (row) {\n        selectRow(row, { scroll: true });\n    } else if (feature?.geometry) {\n        // Prvek nen\u00ED na aktu\u00E1ln\u00ED str\u00E1nce \u2014 zv\u00FDrazn\u00EDme aspo\u0148 na map\u011B\n        // (geometrie z GetFeatureInfo je v projekci mapy, EPSG:3857).\n        panel.highlightId = featureId;\n        highlightOnMap(panel.ctx, { geometry: feature.geometry });\n        updateRowHighlight();\n    }\n}\n\n/** Jednor\u00E1zov\u00E1 inicializace (main.js) \u2014 event bus + kl\u00E1vesa Escape. */\nexport function initAttrTable(ctx) {\n    panel.ctx = ctx;\n    on('layers:open-attr-table', ({ uid, focusFeatureId = null, keepOpen = false }) => {\n        if (isOpenFor(uid)) {\n            if (!keepOpen) {\n                // Opakovan\u00E9 kliknut\u00ED na polo\u017Eku menu t\u00E9\u017Ee vrstvy panel zav\u0159e.\n                closeAttrTable();\n                return;\n            }\n            // Z popupu: tabulka u\u017E je otev\u0159en\u00E1 \u2014 jen p\u0159ej\u00EDt na dan\u00FD prvek.\n            panel.focusId = focusFeatureId;\n            loadPage();\n            return;\n        }\n        openAttrTable(ctx, uid, { focusFeatureId });\n    });\n    on('layers:changed', ({ reason, entry }) => {\n        if (!panel.entry || !entry || entry.uid !== panel.entry.uid) return;\n        if (reason === 'remove') {\n            // Odebr\u00E1n\u00ED vrstvy zav\u0159e jej\u00ED tabulku a odstran\u00ED zv\u00FDrazn\u011Bn\u00ED.\n            closeAttrTable();\n        } else if (reason === 'rename') {\n            const title = panelElement()?.querySelector('span.font-semibold');\n            if (title) {\n                title.textContent = entry.title;\n                title.title = entry.title;\n            }\n        }\n    });\n    on('layers:filter-cleared', ({ entry }) => {\n        // \"Clear filter\" ze stromu vrstev \u2014 obnovit otev\u0159enou tabulku t\u00E9\u017Ee vrstvy.\n        if (panel.entry && entry.uid === panel.entry.uid) {\n            panel.page = 0;\n            renderFilterArea();\n            loadPage();\n        }\n    });\n    // Kresba se zm\u011Bnila (nov\u00FD/smazan\u00FD/upraven\u00FD prvek, sloupce) \u2014 obnovit\n    // otev\u0159enou tabulku. Vlastn\u00ED z\u00E1pis z bu\u0148ky tabulku nep\u0159ekresluje.\n    const reloadDrawing = debounce(() => {\n        if (panel.entry && panel.mode === 'local') loadPage();\n    }, 80);\n    on('drawing:changed', ({ entry }) => {\n        if (panel.selfEdit || !panel.entry || entry?.uid !== panel.entry.uid) return;\n        // P\u0159i psan\u00ED do bu\u0148ky nep\u0159ekreslovat pod rukama (jen geometrie se m\u011Bn\u00ED).\n        const active = document.activeElement;\n        if (active?.dataset?.role === 'cell' && panelElement()?.contains(active)) return;\n        reloadDrawing();\n    });\n    on('identify:feature', onIdentifyFeature);\n    document.addEventListener('keydown', (e) => {\n        if (e.key === 'Escape') clearHighlight();\n    });\n}\n", "/**\n * measure.js \u2014 m\u011B\u0159en\u00ED vzd\u00E1lenost\u00ED (LineString) a ploch (Polygon) na map\u011B.\n *\n * - OL `Draw` interakce + \u017Eiv\u00FD tooltip s pr\u016Fb\u011B\u017Enou hodnotou (ol/sphere).\n * - N\u00E1stroj je JEDNOR\u00C1ZOV\u00DD: po dokon\u010Den\u00ED jednoho m\u011B\u0159en\u00ED se s\u00E1m vypne a mapa se\n *   vr\u00E1t\u00ED do b\u011B\u017En\u00E9ho re\u017Eimu (klik = identify). N\u00E1\u010Drt i \u0161t\u00EDtek s hodnotou na\n *   map\u011B z\u016Fst\u00E1vaj\u00ED, dokud je u\u017Eivatel neodstran\u00ED (k\u0159\u00ED\u017Eek u \u0161t\u00EDtku, nebo\n *   \"Clear measurements\"). Dal\u0161\u00ED m\u011B\u0159en\u00ED = znovu zvolit n\u00E1stroj.\n * - Po dobu m\u011B\u0159en\u00ED je nad mapou li\u0161ta s n\u00E1pov\u011Bdou a tla\u010D\u00EDtky Finish/Cancel\n *   (Finish je nutn\u00FD hlavn\u011B na dotykov\u00FDch za\u0159\u00EDzen\u00EDch, kde je dvojit\u00E9 klepnut\u00ED\n *   nepohodln\u00E9). Escape m\u011B\u0159en\u00ED zru\u0161\u00ED.\n * - M\u011B\u0159en\u00ED je \u010Dist\u011B klientsk\u00E9 \u2014 NEukl\u00E1d\u00E1 se do Map.config.\n */\nimport Draw from 'ol/interaction/Draw.js';\nimport Overlay from 'ol/Overlay.js';\nimport VectorLayer from 'ol/layer/Vector.js';\nimport VectorSource from 'ol/source/Vector.js';\nimport Style from 'ol/style/Style.js';\nimport Stroke from 'ol/style/Stroke.js';\nimport Fill from 'ol/style/Fill.js';\nimport CircleStyle from 'ol/style/Circle.js';\nimport { getArea, getLength } from 'ol/sphere.js';\nimport { unByKey } from 'ol/Observable.js';\nimport { emit } from './utils.js';\n\n/** Jak dlouho po dokon\u010Den\u00ED m\u011B\u0159en\u00ED je\u0161t\u011B dr\u017E\u00EDme potla\u010Den\u00FD identify a zoom\n * dvojklikem: posledn\u00ED klik (resp. dvojklik) pat\u0159\u00ED m\u011B\u0159en\u00ED, ne map\u011B. */\nconst FINISH_GUARD_MS = 350;\n\n/** Styl n\u00E1\u010Drt\u016F m\u011B\u0159en\u00ED \u2014 v\u00FDrazn\u00E1 oran\u017Eov\u00E1, aby se odli\u0161ila od dat i kresby. */\nfunction measureStyle() {\n    return new Style({\n        fill: new Fill({ color: 'rgba(249, 115, 22, 0.15)' }),\n        stroke: new Stroke({ color: '#f97316', width: 2, lineDash: [6, 6] }),\n        image: new CircleStyle({\n            radius: 4,\n            fill: new Fill({ color: '#f97316' }),\n            stroke: new Stroke({ color: '#ffffff', width: 1.5 }),\n        }),\n    });\n}\n\n/** Naform\u00E1tuje d\u00E9lku: do 1 km v metrech, jinak v kilometrech. */\nexport function formatLength(meters) {\n    if (meters < 1000) return `${meters.toFixed(1)} m`;\n    return `${(meters / 1000).toFixed(2)} km`;\n}\n\n/** Naform\u00E1tuje plochu: m\u00B2 \u2192 ha \u2192 km\u00B2 podle \u0159\u00E1du hodnoty. */\nexport function formatArea(squareMeters) {\n    if (squareMeters < 10000) return `${squareMeters.toFixed(1)} m\u00B2`;\n    if (squareMeters < 1000000) return `${(squareMeters / 10000).toFixed(2)} ha`;\n    return `${(squareMeters / 1000000).toFixed(2)} km\u00B2`;\n}\n\nconst TOOL_LABELS = {\n    distance: 'Measure distance',\n    area: 'Measure area',\n};\n\n/** Dotykov\u00E9 za\u0159\u00EDzen\u00ED (bez my\u0161i) \u2014 jin\u00E1 formulace n\u00E1pov\u011Bdy. */\nfunction isTouchDevice() {\n    return window.matchMedia?.('(pointer: coarse)').matches || false;\n}\n\n/**\n * Inicializuje m\u011B\u0159en\u00ED nad mapou. Vrac\u00ED API pro horn\u00ED li\u0161tu:\n * `{ activate(type), deactivate(), clear(), getActiveType(), hasMeasurements() }`,\n * kde `type` je 'distance' | 'area'.\n */\nexport function initMeasure(ctx) {\n    const source = new VectorSource();\n    const layer = new VectorLayer({\n        source,\n        style: measureStyle(),\n        zIndex: 900, // nad WMS vrstvami i kresbou, pod zv\u00FDrazn\u011Bn\u00EDm identify\n        properties: { role: 'measure' },\n    });\n    ctx.map.addLayer(layer);\n\n    let draw = null;            // aktivn\u00ED Draw interakce\n    let activeType = null;      // 'distance' | 'area' | null\n    let liveTooltip = null;     // Overlay s pr\u016Fb\u011B\u017Enou hodnotou\n    let sketchListener = null;  // listener zm\u011Bn geometrie n\u00E1\u010Drtu\n    let sketchFeature = null;   // rozkreslen\u00FD prvek (kv\u016Fli tla\u010D\u00EDtku Finish)\n    let guardTimer = null;      // dob\u011Bh potla\u010Den\u00ED identify po dokon\u010Den\u00ED\n    let hintEl = null;          // li\u0161ta s n\u00E1pov\u011Bdou nad mapou\n    const measurements = [];    // hotov\u00E1 m\u011B\u0159en\u00ED: { feature, overlay }\n\n    /* -- Li\u0161ta s n\u00E1pov\u011Bdou ------------------------------------------------ */\n\n    function hintText(type) {\n        const touch = isTouchDevice();\n        if (type === 'area') {\n            return touch\n                ? 'Tap to add corners, then tap Finish.'\n                : 'Click to add corners, double-click to finish.';\n        }\n        return touch\n            ? 'Tap to add points, then tap Finish.'\n            : 'Click to add points, double-click to finish.';\n    }\n\n    /** M\u00E1 rozkreslen\u00FD n\u00E1\u010Drt dost bod\u016F, aby \u0161el dokon\u010Dit? */\n    function canFinish() {\n        const geometry = sketchFeature?.getGeometry();\n        if (!geometry) return false;\n        if (geometry.getType() === 'Polygon') {\n            // Uzav\u0159en\u00FD prstenec rozkreslen\u00E9ho polygonu obsahuje i pohybliv\u00FD bod.\n            return (geometry.getCoordinates()[0] || []).length >= 4;\n        }\n        return geometry.getCoordinates().length >= 3;\n    }\n\n    function updateHint() {\n        const finishBtn = hintEl?.querySelector('[data-role=\"measure-finish\"]');\n        if (finishBtn) finishBtn.disabled = !canFinish();\n    }\n\n    function showHint(type) {\n        hideHint();\n        hintEl = document.createElement('div');\n        hintEl.className = 'map-tool-hint';\n        hintEl.setAttribute('role', 'status');\n        hintEl.innerHTML = `\n            <svg class=\"h-4 w-4 flex-none text-orange-500\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" aria-hidden=\"true\"><path d=\"m3 21 18-18M7 17l1.5 1.5M10.5 13.5 12 15M14 10l1.5 1.5M17.5 6.5 19 8\"/></svg>\n            <span class=\"min-w-0\">\n                <span class=\"font-semibold text-slate-800\">${TOOL_LABELS[type]}</span>\n                <span class=\"hidden text-slate-500 sm:inline\"> \u2014 ${hintText(type)}</span>\n            </span>\n            <button type=\"button\" data-role=\"measure-finish\" disabled\n                    class=\"flex-none rounded-md bg-brand-600 px-2 py-1 text-xs font-medium text-white hover:bg-brand-700 disabled:cursor-not-allowed disabled:opacity-40\">Finish</button>\n            <button type=\"button\" data-role=\"measure-cancel\"\n                    class=\"flex-none rounded-md px-2 py-1 text-xs font-medium text-slate-600 hover:bg-slate-100\">Cancel</button>`;\n        hintEl.querySelector('[data-role=\"measure-finish\"]').addEventListener('click', () => {\n            if (draw && canFinish()) draw.finishDrawing();\n        });\n        hintEl.querySelector('[data-role=\"measure-cancel\"]').addEventListener('click', cancel);\n        (ctx.elements.mapTarget?.parentElement || document.body).appendChild(hintEl);\n    }\n\n    function hideHint() {\n        hintEl?.remove();\n        hintEl = null;\n    }\n\n    /* -- Tooltipy ---------------------------------------------------------- */\n\n    function createLiveTooltip() {\n        const el = document.createElement('div');\n        el.className = 'map-measure-tooltip map-measure-tooltip-live';\n        const overlay = new Overlay({\n            element: el,\n            offset: [0, -10],\n            positioning: 'bottom-center',\n            stopEvent: false,\n        });\n        ctx.map.addOverlay(overlay);\n        return overlay;\n    }\n\n    function removeLiveTooltip() {\n        if (liveTooltip) {\n            ctx.map.removeOverlay(liveTooltip);\n            liveTooltip = null;\n        }\n    }\n\n    /** Odstran\u00ED jedno hotov\u00E9 m\u011B\u0159en\u00ED (n\u00E1\u010Drt i \u0161t\u00EDtek). */\n    function removeMeasurement(record) {\n        const index = measurements.indexOf(record);\n        if (index === -1) return;\n        measurements.splice(index, 1);\n        if (source.hasFeature(record.feature)) source.removeFeature(record.feature);\n        ctx.map.removeOverlay(record.overlay);\n        emit('measure:changed', { count: measurements.length });\n    }\n\n    /** Statick\u00FD \u0161t\u00EDtek hotov\u00E9ho m\u011B\u0159en\u00ED: hodnota + k\u0159\u00ED\u017Eek pro odstran\u011Bn\u00ED. */\n    function addStaticLabel(feature, text, position) {\n        const el = document.createElement('div');\n        el.className = 'map-measure-tooltip map-measure-tooltip-static';\n        const value = document.createElement('span');\n        value.textContent = text;\n        const remove = document.createElement('button');\n        remove.type = 'button';\n        remove.title = 'Remove this measurement';\n        remove.setAttribute('aria-label', 'Remove this measurement');\n        remove.innerHTML = '<svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2.5\" stroke-linecap=\"round\"><path d=\"M18 6 6 18M6 6l12 12\"/></svg>';\n        el.append(value, remove);\n        // `stopEvent: true` \u2014 klik na k\u0159\u00ED\u017Eek nesm\u00ED propadnout do mapy (identify).\n        const overlay = new Overlay({\n            element: el,\n            offset: [0, -7],\n            positioning: 'bottom-center',\n            stopEvent: true,\n        });\n        ctx.map.addOverlay(overlay);\n        overlay.setPosition(position);\n        const record = { feature, overlay };\n        remove.addEventListener('click', () => removeMeasurement(record));\n        measurements.push(record);\n        emit('measure:changed', { count: measurements.length });\n    }\n\n    /* -- \u017Divotn\u00ED cyklus n\u00E1stroje ------------------------------------------ */\n\n    function releaseMap() {\n        ctx.mapToolActive = false;\n        guardTimer = null;\n    }\n\n    /** Ukon\u010D\u00ED aktivn\u00ED re\u017Eim m\u011B\u0159en\u00ED (interakce + rozkreslen\u00FD n\u00E1\u010Drt). Hotov\u00E1\n     * m\u011B\u0159en\u00ED z\u016Fst\u00E1vaj\u00ED. `guard` = kr\u00E1tce podr\u017Eet potla\u010Den\u00ED identify (posledn\u00ED\n     * klik dokon\u010Den\u00E9ho m\u011B\u0159en\u00ED nesm\u00ED spustit identify ani zoom dvojklikem). */\n    function deactivate({ guard = false } = {}) {\n        if (draw) {\n            ctx.map.removeInteraction(draw);\n            draw = null;\n        }\n        if (sketchListener) {\n            unByKey(sketchListener);\n            sketchListener = null;\n        }\n        sketchFeature = null;\n        removeLiveTooltip();\n        hideHint();\n        const wasActive = Boolean(activeType);\n        activeType = null;\n        clearTimeout(guardTimer);\n        if (guard) {\n            // Dvojklik, kter\u00FDm se m\u011B\u0159en\u00ED dokon\u010Duje, by po odebr\u00E1n\u00ED interakce\n            // propadl do DoubleClickZoom \u2014 po dobu ochrann\u00E9 lh\u016Fty ho spolkneme\n            // (listener mapy vracej\u00EDc\u00ED false zastav\u00ED p\u0159ed\u00E1n\u00ED interakc\u00EDm).\n            const dblKey = ctx.map.on('dblclick', () => false);\n            guardTimer = setTimeout(() => {\n                unByKey(dblKey);\n                releaseMap();\n            }, FINISH_GUARD_MS);\n        } else {\n            releaseMap();\n        }\n        if (wasActive) emit('measure:tool', { type: null });\n    }\n\n    /** Zru\u0161\u00ED rozkreslen\u00E9 m\u011B\u0159en\u00ED a vypne n\u00E1stroj (tla\u010D\u00EDtko Cancel, Escape). */\n    function cancel() {\n        if (draw) {\n            try {\n                draw.abortDrawing();\n            } catch {\n                /* \u017E\u00E1dn\u00FD rozkreslen\u00FD n\u00E1\u010Drt */\n            }\n        }\n        deactivate();\n    }\n\n    /** Aktivuje m\u011B\u0159en\u00ED dan\u00E9ho typu; opakovan\u00E1 aktivace stejn\u00E9ho typu ho vypne. */\n    function activate(type) {\n        if (activeType === type) {\n            cancel();\n            return;\n        }\n        deactivate();\n        activeType = type;\n        ctx.mapToolActive = true; // potla\u010D\u00ED identify klik (viz identify.js)\n\n        draw = new Draw({\n            source,\n            type: type === 'area' ? 'Polygon' : 'LineString',\n            style: measureStyle(),\n        });\n        ctx.map.addInteraction(draw);\n        showHint(type);\n        emit('measure:tool', { type });\n\n        draw.on('drawstart', (event) => {\n            liveTooltip = createLiveTooltip();\n            sketchFeature = event.feature;\n            const geometry = event.feature.getGeometry();\n            sketchListener = geometry.on('change', () => {\n                let text;\n                let anchor;\n                if (type === 'area') {\n                    text = formatArea(getArea(geometry));\n                    anchor = geometry.getInteriorPoint().getCoordinates();\n                } else {\n                    text = formatLength(getLength(geometry));\n                    anchor = geometry.getLastCoordinate();\n                }\n                liveTooltip.getElement().textContent = text;\n                liveTooltip.setPosition(anchor);\n                updateHint();\n            });\n        });\n\n        draw.on('drawend', (event) => {\n            // \u017Div\u00FD tooltip nahrad\u00ED statick\u00FD \u0161t\u00EDtek u geometrie; n\u00E1stroj se po\n            // jednom m\u011B\u0159en\u00ED s\u00E1m vypne (mapa je zase \u201Eklikac\u00ED\u201C).\n            const geometry = event.feature.getGeometry();\n            const isArea = type === 'area';\n            const text = isArea ? formatArea(getArea(geometry)) : formatLength(getLength(geometry));\n            const anchor = isArea\n                ? geometry.getInteriorPoint().getCoordinates()\n                : geometry.getLastCoordinate();\n            addStaticLabel(event.feature, text, anchor);\n            deactivate({ guard: true });\n        });\n\n        draw.on('drawabort', () => {\n            removeLiveTooltip();\n            sketchFeature = null;\n            if (sketchListener) {\n                unByKey(sketchListener);\n                sketchListener = null;\n            }\n            updateHint();\n        });\n    }\n\n    /** Odstran\u00ED v\u0161echny n\u00E1\u010Drty m\u011B\u0159en\u00ED i jejich \u0161t\u00EDtky. */\n    function clear() {\n        cancel();\n        source.clear();\n        measurements.forEach((record) => ctx.map.removeOverlay(record.overlay));\n        measurements.length = 0;\n        emit('measure:changed', { count: 0 });\n    }\n\n    // Escape: zru\u0161\u00ED rozkreslen\u00FD n\u00E1\u010Drt i cel\u00FD re\u017Eim m\u011B\u0159en\u00ED.\n    document.addEventListener('keydown', (event) => {\n        if (event.key !== 'Escape' || !activeType) return;\n        cancel();\n    });\n\n    return {\n        activate,\n        deactivate: cancel,\n        clear,\n        getActiveType: () => activeType,\n        hasMeasurements: () => measurements.length > 0,\n    };\n}\n", "/**\n * export.js \u2014 export aktu\u00E1ln\u00EDho v\u00FD\u0159ezu mapy do PNG/JPEG.\n *\n * Postup dle OL dokumentace (map export example): po `rendercomplete` se\n * canvasy jednotliv\u00FDch vrstev slo\u017E\u00ED do jednoho v\u00FDsledn\u00E9ho canvasu (respektuje\n * se opacity i CSS transform) a st\u00E1hne se jako soubor `<map-title>.png/jpg`.\n * Basemapy i WMS zdroje maj\u00ED `crossOrigin: 'anonymous'`, tak\u017Ee canvas nen\u00ED\n * \"tainted\" a `toDataURL` funguje.\n */\n\n/** Bezpe\u010Dn\u00FD n\u00E1zev souboru z n\u00E1zvu mapy.\n *\n * Zachov\u00E1v\u00E1 diakritiku i nelatinkov\u00E1 p\u00EDsma (Unicode-safe, ve stejn\u00E9m duchu jako\n * `apps.storage.sanitize_filename`) \u2014 odstran\u00ED jen znaky, kter\u00E9 d\u011Blaj\u00ED probl\u00E9m\n * v n\u00E1zvu souboru (odd\u011Blova\u010De cest, \u0159\u00EDdic\u00ED a filesystem-neleg\u00E1ln\u00ED znaky) a\n * krajn\u00ED te\u010Dky. D\u0159\u00EDv\u011Bj\u0161\u00ED `[^\\w.-]` variant\u011B u \u010Dist\u011B diakritick\u00FDch n\u00E1zv\u016F\n * nezbylo nic \u2192 zbyte\u010Dn\u011B obecn\u00FD \u201Emap\u201C. */\nfunction safeFilename(title, extension) {\n    const cleaned = (title || 'map')\n        .normalize('NFC')\n        // Odd\u011Blova\u010De cest, \u0159\u00EDdic\u00ED znaky a znaky neleg\u00E1ln\u00ED v n\u00E1zvech soubor\u016F.\n        .replace(/[\\\\/:*?\"<>|\\u0000-\\u001f]+/g, '_')\n        .replace(/\\s+/g, ' ')\n        .trim()\n        .replace(/^\\.+|\\.+$/g, '')\n        .slice(0, 120)\n        .trim() || 'map';\n    return `${cleaned}.${extension}`;\n}\n\n/** St\u00E1hne obsah canvasu jako soubor.\n *\n * Preferuje `canvas.toBlob()` + object URL: `toDataURL` toti\u017E vytv\u00E1\u0159\u00ED ob\u0159\u00ED\n * base64 \u0159et\u011Bzec, kter\u00FD u v\u011Bt\u0161\u00EDch map (retina/velk\u00E9 okno) n\u011Bkter\u00E9 prohl\u00ED\u017Ee\u010De\n * jako `href` odkazu ke sta\u017Een\u00ED ti\u0161e odm\u00EDtnou \u2014 u\u017Eivatel pak vid\u00ED, \u017Ee \u201Ese po\n * kliknut\u00ED nic nestalo\u201C. Vrac\u00ED Promise (kv\u016Fli chybov\u00E9 hl\u00E1\u0161ce volaj\u00EDc\u00EDho).\n */\nfunction downloadCanvas(canvas, filename, mime, quality) {\n    return new Promise((resolve, reject) => {\n        const trigger = (href, revoke) => {\n            const link = document.createElement('a');\n            link.href = href;\n            link.download = filename;\n            document.body.appendChild(link);\n            link.click();\n            link.remove();\n            if (revoke) window.setTimeout(() => URL.revokeObjectURL(href), 1000);\n            resolve();\n        };\n        try {\n            if (canvas.toBlob) {\n                canvas.toBlob(\n                    (blob) => {\n                        if (!blob) {\n                            reject(new Error('Failed to render image.'));\n                            return;\n                        }\n                        trigger(URL.createObjectURL(blob), true);\n                    },\n                    mime,\n                    quality,\n                );\n            } else {\n                trigger(canvas.toDataURL(mime, quality), false);\n            }\n        } catch (error) {\n            // Typicky SecurityError (tainted canvas) u zdroje bez CORS hlavi\u010Dek.\n            reject(error);\n        }\n    });\n}\n\n/** Slo\u017E\u00ED canvasy vrstev mapy do jednoho canvasu (velikost = aktu\u00E1ln\u00ED okno).\n * Exportov\u00E1no i pro generov\u00E1n\u00ED n\u00E1hledu mapy do galerie (persist.js), aby n\u00E1hled\n * odpov\u00EDdal exportu a spolehliv\u011B obsahoval v\u0161echny vrstvy (ne jen prvn\u00ED canvas). */\nexport function composeMapCanvas(map, backgroundColor) {\n    const size = map.getSize();\n    // Mapa bez rozm\u011Bru (je\u0161t\u011B nezm\u011B\u0159en\u00E1 / skryt\u00E9 okno) \u2014 nelze slo\u017Eit obr\u00E1zek.\n    if (!size || !size[0] || !size[1]) return null;\n    const canvas = document.createElement('canvas');\n    canvas.width = size[0];\n    canvas.height = size[1];\n    const context = canvas.getContext('2d');\n    if (backgroundColor) {\n        // JPEG pr\u016Fhlednost neum\u00ED \u2014 podlije se b\u00EDlou.\n        context.fillStyle = backgroundColor;\n        context.fillRect(0, 0, canvas.width, canvas.height);\n    }\n    const canvases = map.getViewport().querySelectorAll('.ol-layer canvas, canvas.ol-layer');\n    canvases.forEach((layerCanvas) => {\n        if (layerCanvas.width === 0) return;\n        const parent = layerCanvas.parentNode;\n        const opacity = parent?.style?.opacity || layerCanvas.style.opacity;\n        context.globalAlpha = opacity === '' ? 1 : Number(opacity);\n        // P\u0159evezmi CSS transform canvasu vrstvy (posun/\u0161k\u00E1lov\u00E1n\u00ED p\u0159i ratio > 1).\n        const transform = layerCanvas.style.transform;\n        const match = transform ? /^matrix\\(([^(]*)\\)$/.exec(transform) : null;\n        if (match) {\n            const matrix = match[1].split(',').map(Number);\n            context.setTransform(...matrix);\n        } else {\n            context.setTransform(1, 0, 0, 1, 0, 0);\n        }\n        const filter = parent?.style?.filter;\n        context.filter = filter || 'none';\n        context.drawImage(layerCanvas, 0, 0);\n    });\n    context.globalAlpha = 1;\n    context.filter = 'none';\n    context.setTransform(1, 0, 0, 1, 0, 0);\n    return canvas;\n}\n\n/**\n * Vyrenderuje aktu\u00E1ln\u00ED v\u00FD\u0159ez mapy a st\u00E1hne ho jako PNG nebo JPEG.\n * `format` je 'png' | 'jpg'. Vrac\u00ED promise (kv\u016Fli chybov\u00E9 hl\u00E1\u0161ce volaj\u00EDc\u00EDho).\n */\nexport function exportMapImage(ctx, format = 'png') {\n    const isJpeg = format === 'jpg' || format === 'jpeg';\n    return new Promise((resolve, reject) => {\n        ctx.map.once('rendercomplete', () => {\n            try {\n                const canvas = composeMapCanvas(ctx.map, isJpeg ? '#ffffff' : null);\n                if (!canvas) {\n                    reject(new Error('Map is not ready to export.'));\n                    return;\n                }\n                const mime = isJpeg ? 'image/jpeg' : 'image/png';\n                const filename = safeFilename(ctx.state.title, isJpeg ? 'jpg' : 'png');\n                downloadCanvas(canvas, filename, mime, isJpeg ? 0.9 : undefined)\n                    .then(resolve)\n                    .catch(reject);\n            } catch (error) {\n                // Typicky SecurityError (tainted canvas) u zdroje bez CORS hlavi\u010Dek.\n                reject(error);\n            }\n        });\n        ctx.map.renderSync();\n    });\n}\n", "/**\n * present.js \u2014 prezenta\u010Dn\u00ED re\u017Eim: skryje horn\u00ED li\u0161tu, lev\u00FD panel i atributovou\n * tabulku a rozt\u00E1hne mapu p\u0159es celou obrazovku (Fullscreen API s CSS\n * fallbackem). Ovl\u00E1dac\u00ED prvky mapy (zoom, m\u011B\u0159\u00EDtko, sou\u0159adnice) z\u016Fst\u00E1vaj\u00ED.\n *\n * Ukon\u010Den\u00ED: Escape (nativn\u011B ukon\u010D\u00ED fullscreen \u2192 hl\u00EDd\u00E1me `fullscreenchange`),\n * plovouc\u00ED tla\u010D\u00EDtko na map\u011B, nebo Escape v CSS fallbacku.\n */\n\nconst PRESENT_CLASS = 'map-presenting';\n\nexport function initPresentMode(ctx, { button, exitButton }) {\n    let active = false;\n\n    function apply() {\n        document.body.classList.toggle(PRESENT_CLASS, active);\n        exitButton?.classList.toggle('hidden', !active);\n        // Po zm\u011Bn\u011B layoutu si mapa mus\u00ED p\u0159epo\u010D\u00EDtat velikost.\n        setTimeout(() => ctx.map.updateSize(), 50);\n    }\n\n    function enter() {\n        if (active) return;\n        active = true;\n        // Fullscreen API \u2014 pokud sel\u017Ee (nap\u0159. iOS Safari), z\u016Fstane CSS fallback.\n        document.documentElement.requestFullscreen?.().catch(() => {\n            /* fallback: jen skryt\u00ED panel\u016F p\u0159es CSS t\u0159\u00EDdu */\n        });\n        apply();\n    }\n\n    function exit() {\n        if (!active) return;\n        active = false;\n        if (document.fullscreenElement) {\n            document.exitFullscreen?.().catch(() => {\n                /* fullscreen u\u017E mohl skon\u010Dit jinak */\n            });\n        }\n        apply();\n    }\n\n    // Escape v nativn\u00EDm fullscreenu vyvol\u00E1 jen `fullscreenchange` (bez keydown).\n    document.addEventListener('fullscreenchange', () => {\n        if (!document.fullscreenElement && active) exit();\n    });\n\n    // Escape pro CSS fallback (kdy\u017E fullscreen nen\u00ED aktivn\u00ED).\n    document.addEventListener('keydown', (event) => {\n        if (event.key === 'Escape' && active && !document.fullscreenElement) exit();\n    });\n\n    button?.addEventListener('click', enter);\n    exitButton?.addEventListener('click', exit);\n\n    return { enter, exit, isActive: () => active };\n}\n", "/**\n * render-spec.js \u2014 jak viewer kresl\u00ED vrstvy mapy, pro mapovou slu\u017Ebu (WMS).\n *\n * S ka\u017Ed\u00FDm ulo\u017Een\u00EDm mapy jde na server `render` (ulo\u017E\u00ED se do `Map.render_spec`):\n * strom skupin a vrstev v po\u0159ad\u00ED stromu (naho\u0159e prvn\u00ED) a u ka\u017Ed\u00E9 vrstvy z Data\n * workspace parametry Mapserveru, se kter\u00FDmi ji viewer kresl\u00ED \u2014 SLD ze stylu,\n * filtr, nastaven\u00ED rastru (`buildWmsParams`, bez podpisu a souboru, ty dopln\u00ED\n * server). Z toho server slo\u017E\u00ED zve\u0159ejn\u011Bnou mapu (`apps/maps/publishing.py`).\n *\n * Kresba a vlo\u017Een\u00E1 data (`local`) nesou jen cestu do `Map.config`\n * (`[i]` / `[i, j]`), odkud server vezme jejich GeoJSON; vrstvy z ciz\u00EDch slu\u017Eeb\n * (WMS, XYZ, WMTS) jen n\u00E1zev \u2014 ve slu\u017Eb\u011B nebudou a dialog je vyjmenuje.\n *\n * Modul je bez OpenLayers: parametry vrstvy dod\u00E1 `paramsFor` (testy).\n */\n\n/** Parametry vrstvy, kter\u00E9 do slu\u017Eby nepat\u0159\u00ED (podpis, soubor, form\u00E1t obr\u00E1zku). */\nconst DROPPED_PARAMS = new Set(['FILE_URL', 'sig', 'PAYER', 'FILE_CRS', 'TRANSPARENT', 'FORMAT']);\nconst EXTERNAL_TYPES = new Set(['wms', 'xyz', 'wmts']);\n\nfunction zoom(value) {\n    return Number.isFinite(value) ? value : null;\n}\n\nfunction common(entry) {\n    return {\n        title: entry.title || '',\n        visible: entry.visible !== false,\n        opacity: Number.isFinite(entry.opacity) ? entry.opacity : 1,\n        minZoom: zoom(entry.minZoom),\n        maxZoom: zoom(entry.maxZoom),\n    };\n}\n\n/** Parametry vrstvy z Data workspace bez podpisu a pr\u00E1zdn\u00FDch hodnot. */\nexport function cleanParams(params) {\n    const out = {};\n    Object.entries(params || {}).forEach(([key, value]) => {\n        if (DROPPED_PARAMS.has(key) || value === undefined || value === null || value === '') return;\n        out[key] = String(value);\n    });\n    return out;\n}\n\n/**\n * Popis vrstev mapy pro slu\u017Ebu.\n * @param {object} state  `ctx.state` (vrstvy a skupiny, `unloadedLayers`)\n * @param {{paramsFor: (entry) => object}} options\n */\nexport function buildRenderSpec(state, { paramsFor }) {\n    const seen = new Map();\n    const uniqueKey = (key) => {\n        const count = (seen.get(key) || 0) + 1;\n        seen.set(key, count);\n        return count === 1 ? key : `${key}#${count}`;\n    };\n\n    const leaf = (entry, path) => {\n        const base = common(entry);\n        if (entry.dataType === 'drawing' || entry.dataType === 'local') {\n            return { ...base, type: entry.dataType, key: uniqueKey(`${entry.dataType}:${path.join('.')}`), path };\n        }\n        if (entry.external || EXTERNAL_TYPES.has(entry.dataType)) {\n            return { type: 'external', title: base.title, kind: entry.dataType };\n        }\n        if (!entry.itemId) return null;\n        const key = uniqueKey(`${entry.itemId}|${entry.layerKey ?? ''}|${entry.hybridPart ?? ''}`);\n        if (!entry.wms || !(entry.sublayers || []).length) {\n            return { type: 'unloaded', key, title: base.title };\n        }\n        let params;\n        try {\n            params = cleanParams(paramsFor(entry));\n        } catch {\n            return { type: 'unloaded', key, title: base.title };\n        }\n        return {\n            ...base,\n            type: 'item',\n            key,\n            itemId: entry.itemId,\n            dataType: entry.dataType === 'raster' ? 'raster' : 'vector',\n            params,\n        };\n    };\n\n    const layers = [];\n    (state.layers || []).forEach((entry, i) => {\n        if (entry.isGroup) {\n            const children = (entry.children || [])\n                .map((child, j) => leaf(child, [i, j]))\n                .filter(Boolean);\n            layers.push({\n                type: 'group',\n                key: uniqueKey(entry.title || `group ${i}`),\n                title: entry.title || '',\n                visible: entry.visible !== false,\n                children,\n            });\n            return;\n        }\n        const node = leaf(entry, [i]);\n        if (node) layers.push(node);\n    });\n    // Vrstvy, kter\u00E9 se p\u0159i na\u010Dten\u00ED mapy nena\u010Detly (z\u016Fst\u00E1vaj\u00ED v configu).\n    (state.unloadedLayers || []).forEach(({ config }) => {\n        if (config?.itemId) layers.push({ type: 'unloaded', title: config.title || '' });\n    });\n    return { version: 1, layers };\n}\n", "/**\n * persist.js \u2014 perzistence stavu mapy: Save / Save as p\u0159es API, generov\u00E1n\u00ED\n * n\u00E1hledu z canvasu a jeho odesl\u00E1n\u00ED na thumbnail endpoint. Autosave do\n * localStorage byl nahrazen upozorn\u011Bn\u00EDm na neulo\u017Een\u00E9 zm\u011Bny (unsaved.js).\n *\n * Stav mapy je v\u017Edy jedin\u00FD JS objekt tvaru Map.config (viz state.js).\n */\nimport { apiFetch, emit } from './utils.js';\nimport { serializeConfig } from './state.js';\nimport { readViewConfig } from './map.js';\nimport { composeMapCanvas } from './export.js';\nimport { buildRenderSpec } from './render-spec.js';\nimport { buildWmsParams } from './wms.js';\n\n/** Prefix kl\u00ED\u010D\u016F d\u0159\u00EDv\u011Bj\u0161\u00EDho autosave do localStorage (odstran\u011Bn \u2014 viz\n * unsaved.js). Star\u00E9 z\u00E1znamy se jednou uklid\u00ED (`cleanupLegacyAutosave`). */\nconst LEGACY_AUTOSAVE_PREFIX = 'mygeodata:map:autosave:';\n\n/** Sestav\u00ED aktu\u00E1ln\u00ED Map.config z b\u011Bhov\u00E9ho stavu + mapy (basemap kl\u00ED\u010D se \u010Dte\n * z prvn\u00ED viditeln\u00E9 vrstvy v `ctx.basemaps`). */\nexport function buildCurrentConfig(ctx) {\n    const view = readViewConfig(ctx.map);\n    const basemapKey = Object.entries(ctx.basemaps).find(([, layer]) => layer.getVisible())?.[0] || 'none';\n    const config = serializeConfig(ctx.state, view, basemapKey);\n    // Vrstvy, kter\u00E9 se p\u0159i na\u010Dten\u00ED nena\u010Detly jen do\u010Dasn\u011B (nap\u0159. 402 \u2014 do\u0161ly\n    // kredity), v configu zachov\u00E1me, jinak by je ulo\u017Een\u00ED mapy ti\u0161e smazalo.\n    // Vracej\u00ED se na konec (dospod) top-level, resp. do sv\u00E9 skupiny dle n\u00E1zvu.\n    (ctx.state.unloadedLayers || []).forEach(({ config: layerConfig, groupTitle }) => {\n        const group = groupTitle\n            ? config.layers.find((l) => l.type === 'group' && l.title === groupTitle)\n            : null;\n        (group ? group.children : config.layers).push(layerConfig);\n    });\n    return config;\n}\n\n/** Jednor\u00E1zov\u011B sma\u017Ee z\u00E1znamy d\u0159\u00EDv\u011Bj\u0161\u00EDho autosave (`mygeodata:map:autosave:*`).\n * Autosave do localStorage nahradilo upozorn\u011Bn\u00ED na neulo\u017Een\u00E9 zm\u011Bny \u2014 star\u00E9\n * z\u00E1znamy by jen zbyte\u010Dn\u011B zab\u00EDraly m\u00EDsto (u velk\u00FDch kreseb i MB). */\nexport function cleanupLegacyAutosave() {\n    try {\n        const storage = window.localStorage;\n        const keys = [];\n        for (let i = 0; i < storage.length; i += 1) {\n            const key = storage.key(i);\n            if (key && key.startsWith(LEGACY_AUTOSAVE_PREFIX)) keys.push(key);\n        }\n        keys.forEach((key) => storage.removeItem(key));\n    } catch {\n        // localStorage m\u016F\u017Ee b\u00FDt zak\u00E1zan\u00E9 (priv\u00E1tn\u00ED re\u017Eim) \u2014 nen\u00ED co ukl\u00EDzet.\n    }\n}\n\n/** Ulo\u017E\u00ED mapu na server. Pokud `asNew` je true (nebo mapa je\u0161t\u011B neexistuje na\n * serveru a `asNew` nebylo explicitn\u011B false), vytvo\u0159\u00ED novou mapu (POST). */\nexport async function saveMap(ctx, { asNew = false, title, description, quiet = false } = {}) {\n    // Prvn\u00ED ulo\u017Een\u00ED nov\u00E9 mapy (ne \u201ESave as\u201C) \u2014 main.js po n\u011Bm nab\u00EDdne sd\u00EDlen\u00ED,\n    // pokud ukl\u00E1d\u00E1n\u00ED nespustil s\u00E1m dialog sd\u00EDlen\u00ED (`quiet`).\n    const firstSave = !ctx.state.mapId;\n    const config = buildCurrentConfig(ctx);\n    const body = JSON.stringify({\n        title: title ?? ctx.state.title,\n        description: description ?? ctx.state.description,\n        config,\n        // Jak se vrstvy kresl\u00ED \u2014 z toho server skl\u00E1d\u00E1 zve\u0159ejn\u011Bnou mapu (WMS).\n        render: buildRenderSpec(ctx.state, { paramsFor: buildWmsParams }),\n    });\n    let result;\n    if (ctx.state.mapId && !asNew) {\n        result = await apiFetch(`${ctx.bootstrap.apiBase}/maps/${ctx.state.mapId}/`, { method: 'PUT', body });\n    } else {\n        result = await apiFetch(`${ctx.bootstrap.apiBase}/maps/`, { method: 'POST', body });\n    }\n    ctx.state.mapId = result.id;\n    ctx.state.title = result.title ?? ctx.state.title;\n    ctx.state.description = result.description ?? ctx.state.description;\n    ctx.state.dirty = false;\n    ctx.state.savedOnce = true;\n    // Adresn\u00ED \u0159\u00E1dek ukazuje na ulo\u017Eenou mapu (refresh / sd\u00EDlen\u00ED odkazu po\n    // prvn\u00EDm ulo\u017Een\u00ED nebo \u201ESave as\" otev\u0159e spr\u00E1vnou mapu).\n    try {\n        const viewerBase = ctx.bootstrap.apiBase.replace(/\\/api$/, '');\n        const path = `${viewerBase}/${result.id}/`;\n        if (window.location.pathname !== path) {\n            window.history.replaceState(null, '', path + window.location.hash);\n        }\n    } catch {\n        /* history API nedostupn\u00E9 \u2014 nevad\u00ED */\n    }\n    emit('map:saved', { map: result, omittedLayers: result.omitted_layers || 0, firstSave, quiet });\n    // N\u00E1hled je jen \"nice to have\" a b\u011B\u017E\u00ED nez\u00E1visle na ulo\u017Een\u00ED \u2014 jeho p\u0159\u00EDpadn\u00E1\n    // chyba (nap\u0159. v\u00FDjimka z OL renderu) nikdy nesm\u00ED shodit u\u017E \u00FAsp\u011B\u0161n\u00E9 Save.\n    try {\n        captureAndUploadThumbnail(ctx);\n    } catch {\n        /* n\u00E1hled se nepoda\u0159il \u2014 mapa je i tak ulo\u017Een\u00E1 */\n    }\n    return result;\n}\n\n/** Maxim\u00E1ln\u00ED del\u0161\u00ED strana (px) generovan\u00E9ho n\u00E1hledu mapy. N\u00E1hled dr\u017E\u00EDme mal\u00FD\n * z\u00E1m\u011Brn\u011B:\n *  1) Fotografick\u00E9 podklady (Esri World Imagery) vyrob\u00ED z pln\u00E9ho okna ob\u0159\u00ED PNG,\n *     kter\u00E9 snadno p\u0159ekro\u010D\u00ED `MAPS_THUMBNAIL_MAX_BYTES` (2 MiB) \u2014 server ho pak\n *     odm\u00EDtne (HTTP 400) a v galerii n\u00E1hled chyb\u00ED. U ploch\u00E9 OSM se to nestane,\n *     proto se projev jevil \u201Ejen u satelitu\". Zmen\u0161en\u00EDm je PNG v\u017Edy mal\u00E9.\n *  2) Rychlej\u0161\u00ED p\u0159enos a \u00FAlo\u017Ei\u0161t\u011B.\n */\nconst THUMBNAIL_MAX_DIM = 512;\n\n/** Vygeneruje n\u00E1hled mapy z canvasu a po\u0161le ho na thumbnail endpoint. Vol\u00E1 se\n * po ka\u017Ed\u00E9m \u00FAsp\u011B\u0161n\u00E9m ulo\u017Een\u00ED, aby galerie ukazovala aktu\u00E1ln\u00ED v\u00FD\u0159ez.\n *\n * Robustn\u00ED v\u016F\u010Di chyb\u00E1m renderu: n\u00E1hled se skl\u00E1d\u00E1 z u\u017E vykreslen\u00FDch canvas\u016F\n * mapy (`composeMapCanvas`) a pot\u00E9 se zmen\u0161\u00ED (`downscaleCanvas`). Z\u00C1M\u011ARN\u011A\n * nevol\u00E1 `map.renderSync()` \u2014 to vynucuje synchronn\u00ED p\u0159ekreslen\u00ED, kter\u00E9 u\n * n\u011Bkter\u00FDch map spadne hluboko v OpenLayers (projev hl\u00E1\u0161ky \u201E\u2026reading 'find'\").\n * Mapa je p\u0159i ukl\u00E1d\u00E1n\u00ED na obrazovce u\u017E vykreslen\u00E1, tak\u017Ee sta\u010D\u00ED zachytit jej\u00ED\n * aktu\u00E1ln\u00ED canvasy; p\u0159\u00EDpadn\u00E9 dob\u00EDhaj\u00EDc\u00ED dla\u017Edice do\u0159e\u0161\u00ED `rendercomplete`,\n * jinak se zachyt\u00ED aktu\u00E1ln\u00ED stav po kr\u00E1tk\u00E9 prodlev\u011B. Nic z toho nepropadne\n * do Save. */\nexport function captureAndUploadThumbnail(ctx) {\n    if (!ctx.state.mapId) return;\n    const mapId = ctx.state.mapId;\n    let uploaded = false;\n\n    async function capture() {\n        if (uploaded) return;\n        uploaded = true;\n        try {\n            const full = composeMapCanvas(ctx.map, '#ffffff');\n            if (!full) return;\n            const canvas = downscaleCanvas(full, THUMBNAIL_MAX_DIM);\n            const dataUrl = canvas.toDataURL('image/png');\n            await apiFetch(`${ctx.bootstrap.apiBase}/maps/${mapId}/thumbnail/`, {\n                method: 'POST',\n                body: JSON.stringify({ image: dataUrl }),\n            });\n        } catch {\n            // N\u00E1hled je jen \"nice to have\" \u2014 chybu ti\u0161e ignorujeme, aby neshodila Save.\n        }\n    }\n\n    // Kdy\u017E je\u0161t\u011B dob\u00EDhaj\u00ED dla\u017Edice/GetMap (nap\u0159. po zm\u011Bn\u011B podkladu), po\u010Dk\u00E1me na\n    // dokon\u010Den\u00ED; jinak zachyt\u00EDme aktu\u00E1ln\u00ED (u\u017E vykreslen\u00FD) stav po kr\u00E1tk\u00E9\n    // prodlev\u011B. Bez `renderSync()` \u2014 viz koment\u00E1\u0159 v\u00FD\u0161e.\n    ctx.map.once('rendercomplete', capture);\n    window.setTimeout(capture, 1500);\n}\n\n/** Zmen\u0161\u00ED canvas tak, aby jeho del\u0161\u00ED strana nep\u0159es\u00E1hla `maxDim` (pom\u011Br stran\n * zachov\u00E1n). Men\u0161\u00ED n\u00E1hled = v\u00FDrazn\u011B men\u0161\u00ED PNG (kl\u00ED\u010Dov\u00E9 u fotografick\u00FDch\n * podklad\u016F). Vrac\u00ED p\u016Fvodn\u00ED canvas, kdy\u017E zmen\u0161ovat net\u0159eba. */\nfunction downscaleCanvas(source, maxDim) {\n    const longest = Math.max(source.width, source.height);\n    if (!longest || longest <= maxDim) return source;\n    const scale = maxDim / longest;\n    const out = document.createElement('canvas');\n    out.width = Math.max(1, Math.round(source.width * scale));\n    out.height = Math.max(1, Math.round(source.height * scale));\n    const context = out.getContext('2d');\n    context.fillStyle = '#ffffff';\n    context.fillRect(0, 0, out.width, out.height);\n    context.imageSmoothingEnabled = true;\n    context.imageSmoothingQuality = 'high';\n    context.drawImage(source, 0, 0, out.width, out.height);\n    return out;\n}\n", "/**\n * service.js \u2014 z\u00E1lo\u017Eka \u201EMap service (WMS)\u201C dialogu Share.\n *\n * Vlastn\u00EDk ulo\u017Een\u00E9 mapy ji zve\u0159ejn\u00ED jako WMS pro QGIS, ArcGIS a webov\u00E9 mapy\n * (`apps/maps/publishing.py`, mapov\u00E1 slu\u017Eba GCZ `/m/<id>/`). Adresa nese mapov\u00FD\n * kl\u00ED\u010D vlastn\u00EDka \u2014 dialog ho rovnou dopln\u00ED (mapov\u00FD kl\u00ED\u010D je ve\u0159ejn\u00FD), nebo\n * nab\u00EDdne vytvo\u0159it nov\u00FD. Server: `GET/PUT api/maps/<id>/service/`,\n * `POST api/maps/<id>/service/keys/`.\n */\nimport { apiFetch } from './utils.js';\n\nfunction esc(value) {\n    return String(value ?? '')\n        .replaceAll('&', '&amp;')\n        .replaceAll('<', '&lt;')\n        .replaceAll('>', '&gt;')\n        .replaceAll('\"', '&quot;');\n}\n\n/** Z chyby `apiFetch` (\u201E400 Bad Request: {\"error\":\"\u2026\"}\") text pro UI. */\nfunction errorText(error, fallback) {\n    const raw = String(error?.message || '');\n    const start = raw.indexOf('{');\n    if (start !== -1) {\n        try {\n            const data = JSON.parse(raw.slice(start));\n            if (typeof data?.error === 'string') return data.error;\n        } catch {\n            /* t\u011Blo nen\u00ED JSON */\n        }\n    }\n    return fallback;\n}\n\nconst ICON_COPY = '<svg class=\"h-4 w-4\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><rect x=\"9\" y=\"9\" width=\"11\" height=\"11\" rx=\"2\"/><path d=\"M5 15V5a2 2 0 0 1 2-2h10\"/></svg>';\nconst ICON_OPEN = '<svg class=\"h-4 w-4\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M14 4h6v6\"/><path d=\"M20 4 10 14\"/><path d=\"M19 14v5a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V6a1 1 0 0 1 1-1h5\"/></svg>';\nconst ICON_CHEVRON = '<svg class=\"h-4 w-4 flex-none text-slate-400 transition\" data-role=\"chevron\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"m6 9 6 6 6-6\"/></svg>';\nconst BUTTON = 'inline-flex flex-none items-center gap-x-1.5 rounded-lg border border-slate-200 bg-white px-2.5 py-1.5 text-sm font-medium text-slate-700 shadow-sm hover:bg-slate-50';\nconst NEW_KEY = '__new__';\n\nfunction urlRow(label, url, { open = false, hint = '' } = {}) {\n    if (!url) return '';\n    return `\n        <div>\n            <label class=\"form-label\">${esc(label)}</label>\n            <div class=\"flex gap-x-2\">\n                <input type=\"text\" readonly class=\"form-input min-w-0 flex-1 !text-xs\" value=\"${esc(url)}\">\n                <button type=\"button\" data-copy=\"${esc(url)}\" class=\"${BUTTON}\">${ICON_COPY}<span>Copy</span></button>\n                ${open ? `<a href=\"${esc(url)}\" target=\"_blank\" rel=\"noopener\" title=\"Open\" class=\"${BUTTON}\">${ICON_OPEN}</a>` : ''}\n            </div>\n            ${hint ? `<p class=\"mt-1.5 text-xs text-slate-500\">${hint}</p>` : ''}\n        </div>`;\n}\n\nfunction toggle(on) {\n    return `<span class=\"relative inline-flex h-5 w-9 flex-none items-center rounded-full transition ${on ? 'bg-brand-600' : 'bg-slate-300'}\">\n        <span class=\"inline-block h-4 w-4 rounded-full bg-white shadow transition ${on ? 'translate-x-[18px]' : 'translate-x-0.5'}\"></span></span>`;\n}\n\n/** Propoj\u00ED z\u00E1lo\u017Eku s dialogem. Vrac\u00ED `{ open() }` \u2014 na\u010Dte stav a vykresl\u00ED ho. */\nexport function initServiceTab(ctx, container) {\n    let data = null;\n    let busy = false;\n    let moreOpen = false;\n    let creating = false;\n    let message = '';\n\n    const apiUrl = () => `${ctx.bootstrap.apiBase}/maps/${ctx.state.mapId}/service/`;\n\n    async function load() {\n        container.innerHTML = '<p class=\"py-6 text-center text-sm text-slate-400\">Loading\u2026</p>';\n        try {\n            data = await apiFetch(apiUrl());\n            message = '';\n        } catch (error) {\n            data = null;\n            message = errorText(error, 'The map service settings couldn\u2019t be loaded.');\n        }\n        render();\n    }\n\n    async function update(body) {\n        if (busy) return;\n        busy = true;\n        message = '';\n        render();\n        try {\n            data = await apiFetch(apiUrl(), { method: 'PUT', body: JSON.stringify(body) });\n        } catch (error) {\n            message = errorText(error, 'The map service couldn\u2019t be changed.');\n        } finally {\n            busy = false;\n            render();\n        }\n    }\n\n    async function createKey(form) {\n        if (busy) return;\n        busy = true;\n        message = '';\n        render();\n        try {\n            data = await apiFetch(`${apiUrl()}keys/`, {\n                method: 'POST',\n                body: JSON.stringify({\n                    name: form.querySelector('[name=\"name\"]').value,\n                    scope: form.querySelector('[name=\"scope\"]').value,\n                    monthly_limit: form.querySelector('[name=\"limit\"]').value,\n                }),\n            });\n            creating = false;\n        } catch (error) {\n            message = errorText(error, 'The map key couldn\u2019t be created.');\n        } finally {\n            busy = false;\n            render();\n        }\n    }\n\n    function planCard() {\n        return `\n            <div class=\"rounded-xl border border-slate-200 px-4 py-4\">\n                <p class=\"text-sm font-semibold text-slate-800\">Use this map in QGIS, ArcGIS and web maps</p>\n                <p class=\"mt-1 text-sm text-slate-600\">Publish the map as a WMS map service and add it to any GIS program as a layer \u2014 with your styles, labels and legend. Map services come with the paid plans.</p>\n                <ul class=\"mt-3 space-y-1 text-xs text-slate-500\">\n                    <li>\u00B7 Always the version of the map you last saved</li>\n                    <li>\u00B7 The images are paid from your credits</li>\n                    <li>\u00B7 You decide where the map may be used and how much it may cost</li>\n                </ul>\n                <div class=\"mt-4 flex justify-end\"><a href=\"${esc(data.plans_url)}\" target=\"_blank\" rel=\"noopener\" class=\"btn-primary\">See plans</a></div>\n            </div>`;\n    }\n\n    function publishRow(enabled) {\n        return `\n            <button type=\"button\" data-action=\"toggle\" ${busy ? 'disabled' : ''}\n                    class=\"flex w-full items-start gap-x-3 rounded-xl border border-slate-200 px-3 py-2.5 text-left hover:bg-slate-50\">\n                <span class=\"mt-0.5\">${toggle(enabled)}</span>\n                <span class=\"text-sm\"><span class=\"font-medium text-slate-800\">Publish as a map service</span>\n                    <span class=\"block text-xs text-slate-500\">QGIS, ArcGIS and web maps can show this map as WMS layers.</span></span>\n            </button>`;\n    }\n\n    function keyForm() {\n        if (data.can_create_key === false) {\n            return `<p class=\"rounded-lg bg-amber-50 px-3 py-2.5 text-sm text-amber-900 ring-1 ring-inset ring-amber-200\">\n                You use all ${esc(data.keys_limit)} keys of your plan. Delete a key you don\u2019t need in\n                <a href=\"${esc(data.keys_url)}\" target=\"_blank\" rel=\"noopener\" class=\"font-semibold underline\">API keys</a> to create a map key.</p>`;\n        }\n        const title = ctx.state.title || 'Map';\n        const first = !(data.keys || []).length;\n        return `\n            <form data-role=\"key-form\" class=\"space-y-3 rounded-xl border border-slate-200 px-4 py-3.5\">\n                <div>\n                    <p class=\"text-sm font-semibold text-slate-800\">Create a map key</p>\n                    <p class=\"mt-0.5 text-xs text-slate-500\">The address of a map service carries a map key. It says whose credits pay for the images and can limit where the map works.${first ? ' You don\u2019t have one yet.' : ''}</p>\n                </div>\n                <div><label class=\"form-label\">Name</label><input name=\"name\" type=\"text\" maxlength=\"100\" class=\"form-input\" value=\"${esc(`${title} (WMS)`)}\"></div>\n                <div class=\"grid grid-cols-2 gap-3\">\n                    <div><label class=\"form-label\">Use for</label>\n                        <select name=\"scope\" class=\"form-select\"><option value=\"this\">Only this map</option><option value=\"all\">All my maps</option></select></div>\n                    <div><label class=\"form-label\">Monthly limit</label>\n                        <div class=\"flex items-center gap-x-2\"><input name=\"limit\" type=\"number\" min=\"1\" step=\"1\" class=\"form-input\" value=\"100\"><span class=\"flex-none text-xs text-slate-500\">credits</span></div></div>\n                </div>\n                <div class=\"flex items-center justify-between gap-x-3 pt-1\">\n                    <a href=\"${esc(data.keys_url)}\" target=\"_blank\" rel=\"noopener\" class=\"text-xs font-medium text-brand-600 hover:underline\">IP and domain limits in Console</a>\n                    <span class=\"flex gap-x-2\">\n                        ${first ? '' : '<button type=\"button\" data-action=\"cancel-key\" class=\"btn-ghost\">Cancel</button>'}\n                        <button type=\"submit\" class=\"btn-primary\" ${busy ? 'disabled' : ''}>Create map key</button>\n                    </span>\n                </div>\n            </form>`;\n    }\n\n    function keySelect() {\n        const options = (data.keys || []).map((key) => `<option value=\"${esc(key.id)}\" ${key.id === data.selected_key ? 'selected' : ''}>${esc(key.name)} \u00B7 ${esc(key.prefix)}\u2026 \u00B7 ${key.scope === 'this' ? 'only this map' : 'all my maps'}</option>`).join('');\n        const create = data.can_create_key ? `<option value=\"${NEW_KEY}\">Create a new map key\u2026</option>` : '';\n        return `\n            <div>\n                <label class=\"form-label\" for=\"map-service-key\">Map key</label>\n                <select id=\"map-service-key\" data-action=\"key\" class=\"form-select\">${options}${create}</select>\n                <p class=\"mt-1.5 text-xs text-slate-500\">The key is already in the addresses below. It decides whose credits pay and where the map may be used.\n                    <a href=\"${esc(data.keys_url)}\" target=\"_blank\" rel=\"noopener\" class=\"font-medium text-brand-600 hover:underline\">Manage keys</a></p>\n            </div>`;\n    }\n\n    function layerTable(service) {\n        const rows = [{ name: service.root, title: 'Whole map \u2014 all layers in the map\u2019s order', strong: true }]\n            .concat((service.layers || []).map((layer) => ({\n                name: layer.name,\n                title: `${layer.depth ? '\u2003' : ''}${layer.title}${layer.group ? ' (group)' : ''}`,\n            })));\n        return `\n            <div>\n                <p class=\"text-xs font-semibold text-slate-700\">Layers in the service</p>\n                <div class=\"mt-1 max-h-56 overflow-y-auto\">\n                    <table class=\"w-full text-left\"><tbody>\n                        ${rows.map((row) => `<tr class=\"border-t border-slate-100\">\n                            <td class=\"py-1.5 pr-3 align-top font-mono text-[11px] text-slate-700\">${esc(row.name)}</td>\n                            <td class=\"py-1.5 text-xs ${row.strong ? 'font-medium text-slate-800' : 'text-slate-600'}\">${esc(row.title)}</td></tr>`).join('')}\n                    </tbody></table>\n                </div>\n            </div>`;\n    }\n\n    function settings(service) {\n        const chips = (service.crs || []).map((code) => {\n            const extra = (service.extra_crs || []).includes(code);\n            return `<span class=\"inline-flex items-center gap-x-1 rounded-full bg-slate-100 px-2 py-0.5 text-[11px] font-medium text-slate-600\">${esc(code)}${extra ? `<button type=\"button\" data-remove-crs=\"${esc(code)}\" class=\"text-slate-400 hover:text-red-600\" aria-label=\"Remove ${esc(code)}\">\u00D7</button>` : ''}</span>`;\n        }).join('');\n        return `\n            <div class=\"space-y-2.5\">\n                <p class=\"text-xs font-semibold text-slate-700\">Settings</p>\n                <label class=\"flex cursor-pointer items-start gap-x-2.5\">\n                    <input type=\"checkbox\" data-action=\"feature-info\" class=\"mt-0.5 rounded border-slate-300 text-brand-600 focus:ring-brand-500\" ${service.feature_info ? 'checked' : ''} ${busy ? 'disabled' : ''}>\n                    <span class=\"text-sm\"><span class=\"font-medium text-slate-800\">Feature info</span>\n                        <span class=\"block text-xs text-slate-500\">Clicking the map in QGIS or a web map shows the attributes of the features (GetFeatureInfo).</span></span>\n                </label>\n                <div>\n                    <p class=\"text-xs text-slate-500\">Coordinate systems</p>\n                    <div class=\"mt-1 flex flex-wrap items-center gap-1.5\">${chips}</div>\n                    <form data-role=\"crs-form\" class=\"mt-2 flex gap-x-2\">\n                        <input name=\"crs\" type=\"text\" placeholder=\"Add a system, like EPSG:5514\" class=\"form-input min-w-0 flex-1 !py-1 !text-xs\">\n                        <button type=\"submit\" class=\"${BUTTON}\" ${busy ? 'disabled' : ''}>Add</button>\n                    </form>\n                </div>\n            </div>`;\n    }\n\n    /** P\u0159ihl\u00E1\u0161en\u00ED jm\u00E9nem a heslem (HTTP Basic) m\u00EDsto kl\u00ED\u010De v adrese \u2014 QGIS, ArcGIS. */\n    function loginBlock() {\n        const login = data.login;\n        if (!login) return '';\n        return `\n            <div class=\"space-y-2\">\n                <p class=\"text-xs font-semibold text-slate-700\">Log in instead of a key in the address</p>\n                <p class=\"text-xs text-slate-500\">In QGIS or ArcGIS you can keep the key out of the address and out of your project: use the address below and, under <em>Authentication \u2192 Basic</em>, any user name (like <code class=\"font-mono\">${esc(login.user)}</code>) and the map key as the password.</p>\n                <div class=\"grid gap-x-4 gap-y-3 sm:grid-cols-2\">\n                ${urlRow('Address without the key', login.address)}\n                <div>\n                    <label class=\"form-label\">Password</label>\n                    <div class=\"flex gap-x-2\">\n                        <input type=\"password\" readonly class=\"form-input min-w-0 flex-1 !text-xs\" value=\"${esc(login.password)}\">\n                        <button type=\"button\" data-copy=\"${esc(login.password)}\" class=\"${BUTTON}\">${ICON_COPY}<span>Copy</span></button>\n                    </div>\n                </div>\n                </div>\n            </div>`;\n    }\n\n    function omitted(service) {\n        const items = (service.omitted || []).map((o) => `<li>\u00B7 <strong>${esc(o.title)}</strong>${o.reason ? ` \u2014 ${esc(o.reason)}` : ''}</li>`).join('');\n        return `\n            <div class=\"text-xs text-slate-500\">\n                <p>Not in the service: the basemap \u2014 QGIS and web maps add their own.</p>\n                ${items ? `<ul class=\"mt-1 space-y-0.5\">${items}</ul>` : ''}\n            </div>`;\n    }\n\n    function published() {\n        const service = data.service;\n        const urls = data.urls || {};\n        const parts = [publishRow(true)];\n        if (!(data.keys || []).length || creating) {\n            parts.push(keyForm());\n        } else {\n            parts.push(keySelect());\n            parts.push(urlRow('WMS address', urls.wms, {\n                hint: 'QGIS: <em>Layer \u2192 Add Layer \u2192 Add WMS/WMTS Layer \u2192 New</em>, paste the address, <em>Connect</em> and add the first layer \u2014 the whole map in one layer. ArcGIS: <em>Add Data \u2192 Data From Path</em>.',\n            }));\n            parts.push(urlRow('GetCapabilities', urls.capabilities, { open: true }));\n        }\n        if ((service.omitted || []).length) {\n            parts.push(`<p class=\"rounded-lg bg-amber-50 px-3 py-2 text-xs text-amber-900 ring-1 ring-inset ring-amber-200\">${service.omitted.length === 1 ? 'One layer of the map isn\u2019t' : `${service.omitted.length} layers of the map aren\u2019t`} in the service \u2014 see \u201CMore\u201D.</p>`);\n        }\n        parts.push(`\n            <div class=\"rounded-lg border border-slate-200\">\n                <button type=\"button\" data-action=\"more\" class=\"flex w-full items-center justify-between px-3 py-2 text-left text-sm font-medium text-slate-700\">\n                    <span>More addresses, layers and settings</span>${ICON_CHEVRON}</button>\n                <div data-role=\"more\" class=\"${moreOpen ? '' : 'hidden'} space-y-4 border-t border-slate-200 px-3 py-3\">\n                    ${urlRow('Map image (PNG, whole map)', urls.map_image, { open: true })}\n                    ${urlRow('Legend', urls.legend, { open: true })}\n                    ${loginBlock()}\n                    <div class=\"grid items-start gap-x-6 gap-y-4 sm:grid-cols-2\">\n                        ${layerTable(service)}\n                        ${settings(service)}\n                    </div>\n                    ${omitted(service)}\n                </div>\n            </div>`);\n        const per = data.credits?.images_per_credit ? ` \u2014 about ${esc(data.credits.images_per_credit)} images per credit` : '';\n        parts.push(`<p class=\"rounded-lg bg-slate-50 px-3 py-2.5 text-xs text-slate-600\">The service shows the map as you last saved it, without the basemap. Every image it draws is paid from your credits${per}. Set a monthly limit on the key.</p>`);\n        return parts.join('');\n    }\n\n    function render() {\n        if (!data) {\n            container.innerHTML = `<p class=\"text-sm text-red-600\">${esc(message || 'Loading failed.')}</p>`;\n            return;\n        }\n        const parts = [];\n        if (ctx.state.dirty) {\n            parts.push('<p class=\"rounded-lg bg-amber-50 px-3 py-2 text-xs text-amber-900 ring-1 ring-inset ring-amber-200\">This map has unsaved changes. The map service shows them after you save the map.</p>');\n        }\n        if (!data.available) {\n            parts.push(planCard());\n        } else if (!data.service?.enabled) {\n            parts.push(publishRow(false));\n            parts.push('<p class=\"text-xs text-slate-500\">You get the address for QGIS and ArcGIS right after you publish the map. You can switch the service off at any time.</p>');\n        } else {\n            parts.push(published());\n        }\n        if (message) parts.push(`<p class=\"text-sm text-red-600\">${esc(message)}</p>`);\n        container.innerHTML = parts.join('');\n        container.querySelector('[data-role=\"chevron\"]')?.classList.toggle('rotate-180', moreOpen);\n    }\n\n    container.addEventListener('click', async (event) => {\n        const copy = event.target.closest('[data-copy]');\n        if (copy) {\n            try {\n                await navigator.clipboard.writeText(copy.dataset.copy);\n            } catch {\n                copy.parentElement.querySelector('input')?.select();\n                document.execCommand('copy');\n            }\n            const label = copy.querySelector('span');\n            if (label) {\n                label.textContent = 'Copied!';\n                setTimeout(() => { label.textContent = 'Copy'; }, 1500);\n            }\n            return;\n        }\n        const action = event.target.closest('[data-action]')?.dataset.action;\n        if (action === 'toggle') {\n            update({ enabled: !data?.service?.enabled });\n        } else if (action === 'more') {\n            moreOpen = !moreOpen;\n            render();\n        } else if (action === 'cancel-key') {\n            creating = false;\n            render();\n        }\n        const removeCrs = event.target.closest('[data-remove-crs]')?.dataset.removeCrs;\n        if (removeCrs) {\n            update({ extra_crs: (data.service.extra_crs || []).filter((code) => code !== removeCrs) });\n        }\n    });\n\n    container.addEventListener('change', (event) => {\n        const action = event.target.dataset?.action;\n        if (action === 'key') {\n            if (event.target.value === NEW_KEY) {\n                creating = true;\n                render();\n            } else {\n                update({ key: event.target.value });\n            }\n        } else if (action === 'feature-info') {\n            update({ feature_info: event.target.checked });\n        }\n    });\n\n    container.addEventListener('submit', (event) => {\n        event.preventDefault();\n        const form = event.target;\n        if (form.dataset.role === 'key-form') {\n            createKey(form);\n        } else if (form.dataset.role === 'crs-form') {\n            const code = form.querySelector('[name=\"crs\"]').value.trim();\n            if (code) update({ extra_crs: [...(data.service.extra_crs || []), code] });\n        }\n    });\n\n    return { open: load };\n}\n", "/**\n * share.js \u2014 sd\u00EDlen\u00ED mapy (f\u00E1ze 2, d\u00E1vka c).\n *\n * T\u0159i zodpov\u011Bdnosti:\n *  1. Share modal \u2014 p\u0159ep\u00EDn\u00E1n\u00ED `share_mode` (PUT mapy), kop\u00EDrov\u00E1n\u00ED odkazu\n *     (voliteln\u011B s `?view=` permalinkem) a spr\u00E1va pozv\u00E1nek p\u0159es shares API\n *     (`GET/POST /maps/<uuid>/shares/`, `PUT/DELETE \u2026/shares/<id>/`).\n *     Spr\u00E1va pozv\u00E1nek i share_mode jsou jen pro vlastn\u00EDka \u2014 GET shares vrac\u00ED\n *     ne-vlastn\u00EDkovi 404, podle toho se sekce skryj\u00ED.\n *  2. Permalink `?view=<lon>,<lat>,<zoom>` \u2014 p\u0159e\u010Dte a validuje parametr z URL,\n *     odstran\u00ED ho p\u0159es history.replaceState a vr\u00E1t\u00ED view pro po\u010D\u00E1te\u010Dn\u00ED pohled\n *     (Map.config se nem\u011Bn\u00ED).\n *  3. Read-only re\u017Eim (canEdit=false) \u2014 skryje Save/Rename/thumbnail, nech\u00E1\n *     \u201ESave as\" (vytvo\u0159\u00ED kopii p\u0159es POST) a zobraz\u00ED badge \u201EView only\".\n */\nimport { fromLonLat } from 'ol/proj.js';\nimport { apiFetch, emit, on } from './utils.js';\nimport { readViewConfig } from './map.js';\nimport { slowItems } from './advisor.js';\nimport { saveMap } from './persist.js';\nimport { initServiceTab } from './service.js';\n\n/* ---------------------------------------------------------------------------\n * Pom\u016Fcky\n * ------------------------------------------------------------------------- */\n\n/** Z chyby `apiFetch` (\u201E400 Bad Request: {\"error\":\"\u2026\"}\") vyt\u00E1hne text pro UI. */\nfunction apiErrorMessage(error, fallback) {\n    const raw = String(error?.message || '');\n    const jsonStart = raw.indexOf('{');\n    if (jsonStart !== -1) {\n        try {\n            const data = JSON.parse(raw.slice(jsonStart));\n            if (data && typeof data.error === 'string') return data.error;\n        } catch {\n            /* t\u011Blo nen\u00ED JSON \u2014 pou\u017Eije se fallback */\n        }\n    }\n    return fallback;\n}\n\n/** Chyba `apiFetch` odpov\u00EDd\u00E1 HTTP 404 (mapa ciz\u00ED \u2014 ne-vlastn\u00EDk)? */\nfunction isNotFoundError(error) {\n    return String(error?.message || '').startsWith('404');\n}\n\nfunction show(el) { el?.classList.remove('hidden'); }\nfunction hide(el) { el?.classList.add('hidden'); }\n\nfunction escapeHtml(value) {\n    return String(value ?? '')\n        .replaceAll('&', '&amp;')\n        .replaceAll('<', '&lt;')\n        .replaceAll('>', '&gt;')\n        .replaceAll('\"', '&quot;');\n}\n\n/* ---------------------------------------------------------------------------\n * Permalink `?view=<lon>,<lat>,<zoom>`\n * ------------------------------------------------------------------------- */\n\n/** P\u0159e\u010Dte a odstran\u00ED `?view=` z URL. Vrac\u00ED `{ center: [lon, lat], zoom }`,\n * nebo null (parametr chyb\u00ED / je nevalidn\u00ED). Parametr se odstran\u00ED v\u017Edy,\n * aby se refresh a odkazy d\u00E1l chovaly norm\u00E1ln\u011B. */\nexport function consumePermalinkView() {\n    const params = new URLSearchParams(window.location.search);\n    const raw = params.get('view');\n    if (raw === null) return null;\n    params.delete('view');\n    const query = params.toString();\n    window.history.replaceState(\n        null,\n        '',\n        window.location.pathname + (query ? `?${query}` : '') + window.location.hash,\n    );\n    const parts = raw.split(',').map((v) => Number.parseFloat(v));\n    if (parts.length !== 3 || parts.some((v) => !Number.isFinite(v))) return null;\n    const [lon, lat, zoom] = parts;\n    if (lon < -180 || lon > 180 || lat < -90 || lat > 90 || zoom < 0 || zoom > 28) return null;\n    return { center: [lon, lat], zoom };\n}\n\n/** Nastav\u00ED pohled mapy podle v\u00FDsledku `consumePermalinkView`. */\nexport function applyPermalinkView(map, view) {\n    if (!view) return;\n    const olView = map.getView();\n    olView.setCenter(fromLonLat(view.center));\n    olView.setZoom(view.zoom);\n}\n\n/** Sestav\u00ED URL mapy; s `includeView` p\u0159id\u00E1 `?view=<lon>,<lat>,<zoom>`\n * (WGS84, lon/lat na 5 desetinn\u00FDch m\u00EDst, zoom na 2). URL se odvozuje z mapId\n * (ne z adresn\u00EDho \u0159\u00E1dku) \u2014 po \u201ESave as\" m\u00ED\u0159\u00ED odkaz na novou kopii. */\nfunction buildShareUrl(ctx, includeView) {\n    const viewerBase = ctx.bootstrap.apiBase.replace(/\\/api$/, '');\n    const base = `${window.location.origin}${viewerBase}/${ctx.state.mapId}/`;\n    if (!includeView) return base;\n    const view = readViewConfig(ctx.map);\n    const lon = view.center[0].toFixed(5);\n    const lat = view.center[1].toFixed(5);\n    const zoom = (view.zoom ?? 0).toFixed(2);\n    return `${base}?view=${lon},${lat},${zoom}`;\n}\n\n/* ---------------------------------------------------------------------------\n * Read-only re\u017Eim (canEdit=false u na\u010Dten\u00E9 mapy)\n * ------------------------------------------------------------------------- */\n\n/** Aplikuje read-only re\u017Eim: skryje Save, zamkne p\u0159ejmenov\u00E1n\u00ED a zobraz\u00ED badge.\n * \u201ESave as\" z\u016Fst\u00E1v\u00E1 \u2014 po vytvo\u0159en\u00ED vlastn\u00ED kopie se editace zase odemkne. */\nexport function applyReadOnlyMode(ctx, elements) {\n    if (ctx.bootstrap.canEdit !== false || !ctx.state.mapId) return;\n    ctx.readOnly = true;\n    // Uk\u00E1zkov\u00E1 mapa (apps.maps.samples): neutr\u00E1ln\u00ED \u0161t\u00EDtek a tla\u010D\u00EDtko \u201ESave a copy\u201C\n    // m\u00EDsto Share \u2014 kopie je hned vlastn\u00ED mapa u\u017Eivatele (dialog \u201ESave as\u201C).\n    const sample = Boolean(ctx.bootstrap.map?.sample_key);\n    ctx.sampleReadOnly = sample;\n    const badge = elements.readonlyBadge;\n    if (sample && badge) {\n        badge.classList.remove('bg-amber-50', 'text-amber-700', 'ring-amber-200');\n        badge.classList.add('bg-slate-100', 'text-slate-600', 'ring-slate-200');\n        const svg = badge.querySelector('svg');\n        badge.textContent = '';\n        if (svg) badge.appendChild(svg);\n        badge.appendChild(document.createTextNode('Sample map \u00B7 view only'));\n    }\n    elements.saveCopyButton?.addEventListener('click', () => elements.saveAsButton?.click());\n\n    const lock = () => {\n        hide(elements.saveButton);\n        show(elements.readonlyBadge);\n        elements.readonlyBadge?.classList.add('inline-flex');\n        if (sample) {\n            show(elements.saveCopyButton);\n            hide(elements.shareButton);\n            elements.shareButton?.classList.remove('inline-flex');\n        }\n        if (elements.titleInput) {\n            elements.titleInput.readOnly = true;\n            elements.titleInput.classList.add('pointer-events-none');\n        }\n    };\n    const unlock = () => {\n        show(elements.saveButton);\n        hide(elements.readonlyBadge);\n        elements.readonlyBadge?.classList.remove('inline-flex');\n        if (sample) {\n            ctx.sampleReadOnly = false;\n            hide(elements.saveCopyButton);\n            show(elements.shareButton);\n            elements.shareButton?.classList.add('inline-flex');\n        }\n        if (elements.titleInput) {\n            elements.titleInput.readOnly = false;\n            elements.titleInput.classList.remove('pointer-events-none');\n        }\n    };\n\n    lock();\n\n    // \u201ESave as\" vytvo\u0159ilo kopii pod aktu\u00E1ln\u00EDm u\u017Eivatelem \u2014 mapId se zm\u011Bnilo\n    // a u\u017Eivatel je vlastn\u00EDkem, editace se odemyk\u00E1.\n    on('map:saved', ({ map }) => {\n        if (ctx.readOnly && map?.id && map.id !== ctx.bootstrap.map?.id) {\n            ctx.readOnly = false;\n            ctx.bootstrap.canEdit = true;\n            ctx.bootstrap.can_edit = true;\n            // Kopie pat\u0159\u00ED aktu\u00E1ln\u00EDmu u\u017Eivateli (modal kredit\u016F, hl\u00EDd\u00E1n\u00ED zm\u011Bn).\n            ctx.bootstrap.isOwner = true;\n            unlock();\n        }\n    });\n}\n\n/** Re\u017Eim sd\u00EDlen\u00E9ho odkazu (`bootstrap.sharedView`): prohl\u00ED\u017Een\u00ED ciz\u00EDch dat bez\n * ukl\u00E1d\u00E1n\u00ED \u2014 co by n\u00E1v\u0161t\u011Bvn\u00EDk ztratil, se v tomto re\u017Eimu ani nenab\u00EDz\u00ED. Styl,\n * m\u011B\u0159en\u00ED a export z\u016Fst\u00E1vaj\u00ED jako ochutn\u00E1vka, zm\u011Bny se neukl\u00E1daj\u00ED. */\nexport function applySharedView(ctx, elements) {\n    const shared = ctx.bootstrap.sharedView;\n    if (!shared) return;\n    ctx.readOnly = true;\n    ctx.sharedView = true;\n    ctx.state.title = shared.title;\n    [\n        elements.saveButton,\n        elements.saveAsButton?.closest('.hs-dropdown'),\n        elements.openButton,\n        elements.newButton,\n        elements.addDataButton,\n        elements.newGroupButton,\n        elements.saveStatus,\n    ].forEach(hide);\n    if (elements.titleInput) {\n        elements.titleInput.value = shared.title;\n        elements.titleInput.readOnly = true;\n        elements.titleInput.classList.add('pointer-events-none');\n    }\n}\n\n/* ---------------------------------------------------------------------------\n * Share modal\n * ------------------------------------------------------------------------- */\n\n/** Propoj\u00ED tla\u010D\u00EDtko Share a modal. `openOverlay` dod\u00E1v\u00E1 main.js (Preline). */\nexport function initShare(ctx, elements, { openOverlay, closeOverlay } = {}) {\n    const els = {\n        button: elements.shareButton,\n        slow: document.getElementById('map-share-slow'),\n        accessInfo: document.getElementById('map-share-access-info'),\n        modeSection: document.getElementById('map-share-mode-section'),\n        modeError: document.getElementById('map-share-mode-error'),\n        urlInput: document.getElementById('map-share-url'),\n        copyButton: document.getElementById('map-share-copy'),\n        includeView: document.getElementById('map-share-include-view'),\n        inviteSection: document.getElementById('map-share-invite-section'),\n        inviteForm: document.getElementById('map-share-invite-form'),\n        inviteEmail: document.getElementById('map-share-invite-email'),\n        inviteRole: document.getElementById('map-share-invite-role'),\n        inviteError: document.getElementById('map-share-invite-error'),\n        list: document.getElementById('map-share-list'),\n        teamSection: document.getElementById('map-share-team-section'),\n        teamToggle: document.getElementById('map-share-team-toggle'),\n        teamRole: document.getElementById('map-share-team-role'),\n        teamEditors: document.getElementById('map-share-team-editors'),\n        credits: document.getElementById('map-share-credits'),\n        teamName: document.getElementById('map-share-team-name'),\n        teamError: document.getElementById('map-share-team-error'),\n    };\n    const modal = document.getElementById('map-share-modal');\n    if (!els.button || !modal) return;\n\n    const modeRadios = Array.from(modal.querySelectorAll('input[name=\"map-share-mode\"]'));\n    let isOwner = false;\n    let shares = [];\n\n    /* --- Z\u00E1lo\u017Eky: lid\u00E9 a odkaz / mapa jako WMS (service.js) ---------------- */\n    const tabs = document.getElementById('map-share-tabs');\n    const wmsPanel = document.getElementById('map-share-wms');\n    const serviceTab = wmsPanel ? initServiceTab(ctx, wmsPanel) : null;\n    let activeTab = 'people';\n\n    function selectTab(name) {\n        activeTab = name === 'wms' && serviceTab ? 'wms' : 'people';\n        tabs?.querySelectorAll('[data-share-tab]').forEach((button) => {\n            const on = button.dataset.shareTab === activeTab;\n            button.setAttribute('aria-pressed', on ? 'true' : 'false');\n            button.classList.toggle('border-brand-600', on);\n            button.classList.toggle('font-semibold', on);\n            button.classList.toggle('text-slate-900', on);\n            button.classList.toggle('border-transparent', !on);\n            button.classList.toggle('font-medium', !on);\n            button.classList.toggle('text-slate-500', !on);\n        });\n        const body = document.getElementById('map-share-body');\n        body?.classList.toggle('hidden', activeTab !== 'people');\n        wmsPanel?.classList.toggle('hidden', activeTab !== 'wms');\n        if (activeTab === 'wms') serviceTab.open();\n    }\n\n    function showTabs(visible) {\n        if (!tabs) return;\n        tabs.classList.toggle('hidden', !visible);\n        tabs.classList.toggle('flex', visible);\n        if (!visible && activeTab === 'wms') selectTab('people');\n    }\n\n    tabs?.addEventListener('click', (event) => {\n        const button = event.target.closest('[data-share-tab]');\n        if (button) selectTab(button.dataset.shareTab);\n    });\n\n    /** Share je vid\u011Bt i u neulo\u017Een\u00E9 mapy: kdo mapu zkou\u0161\u00ED, m\u00E1 zjistit, \u017Ee ji\n     * m\u016F\u017Ee sd\u00EDlet. Dialog ji pak nejd\u0159\u00EDv ulo\u017E\u00ED (`setup`). */\n    function updateButtonVisibility() {\n        // Uk\u00E1zkov\u00E1 mapa jen pro \u010Dten\u00ED nab\u00EDz\u00ED m\u00EDsto sd\u00EDlen\u00ED \u201ESave a copy\u201C (applyReadOnlyMode),\n        // sd\u00EDlen\u00FD odkaz na data (applySharedView) se neukl\u00E1d\u00E1.\n        if (!ctx.bootstrap.sharedView && !ctx.sampleReadOnly) {\n            show(els.button);\n            els.button.classList.add('inline-flex');\n        } else {\n            hide(els.button);\n            els.button.classList.remove('inline-flex');\n        }\n    }\n\n    function updateUrlField() {\n        if (els.urlInput) els.urlInput.value = buildShareUrl(ctx, els.includeView?.checked);\n    }\n\n    function setModeRadios(mode) {\n        modeRadios.forEach((radio) => { radio.checked = radio.value === mode; });\n    }\n\n    /** Sekce \u201EShare with team\" (zad\u00E1n\u00ED 07) \u2014 jen vlastn\u00EDk v t\u00FDmu s dal\u0161\u00EDmi \u010Dleny. */\n    function renderTeam(team) {\n        if (!els.teamSection) return;\n        hide(els.teamError);\n        if (!team || !team.available) {\n            hide(els.teamSection);\n            return;\n        }\n        if (els.teamName) {\n            const others = Number(team.members || 0);\n            els.teamName.textContent = `\u00B7 ${team.team_name} (${others} member${others === 1 ? '' : 's'})`;\n        }\n        if (els.teamToggle) els.teamToggle.checked = !!team.shared;\n        if (els.teamRole) {\n            els.teamRole.value = team.permission || 'read';\n            els.teamRole.disabled = !team.shared;\n        }\n        teamState = team;\n        syncTeamEditors();\n        show(els.teamSection);\n    }\n\n    /** Zobrazen\u00ED mapy plat\u00ED jej\u00ED vlastn\u00EDk za v\u0161echny div\u00E1ky \u2014 z\u016Fstatek a varov\u00E1n\u00ED. */\n    function renderCredits(credits) {\n        if (!els.credits) return;\n        if (!credits || !credits.enabled) {\n            hide(els.credits);\n            return;\n        }\n        const balance = Number(credits.available || 0).toLocaleString(undefined, { maximumFractionDigits: 1 });\n        const images = Number(credits.images_per_credit || 0);\n        const per = images ? ` (about ${images} map images per credit)` : '';\n        const link = credits.credits_url\n            ? ` <a href=\"${credits.credits_url}\" target=\"_blank\" rel=\"noopener\" class=\"font-semibold underline\">Add credits</a>`\n            : '';\n        els.credits.className = credits.low\n            ? 'rounded-lg bg-amber-50 px-3 py-2.5 text-xs text-amber-900 ring-1 ring-inset ring-amber-200'\n            : 'rounded-lg bg-slate-50 px-3 py-2.5 text-xs text-slate-600';\n        els.credits.innerHTML = `Every view of this map \u2014 yours and everyone you share it with \u2014 is paid from your credits${per}. `\n            + `Your balance: <strong>${balance} credits</strong>.`\n            + (credits.low ? ' When it runs out, people stop seeing your map and we let you know by e-mail.' + link : '');\n    }\n\n    /** \u201EN z M \u010Dlen\u016F sm\u00ED upravovat\u201C \u2014 nastaven\u00ED \u010Dlena \u201ETeam data\u201C m\u016F\u017Ee Can edit omezit. */\n    let teamState = null;\n    function syncTeamEditors() {\n        if (!els.teamEditors || !teamState) return;\n        const members = Number(teamState.members || 0);\n        const editors = Number(teamState.editors ?? members);\n        const limited = els.teamToggle?.checked && els.teamRole?.value === 'edit' && editors < members;\n        els.teamEditors.textContent = limited\n            ? `${editors} of ${members} member${members === 1 ? '' : 's'} can edit \u2014 the others can only view, because of their \u201CTeam data\u201D setting.`\n            : '';\n        els.teamEditors.classList.toggle('hidden', !limited);\n    }\n\n    async function saveTeamShare() {\n        if (!isOwner || !els.teamToggle) return;\n        hide(els.teamError);\n        const permission = els.teamToggle.checked ? (els.teamRole?.value || 'read') : 'none';\n        els.teamToggle.disabled = true;\n        try {\n            const team = await apiFetch(`${ctx.bootstrap.apiBase}/maps/${ctx.state.mapId}/team-share/`, {\n                method: 'PUT',\n                body: JSON.stringify({ permission }),\n            });\n            renderTeam(team);\n        } catch (error) {\n            els.teamToggle.checked = !els.teamToggle.checked;\n            showError(els.teamError, apiErrorMessage(error, 'Failed to update team sharing.'));\n        } finally {\n            els.teamToggle.disabled = false;\n            if (els.teamRole) els.teamRole.disabled = !els.teamToggle.checked;\n        }\n    }\n\n    function renderShares() {\n        if (!els.list) return;\n        if (shares.length === 0) {\n            els.list.innerHTML = '<p class=\"text-sm text-slate-400\">No one has been invited yet.</p>';\n            return;\n        }\n        els.list.innerHTML = shares.map((share) => `\n            <div class=\"flex items-center gap-x-2 rounded-lg border border-slate-200 px-3 py-2\" data-share-id=\"${share.id}\">\n                <span class=\"min-w-0 flex-1 truncate text-sm text-slate-800\" title=\"${escapeHtml(share.email)}\">${escapeHtml(share.email)}</span>\n                <span class=\"flex-none rounded-full px-2 py-0.5 text-[11px] font-medium ${share.user_exists\n        ? 'bg-emerald-50 text-emerald-700 ring-1 ring-emerald-200'\n        : 'bg-slate-50 text-slate-500 ring-1 ring-slate-200'}\">${share.user_exists ? 'registered' : 'pending'}</span>\n                <select data-role=\"share-role\" class=\"form-select !w-28 flex-none !py-1 !text-xs\">\n                    <option value=\"viewer\" ${share.role === 'viewer' ? 'selected' : ''}>Can view</option>\n                    <option value=\"editor\" ${share.role === 'editor' ? 'selected' : ''}>Can edit</option>\n                </select>\n                <button type=\"button\" data-role=\"share-remove\" title=\"Remove\"\n                        class=\"flex-none rounded p-1 text-slate-400 hover:bg-red-50 hover:text-red-600\">\n                    <svg class=\"h-4 w-4\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\"><path d=\"M3 6h18M8 6V4h8v2m-9 0 1 14h8l1-14\"/></svg>\n                </button>\n            </div>\n        `).join('');\n    }\n\n    function showError(el, message) {\n        if (!el) return;\n        el.textContent = message;\n        show(el);\n    }\n\n    /** Na\u010Dte shares (jen vlastn\u00EDk) a p\u0159epne modal do re\u017Eimu vlastn\u00EDk/host. */\n    async function refresh() {\n        hide(els.modeError);\n        hide(els.inviteError);\n        updateUrlField();\n        try {\n            const data = await apiFetch(`${ctx.bootstrap.apiBase}/maps/${ctx.state.mapId}/shares/`);\n            // Nep\u0159ihl\u00E1\u0161en\u00FD u\u017Eivatel dostane redirect na login (HTML) \u2014 chov\u00E1 se\n            // stejn\u011B jako ne-vlastn\u00EDk.\n            if (!data || typeof data !== 'object' || !Array.isArray(data.shares)) throw new Error('404');\n            isOwner = true;\n            shares = data.shares;\n            setModeRadios(data.share_mode || ctx.bootstrap.share_mode || 'private');\n            show(els.modeSection);\n            show(els.inviteSection);\n            hide(els.accessInfo);\n            renderShares();\n            renderTeam(data.team);\n            renderCredits(data.credits);\n            // Mapu jako WMS zve\u0159ej\u0148uje jen p\u0159ihl\u00E1\u0161en\u00FD vlastn\u00EDk.\n            showTabs(Boolean(ctx.bootstrap.isAuthenticated));\n        } catch (error) {\n            showTabs(false);\n            hide(els.credits);\n            if (!isNotFoundError(error)) {\n                console.warn('Failed to load map shares:', error);\n            }\n            isOwner = false;\n            shares = [];\n            hide(els.modeSection);\n            hide(els.inviteSection);\n            hide(els.teamSection);\n            // Anonymn\u00ED vlastn\u00EDk: shares API vy\u017Eaduje p\u0159ihl\u00E1\u0161en\u00ED (redirect) \u2014\n            // nejde o \u201Eciz\u00ED sd\u00EDlenou mapu\u201C, jen o chyb\u011Bj\u00EDc\u00ED \u00FA\u010Det.\n            let roleText;\n            if (ctx.bootstrap.isOwner) {\n                roleText = 'Sign in to invite people or change link sharing of this map.';\n            } else if (ctx.bootstrap.canEdit) {\n                roleText = 'You have edit access to this shared map.';\n            } else {\n                roleText = 'You have view access to this shared map. Use \u201CSave as\u201D to keep your own copy.';\n            }\n            showError(els.accessInfo, roleText);\n            els.accessInfo?.classList.remove('text-red-600');\n        }\n    }\n\n    /** Upozorn\u011Bn\u00ED na pomal\u00E9 vrstvy: kdo mapu dostane, \u010Dekal by na ka\u017Ed\u00E9\n     * p\u0159ekreslen\u00ED. Vlastn\u00EDkovi dat nab\u00EDdne p\u0159evod (dialog advisor.js). */\n    function renderSlowLayers() {\n        if (!els.slow) return;\n        const slow = slowItems(ctx);\n        els.slow.classList.toggle('hidden', slow.length === 0);\n        if (slow.length === 0) return;\n        const esc = (value) => String(value ?? '').replace(/[&<>\"]/g, (c) => ({\n            '&': '&amp;', '<': '&lt;', '>': '&gt;', '\"': '&quot;',\n        })[c]);\n        const rows = slow.slice(0, 4).map(({ entry, verdict }) => `\n            <li class=\"flex items-center justify-between gap-x-3\">\n                <span class=\"min-w-0 truncate\">${esc(entry.source?.name || entry.itemTitle || entry.title)}\n                    <span class=\"text-amber-700\">\u2014 about ${verdict.seconds >= 10 ? Math.round(verdict.seconds) : verdict.seconds.toFixed(1)} s per redraw</span></span>\n                <button type=\"button\" data-item=\"${esc(entry.itemId)}\" class=\"flex-none font-semibold underline underline-offset-2 hover:no-underline\">Speed up\u2026</button>\n            </li>`).join('');\n        els.slow.innerHTML = `\n            <p class=\"font-medium\">${slow.length === 1 ? 'One layer of this map draws slowly' : `${slow.length} layers of this map draw slowly`}</p>\n            <p class=\"mt-0.5 text-xs text-amber-800\">People you share the map with will wait this long every time they move or zoom it.</p>\n            <ul class=\"mt-1.5 space-y-1 text-xs\">${rows}</ul>\n            ${slow.length > 4 ? `<p class=\"mt-1 text-xs text-amber-800\">+ ${slow.length - 4} more</p>` : ''}`;\n        els.slow.querySelectorAll('button[data-item]').forEach((button) => {\n            button.addEventListener('click', () => {\n                closeOverlay?.(modal);\n                emit('advisor:open', { itemId: button.dataset.item });\n            });\n        });\n    }\n\n    /* --- Sd\u00EDlen\u00ED za\u010D\u00EDn\u00E1 ulo\u017Een\u00EDm: neulo\u017Een\u00E1 mapa nebo mapa bez \u00FA\u010Dtu --------- */\n\n    const setup = document.getElementById('map-share-setup');\n    const body = document.getElementById('map-share-body');\n    const setupEls = {\n        intro: setup?.querySelector('[data-role=\"intro\"]'),\n        titleField: setup?.querySelector('[data-role=\"title-field\"]'),\n        title: document.getElementById('map-share-title'),\n        error: setup?.querySelector('[data-role=\"error\"]'),\n        signedIn: setup?.querySelector('[data-role=\"signed-in\"]'),\n        anonymous: setup?.querySelector('[data-role=\"anonymous\"]'),\n        saveShare: setup?.querySelector('[data-role=\"save-share\"]'),\n        signIn: setup?.querySelector('[data-role=\"sign-in\"]'),\n        signUp: setup?.querySelector('[data-role=\"sign-up\"]'),\n    };\n\n    /** Nep\u0159ihl\u00E1\u0161en\u00FD vlastn\u00EDk mapy: odkaz by nikomu nepomohl (mapa bez \u00FA\u010Dtu je\n     * soukrom\u00E1 a pozv\u00E1nky pot\u0159ebuj\u00ED p\u0159ihl\u00E1\u0161en\u00ED) \u2014 nab\u00EDdne se \u00FA\u010Det zdarma. */\n    function needsAccount() {\n        return !ctx.bootstrap.isAuthenticated && ctx.bootstrap.isOwner !== false;\n    }\n\n    function needsSetup() {\n        return Boolean(setup) && (!ctx.state.mapId || needsAccount());\n    }\n\n    function showSetup() {\n        const anonymous = needsAccount();\n        hide(setupEls.error);\n        setupEls.intro.textContent = anonymous\n            ? 'Sign in or create a free account to share this map. Your map stays as it is and becomes yours.'\n            : 'Save the map first \u2014 then you can share it right away.';\n        setupEls.titleField.classList.toggle('hidden', anonymous);\n        setupEls.signedIn.classList.toggle('hidden', anonymous);\n        setupEls.anonymous.classList.toggle('hidden', !anonymous);\n        if (setupEls.title) setupEls.title.value = ctx.state.title || '';\n        hide(body);\n        hide(wmsPanel);\n        showTabs(false);\n        show(setup);\n    }\n\n    function showBody() {\n        hide(setup);\n        selectTab('people');\n        renderSlowLayers();\n        refresh();\n    }\n\n    function setSetupBusy(busy) {\n        [setupEls.saveShare, setupEls.signIn, setupEls.signUp].forEach((button) => {\n            if (button) button.disabled = busy;\n        });\n    }\n\n    /** Ulo\u017E\u00ED mapu bez ozn\u00E1men\u00ED \u201EMap saved\u2026\u201C \u2014 dialog sd\u00EDlen\u00ED je otev\u0159en\u00FD. */\n    async function saveQuietly() {\n        hide(setupEls.error);\n        setSetupBusy(true);\n        try {\n            await saveMap(ctx, { quiet: true });\n            if (elements.saveStatus) elements.saveStatus.textContent = 'Saved';\n            return true;\n        } catch (error) {\n            showError(setupEls.error, apiErrorMessage(error, 'Failed to save the map. Please try again.'));\n            return false;\n        } finally {\n            setSetupBusy(false);\n        }\n    }\n\n    async function saveAndShare() {\n        const title = setupEls.title?.value.trim();\n        if (title) ctx.state.title = title;\n        if (await saveQuietly()) showBody();\n    }\n\n    /** Ulo\u017E\u00ED (neulo\u017Eenou nebo zm\u011Bn\u011Bnou) mapu a po\u0161le n\u00E1v\u0161t\u011Bvn\u00EDka na p\u0159ihl\u00E1\u0161en\u00ED\n     * \u010Di registraci s n\u00E1vratem na ni. Po p\u0159ihl\u00E1\u0161en\u00ED mapa p\u0159ejde na jeho \u00FA\u010Det\n     * (`apps.maps.signals.claim_visitor_maps`). */\n    async function continueWithAccount(signup) {\n        if ((!ctx.state.mapId || ctx.state.dirty) && !(await saveQuietly())) return;\n        const viewerBase = ctx.bootstrap.apiBase.replace(/\\/api$/, '');\n        const params = new URLSearchParams({ next: `${viewerBase}/${ctx.state.mapId}/` });\n        if (signup) params.set('signup', '1');\n        const loginBase = ctx.bootstrap.loginBase || String(ctx.bootstrap.loginUrl || '').split('?')[0];\n        window.location.assign(`${loginBase}?${params}`);\n    }\n\n    setupEls.saveShare?.addEventListener('click', saveAndShare);\n    setupEls.title?.addEventListener('keydown', (event) => {\n        if (event.key === 'Enter') {\n            event.preventDefault();\n            saveAndShare();\n        }\n    });\n    setupEls.signIn?.addEventListener('click', () => continueWithAccount(false));\n    setupEls.signUp?.addEventListener('click', () => continueWithAccount(true));\n\n    els.button.addEventListener('click', () => {\n        if (needsSetup()) {\n            showSetup();\n            openOverlay?.(modal);\n            // Psan\u00ED rovnou p\u0159ep\u00ED\u0161e \u201EUntitled map\u201C.\n            if (!needsAccount()) window.setTimeout(() => setupEls.title?.select(), 120);\n            return;\n        }\n        hide(setup);\n        selectTab(els.button.dataset.openTab || 'people');\n        delete els.button.dataset.openTab;\n        openOverlay?.(modal);\n        renderSlowLayers();\n        refresh();\n    });\n\n    // `?share=wms` (galerie map v Console \u2192 \u201EMap service (WMS)\u2026\u201C): dialog se\n    // otev\u0159e rovnou na z\u00E1lo\u017Ece mapov\u00E9 slu\u017Eby.\n    const params = new URLSearchParams(window.location.search);\n    if (params.get('share') === 'wms') {\n        params.delete('share');\n        const query = params.toString();\n        window.history.replaceState(null, '', window.location.pathname + (query ? `?${query}` : '') + window.location.hash);\n        if (ctx.state.mapId && ctx.bootstrap.isOwner && ctx.bootstrap.isAuthenticated) {\n            window.setTimeout(() => {\n                els.button.dataset.openTab = 'wms';\n                els.button.click();\n            }, 600);\n        }\n    }\n\n    els.includeView?.addEventListener('change', updateUrlField);\n    els.teamToggle?.addEventListener('change', saveTeamShare);\n    els.teamRole?.addEventListener('change', () => { syncTeamEditors(); if (els.teamToggle?.checked) saveTeamShare(); });\n\n    els.copyButton?.addEventListener('click', async () => {\n        updateUrlField();\n        const url = els.urlInput?.value || '';\n        try {\n            await navigator.clipboard.writeText(url);\n        } catch {\n            // Fallback pro prohl\u00ED\u017Ee\u010De bez Clipboard API (nebo bez HTTPS).\n            els.urlInput?.select();\n            document.execCommand('copy');\n        }\n        const original = els.copyButton.textContent;\n        els.copyButton.textContent = 'Copied!';\n        setTimeout(() => { els.copyButton.textContent = original; }, 1500);\n    });\n\n    // Zm\u011Bna share_mode \u2014 PUT mapy (sm\u00ED jen vlastn\u00EDk; radia jsou vid\u011Bt jen jemu).\n    modeRadios.forEach((radio) => {\n        radio.addEventListener('change', async () => {\n            if (!radio.checked || !isOwner) return;\n            hide(els.modeError);\n            try {\n                await apiFetch(`${ctx.bootstrap.apiBase}/maps/${ctx.state.mapId}/`, {\n                    method: 'PUT',\n                    body: JSON.stringify({ share_mode: radio.value }),\n                });\n                ctx.bootstrap.share_mode = radio.value;\n            } catch (error) {\n                showError(els.modeError, apiErrorMessage(error, 'Failed to change link sharing.'));\n                setModeRadios(ctx.bootstrap.share_mode || 'private');\n            }\n        });\n    });\n\n    // Pozv\u00E1nka \u2014 POST shares; 400 (duplicitn\u00ED/neplatn\u00FD e-mail) se uk\u00E1\u017Ee u formul\u00E1\u0159e.\n    els.inviteForm?.addEventListener('submit', async (event) => {\n        event.preventDefault();\n        hide(els.inviteError);\n        const email = els.inviteEmail?.value.trim();\n        if (!email) return;\n        try {\n            const share = await apiFetch(`${ctx.bootstrap.apiBase}/maps/${ctx.state.mapId}/shares/`, {\n                method: 'POST',\n                body: JSON.stringify({ email, role: els.inviteRole?.value || 'viewer' }),\n            });\n            shares.unshift(share);\n            if (els.inviteEmail) els.inviteEmail.value = '';\n            renderShares();\n        } catch (error) {\n            showError(els.inviteError, apiErrorMessage(error, 'Failed to send the invitation.'));\n        }\n    });\n\n    // Delegovan\u00E9 akce v seznamu pozv\u00E1nek: zm\u011Bna role (PUT) a odebr\u00E1n\u00ED (DELETE).\n    els.list?.addEventListener('change', async (event) => {\n        const select = event.target.closest('[data-role=\"share-role\"]');\n        if (!select) return;\n        const shareId = select.closest('[data-share-id]')?.dataset.shareId;\n        const share = shares.find((s) => String(s.id) === shareId);\n        if (!share) return;\n        hide(els.inviteError);\n        try {\n            const updated = await apiFetch(\n                `${ctx.bootstrap.apiBase}/maps/${ctx.state.mapId}/shares/${share.id}/`,\n                { method: 'PUT', body: JSON.stringify({ role: select.value }) },\n            );\n            share.role = updated.role;\n        } catch (error) {\n            showError(els.inviteError, apiErrorMessage(error, 'Failed to change the role.'));\n            select.value = share.role;\n        }\n    });\n\n    els.list?.addEventListener('click', async (event) => {\n        const button = event.target.closest('[data-role=\"share-remove\"]');\n        if (!button) return;\n        const shareId = button.closest('[data-share-id]')?.dataset.shareId;\n        const share = shares.find((s) => String(s.id) === shareId);\n        if (!share) return;\n        hide(els.inviteError);\n        try {\n            await apiFetch(\n                `${ctx.bootstrap.apiBase}/maps/${ctx.state.mapId}/shares/${share.id}/`,\n                { method: 'DELETE' },\n            );\n            shares = shares.filter((s) => s !== share);\n            renderShares();\n        } catch (error) {\n            showError(els.inviteError, apiErrorMessage(error, 'Failed to remove the invitation.'));\n        }\n    });\n\n    // Kopie uk\u00E1zkov\u00E9 mapy (\u201ESave a copy\u201C) u\u017E sd\u00EDlet jde.\n    on('map:saved', updateButtonVisibility);\n    updateButtonVisibility();\n}\n", "/**\n * messaging.js \u2014 komunikace s GeoCzech Console p\u0159es `window.postMessage`\n * (Console b\u011B\u017E\u00ED na jin\u00E9 origin \u2014 v\u017Edy ov\u011B\u0159ujeme `event.origin` proti\n * povolen\u00E9mu seznamu z bootstrap konfigurace \u0161ablony).\n *\n * Protokol:\n *  - viewer \u2192 Console: {type: \"mygeodata:ready\"}            (po na\u010Dten\u00ED)\n *  - Console \u2192 viewer: {type: \"mygeodata:add-item\", itemId} (p\u0159idat vrstvu)\n *  - viewer \u2192 Console: {type: \"mygeodata:item-added\", itemId} (potvrzen\u00ED \u2014\n *    Console podle n\u011Bj pozn\u00E1, \u017Ee mapa b\u011B\u017E\u00ED a nen\u00ED nutn\u00E1 navigace okna)\n *\n * Nav\u00EDc p\u0159i na\u010Dten\u00ED str\u00E1nky zpracuje `?add=<uuid>[,uuid,...]` z URL \u2014\n * umo\u017E\u0148uje otev\u0159\u00EDt mapu s p\u0159edvypln\u011Bn\u00FDmi vrstvami i bez postMessage handshaku\n * (nap\u0159. p\u0159\u00EDm\u00FD odkaz z Console v nov\u00E9m okn\u011B).\n */\nimport { looksLikeUuid } from './utils.js';\n\n/** Nastav\u00ED `window.name`, aby si Console mohla okno naj\u00EDt/znovupou\u017E\u00EDt. */\nexport function setWindowName() {\n    window.name = 'mygeodata-map';\n}\n\n/** Vr\u00E1t\u00ED seznam UUID z `?add=` parametru aktu\u00E1ln\u00ED URL (m\u016F\u017Ee jich b\u00FDt v\u00EDc). */\nexport function parseAddParam() {\n    const params = new URLSearchParams(window.location.search);\n    const raw = params.get('add');\n    if (!raw) return [];\n    return raw.split(',').map((s) => s.trim()).filter(looksLikeUuid);\n}\n\n/** Zaregistruje listener na postMessage z Console a ode\u0161le handshake \"ready\".\n * `onAddItems(itemIds)` se zavol\u00E1 po ov\u011B\u0159en\u00ED origin s validovan\u00FDmi UUID. */\nexport function initMessaging(bootstrap, onAddItems) {\n    setWindowName();\n\n    const allowedOrigins = new Set(bootstrap.allowedOrigins || []);\n\n    window.addEventListener('message', (event) => {\n        if (!allowedOrigins.has(event.origin)) return;\n        const data = event.data;\n        if (!data || typeof data !== 'object') return;\n        if (data.type === 'mygeodata:add-item' && looksLikeUuid(data.itemId)) {\n            onAddItems([data.itemId]);\n            // Potvrzen\u00ED odes\u00EDlateli \u2014 bez n\u011Bj by Console okno mapy navigovala\n            // znovu (fallback `?add=`) a ztratil by se rozpracovan\u00FD stav.\n            if (event.source) {\n                try {\n                    event.source.postMessage(\n                        { type: 'mygeodata:item-added', itemId: data.itemId },\n                        event.origin,\n                    );\n                } catch {\n                    // Odesilatel mohl okno mezit\u00EDm zav\u0159\u00EDt \u2014 nekritick\u00E9.\n                }\n            }\n        }\n    });\n\n    // Handshake \"ready\" \u2014 po\u0161leme oknu, kter\u00E9 n\u00E1s otev\u0159elo (opener), pokud jeho\n    // origin je na povolen\u00E9m seznamu (jinak pos\u00EDl\u00E1me jen na \"*\", co\u017E opener,\n    // kter\u00E9mu na tom nez\u00E1le\u017E\u00ED, ignoruje \u2014 nikdy sem ned\u00E1v\u00E1me citliv\u00E1 data).\n    if (window.opener) {\n        const target = allowedOrigins.size === 1 ? Array.from(allowedOrigins)[0] : '*';\n        try {\n            window.opener.postMessage({ type: 'mygeodata:ready' }, target);\n        } catch {\n            // Cross-origin opener m\u016F\u017Ee vol\u00E1n\u00ED odm\u00EDtnout \u2014 nejde o kritickou chybu.\n        }\n    }\n\n    const addFromUrl = parseAddParam();\n    if (addFromUrl.length > 0) {\n        onAddItems(addFromUrl);\n    }\n}\n", "/**\n * items.js \u2014 modal \"Add data\": seznam polo\u017Eek workspace (GET /map/api/items/)\n * s n\u00E1hledy, filtrem vektor/rastr a fulltextov\u00FDm hled\u00E1n\u00EDm. Kliknut\u00EDm na\n * polo\u017Eku se p\u0159id\u00E1 jako nov\u00E1 vrstva. Tla\u010D\u00EDtko \u201EUpload files\u201C nahr\u00E1v\u00E1 p\u0159\u00EDmo\n * z mapy (upload.js); nahran\u00E1 data se do seznamu dostanou po `invalidateItems`.\n * Hybrid (vektor + rastr v jednom souboru) pat\u0159\u00ED do filtru Vector i Raster.\n */\nimport { apiFetch } from './utils.js';\nimport { HYBRID_ICON_PATHS } from './hybrid.js';\n\nlet cachedItems = null;\n\n/** Typy polo\u017Eek pat\u0159\u00EDc\u00ED pod filtr (hybrid m\u00E1 vektorovou i rastrovou \u010D\u00E1st). */\nconst FILTER_TYPES = {\n    vector: ['vector', 'hybrid'],\n    raster: ['raster', 'hybrid'],\n};\n\n/** Zahod\u00ED na\u010Dten\u00FD seznam (po nahr\u00E1n\u00ED z mapy p\u0159ibyla data). */\nexport function invalidateItems() {\n    cachedItems = null;\n}\n\nasync function loadItems(ctx) {\n    if (cachedItems) return cachedItems;\n    const data = await apiFetch(`${ctx.bootstrap.apiBase}/items/`);\n    cachedItems = data.items || [];\n    return cachedItems;\n}\n\nfunction typeBadge(item) {\n    if (item.data_type === 'raster') {\n        return `<span class=\"chip chip-neutral\">Raster \u00B7 ${item.band_count ?? '?'} bands</span>`;\n    }\n    const geoms = (item.geometry_types || []).join(', ') || '\u2014';\n    if (item.data_type === 'hybrid') {\n        return `<span class=\"chip chip-neutral\">Vector + raster \u00B7 ${geoms} \u00B7 ${item.band_count ?? '?'} bands</span>`;\n    }\n    return `<span class=\"chip chip-neutral\">Vector \u00B7 ${geoms}</span>`;\n}\n\n/** Ikona polo\u017Eky bez n\u00E1hledu (hybrid m\u00E1 vlastn\u00ED). */\nfunction placeholderIcon(item) {\n    if (item.data_type === 'hybrid') {\n        return `<svg class=\"h-6 w-6 text-violet-600\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\">${HYBRID_ICON_PATHS}</svg>`;\n    }\n    return '<svg class=\"h-6 w-6\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\"><path d=\"M3 3v18h18\"/><path d=\"m7 14 4-4 3 3 5-6\"/></svg>';\n}\n\nfunction itemCard(item, onAdd) {\n    const card = document.createElement('button');\n    card.type = 'button';\n    card.className = 'flex items-center gap-x-3 rounded-xl border border-slate-200 bg-white p-3 text-left transition-colors hover:border-brand-300 hover:bg-brand-50/40';\n    card.innerHTML = `\n        <div class=\"preview-bg h-12 w-12 flex-none overflow-hidden rounded-lg border border-slate-200\">\n            ${item.preview_url\n                ? `<img src=\"${item.preview_url}\" alt=\"\" class=\"h-full w-full object-cover\">`\n                : `<div class=\"flex h-full w-full items-center justify-center text-slate-300\">${placeholderIcon(item)}</div>`}\n        </div>\n        <div class=\"min-w-0 flex-1\">\n            <p class=\"truncate text-sm font-medium text-slate-900\">${item.title}</p>\n            <div class=\"mt-1 flex flex-wrap items-center gap-1\">${typeBadge(item)}</div>\n        </div>\n    `;\n    card.addEventListener('click', () => onAdd(item.id, item.title, item));\n    return card;\n}\n\n/** Napln\u00ED/aktualizuje seznam podle aktu\u00E1ln\u00EDho filtru + hledan\u00E9ho textu. */\nfunction applyFilter(items, filter, search) {\n    const q = search.trim().toLowerCase();\n    return items.filter((item) => {\n        if (filter !== 'all' && !(FILTER_TYPES[filter] || [filter]).includes(item.data_type)) return false;\n        if (q && !item.title.toLowerCase().includes(q)) return false;\n        return true;\n    });\n}\n\n/**\n * Z\u00E1lo\u017Eka \u201ESamples\u201C v modalu \"Add data\": uk\u00E1zkov\u00E1 data MyGeodata\n * (GET /map/api/samples/items/, apps.workspace.samples). P\u0159idaj\u00ED se jako\n * vrstva stejn\u011B jako data z workspace \u2014 kresl\u00ED se zdarma a nic se nekop\u00EDruje.\n * Skryt\u00E1, kdy\u017E si u\u017Eivatel uk\u00E1zky vypnul (`bootstrap.showSamples`).\n */\nexport function initSampleData(ctx, modal, onAdd) {\n    const tab = modal?.querySelector('[data-role=\"add-tab\"][data-tab=\"samples\"]');\n    const list = modal?.querySelector('#map-samples-list');\n    const searchInput = modal?.querySelector('#map-samples-search');\n    if (!tab || !list || !ctx.bootstrap.showSamples || ctx.bootstrap.sharedView) return;\n    tab.classList.remove('hidden');\n    let items = null;\n    let search = '';\n\n    async function render() {\n        if (items === null) {\n            list.innerHTML = '<p class=\"col-span-full py-8 text-center text-sm text-slate-400\">Loading\u2026</p>';\n            try {\n                const data = await apiFetch(`${ctx.bootstrap.apiBase}/samples/items/`);\n                items = data.items || [];\n            } catch (error) {\n                list.innerHTML = `<p class=\"col-span-full py-8 text-center text-sm text-red-500\">Failed to load sample data: ${error.message}</p>`;\n                return;\n            }\n        }\n        const filtered = applyFilter(items, 'all', search);\n        list.innerHTML = '';\n        if (filtered.length === 0) {\n            list.innerHTML = '<p class=\"col-span-full py-8 text-center text-sm text-slate-400\">Nothing found.</p>';\n            return;\n        }\n        filtered.forEach((item) => list.appendChild(itemCard(item, onAdd)));\n    }\n\n    tab.addEventListener('click', render);\n    searchInput?.addEventListener('input', (e) => {\n        search = e.target.value;\n        render();\n    });\n}\n\n/**\n * Inicializuje modal \"Add data\". `elements` = { modal, list, search, filterButtons },\n * `onAdd(itemId)` se zavol\u00E1 po kliknut\u00ED na polo\u017Eku.\n */\nexport function initAddDataModal(ctx, elements, onAdd) {\n    let filter = 'all';\n    let search = '';\n\n    async function renderList() {\n        elements.list.innerHTML = '<p class=\"col-span-full py-8 text-center text-sm text-slate-400\">Loading\u2026</p>';\n        try {\n            const items = await loadItems(ctx);\n            const filtered = applyFilter(items, filter, search);\n            elements.list.innerHTML = '';\n            if (filtered.length === 0) {\n                const text = items.length === 0\n                    ? 'No data yet \u2014 upload your files and they appear on the map.'\n                    : 'Nothing found.';\n                elements.list.innerHTML = `<p class=\"col-span-full py-8 text-center text-sm text-slate-400\">${text}</p>`;\n                return;\n            }\n            filtered.forEach((item) => elements.list.appendChild(itemCard(item, onAdd)));\n        } catch (error) {\n            elements.list.innerHTML = `<p class=\"col-span-full py-8 text-center text-sm text-red-500\">Failed to load data: ${error.message}</p>`;\n        }\n    }\n\n    elements.search?.addEventListener('input', (e) => {\n        search = e.target.value;\n        renderList();\n    });\n\n    elements.filterButtons?.forEach((btn) => {\n        btn.addEventListener('click', () => {\n            filter = btn.dataset.filter || 'all';\n            elements.filterButtons.forEach((b) => b.classList.toggle('is-active', b === btn));\n            renderList();\n        });\n    });\n\n    // Preline modal (`hs-overlay`) vyvol\u00E1 tuto vlastn\u00ED ud\u00E1lost p\u0159i otev\u0159en\u00ED \u2014\n    // data se tak dot\u00E1hnou lazy, ne hned p\u0159i startu appky.\n    elements.modal?.addEventListener('open.hs.overlay', renderList);\n\n    return { refresh: renderList };\n}\n", "/**\n * http.js \u2014 fetch pomocn\u00EDci UI Kitu (JSON + CSRF).\n *\n * Chyby se normalizuj\u00ED na `Error` s `status` a `data` (t\u011Blo odpov\u011Bdi),\n * aby na n\u011B komponenty um\u011Bly reagovat (nap\u0159. 402 = m\u00E1lo kredit\u016F).\n *\n * 402 `insufficient_credits` nav\u00EDc zachyt\u00ED glob\u00E1ln\u00ED handler modalu\n * (components/insufficient_credits.js). Kdo si 402 \u0159e\u0161\u00ED s\u00E1m (pr\u016Fvodce\n * s pokra\u010Dov\u00E1n\u00EDm po n\u00E1kupu), p\u0159ed\u00E1 `{ creditsModal: false }`.\n *\n * Dotaz, na kter\u00FD nep\u0159i\u0161la \u017E\u00E1dn\u00E1 odpov\u011B\u010F (v\u00FDpadek s\u00EDt\u011B, p\u0159epnut\u00ED Wi-Fi / VPN,\n * v Chrome `net::ERR_NETWORK_CHANGED`), se opakuje \u2014 `retry`. `getJSON` to d\u011Bl\u00E1\n * v\u017Edy, `postJSON` jen na vy\u017E\u00E1d\u00E1n\u00ED: opakovat se sm\u00ED jen dotaz, kter\u00FD na serveru\n * nic nezakl\u00E1d\u00E1 (nab\u00EDdky, n\u00E1hled pl\u00E1nu, odhad, validace, nastaven\u00ED hodnoty).\n * Odesl\u00E1n\u00ED \u00FAlohy, zalo\u017Een\u00ED anal\u00FDzy nebo e-mail se opakovat nesm\u00ED \u2014 server je\n * mohl zpracovat, i kdy\u017E odpov\u011B\u010F nedorazila. Chyba po vy\u010Derp\u00E1n\u00ED pokus\u016F m\u00E1\n * `network: true` a hl\u00E1\u0161ku pro u\u017Eivatele m\u00EDsto \u201EFailed to fetch\u201C.\n */\n\n// Pauzy p\u0159ed opakov\u00E1n\u00EDm dotazu bez odpov\u011Bdi. S\u00ED\u0165 se po zm\u011Bn\u011B obnov\u00ED do zlomku\n// vte\u0159iny; celkem se \u010Dek\u00E1 nejv\u00FD\u0161 5 s.\nconst RETRY_DELAYS_MS = [500, 1500, 3000];\nconst NETWORK_ERROR_MESSAGE = 'Could not reach the server \u2014 check your connection';\n\n/** Skon\u010Dil dotaz bez odpov\u011Bdi serveru (v\u00FDpadek nebo zm\u011Bna s\u00EDt\u011B)? */\nexport function isNetworkError(err) {\n    return Boolean(err && err.network);\n}\n\nfunction networkError(cause) {\n    const err = new Error(NETWORK_ERROR_MESSAGE);\n    err.network = true;\n    err.cause = cause;\n    return err;\n}\n\n/** `fetch`, kter\u00FD dotaz bez odpov\u011Bdi zopakuje (`retry`) a chybu s\u00EDt\u011B ozna\u010D\u00ED. */\nasync function send(url, init, retry) {\n    for (let attempt = 0; ; attempt++) {\n        try {\n            return await fetch(url, init);\n        } catch (err) {\n            // Zru\u0161en\u00FD dotaz (`AbortController`) nen\u00ED v\u00FDpadek.\n            if (err && err.name === 'AbortError') throw err;\n            if (!retry || attempt >= RETRY_DELAYS_MS.length) throw networkError(err);\n            await new Promise((resolve) => setTimeout(resolve, RETRY_DELAYS_MS[attempt]));\n        }\n    }\n}\n\nexport function getCookie(name) {\n    const row = document.cookie.split('; ').find((r) => r.startsWith(name + '='));\n    return row ? decodeURIComponent(row.split('=').slice(1).join('=')) : '';\n}\n\n/**\n * Hl\u00E1\u0161ka pro chybovou odpov\u011B\u010F bez vlastn\u00EDho textu: str\u00E1nka 500 z Djanga,\n * 502/504 z load balanceru, 403 ochrany CSRF. U\u017Eivatel m\u00E1 poznat, \u017Ee chyba\n * nen\u00ED u n\u011Bj a co m\u016F\u017Ee ud\u011Blat \u2014 ne hol\u00E9 \u201EHTTP 500\u201C. Stejn\u00E9 texty dr\u017E\u00ED\n * i `static/js/s3uploader.js` (str\u00E1nka nahr\u00E1v\u00E1n\u00ED do Data workspace).\n */\nexport function statusMessage(status) {\n    if (status === 502 || status === 503 || status === 504) {\n        return `The service is temporarily unavailable (HTTP ${status}). Please try again in a few minutes.`;\n    }\n    if (status >= 500) {\n        return (\n            `Something went wrong on our side (HTTP ${status}). Please try again later; ` +\n            'if it keeps happening, contact support.'\n        );\n    }\n    if (status === 403) return 'The request was refused (HTTP 403). Reload the page and try again.';\n    return `The request failed (HTTP ${status}).`;\n}\n\n/**\n * \u010Citeln\u00E1 hl\u00E1\u0161ka z chybov\u00E9 odpov\u011Bdi: `error`/`detail`, jinak slo\u017Een\u00E1 z chyb\n * per pole (`errors: {pole: hl\u00E1\u0161ka}`), a\u017E nakonec obecn\u00E1 hl\u00E1\u0161ka ke stavu.\n */\nexport function responseErrorMessage(data, status) {\n    if (data && typeof data === 'object') {\n        if (data.error) return String(data.error);\n        if (data.detail) return String(data.detail);\n        if (data.errors && typeof data.errors === 'object') {\n            const parts = Object.values(data.errors).filter(Boolean).map(String);\n            if (parts.length) return [...new Set(parts)].join(' ');\n        }\n    }\n    return statusMessage(status);\n}\n\n/** Hl\u00E1\u0161ka pro u\u017Eivatele z chyby vyhozen\u00E9 `getJSON`/`postJSON` (nebo jin\u00E9). */\nexport function errorMessage(err) {\n    if (!err) return 'Unknown error.';\n    if (err.data) return responseErrorMessage(err.data, err.status);\n    return err.message || 'Unknown error.';\n}\n\nasync function handle(resp) {\n    let data = null;\n    try {\n        data = await resp.json();\n    } catch {\n        data = null;\n    }\n    if (!resp.ok) {\n        const message = responseErrorMessage(data, resp.status);\n        const err = new Error(message);\n        err.status = resp.status;\n        err.data = data;\n        throw err;\n    }\n    return data;\n}\n\nexport async function getJSON(url, { creditsModal = true, retry = true } = {}) {\n    const resp = await send(\n        url,\n        {\n            headers: { Accept: 'application/json' },\n            mgCreditsModal: creditsModal,\n        },\n        retry,\n    );\n    return handle(resp);\n}\n\n/**\n * `retry: true` jen u dotazu, kter\u00FD jde bez n\u00E1sledk\u016F poslat dvakr\u00E1t (viz \u00FAvod).\n */\nexport async function postJSON(url, body, { creditsModal = true, retry = false } = {}) {\n    const resp = await send(\n        url,\n        {\n            method: 'POST',\n            mgCreditsModal: creditsModal,\n            headers: {\n                Accept: 'application/json',\n                'Content-Type': 'application/json',\n                'X-CSRFToken': getCookie('csrftoken'),\n            },\n            body: JSON.stringify(body || {}),\n        },\n        retry,\n    );\n    return handle(resp);\n}\n\n/** Debounce (pro na\u0161ept\u00E1va\u010De). */\nexport function debounce(fn, waitMs = 250) {\n    let timer = null;\n    return function debounced(...args) {\n        clearTimeout(timer);\n        timer = setTimeout(() => fn.apply(this, args), waitMs);\n    };\n}\n", "/**\n * errors.js \u2014 hl\u00E1\u0161en\u00ED chyb do Admin \u2192 Tool usage (`static/js/error-beacon.js`).\n *\n * Beacon je samostatn\u00FD skript v hlavi\u010Dce str\u00E1nky, a\u0165 zachyt\u00ED i chyby p\u0159i na\u010D\u00EDt\u00E1n\u00ED\n * bundlu. Tady jen dv\u011B pomocn\u00E9 funkce pro chyby, kter\u00E9 pr\u016Fvodce s\u00E1m o\u0161et\u0159\u00ED, a pro\n * ID b\u011B\u017E\u00EDc\u00ED \u00FAlohy, ke kter\u00E9 se dal\u0161\u00ED chyby na str\u00E1nce p\u0159i\u0159ad\u00ED.\n */\nexport function reportError(message, context) {\n    if (window.mgReportError) window.mgReportError(message, context);\n}\n\nexport function setErrorContext(context) {\n    window.mgErrorContext = { ...(window.mgErrorContext || {}), ...context };\n}\n", "/**\n * s3upload.js \u2014 ES-modulov\u00FD port `static/js/s3uploader.js` (workspace upload\n * str\u00E1nka) pro UI Kit.\n *\n * D\u016ELE\u017DIT\u00C9: ob\u011B verze mus\u00ED z\u016Fstat funk\u010Dn\u011B ve shod\u011B (stejn\u00E9 API/eventy,\n * stejn\u00E1 logika begin \u2192 single PUT / multipart sign-parts + complete, retry\n * a paraleln\u00ED \u010D\u00E1sti, \u00FAklid abortem). Pokud upravuje\u0161 chov\u00E1n\u00ED zde, prove\u010F\n * odpov\u00EDdaj\u00EDc\u00ED zm\u011Bnu i ve `static/js/s3uploader.js` (a naopak).\n *\n * Rozd\u00EDl oproti statick\u00E9 verzi: CSRF token se defaultn\u011B bere z cookie\n * (`getCookie()` z `core/http.js`), vol\u00E1n\u00ED `new S3Uploader({csrfToken})` ho\n * ale m\u016F\u017Ee p\u0159eb\u00EDt (stejn\u00E9 jm\u00E9no opce jako ve star\u00E9 verzi).\n *\n * Backend endpointy (apps.storage):\n *   POST  <beginUrl>                          \u2192 { upload_id, multipart, part_size,\n *                                                 part_count, put_url? , batch }\n *   POST  <uploadsBase><id>/sign-parts/       \u2192 { urls: { \"1\": url, ... } }\n *   POST  <uploadsBase><id>/complete/         \u2192 { ok }\n *   POST  <uploadsBase><id>/abort/            \u2192 { ok }\n *\n * Pou\u017Eit\u00ED:\n *   const up = new S3Uploader({ purpose, batch, on: { ... } });\n *   up.addFiles(fileList); up.start();\n */\nimport { getCookie, responseErrorMessage } from './http.js';\nimport { reportError } from './errors.js';\n\nexport function humanBytes(n) {\n    if (!n && n !== 0) return '';\n    const u = ['B', 'KB', 'MB', 'GB', 'TB'];\n    let i = 0;\n    let v = n;\n    while (v >= 1024 && i < u.length - 1) {\n        v /= 1024;\n        i++;\n    }\n    return (i === 0 ? Math.round(v) : v.toFixed(v < 10 ? 2 : 1)) + ' ' + u[i];\n}\n\nexport function humanTime(s) {\n    if (!isFinite(s) || s < 0) return '\u2014';\n    s = Math.round(s);\n    if (s < 60) return s + 's';\n    const m = Math.floor(s / 60);\n    const sec = s % 60;\n    if (m < 60) return m + 'm ' + sec + 's';\n    const h = Math.floor(m / 60);\n    return h + 'h ' + (m % 60) + 'm';\n}\n\nfunction uid() {\n    return 'f' + Math.random().toString(36).slice(2, 10);\n}\n\nexport class S3Uploader {\n    constructor(opts = {}) {\n        this.beginUrl = opts.beginUrl || '/storage/uploads/begin/';\n        this.uploadsBase = opts.uploadsBase || '/storage/uploads/'; // nap\u0159. \"/storage/uploads/\"\n        this.purpose = opts.purpose;\n        this.batch = opts.batch || null;\n        this.csrfToken = opts.csrfToken || getCookie('csrftoken');\n        this.concurrency = opts.concurrency || 4; // paraleln\u00EDch \u010D\u00E1st\u00ED nar\u00E1z\n        this.maxRetries = opts.maxRetries || 3;\n        this.on = opts.on || {};\n        this.entries = [];\n        this._started = false;\n        this._startTime = null;\n        this._speed = 0; // vyhlazen\u00E1 rychlost (B/s)\n    }\n\n    _emit(name, arg) {\n        if (typeof this.on[name] === 'function') this.on[name](arg);\n    }\n\n    addFiles(fileList) {\n        const added = [];\n        for (let i = 0; i < fileList.length; i++) {\n            const file = fileList[i];\n            const entry = {\n                id: uid(),\n                file,\n                name: file.name,\n                size: file.size,\n                contentType: file.type || 'application/octet-stream',\n                status: 'queued', // queued|uploading|done|error|aborted\n                uploaded: 0,\n                error: '',\n                uploadId: null, // public_id z begin\n                s3UploadId: null, // S3 multipart id (jen info)\n                xhrs: [],\n            };\n            this.entries.push(entry);\n            added.push(entry);\n        }\n        this._emit('filesAdded', added);\n        return added;\n    }\n\n    removeEntry(id) {\n        const idx = this.entries.findIndex((e) => e.id === id);\n        if (idx >= 0 && this.entries[idx].status === 'queued') {\n            this.entries.splice(idx, 1);\n            this._emit('filesAdded', []);\n        }\n    }\n\n    totalBytes() {\n        return this.entries.reduce((s, e) => s + (e.status === 'aborted' ? 0 : e.size), 0);\n    }\n\n    uploadedBytes() {\n        return this.entries.reduce((s, e) => s + e.uploaded, 0);\n    }\n\n    _tick() {\n        const total = this.totalBytes();\n        const done = this.uploadedBytes();\n        const elapsed = (Date.now() - this._startTime) / 1000;\n        const inst = elapsed > 0 ? done / elapsed : 0;\n        // Exponenci\u00E1ln\u00ED vyhlazen\u00ED rychlosti pro stabiln\u011Bj\u0161\u00ED ETA.\n        this._speed = this._speed ? this._speed * 0.7 + inst * 0.3 : inst;\n        const remaining = this._speed > 0 ? (total - done) / this._speed : Infinity;\n        this._emit('totalProgress', {\n            total,\n            uploaded: done,\n            percent: total > 0 ? (done / total) * 100 : 0,\n            speed: this._speed,\n            eta: remaining,\n            etaText: humanTime(remaining),\n            speedText: humanBytes(this._speed) + '/s',\n        });\n    }\n\n    // --- HTTP helpery ---------------------------------------------------------\n\n    /**\n     * POST na server uploadu. Dotaz, na kter\u00FD nep\u0159i\u0161la odpov\u011B\u010F (v\u00FDpadek nebo\n     * zm\u011Bna s\u00EDt\u011B), se opakuje: `begin` p\u0159i druh\u00E9m pokusu zalo\u017E\u00ED nov\u00FD z\u00E1znam\n     * a prvn\u00ED z\u016Fstane nedokon\u010Den\u00FD (d\u00E1vka bere jen dokon\u010Den\u00E9), `sign-parts`\n     * jen podepisuje a `complete` u dokon\u010Den\u00E9ho uploadu vr\u00E1t\u00ED jeho stav.\n     */\n    _postJson(url, body) {\n        const self = this;\n        let attempt = 0;\n        function tryOnce() {\n            return self._postJsonOnce(url, body).catch((err) => {\n                if (!err.network || attempt >= self.maxRetries) throw err;\n                attempt++;\n                return new Promise((r) => setTimeout(r, 500 * attempt)).then(tryOnce);\n            });\n        }\n        return tryOnce();\n    }\n\n    _postJsonOnce(url, body) {\n        const self = this;\n        return new Promise((resolve, reject) => {\n            const xhr = new XMLHttpRequest();\n            xhr.open('POST', url, true);\n            xhr.setRequestHeader('Content-Type', 'application/json');\n            if (self.csrfToken) xhr.setRequestHeader('X-CSRFToken', self.csrfToken);\n            xhr.onload = () => {\n                let data = {};\n                try {\n                    data = JSON.parse(xhr.responseText || '{}');\n                } catch {\n                    /* noop */\n                }\n                if (xhr.status >= 200 && xhr.status < 300) {\n                    resolve(data);\n                    return;\n                }\n                // Odpov\u011B\u010F bez vlastn\u00ED hl\u00E1\u0161ky (str\u00E1nka 500, 502 z load balanceru)\n                // dostane obecnou hl\u00E1\u0161ku m\u00EDsto hol\u00E9ho \u201EHTTP 500\u201C. Stav a ID po\u017Eadavku\n                // jdou do hl\u00E1\u0161en\u00ED chyby, a\u0165 se d\u00E1 dohledat z\u00E1znam na serveru.\n                const err = new Error(responseErrorMessage(data, xhr.status));\n                err.status = xhr.status;\n                err.requestId = xhr.getResponseHeader('X-Request-ID') || '';\n                reject(err);\n            };\n            xhr.onerror = () => {\n                const err = new Error('Could not reach the server \u2014 check your connection');\n                err.network = true;\n                reject(err);\n            };\n            xhr.send(JSON.stringify(body || {}));\n        });\n    }\n\n    // PUT jedn\u00E9 \u010D\u00E1sti/souboru na presignovanou URL; hl\u00E1s\u00ED pr\u016Fb\u011Bh po delta bajtech.\n    _putBlob(url, blob, contentType, onDelta) {\n        return new Promise((resolve, reject) => {\n            const xhr = new XMLHttpRequest();\n            xhr.open('PUT', url, true);\n            if (contentType) xhr.setRequestHeader('Content-Type', contentType);\n            let last = 0;\n            xhr.upload.onprogress = (e) => {\n                if (e.lengthComputable && onDelta) {\n                    onDelta(e.loaded - last);\n                    last = e.loaded;\n                }\n            };\n            xhr.onload = () => {\n                if (xhr.status >= 200 && xhr.status < 300) {\n                    if (onDelta) onDelta(blob.size - last); // do\u00FA\u010Dtuj zbytek\n                    resolve(xhr.getResponseHeader('ETag') || '');\n                } else {\n                    reject(new Error('S3 HTTP ' + xhr.status));\n                }\n            };\n            xhr.onerror = () => {\n                const err = new Error('Could not upload the file to storage \u2014 check your connection');\n                err.network = true;\n                reject(err);\n            };\n            xhr.send(blob);\n        });\n    }\n\n    // --- Upload jednoho souboru ----------------------------------------------\n\n    _uploadEntry(entry) {\n        const self = this;\n        entry.status = 'uploading';\n        self._emit('fileStatus', entry);\n\n        return self\n            ._postJson(self.beginUrl, {\n                purpose: self.purpose,\n                filename: entry.name,\n                size: entry.size,\n                content_type: entry.contentType,\n                batch: self.batch,\n            })\n            .then((plan) => {\n                entry.uploadId = plan.upload_id;\n                if (plan.batch) self.batch = plan.batch; // sjedno\u0165 d\u00E1vku nap\u0159\u00ED\u010D soubory\n                // Od te\u010F jdou bajty na \u00FAlo\u017Ei\u0161t\u011B: doba p\u0159enosu jde s `complete` na server\n                // (Admin \u2192 Analytics \u2192 Uploads, rychlost podle zem\u011B a akcelerace).\n                entry.transferStart = performance.now();\n                if (!plan.multipart) {\n                    return self._uploadSingle(entry, plan);\n                }\n                return self._uploadMultipart(entry, plan);\n            })\n            .then(() => {\n                entry.status = 'done';\n                entry.uploaded = entry.size;\n                self._emit('fileStatus', entry);\n                self._tick();\n            })\n            .catch((err) => {\n                entry.status = 'error';\n                entry.error = err.message || String(err);\n                entry.network = Boolean(err.network);\n                reportError(`Upload failed: ${entry.error}`, {\n                    kind: 'upload',\n                    file: entry.name || entry.filename || '',\n                    status: err.status || '',\n                    request_id: err.requestId || '',\n                });\n                self._emit('fileStatus', entry);\n                self._emit('error', { entry, error: entry.error });\n                // Pokus o \u00FAklid rozd\u011Blan\u00E9ho multipartu.\n                if (entry.uploadId) {\n                    self._postJson(self.uploadsBase + entry.uploadId + '/abort/', {}).catch(() => {});\n                }\n                throw err;\n            });\n    }\n\n    _uploadSingle(entry, plan) {\n        const self = this;\n        // I mal\u00FD soubor (jeden PUT) se p\u0159i chyb\u011B zkus\u00ED znovu, stejn\u011B jako \u010D\u00E1st multipartu.\n        return self\n            ._putPartWithRetry(plan.put_url, entry.file, entry, entry.contentType)\n            .then(() => self._postJson(self.uploadsBase + entry.uploadId + '/complete/', {\n                transfer_ms: self._transferMs(entry),\n            }));\n    }\n\n    _uploadMultipart(entry, plan) {\n        const self = this;\n        const partSize = plan.part_size;\n        const partCount = plan.part_count;\n        const numbers = [];\n        for (let i = 1; i <= partCount; i++) numbers.push(i);\n\n        return self\n            ._postJson(self.uploadsBase + entry.uploadId + '/sign-parts/', {\n                part_numbers: numbers,\n            })\n            .then((resp) => {\n                const urls = resp.urls || {};\n                const parts = new Array(partCount);\n                let next = 0;\n\n                function worker() {\n                    if (next >= numbers.length) return Promise.resolve();\n                    const pn = numbers[next++];\n                    const start = (pn - 1) * partSize;\n                    const blob = entry.file.slice(start, Math.min(start + partSize, entry.size));\n                    return self._putPartWithRetry(urls[String(pn)], blob, entry).then((etag) => {\n                        parts[pn - 1] = { PartNumber: pn, ETag: etag };\n                        return worker();\n                    });\n                }\n\n                const workers = [];\n                const n = Math.min(self.concurrency, numbers.length);\n                for (let i = 0; i < n; i++) workers.push(worker());\n                return Promise.all(workers).then(() =>\n                    self._postJson(self.uploadsBase + entry.uploadId + '/complete/', {\n                        parts,\n                        transfer_ms: self._transferMs(entry),\n                    }),\n                );\n            });\n    }\n\n    _transferMs(entry) {\n        return entry.transferStart ? Math.max(1, Math.round(performance.now() - entry.transferStart)) : null;\n    }\n\n    _putPartWithRetry(url, blob, entry, contentType = '') {\n        const self = this;\n        let attempt = 0;\n        function tryOnce() {\n            let counted = 0;\n            return self\n                ._putBlob(url, blob, contentType, (delta) => {\n                    counted += delta;\n                    entry.uploaded += delta;\n                    self._tick();\n                })\n                .catch((err) => {\n                    entry.uploaded -= counted; // vra\u0165 zp\u011Bt nezapo\u010D\u00EDtan\u00E9 bajty\n                    self._tick();\n                    attempt++;\n                    if (attempt > self.maxRetries) throw err;\n                    return new Promise((r) => setTimeout(r, 500 * attempt)).then(tryOnce);\n                });\n        }\n        return tryOnce();\n    }\n\n    // --- \u0158\u00EDzen\u00ED fronty --------------------------------------------------------\n\n    start() {\n        const self = this;\n        if (self._started) return;\n        self._started = true;\n        self._startTime = Date.now();\n        self._emit('start', { total: self.totalBytes() });\n\n        // Soubory jedou sekven\u010Dn\u011B (uvnit\u0159 souboru b\u011B\u017E\u00ED \u010D\u00E1sti paraleln\u011B) \u2014 p\u0159ehledn\u00FD\n        // per-file progress a \u0161etrn\u00E9 k pam\u011Bti u velk\u00FDch d\u00E1vek.\n        const queue = self.entries.filter((e) => e.status === 'queued');\n        let idx = 0;\n        function nextFile() {\n            if (idx >= queue.length) {\n                self._started = false;\n                const failed = self.entries.filter((e) => e.status === 'error');\n                self._emit('allDone', {\n                    batch: self.batch,\n                    ok: self.entries.filter((e) => e.status === 'done'),\n                    failed,\n                });\n                return;\n            }\n            const entry = queue[idx++];\n            self._uploadEntry(entry).then(nextFile, nextFile);\n        }\n        nextFile();\n    }\n}\n", "/**\n * upload-items.js \u2014 \u010Dist\u00E9 pomocn\u00E9 funkce nahr\u00E1v\u00E1n\u00ED z mapy (upload.js), bez DOM,\n * aby \u0161ly testovat v Node (`upload-items.test.mjs`).\n */\n\n/** Rozd\u011Bl\u00ED polo\u017Eky hotov\u00E9 d\u00E1vky (`batch_status.items`) podle toho, co s nimi:\n * `ready` jdou rovnou do mapy, `needsCrs` \u010Dekaj\u00ED na sou\u0159adnicov\u00FD syst\u00E9m,\n * `notMappable` mapa uk\u00E1zat neum\u00ED (tabulka bez geometrie, obr\u00E1zek bez polohy). */\nexport function sortUploadedItems(items) {\n    const ready = [];\n    const needsCrs = [];\n    const notMappable = [];\n    for (const item of items || []) {\n        if (item.needs_crs) needsCrs.push(item);\n        else if (item.mappable === false) notMappable.push(item);\n        else ready.push(item);\n    }\n    return { ready, needsCrs, notMappable };\n}\n\n/** N\u00E1zev \u0159\u00E1dku v panelu vrstev: jm\u00E9no souboru, u v\u00EDce soubor\u016F jejich po\u010Det. */\nexport function uploadLabel(files) {\n    const list = Array.from(files || []);\n    if (list.length === 1) return list[0].name;\n    return `${list.length} files`;\n}\n", "/**\n * upload.js \u2014 nahr\u00E1n\u00ED soubor\u016F p\u0159\u00EDmo z mapy, bez odchodu do Data workspace.\n *\n * Tok: v\u00FDb\u011Br soubor\u016F (tla\u010D\u00EDtko \u201EUpload files\u201C v dialogu \u201EAdd data\u201C a v pr\u00E1zdn\u00E9m\n * panelu vrstev) nebo p\u0159eta\u017Een\u00ED soubor\u016F na mapu \u2192 `S3Uploader` (\u00FA\u010Del\n * `workspace`, v\u0161echny soubory v jedn\u00E9 d\u00E1vce) \u2192 `\u2026/workspace/finalize/`\n * (anal\u00FDza) \u2192 stav d\u00E1vky \u2192 hotov\u00E9 polo\u017Eky se p\u0159idaj\u00ED jako vrstvy a mapa se na\n * n\u011B p\u0159ibl\u00ED\u017E\u00ED. Soubory se t\u00EDm z\u00E1rove\u0148 ulo\u017E\u00ED do Data workspace, stejn\u011B jako p\u0159i\n * nahr\u00E1n\u00ED v Console \u2014 nic dal\u0161\u00EDho se u\u017Eivatele nept\u00E1.\n *\n * Pt\u00E1me se jen tam, kde to bez u\u017Eivatele nejde:\n * - data bez sou\u0159adnicov\u00E9ho syst\u00E9mu \u2192 dialog \u201EDefine coordinate system\u201C z UI\n *   Kitu (bal\u00EDk `crs-dialog.js` se st\u00E1hne a\u017E te\u010F), po p\u0159i\u0159azen\u00ED se vrstva p\u0159id\u00E1,\n * - anal\u00FDza chce dopl\u0148uj\u00EDc\u00ED \u00FAdaje (`needs_input`, nap\u0159. heslo archivu) \u2192\n *   odkaz na str\u00E1nku nahr\u00E1v\u00E1n\u00ED v Data workspace, kter\u00E1 \u010Dekaj\u00EDc\u00ED d\u00E1vku obnov\u00ED.\n *\n * Pr\u016Fb\u011Bh (procenta nahr\u00E1n\u00ED, \u010Dten\u00ED dat) ukazuje \u0159\u00E1dek \u201Ep\u0159ipravuje se\u201C ve\n * stromu vrstev (loading.js) \u2014 stejn\u00FD, jak\u00FD mapa ukazuje p\u0159i otev\u00EDr\u00E1n\u00ED dat.\n */\nimport { S3Uploader, humanBytes } from '../uikit/core/s3upload.js';\nimport { apiFetch } from './utils.js';\nimport { beginPreparing, endPreparing, updatePreparing } from './loading.js';\nimport { refreshPreparingRow, renderLayerTree } from './layers.js';\nimport { showToast } from './notices.js';\nimport { sortUploadedItems, uploadLabel } from './upload-items.js';\n\n/** Jak dlouho \u010Dekat na anal\u00FDzu d\u00E1vky (velk\u00E9 archivy se \u010Dtou i minuty). */\nconst POLL_LIMIT_MS = 15 * 60 * 1000;\n\n/** Soubory z p\u0159eta\u017Een\u00ED \u2014 slo\u017Eky (bez obsahu) prohl\u00ED\u017Ee\u010D p\u0159ed\u00E1 jako pr\u00E1zdn\u00FD\n * \u201Esoubor\u201C, ty se vynechaj\u00ED a ohl\u00E1s\u00ED. */\nfunction droppedFiles(dataTransfer) {\n    const files = [];\n    let folders = 0;\n    const items = Array.from(dataTransfer?.items || []);\n    if (items.length) {\n        for (const item of items) {\n            if (item.kind !== 'file') continue;\n            const entry = typeof item.webkitGetAsEntry === 'function' ? item.webkitGetAsEntry() : null;\n            if (entry?.isDirectory) {\n                folders += 1;\n                continue;\n            }\n            const file = item.getAsFile();\n            if (file) files.push(file);\n        }\n    } else {\n        files.push(...Array.from(dataTransfer?.files || []));\n    }\n    return { files, folders };\n}\n\nfunction hasFiles(event) {\n    return Array.from(event.dataTransfer?.types || []).includes('Files');\n}\n\n/** Text chyby z `apiFetch` (\u201E<status> <text>: <t\u011Blo JSON>\u201C). */\nfunction errorText(error) {\n    const raw = String(error?.message || '');\n    const start = raw.indexOf('{');\n    if (start !== -1) {\n        try {\n            const data = JSON.parse(raw.slice(start));\n            if (data?.message) return String(data.message);\n            if (data?.error) return String(data.error);\n        } catch {\n            /* t\u011Blo nen\u00ED JSON */\n        }\n    }\n    return raw.replace(/<[^>]*>/g, ' ').trim().slice(0, 200) || 'Something went wrong.';\n}\n\nconst sleep = (ms) => new Promise((resolve) => { setTimeout(resolve, ms); });\n\nlet crsDialogPromise = null;\n\n/** St\u00E1hne bal\u00EDk s dialogem CRS (jednou za \u017Eivot str\u00E1nky). */\nfunction loadCrsDialog(ctx) {\n    if (window.MgMapCrsDialog) return Promise.resolve(window.MgMapCrsDialog);\n    if (!crsDialogPromise) {\n        crsDialogPromise = new Promise((resolve, reject) => {\n            const src = ctx.bootstrap.crsDialogJs;\n            if (!src) {\n                reject(new Error('The coordinate system dialog is not available.'));\n                return;\n            }\n            document.addEventListener('mg:crs-dialog-ready', () => resolve(window.MgMapCrsDialog), { once: true });\n            const script = document.createElement('script');\n            script.src = src;\n            script.async = true;\n            script.onerror = () => {\n                crsDialogPromise = null;\n                reject(new Error('The coordinate system dialog could not be loaded.'));\n            };\n            document.head.appendChild(script);\n        });\n    }\n    return crsDialogPromise;\n}\n\n/**\n * Nahr\u00E1v\u00E1n\u00ED z mapy. `onItemsReady(ids, titles)` p\u0159id\u00E1 hotov\u00E9 polo\u017Eky do mapy\n * (main.js \u2192 `handleAddItems`), `beforeUpload()` zav\u0159e dialog \u201EAdd data\u201C.\n * Vrac\u00ED `{ available, pick(), upload(files) }`.\n */\nexport function initMapUpload(ctx, { onItemsReady, beforeUpload = () => {}, dropTarget = null } = {}) {\n    const { bootstrap } = ctx;\n    // Sd\u00EDlen\u00FD pohled (data z odkazu) nic neukl\u00E1d\u00E1 \u2014 upload tam nepat\u0159\u00ED.\n    const enabled = !bootstrap.sharedView;\n    const signedIn = Boolean(bootstrap.isAuthenticated);\n    const workspaceApi = `${bootstrap.apiBase}/workspace`;\n    const workspaceUploadUrl = bootstrap.workspaceUploadUrl || bootstrap.consoleUploadUrl || '';\n\n    // Odchod ze str\u00E1nky uprost\u0159ed nahr\u00E1v\u00E1n\u00ED by soubory ztratil \u2014 prohl\u00ED\u017Ee\u010D se zept\u00E1.\n    let active = 0;\n    window.addEventListener('beforeunload', (event) => {\n        if (active > 0) event.preventDefault();\n    });\n\n    /** \u0158\u00E1dek pr\u016Fb\u011Bhu ve stromu vrstev (a \u0161t\u00EDtek nad mapou). */\n    function startRow(label, status) {\n        active += 1;\n        const row = beginPreparing(ctx, label);\n        updatePreparing(ctx, row, { status });\n        renderLayerTree(ctx);\n        return row;\n    }\n    function setStatus(row, status) {\n        updatePreparing(ctx, row, { status });\n        refreshPreparingRow(ctx, row);\n    }\n    function stopRow(row) {\n        active = Math.max(0, active - 1);\n        endPreparing(ctx, row);\n        renderLayerTree(ctx);\n    }\n\n    const input = document.createElement('input');\n    input.type = 'file';\n    input.multiple = true;\n    input.hidden = true;\n    input.setAttribute('aria-hidden', 'true');\n    document.body.appendChild(input);\n    input.addEventListener('change', () => {\n        const files = Array.from(input.files || []);\n        input.value = '';\n        if (files.length) upload(files);\n    });\n\n    function askToSignIn() {\n        showToast('Sign in to upload your files \u2014 they are kept in your Data workspace.', {\n            tone: 'info',\n            timeout: 10000,\n            action: bootstrap.loginUrl ? { label: 'Sign in', href: bootstrap.loginUrl } : undefined,\n        });\n    }\n\n    function pick() {\n        if (!enabled) return;\n        if (!signedIn) {\n            beforeUpload();\n            askToSignIn();\n            return;\n        }\n        input.click();\n    }\n\n    async function waitForAnalysis(jobId, row) {\n        const started = Date.now();\n        let delay = 1500;\n        while (Date.now() - started < POLL_LIMIT_MS) {\n            let data = null;\n            try {\n                data = await apiFetch(`${workspaceApi}/batch/${jobId}/status/`);\n            } catch (error) {\n                if (error?.status && error.status < 500) throw error;\n                // V\u00FDpadek s\u00EDt\u011B nebo serveru \u2014 zkus\u00EDme to znovu.\n            }\n            if (data && !data.active) return data;\n            if (data?.status === 'needs_input') return data;\n            const seconds = Math.round((Date.now() - started) / 1000);\n            if (seconds >= 20) setStatus(row, `Reading the data\u2026 ${seconds} s`);\n            await sleep(delay);\n            delay = Math.min(5000, delay + 500);\n        }\n        return null;\n    }\n\n    function assignCrs(items) {\n        const titles = Object.fromEntries(items.map((item) => [item.id, item.title]));\n        const later = () => showToast(\n            items.length === 1\n                ? `\u201C${items[0].title}\u201D is in your Data workspace, but without a coordinate system it can\u2019t go on the map.`\n                : `${items.length} datasets are in your Data workspace, but without a coordinate system they can\u2019t go on the map.`,\n            { tone: 'info', timeout: 10000 },\n        );\n        loadCrsDialog(ctx).then((dialog) => {\n            dialog.openCrsAssignDialog({\n                items,\n                onDone: (value) => {\n                    const assignments = value?.assignments || {};\n                    const ids = items\n                        .filter((item) => assignments[item.id] && assignments[item.id].mode !== 'none')\n                        .map((item) => item.id);\n                    if (ids.length) onItemsReady(ids, titles);\n                    if (ids.length < items.length) later();\n                },\n                onSkip: later,\n            });\n        }).catch((error) => {\n            showToast(error.message, { tone: 'error' });\n            later();\n        });\n    }\n\n    function finish(result, row, label) {\n        // Vrstvy se p\u0159idaj\u00ED d\u0159\u00EDv, ne\u017E \u0159\u00E1dek nahr\u00E1v\u00E1n\u00ED zmiz\u00ED \u2014 jinak by panel\n        // na okam\u017Eik uk\u00E1zal pr\u00E1zdnou mapu.\n        try {\n            report(result, label);\n        } finally {\n            stopRow(row);\n        }\n    }\n\n    function report(result, label) {\n        if (!result) {\n            showToast(`Reading \u201C${label}\u201D takes longer than usual \u2014 you\u2019ll find it in your Data workspace when it\u2019s done.`, {\n                tone: 'info',\n                timeout: 12000,\n                action: bootstrap.consoleBaseUrl ? { label: 'Data workspace', href: `${bootstrap.consoleBaseUrl}/workspace/` } : undefined,\n            });\n            return;\n        }\n        if (result.status === 'needs_input') {\n            showToast(`\u201C${label}\u201D needs a few more details before it can be read.`, {\n                tone: 'info',\n                timeout: 0,\n                action: workspaceUploadUrl ? { label: 'Add details', href: workspaceUploadUrl } : undefined,\n            });\n            return;\n        }\n        const { ready, needsCrs, notMappable } = sortUploadedItems(result.items);\n        if (!ready.length && !needsCrs.length) {\n            const message = notMappable.length\n                ? `\u201C${notMappable[0].title}\u201D was saved to your Data workspace, but it has nothing to show on a map.`\n                : (result.error || `\u201C${label}\u201D contains no data that can be shown on a map.`);\n            showToast(message, { tone: notMappable.length ? 'info' : 'error', timeout: 12000 });\n            return;\n        }\n        if (ready.length) {\n            onItemsReady(ready.map((item) => item.id), Object.fromEntries(ready.map((item) => [item.id, item.title])));\n            const auto = ready.filter((item) => item.crs_source === 'default_pref');\n            if (auto.length) {\n                const code = (auto[0].crs || [])[0]?.code || '';\n                showToast(`\u201C${auto[0].title}\u201D had no coordinate system \u2014 your default${code ? ` ${code}` : ''} was used.`, {\n                    tone: 'info',\n                    timeout: 10000,\n                });\n            } else {\n                showToast(ready.length === 1\n                    ? `\u201C${ready[0].title}\u201D is on the map and saved in your Data workspace.`\n                    : `${ready.length} datasets are on the map and saved in your Data workspace.`, { tone: 'ok' });\n            }\n        }\n        if (notMappable.length) {\n            showToast(`\u201C${notMappable[0].title}\u201D was saved to your Data workspace, but it has nothing to show on a map.`, {\n                tone: 'info',\n                timeout: 10000,\n            });\n        }\n        if (needsCrs.length) assignCrs(needsCrs);\n    }\n\n    async function upload(fileList) {\n        const files = Array.from(fileList || []).filter((file) => file && file.size > 0);\n        if (!enabled || !files.length) return;\n        beforeUpload();\n        if (!signedIn) {\n            askToSignIn();\n            return;\n        }\n        const label = uploadLabel(files);\n        const total = files.reduce((sum, file) => sum + file.size, 0);\n        const row = startRow(label, `Uploading ${humanBytes(total)}\u2026`);\n\n        const outcome = await new Promise((resolve) => {\n            const uploader = new S3Uploader({\n                purpose: 'workspace',\n                on: {\n                    totalProgress: (p) => setStatus(row, `Uploading\u2026 ${Math.floor(p.percent)} % of ${humanBytes(p.total)}`),\n                    allDone: resolve,\n                },\n            });\n            uploader.addFiles(files);\n            uploader.start();\n        });\n\n        if (!outcome.ok.length) {\n            stopRow(row);\n            const reason = outcome.failed[0]?.error || 'Upload failed.';\n            showToast(`\u201C${label}\u201D could not be uploaded: ${reason}`, { tone: 'error', timeout: 12000 });\n            return;\n        }\n        if (outcome.failed.length) {\n            showToast(`${outcome.failed.length} of ${files.length} files could not be uploaded: ${outcome.failed[0].error}`, {\n                tone: 'error',\n                timeout: 12000,\n            });\n        }\n\n        setStatus(row, 'Reading the data\u2026');\n        let result = null;\n        try {\n            const job = await apiFetch(`${workspaceApi}/finalize/`, {\n                method: 'POST',\n                body: JSON.stringify({ batch: outcome.batch }),\n            });\n            result = await waitForAnalysis(job.job_id, row);\n        } catch (error) {\n            stopRow(row);\n            const quotaFull = error?.status === 413;\n            showToast(quotaFull ? errorText(error) : `\u201C${label}\u201D could not be read: ${errorText(error)}`, {\n                tone: 'error',\n                timeout: quotaFull ? 0 : 12000,\n                action: quotaFull && bootstrap.billing?.plansUrl ? { label: 'Plans', href: bootstrap.billing.plansUrl } : undefined,\n            });\n            return;\n        }\n        finish(result, row, label);\n    }\n\n    // P\u0159eta\u017Een\u00ED soubor\u016F kamkoli na str\u00E1nku mapy; zv\u00FDrazn\u00ED se plocha mapy.\n    if (enabled) {\n        let depth = 0;\n        const show = (on) => dropTarget?.classList.toggle('hidden', !on);\n        document.addEventListener('dragenter', (event) => {\n            if (!hasFiles(event)) return;\n            depth += 1;\n            show(true);\n        });\n        document.addEventListener('dragleave', (event) => {\n            if (!hasFiles(event)) return;\n            depth = Math.max(0, depth - 1);\n            if (depth === 0) show(false);\n        });\n        document.addEventListener('dragover', (event) => {\n            if (!hasFiles(event)) return;\n            event.preventDefault();\n            if (event.dataTransfer) event.dataTransfer.dropEffect = 'copy';\n        });\n        document.addEventListener('drop', (event) => {\n            if (!hasFiles(event)) return;\n            event.preventDefault();\n            depth = 0;\n            show(false);\n            const { files, folders } = droppedFiles(event.dataTransfer);\n            if (folders) {\n                showToast('Folders can\u2019t be dropped here \u2014 pack the folder into a ZIP and drop the ZIP.', {\n                    tone: 'info',\n                    timeout: 10000,\n                });\n            }\n            if (files.length) upload(files);\n        });\n    }\n\n    return { available: enabled, signedIn, pick, upload };\n}\n", "/**\n * external-ui.js \u2014 z\u00E1lo\u017Eky modalu \"Add data\" pro extern\u00ED zdroje: WMS slu\u017Eba,\n * dla\u017Edicov\u00E1 slu\u017Eba (XYZ/WMTS), vlo\u017Een\u00ED dat (GeoJSON/WKT) a na\u010Dten\u00ED z URL.\n * Logiku vrstev (capabilities, parsov\u00E1n\u00ED, vytvo\u0159en\u00ED OL vrstvy) dod\u00E1v\u00E1 external.js.\n */\nimport { zoomToExtent } from './map.js';\nimport { fromLonLat } from 'ol/proj.js';\nimport {\n    loadWmsCapabilities,\n    loadWmtsCapabilities,\n    addExternalWmsLayer,\n    addXyzLayer,\n    addWmtsLayer,\n    addLocalLayer,\n    parsePastedData,\n} from './external.js';\n\n/** Zobraz\u00ED chybovou hl\u00E1\u0161ku do dan\u00E9ho kontejneru (nebo ji skryje). */\nfunction setError(el, message) {\n    if (!el) return;\n    if (message) {\n        el.textContent = message;\n        el.classList.remove('hidden');\n    } else {\n        el.textContent = '';\n        el.classList.add('hidden');\n    }\n}\n\n/** Nastav\u00ED loading stav tla\u010D\u00EDtka (disabled + n\u00E1hradn\u00ED text). */\nfunction setLoading(button, loading, loadingText) {\n    if (!button) return;\n    if (loading) {\n        button.dataset.originalText = button.textContent;\n        button.textContent = loadingText || 'Loading\u2026';\n        button.disabled = true;\n    } else {\n        button.textContent = button.dataset.originalText || button.textContent;\n        button.disabled = false;\n    }\n}\n\n/** P\u0159ibl\u00ED\u017E\u00ED mapu na WGS84 bbox (pokud je kone\u010Dn\u00FD). */\nfunction zoomToBbox(ctx, bbox) {\n    if (!bbox || bbox.length !== 4 || !bbox.every(Number.isFinite)) return;\n    const extent = [...fromLonLat([bbox[0], bbox[1]]), ...fromLonLat([bbox[2], bbox[3]])];\n    zoomToExtent(ctx.map, extent);\n}\n\n/** P\u0159ibl\u00ED\u017E\u00ED mapu na extent klientsk\u00E9ho vektorov\u00E9ho zdroje (EPSG:3857). */\nfunction zoomToSource(ctx, source) {\n    const extent = source?.getExtent();\n    if (extent && extent.every(Number.isFinite)) zoomToExtent(ctx.map, extent);\n}\n\n/* ---------------------------------------------------------------------------\n * Z\u00E1lo\u017Eka \"WMS service\"\n * ------------------------------------------------------------------------- */\n\nfunction initWmsTab(ctx, root, closeModal) {\n    const urlInput = root.querySelector('[data-role=\"wms-url\"]');\n    const loadButton = root.querySelector('[data-role=\"wms-load\"]');\n    const errorEl = root.querySelector('[data-role=\"wms-error\"]');\n    const listEl = root.querySelector('[data-role=\"wms-list\"]');\n    const addButton = root.querySelector('[data-role=\"wms-add\"]');\n    let capabilities = null;\n\n    function renderLayerList() {\n        listEl.innerHTML = '';\n        capabilities.layers.forEach((layer, index) => {\n            const row = document.createElement('label');\n            row.className = 'flex cursor-pointer items-center gap-x-2 rounded-lg px-2 py-1.5 text-sm text-slate-700 hover:bg-slate-50';\n            row.innerHTML = `\n                <input type=\"checkbox\" data-index=\"${index}\" class=\"h-4 w-4 rounded border-slate-300 text-brand-600 focus:ring-brand-500\">\n                <span class=\"min-w-0 flex-1 truncate\" title=\"${layer.name}\">${layer.title}</span>\n                <span class=\"flex-none text-[11px] text-slate-400\">${layer.name}</span>`;\n            listEl.appendChild(row);\n        });\n        listEl.classList.remove('hidden');\n        addButton.classList.remove('hidden');\n    }\n\n    loadButton?.addEventListener('click', async () => {\n        const url = (urlInput.value || '').trim();\n        setError(errorEl, null);\n        if (!url) {\n            setError(errorEl, 'Enter a WMS service URL.');\n            return;\n        }\n        setLoading(loadButton, true);\n        try {\n            capabilities = await loadWmsCapabilities(url);\n            renderLayerList();\n        } catch (error) {\n            capabilities = null;\n            listEl.classList.add('hidden');\n            addButton.classList.add('hidden');\n            setError(errorEl, error.message);\n        } finally {\n            setLoading(loadButton, false);\n        }\n    });\n\n    addButton?.addEventListener('click', () => {\n        if (!capabilities) return;\n        const checked = Array.from(listEl.querySelectorAll('input:checked'));\n        if (checked.length === 0) {\n            setError(errorEl, 'Select at least one layer.');\n            return;\n        }\n        setError(errorEl, null);\n        // Preferovan\u00FD INFO_FORMAT pro identify (jen kdy\u017E slu\u017Eba HTML um\u00ED).\n        const infoFormat = (capabilities.infoFormats || []).find((f) => f.toLowerCase() === 'text/html') || null;\n        let lastEntry = null;\n        checked.forEach((input) => {\n            const layer = capabilities.layers[Number(input.dataset.index)];\n            lastEntry = addExternalWmsLayer(ctx, {\n                url: capabilities.url,\n                version: capabilities.version,\n                format: capabilities.format,\n                layerName: layer.name,\n                title: layer.title,\n                bbox: layer.bbox,\n                queryable: layer.queryable,\n                legendUrl: layer.legendUrl,\n                infoFormat,\n            });\n        });\n        if (lastEntry?.bbox) zoomToBbox(ctx, lastEntry.bbox);\n        closeModal();\n    });\n}\n\n/* ---------------------------------------------------------------------------\n * Z\u00E1lo\u017Eka \"Tile service\" (XYZ / WMTS)\n * ------------------------------------------------------------------------- */\n\nfunction initTileTab(ctx, root, closeModal) {\n    const kindInputs = Array.from(root.querySelectorAll('[name=\"map-tile-kind\"]'));\n    const xyzSection = root.querySelector('[data-role=\"tile-xyz\"]');\n    const wmtsSection = root.querySelector('[data-role=\"tile-wmts\"]');\n    const xyzUrlInput = root.querySelector('[data-role=\"xyz-url\"]');\n    const xyzTitleInput = root.querySelector('[data-role=\"xyz-title\"]');\n    const xyzAddButton = root.querySelector('[data-role=\"xyz-add\"]');\n    const wmtsUrlInput = root.querySelector('[data-role=\"wmts-url\"]');\n    const wmtsLoadButton = root.querySelector('[data-role=\"wmts-load\"]');\n    const wmtsSelect = root.querySelector('[data-role=\"wmts-select\"]');\n    const wmtsAddButton = root.querySelector('[data-role=\"wmts-add\"]');\n    const errorEl = root.querySelector('[data-role=\"tile-error\"]');\n    let wmtsData = null;\n\n    kindInputs.forEach((input) => {\n        input.addEventListener('change', () => {\n            const isXyz = root.querySelector('[name=\"map-tile-kind\"]:checked')?.value === 'xyz';\n            xyzSection.classList.toggle('hidden', !isXyz);\n            wmtsSection.classList.toggle('hidden', isXyz);\n            setError(errorEl, null);\n        });\n    });\n\n    xyzAddButton?.addEventListener('click', () => {\n        const url = (xyzUrlInput.value || '').trim();\n        setError(errorEl, null);\n        if (!/\\{z\\}/.test(url) || !/\\{x\\}/.test(url) || !/\\{y\\}/.test(url)) {\n            setError(errorEl, 'The URL template must contain {z}, {x} and {y} placeholders.');\n            return;\n        }\n        addXyzLayer(ctx, { url, title: (xyzTitleInput.value || '').trim() || 'XYZ layer' });\n        closeModal();\n    });\n\n    wmtsLoadButton?.addEventListener('click', async () => {\n        const url = (wmtsUrlInput.value || '').trim();\n        setError(errorEl, null);\n        if (!url) {\n            setError(errorEl, 'Enter a WMTS capabilities URL.');\n            return;\n        }\n        setLoading(wmtsLoadButton, true);\n        try {\n            wmtsData = await loadWmtsCapabilities(url);\n            wmtsSelect.innerHTML = wmtsData.layers\n                .map((l, i) => `<option value=\"${i}\">${l.title}</option>`)\n                .join('');\n            wmtsSelect.classList.remove('hidden');\n            wmtsAddButton.classList.remove('hidden');\n        } catch (error) {\n            wmtsData = null;\n            wmtsSelect.classList.add('hidden');\n            wmtsAddButton.classList.add('hidden');\n            setError(errorEl, error.message);\n        } finally {\n            setLoading(wmtsLoadButton, false);\n        }\n    });\n\n    wmtsAddButton?.addEventListener('click', () => {\n        if (!wmtsData) return;\n        const layer = wmtsData.layers[Number(wmtsSelect.value)];\n        if (!layer) return;\n        try {\n            const entry = addWmtsLayer(ctx, {\n                url: wmtsData.url,\n                caps: wmtsData.caps,\n                layerName: layer.name,\n                title: layer.title,\n                bbox: layer.bbox,\n            });\n            if (entry.bbox) zoomToBbox(ctx, entry.bbox);\n            closeModal();\n        } catch (error) {\n            setError(errorEl, error.message);\n        }\n    });\n}\n\n/* ---------------------------------------------------------------------------\n * Z\u00E1lo\u017Eka \"Paste data\" (GeoJSON / WKT)\n * ------------------------------------------------------------------------- */\n\nfunction initPasteTab(ctx, root, closeModal) {\n    const textarea = root.querySelector('[data-role=\"paste-text\"]');\n    const titleInput = root.querySelector('[data-role=\"paste-title\"]');\n    const crsSelect = root.querySelector('[data-role=\"paste-crs\"]');\n    const addButton = root.querySelector('[data-role=\"paste-add\"]');\n    const errorEl = root.querySelector('[data-role=\"paste-error\"]');\n\n    addButton?.addEventListener('click', () => {\n        setError(errorEl, null);\n        try {\n            const geojson = parsePastedData(textarea.value, crsSelect.value || 'EPSG:4326');\n            const entry = addLocalLayer(ctx, {\n                title: (titleInput.value || '').trim() || 'Pasted data',\n                geojson,\n            });\n            zoomToSource(ctx, entry.olSource);\n            closeModal();\n        } catch (error) {\n            setError(errorEl, error.message);\n        }\n    });\n}\n\n/* ---------------------------------------------------------------------------\n * Z\u00E1lo\u017Eka \"From URL\" (GeoJSON soubor)\n * ------------------------------------------------------------------------- */\n\nfunction initUrlTab(ctx, root, closeModal) {\n    const urlInput = root.querySelector('[data-role=\"url-input\"]');\n    const addButton = root.querySelector('[data-role=\"url-add\"]');\n    const errorEl = root.querySelector('[data-role=\"url-error\"]');\n\n    addButton?.addEventListener('click', async () => {\n        const url = (urlInput.value || '').trim();\n        setError(errorEl, null);\n        if (!url) {\n            setError(errorEl, 'Enter a URL of a GeoJSON file.');\n            return;\n        }\n        setLoading(addButton, true);\n        try {\n            let response;\n            try {\n                response = await fetch(url);\n            } catch (fetchError) {\n                if (fetchError instanceof TypeError) {\n                    throw new Error('The server does not allow cross-origin requests (CORS) or is unreachable.');\n                }\n                throw fetchError;\n            }\n            if (!response.ok) throw new Error(`Download failed (${response.status}).`);\n            const text = await response.text();\n            const geojson = parsePastedData(text, 'EPSG:4326');\n            // N\u00E1zev vrstvy z n\u00E1zvu souboru v URL (bez p\u0159\u00EDpony), fallback \"GeoJSON layer\".\n            const fileName = url.split('/').pop()?.split('?')[0] || '';\n            const entry = addLocalLayer(ctx, {\n                title: fileName.replace(/\\.[^.]+$/, '') || 'GeoJSON layer',\n                geojson,\n                sourceUrl: url,\n            });\n            zoomToSource(ctx, entry.olSource);\n            closeModal();\n        } catch (error) {\n            setError(errorEl, error.message);\n        } finally {\n            setLoading(addButton, false);\n        }\n    });\n}\n\n/**\n * Inicializuje z\u00E1lo\u017Eky modalu \"Add data\": p\u0159ep\u00EDn\u00E1n\u00ED panel\u016F + obsluha \u010Dty\u0159\n * z\u00E1lo\u017Eek extern\u00EDch zdroj\u016F. `modal` je ko\u0159en modalu, `closeModal()` ho zav\u0159e.\n */\nexport function initExternalSources(ctx, modal, closeModal) {\n    if (!modal) return;\n    const tabs = Array.from(modal.querySelectorAll('[data-role=\"add-tab\"]'));\n    const panels = Array.from(modal.querySelectorAll('[data-role=\"add-panel\"]'));\n\n    tabs.forEach((tab) => {\n        tab.addEventListener('click', () => {\n            tabs.forEach((t) => t.classList.toggle('is-active', t === tab));\n            panels.forEach((p) => p.classList.toggle('hidden', p.dataset.tab !== tab.dataset.tab));\n        });\n    });\n\n    const byTab = (name) => panels.find((p) => p.dataset.tab === name);\n    if (byTab('wms')) initWmsTab(ctx, byTab('wms'), closeModal);\n    if (byTab('tile')) initTileTab(ctx, byTab('tile'), closeModal);\n    if (byTab('paste')) initPasteTab(ctx, byTab('paste'), closeModal);\n    if (byTab('url')) initUrlTab(ctx, byTab('url'), closeModal);\n}\n", "/**\n * unsaved.js \u2014 upozorn\u011Bn\u00ED na neulo\u017Een\u00E9 zm\u011Bny (n\u00E1hrada d\u0159\u00EDv\u011Bj\u0161\u00EDho autosave do\n * localStorage).\n *\n * Pravidla:\n *  - Hl\u00EDd\u00E1 se jen \u201Edirty\u201C stav OBSAHU mapy (vrstvy, styl, kresba, atributov\u00FD\n *    filtr, n\u00E1zev\u2026) \u2014 posun/zoom mapy zm\u011Bnou nen\u00ED (viz state.js / main.js).\n *  - Upozor\u0148uje se jen, kdy\u017E je mapa dirty A z\u00E1rove\u0148 m\u00E1 obsah (\u2265 1 vrstva\n *    nebo kresba) \u2014 pr\u00E1zdnou mapu nen\u00ED co ztratit.\n *  - Intern\u00ED odkazy (same-origin `<a href>` bez `target`, ne jen `#hash`, ne\n *    `download`) a navigace v aplikaci (dialog \u201EOpen map\u201C) \u2192 vlastn\u00ED modal\n *    \u201ESave and continue\u201C / \u201EDiscard\u201C / \u201EStay\u201C.\n *  - Zav\u0159en\u00ED tabu, refresh, ru\u010Dn\u011B zadan\u00E1 URL, Zp\u011Bt, extern\u00ED odkaz \u2192 nativn\u00ED\n *    `beforeunload` (prohl\u00ED\u017Ee\u010D vlastn\u00ED text nedovol\u00ED). Listener je\n *    registrovan\u00FD JEN kdy\u017E je co ztratit, a p\u0159ed programovou navigac\u00ED po volb\u011B\n *    v modalu se odregistruje (jinak by se u\u017Eivatel ptal dvakr\u00E1t).\n *  - \u201EDiscard\u201C \u2192 u\u017E se nept\u00E1me; \u201EStay\u201C \u2192 zept\u00E1me se zase p\u0159i dal\u0161\u00EDm pokusu.\n *  - Div\u00E1k ciz\u00ED mapy bez pr\u00E1va editace nem\u016F\u017Ee mapu p\u0159epsat, tak\u017Ee ho\n *    neotravujeme pouh\u00FDm prohl\u00ED\u017Een\u00EDm (posun/zoom dirty ned\u011Bl\u00E1); upozorn\u00ED se,\n *    jen kdy\u017E ud\u011Blal vlastn\u00ED zm\u011Bny obsahu \u2014 \u201ESave\u201C pak ulo\u017E\u00ED jeho kopii\n *    (\u201ESave as\u201C).\n */\nimport { on } from './utils.js';\nimport { flatLayers } from './state.js';\nimport { saveMap } from './persist.js';\n\n/** V\u00FDchoz\u00ED titulek nov\u00E9 mapy \u2014 takovou mapu bereme jako \u201Ebez n\u00E1zvu\u201C. */\nconst DEFAULT_TITLE = 'Untitled map';\n\nexport function hasContent(ctx) {\n    return flatLayers(ctx.state).length > 0;\n}\n\n/** Je kliknut\u00ED na odkaz intern\u00ED navigace, kterou m\u00E1 smysl hl\u00EDdat? */\nfunction internalNavigationTarget(event) {\n    if (event.defaultPrevented || event.button !== 0) return null;\n    if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return null; // nov\u00FD tab/okno\n    const link = event.target.closest?.('a[href]');\n    if (!link || link.closest('[data-unsaved-skip]')) return null;\n    const target = (link.getAttribute('target') || '').trim().toLowerCase();\n    if (target && target !== '_self') return null;\n    if (link.hasAttribute('download')) return null;\n    const rawHref = link.getAttribute('href') || '';\n    if (!rawHref || rawHref.startsWith('#') || rawHref.toLowerCase().startsWith('javascript:')) return null;\n    let url;\n    try {\n        url = new URL(link.href, window.location.href);\n    } catch {\n        return null;\n    }\n    if (url.origin !== window.location.origin) return null; // extern\u00ED \u2192 beforeunload\n    // Jen zm\u011Bna #hash na t\u00E9\u017Ee str\u00E1nce str\u00E1nku neopou\u0161t\u00ED.\n    if (url.pathname === window.location.pathname && url.search === window.location.search && url.hash) {\n        return null;\n    }\n    return url.href;\n}\n\n/**\n * Inicializuje hl\u00EDd\u00E1n\u00ED neulo\u017Een\u00FDch zm\u011Bn. Vrac\u00ED API:\n *  - `guardNavigation(proceed)` \u2014 zavol\u00E1 `proceed()` hned, nebo a\u017E po volb\u011B\n *    v modalu (Save and continue / Discard); p\u0159i \u201EStay\u201C nezavol\u00E1 nic.\n *  - `needsGuard()` \u2014 je te\u010F co ztratit?\n */\nexport function initUnsavedGuard(ctx, { openOverlay, closeOverlay }) {\n    const modal = document.getElementById('map-unsaved-modal');\n    const q = (role) => modal?.querySelector(`[data-role=\"${role}\"]`);\n    const els = {\n        text: q('unsaved-text'),\n        titleWrap: q('unsaved-title-wrap'),\n        titleInput: q('unsaved-title'),\n        anonNote: q('unsaved-anon-note'),\n        loginLink: q('unsaved-login'),\n        error: q('unsaved-error'),\n        save: q('unsaved-save'),\n        discard: q('unsaved-discard'),\n        stay: q('unsaved-stay'),\n    };\n\n    let discarded = false; // \u201EDiscard\u201C \u2014 u\u017E se neptat\n    let bypass = false; // programov\u00E1 navigace po volb\u011B v modalu\n    let pending = null; // pokra\u010Dov\u00E1n\u00ED \u010Dekaj\u00EDc\u00ED na volbu v modalu\n    let beforeUnloadRegistered = false;\n\n    const needsGuard = () => !ctx.sharedView && !discarded && !bypass && Boolean(ctx.state.dirty) && hasContent(ctx);\n\n    function onBeforeUnload(event) {\n        if (!needsGuard()) return undefined;\n        event.preventDefault();\n        // Star\u0161\u00ED prohl\u00ED\u017Ee\u010De vy\u017Eaduj\u00ED `returnValue` (text stejn\u011B nezobraz\u00ED).\n        event.returnValue = '';\n        return '';\n    }\n\n    /** (Od)registruje `beforeunload` podle toho, jestli je co ztratit. */\n    function syncBeforeUnload() {\n        const want = needsGuard();\n        if (want && !beforeUnloadRegistered) {\n            window.addEventListener('beforeunload', onBeforeUnload);\n            beforeUnloadRegistered = true;\n        } else if (!want && beforeUnloadRegistered) {\n            window.removeEventListener('beforeunload', onBeforeUnload);\n            beforeUnloadRegistered = false;\n        }\n    }\n\n    on('state:dirty', syncBeforeUnload);\n    on('layers:changed', syncBeforeUnload);\n    on('map:saved', syncBeforeUnload);\n\n    /** Ulo\u017Eit lze p\u0159\u00EDmo jen vlastn\u00ED/editovatelnou, u\u017E ulo\u017Eenou mapu. */\n    const canSaveInPlace = () => Boolean(ctx.state.mapId) && !ctx.readOnly;\n\n    function hasRealTitle() {\n        const title = (ctx.state.title || '').trim();\n        return Boolean(title) && title !== DEFAULT_TITLE;\n    }\n\n    function loginUrlFor() {\n        const base = (ctx.bootstrap.loginUrl || '').split('?')[0];\n        if (!base) return '';\n        const viewerBase = ctx.bootstrap.apiBase.replace(/\\/api$/, '');\n        const next = ctx.state.mapId ? `${viewerBase}/${ctx.state.mapId}/` : window.location.pathname;\n        return `${base}?next=${encodeURIComponent(next)}`;\n    }\n\n    function showError(message) {\n        if (!els.error) return;\n        els.error.textContent = message;\n        els.error.classList.toggle('hidden', !message);\n    }\n\n    function openModal() {\n        if (!modal) return false;\n        showError('');\n        const copy = ctx.readOnly && Boolean(ctx.state.mapId);\n        if (els.text) {\n            els.text.textContent = copy\n                ? 'You have changed this shared map. You can\u2019t save over it, but you can save your own copy before you leave.'\n                : 'You have unsaved changes on this map. Save them before you leave?';\n        }\n        if (els.save) els.save.textContent = copy ? 'Save a copy and continue' : 'Save and continue';\n        // N\u00E1zev je pot\u0159eba jen u nov\u00E9 mapy bez n\u00E1zvu (resp. u kopie ciz\u00ED mapy).\n        const needsTitle = copy || (!ctx.state.mapId && !hasRealTitle());\n        els.titleWrap?.classList.toggle('hidden', !needsTitle);\n        if (els.titleInput) {\n            els.titleInput.value = copy\n                ? `${ctx.state.title || DEFAULT_TITLE} (copy)`\n                : (hasRealTitle() ? ctx.state.title : '');\n        }\n        const anonymous = !ctx.bootstrap.isAuthenticated;\n        els.anonNote?.classList.toggle('hidden', !anonymous);\n        if (anonymous && els.loginLink) els.loginLink.href = loginUrlFor();\n        openOverlay(modal);\n        if (needsTitle) window.setTimeout(() => els.titleInput?.focus(), 50);\n        return true;\n    }\n\n    function proceed() {\n        const next = pending;\n        pending = null;\n        bypass = true;\n        syncBeforeUnload(); // odregistrovat \u2014 navigace je cht\u011Bn\u00E1\n        closeOverlay(modal);\n        next?.();\n    }\n\n    async function onSave() {\n        showError('');\n        const copy = ctx.readOnly && Boolean(ctx.state.mapId);\n        const needsTitle = !els.titleWrap?.classList.contains('hidden');\n        if (needsTitle) {\n            const title = (els.titleInput?.value || '').trim();\n            if (!title) {\n                showError('Please enter a title for the map.');\n                els.titleInput?.focus();\n                return;\n            }\n            ctx.state.title = title;\n            if (ctx.elements?.titleInput) ctx.elements.titleInput.value = title;\n        }\n        if (els.save) els.save.disabled = true;\n        try {\n            // Vlastn\u00ED/editovateln\u00E1 ulo\u017Een\u00E1 mapa \u2192 PUT; nov\u00E1 mapa \u2192 POST;\n            // ciz\u00ED mapa bez pr\u00E1va editace \u2192 POST kopie (\u201ESave as\u201C).\n            await saveMap(ctx, { asNew: copy || !canSaveInPlace() });\n            proceed();\n        } catch (error) {\n            showError(`The map couldn\u2019t be saved: ${error.message}`);\n        } finally {\n            if (els.save) els.save.disabled = false;\n        }\n    }\n\n    els.save?.addEventListener('click', onSave);\n    els.discard?.addEventListener('click', () => {\n        discarded = true;\n        proceed();\n    });\n    els.stay?.addEventListener('click', () => {\n        pending = null;\n        closeOverlay(modal);\n    });\n    els.titleInput?.addEventListener('keydown', (event) => {\n        if (event.key === 'Enter') {\n            event.preventDefault();\n            onSave();\n        }\n    });\n    // Zav\u0159en\u00ED modalu k\u0159\u00ED\u017Ekem/kl\u00E1vesou Esc = \u201EStay\u201C.\n    modal?.addEventListener('close.hs.overlay', () => { pending = null; });\n\n    function guardNavigation(next) {\n        if (!needsGuard()) {\n            next();\n            return;\n        }\n        pending = next;\n        if (!openModal()) {\n            // Bez modalu (chyb\u00ED \u0161ablona) aspo\u0148 nativn\u00ED potvrzen\u00ED.\n            // eslint-disable-next-line no-alert -- nouzov\u00E1 cesta\n            if (window.confirm('You have unsaved changes. Leave without saving?')) {\n                discarded = true;\n                proceed();\n            } else {\n                pending = null;\n            }\n        }\n    }\n\n    // Intern\u00ED odkazy (navbar, odkazy v panelech\u2026) \u2014 capture f\u00E1ze, aby se\n    // modal uk\u00E1zal d\u0159\u00EDv, ne\u017E odkaz zpracuje kdokoli jin\u00FD.\n    document.addEventListener('click', (event) => {\n        if (!needsGuard()) return;\n        const href = internalNavigationTarget(event);\n        if (!href) return;\n        event.preventDefault();\n        guardNavigation(() => window.location.assign(href));\n    }, true);\n\n    syncBeforeUnload();\n    return { guardNavigation, needsGuard };\n}\n", "/**\n * open-map.js \u2014 dialog \u201EOpen map\u201C (tla\u010D\u00EDtko se slo\u017Ekou v horn\u00ED li\u0161t\u011B).\n *\n * Seznam \u201EMy maps\u201C (vlastn\u00ED mapy, u anonyma mapy jeho n\u00E1v\u0161t\u011Bvnick\u00E9 identity)\n * a \u201EShared with me\u201C (jen p\u0159ihl\u00E1\u0161en\u00FD) z `GET /maps/`, hled\u00E1n\u00ED podle n\u00E1zvu,\n * \u0159azen\u00ED podle posledn\u00ED zm\u011Bny. Pod nimi \u201ESample maps\u201C \u2014 hotov\u00E9 uk\u00E1zkov\u00E9\n * kompozice (`GET /samples/`): otev\u0159ou se jen pro \u010Dten\u00ED a jdou ulo\u017Eit jako\n * vlastn\u00ED mapa. Otev\u0159en\u00ED mapy jde p\u0159es hl\u00EDd\u00E1n\u00ED neulo\u017Een\u00FDch\n * zm\u011Bn (unsaved.js) \u2014 `guardNavigation`. Odkaz na celou galerii vede do\n * Console (nov\u00FD tab, rozd\u011Blan\u00E1 mapa z\u016Fstane otev\u0159en\u00E1).\n */\nimport { apiFetch } from './utils.js';\nimport { loadSampleMaps } from './sample-maps.js';\n\nfunction escapeHtml(value) {\n    return String(value ?? '')\n        .replaceAll('&', '&amp;')\n        .replaceAll('<', '&lt;')\n        .replaceAll('>', '&gt;')\n        .replaceAll('\"', '&quot;');\n}\n\n/** Normalizace pro hled\u00E1n\u00ED: mal\u00E1 p\u00EDsmena bez diakritiky. */\nfunction normalize(text) {\n    return String(text || '').normalize('NFD').replace(/[\\u0300-\\u036f]/g, '').toLowerCase();\n}\n\nfunction formatDate(iso) {\n    const date = new Date(iso);\n    if (Number.isNaN(date.getTime())) return '';\n    return date.toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' });\n}\n\nconst MAP_ICON = '<svg class=\"h-5 w-5\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M9 20l-5.447-2.724A1 1 0 0 1 3 16.382V5.618a1 1 0 0 1 1.447-.894L9 7m0 13 6-3m-6 3V7m6 10 4.553 2.276A1 1 0 0 0 21 18.382V7.618a1 1 0 0 0-.553-.894L15 4m0 13V4m0 0L9 7\"/></svg>';\n\nexport function initOpenMapDialog(ctx, { button, openOverlay, closeOverlay, guard }) {\n    const modal = document.getElementById('map-open-modal');\n    if (!button || !modal) return;\n    const q = (role) => modal.querySelector(`[data-role=\"${role}\"]`);\n    const els = {\n        search: q('open-search'),\n        mine: q('open-mine'),\n        shared: q('open-shared'),\n        sharedSection: q('open-shared-section'),\n        signinHint: q('open-signin-hint'),\n        status: q('open-status'),\n        gallery: q('open-gallery'),\n        samples: q('open-samples'),\n        samplesSection: q('open-samples-section'),\n    };\n    let data = { maps: [], shared: [] };\n    let samples = null; // na\u010Dtou se jednou \u2014 m\u011Bn\u00ED se jen s nasazen\u00EDm\n\n    const viewerBase = ctx.bootstrap.apiBase.replace(/\\/api$/, '');\n    const mapUrl = (id) => `${viewerBase}/${id}/`;\n\n    if (els.gallery) {\n        if (ctx.bootstrap.galleryUrl && ctx.bootstrap.isAuthenticated) {\n            els.gallery.href = ctx.bootstrap.galleryUrl;\n        } else {\n            // Galerie v Console je jen pro p\u0159ihl\u00E1\u0161en\u00E9.\n            els.gallery.classList.add('hidden');\n        }\n    }\n    if (!ctx.bootstrap.isAuthenticated) {\n        els.sharedSection?.classList.add('hidden');\n        els.signinHint?.classList.remove('hidden');\n        const link = els.signinHint?.querySelector('a');\n        if (link && ctx.bootstrap.loginUrl) link.href = ctx.bootstrap.loginUrl;\n    }\n\n    function renderList(container, maps, { shared = false } = {}) {\n        if (!container) return;\n        const term = normalize(els.search?.value);\n        const items = maps\n            .filter((m) => !term || normalize(m.title).includes(term))\n            .sort((a, b) => String(b.updated_at).localeCompare(String(a.updated_at)));\n        if (items.length === 0) {\n            let empty = shared ? 'No maps have been shared with you yet.' : 'You have no saved maps yet.';\n            if (term) empty = 'No maps match your search.';\n            container.innerHTML = `<p class=\"px-1 py-3 text-sm text-slate-400\">${empty}</p>`;\n            return;\n        }\n        container.innerHTML = items.map((m) => {\n            const current = m.id === ctx.state.mapId;\n            const meta = [\n                `Updated ${escapeHtml(formatDate(m.updated_at))}`,\n                shared && m.owner_label ? `by ${escapeHtml(m.owner_label)}` : '',\n                shared && m.role ? escapeHtml(m.role === 'editor' ? 'can edit' : 'can view') : '',\n            ].filter(Boolean).join(' \u00B7 ');\n            return `\n            <button type=\"button\" data-map-id=\"${escapeHtml(m.id)}\" ${current ? 'disabled' : ''}\n                    class=\"flex w-full items-center gap-x-3 rounded-lg border border-slate-200 bg-white p-2 text-left hover:border-brand-300 hover:bg-brand-50/40 disabled:cursor-default disabled:border-brand-200 disabled:bg-brand-50/60\">\n                <span class=\"flex h-12 w-16 flex-none items-center justify-center overflow-hidden rounded-md bg-slate-100 text-slate-300\">\n                    ${m.thumbnail_url ? `<img src=\"${escapeHtml(m.thumbnail_url)}\" alt=\"\" class=\"h-full w-full object-cover\" loading=\"lazy\">` : MAP_ICON}\n                </span>\n                <span class=\"min-w-0 flex-1\">\n                    <span class=\"block truncate text-sm font-medium text-slate-800\">${escapeHtml(m.title)}</span>\n                    <span class=\"block truncate text-xs text-slate-400\">${meta}</span>\n                </span>\n                ${current ? '<span class=\"flex-none rounded-full bg-brand-100 px-2 py-0.5 text-[11px] font-medium text-brand-700\">Open now</span>' : ''}\n            </button>`;\n        }).join('');\n    }\n\n    function renderSamples() {\n        if (!els.samples || !els.samplesSection) return;\n        const term = normalize(els.search?.value);\n        const items = (samples || []).filter((m) => !term || normalize(`${m.title} ${m.description}`).includes(term));\n        els.samplesSection.classList.toggle('hidden', items.length === 0);\n        els.samples.innerHTML = items.map((m) => {\n            const current = m.id === ctx.state.mapId;\n            return `\n            <button type=\"button\" data-map-id=\"${escapeHtml(m.id)}\" ${current ? 'disabled' : ''}\n                    class=\"flex w-full items-center gap-x-3 rounded-lg border border-slate-200 bg-white p-2 text-left hover:border-brand-300 hover:bg-brand-50/40 disabled:cursor-default disabled:border-brand-200 disabled:bg-brand-50/60\">\n                <span class=\"flex h-12 w-16 flex-none items-center justify-center overflow-hidden rounded-md bg-slate-100 text-slate-300\">\n                    ${m.image_url ? `<img src=\"${escapeHtml(m.image_url)}\" alt=\"\" class=\"h-full w-full object-cover\" loading=\"lazy\">` : MAP_ICON}\n                </span>\n                <span class=\"min-w-0 flex-1\">\n                    <span class=\"block truncate text-sm font-medium text-slate-800\">${escapeHtml(m.title)}</span>\n                    <span class=\"block truncate text-xs text-slate-400\">${escapeHtml(m.description)}</span>\n                </span>\n                ${current ? '<span class=\"flex-none rounded-full bg-brand-100 px-2 py-0.5 text-[11px] font-medium text-brand-700\">Open now</span>' : ''}\n            </button>`;\n        }).join('');\n    }\n\n    async function loadSamples() {\n        if (samples !== null) return;\n        // Chyba = pr\u00E1zdn\u00FD seznam (uk\u00E1zky jsou jen nab\u00EDdka nav\u00EDc), viz sample-maps.js.\n        samples = ctx.bootstrap.showSamples === false ? [] : await loadSampleMaps(ctx);\n        renderSamples();\n    }\n\n    function render() {\n        renderList(els.mine, data.maps || []);\n        if (ctx.bootstrap.isAuthenticated) renderList(els.shared, data.shared || [], { shared: true });\n        renderSamples();\n    }\n\n    async function load() {\n        if (els.status) {\n            els.status.textContent = 'Loading maps\u2026';\n            els.status.classList.remove('hidden');\n        }\n        try {\n            const result = await apiFetch(`${ctx.bootstrap.apiBase}/maps/`);\n            data = { maps: result?.maps || [], shared: result?.shared || [] };\n            els.status?.classList.add('hidden');\n        } catch (error) {\n            data = { maps: [], shared: [] };\n            if (els.status) els.status.textContent = `Failed to load maps: ${error.message}`;\n        }\n        render();\n    }\n\n    button.addEventListener('click', () => {\n        if (els.search) els.search.value = '';\n        openOverlay(modal);\n        load();\n        loadSamples();\n        window.setTimeout(() => els.search?.focus(), 50);\n    });\n    els.search?.addEventListener('input', render);\n\n    modal.addEventListener('click', (event) => {\n        const item = event.target.closest('[data-map-id]');\n        if (!item || item.disabled) return;\n        const url = mapUrl(item.dataset.mapId);\n        closeOverlay(modal);\n        const go = () => window.location.assign(url);\n        if (!guard?.needsGuard()) {\n            go();\n            return;\n        }\n        // Otev\u0159en\u00ED jin\u00E9 mapy = opu\u0161t\u011Bn\u00ED rozd\u011Blan\u00E9 mapy \u2192 hl\u00EDd\u00E1n\u00ED zm\u011Bn. Modal\n        // neulo\u017Een\u00FDch zm\u011Bn a\u017E po dob\u011Bhnut\u00ED zav\u00EDrac\u00ED animace tohoto dialogu\n        // (closeOverlay po ~300 ms ukl\u00EDz\u00ED backdrop Preline).\n        window.setTimeout(() => guard.guardNavigation(go), 350);\n    });\n}\n", "/**\n * main.js \u2014 vstupn\u00ED bod appky \"Map Viewer\". P\u0159e\u010Dte konfiguraci z JSON script\n * tagu \"map-bootstrap\" (viz templates/maps/viewer.html), postav\u00ED mapu a\n * propoj\u00ED v\u0161echny moduly (vrstvy, styl, identify, perzistence, messaging,\n * \"Add data\", \"Open map\", hl\u00EDd\u00E1n\u00ED neulo\u017Een\u00FDch zm\u011Bn, hl\u00E1\u0161en\u00ED chyb vrstev).\n */\nimport { debounce, on } from './utils.js';\nimport {\n    createState, createGroupEntry, findEntryContainer, flatLayers,\n} from './state.js';\nimport {\n    createBasemaps,\n    createMap,\n    addStandardControls,\n    setBasemap,\n    applyBasemapLook,\n    renderBasemapSwitcher,\n    syncBasemapLookControls,\n} from './map.js';\nimport { normalizeBasemapLook } from './basemap-look.js';\nimport {\n    addLayerByItemId,\n    zoomToAllLayers,\n    createGroup,\n    moveEntry,\n    prefetchItem,\n    removeLayer,\n    renderLayerTree,\n    updateLayerStatus,\n    updateScaleDimming,\n} from './layers.js';\nimport { beginPreparing, endPreparing, initLoadingIndicator } from './loading.js';\nimport { initLocate } from './locate.js';\nimport { initAdvisor } from './advisor.js';\nimport { initStyleExport } from './style-export.js';\nimport { initMobileMenu, isMobileLayout } from './mobile.js';\nimport { initProperties } from './properties.js';\nimport { toggleStylePanel } from './style-ui.js';\nimport { initIdentify } from './identify.js';\nimport { initAttrTable } from './attr-table.js';\nimport { initMeasure } from './measure.js';\nimport { initDraw, restoreDrawingLayer } from './draw.js';\nimport { exportMapImage } from './export.js';\nimport { initPresentMode } from './present.js';\nimport { saveMap, cleanupLegacyAutosave } from './persist.js';\nimport {\n    initShare,\n    applyReadOnlyMode,\n    applySharedView,\n    consumePermalinkView,\n    applyPermalinkView,\n} from './share.js';\nimport { initMessaging } from './messaging.js';\nimport { initAddDataModal, initSampleData, invalidateItems } from './items.js';\nimport { initMapUpload } from './upload.js';\nimport { initExternalSources } from './external-ui.js';\nimport { restoreExternalLayer, isExternalType } from './external.js';\nimport { refreshSignatureIfNeeded } from './wms.js';\nimport { initUnsavedGuard } from './unsaved.js';\nimport { initOpenMapDialog } from './open-map.js';\nimport { initCreditsModal, reportLayerProblems, reportSkippedParts, showToast } from './notices.js';\n\n/** D\u016Fvody `layers:changed`, kter\u00E9 u read-only div\u00E1ka nejsou \u201Evlastn\u00ED zm\u011Bnou\u201C. */\nconst VIEW_ONLY_REASONS = new Set(['visibility', 'opacity']);\n\nfunction readBootstrap() {\n    const el = document.getElementById('map-bootstrap');\n    if (!el) throw new Error('Missing JSON script tag \"map-bootstrap\" \u2014 template was not rendered correctly.');\n    return JSON.parse(el.textContent);\n}\n\nfunction queryElements() {\n    return {\n        mapTarget: document.getElementById('map-view'),\n        layerTree: document.getElementById('map-layer-tree'),\n        newGroupButton: document.getElementById('map-btn-new-group'),\n        sidebar: document.getElementById('map-sidebar'),\n        sidebarToggle: document.getElementById('map-btn-sidebar-toggle'),\n        sidebarClose: document.getElementById('map-btn-sidebar-close'),\n        sidebarOverlay: document.getElementById('map-sidebar-overlay'),\n        sidebarResizer: document.getElementById('map-sidebar-resizer'),\n        basemapSwitcher: document.getElementById('map-basemap-switcher'),\n        mobileBasemaps: document.getElementById('map-mobile-basemaps'),\n        mousePosition: document.getElementById('map-mouse-position'),\n        popup: document.getElementById('map-popup'),\n        attrTable: document.getElementById('map-attr-table'),\n        zoomAllButton: document.getElementById('map-btn-zoom-all'),\n        titleInput: document.getElementById('map-title-input'),\n        saveButton: document.getElementById('map-btn-save'),\n        saveAsButton: document.getElementById('map-btn-save-as'),\n        saveStatus: document.getElementById('map-save-status'),\n        saveModal: document.getElementById('map-save-modal'),\n        saveForm: document.getElementById('map-save-form'),\n        saveFormTitle: document.getElementById('map-save-form-title'),\n        saveFormDescription: document.getElementById('map-save-form-description'),\n        addDataModal: document.getElementById('map-add-data-modal'),\n        addDataButton: document.getElementById('map-btn-add-data'),\n        itemsList: document.getElementById('map-items-list'),\n        itemsSearch: document.getElementById('map-items-search'),\n        itemsFilterButtons: Array.from(document.querySelectorAll('[data-role=\"items-filter\"]')),\n        uploadButton: document.getElementById('map-upload-button'),\n        uploadButtonUrlTab: document.getElementById('map-upload-button-url-tab'),\n        dropZone: document.getElementById('map-drop-zone'),\n        measureDistanceButton: document.getElementById('map-btn-measure-distance'),\n        measureAreaButton: document.getElementById('map-btn-measure-area'),\n        measureClearButton: document.getElementById('map-btn-measure-clear'),\n        drawButton: document.getElementById('map-btn-draw'),\n        drawToolbar: document.getElementById('map-draw-toolbar'),\n        exportPngButton: document.getElementById('map-btn-export-png'),\n        exportJpgButton: document.getElementById('map-btn-export-jpg'),\n        presentButton: document.getElementById('map-btn-present'),\n        presentExitButton: document.getElementById('map-btn-present-exit'),\n        shareButton: document.getElementById('map-btn-share'),\n        saveCopyButton: document.getElementById('map-btn-save-copy'),\n        readonlyBadge: document.getElementById('map-readonly-badge'),\n        openButton: document.getElementById('map-btn-open'),\n        newButton: document.getElementById('map-btn-new'),\n    };\n}\n\nfunction setSaveStatus(elements, text) {\n    if (elements.saveStatus) elements.saveStatus.textContent = text;\n}\n\n/** Otev\u0159e modal Preline programov\u011B (pokud je knihovna na\u010Dten\u00E1). */\nfunction openOverlay(el) {\n    if (!el) return;\n    if (window.HSOverlay) {\n        try {\n            window.HSOverlay.open(el);\n            return;\n        } catch {\n            // Preline inicializuje kolekci overlay\u016F a\u017E po `load` \u2014 modal\n            // otev\u0159en\u00FD d\u0159\u00EDv (nap\u0159. 402 p\u0159i na\u010D\u00EDt\u00E1n\u00ED vrstev) by spadl.\n        }\n        try {\n            window.HSStaticMethods?.autoInit?.(['overlay']);\n            window.HSOverlay.open(el);\n            return;\n        } catch {\n            /* nouzov\u011B bez Preline n\u00ED\u017Ee */\n        }\n    }\n    el.classList.remove('hidden');\n    el.classList.add('open', 'opened');\n}\n\nfunction closeOverlay(el) {\n    if (!el) return;\n    if (window.HSOverlay) {\n        window.HSOverlay.close(el);\n        // Robustn\u00ED fix: Preline n\u011Bkdy p\u0159i programov\u00E9m zav\u0159en\u00ED zapomene odstranit\n        // backdrop nebo t\u0159\u00EDdy na body, co\u017E zp\u016Fsob\u00ED \u201Eza\u0161ednut\u00ED\u201C.\n        setTimeout(() => {\n            const backdrop = document.querySelector('[data-hs-overlay-backdrop-template]');\n            if (backdrop) backdrop.remove();\n            document.body.style.overflow = '';\n            document.body.classList.remove('overflow-hidden');\n        }, 300);\n    } else {\n        el.classList.add('hidden');\n    }\n}\n\n/** Obnov\u00ED jeden ulo\u017Een\u00FD z\u00E1znam vrstvy (bez skupin). Vrac\u00ED entry nebo null. */\nasync function restoreSingleLayer(ctx, saved) {\n    // Kresba (type \"drawing\") je klientsk\u00E1 vrstva bez itemId \u2014 obnov\u00ED\n    // se p\u0159\u00EDmo z GeoJSON v configu (viz draw.js).\n    if (saved.type === 'drawing') {\n        return restoreDrawingLayer(ctx, saved);\n    }\n    // Extern\u00ED vrstvy (wms/xyz/wmts/local) \u2014 obnova z configu bez API;\n    // WMTS znovu na\u010D\u00EDt\u00E1 capabilities (selh\u00E1n\u00ED = p\u0159esko\u010Den\u00ED s varov\u00E1n\u00EDm).\n    if (isExternalType(saved.type)) {\n        return restoreExternalLayer(ctx, saved);\n    }\n    return addLayerByItemId(ctx, saved.itemId, saved, { pending: saved.pendingRow });\n}\n\n/** Z\u00E1znam o vrstv\u011B, kterou se nepoda\u0159ilo na\u010D\u00EDst (pro `reportLayerProblems`). */\nfunction layerProblem(saved, error) {\n    return {\n        key: saved.itemId || saved.title || saved.type,\n        title: saved.title || 'Untitled layer',\n        status: error?.status || 0,\n    };\n}\n\n/** Vrstvu, kter\u00E1 se nena\u010Detla jen do\u010Dasn\u011B (402 = do\u0161ly kredity, s\u00ED\u0165, 5xx) nebo\n * je skryt\u00E1 jen tomuto div\u00E1kovi (403 = data mu nikdo nesd\u00EDlel, ostatn\u00ED ji vid\u00ED),\n * si zapamatujeme, aby ji ulo\u017Een\u00ED mapy (editorem) neodstranilo z configu (viz\n * persist.js `buildCurrentConfig`). 404 (data smazan\u00E1) se nepamatuje \u2014\n * ulo\u017Een\u00EDm se takov\u00E1 vrstva z mapy odebere. */\nfunction rememberUnloaded(ctx, saved, error, groupTitle = null) {\n    const status = error?.status || 0;\n    if (status === 402 || status === 403 || status === 0 || status >= 500) {\n        ctx.state.unloadedLayers.push({ config: saved, groupTitle });\n    }\n}\n\n/** Ulo\u017Een\u00E9 vrstvy z workspace (i uvnit\u0159 skupin). */\nfunction savedWorkspaceLayers(savedLayers) {\n    return savedLayers\n        .flatMap((saved) => (saved.type === 'group' ? (saved.children || []) : [saved]))\n        .filter((saved) => saved.itemId && saved.type !== 'drawing' && !isExternalType(saved.type));\n}\n\nasync function bootstrapLayers(ctx) {\n    const savedLayers = ctx.state.config.layers || [];\n    const problems = [];\n    ctx.state.unloadedLayers = [];\n    // Hned po otev\u0159en\u00ED mapy je vid\u011Bt, co se bude na\u010D\u00EDtat (\u0159\u00E1dky \u201EReading the\n    // data\u2026\u201C ve stromu vrstev), a popisy dat v\u0161ech polo\u017Eek se vy\u017E\u00E1daj\u00ED nar\u00E1z \u2014\n    // vrstvy se pak vkl\u00E1daj\u00ED po jedn\u00E9 kv\u016Fli po\u0159ad\u00ED, ale u\u017E na nic ne\u010Dekaj\u00ED.\n    const workspaceLayers = savedWorkspaceLayers(savedLayers);\n    workspaceLayers.forEach((saved) => {\n        Object.defineProperty(saved, 'pendingRow', {\n            value: beginPreparing(ctx, saved.title || 'Layer'), enumerable: false, configurable: true,\n        });\n    });\n    if (workspaceLayers.length) renderLayerTree(ctx);\n    new Set(workspaceLayers.map((saved) => saved.itemId)).forEach((itemId) => prefetchItem(ctx, itemId));\n    // Vrstvy p\u0159id\u00E1v\u00E1me SEKVEN\u010CN\u011A a v obr\u00E1cen\u00E9m po\u0159ad\u00ED: ka\u017Ed\u00E1 obnoven\u00E1 vrstva\n    // se vkl\u00E1d\u00E1 navrch, tak\u017Ee po zpracov\u00E1n\u00ED [posledn\u00ED \u2192 prvn\u00ED] skon\u010D\u00ED pole\n    // state.layers p\u0159esn\u011B v ulo\u017Een\u00E9m po\u0159ad\u00ED (d\u0159\u00EDv\u011Bj\u0161\u00ED paraleln\u00ED Promise.all\n    // vedlo k n\u00E1hodn\u00E9mu po\u0159ad\u00ED podle rychlosti odpov\u011Bd\u00ED API).\n    for (const saved of [...savedLayers].reverse()) {\n        try {\n            // Skupina vrstev: vytvo\u0159\u00ED se pr\u00E1zdn\u00FD uzel a d\u011Bti se po obnov\u011B\n            // p\u0159esunou dovnit\u0159 (ka\u017Ed\u00E1 vznik\u00E1 v top-level navrchu stromu).\n            if (saved.type === 'group') {\n                const group = createGroupEntry(saved);\n                ctx.state.layers.unshift(group);\n                for (const child of [...(saved.children || [])].reverse()) {\n                    try {\n                        const restored = await restoreSingleLayer(ctx, child);\n                        // Star\u0161\u00ED z\u00E1znam za cel\u00FD v\u00EDcevrstv\u00FD soubor se obnov\u00ED\n                        // jako v\u00EDc vrstev (pole) \u2014 v\u0161echny pat\u0159\u00ED do skupiny.\n                        const entries = Array.isArray(restored) ? restored : [restored];\n                        [...entries].reverse().forEach((entry) => {\n                            if (entry) moveEntry(ctx, entry.uid, group.uid, 0);\n                        });\n                    } catch (error) {\n                        console.warn(`Failed to load layer ${child.itemId || child.type}:`, error);\n                        problems.push(layerProblem(child, error));\n                        rememberUnloaded(ctx, child, error, saved.title || null);\n                    }\n                }\n                renderLayerTree(ctx);\n                continue;\n            }\n            const restored = await restoreSingleLayer(ctx, saved);\n            if (Array.isArray(restored) && restored.length > 1) {\n                // Star\u0161\u00ED ulo\u017Een\u00E1 mapa kreslila v\u00EDcevrstv\u00FD soubor jedn\u00EDm\n                // z\u00E1znamem; te\u010F m\u00E1 ka\u017Ed\u00E1 vrstva vlastn\u00ED \u2192 skupina souboru.\n                const group = createGroupEntry({ title: restored.legacyTitle, dataset: true, visible: true });\n                ctx.state.layers.unshift(group);\n                [...restored].reverse().forEach((entry) => moveEntry(ctx, entry.uid, group.uid, 0));\n                renderLayerTree(ctx);\n            }\n        } catch (error) {\n            // Vrstva mohla b\u00FDt mezit\u00EDm smaz\u00E1na/nedostupn\u00E1 \u2014 nechceme kv\u016Fli\n            // jedn\u00E9 vrstv\u011B shodit na\u010Dten\u00ED cel\u00E9 mapy. U\u017Eivatel dostane souhrnn\u00E9\n            // hl\u00E1\u0161en\u00ED (403/404 \u2192 nem\u00E1 p\u0159\u00EDstup / data smazan\u00E1), ne jen konzoli.\n            console.warn(`Failed to load layer ${saved.itemId || saved.type}:`, error);\n            problems.push(layerProblem(saved, error));\n            rememberUnloaded(ctx, saved, error);\n        }\n    }\n    // \u0158\u00E1dky vrstev, kter\u00E9 se nena\u010Detly (chyba d\u0159\u00EDv, ne\u017E na n\u011B p\u0159i\u0161la \u0159ada).\n    workspaceLayers.forEach((saved) => endPreparing(ctx, saved.pendingRow));\n    renderLayerTree(ctx);\n    if (problems.length) reportLayerProblems(problems);\n}\n\nasync function handleAddItems(ctx, itemIds, titles = {}) {\n    for (const itemId of itemIds) {\n        try {\n            await addLayerByItemId(ctx, itemId, null, { title: titles[itemId] });\n            ctx.state.dirty = true;\n        } catch (error) {\n            console.warn(`Failed to add layer ${itemId}:`, error);\n            reportLayerProblems([{ key: itemId, title: 'New layer', status: error?.status || 0 }]);\n        }\n    }\n    zoomToAllLayers(ctx);\n}\n\nconst ADD_DATA_CTA = ['border-accent-700', 'bg-accent-700', 'text-white', 'hover:bg-accent-800'];\nconst ADD_DATA_PLAIN = ['border-slate-200', 'bg-white', 'text-slate-700', 'hover:bg-slate-50'];\n\n/** \u201EAdd data\u201C v horn\u00ED li\u0161t\u011B je zelen\u00E9, dokud mapa nem\u00E1 \u017E\u00E1dnou vrstvu \u2014 a\u0165\n * nov\u00FD u\u017Eivatel v\u00ED, kde za\u010D\u00EDt. Jakmile se n\u011Bco p\u0159id\u00E1v\u00E1, vr\u00E1t\u00ED se k ostatn\u00EDm. */\nfunction syncAddDataCta(ctx) {\n    const button = ctx.elements.addDataButton;\n    if (!button) return;\n    const empty = ctx.state.layers.length === 0 && (ctx.state.preparing || []).length === 0;\n    ADD_DATA_CTA.forEach((cls) => button.classList.toggle(cls, empty));\n    ADD_DATA_PLAIN.forEach((cls) => button.classList.toggle(cls, !empty));\n}\n\nfunction wireTopBar(ctx, elements) {\n    if (elements.titleInput) {\n        elements.titleInput.value = ctx.state.title;\n        elements.titleInput.addEventListener('input', () => {\n            ctx.state.title = elements.titleInput.value;\n            ctx.state.dirty = true;\n        });\n    }\n\n    async function doSave(asNew) {\n        setSaveStatus(elements, 'Saving\u2026');\n        try {\n            await saveMap(ctx, { asNew });\n            setSaveStatus(elements, 'Saved');\n            closeOverlay(elements.saveModal);\n        } catch (error) {\n            setSaveStatus(elements, `Error saving: ${error.message}`);\n        }\n    }\n\n    elements.saveButton?.addEventListener('click', () => {\n        if (ctx.state.mapId) {\n            doSave(false);\n        } else {\n            elements.saveFormTitle.value = ctx.state.title;\n            elements.saveFormDescription.value = ctx.state.description;\n            ctx.saveModalMode = 'save';\n            openOverlay(elements.saveModal);\n        }\n    });\n\n    elements.saveAsButton?.addEventListener('click', () => {\n        elements.saveFormTitle.value = ctx.state.title;\n        elements.saveFormDescription.value = ctx.state.description;\n        ctx.saveModalMode = 'saveAs';\n        // Kopie ciz\u00ED mapy: vrstvy s daty, kter\u00E1 div\u00E1k s\u00E1m nevid\u00ED, v n\u00ED nebudou.\n        const omits = ctx.bootstrap.copyOmits || [];\n        const note = document.getElementById('map-save-omits');\n        if (note) {\n            note.textContent = omits.length\n                ? `Your copy won\u2019t include ${omits.length === 1 ? 'this layer' : `these ${omits.length} layers`} \u2014 `\n                    + `the owner hasn\u2019t shared their data with you: ${omits.join(', ')}.`\n                : '';\n            note.classList.toggle('hidden', omits.length === 0);\n        }\n        openOverlay(elements.saveModal);\n    });\n    elements.saveButton?.addEventListener('click', () => {\n        document.getElementById('map-save-omits')?.classList.add('hidden');\n    });\n\n    elements.saveForm?.addEventListener('submit', async (event) => {\n        event.preventDefault();\n        ctx.state.title = elements.saveFormTitle.value.trim() || ctx.state.title;\n        ctx.state.description = elements.saveFormDescription.value.trim();\n        await doSave(ctx.saveModalMode === 'saveAs');\n    });\n\n    elements.zoomAllButton?.addEventListener('click', () => zoomToAllLayers(ctx));\n\n    // Nov\u00E1 pr\u00E1zdn\u00E1 skupina vrstev navrchu stromu (p\u0159ejmenov\u00E1n\u00ED dvojklikem).\n    elements.newGroupButton?.addEventListener('click', () => createGroup(ctx));\n\n    elements.addDataButton?.addEventListener('click', () => openOverlay(elements.addDataModal));\n}\n\n/** Propoj\u00ED n\u00E1stroje horn\u00ED li\u0161ty: m\u011B\u0159en\u00ED, kreslen\u00ED, export obr\u00E1zku, prezentace. */\nfunction wireTools(ctx, elements) {\n    const measure = initMeasure(ctx);\n    const draw = initDraw(ctx, elements.drawToolbar);\n\n    elements.measureDistanceButton?.addEventListener('click', () => {\n        draw.close();\n        measure.activate('distance');\n    });\n    elements.measureAreaButton?.addEventListener('click', () => {\n        draw.close();\n        measure.activate('area');\n    });\n    elements.measureClearButton?.addEventListener('click', () => measure.clear());\n\n    elements.drawButton?.addEventListener('click', () => {\n        measure.deactivate();\n        if (draw.isOpen()) {\n            draw.close();\n        } else {\n            draw.open();\n        }\n    });\n\n    async function doExport(format) {\n        try {\n            await exportMapImage(ctx, format);\n        } catch (error) {\n            setSaveStatus(elements, `Export failed: ${error.message}`);\n        }\n    }\n    elements.exportPngButton?.addEventListener('click', () => doExport('png'));\n    elements.exportJpgButton?.addEventListener('click', () => doExport('jpg'));\n\n    initPresentMode(ctx, {\n        button: elements.presentButton,\n        exitButton: elements.presentExitButton,\n    });\n}\n\nfunction wireBasemapSwitcher(ctx, elements) {\n    // P\u0159ep\u00EDna\u010D je v li\u0161t\u011B (desktop) i v nab\u00EDdce \u201EMore\u201C (telefon) \u2014 oba se\n    // p\u0159ekresluj\u00ED spole\u010Dn\u011B, aby ukazovaly stejn\u00FD aktivn\u00ED podklad a vzhled.\n    const containers = [elements.basemapSwitcher, elements.mobileBasemaps].filter(Boolean);\n    function render(key) {\n        containers.forEach((container) => renderBasemapSwitcher(container, ctx.basemaps, key, onChange, {\n            look: ctx.state.config.basemapLook,\n            onLookChange,\n        }));\n    }\n    function onChange(key) {\n        setBasemap(ctx.basemaps, key);\n        if (!ctx.readOnly) ctx.state.dirty = true;\n        render(key);\n    }\n    // Vzhled podkladu (pr\u016Fhlednost, \u010Dernob\u00EDle) se ukl\u00E1d\u00E1 s mapou; ovl\u00E1d\u00E1n\u00ED\n    // se p\u0159i ta\u017Een\u00ED posuvn\u00EDku nep\u0159ekresluje (ta\u017Een\u00ED by se p\u0159eru\u0161ilo), jen\n    // se srovnaj\u00ED hodnoty v obou p\u0159ep\u00EDna\u010D\u00EDch.\n    function onLookChange(look) {\n        ctx.state.config.basemapLook = normalizeBasemapLook(look);\n        applyBasemapLook(ctx.basemaps, ctx.state.config.basemapLook);\n        if (!ctx.readOnly) ctx.state.dirty = true;\n        containers.forEach((container) => syncBasemapLookControls(container, ctx.state.config.basemapLook));\n    }\n    const activeKey = Object.entries(ctx.basemaps).find(([, layer]) => layer.getVisible())?.[0] || 'osm';\n    render(activeKey);\n}\n\n/** Periodicky (ka\u017Ed\u00FDch 30 s) zkontroluje bl\u00ED\u017E\u00EDc\u00ED se expiraci podpis\u016F WMS\n * u aktivn\u00EDch vrstev a v p\u0159\u00EDpad\u011B pot\u0159eby si vy\u017E\u00E1d\u00E1 nov\u00FD podpis. */\nfunction startSignatureWatcher(ctx) {\n    setInterval(() => {\n        flatLayers(ctx.state).forEach((entry) => {\n            if (!entry.wms) return; // kresba/extern\u00ED vrstvy WMS podpis nemaj\u00ED\n            refreshSignatureIfNeeded(entry, ctx.bootstrap, 60, ctx.state.mapId).catch((error) => {\n                // 403/404 = p\u0159\u00EDstup k vrstv\u011B mezit\u00EDm zanikl (odebran\u00E9 sd\u00EDlen\u00ED,\n                // smazan\u00E1 data) \u2014 vrstva po vypr\u0161en\u00ED podpisu p\u0159estane kreslit,\n                // tak to u\u017Eivateli \u0159ekneme. Jin\u00E9 chyby (s\u00ED\u0165) zkus\u00EDme p\u0159i\n                // dal\u0161\u00EDm tiku; 402 \u0159e\u0161\u00ED modal kredit\u016F.\n                if (error?.status === 403 || error?.status === 404) {\n                    reportLayerProblems([{ key: entry.uid, title: entry.title, status: error.status }]);\n                }\n            });\n        });\n    }, 30000);\n}\n\n/** Po \u201ESave as\u201C server z kopie vynech\u00E1 workspace vrstvy, k jejich\u017E dat\u016Fm\n * u\u017Eivatel s\u00E1m p\u0159\u00EDstup nem\u00E1 (p\u0159\u00EDstup zd\u011Bd\u011Bn\u00FD z ciz\u00ED sd\u00EDlen\u00E9 mapy se na kopii\n * nep\u0159en\u00E1\u0161\u00ED). Odebereme je i z b\u011Bhov\u00E9ho stavu, aby mapa odpov\u00EDdala ulo\u017Een\u00E9\n * kopii, a \u0159ekneme pro\u010D. */\nfunction pruneOmittedLayers(ctx, savedMap, omittedLayers) {\n    if (!omittedLayers) return;\n    const keep = new Set();\n    (savedMap?.config?.layers || []).forEach((layer) => {\n        const list = layer?.type === 'group' ? (layer.children || []) : [layer];\n        list.forEach((l) => { if (l?.itemId) keep.add(String(l.itemId).toLowerCase()); });\n    });\n    const removed = flatLayers(ctx.state)\n        .filter((entry) => entry.itemId && !entry.external && entry.dataType !== 'drawing'\n            && !keep.has(String(entry.itemId).toLowerCase()));\n    removed.forEach((entry) => removeLayer(ctx, entry.uid));\n    ctx.state.unloadedLayers = (ctx.state.unloadedLayers || [])\n        .filter(({ config }) => !config?.itemId || keep.has(String(config.itemId).toLowerCase()));\n    ctx.state.dirty = false;\n    reportLayerProblems(removed.map((entry) => ({\n        key: `omitted-${entry.uid}`,\n        title: entry.title,\n        status: 'omitted',\n    })));\n}\n\nfunction wireSidebar(ctx, elements) {\n    const {\n        sidebar, sidebarToggle, sidebarClose, sidebarOverlay, sidebarResizer,\n    } = elements;\n\n    // Mobiln\u00ED drawer\n    const openSidebar = () => {\n        sidebar?.classList.remove('-translate-x-full');\n        sidebarOverlay?.classList.remove('hidden');\n    };\n    const closeSidebar = () => {\n        sidebar?.classList.add('-translate-x-full');\n        sidebarOverlay?.classList.add('hidden');\n    };\n\n    sidebarToggle?.addEventListener('click', openSidebar);\n    sidebarClose?.addEventListener('click', closeSidebar);\n    sidebarOverlay?.addEventListener('click', closeSidebar);\n    // Akce, jej\u00ED\u017E v\u00FDsledek je vid\u011Bt v map\u011B (Zoom to layer, tabulka atribut\u016F\u2026):\n    // na telefonu v\u00FDsuvn\u00FD panel mapu zakr\u00FDv\u00E1, tak se zav\u0159e.\n    on('ui:show-map', () => { if (isMobileLayout()) closeSidebar(); });\n\n    // Resizer logic (Desktop)\n    if (sidebar && sidebarResizer) {\n        let isResizing = false;\n\n        sidebarResizer.addEventListener('mousedown', (e) => {\n            e.preventDefault();\n            isResizing = true;\n            document.addEventListener('mousemove', handleMouseMove);\n            document.addEventListener('mouseup', stopResizing);\n            document.body.classList.add('cursor-col-resize', 'select-none');\n        });\n\n        const handleMouseMove = (e) => {\n            if (!isResizing) return;\n            const newWidth = Math.max(260, Math.min(600, e.clientX));\n            sidebar.style.width = `${newWidth}px`;\n            ctx.map?.updateSize();\n        };\n\n        const stopResizing = () => {\n            isResizing = false;\n            document.removeEventListener('mousemove', handleMouseMove);\n            document.removeEventListener('mouseup', stopResizing);\n            document.body.classList.remove('cursor-col-resize', 'select-none');\n        };\n    }\n}\n\nasync function main() {\n    const bootstrap = readBootstrap();\n    const elements = queryElements();\n    // Nab\u00EDdka \u201EMore\u201C na telefonu ne\u010Dek\u00E1 na na\u010Dten\u00ED vrstev \u2014 jen p\u0159epos\u00EDl\u00E1 kliky.\n    initMobileMenu();\n    const state = createState(bootstrap);\n\n    // Permalink `?view=<lon>,<lat>,<zoom>` se p\u0159e\u010Dte a z URL odstran\u00ED hned na\n    // za\u010D\u00E1tku (refresh se pak chov\u00E1 norm\u00E1ln\u011B); aplikuje se a\u017E po\n    // na\u010Dten\u00ED vrstev m\u00EDsto v\u00FDchoz\u00EDho zoomu na v\u0161echny vrstvy.\n    const permalinkView = consumePermalinkView();\n\n    const basemaps = createBasemaps(bootstrap.basemaps || {});\n    const map = createMap(elements.mapTarget, state.config, basemaps, { defaultExtent: bootstrap.defaultExtent });\n    addStandardControls(map, elements.mousePosition);\n\n    const ctx = {\n        bootstrap, state, map, basemaps, elements,\n        // B\u011Bhem obnovy vrstev z Map.config se zm\u011Bny stromu nepo\u010D\u00EDtaj\u00ED jako\n        // neulo\u017Een\u00E9 zm\u011Bny (viz `layers:changed` n\u00ED\u017Ee).\n        restoring: true,\n    };\n\n    // Autosave do localStorage byl zru\u0161en \u2014 uklid\u00EDme jeho star\u00E9 z\u00E1znamy.\n    cleanupLegacyAutosave();\n\n    wireSidebar(ctx, elements);\n    wireBasemapSwitcher(ctx, elements);\n    wireTopBar(ctx, elements);\n    wireTools(ctx, elements);\n\n    // Sd\u00EDlen\u00ED (d\u00E1vka c): Share modal + read-only re\u017Eim pro canEdit=false.\n    initShare(ctx, elements, { openOverlay, closeOverlay });\n    applyReadOnlyMode(ctx, elements);\n    applySharedView(ctx, elements);\n\n    // Hl\u00EDd\u00E1n\u00ED neulo\u017Een\u00FDch zm\u011Bn (Save and continue / Discard / Stay + beforeunload).\n    const guard = initUnsavedGuard(ctx, { openOverlay, closeOverlay });\n    // Navigace mimo mapu z jin\u00FDch modul\u016F (nab\u00EDdka uk\u00E1zkov\u00FDch map, sample-maps.js).\n    ctx.guard = guard;\n    initOpenMapDialog(ctx, {\n        button: elements.openButton, openOverlay, closeOverlay, guard,\n    });\n    // \u201ENew map\u201C: pr\u00E1zdn\u00E1 mapa na adrese vieweru. Rozd\u011Blanou pr\u00E1ci ohl\u00EDd\u00E1\n    // stejn\u00FD dialog jako ka\u017Ed\u00FD jin\u00FD odchod (Save / Discard / Stay).\n    const newMap = () => guard.guardNavigation(() => {\n        window.location.assign(`${bootstrap.apiBase.replace(/\\/api$/, '')}/`);\n    });\n    elements.newButton?.addEventListener('click', newMap);\n    document.querySelector('#map-open-modal [data-role=\"open-new\"]')?.addEventListener('click', () => {\n        closeOverlay(document.getElementById('map-open-modal'));\n        // A\u017E po zav\u0159en\u00ED dialogu (Preline dr\u017E\u00ED jen jeden overlay nar\u00E1z).\n        window.setTimeout(newMap, 350);\n    });\n\n    on('layers:toggle-style-panel', ({ uid, row, open }) => toggleStylePanel(ctx, uid, row, { open }));\n    // 402 z /wms/: vlastn\u00EDkovi mapy do\u0161ly kredity \u2014 modal s vysv\u011Btlen\u00EDm.\n    const showCreditsModal = initCreditsModal(ctx, { openOverlay, closeOverlay });\n    on('credits:insufficient', (payload) => showCreditsModal(payload));\n    // Jak\u00E1koli zm\u011Bna stromu vrstev (p\u0159id\u00E1n\u00ED, odebr\u00E1n\u00ED, po\u0159ad\u00ED, viditelnost,\n    // pr\u016Fhlednost, p\u0159ejmenov\u00E1n\u00ED\u2026) je neulo\u017Een\u00E1 zm\u011Bna obsahu \u2014 krom\u011B obnovy.\n    // Div\u00E1k ciz\u00ED mapy (read-only) mapu p\u0159epsat nem\u016F\u017Ee \u2014 pouh\u00E9 \u201Eprohl\u00ED\u017Eec\u00ED\u201C\n    // \u00FApravy (viditelnost, pr\u016Fhlednost, podklad) ho neotravuj\u00ED upozorn\u011Bn\u00EDm;\n    // vlastn\u00ED obsah (vrstvy, kresba, styl\u2026) ano (m\u016F\u017Ee si ulo\u017Eit kopii).\n    on('layers:changed', ({ reason } = {}) => {\n        if (ctx.restoring) return;\n        if (ctx.readOnly && VIEW_ONLY_REASONS.has(reason)) return;\n        ctx.state.dirty = true;\n    });\n    on('map:saved', ({ map: savedMap, omittedLayers }) => pruneOmittedLayers(ctx, savedMap, omittedLayers));\n    // N\u00E1zev z dialogu Save / Save as / Share pat\u0159\u00ED i do horn\u00ED li\u0161ty.\n    on('map:saved', () => {\n        if (elements.titleInput && elements.titleInput.value !== ctx.state.title) {\n            elements.titleInput.value = ctx.state.title || '';\n        }\n    });\n    // Prvn\u00ED ulo\u017Een\u00ED nov\u00E9 mapy: nab\u00EDdka sd\u00EDlen\u00ED (bez \u00FA\u010Dtu s upozorn\u011Bn\u00EDm, jak dlouho\n    // mapa vydr\u017E\u00ED). Neukazuje se, kdy\u017E ukl\u00E1d\u00E1n\u00ED spustil dialog sd\u00EDlen\u00ED (`quiet`).\n    on('map:saved', ({ firstSave, quiet }) => {\n        if (!firstSave || quiet || ctx.readOnly) return;\n        const message = bootstrap.isAuthenticated\n            ? 'Map saved. Share it with a link, by e-mail or with your team.'\n            : `Map saved for ${bootstrap.anonRetentionDays} days. Create a free account to keep it and share it.`;\n        showToast(message, {\n            tone: 'ok',\n            timeout: 10000,\n            action: { label: 'Share', onClick: () => elements.shareButton?.click() },\n        });\n    });\n    // \u010C\u00E1sti souboru, kter\u00E9 MapServer nevykreslil (hlavi\u010Dka `X-GCZ-Skipped-Layers`\n    // prvn\u00EDho GetMap vrstvy, viz wms.js) \u2014 vysv\u011Btlen\u00ED podle k\u00F3du d\u016Fvodu.\n    // U \u010D\u00E1sti hybridu se hl\u00E1s\u00ED pod n\u00E1zvem jeho skupiny (= polo\u017Eky).\n    on('wms:diagnostics', ({ entry, skipped }) => {\n        if (!entry || !(skipped?.layers?.length || skipped?.omitted)) return;\n        const container = findEntryContainer(ctx.state, entry.uid)?.group;\n        const group = container?.dataset ? container : null;\n        reportSkippedParts({\n            itemId: entry.itemId || entry.uid,\n            title: group?.title || entry.itemTitle || entry.title,\n            skipped,\n            reasons: bootstrap.skipReasons || {},\n        });\n    });\n\n    // Properties modal vrstvy (kebab menu ve stromu vrstev).\n    initProperties(ctx);\n\n    // Indikace \u010Dek\u00E1n\u00ED na vykreslen\u00ED (pruh + \u0161t\u00EDtek nad mapou, kole\u010Dko u vrstvy).\n    initLoadingIndicator(ctx);\n    initLocate(ctx);\n    initAdvisor(ctx);\n    initStyleExport(ctx);\n    on('layer:loading', ({ entry }) => updateLayerStatus(ctx, entry));\n\n    // Ze\u0161ednut\u00ED n\u00E1zv\u016F vrstev mimo min/max zoom p\u0159i zm\u011Bn\u011B p\u0159ibl\u00ED\u017Een\u00ED mapy.\n    const dimOnZoom = debounce(() => updateScaleDimming(ctx), 150);\n    map.getView().on('change:resolution', dimOnZoom);\n\n    initAddDataModal(ctx, {\n        modal: elements.addDataModal,\n        list: elements.itemsList,\n        search: elements.itemsSearch,\n        filterButtons: elements.itemsFilterButtons,\n    }, (itemId, title, item) => {\n        handleAddItems(ctx, [itemId], { [itemId]: title });\n        closeOverlay(elements.addDataModal);\n        // Editor ciz\u00ED mapy p\u0159id\u00E1v\u00E1 svoje data: uvid\u00ED je ka\u017Ed\u00FD, kdo mapu otev\u0159e\n        // (data, kter\u00E1 mu jen n\u011Bkdo sd\u00EDl\u00ED, ostatn\u00EDm z\u016Fstanou skryt\u00E1).\n        if (item?.owned && ctx.state.mapId && !ctx.bootstrap.isOwner) {\n            showToast(`Everyone who can open this map will see \u201C${title}\u201D.`, { tone: 'info', timeout: 8000 });\n        }\n    });\n\n    // Z\u00E1lo\u017Eka uk\u00E1zkov\u00FDch dat v modalu \"Add data\" (stejn\u00E9 p\u0159id\u00E1n\u00ED jako z workspace).\n    initSampleData(ctx, elements.addDataModal, (itemId, title) => {\n        handleAddItems(ctx, [itemId], { [itemId]: title });\n        closeOverlay(elements.addDataModal);\n    });\n\n    // Z\u00E1lo\u017Eky extern\u00EDch zdroj\u016F v modalu \"Add data\" (WMS/XYZ/WMTS/paste/URL).\n    initExternalSources(ctx, elements.addDataModal, () => closeOverlay(elements.addDataModal));\n\n    // Nahr\u00E1n\u00ED soubor\u016F p\u0159\u00EDmo z mapy (tla\u010D\u00EDtko \u201EUpload files\u201C, p\u0159eta\u017Een\u00ED na mapu):\n    // data se ulo\u017E\u00ED do Data workspace a hned p\u0159idaj\u00ED jako vrstvy (upload.js).\n    const uploads = initMapUpload(ctx, {\n        dropTarget: elements.dropZone,\n        beforeUpload: () => closeOverlay(elements.addDataModal),\n        onItemsReady: (itemIds, titles) => {\n            invalidateItems();\n            handleAddItems(ctx, itemIds, titles);\n        },\n    });\n    elements.uploadButton?.addEventListener('click', () => uploads.pick());\n    elements.uploadButtonUrlTab?.addEventListener('click', () => uploads.pick());\n    // Tla\u010D\u00EDtko \u201EAdd data\u201C v pr\u00E1zdn\u00E9m panelu vrstev (layers.js).\n    on('ui:add-data', () => openOverlay(elements.addDataModal));\n\n    if (elements.popup) {\n        initIdentify(ctx, elements.popup);\n    }\n\n    initAttrTable(ctx);\n\n    await bootstrapLayers(ctx);\n    if (permalinkView) {\n        applyPermalinkView(map, permalinkView);\n    } else if (!ctx.state.savedOnce) {\n        // Jen NOV\u00C1 (dosud neulo\u017Een\u00E1) mapa se p\u0159izp\u016Fsob\u00ED na\u010Dten\u00FDm dat\u016Fm. Ulo\u017Een\u00E1\n        // mapa m\u00E1 vlastn\u00ED v\u00FD\u0159ez v `config.view` (aplikuje ho u\u017E `createMap`),\n        // tak\u017Ee ho tady nesm\u00EDme p\u0159epsat zoomem na celkov\u00FD extent v\u0161ech vrstev.\n        zoomToAllLayers(ctx);\n    }\n\n    if (bootstrap.sharedView) {\n        await handleAddItems(ctx, bootstrap.sharedView.itemIds);\n    } else {\n        initMessaging(bootstrap, (itemIds) => handleAddItems(ctx, itemIds));\n    }\n\n    // Obnova (v\u010D. napln\u011Bn\u00ED kreseb z GeoJSON a v\u00FDchoz\u00EDho zoomu) nen\u00ED zm\u011Bna.\n    // Posun/zoom mapy dirty nenastavuje v\u016Fbec \u2014 v\u00FD\u0159ez se ulo\u017E\u00ED s mapou, ale\n    // kv\u016Fli n\u011Bmu se u\u017Eivatele na odchodu nept\u00E1me.\n    ctx.restoring = false;\n    ctx.state.dirty = false;\n\n    // Pr\u00E1zdn\u00E1 mapa: \u201EAdd data\u201C v li\u0161t\u011B je zv\u00FDrazn\u011Bn\u00E9 jako prvn\u00ED krok.\n    syncAddDataCta(ctx);\n    on('layers:changed', () => syncAddDataCta(ctx));\n    on('layer:preparing', () => syncAddDataCta(ctx));\n\n    startSignatureWatcher(ctx);\n}\n\nmain().catch((error) => {\n    console.error('Failed to start Map Viewer:', error);\n});\n"],
  "mappings": "MASO,IAAMA,GAAM,IAAI,YAGhB,SAASC,EAAKC,EAAMC,EAAQ,CAC/BH,GAAI,cAAc,IAAI,YAAYE,EAAM,CAAE,OAAAC,CAAO,CAAC,CAAC,CACvD,CAGO,SAASC,GAAGF,EAAMG,EAAS,CAC9B,IAAMC,EAAYC,GAAUF,EAAQE,EAAM,MAAM,EAChD,OAAAP,GAAI,iBAAiBE,EAAMI,CAAQ,EAC5B,IAAMN,GAAI,oBAAoBE,EAAMI,CAAQ,CACvD,CAGO,SAASE,GAAUN,EAAM,CAC5B,IAAMO,EAAS,GAAGP,CAAI,IAChBQ,EAAS,SAAS,OACnB,MAAM,GAAG,EACT,IAAKC,GAASA,EAAK,KAAK,CAAC,EACzB,KAAMA,GAASA,EAAK,WAAWF,CAAM,CAAC,EAC3C,OAAOC,EAAS,mBAAmBA,EAAO,MAAMD,EAAO,MAAM,CAAC,EAAI,IACtE,CAGO,SAASG,GAASC,EAAIC,EAAM,CAC/B,IAAIC,EAAQ,KACZ,SAASC,KAAaC,EAAM,CACxB,aAAaF,CAAK,EAClBA,EAAQ,WAAW,IAAMF,EAAG,MAAM,KAAMI,CAAI,EAAGH,CAAI,CACvD,CACA,OAAAE,EAAU,OAAS,IAAM,aAAaD,CAAK,EACpCC,CACX,CAGO,SAASE,GAAMC,EAAOC,EAAKC,EAAK,CACnC,OAAO,KAAK,IAAIA,EAAK,KAAK,IAAID,EAAKD,CAAK,CAAC,CAC7C,CASO,SAASG,GAAiBC,EAAM,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AAMvF,GAAQsF,EAAKC,GAAG,EAAI,KAGxChB,EAAS7F,GAAe6F,CAAM,CAChC,CAEA,OAAO,IACT,CAEA,SAASmB,GAAQvC,EAAiC,CAEhD,GAAI,CAACA,EACH,MAAO,GAGT,GAAI,CACFF,OAAAA,GAAWE,EAAiB,EAAE,EACvB,EACT,MAAQ,CACN,MAAO,EACT,CACF,CC3VA,IAAawC,GAAO/G,GAAO,CACzB,IACA,OACA,UACA,UACA,OACA,UACA,QACA,QACA,IACA,MACA,MACA,MACA,QACA,aACA,OACA,KACA,SACA,SACA,UACA,SACA,OACA,OACA,MACA,WACA,UACA,OACA,WACA,KACA,YACA,MACA,UACA,MACA,SACA,MACA,MACA,KACA,KACA,UACA,KACA,WACA,aACA,SACA,OACA,SACA,OACA,KACA,KACA,KACA,KACA,KACA,KACA,OACA,SACA,SACA,KACA,OACA,IACA,MACA,QACA,MACA,MACA,QACA,SACA,KACA,OACA,MACA,OACA,UACA,OACA,WACA,QACA,MACA,OACA,KACA,WACA,SACA,SACA,IACA,UACA,MACA,WACA,IACA,KACA,KACA,OACA,IACA,OACA,SACA,UACA,SACA,SACA,OACA,QACA,SACA,SACA,OACA,SACA,SACA,QACA,MACA,UACA,MACA,QACA,QACA,KACA,WACA,WACA,QACA,KACA,QACA,OACA,KACA,QACA,KACA,IACA,KACA,MACA,QACA,KAAK,CACG,EAEGgH,GAAMhH,GAAO,CACxB,MACA,IACA,WACA,cACA,eACA,eACA,gBACA,mBACA,SACA,WACA,OACA,OACA,UACA,SACA,OACA,IACA,QACA,WACA,QACA,QACA,OACA,iBACA,SACA,OACA,WACA,QACA,OACA,UACA,UACA,WACA,iBACA,OACA,OACA,QACA,SACA,SACA,OACA,WACA,QACA,OACA,QACA,OACA,OAAO,CACC,EAEGiH,GAAajH,GAAO,CAC/B,UACA,gBACA,sBACA,cACA,mBACA,oBACA,oBACA,iBACA,eACA,UACA,UACA,UACA,UACA,UACA,iBACA,UACA,UACA,cACA,eACA,WACA,eACA,qBACA,cACA,SACA,cAAc,CACN,EAMGkH,GAAgBlH,GAAO,CAClC,UACA,gBACA,SACA,UACA,YACA,mBACA,iBACA,gBACA,gBACA,gBACA,QACA,YACA,OACA,eACA,YACA,UACA,gBACA,SACA,MACA,aACA,UACA,KAAK,CACG,EAEGmH,GAASnH,GAAO,CAC3B,OACA,WACA,SACA,UACA,QACA,SACA,KACA,aACA,gBACA,KACA,KACA,QACA,UACA,WACA,QACA,OACA,KACA,SACA,QACA,SACA,OACA,OACA,UACA,SACA,MACA,QACA,MACA,SACA,aACA,aAAa,CACL,EAIGoH,GAAmBpH,GAAO,CACrC,UACA,cACA,aACA,WACA,YACA,UACA,UACA,SACA,SACA,QACA,YACA,aACA,iBACA,cACA,MAAM,CACE,EAEGqH,GAAOrH,GAAO,CAAC,OAAO,CAAU,ECtRhC+G,GAAO/G,GAAO,CACzB,SACA,SACA,QACA,MACA,iBACA,eACA,uBACA,WACA,aACA,UACA,SACA,UACA,cACA,cACA,UACA,OACA,QACA,QACA,QACA,OACA,UACA,UACA,aACA,WACA,eACA,SACA,cACA,WACA,WACA,UACA,MACA,WACA,0BACA,wBACA,WACA,YACA,UACA,eACA,cACA,OACA,MACA,UACA,SACA,SACA,OACA,OACA,WACA,KACA,QACA,YACA,YACA,QACA,OACA,QACA,OACA,OACA,UACA,OACA,MACA,MACA,YACA,QACA,SACA,MACA,YACA,WACA,QACA,OACA,QACA,UACA,aACA,SACA,OACA,UACA,OACA,UACA,cACA,cACA,UACA,gBACA,sBACA,SACA,UACA,UACA,aACA,WACA,MACA,WACA,MACA,WACA,OACA,OACA,UACA,aACA,QACA,WACA,QACA,OACA,QACA,OACA,OACA,UACA,QACA,MACA,SACA,OACA,QACA,UACA,WACA,QACA,YACA,OACA,SACA,SACA,QACA,QACA,OACA,OAAO,CACC,EAEGgH,GAAMhH,GAAO,CACxB,gBACA,aACA,WACA,qBACA,YACA,SACA,gBACA,gBACA,UACA,gBACA,iBACA,QACA,OACA,KACA,QACA,OACA,gBACA,YACA,YACA,QACA,sBACA,8BACA,gBACA,kBACA,KACA,KACA,IACA,KACA,KACA,kBACA,YACA,UACA,UACA,oBACA,MACA,WACA,YACA,MACA,WACA,OACA,eACA,YACA,SACA,cACA,cACA,gBACA,cACA,YACA,mBACA,eACA,aACA,eACA,cACA,KACA,KACA,KACA,KACA,aACA,WACA,gBACA,oBACA,SACA,OACA,KACA,kBACA,KACA,MACA,YACA,IACA,KACA,KACA,KACA,KACA,UACA,YACA,aACA,WACA,OACA,eACA,iBACA,eACA,mBACA,iBACA,QACA,aACA,aACA,eACA,eACA,cACA,cACA,mBACA,YACA,MACA,OACA,YACA,QACA,SACA,OACA,MACA,OACA,aACA,SACA,WACA,UACA,QACA,SACA,cACA,SACA,WACA,cACA,OACA,aACA,sBACA,mBACA,eACA,iBACA,SACA,gBACA,sBACA,iBACA,IACA,KACA,KACA,SACA,OACA,OACA,cACA,YACA,UACA,SACA,SACA,QACA,OACA,kBACA,QACA,mBACA,mBACA,eACA,cACA,eACA,cACA,aACA,eACA,mBACA,oBACA,iBACA,kBACA,oBACA,iBACA,SACA,eACA,QACA,eACA,iBACA,WACA,cACA,UACA,UACA,YACA,mBACA,cACA,kBACA,mBACA,iBACA,aACA,OACA,KACA,KACA,UACA,SACA,gBACA,UACA,aACA,UACA,aACA,gBACA,gBACA,QACA,eACA,OACA,eACA,mBACA,mBACA,IACA,KACA,KACA,QACA,IACA,KACA,KACA,IACA,YAAY,CACJ,EAEGmH,GAASnH,GAAO,CAC3B,SACA,cACA,QACA,WACA,QACA,cACA,cACA,gBACA,aACA,aACA,QACA,MACA,UACA,eACA,WACA,QACA,QACA,SACA,OACA,KACA,UACA,SACA,gBACA,SACA,SACA,iBACA,YACA,WACA,cACA,UACA,UACA,gBACA,WACA,WACA,OACA,WACA,WACA,aACA,UACA,SACA,SACA,cACA,gBACA,uBACA,YACA,YACA,aACA,WACA,iBACA,iBACA,YACA,UACA,QACA,OAAO,CACR,EAEYsH,GAAMtH,GAAO,C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C/BqH,GAAgB,EAChBvH,GAAe5B,EAAK6B,EAASC,CAAM,CACvC,CACJ,CAAC,EACDpC,EAAS,cAAc,iBAAiB,QAAS,IAAMuJ,EAAQ,KAAK,CAAC,EACrEvJ,EAAS,oBAAoB,iBAAiB,QAAS,IAAMuJ,EAAQ,KAAK,CAAC,EAE3ExD,GAAG,cAAe,IAAM7F,GAAYF,EAAS,YAAY,CAAC,EAEtDA,EAAS,OACT0J,GAAapJ,EAAKN,EAAS,KAAK,EAGpC2J,GAAcrJ,CAAG,EAEjB,MAAMa,GAAgBb,CAAG,EACrBqG,EACAiD,GAAmB7C,EAAKJ,CAAa,EAC7BrG,EAAI,MAAM,WAIlB+B,GAAgB/B,CAAG,EAGnBiG,EAAU,WACV,MAAMrE,GAAe5B,EAAKiG,EAAU,WAAW,OAAO,EAEtDsD,GAActD,EAAYpE,GAAYD,GAAe5B,EAAK6B,CAAO,CAAC,EAMtE7B,EAAI,UAAY,GAChBA,EAAI,MAAM,MAAQ,GAGlBkC,GAAelC,CAAG,EAClByF,GAAG,iBAAkB,IAAMvD,GAAelC,CAAG,CAAC,EAC9CyF,GAAG,kBAAmB,IAAMvD,GAAelC,CAAG,CAAC,EAE/CsE,GAAsBtE,CAAG,CAC7B,CAEAgG,GAAK,EAAE,MAAOzF,GAAU,CACpB,QAAQ,MAAM,8BAA+BA,CAAK,CACtD,CAAC",
  "names": ["bus", "emit", "name", "detail", "on", "handler", "listener", "event", "getCookie", "prefix", "cookie", "part", "debounce", "fn", "wait", "timer", "debounced", "args", "clamp", "value", "min", "max", "isStyleAttribute", "name", "looksLikeUuid", "value", "apiFetch", "url", "options", "method", "headers", "csrfToken", "getCookie", "response", "detail", "error", "emit", "IMAGE_EXT_RE", "IMAGE_HOST_RE", "DATA_IMAGE_RE", "HTML_RE", "URL_RE", "NUMBER_RE", "PHOTO_KEY_RE", "NAME_KEYS", "NAME_PART_RE", "NOT_NAME_RE", "looksLikeHtml", "text", "isImageUrl", "value", "relativeImagePath", "decoded", "part", "isPhotoKey", "key", "photosOf", "token", "path", "nameKeysOf", "keys", "names", "exact", "wanted", "partial", "titleOf", "properties", "shortUrl", "url", "max", "parsed", "kindOf", "htmlText", "html", "repeatsOtherValues", "otherValues", "words", "known", "word", "popupWidth", "longest", "count", "wideHtml", "photos", "mediaUrl", "bootstrap", "itemId", "mapId", "encoded", "decodeURIComponentSafe", "base", "PHOTO_SYMBOL", "PHOTO_SIZE", "PHOTO_MIN_SIZE", "CAMERA_RATIO", "LENS_RATIO", "CAMERA_POINTS", "CAMERA_HEIGHT", "CAMERA_ANCHOR", "PREFERRED_FIELDS", "photoFieldOf", "attributes", "names", "a", "name", "isPhotoKey", "photoMarkerSizes", "size", "ring", "round", "value", "plainDotSize", "cameraPolygonPoints", "cx", "cy", "height", "scale", "x", "y", "geometryGroup", "geometryType", "t", "suggestionDescribesNative", "sublayers", "suggested", "fromData", "s", "groups", "sub", "group", "applyPhotoMarker", "style", "subs", "g", "category", "LABEL_POSITIONS", "ANCHORS", "LINE_LABEL_MODES", "REPEAT_DISTANCE", "ZOOM0_RESOLUTION", "METRES_PER_DEGREE", "LABEL_AREA", "LABEL_COVER", "ALWAYS_UP_TO", "UNKNOWN_DENSITY_ZOOM", "defaultLabels", "LEGACY_PLACEMENT", "normalizeLabels", "labels", "defaults", "legacy", "out", "isText", "attribute", "labelFieldOf", "sublayers", "names", "sub", "a", "nameKeysOf", "applyDefaultLabels", "style", "field", "mercatorY", "lat", "clamped", "autoLabelMinZoom", "count", "bbox", "dx", "dy", "area", "resolution", "zoom", "featureCount", "entry", "counts", "b", "entryAutoLabelMinZoom", "labelMinZoom", "value", "xmlEscape", "vendor", "name", "labelDistance", "markerSize", "rotationXml", "rotation", "pointPlacementXml", "distance", "anchor", "ax", "ay", "displacement", "textSymbolizerXml", "groups", "minZoom", "kinds", "only", "placement", "options", "weight", "DEFAULT_BASEMAP_LOOK", "normalizeBasemapLook", "look", "raw", "value", "isDefaultBasemapLook", "opacity", "gray", "serializeBasemapLook", "basemapFilter", "basemapLookControlsHtml", "disabled", "percent", "off", "CONFIG_VERSION", "STYLE_VERSION", "uidCounter", "newUid", "defaultRules", "VECTOR_STYLE_MODES", "defaultCategorizedStyle", "defaultGraduatedStyle", "defaultVectorStyle", "defaultLabels", "normalizeVectorStyle", "style", "rulesDefaults", "categorizedDefaults", "normalizeLabels", "ruleForCategory", "geometry", "baseRule", "category", "pick", "value", "fallback", "RASTER_MODES", "isByteBand", "band", "rgbBandOrder", "bands", "find", "name", "b", "order", "defaultRasterStyle", "info", "list", "normalizeRasterStyle", "base", "count", "legacyMode", "mode", "clamp", "n", "clip", "stretchType", "range", "dashText", "dash", "ruleFromSymbol", "symbol", "categoryFromSymbol", "rule", "styleFromSuggestions", "suggestions", "usable", "s", "labelField", "suggested", "createGroupEntry", "saved", "flatLayers", "state", "out", "entry", "findEntryByUid", "uid", "child", "c", "findEntryContainer", "topIndex", "e", "index", "isEffectivelyVisible", "container", "createDefaultConfig", "createState", "bootstrap", "mapObj", "dirty", "next", "emit", "createLayerEntry", "itemDetail", "savedLayer", "bandInfo", "isRaster", "native", "rasterInfo", "applyPhotoMarker", "applyDefaultLabels", "geometryTypes", "sub", "g", "normalizeGeometryType", "geometryType", "t", "serializeConfig", "view", "basemapKey", "serializeSafe", "serializeLayerEntry", "error", "serializeBasemapLook", "layer", "zoomLimits", "CollectionEventType_default", "ObjectEventType_default", "clear", "object", "property", "isEmpty", "listen", "target", "type", "listener", "thisArg", "once", "originalListener", "event", "eventsKey", "listenOnce", "unlistenByKey", "key", "clear", "EventType_default", "Disposable", "Disposable_default", "binarySearch", "haystack", "needle", "comparator", "mid", "cmp", "ascending", "low", "high", "found", "a", "b", "descending", "linearFindNearest", "arr", "target", "direction", "n", "candidate", "reverseSubArray", "begin", "end", "tmp", "extend", "data", "extension", "length", "equals", "arr1", "arr2", "len1", "i", "isSorted", "arr", "func", "strict", "compare", "ascending", "currentVal", "index", "res", "TRUE", "FALSE", "VOID", "memoizeOne", "fn", "lastResult", "lastArgs", "lastThis", "nextArgs", "equals", "toPromise", "getter", "promiseGetter", "value", "err", "BaseEvent", "type", "Event_default", "BaseEvent", "Target", "Disposable_default", "target", "type", "listener", "listeners", "listenersForType", "event", "isString", "evt", "Event_default", "dispatching", "pendingRemovals", "propagate", "i", "ii", "pr", "VOID", "clear", "index", "Target_default", "Observable", "Target_default", "EventType_default", "type", "listener", "len", "keys", "i", "listen", "key", "listenOnce", "unByKey", "ii", "unlistenByKey", "Observable_default", "abstract", "uidCounter_", "getUid", "obj", "ObjectEvent", "Event_default", "type", "key", "oldValue", "BaseObject", "Observable_default", "values", "getUid", "value", "eventType", "ObjectEventType_default", "listener", "silent", "source", "isEmpty", "Object_default", "Property", "CollectionEvent", "Event_default", "type", "element", "index", "Collection", "Object_default", "array", "options", "i", "ii", "arr", "f", "elem", "CollectionEventType_default", "n", "prev", "except", "Collection_default", "MapEvent", "Event_default", "type", "map", "frameState", "MapEvent_default", "MapBrowserEvent", "MapEvent_default", "type", "map", "originalEvent", "dragging", "frameState", "activePointers", "pixel", "coordinate", "MapBrowserEvent_default", "MapBrowserEventType_default", "EventType_default", "ua", "SAFARI", "SAFARI_BUG_237906", "WEBKIT", "MAC", "DEVICE_PIXEL_RATIO", "WORKER_OFFSCREEN_CANVAS", "IMAGE_DECODE", "CREATE_IMAGE_BITMAP", "PASSIVE_EVENT_LISTENERS", "passive", "options", "EventType_default", "MapBrowserEventHandler", "Target_default", "map", "moveTolerance", "element", "listen", "EventType_default", "PASSIVE_EVENT_LISTENERS", "pointerEvent", "newEvent", "MapBrowserEvent_default", "MapBrowserEventType_default", "event", "id", "pointerId", "unlistenByKey", "doc", "dragging", "originalEvent", "MapBrowserEventHandler_default", "MapEventType_default", "MapProperty_default", "TileState_default", "assert", "assertion", "errorMessage", "DROP", "PriorityQueue", "priorityFunction", "keyFunction", "clear", "elements", "priorities", "element", "elementKey", "assert", "priority", "index", "i", "key", "count", "startIndex", "lIndex", "rIndex", "smallerChildIndex", "parentIndex", "n", "PriorityQueue_default", "TileQueue", "PriorityQueue_default", "tilePriorityFunction", "tileChangeCallback", "element", "added", "EventType_default", "event", "tile", "state", "TileState_default", "tileKey", "maxTotalLoading", "maxNewLoads", "newLoads", "TileQueue_default", "getTilePriority", "frameState", "tileSourceKey", "tileCenter", "tileResolution", "DROP", "center", "deltaX", "deltaY", "ViewHint_default", "ViewProperty_default", "clamp", "value", "min", "max", "squaredSegmentDistance", "x", "y", "x1", "y1", "x2", "y2", "dx", "dy", "t", "squaredDistance", "solveLinearSystem", "mat", "n", "i", "maxRow", "maxEl", "r", "absValue", "tmp", "j", "coef", "k", "l", "m", "toDegrees", "angleInRadians", "toRadians", "angleInDegrees", "modulo", "a", "b", "lerp", "toFixed", "decimals", "factor", "round", "floor", "ceil", "wrap", "range", "createExtent", "extent", "onlyCenter", "smooth", "center", "resolution", "size", "isMoving", "centerShift", "viewWidth", "viewHeight", "shiftX", "shiftY", "minX", "maxX", "minY", "maxY", "x", "clamp", "y", "ratio", "none", "Relationship_default", "boundingExtent", "coordinates", "extent", "createEmpty", "i", "ii", "extendCoordinate", "_boundingExtentXYs", "xs", "ys", "dest", "minX", "minY", "maxX", "maxY", "createOrUpdate", "buffer", "value", "clone", "closestSquaredDistanceXY", "x", "y", "dx", "dy", "containsCoordinate", "coordinate", "containsXY", "containsExtent", "extent1", "extent2", "coordinateRelationship", "relationship", "Relationship_default", "createOrUpdateEmpty", "createOrUpdateFromCoordinate", "createOrUpdateFromFlatCoordinates", "flatCoordinates", "offset", "end", "stride", "dest", "extent", "createOrUpdateEmpty", "extendFlatCoordinates", "equals", "extent1", "extent2", "extend", "extent1", "extent2", "extendCoordinate", "extent", "coordinate", "extendFlatCoordinates", "extent", "flatCoordinates", "offset", "end", "stride", "extendXY", "extendXY", "extent", "x", "y", "forEachCorner", "callback", "val", "getBottomLeft", "getBottomRight", "getTopRight", "getTopLeft", "getArea", "area", "isEmpty", "getWidth", "getHeight", "getCenter", "getCorner", "corner", "coordinate", "getForViewAndSize", "center", "resolution", "rotation", "size", "dest", "x0", "y0", "x1", "y1", "x2", "y2", "x3", "y3", "getRotatedViewport", "createOrUpdate", "dx", "dy", "cosRotation", "sinRotation", "xCos", "xSin", "yCos", "ySin", "x", "y", "getHeight", "extent", "getIntersection", "extent1", "extent2", "dest", "intersection", "createEmpty", "intersects", "createOrUpdateEmpty", "getTopLeft", "extent", "getTopRight", "getWidth", "intersects", "extent1", "extent2", "isEmpty", "returnOrUpdate", "dest", "intersectsSegment", "extent", "start", "end", "intersects", "startRel", "coordinateRelationship", "endRel", "Relationship_default", "minX", "minY", "maxX", "maxY", "startX", "startY", "endX", "endY", "slope", "x", "y", "applyTransform", "transformFn", "dest", "stops", "isEmpty", "createOrUpdateEmpty", "coordinates", "width", "height", "i", "xs", "ys", "_boundingExtentXYs", "wrapX", "projection", "projectionExtent", "center", "getCenter", "worldWidth", "getWidth", "offset", "wrapAndSliceX", "multiWorld", "compareVersions", "v1", "v2", "s1", "s2", "n1", "n2", "add", "coordinate", "delta", "closestOnSegment", "coordinate", "segment", "x0", "y0", "start", "end", "x1", "y1", "x2", "y2", "dx", "dy", "along", "x", "y", "createStringXY", "fractionDigits", "toStringXY", "format", "coordinate", "template", "fractionDigits", "equals", "coordinate1", "coordinate2", "i", "rotate", "angle", "cosAngle", "sinAngle", "x", "y", "scale", "squaredDistance", "coord1", "coord2", "dx", "dy", "distance", "squaredDistanceToSegment", "segment", "closestOnSegment", "toStringXY", "coordinate", "fractionDigits", "format", "wrapX", "projection", "worldWidth", "getWidth", "worldsAway", "getWorldsAway", "sourceExtentWidth", "projectionExtent", "angleBetween", "p0", "pA", "pB", "lenA", "tangentA", "orthoA", "lenB", "tangentB", "angle", "clamp", "easeIn", "t", "easeOut", "inAndOut", "linear", "DEFAULT_RADIUS", "getDistance", "c1", "c2", "radius", "lat1", "toRadians", "lat2", "deltaLatBy2", "deltaLonBy2", "getLengthInternal", "coordinates", "length", "i", "ii", "getLength", "geometry", "options", "projection", "type", "coords", "j", "jj", "geometries", "getAreaInternal", "area", "len", "x1", "y1", "x2", "y2", "getArea", "offset", "distance", "bearing", "lon1", "dByR", "lat", "lon", "toDegrees", "levels", "level", "warn", "args", "level", "levels", "METERS_PER_UNIT", "Projection", "options", "METERS_PER_UNIT", "global", "tileGrid", "extent", "worldExtent", "func", "Projection_default", "RADIUS", "HALF_SIZE", "EXTENT", "WORLD_EXTENT", "MAX_SAFE_Y", "EPSG3857Projection", "Projection_default", "code", "resolution", "point", "PROJECTIONS", "fromEPSG4326", "input", "output", "dimension", "stride", "length", "i", "y", "toEPSG4326", "RADIUS", "EXTENT", "METERS_PER_UNIT", "EPSG4326Projection", "Projection_default", "code", "axisOrientation", "PROJECTIONS", "cache", "get", "code", "cache", "add", "projection", "transforms", "add", "source", "destination", "transformFn", "sourceCode", "destinationCode", "transforms", "get", "sourceCode", "destinationCode", "transforms", "K0", "E", "E2", "E3", "E_P2", "SQRT_E", "_E", "_E2", "_E3", "_E4", "_E5", "M1", "M2", "M3", "M4", "P2", "P3", "P4", "P5", "R", "toLonLat", "easting", "northing", "zone", "x", "mu", "pRad", "pSin", "pSin2", "pCos", "pTan", "pTan2", "pTan4", "epSin", "epSinSqrt", "n", "r", "c", "c2", "d", "d2", "d3", "d4", "d5", "d6", "latitude", "longitude", "wrap", "toRadians", "zoneToCentralLongitude", "toDegrees", "MIN_LATITUDE", "MAX_LATITUDE", "MIN_LONGITUDE", "MAX_LONGITUDE", "fromLonLat", "latRad", "latSin", "latCos", "latTan", "latTan2", "latTan4", "lonRad", "centralLon", "centralLonRad", "a", "a2", "a3", "a4", "a5", "a6", "m", "epsgRegExes", "zoneFromCode", "code", "epsgId", "re", "match", "number", "north", "makeTransformFunction", "transformer", "input", "output", "dimension", "stride", "length", "i", "y", "coord", "makeProjection", "Projection_default", "makeTransforms", "projection", "transformFactories", "makeTransforms", "projectionFactories", "makeProjection", "showCoordinateWarning", "disableCoordinateWarning", "disable", "cloneTransform", "input", "output", "i", "ii", "identityTransform", "addProjection", "projection", "add", "addProjections", "projections", "get", "projectionLike", "makeProjection", "projectionFactories", "getPointResolution", "resolution", "point", "units", "pointResolution", "getter", "metersPerUnit", "METERS_PER_UNIT", "projUnits", "toEPSG4326", "getTransformFromProjections", "vertices", "width", "getDistance", "height", "addEquivalentProjections", "source", "destination", "addEquivalentTransforms", "projections1", "projections2", "forwardTransform", "inverseTransform", "projection1", "projection2", "createProjection", "projection", "defaultCode", "get", "createTransformFromCoordinateTransform", "coordTransform", "input", "output", "dimension", "stride", "length", "i", "point", "pointLength", "j", "jj", "fromLonLat", "coordinate", "projection", "disableCoordinateWarning", "transform", "toLonLat", "lonLat", "lon", "modulo", "equivalent", "projection1", "projection2", "equalUnits", "getTransformFromProjections", "cloneTransform", "source", "destination", "sourceCode", "destinationCode", "transformFunc", "get", "sourceTransforms", "destinationTransforms", "makeTransforms", "transformFactories", "intermediateCode", "composeTransformFuncs", "fromSource", "toDestination", "addProjection", "add", "t1", "t2", "input", "output", "dimensions", "stride", "getTransform", "sourceProjection", "destinationProjection", "transformExtent", "extent", "stops", "applyTransform", "userProjection", "getUserProjection", "userProjection", "toUserCoordinate", "coordinate", "sourceProjection", "userProjection", "transform", "fromUserCoordinate", "destProjection", "showCoordinateWarning", "equals", "warn", "toUserExtent", "extent", "transformExtent", "fromUserExtent", "toUserResolution", "resolution", "sourceMetersPerUnit", "get", "userMetersPerUnit", "addCommon", "addEquivalentProjections", "PROJECTIONS", "addEquivalentTransforms", "fromEPSG4326", "toEPSG4326", "tmp_", "create", "setFromArray", "transform1", "transform2", "apply", "transform", "coordinate", "x", "y", "compose", "transform", "dx1", "dy1", "sx", "sy", "angle", "dx2", "dy2", "sin", "cos", "makeInverse", "target", "source", "det", "determinant", "assert", "a", "b", "c", "d", "e", "f", "mat", "matrixPrecision", "toString", "fromString", "cssTransform", "equivalent", "cssTransform1", "cssTransform2", "mat1", "mat2", "transform2D", "flatCoordinates", "offset", "end", "stride", "transform", "dest", "destinationStride", "i", "j", "x", "y", "k", "rotate", "angle", "anchor", "cos", "sin", "anchorX", "anchorY", "deltaX", "deltaY", "scale", "sx", "sy", "translate", "tmpTransform", "create", "tmpPoint", "Geometry", "Object_default", "createEmpty", "memoizeOne", "revision", "squaredTolerance", "transform", "clone", "abstract", "x", "y", "closestPoint", "minSquaredDistance", "point", "coordinate", "extent", "createOrUpdateEmpty", "returnOrUpdate", "angle", "anchor", "sx", "sy", "tolerance", "transformFn", "deltaX", "deltaY", "source", "destination", "sourceProj", "get", "inCoordinates", "outCoordinates", "stride", "pixelExtent", "projectedExtent", "scale", "getHeight", "compose", "transformed", "transform2D", "projTransform", "getTransform", "Geometry_default", "SimpleGeometry", "Geometry_default", "extent", "createOrUpdateFromFlatCoordinates", "abstract", "squaredTolerance", "simplifiedGeometry", "layout", "flatCoordinates", "getStrideForLayout", "coordinates", "nesting", "stride", "i", "getLayoutForStride", "transformFn", "angle", "anchor", "rotate", "sx", "sy", "getCenter", "scale", "deltaX", "deltaY", "translate", "transformGeom2D", "simpleGeometry", "transform", "dest", "transform2D", "SimpleGeometry_default", "linearRing", "flatCoordinates", "offset", "end", "stride", "twiceArea", "x0", "y0", "dx1", "dy1", "dx2", "dy2", "linearRings", "ends", "area", "i", "ii", "linearRingss", "endss", "assignClosest", "flatCoordinates", "offset1", "offset2", "stride", "x", "y", "closestPoint", "x1", "y1", "dx", "dy", "offset", "t", "i", "lerp", "maxSquaredDelta", "end", "max", "x2", "y2", "squaredDelta", "squaredDistance", "arrayMaxSquaredDelta", "ends", "ii", "multiArrayMaxSquaredDelta", "endss", "assignClosestPoint", "maxDelta", "isRing", "minSquaredDistance", "tmpPoint", "index", "assignClosestArrayPoint", "assignClosestMultiArrayPoint", "deflateCoordinate", "flatCoordinates", "offset", "coordinate", "stride", "ii", "deflateCoordinates", "coordinates", "j", "deflateCoordinatesArray", "coordinatess", "ends", "i", "jj", "end", "deflateMultiCoordinatesArray", "coordinatesss", "endss", "inflateCoordinates", "flatCoordinates", "offset", "end", "stride", "coordinates", "i", "j", "inflateCoordinatesArray", "ends", "coordinatess", "jj", "inflateMultiCoordinatesArray", "endss", "coordinatesss", "douglasPeucker", "flatCoordinates", "offset", "end", "stride", "squaredTolerance", "simplifiedFlatCoordinates", "simplifiedOffset", "n", "markers", "stack", "index", "last", "first", "maxSquaredDistance", "x1", "y1", "x2", "y2", "i", "x", "y", "squaredDistance", "squaredSegmentDistance", "douglasPeuckerArray", "ends", "simplifiedEnds", "ii", "snap", "value", "tolerance", "quantize", "flatCoordinates", "offset", "end", "stride", "simplifiedFlatCoordinates", "simplifiedOffset", "x1", "y1", "x2", "y2", "x3", "y3", "dx1", "dy1", "dx2", "dy2", "quantizeArray", "ends", "simplifiedEnds", "i", "ii", "quantizeMultiArray", "endss", "simplifiedEndss", "LinearRing", "_LinearRing", "SimpleGeometry_default", "coordinates", "layout", "x", "y", "closestPoint", "minSquaredDistance", "closestSquaredDistanceXY", "maxSquaredDelta", "assignClosestPoint", "linearRing", "inflateCoordinates", "squaredTolerance", "simplifiedFlatCoordinates", "douglasPeucker", "extent", "deflateCoordinates", "LinearRing_default", "Point", "_Point", "SimpleGeometry_default", "coordinates", "layout", "point", "x", "y", "closestPoint", "minSquaredDistance", "flatCoordinates", "squaredDistance", "stride", "i", "extent", "createOrUpdateFromCoordinate", "containsXY", "deflateCoordinate", "Point_default", "linearRingContainsExtent", "flatCoordinates", "offset", "end", "stride", "extent", "forEachCorner", "coordinate", "linearRingContainsXY", "x", "y", "wn", "x1", "y1", "x2", "y2", "linearRingsContainsXY", "ends", "i", "ii", "linearRingssContainsXY", "endss", "getInteriorPointOfArray", "flatCoordinates", "offset", "ends", "stride", "flatCenters", "flatCentersOffset", "dest", "i", "ii", "x", "x1", "x2", "y1", "y2", "y", "intersections", "r", "rr", "end", "pointX", "maxSegmentLength", "ascending", "segmentLength", "linearRingsContainsXY", "getInteriorPointsOfMultiArray", "endss", "interiorPoints", "forEach", "flatCoordinates", "offset", "end", "stride", "callback", "ret", "intersectsLineString", "flatCoordinates", "offset", "end", "stride", "extent", "coordinatesExtent", "extendFlatCoordinates", "createEmpty", "intersects", "forEach", "point1", "point2", "intersectsSegment", "intersectsLineStringArray", "ends", "i", "ii", "intersectsLinearRing", "linearRingContainsXY", "intersectsLinearRingArray", "linearRingContainsExtent", "intersectsLinearRingMultiArray", "endss", "coordinates", "flatCoordinates", "offset", "end", "stride", "tmp", "linearRingIsClockwise", "flatCoordinates", "offset", "end", "stride", "edge", "x1", "y1", "x2", "y2", "linearRingsAreOriented", "ends", "right", "i", "ii", "isClockwise", "linearRingssAreOriented", "endss", "orientLinearRings", "coordinates", "orientLinearRingsArray", "inflateEnds", "prevEndIndex", "startOrientation", "orientation", "Polygon", "_Polygon", "SimpleGeometry_default", "coordinates", "layout", "ends", "linearRing", "extend", "polygon", "x", "y", "closestPoint", "minSquaredDistance", "closestSquaredDistanceXY", "arrayMaxSquaredDelta", "assignClosestArrayPoint", "linearRingsContainsXY", "linearRings", "right", "flatCoordinates", "orientLinearRings", "inflateCoordinatesArray", "flatCenter", "getCenter", "getInteriorPointOfArray", "Point_default", "index", "LinearRing_default", "offset", "i", "ii", "end", "linearRingsAreOriented", "squaredTolerance", "simplifiedFlatCoordinates", "simplifiedEnds", "quantizeArray", "extent", "intersectsLinearRingArray", "deflateCoordinatesArray", "Polygon_default", "circular", "center", "radius", "n", "sphereRadius", "fromExtent", "isEmpty", "minX", "minY", "maxX", "maxY", "fromCircle", "circle", "sides", "angle", "stride", "arrayLength", "j", "makeRegular", "startAngle", "modulo", "getViewportClampedResolution", "resolution", "maxExtent", "viewportSize", "showFullExtent", "xResolution", "getWidth", "yResolution", "getHeight", "getSmoothClampedResolution", "maxResolution", "minResolution", "result", "ratio", "clamp", "createSnapToResolutions", "resolutions", "smooth", "direction", "size", "isMoving", "cappedMaxRes", "capped", "z", "linearFindNearest", "createSnapToPower", "power", "tolerance", "minZoomLevel", "offset", "cappedZoomLevel", "zoomLevel", "newResolution", "createMinMaxResolution", "disable", "rotation", "none", "createSnapToN", "theta", "isMoving", "createSnapToZero", "tolerance", "t", "toRadians", "DEFAULT_MIN_ZOOM", "View", "Object_default", "options", "createProjection", "disableCoordinateWarning", "fromUserCoordinate", "fromUserExtent", "properties", "key", "ViewProperty_default", "resolutionConstraintInfo", "createResolutionConstraint", "centerConstraint", "createCenterConstraint", "resolutionConstraint", "rotationConstraint", "createRotationConstraint", "padding", "oldPadding", "center", "newPadding", "resolution", "offsetX", "offsetY", "newOptions", "var_args", "args", "i", "animationCount", "callback", "state", "animationCallback", "start", "rotation", "series", "animation", "inAndOut", "delta", "modulo", "isNoopAnimation", "ViewHint_default", "anchor", "ii", "j", "jj", "now", "more", "seriesComplete", "elapsed", "fraction", "progress", "x0", "y0", "x1", "y1", "x", "y", "size", "constrainedResolution", "constrainedRotation", "currentCenter", "rotate", "add", "currentResolution", "w", "h", "toUserCoordinate", "hints", "extent", "toUserExtent", "assert", "getForViewAndSize", "zoom", "enabled", "xResolution", "getWidth", "yResolution", "getHeight", "power", "maxResolution", "minResolution", "max", "value", "logPower", "projection", "reducedSize", "calculateCenterOn", "offset", "zoomFactor", "nearest", "linearFindNearest", "baseLevel", "clamp", "geometryOrExtent", "geometry", "isEmpty", "fromExtent", "getCenter", "userProjection", "getUserProjection", "cosAngle", "sinAngle", "coords", "stride", "minRotX", "minRotY", "maxRotX", "maxRotY", "rotX", "rotY", "rotatedExtent", "centerRot", "centerX", "centerY", "VOID", "coordinate", "position", "centerShift", "shiftedCenter", "deltaCoordinates", "ratio", "isMoving", "newResolution", "newRotation", "hint", "doNotCancelAnims", "forceMoving", "newCenter", "equals", "duration", "resolutionDirection", "direction", "easeOut", "targetCenter", "targetResolution", "targetZoom", "targetRes", "returnValue", "smooth", "createExtent", "none", "minZoom", "maxZoom", "multiWorld", "showFullExtent", "projExtent", "constrainOnlyCenter", "resolutions", "createSnapToResolutions", "createMinMaxResolution", "defaultMaxResolution", "METERS_PER_UNIT", "defaultMinResolution", "createSnapToPower", "constrainRotation", "createSnapToZero", "createSnapToN", "disable", "View_default", "CLASS_HIDDEN", "CLASS_SELECTABLE", "CLASS_UNSELECTABLE", "CLASS_CONTROL", "CLASS_COLLAPSED", "fontRegEx", "fontRegExMatchIndex", "fontWeights", "getFontParameters", "fontSpec", "match", "style", "i", "ii", "value", "f", "createCanvasContext2D", "width", "height", "canvasPool", "settings", "canvas", "WORKER_OFFSCREEN_CANVAS", "sharedCanvasContext", "getSharedCanvasContext2D", "releaseCanvas", "context", "outerWidth", "element", "style", "outerHeight", "replaceNode", "newNode", "oldNode", "parent", "removeChildren", "node", "replaceChildren", "children", "oldChildren", "i", "oldChild", "newChild", "createMockDiv", "index", "referenceNode", "target", "prop", "receiver", "isCanvas", "obj", "Control", "Object_default", "options", "element", "map", "i", "ii", "unlistenByKey", "target", "VOID", "listen", "MapEventType_default", "mapEvent", "Control_default", "Attribution", "Control_default", "options", "className", "tipLabel", "expandClassName", "collapseLabel", "collapseClassName", "label", "activeLabel", "EventType_default", "cssClasses", "CLASS_UNSELECTABLE", "CLASS_CONTROL", "CLASS_COLLAPSED", "element", "frameState", "layers", "visibleAttributions", "layer", "item", "collapsible", "attributions", "attribution", "toPromise", "visible", "equals", "removeChildren", "ii", "event", "replaceNode", "collapsed", "mapEvent", "Attribution_default", "Rotate", "Control_default", "options", "className", "label", "compassClassName", "tipLabel", "button", "EventType_default", "cssClasses", "CLASS_UNSELECTABLE", "CLASS_CONTROL", "element", "CLASS_HIDDEN", "event", "view", "rotation", "easeOut", "mapEvent", "frameState", "transform", "contains", "Rotate_default", "Zoom", "Control_default", "options", "className", "delta", "zoomInClassName", "zoomOutClassName", "zoomInLabel", "zoomOutLabel", "zoomInTipLabel", "zoomOutTipLabel", "inElement", "EventType_default", "outElement", "cssClasses", "CLASS_UNSELECTABLE", "CLASS_CONTROL", "element", "event", "view", "currentZoom", "newZoom", "easeOut", "Zoom_default", "defaults", "options", "controls", "Collection_default", "Zoom_default", "Rotate_default", "Attribution_default", "Kinetic", "decay", "minVelocity", "delay", "x", "y", "lastIndex", "firstIndex", "duration", "dx", "dy", "Kinetic_default", "Property_default", "Interaction", "Object_default", "options", "Property_default", "mapBrowserEvent", "active", "map", "pan", "view", "delta", "duration", "currentCenter", "center", "linear", "zoomByDelta", "anchor", "currentZoom", "newZoom", "newResolution", "easeOut", "Interaction_default", "DoubleClickZoom", "Interaction_default", "options", "mapBrowserEvent", "stopEvent", "MapBrowserEventType_default", "browserEvent", "map", "anchor", "delta", "view", "zoomByDelta", "DoubleClickZoom_default", "all", "var_args", "conditions", "event", "pass", "ii", "altKeyOnly", "mapBrowserEvent", "originalEvent", "altShiftKeysOnly", "focus", "targetElement", "rootNode", "activeElement", "focusWithTabindex", "always", "TRUE", "click", "MapBrowserEventType_default", "mouseActionButton", "WEBKIT", "MAC", "never", "FALSE", "singleClick", "mapBrowserEvent", "MapBrowserEventType_default", "noModifierKeys", "mapBrowserEvent", "originalEvent", "platformModifierKey", "mapBrowserEvent", "originalEvent", "MAC", "shiftKeyOnly", "targetNotEditable", "tagName", "mouseOnly", "pointerEvent", "primaryAction", "mapBrowserEvent", "pointerEvent", "PointerInteraction", "Interaction_default", "options", "mapBrowserEvent", "stopEvent", "MapBrowserEventType_default", "handledUp", "handled", "centroid", "pointerEvents", "length", "clientX", "clientY", "Pointer_default", "DragPan", "Pointer_default", "options", "FALSE", "condition", "all", "noModifierKeys", "primaryAction", "focusWithTabindex", "mapBrowserEvent", "map", "targetPointers", "centroid", "delta", "view", "scale", "rotate", "distance", "angle", "center", "centerpx", "dest", "easeOut", "DragPan_default", "DragRotate", "Pointer_default", "options", "FALSE", "altShiftKeysOnly", "mapBrowserEvent", "mouseOnly", "map", "view", "disable", "size", "offset", "theta", "delta", "mouseActionButton", "DragRotate_default", "RenderBox", "Disposable_default", "className", "startPixel", "endPixel", "px", "style", "map", "coordinates", "Polygon_default", "Box_default", "DragBoxEventType", "DragBoxEvent", "Event_default", "type", "coordinate", "mapBrowserEvent", "DragBox", "Pointer_default", "options", "Box_default", "mouseActionButton", "startPixel", "endPixel", "width", "height", "completeBox", "event", "active", "map", "DragBox_default", "DragZoom", "DragBox_default", "options", "condition", "shiftKeyOnly", "event", "view", "geometry", "rotatedExtent", "resolution", "factor", "easeOut", "DragZoom_default", "Key_default", "KeyboardPan", "Interaction_default", "options", "mapBrowserEvent", "noModifierKeys", "targetNotEditable", "stopEvent", "EventType_default", "keyEvent", "key", "Key_default", "view", "mapUnitsDelta", "deltaX", "deltaY", "delta", "rotate", "pan", "KeyboardPan_default", "KeyboardZoom", "Interaction_default", "options", "mapBrowserEvent", "platformModifierKey", "targetNotEditable", "stopEvent", "EventType_default", "keyEvent", "key", "map", "delta", "view", "zoomByDelta", "KeyboardZoom_default", "DELTA_LINE_MULTIPLIER", "DELTA_PAGE_MULTIPLIER", "DELTA_TRACKPAD_PINCH_TO_ZOOM_MULTIPLIER", "MouseWheelZoom", "Interaction_default", "options", "condition", "always", "all", "focusWithTabindex", "map", "unlistenByKey", "doc", "listen", "e", "view", "direction", "mapBrowserEvent", "EventType_default", "wheelEvent", "isPinchToZoom", "delta", "now", "timeLeft", "clamp", "zoomByDelta", "useAnchor", "MouseWheelZoom_default", "PinchRotate", "Pointer_default", "options", "pointerOptions", "FALSE", "mapBrowserEvent", "rotationDelta", "touch0", "touch1", "angle", "delta", "map", "view", "disable", "centroid", "PinchRotate_default", "PinchZoom", "Pointer_default", "options", "pointerOptions", "FALSE", "mapBrowserEvent", "scaleDelta", "touch0", "touch1", "dx", "dy", "distance", "map", "view", "centroid", "direction", "PinchZoom_default", "defaults", "options", "interactions", "Collection_default", "kinetic", "Kinetic_default", "DragRotate_default", "DoubleClickZoom_default", "DragPan_default", "PinchRotate_default", "PinchZoom_default", "KeyboardPan_default", "KeyboardZoom_default", "MouseWheelZoom_default", "DragZoom_default", "Property_default", "BaseLayer", "Object_default", "options", "properties", "Property_default", "assert", "managed", "state", "zIndex", "clamp", "array", "abstract", "states", "background", "extent", "maxResolution", "minResolution", "maxZoom", "minZoom", "opacity", "visible", "zindex", "Base_default", "GroupEventType", "GroupEvent", "Event_default", "type", "layer", "Property", "LayerGroup", "_LayerGroup", "Base_default", "options", "baseOptions", "layers", "Collection_default", "assert", "unlistenByKey", "listen", "CollectionEventType_default", "id", "clear", "layersArray", "i", "ii", "listenerKeys", "ObjectEventType_default", "EventType_default", "getUid", "event", "collectionEvent", "key", "collection", "currentLayers", "array", "dest", "states", "pos", "ownLayerState", "defaultZIndex", "layerState", "getIntersection", "Group_default", "EventType_default", "Layer", "Base_default", "options", "baseOptions", "Property_default", "source", "array", "states", "unlistenByKey", "listen", "EventType_default", "pixel", "view", "frameState", "map", "View_default", "layerState", "layerExtent", "inView", "intersects", "getAttributions", "attributions", "target", "layerRenderer", "renderEvent", "layerStatesArray", "assert", "arrayLayerState", "viewState", "resolution", "zoom", "Layer_default", "quickselect", "arr", "k", "left", "right", "compare", "defaultCompare", "n", "m", "z", "s", "sd", "newLeft", "newRight", "t", "i", "j", "swap", "tmp", "a", "b", "RBush", "maxEntries", "bbox", "node", "result", "intersects", "toBBox", "nodesToSearch", "i", "child", "childBBox", "contains", "data", "tmpNode", "item", "createNode", "equalsFn", "path", "indexes", "parent", "goingUp", "index", "findItem", "a", "b", "items", "left", "right", "height", "N", "M", "calcBBox", "N2", "N1", "multiSelect", "right2", "j", "right3", "level", "minArea", "minEnlargement", "targetNode", "area", "bboxArea", "enlargement", "enlargedArea", "isNode", "insertPath", "extend", "m", "splitIndex", "newNode", "minOverlap", "bbox1", "distBBox", "bbox2", "overlap", "intersectionArea", "compareMinX", "compareNodeMinX", "compareMinY", "compareNodeMinY", "xMargin", "yMargin", "compare", "leftBBox", "rightBBox", "margin", "bboxMargin", "siblings", "k", "p", "destNode", "minX", "minY", "maxX", "maxY", "children", "arr", "n", "stack", "mid", "quickselect", "NO_COLOR", "colorParseContext", "getColorParseContext", "createCanvasContext2D", "rgbModernRegEx", "rgbLegacyAbsoluteRegEx", "rgbLegacyPercentageRegEx", "hexRegEx", "toColorComponent", "s", "divider", "throwInvalidColor", "color", "parseRgba", "rgb", "alpha", "rgbDivider", "clamp", "hex", "step", "colorFromHex", "i", "ii", "colorComponent", "context", "invalidCheckFillStyle", "colorString", "colorFromImage", "toFixed", "asString", "toString", "MAX_CACHE_SIZE", "cache", "cacheSize", "withAlpha", "output", "b1", "v", "b2", "a1", "a2", "rgbaToLcha", "r", "g", "b", "y", "l", "q", "h", "lchaToRgba", "c", "x", "z", "fromString", "key", "asArray", "a", "hasArea", "size", "scale", "ratio", "dest", "toSize", "numTypes", "BooleanType", "numTypes", "NumberType", "StringType", "ColorType", "NumberArrayType", "SizeType", "AnyType", "typeNames", "namedTypes", "ascending", "isSpecific", "type", "typeName", "names", "namedType", "includesType", "broad", "specific", "isType", "type", "expected", "LiteralExpression", "value", "isSpecific", "typeName", "CallExpression", "operator", "args", "newParsingContext", "parse", "encoded", "expectedType", "context", "StringType", "includesType", "BooleanType", "SizeType", "toSize", "NumberType", "ColorType", "fromString", "parseCallExpression", "item", "NumberArrayType", "Ops", "parsers", "createCallExpressionParser", "hasArgsCount", "withGetArgs", "withVarArgs", "usesFeatureId", "withNoArgs", "withArgsOfType", "usesGeometryType", "usesMCoordinate", "usesMapState", "AnyType", "withArgsOfReturnType", "hasEvenArgs", "withMatchArgs", "withInterpolateArgs", "hasOddArgs", "withCaseArgs", "withInArgs", "withPaletteArgs", "returnType", "argsCount", "i", "key", "name", "operation", "minArgs", "maxArgs", "argCount", "plural", "range", "expression", "argType", "inputType", "input", "fallback", "match", "err", "output", "interpolationType", "base", "b", "interpolation", "stop", "condition", "haystack", "needleType", "arg", "index", "colors", "parsedColors", "color", "validators", "parsed", "parser", "computeGeometryType", "geometry", "newEvaluationContext", "buildExpression", "encoded", "type", "context", "expression", "parse", "compileExpression", "LiteralExpression", "ColorType", "colorValue", "fromString", "operator", "Ops", "compileAssertionExpression", "compileAccessorExpression", "args", "e", "arg", "compileLogicalExpression", "compileComparisonExpression", "compileNumericExpression", "compileCaseExpression", "compileMatchExpression", "compileInterpolateExpression", "compileConvertExpression", "length", "i", "value", "name", "ii", "key", "op", "left", "right", "min", "max", "base", "previousInput", "previousOutput", "input", "output", "isColor", "withAlpha", "interpolateColor", "interpolateNumber", "toString", "input1", "output1", "input2", "output2", "delta", "along", "factor", "rgba1", "rgba2", "lcha1", "rgbaToLcha", "lcha2", "deltaHue", "lcha", "lchaToRgba", "ImageState_default", "ImageWrapper", "Target_default", "extent", "resolution", "pixelRatio", "stateOrLoader", "ImageState_default", "EventType_default", "requestResolution", "toPromise", "image", "CREATE_IMAGE_BITMAP", "error", "listenImage", "loadHandler", "errorHandler", "img", "listening", "decoding", "loaded", "listenerKeys", "listenOnce", "IMAGE_DECODE", "unlistenByKey", "load", "src", "resolve", "reject", "handleLoad", "unlisten", "handleError", "decodeFallback", "e", "decode", "Image_default", "IconImageCache", "i", "key", "iconImage", "src", "color", "getCacheKey", "pattern", "update", "ImageState_default", "getSharedCanvasContext2D", "maxCacheSize", "colorString", "asArray", "shared", "IconImageCache", "taintedTestContext", "IconImage", "Target_default", "image", "src", "imageAttributes", "imageState", "color", "ImageState_default", "createCanvasContext2D", "EventType_default", "pixelRatio", "width", "height", "context", "decodeFallback", "ctx", "canvas", "asString", "resolve", "onChange", "get", "pattern", "iconImage", "shared", "IconImage_default", "asColorLike", "color", "toString", "asCanvasPattern", "pattern", "shared", "cacheKey", "canvasPattern", "iconImage", "ImageState_default", "patternCanvasContext", "createCanvasContext2D", "get", "defaultFont", "defaultFillStyle", "defaultLineCap", "defaultLineDash", "defaultLineDashOffset", "defaultLineJoin", "defaultMiterLimit", "defaultStrokeOffset", "defaultStrokeStyle", "defaultTextAlign", "defaultTextBaseline", "defaultPadding", "defaultLineWidth", "checkedFonts", "Object_default", "measureContext", "measureFont", "textHeights", "genericFontFamilies", "getFontKey", "style", "weight", "family", "registerFont", "timeout", "fontFaceSet", "isAvailable", "fontSpec", "fontFaces", "font", "getFontParameters", "checkFamily", "checkWeight", "f", "fontWeights", "check", "done", "checkedFontsProperties", "fonts", "key", "i", "currentRetries", "clear", "WORKER_OFFSCREEN_CANVAS", "families", "needCheck", "measureTextHeight", "measureElement", "height", "metrics", "measureText", "text", "createCanvasContext2D", "measureTextWidth", "measureAndCacheTextWidth", "cache", "width", "prev", "curr", "getTextDimensions", "baseStyle", "chunks", "widths", "heights", "lineWidths", "lineWidth", "lineHeight", "ii", "currentWidth", "currentHeight", "drawImageOrLabel", "context", "transform", "opacity", "labelOrImage", "originX", "originY", "w", "h", "x", "y", "scale", "executeLabelInstructions", "label", "contextInstructions", "i", "ii", "ImageStyle", "_ImageStyle", "options", "toSize", "scale", "abstract", "pixelRatio", "displacement", "opacity", "rotateWithView", "rotation", "listener", "Image_default", "RegularShape", "_RegularShape", "Image_default", "options", "ImageState_default", "scale", "style", "size", "displacement", "fill", "pixelRatio", "fillKey", "cacheKey", "image", "shared", "renderOptions", "context", "createCanvasContext2D", "iconImage", "IconImage_default", "imageBitmap", "radius", "radius2", "stroke", "listener", "lineJoin", "strokeWidth", "miterLimit", "r1", "r2", "tmp", "points", "alpha", "a", "b", "d", "e", "miterRatio", "k", "l", "bevelAdd", "aa", "bb", "dd", "innerMiterRatio", "innerLength", "lineCap", "defaultLineCap", "defaultLineJoin", "lineDash", "lineDashOffset", "strokeStyle", "asColorLike", "defaultStrokeStyle", "defaultLineWidth", "defaultMiterLimit", "add", "maxRadius", "color", "defaultFillStyle", "opacity", "asArray", "startAngle", "step", "i", "angle0", "radiusC", "RegularShape_default", "CircleStyle", "_CircleStyle", "RegularShape_default", "options", "scale", "style", "Circle_default", "Fill", "_Fill", "options", "color", "patternImage", "get", "ImageState_default", "fill", "getUid", "asArray", "Fill_default", "calculateScale", "width", "height", "wantedWidth", "wantedHeight", "Icon", "_Icon", "Image_default", "options", "opacity", "rotation", "scale", "rotateWithView", "image", "cacheKey", "assert", "getUid", "imageState", "ImageState_default", "asArray", "get", "onload", "imageSize", "anchor", "size", "displacement", "color", "nextColor", "value", "index", "src", "pixelRatio", "offset", "iconImageSize", "listener", "EventType_default", "Icon_default", "Stroke", "_Stroke", "options", "color", "lineCap", "lineDash", "lineDashOffset", "lineJoin", "miterLimit", "offset", "width", "Stroke_default", "Style", "_Style", "options", "defaultGeometryFunction", "geometry", "renderer", "fill", "image", "stroke", "text", "feature", "zIndex", "toFunction", "obj", "styleFunction", "styles", "assert", "defaultStyles", "createDefaultStyle", "resolution", "Fill_default", "Stroke_default", "Circle_default", "createEditingStyle", "white", "blue", "width", "Style_default", "DEFAULT_FILL_COLOR", "Text", "_Text", "options", "toSize", "Fill_default", "scale", "overflow", "font", "maxAngle", "offsetX", "offsetY", "placement", "repeat", "rotateWithView", "keepUpright", "fill", "rotation", "stroke", "text", "textAlign", "justify", "textBaseline", "padding", "Text_default", "always", "context", "rulesToStyleFunction", "rules", "parsingContext", "newParsingContext", "evaluator", "buildRuleSet", "evaluationContext", "newEvaluationContext", "feature", "resolution", "id", "computeGeometryType", "flatStylesToStyleFunction", "flatStyles", "length", "evaluators", "i", "buildStyle", "styles", "nonNullCount", "style", "compiledRules", "rule", "filter", "buildExpression", "BooleanType", "styleLength", "j", "someMatched", "filterEvaluator", "styleEvaluator", "flatStyle", "evaluateFill", "buildFill", "evaluateStroke", "buildStroke", "evaluateText", "buildText", "evaluateImage", "buildImage", "evaluateZIndex", "numberEvaluator", "isEmpty", "Style_default", "empty", "fill", "stroke", "text", "image", "prefix", "evaluateColor", "patternEvaluator", "colorLikeEvaluator", "Fill_default", "color", "NO_COLOR", "evaluateWidth", "evaluateLineCap", "stringEvaluator", "evaluateLineJoin", "evaluateLineDash", "numberArrayEvaluator", "evaluateLineDashOffset", "evaluateMiterLimit", "evaluateOffset", "Stroke_default", "lineCap", "lineJoin", "evaluateValue", "evaluateBackgroundFill", "evaluateBackgroundStroke", "evaluateFont", "evaluateMaxAngle", "evaluateOffsetX", "evaluateOffsetY", "evaluateOverflow", "booleanEvaluator", "evaluatePlacement", "evaluateRepeat", "evaluateScale", "sizeLikeEvaluator", "evaluateRotateWithView", "evaluateRotation", "evaluateAlign", "evaluateJustify", "evaluateBaseline", "evaluateKeepUpright", "evaluatePadding", "declutterMode", "optionalDeclutterMode", "Text_default", "placement", "textAlign", "justify", "textBaseline", "buildIcon", "buildShape", "buildCircle", "srcName", "src", "requireString", "evaluateAnchor", "coordinateEvaluator", "evaluateOpacity", "evaluateDisplacement", "anchorOrigin", "optionalIconOrigin", "anchorXUnits", "optionalIconAnchorUnits", "anchorYUnits", "colorValue", "getExpressionValue", "requireColorLike", "crossOrigin", "optionalString", "offset", "optionalNumberArray", "offsetOrigin", "width", "optionalNumber", "height", "size", "optionalSize", "iconOptions", "icon", "initialColor", "Icon_default", "pointsName", "radiusName", "points", "requireNumber", "evaluateRadius", "initialRadius", "radius2Name", "evaluateRadius2", "initialRadius2", "angle", "shape", "RegularShape_default", "circle", "Circle_default", "name", "value", "encoded", "NumberType", "StringType", "srcEvaluator", "offsetEvaluator", "sizeEvaluator", "patternSizeEvaluator", "colorEvaluator", "ColorType", "index", "array", "NumberArrayType", "requireNumberArray", "requireSize", "requireSizeLike", "property", "toSize", "Property", "BaseVectorLayer", "Layer_default", "options", "baseOptions", "pixel", "frameState", "layerState", "declutterGroup", "RBush", "renderOrder", "style", "createDefaultStyle", "styleLike", "toStyleLike", "toFunction", "declutter", "Style_default", "flatStylesToStyleFunction", "length", "first", "styles", "i", "candidate", "rules", "rulesToStyleFunction", "BaseVector_default", "RenderEvent", "Event_default", "type", "inversePixelTransform", "frameState", "context", "MapRenderer", "Disposable_default", "map", "type", "frameState", "abstract", "viewState", "coordinateToPixelTransform", "pixelToCoordinateTransform", "compose", "makeInverse", "coordinate", "hitTolerance", "checkWrapped", "callback", "thisArg", "layerFilter", "thisArg2", "result", "forEachFeatureAtCoordinate", "managed", "feature", "layer", "geometry", "projection", "translatedCoordinate", "wrapX", "offsets", "projectionExtent", "worldWidth", "getWidth", "layerStates", "numLayers", "matches", "tmpCoord", "i", "j", "layerState", "inView", "layerRenderer", "source", "coordinates", "order", "m", "a", "b", "TRUE", "shared", "expireIconCache", "Map_default", "CompositeMapRenderer", "Map_default", "map", "listen", "checkedFonts", "ObjectEventType_default", "WORKER_OFFSCREEN_CANVAS", "createMockDiv", "style", "CLASS_UNSELECTABLE", "container", "type", "frameState", "event", "Event_default", "unlistenByKey", "EventType_default", "layerStatesArray", "a", "b", "layerState", "BaseVector_default", "viewState", "renderedLayerStates", "previousElement", "i", "ii", "layer", "sourceState", "inView", "element", "replaceChildren", "mapCanvas", "isCanvas", "mapContext", "canvas", "backgroundColor", "opacity", "transform", "fromString", "w", "h", "layerStates", "Composite_default", "removeLayerMapProperty", "layer", "Layer_default", "Group_default", "setLayerMapProperty", "map", "layers", "i", "ii", "Map", "Object_default", "options", "optionsInternal", "createOptionsInternal", "DEVICE_PIXEL_RATIO", "create", "WORKER_OFFSCREEN_CANVAS", "Collection_default", "defaults", "TileQueue_default", "MapProperty_default", "View_default", "viewOptions", "CollectionEventType_default", "event", "id", "control", "interaction", "overlay", "pixel", "callback", "coordinate", "hitTolerance", "layerFilter", "TRUE", "checkWrapped", "features", "feature", "addLayersFrom", "layerGroup", "viewportPosition", "viewportSize", "scaleX", "scaleY", "eventPosition", "toUserCoordinate", "frameState", "apply", "group", "collection", "layerStatesArray", "state", "renderer", "source", "viewCoordinate", "fromUserCoordinate", "pixelRatio", "targetElement", "tile", "tileSourceKey", "tileCenter", "tileResolution", "getTilePriority", "browserEvent", "type", "mapBrowserEvent", "MapBrowserEvent_default", "originalEvent", "eventType", "EventType_default", "doc", "rootNode", "target", "currentDoc", "interactionsArray", "tileQueue", "maxTotalLoading", "maxNewLoads", "hints", "animatingOrInteracting", "ViewHint_default", "lowOnFrameBudget", "MapEvent_default", "MapEventType_default", "postRenderFunctions", "unlistenByKey", "isCanvas", "Composite_default", "MapBrowserEventHandler_default", "key", "MapBrowserEventType_default", "PASSIVE_EVENT_LISTENERS", "keyboardEventTarget", "targetRoot", "listen", "view", "ObjectEventType_default", "GroupEvent", "layerStates", "time", "size", "previousFrameState", "hasArea", "viewHints", "viewState", "getForViewAndSize", "getUid", "rotation", "isEmpty", "equals", "createOrUpdateEmpty", "clone", "oldLayerGroup", "width", "height", "transform", "computedStyle", "warn", "oldSize", "values", "controls", "assert", "interactions", "overlays", "Map_default", "Tile", "Target_default", "tileCoord", "state", "options", "EventType_default", "TileState_default", "abstract", "id", "time", "start", "delta", "easeIn", "Tile_default", "asImageLike", "data", "disposedError", "defaultSize", "DataTile", "Tile_default", "options", "state", "TileState_default", "imageData", "asImageLike", "self", "data", "error", "disposedError", "DataTile_default", "ImageTile", "Tile_default", "tileCoord", "state", "src", "imageAttributes", "tileLoadFunction", "options", "WORKER_OFFSCREEN_CANVAS", "element", "TileState_default", "getBlankImage", "image", "listenImage", "ctx", "createCanvasContext2D", "ImageTile_default", "TileRange", "minX", "maxX", "minY", "maxY", "tileCoord", "tileRange", "x", "y", "createOrUpdate", "TileRange_default", "brokenDiagonalRendering_", "canvasPool", "drawTestTriangle", "ctx", "u1", "v1", "u2", "v2", "verifyBrokenDiagonalRendering", "data", "offset", "isBrokenDiagonalRendering", "createCanvasContext2D", "releaseCanvas", "calculateSourceResolution", "sourceProj", "targetProj", "targetCenter", "targetResolution", "sourceCenter", "transform", "sourceResolution", "getPointResolution", "targetMetersPerUnit", "sourceMetersPerUnit", "sourceExtent", "containsCoordinate", "compensationFactor", "calculateSourceExtentResolution", "targetExtent", "getCenter", "forEachCorner", "corner", "render", "width", "height", "pixelRatio", "triangulation", "sources", "gutter", "renderEdges", "interpolate", "drawSingle", "clipExtent", "context", "pixelRound", "value", "sourceDataExtent", "createEmpty", "src", "i", "arr", "extend", "stitchContext", "stitchScale", "inverseScale", "getWidth", "getHeight", "xPos", "yPos", "srcWidth", "srcHeight", "targetTopLeft", "getTopLeft", "triangle", "source", "target", "x0", "y0", "x1", "y1", "x2", "y2", "u0", "v0", "sourceNumericalShiftX", "sourceNumericalShiftY", "augmentedMatrix", "affineCoefs", "solveLinearSystem", "steps", "ud", "vd", "step", "image", "extent", "MAX_SUBDIVISION", "MAX_TRIANGLE_WIDTH", "Triangulation", "sourceProj", "targetProj", "targetExtent", "maxSourceExtent", "errorThreshold", "destinationResolution", "sourceMatrix", "transformInvCache", "transformInv", "createTransformFromCoordinateTransform", "input", "apply", "transform", "getTransform", "c", "key", "getWidth", "destinationTopLeft", "getTopLeft", "destinationTopRight", "getTopRight", "destinationBottomRight", "getBottomRight", "destinationBottomLeft", "getBottomLeft", "sourceTopLeft", "sourceTopRight", "sourceBottomRight", "sourceBottomLeft", "maxSubdivision", "getArea", "leftBound", "triangle", "i", "arr", "newTriangle", "minX", "a", "b", "aSrc", "bSrc", "cSrc", "d", "dSrc", "sourceQuadExtent", "boundingExtent", "sourceCoverageX", "sourceWorldWidth", "wrapsX", "needsSubdivision", "targetQuadExtent", "intersects", "isNotFinite", "center", "centerSrc", "dx", "modulo", "dy", "bc", "bcSrc", "da", "daSrc", "ab", "abSrc", "cd", "cdSrc", "extent", "createEmpty", "src", "extendCoordinate", "Triangulation_default", "ReprojTile", "Tile_default", "sourceProj", "sourceTileGrid", "targetProj", "targetTileGrid", "tileCoord", "wrappedTileCoord", "pixelRatio", "gutter", "getTileFunction", "errorThreshold", "renderEdges", "options", "TileState_default", "targetExtent", "maxTargetExtent", "maxSourceExtent", "limitedTargetExtent", "getIntersection", "getArea", "sourceProjExtent", "targetResolution", "sourceResolution", "calculateSourceExtentResolution", "errorThresholdInPixels", "Triangulation_default", "sourceExtent", "clamp", "worldWidth", "worldsAway", "getWidth", "wrapAndSliceX", "extent", "sourceRange", "srcX", "srcY", "offset", "sources", "source", "tile", "clipExtent", "z", "size", "width", "height", "render", "sourceTile", "leftToLoad", "state", "sourceListenKey", "listen", "EventType_default", "e", "unlistenByKey", "i", "arr", "releaseCanvas", "canvasPool", "LRUCache", "highWaterMark", "entry", "Disposable_default", "keep", "key", "f", "options", "assert", "keys", "i", "values", "value", "size", "LRUCache_default", "createOrUpdate", "z", "x", "y", "tileCoord", "getKeyZXY", "getCacheKey", "source", "sourceKey", "z", "x", "y", "getUid", "getKeyZXY", "hash", "tileCoord", "hashZXY", "z", "x", "y", "withinExtentAndZ", "tileGrid", "tileRange", "ZIndexContext", "getSharedCanvasContext2D", "target", "property", "value", "args", "instructions", "index", "render", "context", "instructionsAtIndex", "i", "ii", "instructionAtIndex", "ZIndexContext_default", "maxStaleKeys", "LayerRenderer", "Observable_default", "layer", "key", "pixel", "abstract", "frameState", "target", "coordinate", "hitTolerance", "callback", "matches", "event", "image", "ImageState_default", "imageState", "EventType_default", "Layer_default", "canvasPool", "pixelContext", "createPixelContext", "createCanvasContext2D", "CanvasLayerRenderer", "Layer_default", "layer", "create", "image", "col", "row", "data", "frameState", "background", "target", "transform", "backgroundColor", "layerClassName", "container", "context", "equals", "asArray", "canvas", "isCanvas", "equivalent", "WORKER_OFFSCREEN_CANVAS", "createMockDiv", "style", "extent", "topLeft", "getTopLeft", "topRight", "getTopRight", "bottomRight", "getBottomRight", "bottomLeft", "getBottomLeft", "apply", "inverted", "resolution", "rotation", "pixelRatio", "width", "getWidth", "height", "getHeight", "compose", "makeInverse", "canvasTransform", "toString", "type", "event", "Event_default", "EventType_default", "ZIndexContext_default", "center", "offsetX", "dx1", "dy1", "sx", "sy", "dx2", "dy2", "addTileToLookup", "tilesByZ", "tile", "z", "set", "existing", "removeTileFromLookup", "getRenderExtent", "frameState", "extent", "layerState", "getIntersection", "fromUserExtent", "source", "gridExtent", "CanvasTileLayerRenderer", "Layer_default", "tileLayer", "options", "createEmpty", "TileRange_default", "createOrUpdate", "cacheSize", "LRUCache_default", "x", "y", "tileCache", "tileSource", "cacheKey", "getCacheKey", "projection", "sourceProjection", "equivalent", "pixel", "layer", "coordinate", "apply", "layerExtent", "containsCoordinate", "viewState", "tileGrid", "tilePixelRatio", "tileCoord", "TileState_default", "tileOrigin", "tileSize", "toSize", "tileResolution", "image", "ImageTile_default", "Tile_default", "DataTile_default", "asImageLike", "col", "row", "gutter", "sourceRevision", "initialZ", "preload", "tileSourceKey", "getUid", "wantedTiles", "map", "minZ", "rotation", "viewport", "getRotatedViewport", "tileRange", "tileQueueKey", "staleKeys", "i", "altZ", "covered", "sourceKey", "loaded", "target", "viewResolution", "viewCenter", "pixelRatio", "frameExtent", "width", "height", "dx", "dy", "canvasExtent", "targetZ", "nextExtent", "renderExtent", "uid", "time", "tileState", "minZoom", "parentZ", "canvasScale", "context", "compose", "zs", "ascending", "currentClip", "clips", "clipZs", "currentZ", "currentTilePixelSize", "currentScale", "originTileCoord", "getTopLeft", "originTileExtent", "origin", "tileGutter", "xIndex", "nextX", "yIndex", "nextY", "w", "h", "transition", "contextSaved", "ii", "clip", "intersects", "equals", "postRenderFunction", "tilesCount", "tileCount", "alpha", "alphaChanged", "usedTiles", "TileLayer_default", "TileProperty_default", "BaseTileLayer", "Layer_default", "options", "baseOptions", "cacheSize", "TileProperty_default", "preload", "useInterimTilesOnError", "pixel", "BaseTile_default", "TileLayer", "BaseTile_default", "options", "TileLayer_default", "Tile_default", "tmpTileCoord", "DECIMALS", "TileGrid", "options", "assert", "isSorted", "a", "b", "zoomFactor", "ii", "extent", "getTopLeft", "size", "z", "tileRange", "TileRange_default", "restrictedTileRange", "zoom", "callback", "i", "j", "jj", "tileCoord", "tempTileRange", "tempExtent", "x", "y", "tileCoordExtent", "createOrUpdate", "minX", "minY", "tileCoordZ", "tileCoordX", "tileCoordY", "factor", "maxX", "maxY", "origin", "resolution", "tileSize", "toSize", "coordinate", "opt_tileCoord", "reverseIntersectionPolicy", "scale", "ceil", "floor", "opt_direction", "linearFindNearest", "clamp", "viewport", "intersectsLinearRing", "length", "fullTileRanges", "TileGrid_default", "WMTSTileGrid", "TileGrid_default", "options", "z", "createFromCapabilitiesMatrixSet", "matrixSet", "extent", "matrixLimits", "resolutions", "matrixIds", "origins", "tileSizes", "sizes", "supportedCRSPropName", "matrixIdsPropName", "identifierPropName", "scaleDenominatorPropName", "topLeftCornerPropName", "tileWidthPropName", "tileHeightPropName", "code", "projection", "get", "metersPerUnit", "switchOriginXY", "a", "b", "elt", "matrixAvailable", "elt_ml", "resolution", "tileWidth", "tileHeight", "WMTSTileGrid", "getForProjection", "projection", "tileGrid", "createForProjection", "wrapX", "tileCoord", "z", "center", "projectionExtent", "extentFromProjection", "containsCoordinate", "worldWidth", "getWidth", "worldsAway", "createForExtent", "extent", "maxZoom", "tileSize", "corner", "resolutions", "resolutionsFromExtent", "TileGrid_default", "getCorner", "createXYZ", "options", "xyzOptions", "get", "gridOptions", "maxResolution", "toSize", "height", "getHeight", "width", "length", "half", "METERS_PER_UNIT", "createOrUpdate", "appendParams", "uri", "params", "keyParams", "k", "qs", "zRegEx", "xRegEx", "yRegEx", "dashYRegEx", "renderXYZTemplate", "template", "z", "x", "y", "maxY", "expandUrl", "url", "urls", "match", "startCharCode", "stopCharCode", "charCode", "stop", "createFromTemplate", "template", "tileGrid", "tileCoord", "pixelRatio", "projection", "maxY", "z", "range", "renderXYZTemplate", "createFromTemplates", "templates", "len", "tileUrlFunctions", "createFromTileUrlFunctions", "h", "hash", "index", "modulo", "Source", "Object_default", "options", "get", "adaptAttributions", "self", "resolve", "reject", "projection", "attributions", "state", "attributionLike", "frameState", "Source_default", "TileSource", "Source_default", "options", "tileSize", "toSize", "getUid", "projection", "key", "tileGrid", "z", "x", "y", "pixelRatio", "tileCache", "abstract", "getForProjection", "tilePixelRatio", "scale", "tileCoord", "gridProjection", "wrapX", "withinExtentAndZ", "TileSourceEvent", "Event_default", "type", "tile", "Tile_default", "TileEventType_default", "UrlTile", "_UrlTile", "Tile_default", "options", "event", "tile", "uid", "getUid", "tileState", "type", "TileState_default", "TileEventType_default", "TileSourceEvent", "tileLoadFunction", "tileUrlFunction", "key", "url", "urls", "expandUrl", "createFromTemplates", "tileCoord", "pixelRatio", "projection", "UrlTile_default", "TileImage", "UrlTile_default", "options", "defaultTileLoadFunction", "ImageTile_default", "projection", "equivalent", "key", "thisProj", "projKey", "getUid", "getForProjection", "z", "x", "y", "pixelRatio", "tileCoord", "urlTileCoord", "tileUrl", "tile", "TileState_default", "EventType_default", "tileCache", "sourceProjection", "sourceTileGrid", "targetTileGrid", "wrappedTileCoord", "Tile_default", "cacheKey", "getCacheKey", "render", "tilegrid", "proj", "get", "imageTile", "src", "WORKER_OFFSCREEN_CANVAS", "crossOrigin", "mode", "credentials", "response", "blob", "imageBitmap", "canvas", "TileImage_default", "XYZ", "TileImage_default", "options", "projection", "tileGrid", "createXYZ", "extentFromProjection", "XYZ_default", "ATTRIBUTION", "OSM", "XYZ_default", "options", "attributions", "url", "OSM_default", "PROJECTION", "COORDINATE_FORMAT", "MousePosition", "Control_default", "options", "element", "event", "map", "viewport", "listen", "EventType_default", "format", "projection", "get", "pixel", "html", "getTransformFromProjections", "identityTransform", "coordinate", "userProjection", "getUserProjection", "wrapX", "coordinateFormat", "mapEvent", "frameState", "MousePosition_default", "Property", "Overlay", "Object_default", "options", "CLASS_SELECTABLE", "removeChildren", "element", "unlistenByKey", "map", "listen", "MapEventType_default", "container", "offset", "position", "panIntoViewOptions", "mapRect", "overlayRect", "outerWidth", "outerHeight", "myMargin", "containsExtent", "offsetLeft", "offsetRight", "offsetTop", "offsetBottom", "delta", "center", "centerPx", "newCenterPx", "panOptions", "size", "box", "offsetX", "offsetY", "positioning", "visible", "pixel", "mapSize", "style", "x", "y", "posX", "posY", "transform", "Overlay_default", "UNITS_PROP", "LEADING_DIGITS", "DEFAULT_DPI", "ScaleLine", "Control_default", "options", "element", "className", "CLASS_UNSELECTABLE", "units", "dpi", "viewState", "center", "projection", "pointResolutionUnits", "pointResolution", "getPointResolution", "minWidth", "maxWidth", "nominalCount", "suffix", "metersPerDegree", "METERS_PER_UNIT", "i", "count", "width", "decimalCount", "previousCount", "previousWidth", "previousDecimalCount", "decimal", "html", "scale", "resolutionScale", "mapScale", "steps", "stepWidth", "scaleSteps", "cls", "position", "isLast", "lengthString", "margin", "resolution", "inchesPerMeter", "mapEvent", "frameState", "ScaleLine_default", "IMAGERY_FALLBACK", "BASEMAP_CLASS", "createBasemaps", "imagery", "satellite", "basemaps", "Tile_default", "OSM_default", "XYZ_default", "layer", "applyBasemapFilter", "event", "container", "filter", "basemapFilter", "applyBasemapLook", "look", "opacity", "gray", "normalizeBasemapLook", "setBasemap", "key", "basemapKey", "WORLD_VIEW", "createMap", "target", "config", "defaultExtent", "view", "View_default", "fromLonLat", "map", "Map_default", "defaults", "size", "transformExtent", "addStandardControls", "mousePositionEl", "Zoom_default", "ScaleLine_default", "MousePosition_default", "createStringXY", "zoomToExtent", "extent", "options", "readViewConfig", "center", "toLonLat", "basemapThumbnail", "gradients", "renderBasemapSwitcher", "activeKey", "onChange", "onLookChange", "title", "btn", "basemapLookControlsHtml", "controls", "range", "emit", "syncBasemapLookControls", "percent", "label", "toggle", "samplesPromise", "loadSampleMaps", "ctx", "apiFetch", "result", "escapeHtml", "value", "offersSampleMaps", "renderSampleMapsHint", "container", "maps", "box", "m", "event", "link", "go", "fromResolutionLike", "resolution", "ReprojImage", "Image_default", "sourceProj", "targetProj", "targetExtent", "targetResolution", "pixelRatio", "getImageFunction", "interpolate", "maxSourceExtent", "maxTargetExtent", "limitedTargetExtent", "getIntersection", "targetCenter", "getCenter", "sourceResolution", "calculateSourceResolution", "errorThresholdInPixels", "triangulation", "Triangulation_default", "sourceExtent", "sourceImage", "isEmpty", "state", "ImageState_default", "sourcePixelRatio", "sourceState", "width", "getWidth", "height", "getHeight", "render", "fromResolutionLike", "listen", "EventType_default", "e", "unlistenByKey", "ImageSourceEventType", "ImageSourceEvent", "Event_default", "type", "image", "ImageSource", "Source_default", "options", "resolutions", "resolution", "idx", "linearFindNearest", "extent", "pixelRatio", "projection", "sourceProjection", "equivalent", "equals", "Image_default", "requestExtent", "getRequestExtent", "requestResolution", "containsExtent", "fromResolutionLike", "EventType_default", "event", "ImageState_default", "defaultImageLoadFunction", "src", "ratio", "imageResolution", "center", "getCenter", "viewWidth", "ceil", "getWidth", "viewHeight", "getHeight", "marginWidth", "requestWidth", "marginHeight", "requestHeight", "getForViewAndSize", "DEFAULT_VERSION", "GETFEATUREINFO_IMAGE_SIZE", "getRequestUrl", "baseUrl", "extent", "size", "projection", "params", "axisOrientation", "v13", "compareVersions", "bbox", "appendParams", "getImageSrc", "resolution", "pixelRatio", "url", "serverType", "imageResolution", "imageSize", "round", "getWidth", "getHeight", "dpi", "getRequestParams", "request", "createLoader", "options", "hidpi", "get", "ratio", "load", "decode", "crossOrigin", "referrerPolicy", "getRequestExtent", "src", "image", "getFeatureInfoUrl", "coordinate", "projectionObj", "getForViewAndSize", "baseParams", "x", "floor", "y", "getLegendUrl", "mpu", "pixelSize", "layers", "ImageWMS", "Image_default", "options", "defaultImageLoadFunction", "coordinate", "resolution", "projection", "params", "projectionObj", "get", "sourceProjectionObj", "calculateSourceResolution", "transform", "getFeatureInfoUrl", "getLegendUrl", "extent", "pixelRatio", "createLoader", "image", "src", "decode", "imageLoadFunction", "url", "ImageWMS_default", "CanvasImageLayerRenderer", "Layer_default", "imageLayer", "frameState", "layerState", "pixelRatio", "viewState", "viewResolution", "imageSource", "hints", "renderedExtent", "getIntersection", "fromUserExtent", "ViewHint_default", "isEmpty", "projection", "image", "ImageState_default", "pixel", "layer", "coordinate", "apply", "layerExtent", "containsCoordinate", "imageExtent", "img", "imageMapWidth", "getWidth", "col", "imageMapHeight", "getHeight", "row", "target", "imageResolution", "imageResolutionX", "imageResolutionY", "imagePixelRatio", "viewCenter", "scaleX", "scaleY", "width", "height", "context", "clipped", "render", "intersects", "containsExtent", "transform", "compose", "dw", "dh", "dx", "dy", "opacity", "ImageLayer_default", "BaseImageLayer", "Layer_default", "options", "BaseImage_default", "ImageLayer", "BaseImage_default", "options", "ImageLayer_default", "pixel", "Image_default", "FILTER_OPERATORS", "xmlEscape", "value", "emptyFilter", "emptyCondition", "attribute", "isConditionComplete", "condition", "op", "o", "isFilterActive", "filter", "binaryOp", "tag", "likeOp", "pattern", "conditionToXml", "operator", "value2", "combineXml", "fragments", "logic", "parts", "filterToXml", "searchToXml", "searchText", "textAttributes", "text", "attr", "buildFilterXml", "combined", "xmlEscape", "value", "POINT_SHAPES", "pointSymbolizer", "rule", "wkn", "stroke", "markSymbolizer", "wellKnownName", "size", "fill", "photoSymbolizer", "ring", "camera", "lens", "photoMarkerSizes", "ink", "outline", "PHOTO_SYMBOL", "pointSymbolizerFor", "photo", "plainDotSize", "lineSymbolizer", "dash", "polygonSymbolizer", "textSymbolizer", "ctx", "textSymbolizerXml", "symbolizersFor", "geometryGroup", "style", "category", "baseRule", "ruleForCategory", "symbolizersForGroups", "geometryGroups", "group", "equalFragment", "attribute", "rangeFragment", "min", "max", "isLast", "upperOp", "wrapFilter", "ruleFragment", "filterFragment", "combined", "combineXml", "hasPhotoFragment", "field", "ruleElements", "fragment", "elseFallback", "title", "photoField", "head", "label", "basePoint", "point", "filter", "hasPhoto", "photoFragment", "simpleRule", "categorizedRules", "categories", "other", "rules", "cat", "graduatedRules", "classes", "cls", "index", "rulesFor", "namedLayer", "sublayer", "minZoom", "normalizeGeometryType", "photoFieldOf", "namedLayers", "entry", "sublayers", "filterToXml", "labelMinZoom", "sub", "buildSldForEntries", "entries", "buildSld", "createElementNS", "namespaceURI", "qualifiedName", "getDocument", "getAllTextContent", "node", "normalizeWhitespace", "getAllTextContent_", "accumulator", "n", "isDocument", "object", "parse", "xml", "makeArrayPusher", "valueReader", "thisArg", "node", "objectStack", "value", "makeObjectPropertyPusher", "valueReader", "property", "thisArg", "node", "objectStack", "value", "object", "name", "array", "makeObjectPropertySetter", "makeSimpleNodeFactory", "fixedNodeName", "fixedNamespaceURI", "value", "objectStack", "newNodeName", "node", "nodeName", "namespaceURI", "createElementNS", "OBJECT_PROPERTY_NODE_FACTORY", "makeStructureNS", "namespaceURIs", "structure", "structureNS", "i", "ii", "parseNode", "parsersNS", "node", "objectStack", "thisArg", "n", "parsers", "parser", "pushParseAndPop", "object", "document_", "getDocument", "document_", "XML", "source", "doc", "parse", "isDocument", "n", "node", "abstract", "XML_default", "NAMESPACE_URI", "readHref", "node", "readBooleanString", "string", "m", "readDecimal", "node", "s", "getAllTextContent", "readDecimalString", "string", "m", "readPositiveInteger", "readNonNegativeIntegerString", "readString", "NAMESPACE_URIS", "isV13", "objectStack", "compareVersions", "PARSERS", "makeStructureNS", "makeObjectPropertySetter", "readService", "readCapability", "CAPABILITY_PARSERS", "readRequest", "readException", "readCapabilityLayer", "readUserDefinedSymbolization", "WMSCapabilities", "XML_default", "node", "wmsCapabilityObject", "pushParseAndPop", "COMMON_SERVICE_PARSERS", "readString", "readKeywordList", "readHref", "readContactInformation", "SERVICE_PARSERS", "SERVICE_PARSERS_V13", "readPositiveInteger", "CONTACT_INFORMATION_PARSERS", "readContactPersonPrimary", "readContactAddress", "CONTACT_PERSON_PARSERS", "CONTACT_ADDRESS_PARSERS", "EXCEPTION_PARSERS", "makeArrayPusher", "COMMON_LAYER_PARSERS", "makeObjectPropertyPusher", "readBoundingBox", "readDimension", "readAttribution", "readAuthorityURL", "readMetadataURL", "readFormatOnlineresource", "readStyle", "readLayer", "LAYER_PARSERS", "readExtent", "readScaleHint", "LAYER_PARSERS_V13", "readEXGeographicBoundingBox", "readDecimal", "ATTRIBUTION_PARSERS", "readSizedFormatOnlineresource", "EX_GEOGRAPHIC_BOUNDING_BOX_PARSERS", "REQUEST_PARSERS", "readOperationType", "OPERATIONTYPE_PARSERS", "readDCPType", "DCPTYPE_PARSERS", "readHTTP", "HTTP_PARSERS", "STYLE_PARSERS", "FORMAT_ONLINERESOURCE_PARSERS", "KEYWORDLIST_PARSERS", "readBooleanString", "withCrs", "extent", "readDecimalString", "resolutions", "result", "geographicBoundingBox", "westBoundLongitude", "southBoundLatitude", "eastBoundLongitude", "northBoundLatitude", "layerObject", "v13", "parentLayerObject", "queryable", "cascaded", "readNonNegativeIntegerString", "opaque", "noSubsets", "fixedWidth", "fixedHeight", "addKeys", "key", "childValue", "replaceKeys", "parentValue", "dimensionObject", "formatOnlineresource", "size", "authorityObject", "metadataObject", "WMSCapabilities_default", "SKIPPED_LAYERS_HEADER", "HYBRID_LAYERS_HEADER", "HYBRID_ICON_PATHS", "DEFAULT_SKIP_REASON", "headerRecords", "raw", "wrapperKeys", "empty", "data", "key", "k", "records", "omitted", "entry", "parseSkippedLayers", "layers", "names", "value", "v", "parseHybridLayers", "groups", "readDiagnostics", "headers", "get", "name", "skippedReasonText", "layer", "reasons", "PNG_FORMAT", "MIXED_FORMAT", "MIXED_PNG_FORMAT", "mixedFormat", "setMixedImages", "setting", "imageFormat", "entry", "SHOW_DELAY", "SLOW_AFTER", "trackSourceLoading", "entry", "source", "kind", "prefix", "emit", "seconds", "preparingSeq", "beginPreparing", "ctx", "title", "note", "item", "updatePreparing", "changes", "endPreparing", "other", "sizeNote", "bytes", "loadingEntries", "flatLayers", "isEffectivelyVisible", "initLoadingIndicator", "host", "bar", "pill", "showTimer", "slowTimer", "visible", "slow", "pillText", "entries", "preparing", "first", "what", "renderPill", "show", "current", "busy", "hide", "update", "on", "reason", "signedParams", "entry", "params", "usesNativeStyle", "rasterParams", "style", "bandCount", "lo", "hi", "nativeFilter", "sublayerNames", "fragment", "filterToXml", "filter", "buildWmsParams", "s", "imageFormat", "buildSld", "URL_LENGTH_LIMIT", "BLANK_IMAGE", "DETAIL_TTL_MS", "detailCache", "fetchItemDetail", "bootstrap", "itemId", "mapId", "url", "wmsDetailUrl", "cached", "promise", "apiFetch", "forgetItemDetail", "base", "reportDiagnostics", "entry", "response", "diagnostics", "readDiagnostics", "emit", "createImageLoadFunction", "lastObjectUrl", "imageWrapper", "src", "img", "cleanup", "isGet", "request", "queryIndex", "body", "blob", "createWmsLayer", "setMixedImages", "source", "ImageWMS_default", "buildWmsParams", "layer", "Image_default", "trackSourceLoading", "debouncedRefreshers", "scheduleWmsRefresh", "delay", "key", "refresh", "debounce", "refreshSignatureIfNeeded", "entry", "bootstrap", "marginSeconds", "mapId", "expiresAt", "now", "detail", "fetchItemDetail", "buildWmsParams", "Feature", "_Feature", "Object_default", "geometryOrProperties", "geometry", "properties", "clone", "geometryName", "key", "style", "unlistenByKey", "listen", "EventType_default", "createStyleFunction", "id", "name", "obj", "styles", "assert", "Feature_default", "Circle", "_Circle", "SimpleGeometry_default", "center", "radius", "layout", "circle", "x", "y", "closestPoint", "minSquaredDistance", "flatCoordinates", "dx", "dy", "squaredDistance", "i", "delta", "extent", "createOrUpdate", "circleExtent", "intersects", "forEachCorner", "stride", "offset", "deflateCoordinate", "ii", "coordinates", "angle", "anchor", "rotate", "Circle_default", "interpolatePoint", "flatCoordinates", "offset", "end", "stride", "fraction", "dest", "dimension", "o", "t", "n", "x1", "y1", "length", "cumulativeLengths", "i", "x2", "y2", "target", "index", "binarySearch", "lerp", "lineStringCoordinateAtM", "m", "extrapolate", "coordinate", "lo", "hi", "mid", "m0", "m1", "lineStringsCoordinateAtM", "ends", "interpolate", "ii", "lineStringLength", "flatCoordinates", "offset", "end", "stride", "x1", "y1", "length", "i", "x2", "y2", "LineString", "_LineString", "SimpleGeometry_default", "coordinates", "layout", "coordinate", "extend", "lineString", "x", "y", "closestPoint", "minSquaredDistance", "closestSquaredDistanceXY", "maxSquaredDelta", "assignClosestPoint", "callback", "forEach", "m", "extrapolate", "lineStringCoordinateAtM", "inflateCoordinates", "fraction", "dest", "interpolatePoint", "lineStringLength", "squaredTolerance", "simplifiedFlatCoordinates", "douglasPeucker", "extent", "intersectsLineString", "deflateCoordinates", "LineString_default", "MultiLineString", "_MultiLineString", "SimpleGeometry_default", "coordinates", "layout", "ends", "lineStrings", "flatCoordinates", "i", "ii", "lineString", "extend", "multiLineString", "x", "y", "closestPoint", "minSquaredDistance", "closestSquaredDistanceXY", "arrayMaxSquaredDelta", "assignClosestArrayPoint", "m", "extrapolate", "interpolate", "lineStringsCoordinateAtM", "inflateCoordinatesArray", "index", "LineString_default", "offset", "end", "start", "length", "lineStringLength", "midpoints", "stride", "midpoint", "interpolatePoint", "squaredTolerance", "simplifiedFlatCoordinates", "simplifiedEnds", "douglasPeuckerArray", "extent", "intersectsLineStringArray", "deflateCoordinatesArray", "MultiLineString_default", "MultiPoint", "_MultiPoint", "SimpleGeometry_default", "coordinates", "layout", "point", "extend", "multiPoint", "x", "y", "closestPoint", "minSquaredDistance", "closestSquaredDistanceXY", "flatCoordinates", "stride", "i", "ii", "squaredDistance", "j", "inflateCoordinates", "index", "n", "Point_default", "points", "extent", "containsXY", "deflateCoordinates", "MultiPoint_default", "linearRingss", "flatCoordinates", "offset", "endss", "stride", "flatCenters", "extent", "createEmpty", "i", "ii", "ends", "createOrUpdateFromFlatCoordinates", "MultiPolygon", "_MultiPolygon", "SimpleGeometry_default", "coordinates", "layout", "endss", "polygons", "flatCoordinates", "thisEndss", "i", "ii", "polygon", "offset", "ends", "j", "jj", "extend", "len", "newEndss", "multiPolygon", "x", "y", "closestPoint", "minSquaredDistance", "closestSquaredDistanceXY", "multiArrayMaxSquaredDelta", "assignClosestMultiArrayPoint", "linearRingssContainsXY", "linearRingss", "right", "orientLinearRingsArray", "inflateMultiCoordinatesArray", "flatCenters", "getInteriorPointsOfMultiArray", "MultiPoint_default", "linearRingssAreOriented", "squaredTolerance", "simplifiedFlatCoordinates", "simplifiedEndss", "quantizeMultiArray", "index", "prevEnds", "end", "Polygon_default", "extent", "intersectsLinearRingMultiArray", "deflateMultiCoordinatesArray", "lastEnds", "MultiPolygon_default", "VectorContext", "geometry", "feature", "renderer", "hitDetectionRenderer", "index", "style", "circleGeometry", "geometryCollectionGeometry", "lineStringGeometry", "multiLineStringGeometry", "multiPointGeometry", "multiPolygonGeometry", "pointGeometry", "polygonGeometry", "fillStyle", "strokeStyle", "imageStyle", "declutterImageWithText", "textStyle", "VectorContext_default", "Instruction", "fillInstruction", "strokeInstruction", "beginPathInstruction", "closePathInstruction", "Instruction_default", "CanvasBuilder", "VectorContext_default", "tolerance", "maxExtent", "resolution", "pixelRatio", "dashArray", "dash", "flatCoordinates", "stride", "extent", "tmpCoord", "coordinates", "myEnd", "i", "ii", "containsCoordinate", "offset", "end", "closed", "skipFirst", "lastXCoord", "lastYCoord", "nextCoord", "skipped", "lastRel", "nextRel", "coordinateRelationship", "Relationship_default", "ends", "builderEnds", "builderEnd", "geometry", "feature", "renderer", "hitDetectionRenderer", "index", "type", "builderBegin", "builderEndss", "endss", "myEnds", "Instruction_default", "inflateMultiCoordinatesArray", "inflateCoordinatesArray", "inflateCoordinates", "hitDetectionInstructions", "n", "instruction", "begin", "reverseSubArray", "fillStyle", "state", "fillStyleColor", "asColorLike", "defaultFillStyle", "strokeStyle", "strokeStyleColor", "defaultStrokeStyle", "strokeStyleLineCap", "defaultLineCap", "strokeStyleLineDash", "defaultLineDash", "strokeStyleLineDashOffset", "defaultLineDashOffset", "strokeStyleLineJoin", "defaultLineJoin", "strokeStyleWidth", "defaultLineWidth", "strokeStyleMiterLimit", "defaultMiterLimit", "strokeStyleOffset", "defaultStrokeOffset", "fillInstruction", "createFill", "applyStroke", "lineCap", "lineDash", "lineDashOffset", "lineJoin", "lineWidth", "miterLimit", "strokeOffset", "equals", "endGeometryInstruction", "clone", "width", "buffer", "Builder_default", "CanvasImageBuilder", "Builder_default", "tolerance", "maxExtent", "resolution", "pixelRatio", "pointGeometry", "feature", "index", "containsCoordinate", "flatCoordinates", "stride", "myBegin", "myEnd", "Instruction_default", "multiPointGeometry", "filteredFlatCoordinates", "i", "ii", "imageStyle", "sharedData", "anchor", "size", "origin", "ImageBuilder_default", "CanvasLineStringBuilder", "Builder_default", "tolerance", "maxExtent", "resolution", "pixelRatio", "flatCoordinates", "offset", "end", "stride", "strokeOffset", "myBegin", "myEnd", "Instruction_default", "lineStringGeometry", "feature", "index", "state", "strokeStyle", "lineWidth", "defaultStrokeStyle", "defaultLineDash", "defaultLineDashOffset", "beginPathInstruction", "strokeInstruction", "multiLineStringGeometry", "ends", "i", "ii", "LineStringBuilder_default", "CanvasPolygonBuilder", "Builder_default", "tolerance", "maxExtent", "resolution", "pixelRatio", "flatCoordinates", "offset", "ends", "stride", "strokeOffset", "state", "fill", "stroke", "numEnds", "beginPathInstruction", "i", "end", "myBegin", "myEnd", "Instruction_default", "closePathInstruction", "fillInstruction", "strokeInstruction", "circleGeometry", "feature", "index", "fillStyle", "strokeStyle", "defaultFillStyle", "defaultStrokeStyle", "defaultLineDash", "defaultLineDashOffset", "circleInstruction", "polygonGeometry", "multiPolygonGeometry", "endss", "ii", "coordinates", "snap", "drawGeometryCallback", "PolygonBuilder_default", "lineChunk", "chunkLength", "flatCoordinates", "offset", "end", "stride", "chunks", "cursor", "chunkM", "currentChunk", "x1", "y1", "x2", "y2", "segmentLength", "m", "x", "lerp", "y", "missing", "matchingChunk", "maxAngle", "flatCoordinates", "offset", "end", "stride", "chunkStart", "chunkEnd", "chunkM", "m", "start", "acos", "i", "m12", "m23", "x1", "y1", "x12", "y12", "x23", "y23", "x2", "y2", "TEXT_ALIGN", "CanvasTextBuilder", "Builder_default", "tolerance", "maxExtent", "resolution", "pixelRatio", "defaultFillStyle", "instructions", "geometry", "feature", "index", "fillState", "strokeState", "textState", "coordinates", "begin", "geometryType", "flatCoordinates", "stride", "intersects", "ends", "endss", "i", "ii", "repeat", "textAlign", "flatOffset", "o", "oo", "chunks", "lineChunk", "c", "cc", "chunk", "chunkBegin", "chunkEnd", "range", "matchingChunk", "end", "geometryWidths", "interiorPoints", "beg", "w", "keep", "backgroundFill", "backgroundStroke", "padding", "defaultPadding", "p0", "p1", "p2", "p3", "Instruction_default", "p", "scale", "hitDetectionBackgroundFill", "strokeKey", "textKey", "defaultTextAlign", "defaultTextBaseline", "fillKey", "baseline", "offsetY", "text", "strokeWidth", "textStyle", "sharedData", "textFillStyle", "asColorLike", "textStrokeStyle", "lineDash", "lineDashOffset", "lineWidth", "miterLimit", "defaultLineCap", "defaultLineDash", "defaultLineDashOffset", "defaultLineJoin", "defaultLineWidth", "defaultMiterLimit", "defaultStrokeStyle", "font", "defaultFont", "registerFont", "textScale", "textOffsetX", "textOffsetY", "textRotateWithView", "textKeepUpright", "textRotation", "getUid", "TextBuilder_default", "BATCH_CONSTRUCTORS", "PolygonBuilder_default", "Builder_default", "ImageBuilder_default", "LineStringBuilder_default", "TextBuilder_default", "BuilderGroup", "tolerance", "maxExtent", "resolution", "pixelRatio", "builderInstructions", "zKey", "builders", "builderKey", "builderInstruction", "zIndex", "builderType", "zIndexKey", "replays", "replay", "Constructor", "BuilderGroup_default", "offsetLineString", "flatCoordinates", "start", "end", "stride", "offset", "isClosedRing", "dest", "destinationStride", "secondPointX", "secondPointY", "secondToLastPointX", "secondToLastPointY", "x", "y", "prevX", "prevY", "nextX", "nextY", "offsetX", "offsetY", "i", "j", "offsetLineVertex", "k", "nx", "ny", "len", "tx", "ty", "joinAngle", "angleBetween", "cos", "sin", "bx", "by", "dx", "dy", "removeOffsetCycles", "coords", "ii", "p1x", "p1y", "p2x", "p2y", "p3x", "p3y", "p4x", "p4y", "d", "t", "u", "ix", "iy", "drawTextOnPath", "flatCoordinates", "offset", "end", "stride", "text", "startM", "maxAngle", "scale", "measureAndCacheTextWidth", "font", "cache", "rotation", "keepUpright", "x2", "y2", "x1", "y1", "segmentLength", "segmentM", "advance", "interpolate", "beginX", "lerp", "beginY", "startOffset", "startLength", "endM", "endX", "endY", "reverse", "flat", "rotate", "PI", "result", "singleSegment", "previousAngle", "x", "y", "i", "ii", "angle", "delta", "iStart", "charLength", "index", "len", "chars", "tmpExtent", "createEmpty", "p1", "p2", "p3", "p4", "getDeclutterBox", "replayImageOrLabelArgs", "rtlRegEx", "horizontalTextAlign", "text", "align", "TEXT_ALIGN", "createTextChunks", "acc", "line", "i", "richTextToPlainText", "result", "part", "index", "Executor", "resolution", "pixelRatio", "overlaps", "instructions", "deferredRendering", "create", "ZIndexContext_default", "textKey", "fillKey", "strokeKey", "key", "strokeState", "fillState", "textState", "scale", "defaultTextAlign", "strokeWidth", "chunks", "width", "height", "widths", "heights", "lineWidths", "getTextDimensions", "renderWidth", "contextInstructions", "w", "h", "label", "leftRight", "x", "strokeInstructions", "fillInstructions", "lineHeight", "lineOffset", "widthHeightIndex", "lineWidthIndex", "previousFont", "ii", "font", "fillStrokeArgs", "context", "fillInstruction", "strokeInstruction", "sheetWidth", "sheetHeight", "centerX", "centerY", "anchorX", "anchorY", "originX", "originY", "rotation", "snapToPixel", "padding", "fillStroke", "feature", "y", "boxW", "boxH", "boxX", "boxY", "transform", "compose", "apply", "createOrUpdate", "scaledCanvasSize", "imageOrLabel", "dimensions", "opacity", "box", "strokePadding", "drawImageOrLabel", "alignAndScale", "origin", "repeatSize", "instruction", "baseline", "defaultTextBaseline", "featureCallback", "hitExtent", "declutterTree", "zIndexContext", "pixelCoordinates", "equals", "transform2D", "setFromArray", "d", "dd", "offsetCoords", "lineOffsetPx", "declutterMode", "prevX", "prevY", "roundX", "roundY", "image", "pendingFill", "pendingStroke", "coordinateCache", "viewRotation", "viewRotationFromTransform", "state", "batchSize", "currentGeometry", "Instruction_default", "intersects", "x1", "y1", "x2", "y2", "dx", "dy", "r", "geometry", "renderer", "fn", "coords", "rotateWithView", "declutterImageWithText", "labelWithAnchor", "textOffsetX", "textOffsetY", "geometryWidths", "backgroundFillInstruction", "backgroundStrokeInstruction", "defaultPadding", "widthIndex", "args", "imageArgs", "imageDeclutterMode", "imageDeclutterBox", "imageDeclutter", "renderImage", "renderText", "render", "begin", "end", "overflow", "maxAngle", "measurePixelRatio", "offsetY", "pixelRatioScale", "textKeepUpright", "textScale", "cachedWidths", "pathLength", "lineStringLength", "textLength", "measureAndCacheTextWidth", "textAlign", "startM", "parts", "drawTextOnPath", "drawChars", "c", "cc", "chars", "lineCoords", "lineStart", "lineEnd", "isClosedRing", "offsetLineString", "removeOffsetCycles", "k", "Executor_default", "ALL", "DECLUTTER", "NON_DECLUTTER", "builderType", "willReadFrequently", "canvasReadsBenchmarked", "benchmarkCanvasReads", "bestResult", "measure", "context", "createCanvasContext2D", "count", "start", "ExecutorGroup", "maxExtent", "resolution", "pixelRatio", "overlaps", "allInstructions", "renderBuffer", "deferredRendering", "create", "transform", "flatClipCoords", "zIndex", "executors", "instructionByZindex", "instructions", "Executor_default", "candidates", "ii", "coordinate", "rotation", "hitTolerance", "callback", "declutteredFeatures", "contextSize", "compose", "newContext", "hitExtent", "createEmpty", "extendCoordinate", "buffer", "indexes", "getPixelIndexArray", "featureCallback", "feature", "geometry", "declutterMode", "imageData", "i", "idx", "x", "y", "result", "zs", "ascending", "j", "executor", "zIndexKey", "minX", "minY", "maxX", "maxY", "transform2D", "isEmpty", "targetContext", "scaledCanvasSize", "viewRotation", "snapToPixel", "builderTypes", "declutterTree", "descending", "maxBuilderTypes", "replays", "jj", "replay", "zIndexContext", "requireClip", "index", "deferredZIndexContexts", "circlePixelIndexArrayCache", "radius", "size", "maxDistanceSq", "distances", "distanceSq", "distance", "pixelIndex", "ExecutorGroup_default", "CanvasImmediateRenderer", "VectorContext_default", "context", "pixelRatio", "extent", "transform", "viewRotation", "squaredTolerance", "userTransform", "toFixed", "create", "flatCoordinates", "offset", "end", "stride", "pixelCoordinates", "transform2D", "localTransform", "alpha", "rotation", "i", "ii", "x", "y", "centerX", "centerY", "compose", "close", "strokeOffset", "offsetLineString", "removeOffsetCycles", "length", "ends", "geometry", "intersects", "transformGeom2D", "dx", "dy", "radius", "style", "feature", "geometries", "flatMidpoint", "geometryExtent", "flatMidpoints", "flatInteriorPoint", "endss", "flatInteriorPoints", "fillState", "contextFillState", "strokeState", "contextStrokeState", "equals", "textState", "contextTextState", "textAlign", "defaultTextAlign", "fillStyle", "strokeStyle", "fillStyleColor", "asColorLike", "defaultFillStyle", "strokeStyleColor", "strokeStyleLineCap", "strokeStyleLineDash", "strokeStyleLineDashOffset", "strokeStyleLineJoin", "strokeStyleWidth", "strokeStyleMiterLimit", "lineDash", "defaultLineDash", "defaultLineCap", "n", "defaultLineDashOffset", "defaultLineJoin", "defaultLineWidth", "defaultMiterLimit", "defaultStrokeStyle", "imageStyle", "imageSize", "imagePixelRatio", "imageAnchor", "imageOrigin", "imageScale", "textStyle", "textFillStyle", "textFillStyleColor", "textStrokeStyle", "textStrokeStyleColor", "textStrokeStyleLineCap", "textStrokeStyleLineDash", "textStrokeStyleLineDashOffset", "textStrokeStyleLineJoin", "textStrokeStyleWidth", "textStrokeStyleMiterLimit", "textFont", "textOffsetX", "textOffsetY", "textRotateWithView", "textRotation", "textScale", "textText", "textTextAlign", "textTextBaseline", "defaultFont", "defaultTextBaseline", "acc", "t", "Immediate_default", "HIT_DETECT_RESOLUTION", "createHitDetectionImageData", "size", "transforms", "features", "styleFunction", "extent", "resolution", "rotation", "squaredTolerance", "projection", "userExtent", "toUserExtent", "width", "height", "context", "createCanvasContext2D", "canvas", "renderer", "Immediate_default", "getTransformFromProjections", "getUserProjection", "featureCount", "indexFactor", "featuresByZIndex", "i", "feature", "featureStyleFunction", "styles", "color", "j", "jj", "originalStyle", "geometry", "intersects", "style", "fill", "stroke", "image", "imgSize", "imgContext", "img", "Icon_default", "zIndex", "byGeometryType", "type", "geometries", "ii", "zIndexKeys", "ascending", "geomAndStyle", "k", "kk", "hitDetect", "pixel", "imageData", "resultFeatures", "x", "y", "index", "clamp", "r", "g", "SIMPLIFY_TOLERANCE", "GEOMETRY_RENDERERS", "renderPointGeometry", "renderLineStringGeometry", "renderPolygonGeometry", "renderMultiPointGeometry", "renderMultiLineStringGeometry", "renderMultiPolygonGeometry", "renderGeometryCollectionGeometry", "renderCircleGeometry", "defaultOrder", "feature1", "feature2", "getUid", "getSquaredTolerance", "resolution", "pixelRatio", "tolerance", "getTolerance", "builderGroup", "geometry", "style", "feature", "index", "fillStyle", "strokeStyle", "circleReplay", "textStyle", "textReplay", "renderFeature", "replayGroup", "squaredTolerance", "listener", "transform", "declutter", "loadingPromises", "imageStyle", "loading", "imageState", "ImageState_default", "renderFeatureInternal", "simplifiedGeometry", "renderGeometry", "geometryRenderer", "geometries", "i", "ii", "declutterBuilderGroup", "lineStringReplay", "polygonReplay", "hasText", "declutterImageWithText", "imageReplay", "hasImage", "CanvasVectorLayerRenderer", "Layer_default", "vectorLayer", "createEmpty", "executorGroup", "frameState", "declutterable", "extent", "viewState", "center", "resolution", "projection", "rotation", "projectionExtent", "vectorSource", "declutter", "pixelRatio", "viewHints", "snapToPixel", "ViewHint_default", "context", "width", "getWidth", "height", "getHeight", "multiWorld", "worldWidth", "endWorld", "world", "transform", "ALL", "DECLUTTER", "NON_DECLUTTER", "createCanvasContext2D", "canvasPool", "alpha", "releaseCanvas", "target", "layerState", "replayGroup", "render", "EventType_default", "clipped", "layerExtent", "fromUserExtent", "intersects", "containsExtent", "pixel", "resolve", "size", "layer", "transforms", "HIT_DETECT_RESOLUTION", "source", "startX", "offsetX", "userProjection", "getUserProjection", "createHitDetectionImageData", "getSquaredTolerance", "hitDetect", "coordinate", "hitTolerance", "callback", "matches", "features", "featureCallback", "feature", "geometry", "distanceSq", "key", "getUid", "match", "item", "event", "animating", "interacting", "updateWhileAnimating", "updateWhileInteracting", "frameStateExtent", "vectorLayerRevision", "vectorLayerRenderBuffer", "vectorLayerRenderOrder", "defaultOrder", "buffer", "renderedExtent", "loadExtents", "canWrapX", "sourceExtent", "isEmpty", "gutter", "projMinX", "projMaxX", "wrapX", "loadExtent", "equals", "BuilderGroup_default", "getTolerance", "userTransform", "i", "ii", "userExtent", "toUserExtent", "toUserResolution", "getTransformFromProjections", "squaredTolerance", "ready", "index", "styles", "styleFunction", "dirty", "replayGroupInstructions", "ExecutorGroup_default", "builderGroup", "loading", "renderFeature", "VectorLayer_default", "VectorLayer", "BaseVector_default", "options", "VectorLayer_default", "Vector_default", "withCredentials", "loadFeaturesXhr", "url", "format", "extent", "resolution", "projection", "success", "failure", "xhr", "event", "type", "source", "features", "dataProjection", "all", "extent", "resolution", "tmpTransform", "create", "RenderFeature", "_RenderFeature", "type", "flatCoordinates", "ends", "stride", "properties", "id", "key", "createOrUpdateFromCoordinate", "createOrUpdateFromFlatCoordinates", "flatCenter", "getCenter", "getInteriorPointOfArray", "inflateEnds", "flatCenters", "linearRingss", "getInteriorPointsOfMultiArray", "interpolatePoint", "offset", "ii", "end", "midpoint", "extend", "squaredTolerance", "transform", "projection", "get", "pixelExtent", "projectedExtent", "scale", "getHeight", "compose", "transform2D", "transformFn", "memoizeOne", "simplifiedFlatCoordinates", "simplifiedEnds", "douglasPeucker", "douglasPeuckerArray", "quantizeArray", "Feature_default", "RenderFeature", "RBush", "maxEntries", "extent", "value", "item", "getUid", "extents", "values", "items", "l", "uid", "bbox", "equals", "callback", "result", "isEmpty", "data", "createOrUpdate", "rbush", "i", "RBush_default", "VectorEventType_default", "VectorSourceEvent", "Event_default", "type", "feature", "features", "VectorSource", "Source_default", "options", "VOID", "assert", "xhr", "all", "useSpatialIndex", "RBush_default", "collection", "Collection_default", "featureKey", "getUid", "geometry", "extent", "VectorEventType_default", "Feature_default", "listen", "EventType_default", "ObjectEventType_default", "valid", "id", "indexedFeature", "extents", "newFeatures", "geometryFeatures", "i", "length", "modifyingCollection", "evt", "CollectionEventType_default", "fast", "featureId", "unlistenByKey", "clearEvent", "callback", "coordinate", "result", "isEmpty", "extend", "projection", "wrapAndSliceX", "anExtent", "filter", "x", "y", "closestFeature", "closestPoint", "minSquaredDistance", "TRUE", "previousMinSquaredDistance", "minDistance", "uid", "event", "sid", "resolution", "loadedExtentsRtree", "extentsToLoad", "ii", "extentToLoad", "object", "containsExtent", "success", "failure", "disableCallbacks", "loaded", "obj", "equals", "removed", "idString", "loader", "url", "overlaps", "Vector_default", "GeometryCollection", "_GeometryCollection", "Geometry_default", "geometries", "unlistenByKey", "i", "ii", "listen", "EventType_default", "geometryCollection", "cloneGeometries", "x", "y", "closestPoint", "minSquaredDistance", "closestSquaredDistanceXY", "extent", "createOrUpdateEmpty", "extend", "geometriesArray", "squaredTolerance", "simplifiedGeometries", "simplified", "geometry", "simplifiedGeometry", "angle", "anchor", "sx", "sy", "getCenter", "transformFn", "deltaX", "deltaY", "GeometryCollection_default", "getCoordinate", "coordinates", "index", "count", "interpolateCoordinate", "startIndex", "along", "endIndex", "start", "x0", "y0", "end", "dx", "dy", "sharedUpdateInfo", "getTraceTargetUpdate", "coordinate", "traceState", "map", "snapTolerance", "x", "y", "closestTargetDistance", "newTargetIndex", "newEndIndex", "targetIndex", "target", "minSegmentDistance", "coordinateIndex", "rel", "getPointSegmentRelationship", "newTarget", "considerBothDirections", "newCoordinate", "pixel", "startPx", "distance", "forwardDistance", "getCumulativeSquaredDistance", "reverseDistance", "getTraceTargets", "features", "targets", "i", "geometry", "appendGeometryTraceTargets", "LineString_default", "appendTraceTarget", "MultiLineString_default", "ii", "Polygon_default", "MultiPolygon_default", "polys", "j", "jj", "GeometryCollection_default", "geometries", "ring", "getSquaredDistance", "a", "b", "squaredDistance", "lowIndex", "highIndex", "lowWholeIndex", "highWholeIndex", "sd", "sharedRel", "x1", "y1", "x2", "y2", "px", "py", "clamp", "toFixed", "DrawEventType", "DrawEvent", "Event_default", "type", "feature", "Draw", "Pointer_default", "options", "pointerOptions", "FALSE", "getMode", "TRUE", "geometryFunction", "mode", "coordinates", "geometry", "projection", "circle", "Circle_default", "center", "fromUserCoordinate", "squaredLength", "squaredDistance", "userProjection", "getUserProjection", "Constructor", "Point_default", "LineString_default", "Polygon_default", "Vector_default", "getDefaultStyleFunction", "noModifierKeys", "always", "shiftKeyOnly", "Property_default", "trace", "condition", "never", "map", "freehand", "event", "EventType_default", "move", "MapBrowserEventType_default", "pass", "MapBrowserEvent_default", "lowerLeft", "upperRight", "extent", "boundingExtent", "features", "targets", "getTraceTargets", "target", "endIndex", "previouslyForward", "currentlyForward", "fromIndex", "toIndex", "remove", "start", "end", "i", "getCoordinate", "traceState", "startPx", "distance", "updatedTraceTarget", "getTraceTargetUpdate", "oldTarget", "newTarget", "coordinate", "interpolateCoordinate", "pixel", "tracing", "startingToDraw", "downPx", "clickPx", "dx", "dy", "at", "potentiallyDone", "potentiallyFinishCoordinates", "sketchCoords", "ii", "finishCoordinate", "finishPixel", "snapTolerance", "Feature_default", "ring", "sketchLineGeom", "stride", "getStrideForLayout", "last", "done", "n", "sketchFeature", "MultiPoint_default", "MultiLineString_default", "MultiPolygon_default", "newDrawing", "ending", "lineString", "sketchFeatures", "overlaySource", "active", "styles", "createEditingStyle", "resolution", "createBox", "coordinates", "geometry", "projection", "extent", "boundingExtent", "coordinate", "fromUserCoordinate", "boxCoordinates", "getBottomLeft", "getBottomRight", "getTopRight", "getTopLeft", "Polygon_default", "userProjection", "getUserProjection", "getMode", "type", "Draw_default", "Draw", "CIRCLE_CENTER_INDEX", "CIRCLE_CIRCUMFERENCE_INDEX", "tempExtent", "tempSegment", "ModifyEventType", "getCoordinatesArray", "coordinates", "geometryType", "depth", "coordinatesArray", "ModifyEvent", "Event_default", "type", "features", "mapBrowserEvent", "Modify", "Pointer_default", "options", "primaryAction", "altKeyOnly", "singleClick", "always", "RBush_default", "Vector_default", "getDefaultStyleFunction", "equals", "CollectionEventType_default", "VectorEventType_default", "feature", "EventType_default", "ObjectEventType_default", "trace", "condition", "never", "geometry", "writer", "map", "evt", "segments", "Collection_default", "ii", "itemIndex", "rBush", "nodesToRemove", "node", "nodeToRemove", "j", "active", "event", "segmentData", "points", "segment", "boundingExtent", "lines", "jj", "i", "rings", "polygons", "k", "kk", "centerSegmentData", "circumferenceSegmentData", "featureSegments", "createOrUpdateFromCoordinate", "circleGeometry", "userProjection", "getUserProjection", "projection", "fromCircle", "geometries", "existing", "vertexFeature", "Feature_default", "Point_default", "handled", "MapBrowserEventType_default", "pixelCoordinate", "insertVertices", "vertex", "vertexExtent", "segmentDataMatches", "componentSegments", "compareIndexes", "segmentDataMatch", "uid", "getUid", "closestVertex", "closestOnSegmentData", "traceState", "startPx", "distance", "updatedTraceTarget", "getTraceTargetUpdate", "oldTarget", "traceSegment", "index", "newTarget", "target", "tolerance", "lowerLeft", "upperRight", "extent", "targets", "getTraceTargets", "endIndex", "previouslyForward", "currentlyForward", "fromIndex", "toIndex", "remove", "start", "end", "removeIndex", "newCoordinates", "getCoordinate", "insertIndex", "dragSegment", "stride", "ring", "targetIndex", "mRing", "mTargetIndex", "circle", "radius", "fromUserCoordinate", "startTraceCoord", "closestOnSegment", "pixel", "sortByDistance", "a", "b", "projectedDistanceToSegmentDataSquared", "nodes", "hitPointGeometry", "layerFilter", "layer", "toUserCoordinate", "geom", "coordinate", "viewExtent", "fromUserExtent", "buffer", "box", "toUserExtent", "closestSegment", "vertexPixel", "dist", "vertexSegments", "pixel1", "pixel2", "squaredDist1", "squaredDistance", "squaredDist2", "geometryUid", "rTree", "newSegmentData", "newSegmentData2", "removed", "dragSegments", "segmentsByFeature", "deleted", "component", "left", "newIndex", "right", "prev", "delta", "pointCoordinates", "distanceToCenterSquared", "distanceToCircumference", "squaredDistanceToSegment", "style", "createEditingStyle", "resolution", "Modify_default", "SelectEventType", "SelectEvent", "Event_default", "type", "selected", "deselected", "mapBrowserEvent", "originalFeatureStyles", "Select", "_Select", "Interaction_default", "options", "singleClick", "never", "shiftKeyOnly", "TRUE", "getDefaultStyleFunction", "Collection_default", "layerFilter", "layers", "layer", "feature", "getUid", "hitTolerance", "map", "CollectionEventType_default", "evt", "Vector_default", "key", "interactions", "interaction", "features", "index", "add", "remove", "toggle", "set", "Feature_default", "i", "hasFeature", "j", "styles", "createEditingStyle", "extend", "Select_default", "FeatureFormat", "Feature_default", "source", "options", "dataProjection", "get", "abstract", "feature", "features", "geometry", "transformGeometryWithOptions", "write", "featureProjection", "transformed", "equivalent", "fromProjection", "toProjection", "getTransform", "power", "transform", "coordinates", "i", "ii", "GeometryConstructor", "Point_default", "LineString_default", "Polygon_default", "MultiPoint_default", "MultiLineString_default", "MultiPolygon_default", "orientFlatCoordinates", "flatCoordinates", "ends", "stride", "linearRingssAreOriented", "orientLinearRingsArray", "linearRingsAreOriented", "orientLinearRings", "createRenderFeature", "object", "options", "geometry", "geometryType", "transformGeometryWithOptions", "Feature_default", "createGeometry", "geometries", "GeometryCollection_default", "Geometry", "JSONFeature", "Feature_default", "source", "options", "getObject", "object", "abstract", "feature", "features", "geometry", "JSONFeature_default", "GeoJSON", "JSONFeature_default", "options", "get", "object", "geoJSONFeature", "geometry", "readGeometryInternal", "Feature_default", "createRenderFeature", "feature", "createGeometry", "geoJSONObject", "features", "geoJSONFeatureCollection", "geoJSONFeatures", "i", "ii", "featureObject", "readGeometry", "crs", "projection", "id", "properties", "writeGeometry", "isEmpty", "objects", "readPointGeometry", "readLineStringGeometry", "readPolygonGeometry", "readMultiPointGeometry", "readMultiLineStringGeometry", "readMultiPolygonGeometry", "readGeometryCollectionGeometry", "geometryObject", "flatCoordinates", "getLayoutForStride", "coordinates", "stride", "ends", "deflateCoordinatesArray", "endss", "deflateMultiCoordinatesArray", "transformGeometryWithOptions", "type", "geoJSON", "writePointGeometry", "writeLineStringGeometry", "writePolygonGeometry", "writeMultiPointGeometry", "writeMultiLineStringGeometry", "writeMultiPolygonGeometry", "writeGeometryCollectionGeometry", "right", "GeoJSON_default", "escapeHtml", "value", "layerProblemReason", "status", "initCreditsModal", "ctx", "openOverlay", "closeOverlay", "modal", "q", "role", "els", "shown", "current", "setStatus", "text", "tone", "labels", "render", "payload", "info", "isPayer", "plan", "payUrl", "cardUrl", "billing", "buyUrl", "plansUrl", "ownerLabel", "url", "apiFetch", "error", "message", "raw", "data", "reported", "renderLayerNotice", "box", "event", "onlyParts", "p", "heading", "reportSkippedParts", "itemId", "title", "skipped", "reasons", "problems", "layer", "skippedReasonText", "reportLayerProblems", "problem", "key", "TOAST_TONES", "toastContainer", "showToast", "options", "el", "timer", "close", "opts", "action", "timeout", "DRAWING_ITEM_ID", "DEFAULT_COLOR", "DEFAULT_WIDTH", "DEFAULT_SIZE", "DRAWING_STYLE_KEYS", "MAX_FIELD_NAME", "geojsonFormat", "GeoJSON_default", "hexToRgba", "hex", "alpha", "match", "num", "r", "g", "b", "featureStyle", "feature", "color", "DEFAULT_COLOR", "width", "DEFAULT_WIDTH", "size", "DEFAULT_SIZE", "label", "isText", "Style_default", "Stroke_default", "Fill_default", "Circle_default", "Text_default", "selectedStyle", "base", "sourceToGeoJSON", "source", "findDrawingEntry", "ctx", "flatLayers", "l", "createDrawingLayer", "saved", "forceNew", "existing", "Vector_default", "layer", "entry", "newUid", "DRAWING_ITEM_ID", "initialFields", "applyZoomLimits", "renderLayerTree", "type", "event", "adoptFeatureFields", "emit", "drawingAttributes", "out", "geometryName", "key", "value", "DRAWING_STYLE_KEYS", "fields", "add", "name", "drawingFieldError", "currentName", "trimmed", "lower", "f", "addDrawingField", "error", "field", "renameDrawingField", "oldName", "newName", "index", "removeDrawingField", "parseDrawingValue", "text", "raw", "setDrawingValue", "removeDrawingFeature", "restoreDrawingLayer", "drawingEntryFor", "uid", "findEntryByUid", "drawingFilename", "exportDrawingGeoJSON", "collection", "blob", "link", "canSaveDrawingToWorkspace", "saveDrawingToWorkspace", "onStatus", "filename", "workspaceApi", "plan", "apiFetch", "putResponse", "job", "pollBatchStatus", "url", "tries", "data", "resolve", "saveErrorText", "jsonStart", "TOOLS", "initDraw", "toolbarContainer", "isOpen", "activeTool", "drawInteraction", "selectInteraction", "modifyInteraction", "currentColor", "currentWidth", "currentSize", "entrySource", "removeDrawInteraction", "addEditInteractions", "Select_default", "click", "Modify_default", "removeEditInteractions", "activateTool", "toolKey", "renderToolbar", "options", "createBox", "Draw_default", "geometry", "fromCircle", "deleteSelected", "selected", "clearAll", "toolButtonClass", "active", "tool", "btn", "e", "applyToSelected", "close", "open", "tag", "on", "reason", "showToast", "toast", "WMTS", "TileImage_default", "options", "requestEncoding", "tileGrid", "urls", "expandUrl", "createFromTileUrlFunctions", "key", "res", "dimensions", "template", "context", "appendParams", "m", "p", "tileCoord", "pixelRatio", "projection", "localContext", "url", "WMTS_default", "optionsFromCapabilities", "wmtsCap", "config", "l", "elt", "tileMatrixSets", "idx", "supportedCRS", "el", "proj1", "get", "proj2", "equivalent", "matrixSet", "matrixLimits", "format", "style", "index", "array", "value", "matrixSetObj", "code", "projConfig", "wrapX", "switchXY", "matrix", "selectedMatrixLimit", "tileMatrixValue", "layerExtent", "bbox", "resolution", "origin", "tileSpanX", "tileSpanY", "matrixSetExtent", "extent", "containsExtent", "wgs84BoundingBox", "wgs84ProjectionExtent", "wgs84MatrixSetExtent", "transformExtent", "createFromCapabilitiesMatrixSet", "gets", "i", "ii", "encodings", "element", "NAMESPACE_URIS", "PARSERS", "makeStructureNS", "makeObjectPropertySetter", "readServiceIdentification", "readServiceProvider", "readOperationsMetadata", "OWS", "XML_default", "node", "owsObject", "pushParseAndPop", "ADDRESS_PARSERS", "readString", "ALLOWED_VALUES_PARSERS", "makeObjectPropertyPusher", "readValue", "CONSTRAINT_PARSERS", "readAllowedValues", "CONTACT_INFO_PARSERS", "readPhone", "readAddress", "DCP_PARSERS", "readHttp", "HTTP_PARSERS", "readGet", "OPERATION_PARSERS", "readDcp", "OPERATIONS_METADATA_PARSERS", "readOperation", "PHONE_PARSERS", "REQUEST_METHOD_PARSERS", "readConstraint", "SERVICE_CONTACT_PARSERS", "readContactInfo", "SERVICE_IDENTIFICATION_PARSERS", "SERVICE_PROVIDER_PARSERS", "readHref", "readServiceContact", "objectStack", "name", "href", "value", "object", "OWS_default", "NAMESPACE_URIS", "OWS_NAMESPACE_URIS", "PARSERS", "makeStructureNS", "makeObjectPropertySetter", "readContents", "WMTSCapabilities", "XML_default", "OWS_default", "node", "version", "WMTSCapabilityObject", "pushParseAndPop", "CONTENTS_PARSERS", "makeObjectPropertyPusher", "readLayer", "readTileMatrixSet", "LAYER_PARSERS", "readStyle", "readString", "readTileMatrixSetLink", "readDimensions", "readResourceUrl", "readBoundingBox", "readBoundingBoxWithCrs", "STYLE_PARSERS", "readLegendUrl", "TMS_LINKS_PARSERS", "readTileMatrixLimitsList", "TMS_LIMITS_LIST_PARSERS", "makeArrayPusher", "readTileMatrixLimits", "TMS_LIMITS_PARSERS", "readPositiveInteger", "DIMENSION_PARSERS", "WGS84_BBOX_READERS", "readCoordinates", "TMS_PARSERS", "readTileMatrix", "TM_PARSERS", "readDecimal", "objectStack", "style", "isDefault", "format", "template", "resourceType", "resource", "coordinates", "boundingExtent", "crs", "legend", "readHref", "x", "y", "WMTSCapabilities_default", "TextFeature", "Feature_default", "source", "options", "getText", "text", "abstract", "feature", "features", "geometry", "TextFeature_default", "GeometryConstructor", "Point_default", "LineString_default", "Polygon_default", "MultiPoint_default", "MultiLineString_default", "MultiPolygon_default", "EMPTY", "Z", "M", "ZM", "TokenType", "wktTypeLookup", "Lexer", "wkt", "c", "decimal", "position", "value", "type", "index", "scientificNotation", "Parser", "lexer", "isMatch", "layout", "dimToken", "dimInfo", "geometries", "coordinates", "dimensions", "i", "token", "isEmpty", "geomType", "GeometryCollection_default", "ctor", "WKT", "TextFeature_default", "options", "text", "geom", "feature", "Feature_default", "geometry", "features", "ii", "transformGeometryWithOptions", "collection", "encode", "encodePointGeometry", "encodeMultiPointGeometry", "array", "components", "encodeGeometryCollectionGeometry", "geoms", "encodeLineStringGeometry", "encodeMultiLineStringGeometry", "encodePolygonGeometry", "rings", "encodeMultiPolygonGeometry", "encodeGeometryLayout", "GeometryEncoder", "geometryEncoder", "enc", "wktType", "WKT_default", "EXTERNAL_TYPES", "isExternalType", "dataType", "LOCAL_DEFAULT_COLOR", "geojsonFormat", "GeoJSON_default", "externalCounter", "nextExternalId", "type", "corsAwareError", "error", "capabilitiesUrl", "serviceUrl", "service", "url", "has", "name", "k", "flattenWmsLayers", "layerNode", "acc", "node", "loadWmsCapabilities", "response", "text", "caps", "WMSCapabilities_default", "formats", "infoFormats", "layers", "loadWmtsCapabilities", "capsUrl", "WMTSCapabilities_default", "insertEntry", "ctx", "entry", "trackSourceLoading", "applyZoomLimits", "renderLayerTree", "emit", "baseEntry", "title", "saved", "newUid", "addExternalWmsLayer", "def", "source", "ImageWMS_default", "Image_default", "addXyzLayer", "XYZ_default", "Tile_default", "addWmtsLayer", "options", "optionsFromCapabilities", "WMTS_default", "hexToRgba", "hex", "alpha", "match", "num", "r", "g", "b", "localLayerStyle", "color", "Style_default", "Stroke_default", "Fill_default", "Circle_default", "parsePastedData", "crs", "trimmed", "json", "collection", "wktFormat", "WKT_default", "lines", "l", "features", "line", "geometry", "addLocalLayer", "Vector_default", "setLocalLayerColor", "restoreExternalLayer", "signedQuery", "params", "query", "key", "requestDescribe", "serviceUrl", "extra", "value", "response", "data", "describeCache", "renderingCache", "describeItem", "bootstrap", "detail", "promise", "error", "forgetDescription", "itemId", "cache", "describeRaster", "entry", "rasterParams", "name", "l", "sublayerFromDescribed", "layer", "predicted", "f", "isStyleAttribute", "nativeOf", "layers", "styled", "unionExtent", "extents", "valid", "e", "acc", "fromDescribed", "described", "out", "vectors", "b", "logical", "normalizeGeometryType", "fromPredicted", "logicalLayers", "layerDetail", "single", "raster", "drawingOrder", "logical", "rank", "layer", "geometries", "sub", "has", "word", "g", "index", "a", "b", "item", "itemLayerEntries", "detail", "createLayerEntry", "layerDetail", "SWATCH_W", "SWATCH_H", "esc", "value", "clamp", "min", "max", "isVeryLight", "color", "match", "n", "CONTRAST", "dashArray", "dash", "valid", "scale", "pointShape", "shape", "cx", "cy", "points", "i", "radius", "angle", "symbolSvg", "symbol", "width", "height", "open", "lineWidth", "casingColor", "casing", "opacity", "PHOTO_SYMBOL", "r", "ink", "outline", "cameraPolygonPoints", "hollow", "strokeWidth", "fill", "fillOpacity", "stroke", "hasFill", "lightFill", "hatch", "symbolFromRule", "geometry", "rule", "primaryGeometries", "entry", "present", "g", "combinedSvg", "symbols", "formatNumber", "abs", "MAX_ITEMS", "vectorLegend", "style", "geometries", "model", "items", "more", "legend", "item", "symbolsFor", "category", "ruleForCategory", "categories", "other", "cls", "rampColors", "rendering", "stop", "rasterLegend", "palette", "paletteSwatch", "names", "key", "rgbSwatch", "colors", "gradientSwatch", "gradientCss", "picked", "step", "stops", "legendModel", "legendHasBody", "legendBodyHtml", "limit", "expanded", "parts", "shown", "hidden", "canExpand", "channel", "COLLAPSE_GROUP_FROM", "mountEntry", "ctx", "entry", "list", "olLayer", "createWmsLayer", "applyZoomLimits", "updateRasterLegend", "missingLayerError", "title", "error", "legacyConfigFor", "saved", "logical", "attributes", "sub", "a", "conditions", "filterFits", "c", "addLayerByItemId", "itemId", "savedLayer", "options", "existing", "flatLayers", "l", "findEntryContainer", "pending", "beginPreparing", "renderLayerTree", "addPreparedLayer", "endPreparing", "prefetchItem", "fetchItemDetail", "detail", "describeItem", "updatePreparing", "sizeNote", "refreshPreparingRow", "described", "logicalLayers", "single", "restored", "restoreItemLayers", "emit", "entries", "itemLayerEntries", "result", "group", "createGroupEntry", "reportSkipped", "byKind", "kind", "layer", "target", "wantedKind", "createLayerEntry", "layerDetail", "layers", "reloadItemLayers", "forgetItemDetail", "forgetDescription", "reloaded", "sameKind", "container", "fresh", "serializeLayerEntry", "syncMapLayerOrder", "applyEffectiveVisibility", "item", "rasterLegendTimers", "rendering", "describeRaster", "rasterParams", "refreshLayerRow", "collection", "isEffectivelyVisible", "setLayerZoomLimits", "uid", "minZoom", "maxZoom", "findEntryByUid", "clamp", "updateScaleDimming", "removeLayer", "removeGroup", "setLayerVisibility", "visible", "setLayerOpacity", "opacity", "refreshOpacityBadge", "row", "slot", "opacityBadgeHtml", "wireOpacityBadge", "renameLayer", "moveEntry", "groupUid", "newIndex", "source", "targetList", "reorderEntry", "step", "index", "createGroup", "removeGroupWithLayers", "e", "duplicateLayer", "savedConfig", "copy", "createDrawingLayer", "restoreExternalLayer", "originalPos", "clearLayerFilter", "scheduleWmsRefresh", "zoomToLayer", "extents", "entryExtent", "zoomToExtent", "acc", "extent", "minx", "miny", "maxx", "maxy", "fromLonLat", "zoomToAllLayers", "merged", "openMenuEl", "closeKebabMenu", "event", "openKebabMenu", "button", "items", "menu", "btn", "rect", "menuRect", "typeIcon", "dataType", "HYBRID_ICON_PATHS", "externalBadge", "hasAttributeTable", "buildLayerMenuItems", "canZoom", "renameFromMenu", "parent", "g", "titleEl", "el", "startInlineRename", "buildGroupMenuItems", "child", "count", "ICON_CARET", "ICON_BRUSH", "ICON_KEBAB", "ICON_GRIP", "ICON_FILTER", "htmlEscape", "value", "percent", "renderLegend", "body", "model", "legendModel", "hasBody", "legendHasBody", "collapsed", "label", "inner", "legendBodyHtml", "badgeSlot", "layerRow", "parentGroup", "dimmed", "isEntryInZoomRange", "isFilterActive", "layerStatusHtml", "wireLayerStatus", "wireRowDrag", "updateLayerStatus", "state", "zoom", "handle", "draggedUid", "dragged", "toIndex", "input", "commit", "groupIcon", "groupRow", "wrapper", "header", "childrenBox", "preparingRow", "status", "emptyLayersHint", "box", "canUpload", "preparing", "offersSampleMaps", "renderSampleMapsHint", "getStylePanelContainer", "Property", "GeolocationErrorType", "GeolocationError", "Event_default", "error", "Geolocation", "Object_default", "options", "identityTransform", "projection", "getTransformFromProjections", "get", "tracking", "position", "coords", "toRadians", "projectedPosition", "geometry", "circular", "Geolocation_default", "ICON", "errorMessage", "error", "initLocate", "ctx", "position", "Feature_default", "Style_default", "Circle_default", "Fill_default", "Stroke_default", "accuracy", "layer", "Vector_default", "geolocation", "Geolocation_default", "element", "button", "active", "centred", "stop", "start", "coordinate", "Point_default", "view", "showToast", "Control_default", "SLOW_SECONDS", "SLOW_RENDERS", "READ_SHARE", "STORAGE_KEY", "POLL_MS", "readStore", "value", "writeStore", "store", "sessionDismissed", "isDismissed", "itemId", "dismiss", "ids", "a", "b", "id", "median", "values", "sorted", "assessEntry", "entry", "perf", "readShare", "times", "recent", "measuredSlow", "t", "slowItems", "ctx", "seen", "flatLayers", "verdict", "esc", "c", "formatSize", "bytes", "formatSeconds", "seconds", "formatCredits", "credits", "fmt", "v", "expected", "low", "high", "fileName", "formatName", "whyText", "facts", "after", "dialogEl", "closeDialog", "event", "running", "openDialog", "overlay", "q", "role", "offer", "errorEl", "convert", "showError", "text", "linkHtml", "close", "refreshHints", "target", "loadOffer", "query", "apiFetch", "showOffer", "info", "watch", "cost", "price", "targets", "formatHtml", "i", "saveCopy", "affordable", "creditsLink", "job", "startConversion", "error", "url", "href", "response", "getCookie", "data", "jobId", "name", "toast", "showToast", "failures", "tick", "status", "reloadItemLayers", "saved", "toasted", "hint", "updateLayerStatus", "maybeToast", "what", "initAdvisor", "on", "reason", "uid", "findEntryByUid", "e", "STYLE_FIELD", "GEOMETRIES", "POLL_MS", "OGR_SYMBOLS", "hex", "color", "opacity", "value", "base", "alpha", "px", "fallback", "number", "dashPattern", "dash", "parts", "n", "ogrSymbol", "geometry", "rule", "id", "outline", "width", "pen", "brush", "OGR_LABEL_ANCHORS", "labelTool", "labels", "halo", "bold", "place", "anchor", "angle", "styleSet", "style", "category", "out", "symbol", "ruleForCategory", "label", "styleRules", "attribute", "categories", "other", "cat", "classes", "cls", "sourceLayers", "entry", "names", "sub", "canSaveStyleToData", "ctx", "NATIVE_LIMITS", "LIMITS_BY_FORMAT", "storageText", "info", "format", "formatCredits", "credits", "fmt", "v", "expected", "low", "high", "creditsLink", "url", "href", "esc", "startCopy", "response", "getCookie", "data", "error", "waitForItems", "tries", "apiFetch", "resolve", "replaceLayerItem", "itemId", "findEntryContainer", "added", "addLayerByItemId", "renameLayer", "moveEntry", "removeLayer", "renderLayerTree", "running", "watch", "uid", "jobId", "name", "replace", "toast", "showToast", "failures", "fail", "text", "finish", "status", "items", "saveErrorText", "item", "current", "findEntryByUid", "title", "tick", "dialogEl", "closeDialog", "event", "c", "raw", "jsonStart", "openDialog", "overlay", "q", "role", "offer", "errorEl", "save", "showError", "linkHtml", "showOffer", "cost", "price", "affordable", "job", "initStyleExport", "on", "MOBILE_QUERY", "isMobileLayout", "isAvailable", "target", "initMobileMenu", "button", "menu", "close", "open", "item", "event", "openModalEl", "closeModal", "event", "esc", "value", "formatBytes", "bytes", "units", "exponent", "scaled", "formatCount", "formatDate", "iso", "date", "geometryLabel", "entry", "names", "list", "g", "text", "typeLabel", "labels", "metaRow", "label", "html", "title", "bandsLabel", "bands", "types", "b", "type", "crsLabel", "crs", "dataRows", "rows", "source", "sublayers", "counts", "sub", "a", "attributes", "shown", "more", "size", "count", "minx", "miny", "maxx", "maxy", "v", "openProperties", "ctx", "uid", "findEntryByUid", "overlay", "finish", "renderLayerTree", "e", "renameLayer", "opacityValue", "setLayerOpacity", "minInput", "maxInput", "applyZoomInputs", "minVal", "maxVal", "setLayerZoomLimits", "initProperties", "on", "reason", "xmlEscape", "value", "buildGetFeatureXml", "params", "filterXml", "typenames", "count", "startIndex", "srsName", "propertyName", "resultType", "outputFormat", "sortBy", "attrs", "propertyNames", "p", "sortProperties", "part", "name", "dir", "sortXml", "ENTITIES", "decodeXml", "text", "match", "code", "point", "parseValueCollection", "xmlText", "values", "memberRe", "member", "inner", "element", "raw", "cdata", "owsExceptionText", "parseFeatureCollection", "features", "wrapper", "body", "properties", "itemRe", "item", "tag", "DEFAULT_PAGE_SIZE", "VALUE_PAGE_SIZE", "VALUE_READ_LIMIT", "baseParams", "entry", "signedParams", "buildUrl", "bootstrap", "params", "usp", "failure", "response", "what", "detail", "owsExceptionText", "error", "requestGeoJson", "filterXml", "url", "buildGetFeatureXml", "parseNumberMatched", "xmlText", "match", "fetchFeaturesPage", "typename", "options", "count", "startIndex", "propertyName", "sortBy", "srsName", "GML_FORMAT", "fetchAttributesPage", "attributes", "text", "exception", "parseFeatureCollection", "fetchHits", "fetchPropertyValues", "attribute", "parseValueCollection", "scanValues", "limit", "onValue", "read", "page", "value", "fetchValueCounts", "counts", "truncated", "notNullNumberFilter", "xmlEscape", "toNumber", "number", "fetchMinMax", "minPage", "maxPage", "min", "max", "values", "fetchNumericValues", "a", "b", "COLOR_RAMPS", "getRamp", "key", "r", "listRamps", "kind", "hexToRgb", "hex", "clean", "i", "rgbToHex", "g", "b", "v", "clamp01", "value", "interpolate", "stops", "t", "scaled", "i0", "i1", "frac", "c0", "c1", "c", "getRampColors", "rampKey", "count", "ramp", "_", "rampPreviewGradient", "CLASSIFICATION_METHODS", "sortedNumbers", "values", "v", "a", "b", "breaksToClasses", "breaks", "classes", "i", "equalIntervalClasses", "classCount", "sorted", "min", "max", "step", "_", "quantileClasses", "percentile", "p", "idx", "lo", "hi", "sampleSorted", "size", "jenksBreaks", "data", "n", "lowerClassLimits", "varianceCombinations", "j", "variance", "sum", "sumSquares", "w", "m", "lowerClassLimit", "value", "i4", "k", "countNum", "firstOfClass", "jenksClasses", "unique", "dropEmptyClasses", "cls", "classify", "method", "isNumeric", "sortCategoryValues", "list", "collator", "pickCategories", "counts", "entries", "chosen", "formatClassLabel", "fmt", "MAX_CATEGORIES", "colorInput", "label", "value", "onInput", "wrap", "e", "rangeInput", "min", "max", "step", "formatter", "fmt", "v", "input", "valueEl", "selectInput", "options", "onChange", "optionsHtml", "checkboxInput", "checked", "textInput", "placeholder", "extraClass", "numberInput", "removeButton", "onClick", "button", "sectionTitle", "text", "el", "uniqueAttributes", "entry", "attributes", "s", "a", "NUMERIC_TYPE_HINTS", "numericAttributes", "hint", "sublayersWithAttribute", "attribute", "dashOptions", "current", "o", "pointSection", "ctx", "onAnyChange", "isClassified", "rule", "box", "PHOTO_SYMBOL", "PHOTO_MIN_SIZE", "PHOTO_SIZE", "renderStylePanel", "note", "sub", "photoFieldOf", "lineSection", "polygonSection", "modeSwitcher", "nativeSection", "fromAttribute", "opacitySection", "setLayerOpacity", "categoryRow", "category", "categories", "index", "row", "categoriesList", "cat", "addBtn", "rememberClassifyNote", "section", "warn", "classifyNoteElement", "status", "shown", "classifyButton", "statusEl", "error", "categorizedSection", "classifyBtn", "preview", "rampPreviewGradient", "rampRow", "listRamps", "r", "typenames", "results", "name", "fetchValueCounts", "counts", "n", "sampled", "picked", "pickCategories", "colors", "getRampColors", "i", "from", "VALUE_READ_LIMIT", "classRow", "cls", "classes", "classesList", "grad", "last", "formatClassLabel", "graduatedSection", "CLASSIFICATION_METHODS", "truncated", "minMax", "fetchMinMax", "mins", "maxs", "classify", "fetchNumericValues", "values", "c", "fewer", "segmented", "option", "active", "labeledRow", "control", "POSITION_TITLES", "positionPicker", "grid", "LABEL_POSITIONS", "position", "cell", "WAVE", "LINE_ICON", "inner", "LINE_MODE_OPTIONS", "labelsSection", "labels", "change", "rerender", "head", "labelFieldOf", "select", "font", "sizes", "size", "b", "sizeSelect", "geometries", "rotation", "auto", "entryAutoLabelMinZoom", "zoomValue", "_", "bandLabel", "band", "interp", "type", "colormapPreview", "COLORMAP_LABELS", "rasterSection", "style", "bandList", "bandOptions", "hasPalette", "colormaps", "modes", "m", "names", "allByte", "stretchOptions", "stretchValue", "scale", "inputs", "apply", "minInput", "maxInput", "transparentValueRow", "container", "getStylePanelContainer", "scheduleWmsRefresh", "refreshLayerRow", "updateRasterLegend", "emit", "setLocalLayerColor", "reset", "applyDefaultLabels", "applyPhotoMarker", "normalizeVectorStyle", "styleFromSuggestions", "toggleStylePanel", "uid", "open", "findEntryByUid", "escapeHtml", "value", "dialog", "photos", "index", "ensureDialog", "image", "show", "event", "button", "next", "photo", "original", "many", "openGallery", "items", "start", "thumbs", "escapeHtml", "entries", "Object", "objectKeys", "keys", "setPrototypeOf", "isFrozen", "getPrototypeOf", "getOwnPropertyDescriptor", "freeze", "seal", "create", "_ref", "Reflect", "apply", "construct", "x", "func", "thisArg", "_len", "arguments", "length", "args", "Array", "_key", "Func", "_len2", "_key2", "arrayForEach", "unapply", "prototype", "forEach", "arrayLastIndexOf", "lastIndexOf", "arrayPop", "pop", "arrayPush", "push", "arraySlice", "slice", "arraySplice", "splice", "arrayIsArray", "isArray", "setCreate", "unconstruct", "Set", "setAdd", "add", "setHas", "has", "stringToLowerCase", "String", "toLowerCase", "stringToString", "toString", "stringMatch", "match", "stringReplace", "replace", "stringIndexOf", "indexOf", "stringTrim", "trim", "numberToString", "Number", "booleanToString", "Boolean", "bigintToString", "BigInt", "symbolToString", "Symbol", "objectHasOwnProperty", "hasOwnProperty", "objectToString", "regExpTestRaw", "RegExp", "test", "regExpTest", "regExp", "value", "lastIndex", "typeErrorCreate", "TypeError", "_len3", "_key3", "_len4", "_key4", "addToSet", "set", "array", "transformCaseFunc", "undefined", "l", "element", "lcElement", "cleanArray", "index", "isPropertyExist", "clone", "object", "newObject", "_ref2", "_ref3", "_slicedToArray", "property", "constructor", "cloneSet", "newSet", "stringifyValue", "valueAsRecord", "valueToString", "lookupGetter", "stringified", "prop", "desc", "get", "fallbackValue", "lookupAccessor", "isRegex", "html", "svg", "svgFilters", "svgDisallowed", "mathMl", "mathMlDisallowed", "text", "xml", "MUSTACHE_EXPR", "ERB_EXPR", "TMPLIT_EXPR", "TMPL_MARKER_SERIALIZED", "DATA_ATTR", "ARIA_ATTR", "IS_ALLOWED_URI", "IS_SCRIPT_OR_DATA", "ATTR_WHITESPACE", "DOCTYPE_NAME", "CUSTOM_ELEMENT", "ELEMENT_MARKUP_PROBE", "COMMENT_MARKUP_PROBE", "FALLBACK_TAG_CLOSE", "SELF_CLOSING_TAG", "ATTR_VALUE_BREAKOUT", "LEADING_WHITESPACE", "NODE_TYPE", "processingInstruction", "comment", "document", "documentFragment", "LITERAL_TEXT_ELEMENTS", "LITERAL_TEXT_ELEMENT_NAMES", "getGlobal", "window", "_createTrustedTypesPolicy", "trustedTypes", "purifyHostElement", "createPolicy", "suffix", "ATTR_NAME", "hasAttribute", "getAttribute", "policyName", "createHTML", "createScriptURL", "scriptUrl", "console", "warn", "_createHooksMap", "afterSanitizeAttributes", "afterSanitizeElements", "afterSanitizeShadowDOM", "beforeSanitizeAttributes", "beforeSanitizeElements", "beforeSanitizeShadowDOM", "uponSanitizeAttribute", "uponSanitizeElement", "uponSanitizeShadowNode", "_resolveSetOption", "cfg", "key", "fallback", "options", "base", "transform", "_resolveObjectOption", "createDOMPurify", "DOMPurify", "root", "version", "removed", "nodeType", "Element", "isSupported", "originalDocument", "currentScript", "HTMLTemplateElement", "Node", "NodeFilter", "DOMParser", "ElementPrototype", "cloneNode", "remove", "removeAttributeNode", "getNextSibling", "getChildNodes", "getParentNode", "getShadowRoot", "getAttributes", "getNodeType", "getNodeName", "getOwnerDocument", "_readNodeType", "node", "_readNodeName", "nodeName", "getNamespaceURI", "_readNamespaceURI", "namespaceURI", "template", "createElement", "content", "ownerDocument", "trustedTypesPolicy", "emptyHTML", "defaultTrustedTypesPolicy", "defaultTrustedTypesPolicyResolved", "IN_TRUSTED_TYPES_POLICY", "_assertNotInTrustedTypesPolicy", "_createTrustedHTML", "_signOutput", "RETURN_TRUSTED_TYPE", "_createTrustedScriptURL", "_getDefaultTrustedTypesPolicy", "_document", "implementation", "createNodeIterator", "createDocumentFragment", "getElementsByTagName", "importNode", "hooks", "createHTMLDocument", "EXPRESSIONS", "ALLOWED_TAGS", "DEFAULT_ALLOWED_TAGS", "TAGS", "ALLOWED_ATTR", "DEFAULT_ALLOWED_ATTR", "ATTRS", "CUSTOM_ELEMENT_HANDLING", "FORBID_TAGS", "FORBID_ATTR", "EXTRA_ELEMENT_HANDLING", "tagCheck", "writable", "configurable", "enumerable", "attributeCheck", "ALLOW_ARIA_ATTR", "ALLOW_DATA_ATTR", "ALLOW_UNKNOWN_PROTOCOLS", "ALLOW_SELF_CLOSE_IN_ATTR", "SAFE_FOR_TEMPLATES", "SAFE_FOR_XML", "WHOLE_DOCUMENT", "SET_CONFIG", "SET_CONFIG_ALLOWED_TAGS", "SET_CONFIG_ALLOWED_ATTR", "FORCE_BODY", "RETURN_DOM", "RETURN_DOM_FRAGMENT", "SANITIZE_DOM", "SANITIZE_NAMED_PROPS", "SANITIZE_NAMED_PROPS_PREFIX", "KEEP_CONTENT", "IN_PLACE", "IN_PLACE_VISITED", "USE_PROFILES", "FORBID_CONTENTS", "DEFAULT_FORBID_CONTENTS", "DATA_URI_TAGS", "DEFAULT_DATA_URI_TAGS", "URI_SAFE_ATTRIBUTES", "DEFAULT_URI_SAFE_ATTRIBUTES", "MATHML_NAMESPACE", "SVG_NAMESPACE", "HTML_NAMESPACE", "NAMESPACE", "IS_EMPTY_INPUT", "ALLOWED_NAMESPACES", "DEFAULT_ALLOWED_NAMESPACES", "DEFAULT_MATHML_TEXT_INTEGRATION_POINTS", "MATHML_TEXT_INTEGRATION_POINTS", "DEFAULT_HTML_INTEGRATION_POINTS", "HTML_INTEGRATION_POINTS", "DEFAULT_CUSTOM_ELEMENT_HANDLING", "COMMON_SVG_AND_HTML_ELEMENTS", "PARSER_MEDIA_TYPE", "SUPPORTED_PARSER_MEDIA_TYPES", "DEFAULT_PARSER_MEDIA_TYPE", "CONFIG", "formElement", "isRegexOrFunction", "testValue", "Function", "_parseConfig", "ALLOWED_URI_REGEXP", "customElementHandling", "tagNameCheck", "attributeNameCheck", "allowCustomizedBuiltInElements", "ADD_TAGS", "ADD_ATTR", "ADD_FORBID_CONTENTS", "table", "tbody", "TRUSTED_TYPES_POLICY", "previousTrustedTypesPolicy", "error", "ALL_SVG_TAGS", "ALL_MATHML_TAGS", "_checkSvgNamespace", "tagName", "parentNamespace", "parentTagName", "_checkMathMlNamespace", "_checkHtmlNamespace", "_checkValidNamespace", "elementNamespace", "parentNode", "_forceRemove", "removeChild", "_stripAttributeNode", "attribute", "name", "removeAttribute", "_neutralizeRoot", "_neutralizeSubtree", "childNodes", "child", "_stripAttributes", "_removeAttribute", "attr", "getAttributeNode", "from", "setAttribute", "keepAllowed", "attributes", "i", "_walkTree", "visit", "intoShadow", "stack", "shadowRoot", "_isDocumentFragment", "_collectLiveNodes", "nodes", "_neutralizeEscapedElements", "before", "reachable", "_neutralizeDiscarded", "rootRemoved", "entry", "MAX_UNVISITED_ROUNDS", "_sanitizeUnvisitedNodes", "visited", "original", "getOriginal", "beforeNode", "round", "live", "containers", "pending", "container", "_sanitizeUnvisitedIn", "inShadow", "iterator", "_createNodeIterator", "nextNode", "_executeHooks", "_sanitizeNode", "_markVisited", "_isPatchLinkageAttribute", "lcName", "lcTag", "_neutralizePatchLinkage", "data", "_initDocument", "dirty", "doc", "leadingWhitespace", "matches", "dirtyPayload", "parseFromString", "documentElement", "createDocument", "innerHTML", "body", "insertBefore", "createTextNode", "call", "characterDataOnly", "SHOW_ELEMENT", "SHOW_COMMENT", "SHOW_TEXT", "SHOW_PROCESSING_INSTRUCTION", "SHOW_CDATA_SECTION", "_stripTemplateExpressions", "_scrubTemplateExpressions", "_node$querySelectorAl", "_scrubOwnCharacterData", "templates", "querySelectorAll", "tmpl", "normalize", "walker", "currentNode", "_isClobbered", "realTagName", "textContent", "hasChildNodes", "_nodeTypeOf", "_isNode", "hook", "_isUnsafeNode", "firstElementChild", "_matchesNameCheck", "check", "_sanitizeDisallowedNode", "_isBasicCustomElement", "childCount", "hoisted", "_forkSharedAllowlist", "hookList", "defaultSet", "setConfigSet", "_handleHookDetachedNode", "_sanitizeElements", "allowedTags", "_isValidAttribute", "nameIsPermitted", "compactValue", "RESERVED_CUSTOM_ELEMENT_NAMES", "_applyTrustedTypesToAttribute", "getAttributeType", "_setAttributeValue", "setAttributeNS", "_isUnsafeAttributeValue", "_sanitizeAttributes", "hookEvent", "attrName", "attrValue", "keepAttr", "allowedAttributes", "forceKeepAttr", "initValue", "recreatedNamedProp", "cleanWrite", "_sanitizeShadowDOM", "fragment", "shadowNode", "shadowIterator", "innerSr", "_sanitizeAttachedShadowRoots", "shadow", "item", "isElement", "rootName", "sr", "sanitize", "importedNode", "returnNode", "inPlace", "inPlaceNodes", "outerVisited", "nn", "appendChild", "firstChild", "walkRoot", "nodeIterator", "shadowroot", "shadowrootmode", "serialize", "outerHTML", "serializedHTML", "doctype", "setConfig", "clearConfig", "isValidAttribute", "tag", "addHook", "entryPoint", "hookFunction", "removeHook", "removeHooks", "removeAllHooks", "purify_default", "ALLOWED_TAGS", "ALLOWED_ATTR", "SAFE_LINK_RE", "SAFE_IMAGE_RE", "purifier", "currentResolveImage", "currentImages", "getPurifier", "purify_default", "node", "tag", "href", "resolved", "src", "safe", "sanitizeHtml", "html", "resolveImage", "purify", "esc", "value", "formatRasterNumber", "number", "formatLonLat", "coordinates", "lon", "lat", "ns", "ew", "formatPixel", "props", "x", "y", "unit", "degrees", "mx", "my", "RGB_NAMES", "hex", "rgbBands", "bands", "found", "band", "key", "scaleOf", "entry", "style", "rendering", "scale", "colors", "stop", "paletteClass", "item", "p", "rasterCardModel", "rows", "model", "palette", "className", "position", "rgb", "color", "shown", "chipOf", "largest", "where", "pixel", "CHIP_CLASS", "rasterCardBodyHtml", "parts", "min", "max", "chips", "INFO_FORMAT", "queryableLayers", "state", "flatLayers", "l", "isEffectivelyVisible", "externalQueryableLayers", "stripUnneededParams", "url", "parsed", "fetchSublayerFeatureInfo", "entry", "sublayerName", "map", "coordinate", "view", "response", "feature", "fetchFeatureInfo", "names", "name", "r", "fetchExternalFeatureInfo", "html", "geojsonFormat", "GeoJSON_default", "HIT_TOLERANCE", "clientFeaturesAtPixel", "ctx", "pixel", "entries", "byLayer", "found", "seen", "layer", "isDrawing", "properties", "drawingAttributes", "geometry", "getUid", "valueHtml", "key", "value", "kind", "text", "escapeHtml", "shortUrl", "createPopup", "element", "overlay", "Overlay_default", "ICON_CLOSE", "ICON_PHOTO", "ICON_ZOOM", "ICON_EXPAND", "ICON_CHEVRON", "footerHtml", "features", "index", "pager", "POPUP_BOX", "renderFeature", "container", "mapId", "resolveImage", "path", "relative", "relativeImagePath", "mediaUrl", "isStyleAttribute", "title", "titleOf", "photos", "seenPhotos", "addPhoto", "src", "caption", "rows", "empty", "rich", "longest", "kindOf", "photo", "photosOf", "sanitized", "item", "fragment", "images", "sanitizeHtml", "image", "others", "k", "v", "repeatsOtherValues", "htmlText", "wideHtml", "width", "popupWidth", "i", "close", "hero", "head", "attrRows", "emptyRows", "nothing", "emptyToggle", "richSections", "sectionTitle", "editBar", "img", "at", "event", "renderPopupContent", "renderRaster", "model", "rasterCardModel", "swatch", "rasterCardBodyHtml", "popupMaxHeight", "box", "viewport", "base", "fitPopupHeight", "natural", "clamp", "more", "initIdentify", "popupElement", "dismissTimer", "clearDismissTimer", "hidePopup", "expanded", "wireFeatureControls", "button", "openGallery", "row", "details", "current", "rerender", "emit", "clickSeq", "clientFeatures", "layers", "externalLayers", "seq", "results", "INPUT_CLASS", "conditionRow", "condition", "index", "working", "attributes", "rerender", "row", "attrSelect", "name", "e", "opDef", "FILTER_OPERATORS", "o", "opSelect", "valueInput", "andLabel", "value2Input", "removeBtn", "renderFilterBuilder", "container", "options", "filter", "onApply", "onClear", "emptyFilter", "wrap", "logicRow", "logicSelect", "buttonsRow", "addBtn", "emptyCondition", "spacer", "clearBtn", "applyBtn", "PAGE_SIZE", "PAGE_BYTES_BUDGET", "TEXT_TYPE_HINTS", "panel", "geojsonFormat", "GeoJSON_default", "HIGHLIGHT_COLOR", "highlightLayer", "getHighlightLayer", "ctx", "stroke", "Stroke_default", "fill", "Fill_default", "Vector_default", "Style_default", "Circle_default", "rowGeometry", "row", "highlightOnMap", "layer", "geometry", "Feature_default", "ensureRowGeometry", "entry", "typename", "query", "fetchFeaturesPage", "page", "error", "renderStatus", "heavyGeometries", "size", "layers", "features", "sum", "own", "clearHighlight", "updateRowHighlight", "zoomToRow", "zoomToExtent", "activeSublayer", "s", "textAttributeNames", "a", "hint", "currentFilterXml", "buildFilterXml", "loadWfsPage", "seq", "filterXml", "sortBy", "startIndex", "attributesOnly", "withGeometry", "feature", "attributes", "fetchAttributesPage", "rows", "total", "fetchHits", "position", "renderTable", "localProperties", "drawingAttributes", "properties", "compareValues", "b", "dir", "emptyA", "emptyB", "numA", "numB", "result", "loadLocalPage", "source", "getUid", "names", "name", "needle", "value", "attribute", "lastPage", "loadPage", "panelElement", "htmlEscape", "cellText", "el", "tr", "selectRow", "scroll", "from", "to", "summary", "note", "pager", "sortIndicator", "ICON_ZOOM", "ICON_TRASH", "ICON_PENCIL", "ICON_X", "TH_CLASS", "FILLER_CELL", "shapeLabel", "type", "headerCell", "label", "valueCell", "text", "actionCell", "emptyStateText", "container", "columns", "local", "leadHeaders", "headers", "cells", "shape", "columnCount", "noColumnsHint", "button", "startColumnRename", "removeColumn", "findRow", "f", "event", "removeDrawingFeature", "input", "commitCell", "applyFocus", "setDrawingValue", "setColumnError", "renderAddColumn", "area", "form", "cancel", "addDrawingField", "th", "done", "finish", "commit", "drawingFieldError", "renameDrawingField", "used", "removeDrawingField", "renderFilterArea", "open", "renderFilterBuilder", "filter", "onFilterChanged", "scheduleWmsRefresh", "renderLayerTree", "renderShell", "wfs", "sublayers", "sublayerSwitcher", "editableBadge", "closeAttrTable", "e", "onSearch", "debounce", "wireResizeHandle", "handle", "startY", "startHeight", "onMove", "height", "onUp", "isOpenFor", "uid", "openAttrTable", "focusFeatureId", "findEntryByUid", "hasAttributeTable", "onIdentifyFeature", "itemId", "featureId", "initAttrTable", "on", "keepOpen", "reason", "title", "reloadDrawing", "active", "FINISH_GUARD_MS", "measureStyle", "Style_default", "Fill_default", "Stroke_default", "Circle_default", "formatLength", "meters", "formatArea", "squareMeters", "TOOL_LABELS", "isTouchDevice", "initMeasure", "ctx", "source", "Vector_default", "layer", "draw", "activeType", "liveTooltip", "sketchListener", "sketchFeature", "guardTimer", "hintEl", "measurements", "hintText", "type", "touch", "canFinish", "geometry", "updateHint", "finishBtn", "showHint", "hideHint", "cancel", "createLiveTooltip", "el", "overlay", "Overlay_default", "removeLiveTooltip", "removeMeasurement", "record", "index", "emit", "addStaticLabel", "feature", "text", "position", "value", "remove", "releaseMap", "deactivate", "guard", "unByKey", "wasActive", "dblKey", "activate", "Draw_default", "event", "anchor", "getArea", "getLength", "isArea", "clear", "safeFilename", "title", "extension", "downloadCanvas", "canvas", "filename", "mime", "quality", "resolve", "reject", "trigger", "href", "revoke", "link", "blob", "error", "composeMapCanvas", "map", "backgroundColor", "size", "context", "layerCanvas", "parent", "opacity", "transform", "match", "matrix", "filter", "exportMapImage", "ctx", "format", "isJpeg", "PRESENT_CLASS", "initPresentMode", "ctx", "button", "exitButton", "active", "apply", "enter", "exit", "event", "DROPPED_PARAMS", "EXTERNAL_TYPES", "zoom", "value", "common", "entry", "cleanParams", "params", "out", "key", "buildRenderSpec", "state", "paramsFor", "seen", "uniqueKey", "count", "leaf", "path", "base", "layers", "i", "children", "child", "j", "node", "config", "LEGACY_AUTOSAVE_PREFIX", "buildCurrentConfig", "ctx", "view", "readViewConfig", "basemapKey", "layer", "config", "serializeConfig", "layerConfig", "groupTitle", "group", "l", "cleanupLegacyAutosave", "storage", "keys", "i", "key", "saveMap", "asNew", "title", "description", "quiet", "firstSave", "body", "buildRenderSpec", "buildWmsParams", "result", "apiFetch", "path", "emit", "captureAndUploadThumbnail", "THUMBNAIL_MAX_DIM", "mapId", "uploaded", "capture", "full", "composeMapCanvas", "dataUrl", "downscaleCanvas", "source", "maxDim", "longest", "scale", "out", "context", "esc", "value", "errorText", "error", "fallback", "raw", "start", "data", "ICON_COPY", "ICON_OPEN", "ICON_CHEVRON", "BUTTON", "NEW_KEY", "urlRow", "label", "url", "open", "hint", "toggle", "on", "initServiceTab", "ctx", "container", "busy", "moreOpen", "creating", "message", "apiUrl", "load", "apiFetch", "render", "update", "body", "createKey", "form", "planCard", "publishRow", "enabled", "keyForm", "title", "first", "keySelect", "options", "key", "create", "layerTable", "service", "layer", "row", "settings", "chips", "code", "extra", "loginBlock", "login", "omitted", "items", "o", "published", "urls", "parts", "per", "event", "copy", "action", "removeCrs", "apiErrorMessage", "error", "fallback", "raw", "jsonStart", "data", "isNotFoundError", "show", "el", "hide", "escapeHtml", "value", "consumePermalinkView", "params", "query", "parts", "v", "lon", "lat", "zoom", "applyPermalinkView", "map", "view", "olView", "fromLonLat", "buildShareUrl", "ctx", "includeView", "viewerBase", "base", "readViewConfig", "applyReadOnlyMode", "elements", "sample", "badge", "svg", "lock", "unlock", "on", "applySharedView", "shared", "initShare", "openOverlay", "closeOverlay", "els", "modal", "modeRadios", "isOwner", "shares", "tabs", "wmsPanel", "serviceTab", "initServiceTab", "activeTab", "selectTab", "name", "button", "showTabs", "visible", "event", "updateButtonVisibility", "updateUrlField", "setModeRadios", "mode", "radio", "renderTeam", "team", "others", "teamState", "syncTeamEditors", "renderCredits", "credits", "balance", "images", "per", "link", "members", "editors", "limited", "saveTeamShare", "permission", "apiFetch", "showError", "renderShares", "share", "message", "refresh", "roleText", "renderSlowLayers", "slow", "slowItems", "esc", "c", "rows", "entry", "verdict", "emit", "setup", "body", "setupEls", "needsAccount", "needsSetup", "showSetup", "anonymous", "showBody", "setSetupBusy", "busy", "saveQuietly", "saveMap", "saveAndShare", "title", "continueWithAccount", "signup", "loginBase", "url", "original", "email", "select", "shareId", "s", "updated", "setWindowName", "parseAddParam", "raw", "s", "looksLikeUuid", "initMessaging", "bootstrap", "onAddItems", "allowedOrigins", "event", "data", "target", "addFromUrl", "cachedItems", "FILTER_TYPES", "invalidateItems", "loadItems", "ctx", "apiFetch", "typeBadge", "item", "geoms", "placeholderIcon", "HYBRID_ICON_PATHS", "itemCard", "onAdd", "card", "applyFilter", "items", "filter", "search", "q", "initSampleData", "modal", "tab", "list", "searchInput", "render", "error", "filtered", "e", "initAddDataModal", "elements", "renderList", "text", "btn", "b", "getCookie", "name", "row", "r", "statusMessage", "status", "responseErrorMessage", "data", "parts", "reportError", "message", "context", "humanBytes", "u", "i", "v", "humanTime", "s", "m", "sec", "uid", "S3Uploader", "opts", "getCookie", "name", "arg", "fileList", "added", "file", "entry", "id", "idx", "e", "total", "done", "elapsed", "inst", "remaining", "url", "body", "self", "attempt", "tryOnce", "err", "r", "resolve", "reject", "xhr", "data", "responseErrorMessage", "blob", "contentType", "onDelta", "last", "plan", "reportError", "partSize", "partCount", "numbers", "resp", "urls", "parts", "next", "worker", "pn", "start", "etag", "workers", "n", "counted", "delta", "queue", "nextFile", "failed", "sortUploadedItems", "items", "ready", "needsCrs", "notMappable", "item", "uploadLabel", "files", "list", "POLL_LIMIT_MS", "droppedFiles", "dataTransfer", "files", "folders", "items", "item", "file", "hasFiles", "event", "errorText", "error", "raw", "start", "data", "sleep", "ms", "resolve", "crsDialogPromise", "loadCrsDialog", "ctx", "reject", "src", "script", "initMapUpload", "onItemsReady", "beforeUpload", "dropTarget", "bootstrap", "enabled", "signedIn", "workspaceApi", "workspaceUploadUrl", "active", "startRow", "label", "status", "row", "beginPreparing", "updatePreparing", "renderLayerTree", "setStatus", "refreshPreparingRow", "stopRow", "endPreparing", "input", "upload", "askToSignIn", "showToast", "pick", "waitForAnalysis", "jobId", "started", "delay", "apiFetch", "seconds", "assignCrs", "titles", "later", "dialog", "value", "assignments", "ids", "finish", "result", "report", "ready", "needsCrs", "notMappable", "sortUploadedItems", "message", "auto", "code", "fileList", "uploadLabel", "total", "sum", "humanBytes", "outcome", "uploader", "S3Uploader", "p", "reason", "job", "quotaFull", "depth", "show", "on", "setError", "el", "message", "setLoading", "button", "loading", "loadingText", "zoomToBbox", "ctx", "bbox", "extent", "fromLonLat", "zoomToExtent", "zoomToSource", "source", "initWmsTab", "root", "closeModal", "urlInput", "loadButton", "errorEl", "listEl", "addButton", "capabilities", "renderLayerList", "layer", "index", "row", "url", "loadWmsCapabilities", "error", "checked", "infoFormat", "f", "lastEntry", "input", "addExternalWmsLayer", "initTileTab", "kindInputs", "xyzSection", "wmtsSection", "xyzUrlInput", "xyzTitleInput", "xyzAddButton", "wmtsUrlInput", "wmtsLoadButton", "wmtsSelect", "wmtsAddButton", "wmtsData", "isXyz", "addXyzLayer", "loadWmtsCapabilities", "l", "i", "entry", "addWmtsLayer", "initPasteTab", "textarea", "titleInput", "crsSelect", "geojson", "parsePastedData", "addLocalLayer", "initUrlTab", "response", "fetchError", "text", "fileName", "initExternalSources", "modal", "tabs", "panels", "tab", "t", "p", "byTab", "name", "DEFAULT_TITLE", "hasContent", "ctx", "flatLayers", "internalNavigationTarget", "event", "link", "target", "rawHref", "url", "initUnsavedGuard", "openOverlay", "closeOverlay", "modal", "q", "role", "els", "discarded", "bypass", "pending", "beforeUnloadRegistered", "needsGuard", "onBeforeUnload", "syncBeforeUnload", "want", "on", "canSaveInPlace", "hasRealTitle", "title", "loginUrlFor", "base", "viewerBase", "next", "showError", "message", "openModal", "copy", "needsTitle", "anonymous", "proceed", "onSave", "saveMap", "error", "guardNavigation", "href", "escapeHtml", "value", "normalize", "text", "formatDate", "iso", "date", "MAP_ICON", "initOpenMapDialog", "ctx", "button", "openOverlay", "closeOverlay", "guard", "modal", "q", "role", "els", "data", "samples", "viewerBase", "mapUrl", "id", "link", "renderList", "container", "maps", "shared", "term", "items", "m", "a", "b", "empty", "current", "meta", "renderSamples", "loadSamples", "loadSampleMaps", "render", "load", "result", "apiFetch", "error", "event", "item", "url", "go", "VIEW_ONLY_REASONS", "readBootstrap", "el", "queryElements", "setSaveStatus", "elements", "text", "openOverlay", "closeOverlay", "backdrop", "restoreSingleLayer", "ctx", "saved", "restoreDrawingLayer", "isExternalType", "restoreExternalLayer", "addLayerByItemId", "layerProblem", "error", "rememberUnloaded", "groupTitle", "status", "savedWorkspaceLayers", "savedLayers", "bootstrapLayers", "problems", "workspaceLayers", "beginPreparing", "renderLayerTree", "itemId", "prefetchItem", "group", "createGroupEntry", "child", "restored", "entry", "moveEntry", "endPreparing", "reportLayerProblems", "handleAddItems", "itemIds", "titles", "zoomToAllLayers", "ADD_DATA_CTA", "ADD_DATA_PLAIN", "syncAddDataCta", "button", "empty", "cls", "wireTopBar", "doSave", "asNew", "saveMap", "omits", "note", "event", "createGroup", "wireTools", "measure", "initMeasure", "draw", "initDraw", "doExport", "format", "exportMapImage", "initPresentMode", "wireBasemapSwitcher", "containers", "render", "key", "container", "renderBasemapSwitcher", "onChange", "onLookChange", "setBasemap", "look", "normalizeBasemapLook", "applyBasemapLook", "syncBasemapLookControls", "activeKey", "layer", "startSignatureWatcher", "flatLayers", "refreshSignatureIfNeeded", "pruneOmittedLayers", "savedMap", "omittedLayers", "keep", "l", "removed", "removeLayer", "config", "wireSidebar", "sidebar", "sidebarToggle", "sidebarClose", "sidebarOverlay", "sidebarResizer", "openSidebar", "closeSidebar", "on", "isMobileLayout", "isResizing", "e", "handleMouseMove", "stopResizing", "newWidth", "main", "bootstrap", "initMobileMenu", "state", "createState", "permalinkView", "consumePermalinkView", "basemaps", "createBasemaps", "map", "createMap", "addStandardControls", "cleanupLegacyAutosave", "initShare", "applyReadOnlyMode", "applySharedView", "guard", "initUnsavedGuard", "initOpenMapDialog", "newMap", "uid", "row", "open", "toggleStylePanel", "showCreditsModal", "initCreditsModal", "payload", "reason", "firstSave", "quiet", "message", "showToast", "skipped", "findEntryContainer", "reportSkippedParts", "initProperties", "initLoadingIndicator", "initLocate", "initAdvisor", "initStyleExport", "updateLayerStatus", "dimOnZoom", "debounce", "updateScaleDimming", "initAddDataModal", "title", "item", "initSampleData", "initExternalSources", "uploads", "initMapUpload", "invalidateItems", "initIdentify", "initAttrTable", "applyPermalinkView", "initMessaging"]
}
