diff --git a/app/build/app.bundle.css b/app/build/app.bundle.css index 9eb80cea2e..6acca78d33 100644 --- a/app/build/app.bundle.css +++ b/app/build/app.bundle.css @@ -1 +1 @@ -.maplibregl-map{font:12px/20px Helvetica Neue,Arial,Helvetica,sans-serif;overflow:hidden;position:relative;-webkit-tap-highlight-color:rgb(0 0 0/0)}.maplibregl-canvas{left:0;position:absolute;top:0}.maplibregl-map:fullscreen{height:100%;width:100%}.maplibregl-ctrl-group button.maplibregl-ctrl-compass{touch-action:none}.maplibregl-canvas-container.maplibregl-interactive,.maplibregl-ctrl-group button.maplibregl-ctrl-compass{cursor:grab;-webkit-user-select:none;-moz-user-select:none;user-select:none}.maplibregl-canvas-container.maplibregl-interactive.maplibregl-track-pointer{cursor:pointer}.maplibregl-canvas-container.maplibregl-interactive:active,.maplibregl-ctrl-group button.maplibregl-ctrl-compass:active{cursor:grabbing}.maplibregl-canvas-container.maplibregl-touch-zoom-rotate,.maplibregl-canvas-container.maplibregl-touch-zoom-rotate .maplibregl-canvas{touch-action:pan-x pan-y}.maplibregl-canvas-container.maplibregl-touch-drag-pan,.maplibregl-canvas-container.maplibregl-touch-drag-pan .maplibregl-canvas{touch-action:pinch-zoom}.maplibregl-canvas-container.maplibregl-touch-zoom-rotate.maplibregl-touch-drag-pan,.maplibregl-canvas-container.maplibregl-touch-zoom-rotate.maplibregl-touch-drag-pan .maplibregl-canvas{touch-action:none}.maplibregl-canvas-container.maplibregl-touch-drag-pan.maplibregl-cooperative-gestures,.maplibregl-canvas-container.maplibregl-touch-drag-pan.maplibregl-cooperative-gestures .maplibregl-canvas{touch-action:pan-x pan-y}.maplibregl-ctrl-bottom-left,.maplibregl-ctrl-bottom-right,.maplibregl-ctrl-top-left,.maplibregl-ctrl-top-right{pointer-events:none;position:absolute;z-index:2}.maplibregl-ctrl-top-left{left:0;top:0}.maplibregl-ctrl-top-right{right:0;top:0}.maplibregl-ctrl-bottom-left{bottom:0;left:0}.maplibregl-ctrl-bottom-right{bottom:0;right:0}.maplibregl-ctrl{clear:both;pointer-events:auto;transform:translate(0)}.maplibregl-ctrl-top-left .maplibregl-ctrl{float:left;margin:10px 0 0 10px}.maplibregl-ctrl-top-right .maplibregl-ctrl{float:right;margin:10px 10px 0 0}.maplibregl-ctrl-bottom-left .maplibregl-ctrl{float:left;margin:0 0 10px 10px}.maplibregl-ctrl-bottom-right .maplibregl-ctrl{float:right;margin:0 10px 10px 0}.maplibregl-ctrl-group{background:#fff;border-radius:4px}.maplibregl-ctrl-group:not(:empty){box-shadow:0 0 0 2px #0000001a}@media(forced-colors:active){.maplibregl-ctrl-group:not(:empty){box-shadow:0 0 0 2px ButtonText}}.maplibregl-ctrl-group button{background-color:transparent;border:0;box-sizing:border-box;cursor:pointer;display:block;height:29px;outline:none;padding:0;width:29px}.maplibregl-ctrl-group button+button{border-top:1px solid #ddd}.maplibregl-ctrl button .maplibregl-ctrl-icon{background-position:50%;background-repeat:no-repeat;display:block;height:100%;width:100%}@media(forced-colors:active){.maplibregl-ctrl-icon{background-color:transparent}.maplibregl-ctrl-group button+button{border-top:1px solid ButtonText}}.maplibregl-ctrl button::-moz-focus-inner{border:0;padding:0}.maplibregl-ctrl-attrib-button:focus,.maplibregl-ctrl-group button:focus{box-shadow:0 0 2px 2px #0096ff}.maplibregl-ctrl button:disabled{cursor:not-allowed}.maplibregl-ctrl button:disabled .maplibregl-ctrl-icon{opacity:.25}@media(hover:hover){.maplibregl-ctrl button:not(:disabled):hover{background-color:#0000000d}}.maplibregl-ctrl button:not(:disabled):active{background-color:#0000000d}.maplibregl-ctrl-group button:focus:focus-visible{box-shadow:0 0 2px 2px #0096ff}.maplibregl-ctrl-group button:focus:not(:focus-visible){box-shadow:none}.maplibregl-ctrl-group button:focus:first-child{border-radius:4px 4px 0 0}.maplibregl-ctrl-group button:focus:last-child{border-radius:0 0 4px 4px}.maplibregl-ctrl-group button:focus:only-child{border-radius:inherit}.maplibregl-ctrl button.maplibregl-ctrl-zoom-out .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23333' viewBox='0 0 29 29'%3E%3Cpath d='M10 13c-.75 0-1.5.75-1.5 1.5S9.25 16 10 16h9c.75 0 1.5-.75 1.5-1.5S19.75 13 19 13z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-zoom-in .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23333' viewBox='0 0 29 29'%3E%3Cpath d='M14.5 8.5c-.75 0-1.5.75-1.5 1.5v3h-3c-.75 0-1.5.75-1.5 1.5S9.25 16 10 16h3v3c0 .75.75 1.5 1.5 1.5S16 19.75 16 19v-3h3c.75 0 1.5-.75 1.5-1.5S19.75 13 19 13h-3v-3c0-.75-.75-1.5-1.5-1.5'/%3E%3C/svg%3E")}@media(forced-colors:active){.maplibregl-ctrl button.maplibregl-ctrl-zoom-out .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23fff' viewBox='0 0 29 29'%3E%3Cpath d='M10 13c-.75 0-1.5.75-1.5 1.5S9.25 16 10 16h9c.75 0 1.5-.75 1.5-1.5S19.75 13 19 13z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-zoom-in .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23fff' viewBox='0 0 29 29'%3E%3Cpath d='M14.5 8.5c-.75 0-1.5.75-1.5 1.5v3h-3c-.75 0-1.5.75-1.5 1.5S9.25 16 10 16h3v3c0 .75.75 1.5 1.5 1.5S16 19.75 16 19v-3h3c.75 0 1.5-.75 1.5-1.5S19.75 13 19 13h-3v-3c0-.75-.75-1.5-1.5-1.5'/%3E%3C/svg%3E")}}@media(forced-colors:active)and (prefers-color-scheme:light){.maplibregl-ctrl button.maplibregl-ctrl-zoom-out .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' viewBox='0 0 29 29'%3E%3Cpath d='M10 13c-.75 0-1.5.75-1.5 1.5S9.25 16 10 16h9c.75 0 1.5-.75 1.5-1.5S19.75 13 19 13z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-zoom-in .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' viewBox='0 0 29 29'%3E%3Cpath d='M14.5 8.5c-.75 0-1.5.75-1.5 1.5v3h-3c-.75 0-1.5.75-1.5 1.5S9.25 16 10 16h3v3c0 .75.75 1.5 1.5 1.5S16 19.75 16 19v-3h3c.75 0 1.5-.75 1.5-1.5S19.75 13 19 13h-3v-3c0-.75-.75-1.5-1.5-1.5'/%3E%3C/svg%3E")}}.maplibregl-ctrl button.maplibregl-ctrl-fullscreen .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23333' viewBox='0 0 29 29'%3E%3Cpath d='M24 16v5.5c0 1.75-.75 2.5-2.5 2.5H16v-1l3-1.5-4-5.5 1-1 5.5 4 1.5-3zM6 16l1.5 3 5.5-4 1 1-4 5.5 3 1.5v1H7.5C5.75 24 5 23.25 5 21.5V16zm7-11v1l-3 1.5 4 5.5-1 1-5.5-4L6 13H5V7.5C5 5.75 5.75 5 7.5 5zm11 2.5c0-1.75-.75-2.5-2.5-2.5H16v1l3 1.5-4 5.5 1 1 5.5-4 1.5 3h1z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-shrink .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' viewBox='0 0 29 29'%3E%3Cpath d='M18.5 16c-1.75 0-2.5.75-2.5 2.5V24h1l1.5-3 5.5 4 1-1-4-5.5 3-1.5v-1zM13 18.5c0-1.75-.75-2.5-2.5-2.5H5v1l3 1.5L4 24l1 1 5.5-4 1.5 3h1zm3-8c0 1.75.75 2.5 2.5 2.5H24v-1l-3-1.5L25 5l-1-1-5.5 4L17 5h-1zM10.5 13c1.75 0 2.5-.75 2.5-2.5V5h-1l-1.5 3L5 4 4 5l4 5.5L5 12v1z'/%3E%3C/svg%3E")}@media(forced-colors:active){.maplibregl-ctrl button.maplibregl-ctrl-fullscreen .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23fff' viewBox='0 0 29 29'%3E%3Cpath d='M24 16v5.5c0 1.75-.75 2.5-2.5 2.5H16v-1l3-1.5-4-5.5 1-1 5.5 4 1.5-3zM6 16l1.5 3 5.5-4 1 1-4 5.5 3 1.5v1H7.5C5.75 24 5 23.25 5 21.5V16zm7-11v1l-3 1.5 4 5.5-1 1-5.5-4L6 13H5V7.5C5 5.75 5.75 5 7.5 5zm11 2.5c0-1.75-.75-2.5-2.5-2.5H16v1l3 1.5-4 5.5 1 1 5.5-4 1.5 3h1z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-shrink .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23fff' viewBox='0 0 29 29'%3E%3Cpath d='M18.5 16c-1.75 0-2.5.75-2.5 2.5V24h1l1.5-3 5.5 4 1-1-4-5.5 3-1.5v-1zM13 18.5c0-1.75-.75-2.5-2.5-2.5H5v1l3 1.5L4 24l1 1 5.5-4 1.5 3h1zm3-8c0 1.75.75 2.5 2.5 2.5H24v-1l-3-1.5L25 5l-1-1-5.5 4L17 5h-1zM10.5 13c1.75 0 2.5-.75 2.5-2.5V5h-1l-1.5 3L5 4 4 5l4 5.5L5 12v1z'/%3E%3C/svg%3E")}}@media(forced-colors:active)and (prefers-color-scheme:light){.maplibregl-ctrl button.maplibregl-ctrl-fullscreen .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' viewBox='0 0 29 29'%3E%3Cpath d='M24 16v5.5c0 1.75-.75 2.5-2.5 2.5H16v-1l3-1.5-4-5.5 1-1 5.5 4 1.5-3zM6 16l1.5 3 5.5-4 1 1-4 5.5 3 1.5v1H7.5C5.75 24 5 23.25 5 21.5V16zm7-11v1l-3 1.5 4 5.5-1 1-5.5-4L6 13H5V7.5C5 5.75 5.75 5 7.5 5zm11 2.5c0-1.75-.75-2.5-2.5-2.5H16v1l3 1.5-4 5.5 1 1 5.5-4 1.5 3h1z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-shrink .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' viewBox='0 0 29 29'%3E%3Cpath d='M18.5 16c-1.75 0-2.5.75-2.5 2.5V24h1l1.5-3 5.5 4 1-1-4-5.5 3-1.5v-1zM13 18.5c0-1.75-.75-2.5-2.5-2.5H5v1l3 1.5L4 24l1 1 5.5-4 1.5 3h1zm3-8c0 1.75.75 2.5 2.5 2.5H24v-1l-3-1.5L25 5l-1-1-5.5 4L17 5h-1zM10.5 13c1.75 0 2.5-.75 2.5-2.5V5h-1l-1.5 3L5 4 4 5l4 5.5L5 12v1z'/%3E%3C/svg%3E")}}.maplibregl-ctrl button.maplibregl-ctrl-compass .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23333' viewBox='0 0 29 29'%3E%3Cpath d='m10.5 14 4-8 4 8z'/%3E%3Cpath fill='%23ccc' d='m10.5 16 4 8 4-8z'/%3E%3C/svg%3E")}@media(forced-colors:active){.maplibregl-ctrl button.maplibregl-ctrl-compass .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23fff' viewBox='0 0 29 29'%3E%3Cpath d='m10.5 14 4-8 4 8z'/%3E%3Cpath fill='%23ccc' d='m10.5 16 4 8 4-8z'/%3E%3C/svg%3E")}}@media(forced-colors:active)and (prefers-color-scheme:light){.maplibregl-ctrl button.maplibregl-ctrl-compass .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' viewBox='0 0 29 29'%3E%3Cpath d='m10.5 14 4-8 4 8z'/%3E%3Cpath fill='%23ccc' d='m10.5 16 4 8 4-8z'/%3E%3C/svg%3E")}}.maplibregl-ctrl button.maplibregl-ctrl-globe .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='22' height='22' fill='none' stroke='%23333' viewBox='0 0 22 22'%3E%3Ccircle cx='11' cy='11' r='8.5'/%3E%3Cpath d='M17.5 11c0 4.819-3.02 8.5-6.5 8.5S4.5 15.819 4.5 11 7.52 2.5 11 2.5s6.5 3.681 6.5 8.5Z'/%3E%3Cpath d='M13.5 11c0 2.447-.331 4.64-.853 6.206-.262.785-.562 1.384-.872 1.777-.314.399-.58.517-.775.517s-.461-.118-.775-.517c-.31-.393-.61-.992-.872-1.777C8.831 15.64 8.5 13.446 8.5 11s.331-4.64.853-6.206c.262-.785.562-1.384.872-1.777.314-.399.58-.517.775-.517s.461.118.775.517c.31.393.61.992.872 1.777.522 1.565.853 3.76.853 6.206Z'/%3E%3Cpath d='M11 7.5c-1.909 0-3.622-.166-4.845-.428-.616-.132-1.08-.283-1.379-.434a1.3 1.3 0 0 1-.224-.138q.07-.058.224-.138c.299-.151.763-.302 1.379-.434C7.378 5.666 9.091 5.5 11 5.5s3.622.166 4.845.428c.616.132 1.08.283 1.379.434.105.053.177.1.224.138q-.07.058-.224.138c-.299.151-.763.302-1.379.434-1.223.262-2.936.428-4.845.428ZM4.486 6.436ZM11 16.5c-1.909 0-3.622-.166-4.845-.428-.616-.132-1.08-.283-1.379-.434a1.3 1.3 0 0 1-.224-.138 1.3 1.3 0 0 1 .224-.138c.299-.151.763-.302 1.379-.434C7.378 14.666 9.091 14.5 11 14.5s3.622.166 4.845.428c.616.132 1.08.283 1.379.434.105.053.177.1.224.138a1.3 1.3 0 0 1-.224.138c-.299.151-.763.302-1.379.434-1.223.262-2.936.428-4.845.428Zm-6.514-1.064ZM11 12.5c-2.46 0-4.672-.222-6.255-.574-.796-.177-1.406-.38-1.805-.59a1.5 1.5 0 0 1-.39-.272.3.3 0 0 1-.047-.064.3.3 0 0 1 .048-.064c.066-.073.189-.167.389-.272.399-.21 1.009-.413 1.805-.59C6.328 9.722 8.54 9.5 11 9.5s4.672.222 6.256.574c.795.177 1.405.38 1.804.59.2.105.323.2.39.272a.3.3 0 0 1 .047.064.3.3 0 0 1-.048.064 1.4 1.4 0 0 1-.389.272c-.399.21-1.009.413-1.804.59-1.584.352-3.796.574-6.256.574Zm-8.501-1.51v.002zm0 .018v.002zm17.002.002v-.002zm0-.018v-.002z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-globe-enabled .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='22' height='22' fill='none' stroke='%2333b5e5' viewBox='0 0 22 22'%3E%3Ccircle cx='11' cy='11' r='8.5'/%3E%3Cpath d='M17.5 11c0 4.819-3.02 8.5-6.5 8.5S4.5 15.819 4.5 11 7.52 2.5 11 2.5s6.5 3.681 6.5 8.5Z'/%3E%3Cpath d='M13.5 11c0 2.447-.331 4.64-.853 6.206-.262.785-.562 1.384-.872 1.777-.314.399-.58.517-.775.517s-.461-.118-.775-.517c-.31-.393-.61-.992-.872-1.777C8.831 15.64 8.5 13.446 8.5 11s.331-4.64.853-6.206c.262-.785.562-1.384.872-1.777.314-.399.58-.517.775-.517s.461.118.775.517c.31.393.61.992.872 1.777.522 1.565.853 3.76.853 6.206Z'/%3E%3Cpath d='M11 7.5c-1.909 0-3.622-.166-4.845-.428-.616-.132-1.08-.283-1.379-.434a1.3 1.3 0 0 1-.224-.138q.07-.058.224-.138c.299-.151.763-.302 1.379-.434C7.378 5.666 9.091 5.5 11 5.5s3.622.166 4.845.428c.616.132 1.08.283 1.379.434.105.053.177.1.224.138q-.07.058-.224.138c-.299.151-.763.302-1.379.434-1.223.262-2.936.428-4.845.428ZM4.486 6.436ZM11 16.5c-1.909 0-3.622-.166-4.845-.428-.616-.132-1.08-.283-1.379-.434a1.3 1.3 0 0 1-.224-.138 1.3 1.3 0 0 1 .224-.138c.299-.151.763-.302 1.379-.434C7.378 14.666 9.091 14.5 11 14.5s3.622.166 4.845.428c.616.132 1.08.283 1.379.434.105.053.177.1.224.138a1.3 1.3 0 0 1-.224.138c-.299.151-.763.302-1.379.434-1.223.262-2.936.428-4.845.428Zm-6.514-1.064ZM11 12.5c-2.46 0-4.672-.222-6.255-.574-.796-.177-1.406-.38-1.805-.59a1.5 1.5 0 0 1-.39-.272.3.3 0 0 1-.047-.064.3.3 0 0 1 .048-.064c.066-.073.189-.167.389-.272.399-.21 1.009-.413 1.805-.59C6.328 9.722 8.54 9.5 11 9.5s4.672.222 6.256.574c.795.177 1.405.38 1.804.59.2.105.323.2.39.272a.3.3 0 0 1 .047.064.3.3 0 0 1-.048.064 1.4 1.4 0 0 1-.389.272c-.399.21-1.009.413-1.804.59-1.584.352-3.796.574-6.256.574Zm-8.501-1.51v.002zm0 .018v.002zm17.002.002v-.002zm0-.018v-.002z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-terrain .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='22' height='22' fill='%23333' viewBox='0 0 22 22'%3E%3Cpath d='m1.754 13.406 4.453-4.851 3.09 3.09 3.281 3.277.969-.969-3.309-3.312 3.844-4.121 6.148 6.886h1.082v-.855l-7.207-8.07-4.84 5.187L6.169 6.57l-5.48 5.965v.871ZM.688 16.844h20.625v1.375H.688Zm0 0'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-terrain-enabled .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='22' height='22' fill='%2333b5e5' viewBox='0 0 22 22'%3E%3Cpath d='m1.754 13.406 4.453-4.851 3.09 3.09 3.281 3.277.969-.969-3.309-3.312 3.844-4.121 6.148 6.886h1.082v-.855l-7.207-8.07-4.84 5.187L6.169 6.57l-5.48 5.965v.871ZM.688 16.844h20.625v1.375H.688Zm0 0'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23333' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate:disabled .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23aaa' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3Cpath fill='red' d='m14 5 1 1-9 9-1-1z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-active .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%2333b5e5' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-active-error .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23e58978' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-background .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%2333b5e5' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-background-error .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23e54e33' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-waiting .maplibregl-ctrl-icon{animation:maplibregl-spin 2s linear infinite}@media(forced-colors:active){.maplibregl-ctrl button.maplibregl-ctrl-geolocate .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23fff' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate:disabled .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23999' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3Cpath fill='red' d='m14 5 1 1-9 9-1-1z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-active .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%2333b5e5' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-active-error .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23e58978' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-background .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%2333b5e5' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-background-error .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23e54e33' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3C/svg%3E")}}@media(forced-colors:active)and (prefers-color-scheme:light){.maplibregl-ctrl button.maplibregl-ctrl-geolocate .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate:disabled .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23666' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3Cpath fill='red' d='m14 5 1 1-9 9-1-1z'/%3E%3C/svg%3E")}}@keyframes maplibregl-spin{0%{transform:rotate(0)}to{transform:rotate(1turn)}}a.maplibregl-ctrl-logo{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='88' height='23' fill='none'%3E%3Cpath fill='%23000' fill-opacity='.4' fill-rule='evenodd' d='M17.408 16.796h-1.827l2.501-12.095h.198l3.324 6.533.988 2.19.988-2.19 3.258-6.533h.181l2.6 12.095h-1.81l-1.218-5.644-.362-1.71-.658 1.71-2.929 5.644h-.098l-2.914-5.644-.757-1.71-.345 1.71zm1.958-3.42-.726 3.663a1.255 1.255 0 0 1-1.232 1.011h-1.827a1.255 1.255 0 0 1-1.229-1.509l2.501-12.095a1.255 1.255 0 0 1 1.23-1.001h.197a1.25 1.25 0 0 1 1.12.685l3.19 6.273 3.125-6.263a1.25 1.25 0 0 1 1.123-.695h.181a1.255 1.255 0 0 1 1.227.991l1.443 6.71a5 5 0 0 1 .314-.787l.009-.016a4.6 4.6 0 0 1 1.777-1.887c.782-.46 1.668-.667 2.611-.667a4.6 4.6 0 0 1 1.7.32l.306.134c.21-.16.474-.256.759-.256h1.694a1.255 1.255 0 0 1 1.212.925 1.255 1.255 0 0 1 1.212-.925h1.711c.284 0 .545.094.755.252.613-.3 1.312-.45 2.075-.45 1.356 0 2.557.445 3.482 1.4q.47.48.763 1.064V4.701a1.255 1.255 0 0 1 1.255-1.255h1.86A1.255 1.255 0 0 1 54.44 4.7v9.194h2.217c.19 0 .37.043.532.118v-4.77c0-.356.147-.678.385-.906a2.42 2.42 0 0 1-.682-1.71c0-.665.267-1.253.735-1.7a2.45 2.45 0 0 1 1.722-.674 2.43 2.43 0 0 1 1.705.675q.318.302.504.683V4.7a1.255 1.255 0 0 1 1.255-1.255h1.744A1.255 1.255 0 0 1 65.812 4.7v3.335a4.8 4.8 0 0 1 1.526-.246c.938 0 1.817.214 2.59.69a4.47 4.47 0 0 1 1.67 1.743v-.98a1.255 1.255 0 0 1 1.256-1.256h1.777c.233 0 .451.064.639.174a3.4 3.4 0 0 1 1.567-.372c.346 0 .861.02 1.285.232a1.25 1.25 0 0 1 .689 1.004 4.7 4.7 0 0 1 .853-.588c.795-.44 1.675-.647 2.61-.647 1.385 0 2.65.39 3.525 1.396.836.938 1.168 2.173 1.168 3.528q-.001.515-.056 1.051a1.255 1.255 0 0 1-.947 1.09l.408.952a1.255 1.255 0 0 1-.477 1.552c-.418.268-.92.463-1.458.612-.613.171-1.304.244-2.049.244-1.06 0-2.043-.207-2.886-.698l-.015-.008c-.798-.48-1.419-1.135-1.818-1.963l-.004-.008a5.8 5.8 0 0 1-.548-2.512q0-.429.053-.843a1.3 1.3 0 0 1-.333-.086l-.166-.004c-.223 0-.426.062-.643.228-.03.024-.142.139-.142.59v3.883a1.255 1.255 0 0 1-1.256 1.256h-1.777a1.255 1.255 0 0 1-1.256-1.256V15.69l-.032.057a4.8 4.8 0 0 1-1.86 1.833 5.04 5.04 0 0 1-2.484.634 4.5 4.5 0 0 1-1.935-.424 1.25 1.25 0 0 1-.764.258h-1.71a1.255 1.255 0 0 1-1.256-1.255V7.687a2.4 2.4 0 0 1-.428.625c.253.23.412.561.412.93v7.553a1.255 1.255 0 0 1-1.256 1.255h-1.843a1.25 1.25 0 0 1-.894-.373c-.228.23-.544.373-.894.373H51.32a1.255 1.255 0 0 1-1.256-1.255v-1.251l-.061.117a4.7 4.7 0 0 1-1.782 1.884 4.77 4.77 0 0 1-2.485.67 5.6 5.6 0 0 1-1.485-.188l.009 2.764a1.255 1.255 0 0 1-1.255 1.259h-1.729a1.255 1.255 0 0 1-1.255-1.255v-3.537a1.255 1.255 0 0 1-1.167.793h-1.679a1.25 1.25 0 0 1-.77-.263 4.5 4.5 0 0 1-1.945.429c-.885 0-1.724-.21-2.495-.632l-.017-.01a5 5 0 0 1-1.081-.836 1.255 1.255 0 0 1-1.254 1.312h-1.81a1.255 1.255 0 0 1-1.228-.99l-.782-3.625-2.044 3.939a1.25 1.25 0 0 1-1.115.676h-.098a1.25 1.25 0 0 1-1.116-.68l-2.061-3.994zM35.92 16.63l.207-.114.223-.15q.493-.356.735-.785l.061-.118.033 1.332h1.678V9.242h-1.694l-.033 1.267q-.133-.329-.526-.658l-.032-.028a3.2 3.2 0 0 0-.668-.428l-.27-.12a3.3 3.3 0 0 0-1.235-.23q-1.136-.001-1.974.493a3.36 3.36 0 0 0-1.3 1.382q-.445.89-.444 2.074 0 1.2.51 2.107a3.8 3.8 0 0 0 1.382 1.381 3.9 3.9 0 0 0 1.893.477q.795 0 1.455-.33zm-2.789-5.38q-.576.675-.575 1.762 0 1.102.559 1.794.576.675 1.645.675a2.25 2.25 0 0 0 .934-.19 2.2 2.2 0 0 0 .468-.29l.178-.161a2.2 2.2 0 0 0 .397-.561q.244-.5.244-1.15v-.115q0-.708-.296-1.267l-.043-.077a2.2 2.2 0 0 0-.633-.709l-.13-.086-.047-.028a2.1 2.1 0 0 0-1.073-.285q-1.052 0-1.629.692zm2.316 2.706c.163-.17.28-.407.28-.83v-.114c0-.292-.06-.508-.15-.68a.96.96 0 0 0-.353-.389.85.85 0 0 0-.464-.127c-.4 0-.56.114-.664.239l-.01.012c-.148.174-.275.45-.275.945 0 .506.122.801.27.99.097.11.266.224.68.224.303 0 .504-.09.687-.269zm7.545 1.705a2.6 2.6 0 0 0 .331.423q.319.33.755.548l.173.074q.65.255 1.49.255 1.02 0 1.844-.493a3.45 3.45 0 0 0 1.316-1.4q.493-.904.493-2.089 0-1.909-.988-2.913-.988-1.02-2.584-1.02-.898 0-1.575.347a3 3 0 0 0-.415.262l-.199.166a3.4 3.4 0 0 0-.64.82V9.242h-1.712v11.553h1.729l-.017-5.134zm.53-1.138q.206.29.48.5l.155.11.053.034q.51.296 1.119.297 1.07 0 1.645-.675.577-.69.576-1.762 0-1.119-.576-1.777-.558-.675-1.645-.675-.435 0-.835.16a2 2 0 0 0-.284.136 2 2 0 0 0-.363.254 2.2 2.2 0 0 0-.46.569l-.082.162a2.6 2.6 0 0 0-.213 1.072v.115q0 .707.296 1.267l.135.211zm.964-.818a1.1 1.1 0 0 0 .367.385.94.94 0 0 0 .476.118c.423 0 .59-.117.687-.23.159-.194.28-.478.28-.95 0-.53-.133-.8-.266-.952l-.021-.025c-.078-.094-.231-.221-.68-.221a1 1 0 0 0-.503.135l-.012.007a.86.86 0 0 0-.335.343c-.073.133-.132.324-.132.614v.115a1.4 1.4 0 0 0 .14.66zm15.7-6.222q.347-.346.346-.856a1.05 1.05 0 0 0-.345-.79 1.18 1.18 0 0 0-.84-.329q-.51 0-.855.33a1.05 1.05 0 0 0-.346.79q0 .51.346.855.345.346.856.346.51 0 .839-.346zm4.337 9.314.033-1.332q.191.403.59.747l.098.081a4 4 0 0 0 .316.224l.223.122a3.2 3.2 0 0 0 1.44.322 3.8 3.8 0 0 0 1.875-.477 3.5 3.5 0 0 0 1.382-1.366q.527-.89.526-2.09 0-1.184-.444-2.073a3.24 3.24 0 0 0-1.283-1.399q-.823-.51-1.942-.51a3.5 3.5 0 0 0-1.527.344l-.086.043-.165.09a3 3 0 0 0-.33.214q-.432.315-.656.707a2 2 0 0 0-.099.198l.082-1.283V4.701h-1.744v12.095zm.473-2.509a2.5 2.5 0 0 0 .566.7q.117.098.245.18l.144.08a2.1 2.1 0 0 0 .975.232q1.07 0 1.645-.675.576-.69.576-1.778 0-1.102-.576-1.777-.56-.691-1.645-.692a2.2 2.2 0 0 0-1.015.235q-.22.113-.415.282l-.15.142a2.1 2.1 0 0 0-.42.594q-.223.479-.223 1.1v.115q0 .705.293 1.26zm2.616-.293c.157-.191.28-.479.28-.967 0-.51-.13-.79-.276-.961l-.021-.026c-.082-.1-.232-.225-.67-.225a.87.87 0 0 0-.681.279l-.012.011c-.154.155-.274.38-.274.807v.115c0 .285.057.499.144.669a1.1 1.1 0 0 0 .367.405c.137.082.28.123.455.123.423 0 .59-.118.686-.23zm8.266-3.013q.345-.13.724-.14l.069-.002q.493 0 .642.099l.247-1.794q-.196-.099-.717-.099a2.3 2.3 0 0 0-.545.063 2 2 0 0 0-.411.148 2.2 2.2 0 0 0-.4.249 2.5 2.5 0 0 0-.485.499 2.7 2.7 0 0 0-.32.581l-.05.137v-1.48h-1.778v7.553h1.777v-3.884q0-.546.159-.943a1.5 1.5 0 0 1 .466-.636 2.5 2.5 0 0 1 .399-.253 2 2 0 0 1 .224-.099zm9.784 2.656.05-.922q0-1.743-.856-2.698-.838-.97-2.584-.97-1.119-.001-2.007.493a3.46 3.46 0 0 0-1.4 1.382q-.493.906-.493 2.106 0 1.07.428 1.975.428.89 1.332 1.432.906.526 2.255.526.973 0 1.668-.185l.044-.012.135-.04q.613-.184.984-.421l-.542-1.267q-.3.162-.642.274l-.297.087q-.51.131-1.3.131-.954 0-1.497-.444a1.6 1.6 0 0 1-.192-.193q-.366-.44-.512-1.234l-.004-.021zm-5.427-1.256-.003.022h3.752v-.138q-.011-.727-.288-1.118a1 1 0 0 0-.156-.176q-.46-.428-1.316-.428-.986 0-1.494.604-.379.45-.494 1.234zm-27.053 2.77V4.7h-1.86v12.095h5.333V15.15zm7.103-5.908v7.553h-1.843V9.242h1.843z'/%3E%3Cpath fill='%23fff' d='m19.63 11.151-.757-1.71-.345 1.71-1.12 5.644h-1.827L18.083 4.7h.197l3.325 6.533.988 2.19.988-2.19L26.839 4.7h.181l2.6 12.095h-1.81l-1.218-5.644-.362-1.71-.658 1.71-2.93 5.644h-.098l-2.913-5.644zm14.836 5.81q-1.02 0-1.893-.478a3.8 3.8 0 0 1-1.381-1.382q-.51-.906-.51-2.106 0-1.185.444-2.074a3.36 3.36 0 0 1 1.3-1.382q.839-.494 1.974-.494a3.3 3.3 0 0 1 1.234.231 3.3 3.3 0 0 1 .97.575q.396.33.527.659l.033-1.267h1.694v7.553H37.18l-.033-1.332q-.279.593-1.02 1.053a3.17 3.17 0 0 1-1.662.444zm.296-1.482q.938 0 1.58-.642.642-.66.642-1.711v-.115q0-.708-.296-1.267a2.2 2.2 0 0 0-.807-.872 2.1 2.1 0 0 0-1.119-.313q-1.053 0-1.629.692-.575.675-.575 1.76 0 1.103.559 1.795.577.675 1.645.675zm6.521-6.237h1.711v1.4q.906-1.597 2.83-1.597 1.596 0 2.584 1.02.988 1.005.988 2.914 0 1.185-.493 2.09a3.46 3.46 0 0 1-1.316 1.399 3.5 3.5 0 0 1-1.844.493q-.954 0-1.662-.329a2.67 2.67 0 0 1-1.086-.97l.017 5.134h-1.728zm4.048 6.22q1.07 0 1.645-.674.577-.69.576-1.762 0-1.119-.576-1.777-.558-.675-1.645-.675-.592 0-1.12.296-.51.28-.822.823-.296.527-.296 1.234v.115q0 .708.296 1.267.313.543.823.855.51.296 1.119.297z'/%3E%3Cpath fill='%23e1e3e9' d='M51.325 4.7h1.86v10.45h3.473v1.646h-5.333zm7.12 4.542h1.843v7.553h-1.843zm.905-1.415a1.16 1.16 0 0 1-.856-.346 1.17 1.17 0 0 1-.346-.856 1.05 1.05 0 0 1 .346-.79q.346-.329.856-.329.494 0 .839.33a1.05 1.05 0 0 1 .345.79 1.16 1.16 0 0 1-.345.855q-.33.346-.84.346zm7.875 9.133a3.17 3.17 0 0 1-1.662-.444q-.723-.46-1.004-1.053l-.033 1.332h-1.71V4.701h1.743v4.657l-.082 1.283q.279-.658 1.086-1.119a3.5 3.5 0 0 1 1.778-.477q1.119 0 1.942.51a3.24 3.24 0 0 1 1.283 1.4q.445.888.444 2.072 0 1.201-.526 2.09a3.5 3.5 0 0 1-1.382 1.366 3.8 3.8 0 0 1-1.876.477zm-.296-1.481q1.069 0 1.645-.675.577-.69.577-1.778 0-1.102-.577-1.776-.56-.691-1.645-.692a2.12 2.12 0 0 0-1.58.659q-.642.641-.642 1.694v.115q0 .71.296 1.267a2.4 2.4 0 0 0 .807.872 2.1 2.1 0 0 0 1.119.313zm5.927-6.237h1.777v1.481q.263-.757.856-1.217a2.14 2.14 0 0 1 1.349-.46q.527 0 .724.098l-.247 1.794q-.149-.099-.642-.099-.774 0-1.416.494-.626.493-.626 1.58v3.883h-1.777V9.242zm9.534 7.718q-1.35 0-2.255-.526-.904-.543-1.332-1.432a4.6 4.6 0 0 1-.428-1.975q0-1.2.493-2.106a3.46 3.46 0 0 1 1.4-1.382q.889-.495 2.007-.494 1.744 0 2.584.97.855.956.856 2.7 0 .444-.05.92h-5.43q.18 1.005.708 1.45.542.443 1.497.443.79 0 1.3-.131a4 4 0 0 0 .938-.362l.542 1.267q-.411.263-1.119.46-.708.198-1.711.197zm1.596-4.558q.016-1.02-.444-1.432-.46-.428-1.316-.428-1.728 0-1.991 1.86z'/%3E%3Cpath d='M5.074 15.948a.484.657 0 0 0-.486.659v1.84a.484.657 0 0 0 .486.659h4.101a.484.657 0 0 0 .486-.659v-1.84a.484.657 0 0 0-.486-.659zm3.56 1.16H5.617v.838h3.017z' style='fill:%23fff;fill-rule:evenodd;stroke-width:1.03600001'/%3E%3Cg style='stroke-width:1.12603545'%3E%3Cpath d='M-9.408-1.416c-3.833-.025-7.056 2.912-7.08 6.615-.02 3.08 1.653 4.832 3.107 6.268.903.892 1.721 1.74 2.32 2.902l-.525-.004c-.543-.003-.992.304-1.24.639a1.87 1.87 0 0 0-.362 1.121l-.011 1.877c-.003.402.104.787.347 1.125.244.338.688.653 1.23.656l4.142.028c.542.003.99-.306 1.238-.641a1.87 1.87 0 0 0 .363-1.121l.012-1.875a1.87 1.87 0 0 0-.348-1.127c-.243-.338-.688-.653-1.23-.656l-.518-.004c.597-1.145 1.425-1.983 2.348-2.87 1.473-1.414 3.18-3.149 3.2-6.226-.016-3.59-2.923-6.684-6.993-6.707m-.006 1.1v.002c3.274.02 5.92 2.532 5.9 5.6-.017 2.706-1.39 4.026-2.863 5.44-1.034.994-2.118 2.033-2.814 3.633-.018.041-.052.055-.075.065q-.013.004-.02.01a.34.34 0 0 1-.226.084.34.34 0 0 1-.224-.086l-.092-.077c-.699-1.615-1.768-2.669-2.781-3.67-1.454-1.435-2.797-2.762-2.78-5.478.02-3.067 2.7-5.545 5.975-5.523m-.02 2.826c-1.62-.01-2.944 1.315-2.955 2.96-.01 1.646 1.295 2.988 2.916 2.999h.002c1.621.01 2.943-1.316 2.953-2.961.011-1.646-1.294-2.988-2.916-2.998m-.005 1.1c1.017.006 1.829.83 1.822 1.89s-.83 1.874-1.848 1.867c-1.018-.006-1.829-.83-1.822-1.89s.83-1.874 1.848-1.868m-2.155 11.857 4.14.025c.271.002.49.305.487.676l-.013 1.875c-.003.37-.224.67-.495.668l-4.14-.025c-.27-.002-.487-.306-.485-.676l.012-1.875c.003-.37.224-.67.494-.668' style='color:%23000;font-style:normal;font-variant:normal;font-weight:400;font-stretch:normal;font-size:medium;line-height:normal;font-family:sans-serif;font-variant-ligatures:normal;font-variant-position:normal;font-variant-caps:normal;font-variant-numeric:normal;font-variant-alternates:normal;font-feature-settings:normal;text-indent:0;text-align:start;text-decoration:none;text-decoration-line:none;text-decoration-style:solid;text-decoration-color:%23000;letter-spacing:normal;word-spacing:normal;text-transform:none;writing-mode:lr-tb;direction:ltr;text-orientation:mixed;dominant-baseline:auto;baseline-shift:baseline;text-anchor:start;white-space:normal;shape-padding:0;clip-rule:evenodd;display:inline;overflow:visible;visibility:visible;opacity:1;isolation:auto;mix-blend-mode:normal;color-interpolation:sRGB;color-interpolation-filters:linearRGB;solid-color:%23000;solid-opacity:1;vector-effect:none;fill:%23000;fill-opacity:.4;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;color-rendering:auto;image-rendering:auto;shape-rendering:auto;text-rendering:auto' transform='translate(15.553 2.85)scale(.88807)'/%3E%3Cpath d='M-9.415-.316C-12.69-.338-15.37 2.14-15.39 5.207c-.017 2.716 1.326 4.041 2.78 5.477 1.013 1 2.081 2.055 2.78 3.67l.092.076a.34.34 0 0 0 .225.086.34.34 0 0 0 .227-.083l.019-.01c.022-.009.057-.024.074-.064.697-1.6 1.78-2.64 2.814-3.634 1.473-1.414 2.847-2.733 2.864-5.44.02-3.067-2.627-5.58-5.901-5.601m-.057 8.784c1.621.011 2.944-1.315 2.955-2.96.01-1.646-1.295-2.988-2.916-2.999-1.622-.01-2.945 1.315-2.955 2.96s1.295 2.989 2.916 3' style='clip-rule:evenodd;fill:%23e1e3e9;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:.4' transform='translate(15.553 2.85)scale(.88807)'/%3E%3Cpath d='M-11.594 15.465c-.27-.002-.492.297-.494.668l-.012 1.876c-.003.371.214.673.485.675l4.14.027c.271.002.492-.298.495-.668l.012-1.877c.003-.37-.215-.672-.485-.674z' style='clip-rule:evenodd;fill:%23fff;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:.4' transform='translate(15.553 2.85)scale(.88807)'/%3E%3C/g%3E%3C/svg%3E");background-repeat:no-repeat;cursor:pointer;display:block;height:23px;margin:0 0 -4px -4px;overflow:hidden;width:88px}a.maplibregl-ctrl-logo.maplibregl-compact{width:14px}@media(forced-colors:active){a.maplibregl-ctrl-logo{background-color:transparent;background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='88' height='23' fill='none'%3E%3Cpath fill='%23000' fill-opacity='.4' fill-rule='evenodd' d='M17.408 16.796h-1.827l2.501-12.095h.198l3.324 6.533.988 2.19.988-2.19 3.258-6.533h.181l2.6 12.095h-1.81l-1.218-5.644-.362-1.71-.658 1.71-2.929 5.644h-.098l-2.914-5.644-.757-1.71-.345 1.71zm1.958-3.42-.726 3.663a1.255 1.255 0 0 1-1.232 1.011h-1.827a1.255 1.255 0 0 1-1.229-1.509l2.501-12.095a1.255 1.255 0 0 1 1.23-1.001h.197a1.25 1.25 0 0 1 1.12.685l3.19 6.273 3.125-6.263a1.25 1.25 0 0 1 1.123-.695h.181a1.255 1.255 0 0 1 1.227.991l1.443 6.71a5 5 0 0 1 .314-.787l.009-.016a4.6 4.6 0 0 1 1.777-1.887c.782-.46 1.668-.667 2.611-.667a4.6 4.6 0 0 1 1.7.32l.306.134c.21-.16.474-.256.759-.256h1.694a1.255 1.255 0 0 1 1.212.925 1.255 1.255 0 0 1 1.212-.925h1.711c.284 0 .545.094.755.252.613-.3 1.312-.45 2.075-.45 1.356 0 2.557.445 3.482 1.4q.47.48.763 1.064V4.701a1.255 1.255 0 0 1 1.255-1.255h1.86A1.255 1.255 0 0 1 54.44 4.7v9.194h2.217c.19 0 .37.043.532.118v-4.77c0-.356.147-.678.385-.906a2.42 2.42 0 0 1-.682-1.71c0-.665.267-1.253.735-1.7a2.45 2.45 0 0 1 1.722-.674 2.43 2.43 0 0 1 1.705.675q.318.302.504.683V4.7a1.255 1.255 0 0 1 1.255-1.255h1.744A1.255 1.255 0 0 1 65.812 4.7v3.335a4.8 4.8 0 0 1 1.526-.246c.938 0 1.817.214 2.59.69a4.47 4.47 0 0 1 1.67 1.743v-.98a1.255 1.255 0 0 1 1.256-1.256h1.777c.233 0 .451.064.639.174a3.4 3.4 0 0 1 1.567-.372c.346 0 .861.02 1.285.232a1.25 1.25 0 0 1 .689 1.004 4.7 4.7 0 0 1 .853-.588c.795-.44 1.675-.647 2.61-.647 1.385 0 2.65.39 3.525 1.396.836.938 1.168 2.173 1.168 3.528q-.001.515-.056 1.051a1.255 1.255 0 0 1-.947 1.09l.408.952a1.255 1.255 0 0 1-.477 1.552c-.418.268-.92.463-1.458.612-.613.171-1.304.244-2.049.244-1.06 0-2.043-.207-2.886-.698l-.015-.008c-.798-.48-1.419-1.135-1.818-1.963l-.004-.008a5.8 5.8 0 0 1-.548-2.512q0-.429.053-.843a1.3 1.3 0 0 1-.333-.086l-.166-.004c-.223 0-.426.062-.643.228-.03.024-.142.139-.142.59v3.883a1.255 1.255 0 0 1-1.256 1.256h-1.777a1.255 1.255 0 0 1-1.256-1.256V15.69l-.032.057a4.8 4.8 0 0 1-1.86 1.833 5.04 5.04 0 0 1-2.484.634 4.5 4.5 0 0 1-1.935-.424 1.25 1.25 0 0 1-.764.258h-1.71a1.255 1.255 0 0 1-1.256-1.255V7.687a2.4 2.4 0 0 1-.428.625c.253.23.412.561.412.93v7.553a1.255 1.255 0 0 1-1.256 1.255h-1.843a1.25 1.25 0 0 1-.894-.373c-.228.23-.544.373-.894.373H51.32a1.255 1.255 0 0 1-1.256-1.255v-1.251l-.061.117a4.7 4.7 0 0 1-1.782 1.884 4.77 4.77 0 0 1-2.485.67 5.6 5.6 0 0 1-1.485-.188l.009 2.764a1.255 1.255 0 0 1-1.255 1.259h-1.729a1.255 1.255 0 0 1-1.255-1.255v-3.537a1.255 1.255 0 0 1-1.167.793h-1.679a1.25 1.25 0 0 1-.77-.263 4.5 4.5 0 0 1-1.945.429c-.885 0-1.724-.21-2.495-.632l-.017-.01a5 5 0 0 1-1.081-.836 1.255 1.255 0 0 1-1.254 1.312h-1.81a1.255 1.255 0 0 1-1.228-.99l-.782-3.625-2.044 3.939a1.25 1.25 0 0 1-1.115.676h-.098a1.25 1.25 0 0 1-1.116-.68l-2.061-3.994zM35.92 16.63l.207-.114.223-.15q.493-.356.735-.785l.061-.118.033 1.332h1.678V9.242h-1.694l-.033 1.267q-.133-.329-.526-.658l-.032-.028a3.2 3.2 0 0 0-.668-.428l-.27-.12a3.3 3.3 0 0 0-1.235-.23q-1.136-.001-1.974.493a3.36 3.36 0 0 0-1.3 1.382q-.445.89-.444 2.074 0 1.2.51 2.107a3.8 3.8 0 0 0 1.382 1.381 3.9 3.9 0 0 0 1.893.477q.795 0 1.455-.33zm-2.789-5.38q-.576.675-.575 1.762 0 1.102.559 1.794.576.675 1.645.675a2.25 2.25 0 0 0 .934-.19 2.2 2.2 0 0 0 .468-.29l.178-.161a2.2 2.2 0 0 0 .397-.561q.244-.5.244-1.15v-.115q0-.708-.296-1.267l-.043-.077a2.2 2.2 0 0 0-.633-.709l-.13-.086-.047-.028a2.1 2.1 0 0 0-1.073-.285q-1.052 0-1.629.692zm2.316 2.706c.163-.17.28-.407.28-.83v-.114c0-.292-.06-.508-.15-.68a.96.96 0 0 0-.353-.389.85.85 0 0 0-.464-.127c-.4 0-.56.114-.664.239l-.01.012c-.148.174-.275.45-.275.945 0 .506.122.801.27.99.097.11.266.224.68.224.303 0 .504-.09.687-.269zm7.545 1.705a2.6 2.6 0 0 0 .331.423q.319.33.755.548l.173.074q.65.255 1.49.255 1.02 0 1.844-.493a3.45 3.45 0 0 0 1.316-1.4q.493-.904.493-2.089 0-1.909-.988-2.913-.988-1.02-2.584-1.02-.898 0-1.575.347a3 3 0 0 0-.415.262l-.199.166a3.4 3.4 0 0 0-.64.82V9.242h-1.712v11.553h1.729l-.017-5.134zm.53-1.138q.206.29.48.5l.155.11.053.034q.51.296 1.119.297 1.07 0 1.645-.675.577-.69.576-1.762 0-1.119-.576-1.777-.558-.675-1.645-.675-.435 0-.835.16a2 2 0 0 0-.284.136 2 2 0 0 0-.363.254 2.2 2.2 0 0 0-.46.569l-.082.162a2.6 2.6 0 0 0-.213 1.072v.115q0 .707.296 1.267l.135.211zm.964-.818a1.1 1.1 0 0 0 .367.385.94.94 0 0 0 .476.118c.423 0 .59-.117.687-.23.159-.194.28-.478.28-.95 0-.53-.133-.8-.266-.952l-.021-.025c-.078-.094-.231-.221-.68-.221a1 1 0 0 0-.503.135l-.012.007a.86.86 0 0 0-.335.343c-.073.133-.132.324-.132.614v.115a1.4 1.4 0 0 0 .14.66zm15.7-6.222q.347-.346.346-.856a1.05 1.05 0 0 0-.345-.79 1.18 1.18 0 0 0-.84-.329q-.51 0-.855.33a1.05 1.05 0 0 0-.346.79q0 .51.346.855.345.346.856.346.51 0 .839-.346zm4.337 9.314.033-1.332q.191.403.59.747l.098.081a4 4 0 0 0 .316.224l.223.122a3.2 3.2 0 0 0 1.44.322 3.8 3.8 0 0 0 1.875-.477 3.5 3.5 0 0 0 1.382-1.366q.527-.89.526-2.09 0-1.184-.444-2.073a3.24 3.24 0 0 0-1.283-1.399q-.823-.51-1.942-.51a3.5 3.5 0 0 0-1.527.344l-.086.043-.165.09a3 3 0 0 0-.33.214q-.432.315-.656.707a2 2 0 0 0-.099.198l.082-1.283V4.701h-1.744v12.095zm.473-2.509a2.5 2.5 0 0 0 .566.7q.117.098.245.18l.144.08a2.1 2.1 0 0 0 .975.232q1.07 0 1.645-.675.576-.69.576-1.778 0-1.102-.576-1.777-.56-.691-1.645-.692a2.2 2.2 0 0 0-1.015.235q-.22.113-.415.282l-.15.142a2.1 2.1 0 0 0-.42.594q-.223.479-.223 1.1v.115q0 .705.293 1.26zm2.616-.293c.157-.191.28-.479.28-.967 0-.51-.13-.79-.276-.961l-.021-.026c-.082-.1-.232-.225-.67-.225a.87.87 0 0 0-.681.279l-.012.011c-.154.155-.274.38-.274.807v.115c0 .285.057.499.144.669a1.1 1.1 0 0 0 .367.405c.137.082.28.123.455.123.423 0 .59-.118.686-.23zm8.266-3.013q.345-.13.724-.14l.069-.002q.493 0 .642.099l.247-1.794q-.196-.099-.717-.099a2.3 2.3 0 0 0-.545.063 2 2 0 0 0-.411.148 2.2 2.2 0 0 0-.4.249 2.5 2.5 0 0 0-.485.499 2.7 2.7 0 0 0-.32.581l-.05.137v-1.48h-1.778v7.553h1.777v-3.884q0-.546.159-.943a1.5 1.5 0 0 1 .466-.636 2.5 2.5 0 0 1 .399-.253 2 2 0 0 1 .224-.099zm9.784 2.656.05-.922q0-1.743-.856-2.698-.838-.97-2.584-.97-1.119-.001-2.007.493a3.46 3.46 0 0 0-1.4 1.382q-.493.906-.493 2.106 0 1.07.428 1.975.428.89 1.332 1.432.906.526 2.255.526.973 0 1.668-.185l.044-.012.135-.04q.613-.184.984-.421l-.542-1.267q-.3.162-.642.274l-.297.087q-.51.131-1.3.131-.954 0-1.497-.444a1.6 1.6 0 0 1-.192-.193q-.366-.44-.512-1.234l-.004-.021zm-5.427-1.256-.003.022h3.752v-.138q-.011-.727-.288-1.118a1 1 0 0 0-.156-.176q-.46-.428-1.316-.428-.986 0-1.494.604-.379.45-.494 1.234zm-27.053 2.77V4.7h-1.86v12.095h5.333V15.15zm7.103-5.908v7.553h-1.843V9.242h1.843z'/%3E%3Cpath fill='%23fff' d='m19.63 11.151-.757-1.71-.345 1.71-1.12 5.644h-1.827L18.083 4.7h.197l3.325 6.533.988 2.19.988-2.19L26.839 4.7h.181l2.6 12.095h-1.81l-1.218-5.644-.362-1.71-.658 1.71-2.93 5.644h-.098l-2.913-5.644zm14.836 5.81q-1.02 0-1.893-.478a3.8 3.8 0 0 1-1.381-1.382q-.51-.906-.51-2.106 0-1.185.444-2.074a3.36 3.36 0 0 1 1.3-1.382q.839-.494 1.974-.494a3.3 3.3 0 0 1 1.234.231 3.3 3.3 0 0 1 .97.575q.396.33.527.659l.033-1.267h1.694v7.553H37.18l-.033-1.332q-.279.593-1.02 1.053a3.17 3.17 0 0 1-1.662.444zm.296-1.482q.938 0 1.58-.642.642-.66.642-1.711v-.115q0-.708-.296-1.267a2.2 2.2 0 0 0-.807-.872 2.1 2.1 0 0 0-1.119-.313q-1.053 0-1.629.692-.575.675-.575 1.76 0 1.103.559 1.795.577.675 1.645.675zm6.521-6.237h1.711v1.4q.906-1.597 2.83-1.597 1.596 0 2.584 1.02.988 1.005.988 2.914 0 1.185-.493 2.09a3.46 3.46 0 0 1-1.316 1.399 3.5 3.5 0 0 1-1.844.493q-.954 0-1.662-.329a2.67 2.67 0 0 1-1.086-.97l.017 5.134h-1.728zm4.048 6.22q1.07 0 1.645-.674.577-.69.576-1.762 0-1.119-.576-1.777-.558-.675-1.645-.675-.592 0-1.12.296-.51.28-.822.823-.296.527-.296 1.234v.115q0 .708.296 1.267.313.543.823.855.51.296 1.119.297z'/%3E%3Cpath fill='%23e1e3e9' d='M51.325 4.7h1.86v10.45h3.473v1.646h-5.333zm7.12 4.542h1.843v7.553h-1.843zm.905-1.415a1.16 1.16 0 0 1-.856-.346 1.17 1.17 0 0 1-.346-.856 1.05 1.05 0 0 1 .346-.79q.346-.329.856-.329.494 0 .839.33a1.05 1.05 0 0 1 .345.79 1.16 1.16 0 0 1-.345.855q-.33.346-.84.346zm7.875 9.133a3.17 3.17 0 0 1-1.662-.444q-.723-.46-1.004-1.053l-.033 1.332h-1.71V4.701h1.743v4.657l-.082 1.283q.279-.658 1.086-1.119a3.5 3.5 0 0 1 1.778-.477q1.119 0 1.942.51a3.24 3.24 0 0 1 1.283 1.4q.445.888.444 2.072 0 1.201-.526 2.09a3.5 3.5 0 0 1-1.382 1.366 3.8 3.8 0 0 1-1.876.477zm-.296-1.481q1.069 0 1.645-.675.577-.69.577-1.778 0-1.102-.577-1.776-.56-.691-1.645-.692a2.12 2.12 0 0 0-1.58.659q-.642.641-.642 1.694v.115q0 .71.296 1.267a2.4 2.4 0 0 0 .807.872 2.1 2.1 0 0 0 1.119.313zm5.927-6.237h1.777v1.481q.263-.757.856-1.217a2.14 2.14 0 0 1 1.349-.46q.527 0 .724.098l-.247 1.794q-.149-.099-.642-.099-.774 0-1.416.494-.626.493-.626 1.58v3.883h-1.777V9.242zm9.534 7.718q-1.35 0-2.255-.526-.904-.543-1.332-1.432a4.6 4.6 0 0 1-.428-1.975q0-1.2.493-2.106a3.46 3.46 0 0 1 1.4-1.382q.889-.495 2.007-.494 1.744 0 2.584.97.855.956.856 2.7 0 .444-.05.92h-5.43q.18 1.005.708 1.45.542.443 1.497.443.79 0 1.3-.131a4 4 0 0 0 .938-.362l.542 1.267q-.411.263-1.119.46-.708.198-1.711.197zm1.596-4.558q.016-1.02-.444-1.432-.46-.428-1.316-.428-1.728 0-1.991 1.86z'/%3E%3Cpath d='M5.074 15.948a.484.657 0 0 0-.486.659v1.84a.484.657 0 0 0 .486.659h4.101a.484.657 0 0 0 .486-.659v-1.84a.484.657 0 0 0-.486-.659zm3.56 1.16H5.617v.838h3.017z' style='fill:%23fff;fill-rule:evenodd;stroke-width:1.03600001'/%3E%3Cg style='stroke-width:1.12603545'%3E%3Cpath d='M-9.408-1.416c-3.833-.025-7.056 2.912-7.08 6.615-.02 3.08 1.653 4.832 3.107 6.268.903.892 1.721 1.74 2.32 2.902l-.525-.004c-.543-.003-.992.304-1.24.639a1.87 1.87 0 0 0-.362 1.121l-.011 1.877c-.003.402.104.787.347 1.125.244.338.688.653 1.23.656l4.142.028c.542.003.99-.306 1.238-.641a1.87 1.87 0 0 0 .363-1.121l.012-1.875a1.87 1.87 0 0 0-.348-1.127c-.243-.338-.688-.653-1.23-.656l-.518-.004c.597-1.145 1.425-1.983 2.348-2.87 1.473-1.414 3.18-3.149 3.2-6.226-.016-3.59-2.923-6.684-6.993-6.707m-.006 1.1v.002c3.274.02 5.92 2.532 5.9 5.6-.017 2.706-1.39 4.026-2.863 5.44-1.034.994-2.118 2.033-2.814 3.633-.018.041-.052.055-.075.065q-.013.004-.02.01a.34.34 0 0 1-.226.084.34.34 0 0 1-.224-.086l-.092-.077c-.699-1.615-1.768-2.669-2.781-3.67-1.454-1.435-2.797-2.762-2.78-5.478.02-3.067 2.7-5.545 5.975-5.523m-.02 2.826c-1.62-.01-2.944 1.315-2.955 2.96-.01 1.646 1.295 2.988 2.916 2.999h.002c1.621.01 2.943-1.316 2.953-2.961.011-1.646-1.294-2.988-2.916-2.998m-.005 1.1c1.017.006 1.829.83 1.822 1.89s-.83 1.874-1.848 1.867c-1.018-.006-1.829-.83-1.822-1.89s.83-1.874 1.848-1.868m-2.155 11.857 4.14.025c.271.002.49.305.487.676l-.013 1.875c-.003.37-.224.67-.495.668l-4.14-.025c-.27-.002-.487-.306-.485-.676l.012-1.875c.003-.37.224-.67.494-.668' style='color:%23000;font-style:normal;font-variant:normal;font-weight:400;font-stretch:normal;font-size:medium;line-height:normal;font-family:sans-serif;font-variant-ligatures:normal;font-variant-position:normal;font-variant-caps:normal;font-variant-numeric:normal;font-variant-alternates:normal;font-feature-settings:normal;text-indent:0;text-align:start;text-decoration:none;text-decoration-line:none;text-decoration-style:solid;text-decoration-color:%23000;letter-spacing:normal;word-spacing:normal;text-transform:none;writing-mode:lr-tb;direction:ltr;text-orientation:mixed;dominant-baseline:auto;baseline-shift:baseline;text-anchor:start;white-space:normal;shape-padding:0;clip-rule:evenodd;display:inline;overflow:visible;visibility:visible;opacity:1;isolation:auto;mix-blend-mode:normal;color-interpolation:sRGB;color-interpolation-filters:linearRGB;solid-color:%23000;solid-opacity:1;vector-effect:none;fill:%23000;fill-opacity:.4;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;color-rendering:auto;image-rendering:auto;shape-rendering:auto;text-rendering:auto' transform='translate(15.553 2.85)scale(.88807)'/%3E%3Cpath d='M-9.415-.316C-12.69-.338-15.37 2.14-15.39 5.207c-.017 2.716 1.326 4.041 2.78 5.477 1.013 1 2.081 2.055 2.78 3.67l.092.076a.34.34 0 0 0 .225.086.34.34 0 0 0 .227-.083l.019-.01c.022-.009.057-.024.074-.064.697-1.6 1.78-2.64 2.814-3.634 1.473-1.414 2.847-2.733 2.864-5.44.02-3.067-2.627-5.58-5.901-5.601m-.057 8.784c1.621.011 2.944-1.315 2.955-2.96.01-1.646-1.295-2.988-2.916-2.999-1.622-.01-2.945 1.315-2.955 2.96s1.295 2.989 2.916 3' style='clip-rule:evenodd;fill:%23e1e3e9;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:.4' transform='translate(15.553 2.85)scale(.88807)'/%3E%3Cpath d='M-11.594 15.465c-.27-.002-.492.297-.494.668l-.012 1.876c-.003.371.214.673.485.675l4.14.027c.271.002.492-.298.495-.668l.012-1.877c.003-.37-.215-.672-.485-.674z' style='clip-rule:evenodd;fill:%23fff;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:.4' transform='translate(15.553 2.85)scale(.88807)'/%3E%3C/g%3E%3C/svg%3E")}}@media(forced-colors:active)and (prefers-color-scheme:light){a.maplibregl-ctrl-logo{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='88' height='23' fill='none'%3E%3Cpath fill='%23000' fill-opacity='.4' fill-rule='evenodd' d='M17.408 16.796h-1.827l2.501-12.095h.198l3.324 6.533.988 2.19.988-2.19 3.258-6.533h.181l2.6 12.095h-1.81l-1.218-5.644-.362-1.71-.658 1.71-2.929 5.644h-.098l-2.914-5.644-.757-1.71-.345 1.71zm1.958-3.42-.726 3.663a1.255 1.255 0 0 1-1.232 1.011h-1.827a1.255 1.255 0 0 1-1.229-1.509l2.501-12.095a1.255 1.255 0 0 1 1.23-1.001h.197a1.25 1.25 0 0 1 1.12.685l3.19 6.273 3.125-6.263a1.25 1.25 0 0 1 1.123-.695h.181a1.255 1.255 0 0 1 1.227.991l1.443 6.71a5 5 0 0 1 .314-.787l.009-.016a4.6 4.6 0 0 1 1.777-1.887c.782-.46 1.668-.667 2.611-.667a4.6 4.6 0 0 1 1.7.32l.306.134c.21-.16.474-.256.759-.256h1.694a1.255 1.255 0 0 1 1.212.925 1.255 1.255 0 0 1 1.212-.925h1.711c.284 0 .545.094.755.252.613-.3 1.312-.45 2.075-.45 1.356 0 2.557.445 3.482 1.4q.47.48.763 1.064V4.701a1.255 1.255 0 0 1 1.255-1.255h1.86A1.255 1.255 0 0 1 54.44 4.7v9.194h2.217c.19 0 .37.043.532.118v-4.77c0-.356.147-.678.385-.906a2.42 2.42 0 0 1-.682-1.71c0-.665.267-1.253.735-1.7a2.45 2.45 0 0 1 1.722-.674 2.43 2.43 0 0 1 1.705.675q.318.302.504.683V4.7a1.255 1.255 0 0 1 1.255-1.255h1.744A1.255 1.255 0 0 1 65.812 4.7v3.335a4.8 4.8 0 0 1 1.526-.246c.938 0 1.817.214 2.59.69a4.47 4.47 0 0 1 1.67 1.743v-.98a1.255 1.255 0 0 1 1.256-1.256h1.777c.233 0 .451.064.639.174a3.4 3.4 0 0 1 1.567-.372c.346 0 .861.02 1.285.232a1.25 1.25 0 0 1 .689 1.004 4.7 4.7 0 0 1 .853-.588c.795-.44 1.675-.647 2.61-.647 1.385 0 2.65.39 3.525 1.396.836.938 1.168 2.173 1.168 3.528q-.001.515-.056 1.051a1.255 1.255 0 0 1-.947 1.09l.408.952a1.255 1.255 0 0 1-.477 1.552c-.418.268-.92.463-1.458.612-.613.171-1.304.244-2.049.244-1.06 0-2.043-.207-2.886-.698l-.015-.008c-.798-.48-1.419-1.135-1.818-1.963l-.004-.008a5.8 5.8 0 0 1-.548-2.512q0-.429.053-.843a1.3 1.3 0 0 1-.333-.086l-.166-.004c-.223 0-.426.062-.643.228-.03.024-.142.139-.142.59v3.883a1.255 1.255 0 0 1-1.256 1.256h-1.777a1.255 1.255 0 0 1-1.256-1.256V15.69l-.032.057a4.8 4.8 0 0 1-1.86 1.833 5.04 5.04 0 0 1-2.484.634 4.5 4.5 0 0 1-1.935-.424 1.25 1.25 0 0 1-.764.258h-1.71a1.255 1.255 0 0 1-1.256-1.255V7.687a2.4 2.4 0 0 1-.428.625c.253.23.412.561.412.93v7.553a1.255 1.255 0 0 1-1.256 1.255h-1.843a1.25 1.25 0 0 1-.894-.373c-.228.23-.544.373-.894.373H51.32a1.255 1.255 0 0 1-1.256-1.255v-1.251l-.061.117a4.7 4.7 0 0 1-1.782 1.884 4.77 4.77 0 0 1-2.485.67 5.6 5.6 0 0 1-1.485-.188l.009 2.764a1.255 1.255 0 0 1-1.255 1.259h-1.729a1.255 1.255 0 0 1-1.255-1.255v-3.537a1.255 1.255 0 0 1-1.167.793h-1.679a1.25 1.25 0 0 1-.77-.263 4.5 4.5 0 0 1-1.945.429c-.885 0-1.724-.21-2.495-.632l-.017-.01a5 5 0 0 1-1.081-.836 1.255 1.255 0 0 1-1.254 1.312h-1.81a1.255 1.255 0 0 1-1.228-.99l-.782-3.625-2.044 3.939a1.25 1.25 0 0 1-1.115.676h-.098a1.25 1.25 0 0 1-1.116-.68l-2.061-3.994zM35.92 16.63l.207-.114.223-.15q.493-.356.735-.785l.061-.118.033 1.332h1.678V9.242h-1.694l-.033 1.267q-.133-.329-.526-.658l-.032-.028a3.2 3.2 0 0 0-.668-.428l-.27-.12a3.3 3.3 0 0 0-1.235-.23q-1.136-.001-1.974.493a3.36 3.36 0 0 0-1.3 1.382q-.445.89-.444 2.074 0 1.2.51 2.107a3.8 3.8 0 0 0 1.382 1.381 3.9 3.9 0 0 0 1.893.477q.795 0 1.455-.33zm-2.789-5.38q-.576.675-.575 1.762 0 1.102.559 1.794.576.675 1.645.675a2.25 2.25 0 0 0 .934-.19 2.2 2.2 0 0 0 .468-.29l.178-.161a2.2 2.2 0 0 0 .397-.561q.244-.5.244-1.15v-.115q0-.708-.296-1.267l-.043-.077a2.2 2.2 0 0 0-.633-.709l-.13-.086-.047-.028a2.1 2.1 0 0 0-1.073-.285q-1.052 0-1.629.692zm2.316 2.706c.163-.17.28-.407.28-.83v-.114c0-.292-.06-.508-.15-.68a.96.96 0 0 0-.353-.389.85.85 0 0 0-.464-.127c-.4 0-.56.114-.664.239l-.01.012c-.148.174-.275.45-.275.945 0 .506.122.801.27.99.097.11.266.224.68.224.303 0 .504-.09.687-.269zm7.545 1.705a2.6 2.6 0 0 0 .331.423q.319.33.755.548l.173.074q.65.255 1.49.255 1.02 0 1.844-.493a3.45 3.45 0 0 0 1.316-1.4q.493-.904.493-2.089 0-1.909-.988-2.913-.988-1.02-2.584-1.02-.898 0-1.575.347a3 3 0 0 0-.415.262l-.199.166a3.4 3.4 0 0 0-.64.82V9.242h-1.712v11.553h1.729l-.017-5.134zm.53-1.138q.206.29.48.5l.155.11.053.034q.51.296 1.119.297 1.07 0 1.645-.675.577-.69.576-1.762 0-1.119-.576-1.777-.558-.675-1.645-.675-.435 0-.835.16a2 2 0 0 0-.284.136 2 2 0 0 0-.363.254 2.2 2.2 0 0 0-.46.569l-.082.162a2.6 2.6 0 0 0-.213 1.072v.115q0 .707.296 1.267l.135.211zm.964-.818a1.1 1.1 0 0 0 .367.385.94.94 0 0 0 .476.118c.423 0 .59-.117.687-.23.159-.194.28-.478.28-.95 0-.53-.133-.8-.266-.952l-.021-.025c-.078-.094-.231-.221-.68-.221a1 1 0 0 0-.503.135l-.012.007a.86.86 0 0 0-.335.343c-.073.133-.132.324-.132.614v.115a1.4 1.4 0 0 0 .14.66zm15.7-6.222q.347-.346.346-.856a1.05 1.05 0 0 0-.345-.79 1.18 1.18 0 0 0-.84-.329q-.51 0-.855.33a1.05 1.05 0 0 0-.346.79q0 .51.346.855.345.346.856.346.51 0 .839-.346zm4.337 9.314.033-1.332q.191.403.59.747l.098.081a4 4 0 0 0 .316.224l.223.122a3.2 3.2 0 0 0 1.44.322 3.8 3.8 0 0 0 1.875-.477 3.5 3.5 0 0 0 1.382-1.366q.527-.89.526-2.09 0-1.184-.444-2.073a3.24 3.24 0 0 0-1.283-1.399q-.823-.51-1.942-.51a3.5 3.5 0 0 0-1.527.344l-.086.043-.165.09a3 3 0 0 0-.33.214q-.432.315-.656.707a2 2 0 0 0-.099.198l.082-1.283V4.701h-1.744v12.095zm.473-2.509a2.5 2.5 0 0 0 .566.7q.117.098.245.18l.144.08a2.1 2.1 0 0 0 .975.232q1.07 0 1.645-.675.576-.69.576-1.778 0-1.102-.576-1.777-.56-.691-1.645-.692a2.2 2.2 0 0 0-1.015.235q-.22.113-.415.282l-.15.142a2.1 2.1 0 0 0-.42.594q-.223.479-.223 1.1v.115q0 .705.293 1.26zm2.616-.293c.157-.191.28-.479.28-.967 0-.51-.13-.79-.276-.961l-.021-.026c-.082-.1-.232-.225-.67-.225a.87.87 0 0 0-.681.279l-.012.011c-.154.155-.274.38-.274.807v.115c0 .285.057.499.144.669a1.1 1.1 0 0 0 .367.405c.137.082.28.123.455.123.423 0 .59-.118.686-.23zm8.266-3.013q.345-.13.724-.14l.069-.002q.493 0 .642.099l.247-1.794q-.196-.099-.717-.099a2.3 2.3 0 0 0-.545.063 2 2 0 0 0-.411.148 2.2 2.2 0 0 0-.4.249 2.5 2.5 0 0 0-.485.499 2.7 2.7 0 0 0-.32.581l-.05.137v-1.48h-1.778v7.553h1.777v-3.884q0-.546.159-.943a1.5 1.5 0 0 1 .466-.636 2.5 2.5 0 0 1 .399-.253 2 2 0 0 1 .224-.099zm9.784 2.656.05-.922q0-1.743-.856-2.698-.838-.97-2.584-.97-1.119-.001-2.007.493a3.46 3.46 0 0 0-1.4 1.382q-.493.906-.493 2.106 0 1.07.428 1.975.428.89 1.332 1.432.906.526 2.255.526.973 0 1.668-.185l.044-.012.135-.04q.613-.184.984-.421l-.542-1.267q-.3.162-.642.274l-.297.087q-.51.131-1.3.131-.954 0-1.497-.444a1.6 1.6 0 0 1-.192-.193q-.366-.44-.512-1.234l-.004-.021zm-5.427-1.256-.003.022h3.752v-.138q-.011-.727-.288-1.118a1 1 0 0 0-.156-.176q-.46-.428-1.316-.428-.986 0-1.494.604-.379.45-.494 1.234zm-27.053 2.77V4.7h-1.86v12.095h5.333V15.15zm7.103-5.908v7.553h-1.843V9.242h1.843z'/%3E%3Cpath fill='%23fff' d='m19.63 11.151-.757-1.71-.345 1.71-1.12 5.644h-1.827L18.083 4.7h.197l3.325 6.533.988 2.19.988-2.19L26.839 4.7h.181l2.6 12.095h-1.81l-1.218-5.644-.362-1.71-.658 1.71-2.93 5.644h-.098l-2.913-5.644zm14.836 5.81q-1.02 0-1.893-.478a3.8 3.8 0 0 1-1.381-1.382q-.51-.906-.51-2.106 0-1.185.444-2.074a3.36 3.36 0 0 1 1.3-1.382q.839-.494 1.974-.494a3.3 3.3 0 0 1 1.234.231 3.3 3.3 0 0 1 .97.575q.396.33.527.659l.033-1.267h1.694v7.553H37.18l-.033-1.332q-.279.593-1.02 1.053a3.17 3.17 0 0 1-1.662.444zm.296-1.482q.938 0 1.58-.642.642-.66.642-1.711v-.115q0-.708-.296-1.267a2.2 2.2 0 0 0-.807-.872 2.1 2.1 0 0 0-1.119-.313q-1.053 0-1.629.692-.575.675-.575 1.76 0 1.103.559 1.795.577.675 1.645.675zm6.521-6.237h1.711v1.4q.906-1.597 2.83-1.597 1.596 0 2.584 1.02.988 1.005.988 2.914 0 1.185-.493 2.09a3.46 3.46 0 0 1-1.316 1.399 3.5 3.5 0 0 1-1.844.493q-.954 0-1.662-.329a2.67 2.67 0 0 1-1.086-.97l.017 5.134h-1.728zm4.048 6.22q1.07 0 1.645-.674.577-.69.576-1.762 0-1.119-.576-1.777-.558-.675-1.645-.675-.592 0-1.12.296-.51.28-.822.823-.296.527-.296 1.234v.115q0 .708.296 1.267.313.543.823.855.51.296 1.119.297z'/%3E%3Cpath fill='%23e1e3e9' d='M51.325 4.7h1.86v10.45h3.473v1.646h-5.333zm7.12 4.542h1.843v7.553h-1.843zm.905-1.415a1.16 1.16 0 0 1-.856-.346 1.17 1.17 0 0 1-.346-.856 1.05 1.05 0 0 1 .346-.79q.346-.329.856-.329.494 0 .839.33a1.05 1.05 0 0 1 .345.79 1.16 1.16 0 0 1-.345.855q-.33.346-.84.346zm7.875 9.133a3.17 3.17 0 0 1-1.662-.444q-.723-.46-1.004-1.053l-.033 1.332h-1.71V4.701h1.743v4.657l-.082 1.283q.279-.658 1.086-1.119a3.5 3.5 0 0 1 1.778-.477q1.119 0 1.942.51a3.24 3.24 0 0 1 1.283 1.4q.445.888.444 2.072 0 1.201-.526 2.09a3.5 3.5 0 0 1-1.382 1.366 3.8 3.8 0 0 1-1.876.477zm-.296-1.481q1.069 0 1.645-.675.577-.69.577-1.778 0-1.102-.577-1.776-.56-.691-1.645-.692a2.12 2.12 0 0 0-1.58.659q-.642.641-.642 1.694v.115q0 .71.296 1.267a2.4 2.4 0 0 0 .807.872 2.1 2.1 0 0 0 1.119.313zm5.927-6.237h1.777v1.481q.263-.757.856-1.217a2.14 2.14 0 0 1 1.349-.46q.527 0 .724.098l-.247 1.794q-.149-.099-.642-.099-.774 0-1.416.494-.626.493-.626 1.58v3.883h-1.777V9.242zm9.534 7.718q-1.35 0-2.255-.526-.904-.543-1.332-1.432a4.6 4.6 0 0 1-.428-1.975q0-1.2.493-2.106a3.46 3.46 0 0 1 1.4-1.382q.889-.495 2.007-.494 1.744 0 2.584.97.855.956.856 2.7 0 .444-.05.92h-5.43q.18 1.005.708 1.45.542.443 1.497.443.79 0 1.3-.131a4 4 0 0 0 .938-.362l.542 1.267q-.411.263-1.119.46-.708.198-1.711.197zm1.596-4.558q.016-1.02-.444-1.432-.46-.428-1.316-.428-1.728 0-1.991 1.86z'/%3E%3Cpath d='M5.074 15.948a.484.657 0 0 0-.486.659v1.84a.484.657 0 0 0 .486.659h4.101a.484.657 0 0 0 .486-.659v-1.84a.484.657 0 0 0-.486-.659zm3.56 1.16H5.617v.838h3.017z' style='fill:%23fff;fill-rule:evenodd;stroke-width:1.03600001'/%3E%3Cg style='stroke-width:1.12603545'%3E%3Cpath d='M-9.408-1.416c-3.833-.025-7.056 2.912-7.08 6.615-.02 3.08 1.653 4.832 3.107 6.268.903.892 1.721 1.74 2.32 2.902l-.525-.004c-.543-.003-.992.304-1.24.639a1.87 1.87 0 0 0-.362 1.121l-.011 1.877c-.003.402.104.787.347 1.125.244.338.688.653 1.23.656l4.142.028c.542.003.99-.306 1.238-.641a1.87 1.87 0 0 0 .363-1.121l.012-1.875a1.87 1.87 0 0 0-.348-1.127c-.243-.338-.688-.653-1.23-.656l-.518-.004c.597-1.145 1.425-1.983 2.348-2.87 1.473-1.414 3.18-3.149 3.2-6.226-.016-3.59-2.923-6.684-6.993-6.707m-.006 1.1v.002c3.274.02 5.92 2.532 5.9 5.6-.017 2.706-1.39 4.026-2.863 5.44-1.034.994-2.118 2.033-2.814 3.633-.018.041-.052.055-.075.065q-.013.004-.02.01a.34.34 0 0 1-.226.084.34.34 0 0 1-.224-.086l-.092-.077c-.699-1.615-1.768-2.669-2.781-3.67-1.454-1.435-2.797-2.762-2.78-5.478.02-3.067 2.7-5.545 5.975-5.523m-.02 2.826c-1.62-.01-2.944 1.315-2.955 2.96-.01 1.646 1.295 2.988 2.916 2.999h.002c1.621.01 2.943-1.316 2.953-2.961.011-1.646-1.294-2.988-2.916-2.998m-.005 1.1c1.017.006 1.829.83 1.822 1.89s-.83 1.874-1.848 1.867c-1.018-.006-1.829-.83-1.822-1.89s.83-1.874 1.848-1.868m-2.155 11.857 4.14.025c.271.002.49.305.487.676l-.013 1.875c-.003.37-.224.67-.495.668l-4.14-.025c-.27-.002-.487-.306-.485-.676l.012-1.875c.003-.37.224-.67.494-.668' style='color:%23000;font-style:normal;font-variant:normal;font-weight:400;font-stretch:normal;font-size:medium;line-height:normal;font-family:sans-serif;font-variant-ligatures:normal;font-variant-position:normal;font-variant-caps:normal;font-variant-numeric:normal;font-variant-alternates:normal;font-feature-settings:normal;text-indent:0;text-align:start;text-decoration:none;text-decoration-line:none;text-decoration-style:solid;text-decoration-color:%23000;letter-spacing:normal;word-spacing:normal;text-transform:none;writing-mode:lr-tb;direction:ltr;text-orientation:mixed;dominant-baseline:auto;baseline-shift:baseline;text-anchor:start;white-space:normal;shape-padding:0;clip-rule:evenodd;display:inline;overflow:visible;visibility:visible;opacity:1;isolation:auto;mix-blend-mode:normal;color-interpolation:sRGB;color-interpolation-filters:linearRGB;solid-color:%23000;solid-opacity:1;vector-effect:none;fill:%23000;fill-opacity:.4;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;color-rendering:auto;image-rendering:auto;shape-rendering:auto;text-rendering:auto' transform='translate(15.553 2.85)scale(.88807)'/%3E%3Cpath d='M-9.415-.316C-12.69-.338-15.37 2.14-15.39 5.207c-.017 2.716 1.326 4.041 2.78 5.477 1.013 1 2.081 2.055 2.78 3.67l.092.076a.34.34 0 0 0 .225.086.34.34 0 0 0 .227-.083l.019-.01c.022-.009.057-.024.074-.064.697-1.6 1.78-2.64 2.814-3.634 1.473-1.414 2.847-2.733 2.864-5.44.02-3.067-2.627-5.58-5.901-5.601m-.057 8.784c1.621.011 2.944-1.315 2.955-2.96.01-1.646-1.295-2.988-2.916-2.999-1.622-.01-2.945 1.315-2.955 2.96s1.295 2.989 2.916 3' style='clip-rule:evenodd;fill:%23e1e3e9;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:.4' transform='translate(15.553 2.85)scale(.88807)'/%3E%3Cpath d='M-11.594 15.465c-.27-.002-.492.297-.494.668l-.012 1.876c-.003.371.214.673.485.675l4.14.027c.271.002.492-.298.495-.668l.012-1.877c.003-.37-.215-.672-.485-.674z' style='clip-rule:evenodd;fill:%23fff;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:.4' transform='translate(15.553 2.85)scale(.88807)'/%3E%3C/g%3E%3C/svg%3E")}}.maplibregl-ctrl.maplibregl-ctrl-attrib{background-color:#ffffff80;margin:0;padding:0 5px}@media screen{.maplibregl-ctrl-attrib.maplibregl-compact{background-color:#fff;border-radius:12px;box-sizing:content-box;color:#000;margin:10px;min-height:20px;padding:2px 24px 2px 0;position:relative}.maplibregl-ctrl-attrib.maplibregl-compact-show{padding:2px 28px 2px 8px;visibility:visible}.maplibregl-ctrl-bottom-left>.maplibregl-ctrl-attrib.maplibregl-compact-show,.maplibregl-ctrl-top-left>.maplibregl-ctrl-attrib.maplibregl-compact-show{border-radius:12px;padding:2px 8px 2px 28px}.maplibregl-ctrl-attrib.maplibregl-compact .maplibregl-ctrl-attrib-inner{display:none}.maplibregl-ctrl-attrib-button{background-color:#ffffff80;background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' fill-rule='evenodd' viewBox='0 0 20 20'%3E%3Cpath d='M4 10a6 6 0 1 0 12 0 6 6 0 1 0-12 0m5-3a1 1 0 1 0 2 0 1 1 0 1 0-2 0m0 3a1 1 0 1 1 2 0v3a1 1 0 1 1-2 0'/%3E%3C/svg%3E");border:0;border-radius:12px;box-sizing:border-box;cursor:pointer;display:none;height:24px;outline:none;position:absolute;right:0;top:0;width:24px}.maplibregl-ctrl-attrib summary.maplibregl-ctrl-attrib-button{-webkit-appearance:none;-moz-appearance:none;appearance:none;list-style:none}.maplibregl-ctrl-attrib summary.maplibregl-ctrl-attrib-button::-webkit-details-marker{display:none}.maplibregl-ctrl-bottom-left .maplibregl-ctrl-attrib-button,.maplibregl-ctrl-top-left .maplibregl-ctrl-attrib-button{left:0}.maplibregl-ctrl-attrib.maplibregl-compact .maplibregl-ctrl-attrib-button,.maplibregl-ctrl-attrib.maplibregl-compact-show .maplibregl-ctrl-attrib-inner{display:block}.maplibregl-ctrl-attrib.maplibregl-compact-show .maplibregl-ctrl-attrib-button{background-color:#0000000d}.maplibregl-ctrl-bottom-right>.maplibregl-ctrl-attrib.maplibregl-compact:after{bottom:0;right:0}.maplibregl-ctrl-top-right>.maplibregl-ctrl-attrib.maplibregl-compact:after{right:0;top:0}.maplibregl-ctrl-top-left>.maplibregl-ctrl-attrib.maplibregl-compact:after{left:0;top:0}.maplibregl-ctrl-bottom-left>.maplibregl-ctrl-attrib.maplibregl-compact:after{bottom:0;left:0}}@media screen and (forced-colors:active){.maplibregl-ctrl-attrib.maplibregl-compact:after{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' fill='%23fff' fill-rule='evenodd' viewBox='0 0 20 20'%3E%3Cpath d='M4 10a6 6 0 1 0 12 0 6 6 0 1 0-12 0m5-3a1 1 0 1 0 2 0 1 1 0 1 0-2 0m0 3a1 1 0 1 1 2 0v3a1 1 0 1 1-2 0'/%3E%3C/svg%3E")}}@media screen and (forced-colors:active)and (prefers-color-scheme:light){.maplibregl-ctrl-attrib.maplibregl-compact:after{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' fill-rule='evenodd' viewBox='0 0 20 20'%3E%3Cpath d='M4 10a6 6 0 1 0 12 0 6 6 0 1 0-12 0m5-3a1 1 0 1 0 2 0 1 1 0 1 0-2 0m0 3a1 1 0 1 1 2 0v3a1 1 0 1 1-2 0'/%3E%3C/svg%3E")}}.maplibregl-ctrl-attrib a{color:#000000bf;text-decoration:none}.maplibregl-ctrl-attrib a:hover{color:inherit;text-decoration:underline}.maplibregl-attrib-empty{display:none}.maplibregl-ctrl-scale{background-color:#ffffffbf;border:2px solid #333;border-top:#333;box-sizing:border-box;color:#333;font-size:10px;padding:0 5px;white-space:nowrap}.maplibregl-popup{display:flex;left:0;pointer-events:none;position:absolute;top:0;will-change:transform}.maplibregl-popup-anchor-top,.maplibregl-popup-anchor-top-left,.maplibregl-popup-anchor-top-right{flex-direction:column}.maplibregl-popup-anchor-bottom,.maplibregl-popup-anchor-bottom-left,.maplibregl-popup-anchor-bottom-right{flex-direction:column-reverse}.maplibregl-popup-anchor-left{flex-direction:row}.maplibregl-popup-anchor-right{flex-direction:row-reverse}.maplibregl-popup-tip{border:10px solid transparent;height:0;width:0;z-index:1}.maplibregl-popup-anchor-top .maplibregl-popup-tip{align-self:center;border-bottom-color:#fff;border-top:none}.maplibregl-popup-anchor-top-left .maplibregl-popup-tip{align-self:flex-start;border-bottom-color:#fff;border-left:none;border-top:none}.maplibregl-popup-anchor-top-right .maplibregl-popup-tip{align-self:flex-end;border-bottom-color:#fff;border-right:none;border-top:none}.maplibregl-popup-anchor-bottom .maplibregl-popup-tip{align-self:center;border-bottom:none;border-top-color:#fff}.maplibregl-popup-anchor-bottom-left .maplibregl-popup-tip{align-self:flex-start;border-bottom:none;border-left:none;border-top-color:#fff}.maplibregl-popup-anchor-bottom-right .maplibregl-popup-tip{align-self:flex-end;border-bottom:none;border-right:none;border-top-color:#fff}.maplibregl-popup-anchor-left .maplibregl-popup-tip{align-self:center;border-left:none;border-right-color:#fff}.maplibregl-popup-anchor-right .maplibregl-popup-tip{align-self:center;border-left-color:#fff;border-right:none}[dir=rtl] .maplibregl-popup-anchor-left{flex-direction:row-reverse}[dir=rtl] .maplibregl-popup-anchor-right{flex-direction:row}[dir=rtl] .maplibregl-popup-anchor-top-left .maplibregl-popup-tip{align-self:flex-end}[dir=rtl] .maplibregl-popup-anchor-top-right .maplibregl-popup-tip{align-self:flex-start}[dir=rtl] .maplibregl-popup-anchor-bottom-left .maplibregl-popup-tip{align-self:flex-end}[dir=rtl] .maplibregl-popup-anchor-bottom-right .maplibregl-popup-tip{align-self:flex-start}.maplibregl-popup-close-button{background-color:transparent;border:0;border-radius:0 3px 0 0;cursor:pointer;position:absolute;right:0;top:0}.maplibregl-popup-close-button:hover{background-color:#0000000d}.maplibregl-popup-content{background:#fff;border-radius:3px;box-shadow:0 1px 2px #0000001a;padding:15px 10px;pointer-events:auto;position:relative}.maplibregl-popup-anchor-top-left .maplibregl-popup-content{border-top-left-radius:0}.maplibregl-popup-anchor-top-right .maplibregl-popup-content{border-top-right-radius:0}.maplibregl-popup-anchor-bottom-left .maplibregl-popup-content{border-bottom-left-radius:0}.maplibregl-popup-anchor-bottom-right .maplibregl-popup-content{border-bottom-right-radius:0}.maplibregl-popup-track-pointer{display:none}.maplibregl-popup-track-pointer *{pointer-events:none;-webkit-user-select:none;-moz-user-select:none;user-select:none}.maplibregl-map:hover .maplibregl-popup-track-pointer{display:flex}.maplibregl-map:active .maplibregl-popup-track-pointer{display:none}.maplibregl-marker{left:0;position:absolute;top:0;transition:opacity .2s;will-change:transform}.maplibregl-user-location-dot,.maplibregl-user-location-dot:before{background-color:#1da1f2;border-radius:50%;height:15px;width:15px}.maplibregl-user-location-dot:before{animation:maplibregl-user-location-dot-pulse 2s infinite;content:"";position:absolute}.maplibregl-user-location-dot:after{border:2px solid #fff;border-radius:50%;box-shadow:0 0 3px #00000059;box-sizing:border-box;content:"";height:19px;left:-2px;position:absolute;top:-2px;width:19px}@media(prefers-reduced-motion:reduce){.maplibregl-user-location-dot:before{animation:none}}@keyframes maplibregl-user-location-dot-pulse{0%{opacity:1;transform:scale(1)}70%{opacity:0;transform:scale(3)}to{opacity:0;transform:scale(1)}}.maplibregl-user-location-dot-stale{background-color:#aaa}.maplibregl-user-location-dot-stale:after{display:none}.maplibregl-user-location-accuracy-circle{background-color:#1da1f233;border-radius:100%;height:1px;width:1px}.maplibregl-crosshair,.maplibregl-crosshair .maplibregl-interactive,.maplibregl-crosshair .maplibregl-interactive:active{cursor:crosshair}.maplibregl-boxzoom{background:#fff;border:2px dotted #202020;height:0;left:0;opacity:.5;position:absolute;top:0;width:0}.maplibregl-cooperative-gesture-screen{align-items:center;background:#0006;color:#fff;display:flex;font-size:1.4em;inset:0;justify-content:center;line-height:1.2;opacity:0;padding:1rem;pointer-events:none;position:absolute;transition:opacity 1s ease 1s;z-index:99999}.maplibregl-cooperative-gesture-screen.maplibregl-show{opacity:1;transition:opacity .05s}.maplibregl-cooperative-gesture-screen .maplibregl-mobile-message{display:none}@media(hover:none),(pointer:coarse){.maplibregl-cooperative-gesture-screen .maplibregl-desktop-message{display:none}.maplibregl-cooperative-gesture-screen .maplibregl-mobile-message{display:block}}.maplibregl-pseudo-fullscreen{height:100%!important;left:0!important;position:fixed!important;top:0!important;width:100%!important;z-index:99999}html{height:100%;overflow:hidden;overscroll-behavior:none}body.app-shell{position:fixed;inset:0;width:100%;height:100dvh;min-height:100dvh;max-height:100dvh;overflow:hidden;overscroll-behavior:none;grid-template-rows:var(--header-height, 64px) minmax(0,1fr)}body.app-shell .app-header{grid-row:1;position:fixed;top:0;right:0;left:0;height:var(--header-height, 64px);min-height:var(--header-height, 64px);max-height:var(--header-height, 64px);z-index:10000;transform:translateZ(0)}.mobile-pane-toggle{display:none}body.app-shell .app-main{grid-row:2;height:calc(100dvh - var(--header-height, 64px));min-height:0}@supports not (height: 100dvh){body.app-shell{height:100vh;min-height:100vh;max-height:100vh}body.app-shell .app-main{height:calc(100vh - var(--header-height, 64px))}}.app-shell{--map-min-height: 220px;--timeline-row-height: 58px;--test2-election-pane-height: min(38vh, max(120px, calc(100vh - var(--header-height, 64px) - var(--map-min-height, 220px) - var(--timeline-row-height, 58px) - 6px)))}.pane--map{min-height:0}#map,#map .maplibregl-map,#map .maplibregl-canvas-container,#map .maplibregl-canvas{touch-action:none!important;overscroll-behavior:contain;-webkit-user-select:none;user-select:none;-webkit-touch-callout:none}#map .maplibregl-canvas{pointer-events:auto}.pane--map>#timelineSlider.timeline-slider{position:static;inset:auto;z-index:auto;display:flex;flex:0 0 auto;align-items:center;justify-content:center;gap:var(--space-3);width:100%;max-width:none;height:auto;min-height:var(--timeline-row-height);margin:0;padding:var(--space-2) var(--space-4);appearance:none;background:var(--color-surface);border:1px solid var(--color-border);border-right:0;border-left:0;border-radius:0;box-shadow:none;cursor:default;transform:none}.pane--map>#timelineSlider.timeline-slider.hidden{display:none}.pane--map>#timelineSlider.timeline-slider .timeline-range{width:clamp(86px,22vw,220px)}.pane--map>#timelineSlider.timeline-slider .timeline-label{max-width:min(32vw,180px)}.pane--map>#timelineSlider.timeline-slider .timeline-playback-group{display:flex;align-items:center;gap:2px;flex:0 0 auto}.pane--map>#timelineSlider.timeline-slider .timeline-btn--play.is-playing,.pane--map>#timelineSlider.timeline-slider .timeline-btn--play.is-replay{color:#fff;background:var(--color-primary);border-color:var(--color-primary)}.pane--map>#timelineSlider.timeline-slider .timeline-btn--stop:not(:disabled){color:var(--color-danger, #b91c1c);border-color:color-mix(in srgb,var(--color-danger, #b91c1c) 42%,var(--color-border))}.pane--map>#timelineSlider.timeline-slider .timeline-btn--stop:hover:not(:disabled){color:#fff;background:var(--color-danger, #b91c1c);border-color:var(--color-danger, #b91c1c)}.maplibregl-ctrl-attrib a{color:#064f63;text-decoration:underline;text-underline-offset:2px}#map .maplibregl-ctrl-top-left{top:10px;left:12px;display:none}#map .maplibregl-ctrl-top-right{top:56px;right:12px}#map .maplibregl-ctrl-bottom-left{bottom:14px;left:12px}#map .maplibregl-ctrl-bottom-right{right:12px;bottom:14px}#map .maplibregl-ctrl-group{border:1px solid #b7c1c8;border-radius:4px;box-shadow:0 1px 5px #00000059;overflow:hidden}#map .maplibregl-ctrl-group button{width:30px;height:30px;background:#fff;color:#111827}#map .maplibregl-ctrl-group button+button{border-top:1px solid #cfd7df}#map .maplibregl-ctrl-compass{display:none}#map .test2-main-control-stack{position:absolute;top:10px;left:12px;z-index:15;display:flex;flex-direction:column;align-items:flex-start;gap:6px;pointer-events:none}#map .test2-main-control-stack>*{pointer-events:auto}#map .test2-main-zoom-control{position:static;margin:0;border:1px solid rgba(0,0,0,.35);border-radius:4px;background:#fff;box-shadow:0 1px 5px #00000059;overflow:hidden}#map .test2-main-zoom-control__button{display:block;width:30px;height:30px;padding:0;border:0;border-bottom:1px solid #cfd7df;background:#fff;color:#000;font:700 22px/28px Arial,Helvetica,sans-serif;text-align:center;cursor:pointer}#map .test2-main-zoom-control__button:last-child{border-bottom:0}#map .test2-main-zoom-control__button:hover,#map .test2-main-zoom-control__button:focus-visible{background:#f4f4f4;outline:none}#map .test2-main-zoom-control__compass{display:grid;place-items:center}#map .test2-main-zoom-control__compass-icon{width:18px;height:18px;fill:#111827;transform-origin:50% 50%;transition:transform .12s ease,fill .12s ease}#map .test2-main-zoom-control__compass--active .test2-main-zoom-control__compass-icon{fill:#064f63}#map #mobileToggle.mobile-toggle.mobile-toggle--map-stack{display:none}#map .maplibregl-ctrl-zoom-in .maplibregl-ctrl-icon,#map .maplibregl-ctrl-zoom-out .maplibregl-ctrl-icon{background-image:none;display:grid;place-items:center;font:700 21px/1 Arial,Helvetica,sans-serif}#map .maplibregl-ctrl-zoom-in .maplibregl-ctrl-icon:before{content:"+"}#map .maplibregl-ctrl-zoom-out .maplibregl-ctrl-icon:before{content:"-"}#map .active-layers-toggle{top:14px!important;right:14px!important}#map .map-controls{bottom:14px;left:14px;pointer-events:none}#map .map-controls>*{pointer-events:auto}.test2-election-seat-overlay{position:absolute;inset:0;z-index:18;pointer-events:none}.test2-election-seat-circle{background:transparent!important;border:0!important;box-shadow:none!important;pointer-events:auto;cursor:pointer}.test2-election-seat-circle:focus-visible{outline:2px solid #f97316;outline-offset:3px;border-radius:999px}.test2-election-seat-circle--synthetic{z-index:19}.test2-election-synthetic-label{height:18px;padding:1px 5px 2px;border:1px solid rgba(17,24,39,.72);border-radius:4px;background:#fffffff0;box-shadow:0 0 0 1px #ffffffd1,0 1px 3px #0003;color:#0f3764;font:700 11px/14px Arial,Helvetica,sans-serif;text-align:center;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;pointer-events:none}.test2-election-seat-dot{display:block;border-radius:50%;border:1px solid rgba(0,0,0,.6);box-shadow:0 0 0 1px #fff,0 .5px 2px #00000026}@media(max-width:768px){.app-shell{--map-min-height: 180px;--timeline-row-height: 54px}body.app-shell .app-header{gap:8px}body.app-shell .mobile-pane-toggle{display:inline-flex;align-items:center;justify-content:center;flex:0 0 auto;order:98;width:38px;height:38px;margin-left:auto;padding:0;color:#fff;background:#ffffff29;border:1px solid rgba(255,255,255,.28);border-radius:8px;box-shadow:0 1px 6px #00000038;font:700 22px/1 Arial,Helvetica,sans-serif;cursor:pointer;touch-action:manipulation}body.app-shell .mobile-pane-toggle:hover,body.app-shell .mobile-pane-toggle:focus-visible{background:#ffffff3d;outline:2px solid rgba(255,255,255,.55);outline-offset:2px}body.app-shell .mobile-menu-toggle{order:99;margin-left:0}.pane--map>#timelineSlider.timeline-slider{gap:6px;min-height:var(--timeline-row-height);padding:6px 8px}.pane--map>#timelineSlider.timeline-slider .timeline-range{width:clamp(76px,26vw,140px)}.pane--map>#timelineSlider.timeline-slider .timeline-label{max-width:96px}.pane--map>#timelineSlider.timeline-slider .timeline-playback-group{gap:1px}.pane--map>#timelineSlider.timeline-slider .timeline-btn{width:30px;height:30px}#map .maplibregl-ctrl-top-left{top:12px;left:12px}#map .active-layers-toggle{top:14px!important;right:14px!important}#map .map-controls{bottom:14px;left:12px;max-width:min(280px,calc(100vw - 104px))}#map .maplibregl-ctrl-bottom-right{right:12px;bottom:14px}#map #mobileToggle.mobile-toggle.mobile-toggle--map-stack{position:static!important;inset:auto!important;display:inline-flex!important;align-items:center;justify-content:center;flex:0 0 auto;width:32px;height:32px;margin:0;padding:0;color:#111827;background:#fff;border:1px solid rgba(0,0,0,.35);border-radius:4px;box-shadow:0 1px 5px #00000059;z-index:auto}#map #mobileToggle.mobile-toggle.mobile-toggle--map-stack:hover,#map #mobileToggle.mobile-toggle.mobile-toggle--map-stack:focus-visible{background:#f4f4f4}.maplibre-dom-label,.maplibre-dom-label *,.test2-election-seat-circle,.test2-election-seat-circle *{pointer-events:none!important}.test2-election-seat-circle[data-non-geographic=true]{touch-action:manipulation}}@media(min-width:769px){#map #mobileToggle.mobile-toggle.mobile-toggle--map-stack{display:none!important}}body.app-shell.test2-election-open{position:relative}body.app-shell.test2-election-open .pane--map{height:calc(100% - var(--test2-election-pane-height));min-height:var(--map-min-height, 220px)}body.app-shell.test2-election-open #electionResultsPane.election-results-pane--open{display:flex;flex-direction:column;overflow:hidden}.test2-election-pane-resizer{position:relative;flex:0 0 12px;width:100%;min-height:12px;cursor:row-resize;background:var(--color-border, #d8e0ea);border-top:1px solid #174569;border-bottom:1px solid #c4ced8;touch-action:none;z-index:20;user-select:none}.test2-election-pane-resizer:before{content:"";position:absolute;top:5px;left:50%;width:56px;height:2px;transform:translate(-50%);border-radius:999px;background:#5f7184}.test2-election-pane-resizer:hover,.test2-election-pane-resizer:focus-visible,body.test2-election-pane-resizing .test2-election-pane-resizer{background:#bdd7f3;outline:none}[data-theme=dark] .test2-election-pane-resizer{background:#314155;border-top-color:#6aa1d8;border-bottom-color:#172233}[data-theme=dark] .test2-election-pane-resizer:before{background:#d8e7f8}@media(prefers-color-scheme:dark){:root:not([data-theme=light]) .test2-election-pane-resizer{background:#314155;border-top-color:#6aa1d8;border-bottom-color:#172233}:root:not([data-theme=light]) .test2-election-pane-resizer:before{background:#d8e7f8}}body.test2-election-pane-resizing,body.test2-election-pane-resizing *{cursor:row-resize!important;user-select:none!important}[data-theme=dark] .maplibregl-ctrl-attrib,:root:not([data-theme=light]) .maplibregl-ctrl-attrib{background:#0f1419d9;color:#e6edf3}[data-theme=dark] .maplibregl-ctrl-attrib a,:root:not([data-theme=light]) .maplibregl-ctrl-attrib a{color:#8fd3ff}[data-theme=dark] .maplibregl-ctrl-group,:root:not([data-theme=light]) .maplibregl-ctrl-group{background:#1b2027}[data-theme=dark] .maplibregl-ctrl-group button,:root:not([data-theme=light]) .maplibregl-ctrl-group button{background:#1b2027}[data-theme=dark] .maplibregl-ctrl-group button+button,:root:not([data-theme=light]) .maplibregl-ctrl-group button+button{border-top-color:#333b45}[data-theme=dark] .maplibregl-ctrl-group button .maplibregl-ctrl-icon,:root:not([data-theme=light]) .maplibregl-ctrl-group button .maplibregl-ctrl-icon{filter:invert(1) brightness(1.6)}.maplibre-dom-label{display:inline-flex;align-items:center;justify-content:center;pointer-events:auto!important;cursor:pointer;z-index:4}.maplibre-dom-label div{position:relative;width:max-content;max-width:140px;color:#38f;font-weight:700;line-height:1.15;text-align:center;overflow-wrap:normal;word-break:keep-all;text-shadow:-1px -1px 0 #fff,1px -1px 0 #fff,-1px 1px 0 #fff,1px 1px 0 #fff;transition:color .12s ease,text-shadow .12s ease,text-decoration-color .12s ease}.maplibre-dom-label.map-label--hover div,.maplibre-dom-label.map-label--selected div,.maplibre-dom-label:hover div{color:#ff7a1a!important;text-decoration:underline;text-decoration-color:currentColor;text-underline-offset:2px;text-shadow:-1px -1px 0 #fff,1px -1px 0 #fff,-1px 1px 0 #fff,1px 1px 0 #fff}@media(max-width:768px),(pointer:coarse){#map .maplibregl-canvas-container,#map .maplibregl-canvas{touch-action:none!important}#map .test2-election-seat-overlay,#map .maplibre-dom-label,#map .maplibre-dom-label *,#map .test2-election-seat-circle,#map .test2-election-seat-circle *{pointer-events:none!important}}#test2Status.map-error{position:absolute;left:16px;bottom:18px;z-index:30;max-width:min(420px,calc(100% - 32px));padding:10px 12px;border:1px solid #f59e0b;border-radius:8px;background:#fffbeb;color:#78350f;box-shadow:0 8px 20px #0000001f;font-size:13px}.test2-source-panel{position:fixed;top:76px;right:18px;z-index:520;width:min(420px,calc(100% - 36px));max-height:min(620px,calc(100% - 110px));display:flex;flex-direction:column;border:1px solid var(--color-border, #d8e0ea);border-radius:8px;background:var(--color-surface, #fff);color:var(--color-text, #1a202c);box-shadow:0 16px 36px #0f172a2e;overflow:hidden}.test2-source-panel.hidden{display:none}.test2-source-panel__header{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:10px 12px;border-bottom:1px solid var(--color-border, #d8e0ea);background:var(--color-surface-elevated, #f7fafc)}.test2-source-panel__header h3,.test2-source-panel__record h4{margin:0;font-size:14px;line-height:1.25}.test2-source-panel__close,.test2-source-panel button{border:1px solid var(--color-border, #d8e0ea);border-radius:6px;background:var(--color-surface, #fff);color:var(--color-text, #1a202c);font:inherit;font-size:12px;line-height:1;padding:6px 8px;cursor:pointer}.test2-source-panel__content{overflow:auto;padding:12px}.test2-source-panel__record{display:grid;gap:10px;padding-bottom:14px}.test2-source-panel__record+.test2-source-panel__record{padding-top:14px;border-top:1px solid var(--color-border, #d8e0ea)}.test2-source-panel__record header,.test2-source-panel__record dl div,.test2-source-panel__link-row{display:flex;align-items:flex-start;justify-content:space-between;gap:10px}.test2-source-panel__record dl{display:grid;gap:6px;margin:0;font-size:12px}.test2-source-panel__record dt{color:var(--color-text-muted, #718096);font-weight:700;text-transform:uppercase}.test2-source-panel__record dd{margin:0;text-align:right;word-break:break-word}.test2-source-panel__record p,.test2-source-panel__group p,.test2-source-panel__link-row small{margin:0;color:var(--color-text-muted, #718096);font-size:12px;line-height:1.35}.test2-source-panel__group{border:1px solid var(--color-border, #d8e0ea);border-radius:6px;padding:8px}.test2-source-panel__group summary{cursor:pointer;font-size:12px;font-weight:700}.test2-source-panel__link-row{padding-top:8px;font-size:12px}.test2-source-panel__link-row a{min-width:0;overflow-wrap:anywhere;text-decoration:underline;text-underline-offset:2px}.test2-source-btn span{display:inline-flex;align-items:center;justify-content:center;width:14px;height:14px;border:1px solid currentColor;border-radius:999px;font-size:10px;font-weight:700;font-style:italic}.test2-election-panel{position:static;width:100%;max-height:none;overflow:visible;background:var(--color-surface, #fff);color:var(--color-text, #1a202c);border:0;border-radius:0;box-shadow:none;padding:0}.test2-election-panel.hidden{display:none}.test2-election-panel__header{display:flex;align-items:flex-start;justify-content:space-between;gap:12px;border-bottom:1px solid var(--color-border, #d8e0ea);padding-bottom:10px;margin-bottom:10px}.test2-election-panel__header h3{margin:0;font-size:15px;line-height:1.2}.test2-election-panel__header p,.test2-election-panel__eyebrow{margin:0;color:var(--color-text-muted, #718096);font-size:12px}.test2-election-panel__header button{min-height:32px;padding:4px 10px}.test2-election-panel__mode{display:grid;gap:4px;margin-bottom:10px;font-size:12px;font-weight:700}.test2-election-turnout__note{margin:0 0 12px;font-size:12px;line-height:1.45;color:var(--test2-muted, #55606b)}.test2-election-panel__mode--inline{display:inline-flex;align-items:center;gap:6px;margin:0;white-space:nowrap}.test2-election-panel__mode--inline select{max-width:150px}.flat-election-entry--loading{opacity:.78;pointer-events:none}.flat-election-entry--active{background:#dbeafe6b;box-shadow:inset 3px 0 0 var(--color-primary, #1a365d)}[data-theme=dark] .flat-election-entry--active{background:#1d2b3d;box-shadow:inset 3px 0 #8fb4ff}[data-theme=dark] .flat-election-entry--active .flat-election-date{color:#f7fafc}[data-theme=dark] .flat-election-entry--active .flat-election-body,[data-theme=dark] .flat-election-entry--active .flat-election-separator{color:#eef6ff}.flat-election-link{font-family:inherit;font-variant-numeric:normal}.flat-election-date{font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,Liberation Mono,monospace;font-variant-numeric:tabular-nums;font-weight:var(--font-semibold, 600);color:var(--color-text, #1a202c)}.flat-election-separator{color:var(--color-text-muted, #718096)}.flat-election-body{font-family:var(--font-sans, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif);font-variant-numeric:normal;font-size:.72rem;font-style:normal;font-weight:700;color:var(--color-text, #1a202c)}.flat-election-entry--loading .election-load-btn{position:relative}.flat-election-entry--loading .election-load-btn:after{content:"";position:absolute;inset:6px;border:2px solid currentColor;border-right-color:transparent;border-radius:999px;animation:test2ElectionSpin .8s linear infinite}.flat-election-entry--loading .election-load-btn>*{opacity:0}.test2-election-loading,.test2-election-loading-badge{color:var(--color-text-muted, #718096);font-size:12px}.test2-election-loading{display:grid;gap:4px}.test2-election-loading-badge{display:inline-flex;align-items:center;min-height:28px;padding:2px 8px;border:1px solid var(--color-border, #d8e0ea);border-radius:999px;background:var(--color-surface-elevated, #f7fafc);font-weight:700}@keyframes test2ElectionSpin{to{transform:rotate(360deg)}}.test2-election-local-mode{display:inline-flex;align-items:center;gap:2px;padding:2px;border:1px solid var(--color-border, #d8e0ea);border-radius:6px;background:var(--color-surface-elevated, #f7fafc)}.test2-election-local-mode button{min-height:28px;padding:3px 8px;border:0;border-radius:4px;background:transparent;color:var(--color-text-muted, #718096);font-size:12px;font-weight:700;cursor:pointer}.test2-election-local-mode button.is-active{background:var(--color-primary, #1a365d);color:#fff}.election-pane__title-link{appearance:none;border:0;background:transparent;color:inherit;font:inherit;font-weight:inherit;padding:0;margin:0;text-align:left;cursor:pointer;text-decoration:none;max-width:100%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.election-pane__title-link:hover,.election-pane__title-link:focus-visible{text-decoration:underline}.test2-election-panel__summary{display:grid;gap:8px;margin-bottom:8px}.test2-election-tabs{display:flex;flex-wrap:wrap;gap:6px;margin-bottom:10px}.test2-election-link{display:inline;padding:0;border:0;background:none;color:var(--color-primary, #1a365d);font:inherit;font-weight:700;text-align:left;text-decoration:underline;text-underline-offset:2px;cursor:pointer}.test2-election-link:hover,.test2-election-link:focus-visible{color:var(--color-primary-dark, #0f2744)}.test2-election-table-wrap{min-height:0;overflow:auto;border:1px solid var(--color-border, #d8e0ea);border-radius:6px;margin-top:8px}.test2-election-table-wrap--constituencies{max-height:220px}.test2-election-table{width:100%;border-collapse:collapse;font-size:12px}.test2-election-table th,.test2-election-table td{padding:5px 7px;border-bottom:1px solid var(--color-border, #d8e0ea);text-align:left;vertical-align:top}.test2-election-table th{position:sticky;top:0;z-index:1;background:var(--color-surface-elevated, #f7fafc);color:var(--color-text-muted, #718096);font-size:11px;text-transform:uppercase}.test2-election-table__elected{background:#2d9c691a;font-weight:700}.test2-election-table__summary{background:var(--color-surface-elevated, #f7fafc)}.test2-election-table__event-row th{background:#fff7ed;color:#9a3412;font-size:10px;text-transform:none}.test2-election-map-display{margin:8px 0 0;font-size:12px}.test2-election-map-display summary{width:max-content;cursor:pointer;color:var(--color-text-muted, #718096);font-weight:700}.test2-election-map-display__controls{display:flex;flex-wrap:wrap;gap:8px;align-items:center;padding-top:6px}.test2-election-map-display .test2-election-panel__mode{display:inline-flex;gap:5px;align-items:center}.test2-election-source-note,.test2-election-coverage-notice,.test2-election-count-toolbar{margin:8px 0}.test2-election-source-note,.test2-election-coverage-notice{padding:8px 10px;border:1px solid var(--color-border, #d8e0ea);border-radius:6px;background:var(--color-surface-elevated, #f7fafc);color:var(--color-text-muted, #718096);font-size:12px}.test2-election-source-note{position:sticky;bottom:0;z-index:2;margin-bottom:0}.test2-election-coverage-notice p{margin:4px 0 0}.test2-election-count-detail{display:grid;gap:2px;margin-top:3px;color:var(--color-text-muted, #718096);font-size:11px;font-weight:400}.test2-election-animation-ready{display:grid;gap:6px;padding:12px;border:1px solid var(--color-border, #d8e0ea);border-radius:6px;background:var(--color-surface-elevated, #f7fafc);font-size:13px}.test2-election-animation-ready p{margin:0}.test2-fptp-results-layout{display:flex;gap:10px;align-items:start;width:max-content;min-width:100%;max-width:none;justify-content:flex-start;overflow:visible}.test2-fptp-results-layout__table{flex:0 0 auto;width:max-content;min-width:max-content;max-width:none;overflow:visible}.test2-fptp-results-layout__table .election-party-wrapper{margin:0}.election-party-wrapper--pane-inline{overflow:visible;max-height:none;width:max-content;min-width:max-content}.test2-fptp-vote-graphic.transfer-animation-preview{display:block;flex:0 0 360px;width:360px;min-width:280px;max-width:min(360px,100%);margin:0;padding:10px 12px 12px;box-sizing:border-box}.test2-fptp-vote-graphic__title{color:#2c3e50;font-size:13px;font-weight:700}.test2-fptp-vote-graphic__animation{position:relative;display:grid;gap:5px;width:100%;min-width:0;padding:8px 0 10px}.test2-fptp-vote-graphic__candidate{position:relative;z-index:1;display:grid;grid-template-columns:92px minmax(0,1fr) 46px;gap:6px;align-items:center;min-height:24px}.test2-fptp-vote-graphic__candidate-label{overflow:hidden;color:#222;font-size:11px;font-weight:700;line-height:1.15;text-overflow:ellipsis;white-space:nowrap}.test2-fptp-vote-graphic__bar{display:flex;align-items:center;width:var(--vote-width, 0%);min-width:0;max-width:100%;min-height:18px;padding:2px 6px;box-sizing:border-box;overflow:visible;background:var(--vote-colour, #6b7280);background:linear-gradient(90deg,color-mix(in srgb,var(--vote-colour, #6b7280) 78%,#ffffff),var(--vote-colour, #6b7280));border:1px solid #111827;border-radius:0 4px 4px 0;color:#fff;font-size:11px;font-weight:700;line-height:1;text-shadow:1px 1px 0 #000,-1px -1px 0 #000,1px -1px 0 #000,-1px 1px 0 #000;white-space:nowrap}.test2-fptp-vote-graphic__candidate--elected .test2-fptp-vote-graphic__bar{outline:2px solid #f1c40f;outline-offset:1px}.test2-fptp-vote-graphic__meta{color:#334155;font-size:11px;font-weight:700;text-align:right;white-space:nowrap}.test2-election-trends{display:grid;gap:10px;padding:10px;border:1px solid var(--color-border, #d8e0ea);border-radius:6px;background:var(--color-surface, #fff)}.test2-election-trends__header{display:flex;align-items:start;justify-content:space-between;gap:14px;flex-wrap:wrap}.test2-election-trends__header h3{margin:0;color:var(--color-text, #111827);font-size:15px;line-height:1.2}.test2-election-trends__header p,.test2-election-trends__note{margin:3px 0 0;color:var(--color-text-muted, #64748b);font-size:12px}.test2-election-trends__scope{display:inline-flex;align-items:center;gap:7px;color:var(--color-text, #111827);font-size:12px;font-weight:700}.test2-election-trends__chart{max-width:100%;overflow-x:auto}.test2-election-trends__legend{display:flex;align-items:center;gap:10px;flex-wrap:wrap;margin-bottom:4px;color:var(--color-text, #111827);font-size:12px;font-weight:700}.test2-election-trends__legend-item{display:inline-flex;align-items:center;gap:4px}.test2-election-trends__legend-item span{width:18px;height:4px;border:1px solid rgba(15,23,42,.35);border-radius:999px}.test2-election-trends__svg{width:100%;min-width:680px;height:auto;display:block}.trend-grid{stroke:var(--color-border, #d8e0ea);stroke-width:1}.trend-axis,.trend-axis-line{fill:var(--color-text-muted, #64748b);stroke:var(--color-text-muted, #64748b);font-size:11px}.trend-axis-line{stroke-width:1.2}.trend-line{fill:none;stroke:var(--trend-colour, #64748b);stroke-width:3.5;stroke-linecap:round;stroke-linejoin:round}.trend-marker{fill:var(--trend-colour, #64748b);stroke:#111827;stroke-width:2.3}@media(max-width:1100px){.test2-fptp-results-layout{flex-direction:column;width:100%;min-width:0;overflow-x:visible}.test2-fptp-results-layout__table,.test2-fptp-vote-graphic.transfer-animation-preview{flex-basis:auto;width:100%;max-width:520px}}[data-theme=dark] .test2-source-panel,[data-theme=dark] .test2-election-panel,[data-theme=dark] .test2-election-table-wrap,[data-theme=dark] .test2-election-source-note,[data-theme=dark] .test2-election-coverage-notice,[data-theme=dark] .test2-election-trends,[data-theme=dark] .test2-election-animation-ready,[data-theme=dark] .test2-fptp-vote-graphic.transfer-animation-preview{background:var(--color-surface, #0f1419);border-color:var(--color-border, #3d444d);color:var(--color-text, #f7fafc)}[data-theme=dark] .test2-source-panel__header,[data-theme=dark] .test2-source-panel__group,[data-theme=dark] .test2-election-table th,[data-theme=dark] .test2-election-table__summary,[data-theme=dark] .test2-election-trends__legend,[data-theme=dark] .test2-fptp-vote-graphic__title{background:var(--color-surface-elevated, #1c2128);border-color:var(--color-border, #3d444d);color:var(--color-text, #f7fafc)}[data-theme=dark] .test2-election-trends__header h3,[data-theme=dark] .test2-election-trends__scope{color:var(--color-text, #f7fafc)}[data-theme=dark] .test2-election-trends__header p,[data-theme=dark] .test2-election-trends__note{color:var(--color-text-muted, #a8b3c5)}[data-theme=dark] .trend-grid{stroke:#3d444d}[data-theme=dark] .trend-axis,[data-theme=dark] .trend-axis-line{fill:#a8b3c5;stroke:#a8b3c5}[data-theme=dark] .trend-marker{stroke:#f7fafc}[data-theme=dark] .test2-election-table td,[data-theme=dark] .test2-source-panel__record+.test2-source-panel__record{border-color:var(--color-border, #3d444d)}[data-theme=dark] .test2-fptp-vote-graphic__candidate-label,[data-theme=dark] .test2-fptp-vote-graphic__meta{color:var(--color-text, #f7fafc)}[data-theme=dark] .test2-election-table__event-row th{background:#92400e47;color:#fed7aa}@media(prefers-color-scheme:dark){:root:not([data-theme=light]) .flat-election-entry--active{background:#1d2b3d;box-shadow:inset 3px 0 #8fb4ff}:root:not([data-theme=light]) .flat-election-entry--active .flat-election-date{color:#f7fafc}:root:not([data-theme=light]) .flat-election-entry--active .flat-election-body,:root:not([data-theme=light]) .flat-election-entry--active .flat-election-separator{color:#eef6ff}:root:not([data-theme=light]) .test2-source-panel,:root:not([data-theme=light]) .test2-election-panel,:root:not([data-theme=light]) .test2-election-table-wrap,:root:not([data-theme=light]) .test2-election-source-note,:root:not([data-theme=light]) .test2-election-coverage-notice,:root:not([data-theme=light]) .test2-election-trends,:root:not([data-theme=light]) .test2-election-animation-ready,:root:not([data-theme=light]) .test2-fptp-vote-graphic.transfer-animation-preview{background:var(--color-surface, #0f1419);border-color:var(--color-border, #3d444d);color:var(--color-text, #f7fafc)}:root:not([data-theme=light]) .test2-source-panel__header,:root:not([data-theme=light]) .test2-source-panel__group,:root:not([data-theme=light]) .test2-election-table th,:root:not([data-theme=light]) .test2-election-table__summary,:root:not([data-theme=light]) .test2-election-trends__legend,:root:not([data-theme=light]) .test2-fptp-vote-graphic__title{background:var(--color-surface-elevated, #1c2128);border-color:var(--color-border, #3d444d);color:var(--color-text, #f7fafc)}:root:not([data-theme=light]) .test2-election-trends__header h3,:root:not([data-theme=light]) .test2-election-trends__scope{color:var(--color-text, #f7fafc)}:root:not([data-theme=light]) .test2-election-trends__header p,:root:not([data-theme=light]) .test2-election-trends__note{color:var(--color-text-muted, #a8b3c5)}:root:not([data-theme=light]) .trend-grid{stroke:#3d444d}:root:not([data-theme=light]) .trend-axis,:root:not([data-theme=light]) .trend-axis-line{fill:#a8b3c5;stroke:#a8b3c5}:root:not([data-theme=light]) .trend-marker{stroke:#f7fafc}:root:not([data-theme=light]) .test2-election-table td,:root:not([data-theme=light]) .test2-source-panel__record+.test2-source-panel__record{border-color:var(--color-border, #3d444d)}:root:not([data-theme=light]) .test2-fptp-vote-graphic__candidate-label,:root:not([data-theme=light]) .test2-fptp-vote-graphic__meta{color:var(--color-text, #f7fafc)}:root:not([data-theme=light]) .test2-election-table__event-row th{background:#92400e47;color:#fed7aa}}.test2-party-swatch{display:inline-block;width:10px;height:10px;margin-right:6px;border:1px solid rgba(15,23,42,.25);border-radius:999px;vertical-align:-1px}.test2-election-panel__mode select{width:100%;min-height:34px}.test2-election-panel__legend{display:flex;flex-wrap:wrap;gap:6px 10px;align-items:center;margin-bottom:10px;font-size:12px}.test2-election-panel__legend-item{display:inline-flex;align-items:center;gap:5px}.test2-election-panel__legend-item i{width:12px;height:12px;border-radius:50%;border:1px solid rgba(17,24,39,.2)}.test2-election-panel__legend-ramp{width:84px;height:12px;border-radius:999px;border:1px solid rgba(17,24,39,.16);background:linear-gradient(90deg,#fef3c7,#fde68a,#f59e0b,#d97706,#92400e)}.test2-election-panel__stats{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:8px;margin:0}.test2-election-panel__stats dt{color:var(--color-text-muted, #718096);font-size:11px}.test2-election-panel__stats dd{margin:0;overflow-wrap:anywhere;font-size:12px;font-weight:700}@media(max-width:640px){.test2-source-panel{top:64px;right:10px;left:10px;width:auto;max-height:calc(100% - 82px)}.test2-election-panel{inset:auto 10px 12px;width:auto;max-height:42vh}}.test2-performance-dashboard{border-top:1px solid var(--color-border, #e2e8f0);padding-top:var(--space-3, .75rem)}.test2-performance-dashboard__header{align-items:center;display:flex;gap:var(--space-2, .5rem);justify-content:space-between;margin-bottom:var(--space-2, .5rem)}.test2-performance-dashboard__body{display:grid;gap:4px;font-size:.75rem}.test2-performance-dashboard__row{align-items:start;background:color-mix(in srgb,var(--color-surface, #fff) 92%,var(--color-primary-50, #ebf4ff) 8%);border:1px solid var(--color-border, #e2e8f0);border-left:3px solid var(--color-border, #e2e8f0);border-radius:4px;display:grid;gap:4px;grid-template-columns:minmax(72px,.85fr) minmax(0,1.25fr);padding:5px 6px}.test2-performance-dashboard__row span{color:var(--color-text-muted, #718096)}.test2-performance-dashboard__row strong{color:var(--color-text, #1a202c);font-weight:650;overflow-wrap:anywhere}.test2-performance-dashboard__row--ok{border-left-color:var(--color-success, #38a169)}.test2-performance-dashboard__row--warning{border-left-color:var(--color-warning, #d69e2e)}.test2-performance-dashboard__row--danger{border-left-color:var(--color-error, #e53e3e)}.catalogue-flat__toc-map-buttons{display:flex;flex-wrap:wrap;gap:6px;padding:6px 0 8px}.catalogue-flat__toc-map-btn{display:inline-flex;align-items:center;min-height:28px;padding:4px 10px;border:1px solid var(--color-border, #d6e0eb);border-radius:6px;background:var(--color-surface, #fff);color:var(--color-link, #173b6d);font-size:.74rem;font-weight:700;text-decoration:none}.catalogue-flat__toc-map-btn:hover,.catalogue-flat__toc-map-btn:focus-visible{border-color:var(--color-primary, #1a365d);color:var(--color-primary, #1a365d);outline:none}.catalogue-search{display:grid;gap:10px;padding:12px 14px 20px}.catalogue-flat-view--search{overflow-anchor:none}.catalogue-search__summary{color:var(--color-text-muted, #5b6b85);font-size:.86rem}.catalogue-search__summary span{color:var(--color-text, #1a202c);font-weight:700}.catalogue-search__results{display:grid;gap:8px}.catalogue-search__result{display:grid;grid-template-columns:54px minmax(0,1fr) auto;gap:10px;align-items:center;padding:8px;border:1px solid var(--color-border, #d6e0eb);border-radius:8px;background:var(--color-surface, #fff)}.catalogue-search__thumb{width:48px;height:48px;display:grid;place-items:center;overflow:hidden;border:1px solid var(--color-border, #d6e0eb);border-radius:6px;background:var(--color-surface-muted, #f5f8fb)}.catalogue-search__thumb .thumb-zone,.catalogue-search__thumbnail-img,.catalogue-search__feature-thumb svg{width:48px;height:48px;display:block}.catalogue-search__feature-thumb,.catalogue-search__fallback-thumb,.catalogue-search__colour-tab{width:34px;height:34px;border-radius:5px;display:inline-block}.catalogue-search__fallback-thumb{background:linear-gradient(135deg,#d8e2ef,#f5f8fb)}.catalogue-search__type{color:var(--color-text-muted, #6b7a90);font-size:.68rem;font-weight:800;letter-spacing:.04em;text-transform:uppercase}.catalogue-search__title{margin:1px 0 2px;color:var(--color-text, #0f172a);font-size:.96rem;line-height:1.15}.catalogue-search__meta,.catalogue-search__empty{color:var(--color-text-muted, #5b6b85);font-size:.8rem;line-height:1.25}.catalogue-search__actions{display:flex;flex-wrap:wrap;justify-content:flex-end;gap:6px}.catalogue-search__title-link{display:inline;padding:0;border:0;background:transparent;color:var(--color-primary, #174a7c);cursor:pointer;font:inherit;font-weight:800;text-align:left;text-decoration:underline;text-decoration-thickness:1px;text-underline-offset:2px}.catalogue-search__title-link:hover,.catalogue-search__title-link:focus-visible{color:var(--color-primary-dark, #0f3154);outline:none}.catalogue-search__action-strip{display:flex;flex-wrap:nowrap;justify-content:flex-end;gap:4px}.catalogue-search__icon-btn{width:30px;height:30px;flex:0 0 30px}@media(max-width:640px){.catalogue-search__result{grid-template-columns:46px minmax(0,1fr)}.catalogue-search__actions{grid-column:1 / -1;justify-content:flex-start}}[data-theme=dark] .catalogue-flat__toc-toplink,[data-theme=dark] .catalogue-flat__toc-map-btn,[data-theme=dark] .catalogue-search__title,[data-theme=dark] .catalogue-search__summary span,[data-theme=dark] .flat-election-body,[data-theme=dark] .flat-election-separator{color:#f7fafc}[data-theme=dark] .catalogue-search__title-link{color:#93c5fd}[data-theme=dark] .catalogue-search__title-link:hover,[data-theme=dark] .catalogue-search__title-link:focus-visible{color:#bfdbfe}[data-theme=dark] .catalogue-flat__toc-map-btn,[data-theme=dark] .catalogue-search__result,[data-theme=dark] .catalogue-search__thumb{background:var(--color-surface, #0f1419);border-color:var(--color-border, #3d444d)}[data-theme=dark] .catalogue-search__summary,[data-theme=dark] .catalogue-search__type,[data-theme=dark] .catalogue-search__meta,[data-theme=dark] .catalogue-search__empty{color:var(--color-text-muted, #a8b3c5)}@media(prefers-color-scheme:dark){:root:not([data-theme=light]) .catalogue-flat__toc-toplink,:root:not([data-theme=light]) .catalogue-flat__toc-map-btn,:root:not([data-theme=light]) .catalogue-search__title,:root:not([data-theme=light]) .catalogue-search__summary span,:root:not([data-theme=light]) .flat-election-body,:root:not([data-theme=light]) .flat-election-separator{color:#f7fafc}:root:not([data-theme=light]) .catalogue-search__title-link{color:#93c5fd}:root:not([data-theme=light]) .catalogue-search__title-link:hover,:root:not([data-theme=light]) .catalogue-search__title-link:focus-visible{color:#bfdbfe}:root:not([data-theme=light]) .catalogue-flat__toc-map-btn,:root:not([data-theme=light]) .catalogue-search__result,:root:not([data-theme=light]) .catalogue-search__thumb{background:var(--color-surface, #0f1419);border-color:var(--color-border, #3d444d)}:root:not([data-theme=light]) .catalogue-search__summary,:root:not([data-theme=light]) .catalogue-search__type,:root:not([data-theme=light]) .catalogue-search__meta,:root:not([data-theme=light]) .catalogue-search__empty{color:var(--color-text-muted, #a8b3c5)}} +.maplibregl-map{font:12px/20px Helvetica Neue,Arial,Helvetica,sans-serif;overflow:hidden;position:relative;-webkit-tap-highlight-color:rgb(0 0 0/0)}.maplibregl-canvas{left:0;position:absolute;top:0}.maplibregl-map:fullscreen{height:100%;width:100%}.maplibregl-ctrl-group button.maplibregl-ctrl-compass{touch-action:none}.maplibregl-canvas-container.maplibregl-interactive,.maplibregl-ctrl-group button.maplibregl-ctrl-compass{cursor:grab;-webkit-user-select:none;-moz-user-select:none;user-select:none}.maplibregl-canvas-container.maplibregl-interactive.maplibregl-track-pointer{cursor:pointer}.maplibregl-canvas-container.maplibregl-interactive:active,.maplibregl-ctrl-group button.maplibregl-ctrl-compass:active{cursor:grabbing}.maplibregl-canvas-container.maplibregl-touch-zoom-rotate,.maplibregl-canvas-container.maplibregl-touch-zoom-rotate .maplibregl-canvas{touch-action:pan-x pan-y}.maplibregl-canvas-container.maplibregl-touch-drag-pan,.maplibregl-canvas-container.maplibregl-touch-drag-pan .maplibregl-canvas{touch-action:pinch-zoom}.maplibregl-canvas-container.maplibregl-touch-zoom-rotate.maplibregl-touch-drag-pan,.maplibregl-canvas-container.maplibregl-touch-zoom-rotate.maplibregl-touch-drag-pan .maplibregl-canvas{touch-action:none}.maplibregl-canvas-container.maplibregl-touch-drag-pan.maplibregl-cooperative-gestures,.maplibregl-canvas-container.maplibregl-touch-drag-pan.maplibregl-cooperative-gestures .maplibregl-canvas{touch-action:pan-x pan-y}.maplibregl-ctrl-bottom-left,.maplibregl-ctrl-bottom-right,.maplibregl-ctrl-top-left,.maplibregl-ctrl-top-right{pointer-events:none;position:absolute;z-index:2}.maplibregl-ctrl-top-left{left:0;top:0}.maplibregl-ctrl-top-right{right:0;top:0}.maplibregl-ctrl-bottom-left{bottom:0;left:0}.maplibregl-ctrl-bottom-right{bottom:0;right:0}.maplibregl-ctrl{clear:both;pointer-events:auto;transform:translate(0)}.maplibregl-ctrl-top-left .maplibregl-ctrl{float:left;margin:10px 0 0 10px}.maplibregl-ctrl-top-right .maplibregl-ctrl{float:right;margin:10px 10px 0 0}.maplibregl-ctrl-bottom-left .maplibregl-ctrl{float:left;margin:0 0 10px 10px}.maplibregl-ctrl-bottom-right .maplibregl-ctrl{float:right;margin:0 10px 10px 0}.maplibregl-ctrl-group{background:#fff;border-radius:4px}.maplibregl-ctrl-group:not(:empty){box-shadow:0 0 0 2px #0000001a}@media(forced-colors:active){.maplibregl-ctrl-group:not(:empty){box-shadow:0 0 0 2px ButtonText}}.maplibregl-ctrl-group button{background-color:transparent;border:0;box-sizing:border-box;cursor:pointer;display:block;height:29px;outline:none;padding:0;width:29px}.maplibregl-ctrl-group button+button{border-top:1px solid #ddd}.maplibregl-ctrl button .maplibregl-ctrl-icon{background-position:50%;background-repeat:no-repeat;display:block;height:100%;width:100%}@media(forced-colors:active){.maplibregl-ctrl-icon{background-color:transparent}.maplibregl-ctrl-group button+button{border-top:1px solid ButtonText}}.maplibregl-ctrl button::-moz-focus-inner{border:0;padding:0}.maplibregl-ctrl-attrib-button:focus,.maplibregl-ctrl-group button:focus{box-shadow:0 0 2px 2px #0096ff}.maplibregl-ctrl button:disabled{cursor:not-allowed}.maplibregl-ctrl button:disabled .maplibregl-ctrl-icon{opacity:.25}@media(hover:hover){.maplibregl-ctrl button:not(:disabled):hover{background-color:#0000000d}}.maplibregl-ctrl button:not(:disabled):active{background-color:#0000000d}.maplibregl-ctrl-group button:focus:focus-visible{box-shadow:0 0 2px 2px #0096ff}.maplibregl-ctrl-group button:focus:not(:focus-visible){box-shadow:none}.maplibregl-ctrl-group button:focus:first-child{border-radius:4px 4px 0 0}.maplibregl-ctrl-group button:focus:last-child{border-radius:0 0 4px 4px}.maplibregl-ctrl-group button:focus:only-child{border-radius:inherit}.maplibregl-ctrl button.maplibregl-ctrl-zoom-out .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23333' viewBox='0 0 29 29'%3E%3Cpath d='M10 13c-.75 0-1.5.75-1.5 1.5S9.25 16 10 16h9c.75 0 1.5-.75 1.5-1.5S19.75 13 19 13z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-zoom-in .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23333' viewBox='0 0 29 29'%3E%3Cpath d='M14.5 8.5c-.75 0-1.5.75-1.5 1.5v3h-3c-.75 0-1.5.75-1.5 1.5S9.25 16 10 16h3v3c0 .75.75 1.5 1.5 1.5S16 19.75 16 19v-3h3c.75 0 1.5-.75 1.5-1.5S19.75 13 19 13h-3v-3c0-.75-.75-1.5-1.5-1.5'/%3E%3C/svg%3E")}@media(forced-colors:active){.maplibregl-ctrl button.maplibregl-ctrl-zoom-out .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23fff' viewBox='0 0 29 29'%3E%3Cpath d='M10 13c-.75 0-1.5.75-1.5 1.5S9.25 16 10 16h9c.75 0 1.5-.75 1.5-1.5S19.75 13 19 13z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-zoom-in .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23fff' viewBox='0 0 29 29'%3E%3Cpath d='M14.5 8.5c-.75 0-1.5.75-1.5 1.5v3h-3c-.75 0-1.5.75-1.5 1.5S9.25 16 10 16h3v3c0 .75.75 1.5 1.5 1.5S16 19.75 16 19v-3h3c.75 0 1.5-.75 1.5-1.5S19.75 13 19 13h-3v-3c0-.75-.75-1.5-1.5-1.5'/%3E%3C/svg%3E")}}@media(forced-colors:active)and (prefers-color-scheme:light){.maplibregl-ctrl button.maplibregl-ctrl-zoom-out .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' viewBox='0 0 29 29'%3E%3Cpath d='M10 13c-.75 0-1.5.75-1.5 1.5S9.25 16 10 16h9c.75 0 1.5-.75 1.5-1.5S19.75 13 19 13z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-zoom-in .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' viewBox='0 0 29 29'%3E%3Cpath d='M14.5 8.5c-.75 0-1.5.75-1.5 1.5v3h-3c-.75 0-1.5.75-1.5 1.5S9.25 16 10 16h3v3c0 .75.75 1.5 1.5 1.5S16 19.75 16 19v-3h3c.75 0 1.5-.75 1.5-1.5S19.75 13 19 13h-3v-3c0-.75-.75-1.5-1.5-1.5'/%3E%3C/svg%3E")}}.maplibregl-ctrl button.maplibregl-ctrl-fullscreen .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23333' viewBox='0 0 29 29'%3E%3Cpath d='M24 16v5.5c0 1.75-.75 2.5-2.5 2.5H16v-1l3-1.5-4-5.5 1-1 5.5 4 1.5-3zM6 16l1.5 3 5.5-4 1 1-4 5.5 3 1.5v1H7.5C5.75 24 5 23.25 5 21.5V16zm7-11v1l-3 1.5 4 5.5-1 1-5.5-4L6 13H5V7.5C5 5.75 5.75 5 7.5 5zm11 2.5c0-1.75-.75-2.5-2.5-2.5H16v1l3 1.5-4 5.5 1 1 5.5-4 1.5 3h1z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-shrink .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' viewBox='0 0 29 29'%3E%3Cpath d='M18.5 16c-1.75 0-2.5.75-2.5 2.5V24h1l1.5-3 5.5 4 1-1-4-5.5 3-1.5v-1zM13 18.5c0-1.75-.75-2.5-2.5-2.5H5v1l3 1.5L4 24l1 1 5.5-4 1.5 3h1zm3-8c0 1.75.75 2.5 2.5 2.5H24v-1l-3-1.5L25 5l-1-1-5.5 4L17 5h-1zM10.5 13c1.75 0 2.5-.75 2.5-2.5V5h-1l-1.5 3L5 4 4 5l4 5.5L5 12v1z'/%3E%3C/svg%3E")}@media(forced-colors:active){.maplibregl-ctrl button.maplibregl-ctrl-fullscreen .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23fff' viewBox='0 0 29 29'%3E%3Cpath d='M24 16v5.5c0 1.75-.75 2.5-2.5 2.5H16v-1l3-1.5-4-5.5 1-1 5.5 4 1.5-3zM6 16l1.5 3 5.5-4 1 1-4 5.5 3 1.5v1H7.5C5.75 24 5 23.25 5 21.5V16zm7-11v1l-3 1.5 4 5.5-1 1-5.5-4L6 13H5V7.5C5 5.75 5.75 5 7.5 5zm11 2.5c0-1.75-.75-2.5-2.5-2.5H16v1l3 1.5-4 5.5 1 1 5.5-4 1.5 3h1z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-shrink .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23fff' viewBox='0 0 29 29'%3E%3Cpath d='M18.5 16c-1.75 0-2.5.75-2.5 2.5V24h1l1.5-3 5.5 4 1-1-4-5.5 3-1.5v-1zM13 18.5c0-1.75-.75-2.5-2.5-2.5H5v1l3 1.5L4 24l1 1 5.5-4 1.5 3h1zm3-8c0 1.75.75 2.5 2.5 2.5H24v-1l-3-1.5L25 5l-1-1-5.5 4L17 5h-1zM10.5 13c1.75 0 2.5-.75 2.5-2.5V5h-1l-1.5 3L5 4 4 5l4 5.5L5 12v1z'/%3E%3C/svg%3E")}}@media(forced-colors:active)and (prefers-color-scheme:light){.maplibregl-ctrl button.maplibregl-ctrl-fullscreen .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' viewBox='0 0 29 29'%3E%3Cpath d='M24 16v5.5c0 1.75-.75 2.5-2.5 2.5H16v-1l3-1.5-4-5.5 1-1 5.5 4 1.5-3zM6 16l1.5 3 5.5-4 1 1-4 5.5 3 1.5v1H7.5C5.75 24 5 23.25 5 21.5V16zm7-11v1l-3 1.5 4 5.5-1 1-5.5-4L6 13H5V7.5C5 5.75 5.75 5 7.5 5zm11 2.5c0-1.75-.75-2.5-2.5-2.5H16v1l3 1.5-4 5.5 1 1 5.5-4 1.5 3h1z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-shrink .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' viewBox='0 0 29 29'%3E%3Cpath d='M18.5 16c-1.75 0-2.5.75-2.5 2.5V24h1l1.5-3 5.5 4 1-1-4-5.5 3-1.5v-1zM13 18.5c0-1.75-.75-2.5-2.5-2.5H5v1l3 1.5L4 24l1 1 5.5-4 1.5 3h1zm3-8c0 1.75.75 2.5 2.5 2.5H24v-1l-3-1.5L25 5l-1-1-5.5 4L17 5h-1zM10.5 13c1.75 0 2.5-.75 2.5-2.5V5h-1l-1.5 3L5 4 4 5l4 5.5L5 12v1z'/%3E%3C/svg%3E")}}.maplibregl-ctrl button.maplibregl-ctrl-compass .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23333' viewBox='0 0 29 29'%3E%3Cpath d='m10.5 14 4-8 4 8z'/%3E%3Cpath fill='%23ccc' d='m10.5 16 4 8 4-8z'/%3E%3C/svg%3E")}@media(forced-colors:active){.maplibregl-ctrl button.maplibregl-ctrl-compass .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23fff' viewBox='0 0 29 29'%3E%3Cpath d='m10.5 14 4-8 4 8z'/%3E%3Cpath fill='%23ccc' d='m10.5 16 4 8 4-8z'/%3E%3C/svg%3E")}}@media(forced-colors:active)and (prefers-color-scheme:light){.maplibregl-ctrl button.maplibregl-ctrl-compass .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' viewBox='0 0 29 29'%3E%3Cpath d='m10.5 14 4-8 4 8z'/%3E%3Cpath fill='%23ccc' d='m10.5 16 4 8 4-8z'/%3E%3C/svg%3E")}}.maplibregl-ctrl button.maplibregl-ctrl-globe .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='22' height='22' fill='none' stroke='%23333' viewBox='0 0 22 22'%3E%3Ccircle cx='11' cy='11' r='8.5'/%3E%3Cpath d='M17.5 11c0 4.819-3.02 8.5-6.5 8.5S4.5 15.819 4.5 11 7.52 2.5 11 2.5s6.5 3.681 6.5 8.5Z'/%3E%3Cpath d='M13.5 11c0 2.447-.331 4.64-.853 6.206-.262.785-.562 1.384-.872 1.777-.314.399-.58.517-.775.517s-.461-.118-.775-.517c-.31-.393-.61-.992-.872-1.777C8.831 15.64 8.5 13.446 8.5 11s.331-4.64.853-6.206c.262-.785.562-1.384.872-1.777.314-.399.58-.517.775-.517s.461.118.775.517c.31.393.61.992.872 1.777.522 1.565.853 3.76.853 6.206Z'/%3E%3Cpath d='M11 7.5c-1.909 0-3.622-.166-4.845-.428-.616-.132-1.08-.283-1.379-.434a1.3 1.3 0 0 1-.224-.138q.07-.058.224-.138c.299-.151.763-.302 1.379-.434C7.378 5.666 9.091 5.5 11 5.5s3.622.166 4.845.428c.616.132 1.08.283 1.379.434.105.053.177.1.224.138q-.07.058-.224.138c-.299.151-.763.302-1.379.434-1.223.262-2.936.428-4.845.428ZM4.486 6.436ZM11 16.5c-1.909 0-3.622-.166-4.845-.428-.616-.132-1.08-.283-1.379-.434a1.3 1.3 0 0 1-.224-.138 1.3 1.3 0 0 1 .224-.138c.299-.151.763-.302 1.379-.434C7.378 14.666 9.091 14.5 11 14.5s3.622.166 4.845.428c.616.132 1.08.283 1.379.434.105.053.177.1.224.138a1.3 1.3 0 0 1-.224.138c-.299.151-.763.302-1.379.434-1.223.262-2.936.428-4.845.428Zm-6.514-1.064ZM11 12.5c-2.46 0-4.672-.222-6.255-.574-.796-.177-1.406-.38-1.805-.59a1.5 1.5 0 0 1-.39-.272.3.3 0 0 1-.047-.064.3.3 0 0 1 .048-.064c.066-.073.189-.167.389-.272.399-.21 1.009-.413 1.805-.59C6.328 9.722 8.54 9.5 11 9.5s4.672.222 6.256.574c.795.177 1.405.38 1.804.59.2.105.323.2.39.272a.3.3 0 0 1 .047.064.3.3 0 0 1-.048.064 1.4 1.4 0 0 1-.389.272c-.399.21-1.009.413-1.804.59-1.584.352-3.796.574-6.256.574Zm-8.501-1.51v.002zm0 .018v.002zm17.002.002v-.002zm0-.018v-.002z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-globe-enabled .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='22' height='22' fill='none' stroke='%2333b5e5' viewBox='0 0 22 22'%3E%3Ccircle cx='11' cy='11' r='8.5'/%3E%3Cpath d='M17.5 11c0 4.819-3.02 8.5-6.5 8.5S4.5 15.819 4.5 11 7.52 2.5 11 2.5s6.5 3.681 6.5 8.5Z'/%3E%3Cpath d='M13.5 11c0 2.447-.331 4.64-.853 6.206-.262.785-.562 1.384-.872 1.777-.314.399-.58.517-.775.517s-.461-.118-.775-.517c-.31-.393-.61-.992-.872-1.777C8.831 15.64 8.5 13.446 8.5 11s.331-4.64.853-6.206c.262-.785.562-1.384.872-1.777.314-.399.58-.517.775-.517s.461.118.775.517c.31.393.61.992.872 1.777.522 1.565.853 3.76.853 6.206Z'/%3E%3Cpath d='M11 7.5c-1.909 0-3.622-.166-4.845-.428-.616-.132-1.08-.283-1.379-.434a1.3 1.3 0 0 1-.224-.138q.07-.058.224-.138c.299-.151.763-.302 1.379-.434C7.378 5.666 9.091 5.5 11 5.5s3.622.166 4.845.428c.616.132 1.08.283 1.379.434.105.053.177.1.224.138q-.07.058-.224.138c-.299.151-.763.302-1.379.434-1.223.262-2.936.428-4.845.428ZM4.486 6.436ZM11 16.5c-1.909 0-3.622-.166-4.845-.428-.616-.132-1.08-.283-1.379-.434a1.3 1.3 0 0 1-.224-.138 1.3 1.3 0 0 1 .224-.138c.299-.151.763-.302 1.379-.434C7.378 14.666 9.091 14.5 11 14.5s3.622.166 4.845.428c.616.132 1.08.283 1.379.434.105.053.177.1.224.138a1.3 1.3 0 0 1-.224.138c-.299.151-.763.302-1.379.434-1.223.262-2.936.428-4.845.428Zm-6.514-1.064ZM11 12.5c-2.46 0-4.672-.222-6.255-.574-.796-.177-1.406-.38-1.805-.59a1.5 1.5 0 0 1-.39-.272.3.3 0 0 1-.047-.064.3.3 0 0 1 .048-.064c.066-.073.189-.167.389-.272.399-.21 1.009-.413 1.805-.59C6.328 9.722 8.54 9.5 11 9.5s4.672.222 6.256.574c.795.177 1.405.38 1.804.59.2.105.323.2.39.272a.3.3 0 0 1 .047.064.3.3 0 0 1-.048.064 1.4 1.4 0 0 1-.389.272c-.399.21-1.009.413-1.804.59-1.584.352-3.796.574-6.256.574Zm-8.501-1.51v.002zm0 .018v.002zm17.002.002v-.002zm0-.018v-.002z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-terrain .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='22' height='22' fill='%23333' viewBox='0 0 22 22'%3E%3Cpath d='m1.754 13.406 4.453-4.851 3.09 3.09 3.281 3.277.969-.969-3.309-3.312 3.844-4.121 6.148 6.886h1.082v-.855l-7.207-8.07-4.84 5.187L6.169 6.57l-5.48 5.965v.871ZM.688 16.844h20.625v1.375H.688Zm0 0'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-terrain-enabled .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='22' height='22' fill='%2333b5e5' viewBox='0 0 22 22'%3E%3Cpath d='m1.754 13.406 4.453-4.851 3.09 3.09 3.281 3.277.969-.969-3.309-3.312 3.844-4.121 6.148 6.886h1.082v-.855l-7.207-8.07-4.84 5.187L6.169 6.57l-5.48 5.965v.871ZM.688 16.844h20.625v1.375H.688Zm0 0'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23333' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate:disabled .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23aaa' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3Cpath fill='red' d='m14 5 1 1-9 9-1-1z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-active .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%2333b5e5' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-active-error .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23e58978' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-background .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%2333b5e5' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-background-error .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23e54e33' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-waiting .maplibregl-ctrl-icon{animation:maplibregl-spin 2s linear infinite}@media(forced-colors:active){.maplibregl-ctrl button.maplibregl-ctrl-geolocate .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23fff' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate:disabled .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23999' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3Cpath fill='red' d='m14 5 1 1-9 9-1-1z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-active .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%2333b5e5' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-active-error .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23e58978' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-background .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%2333b5e5' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-background-error .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23e54e33' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3C/svg%3E")}}@media(forced-colors:active)and (prefers-color-scheme:light){.maplibregl-ctrl button.maplibregl-ctrl-geolocate .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate:disabled .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23666' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3Cpath fill='red' d='m14 5 1 1-9 9-1-1z'/%3E%3C/svg%3E")}}@keyframes maplibregl-spin{0%{transform:rotate(0)}to{transform:rotate(1turn)}}a.maplibregl-ctrl-logo{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='88' height='23' fill='none'%3E%3Cpath fill='%23000' fill-opacity='.4' fill-rule='evenodd' d='M17.408 16.796h-1.827l2.501-12.095h.198l3.324 6.533.988 2.19.988-2.19 3.258-6.533h.181l2.6 12.095h-1.81l-1.218-5.644-.362-1.71-.658 1.71-2.929 5.644h-.098l-2.914-5.644-.757-1.71-.345 1.71zm1.958-3.42-.726 3.663a1.255 1.255 0 0 1-1.232 1.011h-1.827a1.255 1.255 0 0 1-1.229-1.509l2.501-12.095a1.255 1.255 0 0 1 1.23-1.001h.197a1.25 1.25 0 0 1 1.12.685l3.19 6.273 3.125-6.263a1.25 1.25 0 0 1 1.123-.695h.181a1.255 1.255 0 0 1 1.227.991l1.443 6.71a5 5 0 0 1 .314-.787l.009-.016a4.6 4.6 0 0 1 1.777-1.887c.782-.46 1.668-.667 2.611-.667a4.6 4.6 0 0 1 1.7.32l.306.134c.21-.16.474-.256.759-.256h1.694a1.255 1.255 0 0 1 1.212.925 1.255 1.255 0 0 1 1.212-.925h1.711c.284 0 .545.094.755.252.613-.3 1.312-.45 2.075-.45 1.356 0 2.557.445 3.482 1.4q.47.48.763 1.064V4.701a1.255 1.255 0 0 1 1.255-1.255h1.86A1.255 1.255 0 0 1 54.44 4.7v9.194h2.217c.19 0 .37.043.532.118v-4.77c0-.356.147-.678.385-.906a2.42 2.42 0 0 1-.682-1.71c0-.665.267-1.253.735-1.7a2.45 2.45 0 0 1 1.722-.674 2.43 2.43 0 0 1 1.705.675q.318.302.504.683V4.7a1.255 1.255 0 0 1 1.255-1.255h1.744A1.255 1.255 0 0 1 65.812 4.7v3.335a4.8 4.8 0 0 1 1.526-.246c.938 0 1.817.214 2.59.69a4.47 4.47 0 0 1 1.67 1.743v-.98a1.255 1.255 0 0 1 1.256-1.256h1.777c.233 0 .451.064.639.174a3.4 3.4 0 0 1 1.567-.372c.346 0 .861.02 1.285.232a1.25 1.25 0 0 1 .689 1.004 4.7 4.7 0 0 1 .853-.588c.795-.44 1.675-.647 2.61-.647 1.385 0 2.65.39 3.525 1.396.836.938 1.168 2.173 1.168 3.528q-.001.515-.056 1.051a1.255 1.255 0 0 1-.947 1.09l.408.952a1.255 1.255 0 0 1-.477 1.552c-.418.268-.92.463-1.458.612-.613.171-1.304.244-2.049.244-1.06 0-2.043-.207-2.886-.698l-.015-.008c-.798-.48-1.419-1.135-1.818-1.963l-.004-.008a5.8 5.8 0 0 1-.548-2.512q0-.429.053-.843a1.3 1.3 0 0 1-.333-.086l-.166-.004c-.223 0-.426.062-.643.228-.03.024-.142.139-.142.59v3.883a1.255 1.255 0 0 1-1.256 1.256h-1.777a1.255 1.255 0 0 1-1.256-1.256V15.69l-.032.057a4.8 4.8 0 0 1-1.86 1.833 5.04 5.04 0 0 1-2.484.634 4.5 4.5 0 0 1-1.935-.424 1.25 1.25 0 0 1-.764.258h-1.71a1.255 1.255 0 0 1-1.256-1.255V7.687a2.4 2.4 0 0 1-.428.625c.253.23.412.561.412.93v7.553a1.255 1.255 0 0 1-1.256 1.255h-1.843a1.25 1.25 0 0 1-.894-.373c-.228.23-.544.373-.894.373H51.32a1.255 1.255 0 0 1-1.256-1.255v-1.251l-.061.117a4.7 4.7 0 0 1-1.782 1.884 4.77 4.77 0 0 1-2.485.67 5.6 5.6 0 0 1-1.485-.188l.009 2.764a1.255 1.255 0 0 1-1.255 1.259h-1.729a1.255 1.255 0 0 1-1.255-1.255v-3.537a1.255 1.255 0 0 1-1.167.793h-1.679a1.25 1.25 0 0 1-.77-.263 4.5 4.5 0 0 1-1.945.429c-.885 0-1.724-.21-2.495-.632l-.017-.01a5 5 0 0 1-1.081-.836 1.255 1.255 0 0 1-1.254 1.312h-1.81a1.255 1.255 0 0 1-1.228-.99l-.782-3.625-2.044 3.939a1.25 1.25 0 0 1-1.115.676h-.098a1.25 1.25 0 0 1-1.116-.68l-2.061-3.994zM35.92 16.63l.207-.114.223-.15q.493-.356.735-.785l.061-.118.033 1.332h1.678V9.242h-1.694l-.033 1.267q-.133-.329-.526-.658l-.032-.028a3.2 3.2 0 0 0-.668-.428l-.27-.12a3.3 3.3 0 0 0-1.235-.23q-1.136-.001-1.974.493a3.36 3.36 0 0 0-1.3 1.382q-.445.89-.444 2.074 0 1.2.51 2.107a3.8 3.8 0 0 0 1.382 1.381 3.9 3.9 0 0 0 1.893.477q.795 0 1.455-.33zm-2.789-5.38q-.576.675-.575 1.762 0 1.102.559 1.794.576.675 1.645.675a2.25 2.25 0 0 0 .934-.19 2.2 2.2 0 0 0 .468-.29l.178-.161a2.2 2.2 0 0 0 .397-.561q.244-.5.244-1.15v-.115q0-.708-.296-1.267l-.043-.077a2.2 2.2 0 0 0-.633-.709l-.13-.086-.047-.028a2.1 2.1 0 0 0-1.073-.285q-1.052 0-1.629.692zm2.316 2.706c.163-.17.28-.407.28-.83v-.114c0-.292-.06-.508-.15-.68a.96.96 0 0 0-.353-.389.85.85 0 0 0-.464-.127c-.4 0-.56.114-.664.239l-.01.012c-.148.174-.275.45-.275.945 0 .506.122.801.27.99.097.11.266.224.68.224.303 0 .504-.09.687-.269zm7.545 1.705a2.6 2.6 0 0 0 .331.423q.319.33.755.548l.173.074q.65.255 1.49.255 1.02 0 1.844-.493a3.45 3.45 0 0 0 1.316-1.4q.493-.904.493-2.089 0-1.909-.988-2.913-.988-1.02-2.584-1.02-.898 0-1.575.347a3 3 0 0 0-.415.262l-.199.166a3.4 3.4 0 0 0-.64.82V9.242h-1.712v11.553h1.729l-.017-5.134zm.53-1.138q.206.29.48.5l.155.11.053.034q.51.296 1.119.297 1.07 0 1.645-.675.577-.69.576-1.762 0-1.119-.576-1.777-.558-.675-1.645-.675-.435 0-.835.16a2 2 0 0 0-.284.136 2 2 0 0 0-.363.254 2.2 2.2 0 0 0-.46.569l-.082.162a2.6 2.6 0 0 0-.213 1.072v.115q0 .707.296 1.267l.135.211zm.964-.818a1.1 1.1 0 0 0 .367.385.94.94 0 0 0 .476.118c.423 0 .59-.117.687-.23.159-.194.28-.478.28-.95 0-.53-.133-.8-.266-.952l-.021-.025c-.078-.094-.231-.221-.68-.221a1 1 0 0 0-.503.135l-.012.007a.86.86 0 0 0-.335.343c-.073.133-.132.324-.132.614v.115a1.4 1.4 0 0 0 .14.66zm15.7-6.222q.347-.346.346-.856a1.05 1.05 0 0 0-.345-.79 1.18 1.18 0 0 0-.84-.329q-.51 0-.855.33a1.05 1.05 0 0 0-.346.79q0 .51.346.855.345.346.856.346.51 0 .839-.346zm4.337 9.314.033-1.332q.191.403.59.747l.098.081a4 4 0 0 0 .316.224l.223.122a3.2 3.2 0 0 0 1.44.322 3.8 3.8 0 0 0 1.875-.477 3.5 3.5 0 0 0 1.382-1.366q.527-.89.526-2.09 0-1.184-.444-2.073a3.24 3.24 0 0 0-1.283-1.399q-.823-.51-1.942-.51a3.5 3.5 0 0 0-1.527.344l-.086.043-.165.09a3 3 0 0 0-.33.214q-.432.315-.656.707a2 2 0 0 0-.099.198l.082-1.283V4.701h-1.744v12.095zm.473-2.509a2.5 2.5 0 0 0 .566.7q.117.098.245.18l.144.08a2.1 2.1 0 0 0 .975.232q1.07 0 1.645-.675.576-.69.576-1.778 0-1.102-.576-1.777-.56-.691-1.645-.692a2.2 2.2 0 0 0-1.015.235q-.22.113-.415.282l-.15.142a2.1 2.1 0 0 0-.42.594q-.223.479-.223 1.1v.115q0 .705.293 1.26zm2.616-.293c.157-.191.28-.479.28-.967 0-.51-.13-.79-.276-.961l-.021-.026c-.082-.1-.232-.225-.67-.225a.87.87 0 0 0-.681.279l-.012.011c-.154.155-.274.38-.274.807v.115c0 .285.057.499.144.669a1.1 1.1 0 0 0 .367.405c.137.082.28.123.455.123.423 0 .59-.118.686-.23zm8.266-3.013q.345-.13.724-.14l.069-.002q.493 0 .642.099l.247-1.794q-.196-.099-.717-.099a2.3 2.3 0 0 0-.545.063 2 2 0 0 0-.411.148 2.2 2.2 0 0 0-.4.249 2.5 2.5 0 0 0-.485.499 2.7 2.7 0 0 0-.32.581l-.05.137v-1.48h-1.778v7.553h1.777v-3.884q0-.546.159-.943a1.5 1.5 0 0 1 .466-.636 2.5 2.5 0 0 1 .399-.253 2 2 0 0 1 .224-.099zm9.784 2.656.05-.922q0-1.743-.856-2.698-.838-.97-2.584-.97-1.119-.001-2.007.493a3.46 3.46 0 0 0-1.4 1.382q-.493.906-.493 2.106 0 1.07.428 1.975.428.89 1.332 1.432.906.526 2.255.526.973 0 1.668-.185l.044-.012.135-.04q.613-.184.984-.421l-.542-1.267q-.3.162-.642.274l-.297.087q-.51.131-1.3.131-.954 0-1.497-.444a1.6 1.6 0 0 1-.192-.193q-.366-.44-.512-1.234l-.004-.021zm-5.427-1.256-.003.022h3.752v-.138q-.011-.727-.288-1.118a1 1 0 0 0-.156-.176q-.46-.428-1.316-.428-.986 0-1.494.604-.379.45-.494 1.234zm-27.053 2.77V4.7h-1.86v12.095h5.333V15.15zm7.103-5.908v7.553h-1.843V9.242h1.843z'/%3E%3Cpath fill='%23fff' d='m19.63 11.151-.757-1.71-.345 1.71-1.12 5.644h-1.827L18.083 4.7h.197l3.325 6.533.988 2.19.988-2.19L26.839 4.7h.181l2.6 12.095h-1.81l-1.218-5.644-.362-1.71-.658 1.71-2.93 5.644h-.098l-2.913-5.644zm14.836 5.81q-1.02 0-1.893-.478a3.8 3.8 0 0 1-1.381-1.382q-.51-.906-.51-2.106 0-1.185.444-2.074a3.36 3.36 0 0 1 1.3-1.382q.839-.494 1.974-.494a3.3 3.3 0 0 1 1.234.231 3.3 3.3 0 0 1 .97.575q.396.33.527.659l.033-1.267h1.694v7.553H37.18l-.033-1.332q-.279.593-1.02 1.053a3.17 3.17 0 0 1-1.662.444zm.296-1.482q.938 0 1.58-.642.642-.66.642-1.711v-.115q0-.708-.296-1.267a2.2 2.2 0 0 0-.807-.872 2.1 2.1 0 0 0-1.119-.313q-1.053 0-1.629.692-.575.675-.575 1.76 0 1.103.559 1.795.577.675 1.645.675zm6.521-6.237h1.711v1.4q.906-1.597 2.83-1.597 1.596 0 2.584 1.02.988 1.005.988 2.914 0 1.185-.493 2.09a3.46 3.46 0 0 1-1.316 1.399 3.5 3.5 0 0 1-1.844.493q-.954 0-1.662-.329a2.67 2.67 0 0 1-1.086-.97l.017 5.134h-1.728zm4.048 6.22q1.07 0 1.645-.674.577-.69.576-1.762 0-1.119-.576-1.777-.558-.675-1.645-.675-.592 0-1.12.296-.51.28-.822.823-.296.527-.296 1.234v.115q0 .708.296 1.267.313.543.823.855.51.296 1.119.297z'/%3E%3Cpath fill='%23e1e3e9' d='M51.325 4.7h1.86v10.45h3.473v1.646h-5.333zm7.12 4.542h1.843v7.553h-1.843zm.905-1.415a1.16 1.16 0 0 1-.856-.346 1.17 1.17 0 0 1-.346-.856 1.05 1.05 0 0 1 .346-.79q.346-.329.856-.329.494 0 .839.33a1.05 1.05 0 0 1 .345.79 1.16 1.16 0 0 1-.345.855q-.33.346-.84.346zm7.875 9.133a3.17 3.17 0 0 1-1.662-.444q-.723-.46-1.004-1.053l-.033 1.332h-1.71V4.701h1.743v4.657l-.082 1.283q.279-.658 1.086-1.119a3.5 3.5 0 0 1 1.778-.477q1.119 0 1.942.51a3.24 3.24 0 0 1 1.283 1.4q.445.888.444 2.072 0 1.201-.526 2.09a3.5 3.5 0 0 1-1.382 1.366 3.8 3.8 0 0 1-1.876.477zm-.296-1.481q1.069 0 1.645-.675.577-.69.577-1.778 0-1.102-.577-1.776-.56-.691-1.645-.692a2.12 2.12 0 0 0-1.58.659q-.642.641-.642 1.694v.115q0 .71.296 1.267a2.4 2.4 0 0 0 .807.872 2.1 2.1 0 0 0 1.119.313zm5.927-6.237h1.777v1.481q.263-.757.856-1.217a2.14 2.14 0 0 1 1.349-.46q.527 0 .724.098l-.247 1.794q-.149-.099-.642-.099-.774 0-1.416.494-.626.493-.626 1.58v3.883h-1.777V9.242zm9.534 7.718q-1.35 0-2.255-.526-.904-.543-1.332-1.432a4.6 4.6 0 0 1-.428-1.975q0-1.2.493-2.106a3.46 3.46 0 0 1 1.4-1.382q.889-.495 2.007-.494 1.744 0 2.584.97.855.956.856 2.7 0 .444-.05.92h-5.43q.18 1.005.708 1.45.542.443 1.497.443.79 0 1.3-.131a4 4 0 0 0 .938-.362l.542 1.267q-.411.263-1.119.46-.708.198-1.711.197zm1.596-4.558q.016-1.02-.444-1.432-.46-.428-1.316-.428-1.728 0-1.991 1.86z'/%3E%3Cpath d='M5.074 15.948a.484.657 0 0 0-.486.659v1.84a.484.657 0 0 0 .486.659h4.101a.484.657 0 0 0 .486-.659v-1.84a.484.657 0 0 0-.486-.659zm3.56 1.16H5.617v.838h3.017z' style='fill:%23fff;fill-rule:evenodd;stroke-width:1.03600001'/%3E%3Cg style='stroke-width:1.12603545'%3E%3Cpath d='M-9.408-1.416c-3.833-.025-7.056 2.912-7.08 6.615-.02 3.08 1.653 4.832 3.107 6.268.903.892 1.721 1.74 2.32 2.902l-.525-.004c-.543-.003-.992.304-1.24.639a1.87 1.87 0 0 0-.362 1.121l-.011 1.877c-.003.402.104.787.347 1.125.244.338.688.653 1.23.656l4.142.028c.542.003.99-.306 1.238-.641a1.87 1.87 0 0 0 .363-1.121l.012-1.875a1.87 1.87 0 0 0-.348-1.127c-.243-.338-.688-.653-1.23-.656l-.518-.004c.597-1.145 1.425-1.983 2.348-2.87 1.473-1.414 3.18-3.149 3.2-6.226-.016-3.59-2.923-6.684-6.993-6.707m-.006 1.1v.002c3.274.02 5.92 2.532 5.9 5.6-.017 2.706-1.39 4.026-2.863 5.44-1.034.994-2.118 2.033-2.814 3.633-.018.041-.052.055-.075.065q-.013.004-.02.01a.34.34 0 0 1-.226.084.34.34 0 0 1-.224-.086l-.092-.077c-.699-1.615-1.768-2.669-2.781-3.67-1.454-1.435-2.797-2.762-2.78-5.478.02-3.067 2.7-5.545 5.975-5.523m-.02 2.826c-1.62-.01-2.944 1.315-2.955 2.96-.01 1.646 1.295 2.988 2.916 2.999h.002c1.621.01 2.943-1.316 2.953-2.961.011-1.646-1.294-2.988-2.916-2.998m-.005 1.1c1.017.006 1.829.83 1.822 1.89s-.83 1.874-1.848 1.867c-1.018-.006-1.829-.83-1.822-1.89s.83-1.874 1.848-1.868m-2.155 11.857 4.14.025c.271.002.49.305.487.676l-.013 1.875c-.003.37-.224.67-.495.668l-4.14-.025c-.27-.002-.487-.306-.485-.676l.012-1.875c.003-.37.224-.67.494-.668' style='color:%23000;font-style:normal;font-variant:normal;font-weight:400;font-stretch:normal;font-size:medium;line-height:normal;font-family:sans-serif;font-variant-ligatures:normal;font-variant-position:normal;font-variant-caps:normal;font-variant-numeric:normal;font-variant-alternates:normal;font-feature-settings:normal;text-indent:0;text-align:start;text-decoration:none;text-decoration-line:none;text-decoration-style:solid;text-decoration-color:%23000;letter-spacing:normal;word-spacing:normal;text-transform:none;writing-mode:lr-tb;direction:ltr;text-orientation:mixed;dominant-baseline:auto;baseline-shift:baseline;text-anchor:start;white-space:normal;shape-padding:0;clip-rule:evenodd;display:inline;overflow:visible;visibility:visible;opacity:1;isolation:auto;mix-blend-mode:normal;color-interpolation:sRGB;color-interpolation-filters:linearRGB;solid-color:%23000;solid-opacity:1;vector-effect:none;fill:%23000;fill-opacity:.4;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;color-rendering:auto;image-rendering:auto;shape-rendering:auto;text-rendering:auto' transform='translate(15.553 2.85)scale(.88807)'/%3E%3Cpath d='M-9.415-.316C-12.69-.338-15.37 2.14-15.39 5.207c-.017 2.716 1.326 4.041 2.78 5.477 1.013 1 2.081 2.055 2.78 3.67l.092.076a.34.34 0 0 0 .225.086.34.34 0 0 0 .227-.083l.019-.01c.022-.009.057-.024.074-.064.697-1.6 1.78-2.64 2.814-3.634 1.473-1.414 2.847-2.733 2.864-5.44.02-3.067-2.627-5.58-5.901-5.601m-.057 8.784c1.621.011 2.944-1.315 2.955-2.96.01-1.646-1.295-2.988-2.916-2.999-1.622-.01-2.945 1.315-2.955 2.96s1.295 2.989 2.916 3' style='clip-rule:evenodd;fill:%23e1e3e9;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:.4' transform='translate(15.553 2.85)scale(.88807)'/%3E%3Cpath d='M-11.594 15.465c-.27-.002-.492.297-.494.668l-.012 1.876c-.003.371.214.673.485.675l4.14.027c.271.002.492-.298.495-.668l.012-1.877c.003-.37-.215-.672-.485-.674z' style='clip-rule:evenodd;fill:%23fff;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:.4' transform='translate(15.553 2.85)scale(.88807)'/%3E%3C/g%3E%3C/svg%3E");background-repeat:no-repeat;cursor:pointer;display:block;height:23px;margin:0 0 -4px -4px;overflow:hidden;width:88px}a.maplibregl-ctrl-logo.maplibregl-compact{width:14px}@media(forced-colors:active){a.maplibregl-ctrl-logo{background-color:transparent;background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='88' height='23' fill='none'%3E%3Cpath fill='%23000' fill-opacity='.4' fill-rule='evenodd' d='M17.408 16.796h-1.827l2.501-12.095h.198l3.324 6.533.988 2.19.988-2.19 3.258-6.533h.181l2.6 12.095h-1.81l-1.218-5.644-.362-1.71-.658 1.71-2.929 5.644h-.098l-2.914-5.644-.757-1.71-.345 1.71zm1.958-3.42-.726 3.663a1.255 1.255 0 0 1-1.232 1.011h-1.827a1.255 1.255 0 0 1-1.229-1.509l2.501-12.095a1.255 1.255 0 0 1 1.23-1.001h.197a1.25 1.25 0 0 1 1.12.685l3.19 6.273 3.125-6.263a1.25 1.25 0 0 1 1.123-.695h.181a1.255 1.255 0 0 1 1.227.991l1.443 6.71a5 5 0 0 1 .314-.787l.009-.016a4.6 4.6 0 0 1 1.777-1.887c.782-.46 1.668-.667 2.611-.667a4.6 4.6 0 0 1 1.7.32l.306.134c.21-.16.474-.256.759-.256h1.694a1.255 1.255 0 0 1 1.212.925 1.255 1.255 0 0 1 1.212-.925h1.711c.284 0 .545.094.755.252.613-.3 1.312-.45 2.075-.45 1.356 0 2.557.445 3.482 1.4q.47.48.763 1.064V4.701a1.255 1.255 0 0 1 1.255-1.255h1.86A1.255 1.255 0 0 1 54.44 4.7v9.194h2.217c.19 0 .37.043.532.118v-4.77c0-.356.147-.678.385-.906a2.42 2.42 0 0 1-.682-1.71c0-.665.267-1.253.735-1.7a2.45 2.45 0 0 1 1.722-.674 2.43 2.43 0 0 1 1.705.675q.318.302.504.683V4.7a1.255 1.255 0 0 1 1.255-1.255h1.744A1.255 1.255 0 0 1 65.812 4.7v3.335a4.8 4.8 0 0 1 1.526-.246c.938 0 1.817.214 2.59.69a4.47 4.47 0 0 1 1.67 1.743v-.98a1.255 1.255 0 0 1 1.256-1.256h1.777c.233 0 .451.064.639.174a3.4 3.4 0 0 1 1.567-.372c.346 0 .861.02 1.285.232a1.25 1.25 0 0 1 .689 1.004 4.7 4.7 0 0 1 .853-.588c.795-.44 1.675-.647 2.61-.647 1.385 0 2.65.39 3.525 1.396.836.938 1.168 2.173 1.168 3.528q-.001.515-.056 1.051a1.255 1.255 0 0 1-.947 1.09l.408.952a1.255 1.255 0 0 1-.477 1.552c-.418.268-.92.463-1.458.612-.613.171-1.304.244-2.049.244-1.06 0-2.043-.207-2.886-.698l-.015-.008c-.798-.48-1.419-1.135-1.818-1.963l-.004-.008a5.8 5.8 0 0 1-.548-2.512q0-.429.053-.843a1.3 1.3 0 0 1-.333-.086l-.166-.004c-.223 0-.426.062-.643.228-.03.024-.142.139-.142.59v3.883a1.255 1.255 0 0 1-1.256 1.256h-1.777a1.255 1.255 0 0 1-1.256-1.256V15.69l-.032.057a4.8 4.8 0 0 1-1.86 1.833 5.04 5.04 0 0 1-2.484.634 4.5 4.5 0 0 1-1.935-.424 1.25 1.25 0 0 1-.764.258h-1.71a1.255 1.255 0 0 1-1.256-1.255V7.687a2.4 2.4 0 0 1-.428.625c.253.23.412.561.412.93v7.553a1.255 1.255 0 0 1-1.256 1.255h-1.843a1.25 1.25 0 0 1-.894-.373c-.228.23-.544.373-.894.373H51.32a1.255 1.255 0 0 1-1.256-1.255v-1.251l-.061.117a4.7 4.7 0 0 1-1.782 1.884 4.77 4.77 0 0 1-2.485.67 5.6 5.6 0 0 1-1.485-.188l.009 2.764a1.255 1.255 0 0 1-1.255 1.259h-1.729a1.255 1.255 0 0 1-1.255-1.255v-3.537a1.255 1.255 0 0 1-1.167.793h-1.679a1.25 1.25 0 0 1-.77-.263 4.5 4.5 0 0 1-1.945.429c-.885 0-1.724-.21-2.495-.632l-.017-.01a5 5 0 0 1-1.081-.836 1.255 1.255 0 0 1-1.254 1.312h-1.81a1.255 1.255 0 0 1-1.228-.99l-.782-3.625-2.044 3.939a1.25 1.25 0 0 1-1.115.676h-.098a1.25 1.25 0 0 1-1.116-.68l-2.061-3.994zM35.92 16.63l.207-.114.223-.15q.493-.356.735-.785l.061-.118.033 1.332h1.678V9.242h-1.694l-.033 1.267q-.133-.329-.526-.658l-.032-.028a3.2 3.2 0 0 0-.668-.428l-.27-.12a3.3 3.3 0 0 0-1.235-.23q-1.136-.001-1.974.493a3.36 3.36 0 0 0-1.3 1.382q-.445.89-.444 2.074 0 1.2.51 2.107a3.8 3.8 0 0 0 1.382 1.381 3.9 3.9 0 0 0 1.893.477q.795 0 1.455-.33zm-2.789-5.38q-.576.675-.575 1.762 0 1.102.559 1.794.576.675 1.645.675a2.25 2.25 0 0 0 .934-.19 2.2 2.2 0 0 0 .468-.29l.178-.161a2.2 2.2 0 0 0 .397-.561q.244-.5.244-1.15v-.115q0-.708-.296-1.267l-.043-.077a2.2 2.2 0 0 0-.633-.709l-.13-.086-.047-.028a2.1 2.1 0 0 0-1.073-.285q-1.052 0-1.629.692zm2.316 2.706c.163-.17.28-.407.28-.83v-.114c0-.292-.06-.508-.15-.68a.96.96 0 0 0-.353-.389.85.85 0 0 0-.464-.127c-.4 0-.56.114-.664.239l-.01.012c-.148.174-.275.45-.275.945 0 .506.122.801.27.99.097.11.266.224.68.224.303 0 .504-.09.687-.269zm7.545 1.705a2.6 2.6 0 0 0 .331.423q.319.33.755.548l.173.074q.65.255 1.49.255 1.02 0 1.844-.493a3.45 3.45 0 0 0 1.316-1.4q.493-.904.493-2.089 0-1.909-.988-2.913-.988-1.02-2.584-1.02-.898 0-1.575.347a3 3 0 0 0-.415.262l-.199.166a3.4 3.4 0 0 0-.64.82V9.242h-1.712v11.553h1.729l-.017-5.134zm.53-1.138q.206.29.48.5l.155.11.053.034q.51.296 1.119.297 1.07 0 1.645-.675.577-.69.576-1.762 0-1.119-.576-1.777-.558-.675-1.645-.675-.435 0-.835.16a2 2 0 0 0-.284.136 2 2 0 0 0-.363.254 2.2 2.2 0 0 0-.46.569l-.082.162a2.6 2.6 0 0 0-.213 1.072v.115q0 .707.296 1.267l.135.211zm.964-.818a1.1 1.1 0 0 0 .367.385.94.94 0 0 0 .476.118c.423 0 .59-.117.687-.23.159-.194.28-.478.28-.95 0-.53-.133-.8-.266-.952l-.021-.025c-.078-.094-.231-.221-.68-.221a1 1 0 0 0-.503.135l-.012.007a.86.86 0 0 0-.335.343c-.073.133-.132.324-.132.614v.115a1.4 1.4 0 0 0 .14.66zm15.7-6.222q.347-.346.346-.856a1.05 1.05 0 0 0-.345-.79 1.18 1.18 0 0 0-.84-.329q-.51 0-.855.33a1.05 1.05 0 0 0-.346.79q0 .51.346.855.345.346.856.346.51 0 .839-.346zm4.337 9.314.033-1.332q.191.403.59.747l.098.081a4 4 0 0 0 .316.224l.223.122a3.2 3.2 0 0 0 1.44.322 3.8 3.8 0 0 0 1.875-.477 3.5 3.5 0 0 0 1.382-1.366q.527-.89.526-2.09 0-1.184-.444-2.073a3.24 3.24 0 0 0-1.283-1.399q-.823-.51-1.942-.51a3.5 3.5 0 0 0-1.527.344l-.086.043-.165.09a3 3 0 0 0-.33.214q-.432.315-.656.707a2 2 0 0 0-.099.198l.082-1.283V4.701h-1.744v12.095zm.473-2.509a2.5 2.5 0 0 0 .566.7q.117.098.245.18l.144.08a2.1 2.1 0 0 0 .975.232q1.07 0 1.645-.675.576-.69.576-1.778 0-1.102-.576-1.777-.56-.691-1.645-.692a2.2 2.2 0 0 0-1.015.235q-.22.113-.415.282l-.15.142a2.1 2.1 0 0 0-.42.594q-.223.479-.223 1.1v.115q0 .705.293 1.26zm2.616-.293c.157-.191.28-.479.28-.967 0-.51-.13-.79-.276-.961l-.021-.026c-.082-.1-.232-.225-.67-.225a.87.87 0 0 0-.681.279l-.012.011c-.154.155-.274.38-.274.807v.115c0 .285.057.499.144.669a1.1 1.1 0 0 0 .367.405c.137.082.28.123.455.123.423 0 .59-.118.686-.23zm8.266-3.013q.345-.13.724-.14l.069-.002q.493 0 .642.099l.247-1.794q-.196-.099-.717-.099a2.3 2.3 0 0 0-.545.063 2 2 0 0 0-.411.148 2.2 2.2 0 0 0-.4.249 2.5 2.5 0 0 0-.485.499 2.7 2.7 0 0 0-.32.581l-.05.137v-1.48h-1.778v7.553h1.777v-3.884q0-.546.159-.943a1.5 1.5 0 0 1 .466-.636 2.5 2.5 0 0 1 .399-.253 2 2 0 0 1 .224-.099zm9.784 2.656.05-.922q0-1.743-.856-2.698-.838-.97-2.584-.97-1.119-.001-2.007.493a3.46 3.46 0 0 0-1.4 1.382q-.493.906-.493 2.106 0 1.07.428 1.975.428.89 1.332 1.432.906.526 2.255.526.973 0 1.668-.185l.044-.012.135-.04q.613-.184.984-.421l-.542-1.267q-.3.162-.642.274l-.297.087q-.51.131-1.3.131-.954 0-1.497-.444a1.6 1.6 0 0 1-.192-.193q-.366-.44-.512-1.234l-.004-.021zm-5.427-1.256-.003.022h3.752v-.138q-.011-.727-.288-1.118a1 1 0 0 0-.156-.176q-.46-.428-1.316-.428-.986 0-1.494.604-.379.45-.494 1.234zm-27.053 2.77V4.7h-1.86v12.095h5.333V15.15zm7.103-5.908v7.553h-1.843V9.242h1.843z'/%3E%3Cpath fill='%23fff' d='m19.63 11.151-.757-1.71-.345 1.71-1.12 5.644h-1.827L18.083 4.7h.197l3.325 6.533.988 2.19.988-2.19L26.839 4.7h.181l2.6 12.095h-1.81l-1.218-5.644-.362-1.71-.658 1.71-2.93 5.644h-.098l-2.913-5.644zm14.836 5.81q-1.02 0-1.893-.478a3.8 3.8 0 0 1-1.381-1.382q-.51-.906-.51-2.106 0-1.185.444-2.074a3.36 3.36 0 0 1 1.3-1.382q.839-.494 1.974-.494a3.3 3.3 0 0 1 1.234.231 3.3 3.3 0 0 1 .97.575q.396.33.527.659l.033-1.267h1.694v7.553H37.18l-.033-1.332q-.279.593-1.02 1.053a3.17 3.17 0 0 1-1.662.444zm.296-1.482q.938 0 1.58-.642.642-.66.642-1.711v-.115q0-.708-.296-1.267a2.2 2.2 0 0 0-.807-.872 2.1 2.1 0 0 0-1.119-.313q-1.053 0-1.629.692-.575.675-.575 1.76 0 1.103.559 1.795.577.675 1.645.675zm6.521-6.237h1.711v1.4q.906-1.597 2.83-1.597 1.596 0 2.584 1.02.988 1.005.988 2.914 0 1.185-.493 2.09a3.46 3.46 0 0 1-1.316 1.399 3.5 3.5 0 0 1-1.844.493q-.954 0-1.662-.329a2.67 2.67 0 0 1-1.086-.97l.017 5.134h-1.728zm4.048 6.22q1.07 0 1.645-.674.577-.69.576-1.762 0-1.119-.576-1.777-.558-.675-1.645-.675-.592 0-1.12.296-.51.28-.822.823-.296.527-.296 1.234v.115q0 .708.296 1.267.313.543.823.855.51.296 1.119.297z'/%3E%3Cpath fill='%23e1e3e9' d='M51.325 4.7h1.86v10.45h3.473v1.646h-5.333zm7.12 4.542h1.843v7.553h-1.843zm.905-1.415a1.16 1.16 0 0 1-.856-.346 1.17 1.17 0 0 1-.346-.856 1.05 1.05 0 0 1 .346-.79q.346-.329.856-.329.494 0 .839.33a1.05 1.05 0 0 1 .345.79 1.16 1.16 0 0 1-.345.855q-.33.346-.84.346zm7.875 9.133a3.17 3.17 0 0 1-1.662-.444q-.723-.46-1.004-1.053l-.033 1.332h-1.71V4.701h1.743v4.657l-.082 1.283q.279-.658 1.086-1.119a3.5 3.5 0 0 1 1.778-.477q1.119 0 1.942.51a3.24 3.24 0 0 1 1.283 1.4q.445.888.444 2.072 0 1.201-.526 2.09a3.5 3.5 0 0 1-1.382 1.366 3.8 3.8 0 0 1-1.876.477zm-.296-1.481q1.069 0 1.645-.675.577-.69.577-1.778 0-1.102-.577-1.776-.56-.691-1.645-.692a2.12 2.12 0 0 0-1.58.659q-.642.641-.642 1.694v.115q0 .71.296 1.267a2.4 2.4 0 0 0 .807.872 2.1 2.1 0 0 0 1.119.313zm5.927-6.237h1.777v1.481q.263-.757.856-1.217a2.14 2.14 0 0 1 1.349-.46q.527 0 .724.098l-.247 1.794q-.149-.099-.642-.099-.774 0-1.416.494-.626.493-.626 1.58v3.883h-1.777V9.242zm9.534 7.718q-1.35 0-2.255-.526-.904-.543-1.332-1.432a4.6 4.6 0 0 1-.428-1.975q0-1.2.493-2.106a3.46 3.46 0 0 1 1.4-1.382q.889-.495 2.007-.494 1.744 0 2.584.97.855.956.856 2.7 0 .444-.05.92h-5.43q.18 1.005.708 1.45.542.443 1.497.443.79 0 1.3-.131a4 4 0 0 0 .938-.362l.542 1.267q-.411.263-1.119.46-.708.198-1.711.197zm1.596-4.558q.016-1.02-.444-1.432-.46-.428-1.316-.428-1.728 0-1.991 1.86z'/%3E%3Cpath d='M5.074 15.948a.484.657 0 0 0-.486.659v1.84a.484.657 0 0 0 .486.659h4.101a.484.657 0 0 0 .486-.659v-1.84a.484.657 0 0 0-.486-.659zm3.56 1.16H5.617v.838h3.017z' style='fill:%23fff;fill-rule:evenodd;stroke-width:1.03600001'/%3E%3Cg style='stroke-width:1.12603545'%3E%3Cpath d='M-9.408-1.416c-3.833-.025-7.056 2.912-7.08 6.615-.02 3.08 1.653 4.832 3.107 6.268.903.892 1.721 1.74 2.32 2.902l-.525-.004c-.543-.003-.992.304-1.24.639a1.87 1.87 0 0 0-.362 1.121l-.011 1.877c-.003.402.104.787.347 1.125.244.338.688.653 1.23.656l4.142.028c.542.003.99-.306 1.238-.641a1.87 1.87 0 0 0 .363-1.121l.012-1.875a1.87 1.87 0 0 0-.348-1.127c-.243-.338-.688-.653-1.23-.656l-.518-.004c.597-1.145 1.425-1.983 2.348-2.87 1.473-1.414 3.18-3.149 3.2-6.226-.016-3.59-2.923-6.684-6.993-6.707m-.006 1.1v.002c3.274.02 5.92 2.532 5.9 5.6-.017 2.706-1.39 4.026-2.863 5.44-1.034.994-2.118 2.033-2.814 3.633-.018.041-.052.055-.075.065q-.013.004-.02.01a.34.34 0 0 1-.226.084.34.34 0 0 1-.224-.086l-.092-.077c-.699-1.615-1.768-2.669-2.781-3.67-1.454-1.435-2.797-2.762-2.78-5.478.02-3.067 2.7-5.545 5.975-5.523m-.02 2.826c-1.62-.01-2.944 1.315-2.955 2.96-.01 1.646 1.295 2.988 2.916 2.999h.002c1.621.01 2.943-1.316 2.953-2.961.011-1.646-1.294-2.988-2.916-2.998m-.005 1.1c1.017.006 1.829.83 1.822 1.89s-.83 1.874-1.848 1.867c-1.018-.006-1.829-.83-1.822-1.89s.83-1.874 1.848-1.868m-2.155 11.857 4.14.025c.271.002.49.305.487.676l-.013 1.875c-.003.37-.224.67-.495.668l-4.14-.025c-.27-.002-.487-.306-.485-.676l.012-1.875c.003-.37.224-.67.494-.668' style='color:%23000;font-style:normal;font-variant:normal;font-weight:400;font-stretch:normal;font-size:medium;line-height:normal;font-family:sans-serif;font-variant-ligatures:normal;font-variant-position:normal;font-variant-caps:normal;font-variant-numeric:normal;font-variant-alternates:normal;font-feature-settings:normal;text-indent:0;text-align:start;text-decoration:none;text-decoration-line:none;text-decoration-style:solid;text-decoration-color:%23000;letter-spacing:normal;word-spacing:normal;text-transform:none;writing-mode:lr-tb;direction:ltr;text-orientation:mixed;dominant-baseline:auto;baseline-shift:baseline;text-anchor:start;white-space:normal;shape-padding:0;clip-rule:evenodd;display:inline;overflow:visible;visibility:visible;opacity:1;isolation:auto;mix-blend-mode:normal;color-interpolation:sRGB;color-interpolation-filters:linearRGB;solid-color:%23000;solid-opacity:1;vector-effect:none;fill:%23000;fill-opacity:.4;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;color-rendering:auto;image-rendering:auto;shape-rendering:auto;text-rendering:auto' transform='translate(15.553 2.85)scale(.88807)'/%3E%3Cpath d='M-9.415-.316C-12.69-.338-15.37 2.14-15.39 5.207c-.017 2.716 1.326 4.041 2.78 5.477 1.013 1 2.081 2.055 2.78 3.67l.092.076a.34.34 0 0 0 .225.086.34.34 0 0 0 .227-.083l.019-.01c.022-.009.057-.024.074-.064.697-1.6 1.78-2.64 2.814-3.634 1.473-1.414 2.847-2.733 2.864-5.44.02-3.067-2.627-5.58-5.901-5.601m-.057 8.784c1.621.011 2.944-1.315 2.955-2.96.01-1.646-1.295-2.988-2.916-2.999-1.622-.01-2.945 1.315-2.955 2.96s1.295 2.989 2.916 3' style='clip-rule:evenodd;fill:%23e1e3e9;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:.4' transform='translate(15.553 2.85)scale(.88807)'/%3E%3Cpath d='M-11.594 15.465c-.27-.002-.492.297-.494.668l-.012 1.876c-.003.371.214.673.485.675l4.14.027c.271.002.492-.298.495-.668l.012-1.877c.003-.37-.215-.672-.485-.674z' style='clip-rule:evenodd;fill:%23fff;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:.4' transform='translate(15.553 2.85)scale(.88807)'/%3E%3C/g%3E%3C/svg%3E")}}@media(forced-colors:active)and (prefers-color-scheme:light){a.maplibregl-ctrl-logo{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='88' height='23' fill='none'%3E%3Cpath fill='%23000' fill-opacity='.4' fill-rule='evenodd' d='M17.408 16.796h-1.827l2.501-12.095h.198l3.324 6.533.988 2.19.988-2.19 3.258-6.533h.181l2.6 12.095h-1.81l-1.218-5.644-.362-1.71-.658 1.71-2.929 5.644h-.098l-2.914-5.644-.757-1.71-.345 1.71zm1.958-3.42-.726 3.663a1.255 1.255 0 0 1-1.232 1.011h-1.827a1.255 1.255 0 0 1-1.229-1.509l2.501-12.095a1.255 1.255 0 0 1 1.23-1.001h.197a1.25 1.25 0 0 1 1.12.685l3.19 6.273 3.125-6.263a1.25 1.25 0 0 1 1.123-.695h.181a1.255 1.255 0 0 1 1.227.991l1.443 6.71a5 5 0 0 1 .314-.787l.009-.016a4.6 4.6 0 0 1 1.777-1.887c.782-.46 1.668-.667 2.611-.667a4.6 4.6 0 0 1 1.7.32l.306.134c.21-.16.474-.256.759-.256h1.694a1.255 1.255 0 0 1 1.212.925 1.255 1.255 0 0 1 1.212-.925h1.711c.284 0 .545.094.755.252.613-.3 1.312-.45 2.075-.45 1.356 0 2.557.445 3.482 1.4q.47.48.763 1.064V4.701a1.255 1.255 0 0 1 1.255-1.255h1.86A1.255 1.255 0 0 1 54.44 4.7v9.194h2.217c.19 0 .37.043.532.118v-4.77c0-.356.147-.678.385-.906a2.42 2.42 0 0 1-.682-1.71c0-.665.267-1.253.735-1.7a2.45 2.45 0 0 1 1.722-.674 2.43 2.43 0 0 1 1.705.675q.318.302.504.683V4.7a1.255 1.255 0 0 1 1.255-1.255h1.744A1.255 1.255 0 0 1 65.812 4.7v3.335a4.8 4.8 0 0 1 1.526-.246c.938 0 1.817.214 2.59.69a4.47 4.47 0 0 1 1.67 1.743v-.98a1.255 1.255 0 0 1 1.256-1.256h1.777c.233 0 .451.064.639.174a3.4 3.4 0 0 1 1.567-.372c.346 0 .861.02 1.285.232a1.25 1.25 0 0 1 .689 1.004 4.7 4.7 0 0 1 .853-.588c.795-.44 1.675-.647 2.61-.647 1.385 0 2.65.39 3.525 1.396.836.938 1.168 2.173 1.168 3.528q-.001.515-.056 1.051a1.255 1.255 0 0 1-.947 1.09l.408.952a1.255 1.255 0 0 1-.477 1.552c-.418.268-.92.463-1.458.612-.613.171-1.304.244-2.049.244-1.06 0-2.043-.207-2.886-.698l-.015-.008c-.798-.48-1.419-1.135-1.818-1.963l-.004-.008a5.8 5.8 0 0 1-.548-2.512q0-.429.053-.843a1.3 1.3 0 0 1-.333-.086l-.166-.004c-.223 0-.426.062-.643.228-.03.024-.142.139-.142.59v3.883a1.255 1.255 0 0 1-1.256 1.256h-1.777a1.255 1.255 0 0 1-1.256-1.256V15.69l-.032.057a4.8 4.8 0 0 1-1.86 1.833 5.04 5.04 0 0 1-2.484.634 4.5 4.5 0 0 1-1.935-.424 1.25 1.25 0 0 1-.764.258h-1.71a1.255 1.255 0 0 1-1.256-1.255V7.687a2.4 2.4 0 0 1-.428.625c.253.23.412.561.412.93v7.553a1.255 1.255 0 0 1-1.256 1.255h-1.843a1.25 1.25 0 0 1-.894-.373c-.228.23-.544.373-.894.373H51.32a1.255 1.255 0 0 1-1.256-1.255v-1.251l-.061.117a4.7 4.7 0 0 1-1.782 1.884 4.77 4.77 0 0 1-2.485.67 5.6 5.6 0 0 1-1.485-.188l.009 2.764a1.255 1.255 0 0 1-1.255 1.259h-1.729a1.255 1.255 0 0 1-1.255-1.255v-3.537a1.255 1.255 0 0 1-1.167.793h-1.679a1.25 1.25 0 0 1-.77-.263 4.5 4.5 0 0 1-1.945.429c-.885 0-1.724-.21-2.495-.632l-.017-.01a5 5 0 0 1-1.081-.836 1.255 1.255 0 0 1-1.254 1.312h-1.81a1.255 1.255 0 0 1-1.228-.99l-.782-3.625-2.044 3.939a1.25 1.25 0 0 1-1.115.676h-.098a1.25 1.25 0 0 1-1.116-.68l-2.061-3.994zM35.92 16.63l.207-.114.223-.15q.493-.356.735-.785l.061-.118.033 1.332h1.678V9.242h-1.694l-.033 1.267q-.133-.329-.526-.658l-.032-.028a3.2 3.2 0 0 0-.668-.428l-.27-.12a3.3 3.3 0 0 0-1.235-.23q-1.136-.001-1.974.493a3.36 3.36 0 0 0-1.3 1.382q-.445.89-.444 2.074 0 1.2.51 2.107a3.8 3.8 0 0 0 1.382 1.381 3.9 3.9 0 0 0 1.893.477q.795 0 1.455-.33zm-2.789-5.38q-.576.675-.575 1.762 0 1.102.559 1.794.576.675 1.645.675a2.25 2.25 0 0 0 .934-.19 2.2 2.2 0 0 0 .468-.29l.178-.161a2.2 2.2 0 0 0 .397-.561q.244-.5.244-1.15v-.115q0-.708-.296-1.267l-.043-.077a2.2 2.2 0 0 0-.633-.709l-.13-.086-.047-.028a2.1 2.1 0 0 0-1.073-.285q-1.052 0-1.629.692zm2.316 2.706c.163-.17.28-.407.28-.83v-.114c0-.292-.06-.508-.15-.68a.96.96 0 0 0-.353-.389.85.85 0 0 0-.464-.127c-.4 0-.56.114-.664.239l-.01.012c-.148.174-.275.45-.275.945 0 .506.122.801.27.99.097.11.266.224.68.224.303 0 .504-.09.687-.269zm7.545 1.705a2.6 2.6 0 0 0 .331.423q.319.33.755.548l.173.074q.65.255 1.49.255 1.02 0 1.844-.493a3.45 3.45 0 0 0 1.316-1.4q.493-.904.493-2.089 0-1.909-.988-2.913-.988-1.02-2.584-1.02-.898 0-1.575.347a3 3 0 0 0-.415.262l-.199.166a3.4 3.4 0 0 0-.64.82V9.242h-1.712v11.553h1.729l-.017-5.134zm.53-1.138q.206.29.48.5l.155.11.053.034q.51.296 1.119.297 1.07 0 1.645-.675.577-.69.576-1.762 0-1.119-.576-1.777-.558-.675-1.645-.675-.435 0-.835.16a2 2 0 0 0-.284.136 2 2 0 0 0-.363.254 2.2 2.2 0 0 0-.46.569l-.082.162a2.6 2.6 0 0 0-.213 1.072v.115q0 .707.296 1.267l.135.211zm.964-.818a1.1 1.1 0 0 0 .367.385.94.94 0 0 0 .476.118c.423 0 .59-.117.687-.23.159-.194.28-.478.28-.95 0-.53-.133-.8-.266-.952l-.021-.025c-.078-.094-.231-.221-.68-.221a1 1 0 0 0-.503.135l-.012.007a.86.86 0 0 0-.335.343c-.073.133-.132.324-.132.614v.115a1.4 1.4 0 0 0 .14.66zm15.7-6.222q.347-.346.346-.856a1.05 1.05 0 0 0-.345-.79 1.18 1.18 0 0 0-.84-.329q-.51 0-.855.33a1.05 1.05 0 0 0-.346.79q0 .51.346.855.345.346.856.346.51 0 .839-.346zm4.337 9.314.033-1.332q.191.403.59.747l.098.081a4 4 0 0 0 .316.224l.223.122a3.2 3.2 0 0 0 1.44.322 3.8 3.8 0 0 0 1.875-.477 3.5 3.5 0 0 0 1.382-1.366q.527-.89.526-2.09 0-1.184-.444-2.073a3.24 3.24 0 0 0-1.283-1.399q-.823-.51-1.942-.51a3.5 3.5 0 0 0-1.527.344l-.086.043-.165.09a3 3 0 0 0-.33.214q-.432.315-.656.707a2 2 0 0 0-.099.198l.082-1.283V4.701h-1.744v12.095zm.473-2.509a2.5 2.5 0 0 0 .566.7q.117.098.245.18l.144.08a2.1 2.1 0 0 0 .975.232q1.07 0 1.645-.675.576-.69.576-1.778 0-1.102-.576-1.777-.56-.691-1.645-.692a2.2 2.2 0 0 0-1.015.235q-.22.113-.415.282l-.15.142a2.1 2.1 0 0 0-.42.594q-.223.479-.223 1.1v.115q0 .705.293 1.26zm2.616-.293c.157-.191.28-.479.28-.967 0-.51-.13-.79-.276-.961l-.021-.026c-.082-.1-.232-.225-.67-.225a.87.87 0 0 0-.681.279l-.012.011c-.154.155-.274.38-.274.807v.115c0 .285.057.499.144.669a1.1 1.1 0 0 0 .367.405c.137.082.28.123.455.123.423 0 .59-.118.686-.23zm8.266-3.013q.345-.13.724-.14l.069-.002q.493 0 .642.099l.247-1.794q-.196-.099-.717-.099a2.3 2.3 0 0 0-.545.063 2 2 0 0 0-.411.148 2.2 2.2 0 0 0-.4.249 2.5 2.5 0 0 0-.485.499 2.7 2.7 0 0 0-.32.581l-.05.137v-1.48h-1.778v7.553h1.777v-3.884q0-.546.159-.943a1.5 1.5 0 0 1 .466-.636 2.5 2.5 0 0 1 .399-.253 2 2 0 0 1 .224-.099zm9.784 2.656.05-.922q0-1.743-.856-2.698-.838-.97-2.584-.97-1.119-.001-2.007.493a3.46 3.46 0 0 0-1.4 1.382q-.493.906-.493 2.106 0 1.07.428 1.975.428.89 1.332 1.432.906.526 2.255.526.973 0 1.668-.185l.044-.012.135-.04q.613-.184.984-.421l-.542-1.267q-.3.162-.642.274l-.297.087q-.51.131-1.3.131-.954 0-1.497-.444a1.6 1.6 0 0 1-.192-.193q-.366-.44-.512-1.234l-.004-.021zm-5.427-1.256-.003.022h3.752v-.138q-.011-.727-.288-1.118a1 1 0 0 0-.156-.176q-.46-.428-1.316-.428-.986 0-1.494.604-.379.45-.494 1.234zm-27.053 2.77V4.7h-1.86v12.095h5.333V15.15zm7.103-5.908v7.553h-1.843V9.242h1.843z'/%3E%3Cpath fill='%23fff' d='m19.63 11.151-.757-1.71-.345 1.71-1.12 5.644h-1.827L18.083 4.7h.197l3.325 6.533.988 2.19.988-2.19L26.839 4.7h.181l2.6 12.095h-1.81l-1.218-5.644-.362-1.71-.658 1.71-2.93 5.644h-.098l-2.913-5.644zm14.836 5.81q-1.02 0-1.893-.478a3.8 3.8 0 0 1-1.381-1.382q-.51-.906-.51-2.106 0-1.185.444-2.074a3.36 3.36 0 0 1 1.3-1.382q.839-.494 1.974-.494a3.3 3.3 0 0 1 1.234.231 3.3 3.3 0 0 1 .97.575q.396.33.527.659l.033-1.267h1.694v7.553H37.18l-.033-1.332q-.279.593-1.02 1.053a3.17 3.17 0 0 1-1.662.444zm.296-1.482q.938 0 1.58-.642.642-.66.642-1.711v-.115q0-.708-.296-1.267a2.2 2.2 0 0 0-.807-.872 2.1 2.1 0 0 0-1.119-.313q-1.053 0-1.629.692-.575.675-.575 1.76 0 1.103.559 1.795.577.675 1.645.675zm6.521-6.237h1.711v1.4q.906-1.597 2.83-1.597 1.596 0 2.584 1.02.988 1.005.988 2.914 0 1.185-.493 2.09a3.46 3.46 0 0 1-1.316 1.399 3.5 3.5 0 0 1-1.844.493q-.954 0-1.662-.329a2.67 2.67 0 0 1-1.086-.97l.017 5.134h-1.728zm4.048 6.22q1.07 0 1.645-.674.577-.69.576-1.762 0-1.119-.576-1.777-.558-.675-1.645-.675-.592 0-1.12.296-.51.28-.822.823-.296.527-.296 1.234v.115q0 .708.296 1.267.313.543.823.855.51.296 1.119.297z'/%3E%3Cpath fill='%23e1e3e9' d='M51.325 4.7h1.86v10.45h3.473v1.646h-5.333zm7.12 4.542h1.843v7.553h-1.843zm.905-1.415a1.16 1.16 0 0 1-.856-.346 1.17 1.17 0 0 1-.346-.856 1.05 1.05 0 0 1 .346-.79q.346-.329.856-.329.494 0 .839.33a1.05 1.05 0 0 1 .345.79 1.16 1.16 0 0 1-.345.855q-.33.346-.84.346zm7.875 9.133a3.17 3.17 0 0 1-1.662-.444q-.723-.46-1.004-1.053l-.033 1.332h-1.71V4.701h1.743v4.657l-.082 1.283q.279-.658 1.086-1.119a3.5 3.5 0 0 1 1.778-.477q1.119 0 1.942.51a3.24 3.24 0 0 1 1.283 1.4q.445.888.444 2.072 0 1.201-.526 2.09a3.5 3.5 0 0 1-1.382 1.366 3.8 3.8 0 0 1-1.876.477zm-.296-1.481q1.069 0 1.645-.675.577-.69.577-1.778 0-1.102-.577-1.776-.56-.691-1.645-.692a2.12 2.12 0 0 0-1.58.659q-.642.641-.642 1.694v.115q0 .71.296 1.267a2.4 2.4 0 0 0 .807.872 2.1 2.1 0 0 0 1.119.313zm5.927-6.237h1.777v1.481q.263-.757.856-1.217a2.14 2.14 0 0 1 1.349-.46q.527 0 .724.098l-.247 1.794q-.149-.099-.642-.099-.774 0-1.416.494-.626.493-.626 1.58v3.883h-1.777V9.242zm9.534 7.718q-1.35 0-2.255-.526-.904-.543-1.332-1.432a4.6 4.6 0 0 1-.428-1.975q0-1.2.493-2.106a3.46 3.46 0 0 1 1.4-1.382q.889-.495 2.007-.494 1.744 0 2.584.97.855.956.856 2.7 0 .444-.05.92h-5.43q.18 1.005.708 1.45.542.443 1.497.443.79 0 1.3-.131a4 4 0 0 0 .938-.362l.542 1.267q-.411.263-1.119.46-.708.198-1.711.197zm1.596-4.558q.016-1.02-.444-1.432-.46-.428-1.316-.428-1.728 0-1.991 1.86z'/%3E%3Cpath d='M5.074 15.948a.484.657 0 0 0-.486.659v1.84a.484.657 0 0 0 .486.659h4.101a.484.657 0 0 0 .486-.659v-1.84a.484.657 0 0 0-.486-.659zm3.56 1.16H5.617v.838h3.017z' style='fill:%23fff;fill-rule:evenodd;stroke-width:1.03600001'/%3E%3Cg style='stroke-width:1.12603545'%3E%3Cpath d='M-9.408-1.416c-3.833-.025-7.056 2.912-7.08 6.615-.02 3.08 1.653 4.832 3.107 6.268.903.892 1.721 1.74 2.32 2.902l-.525-.004c-.543-.003-.992.304-1.24.639a1.87 1.87 0 0 0-.362 1.121l-.011 1.877c-.003.402.104.787.347 1.125.244.338.688.653 1.23.656l4.142.028c.542.003.99-.306 1.238-.641a1.87 1.87 0 0 0 .363-1.121l.012-1.875a1.87 1.87 0 0 0-.348-1.127c-.243-.338-.688-.653-1.23-.656l-.518-.004c.597-1.145 1.425-1.983 2.348-2.87 1.473-1.414 3.18-3.149 3.2-6.226-.016-3.59-2.923-6.684-6.993-6.707m-.006 1.1v.002c3.274.02 5.92 2.532 5.9 5.6-.017 2.706-1.39 4.026-2.863 5.44-1.034.994-2.118 2.033-2.814 3.633-.018.041-.052.055-.075.065q-.013.004-.02.01a.34.34 0 0 1-.226.084.34.34 0 0 1-.224-.086l-.092-.077c-.699-1.615-1.768-2.669-2.781-3.67-1.454-1.435-2.797-2.762-2.78-5.478.02-3.067 2.7-5.545 5.975-5.523m-.02 2.826c-1.62-.01-2.944 1.315-2.955 2.96-.01 1.646 1.295 2.988 2.916 2.999h.002c1.621.01 2.943-1.316 2.953-2.961.011-1.646-1.294-2.988-2.916-2.998m-.005 1.1c1.017.006 1.829.83 1.822 1.89s-.83 1.874-1.848 1.867c-1.018-.006-1.829-.83-1.822-1.89s.83-1.874 1.848-1.868m-2.155 11.857 4.14.025c.271.002.49.305.487.676l-.013 1.875c-.003.37-.224.67-.495.668l-4.14-.025c-.27-.002-.487-.306-.485-.676l.012-1.875c.003-.37.224-.67.494-.668' style='color:%23000;font-style:normal;font-variant:normal;font-weight:400;font-stretch:normal;font-size:medium;line-height:normal;font-family:sans-serif;font-variant-ligatures:normal;font-variant-position:normal;font-variant-caps:normal;font-variant-numeric:normal;font-variant-alternates:normal;font-feature-settings:normal;text-indent:0;text-align:start;text-decoration:none;text-decoration-line:none;text-decoration-style:solid;text-decoration-color:%23000;letter-spacing:normal;word-spacing:normal;text-transform:none;writing-mode:lr-tb;direction:ltr;text-orientation:mixed;dominant-baseline:auto;baseline-shift:baseline;text-anchor:start;white-space:normal;shape-padding:0;clip-rule:evenodd;display:inline;overflow:visible;visibility:visible;opacity:1;isolation:auto;mix-blend-mode:normal;color-interpolation:sRGB;color-interpolation-filters:linearRGB;solid-color:%23000;solid-opacity:1;vector-effect:none;fill:%23000;fill-opacity:.4;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;color-rendering:auto;image-rendering:auto;shape-rendering:auto;text-rendering:auto' transform='translate(15.553 2.85)scale(.88807)'/%3E%3Cpath d='M-9.415-.316C-12.69-.338-15.37 2.14-15.39 5.207c-.017 2.716 1.326 4.041 2.78 5.477 1.013 1 2.081 2.055 2.78 3.67l.092.076a.34.34 0 0 0 .225.086.34.34 0 0 0 .227-.083l.019-.01c.022-.009.057-.024.074-.064.697-1.6 1.78-2.64 2.814-3.634 1.473-1.414 2.847-2.733 2.864-5.44.02-3.067-2.627-5.58-5.901-5.601m-.057 8.784c1.621.011 2.944-1.315 2.955-2.96.01-1.646-1.295-2.988-2.916-2.999-1.622-.01-2.945 1.315-2.955 2.96s1.295 2.989 2.916 3' style='clip-rule:evenodd;fill:%23e1e3e9;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:.4' transform='translate(15.553 2.85)scale(.88807)'/%3E%3Cpath d='M-11.594 15.465c-.27-.002-.492.297-.494.668l-.012 1.876c-.003.371.214.673.485.675l4.14.027c.271.002.492-.298.495-.668l.012-1.877c.003-.37-.215-.672-.485-.674z' style='clip-rule:evenodd;fill:%23fff;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:.4' transform='translate(15.553 2.85)scale(.88807)'/%3E%3C/g%3E%3C/svg%3E")}}.maplibregl-ctrl.maplibregl-ctrl-attrib{background-color:#ffffff80;margin:0;padding:0 5px}@media screen{.maplibregl-ctrl-attrib.maplibregl-compact{background-color:#fff;border-radius:12px;box-sizing:content-box;color:#000;margin:10px;min-height:20px;padding:2px 24px 2px 0;position:relative}.maplibregl-ctrl-attrib.maplibregl-compact-show{padding:2px 28px 2px 8px;visibility:visible}.maplibregl-ctrl-bottom-left>.maplibregl-ctrl-attrib.maplibregl-compact-show,.maplibregl-ctrl-top-left>.maplibregl-ctrl-attrib.maplibregl-compact-show{border-radius:12px;padding:2px 8px 2px 28px}.maplibregl-ctrl-attrib.maplibregl-compact .maplibregl-ctrl-attrib-inner{display:none}.maplibregl-ctrl-attrib-button{background-color:#ffffff80;background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' fill-rule='evenodd' viewBox='0 0 20 20'%3E%3Cpath d='M4 10a6 6 0 1 0 12 0 6 6 0 1 0-12 0m5-3a1 1 0 1 0 2 0 1 1 0 1 0-2 0m0 3a1 1 0 1 1 2 0v3a1 1 0 1 1-2 0'/%3E%3C/svg%3E");border:0;border-radius:12px;box-sizing:border-box;cursor:pointer;display:none;height:24px;outline:none;position:absolute;right:0;top:0;width:24px}.maplibregl-ctrl-attrib summary.maplibregl-ctrl-attrib-button{-webkit-appearance:none;-moz-appearance:none;appearance:none;list-style:none}.maplibregl-ctrl-attrib summary.maplibregl-ctrl-attrib-button::-webkit-details-marker{display:none}.maplibregl-ctrl-bottom-left .maplibregl-ctrl-attrib-button,.maplibregl-ctrl-top-left .maplibregl-ctrl-attrib-button{left:0}.maplibregl-ctrl-attrib.maplibregl-compact .maplibregl-ctrl-attrib-button,.maplibregl-ctrl-attrib.maplibregl-compact-show .maplibregl-ctrl-attrib-inner{display:block}.maplibregl-ctrl-attrib.maplibregl-compact-show .maplibregl-ctrl-attrib-button{background-color:#0000000d}.maplibregl-ctrl-bottom-right>.maplibregl-ctrl-attrib.maplibregl-compact:after{bottom:0;right:0}.maplibregl-ctrl-top-right>.maplibregl-ctrl-attrib.maplibregl-compact:after{right:0;top:0}.maplibregl-ctrl-top-left>.maplibregl-ctrl-attrib.maplibregl-compact:after{left:0;top:0}.maplibregl-ctrl-bottom-left>.maplibregl-ctrl-attrib.maplibregl-compact:after{bottom:0;left:0}}@media screen and (forced-colors:active){.maplibregl-ctrl-attrib.maplibregl-compact:after{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' fill='%23fff' fill-rule='evenodd' viewBox='0 0 20 20'%3E%3Cpath d='M4 10a6 6 0 1 0 12 0 6 6 0 1 0-12 0m5-3a1 1 0 1 0 2 0 1 1 0 1 0-2 0m0 3a1 1 0 1 1 2 0v3a1 1 0 1 1-2 0'/%3E%3C/svg%3E")}}@media screen and (forced-colors:active)and (prefers-color-scheme:light){.maplibregl-ctrl-attrib.maplibregl-compact:after{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' fill-rule='evenodd' viewBox='0 0 20 20'%3E%3Cpath d='M4 10a6 6 0 1 0 12 0 6 6 0 1 0-12 0m5-3a1 1 0 1 0 2 0 1 1 0 1 0-2 0m0 3a1 1 0 1 1 2 0v3a1 1 0 1 1-2 0'/%3E%3C/svg%3E")}}.maplibregl-ctrl-attrib a{color:#000000bf;text-decoration:none}.maplibregl-ctrl-attrib a:hover{color:inherit;text-decoration:underline}.maplibregl-attrib-empty{display:none}.maplibregl-ctrl-scale{background-color:#ffffffbf;border:2px solid #333;border-top:#333;box-sizing:border-box;color:#333;font-size:10px;padding:0 5px;white-space:nowrap}.maplibregl-popup{display:flex;left:0;pointer-events:none;position:absolute;top:0;will-change:transform}.maplibregl-popup-anchor-top,.maplibregl-popup-anchor-top-left,.maplibregl-popup-anchor-top-right{flex-direction:column}.maplibregl-popup-anchor-bottom,.maplibregl-popup-anchor-bottom-left,.maplibregl-popup-anchor-bottom-right{flex-direction:column-reverse}.maplibregl-popup-anchor-left{flex-direction:row}.maplibregl-popup-anchor-right{flex-direction:row-reverse}.maplibregl-popup-tip{border:10px solid transparent;height:0;width:0;z-index:1}.maplibregl-popup-anchor-top .maplibregl-popup-tip{align-self:center;border-bottom-color:#fff;border-top:none}.maplibregl-popup-anchor-top-left .maplibregl-popup-tip{align-self:flex-start;border-bottom-color:#fff;border-left:none;border-top:none}.maplibregl-popup-anchor-top-right .maplibregl-popup-tip{align-self:flex-end;border-bottom-color:#fff;border-right:none;border-top:none}.maplibregl-popup-anchor-bottom .maplibregl-popup-tip{align-self:center;border-bottom:none;border-top-color:#fff}.maplibregl-popup-anchor-bottom-left .maplibregl-popup-tip{align-self:flex-start;border-bottom:none;border-left:none;border-top-color:#fff}.maplibregl-popup-anchor-bottom-right .maplibregl-popup-tip{align-self:flex-end;border-bottom:none;border-right:none;border-top-color:#fff}.maplibregl-popup-anchor-left .maplibregl-popup-tip{align-self:center;border-left:none;border-right-color:#fff}.maplibregl-popup-anchor-right .maplibregl-popup-tip{align-self:center;border-left-color:#fff;border-right:none}[dir=rtl] .maplibregl-popup-anchor-left{flex-direction:row-reverse}[dir=rtl] .maplibregl-popup-anchor-right{flex-direction:row}[dir=rtl] .maplibregl-popup-anchor-top-left .maplibregl-popup-tip{align-self:flex-end}[dir=rtl] .maplibregl-popup-anchor-top-right .maplibregl-popup-tip{align-self:flex-start}[dir=rtl] .maplibregl-popup-anchor-bottom-left .maplibregl-popup-tip{align-self:flex-end}[dir=rtl] .maplibregl-popup-anchor-bottom-right .maplibregl-popup-tip{align-self:flex-start}.maplibregl-popup-close-button{background-color:transparent;border:0;border-radius:0 3px 0 0;cursor:pointer;position:absolute;right:0;top:0}.maplibregl-popup-close-button:hover{background-color:#0000000d}.maplibregl-popup-content{background:#fff;border-radius:3px;box-shadow:0 1px 2px #0000001a;padding:15px 10px;pointer-events:auto;position:relative}.maplibregl-popup-anchor-top-left .maplibregl-popup-content{border-top-left-radius:0}.maplibregl-popup-anchor-top-right .maplibregl-popup-content{border-top-right-radius:0}.maplibregl-popup-anchor-bottom-left .maplibregl-popup-content{border-bottom-left-radius:0}.maplibregl-popup-anchor-bottom-right .maplibregl-popup-content{border-bottom-right-radius:0}.maplibregl-popup-track-pointer{display:none}.maplibregl-popup-track-pointer *{pointer-events:none;-webkit-user-select:none;-moz-user-select:none;user-select:none}.maplibregl-map:hover .maplibregl-popup-track-pointer{display:flex}.maplibregl-map:active .maplibregl-popup-track-pointer{display:none}.maplibregl-marker{left:0;position:absolute;top:0;transition:opacity .2s;will-change:transform}.maplibregl-user-location-dot,.maplibregl-user-location-dot:before{background-color:#1da1f2;border-radius:50%;height:15px;width:15px}.maplibregl-user-location-dot:before{animation:maplibregl-user-location-dot-pulse 2s infinite;content:"";position:absolute}.maplibregl-user-location-dot:after{border:2px solid #fff;border-radius:50%;box-shadow:0 0 3px #00000059;box-sizing:border-box;content:"";height:19px;left:-2px;position:absolute;top:-2px;width:19px}@media(prefers-reduced-motion:reduce){.maplibregl-user-location-dot:before{animation:none}}@keyframes maplibregl-user-location-dot-pulse{0%{opacity:1;transform:scale(1)}70%{opacity:0;transform:scale(3)}to{opacity:0;transform:scale(1)}}.maplibregl-user-location-dot-stale{background-color:#aaa}.maplibregl-user-location-dot-stale:after{display:none}.maplibregl-user-location-accuracy-circle{background-color:#1da1f233;border-radius:100%;height:1px;width:1px}.maplibregl-crosshair,.maplibregl-crosshair .maplibregl-interactive,.maplibregl-crosshair .maplibregl-interactive:active{cursor:crosshair}.maplibregl-boxzoom{background:#fff;border:2px dotted #202020;height:0;left:0;opacity:.5;position:absolute;top:0;width:0}.maplibregl-cooperative-gesture-screen{align-items:center;background:#0006;color:#fff;display:flex;font-size:1.4em;inset:0;justify-content:center;line-height:1.2;opacity:0;padding:1rem;pointer-events:none;position:absolute;transition:opacity 1s ease 1s;z-index:99999}.maplibregl-cooperative-gesture-screen.maplibregl-show{opacity:1;transition:opacity .05s}.maplibregl-cooperative-gesture-screen .maplibregl-mobile-message{display:none}@media(hover:none),(pointer:coarse){.maplibregl-cooperative-gesture-screen .maplibregl-desktop-message{display:none}.maplibregl-cooperative-gesture-screen .maplibregl-mobile-message{display:block}}.maplibregl-pseudo-fullscreen{height:100%!important;left:0!important;position:fixed!important;top:0!important;width:100%!important;z-index:99999}html{height:100%;overflow:hidden;overscroll-behavior:none}body.app-shell{position:fixed;inset:0;width:100%;height:100dvh;min-height:100dvh;max-height:100dvh;overflow:hidden;overscroll-behavior:none;grid-template-rows:var(--header-height, 64px) minmax(0,1fr)}body.app-shell .app-header{grid-row:1;position:fixed;top:0;right:0;left:0;height:var(--header-height, 64px);min-height:var(--header-height, 64px);max-height:var(--header-height, 64px);z-index:10000;transform:translateZ(0)}.mobile-pane-toggle{display:none}body.app-shell .app-main{grid-row:2;height:calc(100dvh - var(--header-height, 64px));min-height:0}@supports not (height: 100dvh){body.app-shell{height:100vh;min-height:100vh;max-height:100vh}body.app-shell .app-main{height:calc(100vh - var(--header-height, 64px))}}.app-shell{--map-min-height: 220px;--timeline-row-height: 58px;--test2-election-pane-height: min(38vh, max(120px, calc(100vh - var(--header-height, 64px) - var(--map-min-height, 220px) - var(--timeline-row-height, 58px) - 6px)))}.pane--map{min-height:0}#map,#map .maplibregl-map,#map .maplibregl-canvas-container,#map .maplibregl-canvas{touch-action:none!important;overscroll-behavior:contain;-webkit-user-select:none;user-select:none;-webkit-touch-callout:none}#map .maplibregl-canvas{pointer-events:auto}.pane--map>#timelineSlider.timeline-slider{position:static;inset:auto;z-index:auto;display:flex;flex:0 0 auto;align-items:center;justify-content:center;gap:var(--space-3);width:100%;max-width:none;height:auto;min-height:var(--timeline-row-height);margin:0;padding:var(--space-2) var(--space-4);appearance:none;background:var(--color-surface);border:1px solid var(--color-border);border-right:0;border-left:0;border-radius:0;box-shadow:none;cursor:default;transform:none}.pane--map>#timelineSlider.timeline-slider.hidden{display:none}.pane--map>#timelineSlider.timeline-slider .timeline-range{width:clamp(86px,22vw,220px)}.pane--map>#timelineSlider.timeline-slider .timeline-label{max-width:min(32vw,180px)}.pane--map>#timelineSlider.timeline-slider .timeline-playback-group{display:flex;align-items:center;gap:2px;flex:0 0 auto}.pane--map>#timelineSlider.timeline-slider .timeline-playback-group--hidden{display:none}.pane--map>#timelineSlider.timeline-slider .timeline-btn--play.is-playing,.pane--map>#timelineSlider.timeline-slider .timeline-btn--play.is-replay{color:#fff;background:var(--color-primary);border-color:var(--color-primary)}.pane--map>#timelineSlider.timeline-slider .timeline-btn--stop:not(:disabled){color:var(--color-danger, #b91c1c);border-color:color-mix(in srgb,var(--color-danger, #b91c1c) 42%,var(--color-border))}.pane--map>#timelineSlider.timeline-slider .timeline-btn--stop:hover:not(:disabled){color:#fff;background:var(--color-danger, #b91c1c);border-color:var(--color-danger, #b91c1c)}.maplibregl-ctrl-attrib a{color:#064f63;text-decoration:underline;text-underline-offset:2px}#map .maplibregl-ctrl-top-left{top:10px;left:12px;display:none}#map .maplibregl-ctrl-top-right{top:56px;right:12px}#map .maplibregl-ctrl-bottom-left{bottom:14px;left:12px}#map .maplibregl-ctrl-bottom-right{right:12px;bottom:14px}#map .maplibregl-ctrl-group{border:1px solid #b7c1c8;border-radius:4px;box-shadow:0 1px 5px #00000059;overflow:hidden}#map .maplibregl-ctrl-group button{width:30px;height:30px;background:#fff;color:#111827}#map .maplibregl-ctrl-group button+button{border-top:1px solid #cfd7df}#map .maplibregl-ctrl-compass{display:none}#map .test2-main-control-stack{position:absolute;top:10px;left:12px;z-index:15;display:flex;flex-direction:column;align-items:flex-start;gap:6px;pointer-events:none}#map .test2-main-control-stack>*{pointer-events:auto}#map .test2-main-zoom-control{position:static;margin:0;border:1px solid rgba(0,0,0,.35);border-radius:4px;background:#fff;box-shadow:0 1px 5px #00000059;overflow:hidden}#map .test2-main-zoom-control__button{display:block;width:30px;height:30px;padding:0;border:0;border-bottom:1px solid #cfd7df;background:#fff;color:#000;font:700 22px/28px Arial,Helvetica,sans-serif;text-align:center;cursor:pointer}#map .test2-main-zoom-control__button:last-child{border-bottom:0}#map .test2-main-zoom-control__button:hover,#map .test2-main-zoom-control__button:focus-visible{background:#f4f4f4;outline:none}#map .test2-main-zoom-control__compass{display:grid;place-items:center}#map .test2-main-zoom-control__compass-icon{width:18px;height:18px;fill:#111827;transform-origin:50% 50%;transition:transform .12s ease,fill .12s ease}#map .test2-main-zoom-control__compass--active .test2-main-zoom-control__compass-icon{fill:#064f63}#map #mobileToggle.mobile-toggle.mobile-toggle--map-stack{display:none}#map .maplibregl-ctrl-zoom-in .maplibregl-ctrl-icon,#map .maplibregl-ctrl-zoom-out .maplibregl-ctrl-icon{background-image:none;display:grid;place-items:center;font:700 21px/1 Arial,Helvetica,sans-serif}#map .maplibregl-ctrl-zoom-in .maplibregl-ctrl-icon:before{content:"+"}#map .maplibregl-ctrl-zoom-out .maplibregl-ctrl-icon:before{content:"-"}#map .active-layers-toggle{top:14px!important;right:14px!important}#map .map-controls{bottom:14px;left:14px;pointer-events:none}#map .map-controls>*{pointer-events:auto}.test2-election-seat-overlay{position:absolute;inset:0;z-index:18;pointer-events:none}.test2-election-seat-circle{background:transparent!important;border:0!important;box-shadow:none!important;pointer-events:auto;cursor:pointer}.test2-election-seat-circle:focus-visible{outline:2px solid #f97316;outline-offset:3px;border-radius:999px}.test2-election-seat-circle--synthetic{z-index:19}.test2-election-synthetic-label{height:18px;padding:1px 5px 2px;border:1px solid rgba(17,24,39,.72);border-radius:4px;background:#fffffff0;box-shadow:0 0 0 1px #ffffffd1,0 1px 3px #0003;color:#0f3764;font:700 11px/14px Arial,Helvetica,sans-serif;text-align:center;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;pointer-events:none}.test2-election-seat-dot{display:block;border-radius:50%;border:1px solid rgba(0,0,0,.6);box-shadow:0 0 0 1px #fff,0 .5px 2px #00000026}@media(max-width:768px){.app-shell{--map-min-height: 180px;--timeline-row-height: 54px}body.app-shell .app-header{gap:8px}body.app-shell .mobile-pane-toggle{display:inline-flex;align-items:center;justify-content:center;flex:0 0 auto;order:98;width:38px;height:38px;margin-left:auto;padding:0;color:#fff;background:#ffffff29;border:1px solid rgba(255,255,255,.28);border-radius:8px;box-shadow:0 1px 6px #00000038;font:700 22px/1 Arial,Helvetica,sans-serif;cursor:pointer;touch-action:manipulation}body.app-shell .mobile-pane-toggle:hover,body.app-shell .mobile-pane-toggle:focus-visible{background:#ffffff3d;outline:2px solid rgba(255,255,255,.55);outline-offset:2px}body.app-shell .mobile-menu-toggle{order:99;margin-left:0}.pane--map>#timelineSlider.timeline-slider{gap:6px;min-height:var(--timeline-row-height);padding:6px 8px}.pane--map>#timelineSlider.timeline-slider .timeline-range{width:clamp(76px,26vw,140px)}.pane--map>#timelineSlider.timeline-slider .timeline-label{max-width:96px}.pane--map>#timelineSlider.timeline-slider .timeline-playback-group{gap:1px}.pane--map>#timelineSlider.timeline-slider .timeline-btn{width:30px;height:30px}#map .maplibregl-ctrl-top-left{top:12px;left:12px}#map .active-layers-toggle{top:14px!important;right:14px!important}#map .map-controls{bottom:14px;left:12px;max-width:min(280px,calc(100vw - 104px))}#map .maplibregl-ctrl-bottom-right{right:12px;bottom:14px}#map #mobileToggle.mobile-toggle.mobile-toggle--map-stack{position:static!important;inset:auto!important;display:inline-flex!important;align-items:center;justify-content:center;flex:0 0 auto;width:32px;height:32px;margin:0;padding:0;color:#111827;background:#fff;border:1px solid rgba(0,0,0,.35);border-radius:4px;box-shadow:0 1px 5px #00000059;z-index:auto}#map #mobileToggle.mobile-toggle.mobile-toggle--map-stack:hover,#map #mobileToggle.mobile-toggle.mobile-toggle--map-stack:focus-visible{background:#f4f4f4}.maplibre-dom-label,.maplibre-dom-label *,.test2-election-seat-circle,.test2-election-seat-circle *{pointer-events:none!important}.test2-election-seat-circle[data-non-geographic=true]{touch-action:manipulation}}@media(min-width:769px){#map #mobileToggle.mobile-toggle.mobile-toggle--map-stack{display:none!important}}body.app-shell.test2-election-open{position:relative}body.app-shell.test2-election-open .pane--map{height:calc(100% - var(--test2-election-pane-height));min-height:var(--map-min-height, 220px)}body.app-shell.test2-election-open #electionResultsPane.election-results-pane--open{display:flex;flex-direction:column;overflow:hidden}.test2-election-pane-resizer{position:relative;flex:0 0 12px;width:100%;min-height:12px;cursor:row-resize;background:var(--color-border, #d8e0ea);border-top:1px solid #174569;border-bottom:1px solid #c4ced8;touch-action:none;z-index:20;user-select:none}.test2-election-pane-resizer:before{content:"";position:absolute;top:5px;left:50%;width:56px;height:2px;transform:translate(-50%);border-radius:999px;background:#5f7184}.test2-election-pane-resizer:hover,.test2-election-pane-resizer:focus-visible,body.test2-election-pane-resizing .test2-election-pane-resizer{background:#bdd7f3;outline:none}[data-theme=dark] .test2-election-pane-resizer{background:#314155;border-top-color:#6aa1d8;border-bottom-color:#172233}[data-theme=dark] .test2-election-pane-resizer:before{background:#d8e7f8}@media(prefers-color-scheme:dark){:root:not([data-theme=light]) .test2-election-pane-resizer{background:#314155;border-top-color:#6aa1d8;border-bottom-color:#172233}:root:not([data-theme=light]) .test2-election-pane-resizer:before{background:#d8e7f8}}body.test2-election-pane-resizing,body.test2-election-pane-resizing *{cursor:row-resize!important;user-select:none!important}[data-theme=dark] .maplibregl-ctrl-attrib,:root:not([data-theme=light]) .maplibregl-ctrl-attrib{background:#0f1419d9;color:#e6edf3}[data-theme=dark] .maplibregl-ctrl-attrib a,:root:not([data-theme=light]) .maplibregl-ctrl-attrib a{color:#8fd3ff}[data-theme=dark] .maplibregl-ctrl-group,:root:not([data-theme=light]) .maplibregl-ctrl-group{background:#1b2027}[data-theme=dark] .maplibregl-ctrl-group button,:root:not([data-theme=light]) .maplibregl-ctrl-group button{background:#1b2027}[data-theme=dark] .maplibregl-ctrl-group button+button,:root:not([data-theme=light]) .maplibregl-ctrl-group button+button{border-top-color:#333b45}[data-theme=dark] .maplibregl-ctrl-group button .maplibregl-ctrl-icon,:root:not([data-theme=light]) .maplibregl-ctrl-group button .maplibregl-ctrl-icon{filter:invert(1) brightness(1.6)}.maplibre-dom-label{display:inline-flex;align-items:center;justify-content:center;pointer-events:auto!important;cursor:pointer;z-index:4}.maplibre-dom-label div{position:relative;width:max-content;max-width:140px;color:#38f;font-weight:700;line-height:1.15;text-align:center;overflow-wrap:normal;word-break:keep-all;text-shadow:-1px -1px 0 #fff,1px -1px 0 #fff,-1px 1px 0 #fff,1px 1px 0 #fff;transition:color .12s ease,text-shadow .12s ease,text-decoration-color .12s ease}.maplibre-dom-label.map-label--hover div,.maplibre-dom-label.map-label--selected div,.maplibre-dom-label:hover div{color:#ff7a1a!important;text-decoration:underline;text-decoration-color:currentColor;text-underline-offset:2px;text-shadow:-1px -1px 0 #fff,1px -1px 0 #fff,-1px 1px 0 #fff,1px 1px 0 #fff}@media(max-width:768px),(pointer:coarse){#map .maplibregl-canvas-container,#map .maplibregl-canvas{touch-action:none!important}#map .test2-election-seat-overlay,#map .maplibre-dom-label,#map .maplibre-dom-label *,#map .test2-election-seat-circle,#map .test2-election-seat-circle *{pointer-events:none!important}}#test2Status.map-error{position:absolute;left:16px;bottom:18px;z-index:30;max-width:min(420px,calc(100% - 32px));padding:10px 12px;border:1px solid #f59e0b;border-radius:8px;background:#fffbeb;color:#78350f;box-shadow:0 8px 20px #0000001f;font-size:13px}.test2-source-panel{position:fixed;top:76px;right:18px;z-index:520;width:min(420px,calc(100% - 36px));max-height:min(620px,calc(100% - 110px));display:flex;flex-direction:column;border:1px solid var(--color-border, #d8e0ea);border-radius:8px;background:var(--color-surface, #fff);color:var(--color-text, #1a202c);box-shadow:0 16px 36px #0f172a2e;overflow:hidden}.test2-source-panel.hidden{display:none}.test2-source-panel__header{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:10px 12px;border-bottom:1px solid var(--color-border, #d8e0ea);background:var(--color-surface-elevated, #f7fafc)}.test2-source-panel__header h3,.test2-source-panel__record h4{margin:0;font-size:14px;line-height:1.25}.test2-source-panel__close,.test2-source-panel button{border:1px solid var(--color-border, #d8e0ea);border-radius:6px;background:var(--color-surface, #fff);color:var(--color-text, #1a202c);font:inherit;font-size:12px;line-height:1;padding:6px 8px;cursor:pointer}.test2-source-panel__content{overflow:auto;padding:12px}.test2-source-panel__record{display:grid;gap:10px;padding-bottom:14px}.test2-source-panel__record+.test2-source-panel__record{padding-top:14px;border-top:1px solid var(--color-border, #d8e0ea)}.test2-source-panel__record header,.test2-source-panel__record dl div,.test2-source-panel__link-row{display:flex;align-items:flex-start;justify-content:space-between;gap:10px}.test2-source-panel__record dl{display:grid;gap:6px;margin:0;font-size:12px}.test2-source-panel__record dt{color:var(--color-text-muted, #718096);font-weight:700;text-transform:uppercase}.test2-source-panel__record dd{margin:0;text-align:right;word-break:break-word}.test2-source-panel__record p,.test2-source-panel__group p,.test2-source-panel__link-row small{margin:0;color:var(--color-text-muted, #718096);font-size:12px;line-height:1.35}.test2-source-panel__group{border:1px solid var(--color-border, #d8e0ea);border-radius:6px;padding:8px}.test2-source-panel__group summary{cursor:pointer;font-size:12px;font-weight:700}.test2-source-panel__link-row{padding-top:8px;font-size:12px}.test2-source-panel__link-row a{min-width:0;overflow-wrap:anywhere;text-decoration:underline;text-underline-offset:2px}.test2-source-btn span{display:inline-flex;align-items:center;justify-content:center;width:14px;height:14px;border:1px solid currentColor;border-radius:999px;font-size:10px;font-weight:700;font-style:italic}.test2-election-panel{position:static;width:100%;max-height:none;overflow:visible;background:var(--color-surface, #fff);color:var(--color-text, #1a202c);border:0;border-radius:0;box-shadow:none;padding:0}.test2-election-panel.hidden{display:none}.test2-election-panel__header{display:flex;align-items:flex-start;justify-content:space-between;gap:12px;border-bottom:1px solid var(--color-border, #d8e0ea);padding-bottom:10px;margin-bottom:10px}.test2-election-panel__header h3{margin:0;font-size:15px;line-height:1.2}.test2-election-panel__header p,.test2-election-panel__eyebrow{margin:0;color:var(--color-text-muted, #718096);font-size:12px}.test2-election-panel__header button{min-height:32px;padding:4px 10px}.test2-election-panel__mode{display:grid;gap:4px;margin-bottom:10px;font-size:12px;font-weight:700}.test2-election-turnout__note{margin:0 0 12px;font-size:12px;line-height:1.45;color:var(--test2-muted, #55606b)}.test2-election-panel__mode--inline{display:inline-flex;align-items:center;gap:6px;margin:0;white-space:nowrap}.test2-election-panel__mode--inline select{max-width:150px}.flat-election-entry--loading{opacity:.78;pointer-events:none}.flat-election-entry--active{background:#dbeafe6b;box-shadow:inset 3px 0 0 var(--color-primary, #1a365d)}[data-theme=dark] .flat-election-entry--active{background:#1d2b3d;box-shadow:inset 3px 0 #8fb4ff}[data-theme=dark] .flat-election-entry--active .flat-election-date{color:#f7fafc}[data-theme=dark] .flat-election-entry--active .flat-election-body,[data-theme=dark] .flat-election-entry--active .flat-election-separator{color:#eef6ff}.flat-election-link{font-family:inherit;font-variant-numeric:normal}.flat-election-date{font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,Liberation Mono,monospace;font-variant-numeric:tabular-nums;font-weight:var(--font-semibold, 600);color:var(--color-text, #1a202c)}.flat-election-separator{color:var(--color-text-muted, #718096)}.flat-election-body{font-family:var(--font-sans, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif);font-variant-numeric:normal;font-size:.72rem;font-style:normal;font-weight:700;color:var(--color-text, #1a202c)}.flat-election-entry--loading .election-load-btn{position:relative}.flat-election-entry--loading .election-load-btn:after{content:"";position:absolute;inset:6px;border:2px solid currentColor;border-right-color:transparent;border-radius:999px;animation:test2ElectionSpin .8s linear infinite}.flat-election-entry--loading .election-load-btn>*{opacity:0}.test2-election-loading,.test2-election-loading-badge{color:var(--color-text-muted, #718096);font-size:12px}.test2-election-loading{display:grid;gap:4px}.test2-election-loading-badge{display:inline-flex;align-items:center;min-height:28px;padding:2px 8px;border:1px solid var(--color-border, #d8e0ea);border-radius:999px;background:var(--color-surface-elevated, #f7fafc);font-weight:700}@keyframes test2ElectionSpin{to{transform:rotate(360deg)}}.test2-election-local-mode{display:inline-flex;align-items:center;gap:2px;padding:2px;border:1px solid var(--color-border, #d8e0ea);border-radius:6px;background:var(--color-surface-elevated, #f7fafc)}.test2-election-local-mode button{min-height:28px;padding:3px 8px;border:0;border-radius:4px;background:transparent;color:var(--color-text-muted, #718096);font-size:12px;font-weight:700;cursor:pointer}.test2-election-local-mode button.is-active{background:var(--color-primary, #1a365d);color:#fff}.election-pane__title-link{appearance:none;border:0;background:transparent;color:inherit;font:inherit;font-weight:inherit;padding:0;margin:0;text-align:left;cursor:pointer;text-decoration:none;max-width:100%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.election-pane__title-link:hover,.election-pane__title-link:focus-visible{text-decoration:underline}.test2-election-panel__summary{display:grid;gap:8px;margin-bottom:8px}.test2-election-tabs{display:flex;flex-wrap:wrap;gap:6px;margin-bottom:10px}.test2-election-link{display:inline;padding:0;border:0;background:none;color:var(--color-primary, #1a365d);font:inherit;font-weight:700;text-align:left;text-decoration:underline;text-underline-offset:2px;cursor:pointer}.test2-election-link:hover,.test2-election-link:focus-visible{color:var(--color-primary-dark, #0f2744)}.test2-election-table-wrap{min-height:0;overflow:auto;border:1px solid var(--color-border, #d8e0ea);border-radius:6px;margin-top:8px}.test2-election-table-wrap--constituencies{max-height:220px}.test2-election-table{width:100%;border-collapse:collapse;font-size:12px}.test2-election-table th,.test2-election-table td{padding:5px 7px;border-bottom:1px solid var(--color-border, #d8e0ea);text-align:left;vertical-align:top}.test2-election-table th{position:sticky;top:0;z-index:1;background:var(--color-surface-elevated, #f7fafc);color:var(--color-text-muted, #718096);font-size:11px;text-transform:uppercase}.test2-election-table__elected{background:#2d9c691a;font-weight:700}.test2-election-table__summary{background:var(--color-surface-elevated, #f7fafc)}.test2-election-table__event-row th{background:#fff7ed;color:#9a3412;font-size:10px;text-transform:none}.test2-election-map-display{margin:8px 0 0;font-size:12px}.test2-election-map-display summary{width:max-content;cursor:pointer;color:var(--color-text-muted, #718096);font-weight:700}.test2-election-map-display__controls{display:flex;flex-wrap:wrap;gap:8px;align-items:center;padding-top:6px}.test2-election-map-display .test2-election-panel__mode{display:inline-flex;gap:5px;align-items:center}.test2-election-source-note,.test2-election-coverage-notice,.test2-election-count-toolbar{margin:8px 0}.test2-election-source-note,.test2-election-coverage-notice{padding:8px 10px;border:1px solid var(--color-border, #d8e0ea);border-radius:6px;background:var(--color-surface-elevated, #f7fafc);color:var(--color-text-muted, #718096);font-size:12px}.test2-election-source-note{position:sticky;bottom:0;z-index:2;margin-bottom:0}.test2-election-coverage-notice p{margin:4px 0 0}.test2-election-count-detail{display:grid;gap:2px;margin-top:3px;color:var(--color-text-muted, #718096);font-size:11px;font-weight:400}.test2-election-animation-ready{display:grid;gap:6px;padding:12px;border:1px solid var(--color-border, #d8e0ea);border-radius:6px;background:var(--color-surface-elevated, #f7fafc);font-size:13px}.test2-election-animation-ready p{margin:0}.test2-fptp-results-layout{display:flex;gap:10px;align-items:start;width:max-content;min-width:100%;max-width:none;justify-content:flex-start;overflow:visible}.test2-fptp-results-layout__table{flex:0 0 auto;width:max-content;min-width:max-content;max-width:none;overflow:visible}.test2-fptp-results-layout__table .election-party-wrapper{margin:0}.election-party-wrapper--pane-inline{overflow:visible;max-height:none;width:max-content;min-width:max-content}.test2-fptp-vote-graphic.transfer-animation-preview{display:block;flex:0 0 360px;width:360px;min-width:280px;max-width:min(360px,100%);margin:0;padding:10px 12px 12px;box-sizing:border-box}.test2-fptp-vote-graphic__title{color:#2c3e50;font-size:13px;font-weight:700}.test2-fptp-vote-graphic__animation{position:relative;display:grid;gap:5px;width:100%;min-width:0;padding:8px 0 10px}.test2-fptp-vote-graphic__candidate{position:relative;z-index:1;display:grid;grid-template-columns:92px minmax(0,1fr) 46px;gap:6px;align-items:center;min-height:24px}.test2-fptp-vote-graphic__candidate-label{overflow:hidden;color:#222;font-size:11px;font-weight:700;line-height:1.15;text-overflow:ellipsis;white-space:nowrap}.test2-fptp-vote-graphic__bar{display:flex;align-items:center;width:var(--vote-width, 0%);min-width:0;max-width:100%;min-height:18px;padding:2px 6px;box-sizing:border-box;overflow:visible;background:var(--vote-colour, #6b7280);background:linear-gradient(90deg,color-mix(in srgb,var(--vote-colour, #6b7280) 78%,#ffffff),var(--vote-colour, #6b7280));border:1px solid #111827;border-radius:0 4px 4px 0;color:#fff;font-size:11px;font-weight:700;line-height:1;text-shadow:1px 1px 0 #000,-1px -1px 0 #000,1px -1px 0 #000,-1px 1px 0 #000;white-space:nowrap}.test2-fptp-vote-graphic__candidate--elected .test2-fptp-vote-graphic__bar{outline:2px solid #f1c40f;outline-offset:1px}.test2-fptp-vote-graphic__meta{color:#334155;font-size:11px;font-weight:700;text-align:right;white-space:nowrap}.test2-election-trends{--trend-surface: var(--color-surface, #fff);--trend-text: var(--color-text, #111827);--trend-muted: var(--color-text-muted, #6b7280);--trend-grid: rgba(15, 23, 42, .09);--trend-baseline: rgba(15, 23, 42, .3);--trend-crosshair: rgba(15, 23, 42, .4);--trend-hover: rgba(15, 23, 42, .06);display:grid;gap:6px;padding:10px 12px 6px;border-radius:6px;background:var(--trend-surface);color:var(--trend-text);font-family:var(--font-sans, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif)}.test2-election-trends__header{display:flex;align-items:flex-start;justify-content:space-between;gap:12px 18px;flex-wrap:wrap}.test2-election-trends__header h3{margin:0;color:var(--trend-text);font-size:15px;font-weight:700;line-height:1.25;letter-spacing:-.01em}.test2-election-trends__header p{margin:2px 0 0;color:var(--trend-muted);font-size:12.5px;line-height:1.4}.test2-election-trends__scope{display:inline-flex;align-items:center;gap:6px;color:var(--trend-muted);font-size:12px;font-weight:500;cursor:pointer;white-space:nowrap}.test2-election-trends__scope input{margin:0;accent-color:var(--color-accent, #2563eb)}.test2-election-trends__chart{min-width:0;max-width:100%}.test2-election-trends__loading,.test2-election-trends__chart>.election-no-data{margin:0;padding:18px 0;color:var(--trend-muted);font-size:12.5px}.trend-chart{position:relative;display:grid;gap:4px}.test2-election-trends__legend{display:flex;align-items:center;flex-wrap:wrap;gap:0 6px;margin:0 0 0 -4px;font-size:11.5px;line-height:1.25}.test2-election-trends__legend-item{display:inline-flex;align-items:center;gap:5px;margin:0;padding:2px 4px;border:0;border-radius:4px;background:none;color:var(--trend-text);font:inherit;font-size:11.5px;cursor:pointer;transition:opacity .15s ease,background-color .15s ease}.test2-election-trends__legend-item:hover{background:var(--trend-hover)}.test2-election-trends__legend-item:focus-visible{outline:2px solid var(--color-accent, #2563eb);outline-offset:1px}.test2-election-trends__legend-item[aria-pressed=true]{font-weight:700}.test2-election-trends__legend-swatch{flex:0 0 auto;width:14px;height:3px;border-radius:2px}.trend-chart__stage{position:relative;min-width:0}.test2-election-trends__svg{display:block;width:100%;height:auto;overflow:visible;font-family:inherit;touch-action:pan-y;outline:none;-webkit-user-select:none;user-select:none;-webkit-tap-highlight-color:transparent}.test2-election-trends__svg:focus-visible{outline:2px solid var(--color-accent, #2563eb);outline-offset:4px;border-radius:2px}.trend-grid{stroke:var(--trend-grid);stroke-width:1;shape-rendering:crispEdges}.trend-grid--baseline{stroke:var(--trend-baseline)}.trend-election-tick{stroke:var(--trend-baseline);stroke-width:1;shape-rendering:crispEdges}.trend-axis{fill:var(--trend-muted);font-size:11.5px;font-variant-numeric:tabular-nums}.trend-series{transition:opacity .15s ease}.trend-line{fill:none;stroke:var(--trend-colour, #64748b);stroke-width:2.25;stroke-linecap:round;stroke-linejoin:round;transition:stroke-width .15s ease}.trend-hit{fill:none;stroke:transparent;stroke-width:14;stroke-linecap:round;stroke-linejoin:round;pointer-events:stroke;cursor:pointer}.trend-dot{fill:var(--trend-colour, #64748b)}.trend-gap{fill:none;stroke:var(--trend-colour, #64748b);stroke-width:1.25;stroke-dasharray:2 4;stroke-linecap:round;opacity:.5}.trend-marker{fill:var(--trend-colour, #64748b);stroke:var(--trend-surface);stroke-width:1.5;opacity:0;pointer-events:none;transition:opacity .12s ease}.trend-marker.is-active,.trend-series.is-focused .trend-marker{opacity:1}.trend-series.is-focused .trend-line{stroke-width:3}.trend-chart[data-trend-focus] .trend-series:not(.is-focused){opacity:.16}.trend-chart[data-trend-focus] .trend-label:not(.is-focused){opacity:.28}.trend-chart[data-trend-focus] .test2-election-trends__legend-item:not(.is-focused){opacity:.45}.trend-label{cursor:pointer;transition:opacity .15s ease}.trend-label text{fill:var(--trend-colour, #64748b);font-size:12px;font-variant-numeric:tabular-nums;paint-order:stroke;stroke:var(--trend-surface);stroke-width:3px;stroke-linejoin:round}.trend-label__value{font-weight:600}.trend-label-leader{stroke:var(--trend-colour, #64748b);stroke-width:1;opacity:.55}.trend-crosshair{display:none;stroke:var(--trend-crosshair);stroke-width:1;stroke-dasharray:3 3;pointer-events:none;shape-rendering:crispEdges}.trend-crosshair.is-active{display:block}.trend-tooltip{position:absolute;z-index:5;min-width:150px;max-width:250px;padding:7px 10px 8px;border:1px solid var(--color-border, #d8e0ea);border-radius:6px;background:var(--trend-surface);color:var(--trend-text);box-shadow:0 4px 14px #0f172a24;font-size:12px;line-height:1.35;pointer-events:none}.trend-tooltip__title{font-weight:700}.trend-tooltip__subtitle{color:var(--trend-muted);font-size:11px}.trend-tooltip__table{width:100%;margin-top:4px;border-collapse:collapse}.trend-tooltip__table td{padding:1px 0;white-space:nowrap}.trend-tooltip__table tr.is-focused td{font-weight:700}.trend-tooltip__value{padding-left:14px!important;text-align:right;font-variant-numeric:tabular-nums;font-weight:600}.trend-tooltip__swatch{display:inline-block;width:10px;height:3px;margin:0 6px 3px 0;border-radius:2px;vertical-align:middle}.test2-election-trends__notes{display:grid;gap:2px}.test2-election-trends__note{margin:0;color:var(--trend-muted);font-size:11px;line-height:1.4}@media(max-width:640px){.test2-election-trends{padding:10px 8px 6px}.test2-election-trends__header h3{font-size:14px}.trend-tooltip{max-width:200px}}@media(max-width:1100px){.test2-fptp-results-layout{flex-direction:column;width:100%;min-width:0;overflow-x:visible}.test2-fptp-results-layout__table,.test2-fptp-vote-graphic.transfer-animation-preview{flex-basis:auto;width:100%;max-width:520px}}[data-theme=dark] .test2-source-panel,[data-theme=dark] .test2-election-panel,[data-theme=dark] .test2-election-table-wrap,[data-theme=dark] .test2-election-source-note,[data-theme=dark] .test2-election-coverage-notice,[data-theme=dark] .test2-election-trends,[data-theme=dark] .test2-election-animation-ready,[data-theme=dark] .test2-fptp-vote-graphic.transfer-animation-preview{background:var(--color-surface, #0f1419);border-color:var(--color-border, #3d444d);color:var(--color-text, #f7fafc)}[data-theme=dark] .test2-source-panel__header,[data-theme=dark] .test2-source-panel__group,[data-theme=dark] .test2-election-table th,[data-theme=dark] .test2-election-table__summary,[data-theme=dark] .test2-fptp-vote-graphic__title{background:var(--color-surface-elevated, #1c2128);border-color:var(--color-border, #3d444d);color:var(--color-text, #f7fafc)}[data-theme=dark] .test2-election-trends{--trend-muted: var(--color-text-muted, #a8b3c5);--trend-grid: rgba(255, 255, 255, .1);--trend-baseline: rgba(255, 255, 255, .32);--trend-crosshair: rgba(255, 255, 255, .45);--trend-hover: rgba(255, 255, 255, .08)}[data-theme=dark] .trend-tooltip{box-shadow:0 4px 16px #00000080}[data-theme=dark] .test2-election-table td,[data-theme=dark] .test2-source-panel__record+.test2-source-panel__record{border-color:var(--color-border, #3d444d)}[data-theme=dark] .test2-fptp-vote-graphic__candidate-label,[data-theme=dark] .test2-fptp-vote-graphic__meta{color:var(--color-text, #f7fafc)}[data-theme=dark] .test2-election-table__event-row th{background:#92400e47;color:#fed7aa}@media(prefers-color-scheme:dark){:root:not([data-theme=light]) .flat-election-entry--active{background:#1d2b3d;box-shadow:inset 3px 0 #8fb4ff}:root:not([data-theme=light]) .flat-election-entry--active .flat-election-date{color:#f7fafc}:root:not([data-theme=light]) .flat-election-entry--active .flat-election-body,:root:not([data-theme=light]) .flat-election-entry--active .flat-election-separator{color:#eef6ff}:root:not([data-theme=light]) .test2-source-panel,:root:not([data-theme=light]) .test2-election-panel,:root:not([data-theme=light]) .test2-election-table-wrap,:root:not([data-theme=light]) .test2-election-source-note,:root:not([data-theme=light]) .test2-election-coverage-notice,:root:not([data-theme=light]) .test2-election-trends,:root:not([data-theme=light]) .test2-election-animation-ready,:root:not([data-theme=light]) .test2-fptp-vote-graphic.transfer-animation-preview{background:var(--color-surface, #0f1419);border-color:var(--color-border, #3d444d);color:var(--color-text, #f7fafc)}:root:not([data-theme=light]) .test2-source-panel__header,:root:not([data-theme=light]) .test2-source-panel__group,:root:not([data-theme=light]) .test2-election-table th,:root:not([data-theme=light]) .test2-election-table__summary,:root:not([data-theme=light]) .test2-fptp-vote-graphic__title{background:var(--color-surface-elevated, #1c2128);border-color:var(--color-border, #3d444d);color:var(--color-text, #f7fafc)}:root:not([data-theme=light]) .test2-election-trends{--trend-muted: var(--color-text-muted, #a8b3c5);--trend-grid: rgba(255, 255, 255, .1);--trend-baseline: rgba(255, 255, 255, .32);--trend-crosshair: rgba(255, 255, 255, .45);--trend-hover: rgba(255, 255, 255, .08)}:root:not([data-theme=light]) .trend-tooltip{box-shadow:0 4px 16px #00000080}:root:not([data-theme=light]) .test2-election-table td,:root:not([data-theme=light]) .test2-source-panel__record+.test2-source-panel__record{border-color:var(--color-border, #3d444d)}:root:not([data-theme=light]) .test2-fptp-vote-graphic__candidate-label,:root:not([data-theme=light]) .test2-fptp-vote-graphic__meta{color:var(--color-text, #f7fafc)}:root:not([data-theme=light]) .test2-election-table__event-row th{background:#92400e47;color:#fed7aa}}.test2-party-swatch{display:inline-block;width:10px;height:10px;margin-right:6px;border:1px solid rgba(15,23,42,.25);border-radius:999px;vertical-align:-1px}.test2-election-panel__mode select{width:100%;min-height:34px}.test2-election-panel__legend{display:flex;flex-wrap:wrap;gap:6px 10px;align-items:center;margin-bottom:10px;font-size:12px}.test2-election-panel__legend-item{display:inline-flex;align-items:center;gap:5px}.test2-election-panel__legend-item i{width:12px;height:12px;border-radius:50%;border:1px solid rgba(17,24,39,.2)}.test2-election-panel__legend-ramp{width:84px;height:12px;border-radius:999px;border:1px solid rgba(17,24,39,.16);background:linear-gradient(90deg,#fef3c7,#fde68a,#f59e0b,#d97706,#92400e)}.test2-election-panel__stats{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:8px;margin:0}.test2-election-panel__stats dt{color:var(--color-text-muted, #718096);font-size:11px}.test2-election-panel__stats dd{margin:0;overflow-wrap:anywhere;font-size:12px;font-weight:700}@media(max-width:640px){.test2-source-panel{top:64px;right:10px;left:10px;width:auto;max-height:calc(100% - 82px)}.test2-election-panel{inset:auto 10px 12px;width:auto;max-height:42vh}}.test2-performance-dashboard{border-top:1px solid var(--color-border, #e2e8f0);padding-top:var(--space-3, .75rem)}.test2-performance-dashboard__header{align-items:center;display:flex;gap:var(--space-2, .5rem);justify-content:space-between;margin-bottom:var(--space-2, .5rem)}.test2-performance-dashboard__body{display:grid;gap:4px;font-size:.75rem}.test2-performance-dashboard__row{align-items:start;background:color-mix(in srgb,var(--color-surface, #fff) 92%,var(--color-primary-50, #ebf4ff) 8%);border:1px solid var(--color-border, #e2e8f0);border-left:3px solid var(--color-border, #e2e8f0);border-radius:4px;display:grid;gap:4px;grid-template-columns:minmax(72px,.85fr) minmax(0,1.25fr);padding:5px 6px}.test2-performance-dashboard__row span{color:var(--color-text-muted, #718096)}.test2-performance-dashboard__row strong{color:var(--color-text, #1a202c);font-weight:650;overflow-wrap:anywhere}.test2-performance-dashboard__row--ok{border-left-color:var(--color-success, #38a169)}.test2-performance-dashboard__row--warning{border-left-color:var(--color-warning, #d69e2e)}.test2-performance-dashboard__row--danger{border-left-color:var(--color-error, #e53e3e)}.catalogue-flat__toc-map-buttons{display:flex;flex-wrap:wrap;gap:6px;padding:6px 0 8px}.catalogue-flat__toc-map-btn{display:inline-flex;align-items:center;min-height:28px;padding:4px 10px;border:1px solid var(--color-border, #d6e0eb);border-radius:6px;background:var(--color-surface, #fff);color:var(--color-link, #173b6d);font-size:.74rem;font-weight:700;text-decoration:none}.catalogue-flat__toc-map-btn:hover,.catalogue-flat__toc-map-btn:focus-visible{border-color:var(--color-primary, #1a365d);color:var(--color-primary, #1a365d);outline:none}.catalogue-search{display:grid;gap:10px;padding:12px 14px 20px}.catalogue-flat-view--search{overflow-anchor:none}.catalogue-search__summary{color:var(--color-text-muted, #5b6b85);font-size:.86rem}.catalogue-search__summary span{color:var(--color-text, #1a202c);font-weight:700}.catalogue-search__results{display:grid;gap:8px}.catalogue-search__result{display:grid;grid-template-columns:54px minmax(0,1fr) auto;gap:10px;align-items:center;padding:8px;border:1px solid var(--color-border, #d6e0eb);border-radius:8px;background:var(--color-surface, #fff)}.catalogue-search__thumb{width:48px;height:48px;display:grid;place-items:center;overflow:hidden;border:1px solid var(--color-border, #d6e0eb);border-radius:6px;background:var(--color-surface-muted, #f5f8fb)}.catalogue-search__thumb .thumb-zone,.catalogue-search__thumbnail-img,.catalogue-search__feature-thumb svg{width:48px;height:48px;display:block}.catalogue-search__feature-thumb,.catalogue-search__fallback-thumb,.catalogue-search__colour-tab{width:34px;height:34px;border-radius:5px;display:inline-block}.catalogue-search__fallback-thumb{background:linear-gradient(135deg,#d8e2ef,#f5f8fb)}.catalogue-search__type{color:var(--color-text-muted, #6b7a90);font-size:.68rem;font-weight:800;letter-spacing:.04em;text-transform:uppercase}.catalogue-search__title{margin:1px 0 2px;color:var(--color-text, #0f172a);font-size:.96rem;line-height:1.15}.catalogue-search__meta,.catalogue-search__empty{color:var(--color-text-muted, #5b6b85);font-size:.8rem;line-height:1.25}.catalogue-search__actions{display:flex;flex-wrap:wrap;justify-content:flex-end;gap:6px}.catalogue-search__title-link{display:inline;padding:0;border:0;background:transparent;color:var(--color-primary, #174a7c);cursor:pointer;font:inherit;font-weight:800;text-align:left;text-decoration:underline;text-decoration-thickness:1px;text-underline-offset:2px}.catalogue-search__title-link:hover,.catalogue-search__title-link:focus-visible{color:var(--color-primary-dark, #0f3154);outline:none}.catalogue-search__action-strip{display:flex;flex-wrap:nowrap;justify-content:flex-end;gap:4px}.catalogue-search__icon-btn{width:30px;height:30px;flex:0 0 30px}@media(max-width:640px){.catalogue-search__result{grid-template-columns:46px minmax(0,1fr)}.catalogue-search__actions{grid-column:1 / -1;justify-content:flex-start}}[data-theme=dark] .catalogue-flat__toc-toplink,[data-theme=dark] .catalogue-flat__toc-map-btn,[data-theme=dark] .catalogue-search__title,[data-theme=dark] .catalogue-search__summary span,[data-theme=dark] .flat-election-body,[data-theme=dark] .flat-election-separator{color:#f7fafc}[data-theme=dark] .catalogue-search__title-link{color:#93c5fd}[data-theme=dark] .catalogue-search__title-link:hover,[data-theme=dark] .catalogue-search__title-link:focus-visible{color:#bfdbfe}[data-theme=dark] .catalogue-flat__toc-map-btn,[data-theme=dark] .catalogue-search__result,[data-theme=dark] .catalogue-search__thumb{background:var(--color-surface, #0f1419);border-color:var(--color-border, #3d444d)}[data-theme=dark] .catalogue-search__summary,[data-theme=dark] .catalogue-search__type,[data-theme=dark] .catalogue-search__meta,[data-theme=dark] .catalogue-search__empty{color:var(--color-text-muted, #a8b3c5)}@media(prefers-color-scheme:dark){:root:not([data-theme=light]) .catalogue-flat__toc-toplink,:root:not([data-theme=light]) .catalogue-flat__toc-map-btn,:root:not([data-theme=light]) .catalogue-search__title,:root:not([data-theme=light]) .catalogue-search__summary span,:root:not([data-theme=light]) .flat-election-body,:root:not([data-theme=light]) .flat-election-separator{color:#f7fafc}:root:not([data-theme=light]) .catalogue-search__title-link{color:#93c5fd}:root:not([data-theme=light]) .catalogue-search__title-link:hover,:root:not([data-theme=light]) .catalogue-search__title-link:focus-visible{color:#bfdbfe}:root:not([data-theme=light]) .catalogue-flat__toc-map-btn,:root:not([data-theme=light]) .catalogue-search__result,:root:not([data-theme=light]) .catalogue-search__thumb{background:var(--color-surface, #0f1419);border-color:var(--color-border, #3d444d)}:root:not([data-theme=light]) .catalogue-search__summary,:root:not([data-theme=light]) .catalogue-search__type,:root:not([data-theme=light]) .catalogue-search__meta,:root:not([data-theme=light]) .catalogue-search__empty{color:var(--color-text-muted, #a8b3c5)}}.election-pane__content{--table-surface: var(--color-surface, #fff);--table-text: var(--color-text, #111827);--table-muted: var(--color-text-muted, #6b7280);--table-rule: rgba(15, 23, 42, .1);--table-header-rule: rgba(15, 23, 42, .35);--table-hover: rgba(15, 23, 42, .045);--table-pos: #1f7a46;--table-neg: #b83a2c;--table-link: var(--color-primary, #1a4b8c);--table-link-rule: rgba(26, 75, 140, .35)}.election-pane__content .election-party-wrapper,.election-pane__content .election-count-wrapper{border:0;border-radius:0;background:var(--table-surface)}.election-pane__content .election-party-table,.election-pane__content .election-count-table{background:var(--table-surface);color:var(--table-text);font-family:var(--font-sans, "Inter", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif);font-size:.76rem;line-height:1.3}.election-pane__content .election-party-table th,.election-pane__content .election-party-table td,.election-pane__content .election-count-table th,.election-pane__content .election-count-table td{border:0;border-bottom:1px solid var(--table-rule);padding:6px 8px;background:var(--table-surface);color:var(--table-text)}.election-pane__content .election-party-table th,.election-pane__content .election-count-table th,.election-pane__content .election-party-table th:first-child,.election-pane__content .election-count-table th:first-child,.election-pane__content .election-party-table--grouped thead tr:nth-child(1) th,.election-pane__content .election-count-table--grouped thead tr:nth-child(1) th,.election-pane__content .election-party-table--grouped thead tr:nth-child(2) th,.election-pane__content .election-count-table--grouped thead tr:nth-child(2) th,.election-pane__content .election-party-table--grouped thead tr:nth-child(3) th,.election-pane__content .election-count-table--grouped thead tr:nth-child(3) th{background:var(--table-surface);color:var(--table-text);font-weight:700;border-bottom:0;box-shadow:0 1px 0 var(--table-rule)}.election-pane__content .election-party-table--grouped thead tr:nth-child(1) th:not([rowspan]),.election-pane__content .election-count-table--grouped thead tr:nth-child(1) th:not([rowspan]),.election-pane__content .election-count-table--grouped thead tr:nth-child(2) th:not([rowspan]){color:var(--table-muted);font-weight:600;font-size:.72rem;letter-spacing:.02em;text-transform:uppercase}.election-pane__content .election-party-table thead tr:last-child th,.election-pane__content .election-count-table thead tr:last-child th,.election-pane__content .election-party-table thead th[rowspan],.election-pane__content .election-count-table thead th[rowspan]{box-shadow:0 1.5px 0 var(--table-header-rule)}.election-pane__content .election-th-indicator{color:var(--color-accent, #2563eb)}.election-pane__content .election-party-table tbody td:not(.election-colour-col),.election-pane__content .election-count-table tbody td:not(.election-colour-col){background:var(--table-surface)!important;border:0!important;box-shadow:inset 0 -1px 0 var(--table-rule)!important;color:var(--table-text)}.election-pane__content .election-party-table thead th,.election-pane__content .election-count-table thead th{border:0!important;box-shadow:inset 0 -1px 0 var(--table-rule)!important}.election-pane__content .election-party-table thead tr:last-child th,.election-pane__content .election-count-table thead tr:last-child th,.election-pane__content .election-party-table thead th[rowspan],.election-pane__content .election-count-table thead th[rowspan]{box-shadow:inset 0 -1.5px 0 var(--table-header-rule)!important}.election-pane__content .election-party-table tbody tr:hover td:not(.election-colour-col),.election-pane__content .election-count-table tbody tr:hover td:not(.election-colour-col){background:var(--table-hover)!important}.election-pane__content .election-table-summary-row td:not(.election-colour-col){color:var(--table-text);font-style:normal;font-weight:600;box-shadow:inset 0 1.5px 0 var(--table-header-rule),inset 0 -1px 0 var(--table-rule)!important}.election-pane__content .election-party-table tbody td:has(.election-entity-link),.election-pane__content .election-count-table tbody td:has(.election-entity-link),.election-pane__content td.election-party-cell{text-align:left}.election-pane__content .election-entity-link{color:var(--table-text);text-decoration:underline;text-decoration-color:var(--table-link-rule);text-decoration-thickness:1px;text-underline-offset:2px}.election-pane__content .election-count-table .election-entity-link:not([data-election-entity-kind=candidate]),.election-pane__content .election-results-table--district .election-entity-link[data-election-entity-kind=party]{text-decoration-color:transparent}.election-pane__content .election-entity-link:hover,.election-pane__content .election-entity-link:focus-visible{color:var(--table-link);text-decoration-color:currentColor}.election-pane__content .election-party-table .election-rank-col,.election-pane__content .election-count-table .election-rank-col{color:var(--table-muted);font-variant-numeric:tabular-nums}.election-pane__content td.election-party-cell:before{width:3px;top:5px;bottom:5px;border-radius:2px}.election-pane__content .election-delta,.election-pane__content .count-transfer--pos,.election-pane__content .count-transfer--neg,.election-pane__content .election-delta--neutral,.election-pane__content .election-na{color:var(--table-muted)}.election-pane__content .election-delta--share.election-delta--pos{color:var(--table-pos)}.election-pane__content .election-delta--share.election-delta--neg{color:var(--table-neg)}.election-pane__content .election-na em{font-style:normal}.election-pane__content .election-elected-mark{display:inline-block;width:8px;height:8px;border-radius:50%;overflow:hidden;color:transparent;font-size:0;line-height:0;vertical-align:middle}.election-pane__content .election-elected-mark--yes{background:var(--table-text)}.election-pane__content .election-elected-mark--no{background:transparent;box-shadow:inset 0 0 0 1px var(--table-rule)}[data-theme=dark] .election-pane__content{--table-link: #8fb4ff;--table-link-rule: rgba(143, 180, 255, .4);--table-muted: var(--color-text-muted, #a8b3c5);--table-rule: rgba(255, 255, 255, .1);--table-header-rule: rgba(255, 255, 255, .38);--table-hover: rgba(255, 255, 255, .06);--table-pos: #4ade80;--table-neg: #f87171}@media(prefers-color-scheme:dark){:root:not([data-theme=light]) .election-pane__content{--table-link: #8fb4ff;--table-link-rule: rgba(143, 180, 255, .4);--table-muted: var(--color-text-muted, #a8b3c5);--table-rule: rgba(255, 255, 255, .1);--table-header-rule: rgba(255, 255, 255, .38);--table-hover: rgba(255, 255, 255, .06);--table-pos: #4ade80;--table-neg: #f87171}} diff --git a/app/build/app.bundle.js b/app/build/app.bundle.js index 5f57c288e5..9675ea558a 100644 --- a/app/build/app.bundle.js +++ b/app/build/app.bundle.js @@ -1 +1 @@ -import{d as a}from"./chunks/chunk-2YPEAJVR.js";a();var r=()=>{window.__civgraphTest2BootStarted||(window.__civgraphTest2BootStarted=!0,window.__civgraphTest2RuntimeImportStartedAt=performance?.now?.()||Date.now(),import("./chunks/app-5QB5UQHT.js").catch(e=>{console.error("[Test2] Failed to load runtime",e),(document.getElementById("map")||document.body).insertAdjacentHTML("beforeend",`
Failed to load Civgraph runtime: ${l(e?.message||e)}
`)}))},o=()=>{requestAnimationFrame(()=>{requestAnimationFrame(r)})};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",o,{once:!0}):o();function l(e){return String(e??"").replace(/[&<>"']/g,t=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[t])} +import{d as a}from"./chunks/chunk-57HMLXXU.js";a();var r=()=>{window.__civgraphTest2BootStarted||(window.__civgraphTest2BootStarted=!0,window.__civgraphTest2RuntimeImportStartedAt=performance?.now?.()||Date.now(),import("./chunks/app-RDZI4COH.js").catch(e=>{console.error("[Test2] Failed to load runtime",e),(document.getElementById("map")||document.body).insertAdjacentHTML("beforeend",`
Failed to load Civgraph runtime: ${l(e?.message||e)}
`)}))},o=()=>{requestAnimationFrame(()=>{requestAnimationFrame(r)})};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",o,{once:!0}):o();function l(e){return String(e??"").replace(/[&<>"']/g,t=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[t])} diff --git a/app/build/chunks/app-5QB5UQHT.js b/app/build/chunks/app-RDZI4COH.js similarity index 81% rename from app/build/chunks/app-5QB5UQHT.js rename to app/build/chunks/app-RDZI4COH.js index 9a866902c5..d7a0f68c45 100644 --- a/app/build/chunks/app-5QB5UQHT.js +++ b/app/build/chunks/app-RDZI4COH.js @@ -1,10 +1,10 @@ -import{a as At,b as ut,c as ze,d as fa,e as ga}from"./chunk-V4IEUOVV.js";import{b as dt,c as ma,d as W}from"./chunk-2YPEAJVR.js";W();W();W();function oe(c){if(!c)return[];let e=(c.variants||[]).map(t=>typeof t=="string"?t:t?.id).filter(Boolean);return e.length?e:Array.isArray(c.members)&&c.members.length?c.members.filter(Boolean):Array.isArray(c.compositeSources)&&c.compositeSources.length?c.compositeSources.filter(Boolean):[]}var $t=class{constructor(){this.maps=null,this.books=null,this.geographies=null,this.baseUrl="",this.fuse=null,this.mapClassIndex=new Map}async loadCatalogue(){try{let e=await fetch("/_api/catalogue",{headers:{Accept:"application/json"}});if(!e.ok)throw new Error(`HTTP ${e.status}`);let t=await e.json();if(!Array.isArray(t?.maps)||!t.maps.length)throw new Error("empty catalogue");return t}catch(e){return console.warn("[DataService] /_api/catalogue unavailable, falling back to the static catalogue",e),this.loadJson("data/database/maps.json")}}async init(e={}){let{loadBooks:t=!0,loadGeographies:a=!0}=e||{},[i,s,n,r]=await Promise.all([this.loadCatalogue(),this.loadJson("data/database/data-entries.json"),t?this.loadJson("data/database/books.json"):Promise.resolve(null),a?this.loadJson("data/database/geographies.json"):Promise.resolve(null)]);return this.maps=i,s?.dataEntries&&(this.maps.dataEntries=s.dataEntries),this.books=n||this.books||{categories:[],books:[]},this.geographies=r||this.geographies||{geographyTypes:[],hierarchies:{}},this.buildMapClassIndex(),this.initFuseSearch(),console.log(`[DataService] Loaded ${this.maps.maps.length} maps, ${this.books.books.length} books`),this}async ensureBooksLoaded(){return this.books?.books?.length?this.books:(this.books=await this.loadJson("data/database/books.json"),this.books)}async ensureGeographiesLoaded(){return this.geographies?.geographyTypes?.length||Object.keys(this.geographies?.hierarchies||{}).length?this.geographies:(this.geographies=await this.loadJson("data/database/geographies.json"),this.geographies)}initFuseSearch(){typeof Fuse<"u"&&this.maps?.maps&&(this.fuse=new Fuse(this.getAllMaps(),{keys:[{name:"name",weight:2},{name:"keywords",weight:1.5},{name:"provider",weight:1},{name:"category",weight:.5}],threshold:.4,includeScore:!0,ignoreLocation:!0}),console.log("[DataService] Fuse.js search initialized"))}async loadJson(e){let t=await fetch(this.baseUrl+e,{cache:"no-cache"});if(!t.ok)throw new Error(`Failed to load ${e}: ${t.status}`);return t.json()}getAllMaps(){return(this.maps?.maps||[]).filter(t=>!t.hidden)}getMapById(e){let t=this.maps?.maps||[],a=t.find(n=>n.id===e);if(a)return a;let s=(this.maps?.dataEntries||[]).find(n=>n.id===e);if(s)return{...s,isDataEntry:!0};for(let n of t){if(n.variants){let r=n.variants.find(o=>o.id===e);if(r)return{...n,...r,parentId:n.id,style:r.style||n.style,labelProperty:r.labelProperty||n.labelProperty,priorityProperty:r.priorityProperty||n.priorityProperty,name:r.label||r.id,variants:void 0,members:void 0,isGroup:!1}}if(oe(n).includes(e)){let r=t.find(o=>o.id===e);if(r)return r}}}buildMapClassIndex(){this.mapClassIndex=new Map;let e=this.maps?.maps||[],t=this.maps?.classes||[];for(let a of t)for(let i of a.maps||[])this.mapClassIndex.has(i)||this.mapClassIndex.set(i,{classId:a.id,className:a.name,scope:a.scope||null});for(let a of e)for(let i of a.variants||[])i?.id&&!this.mapClassIndex.has(i.id)&&this.mapClassIndex.set(i.id,{classId:a.id,className:a.name||a.title||a.id,scope:a.scope||null,parentId:a.id})}getMapClassInfo(e){return e&&this.mapClassIndex?.get(e)||null}getMapDisplayTitle(e){let t=typeof e=="string"?this.getMapById(e):e;if(!t)return typeof e=="string"?e:"";let a=String(t.name||t.title||t.label||t.id||"").trim();if(!a)return"";let i=this.getMapClassInfo(t.id)||(t.parentId?this.getMapClassInfo(t.parentId):null),s=String(i?.className||t.parentName||"").trim(),n=this.getDerivedMapNamePart(t,a,s);return!s||!n?a:`${s} - ${n}`}getDerivedMapNamePart(e,t=e?.name||e?.title||"",a=""){let i=String(t||"").trim();if(!i)return"";let s=String(a||"").trim();if(s){let n=this.escapeRegExp(s).replace(/\\ /g,"\\s+"),r=i.match(new RegExp(`^${n}\\s+(.+)$`,"i"));if(r&&this.isDerivedMapName(e,r[1]))return r[1].trim()}return this.isDerivedMapName(e,i)?i:""}isDerivedMapName(e,t=e?.name||e?.title||""){let a=String(t||"").trim();if(!a)return!1;if(/^\d{4}$/.test(a)||/^\d{1,2}\s+[A-Za-z]{3,9}\s+\d{4}(?:\s*\([^)]*\))?$/.test(a)||/^[A-Za-z]{3,9}\s+\d{4}$/.test(a))return!0;let i=this.formatPlainMapDate(e?.date),s=this.getPlainMapYear(e?.date),n=this.normaliseDisplayText(a);for(let r of[i,s]){let o=this.normaliseDisplayText(r);if(o&&(n===o||n.startsWith(`${o} (`)))return!0}return!1}escapeRegExp(e){return String(e||"").replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}formatPlainMapDate(e){if(!e)return"";let t=String(e),a=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],i=["January","February","March","April","May","June","July","August","September","October","November","December"];if(/^\d{4}$/.test(t))return t;if(/^\d{4}-\d{2}$/.test(t)){let[s,n]=t.split("-").map(Number);return`${a[n-1]} ${s}`}if(/^\d{4}-\d{2}-\d{2}$/.test(t)){let[s,n,r]=t.split("-").map(Number);return`${String(r).padStart(2,"0")} ${i[n-1]} ${s}`}return t}getPlainMapYear(e){let t=String(e||"").match(/^(\d{4})/);return t?t[1]:""}normaliseDisplayText(e){return String(e||"").replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim().toLowerCase()}getMapsByCategory(e){if(e==="all")return this.getAllMaps();let t=this.maps?.categories||[];if(["communities","history","elections-and-government","public-services","physical-geography","built-environment"].includes(e)){let i=e.split("-").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" "),s=t.filter(n=>n.group===i).map(n=>n.id);return this.getAllMaps().filter(n=>s.includes(n.category))}return this.getAllMaps().filter(i=>i.category===e)}searchMaps(e){if(!e||!e.trim())return this.getAllMaps();if(this.fuse)return this.fuse.search(e.trim()).map(i=>i.item);let t=e.toLowerCase().trim().split(/\s+/);return this.getAllMaps().filter(a=>{let i=[a.name,a.category,...a.keywords||[],...a.provider||[]].join(" ").toLowerCase();return t.every(s=>i.includes(s))})}getMapCategories(){return(this.maps?.categories||[]).filter(t=>!t.hidden)}getClasses(){return(this.maps?.classes||[]).filter(t=>!t.hidden)}getAllClasses(){return this.maps?.classes||[]}getC1s(){return this.maps?.c1s||[]}getData(){return this.maps?{categories:this.getMapCategories(),classes:this.getClasses(),maps:this.getAllMaps(),books:this.getAllBooks()}:null}getDefaultMaps(){return this.getAllMaps().filter(e=>e.defaultOn)}getMapFilePath(e){if(!e)return null;if(e.cloneOf){let t=this.getMapById(e.cloneOf);if(t?.files)return t.files.fgb||t.files.geojson||Object.values(t.files)[0]}return e.files?e.files.fgb||e.files.geojson||Object.values(e.files)[0]:null}getMapFormats(e){return e?.files?Object.entries(e.files).filter(([t,a])=>a).map(([t,a])=>({format:t,path:a})):[]}getAllBooks(){return this.books?.books||[]}getBookById(e){return this.getAllBooks().find(t=>t.id===e)}getBooksByCategory(e){return e==="all"?this.getAllBooks():this.getAllBooks().filter(t=>t.category===e)}searchBooks(e){if(!e||!e.trim())return this.getAllBooks();let t=e.toLowerCase().trim().split(/\s+/);return this.getAllBooks().filter(a=>{let i=[a.title,...a.authors||[],...a.keywords||[]].join(" ").toLowerCase();return t.every(s=>i.includes(s))})}getBookCategories(){return this.books?.categories||[]}getBooksForMap(e){return this.getAllBooks().filter(t=>t.relatedMaps&&t.relatedMaps.includes(e))}getGeographyTypes(){return this.geographies?.geographyTypes||[]}getHierarchies(){return this.geographies?.hierarchies||{}}getTimeSeriesChains(){return this.maps?.timeSeriesChains||[]}getChainForClass(e){let t=this.getTimeSeriesChains();for(let a of t){if(a.classIds?.includes(e))return a;if(a.segments){for(let i of a.segments)if(i.classIds?.includes(e))return a}if(a.columns){for(let i of a.columns)if(i.classIds?.includes(e))return a}if(a.predecessor?.classIds?.includes(e))return a}return null}getChainForMap(e){if(!this.getMapById(e))return null;let a=this.getAllClasses();for(let i of a)if(i.maps?.includes(e))return this.getChainForClass(i.id);return null}getAllClassIdsInChain(e){let t=new Set;return e.classIds&&e.classIds.forEach(a=>t.add(a)),e.segments&&e.segments.forEach(a=>{a.classIds?.forEach(i=>t.add(i))}),e.columns&&e.columns.forEach(a=>{a.classIds?.forEach(i=>t.add(i))}),e.predecessor?.classIds&&e.predecessor.classIds.forEach(a=>t.add(a)),[...t]}parseMapDate(e){if(!e)return null;if(/^\d{4}$/.test(e))return new Date(`${e}-01-01`).getTime();if(/^\d{4}-\d{2}-\d{2}$/.test(e))return new Date(e).getTime();let t=Date.parse(e);return isNaN(t)?null:t}getMapsInChain(e){let t=this.getAllClassIdsInChain(e),a=this.getAllClasses(),i=[];for(let s of t){let n=a.find(r=>r.id===s);if(n?.maps)for(let r of n.maps){let o=this.getMapById(r);o&&i.push({map:o,classId:s,timestamp:this.parseMapDate(o.date)})}}return i.sort((s,n)=>(n.timestamp||0)-(s.timestamp||0))}getApplicableDates(e){let t=new Set;for(let a of e)this.getMapsInChain(a).forEach(s=>{s.timestamp&&t.add(s.timestamp)});return[...t].sort((a,i)=>i-a)}getEquivalentMapsForDate(e,t){let a={};console.log("[DataService] getEquivalentMapsForDate - activeMapIds:",e,"targetTimestamp:",t);for(let i of e){let s=this.getChainForMap(i);if(console.log("[DataService] Map:",i,"chain:",s?.id||"none"),!s){a[i]=i;continue}let n=this.getMapsInChain(s);console.log("[DataService] mapsInChain:",n.map(o=>({id:o.map.id,timestamp:o.timestamp})));let r=null;for(let{map:o,timestamp:l}of n)l&&l<=t&&(!r||l>r.timestamp)&&(r={map:o,timestamp:l});console.log("[DataService] bestMatch for",i,":",r?r.map.id:"null"),a[i]=r?r.map.id:null}return a}};function ht(c){return c&&[c.downloads?.fgb,typeof c.files=="object"&&c.files?c.files.fgb:null,c.sourceFile].find(t=>typeof t=="string"&&/^https?:\/\//i.test(t))||null}var Ki=new $t,P=Ki;W();var Zi="boundaries-feature-cache";var Ve="features";function Yi(){return new Promise((c,e)=>{if(typeof indexedDB>"u"){c(null);return}let t=indexedDB.open(Zi,1);t.onupgradeneeded=()=>{let a=t.result;a.objectStoreNames.contains(Ve)||a.createObjectStore(Ve)},t.onsuccess=()=>c(t.result),t.onerror=()=>c(null)})}function Xi(c,e){return new Promise(t=>{try{let i=c.transaction(Ve,"readonly").objectStore(Ve).get(e);i.onsuccess=()=>t(i.result??null),i.onerror=()=>t(null)}catch{t(null)}})}function Ji(c,e,t){try{c.transaction(Ve,"readwrite").objectStore(Ve).put(t,e)}catch{}}var Pt=class{constructor(){this.spatialIndex=null,this.spatialIndexByMap=new Map,this.loadedFeatures=new Map,this.pendingLoads=new Map,this.initialized=!1,this._initPromise=null,this._chunkManifest=null,this._chunkPromises=new Map,this._idb=null,this._idbReady=null,this.useChunkedIndex=typeof window>"u"||new URLSearchParams(window.location?.search).get("chunkedIndex")!=="0",this._idbReady=Yi().then(e=>{this._idb=e})}async ensureInitialized(){if(!this.initialized)return this._initPromise?this._initPromise:(this._initPromise=this.useChunkedIndex?this._initFromManifest():this._initMonolithic(),this._initPromise)}async _initMonolithic(){if(this.initialized)return;let t=new URLSearchParams(window.location.search).get("v")||Date.now();try{let a=await fetch(`data/database/spatial-index.json?v=${t}`);if(!a.ok){console.warn("[FeatureLoader] Spatial index not found");return}let i=await a.json();this.spatialIndex=i.features||[];for(let s of this.spatialIndex)this.spatialIndexByMap.has(s.mapId)||this.spatialIndexByMap.set(s.mapId,[]),this.spatialIndexByMap.get(s.mapId).push(s);this.initialized=!0,console.log(`[FeatureLoader] Loaded spatial index: ${this.spatialIndex.length} features across ${this.spatialIndexByMap.size} maps`)}catch(a){console.warn("[FeatureLoader] Failed to load spatial index:",a)}}async _initFromManifest(){if(this.initialized)return;let e=await this._loadChunkManifest();if(!e)return console.warn("[FeatureLoader] Chunk manifest not found, falling back to monolithic"),this._initMonolithic();this.initialized=!0,console.log(`[FeatureLoader] Chunked mode: manifest loaded (${e.maps.length} maps)`)}async _ensureFullIndex(){if(!(this.spatialIndex&&this.spatialIndex.length>0))try{let e=await fetch("data/database/spatial-index/_names.json");if(e.ok){this.spatialIndex=await e.json(),console.log(`[FeatureLoader] Loaded names index for search: ${this.spatialIndex.length} features`);return}if(e=await fetch("data/database/spatial-index.json"),!e.ok)return;let t=await e.json();this.spatialIndex=t.features||[],console.log(`[FeatureLoader] Loaded full index for search: ${this.spatialIndex.length} features`)}catch(e){console.warn("[FeatureLoader] Failed to load search index:",e),this.spatialIndex||(this.spatialIndex=[])}}async searchViaAPI(e,t=20){try{let a=await fetch(`/_api/search?q=${encodeURIComponent(e)}&limit=${t}`);return a.ok&&(await a.json()).results||null}catch{return null}}async _loadChunkManifest(){if(this._chunkManifest)return this._chunkManifest;try{let e=await fetch("data/database/spatial-index/_manifest.json");return e.ok?(this._chunkManifest=await e.json(),this._chunkManifest):null}catch{return null}}async loadMapIndex(e){if(this.spatialIndexByMap.has(e))return this.spatialIndexByMap.get(e);if(this._chunkPromises.has(e))return this._chunkPromises.get(e);let t=(async()=>{try{let a;try{let i=await fetch(`/_api/spatial?mapId=${encodeURIComponent(e)}`);i.ok&&(a=(await i.json()).features||[])}catch{}if(!a){let i=await fetch(`data/database/spatial-index/${e}.json`);if(!i.ok)return[];a=await i.json()}return this.spatialIndexByMap.set(e,a),this.spatialIndex&&this.spatialIndex.push(...a),a}catch{return[]}finally{this._chunkPromises.delete(e)}})();return this._chunkPromises.set(e,t),t}supportsLOD(e){this._supportsLODCache||(this._supportsLODCache=new Map);let t=this._supportsLODCache.get(e);if(t!==void 0)return t;if(!this.initialized&&!this.spatialIndexByMap.has(e))return!1;let a=this.spatialIndexByMap.get(e),i=!!(a&&a.length>=50&&a[0]?.id!=null);return a&&this._supportsLODCache.set(e,i),i}getFeatureCount(e){return this.spatialIndexByMap.get(e)?.length||0}getLODForZoom(e){return e>=12?2:e>=8?1:0}getBufferedBounds(e){let t=e.getNorth()-e.getSouth(),a=e.getEast()-e.getWest();return L.latLngBounds([e.getSouth()-t*.2,e.getWest()-a*.2],[e.getNorth()+t*.2,e.getEast()+a*.2])}getFeaturesInBounds(e,t){let a=this.spatialIndexByMap.get(e);if(!a)return[];let i=this.getBufferedBounds(t),s=i.getWest(),n=i.getEast(),r=i.getSouth(),o=i.getNorth();return a.filter(l=>{let[d,h,u,p]=l.bbox;return!(un||po)})}parseFeatureId(e){let t=e.split(":");return parseInt(t[1],10)}async loadFeature(e,t,a){let i=`data/features/${e}/${t}-lod-${a}.json`,s=`${e}:${t}:${a}`;if(this.loadedFeatures.has(s))return this.loadedFeatures.get(s);if(this.pendingLoads.has(i))return this.pendingLoads.get(i);let n=(async()=>{if(await this._idbReady,this._idb){let r=await Xi(this._idb,s);if(r)return this.loadedFeatures.set(s,r),this.pendingLoads.delete(i),r}try{let r=await fetch(i);if(!r.ok)throw new Error(`HTTP ${r.status}`);let o=await r.json();return this.loadedFeatures.set(s,o),this._idb&&Ji(this._idb,s,o),o}catch(r){return console.warn(`[FeatureLoader] Failed to load ${i}:`,r.message),null}finally{this.pendingLoads.delete(i)}})();return this.pendingLoads.set(i,n),n}async loadFeatures(e,t,a){let i=[];for(let s=0;sthis.loadFeature(e,o,a)));i.push(...r.filter(o=>o!==null))}return i}getFeaturesToLoad(e,t,a){let i=[];for(let s of t){let n=this.parseFeatureId(s),r=!1;for(let o=a;o<=2;o++)if(this.loadedFeatures.has(`${e}:${n}:${o}`)){r=!0;break}r||i.push(n)}return i}async searchFeaturesByName(e,t=20){if(!this.initialized||!e||e.length<2)return[];let a=await this.searchViaAPI(e,t);if(a)return a;if(this.useChunkedIndex&&(!this.spatialIndex||this.spatialIndex.length===0))return this._ensureFullIndex(),[];let i=e.toLowerCase(),s=[];for(let n of this.spatialIndex||[])if(n.name&&n.name.toLowerCase().includes(i)&&(s.push(n),s.length>=t))break;return s}clearMap(e){for(let t of this.loadedFeatures.keys())t.startsWith(e+":")&&this.loadedFeatures.delete(t)}},Qi=new Pt,ye=Qi;W();W();var Bt="civgraph.",ya="ni-boundaries.",ba=c=>{try{return window.localStorage?.getItem(c)??null}catch{return null}},va=(c,e)=>{try{window.localStorage?.setItem(c,e)}catch{}},es=c=>{try{window.localStorage?.removeItem(c)}catch{}};function De(c,e=null){let t=ba(Bt+c);if(t!==null)return t;let a=ba(ya+c);return a===null?e:(va(Bt+c,a),es(ya+c),a)}function Ye(c,e){va(Bt+c,String(e))}W();function be(c){try{let e=String(c||"").match(/^(\d{4}-\d{2}-\d{2})/);return e?new Date(e[1]+"T00:00:00").toLocaleDateString("en-GB",{day:"2-digit",month:"short",year:"numeric"}):c}catch{return c}}function _a(c){return{"European Parliament":"European","European Parliament (Ireland)":"European (Republic of Ireland)","House of Commons of the United Kingdom":"Westminster","Northern Ireland Assembly":"Assembly","Northern Ireland Constitutional Convention":"Convention","Northern Ireland Forum for Political Dialogue":"Forum","D\xE1il \xC9ireann":"D\xE1il","President of Ireland":"President","Referendum (Ireland)":"Referendum"}[c]||c}function Xe(c){let e=document.createElement("div");return e.textContent=String(c??""),e.innerHTML}function Ft(c,e,t,a,i="",s="dea"){let n=Xe(a||""),r=String(t||"").trim();return!r||r==="-"||r==="\u2014"?`${n||"-"}`:``}W();var ts="https://data.civgraph.net";function wa(c){if(typeof c!="string"||!c)return"";let e=c.replace(/^\/+/,"");return typeof window<"u"&&window.location?.hostname==="localhost"?`/_r/${e}`:`${ts}/${e}`}var Dt=class{constructor(){ma(this,"_expandedVariants",new Set);this.splitStates=[{id:"info-full",label:"Info only",mobileLabel:"Info"},{id:"info-75",label:"Info focus"},{id:"balanced",label:"Split 50/50"},{id:"map-75",label:"Map focus"},{id:"map-full",label:"Map only",mobileLabel:"Map"}],this.currentStateId="balanced",this.storageKey="split-preference.v2",this.isMobile=!1,this.focusedCardIndex=-1,this._savedSliderValues=new Map,this.showAllMaps=!1,this.onSplitChange=null,this.onMapLoad=null,this.onMapUnload=null,this.onMapToggle=null,this.onCheckMapLoaded=null,this.onCheckMapVisible=null,this.onLoadSingleFeature=null,this.onHideMap=null,this.onVisibilityToggle=null,this.onCategoryChange=null,this.onProviderCategoryChange=null,this.onExpandToFullMap=null,this.onPartialFeatureToggle=null,this.onPartialFeatureUnload=null,this.onCheckFeatureLoaded=null,this.onCheckFeatureVisible=null,this.onFeatureLoad=null,this.onSearch=null,this.onMapDetailClick=null,this.onOpenElectionEntityDetail=null,this.onElectionEntityElectionOpen=null,this.onOpenElectionConstituencyFeature=null,this.onBuildElectionCatalogueCards=null,this.onLoadElection=null,this.onUnloadElection=null,this.onCheckElectionLoaded=null,this.onSetupElectionTableControls=null,this._searchAddressAbortController=null,this.catalogueHistory=[],this.catalogueHistoryIndex=-1,this.catalogueView="list",this._lastMapListOptions={},this._showPlaceholdersCards=new Set,this._showByElectionCards=new Set,this._cataloguePane=null,this._electionEntityDetailCache=new Map,this._catalogueBookView=null,this._bookMarkdownCache=new Map,this._flatRenderToken=null,this._flatRenderScheduled=!1,this._pendingFlatRenderOptions=null,this._flatRenderResolvers=[],this._flatTocTargetIds=new Set,this.singleSectionFlatCatalogue=!1,this._flatActiveSectionKey=null,this._flatTargetToSection=new Map,this._flatSectionTargets=new Map,this._thumbnailIds=null,this._thumbnailManifestPromise=null,this._featureCountManifest=null,this._featureCountManifestPromise=null,this._featureThumbnailManifest=null,this._featureThumbnailManifestPromise=null,this._featureThumbnailRenderedIdsByMap=new Map,this._catalogueSearchIndex=null,this._catalogueSearchIndexPromise=null,this._catalogueSearchBrowseCache=new Map,this._catalogueSearchQuery="",this._catalogueSearchToken=0,this._thumbnailObserver=null,this._mobileCatalogueExpanded=!1,this._mobileCatalogueDeferred=!1,this._mobileInitialMapCardLimit=24,this._mobileInitialElectionCardLimit=2}init(){return this.mediaQuery=window.matchMedia("(max-width: 768px)"),this.isMobile=this.mediaQuery.matches,this.mediaQuery.addEventListener("change",e=>{if(this.isMobile=e.matches,e.matches)try{let t=JSON.parse(De(this.storageKey)||"{}");t.mobile&&this.getAllowedStates().some(a=>a.id===t.mobile)?this.currentStateId=t.mobile:this.currentStateId="map-full"}catch{this.currentStateId="map-full"}else try{let t=JSON.parse(De(this.storageKey)||"{}");t.desktop&&this.getAllowedStates().some(a=>a.id===t.desktop)?this.currentStateId=t.desktop:this.currentStateId="balanced"}catch{this.currentStateId="balanced"}this.updateSplitState(),setTimeout(()=>{window.mapController?.map&&window.mapController.map.invalidateSize()},350)}),this.loadPreference(),this.setupSplitToggle(),this.setupTabSwitching(),this.setupCatalogueReturnTop(),this.setupCatalogueNav(),this.setupCatalogueViewToggle(),this.setupMobileMenu(),this.ensureThumbnailManifest().catch(()=>{}),this.ensureFeatureCountManifest().catch(()=>{}),this}setupMobileMenu(){let e=document.getElementById("mobileMenuBtn"),t=document.getElementById("mobileMenu");if(!e||!t)return;e.addEventListener("click",s=>{s.stopPropagation(),!t.classList.contains("hidden")?(t.classList.add("hidden"),e.setAttribute("aria-expanded","false")):(t.classList.remove("hidden"),e.setAttribute("aria-expanded","true"))}),document.addEventListener("click",s=>{!t.classList.contains("hidden")&&!t.contains(s.target)&&!e.contains(s.target)&&(t.classList.add("hidden"),e.setAttribute("aria-expanded","false"))});let a=document.getElementById("mobileSupportBtn"),i=document.getElementById("supportBtn");a&&i&&a.addEventListener("click",s=>{s.preventDefault(),i.click()})}setupCatalogueNav(){let e=document.getElementById("catalogueBack"),t=document.getElementById("catalogueForward"),a=document.getElementById("catalogueHistory"),i=document.getElementById("catalogueHome");e&&e.addEventListener("click",()=>this.catalogueGoBack()),t&&t.addEventListener("click",()=>this.catalogueGoForward()),a&&a.addEventListener("click",()=>this.showCatalogueHistory()),i&&i.addEventListener("click",()=>{this.isOnMainCataloguePage()?this.scrollCatalogueToTop():this.showCatalogueListView(!0)}),this.catalogueHistory.length===0&&this._pushCatalogueHistoryEntry({type:"list"}),this.updateCatalogueNavButtons();let s=document.getElementById("catalogueListView");s&&s.addEventListener("click",n=>{let r=n.target.closest(".class-member__name-link");if(r){n.preventDefault();let l=r.dataset.detailMapId;l&&this.showCatalogueDetailView(l);return}let o=n.target.closest(".map-card__name-link");if(o){n.preventDefault();let l=o.dataset.detailMapId;l&&this.showCatalogueDetailView(l);return}})}showCatalogueDetailView(e,t=!0){let a=P.getMapById(e);if(!a){console.warn("[UIController] Map not found:",e);return}t&&this._pushCatalogueHistoryEntry({type:"detail",mapId:e}),this.catalogueView="detail";let i=document.getElementById("catalogueNav"),s=document.getElementById("catalogueListView"),n=document.getElementById("catalogueDetailView");if(!i||!s||!n)return;s.classList.add("hidden"),n.classList.remove("hidden"),this.updateCatalogueNavButtons();let r=this.getMapIdsFromURL().includes(a.id),o=a.style?.color||"#888",l=this.formatMapDate(a.date)||"",u=(P.getMapCategories()||[]).find(x=>x.id===a.category)?.name||a.category||"Unknown",p="",f=[];a.featured&&f.push('Featured'),a.isGroup&&f.push('Group'),a.hidden&&f.push('Hidden'),f.length>0&&(p=`
${f.join("")}
`);let g=a.description?`
${this.escapeHtml(a.description)}
`:"",y=(a.keywords||[]).map(x=>`${this.escapeHtml(x)}`).join(""),b=(a.references||[]).map((x,B)=>{let H=B+1,E=x.label?this.escapeHtml(x.label):x.url,k=x.url?`${E}`:E,N=x.note?` ${this.escapeHtml(x.note)}`:"",U=x.accessed?` Accessed ${this.escapeHtml(x.accessed)}`:"";return`
[${H}] ${k}${N}${U}
`}).join(""),v=a.files?.fgb||a.files?.geojson||null,w=[];a.style?.color&&w.push(`Color: ${a.style.color}`),a.style?.weight&&w.push(`Weight: ${a.style.weight}`),a.style?.fillOpacity!==void 0&&w.push(`Fill: ${a.style.fillOpacity}`);let S=w.join(", "),M="";a.isGroup&&a.variants&&a.variants.length>0&&(M=` + data-election-constituency-level="${tt(s||"dea")}" + data-election-constituency-body="${tt(c||"")}" + data-election-constituency-date="${tt(e||"")}" + data-election-constituency-name="${tt(r)}">${n}`}W();var os="https://data.civgraph.net";function Ta(c){if(typeof c!="string"||!c)return"";let e=c.replace(/^\/+/,"");return typeof window<"u"&&window.location?.hostname==="localhost"?`/_r/${e}`:`${os}/${e}`}var xa={vote:'',map:'',"book-open":'',table:'',"clipboard-list":'',landmark:'',"chart-column":'',scale:'',library:''},ls={"boundary-reports":"clipboard-list","parliamentary-debates":"landmark","election-results":"vote","census-reports":"chart-column",legislation:"scale",other:"library"};function Oe(c,e="catalogue-flat__section-icon"){let t=xa[c]||xa["book-open"];return``}function Ot(c){return Oe(ls[c?.id]||"book-open")}var zt=class{constructor(){va(this,"_expandedVariants",new Set);this.splitStates=[{id:"info-full",label:"Info only",mobileLabel:"Info"},{id:"info-75",label:"Info focus"},{id:"balanced",label:"Split 50/50"},{id:"map-75",label:"Map focus"},{id:"map-full",label:"Map only",mobileLabel:"Map"}],this.currentStateId="balanced",this.storageKey="split-preference.v2",this.isMobile=!1,this.focusedCardIndex=-1,this._savedSliderValues=new Map,this.showAllMaps=!1,this.onSplitChange=null,this.onMapLoad=null,this.onMapUnload=null,this.onMapToggle=null,this.onCheckMapLoaded=null,this.onCheckMapVisible=null,this.onLoadSingleFeature=null,this.onHideMap=null,this.onVisibilityToggle=null,this.onCategoryChange=null,this.onProviderCategoryChange=null,this.onExpandToFullMap=null,this.onPartialFeatureToggle=null,this.onPartialFeatureUnload=null,this.onCheckFeatureLoaded=null,this.onCheckFeatureVisible=null,this.onFeatureLoad=null,this.onSearch=null,this.onMapDetailClick=null,this.onOpenElectionEntityDetail=null,this.onElectionEntityElectionOpen=null,this.onOpenElectionConstituencyFeature=null,this.onBuildElectionCatalogueCards=null,this.onLoadElection=null,this.onUnloadElection=null,this.onCheckElectionLoaded=null,this.onSetupElectionTableControls=null,this._searchAddressAbortController=null,this.catalogueHistory=[],this.catalogueHistoryIndex=-1,this.catalogueView="list",this._lastMapListOptions={},this._showPlaceholdersCards=new Set,this._showByElectionCards=new Set,this._cataloguePane=null,this._electionEntityDetailCache=new Map,this._catalogueBookView=null,this._bookMarkdownCache=new Map,this._flatRenderToken=null,this._flatRenderScheduled=!1,this._pendingFlatRenderOptions=null,this._flatRenderResolvers=[],this._flatTocTargetIds=new Set,this.singleSectionFlatCatalogue=!1,this._flatActiveSectionKey=null,this._flatTargetToSection=new Map,this._flatSectionTargets=new Map,this._thumbnailIds=null,this._thumbnailManifestPromise=null,this._featureCountManifest=null,this._featureCountManifestPromise=null,this._featureThumbnailManifest=null,this._featureThumbnailManifestPromise=null,this._featureThumbnailRenderedIdsByMap=new Map,this._catalogueSearchIndex=null,this._catalogueSearchIndexPromise=null,this._catalogueSearchBrowseCache=new Map,this._catalogueSearchQuery="",this._catalogueSearchToken=0,this._thumbnailObserver=null,this._mobileCatalogueExpanded=!1,this._mobileCatalogueDeferred=!1,this._mobileInitialMapCardLimit=24,this._mobileInitialElectionCardLimit=2}init(){return this.mediaQuery=window.matchMedia("(max-width: 768px)"),this.isMobile=this.mediaQuery.matches,this.mediaQuery.addEventListener("change",e=>{if(this.isMobile=e.matches,e.matches)try{let t=JSON.parse(He(this.storageKey)||"{}");t.mobile&&this.getAllowedStates().some(a=>a.id===t.mobile)?this.currentStateId=t.mobile:this.currentStateId="map-full"}catch{this.currentStateId="map-full"}else try{let t=JSON.parse(He(this.storageKey)||"{}");t.desktop&&this.getAllowedStates().some(a=>a.id===t.desktop)?this.currentStateId=t.desktop:this.currentStateId="balanced"}catch{this.currentStateId="balanced"}this.updateSplitState(),setTimeout(()=>{window.mapController?.map&&window.mapController.map.invalidateSize()},350)}),this.loadPreference(),this.setupSplitToggle(),this.setupTabSwitching(),this.setupCatalogueReturnTop(),this.setupCatalogueNav(),this.setupCatalogueViewToggle(),this.setupMobileMenu(),this.ensureThumbnailManifest().catch(()=>{}),this.ensureFeatureCountManifest().catch(()=>{}),this}setupMobileMenu(){let e=document.getElementById("mobileMenuBtn"),t=document.getElementById("mobileMenu");if(!e||!t)return;e.addEventListener("click",s=>{s.stopPropagation(),!t.classList.contains("hidden")?(t.classList.add("hidden"),e.setAttribute("aria-expanded","false")):(t.classList.remove("hidden"),e.setAttribute("aria-expanded","true"))}),document.addEventListener("click",s=>{!t.classList.contains("hidden")&&!t.contains(s.target)&&!e.contains(s.target)&&(t.classList.add("hidden"),e.setAttribute("aria-expanded","false"))});let a=document.getElementById("mobileSupportBtn"),i=document.getElementById("supportBtn");a&&i&&a.addEventListener("click",s=>{s.preventDefault(),i.click()})}setupCatalogueNav(){let e=document.getElementById("catalogueBack"),t=document.getElementById("catalogueForward"),a=document.getElementById("catalogueHistory"),i=document.getElementById("catalogueHome");e&&e.addEventListener("click",()=>this.catalogueGoBack()),t&&t.addEventListener("click",()=>this.catalogueGoForward()),a&&a.addEventListener("click",()=>this.showCatalogueHistory()),i&&i.addEventListener("click",()=>{this.isOnMainCataloguePage()?this.scrollCatalogueToTop():this.showCatalogueListView(!0)}),this.catalogueHistory.length===0&&this._pushCatalogueHistoryEntry({type:"list"}),this.updateCatalogueNavButtons();let s=document.getElementById("catalogueListView");s&&s.addEventListener("click",n=>{let r=n.target.closest(".class-member__name-link");if(r){n.preventDefault();let l=r.dataset.detailMapId;l&&this.showCatalogueDetailView(l);return}let o=n.target.closest(".map-card__name-link");if(o){n.preventDefault();let l=o.dataset.detailMapId;l&&this.showCatalogueDetailView(l);return}})}showCatalogueDetailView(e,t=!0){let a=P.getMapById(e);if(!a){console.warn("[UIController] Map not found:",e);return}t&&this._pushCatalogueHistoryEntry({type:"detail",mapId:e}),this.catalogueView="detail";let i=document.getElementById("catalogueNav"),s=document.getElementById("catalogueListView"),n=document.getElementById("catalogueDetailView");if(!i||!s||!n)return;s.classList.add("hidden"),n.classList.remove("hidden"),this.updateCatalogueNavButtons();let r=this.getMapIdsFromURL().includes(a.id),o=a.style?.color||"#888",l=this.formatMapDate(a.date)||"",u=(P.getMapCategories()||[]).find(x=>x.id===a.category)?.name||a.category||"Unknown",p="",f=[];a.featured&&f.push('Featured'),a.isGroup&&f.push('Group'),a.hidden&&f.push('Hidden'),f.length>0&&(p=`
${f.join("")}
`);let g=a.description?`
${this.escapeHtml(a.description)}
`:"",y=(a.keywords||[]).map(x=>`${this.escapeHtml(x)}`).join(""),b=(a.references||[]).map((x,B)=>{let H=B+1,M=x.label?this.escapeHtml(x.label):x.url,k=x.url?`${M}`:M,N=x.note?` ${this.escapeHtml(x.note)}`:"",V=x.accessed?` Accessed ${this.escapeHtml(x.accessed)}`:"";return`
[${H}] ${k}${N}${V}
`}).join(""),v=a.files?.fgb||a.files?.geojson||null,w=[];a.style?.color&&w.push(`Color: ${a.style.color}`),a.style?.weight&&w.push(`Weight: ${a.style.weight}`),a.style?.fillOpacity!==void 0&&w.push(`Fill: ${a.style.fillOpacity}`);let S=w.join(", "),E="";a.isGroup&&a.variants&&a.variants.length>0&&(E=`
Variants (${a.variants.length})
@@ -15,7 +15,7 @@ import{a as At,b as ut,c as ze,d as fa,e as ga}from"./chunk-V4IEUOVV.js";import{
`:""}).join("")}
- `);let C="",T=!a.variants||a.variants.length===0?oe(a):[];a.isGroup&&T.length>0&&(C=` + `);let C="",T=!a.variants||a.variants.length===0?re(a):[];a.isGroup&&T.length>0&&(C=`
Members (${T.length})
@@ -89,7 +89,7 @@ import{a as At,b as ut,c as ze,d as fa,e as ga}from"./chunk-V4IEUOVV.js";import{
${b}
`:""} - ${M} + ${E} ${C}
@@ -101,9 +101,9 @@ import{a as At,b as ut,c as ze,d as fa,e as ga}from"./chunk-V4IEUOVV.js";import{
Loading attributes...
- `;let V=document.getElementById("catalogueBackLink");V&&V.addEventListener("click",()=>this.showCatalogueListView()),this.bindMapActionStrip(n,a,{activeClassTarget:n,variantsHost:n}),n.querySelectorAll(".catalogue-detail__variant").forEach(x=>{x.addEventListener("click",()=>{let B=x.dataset.mapId;B&&this.showCatalogueDetailView(B)})});let z=document.getElementById("catalogueAttrTableHeader"),I=document.getElementById("catalogueAttrTableBody");z&&I&&z.addEventListener("click",()=>{I.classList.toggle("catalogue-detail__attr-table-body--collapsed");let x=z.querySelector(".catalogue-detail__attr-table-toggle");x&&(x.innerHTML=I.classList.contains("catalogue-detail__attr-table-body--collapsed")?"▶":"▼")}),this.loadAttributeSchema(a,v)}_pushCatalogueHistoryEntry(e){this.catalogueHistory=this.catalogueHistory.slice(0,this.catalogueHistoryIndex+1),this.catalogueHistory.push(e),this.catalogueHistoryIndex=this.catalogueHistory.length-1}_getActivePaneTabId(){return document.querySelector(".pane-tab.pane-tab--active")?.dataset?.tab||"catalogue"}_pushCatalogueTabHistoryIfNeeded(e){if(!e||e==="catalogue")return;let t=this.catalogueHistory[this.catalogueHistoryIndex];t?.type==="tab"&&t.tabId===e||this._pushCatalogueHistoryEntry({type:"tab",tabId:e})}resolveFeaturePrimaryName(e,t){let a=e?.properties||{},i=[];t?.labelProperty&&i.push(t.labelProperty),Array.isArray(t?.labelPropertyFallbacks)&&i.push(...t.labelPropertyFallbacks),i.push("Name","name","NAME","FinalR_DEA","DEA","DEANAME","WARDNAME","LGDNAME","CONSTITUENCY","COUNTY","PARISH","BARONY");let s=new Set;for(let r of i){if(!r||s.has(r))continue;s.add(r);let o=a[r];if(typeof o=="string"&&o.trim())return{key:r,value:o.trim()}}let n=Object.entries(a).find(([r,o])=>typeof o=="string"&&o.trim()&&/(name|title|label|dea|ward|district|constituency|county)/i.test(r));return n?{key:n[0],value:n[1].trim()}:{key:null,value:"Unnamed Feature"}}createFeatureDetailId(e,t,a){return`${e||"feature"}:${t??a}`}createElectionEntityDetailId(e,t){return`election:${e}:${t}`}cacheElectionEntityDetailEntry(e){if(!e?.kind||!e?.key)return null;let t=this.createElectionEntityDetailId(e.kind,e.key);return this._electionEntityDetailCache.set(t,e),t}cacheFeatureDetailEntry(e,t,a=null,i=null,s=null){let n=a?{value:a}:this.resolveFeaturePrimaryName(t,e),r=i??t?.id,o=this.createFeatureDetailId(e?.id,r,n.value);return this._featureDetailCache||(this._featureDetailCache=new Map),this._featureDetailCache.set(o,{feature:{mapId:e?.id,id:r??n.value,properties:t?.properties||{},geometry:t?.geometry||null},mapConfig:e,primaryName:n.value,electoralHistory:s?.electoralHistory||null}),o}slugifyForFilename(e){return String(e||"feature").normalize("NFKD").replace(/[^\w\s-]/g,"").trim().replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"").toLowerCase()||"feature"}buildFeatureFileBase(e){let t=this._featureDetailCache?.get(e);if(!t)return"feature";let a=this.slugifyForFilename(t.mapConfig?.slug||t.mapConfig?.id||t.mapConfig?.name||"map"),i=this.slugifyForFilename(t.primaryName||t.feature?.id||"feature");return`${a}--${i}`}buildFeatureGeoJSON(e){let t=this._featureDetailCache?.get(e);return t?{type:"FeatureCollection",features:[{type:"Feature",id:t.feature?.id??void 0,properties:t.feature?.properties||{},geometry:t.feature?.geometry||null}]}:null}buildFeatureShareUrl(e){let t=this._featureDetailCache?.get(e);if(!t?.mapConfig?.id)return null;let a=new URL(window.location.href),i=new URLSearchParams(a.hash.replace(/^#/,"")),s=new Set((i.get("layers")||"").split(",").filter(Boolean));return s.add(t.mapConfig.id),i.set("layers",Array.from(s).join(",")),i.set("featureMap",t.mapConfig.id),i.set("featureId",String(t.feature?.id??"")),i.set("featureName",t.primaryName||"Feature"),a.hash=i.toString(),a.toString()}copyFeatureUrl(e,t){let a=this.buildFeatureShareUrl(e);a&&navigator.clipboard.writeText(a).then(()=>{let i=t?.getAttribute("title");t&&(t.setAttribute("title","Copied!"),setTimeout(()=>{t.setAttribute("title",i||"Copy shareable URL")},1500)),this.announce("Feature URL copied to clipboard")}).catch(i=>{console.error("[UIController] Failed to copy feature URL:",i)})}triggerBlobDownload(e,t){let a=URL.createObjectURL(e),i=document.createElement("a");i.href=a,i.download=t,document.body.appendChild(i),i.click(),i.remove(),setTimeout(()=>URL.revokeObjectURL(a),1e3)}featureToCsv(e){let t=this._featureDetailCache?.get(e);if(!t)return null;let a=t.feature?.properties||{},i=[...Object.keys(a),"geometry_type"],s=i.map(r=>{if(r==="geometry_type")return t.feature?.geometry?.type||"";let o=a[r];return o==null?"":typeof o=="object"?JSON.stringify(o):String(o)}),n=r=>{let o=String(r??"");return/[",\n]/.test(o)?`"${o.replace(/"/g,'""')}"`:o};return`${i.map(n).join(",")} + `;let z=document.getElementById("catalogueBackLink");z&&z.addEventListener("click",()=>this.showCatalogueListView()),this.bindMapActionStrip(n,a,{activeClassTarget:n,variantsHost:n}),n.querySelectorAll(".catalogue-detail__variant").forEach(x=>{x.addEventListener("click",()=>{let B=x.dataset.mapId;B&&this.showCatalogueDetailView(B)})});let O=document.getElementById("catalogueAttrTableHeader"),I=document.getElementById("catalogueAttrTableBody");O&&I&&O.addEventListener("click",()=>{I.classList.toggle("catalogue-detail__attr-table-body--collapsed");let x=O.querySelector(".catalogue-detail__attr-table-toggle");x&&(x.innerHTML=I.classList.contains("catalogue-detail__attr-table-body--collapsed")?"▶":"▼")}),this.loadAttributeSchema(a,v)}_pushCatalogueHistoryEntry(e){this.catalogueHistory=this.catalogueHistory.slice(0,this.catalogueHistoryIndex+1),this.catalogueHistory.push(e),this.catalogueHistoryIndex=this.catalogueHistory.length-1}_getActivePaneTabId(){return document.querySelector(".pane-tab.pane-tab--active")?.dataset?.tab||"catalogue"}_pushCatalogueTabHistoryIfNeeded(e){if(!e||e==="catalogue")return;let t=this.catalogueHistory[this.catalogueHistoryIndex];t?.type==="tab"&&t.tabId===e||this._pushCatalogueHistoryEntry({type:"tab",tabId:e})}resolveFeaturePrimaryName(e,t){let a=e?.properties||{},i=[];t?.labelProperty&&i.push(t.labelProperty),Array.isArray(t?.labelPropertyFallbacks)&&i.push(...t.labelPropertyFallbacks),i.push("Name","name","NAME","FinalR_DEA","DEA","DEANAME","WARDNAME","LGDNAME","CONSTITUENCY","COUNTY","PARISH","BARONY");let s=new Set;for(let r of i){if(!r||s.has(r))continue;s.add(r);let o=a[r];if(typeof o=="string"&&o.trim())return{key:r,value:o.trim()}}let n=Object.entries(a).find(([r,o])=>typeof o=="string"&&o.trim()&&/(name|title|label|dea|ward|district|constituency|county)/i.test(r));return n?{key:n[0],value:n[1].trim()}:{key:null,value:"Unnamed Feature"}}createFeatureDetailId(e,t,a){return`${e||"feature"}:${t??a}`}createElectionEntityDetailId(e,t){return`election:${e}:${t}`}cacheElectionEntityDetailEntry(e){if(!e?.kind||!e?.key)return null;let t=this.createElectionEntityDetailId(e.kind,e.key);return this._electionEntityDetailCache.set(t,e),t}cacheFeatureDetailEntry(e,t,a=null,i=null,s=null){let n=a?{value:a}:this.resolveFeaturePrimaryName(t,e),r=i??t?.id,o=this.createFeatureDetailId(e?.id,r,n.value);return this._featureDetailCache||(this._featureDetailCache=new Map),this._featureDetailCache.set(o,{feature:{mapId:e?.id,id:r??n.value,properties:t?.properties||{},geometry:t?.geometry||null},mapConfig:e,primaryName:n.value,electoralHistory:s?.electoralHistory||null}),o}slugifyForFilename(e){return String(e||"feature").normalize("NFKD").replace(/[^\w\s-]/g,"").trim().replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"").toLowerCase()||"feature"}buildFeatureFileBase(e){let t=this._featureDetailCache?.get(e);if(!t)return"feature";let a=this.slugifyForFilename(t.mapConfig?.slug||t.mapConfig?.id||t.mapConfig?.name||"map"),i=this.slugifyForFilename(t.primaryName||t.feature?.id||"feature");return`${a}--${i}`}buildFeatureGeoJSON(e){let t=this._featureDetailCache?.get(e);return t?{type:"FeatureCollection",features:[{type:"Feature",id:t.feature?.id??void 0,properties:t.feature?.properties||{},geometry:t.feature?.geometry||null}]}:null}buildFeatureShareUrl(e){let t=this._featureDetailCache?.get(e);if(!t?.mapConfig?.id)return null;let a=new URL(window.location.href),i=new URLSearchParams(a.hash.replace(/^#/,"")),s=new Set((i.get("layers")||"").split(",").filter(Boolean));return s.add(t.mapConfig.id),i.set("layers",Array.from(s).join(",")),i.set("featureMap",t.mapConfig.id),i.set("featureId",String(t.feature?.id??"")),i.set("featureName",t.primaryName||"Feature"),a.hash=i.toString(),a.toString()}copyFeatureUrl(e,t){let a=this.buildFeatureShareUrl(e);a&&navigator.clipboard.writeText(a).then(()=>{let i=t?.getAttribute("title");t&&(t.setAttribute("title","Copied!"),setTimeout(()=>{t.setAttribute("title",i||"Copy shareable URL")},1500)),this.announce("Feature URL copied to clipboard")}).catch(i=>{console.error("[UIController] Failed to copy feature URL:",i)})}triggerBlobDownload(e,t){let a=URL.createObjectURL(e),i=document.createElement("a");i.href=a,i.download=t,document.body.appendChild(i),i.click(),i.remove(),setTimeout(()=>URL.revokeObjectURL(a),1e3)}featureToCsv(e){let t=this._featureDetailCache?.get(e);if(!t)return null;let a=t.feature?.properties||{},i=[...Object.keys(a),"geometry_type"],s=i.map(r=>{if(r==="geometry_type")return t.feature?.geometry?.type||"";let o=a[r];return o==null?"":typeof o=="object"?JSON.stringify(o):String(o)}),n=r=>{let o=String(r??"");return/[",\n]/.test(o)?`"${o.replace(/"/g,'""')}"`:o};return`${i.map(n).join(",")} ${s.map(n).join(",")} -`}downloadFeature(e,t){let a=this._featureDetailCache?.get(e);if(!a)return;let i=this.buildFeatureFileBase(e),s=this.buildFeatureGeoJSON(e);if(s){if(t==="geojson"){this.triggerBlobDownload(new Blob([JSON.stringify(s,null,2)],{type:"application/geo+json"}),`${i}.geojson`);return}if(t==="json"){let n={mapId:a.mapConfig?.id||null,mapName:a.mapConfig?.name||null,feature:s.features[0]};this.triggerBlobDownload(new Blob([JSON.stringify(n,null,2)],{type:"application/json"}),`${i}.json`);return}if(t==="csv"){let n=this.featureToCsv(e);if(!n)return;this.triggerBlobDownload(new Blob([n],{type:"text/csv;charset=utf-8"}),`${i}.csv`);return}if(t==="fgb")try{let n=flatgeobuf.serialize(s);this.triggerBlobDownload(new Blob([n],{type:"application/octet-stream"}),`${i}.fgb`);return}catch(n){console.error("[UIController] Failed to serialize feature FGB:",n),this.announce("Failed to export feature as FGB")}}}syncFeatureDetailActionButtons(e,t){let a=this._featureDetailCache?.get(t);if(!e||!a?.mapConfig?.id)return;let i=a.mapConfig.id,s=a.feature?.id,n=this.onCheckFeatureLoaded?!!this.onCheckFeatureLoaded(i,s):!1,r=this.onCheckFeatureVisible?!!this.onCheckFeatureVisible(i,s):!1,o=e.querySelector(".feature-load-btn");o&&(o.innerHTML=this.getLoadButtonIcon(n),o.title=n?"Unload feature":"Load feature",o.setAttribute("aria-label",n?"Unload feature":"Load feature"));let l=e.querySelector(".feature-visibility-btn");l&&(l.innerHTML=this.getVisibilityButtonIcon(r),l.title=r?"Hide feature":"Show feature",l.setAttribute("aria-label",r?"Hide feature":"Show feature"),l.disabled=!n)}getFeatureBBox(e){let t={minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0},a=i=>{if(Array.isArray(i)){if(i.length>=2&&typeof i[0]=="number"&&typeof i[1]=="number"){let[s,n]=i;Number.isFinite(s)&&Number.isFinite(n)&&(t.minX=Math.min(t.minX,s),t.minY=Math.min(t.minY,n),t.maxX=Math.max(t.maxX,s),t.maxY=Math.max(t.maxY,n));return}i.forEach(a)}};return a(e?.coordinates),[t.minX,t.minY,t.maxX,t.maxY].every(Number.isFinite)?[t.minX,t.minY,t.maxX,t.maxY]:null}focusFeatureFromTable(e,t,a,i,s){e&&(e.id&&this.onLoadSingleFeature?this.onLoadSingleFeature(e.id,a,i||null,s||null):e.id&&this.onMapLoad&&(this.getMapIdsFromURL().includes(e.id)||this.onMapLoad(e.id)),s&&s.length===4&&this.onZoomToBbox&&this.onZoomToBbox([[s[1],s[0]],[s[3],s[2]]],{smooth:!0}),e.id&&this.onHighlightFeature&&setTimeout(()=>{this.onHighlightFeature(e.id,t?.id??a,{bbox:s,featureName:i||null,labelProperty:e.labelProperty||null,labelPropertyFallbacks:e.labelPropertyFallbacks||[]})},500))}async loadAttributeSchema(e,t){let a=document.getElementById("catalogueAttrTableBody");if(!a)return;let i=t;if(!i&&e.isGroup){if(e.variants&&e.variants.length>0){let s=P.getMapById(e.variants[0].id);i=s?.files?.fgb||s?.files?.geojson}else if(oe(e).length>0){let s=P.getMapById(oe(e)[0]);i=s?.files?.fgb||s?.files?.geojson}}if(!i){a.innerHTML='
No data file available
';return}try{let s=i.split(".").pop()?.toLowerCase(),n=[],r=null;if(s==="fgb"){let E;try{let k=await fetch(i);E=flatgeobuf.deserialize(k.body)[Symbol.asyncIterator]()}catch{E=flatgeobuf.deserialize(i)[Symbol.asyncIterator]()}for(;;){let k=await E.next();if(k.done)break;n.push(k.value)}}else{let k=await(await fetch(i)).json();n=k.features||[k]}if(n.length>0&&n[0].properties&&(r=Object.keys(n[0].properties)),n.length===0||!r){a.innerHTML='
No attributes found
';return}let o=r.map(E=>`${this.escapeHtml(E)}`).join("");a.innerHTML=` +`}downloadFeature(e,t){let a=this._featureDetailCache?.get(e);if(!a)return;let i=this.buildFeatureFileBase(e),s=this.buildFeatureGeoJSON(e);if(s){if(t==="geojson"){this.triggerBlobDownload(new Blob([JSON.stringify(s,null,2)],{type:"application/geo+json"}),`${i}.geojson`);return}if(t==="json"){let n={mapId:a.mapConfig?.id||null,mapName:a.mapConfig?.name||null,feature:s.features[0]};this.triggerBlobDownload(new Blob([JSON.stringify(n,null,2)],{type:"application/json"}),`${i}.json`);return}if(t==="csv"){let n=this.featureToCsv(e);if(!n)return;this.triggerBlobDownload(new Blob([n],{type:"text/csv;charset=utf-8"}),`${i}.csv`);return}if(t==="fgb")try{let n=flatgeobuf.serialize(s);this.triggerBlobDownload(new Blob([n],{type:"application/octet-stream"}),`${i}.fgb`);return}catch(n){console.error("[UIController] Failed to serialize feature FGB:",n),this.announce("Failed to export feature as FGB")}}}syncFeatureDetailActionButtons(e,t){let a=this._featureDetailCache?.get(t);if(!e||!a?.mapConfig?.id)return;let i=a.mapConfig.id,s=a.feature?.id,n=this.onCheckFeatureLoaded?!!this.onCheckFeatureLoaded(i,s):!1,r=this.onCheckFeatureVisible?!!this.onCheckFeatureVisible(i,s):!1,o=e.querySelector(".feature-load-btn");o&&(o.innerHTML=this.getLoadButtonIcon(n),o.title=n?"Unload feature":"Load feature",o.setAttribute("aria-label",n?"Unload feature":"Load feature"));let l=e.querySelector(".feature-visibility-btn");l&&(l.innerHTML=this.getVisibilityButtonIcon(r),l.title=r?"Hide feature":"Show feature",l.setAttribute("aria-label",r?"Hide feature":"Show feature"),l.disabled=!n)}getFeatureBBox(e){let t={minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0},a=i=>{if(Array.isArray(i)){if(i.length>=2&&typeof i[0]=="number"&&typeof i[1]=="number"){let[s,n]=i;Number.isFinite(s)&&Number.isFinite(n)&&(t.minX=Math.min(t.minX,s),t.minY=Math.min(t.minY,n),t.maxX=Math.max(t.maxX,s),t.maxY=Math.max(t.maxY,n));return}i.forEach(a)}};return a(e?.coordinates),[t.minX,t.minY,t.maxX,t.maxY].every(Number.isFinite)?[t.minX,t.minY,t.maxX,t.maxY]:null}focusFeatureFromTable(e,t,a,i,s){e&&(e.id&&this.onLoadSingleFeature?this.onLoadSingleFeature(e.id,a,i||null,s||null):e.id&&this.onMapLoad&&(this.getMapIdsFromURL().includes(e.id)||this.onMapLoad(e.id)),s&&s.length===4&&this.onZoomToBbox&&this.onZoomToBbox([[s[1],s[0]],[s[3],s[2]]],{smooth:!0}),e.id&&this.onHighlightFeature&&setTimeout(()=>{this.onHighlightFeature(e.id,t?.id??a,{bbox:s,featureName:i||null,labelProperty:e.labelProperty||null,labelPropertyFallbacks:e.labelPropertyFallbacks||[]})},500))}async loadAttributeSchema(e,t){let a=document.getElementById("catalogueAttrTableBody");if(!a)return;let i=t;if(!i&&e.isGroup){if(e.variants&&e.variants.length>0){let s=P.getMapById(e.variants[0].id);i=s?.files?.fgb||s?.files?.geojson}else if(re(e).length>0){let s=P.getMapById(re(e)[0]);i=s?.files?.fgb||s?.files?.geojson}}if(!i){a.innerHTML='
No data file available
';return}try{let s=i.split(".").pop()?.toLowerCase(),n=[],r=null;if(s==="fgb"){let M;try{let k=await fetch(i);M=flatgeobuf.deserialize(k.body)[Symbol.asyncIterator]()}catch{M=flatgeobuf.deserialize(i)[Symbol.asyncIterator]()}for(;;){let k=await M.next();if(k.done)break;n.push(k.value)}}else{let k=await(await fetch(i)).json();n=k.features||[k]}if(n.length>0&&n[0].properties&&(r=Object.keys(n[0].properties)),n.length===0||!r){a.innerHTML='
No attributes found
';return}let o=r.map(M=>`${this.escapeHtml(M)}`).join("");a.innerHTML=`
@@ -113,12 +113,12 @@ ${s.map(n).join(",")}
- `;let l=100,d=document.getElementById("attrTableScroll"),h=document.getElementById("attrTableTbody"),u=document.getElementById("attrTableFooter"),p=a.querySelector(".catalogue-detail__attr-table-inner"),f=p?[...p.querySelectorAll("thead th")]:[];if(!d||!h||!u||!p||f.length===0)return;let g=E=>{if(E==null)return"";if(typeof E=="object")try{return JSON.stringify(E)}catch{return String(E)}return String(E)},y=E=>{if(E===null)return{html:"null",title:"null"};let k=typeof E=="object"?g(E):this.formatDisplayValue(E),N=k.substring(0,50)+(k.length>50?"...":"");return{html:this.escapeHtml(N),title:this.escapeHtml(k)}},b=({feature:E,index:k})=>{let N=this.resolveFeaturePrimaryName(E,e),U=this.cacheFeatureDetailEntry(e,E,N.value,E?.id??k),K=r.map(j=>{let m=E.properties?.[j],D=y(m);return N.key&&j===N.key?``:`${D.html}`}).join(""),G=this.getFeatureBBox(E?.geometry);return`{if(M==null)return"";if(typeof M=="object")try{return JSON.stringify(M)}catch{return String(M)}return String(M)},y=M=>{if(M===null)return{html:"null",title:"null"};let k=typeof M=="object"?g(M):this.formatDisplayValue(M),N=k.substring(0,50)+(k.length>50?"...":"");return{html:this.escapeHtml(N),title:this.escapeHtml(k)}},b=({feature:M,index:k})=>{let N=this.resolveFeaturePrimaryName(M,e),V=this.cacheFeatureDetailEntry(e,M,N.value,M?.id??k),K=r.map(j=>{let m=M.properties?.[j],D=y(m);return N.key&&j===N.key?``:`${D.html}`}).join(""),G=this.getFeatureBBox(M?.geometry);return`${K}`},v=E=>{let k=String(E||"").replace(/,/g,"").replace(/%/g,"").replace(/[+\u2212]/g,U=>U==="\u2212"?"-":"+").trim();if(!k||k==="-"||k==="\u2014"||k.toLowerCase()==="n/a")return null;let N=Number(k);return Number.isFinite(N)?N:null},w=E=>{let k=String(E||"").trim().toLowerCase();if(!k)return null;let N=k.match(/^(\d+)(st|nd|rd|th)?$/);if(N)return Number(N[1]);let U=k.match(/count\s+(\d+)/);return U?Number(U[1]):null},S=(E,k)=>g(E?.properties?.[k]),M=E=>{let k=n.slice(0,100).map(G=>S(G,E)).filter(Boolean),N=k.filter(G=>v(G)!==null).length,U=k.filter(G=>w(G)!==null).length;return String(E||"").trim().toLowerCase().includes("rank")?"ordinal":k.length>0&&N/k.length>=.8?"numeric":k.length>0&&U/k.length>=.8?"ordinal":"text"},C=(E,k,N,U,K)=>{if(U==="default")return 0;let G=S(E,N),j=S(k,N),m=0;if(K==="numeric"){let D=v(G),q=v(j);D!==null&&q!==null?m=D-q:D!==null?m=1:q!==null?m=-1:m=G.localeCompare(j,void 0,{numeric:!0,sensitivity:"base"})}else if(K==="ordinal"){let D=w(G),q=w(j);D!==null&&q!==null?m=D-q:m=G.localeCompare(j,void 0,{numeric:!0,sensitivity:"base"})}else m=G.localeCompare(j,void 0,{numeric:!0,sensitivity:"base"});return U==="asc"?m:-m},T={allFeatures:n.map((E,k)=>({feature:E,index:k})),filteredFeatures:[],renderedCount:0,sort:{key:null,dir:"default"},filters:new Map,activeMenu:null,activeMenuBtn:null,documentClickHandler:null},V=()=>{T.activeMenu&&T.activeMenu.remove(),T.activeMenuBtn&&T.activeMenuBtn.classList.remove("election-th-btn--open"),T.documentClickHandler&&(document.removeEventListener("click",T.documentClickHandler),T.documentClickHandler=null),T.activeMenu=null,T.activeMenuBtn=null},z=()=>{let E=T.filteredFeatures.length,k=Math.min(T.renderedCount,E);E===0?u.textContent=`Showing 0 of ${T.allFeatures.length} features`:E===T.allFeatures.length?u.textContent=k{let E=T.filteredFeatures.slice(0,T.renderedCount);E.length===0?h.innerHTML=`No matching features`:h.innerHTML=E.map(k=>b(k)).join(""),z()},x=E=>{let k=new Map;return T.allFeatures.forEach(({feature:N})=>{let U=S(N,E);k.has(U)||k.set(U,U)}),[...k.values()].sort((N,U)=>N.localeCompare(U,void 0,{numeric:!0,sensitivity:"base"}))},B=()=>{let E=T.allFeatures.filter(({feature:k})=>{for(let[N,U]of T.filters.entries())if(!(!(U instanceof Set)||U.size===0)&&!U.has(S(k,N)))return!1;return!0});if(T.sort.key&&T.sort.dir!=="default"){let k=M(T.sort.key);E=[...E].sort((N,U)=>{let K=C(N.feature,U.feature,T.sort.key,T.sort.dir,k);return K!==0?K:N.index-U.index})}else E=[...E].sort((k,N)=>k.index-N.index);T.filteredFeatures=E,T.renderedCount=Math.min(l,T.filteredFeatures.length),I(),f.forEach((k,N)=>{let U=k.querySelector("[data-table-filter-sort-btn]");if(!U)return;let K=r[N],G=T.filters.has(K)&&(T.filters.get(K)?.size??0)>0,j=T.sort.key===K&&T.sort.dir!=="default";U.classList.toggle("election-th-btn--active",G||j),j&&T.sort.dir==="asc"?U.innerHTML="↑":j&&T.sort.dir==="desc"?U.innerHTML="↓":U.innerHTML="⇅"})},H=(E,k)=>{V();let N=r[E],U=M(N),K=x(N),G=T.filters.get(N),j=new Set(G instanceof Set?G:K),m=U==="numeric"?"Sort Smallest to Largest":U==="ordinal"?"Sort Lowest to Highest":"Sort A to Z",D=U==="numeric"?"Sort Largest to Smallest":U==="ordinal"?"Sort Highest to Lowest":"Sort Z to A",q=document.createElement("div");q.className="election-filter-menu",q.innerHTML=` + data-feature-detail-id="${this.escapeHtml(V)}">${K}`},v=M=>{let k=String(M||"").replace(/,/g,"").replace(/%/g,"").replace(/[+\u2212]/g,V=>V==="\u2212"?"-":"+").trim();if(!k||k==="-"||k==="\u2014"||k.toLowerCase()==="n/a")return null;let N=Number(k);return Number.isFinite(N)?N:null},w=M=>{let k=String(M||"").trim().toLowerCase();if(!k)return null;let N=k.match(/^(\d+)(st|nd|rd|th)?$/);if(N)return Number(N[1]);let V=k.match(/count\s+(\d+)/);return V?Number(V[1]):null},S=(M,k)=>g(M?.properties?.[k]),E=M=>{let k=n.slice(0,100).map(G=>S(G,M)).filter(Boolean),N=k.filter(G=>v(G)!==null).length,V=k.filter(G=>w(G)!==null).length;return String(M||"").trim().toLowerCase().includes("rank")?"ordinal":k.length>0&&N/k.length>=.8?"numeric":k.length>0&&V/k.length>=.8?"ordinal":"text"},C=(M,k,N,V,K)=>{if(V==="default")return 0;let G=S(M,N),j=S(k,N),m=0;if(K==="numeric"){let D=v(G),q=v(j);D!==null&&q!==null?m=D-q:D!==null?m=1:q!==null?m=-1:m=G.localeCompare(j,void 0,{numeric:!0,sensitivity:"base"})}else if(K==="ordinal"){let D=w(G),q=w(j);D!==null&&q!==null?m=D-q:m=G.localeCompare(j,void 0,{numeric:!0,sensitivity:"base"})}else m=G.localeCompare(j,void 0,{numeric:!0,sensitivity:"base"});return V==="asc"?m:-m},T={allFeatures:n.map((M,k)=>({feature:M,index:k})),filteredFeatures:[],renderedCount:0,sort:{key:null,dir:"default"},filters:new Map,activeMenu:null,activeMenuBtn:null,documentClickHandler:null},z=()=>{T.activeMenu&&T.activeMenu.remove(),T.activeMenuBtn&&T.activeMenuBtn.classList.remove("election-th-btn--open"),T.documentClickHandler&&(document.removeEventListener("click",T.documentClickHandler),T.documentClickHandler=null),T.activeMenu=null,T.activeMenuBtn=null},O=()=>{let M=T.filteredFeatures.length,k=Math.min(T.renderedCount,M);M===0?u.textContent=`Showing 0 of ${T.allFeatures.length} features`:M===T.allFeatures.length?u.textContent=k{let M=T.filteredFeatures.slice(0,T.renderedCount);M.length===0?h.innerHTML=`No matching features`:h.innerHTML=M.map(k=>b(k)).join(""),O()},x=M=>{let k=new Map;return T.allFeatures.forEach(({feature:N})=>{let V=S(N,M);k.has(V)||k.set(V,V)}),[...k.values()].sort((N,V)=>N.localeCompare(V,void 0,{numeric:!0,sensitivity:"base"}))},B=()=>{let M=T.allFeatures.filter(({feature:k})=>{for(let[N,V]of T.filters.entries())if(!(!(V instanceof Set)||V.size===0)&&!V.has(S(k,N)))return!1;return!0});if(T.sort.key&&T.sort.dir!=="default"){let k=E(T.sort.key);M=[...M].sort((N,V)=>{let K=C(N.feature,V.feature,T.sort.key,T.sort.dir,k);return K!==0?K:N.index-V.index})}else M=[...M].sort((k,N)=>k.index-N.index);T.filteredFeatures=M,T.renderedCount=Math.min(l,T.filteredFeatures.length),I(),f.forEach((k,N)=>{let V=k.querySelector("[data-table-filter-sort-btn]");if(!V)return;let K=r[N],G=T.filters.has(K)&&(T.filters.get(K)?.size??0)>0,j=T.sort.key===K&&T.sort.dir!=="default";V.classList.toggle("election-th-btn--active",G||j),j&&T.sort.dir==="asc"?V.innerHTML="↑":j&&T.sort.dir==="desc"?V.innerHTML="↓":V.innerHTML="⇅"})},H=(M,k)=>{z();let N=r[M],V=E(N),K=x(N),G=T.filters.get(N),j=new Set(G instanceof Set?G:K),m=V==="numeric"?"Sort Smallest to Largest":V==="ordinal"?"Sort Lowest to Highest":"Sort A to Z",D=V==="numeric"?"Sort Largest to Smallest":V==="ordinal"?"Sort Highest to Lowest":"Sort Z to A",q=document.createElement("div");q.className="election-filter-menu",q.innerHTML=` @@ -133,23 +133,21 @@ ${s.map(n).join(",")} - `,document.body.appendChild(q),T.activeMenu=q,T.activeMenuBtn=k,k.classList.add("election-th-btn--open");let J=k.getBoundingClientRect(),se=248,ee=8,he=window.scrollX||window.pageXOffset||0,ce=window.scrollY||window.pageYOffset||0,Be=he+J.right-se,Ne=he+window.innerWidth-se-ee;q.style.left=`${Math.max(he+ee,Math.min(Be,Ne))}px`;let re=q.offsetHeight||320,Fe=ce+J.bottom+4,Me=ce+J.top-re-4,lt=ce+window.innerHeight-ee,ct=ce+ee,Et=Fe+re<=lt,fe=Me>=ct;q.style.top=`${Et||!fe?Fe:Me}px`;let Ze=q.querySelector('[data-role="values"]'),ge=(_="")=>{let R=_.trim().toLowerCase();Ze.innerHTML="",K.filter(O=>!R||O.toLowerCase().includes(R)).forEach(O=>{let F=document.createElement("label");F.className="election-filter-menu__value",F.innerHTML=`${this.escapeHtml(O||"(Blank)")}`;let $=F.querySelector("input");$.addEventListener("change",()=>{$.checked?j.add(O):j.delete(O)}),Ze.appendChild(F)})};ge();let He=q.querySelector(".election-filter-menu__search");He?.addEventListener("input",()=>ge(He.value||"")),q.addEventListener("click",_=>{let R=_.target.closest("button[data-action]");if(!R)return;let O=R.dataset.action;O==="sort-asc"?(T.sort.key=N,T.sort.dir="asc",B(),V()):O==="sort-desc"?(T.sort.key=N,T.sort.dir="desc",B(),V()):O==="reset-sort"?(T.sort.key=null,T.sort.dir="default",B(),V()):O==="select-all"?(K.forEach(F=>j.add(F)),ge(He?.value||"")):O==="deselect-all"?(j.clear(),ge(He?.value||"")):O==="clear-filter"?(T.filters.delete(N),B(),V()):O==="apply"&&(j.size===0||j.size===K.length?T.filters.delete(N):T.filters.set(N,new Set(j)),B(),V())}),T.documentClickHandler=_=>{T.activeMenu&&(T.activeMenu.contains(_.target)||T.activeMenuBtn&&T.activeMenuBtn.contains(_.target)||V())},document.addEventListener("click",T.documentClickHandler)};f.forEach((E,k)=>{let N=E.innerHTML;E.innerHTML="";let U=document.createElement("div");U.className="election-th-controls";let K=document.createElement("span");K.className="election-th-label",K.innerHTML=N,U.appendChild(K);let G=document.createElement("span");G.className="election-th-actions";let j=document.createElement("button");j.type="button",j.className="election-th-btn",j.setAttribute("data-table-filter-sort-btn","1"),j.setAttribute("aria-label","Sort and Filter"),j.setAttribute("title","Sort and Filter"),j.innerHTML="⇅",j.addEventListener("click",m=>{m.preventDefault(),m.stopPropagation(),T.activeMenu&&T.activeMenuBtn===j?V():H(k,j)}),G.appendChild(j),U.appendChild(G),E.appendChild(U)}),d.addEventListener("scroll",()=>{let E=d.scrollTop+d.clientHeight,k=d.scrollHeight-50;E=T.filteredFeatures.length||(T.renderedCount=Math.min(T.renderedCount+l,T.filteredFeatures.length),I())},{passive:!0}),h.addEventListener("click",E=>{let k=E.target.closest(".catalogue-detail__attr-link");if(k){E.preventDefault(),E.stopPropagation();let D=k.dataset.featureDetailId;D&&this.showFeatureDetailInCatalogue(D);return}let N=E.target.closest(".catalogue-detail__attr-tr--interactive");if(!N)return;let U=Number(N.dataset.featureIndex),K=N.dataset.featureName||"",G=(N.dataset.featureBbox||"").split(",").map(Number).filter(Number.isFinite),j=N.dataset.featureId||"",m=T.allFeatures.find(D=>D.index===U)?.feature;this.focusFeatureFromTable(e,m,Number.isFinite(U)?U:j,K,G.length===4?G:null)}),B()}catch(s){console.warn("[UIController] Failed to load attribute schema:",s),a.innerHTML='
Failed to load attributes
'}}showCatalogueListView(e=!1){this.catalogueView="list",this._catalogueBookView=null;let t=document.getElementById("catalogueNav"),a=document.getElementById("catalogueListView"),i=document.getElementById("catalogueDetailView");if(!(!t||!a||!i)){if(e){let s=this.catalogueHistory[this.catalogueHistoryIndex];(!s||s.type!=="list")&&this._pushCatalogueHistoryEntry({type:"list"})}a.classList.remove("hidden"),i.classList.add("hidden"),this.requestFlatViewRender(this._lastMapListOptions||{},{defer:this.isMobile}),this.updateCatalogueNavButtons()}}catalogueGoBack(){let e=document.querySelector('.pane__content[data-tab-content="tables"]');if(e&&!e.classList.contains("pane-tab-content--hidden")){this.showTab("catalogue"),this.updateCatalogueNavButtons();return}if(this.catalogueHistoryIndex>0){this.catalogueHistoryIndex--;let t=this.catalogueHistory[this.catalogueHistoryIndex];this._applyCatalogueHistoryEntry(t)}this.updateCatalogueNavButtons()}catalogueGoForward(){if(this.catalogueHistoryIndex{let h=d===this.catalogueHistoryIndex;return`
  • `}).reverse().join("");i.innerHTML=`
      ${o}
    `}e.setAttribute("aria-expanded","true"),(e.parentElement||document.body).appendChild(i);let s=()=>{i.remove(),e.setAttribute("aria-expanded","false"),document.removeEventListener("keydown",n,!0),document.removeEventListener("pointerdown",r,!0),e.focus()},n=o=>{o.key==="Escape"&&(o.preventDefault(),s())},r=o=>{!i.contains(o.target)&&o.target!==e&&s()};document.addEventListener("keydown",n,!0),document.addEventListener("pointerdown",r,!0),i.addEventListener("click",o=>{let l=o.target.closest?.("[data-history-index]");if(!l)return;let d=Number(l.dataset.historyIndex);!Number.isInteger(d)||d<0||d>=a.length||(this.catalogueHistoryIndex=d,this._applyCatalogueHistoryEntry(a[d]),this.updateCatalogueNavButtons(),s())}),i.querySelector(".catalogue-history-popup__item")?.focus()}updateCatalogueNavButtons(){let e=document.getElementById("catalogueBack"),t=document.getElementById("catalogueForward"),a=document.querySelector('.pane__content[data-tab-content="tables"]'),i=a&&!a.classList.contains("pane-tab-content--hidden");e&&(e.disabled=i?!1:this.catalogueHistoryIndex<=0),t&&(t.disabled=this.catalogueHistoryIndex>=this.catalogueHistory.length-1),this.updateCatalogueHomeButton()}setupTabSwitching(){let e=document.querySelectorAll(".pane-tab"),t=document.getElementById("mapList"),a=document.getElementById("exploreContent"),i=document.getElementById("tablesContent");e.forEach(s=>{s.addEventListener("click",()=>{let n=s.dataset.tab;this.showTab(n)})}),document.addEventListener("click",s=>{let n=s.target.closest("[data-tab-target]");n&&(s.preventDefault(),this.showTab(n.dataset.tabTarget))})}showTab(e){let t=document.querySelectorAll(".pane-tab"),a=document.querySelectorAll(".pane-tab-content");t.forEach(i=>{let s=i.dataset.tab===e;i.classList.toggle("pane-tab--active",s),i.setAttribute("aria-selected",s?"true":"false")}),a.forEach(i=>{let n=i.dataset.tabContent===e;i.classList.toggle("pane-tab-content--hidden",!n)}),this.moveCatalogueShellForTab(e),this.updateCatalogueNavButtons(),this.updateCatalogueHomeButton(),e==="explore"&&this.initializeExplore(),e==="tables"&&this.initializeTables(),e==="catalogue"&&this.ensureMobileCatalogueReady()}moveCatalogueShellForTab(e){let t=document.querySelector(".catalogue-sticky-shell");if(t)if(e==="tables"){let a=document.querySelector('.pane__content[data-tab-content="tables"]');a&&t.parentElement!==a&&a.insertBefore(t,a.firstChild)}else{let a=document.querySelector('.pane__content[data-tab-content="catalogue"]');a&&t.parentElement!==a&&a.insertBefore(t,a.firstChild)}}setupCatalogueReturnTop(){let e=document.querySelector('.pane__content[data-tab-content="catalogue"]');e&&(this._cataloguePane=e,e.addEventListener("scroll",()=>this.updateCatalogueHomeButton(),{passive:!0}),window.addEventListener("resize",()=>this.updateCatalogueHomeButton()),this.updateCatalogueHomeButton())}isOnMainCataloguePage(){let e=document.getElementById("catalogueListView"),t=document.getElementById("catalogueDetailView");return!!e&&!!t&&!e.classList.contains("hidden")&&t.classList.contains("hidden")&&!this._catalogueBookView}_applyCatalogueBookViewerChrome(e){let t=document.getElementById("filterStats"),a=document.querySelector(".category-pills-container"),i=document.querySelector(".provider-pills-container");t&&t.classList.toggle("hidden",!!e),a&&a.classList.toggle("hidden",!0),i&&i.classList.toggle("hidden",!0)}_buildBookCardHtml(e){let t=(this.booksData?.categories||[]).find(n=>n.id===e.category)||null,a=this._getBookThumbnailFallbackLabel(e),i=e.file?``}).reverse().join("");i.innerHTML=`
      ${o}
    `}e.setAttribute("aria-expanded","true"),(e.parentElement||document.body).appendChild(i);let s=()=>{i.remove(),e.setAttribute("aria-expanded","false"),document.removeEventListener("keydown",n,!0),document.removeEventListener("pointerdown",r,!0),e.focus()},n=o=>{o.key==="Escape"&&(o.preventDefault(),s())},r=o=>{!i.contains(o.target)&&o.target!==e&&s()};document.addEventListener("keydown",n,!0),document.addEventListener("pointerdown",r,!0),i.addEventListener("click",o=>{let l=o.target.closest?.("[data-history-index]");if(!l)return;let d=Number(l.dataset.historyIndex);!Number.isInteger(d)||d<0||d>=a.length||(this.catalogueHistoryIndex=d,this._applyCatalogueHistoryEntry(a[d]),this.updateCatalogueNavButtons(),s())}),i.querySelector(".catalogue-history-popup__item")?.focus()}updateCatalogueNavButtons(){let e=document.getElementById("catalogueBack"),t=document.getElementById("catalogueForward"),a=document.querySelector('.pane__content[data-tab-content="tables"]'),i=a&&!a.classList.contains("pane-tab-content--hidden");e&&(e.disabled=i?!1:this.catalogueHistoryIndex<=0),t&&(t.disabled=this.catalogueHistoryIndex>=this.catalogueHistory.length-1),this.updateCatalogueHomeButton()}setupTabSwitching(){let e=document.querySelectorAll(".pane-tab"),t=document.getElementById("mapList"),a=document.getElementById("exploreContent"),i=document.getElementById("tablesContent");e.forEach(s=>{s.addEventListener("click",()=>{let n=s.dataset.tab;this.showTab(n)})}),document.addEventListener("click",s=>{let n=s.target.closest("[data-tab-target]");n&&(s.preventDefault(),this.showTab(n.dataset.tabTarget))})}showTab(e){let t=document.querySelectorAll(".pane-tab"),a=document.querySelectorAll(".pane-tab-content");t.forEach(i=>{let s=i.dataset.tab===e;i.classList.toggle("pane-tab--active",s),i.setAttribute("aria-selected",s?"true":"false")}),a.forEach(i=>{let n=i.dataset.tabContent===e;i.classList.toggle("pane-tab-content--hidden",!n)}),this.moveCatalogueShellForTab(e),this.updateCatalogueNavButtons(),this.updateCatalogueHomeButton(),e==="explore"&&this.initializeExplore(),e==="tables"&&this.initializeTables(),e==="catalogue"&&this.ensureMobileCatalogueReady()}moveCatalogueShellForTab(e){let t=document.querySelector(".catalogue-sticky-shell");if(t)if(e==="tables"){let a=document.querySelector('.pane__content[data-tab-content="tables"]');a&&t.parentElement!==a&&a.insertBefore(t,a.firstChild)}else{let a=document.querySelector('.pane__content[data-tab-content="catalogue"]');a&&t.parentElement!==a&&a.insertBefore(t,a.firstChild)}}setupCatalogueReturnTop(){let e=document.querySelector('.pane__content[data-tab-content="catalogue"]');e&&(this._cataloguePane=e,e.addEventListener("scroll",()=>this.updateCatalogueHomeButton(),{passive:!0}),window.addEventListener("resize",()=>this.updateCatalogueHomeButton()),this.updateCatalogueHomeButton())}isOnMainCataloguePage(){let e=document.getElementById("catalogueListView"),t=document.getElementById("catalogueDetailView");return!!e&&!!t&&!e.classList.contains("hidden")&&t.classList.contains("hidden")&&!this._catalogueBookView}_applyCatalogueBookViewerChrome(e){let t=document.getElementById("filterStats"),a=document.querySelector(".category-pills-container"),i=document.querySelector(".provider-pills-container");t&&t.classList.toggle("hidden",!!e),a&&a.classList.toggle("hidden",!0),i&&i.classList.toggle("hidden",!0)}_buildBookCardHtml(e){let t=(this.booksData?.categories||[]).find(n=>n.id===e.category)||null,a=this._getBookThumbnailFallbackLabel(e),i=e.file?``:"",s=e.markdownFile?``:"";return` + `:"",s=e.markdownFile?``:"";return` ${this.renderBookThumbnail(e,t,a)}

    ${this.escapeHtml(e.title)}

    -

    ${this.escapeHtml((e.authors||[]).join(", "))}

    -

    ${this.escapeHtml(e.dateDisplay||e.date||"")}

    +

    ${this.escapeHtml((e.authors||[]).join(", "))}${this.escapeHtml(e.dateDisplay||e.date||"")}

    ${i} ${s} ${e.archiveUrl?`Archive.org`:""}
    - ${e.transcriptionNotice?`

    ${this.escapeHtml(e.transcriptionNotice)}

    `:""}
    `}_bookMatchesSearch(e,t,a){let i=String(a||"").trim().toLowerCase();return i?[e?.title||"",(e?.authors||[]).join(" "),(e?.keywords||[]).join(" "),t?.name||"",t?.description||"","books","book","documents","document"].some(n=>String(n||"").toLowerCase().includes(i)):!0}_getBookThumbnailFallbackLabel(e){let t=String(e?.id||"");return t.startsWith("ni-acts-")?"Acts":t.startsWith("ni-sro-")?"SRO":"Book"}async _getBookMarkdownText(e){if(!e?.markdownFile)return"";if(this._bookMarkdownCache.has(e.markdownFile))return this._bookMarkdownCache.get(e.markdownFile);let t=await fetch(e.markdownFile);if(!t.ok)throw new Error(`Failed to load Markdown (${t.status})`);let a=await t.text();return this._bookMarkdownCache.set(e.markdownFile,a),a}_renderCatalogueBookViewer(e,t,a=""){let i=this.escapeHtml(e.title||""),s=this.escapeHtml((e.authors||[]).join(", ")),n=this.escapeHtml(e.dateDisplay||e.date||""),r=this.escapeHtml(e.transcriptionNotice||"Markdown version may contain inaccuracies and errors."),o=t==="markdown",l=e.file?"":" disabled",d=e.markdownFile?"":" disabled",h=o?`
    ${this.escapeHtml(a||"")}
    `:``;return`
    @@ -181,137 +179,137 @@ ${s.map(n).join(",")} ${h}
    - `}async openCatalogueBookViewer(e,t="pdf",a=!0){let i=P.getBookById(e);if(!i)return;let s=t==="markdown"&&i.markdownFile?"markdown":"pdf";this._catalogueBookView={bookId:e,format:s},this.catalogueView="list";let n=document.getElementById("catalogueListView"),r=document.getElementById("catalogueDetailView");if(n&&n.classList.remove("hidden"),r&&r.classList.add("hidden"),a){let o=this.catalogueHistory[this.catalogueHistoryIndex];(!o||o.type!=="book-viewer"||o.bookId!==e||o.format!==s)&&this._pushCatalogueHistoryEntry({type:"book-viewer",bookId:e,format:s})}await this.renderFlatView(this._lastMapListOptions||{}),this.updateCatalogueNavButtons()}scrollCatalogueToTop(){let e=this._cataloguePane||document.querySelector('.pane__content[data-tab-content="catalogue"]');e&&e.scrollTo({top:0,behavior:"smooth"})}updateCatalogueHomeButton(){let e=document.getElementById("catalogueHome");if(!e)return;let t=this.isOnMainCataloguePage();e.classList.toggle("catalogue-home--top",t),e.title=t?"Return to top":"Back to main catalogue",e.setAttribute("aria-label",t?"Return to top":"Back to main catalogue"),e.innerHTML=t?'':''}setupSplitToggle(){document.querySelectorAll(".split-toggle__btn").forEach(t=>{t.addEventListener("click",()=>{let a=t.dataset.action;a&&this.setSplitState(a)})}),this.updateSplitState(),this.setupSplitDrag(),this.setupMobileToggle()}setupMobileToggle(){let e=document.getElementById("mobileToggle");e&&e.addEventListener("click",()=>{this.currentStateId==="info-full"?this.setSplitState("map-full"):this.setSplitState("info-full"),setTimeout(()=>{window.mapController?.map&&window.mapController.map.invalidateSize()},350)})}setupSplitDrag(){let e=document.getElementById("splitDrag"),t=document.querySelector(".app-main");if(!e||!t)return;let a=!1,i=0,s=50,n=h=>{let u=h.touches?h.touches[0].clientX:h.clientX,p=t.getBoundingClientRect(),f=(u-p.left)/p.width*100,g=5/p.width*100,y=100-g;return Math.max(g,Math.min(y,f))},r=document.body.classList.contains("app-shell")?document.body:t.closest(".app-shell")||document.body,o=h=>{a=!0,i=h.touches?h.touches[0].clientX:h.clientX;let u=getComputedStyle(r).getPropertyValue("--split-position");s=parseFloat(u)||50,document.body.classList.add("split-dragging"),h.preventDefault()},l=h=>{if(!a)return;let u=n(h);r.style.setProperty("--split-position",`${u}%`),u<10?this.currentStateId="map-full":u<30?this.currentStateId="map-75":u<60?this.currentStateId="balanced":u<85?this.currentStateId="info-75":this.currentStateId="info-full"},d=()=>{a&&(a=!1,document.body.classList.remove("split-dragging"),this.savePreference(),this.onSplitChange&&this.onSplitChange(this.currentStateId),setTimeout(()=>{window.mapController?.map&&window.mapController.map.invalidateSize()},50))};e.addEventListener("mousedown",o),document.addEventListener("mousemove",l),document.addEventListener("mouseup",d),e.addEventListener("touchstart",o,{passive:!1}),document.addEventListener("touchmove",l,{passive:!0}),document.addEventListener("touchend",d),e.addEventListener("dblclick",()=>{this.setSplitState("balanced"),r.style.setProperty("--split-position","50%")})}setSplitState(e){let t=this.getAllowedStates();t.find(a=>a.id===e)||(e=t[0]?.id||"balanced"),this.currentStateId=e,this.updateSplitState(),this.savePreference(),this.onSplitChange&&this.onSplitChange(e),e==="info-full"&&this.ensureMobileCatalogueReady(),e!=="info-full"&&setTimeout(()=>{window.mapController?.map&&window.mapController.map.invalidateSize()},350)}cycleSplitState(e=1){let t=this.getAllowedStates(),i=(t.findIndex(s=>s.id===this.currentStateId)+e+t.length)%t.length;this.setSplitState(t[i].id)}getAllowedStates(){return this.isMobile?[this.splitStates.find(e=>e.id==="map-full"),this.splitStates.find(e=>e.id==="info-full")]:this.splitStates}updateSplitState(){let e=document.querySelector(".app-shell");if(!e)return;let t=this.getAllowedStates();t.find(s=>s.id===this.currentStateId)||(this.currentStateId=t[0]?.id||"balanced"),e.dataset.splitState=this.currentStateId,document.querySelectorAll(".split-toggle__btn").forEach(s=>{let n=s.dataset.action===this.currentStateId;s.classList.toggle("split-toggle__btn--active",n);let r=s.dataset.action,o=t.some(l=>l.id===r);s.style.display=o?"":"none"});let i=this.splitStates.find(s=>s.id===this.currentStateId);i&&this.announce(`View changed to ${i.label}`)}savePreference(){try{let e={desktop:this.isMobile?null:this.currentStateId,mobile:this.isMobile?this.currentStateId:null,last:this.currentStateId},t=JSON.parse(De(this.storageKey)||"{}");Object.assign(t,e),localStorage.setItem(this.storageKey,JSON.stringify(t))}catch{}}loadPreference(){try{let e=JSON.parse(localStorage.getItem(this.storageKey)||"{}"),t=this.isMobile?"mobile":"desktop",a=this.isMobile?e[t]||e.last:e[t];a&&this.getAllowedStates().some(i=>i.id===a)&&(this.currentStateId=a)}catch{}}announce(e){let t=document.getElementById("announcer");t&&(t.textContent="",requestAnimationFrame(()=>{t.textContent=e}))}async ensureThumbnailManifest(){return this._thumbnailIds?this._thumbnailIds:(this._thumbnailManifestPromise||(this._thumbnailManifestPromise=fetch("assets/thumbnails/manifest.json",{cache:"force-cache"}).then(e=>e.ok?e.json():[]).then(e=>(this._thumbnailIds=new Set(Array.isArray(e)?e.map(String):[]),this._thumbnailIds)).catch(e=>(console.warn("[UIController] Thumbnail manifest unavailable:",e),this._thumbnailIds=new Set,this._thumbnailIds))),this._thumbnailManifestPromise)}async ensureFeatureCountManifest(){return this._featureCountManifest?this._featureCountManifest:(this._featureCountManifestPromise||(this._featureCountManifestPromise=fetch("data/database/map-feature-counts.json",{cache:"force-cache"}).then(e=>e.ok?e.json():{counts:{}}).then(e=>(this._featureCountManifest=e&&typeof e=="object"?e:{counts:{}},(!this._featureCountManifest.counts||typeof this._featureCountManifest.counts!="object")&&(this._featureCountManifest.counts={}),this._featureCountManifest)).catch(e=>(console.warn("[UIController] Feature-count manifest unavailable:",e),this._featureCountManifest={counts:{}},this._featureCountManifest))),this._featureCountManifestPromise)}async ensureFeatureThumbnailManifest(){return this._featureThumbnailManifest?this._featureThumbnailManifest:(this._featureThumbnailManifestPromise||(this._featureThumbnailManifestPromise=fetch("data/database/feature-thumbnails/_manifest.json",{cache:"force-cache"}).then(e=>e.ok?e.json():{maps:{}}).then(e=>(this._featureThumbnailManifest=e&&typeof e=="object"?e:{maps:{}},(!this._featureThumbnailManifest.maps||typeof this._featureThumbnailManifest.maps!="object")&&(this._featureThumbnailManifest.maps={}),this._featureThumbnailRenderedIdsByMap=new Map,Object.entries(this._featureThumbnailManifest.maps).forEach(([t,a])=>{let i=Array.isArray(a?.renderedAssetIds)?a.renderedAssetIds.map(String):[];i.length&&this._featureThumbnailRenderedIdsByMap.set(String(t),new Set(i))}),this._featureThumbnailManifest)).catch(e=>(console.warn("[UIController] Feature-thumbnail manifest unavailable:",e),this._featureThumbnailManifest={maps:{}},this._featureThumbnailRenderedIdsByMap=new Map,this._featureThumbnailManifest))),this._featureThumbnailManifestPromise)}featureThumbnailBboxKey(e){return!Array.isArray(e)||e.length!==4?"":e.map(t=>Number.isFinite(Number(t))?Number(t).toFixed(8):"").join(",")}featureThumbnailHash(e){let t=2166136261,a=String(e||"");for(let i=0;i>>0).toString(16).padStart(8,"0")}featureThumbnailIdFor(e,t,a){let i=String(e||"feature").normalize("NFKD").replace(/[\u0300-\u036f]/g,"").replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")||"feature",s=this.featureThumbnailHash(String(e||"")+"|"+String(t||"")+"|"+this.featureThumbnailBboxKey(a));return"feature-"+i+"-"+s}getFeatureThumbnailForResult(e,t,a){let i=String(e?.mapId||t?.id||""),s=Array.isArray(e?.bbox)&&e.bbox.length===4?e.bbox:null,n=this._featureThumbnailManifest?.maps?.[i]||null,r=n?.colour||t?.style?.fillColor||t?.style?.color||t?.color||"#3388ff",o=this.featureThumbnailIdFor(i,a||e?.name||e?.id||"",s);if(this._featureThumbnailRenderedIdsByMap?.get(i)?.has(o)&&n?.renderedAssetBasePath){let d=n.renderedAssetExtensionsById&&typeof n.renderedAssetExtensionsById=="object"?n.renderedAssetExtensionsById:null,h=String(d?.[o]||n.renderedAssetExtension||"webp").replace(/^\./,"").replace(/[^a-z0-9]/gi,"")||"webp";return{kind:"rendered",thumbnailId:o,bbox:s,colour:r,url:n.renderedAssetBasePath+encodeURIComponent(o)+"."+h}}return{kind:"bbox-locator",thumbnailId:o,bbox:s,colour:r}}hasThumbnailAsset(e){return!e||!this._thumbnailIds?!1:this._thumbnailIds.has(String(e))}getThumbnailId(e){return e?typeof e=="string"?e:e.cloneOf||e.id||"":""}thumbnailPath(e,t=""){let a=String(e||"");if(!a)return"";let i=`${a}${t}`;return this.hasThumbnailAsset(i)?wa(`assets/thumbnails/${this.escapeHtml(i)}.webp`):""}renderThumbnailImage(e,t,a,i={}){let s=String(e||""),n=this.thumbnailPath(s);if(!n)return"";let r=this.thumbnailPath(s,"-60"),o=r?` data-thumbnail-srcset="${r} 60w, ${n} 120w"`:"",l=i.defer==="hover"?' data-thumbnail-defer="hover"':"";return``}renderThumbnailZone(e,t,a){let i=this.renderThumbnailImage(e,t,a);return`
    ${i}
    `}getMapFeatureCount(e){if(!e||!this._featureCountManifest?.counts)return null;let t=this._featureCountManifest.counts,a=[e.id,e.cloneOf,e.aliasOf,e.sourceMapId].filter(Boolean).map(String);for(let i of a){let s=t[i];if(Number.isFinite(s))return s}return null}getMapFeatureUnitLabel(e,t=null){let a=String(e?.featureUnit||e?.featureType||e?.unitName||"").trim();if(a)return t===1?a.replace(/s$/i,""):a;let i=(String(e?.id||"")+" "+String(e?.name||"")+" "+String(e?.category||"")).toLowerCase(),s=[[/\bwards?\b/,["Ward","Wards"]],[/\bdea|district electoral area/,["DEA","DEAs"]],[/small area|\bsa\b/,["Small Area","Small Areas"]],[/super output area|\bsoa\b/,["Super Output Area","Super Output Areas"]],[/townland/,["Townland","Townlands"]],[/constituenc/,["Constituency","Constituencies"]],[/local government district|\blgd\b/,["Local Government District","Local Government Districts"]],[/electoral division|\bed\b|\bded\b/,["Electoral Division","Electoral Divisions"]],[/settlement/,["Settlement","Settlements"]],[/baron/,["Barony","Baronies"]],[/parish/,["Parish","Parishes"]]];for(let[n,r]of s)if(n.test(i))return t===1?r[0]:r[1];return t===1?"feature":"features"}renderMapProviderSummary(e){let t=Array.isArray(e?.provider)?e.provider.filter(Boolean).join(", "):String(e?.provider||"").trim(),a=this.getMapFeatureCount(e);if(!Number.isFinite(a))return t;let i=a.toLocaleString()+" "+this.getMapFeatureUnitLabel(e,a);return t?t+" - "+i:i}renderBookThumbnail(e,t,a){let i=`book-${e.id}`,s=this.renderThumbnailImage(i,"book-card__thumbnail","60px"),n=e.category?` book-card__thumbnail-fallback--${this.escapeHtml(e.category)}`:"";return` + `}async openCatalogueBookViewer(e,t="pdf",a=!0){let i=P.getBookById(e);if(!i)return;let s=t==="markdown"&&i.markdownFile?"markdown":"pdf";this._catalogueBookView={bookId:e,format:s},this.catalogueView="list";let n=document.getElementById("catalogueListView"),r=document.getElementById("catalogueDetailView");if(n&&n.classList.remove("hidden"),r&&r.classList.add("hidden"),a){let o=this.catalogueHistory[this.catalogueHistoryIndex];(!o||o.type!=="book-viewer"||o.bookId!==e||o.format!==s)&&this._pushCatalogueHistoryEntry({type:"book-viewer",bookId:e,format:s})}await this.renderFlatView(this._lastMapListOptions||{}),this.updateCatalogueNavButtons()}scrollCatalogueToTop(){let e=this._cataloguePane||document.querySelector('.pane__content[data-tab-content="catalogue"]');e&&e.scrollTo({top:0,behavior:"smooth"})}updateCatalogueHomeButton(){let e=document.getElementById("catalogueHome");if(!e)return;let t=this.isOnMainCataloguePage();e.classList.toggle("catalogue-home--top",t),e.title=t?"Return to top":"Back to main catalogue",e.setAttribute("aria-label",t?"Return to top":"Back to main catalogue"),e.innerHTML=t?'':''}setupSplitToggle(){document.querySelectorAll(".split-toggle__btn").forEach(t=>{t.addEventListener("click",()=>{let a=t.dataset.action;a&&this.setSplitState(a)})}),this.updateSplitState(),this.setupSplitDrag(),this.setupMobileToggle()}setupMobileToggle(){let e=document.getElementById("mobileToggle");e&&e.addEventListener("click",()=>{this.currentStateId==="info-full"?this.setSplitState("map-full"):this.setSplitState("info-full"),setTimeout(()=>{window.mapController?.map&&window.mapController.map.invalidateSize()},350)})}setupSplitDrag(){let e=document.getElementById("splitDrag"),t=document.querySelector(".app-main");if(!e||!t)return;let a=!1,i=0,s=50,n=h=>{let u=h.touches?h.touches[0].clientX:h.clientX,p=t.getBoundingClientRect(),f=(u-p.left)/p.width*100,g=5/p.width*100,y=100-g;return Math.max(g,Math.min(y,f))},r=document.body.classList.contains("app-shell")?document.body:t.closest(".app-shell")||document.body,o=h=>{a=!0,i=h.touches?h.touches[0].clientX:h.clientX;let u=getComputedStyle(r).getPropertyValue("--split-position");s=parseFloat(u)||50,document.body.classList.add("split-dragging"),h.preventDefault()},l=h=>{if(!a)return;let u=n(h);r.style.setProperty("--split-position",`${u}%`),u<10?this.currentStateId="map-full":u<30?this.currentStateId="map-75":u<60?this.currentStateId="balanced":u<85?this.currentStateId="info-75":this.currentStateId="info-full"},d=()=>{a&&(a=!1,document.body.classList.remove("split-dragging"),this.savePreference(),this.onSplitChange&&this.onSplitChange(this.currentStateId),setTimeout(()=>{window.mapController?.map&&window.mapController.map.invalidateSize()},50))};e.addEventListener("mousedown",o),document.addEventListener("mousemove",l),document.addEventListener("mouseup",d),e.addEventListener("touchstart",o,{passive:!1}),document.addEventListener("touchmove",l,{passive:!0}),document.addEventListener("touchend",d),e.addEventListener("dblclick",()=>{this.setSplitState("balanced"),r.style.setProperty("--split-position","50%")})}setSplitState(e){let t=this.getAllowedStates();t.find(a=>a.id===e)||(e=t[0]?.id||"balanced"),this.currentStateId=e,this.updateSplitState(),this.savePreference(),this.onSplitChange&&this.onSplitChange(e),e==="info-full"&&this.ensureMobileCatalogueReady(),e!=="info-full"&&setTimeout(()=>{window.mapController?.map&&window.mapController.map.invalidateSize()},350)}cycleSplitState(e=1){let t=this.getAllowedStates(),i=(t.findIndex(s=>s.id===this.currentStateId)+e+t.length)%t.length;this.setSplitState(t[i].id)}getAllowedStates(){return this.isMobile?[this.splitStates.find(e=>e.id==="map-full"),this.splitStates.find(e=>e.id==="info-full")]:this.splitStates}updateSplitState(){let e=document.querySelector(".app-shell");if(!e)return;let t=this.getAllowedStates();t.find(s=>s.id===this.currentStateId)||(this.currentStateId=t[0]?.id||"balanced"),e.dataset.splitState=this.currentStateId,document.querySelectorAll(".split-toggle__btn").forEach(s=>{let n=s.dataset.action===this.currentStateId;s.classList.toggle("split-toggle__btn--active",n);let r=s.dataset.action,o=t.some(l=>l.id===r);s.style.display=o?"":"none"});let i=this.splitStates.find(s=>s.id===this.currentStateId);i&&this.announce(`View changed to ${i.label}`)}savePreference(){try{let e={desktop:this.isMobile?null:this.currentStateId,mobile:this.isMobile?this.currentStateId:null,last:this.currentStateId},t=JSON.parse(He(this.storageKey)||"{}");Object.assign(t,e),localStorage.setItem(this.storageKey,JSON.stringify(t))}catch{}}loadPreference(){try{let e=JSON.parse(localStorage.getItem(this.storageKey)||"{}"),t=this.isMobile?"mobile":"desktop",a=this.isMobile?e[t]||e.last:e[t];a&&this.getAllowedStates().some(i=>i.id===a)&&(this.currentStateId=a)}catch{}}announce(e){let t=document.getElementById("announcer");t&&(t.textContent="",requestAnimationFrame(()=>{t.textContent=e}))}async ensureThumbnailManifest(){return this._thumbnailIds?this._thumbnailIds:(this._thumbnailManifestPromise||(this._thumbnailManifestPromise=fetch("assets/thumbnails/manifest.json",{cache:"force-cache"}).then(e=>e.ok?e.json():[]).then(e=>(this._thumbnailIds=new Set(Array.isArray(e)?e.map(String):[]),this._thumbnailIds)).catch(e=>(console.warn("[UIController] Thumbnail manifest unavailable:",e),this._thumbnailIds=new Set,this._thumbnailIds))),this._thumbnailManifestPromise)}async ensureFeatureCountManifest(){return this._featureCountManifest?this._featureCountManifest:(this._featureCountManifestPromise||(this._featureCountManifestPromise=fetch("data/database/map-feature-counts.json",{cache:"force-cache"}).then(e=>e.ok?e.json():{counts:{}}).then(e=>(this._featureCountManifest=e&&typeof e=="object"?e:{counts:{}},(!this._featureCountManifest.counts||typeof this._featureCountManifest.counts!="object")&&(this._featureCountManifest.counts={}),this._featureCountManifest)).catch(e=>(console.warn("[UIController] Feature-count manifest unavailable:",e),this._featureCountManifest={counts:{}},this._featureCountManifest))),this._featureCountManifestPromise)}async ensureFeatureThumbnailManifest(){return this._featureThumbnailManifest?this._featureThumbnailManifest:(this._featureThumbnailManifestPromise||(this._featureThumbnailManifestPromise=fetch("data/database/feature-thumbnails/_manifest.json",{cache:"force-cache"}).then(e=>e.ok?e.json():{maps:{}}).then(e=>(this._featureThumbnailManifest=e&&typeof e=="object"?e:{maps:{}},(!this._featureThumbnailManifest.maps||typeof this._featureThumbnailManifest.maps!="object")&&(this._featureThumbnailManifest.maps={}),this._featureThumbnailRenderedIdsByMap=new Map,Object.entries(this._featureThumbnailManifest.maps).forEach(([t,a])=>{let i=Array.isArray(a?.renderedAssetIds)?a.renderedAssetIds.map(String):[];i.length&&this._featureThumbnailRenderedIdsByMap.set(String(t),new Set(i))}),this._featureThumbnailManifest)).catch(e=>(console.warn("[UIController] Feature-thumbnail manifest unavailable:",e),this._featureThumbnailManifest={maps:{}},this._featureThumbnailRenderedIdsByMap=new Map,this._featureThumbnailManifest))),this._featureThumbnailManifestPromise)}featureThumbnailBboxKey(e){return!Array.isArray(e)||e.length!==4?"":e.map(t=>Number.isFinite(Number(t))?Number(t).toFixed(8):"").join(",")}featureThumbnailHash(e){let t=2166136261,a=String(e||"");for(let i=0;i>>0).toString(16).padStart(8,"0")}featureThumbnailIdFor(e,t,a){let i=String(e||"feature").normalize("NFKD").replace(/[\u0300-\u036f]/g,"").replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")||"feature",s=this.featureThumbnailHash(String(e||"")+"|"+String(t||"")+"|"+this.featureThumbnailBboxKey(a));return"feature-"+i+"-"+s}getFeatureThumbnailForResult(e,t,a){let i=String(e?.mapId||t?.id||""),s=Array.isArray(e?.bbox)&&e.bbox.length===4?e.bbox:null,n=this._featureThumbnailManifest?.maps?.[i]||null,r=n?.colour||t?.style?.fillColor||t?.style?.color||t?.color||"#3388ff",o=this.featureThumbnailIdFor(i,a||e?.name||e?.id||"",s);if(this._featureThumbnailRenderedIdsByMap?.get(i)?.has(o)&&n?.renderedAssetBasePath){let d=n.renderedAssetExtensionsById&&typeof n.renderedAssetExtensionsById=="object"?n.renderedAssetExtensionsById:null,h=String(d?.[o]||n.renderedAssetExtension||"webp").replace(/^\./,"").replace(/[^a-z0-9]/gi,"")||"webp";return{kind:"rendered",thumbnailId:o,bbox:s,colour:r,url:n.renderedAssetBasePath+encodeURIComponent(o)+"."+h}}return{kind:"bbox-locator",thumbnailId:o,bbox:s,colour:r}}hasThumbnailAsset(e){return!e||!this._thumbnailIds?!1:this._thumbnailIds.has(String(e))}getThumbnailId(e){return e?typeof e=="string"?e:e.cloneOf||e.id||"":""}thumbnailPath(e,t=""){let a=String(e||"");if(!a)return"";let i=`${a}${t}`;return this.hasThumbnailAsset(i)?Ta(`assets/thumbnails/${this.escapeHtml(i)}.webp`):""}renderThumbnailImage(e,t,a,i={}){let s=String(e||""),n=this.thumbnailPath(s);if(!n)return"";let r=this.thumbnailPath(s,"-60"),o=r?` data-thumbnail-srcset="${r} 60w, ${n} 120w"`:"",l=i.defer==="hover"?' data-thumbnail-defer="hover"':"";return``}renderThumbnailZone(e,t,a){let i=this.renderThumbnailImage(e,t,a);return`
    ${i}
    `}getMapFeatureCount(e){if(!e||!this._featureCountManifest?.counts)return null;let t=this._featureCountManifest.counts,a=[e.id,e.cloneOf,e.aliasOf,e.sourceMapId].filter(Boolean).map(String);for(let i of a){let s=t[i];if(Number.isFinite(s))return s}return null}getMapFeatureUnitLabel(e,t=null){let a=String(e?.featureUnit||e?.featureType||e?.unitName||"").trim();if(a)return t===1?a.replace(/s$/i,""):a;let i=(String(e?.id||"")+" "+String(e?.name||"")+" "+String(e?.category||"")).toLowerCase(),s=[[/\bwards?\b/,["Ward","Wards"]],[/\bdea|district electoral area/,["DEA","DEAs"]],[/small area|\bsa\b/,["Small Area","Small Areas"]],[/super output area|\bsoa\b/,["Super Output Area","Super Output Areas"]],[/townland/,["Townland","Townlands"]],[/constituenc/,["Constituency","Constituencies"]],[/local government district|\blgd\b/,["Local Government District","Local Government Districts"]],[/electoral division|\bed\b|\bded\b/,["Electoral Division","Electoral Divisions"]],[/settlement/,["Settlement","Settlements"]],[/baron/,["Barony","Baronies"]],[/parish/,["Parish","Parishes"]]];for(let[n,r]of s)if(n.test(i))return t===1?r[0]:r[1];return t===1?"feature":"features"}renderMapProviderSummary(e){let t=Array.isArray(e?.provider)?e.provider.filter(Boolean).join(", "):String(e?.provider||"").trim(),a=this.getMapFeatureCount(e);if(!Number.isFinite(a))return t;let i=a.toLocaleString()+" "+this.getMapFeatureUnitLabel(e,a);return t?t+" - "+i:i}renderBookThumbnail(e,t,a){let i=`book-${e.id}`,s=this.renderThumbnailImage(i,"book-card__thumbnail","60px"),n=e.category?` book-card__thumbnail-fallback--${this.escapeHtml(e.category)}`:"";return`
    ${s} - ${this.escapeHtml(t?.icon||"[book]")} + ${Ot(t)} ${this.escapeHtml(a)} -
    `}renderTocThumbnail(e){let t=String(e||""),a=this.thumbnailPath(t,"-60")||this.thumbnailPath(t),i=this.thumbnailPath(t);if(!a)return'';let s=i?``:"";return`${s}`}hydrateLazyThumbnails(e=document){let t=Array.from(e.querySelectorAll("img[data-thumbnail-src]:not([data-thumbnail-hydrated])")).filter(i=>i.dataset.thumbnailDefer!=="hover");if(t.length===0)return;let a=i=>this.loadLazyThumbnailImage(i);if(!("IntersectionObserver"in window)){t.forEach(a);return}this._thumbnailObserver||(this._thumbnailObserver=new IntersectionObserver(i=>{i.forEach(s=>{s.isIntersecting&&(this._thumbnailObserver.unobserve(s.target),this.loadLazyThumbnailImage(s.target))})},{rootMargin:"320px 0px"})),t.forEach(i=>this._thumbnailObserver.observe(i))}loadLazyThumbnailImage(e){if(!e||e.dataset.thumbnailHydrated==="1")return;let t=e.dataset.thumbnailSrc;if(!t)return;let a=e.dataset.thumbnailSrcset;a&&(e.srcset=a),e.src=t,e.dataset.thumbnailHydrated="1"}scheduleIdleWork(e,t=120){return typeof window<"u"&&"requestIdleCallback"in window?window.requestIdleCallback(e,{timeout:t}):window.setTimeout(e,0)}async yieldForCatalogueRender(e,t=8){!this.isMobile&&e%(t*2)!==t*2-1||e%t===t-1&&await new Promise(a=>this.scheduleIdleWork(a,80))}requestFlatViewRender(e={},{defer:t=!1}={}){if(this.shouldDeferMobileCatalogueRender())return this.renderDeferredMobileCatalogueShell(),Promise.resolve(!1);this._pendingFlatRenderOptions=e||{};let a=new Promise(n=>{this._flatRenderResolvers.push(n)}),i=n=>{this._flatRenderResolvers.splice(0).forEach(o=>o(n))},s=()=>{this._flatRenderScheduled=!1;let n=this._pendingFlatRenderOptions||{};this.renderFlatView(n).then(()=>{this.restoreExpandedVariants(),i(!0)}).catch(r=>{i(!1),console.error("[UIController] Failed to render flat catalogue view",r)})};return t?(this._flatRenderScheduled||(this._flatRenderScheduled=!0,this.scheduleIdleWork(s,350)),a):(s(),a)}shouldDeferMobileCatalogueRender(){return!(!this.isMobile||this.currentStateId==="info-full"||this.catalogueView!=="list"||this._catalogueBookView)}renderDeferredMobileCatalogueShell(){let e=document.getElementById("catalogueFlatView");e&&(this._mobileCatalogueDeferred=!0,this._flatRenderToken=Symbol("mobile-catalogue-deferred"),e.innerHTML="",e.dataset.rendered="deferred",e.dataset.mobileDeferred="true")}ensureMobileCatalogueReady(){if(!this.isMobile||this.currentStateId!=="info-full")return;let e=document.getElementById("catalogueFlatView");e&&e.dataset.rendered!=="true"&&(this._mobileCatalogueDeferred=!1,delete e.dataset.mobileDeferred,this.requestFlatViewRender(this._lastMapListOptions||{},{defer:!0}))}shouldUseBoundedMobileCatalogue(e={}){return!(!this.isMobile||this._mobileCatalogueExpanded||e.fullCatalogue||this._catalogueBookView)}renderMobileCatalogueExpandControl(){return!this.isMobile||this._mobileCatalogueExpanded?"":'
    '}bindFlatViewDelegates(e){!e||e.dataset.flatDelegatesBound==="true"||(e.dataset.flatDelegatesBound="true",e.addEventListener("click",t=>this.handleFlatViewDelegatedClick(t)),e.addEventListener("mouseenter",t=>this.handleFlatThumbnailMouseEnter(t),!0),e.addEventListener("mouseleave",t=>this.handleFlatThumbnailMouseLeave(t),!0))}normalizeCatalogueSearchText(e){return String(e||"").normalize("NFKD").replace(/[\u0300-\u036f]/g,"").toLowerCase().replace(/[^a-z0-9]+/g," ").trim()}async fetchCatalogueBrowseItems(e){if(this._catalogueSearchBrowseCache.has(e))return this._catalogueSearchBrowseCache.get(e);let t=fetch("data/browse/"+e+".json",{cache:"force-cache"}).then(a=>a.ok?a.json():{items:[]}).then(a=>Array.isArray(a?.items)?a.items:[]).catch(()=>[]);return this._catalogueSearchBrowseCache.set(e,t),t}buildCatalogueSearchBrowseUrl(e,t){if(t?.browseUrl)return t.browseUrl;let a=String(t?.slug||t?.id||t?.key||"").replace(/^(party|person|source):/,"");return a?"/browse/#/"+({elections:"elections",parties:"parties",persons:"persons",sources:"sources"}[e]||e)+"/"+encodeURIComponent(a):""}makeCatalogueSearchRecord(e){let t=String(e.title||e.name||e.id||"").trim(),a=String(e.subtitle||e.category||"").trim(),i=Array.isArray(e.provider)?e.provider.join(", "):String(e.provider||"").trim(),s=[];["date","year","category","group","extent","status","description"].forEach(r=>{let o=e[r];Array.isArray(o)?s.push(o.join(" ")):o!=null&&s.push(String(o))}),Array.isArray(e.keywords)&&s.push(e.keywords.join(" ")),Array.isArray(e.constituencies)&&s.push(e.constituencies.join(" ")),Array.isArray(e.parties)&&s.push(e.parties.map(r=>r?.name||r).join(" "));let n=[t,a,i,s.join(" ")].join(" ");return{...e,title:t,subtitle:a,provider:i,searchText:this.normalizeCatalogueSearchText(n)}}async ensureCatalogueSearchIndex(){return this._catalogueSearchIndex?this._catalogueSearchIndex:(this._catalogueSearchIndexPromise||(this._catalogueSearchIndexPromise=(async()=>{let e=[];P.getAllMaps().filter(s=>!s.hidden).forEach(s=>{e.push(this.makeCatalogueSearchRecord({type:"map",id:s.id,mapId:s.id,title:s.name||s.id,subtitle:this.renderMapProviderSummary(s),provider:s.provider,category:s.category,group:s.group,date:s.date||s.dateRange,keywords:s.keywords,description:s.description,status:s.status,thumbId:s.cloneOf||s.id,url:"/browse/#/maps/"+encodeURIComponent(s.id),actionLabel:s.status==="not yet converted"?"Open details":"Load map"}))});let a=[["elections","election","Election"],["parties","party","Party / label"],["persons","person","Person"],["sources","source","Source"]];return(await Promise.all(a.map(async([s,n,r])=>[s,n,r,await this.fetchCatalogueBrowseItems(s)]))).forEach(([s,n,r,o])=>{o.forEach(l=>{e.push(this.makeCatalogueSearchRecord({...l,type:n,typeLabel:r,id:l.id||l.key||l.slug,title:l.title||l.name||l.id,subtitle:l.subtitle||l.category||"",provider:l.provider,category:l.category,date:l.date,year:l.year,keywords:l.keywords,description:l.description,body:l.body,electionBody:l.body,electionDate:l.date,thumbId:n==="election"?l.thumbnailMapId:null,url:this.buildCatalogueSearchBrowseUrl(s,l)}))})}),this._catalogueSearchIndex=e,e})()),this._catalogueSearchIndexPromise)}featureSearchResultToCatalogueRecord(e){let t=P.getMapById(e.mapId),a=String(e.name||e.id||"Unnamed feature"),i=e.id!==void 0&&e.id!==null&&String(e.id).trim()!==""?e.id:a,s=String(i),n=t?.name||e.mapId||"Map feature";return this.makeCatalogueSearchRecord({type:"feature",typeLabel:"Feature",id:s,featureId:s,mapId:String(e.mapId||""),title:a,subtitle:n,provider:t?.provider,category:t?.category,group:t?.group,bbox:Array.isArray(e.bbox)?e.bbox:null,featureThumbnail:this.getFeatureThumbnailForResult(e,t,a)})}renderCatalogueSearchIconButton(e,t,a,i={},s={}){let n=d=>this.escapeHtml(d==null?"":String(d)),r=Object.entries(i).filter(([,d])=>d!=null).map(([d,h])=>` data-${d}="${n(h)}"`).join(""),o=s.disabled?" disabled":"";return``}renderCatalogueSearchActionStrip(e){let t=s=>this.escapeHtml(s==null?"":String(s)),a='',i='';if(e.type==="map"&&e.mapId&&e.actionLabel!=="Open details"){let s=P.getMapById(e.mapId),n=this.onCheckMapLoaded?!!this.onCheckMapLoaded(e.mapId):!1,r=this.onCheckMapVisible?!!this.onCheckMapVisible(e.mapId):n,o=!!(s?.downloads?.fgb||s?.files?.fgb||s?.files?.geojson||this.getSourceDownloads(s||{}).length);return'
    '+this.renderCatalogueSearchIconButton("toggle-map-visibility",r?"Hide map":"Show map",this.getVisibilityButtonIcon(r),{"map-id":e.mapId})+this.renderCatalogueSearchIconButton("toggle-map-load",n?"Unload map":"Load map",this.getLoadButtonIcon(n),{"map-id":e.mapId})+this.renderCatalogueSearchIconButton("copy-map-url","Copy map URL",a,{"map-id":e.mapId})+(o?this.renderCatalogueSearchIconButton("download-map","Download map",i,{"map-id":e.mapId}):"")+"
    "}if(e.type==="feature"&&e.mapId){let s=e.featureId||e.id,n=Array.isArray(e.bbox)?e.bbox.join(","):"",r=this.onCheckFeatureLoaded?!!this.onCheckFeatureLoaded(e.mapId,s):!1,o=this.onCheckFeatureVisible?!!this.onCheckFeatureVisible(e.mapId,s):r,l={"map-id":e.mapId,"feature-id":s,"feature-name":e.title,"feature-bbox":n};return'
    '+this.renderCatalogueSearchIconButton("toggle-feature-visibility",o?"Hide feature":"Show feature",this.getVisibilityButtonIcon(o),l,{disabled:!r})+this.renderCatalogueSearchIconButton("toggle-feature-load",r?"Unload feature":"Load feature",this.getLoadButtonIcon(r),l)+this.renderCatalogueSearchIconButton("copy-feature-url","Copy feature URL",a,l)+this.renderCatalogueSearchIconButton("download-feature","Download feature",i,l)+"
    "}return e.type==="election"&&e.electionBody&&e.electionDate?'':""}getCatalogueSearchFeaturePayload(e){let t=(e.dataset.featureBbox||"").split(",").map(Number).filter(a=>Number.isFinite(a));return{mapId:e.dataset.mapId,featureId:e.dataset.featureId,featureName:e.dataset.featureName||e.dataset.featureId||"",bbox:t.length===4?t:null}}buildFeatureSearchShareUrl(e,t,a){if(!e||!t)return null;let i=new URL(window.location.href),s=new URLSearchParams(i.hash.replace(/^#/,""));return s.set("layers",e),s.set("featureMap",e),s.set("featureId",String(t)),a&&s.set("featureName",String(a)),i.hash=s.toString(),i.toString()}async loadFeatureFromSearchButton(e,t={}){let{mapId:a,featureId:i,featureName:s,bbox:n}=this.getCatalogueSearchFeaturePayload(e);if(!a||!i)return null;let r=this.onLoadSingleFeature?await this.onLoadSingleFeature(a,i,s,n,{isolate:!0,showInfo:t.showInfo!==!1}):null;return!r&&n&&this.zoomToFeature(n,a,i,s),r}syncDownloadButtons(e=document){e.querySelectorAll?.(".download-fgb-btn[data-map-id]").forEach(t=>{let a=P.getMapById(t.dataset.mapId),i=ht(a);if(i){t.hidden=!1,t.dataset.downloadUrl=i;let s="Download data file (FlatGeobuf)";t.title=s,t.setAttribute("aria-label",s)}else t.hidden=!0,t.setAttribute("aria-hidden","true"),t.tabIndex=-1})}syncCatalogueSearchActionButtons(e=document){e.querySelectorAll?.('.catalogue-search__action-strip[data-search-kind="map"]').forEach(t=>{let a=t.dataset.mapId,i=this.onCheckMapLoaded?!!this.onCheckMapLoaded(a):!1,s=this.onCheckMapVisible?!!this.onCheckMapVisible(a):i,n=t.querySelector('[data-catalogue-search-action="toggle-map-load"]');n&&(n.innerHTML=this.getLoadButtonIcon(i),n.title=i?"Unload map":"Load map",n.setAttribute("aria-label",n.title));let r=t.querySelector('[data-catalogue-search-action="toggle-map-visibility"]');r&&(r.innerHTML=this.getVisibilityButtonIcon(s),r.title=s?"Hide map":"Show map",r.setAttribute("aria-label",r.title))}),e.querySelectorAll?.('.catalogue-search__action-strip[data-search-kind="feature"]').forEach(t=>{let a=t.dataset.mapId,i=t.dataset.featureId,s=this.onCheckFeatureLoaded?!!this.onCheckFeatureLoaded(a,i):!1,n=this.onCheckFeatureVisible?!!this.onCheckFeatureVisible(a,i):s,r=t.querySelector('[data-catalogue-search-action="toggle-feature-load"]');r&&(r.innerHTML=this.getLoadButtonIcon(s),r.title=s?"Unload feature":"Load feature",r.setAttribute("aria-label",r.title));let o=t.querySelector('[data-catalogue-search-action="toggle-feature-visibility"]');o&&(o.innerHTML=this.getVisibilityButtonIcon(n),o.title=n?"Hide feature":"Show feature",o.setAttribute("aria-label",o.title),o.disabled=!s)})}scoreCatalogueSearchRecord(e,t,a,i){if(!e?.searchText)return 0;let s=this.normalizeCatalogueSearchText(e.title),n=0,r=!1;return s===a&&(n+=1e3,r=!0),s.startsWith(a)&&(n+=650,r=!0),e.searchText.includes(a)&&(n+=240,r=!0),t.forEach(l=>{l&&(s.split(" ").includes(l)?(n+=170,r=!0):s.includes(l)&&(n+=100,r=!0),e.searchText.includes(l)&&(n+=40,r=!0))}),r?(e.type==="map"&&i?.has(e.mapId||e.id)&&(n+=Math.max(0,450-i.get(e.mapId||e.id))),n+={map:90,election:85,feature:80,party:70,person:60,source:40}[e.type]||0,n):0}renderCatalogueSearchResult(e){let t=l=>this.escapeHtml(l==null?"":String(l)),a=e.typeLabel||{map:"Map",election:"Election",feature:"Feature",party:"Party / label",person:"Person",source:"Source"}[e.type]||e.type||"Result",i="";e.featureThumbnail?.url?i='':e.featureThumbnail?i='":e.thumbSvg?i='":e.thumbId?i=this.renderThumbnailZone(e.thumbId,"catalogue-search__thumbnail-img","48px"):e.colour?i='':i='';let s=this.renderCatalogueSearchActionStrip(e),n=e.url?'Open details':"",r=e.type==="feature"&&e.mapId?'":'

    '+t(e.title)+"

    ",o=[a,e.subtitle,e.provider].filter(Boolean);return'
    '+i+'
    '+t(a)+"
    "+r+'
    '+t(o.join(" - "))+'
    '+s+n+"
    "}async renderCatalogueSearchResults(e,t={}){let a=this.normalizeCatalogueSearchText(e);this._catalogueSearchQuery=String(e||"").trim();let i=++this._catalogueSearchToken,s=document.getElementById("catalogueFlatView");if(!s)return[];if(!a)return this.clearCatalogueSearchResults({render:!0}),[];this._applyCatalogueBookViewerChrome(!1),s.classList.remove("catalogue-flat-view--book-viewer"),s.classList.add("catalogue-flat-view--search"),s.dataset.rendered="search",s.innerHTML='';let n=Array.isArray(t.mapResultIds)?t.mapResultIds:[],r=new Map(n.map((g,y)=>[String(g),y])),[o,l]=await Promise.all([this.ensureCatalogueSearchIndex(),a.length>=2?this.searchFeatures(e).catch(()=>[]):Promise.resolve([]),a.length>=2?this.ensureFeatureThumbnailManifest().catch(()=>null):Promise.resolve(null)]);if(i!==this._catalogueSearchToken||this.normalizeCatalogueSearchText(this._catalogueSearchQuery)!==a)return[];let d=a.split(/\s+/).filter(Boolean),h=[];o.forEach(g=>{let y=this.scoreCatalogueSearchRecord(g,d,a,r);y>0&&h.push({record:g,score:y})}),l.slice(0,60).forEach(g=>{let y=this.featureSearchResultToCatalogueRecord(g),b=this.scoreCatalogueSearchRecord(y,d,a,r);h.push({record:y,score:Math.max(b,1)+120})});let u=new Map;h.sort((g,y)=>y.score-g.score).forEach(g=>{let y=g.record.type==="feature"?`feature:${g.record.mapId||""}:${g.record.featureId||g.record.id||g.record.title}`:g.record.type+":"+(g.record.mapId||g.record.id||g.record.url||g.record.title);u.has(y)||u.set(y,g.record)});let p=Array.from(u.values()).slice(0,80),f=p.length?p.map(g=>this.renderCatalogueSearchResult(g)).join(""):'
    No matching maps, elections, features, people, parties, or sources found.
    ';return s.innerHTML='",this.bindFlatViewDelegates(s),this.hydrateLazyThumbnails(s),this.syncCatalogueSearchActionButtons(s),this.syncDownloadButtons(s),p}clearCatalogueSearchResults({render:e=!1}={}){this._catalogueSearchQuery="",this._catalogueSearchToken+=1;let t=document.getElementById("catalogueFlatView");t&&t.classList.remove("catalogue-flat-view--search"),e&&this.requestFlatViewRender({...this._lastMapListOptions||{}},{defer:this.isMobile})}async handleCatalogueSearchAction(e){let t=e.dataset.catalogueSearchAction,a=e.closest(".catalogue-search")||document;if((t==="load-map"||t==="toggle-map-load")&&e.dataset.mapId){e.disabled=!0;try{(this.onCheckMapLoaded?!!this.onCheckMapLoaded(e.dataset.mapId):!1)?await this.onMapUnload?.(e.dataset.mapId):await this.onMapLoad?.(e.dataset.mapId)}finally{e.disabled=!1,this.syncCatalogueSearchActionButtons(a)}return}if(t==="toggle-map-visibility"&&e.dataset.mapId){(this.onCheckMapLoaded?!!this.onCheckMapLoaded(e.dataset.mapId):!1)?this.onHideMap?.(e.dataset.mapId):await this.onMapLoad?.(e.dataset.mapId),this.syncCatalogueSearchActionButtons(a);return}if(t==="copy-map-url"&&e.dataset.mapId){this.copyMapUrl(e.dataset.mapId,e);return}if(t==="download-map"&&e.dataset.mapId){this.onDownloadFgb?.(e.dataset.mapId);return}if(t==="load-election"&&e.dataset.electionBody&&e.dataset.electionDate){e.disabled=!0;try{await this.onLoadElection?.(e.dataset.electionBody,e.dataset.electionDate)}finally{e.disabled=!1}return}if((t==="zoom-feature"||t==="toggle-feature-load")&&e.dataset.mapId){let{mapId:i,featureId:s}=this.getCatalogueSearchFeaturePayload(e),n=this.onCheckFeatureLoaded?!!this.onCheckFeatureLoaded(i,s):!1;e.disabled=!0;try{n?this.onPartialFeatureUnload?.(i,s):await this.loadFeatureFromSearchButton(e)}finally{e.disabled=!1,this.syncCatalogueSearchActionButtons(a)}return}if(t==="toggle-feature-visibility"&&e.dataset.mapId){let{mapId:i,featureId:s}=this.getCatalogueSearchFeaturePayload(e);(this.onCheckFeatureLoaded?!!this.onCheckFeatureLoaded(i,s):!1)?this.onPartialFeatureToggle?.(i,s):await this.loadFeatureFromSearchButton(e),this.syncCatalogueSearchActionButtons(a);return}if(t==="copy-feature-url"&&e.dataset.mapId){let{mapId:i,featureId:s,featureName:n}=this.getCatalogueSearchFeaturePayload(e),r=this.buildFeatureSearchShareUrl(i,s,n);r&&navigator.clipboard.writeText(r).then(()=>{let o=e.getAttribute("title");e.setAttribute("title","Copied!"),setTimeout(()=>e.setAttribute("title",o||"Copy feature URL"),1500),this.announce("Feature URL copied to clipboard")}).catch(o=>console.error("[UIController] Failed to copy feature URL:",o));return}if(t==="download-feature"&&e.dataset.mapId){let i=await this.loadFeatureFromSearchButton(e,{showInfo:!1});if(i?.feature){let s=this.cacheFeatureDetailEntry(P.getMapById(e.dataset.mapId),i.feature,i.feature.featureName||e.dataset.featureName,e.dataset.featureId);this.downloadFeature(s,"fgb")}this.syncCatalogueSearchActionButtons(a);return}if(t==="open-feature-detail"&&e.dataset.mapId){let i=await this.loadFeatureFromSearchButton(e,{showInfo:!1});if(i?.feature){let s=this.cacheFeatureDetailEntry(P.getMapById(e.dataset.mapId),i.feature,i.feature.featureName||e.dataset.featureName,e.dataset.featureId);this.showFeatureDetailInCatalogue(s,!0)}this.syncCatalogueSearchActionButtons(a)}}async handleFlatViewDelegatedClick(e){let t=e.target,a=t.closest?.("[data-catalogue-search-action]");if(a){e.preventDefault(),await this.handleCatalogueSearchAction(a);return}if(t.closest?.("[data-mobile-catalogue-full]")){e.preventDefault(),this._mobileCatalogueExpanded=!0,this.requestFlatViewRender({...this._lastMapListOptions||{},fullCatalogue:!0},{defer:!0});return}let s=t.closest?.("[data-book-view]");if(s){e.preventDefault(),this.openCatalogueBookViewer(s.dataset.bookView,s.dataset.bookFormat||"pdf");return}let n=t.closest?.(".catalogue-flat__toc-toplink--tab[data-tab-target]");if(n){e.preventDefault(),this.showTab(n.dataset.tabTarget),location.hash.startsWith("#flat-section-")&&history.replaceState(null,"",location.pathname+location.search),this._markActiveToplink(n),this.updateCatalogueNavButtons();return}let r=t.closest?.(".catalogue-flat__toc-link, .catalogue-flat__toc-toplink, .catalogue-flat__toc-subheading-link, .catalogue-flat__toc-decade-btn, .catalogue-flat__toc-map-btn");if(r){await this.handleFlatTocClick(e,r);return}let o=t.closest?.(".flat-election-by-toggle");if(o){e.preventDefault();let h=o.dataset.electionCardId||o.closest(".c1-card, .class-card, .map-card")?.dataset?.c1Id;if(!h)return;this._showByElectionCards.has(h)?this._showByElectionCards.delete(h):this._showByElectionCards.add(h),await this.requestFlatViewRender({...this._lastMapListOptions||{}},{defer:this.isMobile});let u=document.getElementById(`flat-card-${h}`);u&&this.scrollCatalogueTargetIntoView(u,{focus:!1});return}let l=t.closest?.(".class-card__placeholder-toggle");if(l){e.preventDefault();let h=l.closest(".c1-card, .class-card, .map-card");if(!h)return;let u=l.dataset.showing==="true",p=this._getCardPlaceholderKey(h);!u&&p?this._showPlaceholdersCards.add(p):p&&this._showPlaceholdersCards.delete(p),this._applyPlaceholderToggle(h,!u);return}let d=t.closest?.(".flat-election-link, .election-load-btn, .flat-election-entry");d&&await this.handleFlatElectionClick(e,d)}getCataloguePaneScroller(){return document.querySelector('.pane__content[data-tab-content="catalogue"]')||document.getElementById("catalogueListView")||document.querySelector(".pane--info")}async waitForCatalogueFrame(e=1){for(let t=0;trequestAnimationFrame(a))}async ensureCatalogueTargetRendered(e,t=null){let a=()=>document.getElementById(e),i=a(),s=!i,n=i?.dataset?.catalogueDeferredTarget==="1";if(!s&&!n)return i;if(this.singleSectionFlatCatalogue){let o=t||this._flatTargetToSection?.get?.(e)||null;if(!o)return i||null;this._flatActiveSectionKey=o,await this.requestFlatViewRender({...this._lastMapListOptions||{},flatSectionKey:o},{defer:this.isMobile});for(let l=0;l<12;l+=1)if(await this.waitForCatalogueFrame(1),i=a(),i&&i.dataset?.catalogueDeferredTarget!=="1")return i;return a()}return this.isMobile||n||s?(this._mobileCatalogueExpanded=!0,await this.requestFlatViewRender({...this._lastMapListOptions||{},fullCatalogue:!0},{defer:this.isMobile}),await this.waitForCatalogueFrame(2),a()):i||null}scrollCatalogueTargetIntoView(e,{focus:t=!0}={}){let a=this.getCataloguePaneScroller();if(!e||!a)return!1;let i=a.getBoundingClientRect(),s=e.getBoundingClientRect(),r=a.querySelector(".catalogue-sticky-shell")?.getBoundingClientRect?.().height||0,o=Math.max(12,r+10),l=a.scrollTop+s.top-i.top-o,d=typeof window<"u"&&window.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches;return a.scrollTo({top:Math.max(0,l),behavior:this.isMobile||d?"auto":"smooth"}),t&&(e.setAttribute("tabindex","-1"),e.focus?.({preventScroll:!0})),!0}isCatalogueTargetVisible(e){let t=this.getCataloguePaneScroller();if(!e||!t)return!1;let a=t.getBoundingClientRect(),i=e.getBoundingClientRect(),n=t.querySelector(".catalogue-sticky-shell")?.getBoundingClientRect?.().height||0;return i.top>=a.top+n&&i.top<=a.bottom-12}_markActiveToplink(e){document.querySelectorAll(".catalogue-flat__toc-toplink").forEach(a=>{a===e?a.setAttribute("aria-current","true"):a.removeAttribute("aria-current")})}async handleFlatTocClick(e,t){e.preventDefault(),t.classList.contains("catalogue-flat__toc-toplink")&&this._markActiveToplink(t);let a=t.dataset.catalogueTarget||(t.getAttribute("href")||"").replace(/^#/,"");if(!a)return;let i=t.dataset.catalogueSection||this._flatTargetToSection?.get?.(a)||null,s=await this.ensureCatalogueTargetRendered(a,i);if(!s)return;let n=t.getAttribute("href")||"";n.startsWith("#")&&window.location.hash!==n&&history.pushState(null,"",n);for(let r=0;r<4;r+=1)if(this.scrollCatalogueTargetIntoView(s,{focus:r===0}),await this.waitForCatalogueFrame(r===0?2:1),s=document.getElementById(a),this.isCatalogueTargetVisible(s))return}async handleFlatElectionClick(e,t){if((t.closest(".flat-election-entry")||t)?.dataset?.electionPlaceholder==="1"){e.preventDefault(),e.stopPropagation();return}if(t.classList.contains("flat-election-entry")&&e.target.closest(".flat-election-link, .election-load-btn"))return;e.preventDefault(),e.stopPropagation();let i=document.getElementById("catalogueFlatView")||document,s=t.dataset.electionBody||t.closest(".flat-election-entry")?.dataset.electionBody,n=t.dataset.electionDate||t.closest(".flat-election-entry")?.dataset.electionDate;if(!s||!n)return;let r=[...i.querySelectorAll(".flat-election-entry")].filter(u=>u.dataset.electionBody===s&&u.dataset.electionDate===n),o=[...i.querySelectorAll(".election-load-btn")].filter(u=>u.dataset.electionBody===s&&u.dataset.electionDate===n);if(r.some(u=>u.classList.contains("flat-election-entry--loading")))return;if(t.classList.contains("election-load-btn")&&this.onCheckElectionLoaded?.(s,n)){this.onUnloadElection?.();return}let d=this.getCataloguePaneScroller(),h=d?.scrollTop??null;r.forEach(u=>{u.classList.add("flat-election-entry--loading"),u.setAttribute("aria-busy","true")}),o.forEach(u=>{u.disabled=!0,u.setAttribute("aria-busy","true"),u.dataset.previousTitle=u.getAttribute("title")||"",u.setAttribute("title","Loading")});try{await this.onLoadElection?.(s,n)}finally{d&&h!==null&&requestAnimationFrame(()=>{d.scrollTop=h}),r.forEach(u=>{u.classList.remove("flat-election-entry--loading"),u.removeAttribute("aria-busy")}),o.forEach(u=>{u.disabled=!1,u.removeAttribute("aria-busy"),u.dataset.previousTitle!==void 0&&(u.setAttribute("title",u.dataset.previousTitle),delete u.dataset.previousTitle)})}}handleFlatThumbnailMouseEnter(e){if(this.isMobile)return;let t=e.target.closest(".catalogue-flat__toc-thumbwrap");if(!t||t.classList.contains("catalogue-flat__toc-thumbwrap--missing"))return;let a=t.querySelector(".catalogue-flat__toc-thumbzoom");if(!a)return;this.loadLazyThumbnailImage(a.querySelector("img[data-thumbnail-src]"));let i=t.getBoundingClientRect(),s=i.right+8,n=i.top+i.height/2-60;s+128>window.innerWidth&&(s=i.left-128),n<4&&(n=4),n+128>window.innerHeight&&(n=window.innerHeight-128),a.style.left=s+"px",a.style.top=n+"px",a.classList.add("catalogue-flat__toc-thumbzoom--visible")}handleFlatThumbnailMouseLeave(e){let t=e.target.closest(".catalogue-flat__toc-thumbwrap");if(!t)return;let a=t.querySelector(".catalogue-flat__toc-thumbzoom");a&&a.classList.remove("catalogue-flat__toc-thumbzoom--visible")}syncMapCatalogueState(e={}){this._lastMapListOptions={...this._lastMapListOptions||{},...e||{}};let t=document.getElementById("catalogueFlatView")||document,a=new Set(e.visibleIds||this._lastMapListOptions.visibleIds||[]),i=(s,n)=>{if(typeof this.onCheckMapVisible=="function")try{return!!this.onCheckMapVisible(s)}catch{}return n&&a.has(s)};t.querySelectorAll("[data-map-id]").forEach(s=>{let n=s.dataset.mapId;if(!n)return;let r=this.isMapLoadedState(n,this._lastMapListOptions),o=i(n,r);s.classList.toggle("class-member--loaded",r&&s.classList.contains("class-member")),s.classList.toggle("c1-grid-entry--loaded",r&&s.classList.contains("c1-grid-entry")),s.classList.toggle("variant-item--loaded",r&&s.classList.contains("variant-item")),s.classList.toggle("map-card--active",r&&s.classList.contains("map-card")),s.classList.contains("catalogue-detail")&&s.classList.toggle("catalogue-detail--loaded",r)}),t.querySelectorAll(".load-btn[data-map-id], .c1-load-btn[data-map-id]").forEach(s=>{let n=s.dataset.mapId,r=this.isMapLoadedState(n,this._lastMapListOptions),o=this.isLoadTogglePending(n);s.innerHTML=this.getLoadButtonIcon(r,o),s.classList.toggle("load-btn--busy",o),s.disabled=o,o?s.setAttribute("aria-busy","true"):s.removeAttribute("aria-busy"),s.title=o?r?"Unloading...":"Loading...":r?"Unload":"Load"}),t.querySelectorAll(".visibility-btn[data-map-id]").forEach(s=>{let n=s.dataset.mapId,r=this.isMapLoadedState(n,this._lastMapListOptions),o=i(n,r);s.innerHTML=this.getVisibilityButtonIcon(o),s.title=o?"Hide":"Show",s.disabled=!r})}renderMapList(e,t={}){this._lastMapListOptions=t||{};let a=document.getElementById("mapList");if(this.invalidateFlatView({render:!1}),this._catalogueViewMode==="flat"&&this.requestFlatViewRender(this._lastMapListOptions,{defer:this.isMobile}),this.updateFilterStats(t.shownMaps??e.length,t.totalMaps||e.length),!a)return;let i=new Map;a.querySelectorAll(".map-card--class").forEach(y=>{let b=y.dataset.classId,v=y.querySelector(".timeline-slider");b&&v&&i.set(b,v.value)}),a.querySelectorAll(".c1-card").forEach(y=>{let b=y.dataset.c1Id,v=y.querySelector(".timeline-slider");b&&v&&i.set(`c1:${b}`,v.value)}),a.querySelectorAll(".conjoined-class-group").forEach(y=>{let b=y.dataset.groupId,v=y.querySelector(".timeline-slider");b&&v&&i.set(`group:${b}`,v.value)});let s=new Set;if(a.querySelectorAll(".category-more-maps--expanded").forEach(y=>{y.dataset.categoryId&&s.add(y.dataset.categoryId)}),a.innerHTML="",this.focusedCardIndex=-1,this._savedSliderValues=i,this.invalidateFlatView({render:!1}),e.length===0){a.innerHTML='

    No maps found

    ',this.updateFilterStats(0,t.totalMaps||0);return}let n=P.getAllClasses()||[],r=P.getClasses()||[],o=P.getC1s()||[],l=new Map,d=new Map;n.forEach(y=>{(y.maps||[]).forEach(b=>l.set(b,y))}),r.forEach(y=>{let b=y.category||"other";d.has(b)||d.set(b,[]),d.get(b).push(y)});let h=P.getMapCategories()||[],u=new Map;e.forEach(y=>{let b=y.category||"other";u.has(b)||u.set(b,[]),u.get(b).push(y)});let p=new Set,f=["Communities","History","Elections and Government","Public Services","Physical Geography","Built Environment"],g=new Map;if(f.forEach(y=>g.set(y,[])),h.forEach(y=>{let b=y.group||"Built Environment";g.has(b)||g.set(b,[]),g.get(b).push(y)}),f.forEach(y=>{let b=g.get(y)||[];if(b.length===0||!b.some(S=>{let M=u.get(S.id);return M&&M.length>0}))return;let w=document.createElement("div");w.className="map-list__group-heading",w.innerHTML=`${this.escapeHtml(y)}`,a.appendChild(w),b.forEach(S=>{let M=u.get(S.id);if(!M||M.length===0)return;let C=document.createElement("div");C.className="category-section",C.dataset.categoryId=S.id,a.appendChild(C);let T=o.filter(x=>x.category===S.id),V=d.get(S.id)||[],z=new Set;T.forEach(x=>{this.getC1ClassIds(x).forEach(B=>z.add(B))}),T.forEach(x=>{let B=this.createC1Card(x,t);C.appendChild(B);let H=`c1:${x.id}`;if(this._savedSliderValues.has(H)){let E=B.querySelector(".timeline-slider"),k=B.querySelectorAll(".timeline-labels span");E&&(E.value=this._savedSliderValues.get(H),k.forEach((N,U)=>N.classList.toggle("active",U===parseInt(E.value))))}this.getC1ClassIds(x).forEach(E=>p.add(E))});let I=new Map;if(V.forEach(x=>{z.has(x.id)||x.conjoinedTo&&(I.has(x.conjoinedTo)||I.set(x.conjoinedTo,[]),I.get(x.conjoinedTo).push(x))}),V.forEach(x=>{if(p.has(x.id)||z.has(x.id)||x.conjoinedTo)return;let B=I.get(x.id)||[];if(B.length>0){let H=this.createConjoinedClassGroup(B,x,t);C.appendChild(H);let k=`group:${H.dataset.groupId}`;if(this._savedSliderValues.has(k)){let N=H.querySelector(".timeline-slider"),U=H.querySelectorAll(".timeline-labels span");N&&(N.value=this._savedSliderValues.get(k),U.forEach((K,G)=>K.classList.toggle("active",G===parseInt(N.value))))}p.add(x.id),B.forEach(N=>p.add(N.id))}else{let H=this.createClassCard(x,t);if(C.appendChild(H),this._savedSliderValues.has(x.id)){let E=H.querySelector(".timeline-slider"),k=H.querySelectorAll(".timeline-labels span");E&&(E.value=this._savedSliderValues.get(x.id),k.forEach((N,U)=>N.classList.toggle("active",U===parseInt(E.value))))}p.add(x.id)}}),M&&M.filter(x=>x.featured&&!x.hidden&&!l.has(x.id)).forEach(x=>{let B=this.createMapCard(x,t);C.appendChild(B)}),S.id==="regional-divides"){M&&M.filter(x=>!x.featured&&!x.hidden&&!l.has(x.id)).forEach(x=>{let B=this.createMapCard(x,t);C.appendChild(B)});return}if(M){let x=M.filter(B=>!B.featured&&!B.hidden&&!l.has(B.id));if(x.length>0)if(this.showAllMaps)x.forEach(B=>{let H=this.createMapCard(B,t);C.appendChild(H)});else{let B=document.createElement("div");B.className="category-more-maps category-more-maps--collapsed",B.dataset.categoryId=S.id,x.forEach(k=>{let N=this.createMapCard(k,t);B.appendChild(N)});let H=s.has(S.id);H&&(B.classList.remove("category-more-maps--collapsed"),B.classList.add("category-more-maps--expanded")),C.appendChild(B);let E=document.createElement("button");E.className="category-more-toggle"+(H?" category-more-toggle--expanded":""),E.innerHTML=` + `}renderTocThumbnail(e){let t=String(e||""),a=this.thumbnailPath(t,"-60")||this.thumbnailPath(t),i=this.thumbnailPath(t);if(!a)return'';let s=i?``:"";return`${s}`}hydrateLazyThumbnails(e=document){let t=Array.from(e.querySelectorAll("img[data-thumbnail-src]:not([data-thumbnail-hydrated])")).filter(i=>i.dataset.thumbnailDefer!=="hover");if(t.length===0)return;let a=i=>this.loadLazyThumbnailImage(i);if(!("IntersectionObserver"in window)){t.forEach(a);return}this._thumbnailObserver||(this._thumbnailObserver=new IntersectionObserver(i=>{i.forEach(s=>{s.isIntersecting&&(this._thumbnailObserver.unobserve(s.target),this.loadLazyThumbnailImage(s.target))})},{rootMargin:"320px 0px"})),t.forEach(i=>this._thumbnailObserver.observe(i))}loadLazyThumbnailImage(e){if(!e||e.dataset.thumbnailHydrated==="1")return;let t=e.dataset.thumbnailSrc;if(!t)return;let a=e.dataset.thumbnailSrcset;a&&(e.srcset=a),e.src=t,e.dataset.thumbnailHydrated="1"}scheduleIdleWork(e,t=120){return typeof window<"u"&&"requestIdleCallback"in window?window.requestIdleCallback(e,{timeout:t}):window.setTimeout(e,0)}async yieldForCatalogueRender(e,t=8){!this.isMobile&&e%(t*2)!==t*2-1||e%t===t-1&&await new Promise(a=>this.scheduleIdleWork(a,80))}requestFlatViewRender(e={},{defer:t=!1}={}){if(this.shouldDeferMobileCatalogueRender())return this.renderDeferredMobileCatalogueShell(),Promise.resolve(!1);this._pendingFlatRenderOptions=e||{};let a=new Promise(n=>{this._flatRenderResolvers.push(n)}),i=n=>{this._flatRenderResolvers.splice(0).forEach(o=>o(n))},s=()=>{this._flatRenderScheduled=!1;let n=this._pendingFlatRenderOptions||{};this.renderFlatView(n).then(()=>{this.restoreExpandedVariants(),i(!0)}).catch(r=>{i(!1),console.error("[UIController] Failed to render flat catalogue view",r)})};return t?(this._flatRenderScheduled||(this._flatRenderScheduled=!0,this.scheduleIdleWork(s,350)),a):(s(),a)}shouldDeferMobileCatalogueRender(){return!(!this.isMobile||this.currentStateId==="info-full"||this.catalogueView!=="list"||this._catalogueBookView)}renderDeferredMobileCatalogueShell(){let e=document.getElementById("catalogueFlatView");e&&(this._mobileCatalogueDeferred=!0,this._flatRenderToken=Symbol("mobile-catalogue-deferred"),e.innerHTML="",e.dataset.rendered="deferred",e.dataset.mobileDeferred="true")}ensureMobileCatalogueReady(){if(!this.isMobile||this.currentStateId!=="info-full")return;let e=document.getElementById("catalogueFlatView");e&&e.dataset.rendered!=="true"&&(this._mobileCatalogueDeferred=!1,delete e.dataset.mobileDeferred,this.requestFlatViewRender(this._lastMapListOptions||{},{defer:!0}))}shouldUseBoundedMobileCatalogue(e={}){return!(!this.isMobile||this._mobileCatalogueExpanded||e.fullCatalogue||this._catalogueBookView)}renderMobileCatalogueExpandControl(){return!this.isMobile||this._mobileCatalogueExpanded?"":'
    '}bindFlatViewDelegates(e){!e||e.dataset.flatDelegatesBound==="true"||(e.dataset.flatDelegatesBound="true",e.addEventListener("click",t=>this.handleFlatViewDelegatedClick(t)),e.addEventListener("mouseenter",t=>this.handleFlatThumbnailMouseEnter(t),!0),e.addEventListener("mouseleave",t=>this.handleFlatThumbnailMouseLeave(t),!0))}normalizeCatalogueSearchText(e){return String(e||"").normalize("NFKD").replace(/[\u0300-\u036f]/g,"").toLowerCase().replace(/[^a-z0-9]+/g," ").trim()}async fetchCatalogueBrowseItems(e){if(this._catalogueSearchBrowseCache.has(e))return this._catalogueSearchBrowseCache.get(e);let t=fetch("data/browse/"+e+".json",{cache:"force-cache"}).then(a=>a.ok?a.json():{items:[]}).then(a=>Array.isArray(a?.items)?a.items:[]).catch(()=>[]);return this._catalogueSearchBrowseCache.set(e,t),t}buildCatalogueSearchBrowseUrl(e,t){if(t?.browseUrl)return t.browseUrl;let a=String(t?.slug||t?.id||t?.key||"").replace(/^(party|person|source):/,"");return a?"/browse/#/"+({elections:"elections",parties:"parties",persons:"persons",sources:"sources"}[e]||e)+"/"+encodeURIComponent(a):""}makeCatalogueSearchRecord(e){let t=String(e.title||e.name||e.id||"").trim(),a=String(e.subtitle||e.category||"").trim(),i=Array.isArray(e.provider)?e.provider.join(", "):String(e.provider||"").trim(),s=[];["date","year","category","group","extent","status","description"].forEach(r=>{let o=e[r];Array.isArray(o)?s.push(o.join(" ")):o!=null&&s.push(String(o))}),Array.isArray(e.keywords)&&s.push(e.keywords.join(" ")),Array.isArray(e.constituencies)&&s.push(e.constituencies.join(" ")),Array.isArray(e.parties)&&s.push(e.parties.map(r=>r?.name||r).join(" "));let n=[t,a,i,s.join(" ")].join(" ");return{...e,title:t,subtitle:a,provider:i,searchText:this.normalizeCatalogueSearchText(n)}}async ensureCatalogueSearchIndex(){return this._catalogueSearchIndex?this._catalogueSearchIndex:(this._catalogueSearchIndexPromise||(this._catalogueSearchIndexPromise=(async()=>{let e=[];P.getAllMaps().filter(s=>!s.hidden).forEach(s=>{e.push(this.makeCatalogueSearchRecord({type:"map",id:s.id,mapId:s.id,title:s.name||s.id,subtitle:this.renderMapProviderSummary(s),provider:s.provider,category:s.category,group:s.group,date:s.date||s.dateRange,keywords:s.keywords,description:s.description,status:s.status,thumbId:s.cloneOf||s.id,url:"/browse/#/maps/"+encodeURIComponent(s.id),actionLabel:s.status==="not yet converted"?"Open details":"Load map"}))});let a=[["elections","election","Election"],["parties","party","Party / label"],["persons","person","Person"],["sources","source","Source"]];return(await Promise.all(a.map(async([s,n,r])=>[s,n,r,await this.fetchCatalogueBrowseItems(s)]))).forEach(([s,n,r,o])=>{o.forEach(l=>{e.push(this.makeCatalogueSearchRecord({...l,type:n,typeLabel:r,id:l.id||l.key||l.slug,title:l.title||l.name||l.id,subtitle:l.subtitle||l.category||"",provider:l.provider,category:l.category,date:l.date,year:l.year,keywords:l.keywords,description:l.description,body:l.body,electionBody:l.body,electionDate:l.date,thumbId:n==="election"?l.thumbnailMapId:null,url:this.buildCatalogueSearchBrowseUrl(s,l)}))})}),this._catalogueSearchIndex=e,e})()),this._catalogueSearchIndexPromise)}featureSearchResultToCatalogueRecord(e){let t=P.getMapById(e.mapId),a=String(e.name||e.id||"Unnamed feature"),i=e.id!==void 0&&e.id!==null&&String(e.id).trim()!==""?e.id:a,s=String(i),n=t?.name||e.mapId||"Map feature";return this.makeCatalogueSearchRecord({type:"feature",typeLabel:"Feature",id:s,featureId:s,mapId:String(e.mapId||""),title:a,subtitle:n,provider:t?.provider,category:t?.category,group:t?.group,bbox:Array.isArray(e.bbox)?e.bbox:null,featureThumbnail:this.getFeatureThumbnailForResult(e,t,a)})}renderCatalogueSearchIconButton(e,t,a,i={},s={}){let n=d=>this.escapeHtml(d==null?"":String(d)),r=Object.entries(i).filter(([,d])=>d!=null).map(([d,h])=>` data-${d}="${n(h)}"`).join(""),o=s.disabled?" disabled":"";return``}renderCatalogueSearchActionStrip(e){let t=s=>this.escapeHtml(s==null?"":String(s)),a='',i='';if(e.type==="map"&&e.mapId&&e.actionLabel!=="Open details"){let s=P.getMapById(e.mapId),n=this.onCheckMapLoaded?!!this.onCheckMapLoaded(e.mapId):!1,r=this.onCheckMapVisible?!!this.onCheckMapVisible(e.mapId):n,o=!!(s?.downloads?.fgb||s?.files?.fgb||s?.files?.geojson||this.getSourceDownloads(s||{}).length);return'
    '+this.renderCatalogueSearchIconButton("toggle-map-visibility",r?"Hide map":"Show map",this.getVisibilityButtonIcon(r),{"map-id":e.mapId})+this.renderCatalogueSearchIconButton("toggle-map-load",n?"Unload map":"Load map",this.getLoadButtonIcon(n),{"map-id":e.mapId})+this.renderCatalogueSearchIconButton("copy-map-url","Copy map URL",a,{"map-id":e.mapId})+(o?this.renderCatalogueSearchIconButton("download-map","Download map",i,{"map-id":e.mapId}):"")+"
    "}if(e.type==="feature"&&e.mapId){let s=e.featureId||e.id,n=Array.isArray(e.bbox)?e.bbox.join(","):"",r=this.onCheckFeatureLoaded?!!this.onCheckFeatureLoaded(e.mapId,s):!1,o=this.onCheckFeatureVisible?!!this.onCheckFeatureVisible(e.mapId,s):r,l={"map-id":e.mapId,"feature-id":s,"feature-name":e.title,"feature-bbox":n};return'
    '+this.renderCatalogueSearchIconButton("toggle-feature-visibility",o?"Hide feature":"Show feature",this.getVisibilityButtonIcon(o),l,{disabled:!r})+this.renderCatalogueSearchIconButton("toggle-feature-load",r?"Unload feature":"Load feature",this.getLoadButtonIcon(r),l)+this.renderCatalogueSearchIconButton("copy-feature-url","Copy feature URL",a,l)+this.renderCatalogueSearchIconButton("download-feature","Download feature",i,l)+"
    "}return e.type==="election"&&e.electionBody&&e.electionDate?'':""}getCatalogueSearchFeaturePayload(e){let t=(e.dataset.featureBbox||"").split(",").map(Number).filter(a=>Number.isFinite(a));return{mapId:e.dataset.mapId,featureId:e.dataset.featureId,featureName:e.dataset.featureName||e.dataset.featureId||"",bbox:t.length===4?t:null}}buildFeatureSearchShareUrl(e,t,a){if(!e||!t)return null;let i=new URL(window.location.href),s=new URLSearchParams(i.hash.replace(/^#/,""));return s.set("layers",e),s.set("featureMap",e),s.set("featureId",String(t)),a&&s.set("featureName",String(a)),i.hash=s.toString(),i.toString()}async loadFeatureFromSearchButton(e,t={}){let{mapId:a,featureId:i,featureName:s,bbox:n}=this.getCatalogueSearchFeaturePayload(e);if(!a||!i)return null;let r=this.onLoadSingleFeature?await this.onLoadSingleFeature(a,i,s,n,{isolate:!0,showInfo:t.showInfo!==!1}):null;return!r&&n&&this.zoomToFeature(n,a,i,s),r}syncDownloadButtons(e=document){e.querySelectorAll?.(".download-fgb-btn[data-map-id]").forEach(t=>{let a=P.getMapById(t.dataset.mapId),i=gt(a);if(i){t.hidden=!1,t.dataset.downloadUrl=i;let s="Download data file (FlatGeobuf)";t.title=s,t.setAttribute("aria-label",s)}else t.hidden=!0,t.setAttribute("aria-hidden","true"),t.tabIndex=-1})}syncCatalogueSearchActionButtons(e=document){e.querySelectorAll?.('.catalogue-search__action-strip[data-search-kind="map"]').forEach(t=>{let a=t.dataset.mapId,i=this.onCheckMapLoaded?!!this.onCheckMapLoaded(a):!1,s=this.onCheckMapVisible?!!this.onCheckMapVisible(a):i,n=t.querySelector('[data-catalogue-search-action="toggle-map-load"]');n&&(n.innerHTML=this.getLoadButtonIcon(i),n.title=i?"Unload map":"Load map",n.setAttribute("aria-label",n.title));let r=t.querySelector('[data-catalogue-search-action="toggle-map-visibility"]');r&&(r.innerHTML=this.getVisibilityButtonIcon(s),r.title=s?"Hide map":"Show map",r.setAttribute("aria-label",r.title))}),e.querySelectorAll?.('.catalogue-search__action-strip[data-search-kind="feature"]').forEach(t=>{let a=t.dataset.mapId,i=t.dataset.featureId,s=this.onCheckFeatureLoaded?!!this.onCheckFeatureLoaded(a,i):!1,n=this.onCheckFeatureVisible?!!this.onCheckFeatureVisible(a,i):s,r=t.querySelector('[data-catalogue-search-action="toggle-feature-load"]');r&&(r.innerHTML=this.getLoadButtonIcon(s),r.title=s?"Unload feature":"Load feature",r.setAttribute("aria-label",r.title));let o=t.querySelector('[data-catalogue-search-action="toggle-feature-visibility"]');o&&(o.innerHTML=this.getVisibilityButtonIcon(n),o.title=n?"Hide feature":"Show feature",o.setAttribute("aria-label",o.title),o.disabled=!s)})}scoreCatalogueSearchRecord(e,t,a,i){if(!e?.searchText)return 0;let s=this.normalizeCatalogueSearchText(e.title),n=0,r=!1;return s===a&&(n+=1e3,r=!0),s.startsWith(a)&&(n+=650,r=!0),e.searchText.includes(a)&&(n+=240,r=!0),t.forEach(l=>{l&&(s.split(" ").includes(l)?(n+=170,r=!0):s.includes(l)&&(n+=100,r=!0),e.searchText.includes(l)&&(n+=40,r=!0))}),r?(e.type==="map"&&i?.has(e.mapId||e.id)&&(n+=Math.max(0,450-i.get(e.mapId||e.id))),n+={map:90,election:85,feature:80,party:70,person:60,source:40}[e.type]||0,n):0}renderCatalogueSearchResult(e){let t=l=>this.escapeHtml(l==null?"":String(l)),a=e.typeLabel||{map:"Map",election:"Election",feature:"Feature",party:"Party / label",person:"Person",source:"Source"}[e.type]||e.type||"Result",i="";e.featureThumbnail?.url?i='':e.featureThumbnail?i='":e.thumbSvg?i='":e.thumbId?i=this.renderThumbnailZone(e.thumbId,"catalogue-search__thumbnail-img","48px"):e.colour?i='':i='';let s=this.renderCatalogueSearchActionStrip(e),n=e.url?'Open details':"",r=e.type==="feature"&&e.mapId?'":'

    '+t(e.title)+"

    ",o=[a,e.subtitle,e.provider].filter(Boolean);return'
    '+i+'
    '+t(a)+"
    "+r+'
    '+t(o.join(" - "))+'
    '+s+n+"
    "}async renderCatalogueSearchResults(e,t={}){let a=this.normalizeCatalogueSearchText(e);this._catalogueSearchQuery=String(e||"").trim();let i=++this._catalogueSearchToken,s=document.getElementById("catalogueFlatView");if(!s)return[];if(!a)return this.clearCatalogueSearchResults({render:!0}),[];this._applyCatalogueBookViewerChrome(!1),s.classList.remove("catalogue-flat-view--book-viewer"),s.classList.add("catalogue-flat-view--search"),s.dataset.rendered="search",s.innerHTML='';let n=Array.isArray(t.mapResultIds)?t.mapResultIds:[],r=new Map(n.map((g,y)=>[String(g),y])),[o,l]=await Promise.all([this.ensureCatalogueSearchIndex(),a.length>=2?this.searchFeatures(e).catch(()=>[]):Promise.resolve([]),a.length>=2?this.ensureFeatureThumbnailManifest().catch(()=>null):Promise.resolve(null)]);if(i!==this._catalogueSearchToken||this.normalizeCatalogueSearchText(this._catalogueSearchQuery)!==a)return[];let d=a.split(/\s+/).filter(Boolean),h=[];o.forEach(g=>{let y=this.scoreCatalogueSearchRecord(g,d,a,r);y>0&&h.push({record:g,score:y})}),l.slice(0,60).forEach(g=>{let y=this.featureSearchResultToCatalogueRecord(g),b=this.scoreCatalogueSearchRecord(y,d,a,r);h.push({record:y,score:Math.max(b,1)+120})});let u=new Map;h.sort((g,y)=>y.score-g.score).forEach(g=>{let y=g.record.type==="feature"?`feature:${g.record.mapId||""}:${g.record.featureId||g.record.id||g.record.title}`:g.record.type+":"+(g.record.mapId||g.record.id||g.record.url||g.record.title);u.has(y)||u.set(y,g.record)});let p=Array.from(u.values()).slice(0,80),f=p.length?p.map(g=>this.renderCatalogueSearchResult(g)).join(""):'
    No matching maps, elections, features, people, parties, or sources found.
    ';return s.innerHTML='",this.bindFlatViewDelegates(s),this.hydrateLazyThumbnails(s),this.syncCatalogueSearchActionButtons(s),this.syncDownloadButtons(s),p}clearCatalogueSearchResults({render:e=!1}={}){this._catalogueSearchQuery="",this._catalogueSearchToken+=1;let t=document.getElementById("catalogueFlatView");t&&t.classList.remove("catalogue-flat-view--search"),e&&this.requestFlatViewRender({...this._lastMapListOptions||{}},{defer:this.isMobile})}async handleCatalogueSearchAction(e){let t=e.dataset.catalogueSearchAction,a=e.closest(".catalogue-search")||document;if((t==="load-map"||t==="toggle-map-load")&&e.dataset.mapId){e.disabled=!0;try{(this.onCheckMapLoaded?!!this.onCheckMapLoaded(e.dataset.mapId):!1)?await this.onMapUnload?.(e.dataset.mapId):await this.onMapLoad?.(e.dataset.mapId)}finally{e.disabled=!1,this.syncCatalogueSearchActionButtons(a)}return}if(t==="toggle-map-visibility"&&e.dataset.mapId){(this.onCheckMapLoaded?!!this.onCheckMapLoaded(e.dataset.mapId):!1)?this.onHideMap?.(e.dataset.mapId):await this.onMapLoad?.(e.dataset.mapId),this.syncCatalogueSearchActionButtons(a);return}if(t==="copy-map-url"&&e.dataset.mapId){this.copyMapUrl(e.dataset.mapId,e);return}if(t==="download-map"&&e.dataset.mapId){this.onDownloadFgb?.(e.dataset.mapId);return}if(t==="load-election"&&e.dataset.electionBody&&e.dataset.electionDate){e.disabled=!0;try{await this.onLoadElection?.(e.dataset.electionBody,e.dataset.electionDate)}finally{e.disabled=!1}return}if((t==="zoom-feature"||t==="toggle-feature-load")&&e.dataset.mapId){let{mapId:i,featureId:s}=this.getCatalogueSearchFeaturePayload(e),n=this.onCheckFeatureLoaded?!!this.onCheckFeatureLoaded(i,s):!1;e.disabled=!0;try{n?this.onPartialFeatureUnload?.(i,s):await this.loadFeatureFromSearchButton(e)}finally{e.disabled=!1,this.syncCatalogueSearchActionButtons(a)}return}if(t==="toggle-feature-visibility"&&e.dataset.mapId){let{mapId:i,featureId:s}=this.getCatalogueSearchFeaturePayload(e);(this.onCheckFeatureLoaded?!!this.onCheckFeatureLoaded(i,s):!1)?this.onPartialFeatureToggle?.(i,s):await this.loadFeatureFromSearchButton(e),this.syncCatalogueSearchActionButtons(a);return}if(t==="copy-feature-url"&&e.dataset.mapId){let{mapId:i,featureId:s,featureName:n}=this.getCatalogueSearchFeaturePayload(e),r=this.buildFeatureSearchShareUrl(i,s,n);r&&navigator.clipboard.writeText(r).then(()=>{let o=e.getAttribute("title");e.setAttribute("title","Copied!"),setTimeout(()=>e.setAttribute("title",o||"Copy feature URL"),1500),this.announce("Feature URL copied to clipboard")}).catch(o=>console.error("[UIController] Failed to copy feature URL:",o));return}if(t==="download-feature"&&e.dataset.mapId){let i=await this.loadFeatureFromSearchButton(e,{showInfo:!1});if(i?.feature){let s=this.cacheFeatureDetailEntry(P.getMapById(e.dataset.mapId),i.feature,i.feature.featureName||e.dataset.featureName,e.dataset.featureId);this.downloadFeature(s,"fgb")}this.syncCatalogueSearchActionButtons(a);return}if(t==="open-feature-detail"&&e.dataset.mapId){let i=await this.loadFeatureFromSearchButton(e,{showInfo:!1});if(i?.feature){let s=this.cacheFeatureDetailEntry(P.getMapById(e.dataset.mapId),i.feature,i.feature.featureName||e.dataset.featureName,e.dataset.featureId);this.showFeatureDetailInCatalogue(s,!0)}this.syncCatalogueSearchActionButtons(a)}}async handleFlatViewDelegatedClick(e){let t=e.target,a=t.closest?.("[data-catalogue-search-action]");if(a){e.preventDefault(),await this.handleCatalogueSearchAction(a);return}if(t.closest?.("[data-mobile-catalogue-full]")){e.preventDefault(),this._mobileCatalogueExpanded=!0,this.requestFlatViewRender({...this._lastMapListOptions||{},fullCatalogue:!0},{defer:!0});return}let s=t.closest?.("[data-book-view]");if(s){e.preventDefault(),this.openCatalogueBookViewer(s.dataset.bookView,s.dataset.bookFormat||"pdf");return}let n=t.closest?.(".catalogue-flat__toc-toplink--tab[data-tab-target]");if(n){e.preventDefault(),this.showTab(n.dataset.tabTarget),location.hash.startsWith("#flat-section-")&&history.replaceState(null,"",location.pathname+location.search),this._markActiveToplink(n),this.updateCatalogueNavButtons();return}let r=t.closest?.(".catalogue-flat__toc-link, .catalogue-flat__toc-toplink, .catalogue-flat__toc-subheading-link, .catalogue-flat__toc-decade-btn, .catalogue-flat__toc-map-btn");if(r){await this.handleFlatTocClick(e,r);return}let o=t.closest?.(".flat-election-by-toggle");if(o){e.preventDefault();let h=o.dataset.electionCardId||o.closest(".c1-card, .class-card, .map-card")?.dataset?.c1Id;if(!h)return;this._showByElectionCards.has(h)?this._showByElectionCards.delete(h):this._showByElectionCards.add(h),await this.requestFlatViewRender({...this._lastMapListOptions||{}},{defer:this.isMobile});let u=document.getElementById(`flat-card-${h}`);u&&this.scrollCatalogueTargetIntoView(u,{focus:!1});return}let l=t.closest?.(".class-card__placeholder-toggle");if(l){e.preventDefault();let h=l.closest(".c1-card, .class-card, .map-card");if(!h)return;let u=l.dataset.showing==="true",p=this._getCardPlaceholderKey(h);!u&&p?this._showPlaceholdersCards.add(p):p&&this._showPlaceholdersCards.delete(p),this._applyPlaceholderToggle(h,!u);return}let d=t.closest?.(".flat-election-link, .election-load-btn, .flat-election-entry");d&&await this.handleFlatElectionClick(e,d)}getCataloguePaneScroller(){return document.querySelector('.pane__content[data-tab-content="catalogue"]')||document.getElementById("catalogueListView")||document.querySelector(".pane--info")}async waitForCatalogueFrame(e=1){for(let t=0;trequestAnimationFrame(a))}async ensureCatalogueTargetRendered(e,t=null){let a=()=>document.getElementById(e),i=a(),s=!i,n=i?.dataset?.catalogueDeferredTarget==="1";if(!s&&!n)return i;if(this.singleSectionFlatCatalogue){let o=t||this._flatTargetToSection?.get?.(e)||null;if(!o)return i||null;this._flatActiveSectionKey=o,await this.requestFlatViewRender({...this._lastMapListOptions||{},flatSectionKey:o},{defer:this.isMobile});for(let l=0;l<12;l+=1)if(await this.waitForCatalogueFrame(1),i=a(),i&&i.dataset?.catalogueDeferredTarget!=="1")return i;return a()}return this.isMobile||n||s?(this._mobileCatalogueExpanded=!0,await this.requestFlatViewRender({...this._lastMapListOptions||{},fullCatalogue:!0},{defer:this.isMobile}),await this.waitForCatalogueFrame(2),a()):i||null}scrollCatalogueTargetIntoView(e,{focus:t=!0}={}){let a=this.getCataloguePaneScroller();if(!e||!a)return!1;let i=a.getBoundingClientRect(),s=e.getBoundingClientRect(),n=this._catalogueStickyHeight(a),r=Math.max(12,n+10),o=a.scrollTop+s.top-i.top-r,l=typeof window<"u"&&window.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches;return a.scrollTo({top:Math.max(0,o),behavior:this.isMobile||l?"auto":"smooth"}),t&&(e.setAttribute("tabindex","-1"),e.focus?.({preventScroll:!0})),!0}isCatalogueTargetVisible(e){let t=this.getCataloguePaneScroller();if(!e||!t)return!1;let a=t.getBoundingClientRect(),i=e.getBoundingClientRect(),s=this._catalogueStickyHeight(t);return i.top>=a.top+s&&i.top<=a.bottom-12}_catalogueStickyHeight(e){let t=e?.querySelector?.(".catalogue-sticky-shell"),a=e?.querySelector?.(".catalogue-flat__sections"),i=t?.getBoundingClientRect?.().height||0,s=a&&getComputedStyle(a).position==="sticky"?(a.getBoundingClientRect().height||0)+8:0;return i+s}_syncCatalogueShellHeight(){let e=this.getCataloguePaneScroller?.(),t=e?.querySelector?.(".catalogue-sticky-shell");if(!e||!t)return;let a=()=>{let i=Math.round(t.getBoundingClientRect().height);i>0&&e.style.setProperty("--catalogue-sticky-shell-height",`${i}px`)};a(),!this._catalogueShellResizeObserver&&typeof ResizeObserver=="function"&&(this._catalogueShellResizeObserver=new ResizeObserver(a),this._catalogueShellResizeObserver.observe(t))}_markActiveToplink(e){this._activeSectionTab=e?.dataset?.catalogueTarget||e?.dataset?.tabTarget||this._activeSectionTab,document.querySelectorAll(".catalogue-flat__toc-toplink").forEach(a=>{a===e?a.setAttribute("aria-current","true"):a.removeAttribute("aria-current")})}async handleFlatTocClick(e,t){e.preventDefault(),t.classList.contains("catalogue-flat__toc-toplink")&&this._markActiveToplink(t);let a=t.dataset.catalogueTarget||(t.getAttribute("href")||"").replace(/^#/,"");if(!a)return;let i=t.dataset.catalogueSection||this._flatTargetToSection?.get?.(a)||null,s=await this.ensureCatalogueTargetRendered(a,i);if(!s)return;let n=t.getAttribute("href")||"";n.startsWith("#")&&window.location.hash!==n&&history.pushState(null,"",n);for(let r=0;r<4;r+=1)if(this.scrollCatalogueTargetIntoView(s,{focus:r===0}),await this.waitForCatalogueFrame(r===0?2:1),s=document.getElementById(a),this.isCatalogueTargetVisible(s))return}async handleFlatElectionClick(e,t){if((t.closest(".flat-election-entry")||t)?.dataset?.electionPlaceholder==="1"){e.preventDefault(),e.stopPropagation();return}if(t.classList.contains("flat-election-entry")&&e.target.closest(".flat-election-link, .election-load-btn"))return;e.preventDefault(),e.stopPropagation();let i=document.getElementById("catalogueFlatView")||document,s=t.dataset.electionBody||t.closest(".flat-election-entry")?.dataset.electionBody,n=t.dataset.electionDate||t.closest(".flat-election-entry")?.dataset.electionDate;if(!s||!n)return;let r=[...i.querySelectorAll(".flat-election-entry")].filter(u=>u.dataset.electionBody===s&&u.dataset.electionDate===n),o=[...i.querySelectorAll(".election-load-btn")].filter(u=>u.dataset.electionBody===s&&u.dataset.electionDate===n);if(r.some(u=>u.classList.contains("flat-election-entry--loading")))return;if(t.classList.contains("election-load-btn")&&this.onCheckElectionLoaded?.(s,n)){this.onUnloadElection?.();return}let d=this.getCataloguePaneScroller(),h=d?.scrollTop??null;r.forEach(u=>{u.classList.add("flat-election-entry--loading"),u.setAttribute("aria-busy","true")}),o.forEach(u=>{u.disabled=!0,u.setAttribute("aria-busy","true"),u.dataset.previousTitle=u.getAttribute("title")||"",u.setAttribute("title","Loading")});try{await this.onLoadElection?.(s,n)}finally{d&&h!==null&&requestAnimationFrame(()=>{d.scrollTop=h}),r.forEach(u=>{u.classList.remove("flat-election-entry--loading"),u.removeAttribute("aria-busy")}),o.forEach(u=>{u.disabled=!1,u.removeAttribute("aria-busy"),u.dataset.previousTitle!==void 0&&(u.setAttribute("title",u.dataset.previousTitle),delete u.dataset.previousTitle)})}}handleFlatThumbnailMouseEnter(e){if(this.isMobile)return;let t=e.target.closest(".catalogue-flat__toc-thumbwrap");if(!t||t.classList.contains("catalogue-flat__toc-thumbwrap--missing"))return;let a=t.querySelector(".catalogue-flat__toc-thumbzoom");if(!a)return;this.loadLazyThumbnailImage(a.querySelector("img[data-thumbnail-src]"));let i=t.getBoundingClientRect(),s=i.right+8,n=i.top+i.height/2-60;s+128>window.innerWidth&&(s=i.left-128),n<4&&(n=4),n+128>window.innerHeight&&(n=window.innerHeight-128),a.style.left=s+"px",a.style.top=n+"px",a.classList.add("catalogue-flat__toc-thumbzoom--visible")}handleFlatThumbnailMouseLeave(e){let t=e.target.closest(".catalogue-flat__toc-thumbwrap");if(!t)return;let a=t.querySelector(".catalogue-flat__toc-thumbzoom");a&&a.classList.remove("catalogue-flat__toc-thumbzoom--visible")}syncMapCatalogueState(e={}){this._lastMapListOptions={...this._lastMapListOptions||{},...e||{}};let t=document.getElementById("catalogueFlatView")||document,a=new Set(e.visibleIds||this._lastMapListOptions.visibleIds||[]),i=(s,n)=>{if(typeof this.onCheckMapVisible=="function")try{return!!this.onCheckMapVisible(s)}catch{}return n&&a.has(s)};t.querySelectorAll("[data-map-id]").forEach(s=>{let n=s.dataset.mapId;if(!n)return;let r=this.isMapLoadedState(n,this._lastMapListOptions),o=i(n,r);s.classList.toggle("class-member--loaded",r&&s.classList.contains("class-member")),s.classList.toggle("c1-grid-entry--loaded",r&&s.classList.contains("c1-grid-entry")),s.classList.toggle("variant-item--loaded",r&&s.classList.contains("variant-item")),s.classList.toggle("map-card--active",r&&s.classList.contains("map-card")),s.classList.contains("catalogue-detail")&&s.classList.toggle("catalogue-detail--loaded",r)}),t.querySelectorAll(".load-btn[data-map-id], .c1-load-btn[data-map-id]").forEach(s=>{let n=s.dataset.mapId,r=this.isMapLoadedState(n,this._lastMapListOptions),o=this.isLoadTogglePending(n);s.innerHTML=this.getLoadButtonIcon(r,o),s.classList.toggle("load-btn--busy",o),s.disabled=o,o?s.setAttribute("aria-busy","true"):s.removeAttribute("aria-busy"),s.title=o?r?"Unloading...":"Loading...":r?"Unload":"Load"}),t.querySelectorAll(".visibility-btn[data-map-id]").forEach(s=>{let n=s.dataset.mapId,r=this.isMapLoadedState(n,this._lastMapListOptions),o=i(n,r);s.innerHTML=this.getVisibilityButtonIcon(o),s.title=o?"Hide":"Show",s.disabled=!r})}renderMapList(e,t={}){this._lastMapListOptions=t||{};let a=document.getElementById("mapList");if(this.invalidateFlatView({render:!1}),this._catalogueViewMode==="flat"&&this.requestFlatViewRender(this._lastMapListOptions,{defer:this.isMobile}),this.updateFilterStats(t.shownMaps??e.length,t.totalMaps||e.length),!a)return;let i=new Map;a.querySelectorAll(".map-card--class").forEach(y=>{let b=y.dataset.classId,v=y.querySelector(".timeline-slider");b&&v&&i.set(b,v.value)}),a.querySelectorAll(".c1-card").forEach(y=>{let b=y.dataset.c1Id,v=y.querySelector(".timeline-slider");b&&v&&i.set(`c1:${b}`,v.value)}),a.querySelectorAll(".conjoined-class-group").forEach(y=>{let b=y.dataset.groupId,v=y.querySelector(".timeline-slider");b&&v&&i.set(`group:${b}`,v.value)});let s=new Set;if(a.querySelectorAll(".category-more-maps--expanded").forEach(y=>{y.dataset.categoryId&&s.add(y.dataset.categoryId)}),a.innerHTML="",this.focusedCardIndex=-1,this._savedSliderValues=i,this.invalidateFlatView({render:!1}),e.length===0){a.innerHTML='

    No maps found

    ',this.updateFilterStats(0,t.totalMaps||0);return}let n=P.getAllClasses()||[],r=P.getClasses()||[],o=P.getC1s()||[],l=new Map,d=new Map;n.forEach(y=>{(y.maps||[]).forEach(b=>l.set(b,y))}),r.forEach(y=>{let b=y.category||"other";d.has(b)||d.set(b,[]),d.get(b).push(y)});let h=P.getMapCategories()||[],u=new Map;e.forEach(y=>{let b=y.category||"other";u.has(b)||u.set(b,[]),u.get(b).push(y)});let p=new Set,f=["Communities","History","Elections and Government","Public Services","Physical Geography","Built Environment"],g=new Map;if(f.forEach(y=>g.set(y,[])),h.forEach(y=>{let b=y.group||"Built Environment";g.has(b)||g.set(b,[]),g.get(b).push(y)}),f.forEach(y=>{let b=g.get(y)||[];if(b.length===0||!b.some(S=>{let E=u.get(S.id);return E&&E.length>0}))return;let w=document.createElement("div");w.className="map-list__group-heading",w.innerHTML=`${this.escapeHtml(y)}`,a.appendChild(w),b.forEach(S=>{let E=u.get(S.id);if(!E||E.length===0)return;let C=document.createElement("div");C.className="category-section",C.dataset.categoryId=S.id,a.appendChild(C);let T=o.filter(x=>x.category===S.id),z=d.get(S.id)||[],O=new Set;T.forEach(x=>{this.getC1ClassIds(x).forEach(B=>O.add(B))}),T.forEach(x=>{let B=this.createC1Card(x,t);C.appendChild(B);let H=`c1:${x.id}`;if(this._savedSliderValues.has(H)){let M=B.querySelector(".timeline-slider"),k=B.querySelectorAll(".timeline-labels span");M&&(M.value=this._savedSliderValues.get(H),k.forEach((N,V)=>N.classList.toggle("active",V===parseInt(M.value))))}this.getC1ClassIds(x).forEach(M=>p.add(M))});let I=new Map;if(z.forEach(x=>{O.has(x.id)||x.conjoinedTo&&(I.has(x.conjoinedTo)||I.set(x.conjoinedTo,[]),I.get(x.conjoinedTo).push(x))}),z.forEach(x=>{if(p.has(x.id)||O.has(x.id)||x.conjoinedTo)return;let B=I.get(x.id)||[];if(B.length>0){let H=this.createConjoinedClassGroup(B,x,t);C.appendChild(H);let k=`group:${H.dataset.groupId}`;if(this._savedSliderValues.has(k)){let N=H.querySelector(".timeline-slider"),V=H.querySelectorAll(".timeline-labels span");N&&(N.value=this._savedSliderValues.get(k),V.forEach((K,G)=>K.classList.toggle("active",G===parseInt(N.value))))}p.add(x.id),B.forEach(N=>p.add(N.id))}else{let H=this.createClassCard(x,t);if(C.appendChild(H),this._savedSliderValues.has(x.id)){let M=H.querySelector(".timeline-slider"),k=H.querySelectorAll(".timeline-labels span");M&&(M.value=this._savedSliderValues.get(x.id),k.forEach((N,V)=>N.classList.toggle("active",V===parseInt(M.value))))}p.add(x.id)}}),E&&E.filter(x=>x.featured&&!x.hidden&&!l.has(x.id)).forEach(x=>{let B=this.createMapCard(x,t);C.appendChild(B)}),S.id==="regional-divides"){E&&E.filter(x=>!x.featured&&!x.hidden&&!l.has(x.id)).forEach(x=>{let B=this.createMapCard(x,t);C.appendChild(B)});return}if(E){let x=E.filter(B=>!B.featured&&!B.hidden&&!l.has(B.id));if(x.length>0)if(this.showAllMaps)x.forEach(B=>{let H=this.createMapCard(B,t);C.appendChild(H)});else{let B=document.createElement("div");B.className="category-more-maps category-more-maps--collapsed",B.dataset.categoryId=S.id,x.forEach(k=>{let N=this.createMapCard(k,t);B.appendChild(N)});let H=s.has(S.id);H&&(B.classList.remove("category-more-maps--collapsed"),B.classList.add("category-more-maps--expanded")),C.appendChild(B);let M=document.createElement("button");M.className="category-more-toggle"+(H?" category-more-toggle--expanded":""),M.innerHTML=` ${H?"Show fewer maps":`Show ${x.length} more maps`} - `,E.addEventListener("click",()=>{let k=B.classList.toggle("category-more-maps--expanded");B.classList.toggle("category-more-maps--collapsed",!k),E.classList.toggle("category-more-toggle--expanded",k),E.querySelector(".category-more-toggle__text").textContent=k?"Show fewer maps":`Show ${x.length} more maps`}),C.appendChild(E)}}})}),this.booksData&&this.booksData.books&&this.booksData.books.length>0){let y=this.booksData.categories||[],b=new Map(y.map(w=>[w.id,w]));if((!this.searchQuery||this.booksData.books.some(w=>this._bookMatchesSearch(w,b.get(w.category||"other"),this.searchQuery)))&&(this.currentCategory===void 0||this.currentCategory==="all"||!this.currentCategory)){let w=document.createElement("div");w.className="category-group-header",w.innerHTML='

    Books & Documents

    ',a.appendChild(w);let S=new Map;this.booksData.books.forEach(M=>{let C=M.category||"other";S.has(C)||S.set(C,[]),S.get(C).push(M)}),y.forEach(M=>{let C=S.get(M.id);if(!C||C.length===0)return;let T=C;if(this.searchQuery&&(T=C.filter(z=>this._bookMatchesSearch(z,M,this.searchQuery)),T.length===0))return;let V=document.createElement("div");V.className="category-section",V.innerHTML=` + `,M.addEventListener("click",()=>{let k=B.classList.toggle("category-more-maps--expanded");B.classList.toggle("category-more-maps--collapsed",!k),M.classList.toggle("category-more-toggle--expanded",k),M.querySelector(".category-more-toggle__text").textContent=k?"Show fewer maps":`Show ${x.length} more maps`}),C.appendChild(M)}}})}),this.booksData&&this.booksData.books&&this.booksData.books.length>0){let y=this.booksData.categories||[],b=new Map(y.map(w=>[w.id,w]));if((!this.searchQuery||this.booksData.books.some(w=>this._bookMatchesSearch(w,b.get(w.category||"other"),this.searchQuery)))&&(this.currentCategory===void 0||this.currentCategory==="all"||!this.currentCategory)){let w=document.createElement("div");w.className="category-group-header",w.innerHTML=`

    ${Oe("book-open")}Books & Documents

    `,a.appendChild(w);let S=new Map;this.booksData.books.forEach(E=>{let C=E.category||"other";S.has(C)||S.set(C,[]),S.get(C).push(E)}),y.forEach(E=>{let C=S.get(E.id);if(!C||C.length===0)return;let T=C;if(this.searchQuery&&(T=C.filter(O=>this._bookMatchesSearch(O,E,this.searchQuery)),T.length===0))return;let z=document.createElement("div");z.className="category-section",z.innerHTML=`
    - ${M.icon||"[book]"} -

    ${this.escapeHtml(M.name)}

    + ${Ot(E)} +

    ${this.escapeHtml(E.name)}

    - `,T.forEach(z=>{let I=document.createElement("div");I.className="map-card book-card",I.innerHTML=this._buildBookCardHtml(z),V.appendChild(I)}),a.appendChild(V)})}}a.querySelectorAll("[data-book-view]").forEach(y=>{y.addEventListener("click",()=>{this.openCatalogueBookViewer(y.dataset.bookView,y.dataset.bookFormat||"pdf")})}),this.updateFilterStats(t.shownMaps??e.length,t.totalMaps||e.length)}updateFilterStats(e,t){let a=e===t?`${t.toLocaleString("en-GB")} maps`:`${e.toLocaleString("en-GB")} of ${t.toLocaleString("en-GB")} maps`;this._lastFilterStatsText=a;let i=document.getElementById("filterStats");i&&(i.textContent=a);let s=document.getElementById("catalogueTocStats");s&&(s.textContent=a)}setupCatalogueViewToggle(){let e=document.getElementById("catalogueViewToggle");e&&(e.querySelectorAll(".catalogue-view-toggle__btn").forEach(t=>{t.addEventListener("click",()=>{let a=t.dataset.view;this.setCatalogueViewMode(a)})}),e.classList.add("hidden"),this.setCatalogueViewMode("flat"))}setCatalogueViewMode(e){let t=document.getElementById("catalogueFlatView"),a=document.getElementById("catalogueViewToggle"),i=document.querySelector(".category-pills-container"),s=document.querySelector(".provider-pills-container");if(!t||!a)return;let n="flat",r=!0;a.querySelectorAll(".catalogue-view-toggle__btn").forEach(o=>{o.classList.toggle("catalogue-view-toggle__btn--active",o.dataset.view===n)}),r&&(t.classList.remove("hidden"),t.dataset.rendered||(this.shouldDeferMobileCatalogueRender()?this.renderDeferredMobileCatalogueShell():this.requestFlatViewRender(this._lastMapListOptions||{},{defer:this.isMobile}))),i&&i.classList.toggle("hidden",r),s&&s.classList.toggle("hidden",r),Ye("catalogue-view",n),this._catalogueViewMode=n,this.updateCatalogueHomeButton()}async renderFlatView(e={}){if(typeof window<"u"&&window.__civgraphTest2){let _=window.__civgraphTest2.flatRenders||(window.__civgraphTest2.flatRenders=[]);_.length<50&&_.push(String(new Error().stack||"").split(` -`).slice(1,7).join(" | "))}let t=document.getElementById("catalogueFlatView");if(!t){console.warn("[catalogue] renderFlatView: #catalogueFlatView is not in the DOM; nothing rendered.");return}if(this.shouldDeferMobileCatalogueRender()){this.renderDeferredMobileCatalogueShell();return}let a=Symbol("flat-render");if(this._flatRenderToken=a,await Promise.all([this.ensureThumbnailManifest(),this.ensureFeatureCountManifest()]),this._flatRenderToken!==a)return;let i=String(this._catalogueSearchQuery||document.getElementById("searchInput")?.value||"").trim();if(i){await this.renderCatalogueSearchResults(i);return}let s=!!this.singleSectionFlatCatalogue,n=s?e.flatSectionKey??this._flatActiveSectionKey??null:null;s&&(this._flatActiveSectionKey=n);let r=!s&&this.shouldUseBoundedMobileCatalogue(e);if(this._catalogueBookView){let _=P.getBookById(this._catalogueBookView.bookId);if(!_)this._catalogueBookView=null,this._applyCatalogueBookViewerChrome(!1);else{let R="";if(this._catalogueBookView.format==="markdown")try{R=await this._getBookMarkdownText(_)}catch(O){console.error("[UIController] Failed to load book markdown:",O),R="Failed to load Markdown file."}this._applyCatalogueBookViewerChrome(!0),t.classList.add("catalogue-flat-view--book-viewer"),t.innerHTML=this._renderCatalogueBookViewer(_,this._catalogueBookView.format,R),t.dataset.rendered="true",this.hydrateLazyThumbnails(t),t.querySelector("[data-book-view-close]")?.addEventListener("click",()=>{this.showCatalogueListView(!0)}),t.querySelectorAll("[data-book-view-format]").forEach(O=>{O.addEventListener("click",()=>{O.disabled||this.openCatalogueBookViewer(_.id,O.dataset.bookViewFormat||"pdf")})}),this.updateCatalogueHomeButton();return}}this._applyCatalogueBookViewerChrome(!1),t.classList.remove("catalogue-flat-view--book-viewer");let o=P.getAllClasses()||[],l=new Map(o.map(_=>[_.id,_])),d=new Map((P.maps?.maps||[]).map(_=>[_.id,_])),h=[{id:"flat-townlands",name:"Townlands",years:"",extent:"Ireland",mapIds:["all-ireland-townlands"]},{id:"flat-civil-parishes",name:"Civil Parishes",years:"",extent:"Ireland",classIds:["ireland-civil-parishes"],thumbMapId:"civil-parishes-by-province"},{id:"flat-baronies",name:"Baronies",years:"",extent:"Ireland",mapIds:["baronies-all-ireland"]},{id:"flat-counties",name:"Counties (Ireland)",years:"1899-1977",extent:"Ireland",classIds:["ni-counties"]},{id:"flat-provinces",name:"Provinces",years:"1899-1955",extent:"Ireland",classIds:["ireland-provinces"],mapIds:["tailte-province-boundaries-generalised-20m"]},{id:"flat-polities",name:"Polities",years:"",extent:"",mapIds:["ni-1921","roi-1938"]},{id:"flat-place-names",name:"Place Names (Northern Ireland)",years:"",extent:"Northern Ireland",mapIds:["place-names-gazetteer"]},{id:"flat-street-names",name:"Street Names (Northern Ireland)",years:"",extent:"Northern Ireland",mapIds:["streetnames-gazetteer"]},{id:"flat-tailte-physical",name:"Physical Features (Republic of Ireland, Tailte \xC9ireann)",years:"",extent:"Republic of Ireland",mapIds:["tailte-boundaries-seawater-area","tailte-boundaries-seawater-line","tailte-coast","tailte-high-water-mark","tailte-hydro-nodes","tailte-lakes-reservoirs","tailte-mountains","tailte-reservoirs","tailte-shore","tailte-vegetation-areas","tailte-water","tailte-watercourse-start-end-points","tailte-waterfalls","tailte-low-water-mark"]},{id:"flat-tailte-transport",name:"Transport Network (Republic of Ireland, Tailte \xC9ireann)",years:"",extent:"Republic of Ireland",mapIds:["tailte-airfield-area","tailte-airports","tailte-border-exits-entrances","tailte-ferry-crossing","tailte-main-harbours","tailte-motorway-access-exit-points","tailte-other-harbours","tailte-rail-network","tailte-railway-stations","tailte-road-rail-intersections","tailte-road-interchanges","tailte-road-intersections","tailte-roads","tailte-runways","tailte-ferry-station"]},{id:"flat-tailte-regions",name:"Regions & Boundaries (Republic of Ireland, Tailte \xC9ireann)",years:"",extent:"Republic of Ireland",mapIds:["tailte-rural-areas"]},{id:"flat-tailte-settlements",name:"Settlements & Names (Republic of Ireland, Tailte \xC9ireann)",years:"",extent:"Republic of Ireland",mapIds:["tailte-centres-of-population","tailte-geographical-names","tailte-settlements-generalised-20m"]},{id:"flat-tailte-built",name:"Heritage & Infrastructure (Republic of Ireland, Tailte \xC9ireann)",years:"",extent:"Republic of Ireland",mapIds:["tailte-heritage","tailte-power-plant"]},{id:"flat-tailte-hvd",name:"High Value Datasets (Republic of Ireland, Tailte \xC9ireann)",years:"",extent:"Republic of Ireland",mapIds:["tailte-hvd-rail-points","tailte-hvd-water-single-stream","tailte-hvd-locales","tailte-hvd-building-groups","tailte-hvd-rail-network-segment","tailte-hvd-way-points","tailte-hvd-way-gdf2","tailte-hvd-sites","tailte-hvd-cadastral-parcels-leasehold","tailte-hvd-water-points"]},{id:"flat-seas",name:"Seas (2023) (These islands)",years:"2023",extent:"These islands",mapIds:["britain-ireland-seas"]},{id:"flat-islands",name:"Islands",years:"",extent:"",mapIds:["ireland-island"]},{id:"flat-rivers",name:"Rivers (2016) (Northern Ireland)",years:"2016",extent:"Northern Ireland",mapIds:["rivers-2016"]},{id:"flat-lgds",name:"Local Government Districts (Northern Ireland) (1973-)",years:"1972-2022",extent:"Northern Ireland",classIds:["ni-lgds"]},{id:"flat-ireland-local-authorities-pre-partition",name:"Local Authorities (Ireland, pre-partition)",years:"1899-1920",extent:"Ireland",classIds:["ireland-local-authorities-pre-partition"]},{id:"flat-roi-local-authorities",name:"Local Authorities (Republic of Ireland)",years:"1921-2019",extent:"Republic of Ireland",classIds:["roi-local-authorities"]},{id:"flat-admin-counties",name:"Local Authorities (Northern Ireland) (1921)",years:"1921",extent:"Northern Ireland",classIds:["ni-admin-counties"]},{id:"flat-admin-areas",name:"Administrative Areas (Northern Ireland) (1920-1973)",years:"1921-1969",extent:"Northern Ireland",classIds:["ni-admin-areas"]},{id:"flat-elb",name:"Education and Library Boards (Northern Ireland)",years:"1984-1993",extent:"Northern Ireland",classIds:["ni-elb"]},{id:"flat-hsct",name:"Health and Social Care Trusts (Northern Ireland) (2007)",years:"2007",extent:"Northern Ireland",mapIds:["hsct-2007"]},{id:"flat-roi-garda-areas",name:"An Garda S\xEDoch\xE1na Areas (Republic of Ireland)",years:"2011",extent:"Republic of Ireland",classIds:["roi-garda-areas"]},{id:"flat-roi-gaeltacht",name:"Gaeltacht Areas (Republic of Ireland)",years:"1926-1982",extent:"Republic of Ireland",classIds:["roi-gaeltacht"],mapIds:["tailte-gaeltacht-boundaries-generalised-20m","tailte-gaeltacht-language-planning-area-boundaries-generalised-20m"]},{id:"flat-roi-lea",name:"Local Electoral Areas (Republic of Ireland)",years:"2008",extent:"Republic of Ireland",classIds:["roi-lea"]},{id:"flat-deas",name:"District Electoral Areas (1973-)",years:"1972-2012",extent:"Northern Ireland",classIds:["ni-deas"]},{id:"flat-county-eds",name:"County Electoral Divisions (Northern Ireland)",years:"1921-1969",extent:"Northern Ireland",classIds:["ni-county-eds"]},{id:"flat-dublin-electoral-counties",name:"Dublin Electoral Counties (1985)",years:"1985",extent:"Ireland",classIds:["roi-dublin-electoral-counties"]},{id:"flat-wards",name:"Wards (Northern Ireland) (1973-)",years:"1972-2022",extent:"Northern Ireland",classIds:["ni-wards"]},{id:"flat-deds",name:"District Electoral Divisions (Northern Ireland) (1920-1973)",years:"1912-1969",extent:"Northern Ireland",classIds:["ni-deds"]},{id:"flat-eds-pre-partition",name:"District Electoral Divisions/Wards (Ireland, pre-partition)",years:"1911-1919",extent:"Ireland",mapIds:["eds-1911","eds-1912","eds-1914","eds-1915","eds-1919-04-01"]},{id:"flat-roi-deds",name:"Electoral Divisions",years:"1921-2019",extent:"Republic of Ireland",mapIds:["eds-roi-1921-05-03","eds-roi-1931","eds-roi-1936","eds-roi-1941","eds-roi-1942","eds-roi-1943","eds-roi-1944","eds-roi-1946","eds-roi-1950","eds-roi-1953","eds-roi-1954","eds-roi-1955","eds-roi-1957","eds-roi-1965","eds-roi-1966","eds-roi-1970","eds-1971","eds-1977","eds-1980","eds-1983","eds-roi-1985","eds-1986","eds-1994","eds-1997","eds-2019"]},{id:"flat-nra",name:"Neighbourhood Renewal Areas (Northern Ireland)",years:"",extent:"Northern Ireland",mapIds:["nra"]},{id:"flat-eoni-polling",name:"EONI Polling Stations",years:"",extent:"Northern Ireland",mapIds:["eoni-polling-stations"]},{id:"flat-settlements",name:"Settlements",years:"2005-2015",extent:"Northern Ireland",classIds:["ni-settlements"]},{id:"flat-settlements-roi",name:"Settlements",years:"2011-2015",extent:"Republic of Ireland",classIds:["roi-settlements"]},{id:"flat-roi-legal-towns",name:"Legal Towns and Cities (Republic of Ireland)",years:"2011",extent:"Republic of Ireland",classIds:["roi-legal-towns"]},{id:"flat-tailte-builtup",name:"T\xC9 Built-Up Areas",years:"",extent:"Ireland",mapIds:["tailte-built-up-1m","tailte-built-up-points-250k"]},{id:"flat-cso-urban",name:"CSO Urban Areas (2022)",years:"2022",extent:"Republic of Ireland",mapIds:["cso-urban-areas-2022"]},{id:"flat-cso-eds",name:"CSO Electoral Divisions (Republic of Ireland) (2006-)",years:"2006-2022",extent:"Republic of Ireland",mapIds:["eds-2006","eds-2022"]},{id:"flat-small-census",name:"Small Census Units (Northern Ireland) (2001-present)",years:"2001-2021",extent:"Northern Ireland",classIds:["ni-small-census"]},{id:"flat-roi-small-census",name:"Small Census Units (Republic of Ireland)",years:"2011-2022",extent:"Republic of Ireland",classIds:["roi-small-census"]},{id:"flat-super-census",name:"Super Census Units (Northern Ireland) (2001-present)",years:"2001-2021",extent:"Northern Ireland",classIds:["ni-super-census"]},{id:"flat-ttwa",name:"Travel To Work Areas (Northern Ireland) (2007-present)",years:"2007-2011",extent:"Northern Ireland",classIds:["ni-ttwa"]},{id:"flat-census-grid",name:"Census Grid (2021) (Northern Ireland)",years:"2021",extent:"Northern Ireland",mapIds:["census-grid-2021"]},{id:"flat-nuts2",name:"NUTS 2 Regions (Ireland)",years:"2011",extent:"Ireland",mapIds:["nuts-2-all-ireland","nuts-2-roi","tailte-nuts2-boundaries-ungeneralised"]},{id:"flat-nuts3",name:"NUTS 3 Regions (2003) (Northern Ireland)",years:"2003",extent:"Northern Ireland",mapIds:["nuts-3","tailte-nuts3-boundaries-generalised-20m"]},{id:"flat-eu-parliament",name:"European Parliament Constituencies (1979-)",years:"1979-2024",extent:"Ireland",classIds:["eu-parliament"]},{id:"flat-uk-parliament",name:"UK Parliamentary Constituencies (1885-)",years:"1885-2023",extent:"Ireland / Northern Ireland",classIds:["pre-1921-pcs","ni-pcs"]},{id:"flat-dail",name:"D\xE1il \xC9ireann Constituencies (1923-)",years:"1923-2023",extent:"Republic of Ireland",classIds:["roi-dail"]},{id:"flat-ni-parliament",name:"Parliament of Northern Ireland Constituencies (1920-1973)",years:"1920-1969",extent:"Northern Ireland",classIds:["ni-parliament"]},{id:"flat-assembly-areas",name:"Assembly Areas (1998-)",years:"1995-2023",extent:"Northern Ireland",classIds:["ni-assembly"]},{id:"flat-assembly-1982",name:"Assembly Constituencies (1982)",years:"1982",extent:"Northern Ireland",classIds:["ni-assembly-1982"]},{id:"flat-con-conv",name:"Constitutional Convention Constituencies (1975)",years:"1975",extent:"Northern Ireland",classIds:["ni-constitutional-convention"]},{id:"flat-assembly-1973",name:"Assembly Constituencies (1973)",years:"1970",extent:"Northern Ireland",classIds:["ni-assembly-1973"]},{id:"flat-forum",name:"Forum Constituencies (1996)",years:"1995",extent:"Northern Ireland",classIds:["ni-forum"]},{id:"flat-referendum",name:"Referendum Counting Areas (1975-)",years:"1973-2016",extent:"Northern Ireland",classIds:["ni-referendum-areas"]},{id:"flat-data-2021-population",name:"Data - Census 2021: Usual resident population",years:"2021",extent:"Northern Ireland",mapIds:["data-2021-population-lgd","data-2021-population-dea","data-2021-population-ward","data-2021-population-settlement","data-2021-population-sdz","data-2021-population-dz"]},{id:"flat-data-2021-population-density",name:"Data - Census 2021: Population density",years:"2021",extent:"Northern Ireland",mapIds:["data-2021-population-density-lgd","data-2021-population-density-dea","data-2021-population-density-sdz","data-2021-population-density-dz"]},{id:"flat-data-2021-households",name:"Data - Census 2021: Total households",years:"2021",extent:"Northern Ireland",mapIds:["data-2021-households-lgd","data-2021-households-dea","data-2021-households-ward","data-2021-households-settlement","data-2021-households-sdz","data-2021-households-dz"]},{id:"flat-data-2021-household-size",name:"Data - Census 2021: Average household size",years:"2021",extent:"Northern Ireland",mapIds:["data-2021-household-size-lgd","data-2021-household-size-dea","data-2021-household-size-ward","data-2021-household-size-settlement","data-2021-household-size-sdz","data-2021-household-size-dz"]},{id:"flat-data-2021-female-share",name:"Data - Census 2021: Female population share",years:"2021",extent:"Northern Ireland",mapIds:["data-2021-female-share-lgd","data-2021-female-share-ward","data-2021-female-share-settlement"]},{id:"flat-data-2021-born-in-ni",name:"Data - Census 2021: Born in Northern Ireland",years:"2021",extent:"Northern Ireland",mapIds:["data-2021-born-in-ni-lgd","data-2021-born-in-ni-ward","data-2021-born-in-ni-settlement"]},{id:"flat-data-2021-irish-knowledge",name:"Data - Census 2021: Some ability in Irish",years:"2021",extent:"Northern Ireland",mapIds:["data-2021-irish-knowledge-lgd","data-2021-irish-knowledge-ward","data-2021-irish-knowledge-settlement"]},{id:"flat-data-2021-ulster-scots-knowledge",name:"Data - Census 2021: Some ability in Ulster-Scots",years:"2021",extent:"Northern Ireland",mapIds:["data-2021-ulster-scots-knowledge-lgd","data-2021-ulster-scots-knowledge-ward","data-2021-ulster-scots-knowledge-settlement"]},{id:"flat-data-2021-religion-catholic",name:"Data - Census 2021: Religion (% Catholic)",years:"2021",extent:"Northern Ireland",mapIds:["data-2021-religion-catholic-lgd","data-2021-religion-catholic-ward","data-2021-religion-catholic-settlement"]},{id:"flat-data-2021-catholic-background",name:"Data - Census 2021: Catholic community background",years:"2021",extent:"Northern Ireland",mapIds:["data-2021-catholic-background-lgd","data-2021-catholic-background-ward","data-2021-catholic-background-settlement"]},{id:"flat-data-2021-limiting-condition",name:"Data - Census 2021: Day-to-day activities limited",years:"2021",extent:"Northern Ireland",mapIds:["data-2021-limiting-condition-lgd","data-2021-limiting-condition-ward","data-2021-limiting-condition-settlement"]},{id:"flat-data-2021-unpaid-care",name:"Data - Census 2021: Provides unpaid care",years:"2021",extent:"Northern Ireland",mapIds:["data-2021-unpaid-care-lgd","data-2021-unpaid-care-ward","data-2021-unpaid-care-settlement"]},{id:"flat-data-2021-no-car",name:"Data - Census 2021: Households with no car or van",years:"2021",extent:"Northern Ireland",mapIds:["data-2021-no-car-lgd","data-2021-no-car-ward","data-2021-no-car-settlement"]},{id:"flat-data-2021-owner-occupied",name:"Data - Census 2021: Owner-occupied households",years:"2021",extent:"Northern Ireland",mapIds:["data-2021-owner-occupied-lgd","data-2021-owner-occupied-ward","data-2021-owner-occupied-settlement"]},{id:"flat-data-2021-social-rented",name:"Data - Census 2021: Social-rented households",years:"2021",extent:"Northern Ireland",mapIds:["data-2021-social-rented-lgd","data-2021-social-rented-ward","data-2021-social-rented-settlement"]},{id:"flat-data-2021-private-rented",name:"Data - Census 2021: Private-rented households",years:"2021",extent:"Northern Ireland",mapIds:["data-2021-private-rented-lgd","data-2021-private-rented-ward","data-2021-private-rented-settlement"]},{id:"flat-data-2021-no-quals",name:"Data - Census 2021: No qualifications",years:"2021",extent:"Northern Ireland",mapIds:["data-2021-no-quals-lgd","data-2021-no-quals-ward","data-2021-no-quals-settlement"]},{id:"flat-data-2021-level-4-plus",name:"Data - Census 2021: Level 4+ qualifications",years:"2021",extent:"Northern Ireland",mapIds:["data-2021-level-4-plus-lgd","data-2021-level-4-plus-ward","data-2021-level-4-plus-settlement"]},{id:"flat-data-2021-unemployed",name:"Data - Census 2021: Unemployed",years:"2021",extent:"Northern Ireland",mapIds:["data-2021-unemployed-lgd","data-2021-unemployed-ward","data-2021-unemployed-settlement"]},{id:"flat-data-2021-work-from-home",name:"Data - Census 2021: Work mainly at or from home",years:"2021",extent:"Northern Ireland",mapIds:["data-2021-work-from-home-lgd","data-2021-work-from-home-ward","data-2021-work-from-home-settlement"]},{id:"flat-historic-sites",name:"Historic Sites",years:"",extent:"Ireland",mapIds:["historic-bullaun-stones","historic-crannog","historic-ringfort-cashel","historic-ringfort-rath","historic-ringfort-unclassified","historic-rock-scribing","historic-standing-stones","historic-wedge-tomb"]},{id:"flat-catholic-parishes",name:"Catholic Parishes",years:"2011",extent:"Dublin",mapIds:["catholic-dublin-parishes"]},{id:"flat-catholic-dioceses",name:"Catholic Dioceses",years:"",extent:"Ireland",mapIds:["catholic-dioceses"]},{id:"flat-hed-heritage",name:"Heritage Sites",years:"",extent:"Northern Ireland",mapIds:["hed-listed-buildings","hed-scheduled-monument-areas","hed-sites-and-monuments","hed-defence-heritage","hed-industrial-heritage","ni-listed-buildings","ni-scheduled-monument-areas","ni-defence-heritage","ni-industrial-heritage"]},{id:"flat-glpr",name:"NI Government Land & Property Register (snapshots)",years:"2020-2023",extent:"Northern Ireland",mapIds:["glpr-2020-03","glpr-2021-03","glpr-2021-08","glpr-2021-09","glpr-2022-04","glpr-2023-04"]},{id:"flat-peacelines",name:"Peacelines (Northern Ireland)",years:"",extent:"Northern Ireland",mapIds:["peacelines"]},{id:"flat-roi-planning",name:"ROI National Planning Applications",years:"",extent:"Republic of Ireland",mapIds:["roi-national-planning-applications"]},{id:"flat-designated-sites",name:"Designated & Protected Sites (NIEA)",years:"",extent:"Northern Ireland",mapIds:["designated-aonb","designated-assi","designated-nnr","designated-ramsar","designated-sac","designated-spa","designated-whs","designated-lca"]},{id:"flat-hills-mountains-britain-ireland",name:"Britain and Ireland Hills and Mountains",years:"2026",extent:"Britain and Ireland",classIds:["dobih-britain-ireland-hills-and-mountains"],thumbMapId:"dobih-v18-4"},{id:"flat-hills-mountains-ireland",name:"Ireland Hills and Mountains",years:"2026",extent:"Ireland",classIds:["dobih-ireland-hills-and-mountains"],thumbMapId:"dobih-v18-4-arderins"},{id:"flat-hills-mountains-england-wales",name:"England and Wales Hills and Mountains",years:"2026",extent:"England and Wales",classIds:["dobih-england-wales-hills-and-mountains"],thumbMapId:"dobih-v18-4-nuttalls"},{id:"flat-hills-mountains-scotland",name:"Scotland Hills and Mountains",years:"2026",extent:"Scotland",classIds:["dobih-scotland-hills-and-mountains"],thumbMapId:"dobih-v18-4-munros"},{id:"flat-habitat-networks",name:"Habitat Networks (Ulster Wildlife)",years:"2020-2021",extent:"Northern Ireland",mapIds:["habitat-coastal-grouped","habitat-woodland-grouped","habitat-grassland-grouped","habitat-wetland-grouped","habitat-bog","habitat-deciduous-woodland","habitat-ancient-semi-natural-woodland","habitat-fen","habitat-heath","habitat-lake","habitat-pond","habitat-river","habitat-reedbed","habitat-acid-grassland","habitat-calcareous-grassland","habitat-lowland-meadow","habitat-purple-moor-grass","habitat-traditional-orchard","habitat-wood-pasture-parkland","habitat-coastal-sand-dune","habitat-coastal-saltmarsh","habitat-coastal-vegetated-shingle","habitat-maritime-cliff-slope","habitat-limestone-pavement"]},{id:"flat-niea-extra",name:"NIEA Catchments, Waste & Water Bodies",years:"2013-2021",extent:"Northern Ireland",mapIds:["niea-catchment-stakeholder-groups","niea-local-management-areas","niea-river-segments","niea-transitional-water-bodies","niea-landfill-sites-2013","niea-landfill-sites-2014","niea-landfill-sites-2015","niea-landfill-sites-2016","niea-landfill-sites-2017","niea-waste-sites-2021"]},{id:"flat-ni-mineral",name:"NI Mineral & Mining Licences",years:"",extent:"Northern Ireland",mapIds:["ni-mineral-prospecting-licences","ni-mining-leases"]},{id:"flat-ni-livestock",name:"NI Livestock Density (DAERA)",years:"",extent:"Northern Ireland",mapIds:["ni-livestock-bovine","ni-livestock-caprine","ni-livestock-ovine","ni-livestock-porcine","ni-livestock-poultry"]},{id:"flat-water-quality",name:"Water Quality and Hydrology",years:"",extent:"Northern Ireland",mapIds:["wq-surface-water-bodies-2015","wq-wfd-river-water-bodies","wq-wfd-monitoring-sites","wq-lake-water-bodies","wq-groundwater-bodies","wq-groundwater-dwpa","wq-surface-dwpa","wq-agricultural-critical-risk","wq-network-contribution","wq-river-quality-1990-2018","wq-aquatroll-realtime","wq-ni-water-drinking"]},{id:"flat-rwq-parameters",name:"River Water Quality 1990\u20132018 - by parameter",years:"1990-2018",extent:"Northern Ireland",mapIds:["wq-rwq-ph","wq-rwq-dissolved-oxygen","wq-rwq-biochemical-oxygen-demand","wq-rwq-ammonia","wq-rwq-nitrate","wq-rwq-nitrite","wq-rwq-dissolved-iron","wq-rwq-dissolved-copper","wq-rwq-dissolved-zinc","wq-rwq-suspended-solids","wq-rwq-conductivity","wq-rwq-alkalinity","wq-rwq-soluble-phosphorus"]},{id:"flat-rbd",name:"River Basin Districts (2016) (Northern Ireland)",years:"2016",extent:"Northern Ireland",mapIds:["river-basin-districts"]},{id:"flat-river-basins",name:"River Basins (2016) (Northern Ireland)",years:"2016",extent:"Northern Ireland",mapIds:["river-basins"]},{id:"flat-opw-flood",name:"OPW Flood Extents",years:"2018-2021",extent:"Ireland",mapIds:["opw-coastal-flood-extents-2021-current","opw-nifm-river-flood-extents-current","opw-fsu-catchments-gauged","rivers-coastal-flood-2018"]},{id:"flat-gsi",name:"Geological Survey Ireland - Bedrock & Karst",years:"",extent:"Republic of Ireland",mapIds:["gsi-bedrock-boreholes-50k","gsi-karst-data","gsi-groundwater-flooding-low","gsi-groundwater-flooding-medium"]},{id:"flat-gsni-bedrock",name:"GSNI Bedrock and Surface Geology",years:"",extent:"Northern Ireland",mapIds:["gsni-bedrock-geology-polygons-250k","gsni-bedrock-geology-lines-250k","gsni-superficial-geology-polygons-250k","gsni-mineral-resources","gsni-core-cuttings-register"]},{id:"flat-tellus-geochem",name:"Tellus Stream Sediments and Soils",years:"2005-2008",extent:"Northern Ireland",mapIds:["gsni-tellus-stream-sediments-xrf","gsni-tellus-stream-sediments-xrf-set2","gsni-tellus-stream-sediments-au-pge","gsni-tellus-stream-sediments-boron","gsni-tellus-stream-waters-icp","gsni-tellus-rural-soil-a-xrf","gsni-tellus-rural-soil-a-aqua-regia","gsni-tellus-rural-soil-s-aqua-regia","gsni-tellus-rural-soil-s-near-total","gsni-tellus-rural-soil-s-fire-assay"]},{id:"flat-tellus-airborne",name:"Tellus Airborne Geophysics",years:"2005-2008",extent:"Northern Ireland",mapIds:["tellus-mag-tmi","tellus-mag-rtp","tellus-mag-rtp-tilt","tellus-em-3khz","tellus-em-14khz","tellus-rad-k","tellus-rad-u","tellus-rad-th","tellus-rad-total","tellus-rad-ternary"]},{id:"flat-tellus-raw",name:"Tellus Airborne - raw flight-line data",years:"2005-2008",extent:"Northern Ireland",mapIds:["tellus-mag-raw","tellus-em-raw","tellus-rad-raw"]},{id:"flat-tellus-flightlines",name:"Tellus Airborne Survey - Flight Lines",years:"2005-2008",extent:"Northern Ireland",mapIds:["tellus-flight-tracks"]},{id:"flat-noise",name:"Environmental Noise (END 2017)",years:"2017",extent:"Northern Ireland",mapIds:["env-noise-agglomeration-lden","env-noise-major-roads-lden","env-noise-major-rail-lden"]},{id:"flat-copernicus-dem",name:"Copernicus 30m DEM (Ireland)",years:"",extent:"Ireland",mapIds:["copernicus-dem-30m-ireland"]},{id:"flat-secondary",name:"Secondary maps",years:"",extent:"",mapIds:["highlands-above-199m","highlands-without-settlements","west-bann-sperrins","east-west-bann","uninhabited-highlands","major-river-basins"]},{id:"flat-railways",name:"Railways",years:"",extent:"Northern Ireland",mapIds:["railways-network"]},{id:"flat-transport-lines",name:"Transport Lines (Roads and Railways)",years:"",extent:"Northern Ireland",mapIds:["transport-lines-road-rail"]},{id:"flat-dfi-pothole",name:"NI DfI Pothole Enquiries (2014-2021)",years:"2014-2021",extent:"Northern Ireland",mapIds:["dfi-pothole-enquiries-2014","dfi-pothole-enquiries-2015","dfi-pothole-enquiries-2016","dfi-pothole-enquiries-2017","dfi-pothole-enquiries-2018","dfi-pothole-enquiries-2019","dfi-pothole-enquiries-2020","dfi-pothole-enquiries-2021","roads-pothole-enquiries"]},{id:"flat-dfi-surface",name:"NI DfI Road Surface Defects (2008-2021)",years:"2008-2021",extent:"Northern Ireland",mapIds:["dfi-surface-defects-2008","dfi-surface-defects-2010","dfi-surface-defects-2011","dfi-surface-defects-2012","dfi-surface-defects-2013","dfi-surface-defects-2014","dfi-surface-defects-2015","dfi-surface-defects-2016","dfi-surface-defects-2017","dfi-surface-defects-2018","dfi-surface-defects-2019","dfi-surface-defects-2020","dfi-surface-defects-2021"]},{id:"flat-transport-defects",name:"Carriageway and Footway Surface Defects",years:"2021",extent:"Northern Ireland",mapIds:["transport-carriageway-defects-2021"]},{id:"flat-dfi-borders-crossings",name:"NI Border Crossings & Pedestrian Crossings (DfI)",years:"2018",extent:"Northern Ireland",mapIds:["dfi-border-crossings-2018-lines","dfi-border-crossings-2018-points","dfi-pedestrian-crossings","roads-border-crossings-2018","roads-pedestrian-crossings"]},{id:"flat-belfast-cycle",name:"Belfast Cycle Network",years:"",extent:"Northern Ireland",mapIds:["belfast-cycle-network"]},{id:"flat-translink",name:"Translink (NI Public Transport)",years:"2024",extent:"Northern Ireland",mapIds:["translink-bus-stops-2024","translink-metro-glider-routes","translink-rail-stations","translink-rail-halts","translink-rail-platforms","translink-rail-bridges","translink-rail-culverts","translink-rail-signal-posts","translink-ulsterbus-goldliner-routes"]},{id:"flat-tii",name:"TII Transport Infrastructure (ROI National Roads)",years:"2011-2016",extent:"Republic of Ireland",mapIds:["tii-national-road-network","tii-collision-rates-2011-2013","tii-collision-rates-2014-2016","tii-luas-stops","tii-marker-plates","tii-traffic-counter-locations","tii-wim-sensor-locations"]},{id:"flat-psni-collisions",name:"PSNI Collisions (2013-2018)",years:"2013-2018",extent:"Northern Ireland",mapIds:["psni-collisions-2013","psni-collisions-2014","psni-collisions-2015","psni-collisions-2016","psni-collisions-2017","psni-collisions-2018"]},{id:"flat-osni-coverage",name:"OSNI Map Sheet Coverage Grids and Benchmarks",years:"",extent:"Northern Ireland",mapIds:["osni-coverage-grid-10k","osni-coverage-grid-50k","osni-benchmarks"]},{id:"flat-osni-rasters",name:"OSNI Printed Raster Maps",years:"",extent:"Northern Ireland",mapIds:["osni-mid-scale-raster","osni-streetmaps","osni-eire-thuaidh","osni-1m-county-boundaries","osni-1m-infrastructure","osni-1m-locations","osni-1m-natural-environment","osni-1m-parliamentary"]},{id:"flat-osni-sixinch",name:"OSNI Historical Six-Inch Maps",years:"1829-1862",extent:"Northern Ireland",mapIds:["osni-sixinch-edition-1","osni-sixinch-edition-2"]},{id:"flat-dcc",name:"Dublin City Council - Open Data",years:"",extent:"Republic of Ireland",mapIds:["dcc-accessible-parking-spaces","dcc-adult-learning-centres","dcc-allotments-and-community-gardens","dcc-beaches","dcc-bike-parking-stands","dcc-bleeperbike","dcc-coach-parking","dcc-community-centres","dcc-dcc-public-bin-locations","dcc-dcc-public-cycle-parking-stands","dcc-development-plan-dcc-2022-2028","dcc-dublin-canvas-public-art","dcc-dublin-city-council-traffic-poles-with-cctv","dcc-dublin-city-council-variable-message-signs","dcc-dublin-city-libraries","dcc-dublin-fire-brigade-stations-dublin-region","dcc-dublin-metropolitan-area-existing-protected-cycle-infrastructure-2025","dcc-dublin-public-cycle-parking-facilities","dcc-dublinbikes-api","dcc-electoral-divisions","dcc-eligible-entities-for-wifi","dcc-enterprise-centres","dcc-fire-stations","dcc-galleries-exhibition-spaces-open-studios","dcc-garda-station","dcc-heritage-sites-historic-monuments-and-government-buildings","dcc-journey-times-across-dublin-city-from-dublin-city-council-traffic-departments-trips-system","dcc-local-authority-offices","dcc-moby-bikes","dcc-museums-and-archives","dcc-noise-maps-from-traffic-sources-in-dublin-city-council","dcc-parking-meters-location-tariffs-and-zones-in-dublin-city","dcc-parks-and-open-spaces","dcc-parks-gardens-and-public-spaces","dcc-pedestrian-and-cycle-counter-api-for-dublin-region","dcc-places-of-worship","dcc-public-artworks-in-dublin-city","dcc-public-toilets","dcc-record-protected-structures","dcc-skateboard-parks","dcc-sport-pitches-and-facilities","dcc-street-lighting-dublin-city","dcc-swimming-pools","dcc-theatres-arts-centres-performance-spaces","dcc-traffic-signal-sites-juctions","dcc-traffic-signals-and-scats-sites-locations","dcc-universities-and-colleges","dcc-wifi4eu-access-points"]},{id:"flat-dlr",name:"D\xFAn Laoghaire-Rathdown - Open Data",years:"",extent:"Republic of Ireland",mapIds:["dlr-access-points-to-main-parks","dlr-accessible-parking-bays","dlr-administrative-area","dlr-bicycle-counter-locations","dlr-bicycle-maintenance-stands","dlr-bicycle-parking-stands","dlr-boundary-plan-areas","dlr-bridges","dlr-burial-grounds","dlr-cherrywood-adapted-planning-scheme","dlr-coco-markets","dlr-core-bus-corridors","dlr-council-allotments","dlr-council-offices","dlr-derelict-sites-register","dlr-development-plans","dlr-dlr-arts-venues","dlr-dlr-decarbonising-zone","dlr-dlr-development-plan-2016-2022-zoning-objectives","dlr-dlr-public-lighting","dlr-dlr-residential-land-availability","dlr-dlr-river-and-bathing-water-sample-points","dlr-dlr-roads-schedule","dlr-dlr-unfinished-housing","dlr-ed-boundaries","dlr-existing-conservation-areas","dlr-golf-courses","dlr-industrial-heritage-survey-sites","dlr-institutional-lands","dlr-land-use-zoning","dlr-leisure-centres","dlr-libraries","dlr-main-parks","dlr-mews-development","dlr-muga","dlr-parking-meters","dlr-playgrounds","dlr-proposed-education-sites","dlr-protected-structures","dlr-public-art","dlr-public-ev-charging-points","dlr-public-toilets","dlr-record-of-monuments-and-place","dlr-right-of-way","dlr-sculpture-trail","dlr-skateboard-parks","dlr-spacefinder-app-locations","dlr-specific-local-objectives-point","dlr-specific-local-objectives-polygon","dlr-speed-signs","dlr-strategic-land-reserve","dlr-tennis-clubs","dlr-the-metals","dlr-transport","dlr-traveller-accommodation","dlr-tree-preservation-orders","dlr-trees-and-woodlands","dlr-trim-trails","dlr-views-prospects","dlr-wifi4eu-access-points"]},{id:"flat-sdcc",name:"South Dublin County Council - Open Data",years:"",extent:"Republic of Ireland",mapIds:["sdcc-bicycle-parking-stands","sdcc-monthly-river-quality-data-sdcc1"]},{id:"flat-fingal",name:"Fingal - Open Data",years:"",extent:"Republic of Ireland",mapIds:["fingal-polling-station-data","fingal-trees"]},{id:"flat-lidar-pointclouds",name:"LiDAR Point Clouds (3D)",years:"2019-2022",extent:"Northern Ireland",mapIds:["ni-lidar-a26-pointcloud","ni-lidar-newry-pointcloud","ni-lidar-york-street-pointcloud","ni-lidar-sept2022-northcoast-pointcloud","ni-lidar-march2022-northcoast-pointcloud"]},{id:"flat-ni-lidar-dem",name:"NI LiDAR Elevation Models (3D)",years:"2008-2021",extent:"Ireland",mapIds:["ireland-terrain-3d","ni-lidar-1m-3d","ni-lidar-armagh-dungannon-coalisland-3d","ni-lidar-ballycastle-3d","ni-lidar-ballyclare-3d","ni-lidar-ballygalley-3d","ni-lidar-ballygowan-3d","ni-lidar-ballymena-3d","ni-lidar-ballynahinch-3d","ni-lidar-ballynavally-3d","ni-lidar-banbridge-3d","ni-lidar-bangor-3d","ni-lidar-blackwater-3d","ni-lidar-bushmills-3d","ni-lidar-camowen-3d","ni-lidar-carrickfergus-3d","ni-lidar-carryduff-3d","ni-lidar-castlederg-3d","ni-lidar-castlereagh-3d","ni-lidar-clady-3d","ni-lidar-cloghmills-3d","ni-lidar-coleraine-portstewart-portrush-3d","ni-lidar-cookstown-3d","ni-lidar-cullybackey-3d","ni-lidar-cushendall-3d","ni-lidar-downpatrick-3d","ni-lidar-dunmurry-3d","ni-lidar-east-belfast-3d","ni-lidar-foyle-3d","ni-lidar-killyleagh-3d","ni-lidar-larne-3d","ni-lidar-limavady-3d","ni-lidar-lisburn-3d","ni-lidar-lowerbann-3d","ni-lidar-maghera-3d","ni-lidar-magherafelt-3d","ni-lidar-newcastle-3d","ni-lidar-newry-3d","ni-lidar-newtownabbey-3d","ni-lidar-newtownards-3d","ni-lidar-newtownstewart-3d","ni-lidar-omagh-3d","ni-lidar-portadown-3d","ni-lidar-randalstown-3d","ni-lidar-stonyford-3d","ni-lidar-strabane-3d","ni-lidar-tandragee-3d","ireland-terrain-3d-grey","ni-lidar-1m-3d-grey","ni-lidar-armagh-dungannon-coalisland-3d-grey","ni-lidar-ballycastle-3d-grey","ni-lidar-ballyclare-3d-grey","ni-lidar-ballygalley-3d-grey","ni-lidar-ballygowan-3d-grey","ni-lidar-ballymena-3d-grey","ni-lidar-ballynahinch-3d-grey","ni-lidar-ballynavally-3d-grey","ni-lidar-banbridge-3d-grey","ni-lidar-bangor-3d-grey","ni-lidar-blackwater-3d-grey","ni-lidar-bushmills-3d-grey","ni-lidar-camowen-3d-grey","ni-lidar-carrickfergus-3d-grey","ni-lidar-carryduff-3d-grey","ni-lidar-castlederg-3d-grey","ni-lidar-castlereagh-3d-grey","ni-lidar-clady-3d-grey","ni-lidar-cloghmills-3d-grey","ni-lidar-coleraine-portstewart-portrush-3d-grey","ni-lidar-cookstown-3d-grey","ni-lidar-cullybackey-3d-grey","ni-lidar-cushendall-3d-grey","ni-lidar-downpatrick-3d-grey","ni-lidar-dunmurry-3d-grey","ni-lidar-east-belfast-3d-grey","ni-lidar-foyle-3d-grey","ni-lidar-killyleagh-3d-grey","ni-lidar-larne-3d-grey","ni-lidar-limavady-3d-grey","ni-lidar-lisburn-3d-grey","ni-lidar-lowerbann-3d-grey","ni-lidar-maghera-3d-grey","ni-lidar-magherafelt-3d-grey","ni-lidar-newcastle-3d-grey","ni-lidar-newry-3d-grey","ni-lidar-newtownabbey-3d-grey","ni-lidar-newtownards-3d-grey","ni-lidar-newtownstewart-3d-grey","ni-lidar-omagh-3d-grey","ni-lidar-portadown-3d-grey","ni-lidar-randalstown-3d-grey","ni-lidar-stonyford-3d-grey","ni-lidar-strabane-3d-grey","ni-lidar-tandragee-3d-grey"]}],u=h.filter(_=>String(_.id||"").startsWith("flat-data-2021-"));if(u.length>0){let _=[],R=new Set;u.forEach(F=>{(F.mapIds||[]).forEach($=>{R.has($)||(R.add($),_.push($))})});let O=h.findIndex(F=>String(F.id||"").startsWith("flat-data-2021-"));for(let F=h.length-1;F>=0;F-=1)String(h[F]?.id||"").startsWith("flat-data-2021-")&&h.splice(F,1);h.splice(Math.max(0,O),0,{id:"flat-data-2021-census-data-ni",name:"Census Data",years:"2021",extent:"Northern Ireland",mapIds:_,thumbMapId:_[0]||"data-2021-population-lgd"})}let p=new Set;h.forEach(_=>{(_.mapIds||[]).forEach(R=>p.add(R)),(_.classIds||[]).forEach(R=>{((l.get(R)||{}).maps||[]).forEach(O=>p.add(O))})});let f=P.maps?.maps||[],g=new Set;f.forEach(_=>(_.variants||[]).forEach(R=>R.id&&g.add(R.id)));let y=new Map((P.maps?.categories||[]).map(_=>[_.id,_.name])),b=new Map;f.forEach(_=>{if(_.hidden||p.has(_.id)||g.has(_.id)||!(Object.keys(_.files||{}).length||(_.variants||[]).length||(_.members||[]).length||_.chunked))return;let O=_.category||"other";b.has(O)||b.set(O,[]),b.get(O).push(_.id)});let v=new Set(h.map(_=>String(_.name||"")));[...b.entries()].sort((_,R)=>R[1].length-_[1].length||String(_[0]).localeCompare(String(R[0]))).forEach(([_,R])=>{let O=R.map(X=>this.getYear(d.get(X)?.date)).filter(Boolean).map(Number).filter(Number.isFinite).sort((X,ae)=>X-ae),F=O.length?O[0]===O[O.length-1]?`${O[0]}`:`${O[0]}-${O[O.length-1]}`:"",$=y.get(_)||String(_);h.push({id:`flat-uncarded-${String(_).toLowerCase().replace(/[^a-z0-9]+/g,"-")}`,name:$,years:F,extent:v.has($)?"Further layers":"",mapIds:R})});let w=[{id:"flat-elections-2020s",name:"2020s",from:2020,to:2029},{id:"flat-elections-2010s",name:"2010s",from:2010,to:2019},{id:"flat-elections-2000s",name:"2000s",from:2e3,to:2009},{id:"flat-elections-1990s",name:"1990s",from:1990,to:1999},{id:"flat-elections-1980s",name:"1980s",from:1980,to:1989},{id:"flat-elections-1970s",name:"1970s",from:1970,to:1979},{id:"flat-elections-1960s",name:"1960s",from:1960,to:1969},{id:"flat-elections-1950s",name:"1950s",from:1950,to:1959},{id:"flat-elections-1940s",name:"1940s",from:1940,to:1949},{id:"flat-elections-1930s",name:"1930s",from:1930,to:1939},{id:"flat-elections-1920s",name:"1920s",from:1920,to:1929},{id:"flat-elections-1910s",name:"1910s",from:1910,to:1919},{id:"flat-elections-1900s",name:"1900s",from:1900,to:1909},{id:"flat-elections-1890s",name:"1890s",from:1890,to:1899},{id:"flat-elections-1880s",name:"1880s",from:1880,to:1889}],S=[];try{S=this.onBuildElectionCatalogueCards?await this.onBuildElectionCatalogueCards():[]}catch(_){console.error("[UI] Failed to build flat-view election cards:",_),S=[]}let M=(_,R,O=null)=>{let F=parseInt(String(R).slice(0,4),10)||0,$="pc-2008";return O==="local-government"?$="deas-2012":_==="House of Commons of the United Kingdom"?$=F>=2024?"pc-2023":F>=2005?"pc-2008":F>=1995?"pc-1995":F>=1983?"pc-1982":F>=1922?"pc-1970":F>=1918?"pc-1918":"pc-1885-ireland":_==="Northern Ireland Assembly"?$=F>=2007?"pc-2008":F>=1998?"pc-1995":"pc-1970":_==="Northern Ireland Constitutional Convention"?$="pc-1970":_==="Northern Ireland Forum for Political Dialogue"?$="pc-1995":_==="Parliament of Northern Ireland"?$="pc-1970":_==="European Parliament"?$="pc-2008":_==="European Parliament (Ireland)"?F>=2024?$="mep-2024":F>=2019?$="mep-2019":F>=2014?$="mep-2014":F>=2009?$="mep-2009":F>=2004?$="mep-2004":$="mep-1979":_==="D\xE1il \xC9ireann"||_==="Referendum (Ireland)"?F>=2024?$="dail-2023":F>=2016?$="dail-2017":F>=2011?$="dail-2013":F>=2007?$="dail-2009":F>=2002?$="dail-2005":F>=1997?$="dail-1998":F>=1992?$="dail-1995":F>=1987?$="dail-1990":F>=1981?$="dail-1983":F>=1977?$="dail-1980":F>=1973?$="dail-1974":F>=1965?$="dail-1969":F>=1957?$="dail-1961":F>=1937?$="dail-1947":F>=1923?$="dail-1935":$="pc-1918-ireland":_==="President of Ireland"&&(F>=2024?$="dail-2023":F>=2016?$="dail-2017":F>=2011?$="dail-2013":F>=2007?$="dail-2009":F>=2002?$="dail-2005":F>=1997?$="dail-1998":F>=1992?$="dail-1995":F>=1987?$="dail-1990":F>=1981?$="dail-1983":$="dail-1980"),{thumb:$,color:{"House of Commons of the United Kingdom":"#1e3a8a","Northern Ireland Assembly":"#2563eb","Northern Ireland Constitutional Convention":"#7c3aed","Northern Ireland Forum for Political Dialogue":"#0f766e","European Parliament":"#0ea5e9","local-government":"#b45309"}[O||_]||"#4b5563"}},C=w.map(_=>{let R=S.filter(F=>{let $=parseInt(String(F.date).slice(0,4),10);return Number.isFinite($)&&$>=_.from&&$<=_.to}).sort((F,$)=>String($.date).localeCompare(String(F.date))),O=R.some(F=>F.body==="D\xE1il \xC9ireann"||F.body==="President of Ireland"||F.body==="Referendum (Ireland)");return{id:_.id,name:_.name,years:`${_.from}-${_.to}`,extent:O?"Ireland":"Northern Ireland",electionEntries:R}}),T=_=>String(_||"").replace(/\s*\([^)]*\)/g,"").trim(),V=_=>{let R=[],O=new Set,F=new Set(_.id==="flat-settlements"?["settlements-2015-craigavon"]:[]);return(_.classIds||[]).forEach($=>{let X=l.get($);X&&(X.maps||[]).forEach(ae=>{if(O.has(ae)||F.has(ae))return;let Y=d.get(ae)||P.getMapById(ae);!Y||Y.hidden||(O.add(ae),R.push({map:Y,classId:_.id}))})}),(_.mapIds||[]).forEach($=>{if(O.has($)||F.has($))return;let X=d.get($)||P.getMapById($);!X||X.hidden||(O.add($),R.push({map:X,classId:_.id}))}),R.sort(($,X)=>(this.parseDateToTimestamp(X.map.date)||0)-(this.parseDateToTimestamp($.map.date)||0)),R},z=new Set,I=new Map,x=new Map,B=new Map,H=_=>String(_||"section").toLowerCase().normalize("NFKD").replace(/[\u0300-\u036f]/g,"").replace(/[^\w\s-]/g,"").replace(/\s+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")||"section",E=_=>`maps:${H(_)}`,k=(_,R=null)=>(_&&(z.add(_),R&&(I.set(_,R),x.has(R)||x.set(R,_))),_);k("flat-section-elections","elections"),k("flat-section-maps","maps-index"),k("flat-section-books","books");let N=` + `,T.forEach(O=>{let I=document.createElement("div");I.className="map-card book-card",I.innerHTML=this._buildBookCardHtml(O),z.appendChild(I)}),a.appendChild(z)})}}a.querySelectorAll("[data-book-view]").forEach(y=>{y.addEventListener("click",()=>{this.openCatalogueBookViewer(y.dataset.bookView,y.dataset.bookFormat||"pdf")})}),this.updateFilterStats(t.shownMaps??e.length,t.totalMaps||e.length)}updateFilterStats(e,t){let a=e===t?`${t.toLocaleString("en-GB")} maps`:`${e.toLocaleString("en-GB")} of ${t.toLocaleString("en-GB")} maps`;this._lastFilterStatsText=a;let i=document.getElementById("filterStats");i&&(i.textContent=a);let s=document.getElementById("catalogueTocStats");s&&(s.textContent=a)}setupCatalogueViewToggle(){let e=document.getElementById("catalogueViewToggle");e&&(e.querySelectorAll(".catalogue-view-toggle__btn").forEach(t=>{t.addEventListener("click",()=>{let a=t.dataset.view;this.setCatalogueViewMode(a)})}),e.classList.add("hidden"),this.setCatalogueViewMode("flat"))}setCatalogueViewMode(e){let t=document.getElementById("catalogueFlatView"),a=document.getElementById("catalogueViewToggle"),i=document.querySelector(".category-pills-container"),s=document.querySelector(".provider-pills-container");if(!t||!a)return;let n="flat",r=!0;a.querySelectorAll(".catalogue-view-toggle__btn").forEach(o=>{o.classList.toggle("catalogue-view-toggle__btn--active",o.dataset.view===n)}),r&&(t.classList.remove("hidden"),t.dataset.rendered||(this.shouldDeferMobileCatalogueRender()?this.renderDeferredMobileCatalogueShell():this.requestFlatViewRender(this._lastMapListOptions||{},{defer:this.isMobile}))),i&&i.classList.toggle("hidden",r),s&&s.classList.toggle("hidden",r),et("catalogue-view",n),this._catalogueViewMode=n,this.updateCatalogueHomeButton()}async renderFlatView(e={}){if(typeof window<"u"&&window.__civgraphTest2){let _=window.__civgraphTest2.flatRenders||(window.__civgraphTest2.flatRenders=[]);_.length<50&&_.push(String(new Error().stack||"").split(` +`).slice(1,7).join(" | "))}let t=document.getElementById("catalogueFlatView");if(!t){console.warn("[catalogue] renderFlatView: #catalogueFlatView is not in the DOM; nothing rendered.");return}if(this.shouldDeferMobileCatalogueRender()){this.renderDeferredMobileCatalogueShell();return}let a=Symbol("flat-render");if(this._flatRenderToken=a,await Promise.all([this.ensureThumbnailManifest(),this.ensureFeatureCountManifest()]),this._flatRenderToken!==a)return;let i=String(this._catalogueSearchQuery||document.getElementById("searchInput")?.value||"").trim();if(i){await this.renderCatalogueSearchResults(i);return}let s=!!this.singleSectionFlatCatalogue,n=s?e.flatSectionKey??this._flatActiveSectionKey??null:null;s&&(this._flatActiveSectionKey=n);let r=!s&&this.shouldUseBoundedMobileCatalogue(e);if(this._catalogueBookView){let _=P.getBookById(this._catalogueBookView.bookId);if(!_)this._catalogueBookView=null,this._applyCatalogueBookViewerChrome(!1);else{let R="";if(this._catalogueBookView.format==="markdown")try{R=await this._getBookMarkdownText(_)}catch(U){console.error("[UIController] Failed to load book markdown:",U),R="Failed to load Markdown file."}this._applyCatalogueBookViewerChrome(!0),t.classList.add("catalogue-flat-view--book-viewer"),t.innerHTML=this._renderCatalogueBookViewer(_,this._catalogueBookView.format,R),t.dataset.rendered="true",this.hydrateLazyThumbnails(t),t.querySelector("[data-book-view-close]")?.addEventListener("click",()=>{this.showCatalogueListView(!0)}),t.querySelectorAll("[data-book-view-format]").forEach(U=>{U.addEventListener("click",()=>{U.disabled||this.openCatalogueBookViewer(_.id,U.dataset.bookViewFormat||"pdf")})}),this.updateCatalogueHomeButton();return}}this._applyCatalogueBookViewerChrome(!1),t.classList.remove("catalogue-flat-view--book-viewer");let o=P.getAllClasses()||[],l=new Map(o.map(_=>[_.id,_])),d=new Map((P.maps?.maps||[]).map(_=>[_.id,_])),h=[{id:"flat-townlands",name:"Townlands",years:"",extent:"Ireland",mapIds:["all-ireland-townlands"]},{id:"flat-civil-parishes",name:"Civil Parishes",years:"",extent:"Ireland",classIds:["ireland-civil-parishes"],thumbMapId:"civil-parishes-by-province"},{id:"flat-baronies",name:"Baronies",years:"",extent:"Ireland",mapIds:["baronies-all-ireland"]},{id:"flat-counties",name:"Counties (Ireland)",years:"1899-1977",extent:"Ireland",classIds:["ni-counties"]},{id:"flat-provinces",name:"Provinces",years:"1899-1955",extent:"Ireland",classIds:["ireland-provinces"],mapIds:["tailte-province-boundaries-generalised-20m"]},{id:"flat-polities",name:"Polities",years:"",extent:"",mapIds:["ni-1921","roi-1938"]},{id:"flat-place-names",name:"Place Names (Northern Ireland)",years:"",extent:"Northern Ireland",mapIds:["place-names-gazetteer"]},{id:"flat-street-names",name:"Street Names (Northern Ireland)",years:"",extent:"Northern Ireland",mapIds:["streetnames-gazetteer"]},{id:"flat-tailte-physical",name:"Physical Features (Republic of Ireland, Tailte \xC9ireann)",years:"",extent:"Republic of Ireland",mapIds:["tailte-boundaries-seawater-area","tailte-boundaries-seawater-line","tailte-coast","tailte-high-water-mark","tailte-hydro-nodes","tailte-lakes-reservoirs","tailte-mountains","tailte-reservoirs","tailte-shore","tailte-vegetation-areas","tailte-water","tailte-watercourse-start-end-points","tailte-waterfalls","tailte-low-water-mark"]},{id:"flat-tailte-transport",name:"Transport Network (Republic of Ireland, Tailte \xC9ireann)",years:"",extent:"Republic of Ireland",mapIds:["tailte-airfield-area","tailte-airports","tailte-border-exits-entrances","tailte-ferry-crossing","tailte-main-harbours","tailte-motorway-access-exit-points","tailte-other-harbours","tailte-rail-network","tailte-railway-stations","tailte-road-rail-intersections","tailte-road-interchanges","tailte-road-intersections","tailte-roads","tailte-runways","tailte-ferry-station"]},{id:"flat-tailte-regions",name:"Regions & Boundaries (Republic of Ireland, Tailte \xC9ireann)",years:"",extent:"Republic of Ireland",mapIds:["tailte-rural-areas"]},{id:"flat-tailte-settlements",name:"Settlements & Names (Republic of Ireland, Tailte \xC9ireann)",years:"",extent:"Republic of Ireland",mapIds:["tailte-centres-of-population","tailte-geographical-names","tailte-settlements-generalised-20m"]},{id:"flat-tailte-built",name:"Heritage & Infrastructure (Republic of Ireland, Tailte \xC9ireann)",years:"",extent:"Republic of Ireland",mapIds:["tailte-heritage","tailte-power-plant"]},{id:"flat-tailte-hvd",name:"High Value Datasets (Republic of Ireland, Tailte \xC9ireann)",years:"",extent:"Republic of Ireland",mapIds:["tailte-hvd-rail-points","tailte-hvd-water-single-stream","tailte-hvd-locales","tailte-hvd-building-groups","tailte-hvd-rail-network-segment","tailte-hvd-way-points","tailte-hvd-way-gdf2","tailte-hvd-sites","tailte-hvd-cadastral-parcels-leasehold","tailte-hvd-water-points"]},{id:"flat-seas",name:"Seas (2023) (These islands)",years:"2023",extent:"These islands",mapIds:["britain-ireland-seas"]},{id:"flat-islands",name:"Islands",years:"",extent:"",mapIds:["ireland-island"]},{id:"flat-rivers",name:"Rivers (2016) (Northern Ireland)",years:"2016",extent:"Northern Ireland",mapIds:["rivers-2016"]},{id:"flat-lgds",name:"Local Government Districts (Northern Ireland) (1973-)",years:"1972-2022",extent:"Northern Ireland",classIds:["ni-lgds"]},{id:"flat-ireland-local-authorities-pre-partition",name:"Local Authorities (Ireland, pre-partition)",years:"1899-1920",extent:"Ireland",classIds:["ireland-local-authorities-pre-partition"]},{id:"flat-roi-local-authorities",name:"Local Authorities (Republic of Ireland)",years:"1921-2019",extent:"Republic of Ireland",classIds:["roi-local-authorities"]},{id:"flat-admin-counties",name:"Local Authorities (Northern Ireland) (1921)",years:"1921",extent:"Northern Ireland",classIds:["ni-admin-counties"]},{id:"flat-admin-areas",name:"Administrative Areas (Northern Ireland) (1920-1973)",years:"1921-1969",extent:"Northern Ireland",classIds:["ni-admin-areas"]},{id:"flat-elb",name:"Education and Library Boards (Northern Ireland)",years:"1984-1993",extent:"Northern Ireland",classIds:["ni-elb"]},{id:"flat-hsct",name:"Health and Social Care Trusts (Northern Ireland) (2007)",years:"2007",extent:"Northern Ireland",mapIds:["hsct-2007"]},{id:"flat-roi-garda-areas",name:"An Garda S\xEDoch\xE1na Areas (Republic of Ireland)",years:"2011",extent:"Republic of Ireland",classIds:["roi-garda-areas"]},{id:"flat-roi-gaeltacht",name:"Gaeltacht Areas (Republic of Ireland)",years:"1926-1982",extent:"Republic of Ireland",classIds:["roi-gaeltacht"],mapIds:["tailte-gaeltacht-boundaries-generalised-20m","tailte-gaeltacht-language-planning-area-boundaries-generalised-20m"]},{id:"flat-roi-lea",name:"Local Electoral Areas (Republic of Ireland)",years:"2008",extent:"Republic of Ireland",classIds:["roi-lea"]},{id:"flat-deas",name:"District Electoral Areas (1973-)",years:"1972-2012",extent:"Northern Ireland",classIds:["ni-deas"]},{id:"flat-county-eds",name:"County Electoral Divisions (Northern Ireland)",years:"1921-1969",extent:"Northern Ireland",classIds:["ni-county-eds"]},{id:"flat-dublin-electoral-counties",name:"Dublin Electoral Counties (1985)",years:"1985",extent:"Ireland",classIds:["roi-dublin-electoral-counties"]},{id:"flat-wards",name:"Wards (Northern Ireland) (1973-)",years:"1972-2022",extent:"Northern Ireland",classIds:["ni-wards"]},{id:"flat-deds",name:"District Electoral Divisions (Northern Ireland) (1920-1973)",years:"1912-1969",extent:"Northern Ireland",classIds:["ni-deds"]},{id:"flat-eds-pre-partition",name:"District Electoral Divisions/Wards (Ireland, pre-partition)",years:"1911-1919",extent:"Ireland",mapIds:["eds-1911","eds-1912","eds-1914","eds-1915","eds-1919-04-01"]},{id:"flat-roi-deds",name:"Electoral Divisions",years:"1921-2019",extent:"Republic of Ireland",mapIds:["eds-roi-1921-05-03","eds-roi-1931","eds-roi-1936","eds-roi-1941","eds-roi-1942","eds-roi-1943","eds-roi-1944","eds-roi-1946","eds-roi-1950","eds-roi-1953","eds-roi-1954","eds-roi-1955","eds-roi-1957","eds-roi-1965","eds-roi-1966","eds-roi-1970","eds-1971","eds-1977","eds-1980","eds-1983","eds-roi-1985","eds-1986","eds-1994","eds-1997","eds-2019"]},{id:"flat-nra",name:"Neighbourhood Renewal Areas (Northern Ireland)",years:"",extent:"Northern Ireland",mapIds:["nra"]},{id:"flat-eoni-polling",name:"EONI Polling Stations",years:"",extent:"Northern Ireland",mapIds:["eoni-polling-stations"]},{id:"flat-settlements",name:"Settlements",years:"2005-2015",extent:"Northern Ireland",classIds:["ni-settlements"]},{id:"flat-settlements-roi",name:"Settlements",years:"2011-2015",extent:"Republic of Ireland",classIds:["roi-settlements"]},{id:"flat-roi-legal-towns",name:"Legal Towns and Cities (Republic of Ireland)",years:"2011",extent:"Republic of Ireland",classIds:["roi-legal-towns"]},{id:"flat-tailte-builtup",name:"T\xC9 Built-Up Areas",years:"",extent:"Ireland",mapIds:["tailte-built-up-1m","tailte-built-up-points-250k"]},{id:"flat-cso-urban",name:"CSO Urban Areas (2022)",years:"2022",extent:"Republic of Ireland",mapIds:["cso-urban-areas-2022"]},{id:"flat-cso-eds",name:"CSO Electoral Divisions (Republic of Ireland) (2006-)",years:"2006-2022",extent:"Republic of Ireland",mapIds:["eds-2006","eds-2022"]},{id:"flat-small-census",name:"Small Census Units (Northern Ireland) (2001-present)",years:"2001-2021",extent:"Northern Ireland",classIds:["ni-small-census"]},{id:"flat-roi-small-census",name:"Small Census Units (Republic of Ireland)",years:"2011-2022",extent:"Republic of Ireland",classIds:["roi-small-census"]},{id:"flat-super-census",name:"Super Census Units (Northern Ireland) (2001-present)",years:"2001-2021",extent:"Northern Ireland",classIds:["ni-super-census"]},{id:"flat-ttwa",name:"Travel To Work Areas (Northern Ireland) (2007-present)",years:"2007-2011",extent:"Northern Ireland",classIds:["ni-ttwa"]},{id:"flat-census-grid",name:"Census Grid (2021) (Northern Ireland)",years:"2021",extent:"Northern Ireland",mapIds:["census-grid-2021"]},{id:"flat-nuts2",name:"NUTS 2 Regions (Ireland)",years:"2011",extent:"Ireland",mapIds:["nuts-2-all-ireland","nuts-2-roi","tailte-nuts2-boundaries-ungeneralised"]},{id:"flat-nuts3",name:"NUTS 3 Regions (2003) (Northern Ireland)",years:"2003",extent:"Northern Ireland",mapIds:["nuts-3","tailte-nuts3-boundaries-generalised-20m"]},{id:"flat-eu-parliament",name:"European Parliament Constituencies (1979-)",years:"1979-2024",extent:"Ireland",classIds:["eu-parliament"]},{id:"flat-uk-parliament",name:"UK Parliamentary Constituencies (1885-)",years:"1885-2023",extent:"Ireland / Northern Ireland",classIds:["pre-1921-pcs","ni-pcs"]},{id:"flat-dail",name:"D\xE1il \xC9ireann Constituencies (1923-)",years:"1923-2023",extent:"Republic of Ireland",classIds:["roi-dail"]},{id:"flat-ni-parliament",name:"Parliament of Northern Ireland Constituencies (1920-1973)",years:"1920-1969",extent:"Northern Ireland",classIds:["ni-parliament"]},{id:"flat-assembly-areas",name:"Assembly Areas (1998-)",years:"1995-2023",extent:"Northern Ireland",classIds:["ni-assembly"]},{id:"flat-assembly-1982",name:"Assembly Constituencies (1982)",years:"1982",extent:"Northern Ireland",classIds:["ni-assembly-1982"]},{id:"flat-con-conv",name:"Constitutional Convention Constituencies (1975)",years:"1975",extent:"Northern Ireland",classIds:["ni-constitutional-convention"]},{id:"flat-assembly-1973",name:"Assembly Constituencies (1973)",years:"1970",extent:"Northern Ireland",classIds:["ni-assembly-1973"]},{id:"flat-forum",name:"Forum Constituencies (1996)",years:"1995",extent:"Northern Ireland",classIds:["ni-forum"]},{id:"flat-referendum",name:"Referendum Counting Areas (1975-)",years:"1973-2016",extent:"Northern Ireland",classIds:["ni-referendum-areas"]},{id:"flat-data-2021-population",name:"Data - Census 2021: Usual resident population",years:"2021",extent:"Northern Ireland",mapIds:["data-2021-population-lgd","data-2021-population-dea","data-2021-population-ward","data-2021-population-settlement","data-2021-population-sdz","data-2021-population-dz"]},{id:"flat-data-2021-population-density",name:"Data - Census 2021: Population density",years:"2021",extent:"Northern Ireland",mapIds:["data-2021-population-density-lgd","data-2021-population-density-dea","data-2021-population-density-sdz","data-2021-population-density-dz"]},{id:"flat-data-2021-households",name:"Data - Census 2021: Total households",years:"2021",extent:"Northern Ireland",mapIds:["data-2021-households-lgd","data-2021-households-dea","data-2021-households-ward","data-2021-households-settlement","data-2021-households-sdz","data-2021-households-dz"]},{id:"flat-data-2021-household-size",name:"Data - Census 2021: Average household size",years:"2021",extent:"Northern Ireland",mapIds:["data-2021-household-size-lgd","data-2021-household-size-dea","data-2021-household-size-ward","data-2021-household-size-settlement","data-2021-household-size-sdz","data-2021-household-size-dz"]},{id:"flat-data-2021-female-share",name:"Data - Census 2021: Female population share",years:"2021",extent:"Northern Ireland",mapIds:["data-2021-female-share-lgd","data-2021-female-share-ward","data-2021-female-share-settlement"]},{id:"flat-data-2021-born-in-ni",name:"Data - Census 2021: Born in Northern Ireland",years:"2021",extent:"Northern Ireland",mapIds:["data-2021-born-in-ni-lgd","data-2021-born-in-ni-ward","data-2021-born-in-ni-settlement"]},{id:"flat-data-2021-irish-knowledge",name:"Data - Census 2021: Some ability in Irish",years:"2021",extent:"Northern Ireland",mapIds:["data-2021-irish-knowledge-lgd","data-2021-irish-knowledge-ward","data-2021-irish-knowledge-settlement"]},{id:"flat-data-2021-ulster-scots-knowledge",name:"Data - Census 2021: Some ability in Ulster-Scots",years:"2021",extent:"Northern Ireland",mapIds:["data-2021-ulster-scots-knowledge-lgd","data-2021-ulster-scots-knowledge-ward","data-2021-ulster-scots-knowledge-settlement"]},{id:"flat-data-2021-religion-catholic",name:"Data - Census 2021: Religion (% Catholic)",years:"2021",extent:"Northern Ireland",mapIds:["data-2021-religion-catholic-lgd","data-2021-religion-catholic-ward","data-2021-religion-catholic-settlement"]},{id:"flat-data-2021-catholic-background",name:"Data - Census 2021: Catholic community background",years:"2021",extent:"Northern Ireland",mapIds:["data-2021-catholic-background-lgd","data-2021-catholic-background-ward","data-2021-catholic-background-settlement"]},{id:"flat-data-2021-limiting-condition",name:"Data - Census 2021: Day-to-day activities limited",years:"2021",extent:"Northern Ireland",mapIds:["data-2021-limiting-condition-lgd","data-2021-limiting-condition-ward","data-2021-limiting-condition-settlement"]},{id:"flat-data-2021-unpaid-care",name:"Data - Census 2021: Provides unpaid care",years:"2021",extent:"Northern Ireland",mapIds:["data-2021-unpaid-care-lgd","data-2021-unpaid-care-ward","data-2021-unpaid-care-settlement"]},{id:"flat-data-2021-no-car",name:"Data - Census 2021: Households with no car or van",years:"2021",extent:"Northern Ireland",mapIds:["data-2021-no-car-lgd","data-2021-no-car-ward","data-2021-no-car-settlement"]},{id:"flat-data-2021-owner-occupied",name:"Data - Census 2021: Owner-occupied households",years:"2021",extent:"Northern Ireland",mapIds:["data-2021-owner-occupied-lgd","data-2021-owner-occupied-ward","data-2021-owner-occupied-settlement"]},{id:"flat-data-2021-social-rented",name:"Data - Census 2021: Social-rented households",years:"2021",extent:"Northern Ireland",mapIds:["data-2021-social-rented-lgd","data-2021-social-rented-ward","data-2021-social-rented-settlement"]},{id:"flat-data-2021-private-rented",name:"Data - Census 2021: Private-rented households",years:"2021",extent:"Northern Ireland",mapIds:["data-2021-private-rented-lgd","data-2021-private-rented-ward","data-2021-private-rented-settlement"]},{id:"flat-data-2021-no-quals",name:"Data - Census 2021: No qualifications",years:"2021",extent:"Northern Ireland",mapIds:["data-2021-no-quals-lgd","data-2021-no-quals-ward","data-2021-no-quals-settlement"]},{id:"flat-data-2021-level-4-plus",name:"Data - Census 2021: Level 4+ qualifications",years:"2021",extent:"Northern Ireland",mapIds:["data-2021-level-4-plus-lgd","data-2021-level-4-plus-ward","data-2021-level-4-plus-settlement"]},{id:"flat-data-2021-unemployed",name:"Data - Census 2021: Unemployed",years:"2021",extent:"Northern Ireland",mapIds:["data-2021-unemployed-lgd","data-2021-unemployed-ward","data-2021-unemployed-settlement"]},{id:"flat-data-2021-work-from-home",name:"Data - Census 2021: Work mainly at or from home",years:"2021",extent:"Northern Ireland",mapIds:["data-2021-work-from-home-lgd","data-2021-work-from-home-ward","data-2021-work-from-home-settlement"]},{id:"flat-historic-sites",name:"Historic Sites",years:"",extent:"Ireland",mapIds:["historic-bullaun-stones","historic-crannog","historic-ringfort-cashel","historic-ringfort-rath","historic-ringfort-unclassified","historic-rock-scribing","historic-standing-stones","historic-wedge-tomb"]},{id:"flat-catholic-parishes",name:"Catholic Parishes",years:"2011",extent:"Dublin",mapIds:["catholic-dublin-parishes"]},{id:"flat-catholic-dioceses",name:"Catholic Dioceses",years:"",extent:"Ireland",mapIds:["catholic-dioceses"]},{id:"flat-hed-heritage",name:"Heritage Sites",years:"",extent:"Northern Ireland",mapIds:["hed-listed-buildings","hed-scheduled-monument-areas","hed-sites-and-monuments","hed-defence-heritage","hed-industrial-heritage","ni-listed-buildings","ni-scheduled-monument-areas","ni-defence-heritage","ni-industrial-heritage"]},{id:"flat-glpr",name:"NI Government Land & Property Register (snapshots)",years:"2020-2023",extent:"Northern Ireland",mapIds:["glpr-2020-03","glpr-2021-03","glpr-2021-08","glpr-2021-09","glpr-2022-04","glpr-2023-04"]},{id:"flat-peacelines",name:"Peacelines (Northern Ireland)",years:"",extent:"Northern Ireland",mapIds:["peacelines"]},{id:"flat-roi-planning",name:"ROI National Planning Applications",years:"",extent:"Republic of Ireland",mapIds:["roi-national-planning-applications"]},{id:"flat-designated-sites",name:"Designated & Protected Sites (NIEA)",years:"",extent:"Northern Ireland",mapIds:["designated-aonb","designated-assi","designated-nnr","designated-ramsar","designated-sac","designated-spa","designated-whs","designated-lca"]},{id:"flat-hills-mountains-britain-ireland",name:"Britain and Ireland Hills and Mountains",years:"2026",extent:"Britain and Ireland",classIds:["dobih-britain-ireland-hills-and-mountains"],thumbMapId:"dobih-v18-4"},{id:"flat-hills-mountains-ireland",name:"Ireland Hills and Mountains",years:"2026",extent:"Ireland",classIds:["dobih-ireland-hills-and-mountains"],thumbMapId:"dobih-v18-4-arderins"},{id:"flat-hills-mountains-england-wales",name:"England and Wales Hills and Mountains",years:"2026",extent:"England and Wales",classIds:["dobih-england-wales-hills-and-mountains"],thumbMapId:"dobih-v18-4-nuttalls"},{id:"flat-hills-mountains-scotland",name:"Scotland Hills and Mountains",years:"2026",extent:"Scotland",classIds:["dobih-scotland-hills-and-mountains"],thumbMapId:"dobih-v18-4-munros"},{id:"flat-habitat-networks",name:"Habitat Networks (Ulster Wildlife)",years:"2020-2021",extent:"Northern Ireland",mapIds:["habitat-coastal-grouped","habitat-woodland-grouped","habitat-grassland-grouped","habitat-wetland-grouped","habitat-bog","habitat-deciduous-woodland","habitat-ancient-semi-natural-woodland","habitat-fen","habitat-heath","habitat-lake","habitat-pond","habitat-river","habitat-reedbed","habitat-acid-grassland","habitat-calcareous-grassland","habitat-lowland-meadow","habitat-purple-moor-grass","habitat-traditional-orchard","habitat-wood-pasture-parkland","habitat-coastal-sand-dune","habitat-coastal-saltmarsh","habitat-coastal-vegetated-shingle","habitat-maritime-cliff-slope","habitat-limestone-pavement"]},{id:"flat-niea-extra",name:"NIEA Catchments, Waste & Water Bodies",years:"2013-2021",extent:"Northern Ireland",mapIds:["niea-catchment-stakeholder-groups","niea-local-management-areas","niea-river-segments","niea-transitional-water-bodies","niea-landfill-sites-2013","niea-landfill-sites-2014","niea-landfill-sites-2015","niea-landfill-sites-2016","niea-landfill-sites-2017","niea-waste-sites-2021"]},{id:"flat-ni-mineral",name:"NI Mineral & Mining Licences",years:"",extent:"Northern Ireland",mapIds:["ni-mineral-prospecting-licences","ni-mining-leases"]},{id:"flat-ni-livestock",name:"NI Livestock Density (DAERA)",years:"",extent:"Northern Ireland",mapIds:["ni-livestock-bovine","ni-livestock-caprine","ni-livestock-ovine","ni-livestock-porcine","ni-livestock-poultry"]},{id:"flat-water-quality",name:"Water Quality and Hydrology",years:"",extent:"Northern Ireland",mapIds:["wq-surface-water-bodies-2015","wq-wfd-river-water-bodies","wq-wfd-monitoring-sites","wq-lake-water-bodies","wq-groundwater-bodies","wq-groundwater-dwpa","wq-surface-dwpa","wq-agricultural-critical-risk","wq-network-contribution","wq-river-quality-1990-2018","wq-aquatroll-realtime","wq-ni-water-drinking"]},{id:"flat-rwq-parameters",name:"River Water Quality 1990\u20132018 - by parameter",years:"1990-2018",extent:"Northern Ireland",mapIds:["wq-rwq-ph","wq-rwq-dissolved-oxygen","wq-rwq-biochemical-oxygen-demand","wq-rwq-ammonia","wq-rwq-nitrate","wq-rwq-nitrite","wq-rwq-dissolved-iron","wq-rwq-dissolved-copper","wq-rwq-dissolved-zinc","wq-rwq-suspended-solids","wq-rwq-conductivity","wq-rwq-alkalinity","wq-rwq-soluble-phosphorus"]},{id:"flat-rbd",name:"River Basin Districts (2016) (Northern Ireland)",years:"2016",extent:"Northern Ireland",mapIds:["river-basin-districts"]},{id:"flat-river-basins",name:"River Basins (2016) (Northern Ireland)",years:"2016",extent:"Northern Ireland",mapIds:["river-basins"]},{id:"flat-opw-flood",name:"OPW Flood Extents",years:"2018-2021",extent:"Ireland",mapIds:["opw-coastal-flood-extents-2021-current","opw-nifm-river-flood-extents-current","opw-fsu-catchments-gauged","rivers-coastal-flood-2018"]},{id:"flat-gsi",name:"Geological Survey Ireland - Bedrock & Karst",years:"",extent:"Republic of Ireland",mapIds:["gsi-bedrock-boreholes-50k","gsi-karst-data","gsi-groundwater-flooding-low","gsi-groundwater-flooding-medium"]},{id:"flat-gsni-bedrock",name:"GSNI Bedrock and Surface Geology",years:"",extent:"Northern Ireland",mapIds:["gsni-bedrock-geology-polygons-250k","gsni-bedrock-geology-lines-250k","gsni-superficial-geology-polygons-250k","gsni-mineral-resources","gsni-core-cuttings-register"]},{id:"flat-tellus-geochem",name:"Tellus Stream Sediments and Soils",years:"2005-2008",extent:"Northern Ireland",mapIds:["gsni-tellus-stream-sediments-xrf","gsni-tellus-stream-sediments-xrf-set2","gsni-tellus-stream-sediments-au-pge","gsni-tellus-stream-sediments-boron","gsni-tellus-stream-waters-icp","gsni-tellus-rural-soil-a-xrf","gsni-tellus-rural-soil-a-aqua-regia","gsni-tellus-rural-soil-s-aqua-regia","gsni-tellus-rural-soil-s-near-total","gsni-tellus-rural-soil-s-fire-assay"]},{id:"flat-tellus-airborne",name:"Tellus Airborne Geophysics",years:"2005-2008",extent:"Northern Ireland",mapIds:["tellus-mag-tmi","tellus-mag-rtp","tellus-mag-rtp-tilt","tellus-em-3khz","tellus-em-14khz","tellus-rad-k","tellus-rad-u","tellus-rad-th","tellus-rad-total","tellus-rad-ternary"]},{id:"flat-tellus-raw",name:"Tellus Airborne - raw flight-line data",years:"2005-2008",extent:"Northern Ireland",mapIds:["tellus-mag-raw","tellus-em-raw","tellus-rad-raw"]},{id:"flat-tellus-flightlines",name:"Tellus Airborne Survey - Flight Lines",years:"2005-2008",extent:"Northern Ireland",mapIds:["tellus-flight-tracks"]},{id:"flat-noise",name:"Environmental Noise (END 2017)",years:"2017",extent:"Northern Ireland",mapIds:["env-noise-agglomeration-lden","env-noise-major-roads-lden","env-noise-major-rail-lden"]},{id:"flat-copernicus-dem",name:"Copernicus 30m DEM (Ireland)",years:"",extent:"Ireland",mapIds:["copernicus-dem-30m-ireland"]},{id:"flat-secondary",name:"Secondary maps",years:"",extent:"",mapIds:["highlands-above-199m","highlands-without-settlements","west-bann-sperrins","east-west-bann","uninhabited-highlands","major-river-basins"]},{id:"flat-railways",name:"Railways",years:"",extent:"Northern Ireland",mapIds:["railways-network"]},{id:"flat-transport-lines",name:"Transport Lines (Roads and Railways)",years:"",extent:"Northern Ireland",mapIds:["transport-lines-road-rail"]},{id:"flat-dfi-pothole",name:"NI DfI Pothole Enquiries (2014-2021)",years:"2014-2021",extent:"Northern Ireland",mapIds:["dfi-pothole-enquiries-2014","dfi-pothole-enquiries-2015","dfi-pothole-enquiries-2016","dfi-pothole-enquiries-2017","dfi-pothole-enquiries-2018","dfi-pothole-enquiries-2019","dfi-pothole-enquiries-2020","dfi-pothole-enquiries-2021","roads-pothole-enquiries"]},{id:"flat-dfi-surface",name:"NI DfI Road Surface Defects (2008-2021)",years:"2008-2021",extent:"Northern Ireland",mapIds:["dfi-surface-defects-2008","dfi-surface-defects-2010","dfi-surface-defects-2011","dfi-surface-defects-2012","dfi-surface-defects-2013","dfi-surface-defects-2014","dfi-surface-defects-2015","dfi-surface-defects-2016","dfi-surface-defects-2017","dfi-surface-defects-2018","dfi-surface-defects-2019","dfi-surface-defects-2020","dfi-surface-defects-2021"]},{id:"flat-transport-defects",name:"Carriageway and Footway Surface Defects",years:"2021",extent:"Northern Ireland",mapIds:["transport-carriageway-defects-2021"]},{id:"flat-dfi-borders-crossings",name:"NI Border Crossings & Pedestrian Crossings (DfI)",years:"2018",extent:"Northern Ireland",mapIds:["dfi-border-crossings-2018-lines","dfi-border-crossings-2018-points","dfi-pedestrian-crossings","roads-border-crossings-2018","roads-pedestrian-crossings"]},{id:"flat-belfast-cycle",name:"Belfast Cycle Network",years:"",extent:"Northern Ireland",mapIds:["belfast-cycle-network"]},{id:"flat-translink",name:"Translink (NI Public Transport)",years:"2024",extent:"Northern Ireland",mapIds:["translink-bus-stops-2024","translink-metro-glider-routes","translink-rail-stations","translink-rail-halts","translink-rail-platforms","translink-rail-bridges","translink-rail-culverts","translink-rail-signal-posts","translink-ulsterbus-goldliner-routes"]},{id:"flat-tii",name:"TII Transport Infrastructure (ROI National Roads)",years:"2011-2016",extent:"Republic of Ireland",mapIds:["tii-national-road-network","tii-collision-rates-2011-2013","tii-collision-rates-2014-2016","tii-luas-stops","tii-marker-plates","tii-traffic-counter-locations","tii-wim-sensor-locations"]},{id:"flat-psni-collisions",name:"PSNI Collisions (2013-2018)",years:"2013-2018",extent:"Northern Ireland",mapIds:["psni-collisions-2013","psni-collisions-2014","psni-collisions-2015","psni-collisions-2016","psni-collisions-2017","psni-collisions-2018"]},{id:"flat-osni-coverage",name:"OSNI Map Sheet Coverage Grids and Benchmarks",years:"",extent:"Northern Ireland",mapIds:["osni-coverage-grid-10k","osni-coverage-grid-50k","osni-benchmarks"]},{id:"flat-osni-rasters",name:"OSNI Printed Raster Maps",years:"",extent:"Northern Ireland",mapIds:["osni-mid-scale-raster","osni-streetmaps","osni-eire-thuaidh","osni-1m-county-boundaries","osni-1m-infrastructure","osni-1m-locations","osni-1m-natural-environment","osni-1m-parliamentary"]},{id:"flat-osni-sixinch",name:"OSNI Historical Six-Inch Maps",years:"1829-1862",extent:"Northern Ireland",mapIds:["osni-sixinch-edition-1","osni-sixinch-edition-2"]},{id:"flat-dcc",name:"Dublin City Council - Open Data",years:"",extent:"Republic of Ireland",mapIds:["dcc-accessible-parking-spaces","dcc-adult-learning-centres","dcc-allotments-and-community-gardens","dcc-beaches","dcc-bike-parking-stands","dcc-bleeperbike","dcc-coach-parking","dcc-community-centres","dcc-dcc-public-bin-locations","dcc-dcc-public-cycle-parking-stands","dcc-development-plan-dcc-2022-2028","dcc-dublin-canvas-public-art","dcc-dublin-city-council-traffic-poles-with-cctv","dcc-dublin-city-council-variable-message-signs","dcc-dublin-city-libraries","dcc-dublin-fire-brigade-stations-dublin-region","dcc-dublin-metropolitan-area-existing-protected-cycle-infrastructure-2025","dcc-dublin-public-cycle-parking-facilities","dcc-dublinbikes-api","dcc-electoral-divisions","dcc-eligible-entities-for-wifi","dcc-enterprise-centres","dcc-fire-stations","dcc-galleries-exhibition-spaces-open-studios","dcc-garda-station","dcc-heritage-sites-historic-monuments-and-government-buildings","dcc-journey-times-across-dublin-city-from-dublin-city-council-traffic-departments-trips-system","dcc-local-authority-offices","dcc-moby-bikes","dcc-museums-and-archives","dcc-noise-maps-from-traffic-sources-in-dublin-city-council","dcc-parking-meters-location-tariffs-and-zones-in-dublin-city","dcc-parks-and-open-spaces","dcc-parks-gardens-and-public-spaces","dcc-pedestrian-and-cycle-counter-api-for-dublin-region","dcc-places-of-worship","dcc-public-artworks-in-dublin-city","dcc-public-toilets","dcc-record-protected-structures","dcc-skateboard-parks","dcc-sport-pitches-and-facilities","dcc-street-lighting-dublin-city","dcc-swimming-pools","dcc-theatres-arts-centres-performance-spaces","dcc-traffic-signal-sites-juctions","dcc-traffic-signals-and-scats-sites-locations","dcc-universities-and-colleges","dcc-wifi4eu-access-points"]},{id:"flat-dlr",name:"D\xFAn Laoghaire-Rathdown - Open Data",years:"",extent:"Republic of Ireland",mapIds:["dlr-access-points-to-main-parks","dlr-accessible-parking-bays","dlr-administrative-area","dlr-bicycle-counter-locations","dlr-bicycle-maintenance-stands","dlr-bicycle-parking-stands","dlr-boundary-plan-areas","dlr-bridges","dlr-burial-grounds","dlr-cherrywood-adapted-planning-scheme","dlr-coco-markets","dlr-core-bus-corridors","dlr-council-allotments","dlr-council-offices","dlr-derelict-sites-register","dlr-development-plans","dlr-dlr-arts-venues","dlr-dlr-decarbonising-zone","dlr-dlr-development-plan-2016-2022-zoning-objectives","dlr-dlr-public-lighting","dlr-dlr-residential-land-availability","dlr-dlr-river-and-bathing-water-sample-points","dlr-dlr-roads-schedule","dlr-dlr-unfinished-housing","dlr-ed-boundaries","dlr-existing-conservation-areas","dlr-golf-courses","dlr-industrial-heritage-survey-sites","dlr-institutional-lands","dlr-land-use-zoning","dlr-leisure-centres","dlr-libraries","dlr-main-parks","dlr-mews-development","dlr-muga","dlr-parking-meters","dlr-playgrounds","dlr-proposed-education-sites","dlr-protected-structures","dlr-public-art","dlr-public-ev-charging-points","dlr-public-toilets","dlr-record-of-monuments-and-place","dlr-right-of-way","dlr-sculpture-trail","dlr-skateboard-parks","dlr-spacefinder-app-locations","dlr-specific-local-objectives-point","dlr-specific-local-objectives-polygon","dlr-speed-signs","dlr-strategic-land-reserve","dlr-tennis-clubs","dlr-the-metals","dlr-transport","dlr-traveller-accommodation","dlr-tree-preservation-orders","dlr-trees-and-woodlands","dlr-trim-trails","dlr-views-prospects","dlr-wifi4eu-access-points"]},{id:"flat-sdcc",name:"South Dublin County Council - Open Data",years:"",extent:"Republic of Ireland",mapIds:["sdcc-bicycle-parking-stands","sdcc-monthly-river-quality-data-sdcc1"]},{id:"flat-fingal",name:"Fingal - Open Data",years:"",extent:"Republic of Ireland",mapIds:["fingal-polling-station-data","fingal-trees"]},{id:"flat-lidar-pointclouds",name:"LiDAR Point Clouds (3D)",years:"2019-2022",extent:"Northern Ireland",mapIds:["ni-lidar-a26-pointcloud","ni-lidar-newry-pointcloud","ni-lidar-york-street-pointcloud","ni-lidar-sept2022-northcoast-pointcloud","ni-lidar-march2022-northcoast-pointcloud"]},{id:"flat-ni-lidar-dem",name:"NI LiDAR Elevation Models (3D)",years:"2008-2021",extent:"Ireland",mapIds:["ireland-terrain-3d","ni-lidar-1m-3d","ni-lidar-armagh-dungannon-coalisland-3d","ni-lidar-ballycastle-3d","ni-lidar-ballyclare-3d","ni-lidar-ballygalley-3d","ni-lidar-ballygowan-3d","ni-lidar-ballymena-3d","ni-lidar-ballynahinch-3d","ni-lidar-ballynavally-3d","ni-lidar-banbridge-3d","ni-lidar-bangor-3d","ni-lidar-blackwater-3d","ni-lidar-bushmills-3d","ni-lidar-camowen-3d","ni-lidar-carrickfergus-3d","ni-lidar-carryduff-3d","ni-lidar-castlederg-3d","ni-lidar-castlereagh-3d","ni-lidar-clady-3d","ni-lidar-cloghmills-3d","ni-lidar-coleraine-portstewart-portrush-3d","ni-lidar-cookstown-3d","ni-lidar-cullybackey-3d","ni-lidar-cushendall-3d","ni-lidar-downpatrick-3d","ni-lidar-dunmurry-3d","ni-lidar-east-belfast-3d","ni-lidar-foyle-3d","ni-lidar-killyleagh-3d","ni-lidar-larne-3d","ni-lidar-limavady-3d","ni-lidar-lisburn-3d","ni-lidar-lowerbann-3d","ni-lidar-maghera-3d","ni-lidar-magherafelt-3d","ni-lidar-newcastle-3d","ni-lidar-newry-3d","ni-lidar-newtownabbey-3d","ni-lidar-newtownards-3d","ni-lidar-newtownstewart-3d","ni-lidar-omagh-3d","ni-lidar-portadown-3d","ni-lidar-randalstown-3d","ni-lidar-stonyford-3d","ni-lidar-strabane-3d","ni-lidar-tandragee-3d","ireland-terrain-3d-grey","ni-lidar-1m-3d-grey","ni-lidar-armagh-dungannon-coalisland-3d-grey","ni-lidar-ballycastle-3d-grey","ni-lidar-ballyclare-3d-grey","ni-lidar-ballygalley-3d-grey","ni-lidar-ballygowan-3d-grey","ni-lidar-ballymena-3d-grey","ni-lidar-ballynahinch-3d-grey","ni-lidar-ballynavally-3d-grey","ni-lidar-banbridge-3d-grey","ni-lidar-bangor-3d-grey","ni-lidar-blackwater-3d-grey","ni-lidar-bushmills-3d-grey","ni-lidar-camowen-3d-grey","ni-lidar-carrickfergus-3d-grey","ni-lidar-carryduff-3d-grey","ni-lidar-castlederg-3d-grey","ni-lidar-castlereagh-3d-grey","ni-lidar-clady-3d-grey","ni-lidar-cloghmills-3d-grey","ni-lidar-coleraine-portstewart-portrush-3d-grey","ni-lidar-cookstown-3d-grey","ni-lidar-cullybackey-3d-grey","ni-lidar-cushendall-3d-grey","ni-lidar-downpatrick-3d-grey","ni-lidar-dunmurry-3d-grey","ni-lidar-east-belfast-3d-grey","ni-lidar-foyle-3d-grey","ni-lidar-killyleagh-3d-grey","ni-lidar-larne-3d-grey","ni-lidar-limavady-3d-grey","ni-lidar-lisburn-3d-grey","ni-lidar-lowerbann-3d-grey","ni-lidar-maghera-3d-grey","ni-lidar-magherafelt-3d-grey","ni-lidar-newcastle-3d-grey","ni-lidar-newry-3d-grey","ni-lidar-newtownabbey-3d-grey","ni-lidar-newtownards-3d-grey","ni-lidar-newtownstewart-3d-grey","ni-lidar-omagh-3d-grey","ni-lidar-portadown-3d-grey","ni-lidar-randalstown-3d-grey","ni-lidar-stonyford-3d-grey","ni-lidar-strabane-3d-grey","ni-lidar-tandragee-3d-grey"]}],u=h.filter(_=>String(_.id||"").startsWith("flat-data-2021-"));if(u.length>0){let _=[],R=new Set;u.forEach(F=>{(F.mapIds||[]).forEach($=>{R.has($)||(R.add($),_.push($))})});let U=h.findIndex(F=>String(F.id||"").startsWith("flat-data-2021-"));for(let F=h.length-1;F>=0;F-=1)String(h[F]?.id||"").startsWith("flat-data-2021-")&&h.splice(F,1);h.splice(Math.max(0,U),0,{id:"flat-data-2021-census-data-ni",name:"Census Data",years:"2021",extent:"Northern Ireland",mapIds:_,thumbMapId:_[0]||"data-2021-population-lgd"})}let p=new Set;h.forEach(_=>{(_.mapIds||[]).forEach(R=>p.add(R)),(_.classIds||[]).forEach(R=>{((l.get(R)||{}).maps||[]).forEach(U=>p.add(U))})});let f=P.maps?.maps||[],g=new Set;f.forEach(_=>(_.variants||[]).forEach(R=>R.id&&g.add(R.id)));let y=new Map((P.maps?.categories||[]).map(_=>[_.id,_.name])),b=new Map;f.forEach(_=>{if(_.hidden||p.has(_.id)||g.has(_.id)||!(Object.keys(_.files||{}).length||(_.variants||[]).length||(_.members||[]).length||_.chunked))return;let U=_.category||"other";b.has(U)||b.set(U,[]),b.get(U).push(_.id)});let v=new Set(h.map(_=>String(_.name||"")));[...b.entries()].sort((_,R)=>R[1].length-_[1].length||String(_[0]).localeCompare(String(R[0]))).forEach(([_,R])=>{let U=R.map(X=>this.getYear(d.get(X)?.date)).filter(Boolean).map(Number).filter(Number.isFinite).sort((X,ie)=>X-ie),F=U.length?U[0]===U[U.length-1]?`${U[0]}`:`${U[0]}-${U[U.length-1]}`:"",$=y.get(_)||String(_);h.push({id:`flat-uncarded-${String(_).toLowerCase().replace(/[^a-z0-9]+/g,"-")}`,name:$,years:F,extent:v.has($)?"Further layers":"",mapIds:R})});let w=[{id:"flat-elections-2020s",name:"2020s",from:2020,to:2029},{id:"flat-elections-2010s",name:"2010s",from:2010,to:2019},{id:"flat-elections-2000s",name:"2000s",from:2e3,to:2009},{id:"flat-elections-1990s",name:"1990s",from:1990,to:1999},{id:"flat-elections-1980s",name:"1980s",from:1980,to:1989},{id:"flat-elections-1970s",name:"1970s",from:1970,to:1979},{id:"flat-elections-1960s",name:"1960s",from:1960,to:1969},{id:"flat-elections-1950s",name:"1950s",from:1950,to:1959},{id:"flat-elections-1940s",name:"1940s",from:1940,to:1949},{id:"flat-elections-1930s",name:"1930s",from:1930,to:1939},{id:"flat-elections-1920s",name:"1920s",from:1920,to:1929},{id:"flat-elections-1910s",name:"1910s",from:1910,to:1919},{id:"flat-elections-1900s",name:"1900s",from:1900,to:1909},{id:"flat-elections-1890s",name:"1890s",from:1890,to:1899},{id:"flat-elections-1880s",name:"1880s",from:1880,to:1889}],S=[];try{S=this.onBuildElectionCatalogueCards?await this.onBuildElectionCatalogueCards():[]}catch(_){console.error("[UI] Failed to build flat-view election cards:",_),S=[]}let E=(_,R,U=null)=>{let F=parseInt(String(R).slice(0,4),10)||0,$="pc-2008";return U==="local-government"?$="deas-2012":_==="House of Commons of the United Kingdom"?$=F>=2024?"pc-2023":F>=2005?"pc-2008":F>=1995?"pc-1995":F>=1983?"pc-1982":F>=1922?"pc-1970":F>=1918?"pc-1918":"pc-1885-ireland":_==="Northern Ireland Assembly"?$=F>=2007?"pc-2008":F>=1998?"pc-1995":"pc-1970":_==="Northern Ireland Constitutional Convention"?$="pc-1970":_==="Northern Ireland Forum for Political Dialogue"?$="pc-1995":_==="Parliament of Northern Ireland"?$="pc-1970":_==="European Parliament"?$="pc-2008":_==="European Parliament (Ireland)"?F>=2024?$="mep-2024":F>=2019?$="mep-2019":F>=2014?$="mep-2014":F>=2009?$="mep-2009":F>=2004?$="mep-2004":$="mep-1979":_==="D\xE1il \xC9ireann"||_==="Referendum (Ireland)"?F>=2024?$="dail-2023":F>=2016?$="dail-2017":F>=2011?$="dail-2013":F>=2007?$="dail-2009":F>=2002?$="dail-2005":F>=1997?$="dail-1998":F>=1992?$="dail-1995":F>=1987?$="dail-1990":F>=1981?$="dail-1983":F>=1977?$="dail-1980":F>=1973?$="dail-1974":F>=1965?$="dail-1969":F>=1957?$="dail-1961":F>=1937?$="dail-1947":F>=1923?$="dail-1935":$="pc-1918-ireland":_==="President of Ireland"&&(F>=2024?$="dail-2023":F>=2016?$="dail-2017":F>=2011?$="dail-2013":F>=2007?$="dail-2009":F>=2002?$="dail-2005":F>=1997?$="dail-1998":F>=1992?$="dail-1995":F>=1987?$="dail-1990":F>=1981?$="dail-1983":$="dail-1980"),{thumb:$,color:{"House of Commons of the United Kingdom":"#1e3a8a","Northern Ireland Assembly":"#2563eb","Northern Ireland Constitutional Convention":"#7c3aed","Northern Ireland Forum for Political Dialogue":"#0f766e","European Parliament":"#0ea5e9","local-government":"#b45309"}[U||_]||"#4b5563"}},C=w.map(_=>{let R=S.filter(F=>{let $=parseInt(String(F.date).slice(0,4),10);return Number.isFinite($)&&$>=_.from&&$<=_.to}).sort((F,$)=>String($.date).localeCompare(String(F.date))),U=R.some(F=>F.body==="D\xE1il \xC9ireann"||F.body==="President of Ireland"||F.body==="Referendum (Ireland)");return{id:_.id,name:_.name,years:`${_.from}-${_.to}`,extent:U?"Ireland":"Northern Ireland",electionEntries:R}}),T=_=>String(_||"").replace(/\s*\([^)]*\)/g,"").trim(),z=_=>{let R=[],U=new Set,F=new Set(_.id==="flat-settlements"?["settlements-2015-craigavon"]:[]);return(_.classIds||[]).forEach($=>{let X=l.get($);X&&(X.maps||[]).forEach(ie=>{if(U.has(ie)||F.has(ie))return;let Y=d.get(ie)||P.getMapById(ie);!Y||Y.hidden||(U.add(ie),R.push({map:Y,classId:_.id}))})}),(_.mapIds||[]).forEach($=>{if(U.has($)||F.has($))return;let X=d.get($)||P.getMapById($);!X||X.hidden||(U.add($),R.push({map:X,classId:_.id}))}),R.sort(($,X)=>(this.parseDateToTimestamp(X.map.date)||0)-(this.parseDateToTimestamp($.map.date)||0)),R},O=new Set,I=new Map,x=new Map,B=new Map,H=_=>String(_||"section").toLowerCase().normalize("NFKD").replace(/[\u0300-\u036f]/g,"").replace(/[^\w\s-]/g,"").replace(/\s+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")||"section",M=_=>`maps:${H(_)}`,k=(_,R=null)=>(_&&(O.add(_),R&&(I.set(_,R),x.has(R)||x.set(R,_))),_);k("flat-section-elections","elections"),k("flat-section-maps","maps-index"),k("flat-section-books","books");let N={elections:Oe("vote"),maps:Oe("map"),books:Oe("book-open"),tables:Oe("table")},V=this._activeSectionTab||"flat-section-elections",K=_=>V===_?' aria-current="true"':"",G=` +
    - ",this._flatTocTargetIds=z,this._flatTargetToSection=I,this._flatSectionTargets=x,t.innerHTML=N+'
    ';let re=t.querySelector("#catalogueFlatCards"),Fe=e||{},Me=0,lt=_=>!s||n===_,ct=new Map(D.map(_=>[E(_.heading),_.heading])),Et=_=>{if(!s)return!0;let R=B.get(_.id)||`map:${_.id}`;return n===R},fe=_=>this.escapeHtml(_||"");if(lt("elections")){let _=document.createElement("div");_.id="flat-section-elections",_.className="catalogue-flat__anchor",re.appendChild(_);let R=C,O=r&&!s;O&&(R=this.includeMobileElectionCatalogue?C.slice(0,this._mobileInitialElectionCardLimit):[]);for(let F=0;FZ.isByElection),Y=this._showByElectionCards.has($.id),Se=($.electionEntries||[]).filter(Z=>!Z.isByElection||Y).map(Z=>{let Oe=M(Z.body,Z.date,Z.bodyGroup||null),da=_a(Z.body),zi=Z.displaySubtitle||(Z.isByElection?(Z.constituencies||[]).join(", "):Z.body==="European Parliament"&&(Z.constituencies||[]).filter(kt=>kt!=="Northern Ireland").length===0?"Northern Ireland":`${(Z.constituencies||[]).filter(kt=>kt!=="Northern Ireland").length} constituencies`),Vi=Z.displayProvider||da,Ui=Z.placeholder?" class-member--placeholder":"",Mt=!Z.placeholder&&!!this.onCheckElectionLoaded?.(Z.body,Z.date),qi=Mt?" class-member--loaded":"",ua=fe(Z.displayTitle||Vi||da),ha=Z.date?fe(be(Z.date)):"",pa=ha?`${ha} - ${ua}`:`${ua}`,Gi=Z.placeholder?`${pa}`:`${pa}`,ji=Z.placeholder?"":``,Wi=Z.placeholder?'To Be Added':"";return` -
    `,Ve.add(U),(ye.get(U)?.members||[]).forEach(Y=>{let pe=J.get(`${U}::${Y}`);if(pe&&pe.mergedIds.every(ce=>!be.has(ce))){Be(pe,!0,$);return}(Ee.get(Y)||[]).forEach(ce=>{be.has(ce.id)||Pe(ce,!0,$)})})}),G+="
    ",this._flatTocTargetIds=O,this._flatTargetToSection=I,this._flatSectionTargets=x,t.innerHTML=G+'
    ',this._syncCatalogueShellHeight();let he=t.querySelector("#catalogueFlatCards"),$t=e||{},ht=0,pt=_=>!s||n===_,Qe=new Map(ae.map(_=>[M(_.heading),_.heading])),Ue=_=>{if(!s)return!0;let R=B.get(_.id)||`map:${_.id}`;return n===R},oe=_=>this.escapeHtml(_||"");if(pt("elections")){let _=document.createElement("div");_.id="flat-section-elections",_.className="catalogue-flat__anchor",he.appendChild(_);let R=C,U=r&&!s;U&&(R=this.includeMobileElectionCatalogue?C.slice(0,this._mobileInitialElectionCardLimit):[]);for(let F=0;FZ.isByElection),Y=this._showByElectionCards.has($.id),Le=($.electionEntries||[]).filter(Z=>!Z.isByElection||Y).map(Z=>{let qe=E(Z.body,Z.date,Z.bodyGroup||null),fa=Ca(Z.body),Wi=Z.displaySubtitle||(Z.isByElection?(Z.constituencies||[]).join(", "):Z.body==="European Parliament"&&(Z.constituencies||[]).filter(Bt=>Bt!=="Northern Ireland").length===0?"Northern Ireland":`${(Z.constituencies||[]).filter(Bt=>Bt!=="Northern Ireland").length} constituencies`),Ki=Z.displayProvider||fa,Zi=Z.placeholder?" class-member--placeholder":"",Pt=!Z.placeholder&&!!this.onCheckElectionLoaded?.(Z.body,Z.date),Yi=Pt?" class-member--loaded":"",ga=oe(Z.displayTitle||Ki||fa),ya=Z.date?oe(_e(Z.date)):"",ba=ya?`${ya} - ${ga}`:`${ga}`,Xi=Z.placeholder?`${ba}`:`${ba}`,Ji=Z.placeholder?"":``,Qi=Z.placeholder?'To Be Added':"";return` +
    - ${this.renderThumbnailZone(Oe.thumb,"class-member__thumbnail","28px")} + style="--map-color:${oe(qe.color)};"> + ${this.renderThumbnailZone(qe.thumb,"class-member__thumbnail","28px")}
    - ${Gi} - ${fe(zi)} - ${Wi} + ${Xi} + ${oe(Wi)} + ${Qi}
    - ${ji} + ${Ji}
    -
    `}).join(""),de=($.electionEntries||[]).filter(Z=>Z.placeholder).length,ke=de>0?``:"",ie=ae.length>0?``:"",Ae=document.createElement("div");Ae.className="c1-card map-card",Ae.dataset.c1Id=$.id,Ae.innerHTML=` +
    `}).join(""),ce=($.electionEntries||[]).filter(Z=>Z.placeholder).length,Fe=ce>0?``:"",se=ie.length>0?``:"",De=document.createElement("div");De.className="c1-card map-card",De.dataset.c1Id=$.id,De.innerHTML=`
    -

    ${fe($.name)}

    -
    ${fe($.years)} | ${fe($.extent)}
    +

    ${oe($.name)}

    +
    ${oe($.years)} | ${oe($.extent)}
    - ${ie} - ${ke} + ${se} + ${Fe}
    - ${Se||'
    No elections in this decade.
    '} + ${Le||'
    No elections in this decade.
    '}
    -
    `,re.appendChild(Ae),await this.yieldForCatalogueRender(F)}if(O&&R.length${this.escapeHtml(Z)}`,re.appendChild(Oe)}Ze=!0}if(r&&Me>=this._mobileInitialMapCardLimit){let ie=document.createElement("div");ie.id=`flat-card-${R.id}`,ie.className="catalogue-flat__anchor catalogue-flat__anchor--deferred",ie.dataset.catalogueDeferredTarget="1",ie.dataset.catalogueTargetKind="map-card",ie.dataset.catalogueTocTarget=z.has(ie.id)?"1":"0",re.appendChild(ie);continue}let F=document.createElement("div");F.id=`flat-card-${R.id}`,F.className="catalogue-flat__anchor",re.appendChild(F);let $=V(R),X={id:`flat-${R.id}`,name:R.name},ae=$.map(ie=>({map:ie.map,classId:X.id,className:R.name})),Y=this.renderC2Section(X,ae,{...Fe,ignoreMemberHeight:!0,fullWidth:!0}).replace(/
    [\s\S]*?<\/div>/,""),pe=ae.filter(ie=>ie.map.placeholder||ie.map.incomplete).length,Se=pe>0?`
    `,he.appendChild(De),await this.yieldForCatalogueRender(F)}if(U&&R.length${this.escapeHtml(Z)}`,he.appendChild(qe)}ke=!0}if(r&&ht>=this._mobileInitialMapCardLimit){let se=document.createElement("div");se.id=`flat-card-${R.id}`,se.className="catalogue-flat__anchor catalogue-flat__anchor--deferred",se.dataset.catalogueDeferredTarget="1",se.dataset.catalogueTargetKind="map-card",se.dataset.catalogueTocTarget=O.has(se.id)?"1":"0",he.appendChild(se);continue}let F=document.createElement("div");F.id=`flat-card-${R.id}`,F.className="catalogue-flat__anchor",he.appendChild(F);let $=z(R),X={id:`flat-${R.id}`,name:R.name},ie=$.map(se=>({map:se.map,classId:X.id,className:R.name})),Y=this.renderC2Section(X,ie,{...$t,ignoreMemberHeight:!0,fullWidth:!0}).replace(/
    [\s\S]*?<\/div>/,""),pe=ie.filter(se=>se.map.placeholder||se.map.incomplete).length,Le=pe>0?``:"",de=document.createElement("div");de.className="c1-card map-card",de.dataset.c1Id=R.id;let ke=[R.years,R.extent].filter(Boolean).join(" | ");de.innerHTML=` + `:"",ce=document.createElement("div");ce.className="c1-card map-card",ce.dataset.c1Id=R.id;let Fe=[R.years,R.extent].filter(Boolean).join(" | ");ce.innerHTML=`

    ${this.escapeHtml(T(R.name))}

    - ${ke?`
    ${this.escapeHtml(ke)}
    `:""} + ${Fe?`
    ${this.escapeHtml(Fe)}
    `:""}
    - ${Se} + ${Le}
    -
    ${Y}
    `,this.addC1CardEventListeners(de,ae.filter(ie=>!ie.map.placeholder)),re.appendChild(de),Me+=1,await this.yieldForCatalogueRender(_)}let ge=document.createElement("div");ge.id="flat-section-books",ge.className="catalogue-flat__anchor";let He=lt("books");if(r&&(ge.classList.add("catalogue-flat__anchor--deferred"),ge.dataset.catalogueDeferredTarget="1",ge.dataset.catalogueTargetKind="books",ge.dataset.catalogueTocTarget="1",re.appendChild(ge),re.insertAdjacentHTML("beforeend",this.renderMobileCatalogueExpandControl())),this.bindFlatViewDelegates(t),this.syncDownloadButtons(t),!r&&He&&this.booksData&&this.booksData.books&&this.booksData.books.length>0){re.appendChild(ge);let _=document.createElement("div");_.className="category-group-header",_.innerHTML='

    Books & Documents

    ',re.appendChild(_);let R=this.booksData.categories||[],O=new Map;this.booksData.books.forEach(F=>{let $=F.category||"other";O.has($)||O.set($,[]),O.get($).push(F)}),R.forEach(F=>{let $=O.get(F.id);if(!$||$.length===0)return;let X=this.searchQuery?$.filter(Y=>this._bookMatchesSearch(Y,F,this.searchQuery)):$;if(X.length===0)return;let ae=document.createElement("div");ae.className="category-section",ae.innerHTML=` +
    ${Y}
    `,this.addC1CardEventListeners(ce,ie.filter(se=>!se.map.placeholder)),he.appendChild(ce),ht+=1,await this.yieldForCatalogueRender(_)}let ge=document.createElement("div");ge.id="flat-section-books",ge.className="catalogue-flat__anchor";let fe=pt("books");if(r&&(ge.classList.add("catalogue-flat__anchor--deferred"),ge.dataset.catalogueDeferredTarget="1",ge.dataset.catalogueTargetKind="books",ge.dataset.catalogueTocTarget="1",he.appendChild(ge),he.insertAdjacentHTML("beforeend",this.renderMobileCatalogueExpandControl())),this.bindFlatViewDelegates(t),this.syncDownloadButtons(t),!r&&fe&&this.booksData&&this.booksData.books&&this.booksData.books.length>0){he.appendChild(ge);let _=document.createElement("div");_.className="category-group-header",_.innerHTML=`

    ${Oe("book-open")}Books & Documents

    `,he.appendChild(_);let R=this.booksData.categories||[],U=new Map;this.booksData.books.forEach(F=>{let $=F.category||"other";U.has($)||U.set($,[]),U.get($).push(F)}),R.forEach(F=>{let $=U.get(F.id);if(!$||$.length===0)return;let X=this.searchQuery?$.filter(Y=>this._bookMatchesSearch(Y,F,this.searchQuery)):$;if(X.length===0)return;let ie=document.createElement("div");ie.className="category-section",ie.innerHTML=`
    - ${F.icon||"[book]"} + ${Ot(F)}

    ${this.escapeHtml(F.name)}

    - `,X.forEach(Y=>{let pe=document.createElement("div");pe.className="map-card book-card",pe.innerHTML=this._buildBookCardHtml(Y),ae.appendChild(pe)}),re.appendChild(ae)})}if(this.ensureMobileThumbnailDismissal(),this._flatRenderToken===a){if(this.hydrateLazyThumbnails(t),this.syncMapCatalogueState(e),t.dataset.rendered="true",this._lastFilterStatsText){let _=document.getElementById("catalogueTocStats");_&&(_.textContent=this._lastFilterStatsText)}this._restorePlaceholderToggles(t),this.updateCatalogueHomeButton()}}_getCardPlaceholderKey(e){if(!e)return null;let t=e.dataset||{};return t.c1Id?`c1:${t.c1Id}`:t.classId?`class:${t.classId}`:t.groupId?`group:${t.groupId}`:null}_applyPlaceholderToggle(e,t){if(!e)return;e.classList.toggle("class-card--show-placeholders",!!t);let a=e.querySelector(".class-card__placeholder-toggle");if(!a)return;a.dataset.showing=t?"true":"false";let i=a.querySelector(".class-card__placeholder-toggle-label");if(i){let s=i.textContent.match(/\d+/)?.[0]||"";i.textContent=t?`Hide ${s} to be added`:`Show ${s} to be added`}}_restorePlaceholderToggles(e){!e||!this._showPlaceholdersCards?.size||e.querySelectorAll(".c1-card, .map-card--class, .conjoined-class-group").forEach(t=>{let a=this._getCardPlaceholderKey(t);a&&this._showPlaceholdersCards.has(a)&&this._applyPlaceholderToggle(t,!0)})}invalidateFlatView({render:e=!0}={}){let t=document.getElementById("catalogueFlatView");t&&(delete t.dataset.rendered,e&&this._catalogueViewMode==="flat"&&this.requestFlatViewRender(this._lastMapListOptions||{},{defer:this.isMobile}))}ensureMobileThumbnailDismissal(){if(this._mobileThumbnailDismissalBound||typeof document>"u")return;this._mobileThumbnailDismissalBound=!0;let e=(t=null)=>{if(t?.target?.closest?.(".catalogue-flat__toc-thumbwrap, .thumb-zone, .thumbnail-preview"))return;document.querySelectorAll(".catalogue-flat__toc-thumbzoom--visible").forEach(s=>{s.classList.remove("catalogue-flat__toc-thumbzoom--visible")});let i=document.querySelector(".thumbnail-preview");i&&(i.style.display="none")};document.addEventListener("pointerdown",e,!0),document.addEventListener("touchstart",e,!0),document.addEventListener("scroll",e,!0)}createClassCard(e,t={}){let a=document.createElement("div");a.className="map-card map-card--class",a.dataset.classId=e.id;let i=(e.maps||[]).map(p=>P.getMapById(p)).filter(Boolean);i.sort((p,f)=>(this.parseDateToTimestamp(f.date)||0)-(this.parseDateToTimestamp(p.date)||0));let s=i.filter(p=>!p.placeholder),r=["ni-wards","ni-deas","ni-lgds","ni-pcs","ni-assembly","ni-settlements","roi-settlements","ni-deds","ni-county-eds","eu-parliament"].includes(e.id),o="",l=i.map(p=>{let f=this.isMapLoadedState(p.id,t),g=p.placeholder,y=p.incomplete,b=r&&this.getYear(p.date)||p.name,v=p.style?.color||"#3388ff";return` + `,X.forEach(Y=>{let pe=document.createElement("div");pe.className="map-card book-card",pe.innerHTML=this._buildBookCardHtml(Y),ie.appendChild(pe)}),he.appendChild(ie)})}if(this.ensureMobileThumbnailDismissal(),this._flatRenderToken===a){if(this.hydrateLazyThumbnails(t),this.syncMapCatalogueState(e),t.dataset.rendered="true",this._lastFilterStatsText){let _=document.getElementById("catalogueTocStats");_&&(_.textContent=this._lastFilterStatsText)}this._restorePlaceholderToggles(t),this.updateCatalogueHomeButton()}}_getCardPlaceholderKey(e){if(!e)return null;let t=e.dataset||{};return t.c1Id?`c1:${t.c1Id}`:t.classId?`class:${t.classId}`:t.groupId?`group:${t.groupId}`:null}_applyPlaceholderToggle(e,t){if(!e)return;e.classList.toggle("class-card--show-placeholders",!!t);let a=e.querySelector(".class-card__placeholder-toggle");if(!a)return;a.dataset.showing=t?"true":"false";let i=a.querySelector(".class-card__placeholder-toggle-label");if(i){let s=i.textContent.match(/\d+/)?.[0]||"";i.textContent=t?`Hide ${s} to be added`:`Show ${s} to be added`}}_restorePlaceholderToggles(e){!e||!this._showPlaceholdersCards?.size||e.querySelectorAll(".c1-card, .map-card--class, .conjoined-class-group").forEach(t=>{let a=this._getCardPlaceholderKey(t);a&&this._showPlaceholdersCards.has(a)&&this._applyPlaceholderToggle(t,!0)})}invalidateFlatView({render:e=!0}={}){let t=document.getElementById("catalogueFlatView");t&&(delete t.dataset.rendered,e&&this._catalogueViewMode==="flat"&&this.requestFlatViewRender(this._lastMapListOptions||{},{defer:this.isMobile}))}ensureMobileThumbnailDismissal(){if(this._mobileThumbnailDismissalBound||typeof document>"u")return;this._mobileThumbnailDismissalBound=!0;let e=(t=null)=>{if(t?.target?.closest?.(".catalogue-flat__toc-thumbwrap, .thumb-zone, .thumbnail-preview"))return;document.querySelectorAll(".catalogue-flat__toc-thumbzoom--visible").forEach(s=>{s.classList.remove("catalogue-flat__toc-thumbzoom--visible")});let i=document.querySelector(".thumbnail-preview");i&&(i.style.display="none")};document.addEventListener("pointerdown",e,!0),document.addEventListener("touchstart",e,!0),document.addEventListener("scroll",e,!0)}createClassCard(e,t={}){let a=document.createElement("div");a.className="map-card map-card--class",a.dataset.classId=e.id;let i=(e.maps||[]).map(p=>P.getMapById(p)).filter(Boolean);i.sort((p,f)=>(this.parseDateToTimestamp(f.date)||0)-(this.parseDateToTimestamp(p.date)||0));let s=i.filter(p=>!p.placeholder),r=["ni-wards","ni-deas","ni-lgds","ni-pcs","ni-assembly","ni-settlements","roi-settlements","ni-deds","ni-county-eds","eu-parliament"].includes(e.id),o="",l=i.map(p=>{let f=this.isMapLoadedState(p.id,t),g=p.placeholder,y=p.incomplete,b=r&&this.getYear(p.date)||p.name,v=p.style?.color||"#3388ff";return`
    ${this.renderThumbnailZone(this.getThumbnailId(p),"class-member__thumbnail","28px")}
    @@ -406,10 +404,10 @@ ${s.map(n).join(",")} `:"";return a.innerHTML=`

    ${this.escapeHtml(e.name)}

    ${u}
    ${l} -
    ${d}
    `,this.addC1CardEventListeners(a,o),setTimeout(()=>this.alignChronologicalColumns(a),0),a}renderC2Section(e,t,a){let s=[...t.filter(g=>g.classId===e.id)].sort((g,y)=>(this.parseDateToTimestamp(y.map.date)||0)-(this.parseDateToTimestamp(g.map.date)||0)),n=["ni-deds","ni-county-eds","ni-admin-areas","ni-admin-counties"],r=new Set(["District Electoral Divisions","County Electoral Divisions","Administrative Areas"]),o=["ni-wards","ni-deas"],l=["ni-assembly","flat-flat-lidar-pointclouds","flat-flat-ni-lidar-dem"],d=String(e?.name||"").replace(/\s*\([^)]*\)/g,"").trim(),h=s.map(({map:g})=>this.getYear(g.date)).filter(Boolean),u=h.length>1&&h.every(g=>g===h[0]),p=s.map(({map:g})=>{let y=this.isMapLoadedState(g.id,a),b=g.placeholder,v=g.incomplete,w=g.variants&&g.variants.length>0,S,M="";if(g.id==="cso-urban-areas-2022")S="2022";else if(n.includes(e.id)||r.has(d))S=this.formatMapDate(g.date)||g.name;else if(o.includes(e.id)){S=this.getYear(g.date)||g.name;let I=this.formatMapDate(g.date);I&&I!==S&&(M=`${I}`)}else l.includes(e.id)||u?S=g.name:S=this.getYear(g.date)||g.name;let C=w&&this.shouldExpandVariantsByDefault(g),T=w?``:"",V=w?this.renderVariantsDropdown(g,y):"",z=!a.ignoreMemberHeight&&g.style?.height?`height: ${g.style.height};`:"";return` -
    +
    ${d}
    `,this.addC1CardEventListeners(a,o),setTimeout(()=>this.alignChronologicalColumns(a),0),a}renderC2Section(e,t,a){let s=[...t.filter(g=>g.classId===e.id)].sort((g,y)=>(this.parseDateToTimestamp(y.map.date)||0)-(this.parseDateToTimestamp(g.map.date)||0)),n=["ni-deds","ni-county-eds","ni-admin-areas","ni-admin-counties"],r=new Set(["District Electoral Divisions","County Electoral Divisions","Administrative Areas"]),o=["ni-wards","ni-deas"],l=["ni-assembly","flat-flat-lidar-pointclouds","flat-flat-ni-lidar-dem"],d=String(e?.name||"").replace(/\s*\([^)]*\)/g,"").trim(),h=s.map(({map:g})=>this.getYear(g.date)).filter(Boolean),u=h.length>1&&h.every(g=>g===h[0]),p=s.map(({map:g})=>{let y=this.isMapLoadedState(g.id,a),b=g.placeholder,v=g.incomplete,w=g.variants&&g.variants.length>0,S,E="";if(g.id==="cso-urban-areas-2022")S="2022";else if(n.includes(e.id)||r.has(d))S=this.formatMapDate(g.date)||g.name;else if(o.includes(e.id)){S=this.getYear(g.date)||g.name;let I=this.formatMapDate(g.date);I&&I!==S&&(E=`${I}`)}else l.includes(e.id)||u?S=g.name:S=this.getYear(g.date)||g.name;let C=w&&this.shouldExpandVariantsByDefault(g),T=w?``:"",z=w?this.renderVariantsDropdown(g,y):"",O=!a.ignoreMemberHeight&&g.style?.height?`height: ${g.style.height};`:"";return` +
    ${this.renderThumbnailZone(this.getThumbnailId(g),"class-member__thumbnail","28px")} -
    ${b?`${S}`:`${S}`}${M} +
    ${b?`${S}`:`${S}`}${E} ${g.changeNote?`${this.escapeHtml(g.changeNote)}`:""} ${b?"":`${this.escapeHtml(this.renderMapProviderSummary(g))}`} ${b?'To Be Added':v?'Incomplete':""} @@ -444,10 +442,10 @@ ${s.map(n).join(",")}
    `} -
    ${V} `}).join("");return`
    +
    ${z} `}).join("");return`
    ${this.escapeHtml(e.name)}
    ${p}
    -
    `}renderChronologicalGrid(e,t,a,i){let s=[];if(e.columns.forEach((d,h)=>{let u=d.stack||(d.classId?[d.classId]:[]),p=u.length>1,f=[];u.forEach(v=>{let w=t.find(C=>C.id===v);if(!w)return;[...a.filter(C=>C.classId===w.id)].sort((C,T)=>(this.parseDateToTimestamp(T.map.date)||0)-(this.parseDateToTimestamp(C.map.date)||0)).forEach(({map:C},T)=>{let V=parseInt(this.getYear(C.date));V&&(T===0&&p&&f.push({type:"header",year:V,name:w.name,classId:w.id}),f.push({type:"entry",year:V,map:C,className:w.name,classId:w.id,isLoaded:this.isMapLoadedState(C.id,i),isPlaceholder:C.placeholder,isIncomplete:C.incomplete}))})});let g=u[0],y=t.find(v=>v.id===g),b=p?"":y?.name||"";s.push({items:f,header:b,isStacked:p,colIndex:h})}),s.every(d=>d.items.length===0))return"";let r=Math.max(...s.map(d=>d.items.length)),o=s.length;s.forEach(d=>{d.items.forEach((h,u)=>{h.gridRowStart=u+2,h.type==="header"?h.gridRowEnd=h.gridRowStart+1:d.items[u+1]?h.gridRowEnd=u+1+2:h.gridRowEnd=r+2})});let l=`
    `;s.forEach((d,h)=>{l+=`
    ${this.escapeHtml(d.header)}
    `}),s.forEach((d,h)=>{let u=h+1;d.items.forEach(p=>{if(p.type==="header")l+=`
    `,l+=this.escapeHtml(p.name),l+="
    ";else{let f=p.isLoaded?" c1-grid-entry--loaded":"",g=p.isPlaceholder?" c1-grid-entry--placeholder":"",y=p.isIncomplete?" c1-grid-entry--incomplete":"",b=this.getYear(p.map.date)||p.map.name,v=p.map.style?.color||"#888";l+=`
    `,l+=`
    `,l+=this.renderThumbnailZone(this.getThumbnailId(p.map),"c1-entry__thumbnail","22px"),l+='
    ',l+=`${b}`,!p.isPlaceholder&&p.map.provider&&(l+=`${this.escapeHtml(p.map.provider.join(", "))}`),l+="
    ",p.isPlaceholder?l+='To Be Added':p.isIncomplete&&(l+='Incomplete'),p.isPlaceholder||(l+=`
    `}renderChronologicalGrid(e,t,a,i){let s=[];if(e.columns.forEach((d,h)=>{let u=d.stack||(d.classId?[d.classId]:[]),p=u.length>1,f=[];u.forEach(v=>{let w=t.find(C=>C.id===v);if(!w)return;[...a.filter(C=>C.classId===w.id)].sort((C,T)=>(this.parseDateToTimestamp(T.map.date)||0)-(this.parseDateToTimestamp(C.map.date)||0)).forEach(({map:C},T)=>{let z=parseInt(this.getYear(C.date));z&&(T===0&&p&&f.push({type:"header",year:z,name:w.name,classId:w.id}),f.push({type:"entry",year:z,map:C,className:w.name,classId:w.id,isLoaded:this.isMapLoadedState(C.id,i),isPlaceholder:C.placeholder,isIncomplete:C.incomplete}))})});let g=u[0],y=t.find(v=>v.id===g),b=p?"":y?.name||"";s.push({items:f,header:b,isStacked:p,colIndex:h})}),s.every(d=>d.items.length===0))return"";let r=Math.max(...s.map(d=>d.items.length)),o=s.length;s.forEach(d=>{d.items.forEach((h,u)=>{h.gridRowStart=u+2,h.type==="header"?h.gridRowEnd=h.gridRowStart+1:d.items[u+1]?h.gridRowEnd=u+1+2:h.gridRowEnd=r+2})});let l=`
    `;s.forEach((d,h)=>{l+=`
    ${this.escapeHtml(d.header)}
    `}),s.forEach((d,h)=>{let u=h+1;d.items.forEach(p=>{if(p.type==="header")l+=`
    `,l+=this.escapeHtml(p.name),l+="
    ";else{let f=p.isLoaded?" c1-grid-entry--loaded":"",g=p.isPlaceholder?" c1-grid-entry--placeholder":"",y=p.isIncomplete?" c1-grid-entry--incomplete":"",b=this.getYear(p.map.date)||p.map.name,v=p.map.style?.color||"#888";l+=`
    `,l+=`
    `,l+=this.renderThumbnailZone(this.getThumbnailId(p.map),"c1-entry__thumbnail","22px"),l+='
    ',l+=`${b}`,!p.isPlaceholder&&p.map.provider&&(l+=`${this.escapeHtml(p.map.provider.join(", "))}`),l+="
    ",p.isPlaceholder?l+='To Be Added':p.isIncomplete&&(l+='Incomplete'),p.isPlaceholder||(l+=``,l+=``,l+=` ${this.renderOsniOverflowItems(p.map)}
    -
    `),l+="
    "}})});for(let d=0;d{let f=p+1;u.items.some(y=>y.gridRowStart<=h&&h
    `)})}return l+="
    ",l}renderExplicitGrid(e,t){let a=e.totalRows||33,s=`
    `;e.columns.forEach((n,r)=>{s+=`
    ${this.escapeHtml(n.header||"")}
    `}),e.columns.forEach((n,r)=>{let o=r+1;n.items.forEach(l=>{let d=l.rows||[];if(d.length===0)return;let h=Math.min(...d),u=Math.max(...d)+1;if(l.type==="header")s+=`
    `,s+=this.escapeHtml(l.label),s+="
    ";else if(l.type==="annotation")s+=`
    `,s+=`${this.escapeHtml(l.label)}`,s+="
    ";else if(l.mapId){let p=P.getMapById(l.mapId);if(!p){s+=`
    `;return}let f=this.isMapLoadedState(p.id,t),g=p.placeholder,y=p.incomplete,b=f?" c1-grid-entry--loaded":"",v=g?" c1-grid-entry--placeholder":"",w=y?" c1-grid-entry--incomplete":"",S=this.getYear(p.date)||p.name,M=p.style?.color||"#888";s+=`
    `,s+=`
    `,s+=this.renderThumbnailZone(this.getThumbnailId(p),"c1-entry__thumbnail","22px"),s+='
    ',s+=`${S}`,!g&&p.provider&&(s+=`${this.escapeHtml(p.provider.join(", "))}`),s+="
    ",g?s+='To Be Added':y&&(s+='Incomplete'),g||(s+=`
    `),l+="
    "}})});for(let d=0;d{let f=p+1;u.items.some(y=>y.gridRowStart<=h&&h
    `)})}return l+="
    ",l}renderExplicitGrid(e,t){let a=e.totalRows||33,s=`
    `;e.columns.forEach((n,r)=>{s+=`
    ${this.escapeHtml(n.header||"")}
    `}),e.columns.forEach((n,r)=>{let o=r+1;n.items.forEach(l=>{let d=l.rows||[];if(d.length===0)return;let h=Math.min(...d),u=Math.max(...d)+1;if(l.type==="header")s+=`
    `,s+=this.escapeHtml(l.label),s+="
    ";else if(l.type==="annotation")s+=`
    `,s+=`${this.escapeHtml(l.label)}`,s+="
    ";else if(l.mapId){let p=P.getMapById(l.mapId);if(!p){s+=`
    `;return}let f=this.isMapLoadedState(p.id,t),g=p.placeholder,y=p.incomplete,b=f?" c1-grid-entry--loaded":"",v=g?" c1-grid-entry--placeholder":"",w=y?" c1-grid-entry--incomplete":"",S=this.getYear(p.date)||p.name,E=p.style?.color||"#888";s+=`
    `,s+=`
    `,s+=this.renderThumbnailZone(this.getThumbnailId(p),"c1-entry__thumbnail","22px"),s+='
    ',s+=`${S}`,!g&&p.provider&&(s+=`${this.escapeHtml(p.provider.join(", "))}`),s+="
    ",g?s+='To Be Added':y&&(s+='Incomplete'),g||(s+=``,s+=``,s+=` ${this.renderOsniOverflowItems(p)}
    -
    `),s+="
    "}})});for(let n=2;n<=a+1;n++)e.columns.forEach((r,o)=>{let l=o+1;r.items.some(h=>{let u=h.rows||[],p=Math.min(...u),f=Math.max(...u)+1;return p<=n&&n`)});return s+="",s}alignChronologicalColumns(e){}addC1CardEventListeners(e,t){e.addEventListener("click",s=>{let n=s.target.closest("button");if(!n)return;if(n.classList.contains("overflow-menu__trigger")){s.stopPropagation();let o=n.closest(".overflow-menu"),l=o.querySelector(".overflow-menu__dropdown");document.querySelectorAll(".overflow-menu--open").forEach(h=>{h!==o&&h.classList.remove("overflow-menu--open")});let d=o.classList.contains("overflow-menu--open");if(o.classList.toggle("overflow-menu--open"),!d&&l){let h=n.getBoundingClientRect();l.style.top=`${h.bottom+2}px`,l.style.right=`${window.innerWidth-h.right}px`,l.offsetHeight}return}let r=n.dataset.mapId;if(r){if(n.classList.contains("variants-toggle")){s.stopPropagation(),this.toggleVariants(r,e);return}if(n.classList.contains("load-btn")){s.stopPropagation();let o=n.closest(".class-member, .c1-grid-entry, .variant-item"),l=o?.classList.contains("class-member--loaded")||o?.classList.contains("c1-grid-entry--loaded")||o?.classList.contains("variant-item--loaded");this.handleLoadToggle(r,!!l)}else n.classList.contains("visibility-btn")?(s.stopPropagation(),n.closest(".overflow-menu")?.classList.remove("overflow-menu--open"),this.onMapToggle&&this.onMapToggle(r)):n.classList.contains("copy-url-btn")?(s.stopPropagation(),n.closest(".overflow-menu")?.classList.remove("overflow-menu--open"),this.copyMapUrl(r,n)):n.classList.contains("download-fgb-btn")&&(s.stopPropagation(),n.closest(".overflow-menu")?.classList.remove("overflow-menu--open"),this.onDownloadFgb&&this.onDownloadFgb(r))}}),e.addEventListener("click",s=>{let n=s.target.closest(".c1-grid-entry");if(!n||!e.contains(n)||s.target.closest("button"))return;let r=n.dataset.mapId;if(!r||n.classList.contains("c1-grid-entry--placeholder"))return;n.classList.contains("c1-grid-entry--loaded")&&this.onMapToggle?this.onMapToggle(r):this.handleLoadToggle(r,!1)});let a=e.querySelector(".timeline-slider"),i=e.querySelector(".class-card__timeline");if(a&&i){let s=e.querySelectorAll(".timeline-labels span"),n=null,r=JSON.parse(i.dataset.percentages||"[]"),o=l=>{let d=0,h=1/0;return r.forEach((u,p)=>{let f=Math.abs(u-l);f{let l=o(parseFloat(a.value));s.forEach((d,h)=>d.classList.toggle("active",h===l))}),a.addEventListener("change",()=>{let l=o(parseFloat(a.value));a.value=r[l],s.forEach((f,g)=>f.classList.toggle("active",g===l));let d=t[l];if(!d)return;let h=d.map.date;if(h===n)return;let u=t.filter(f=>f.map.date===h);t.filter(f=>f.map.date!==h).forEach(f=>{this.onHideMap&&this.onHideMap(f.map.id)}),u.sort((f,g)=>{let y=f.classId==="ni-wards"?0:1,b=g.classId==="ni-wards"?0:1;return y-b}),u.forEach(f=>{this.onMapLoad&&this.onMapLoad(f.map.id)}),n=h}),s.length&&s[0].parentNode){let l=s[0].parentNode;l.addEventListener("click",d=>{let h=d.target.closest("span[data-pct]");if(!h||!l.contains(h))return;let u=parseFloat(h.dataset.pct);Number.isFinite(u)&&(a.value=u,a.dispatchEvent(new Event("change")))})}}this.initSectionHeaderScrollTracking(e)}initSectionHeaderScrollTracking(e){let t=e.querySelectorAll(".c1-explicit-grid");t.length!==0&&t.forEach(a=>{let i=a.closest(".pane-tab-content")||a.closest(".pane__content")||document.querySelector(".pane-tab-content")||document.querySelector(".pane__content")||a.closest(".sidebar__content");if(!i)return;let s=a.querySelectorAll(".c1-grid-section-header");if(s.length===0)return;let n=new Map;s.forEach(f=>{let y=(f.getAttribute("style")||"").match(/grid-column:\s*(\d+)/),b=y?parseInt(y[1]):1;n.has(b)||n.set(b,[]),n.get(b).push(f)}),n.forEach((f,g)=>{f.sort((y,b)=>{let v=y.getAttribute("style")||"",w=b.getAttribute("style")||"",S=parseInt(v.match(/grid-row:\s*(\d+)/)?.[1]||"0"),M=parseInt(w.match(/grid-row:\s*(\d+)/)?.[1]||"0");return S-M})});let r=[];s.forEach(f=>{let g=f.getAttribute("style")||"",y=g.match(/grid-row:\s*(\d+)/),b=y?parseInt(y[1]):1,v=g.match(/grid-column:\s*(\d+)/),w=v?parseInt(v[1]):1,S=n.get(w)||[],M=S.indexOf(f),C;if(M>=0&&M{let I=z.getAttribute("style")||"",x=I.match(/grid-column:\s*(\d+)/);if((x?parseInt(x[1]):1)===w){let H=I.match(/grid-row:\s*(\d+)(?:\s*\/\s*(\d+))?/);if(H){let E=H[2]?parseInt(H[2]):parseInt(H[1])+1;V=Math.max(V,E)}}}),C=V}r.push({header:f,startRow:b,endRow:C,col:w})});let o=0,l=()=>{let f=i.getBoundingClientRect(),g=getComputedStyle(i),y=parseFloat(g.paddingTop)||0;o=f.top+y+96};l(),window.addEventListener("resize",l,{passive:!0});let d=()=>o,h=Array.from(a.querySelectorAll(".c1-grid-cell, .c1-grid-annotation")).map(f=>{let g=f.getAttribute("style")||"",y=g.match(/grid-column:\s*(\d+)/),b=g.match(/grid-row:\s*(\d+)(?:\s*\/\s*(\d+))?/),v=y?parseInt(y[1]):0,w=b?parseInt(b[1]):0,S=b&&b[2]?parseInt(b[2]):w+1;return{item:f,col:v,rowStart:w,rowEnd:S}});r.forEach(f=>{let g=null,y=0;for(let b of h)b.col===f.col&&b.rowStart>=f.startRow&&b.rowStarty&&(y=b.rowEnd,g=b.item);f.lastItem=g});let u=()=>{r.forEach(({header:f,col:g,lastItem:y})=>{let b=!1;if(y){let v=y.getBoundingClientRect(),S=f.getBoundingClientRect().height;if(v.bottom===0&&v.top===0){if(i.scrollTop===0)return;b=!0}else{let M=d()+S;b=v.bottom{f.forEach(S=>S.classList.remove("c1-grid-section-header--collision-hidden"));let y=f.filter(S=>!S.classList.contains("c1-grid-section-header--scrolled-past"));if(y.length<2)return;let b=y.map(S=>{let M=r.find(C=>C.header===S);return{header:S,top:S.getBoundingClientRect().top,startRow:M?.startRow||0,text:S.textContent.trim().substring(0,25)}}),v=d();if(b.some(S=>Math.abs(S.top-v)<15)){b.sort((S,M)=>S.startRow-M.startRow);for(let S=0;S{p||(requestAnimationFrame(()=>{u(),p=!1}),p=!0)}),u()})}getC1ClassIds(e){let t=[];return e.c2s&&t.push(...e.c2s),e.rows&&e.rows.forEach(a=>{a.left&&t.push(a.left),a.right&&t.push(a.right)}),e.sections&&e.sections.forEach(a=>{a.classId&&t.push(a.classId),a.left&&t.push(a.left),a.center&&t.push(a.center),a.right&&t.push(a.right),a.columns&&a.columns.forEach(i=>{i.classId&&t.push(i.classId),i.stack&&t.push(...i.stack)})}),[...new Set(t)]}getSourceDownloads(e){return Array.isArray(e.sourceDownloads)&&e.sourceDownloads.length?e.sourceDownloads:Array.isArray(e.osniDownloads)&&e.osniDownloads.length?e.osniDownloads:[]}openDownloadDropdown(e,t){if(!e)return;this.closeDownloadDropdown(e,{keepOpen:!0}),e._ddHome||(e._ddHome={parent:e.parentNode,next:e.nextSibling}),document.body.appendChild(e),e.style.zIndex="10000",e.classList.remove("hidden"),this.positionDropdownInViewport(e,t);let a=i=>{i&&i.type==="click"&&(e.contains(i.target)||t?.contains?.(i.target))||this.closeDownloadDropdown(e)};e._ddCloseHandler=a,setTimeout(()=>{document.addEventListener("click",a,!0),window.addEventListener("scroll",a,!0),window.addEventListener("resize",a,!0)},0)}closeDownloadDropdown(e,{keepOpen:t=!1}={}){if(!e||(e._ddCloseHandler&&(document.removeEventListener("click",e._ddCloseHandler,!0),window.removeEventListener("scroll",e._ddCloseHandler,!0),window.removeEventListener("resize",e._ddCloseHandler,!0),e._ddCloseHandler=null),t))return;e.classList.add("hidden"),e.style.position="",e.style.top="",e.style.left="",e.style.right="",e.style.bottom="",e.style.margin="",e.style.maxHeight="",e.style.overflowY="",e.style.zIndex="";let a=e._ddHome;e._ddHome=null,a?.parent?.isConnected?a.parent.insertBefore(e,a.next&&a.next.parentNode===a.parent?a.next:null):e.parentNode===document.body&&e.remove()}toggleDownloadDropdown(e,t){return e?e.classList.contains("hidden")?(this.openDownloadDropdown(e,t),!0):(this.closeDownloadDropdown(e),!1):!1}positionDropdownInViewport(e,t){let a=t?.getBoundingClientRect?.();if(!a)return;let i=8,s=4,n=window.innerWidth,r=window.innerHeight;e.style.position="fixed",e.style.margin="0",e.style.top="0px",e.style.left="0px",e.style.right="auto",e.style.bottom="auto",e.style.maxHeight="",e.style.overflowY="";let{width:o,height:l}=e.getBoundingClientRect(),d=r-i*2;l>d&&(e.style.maxHeight=`${d}px`,e.style.overflowY="auto",l=d);let h=a.bottom+s;h+l+i>r&&a.top-s-l>=i&&(h=a.top-s-l),h=Math.min(Math.max(h,i),Math.max(i,r-l-i));let u=a.right-o;u+o+i>n&&(u=n-o-i),u`${a} ${this.escapeHtml(i.label)}`).join("")}getVisibilityButtonIcon(e){return` + `),s+=""}})});for(let n=2;n<=a+1;n++)e.columns.forEach((r,o)=>{let l=o+1;r.items.some(h=>{let u=h.rows||[],p=Math.min(...u),f=Math.max(...u)+1;return p<=n&&n`)});return s+="",s}alignChronologicalColumns(e){}addC1CardEventListeners(e,t){e.addEventListener("click",s=>{let n=s.target.closest("button");if(!n)return;if(n.classList.contains("overflow-menu__trigger")){s.stopPropagation();let o=n.closest(".overflow-menu"),l=o.querySelector(".overflow-menu__dropdown");document.querySelectorAll(".overflow-menu--open").forEach(h=>{h!==o&&h.classList.remove("overflow-menu--open")});let d=o.classList.contains("overflow-menu--open");if(o.classList.toggle("overflow-menu--open"),!d&&l){let h=n.getBoundingClientRect();l.style.top=`${h.bottom+2}px`,l.style.right=`${window.innerWidth-h.right}px`,l.offsetHeight}return}let r=n.dataset.mapId;if(r){if(n.classList.contains("variants-toggle")){s.stopPropagation(),this.toggleVariants(r,e);return}if(n.classList.contains("load-btn")){s.stopPropagation();let o=n.closest(".class-member, .c1-grid-entry, .variant-item"),l=o?.classList.contains("class-member--loaded")||o?.classList.contains("c1-grid-entry--loaded")||o?.classList.contains("variant-item--loaded");this.handleLoadToggle(r,!!l)}else n.classList.contains("visibility-btn")?(s.stopPropagation(),n.closest(".overflow-menu")?.classList.remove("overflow-menu--open"),this.onMapToggle&&this.onMapToggle(r)):n.classList.contains("copy-url-btn")?(s.stopPropagation(),n.closest(".overflow-menu")?.classList.remove("overflow-menu--open"),this.copyMapUrl(r,n)):n.classList.contains("download-fgb-btn")&&(s.stopPropagation(),n.closest(".overflow-menu")?.classList.remove("overflow-menu--open"),this.onDownloadFgb&&this.onDownloadFgb(r))}}),e.addEventListener("click",s=>{let n=s.target.closest(".c1-grid-entry");if(!n||!e.contains(n)||s.target.closest("button"))return;let r=n.dataset.mapId;if(!r||n.classList.contains("c1-grid-entry--placeholder"))return;n.classList.contains("c1-grid-entry--loaded")&&this.onMapToggle?this.onMapToggle(r):this.handleLoadToggle(r,!1)});let a=e.querySelector(".timeline-slider"),i=e.querySelector(".class-card__timeline");if(a&&i){let s=e.querySelectorAll(".timeline-labels span"),n=null,r=JSON.parse(i.dataset.percentages||"[]"),o=l=>{let d=0,h=1/0;return r.forEach((u,p)=>{let f=Math.abs(u-l);f{let l=o(parseFloat(a.value));s.forEach((d,h)=>d.classList.toggle("active",h===l))}),a.addEventListener("change",()=>{let l=o(parseFloat(a.value));a.value=r[l],s.forEach((f,g)=>f.classList.toggle("active",g===l));let d=t[l];if(!d)return;let h=d.map.date;if(h===n)return;let u=t.filter(f=>f.map.date===h);t.filter(f=>f.map.date!==h).forEach(f=>{this.onHideMap&&this.onHideMap(f.map.id)}),u.sort((f,g)=>{let y=f.classId==="ni-wards"?0:1,b=g.classId==="ni-wards"?0:1;return y-b}),u.forEach(f=>{this.onMapLoad&&this.onMapLoad(f.map.id)}),n=h}),s.length&&s[0].parentNode){let l=s[0].parentNode;l.addEventListener("click",d=>{let h=d.target.closest("span[data-pct]");if(!h||!l.contains(h))return;let u=parseFloat(h.dataset.pct);Number.isFinite(u)&&(a.value=u,a.dispatchEvent(new Event("change")))})}}this.initSectionHeaderScrollTracking(e)}initSectionHeaderScrollTracking(e){let t=e.querySelectorAll(".c1-explicit-grid");t.length!==0&&t.forEach(a=>{let i=a.closest(".pane-tab-content")||a.closest(".pane__content")||document.querySelector(".pane-tab-content")||document.querySelector(".pane__content")||a.closest(".sidebar__content");if(!i)return;let s=a.querySelectorAll(".c1-grid-section-header");if(s.length===0)return;let n=new Map;s.forEach(f=>{let y=(f.getAttribute("style")||"").match(/grid-column:\s*(\d+)/),b=y?parseInt(y[1]):1;n.has(b)||n.set(b,[]),n.get(b).push(f)}),n.forEach((f,g)=>{f.sort((y,b)=>{let v=y.getAttribute("style")||"",w=b.getAttribute("style")||"",S=parseInt(v.match(/grid-row:\s*(\d+)/)?.[1]||"0"),E=parseInt(w.match(/grid-row:\s*(\d+)/)?.[1]||"0");return S-E})});let r=[];s.forEach(f=>{let g=f.getAttribute("style")||"",y=g.match(/grid-row:\s*(\d+)/),b=y?parseInt(y[1]):1,v=g.match(/grid-column:\s*(\d+)/),w=v?parseInt(v[1]):1,S=n.get(w)||[],E=S.indexOf(f),C;if(E>=0&&E{let I=O.getAttribute("style")||"",x=I.match(/grid-column:\s*(\d+)/);if((x?parseInt(x[1]):1)===w){let H=I.match(/grid-row:\s*(\d+)(?:\s*\/\s*(\d+))?/);if(H){let M=H[2]?parseInt(H[2]):parseInt(H[1])+1;z=Math.max(z,M)}}}),C=z}r.push({header:f,startRow:b,endRow:C,col:w})});let o=0,l=()=>{let f=i.getBoundingClientRect(),g=getComputedStyle(i),y=parseFloat(g.paddingTop)||0;o=f.top+y+96};l(),window.addEventListener("resize",l,{passive:!0});let d=()=>o,h=Array.from(a.querySelectorAll(".c1-grid-cell, .c1-grid-annotation")).map(f=>{let g=f.getAttribute("style")||"",y=g.match(/grid-column:\s*(\d+)/),b=g.match(/grid-row:\s*(\d+)(?:\s*\/\s*(\d+))?/),v=y?parseInt(y[1]):0,w=b?parseInt(b[1]):0,S=b&&b[2]?parseInt(b[2]):w+1;return{item:f,col:v,rowStart:w,rowEnd:S}});r.forEach(f=>{let g=null,y=0;for(let b of h)b.col===f.col&&b.rowStart>=f.startRow&&b.rowStarty&&(y=b.rowEnd,g=b.item);f.lastItem=g});let u=()=>{r.forEach(({header:f,col:g,lastItem:y})=>{let b=!1;if(y){let v=y.getBoundingClientRect(),S=f.getBoundingClientRect().height;if(v.bottom===0&&v.top===0){if(i.scrollTop===0)return;b=!0}else{let E=d()+S;b=v.bottom{f.forEach(S=>S.classList.remove("c1-grid-section-header--collision-hidden"));let y=f.filter(S=>!S.classList.contains("c1-grid-section-header--scrolled-past"));if(y.length<2)return;let b=y.map(S=>{let E=r.find(C=>C.header===S);return{header:S,top:S.getBoundingClientRect().top,startRow:E?.startRow||0,text:S.textContent.trim().substring(0,25)}}),v=d();if(b.some(S=>Math.abs(S.top-v)<15)){b.sort((S,E)=>S.startRow-E.startRow);for(let S=0;S{p||(requestAnimationFrame(()=>{u(),p=!1}),p=!0)}),u()})}getC1ClassIds(e){let t=[];return e.c2s&&t.push(...e.c2s),e.rows&&e.rows.forEach(a=>{a.left&&t.push(a.left),a.right&&t.push(a.right)}),e.sections&&e.sections.forEach(a=>{a.classId&&t.push(a.classId),a.left&&t.push(a.left),a.center&&t.push(a.center),a.right&&t.push(a.right),a.columns&&a.columns.forEach(i=>{i.classId&&t.push(i.classId),i.stack&&t.push(...i.stack)})}),[...new Set(t)]}getSourceDownloads(e){return Array.isArray(e.sourceDownloads)&&e.sourceDownloads.length?e.sourceDownloads:Array.isArray(e.osniDownloads)&&e.osniDownloads.length?e.osniDownloads:[]}openDownloadDropdown(e,t){if(!e)return;this.closeDownloadDropdown(e,{keepOpen:!0}),e._ddHome||(e._ddHome={parent:e.parentNode,next:e.nextSibling}),document.body.appendChild(e),e.style.zIndex="10000",e.classList.remove("hidden"),this.positionDropdownInViewport(e,t);let a=i=>{i&&i.type==="click"&&(e.contains(i.target)||t?.contains?.(i.target))||this.closeDownloadDropdown(e)};e._ddCloseHandler=a,setTimeout(()=>{document.addEventListener("click",a,!0),window.addEventListener("scroll",a,!0),window.addEventListener("resize",a,!0)},0)}closeDownloadDropdown(e,{keepOpen:t=!1}={}){if(!e||(e._ddCloseHandler&&(document.removeEventListener("click",e._ddCloseHandler,!0),window.removeEventListener("scroll",e._ddCloseHandler,!0),window.removeEventListener("resize",e._ddCloseHandler,!0),e._ddCloseHandler=null),t))return;e.classList.add("hidden"),e.style.position="",e.style.top="",e.style.left="",e.style.right="",e.style.bottom="",e.style.margin="",e.style.maxHeight="",e.style.overflowY="",e.style.zIndex="";let a=e._ddHome;e._ddHome=null,a?.parent?.isConnected?a.parent.insertBefore(e,a.next&&a.next.parentNode===a.parent?a.next:null):e.parentNode===document.body&&e.remove()}toggleDownloadDropdown(e,t){return e?e.classList.contains("hidden")?(this.openDownloadDropdown(e,t),!0):(this.closeDownloadDropdown(e),!1):!1}positionDropdownInViewport(e,t){let a=t?.getBoundingClientRect?.();if(!a)return;let i=8,s=4,n=window.innerWidth,r=window.innerHeight;e.style.position="fixed",e.style.margin="0",e.style.top="0px",e.style.left="0px",e.style.right="auto",e.style.bottom="auto",e.style.maxHeight="",e.style.overflowY="";let{width:o,height:l}=e.getBoundingClientRect(),d=r-i*2;l>d&&(e.style.maxHeight=`${d}px`,e.style.overflowY="auto",l=d);let h=a.bottom+s;h+l+i>r&&a.top-s-l>=i&&(h=a.top-s-l),h=Math.min(Math.max(h,i),Math.max(i,r-l-i));let u=a.right-o;u+o+i>n&&(u=n-o-i),u`${a} ${this.escapeHtml(i.label)}`).join("")}getVisibilityButtonIcon(e){return` ${e?'':''} @@ -619,41 +617,41 @@ ${s.map(n).join(",")}

    ${this.escapeHtml(r?.name||"Unknown Layer")}

    - `,u=[];r?.labelProperty&&u.push(r.labelProperty),Array.isArray(r?.labelPropertyFallbacks)&&u.push(...r.labelPropertyFallbacks),u.push("Name","name","NAME","FinalR_DEA","DEA","DEANAME","WARDNAME","LGDNAME","CONSTITUENCY","COUNTY","PARISH","BARONY");let p=new Set,f="";for(let H of u){if(!H||p.has(H))continue;p.add(H);let E=o[H];if(typeof E=="string"&&E.trim()){f=E.trim();break}}if(!f){let H=Object.entries(o).find(([E,k])=>typeof k=="string"&&k.trim()&&/(name|title|label|dea|ward|district|constituency|county)/i.test(E));H&&(f=H[1].trim())}f||(f="Unnamed Feature");let g=this.cacheFeatureDetailEntry(r,n,f,n.id||f);r?.id?h+=``:h+=`
    ${this.escapeHtml(f)}
    `;let y=o.Area||o.area||o.AREA||o.Shape_Area||o.SHAPE_AREA||o.Shape__Area||o.SHAPE__AREA,b=o.Perimeter||o.perimeter||o.PERIMETER,v=!1;if(l&&(!y||!b)){let H=this.calculateGeodesicMetrics(l);!y&&H.area&&(y=H.area,n.geometryIsClipped&&(v=!0)),!b&&H.perimeter&&(b=H.perimeter,n.geometryIsClipped&&(v=!0))}let w=v?"Part area":"Area",S=v?"Part perimeter":"Perimeter",M=o.minElev_m,C=o.maxElev_m,T=o.minElev_ft,V=o.maxElev_ft,z=o.meanElev_m,I=o.meanElev_ft;if((z==null||isNaN(z))&&M!==void 0&&M!==null&&!isNaN(M)&&C!==void 0&&C!==null&&!isNaN(C)&&(z=(Number(M)+Number(C))/2),(I==null||isNaN(I))&&z!==void 0&&z!==null&&!isNaN(z)&&(I=Math.round(Number(z)*3.28084)),y||b||M!==void 0&&C!==void 0){if(h+='
    ',y){let H=typeof y=="number"?y:parseFloat(y);if(Number.isFinite(H)&&H>1e5&&(H=H/1e6),!isNaN(H)){let E=H*.386102;h+=`
    + `,u=[];r?.labelProperty&&u.push(r.labelProperty),Array.isArray(r?.labelPropertyFallbacks)&&u.push(...r.labelPropertyFallbacks),u.push("Name","name","NAME","FinalR_DEA","DEA","DEANAME","WARDNAME","LGDNAME","CONSTITUENCY","COUNTY","PARISH","BARONY");let p=new Set,f="";for(let H of u){if(!H||p.has(H))continue;p.add(H);let M=o[H];if(typeof M=="string"&&M.trim()){f=M.trim();break}}if(!f){let H=Object.entries(o).find(([M,k])=>typeof k=="string"&&k.trim()&&/(name|title|label|dea|ward|district|constituency|county)/i.test(M));H&&(f=H[1].trim())}f||(f="Unnamed Feature");let g=this.cacheFeatureDetailEntry(r,n,f,n.id||f);r?.id?h+=``:h+=`
    ${this.escapeHtml(f)}
    `;let y=o.Area||o.area||o.AREA||o.Shape_Area||o.SHAPE_AREA||o.Shape__Area||o.SHAPE__AREA,b=o.Perimeter||o.perimeter||o.PERIMETER,v=!1;if(l&&(!y||!b)){let H=this.calculateGeodesicMetrics(l);!y&&H.area&&(y=H.area,n.geometryIsClipped&&(v=!0)),!b&&H.perimeter&&(b=H.perimeter,n.geometryIsClipped&&(v=!0))}let w=v?"Part area":"Area",S=v?"Part perimeter":"Perimeter",E=o.minElev_m,C=o.maxElev_m,T=o.minElev_ft,z=o.maxElev_ft,O=o.meanElev_m,I=o.meanElev_ft;if((O==null||isNaN(O))&&E!==void 0&&E!==null&&!isNaN(E)&&C!==void 0&&C!==null&&!isNaN(C)&&(O=(Number(E)+Number(C))/2),(I==null||isNaN(I))&&O!==void 0&&O!==null&&!isNaN(O)&&(I=Math.round(Number(O)*3.28084)),y||b||E!==void 0&&C!==void 0){if(h+='
    ',y){let H=typeof y=="number"?y:parseFloat(y);if(Number.isFinite(H)&&H>1e5&&(H=H/1e6),!isNaN(H)){let M=H*.386102;h+=`
    ${w} ${this.formatNumber(H,2)} km2
    - (${this.formatNumber(E,2)} sq mi) + (${this.formatNumber(M,2)} sq mi)
    -
    `}}if(b){let H=typeof b=="number"?b:parseFloat(b);if(Number.isFinite(H)&&H>1e5&&(H=H/1e3),!isNaN(H)){let E=H*.621371;h+=`
    +
    `}}if(b){let H=typeof b=="number"?b:parseFloat(b);if(Number.isFinite(H)&&H>1e5&&(H=H/1e3),!isNaN(H)){let M=H*.621371;h+=`
    ${S} ${this.formatNumber(H,2)} km
    - (${this.formatNumber(E,2)} mi) + (${this.formatNumber(M,2)} mi)
    -
    `}}M!=null&&!isNaN(M)&&(h+=`
    +
    `}}E!=null&&!isNaN(E)&&(h+=`
    Min Elevation - ${this.formatNumber(M,1)} m
    - (${T||Math.round(M*3.28084)} ft) + ${this.formatNumber(E,1)} m
    + (${T||Math.round(E*3.28084)} ft)
    -
    `),z!=null&&!isNaN(z)&&(h+=`
    +
    `),O!=null&&!isNaN(O)&&(h+=`
    Mean Elevation - ${this.formatNumber(z,1)} m
    - (${I||Math.round(z*3.28084)} ft) + ${this.formatNumber(O,1)} m
    + (${I||Math.round(O*3.28084)} ft)
    `),C!=null&&!isNaN(C)&&(h+=`
    Max Elevation ${this.formatNumber(C,1)} m
    - (${V||Math.round(C*3.28084)} ft) + (${z||Math.round(C*3.28084)} ft)
    -
    `),h+="
    "}let x=["Name","name","NAME","Area","area","AREA","Perimeter","perimeter","PERIMETER","geometry","minElev_m","maxElev_m","meanElev_m","minElev_ft","maxElev_ft","meanElev_ft"],B=Object.entries(o).filter(([H,E])=>!x.includes(H)&&E!==null&&E!==void 0&&E!=="");B.length>0&&(h+=` +
    `),h+="
    "}let x=["Name","name","NAME","Area","area","AREA","Perimeter","perimeter","PERIMETER","geometry","minElev_m","maxElev_m","meanElev_m","minElev_ft","maxElev_ft","meanElev_ft"],B=Object.entries(o).filter(([H,M])=>!x.includes(H)&&M!==null&&M!==void 0&&M!=="");B.length>0&&(h+=`
    All Properties (${B.length})
    - `,B.forEach(([H,E])=>{let k=typeof E=="number"?this.formatNumber(E):this.escapeHtml(String(E));h+=`
    + `,B.forEach(([H,M])=>{let k=typeof M=="number"?this.formatNumber(M):this.escapeHtml(String(M));h+=`
    ${this.escapeHtml(H)} ${k}
    `}),h+="
    "),d.innerHTML=h,i.appendChild(d)});let s=document.getElementById("featureInfoClose");s&&(s.onclick=()=>this.hideFeatureInfo()),i.querySelectorAll(".feature-info__metric--clickable").forEach(n=>{n.addEventListener("click",()=>{let o=(parseInt(n.dataset.precision)||2)===2?10:2;if(n.dataset.precision=o,n.dataset.areaKm){let l=parseFloat(n.dataset.areaKm),d=parseFloat(n.dataset.areaMi),h=n.querySelector(".metric-km"),u=n.querySelector(".metric-mi");h&&(h.textContent=`${this.formatNumber(l,o)} km2`),u&&(u.textContent=`(${this.formatNumber(d,o)} sq mi)`)}if(n.dataset.perimKm){let l=parseFloat(n.dataset.perimKm),d=parseFloat(n.dataset.perimMi),h=n.querySelector(".metric-km"),u=n.querySelector(".metric-mi");h&&(h.textContent=`${this.formatNumber(l,o)} km`),u&&(u.textContent=`(${this.formatNumber(d,o)} mi)`)}})}),i.querySelectorAll(".feature-info__primary-name-link").forEach(n=>{n.addEventListener("click",()=>{let r=n.dataset.featureDetailId;r&&this.showFeatureDetailInCatalogue(r)})}),a.classList.remove("hidden")}showFeatureDetailInCatalogue(e,t=!0){let a=this._featureDetailCache?.get(e);if(!a)return;let{feature:i,mapConfig:s,primaryName:n}=a,r=this._getActivePaneTabId();if(t){let I=this.catalogueHistory[this.catalogueHistoryIndex];if(I?.type==="feature-detail"&&I.detailId===e){this.updateCatalogueNavButtons(),this.updateCatalogueHomeButton();return}this._pushCatalogueTabHistoryIfNeeded(r),this._pushCatalogueHistoryEntry({type:"feature-detail",detailId:e})}r!=="catalogue"&&this.showTab("catalogue");let o=document.getElementById("catalogueDetailView"),l=document.getElementById("catalogueListView"),d=document.getElementById("catalogueNav");if(!o||!l||!d)return;d.classList.remove("hidden"),l.classList.add("hidden"),o.classList.remove("hidden"),this.catalogueView="detail",this.updateCatalogueNavButtons(),this.updateCatalogueHomeButton();let h=i?.properties||{},u=a?.electoralHistory||null,p=I=>I.isByElection?"catalogue-detail__entity-row--by-election":"",f=(I,x)=>` @@ -668,12 +666,12 @@ ${s.map(n).join(",")} data-election-entity-detail-kind="${this.escapeHtml(I)}" data-election-entity-detail-key="${this.escapeHtml(x)}"> ${this.escapeHtml(B)} - `,y=I=>`${At(I,x=>this.escapeHtml(x))}`,b=I=>I?.winnerParty?`${y(I.winnerParty)}`:"-",v=I=>{let x=I?.districtElectoralAreas||[];if(!x.length)return"-";let B=x.map(H=>g("dea",H,H)).join(", ");return` + `,y=I=>`${Ft(I,x=>this.escapeHtml(x))}`,b=I=>I?.winnerParty?`${y(I.winnerParty)}`:"-",v=I=>{let x=I?.districtElectoralAreas||[];if(!x.length)return"-";let B=x.map(H=>g("dea",H,H)).join(", ");return`
    Show DEAs (${x.length})
    ${B}
    - `},w=null,S=null,M=null;u?.kind==="dea"?(w="catalogue-feature-dea-history-table",M=u.historyRows||[],S=[{key:"electionDisplayName",label:"Election",kind:"text",getValue:I=>I.electionDisplayName,render:I=>f(I,I.electionDisplayName)},{key:"date",label:"Date",kind:"date",getValue:I=>I.date,render:I=>this.escapeHtml(be(I.date||""))},{key:"localGovernmentDistrict",label:"Local Government District",kind:"text",getValue:I=>I.localGovernmentDistrict,render:I=>g("lgd",I.localGovernmentDistrict,I.localGovernmentDistrict)},{key:"winnerParty",label:"Leading party",kind:"text",getValue:I=>I.winnerParty,render:I=>b(I)},{key:"winnerVotes",label:"Leading party votes",kind:"numeric",align:"num",getValue:I=>I.winnerVotes,render:I=>this.escapeHtml(this.formatDisplayValue(Math.round(Number(I.winnerVotes||0))))},{key:"winnerPct",label:"Leading party %",kind:"numeric",align:"num",getValue:I=>I.winnerPct,render:I=>`${Number(I.winnerPct||0).toFixed(2)}%`},{key:"validVotes",label:"Valid votes",kind:"numeric",align:"num",getValue:I=>I.validVotes,render:I=>this.escapeHtml(this.formatDisplayValue(Math.round(Number(I.validVotes||0))))},{key:"seats",label:"Seats",kind:"numeric",align:"num",getValue:I=>I.seats,render:I=>this.escapeHtml(this.formatDisplayValue(Math.round(Number(I.seats||0))))}]):u?.kind==="lgd"&&(w="catalogue-feature-lgd-history-table",M=u.historyRows||[],S=[{key:"electionDisplayName",label:"Election",kind:"text",getValue:I=>I.electionDisplayName,render:I=>f(I,I.electionDisplayName)},{key:"date",label:"Date",kind:"date",getValue:I=>I.date,render:I=>this.escapeHtml(be(I.date||""))},{key:"deaCount",label:"DEAs",kind:"numeric",align:"num",getValue:I=>I.deaCount,render:I=>this.escapeHtml(this.formatDisplayValue(Math.round(Number(I.deaCount||0))))},{key:"districtElectoralAreas",label:"District Electoral Areas",kind:"text",getValue:I=>(I.districtElectoralAreas||[]).join(", "),render:I=>v(I)},{key:"winnerParty",label:"Leading party",kind:"text",getValue:I=>I.winnerParty,render:I=>b(I)},{key:"winnerVotes",label:"Leading party votes",kind:"numeric",align:"num",getValue:I=>I.winnerVotes,render:I=>this.escapeHtml(this.formatDisplayValue(Math.round(Number(I.winnerVotes||0))))},{key:"winnerPct",label:"Leading party %",kind:"numeric",align:"num",getValue:I=>I.winnerPct,render:I=>`${Number(I.winnerPct||0).toFixed(2)}%`},{key:"validVotes",label:"Valid votes",kind:"numeric",align:"num",getValue:I=>I.validVotes,render:I=>this.escapeHtml(this.formatDisplayValue(Math.round(Number(I.validVotes||0))))},{key:"seats",label:"Seats",kind:"numeric",align:"num",getValue:I=>I.seats,render:I=>this.escapeHtml(this.formatDisplayValue(Math.round(Number(I.seats||0))))}]);let C=Object.entries(h).map(([I,x])=>` + `},w=null,S=null,E=null;u?.kind==="dea"?(w="catalogue-feature-dea-history-table",E=u.historyRows||[],S=[{key:"electionDisplayName",label:"Election",kind:"text",getValue:I=>I.electionDisplayName,render:I=>f(I,I.electionDisplayName)},{key:"date",label:"Date",kind:"date",getValue:I=>I.date,render:I=>this.escapeHtml(_e(I.date||""))},{key:"localGovernmentDistrict",label:"Local Government District",kind:"text",getValue:I=>I.localGovernmentDistrict,render:I=>g("lgd",I.localGovernmentDistrict,I.localGovernmentDistrict)},{key:"winnerParty",label:"Leading party",kind:"text",getValue:I=>I.winnerParty,render:I=>b(I)},{key:"winnerVotes",label:"Leading party votes",kind:"numeric",align:"num",getValue:I=>I.winnerVotes,render:I=>this.escapeHtml(this.formatDisplayValue(Math.round(Number(I.winnerVotes||0))))},{key:"winnerPct",label:"Leading party %",kind:"numeric",align:"num",getValue:I=>I.winnerPct,render:I=>`${Number(I.winnerPct||0).toFixed(2)}%`},{key:"validVotes",label:"Valid votes",kind:"numeric",align:"num",getValue:I=>I.validVotes,render:I=>this.escapeHtml(this.formatDisplayValue(Math.round(Number(I.validVotes||0))))},{key:"seats",label:"Seats",kind:"numeric",align:"num",getValue:I=>I.seats,render:I=>this.escapeHtml(this.formatDisplayValue(Math.round(Number(I.seats||0))))}]):u?.kind==="lgd"&&(w="catalogue-feature-lgd-history-table",E=u.historyRows||[],S=[{key:"electionDisplayName",label:"Election",kind:"text",getValue:I=>I.electionDisplayName,render:I=>f(I,I.electionDisplayName)},{key:"date",label:"Date",kind:"date",getValue:I=>I.date,render:I=>this.escapeHtml(_e(I.date||""))},{key:"deaCount",label:"DEAs",kind:"numeric",align:"num",getValue:I=>I.deaCount,render:I=>this.escapeHtml(this.formatDisplayValue(Math.round(Number(I.deaCount||0))))},{key:"districtElectoralAreas",label:"District Electoral Areas",kind:"text",getValue:I=>(I.districtElectoralAreas||[]).join(", "),render:I=>v(I)},{key:"winnerParty",label:"Leading party",kind:"text",getValue:I=>I.winnerParty,render:I=>b(I)},{key:"winnerVotes",label:"Leading party votes",kind:"numeric",align:"num",getValue:I=>I.winnerVotes,render:I=>this.escapeHtml(this.formatDisplayValue(Math.round(Number(I.winnerVotes||0))))},{key:"winnerPct",label:"Leading party %",kind:"numeric",align:"num",getValue:I=>I.winnerPct,render:I=>`${Number(I.winnerPct||0).toFixed(2)}%`},{key:"validVotes",label:"Valid votes",kind:"numeric",align:"num",getValue:I=>I.validVotes,render:I=>this.escapeHtml(this.formatDisplayValue(Math.round(Number(I.validVotes||0))))},{key:"seats",label:"Seats",kind:"numeric",align:"num",getValue:I=>I.seats,render:I=>this.escapeHtml(this.formatDisplayValue(Math.round(Number(I.seats||0))))}]);let C=Object.entries(h).map(([I,x])=>`
    ${this.escapeHtml(I)} ${this.escapeHtml(this.formatDisplayValue(x))} @@ -716,13 +714,13 @@ ${s.map(n).join(",")}
    - ${S&&M?` + ${S&&E?`
    -
    Electoral History (${M.length})
    +
    Electoral History (${E.length})
    ${this._buildEntityTableMarkup(w,S)}
    `:""}
    ${C||'
    No properties
    '}
    - `;let T=this.getFeatureBBox(i?.geometry);o.querySelector(".feature-load-btn")?.addEventListener("click",async I=>{let x=s?.id,B=i?.id;if(!x||B===void 0||B===null)return;(this.onCheckFeatureLoaded?!!this.onCheckFeatureLoaded(x,B):!1)?this.onPartialFeatureUnload?.(x,B):this.onFeatureLoad&&await this.onFeatureLoad(x,B,n,T),this.syncFeatureDetailActionButtons(o,e)}),o.querySelector(".feature-visibility-btn")?.addEventListener("click",()=>{let I=s?.id,x=i?.id;!I||x===void 0||x===null||(this.onPartialFeatureToggle&&this.onPartialFeatureToggle(I,x),this.syncFeatureDetailActionButtons(o,e))}),o.querySelector(".feature-copy-url-btn")?.addEventListener("click",I=>{this.copyFeatureUrl(e,I.currentTarget)}),o.querySelector(".feature-download-fgb-btn")?.addEventListener("click",()=>{this.downloadFeature(e,"fgb")});let V=o.querySelector(".feature-download-dropdown");o.querySelector(".feature-download-menu-btn")?.addEventListener("click",I=>{I.stopPropagation(),V&&this.toggleDownloadDropdown(V,I.currentTarget)}),o.querySelectorAll(".feature-download-alt-btn").forEach(I=>{I.addEventListener("click",x=>{x.stopPropagation(),this.downloadFeature(e,I.dataset.format),V&&this.closeDownloadDropdown(V)})}),S&&M&&this._initEntityDataTable(o,w,S,M,{rowClassNameFn:p}),o._featureDetailClickHandler&&o.removeEventListener("click",o._featureDetailClickHandler),o._featureDetailClickHandler=async I=>{let x=I.target.closest("[data-election-body][data-election-date]");if(x){I.preventDefault(),this.onElectionEntityElectionOpen?.({body:x.dataset.electionBody,date:x.dataset.electionDate,constituency:x.dataset.electionConstituency||null});return}let B=I.target.closest("[data-election-entity-detail-kind][data-election-entity-detail-key]");B&&(I.preventDefault(),this.onOpenElectionEntityDetail?.(B.dataset.electionEntityDetailKind,B.dataset.electionEntityDetailKey))},o.addEventListener("click",o._featureDetailClickHandler),this.syncFeatureDetailActionButtons(o,e),(this._cataloguePane||document.querySelector('.pane__content[data-tab-content="catalogue"]'))?.scrollTo({top:0,behavior:"auto"}),this.updateCatalogueNavButtons()}_buildEntityGroupedHeaderMarkup(e){let t=Array.isArray(e.headerRows)?e.headerRows:[];return t.map((a,i)=>` + `;let T=this.getFeatureBBox(i?.geometry);o.querySelector(".feature-load-btn")?.addEventListener("click",async I=>{let x=s?.id,B=i?.id;if(!x||B===void 0||B===null)return;(this.onCheckFeatureLoaded?!!this.onCheckFeatureLoaded(x,B):!1)?this.onPartialFeatureUnload?.(x,B):this.onFeatureLoad&&await this.onFeatureLoad(x,B,n,T),this.syncFeatureDetailActionButtons(o,e)}),o.querySelector(".feature-visibility-btn")?.addEventListener("click",()=>{let I=s?.id,x=i?.id;!I||x===void 0||x===null||(this.onPartialFeatureToggle&&this.onPartialFeatureToggle(I,x),this.syncFeatureDetailActionButtons(o,e))}),o.querySelector(".feature-copy-url-btn")?.addEventListener("click",I=>{this.copyFeatureUrl(e,I.currentTarget)}),o.querySelector(".feature-download-fgb-btn")?.addEventListener("click",()=>{this.downloadFeature(e,"fgb")});let z=o.querySelector(".feature-download-dropdown");o.querySelector(".feature-download-menu-btn")?.addEventListener("click",I=>{I.stopPropagation(),z&&this.toggleDownloadDropdown(z,I.currentTarget)}),o.querySelectorAll(".feature-download-alt-btn").forEach(I=>{I.addEventListener("click",x=>{x.stopPropagation(),this.downloadFeature(e,I.dataset.format),z&&this.closeDownloadDropdown(z)})}),S&&E&&this._initEntityDataTable(o,w,S,E,{rowClassNameFn:p}),o._featureDetailClickHandler&&o.removeEventListener("click",o._featureDetailClickHandler),o._featureDetailClickHandler=async I=>{let x=I.target.closest("[data-election-body][data-election-date]");if(x){I.preventDefault(),this.onElectionEntityElectionOpen?.({body:x.dataset.electionBody,date:x.dataset.electionDate,constituency:x.dataset.electionConstituency||null});return}let B=I.target.closest("[data-election-entity-detail-kind][data-election-entity-detail-key]");B&&(I.preventDefault(),this.onOpenElectionEntityDetail?.(B.dataset.electionEntityDetailKind,B.dataset.electionEntityDetailKey))},o.addEventListener("click",o._featureDetailClickHandler),this.syncFeatureDetailActionButtons(o,e),(this._cataloguePane||document.querySelector('.pane__content[data-tab-content="catalogue"]'))?.scrollTo({top:0,behavior:"auto"}),this.updateCatalogueNavButtons()}_buildEntityGroupedHeaderMarkup(e){let t=Array.isArray(e.headerRows)?e.headerRows:[];return t.map((a,i)=>` ${a.map(s=>{let n=[];s.align==="num"&&n.push("catalogue-detail__entity-num"),s.leafIndex!==void 0&&s.leafIndex!==null&&n.push("catalogue-detail__entity-header-leaf");let r=[s.colspan?`colspan="${Number(s.colspan)}"`:"",s.rowspan?`rowspan="${Number(s.rowspan)}"`:"",s.leafIndex!==void 0&&s.leafIndex!==null?`data-leaf-col-idx="${Number(s.leafIndex)}"`:"",s.leafIndex!==void 0&&s.leafIndex!==null?`data-leaf-label="${this.escapeHtml(s.label||"")}"`:""].filter(Boolean).join(" ");return`${this.escapeHtml(s.label||"")}`}).join("")} @@ -749,9 +747,9 @@ ${s.map(n).join(",")} `).join("")} - `}).join(""):`No rows`}_getEntityTableFilterValue(e,t){let a=t.filterValue?t.filterValue(e):t.getValue?t.getValue(e):e[t.key];return a==null||a===""?"":String(a)}_compareEntityTableValues(e,t,a,i){let s=a.kind||"text",n=a.getValue?a.getValue(e):e[a.key],r=a.getValue?a.getValue(t):t[a.key],o=i==="asc"?1:-1;if(s==="numeric"||s==="ordinal"||s==="date"){let h=s==="date"?Date.parse(n):Number(n),u=s==="date"?Date.parse(r):Number(r),p=Number.isFinite(h),f=Number.isFinite(u);if(p&&f)return(h-u)*o;if(p)return-1;if(f)return 1}let l=n==null?"":String(n),d=r==null?"":String(r);return l.localeCompare(d,void 0,{numeric:!0,sensitivity:"base"})*o}_initEntityDataTable(e,t,a,i,s={}){let n=e.querySelector(`[data-entity-table-id="${t}"]`);if(!n)return;let r=[...n.querySelectorAll("thead th[data-leaf-col-idx]")],o=n.querySelector("tbody"),l={filters:new Map,sort:{key:null,dir:"default"},activeMenu:null,activeMenuBtn:null,documentClickHandler:null,filteredRows:[...i]},d=()=>{l.activeMenu&&l.activeMenu.remove(),l.activeMenuBtn&&l.activeMenuBtn.classList.remove("election-th-btn--open"),l.documentClickHandler&&(document.removeEventListener("click",l.documentClickHandler),l.documentClickHandler=null),l.activeMenu=null,l.activeMenuBtn=null},h=()=>{o.innerHTML=this._renderEntityTableRows(a,l.filteredRows,s.rowClassNameFn),r.forEach((f,g)=>{let y=f.querySelector("[data-table-filter-sort-btn]");if(!y)return;let b=a[g],v=l.filters.has(b.key)&&(l.filters.get(b.key)?.size??0)>0,w=l.sort.key===b.key&&l.sort.dir!=="default";y.classList.toggle("election-th-btn--active",v||w),w&&l.sort.dir==="asc"?y.innerHTML="↑":w&&l.sort.dir==="desc"?y.innerHTML="↓":y.innerHTML="⇅"})},u=()=>{let f=i.filter(g=>{for(let[y,b]of l.filters.entries()){if(!(b instanceof Set)||b.size===0)continue;let v=a.find(w=>w.key===y);if(v&&!b.has(this._getEntityTableFilterValue(g,v)))return!1}return!0});if(l.sort.key&&l.sort.dir!=="default"){let g=a.find(y=>y.key===l.sort.key);g&&(f=[...f].sort((y,b)=>{let v=this._compareEntityTableValues(y,b,g,l.sort.dir);return v!==0?v:i.indexOf(y)-i.indexOf(b)}))}l.filteredRows=f,h()},p=(f,g)=>{d();let y=[...new Set(i.map(J=>this._getEntityTableFilterValue(J,f)))].sort((J,se)=>J.localeCompare(se,void 0,{numeric:!0,sensitivity:"base"})),b=l.filters.get(f.key),v=new Set(b instanceof Set?b:y),w=f.kind||"text",S=w==="numeric"?"Sort Smallest to Largest":w==="ordinal"||w==="date"?"Sort Lowest to Highest":"Sort A to Z",M=w==="numeric"?"Sort Largest to Smallest":w==="ordinal"||w==="date"?"Sort Highest to Lowest":"Sort Z to A",C=document.createElement("div");C.className="election-filter-menu",C.innerHTML=` + `}).join(""):`No rows`}_getEntityTableFilterValue(e,t){let a=t.filterValue?t.filterValue(e):t.getValue?t.getValue(e):e[t.key];return a==null||a===""?"":String(a)}_compareEntityTableValues(e,t,a,i){let s=a.kind||"text",n=a.getValue?a.getValue(e):e[a.key],r=a.getValue?a.getValue(t):t[a.key],o=i==="asc"?1:-1;if(s==="numeric"||s==="ordinal"||s==="date"){let h=s==="date"?Date.parse(n):Number(n),u=s==="date"?Date.parse(r):Number(r),p=Number.isFinite(h),f=Number.isFinite(u);if(p&&f)return(h-u)*o;if(p)return-1;if(f)return 1}let l=n==null?"":String(n),d=r==null?"":String(r);return l.localeCompare(d,void 0,{numeric:!0,sensitivity:"base"})*o}_initEntityDataTable(e,t,a,i,s={}){let n=e.querySelector(`[data-entity-table-id="${t}"]`);if(!n)return;let r=[...n.querySelectorAll("thead th[data-leaf-col-idx]")],o=n.querySelector("tbody"),l={filters:new Map,sort:{key:null,dir:"default"},activeMenu:null,activeMenuBtn:null,documentClickHandler:null,filteredRows:[...i]},d=()=>{l.activeMenu&&l.activeMenu.remove(),l.activeMenuBtn&&l.activeMenuBtn.classList.remove("election-th-btn--open"),l.documentClickHandler&&(document.removeEventListener("click",l.documentClickHandler),l.documentClickHandler=null),l.activeMenu=null,l.activeMenuBtn=null},h=()=>{o.innerHTML=this._renderEntityTableRows(a,l.filteredRows,s.rowClassNameFn),r.forEach((f,g)=>{let y=f.querySelector("[data-table-filter-sort-btn]");if(!y)return;let b=a[g],v=l.filters.has(b.key)&&(l.filters.get(b.key)?.size??0)>0,w=l.sort.key===b.key&&l.sort.dir!=="default";y.classList.toggle("election-th-btn--active",v||w),w&&l.sort.dir==="asc"?y.innerHTML="↑":w&&l.sort.dir==="desc"?y.innerHTML="↓":y.innerHTML="⇅"})},u=()=>{let f=i.filter(g=>{for(let[y,b]of l.filters.entries()){if(!(b instanceof Set)||b.size===0)continue;let v=a.find(w=>w.key===y);if(v&&!b.has(this._getEntityTableFilterValue(g,v)))return!1}return!0});if(l.sort.key&&l.sort.dir!=="default"){let g=a.find(y=>y.key===l.sort.key);g&&(f=[...f].sort((y,b)=>{let v=this._compareEntityTableValues(y,b,g,l.sort.dir);return v!==0?v:i.indexOf(y)-i.indexOf(b)}))}l.filteredRows=f,h()},p=(f,g)=>{d();let y=[...new Set(i.map(J=>this._getEntityTableFilterValue(J,f)))].sort((J,ae)=>J.localeCompare(ae,void 0,{numeric:!0,sensitivity:"base"})),b=l.filters.get(f.key),v=new Set(b instanceof Set?b:y),w=f.kind||"text",S=w==="numeric"?"Sort Smallest to Largest":w==="ordinal"||w==="date"?"Sort Lowest to Highest":"Sort A to Z",E=w==="numeric"?"Sort Largest to Smallest":w==="ordinal"||w==="date"?"Sort Highest to Lowest":"Sort Z to A",C=document.createElement("div");C.className="election-filter-menu",C.innerHTML=` - +
    @@ -764,7 +762,7 @@ ${s.map(n).join(",")} - `,document.body.appendChild(C),l.activeMenu=C,l.activeMenuBtn=g,g.classList.add("election-th-btn--open");let T=g.getBoundingClientRect(),V=248,z=8,I=window.scrollX||window.pageXOffset||0,x=window.scrollY||window.pageYOffset||0,B=I+T.right-V,H=I+window.innerWidth-V-z;C.style.left=`${Math.max(I+z,Math.min(B,H))}px`;let E=C.offsetHeight||320,k=x+T.bottom+4,N=x+T.top-E-4,U=x+window.innerHeight-z,K=x+z,G=k+E<=U,j=N>=K;C.style.top=`${G||!j?k:N}px`;let m=C.querySelector('[data-role="values"]'),D=(J="")=>{let se=J.trim().toLowerCase();m.innerHTML="",y.filter(ee=>!se||ee.toLowerCase().includes(se)).forEach(ee=>{let he=document.createElement("label");he.className="election-filter-menu__value",he.innerHTML=`${this.escapeHtml(ee||"(Blank)")}`;let ce=he.querySelector("input");ce.addEventListener("change",()=>{ce.checked?v.add(ee):v.delete(ee)}),m.appendChild(he)})};D();let q=C.querySelector(".election-filter-menu__search");q?.addEventListener("input",()=>D(q.value||"")),C.addEventListener("click",J=>{let se=J.target.closest("button[data-action]");if(!se)return;let ee=se.dataset.action;ee==="sort-asc"?(l.sort.key=f.key,l.sort.dir="asc",u(),d()):ee==="sort-desc"?(l.sort.key=f.key,l.sort.dir="desc",u(),d()):ee==="reset-sort"?(l.sort.key=null,l.sort.dir="default",u(),d()):ee==="select-all"?(y.forEach(he=>v.add(he)),D(q?.value||"")):ee==="deselect-all"?(v.clear(),D(q?.value||"")):ee==="clear-filter"?(l.filters.delete(f.key),u(),d()):ee==="apply"&&(v.size===0||v.size===y.length?l.filters.delete(f.key):l.filters.set(f.key,new Set(v)),u(),d())}),l.documentClickHandler=J=>{l.activeMenu&&(l.activeMenu.contains(J.target)||l.activeMenuBtn&&l.activeMenuBtn.contains(J.target)||d())},document.addEventListener("click",l.documentClickHandler)};r.forEach((f,g)=>{let y=Number(f.dataset.leafColIdx),b=a[Number.isFinite(y)?y:g];if(!b)return;let v=f.dataset.leafLabel||b.label;f.innerHTML="";let w=document.createElement("div");w.className="election-th-controls";let S=document.createElement("span");S.className="election-th-label",S.textContent=v,w.appendChild(S);let M=document.createElement("span");M.className="election-th-actions";let C=document.createElement("button");C.type="button",C.className="election-th-btn",C.setAttribute("data-table-filter-sort-btn","1"),C.setAttribute("aria-label","Sort and Filter"),C.setAttribute("title","Sort and Filter"),C.innerHTML="⇅",C.addEventListener("click",T=>{T.preventDefault(),T.stopPropagation(),l.activeMenu&&l.activeMenuBtn===C?d():p(b,C)}),M.appendChild(C),w.appendChild(M),f.appendChild(w)}),u()}_formatEntityDelta(e,t=0,a=""){if(e==null||Number.isNaN(Number(e)))return'-';let i=Number(e);if(i===0)return'-';let s=i>0?"catalogue-detail__delta--positive":"catalogue-detail__delta--negative",n=Math.abs(i).toLocaleString(void 0,{minimumFractionDigits:t,maximumFractionDigits:t}),r=i>0?"+":"-";return`${r}${n}${a}`}_formatEntityRankDelta(e){if(e==null||Number.isNaN(Number(e))||Number(e)===0)return'-';let t=Number(e),a=t>0?"up":"down",i=t>0?"▲":"▼";return`${i} ${Math.abs(t)}`}_renderConstituencyEntryList(e=[]){return!Array.isArray(e)||e.length===0?"-":e.map(t=>{let a=t.constituency&&t.constituency!=="Northern Ireland"&&t.mapLayerYear,i=`${t.constituency||"-"}${a?` (${t.mapLayerYear})`:""}`,s=` + `,document.body.appendChild(C),l.activeMenu=C,l.activeMenuBtn=g,g.classList.add("election-th-btn--open");let T=g.getBoundingClientRect(),z=248,O=8,I=window.scrollX||window.pageXOffset||0,x=window.scrollY||window.pageYOffset||0,B=I+T.right-z,H=I+window.innerWidth-z-O;C.style.left=`${Math.max(I+O,Math.min(B,H))}px`;let M=C.offsetHeight||320,k=x+T.bottom+4,N=x+T.top-M-4,V=x+window.innerHeight-O,K=x+O,G=k+M<=V,j=N>=K;C.style.top=`${G||!j?k:N}px`;let m=C.querySelector('[data-role="values"]'),D=(J="")=>{let ae=J.trim().toLowerCase();m.innerHTML="",y.filter(te=>!ae||te.toLowerCase().includes(ae)).forEach(te=>{let ue=document.createElement("label");ue.className="election-filter-menu__value",ue.innerHTML=`${this.escapeHtml(te||"(Blank)")}`;let ye=ue.querySelector("input");ye.addEventListener("change",()=>{ye.checked?v.add(te):v.delete(te)}),m.appendChild(ue)})};D();let q=C.querySelector(".election-filter-menu__search");q?.addEventListener("input",()=>D(q.value||"")),C.addEventListener("click",J=>{let ae=J.target.closest("button[data-action]");if(!ae)return;let te=ae.dataset.action;te==="sort-asc"?(l.sort.key=f.key,l.sort.dir="asc",u(),d()):te==="sort-desc"?(l.sort.key=f.key,l.sort.dir="desc",u(),d()):te==="reset-sort"?(l.sort.key=null,l.sort.dir="default",u(),d()):te==="select-all"?(y.forEach(ue=>v.add(ue)),D(q?.value||"")):te==="deselect-all"?(v.clear(),D(q?.value||"")):te==="clear-filter"?(l.filters.delete(f.key),u(),d()):te==="apply"&&(v.size===0||v.size===y.length?l.filters.delete(f.key):l.filters.set(f.key,new Set(v)),u(),d())}),l.documentClickHandler=J=>{l.activeMenu&&(l.activeMenu.contains(J.target)||l.activeMenuBtn&&l.activeMenuBtn.contains(J.target)||d())},document.addEventListener("click",l.documentClickHandler)};r.forEach((f,g)=>{let y=Number(f.dataset.leafColIdx),b=a[Number.isFinite(y)?y:g];if(!b)return;let v=f.dataset.leafLabel||b.label;f.innerHTML="";let w=document.createElement("div");w.className="election-th-controls";let S=document.createElement("span");S.className="election-th-label",S.textContent=v,w.appendChild(S);let E=document.createElement("span");E.className="election-th-actions";let C=document.createElement("button");C.type="button",C.className="election-th-btn",C.setAttribute("data-table-filter-sort-btn","1"),C.setAttribute("aria-label","Sort and Filter"),C.setAttribute("title","Sort and Filter"),C.innerHTML="⇅",C.addEventListener("click",T=>{T.preventDefault(),T.stopPropagation(),l.activeMenu&&l.activeMenuBtn===C?d():p(b,C)}),E.appendChild(C),w.appendChild(E),f.appendChild(w)}),u()}_formatEntityDelta(e,t=0,a=""){if(e==null||Number.isNaN(Number(e)))return'-';let i=Number(e);if(i===0)return'-';let s=i>0?"catalogue-detail__delta--positive":"catalogue-detail__delta--negative",n=Math.abs(i).toLocaleString(void 0,{minimumFractionDigits:t,maximumFractionDigits:t}),r=i>0?"+":"-";return`${r}${n}${a}`}_formatEntityRankDelta(e){if(e==null||Number.isNaN(Number(e))||Number(e)===0)return'-';let t=Number(e),a=t>0?"up":"down",i=t>0?"▲":"▼";return`${i} ${Math.abs(t)}`}_renderConstituencyEntryList(e=[]){return!Array.isArray(e)||e.length===0?"-":e.map(t=>{let a=t.constituency&&t.constituency!=="Northern Ireland"&&t.mapLayerYear,i=`${t.constituency||"-"}${a?` (${t.mapLayerYear})`:""}`,s=` ${this.escapeHtml(i)} - `;return t.elected?`${s}`:s}).join(", ")}showElectionEntityDetailInCatalogue(e,t=!0){let a=typeof e=="string"?e:this.cacheElectionEntityDetailEntry(e),i=this._electionEntityDetailCache?.get(a);if(!i||!a)return;let s=this._getActivePaneTabId();if(t){let m=this.catalogueHistory[this.catalogueHistoryIndex];if(m?.type==="election-entity-detail"&&m.detailId===a){this.updateCatalogueNavButtons(),this.updateCatalogueHomeButton();return}this._pushCatalogueTabHistoryIfNeeded(s),this._pushCatalogueHistoryEntry({type:"election-entity-detail",detailId:a})}s!=="catalogue"&&this.showTab("catalogue");let n=document.getElementById("catalogueDetailView"),r=document.getElementById("catalogueListView"),o=document.getElementById("catalogueNav");if(!n||!r||!o)return;o.classList.remove("hidden"),r.classList.add("hidden"),n.classList.remove("hidden"),this.catalogueView="detail",this.updateCatalogueNavButtons(),this.updateCatalogueHomeButton();let l=m=>this.formatNumber(Math.round(Number(m)||0),0),d=m=>`${Number(m||0).toFixed(2)}%`,h=m=>{let D=new Date(`${m}T00:00:00`);if(Number.isNaN(D.getTime()))return String(m||"");let q=String(D.getDate()).padStart(2,"0"),J=D.toLocaleDateString("en-GB",{month:"short"}),se=D.getFullYear();return`${q} ${J} ${se}`},u=m=>{let D=Number(m||0);return D?D%10===1&&D%100!==11?`${D}st`:D%10===2&&D%100!==12?`${D}nd`:D%10===3&&D%100!==13?`${D}rd`:`${D}th`:"-"},p=(m,D,q=!1)=>` + `;return t.elected?`${s}`:s}).join(", ")}showElectionEntityDetailInCatalogue(e,t=!0){let a=typeof e=="string"?e:this.cacheElectionEntityDetailEntry(e),i=this._electionEntityDetailCache?.get(a);if(!i||!a)return;let s=this._getActivePaneTabId();if(t){let m=this.catalogueHistory[this.catalogueHistoryIndex];if(m?.type==="election-entity-detail"&&m.detailId===a){this.updateCatalogueNavButtons(),this.updateCatalogueHomeButton();return}this._pushCatalogueTabHistoryIfNeeded(s),this._pushCatalogueHistoryEntry({type:"election-entity-detail",detailId:a})}s!=="catalogue"&&this.showTab("catalogue");let n=document.getElementById("catalogueDetailView"),r=document.getElementById("catalogueListView"),o=document.getElementById("catalogueNav");if(!n||!r||!o)return;o.classList.remove("hidden"),r.classList.add("hidden"),n.classList.remove("hidden"),this.catalogueView="detail",this.updateCatalogueNavButtons(),this.updateCatalogueHomeButton();let l=m=>this.formatNumber(Math.round(Number(m)||0),0),d=m=>`${Number(m||0).toFixed(2)}%`,h=m=>{let D=new Date(`${m}T00:00:00`);if(Number.isNaN(D.getTime()))return String(m||"");let q=String(D.getDate()).padStart(2,"0"),J=D.toLocaleDateString("en-GB",{month:"short"}),ae=D.getFullYear();return`${q} ${J} ${ae}`},u=m=>{let D=Number(m||0);return D?D%10===1&&D%100!==11?`${D}st`:D%10===2&&D%100!==12?`${D}nd`:D%10===3&&D%100!==13?`${D}rd`:`${D}th`:"-"},p=(m,D,q=!1)=>` ${this.escapeHtml(q)} - `,g=m=>`${At(m,D=>this.escapeHtml(D))}`,y=m=>m?.winnerParty?`${g(m.winnerParty)}`:"-",b=m=>{let D=m?.districtElectoralAreas||[];if(!D.length)return"-";let q=D.map(J=>f("dea",J,J)).join(", ");return` + `,g=m=>`${Ft(m,D=>this.escapeHtml(D))}`,y=m=>m?.winnerParty?`${g(m.winnerParty)}`:"-",b=m=>{let D=m?.districtElectoralAreas||[];if(!D.length)return"-";let q=D.map(J=>f("dea",J,J)).join(", ");return`
    Show DEAs (${D.length})
    ${q}
    - `},v=i.kind==="candidate",w=i.kind==="party",S=i.kind==="dea"||i.kind==="lgd"||i.kind==="constituency",M=v?i.name||i.personId:i.name,C=v?`${i.latestParty||(i.parties||[]).join(", ")||"Independent"}`:S?i.subtitle||"":w?"Political Party":"",T=v?`Candidate | Person ID ${this.escapeHtml(i.personId||"")}`:w?"Political Party":"Electoral Geography",z=(v?[["Latest party",i.latestParty||"Independent"],["1st prefs",l(i.firstPrefs)],["% of all valid votes",d(i.shareOfAllValid)],["Election wins",l(i.electedCount)],["Elections contested",l((i.appearances||[]).length)],["Constituencies",l((i.constituencies||[]).length)]]:w?[["MPs",{value:l(i.latestWestminster?.elected||0),subtext:i.latestWestminster?.date?be(i.latestWestminster.date):""}],["Last Westminster result",i.latestWestminster?d(i.latestWestminster.validVotePct):"N/A"],["Last Westminster votes",i.latestWestminster?l(i.latestWestminster.firstPrefs):"N/A"],["MLAs",{value:l(i.latestAssembly?.elected||0),subtext:i.latestAssembly?.date?be(i.latestAssembly.date):""}],["Last Assembly result",i.latestAssembly?d(i.latestAssembly.validVotePct):"N/A"],["Last Assembly 1st prefs",i.latestAssembly?l(i.latestAssembly.firstPrefs):"N/A"]]:i.kind==="constituency"?[["Elections",l(i.metrics?.elections||0)],["Total valid votes",l(i.metrics?.totalValidVotes||0)],["Total seats",l(i.metrics?.totalSeats||0)],["Latest election",i.metrics?.latestDate?this.escapeHtml(be(i.metrics.latestDate)):"N/A"],["Area type",this.escapeHtml(i.subtitle||"Constituency")]]:[["Elections",l(i.metrics?.elections||0)],[i.kind==="dea"?"Districts":"DEAs",l(i.kind==="dea"?i.metrics?.districts||0:i.metrics?.deas||0)],["Total valid votes",l(i.metrics?.totalValidVotes||0)],["Total seats",l(i.metrics?.totalSeats||0)],["Latest election",i.metrics?.latestDate?this.escapeHtml(be(i.metrics.latestDate)):"N/A"],[i.kind==="dea"?"Area type":"Body type",this.escapeHtml(i.subtitle||"")]]).map(([m,D])=>` + `},v=i.kind==="candidate",w=i.kind==="party",S=i.kind==="dea"||i.kind==="lgd"||i.kind==="constituency",E=v?i.name||i.personId:i.name,C=v?`${i.latestParty||(i.parties||[]).join(", ")||"Independent"}`:S?i.subtitle||"":w?"Political Party":"",T=v?`Candidate | Person ID ${this.escapeHtml(i.personId||"")}`:w?"Political Party":"Electoral Geography",O=(v?[["Latest party",i.latestParty||"Independent"],["1st prefs",l(i.firstPrefs)],["% of all valid votes",d(i.shareOfAllValid)],["Election wins",l(i.electedCount)],["Elections contested",l((i.appearances||[]).length)],["Constituencies",l((i.constituencies||[]).length)]]:w?[["MPs",{value:l(i.latestWestminster?.elected||0),subtext:i.latestWestminster?.date?_e(i.latestWestminster.date):""}],["Last Westminster result",i.latestWestminster?d(i.latestWestminster.validVotePct):"N/A"],["Last Westminster votes",i.latestWestminster?l(i.latestWestminster.firstPrefs):"N/A"],["MLAs",{value:l(i.latestAssembly?.elected||0),subtext:i.latestAssembly?.date?_e(i.latestAssembly.date):""}],["Last Assembly result",i.latestAssembly?d(i.latestAssembly.validVotePct):"N/A"],["Last Assembly 1st prefs",i.latestAssembly?l(i.latestAssembly.firstPrefs):"N/A"]]:i.kind==="constituency"?[["Elections",l(i.metrics?.elections||0)],["Total valid votes",l(i.metrics?.totalValidVotes||0)],["Total seats",l(i.metrics?.totalSeats||0)],["Latest election",i.metrics?.latestDate?this.escapeHtml(_e(i.metrics.latestDate)):"N/A"],["Area type",this.escapeHtml(i.subtitle||"Constituency")]]:[["Elections",l(i.metrics?.elections||0)],[i.kind==="dea"?"Districts":"DEAs",l(i.kind==="dea"?i.metrics?.districts||0:i.metrics?.deas||0)],["Total valid votes",l(i.metrics?.totalValidVotes||0)],["Total seats",l(i.metrics?.totalSeats||0)],["Latest election",i.metrics?.latestDate?this.escapeHtml(_e(i.metrics.latestDate)):"N/A"],[i.kind==="dea"?"Area type":"Body type",this.escapeHtml(i.subtitle||"")]]).map(([m,D])=>`
    ${this.escapeHtml(m)} ${typeof D=="object"?`${this.escapeHtml(D.value||"")}${D.subtext?`${this.escapeHtml(D.subtext)}`:""}`:this.escapeHtml(D)} @@ -803,7 +801,7 @@ ${s.map(n).join(",")} ${this.escapeHtml(m)} ${q?D||"-":this.escapeHtml(D||"-")}
    - `).join(""),B=(m,D)=>m?.isRecallPetition?"-":D,H=(i.candidateSummaries||[]).map((m,D)=>({...m,candidateRank:D+1})),E=[{key:"electionDisplayName",label:"Election",kind:"text",getValue:m=>m.electionDisplayName,render:m=>p(m,m.electionDisplayName,!1)},{key:"date",label:"Date",kind:"date",getValue:m=>m.date,render:m=>this.escapeHtml(h(m.date||""))},{key:"electionType",label:"Type",kind:"text",getValue:m=>m.electionType||"-",render:m=>this.escapeHtml(m.electionType||"-")},{key:"rank",label:"#",kind:"ordinal",align:"num",getValue:m=>m.rank,render:m=>B(m,m.contested?u(m.rank):"-")},{key:"rankDelta",label:"+/-",kind:"ordinal",align:"num",getValue:m=>m.rankDelta,render:m=>B(m,this._formatEntityRankDelta(m.rankDelta))},{key:"elected",label:"Seats won",kind:"numeric",align:"num",getValue:m=>m.elected,render:m=>B(m,m.contested?l(m.elected):"-")},{key:"electedDelta",label:"+/-",kind:"numeric",align:"num",getValue:m=>m.electedDelta,render:m=>B(m,this._formatEntityDelta(m.electedDelta))},{key:"seatPct",label:"% seats won",kind:"numeric",align:"num",getValue:m=>m.seatPct,render:m=>B(m,m.contested?d(m.seatPct):"-")},{key:"seatPctDelta",label:"+/-",kind:"numeric",align:"num",getValue:m=>m.seatPctDelta,render:m=>B(m,this._formatEntityDelta(m.seatPctDelta,2,"%"))},{key:"totalSeats",label:"Total seats",kind:"numeric",align:"num",getValue:m=>m.totalSeats,render:m=>B(m,l(m.totalSeats))},{key:"totalSeatsDelta",label:"+/-",kind:"numeric",align:"num",getValue:m=>m.totalSeatsDelta,render:m=>B(m,m.isByElection?"-":this._formatEntityDelta(m.totalSeatsDelta))},{key:"stood",label:"Candidates stood",kind:"numeric",align:"num",getValue:m=>m.stood,filterValue:m=>m.contested?m.stood:"N/A",render:m=>B(m,m.contested?l(m.stood):"N/A")},{key:"stoodDelta",label:"+/-",kind:"numeric",align:"num",getValue:m=>m.stoodDelta,render:m=>B(m,this._formatEntityDelta(m.stoodDelta))},{key:"constituenciesContested",label:"Constituencies",kind:"numeric",align:"num",getValue:m=>m.constituenciesContested,render:m=>B(m,l(m.constituenciesContested))},{key:"constituenciesContestedDelta",label:"+/-",kind:"numeric",align:"num",getValue:m=>m.constituenciesContestedDelta,render:m=>B(m,this._formatEntityDelta(m.constituenciesContestedDelta))},{key:"totalConstituencies",label:"Total constituencies",kind:"numeric",align:"num",getValue:m=>m.totalConstituencies,render:m=>B(m,l(m.totalConstituencies))},{key:"totalConstituenciesDelta",label:"+/-",kind:"numeric",align:"num",getValue:m=>m.totalConstituenciesDelta,render:m=>B(m,m.isByElection?"":this._formatEntityDelta(m.totalConstituenciesDelta))},{key:"firstPrefs",label:"1st prefs",kind:"numeric",align:"num",getValue:m=>m.firstPrefs,render:m=>B(m,m.contested?l(m.firstPrefs):"-")},{key:"firstPrefsDelta",label:"+/-",kind:"numeric",align:"num",getValue:m=>m.firstPrefsDelta,render:m=>B(m,this._formatEntityDelta(m.firstPrefsDelta))},{key:"validVotePct",label:"% 1st prefs",kind:"numeric",align:"num",getValue:m=>m.validVotePct,render:m=>B(m,m.contested?d(m.validVotePct):"-")},{key:"validVotePctDelta",label:"+/-",kind:"numeric",align:"num",getValue:m=>m.validVotePctDelta,render:m=>B(m,this._formatEntityDelta(m.validVotePctDelta,2,"%"))}];E.headerRows=[[{label:"Election",leafIndex:0,rowspan:3},{label:"Date",leafIndex:1,rowspan:3},{label:"Type",leafIndex:2,rowspan:3},{label:"#",rowspan:2,colspan:2},{label:"Seats",colspan:6},{label:"Candidates",rowspan:2,colspan:2},{label:"Constituencies",colspan:4},{label:"1st preferences",colspan:4}],[{label:"Won",colspan:4},{label:"Total",colspan:2},{label:"Stood in",colspan:2},{label:"Total",colspan:2},{label:"No.",colspan:2},{label:"%",colspan:2}],[{label:"No.",leafIndex:3,align:"num"},{label:"+/-",leafIndex:4,align:"num"},{label:"No.",leafIndex:5,align:"num"},{label:"+/-",leafIndex:6,align:"num"},{label:"%",leafIndex:7,align:"num"},{label:"+/-",leafIndex:8,align:"num"},{label:"No.",leafIndex:9,align:"num"},{label:"+/-",leafIndex:10,align:"num"},{label:"No.",leafIndex:11,align:"num"},{label:"+/-",leafIndex:12,align:"num"},{label:"No.",leafIndex:13,align:"num"},{label:"+/-",leafIndex:14,align:"num"},{label:"No.",leafIndex:15,align:"num"},{label:"+/-",leafIndex:16,align:"num"},{label:"No.",leafIndex:17,align:"num"},{label:"+/-",leafIndex:18,align:"num"},{label:"%",leafIndex:19,align:"num"},{label:"+/-",leafIndex:20,align:"num"}]];let k=[{key:"candidateRank",label:"#",kind:"ordinal",align:"num",getValue:m=>m.candidateRank,render:m=>l(m.candidateRank)},{key:"name",label:"Candidate",kind:"text",getValue:m=>m.name,render:m=>f("candidate",m.personId,m.name)},{key:"totalFirstPrefs",label:"Total 1st prefs",kind:"numeric",align:"num",getValue:m=>m.totalFirstPrefs,render:m=>l(m.totalFirstPrefs)},{key:"timesStood",label:"Total",kind:"numeric",align:"num",getValue:m=>m.timesStood,render:m=>l(m.timesStood)},{key:"timesStoodLocal",label:"Local",kind:"numeric",align:"num",getValue:m=>m.timesStoodLocal,render:m=>l(m.timesStoodLocal)},{key:"timesStoodDevolved",label:"Devolved",kind:"numeric",align:"num",getValue:m=>m.timesStoodDevolved,render:m=>l(m.timesStoodDevolved)},{key:"timesStoodWestminster",label:"Westminster",kind:"numeric",align:"num",getValue:m=>m.timesStoodWestminster,render:m=>l(m.timesStoodWestminster)},{key:"timesStoodEuropean",label:"Europe",kind:"numeric",align:"num",getValue:m=>m.timesStoodEuropean,render:m=>l(m.timesStoodEuropean)},{key:"timesElected",label:"Total",kind:"numeric",align:"num",getValue:m=>m.timesElected,render:m=>l(m.timesElected)},{key:"timesElectedLocal",label:"Local",kind:"numeric",align:"num",getValue:m=>m.timesElectedLocal,render:m=>l(m.timesElectedLocal)},{key:"timesElectedDevolved",label:"Devolved",kind:"numeric",align:"num",getValue:m=>m.timesElectedDevolved,render:m=>l(m.timesElectedDevolved)},{key:"timesElectedWestminster",label:"Westminster",kind:"numeric",align:"num",getValue:m=>m.timesElectedWestminster,render:m=>l(m.timesElectedWestminster)},{key:"timesElectedEuropean",label:"Europe",kind:"numeric",align:"num",getValue:m=>m.timesElectedEuropean,render:m=>l(m.timesElectedEuropean)},{key:"constituenciesLabel",label:"Stood in",kind:"text",getValue:m=>(m.constituencyEntries||[]).map(D=>{let q=D.constituency&&D.constituency!=="Northern Ireland"&&D.mapLayerYear;return`${D.constituency||""}${q?` (${D.mapLayerYear||""})`:""}`}).join(", "),render:m=>this._renderConstituencyEntryList(m.constituencyEntries||[])}];k.headerRows=[[{label:"#",leafIndex:0,rowspan:2,align:"num"},{label:"Candidate",leafIndex:1,rowspan:2},{label:"Total 1st prefs",leafIndex:2,rowspan:2,align:"num"},{label:"Times stood",colspan:5},{label:"Times elected",colspan:5},{label:"Stood in",leafIndex:13,rowspan:2}],[{label:"Total",leafIndex:3,align:"num"},{label:"Local",leafIndex:4,align:"num"},{label:"Devolved",leafIndex:5,align:"num"},{label:"Westminster",leafIndex:6,align:"num"},{label:"Europe",leafIndex:7,align:"num"},{label:"Total",leafIndex:8,align:"num"},{label:"Local",leafIndex:9,align:"num"},{label:"Devolved",leafIndex:10,align:"num"},{label:"Westminster",leafIndex:11,align:"num"},{label:"Europe",leafIndex:12,align:"num"}]];let N=[{key:"electionDisplayName",label:"Election",kind:"text",getValue:m=>m.electionDisplayName,render:m=>p(m,m.electionDisplayName,!0)},{key:"date",label:"Date",kind:"date",getValue:m=>m.date,render:m=>this.escapeHtml(be(m.date||""))},{key:"electionType",label:"Type",kind:"text",getValue:m=>m.electionType||"-",render:m=>this.escapeHtml(m.electionType||"-")},{key:"constituency",label:"Constituency",kind:"text",getValue:m=>m.constituency,render:m=>{let D=m.constituency||"-";return!m.constituency||!m.body||!m.date?this.escapeHtml(D):Ft(m.body,m.date,m.constituency,m.constituency,"election-cell-wrap",m.electionType==="Local"?"dea":"constituency")}},{key:"bodyLabel",label:"Elected body",kind:"text",getValue:m=>m.bodyLabel||m.body,render:m=>{let D=m.bodyLabel||m.body||"-";return m.electionType==="Local"&&D!=="-"&&m.body&&m.date?Ft(m.body,m.date,D,D,"election-cell-wrap election-cell-wrap--full","council"):`${this.escapeHtml(D)}`}},{key:"status",label:"Status",kind:"text",getValue:m=>m.status,render:m=>this.escapeHtml(m.status||"-")},{key:"firstPref",label:"Valid votes",kind:"numeric",align:"num",getValue:m=>m.firstPref,render:m=>l(m.firstPref)},{key:"firstPrefPct",label:"Valid vote %",kind:"numeric",align:"num",getValue:m=>m.firstPrefPct,render:m=>d(m.firstPrefPct)},{key:"overallStandingNumber",label:"Overall standing",kind:"ordinal",getValue:m=>m.overallStandingNumber,render:m=>`${u(m.overallStandingNumber)} time standing`},{key:"overallElectedNumber",label:"Overall elected",kind:"ordinal",getValue:m=>m.overallElectedNumber,render:m=>m.overallElectedNumber?`${u(m.overallElectedNumber)} time elected`:"-"},{key:"bodyStandingNumber",label:"Type standing",kind:"ordinal",getValue:m=>m.bodyStandingNumber,render:m=>`${u(m.bodyStandingNumber)} ${this.escapeHtml(m.electionType||"unknown")} election`},{key:"bodyElectedNumber",label:"Type elected",kind:"ordinal",getValue:m=>m.bodyElectedNumber,render:m=>m.bodyElectedNumber?`${u(m.bodyElectedNumber)} ${this.escapeHtml(m.electionType||"unknown")} win`:"-"}],U=i.kind==="candidate"&&i.latestAppearance?` + `).join(""),B=(m,D)=>m?.isRecallPetition?"-":D,H=(i.candidateSummaries||[]).map((m,D)=>({...m,candidateRank:D+1})),M=[{key:"electionDisplayName",label:"Election",kind:"text",getValue:m=>m.electionDisplayName,render:m=>p(m,m.electionDisplayName,!1)},{key:"date",label:"Date",kind:"date",getValue:m=>m.date,render:m=>this.escapeHtml(h(m.date||""))},{key:"electionType",label:"Type",kind:"text",getValue:m=>m.electionType||"-",render:m=>this.escapeHtml(m.electionType||"-")},{key:"rank",label:"#",kind:"ordinal",align:"num",getValue:m=>m.rank,render:m=>B(m,m.contested?u(m.rank):"-")},{key:"rankDelta",label:"+/-",kind:"ordinal",align:"num",getValue:m=>m.rankDelta,render:m=>B(m,this._formatEntityRankDelta(m.rankDelta))},{key:"elected",label:"Seats won",kind:"numeric",align:"num",getValue:m=>m.elected,render:m=>B(m,m.contested?l(m.elected):"-")},{key:"electedDelta",label:"+/-",kind:"numeric",align:"num",getValue:m=>m.electedDelta,render:m=>B(m,this._formatEntityDelta(m.electedDelta))},{key:"seatPct",label:"% seats won",kind:"numeric",align:"num",getValue:m=>m.seatPct,render:m=>B(m,m.contested?d(m.seatPct):"-")},{key:"seatPctDelta",label:"+/-",kind:"numeric",align:"num",getValue:m=>m.seatPctDelta,render:m=>B(m,this._formatEntityDelta(m.seatPctDelta,2,"%"))},{key:"totalSeats",label:"Total seats",kind:"numeric",align:"num",getValue:m=>m.totalSeats,render:m=>B(m,l(m.totalSeats))},{key:"totalSeatsDelta",label:"+/-",kind:"numeric",align:"num",getValue:m=>m.totalSeatsDelta,render:m=>B(m,m.isByElection?"-":this._formatEntityDelta(m.totalSeatsDelta))},{key:"stood",label:"Candidates stood",kind:"numeric",align:"num",getValue:m=>m.stood,filterValue:m=>m.contested?m.stood:"N/A",render:m=>B(m,m.contested?l(m.stood):"N/A")},{key:"stoodDelta",label:"+/-",kind:"numeric",align:"num",getValue:m=>m.stoodDelta,render:m=>B(m,this._formatEntityDelta(m.stoodDelta))},{key:"constituenciesContested",label:"Constituencies",kind:"numeric",align:"num",getValue:m=>m.constituenciesContested,render:m=>B(m,l(m.constituenciesContested))},{key:"constituenciesContestedDelta",label:"+/-",kind:"numeric",align:"num",getValue:m=>m.constituenciesContestedDelta,render:m=>B(m,this._formatEntityDelta(m.constituenciesContestedDelta))},{key:"totalConstituencies",label:"Total constituencies",kind:"numeric",align:"num",getValue:m=>m.totalConstituencies,render:m=>B(m,l(m.totalConstituencies))},{key:"totalConstituenciesDelta",label:"+/-",kind:"numeric",align:"num",getValue:m=>m.totalConstituenciesDelta,render:m=>B(m,m.isByElection?"":this._formatEntityDelta(m.totalConstituenciesDelta))},{key:"firstPrefs",label:"1st prefs",kind:"numeric",align:"num",getValue:m=>m.firstPrefs,render:m=>B(m,m.contested?l(m.firstPrefs):"-")},{key:"firstPrefsDelta",label:"+/-",kind:"numeric",align:"num",getValue:m=>m.firstPrefsDelta,render:m=>B(m,this._formatEntityDelta(m.firstPrefsDelta))},{key:"validVotePct",label:"% 1st prefs",kind:"numeric",align:"num",getValue:m=>m.validVotePct,render:m=>B(m,m.contested?d(m.validVotePct):"-")},{key:"validVotePctDelta",label:"+/-",kind:"numeric",align:"num",getValue:m=>m.validVotePctDelta,render:m=>B(m,this._formatEntityDelta(m.validVotePctDelta,2,"%"))}];M.headerRows=[[{label:"Election",leafIndex:0,rowspan:3},{label:"Date",leafIndex:1,rowspan:3},{label:"Type",leafIndex:2,rowspan:3},{label:"#",rowspan:2,colspan:2},{label:"Seats",colspan:6},{label:"Candidates",rowspan:2,colspan:2},{label:"Constituencies",colspan:4},{label:"1st preferences",colspan:4}],[{label:"Won",colspan:4},{label:"Total",colspan:2},{label:"Stood in",colspan:2},{label:"Total",colspan:2},{label:"No.",colspan:2},{label:"%",colspan:2}],[{label:"No.",leafIndex:3,align:"num"},{label:"+/-",leafIndex:4,align:"num"},{label:"No.",leafIndex:5,align:"num"},{label:"+/-",leafIndex:6,align:"num"},{label:"%",leafIndex:7,align:"num"},{label:"+/-",leafIndex:8,align:"num"},{label:"No.",leafIndex:9,align:"num"},{label:"+/-",leafIndex:10,align:"num"},{label:"No.",leafIndex:11,align:"num"},{label:"+/-",leafIndex:12,align:"num"},{label:"No.",leafIndex:13,align:"num"},{label:"+/-",leafIndex:14,align:"num"},{label:"No.",leafIndex:15,align:"num"},{label:"+/-",leafIndex:16,align:"num"},{label:"No.",leafIndex:17,align:"num"},{label:"+/-",leafIndex:18,align:"num"},{label:"%",leafIndex:19,align:"num"},{label:"+/-",leafIndex:20,align:"num"}]];let k=[{key:"candidateRank",label:"#",kind:"ordinal",align:"num",getValue:m=>m.candidateRank,render:m=>l(m.candidateRank)},{key:"name",label:"Candidate",kind:"text",getValue:m=>m.name,render:m=>f("candidate",m.personId,m.name)},{key:"totalFirstPrefs",label:"Total 1st prefs",kind:"numeric",align:"num",getValue:m=>m.totalFirstPrefs,render:m=>l(m.totalFirstPrefs)},{key:"timesStood",label:"Total",kind:"numeric",align:"num",getValue:m=>m.timesStood,render:m=>l(m.timesStood)},{key:"timesStoodLocal",label:"Local",kind:"numeric",align:"num",getValue:m=>m.timesStoodLocal,render:m=>l(m.timesStoodLocal)},{key:"timesStoodDevolved",label:"Devolved",kind:"numeric",align:"num",getValue:m=>m.timesStoodDevolved,render:m=>l(m.timesStoodDevolved)},{key:"timesStoodWestminster",label:"Westminster",kind:"numeric",align:"num",getValue:m=>m.timesStoodWestminster,render:m=>l(m.timesStoodWestminster)},{key:"timesStoodEuropean",label:"Europe",kind:"numeric",align:"num",getValue:m=>m.timesStoodEuropean,render:m=>l(m.timesStoodEuropean)},{key:"timesElected",label:"Total",kind:"numeric",align:"num",getValue:m=>m.timesElected,render:m=>l(m.timesElected)},{key:"timesElectedLocal",label:"Local",kind:"numeric",align:"num",getValue:m=>m.timesElectedLocal,render:m=>l(m.timesElectedLocal)},{key:"timesElectedDevolved",label:"Devolved",kind:"numeric",align:"num",getValue:m=>m.timesElectedDevolved,render:m=>l(m.timesElectedDevolved)},{key:"timesElectedWestminster",label:"Westminster",kind:"numeric",align:"num",getValue:m=>m.timesElectedWestminster,render:m=>l(m.timesElectedWestminster)},{key:"timesElectedEuropean",label:"Europe",kind:"numeric",align:"num",getValue:m=>m.timesElectedEuropean,render:m=>l(m.timesElectedEuropean)},{key:"constituenciesLabel",label:"Stood in",kind:"text",getValue:m=>(m.constituencyEntries||[]).map(D=>{let q=D.constituency&&D.constituency!=="Northern Ireland"&&D.mapLayerYear;return`${D.constituency||""}${q?` (${D.mapLayerYear||""})`:""}`}).join(", "),render:m=>this._renderConstituencyEntryList(m.constituencyEntries||[])}];k.headerRows=[[{label:"#",leafIndex:0,rowspan:2,align:"num"},{label:"Candidate",leafIndex:1,rowspan:2},{label:"Total 1st prefs",leafIndex:2,rowspan:2,align:"num"},{label:"Times stood",colspan:5},{label:"Times elected",colspan:5},{label:"Stood in",leafIndex:13,rowspan:2}],[{label:"Total",leafIndex:3,align:"num"},{label:"Local",leafIndex:4,align:"num"},{label:"Devolved",leafIndex:5,align:"num"},{label:"Westminster",leafIndex:6,align:"num"},{label:"Europe",leafIndex:7,align:"num"},{label:"Total",leafIndex:8,align:"num"},{label:"Local",leafIndex:9,align:"num"},{label:"Devolved",leafIndex:10,align:"num"},{label:"Westminster",leafIndex:11,align:"num"},{label:"Europe",leafIndex:12,align:"num"}]];let N=[{key:"electionDisplayName",label:"Election",kind:"text",getValue:m=>m.electionDisplayName,render:m=>p(m,m.electionDisplayName,!0)},{key:"date",label:"Date",kind:"date",getValue:m=>m.date,render:m=>this.escapeHtml(_e(m.date||""))},{key:"electionType",label:"Type",kind:"text",getValue:m=>m.electionType||"-",render:m=>this.escapeHtml(m.electionType||"-")},{key:"constituency",label:"Constituency",kind:"text",getValue:m=>m.constituency,render:m=>{let D=m.constituency||"-";return!m.constituency||!m.body||!m.date?this.escapeHtml(D):Ht(m.body,m.date,m.constituency,m.constituency,"election-cell-wrap",m.electionType==="Local"?"dea":"constituency")}},{key:"bodyLabel",label:"Elected body",kind:"text",getValue:m=>m.bodyLabel||m.body,render:m=>{let D=m.bodyLabel||m.body||"-";return m.electionType==="Local"&&D!=="-"&&m.body&&m.date?Ht(m.body,m.date,D,D,"election-cell-wrap election-cell-wrap--full","council"):`${this.escapeHtml(D)}`}},{key:"status",label:"Status",kind:"text",getValue:m=>m.status,render:m=>this.escapeHtml(m.status||"-")},{key:"firstPref",label:"Valid votes",kind:"numeric",align:"num",getValue:m=>m.firstPref,render:m=>l(m.firstPref)},{key:"firstPrefPct",label:"Valid vote %",kind:"numeric",align:"num",getValue:m=>m.firstPrefPct,render:m=>d(m.firstPrefPct)},{key:"overallStandingNumber",label:"Overall standing",kind:"ordinal",getValue:m=>m.overallStandingNumber,render:m=>`${u(m.overallStandingNumber)} time standing`},{key:"overallElectedNumber",label:"Overall elected",kind:"ordinal",getValue:m=>m.overallElectedNumber,render:m=>m.overallElectedNumber?`${u(m.overallElectedNumber)} time elected`:"-"},{key:"bodyStandingNumber",label:"Type standing",kind:"ordinal",getValue:m=>m.bodyStandingNumber,render:m=>`${u(m.bodyStandingNumber)} ${this.escapeHtml(m.electionType||"unknown")} election`},{key:"bodyElectedNumber",label:"Type elected",kind:"ordinal",getValue:m=>m.bodyElectedNumber,render:m=>m.bodyElectedNumber?`${u(m.bodyElectedNumber)} ${this.escapeHtml(m.electionType||"unknown")} win`:"-"}],V=i.kind==="candidate"&&i.latestAppearance?`
    Last Election Stood In
    @@ -813,7 +811,7 @@ ${s.map(n).join(",")}
    Date - ${this.escapeHtml(be(i.latestAppearance.date||""))} + ${this.escapeHtml(_e(i.latestAppearance.date||""))}
    Valid vote @@ -837,17 +835,17 @@ ${s.map(n).join(",")}
    - `:"",K=i.kind==="dea"?[{key:"electionDisplayName",label:"Election",kind:"text",getValue:m=>m.electionDisplayName,render:m=>p(m,m.electionDisplayName,!0)},{key:"date",label:"Date",kind:"date",getValue:m=>m.date,render:m=>this.escapeHtml(be(m.date||""))},{key:"localGovernmentDistrict",label:"Local Government District",kind:"text",getValue:m=>m.localGovernmentDistrict,render:m=>f("lgd",m.localGovernmentDistrict,m.localGovernmentDistrict)},{key:"winnerParty",label:"Leading party",kind:"text",getValue:m=>m.winnerParty,render:m=>y(m)},{key:"winnerVotes",label:"Leading party votes",kind:"numeric",align:"num",getValue:m=>m.winnerVotes,render:m=>l(m.winnerVotes)},{key:"winnerPct",label:"Leading party %",kind:"numeric",align:"num",getValue:m=>m.winnerPct,render:m=>d(m.winnerPct)},{key:"validVotes",label:"Valid votes",kind:"numeric",align:"num",getValue:m=>m.validVotes,render:m=>l(m.validVotes)},{key:"seats",label:"Seats",kind:"numeric",align:"num",getValue:m=>m.seats,render:m=>l(m.seats)}]:i.kind==="constituency"?[{key:"electionDisplayName",label:"Election",kind:"text",getValue:m=>m.electionDisplayName,render:m=>p(m,m.electionDisplayName,!0)},{key:"date",label:"Date",kind:"date",getValue:m=>m.date,render:m=>this.escapeHtml(be(m.date||""))},{key:"winnerParty",label:"Leading party",kind:"text",getValue:m=>m.winnerParty,render:m=>y(m)},{key:"winnerVotes",label:"Leading party votes",kind:"numeric",align:"num",getValue:m=>m.winnerVotes,render:m=>l(m.winnerVotes)},{key:"winnerPct",label:"Leading party %",kind:"numeric",align:"num",getValue:m=>m.winnerPct,render:m=>d(m.winnerPct)},{key:"validVotes",label:"Valid votes",kind:"numeric",align:"num",getValue:m=>m.validVotes,render:m=>l(m.validVotes)},{key:"seats",label:"Seats",kind:"numeric",align:"num",getValue:m=>m.seats,render:m=>l(m.seats)}]:[{key:"electionDisplayName",label:"Election",kind:"text",getValue:m=>m.electionDisplayName,render:m=>p(m,m.electionDisplayName,!1)},{key:"date",label:"Date",kind:"date",getValue:m=>m.date,render:m=>this.escapeHtml(be(m.date||""))},{key:"deaCount",label:"DEAs",kind:"numeric",align:"num",getValue:m=>m.deaCount,render:m=>l(m.deaCount)},{key:"districtElectoralAreas",label:"District Electoral Areas",kind:"text",getValue:m=>(m.districtElectoralAreas||[]).join(", "),render:m=>b(m)},{key:"winnerParty",label:"Leading party",kind:"text",getValue:m=>m.winnerParty,render:m=>y(m)},{key:"winnerVotes",label:"Leading party votes",kind:"numeric",align:"num",getValue:m=>m.winnerVotes,render:m=>l(m.winnerVotes)},{key:"winnerPct",label:"Leading party %",kind:"numeric",align:"num",getValue:m=>m.winnerPct,render:m=>d(m.winnerPct)},{key:"validVotes",label:"Valid votes",kind:"numeric",align:"num",getValue:m=>m.validVotes,render:m=>l(m.validVotes)},{key:"seats",label:"Seats",kind:"numeric",align:"num",getValue:m=>m.seats,render:m=>l(m.seats)}],G=w?` + `:"",K=i.kind==="dea"?[{key:"electionDisplayName",label:"Election",kind:"text",getValue:m=>m.electionDisplayName,render:m=>p(m,m.electionDisplayName,!0)},{key:"date",label:"Date",kind:"date",getValue:m=>m.date,render:m=>this.escapeHtml(_e(m.date||""))},{key:"localGovernmentDistrict",label:"Local Government District",kind:"text",getValue:m=>m.localGovernmentDistrict,render:m=>f("lgd",m.localGovernmentDistrict,m.localGovernmentDistrict)},{key:"winnerParty",label:"Leading party",kind:"text",getValue:m=>m.winnerParty,render:m=>y(m)},{key:"winnerVotes",label:"Leading party votes",kind:"numeric",align:"num",getValue:m=>m.winnerVotes,render:m=>l(m.winnerVotes)},{key:"winnerPct",label:"Leading party %",kind:"numeric",align:"num",getValue:m=>m.winnerPct,render:m=>d(m.winnerPct)},{key:"validVotes",label:"Valid votes",kind:"numeric",align:"num",getValue:m=>m.validVotes,render:m=>l(m.validVotes)},{key:"seats",label:"Seats",kind:"numeric",align:"num",getValue:m=>m.seats,render:m=>l(m.seats)}]:i.kind==="constituency"?[{key:"electionDisplayName",label:"Election",kind:"text",getValue:m=>m.electionDisplayName,render:m=>p(m,m.electionDisplayName,!0)},{key:"date",label:"Date",kind:"date",getValue:m=>m.date,render:m=>this.escapeHtml(_e(m.date||""))},{key:"winnerParty",label:"Leading party",kind:"text",getValue:m=>m.winnerParty,render:m=>y(m)},{key:"winnerVotes",label:"Leading party votes",kind:"numeric",align:"num",getValue:m=>m.winnerVotes,render:m=>l(m.winnerVotes)},{key:"winnerPct",label:"Leading party %",kind:"numeric",align:"num",getValue:m=>m.winnerPct,render:m=>d(m.winnerPct)},{key:"validVotes",label:"Valid votes",kind:"numeric",align:"num",getValue:m=>m.validVotes,render:m=>l(m.validVotes)},{key:"seats",label:"Seats",kind:"numeric",align:"num",getValue:m=>m.seats,render:m=>l(m.seats)}]:[{key:"electionDisplayName",label:"Election",kind:"text",getValue:m=>m.electionDisplayName,render:m=>p(m,m.electionDisplayName,!1)},{key:"date",label:"Date",kind:"date",getValue:m=>m.date,render:m=>this.escapeHtml(_e(m.date||""))},{key:"deaCount",label:"DEAs",kind:"numeric",align:"num",getValue:m=>m.deaCount,render:m=>l(m.deaCount)},{key:"districtElectoralAreas",label:"District Electoral Areas",kind:"text",getValue:m=>(m.districtElectoralAreas||[]).join(", "),render:m=>b(m)},{key:"winnerParty",label:"Leading party",kind:"text",getValue:m=>m.winnerParty,render:m=>y(m)},{key:"winnerVotes",label:"Leading party votes",kind:"numeric",align:"num",getValue:m=>m.winnerVotes,render:m=>l(m.winnerVotes)},{key:"winnerPct",label:"Leading party %",kind:"numeric",align:"num",getValue:m=>m.winnerPct,render:m=>d(m.winnerPct)},{key:"validVotes",label:"Valid votes",kind:"numeric",align:"num",getValue:m=>m.validVotes,render:m=>l(m.validVotes)},{key:"seats",label:"Seats",kind:"numeric",align:"num",getValue:m=>m.seats,render:m=>l(m.seats)}],G=w?`
    Election History (${(i.historyRows||[]).length})
    - ${this._buildEntityTableMarkup("catalogue-party-history-table",E)} + ${this._buildEntityTableMarkup("catalogue-party-history-table",M)}
    Candidates (${(i.candidateSummaries||[]).length})
    ${this._buildEntityTableMarkup("catalogue-party-candidates-table",k)}
    `:v?` - ${U} + ${V}
    Election History (${(i.appearances||[]).length})
    ${this._buildEntityTableMarkup("catalogue-candidate-history-table",N)} @@ -860,14 +858,14 @@ ${s.map(n).join(",")} `;n.innerHTML=`
    -
    ${this.escapeHtml(M)}
    +
    ${this.escapeHtml(E)}
    ${this.escapeHtml(C)}
    ${w?"":`
    ${this.escapeHtml(T)}
    `} -
    ${z}
    +
    ${O}
    ${v?`
    ${x}
    `:""} ${G} - `,w?(this._initEntityDataTable(n,"catalogue-party-history-table",E,i.historyRows||[],{rowClassNameFn:m=>m.isByElection?"catalogue-detail__entity-row--by-election":""}),this._initEntityDataTable(n,"catalogue-party-candidates-table",k,H)):v?this._initEntityDataTable(n,"catalogue-candidate-history-table",N,i.appearances||[],{rowClassNameFn:m=>m.isByElection?"catalogue-detail__entity-row--by-election":""}):this._initEntityDataTable(n,`catalogue-${i.kind}-history-table`,K,i.historyRows||[],{rowClassNameFn:m=>m.isByElection?"catalogue-detail__entity-row--by-election":""}),n._entityDetailClickHandler&&n.removeEventListener("click",n._entityDetailClickHandler),n._entityDetailClickHandler=async m=>{let D=m.target.closest("[data-election-body][data-election-date]");if(D){m.preventDefault(),this.onElectionEntityElectionOpen?.({body:D.dataset.electionBody,date:D.dataset.electionDate,constituency:D.dataset.electionConstituency||null});return}let q=m.target.closest('[data-election-constituency-feature="1"]');if(q){m.preventDefault(),await this.onOpenElectionConstituencyFeature?.({body:q.dataset.electionConstituencyBody,date:q.dataset.electionConstituencyDate,constituency:q.dataset.electionConstituencyName,level:q.dataset.electionConstituencyLevel||"dea"});return}let J=m.target.closest("[data-election-entity-detail-kind][data-election-entity-detail-key]");if(!J)return;if(m.preventDefault(),typeof this.onOpenElectionEntityDetail=="function"){await this.onOpenElectionEntityDetail(J.dataset.electionEntityDetailKind,J.dataset.electionEntityDetailKey);return}let se=this.createElectionEntityDetailId(J.dataset.electionEntityDetailKind,J.dataset.electionEntityDetailKey);this.showElectionEntityDetailInCatalogue(se,!0)},n.addEventListener("click",n._entityDetailClickHandler),(this._cataloguePane||document.querySelector('.pane__content[data-tab-content="catalogue"]'))?.scrollTo({top:0,behavior:"auto"}),this.updateCatalogueNavButtons()}calculateGeodesicMetrics(e){let t={area:null,perimeter:null};if(!e||!e.coordinates)return t;let a=6371;try{if(e.type==="Polygon"){let i=e.coordinates[0];t.area=this.calculatePolygonArea(i,a),t.perimeter=this.calculatePolygonPerimeter(i,a)}else if(e.type==="MultiPolygon"){let i=0,s=0;e.coordinates.forEach(n=>{let r=n[0];i+=this.calculatePolygonArea(r,a),s+=this.calculatePolygonPerimeter(r,a)}),t.area=i,t.perimeter=s}}catch(i){console.warn("[UIController] Error calculating geodesic metrics:",i)}return t}calculatePolygonArea(e,t){let a=0;for(let i=0;i=.01?e.toLocaleString(void 0,{minimumFractionDigits:2,maximumFractionDigits:2}):e.toLocaleString(void 0,{minimumFractionDigits:4,maximumFractionDigits:4})}formatDisplayValue(e){return typeof e=="number"&&Number.isFinite(e)?Math.abs(e)>=1e3?e.toLocaleString("en-GB"):String(e):e==null?"":String(e)}isMapLoadedState(e,t={}){if(!e)return!1;if(typeof this.onCheckMapLoaded=="function")try{return!!this.onCheckMapLoaded(e)}catch{}return!!t.loadedIds?.includes(e)}getLoadButtonIcon(e,t=!1){return t?'':e?'':''}isLoadTogglePending(e){return!!e&&!!this._pendingLoadToggles?.has(e)}isPendingUnload(e){return!!this._pendingLoadToggles?.get(e)}loadButtonSelector(e){let t=CSS.escape(e);return`.load-btn[data-map-id="${t}"], .c1-load-btn[data-map-id="${t}"]`}applyLoadButtonVisual(e,t,a){!!e.querySelector(".load-btn__spinner")!==a&&(e.innerHTML=this.getLoadButtonIcon(t,a)),e.classList.toggle("load-btn--busy",a),e.disabled=a,a?e.setAttribute("aria-busy","true"):e.removeAttribute("aria-busy"),a?e.title=this._pendingLoadToggles?.get(e.dataset.mapId)?"Unloading...":"Loading...":e.title=t?"Unload":"Load"}setLoadButtonBusy(e,t,a){this._pendingLoadToggles||(this._pendingLoadToggles=new Map),t?this._pendingLoadToggles.set(e,!!a):this._pendingLoadToggles.delete(e),document.querySelectorAll(this.loadButtonSelector(e)).forEach(i=>{this.applyLoadButtonVisual(i,a,t)}),this.syncPendingLoadObserver()}syncPendingLoadObserver(){let e=this._pendingLoadToggles;if(!e||e.size===0){this._pendingLoadObserver?.disconnect(),this._pendingLoadObserver=null;return}this._pendingLoadObserver||(this._pendingLoadObserver=new MutationObserver(()=>{for(let t of this._pendingLoadToggles.keys()){let a=this.isMapLoadedState(t,this._lastMapListOptions);document.querySelectorAll(this.loadButtonSelector(t)).forEach(i=>{this.applyLoadButtonVisual(i,a,!0)}),this.restoreLoadButtonFocus(t)}}),this._pendingLoadObserver.observe(document.body,{childList:!0,subtree:!0}))}async handleLoadToggle(e,t){if(!e||this.isLoadTogglePending(e))return;let a=t?this.onMapUnload:this.onMapLoad;if(!a)return;let i=!!(document.activeElement&&document.activeElement.matches?.(this.loadButtonSelector(e)));this._loadFocusMapId=i?e:null;let s=this.layerLabelForAnnounce(e);this.announce(t?`Removing ${s}`:`Loading ${s}`),this.setLoadButtonBusy(e,!0,t);try{await a(e)}catch(n){console.error(`[catalogue] ${t?"unload":"load"} failed for ${e}`,n)}finally{let n=this.onCheckMapLoaded?!!this.onCheckMapLoaded(e):this.isMapLoadedState(e,this._lastMapListOptions);this.setLoadButtonBusy(e,!1,n),this.applyLoadedStateToRows(e,n);let r=!t&&this.onCheckMapSettled?String(this.onCheckMapSettled(e)||"unknown"):"unknown",o=n&&r==="timeout";this.applyStalledStateToRows(e,o),t?this.announce(n?`${s} could not be removed`:`${s} removed`):n?o?this.announce(`${s} is taking too long. Its tiles have not arrived; it may appear blank. Use the layer's load button to try again.`):this.announce(`${s} loaded`):this.announce(`${s} failed to load`),this.restoreLoadButtonFocus(e),this._loadFocusMapId=null}}layerLabelForAnnounce(e){let t=P.getMapById?.(e),a=t?.name||t?.title||"";return String(a||e).replace(/\s+/g," ").trim()}restoreLoadButtonFocus(e){if(!e||this._loadFocusMapId!==e)return;let t=document.querySelector(this.loadButtonSelector(e));t&&t.isConnected&&t.focus({preventScroll:!0})}applyStalledStateToRows(e,t){e&&document.querySelectorAll(`[data-map-id="${CSS.escape(e)}"]`).forEach(a=>{a.classList.toggle("map-row--stalled",!!t),t?a.setAttribute("data-load-stalled","true"):a.removeAttribute("data-load-stalled")})}applyLoadedStateToRows(e,t){if(!e)return;let a=`[data-map-id="${CSS.escape(e)}"]`;document.querySelectorAll(a).forEach(i=>{i.classList.contains("class-member")&&i.classList.toggle("class-member--loaded",t),i.classList.contains("c1-grid-entry")&&i.classList.toggle("c1-grid-entry--loaded",t),i.classList.contains("variant-item")&&i.classList.toggle("variant-item--loaded",t)})}hideFeatureInfo(){let e=document.getElementById("featureInfo");e&&e.classList.add("hidden")}showLoadProgress(e,t){}updateActiveLayers(e,t,a){let i=document.getElementById("activeLayersList");if(!i)return;let s=new Set([...i.querySelectorAll(".active-layer-item__opacity-panel")].filter(r=>r.style.display&&r.style.display!=="none").map(r=>r.dataset.mapId));if(!e||e.length===0){i.innerHTML='

    No layers loaded

    ';return}i.innerHTML=e.map(r=>{let o=t?.get(r.id)??!0,l=a?.get(r.id),d=r.style?.color||"#3388ff",h=r.authors?.join(", ")||"",u=r.date?this.getYear(r.date):"",p=P.getMapDisplayTitle?.(r)||r.name,f=l?.featureItems?.length?(l.featureItems||[]).map(C=>` + `,w?(this._initEntityDataTable(n,"catalogue-party-history-table",M,i.historyRows||[],{rowClassNameFn:m=>m.isByElection?"catalogue-detail__entity-row--by-election":""}),this._initEntityDataTable(n,"catalogue-party-candidates-table",k,H)):v?this._initEntityDataTable(n,"catalogue-candidate-history-table",N,i.appearances||[],{rowClassNameFn:m=>m.isByElection?"catalogue-detail__entity-row--by-election":""}):this._initEntityDataTable(n,`catalogue-${i.kind}-history-table`,K,i.historyRows||[],{rowClassNameFn:m=>m.isByElection?"catalogue-detail__entity-row--by-election":""}),n._entityDetailClickHandler&&n.removeEventListener("click",n._entityDetailClickHandler),n._entityDetailClickHandler=async m=>{let D=m.target.closest("[data-election-body][data-election-date]");if(D){m.preventDefault(),this.onElectionEntityElectionOpen?.({body:D.dataset.electionBody,date:D.dataset.electionDate,constituency:D.dataset.electionConstituency||null});return}let q=m.target.closest('[data-election-constituency-feature="1"]');if(q){m.preventDefault(),await this.onOpenElectionConstituencyFeature?.({body:q.dataset.electionConstituencyBody,date:q.dataset.electionConstituencyDate,constituency:q.dataset.electionConstituencyName,level:q.dataset.electionConstituencyLevel||"dea"});return}let J=m.target.closest("[data-election-entity-detail-kind][data-election-entity-detail-key]");if(!J)return;if(m.preventDefault(),typeof this.onOpenElectionEntityDetail=="function"){await this.onOpenElectionEntityDetail(J.dataset.electionEntityDetailKind,J.dataset.electionEntityDetailKey);return}let ae=this.createElectionEntityDetailId(J.dataset.electionEntityDetailKind,J.dataset.electionEntityDetailKey);this.showElectionEntityDetailInCatalogue(ae,!0)},n.addEventListener("click",n._entityDetailClickHandler),(this._cataloguePane||document.querySelector('.pane__content[data-tab-content="catalogue"]'))?.scrollTo({top:0,behavior:"auto"}),this.updateCatalogueNavButtons()}calculateGeodesicMetrics(e){let t={area:null,perimeter:null};if(!e||!e.coordinates)return t;let a=6371;try{if(e.type==="Polygon"){let i=e.coordinates[0];t.area=this.calculatePolygonArea(i,a),t.perimeter=this.calculatePolygonPerimeter(i,a)}else if(e.type==="MultiPolygon"){let i=0,s=0;e.coordinates.forEach(n=>{let r=n[0];i+=this.calculatePolygonArea(r,a),s+=this.calculatePolygonPerimeter(r,a)}),t.area=i,t.perimeter=s}}catch(i){console.warn("[UIController] Error calculating geodesic metrics:",i)}return t}calculatePolygonArea(e,t){let a=0;for(let i=0;i=.01?e.toLocaleString(void 0,{minimumFractionDigits:2,maximumFractionDigits:2}):e.toLocaleString(void 0,{minimumFractionDigits:4,maximumFractionDigits:4})}formatDisplayValue(e){return typeof e=="number"&&Number.isFinite(e)?Math.abs(e)>=1e3?e.toLocaleString("en-GB"):String(e):e==null?"":String(e)}isMapLoadedState(e,t={}){if(!e)return!1;if(typeof this.onCheckMapLoaded=="function")try{return!!this.onCheckMapLoaded(e)}catch{}return!!t.loadedIds?.includes(e)}getLoadButtonIcon(e,t=!1){return t?'':e?'':''}isLoadTogglePending(e){return!!e&&!!this._pendingLoadToggles?.has(e)}isPendingUnload(e){return!!this._pendingLoadToggles?.get(e)}loadButtonSelector(e){let t=CSS.escape(e);return`.load-btn[data-map-id="${t}"], .c1-load-btn[data-map-id="${t}"]`}applyLoadButtonVisual(e,t,a){!!e.querySelector(".load-btn__spinner")!==a&&(e.innerHTML=this.getLoadButtonIcon(t,a)),e.classList.toggle("load-btn--busy",a),e.disabled=a,a?e.setAttribute("aria-busy","true"):e.removeAttribute("aria-busy"),a?e.title=this._pendingLoadToggles?.get(e.dataset.mapId)?"Unloading...":"Loading...":e.title=t?"Unload":"Load"}setLoadButtonBusy(e,t,a){this._pendingLoadToggles||(this._pendingLoadToggles=new Map),t?this._pendingLoadToggles.set(e,!!a):this._pendingLoadToggles.delete(e),document.querySelectorAll(this.loadButtonSelector(e)).forEach(i=>{this.applyLoadButtonVisual(i,a,t)}),this.syncPendingLoadObserver()}syncPendingLoadObserver(){let e=this._pendingLoadToggles;if(!e||e.size===0){this._pendingLoadObserver?.disconnect(),this._pendingLoadObserver=null;return}this._pendingLoadObserver||(this._pendingLoadObserver=new MutationObserver(()=>{for(let t of this._pendingLoadToggles.keys()){let a=this.isMapLoadedState(t,this._lastMapListOptions);document.querySelectorAll(this.loadButtonSelector(t)).forEach(i=>{this.applyLoadButtonVisual(i,a,!0)}),this.restoreLoadButtonFocus(t)}}),this._pendingLoadObserver.observe(document.body,{childList:!0,subtree:!0}))}async handleLoadToggle(e,t){if(!e||this.isLoadTogglePending(e))return;let a=t?this.onMapUnload:this.onMapLoad;if(!a)return;let i=!!(document.activeElement&&document.activeElement.matches?.(this.loadButtonSelector(e)));this._loadFocusMapId=i?e:null;let s=this.layerLabelForAnnounce(e);this.announce(t?`Removing ${s}`:`Loading ${s}`),this.setLoadButtonBusy(e,!0,t);try{await a(e)}catch(n){console.error(`[catalogue] ${t?"unload":"load"} failed for ${e}`,n)}finally{let n=this.onCheckMapLoaded?!!this.onCheckMapLoaded(e):this.isMapLoadedState(e,this._lastMapListOptions);this.setLoadButtonBusy(e,!1,n),this.applyLoadedStateToRows(e,n);let r=!t&&this.onCheckMapSettled?String(this.onCheckMapSettled(e)||"unknown"):"unknown",o=n&&r==="timeout";this.applyStalledStateToRows(e,o),t?this.announce(n?`${s} could not be removed`:`${s} removed`):n?o?this.announce(`${s} is taking too long. Its tiles have not arrived; it may appear blank. Use the layer's load button to try again.`):this.announce(`${s} loaded`):this.announce(`${s} failed to load`),this.restoreLoadButtonFocus(e),this._loadFocusMapId=null}}layerLabelForAnnounce(e){let t=P.getMapById?.(e),a=t?.name||t?.title||"";return String(a||e).replace(/\s+/g," ").trim()}restoreLoadButtonFocus(e){if(!e||this._loadFocusMapId!==e)return;let t=document.querySelector(this.loadButtonSelector(e));t&&t.isConnected&&t.focus({preventScroll:!0})}applyStalledStateToRows(e,t){e&&document.querySelectorAll(`[data-map-id="${CSS.escape(e)}"]`).forEach(a=>{a.classList.toggle("map-row--stalled",!!t),t?a.setAttribute("data-load-stalled","true"):a.removeAttribute("data-load-stalled")})}applyLoadedStateToRows(e,t){if(!e)return;let a=`[data-map-id="${CSS.escape(e)}"]`;document.querySelectorAll(a).forEach(i=>{i.classList.contains("class-member")&&i.classList.toggle("class-member--loaded",t),i.classList.contains("c1-grid-entry")&&i.classList.toggle("c1-grid-entry--loaded",t),i.classList.contains("variant-item")&&i.classList.toggle("variant-item--loaded",t)})}hideFeatureInfo(){let e=document.getElementById("featureInfo");e&&e.classList.add("hidden")}showLoadProgress(e,t){}updateActiveLayers(e,t,a){let i=document.getElementById("activeLayersList");if(!i)return;let s=new Set([...i.querySelectorAll(".active-layer-item__opacity-panel")].filter(r=>r.style.display&&r.style.display!=="none").map(r=>r.dataset.mapId));if(!e||e.length===0){i.innerHTML='

    No layers loaded

    ';return}i.innerHTML=e.map(r=>{let o=t?.get(r.id)??!0,l=a?.get(r.id),d=r.style?.color||"#3388ff",h=r.authors?.join(", ")||"",u=r.date?this.getYear(r.date):"",p=P.getMapDisplayTitle?.(r)||r.name,f=l?.featureItems?.length?(l.featureItems||[]).map(C=>`
    ${this.escapeHtml(C.name||`Feature ${C.index}`)}
    @@ -890,7 +888,7 @@ ${s.map(n).join(",")}
    %
    -
    `,M=``;return` +
    `,E=``;return`
    - ${M} -
    `}).join(""),i.querySelectorAll(".visibility-btn").forEach(r=>{r.addEventListener("click",()=>{let o=r.dataset.mapId;this.onMapToggle&&this.onMapToggle(o)})}),i.querySelectorAll(".expand-btn").forEach(r=>{r.addEventListener("click",()=>{let o=r.dataset.mapId;this.onExpandToFullMap&&this.onExpandToFullMap(o)})}),i.querySelectorAll(".remove-btn").forEach(r=>{r.addEventListener("click",()=>{let o=r.dataset.mapId;this.onMapUnload&&this.onMapUnload(o)})}),i.querySelectorAll(".partial-visibility-btn").forEach(r=>{r.addEventListener("click",()=>{let o=r.dataset.mapId,l=r.dataset.featureIndex,d=Number(l),h=Number.isFinite(d)&&l!==""?d:l;this.onPartialFeatureToggle&&h!==void 0&&h!==null&&h!==""&&this.onPartialFeatureToggle(o,h)})}),i.querySelectorAll(".partial-unload-btn").forEach(r=>{r.addEventListener("click",()=>{let o=r.dataset.mapId,l=r.dataset.featureIndex,d=Number(l),h=Number.isFinite(d)&&l!==""?d:l;this.onPartialFeatureUnload&&h!==void 0&&h!==null&&h!==""&&this.onPartialFeatureUnload(o,h)})}),i.querySelectorAll(".opacity-toggle-btn").forEach(r=>{r.addEventListener("click",()=>{let o=r.dataset.mapId,l=i.querySelector(`.active-layer-item__opacity-panel[data-map-id="${o}"]`);if(l){let d=l.style.display!=="none";l.style.display=d?"none":"block",r.classList.toggle("active",!d)}})}),s.forEach(r=>{let o=i.querySelector(`.active-layer-item__opacity-panel[data-map-id="${r}"]`),l=i.querySelector(`.opacity-toggle-btn[data-map-id="${r}"]`);o&&(o.style.display="block"),l&&l.classList.add("active")});let n=(r,o,l)=>{l=Math.max(0,Math.min(100,parseInt(l)||0));let d=l/100,h=mapController?.getLayerState?.(r)||mapController?.layerStates?.get(r);if(!h)return;o==="raster"?(h._rasterOpacity=d,h.group?.eachLayer(p=>{p.setOpacity&&p.setOpacity(d)})):o==="stroke"?(h._strokeOpacity=d,h.geoJsonLayers?.forEach(p=>p.setStyle({opacity:d}))):o==="fill"&&(h._fillOpacity=d,h.geoJsonLayers?.forEach(p=>p.setStyle({fillOpacity:d})));let u=i.querySelector(`.active-layer-item[data-map-id="${r}"]`);if(u){let p=u.querySelector(`.${o}-opacity-slider`),f=u.querySelector(`.${o}-opacity-input`);p&&(p.value=l),f&&(f.value=l)}};["raster","stroke","fill"].forEach(r=>{i.querySelectorAll(`.${r}-opacity-slider`).forEach(o=>{o.addEventListener("input",()=>n(o.dataset.mapId,r,o.value))}),i.querySelectorAll(`.${r}-opacity-input`).forEach(o=>{o.addEventListener("change",()=>n(o.dataset.mapId,r,o.value))})}),this._attachActiveLayerDragReorder(i)}_attachActiveLayerDragReorder(e){let t=e.querySelectorAll(".active-layer-item__drag");if(!t.length)return;let a=180;t.forEach(i=>{i.addEventListener("keydown",s=>{if(s.key!=="ArrowUp"&&s.key!=="ArrowDown")return;let n=i.closest(".active-layer-item");if(!n)return;let r=[...e.querySelectorAll(".active-layer-item")],o=r.indexOf(n),l=s.key==="ArrowUp"?o-1:o+1;if(l<0||l>=r.length)return;s.preventDefault(),s.key==="ArrowUp"?e.insertBefore(n,r[l]):e.insertBefore(r[l],n);let d=[...e.querySelectorAll(".active-layer-item")].map(p=>p.dataset.mapId);typeof this.onReorderLayers=="function"&&this.onReorderLayers(d);let h=n.querySelector(".active-layer-item__name")?.textContent?.trim()||"Layer";this.announce?.(`${h} moved to position ${d.indexOf(n.dataset.mapId)+1} of ${d.length}`);let u=i.dataset.mapId;requestAnimationFrame(()=>{(e.querySelector(`.active-layer-item[data-map-id="${u}"] .active-layer-item__drag`)||i).focus()})})}),t.forEach(i=>{i.addEventListener("pointerdown",s=>{if(s.button!==void 0&&s.button!==0)return;let n=i.closest(".active-layer-item");if(!n)return;s.preventDefault();let r=[...e.querySelectorAll(".active-layer-item")].map(w=>w.dataset.mapId),o=s.pointerId,l=n.getBoundingClientRect(),d=s.clientX,h=s.clientY;n.classList.add("active-layer-item--dragging");let u=n.cloneNode(!0);u.classList.remove("active-layer-item--dragging"),u.classList.add("active-layer-item--clone"),Object.assign(u.style,{position:"fixed",left:l.left+"px",top:l.top+"px",width:l.width+"px",margin:"0",pointerEvents:"none",zIndex:"9999",transition:"none",willChange:"transform"}),document.body.appendChild(u);let p=w=>{let S=[...e.querySelectorAll(".active-layer-item")],M=new Map(S.map(C=>[C,C.getBoundingClientRect()]));w();for(let C of S){if(C===n)continue;let T=C.getBoundingClientRect(),V=M.get(C),z=V.left-T.left,I=V.top-T.top;!z&&!I||(C.style.transition="none",C.style.transform=`translate(${z}px, ${I}px)`,C.offsetHeight,C.style.transition=`transform ${a}ms ease`,C.style.transform="")}},f=w=>{if(w.pointerId!==o)return;let S=w.clientX-d,M=w.clientY-h;u.style.transform=`translate(${S}px, ${M}px)`;let C=[...e.querySelectorAll(".active-layer-item:not(.active-layer-item--dragging)")],T=null;for(let z of C){let I=z.getBoundingClientRect();if(w.clientY{T?e.insertBefore(n,T):e.appendChild(n)})},g=()=>{window.removeEventListener("pointermove",f,!0),window.removeEventListener("pointerup",b,!0),window.removeEventListener("pointercancel",v,!0)},y=()=>{let w=n.getBoundingClientRect(),S=u.getBoundingClientRect(),M=w.left-S.left,C=w.top-S.top,T=u.style.transform.match(/translate\(\s*(-?[\d.]+)px\s*,\s*(-?[\d.]+)px\s*\)/),V=T?parseFloat(T[1]):0,z=T?parseFloat(T[2]):0;u.style.transition=`transform ${a}ms ease`,u.style.transform=`translate(${V+M}px, ${z+C}px)`;let I=()=>{u.removeEventListener("transitionend",I),u.parentNode&&u.parentNode.removeChild(u),n.classList.remove("active-layer-item--dragging")};u.addEventListener("transitionend",I),setTimeout(I,a+80)},b=w=>{if(w.pointerId!==o)return;g(),y();let S=[...e.querySelectorAll(".active-layer-item")].map(C=>C.dataset.mapId);(S.length!==r.length||S.some((C,T)=>C!==r[T]))&&typeof this.onReorderLayers=="function"&&this.onReorderLayers(S)},v=w=>{w.pointerId===o&&(g(),y())};window.addEventListener("pointermove",f,!0),window.addEventListener("pointerup",b,!0),window.addEventListener("pointercancel",v,!0)})})}initializeTables(){this.tablesInitialized||(this.setupTablesTab(),this.loadTablesData(),this.tablesInitialized=!0)}setupTablesTab(){let e=document.getElementById("tablesDataType"),t=document.getElementById("tablesSearch"),a=document.getElementById("tablesContainer");if(e&&(this.tablesState={dataType:"maps",searchQuery:"",sortKey:null,sortDir:"asc",currentPage:1,pageSize:50,allData:[],filteredData:[],columns:[],allColumns:[],columnCoverage:new Map,visibleColumnCount:3,manifestData:null},e.addEventListener("change",i=>{this.tablesState.dataType=i.target.value,this.tablesState.currentPage=1,this.loadTablesData()}),t)){let i;t.addEventListener("input",s=>{clearTimeout(i),i=setTimeout(()=>{this.tablesState.searchQuery=s.target.value.trim().toLowerCase(),this.tablesState.currentPage=1,this.filterAndRenderTable()},200)})}}loadTablesData(){let e=document.getElementById("tablesContainer");if(!e)return;let t=P.getData();if(!t){e.innerHTML='

    Loading data...

    ';return}switch(this.tablesState.dataType){case"maps":this.tablesState.allData=(t.maps||[]).map(a=>({id:a.id,name:a.name,category:a.category||"",provider:(a.provider||[]).join(", "),date:a.date||"",featured:a.featured?"Yes":"No"})),this.tablesState.columns=["name","category","provider","date","featured"];break;case"books":this.tablesState.allData=(t.books||[]).map(a=>({id:a.id,title:a.title||a.name,authors:(a.authors||[]).join(", "),year:a.year||"",publisher:a.publisher||""})),this.tablesState.columns=["title","authors","year","publisher"];break;case"allFeatures":e.innerHTML='

    Loading all features... This may take a moment.

    ',this.loadAllFeatures();return;case"features":this.onGetLoadedFeatures?(this.tablesState.allData=this.onGetLoadedFeatures()||[],this.tablesState.columns=this.calculateDynamicColumns(this.tablesState.allData)):(this.tablesState.allData=[],this.tablesState.columns=[]);break}this.filterAndRenderTable()}async loadAllFeatures(){let e=document.getElementById("tablesContainer");if(e){this.tablesState.allData=[],this.tablesState.filteredData=[],this.tablesState.columns=[],this.tablesState.allColumns=[],this.tablesState.columnCoverage=new Map,this.tablesState.visibleColumnCount=3,e.innerHTML='

    Loading all features... This may take a moment.

    ';try{let t=await fetch("./data/build-manifest.json");if(!t.ok)throw new Error(`HTTP ${t.status}: ${t.statusText}`);let a=await t.json();this.tablesState.manifestData=a;let i=P.getData(),s=[],n=new Map,r=Object.keys(a.files||{}).length;for(let[o,l]of Object.entries(a.files||{})){if(!l.features)continue;let d=(i?.maps||[]).find(f=>f.id===o),h=d?.name||o,u=d?.category||"",p=new Set;for(let f of l.features){let g={name:f.name||`Feature ${f.index+1}`,map:h,mapId:o,category:u,index:f.index},y=f.properties;if(y&&typeof y=="object"&&!Array.isArray(y))for(let[b,v]of Object.entries(y))p.add(b),g[b]=v;else if(Array.isArray(y))for(let b of y)p.add(b);s.push(g)}for(let f of p)n.has(f)||n.set(f,new Set),n.get(f).add(o)}this.tablesState.allData=s,this.tablesState.columnCoverage=n,this.tablesState.totalMapCount=r,this.calculateSortedColumns(),this.filterAndRenderTable()}catch(t){console.error("[UIController] Failed to load build manifest:",t),e.innerHTML='

    Failed to load features. The build manifest may not be available.

    '}}}calculateSortedColumns(e=null){let t=["name","map","category"],a=this.tablesState.columnCoverage,i;if(e&&e.size>0)i=e;else{i=new Set;for(let u of a.values())for(let p of u)i.add(p)}let s=i.size;if(s===0){this.tablesState.columns=t,this.tablesState.allColumns=t;return}let n=[];for(let[u,p]of a.entries()){let f=0;for(let g of p)i.has(g)&&f++;f>0&&n.push({column:u,mapCount:f,isUniversal:f===s})}n.sort((u,p)=>u.isUniversal!==p.isUniversal?u.isUniversal?-1:1:u.mapCount!==p.mapCount?p.mapCount-u.mapCount:u.column.localeCompare(p.column));let r=n.map(u=>u.column);this.tablesState.allColumns=[...t,...r];let o=n.filter(u=>u.isUniversal).length,l=n.filter(u=>u.mapCount>=s*.5).length,h=t.length+Math.max(o+l,7);this.tablesState.visibleColumnCount=Math.min(h,this.tablesState.allColumns.length),this.tablesState.columns=this.tablesState.allColumns.slice(0,this.tablesState.visibleColumnCount)}calculateDynamicColumns(e){if(!e||e.length===0)return["name","mapName"];let t=new Set;e.slice(0,100).forEach(s=>{Object.keys(s).forEach(n=>t.add(n))});let i=["name","Name","NAME","mapName","area","perimeter","date"].filter(s=>t.has(s));return t.forEach(s=>{!i.includes(s)&&!["geometry","id"].includes(s)&&i.push(s)}),i.slice(0,10)}filterAndRenderTable(){let e=document.getElementById("tablesContainer");if(!e)return;let t=this.tablesState.searchQuery;if(this.tablesState.filteredData=this.tablesState.allData.filter(a=>t?Object.values(a).some(i=>String(i).toLowerCase().includes(t)):!0),this.tablesState.dataType==="allFeatures"&&this.tablesState.columnCoverage.size>0){let a=new Set(this.tablesState.filteredData.map(i=>i.mapId));this.calculateSortedColumns(a)}if(this.tablesState.sortKey){let a=this.tablesState.sortKey,i=this.tablesState.sortDir==="asc"?1:-1;this.tablesState.filteredData.sort((s,n)=>{let r=s[a]??"",o=n[a]??"";return typeof r=="number"&&typeof o=="number"?(r-o)*i:String(r).localeCompare(String(o))*i})}this.renderTable(e)}renderTable(e){let{filteredData:t,columns:a,currentPage:i,pageSize:s,allColumns:n,visibleColumnCount:r}=this.tablesState,o=Math.ceil(t.length/s),l=(i-1)*s,d=t.slice(l,l+s),h=n&&n.length>r,u=h?n.length-r:0,p=` + ${E} + `}).join(""),i.querySelectorAll(".visibility-btn").forEach(r=>{r.addEventListener("click",()=>{let o=r.dataset.mapId;this.onMapToggle&&this.onMapToggle(o)})}),i.querySelectorAll(".expand-btn").forEach(r=>{r.addEventListener("click",()=>{let o=r.dataset.mapId;this.onExpandToFullMap&&this.onExpandToFullMap(o)})}),i.querySelectorAll(".remove-btn").forEach(r=>{r.addEventListener("click",()=>{let o=r.dataset.mapId;this.onMapUnload&&this.onMapUnload(o)})}),i.querySelectorAll(".partial-visibility-btn").forEach(r=>{r.addEventListener("click",()=>{let o=r.dataset.mapId,l=r.dataset.featureIndex,d=Number(l),h=Number.isFinite(d)&&l!==""?d:l;this.onPartialFeatureToggle&&h!==void 0&&h!==null&&h!==""&&this.onPartialFeatureToggle(o,h)})}),i.querySelectorAll(".partial-unload-btn").forEach(r=>{r.addEventListener("click",()=>{let o=r.dataset.mapId,l=r.dataset.featureIndex,d=Number(l),h=Number.isFinite(d)&&l!==""?d:l;this.onPartialFeatureUnload&&h!==void 0&&h!==null&&h!==""&&this.onPartialFeatureUnload(o,h)})}),i.querySelectorAll(".opacity-toggle-btn").forEach(r=>{r.addEventListener("click",()=>{let o=r.dataset.mapId,l=i.querySelector(`.active-layer-item__opacity-panel[data-map-id="${o}"]`);if(l){let d=l.style.display!=="none";l.style.display=d?"none":"block",r.classList.toggle("active",!d)}})}),s.forEach(r=>{let o=i.querySelector(`.active-layer-item__opacity-panel[data-map-id="${r}"]`),l=i.querySelector(`.opacity-toggle-btn[data-map-id="${r}"]`);o&&(o.style.display="block"),l&&l.classList.add("active")});let n=(r,o,l)=>{l=Math.max(0,Math.min(100,parseInt(l)||0));let d=l/100,h=mapController?.getLayerState?.(r)||mapController?.layerStates?.get(r);if(!h)return;o==="raster"?(h._rasterOpacity=d,h.group?.eachLayer(p=>{p.setOpacity&&p.setOpacity(d)})):o==="stroke"?(h._strokeOpacity=d,h.geoJsonLayers?.forEach(p=>p.setStyle({opacity:d}))):o==="fill"&&(h._fillOpacity=d,h.geoJsonLayers?.forEach(p=>p.setStyle({fillOpacity:d})));let u=i.querySelector(`.active-layer-item[data-map-id="${r}"]`);if(u){let p=u.querySelector(`.${o}-opacity-slider`),f=u.querySelector(`.${o}-opacity-input`);p&&(p.value=l),f&&(f.value=l)}};["raster","stroke","fill"].forEach(r=>{i.querySelectorAll(`.${r}-opacity-slider`).forEach(o=>{o.addEventListener("input",()=>n(o.dataset.mapId,r,o.value))}),i.querySelectorAll(`.${r}-opacity-input`).forEach(o=>{o.addEventListener("change",()=>n(o.dataset.mapId,r,o.value))})}),this._attachActiveLayerDragReorder(i)}_attachActiveLayerDragReorder(e){let t=e.querySelectorAll(".active-layer-item__drag");if(!t.length)return;let a=180;t.forEach(i=>{i.addEventListener("keydown",s=>{if(s.key!=="ArrowUp"&&s.key!=="ArrowDown")return;let n=i.closest(".active-layer-item");if(!n)return;let r=[...e.querySelectorAll(".active-layer-item")],o=r.indexOf(n),l=s.key==="ArrowUp"?o-1:o+1;if(l<0||l>=r.length)return;s.preventDefault(),s.key==="ArrowUp"?e.insertBefore(n,r[l]):e.insertBefore(r[l],n);let d=[...e.querySelectorAll(".active-layer-item")].map(p=>p.dataset.mapId);typeof this.onReorderLayers=="function"&&this.onReorderLayers(d);let h=n.querySelector(".active-layer-item__name")?.textContent?.trim()||"Layer";this.announce?.(`${h} moved to position ${d.indexOf(n.dataset.mapId)+1} of ${d.length}`);let u=i.dataset.mapId;requestAnimationFrame(()=>{(e.querySelector(`.active-layer-item[data-map-id="${u}"] .active-layer-item__drag`)||i).focus()})})}),t.forEach(i=>{i.addEventListener("pointerdown",s=>{if(s.button!==void 0&&s.button!==0)return;let n=i.closest(".active-layer-item");if(!n)return;s.preventDefault();let r=[...e.querySelectorAll(".active-layer-item")].map(w=>w.dataset.mapId),o=s.pointerId,l=n.getBoundingClientRect(),d=s.clientX,h=s.clientY;n.classList.add("active-layer-item--dragging");let u=n.cloneNode(!0);u.classList.remove("active-layer-item--dragging"),u.classList.add("active-layer-item--clone"),Object.assign(u.style,{position:"fixed",left:l.left+"px",top:l.top+"px",width:l.width+"px",margin:"0",pointerEvents:"none",zIndex:"9999",transition:"none",willChange:"transform"}),document.body.appendChild(u);let p=w=>{let S=[...e.querySelectorAll(".active-layer-item")],E=new Map(S.map(C=>[C,C.getBoundingClientRect()]));w();for(let C of S){if(C===n)continue;let T=C.getBoundingClientRect(),z=E.get(C),O=z.left-T.left,I=z.top-T.top;!O&&!I||(C.style.transition="none",C.style.transform=`translate(${O}px, ${I}px)`,C.offsetHeight,C.style.transition=`transform ${a}ms ease`,C.style.transform="")}},f=w=>{if(w.pointerId!==o)return;let S=w.clientX-d,E=w.clientY-h;u.style.transform=`translate(${S}px, ${E}px)`;let C=[...e.querySelectorAll(".active-layer-item:not(.active-layer-item--dragging)")],T=null;for(let O of C){let I=O.getBoundingClientRect();if(w.clientY{T?e.insertBefore(n,T):e.appendChild(n)})},g=()=>{window.removeEventListener("pointermove",f,!0),window.removeEventListener("pointerup",b,!0),window.removeEventListener("pointercancel",v,!0)},y=()=>{let w=n.getBoundingClientRect(),S=u.getBoundingClientRect(),E=w.left-S.left,C=w.top-S.top,T=u.style.transform.match(/translate\(\s*(-?[\d.]+)px\s*,\s*(-?[\d.]+)px\s*\)/),z=T?parseFloat(T[1]):0,O=T?parseFloat(T[2]):0;u.style.transition=`transform ${a}ms ease`,u.style.transform=`translate(${z+E}px, ${O+C}px)`;let I=()=>{u.removeEventListener("transitionend",I),u.parentNode&&u.parentNode.removeChild(u),n.classList.remove("active-layer-item--dragging")};u.addEventListener("transitionend",I),setTimeout(I,a+80)},b=w=>{if(w.pointerId!==o)return;g(),y();let S=[...e.querySelectorAll(".active-layer-item")].map(C=>C.dataset.mapId);(S.length!==r.length||S.some((C,T)=>C!==r[T]))&&typeof this.onReorderLayers=="function"&&this.onReorderLayers(S)},v=w=>{w.pointerId===o&&(g(),y())};window.addEventListener("pointermove",f,!0),window.addEventListener("pointerup",b,!0),window.addEventListener("pointercancel",v,!0)})})}initializeTables(){this.tablesInitialized||(this.setupTablesTab(),this.loadTablesData(),this.tablesInitialized=!0)}setupTablesTab(){let e=document.getElementById("tablesDataType"),t=document.getElementById("tablesSearch"),a=document.getElementById("tablesContainer");if(e&&(this.tablesState={dataType:"maps",searchQuery:"",sortKey:null,sortDir:"asc",currentPage:1,pageSize:50,allData:[],filteredData:[],columns:[],allColumns:[],columnCoverage:new Map,visibleColumnCount:3,manifestData:null},e.addEventListener("change",i=>{this.tablesState.dataType=i.target.value,this.tablesState.currentPage=1,this.loadTablesData()}),t)){let i;t.addEventListener("input",s=>{clearTimeout(i),i=setTimeout(()=>{this.tablesState.searchQuery=s.target.value.trim().toLowerCase(),this.tablesState.currentPage=1,this.filterAndRenderTable()},200)})}}loadTablesData(){let e=document.getElementById("tablesContainer");if(!e)return;let t=P.getData();if(!t){e.innerHTML='

    Loading data...

    ';return}switch(this.tablesState.dataType){case"maps":this.tablesState.allData=(t.maps||[]).map(a=>({id:a.id,name:a.name,category:a.category||"",provider:(a.provider||[]).join(", "),date:a.date||"",featured:a.featured?"Yes":"No"})),this.tablesState.columns=["name","category","provider","date","featured"];break;case"books":this.tablesState.allData=(t.books||[]).map(a=>({id:a.id,title:a.title||a.name,authors:(a.authors||[]).join(", "),year:a.year||"",publisher:a.publisher||""})),this.tablesState.columns=["title","authors","year","publisher"];break;case"allFeatures":e.innerHTML='

    Loading all features... This may take a moment.

    ',this.loadAllFeatures();return;case"features":this.onGetLoadedFeatures?(this.tablesState.allData=this.onGetLoadedFeatures()||[],this.tablesState.columns=this.calculateDynamicColumns(this.tablesState.allData)):(this.tablesState.allData=[],this.tablesState.columns=[]);break}this.filterAndRenderTable()}async loadAllFeatures(){let e=document.getElementById("tablesContainer");if(e){this.tablesState.allData=[],this.tablesState.filteredData=[],this.tablesState.columns=[],this.tablesState.allColumns=[],this.tablesState.columnCoverage=new Map,this.tablesState.visibleColumnCount=3,e.innerHTML='

    Loading all features... This may take a moment.

    ';try{let t=await fetch("./data/build-manifest.json");if(!t.ok)throw new Error(`HTTP ${t.status}: ${t.statusText}`);let a=await t.json();this.tablesState.manifestData=a;let i=P.getData(),s=[],n=new Map,r=Object.keys(a.files||{}).length;for(let[o,l]of Object.entries(a.files||{})){if(!l.features)continue;let d=(i?.maps||[]).find(f=>f.id===o),h=d?.name||o,u=d?.category||"",p=new Set;for(let f of l.features){let g={name:f.name||`Feature ${f.index+1}`,map:h,mapId:o,category:u,index:f.index},y=f.properties;if(y&&typeof y=="object"&&!Array.isArray(y))for(let[b,v]of Object.entries(y))p.add(b),g[b]=v;else if(Array.isArray(y))for(let b of y)p.add(b);s.push(g)}for(let f of p)n.has(f)||n.set(f,new Set),n.get(f).add(o)}this.tablesState.allData=s,this.tablesState.columnCoverage=n,this.tablesState.totalMapCount=r,this.calculateSortedColumns(),this.filterAndRenderTable()}catch(t){console.error("[UIController] Failed to load build manifest:",t),e.innerHTML='

    Failed to load features. The build manifest may not be available.

    '}}}calculateSortedColumns(e=null){let t=["name","map","category"],a=this.tablesState.columnCoverage,i;if(e&&e.size>0)i=e;else{i=new Set;for(let u of a.values())for(let p of u)i.add(p)}let s=i.size;if(s===0){this.tablesState.columns=t,this.tablesState.allColumns=t;return}let n=[];for(let[u,p]of a.entries()){let f=0;for(let g of p)i.has(g)&&f++;f>0&&n.push({column:u,mapCount:f,isUniversal:f===s})}n.sort((u,p)=>u.isUniversal!==p.isUniversal?u.isUniversal?-1:1:u.mapCount!==p.mapCount?p.mapCount-u.mapCount:u.column.localeCompare(p.column));let r=n.map(u=>u.column);this.tablesState.allColumns=[...t,...r];let o=n.filter(u=>u.isUniversal).length,l=n.filter(u=>u.mapCount>=s*.5).length,h=t.length+Math.max(o+l,7);this.tablesState.visibleColumnCount=Math.min(h,this.tablesState.allColumns.length),this.tablesState.columns=this.tablesState.allColumns.slice(0,this.tablesState.visibleColumnCount)}calculateDynamicColumns(e){if(!e||e.length===0)return["name","mapName"];let t=new Set;e.slice(0,100).forEach(s=>{Object.keys(s).forEach(n=>t.add(n))});let i=["name","Name","NAME","mapName","area","perimeter","date"].filter(s=>t.has(s));return t.forEach(s=>{!i.includes(s)&&!["geometry","id"].includes(s)&&i.push(s)}),i.slice(0,10)}filterAndRenderTable(){let e=document.getElementById("tablesContainer");if(!e)return;let t=this.tablesState.searchQuery;if(this.tablesState.filteredData=this.tablesState.allData.filter(a=>t?Object.values(a).some(i=>String(i).toLowerCase().includes(t)):!0),this.tablesState.dataType==="allFeatures"&&this.tablesState.columnCoverage.size>0){let a=new Set(this.tablesState.filteredData.map(i=>i.mapId));this.calculateSortedColumns(a)}if(this.tablesState.sortKey){let a=this.tablesState.sortKey,i=this.tablesState.sortDir==="asc"?1:-1;this.tablesState.filteredData.sort((s,n)=>{let r=s[a]??"",o=n[a]??"";return typeof r=="number"&&typeof o=="number"?(r-o)*i:String(r).localeCompare(String(o))*i})}this.renderTable(e)}renderTable(e){let{filteredData:t,columns:a,currentPage:i,pageSize:s,allColumns:n,visibleColumnCount:r}=this.tablesState,o=Math.ceil(t.length/s),l=(i-1)*s,d=t.slice(l,l+s),h=n&&n.length>r,u=h?n.length-r:0,p=`
    Showing ${this.formatDisplayValue(l+1)}-${this.formatDisplayValue(Math.min(l+s,t.length))} of ${this.formatDisplayValue(t.length)} features ${n&&n.length>3?` · ${this.formatDisplayValue(a.length)} of ${this.formatDisplayValue(n.length)} columns`:""} @@ -1121,7 +1119,7 @@ ${s.map(n).join(",")} ${r.color?``:`${r.icon||""}`} ${this.escapeHtml(r.name)} ${r.type} -
    `}),n+="",t.innerHTML=n,t.querySelectorAll(".explore-item[data-type]").forEach(r=>{r.addEventListener("click",()=>{this.showEntityInfo(r.dataset.type,r.dataset.id)})})}isClassCollapsed(e){try{return De(`class-collapsed.${e}`)==="true"}catch{return!1}}setClassCollapsed(e,t){try{Ye(`class-collapsed.${e}`,t?"true":"false")}catch{}}toggleClassCollapse(e,t){let a=t.querySelector(".class-card__members"),i=a?.classList.contains("collapsed");a&&(a.classList.toggle("collapsed",!i),this.setClassCollapsed(e,!i))}toggleVariants(e,t){let a=t.querySelector(`.variants-container[data-parent-id="${e}"]`);if(a){let i=!a.classList.contains("variants-container--expanded");a.classList.toggle("variants-container--expanded",i);let s=t.querySelector(`.variants-toggle[data-map-id="${e}"]`);s&&s.classList.toggle("active",i),i?this._expandedVariants.add(e):this._expandedVariants.delete(e)}}restoreExpandedVariants(){for(let e of this._expandedVariants){let t=document.querySelector(`.variants-container[data-parent-id="${e}"]`);if(t){t.classList.add("variants-container--expanded");let a=document.querySelector(`.variants-toggle[data-map-id="${e}"]`);a&&a.classList.add("active")}}}renderVariantsDropdown(e,t){if(!e.variants||e.variants.length===0)return"";let a=e.variants.filter(n=>!n.hidden);if(!a.length)return"";let s=`
    `;return a.forEach(n=>{let r=this.isMapLoadedState(n.id,{}),o=n.description||"",l=!!(n.files?.fgb||n.files?.image),d=this.renderThumbnailImage(n.id,"","40px"),h=this.renderThumbnailImage(n.id,"","120px",{defer:"hover"});s+=`
    +
    `}),n+="
    ",t.innerHTML=n,t.querySelectorAll(".explore-item[data-type]").forEach(r=>{r.addEventListener("click",()=>{this.showEntityInfo(r.dataset.type,r.dataset.id)})})}isClassCollapsed(e){try{return He(`class-collapsed.${e}`)==="true"}catch{return!1}}setClassCollapsed(e,t){try{et(`class-collapsed.${e}`,t?"true":"false")}catch{}}toggleClassCollapse(e,t){let a=t.querySelector(".class-card__members"),i=a?.classList.contains("collapsed");a&&(a.classList.toggle("collapsed",!i),this.setClassCollapsed(e,!i))}toggleVariants(e,t){let a=t.querySelector(`.variants-container[data-parent-id="${e}"]`);if(a){let i=!a.classList.contains("variants-container--expanded");a.classList.toggle("variants-container--expanded",i);let s=t.querySelector(`.variants-toggle[data-map-id="${e}"]`);s&&s.classList.toggle("active",i),i?this._expandedVariants.add(e):this._expandedVariants.delete(e)}}restoreExpandedVariants(){for(let e of this._expandedVariants){let t=document.querySelector(`.variants-container[data-parent-id="${e}"]`);if(t){t.classList.add("variants-container--expanded");let a=document.querySelector(`.variants-toggle[data-map-id="${e}"]`);a&&a.classList.add("active")}}}renderVariantsDropdown(e,t){if(!e.variants||e.variants.length===0)return"";let a=e.variants.filter(n=>!n.hidden);if(!a.length)return"";let s=`
    `;return a.forEach(n=>{let r=this.isMapLoadedState(n.id,{}),o=n.description||"",l=!!(n.files?.fgb||n.files?.image),d=this.renderThumbnailImage(n.id,"","40px"),h=this.renderThumbnailImage(n.id,"","120px",{defer:"hover"});s+=`
    ${d?`
    ${d}
    ${h}
    `:'
    '}
    ${this.escapeHtml(n.label||n.id)}
    @@ -1160,7 +1158,7 @@ ${s.map(n).join(",")}
    - `}),s+="",s}shouldExpandVariantsByDefault(e){return!1}getMapIdsFromURL(){let t=window.location.hash.match(/layers=([^&]+)/);return t?t[1].split("%2C").map(decodeURIComponent):[]}async loadSpatialIndex(){return await ye.ensureInitialized(),{features:ye.spatialIndex||[]}}async searchAddressSuggestions(e,t=5){if(!e||e.trim().length<3)return[];this._searchAddressAbortController&&this._searchAddressAbortController.abort(),this._searchAddressAbortController=new AbortController;let i=`https://nominatim.openstreetmap.org/search?q=${encodeURIComponent(e.trim())}&format=json&addressdetails=1&limit=${t}&countrycodes=gb,ie`,s=await fetch(i,{headers:{Accept:"application/json"},signal:this._searchAddressAbortController.signal});if(!s.ok)throw new Error(`Address lookup failed (${s.status})`);let n=await s.json();return Array.isArray(n)?n:[]}buildAddressDisplayName(e){if(!e)return"";let t=e.address||{},a=[];return t.house_number&&t.road?a.push(`${t.house_number} ${t.road}`):t.road?a.push(t.road):t.name&&a.push(t.name),t.suburb?a.push(t.suburb):t.neighbourhood&&a.push(t.neighbourhood),t.city?a.push(t.city):t.town?a.push(t.town):t.village&&a.push(t.village),t.county&&a.push(t.county),a.length>0?a.join(", "):e.display_name||""}getSearchTypeIconSvg(e){return e==="map"?` + `}),s+="",s}shouldExpandVariantsByDefault(e){return!1}getMapIdsFromURL(){let t=window.location.hash.match(/layers=([^&]+)/);return t?t[1].split("%2C").map(decodeURIComponent):[]}async loadSpatialIndex(){return await ve.ensureInitialized(),{features:ve.spatialIndex||[]}}async searchAddressSuggestions(e,t=5){if(!e||e.trim().length<3)return[];this._searchAddressAbortController&&this._searchAddressAbortController.abort(),this._searchAddressAbortController=new AbortController;let i=`https://nominatim.openstreetmap.org/search?q=${encodeURIComponent(e.trim())}&format=json&addressdetails=1&limit=${t}&countrycodes=gb,ie`,s=await fetch(i,{headers:{Accept:"application/json"},signal:this._searchAddressAbortController.signal});if(!s.ok)throw new Error(`Address lookup failed (${s.status})`);let n=await s.json();return Array.isArray(n)?n:[]}buildAddressDisplayName(e){if(!e)return"";let t=e.address||{},a=[];return t.house_number&&t.road?a.push(`${t.house_number} ${t.road}`):t.road?a.push(t.road):t.name&&a.push(t.name),t.suburb?a.push(t.suburb):t.neighbourhood&&a.push(t.neighbourhood),t.city?a.push(t.city):t.town?a.push(t.town):t.village&&a.push(t.village),t.county&&a.push(t.county),a.length>0?a.join(", "):e.display_name||""}getSearchTypeIconSvg(e){return e==="map"?` @@ -1176,7 +1174,7 @@ ${s.map(n).join(",")} `}_tokenMatchesMap(e,t){return!t||!e?!1:!!(t.id&&t.id.toLowerCase().includes(e)||t.slug&&String(t.slug).toLowerCase().includes(e)||t.category&&String(t.category).toLowerCase().includes(e))}_classifyQueryTokens(e,t){let a=(e||"").trim().toLowerCase().split(/\s+/).filter(n=>n.length>=2);if(a.length===0)return{featureTokens:[],layerTokens:[]};if(a.length===1)return{featureTokens:a,layerTokens:[]};let i=[],s=[];for(let n of a)(t.some(o=>this._tokenMatchesMap(n,o))?s:i).push(n);if(i.length===0&&s.length>0){let n=s.slice().sort((o,l)=>l.length-o.length)[0],r=s.indexOf(n);s.splice(r,1),i.push(n)}return{featureTokens:i,layerTokens:s}}_buildFeatureLocatorSvg(e,t){let s={minX:-10.7,maxX:-5.3,minY:51.3,maxY:55.5},n=S=>(S-s.minX)/(s.maxX-s.minX)*36,r=S=>(s.maxY-S)/(s.maxY-s.minY)*44,o="7.5,9 9,5 12,3 16,2 20,2 24,4 27,7 30,11 32,15 32,19 31,22 32,26 31,30 29,33 27,36 24,38 20,39 16,39 13,37 11,35 9,32 7,28 6,24 5,20 5,16 6,13",l=String(t||"#3388ff").replace(/[^#0-9a-zA-Z(),. ]/g,"");if(!Array.isArray(e)||e.length!==4)return``;let[d,h,u,p]=e,f=(d+u)/2,g=(h+p)/2,y=n(f),b=r(g),v=Math.hypot(u-d,p-h),w=Math.max(1.5,Math.min(8,v*6));return` - `}async _loadTownlandFeatureIndex(e){if(this._townlandIndexCache||(this._townlandIndexCache=new Map),this._townlandIndexCache.has(e))return this._townlandIndexCache.get(e);try{let t=`data/maps/townlands/${e}-feature-index.json`,a=await fetch(t);if(!a.ok)return this._townlandIndexCache.set(e,null),null;let i=await a.json(),s=i.columns||["minX","minY","maxX","maxY","diag","chunk","name"],n={minX:s.indexOf("minX"),minY:s.indexOf("minY"),maxX:s.indexOf("maxX"),maxY:s.indexOf("maxY"),chunk:s.indexOf("chunk"),name:s.indexOf("name")};if(n.name<0)return this._townlandIndexCache.set(e,null),null;let r=(i.features||[]).map(o=>({name:o[n.name],bbox:[o[n.minX],o[n.minY],o[n.maxX],o[n.maxY]],chunk:o[n.chunk]}));return this._townlandIndexCache.set(e,r),r}catch{return this._townlandIndexCache.set(e,null),null}}async searchFeatures(e){if(!e||e.length<2)return[];let t=P.maps?.maps||[],a=[];for(let h of t)if(a.push(h),Array.isArray(h.variants))for(let u of h.variants)a.push({...u,category:u.category||h.category});let i=new Map(a.map(h=>[h.id,h])),{featureTokens:s,layerTokens:n}=this._classifyQueryTokens(e,a);if(s.length===0)return[];let r=s.slice().sort((h,u)=>u.length-h.length)[0],o=n.length>0?100:60,l=await ye.searchViaAPI(r,o);if(!l){await ye.ensureInitialized(),ye.useChunkedIndex&&await ye._ensureFullIndex(),l=[];for(let h of ye.spatialIndex||[])if((h.name||"").toLowerCase().includes(r)&&(l.push({id:h.id,name:h.name,mapId:h.mapId,bbox:h.bbox,centroid:h.centroid}),l.length>=o))break}if(n.length>0){let h=(f,g)=>{if(!g)return 0;let y=(g.id||"").toLowerCase(),b=String(g.slug||"").toLowerCase(),v=String(g.category||"").toLowerCase(),w=0;return y===f?w+=6:y.startsWith(f+"-")||y.endsWith("-"+f)?w+=5:y.includes(f)&&(w+=3),b===f?w+=4:b.includes(f)&&(w+=2),v===f?w+=3:v.includes(f)&&(w+=1),w},u=a.map(f=>({m:f,s:n.reduce((g,y)=>g+h(y,f),0)})).filter(f=>f.s>0).sort((f,g)=>g.s-f.s).slice(0,8).map(f=>f.m),p=new Set(l.map(f=>`${f.mapId}::${f.id??f.name}`));for(let f of u){if(f.id==="ni-townlands"||f.id==="roi-townlands"||f.id==="all-ireland-townlands"){let b=await this._loadTownlandFeatureIndex(f.id);if(!b)continue;for(let v of b){if(!(v.name||"").toLowerCase().includes(r))continue;let S=`${f.id}::${v.name}::${v.bbox?.join?.(",")||""}`;p.has(S)||(p.add(S),l.push({id:null,name:v.name,mapId:f.id,bbox:v.bbox,centroid:null}))}continue}let y;try{y=await ye.loadMapIndex(f.id)}catch{y=null}if(y)for(let b of y){if(!(b.name||"").toLowerCase().includes(r))continue;let w=`${b.mapId||f.id}::${b.id??b.name}`;p.has(w)||(p.add(w),l.push({id:b.id,name:b.name,mapId:b.mapId||f.id,bbox:b.bbox,centroid:b.centroid}))}}}if(l.length===0)return[];let d=[];for(let h of l){let u=(h.name||"").toLowerCase(),p=!0,f=0;for(let b of s){if(!u.includes(b)){p=!1;break}f+=1,u.startsWith(b)&&(f+=1),new RegExp(`\\b${b.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\b`).test(u)&&(f+=1)}if(!p)continue;let g=i.get(h.mapId),y=0;for(let b of n)this._tokenMatchesMap(b,g)&&(y+=1);d.push({...h,score:f+y*10,layerScore:y})}return d.sort((h,u)=>u.score!==h.score?u.score-h.score:(h.name||"").localeCompare(u.name||"")),await this._enrichResultsWithBbox(d.slice(0,50)),d}async _enrichResultsWithBbox(e){let t=e.filter(o=>!Array.isArray(o.bbox)||o.bbox.length!==4);if(t.length===0)return;let a=new Set(t.map(o=>o.mapId).filter(Boolean)),i=new Map;for(let o of t)i.set(o.mapId,(i.get(o.mapId)||0)+1);let s=[...a].sort((o,l)=>(i.get(l)||0)-(i.get(o)||0)).slice(0,30),n=await Promise.all(s.map(async o=>{try{let d=o==="ni-townlands"||o==="roi-townlands"||o==="all-ireland-townlands"?await this._loadTownlandFeatureIndex(o):await ye.loadMapIndex(o);if(!d)return[o,null];let h=new Map;for(let u of d)u?.name&&Array.isArray(u.bbox)&&h.set(String(u.name).toLowerCase(),u.bbox);return[o,h]}catch{return[o,null]}})),r=new Map(n);for(let o of t){let l=r.get(o.mapId);if(!l)continue;let d=l.get(String(o.name||"").toLowerCase());d&&(o.bbox=d)}}renderFeatureSearchResults(e,t){let a=document.getElementById("searchAutocomplete");if(!a)return;if(e.length===0){a.innerHTML='
    No features found
    ',a.classList.remove("hidden");return}let i=e.map(s=>{let o=P.getData()?.maps?.find(l=>l.id===s.mapId)?.name||s.mapId;return`
    `}async _loadTownlandFeatureIndex(e){if(this._townlandIndexCache||(this._townlandIndexCache=new Map),this._townlandIndexCache.has(e))return this._townlandIndexCache.get(e);try{let t=`data/maps/townlands/${e}-feature-index.json`,a=await fetch(t);if(!a.ok)return this._townlandIndexCache.set(e,null),null;let i=await a.json(),s=i.columns||["minX","minY","maxX","maxY","diag","chunk","name"],n={minX:s.indexOf("minX"),minY:s.indexOf("minY"),maxX:s.indexOf("maxX"),maxY:s.indexOf("maxY"),chunk:s.indexOf("chunk"),name:s.indexOf("name")};if(n.name<0)return this._townlandIndexCache.set(e,null),null;let r=(i.features||[]).map(o=>({name:o[n.name],bbox:[o[n.minX],o[n.minY],o[n.maxX],o[n.maxY]],chunk:o[n.chunk]}));return this._townlandIndexCache.set(e,r),r}catch{return this._townlandIndexCache.set(e,null),null}}async searchFeatures(e){if(!e||e.length<2)return[];let t=P.maps?.maps||[],a=[];for(let h of t)if(a.push(h),Array.isArray(h.variants))for(let u of h.variants)a.push({...u,category:u.category||h.category});let i=new Map(a.map(h=>[h.id,h])),{featureTokens:s,layerTokens:n}=this._classifyQueryTokens(e,a);if(s.length===0)return[];let r=s.slice().sort((h,u)=>u.length-h.length)[0],o=n.length>0?100:60,l=await ve.searchViaAPI(r,o);if(!l){await ve.ensureInitialized(),ve.useChunkedIndex&&await ve._ensureFullIndex(),l=[];for(let h of ve.spatialIndex||[])if((h.name||"").toLowerCase().includes(r)&&(l.push({id:h.id,name:h.name,mapId:h.mapId,bbox:h.bbox,centroid:h.centroid}),l.length>=o))break}if(n.length>0){let h=(f,g)=>{if(!g)return 0;let y=(g.id||"").toLowerCase(),b=String(g.slug||"").toLowerCase(),v=String(g.category||"").toLowerCase(),w=0;return y===f?w+=6:y.startsWith(f+"-")||y.endsWith("-"+f)?w+=5:y.includes(f)&&(w+=3),b===f?w+=4:b.includes(f)&&(w+=2),v===f?w+=3:v.includes(f)&&(w+=1),w},u=a.map(f=>({m:f,s:n.reduce((g,y)=>g+h(y,f),0)})).filter(f=>f.s>0).sort((f,g)=>g.s-f.s).slice(0,8).map(f=>f.m),p=new Set(l.map(f=>`${f.mapId}::${f.id??f.name}`));for(let f of u){if(f.id==="ni-townlands"||f.id==="roi-townlands"||f.id==="all-ireland-townlands"){let b=await this._loadTownlandFeatureIndex(f.id);if(!b)continue;for(let v of b){if(!(v.name||"").toLowerCase().includes(r))continue;let S=`${f.id}::${v.name}::${v.bbox?.join?.(",")||""}`;p.has(S)||(p.add(S),l.push({id:null,name:v.name,mapId:f.id,bbox:v.bbox,centroid:null}))}continue}let y;try{y=await ve.loadMapIndex(f.id)}catch{y=null}if(y)for(let b of y){if(!(b.name||"").toLowerCase().includes(r))continue;let w=`${b.mapId||f.id}::${b.id??b.name}`;p.has(w)||(p.add(w),l.push({id:b.id,name:b.name,mapId:b.mapId||f.id,bbox:b.bbox,centroid:b.centroid}))}}}if(l.length===0)return[];let d=[];for(let h of l){let u=(h.name||"").toLowerCase(),p=!0,f=0;for(let b of s){if(!u.includes(b)){p=!1;break}f+=1,u.startsWith(b)&&(f+=1),new RegExp(`\\b${b.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\b`).test(u)&&(f+=1)}if(!p)continue;let g=i.get(h.mapId),y=0;for(let b of n)this._tokenMatchesMap(b,g)&&(y+=1);d.push({...h,score:f+y*10,layerScore:y})}return d.sort((h,u)=>u.score!==h.score?u.score-h.score:(h.name||"").localeCompare(u.name||"")),await this._enrichResultsWithBbox(d.slice(0,50)),d}async _enrichResultsWithBbox(e){let t=e.filter(o=>!Array.isArray(o.bbox)||o.bbox.length!==4);if(t.length===0)return;let a=new Set(t.map(o=>o.mapId).filter(Boolean)),i=new Map;for(let o of t)i.set(o.mapId,(i.get(o.mapId)||0)+1);let s=[...a].sort((o,l)=>(i.get(l)||0)-(i.get(o)||0)).slice(0,30),n=await Promise.all(s.map(async o=>{try{let d=o==="ni-townlands"||o==="roi-townlands"||o==="all-ireland-townlands"?await this._loadTownlandFeatureIndex(o):await ve.loadMapIndex(o);if(!d)return[o,null];let h=new Map;for(let u of d)u?.name&&Array.isArray(u.bbox)&&h.set(String(u.name).toLowerCase(),u.bbox);return[o,h]}catch{return[o,null]}})),r=new Map(n);for(let o of t){let l=r.get(o.mapId);if(!l)continue;let d=l.get(String(o.name||"").toLowerCase());d&&(o.bbox=d)}}renderFeatureSearchResults(e,t){let a=document.getElementById("searchAutocomplete");if(!a)return;if(e.length===0){a.innerHTML='
    No features found
    ',a.classList.remove("hidden");return}let i=e.map(s=>{let o=P.getData()?.maps?.find(l=>l.id===s.mapId)?.name||s.mapId;return`
    ${this.highlightText(s.name,t)} ${this.escapeHtml(o)}
    -
    `}).join("");a.innerHTML=i,a.classList.remove("hidden"),a.querySelectorAll(".search-autocomplete__item--feature").forEach(s=>{s.addEventListener("click",()=>{let n=s.dataset.bbox,r=s.dataset.mapId,o=s.dataset.featureId;if(n){let l=n.split(",").map(Number);this.zoomToFeature(l,r,o)}this.hideAutocomplete()})})}zoomToFeature(e,t,a,i=null){if(t&&a&&this.onLoadSingleFeature?this.onLoadSingleFeature(t,a,i,e,{isolate:!0}):t&&this.onMapLoad&&(this.getMapIdsFromURL().includes(t)||this.onMapLoad(t)),e&&e.length===4&&this.onZoomToBbox){let[s,n,r,o]=e;this.onZoomToBbox([[n,s],[o,r]])}a&&this.onHighlightFeature&&setTimeout(()=>{this.onHighlightFeature(t,a)},500),this.announce(`Zooming to ${i||a}`)}highlightText(e,t){if(!t||!e)return this.escapeHtml(e);let a=e.toLowerCase(),i=t.toLowerCase(),s=a.indexOf(i);if(s===-1)return this.escapeHtml(e);let n=e.slice(0,s),r=e.slice(s,s+t.length),o=e.slice(s+t.length);return`${this.escapeHtml(n)}${this.escapeHtml(r)}${this.escapeHtml(o)}`}async getFeaturesInViewport(e,t){let a=[],[i,s]=e;for(let n of t){let r=ye.spatialIndexByMap.get(n)||[];for(let o of r){if(!o.centroid)continue;let[l,d]=o.centroid;d>=i[0]&&d<=s[0]&&l>=i[1]&&l<=s[1]&&a.push(o)}}return a}},Rt=new Dt;typeof window<"u"&&(window.uiController=Rt);(function(){let e=document.createElement("div");e.className="thumbnail-preview",e.innerHTML="",document.body.appendChild(e);let t=e.querySelector("img"),a=".thumb-zone",i=16,s=16;document.addEventListener("mouseenter",n=>{if(!n.target||!n.target.closest)return;let r=n.target.closest(a);if(!r)return;let o=r.querySelector("img");!o||o.style.display==="none"||(t.src=o.src,e.style.display="block")},!0),document.addEventListener("mouseleave",n=>{if(!n.target||!n.target.closest)return;let r=n.target.closest(a);r&&(r.contains(n.relatedTarget)||(e.style.display="none"))},!0),document.addEventListener("mousemove",n=>{if(e.style.display!=="block")return;let r=162,o=162,l=n.clientX+i,d=n.clientY+s;l+r>window.innerWidth&&(l=n.clientX-i-r),d+o>window.innerHeight&&(d=n.clientY-s-o),e.style.left=l+"px",e.style.top=d+"px"}),Rt.ensureMobileThumbnailDismissal?.()})();var A=Rt;W();var as=c=>!!(c.files&&Object.keys(c.files).length||(c.compositeSources||[]).length||(c.variants||[]).length||c.isGroup&&(c.members||[]).length);function Nt(c,e,t,a=new Set){return!c||!c.id||a.has(c.id)?!1:(a.add(c.id),t&&t(c.id)||as(c)?!0:c.cloneOf?Nt(e(c.cloneOf),e,t,a):c.isGroup&&(c.members||[]).length?(c.members||[]).some(i=>Nt(e(i),e,t,a)):!1)}function is(c,e,t){return!c||c.hidden||c.placeholder?!1:Nt(c,e,t)}function Sa(c,e){let t=new Map((c||[]).map(i=>[i.id,i])),a=i=>t.get(i);return(c||[]).filter(i=>is(i,a,e))}W();W();var Ia="test-065",La=`/render/metadata/maps-test.json?v=${Ia}`,Ca=`/render/metadata/main-site-port-plan.json?v=${Ia}`,Ta=[[-10.75,51.35],[-5.35,55.55]];var xa=80,Ht=6,pt=100,Ea=0,nr=Object.freeze({metadataV2:!0,vectorTiles:!0,catalogue:!0,activeLayerControls:!0,labels:!0,featureDetails:!0,featureSearch:!0,urlState:!0,timeSeriesScaffold:!0,electionScaffold:!0,conditionalStylingScaffold:!0,migrationReadiness:!0});W();function ne(c,e,t){let a=Number(c);return Number.isFinite(a)?Math.max(e,Math.min(t,a)):e}function Je(c){if(!Array.isArray(c)||c.length!==2)return null;let[[e,t],[a,i]]=c;return[[t,e],[i,a]]}function Qe(c){let e=Je(c);if(e)return[e[0][0],e[0][1],e[1][0],e[1][1]]}function Ma(c){if(!Array.isArray(c)||c.length!==2)return null;let[[e,t],[a,i]]=c;return[e,t,a,i].every(Number.isFinite)?[[t,a],[i,a],[i,e],[t,e]]:null}function et(c){if(/^https?:\/\//i.test(c))return c;let e=location.origin.replace(/\/$/,"");return c.startsWith("/")?`${e}${c}`:`${e}/${c}`}function tt(c){return[...new Set(c.filter(Boolean))]}function at(c){return String(c??"").trim().toLowerCase()}var mt=class{constructor(e=La,t=Ca,a={}){this.url=e,this.portPlanUrl=t,this.cacheMode=a.cache||"no-cache",this.portPlanCacheMode=a.portPlanCache||"no-cache",this.metadata=null,this.portPlan=null,this.layers=[],this.layerById=new Map,this.layerDetailCache=new Map}async load(){let e=await fetch(this.url,{cache:this.cacheMode});if(!e.ok)throw new Error(`failed to load ${this.url}: ${e.status}`);let t=await e.json();return this.portPlan=await this.loadPortPlan(),this.metadata=ss(t,this.portPlan),this.layers=this.metadata.layers,this.layerById=ka(this.layers),this.metadata}async loadPortPlan(){try{let e=await fetch(this.portPlanUrl,{cache:this.portPlanCacheMode});return e.ok?e.json():null}catch{return null}}getLayer(e){return this.layerById.get(e)||null}async loadLayerDetails(e){let t=this.getLayer(e);return t?.detailUrl?(this.layerDetailCache.has(t.id)||this.layerDetailCache.set(t.id,fetch(t.detailUrl,{cache:"force-cache"}).then(a=>{if(!a.ok)throw new Error(`failed to load ${t.detailUrl}: ${a.status}`);return a.json()}).then(a=>{let i=Aa({...t,...a,detailUrl:t.detailUrl,detailLoaded:!0},this.metadata?.categories||[],t.order||0);return Object.assign(t,i),this.layerById=ka(this.layers),t}).catch(a=>{throw this.layerDetailCache.delete(t.id),a})),this.layerDetailCache.get(t.id)):t}searchLayers(e){let t=at(e).split(/\s+/).filter(Boolean);return t.length?this.layers.filter(a=>t.every(i=>a.searchText.includes(i))):this.layers}};function ka(c){let e=new Map;for(let t of c||[])for(let a of[t.id,t.sourceMapId,t.sourceMapId?`port-${t.sourceMapId}`:null])a&&!e.has(a)&&e.set(a,t);return e}function ss(c,e=null){let t=Array.isArray(e?.rows)?e.rows:[],a=c.layers||[],i=ns(c.categories||[],[...a,...t.map(os)]),s=a.map((l,d)=>Aa({...l,conversionStatus:"converted",loadable:!0},i,d)),n=new Set(s.flatMap(l=>[l.id,l.sourceMapId]).filter(Boolean)),r=t.filter(l=>!Pa(l.conversionStatus)&&!n.has(l.sourceMapId)).map((l,d)=>rs(l,i,s.length+d)),o=[...s,...r];return{version:Number(c.version||1),schemaVersion:Number(c.schemaVersion||2),description:c.description||"",publicMapCount:Number.isFinite(c.publicMapCount)?c.publicMapCount:void 0,categories:i,capabilities:c.capabilities||{},readiness:c.readiness||{},timeSeriesChains:c.timeSeriesChains||[],electionCatalogues:c.electionCatalogues||[],portPlanSummary:e?.totals||null,layers:o}}function ns(c,e){let t=new Map;for(let a of c){let i={id:a.id||ft(a.name),name:a.name||a.id,group:a.group||"Maps",description:a.description||""};t.set(i.id,i),t.set(i.name,i)}for(let a of e){let i=a.category||"Maps";if(!t.has(i)){let s={id:ft(i),name:i,group:a.group||"Maps",description:""};t.set(s.id,s),t.set(s.name,s)}}return[...new Map([...t.values()].map(a=>[a.id,a])).values()]}function Aa(c,e,t){let a=c.category||"Maps",i=e.find(o=>o.name===a||o.id===a)||{id:ft(a),name:a,group:"Maps"},s=Array.isArray(c.references)?c.references:[],n=Array.isArray(c.sourceDownloads)?c.sourceDownloads:[],r=tt([...Array.isArray(c.keywords)?c.keywords:[],c.name,c.id,c.sourceMapId,i.name,i.group,c.provider,c.status,c.description,...Array.isArray(c.sourceCredits)?c.sourceCredits:[]]);return{...c,isConverted:Pa(c.conversionStatus)||c.loadable===!0,loadable:c.loadable!==!1&&c.sourceType!=="unconverted",category:i.name,categoryId:i.id,group:c.group||i.group||"Maps",renderer:c.renderer||"maplibre",geometryType:c.geometryType||"polygon",status:c.status||"pilot",description:c.description||c.notes||"",dateAdded:c.dateAdded||null,dateEffective:c.dateEffective||null,sourceCredits:Array.isArray(c.sourceCredits)?c.sourceCredits:$a(c.provider),references:s,sourceDownloads:n,variants:Array.isArray(c.variants)?c.variants:[],order:Number.isFinite(Number(c.order))?Number(c.order):t,searchText:at(r.join(" ")),migration:{sourceMapId:c.sourceMapId||c.id,portedFromMainSite:!!c.sourceMapId,unsupportedReason:c.unsupportedReason||null}}}function rs(c,e,t){let a=c.category||"Uncategorised",i=e.find(l=>l.name===a||l.id===c.categoryId)||{id:c.categoryId||ft(a),name:a,group:c.group||"Maps"},s=(c.sourceDownloads||[]).filter(l=>l.url).map(l=>({label:l.label||"Source",file:l.url})),n=(c.references||[]).filter(l=>l.url).map(l=>({label:l.label||"Reference",url:l.url})),r=c.sourceFiles||[],o=tt([c.name,c.sourceMapId,c.parentId,c.category,c.group,c.provider,c.description,c.conversionStatus,c.recommendedTarget,...Array.isArray(c.sourceCredits)?c.sourceCredits:[],...(r||[]).map(l=>l.file)]);return{id:`port-${c.sourceMapId}`,sourceMapId:c.sourceMapId,parentId:c.parentId,name:c.name||c.sourceMapId,category:i.name,categoryId:i.id,group:c.group||i.group||"Maps",date:c.date,dateAdded:c.dateAdded,dateEffective:c.dateEffective,provider:c.provider,description:c.description||"",sourceCredits:Array.isArray(c.sourceCredits)?c.sourceCredits:$a(c.provider),renderer:"maplibre",sourceType:"unconverted",geometryType:"unknown",status:"not-yet-converted",conversionStatus:c.conversionStatus,recommendedTarget:c.recommendedTarget,unsupportedReason:c.unsupportedReason,bounds:c.bounds,style:c.style||{},sourceDownloads:s,references:n,sourceFiles:r,variants:[],variantCount:c.variants||0,order:t,isConverted:!1,loadable:!1,searchText:at(o.join(" ")),migration:{sourceMapId:c.sourceMapId,portedFromMainSite:!0,unsupportedReason:c.unsupportedReason||c.conversionStatus}}}function $a(c){return Array.isArray(c)?c.map(e=>String(e)).filter(Boolean):c?[String(c)]:[]}function Pa(c){return c==="converted"||c==="convertedComposite"||c==="convertedAlias"}function os(c){return{category:c.category||c.categoryId||"Uncategorised",group:c.group||"Maps"}}function ft(c){return at(c).replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")||"maps"}W();var sa=dt(ut());W();var Ee=dt(ut());W();W();var _e=Uint8Array,Ue=Uint16Array,ls=Int32Array,Ba=new _e([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Fa=new _e([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),cs=new _e([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Da=function(c,e){for(var t=new Ue(31),a=0;a<31;++a)t[a]=e+=1<>1|(Q&21845)<<1,xe=(xe&52428)>>2|(xe&13107)<<2,xe=(xe&61680)>>4|(xe&3855)<<4,Vt[Q]=((xe&65280)>>8|(xe&255)<<8)>>1;var xe,Q,it=(function(c,e,t){for(var a=c.length,i=0,s=new Ue(e);i>o]=l}else for(r=new Ue(a),i=0;i>15-c[i]);return r}),st=new _e(288);for(Q=0;Q<144;++Q)st[Q]=8;var Q;for(Q=144;Q<256;++Q)st[Q]=9;var Q;for(Q=256;Q<280;++Q)st[Q]=7;var Q;for(Q=280;Q<288;++Q)st[Q]=8;var Q,Oa=new _e(32);for(Q=0;Q<32;++Q)Oa[Q]=5;var Q;var hs=it(st,9,1);var ps=it(Oa,5,1),Ot=function(c){for(var e=c[0],t=1;te&&(e=c[t]);return e},Ie=function(c,e,t){var a=e/8|0;return(c[a]|c[a+1]<<8)>>(e&7)&t},zt=function(c,e){var t=e/8|0;return(c[t]|c[t+1]<<8|c[t+2]<<16)>>(e&7)},ms=function(c){return(c+7)/8|0},fs=function(c,e,t){return(e==null||e<0)&&(e=0),(t==null||t>c.length)&&(t=c.length),new _e(c.subarray(e,t))};var gs=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],ve=function(c,e,t){var a=new Error(e||gs[c]);if(a.code=c,Error.captureStackTrace&&Error.captureStackTrace(a,ve),!t)throw a;return a},Ut=function(c,e,t,a){var i=c.length,s=a?a.length:0;if(!i||e.f&&!e.l)return t||new _e(0);var n=!t,r=n||e.i!=2,o=e.i;n&&(t=new _e(i*3));var l=function(re){var Fe=t.length;if(re>Fe){var Me=new _e(Math.max(Fe*2,re));Me.set(t),t=Me}},d=e.f||0,h=e.p||0,u=e.b||0,p=e.l,f=e.d,g=e.m,y=e.n,b=i*8;do{if(!p){d=Ie(c,h,1);var v=Ie(c,h+1,3);if(h+=3,v)if(v==1)p=hs,f=ps,g=9,y=5;else if(v==2){var C=Ie(c,h,31)+257,T=Ie(c,h+10,15)+4,V=C+Ie(c,h+5,31)+1;h+=14;for(var z=new _e(V),I=new _e(19),x=0;x>4;if(w<16)z[x++]=w;else{var N=0,U=0;for(w==16?(U=3+Ie(c,h,3),h+=2,N=z[x-1]):w==17?(U=3+Ie(c,h,7),h+=3):w==18&&(U=11+Ie(c,h,127),h+=7);U--;)z[x++]=N}}var K=z.subarray(0,C),G=z.subarray(C);g=Ot(K),y=Ot(G),p=it(K,g,1),f=it(G,y,1)}else ve(1);else{var w=ms(h)+4,S=c[w-4]|c[w-3]<<8,M=w+S;if(M>i){o&&ve(0);break}r&&l(u+S),t.set(c.subarray(w,M),u),e.b=u+=S,e.p=h=M*8,e.f=d;continue}if(h>b){o&&ve(0);break}}r&&l(u+131072);for(var j=(1<>4;if(h+=N&15,h>b){o&&ve(0);break}if(N||ve(2),q<256)t[u++]=q;else if(q==256){D=h,p=null;break}else{var J=q-254;if(q>264){var x=q-257,se=Ba[x];J=Ie(c,h,(1<>4;ee||ve(3),h+=ee&15;var G=us[he];if(he>3){var se=Fa[he];G+=zt(c,h)&(1<b){o&&ve(0);break}r&&l(u+131072);var ce=u+J;if(u>3&1)+(e>>4&1);a>0;a-=!c[t++]);return t+(e&2)},vs=function(c){var e=c.length;return(c[e-4]|c[e-3]<<8|c[e-2]<<16|c[e-1]<<24)>>>0};var _s=function(c,e){return((c[0]&15)!=8||c[0]>>4>7||(c[0]<<8|c[1])%31)&&ve(6,"invalid zlib data"),(c[1]>>5&1)==+!e&&ve(6,"invalid zlib data: "+(c[1]&32?"need":"unexpected")+" dictionary"),(c[1]>>3&4)+2};function ws(c,e){return Ut(c,{i:2},e&&e.out,e&&e.dictionary)}function Ss(c,e){var t=bs(c);return t+8>c.length&&ve(6,"invalid gzip data"),Ut(c.subarray(t,-8),{i:2},e&&e.out||new _e(vs(c)),e&&e.dictionary)}function Is(c,e){return Ut(c.subarray(_s(c,e&&e.dictionary),-4),{i:2},e&&e.out,e&&e.dictionary)}function za(c,e){return c[0]==31&&c[1]==139&&c[2]==8?Ss(c,e):(c[0]&15)!=8||c[0]>>4>7||(c[0]<<8|c[1])%31?ws(c,e):Is(c,e)}var Ls=typeof TextDecoder<"u"&&new TextDecoder,Cs=0;try{Ls.decode(ys,{stream:!0}),Cs=1}catch{}var Ts=Object.defineProperty,xs=Math.pow,te=(c,e)=>Ts(c,"name",{value:e,configurable:!0}),ue=(c,e,t)=>new Promise((a,i)=>{var s=o=>{try{r(t.next(o))}catch(l){i(l)}},n=o=>{try{r(t.throw(o))}catch(l){i(l)}},r=o=>o.done?a(o.value):Promise.resolve(o.value).then(s,n);r((t=t.apply(c,e)).next())}),br=te((c,e)=>{let t=!1,a="",i=L.GridLayer.extend({createTile:te((s,n)=>{let r=document.createElement("img"),o=new AbortController,l=o.signal;return r.cancel=()=>{o.abort()},t||(c.getHeader().then(d=>{d.tileType===1||d.tileType===6?console.error("Error: archive contains vector tiles, but leafletRasterLayer is for displaying raster tiles. See https://github.com/protomaps/PMTiles/tree/main/js for details."):d.tileType===2?a="image/png":d.tileType===3?a="image/jpeg":d.tileType===4?a="image/webp":d.tileType===5&&(a="image/avif")}),t=!0),c.getZxy(s.z,s.x,s.y,l).then(d=>{if(d){let h=new Blob([d.data],{type:a}),u=window.URL.createObjectURL(h);r.src=u}else r.style.display="none";r.cancel=void 0,n(void 0,r)}).catch(d=>{if(d.name!=="AbortError")throw d}),r},"createTile"),_removeTile:te(function(s){let n=this._tiles[s];n&&(n.el.cancel&&n.el.cancel(),n.el.src&&window.URL.revokeObjectURL(n.el.src),n.el.width=0,n.el.height=0,n.el.deleted=!0,L.DomUtil.remove(n.el),delete this._tiles[s],this.fire("tileunload",{tile:n.el,coords:this._keyToTileCoords(s)}))},"_removeTile")});return new i(e)},"leafletRasterLayer"),Es=te(c=>(e,t)=>{if(t instanceof AbortController)return c(e,t);let a=new AbortController;return c(e,a).then(i=>t(void 0,i.data,i.cacheControl||"",i.expires||""),i=>t(i)).catch(i=>t(i)),{cancel:te(()=>a.abort(),"cancel")}},"v3compat"),Va=class{constructor(e){this.tilev4=te((t,a)=>ue(this,null,function*(){if(t.type==="json"){let p=t.url.substr(10),f=this.tiles.get(p);if(f||(f=new gt(p),this.tiles.set(p,f)),this.metadata){let y=yield f.getTileJson(t.url);return a.signal.throwIfAborted(),{data:y}}let g=yield f.getHeader();return a.signal.throwIfAborted(),(g.minLon>=g.maxLon||g.minLat>=g.maxLat)&&console.error(`Bounds of PMTiles archive ${g.minLon},${g.minLat},${g.maxLon},${g.maxLat} are not valid.`),{data:{tiles:[`${t.url}/{z}/{x}/{y}`],minzoom:g.minZoom,maxzoom:g.maxZoom,bounds:[g.minLon,g.minLat,g.maxLon,g.maxLat]}}}let i=new RegExp(/pmtiles:\/\/(.+)\/(\d+)\/(\d+)\/(\d+)/),s=t.url.match(i);if(!s)throw new Error("Invalid PMTiles protocol URL");let n=s[1],r=this.tiles.get(n);r||(r=new gt(n),this.tiles.set(n,r));let o=s[2],l=s[3],d=s[4],h=yield r?.getZxy(+o,+l,+d,a.signal);if(a.signal.throwIfAborted(),h)return{data:new Uint8Array(h.data),cacheControl:h.cacheControl,expires:h.expires};let u=yield r.getHeader();if(u.tileType===1||u.tileType===6){if(this.errorOnMissingTile)throw new Error("Tile not found.");return{data:new Uint8Array}}return{data:null}}),"tilev4"),this.tile=Es(this.tilev4),this.tiles=new Map,this.metadata=e?.metadata||!1,this.errorOnMissingTile=e?.errorOnMissingTile||!1}add(e){this.tiles.set(e.source.getKey(),e)}get(e){return this.tiles.get(e)}};te(Va,"Protocol");var Ua=Va;function qa(c,e){return(e>>>0)*4294967296+(c>>>0)}te(qa,"toNum");function Ga(c,e){let t=e.buf,a=t[e.pos++],i=(a&112)>>4;if(a<128||(a=t[e.pos++],i|=(a&127)<<3,a<128)||(a=t[e.pos++],i|=(a&127)<<10,a<128)||(a=t[e.pos++],i|=(a&127)<<17,a<128)||(a=t[e.pos++],i|=(a&127)<<24,a<128)||(a=t[e.pos++],i|=(a&1)<<31,a<128))return qa(c,i);throw new Error("Expected varint not more than 10 bytes")}te(Ga,"readVarintRemainder");function qe(c){let e=c.buf,t=e[c.pos++],a=t&127;return t<128||(t=e[c.pos++],a|=(t&127)<<7,t<128)||(t=e[c.pos++],a|=(t&127)<<14,t<128)||(t=e[c.pos++],a|=(t&127)<<21,t<128)?a:(t=e[c.pos],a|=(t&15)<<28,Ga(a,c))}te(qe,"readVarint");function Gt(c,e,t,a,i){return i===0?a!==0?[c-1-t,c-1-e]:[t,e]:[e,t]}te(Gt,"rotate");function ja(c,e,t){if(c>26)throw new Error("Tile zoom level exceeds max safe number limit (26)");if(e>=1<=1<0;r>>=1){let o=s&r,l=n&r;a+=(3*o^l)*(1<>1;if(e>26)throw new Error("Tile zoom level exceeds max safe number limit (26)");let t=((1<(c[c.Unknown=0]="Unknown",c[c.None=1]="None",c[c.Gzip=2]="Gzip",c[c.Brotli=3]="Brotli",c[c.Zstd=4]="Zstd",c))(ks||{});function yt(c,e){return ue(this,null,function*(){if(e===1||e===0)return c;if(e===2){if(typeof globalThis.DecompressionStream>"u")return za(new Uint8Array(c));let t=new Response(c).body;if(!t)throw new Error("Failed to read response stream");let a=t.pipeThrough(new globalThis.DecompressionStream("gzip"));return new Response(a).arrayBuffer()}throw new Error("Compression method not supported")})}te(yt,"defaultDecompress");var As=(c=>(c[c.Unknown=0]="Unknown",c[c.Mvt=1]="Mvt",c[c.Png=2]="Png",c[c.Jpeg=3]="Jpeg",c[c.Webp=4]="Webp",c[c.Avif=5]="Avif",c[c.Mlt=6]="Mlt",c))(As||{});function Ka(c){return c===1?".mvt":c===2?".png":c===3?".jpg":c===4?".webp":c===5?".avif":c===6?".mlt":""}te(Ka,"tileTypeExt");var $s=127;function Za(c,e){let t=0,a=c.length-1;for(;t<=a;){let i=a+t>>1,s=e-c[i].tileId;if(s>0)t=i+1;else if(s<0)a=i-1;else return c[i]}return a>=0&&(c[a].runLength===0||e-c[a].tileId-1,o=/Chrome|Chromium|Edg|OPR|Brave/.test(n);this.chromeWindowsNoCache=!1,r&&o&&(this.chromeWindowsNoCache=!0)}getKey(){return this.url}setHeaders(e){this.customHeaders=e}getBytes(e,t,a,i){return ue(this,null,function*(){let s,n;a?n=a:(s=new AbortController,n=s.signal);let r=new Headers(this.customHeaders);r.set("range",`bytes=${e}-${e+t-1}`);let o;this.mustReload?o="reload":this.chromeWindowsNoCache&&(o="no-store");let l=yield fetch(this.url,{signal:n,cache:o,headers:r,credentials:this.credentials});if(e===0&&l.status===416){let u=l.headers.get("Content-Range");if(!u||!u.startsWith("bytes */"))throw new Error("Missing content-length on 416 response");let p=+u.substr(8);r.set("range",`bytes=0-${p-1}`),l=yield fetch(this.url,{signal:n,cache:"reload",headers:r,credentials:this.credentials})}let d=l.headers.get("Etag");if(d!=null&&d.startsWith("W/")&&(d=null),l.status===416||i&&d&&d!==i)throw this.mustReload=!0,new qt(`Server returned non-matching ETag ${i} after one retry. Check browser extensions and servers for issues that may affect correct ETag headers.`);if(l.status>=300)throw new Error(`Bad response code: ${l.status}`);let h=l.headers.get("Content-Length");if(l.status===200&&(!h||+h>t))throw s&&s.abort(),new Error("Server returned no content-length header or content-length exceeding request. Check that your storage backend supports HTTP Byte Serving.");return{data:yield l.arrayBuffer(),etag:d||void 0,cacheControl:l.headers.get("Cache-Control")||void 0,expires:l.headers.get("Expires")||void 0}})}};te(Ya,"FetchSource");var Bs=Ya;function we(c,e){let t=c.getUint32(e+4,!0),a=c.getUint32(e+0,!0);return t*xs(2,32)+a}te(we,"getUint64");function Xa(c,e){let t=new DataView(c),a=t.getUint8(7);if(a>3)throw new Error(`Archive is spec version ${a} but this library supports up to spec version 3`);return{specVersion:a,rootDirectoryOffset:we(t,8),rootDirectoryLength:we(t,16),jsonMetadataOffset:we(t,24),jsonMetadataLength:we(t,32),leafDirectoryOffset:we(t,40),leafDirectoryLength:we(t,48),tileDataOffset:we(t,56),tileDataLength:we(t,64),numAddressedTiles:we(t,72),numTileEntries:we(t,80),numTileContents:we(t,88),clustered:t.getUint8(96)===1,internalCompression:t.getUint8(97),tileCompression:t.getUint8(98),tileType:t.getUint8(99),minZoom:t.getUint8(100),maxZoom:t.getUint8(101),minLon:t.getInt32(102,!0)/1e7,minLat:t.getInt32(106,!0)/1e7,maxLon:t.getInt32(110,!0)/1e7,maxLat:t.getInt32(114,!0)/1e7,centerZoom:t.getUint8(118),centerLon:t.getInt32(119,!0)/1e7,centerLat:t.getInt32(123,!0)/1e7,etag:e}}te(Xa,"bytesToHeader");function jt(c){let e={buf:new Uint8Array(c),pos:0},t=qe(e),a=[],i=0;for(let s=0;s0?a[s].offset=a[s-1].offset+a[s-1].length:a[s].offset=n-1}return a}te(jt,"deserializeIndex");var Ja=class extends Error{};te(Ja,"EtagMismatch");var qt=Ja;function Wt(c,e){return ue(this,null,function*(){let t=yield c.getBytes(0,16384);if(new DataView(t.data).getUint16(0,!0)!==19792)throw new Error("Wrong magic number for PMTiles archive");let a=t.data.slice(0,$s),i=Xa(a,t.etag),s=t.data.slice(i.rootDirectoryOffset,i.rootDirectoryOffset+i.rootDirectoryLength),n=`${c.getKey()}|${i.etag||""}|${i.rootDirectoryOffset}|${i.rootDirectoryLength}`,r=jt(yield e(s,i.internalCompression));return[i,[n,r.length,r]]})}te(Wt,"getHeaderAndRoot");function Kt(c,e,t,a,i,s){return ue(this,null,function*(){let n=yield c.getBytes(t,a,s,i.etag),r=yield e(n.data,i.internalCompression),o=jt(r);if(o.length===0)throw new Error("Empty directory is invalid");return o})}te(Kt,"getDirectory");var Fs=class{constructor(e=100,t=!0,a=yt){this.cache=new Map,this.maxCacheEntries=e,this.counter=1,this.decompress=a}getHeader(e){return ue(this,null,function*(){let t=e.getKey(),a=this.cache.get(t);if(a)return a.lastUsed=this.counter++,a.data;let i=yield Wt(e,this.decompress);return i[1]&&this.cache.set(i[1][0],{lastUsed:this.counter++,data:i[1][2]}),this.cache.set(t,{lastUsed:this.counter++,data:i[0]}),this.prune(),i[0]})}getDirectory(e,t,a,i,s){return ue(this,null,function*(){let n=`${e.getKey()}|${i.etag||""}|${t}|${a}`,r=this.cache.get(n);if(r)return r.lastUsed=this.counter++,r.data;let o=yield Kt(e,this.decompress,t,a,i,s);return this.cache.set(n,{lastUsed:this.counter++,data:o}),this.prune(),o})}prune(){if(this.cache.size>this.maxCacheEntries){let e=1/0,t;this.cache.forEach((a,i)=>{a.lastUsed{Wt(e,this.decompress).then(r=>{r[1]&&this.cache.set(r[1][0],{lastUsed:this.counter++,data:Promise.resolve(r[1][2])}),s(r[0]),this.prune()}).catch(r=>{n(r)})});return this.cache.set(t,{lastUsed:this.counter++,data:i}),i})}trackSignal(e,t,a){t.refs++,a.addEventListener("abort",()=>{--t.refs<=0&&this.pendingFetches.get(e)===t&&(t.controller.abort(),this.cache.delete(e),this.pendingFetches.delete(e))},{once:!0})}getDirectory(e,t,a,i,s){return ue(this,null,function*(){let n=`${e.getKey()}|${i.etag||""}|${t}|${a}`,r=this.cache.get(n);if(r){r.lastUsed=this.counter++;let h=this.pendingFetches.get(n);return h&&this.trackSignal(n,h,s??new AbortController().signal),yield r.data}let o=new AbortController,l={controller:o,refs:0};this.trackSignal(n,l,s??new AbortController().signal),this.pendingFetches.set(n,l);let d=new Promise((h,u)=>{Kt(e,this.decompress,t,a,i,o.signal).then(p=>{this.pendingFetches.delete(n),h(p),this.prune()}).catch(p=>{u(p)})});return this.cache.set(n,{lastUsed:this.counter++,data:d}),d})}prune(){if(this.cache.size>=this.maxCacheEntries){let e=1/0,t;this.cache.forEach((a,i)=>{a.lastUsed{this.getHeader(e).then(n=>{i(),this.invalidations.delete(t)}).catch(n=>{s(n)})});this.invalidations.set(t,a)})}};te(Qa,"SharedPromiseCache");var Ds=Qa,ei=class{constructor(e,t,a){typeof e=="string"?this.source=new Bs(e):this.source=e,a?this.decompress=a:this.decompress=yt,t?this.cache=t:this.cache=new Ds}getHeader(){return ue(this,null,function*(){return yield this.cache.getHeader(this.source)})}getZxyAttempt(e,t,a,i){return ue(this,null,function*(){let s=ja(e,t,a),n=yield this.cache.getHeader(this.source);if(i?.throwIfAborted(),en.maxZoom)return;let r=n.rootDirectoryOffset,o=n.rootDirectoryLength;for(let l=0;l<=3;l++){let d=yield this.cache.getDirectory(this.source,r,o,n,i);i?.throwIfAborted();let h=Za(d,s);if(h){if(h.runLength>0){let u=yield this.source.getBytes(n.tileDataOffset+h.offset,h.length,i,n.etag);return{data:yield this.decompress(u.data,n.tileCompression),cacheControl:u.cacheControl,expires:u.expires}}r=n.leafDirectoryOffset+h.offset,o=h.length}else return}throw new Error("Maximum directory depth exceeded")})}getZxy(e,t,a,i){return ue(this,null,function*(){try{return yield this.getZxyAttempt(e,t,a,i)}catch(s){if(s instanceof qt)return this.cache.invalidate(this.source),yield this.getZxyAttempt(e,t,a,i);throw s}})}getMetadataAttempt(){return ue(this,null,function*(){let e=yield this.cache.getHeader(this.source),t=yield this.source.getBytes(e.jsonMetadataOffset,e.jsonMetadataLength,void 0,e.etag),a=yield this.decompress(t.data,e.internalCompression),i=new TextDecoder("utf-8");return JSON.parse(i.decode(a))})}getMetadata(){return ue(this,null,function*(){try{return yield this.getMetadataAttempt()}catch(e){if(e instanceof qt)return this.cache.invalidate(this.source),yield this.getMetadataAttempt();throw e}})}getTileJson(e){return ue(this,null,function*(){let t=yield this.getHeader(),a=yield this.getMetadata(),i=Ka(t.tileType);return{tilejson:"3.0.0",scheme:"xyz",tiles:[`${e}/{z}/{x}/{y}${i}`],vector_layers:a.vector_layers,attribution:a.attribution,description:a.description,name:a.name,version:a.version,bounds:[t.minLon,t.minLat,t.maxLon,t.maxLat],center:[t.centerLon,t.centerLat,t.centerZoom],minzoom:t.minZoom,maxzoom:t.maxZoom}})}};te(ei,"PMTiles");var gt=ei;W();var ai=dt(ut()),Rs=` + `}).join("");a.innerHTML=i,a.classList.remove("hidden"),a.querySelectorAll(".search-autocomplete__item--feature").forEach(s=>{s.addEventListener("click",()=>{let n=s.dataset.bbox,r=s.dataset.mapId,o=s.dataset.featureId;if(n){let l=n.split(",").map(Number);this.zoomToFeature(l,r,o)}this.hideAutocomplete()})})}zoomToFeature(e,t,a,i=null){if(t&&a&&this.onLoadSingleFeature?this.onLoadSingleFeature(t,a,i,e,{isolate:!0}):t&&this.onMapLoad&&(this.getMapIdsFromURL().includes(t)||this.onMapLoad(t)),e&&e.length===4&&this.onZoomToBbox){let[s,n,r,o]=e;this.onZoomToBbox([[n,s],[o,r]])}a&&this.onHighlightFeature&&setTimeout(()=>{this.onHighlightFeature(t,a)},500),this.announce(`Zooming to ${i||a}`)}highlightText(e,t){if(!t||!e)return this.escapeHtml(e);let a=e.toLowerCase(),i=t.toLowerCase(),s=a.indexOf(i);if(s===-1)return this.escapeHtml(e);let n=e.slice(0,s),r=e.slice(s,s+t.length),o=e.slice(s+t.length);return`${this.escapeHtml(n)}${this.escapeHtml(r)}${this.escapeHtml(o)}`}async getFeaturesInViewport(e,t){let a=[],[i,s]=e;for(let n of t){let r=ve.spatialIndexByMap.get(n)||[];for(let o of r){if(!o.centroid)continue;let[l,d]=o.centroid;d>=i[0]&&d<=s[0]&&l>=i[1]&&l<=s[1]&&a.push(o)}}return a}},Vt=new zt;typeof window<"u"&&(window.uiController=Vt);(function(){let e=document.createElement("div");e.className="thumbnail-preview",e.innerHTML="",document.body.appendChild(e);let t=e.querySelector("img"),a=".thumb-zone",i=16,s=16;document.addEventListener("mouseenter",n=>{if(!n.target||!n.target.closest)return;let r=n.target.closest(a);if(!r)return;let o=r.querySelector("img");!o||o.style.display==="none"||(t.src=o.src,e.style.display="block")},!0),document.addEventListener("mouseleave",n=>{if(!n.target||!n.target.closest)return;let r=n.target.closest(a);r&&(r.contains(n.relatedTarget)||(e.style.display="none"))},!0),document.addEventListener("mousemove",n=>{if(e.style.display!=="block")return;let r=162,o=162,l=n.clientX+i,d=n.clientY+s;l+r>window.innerWidth&&(l=n.clientX-i-r),d+o>window.innerHeight&&(d=n.clientY-s-o),e.style.left=l+"px",e.style.top=d+"px"}),Vt.ensureMobileThumbnailDismissal?.()})();var A=Vt;W();var cs=c=>!!(c.files&&Object.keys(c.files).length||(c.compositeSources||[]).length||(c.variants||[]).length||c.isGroup&&(c.members||[]).length);function Ut(c,e,t,a=new Set){return!c||!c.id||a.has(c.id)?!1:(a.add(c.id),t&&t(c.id)||cs(c)?!0:c.cloneOf?Ut(e(c.cloneOf),e,t,a):c.isGroup&&(c.members||[]).length?(c.members||[]).some(i=>Ut(e(i),e,t,a)):!1)}function ds(c,e,t){return!c||c.hidden||c.placeholder?!1:Ut(c,e,t)}function Ma(c,e){let t=new Map((c||[]).map(i=>[i.id,i])),a=i=>t.get(i);return(c||[]).filter(i=>ds(i,a,e))}W();W();var Ea="test-065",ka=`/render/metadata/maps-test.json?v=${Ea}`,Aa=`/render/metadata/main-site-port-plan.json?v=${Ea}`,$a=[[-10.75,51.35],[-5.35,55.55]];var Pa=80,qt=6,yt=100,Ba=0,hr=Object.freeze({metadataV2:!0,vectorTiles:!0,catalogue:!0,activeLayerControls:!0,labels:!0,featureDetails:!0,featureSearch:!0,urlState:!0,timeSeriesScaffold:!0,electionScaffold:!0,conditionalStylingScaffold:!0,migrationReadiness:!0});W();function ne(c,e,t){let a=Number(c);return Number.isFinite(a)?Math.max(e,Math.min(t,a)):e}function at(c){if(!Array.isArray(c)||c.length!==2)return null;let[[e,t],[a,i]]=c;return[[t,e],[i,a]]}function it(c){let e=at(c);if(e)return[e[0][0],e[0][1],e[1][0],e[1][1]]}function Fa(c){if(!Array.isArray(c)||c.length!==2)return null;let[[e,t],[a,i]]=c;return[e,t,a,i].every(Number.isFinite)?[[t,a],[i,a],[i,e],[t,e]]:null}function st(c){if(/^https?:\/\//i.test(c))return c;let e=location.origin.replace(/\/$/,"");return c.startsWith("/")?`${e}${c}`:`${e}/${c}`}function nt(c){return[...new Set(c.filter(Boolean))]}function rt(c){return String(c??"").trim().toLowerCase()}var bt=class{constructor(e=ka,t=Aa,a={}){this.url=e,this.portPlanUrl=t,this.cacheMode=a.cache||"no-cache",this.portPlanCacheMode=a.portPlanCache||"no-cache",this.metadata=null,this.portPlan=null,this.layers=[],this.layerById=new Map,this.layerDetailCache=new Map}async load(){let e=await fetch(this.url,{cache:this.cacheMode});if(!e.ok)throw new Error(`failed to load ${this.url}: ${e.status}`);let t=await e.json();return this.portPlan=await this.loadPortPlan(),this.metadata=us(t,this.portPlan),this.layers=this.metadata.layers,this.layerById=Da(this.layers),this.metadata}async loadPortPlan(){try{let e=await fetch(this.portPlanUrl,{cache:this.portPlanCacheMode});return e.ok?e.json():null}catch{return null}}getLayer(e){return this.layerById.get(e)||null}async loadLayerDetails(e){let t=this.getLayer(e);return t?.detailUrl?(this.layerDetailCache.has(t.id)||this.layerDetailCache.set(t.id,fetch(t.detailUrl,{cache:"force-cache"}).then(a=>{if(!a.ok)throw new Error(`failed to load ${t.detailUrl}: ${a.status}`);return a.json()}).then(a=>{let i=Ra({...t,...a,detailUrl:t.detailUrl,detailLoaded:!0},this.metadata?.categories||[],t.order||0);return Object.assign(t,i),this.layerById=Da(this.layers),t}).catch(a=>{throw this.layerDetailCache.delete(t.id),a})),this.layerDetailCache.get(t.id)):t}searchLayers(e){let t=rt(e).split(/\s+/).filter(Boolean);return t.length?this.layers.filter(a=>t.every(i=>a.searchText.includes(i))):this.layers}};function Da(c){let e=new Map;for(let t of c||[])for(let a of[t.id,t.sourceMapId,t.sourceMapId?`port-${t.sourceMapId}`:null])a&&!e.has(a)&&e.set(a,t);return e}function us(c,e=null){let t=Array.isArray(e?.rows)?e.rows:[],a=c.layers||[],i=hs(c.categories||[],[...a,...t.map(ms)]),s=a.map((l,d)=>Ra({...l,conversionStatus:"converted",loadable:!0},i,d)),n=new Set(s.flatMap(l=>[l.id,l.sourceMapId]).filter(Boolean)),r=t.filter(l=>!Ha(l.conversionStatus)&&!n.has(l.sourceMapId)).map((l,d)=>ps(l,i,s.length+d)),o=[...s,...r];return{version:Number(c.version||1),schemaVersion:Number(c.schemaVersion||2),description:c.description||"",publicMapCount:Number.isFinite(c.publicMapCount)?c.publicMapCount:void 0,categories:i,capabilities:c.capabilities||{},readiness:c.readiness||{},timeSeriesChains:c.timeSeriesChains||[],electionCatalogues:c.electionCatalogues||[],portPlanSummary:e?.totals||null,layers:o}}function hs(c,e){let t=new Map;for(let a of c){let i={id:a.id||vt(a.name),name:a.name||a.id,group:a.group||"Maps",description:a.description||""};t.set(i.id,i),t.set(i.name,i)}for(let a of e){let i=a.category||"Maps";if(!t.has(i)){let s={id:vt(i),name:i,group:a.group||"Maps",description:""};t.set(s.id,s),t.set(s.name,s)}}return[...new Map([...t.values()].map(a=>[a.id,a])).values()]}function Ra(c,e,t){let a=c.category||"Maps",i=e.find(o=>o.name===a||o.id===a)||{id:vt(a),name:a,group:"Maps"},s=Array.isArray(c.references)?c.references:[],n=Array.isArray(c.sourceDownloads)?c.sourceDownloads:[],r=nt([...Array.isArray(c.keywords)?c.keywords:[],c.name,c.id,c.sourceMapId,i.name,i.group,c.provider,c.status,c.description,...Array.isArray(c.sourceCredits)?c.sourceCredits:[]]);return{...c,isConverted:Ha(c.conversionStatus)||c.loadable===!0,loadable:c.loadable!==!1&&c.sourceType!=="unconverted",category:i.name,categoryId:i.id,group:c.group||i.group||"Maps",renderer:c.renderer||"maplibre",geometryType:c.geometryType||"polygon",status:c.status||"pilot",description:c.description||c.notes||"",dateAdded:c.dateAdded||null,dateEffective:c.dateEffective||null,sourceCredits:Array.isArray(c.sourceCredits)?c.sourceCredits:Na(c.provider),references:s,sourceDownloads:n,variants:Array.isArray(c.variants)?c.variants:[],order:Number.isFinite(Number(c.order))?Number(c.order):t,searchText:rt(r.join(" ")),migration:{sourceMapId:c.sourceMapId||c.id,portedFromMainSite:!!c.sourceMapId,unsupportedReason:c.unsupportedReason||null}}}function ps(c,e,t){let a=c.category||"Uncategorised",i=e.find(l=>l.name===a||l.id===c.categoryId)||{id:c.categoryId||vt(a),name:a,group:c.group||"Maps"},s=(c.sourceDownloads||[]).filter(l=>l.url).map(l=>({label:l.label||"Source",file:l.url})),n=(c.references||[]).filter(l=>l.url).map(l=>({label:l.label||"Reference",url:l.url})),r=c.sourceFiles||[],o=nt([c.name,c.sourceMapId,c.parentId,c.category,c.group,c.provider,c.description,c.conversionStatus,c.recommendedTarget,...Array.isArray(c.sourceCredits)?c.sourceCredits:[],...(r||[]).map(l=>l.file)]);return{id:`port-${c.sourceMapId}`,sourceMapId:c.sourceMapId,parentId:c.parentId,name:c.name||c.sourceMapId,category:i.name,categoryId:i.id,group:c.group||i.group||"Maps",date:c.date,dateAdded:c.dateAdded,dateEffective:c.dateEffective,provider:c.provider,description:c.description||"",sourceCredits:Array.isArray(c.sourceCredits)?c.sourceCredits:Na(c.provider),renderer:"maplibre",sourceType:"unconverted",geometryType:"unknown",status:"not-yet-converted",conversionStatus:c.conversionStatus,recommendedTarget:c.recommendedTarget,unsupportedReason:c.unsupportedReason,bounds:c.bounds,style:c.style||{},sourceDownloads:s,references:n,sourceFiles:r,variants:[],variantCount:c.variants||0,order:t,isConverted:!1,loadable:!1,searchText:rt(o.join(" ")),migration:{sourceMapId:c.sourceMapId,portedFromMainSite:!0,unsupportedReason:c.unsupportedReason||c.conversionStatus}}}function Na(c){return Array.isArray(c)?c.map(e=>String(e)).filter(Boolean):c?[String(c)]:[]}function Ha(c){return c==="converted"||c==="convertedComposite"||c==="convertedAlias"}function ms(c){return{category:c.category||c.categoryId||"Uncategorised",group:c.group||"Maps"}}function vt(c){return rt(c).replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")||"maps"}W();var ca=mt(ft());W();var $e=mt(ft());W();W();var Se=Uint8Array,We=Uint16Array,fs=Int32Array,Oa=new Se([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),za=new Se([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),gs=new Se([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Va=function(c,e){for(var t=new We(31),a=0;a<31;++a)t[a]=e+=1<>1|(Q&21845)<<1,Ae=(Ae&52428)>>2|(Ae&13107)<<2,Ae=(Ae&61680)>>4|(Ae&3855)<<4,Wt[Q]=((Ae&65280)>>8|(Ae&255)<<8)>>1;var Ae,Q,ot=(function(c,e,t){for(var a=c.length,i=0,s=new We(e);i>o]=l}else for(r=new We(a),i=0;i>15-c[i]);return r}),lt=new Se(288);for(Q=0;Q<144;++Q)lt[Q]=8;var Q;for(Q=144;Q<256;++Q)lt[Q]=9;var Q;for(Q=256;Q<280;++Q)lt[Q]=7;var Q;for(Q=280;Q<288;++Q)lt[Q]=8;var Q,ja=new Se(32);for(Q=0;Q<32;++Q)ja[Q]=5;var Q;var vs=ot(lt,9,1);var _s=ot(ja,5,1),Gt=function(c){for(var e=c[0],t=1;te&&(e=c[t]);return e},Ce=function(c,e,t){var a=e/8|0;return(c[a]|c[a+1]<<8)>>(e&7)&t},jt=function(c,e){var t=e/8|0;return(c[t]|c[t+1]<<8|c[t+2]<<16)>>(e&7)},ws=function(c){return(c+7)/8|0},Ss=function(c,e,t){return(e==null||e<0)&&(e=0),(t==null||t>c.length)&&(t=c.length),new Se(c.subarray(e,t))};var Is=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],we=function(c,e,t){var a=new Error(e||Is[c]);if(a.code=c,Error.captureStackTrace&&Error.captureStackTrace(a,we),!t)throw a;return a},Kt=function(c,e,t,a){var i=c.length,s=a?a.length:0;if(!i||e.f&&!e.l)return t||new Se(0);var n=!t,r=n||e.i!=2,o=e.i;n&&(t=new Se(i*3));var l=function(be){var Pe=t.length;if(be>Pe){var Be=new Se(Math.max(Pe*2,be));Be.set(t),t=Be}},d=e.f||0,h=e.p||0,u=e.b||0,p=e.l,f=e.d,g=e.m,y=e.n,b=i*8;do{if(!p){d=Ce(c,h,1);var v=Ce(c,h+1,3);if(h+=3,v)if(v==1)p=vs,f=_s,g=9,y=5;else if(v==2){var C=Ce(c,h,31)+257,T=Ce(c,h+10,15)+4,z=C+Ce(c,h+5,31)+1;h+=14;for(var O=new Se(z),I=new Se(19),x=0;x>4;if(w<16)O[x++]=w;else{var N=0,V=0;for(w==16?(V=3+Ce(c,h,3),h+=2,N=O[x-1]):w==17?(V=3+Ce(c,h,7),h+=3):w==18&&(V=11+Ce(c,h,127),h+=7);V--;)O[x++]=N}}var K=O.subarray(0,C),G=O.subarray(C);g=Gt(K),y=Gt(G),p=ot(K,g,1),f=ot(G,y,1)}else we(1);else{var w=ws(h)+4,S=c[w-4]|c[w-3]<<8,E=w+S;if(E>i){o&&we(0);break}r&&l(u+S),t.set(c.subarray(w,E),u),e.b=u+=S,e.p=h=E*8,e.f=d;continue}if(h>b){o&&we(0);break}}r&&l(u+131072);for(var j=(1<>4;if(h+=N&15,h>b){o&&we(0);break}if(N||we(2),q<256)t[u++]=q;else if(q==256){D=h,p=null;break}else{var J=q-254;if(q>264){var x=q-257,ae=Oa[x];J=Ce(c,h,(1<>4;te||we(3),h+=te&15;var G=bs[ue];if(ue>3){var ae=za[ue];G+=jt(c,h)&(1<b){o&&we(0);break}r&&l(u+131072);var ye=u+J;if(u>3&1)+(e>>4&1);a>0;a-=!c[t++]);return t+(e&2)},Ts=function(c){var e=c.length;return(c[e-4]|c[e-3]<<8|c[e-2]<<16|c[e-1]<<24)>>>0};var xs=function(c,e){return((c[0]&15)!=8||c[0]>>4>7||(c[0]<<8|c[1])%31)&&we(6,"invalid zlib data"),(c[1]>>5&1)==+!e&&we(6,"invalid zlib data: "+(c[1]&32?"need":"unexpected")+" dictionary"),(c[1]>>3&4)+2};function Ms(c,e){return Kt(c,{i:2},e&&e.out,e&&e.dictionary)}function Es(c,e){var t=Cs(c);return t+8>c.length&&we(6,"invalid gzip data"),Kt(c.subarray(t,-8),{i:2},e&&e.out||new Se(Ts(c)),e&&e.dictionary)}function ks(c,e){return Kt(c.subarray(xs(c,e&&e.dictionary),-4),{i:2},e&&e.out,e&&e.dictionary)}function Wa(c,e){return c[0]==31&&c[1]==139&&c[2]==8?Es(c,e):(c[0]&15)!=8||c[0]>>4>7||(c[0]<<8|c[1])%31?Ms(c,e):ks(c,e)}var As=typeof TextDecoder<"u"&&new TextDecoder,$s=0;try{As.decode(Ls,{stream:!0}),$s=1}catch{}var Ps=Object.defineProperty,Bs=Math.pow,ee=(c,e)=>Ps(c,"name",{value:e,configurable:!0}),de=(c,e,t)=>new Promise((a,i)=>{var s=o=>{try{r(t.next(o))}catch(l){i(l)}},n=o=>{try{r(t.throw(o))}catch(l){i(l)}},r=o=>o.done?a(o.value):Promise.resolve(o.value).then(s,n);r((t=t.apply(c,e)).next())}),Cr=ee((c,e)=>{let t=!1,a="",i=L.GridLayer.extend({createTile:ee((s,n)=>{let r=document.createElement("img"),o=new AbortController,l=o.signal;return r.cancel=()=>{o.abort()},t||(c.getHeader().then(d=>{d.tileType===1||d.tileType===6?console.error("Error: archive contains vector tiles, but leafletRasterLayer is for displaying raster tiles. See https://github.com/protomaps/PMTiles/tree/main/js for details."):d.tileType===2?a="image/png":d.tileType===3?a="image/jpeg":d.tileType===4?a="image/webp":d.tileType===5&&(a="image/avif")}),t=!0),c.getZxy(s.z,s.x,s.y,l).then(d=>{if(d){let h=new Blob([d.data],{type:a}),u=window.URL.createObjectURL(h);r.src=u}else r.style.display="none";r.cancel=void 0,n(void 0,r)}).catch(d=>{if(d.name!=="AbortError")throw d}),r},"createTile"),_removeTile:ee(function(s){let n=this._tiles[s];n&&(n.el.cancel&&n.el.cancel(),n.el.src&&window.URL.revokeObjectURL(n.el.src),n.el.width=0,n.el.height=0,n.el.deleted=!0,L.DomUtil.remove(n.el),delete this._tiles[s],this.fire("tileunload",{tile:n.el,coords:this._keyToTileCoords(s)}))},"_removeTile")});return new i(e)},"leafletRasterLayer"),Fs=ee(c=>(e,t)=>{if(t instanceof AbortController)return c(e,t);let a=new AbortController;return c(e,a).then(i=>t(void 0,i.data,i.cacheControl||"",i.expires||""),i=>t(i)).catch(i=>t(i)),{cancel:ee(()=>a.abort(),"cancel")}},"v3compat"),Ka=class{constructor(e){this.tilev4=ee((t,a)=>de(this,null,function*(){if(t.type==="json"){let p=t.url.substr(10),f=this.tiles.get(p);if(f||(f=new _t(p),this.tiles.set(p,f)),this.metadata){let y=yield f.getTileJson(t.url);return a.signal.throwIfAborted(),{data:y}}let g=yield f.getHeader();return a.signal.throwIfAborted(),(g.minLon>=g.maxLon||g.minLat>=g.maxLat)&&console.error(`Bounds of PMTiles archive ${g.minLon},${g.minLat},${g.maxLon},${g.maxLat} are not valid.`),{data:{tiles:[`${t.url}/{z}/{x}/{y}`],minzoom:g.minZoom,maxzoom:g.maxZoom,bounds:[g.minLon,g.minLat,g.maxLon,g.maxLat]}}}let i=new RegExp(/pmtiles:\/\/(.+)\/(\d+)\/(\d+)\/(\d+)/),s=t.url.match(i);if(!s)throw new Error("Invalid PMTiles protocol URL");let n=s[1],r=this.tiles.get(n);r||(r=new _t(n),this.tiles.set(n,r));let o=s[2],l=s[3],d=s[4],h=yield r?.getZxy(+o,+l,+d,a.signal);if(a.signal.throwIfAborted(),h)return{data:new Uint8Array(h.data),cacheControl:h.cacheControl,expires:h.expires};let u=yield r.getHeader();if(u.tileType===1||u.tileType===6){if(this.errorOnMissingTile)throw new Error("Tile not found.");return{data:new Uint8Array}}return{data:null}}),"tilev4"),this.tile=Fs(this.tilev4),this.tiles=new Map,this.metadata=e?.metadata||!1,this.errorOnMissingTile=e?.errorOnMissingTile||!1}add(e){this.tiles.set(e.source.getKey(),e)}get(e){return this.tiles.get(e)}};ee(Ka,"Protocol");var Za=Ka;function Ya(c,e){return(e>>>0)*4294967296+(c>>>0)}ee(Ya,"toNum");function Xa(c,e){let t=e.buf,a=t[e.pos++],i=(a&112)>>4;if(a<128||(a=t[e.pos++],i|=(a&127)<<3,a<128)||(a=t[e.pos++],i|=(a&127)<<10,a<128)||(a=t[e.pos++],i|=(a&127)<<17,a<128)||(a=t[e.pos++],i|=(a&127)<<24,a<128)||(a=t[e.pos++],i|=(a&1)<<31,a<128))return Ya(c,i);throw new Error("Expected varint not more than 10 bytes")}ee(Xa,"readVarintRemainder");function Ke(c){let e=c.buf,t=e[c.pos++],a=t&127;return t<128||(t=e[c.pos++],a|=(t&127)<<7,t<128)||(t=e[c.pos++],a|=(t&127)<<14,t<128)||(t=e[c.pos++],a|=(t&127)<<21,t<128)?a:(t=e[c.pos],a|=(t&15)<<28,Xa(a,c))}ee(Ke,"readVarint");function Yt(c,e,t,a,i){return i===0?a!==0?[c-1-t,c-1-e]:[t,e]:[e,t]}ee(Yt,"rotate");function Ja(c,e,t){if(c>26)throw new Error("Tile zoom level exceeds max safe number limit (26)");if(e>=1<=1<0;r>>=1){let o=s&r,l=n&r;a+=(3*o^l)*(1<>1;if(e>26)throw new Error("Tile zoom level exceeds max safe number limit (26)");let t=((1<(c[c.Unknown=0]="Unknown",c[c.None=1]="None",c[c.Gzip=2]="Gzip",c[c.Brotli=3]="Brotli",c[c.Zstd=4]="Zstd",c))(Rs||{});function wt(c,e){return de(this,null,function*(){if(e===1||e===0)return c;if(e===2){if(typeof globalThis.DecompressionStream>"u")return Wa(new Uint8Array(c));let t=new Response(c).body;if(!t)throw new Error("Failed to read response stream");let a=t.pipeThrough(new globalThis.DecompressionStream("gzip"));return new Response(a).arrayBuffer()}throw new Error("Compression method not supported")})}ee(wt,"defaultDecompress");var Ns=(c=>(c[c.Unknown=0]="Unknown",c[c.Mvt=1]="Mvt",c[c.Png=2]="Png",c[c.Jpeg=3]="Jpeg",c[c.Webp=4]="Webp",c[c.Avif=5]="Avif",c[c.Mlt=6]="Mlt",c))(Ns||{});function ei(c){return c===1?".mvt":c===2?".png":c===3?".jpg":c===4?".webp":c===5?".avif":c===6?".mlt":""}ee(ei,"tileTypeExt");var Hs=127;function ti(c,e){let t=0,a=c.length-1;for(;t<=a;){let i=a+t>>1,s=e-c[i].tileId;if(s>0)t=i+1;else if(s<0)a=i-1;else return c[i]}return a>=0&&(c[a].runLength===0||e-c[a].tileId-1,o=/Chrome|Chromium|Edg|OPR|Brave/.test(n);this.chromeWindowsNoCache=!1,r&&o&&(this.chromeWindowsNoCache=!0)}getKey(){return this.url}setHeaders(e){this.customHeaders=e}getBytes(e,t,a,i){return de(this,null,function*(){let s,n;a?n=a:(s=new AbortController,n=s.signal);let r=new Headers(this.customHeaders);r.set("range",`bytes=${e}-${e+t-1}`);let o;this.mustReload?o="reload":this.chromeWindowsNoCache&&(o="no-store");let l=yield fetch(this.url,{signal:n,cache:o,headers:r,credentials:this.credentials});if(e===0&&l.status===416){let u=l.headers.get("Content-Range");if(!u||!u.startsWith("bytes */"))throw new Error("Missing content-length on 416 response");let p=+u.substr(8);r.set("range",`bytes=0-${p-1}`),l=yield fetch(this.url,{signal:n,cache:"reload",headers:r,credentials:this.credentials})}let d=l.headers.get("Etag");if(d!=null&&d.startsWith("W/")&&(d=null),l.status===416||i&&d&&d!==i)throw this.mustReload=!0,new Zt(`Server returned non-matching ETag ${i} after one retry. Check browser extensions and servers for issues that may affect correct ETag headers.`);if(l.status>=300)throw new Error(`Bad response code: ${l.status}`);let h=l.headers.get("Content-Length");if(l.status===200&&(!h||+h>t))throw s&&s.abort(),new Error("Server returned no content-length header or content-length exceeding request. Check that your storage backend supports HTTP Byte Serving.");return{data:yield l.arrayBuffer(),etag:d||void 0,cacheControl:l.headers.get("Cache-Control")||void 0,expires:l.headers.get("Expires")||void 0}})}};ee(ai,"FetchSource");var zs=ai;function Ie(c,e){let t=c.getUint32(e+4,!0),a=c.getUint32(e+0,!0);return t*Bs(2,32)+a}ee(Ie,"getUint64");function ii(c,e){let t=new DataView(c),a=t.getUint8(7);if(a>3)throw new Error(`Archive is spec version ${a} but this library supports up to spec version 3`);return{specVersion:a,rootDirectoryOffset:Ie(t,8),rootDirectoryLength:Ie(t,16),jsonMetadataOffset:Ie(t,24),jsonMetadataLength:Ie(t,32),leafDirectoryOffset:Ie(t,40),leafDirectoryLength:Ie(t,48),tileDataOffset:Ie(t,56),tileDataLength:Ie(t,64),numAddressedTiles:Ie(t,72),numTileEntries:Ie(t,80),numTileContents:Ie(t,88),clustered:t.getUint8(96)===1,internalCompression:t.getUint8(97),tileCompression:t.getUint8(98),tileType:t.getUint8(99),minZoom:t.getUint8(100),maxZoom:t.getUint8(101),minLon:t.getInt32(102,!0)/1e7,minLat:t.getInt32(106,!0)/1e7,maxLon:t.getInt32(110,!0)/1e7,maxLat:t.getInt32(114,!0)/1e7,centerZoom:t.getUint8(118),centerLon:t.getInt32(119,!0)/1e7,centerLat:t.getInt32(123,!0)/1e7,etag:e}}ee(ii,"bytesToHeader");function Xt(c){let e={buf:new Uint8Array(c),pos:0},t=Ke(e),a=[],i=0;for(let s=0;s0?a[s].offset=a[s-1].offset+a[s-1].length:a[s].offset=n-1}return a}ee(Xt,"deserializeIndex");var si=class extends Error{};ee(si,"EtagMismatch");var Zt=si;function Jt(c,e){return de(this,null,function*(){let t=yield c.getBytes(0,16384);if(new DataView(t.data).getUint16(0,!0)!==19792)throw new Error("Wrong magic number for PMTiles archive");let a=t.data.slice(0,Hs),i=ii(a,t.etag),s=t.data.slice(i.rootDirectoryOffset,i.rootDirectoryOffset+i.rootDirectoryLength),n=`${c.getKey()}|${i.etag||""}|${i.rootDirectoryOffset}|${i.rootDirectoryLength}`,r=Xt(yield e(s,i.internalCompression));return[i,[n,r.length,r]]})}ee(Jt,"getHeaderAndRoot");function Qt(c,e,t,a,i,s){return de(this,null,function*(){let n=yield c.getBytes(t,a,s,i.etag),r=yield e(n.data,i.internalCompression),o=Xt(r);if(o.length===0)throw new Error("Empty directory is invalid");return o})}ee(Qt,"getDirectory");var Vs=class{constructor(e=100,t=!0,a=wt){this.cache=new Map,this.maxCacheEntries=e,this.counter=1,this.decompress=a}getHeader(e){return de(this,null,function*(){let t=e.getKey(),a=this.cache.get(t);if(a)return a.lastUsed=this.counter++,a.data;let i=yield Jt(e,this.decompress);return i[1]&&this.cache.set(i[1][0],{lastUsed:this.counter++,data:i[1][2]}),this.cache.set(t,{lastUsed:this.counter++,data:i[0]}),this.prune(),i[0]})}getDirectory(e,t,a,i,s){return de(this,null,function*(){let n=`${e.getKey()}|${i.etag||""}|${t}|${a}`,r=this.cache.get(n);if(r)return r.lastUsed=this.counter++,r.data;let o=yield Qt(e,this.decompress,t,a,i,s);return this.cache.set(n,{lastUsed:this.counter++,data:o}),this.prune(),o})}prune(){if(this.cache.size>this.maxCacheEntries){let e=1/0,t;this.cache.forEach((a,i)=>{a.lastUsed{Jt(e,this.decompress).then(r=>{r[1]&&this.cache.set(r[1][0],{lastUsed:this.counter++,data:Promise.resolve(r[1][2])}),s(r[0]),this.prune()}).catch(r=>{n(r)})});return this.cache.set(t,{lastUsed:this.counter++,data:i}),i})}trackSignal(e,t,a){t.refs++,a.addEventListener("abort",()=>{--t.refs<=0&&this.pendingFetches.get(e)===t&&(t.controller.abort(),this.cache.delete(e),this.pendingFetches.delete(e))},{once:!0})}getDirectory(e,t,a,i,s){return de(this,null,function*(){let n=`${e.getKey()}|${i.etag||""}|${t}|${a}`,r=this.cache.get(n);if(r){r.lastUsed=this.counter++;let h=this.pendingFetches.get(n);return h&&this.trackSignal(n,h,s??new AbortController().signal),yield r.data}let o=new AbortController,l={controller:o,refs:0};this.trackSignal(n,l,s??new AbortController().signal),this.pendingFetches.set(n,l);let d=new Promise((h,u)=>{Qt(e,this.decompress,t,a,i,o.signal).then(p=>{this.pendingFetches.delete(n),h(p),this.prune()}).catch(p=>{u(p)})});return this.cache.set(n,{lastUsed:this.counter++,data:d}),d})}prune(){if(this.cache.size>=this.maxCacheEntries){let e=1/0,t;this.cache.forEach((a,i)=>{a.lastUsed{this.getHeader(e).then(n=>{i(),this.invalidations.delete(t)}).catch(n=>{s(n)})});this.invalidations.set(t,a)})}};ee(ni,"SharedPromiseCache");var Us=ni,ri=class{constructor(e,t,a){typeof e=="string"?this.source=new zs(e):this.source=e,a?this.decompress=a:this.decompress=wt,t?this.cache=t:this.cache=new Us}getHeader(){return de(this,null,function*(){return yield this.cache.getHeader(this.source)})}getZxyAttempt(e,t,a,i){return de(this,null,function*(){let s=Ja(e,t,a),n=yield this.cache.getHeader(this.source);if(i?.throwIfAborted(),en.maxZoom)return;let r=n.rootDirectoryOffset,o=n.rootDirectoryLength;for(let l=0;l<=3;l++){let d=yield this.cache.getDirectory(this.source,r,o,n,i);i?.throwIfAborted();let h=ti(d,s);if(h){if(h.runLength>0){let u=yield this.source.getBytes(n.tileDataOffset+h.offset,h.length,i,n.etag);return{data:yield this.decompress(u.data,n.tileCompression),cacheControl:u.cacheControl,expires:u.expires}}r=n.leafDirectoryOffset+h.offset,o=h.length}else return}throw new Error("Maximum directory depth exceeded")})}getZxy(e,t,a,i){return de(this,null,function*(){try{return yield this.getZxyAttempt(e,t,a,i)}catch(s){if(s instanceof Zt)return this.cache.invalidate(this.source),yield this.getZxyAttempt(e,t,a,i);throw s}})}getMetadataAttempt(){return de(this,null,function*(){let e=yield this.cache.getHeader(this.source),t=yield this.source.getBytes(e.jsonMetadataOffset,e.jsonMetadataLength,void 0,e.etag),a=yield this.decompress(t.data,e.internalCompression),i=new TextDecoder("utf-8");return JSON.parse(i.decode(a))})}getMetadata(){return de(this,null,function*(){try{return yield this.getMetadataAttempt()}catch(e){if(e instanceof Zt)return this.cache.invalidate(this.source),yield this.getMetadataAttempt();throw e}})}getTileJson(e){return de(this,null,function*(){let t=yield this.getHeader(),a=yield this.getMetadata(),i=ei(t.tileType);return{tilejson:"3.0.0",scheme:"xyz",tiles:[`${e}/{z}/{x}/{y}${i}`],vector_layers:a.vector_layers,attribution:a.attribution,description:a.description,name:a.name,version:a.version,bounds:[t.minLon,t.minLat,t.maxLon,t.maxLat],center:[t.centerLon,t.centerLat,t.centerZoom],minzoom:t.minZoom,maxzoom:t.maxZoom}})}};ee(ri,"PMTiles");var _t=ri;W();var li=mt(ft()),qs=` precision highp float; attribute vec3 a_off; // mercator offset from reference attribute vec3 a_color; // rgb 0..1 (or height-encoded) @@ -1198,7 +1196,7 @@ void main() { gl_Position = u_matrix * vec4(a_off, 1.0); gl_PointSize = u_size; v_color = a_color; -}`,Ns=` +}`,Gs=` precision mediump float; varying vec3 v_color; uniform float u_opacity; @@ -1206,7 +1204,7 @@ void main() { vec2 c = gl_PointCoord * 2.0 - 1.0; if (dot(c, c) > 1.0) discard; // round points gl_FragColor = vec4(v_color, u_opacity); -}`;function ti(c,e,t){let a=c.createShader(e);if(c.shaderSource(a,t),c.compileShader(a),!c.getShaderParameter(a,c.COMPILE_STATUS))throw new Error("pc shader: "+c.getShaderInfoLog(a));return a}function Hs(c){if(c=Math.max(0,Math.min(1,c)),c<.5){let t=c*2;return[.15+.1*t,.35+.55*t,.9-.5*t]}let e=(c-.5)*2;return[.25+.7*e,.9-.55*e,.4-.3*e]}function ii(c,e,t={}){let a=e.replace(/pc\.json(\?.*)?$/,"pc.bin$1");return{id:c,type:"custom",renderingMode:"3d",_pointSize:t.pointSize??2.5,_opacity:t.opacity??1,_ready:!1,_n:0,onAdd(i,s){this._map=i;let n=s.createProgram();s.attachShader(n,ti(s,s.VERTEX_SHADER,Rs)),s.attachShader(n,ti(s,s.FRAGMENT_SHADER,Ns)),s.linkProgram(n),this._prog=n,this._loc={a_off:s.getAttribLocation(n,"a_off"),a_color:s.getAttribLocation(n,"a_color"),u_matrix:s.getUniformLocation(n,"u_matrix"),u_size:s.getUniformLocation(n,"u_size"),u_opacity:s.getUniformLocation(n,"u_opacity")},this._offBuf=s.createBuffer(),this._colBuf=s.createBuffer(),this._load(s).catch(r=>console.error("[pointcloud] load failed",c,r))},async _load(i){let s=await fetch(e).then(S=>S.json()),n=await fetch(a).then(S=>S.arrayBuffer()),r=s.stride||(s.hasColor?16:12),o=Math.min(s.count,Math.floor(n.byteLength/r));o",o);let l=new DataView(n),[d,h,u]=s.center,p=ai.default.MercatorCoordinate.fromLngLat([d,h],u),f=p.meterInMercatorCoordinateUnits();this._ref=[p.x,p.y,p.z];let g=new Float32Array(o*3),y=new Float32Array(o*3),[b,v]=s.upRange||[0,1],w=v-b||1;for(let S=0;Sconsole.error("[pointcloud] load failed",c,r))},async _load(i){let s=await fetch(e).then(S=>S.json()),n=await fetch(a).then(S=>S.arrayBuffer()),r=s.stride||(s.hasColor?16:12),o=Math.min(s.count,Math.floor(n.byteLength/r));o",o);let l=new DataView(n),[d,h,u]=s.center,p=li.default.MercatorCoordinate.fromLngLat([d,h],u),f=p.meterInMercatorCoordinateUnits();this._ref=[p.x,p.y,p.z];let g=new Float32Array(o*3),y=new Float32Array(o*3),[b,v]=s.upRange||[0,1],w=v-b||1;for(let S=0;S 1.0) discard; gl_FragColor = vec4(v_color, u_opacity); -}`;function bt(c,e,t){let a=c.createShader(e);if(c.shaderSource(a,t),c.compileShader(a),!c.getShaderParameter(a,c.COMPILE_STATUS))throw new Error("pc shader: "+c.getShaderInfoLog(a));return a}function js(c){if(c=Math.max(0,Math.min(1,c)),c<.5){let t=c*2;return[.15+.1*t,.35+.55*t,.9-.5*t]}let e=(c-.5)*2;return[.25+.7*e,.9-.55*e,.4-.3*e]}function Xt(c,e,t){let a=c.createProgram();if(c.attachShader(a,bt(c,c.VERTEX_SHADER,e)),c.attachShader(a,bt(c,c.FRAGMENT_SHADER,t)),c.linkProgram(a),!c.getProgramParameter(a,c.LINK_STATUS))throw new Error("pc link: "+c.getProgramInfoLog(a));return a}var ea=` +}`;function St(c,e,t){let a=c.createShader(e);if(c.shaderSource(a,t),c.compileShader(a),!c.getShaderParameter(a,c.COMPILE_STATUS))throw new Error("pc shader: "+c.getShaderInfoLog(a));return a}function Qs(c){if(c=Math.max(0,Math.min(1,c)),c<.5){let t=c*2;return[.15+.1*t,.35+.55*t,.9-.5*t]}let e=(c-.5)*2;return[.25+.7*e,.9-.55*e,.4-.3*e]}function aa(c,e,t){let a=c.createProgram();if(c.attachShader(a,St(c,c.VERTEX_SHADER,e)),c.attachShader(a,St(c,c.FRAGMENT_SHADER,t)),c.linkProgram(a),!c.getProgramParameter(a,c.LINK_STATUS))throw new Error("pc link: "+c.getProgramInfoLog(a));return a}var na=` vec4 packF(float v){ v=clamp(v,0.0,1.0); vec4 e=fract(v*vec4(1.0,255.0,65025.0,16581375.0)); e-=e.yzww*vec4(1.0/255.0,1.0/255.0,1.0/255.0,0.0); return e; } -float unpackF(vec4 c){ return dot(c, vec4(1.0,1.0/255.0,1.0/65025.0,1.0/16581375.0)); }`,ni=`#version 300 es +float unpackF(vec4 c){ return dot(c, vec4(1.0,1.0/255.0,1.0/65025.0,1.0/16581375.0)); }`,ui=`#version 300 es precision highp float; out vec2 v_uv; -void main(){ vec2 p=vec2(float((gl_VertexID<<1)&2), float(gl_VertexID&2)); v_uv=p; gl_Position=vec4(p*2.0-1.0,0.0,1.0); }`,Ws=`#version 300 es +void main(){ vec2 p=vec2(float((gl_VertexID<<1)&2), float(gl_VertexID&2)); v_uv=p; gl_Position=vec4(p*2.0-1.0,0.0,1.0); }`,en=`#version 300 es precision highp float; in vec3 a_pos; in vec3 a_color; uniform mat4 u_matrix; uniform float u_size; out vec3 v_color; out float v_w; -void main(){ gl_Position=u_matrix*vec4(a_pos,1.0); gl_PointSize=u_size; v_color=a_color; v_w=gl_Position.w; }`,Ks=`#version 300 es +void main(){ gl_Position=u_matrix*vec4(a_pos,1.0); gl_PointSize=u_size; v_color=a_color; v_w=gl_Position.w; }`,tn=`#version 300 es precision highp float; in vec3 v_color; in float v_w; uniform float u_k; layout(location=0) out vec4 o_color; layout(location=1) out vec4 o_depth; -${ea} +${na} void main(){ vec2 c=gl_PointCoord*2.0-1.0; if(dot(c,c)>1.0) discard; - o_color=vec4(v_color,1.0); o_depth=packF(1.0-1.0/(1.0+v_w*u_k)); }`,Zs=`#version 300 es + o_color=vec4(v_color,1.0); o_depth=packF(1.0-1.0/(1.0+v_w*u_k)); }`,an=`#version 300 es precision highp float; in vec2 v_uv; uniform sampler2D u_color; uniform sampler2D u_depth; uniform vec2 u_texel; uniform float u_radius; uniform float u_depthThresh; layout(location=0) out vec4 o_color; layout(location=1) out vec4 o_depth; -${ea} +${na} void main(){ vec4 c=texture(u_color, v_uv); if(c.a>0.5){ o_color=c; o_depth=texture(u_depth, v_uv); return; } // already covered @@ -1265,7 +1263,7 @@ void main(){ if(abs(nd-nearest)=2 to avoid speckle o_color=vec4(sum/cnt, 1.0); o_depth=packF(dsum/cnt); -}`,Ys=`#version 300 es +}`,sn=`#version 300 es precision highp float; in vec2 v_uv; uniform sampler2D u_color; uniform sampler2D u_depth; @@ -1273,7 +1271,7 @@ uniform vec2 u_texel; uniform float u_opacity; uniform float u_edlStrength; uniform float u_edlRadius; uniform float u_normalStr; uniform vec3 u_lightDir; uniform float u_ambient; uniform float u_diffuse; out vec4 frag; -${ea} +${na} void main(){ vec4 col=texture(u_color, v_uv); if(col.a<0.5) discard; // still empty -> keep map @@ -1290,7 +1288,7 @@ void main(){ if(texture(u_color, v_uv+o).a>0.5){ float zn=unpackF(texture(u_depth, v_uv+o)); sum+=max(0.0, zc-zn); cnt+=1.0; } } float edl=exp(-u_edlStrength*(cnt>0.0?sum/cnt:0.0)); frag=vec4(col.rgb*lit*edl, u_opacity); -}`;function Xs(c,e){return/^https?:/i.test(e)?e:c.replace(/[^/]*$/,"")+e}function Jt(c,e,t,a){let i=c.transform?oi(e,c.transform):e,s=c.boundingVolume.box,n=[s[0],s[1],s[2]],r=[s[3],s[4],s[5]],o=[s[6],s[7],s[8]],l=[s[9],s[10],s[11]],d=Yt(i,n[0],n[1],n[2]),h=Zt(d[0],d[1],d[2]),u=[];for(let M of[[1,0,0],[0,1,0],[0,0,1]]){let C=Yt(i,n[0]+M[0],n[1]+M[1],n[2]+M[2]),T=Zt(C[0],C[1],C[2]);u.push([T[0]-h[0],T[1]-h[1],T[2]-h[2]])}let p=[-(u[0][0]*n[0]+u[1][0]*n[1]+u[2][0]*n[2]),-(u[0][1]*n[0]+u[1][1]*n[1]+u[2][1]*n[2]),-(u[0][2]*n[0]+u[1][2]*n[1]+u[2][2]*n[2])],f=[u[0][0],u[0][1],u[0][2],0,u[1][0],u[1][1],u[1][2],0,u[2][0],u[2][1],u[2][2],0,p[0],p[1],p[2],1],g=[];for(let M=-1;M<=1;M+=2)for(let C=-1;C<=1;C+=2)for(let T=-1;T<=1;T+=2){let V=n[0]+M*r[0]+C*o[0]+T*l[0],z=n[1]+M*r[1]+C*o[1]+T*l[1],I=n[2]+M*r[2]+C*o[2]+T*l[2],x=Yt(i,V,z,I);g.push(Zt(x[0],x[1],x[2]))}let y=c.content||c.contents?.[0],b=y&&(y.uri||y.url),v=b?Xs(t,b):null,w=!!v&&/\.pnts(\?|$)/i.test(v),S=!!v&&/\.json(\?|$)/i.test(v);return{world:i,box:s,ref:h,affine:f,corners:g,geometricError:c.geometricError??0,refine:(c.refine||a||"REPLACE").toUpperCase(),baseUrl:t,contentUri:w?v:null,externalUri:S?v:null,rawChildren:c.children||null,children:null,resolving:!1,state:"unloaded",buf:null,colBuf:null,count:0,lastFrame:0}}function li(c,e,t={}){return{id:c,type:"custom",renderingMode:"3d",_pointSize:t.pointSize??1.6,_opacity:t.opacity??1,_errK:t.errorFactor??1.5,_maxPoints:t.maxPoints??22e6,_maxConcurrent:24,_evictGrace:300,_mzMin:0,_mzMax:1,_root:null,_frame:0,_loadedPoints:0,_inflight:0,_queue:[],_loadedNodes:new Set,_visitBudget:0,_resolving:0,_maxResolving:24,_maxVisitsPerFrame:4e4,_edlEnabled:t.edl??!0,_edlStrength:t.edlStrength??2e3,_edlRadius:t.edlRadius??3,_edlK:t.edlK??.001,_fillIters:t.fillIters??8,_fillRadius:t.fillRadius??1.5,_fillDepthThresh:t.fillDepthThresh??.03,_fillMinZoom:t.fillMinZoom??16.5,_normalStr:t.normalStr??6,_ambient:t.ambient??.6,_diffuse:t.diffuse??.5,_lightDir:t.lightDir??[-.4,.6,.8],_superScale:t.superScale??1,_edl:null,onAdd(a,i){this._map=a;let s=i.createProgram();if(i.attachShader(s,bt(i,i.VERTEX_SHADER,qs)),i.attachShader(s,bt(i,i.FRAGMENT_SHADER,Gs)),i.linkProgram(s),!i.getProgramParameter(s,i.LINK_STATUS))throw new Error("pc link: "+i.getProgramInfoLog(s));if(this._prog=s,this._loc={a_pos:i.getAttribLocation(s,"a_pos"),a_color:i.getAttribLocation(s,"a_color"),u_matrix:i.getUniformLocation(s,"u_matrix"),u_size:i.getUniformLocation(s,"u_size"),u_opacity:i.getUniformLocation(s,"u_opacity")},typeof a.setMaxPitch=="function"&&a.getMaxPitch()<80&&a.setMaxPitch(85),this._edlEnabled)try{this._initEDL(i)}catch(n){this._edl=null,console.warn("[pc-stream] EDL unavailable, using direct render",n)}fetch(e).then(n=>n.json()).then(n=>{let r=e.split("?")[0];this._root=Jt(n.root,Us,r,"REPLACE");let o=1/0,l=-1/0;for(let d of this._root.corners)d[2]l&&(l=d[2]);l>o&&(this._mzMin=o,this._mzMax=l),this._map?.triggerRepaint()}).catch(n=>console.error("[pc-stream] tileset load failed",c,n))},_resolveChildren(a){if(a.children||a.resolving||a.externalUri&&this._resolving>=this._maxResolving)return;a.resolving=!0,a.externalUri&&this._resolving++;let i=s=>{let n=[];if(s&&n.push(Jt(s,a.world,a._extBase||a.baseUrl,a.refine)),a.rawChildren)for(let r of a.rawChildren)n.push(Jt(r,a.world,a.baseUrl,a.refine));a.children=n,a.resolving=!1,this._map?.triggerRepaint()};a.externalUri?fetch(a.externalUri).then(s=>s.json()).then(s=>{a._extBase=a.externalUri.split("?")[0],i(s.root)}).catch(s=>{a.children=[],a.resolving=!1}).finally(()=>{this._resolving--}):i(null)},_enqueue(a){a.state==="unloaded"&&(a.state="queued",this._queue.push(a))},_pump(a){if(!this._queue.length)return;this._queue.sort((s,n)=>n.lastFrame-s.lastFrame||n.geometricError-s.geometricError);let i=this._frame-120;for(;this._inflightn.arrayBuffer()).then(n=>{this._upload(a,s,n)}).catch(()=>{s.state="unloaded"}).finally(()=>{this._inflight--,this._map?.triggerRepaint()})}}},_upload(a,i,s){let r=new DataView(s).getUint32(12,!0),o=JSON.parse(new TextDecoder().decode(new Uint8Array(s,28,r))),l=o.POINTS_LENGTH|0,d=28+r,h=d+(o.POSITION?.byteOffset??0),u=new Float32Array(s.slice(h,h+l*12)),p=new Float32Array(l*3),f=!1;if(o.RGB){let g=d+o.RGB.byteOffset,y=new Uint8Array(s,g,l*3),b=0;for(let v=0;vb&&(b=y[v],b>=8));v++);if(b>=8){f=!0;for(let v=0;vthis._maxPoints*2?this._frame:this._frame-this._evictGrace,n=[...this._loadedNodes].filter(r=>r.lastFramer.lastFrame-o.lastFrame);for(let r of n){if(this._loadedPoints<=this._maxPoints*.85)break;a.deleteBuffer(r.buf),a.deleteBuffer(r.colBuf),this._loadedPoints-=r.count,r.buf=r.colBuf=null,r.count=0,r.state="unloaded",this._loadedNodes.delete(r)}},_culled(a,i){let s=0,n=0,r=0,o=0,l=0;for(let h of a.corners){let u=i[0]*h[0]+i[4]*h[1]+i[8]*h[2]+i[12],p=i[1]*h[0]+i[5]*h[1]+i[9]*h[2]+i[13],f=i[3]*h[0]+i[7]*h[1]+i[11]*h[2]+i[15];if(f<=0){l++;continue}let g=u/f,y=p/f;g<-1&&s++,g>1&&n++,y<-1&&r++,y>1&&o++}let d=a.corners.length;return s===d||n===d||r===d||o===d||l===d},_selectVisit(a,i,s,n,r){if(this._visitBudget--<=0){i.contentUri&&i.state==="loaded"&&r.push(i);return}if(i.lastFrame=this._frame,!(i.geometricError>n)){if(i.contentUri)i.state==="loaded"?r.push(i):this._enqueue(i);else if(i.children||i.externalUri||i.rawChildren)if(!i.children)this._resolveChildren(i);else for(let d of i.children)this._culled(d,s)||this._selectVisit(a,d,s,n,r);return}if(!i.children){this._resolveChildren(i),i.contentUri&&(i.state==="loaded"?r.push(i):this._enqueue(i));return}let l=!1;for(let d of i.children){if(this._culled(d,s))continue;let h=r.length;this._selectVisit(a,d,s,n,r),r.length===h&&(d.contentUri||d.externalUri||d.rawChildren)&&(l=!0)}(i.refine==="ADD"||l)&&i.contentUri&&(i.state==="loaded"?r.push(i):this._enqueue(i))},render(a,i){if(!this._root||!this._prog)return;let s=Array.isArray(i)?i:i?.defaultProjectionData?.mainMatrix||i?.mainMatrix||i;if(!s||s.length!==16)return;this._frame++;let n=this._map.getCenter().lat,r=this._map.getZoom(),l=ri*Math.cos(n*nt)/(512*Math.pow(2,r))*this._errK,d=[];if(this._visitBudget=this._maxVisitsPerFrame,this._culled(this._root,s)||this._selectVisit(a,this._root,s,l,d),this._pump(a),this._evict(a),this._edl&&d.length)try{this._renderEDL(a,s,d)}catch(h){console.warn("[pc-stream] EDL render failed, falling back to direct",h),this._edl=null,this._renderDirect(a,s,d)}else this._renderDirect(a,s,d);(this._queue.length||this._inflight)&&this._map?.triggerRepaint()},_nodeMatrix(a,i){let s=i.ref[0],n=i.ref[1],r=i.ref[2],o=a.slice();return o[12]=a[0]*s+a[4]*n+a[8]*r+a[12],o[13]=a[1]*s+a[5]*n+a[9]*r+a[13],o[14]=a[2]*s+a[6]*n+a[10]*r+a[14],o[15]=a[3]*s+a[7]*n+a[11]*r+a[15],new Float32Array(oi(o,i.affine))},_renderDirect(a,i,s){a.useProgram(this._prog),a.uniform1f(this._loc.u_size,this._pointSize*(window.devicePixelRatio||1)),a.uniform1f(this._loc.u_opacity,this._opacity||1),a.enable(a.DEPTH_TEST),a.depthFunc(a.LEQUAL);for(let n of s)a.uniformMatrix4fv(this._loc.u_matrix,!1,this._nodeMatrix(i,n)),a.bindBuffer(a.ARRAY_BUFFER,n.buf),a.enableVertexAttribArray(this._loc.a_pos),a.vertexAttribPointer(this._loc.a_pos,3,a.FLOAT,!1,0,0),a.bindBuffer(a.ARRAY_BUFFER,n.colBuf),a.enableVertexAttribArray(this._loc.a_color),a.vertexAttribPointer(this._loc.a_color,3,a.FLOAT,!1,0,0),a.drawArrays(a.POINTS,0,n.count)},_initEDL(a){if(!(typeof WebGL2RenderingContext<"u"&&a instanceof WebGL2RenderingContext)){this._edl=null;return}let s=Xt(a,Ws,Ks),n=Xt(a,ni,Zs),r=Xt(a,ni,Ys),o=(d,...h)=>{let u={};for(let p of h)u[p]=a.getUniformLocation(d,p);return u},l=d=>({fbo:a.createFramebuffer(),col:a.createTexture(),dep:a.createTexture(),rb:d?a.createRenderbuffer():null});this._edl={gbufProg:s,fillProg:n,shadeProg:r,gLoc:{a_pos:a.getAttribLocation(s,"a_pos"),a_color:a.getAttribLocation(s,"a_color"),...o(s,"u_matrix","u_size","u_k")},fLoc:o(n,"u_color","u_depth","u_texel","u_radius","u_depthThresh"),sLoc:o(r,"u_color","u_depth","u_texel","u_opacity","u_edlStrength","u_edlRadius","u_normalStr","u_lightDir","u_ambient","u_diffuse"),gbuf:l(!0),pp0:l(!1),pp1:l(!1),vao:a.createVertexArray(),w:0,h:0}},_sizeTarget(a,i,s,n,r){for(let o of[i.col,i.dep])a.bindTexture(a.TEXTURE_2D,o),a.texImage2D(a.TEXTURE_2D,0,a.RGBA8,s,n,0,a.RGBA,a.UNSIGNED_BYTE,null),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MIN_FILTER,a.NEAREST),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MAG_FILTER,a.NEAREST),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_WRAP_S,a.CLAMP_TO_EDGE),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_WRAP_T,a.CLAMP_TO_EDGE);a.bindFramebuffer(a.FRAMEBUFFER,i.fbo),a.framebufferTexture2D(a.FRAMEBUFFER,a.COLOR_ATTACHMENT0,a.TEXTURE_2D,i.col,0),a.framebufferTexture2D(a.FRAMEBUFFER,a.COLOR_ATTACHMENT1,a.TEXTURE_2D,i.dep,0),r&&(a.bindRenderbuffer(a.RENDERBUFFER,i.rb),a.renderbufferStorage(a.RENDERBUFFER,a.DEPTH_COMPONENT16,s,n),a.framebufferRenderbuffer(a.FRAMEBUFFER,a.DEPTH_ATTACHMENT,a.RENDERBUFFER,i.rb))},_ensureEdlSize(a,i,s){let n=this._edl;n.w===i&&n.h===s||(n.w=i,n.h=s,this._sizeTarget(a,n.gbuf,i,s,!0),this._sizeTarget(a,n.pp0,i,s,!1),this._sizeTarget(a,n.pp1,i,s,!1),a.bindFramebuffer(a.FRAMEBUFFER,null),a.bindTexture(a.TEXTURE_2D,null),a.bindRenderbuffer(a.RENDERBUFFER,null))},_renderEDL(a,i,s){let n=this._edl,r=Math.max(1,this._superScale),o=Math.round(a.drawingBufferWidth*r),l=Math.round(a.drawingBufferHeight*r);this._ensureEdlSize(a,o,l);let d=[a.COLOR_ATTACHMENT0,a.COLOR_ATTACHMENT1],h=window.devicePixelRatio||1,u={fbo:a.getParameter(a.FRAMEBUFFER_BINDING),vp:a.getParameter(a.VIEWPORT),vao:a.getParameter(a.VERTEX_ARRAY_BINDING),prog:a.getParameter(a.CURRENT_PROGRAM),arr:a.getParameter(a.ARRAY_BUFFER_BINDING),actTex:a.getParameter(a.ACTIVE_TEXTURE),blend:a.isEnabled(a.BLEND),bsrc:a.getParameter(a.BLEND_SRC_RGB),bdst:a.getParameter(a.BLEND_DST_RGB),dtest:a.isEnabled(a.DEPTH_TEST),dmask:a.getParameter(a.DEPTH_WRITEMASK),dfunc:a.getParameter(a.DEPTH_FUNC)};a.bindVertexArray(n.vao),a.bindFramebuffer(a.FRAMEBUFFER,n.gbuf.fbo),a.drawBuffers(d),a.viewport(0,0,o,l),a.disable(a.BLEND),a.enable(a.DEPTH_TEST),a.depthMask(!0),a.depthFunc(a.LEQUAL),a.clearColor(0,0,0,0),a.clear(a.COLOR_BUFFER_BIT|a.DEPTH_BUFFER_BIT),a.useProgram(n.gbufProg),a.uniform1f(n.gLoc.u_size,this._pointSize*h*r),a.uniform1f(n.gLoc.u_k,this._edlK);for(let b of s)a.uniformMatrix4fv(n.gLoc.u_matrix,!1,this._nodeMatrix(i,b)),a.bindBuffer(a.ARRAY_BUFFER,b.buf),a.enableVertexAttribArray(n.gLoc.a_pos),a.vertexAttribPointer(n.gLoc.a_pos,3,a.FLOAT,!1,0,0),a.bindBuffer(a.ARRAY_BUFFER,b.colBuf),a.enableVertexAttribArray(n.gLoc.a_color),a.vertexAttribPointer(n.gLoc.a_color,3,a.FLOAT,!1,0,0),a.drawArrays(a.POINTS,0,b.count);a.disable(a.DEPTH_TEST),a.depthMask(!1),a.disable(a.BLEND);let p=this._map.getZoom(),f=p>=this._fillMinZoom?Math.max(2,Math.min(this._fillIters,Math.round(2+(p-this._fillMinZoom)*1.5))):0,g=n.gbuf.col,y=n.gbuf.dep;for(let b=0;b["get",t]),""])}function pi(c){let e=aa(c),t=e.length>0?["any",...e.map(i=>["has",i])]:!0,a=ga(c);return a?["any",t,a]:t}function _t(c,e){let t=rt(c),a=ne(e,50,200)/100;return t.fontSize*a}function mi(c){return["*",-1,["to-number",["get",c.labelRankProperty||"label_rank"],0]]}function wt(c,e){let t=ze(c,e||{});for(let a of aa(c)){let i=Js(t?.[a],c.labelCleanup);if(i)return i}return""}function Js(c,e){if(c==null)return"";let t=String(c).trim();if(!t)return"";if(e==="stripTrailingBracketNumber")return t.replace(/\s*\([^()]*\)\s*$/,"").trim();if(e&&typeof e=="object"&&e.type==="mapValues"){let a=e.map?.[t];if(typeof a=="string"&&a.trim())return a.trim()}return t}var We="#FDBA74",Ke="#FF7A1A",Qs=0,en=60,tn=10,an=new Set(["pmtiles","vector","mvt"]);var sn=["button","a","input","select","textarea",'[contenteditable="true"]',".maplibregl-ctrl",".test2-main-zoom-control",".active-layers-toggle",".map-controls",".map-control-panel",".active-layers",".feature-info",".test2-source-panel",".test2-election-pane-resizer","#timelineSlider"].join(","),St=Object.freeze({type:"FeatureCollection",features:[]});function Re(c){return!!c?.closest?.(sn)}function fi(c){if(!c?.touches||c.touches.length<2)return null;let e=c.touches[0],t=c.touches[1];return!e||!t?null:[{x:e.clientX,y:e.clientY},{x:t.clientX,y:t.clientY}]}function gi(c){return{x:(c[0].x+c[1].x)/2,y:(c[0].y+c[1].y)/2}}function yi(c){return Math.hypot(c[1].x-c[0].x,c[1].y-c[0].y)}function bi(c){return Math.atan2(c[1].y-c[0].y,c[1].x-c[0].x)}function nn(c){return c*180/Math.PI}function vi(c){let e=c;for(;e>180;)e-=360;for(;e<-180;)e+=360;return e}function rn(c){return typeof c=="string"&&c.startsWith("/render/tiles/")}function on(){let c=globalThis.location?.hostname||"";return globalThis.__civgraphUseLocalTileFallback===!0&&(c==="localhost"||c==="127.0.0.1"||c==="::1")}function ln(c){let e=Number(c?.maxDomLabels);if(Number.isFinite(e)&&e>0)return e;let t=Number(globalThis.innerWidth||1024),a=Number(globalThis.navigator?.deviceMemory||4);return t<700||a<=2?90:t<1100||a<=4?180:320}function cn(){let c=Number(globalThis.innerWidth||1024),e=Number(globalThis.navigator?.deviceMemory||4),t=Number(globalThis.navigator?.hardwareConcurrency||4),a=Number(globalThis.devicePixelRatio||1),i=!!globalThis.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches,s=c<700||e<=2||t<=2,n=!s&&(c<1100||e<=4||t<=4),r=s?1:Math.max(1,Math.min(3,t-1));return{deviceClass:s?"low":n?"medium":"high",workerCount:r,maxTileCacheSize:s?80:n?140:260,maxParallelImageRequests:s?8:n?12:16,fadeDuration:s||i?0:100,pixelRatio:s?Math.min(a,1.5):Math.min(a,2),reducedMotion:i}}function Ci(c){return ne(c?.style?.fillOpacity??Qs,0,1)}function _i(c){return c?.sourceType==="raster"||c?.sourceType==="image"?ne(c.rasterOpacity??c.style?.opacity??.85,0,1):Ci(c)}var It=class{constructor(e,t={}){this.container=e,this.options=t,this.map=null,this.maplibreVersion=Ee.default.version,this.protocol=new Ua({metadata:!0}),this.layers=new Map,this.selected=null,this.hovered=null,this.metrics=[],this.fallbackLayers=new Map,this.interactionCleanups=new Map,this.fallbackCleanups=new Map,this.duplicateFeatureIdCache=new Map,this.pmtilesArchiveCache=new Map,this.runtimeProfile=cn(),this.mobileGestureGuardInstalled=!1,this.mobileGestureGuardTargetCount=0,this.mobileGestureResizeObserver=null,this.mobileGestureResizeFrame=0,this.mobileGestureResizeSize=null,this.mobileGestureResizeObserverEligible=!1,this.directGestureActive=!1,this.directPanGestureInstalled=!1,this.directPanGestureState=null,this.directPanFrame=0,this.directPanPendingCenter=null,this.directPanPendingDelta=null,this.directPanFallbackActivations=0,this.directWheelGestureInstalled=!1,this.directWheelFrame=0,this.directWheelPendingZoom=null,this.directWheelEndTimer=0,this.directWheelFallbackActive=!1,this.directWheelFallbackActivations=0,this.directTwoFingerGestureInstalled=!1,this.directTwoFingerGestureState=null,this.directTwoFingerGestureFrame=0,this.directTwoFingerGesturePending=null,this.directTwoFingerFallbackActivations=0,this.mapCursor="",this.cursorMutationCount=0,this.documentHoverClearInstalled=!1,this.documentHoverClearHandler=null,Ee.default.addProtocol("pmtiles",this.protocol.tile)}init(){Number.isFinite(this.runtimeProfile.workerCount)&&(Ee.default.workerCount=this.runtimeProfile.workerCount),Number.isFinite(this.runtimeProfile.maxParallelImageRequests)&&(Ee.default.maxParallelImageRequests=this.runtimeProfile.maxParallelImageRequests),this.map=new Ee.default.Map({container:this.container,style:{version:8,sources:{osm:{type:"raster",tiles:["https://tile.openstreetmap.org/{z}/{x}/{y}.png"],tileSize:256,attribution:"© OpenStreetMap contributors"}},layers:[{id:"osm",type:"raster",source:"osm"}]},center:[-8.05,53.4],zoom:5.8,minZoom:4,maxZoom:22,attributionControl:!0,fadeDuration:this.runtimeProfile.fadeDuration,maxTileCacheSize:this.runtimeProfile.maxTileCacheSize,pixelRatio:this.runtimeProfile.pixelRatio,refreshExpiredTiles:!1,renderWorldCopies:!1,interactive:!0,dragRotate:!0,dragPan:!0,touchZoomRotate:!0,touchPitch:!0,pitchWithRotate:!0,scrollZoom:!0,cooperativeGestures:!1}),this.recordMetric({event:"runtime-profile",profile:this.runtimeProfile}),this.map.doubleClickZoom?.disable(),this.enableGestureHandlers(),this.installMobileGestureGuards(),this.installDirectPanGestureFallback(),this.installDirectWheelGestureFallback(),this.installDirectTwoFingerGestureFallback(),this.installDocumentHoverClear(),this.applyMobileTouchContract(),this.map.on("load",()=>{this.enableGestureHandlers(),this.applyMobileTouchContract()}),this.map.on("styledata",()=>{this.enableGestureHandlers(),this.applyMobileTouchContract()}),this.map.addControl(new Ee.default.NavigationControl({visualizePitch:!0}),"top-left"),this.map.addControl(new Ee.default.ScaleControl({unit:"metric"}),"bottom-right"),this.map.on("moveend",()=>{this.directGestureActive||this.notifyChange()}),this.map.on("idle",()=>{this.directGestureActive||this.notifyChange()}),this.map.fitBounds(Ta,{padding:28,duration:0})}installDocumentHoverClear(){this.documentHoverClearInstalled||(this.documentHoverClearInstalled=!0,this.documentHoverClearHandler=e=>{if(!this.hovered||!this.map)return;let t=e.target,a=this.map.getContainer?.();if(!a)return;let i=a.contains(t),s=i&&!t?.closest?.([".maplibre-dom-label",".test2-election-seat-group",".maplibregl-canvas",".maplibregl-canvas-container"].join(","));i&&!Re(t)&&!s||this.clearHover()},document.addEventListener("pointerdown",this.documentHoverClearHandler,!0))}readCameraState(){if(!this.map)return null;let e=this.map.getCenter();return{lng:e.lng,lat:e.lat,zoom:this.map.getZoom(),pitch:this.map.getPitch(),bearing:this.map.getBearing()}}cameraMovedSince(e,t={}){if(!e||!this.map)return!1;let a=this.readCameraState();if(!a)return!1;let i=t.lng??1e-6,s=t.lat??1e-6,n=t.zoom??5e-4,r=t.pitch??.05,o=t.bearing??.05;return Math.abs(a.lng-e.lng)>i||Math.abs(a.lat-e.lat)>s||Math.abs(a.zoom-e.zoom)>n||Math.abs(a.pitch-e.pitch)>r||Math.abs(vi(a.bearing-e.bearing))>o}resetDirectPanGestureState(e=null,t=null){this.directPanFrame&&(cancelAnimationFrame(this.directPanFrame),this.directPanFrame=0),this.directPanPendingCenter=null,this.directPanPendingDelta=null;let a=this.directPanGestureState;if(a){a.nativeCheckFrame&&(cancelAnimationFrame(a.nativeCheckFrame),a.nativeCheckFrame=0);let i=e||a.target||this.map?.getContainer?.(),s=t??a.pointerId;try{i?.hasPointerCapture?.(s)&&i.releasePointerCapture(s)}catch{}}this.directPanGestureState=null}enableGestureHandlers(){this.map&&(this.map.dragPan?.enable?.(),this.map.dragRotate?.enable?.(),this.map.touchZoomRotate?.enable?.(),this.map.touchZoomRotate?.enableRotation?.(),this.map.touchPitch?.enable?.(),this.map.scrollZoom?.enable?.(),this.map.keyboard?.enable?.(),this.applyMobileTouchContract())}setMapCursor(e=""){let t=e||"",a=this.map?.getCanvas?.();this.mapCursor===t&&(!a||a.style.cursor===t)||(this.mapCursor=t,a&&a.style.cursor!==t&&(a.style.cursor=t,this.cursorMutationCount+=1))}installMobileGestureGuards(){if(!this.map||this.mobileGestureGuardInstalled)return;let e=this.map.getContainer?.();if(!e?.addEventListener)return;this.mobileGestureGuardInstalled=!0;let t=r=>{Re(r.target)||r.cancelable&&r.preventDefault()},a=r=>{Re(r.target)||this.applyMobileTouchContract()},i=new Set([e,this.map.getCanvasContainer?.()].filter(Boolean)),s={passive:!1},n={passive:!0};for(let r of i)r.addEventListener("touchstart",a,n),r.addEventListener("gesturestart",t,s),r.addEventListener("gesturechange",t,s),r.addEventListener("gestureend",t,s);this.mobileGestureGuardTargetCount=i.size,this.installMobileGestureResizeObserver(e)}installDirectPanGestureFallback(){if(!this.map||this.directPanGestureInstalled)return;let e=this.map.getContainer?.();if(!e?.addEventListener)return;this.directPanGestureInstalled=!0;let t={touch:{distance:24,elapsedMs:120,samples:3},mouse:{distance:14,elapsedMs:48,samples:2},pen:{distance:18,elapsedMs:80,samples:2},default:{distance:18,elapsedMs:80,samples:2}},a={passive:!1},i=()=>{this.directPanFrame=0;let u=this.directPanPendingDelta;this.directPanPendingDelta=null;let p=this.directPanPendingCenter;if(this.directPanPendingCenter=null,!!this.map){if(u){let f=this.map.project(this.map.getCenter()),g=this.map.unproject([f.x-u.dx,f.y-u.dy]);this.map.jumpTo({center:g});return}p&&this.map.jumpTo({center:p})}},s=(u,p)=>{if(!Number.isFinite(u)||!Number.isFinite(p)||u===0&&p===0)return;let f=this.directPanPendingDelta||{dx:0,dy:0};f.dx+=u,f.dy+=p,this.directPanPendingDelta=f,this.directPanPendingCenter=null,!this.directPanFrame&&(this.directPanFrame=requestAnimationFrame(i))},n=()=>{this.directPanFrame&&(cancelAnimationFrame(this.directPanFrame),this.directPanFrame=0),i()},r=u=>{let p=t[u.pointerType]||t.default,f=performance.now()-u.startedAt;return Math.hypot(u.latestDx,u.latestDy)>=p.distance&&u.noCameraSamples>=p.samples&&f>=p.elapsedMs},o=u=>{u.nativeCheckFrame||u.fallbackActive||u.nativeMoved||(u.nativeCheckFrame=requestAnimationFrame(()=>{if(u.nativeCheckFrame=0,!(this.directPanGestureState!==u||u.cancelled||u.fallbackActive||u.nativeMoved)){if(this.cameraMovedSince(u.camera,{lng:5e-6,lat:5e-6})){u.nativeMoved=!0;return}r(u)&&(u.fallbackActive=!0,u.moved=!0,this.directPanFallbackActivations+=1,this.directGestureActive=!0,s(u.latestDx,u.latestDy),u.lastX=u.latestX,u.lastY=u.latestY)}}))},l=u=>{if(Re(u.target)||u.button!==void 0&&u.button!==0)return;if(this.directPanGestureState&&u.pointerType==="touch"){this.directPanGestureState.cancelled=!0;return}if(this.directPanGestureState||u.isPrimary===!1)return;let p=this.map.getCenter();this.directPanGestureState={pointerId:u.pointerId,pointerType:u.pointerType||"mouse",startX:u.clientX,startY:u.clientY,lastX:u.clientX,lastY:u.clientY,latestX:u.clientX,latestY:u.clientY,center:p,camera:this.readCameraState(),startedAt:performance.now(),latestDx:0,latestDy:0,noCameraSamples:0,moved:!1,fallbackActive:!1,nativeMoved:!1,nativeCheckFrame:0,cancelled:!1,captured:!1,target:u.currentTarget||e}},d=u=>{let p=this.directPanGestureState;if(!p||p.cancelled||u.pointerId!==p.pointerId)return;let f=u.clientX-p.startX,g=u.clientY-p.startY;if(p.latestX=u.clientX,p.latestY=u.clientY,p.latestDx=f,p.latestDy=g,!p.fallbackActive&&this.cameraMovedSince(p.camera,{lng:5e-6,lat:5e-6})){p.nativeMoved=!0;return}if(!p.fallbackActive){let v=t[p.pointerType]||t.default;if(Math.hypot(f,g){let p=this.directPanGestureState;!p||u?.pointerId!==void 0&&u.pointerId!==p.pointerId||(p.nativeCheckFrame&&(cancelAnimationFrame(p.nativeCheckFrame),p.nativeCheckFrame=0),(p.fallbackActive||p.moved)&&(n(),p.fallbackActive&&(u?.cancelable&&u.preventDefault(),u?.stopPropagation?.()),this.directGestureActive=!1,this.notifyChange()),this.resetDirectPanGestureState(u?.currentTarget||e,p.pointerId))};e.addEventListener("pointerdown",l,a),e.addEventListener("pointermove",d,a),e.addEventListener("pointerup",h,a),e.addEventListener("pointercancel",h,a),e.addEventListener("lostpointercapture",h,a),document.addEventListener("pointerup",h,a),document.addEventListener("pointercancel",h,a)}installDirectWheelGestureFallback(){if(!this.map||this.directWheelGestureInstalled)return;let e=this.map.getContainer?.();if(!e?.addEventListener)return;this.directWheelGestureInstalled=!0;let t=()=>{this.directWheelFrame=0;let n=this.directWheelPendingZoom;this.directWheelPendingZoom=null,!(!Number.isFinite(n)||!this.map)&&this.map.jumpTo({zoom:n})},a=()=>{this.directWheelEndTimer&&clearTimeout(this.directWheelEndTimer),this.directWheelEndTimer=setTimeout(()=>{this.directWheelEndTimer=0,this.directWheelFallbackActive=!1,this.directGestureActive=!1,this.notifyChange()},140)},i=(n,r)=>{requestAnimationFrame(()=>{!this.map||this.cameraMovedSince(r,{zoom:.001})||(this.directWheelFallbackActive||(this.directWheelFallbackActive=!0,this.directWheelFallbackActivations+=1),this.directWheelPendingZoom=n,this.directGestureActive=!0,this.directWheelFrame||(this.directWheelFrame=requestAnimationFrame(t)),a())})},s=n=>{if(Re(n.target))return;let r=n.deltaMode===1?40:n.deltaMode===2?Math.max(1,globalThis.innerHeight||800):1,o=Number(n.deltaY||0)*r;if(!Number.isFinite(o)||o===0)return;let l=typeof this.map.getMinZoom=="function"?this.map.getMinZoom():0,d=typeof this.map.getMaxZoom=="function"?this.map.getMaxZoom():22,h=Number.isFinite(this.directWheelPendingZoom)?this.directWheelPendingZoom:this.map.getZoom(),u=ne(h-o/450,l,d);if(!this.directWheelFallbackActive){i(u,this.readCameraState());return}this.directWheelPendingZoom=u,this.directGestureActive=!0,this.directWheelFrame||(this.directWheelFrame=requestAnimationFrame(t)),a(),n.cancelable&&n.preventDefault(),n.stopPropagation()};e.addEventListener("wheel",s,{passive:!1})}installDirectTwoFingerGestureFallback(){if(!this.map||this.directTwoFingerGestureInstalled)return;let e=this.map.getContainer?.();if(!e?.addEventListener)return;this.directTwoFingerGestureInstalled=!0;let t={passive:!1},a=u=>{u.cancelable&&u.preventDefault(),u.stopPropagation()},i=()=>{this.directTwoFingerGestureFrame=0;let u=this.directTwoFingerGesturePending;this.directTwoFingerGesturePending=null,!(!u||!this.map)&&this.map.jumpTo(u)},s=u=>{this.directTwoFingerGesturePending=u,!this.directTwoFingerGestureFrame&&(this.directTwoFingerGestureFrame=requestAnimationFrame(i))},n=()=>{this.directTwoFingerGestureFrame&&(cancelAnimationFrame(this.directTwoFingerGestureFrame),this.directTwoFingerGestureFrame=0),i()},r=(u,p)=>{let f=yi(p);if(!u||!Number.isFinite(f)||f<=0)return null;let g=gi(p),y=this.map.project(u.center),b=typeof this.map.getMinZoom=="function"?this.map.getMinZoom():0,v=typeof this.map.getMaxZoom=="function"?this.map.getMaxZoom():22,w=f/u.distance,S=ne(u.zoom+Math.log2(Math.max(w,.01)),b,v),M=vi(nn(bi(p)-u.angle)),C=u.bearing+M,T=ne(u.pitch-(g.y-u.midpoint.y)*.18,0,60);return{center:this.map.unproject([y.x-(g.x-u.midpoint.x),y.y-(g.y-u.midpoint.y)]),zoom:S,bearing:C,pitch:T}},o=u=>{u.nativeCheckFrame||u.fallbackActive||u.nativeMoved||(u.nativeCheckFrame=requestAnimationFrame(()=>{if(u.nativeCheckFrame=0,this.directTwoFingerGestureState!==u||u.fallbackActive||u.nativeMoved)return;if(this.cameraMovedSince(u.camera)){u.nativeMoved=!0;return}let p=u.latestPoints?r(u,u.latestPoints):null;p&&(u.fallbackActive=!0,this.directTwoFingerFallbackActivations+=1,this.directGestureActive=!0,s(p))}))},l=u=>{if(Re(u.target))return!1;let p=fi(u);if(!p)return!1;let f=yi(p);if(!Number.isFinite(f)||f<=0)return!1;this.resetDirectPanGestureState(e);let g=this.map.getCenter();return this.directTwoFingerGestureState={distance:f,midpoint:gi(p),angle:bi(p),center:g,zoom:this.map.getZoom(),pitch:this.map.getPitch(),bearing:this.map.getBearing(),camera:this.readCameraState(),latestPoints:p,nativeCheckFrame:0,fallbackActive:!1,nativeMoved:!1},!0},d=u=>{if(Re(u.target))return;let p=fi(u);if(!p||!this.directTwoFingerGestureState&&!l(u))return;let f=this.directTwoFingerGestureState;if(!f)return;if(f.latestPoints=p,!f.fallbackActive&&this.cameraMovedSince(f.camera)){f.nativeMoved=!0;return}if(!f.fallbackActive){o(f);return}let g=r(f,p);g&&(this.directGestureActive=!0,s(g),a(u))},h=u=>{if(!this.directTwoFingerGestureState||u.touches&&u.touches.length>=2)return;let p=this.directTwoFingerGestureState;p.nativeCheckFrame&&(cancelAnimationFrame(p.nativeCheckFrame),p.nativeCheckFrame=0),p.fallbackActive&&n(),this.directTwoFingerGestureState=null,this.resetDirectPanGestureState(e),this.enableGestureHandlers(),p.fallbackActive&&(this.directGestureActive=!1,this.notifyChange(),a(u))};e.addEventListener("touchstart",l,t),e.addEventListener("touchmove",d,t),e.addEventListener("touchend",h,t),e.addEventListener("touchcancel",h,t)}installMobileGestureResizeObserver(e){if(!this.map||this.mobileGestureResizeObserver||typeof ResizeObserver>"u")return;if(!this.shouldInstallMobileGestureResizeObserver()){this.mobileGestureResizeObserverEligible=!1;return}this.mobileGestureResizeObserverEligible=!0;let t=s=>{let n=Array.isArray(s?.borderBoxSize)?s.borderBoxSize[0]:s?.borderBoxSize,r=Number(n?.inlineSize),o=Number(n?.blockSize);if(Number.isFinite(r)&&Number.isFinite(o))return{width:r,height:o};let l=e.getBoundingClientRect?.();return l?{width:l.width,height:l.height}:null},a=s=>{let n=this.mobileGestureResizeSize;return this.mobileGestureResizeSize=s,n?Math.abs(s.width-n.width)>.5||Math.abs(s.height-n.height)>.5:!1},i=(s=[])=>{let n=t(s[0]);this.applyMobileTouchContract(),!(!n||!a(n))&&(this.mobileGestureResizeFrame||(this.mobileGestureResizeFrame=requestAnimationFrame(()=>{this.mobileGestureResizeFrame=0,this.applyMobileTouchContract(),this.map?.resize?.()})))};this.mobileGestureResizeObserver=new ResizeObserver(i),this.mobileGestureResizeObserver.observe(e)}shouldInstallMobileGestureResizeObserver(){let e=t=>{try{return!!globalThis.matchMedia?.(t)?.matches}catch{return!1}};return e("(pointer: coarse)")||e("(max-width: 768px)")}applyMobileTouchContract(){if(!this.map)return;let e=[document.getElementById(typeof this.container=="string"?this.container:""),this.map.getContainer?.(),this.map.getCanvasContainer?.(),this.map.getCanvas?.()].filter(Boolean);for(let a of new Set(e))a.style.touchAction="none",a.style.overscrollBehavior="contain",a.style.userSelect="none",a.style.webkitUserSelect="none",a.style.webkitTouchCallout="none",a.style.webkitOverflowScrolling="auto";let t=this.map.getCanvas?.();t&&(t.style.pointerEvents="auto")}getMobileGestureDiagnostics(){if(!this.map)return null;this.applyMobileTouchContract();let e=this.map.getCanvas?.(),t=this.map.getCanvasContainer?.(),a=this.map.getContainer?.(),i=e?.getBoundingClientRect?.(),s=i?i.left+i.width*.5:0,n=i?i.top+i.height*.5:0,r=i?document.elementFromPoint(s,n):null;return{topTag:r?.tagName||"",topClass:r?.className?String(r.className):"",topIsCanvas:r===e,topWithinMap:!!r?.closest?.("#map"),topWithinCanvasContainer:!!t?.contains?.(r),rootTouchAction:a?getComputedStyle(a).touchAction:"",canvasTouchAction:e?getComputedStyle(e).touchAction:"",canvasContainerTouchAction:t?getComputedStyle(t).touchAction:"",dragPanEnabled:typeof this.map.dragPan?.isEnabled=="function"?this.map.dragPan.isEnabled():!0,scrollZoomEnabled:typeof this.map.scrollZoom?.isEnabled=="function"?this.map.scrollZoom.isEnabled():!0,dragRotateEnabled:typeof this.map.dragRotate?.isEnabled=="function"?this.map.dragRotate.isEnabled():!0,touchZoomEnabled:typeof this.map.touchZoomRotate?.isEnabled=="function"?this.map.touchZoomRotate.isEnabled():!0,touchPitchEnabled:typeof this.map.touchPitch?.isEnabled=="function"?this.map.touchPitch.isEnabled():!0,guardTargetCount:this.mobileGestureGuardTargetCount||0,resizeObserverTargets:this.mobileGestureResizeObserver?1:0,resizeObserverMobileEligible:this.mobileGestureResizeObserverEligible,nativeGesturePrimary:!0,directPanFallbackMode:"emergency",directWheelFallbackMode:"emergency",directTwoFingerFallbackMode:"emergency",directPanGestureInstalled:this.directPanGestureInstalled,directWheelGestureInstalled:this.directWheelGestureInstalled,directTwoFingerGestureInstalled:this.directTwoFingerGestureInstalled,directPanFallbackActivations:this.directPanFallbackActivations,directWheelFallbackActivations:this.directWheelFallbackActivations,directTwoFingerFallbackActivations:this.directTwoFingerFallbackActivations,mapCursor:this.mapCursor,cursorMutationCount:this.cursorMutationCount}}async loadLayer(e){if(e.loadable===!1||e.sourceType==="unconverted")throw new Error(`${e.name} is not yet converted for the /test MapLibre renderer`);if(this.layers.has(e.id)){this.fitToLayer(e.id);return}let t=performance.now(),a=`${e.id}-source`,i=`${e.id}-fill`,s=`${e.id}-line`,n=`${e.id}-raster`,r=`${e.id}-hover`,o=`${e.id}-hover-line`,l=`${e.id}-selected-fill`,d=`${e.id}-selected`,h=`${e.id}-label`;await this.waitForMap();let u=await this.loadDuplicateFeatureIds(e),p={layerIds:[],sourceIds:[]};if(e.sourceType==="point-cloud")await this.addPointCloudLayer(e);else{let g=this.buildSource(e);this.map.addSource(a,g),e.sourceType==="raster-dem"?p=this.addTerrainLayer(e,{sourceId:a,rasterId:n}):e.sourceType==="raster"||e.sourceType==="image"?this.addRasterLayer(e,{sourceId:a,rasterId:n}):(this.addGeometryLayers(e,{sourceId:a,fillId:i,lineId:s,hoverId:r,selectedFillId:l,selectedId:d}),p=this.addInteractionOverlayLayers(e))}let f=this.addLabelLayers(e,{sourceId:a,labelId:h});this.layers.set(e.id,{config:e,sourceId:a,sourceIds:[a,...p.sourceIds],layerIds:[i,s,r,o,l,d,...p.layerIds,h,n].filter(g=>this.map.getLayer(g)),labelLayerIds:f,domLabelMarkers:new Map,domLabelsScheduled:0,duplicateFeatureIds:u,labelsEnabled:!0,textScale:pt,opacity:_i(e),color:e.style?.color||"#5B21B6",fillColor:e.style?.fillColor||e.style?.color||"#7C3AED"}),this.applySavedLayerPreferences(e.id),e.sourceType!=="raster"&&e.sourceType!=="image"&&e.sourceType!=="raster-dem"&&e.sourceType!=="point-cloud"&&(this.interactionCleanups.set(e.id,this.bindLayerInteractions(e,i,h,a)),this.scheduleDomLabelRefresh(e.id)),e.sourceType==="pmtiles"&&this.fallbackCleanups.set(e.id,this.monitorPmtilesFallback(e,a)),this.reorderFromSavedLayerOrder(),this.scheduleAllDomLabelRefresh(),this.fitToLayer(e.id),this.recordMetric({layerId:e.id,layerName:e.name,event:"load",durationMs:Math.round(performance.now()-t),sourceType:e.sourceType}),this.notifyChange()}addRasterLayer(e,t){this.map.addLayer({id:t.rasterId,type:"raster",source:t.sourceId,paint:{"raster-opacity":ne(e.rasterOpacity??e.style?.opacity??.85,0,1)}})}addTerrainLayer(e,t){let{sourceId:a,rasterId:i}=t,s={layerIds:[],sourceIds:[]},n=ne(e.exaggeration??1.5,0,12);if(this.map.setTerrain({source:a,exaggeration:n}),this.terrainLayerId=e.id,this.terrainSourceId=a,this.terrainExaggeration=n,typeof this.map.setMaxPitch=="function"&&this.map.getMaxPitch()<80&&this.map.setMaxPitch(85),e.hillshadeTiles){let r=`${a}-hs`;this.map.addSource(r,{type:"raster",tiles:[et(e.hillshadeTiles)],tileSize:e.tileSize||256,minzoom:e.hillshadeMinzoom??e.minzoom,maxzoom:e.hillshadeMaxzoom??e.maxzoom,bounds:Qe(e.bounds)}),this.map.addLayer({id:i,type:"raster",source:r,paint:{"raster-opacity":ne(e.hillshadeOpacity??.5,0,1)}}),s.sourceIds.push(r),s.layerIds.push(i)}return s}setTerrainExaggeration(e){if(!this.terrainSourceId)return;let t=ne(e,0,12);this.terrainExaggeration=t,this.map.setTerrain({source:this.terrainSourceId,exaggeration:t})}addPointCloudLayer(e){if(this.pointCloudLayers||(this.pointCloudLayers=new Map),this.pointCloudLayers.has(e.id))return{layerIds:[`pointcloud-${e.id}`],sourceIds:[]};typeof this.map.setMaxPitch=="function"&&this.map.getMaxPitch()<80&&this.map.setMaxPitch(85);let t=`pointcloud-${e.id}`,a=String(e.tilesetUrl||""),i=this.layers.get(e.id),s=ne(i?.opacity??_i(e),0,1),n;if(e.pcFlat){let r=a.split("?")[0].replace(/tileset\.json$/,"pc.json");n=ii(t,r+"?v="+(e.pcVersion||"pc2"),{pointSize:e.pointSize??2.5,opacity:s})}else n=li(t,a,{pointSize:e.pointSize??1.6,opacity:s});return this.map.addLayer(n),this.pointCloudLayers.set(e.id,n),{layerIds:[`pointcloud-${e.id}`],sourceIds:[]}}removePointCloudLayer(e){let t=this.pointCloudLayers?.get(e);if(t){try{this.map.getLayer(t.id)&&this.map.removeLayer(t.id)}catch{}this.pointCloudLayers.delete(e)}}setPointSize(e,t){this.pointCloudLayers?.get(e)?.setPointSize(ne(Number(t)||2.5,.5,10))}addGeometryLayers(e,t){let{sourceId:a,fillId:i,lineId:s,hoverId:n,selectedFillId:r,selectedId:o}=t;if(e.geometryType!=="line"&&e.geometryType!=="point"&&this.map.addLayer({id:i,type:"fill",source:a,"source-layer":e.sourceLayer,paint:{"fill-color":e.style?.fillColor||e.style?.color||"#7C3AED","fill-opacity":Ci(e),"fill-antialias":!1}}),this.map.addLayer({id:s,type:e.geometryType==="point"?"circle":"line",source:a,"source-layer":e.sourceLayer,paint:e.geometryType==="point"?{"circle-color":e.style?.color||"#5B21B6","circle-radius":["interpolate",["linear"],["zoom"],5,2.5,12,6],"circle-opacity":.88}:{"line-color":e.style?.color||"#5B21B6","line-width":["interpolate",["linear"],["zoom"],5,Math.max(.4,Number(e.style?.weight||1)*.55),12,Math.max(.8,Number(e.style?.weight||1)*1.4)],"line-opacity":.88}}),e.geometryType==="point"?this.map.addLayer({id:n,type:"circle",source:a,"source-layer":e.sourceLayer,paint:{"circle-color":We,"circle-stroke-color":Ke,"circle-stroke-width":["case",["boolean",["feature-state","hover"],!1],2,0],"circle-radius":["case",["boolean",["feature-state","hover"],!1],7,0],"circle-opacity":["case",["boolean",["feature-state","hover"],!1],.95,0]}}):e.geometryType==="line"?this.map.addLayer({id:n,type:"line",source:a,"source-layer":e.sourceLayer,paint:{"line-color":Ke,"line-width":["case",["boolean",["feature-state","hover"],!1],3,0],"line-opacity":["case",["boolean",["feature-state","hover"],!1],.95,0]}}):this.map.addLayer({id:n,type:"fill",source:a,"source-layer":e.sourceLayer,paint:{"fill-color":We,"fill-opacity":["case",["boolean",["feature-state","hover"],!1],.42,0],"fill-antialias":!1}}),e.geometryType==="point"){this.map.addLayer({id:o,type:"circle",source:a,"source-layer":e.sourceLayer,paint:{"circle-color":We,"circle-stroke-color":Ke,"circle-stroke-width":["case",["boolean",["feature-state","selected"],!1],2.5,0],"circle-radius":["case",["boolean",["feature-state","selected"],!1],8,0],"circle-opacity":["case",["boolean",["feature-state","selected"],!1],.95,0]}});return}if(e.geometryType!=="line"){this.map.addLayer({id:r,type:"fill",source:a,"source-layer":e.sourceLayer,paint:{"fill-color":We,"fill-opacity":["case",["boolean",["feature-state","selected"],!1],.42,0],"fill-antialias":!1}});return}this.map.addLayer({id:o,type:"line",source:a,"source-layer":e.sourceLayer,paint:{"line-color":Ke,"line-width":["case",["boolean",["feature-state","selected"],!1],3,0],"line-opacity":["case",["boolean",["feature-state","selected"],!1],.95,0]}})}addInteractionOverlayLayers(e){let t=`${e.id}-fallback-hover-source`,a=`${e.id}-fallback-selected-source`;this.map.addSource(t,{type:"geojson",data:St}),this.map.addSource(a,{type:"geojson",data:St});let i=[],s=[t,a],n=(l,d,h)=>{this.map.addLayer({id:l,type:"circle",source:d,paint:{"circle-color":We,"circle-stroke-color":Ke,"circle-stroke-width":2.5,"circle-radius":h,"circle-opacity":.95}}),i.push(l)},r=(l,d,h=3)=>{this.map.addLayer({id:l,type:"line",source:d,paint:{"line-color":Ke,"line-width":h,"line-opacity":.95}}),i.push(l)},o=(l,d)=>{this.map.addLayer({id:l,type:"fill",source:d,paint:{"fill-color":We,"fill-opacity":.42,"fill-antialias":!1}}),i.push(l)};return e.geometryType==="point"?(n(`${e.id}-fallback-hover`,t,7),n(`${e.id}-fallback-selected`,a,8)):e.geometryType==="line"?(r(`${e.id}-fallback-hover`,t,3),r(`${e.id}-fallback-selected`,a,3)):(o(`${e.id}-fallback-hover-fill`,t),o(`${e.id}-fallback-selected-fill`,a)),{layerIds:i,sourceIds:s}}addLabelLayers(e,t){if(!e.labelProperty)return[];let{sourceId:a,labelId:i}=t,s=ta(e),n=ci(e),r=rt(e);return this.map.addLayer({id:i,type:"symbol",source:a,"source-layer":e.sourceLayer,minzoom:s,maxzoom:n,filter:pi(e),layout:{"text-field":hi(e),"text-size":_t(e,pt),"text-font":ui(r),"text-max-width":r.maxWidth,"text-line-height":r.lineHeight,"text-justify":"center","text-padding":2,"text-allow-overlap":!!e.labelAllowOverlap,"text-ignore-placement":!!e.labelIgnorePlacement,"symbol-sort-key":mi(e)},paint:{"text-color":di(e),"text-halo-color":r.haloColor,"text-halo-width":r.haloWidth,"text-halo-blur":r.haloBlur,"text-opacity":0}}),[i]}unloadLayer(e){let t=this.layers.get(e);if(t){this.terrainLayerId===e&&(this.map.setTerrain(null),this.terrainLayerId=null,this.terrainSourceId=null,this.terrainExaggeration=null),this.pointCloudLayers?.has(e)&&this.removePointCloudLayer(e),this.clearFeatureState(this.hovered,"hover"),this.clearFeatureState(this.selected,"selected"),this.interactionCleanups.get(e)?.(),this.interactionCleanups.delete(e),this.fallbackCleanups.get(e)?.(),this.fallbackCleanups.delete(e),this.clearDomLabels(e);for(let a of[...t.layerIds].reverse())this.map.getLayer(a)&&this.map.removeLayer(a);for(let a of[...t.sourceIds||[],t.sourceId])this.map.getSource(a)&&this.map.removeSource(a);this.layers.delete(e),this.scheduleAllDomLabelRefresh(),this.selected?.layerId===e&&(this.selected=null,this.options.onSelection?.(null)),this.notifyChange()}}setOpacity(e,t){let a=this.layers.get(e);if(!a)return;if(a.opacity=ne(t,0,1),this.pointCloudLayers?.has(e)){this.pointCloudLayers.get(e)?.setOpacity(a.opacity),this.notifyChange();return}let i=`${e}-fill`,s=`${e}-line`,n=`${e}-raster`;if(this.map.getLayer(n)&&this.map.setPaintProperty(n,"raster-opacity",a.opacity),this.map.getLayer(i)&&this.map.setPaintProperty(i,"fill-opacity",a.opacity),this.map.getLayer(s)){let r=a.config.geometryType==="point"?"circle-opacity":"line-opacity";this.map.setPaintProperty(s,r,ne(a.opacity+.35,0,1))}this.notifyChange()}setLayerColor(e,t){let a=this.layers.get(e);if(!a||!wi(t))return;a.color=t;let i=`${e}-line`;if(this.map.getLayer(i)){let s=a.config.geometryType==="point"?"circle-color":"line-color";this.map.setPaintProperty(i,s,t)}this.notifyChange()}setLayerFillColor(e,t){let a=this.layers.get(e);if(!a||!wi(t))return;a.fillColor=t;let i=`${e}-fill`;this.map.getLayer(i)&&this.map.setPaintProperty(i,"fill-color",t),this.notifyChange()}setLayerStrokeWidth(e,t){let a=this.layers.get(e);if(!a)return;let i=`${e}-line`;if(!this.map.getLayer(i))return;let s=ne(t,.2,8);a.config.geometryType==="point"?this.map.setPaintProperty(i,"circle-radius",s):this.map.setPaintProperty(i,"line-width",s),a.strokeWidth=s,this.notifyChange()}setLayerAttributeFilter(e,t,a){let i=this.layers.get(e);if(!i||!t)return!1;let s=a==null||a===""?null:["==",["to-string",["get",t]],String(a)];for(let n of i.layerIds||[])!this.map.getLayer(n)||/label|hover|selected/i.test(n)||this.map.setFilter(n,s);return i.attributeFilter=s?{attribute:t,value:String(a)}:null,this.notifyChange(),!0}clearLayerFilter(e){let t=this.layers.get(e);if(!t)return!1;for(let a of t.layerIds||[])!this.map.getLayer(a)||/label|hover|selected/i.test(a)||this.map.setFilter(a,null);return t.attributeFilter=null,this.notifyChange(),!0}setLayerLabelsEnabled(e,t){let a=this.layers.get(e);if(!a)return;a.labelsEnabled=!!t;let i=a.labelsEnabled?"visible":"none";for(let s of a.labelLayerIds||[])this.map.getLayer(s)&&this.map.setLayoutProperty(s,"visibility",i);for(let s of a.domLabelMarkers?.values?.()||[])s.getElement().hidden=!a.labelsEnabled;this.notifyChange()}setLayerTextScale(e,t){let a=this.layers.get(e);if(a){a.textScale=ne(t,50,200);for(let i of a.labelLayerIds||[])this.map.getLayer(i)&&this.map.setLayoutProperty(i,"text-size",_t(a.config,a.textScale));this.scheduleDomLabelRefresh(e),this.notifyChange()}}moveLayerOrder(e,t){if(!this.layers.has(e)||!t)return!1;let a=[...this.layers.entries()],i=a.findIndex(([r])=>r===e),s=i+t;if(s<0||s>=a.length)return!1;let[n]=a.splice(i,1);return a.splice(s,0,n),this.layers=new Map(a),this.reapplyLayerOrder(),Li([...this.layers.keys()]),this.notifyChange(),!0}moveLayerBefore(e,t){if(!this.layers.has(e)||!this.layers.has(t)||e===t)return!1;let a=[...this.layers.entries()],i=a.findIndex(([o])=>o===e),s=a.findIndex(([o])=>o===t);if(i<0||s<0)return!1;let[n]=a.splice(i,1),r=a.findIndex(([o])=>o===t);return a.splice(r<0?s:r,0,n),this.layers=new Map(a),this.reapplyLayerOrder(),Li([...this.layers.keys()]),this.notifyChange(),!0}reorderFromSavedLayerOrder(){let e=gn();if(!e.length||this.layers.size<2)return;let t=new Map(e.map((i,s)=>[i,s])),a=[...this.layers.entries()].sort((i,s)=>{let n=t.has(i[0])?t.get(i[0]):Number.MAX_SAFE_INTEGER,r=t.has(s[0])?t.get(s[0]):Number.MAX_SAFE_INTEGER;return n-r});this.layers=new Map(a),this.reapplyLayerOrder()}reapplyLayerOrder(){for(let e of this.layers.values())for(let t of e.layerIds||[])this.map.getLayer(t)&&this.map.moveLayer(t);this.scheduleAllDomLabelRefresh()}applySavedLayerPreferences(e){let t=fn(e);t&&(t.opacity!==void 0&&this.setOpacity(e,Number(t.opacity)),t.strokeWidth!==void 0&&this.setLayerStrokeWidth(e,Number(t.strokeWidth)),t.color&&this.setLayerColor(e,t.color),t.fillColor&&this.setLayerFillColor(e,t.fillColor),t.labelsEnabled!==void 0&&this.setLayerLabelsEnabled(e,!!t.labelsEnabled),t.textScale!==void 0&&this.setLayerTextScale(e,Number(t.textScale)))}selectFeatureById(e,t,a={}){let i=this.layers.get(e);return!i||t===void 0||t===null||i.config.sourceType==="raster"?!1:(this.setDomLabelSelected(this.selected?.layerId,this.selected?.id,!1),this.clearFeatureState(this.selected,"selected"),this.selected={layerId:e,sourceId:i.sourceId,sourceLayer:i.config.sourceLayer,id:t,properties:a},this.map.setFeatureState({source:i.sourceId,sourceLayer:i.config.sourceLayer,id:t},{selected:!0}),this.setDomLabelSelected(e,t,!0),this.options.onSelection?.({layer:i.config,feature:{id:t,properties:a}}),this.notifyChange(),!0)}fitToLayer(e){let t=this.layers.get(e);t&&this.fitToBounds(t.config.bounds,{terrain:t.config.sourceType==="raster-dem"||t.config.sourceType==="point-cloud"})}fitToBounds(e,t={}){let a=Je(e);if(a){if(t.terrain&&typeof this.map.cameraForBounds=="function"){let i=this.map.cameraForBounds(a,{padding:36});if(i){let s=this.map.getPitch(),n=s{a=!0,this.map.off("error",s)},9e3),s=n=>{if(a||!this.layers.has(e.id))return;let r=String(n?.error?.message||n?.error||""),o=!n.sourceId||n.sourceId===t,l=/pmtiles|byte|range|content-length|fetch|network|failed/i.test(r);if(!o||!l)return;a=!0,clearTimeout(i),this.map.off("error",s);let d={layerId:e.id,layerName:e.name,event:"pmtiles-fallback",sourceType:"pmtiles",reason:r.slice(0,240)};if(this.recordMetric(d),!(e.tilesFallback&&(!rn(e.tilesFallback)||on()))){let p={...d,event:"pmtiles-fallback-unavailable",fallbackUnavailable:!0,reason:`${d.reason}${d.reason?" ":""}Directory MVT fallback is not deployed on production Pages.`};this.recordMetric(p),this.fallbackLayers.set(e.id,p),this.options.onFallback?.(p);return}let u={...e,sourceType:"mvt",tiles:e.tilesFallback,tileUrl:void 0,fallbackFromPmtiles:!0};this.unloadLayer(e.id),this.loadLayer(u).catch(p=>{this.recordMetric({layerId:e.id,layerName:e.name,event:"pmtiles-fallback-failed",sourceType:"mvt",reason:String(p.message||p).slice(0,240)}),this.options.onError?.(p)}),this.fallbackLayers.set(e.id,d),this.options.onFallback?.(d)};return this.map.on("error",s),()=>{a=!0,clearTimeout(i),this.map.off("error",s)}}bindLayerInteractions(e,t,a,i){let s=0,n=null,r=0,o=()=>this.clearHover(),l=(v,w=0)=>{let S=[t,`${e.id}-line`].filter(C=>C&&this.map.getLayer(C));if(S.length===0)return[];let M=w>0?[[v.x-w,v.y-w],[v.x+w,v.y+w]]:v;return this.map.queryRenderedFeatures(M,{layers:S})},d=()=>{r=0;let v=n;if(n=null,!v||!this.layers.has(e.id))return;if(this.options.shouldSuppressLayerInteraction?.(v)){o();return}let w=typeof this.map.isSourceLoaded=="function"?this.map.isSourceLoaded(i):this.map.areTilesLoaded();if(this.map.isMoving()||!w){o();return}this.setHover(e,l(v.point)[0])},h=v=>{let w=v.originalEvent;if(w&&document.elementFromPoint(w.clientX,w.clientY)?.closest?.(".maplibre-dom-label"))return;n=v;let S=performance.now();if(S-s{let w=v.target?.closest?.(".maplibre-dom-label")||document.elementFromPoint(v.clientX,v.clientY)?.closest?.(".maplibre-dom-label");if(w?.dataset?.layerId!==e.id)return;let S=w.__civgraphFeature;S&&this.setHover(e,S)},p=v=>{if(this.options.shouldSuppressLayerInteraction?.(v))return;v.preventDefault?.();let w=l(v.point,Ht)[0];w&&this.selectFeature(e,w)},f=v=>{let w=v.originalEvent;if(this.options.shouldSuppressLayerInteraction?.(v)||w&&document.elementFromPoint(w.clientX,w.clientY)?.closest?.(".maplibre-dom-label, .maplibregl-ctrl, .map-controls, .active-layers-toggle"))return;let S=l(v.point,Ht)[0];if(!S){this.clearHover();return}v.preventDefault?.(),this.selectFeature(e,S)},g=()=>this.scheduleDomLabelRefresh(e.id),y=()=>{this.hovered?.layerId!==e.id&&this.scheduleDomLabelRefresh(e.id)},b=this.map.getContainer();return this.map.on("mousemove",h),this.map.on("click",f),this.map.on("dblclick",p),this.map.on("movestart",o),this.map.on("moveend",g),this.map.on("zoomend",g),this.map.on("idle",y),b.addEventListener("pointermove",u,!0),b.addEventListener("mouseleave",o),()=>{r&&cancelAnimationFrame(r),this.map.off("mousemove",h),this.map.off("click",f),this.map.off("dblclick",p),this.map.off("movestart",o),this.map.off("moveend",g),this.map.off("zoomend",g),this.map.off("idle",y),b.removeEventListener("pointermove",u,!0),b.removeEventListener("mouseleave",o)}}readFeatureId(e,t){return this.readFeatureIdentity(e,t).id}readFeatureIdentity(e,t){let a=e?.promoteId||"id",i=t?.id??t?.properties?.[a]??t?.properties?.id;if(i!=null&&i!==""){if(this.layers.get(e.id)?.duplicateFeatureIds?.has(String(i))){let r=Ii(e,t)||hn(e,t,i);return r?{id:r,generated:!0,sourceFeatureId:i,duplicatePromoteId:!0}:{id:i,generated:!1}}return{id:i,generated:!1}}let s=Ii(e,t);return s?{id:s,generated:!0}:{id:null,generated:!0}}async loadDuplicateFeatureIds(e){if(e?.featureIdMode==="unique"||e?.duplicateFeatureIdCount===0)return new Set;if(Array.isArray(e?.duplicateFeatureIds))return new Set(e.duplicateFeatureIds.map(String));let t=e?.duplicateFeatureIdsUrl;if(t){let s=`sidecar:${t}`;return this.duplicateFeatureIdCache.has(s)||this.duplicateFeatureIdCache.set(s,fetch(t,{cache:"force-cache"}).then(n=>n.ok?n.json():null).then(n=>new Set((n?.duplicateFeatureIds||[]).map(String))).catch(()=>new Set)),this.duplicateFeatureIdCache.get(s)}let a=e?.featureIndexUrl;if(!a)return new Set;let i=`index:${a}`;return this.duplicateFeatureIdCache.has(i)||this.duplicateFeatureIdCache.set(i,fetch(a,{cache:"force-cache"}).then(s=>s.ok?s.json():null).then(s=>{let n=Array.isArray(s)?s:Array.isArray(s?.items)?s.items:Array.isArray(s?.features)?s.features:[],r=new Map;for(let o of n){if(o?.id===void 0||o?.id===null||o.id==="")continue;let l=String(o.id);r.set(l,(r.get(l)||0)+1)}return new Set([...r].filter(([,o])=>o>1).map(([o])=>o))}).catch(()=>new Set)),this.duplicateFeatureIdCache.get(i)}clearHover({resetCursor:e=!0}={}){let t=this.hovered;this.clearFeatureState(t,"hover"),this.setDomLabelHover(t?.layerId,t?.id,!1),this.hovered=null,e&&this.setMapCursor("")}setHover(e,t){let{id:a,generated:i}=this.readFeatureIdentity(e,t);if(a===null){this.clearHover();return}if(this.hovered?.layerId===e.id&&this.hovered.id===a)return;this.clearHover({resetCursor:!1});let s=this.layers.get(e.id);if(this.hovered={layerId:e.id,sourceId:s?.sourceId,sourceLayer:e.sourceLayer,id:a,generated:i},this.setDomLabelHover(e.id,a,!0),!i)try{this.map.setFeatureState({source:s.sourceId,sourceLayer:e.sourceLayer,id:a},{hover:!0})}catch{}i||e.geometryType==="point"||e.geometryType==="line"?this.setInteractionOverlay(e.id,"hover",t):this.clearInteractionOverlay(e.id,"hover"),this.setMapCursor("pointer")}selectFeature(e,t){let{id:a,generated:i}=this.readFeatureIdentity(e,t);if(a===null)return!1;let s=this.layers.get(e.id);if(!s)return!1;this.setDomLabelSelected(this.selected?.layerId,this.selected?.id,!1),this.clearFeatureState(this.selected,"selected");let n=t.geometry||null;if(!i&&e.geometryType==="polygon"&&an.has(e.sourceType)){let o=this.mergePolygonFragments(e,a);o&&(n=o)}let r={...t,id:a,properties:ze(e,t.properties||{}),geometry:n};if(this.selected={layerId:e.id,sourceId:s.sourceId,sourceLayer:e.sourceLayer,id:a,generated:i,properties:r.properties},!i)try{this.map.setFeatureState({source:s.sourceId,sourceLayer:e.sourceLayer,id:a},{selected:!0})}catch{}return i||e.geometryType==="point"||e.geometryType==="line"?this.setInteractionOverlay(e.id,"selected",r):this.clearInteractionOverlay(e.id,"selected"),this.setDomLabelSelected(e.id,a,!0),this.options.onSelection?.({layer:e,feature:r}),this.notifyChange(),!0}mergePolygonFragments(e,t){let i=this.layers.get(e.id)?.sourceId,s=String(t),n=[],r=o=>{for(let l of o||[]){if(String(this.readFeatureIdentity(e,l).id)!==s)continue;let d=l.geometry;if(d){if(d.type==="Polygon")n.push(d.coordinates);else if(d.type==="MultiPolygon")for(let h of d.coordinates)n.push(h)}}};if(i)try{r(this.map.querySourceFeatures(i,{sourceLayer:e.sourceLayer,filter:["==",["get",e.promoteId||"id"],t]}))}catch{}if(n.length===0){let o=`${e.id}-fill`;if(this.map.getLayer(o))try{r(this.map.queryRenderedFeatures({layers:[o]}))}catch{}}return n.length<=1?null:{type:"MultiPolygon",coordinates:n}}setInteractionOverlay(e,t,a){let i=this.layers.get(e),s=`${e}-fallback-${t}-source`,n=i&&this.map.getSource(s);if(!n?.setData)return;let r=mn(a?.geometry);if(!r){n.setData(St);return}n.setData({type:"FeatureCollection",features:[{type:"Feature",geometry:r,properties:{...a.properties||{}}}]})}clearInteractionOverlay(e,t){let a=e?this.map.getSource(`${e}-fallback-${t}-source`):null;a?.setData&&a.setData(St)}scheduleDomLabelRefresh(e){let t=this.layers.get(e);!t||!t.config?.labelProperty||t.config.sourceType==="raster"||t.config.sourceType==="image"||t.domLabelsScheduled||(t.domLabelsScheduled=requestAnimationFrame(()=>{t.domLabelsScheduled=0,this.refreshDomLabels(e)}))}scheduleAllDomLabelRefresh(){for(let e of this.layers.keys())this.scheduleDomLabelRefresh(e)}refreshDomLabels(e){let t=this.layers.get(e);if(!t||!t.config?.labelProperty)return;let a=t.config,i=[`${e}-fill`,`${e}-line`].filter(u=>this.map.getLayer(u)),s=Number.isFinite(Number(a.test2LabelMinZoomOverride))?Number(a.test2LabelMinZoomOverride):ta(a);if(!i.length||!t.labelsEnabled||this.map.getZoom()=r)break;let p=this.readFeatureId(a,u);if(p===null)continue;let f=wt(a,u.properties);if(!f)continue;let g=dn(u);if(!g)continue;let y=String(p);if(o.has(y))continue;let b=this.map.project(g),v=Si(b,f);if(l.some(z=>un(z,v)))continue;l.push(v),o.add(y);let w=t.domLabelMarkers.get(y);w||(w=this.createDomLabelMarker(a,u,p,f),t.domLabelMarkers.set(y,w));let S=w.getElement();S.__civgraphFeature=u;let M=S.querySelector("div");M&&M.textContent!==f&&(M.textContent=f);let C=this.selected?.layerId===e&&String(this.selected.id)===y;S.classList.contains("map-label--selected")!==C&&S.classList.toggle("map-label--selected",C);let T=!t.labelsEnabled;S.hidden!==T&&(S.hidden=T);let V=`${Number(g[0]).toFixed(7)},${Number(g[1]).toFixed(7)}`;S.__civgraphLngLatKey!==V&&(w.setLngLat(g),S.__civgraphLngLatKey=V),S.isConnected||w.addTo(this.map)}let h=this.hovered?.layerId===e?String(this.hovered.id):null;h&&t.domLabelMarkers.has(h)&&o.add(h);for(let[u,p]of t.domLabelMarkers)o.has(u)||(p.remove(),t.domLabelMarkers.delete(u))}createDomLabelMarker(e,t,a,i){let s=rt(e),n=document.createElement("span");n.className="map-label map-label--clickable maplibre-dom-label",n.dataset.layerId=e.id,n.dataset.featureId=String(a),n.__civgraphFeature=t,n.setAttribute("role","button"),n.setAttribute("tabindex","0"),n.setAttribute("aria-label",`Show details for ${i}`);let r=document.createElement("div");r.textContent=i,r.style.color=s.color,r.style.fontSize=`${_t(e,this.layers.get(e.id)?.textScale||pt)}px`,n.appendChild(r);let o=d=>{d.preventDefault(),d.stopPropagation(),this.selectFeature(e,n.__civgraphFeature||t)};n.addEventListener("click",o),n.addEventListener("keydown",d=>{(d.key==="Enter"||d.key===" ")&&o(d)});let l=()=>this.setHover(e,n.__civgraphFeature||t);return n.addEventListener("mouseenter",l),n.addEventListener("mouseover",l),n.addEventListener("pointerenter",l),n.addEventListener("mouseleave",()=>this.clearHover()),n.addEventListener("pointerleave",()=>this.clearHover()),new Ee.default.Marker({element:n,anchor:"center"})}clearDomLabels(e){let t=this.layers.get(e);if(t?.domLabelMarkers){t.domLabelsScheduled&&(cancelAnimationFrame(t.domLabelsScheduled),t.domLabelsScheduled=0);for(let a of t.domLabelMarkers.values())a.remove();t.domLabelMarkers.clear()}}setDomLabelHover(e,t,a){this.layers.get(e)?.domLabelMarkers?.get(String(t))?.getElement().classList.toggle("map-label--hover",!!a)}setDomLabelSelected(e,t,a){this.layers.get(e)?.domLabelMarkers?.get(String(t))?.getElement().classList.toggle("map-label--selected",!!a)}clearFeatureState(e,t){if(e?.layerId&&this.clearInteractionOverlay(e.layerId,t),!(!e?.sourceId||e.id===void 0||e.id===null)&&this.map.getSource(e.sourceId)&&!e.generated)try{this.map.setFeatureState({source:e.sourceId,sourceLayer:e.sourceLayer,id:e.id},{[t]:!1})}catch{}}waitForMap(){return this.map.isStyleLoaded?.()||this.map.loaded()?Promise.resolve():new Promise(e=>{let t=0,a=()=>{clearTimeout(t),this.map.off("load",a),this.map.off("styledata",i),e()},i=()=>{(this.map.isStyleLoaded?.()||this.map.loaded())&&a()};this.map.once("load",a),this.map.on("styledata",i),t=setTimeout(a,3e3)})}notifyChange(){this.options.onChange?.(this)}recordMetric(e){this.metrics.push(e),this.options.onMetric?.(e)}getMetrics(){return[...this.metrics]}};function wi(c){return typeof c=="string"&&/^#[0-9a-f]{6}$/i.test(c)}function dn(c){let e=c?.properties||{},t=Number(e.label_lon??e.label_lng??e.lon??e.lng??e.longitude),a=Number(e.label_lat??e.lat??e.latitude);if(Number.isFinite(t)&&Number.isFinite(a))return[t,a];let i=[];if(ia(c?.geometry?.coordinates,i),!i.length)return null;let s=1/0,n=1/0,r=-1/0,o=-1/0;for(let[l,d]of i)!Number.isFinite(l)||!Number.isFinite(d)||(s=Math.min(s,l),r=Math.max(r,l),n=Math.min(n,d),o=Math.max(o,d));return[s,r,n,o].every(Number.isFinite)?[(s+r)/2,(n+o)/2]:null}function Si(c,e){let t=Math.min(Math.max(String(e).length*7.5,34),150),a=Math.max(16,Math.ceil(String(e).length/18)*15),i=4;return{left:c.x-t/2-i,right:c.x+t/2+i,top:c.y-a/2-i,bottom:c.y+a/2+i}}function un(c,e){return c.lefte.left&&c.tope.top}function ia(c,e){if(Array.isArray(c)){if(c.length>=2&&typeof c[0]=="number"&&typeof c[1]=="number"){e.push([c[0],c[1]]);return}for(let t of c)ia(t,e)}}function Ii(c,e){let t=e?.properties||{},a=wt(c,t)||"",i=pn(e?.geometry),s=Ti(t,c),n=[a,s,i].filter(Boolean).join("|");return n?`generated:${xi(n)}`:null}function hn(c,e,t){let a=e?.properties||{},i=wt(c,a)||"",s=Ti(a,c),n=[c?.id||"",t==null?"":String(t),i,s,JSON.stringify(a).slice(0,500)].filter(Boolean).join("|");return n?`generated:${xi(n)}`:null}function pn(c){let e=[];if(ia(c?.coordinates,e),!e.length)return"";let t=1/0,a=1/0,i=-1/0,s=-1/0;for(let[l,d]of e)!Number.isFinite(l)||!Number.isFinite(d)||(t=Math.min(t,l),i=Math.max(i,l),a=Math.min(a,d),s=Math.max(s,d));if(![t,a,i,s].every(Number.isFinite))return"";let n=e[0]||[],r=e[Math.floor(e.length/2)]||[],o=e[e.length-1]||[];return[c?.type||"Geometry",e.length,Ce(t),Ce(a),Ce(i),Ce(s),Ce(n[0]),Ce(n[1]),Ce(r[0]),Ce(r[1]),Ce(o[0]),Ce(o[1])].join(":")}function Ti(c,e){let t=[e?.labelProperty,...e?.labelPropertyFallbacks||[],...e?.popupProperties||[],"name","Name","NAME"].filter(Boolean);return[...new Set(t)].slice(0,8).map(a=>{let i=c?.[a];return i==null?"":`${a}=${String(i).slice(0,80)}`}).filter(Boolean).join(";")}function Ce(c){let e=Number(c);return Number.isFinite(e)?e.toFixed(6):""}function xi(c){let e=2166136261,t=String(c);for(let a=0;a>>0).toString(36)}function mn(c){return!c?.type||!c.coordinates?null:JSON.parse(JSON.stringify({type:c.type,coordinates:c.coordinates}))}function fn(c){try{return JSON.parse(localStorage.getItem(`civgraph:test:controls:${c}`)||"null")}catch{return null}}function gn(){try{return JSON.parse(localStorage.getItem("civgraph:test:layer-order")||"[]")}catch{return[]}}function Li(c){try{localStorage.setItem("civgraph:test:layer-order",JSON.stringify(c))}catch{}}W();var yn="settled",bn="timeout",vn="unavailable";function Ei(c,{timeoutMs:e=2e4}={}){return!c||typeof c.on!="function"||typeof c.off!="function"?Promise.resolve(vn):new Promise(t=>{let a=!1,i=r=>{a||(a=!0,clearTimeout(n),c.off("idle",s),t(r))},s=()=>{(typeof c.areTilesLoaded!="function"||c.areTilesLoaded())&&i(yn)},n=setTimeout(()=>i(bn),e);c.on("idle",s)})}var Mi={"osm-standard":["https://tile.openstreetmap.org/{z}/{x}/{y}.png"],"osm-humanitarian":["https://tile-{a-c}.openstreetmap.fr/hot/{z}/{x}/{y}.png"],"cartodb-positron":["https://a.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png"],"cartodb-dark":["https://a.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}.png"],"cartodb-dark-nolabels":["https://a.basemaps.cartocdn.com/dark_nolabels/{z}/{x}/{y}.png"],"cartodb-voyager":["https://a.basemaps.cartocdn.com/rastertiles/voyager/{z}/{x}/{y}.png"],"esri-satellite":["https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}"],"esri-world-topo":["https://services.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer/tile/{z}/{y}/{x}"],"esri-natgeo":["https://services.arcgisonline.com/ArcGIS/rest/services/NatGeo_World_Map/MapServer/tile/{z}/{y}/{x}"],"esri-ocean":["https://services.arcgisonline.com/ArcGIS/rest/services/Ocean/World_Ocean_Base/MapServer/tile/{z}/{y}/{x}"],opentopomap:["https://a.tile.opentopomap.org/{z}/{x}/{y}.png"],"stamen-terrain":["https://stamen-tiles.a.ssl.fastly.net/terrain/{z}/{x}/{y}.jpg"],"usgs-topo":["https://basemap.nationalmap.gov/arcgis/rest/services/USGSTopo/MapServer/tile/{z}/{y}/{x}"]},_n={"voyager-labels":{tiles:["https://a.basemaps.cartocdn.com/rastertiles/voyager_only_labels/{z}/{x}/{y}.png","https://b.basemaps.cartocdn.com/rastertiles/voyager_only_labels/{z}/{x}/{y}.png","https://c.basemaps.cartocdn.com/rastertiles/voyager_only_labels/{z}/{x}/{y}.png"],attribution:"© CARTO",maxzoom:20},"merit-catchments":{tiles:["https://tiles.arcgis.com/tiles/P3ePLMYs2RVChkJx/arcgis/rest/services/MERIT_River_Basins_v1/MapServer/tile/{z}/{y}/{x}"],attribution:"© MERIT-Basins",maxzoom:12},"merit-rivers":{tiles:["https://tiles.arcgis.com/tiles/P3ePLMYs2RVChkJx/arcgis/rest/services/MERIT_Rivers_v1/MapServer/tile/{z}/{y}/{x}"],attribution:"© MERIT-Basins",maxzoom:12}},wn=0;function ki(c){if(!Array.isArray(c))return null;if(c.length===4){let a=c.map(Number);return a.every(Number.isFinite)?[[a[0],a[1]],[a[2],a[3]]]:null}let e=Je(c);if(!e)return null;let t=e.flat().map(Number);return t.every(Number.isFinite)?[[t[0],t[1]],[t[2],t[3]]]:null}function Sn(c,e){return e?c?[[Math.min(c[0][0],e[0][0]),Math.min(c[0][1],e[0][1])],[Math.max(c[1][0],e[1][0]),Math.max(c[1][1],e[1][1])]]:e:c}function In(c){if(!Array.isArray(c))return[];let e=new Set,t=[];for(let a of c){let i=String(a||"").trim();!i||e.has(i)||(e.add(i),t.push(i))}return t}function Ai(c){return Le(c?.style?.fillOpacity??wn)}var Lt=class{constructor(e,t,a={}){this.container=e,this.metadataService=t,this.options=a,this.renderer=null,this.map=null,this.layerStates=new Map,this.groupStates=new Map,this.mainToTest=new Map,this.testToMain=new Map,this.overlayLayers=new Map,this.timelineTransitionOverlay=null,this.timelineTransitionOverlayHandlers=[],this.hoveredTimelineTransitionId=null,this.lastTimelineTransitionInteractionAt=0,this._rememberedOrder=[],this.addressMarker=null,this.onFeatureClick=null,this.resizeFrame=0,this.lastResizeSize=null}init(e=this.container){return this.renderer=new It(e,{onSelection:t=>this.handleSelection(t),shouldSuppressLayerInteraction:t=>this.isTimelineTransitionEventAtPoint(t),onChange:()=>this.options.onChange?.(this),onMetric:t=>this.options.onMetric?.(t),onFallback:t=>this.options.onFallback?.(t)}),this.renderer.init(),this.map=this.renderer.map,this.map.invalidateSize=()=>this.invalidateSize(),this.installMainStyleMapControls(),this.applyMobileTouchContract(),this}applyMobileTouchContract(){this.renderer?.applyMobileTouchContract?.()}getMobileGestureDiagnostics(){return this.renderer?.getMobileGestureDiagnostics?.()||null}installMainStyleMapControls(){let e=this.map,t=e?.getContainer?.();if(!e||!t||t.querySelector(".test2-main-control-stack"))return;t.querySelectorAll([".maplibregl-ctrl-top-left .maplibregl-ctrl-group",".maplibregl-ctrl-top-right .maplibregl-ctrl-group",".maplibregl-ctrl-bottom-left .maplibregl-ctrl-group",".maplibregl-ctrl-bottom-right .maplibregl-ctrl-group",".maplibregl-ctrl-scale"].join(",")).forEach(o=>o.remove());let a=document.createElement("div");a.className="test2-main-control-stack",a.setAttribute("aria-label","Map controls");let i=document.createElement("div");i.className="leaflet-control leaflet-bar leaflet-control-zoom test2-main-zoom-control",i.setAttribute("aria-label","Zoom controls"),i.innerHTML=` +}`;function nn(c,e){return/^https?:/i.test(e)?e:c.replace(/[^/]*$/,"")+e}function ia(c,e,t,a){let i=c.transform?pi(e,c.transform):e,s=c.boundingVolume.box,n=[s[0],s[1],s[2]],r=[s[3],s[4],s[5]],o=[s[6],s[7],s[8]],l=[s[9],s[10],s[11]],d=ta(i,n[0],n[1],n[2]),h=ea(d[0],d[1],d[2]),u=[];for(let E of[[1,0,0],[0,1,0],[0,0,1]]){let C=ta(i,n[0]+E[0],n[1]+E[1],n[2]+E[2]),T=ea(C[0],C[1],C[2]);u.push([T[0]-h[0],T[1]-h[1],T[2]-h[2]])}let p=[-(u[0][0]*n[0]+u[1][0]*n[1]+u[2][0]*n[2]),-(u[0][1]*n[0]+u[1][1]*n[1]+u[2][1]*n[2]),-(u[0][2]*n[0]+u[1][2]*n[1]+u[2][2]*n[2])],f=[u[0][0],u[0][1],u[0][2],0,u[1][0],u[1][1],u[1][2],0,u[2][0],u[2][1],u[2][2],0,p[0],p[1],p[2],1],g=[];for(let E=-1;E<=1;E+=2)for(let C=-1;C<=1;C+=2)for(let T=-1;T<=1;T+=2){let z=n[0]+E*r[0]+C*o[0]+T*l[0],O=n[1]+E*r[1]+C*o[1]+T*l[1],I=n[2]+E*r[2]+C*o[2]+T*l[2],x=ta(i,z,O,I);g.push(ea(x[0],x[1],x[2]))}let y=c.content||c.contents?.[0],b=y&&(y.uri||y.url),v=b?nn(t,b):null,w=!!v&&/\.pnts(\?|$)/i.test(v),S=!!v&&/\.json(\?|$)/i.test(v);return{world:i,box:s,ref:h,affine:f,corners:g,geometricError:c.geometricError??0,refine:(c.refine||a||"REPLACE").toUpperCase(),baseUrl:t,contentUri:w?v:null,externalUri:S?v:null,rawChildren:c.children||null,children:null,resolving:!1,state:"unloaded",buf:null,colBuf:null,count:0,lastFrame:0}}function mi(c,e,t={}){return{id:c,type:"custom",renderingMode:"3d",_pointSize:t.pointSize??1.6,_opacity:t.opacity??1,_errK:t.errorFactor??1.5,_maxPoints:t.maxPoints??22e6,_maxConcurrent:24,_evictGrace:300,_mzMin:0,_mzMax:1,_root:null,_frame:0,_loadedPoints:0,_inflight:0,_queue:[],_loadedNodes:new Set,_visitBudget:0,_resolving:0,_maxResolving:24,_maxVisitsPerFrame:4e4,_edlEnabled:t.edl??!0,_edlStrength:t.edlStrength??2e3,_edlRadius:t.edlRadius??3,_edlK:t.edlK??.001,_fillIters:t.fillIters??8,_fillRadius:t.fillRadius??1.5,_fillDepthThresh:t.fillDepthThresh??.03,_fillMinZoom:t.fillMinZoom??16.5,_normalStr:t.normalStr??6,_ambient:t.ambient??.6,_diffuse:t.diffuse??.5,_lightDir:t.lightDir??[-.4,.6,.8],_superScale:t.superScale??1,_edl:null,onAdd(a,i){this._map=a;let s=i.createProgram();if(i.attachShader(s,St(i,i.VERTEX_SHADER,Xs)),i.attachShader(s,St(i,i.FRAGMENT_SHADER,Js)),i.linkProgram(s),!i.getProgramParameter(s,i.LINK_STATUS))throw new Error("pc link: "+i.getProgramInfoLog(s));if(this._prog=s,this._loc={a_pos:i.getAttribLocation(s,"a_pos"),a_color:i.getAttribLocation(s,"a_color"),u_matrix:i.getUniformLocation(s,"u_matrix"),u_size:i.getUniformLocation(s,"u_size"),u_opacity:i.getUniformLocation(s,"u_opacity")},typeof a.setMaxPitch=="function"&&a.getMaxPitch()<80&&a.setMaxPitch(85),this._edlEnabled)try{this._initEDL(i)}catch(n){this._edl=null,console.warn("[pc-stream] EDL unavailable, using direct render",n)}fetch(e).then(n=>n.json()).then(n=>{let r=e.split("?")[0];this._root=ia(n.root,Ys,r,"REPLACE");let o=1/0,l=-1/0;for(let d of this._root.corners)d[2]l&&(l=d[2]);l>o&&(this._mzMin=o,this._mzMax=l),this._map?.triggerRepaint()}).catch(n=>console.error("[pc-stream] tileset load failed",c,n))},_resolveChildren(a){if(a.children||a.resolving||a.externalUri&&this._resolving>=this._maxResolving)return;a.resolving=!0,a.externalUri&&this._resolving++;let i=s=>{let n=[];if(s&&n.push(ia(s,a.world,a._extBase||a.baseUrl,a.refine)),a.rawChildren)for(let r of a.rawChildren)n.push(ia(r,a.world,a.baseUrl,a.refine));a.children=n,a.resolving=!1,this._map?.triggerRepaint()};a.externalUri?fetch(a.externalUri).then(s=>s.json()).then(s=>{a._extBase=a.externalUri.split("?")[0],i(s.root)}).catch(s=>{a.children=[],a.resolving=!1}).finally(()=>{this._resolving--}):i(null)},_enqueue(a){a.state==="unloaded"&&(a.state="queued",this._queue.push(a))},_pump(a){if(!this._queue.length)return;this._queue.sort((s,n)=>n.lastFrame-s.lastFrame||n.geometricError-s.geometricError);let i=this._frame-120;for(;this._inflightn.arrayBuffer()).then(n=>{this._upload(a,s,n)}).catch(()=>{s.state="unloaded"}).finally(()=>{this._inflight--,this._map?.triggerRepaint()})}}},_upload(a,i,s){let r=new DataView(s).getUint32(12,!0),o=JSON.parse(new TextDecoder().decode(new Uint8Array(s,28,r))),l=o.POINTS_LENGTH|0,d=28+r,h=d+(o.POSITION?.byteOffset??0),u=new Float32Array(s.slice(h,h+l*12)),p=new Float32Array(l*3),f=!1;if(o.RGB){let g=d+o.RGB.byteOffset,y=new Uint8Array(s,g,l*3),b=0;for(let v=0;vb&&(b=y[v],b>=8));v++);if(b>=8){f=!0;for(let v=0;vthis._maxPoints*2?this._frame:this._frame-this._evictGrace,n=[...this._loadedNodes].filter(r=>r.lastFramer.lastFrame-o.lastFrame);for(let r of n){if(this._loadedPoints<=this._maxPoints*.85)break;a.deleteBuffer(r.buf),a.deleteBuffer(r.colBuf),this._loadedPoints-=r.count,r.buf=r.colBuf=null,r.count=0,r.state="unloaded",this._loadedNodes.delete(r)}},_culled(a,i){let s=0,n=0,r=0,o=0,l=0;for(let h of a.corners){let u=i[0]*h[0]+i[4]*h[1]+i[8]*h[2]+i[12],p=i[1]*h[0]+i[5]*h[1]+i[9]*h[2]+i[13],f=i[3]*h[0]+i[7]*h[1]+i[11]*h[2]+i[15];if(f<=0){l++;continue}let g=u/f,y=p/f;g<-1&&s++,g>1&&n++,y<-1&&r++,y>1&&o++}let d=a.corners.length;return s===d||n===d||r===d||o===d||l===d},_selectVisit(a,i,s,n,r){if(this._visitBudget--<=0){i.contentUri&&i.state==="loaded"&&r.push(i);return}if(i.lastFrame=this._frame,!(i.geometricError>n)){if(i.contentUri)i.state==="loaded"?r.push(i):this._enqueue(i);else if(i.children||i.externalUri||i.rawChildren)if(!i.children)this._resolveChildren(i);else for(let d of i.children)this._culled(d,s)||this._selectVisit(a,d,s,n,r);return}if(!i.children){this._resolveChildren(i),i.contentUri&&(i.state==="loaded"?r.push(i):this._enqueue(i));return}let l=!1;for(let d of i.children){if(this._culled(d,s))continue;let h=r.length;this._selectVisit(a,d,s,n,r),r.length===h&&(d.contentUri||d.externalUri||d.rawChildren)&&(l=!0)}(i.refine==="ADD"||l)&&i.contentUri&&(i.state==="loaded"?r.push(i):this._enqueue(i))},render(a,i){if(!this._root||!this._prog)return;let s=Array.isArray(i)?i:i?.defaultProjectionData?.mainMatrix||i?.mainMatrix||i;if(!s||s.length!==16)return;this._frame++;let n=this._map.getCenter().lat,r=this._map.getZoom(),l=hi*Math.cos(n*ct)/(512*Math.pow(2,r))*this._errK,d=[];if(this._visitBudget=this._maxVisitsPerFrame,this._culled(this._root,s)||this._selectVisit(a,this._root,s,l,d),this._pump(a),this._evict(a),this._edl&&d.length)try{this._renderEDL(a,s,d)}catch(h){console.warn("[pc-stream] EDL render failed, falling back to direct",h),this._edl=null,this._renderDirect(a,s,d)}else this._renderDirect(a,s,d);(this._queue.length||this._inflight)&&this._map?.triggerRepaint()},_nodeMatrix(a,i){let s=i.ref[0],n=i.ref[1],r=i.ref[2],o=a.slice();return o[12]=a[0]*s+a[4]*n+a[8]*r+a[12],o[13]=a[1]*s+a[5]*n+a[9]*r+a[13],o[14]=a[2]*s+a[6]*n+a[10]*r+a[14],o[15]=a[3]*s+a[7]*n+a[11]*r+a[15],new Float32Array(pi(o,i.affine))},_renderDirect(a,i,s){a.useProgram(this._prog),a.uniform1f(this._loc.u_size,this._pointSize*(window.devicePixelRatio||1)),a.uniform1f(this._loc.u_opacity,this._opacity||1),a.enable(a.DEPTH_TEST),a.depthFunc(a.LEQUAL);for(let n of s)a.uniformMatrix4fv(this._loc.u_matrix,!1,this._nodeMatrix(i,n)),a.bindBuffer(a.ARRAY_BUFFER,n.buf),a.enableVertexAttribArray(this._loc.a_pos),a.vertexAttribPointer(this._loc.a_pos,3,a.FLOAT,!1,0,0),a.bindBuffer(a.ARRAY_BUFFER,n.colBuf),a.enableVertexAttribArray(this._loc.a_color),a.vertexAttribPointer(this._loc.a_color,3,a.FLOAT,!1,0,0),a.drawArrays(a.POINTS,0,n.count)},_initEDL(a){if(!(typeof WebGL2RenderingContext<"u"&&a instanceof WebGL2RenderingContext)){this._edl=null;return}let s=aa(a,en,tn),n=aa(a,ui,an),r=aa(a,ui,sn),o=(d,...h)=>{let u={};for(let p of h)u[p]=a.getUniformLocation(d,p);return u},l=d=>({fbo:a.createFramebuffer(),col:a.createTexture(),dep:a.createTexture(),rb:d?a.createRenderbuffer():null});this._edl={gbufProg:s,fillProg:n,shadeProg:r,gLoc:{a_pos:a.getAttribLocation(s,"a_pos"),a_color:a.getAttribLocation(s,"a_color"),...o(s,"u_matrix","u_size","u_k")},fLoc:o(n,"u_color","u_depth","u_texel","u_radius","u_depthThresh"),sLoc:o(r,"u_color","u_depth","u_texel","u_opacity","u_edlStrength","u_edlRadius","u_normalStr","u_lightDir","u_ambient","u_diffuse"),gbuf:l(!0),pp0:l(!1),pp1:l(!1),vao:a.createVertexArray(),w:0,h:0}},_sizeTarget(a,i,s,n,r){for(let o of[i.col,i.dep])a.bindTexture(a.TEXTURE_2D,o),a.texImage2D(a.TEXTURE_2D,0,a.RGBA8,s,n,0,a.RGBA,a.UNSIGNED_BYTE,null),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MIN_FILTER,a.NEAREST),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MAG_FILTER,a.NEAREST),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_WRAP_S,a.CLAMP_TO_EDGE),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_WRAP_T,a.CLAMP_TO_EDGE);a.bindFramebuffer(a.FRAMEBUFFER,i.fbo),a.framebufferTexture2D(a.FRAMEBUFFER,a.COLOR_ATTACHMENT0,a.TEXTURE_2D,i.col,0),a.framebufferTexture2D(a.FRAMEBUFFER,a.COLOR_ATTACHMENT1,a.TEXTURE_2D,i.dep,0),r&&(a.bindRenderbuffer(a.RENDERBUFFER,i.rb),a.renderbufferStorage(a.RENDERBUFFER,a.DEPTH_COMPONENT16,s,n),a.framebufferRenderbuffer(a.FRAMEBUFFER,a.DEPTH_ATTACHMENT,a.RENDERBUFFER,i.rb))},_ensureEdlSize(a,i,s){let n=this._edl;n.w===i&&n.h===s||(n.w=i,n.h=s,this._sizeTarget(a,n.gbuf,i,s,!0),this._sizeTarget(a,n.pp0,i,s,!1),this._sizeTarget(a,n.pp1,i,s,!1),a.bindFramebuffer(a.FRAMEBUFFER,null),a.bindTexture(a.TEXTURE_2D,null),a.bindRenderbuffer(a.RENDERBUFFER,null))},_renderEDL(a,i,s){let n=this._edl,r=Math.max(1,this._superScale),o=Math.round(a.drawingBufferWidth*r),l=Math.round(a.drawingBufferHeight*r);this._ensureEdlSize(a,o,l);let d=[a.COLOR_ATTACHMENT0,a.COLOR_ATTACHMENT1],h=window.devicePixelRatio||1,u={fbo:a.getParameter(a.FRAMEBUFFER_BINDING),vp:a.getParameter(a.VIEWPORT),vao:a.getParameter(a.VERTEX_ARRAY_BINDING),prog:a.getParameter(a.CURRENT_PROGRAM),arr:a.getParameter(a.ARRAY_BUFFER_BINDING),actTex:a.getParameter(a.ACTIVE_TEXTURE),blend:a.isEnabled(a.BLEND),bsrc:a.getParameter(a.BLEND_SRC_RGB),bdst:a.getParameter(a.BLEND_DST_RGB),dtest:a.isEnabled(a.DEPTH_TEST),dmask:a.getParameter(a.DEPTH_WRITEMASK),dfunc:a.getParameter(a.DEPTH_FUNC)};a.bindVertexArray(n.vao),a.bindFramebuffer(a.FRAMEBUFFER,n.gbuf.fbo),a.drawBuffers(d),a.viewport(0,0,o,l),a.disable(a.BLEND),a.enable(a.DEPTH_TEST),a.depthMask(!0),a.depthFunc(a.LEQUAL),a.clearColor(0,0,0,0),a.clear(a.COLOR_BUFFER_BIT|a.DEPTH_BUFFER_BIT),a.useProgram(n.gbufProg),a.uniform1f(n.gLoc.u_size,this._pointSize*h*r),a.uniform1f(n.gLoc.u_k,this._edlK);for(let b of s)a.uniformMatrix4fv(n.gLoc.u_matrix,!1,this._nodeMatrix(i,b)),a.bindBuffer(a.ARRAY_BUFFER,b.buf),a.enableVertexAttribArray(n.gLoc.a_pos),a.vertexAttribPointer(n.gLoc.a_pos,3,a.FLOAT,!1,0,0),a.bindBuffer(a.ARRAY_BUFFER,b.colBuf),a.enableVertexAttribArray(n.gLoc.a_color),a.vertexAttribPointer(n.gLoc.a_color,3,a.FLOAT,!1,0,0),a.drawArrays(a.POINTS,0,b.count);a.disable(a.DEPTH_TEST),a.depthMask(!1),a.disable(a.BLEND);let p=this._map.getZoom(),f=p>=this._fillMinZoom?Math.max(2,Math.min(this._fillIters,Math.round(2+(p-this._fillMinZoom)*1.5))):0,g=n.gbuf.col,y=n.gbuf.dep;for(let b=0;b["get",t]),""])}function vi(c){let e=oa(c),t=e.length>0?["any",...e.map(i=>["has",i])]:!0,a=wa(c);return a?["any",t,a]:t}function Lt(c,e){let t=dt(c),a=ne(e,50,200)/100;return t.fontSize*a}function _i(c){return["*",-1,["to-number",["get",c.labelRankProperty||"label_rank"],0]]}function Ct(c,e){let t=Ge(c,e||{});for(let a of oa(c)){let i=rn(t?.[a],c.labelCleanup);if(i)return i}return""}function rn(c,e){if(c==null)return"";let t=String(c).trim();if(!t)return"";if(e==="stripTrailingBracketNumber")return t.replace(/\s*\([^()]*\)\s*$/,"").trim();if(e&&typeof e=="object"&&e.type==="mapValues"){let a=e.map?.[t];if(typeof a=="string"&&a.trim())return a.trim()}return t}var Xe="#FDBA74",Je="#FF7A1A",on=0,ln=60,cn=10,dn=new Set(["pmtiles","vector","mvt"]);var un=["button","a","input","select","textarea",'[contenteditable="true"]',".maplibregl-ctrl",".test2-main-zoom-control",".active-layers-toggle",".map-controls",".map-control-panel",".active-layers",".feature-info",".test2-source-panel",".test2-election-pane-resizer","#timelineSlider"].join(","),Tt=Object.freeze({type:"FeatureCollection",features:[]});function ze(c){return!!c?.closest?.(un)}function wi(c){if(!c?.touches||c.touches.length<2)return null;let e=c.touches[0],t=c.touches[1];return!e||!t?null:[{x:e.clientX,y:e.clientY},{x:t.clientX,y:t.clientY}]}function Si(c){return{x:(c[0].x+c[1].x)/2,y:(c[0].y+c[1].y)/2}}function Ii(c){return Math.hypot(c[1].x-c[0].x,c[1].y-c[0].y)}function Li(c){return Math.atan2(c[1].y-c[0].y,c[1].x-c[0].x)}function hn(c){return c*180/Math.PI}function Ci(c){let e=c;for(;e>180;)e-=360;for(;e<-180;)e+=360;return e}function pn(c){return typeof c=="string"&&c.startsWith("/render/tiles/")}function mn(){let c=globalThis.location?.hostname||"";return globalThis.__civgraphUseLocalTileFallback===!0&&(c==="localhost"||c==="127.0.0.1"||c==="::1")}function fn(c){let e=Number(c?.maxDomLabels);if(Number.isFinite(e)&&e>0)return e;let t=Number(globalThis.innerWidth||1024),a=Number(globalThis.navigator?.deviceMemory||4);return t<700||a<=2?90:t<1100||a<=4?180:320}function gn(){let c=Number(globalThis.innerWidth||1024),e=Number(globalThis.navigator?.deviceMemory||4),t=Number(globalThis.navigator?.hardwareConcurrency||4),a=Number(globalThis.devicePixelRatio||1),i=!!globalThis.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches,s=c<700||e<=2||t<=2,n=!s&&(c<1100||e<=4||t<=4),r=s?1:Math.max(1,Math.min(3,t-1));return{deviceClass:s?"low":n?"medium":"high",workerCount:r,maxTileCacheSize:s?80:n?140:260,maxParallelImageRequests:s?8:n?12:16,fadeDuration:s||i?0:100,pixelRatio:s?Math.min(a,1.5):Math.min(a,2),reducedMotion:i}}function Ai(c){return ne(c?.style?.fillOpacity??on,0,1)}function Ti(c){return c?.sourceType==="raster"||c?.sourceType==="image"?ne(c.rasterOpacity??c.style?.opacity??.85,0,1):Ai(c)}var xt=class{constructor(e,t={}){this.container=e,this.options=t,this.map=null,this.maplibreVersion=$e.default.version,this.protocol=new Za({metadata:!0}),this.layers=new Map,this.selected=null,this.hovered=null,this.metrics=[],this.fallbackLayers=new Map,this.interactionCleanups=new Map,this.fallbackCleanups=new Map,this.duplicateFeatureIdCache=new Map,this.pmtilesArchiveCache=new Map,this.runtimeProfile=gn(),this.mobileGestureGuardInstalled=!1,this.mobileGestureGuardTargetCount=0,this.mobileGestureResizeObserver=null,this.mobileGestureResizeFrame=0,this.mobileGestureResizeSize=null,this.mobileGestureResizeObserverEligible=!1,this.directGestureActive=!1,this.directPanGestureInstalled=!1,this.directPanGestureState=null,this.directPanFrame=0,this.directPanPendingCenter=null,this.directPanPendingDelta=null,this.directPanFallbackActivations=0,this.directWheelGestureInstalled=!1,this.directWheelFrame=0,this.directWheelPendingZoom=null,this.directWheelEndTimer=0,this.directWheelFallbackActive=!1,this.directWheelFallbackActivations=0,this.directTwoFingerGestureInstalled=!1,this.directTwoFingerGestureState=null,this.directTwoFingerGestureFrame=0,this.directTwoFingerGesturePending=null,this.directTwoFingerFallbackActivations=0,this.mapCursor="",this.cursorMutationCount=0,this.documentHoverClearInstalled=!1,this.documentHoverClearHandler=null,$e.default.addProtocol("pmtiles",this.protocol.tile)}init(){Number.isFinite(this.runtimeProfile.workerCount)&&($e.default.workerCount=this.runtimeProfile.workerCount),Number.isFinite(this.runtimeProfile.maxParallelImageRequests)&&($e.default.maxParallelImageRequests=this.runtimeProfile.maxParallelImageRequests),this.map=new $e.default.Map({container:this.container,style:{version:8,sources:{osm:{type:"raster",tiles:["https://tile.openstreetmap.org/{z}/{x}/{y}.png"],tileSize:256,attribution:"© OpenStreetMap contributors"}},layers:[{id:"osm",type:"raster",source:"osm"}]},center:[-8.05,53.4],zoom:5.8,minZoom:4,maxZoom:22,attributionControl:!0,fadeDuration:this.runtimeProfile.fadeDuration,maxTileCacheSize:this.runtimeProfile.maxTileCacheSize,pixelRatio:this.runtimeProfile.pixelRatio,refreshExpiredTiles:!1,renderWorldCopies:!1,interactive:!0,dragRotate:!0,dragPan:!0,touchZoomRotate:!0,touchPitch:!0,pitchWithRotate:!0,scrollZoom:!0,cooperativeGestures:!1}),this.recordMetric({event:"runtime-profile",profile:this.runtimeProfile}),this.map.doubleClickZoom?.disable(),this.enableGestureHandlers(),this.installMobileGestureGuards(),this.installDirectPanGestureFallback(),this.installDirectWheelGestureFallback(),this.installDirectTwoFingerGestureFallback(),this.installDocumentHoverClear(),this.applyMobileTouchContract(),this.map.on("load",()=>{this.enableGestureHandlers(),this.applyMobileTouchContract()}),this.map.on("styledata",()=>{this.enableGestureHandlers(),this.applyMobileTouchContract()}),this.map.addControl(new $e.default.NavigationControl({visualizePitch:!0}),"top-left"),this.map.addControl(new $e.default.ScaleControl({unit:"metric"}),"bottom-right"),this.map.on("moveend",()=>{this.directGestureActive||this.notifyChange()}),this.map.on("idle",()=>{this.directGestureActive||this.notifyChange()}),this.map.fitBounds($a,{padding:28,duration:0})}installDocumentHoverClear(){this.documentHoverClearInstalled||(this.documentHoverClearInstalled=!0,this.documentHoverClearHandler=e=>{if(!this.hovered||!this.map)return;let t=e.target,a=this.map.getContainer?.();if(!a)return;let i=a.contains(t),s=i&&!t?.closest?.([".maplibre-dom-label",".test2-election-seat-group",".maplibregl-canvas",".maplibregl-canvas-container"].join(","));i&&!ze(t)&&!s||this.clearHover()},document.addEventListener("pointerdown",this.documentHoverClearHandler,!0))}readCameraState(){if(!this.map)return null;let e=this.map.getCenter();return{lng:e.lng,lat:e.lat,zoom:this.map.getZoom(),pitch:this.map.getPitch(),bearing:this.map.getBearing()}}cameraMovedSince(e,t={}){if(!e||!this.map)return!1;let a=this.readCameraState();if(!a)return!1;let i=t.lng??1e-6,s=t.lat??1e-6,n=t.zoom??5e-4,r=t.pitch??.05,o=t.bearing??.05;return Math.abs(a.lng-e.lng)>i||Math.abs(a.lat-e.lat)>s||Math.abs(a.zoom-e.zoom)>n||Math.abs(a.pitch-e.pitch)>r||Math.abs(Ci(a.bearing-e.bearing))>o}resetDirectPanGestureState(e=null,t=null){this.directPanFrame&&(cancelAnimationFrame(this.directPanFrame),this.directPanFrame=0),this.directPanPendingCenter=null,this.directPanPendingDelta=null;let a=this.directPanGestureState;if(a){a.nativeCheckFrame&&(cancelAnimationFrame(a.nativeCheckFrame),a.nativeCheckFrame=0);let i=e||a.target||this.map?.getContainer?.(),s=t??a.pointerId;try{i?.hasPointerCapture?.(s)&&i.releasePointerCapture(s)}catch{}}this.directPanGestureState=null}enableGestureHandlers(){this.map&&(this.map.dragPan?.enable?.(),this.map.dragRotate?.enable?.(),this.map.touchZoomRotate?.enable?.(),this.map.touchZoomRotate?.enableRotation?.(),this.map.touchPitch?.enable?.(),this.map.scrollZoom?.enable?.(),this.map.keyboard?.enable?.(),this.applyMobileTouchContract())}setMapCursor(e=""){let t=e||"",a=this.map?.getCanvas?.();this.mapCursor===t&&(!a||a.style.cursor===t)||(this.mapCursor=t,a&&a.style.cursor!==t&&(a.style.cursor=t,this.cursorMutationCount+=1))}installMobileGestureGuards(){if(!this.map||this.mobileGestureGuardInstalled)return;let e=this.map.getContainer?.();if(!e?.addEventListener)return;this.mobileGestureGuardInstalled=!0;let t=r=>{ze(r.target)||r.cancelable&&r.preventDefault()},a=r=>{ze(r.target)||this.applyMobileTouchContract()},i=new Set([e,this.map.getCanvasContainer?.()].filter(Boolean)),s={passive:!1},n={passive:!0};for(let r of i)r.addEventListener("touchstart",a,n),r.addEventListener("gesturestart",t,s),r.addEventListener("gesturechange",t,s),r.addEventListener("gestureend",t,s);this.mobileGestureGuardTargetCount=i.size,this.installMobileGestureResizeObserver(e)}installDirectPanGestureFallback(){if(!this.map||this.directPanGestureInstalled)return;let e=this.map.getContainer?.();if(!e?.addEventListener)return;this.directPanGestureInstalled=!0;let t={touch:{distance:24,elapsedMs:120,samples:3},mouse:{distance:14,elapsedMs:48,samples:2},pen:{distance:18,elapsedMs:80,samples:2},default:{distance:18,elapsedMs:80,samples:2}},a={passive:!1},i=()=>{this.directPanFrame=0;let u=this.directPanPendingDelta;this.directPanPendingDelta=null;let p=this.directPanPendingCenter;if(this.directPanPendingCenter=null,!!this.map){if(u){let f=this.map.project(this.map.getCenter()),g=this.map.unproject([f.x-u.dx,f.y-u.dy]);this.map.jumpTo({center:g});return}p&&this.map.jumpTo({center:p})}},s=(u,p)=>{if(!Number.isFinite(u)||!Number.isFinite(p)||u===0&&p===0)return;let f=this.directPanPendingDelta||{dx:0,dy:0};f.dx+=u,f.dy+=p,this.directPanPendingDelta=f,this.directPanPendingCenter=null,!this.directPanFrame&&(this.directPanFrame=requestAnimationFrame(i))},n=()=>{this.directPanFrame&&(cancelAnimationFrame(this.directPanFrame),this.directPanFrame=0),i()},r=u=>{let p=t[u.pointerType]||t.default,f=performance.now()-u.startedAt;return Math.hypot(u.latestDx,u.latestDy)>=p.distance&&u.noCameraSamples>=p.samples&&f>=p.elapsedMs},o=u=>{u.nativeCheckFrame||u.fallbackActive||u.nativeMoved||(u.nativeCheckFrame=requestAnimationFrame(()=>{if(u.nativeCheckFrame=0,!(this.directPanGestureState!==u||u.cancelled||u.fallbackActive||u.nativeMoved)){if(this.cameraMovedSince(u.camera,{lng:5e-6,lat:5e-6})){u.nativeMoved=!0;return}r(u)&&(u.fallbackActive=!0,u.moved=!0,this.directPanFallbackActivations+=1,this.directGestureActive=!0,s(u.latestDx,u.latestDy),u.lastX=u.latestX,u.lastY=u.latestY)}}))},l=u=>{if(ze(u.target)||u.button!==void 0&&u.button!==0)return;if(this.directPanGestureState&&u.pointerType==="touch"){this.directPanGestureState.cancelled=!0;return}if(this.directPanGestureState||u.isPrimary===!1)return;let p=this.map.getCenter();this.directPanGestureState={pointerId:u.pointerId,pointerType:u.pointerType||"mouse",startX:u.clientX,startY:u.clientY,lastX:u.clientX,lastY:u.clientY,latestX:u.clientX,latestY:u.clientY,center:p,camera:this.readCameraState(),startedAt:performance.now(),latestDx:0,latestDy:0,noCameraSamples:0,moved:!1,fallbackActive:!1,nativeMoved:!1,nativeCheckFrame:0,cancelled:!1,captured:!1,target:u.currentTarget||e}},d=u=>{let p=this.directPanGestureState;if(!p||p.cancelled||u.pointerId!==p.pointerId)return;let f=u.clientX-p.startX,g=u.clientY-p.startY;if(p.latestX=u.clientX,p.latestY=u.clientY,p.latestDx=f,p.latestDy=g,!p.fallbackActive&&this.cameraMovedSince(p.camera,{lng:5e-6,lat:5e-6})){p.nativeMoved=!0;return}if(!p.fallbackActive){let v=t[p.pointerType]||t.default;if(Math.hypot(f,g){let p=this.directPanGestureState;!p||u?.pointerId!==void 0&&u.pointerId!==p.pointerId||(p.nativeCheckFrame&&(cancelAnimationFrame(p.nativeCheckFrame),p.nativeCheckFrame=0),(p.fallbackActive||p.moved)&&(n(),p.fallbackActive&&(u?.cancelable&&u.preventDefault(),u?.stopPropagation?.()),this.directGestureActive=!1,this.notifyChange()),this.resetDirectPanGestureState(u?.currentTarget||e,p.pointerId))};e.addEventListener("pointerdown",l,a),e.addEventListener("pointermove",d,a),e.addEventListener("pointerup",h,a),e.addEventListener("pointercancel",h,a),e.addEventListener("lostpointercapture",h,a),document.addEventListener("pointerup",h,a),document.addEventListener("pointercancel",h,a)}installDirectWheelGestureFallback(){if(!this.map||this.directWheelGestureInstalled)return;let e=this.map.getContainer?.();if(!e?.addEventListener)return;this.directWheelGestureInstalled=!0;let t=()=>{this.directWheelFrame=0;let n=this.directWheelPendingZoom;this.directWheelPendingZoom=null,!(!Number.isFinite(n)||!this.map)&&this.map.jumpTo({zoom:n})},a=()=>{this.directWheelEndTimer&&clearTimeout(this.directWheelEndTimer),this.directWheelEndTimer=setTimeout(()=>{this.directWheelEndTimer=0,this.directWheelFallbackActive=!1,this.directGestureActive=!1,this.notifyChange()},140)},i=(n,r)=>{requestAnimationFrame(()=>{!this.map||this.cameraMovedSince(r,{zoom:.001})||(this.directWheelFallbackActive||(this.directWheelFallbackActive=!0,this.directWheelFallbackActivations+=1),this.directWheelPendingZoom=n,this.directGestureActive=!0,this.directWheelFrame||(this.directWheelFrame=requestAnimationFrame(t)),a())})},s=n=>{if(ze(n.target))return;let r=n.deltaMode===1?40:n.deltaMode===2?Math.max(1,globalThis.innerHeight||800):1,o=Number(n.deltaY||0)*r;if(!Number.isFinite(o)||o===0)return;let l=typeof this.map.getMinZoom=="function"?this.map.getMinZoom():0,d=typeof this.map.getMaxZoom=="function"?this.map.getMaxZoom():22,h=Number.isFinite(this.directWheelPendingZoom)?this.directWheelPendingZoom:this.map.getZoom(),u=ne(h-o/450,l,d);if(!this.directWheelFallbackActive){i(u,this.readCameraState());return}this.directWheelPendingZoom=u,this.directGestureActive=!0,this.directWheelFrame||(this.directWheelFrame=requestAnimationFrame(t)),a(),n.cancelable&&n.preventDefault(),n.stopPropagation()};e.addEventListener("wheel",s,{passive:!1})}installDirectTwoFingerGestureFallback(){if(!this.map||this.directTwoFingerGestureInstalled)return;let e=this.map.getContainer?.();if(!e?.addEventListener)return;this.directTwoFingerGestureInstalled=!0;let t={passive:!1},a=u=>{u.cancelable&&u.preventDefault(),u.stopPropagation()},i=()=>{this.directTwoFingerGestureFrame=0;let u=this.directTwoFingerGesturePending;this.directTwoFingerGesturePending=null,!(!u||!this.map)&&this.map.jumpTo(u)},s=u=>{this.directTwoFingerGesturePending=u,!this.directTwoFingerGestureFrame&&(this.directTwoFingerGestureFrame=requestAnimationFrame(i))},n=()=>{this.directTwoFingerGestureFrame&&(cancelAnimationFrame(this.directTwoFingerGestureFrame),this.directTwoFingerGestureFrame=0),i()},r=(u,p)=>{let f=Ii(p);if(!u||!Number.isFinite(f)||f<=0)return null;let g=Si(p),y=this.map.project(u.center),b=typeof this.map.getMinZoom=="function"?this.map.getMinZoom():0,v=typeof this.map.getMaxZoom=="function"?this.map.getMaxZoom():22,w=f/u.distance,S=ne(u.zoom+Math.log2(Math.max(w,.01)),b,v),E=Ci(hn(Li(p)-u.angle)),C=u.bearing+E,T=ne(u.pitch-(g.y-u.midpoint.y)*.18,0,60);return{center:this.map.unproject([y.x-(g.x-u.midpoint.x),y.y-(g.y-u.midpoint.y)]),zoom:S,bearing:C,pitch:T}},o=u=>{u.nativeCheckFrame||u.fallbackActive||u.nativeMoved||(u.nativeCheckFrame=requestAnimationFrame(()=>{if(u.nativeCheckFrame=0,this.directTwoFingerGestureState!==u||u.fallbackActive||u.nativeMoved)return;if(this.cameraMovedSince(u.camera)){u.nativeMoved=!0;return}let p=u.latestPoints?r(u,u.latestPoints):null;p&&(u.fallbackActive=!0,this.directTwoFingerFallbackActivations+=1,this.directGestureActive=!0,s(p))}))},l=u=>{if(ze(u.target))return!1;let p=wi(u);if(!p)return!1;let f=Ii(p);if(!Number.isFinite(f)||f<=0)return!1;this.resetDirectPanGestureState(e);let g=this.map.getCenter();return this.directTwoFingerGestureState={distance:f,midpoint:Si(p),angle:Li(p),center:g,zoom:this.map.getZoom(),pitch:this.map.getPitch(),bearing:this.map.getBearing(),camera:this.readCameraState(),latestPoints:p,nativeCheckFrame:0,fallbackActive:!1,nativeMoved:!1},!0},d=u=>{if(ze(u.target))return;let p=wi(u);if(!p||!this.directTwoFingerGestureState&&!l(u))return;let f=this.directTwoFingerGestureState;if(!f)return;if(f.latestPoints=p,!f.fallbackActive&&this.cameraMovedSince(f.camera)){f.nativeMoved=!0;return}if(!f.fallbackActive){o(f);return}let g=r(f,p);g&&(this.directGestureActive=!0,s(g),a(u))},h=u=>{if(!this.directTwoFingerGestureState||u.touches&&u.touches.length>=2)return;let p=this.directTwoFingerGestureState;p.nativeCheckFrame&&(cancelAnimationFrame(p.nativeCheckFrame),p.nativeCheckFrame=0),p.fallbackActive&&n(),this.directTwoFingerGestureState=null,this.resetDirectPanGestureState(e),this.enableGestureHandlers(),p.fallbackActive&&(this.directGestureActive=!1,this.notifyChange(),a(u))};e.addEventListener("touchstart",l,t),e.addEventListener("touchmove",d,t),e.addEventListener("touchend",h,t),e.addEventListener("touchcancel",h,t)}installMobileGestureResizeObserver(e){if(!this.map||this.mobileGestureResizeObserver||typeof ResizeObserver>"u")return;if(!this.shouldInstallMobileGestureResizeObserver()){this.mobileGestureResizeObserverEligible=!1;return}this.mobileGestureResizeObserverEligible=!0;let t=s=>{let n=Array.isArray(s?.borderBoxSize)?s.borderBoxSize[0]:s?.borderBoxSize,r=Number(n?.inlineSize),o=Number(n?.blockSize);if(Number.isFinite(r)&&Number.isFinite(o))return{width:r,height:o};let l=e.getBoundingClientRect?.();return l?{width:l.width,height:l.height}:null},a=s=>{let n=this.mobileGestureResizeSize;return this.mobileGestureResizeSize=s,n?Math.abs(s.width-n.width)>.5||Math.abs(s.height-n.height)>.5:!1},i=(s=[])=>{let n=t(s[0]);this.applyMobileTouchContract(),!(!n||!a(n))&&(this.mobileGestureResizeFrame||(this.mobileGestureResizeFrame=requestAnimationFrame(()=>{this.mobileGestureResizeFrame=0,this.applyMobileTouchContract(),this.map?.resize?.()})))};this.mobileGestureResizeObserver=new ResizeObserver(i),this.mobileGestureResizeObserver.observe(e)}shouldInstallMobileGestureResizeObserver(){let e=t=>{try{return!!globalThis.matchMedia?.(t)?.matches}catch{return!1}};return e("(pointer: coarse)")||e("(max-width: 768px)")}applyMobileTouchContract(){if(!this.map)return;let e=[document.getElementById(typeof this.container=="string"?this.container:""),this.map.getContainer?.(),this.map.getCanvasContainer?.(),this.map.getCanvas?.()].filter(Boolean);for(let a of new Set(e))a.style.touchAction="none",a.style.overscrollBehavior="contain",a.style.userSelect="none",a.style.webkitUserSelect="none",a.style.webkitTouchCallout="none",a.style.webkitOverflowScrolling="auto";let t=this.map.getCanvas?.();t&&(t.style.pointerEvents="auto")}getMobileGestureDiagnostics(){if(!this.map)return null;this.applyMobileTouchContract();let e=this.map.getCanvas?.(),t=this.map.getCanvasContainer?.(),a=this.map.getContainer?.(),i=e?.getBoundingClientRect?.(),s=i?i.left+i.width*.5:0,n=i?i.top+i.height*.5:0,r=i?document.elementFromPoint(s,n):null;return{topTag:r?.tagName||"",topClass:r?.className?String(r.className):"",topIsCanvas:r===e,topWithinMap:!!r?.closest?.("#map"),topWithinCanvasContainer:!!t?.contains?.(r),rootTouchAction:a?getComputedStyle(a).touchAction:"",canvasTouchAction:e?getComputedStyle(e).touchAction:"",canvasContainerTouchAction:t?getComputedStyle(t).touchAction:"",dragPanEnabled:typeof this.map.dragPan?.isEnabled=="function"?this.map.dragPan.isEnabled():!0,scrollZoomEnabled:typeof this.map.scrollZoom?.isEnabled=="function"?this.map.scrollZoom.isEnabled():!0,dragRotateEnabled:typeof this.map.dragRotate?.isEnabled=="function"?this.map.dragRotate.isEnabled():!0,touchZoomEnabled:typeof this.map.touchZoomRotate?.isEnabled=="function"?this.map.touchZoomRotate.isEnabled():!0,touchPitchEnabled:typeof this.map.touchPitch?.isEnabled=="function"?this.map.touchPitch.isEnabled():!0,guardTargetCount:this.mobileGestureGuardTargetCount||0,resizeObserverTargets:this.mobileGestureResizeObserver?1:0,resizeObserverMobileEligible:this.mobileGestureResizeObserverEligible,nativeGesturePrimary:!0,directPanFallbackMode:"emergency",directWheelFallbackMode:"emergency",directTwoFingerFallbackMode:"emergency",directPanGestureInstalled:this.directPanGestureInstalled,directWheelGestureInstalled:this.directWheelGestureInstalled,directTwoFingerGestureInstalled:this.directTwoFingerGestureInstalled,directPanFallbackActivations:this.directPanFallbackActivations,directWheelFallbackActivations:this.directWheelFallbackActivations,directTwoFingerFallbackActivations:this.directTwoFingerFallbackActivations,mapCursor:this.mapCursor,cursorMutationCount:this.cursorMutationCount}}async loadLayer(e){if(e.loadable===!1||e.sourceType==="unconverted")throw new Error(`${e.name} is not yet converted for the /test MapLibre renderer`);if(this.layers.has(e.id)){this.fitToLayer(e.id);return}let t=performance.now(),a=`${e.id}-source`,i=`${e.id}-fill`,s=`${e.id}-line`,n=`${e.id}-raster`,r=`${e.id}-hover`,o=`${e.id}-hover-line`,l=`${e.id}-selected-fill`,d=`${e.id}-selected`,h=`${e.id}-label`;await this.waitForMap();let u=await this.loadDuplicateFeatureIds(e),p={layerIds:[],sourceIds:[]};if(e.sourceType==="point-cloud")await this.addPointCloudLayer(e);else{let g=this.buildSource(e);this.map.addSource(a,g),e.sourceType==="raster-dem"?p=this.addTerrainLayer(e,{sourceId:a,rasterId:n}):e.sourceType==="raster"||e.sourceType==="image"?this.addRasterLayer(e,{sourceId:a,rasterId:n}):(this.addGeometryLayers(e,{sourceId:a,fillId:i,lineId:s,hoverId:r,selectedFillId:l,selectedId:d}),p=this.addInteractionOverlayLayers(e))}let f=this.addLabelLayers(e,{sourceId:a,labelId:h});this.layers.set(e.id,{config:e,sourceId:a,sourceIds:[a,...p.sourceIds],layerIds:[i,s,r,o,l,d,...p.layerIds,h,n].filter(g=>this.map.getLayer(g)),labelLayerIds:f,domLabelMarkers:new Map,domLabelsScheduled:0,duplicateFeatureIds:u,labelsEnabled:!0,textScale:yt,opacity:Ti(e),color:e.style?.color||"#5B21B6",fillColor:e.style?.fillColor||e.style?.color||"#7C3AED"}),this.applySavedLayerPreferences(e.id),e.sourceType!=="raster"&&e.sourceType!=="image"&&e.sourceType!=="raster-dem"&&e.sourceType!=="point-cloud"&&(this.interactionCleanups.set(e.id,this.bindLayerInteractions(e,i,h,a)),this.scheduleDomLabelRefresh(e.id)),e.sourceType==="pmtiles"&&this.fallbackCleanups.set(e.id,this.monitorPmtilesFallback(e,a)),this.reorderFromSavedLayerOrder(),this.scheduleAllDomLabelRefresh(),this.fitToLayer(e.id),this.recordMetric({layerId:e.id,layerName:e.name,event:"load",durationMs:Math.round(performance.now()-t),sourceType:e.sourceType}),this.notifyChange()}addRasterLayer(e,t){this.map.addLayer({id:t.rasterId,type:"raster",source:t.sourceId,paint:{"raster-opacity":ne(e.rasterOpacity??e.style?.opacity??.85,0,1)}})}addTerrainLayer(e,t){let{sourceId:a,rasterId:i}=t,s={layerIds:[],sourceIds:[]},n=ne(e.exaggeration??1.5,0,12);if(this.map.setTerrain({source:a,exaggeration:n}),this.terrainLayerId=e.id,this.terrainSourceId=a,this.terrainExaggeration=n,typeof this.map.setMaxPitch=="function"&&this.map.getMaxPitch()<80&&this.map.setMaxPitch(85),e.hillshadeTiles){let r=`${a}-hs`;this.map.addSource(r,{type:"raster",tiles:[st(e.hillshadeTiles)],tileSize:e.tileSize||256,minzoom:e.hillshadeMinzoom??e.minzoom,maxzoom:e.hillshadeMaxzoom??e.maxzoom,bounds:it(e.bounds)}),this.map.addLayer({id:i,type:"raster",source:r,paint:{"raster-opacity":ne(e.hillshadeOpacity??.5,0,1)}}),s.sourceIds.push(r),s.layerIds.push(i)}return s}setTerrainExaggeration(e){if(!this.terrainSourceId)return;let t=ne(e,0,12);this.terrainExaggeration=t,this.map.setTerrain({source:this.terrainSourceId,exaggeration:t})}addPointCloudLayer(e){if(this.pointCloudLayers||(this.pointCloudLayers=new Map),this.pointCloudLayers.has(e.id))return{layerIds:[`pointcloud-${e.id}`],sourceIds:[]};typeof this.map.setMaxPitch=="function"&&this.map.getMaxPitch()<80&&this.map.setMaxPitch(85);let t=`pointcloud-${e.id}`,a=String(e.tilesetUrl||""),i=this.layers.get(e.id),s=ne(i?.opacity??Ti(e),0,1),n;if(e.pcFlat){let r=a.split("?")[0].replace(/tileset\.json$/,"pc.json");n=ci(t,r+"?v="+(e.pcVersion||"pc2"),{pointSize:e.pointSize??2.5,opacity:s})}else n=mi(t,a,{pointSize:e.pointSize??1.6,opacity:s});return this.map.addLayer(n),this.pointCloudLayers.set(e.id,n),{layerIds:[`pointcloud-${e.id}`],sourceIds:[]}}removePointCloudLayer(e){let t=this.pointCloudLayers?.get(e);if(t){try{this.map.getLayer(t.id)&&this.map.removeLayer(t.id)}catch{}this.pointCloudLayers.delete(e)}}setPointSize(e,t){this.pointCloudLayers?.get(e)?.setPointSize(ne(Number(t)||2.5,.5,10))}addGeometryLayers(e,t){let{sourceId:a,fillId:i,lineId:s,hoverId:n,selectedFillId:r,selectedId:o}=t;if(e.geometryType!=="line"&&e.geometryType!=="point"&&this.map.addLayer({id:i,type:"fill",source:a,"source-layer":e.sourceLayer,paint:{"fill-color":e.style?.fillColor||e.style?.color||"#7C3AED","fill-opacity":Ai(e),"fill-antialias":!1}}),this.map.addLayer({id:s,type:e.geometryType==="point"?"circle":"line",source:a,"source-layer":e.sourceLayer,paint:e.geometryType==="point"?{"circle-color":e.style?.color||"#5B21B6","circle-radius":["interpolate",["linear"],["zoom"],5,2.5,12,6],"circle-opacity":.88}:{"line-color":e.style?.color||"#5B21B6","line-width":["interpolate",["linear"],["zoom"],5,Math.max(.4,Number(e.style?.weight||1)*.55),12,Math.max(.8,Number(e.style?.weight||1)*1.4)],"line-opacity":.88}}),e.geometryType==="point"?this.map.addLayer({id:n,type:"circle",source:a,"source-layer":e.sourceLayer,paint:{"circle-color":Xe,"circle-stroke-color":Je,"circle-stroke-width":["case",["boolean",["feature-state","hover"],!1],2,0],"circle-radius":["case",["boolean",["feature-state","hover"],!1],7,0],"circle-opacity":["case",["boolean",["feature-state","hover"],!1],.95,0]}}):e.geometryType==="line"?this.map.addLayer({id:n,type:"line",source:a,"source-layer":e.sourceLayer,paint:{"line-color":Je,"line-width":["case",["boolean",["feature-state","hover"],!1],3,0],"line-opacity":["case",["boolean",["feature-state","hover"],!1],.95,0]}}):this.map.addLayer({id:n,type:"fill",source:a,"source-layer":e.sourceLayer,paint:{"fill-color":Xe,"fill-opacity":["case",["boolean",["feature-state","hover"],!1],.42,0],"fill-antialias":!1}}),e.geometryType==="point"){this.map.addLayer({id:o,type:"circle",source:a,"source-layer":e.sourceLayer,paint:{"circle-color":Xe,"circle-stroke-color":Je,"circle-stroke-width":["case",["boolean",["feature-state","selected"],!1],2.5,0],"circle-radius":["case",["boolean",["feature-state","selected"],!1],8,0],"circle-opacity":["case",["boolean",["feature-state","selected"],!1],.95,0]}});return}if(e.geometryType!=="line"){this.map.addLayer({id:r,type:"fill",source:a,"source-layer":e.sourceLayer,paint:{"fill-color":Xe,"fill-opacity":["case",["boolean",["feature-state","selected"],!1],.42,0],"fill-antialias":!1}});return}this.map.addLayer({id:o,type:"line",source:a,"source-layer":e.sourceLayer,paint:{"line-color":Je,"line-width":["case",["boolean",["feature-state","selected"],!1],3,0],"line-opacity":["case",["boolean",["feature-state","selected"],!1],.95,0]}})}addInteractionOverlayLayers(e){let t=`${e.id}-fallback-hover-source`,a=`${e.id}-fallback-selected-source`;this.map.addSource(t,{type:"geojson",data:Tt}),this.map.addSource(a,{type:"geojson",data:Tt});let i=[],s=[t,a],n=(l,d,h)=>{this.map.addLayer({id:l,type:"circle",source:d,paint:{"circle-color":Xe,"circle-stroke-color":Je,"circle-stroke-width":2.5,"circle-radius":h,"circle-opacity":.95}}),i.push(l)},r=(l,d,h=3)=>{this.map.addLayer({id:l,type:"line",source:d,paint:{"line-color":Je,"line-width":h,"line-opacity":.95}}),i.push(l)},o=(l,d)=>{this.map.addLayer({id:l,type:"fill",source:d,paint:{"fill-color":Xe,"fill-opacity":.42,"fill-antialias":!1}}),i.push(l)};return e.geometryType==="point"?(n(`${e.id}-fallback-hover`,t,7),n(`${e.id}-fallback-selected`,a,8)):e.geometryType==="line"?(r(`${e.id}-fallback-hover`,t,3),r(`${e.id}-fallback-selected`,a,3)):(o(`${e.id}-fallback-hover-fill`,t),o(`${e.id}-fallback-selected-fill`,a)),{layerIds:i,sourceIds:s}}addLabelLayers(e,t){if(!e.labelProperty)return[];let{sourceId:a,labelId:i}=t,s=ra(e),n=fi(e),r=dt(e);return this.map.addLayer({id:i,type:"symbol",source:a,"source-layer":e.sourceLayer,minzoom:s,maxzoom:n,filter:vi(e),layout:{"text-field":bi(e),"text-size":Lt(e,yt),"text-font":yi(r),"text-max-width":r.maxWidth,"text-line-height":r.lineHeight,"text-justify":"center","text-padding":2,"text-allow-overlap":!!e.labelAllowOverlap,"text-ignore-placement":!!e.labelIgnorePlacement,"symbol-sort-key":_i(e)},paint:{"text-color":gi(e),"text-halo-color":r.haloColor,"text-halo-width":r.haloWidth,"text-halo-blur":r.haloBlur,"text-opacity":0}}),[i]}unloadLayer(e){let t=this.layers.get(e);if(t){this.terrainLayerId===e&&(this.map.setTerrain(null),this.terrainLayerId=null,this.terrainSourceId=null,this.terrainExaggeration=null),this.pointCloudLayers?.has(e)&&this.removePointCloudLayer(e),this.clearFeatureState(this.hovered,"hover"),this.clearFeatureState(this.selected,"selected"),this.interactionCleanups.get(e)?.(),this.interactionCleanups.delete(e),this.fallbackCleanups.get(e)?.(),this.fallbackCleanups.delete(e),this.clearDomLabels(e);for(let a of[...t.layerIds].reverse())this.map.getLayer(a)&&this.map.removeLayer(a);for(let a of[...t.sourceIds||[],t.sourceId])this.map.getSource(a)&&this.map.removeSource(a);this.layers.delete(e),this.scheduleAllDomLabelRefresh(),this.selected?.layerId===e&&(this.selected=null,this.options.onSelection?.(null)),this.notifyChange()}}setOpacity(e,t){let a=this.layers.get(e);if(!a)return;if(a.opacity=ne(t,0,1),this.pointCloudLayers?.has(e)){this.pointCloudLayers.get(e)?.setOpacity(a.opacity),this.notifyChange();return}let i=`${e}-fill`,s=`${e}-line`,n=`${e}-raster`;if(this.map.getLayer(n)&&this.map.setPaintProperty(n,"raster-opacity",a.opacity),this.map.getLayer(i)&&this.map.setPaintProperty(i,"fill-opacity",a.opacity),this.map.getLayer(s)){let r=a.config.geometryType==="point"?"circle-opacity":"line-opacity";this.map.setPaintProperty(s,r,ne(a.opacity+.35,0,1))}this.notifyChange()}setLayerColor(e,t){let a=this.layers.get(e);if(!a||!xi(t))return;a.color=t;let i=`${e}-line`;if(this.map.getLayer(i)){let s=a.config.geometryType==="point"?"circle-color":"line-color";this.map.setPaintProperty(i,s,t)}this.notifyChange()}setLayerFillColor(e,t){let a=this.layers.get(e);if(!a||!xi(t))return;a.fillColor=t;let i=`${e}-fill`;this.map.getLayer(i)&&this.map.setPaintProperty(i,"fill-color",t),this.notifyChange()}setLayerStrokeWidth(e,t){let a=this.layers.get(e);if(!a)return;let i=`${e}-line`;if(!this.map.getLayer(i))return;let s=ne(t,.2,8);a.config.geometryType==="point"?this.map.setPaintProperty(i,"circle-radius",s):this.map.setPaintProperty(i,"line-width",s),a.strokeWidth=s,this.notifyChange()}setLayerAttributeFilter(e,t,a){let i=this.layers.get(e);if(!i||!t)return!1;let s=a==null||a===""?null:["==",["to-string",["get",t]],String(a)];for(let n of i.layerIds||[])!this.map.getLayer(n)||/label|hover|selected/i.test(n)||this.map.setFilter(n,s);return i.attributeFilter=s?{attribute:t,value:String(a)}:null,this.notifyChange(),!0}clearLayerFilter(e){let t=this.layers.get(e);if(!t)return!1;for(let a of t.layerIds||[])!this.map.getLayer(a)||/label|hover|selected/i.test(a)||this.map.setFilter(a,null);return t.attributeFilter=null,this.notifyChange(),!0}setLayerLabelsEnabled(e,t){let a=this.layers.get(e);if(!a)return;a.labelsEnabled=!!t;let i=a.labelsEnabled?"visible":"none";for(let s of a.labelLayerIds||[])this.map.getLayer(s)&&this.map.setLayoutProperty(s,"visibility",i);for(let s of a.domLabelMarkers?.values?.()||[])s.getElement().hidden=!a.labelsEnabled;this.notifyChange()}setLayerTextScale(e,t){let a=this.layers.get(e);if(a){a.textScale=ne(t,50,200);for(let i of a.labelLayerIds||[])this.map.getLayer(i)&&this.map.setLayoutProperty(i,"text-size",Lt(a.config,a.textScale));this.scheduleDomLabelRefresh(e),this.notifyChange()}}moveLayerOrder(e,t){if(!this.layers.has(e)||!t)return!1;let a=[...this.layers.entries()],i=a.findIndex(([r])=>r===e),s=i+t;if(s<0||s>=a.length)return!1;let[n]=a.splice(i,1);return a.splice(s,0,n),this.layers=new Map(a),this.reapplyLayerOrder(),ki([...this.layers.keys()]),this.notifyChange(),!0}moveLayerBefore(e,t){if(!this.layers.has(e)||!this.layers.has(t)||e===t)return!1;let a=[...this.layers.entries()],i=a.findIndex(([o])=>o===e),s=a.findIndex(([o])=>o===t);if(i<0||s<0)return!1;let[n]=a.splice(i,1),r=a.findIndex(([o])=>o===t);return a.splice(r<0?s:r,0,n),this.layers=new Map(a),this.reapplyLayerOrder(),ki([...this.layers.keys()]),this.notifyChange(),!0}reorderFromSavedLayerOrder(){let e=In();if(!e.length||this.layers.size<2)return;let t=new Map(e.map((i,s)=>[i,s])),a=[...this.layers.entries()].sort((i,s)=>{let n=t.has(i[0])?t.get(i[0]):Number.MAX_SAFE_INTEGER,r=t.has(s[0])?t.get(s[0]):Number.MAX_SAFE_INTEGER;return n-r});this.layers=new Map(a),this.reapplyLayerOrder()}reapplyLayerOrder(){for(let e of this.layers.values())for(let t of e.layerIds||[])this.map.getLayer(t)&&this.map.moveLayer(t);this.scheduleAllDomLabelRefresh()}applySavedLayerPreferences(e){let t=Sn(e);t&&(t.opacity!==void 0&&this.setOpacity(e,Number(t.opacity)),t.strokeWidth!==void 0&&this.setLayerStrokeWidth(e,Number(t.strokeWidth)),t.color&&this.setLayerColor(e,t.color),t.fillColor&&this.setLayerFillColor(e,t.fillColor),t.labelsEnabled!==void 0&&this.setLayerLabelsEnabled(e,!!t.labelsEnabled),t.textScale!==void 0&&this.setLayerTextScale(e,Number(t.textScale)))}selectFeatureById(e,t,a={}){let i=this.layers.get(e);return!i||t===void 0||t===null||i.config.sourceType==="raster"?!1:(this.setDomLabelSelected(this.selected?.layerId,this.selected?.id,!1),this.clearFeatureState(this.selected,"selected"),this.selected={layerId:e,sourceId:i.sourceId,sourceLayer:i.config.sourceLayer,id:t,properties:a},this.map.setFeatureState({source:i.sourceId,sourceLayer:i.config.sourceLayer,id:t},{selected:!0}),this.setDomLabelSelected(e,t,!0),this.options.onSelection?.({layer:i.config,feature:{id:t,properties:a}}),this.notifyChange(),!0)}fitToLayer(e){let t=this.layers.get(e);t&&this.fitToBounds(t.config.bounds,{terrain:t.config.sourceType==="raster-dem"||t.config.sourceType==="point-cloud"})}fitToBounds(e,t={}){let a=at(e);if(a){if(t.terrain&&typeof this.map.cameraForBounds=="function"){let i=this.map.cameraForBounds(a,{padding:36});if(i){let s=this.map.getPitch(),n=s{a=!0,this.map.off("error",s)},9e3),s=n=>{if(a||!this.layers.has(e.id))return;let r=String(n?.error?.message||n?.error||""),o=!n.sourceId||n.sourceId===t,l=/pmtiles|byte|range|content-length|fetch|network|failed/i.test(r);if(!o||!l)return;a=!0,clearTimeout(i),this.map.off("error",s);let d={layerId:e.id,layerName:e.name,event:"pmtiles-fallback",sourceType:"pmtiles",reason:r.slice(0,240)};if(this.recordMetric(d),!(e.tilesFallback&&(!pn(e.tilesFallback)||mn()))){let p={...d,event:"pmtiles-fallback-unavailable",fallbackUnavailable:!0,reason:`${d.reason}${d.reason?" ":""}Directory MVT fallback is not deployed on production Pages.`};this.recordMetric(p),this.fallbackLayers.set(e.id,p),this.options.onFallback?.(p);return}let u={...e,sourceType:"mvt",tiles:e.tilesFallback,tileUrl:void 0,fallbackFromPmtiles:!0};this.unloadLayer(e.id),this.loadLayer(u).catch(p=>{this.recordMetric({layerId:e.id,layerName:e.name,event:"pmtiles-fallback-failed",sourceType:"mvt",reason:String(p.message||p).slice(0,240)}),this.options.onError?.(p)}),this.fallbackLayers.set(e.id,d),this.options.onFallback?.(d)};return this.map.on("error",s),()=>{a=!0,clearTimeout(i),this.map.off("error",s)}}bindLayerInteractions(e,t,a,i){let s=0,n=null,r=0,o=()=>this.clearHover(),l=(v,w=0)=>{let S=[t,`${e.id}-line`].filter(C=>C&&this.map.getLayer(C));if(S.length===0)return[];let E=w>0?[[v.x-w,v.y-w],[v.x+w,v.y+w]]:v;return this.map.queryRenderedFeatures(E,{layers:S})},d=()=>{r=0;let v=n;if(n=null,!v||!this.layers.has(e.id))return;if(this.options.shouldSuppressLayerInteraction?.(v)){o();return}let w=typeof this.map.isSourceLoaded=="function"?this.map.isSourceLoaded(i):this.map.areTilesLoaded();if(this.map.isMoving()||!w){o();return}this.setHover(e,l(v.point)[0])},h=v=>{let w=v.originalEvent;if(w&&document.elementFromPoint(w.clientX,w.clientY)?.closest?.(".maplibre-dom-label"))return;n=v;let S=performance.now();if(S-s{let w=v.target?.closest?.(".maplibre-dom-label")||document.elementFromPoint(v.clientX,v.clientY)?.closest?.(".maplibre-dom-label");if(w?.dataset?.layerId!==e.id)return;let S=w.__civgraphFeature;S&&this.setHover(e,S)},p=v=>{if(this.options.shouldSuppressLayerInteraction?.(v))return;v.preventDefault?.();let w=l(v.point,qt)[0];w&&this.selectFeature(e,w)},f=v=>{let w=v.originalEvent;if(this.options.shouldSuppressLayerInteraction?.(v)||w&&document.elementFromPoint(w.clientX,w.clientY)?.closest?.(".maplibre-dom-label, .maplibregl-ctrl, .map-controls, .active-layers-toggle"))return;let S=l(v.point,qt)[0];if(!S){this.clearHover();return}v.preventDefault?.(),this.selectFeature(e,S)},g=()=>this.scheduleDomLabelRefresh(e.id),y=()=>{this.hovered?.layerId!==e.id&&this.scheduleDomLabelRefresh(e.id)},b=this.map.getContainer();return this.map.on("mousemove",h),this.map.on("click",f),this.map.on("dblclick",p),this.map.on("movestart",o),this.map.on("moveend",g),this.map.on("zoomend",g),this.map.on("idle",y),b.addEventListener("pointermove",u,!0),b.addEventListener("mouseleave",o),()=>{r&&cancelAnimationFrame(r),this.map.off("mousemove",h),this.map.off("click",f),this.map.off("dblclick",p),this.map.off("movestart",o),this.map.off("moveend",g),this.map.off("zoomend",g),this.map.off("idle",y),b.removeEventListener("pointermove",u,!0),b.removeEventListener("mouseleave",o)}}readFeatureId(e,t){return this.readFeatureIdentity(e,t).id}readFeatureIdentity(e,t){let a=e?.promoteId||"id",i=t?.id??t?.properties?.[a]??t?.properties?.id;if(i!=null&&i!==""){if(this.layers.get(e.id)?.duplicateFeatureIds?.has(String(i))){let r=Ei(e,t)||vn(e,t,i);return r?{id:r,generated:!0,sourceFeatureId:i,duplicatePromoteId:!0}:{id:i,generated:!1}}return{id:i,generated:!1}}let s=Ei(e,t);return s?{id:s,generated:!0}:{id:null,generated:!0}}async loadDuplicateFeatureIds(e){if(e?.featureIdMode==="unique"||e?.duplicateFeatureIdCount===0)return new Set;if(Array.isArray(e?.duplicateFeatureIds))return new Set(e.duplicateFeatureIds.map(String));let t=e?.duplicateFeatureIdsUrl;if(t){let s=`sidecar:${t}`;return this.duplicateFeatureIdCache.has(s)||this.duplicateFeatureIdCache.set(s,fetch(t,{cache:"force-cache"}).then(n=>n.ok?n.json():null).then(n=>new Set((n?.duplicateFeatureIds||[]).map(String))).catch(()=>new Set)),this.duplicateFeatureIdCache.get(s)}let a=e?.featureIndexUrl;if(!a)return new Set;let i=`index:${a}`;return this.duplicateFeatureIdCache.has(i)||this.duplicateFeatureIdCache.set(i,fetch(a,{cache:"force-cache"}).then(s=>s.ok?s.json():null).then(s=>{let n=Array.isArray(s)?s:Array.isArray(s?.items)?s.items:Array.isArray(s?.features)?s.features:[],r=new Map;for(let o of n){if(o?.id===void 0||o?.id===null||o.id==="")continue;let l=String(o.id);r.set(l,(r.get(l)||0)+1)}return new Set([...r].filter(([,o])=>o>1).map(([o])=>o))}).catch(()=>new Set)),this.duplicateFeatureIdCache.get(i)}clearHover({resetCursor:e=!0}={}){let t=this.hovered;this.clearFeatureState(t,"hover"),this.setDomLabelHover(t?.layerId,t?.id,!1),this.hovered=null,e&&this.setMapCursor("")}setHover(e,t){let{id:a,generated:i}=this.readFeatureIdentity(e,t);if(a===null){this.clearHover();return}if(this.hovered?.layerId===e.id&&this.hovered.id===a)return;this.clearHover({resetCursor:!1});let s=this.layers.get(e.id);if(this.hovered={layerId:e.id,sourceId:s?.sourceId,sourceLayer:e.sourceLayer,id:a,generated:i},this.setDomLabelHover(e.id,a,!0),!i)try{this.map.setFeatureState({source:s.sourceId,sourceLayer:e.sourceLayer,id:a},{hover:!0})}catch{}i||e.geometryType==="point"||e.geometryType==="line"?this.setInteractionOverlay(e.id,"hover",t):this.clearInteractionOverlay(e.id,"hover"),this.setMapCursor("pointer")}selectFeature(e,t){let{id:a,generated:i}=this.readFeatureIdentity(e,t);if(a===null)return!1;let s=this.layers.get(e.id);if(!s)return!1;this.setDomLabelSelected(this.selected?.layerId,this.selected?.id,!1),this.clearFeatureState(this.selected,"selected");let n=t.geometry||null;if(!i&&e.geometryType==="polygon"&&dn.has(e.sourceType)){let o=this.mergePolygonFragments(e,a);o&&(n=o)}let r={...t,id:a,properties:Ge(e,t.properties||{}),geometry:n};if(this.selected={layerId:e.id,sourceId:s.sourceId,sourceLayer:e.sourceLayer,id:a,generated:i,properties:r.properties},!i)try{this.map.setFeatureState({source:s.sourceId,sourceLayer:e.sourceLayer,id:a},{selected:!0})}catch{}return i||e.geometryType==="point"||e.geometryType==="line"?this.setInteractionOverlay(e.id,"selected",r):this.clearInteractionOverlay(e.id,"selected"),this.setDomLabelSelected(e.id,a,!0),this.options.onSelection?.({layer:e,feature:r}),this.notifyChange(),!0}mergePolygonFragments(e,t){let i=this.layers.get(e.id)?.sourceId,s=String(t),n=[],r=o=>{for(let l of o||[]){if(String(this.readFeatureIdentity(e,l).id)!==s)continue;let d=l.geometry;if(d){if(d.type==="Polygon")n.push(d.coordinates);else if(d.type==="MultiPolygon")for(let h of d.coordinates)n.push(h)}}};if(i)try{r(this.map.querySourceFeatures(i,{sourceLayer:e.sourceLayer,filter:["==",["get",e.promoteId||"id"],t]}))}catch{}if(n.length===0){let o=`${e.id}-fill`;if(this.map.getLayer(o))try{r(this.map.queryRenderedFeatures({layers:[o]}))}catch{}}return n.length<=1?null:{type:"MultiPolygon",coordinates:n}}setInteractionOverlay(e,t,a){let i=this.layers.get(e),s=`${e}-fallback-${t}-source`,n=i&&this.map.getSource(s);if(!n?.setData)return;let r=wn(a?.geometry);if(!r){n.setData(Tt);return}n.setData({type:"FeatureCollection",features:[{type:"Feature",geometry:r,properties:{...a.properties||{}}}]})}clearInteractionOverlay(e,t){let a=e?this.map.getSource(`${e}-fallback-${t}-source`):null;a?.setData&&a.setData(Tt)}scheduleDomLabelRefresh(e){let t=this.layers.get(e);!t||!t.config?.labelProperty||t.config.sourceType==="raster"||t.config.sourceType==="image"||t.domLabelsScheduled||(t.domLabelsScheduled=requestAnimationFrame(()=>{t.domLabelsScheduled=0,this.refreshDomLabels(e)}))}scheduleAllDomLabelRefresh(){for(let e of this.layers.keys())this.scheduleDomLabelRefresh(e)}refreshDomLabels(e){let t=this.layers.get(e);if(!t||!t.config?.labelProperty)return;let a=t.config,i=[`${e}-fill`,`${e}-line`].filter(u=>this.map.getLayer(u)),s=Number.isFinite(Number(a.test2LabelMinZoomOverride))?Number(a.test2LabelMinZoomOverride):ra(a);if(!i.length||!t.labelsEnabled||this.map.getZoom()=r)break;let p=this.readFeatureId(a,u);if(p===null)continue;let f=Ct(a,u.properties);if(!f)continue;let g=yn(u);if(!g)continue;let y=String(p);if(o.has(y))continue;let b=this.map.project(g),v=Mi(b,f);if(l.some(O=>bn(O,v)))continue;l.push(v),o.add(y);let w=t.domLabelMarkers.get(y);w||(w=this.createDomLabelMarker(a,u,p,f),t.domLabelMarkers.set(y,w));let S=w.getElement();S.__civgraphFeature=u;let E=S.querySelector("div");E&&E.textContent!==f&&(E.textContent=f);let C=this.selected?.layerId===e&&String(this.selected.id)===y;S.classList.contains("map-label--selected")!==C&&S.classList.toggle("map-label--selected",C);let T=!t.labelsEnabled;S.hidden!==T&&(S.hidden=T);let z=`${Number(g[0]).toFixed(7)},${Number(g[1]).toFixed(7)}`;S.__civgraphLngLatKey!==z&&(w.setLngLat(g),S.__civgraphLngLatKey=z),S.isConnected||w.addTo(this.map)}let h=this.hovered?.layerId===e?String(this.hovered.id):null;h&&t.domLabelMarkers.has(h)&&o.add(h);for(let[u,p]of t.domLabelMarkers)o.has(u)||(p.remove(),t.domLabelMarkers.delete(u))}createDomLabelMarker(e,t,a,i){let s=dt(e),n=document.createElement("span");n.className="map-label map-label--clickable maplibre-dom-label",n.dataset.layerId=e.id,n.dataset.featureId=String(a),n.__civgraphFeature=t,n.setAttribute("role","button"),n.setAttribute("tabindex","0"),n.setAttribute("aria-label",`Show details for ${i}`);let r=document.createElement("div");r.textContent=i,r.style.color=s.color,r.style.fontSize=`${Lt(e,this.layers.get(e.id)?.textScale||yt)}px`,n.appendChild(r);let o=d=>{d.preventDefault(),d.stopPropagation(),this.selectFeature(e,n.__civgraphFeature||t)};n.addEventListener("click",o),n.addEventListener("keydown",d=>{(d.key==="Enter"||d.key===" ")&&o(d)});let l=()=>this.setHover(e,n.__civgraphFeature||t);return n.addEventListener("mouseenter",l),n.addEventListener("mouseover",l),n.addEventListener("pointerenter",l),n.addEventListener("mouseleave",()=>this.clearHover()),n.addEventListener("pointerleave",()=>this.clearHover()),new $e.default.Marker({element:n,anchor:"center"})}clearDomLabels(e){let t=this.layers.get(e);if(t?.domLabelMarkers){t.domLabelsScheduled&&(cancelAnimationFrame(t.domLabelsScheduled),t.domLabelsScheduled=0);for(let a of t.domLabelMarkers.values())a.remove();t.domLabelMarkers.clear()}}setDomLabelHover(e,t,a){this.layers.get(e)?.domLabelMarkers?.get(String(t))?.getElement().classList.toggle("map-label--hover",!!a)}setDomLabelSelected(e,t,a){this.layers.get(e)?.domLabelMarkers?.get(String(t))?.getElement().classList.toggle("map-label--selected",!!a)}clearFeatureState(e,t){if(e?.layerId&&this.clearInteractionOverlay(e.layerId,t),!(!e?.sourceId||e.id===void 0||e.id===null)&&this.map.getSource(e.sourceId)&&!e.generated)try{this.map.setFeatureState({source:e.sourceId,sourceLayer:e.sourceLayer,id:e.id},{[t]:!1})}catch{}}waitForMap(){return this.map.isStyleLoaded?.()||this.map.loaded()?Promise.resolve():new Promise(e=>{let t=0,a=()=>{clearTimeout(t),this.map.off("load",a),this.map.off("styledata",i),e()},i=()=>{(this.map.isStyleLoaded?.()||this.map.loaded())&&a()};this.map.once("load",a),this.map.on("styledata",i),t=setTimeout(a,3e3)})}notifyChange(){this.options.onChange?.(this)}recordMetric(e){this.metrics.push(e),this.options.onMetric?.(e)}getMetrics(){return[...this.metrics]}};function xi(c){return typeof c=="string"&&/^#[0-9a-f]{6}$/i.test(c)}function yn(c){let e=c?.properties||{},t=Number(e.label_lon??e.label_lng??e.lon??e.lng??e.longitude),a=Number(e.label_lat??e.lat??e.latitude);if(Number.isFinite(t)&&Number.isFinite(a))return[t,a];let i=[];if(la(c?.geometry?.coordinates,i),!i.length)return null;let s=1/0,n=1/0,r=-1/0,o=-1/0;for(let[l,d]of i)!Number.isFinite(l)||!Number.isFinite(d)||(s=Math.min(s,l),r=Math.max(r,l),n=Math.min(n,d),o=Math.max(o,d));return[s,r,n,o].every(Number.isFinite)?[(s+r)/2,(n+o)/2]:null}function Mi(c,e){let t=Math.min(Math.max(String(e).length*7.5,34),150),a=Math.max(16,Math.ceil(String(e).length/18)*15),i=4;return{left:c.x-t/2-i,right:c.x+t/2+i,top:c.y-a/2-i,bottom:c.y+a/2+i}}function bn(c,e){return c.lefte.left&&c.tope.top}function la(c,e){if(Array.isArray(c)){if(c.length>=2&&typeof c[0]=="number"&&typeof c[1]=="number"){e.push([c[0],c[1]]);return}for(let t of c)la(t,e)}}function Ei(c,e){let t=e?.properties||{},a=Ct(c,t)||"",i=_n(e?.geometry),s=$i(t,c),n=[a,s,i].filter(Boolean).join("|");return n?`generated:${Pi(n)}`:null}function vn(c,e,t){let a=e?.properties||{},i=Ct(c,a)||"",s=$i(a,c),n=[c?.id||"",t==null?"":String(t),i,s,JSON.stringify(a).slice(0,500)].filter(Boolean).join("|");return n?`generated:${Pi(n)}`:null}function _n(c){let e=[];if(la(c?.coordinates,e),!e.length)return"";let t=1/0,a=1/0,i=-1/0,s=-1/0;for(let[l,d]of e)!Number.isFinite(l)||!Number.isFinite(d)||(t=Math.min(t,l),i=Math.max(i,l),a=Math.min(a,d),s=Math.max(s,d));if(![t,a,i,s].every(Number.isFinite))return"";let n=e[0]||[],r=e[Math.floor(e.length/2)]||[],o=e[e.length-1]||[];return[c?.type||"Geometry",e.length,xe(t),xe(a),xe(i),xe(s),xe(n[0]),xe(n[1]),xe(r[0]),xe(r[1]),xe(o[0]),xe(o[1])].join(":")}function $i(c,e){let t=[e?.labelProperty,...e?.labelPropertyFallbacks||[],...e?.popupProperties||[],"name","Name","NAME"].filter(Boolean);return[...new Set(t)].slice(0,8).map(a=>{let i=c?.[a];return i==null?"":`${a}=${String(i).slice(0,80)}`}).filter(Boolean).join(";")}function xe(c){let e=Number(c);return Number.isFinite(e)?e.toFixed(6):""}function Pi(c){let e=2166136261,t=String(c);for(let a=0;a>>0).toString(36)}function wn(c){return!c?.type||!c.coordinates?null:JSON.parse(JSON.stringify({type:c.type,coordinates:c.coordinates}))}function Sn(c){try{return JSON.parse(localStorage.getItem(`civgraph:test:controls:${c}`)||"null")}catch{return null}}function In(){try{return JSON.parse(localStorage.getItem("civgraph:test:layer-order")||"[]")}catch{return[]}}function ki(c){try{localStorage.setItem("civgraph:test:layer-order",JSON.stringify(c))}catch{}}W();var Ln="settled",Cn="timeout",Tn="unavailable";function Bi(c,{timeoutMs:e=2e4}={}){return!c||typeof c.on!="function"||typeof c.off!="function"?Promise.resolve(Tn):new Promise(t=>{let a=!1,i=r=>{a||(a=!0,clearTimeout(n),c.off("idle",s),t(r))},s=()=>{(typeof c.areTilesLoaded!="function"||c.areTilesLoaded())&&i(Ln)},n=setTimeout(()=>i(Cn),e);c.on("idle",s)})}var Fi={"osm-standard":["https://tile.openstreetmap.org/{z}/{x}/{y}.png"],"osm-humanitarian":["https://tile-{a-c}.openstreetmap.fr/hot/{z}/{x}/{y}.png"],"cartodb-positron":["https://a.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png"],"cartodb-dark":["https://a.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}.png"],"cartodb-dark-nolabels":["https://a.basemaps.cartocdn.com/dark_nolabels/{z}/{x}/{y}.png"],"cartodb-voyager":["https://a.basemaps.cartocdn.com/rastertiles/voyager/{z}/{x}/{y}.png"],"esri-satellite":["https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}"],"esri-world-topo":["https://services.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer/tile/{z}/{y}/{x}"],"esri-natgeo":["https://services.arcgisonline.com/ArcGIS/rest/services/NatGeo_World_Map/MapServer/tile/{z}/{y}/{x}"],"esri-ocean":["https://services.arcgisonline.com/ArcGIS/rest/services/Ocean/World_Ocean_Base/MapServer/tile/{z}/{y}/{x}"],opentopomap:["https://a.tile.opentopomap.org/{z}/{x}/{y}.png"],"stamen-terrain":["https://stamen-tiles.a.ssl.fastly.net/terrain/{z}/{x}/{y}.jpg"],"usgs-topo":["https://basemap.nationalmap.gov/arcgis/rest/services/USGSTopo/MapServer/tile/{z}/{y}/{x}"]},xn={"voyager-labels":{tiles:["https://a.basemaps.cartocdn.com/rastertiles/voyager_only_labels/{z}/{x}/{y}.png","https://b.basemaps.cartocdn.com/rastertiles/voyager_only_labels/{z}/{x}/{y}.png","https://c.basemaps.cartocdn.com/rastertiles/voyager_only_labels/{z}/{x}/{y}.png"],attribution:"© CARTO",maxzoom:20},"merit-catchments":{tiles:["https://tiles.arcgis.com/tiles/P3ePLMYs2RVChkJx/arcgis/rest/services/MERIT_River_Basins_v1/MapServer/tile/{z}/{y}/{x}"],attribution:"© MERIT-Basins",maxzoom:12},"merit-rivers":{tiles:["https://tiles.arcgis.com/tiles/P3ePLMYs2RVChkJx/arcgis/rest/services/MERIT_Rivers_v1/MapServer/tile/{z}/{y}/{x}"],attribution:"© MERIT-Basins",maxzoom:12}},Mn=0;function Di(c){if(!Array.isArray(c))return null;if(c.length===4){let a=c.map(Number);return a.every(Number.isFinite)?[[a[0],a[1]],[a[2],a[3]]]:null}let e=at(c);if(!e)return null;let t=e.flat().map(Number);return t.every(Number.isFinite)?[[t[0],t[1]],[t[2],t[3]]]:null}function En(c,e){return e?c?[[Math.min(c[0][0],e[0][0]),Math.min(c[0][1],e[0][1])],[Math.max(c[1][0],e[1][0]),Math.max(c[1][1],e[1][1])]]:e:c}function kn(c){if(!Array.isArray(c))return[];let e=new Set,t=[];for(let a of c){let i=String(a||"").trim();!i||e.has(i)||(e.add(i),t.push(i))}return t}function Ri(c){return Te(c?.style?.fillOpacity??Mn)}var Mt=class{constructor(e,t,a={}){this.container=e,this.metadataService=t,this.options=a,this.renderer=null,this.map=null,this.layerStates=new Map,this.groupStates=new Map,this.mainToTest=new Map,this.testToMain=new Map,this.overlayLayers=new Map,this.timelineTransitionOverlay=null,this.timelineTransitionOverlayHandlers=[],this.hoveredTimelineTransitionId=null,this.lastTimelineTransitionInteractionAt=0,this._rememberedOrder=[],this.addressMarker=null,this.onFeatureClick=null,this.resizeFrame=0,this.lastResizeSize=null}init(e=this.container){return this.renderer=new xt(e,{onSelection:t=>this.handleSelection(t),shouldSuppressLayerInteraction:t=>this.isTimelineTransitionEventAtPoint(t),onChange:()=>this.options.onChange?.(this),onMetric:t=>this.options.onMetric?.(t),onFallback:t=>this.options.onFallback?.(t)}),this.renderer.init(),this.map=this.renderer.map,this.map.invalidateSize=()=>this.invalidateSize(),this.installMainStyleMapControls(),this.applyMobileTouchContract(),this}applyMobileTouchContract(){this.renderer?.applyMobileTouchContract?.()}getMobileGestureDiagnostics(){return this.renderer?.getMobileGestureDiagnostics?.()||null}installMainStyleMapControls(){let e=this.map,t=e?.getContainer?.();if(!e||!t||t.querySelector(".test2-main-control-stack"))return;t.querySelectorAll([".maplibregl-ctrl-top-left .maplibregl-ctrl-group",".maplibregl-ctrl-top-right .maplibregl-ctrl-group",".maplibregl-ctrl-bottom-left .maplibregl-ctrl-group",".maplibregl-ctrl-bottom-right .maplibregl-ctrl-group",".maplibregl-ctrl-scale"].join(",")).forEach(o=>o.remove());let a=document.createElement("div");a.className="test2-main-control-stack",a.setAttribute("aria-label","Map controls");let i=document.createElement("div");i.className="leaflet-control leaflet-bar leaflet-control-zoom test2-main-zoom-control",i.setAttribute("aria-label","Zoom controls"),i.innerHTML=` - `,i.querySelector(".leaflet-control-zoom-in")?.addEventListener("click",o=>{o.preventDefault(),e.zoomIn({duration:150})}),i.querySelector(".leaflet-control-zoom-out")?.addEventListener("click",o=>{o.preventDefault(),e.zoomOut({duration:150})});let s=i.querySelector(".leaflet-control-compass"),n=i.querySelector(".test2-main-zoom-control__compass-icon"),r=()=>{let o=Number(e.getBearing?.()||0);n&&(n.style.transform=`rotate(${-o}deg)`),s?.classList.toggle("test2-main-zoom-control__compass--active",Math.abs(o)>.1)};s?.addEventListener("click",o=>{o.preventDefault(),e.easeTo({bearing:0,pitch:0,duration:150})}),e.on("rotate",r),e.on("rotateend",r),e.on("pitch",r),r(),a.appendChild(i),t.appendChild(a)}async loadLayer(e,t={}){let a=typeof e=="string"?e:e?.id,i=typeof e=="object"&&e?e:null;if(!a)return null;!t.partial&&this.layerStates.get(a)?.isPartial&&this.unloadLayer(a);let s=oe(i);if(i?.isGroup&&s.length){let d=await Promise.all(s.map(h=>this.loadLayer(h,{...t,fit:!1})));return t.fit!==!1&&this.fitToLayers(s),d[0]||null}let n=this.resolveLayer(a);if(!n){let d=new Error(`${i?.name||a} is not converted for the MapLibre route yet.`);throw this.options.onError?.(d,{mainId:a,config:i}),d}if(!n.loadable){let d=new Error(`${n.name||i?.name||a} is listed in the catalogue but is not yet converted.`);throw this.options.onError?.(d,{mainId:a,config:i,layer:n}),d}let r=i||this.options.getMainMap?.(a)||this.options.getMainMap?.(n.sourceMapId)||null,o=this.toRuntimeLayer(n,r);this.mainToTest.set(a,o.id),this.testToMain.set(o.id,a),await this.renderer.loadLayer(o);let l=this.createMainLayerState(a,o,r);return this.layerStates.set(a,{...l}),this._rememberLayerOrderId(a),this._applyRememberedOrderToMap(),t.fit!==!1&&this.fitToLayer(a),this.options.onChange?.(this),this.layerStates.get(a)}loadLayerFilteredByIndex(e,t){return this.loadLayer(t?.id||e,{fit:!0})}async expandToFullMap(e){let t=typeof e=="string"?e:e?.id;return t&&this.layerStates.get(t)?.isPartial&&this.unloadLayer(t),this.loadLayer(e)}unloadLayer(e){let t=this.groupStates.get(e);if(t){for(let i of t.childIds||[])this.unloadLayer(i);this.groupStates.delete(e),this.options.onChange?.(this);return}let a=this.mainToTest.get(e)||e;this.renderer?.unloadLayer(a),this.mainToTest.delete(e),this.testToMain.delete(a),this.layerStates.delete(e),this.options.onChange?.(this)}showLayer(e){this.setLayerVisibility(e,!0)}hideLayer(e){this.setLayerVisibility(e,!1)}toggleLayer(e){let t=this.groupStates.get(e);if(t){this.setLayerVisibility(e,!t.visible);return}let a=this.layerStates.get(e);a&&this.setLayerVisibility(e,!a.visible)}setLayerVisibility(e,t){let a=this.groupStates.get(e);if(a){for(let r of a.childIds||[])this.setLayerVisibility(r,t);a.visible=!!t,this._applyRememberedOrderToMap(),this.options.onChange?.(this);return}let i=this.layerStates.get(e),s=i?.testLayerId||this.mainToTest.get(e)||e,n=this.renderer?.layers.get(s);if(n){for(let r of n.layerIds||[])this.map.getLayer(r)&&this.map.setLayoutProperty(r,"visibility",t?"visible":"none");i&&(i.visible=!!t),this._applyRememberedOrderToMap(),this.options.onChange?.(this)}}isLayerLoaded(e){let t=this.groupStates.get(e);return t?t.childIds.every(a=>this.isLayerLoaded(a)):this.layerStates.has(e)||this.renderer?.layers.has(e)||!1}isLayerVisible(e){let t=this.groupStates.get(e);return t?t.childIds.some(a=>this.isLayerVisible(a)):this.layerStates.get(e)?.visible||!1}getVisibleLayers(){let e=new Set,t=[...this.groupStates.entries()].filter(([,i])=>i.visible).map(([i,s])=>{for(let n of s.childIds||[])e.add(n);return i}),a=[...this.layerStates.entries()].filter(([i,s])=>s.visible&&!e.has(i)).map(([i])=>i);return[...t,...a]}getLayerState(e){return this.groupStates.has(e)?this.groupStates.get(e):this.layerStates.get(e)||null}markGroupLoaded(e,t,a=[]){let i=a.filter(Boolean);if(!e||!i.length)return;let s={loaded:!0,visible:i.some(n=>this.isLayerVisible(n)),config:t,childIds:i,isGroup:!0,_strokeOpacity:1,_fillOpacity:Ai(t),_rasterOpacity:t?.rasterOpacity??t?.style?.opacity??.85};s.geoJsonLayers=[{setStyle:(n={})=>{if(n.opacity!==void 0){s._strokeOpacity=Le(n.opacity);for(let r of i)this.setStrokeOpacity(r,n.opacity)}if(n.fillOpacity!==void 0){s._fillOpacity=Le(n.fillOpacity);for(let r of i)this.setFillOpacity(r,n.fillOpacity)}}}],s.group={eachLayer:n=>{n({setOpacity:r=>{s._rasterOpacity=Le(r);for(let o of i)this.setRasterOpacity(o,r)}})}},this.groupStates.set(e,s),this._rememberLayerOrderId(e),this._applyRememberedOrderToMap(),this.options.onChange?.(this)}getLayerDrawOrder(e={}){let{loadedOnly:t=!0}=e||{};this._ensureRememberedOrderCoverage();let a=[...this._rememberedOrder].reverse();if(!t)return a;let i=this._getGroupedChildIds();return a.filter(s=>{if(i.has(s))return!1;let n=this.groupStates.get(s);return n?!!n.loaded:!!this.layerStates.get(s)?.loaded})}setLayerDrawOrder(e=[],t={}){let{notify:a=!1}=t||{},i=In(e);if(!i.length)return;this._ensureRememberedOrderCoverage();let s=[...i].reverse(),n=new Set(s),r=this._rememberedOrder.filter(o=>!n.has(o));this._rememberedOrder=[...r,...s],this._applyRememberedOrderToMap(),a&&this.options.onChange?.(this)}_rememberLayerOrderId(e){!e||this._rememberedOrder.includes(e)||this._rememberedOrder.push(e)}_ensureRememberedOrderCoverage(){for(let[e,t]of this.groupStates.entries())t?.loaded&&this._rememberLayerOrderId(e);for(let[e,t]of this.layerStates.entries())t?.loaded&&this._rememberLayerOrderId(e)}_getGroupedChildIds(){let e=new Set;for(let t of this.groupStates.values())for(let a of t?.childIds||[])e.add(a);return e}_moveMainLayerToTop(e){let t=this.mainToTest.get(e)||e,a=this.renderer?.layers.get(t);if(!(!a||!this.map))for(let i of a.layerIds||[])this.map.getLayer(i)&&this.map.moveLayer(i)}_applyRememberedOrderToMap(){if(!this.map||!this.renderer)return;this._ensureRememberedOrderCoverage();let e=this._getGroupedChildIds();for(let t of this._rememberedOrder){let a=this.groupStates.get(t);if(a?.loaded){for(let i of a.childIds||[])this._moveMainLayerToTop(i);continue}e.has(t)||this.layerStates.get(t)?.loaded&&this._moveMainLayerToTop(t)}}setOpacity(e,t){let a=this.mainToTest.get(e)||e;this.renderer?.setOpacity(a,t)}setStrokeOpacity(e,t){let a=this.layerStates.get(e),i=a?.testLayerId||this.mainToTest.get(e)||e,s=this.renderer?.layers.get(i);if(!s)return;let n=Le(t);a._strokeOpacity=n;let r=`${i}-line`;if(this.map.getLayer(r)){let o=s.config.geometryType==="point"?"circle-opacity":"line-opacity";this.map.setPaintProperty(r,o,n)}}setFillOpacity(e,t){let a=this.layerStates.get(e),i=a?.testLayerId||this.mainToTest.get(e)||e,s=Le(t);a._fillOpacity=s;let n=`${i}-fill`;this.map.getLayer(n)&&this.map.setPaintProperty(n,"fill-opacity",s)}setRasterOpacity(e,t){let a=this.layerStates.get(e)||this.groupStates?.get(e),s=`${a?.testLayerId||this.mainToTest.get(e)||e}-raster`;if(!this.map.getLayer(s))return;let n=Le(t);a&&(a._rasterOpacity=n),this.map.setPaintProperty(s,"raster-opacity",n)}setTransparency(e){let t=1-Le(Number(e)/100);for(let a of this.layerStates.keys())this.setStrokeOpacity(a,t)}setFillTransparency(e){let t=1-Le(Number(e)/100);for(let a of this.layerStates.keys())this.setFillOpacity(a,t)}setLabelsEnabled(e){for(let t of this.mainToTest.values())this.renderer?.setLayerLabelsEnabled(t,!!e)}setTextScale(e){for(let t of this.mainToTest.values())this.renderer?.setLayerTextScale(t,e)}setLayerLabelsHidden(e,t){let a=this.mainToTest.get(e)||e;this.renderer?.setLayerLabelsEnabled(a,!t)}applyElectionStyle(e,t={}){var o,l,d,h,u,p;let i=(this.layerStates.get(e)||[...this.layerStates.values()].find(f=>f.testLayerId===e))?.testLayerId||this.mainToTest.get(e)||e,s=this.renderer?.layers.get(i);if(!s)return;s._electionOriginalPaint||(s._electionOriginalPaint={});let n=`${i}-fill`,r=`${i}-line`;if(this.map.getLayer(n)&&((o=s._electionOriginalPaint).fillColor??(o.fillColor=this.map.getPaintProperty(n,"fill-color")),(l=s._electionOriginalPaint).fillOpacity??(l.fillOpacity=this.map.getPaintProperty(n,"fill-opacity")),t.fillColorExpression!==void 0&&this.map.setPaintProperty(n,"fill-color",t.fillColorExpression),t.fillOpacityExpression!==void 0?this.map.setPaintProperty(n,"fill-opacity",t.fillOpacityExpression):t.fillOpacity!==void 0&&this.map.setPaintProperty(n,"fill-opacity",Le(t.fillOpacity))),this.map.getLayer(r)){let f=s.config.geometryType==="point"?"circle-color":"line-color";(d=s._electionOriginalPaint).lineColor??(d.lineColor=this.map.getPaintProperty(r,f)),(h=s._electionOriginalPaint).lineOpacity??(h.lineOpacity=this.map.getPaintProperty(r,s.config.geometryType==="point"?"circle-opacity":"line-opacity")),(u=s._electionOriginalPaint).lineWidth??(u.lineWidth=this.map.getPaintProperty(r,s.config.geometryType==="point"?"circle-radius":"line-width")),this.map.setPaintProperty(r,f,t.lineColorExpression||t.fillColorExpression),t.lineOpacityExpression!==void 0?this.map.setPaintProperty(r,s.config.geometryType==="point"?"circle-opacity":"line-opacity",t.lineOpacityExpression):t.lineOpacity!==void 0&&this.map.setPaintProperty(r,s.config.geometryType==="point"?"circle-opacity":"line-opacity",Le(t.lineOpacity)),t.lineWidth!==void 0&&s.config.geometryType!=="point"&&this.map.setPaintProperty(r,"line-width",t.lineWidth)}Number.isFinite(Number(t.labelMinZoomOverride))&&(s.config.test2LabelMinZoomOverride=Number(t.labelMinZoomOverride),this.renderer?.refreshDomLabels?.(i)),t.hideLabels===!0&&((p=s._electionOriginalPaint).labelsEnabled??(p.labelsEnabled=s.labelsEnabled),this.renderer?.setLayerLabelsEnabled(i,!1)),s.electionStyle={mode:t.mode||"winner"},this.options.onChange?.(this)}clearElectionStyle(e){let a=(this.layerStates.get(e)||[...this.layerStates.values()].find(r=>r.testLayerId===e))?.testLayerId||this.mainToTest.get(e)||e,i=this.renderer?.layers.get(a);if(!i?._electionOriginalPaint)return;let s=`${a}-fill`,n=`${a}-line`;if(this.map.getLayer(s)&&(i._electionOriginalPaint.fillColor!==void 0&&this.map.setPaintProperty(s,"fill-color",i._electionOriginalPaint.fillColor),i._electionOriginalPaint.fillOpacity!==void 0&&this.map.setPaintProperty(s,"fill-opacity",i._electionOriginalPaint.fillOpacity)),this.map.getLayer(n)){let r=i.config.geometryType==="point"?"circle-color":"line-color";i._electionOriginalPaint.lineColor!==void 0&&this.map.setPaintProperty(n,r,i._electionOriginalPaint.lineColor),i._electionOriginalPaint.lineOpacity!==void 0&&this.map.setPaintProperty(n,i.config.geometryType==="point"?"circle-opacity":"line-opacity",i._electionOriginalPaint.lineOpacity),i._electionOriginalPaint.lineWidth!==void 0&&i.config.geometryType!=="point"&&this.map.setPaintProperty(n,"line-width",i._electionOriginalPaint.lineWidth)}i._electionOriginalPaint.labelsEnabled!==void 0&&this.renderer?.setLayerLabelsEnabled(a,!!i._electionOriginalPaint.labelsEnabled),delete i.config.test2LabelMinZoomOverride,this.renderer?.refreshDomLabels?.(a),delete i._electionOriginalPaint,delete i.electionStyle,this.options.onChange?.(this)}setBaseMap(e){let t=Mi[e]||Mi["osm-standard"];if(!this.map)return;this.map.getLayer("osm")&&this.map.removeLayer("osm"),this.map.getSource("osm")&&this.map.removeSource("osm"),this.map.addSource("osm",{type:"raster",tiles:t,tileSize:256,attribution:"© OpenStreetMap contributors"});let a=this.map.getStyle().layers?.[0]?.id;this.map.addLayer({id:"osm",type:"raster",source:"osm"},a)}toggleOverlay(){let[e,t=!0]=arguments;return t?this.showOverlay(e):this.hideOverlay(e)}showOverlay(e){if(!this.map||!e)return!1;if(this.overlayLayers.has(e)){let s=this.overlayLayers.get(e),n=s.layerId;return this.map.getLayer(n)&&this.map.setLayoutProperty(n,"visibility","visible"),s.visible=!0,!0}let t=_n[e];if(!t)return!1;let a=`test2-overlay-${e}-source`,i=`test2-overlay-${e}`;return this.map.getSource(a)||this.map.addSource(a,{type:"raster",tiles:t.tiles,tileSize:256,attribution:t.attribution,maxzoom:t.maxzoom}),this.map.getLayer(i)||this.map.addLayer({id:i,type:"raster",source:a,paint:{"raster-opacity":.82}}),this.overlayLayers.set(e,{sourceId:a,layerId:i,visible:!0}),this.options.onChange?.(this),!0}hideOverlay(e){let t=this.overlayLayers.get(e);return!this.map||!t?!1:(this.map.getLayer(t.layerId)&&this.map.setLayoutProperty(t.layerId,"visibility","none"),t.visible=!1,this.options.onChange?.(this),!0)}setTimelineTransitionOverlay(e,t={}){if(!this.map)return!1;let a="test2-timeline-transition-source",i="test2-timeline-transition-fill",s="test2-timeline-transition-line",n=["coalesce",["get","transitionType"],["get","changeType"],"transfer"],r=t.fillColor||["case",["boolean",["feature-state","hover"],!1],"#FDBA74",["match",n,"split","#7c3aed","territory-split","#7c3aed","unchanged","#ffffff","retained","#ffffff","transfer","#ef4444","#ef4444"]],o=["case",["boolean",["feature-state","hover"],!1],.46,["match",n,"unchanged",0,"retained",0,t.fillOpacity??.34]],l=t.lineColor||["case",["boolean",["feature-state","hover"],!1],"#FF7A1A",["match",n,"split","#6d28d9","territory-split","#6d28d9","unchanged","#ffffff","retained","#ffffff","transfer","#dc2626","#dc2626"]],d=["case",["boolean",["feature-state","hover"],!1],.92,["match",n,"unchanged",0,"retained",0,t.lineOpacity??.82]],h=Ln(e);return this.clearTimelineTransitionHover(),this.map.getSource(a)?this.map.getSource(a).setData(h):this.map.addSource(a,{type:"geojson",data:h,promoteId:"transitionId"}),this.map.getLayer(i)?(this.map.setPaintProperty(i,"fill-color",r),this.map.setPaintProperty(i,"fill-opacity",o)):this.map.addLayer({id:i,type:"fill",source:a,paint:{"fill-color":r,"fill-opacity":o,"fill-antialias":!1}}),this.map.getLayer(s)?(this.map.setPaintProperty(s,"line-color",l),this.map.setPaintProperty(s,"line-opacity",d)):this.map.addLayer({id:s,type:"line",source:a,paint:{"line-color":l,"line-opacity":d,"line-width":["interpolate",["linear"],["zoom"],5,.8,11,1.6,14,2.4]}}),this.installTimelineTransitionHandlers(i,s,t),this.timelineTransitionOverlay={sourceId:a,fillLayerId:i,lineLayerId:s,options:t},!0}installTimelineTransitionHandlers(e,t,a={}){if(!this.map)return;for(let{layerId:l,event:d,handler:h}of this.timelineTransitionOverlayHandlers)this.map.getLayer(l)&&this.map.off(d,l,h);this.timelineTransitionOverlayHandlers=[];let i=l=>(l?.features||[]).map(d=>this.normalizeTimelineTransitionFeature(d,a)).filter(Boolean)[0]||null,s=l=>{let d=i(l);d&&(this.lastTimelineTransitionInteractionAt=performance?.now?.()||Date.now(),l.preventDefault?.(),l.originalEvent?.preventDefault?.(),l.originalEvent?.stopPropagation?.(),this.setTimelineTransitionHover(d.id),this.options.onFeatureClick?.([d]))},n=l=>{let d=i(l);d&&(this.setTimelineTransitionHover(d.id),this.map?.getCanvas?.()&&(this.map.getCanvas().style.cursor="pointer"))},r=()=>{this.map?.getCanvas?.()&&(this.map.getCanvas().style.cursor="pointer")},o=()=>{this.clearTimelineTransitionHover(),this.map?.getCanvas?.()&&(this.map.getCanvas().style.cursor="")};for(let l of[e,t])this.map.on("click",l,s),this.map.on("mousemove",l,n),this.map.on("mouseenter",l,r),this.map.on("mouseleave",l,o),this.timelineTransitionOverlayHandlers.push({layerId:l,event:"click",handler:s},{layerId:l,event:"mousemove",handler:n},{layerId:l,event:"mouseenter",handler:r},{layerId:l,event:"mouseleave",handler:o})}isTimelineTransitionEventAtPoint(e){if(!this.map||!this.timelineTransitionOverlay||!e?.point)return!1;let{fillLayerId:t,lineLayerId:a}=this.timelineTransitionOverlay,i=[t,a].filter(s=>this.map.getLayer(s));return i.length?this.map.queryRenderedFeatures(e.point,{layers:i}).length>0:!1}setTimelineTransitionHover(e){if(!this.map||!this.timelineTransitionOverlay||e===void 0||e===null)return;let{sourceId:t}=this.timelineTransitionOverlay;if(this.hoveredTimelineTransitionId!==e){this.clearTimelineTransitionHover(),this.hoveredTimelineTransitionId=e;try{this.map.setFeatureState({source:t,id:e},{hover:!0})}catch{this.hoveredTimelineTransitionId=null}}}clearTimelineTransitionHover(){if(!this.map||!this.timelineTransitionOverlay||this.hoveredTimelineTransitionId===null)return;let{sourceId:e}=this.timelineTransitionOverlay;try{this.map.setFeatureState({source:e,id:this.hoveredTimelineTransitionId},{hover:!1})}catch{}this.hoveredTimelineTransitionId=null}normalizeTimelineTransitionFeature(e,t={}){let a={...e?.properties||{}},i=a.fromFeatureName||a.from_name||a.fromName||a.oldName||"Earlier feature",s=a.toFeatureName||a.to_name||a.toName||a.newName||"Later feature",n=a.fromMapName||t.fromMapName||a.fromLayerName||"Earlier layer",r=a.toMapName||t.toMapName||a.toLayerName||"Later layer",o=`${n} to ${r}`,l=a.transitionName||a.name||`${i} to ${s}`,d=a.transitionType||a.changeType||"transfer";return{...a,id:a.transitionId||e?.id||`${t.fromMapId||"from"}__${t.toMapId||"to"}__${l}`,mapId:"__timeline_transition__",mapName:o,layerName:o,featureName:l,name:l,isTimelineTransitionFeature:!0,transitionType:d,color:d==="split"||d==="territory-split"?"#7c3aed":d==="unchanged"||d==="retained"?"#64748b":"#dc2626",properties:{...a,transitionType:d,transitionLayerName:o,fromMapId:a.fromMapId||t.fromMapId||"",toMapId:a.toMapId||t.toMapId||"",fromMapName:n,toMapName:r,fromFeatureName:i,toFeatureName:s,minimumDisplayedAreaM2:t.minAreaM2},geometry:e?.geometry||null,sourceLayer:"timeline-transition"}}clearTimelineTransitionOverlay(e={}){if(!this.map||!this.timelineTransitionOverlay)return!1;let{sourceId:t,fillLayerId:a,lineLayerId:i}=this.timelineTransitionOverlay,s=this.map.getSource(t),n={type:"FeatureCollection",features:[]};this.clearTimelineTransitionHover();let r=()=>{this.map?.getSource(t)&&this.map.getSource(t).setData(n),this.map?.getLayer(a)&&this.map.setPaintProperty(a,"fill-opacity",0),this.map?.getLayer(i)&&this.map.setPaintProperty(i,"line-opacity",0)};return e.fade&&this.map.getLayer(a)?(this.map.setPaintProperty(a,"fill-opacity-transition",{duration:260,delay:0}),this.map.setPaintProperty(i,"line-opacity-transition",{duration:260,delay:0}),this.map.setPaintProperty(a,"fill-opacity",0),this.map.setPaintProperty(i,"line-opacity",0),window.setTimeout(r,280)):s&&r(),!0}clearTransientHighlight(e={}){if(this.renderer?.clearHover?.(),this.clearTimelineTransitionHover(),e.clearSelection===!1||!this.renderer?.selected)return;let t=this.renderer.selected;this.renderer.clearFeatureState?.(t,"selected"),this.renderer.setDomLabelSelected?.(t.layerId,t.id,!1),this.renderer.selected=null,this.renderer.notifyChange?.()}fitToLayer(e){let t=this.mainToTest.get(e)||e;this.renderer?.fitToLayer(t)}fitToLayers(e=[]){let t=e.reduce((a,i)=>{let s=this.layerStates.get(i),n=ki(s?.config?.bounds);return n?Sn(a,n):a},null);t&&this.fitToBounds(t,{smooth:!1})}fitToBounds(e,t={}){let a=ki(e);!a||!this.map||this.map.fitBounds(a,{padding:36,duration:t?.smooth===!1?0:400,maxZoom:14})}waitUntilSettled({timeoutMs:e=2e4}={}){return Ei(this.map,{timeoutMs:e})}invalidateSize(){this.map&&(this.applyMobileTouchContract(),!this.resizeFrame&&(this.resizeFrame=requestAnimationFrame(()=>{this.resizeFrame=0,this.applyMobileTouchContract();let e=this.readMapContainerSize();this.shouldResizeMap(e)&&(this.lastResizeSize=e,this.map.resize())})))}readMapContainerSize(){let t=this.map?.getContainer?.()?.getBoundingClientRect?.();return t?{width:Math.round(t.width*10)/10,height:Math.round(t.height*10)/10}:null}shouldResizeMap(e){if(!e||e.width<=0||e.height<=0)return!1;let t=this.lastResizeSize;if(!t||Math.abs(e.width-t.width)>1||Math.abs(e.height-t.height)>1)return!0;let i=this.map?.getCanvas?.()?.getBoundingClientRect?.();return i?Math.abs(i.width-e.width)>1||Math.abs(i.height-e.height)>1:!1}highlightFeature(e,t,a={}){let i=this.mainToTest.get(e)||e;return this.renderer?.selectFeatureById(i,t,a.properties||{})||!1}waitForMapRender(e=700){return this.map?new Promise(t=>{let a=!1,i=()=>{a||(a=!0,clearTimeout(s),t())},s=setTimeout(i,e);this.map.once?.("idle",i),this.map.triggerRepaint?.()}):Promise.resolve()}async loadSingleFeature(e,t,a,i,s={}){let n=e?.id;if(s.isolate&&n){let p=this.layerStates.get(n);p?.baseLoaded===!0&&!p?.isPartial&&this.unloadLayer(n)}let r=n?this.layerStates.get(n)?.baseLoaded===!0&&!this.layerStates.get(n)?.isPartial:!1,o=this.layerStates.get(n);(!o||!this.renderer?.layers.has(o.testLayerId))&&(o=await this.loadLayer(e,{fit:!1,partial:!0})),this.ensurePartialFeatureState(o);let l={name:a||t},d=Te(t),h=this.findRenderedFeature(n,d,a),u=d||Te(h?.id)||Te(a);return h?.properties&&Object.assign(l,h.properties),r||(o.isPartial=!0,o.baseLoaded=!1,o.loadedIndices.add(u),o.featureNames.set(u,a||h?.featureName||`Feature ${t}`),o.featureVisibility.set(u,!0),o.featureProperties.set(u,l),h?.geometry&&o.featureGeometry.set(u,h.geometry),this.applyPartialFeatureFilter(n)),i&&(this.fitToBounds(i),await this.waitForMapRender()),h||(h=this.findRenderedFeature(n,u,a),h?.properties&&Object.assign(l,h.properties),h?.geometry&&o.featureGeometry.set(u,h.geometry),o.featureProperties.set(u,l)),this.highlightFeature(n,u,{properties:l}),{state:o,feature:{id:u,mapId:n,name:a||h?.featureName||l.name,featureName:a||h?.featureName||l.name,properties:l,geometry:h?.geometry||o.featureGeometry.get(u)||null}}}togglePartialFeature(e,t){let a=this.layerStates.get(e),i=Te(t);a?.featureVisibility?.has(i)&&(a.featureVisibility.set(i,a.featureVisibility.get(i)===!1),this.applyPartialFeatureFilter(e),this.options.onChange?.(this))}unloadPartialFeature(e,t){let a=this.layerStates.get(e),i=Te(t);if(a?.loadedIndices?.has(i)){if(a.loadedIndices.delete(i),a.featureNames?.delete(i),a.featureVisibility?.delete(i),a.featureProperties?.delete(i),a.featureGeometry?.delete(i),this.renderer?.selected?.layerId===a.testLayerId&&Te(this.renderer.selected.id)===i&&(this.renderer.clearFeatureState?.(this.renderer.selected,"selected"),this.renderer.setDomLabelSelected?.(a.testLayerId,i,!1),this.renderer.selected=null),a.loadedIndices.size===0&&a.isPartial&&!a.baseLoaded){this.unloadLayer(e);return}this.applyPartialFeatureFilter(e),this.options.onChange?.(this)}}isFeatureLoaded(e,t){let a=this.layerStates.get(e);return a?a.baseLoaded&&!a.isPartial?!0:a.loadedIndices?.has(Te(t))||!1:!1}isFeatureVisible(e,t){let a=this.layerStates.get(e);if(!a)return!1;if(a.baseLoaded&&!a.isPartial)return this.isLayerVisible(e);let i=Te(t);return!!(a.loadedIndices?.has(i)&&a.featureVisibility?.get(i)!==!1&&a.visible)}isPartialLayer(e){return!!this.layerStates.get(e)?.isPartial}getPartialFeatureNames(e){let t=this.layerStates.get(e);return t?.loadedIndices?[...t.loadedIndices].map(a=>t.featureNames?.get(a)||t.featureProperties?.get(a)?.name||`Feature ${a}`):[]}getPartialFeatureItems(e){let t=this.layerStates.get(e);return t?.loadedIndices?[...t.loadedIndices].map(a=>({index:a,name:t.featureNames?.get(a)||t.featureProperties?.get(a)?.name||`Feature ${a}`,visible:t.featureVisibility?.get(a)!==!1&&t.visible!==!1})):[]}findFeaturesAtPoint(e,t,a=8){return this.queryFeaturesAtLngLat(e,t,a)}getLoadedFeatures(e=500){let t=[],a=new Set;for(let[i,s]of this.layerStates){if(!s.visible)continue;let n=this.renderer?.layers.get(s.testLayerId),r=this.getQueryableLayerIds(n);if(!r.length)continue;let o=this.map.queryRenderedFeatures({layers:r});for(let l of o){let d=this.normalizeRenderedFeature(l,i,s,n),h=Bi(d);if(!a.has(h)&&(a.add(h),t.push(d),t.length>=e))return t}}return t}queryFeaturesAtLngLat(e,t,a=8){if(!this.map)return[];let i=this.map.project([Number(t),Number(e)]),s=[];for(let o of this.layerStates.values()){if(!o.visible)continue;let l=this.renderer?.layers.get(o.testLayerId);s.push(...this.getQueryableLayerIds(l))}if(!s.length)return[];let n=this.map.queryRenderedFeatures([[i.x-a,i.y-a],[i.x+a,i.y+a]],{layers:s}),r=new Set;return n.map(o=>{let l=o.layer?.id?.replace(/-(fill|line|label|raster)$/,""),d=this.testToMain.get(l)||l,h=this.layerStates.get(d);return this.normalizeRenderedFeature(o,d,h,this.renderer?.layers.get(h?.testLayerId))}).filter(o=>{let l=Bi(o);return r.has(l)?!1:(r.add(l),!0)})}addAddressMarker(e,t,a){this.removeAddressMarker(),this.map&&(this.addressMarker=new sa.default.Marker({color:"#065a6e"}).setLngLat([Number(t),Number(e)]).setPopup(new sa.default.Popup().setHTML(`${xn(a||"Selected location")}`)).addTo(this.map),this.addressMarker.togglePopup(),this.map.flyTo({center:[Number(t),Number(e)],zoom:14,essential:!0}))}removeAddressMarker(){this.addressMarker?.remove(),this.addressMarker=null}resolveLayer(e){let t=this.metadataService.getLayer(e);if(t?.loadable)return t;let a=this.metadataService.layers||[];return a.find(i=>i.sourceMapId===e&&i.loadable)||a.find(i=>i.migration?.sourceMapId===e&&i.loadable)||a.find(i=>i.parentId===e&&i.loadable)||t||null}toRuntimeLayer(e,t=null){let a=this.applyMainStyle(e,t),i=["localhost","127.0.0.1","::1"].includes(location.hostname);return globalThis.__civgraphUseLocalTileFallback===!0&&i&&a.sourceType==="pmtiles"&&a.tilesFallback?(this._warnedLocalTileFallback||(this._warnedLocalTileFallback=!0,console.warn("[civgraph] __civgraphUseLocalTileFallback is on: serving layers from directory MVT under /render/tiles/generated/ instead of PMTiles. Those tiles are untracked and never deployed, so unless you generated them locally every tile request will 404. Unset the flag to return to PMTiles.")),{...a,sourceType:"mvt",tiles:a.tilesFallback,tileUrl:void 0}):a}applyMainStyle(e,t=null){let a=t?.style||{},i={...e.style||{}};for(let s of["color","fillColor","fillOpacity","weight","opacity","radius"])a[s]!==void 0&&(i[s]=a[s]);return a.fillOpacity===void 0&&delete i.fillOpacity,{...e,style:i}}createMainLayerState(e,t,a){let s={loaded:!0,visible:!0,config:a||this.toMainConfig(t),testLayerId:t.id,layerIds:[t.id],geoJsonLayers:[],group:null,_strokeOpacity:1,_fillOpacity:Ai(t),_rasterOpacity:t.rasterOpacity??t.style?.opacity??.85,isPartial:!1,baseLoaded:!0,loadedIndices:new Set,featureNames:new Map,featureVisibility:new Map,featureProperties:new Map,featureGeometry:new Map};return s.geoJsonLayers=[{setStyle:(n={})=>{n.opacity!==void 0&&this.setStrokeOpacity(e,Number(n.opacity)),n.fillOpacity!==void 0&&this.setFillOpacity(e,Number(n.fillOpacity))}}],s.group={eachLayer:n=>n({setOpacity:r=>this.setRasterOpacity(e,Number(r))})},s}ensurePartialFeatureState(e){e.loadedIndices||(e.loadedIndices=new Set),e.featureNames||(e.featureNames=new Map),e.featureVisibility||(e.featureVisibility=new Map),e.featureProperties||(e.featureProperties=new Map),e.featureGeometry||(e.featureGeometry=new Map)}applyPartialFeatureFilter(e){let t=this.layerStates.get(e);if(!t?.isPartial)return;this.ensurePartialFeatureState(t);let a=this.renderer?.layers.get(t.testLayerId);if(!a)return;let i=[...t.loadedIndices].filter(n=>t.featureVisibility.get(n)!==!1),s=Cn(a.config,i,t);for(let n of this.getQueryableLayerIds(a,{includeHidden:!0}))this.map.getLayer(n)&&this.map.setFilter(n,s);this.renderer?.scheduleDomLabelRefresh?.(t.testLayerId)}getQueryableLayerIds(e,t={}){return e?(e.layerIds||[]).filter(a=>!this.map.getLayer(a)||/-((hover)|(hover-line)|(selected)|(selected-fill)|(label)|(raster))$/.test(a)?!1:t.includeHidden?!0:this.map.getLayoutProperty(a,"visibility")!=="none"):[]}findRenderedFeature(e,t,a=null){let i=this.layerStates.get(e),s=this.renderer?.layers.get(i?.testLayerId),n=this.getQueryableLayerIds(s);if(!n.length)return null;let r=Te(t),o=$i(a),l=this.map.queryRenderedFeatures({layers:n});for(let d of l){let h=this.normalizeRenderedFeature(d,e,i,s);if(Te(h.id)===r||o&&$i(h.featureName)===o)return h}return null}normalizeRenderedFeature(e,t,a,i){let s=i?.config||a?.config||{},n=ze(s,{...e.properties||{}}),r=e.id??n[s.promoteId||"id"]??n.id,o=Tn(s,n,r);return{...n,id:r,mapId:t,mapName:a?.config?.name||s.name||t,layerName:a?.config?.name||s.name||t,featureName:o,name:n.name||o,color:s.style?.color||s.style?.fillColor||"#3388ff",properties:n,geometry:e.geometry||null,geometryIsClipped:!0,sourceLayer:e.sourceLayer||s.sourceLayer||null}}toMainConfig(e){return{id:e.sourceMapId||e.id,name:e.name,category:e.category,group:e.group,date:e.date||e.dateEffective,provider:Array.isArray(e.provider)?e.provider:e.provider?[e.provider]:[],style:e.style||{}}}handleSelection(e){if(!e)return;let t=this.testToMain.get(e.layer.id)||e.layer.sourceMapId||e.layer.id,a=this.layerStates.get(t),i=this.renderer?.layers.get(a?.testLayerId||e.layer.id),s=this.normalizeRenderedFeature(e.feature,t,a,i),r=[this.options.enrichFeature?.(s,e)||s];this.onFeatureClick?.(r),this.options.onFeatureClick?.(r)}};function Ln(c){return{type:"FeatureCollection",features:Array.isArray(c?.features)?c.features:[]}}function Le(c){let e=Number(c);return Number.isFinite(e)?Math.max(0,Math.min(1,e)):0}function Te(c){if(typeof c=="number")return Number.isFinite(c)?c:String(c);let e=String(c??"").trim();return e!==""&&/^-?\d+(?:\.\d+)?$/.test(e)?Number(e):e}function $i(c){return String(c??"").trim().toLowerCase()}function Cn(c,e,t=null){if(!e.length)return Pi();let a=[...new Set(e.filter(r=>r!=null&&r!==""))],i=e.map(r=>t?.featureNames?.get(r)).filter(r=>r!=null&&String(r).trim()),s=[...new Set([...a,...i].map(r=>String(r)))];if(!s.length)return Pi();let n=[];for(let r of[c?.promoteId,"id"].filter(Boolean))n.push(["in",["to-string",["get",r]],["literal",s]]);for(let r of Fi(c))n.push(["in",["to-string",["get",r]],["literal",s]]);return["any",...n]}function Pi(){return["==",["get","__civgraph_no_visible_feature__"],"__civgraph_visible_feature__"]}function Tn(c,e,t){let a=Fi(c);for(let i of a){let s=e?.[i];if(s!=null&&String(s).trim())return String(s).trim()}return t!=null&&t!==""?`Feature ${t}`:"Unnamed feature"}function Fi(c){return[...new Set([c?.labelProperty,c?.nameProperty,"name","Name","NAME","label","LABEL","title","TITLE"].filter(Boolean))]}function Bi(c){if(c?.id!==void 0&&c?.id!==null&&c?.id!=="")return`${c.mapId}:${c.id}`;let e=JSON.stringify(c?.geometry?.coordinates||"").slice(0,120);return`${c?.mapId}:${c?.featureName||c?.name||"feature"}:${e}`}function xn(c){return String(c??"").replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[e])}var na="civgraph:maplibre:layer-order",Di=100,Ri="/data/timeline-transition-overlays",Ni="/data/timeline-transitions",Oi=Object.freeze(["wards-1972__wards-1984","wards-1984__wards-1993","wards-1993__wards-2012","wards-2012__wards-2022-final-recommendations"]),ra=new Set(Oi),Ct=Object.freeze({start:900,overlay:1500,settle:450}),En=new Set(["civil-parishes-by-province","ireland-civil-parishes","flat-civil-parishes"]),Mn=["civil-parishes-connacht","civil-parishes-leinster","civil-parishes-munster","civil-parishes-ulster"];function ot(c){if(!c)return[];let e=[];if(Array.isArray(c))e=c;else{let i=String(c).trim();if(!i)return[];if(i.startsWith("["))try{let s=JSON.parse(i);Array.isArray(s)&&(e=s)}catch{e=[]}e.length||(e=i.split(","))}let t=new Set,a=[];for(let i of e){let s=String(i||"").trim();!s||t.has(s)||(t.add(s),a.push(s))}return a}var ca=class{constructor(){this.currentCategory="all",this.currentAuthor="all",this.currentProviderCategory="all-providers",this.currentProviderList=[],this.searchQuery="",this.mapController=null,this.metadataService=null,this._suspendURLState=!1,this._restoringURLState=!1,this.currentDetailMapId=null,this.currentSourceMapId=null,this.baseMapId="osm-standard",this.userPickedBasemap=(()=>{try{return localStorage.getItem("basemapUserChoice")==="1"}catch{return!1}})(),this.elections=null,this.timelineItems=[],this.timelineOnSelect=null,this.timelineApplying=!1,this.timelineApplyDepth=0,this.timelineTransitionCache=new Map,this.timelineTransitionSidecarSet=new Set(ra),this.timelineTransitionManifestEntries=new Map,this.timelineAnimation={playing:!1,paused:!1,atEnd:!1,timer:0,runId:0,originalLayerId:null,currentIndex:0,singleLayerReferenceId:null,sequenceItems:[]},this.booksPromise=null,this.electionModulePromise=null,this.electionLoadPromise=null,this.electionCatalogueWarmScheduled=!1,this.searchWorker=null,this.searchWorkerReady=!1,this.searchWorkerSeq=0,this.searchWorkerCallbacks=new Map,this.workerSearchQuery="",this.workerSearchResultIds=null,this.serviceWorkerStatusPromise=null,this.performanceBudget=null,this.browseEntityDetailCache=new Map,this.browsePersonsIndexPromise=null,this.classicScriptPromises=new Map}readSavedLayerOrder(){try{return ot(localStorage.getItem(na))}catch{return[]}}writeSavedLayerOrder(e){let t=ot(e);try{t.length>1?localStorage.setItem(na,JSON.stringify(t)):localStorage.removeItem(na)}catch{}}normalizeLoadedLayerOrder(e,t=this.getLoadedLayerIds()){let a=new Set(t),i=[],s=new Set;for(let n of ot(e))!a.has(n)||s.has(n)||(s.add(n),i.push(n));for(let n of t)s.has(n)||(s.add(n),i.push(n));return i}getActiveLayerOrder(e=this.getLoadedLayerIds()){let t=this.mapController?.getLayerDrawOrder?.({loadedOnly:!0})||[];return this.normalizeLoadedLayerOrder(t,e)}setActiveLayerOrder(e,t={}){let{persist:a=!0,notify:i=!1}=t||{},s=this.normalizeLoadedLayerOrder(e);return s.length<2||(this.mapController?.setLayerDrawOrder?.(s,{notify:i}),a&&this.writeSavedLayerOrder(s),this.syncCatalogueMapState(),this.updateActiveLayers(),this.updateURLState()),s}restoreLayerOrder(e){let t=ot(e?.get?.("layerOrder")),a=t.length?t:this.readSavedLayerOrder();if(!a.length)return;let i=this.normalizeLoadedLayerOrder(a);i.length<2||this.mapController?.setLayerDrawOrder?.(i)}async init(){let e=performance?.now?.()||Date.now();window.__civgraphTest2={...window.__civgraphTest2||{},app:this,runtimeInitStartedAt:e},this.installRouteGuard(),this.registerServiceWorker(),await P.init({loadBooks:!1,loadGeographies:!1}),P.fuse=null,await this.loadTimelineTransitionManifest(),this.metadataService=new mt("/render/metadata/maps-test-index.json?v=c2c120cf87c6",void 0,{cache:"force-cache",portPlanCache:"force-cache"}),await this.metadataService.load();try{if(P.maps&&Array.isArray(P.maps.maps)){let t=new Set(P.maps.maps.map(a=>a.id));for(let a of this.metadataService.layers||[])(a.sourceType==="point-cloud"||a.sourceType==="raster-dem")&&!t.has(a.id)&&P.maps.maps.push(a)}}catch(t){console.warn("[app] 3D layer catalogue injection failed",t)}this.mapController=new Lt("map",this.metadataService,{onFeatureClick:t=>{let a=t?.[0]||null;if(a&&this.elections?.showFeatureResults(a)){A.hideFeatureInfo?.();return}A.showFeatureInfo(t,P.getAllMaps())},getMainMap:t=>P.getMapById(t),enrichFeature:(t,a)=>this.elections?.enrichFeature(t,a)||t,onChange:()=>{this.syncCatalogueMapState(),this.updateActiveLayers(),this.updateURLState()},onError:t=>this.showMapError(t)}),window.mapController=this.mapController,globalThis.mapController=this.mapController,this.wireUiCallbacks(),this.installCatalogueStateBridge(),this.installLazyCatalogueDataBridge(),this.installLazyRuntimeHelpersBridge(),A.init(),this.configureCataloguePerformanceProfile(),this._suspendURLState=!0,this.mapController.init("map"),this.installOutsideMapHighlightClear(),this.relocateMobileCatalogueToggle(),this.installMobilePaneToggle(),window.__civgraphTest2={...window.__civgraphTest2||{},app:this,mapController:this.mapController,metadataService:this.metadataService,elections:null,restorePromise:null,runtimeReadyAt:performance?.now?.()||Date.now(),serviceWorkerStatusPromise:this.serviceWorkerStatusPromise,getPerformanceStatus:()=>this.collectPerformanceStatus(),whenIdle:(t=15e3)=>new Promise(a=>{let i=this.mapController?.map;if(!i){a({idle:!1,reason:"no map"});return}if(i.loaded?.()&&!i.isMoving?.()){a({idle:!0,immediate:!0});return}let s=!1,n=o=>{s||(s=!0,i.off?.("idle",r),a(o))},r=()=>n({idle:!0,immediate:!1});i.once?.("idle",r),setTimeout(()=>n({idle:!1,reason:"timeout"}),t)}),urlState:()=>({hash:window.location.hash,suspended:this._suspendURLState})},this.scheduleIdleTask(()=>this.prepareSearchWorker(),{timeout:3500}),this.renderCategoryPills(),this.updateMapList(),this.setupSearch(),this.setupThemeToggle(),this.setupSupportModal(),this.setupMapControls(),this.setupOverlayEscape(),this.setupPerformanceDashboard(),this.setupTimelineControls(),this.setupElectionPaneResize(),this.setupSourcePanel(),this.setupURLStateListener(),this.scheduleElectionCatalogueWarm(),window.__civgraphTest2.restorePromise=this.restoreURLState().catch(t=>this.showMapError(t)).finally(()=>{this._suspendURLState=!1,this.updateURLState()}),await window.__civgraphTest2.restorePromise}registerServiceWorker(){if(!("serviceWorker"in navigator)||location.protocol==="file:"){this.serviceWorkerStatusPromise=Promise.resolve({available:!1,reason:"service-worker API unavailable"});return}this.serviceWorkerConfig=this.getServiceWorkerConfig(),this.serviceWorkerStatusPromise=navigator.serviceWorker.register(this.serviceWorkerConfig.url,{scope:this.serviceWorkerConfig.scope}).then(async e=>(await navigator.serviceWorker.ready.catch(()=>e),this.getServiceWorkerStatus(e))).catch(e=>({available:!1,reason:String(e?.message||e)}))}getServiceWorkerConfig(){let e=window.location.pathname||"/";return{url:"/sw.js",scope:"/",route:"root"}}async getServiceWorkerStatus(e=null){if(!("serviceWorker"in navigator))return{available:!1,reason:"service-worker API unavailable"};let t=this.serviceWorkerConfig||this.getServiceWorkerConfig(),a=e||await navigator.serviceWorker.getRegistration(t.scope),i=navigator.serviceWorker.controller||a?.active||a?.waiting||a?.installing;return i?new Promise(s=>{let n=new MessageChannel,r=setTimeout(()=>s({available:!0,controlled:!!navigator.serviceWorker.controller,reason:"status timeout"}),900);n.port1.onmessage=o=>{clearTimeout(r),s({available:!0,route:t.route,controlled:!!navigator.serviceWorker.controller,...o.data||{}})},i.postMessage({type:"TEST2_SW_STATUS"},[n.port2])}):{available:!0,controlled:!1,reason:"registered but not yet controlling this page"}}async collectPerformanceStatus(){let e=await this.loadPerformanceBudget(),t=await this.getServiceWorkerStatus().catch(s=>({available:!1,reason:String(s?.message||s)})),a=this.mapController?.getMetrics?.()||this.mapController?.metrics||[],i=this.elections?.getSeatCircleOverlayState?.()||null;return{generatedAt:new Date().toISOString(),budget:e,serviceWorker:t,map:{runtimeProfile:this.mapController?.runtimeProfile||null,loadedLayers:this.mapController?.layers?.size||0,metrics:a.slice(-40),fallbackCount:a.filter(s=>/fallback/i.test(s?.event||"")).length},elections:{active:this.elections?.activeEntry?.key||null,seatCircleRenderMs:Number(this.elections?.lastSeatCircleRenderMs||0),overlay:i},browser:{memory:performance.memory?.usedJSHeapSize||0,deviceMemory:navigator.deviceMemory||null,hardwareConcurrency:navigator.hardwareConcurrency||null,dpr:window.devicePixelRatio||1}}}async loadPerformanceBudget(){return this.performanceBudget?this.performanceBudget:(this.performanceBudget=fetch("/app/build/performance-dashboard.json",{cache:"no-cache"}).then(e=>e.ok?e.json():null).catch(()=>null),this.performanceBudget)}relocateMobileCatalogueToggle(){let e=document.getElementById("mobileToggle"),t=document.querySelector("#map .test2-main-control-stack"),a=t?.querySelector(".test2-main-zoom-control");!e||!t||!a||(e.classList.remove("mobile-toggle--navbar"),e.classList.add("mobile-toggle--map-stack"),e.removeAttribute("style"),this.updateMobilePaneToggleState(),(e.parentElement!==t||e.nextElementSibling!==a)&&t.insertBefore(e,a))}installMobilePaneToggle(){if(this._mobilePaneToggleInstalled){this.updateMobilePaneToggleState();return}let e=document.querySelector(".app-header");if(!e)return;let t=document.getElementById("mobilePaneToggle");if(!t){t=document.createElement("button"),t.id="mobilePaneToggle",t.type="button",t.className="mobile-pane-toggle",t.innerHTML='';let i=e.querySelector(":scope > .mobile-menu-toggle")||document.getElementById("mobileMenuBtn");i?.parentElement===e?e.insertBefore(t,i):e.appendChild(t)}t.addEventListener("click",i=>{i.preventDefault();let s=A.currentStateId==="info-full"?"map-full":"info-full";A.setSplitState(s),setTimeout(()=>this.mapController?.invalidateSize?.(),250),this.updateMobilePaneToggleState()});let a=A.onSplitChange;A.onSplitChange=i=>{typeof a=="function"&&a(i),this.updateMobilePaneToggleState()},window.matchMedia?.("(max-width: 768px)")?.addEventListener?.("change",()=>{this.updateMobilePaneToggleState()}),this._mobilePaneToggleInstalled=!0,this.mobilePaneToggle=t,this.updateMobilePaneToggleState()}dismissMobileCatalogueAfterLoad(){(A.isMobile||window.matchMedia?.("(max-width: 768px), (pointer: coarse)")?.matches)&&A.currentStateId==="info-full"&&(A.setSplitState("map-full"),this.updateMobilePaneToggleState(),setTimeout(()=>this.mapController?.invalidateSize?.(),250))}refitAfterElectionPane(e){if(!e||this._restoringURLState)return;let t=this.mapController?.map;t&&(t.resize(),this.mapController.fitToLayer?.(e))}updateMobilePaneToggleState(){let e=document.getElementById("mobilePaneToggle");if(!e)return;let t=A.currentStateId==="info-full",a=t?"Show map":"Show catalogue";e.setAttribute("aria-label",a),e.setAttribute("title",a),e.dataset.target=t?"map":"catalogue"}configureCataloguePerformanceProfile(){let e=window.matchMedia?.("(max-width: 768px), (pointer: coarse)"),t=()=>{let a=!!(A.isMobile||e?.matches);A.showAllMaps=!a,A.includeMobileElectionCatalogue=!0,A.singleSectionFlatCatalogue=!0,A._mobileInitialMapCardLimit=a?12:24,A._mobileInitialElectionCardLimit=a?2:15,a||(A._mobileCatalogueExpanded=!1)};t(),e?.addEventListener?.("change",()=>{t(),A.requestFlatViewRender?.(A._lastMapListOptions||{},{defer:!0})})}setupElectionPaneResize(){if(this._electionPaneResizeReady)return;this._electionPaneResizeReady=!0;let e="civgraph:test2:electionPaneHeight",t=120,a=()=>Math.round(Math.min(window.innerHeight*.38,Math.max(t,window.innerHeight*.32))),i=(p,f)=>{let g=Number.parseFloat(String(p||"").trim());return Number.isFinite(g)?g:f},s=()=>{let p=getComputedStyle(document.body),f=document.querySelector(".app-header")?.getBoundingClientRect().height||i(p.getPropertyValue("--header-height"),64),g=i(p.getPropertyValue("--map-min-height"),220),y=document.getElementById("timelineSlider"),b=y&&!y.classList.contains("hidden")?y.getBoundingClientRect().height:0;return Math.max(t,window.innerHeight-f-g-b-6)},n=p=>Math.max(t,Math.min(s(),Math.round(p))),r=()=>{requestAnimationFrame(()=>this.mapController?.invalidateSize?.())},o=p=>{let f=`${p}px`;document.documentElement.style.setProperty("--test2-election-pane-height",f),document.body.style.setProperty("--test2-election-pane-height",f),document.querySelector(".app-shell")?.style.setProperty("--test2-election-pane-height",f)},l=(p,f={})=>{let{invalidate:g=!0,persist:y=!0}=f||{},b=n(p);if(this._electionPaneHeight=b,o(b),y)try{localStorage.setItem(e,String(b))}catch{}return g&&r(),b};try{let p=Number.parseFloat(localStorage.getItem(e)||"");Number.isFinite(p)&&l(p,{invalidate:!1,persist:!1})}catch{}let d=()=>{let p=NaN;try{p=i(localStorage.getItem(e),NaN)}catch{p=NaN}let f=this._electionPaneHeight||p;Number.isFinite(f)&&l(f,{invalidate:!0,persist:!1})};window.addEventListener("resize",()=>requestAnimationFrame(d),{passive:!0});let h=p=>{let f=p.closest?.("[data-election-pane-resize]");if(f)return f;let g=p.closest?.(".election-pane__header");return g?p.closest?.('button,a,input,select,textarea,[role="button"],[data-election-view],[data-election-entity],[data-election-result-key]')?null:document.querySelector("[data-election-pane-resize]")||g:null},u=p=>{let f=h(p.target);if(!f)return;let g=document.getElementById("electionResultsPane");if(!g?.classList.contains("election-results-pane--open"))return;p.preventDefault(),p.stopPropagation();try{f.setPointerCapture?.(p.pointerId)}catch{}document.body.classList.add("test2-election-pane-resizing"),f.setAttribute("aria-valuemin",String(t)),f.setAttribute("aria-valuemax",String(s()));let y=v=>{v.preventDefault(),v.stopPropagation();let w=l(window.innerHeight-v.clientY,{invalidate:!1,persist:!1});f.setAttribute("aria-valuenow",String(w))},b=()=>{document.body.classList.remove("test2-election-pane-resizing"),window.removeEventListener("pointermove",y),window.removeEventListener("pointerup",b),window.removeEventListener("pointercancel",b);let v=this._electionPaneHeight||g.getBoundingClientRect().height||a();l(v,{invalidate:!1,persist:!0}),r()};window.addEventListener("pointermove",y),window.addEventListener("pointerup",b),window.addEventListener("pointercancel",b)};document.addEventListener("pointerdown",u),document.addEventListener("keydown",p=>{let f=h(p.target);if(!f)return;let g=document.getElementById("electionResultsPane");if(!g?.classList.contains("election-results-pane--open"))return;let y=g.getBoundingClientRect().height||a(),b=p.shiftKey?50:20;p.key==="ArrowUp"?(p.preventDefault(),f.setAttribute("aria-valuenow",String(l(y+b)))):p.key==="ArrowDown"?(p.preventDefault(),f.setAttribute("aria-valuenow",String(l(y-b)))):p.key==="Home"?(p.preventDefault(),f.setAttribute("aria-valuenow",String(l(s())))):p.key==="End"&&(p.preventDefault(),f.setAttribute("aria-valuenow",String(l(t))))}),document.addEventListener("dblclick",p=>{h(p.target)&&(p.preventDefault(),l(a()))})}installRouteGuard(){if(window.__civgraphTest2RouteGuardInstalled)return;window.__civgraphTest2RouteGuardInstalled=!0;let e=i=>typeof i!="string"||!i.startsWith("#")?i:`${window.location.pathname}${window.location.search||""}${i}`,t=history.replaceState.bind(history),a=history.pushState.bind(history);history.replaceState=(i,s,n)=>t(i,s,e(n)),history.pushState=(i,s,n)=>a(i,s,e(n)),document.addEventListener("click",i=>{let s=i.target.closest?.('a[href^="#"]');if(!s||s.closest?.("#catalogueFlatView")||s.dataset?.catalogueTarget)return;let n=s.getAttribute("href")||"";if(i.preventDefault(),!n||n==="#")return;let r=`${window.location.pathname}${window.location.search||""}${n}`;history.pushState(null,"",r);let o=decodeURIComponent(n.slice(1));(document.getElementById(o)||document.querySelector(`[name="${CSS.escape(o)}"]`))?.scrollIntoView({block:"start"})},!0)}async loadBooks(){try{A.booksData=await P.ensureBooksLoaded()}catch(e){console.warn("[Test2] Could not load books data",e)}}scheduleIdleTask(e,{timeout:t=2e3}={}){typeof e=="function"&&("requestIdleCallback"in window?window.requestIdleCallback(e,{timeout:t}):setTimeout(e,Math.min(t,1e3)))}loadClassicScript(e,t){if(t&&globalThis[t])return Promise.resolve(globalThis[t]);if(this.classicScriptPromises.has(e))return this.classicScriptPromises.get(e);let a=new Promise((i,s)=>{let n=document.querySelector(`script[src="${e}"]`);if(n){n.addEventListener("load",()=>i(t?globalThis[t]:!0),{once:!0}),n.addEventListener("error",()=>s(new Error(`Could not load ${e}`)),{once:!0});return}let r=document.createElement("script");r.src=e,r.async=!0,r.onload=()=>i(t?globalThis[t]:!0),r.onerror=()=>s(new Error(`Could not load ${e}`)),document.head.appendChild(r)});return this.classicScriptPromises.set(e,a),a}async ensureFlatgeobufRuntime(){return this.loadClassicScript("/app/js/libs/flatgeobuf-geojson.min.js","flatgeobuf")}async ensureElections(e={}){if(this.elections?.catalogue)return this.elections;this.electionModulePromise||(this.electionModulePromise=import("./election-manager-ZWKCF5OK.js"));let{Test2ElectionManager:t}=await this.electionModulePromise;return this.elections||(this.elections=new t({app:this,mapController:this.mapController,onError:a=>this.showMapError(a)}),window.__civgraphTest2&&(window.__civgraphTest2.elections=this.elections)),this.electionLoadPromise||(this.electionLoadPromise=this.elections.load()),await this.electionLoadPromise,e.refreshCatalogue&&this.updateMapList(),this.elections}scheduleElectionCatalogueWarm(){if(this.electionCatalogueWarmScheduled||this.elections?.catalogue)return;this.electionCatalogueWarmScheduled=!0;let e=()=>{this.ensureElections({refreshCatalogue:!0}).catch(s=>{console.warn("[Test2] Election catalogue warmup failed",s)})},t=new URLSearchParams(window.location.hash.replace(/^#/,"")),i=this.hasElectionURLState(t,ot(t.get("layers")))?1200:6e3;this.scheduleIdleTask(e,{timeout:i})}hasElectionURLState(e,t=[]){return[...t].some(a=>String(a).startsWith("election-"))?!0:e.has("electionBody")||e.has("electionDate")||e.has("electionMode")||e.has("electionView")}wireUiCallbacks(){A.onBuildElectionCatalogueCards=async()=>this.elections?.catalogue?this.elections.buildCatalogueCards():(this.scheduleElectionCatalogueWarm(),[]),A.onLoadElection=async(e,t)=>{try{await(await this.ensureElections()).loadElection(e,t),this.updateMapList(),this.focusActiveElectionCatalogueEntry(this.elections?.activeEntry,{scroll:!1})}catch(a){this.showMapError(a)}},A.onUnloadElection=()=>{this.elections?.unloadElection(),this.updateMapList()},A.onCheckElectionLoaded=(e,t)=>this.elections?.isElectionLoaded(e,t)||!1,A.onSetupElectionTableControls=()=>{},A.onOpenElectionEntityDetail=async(e,t)=>this.openElectionEntityDetailInCatalogue(e,t),A.onOpenElectionConstituencyFeature=async({constituency:e,level:t})=>{let a=t==="council"?"lgd":t==="dea"?"dea":"constituency";return this.openElectionEntityDetailInCatalogue(a,e)},A.onSplitChange=()=>{this.mapController.invalidateSize(),this.updateURLState()},A.onMapLoad=async e=>{await this.stopTimelineAnimation({restoreOriginal:!1}),await this.loadMap(e),this.syncCatalogueMapState(),this.updateActiveLayers(),this.dismissMobileCatalogueAfterLoad(),this.updateURLState(),this.recordSettleOutcome(e,await this.mapController.waitUntilSettled())},A.onMapUnload=async e=>{if(await this.stopTimelineAnimation({restoreOriginal:!1}),this.unloadActiveElectionForLayer(e)){this.updateMapList();return}let t=P.getMapById(e);this.mapController.getLayerState(e)?.isGroup?this.mapController.unloadLayer(e):t?.isGroup&&oe(t).length?oe(t).forEach(a=>this.mapController.unloadLayer(a)):t?.isGroup&&Array.isArray(t.variants)?t.variants.forEach(a=>this.mapController.unloadLayer(a.id)):this.mapController.unloadLayer(e),this.syncCatalogueMapState(),this.updateActiveLayers(),this.updateURLState(),await this.mapController.waitUntilSettled(),this.settleOutcomes?.delete(e)},A.onMapToggle=e=>{this.isTimelineAnimationLayer(e)&&this.pauseTimelineAnimation({preserveOverlay:!1}),this.mapController.toggleLayer(e),this.syncCatalogueMapState(),this.updateActiveLayers(),this.updateURLState()},A.onHideMap=e=>{this.isTimelineAnimationLayer(e)&&this.pauseTimelineAnimation({preserveOverlay:!1}),this.mapController.hideLayer(e),this.syncCatalogueMapState(),this.updateActiveLayers(),this.updateURLState()},A.onCheckMapLoaded=e=>this.isMapLoaded(e),A.onCheckMapSettled=e=>this.settleOutcomes?.get(e)||"unknown",A.onCheckMapVisible=e=>this.isMapVisible(e),A.onReorderLayers=e=>this.setActiveLayerOrder(e),A.onExpandToFullMap=async e=>this.loadMap(e),A.onPartialFeatureToggle=(e,t)=>{this.mapController.togglePartialFeature(e,t),this.syncCatalogueMapState(),this.updateActiveLayers(),this.updateURLState()},A.onPartialFeatureUnload=(e,t)=>{this.mapController.unloadPartialFeature(e,t),this.syncCatalogueMapState(),this.updateActiveLayers(),this.updateURLState()},A.onCheckFeatureLoaded=(e,t)=>this.mapController.isFeatureLoaded(e,t),A.onCheckFeatureVisible=(e,t)=>this.mapController.isFeatureVisible(e,t),A.onFeatureLoad=async(e,t,a,i,s={})=>{let n=P.getMapById(e);if(!n)return null;let r=await this.mapController.loadSingleFeature(n,t,a,i,{isolate:s.isolate===!0});return this.syncCatalogueMapState(),this.updateActiveLayers(),this.updateURLState(),r},A.onCategoryChange=e=>{this.currentCategory=e,this.updateMapList(),this.updateURLState()},A.onProviderCategoryChange=(e,t)=>{this.currentProviderCategory=e,this.currentProviderList=t||[],this.updateMapList(),this.updateURLState()},A.onAuthorFilter=e=>{this.currentAuthor=!e||e.length===0?"all":e,this.updateMapList(),this.updateURLState()},A.onDownloadFgb=async e=>{let t=P.getMapById(e),a=ht(t);a&&this.triggerDownload(a,a.split("/").pop())},A.onAddressSelect=(e,t,a)=>this.mapController.addAddressMarker(e,t,a),A.onRemoveAddressMarker=()=>this.mapController.removeAddressMarker(),A.onCheckIntersection=async(e,t)=>this.mapController.queryFeaturesAtLngLat(e,t),A.onGetLoadedFeatures=()=>this.mapController.getLoadedFeatures(),A.onZoomToBbox=(e,t)=>this.mapController.fitToBounds(e,t),A.onHighlightFeature=(e,t,a)=>this.mapController.highlightFeature(e,t,a),A.onLoadSingleFeature=async(e,t,a,i,s={})=>{let n=P.getMapById(e);if(!n)return null;let r=await this.mapController.loadSingleFeature(n,t,a,i,{isolate:s.isolate!==!1});return this.syncCatalogueMapState(),this.updateActiveLayers(),this.updateURLState(),s.showInfo!==!1&&A.showFeatureInfo([{...r.feature,mapId:e,id:t}],P.getAllMaps()),r}}installCatalogueStateBridge(){if(A.__test2CatalogueStateBridgeInstalled)return;A.__test2CatalogueStateBridgeInstalled=!0;let e=A.showCatalogueDetailView.bind(A);A.showCatalogueDetailView=(a,i=!0)=>{let s=e(a,i);return this.currentDetailMapId=a||null,this.updateURLState(),s};let t=A.showCatalogueListView.bind(A);A.showCatalogueListView=(a=!1)=>{let i=t(a);return this.currentDetailMapId=null,this.updateURLState(),i}}setupURLStateListener(){window.addEventListener("hashchange",()=>{this._suspendURLState||this._restoringURLState||this.restoreURLState({updateAfterRestore:!1}).catch(e=>this.showMapError(e))})}async loadMap(e,t={}){let a=P.getMapById(e);if(a?.isGroup&&oe(a).length){let s=oe(a);await Promise.all(s.map(n=>this.loadMap(n,{fit:t.fit!==!1}))),this.mapController.markGroupLoaded(e,a,s);return}if(a?.isGroup&&Array.isArray(a.variants)&&a.variants.length){let s=a.variants.map(n=>n?.id).filter(n=>this.mapController.resolveLayer(n)?.loadable);await Promise.all(s.map(n=>this.mapController.loadLayer(n,{fit:!1}))),this.mapController.markGroupLoaded(e,a,s),t.fit!==!1&&(a.bounds?this.mapController.fitToBounds(a.bounds,{smooth:!1}):this.mapController.fitToLayers(s));return}if(!this.mapController.resolveLayer(a?.id||e)?.loadable){let s=this.getCivilParishesCompositeChildIds(e,a);if(s.length){let r=a||P.getMapById("civil-parishes-by-province")||{id:e,name:"Civil Parishes of Ireland"};await Promise.all(s.map(o=>this.mapController.loadLayer(o,{fit:!1}))),this.mapController.markGroupLoaded(r.id||e,r,s),t.fit!==!1&&(r.bounds?this.mapController.fitToBounds(r.bounds,{smooth:!1}):this.mapController.fitToLayers(s));return}let n=this.getConvertedCompositeChildIds(a);if(n.length){await Promise.all(n.map(r=>this.mapController.loadLayer(r,{fit:!1}))),this.mapController.markGroupLoaded(a.id,a,n),t.fit!==!1&&a.bounds&&this.mapController.fitToBounds(a.bounds,{smooth:!1});return}}await this.mapController.loadLayer(a||e,{fit:t.fit!==!1})}getCivilParishesCompositeChildIds(e,t){return[...new Set([e,t?.id,t?.classId,t?.slug].filter(Boolean))].some(s=>En.has(s))?Mn.filter(s=>this.mapController.resolveLayer(s)?.loadable):[]}getConvertedCompositeChildIds(e){if(!e)return[];let t=Array.isArray(e.compositeSources)?e.compositeSources:[],a=!e.isGroup&&Array.isArray(e.variants)?e.variants.map(s=>s.id):[];return[...new Set([...t,...a].filter(Boolean))].filter(s=>this.mapController.resolveLayer(s)?.loadable)}isPlaceholderTimelineMap(e){if(!e)return!0;let t=[...Array.isArray(e.keywords)?e.keywords:[],...Array.isArray(e.rawMetadata?.keywords)?e.rawMetadata.keywords:[]].map(i=>String(i).trim().toLowerCase()),a=String(e.status||e.rawMetadata?.status||"").toLowerCase();return!!(e.placeholder||e.rawMetadata?.placeholder||e.thumbnail?.kind==="placeholder"||t.includes("placeholder")||t.includes("to-be-added")||t.includes("to be added")||a.includes("to be added"))}isTimelineMapPlayable(e){if(!e)return!1;let t=P.getMapById(e);return!t||this.isPlaceholderTimelineMap(t)?!1:this.mapController.resolveLayer(t.id||e)?.loadable?!0:t.isGroup&&oe(t).length?oe(t).some(i=>this.isTimelineMapPlayable(i)):t.isGroup&&Array.isArray(t.variants)&&t.variants.length?t.variants.some(i=>this.mapController.resolveLayer(i?.id)?.loadable):this.getConvertedCompositeChildIds(t).length>0}renderCategoryPills(){A.renderCategoryPills(P.getMapCategories(),this.currentCategory),A.renderProviderPills(this.currentProviderCategory)}updateMapList(){let e=P.getAllMaps(),t=P.getMapsByCategory(this.currentCategory);if(this.currentAuthor!=="all"){let i=Array.isArray(this.currentAuthor)?this.currentAuthor:[this.currentAuthor];t=t.filter(s=>i.some(n=>s.provider?.includes(n)))}this.currentProviderCategory!=="all-providers"&&this.currentProviderList.length>0&&(t=t.filter(i=>(Array.isArray(i.provider)?i.provider:i.provider?[i.provider]:[]).some(n=>this.currentProviderList.includes(n)))),this.searchQuery&&(t=this.searchMapsForCatalogue(this.searchQuery,e),this.currentCategory!=="all"&&(t=t.filter(i=>i.category===this.currentCategory)));let a=new Map;t.forEach(i=>{let s=ye.getFeatureCount(i.id);s>0&&a.set(i.id,s)}),A.renderMapList(t,{visibleIds:this.mapController.getVisibleLayers(),loadedIds:this.getLoadedLayerIds(),featureCounts:a,totalMaps:this.publicMapCount(),shownMaps:Math.min(t.length,this.publicMapCount())})}publicMapCount(){let e=this.metadataService?.metadata?.publicMapCount;if(Number.isFinite(e))return e;let t=new Set((this.metadataService?.layers||[]).map(a=>a.sourceMapId).filter(Boolean));return Sa(P.maps?.maps||[],a=>t.has(a)).length}focusActiveElectionCatalogueEntry(e,t={}){if(!e?.body||!e?.date)return;let a=()=>{this.searchQuery="",this.currentCategory="all",this.currentProviderCategory="all-providers",this.currentProviderList=[];let d=document.getElementById("searchInput");d&&(d.value=""),document.getElementById("searchClear")?.classList.remove("visible"),A.showCatalogueListView?.(!1),this.updateMapList()},i=async()=>{let d=Number.parseInt(String(e.date).slice(0,4),10);if(!Number.isFinite(d))return;let h=`${Math.floor(d/10)*10}s`,p=[...document.querySelectorAll("#catalogueFlatView .catalogue-flat__toc-decade-btn")].find(f=>f.textContent.trim()===h)?.dataset?.catalogueTarget;p&&await A.ensureCatalogueTargetRendered?.(p,"elections")},s=8e3,n=120,r=performance.now()+s,o=!1,l=()=>{let d=[...document.querySelectorAll("#catalogueFlatView .flat-election-entry")],h=d.find(u=>u.dataset.electionBody===e.body&&u.dataset.electionDate===e.date);if(!h){if(performance.now()>=r)return;o||(o=!0,a()),Promise.resolve(i()).catch(()=>{}).then(()=>setTimeout(l,n));return}if(d.forEach(u=>{let p=u===h;u.classList.toggle("class-member--loaded",p),u.classList.toggle("flat-election-entry--active",p);let f=u.querySelector(".election-load-btn");f&&f.setAttribute("title",p?"Unload":"Load")}),h.querySelector(".election-load-btn")?.setAttribute("title","Unload"),t.scroll){let u=h.closest(".pane__content")||document.querySelector('.pane__content[data-tab-content="catalogue"]');u?.scrollTo?u.scrollTo({top:Math.max(0,h.offsetTop-72),behavior:"auto"}):h.scrollIntoView({block:"nearest"})}};requestAnimationFrame(()=>requestAnimationFrame(l))}setupSearch(){A.initializeFuse=()=>{A.fuse=null,A.searchItems=[]};let e=(t,a=1e3)=>this.searchCatalogueWithWorker(t,a);A.performSearch=async t=>{let a=String(t||"").trim();if(A.hideAutocomplete?.(),this.searchQuery=a,A._catalogueSearchQuery=a,!a)return this.workerSearchQuery="",this.workerSearchResultIds=null,A.clearCatalogueSearchResults?.({render:!0}),this.updateURLState(),[];let i=await e(a,1e3);return this.searchQuery!==a?[]:(this.workerSearchQuery=a,this.workerSearchResultIds=i,await A.renderCatalogueSearchResults?.(a,{mapResultIds:i,mapResultsProvider:e}),this.updateURLState(),i)},A.onSearch=t=>{let a=String(t||"").trim();if(this.searchQuery=a,A._catalogueSearchQuery=a,!a){this.workerSearchQuery="",this.workerSearchResultIds=null,A.clearCatalogueSearchResults?.({render:!0}),this.updateMapList(),this.updateURLState();return}A.performSearch(a).catch(i=>{console.warn("[App] Catalogue search failed:",i)})},A.setupSearch(),document.addEventListener("click",t=>{t.target.closest(".overflow-menu")||document.querySelectorAll(".overflow-menu--open").forEach(a=>a.classList.remove("overflow-menu--open"))})}prepareSearchWorker(){if("Worker"in window)try{this.searchWorker=new Worker("/app/src/search-worker.js?v=app-search-001",{type:"module"}),this.searchWorker.addEventListener("message",e=>{let t=e.data||{};if(t.type==="ready"){this.searchWorkerReady=!0;return}if(t.type==="results"){let a=this.searchWorkerCallbacks.get(t.seq);if(!a)return;this.searchWorkerCallbacks.delete(t.seq),a.resolve(Array.isArray(t.ids)?t.ids:[])}}),this.searchWorker.addEventListener("error",()=>{this.searchWorkerReady=!1}),this.searchWorker.postMessage({type:"init",maps:P.getAllMaps().map(e=>({id:e.id,name:e.name,category:e.category,group:e.group,provider:e.provider,description:e.description,date:e.date,dateRange:e.dateRange,keywords:e.keywords}))})}catch(e){console.warn("[Test2] Search worker unavailable",e),this.searchWorker=null}}async searchCatalogueWithWorker(e,t=200){let a=String(e||"").trim();if(!a||a.length<1)return[];if(!this.searchWorker)return this.simpleSearchMapIds(a,t);let i=++this.searchWorkerSeq;return new Promise(s=>{let n=setTimeout(()=>{this.searchWorkerCallbacks.delete(i),s(this.simpleSearchMapIds(a,t))},900);this.searchWorkerCallbacks.set(i,{resolve:r=>{clearTimeout(n),s(r)}}),this.searchWorker.postMessage({type:"search",query:a,limit:t,seq:i})})}searchMapsForCatalogue(e,t){if(this.workerSearchQuery===e&&Array.isArray(this.workerSearchResultIds)){let i=new Set(this.workerSearchResultIds);return t.filter(s=>i.has(s.id))}let a=new Set(this.simpleSearchMapIds(e,1e3));return t.filter(i=>a.has(i.id))}simpleSearchMapIds(e,t=200){let a=la(e).split(/\s+/).filter(Boolean);return a.length?P.getAllMaps().map(i=>{let s=la([i.id,i.name,i.category,i.group,i.provider,i.description,i.date,i.dateRange,...Array.isArray(i.keywords)?i.keywords:[]].flat().filter(Boolean).join(" ")),n=la(i.name||"");if(!a.every(o=>s.includes(o)))return null;let r=a.reduce((o,l)=>o+(n.startsWith(l)?100:n.includes(l)?60:10),0);return{id:i.id,score:r,name:i.name||""}}).filter(Boolean).sort((i,s)=>s.score-i.score||i.name.localeCompare(s.name)).slice(0,t).map(i=>i.id):[]}setupThemeToggle(){if(document.querySelector(".app-header[data-site-chrome]")){this.syncBasemapToTheme(),document.addEventListener("civgraph:themechange",()=>{this.syncBasemapToTheme()});return}let e=[document.getElementById("themeToggle"),document.getElementById("themeToggleMobile")].filter(Boolean),t=localStorage.getItem("theme"),a=window.matchMedia?.("(prefers-color-scheme: dark)").matches;document.documentElement.dataset.theme=t||(a?"dark":"light"),this.syncBasemapToTheme(),e.forEach(i=>{i.addEventListener("click",()=>{let s=document.documentElement.dataset.theme==="dark"?"light":"dark";document.documentElement.dataset.theme=s,localStorage.setItem("theme",s),this.syncBasemapToTheme()})})}setupSupportModal(){if(document.querySelector(".app-header[data-site-chrome]"))return;let e=document.getElementById("supportModal"),t=[document.getElementById("supportBtn"),document.getElementById("mobileSupportBtn")].filter(Boolean);if(!e||t.length===0)return;let a='a[href], button:not([disabled]), textarea, input, select, [tabindex]:not([tabindex="-1"])',i=null,s=()=>[...e.querySelectorAll(a)].filter(d=>d.offsetParent!==null),n=d=>{if(d.key!=="Tab")return;let h=s();if(!h.length)return;let u=h[0],p=h[h.length-1];d.shiftKey&&(document.activeElement===u||!e.contains(document.activeElement))?(d.preventDefault(),p.focus()):!d.shiftKey&&(document.activeElement===p||!e.contains(document.activeElement))&&(d.preventDefault(),u.focus())},r=()=>[...document.body.children].filter(d=>d!==e),o=()=>{i=document.activeElement,e.classList.remove("hidden"),r().forEach(d=>{d.setAttribute("aria-hidden","true"),"inert"in d&&(d.inert=!0)}),document.addEventListener("keydown",n,!0),(s()[0]||e).focus()},l=()=>{e.classList.add("hidden"),r().forEach(d=>{d.removeAttribute("aria-hidden"),"inert"in d&&(d.inert=!1)}),document.removeEventListener("keydown",n,!0),i&&typeof i.focus=="function"&&document.contains(i)&&i.focus(),i=null};t.forEach(d=>d.addEventListener("click",h=>{h.preventDefault(),o()})),e.querySelector(".support-modal__backdrop")?.addEventListener("click",l),e.querySelector(".support-modal__close")?.addEventListener("click",l),document.addEventListener("keydown",d=>{d.key==="Escape"&&!e.classList.contains("hidden")&&l()})}setupOverlayEscape(){document.addEventListener("keydown",e=>{if(e.key!=="Escape"||e.defaultPrevented)return;let t=document.activeElement;if(t&&(t.tagName==="INPUT"||t.tagName==="TEXTAREA"||t.isContentEditable))return;let a=document.getElementById("supportModal");if(a&&!a.classList.contains("hidden"))return;let i=document.getElementById("featureInfo");if(i&&!i.classList.contains("hidden")){A.hideFeatureInfo?.();return}if(document.getElementById("activeLayersToggle")?.getAttribute("aria-expanded")==="true"){this.setActiveLayersPanelOpen(!1),document.getElementById("activeLayersToggle")?.focus({preventScroll:!0});return}document.getElementById("mapControlsToggle")?.getAttribute("aria-expanded")==="true"&&(this.setMapControlsOpen(!1),document.getElementById("mapControlsToggle")?.focus({preventScroll:!0}))})}setupMapControls(){let e=document.getElementById("mapControlsToggle"),t=document.getElementById("mapControlPanel"),a=document.getElementById("mapControlsClose"),i=document.getElementById("activeLayersToggle"),s=document.getElementById("activeLayers"),n=document.getElementById("activeLayersClose"),r=document.getElementById("featureInfoClose");e?.addEventListener("click",()=>{this.setMapControlsOpen(e.getAttribute("aria-expanded")!=="true")}),a?.addEventListener("click",()=>this.setMapControlsOpen(!1));let o=document.getElementById("overlayToggle"),l=document.getElementById("overlayList");o?.addEventListener("click",()=>{let v=o.getAttribute("aria-expanded")!=="true";o.setAttribute("aria-expanded",String(v)),l?.classList.toggle("overlay-list--collapsed",!v),l?.classList.toggle("overlay-list--expanded",v)}),document.getElementById("baseMapSelect")?.addEventListener("change",async v=>{await this.applyBaseMap(v.target.value||"osm-standard",{userChoice:!0}),this.updateURLState()});let d=document.getElementById("transparencySlider"),h=document.getElementById("transparencyValue");d?.addEventListener("input",()=>{let v=Number(d.value);this.mapController.setTransparency(v),h&&(h.textContent=`${v}%`),this.updateURLState()});let u=document.getElementById("fillTransparencySlider"),p=document.getElementById("fillTransparencyValue");u?.addEventListener("input",()=>{let v=Number(u.value);this.mapController.setFillTransparency(v),p&&(p.textContent=`${v}%`),this.updateURLState()}),document.getElementById("labelsToggle")?.addEventListener("change",v=>{this.mapController.setLabelsEnabled(v.target.checked),this.updateURLState()});let f=Number(De("textScale")||"100"),g=[50,60,70,80,90,100,110,125,150,175,200],y=document.getElementById("textSizeValue"),b=()=>{y&&(y.textContent=`${f}%`),this.mapController.setTextScale(f),Ye("textScale",f),this.updateURLState()};document.getElementById("textSizeDecrease")?.addEventListener("click",()=>{let v=g.indexOf(f);f=g[Math.max(0,v-1)]||100,b()}),document.getElementById("textSizeIncrease")?.addEventListener("click",()=>{let v=g.indexOf(f);f=g[Math.min(g.length-1,v+1)]||100,b()}),b(),i?.addEventListener("click",()=>{this.setActiveLayersPanelOpen(i.getAttribute("aria-expanded")!=="true")}),n?.addEventListener("click",()=>this.setActiveLayersPanelOpen(!1)),r?.addEventListener("click",()=>A.hideFeatureInfo()),document.getElementById("conditionalStylingBtn")?.addEventListener("click",()=>{this.showMapError(new Error("Conditional styling controls use MapLibre expressions; this route currently supports base opacity, labels, and text scale."))}),this.mapController.map?.on("moveend",()=>this.updateURLState())}setupPerformanceDashboard(){document.getElementById("performanceDashboard")?.setAttribute("hidden","");let e=document.getElementById("performanceDashboardRefresh"),t=()=>this.renderPerformanceDashboard().catch(a=>{let i=document.getElementById("performanceDashboardStatus");i&&(i.textContent=`Performance status unavailable: ${a?.message||a}`)});e?.addEventListener("click",t)}async openElectionEntityDetailInCatalogue(e,t){let a=await this.loadElectionEntityBrowseDetail(e,t);return a?(A.showElectionEntityDetailInCatalogue(a,!0),!0):!1}async loadElectionEntityBrowseDetail(e,t){let a=String(e||"").toLowerCase(),i=`${a}:${t||""}`;if(this.browseEntityDetailCache.has(i))return this.browseEntityDetailCache.get(i);let s=null;return a==="party"?s=await this.loadPartyBrowseDetail(t):a==="candidate"?s=await this.loadPersonBrowseDetail(t):["constituency","dea","lgd"].includes(a)&&(s=await this.loadAreaBrowseDetail(a,t)),s&&this.browseEntityDetailCache.set(i,s),s}async loadPartyBrowseDetail(e){let t=$e(e),a=[...new Set([t,String(e||"").trim().toLowerCase()].filter(Boolean))];for(let i of a)try{let s=await fetch(`/data/browse/details/parties/${encodeURIComponent(i)}.json`,{cache:"force-cache"});if(!s.ok)continue;let n=await s.json(),r=n.item||n,o=await this.loadPartyPersons(r);return this.mapPartyBrowseItem(r,o)}catch(s){console.warn("[Test2] Party Browse detail unavailable",i,s)}return null}async loadPersonBrowseDetail(e){let t=$e(e),a=String(e||"").split("|")[0].trim(),i=$e(a);for(let n of[...new Set([t,i].filter(Boolean))])try{let r=await fetch(`/_api/persons?slug=${encodeURIComponent(n)}`,{cache:"force-cache"});if(r.status===404)continue;if(!r.ok)break;let o=await r.json();if(o?.person)return this.mapPersonBrowseItem(o.person)}catch{break}let s=await this.findBrowsePerson(n=>{let r=[n.slug,n.id,n.name,n.title].map($e);return r.includes(t)||i&&r.includes(i)});return s?this.mapPersonBrowseItem(s):null}async loadPartyPersons(e={}){let t=[...new Set([e.canonicalName,e.title,...e.observedNames||[],...e.knownAliases||[]].filter(Boolean))];if(!t.length)return[];let a=new URLSearchParams;for(let i of t)a.append("party",i);a.set("limit","200");try{let i=await fetch(`/_api/persons?${a}`,{cache:"force-cache"});if(i.ok){let s=await i.json();if(Array.isArray(s?.persons))return s.persons}}catch{}return this.loadBrowsePersonsIndex().catch(()=>[])}async loadAreaBrowseDetail(e,t){let a=String(t||"").trim();if(!a)return null;let i=await this.ensureElections(),s=Array.isArray(i?.catalogue?.elections)?i.catalogue.elections:[],n=Pe(a),r=[];for(let l of s){if(!(e==="lgd"?[...l.localBodies||[],l.body]:l.constituencies||[]).some(f=>Pe(f)===n)&&!(e==="constituency"&&l.key===this.elections?.activeEntry?.key))continue;let u=null;try{u=await i.loadBundle(l)}catch{continue}let p=(u.results||[]).filter(f=>e==="lgd"?Pe(f.localBody||f.localGovernmentDistrict||f.council||f.bodyLabel||"")===n:Pe(f.constituency||f.matchName||f.featureName||"")===n);if(p.length)if(e==="lgd")r.push(this.mapCouncilAreaHistoryRow(l,u,a,p));else for(let f of p)r.push(this.mapConstituencyAreaHistoryRow(l,u,f,e))}if(r.sort((l,d)=>String(d.date||"").localeCompare(String(l.date||""))||String(l.electionDisplayName||"").localeCompare(String(d.electionDisplayName||""))),!r.length)return null;let o={elections:r.length,districts:[...new Set(r.map(l=>Pe(l.localGovernmentDistrict)).filter(Boolean))].length,deas:e==="lgd"?r.reduce((l,d)=>l+Number(d.deaCount||0),0):r.length,totalValidVotes:r.reduce((l,d)=>l+Number(d.validVotes||0),0),totalSeats:r.reduce((l,d)=>l+Number(d.seats||0),0),latestDate:r[0]?.date||null};return{kind:e,key:$e(a),name:a,colour:r[0]?.winnerColour||"#64748b",subtitle:e==="lgd"?"Local Government District / Council":e==="dea"?"District Electoral Area":"Constituency",metrics:o,historyRows:r}}installLazyCatalogueDataBridge(){if(A.__test2LazyCatalogueDataBridgeInstalled)return;A.__test2LazyCatalogueDataBridgeInstalled=!0;let e=A.ensureCatalogueTargetRendered?.bind(A);e&&(A.ensureCatalogueTargetRendered=async(a,i=null)=>((i||A._flatTargetToSection?.get?.(a))==="books"&&await this.loadBooks(),e(a,i)));let t=A.openCatalogueBookViewer?.bind(A);t&&(A.openCatalogueBookViewer=async(...a)=>(await this.loadBooks(),t(...a)))}installLazyRuntimeHelpersBridge(){if(A.__test2LazyRuntimeHelpersBridgeInstalled)return;A.__test2LazyRuntimeHelpersBridgeInstalled=!0;let e=A.downloadFeature?.bind(A);e&&(A.downloadFeature=async(a,i)=>(i==="fgb"&&await this.ensureFlatgeobufRuntime(),e(a,i)));let t=A.loadAttributeSchema?.bind(A);t&&(A.loadAttributeSchema=async(...a)=>(await this.ensureFlatgeobufRuntime(),t(...a)))}async fetchBrowseIndexItems(e){let t=await fetch(e,{cache:"force-cache"});if(!t.ok)throw new Error(`Browse index failed: ${t.status} ${e}`);let a=await t.json();return a?.indexLayout==="sharded"&&Array.isArray(a.shards)?(await Promise.all(a.shards.map(s=>this.fetchBrowseIndexItems(s.url)))).flat():Array.isArray(a.items)?a.items:[]}async loadBrowsePersonsIndex(){return this.browsePersonsIndexPromise||(this.browsePersonsIndexPromise=this.fetchBrowseIndexItems("/data/browse/persons.json")),this.browsePersonsIndexPromise}async findBrowsePerson(e){if(this.browsePersonsIndexPromise)return(await this.browsePersonsIndexPromise).find(e)||null;let t=await fetch("/data/browse/persons.json",{cache:"force-cache"});if(!t.ok)return null;let a=await t.json();if(!(a?.indexLayout==="sharded"&&Array.isArray(a.shards)))return(Array.isArray(a.items)?a.items:[]).find(e)||null;for(let i of a.shards){let n=(await this.fetchBrowseIndexItems(i.url).catch(()=>[])).find(e);if(n)return n}return null}mapPartyBrowseItem(e,t=[]){let a=Array.isArray(e.relatedElections)?e.relatedElections:[],i=r=>a.find(o=>r.test(`${o.key||""} ${o.title||""}`)),s=a.map(r=>this.mapPartyHistoryRow(r)),n=this.buildPartyCandidateSummaries(e,t);return{kind:"party",key:e.slug||$e(e.canonicalName||e.title),name:e.canonicalName||e.title||e.slug||"",colour:e.colour||e.color||e.partyColour||"#6b7280",latestWestminster:s.find(r=>/Westminster/i.test(r.electionType))||i(/house-of-commons|UK general|Westminster/i),latestAssembly:s.find(r=>/Assembly/i.test(r.electionType))||i(/northern-ireland-assembly|Assembly/i),historyRows:s,partySummaries:s,candidateSummaries:n,totals:e.totals||{},observedNames:e.observedNames||[],knownAliases:e.knownAliases||[],firstYear:e.firstYear,lastYear:e.lastYear}}mapPersonBrowseItem(e){let t=Array.isArray(e.elections)?e.elections:[],a=t[0]||null,i=t.map(s=>this.mapPersonAppearanceRow(s));return{kind:"candidate",key:e.slug||e.id||$e(e.name||e.title),personId:e.id||e.slug||"",name:e.name||e.title||"",latestParty:a?.party||e.parties?.[0]?.name||"",parties:(e.parties||[]).map(s=>s.name||s).filter(Boolean),dates:[...new Set(t.map(s=>String(s.year||s.date||"")).filter(Boolean))],constituencies:(e.constituencies||[]).map(s=>s.name||s).filter(Boolean),constituencyEntries:t.map(s=>({body:Tt(s.key),date:s.date||"",constituency:s.constituency||"",level:xt(s.key,s.title)==="Local"?"dea":"constituency",elected:!!s.elected,mapLayerYear:s.year||String(s.date||"").slice(0,4)})),appearances:i,firstPrefs:e.totals?.firstPrefs||0,electedCount:e.totals?.elected||0,shareOfAllValid:null,latestAppearance:i[0]||a}}mapPartyHistoryRow(e={}){let t=Tt(e.key)||e.body||"",a=xt(e.key,e.title),i=e.totalSeats??null,s=e.seats??e.elected??null,n=e.stood??e.candidates??null;return{electionDisplayName:e.title||e.key||"",electionBodyForOpen:t,body:t,bodyLabel:t,date:e.date||"",electionType:a,rank:e.rank??null,rankDelta:e.rankDelta??null,contested:!/referendum|recall/i.test(`${e.title||""} ${e.key||""}`),isRecallPetition:/recall petition/i.test(`${e.title||""} ${e.key||""}`),isByElection:/by-election/i.test(`${e.title||""} ${e.key||""}`),stood:n,stoodDelta:e.stoodDelta??null,elected:s,electedDelta:e.electedDelta??e.seatsDelta??null,totalSeats:i,totalSeatsDelta:e.totalSeatsDelta??null,seatPct:i?Number(s||0)/Number(i)*100:null,seatPctDelta:e.seatPctDelta??null,constituenciesContested:e.constituenciesContested??e.constituencies??null,constituenciesContestedDelta:e.constituenciesContestedDelta??null,totalConstituencies:e.totalConstituencies??null,totalConstituenciesDelta:e.totalConstituenciesDelta??null,firstPrefs:e.votes??e.firstPrefs??null,firstPrefsDelta:e.votesDelta??e.firstPrefsDelta??null,validVotePct:e.share??e.validVotePct??null,validVotePctDelta:e.shareDelta??e.validVotePctDelta??null,bodyGroup:e.bodyGroup||null}}mapPersonAppearanceRow(e={}){let t=Tt(e.key),a=xt(e.key,e.title),i=e.firstPref??e.firstPrefs??e.votes??null;return{electionDisplayName:e.title||e.key||"",electionBodyForOpen:t,body:t,bodyLabel:a==="Local"&&(e.localBody||e.bodyLabel)||t,date:e.date||"",constituency:e.constituency||"",party:e.party||"",status:e.status||(e.elected?"Elected":""),rank:e.rank||null,firstPref:i,firstPrefs:i,firstPrefPct:e.firstPrefPct??e.share??null,elected:!!e.elected,electionType:a,isByElection:/by-election/i.test(`${e.title||""} ${e.key||""}`),overallStandingNumber:e.overallStandingNumber??null,overallElectedNumber:e.overallElectedNumber??null,bodyStandingNumber:e.bodyStandingNumber??null,bodyElectedNumber:e.bodyElectedNumber??null}}buildPartyCandidateSummaries(e={},t=[]){let a=new Set([e.canonicalName,e.title,...e.observedNames||[],...e.knownAliases||[]].map(Pe).filter(Boolean)),i=new Map;for(let s of t||[])for(let n of s.elections||[]){if(!a.has(Pe(n.party)))continue;let r=s.id||s.slug||$e(s.name||s.title);i.has(r)||i.set(r,{personId:r,name:s.name||s.title||r,totalFirstPrefs:0,timesStood:0,timesStoodLocal:0,timesStoodDevolved:0,timesStoodWestminster:0,timesStoodEuropean:0,timesElected:0,timesElectedLocal:0,timesElectedDevolved:0,timesElectedWestminster:0,timesElectedEuropean:0,constituencyEntries:[]});let o=i.get(r),l=xt(n.key,n.title),d=$n(l);o.totalFirstPrefs+=Number(n.firstPref??n.firstPrefs??n.votes??0)||0,o.timesStood+=1,d&&(o[`timesStood${d}`]+=1),n.elected&&(o.timesElected+=1,d&&(o[`timesElected${d}`]+=1)),n.constituency&&o.constituencyEntries.push({body:Tt(n.key),date:n.date||"",constituency:n.constituency,level:l==="Local"?"dea":"constituency",elected:!!n.elected,mapLayerYear:n.year||String(n.date||"").slice(0,4)})}return[...i.values()].sort((s,n)=>n.timesElected-s.timesElected||n.totalFirstPrefs-s.totalFirstPrefs||n.timesStood-s.timesStood||s.name.localeCompare(n.name))}mapConstituencyAreaHistoryRow(e,t,a,i){let s=a.winnerParty||a.leadingParty||"",n=a.leadingVotes??a.winnerVotes??null,r=a.validPoll??a.totalVotes??null;return{electionDisplayName:t.displayTitle||e.displayTitle||e.title||e.key||"",electionBodyForOpen:t.body||e.body||"",body:t.body||e.body||"",date:t.date||e.date||"",localGovernmentDistrict:a.localBody||a.localGovernmentDistrict||"",winnerParty:s,winnerColour:a.winnerColour||a.leadingColour||a.colour||"#b0bec5",winnerVotes:n,winnerPct:a.leadingPct??a.winnerPct??(r&&n?Number(n)/Number(r)*100:null),validVotes:r,seats:a.seatsTotal??a.seatsWon??null,isByElection:/by-election/i.test(`${t.displayTitle||e.displayTitle||""}`),areaKind:i}}mapCouncilAreaHistoryRow(e,t,a,i){let s=new Map,n=0,r=0;for(let l of i){n+=Number(l.validPoll||0),r+=Number(l.seatsTotal??l.seatsWon??0)||0;for(let d of l.candidates||[]){let h=d.party||l.leadingParty||"Independent",u=Pe(h),p=s.get(u)||{party:h,votes:0,colour:d.colour||l.leadingColour||"#b0bec5"};p.votes+=Number(d.firstPrefs??d.votes??0)||0,s.set(u,p)}}let o=[...s.values()].sort((l,d)=>d.votes-l.votes)[0]||{};return{electionDisplayName:t.displayTitle||e.displayTitle||e.title||e.key||"",electionBodyForOpen:t.body||e.body||"",body:t.body||e.body||"",date:t.date||e.date||"",deaCount:i.length,districtElectoralAreas:i.map(l=>l.constituency).filter(Boolean),winnerParty:o.party||"",winnerColour:o.colour||"#b0bec5",winnerVotes:o.votes||null,winnerPct:n&&o.votes?o.votes/n*100:null,validVotes:n,seats:r,isByElection:/by-election/i.test(`${t.displayTitle||e.displayTitle||""}`),localGovernmentDistrict:a}}async renderPerformanceDashboard(){let e=document.getElementById("performanceDashboardStatus");if(!e)return;let t=await this.collectPerformanceStatus(),a=t.budget||{},i=Number(a?.totals?.failed||0),s=Number(a?.totals?.warnings||0),n=i?"danger":s?"warning":"ok",r=t.serviceWorker||{},o=r.storage||{},l=r.caches?Object.entries(r.caches).map(([h,u])=>`${Pn(h)}: ${u}`).join(", "):"not controlling this page yet",d=[["Budgets",`${a?.summary||"No budget report"}${i?` (${i} fail)`:""}`,n],["Service worker",r.available?r.controlled?"controlled":"registered":"unavailable",r.available?"ok":"warning"],["Cache entries",l,"neutral"],["Storage",o.quota?`${oa(o.usage)} / ${oa(o.quota)}`:"unreported","neutral"],["Runtime",t.map.runtimeProfile?.deviceClass||"unknown","neutral"],["Loaded layers",String(t.map.loadedLayers||0),"neutral"],["Fallbacks",String(t.map.fallbackCount||0),t.map.fallbackCount?"warning":"ok"],["Seat circles",t.elections.seatCircleRenderMs?`${t.elections.seatCircleRenderMs}ms`:"not active","neutral"],["Heap",t.browser.memory?oa(t.browser.memory):"unreported","neutral"]];e.innerHTML=d.map(([h,u,p])=>` + `,i.querySelector(".leaflet-control-zoom-in")?.addEventListener("click",o=>{o.preventDefault(),e.zoomIn({duration:150})}),i.querySelector(".leaflet-control-zoom-out")?.addEventListener("click",o=>{o.preventDefault(),e.zoomOut({duration:150})});let s=i.querySelector(".leaflet-control-compass"),n=i.querySelector(".test2-main-zoom-control__compass-icon"),r=()=>{let o=Number(e.getBearing?.()||0);n&&(n.style.transform=`rotate(${-o}deg)`),s?.classList.toggle("test2-main-zoom-control__compass--active",Math.abs(o)>.1)};s?.addEventListener("click",o=>{o.preventDefault(),e.easeTo({bearing:0,pitch:0,duration:150})}),e.on("rotate",r),e.on("rotateend",r),e.on("pitch",r),r(),a.appendChild(i),t.appendChild(a)}async loadLayer(e,t={}){let a=typeof e=="string"?e:e?.id,i=typeof e=="object"&&e?e:null;if(!a)return null;!t.partial&&this.layerStates.get(a)?.isPartial&&this.unloadLayer(a);let s=re(i);if(i?.isGroup&&s.length){let d=await Promise.all(s.map(h=>this.loadLayer(h,{...t,fit:!1})));return t.fit!==!1&&this.fitToLayers(s),d[0]||null}let n=this.resolveLayer(a);if(!n){let d=new Error(`${i?.name||a} is not converted for the MapLibre route yet.`);throw this.options.onError?.(d,{mainId:a,config:i}),d}if(!n.loadable){let d=new Error(`${n.name||i?.name||a} is listed in the catalogue but is not yet converted.`);throw this.options.onError?.(d,{mainId:a,config:i,layer:n}),d}let r=i||this.options.getMainMap?.(a)||this.options.getMainMap?.(n.sourceMapId)||null,o=this.toRuntimeLayer(n,r);this.mainToTest.set(a,o.id),this.testToMain.set(o.id,a),await this.renderer.loadLayer(o);let l=this.createMainLayerState(a,o,r);return this.layerStates.set(a,{...l}),this._rememberLayerOrderId(a),this._applyRememberedOrderToMap(),t.fit!==!1&&this.fitToLayer(a),this.options.onChange?.(this),this.layerStates.get(a)}loadLayerFilteredByIndex(e,t){return this.loadLayer(t?.id||e,{fit:!0})}async expandToFullMap(e){let t=typeof e=="string"?e:e?.id;return t&&this.layerStates.get(t)?.isPartial&&this.unloadLayer(t),this.loadLayer(e)}unloadLayer(e){let t=this.groupStates.get(e);if(t){for(let i of t.childIds||[])this.unloadLayer(i);this.groupStates.delete(e),this.options.onChange?.(this);return}let a=this.mainToTest.get(e)||e;this.renderer?.unloadLayer(a),this.mainToTest.delete(e),this.testToMain.delete(a),this.layerStates.delete(e),this.options.onChange?.(this)}showLayer(e){this.setLayerVisibility(e,!0)}hideLayer(e){this.setLayerVisibility(e,!1)}toggleLayer(e){let t=this.groupStates.get(e);if(t){this.setLayerVisibility(e,!t.visible);return}let a=this.layerStates.get(e);a&&this.setLayerVisibility(e,!a.visible)}setLayerVisibility(e,t){let a=this.groupStates.get(e);if(a){for(let r of a.childIds||[])this.setLayerVisibility(r,t);a.visible=!!t,this._applyRememberedOrderToMap(),this.options.onChange?.(this);return}let i=this.layerStates.get(e),s=i?.testLayerId||this.mainToTest.get(e)||e,n=this.renderer?.layers.get(s);if(n){for(let r of n.layerIds||[])this.map.getLayer(r)&&this.map.setLayoutProperty(r,"visibility",t?"visible":"none");i&&(i.visible=!!t),this._applyRememberedOrderToMap(),this.options.onChange?.(this)}}isLayerLoaded(e){let t=this.groupStates.get(e);return t?t.childIds.every(a=>this.isLayerLoaded(a)):this.layerStates.has(e)||this.renderer?.layers.has(e)||!1}isLayerVisible(e){let t=this.groupStates.get(e);return t?t.childIds.some(a=>this.isLayerVisible(a)):this.layerStates.get(e)?.visible||!1}getVisibleLayers(){let e=new Set,t=[...this.groupStates.entries()].filter(([,i])=>i.visible).map(([i,s])=>{for(let n of s.childIds||[])e.add(n);return i}),a=[...this.layerStates.entries()].filter(([i,s])=>s.visible&&!e.has(i)).map(([i])=>i);return[...t,...a]}getLayerState(e){return this.groupStates.has(e)?this.groupStates.get(e):this.layerStates.get(e)||null}markGroupLoaded(e,t,a=[]){let i=a.filter(Boolean);if(!e||!i.length)return;let s={loaded:!0,visible:i.some(n=>this.isLayerVisible(n)),config:t,childIds:i,isGroup:!0,_strokeOpacity:1,_fillOpacity:Ri(t),_rasterOpacity:t?.rasterOpacity??t?.style?.opacity??.85};s.geoJsonLayers=[{setStyle:(n={})=>{if(n.opacity!==void 0){s._strokeOpacity=Te(n.opacity);for(let r of i)this.setStrokeOpacity(r,n.opacity)}if(n.fillOpacity!==void 0){s._fillOpacity=Te(n.fillOpacity);for(let r of i)this.setFillOpacity(r,n.fillOpacity)}}}],s.group={eachLayer:n=>{n({setOpacity:r=>{s._rasterOpacity=Te(r);for(let o of i)this.setRasterOpacity(o,r)}})}},this.groupStates.set(e,s),this._rememberLayerOrderId(e),this._applyRememberedOrderToMap(),this.options.onChange?.(this)}getLayerDrawOrder(e={}){let{loadedOnly:t=!0}=e||{};this._ensureRememberedOrderCoverage();let a=[...this._rememberedOrder].reverse();if(!t)return a;let i=this._getGroupedChildIds();return a.filter(s=>{if(i.has(s))return!1;let n=this.groupStates.get(s);return n?!!n.loaded:!!this.layerStates.get(s)?.loaded})}setLayerDrawOrder(e=[],t={}){let{notify:a=!1}=t||{},i=kn(e);if(!i.length)return;this._ensureRememberedOrderCoverage();let s=[...i].reverse(),n=new Set(s),r=this._rememberedOrder.filter(o=>!n.has(o));this._rememberedOrder=[...r,...s],this._applyRememberedOrderToMap(),a&&this.options.onChange?.(this)}_rememberLayerOrderId(e){!e||this._rememberedOrder.includes(e)||this._rememberedOrder.push(e)}_ensureRememberedOrderCoverage(){for(let[e,t]of this.groupStates.entries())t?.loaded&&this._rememberLayerOrderId(e);for(let[e,t]of this.layerStates.entries())t?.loaded&&this._rememberLayerOrderId(e)}_getGroupedChildIds(){let e=new Set;for(let t of this.groupStates.values())for(let a of t?.childIds||[])e.add(a);return e}_moveMainLayerToTop(e){let t=this.mainToTest.get(e)||e,a=this.renderer?.layers.get(t);if(!(!a||!this.map))for(let i of a.layerIds||[])this.map.getLayer(i)&&this.map.moveLayer(i)}_applyRememberedOrderToMap(){if(!this.map||!this.renderer)return;this._ensureRememberedOrderCoverage();let e=this._getGroupedChildIds();for(let t of this._rememberedOrder){let a=this.groupStates.get(t);if(a?.loaded){for(let i of a.childIds||[])this._moveMainLayerToTop(i);continue}e.has(t)||this.layerStates.get(t)?.loaded&&this._moveMainLayerToTop(t)}}setOpacity(e,t){let a=this.mainToTest.get(e)||e;this.renderer?.setOpacity(a,t)}setStrokeOpacity(e,t){let a=this.layerStates.get(e),i=a?.testLayerId||this.mainToTest.get(e)||e,s=this.renderer?.layers.get(i);if(!s)return;let n=Te(t);a._strokeOpacity=n;let r=`${i}-line`;if(this.map.getLayer(r)){let o=s.config.geometryType==="point"?"circle-opacity":"line-opacity";this.map.setPaintProperty(r,o,n)}}setFillOpacity(e,t){let a=this.layerStates.get(e),i=a?.testLayerId||this.mainToTest.get(e)||e,s=Te(t);a._fillOpacity=s;let n=`${i}-fill`;this.map.getLayer(n)&&this.map.setPaintProperty(n,"fill-opacity",s)}setRasterOpacity(e,t){let a=this.layerStates.get(e)||this.groupStates?.get(e),s=`${a?.testLayerId||this.mainToTest.get(e)||e}-raster`;if(!this.map.getLayer(s))return;let n=Te(t);a&&(a._rasterOpacity=n),this.map.setPaintProperty(s,"raster-opacity",n)}setTransparency(e){let t=1-Te(Number(e)/100);for(let a of this.layerStates.keys())this.setStrokeOpacity(a,t)}setFillTransparency(e){let t=1-Te(Number(e)/100);for(let a of this.layerStates.keys())this.setFillOpacity(a,t)}setLabelsEnabled(e){for(let t of this.mainToTest.values())this.renderer?.setLayerLabelsEnabled(t,!!e)}setTextScale(e){for(let t of this.mainToTest.values())this.renderer?.setLayerTextScale(t,e)}setLayerLabelsHidden(e,t){let a=this.mainToTest.get(e)||e;this.renderer?.setLayerLabelsEnabled(a,!t)}applyElectionStyle(e,t={}){var o,l,d,h,u,p;let i=(this.layerStates.get(e)||[...this.layerStates.values()].find(f=>f.testLayerId===e))?.testLayerId||this.mainToTest.get(e)||e,s=this.renderer?.layers.get(i);if(!s)return;s._electionOriginalPaint||(s._electionOriginalPaint={});let n=`${i}-fill`,r=`${i}-line`;if(this.map.getLayer(n)&&((o=s._electionOriginalPaint).fillColor??(o.fillColor=this.map.getPaintProperty(n,"fill-color")),(l=s._electionOriginalPaint).fillOpacity??(l.fillOpacity=this.map.getPaintProperty(n,"fill-opacity")),t.fillColorExpression!==void 0&&this.map.setPaintProperty(n,"fill-color",t.fillColorExpression),t.fillOpacityExpression!==void 0?this.map.setPaintProperty(n,"fill-opacity",t.fillOpacityExpression):t.fillOpacity!==void 0&&this.map.setPaintProperty(n,"fill-opacity",Te(t.fillOpacity))),this.map.getLayer(r)){let f=s.config.geometryType==="point"?"circle-color":"line-color";(d=s._electionOriginalPaint).lineColor??(d.lineColor=this.map.getPaintProperty(r,f)),(h=s._electionOriginalPaint).lineOpacity??(h.lineOpacity=this.map.getPaintProperty(r,s.config.geometryType==="point"?"circle-opacity":"line-opacity")),(u=s._electionOriginalPaint).lineWidth??(u.lineWidth=this.map.getPaintProperty(r,s.config.geometryType==="point"?"circle-radius":"line-width")),this.map.setPaintProperty(r,f,t.lineColorExpression||t.fillColorExpression),t.lineOpacityExpression!==void 0?this.map.setPaintProperty(r,s.config.geometryType==="point"?"circle-opacity":"line-opacity",t.lineOpacityExpression):t.lineOpacity!==void 0&&this.map.setPaintProperty(r,s.config.geometryType==="point"?"circle-opacity":"line-opacity",Te(t.lineOpacity)),t.lineWidth!==void 0&&s.config.geometryType!=="point"&&this.map.setPaintProperty(r,"line-width",t.lineWidth)}Number.isFinite(Number(t.labelMinZoomOverride))&&(s.config.test2LabelMinZoomOverride=Number(t.labelMinZoomOverride),this.renderer?.refreshDomLabels?.(i)),t.hideLabels===!0&&((p=s._electionOriginalPaint).labelsEnabled??(p.labelsEnabled=s.labelsEnabled),this.renderer?.setLayerLabelsEnabled(i,!1)),s.electionStyle={mode:t.mode||"winner"},this.options.onChange?.(this)}clearElectionStyle(e){let a=(this.layerStates.get(e)||[...this.layerStates.values()].find(r=>r.testLayerId===e))?.testLayerId||this.mainToTest.get(e)||e,i=this.renderer?.layers.get(a);if(!i?._electionOriginalPaint)return;let s=`${a}-fill`,n=`${a}-line`;if(this.map.getLayer(s)&&(i._electionOriginalPaint.fillColor!==void 0&&this.map.setPaintProperty(s,"fill-color",i._electionOriginalPaint.fillColor),i._electionOriginalPaint.fillOpacity!==void 0&&this.map.setPaintProperty(s,"fill-opacity",i._electionOriginalPaint.fillOpacity)),this.map.getLayer(n)){let r=i.config.geometryType==="point"?"circle-color":"line-color";i._electionOriginalPaint.lineColor!==void 0&&this.map.setPaintProperty(n,r,i._electionOriginalPaint.lineColor),i._electionOriginalPaint.lineOpacity!==void 0&&this.map.setPaintProperty(n,i.config.geometryType==="point"?"circle-opacity":"line-opacity",i._electionOriginalPaint.lineOpacity),i._electionOriginalPaint.lineWidth!==void 0&&i.config.geometryType!=="point"&&this.map.setPaintProperty(n,"line-width",i._electionOriginalPaint.lineWidth)}i._electionOriginalPaint.labelsEnabled!==void 0&&this.renderer?.setLayerLabelsEnabled(a,!!i._electionOriginalPaint.labelsEnabled),delete i.config.test2LabelMinZoomOverride,this.renderer?.refreshDomLabels?.(a),delete i._electionOriginalPaint,delete i.electionStyle,this.options.onChange?.(this)}setBaseMap(e){let t=Fi[e]||Fi["osm-standard"];if(!this.map)return;this.map.getLayer("osm")&&this.map.removeLayer("osm"),this.map.getSource("osm")&&this.map.removeSource("osm"),this.map.addSource("osm",{type:"raster",tiles:t,tileSize:256,attribution:"© OpenStreetMap contributors"});let a=this.map.getStyle().layers?.[0]?.id;this.map.addLayer({id:"osm",type:"raster",source:"osm"},a)}toggleOverlay(){let[e,t=!0]=arguments;return t?this.showOverlay(e):this.hideOverlay(e)}showOverlay(e){if(!this.map||!e)return!1;if(this.overlayLayers.has(e)){let s=this.overlayLayers.get(e),n=s.layerId;return this.map.getLayer(n)&&this.map.setLayoutProperty(n,"visibility","visible"),s.visible=!0,!0}let t=xn[e];if(!t)return!1;let a=`test2-overlay-${e}-source`,i=`test2-overlay-${e}`;return this.map.getSource(a)||this.map.addSource(a,{type:"raster",tiles:t.tiles,tileSize:256,attribution:t.attribution,maxzoom:t.maxzoom}),this.map.getLayer(i)||this.map.addLayer({id:i,type:"raster",source:a,paint:{"raster-opacity":.82}}),this.overlayLayers.set(e,{sourceId:a,layerId:i,visible:!0}),this.options.onChange?.(this),!0}hideOverlay(e){let t=this.overlayLayers.get(e);return!this.map||!t?!1:(this.map.getLayer(t.layerId)&&this.map.setLayoutProperty(t.layerId,"visibility","none"),t.visible=!1,this.options.onChange?.(this),!0)}setTimelineTransitionOverlay(e,t={}){if(!this.map)return!1;let a="test2-timeline-transition-source",i="test2-timeline-transition-fill",s="test2-timeline-transition-line",n=["coalesce",["get","transitionType"],["get","changeType"],"transfer"],r=t.fillColor||["case",["boolean",["feature-state","hover"],!1],"#FDBA74",["match",n,"split","#7c3aed","territory-split","#7c3aed","unchanged","#ffffff","retained","#ffffff","transfer","#ef4444","#ef4444"]],o=["case",["boolean",["feature-state","hover"],!1],.46,["match",n,"unchanged",0,"retained",0,t.fillOpacity??.34]],l=t.lineColor||["case",["boolean",["feature-state","hover"],!1],"#FF7A1A",["match",n,"split","#6d28d9","territory-split","#6d28d9","unchanged","#ffffff","retained","#ffffff","transfer","#dc2626","#dc2626"]],d=["case",["boolean",["feature-state","hover"],!1],.92,["match",n,"unchanged",0,"retained",0,t.lineOpacity??.82]],h=An(e);return this.clearTimelineTransitionHover(),this.map.getSource(a)?this.map.getSource(a).setData(h):this.map.addSource(a,{type:"geojson",data:h,promoteId:"transitionId"}),this.map.getLayer(i)?(this.map.setPaintProperty(i,"fill-color",r),this.map.setPaintProperty(i,"fill-opacity",o)):this.map.addLayer({id:i,type:"fill",source:a,paint:{"fill-color":r,"fill-opacity":o,"fill-antialias":!1}}),this.map.getLayer(s)?(this.map.setPaintProperty(s,"line-color",l),this.map.setPaintProperty(s,"line-opacity",d)):this.map.addLayer({id:s,type:"line",source:a,paint:{"line-color":l,"line-opacity":d,"line-width":["interpolate",["linear"],["zoom"],5,.8,11,1.6,14,2.4]}}),this.installTimelineTransitionHandlers(i,s,t),this.timelineTransitionOverlay={sourceId:a,fillLayerId:i,lineLayerId:s,options:t},!0}installTimelineTransitionHandlers(e,t,a={}){if(!this.map)return;for(let{layerId:l,event:d,handler:h}of this.timelineTransitionOverlayHandlers)this.map.getLayer(l)&&this.map.off(d,l,h);this.timelineTransitionOverlayHandlers=[];let i=l=>(l?.features||[]).map(d=>this.normalizeTimelineTransitionFeature(d,a)).filter(Boolean)[0]||null,s=l=>{let d=i(l);d&&(this.lastTimelineTransitionInteractionAt=performance?.now?.()||Date.now(),l.preventDefault?.(),l.originalEvent?.preventDefault?.(),l.originalEvent?.stopPropagation?.(),this.setTimelineTransitionHover(d.id),this.options.onFeatureClick?.([d]))},n=l=>{let d=i(l);d&&(this.setTimelineTransitionHover(d.id),this.map?.getCanvas?.()&&(this.map.getCanvas().style.cursor="pointer"))},r=()=>{this.map?.getCanvas?.()&&(this.map.getCanvas().style.cursor="pointer")},o=()=>{this.clearTimelineTransitionHover(),this.map?.getCanvas?.()&&(this.map.getCanvas().style.cursor="")};for(let l of[e,t])this.map.on("click",l,s),this.map.on("mousemove",l,n),this.map.on("mouseenter",l,r),this.map.on("mouseleave",l,o),this.timelineTransitionOverlayHandlers.push({layerId:l,event:"click",handler:s},{layerId:l,event:"mousemove",handler:n},{layerId:l,event:"mouseenter",handler:r},{layerId:l,event:"mouseleave",handler:o})}isTimelineTransitionEventAtPoint(e){if(!this.map||!this.timelineTransitionOverlay||!e?.point)return!1;let{fillLayerId:t,lineLayerId:a}=this.timelineTransitionOverlay,i=[t,a].filter(s=>this.map.getLayer(s));return i.length?this.map.queryRenderedFeatures(e.point,{layers:i}).length>0:!1}setTimelineTransitionHover(e){if(!this.map||!this.timelineTransitionOverlay||e===void 0||e===null)return;let{sourceId:t}=this.timelineTransitionOverlay;if(this.hoveredTimelineTransitionId!==e){this.clearTimelineTransitionHover(),this.hoveredTimelineTransitionId=e;try{this.map.setFeatureState({source:t,id:e},{hover:!0})}catch{this.hoveredTimelineTransitionId=null}}}clearTimelineTransitionHover(){if(!this.map||!this.timelineTransitionOverlay||this.hoveredTimelineTransitionId===null)return;let{sourceId:e}=this.timelineTransitionOverlay;try{this.map.setFeatureState({source:e,id:this.hoveredTimelineTransitionId},{hover:!1})}catch{}this.hoveredTimelineTransitionId=null}normalizeTimelineTransitionFeature(e,t={}){let a={...e?.properties||{}},i=a.fromFeatureName||a.from_name||a.fromName||a.oldName||"Earlier feature",s=a.toFeatureName||a.to_name||a.toName||a.newName||"Later feature",n=a.fromMapName||t.fromMapName||a.fromLayerName||"Earlier layer",r=a.toMapName||t.toMapName||a.toLayerName||"Later layer",o=`${n} to ${r}`,l=a.transitionName||a.name||`${i} to ${s}`,d=a.transitionType||a.changeType||"transfer";return{...a,id:a.transitionId||e?.id||`${t.fromMapId||"from"}__${t.toMapId||"to"}__${l}`,mapId:"__timeline_transition__",mapName:o,layerName:o,featureName:l,name:l,isTimelineTransitionFeature:!0,transitionType:d,color:d==="split"||d==="territory-split"?"#7c3aed":d==="unchanged"||d==="retained"?"#64748b":"#dc2626",properties:{...a,transitionType:d,transitionLayerName:o,fromMapId:a.fromMapId||t.fromMapId||"",toMapId:a.toMapId||t.toMapId||"",fromMapName:n,toMapName:r,fromFeatureName:i,toFeatureName:s,minimumDisplayedAreaM2:t.minAreaM2},geometry:e?.geometry||null,sourceLayer:"timeline-transition"}}clearTimelineTransitionOverlay(e={}){if(!this.map||!this.timelineTransitionOverlay)return!1;let{sourceId:t,fillLayerId:a,lineLayerId:i}=this.timelineTransitionOverlay,s=this.map.getSource(t),n={type:"FeatureCollection",features:[]};this.clearTimelineTransitionHover();let r=()=>{this.map?.getSource(t)&&this.map.getSource(t).setData(n),this.map?.getLayer(a)&&this.map.setPaintProperty(a,"fill-opacity",0),this.map?.getLayer(i)&&this.map.setPaintProperty(i,"line-opacity",0)};return e.fade&&this.map.getLayer(a)?(this.map.setPaintProperty(a,"fill-opacity-transition",{duration:260,delay:0}),this.map.setPaintProperty(i,"line-opacity-transition",{duration:260,delay:0}),this.map.setPaintProperty(a,"fill-opacity",0),this.map.setPaintProperty(i,"line-opacity",0),window.setTimeout(r,280)):s&&r(),!0}clearTransientHighlight(e={}){if(this.renderer?.clearHover?.(),this.clearTimelineTransitionHover(),e.clearSelection===!1||!this.renderer?.selected)return;let t=this.renderer.selected;this.renderer.clearFeatureState?.(t,"selected"),this.renderer.setDomLabelSelected?.(t.layerId,t.id,!1),this.renderer.selected=null,this.renderer.notifyChange?.()}fitToLayer(e){let t=this.mainToTest.get(e)||e;this.renderer?.fitToLayer(t)}fitToLayers(e=[]){let t=e.reduce((a,i)=>{let s=this.layerStates.get(i),n=Di(s?.config?.bounds);return n?En(a,n):a},null);t&&this.fitToBounds(t,{smooth:!1})}fitToBounds(e,t={}){let a=Di(e);!a||!this.map||this.map.fitBounds(a,{padding:36,duration:t?.smooth===!1?0:400,maxZoom:14})}waitUntilSettled({timeoutMs:e=2e4}={}){return Bi(this.map,{timeoutMs:e})}invalidateSize(){this.map&&(this.applyMobileTouchContract(),!this.resizeFrame&&(this.resizeFrame=requestAnimationFrame(()=>{this.resizeFrame=0,this.applyMobileTouchContract();let e=this.readMapContainerSize();this.shouldResizeMap(e)&&(this.lastResizeSize=e,this.map.resize())})))}readMapContainerSize(){let t=this.map?.getContainer?.()?.getBoundingClientRect?.();return t?{width:Math.round(t.width*10)/10,height:Math.round(t.height*10)/10}:null}shouldResizeMap(e){if(!e||e.width<=0||e.height<=0)return!1;let t=this.lastResizeSize;if(!t||Math.abs(e.width-t.width)>1||Math.abs(e.height-t.height)>1)return!0;let i=this.map?.getCanvas?.()?.getBoundingClientRect?.();return i?Math.abs(i.width-e.width)>1||Math.abs(i.height-e.height)>1:!1}highlightFeature(e,t,a={}){let i=this.mainToTest.get(e)||e;return this.renderer?.selectFeatureById(i,t,a.properties||{})||!1}waitForMapRender(e=700){return this.map?new Promise(t=>{let a=!1,i=()=>{a||(a=!0,clearTimeout(s),t())},s=setTimeout(i,e);this.map.once?.("idle",i),this.map.triggerRepaint?.()}):Promise.resolve()}async loadSingleFeature(e,t,a,i,s={}){let n=e?.id;if(s.isolate&&n){let p=this.layerStates.get(n);p?.baseLoaded===!0&&!p?.isPartial&&this.unloadLayer(n)}let r=n?this.layerStates.get(n)?.baseLoaded===!0&&!this.layerStates.get(n)?.isPartial:!1,o=this.layerStates.get(n);(!o||!this.renderer?.layers.has(o.testLayerId))&&(o=await this.loadLayer(e,{fit:!1,partial:!0})),this.ensurePartialFeatureState(o);let l={name:a||t},d=Me(t),h=this.findRenderedFeature(n,d,a),u=d||Me(h?.id)||Me(a);return h?.properties&&Object.assign(l,h.properties),r||(o.isPartial=!0,o.baseLoaded=!1,o.loadedIndices.add(u),o.featureNames.set(u,a||h?.featureName||`Feature ${t}`),o.featureVisibility.set(u,!0),o.featureProperties.set(u,l),h?.geometry&&o.featureGeometry.set(u,h.geometry),this.applyPartialFeatureFilter(n)),i&&(this.fitToBounds(i),await this.waitForMapRender()),h||(h=this.findRenderedFeature(n,u,a),h?.properties&&Object.assign(l,h.properties),h?.geometry&&o.featureGeometry.set(u,h.geometry),o.featureProperties.set(u,l)),this.highlightFeature(n,u,{properties:l}),{state:o,feature:{id:u,mapId:n,name:a||h?.featureName||l.name,featureName:a||h?.featureName||l.name,properties:l,geometry:h?.geometry||o.featureGeometry.get(u)||null}}}togglePartialFeature(e,t){let a=this.layerStates.get(e),i=Me(t);a?.featureVisibility?.has(i)&&(a.featureVisibility.set(i,a.featureVisibility.get(i)===!1),this.applyPartialFeatureFilter(e),this.options.onChange?.(this))}unloadPartialFeature(e,t){let a=this.layerStates.get(e),i=Me(t);if(a?.loadedIndices?.has(i)){if(a.loadedIndices.delete(i),a.featureNames?.delete(i),a.featureVisibility?.delete(i),a.featureProperties?.delete(i),a.featureGeometry?.delete(i),this.renderer?.selected?.layerId===a.testLayerId&&Me(this.renderer.selected.id)===i&&(this.renderer.clearFeatureState?.(this.renderer.selected,"selected"),this.renderer.setDomLabelSelected?.(a.testLayerId,i,!1),this.renderer.selected=null),a.loadedIndices.size===0&&a.isPartial&&!a.baseLoaded){this.unloadLayer(e);return}this.applyPartialFeatureFilter(e),this.options.onChange?.(this)}}isFeatureLoaded(e,t){let a=this.layerStates.get(e);return a?a.baseLoaded&&!a.isPartial?!0:a.loadedIndices?.has(Me(t))||!1:!1}isFeatureVisible(e,t){let a=this.layerStates.get(e);if(!a)return!1;if(a.baseLoaded&&!a.isPartial)return this.isLayerVisible(e);let i=Me(t);return!!(a.loadedIndices?.has(i)&&a.featureVisibility?.get(i)!==!1&&a.visible)}isPartialLayer(e){return!!this.layerStates.get(e)?.isPartial}getPartialFeatureNames(e){let t=this.layerStates.get(e);return t?.loadedIndices?[...t.loadedIndices].map(a=>t.featureNames?.get(a)||t.featureProperties?.get(a)?.name||`Feature ${a}`):[]}getPartialFeatureItems(e){let t=this.layerStates.get(e);return t?.loadedIndices?[...t.loadedIndices].map(a=>({index:a,name:t.featureNames?.get(a)||t.featureProperties?.get(a)?.name||`Feature ${a}`,visible:t.featureVisibility?.get(a)!==!1&&t.visible!==!1})):[]}findFeaturesAtPoint(e,t,a=8){return this.queryFeaturesAtLngLat(e,t,a)}getLoadedFeatures(e=500){let t=[],a=new Set;for(let[i,s]of this.layerStates){if(!s.visible)continue;let n=this.renderer?.layers.get(s.testLayerId),r=this.getQueryableLayerIds(n);if(!r.length)continue;let o=this.map.queryRenderedFeatures({layers:r});for(let l of o){let d=this.normalizeRenderedFeature(l,i,s,n),h=Oi(d);if(!a.has(h)&&(a.add(h),t.push(d),t.length>=e))return t}}return t}queryFeaturesAtLngLat(e,t,a=8){if(!this.map)return[];let i=this.map.project([Number(t),Number(e)]),s=[];for(let o of this.layerStates.values()){if(!o.visible)continue;let l=this.renderer?.layers.get(o.testLayerId);s.push(...this.getQueryableLayerIds(l))}if(!s.length)return[];let n=this.map.queryRenderedFeatures([[i.x-a,i.y-a],[i.x+a,i.y+a]],{layers:s}),r=new Set;return n.map(o=>{let l=o.layer?.id?.replace(/-(fill|line|label|raster)$/,""),d=this.testToMain.get(l)||l,h=this.layerStates.get(d);return this.normalizeRenderedFeature(o,d,h,this.renderer?.layers.get(h?.testLayerId))}).filter(o=>{let l=Oi(o);return r.has(l)?!1:(r.add(l),!0)})}addAddressMarker(e,t,a){this.removeAddressMarker(),this.map&&(this.addressMarker=new ca.default.Marker({color:"#065a6e"}).setLngLat([Number(t),Number(e)]).setPopup(new ca.default.Popup().setHTML(`${Bn(a||"Selected location")}`)).addTo(this.map),this.addressMarker.togglePopup(),this.map.flyTo({center:[Number(t),Number(e)],zoom:14,essential:!0}))}removeAddressMarker(){this.addressMarker?.remove(),this.addressMarker=null}resolveLayer(e){let t=this.metadataService.getLayer(e);if(t?.loadable)return t;let a=this.metadataService.layers||[];return a.find(i=>i.sourceMapId===e&&i.loadable)||a.find(i=>i.migration?.sourceMapId===e&&i.loadable)||a.find(i=>i.parentId===e&&i.loadable)||t||null}toRuntimeLayer(e,t=null){let a=this.applyMainStyle(e,t),i=["localhost","127.0.0.1","::1"].includes(location.hostname);return globalThis.__civgraphUseLocalTileFallback===!0&&i&&a.sourceType==="pmtiles"&&a.tilesFallback?(this._warnedLocalTileFallback||(this._warnedLocalTileFallback=!0,console.warn("[civgraph] __civgraphUseLocalTileFallback is on: serving layers from directory MVT under /render/tiles/generated/ instead of PMTiles. Those tiles are untracked and never deployed, so unless you generated them locally every tile request will 404. Unset the flag to return to PMTiles.")),{...a,sourceType:"mvt",tiles:a.tilesFallback,tileUrl:void 0}):a}applyMainStyle(e,t=null){let a=t?.style||{},i={...e.style||{}};for(let s of["color","fillColor","fillOpacity","weight","opacity","radius"])a[s]!==void 0&&(i[s]=a[s]);return a.fillOpacity===void 0&&delete i.fillOpacity,{...e,style:i}}createMainLayerState(e,t,a){let s={loaded:!0,visible:!0,config:a||this.toMainConfig(t),testLayerId:t.id,layerIds:[t.id],geoJsonLayers:[],group:null,_strokeOpacity:1,_fillOpacity:Ri(t),_rasterOpacity:t.rasterOpacity??t.style?.opacity??.85,isPartial:!1,baseLoaded:!0,loadedIndices:new Set,featureNames:new Map,featureVisibility:new Map,featureProperties:new Map,featureGeometry:new Map};return s.geoJsonLayers=[{setStyle:(n={})=>{n.opacity!==void 0&&this.setStrokeOpacity(e,Number(n.opacity)),n.fillOpacity!==void 0&&this.setFillOpacity(e,Number(n.fillOpacity))}}],s.group={eachLayer:n=>n({setOpacity:r=>this.setRasterOpacity(e,Number(r))})},s}ensurePartialFeatureState(e){e.loadedIndices||(e.loadedIndices=new Set),e.featureNames||(e.featureNames=new Map),e.featureVisibility||(e.featureVisibility=new Map),e.featureProperties||(e.featureProperties=new Map),e.featureGeometry||(e.featureGeometry=new Map)}applyPartialFeatureFilter(e){let t=this.layerStates.get(e);if(!t?.isPartial)return;this.ensurePartialFeatureState(t);let a=this.renderer?.layers.get(t.testLayerId);if(!a)return;let i=[...t.loadedIndices].filter(n=>t.featureVisibility.get(n)!==!1),s=$n(a.config,i,t);for(let n of this.getQueryableLayerIds(a,{includeHidden:!0}))this.map.getLayer(n)&&this.map.setFilter(n,s);this.renderer?.scheduleDomLabelRefresh?.(t.testLayerId)}getQueryableLayerIds(e,t={}){return e?(e.layerIds||[]).filter(a=>!this.map.getLayer(a)||/-((hover)|(hover-line)|(selected)|(selected-fill)|(label)|(raster))$/.test(a)?!1:t.includeHidden?!0:this.map.getLayoutProperty(a,"visibility")!=="none"):[]}findRenderedFeature(e,t,a=null){let i=this.layerStates.get(e),s=this.renderer?.layers.get(i?.testLayerId),n=this.getQueryableLayerIds(s);if(!n.length)return null;let r=Me(t),o=Ni(a),l=this.map.queryRenderedFeatures({layers:n});for(let d of l){let h=this.normalizeRenderedFeature(d,e,i,s);if(Me(h.id)===r||o&&Ni(h.featureName)===o)return h}return null}normalizeRenderedFeature(e,t,a,i){let s=i?.config||a?.config||{},n=Ge(s,{...e.properties||{}}),r=e.id??n[s.promoteId||"id"]??n.id,o=Pn(s,n,r);return{...n,id:r,mapId:t,mapName:a?.config?.name||s.name||t,layerName:a?.config?.name||s.name||t,featureName:o,name:n.name||o,color:s.style?.color||s.style?.fillColor||"#3388ff",properties:n,geometry:e.geometry||null,geometryIsClipped:!0,sourceLayer:e.sourceLayer||s.sourceLayer||null}}toMainConfig(e){return{id:e.sourceMapId||e.id,name:e.name,category:e.category,group:e.group,date:e.date||e.dateEffective,provider:Array.isArray(e.provider)?e.provider:e.provider?[e.provider]:[],style:e.style||{}}}handleSelection(e){if(!e)return;let t=this.testToMain.get(e.layer.id)||e.layer.sourceMapId||e.layer.id,a=this.layerStates.get(t),i=this.renderer?.layers.get(a?.testLayerId||e.layer.id),s=this.normalizeRenderedFeature(e.feature,t,a,i),r=[this.options.enrichFeature?.(s,e)||s];this.onFeatureClick?.(r),this.options.onFeatureClick?.(r)}};function An(c){return{type:"FeatureCollection",features:Array.isArray(c?.features)?c.features:[]}}function Te(c){let e=Number(c);return Number.isFinite(e)?Math.max(0,Math.min(1,e)):0}function Me(c){if(typeof c=="number")return Number.isFinite(c)?c:String(c);let e=String(c??"").trim();return e!==""&&/^-?\d+(?:\.\d+)?$/.test(e)?Number(e):e}function Ni(c){return String(c??"").trim().toLowerCase()}function $n(c,e,t=null){if(!e.length)return Hi();let a=[...new Set(e.filter(r=>r!=null&&r!==""))],i=e.map(r=>t?.featureNames?.get(r)).filter(r=>r!=null&&String(r).trim()),s=[...new Set([...a,...i].map(r=>String(r)))];if(!s.length)return Hi();let n=[];for(let r of[c?.promoteId,"id"].filter(Boolean))n.push(["in",["to-string",["get",r]],["literal",s]]);for(let r of zi(c))n.push(["in",["to-string",["get",r]],["literal",s]]);return["any",...n]}function Hi(){return["==",["get","__civgraph_no_visible_feature__"],"__civgraph_visible_feature__"]}function Pn(c,e,t){let a=zi(c);for(let i of a){let s=e?.[i];if(s!=null&&String(s).trim())return String(s).trim()}return t!=null&&t!==""?`Feature ${t}`:"Unnamed feature"}function zi(c){return[...new Set([c?.labelProperty,c?.nameProperty,"name","Name","NAME","label","LABEL","title","TITLE"].filter(Boolean))]}function Oi(c){if(c?.id!==void 0&&c?.id!==null&&c?.id!=="")return`${c.mapId}:${c.id}`;let e=JSON.stringify(c?.geometry?.coordinates||"").slice(0,120);return`${c?.mapId}:${c?.featureName||c?.name||"feature"}:${e}`}function Bn(c){return String(c??"").replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[e])}var da="civgraph:maplibre:layer-order",Vi=100,Ui="/data/timeline-transition-overlays",qi="/data/timeline-transitions",ji=Object.freeze(["wards-1972__wards-1984","wards-1984__wards-1993","wards-1993__wards-2012","wards-2012__wards-2022-final-recommendations"]),ua=new Set(ji),Et=Object.freeze({start:900,overlay:1500,settle:450}),Fn=new Set(["civil-parishes-by-province","ireland-civil-parishes","flat-civil-parishes"]),Dn=["civil-parishes-connacht","civil-parishes-leinster","civil-parishes-munster","civil-parishes-ulster"];function ut(c){if(!c)return[];let e=[];if(Array.isArray(c))e=c;else{let i=String(c).trim();if(!i)return[];if(i.startsWith("["))try{let s=JSON.parse(i);Array.isArray(s)&&(e=s)}catch{e=[]}e.length||(e=i.split(","))}let t=new Set,a=[];for(let i of e){let s=String(i||"").trim();!s||t.has(s)||(t.add(s),a.push(s))}return a}var ma=class{constructor(){this.currentCategory="all",this.currentAuthor="all",this.currentProviderCategory="all-providers",this.currentProviderList=[],this.searchQuery="",this.mapController=null,this.metadataService=null,this._suspendURLState=!1,this._restoringURLState=!1,this.currentDetailMapId=null,this.currentSourceMapId=null,this.baseMapId="osm-standard",this.userPickedBasemap=(()=>{try{return localStorage.getItem("basemapUserChoice")==="1"}catch{return!1}})(),this.elections=null,this.timelineItems=[],this.timelineOnSelect=null,this.timelineApplying=!1,this.timelineApplyDepth=0,this.timelineTransitionCache=new Map,this.timelineTransitionSidecarSet=new Set(ua),this.timelineTransitionManifestEntries=new Map,this.timelineAnimation={playing:!1,paused:!1,atEnd:!1,timer:0,runId:0,originalLayerId:null,currentIndex:0,singleLayerReferenceId:null,sequenceItems:[]},this.booksPromise=null,this.electionModulePromise=null,this.electionLoadPromise=null,this.electionCatalogueWarmScheduled=!1,this.searchWorker=null,this.searchWorkerReady=!1,this.searchWorkerSeq=0,this.searchWorkerCallbacks=new Map,this.workerSearchQuery="",this.workerSearchResultIds=null,this.serviceWorkerStatusPromise=null,this.performanceBudget=null,this.browseEntityDetailCache=new Map,this.browsePersonsIndexPromise=null,this.classicScriptPromises=new Map}readSavedLayerOrder(){try{return ut(localStorage.getItem(da))}catch{return[]}}writeSavedLayerOrder(e){let t=ut(e);try{t.length>1?localStorage.setItem(da,JSON.stringify(t)):localStorage.removeItem(da)}catch{}}normalizeLoadedLayerOrder(e,t=this.getLoadedLayerIds()){let a=new Set(t),i=[],s=new Set;for(let n of ut(e))!a.has(n)||s.has(n)||(s.add(n),i.push(n));for(let n of t)s.has(n)||(s.add(n),i.push(n));return i}getActiveLayerOrder(e=this.getLoadedLayerIds()){let t=this.mapController?.getLayerDrawOrder?.({loadedOnly:!0})||[];return this.normalizeLoadedLayerOrder(t,e)}setActiveLayerOrder(e,t={}){let{persist:a=!0,notify:i=!1}=t||{},s=this.normalizeLoadedLayerOrder(e);return s.length<2||(this.mapController?.setLayerDrawOrder?.(s,{notify:i}),a&&this.writeSavedLayerOrder(s),this.syncCatalogueMapState(),this.updateActiveLayers(),this.updateURLState()),s}restoreLayerOrder(e){let t=ut(e?.get?.("layerOrder")),a=t.length?t:this.readSavedLayerOrder();if(!a.length)return;let i=this.normalizeLoadedLayerOrder(a);i.length<2||this.mapController?.setLayerDrawOrder?.(i)}async init(){let e=performance?.now?.()||Date.now();window.__civgraphTest2={...window.__civgraphTest2||{},app:this,runtimeInitStartedAt:e},this.installRouteGuard(),this.registerServiceWorker(),await P.init({loadBooks:!1,loadGeographies:!1}),P.fuse=null,await this.loadTimelineTransitionManifest(),this.metadataService=new bt("/render/metadata/maps-test-index.json?v=c2c120cf87c6",void 0,{cache:"force-cache",portPlanCache:"force-cache"}),await this.metadataService.load();try{if(P.maps&&Array.isArray(P.maps.maps)){let t=new Set(P.maps.maps.map(a=>a.id));for(let a of this.metadataService.layers||[])(a.sourceType==="point-cloud"||a.sourceType==="raster-dem")&&!t.has(a.id)&&P.maps.maps.push(a)}}catch(t){console.warn("[app] 3D layer catalogue injection failed",t)}this.mapController=new Mt("map",this.metadataService,{onFeatureClick:t=>{let a=t?.[0]||null;if(a&&this.elections?.showFeatureResults(a)){A.hideFeatureInfo?.();return}A.showFeatureInfo(t,P.getAllMaps())},getMainMap:t=>P.getMapById(t),enrichFeature:(t,a)=>this.elections?.enrichFeature(t,a)||t,onChange:()=>{this.syncCatalogueMapState(),this.updateActiveLayers(),this.updateURLState()},onError:t=>this.showMapError(t)}),window.mapController=this.mapController,globalThis.mapController=this.mapController,this.wireUiCallbacks(),this.installCatalogueStateBridge(),this.installLazyCatalogueDataBridge(),this.installLazyRuntimeHelpersBridge(),A.init(),this.configureCataloguePerformanceProfile(),this._suspendURLState=!0,this.mapController.init("map"),this.installOutsideMapHighlightClear(),this.relocateMobileCatalogueToggle(),this.installMobilePaneToggle(),window.__civgraphTest2={...window.__civgraphTest2||{},app:this,mapController:this.mapController,metadataService:this.metadataService,elections:null,restorePromise:null,runtimeReadyAt:performance?.now?.()||Date.now(),serviceWorkerStatusPromise:this.serviceWorkerStatusPromise,getPerformanceStatus:()=>this.collectPerformanceStatus(),whenIdle:(t=15e3)=>new Promise(a=>{let i=this.mapController?.map;if(!i){a({idle:!1,reason:"no map"});return}if(i.loaded?.()&&!i.isMoving?.()){a({idle:!0,immediate:!0});return}let s=!1,n=o=>{s||(s=!0,i.off?.("idle",r),a(o))},r=()=>n({idle:!0,immediate:!1});i.once?.("idle",r),setTimeout(()=>n({idle:!1,reason:"timeout"}),t)}),urlState:()=>({hash:window.location.hash,suspended:this._suspendURLState})},this.scheduleIdleTask(()=>this.prepareSearchWorker(),{timeout:3500}),this.renderCategoryPills(),this.updateMapList(),this.setupSearch(),this.setupThemeToggle(),this.setupSupportModal(),this.setupMapControls(),this.setupOverlayEscape(),this.setupPerformanceDashboard(),this.setupTimelineControls(),this.setupElectionPaneResize(),this.setupSourcePanel(),this.setupURLStateListener(),this.scheduleElectionCatalogueWarm(),window.__civgraphTest2.restorePromise=this.restoreURLState().catch(t=>this.showMapError(t)).finally(()=>{this._suspendURLState=!1,this.updateURLState()}),await window.__civgraphTest2.restorePromise}registerServiceWorker(){if(!("serviceWorker"in navigator)||location.protocol==="file:"){this.serviceWorkerStatusPromise=Promise.resolve({available:!1,reason:"service-worker API unavailable"});return}this.serviceWorkerConfig=this.getServiceWorkerConfig(),this.serviceWorkerStatusPromise=navigator.serviceWorker.register(this.serviceWorkerConfig.url,{scope:this.serviceWorkerConfig.scope}).then(async e=>(await navigator.serviceWorker.ready.catch(()=>e),this.getServiceWorkerStatus(e))).catch(e=>({available:!1,reason:String(e?.message||e)}))}getServiceWorkerConfig(){let e=window.location.pathname||"/";return{url:"/sw.js",scope:"/",route:"root"}}async getServiceWorkerStatus(e=null){if(!("serviceWorker"in navigator))return{available:!1,reason:"service-worker API unavailable"};let t=this.serviceWorkerConfig||this.getServiceWorkerConfig(),a=e||await navigator.serviceWorker.getRegistration(t.scope),i=navigator.serviceWorker.controller||a?.active||a?.waiting||a?.installing;return i?new Promise(s=>{let n=new MessageChannel,r=setTimeout(()=>s({available:!0,controlled:!!navigator.serviceWorker.controller,reason:"status timeout"}),900);n.port1.onmessage=o=>{clearTimeout(r),s({available:!0,route:t.route,controlled:!!navigator.serviceWorker.controller,...o.data||{}})},i.postMessage({type:"TEST2_SW_STATUS"},[n.port2])}):{available:!0,controlled:!1,reason:"registered but not yet controlling this page"}}async collectPerformanceStatus(){let e=await this.loadPerformanceBudget(),t=await this.getServiceWorkerStatus().catch(s=>({available:!1,reason:String(s?.message||s)})),a=this.mapController?.getMetrics?.()||this.mapController?.metrics||[],i=this.elections?.getSeatCircleOverlayState?.()||null;return{generatedAt:new Date().toISOString(),budget:e,serviceWorker:t,map:{runtimeProfile:this.mapController?.runtimeProfile||null,loadedLayers:this.mapController?.layers?.size||0,metrics:a.slice(-40),fallbackCount:a.filter(s=>/fallback/i.test(s?.event||"")).length},elections:{active:this.elections?.activeEntry?.key||null,seatCircleRenderMs:Number(this.elections?.lastSeatCircleRenderMs||0),overlay:i},browser:{memory:performance.memory?.usedJSHeapSize||0,deviceMemory:navigator.deviceMemory||null,hardwareConcurrency:navigator.hardwareConcurrency||null,dpr:window.devicePixelRatio||1}}}async loadPerformanceBudget(){return this.performanceBudget?this.performanceBudget:(this.performanceBudget=fetch("/app/build/performance-dashboard.json",{cache:"no-cache"}).then(e=>e.ok?e.json():null).catch(()=>null),this.performanceBudget)}relocateMobileCatalogueToggle(){let e=document.getElementById("mobileToggle"),t=document.querySelector("#map .test2-main-control-stack"),a=t?.querySelector(".test2-main-zoom-control");!e||!t||!a||(e.classList.remove("mobile-toggle--navbar"),e.classList.add("mobile-toggle--map-stack"),e.removeAttribute("style"),this.updateMobilePaneToggleState(),(e.parentElement!==t||e.nextElementSibling!==a)&&t.insertBefore(e,a))}installMobilePaneToggle(){if(this._mobilePaneToggleInstalled){this.updateMobilePaneToggleState();return}let e=document.querySelector(".app-header");if(!e)return;let t=document.getElementById("mobilePaneToggle");if(!t){t=document.createElement("button"),t.id="mobilePaneToggle",t.type="button",t.className="mobile-pane-toggle",t.innerHTML='';let i=e.querySelector(":scope > .mobile-menu-toggle")||document.getElementById("mobileMenuBtn");i?.parentElement===e?e.insertBefore(t,i):e.appendChild(t)}t.addEventListener("click",i=>{i.preventDefault();let s=A.currentStateId==="info-full"?"map-full":"info-full";A.setSplitState(s),setTimeout(()=>this.mapController?.invalidateSize?.(),250),this.updateMobilePaneToggleState()});let a=A.onSplitChange;A.onSplitChange=i=>{typeof a=="function"&&a(i),this.updateMobilePaneToggleState()},window.matchMedia?.("(max-width: 768px)")?.addEventListener?.("change",()=>{this.updateMobilePaneToggleState()}),this._mobilePaneToggleInstalled=!0,this.mobilePaneToggle=t,this.updateMobilePaneToggleState()}dismissMobileCatalogueAfterLoad(){(A.isMobile||window.matchMedia?.("(max-width: 768px), (pointer: coarse)")?.matches)&&A.currentStateId==="info-full"&&(A.setSplitState("map-full"),this.updateMobilePaneToggleState(),setTimeout(()=>this.mapController?.invalidateSize?.(),250))}refitAfterElectionPane(e){if(!e||this._restoringURLState)return;let t=this.mapController?.map;t&&(t.resize(),this.mapController.fitToLayer?.(e))}updateMobilePaneToggleState(){let e=document.getElementById("mobilePaneToggle");if(!e)return;let t=A.currentStateId==="info-full",a=t?"Show map":"Show catalogue";e.setAttribute("aria-label",a),e.setAttribute("title",a),e.dataset.target=t?"map":"catalogue"}configureCataloguePerformanceProfile(){let e=window.matchMedia?.("(max-width: 768px), (pointer: coarse)"),t=()=>{let a=!!(A.isMobile||e?.matches);A.showAllMaps=!a,A.includeMobileElectionCatalogue=!0,A.singleSectionFlatCatalogue=!0,A._mobileInitialMapCardLimit=a?12:24,A._mobileInitialElectionCardLimit=a?2:15,a||(A._mobileCatalogueExpanded=!1)};t(),e?.addEventListener?.("change",()=>{t(),A.requestFlatViewRender?.(A._lastMapListOptions||{},{defer:!0})})}setupElectionPaneResize(){if(this._electionPaneResizeReady)return;this._electionPaneResizeReady=!0;let e="civgraph:test2:electionPaneHeight",t=120,a=()=>Math.round(Math.min(window.innerHeight*.38,Math.max(t,window.innerHeight*.32))),i=(p,f)=>{let g=Number.parseFloat(String(p||"").trim());return Number.isFinite(g)?g:f},s=()=>{let p=getComputedStyle(document.body),f=document.querySelector(".app-header")?.getBoundingClientRect().height||i(p.getPropertyValue("--header-height"),64),g=i(p.getPropertyValue("--map-min-height"),220),y=document.getElementById("timelineSlider"),b=y&&!y.classList.contains("hidden")?y.getBoundingClientRect().height:0;return Math.max(t,window.innerHeight-f-g-b-6)},n=p=>Math.max(t,Math.min(s(),Math.round(p))),r=()=>{requestAnimationFrame(()=>this.mapController?.invalidateSize?.())},o=p=>{let f=`${p}px`;document.documentElement.style.setProperty("--test2-election-pane-height",f),document.body.style.setProperty("--test2-election-pane-height",f),document.querySelector(".app-shell")?.style.setProperty("--test2-election-pane-height",f)},l=(p,f={})=>{let{invalidate:g=!0,persist:y=!0}=f||{},b=n(p);if(this._electionPaneHeight=b,o(b),y)try{localStorage.setItem(e,String(b))}catch{}return g&&r(),b};try{let p=Number.parseFloat(localStorage.getItem(e)||"");Number.isFinite(p)&&l(p,{invalidate:!1,persist:!1})}catch{}let d=()=>{let p=NaN;try{p=i(localStorage.getItem(e),NaN)}catch{p=NaN}let f=this._electionPaneHeight||p;Number.isFinite(f)&&l(f,{invalidate:!0,persist:!1})};window.addEventListener("resize",()=>requestAnimationFrame(d),{passive:!0});let h=p=>{let f=p.closest?.("[data-election-pane-resize]");if(f)return f;let g=p.closest?.(".election-pane__header");return g?p.closest?.('button,a,input,select,textarea,[role="button"],[data-election-view],[data-election-entity],[data-election-result-key]')?null:document.querySelector("[data-election-pane-resize]")||g:null},u=p=>{let f=h(p.target);if(!f)return;let g=document.getElementById("electionResultsPane");if(!g?.classList.contains("election-results-pane--open"))return;p.preventDefault(),p.stopPropagation();try{f.setPointerCapture?.(p.pointerId)}catch{}document.body.classList.add("test2-election-pane-resizing"),f.setAttribute("aria-valuemin",String(t)),f.setAttribute("aria-valuemax",String(s()));let y=v=>{v.preventDefault(),v.stopPropagation();let w=l(window.innerHeight-v.clientY,{invalidate:!1,persist:!1});f.setAttribute("aria-valuenow",String(w))},b=()=>{document.body.classList.remove("test2-election-pane-resizing"),window.removeEventListener("pointermove",y),window.removeEventListener("pointerup",b),window.removeEventListener("pointercancel",b);let v=this._electionPaneHeight||g.getBoundingClientRect().height||a();l(v,{invalidate:!1,persist:!0}),r()};window.addEventListener("pointermove",y),window.addEventListener("pointerup",b),window.addEventListener("pointercancel",b)};document.addEventListener("pointerdown",u),document.addEventListener("keydown",p=>{let f=h(p.target);if(!f)return;let g=document.getElementById("electionResultsPane");if(!g?.classList.contains("election-results-pane--open"))return;let y=g.getBoundingClientRect().height||a(),b=p.shiftKey?50:20;p.key==="ArrowUp"?(p.preventDefault(),f.setAttribute("aria-valuenow",String(l(y+b)))):p.key==="ArrowDown"?(p.preventDefault(),f.setAttribute("aria-valuenow",String(l(y-b)))):p.key==="Home"?(p.preventDefault(),f.setAttribute("aria-valuenow",String(l(s())))):p.key==="End"&&(p.preventDefault(),f.setAttribute("aria-valuenow",String(l(t))))}),document.addEventListener("dblclick",p=>{h(p.target)&&(p.preventDefault(),l(a()))})}installRouteGuard(){if(window.__civgraphTest2RouteGuardInstalled)return;window.__civgraphTest2RouteGuardInstalled=!0;let e=i=>typeof i!="string"||!i.startsWith("#")?i:`${window.location.pathname}${window.location.search||""}${i}`,t=history.replaceState.bind(history),a=history.pushState.bind(history);history.replaceState=(i,s,n)=>t(i,s,e(n)),history.pushState=(i,s,n)=>a(i,s,e(n)),document.addEventListener("click",i=>{let s=i.target.closest?.('a[href^="#"]');if(!s||s.closest?.("#catalogueFlatView")||s.dataset?.catalogueTarget)return;let n=s.getAttribute("href")||"";if(i.preventDefault(),!n||n==="#")return;let r=`${window.location.pathname}${window.location.search||""}${n}`;history.pushState(null,"",r);let o=decodeURIComponent(n.slice(1));(document.getElementById(o)||document.querySelector(`[name="${CSS.escape(o)}"]`))?.scrollIntoView({block:"start"})},!0)}async loadBooks(){try{A.booksData=await P.ensureBooksLoaded()}catch(e){console.warn("[Test2] Could not load books data",e)}}scheduleIdleTask(e,{timeout:t=2e3}={}){typeof e=="function"&&("requestIdleCallback"in window?window.requestIdleCallback(e,{timeout:t}):setTimeout(e,Math.min(t,1e3)))}loadClassicScript(e,t){if(t&&globalThis[t])return Promise.resolve(globalThis[t]);if(this.classicScriptPromises.has(e))return this.classicScriptPromises.get(e);let a=new Promise((i,s)=>{let n=document.querySelector(`script[src="${e}"]`);if(n){n.addEventListener("load",()=>i(t?globalThis[t]:!0),{once:!0}),n.addEventListener("error",()=>s(new Error(`Could not load ${e}`)),{once:!0});return}let r=document.createElement("script");r.src=e,r.async=!0,r.onload=()=>i(t?globalThis[t]:!0),r.onerror=()=>s(new Error(`Could not load ${e}`)),document.head.appendChild(r)});return this.classicScriptPromises.set(e,a),a}async ensureFlatgeobufRuntime(){return this.loadClassicScript("/app/js/libs/flatgeobuf-geojson.min.js","flatgeobuf")}async ensureElections(e={}){if(this.elections?.catalogue)return this.elections;this.electionModulePromise||(this.electionModulePromise=import("./election-manager-MOZS4OJM.js"));let{Test2ElectionManager:t}=await this.electionModulePromise;return this.elections||(this.elections=new t({app:this,mapController:this.mapController,onError:a=>this.showMapError(a)}),window.__civgraphTest2&&(window.__civgraphTest2.elections=this.elections)),this.electionLoadPromise||(this.electionLoadPromise=this.elections.load()),await this.electionLoadPromise,e.refreshCatalogue&&this.updateMapList(),this.elections}scheduleElectionCatalogueWarm(){if(this.electionCatalogueWarmScheduled||this.elections?.catalogue)return;this.electionCatalogueWarmScheduled=!0;let e=()=>{this.ensureElections({refreshCatalogue:!0}).catch(s=>{console.warn("[Test2] Election catalogue warmup failed",s)})},t=new URLSearchParams(window.location.hash.replace(/^#/,"")),i=this.hasElectionURLState(t,ut(t.get("layers")))?1200:6e3;this.scheduleIdleTask(e,{timeout:i})}hasElectionURLState(e,t=[]){return[...t].some(a=>String(a).startsWith("election-"))?!0:e.has("electionBody")||e.has("electionDate")||e.has("electionMode")||e.has("electionView")}wireUiCallbacks(){A.onBuildElectionCatalogueCards=async()=>this.elections?.catalogue?this.elections.buildCatalogueCards():(this.scheduleElectionCatalogueWarm(),[]),A.onLoadElection=async(e,t)=>{try{await(await this.ensureElections()).loadElection(e,t),this.updateMapList(),this.focusActiveElectionCatalogueEntry(this.elections?.activeEntry,{scroll:!1})}catch(a){this.showMapError(a)}},A.onUnloadElection=()=>{this.elections?.unloadElection(),this.updateMapList()},A.onCheckElectionLoaded=(e,t)=>this.elections?.isElectionLoaded(e,t)||!1,A.onSetupElectionTableControls=()=>{},A.onOpenElectionEntityDetail=async(e,t)=>this.openElectionEntityDetailInCatalogue(e,t),A.onOpenElectionConstituencyFeature=async({constituency:e,level:t})=>{let a=t==="council"?"lgd":t==="dea"?"dea":"constituency";return this.openElectionEntityDetailInCatalogue(a,e)},A.onSplitChange=()=>{this.mapController.invalidateSize(),this.updateURLState()},A.onMapLoad=async e=>{await this.stopTimelineAnimation({restoreOriginal:!1}),await this.loadMap(e),this.syncCatalogueMapState(),this.updateActiveLayers(),this.dismissMobileCatalogueAfterLoad(),this.updateURLState(),this.recordSettleOutcome(e,await this.mapController.waitUntilSettled())},A.onMapUnload=async e=>{if(await this.stopTimelineAnimation({restoreOriginal:!1}),this.unloadActiveElectionForLayer(e)){this.updateMapList();return}let t=P.getMapById(e);this.mapController.getLayerState(e)?.isGroup?this.mapController.unloadLayer(e):t?.isGroup&&re(t).length?re(t).forEach(a=>this.mapController.unloadLayer(a)):t?.isGroup&&Array.isArray(t.variants)?t.variants.forEach(a=>this.mapController.unloadLayer(a.id)):this.mapController.unloadLayer(e),this.syncCatalogueMapState(),this.updateActiveLayers(),this.updateURLState(),await this.mapController.waitUntilSettled(),this.settleOutcomes?.delete(e)},A.onMapToggle=e=>{this.isTimelineAnimationLayer(e)&&this.pauseTimelineAnimation({preserveOverlay:!1}),this.mapController.toggleLayer(e),this.syncCatalogueMapState(),this.updateActiveLayers(),this.updateURLState()},A.onHideMap=e=>{this.isTimelineAnimationLayer(e)&&this.pauseTimelineAnimation({preserveOverlay:!1}),this.mapController.hideLayer(e),this.syncCatalogueMapState(),this.updateActiveLayers(),this.updateURLState()},A.onCheckMapLoaded=e=>this.isMapLoaded(e),A.onCheckMapSettled=e=>this.settleOutcomes?.get(e)||"unknown",A.onCheckMapVisible=e=>this.isMapVisible(e),A.onReorderLayers=e=>this.setActiveLayerOrder(e),A.onExpandToFullMap=async e=>this.loadMap(e),A.onPartialFeatureToggle=(e,t)=>{this.mapController.togglePartialFeature(e,t),this.syncCatalogueMapState(),this.updateActiveLayers(),this.updateURLState()},A.onPartialFeatureUnload=(e,t)=>{this.mapController.unloadPartialFeature(e,t),this.syncCatalogueMapState(),this.updateActiveLayers(),this.updateURLState()},A.onCheckFeatureLoaded=(e,t)=>this.mapController.isFeatureLoaded(e,t),A.onCheckFeatureVisible=(e,t)=>this.mapController.isFeatureVisible(e,t),A.onFeatureLoad=async(e,t,a,i,s={})=>{let n=P.getMapById(e);if(!n)return null;let r=await this.mapController.loadSingleFeature(n,t,a,i,{isolate:s.isolate===!0});return this.syncCatalogueMapState(),this.updateActiveLayers(),this.updateURLState(),r},A.onCategoryChange=e=>{this.currentCategory=e,this.updateMapList(),this.updateURLState()},A.onProviderCategoryChange=(e,t)=>{this.currentProviderCategory=e,this.currentProviderList=t||[],this.updateMapList(),this.updateURLState()},A.onAuthorFilter=e=>{this.currentAuthor=!e||e.length===0?"all":e,this.updateMapList(),this.updateURLState()},A.onDownloadFgb=async e=>{let t=P.getMapById(e),a=gt(t);a&&this.triggerDownload(a,a.split("/").pop())},A.onAddressSelect=(e,t,a)=>this.mapController.addAddressMarker(e,t,a),A.onRemoveAddressMarker=()=>this.mapController.removeAddressMarker(),A.onCheckIntersection=async(e,t)=>this.mapController.queryFeaturesAtLngLat(e,t),A.onGetLoadedFeatures=()=>this.mapController.getLoadedFeatures(),A.onZoomToBbox=(e,t)=>this.mapController.fitToBounds(e,t),A.onHighlightFeature=(e,t,a)=>this.mapController.highlightFeature(e,t,a),A.onLoadSingleFeature=async(e,t,a,i,s={})=>{let n=P.getMapById(e);if(!n)return null;let r=await this.mapController.loadSingleFeature(n,t,a,i,{isolate:s.isolate!==!1});return this.syncCatalogueMapState(),this.updateActiveLayers(),this.updateURLState(),s.showInfo!==!1&&A.showFeatureInfo([{...r.feature,mapId:e,id:t}],P.getAllMaps()),r}}installCatalogueStateBridge(){if(A.__test2CatalogueStateBridgeInstalled)return;A.__test2CatalogueStateBridgeInstalled=!0;let e=A.showCatalogueDetailView.bind(A);A.showCatalogueDetailView=(a,i=!0)=>{let s=e(a,i);return this.currentDetailMapId=a||null,this.updateURLState(),s};let t=A.showCatalogueListView.bind(A);A.showCatalogueListView=(a=!1)=>{let i=t(a);return this.currentDetailMapId=null,this.updateURLState(),i}}setupURLStateListener(){window.addEventListener("hashchange",()=>{this._suspendURLState||this._restoringURLState||this.restoreURLState({updateAfterRestore:!1}).catch(e=>this.showMapError(e))})}async loadMap(e,t={}){let a=P.getMapById(e);if(a?.isGroup&&re(a).length){let s=re(a);await Promise.all(s.map(n=>this.loadMap(n,{fit:t.fit!==!1}))),this.mapController.markGroupLoaded(e,a,s);return}if(a?.isGroup&&Array.isArray(a.variants)&&a.variants.length){let s=a.variants.map(n=>n?.id).filter(n=>this.mapController.resolveLayer(n)?.loadable);await Promise.all(s.map(n=>this.mapController.loadLayer(n,{fit:!1}))),this.mapController.markGroupLoaded(e,a,s),t.fit!==!1&&(a.bounds?this.mapController.fitToBounds(a.bounds,{smooth:!1}):this.mapController.fitToLayers(s));return}if(!this.mapController.resolveLayer(a?.id||e)?.loadable){let s=this.getCivilParishesCompositeChildIds(e,a);if(s.length){let r=a||P.getMapById("civil-parishes-by-province")||{id:e,name:"Civil Parishes of Ireland"};await Promise.all(s.map(o=>this.mapController.loadLayer(o,{fit:!1}))),this.mapController.markGroupLoaded(r.id||e,r,s),t.fit!==!1&&(r.bounds?this.mapController.fitToBounds(r.bounds,{smooth:!1}):this.mapController.fitToLayers(s));return}let n=this.getConvertedCompositeChildIds(a);if(n.length){await Promise.all(n.map(r=>this.mapController.loadLayer(r,{fit:!1}))),this.mapController.markGroupLoaded(a.id,a,n),t.fit!==!1&&a.bounds&&this.mapController.fitToBounds(a.bounds,{smooth:!1});return}}await this.mapController.loadLayer(a||e,{fit:t.fit!==!1})}getCivilParishesCompositeChildIds(e,t){return[...new Set([e,t?.id,t?.classId,t?.slug].filter(Boolean))].some(s=>Fn.has(s))?Dn.filter(s=>this.mapController.resolveLayer(s)?.loadable):[]}getConvertedCompositeChildIds(e){if(!e)return[];let t=Array.isArray(e.compositeSources)?e.compositeSources:[],a=!e.isGroup&&Array.isArray(e.variants)?e.variants.map(s=>s.id):[];return[...new Set([...t,...a].filter(Boolean))].filter(s=>this.mapController.resolveLayer(s)?.loadable)}isPlaceholderTimelineMap(e){if(!e)return!0;let t=[...Array.isArray(e.keywords)?e.keywords:[],...Array.isArray(e.rawMetadata?.keywords)?e.rawMetadata.keywords:[]].map(i=>String(i).trim().toLowerCase()),a=String(e.status||e.rawMetadata?.status||"").toLowerCase();return!!(e.placeholder||e.rawMetadata?.placeholder||e.thumbnail?.kind==="placeholder"||t.includes("placeholder")||t.includes("to-be-added")||t.includes("to be added")||a.includes("to be added"))}isTimelineMapPlayable(e){if(!e)return!1;let t=P.getMapById(e);return!t||this.isPlaceholderTimelineMap(t)?!1:this.mapController.resolveLayer(t.id||e)?.loadable?!0:t.isGroup&&re(t).length?re(t).some(i=>this.isTimelineMapPlayable(i)):t.isGroup&&Array.isArray(t.variants)&&t.variants.length?t.variants.some(i=>this.mapController.resolveLayer(i?.id)?.loadable):this.getConvertedCompositeChildIds(t).length>0}renderCategoryPills(){A.renderCategoryPills(P.getMapCategories(),this.currentCategory),A.renderProviderPills(this.currentProviderCategory)}updateMapList(){let e=P.getAllMaps(),t=P.getMapsByCategory(this.currentCategory);if(this.currentAuthor!=="all"){let i=Array.isArray(this.currentAuthor)?this.currentAuthor:[this.currentAuthor];t=t.filter(s=>i.some(n=>s.provider?.includes(n)))}this.currentProviderCategory!=="all-providers"&&this.currentProviderList.length>0&&(t=t.filter(i=>(Array.isArray(i.provider)?i.provider:i.provider?[i.provider]:[]).some(n=>this.currentProviderList.includes(n)))),this.searchQuery&&(t=this.searchMapsForCatalogue(this.searchQuery,e),this.currentCategory!=="all"&&(t=t.filter(i=>i.category===this.currentCategory)));let a=new Map;t.forEach(i=>{let s=ve.getFeatureCount(i.id);s>0&&a.set(i.id,s)}),A.renderMapList(t,{visibleIds:this.mapController.getVisibleLayers(),loadedIds:this.getLoadedLayerIds(),featureCounts:a,totalMaps:this.publicMapCount(),shownMaps:Math.min(t.length,this.publicMapCount())})}publicMapCount(){let e=this.metadataService?.metadata?.publicMapCount;if(Number.isFinite(e))return e;let t=new Set((this.metadataService?.layers||[]).map(a=>a.sourceMapId).filter(Boolean));return Ma(P.maps?.maps||[],a=>t.has(a)).length}focusActiveElectionCatalogueEntry(e,t={}){if(!e?.body||!e?.date)return;let a=()=>{this.searchQuery="",this.currentCategory="all",this.currentProviderCategory="all-providers",this.currentProviderList=[];let d=document.getElementById("searchInput");d&&(d.value=""),document.getElementById("searchClear")?.classList.remove("visible"),A.showCatalogueListView?.(!1),this.updateMapList()},i=async()=>{let d=Number.parseInt(String(e.date).slice(0,4),10);if(!Number.isFinite(d))return;let h=`${Math.floor(d/10)*10}s`,p=[...document.querySelectorAll("#catalogueFlatView .catalogue-flat__toc-decade-btn")].find(f=>f.textContent.trim()===h)?.dataset?.catalogueTarget;p&&await A.ensureCatalogueTargetRendered?.(p,"elections")},s=8e3,n=120,r=performance.now()+s,o=!1,l=()=>{let d=[...document.querySelectorAll("#catalogueFlatView .flat-election-entry")],h=d.find(u=>u.dataset.electionBody===e.body&&u.dataset.electionDate===e.date);if(!h){if(performance.now()>=r)return;o||(o=!0,a()),Promise.resolve(i()).catch(()=>{}).then(()=>setTimeout(l,n));return}if(d.forEach(u=>{let p=u===h;u.classList.toggle("class-member--loaded",p),u.classList.toggle("flat-election-entry--active",p);let f=u.querySelector(".election-load-btn");f&&f.setAttribute("title",p?"Unload":"Load")}),h.querySelector(".election-load-btn")?.setAttribute("title","Unload"),t.scroll){let u=h.closest(".pane__content")||document.querySelector('.pane__content[data-tab-content="catalogue"]');u?.scrollTo?u.scrollTo({top:Math.max(0,h.offsetTop-72),behavior:"auto"}):h.scrollIntoView({block:"nearest"})}};requestAnimationFrame(()=>requestAnimationFrame(l))}setupSearch(){A.initializeFuse=()=>{A.fuse=null,A.searchItems=[]};let e=(t,a=1e3)=>this.searchCatalogueWithWorker(t,a);A.performSearch=async t=>{let a=String(t||"").trim();if(A.hideAutocomplete?.(),this.searchQuery=a,A._catalogueSearchQuery=a,!a)return this.workerSearchQuery="",this.workerSearchResultIds=null,A.clearCatalogueSearchResults?.({render:!0}),this.updateURLState(),[];let i=await e(a,1e3);return this.searchQuery!==a?[]:(this.workerSearchQuery=a,this.workerSearchResultIds=i,await A.renderCatalogueSearchResults?.(a,{mapResultIds:i,mapResultsProvider:e}),this.updateURLState(),i)},A.onSearch=t=>{let a=String(t||"").trim();if(this.searchQuery=a,A._catalogueSearchQuery=a,!a){this.workerSearchQuery="",this.workerSearchResultIds=null,A.clearCatalogueSearchResults?.({render:!0}),this.updateMapList(),this.updateURLState();return}A.performSearch(a).catch(i=>{console.warn("[App] Catalogue search failed:",i)})},A.setupSearch(),document.addEventListener("click",t=>{t.target.closest(".overflow-menu")||document.querySelectorAll(".overflow-menu--open").forEach(a=>a.classList.remove("overflow-menu--open"))})}prepareSearchWorker(){if("Worker"in window)try{this.searchWorker=new Worker("/app/src/search-worker.js?v=app-search-001",{type:"module"}),this.searchWorker.addEventListener("message",e=>{let t=e.data||{};if(t.type==="ready"){this.searchWorkerReady=!0;return}if(t.type==="results"){let a=this.searchWorkerCallbacks.get(t.seq);if(!a)return;this.searchWorkerCallbacks.delete(t.seq),a.resolve(Array.isArray(t.ids)?t.ids:[])}}),this.searchWorker.addEventListener("error",()=>{this.searchWorkerReady=!1}),this.searchWorker.postMessage({type:"init",maps:P.getAllMaps().map(e=>({id:e.id,name:e.name,category:e.category,group:e.group,provider:e.provider,description:e.description,date:e.date,dateRange:e.dateRange,keywords:e.keywords}))})}catch(e){console.warn("[Test2] Search worker unavailable",e),this.searchWorker=null}}async searchCatalogueWithWorker(e,t=200){let a=String(e||"").trim();if(!a||a.length<1)return[];if(!this.searchWorker)return this.simpleSearchMapIds(a,t);let i=++this.searchWorkerSeq;return new Promise(s=>{let n=setTimeout(()=>{this.searchWorkerCallbacks.delete(i),s(this.simpleSearchMapIds(a,t))},900);this.searchWorkerCallbacks.set(i,{resolve:r=>{clearTimeout(n),s(r)}}),this.searchWorker.postMessage({type:"search",query:a,limit:t,seq:i})})}searchMapsForCatalogue(e,t){if(this.workerSearchQuery===e&&Array.isArray(this.workerSearchResultIds)){let i=new Set(this.workerSearchResultIds);return t.filter(s=>i.has(s.id))}let a=new Set(this.simpleSearchMapIds(e,1e3));return t.filter(i=>a.has(i.id))}simpleSearchMapIds(e,t=200){let a=pa(e).split(/\s+/).filter(Boolean);return a.length?P.getAllMaps().map(i=>{let s=pa([i.id,i.name,i.category,i.group,i.provider,i.description,i.date,i.dateRange,...Array.isArray(i.keywords)?i.keywords:[]].flat().filter(Boolean).join(" ")),n=pa(i.name||"");if(!a.every(o=>s.includes(o)))return null;let r=a.reduce((o,l)=>o+(n.startsWith(l)?100:n.includes(l)?60:10),0);return{id:i.id,score:r,name:i.name||""}}).filter(Boolean).sort((i,s)=>s.score-i.score||i.name.localeCompare(s.name)).slice(0,t).map(i=>i.id):[]}setupThemeToggle(){if(document.querySelector(".app-header[data-site-chrome]")){this.syncBasemapToTheme(),document.addEventListener("civgraph:themechange",()=>{this.syncBasemapToTheme()});return}let e=[document.getElementById("themeToggle"),document.getElementById("themeToggleMobile")].filter(Boolean),t=localStorage.getItem("theme"),a=window.matchMedia?.("(prefers-color-scheme: dark)").matches;document.documentElement.dataset.theme=t||(a?"dark":"light"),this.syncBasemapToTheme(),e.forEach(i=>{i.addEventListener("click",()=>{let s=document.documentElement.dataset.theme==="dark"?"light":"dark";document.documentElement.dataset.theme=s,localStorage.setItem("theme",s),this.syncBasemapToTheme()})})}setupSupportModal(){if(document.querySelector(".app-header[data-site-chrome]"))return;let e=document.getElementById("supportModal"),t=[document.getElementById("supportBtn"),document.getElementById("mobileSupportBtn")].filter(Boolean);if(!e||t.length===0)return;let a='a[href], button:not([disabled]), textarea, input, select, [tabindex]:not([tabindex="-1"])',i=null,s=()=>[...e.querySelectorAll(a)].filter(d=>d.offsetParent!==null),n=d=>{if(d.key!=="Tab")return;let h=s();if(!h.length)return;let u=h[0],p=h[h.length-1];d.shiftKey&&(document.activeElement===u||!e.contains(document.activeElement))?(d.preventDefault(),p.focus()):!d.shiftKey&&(document.activeElement===p||!e.contains(document.activeElement))&&(d.preventDefault(),u.focus())},r=()=>[...document.body.children].filter(d=>d!==e),o=()=>{i=document.activeElement,e.classList.remove("hidden"),r().forEach(d=>{d.setAttribute("aria-hidden","true"),"inert"in d&&(d.inert=!0)}),document.addEventListener("keydown",n,!0),(s()[0]||e).focus()},l=()=>{e.classList.add("hidden"),r().forEach(d=>{d.removeAttribute("aria-hidden"),"inert"in d&&(d.inert=!1)}),document.removeEventListener("keydown",n,!0),i&&typeof i.focus=="function"&&document.contains(i)&&i.focus(),i=null};t.forEach(d=>d.addEventListener("click",h=>{h.preventDefault(),o()})),e.querySelector(".support-modal__backdrop")?.addEventListener("click",l),e.querySelector(".support-modal__close")?.addEventListener("click",l),document.addEventListener("keydown",d=>{d.key==="Escape"&&!e.classList.contains("hidden")&&l()})}setupOverlayEscape(){document.addEventListener("keydown",e=>{if(e.key!=="Escape"||e.defaultPrevented)return;let t=document.activeElement;if(t&&(t.tagName==="INPUT"||t.tagName==="TEXTAREA"||t.isContentEditable))return;let a=document.getElementById("supportModal");if(a&&!a.classList.contains("hidden"))return;let i=document.getElementById("featureInfo");if(i&&!i.classList.contains("hidden")){A.hideFeatureInfo?.();return}if(document.getElementById("activeLayersToggle")?.getAttribute("aria-expanded")==="true"){this.setActiveLayersPanelOpen(!1),document.getElementById("activeLayersToggle")?.focus({preventScroll:!0});return}document.getElementById("mapControlsToggle")?.getAttribute("aria-expanded")==="true"&&(this.setMapControlsOpen(!1),document.getElementById("mapControlsToggle")?.focus({preventScroll:!0}))})}setupMapControls(){let e=document.getElementById("mapControlsToggle"),t=document.getElementById("mapControlPanel"),a=document.getElementById("mapControlsClose"),i=document.getElementById("activeLayersToggle"),s=document.getElementById("activeLayers"),n=document.getElementById("activeLayersClose"),r=document.getElementById("featureInfoClose");e?.addEventListener("click",()=>{this.setMapControlsOpen(e.getAttribute("aria-expanded")!=="true")}),a?.addEventListener("click",()=>this.setMapControlsOpen(!1));let o=document.getElementById("overlayToggle"),l=document.getElementById("overlayList");o?.addEventListener("click",()=>{let v=o.getAttribute("aria-expanded")!=="true";o.setAttribute("aria-expanded",String(v)),l?.classList.toggle("overlay-list--collapsed",!v),l?.classList.toggle("overlay-list--expanded",v)}),document.getElementById("baseMapSelect")?.addEventListener("change",async v=>{await this.applyBaseMap(v.target.value||"osm-standard",{userChoice:!0}),this.updateURLState()});let d=document.getElementById("transparencySlider"),h=document.getElementById("transparencyValue");d?.addEventListener("input",()=>{let v=Number(d.value);this.mapController.setTransparency(v),h&&(h.textContent=`${v}%`),this.updateURLState()});let u=document.getElementById("fillTransparencySlider"),p=document.getElementById("fillTransparencyValue");u?.addEventListener("input",()=>{let v=Number(u.value);this.mapController.setFillTransparency(v),p&&(p.textContent=`${v}%`),this.updateURLState()}),document.getElementById("labelsToggle")?.addEventListener("change",v=>{this.mapController.setLabelsEnabled(v.target.checked),this.updateURLState()});let f=Number(He("textScale")||"100"),g=[50,60,70,80,90,100,110,125,150,175,200],y=document.getElementById("textSizeValue"),b=()=>{y&&(y.textContent=`${f}%`),this.mapController.setTextScale(f),et("textScale",f),this.updateURLState()};document.getElementById("textSizeDecrease")?.addEventListener("click",()=>{let v=g.indexOf(f);f=g[Math.max(0,v-1)]||100,b()}),document.getElementById("textSizeIncrease")?.addEventListener("click",()=>{let v=g.indexOf(f);f=g[Math.min(g.length-1,v+1)]||100,b()}),b(),i?.addEventListener("click",()=>{this.setActiveLayersPanelOpen(i.getAttribute("aria-expanded")!=="true")}),n?.addEventListener("click",()=>this.setActiveLayersPanelOpen(!1)),r?.addEventListener("click",()=>A.hideFeatureInfo()),document.getElementById("conditionalStylingBtn")?.addEventListener("click",()=>{this.showMapError(new Error("Conditional styling controls use MapLibre expressions; this route currently supports base opacity, labels, and text scale."))}),this.mapController.map?.on("moveend",()=>this.updateURLState())}setupPerformanceDashboard(){document.getElementById("performanceDashboard")?.setAttribute("hidden","");let e=document.getElementById("performanceDashboardRefresh"),t=()=>this.renderPerformanceDashboard().catch(a=>{let i=document.getElementById("performanceDashboardStatus");i&&(i.textContent=`Performance status unavailable: ${a?.message||a}`)});e?.addEventListener("click",t)}async openElectionEntityDetailInCatalogue(e,t){let a=await this.loadElectionEntityBrowseDetail(e,t);return a?(A.showElectionEntityDetailInCatalogue(a,!0),!0):!1}async loadElectionEntityBrowseDetail(e,t){let a=String(e||"").toLowerCase(),i=`${a}:${t||""}`;if(this.browseEntityDetailCache.has(i))return this.browseEntityDetailCache.get(i);let s=null;return a==="party"?s=await this.loadPartyBrowseDetail(t):a==="candidate"?s=await this.loadPersonBrowseDetail(t):["constituency","dea","lgd"].includes(a)&&(s=await this.loadAreaBrowseDetail(a,t)),s&&this.browseEntityDetailCache.set(i,s),s}async loadPartyBrowseDetail(e){let t=Re(e),a=[...new Set([t,String(e||"").trim().toLowerCase()].filter(Boolean))];for(let i of a)try{let s=await fetch(`/data/browse/details/parties/${encodeURIComponent(i)}.json`,{cache:"force-cache"});if(!s.ok)continue;let n=await s.json(),r=n.item||n,o=await this.loadPartyPersons(r);return this.mapPartyBrowseItem(r,o)}catch(s){console.warn("[Test2] Party Browse detail unavailable",i,s)}return null}async loadPersonBrowseDetail(e){let t=Re(e),a=String(e||"").split("|")[0].trim(),i=Re(a);for(let n of[...new Set([t,i].filter(Boolean))])try{let r=await fetch(`/_api/persons?slug=${encodeURIComponent(n)}`,{cache:"force-cache"});if(r.status===404)continue;if(!r.ok)break;let o=await r.json();if(o?.person)return this.mapPersonBrowseItem(o.person)}catch{break}let s=await this.findBrowsePerson(n=>{let r=[n.slug,n.id,n.name,n.title].map(Re);return r.includes(t)||i&&r.includes(i)});return s?this.mapPersonBrowseItem(s):null}async loadPartyPersons(e={}){let t=[...new Set([e.canonicalName,e.title,...e.observedNames||[],...e.knownAliases||[]].filter(Boolean))];if(!t.length)return[];let a=new URLSearchParams;for(let i of t)a.append("party",i);a.set("limit","200");try{let i=await fetch(`/_api/persons?${a}`,{cache:"force-cache"});if(i.ok){let s=await i.json();if(Array.isArray(s?.persons))return s.persons}}catch{}return this.loadBrowsePersonsIndex().catch(()=>[])}async loadAreaBrowseDetail(e,t){let a=String(t||"").trim();if(!a)return null;let i=await this.ensureElections(),s=Array.isArray(i?.catalogue?.elections)?i.catalogue.elections:[],n=Ne(a),r=[];for(let l of s){if(!(e==="lgd"?[...l.localBodies||[],l.body]:l.constituencies||[]).some(f=>Ne(f)===n)&&!(e==="constituency"&&l.key===this.elections?.activeEntry?.key))continue;let u=null;try{u=await i.loadBundle(l)}catch{continue}let p=(u.results||[]).filter(f=>e==="lgd"?Ne(f.localBody||f.localGovernmentDistrict||f.council||f.bodyLabel||"")===n:Ne(f.constituency||f.matchName||f.featureName||"")===n);if(p.length)if(e==="lgd")r.push(this.mapCouncilAreaHistoryRow(l,u,a,p));else for(let f of p)r.push(this.mapConstituencyAreaHistoryRow(l,u,f,e))}if(r.sort((l,d)=>String(d.date||"").localeCompare(String(l.date||""))||String(l.electionDisplayName||"").localeCompare(String(d.electionDisplayName||""))),!r.length)return null;let o={elections:r.length,districts:[...new Set(r.map(l=>Ne(l.localGovernmentDistrict)).filter(Boolean))].length,deas:e==="lgd"?r.reduce((l,d)=>l+Number(d.deaCount||0),0):r.length,totalValidVotes:r.reduce((l,d)=>l+Number(d.validVotes||0),0),totalSeats:r.reduce((l,d)=>l+Number(d.seats||0),0),latestDate:r[0]?.date||null};return{kind:e,key:Re(a),name:a,colour:r[0]?.winnerColour||"#64748b",subtitle:e==="lgd"?"Local Government District / Council":e==="dea"?"District Electoral Area":"Constituency",metrics:o,historyRows:r}}installLazyCatalogueDataBridge(){if(A.__test2LazyCatalogueDataBridgeInstalled)return;A.__test2LazyCatalogueDataBridgeInstalled=!0;let e=A.ensureCatalogueTargetRendered?.bind(A);e&&(A.ensureCatalogueTargetRendered=async(a,i=null)=>((i||A._flatTargetToSection?.get?.(a))==="books"&&await this.loadBooks(),e(a,i)));let t=A.openCatalogueBookViewer?.bind(A);t&&(A.openCatalogueBookViewer=async(...a)=>(await this.loadBooks(),t(...a)))}installLazyRuntimeHelpersBridge(){if(A.__test2LazyRuntimeHelpersBridgeInstalled)return;A.__test2LazyRuntimeHelpersBridgeInstalled=!0;let e=A.downloadFeature?.bind(A);e&&(A.downloadFeature=async(a,i)=>(i==="fgb"&&await this.ensureFlatgeobufRuntime(),e(a,i)));let t=A.loadAttributeSchema?.bind(A);t&&(A.loadAttributeSchema=async(...a)=>(await this.ensureFlatgeobufRuntime(),t(...a)))}async fetchBrowseIndexItems(e){let t=await fetch(e,{cache:"force-cache"});if(!t.ok)throw new Error(`Browse index failed: ${t.status} ${e}`);let a=await t.json();return a?.indexLayout==="sharded"&&Array.isArray(a.shards)?(await Promise.all(a.shards.map(s=>this.fetchBrowseIndexItems(s.url)))).flat():Array.isArray(a.items)?a.items:[]}async loadBrowsePersonsIndex(){return this.browsePersonsIndexPromise||(this.browsePersonsIndexPromise=this.fetchBrowseIndexItems("/data/browse/persons.json")),this.browsePersonsIndexPromise}async findBrowsePerson(e){if(this.browsePersonsIndexPromise)return(await this.browsePersonsIndexPromise).find(e)||null;let t=await fetch("/data/browse/persons.json",{cache:"force-cache"});if(!t.ok)return null;let a=await t.json();if(!(a?.indexLayout==="sharded"&&Array.isArray(a.shards)))return(Array.isArray(a.items)?a.items:[]).find(e)||null;for(let i of a.shards){let n=(await this.fetchBrowseIndexItems(i.url).catch(()=>[])).find(e);if(n)return n}return null}mapPartyBrowseItem(e,t=[]){let a=Array.isArray(e.relatedElections)?e.relatedElections:[],i=r=>a.find(o=>r.test(`${o.key||""} ${o.title||""}`)),s=a.map(r=>this.mapPartyHistoryRow(r)),n=this.buildPartyCandidateSummaries(e,t);return{kind:"party",key:e.slug||Re(e.canonicalName||e.title),name:e.canonicalName||e.title||e.slug||"",colour:e.colour||e.color||e.partyColour||"#6b7280",latestWestminster:s.find(r=>/Westminster/i.test(r.electionType))||i(/house-of-commons|UK general|Westminster/i),latestAssembly:s.find(r=>/Assembly/i.test(r.electionType))||i(/northern-ireland-assembly|Assembly/i),historyRows:s,partySummaries:s,candidateSummaries:n,totals:e.totals||{},observedNames:e.observedNames||[],knownAliases:e.knownAliases||[],firstYear:e.firstYear,lastYear:e.lastYear}}mapPersonBrowseItem(e){let t=Array.isArray(e.elections)?e.elections:[],a=t[0]||null,i=t.map(s=>this.mapPersonAppearanceRow(s));return{kind:"candidate",key:e.slug||e.id||Re(e.name||e.title),personId:e.id||e.slug||"",name:e.name||e.title||"",latestParty:a?.party||e.parties?.[0]?.name||"",parties:(e.parties||[]).map(s=>s.name||s).filter(Boolean),dates:[...new Set(t.map(s=>String(s.year||s.date||"")).filter(Boolean))],constituencies:(e.constituencies||[]).map(s=>s.name||s).filter(Boolean),constituencyEntries:t.map(s=>({body:kt(s.key),date:s.date||"",constituency:s.constituency||"",level:At(s.key,s.title)==="Local"?"dea":"constituency",elected:!!s.elected,mapLayerYear:s.year||String(s.date||"").slice(0,4)})),appearances:i,firstPrefs:e.totals?.firstPrefs||0,electedCount:e.totals?.elected||0,shareOfAllValid:null,latestAppearance:i[0]||a}}mapPartyHistoryRow(e={}){let t=kt(e.key)||e.body||"",a=At(e.key,e.title),i=e.totalSeats??null,s=e.seats??e.elected??null,n=e.stood??e.candidates??null;return{electionDisplayName:e.title||e.key||"",electionBodyForOpen:t,body:t,bodyLabel:t,date:e.date||"",electionType:a,rank:e.rank??null,rankDelta:e.rankDelta??null,contested:!/referendum|recall/i.test(`${e.title||""} ${e.key||""}`),isRecallPetition:/recall petition/i.test(`${e.title||""} ${e.key||""}`),isByElection:/by-election/i.test(`${e.title||""} ${e.key||""}`),stood:n,stoodDelta:e.stoodDelta??null,elected:s,electedDelta:e.electedDelta??e.seatsDelta??null,totalSeats:i,totalSeatsDelta:e.totalSeatsDelta??null,seatPct:i?Number(s||0)/Number(i)*100:null,seatPctDelta:e.seatPctDelta??null,constituenciesContested:e.constituenciesContested??e.constituencies??null,constituenciesContestedDelta:e.constituenciesContestedDelta??null,totalConstituencies:e.totalConstituencies??null,totalConstituenciesDelta:e.totalConstituenciesDelta??null,firstPrefs:e.votes??e.firstPrefs??null,firstPrefsDelta:e.votesDelta??e.firstPrefsDelta??null,validVotePct:e.share??e.validVotePct??null,validVotePctDelta:e.shareDelta??e.validVotePctDelta??null,bodyGroup:e.bodyGroup||null}}mapPersonAppearanceRow(e={}){let t=kt(e.key),a=At(e.key,e.title),i=e.firstPref??e.firstPrefs??e.votes??null;return{electionDisplayName:e.title||e.key||"",electionBodyForOpen:t,body:t,bodyLabel:a==="Local"&&(e.localBody||e.bodyLabel)||t,date:e.date||"",constituency:e.constituency||"",party:e.party||"",status:e.status||(e.elected?"Elected":""),rank:e.rank||null,firstPref:i,firstPrefs:i,firstPrefPct:e.firstPrefPct??e.share??null,elected:!!e.elected,electionType:a,isByElection:/by-election/i.test(`${e.title||""} ${e.key||""}`),overallStandingNumber:e.overallStandingNumber??null,overallElectedNumber:e.overallElectedNumber??null,bodyStandingNumber:e.bodyStandingNumber??null,bodyElectedNumber:e.bodyElectedNumber??null}}buildPartyCandidateSummaries(e={},t=[]){let a=new Set([e.canonicalName,e.title,...e.observedNames||[],...e.knownAliases||[]].map(Ne).filter(Boolean)),i=new Map;for(let s of t||[])for(let n of s.elections||[]){if(!a.has(Ne(n.party)))continue;let r=s.id||s.slug||Re(s.name||s.title);i.has(r)||i.set(r,{personId:r,name:s.name||s.title||r,totalFirstPrefs:0,timesStood:0,timesStoodLocal:0,timesStoodDevolved:0,timesStoodWestminster:0,timesStoodEuropean:0,timesElected:0,timesElectedLocal:0,timesElectedDevolved:0,timesElectedWestminster:0,timesElectedEuropean:0,constituencyEntries:[]});let o=i.get(r),l=At(n.key,n.title),d=Hn(l);o.totalFirstPrefs+=Number(n.firstPref??n.firstPrefs??n.votes??0)||0,o.timesStood+=1,d&&(o[`timesStood${d}`]+=1),n.elected&&(o.timesElected+=1,d&&(o[`timesElected${d}`]+=1)),n.constituency&&o.constituencyEntries.push({body:kt(n.key),date:n.date||"",constituency:n.constituency,level:l==="Local"?"dea":"constituency",elected:!!n.elected,mapLayerYear:n.year||String(n.date||"").slice(0,4)})}return[...i.values()].sort((s,n)=>n.timesElected-s.timesElected||n.totalFirstPrefs-s.totalFirstPrefs||n.timesStood-s.timesStood||s.name.localeCompare(n.name))}mapConstituencyAreaHistoryRow(e,t,a,i){let s=a.winnerParty||a.leadingParty||"",n=a.leadingVotes??a.winnerVotes??null,r=a.validPoll??a.totalVotes??null;return{electionDisplayName:t.displayTitle||e.displayTitle||e.title||e.key||"",electionBodyForOpen:t.body||e.body||"",body:t.body||e.body||"",date:t.date||e.date||"",localGovernmentDistrict:a.localBody||a.localGovernmentDistrict||"",winnerParty:s,winnerColour:a.winnerColour||a.leadingColour||a.colour||"#b0bec5",winnerVotes:n,winnerPct:a.leadingPct??a.winnerPct??(r&&n?Number(n)/Number(r)*100:null),validVotes:r,seats:a.seatsTotal??a.seatsWon??null,isByElection:/by-election/i.test(`${t.displayTitle||e.displayTitle||""}`),areaKind:i}}mapCouncilAreaHistoryRow(e,t,a,i){let s=new Map,n=0,r=0;for(let l of i){n+=Number(l.validPoll||0),r+=Number(l.seatsTotal??l.seatsWon??0)||0;for(let d of l.candidates||[]){let h=d.party||l.leadingParty||"Independent",u=Ne(h),p=s.get(u)||{party:h,votes:0,colour:d.colour||l.leadingColour||"#b0bec5"};p.votes+=Number(d.firstPrefs??d.votes??0)||0,s.set(u,p)}}let o=[...s.values()].sort((l,d)=>d.votes-l.votes)[0]||{};return{electionDisplayName:t.displayTitle||e.displayTitle||e.title||e.key||"",electionBodyForOpen:t.body||e.body||"",body:t.body||e.body||"",date:t.date||e.date||"",deaCount:i.length,districtElectoralAreas:i.map(l=>l.constituency).filter(Boolean),winnerParty:o.party||"",winnerColour:o.colour||"#b0bec5",winnerVotes:o.votes||null,winnerPct:n&&o.votes?o.votes/n*100:null,validVotes:n,seats:r,isByElection:/by-election/i.test(`${t.displayTitle||e.displayTitle||""}`),localGovernmentDistrict:a}}async renderPerformanceDashboard(){let e=document.getElementById("performanceDashboardStatus");if(!e)return;let t=await this.collectPerformanceStatus(),a=t.budget||{},i=Number(a?.totals?.failed||0),s=Number(a?.totals?.warnings||0),n=i?"danger":s?"warning":"ok",r=t.serviceWorker||{},o=r.storage||{},l=r.caches?Object.entries(r.caches).map(([h,u])=>`${On(h)}: ${u}`).join(", "):"not controlling this page yet",d=[["Budgets",`${a?.summary||"No budget report"}${i?` (${i} fail)`:""}`,n],["Service worker",r.available?r.controlled?"controlled":"registered":"unavailable",r.available?"ok":"warning"],["Cache entries",l,"neutral"],["Storage",o.quota?`${ha(o.usage)} / ${ha(o.quota)}`:"unreported","neutral"],["Runtime",t.map.runtimeProfile?.deviceClass||"unknown","neutral"],["Loaded layers",String(t.map.loadedLayers||0),"neutral"],["Fallbacks",String(t.map.fallbackCount||0),t.map.fallbackCount?"warning":"ok"],["Seat circles",t.elections.seatCircleRenderMs?`${t.elections.seatCircleRenderMs}ms`:"not active","neutral"],["Heap",t.browser.memory?ha(t.browser.memory):"unreported","neutral"]];e.innerHTML=d.map(([h,u,p])=>`
    ${me(h)} ${me(u)}
    - `).join("")}async loadTimelineTransitionManifest(){try{let e=await fetch(`${Ri}/manifest.json`,{cache:"force-cache"});if(!e.ok)return;let t=await e.json(),a=Array.isArray(t?.transitions)?t.transitions:[],i=a.map(s=>s?.id).filter(Boolean);if(!i.length)return;this.timelineTransitionSidecarSet=new Set([...Oi,...i]),this.timelineTransitionManifestEntries=new Map(a.filter(s=>s?.id).map(s=>[s.id,s])),window.__civgraphTest2={...window.__civgraphTest2||{},timelineTransitionManifest:t}}catch{this.timelineTransitionSidecarSet=new Set(ra),this.timelineTransitionManifestEntries=new Map}}getTimelineTransitionSidecarSet(){return this.timelineTransitionSidecarSet instanceof Set?this.timelineTransitionSidecarSet:ra}setupTimelineControls(){let e=document.getElementById("timelineRange"),t=document.getElementById("timelinePrev"),a=document.getElementById("timelineNext"),i=document.getElementById("timelineReset"),s=document.getElementById("timelinePlay"),n=document.getElementById("timelineStop"),r=0,o=Promise.resolve(),l=async(d,h={})=>{let u=this.getTimelineAnimationItems();if(!u.length||!this.timelineOnSelect)return;h.manual!==!1&&this.pauseTimelineAnimation({preserveOverlay:!0});let p=this.clampTimelineIndex(d,u),f=++r;this.setTimelineRangeIndex(p),this.timelineAnimation.currentIndex=p;let g=o.then(async()=>{if(f===r){this.beginTimelineApply();try{await this.timelineOnSelect(u[p],p)}finally{this.endTimelineApply()}f===r&&(this.setTimelineRangeIndex(p),this.timelineAnimation.currentIndex=p,this.updateTimelineAnimationButtons())}});return o=g.catch(()=>{}),g};window.__civgraphTest2&&(window.__civgraphTest2.timeline={element:e,getItems:()=>this.getTimelineAnimationItems(),getIndex:()=>this.getTimelineRangeIndex(),setIndex:d=>l(d),isApplying:()=>this.timelineApplying,currentIndex:()=>this.timelineAnimation.currentIndex}),e?.addEventListener("change",d=>l(d.target.value).catch(h=>this.showMapError(h))),e?.addEventListener("input",d=>{this.pauseTimelineAnimation({preserveOverlay:!0});let h=this.getTimelineAnimationItems(),u=this.clampTimelineIndex(d.target.value,h);this.timelineAnimation.currentIndex=u,this.updateTimelineLabel(u),this.updateTimelineAnimationButtons()}),t?.addEventListener("click",()=>l(this.getTimelineRangeIndex()-1).catch(d=>this.showMapError(d))),a?.addEventListener("click",()=>l(this.getTimelineRangeIndex()+1).catch(d=>this.showMapError(d))),i?.addEventListener("click",()=>{let d=Math.max(0,this.getTimelineAnimationItems().length-1);l(d).catch(h=>this.showMapError(h))}),s?.addEventListener("click",()=>{if(this.timelineAnimation.playing){this.pauseTimelineAnimation({preserveOverlay:!0});return}this.startTimelineAnimation().catch(d=>this.showMapError(d))}),n?.addEventListener("click",()=>{this.stopTimelineAnimation({restoreOriginal:!0}).catch(d=>this.showMapError(d))})}beginTimelineApply(){this.timelineApplyDepth=(this.timelineApplyDepth||0)+1,this.timelineApplying=!0}endTimelineApply(){return this.timelineApplyDepth=Math.max(0,(this.timelineApplyDepth||0)-1),this.timelineApplying=this.timelineApplyDepth>0,!this.timelineApplying}setTimelineItems(e,t,a){let i=document.getElementById("timelineSlider"),s=document.getElementById("timelineRange"),n=Array.isArray(e)?e.filter(h=>!h?.mapId||this.isTimelineMapPlayable(h.mapId)):[];if(this.timelineItems=n,this.timelineOnSelect=typeof a=="function"?a:null,!i||!s||this.timelineItems.length<2||!this.timelineOnSelect){this.hideTimeline();return}let r=Array.isArray(e)?e[Number(t)]:null,o=(h,u)=>!h||!u?!1:u.mapId!=null?h.mapId===u.mapId:u.timestamp!=null?h.timestamp===u.timestamp:u.date!=null?h.date===u.date&&h.body===u.body:!1,l=this.timelineItems.findIndex(h=>o(h,r)),d=this.clampTimelineIndex(l>=0?l:t);s.min="0",s.max=String(this.timelineItems.length-1),this.setTimelineRangeIndex(d),i.classList.remove("hidden"),this.updateTimelineLabel(d),this.updateTimelineAnimationButtons(),this.notifyTimelineLayoutChanged()}selectTimelineTransitionSequence(e){let t=Array.isArray(e)?e.filter(s=>s?.mapId&&this.isTimelineMapPlayable(s.mapId)):[],a=[],i=[];for(let s of t){if(!i.length){i=[s];continue}let n=i[i.length-1];if(this.hasTimelineTransitionSidecar(n.mapId,s.mapId)){i.push(s);continue}i.length>a.length&&(a=i),i=[s]}return i.length>a.length&&(a=i),a.length>=2?a:[]}hasTimelineTransitionSidecar(e,t){let a=this.getTimelineTransitionSidecarSet();return this.getTimelineTransitionKeys(e,t).some(i=>a.has(i))}clampTimelineIndex(e,t=this.timelineItems){let a=Array.isArray(t)?t:[];return a.length?Math.max(0,Math.min(a.length-1,Number(e)||0)):0}getTimelineRangeIndex(){return this.clampTimelineIndex(document.getElementById("timelineRange")?.value||0)}setTimelineRangeIndex(e){let t=this.clampTimelineIndex(e),a=document.getElementById("timelineRange");if(a&&(a.value=String(t)),this.updateTimelineLabel(t),window.__civgraphTest2){let i=window.__civgraphTest2.timelineWrites||(window.__civgraphTest2.timelineWrites=[]);i.length>200&&i.shift(),i.push({index:t,from:String(new Error().stack||"").split(` -`).slice(1,6).join(" | ")})}return t}getTimelineAnimationItems(){let e=this.timelineAnimation?.sequenceItems;return Array.isArray(e)&&e.length?e:this.timelineItems}updateTimelineLabel(e){let t=this.getTimelineAnimationItems(),a=t[this.clampTimelineIndex(e,t)],i=document.getElementById("timelineLabel");i&&(i.textContent=this.formatTimelineItemLabel(a))}hideTimeline(){this.clearTimelineAnimationTimer(),this.timelineItems=[],this.timelineOnSelect=null,this.timelineAnimation.runId+=1,this.timelineAnimation.playing=!1,this.timelineAnimation.paused=!1,this.timelineAnimation.atEnd=!1,this.timelineAnimation.singleLayerReferenceId=null,this.timelineAnimation.sequenceItems=[],this.mapController?.clearTimelineTransitionOverlay?.(),document.getElementById("timelineSlider")?.classList.add("hidden"),this.updateTimelineAnimationButtons(),this.notifyTimelineLayoutChanged()}notifyTimelineLayoutChanged(){requestAnimationFrame(()=>this.mapController?.invalidateSize?.())}installOutsideMapHighlightClear(){this._outsideMapHighlightClearInstalled||(this._outsideMapHighlightClearInstalled=!0,document.addEventListener("pointerdown",e=>{e.target?.closest?.("#map, .maplibregl-map, .maplibre-dom-label")||this.mapController?.clearTransientHighlight?.()},!0))}isTimelineRunCurrent(e){return this.timelineAnimation.runId===e&&this.timelineAnimation.playing}updateTimeline(){if(this.timelineApplying||this.timelineAnimation?.playing)return;if(this.elections?.activeEntry){this.elections.updateElectionTimeline();return}let e=this.getLoadedLayerIds().filter(l=>P.getMapById(l)).filter(l=>this.isMapVisible(l)),t=[],a=new Set;for(let l of e){let d=P.getChainForMap?.(l);!d||a.has(d.id)||(a.add(d.id),t.push(d))}if(!t.length){this.hideTimeline();return}let i=(P.getApplicableDates?.(t)||[]).filter(l=>Number.isFinite(Number(l))).sort((l,d)=>l-d);if(i.length<2){this.hideTimeline();return}let s=e.length===1?e[0]:this.timelineAnimation.singleLayerReferenceId;this.timelineAnimation.singleLayerReferenceId=e.length===1?e[0]:this.timelineAnimation.singleLayerReferenceId;let n=this.getCurrentTimelineTimestamp(e),r=i.map(l=>({timestamp:l,label:this.formatTimelineTimestamp(l),mapId:s?this.getTimelineMapIdForTimestamp(s,l):null})).filter(l=>this.isTimelineMapPlayable(l.mapId)),o=r.findIndex(l=>l.timestamp===n);this.setTimelineItems(r,o>=0?o:r.length-1,async(l,d)=>{this.timelineAnimation.currentIndex=this.clampTimelineIndex(d),await this.applyTimelineTimestamp(l.timestamp)})}getTimelineMapIdForTimestamp(e,t){if(!e||!Number.isFinite(Number(t)))return null;let i=(P.getEquivalentMapsForDate?.([e],t)||{})[e];if(i&&this.isTimelineMapPlayable(i))return i;let s=P.getMapById(e);return P.parseMapDate?.(s?.date)===t&&this.isTimelineMapPlayable(e)?e:null}getCurrentTimelineTimestamp(e){let t=e.map(a=>P.parseMapDate?.(P.getMapById(a)?.date)).filter(a=>Number.isFinite(Number(a)));return t.length?Math.max(...t):null}formatTimelineTimestamp(e){let t=new Date(Number(e));return Number.isFinite(t.getTime())?this.formatTimelineDate(t):""}formatTimelineItemLabel(e){if(!e)return"";let t=[e.timestamp,e.date,e.label];for(let a of t){let i=this.parseTimelineDate(a);if(i)return this.formatTimelineDate(i)}return e.label||""}parseTimelineDate(e){if(e==null||e==="")return null;if(typeof e=="number"||/^\d+$/.test(String(e))){let i=Number(e),s=i>9999?new Date(i):new Date(Date.UTC(i,0,1));return Number.isFinite(s.getTime())?s:null}let t=String(e).trim().match(/^(\d{4})(?:-(\d{2})(?:-(\d{2}))?)?$/);if(t){let i=Number(t[1]),s=Number(t[2]||1)-1,n=Number(t[3]||1),r=new Date(Date.UTC(i,s,n));return Number.isFinite(r.getTime())?r:null}let a=new Date(e);return Number.isFinite(a.getTime())?a:null}formatTimelineDate(e){return e.toLocaleDateString("en-GB",{day:"2-digit",month:"short",year:"numeric",timeZone:"UTC"})}async applyTimelineTimestamp(e,t={}){let a=this.getLoadedLayerIds().filter(s=>P.getMapById(s)).filter(s=>this.isMapVisible(s)),i=P.getEquivalentMapsForDate?.(a,e)||{};this.beginTimelineApply();try{for(let[s,n]of Object.entries(i))!n||n===s||!this.isTimelineMapPlayable(n)||(await this.unloadMap(s,{preserveTimelineAnimation:!0}),await this.loadMap(n,{fit:t.fit!==!1}));this.syncCatalogueMapState(),this.updateActiveLayers(),this.updateURLState()}finally{this.endTimelineApply()&&this.updateTimeline()}}getTimelineItemMapIds(){return new Set(this.getTimelineAnimationItems().map(e=>e?.mapId).filter(Boolean))}isTimelineAnimationLayer(e){if(!e)return!1;let t=this.timelineAnimation||{};return!!(t.playing||t.paused||t.originalLayerId)&&(t.originalLayerId===e||this.getTimelineItemMapIds().has(e))}getVisibleTimelineLayerIds(){let e=this.getTimelineItemMapIds();return this.getLoadedLayerIds().filter(t=>e.has(t)).filter(t=>this.isMapVisible(t))}canAnimateTimeline(){return this.elections?.activeEntry||!this.timelineItems.length||this.timelineItems.length<2||!this.timelineOnSelect||this.getTimelineItemMapIds().size<2?!1:this.timelineAnimation.playing||this.timelineAnimation.paused||this.timelineAnimation.originalLayerId?!0:this.getVisibleTimelineLayerIds().length===1}updateTimelineAnimationButtons(){let e=document.getElementById("timelinePlay"),t=document.getElementById("timelineStop");if(!e||!t)return;let a=this.canAnimateTimeline(),{playing:i,paused:s,atEnd:n,originalLayerId:r}=this.timelineAnimation;e.disabled=!a,t.disabled=!(i||s||r),e.classList.toggle("is-playing",i),e.classList.toggle("is-paused",s),e.classList.toggle("is-replay",n&&!i),i?(e.title="Pause territorial animation",e.setAttribute("aria-label","Pause territorial animation"),e.innerHTML=''):n?(e.title="Replay territorial animation",e.setAttribute("aria-label","Replay territorial animation"),e.innerHTML=''):(e.title="Play territorial animation",e.setAttribute("aria-label","Play territorial animation"),e.innerHTML=''),t.title="Stop territorial animation",t.setAttribute("aria-label","Stop territorial animation")}clearTimelineAnimationTimer(){if(this.timelineAnimation.timer&&(window.clearTimeout(this.timelineAnimation.timer),this.timelineAnimation.timer=0),this.timelineAnimation.delayResolve){let e=this.timelineAnimation.delayResolve;this.timelineAnimation.delayResolve=null,e()}}scheduleTimelineAnimation(e,t){this.clearTimelineAnimationTimer(),this.timelineAnimation.timer=window.setTimeout(()=>{this.timelineAnimation.timer=0,t()},Math.max(0,Number(e)||0))}waitTimelineDelay(e){return this.clearTimelineAnimationTimer(),new Promise(t=>{this.timelineAnimation.delayResolve=t,this.timelineAnimation.timer=window.setTimeout(()=>{this.timelineAnimation.timer=0,this.timelineAnimation.delayResolve=null,t()},Math.max(0,Number(e)||0))})}pauseTimelineAnimation(e={}){let t=this.timelineAnimation.playing||this.timelineAnimation.paused;t&&(this.timelineAnimation.runId+=1),this.clearTimelineAnimationTimer(),t&&(this.timelineAnimation.playing=!1,this.timelineAnimation.paused=!0,this.timelineAnimation.currentIndex=this.getTimelineRangeIndex()),t&&e.preserveOverlay!==!0&&this.mapController?.clearTimelineTransitionOverlay?.(),this.updateTimelineAnimationButtons()}async stopTimelineAnimation(e={}){let{restoreOriginal:t=!0}=e,a=this.timelineAnimation.originalLayerId,i=this.timelineAnimation.playing||this.timelineAnimation.paused||a;if(this.timelineAnimation.runId+=1,this.clearTimelineAnimationTimer(),this.timelineAnimation.playing=!1,this.timelineAnimation.paused=!1,this.timelineAnimation.atEnd=!1,this.mapController?.clearTimelineTransitionOverlay?.(),!i){this.updateTimelineAnimationButtons();return}if(t&&a&&P.getMapById(a)){let s=this.getTimelineItemMapIds();this.beginTimelineApply();try{for(let l of this.getLoadedLayerIds())l!==a&&s.has(l)&&await this.unloadMap(l,{preserveTimelineAnimation:!0});this.isMapLoaded(a)||await this.loadMap(a,{fit:!1}),this.mapController.showLayer?.(a);let n=P.parseMapDate?.(P.getMapById(a)?.date),o=this.getTimelineAnimationItems().findIndex(l=>l.mapId===a||l.timestamp===n);o>=0&&this.setTimelineRangeIndex(o),this.syncCatalogueMapState(),this.updateActiveLayers(),this.updateURLState()}finally{this.endTimelineApply()&&this.updateTimeline()}}this.timelineAnimation.originalLayerId=null,this.timelineAnimation.sequenceItems=[],this.timelineAnimation.currentIndex=this.getTimelineRangeIndex(),this.updateTimelineAnimationButtons()}async startTimelineAnimation(){if(!this.canAnimateTimeline()){this.updateTimelineAnimationButtons();return}let e=this.timelineAnimation.paused&&Array.isArray(this.timelineAnimation.sequenceItems)&&this.timelineAnimation.sequenceItems.length?this.timelineAnimation.sequenceItems:this.timelineItems.slice();this.timelineAnimation.sequenceItems=e;let t=this.getVisibleTimelineLayerIds();(!this.timelineAnimation.originalLayerId||this.timelineAnimation.atEnd)&&(this.timelineAnimation.originalLayerId=t[0]||e[this.getTimelineRangeIndex()]?.mapId||null);let a=this.timelineAnimation.paused?this.timelineAnimation.currentIndex:0;this.timelineAnimation.atEnd&&(a=0),a=this.clampTimelineIndex(a,e);let i=this.timelineAnimation.runId+1;this.timelineAnimation.runId=i,this.timelineAnimation.playing=!0,this.timelineAnimation.paused=!1,this.timelineAnimation.atEnd=!1,this.timelineAnimation.currentIndex=a,this.setTimelineRangeIndex(a),this.updateTimelineAnimationButtons();let s=e[a];if(s?.timestamp!==void 0&&await this.applyTimelineTimestamp(s.timestamp,{fit:!1}),!!this.isTimelineRunCurrent(i)){if(a>=e.length-1){this.timelineAnimation.playing=!1,this.timelineAnimation.atEnd=!0,this.updateTimelineAnimationButtons();return}this.scheduleTimelineAnimation(Ct.start,()=>{this.advanceTimelineAnimation(i).catch(n=>this.showMapError(n))})}}async advanceTimelineAnimation(e=this.timelineAnimation.runId){if(!this.isTimelineRunCurrent(e))return;let t=this.getTimelineAnimationItems(),a=this.clampTimelineIndex(this.timelineAnimation.currentIndex,t),i=a+1;if(i>=t.length){this.timelineAnimation.playing=!1,this.timelineAnimation.paused=!1,this.timelineAnimation.atEnd=!0,this.updateTimelineAnimationButtons();return}if(await this.applyTimelineAnimationTransition(a,i,e,t),!!this.isTimelineRunCurrent(e)){if(this.timelineAnimation.currentIndex=i,i>=t.length-1){this.timelineAnimation.playing=!1,this.timelineAnimation.paused=!1,this.timelineAnimation.atEnd=!0,this.updateTimelineAnimationButtons();return}this.scheduleTimelineAnimation(Ct.start,()=>{this.advanceTimelineAnimation(e).catch(s=>this.showMapError(s))})}}async applyTimelineAnimationTransition(e,t,a=this.timelineAnimation.runId,i=this.getTimelineAnimationItems()){let s=Array.isArray(i)&&i.length?i:this.getTimelineAnimationItems(),n=s[this.clampTimelineIndex(e,s)],r=s[this.clampTimelineIndex(t,s)],o=n?.mapId,l=r?.mapId;if(!o||!l){r?.timestamp!==void 0&&await this.applyTimelineTimestamp(r.timestamp,{fit:!1}),this.timelineAnimation.currentIndex=this.clampTimelineIndex(t,s);return}this.beginTimelineApply();try{if(!this.isTimelineMapPlayable(o)||!this.isTimelineMapPlayable(l)){r?.timestamp!==void 0&&await this.applyTimelineTimestamp(r.timestamp,{fit:!1}),this.timelineAnimation.currentIndex=this.clampTimelineIndex(t,s);return}let d=await this.ensureTimelineLayerLoaded(o);if(!this.isTimelineRunCurrent(a))return;let h=await this.ensureTimelineLayerLoaded(l);if(!this.isTimelineRunCurrent(a))return;if(!d||!h){r?.timestamp!==void 0&&await this.applyTimelineTimestamp(r.timestamp,{fit:!1}),this.timelineAnimation.currentIndex=this.clampTimelineIndex(t,s);return}this.mapController.showLayer?.(o),this.mapController.showLayer?.(l);let u=await this.loadTimelineTransitionOverlay(o,l);if(!this.isTimelineRunCurrent(a))return;u?.features?.length?this.mapController.setTimelineTransitionOverlay?.(u,{fromMapId:o,toMapId:l,minAreaM2:Di}):this.mapController.clearTimelineTransitionOverlay?.(),this.setTimelineRangeIndex(t),this.timelineAnimation.currentIndex=this.clampTimelineIndex(t,s),this.syncCatalogueMapState(),this.updateActiveLayers(),this.updateURLState()}finally{this.endTimelineApply()&&this.updateTimeline()}await this.waitTimelineDelay(Ct.overlay),this.isTimelineRunCurrent(a)&&(this.mapController.clearTimelineTransitionOverlay?.({fade:!0}),await this.waitTimelineDelay(Ct.settle),this.isTimelineRunCurrent(a)&&(o!==l&&this.isMapLoaded(o)&&await this.unloadMap(o,{preserveTimelineAnimation:!0}),this.syncCatalogueMapState(),this.updateActiveLayers(),this.updateURLState()))}async ensureTimelineLayerLoaded(e){return this.isTimelineMapPlayable(e)?(this.isMapLoaded(e)||await this.loadMap(e,{fit:!1}),this.mapController.showLayer?.(e),!0):!1}getTimelineTransitionCandidateIds(e){let t=P.getMapById(e),a=new Set,i=s=>{if(!s)return;let n=String(s).trim();if(!n)return;let r=[n,n.replace(/-vector-test$/,""),n.replace(/-(standard|full|largescale|50k)$/,"")],o=n.match(/^wards-(1972|1984|1993|2012)(?:-|$)/);o&&r.push("wards-"+o[1]),/^wards-2022(?:-|$)/.test(n)&&r.push("wards-2022-final-recommendations");for(let l of r)l&&a.add(l)};return i(e),i(t?.id),i(t?.sourceMapId),i(t?.cloneOf),i(t?.aliasOf),i(t?.parentId),i(t?.coLoadMapId),[...a]}getTimelineTransitionKeys(e,t){let a=this.getTimelineTransitionCandidateIds(e),i=this.getTimelineTransitionCandidateIds(t),s=[],n=[],r=new Set;for(let o of a)for(let l of i){let d=o+"__"+l;r.has(d)||(r.add(d),this.getTimelineTransitionSidecarSet().has(d)?s.push(d):n.push(d))}return[...s,...n]}async loadTimelineTransitionOverlay(e,t){let a=this.getTimelineTransitionKeys(e,t);for(let i of a){let s=this.timelineTransitionManifestEntries?.get?.(i),n=s?Array.isArray(s.runtimePaths)&&s.runtimePaths.length?s.runtimePaths:[s.runtimePath].filter(Boolean):[];if(n.length){let o=await this.fetchTimelineTransitionGeoJsonParts(n);if(o?.features?.length)return o}let r=n.length?[`${Ni}/${i}.geojson`]:[`${Ri}/${i}.geojson`,`${Ni}/${i}.geojson`];for(let o of r){let l=await this.fetchTimelineTransitionGeoJson(o);if(l?.features?.length)return l}}return null}async fetchTimelineTransitionGeoJsonParts(e){let t=(Array.isArray(e)?e:[]).map(o=>String(o||"").trim()).filter(Boolean).map(o=>o.startsWith("/")?o:`/${o}`);if(!t.length)return null;let a=`parts:${t.join("|")}`;if(this.timelineTransitionCache.has(a))return this.timelineTransitionCache.get(a);let i=[],s="Territorial transition",n={};for(let o of t){let l=await this.fetchTimelineTransitionGeoJson(o);l&&(l.name&&(s=l.name),n={...n,...l.metadata||{}},Array.isArray(l.features)&&i.push(...l.features))}let r=i.length?{type:"FeatureCollection",name:s,metadata:n,features:i}:null;return this.timelineTransitionCache.set(a,r),r}async fetchTimelineTransitionGeoJson(e){if(this.timelineTransitionCache.has(e))return this.timelineTransitionCache.get(e);try{let t=await fetch(e,{cache:"force-cache"}),a=String(t.headers?.get?.("content-type")||"").toLowerCase();if(!t.ok||a.includes("text/html"))return this.timelineTransitionCache.set(e,null),null;let i=await t.json(),s=this.filterTimelineTransitionGeoJson(i);return this.timelineTransitionCache.set(e,s),s}catch{return this.timelineTransitionCache.set(e,null),null}}filterTimelineTransitionGeoJson(e){let t=(Array.isArray(e?.features)?e.features:[]).filter(a=>{let i=Number(a?.properties?.area_m2??a?.properties?.areaM2??a?.properties?.areaSqm);return!Number.isFinite(i)||i>=Di});return{type:"FeatureCollection",name:e?.name||"Territorial transition",metadata:e?.metadata||{},features:t}}async unloadMap(e,t={}){if(!t.preserveTimelineAnimation&&this.isTimelineAnimationLayer(e)&&await this.stopTimelineAnimation({restoreOriginal:!1}),this.unloadActiveElectionForLayer(e))return;let a=P.getMapById(e);this.mapController.getLayerState(e)?.isGroup?this.mapController.unloadLayer(e):a?.isGroup&&oe(a).length?(oe(a).forEach(i=>this.mapController.unloadLayer(i)),this.mapController.unloadLayer(e)):a?.isGroup&&Array.isArray(a.variants)?(a.variants.forEach(i=>this.mapController.unloadLayer(i.id)),this.mapController.unloadLayer(e)):this.mapController.unloadLayer(e)}unloadActiveElectionForLayer(e){if(!e||!this.elections?.activeEntry||!this.isActiveElectionLayerId(e))return!1;let t=this.getActiveElectionBackingLayerIds(e);this.elections.unloadElection({unloadBackingLayer:!1});for(let a of t)(this.mapController.getLayerState(a)||this.mapController.groupStates?.has(a))&&this.mapController.unloadLayer(a);return!0}isActiveElectionLayerId(e){if(!e||!this.elections?.activeEntry)return!1;let t=this.getActiveElectionLayerIds();return[...this.getMapUnloadCandidateIds(e)].some(i=>t.has(i))}getActiveElectionLayerIds(){if(!this.elections?.activeEntry)return new Set;let e=this.elections.activeEntry,t=this.elections.activeBundle;return new Set([this.elections.getCanonicalLayerId?.(e),e?.sourceMapId,t?.sourceMapId,t?.layerId].filter(Boolean))}getMapUnloadCandidateIds(e){let t=P.getMapById(e);return new Set([e,...oe(t),...Array.isArray(t?.variants)?t.variants.map(a=>a?.id).filter(Boolean):[]].filter(Boolean))}getActiveElectionBackingLayerIds(e){let t=this.elections?.activeEntry,a=this.elections?.activeBundle,i=new Set([t?.sourceMapId,a?.sourceMapId,a?.layerId].filter(Boolean)),n=[...this.getMapUnloadCandidateIds(e)].filter(r=>i.has(r));return n.length?n:[...i]}setMapControlsOpen(e){let t=document.getElementById("mapControlsToggle"),a=document.getElementById("mapControlPanel");t?.setAttribute("aria-expanded",String(!!e)),a?.classList.toggle("map-control-panel--collapsed",!e),a?.classList.toggle("map-control-panel--expanded",!!e),this.updateURLState()}setActiveLayersPanelOpen(e){let t=document.getElementById("activeLayersToggle"),a=document.getElementById("activeLayers");t?.setAttribute("aria-expanded",String(!!e)),a?.classList.toggle("hidden",!e),this.updateURLState()}async applyBaseMap(e,{userChoice:t=!1}={}){if(this.baseMapId=e||"osm-standard",t){this.userPickedBasemap=!0;try{localStorage.setItem("basemapUserChoice","1")}catch{}}let a=this.mapController?.map;a&&(typeof a.isStyleLoaded=="function"&&!a.isStyleLoaded()&&await new Promise(i=>a.once("load",i)),this.mapController.setBaseMap(this.baseMapId))}async syncBasemapToTheme(){if(this.userPickedBasemap)return null;let e="osm-standard";if(this.baseMapId===e)return null;await this.applyBaseMap(e);let t=document.getElementById("baseMapSelect");return t&&(t.value=e),e}setupSourcePanel(){if(document.getElementById("test2SourcePanel"))return;let e=document.createElement("aside");e.id="test2SourcePanel",e.className="test2-source-panel hidden",e.setAttribute("aria-label","Layer sources"),e.innerHTML=` + `).join("")}async loadTimelineTransitionManifest(){try{let e=await fetch(`${Ui}/manifest.json`,{cache:"force-cache"});if(!e.ok)return;let t=await e.json(),a=Array.isArray(t?.transitions)?t.transitions:[],i=a.map(s=>s?.id).filter(Boolean);if(!i.length)return;this.timelineTransitionSidecarSet=new Set([...ji,...i]),this.timelineTransitionManifestEntries=new Map(a.filter(s=>s?.id).map(s=>[s.id,s])),window.__civgraphTest2={...window.__civgraphTest2||{},timelineTransitionManifest:t}}catch{this.timelineTransitionSidecarSet=new Set(ua),this.timelineTransitionManifestEntries=new Map}}getTimelineTransitionSidecarSet(){return this.timelineTransitionSidecarSet instanceof Set?this.timelineTransitionSidecarSet:ua}setupTimelineControls(){let e=document.getElementById("timelineRange"),t=document.getElementById("timelinePrev"),a=document.getElementById("timelineNext"),i=document.getElementById("timelineReset"),s=document.getElementById("timelinePlay"),n=document.getElementById("timelineStop"),r=0,o=Promise.resolve(),l=async(d,h={})=>{let u=this.getTimelineAnimationItems();if(!u.length||!this.timelineOnSelect)return;h.manual!==!1&&this.pauseTimelineAnimation({preserveOverlay:!0});let p=this.clampTimelineIndex(d,u),f=++r;this.setTimelineRangeIndex(p),this.timelineAnimation.currentIndex=p;let g=o.then(async()=>{if(f===r){this.beginTimelineApply();try{await this.timelineOnSelect(u[p],p)}finally{this.endTimelineApply()}f===r&&(this.setTimelineRangeIndex(p),this.timelineAnimation.currentIndex=p,this.updateTimelineAnimationButtons())}});return o=g.catch(()=>{}),g};window.__civgraphTest2&&(window.__civgraphTest2.timeline={element:e,getItems:()=>this.getTimelineAnimationItems(),getIndex:()=>this.getTimelineRangeIndex(),setIndex:d=>l(d),isApplying:()=>this.timelineApplying,currentIndex:()=>this.timelineAnimation.currentIndex}),e?.addEventListener("change",d=>l(d.target.value).catch(h=>this.showMapError(h))),e?.addEventListener("input",d=>{this.pauseTimelineAnimation({preserveOverlay:!0});let h=this.getTimelineAnimationItems(),u=this.clampTimelineIndex(d.target.value,h);this.timelineAnimation.currentIndex=u,this.updateTimelineLabel(u),this.updateTimelineAnimationButtons()}),t?.addEventListener("click",()=>l(this.getTimelineRangeIndex()-1).catch(d=>this.showMapError(d))),a?.addEventListener("click",()=>l(this.getTimelineRangeIndex()+1).catch(d=>this.showMapError(d))),i?.addEventListener("click",()=>{let d=Math.max(0,this.getTimelineAnimationItems().length-1);l(d).catch(h=>this.showMapError(h))}),s?.addEventListener("click",()=>{if(this.timelineAnimation.playing){this.pauseTimelineAnimation({preserveOverlay:!0});return}this.startTimelineAnimation().catch(d=>this.showMapError(d))}),n?.addEventListener("click",()=>{this.stopTimelineAnimation({restoreOriginal:!0}).catch(d=>this.showMapError(d))})}beginTimelineApply(){this.timelineApplyDepth=(this.timelineApplyDepth||0)+1,this.timelineApplying=!0}endTimelineApply(){return this.timelineApplyDepth=Math.max(0,(this.timelineApplyDepth||0)-1),this.timelineApplying=this.timelineApplyDepth>0,!this.timelineApplying}setTimelineItems(e,t,a){let i=document.getElementById("timelineSlider"),s=document.getElementById("timelineRange"),n=Array.isArray(e)?e.filter(h=>!h?.mapId||this.isTimelineMapPlayable(h.mapId)):[];if(this.timelineItems=n,this.timelineOnSelect=typeof a=="function"?a:null,!i||!s||this.timelineItems.length<2||!this.timelineOnSelect){this.hideTimeline();return}let r=Array.isArray(e)?e[Number(t)]:null,o=(h,u)=>!h||!u?!1:u.mapId!=null?h.mapId===u.mapId:u.timestamp!=null?h.timestamp===u.timestamp:u.date!=null?h.date===u.date&&h.body===u.body:!1,l=this.timelineItems.findIndex(h=>o(h,r)),d=this.clampTimelineIndex(l>=0?l:t);s.min="0",s.max=String(this.timelineItems.length-1),this.setTimelineRangeIndex(d),i.classList.remove("hidden"),this.updateTimelineLabel(d),this.updateTimelineAnimationButtons(),this.notifyTimelineLayoutChanged()}selectTimelineTransitionSequence(e){let t=Array.isArray(e)?e.filter(s=>s?.mapId&&this.isTimelineMapPlayable(s.mapId)):[],a=[],i=[];for(let s of t){if(!i.length){i=[s];continue}let n=i[i.length-1];if(this.hasTimelineTransitionSidecar(n.mapId,s.mapId)){i.push(s);continue}i.length>a.length&&(a=i),i=[s]}return i.length>a.length&&(a=i),a.length>=2?a:[]}hasTimelineTransitionSidecar(e,t){let a=this.getTimelineTransitionSidecarSet();return this.getTimelineTransitionKeys(e,t).some(i=>a.has(i))}clampTimelineIndex(e,t=this.timelineItems){let a=Array.isArray(t)?t:[];return a.length?Math.max(0,Math.min(a.length-1,Number(e)||0)):0}getTimelineRangeIndex(){return this.clampTimelineIndex(document.getElementById("timelineRange")?.value||0)}setTimelineRangeIndex(e){let t=this.clampTimelineIndex(e),a=document.getElementById("timelineRange");if(a&&(a.value=String(t)),this.updateTimelineLabel(t),window.__civgraphTest2){let i=window.__civgraphTest2.timelineWrites||(window.__civgraphTest2.timelineWrites=[]);i.length>200&&i.shift(),i.push({index:t,from:String(new Error().stack||"").split(` +`).slice(1,6).join(" | ")})}return t}getTimelineAnimationItems(){let e=this.timelineAnimation?.sequenceItems;return Array.isArray(e)&&e.length?e:this.timelineItems}updateTimelineLabel(e){let t=this.getTimelineAnimationItems(),a=t[this.clampTimelineIndex(e,t)],i=document.getElementById("timelineLabel");i&&(i.textContent=this.formatTimelineItemLabel(a))}hideTimeline(){this.clearTimelineAnimationTimer(),this.timelineItems=[],this.timelineOnSelect=null,this.timelineAnimation.runId+=1,this.timelineAnimation.playing=!1,this.timelineAnimation.paused=!1,this.timelineAnimation.atEnd=!1,this.timelineAnimation.singleLayerReferenceId=null,this.timelineAnimation.sequenceItems=[],this.mapController?.clearTimelineTransitionOverlay?.(),document.getElementById("timelineSlider")?.classList.add("hidden"),this.updateTimelineAnimationButtons(),this.notifyTimelineLayoutChanged()}notifyTimelineLayoutChanged(){requestAnimationFrame(()=>this.mapController?.invalidateSize?.())}installOutsideMapHighlightClear(){this._outsideMapHighlightClearInstalled||(this._outsideMapHighlightClearInstalled=!0,document.addEventListener("pointerdown",e=>{e.target?.closest?.("#map, .maplibregl-map, .maplibre-dom-label")||this.mapController?.clearTransientHighlight?.()},!0))}isTimelineRunCurrent(e){return this.timelineAnimation.runId===e&&this.timelineAnimation.playing}updateTimeline(){if(this.timelineApplying||this.timelineAnimation?.playing)return;if(this.elections?.activeEntry){this.elections.updateElectionTimeline();return}let e=this.getLoadedLayerIds().filter(l=>P.getMapById(l)).filter(l=>this.isMapVisible(l)),t=[],a=new Set;for(let l of e){let d=P.getChainForMap?.(l);!d||a.has(d.id)||(a.add(d.id),t.push(d))}if(!t.length){this.hideTimeline();return}let i=(P.getApplicableDates?.(t)||[]).filter(l=>Number.isFinite(Number(l))).sort((l,d)=>l-d);if(i.length<2){this.hideTimeline();return}let s=e.length===1?e[0]:this.timelineAnimation.singleLayerReferenceId;this.timelineAnimation.singleLayerReferenceId=e.length===1?e[0]:this.timelineAnimation.singleLayerReferenceId;let n=this.getCurrentTimelineTimestamp(e),r=i.map(l=>({timestamp:l,label:this.formatTimelineTimestamp(l),mapId:s?this.getTimelineMapIdForTimestamp(s,l):null})).filter(l=>this.isTimelineMapPlayable(l.mapId)),o=r.findIndex(l=>l.timestamp===n);this.setTimelineItems(r,o>=0?o:r.length-1,async(l,d)=>{this.timelineAnimation.currentIndex=this.clampTimelineIndex(d),await this.applyTimelineTimestamp(l.timestamp)})}getTimelineMapIdForTimestamp(e,t){if(!e||!Number.isFinite(Number(t)))return null;let i=(P.getEquivalentMapsForDate?.([e],t)||{})[e];if(i&&this.isTimelineMapPlayable(i))return i;let s=P.getMapById(e);return P.parseMapDate?.(s?.date)===t&&this.isTimelineMapPlayable(e)?e:null}getCurrentTimelineTimestamp(e){let t=e.map(a=>P.parseMapDate?.(P.getMapById(a)?.date)).filter(a=>Number.isFinite(Number(a)));return t.length?Math.max(...t):null}formatTimelineTimestamp(e){let t=new Date(Number(e));return Number.isFinite(t.getTime())?this.formatTimelineDate(t):""}formatTimelineItemLabel(e){if(!e)return"";let t=[e.timestamp,e.date,e.label];for(let a of t){let i=this.parseTimelineDate(a);if(i)return this.formatTimelineDate(i)}return e.label||""}parseTimelineDate(e){if(e==null||e==="")return null;if(typeof e=="number"||/^\d+$/.test(String(e))){let i=Number(e),s=i>9999?new Date(i):new Date(Date.UTC(i,0,1));return Number.isFinite(s.getTime())?s:null}let t=String(e).trim().match(/^(\d{4})(?:-(\d{2})(?:-(\d{2}))?)?$/);if(t){let i=Number(t[1]),s=Number(t[2]||1)-1,n=Number(t[3]||1),r=new Date(Date.UTC(i,s,n));return Number.isFinite(r.getTime())?r:null}let a=new Date(e);return Number.isFinite(a.getTime())?a:null}formatTimelineDate(e){return e.toLocaleDateString("en-GB",{day:"2-digit",month:"short",year:"numeric",timeZone:"UTC"})}async applyTimelineTimestamp(e,t={}){let a=this.getLoadedLayerIds().filter(s=>P.getMapById(s)).filter(s=>this.isMapVisible(s)),i=P.getEquivalentMapsForDate?.(a,e)||{};this.beginTimelineApply();try{for(let[s,n]of Object.entries(i))!n||n===s||!this.isTimelineMapPlayable(n)||(await this.unloadMap(s,{preserveTimelineAnimation:!0}),await this.loadMap(n,{fit:t.fit!==!1}));this.syncCatalogueMapState(),this.updateActiveLayers(),this.updateURLState()}finally{this.endTimelineApply()&&this.updateTimeline()}}getTimelineItemMapIds(){return new Set(this.getTimelineAnimationItems().map(e=>e?.mapId).filter(Boolean))}isTimelineAnimationLayer(e){if(!e)return!1;let t=this.timelineAnimation||{};return!!(t.playing||t.paused||t.originalLayerId)&&(t.originalLayerId===e||this.getTimelineItemMapIds().has(e))}getVisibleTimelineLayerIds(){let e=this.getTimelineItemMapIds();return this.getLoadedLayerIds().filter(t=>e.has(t)).filter(t=>this.isMapVisible(t))}canAnimateTimeline(){return this.elections?.activeEntry||!this.timelineItems.length||this.timelineItems.length<2||!this.timelineOnSelect||this.getTimelineItemMapIds().size<2?!1:this.timelineAnimation.playing||this.timelineAnimation.paused||this.timelineAnimation.originalLayerId?!0:this.getVisibleTimelineLayerIds().length===1}updateTimelineAnimationButtons(){let e=document.getElementById("timelinePlay"),t=document.getElementById("timelineStop");if(!e||!t)return;e.parentElement?.classList.toggle("timeline-playback-group--hidden",!!this.elections?.activeEntry);let a=this.canAnimateTimeline(),{playing:i,paused:s,atEnd:n,originalLayerId:r}=this.timelineAnimation;e.disabled=!a,t.disabled=!(i||s||r),e.classList.toggle("is-playing",i),e.classList.toggle("is-paused",s),e.classList.toggle("is-replay",n&&!i),i?(e.title="Pause territorial animation",e.setAttribute("aria-label","Pause territorial animation"),e.innerHTML=''):n?(e.title="Replay territorial animation",e.setAttribute("aria-label","Replay territorial animation"),e.innerHTML=''):(e.title="Play territorial animation",e.setAttribute("aria-label","Play territorial animation"),e.innerHTML=''),t.title="Stop territorial animation",t.setAttribute("aria-label","Stop territorial animation")}clearTimelineAnimationTimer(){if(this.timelineAnimation.timer&&(window.clearTimeout(this.timelineAnimation.timer),this.timelineAnimation.timer=0),this.timelineAnimation.delayResolve){let e=this.timelineAnimation.delayResolve;this.timelineAnimation.delayResolve=null,e()}}scheduleTimelineAnimation(e,t){this.clearTimelineAnimationTimer(),this.timelineAnimation.timer=window.setTimeout(()=>{this.timelineAnimation.timer=0,t()},Math.max(0,Number(e)||0))}waitTimelineDelay(e){return this.clearTimelineAnimationTimer(),new Promise(t=>{this.timelineAnimation.delayResolve=t,this.timelineAnimation.timer=window.setTimeout(()=>{this.timelineAnimation.timer=0,this.timelineAnimation.delayResolve=null,t()},Math.max(0,Number(e)||0))})}pauseTimelineAnimation(e={}){let t=this.timelineAnimation.playing||this.timelineAnimation.paused;t&&(this.timelineAnimation.runId+=1),this.clearTimelineAnimationTimer(),t&&(this.timelineAnimation.playing=!1,this.timelineAnimation.paused=!0,this.timelineAnimation.currentIndex=this.getTimelineRangeIndex()),t&&e.preserveOverlay!==!0&&this.mapController?.clearTimelineTransitionOverlay?.(),this.updateTimelineAnimationButtons()}async stopTimelineAnimation(e={}){let{restoreOriginal:t=!0}=e,a=this.timelineAnimation.originalLayerId,i=this.timelineAnimation.playing||this.timelineAnimation.paused||a;if(this.timelineAnimation.runId+=1,this.clearTimelineAnimationTimer(),this.timelineAnimation.playing=!1,this.timelineAnimation.paused=!1,this.timelineAnimation.atEnd=!1,this.mapController?.clearTimelineTransitionOverlay?.(),!i){this.updateTimelineAnimationButtons();return}if(t&&a&&P.getMapById(a)){let s=this.getTimelineItemMapIds();this.beginTimelineApply();try{for(let l of this.getLoadedLayerIds())l!==a&&s.has(l)&&await this.unloadMap(l,{preserveTimelineAnimation:!0});this.isMapLoaded(a)||await this.loadMap(a,{fit:!1}),this.mapController.showLayer?.(a);let n=P.parseMapDate?.(P.getMapById(a)?.date),o=this.getTimelineAnimationItems().findIndex(l=>l.mapId===a||l.timestamp===n);o>=0&&this.setTimelineRangeIndex(o),this.syncCatalogueMapState(),this.updateActiveLayers(),this.updateURLState()}finally{this.endTimelineApply()&&this.updateTimeline()}}this.timelineAnimation.originalLayerId=null,this.timelineAnimation.sequenceItems=[],this.timelineAnimation.currentIndex=this.getTimelineRangeIndex(),this.updateTimelineAnimationButtons()}async startTimelineAnimation(){if(!this.canAnimateTimeline()){this.updateTimelineAnimationButtons();return}let e=this.timelineAnimation.paused&&Array.isArray(this.timelineAnimation.sequenceItems)&&this.timelineAnimation.sequenceItems.length?this.timelineAnimation.sequenceItems:this.timelineItems.slice();this.timelineAnimation.sequenceItems=e;let t=this.getVisibleTimelineLayerIds();(!this.timelineAnimation.originalLayerId||this.timelineAnimation.atEnd)&&(this.timelineAnimation.originalLayerId=t[0]||e[this.getTimelineRangeIndex()]?.mapId||null);let a=this.timelineAnimation.paused?this.timelineAnimation.currentIndex:0;this.timelineAnimation.atEnd&&(a=0),a=this.clampTimelineIndex(a,e);let i=this.timelineAnimation.runId+1;this.timelineAnimation.runId=i,this.timelineAnimation.playing=!0,this.timelineAnimation.paused=!1,this.timelineAnimation.atEnd=!1,this.timelineAnimation.currentIndex=a,this.setTimelineRangeIndex(a),this.updateTimelineAnimationButtons();let s=e[a];if(s?.timestamp!==void 0&&await this.applyTimelineTimestamp(s.timestamp,{fit:!1}),!!this.isTimelineRunCurrent(i)){if(a>=e.length-1){this.timelineAnimation.playing=!1,this.timelineAnimation.atEnd=!0,this.updateTimelineAnimationButtons();return}this.scheduleTimelineAnimation(Et.start,()=>{this.advanceTimelineAnimation(i).catch(n=>this.showMapError(n))})}}async advanceTimelineAnimation(e=this.timelineAnimation.runId){if(!this.isTimelineRunCurrent(e))return;let t=this.getTimelineAnimationItems(),a=this.clampTimelineIndex(this.timelineAnimation.currentIndex,t),i=a+1;if(i>=t.length){this.timelineAnimation.playing=!1,this.timelineAnimation.paused=!1,this.timelineAnimation.atEnd=!0,this.updateTimelineAnimationButtons();return}if(await this.applyTimelineAnimationTransition(a,i,e,t),!!this.isTimelineRunCurrent(e)){if(this.timelineAnimation.currentIndex=i,i>=t.length-1){this.timelineAnimation.playing=!1,this.timelineAnimation.paused=!1,this.timelineAnimation.atEnd=!0,this.updateTimelineAnimationButtons();return}this.scheduleTimelineAnimation(Et.start,()=>{this.advanceTimelineAnimation(e).catch(s=>this.showMapError(s))})}}async applyTimelineAnimationTransition(e,t,a=this.timelineAnimation.runId,i=this.getTimelineAnimationItems()){let s=Array.isArray(i)&&i.length?i:this.getTimelineAnimationItems(),n=s[this.clampTimelineIndex(e,s)],r=s[this.clampTimelineIndex(t,s)],o=n?.mapId,l=r?.mapId;if(!o||!l){r?.timestamp!==void 0&&await this.applyTimelineTimestamp(r.timestamp,{fit:!1}),this.timelineAnimation.currentIndex=this.clampTimelineIndex(t,s);return}this.beginTimelineApply();try{if(!this.isTimelineMapPlayable(o)||!this.isTimelineMapPlayable(l)){r?.timestamp!==void 0&&await this.applyTimelineTimestamp(r.timestamp,{fit:!1}),this.timelineAnimation.currentIndex=this.clampTimelineIndex(t,s);return}let d=await this.ensureTimelineLayerLoaded(o);if(!this.isTimelineRunCurrent(a))return;let h=await this.ensureTimelineLayerLoaded(l);if(!this.isTimelineRunCurrent(a))return;if(!d||!h){r?.timestamp!==void 0&&await this.applyTimelineTimestamp(r.timestamp,{fit:!1}),this.timelineAnimation.currentIndex=this.clampTimelineIndex(t,s);return}this.mapController.showLayer?.(o),this.mapController.showLayer?.(l);let u=await this.loadTimelineTransitionOverlay(o,l);if(!this.isTimelineRunCurrent(a))return;u?.features?.length?this.mapController.setTimelineTransitionOverlay?.(u,{fromMapId:o,toMapId:l,minAreaM2:Vi}):this.mapController.clearTimelineTransitionOverlay?.(),this.setTimelineRangeIndex(t),this.timelineAnimation.currentIndex=this.clampTimelineIndex(t,s),this.syncCatalogueMapState(),this.updateActiveLayers(),this.updateURLState()}finally{this.endTimelineApply()&&this.updateTimeline()}await this.waitTimelineDelay(Et.overlay),this.isTimelineRunCurrent(a)&&(this.mapController.clearTimelineTransitionOverlay?.({fade:!0}),await this.waitTimelineDelay(Et.settle),this.isTimelineRunCurrent(a)&&(o!==l&&this.isMapLoaded(o)&&await this.unloadMap(o,{preserveTimelineAnimation:!0}),this.syncCatalogueMapState(),this.updateActiveLayers(),this.updateURLState()))}async ensureTimelineLayerLoaded(e){return this.isTimelineMapPlayable(e)?(this.isMapLoaded(e)||await this.loadMap(e,{fit:!1}),this.mapController.showLayer?.(e),!0):!1}getTimelineTransitionCandidateIds(e){let t=P.getMapById(e),a=new Set,i=s=>{if(!s)return;let n=String(s).trim();if(!n)return;let r=[n,n.replace(/-vector-test$/,""),n.replace(/-(standard|full|largescale|50k)$/,"")],o=n.match(/^wards-(1972|1984|1993|2012)(?:-|$)/);o&&r.push("wards-"+o[1]),/^wards-2022(?:-|$)/.test(n)&&r.push("wards-2022-final-recommendations");for(let l of r)l&&a.add(l)};return i(e),i(t?.id),i(t?.sourceMapId),i(t?.cloneOf),i(t?.aliasOf),i(t?.parentId),i(t?.coLoadMapId),[...a]}getTimelineTransitionKeys(e,t){let a=this.getTimelineTransitionCandidateIds(e),i=this.getTimelineTransitionCandidateIds(t),s=[],n=[],r=new Set;for(let o of a)for(let l of i){let d=o+"__"+l;r.has(d)||(r.add(d),this.getTimelineTransitionSidecarSet().has(d)?s.push(d):n.push(d))}return[...s,...n]}async loadTimelineTransitionOverlay(e,t){let a=this.getTimelineTransitionKeys(e,t);for(let i of a){let s=this.timelineTransitionManifestEntries?.get?.(i),n=s?Array.isArray(s.runtimePaths)&&s.runtimePaths.length?s.runtimePaths:[s.runtimePath].filter(Boolean):[];if(n.length){let o=await this.fetchTimelineTransitionGeoJsonParts(n);if(o?.features?.length)return o}let r=n.length?[`${qi}/${i}.geojson`]:[`${Ui}/${i}.geojson`,`${qi}/${i}.geojson`];for(let o of r){let l=await this.fetchTimelineTransitionGeoJson(o);if(l?.features?.length)return l}}return null}async fetchTimelineTransitionGeoJsonParts(e){let t=(Array.isArray(e)?e:[]).map(o=>String(o||"").trim()).filter(Boolean).map(o=>o.startsWith("/")?o:`/${o}`);if(!t.length)return null;let a=`parts:${t.join("|")}`;if(this.timelineTransitionCache.has(a))return this.timelineTransitionCache.get(a);let i=[],s="Territorial transition",n={};for(let o of t){let l=await this.fetchTimelineTransitionGeoJson(o);l&&(l.name&&(s=l.name),n={...n,...l.metadata||{}},Array.isArray(l.features)&&i.push(...l.features))}let r=i.length?{type:"FeatureCollection",name:s,metadata:n,features:i}:null;return this.timelineTransitionCache.set(a,r),r}async fetchTimelineTransitionGeoJson(e){if(this.timelineTransitionCache.has(e))return this.timelineTransitionCache.get(e);try{let t=await fetch(e,{cache:"force-cache"}),a=String(t.headers?.get?.("content-type")||"").toLowerCase();if(!t.ok||a.includes("text/html"))return this.timelineTransitionCache.set(e,null),null;let i=await t.json(),s=this.filterTimelineTransitionGeoJson(i);return this.timelineTransitionCache.set(e,s),s}catch{return this.timelineTransitionCache.set(e,null),null}}filterTimelineTransitionGeoJson(e){let t=(Array.isArray(e?.features)?e.features:[]).filter(a=>{let i=Number(a?.properties?.area_m2??a?.properties?.areaM2??a?.properties?.areaSqm);return!Number.isFinite(i)||i>=Vi});return{type:"FeatureCollection",name:e?.name||"Territorial transition",metadata:e?.metadata||{},features:t}}async unloadMap(e,t={}){if(!t.preserveTimelineAnimation&&this.isTimelineAnimationLayer(e)&&await this.stopTimelineAnimation({restoreOriginal:!1}),this.unloadActiveElectionForLayer(e))return;let a=P.getMapById(e);this.mapController.getLayerState(e)?.isGroup?this.mapController.unloadLayer(e):a?.isGroup&&re(a).length?(re(a).forEach(i=>this.mapController.unloadLayer(i)),this.mapController.unloadLayer(e)):a?.isGroup&&Array.isArray(a.variants)?(a.variants.forEach(i=>this.mapController.unloadLayer(i.id)),this.mapController.unloadLayer(e)):this.mapController.unloadLayer(e)}unloadActiveElectionForLayer(e){if(!e||!this.elections?.activeEntry||!this.isActiveElectionLayerId(e))return!1;let t=this.getActiveElectionBackingLayerIds(e);this.elections.unloadElection({unloadBackingLayer:!1});for(let a of t)(this.mapController.getLayerState(a)||this.mapController.groupStates?.has(a))&&this.mapController.unloadLayer(a);return!0}isActiveElectionLayerId(e){if(!e||!this.elections?.activeEntry)return!1;let t=this.getActiveElectionLayerIds();return[...this.getMapUnloadCandidateIds(e)].some(i=>t.has(i))}getActiveElectionLayerIds(){if(!this.elections?.activeEntry)return new Set;let e=this.elections.activeEntry,t=this.elections.activeBundle;return new Set([this.elections.getCanonicalLayerId?.(e),e?.sourceMapId,t?.sourceMapId,t?.layerId].filter(Boolean))}getMapUnloadCandidateIds(e){let t=P.getMapById(e);return new Set([e,...re(t),...Array.isArray(t?.variants)?t.variants.map(a=>a?.id).filter(Boolean):[]].filter(Boolean))}getActiveElectionBackingLayerIds(e){let t=this.elections?.activeEntry,a=this.elections?.activeBundle,i=new Set([t?.sourceMapId,a?.sourceMapId,a?.layerId].filter(Boolean)),n=[...this.getMapUnloadCandidateIds(e)].filter(r=>i.has(r));return n.length?n:[...i]}setMapControlsOpen(e){let t=document.getElementById("mapControlsToggle"),a=document.getElementById("mapControlPanel");t?.setAttribute("aria-expanded",String(!!e)),a?.classList.toggle("map-control-panel--collapsed",!e),a?.classList.toggle("map-control-panel--expanded",!!e),this.updateURLState()}setActiveLayersPanelOpen(e){let t=document.getElementById("activeLayersToggle"),a=document.getElementById("activeLayers");t?.setAttribute("aria-expanded",String(!!e)),a?.classList.toggle("hidden",!e),this.updateURLState()}async applyBaseMap(e,{userChoice:t=!1}={}){if(this.baseMapId=e||"osm-standard",t){this.userPickedBasemap=!0;try{localStorage.setItem("basemapUserChoice","1")}catch{}}let a=this.mapController?.map;a&&(typeof a.isStyleLoaded=="function"&&!a.isStyleLoaded()&&await new Promise(i=>a.once("load",i)),this.mapController.setBaseMap(this.baseMapId))}async syncBasemapToTheme(){if(this.userPickedBasemap)return null;let e="osm-standard";if(this.baseMapId===e)return null;await this.applyBaseMap(e);let t=document.getElementById("baseMapSelect");return t&&(t.value=e),e}setupSourcePanel(){if(document.getElementById("test2SourcePanel"))return;let e=document.createElement("aside");e.id="test2SourcePanel",e.className="test2-source-panel hidden",e.setAttribute("aria-label","Layer sources"),e.innerHTML=`

    Sources

    @@ -1337,4 +1335,4 @@ void main(){
    `).join("")} - `:`
    ${me(e)} 0

    No ${me(e.toLowerCase())} recorded.

    `}buildLayerShareUrl(e){let t=new URL(location.href),a=this.getCurrentURLParams();return a.set("layers",e),t.hash=a.toString(),t.toString()}getLoadedLayerIds(){let e=new Set,t=new Set;for(let[a,i]of this.mapController.groupStates.entries())if(i.loaded){t.add(a);for(let s of i.childIds||[])e.add(s)}for(let[a,i]of this.mapController.layerStates.entries())i.loaded&&!e.has(a)&&t.add(a);for(let a of P.getAllMaps()){let i=oe(a);a.isGroup&&i.length&&i.every(s=>t.has(s))&&t.add(a.id)}return[...t]}syncCatalogueMapState(){A.syncMapCatalogueState?.({visibleIds:this.mapController.getVisibleLayers(),loadedIds:this.getLoadedLayerIds()})}updateActiveLayers(){let e=[],t=new Map,a=new Map,i=new Set;for(let[r,o]of this.mapController.groupStates){if(!o.loaded)continue;let l=P.getMapById(r)||o.config;l&&e.push(l),t.set(r,o.visible);for(let d of o.childIds||[])i.add(d)}for(let[r,o]of this.mapController.layerStates){if(i.has(r))continue;let l=P.getMapById(r)||o.config;l&&e.push(l),t.set(r,o.visible);let d=this.mapController.getPartialFeatureItems?.(r)||[];d.length>0&&a.set(r,{isPartial:this.mapController.isPartialLayer?.(r)||!1,featureNames:this.mapController.getPartialFeatureNames?.(r)||d.map(h=>h.name),featureItems:d})}let s=this.getActiveLayerOrder(e.map(r=>r.id)),n=new Map(s.map((r,o)=>[r,o]));e.sort((r,o)=>{let l=n.has(r.id)?n.get(r.id):Number.MAX_SAFE_INTEGER,d=n.has(o.id)?n.get(o.id):Number.MAX_SAFE_INTEGER;return l!==d?l-d:String(r.name||r.id).localeCompare(String(o.name||o.id))}),A.updateActiveLayers(e,t,a),this.bindActiveLayerSourceButtons(),this.currentSourceMapId&&this.renderSourcePanel(),this.updateTimeline()}recordSettleOutcome(e,t){return e&&(this.settleOutcomes||(this.settleOutcomes=new Map),t==="settled"||t==="timeout"?this.settleOutcomes.set(e,t):this.settleOutcomes.delete(e)),t}isMapLoaded(e){let t=P.getMapById(e);return t?.isGroup&&oe(t).length?oe(t).some(a=>this.mapController.isLayerLoaded(a)):this.mapController.isLayerLoaded(e)}isMapVisible(e){return this.mapController.isLayerVisible(e)}getPrimaryPartialFeatureURLState(){let e=this.mapController?.layerStates;if(!e?.[Symbol.iterator])return null;for(let[t,a]of e){if(!a?.isPartial||!a.loadedIndices?.size)continue;let i=[...a.loadedIndices][0],s=a.featureNames?.get(i)||a.featureProperties?.get(i)?.name||"";return{mapId:t,featureId:i,featureName:s}}return null}updateURLState(){if(this._suspendURLState||this._restoringURLState)return;let e=this.getLoadedLayerIds(),t=this.elections?.getURLState?.(),a=new Set([this.elections?.activeEntry?.sourceMapId,this.elections?.activeBundle?.sourceMapId,this.elections?.activeBundle?.layerId].filter(Boolean)),i=t?.layerId?[t.layerId,...e.filter(p=>!a.has(p))]:e,s=i.filter(p=>p!==t?.layerId&&!a.has(p)&&!this.isMapVisible(p)),n=this.getActiveLayerOrder(i).filter(p=>i.includes(p)),r=this.getPrimaryPartialFeatureURLState(),o=new URLSearchParams,l=this.mapController.map?.getCenter?.(),d=this.mapController.map?.getZoom?.();i.length&&o.set("layers",i.join(",")),n.length>1&&n.some((p,f)=>p!==i[f])&&o.set("layerOrder",n.join(",")),s.length&&o.set("hidden",s.join(",")),r?.mapId&&r.featureId!==void 0&&r.featureId!==null&&(o.set("featureMap",r.mapId),o.set("featureId",String(r.featureId)),r.featureName&&o.set("featureName",r.featureName)),this.searchQuery&&o.set("q",this.searchQuery),this.currentDetailMapId&&!document.getElementById("catalogueDetailView")?.classList.contains("hidden")&&o.set("detail",this.currentDetailMapId),this.currentSourceMapId&&!document.getElementById("test2SourcePanel")?.classList.contains("hidden")&&o.set("source",this.currentSourceMapId),l&&(o.set("lng",l.lng.toFixed(5)),o.set("lat",l.lat.toFixed(5))),Number.isFinite(d)&&o.set("zoom",d.toFixed(2)),this.baseMapId&&this.baseMapId!=="osm-standard"&&o.set("base",this.baseMapId),document.getElementById("activeLayersToggle")?.getAttribute("aria-expanded")==="true"&&o.set("activePanel","1"),document.getElementById("mapControlsToggle")?.getAttribute("aria-expanded")==="true"&&o.set("controls","1"),t&&(o.set("electionBody",t.body),o.set("electionDate",t.date),o.set("electionMode",t.mode),o.set("electionOverlay",t.overlay),o.set("electionView",t.view),o.set("electionLocalMode",t.localMode),t.geographyMode&&o.set("electionGeographyMode",t.geographyMode),t.selected&&o.set("electionSelected",t.selected),t.countDetail&&o.set("electionCountDetail","1"),t.entityKind&&t.entityKey&&(o.set("electionEntityKind",t.entityKind),o.set("electionEntityKey",t.entityKey),t.entityReturnView&&o.set("electionEntityReturnView",t.entityReturnView)));let h=`${location.pathname}${location.search||""}`,u=o.toString()?`${h}#${o.toString()}`:h;history.replaceState(null,"",u),this.syncDocumentTitle()}syncDocumentTitle(){let e="Civgraph",t=null;try{let i=this.elections?.activeBundle;if(i?.displayTitle)t=i.displayTitle;else if(this.currentDetailMapId)t=this.metadataService?.getLayer?.(this.currentDetailMapId)?.name||this.currentDetailMapId;else{let s=this.getLoadedLayerIds?.()||[];s.length===1?t=this.metadataService?.getLayer?.(s[0])?.name||null:s.length>1?t=`${s.length} layers`:this.searchQuery&&(t=`Search: ${this.searchQuery}`)}}catch{t=null}let a=t?`${String(t).replace(/\s+/g," ").trim()} - ${e}`:`${e} - Maps of Irish administrative geography and history`;document.title!==a&&(document.title=a)}getCurrentURLParams(){return new URLSearchParams(location.hash.replace(/^#/,""))}async restoreURLState(e={}){this._restoringURLState=!0;let t=e.updateAfterRestore!==!1,a=this.getCurrentURLParams(),i=a.get("q");try{this.searchQuery=i||"";let s=document.getElementById("searchInput");s&&(s.value=this.searchQuery),document.getElementById("searchClear")?.classList.toggle("visible",this.searchQuery.length>0),this.updateMapList();let n=a.get("base");if(n){let S=document.getElementById("baseMapSelect");S&&(S.value=n),await this.applyBaseMap(n,{userChoice:!0})}let r=(a.get("layers")||"").split(",").map(S=>Hi(S.trim())).filter(Boolean),o=Hi(a.get("featureMap")||""),l=a.get("featureId")||"",d=a.get("featureName")||"";this.hasElectionURLState(a,r)&&await this.ensureElections({refreshCatalogue:!0});let h=r.filter(S=>!String(S).startsWith("election-")&&!this.elections?.isCanonicalElectionLayerId?.(S)&&(!o||S!==o));if(await Promise.all(h.map(S=>this.loadMap(S).catch(M=>this.showMapError(M)))),await this.elections?.restoreURLState?.(a),o&&l){let S=P.getMapById(o);S&&await this.mapController.loadSingleFeature(S,l,d||l,null,{isolate:!0})}new Set((a.get("hidden")||"").split(",").map(S=>S.trim()).filter(Boolean)).forEach(S=>this.mapController.hideLayer(S)),this.restoreLayerOrder(a),this.syncCatalogueMapState(),this.updateActiveLayers();let p=a.get("detail");p&&P.getMapById(p)?(A.showCatalogueDetailView(p,!1),this.currentDetailMapId=p):!p&&this.currentDetailMapId&&A.showCatalogueListView(!1);let f=a.get("source");f?(this.currentSourceMapId=f,document.getElementById("test2SourcePanel")?.classList.remove("hidden"),await this.renderSourcePanel()):(this.currentSourceMapId=null,document.getElementById("test2SourcePanel")?.classList.add("hidden"));let g=a.has("lng")&&a.has("lat"),y=g?Number(a.get("lng")):NaN,b=g?Number(a.get("lat")):NaN,v=a.get("zoom")??a.get("z"),w=Number(v);Number.isFinite(y)&&Number.isFinite(b)&&this.mapController.map?.jumpTo({center:[y,b],zoom:Number.isFinite(w)?w:void 0}),this.setActiveLayersPanelOpen(a.get("activePanel")==="1"),this.setMapControlsOpen(a.get("controls")==="1")}finally{this._restoringURLState=!1,t&&this.updateURLState()}}triggerDownload(e,t){let a=document.createElement("a");a.href=e,t&&(a.download=t);let i=!1;try{i=new URL(e,window.location.href).origin!==window.location.origin}catch{}i&&(a.target="_blank",a.rel="noopener"),document.body.appendChild(a),a.click(),a.remove()}showMapError(e){console.warn("[Test2]",e);let t=document.getElementById("announcer"),a=e?.message||"Map layer is not available in MapLibre yet.";t&&(t.textContent=a);let i=document.getElementById("test2Status");i||(i=document.createElement("div"),i.id="test2Status",i.className="map-error",document.querySelector(".pane--map")?.appendChild(i)),i.textContent=a}},kn=new ca;kn.init().catch(c=>{console.error("[Test2] Failed to start",c),(document.getElementById("map")||document.body).insertAdjacentHTML("beforeend",`
    Failed to start Civgraph: ${me(c.message)}
    `)});var An=[["roi-local-authorities-","local-authorities-"]];function Hi(c){let e=String(c||"");if(!e)return e;for(let[t,a]of An)if(e.startsWith(t))return`${a}${e.slice(t.length)}`;return e}function me(c){return String(c??"").replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[e])}function $e(c){return String(c||"").split("|")[0].normalize("NFKD").replace(/[\u0300-\u036f]/g,"").toLowerCase().replace(/^(party|candidate|person|name):/,"").replace(/&/g," and ").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function Pe(c){return String(c||"").split("|")[0].normalize("NFKD").replace(/[\u0300-\u036f]/g,"").replace(/\([^)]*\)/g," ").replace(/&/g," and ").replace(/[''`]/g,"").replace(/[-_/.,()]/g," ").replace(/\s+/g," ").trim().toLowerCase()}function Tt(c){let e=String(c||"").split("__")[0];return e?e.startsWith("local-government")?"Local Government Districts":new Map([["dail-eireann","D\xE1il \xC9ireann"],["house-of-commons-of-the-united-kingdom","House of Commons of the United Kingdom"],["northern-ireland-assembly","Northern Ireland Assembly"],["northern-ireland-forum-for-political-dialogue","Northern Ireland Forum for Political Dialogue"],["northern-ireland-constitutional-convention","Northern Ireland Constitutional Convention"],["parliament-of-northern-ireland","Parliament of Northern Ireland"],["european-parliament","European Parliament"],["ireland-european","European Parliament (Ireland)"],["ireland-president","President of Ireland"],["president-of-ireland","President of Ireland"],["ireland-referendum","Referendum (Ireland)"],["ireland-local","Local Government (Ireland)"]]).get(e)||e.replace(/-/g," ").replace(/\b\w/g,a=>a.toUpperCase()):""}function xt(c,e=""){let t=String(c||"").split("__")[0],a=`${t} ${e||""}`;return t.startsWith("local-government")||t==="ireland-local"?"Local":t==="house-of-commons-of-the-united-kingdom"?"Westminster":t==="dail-eireann"?"D\xE1il":t==="northern-ireland-assembly"?"Assembly":t==="northern-ireland-forum-for-political-dialogue"?"Forum":t==="northern-ireland-constitutional-convention"?"Convention":t==="parliament-of-northern-ireland"?"Parliament of NI":t==="european-parliament"||t==="ireland-european"?"European":t==="ireland-president"||t==="president-of-ireland"?"Presidential":/referendum/i.test(a)?"Referendum":t?t.replace(/-/g," "):"Election"}function $n(c){return/Local/i.test(c)?"Local":/Assembly|Forum|Convention|Parliament of NI/i.test(c)?"Devolved":/Westminster/i.test(c)?"Westminster":/European/i.test(c)?"European":""}function oa(c){let e=Number(c||0);if(!Number.isFinite(e)||e<=0)return"0 B";let t=["B","KB","MB","GB"],a=e,i=0;for(;a>=1024&&i${me(e)} 0

    No ${me(e.toLowerCase())} recorded.

    `}buildLayerShareUrl(e){let t=new URL(location.href),a=this.getCurrentURLParams();return a.set("layers",e),t.hash=a.toString(),t.toString()}getLoadedLayerIds(){let e=new Set,t=new Set;for(let[a,i]of this.mapController.groupStates.entries())if(i.loaded){t.add(a);for(let s of i.childIds||[])e.add(s)}for(let[a,i]of this.mapController.layerStates.entries())i.loaded&&!e.has(a)&&t.add(a);for(let a of P.getAllMaps()){let i=re(a);a.isGroup&&i.length&&i.every(s=>t.has(s))&&t.add(a.id)}return[...t]}syncCatalogueMapState(){A.syncMapCatalogueState?.({visibleIds:this.mapController.getVisibleLayers(),loadedIds:this.getLoadedLayerIds()})}updateActiveLayers(){let e=[],t=new Map,a=new Map,i=new Set;for(let[r,o]of this.mapController.groupStates){if(!o.loaded)continue;let l=P.getMapById(r)||o.config;l&&e.push(l),t.set(r,o.visible);for(let d of o.childIds||[])i.add(d)}for(let[r,o]of this.mapController.layerStates){if(i.has(r))continue;let l=P.getMapById(r)||o.config;l&&e.push(l),t.set(r,o.visible);let d=this.mapController.getPartialFeatureItems?.(r)||[];d.length>0&&a.set(r,{isPartial:this.mapController.isPartialLayer?.(r)||!1,featureNames:this.mapController.getPartialFeatureNames?.(r)||d.map(h=>h.name),featureItems:d})}let s=this.getActiveLayerOrder(e.map(r=>r.id)),n=new Map(s.map((r,o)=>[r,o]));e.sort((r,o)=>{let l=n.has(r.id)?n.get(r.id):Number.MAX_SAFE_INTEGER,d=n.has(o.id)?n.get(o.id):Number.MAX_SAFE_INTEGER;return l!==d?l-d:String(r.name||r.id).localeCompare(String(o.name||o.id))}),A.updateActiveLayers(e,t,a),this.bindActiveLayerSourceButtons(),this.currentSourceMapId&&this.renderSourcePanel(),this.updateTimeline()}recordSettleOutcome(e,t){return e&&(this.settleOutcomes||(this.settleOutcomes=new Map),t==="settled"||t==="timeout"?this.settleOutcomes.set(e,t):this.settleOutcomes.delete(e)),t}isMapLoaded(e){let t=P.getMapById(e);return t?.isGroup&&re(t).length?re(t).some(a=>this.mapController.isLayerLoaded(a)):this.mapController.isLayerLoaded(e)}isMapVisible(e){return this.mapController.isLayerVisible(e)}getPrimaryPartialFeatureURLState(){let e=this.mapController?.layerStates;if(!e?.[Symbol.iterator])return null;for(let[t,a]of e){if(!a?.isPartial||!a.loadedIndices?.size)continue;let i=[...a.loadedIndices][0],s=a.featureNames?.get(i)||a.featureProperties?.get(i)?.name||"";return{mapId:t,featureId:i,featureName:s}}return null}updateURLState(){if(this._suspendURLState||this._restoringURLState)return;let e=this.getLoadedLayerIds(),t=this.elections?.getURLState?.(),a=new Set([this.elections?.activeEntry?.sourceMapId,this.elections?.activeBundle?.sourceMapId,this.elections?.activeBundle?.layerId].filter(Boolean)),i=t?.layerId?[t.layerId,...e.filter(p=>!a.has(p))]:e,s=i.filter(p=>p!==t?.layerId&&!a.has(p)&&!this.isMapVisible(p)),n=this.getActiveLayerOrder(i).filter(p=>i.includes(p)),r=this.getPrimaryPartialFeatureURLState(),o=new URLSearchParams,l=this.mapController.map?.getCenter?.(),d=this.mapController.map?.getZoom?.();i.length&&o.set("layers",i.join(",")),n.length>1&&n.some((p,f)=>p!==i[f])&&o.set("layerOrder",n.join(",")),s.length&&o.set("hidden",s.join(",")),r?.mapId&&r.featureId!==void 0&&r.featureId!==null&&(o.set("featureMap",r.mapId),o.set("featureId",String(r.featureId)),r.featureName&&o.set("featureName",r.featureName)),this.searchQuery&&o.set("q",this.searchQuery),this.currentDetailMapId&&!document.getElementById("catalogueDetailView")?.classList.contains("hidden")&&o.set("detail",this.currentDetailMapId),this.currentSourceMapId&&!document.getElementById("test2SourcePanel")?.classList.contains("hidden")&&o.set("source",this.currentSourceMapId),l&&(o.set("lng",l.lng.toFixed(5)),o.set("lat",l.lat.toFixed(5))),Number.isFinite(d)&&o.set("zoom",d.toFixed(2)),this.baseMapId&&this.baseMapId!=="osm-standard"&&o.set("base",this.baseMapId),document.getElementById("activeLayersToggle")?.getAttribute("aria-expanded")==="true"&&o.set("activePanel","1"),document.getElementById("mapControlsToggle")?.getAttribute("aria-expanded")==="true"&&o.set("controls","1"),t&&(o.set("electionBody",t.body),o.set("electionDate",t.date),o.set("electionMode",t.mode),o.set("electionOverlay",t.overlay),o.set("electionView",t.view),o.set("electionLocalMode",t.localMode),t.geographyMode&&o.set("electionGeographyMode",t.geographyMode),t.selected&&o.set("electionSelected",t.selected),t.countDetail&&o.set("electionCountDetail","1"),t.entityKind&&t.entityKey&&(o.set("electionEntityKind",t.entityKind),o.set("electionEntityKey",t.entityKey),t.entityReturnView&&o.set("electionEntityReturnView",t.entityReturnView)));let h=`${location.pathname}${location.search||""}`,u=o.toString()?`${h}#${o.toString()}`:h;history.replaceState(null,"",u),this.syncDocumentTitle()}syncDocumentTitle(){let e="Civgraph",t=null;try{let i=this.elections?.activeBundle;if(i?.displayTitle)t=i.displayTitle;else if(this.currentDetailMapId)t=this.metadataService?.getLayer?.(this.currentDetailMapId)?.name||this.currentDetailMapId;else{let s=this.getLoadedLayerIds?.()||[];s.length===1?t=this.metadataService?.getLayer?.(s[0])?.name||null:s.length>1?t=`${s.length} layers`:this.searchQuery&&(t=`Search: ${this.searchQuery}`)}}catch{t=null}let a=t?`${String(t).replace(/\s+/g," ").trim()} - ${e}`:`${e} - Maps of Irish administrative geography and history`;document.title!==a&&(document.title=a)}getCurrentURLParams(){return new URLSearchParams(location.hash.replace(/^#/,""))}async restoreURLState(e={}){this._restoringURLState=!0;let t=e.updateAfterRestore!==!1,a=this.getCurrentURLParams(),i=a.get("q");try{this.searchQuery=i||"";let s=document.getElementById("searchInput");s&&(s.value=this.searchQuery),document.getElementById("searchClear")?.classList.toggle("visible",this.searchQuery.length>0),this.updateMapList();let n=a.get("base");if(n){let S=document.getElementById("baseMapSelect");S&&(S.value=n),await this.applyBaseMap(n,{userChoice:!0})}let r=(a.get("layers")||"").split(",").map(S=>Gi(S.trim())).filter(Boolean),o=Gi(a.get("featureMap")||""),l=a.get("featureId")||"",d=a.get("featureName")||"";this.hasElectionURLState(a,r)&&await this.ensureElections({refreshCatalogue:!0});let h=r.filter(S=>!String(S).startsWith("election-")&&!this.elections?.isCanonicalElectionLayerId?.(S)&&(!o||S!==o));if(await Promise.all(h.map(S=>this.loadMap(S).catch(E=>this.showMapError(E)))),await this.elections?.restoreURLState?.(a),o&&l){let S=P.getMapById(o);S&&await this.mapController.loadSingleFeature(S,l,d||l,null,{isolate:!0})}new Set((a.get("hidden")||"").split(",").map(S=>S.trim()).filter(Boolean)).forEach(S=>this.mapController.hideLayer(S)),this.restoreLayerOrder(a),this.syncCatalogueMapState(),this.updateActiveLayers();let p=a.get("detail");p&&P.getMapById(p)?(A.showCatalogueDetailView(p,!1),this.currentDetailMapId=p):!p&&this.currentDetailMapId&&A.showCatalogueListView(!1);let f=a.get("source");f?(this.currentSourceMapId=f,document.getElementById("test2SourcePanel")?.classList.remove("hidden"),await this.renderSourcePanel()):(this.currentSourceMapId=null,document.getElementById("test2SourcePanel")?.classList.add("hidden"));let g=a.has("lng")&&a.has("lat"),y=g?Number(a.get("lng")):NaN,b=g?Number(a.get("lat")):NaN,v=a.get("zoom")??a.get("z"),w=Number(v);Number.isFinite(y)&&Number.isFinite(b)&&this.mapController.map?.jumpTo({center:[y,b],zoom:Number.isFinite(w)?w:void 0}),this.setActiveLayersPanelOpen(a.get("activePanel")==="1"),this.setMapControlsOpen(a.get("controls")==="1")}finally{this._restoringURLState=!1,t&&this.updateURLState()}}triggerDownload(e,t){let a=document.createElement("a");a.href=e,t&&(a.download=t);let i=!1;try{i=new URL(e,window.location.href).origin!==window.location.origin}catch{}i&&(a.target="_blank",a.rel="noopener"),document.body.appendChild(a),a.click(),a.remove()}showMapError(e){console.warn("[Test2]",e);let t=document.getElementById("announcer"),a=e?.message||"Map layer is not available in MapLibre yet.";t&&(t.textContent=a);let i=document.getElementById("test2Status");i||(i=document.createElement("div"),i.id="test2Status",i.className="map-error",document.querySelector(".pane--map")?.appendChild(i)),i.textContent=a}},Rn=new ma;Rn.init().catch(c=>{console.error("[Test2] Failed to start",c),(document.getElementById("map")||document.body).insertAdjacentHTML("beforeend",`
    Failed to start Civgraph: ${me(c.message)}
    `)});var Nn=[["roi-local-authorities-","local-authorities-"]];function Gi(c){let e=String(c||"");if(!e)return e;for(let[t,a]of Nn)if(e.startsWith(t))return`${a}${e.slice(t.length)}`;return e}function me(c){return String(c??"").replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[e])}function Re(c){return String(c||"").split("|")[0].normalize("NFKD").replace(/[\u0300-\u036f]/g,"").toLowerCase().replace(/^(party|candidate|person|name):/,"").replace(/&/g," and ").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function Ne(c){return String(c||"").split("|")[0].normalize("NFKD").replace(/[\u0300-\u036f]/g,"").replace(/\([^)]*\)/g," ").replace(/&/g," and ").replace(/[''`]/g,"").replace(/[-_/.,()]/g," ").replace(/\s+/g," ").trim().toLowerCase()}function kt(c){let e=String(c||"").split("__")[0];return e?e.startsWith("local-government")?"Local Government Districts":new Map([["dail-eireann","D\xE1il \xC9ireann"],["house-of-commons-of-the-united-kingdom","House of Commons of the United Kingdom"],["northern-ireland-assembly","Northern Ireland Assembly"],["northern-ireland-forum-for-political-dialogue","Northern Ireland Forum for Political Dialogue"],["northern-ireland-constitutional-convention","Northern Ireland Constitutional Convention"],["parliament-of-northern-ireland","Parliament of Northern Ireland"],["european-parliament","European Parliament"],["ireland-european","European Parliament (Ireland)"],["ireland-president","President of Ireland"],["president-of-ireland","President of Ireland"],["ireland-referendum","Referendum (Ireland)"],["ireland-local","Local Government (Ireland)"]]).get(e)||e.replace(/-/g," ").replace(/\b\w/g,a=>a.toUpperCase()):""}function At(c,e=""){let t=String(c||"").split("__")[0],a=`${t} ${e||""}`;return t.startsWith("local-government")||t==="ireland-local"?"Local":t==="house-of-commons-of-the-united-kingdom"?"Westminster":t==="dail-eireann"?"D\xE1il":t==="northern-ireland-assembly"?"Assembly":t==="northern-ireland-forum-for-political-dialogue"?"Forum":t==="northern-ireland-constitutional-convention"?"Convention":t==="parliament-of-northern-ireland"?"Parliament of NI":t==="european-parliament"||t==="ireland-european"?"European":t==="ireland-president"||t==="president-of-ireland"?"Presidential":/referendum/i.test(a)?"Referendum":t?t.replace(/-/g," "):"Election"}function Hn(c){return/Local/i.test(c)?"Local":/Assembly|Forum|Convention|Parliament of NI/i.test(c)?"Devolved":/Westminster/i.test(c)?"Westminster":/European/i.test(c)?"European":""}function ha(c){let e=Number(c||0);if(!Number.isFinite(e)||e<=0)return"0 B";let t=["B","KB","MB","GB"],a=e,i=0;for(;a>=1024&&ie in a?i(a,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):a[e]=s;var b=(a,e)=>()=>(a&&(e=a(a=0)),e);var k=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var l=(a,e,s,p)=>{if(e&&typeof e=="object"||typeof e=="function")for(let c of o(e))!r.call(a,c)&&c!==s&&i(a,c,{get:()=>e[c],enumerable:!(p=j(e,c))||p.enumerable});return a};var f=(a,e,s)=>(s=a!=null?n(t(a)):{},l(e||!a||!a.__esModule?i(s,"default",{value:a,enumerable:!0}):s,a));var m=(a,e,s)=>g(a,typeof e!="symbol"?e+"":e,s);var d,w=b(()=>{d={"/app/js/jquery-shim.js":"6bed0b11e32c","/app/js/libs/flatgeobuf-geojson.min.js":"e650c7105ca9","/app/election-viewer-package/js/stages2.js":"0593a3f68913","/app/election-viewer-package/js/animation_preview.js":"913bc83b354c","/app/election-viewer-package/js/animation_preview_manager.js":"e0fab59ea446","/app/election-viewer-package/js/election_viewer.js":"945b6492aac7","/app/election-viewer-package/css/stages.css":"6eee8aa01182","/app/election-viewer-package/css/election-viewer.css":"a999f742cbb1"}});export{k as a,f as b,m as c,w as d,d as e}; diff --git a/app/build/chunks/chunk-57HMLXXU.js b/app/build/chunks/chunk-57HMLXXU.js new file mode 100644 index 0000000000..793023b35d --- /dev/null +++ b/app/build/chunks/chunk-57HMLXXU.js @@ -0,0 +1 @@ +var n=Object.create;var c=Object.defineProperty;var j=Object.getOwnPropertyDescriptor;var o=Object.getOwnPropertyNames;var t=Object.getPrototypeOf,r=Object.prototype.hasOwnProperty;var g=(a,e,s)=>e in a?c(a,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):a[e]=s;var b=(a,e)=>()=>(a&&(e=a(a=0)),e);var f=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var l=(a,e,s,p)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of o(e))!r.call(a,i)&&i!==s&&c(a,i,{get:()=>e[i],enumerable:!(p=j(e,i))||p.enumerable});return a};var k=(a,e,s)=>(s=a!=null?n(t(a)):{},l(e||!a||!a.__esModule?c(s,"default",{value:a,enumerable:!0}):s,a));var m=(a,e,s)=>g(a,typeof e!="symbol"?e+"":e,s);var u,w=b(()=>{u={"/app/js/jquery-shim.js":"3bbf45385a68","/app/js/libs/flatgeobuf-geojson.min.js":"e650c7105ca9","/app/election-viewer-package/js/stages2.js":"b81c007128e2","/app/election-viewer-package/js/animation_preview.js":"913bc83b354c","/app/election-viewer-package/js/animation_preview_manager.js":"e0fab59ea446","/app/election-viewer-package/js/election_viewer.js":"747648b4d88c","/app/election-viewer-package/css/stages.css":"6eee8aa01182","/app/election-viewer-package/css/election-viewer.css":"1ff92e8efbd7"}});export{f as a,k as b,m as c,w as d,u as e}; diff --git a/app/build/chunks/chunk-V4IEUOVV.js b/app/build/chunks/chunk-MJD6VXSO.js similarity index 98% rename from app/build/chunks/chunk-V4IEUOVV.js rename to app/build/chunks/chunk-MJD6VXSO.js index e36954c313..62c259ced4 100644 --- a/app/build/chunks/chunk-V4IEUOVV.js +++ b/app/build/chunks/chunk-MJD6VXSO.js @@ -1,5 +1,5 @@ -import{a as U_,d as Da}from"./chunk-2YPEAJVR.js";var q_=U_((yd,vd)=>{Da();(function(Le,Qe){typeof yd=="object"&&typeof vd<"u"?vd.exports=Qe():typeof define=="function"&&define.amd?define(Qe):(Le=typeof globalThis<"u"?globalThis:Le||self,Le.maplibregl=Qe())})(yd,(function(){"use strict";var Le={},Qe={};function Zt(k,p,Te){if(Qe[k]=Te,k==="index"){var Sr="var sharedModule = {}; ("+Qe.shared+")(sharedModule); ("+Qe.worker+")(sharedModule);",Si={};return Qe.shared(Si),Qe.index(Le,Si),typeof window<"u"&&Le.setWorkerUrl(window.URL.createObjectURL(new Blob([Sr],{type:"text/javascript"}))),Le}}Zt("shared",["exports"],(function(k){"use strict";function p(r,e,i,o){return new(i||(i=Promise))((function(s,l){function h(m){try{g(o.next(m))}catch(v){l(v)}}function d(m){try{g(o.throw(m))}catch(v){l(v)}}function g(m){var v;m.done?s(m.value):(v=m.value,v instanceof i?v:new i((function(_){_(v)}))).then(h,d)}g((o=o.apply(r,e||[])).next())}))}function Te(r,e){this.x=r,this.y=e}function Sr(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var Si,Wr;typeof SuppressedError=="function"&&SuppressedError,Te.prototype={clone(){return new Te(this.x,this.y)},add(r){return this.clone()._add(r)},sub(r){return this.clone()._sub(r)},multByPoint(r){return this.clone()._multByPoint(r)},divByPoint(r){return this.clone()._divByPoint(r)},mult(r){return this.clone()._mult(r)},div(r){return this.clone()._div(r)},rotate(r){return this.clone()._rotate(r)},rotateAround(r,e){return this.clone()._rotateAround(r,e)},matMult(r){return this.clone()._matMult(r)},unit(){return this.clone()._unit()},perp(){return this.clone()._perp()},round(){return this.clone()._round()},mag(){return Math.sqrt(this.x*this.x+this.y*this.y)},equals(r){return this.x===r.x&&this.y===r.y},dist(r){return Math.sqrt(this.distSqr(r))},distSqr(r){let e=r.x-this.x,i=r.y-this.y;return e*e+i*i},angle(){return Math.atan2(this.y,this.x)},angleTo(r){return Math.atan2(this.y-r.y,this.x-r.x)},angleWith(r){return this.angleWithSep(r.x,r.y)},angleWithSep(r,e){return Math.atan2(this.x*e-this.y*r,this.x*r+this.y*e)},_matMult(r){let e=r[2]*this.x+r[3]*this.y;return this.x=r[0]*this.x+r[1]*this.y,this.y=e,this},_add(r){return this.x+=r.x,this.y+=r.y,this},_sub(r){return this.x-=r.x,this.y-=r.y,this},_mult(r){return this.x*=r,this.y*=r,this},_div(r){return this.x/=r,this.y/=r,this},_multByPoint(r){return this.x*=r.x,this.y*=r.y,this},_divByPoint(r){return this.x/=r.x,this.y/=r.y,this},_unit(){return this._div(this.mag()),this},_perp(){let r=this.y;return this.y=this.x,this.x=-r,this},_rotate(r){let e=Math.cos(r),i=Math.sin(r),o=i*this.x+e*this.y;return this.x=e*this.x-i*this.y,this.y=o,this},_rotateAround(r,e){let i=Math.cos(r),o=Math.sin(r),s=e.y+o*(this.x-e.x)+i*(this.y-e.y);return this.x=e.x+i*(this.x-e.x)-o*(this.y-e.y),this.y=s,this},_round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this},constructor:Te},Te.convert=function(r){if(r instanceof Te)return r;if(Array.isArray(r))return new Te(+r[0],+r[1]);if(r.x!==void 0&&r.y!==void 0)return new Te(+r.x,+r.y);throw new Error("Expected [x, y] or {x, y} point format")};var An=(function(){if(Wr)return Si;function r(e,i,o,s){this.cx=3*e,this.bx=3*(o-e)-this.cx,this.ax=1-this.cx-this.bx,this.cy=3*i,this.by=3*(s-i)-this.cy,this.ay=1-this.cy-this.by,this.p1x=e,this.p1y=i,this.p2x=o,this.p2y=s}return Wr=1,Si=r,r.prototype={sampleCurveX:function(e){return((this.ax*e+this.bx)*e+this.cx)*e},sampleCurveY:function(e){return((this.ay*e+this.by)*e+this.cy)*e},sampleCurveDerivativeX:function(e){return(3*this.ax*e+2*this.bx)*e+this.cx},solveCurveX:function(e,i){if(i===void 0&&(i=1e-6),e<0)return 0;if(e>1)return 1;for(var o=e,s=0;s<8;s++){var l=this.sampleCurveX(o)-e;if(Math.abs(l)l?d=o:g=o,o=.5*(g-d)+d;return o},solve:function(e,i){return this.sampleCurveY(this.solveCurveX(e,i))}},Si})(),qt=Sr(An);let Ir,Xe;function Hr(){return Ir!=null||(Ir=typeof OffscreenCanvas<"u"&&new OffscreenCanvas(1,1).getContext("2d")&&typeof createImageBitmap=="function"),Ir}function Ii(){if(Xe==null&&(Xe=!1,Hr())){let e=new OffscreenCanvas(5,5).getContext("2d",{willReadFrequently:!0});if(e){for(let o=0;o<25;o++){let s=4*o;e.fillStyle=`rgb(${s},${s+1},${s+2})`,e.fillRect(o%5,Math.floor(o/5),1,1)}let i=e.getImageData(0,0,5,5).data;for(let o=0;o<100;o++)if(o%4!=3&&i[o]!==o){Xe=!0;break}}}return Xe||!1}var pe=1e-6,kt=typeof Float32Array<"u"?Float32Array:Array;function Xr(){var r=new kt(9);return kt!=Float32Array&&(r[1]=0,r[2]=0,r[3]=0,r[5]=0,r[6]=0,r[7]=0),r[0]=1,r[4]=1,r[8]=1,r}function Dn(r){return r[0]=1,r[1]=0,r[2]=0,r[3]=0,r[4]=0,r[5]=1,r[6]=0,r[7]=0,r[8]=0,r[9]=0,r[10]=1,r[11]=0,r[12]=0,r[13]=0,r[14]=0,r[15]=1,r}function go(){var r=new kt(3);return kt!=Float32Array&&(r[0]=0,r[1]=0,r[2]=0),r}function _o(r){var e=r[0],i=r[1],o=r[2];return Math.sqrt(e*e+i*i+o*o)}function We(r,e,i){var o=new kt(3);return o[0]=r,o[1]=e,o[2]=i,o}function W(r,e,i){return r[0]=e[0]+i[0],r[1]=e[1]+i[1],r[2]=e[2]+i[2],r}function K(r,e,i){return r[0]=e[0]*i,r[1]=e[1]*i,r[2]=e[2]*i,r}function ee(r,e,i){var o=e[0],s=e[1],l=e[2],h=i[0],d=i[1],g=i[2];return r[0]=s*g-l*d,r[1]=l*h-o*g,r[2]=o*d-s*h,r}var ge,Me=_o;function Ze(r,e,i){var o=e[0],s=e[1],l=e[2],h=e[3];return r[0]=i[0]*o+i[4]*s+i[8]*l+i[12]*h,r[1]=i[1]*o+i[5]*s+i[9]*l+i[13]*h,r[2]=i[2]*o+i[6]*s+i[10]*l+i[14]*h,r[3]=i[3]*o+i[7]*s+i[11]*l+i[15]*h,r}function ze(){var r=new kt(4);return kt!=Float32Array&&(r[0]=0,r[1]=0,r[2]=0),r[3]=1,r}function $e(r,e,i,o){var s=arguments.length>4&&arguments[4]!==void 0?arguments[4]:"zyx",l=Math.PI/360;e*=l,o*=l,i*=l;var h=Math.sin(e),d=Math.cos(e),g=Math.sin(i),m=Math.cos(i),v=Math.sin(o),_=Math.cos(o);switch(s){case"xyz":r[0]=h*m*_+d*g*v,r[1]=d*g*_-h*m*v,r[2]=d*m*v+h*g*_,r[3]=d*m*_-h*g*v;break;case"xzy":r[0]=h*m*_-d*g*v,r[1]=d*g*_-h*m*v,r[2]=d*m*v+h*g*_,r[3]=d*m*_+h*g*v;break;case"yxz":r[0]=h*m*_+d*g*v,r[1]=d*g*_-h*m*v,r[2]=d*m*v-h*g*_,r[3]=d*m*_+h*g*v;break;case"yzx":r[0]=h*m*_+d*g*v,r[1]=d*g*_+h*m*v,r[2]=d*m*v-h*g*_,r[3]=d*m*_-h*g*v;break;case"zxy":r[0]=h*m*_-d*g*v,r[1]=d*g*_+h*m*v,r[2]=d*m*v+h*g*_,r[3]=d*m*_-h*g*v;break;case"zyx":r[0]=h*m*_-d*g*v,r[1]=d*g*_+h*m*v,r[2]=d*m*v-h*g*_,r[3]=d*m*_+h*g*v;break;default:throw new Error("Unknown angle order "+s)}return r}function Be(){var r=new kt(2);return kt!=Float32Array&&(r[0]=0,r[1]=0),r}function Ke(r,e){var i=new kt(2);return i[0]=r,i[1]=e,i}go(),ge=new kt(4),kt!=Float32Array&&(ge[0]=0,ge[1]=0,ge[2]=0,ge[3]=0),go(),We(1,0,0),We(0,1,0),ze(),ze(),Xr(),Be();let De=8192;function vt(r,e,i){return e*(De/(r.tileSize*Math.pow(2,i-r.tileID.overscaledZ)))}function xt(r){return r instanceof Error?r:new Error(typeof r=="string"?r:String(r))}function Wi(r,e){return(r%e+e)%e}function Bi(r,e,i){return r*(1-i)+e*i}function Mr(r){if(r<=0)return 0;if(r>=1)return 1;let e=r*r,i=e*r;return 4*(r<.5?i:3*(r-e)+i-.75)}function Yr(r,e,i,o){let s=new qt(r,e,i,o);return l=>s.solve(l)}let yo=Yr(.25,.1,.25,1);function li(r,e,i){return Math.min(i,Math.max(e,r))}function zn(r,e,i){let o=i-e,s=((r-e)%o+o)%o+e;return s===e?i:s}function Oi(r,...e){for(let i of e)for(let o in i)r[o]=i[o];return r}let vo=1;function Er(r,e,i){let o={};for(let s in r)o[s]=e.call(this,r[s],s,r);return o}function Kr(r,e,i){let o={};for(let s in r)e.call(this,r[s],s,r)&&(o[s]=r[s]);return o}function Re(r){return Array.isArray(r)?r.map(Re):typeof r=="object"&&r?Er(r,Re):r}let Bt={};function Wt(r){Bt[r]||(typeof console<"u"&&console.warn(r),Bt[r]=!0)}function Mi(r,e,i){return(i.y-r.y)*(e.x-r.x)>(e.y-r.y)*(i.x-r.x)}function Ht(r){return typeof WorkerGlobalScope<"u"&&r!==void 0&&r instanceof WorkerGlobalScope}let yi=null;function Jr(r){return typeof ImageBitmap<"u"&&r instanceof ImageBitmap}let za="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVQYV2NgAAIAAAUAAarVyFEAAAAASUVORK5CYII=";function Ra(r,e,i,o,s){return p(this,void 0,void 0,(function*(){if(typeof VideoFrame>"u")throw new Error("VideoFrame not supported");let l=new VideoFrame(r,{timestamp:0});try{let h=l?.format;if(!h||!h.startsWith("BGR")&&!h.startsWith("RGB"))throw new Error(`Unrecognized format ${h}`);let d=h.startsWith("BGR"),g=new Uint8ClampedArray(o*s*4);if(yield l.copyTo(g,(function(m,v,_,T,b){let I=4*Math.max(-v,0),M=(Math.max(0,_)-_)*T*4+I,A=4*T,D=Math.max(0,v),L=Math.max(0,_);return{rect:{x:D,y:L,width:Math.min(m.width,v+T)-D,height:Math.min(m.height,_+b)-L},layout:[{offset:M,stride:A}]}})(r,e,i,o,s)),d)for(let m=0;m{r.removeEventListener(e,i,o)}}}function Ar(r){return r*Math.PI/180}function Qr(r){return r/Math.PI*180}let ka={touchstart:!0,touchmove:!0,touchmoveWindow:!0,touchend:!0,touchcancel:!0},La={dblclick:!0,click:!0,mouseover:!0,mouseout:!0,mousedown:!0,mousemove:!0,mousemoveWindow:!0,mouseup:!0,mouseupWindow:!0,contextmenu:!0,wheel:!0},ds="AbortError";class xo extends Error{constructor(e=ds){super(e instanceof Error?e.message:e),this.name=ds,e instanceof Error&&e.stack&&(this.stack=e.stack)}}function rc(r){return r instanceof Error&&r.name===ds}function ps(r){if(r.aborted)throw new xo(r.reason)}let Dr={MAX_PARALLEL_IMAGE_REQUESTS:16,MAX_PARALLEL_IMAGE_REQUESTS_PER_FRAME:8,MAX_TILE_CACHE_ZOOM_LEVELS:5,REGISTERED_PROTOCOLS:{},WORKER_URL:""};function hr(r){return Dr.REGISTERED_PROTOCOLS[r.substring(0,r.indexOf("://"))]}let Ni="global-dispatcher";class kn extends Error{constructor(e,i,o,s){super(`AJAXError: ${i} (${e}): ${o}`),this.status=e,this.statusText=i,this.url=o,this.body=s}}let Fa=()=>{var r;return Ht(self)?(r=self.worker)===null||r===void 0?void 0:r.referrer:(window.location.protocol==="blob:"?window.parent:window).location.href},en=function(r,e){return p(this,void 0,void 0,(function*(){var i,o;if(r.url.includes("://")&&!/^https?:|^file:/.test(r.url)){let s=hr(r.url);if(s){let l=yield s(r,e);return l.data||r.type!=="arrayBuffer"?l:Oi(l,{data:new ArrayBuffer(0)})}if(Ht(self)&&(!((i=self.worker)===null||i===void 0)&&i.actor))return self.worker.actor.sendAsync({type:"GR",data:r,targetMapId:Ni},e)}if(!(s=>{var l;return s.startsWith("file:")||((l=Fa())===null||l===void 0?void 0:l.startsWith("file:"))&&!/^\w+:/.test(s)})(r.url)){if(fetch&&Request&&AbortController&&Object.hasOwn(Request.prototype,"signal"))return(function(s,l){return p(this,void 0,void 0,(function*(){let h=new Request(s.url,{method:s.method||"GET",body:s.body,credentials:s.credentials,headers:s.headers,cache:s.cache,referrer:Fa(),referrerPolicy:s.referrerPolicy,signal:l.signal}),d,g;s.type!=="json"||h.headers.has("Accept")||h.headers.set("Accept","application/json");try{d=yield fetch(h)}catch(v){throw rc(v)?v:new kn(0,xt(v).message,s.url,new Blob)}if(!d.ok){let v=yield d.blob();throw new kn(d.status,d.statusText,s.url,v)}g=s.type==="arrayBuffer"||s.type==="image"?d.arrayBuffer():s.type==="json"?d.json():d.text();let m=yield g;return ps(l.signal),{data:m,cacheControl:d.headers.get("Cache-Control"),expires:d.headers.get("Expires"),etag:d.headers.get("ETag")}}))})(r,e);if(Ht(self)&&(!((o=self.worker)===null||o===void 0)&&o.actor))return self.worker.actor.sendAsync({type:"GR",data:r,mustQueue:!0,targetMapId:Ni},e)}return(function(s,l){return new Promise(((h,d)=>{var g;let m=new XMLHttpRequest;m.open(s.method||"GET",s.url,!0),s.type!=="arrayBuffer"&&s.type!=="image"||(m.responseType="arraybuffer");for(let v in s.headers)m.setRequestHeader(v,s.headers[v]);s.type==="json"&&(m.responseType="text",!((g=s.headers)===null||g===void 0)&&g.Accept||m.setRequestHeader("Accept","application/json")),m.withCredentials=s.credentials==="include",m.onerror=()=>{d(new Error(m.statusText))},m.onload=()=>{if(!l.signal.aborted)if((m.status>=200&&m.status<300||m.status===0)&&m.response!==null){let v=m.response;if(s.type==="json")try{v=JSON.parse(m.response)}catch(_){return void d(_)}h({data:v,cacheControl:m.getResponseHeader("Cache-Control"),expires:m.getResponseHeader("Expires"),etag:m.getResponseHeader("ETag")})}else{let v=new Blob([m.response],{type:m.getResponseHeader("Content-Type")});d(new kn(m.status,m.statusText,s.url,v))}},l.signal.addEventListener("abort",(()=>{m.abort(),d(new xo(l.signal.reason))})),m.send(s.body)}))})(r,e)}))};function Hi(r){if(!r||r.indexOf("://")<=0||r.startsWith("data:image/")||r.startsWith("blob:"))return!0;let e=new URL(r),i=window.location;return e.protocol===i.protocol&&e.host===i.host}function Ln(r,e,i){var o;!((o=i[r])===null||o===void 0)&&o.includes(e)||(i[r]||(i[r]=[]),i[r].push(e))}function tn(r,e,i){if(i?.[r]){let o=i[r].indexOf(e);o!==-1&&i[r].splice(o,1)}}class bo{constructor(e,i={}){Oi(this,i),this.type=e}}class Fn extends bo{constructor(e,i={}){super("error",Oi({error:e},i))}}class fs{on(e,i){return this._listeners||(this._listeners={}),Ln(e,i,this._listeners),{unsubscribe:()=>{this.off(e,i)}}}off(e,i){return tn(e,i,this._listeners),tn(e,i,this._oneTimeListeners),this}once(e,i){return i?(this._oneTimeListeners||(this._oneTimeListeners={}),Ln(e,i,this._oneTimeListeners),this):new Promise((o=>this.once(e,o)))}fire(e,i){var o,s;typeof e=="string"&&(e=new bo(e,i||{}));let l=e.type;if(this.listens(l)){e.target=this;let h=!((o=this._listeners)===null||o===void 0)&&o[l]?this._listeners[l].slice():[];for(let m of h)m.call(this,e);let d=!((s=this._oneTimeListeners)===null||s===void 0)&&s[l]?this._oneTimeListeners[l].slice():[];for(let m of d)tn(l,m,this._oneTimeListeners),m.call(this,e);let g=this._eventedParent;g&&(Oi(e,typeof this._eventedParentData=="function"?this._eventedParentData():this._eventedParentData),g.fire(e))}else e instanceof Fn&&console.error(e.error);return this}listens(e){var i,o,s,l,h;return((o=(i=this._listeners)===null||i===void 0?void 0:i[e])===null||o===void 0?void 0:o.length)>0||((l=(s=this._oneTimeListeners)===null||s===void 0?void 0:s[e])===null||l===void 0?void 0:l.length)>0||((h=this._eventedParent)===null||h===void 0?void 0:h.listens(e))}setEventedParent(e,i){return this._eventedParent=e,this._eventedParentData=i,this}}var ce={$version:8,$root:{version:{required:!0,type:"enum",values:[8]},name:{type:"string"},metadata:{type:"*"},center:{type:"array",value:"number",length:2},centerAltitude:{type:"number"},zoom:{type:"number"},bearing:{type:"number",default:0,period:360,units:"degrees"},pitch:{type:"number",default:0,units:"degrees"},roll:{type:"number",default:0,units:"degrees"},state:{type:"state",default:{}},light:{type:"light"},sky:{type:"sky"},projection:{type:"projection"},terrain:{type:"terrain"},sources:{required:!0,type:"sources"},sprite:{type:"sprite"},glyphs:{type:"string"},"font-faces":{type:"fontFaces"},transition:{type:"transition"},layers:{required:!0,type:"array",value:"layer"}},sources:{"*":{type:"source"}},source:["source_vector","source_raster","source_raster_dem","source_geojson","source_video","source_image"],source_vector:{type:{required:!0,type:"enum",values:{vector:{}}},url:{type:"string"},tiles:{type:"array",value:"string"},bounds:{type:"array",value:"number",length:4,default:[-180,-85.051129,180,85.051129]},scheme:{type:"enum",values:{xyz:{},tms:{}},default:"xyz"},minzoom:{type:"number",default:0},maxzoom:{type:"number",default:22},attribution:{type:"string"},promoteId:{type:"promoteId"},volatile:{type:"boolean",default:!1},encoding:{type:"enum",values:{mvt:{},mlt:{}},default:"mvt"},"*":{type:"*"}},source_raster:{type:{required:!0,type:"enum",values:{raster:{}}},url:{type:"string"},tiles:{type:"array",value:"string"},bounds:{type:"array",value:"number",length:4,default:[-180,-85.051129,180,85.051129]},minzoom:{type:"number",default:0},maxzoom:{type:"number",default:22},tileSize:{type:"number",default:512,units:"pixels"},scheme:{type:"enum",values:{xyz:{},tms:{}},default:"xyz"},attribution:{type:"string"},volatile:{type:"boolean",default:!1},"*":{type:"*"}},source_raster_dem:{type:{required:!0,type:"enum",values:{"raster-dem":{}}},url:{type:"string"},tiles:{type:"array",value:"string"},bounds:{type:"array",value:"number",length:4,default:[-180,-85.051129,180,85.051129]},minzoom:{type:"number",default:0},maxzoom:{type:"number",default:22},tileSize:{type:"number",default:512,units:"pixels"},attribution:{type:"string"},encoding:{type:"enum",values:{terrarium:{},mapbox:{},custom:{}},default:"mapbox"},redFactor:{type:"number",default:1},blueFactor:{type:"number",default:1},greenFactor:{type:"number",default:1},baseShift:{type:"number",default:0},volatile:{type:"boolean",default:!1},"*":{type:"*"}},source_geojson:{type:{required:!0,type:"enum",values:{geojson:{}}},data:{required:!0,type:"*"},maxzoom:{type:"number",default:18},attribution:{type:"string"},buffer:{type:"number",default:128,maximum:512,minimum:0},filter:{type:"filter"},tolerance:{type:"number",default:.375},cluster:{type:"boolean",default:!1},clusterRadius:{type:"number",default:50,minimum:0},clusterMaxZoom:{type:"number"},clusterMinPoints:{type:"number"},clusterProperties:{type:"*"},lineMetrics:{type:"boolean",default:!1},generateId:{type:"boolean",default:!1},promoteId:{type:"promoteId"}},source_video:{type:{required:!0,type:"enum",values:{video:{}}},urls:{required:!0,type:"array",value:"string"},coordinates:{required:!0,type:"array",length:4,value:{type:"array",length:2,value:"number"}}},source_image:{type:{required:!0,type:"enum",values:{image:{}}},url:{required:!0,type:"string"},coordinates:{required:!0,type:"array",length:4,value:{type:"array",length:2,value:"number"}}},layer:{id:{type:"string",required:!0},type:{type:"enum",values:{fill:{},line:{},symbol:{},circle:{},heatmap:{},"fill-extrusion":{},raster:{},hillshade:{},"color-relief":{},background:{}},required:!0},metadata:{type:"*"},source:{type:"string"},"source-layer":{type:"string"},minzoom:{type:"number",minimum:0,maximum:24},maxzoom:{type:"number",minimum:0,maximum:24},filter:{type:"filter"},layout:{type:"layout"},paint:{type:"paint"}},layout:["layout_fill","layout_line","layout_circle","layout_heatmap","layout_fill-extrusion","layout_symbol","layout_raster","layout_hillshade","layout_color-relief","layout_background"],layout_background:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible",expression:{interpolated:!1,parameters:["global-state"]},"property-type":"data-constant"}},layout_fill:{"fill-sort-key":{type:"number",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible",expression:{interpolated:!1,parameters:["global-state"]},"property-type":"data-constant"}},layout_circle:{"circle-sort-key":{type:"number",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible",expression:{interpolated:!1,parameters:["global-state"]},"property-type":"data-constant"}},layout_heatmap:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible",expression:{interpolated:!1,parameters:["global-state"]},"property-type":"data-constant"}},"layout_fill-extrusion":{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible",expression:{interpolated:!1,parameters:["global-state"]},"property-type":"data-constant"}},layout_line:{"line-cap":{type:"enum",values:{butt:{},round:{},square:{}},default:"butt",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"line-join":{type:"enum",values:{bevel:{},round:{},miter:{}},default:"miter",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"line-miter-limit":{type:"number",default:2,requires:[{"line-join":"miter"}],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"line-round-limit":{type:"number",default:1.05,requires:[{"line-join":"round"}],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"line-sort-key":{type:"number",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible",expression:{interpolated:!1,parameters:["global-state"]},"property-type":"data-constant"}},layout_symbol:{"symbol-placement":{type:"enum",values:{point:{},line:{},"line-center":{}},default:"point",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"symbol-spacing":{type:"number",default:250,minimum:1,units:"pixels",requires:[{"symbol-placement":"line"}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"symbol-avoid-edges":{type:"boolean",default:!1,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"symbol-sort-key":{type:"number",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"symbol-z-order":{type:"enum",values:{auto:{},"viewport-y":{},source:{}},default:"auto",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-allow-overlap":{type:"boolean",default:!1,requires:["icon-image",{"!":"icon-overlap"}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-overlap":{type:"enum",values:{never:{},always:{},cooperative:{}},requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-ignore-placement":{type:"boolean",default:!1,requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-optional":{type:"boolean",default:!1,requires:["icon-image","text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-rotation-alignment":{type:"enum",values:{map:{},viewport:{},auto:{}},default:"auto",requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-size":{type:"number",default:1,minimum:0,units:"factor of the original icon size",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-text-fit":{type:"enum",values:{none:{},width:{},height:{},both:{}},default:"none",requires:["icon-image","text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-text-fit-padding":{type:"array",value:"number",length:4,default:[0,0,0,0],units:"pixels",requires:["icon-image","text-field",{"icon-text-fit":["both","width","height"]}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"icon-image":{type:"resolvedImage",tokens:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-rotate":{type:"number",default:0,period:360,units:"degrees",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-padding":{type:"padding",default:[2],units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-keep-upright":{type:"boolean",default:!1,requires:["icon-image",{"icon-rotation-alignment":"map"},{"symbol-placement":["line","line-center"]}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-offset":{type:"array",value:"number",length:2,default:[0,0],requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-anchor":{type:"enum",values:{center:{},left:{},right:{},top:{},bottom:{},"top-left":{},"top-right":{},"bottom-left":{},"bottom-right":{}},default:"center",requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-pitch-alignment":{type:"enum",values:{map:{},viewport:{},auto:{}},default:"auto",requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-pitch-alignment":{type:"enum",values:{map:{},viewport:{},auto:{}},default:"auto",requires:["text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-rotation-alignment":{type:"enum",values:{map:{},viewport:{},"viewport-glyph":{},auto:{}},default:"auto",requires:["text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-field":{type:"formatted",default:"",tokens:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-font":{type:"array",value:"string",default:["Open Sans Regular","Arial Unicode MS Regular"],requires:["text-field"],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-size":{type:"number",default:16,minimum:0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-max-width":{type:"number",default:10,minimum:0,units:"ems",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-line-height":{type:"number",default:1.2,units:"ems",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"text-letter-spacing":{type:"number",default:0,units:"ems",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-justify":{type:"enum",values:{auto:{},left:{},center:{},right:{}},default:"center",requires:["text-field"],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-radial-offset":{type:"number",units:"ems",default:0,requires:["text-field"],"property-type":"data-driven",expression:{interpolated:!0,parameters:["zoom","feature"]}},"text-variable-anchor":{type:"array",value:"enum",values:{center:{},left:{},right:{},top:{},bottom:{},"top-left":{},"top-right":{},"bottom-left":{},"bottom-right":{}},requires:["text-field",{"symbol-placement":["point"]}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-variable-anchor-offset":{type:"variableAnchorOffsetCollection",requires:["text-field",{"symbol-placement":["point"]}],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-anchor":{type:"enum",values:{center:{},left:{},right:{},top:{},bottom:{},"top-left":{},"top-right":{},"bottom-left":{},"bottom-right":{}},default:"center",requires:["text-field",{"!":"text-variable-anchor"}],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-max-angle":{type:"number",default:45,units:"degrees",requires:["text-field",{"symbol-placement":["line","line-center"]}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"text-writing-mode":{type:"array",value:"enum",values:{horizontal:{},vertical:{}},requires:["text-field",{"symbol-placement":["point"]}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-rotate":{type:"number",default:0,period:360,units:"degrees",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-padding":{type:"number",default:2,minimum:0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"text-keep-upright":{type:"boolean",default:!0,requires:["text-field",{"text-rotation-alignment":"map"},{"symbol-placement":["line","line-center"]}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-transform":{type:"enum",values:{none:{},uppercase:{},lowercase:{}},default:"none",requires:["text-field"],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-offset":{type:"array",value:"number",units:"ems",length:2,default:[0,0],requires:["text-field",{"!":"text-radial-offset"}],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-allow-overlap":{type:"boolean",default:!1,requires:["text-field",{"!":"text-overlap"}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-overlap":{type:"enum",values:{never:{},always:{},cooperative:{}},requires:["text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-ignore-placement":{type:"boolean",default:!1,requires:["text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-optional":{type:"boolean",default:!1,requires:["text-field","icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible",expression:{interpolated:!1,parameters:["global-state"]},"property-type":"data-constant"}},layout_raster:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible",expression:{interpolated:!1,parameters:["global-state"]},"property-type":"data-constant"}},layout_hillshade:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible",expression:{interpolated:!1,parameters:["global-state"]},"property-type":"data-constant"}},"layout_color-relief":{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible",expression:{interpolated:!1,parameters:["global-state"]},"property-type":"data-constant"}},filter:{type:"boolean",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},filter_operator:{type:"enum",values:{"==":{},"!=":{},">":{},">=":{},"<":{},"<=":{},in:{},"!in":{},all:{},any:{},none:{},has:{},"!has":{}}},geometry_type:{type:"enum",values:{Point:{},LineString:{},Polygon:{}}},function:{expression:{type:"expression"},stops:{type:"array",value:"function_stop"},base:{type:"number",default:1,minimum:0},property:{type:"string",default:"$zoom"},type:{type:"enum",values:{identity:{},exponential:{},interval:{},categorical:{}},default:"exponential"},colorSpace:{type:"enum",values:{rgb:{},lab:{},hcl:{}},default:"rgb"},default:{type:"*",required:!1}},function_stop:{type:"array",minimum:0,maximum:24,value:["number","color"],length:2},expression:{type:"array",value:"expression_name",minimum:1},light:{anchor:{type:"enum",default:"viewport",values:{map:{},viewport:{}},"property-type":"data-constant",transition:!1,expression:{interpolated:!1,parameters:["zoom"]}},position:{type:"array",default:[1.15,210,30],length:3,value:"number","property-type":"data-constant",transition:!0,expression:{interpolated:!0,parameters:["zoom"]}},color:{type:"color","property-type":"data-constant",default:"#ffffff",expression:{interpolated:!0,parameters:["zoom"]},transition:!0},intensity:{type:"number","property-type":"data-constant",default:.5,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0}},sky:{"sky-color":{type:"color","property-type":"data-constant",default:"#88C6FC",expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"horizon-color":{type:"color","property-type":"data-constant",default:"#ffffff",expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"fog-color":{type:"color","property-type":"data-constant",default:"#ffffff",expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"fog-ground-blend":{type:"number","property-type":"data-constant",default:.5,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"horizon-fog-blend":{type:"number","property-type":"data-constant",default:.8,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"sky-horizon-blend":{type:"number","property-type":"data-constant",default:.8,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"atmosphere-blend":{type:"number","property-type":"data-constant",default:.8,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0}},terrain:{source:{type:"string",required:!0},exaggeration:{type:"number",minimum:0,default:1}},projection:{type:{type:"projectionDefinition",default:"mercator","property-type":"data-constant",transition:!1,expression:{interpolated:!0,parameters:["zoom"]}}},paint:["paint_fill","paint_line","paint_circle","paint_heatmap","paint_fill-extrusion","paint_symbol","paint_raster","paint_hillshade","paint_color-relief","paint_background"],paint_fill:{"fill-antialias":{type:"boolean",default:!0,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"fill-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"fill-pattern"}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-outline-color":{type:"color",transition:!0,requires:[{"!":"fill-pattern"},{"fill-antialias":!0}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"fill-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["fill-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"fill-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"}},"paint_fill-extrusion":{"fill-extrusion-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"fill-extrusion-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"fill-extrusion-pattern"}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"fill-extrusion-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["fill-extrusion-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"fill-extrusion-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"},"fill-extrusion-height":{type:"number",default:0,minimum:0,units:"meters",transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-base":{type:"number",default:0,minimum:0,units:"meters",transition:!0,requires:["fill-extrusion-height"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-vertical-gradient":{type:"boolean",default:!0,transition:!1,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"}},paint_line:{"line-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"line-pattern"}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"line-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["line-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"line-width":{type:"number",default:1,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-gap-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-offset":{type:"number",default:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-blur":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-dasharray":{type:"array",value:"number",minimum:0,transition:!0,units:"line widths",requires:[{"!":"line-pattern"}],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"},"line-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"},"line-gradient":{type:"color",transition:!1,requires:[{"!":"line-dasharray"},{"!":"line-pattern"},{source:"geojson",has:{lineMetrics:!0}}],expression:{interpolated:!0,parameters:["line-progress"]},"property-type":"color-ramp"}},paint_circle:{"circle-radius":{type:"number",default:5,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-color":{type:"color",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-blur":{type:"number",default:0,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"circle-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["circle-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"circle-pitch-scale":{type:"enum",values:{map:{},viewport:{}},default:"map",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"circle-pitch-alignment":{type:"enum",values:{map:{},viewport:{}},default:"viewport",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"circle-stroke-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-stroke-color":{type:"color",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-stroke-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"}},paint_heatmap:{"heatmap-radius":{type:"number",default:30,minimum:1,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"heatmap-weight":{type:"number",default:1,minimum:0,transition:!1,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"heatmap-intensity":{type:"number",default:1,minimum:0,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"heatmap-color":{type:"color",default:["interpolate",["linear"],["heatmap-density"],0,"rgba(0, 0, 255, 0)",.1,"royalblue",.3,"cyan",.5,"lime",.7,"yellow",1,"red"],transition:!1,expression:{interpolated:!0,parameters:["heatmap-density"]},"property-type":"color-ramp"},"heatmap-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"}},paint_symbol:{"icon-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-color":{type:"color",default:"#000000",transition:!0,requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-halo-color":{type:"color",default:"rgba(0, 0, 0, 0)",transition:!0,requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-halo-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-halo-blur":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"icon-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["icon-image","icon-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-color":{type:"color",default:"#000000",transition:!0,overridable:!0,requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-halo-color":{type:"color",default:"rgba(0, 0, 0, 0)",transition:!0,requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-halo-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-halo-blur":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"text-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["text-field","text-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"}},paint_raster:{"raster-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-hue-rotate":{type:"number",default:0,period:360,transition:!0,units:"degrees",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-brightness-min":{type:"number",default:0,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-brightness-max":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-saturation":{type:"number",default:0,minimum:-1,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-contrast":{type:"number",default:0,minimum:-1,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},resampling:{type:"enum",values:{linear:{},nearest:{}},default:"linear",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"raster-resampling":{type:"enum",values:{linear:{},nearest:{}},default:"linear",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"raster-fade-duration":{type:"number",default:300,minimum:0,transition:!1,units:"milliseconds",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"}},paint_hillshade:{"hillshade-illumination-direction":{type:"numberArray",default:335,minimum:0,maximum:359,transition:!1,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-illumination-altitude":{type:"numberArray",default:45,minimum:0,maximum:90,transition:!1,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-illumination-anchor":{type:"enum",values:{map:{},viewport:{}},default:"viewport",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-exaggeration":{type:"number",default:.5,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-shadow-color":{type:"colorArray",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-highlight-color":{type:"colorArray",default:"#FFFFFF",transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-accent-color":{type:"color",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-method":{type:"enum",values:{standard:{},basic:{},combined:{},igor:{},multidirectional:{}},default:"standard",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},resampling:{type:"enum",values:{linear:{},nearest:{}},default:"linear",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"}},"paint_color-relief":{"color-relief-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"color-relief-color":{type:"color",transition:!1,expression:{interpolated:!0,parameters:["elevation"]},"property-type":"color-ramp"},resampling:{type:"enum",values:{linear:{},nearest:{}},default:"linear",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"}},paint_background:{"background-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"background-pattern"}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"background-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"cross-faded"},"background-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"}},transition:{duration:{type:"number",default:300,minimum:0,units:"milliseconds"},delay:{type:"number",default:0,minimum:0,units:"milliseconds"}},"property-type":{"data-driven":{type:"property-type"},"cross-faded":{type:"property-type"},"cross-faded-data-driven":{type:"property-type"},"color-ramp":{type:"property-type"},"data-constant":{type:"property-type"},constant:{type:"property-type"}},promoteId:{"*":{type:"string"}},interpolation:{type:"array",value:"interpolation_name",minimum:1},interpolation_name:{type:"enum",values:{linear:{syntax:{overloads:[{parameters:[],"output-type":"interpolation"}],parameters:[]}},exponential:{syntax:{overloads:[{parameters:["base"],"output-type":"interpolation"}],parameters:[{name:"base",type:"number literal"}]}},"cubic-bezier":{syntax:{overloads:[{parameters:["x1","y1","x2","y2"],"output-type":"interpolation"}],parameters:[{name:"x1",type:"number literal"},{name:"y1",type:"number literal"},{name:"x2",type:"number literal"},{name:"y2",type:"number literal"}]}}}}};let Ba=["type","source","source-layer","minzoom","maxzoom","filter","layout"];function Oa(r,e){let i={};for(let o in r)o!=="ref"&&(i[o]=r[o]);return Ba.forEach((o=>{o in e&&(i[o]=e[o])})),i}function it(r,e){if(Array.isArray(r)){if(!Array.isArray(e)||r.length!==e.length)return!1;for(let i=0;i`:r.itemType.kind==="value"?"array":`array<${e}>`}return r.kind}let ys=[zr,be,Fe,je,Ei,gs,To,ur,Yt(Oe),_s,Po,Bn,On,So];function Nn(r,e){if(e.kind==="error")return null;if(r.kind==="array"){if(e.kind==="array"&&(e.N===0&&e.itemType.kind==="value"||!Nn(r.itemType,e.itemType))&&(typeof r.N!="number"||r.N===e.N))return null}else{if(r.kind===e.kind)return null;if(r.kind==="value"){for(let i of ys)if(!Nn(i,e))return null}}return`Expected ${rt(r)} but found ${rt(e)} instead.`}function Io(r,e){return e.some((i=>i.kind===r.kind))}function on(r,e){return e.some((i=>i==="null"?r===null:i==="array"?Array.isArray(r):i==="object"?r&&!Array.isArray(r)&&typeof r=="object":i===typeof r))}function Xi(r,e){return r.kind==="array"&&e.kind==="array"?r.itemType.kind===e.itemType.kind&&typeof r.N=="number":r.kind===e.kind}let ac=.96422,sn=.82521,vs=4/29,bt=6/29,lc=3*bt*bt,cc=bt*bt*bt,Mo=Math.PI/180,hc=180/Math.PI;function uc(r){return(r%=360)<0&&(r+=360),r}function dc([r,e,i,o]){let s,l,h=ja((.2225045*(r=xs(r))+.7168786*(e=xs(e))+.0606169*(i=xs(i)))/1);r===e&&e===i?s=l=h:(s=ja((.4360747*r+.3850649*e+.1430804*i)/ac),l=ja((.0139322*r+.0971045*e+.7141733*i)/sn));let d=116*h-16;return[d<0?0:d,500*(s-h),200*(h-l),o]}function xs(r){return r<=.04045?r/12.92:Math.pow((r+.055)/1.055,2.4)}function ja(r){return r>cc?Math.pow(r,1/3):r/lc+vs}function Ua([r,e,i,o]){let s=(r+16)/116,l=isNaN(e)?s:s+e/500,h=isNaN(i)?s:s-i/200;return s=1*$a(s),l=ac*$a(l),h=sn*$a(h),[Ga(3.1338561*l-1.6168667*s-.4906146*h),Ga(-.9787684*l+1.9161415*s+.033454*h),Ga(.0719453*l-.2289914*s+1.4052427*h),o]}function Ga(r){return(r=r<=.00304?12.92*r:1.055*Math.pow(r,1/2.4)-.055)<0?0:r>1?1:r}function $a(r){return r>bt?r*r*r:lc*(r-vs)}let Bh=Object.hasOwn||function(r,e){return Object.prototype.hasOwnProperty.call(r,e)};function Eo(r,e){return Bh(r,e)?r[e]:void 0}function bs(r){return parseInt(r.padEnd(2,r),16)/255}function pc(r,e){return Vn(e?r/100:r,0,1)}function Vn(r,e,i){return Math.min(Math.max(e,r),i)}function Za(r){return!r.some(Number.isNaN)}let Co={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]};function Rr(r,e,i){return r+i*(e-r)}function jn(r,e,i){return r.map(((o,s)=>Rr(o,e[s],i)))}class Ve{constructor(e,i,o,s=1,l=!0){this.r=e,this.g=i,this.b=o,this.a=s,l||(this.r*=s,this.g*=s,this.b*=s,s||this.overwriteGetter("rgb",[e,i,o,s]))}static parse(e){if(e instanceof Ve)return e;if(typeof e!="string")return;let i=(function(o){if((o=o.toLowerCase().trim())==="transparent")return[0,0,0,0];let s=Eo(Co,o);if(s){let[h,d,g]=s;return[h/255,d/255,g/255,1]}if(o.startsWith("#")&&/^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/.test(o)){let h=o.length<6?1:2,d=1;return[bs(o.slice(d,d+=h)),bs(o.slice(d,d+=h)),bs(o.slice(d,d+=h)),bs(o.slice(d,d+h)||"ff")]}if(o.startsWith("rgb")){let h=o.match(/^rgba?\(\s*([\de.+-]+)(%)?(?:\s+|\s*(,)\s*)([\de.+-]+)(%)?(?:\s+|\s*(,)\s*)([\de.+-]+)(%)?(?:\s*([,\/])\s*([\de.+-]+)(%)?)?\s*\)$/);if(h){let[d,g,m,v,_,T,b,I,M,A,D,L]=h,R=[v||" ",b||" ",A].join("");if(R===" "||R===" /"||R===",,"||R===",,,"){let F=[m,T,M].join(""),O=F==="%%%"?100:F===""?255:0;if(O){let V=[Vn(+g/O,0,1),Vn(+_/O,0,1),Vn(+I/O,0,1),D?pc(+D,L):1];if(Za(V))return V}}return}}let l=o.match(/^hsla?\(\s*([\de.+-]+)(?:deg)?(?:\s+|\s*(,)\s*)([\de.+-]+)%(?:\s+|\s*(,)\s*)([\de.+-]+)%(?:\s*([,\/])\s*([\de.+-]+)(%)?)?\s*\)$/);if(l){let[h,d,g,m,v,_,T,b,I]=l,M=[g||" ",v||" ",T].join("");if(M===" "||M===" /"||M===",,"||M===",,,"){let A=[+d,Vn(+m,0,100),Vn(+_,0,100),b?pc(+b,I):1];if(Za(A))return(function([D,L,R,F]){function O(V){let Y=(V+D/30)%12,J=L*Math.min(R,1-R);return R-J*Math.max(-1,Math.min(Y-3,9-Y,1))}return D=uc(D),L/=100,R/=100,[O(0),O(8),O(4),F]})(A)}}})(e);return i?new Ve(...i,!1):void 0}get rgb(){let{r:e,g:i,b:o,a:s}=this,l=s||1/0;return this.overwriteGetter("rgb",[e/l,i/l,o/l,s])}get hcl(){return this.overwriteGetter("hcl",(function(e){let[i,o,s,l]=dc(e),h=Math.sqrt(o*o+s*s);return[Math.round(1e4*h)?uc(Math.atan2(s,o)*hc):NaN,h,i,l]})(this.rgb))}get lab(){return this.overwriteGetter("lab",dc(this.rgb))}overwriteGetter(e,i){return Object.defineProperty(this,e,{value:i}),i}toString(){let[e,i,o,s]=this.rgb;return`rgba(${[e,i,o].map((l=>Math.round(255*l))).join(",")},${s})`}static interpolate(e,i,o,s="rgb"){switch(s){case"rgb":{let[l,h,d,g]=jn(e.rgb,i.rgb,o);return new Ve(l,h,d,g,!1)}case"hcl":{let[l,h,d,g]=e.hcl,[m,v,_,T]=i.hcl,b,I;if(isNaN(l)||isNaN(m))isNaN(l)?isNaN(m)?b=NaN:(b=m,d!==1&&d!==0||(I=v)):(b=l,_!==1&&_!==0||(I=h));else{let R=m-l;m>l&&R>180?R-=360:m180&&(R+=360),b=l+o*R}let[M,A,D,L]=(function([R,F,O,V]){return R=isNaN(R)?0:R*Mo,Ua([O,Math.cos(R)*F,Math.sin(R)*F,V])})([b,I??Rr(h,v,o),Rr(d,_,o),Rr(g,T,o)]);return new Ve(M,A,D,L,!1)}case"lab":{let[l,h,d,g]=Ua(jn(e.lab,i.lab,o));return new Ve(l,h,d,g,!1)}}}}Ve.black=new Ve(0,0,0,1),Ve.white=new Ve(1,1,1,1),Ve.transparent=new Ve(0,0,0,0),Ve.red=new Ve(1,0,0,1);class qa{constructor(e,i,o){this.sensitivity=e?i?"variant":"case":i?"accent":"base",this.locale=o,this.collator=new Intl.Collator(this.locale?this.locale:[],{sensitivity:this.sensitivity,usage:"search"})}compare(e,i){return this.collator.compare(e,i)}resolvedLocale(){return new Intl.Collator(this.locale?this.locale:[]).resolvedOptions().locale}}let Oh=["bottom","center","top"];class Wa{constructor(e,i,o,s,l,h){this.text=e,this.image=i,this.scale=o,this.fontStack=s,this.textColor=l,this.verticalAlign=h}}class xi{constructor(e){this.sections=e}static fromString(e){return new xi([new Wa(e,null,null,null,null,null)])}isEmpty(){return this.sections.length===0||!this.sections.some((e=>e.text.length!==0||e.image&&e.image.name.length!==0))}static factory(e){return e instanceof xi?e:xi.fromString(e)}toString(){return this.sections.length===0?"":this.sections.map((e=>e.text)).join("")}}class ei{constructor(e){this.values=e.slice()}static parse(e){if(e instanceof ei)return e;if(typeof e=="number")return new ei([e,e,e,e]);if(Array.isArray(e)&&!(e.length<1||e.length>4)){for(let i of e)if(typeof i!="number")return;switch(e.length){case 1:e=[e[0],e[0],e[0],e[0]];break;case 2:e=[e[0],e[1],e[0],e[1]];break;case 3:e=[e[0],e[1],e[2],e[1]]}return new ei(e)}}toString(){return JSON.stringify(this.values)}static interpolate(e,i,o){return new ei(jn(e.values,i.values,o))}}class ft{constructor(e){this.values=e.slice()}static parse(e){if(e instanceof ft)return e;if(typeof e=="number")return new ft([e]);if(Array.isArray(e)){for(let i of e)if(typeof i!="number")return;return new ft(e)}}toString(){return JSON.stringify(this.values)}static interpolate(e,i,o){return new ft(jn(e.values,i.values,o))}}class ke{constructor(e){this.values=e.slice()}static parse(e){if(e instanceof ke)return e;if(typeof e=="string"){let o=Ve.parse(e);return o?new ke([o]):void 0}if(!Array.isArray(e))return;let i=[];for(let o of e){if(typeof o!="string")return;let s=Ve.parse(o);if(!s)return;i.push(s)}return new ke(i)}toString(){return JSON.stringify(this.values)}static interpolate(e,i,o,s="rgb"){let l=[];if(e.values.length!=i.values.length)throw new Error(`colorArray: Arrays have mismatched length (${e.values.length} vs. ${i.values.length}), cannot interpolate.`);for(let h=0;h=0&&r<=255&&typeof e=="number"&&e>=0&&e<=255&&typeof i=="number"&&i>=0&&i<=255?o===void 0||typeof o=="number"&&o>=0&&o<=1?null:`Invalid rgba value [${[r,e,i,o].join(", ")}]: 'a' must be between 0 and 1.`:`Invalid rgba value [${(typeof o=="number"?[r,e,i,o]:[r,e,i]).join(", ")}]: 'r', 'g', and 'b' must be between 0 and 255.`}function Lr(r){if(r===null||typeof r=="string"||typeof r=="boolean"||typeof r=="number"||r instanceof hi||r instanceof Ve||r instanceof qa||r instanceof xi||r instanceof ei||r instanceof ft||r instanceof ke||r instanceof ci||r instanceof Ci)return!0;if(Array.isArray(r)){for(let e of r)if(!Lr(e))return!1;return!0}if(typeof r=="object"){for(let e in r)if(!Lr(r[e]))return!1;return!0}return!1}function St(r){if(r===null)return zr;if(typeof r=="string")return Fe;if(typeof r=="boolean")return je;if(typeof r=="number")return be;if(r instanceof Ve)return Ei;if(r instanceof hi)return gs;if(r instanceof qa)return wo;if(r instanceof xi)return To;if(r instanceof ei)return _s;if(r instanceof ft)return Po;if(r instanceof ke)return Bn;if(r instanceof ci)return So;if(r instanceof Ci)return On;if(Array.isArray(r)){let e=r.length,i;for(let o of r){let s=St(o);if(i){if(i===s)continue;i=Oe;break}i=s}return Yt(i||Oe,e)}return ur}function an(r){let e=typeof r;return r===null?"":e==="string"||e==="number"||e==="boolean"?String(r):r instanceof Ve||r instanceof hi||r instanceof xi||r instanceof ei||r instanceof ft||r instanceof ke||r instanceof ci||r instanceof Ci?r.toString():JSON.stringify(r)}class ir{constructor(e,i){this.type=e,this.value=i}static parse(e,i){if(e.length!==2)return i.error(`'literal' expression requires exactly one argument, but found ${e.length-1} instead.`);if(!Lr(e[1]))return i.error("invalid value");let o=e[1],s=St(o),l=i.expectedType;return s.kind!=="array"||s.N!==0||!l||l.kind!=="array"||typeof l.N=="number"&&l.N!==0||(s=l),new ir(s,o)}evaluate(){return this.value}eachChild(){}outputDefined(){return!0}}let ws={string:Fe,number:be,boolean:je,object:ur};class bi{constructor(e,i){this.type=e,this.args=i}static parse(e,i){if(e.length<2)return i.error("Expected at least one argument.");let o,s=1,l=e[0];if(l==="array"){let d,g;if(e.length>2){let m=e[1];if(typeof m!="string"||!(m in ws)||m==="object")return i.error('The item type argument of "array" must be one of string, number, boolean',1);d=ws[m],s++}else d=Oe;if(e.length>3){if(e[2]!==null&&(typeof e[2]!="number"||e[2]<0||e[2]!==Math.floor(e[2])))return i.error('The length argument to "array" must be a positive integer literal',2);g=e[2],s++}o=Yt(d,g)}else{if(!ws[l])throw new Error(`Types doesn't contain name = ${l}`);o=ws[l]}let h=[];for(;se.outputDefined()))}}let ln={"to-boolean":je,"to-color":Ei,"to-number":be,"to-string":Fe};class dr{constructor(e,i){this.type=e,this.args=i}static parse(e,i){if(e.length<2)return i.error("Expected at least one argument.");let o=e[0];if(!ln[o])throw new Error(`Can't parse ${o} as it is not part of the known types`);if((o==="to-boolean"||o==="to-string")&&e.length!==2)return i.error("Expected one argument.");let s=ln[o],l=[];for(let h=1;h4?`Invalid rgba value ${JSON.stringify(i)}: expected an array containing either three or four numeric values.`:Un(i[0],i[1],i[2],i[3]),!o))return new Ve(i[0]/255,i[1]/255,i[2]/255,i[3])}throw new at(o||`Could not parse color from value '${typeof i=="string"?i:JSON.stringify(i)}'`)}case"padding":{let i;for(let o of this.args){i=o.evaluate(e);let s=ei.parse(i);if(s)return s}throw new at(`Could not parse padding from value '${typeof i=="string"?i:JSON.stringify(i)}'`)}case"numberArray":{let i;for(let o of this.args){i=o.evaluate(e);let s=ft.parse(i);if(s)return s}throw new at(`Could not parse numberArray from value '${typeof i=="string"?i:JSON.stringify(i)}'`)}case"colorArray":{let i;for(let o of this.args){i=o.evaluate(e);let s=ke.parse(i);if(s)return s}throw new at(`Could not parse colorArray from value '${typeof i=="string"?i:JSON.stringify(i)}'`)}case"variableAnchorOffsetCollection":{let i;for(let o of this.args){i=o.evaluate(e);let s=ci.parse(i);if(s)return s}throw new at(`Could not parse variableAnchorOffsetCollection from value '${typeof i=="string"?i:JSON.stringify(i)}'`)}case"number":{let i=null;for(let o of this.args){if(i=o.evaluate(e),i===null)return 0;let s=Number(i);if(!isNaN(s))return s}throw new at(`Could not convert ${JSON.stringify(i)} to number.`)}case"formatted":return xi.fromString(an(this.args[0].evaluate(e)));case"resolvedImage":return Ci.fromString(an(this.args[0].evaluate(e)));case"projectionDefinition":return this.args[0].evaluate(e);default:return an(this.args[0].evaluate(e))}}eachChild(e){this.args.forEach(e)}outputDefined(){return this.args.every((e=>e.outputDefined()))}}let fc=["Unknown","Point","LineString","Polygon"];class Ha{constructor(){this.globals=null,this.feature=null,this.featureState=null,this.formattedSection=null,this._parseColorCache=new Map,this.availableImages=null,this.canonical=null}id(){return this.feature&&"id"in this.feature?this.feature.id:null}geometryType(){return this.feature?typeof this.feature.type=="number"?fc[this.feature.type]:this.feature.type:null}geometry(){return this.feature&&"geometry"in this.feature?this.feature.geometry:null}canonicalID(){return this.canonical}properties(){return this.feature&&this.feature.properties||{}}parseColor(e){let i=this._parseColorCache.get(e);return i||(i=Ve.parse(e),this._parseColorCache.set(e,i)),i}}class cn{constructor(e,i,o=[],s,l=new Va,h=[]){this.registry=e,this.path=o,this.key=o.map((d=>`[${d}]`)).join(""),this.scope=l,this.errors=h,this.expectedType=s,this._isConstant=i}parse(e,i,o,s,l={}){return i?this.concat(i,o,s)._parse(e,l):this._parse(e,l)}_parse(e,i){function o(s,l,h){return h==="assert"?new bi(l,[s]):h==="coerce"?new dr(l,[s]):s}if(e!==null&&typeof e!="string"&&typeof e!="boolean"&&typeof e!="number"||(e=["literal",e]),Array.isArray(e)){if(e.length===0)return this.error('Expected an array with at least one element. If you wanted a literal array, use ["literal", []].');let s=e[0];if(typeof s!="string")return this.error(`Expression name must be a string, but found ${typeof s} instead. If you wanted a literal array, use ["literal", [...]].`,0),null;let l=this.registry[s];if(l){let h=l.parse(e,this);if(!h)return null;if(this.expectedType){let d=this.expectedType,g=h.type;if(d.kind!=="string"&&d.kind!=="number"&&d.kind!=="boolean"&&d.kind!=="object"&&d.kind!=="array"||g.kind!=="value"){if(d.kind==="projectionDefinition"&&["string","array"].includes(g.kind)||["color","formatted","resolvedImage"].includes(d.kind)&&["value","string"].includes(g.kind)||["padding","numberArray"].includes(d.kind)&&["value","number","array"].includes(g.kind)||d.kind==="colorArray"&&["value","string","array"].includes(g.kind)||d.kind==="variableAnchorOffsetCollection"&&["value","array"].includes(g.kind))h=o(h,d,i.typeAnnotation||"coerce");else if(this.checkSubtype(d,g))return null}else h=o(h,d,i.typeAnnotation||"assert")}if(!(h instanceof ir)&&h.type.kind!=="resolvedImage"&&this._isConstant(h)){let d=new Ha;try{h=new ir(h.type,h.evaluate(d))}catch(g){return this.error(g.message),null}}return h}return this.error(`Unknown expression "${s}". If you wanted a literal array, use ["literal", [...]].`,0)}return this.error(e===void 0?"'undefined' value invalid. Use null instead.":typeof e=="object"?'Bare objects invalid. Use ["literal", {...}] instead.':`Expected an array, but found ${typeof e} instead.`)}concat(e,i,o){let s=typeof e=="number"?this.path.concat(e):this.path,l=o?this.scope.concat(o):this.scope;return new cn(this.registry,this._isConstant,s,i||null,l,this.errors)}error(e,...i){let o=`${this.key}${i.map((s=>`[${s}]`)).join("")}`;this.errors.push(new Xt(o,e))}checkSubtype(e,i){let o=Nn(e,i);return o&&this.error(o),o}}class lt{constructor(e,i){this.type=i.type,this.bindings=[].concat(e),this.result=i}evaluate(e){return this.result.evaluate(e)}eachChild(e){for(let i of this.bindings)e(i[1]);e(this.result)}static parse(e,i){if(e.length<4)return i.error(`Expected at least 3 arguments, but found ${e.length-1} instead.`);let o=[];for(let l=1;l=o.length)throw new at(`Array index out of bounds: ${i} > ${o.length-1}.`);if(i!==Math.floor(i))throw new at(`Array index must be an integer, but found ${i} instead.`);return o[i]}eachChild(e){e(this.index),e(this.input)}outputDefined(){return!1}}class Ne{constructor(e,i){this.type=je,this.needle=e,this.haystack=i}static parse(e,i){if(e.length!==3)return i.error(`Expected 2 arguments, but found ${e.length-1} instead.`);let o=i.parse(e[1],1,Oe),s=i.parse(e[2],2,Oe);return o&&s?Io(o.type,[je,Fe,be,zr,Oe])?new Ne(o,s):i.error(`Expected first argument to be of type boolean, string, number or null, but found ${rt(o.type)} instead`):null}evaluate(e){let i=this.needle.evaluate(e),o=this.haystack.evaluate(e);if(!o)return!1;if(!on(i,["boolean","string","number","null"]))throw new at(`Expected first argument to be of type boolean, string, number or null, but found ${rt(St(i))} instead.`);if(!on(o,["string","array"]))throw new at(`Expected second argument to be of type array or string, but found ${rt(St(o))} instead.`);return o.indexOf(i)>=0}eachChild(e){e(this.needle),e(this.haystack)}outputDefined(){return!0}}class $n{constructor(e,i,o){this.type=be,this.needle=e,this.haystack=i,this.fromIndex=o}static parse(e,i){if(e.length<=2||e.length>=5)return i.error(`Expected 2 or 3 arguments, but found ${e.length-1} instead.`);let o=i.parse(e[1],1,Oe),s=i.parse(e[2],2,Oe);if(!o||!s)return null;if(!Io(o.type,[je,Fe,be,zr,Oe]))return i.error(`Expected first argument to be of type boolean, string, number or null, but found ${rt(o.type)} instead`);if(e.length===4){let l=i.parse(e[3],3,be);return l?new $n(o,s,l):null}return new $n(o,s)}evaluate(e){let i=this.needle.evaluate(e),o=this.haystack.evaluate(e);if(!on(i,["boolean","string","number","null"]))throw new at(`Expected first argument to be of type boolean, string, number or null, but found ${rt(St(i))} instead.`);let s;if(this.fromIndex&&(s=this.fromIndex.evaluate(e)),on(o,["string"])){let l=o.indexOf(i,s);return l===-1?-1:[...o.slice(0,l)].length}if(on(o,["array"]))return o.indexOf(i,s);throw new at(`Expected second argument to be of type array or string, but found ${rt(St(o))} instead.`)}eachChild(e){e(this.needle),e(this.haystack),this.fromIndex&&e(this.fromIndex)}outputDefined(){return!1}}class He{constructor(e,i,o,s,l,h){this.inputType=e,this.type=i,this.input=o,this.cases=s,this.outputs=l,this.otherwise=h}static parse(e,i){if(e.length<5)return i.error(`Expected at least 4 arguments, but found only ${e.length-1}.`);if(e.length%2!=1)return i.error("Expected an even number of arguments.");let o,s;i.expectedType&&i.expectedType.kind!=="value"&&(s=i.expectedType);let l={},h=[];for(let m=2;mNumber.MAX_SAFE_INTEGER)return T.error(`Branch labels must be integers no larger than ${Number.MAX_SAFE_INTEGER}.`);if(typeof I=="number"&&Math.floor(I)!==I)return T.error("Numeric branch labels must be integer values.");if(o){if(T.checkSubtype(o,St(I)))return null}else o=St(I);if(l[String(I)]!==void 0)return T.error("Branch labels must be unique.");l[String(I)]=h.length}let b=i.parse(_,m,s);if(!b)return null;s=s||b.type,h.push(b)}let d=i.parse(e[1],1,Oe);if(!d)return null;let g=i.parse(e[e.length-1],e.length-1,s);return g?d.type.kind!=="value"&&i.concat(1).checkSubtype(o,d.type)?null:new He(o,s,d,l,h,g):null}evaluate(e){let i=this.input.evaluate(e);return(St(i)===this.inputType&&this.outputs[this.cases[i]]||this.otherwise).evaluate(e)}eachChild(e){e(this.input),this.outputs.forEach(e),e(this.otherwise)}outputDefined(){return this.outputs.every((e=>e.outputDefined()))&&this.otherwise.outputDefined()}}class Yi{constructor(e,i,o){this.type=e,this.branches=i,this.otherwise=o}static parse(e,i){if(e.length<4)return i.error(`Expected at least 3 arguments, but found only ${e.length-1}.`);if(e.length%2!=0)return i.error("Expected an odd number of arguments.");let o;i.expectedType&&i.expectedType.kind!=="value"&&(o=i.expectedType);let s=[];for(let h=1;hi.outputDefined()))&&this.otherwise.outputDefined()}}class Zn{constructor(e,i,o,s){this.type=e,this.input=i,this.beginIndex=o,this.endIndex=s}static parse(e,i){if(e.length<=2||e.length>=5)return i.error(`Expected 2 or 3 arguments, but found ${e.length-1} instead.`);let o=i.parse(e[1],1,Oe),s=i.parse(e[2],2,be);if(!o||!s)return null;if(!Io(o.type,[Yt(Oe),Fe,Oe]))return i.error(`Expected first argument to be of type array or string, but found ${rt(o.type)} instead`);if(e.length===4){let l=i.parse(e[3],3,be);return l?new Zn(o.type,o,s,l):null}return new Zn(o.type,o,s)}evaluate(e){let i=this.input.evaluate(e),o=this.beginIndex.evaluate(e),s;if(this.endIndex&&(s=this.endIndex.evaluate(e)),on(i,["string"]))return[...i].slice(o,s).join("");if(on(i,["array"]))return i.slice(o,s);throw new at(`Expected first argument to be of type array or string, but found ${rt(St(i))} instead.`)}eachChild(e){e(this.input),e(this.beginIndex),this.endIndex&&e(this.endIndex)}outputDefined(){return!1}}function hn(r,e){let i=r.length-1,o,s,l=0,h=i,d=0;for(;l<=h;)if(d=Math.floor((l+h)/2),o=r[d],s=r[d+1],o<=e){if(d===i||ee))throw new at("Input is not a number.");h=d-1}return 0}class qn{constructor(e,i,o){this.type=e,this.input=i,this.labels=[],this.outputs=[];for(let[s,l]of o)this.labels.push(s),this.outputs.push(l)}static parse(e,i){if(e.length-1<4)return i.error(`Expected at least 4 arguments, but found only ${e.length-1}.`);if((e.length-1)%2!=0)return i.error("Expected an even number of arguments.");let o=i.parse(e[1],1,be);if(!o)return null;let s=[],l=null;i.expectedType&&i.expectedType.kind!=="value"&&(l=i.expectedType);for(let h=1;h=d)return i.error('Input/output pairs for "step" expressions must be arranged with input values in strictly ascending order.',m);let _=i.parse(g,v,l);if(!_)return null;l=l||_.type,s.push([d,_])}return new qn(l,o,s)}evaluate(e){let i=this.labels,o=this.outputs;if(i.length===1)return o[0].evaluate(e);let s=this.input.evaluate(e);if(s<=i[0])return o[0].evaluate(e);let l=i.length;return s>=i[l-1]?o[l-1].evaluate(e):o[hn(i,s)].evaluate(e)}eachChild(e){e(this.input);for(let i of this.outputs)e(i)}outputDefined(){return this.outputs.every((e=>e.outputDefined()))}}function Xa(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var Ts,mc,gc=(function(){if(mc)return Ts;function r(e,i,o,s){this.cx=3*e,this.bx=3*(o-e)-this.cx,this.ax=1-this.cx-this.bx,this.cy=3*i,this.by=3*(s-i)-this.cy,this.ay=1-this.cy-this.by,this.p1x=e,this.p1y=i,this.p2x=o,this.p2y=s}return mc=1,Ts=r,r.prototype={sampleCurveX:function(e){return((this.ax*e+this.bx)*e+this.cx)*e},sampleCurveY:function(e){return((this.ay*e+this.by)*e+this.cy)*e},sampleCurveDerivativeX:function(e){return(3*this.ax*e+2*this.bx)*e+this.cx},solveCurveX:function(e,i){if(i===void 0&&(i=1e-6),e<0)return 0;if(e>1)return 1;for(var o=e,s=0;s<8;s++){var l=this.sampleCurveX(o)-e;if(Math.abs(l)l?d=o:g=o,o=.5*(g-d)+d;return o},solve:function(e,i){return this.sampleCurveY(this.solveCurveX(e,i))}},Ts})(),_c=Xa(gc);class Et{constructor(e,i,o,s,l){this.type=e,this.operator=i,this.interpolation=o,this.input=s,this.labels=[],this.outputs=[];for(let[h,d]of l)this.labels.push(h),this.outputs.push(d)}static interpolationFactor(e,i,o,s){let l=0;if(e.name==="exponential")l=Ot(i,e.base,o,s);else if(e.name==="linear")l=Ot(i,1,o,s);else if(e.name==="cubic-bezier"){let h=e.controlPoints;l=new _c(h[0],h[1],h[2],h[3]).solve(Ot(i,1,o,s))}return l}static parse(e,i){let[o,s,l,...h]=e;if(!Array.isArray(s)||s.length===0)return i.error("Expected an interpolation type expression.",1);if(s[0]==="linear")s={name:"linear"};else if(s[0]==="exponential"){let m=s[1];if(typeof m!="number")return i.error("Exponential interpolation requires a numeric base.",1,1);s={name:"exponential",base:m}}else{if(s[0]!=="cubic-bezier")return i.error(`Unknown interpolation type ${String(s[0])}`,1,0);{let m=s.slice(1);if(m.length!==4||m.some((v=>typeof v!="number"||v<0||v>1)))return i.error("Cubic bezier interpolation requires four numeric arguments with values between 0 and 1.",1);s={name:"cubic-bezier",controlPoints:m}}}if(e.length-1<4)return i.error(`Expected at least 4 arguments, but found only ${e.length-1}.`);if((e.length-1)%2!=0)return i.error("Expected an even number of arguments.");if(l=i.parse(l,2,be),!l)return null;let d=[],g=null;o!=="interpolate-hcl"&&o!=="interpolate-lab"||i.expectedType==Bn?i.expectedType&&i.expectedType.kind!=="value"&&(g=i.expectedType):g=Ei;for(let m=0;m=v)return i.error('Input/output pairs for "interpolate" expressions must be arranged with input values in strictly ascending order.',T);let I=i.parse(_,b,g);if(!I)return null;g=g||I.type,d.push([v,I])}return Xi(g,be)||Xi(g,gs)||Xi(g,Ei)||Xi(g,_s)||Xi(g,Po)||Xi(g,Bn)||Xi(g,So)||Xi(g,Yt(be))?new Et(g,o,s,l,d):i.error(`Type ${rt(g)} is not interpolatable.`)}evaluate(e){let i=this.labels,o=this.outputs;if(i.length===1)return o[0].evaluate(e);let s=this.input.evaluate(e);if(s<=i[0])return o[0].evaluate(e);let l=i.length;if(s>=i[l-1])return o[l-1].evaluate(e);let h=hn(i,s),d=Et.interpolationFactor(this.interpolation,s,i[h],i[h+1]),g=o[h].evaluate(e),m=o[h+1].evaluate(e);switch(this.operator){case"interpolate":switch(this.type.kind){case"number":return Rr(g,m,d);case"color":return Ve.interpolate(g,m,d);case"padding":return ei.interpolate(g,m,d);case"colorArray":return ke.interpolate(g,m,d);case"numberArray":return ft.interpolate(g,m,d);case"variableAnchorOffsetCollection":return ci.interpolate(g,m,d);case"array":return jn(g,m,d);case"projectionDefinition":return hi.interpolate(g,m,d)}case"interpolate-hcl":switch(this.type.kind){case"color":return Ve.interpolate(g,m,d,"hcl");case"colorArray":return ke.interpolate(g,m,d,"hcl")}case"interpolate-lab":switch(this.type.kind){case"color":return Ve.interpolate(g,m,d,"lab");case"colorArray":return ke.interpolate(g,m,d,"lab")}}}eachChild(e){e(this.input);for(let i of this.outputs)e(i)}outputDefined(){return this.outputs.every((e=>e.outputDefined()))}}function Ot(r,e,i,o){let s=o-i,l=r-i;return s===0?0:e===1?l/s:(Math.pow(e,l)-1)/(Math.pow(e,s)-1)}let Ai={color:Ve.interpolate,number:Rr,padding:ei.interpolate,numberArray:ft.interpolate,colorArray:ke.interpolate,variableAnchorOffsetCollection:ci.interpolate,array:jn};class Ao{constructor(e,i){this.type=e,this.args=i}static parse(e,i){if(e.length<2)return i.error("Expected at least one argument.");let o=null,s=i.expectedType;s&&s.kind!=="value"&&(o=s);let l=[];for(let d of e.slice(1)){let g=i.parse(d,1+l.length,o,void 0,{typeAnnotation:"omit"});if(!g)return null;o=o||g.type,l.push(g)}if(!o)throw new Error("No output type");let h=s&&l.some((d=>Nn(s,d.type)));return new Ao(h?Oe:o,l)}evaluate(e){let i,o=null,s=0;for(let l of this.args)if(s++,o=l.evaluate(e),o&&o instanceof Ci&&!o.available&&(i||(i=o.name),o=null,s===this.args.length&&(o=i)),o!==null)break;return o}eachChild(e){this.args.forEach(e)}outputDefined(){return this.args.every((e=>e.outputDefined()))}}function Do(r,e){return r==="=="||r==="!="?e.kind==="boolean"||e.kind==="string"||e.kind==="number"||e.kind==="null"||e.kind==="value":e.kind==="string"||e.kind==="number"||e.kind==="value"}function Lt(r,e,i,o){return o.compare(e,i)===0}function un(r,e,i){let o=r!=="=="&&r!=="!=";return class Zf{constructor(l,h,d){this.type=je,this.lhs=l,this.rhs=h,this.collator=d,this.hasUntypedArgument=l.type.kind==="value"||h.type.kind==="value"}static parse(l,h){if(l.length!==3&&l.length!==4)return h.error("Expected two or three arguments.");let d=l[0],g=h.parse(l[1],1,Oe);if(!g)return null;if(!Do(d,g.type))return h.concat(1).error(`"${d}" comparisons are not supported for type '${rt(g.type)}'.`);let m=h.parse(l[2],2,Oe);if(!m)return null;if(!Do(d,m.type))return h.concat(2).error(`"${d}" comparisons are not supported for type '${rt(m.type)}'.`);if(g.type.kind!==m.type.kind&&g.type.kind!=="value"&&m.type.kind!=="value")return h.error(`Cannot compare types '${rt(g.type)}' and '${rt(m.type)}'.`);o&&(g.type.kind==="value"&&m.type.kind!=="value"?g=new bi(m.type,[g]):g.type.kind!=="value"&&m.type.kind==="value"&&(m=new bi(g.type,[m])));let v=null;if(l.length===4){if(g.type.kind!=="string"&&m.type.kind!=="string"&&g.type.kind!=="value"&&m.type.kind!=="value")return h.error("Cannot use collator to compare non-string types.");if(v=h.parse(l[3],3,wo),!v)return null}return new Zf(g,m,v)}evaluate(l){let h=this.lhs.evaluate(l),d=this.rhs.evaluate(l);if(o&&this.hasUntypedArgument){let g=St(h),m=St(d);if(g.kind!==m.kind||g.kind!=="string"&&g.kind!=="number")throw new at(`Expected arguments for "${r}" to be (string, string) or (number, number), but found (${g.kind}, ${m.kind}) instead.`)}if(this.collator&&!o&&this.hasUntypedArgument){let g=St(h),m=St(d);if(g.kind!=="string"||m.kind!=="string")return e(l,h,d)}return this.collator?i(l,h,d,this.collator.evaluate(l)):e(l,h,d)}eachChild(l){l(this.lhs),l(this.rhs),this.collator&&l(this.collator)}outputDefined(){return!0}}}let Ya=un("==",(function(r,e,i){return e===i}),Lt),yc=un("!=",(function(r,e,i){return e!==i}),(function(r,e,i,o){return!Lt(0,e,i,o)})),Nh=un("<",(function(r,e,i){return e",(function(r,e,i){return e>i}),(function(r,e,i,o){return o.compare(e,i)>0})),Ps=un("<=",(function(r,e,i){return e<=i}),(function(r,e,i,o){return o.compare(e,i)<=0})),Ka=un(">=",(function(r,e,i){return e>=i}),(function(r,e,i,o){return o.compare(e,i)>=0}));class Ss{constructor(e,i,o){this.type=wo,this.locale=o,this.caseSensitive=e,this.diacriticSensitive=i}static parse(e,i){if(e.length!==2)return i.error("Expected one argument.");let o=e[1];if(typeof o!="object"||Array.isArray(o))return i.error("Collator options argument must be an object.");let s=i.parse(o["case-sensitive"]!==void 0&&o["case-sensitive"],1,je);if(!s)return null;let l=i.parse(o["diacritic-sensitive"]!==void 0&&o["diacritic-sensitive"],1,je);if(!l)return null;let h=null;return o.locale&&(h=i.parse(o.locale,1,Fe),!h)?null:new Ss(s,l,h)}evaluate(e){return new qa(this.caseSensitive.evaluate(e),this.diacriticSensitive.evaluate(e),this.locale?this.locale.evaluate(e):null)}eachChild(e){e(this.caseSensitive),e(this.diacriticSensitive),this.locale&&e(this.locale)}outputDefined(){return!1}}class Is{constructor(e,i,o,s,l,h){this.type=Fe,this.number=e,this.locale=i,this.currency=o,this.unit=s,this.minFractionDigits=l,this.maxFractionDigits=h}static parse(e,i){if(e.length!==3)return i.error("Expected two arguments.");let o=i.parse(e[1],1,be);if(!o)return null;let s=e[2];if(typeof s!="object"||Array.isArray(s))return i.error("NumberFormat options argument must be an object.");let l=null;if(s.locale&&(l=i.parse(s.locale,1,Fe),!l))return null;let h=null;if(s.currency&&(h=i.parse(s.currency,1,Fe),!h))return null;let d=null;if(s.unit&&(d=i.parse(s.unit,1,Fe),!d))return null;if(h&&d)return i.error("NumberFormat options `currency` and `unit` are mutually exclusive");let g=null;if(s["min-fraction-digits"]&&(g=i.parse(s["min-fraction-digits"],1,be),!g))return null;let m=null;return s["max-fraction-digits"]&&(m=i.parse(s["max-fraction-digits"],1,be),!m)?null:new Is(o,l,h,d,g,m)}evaluate(e){return new Intl.NumberFormat(this.locale?this.locale.evaluate(e):[],{style:this.currency?"currency":this.unit?"unit":"decimal",currency:this.currency?this.currency.evaluate(e):void 0,unit:this.unit?this.unit.evaluate(e):void 0,minimumFractionDigits:this.minFractionDigits?this.minFractionDigits.evaluate(e):void 0,maximumFractionDigits:this.maxFractionDigits?this.maxFractionDigits.evaluate(e):void 0}).format(this.number.evaluate(e))}eachChild(e){e(this.number),this.locale&&e(this.locale),this.currency&&e(this.currency),this.unit&&e(this.unit),this.minFractionDigits&&e(this.minFractionDigits),this.maxFractionDigits&&e(this.maxFractionDigits)}outputDefined(){return!1}}class dn{constructor(e){this.type=To,this.sections=e}static parse(e,i){if(e.length<2)return i.error("Expected at least one argument.");let o=e[1];if(!Array.isArray(o)&&typeof o=="object")return i.error("First argument must be an image or text section.");let s=[],l=!1;for(let h=1;h<=e.length-1;++h){let d=e[h];if(l&&typeof d=="object"&&!Array.isArray(d)){l=!1;let g=null;if(d["font-scale"]&&(g=i.parse(d["font-scale"],1,be),!g))return null;let m=null;if(d["text-font"]&&(m=i.parse(d["text-font"],1,Yt(Fe)),!m))return null;let v=null;if(d["text-color"]&&(v=i.parse(d["text-color"],1,Ei),!v))return null;let _=null;if(d["vertical-align"]){if(typeof d["vertical-align"]=="string"&&!Oh.includes(d["vertical-align"]))return i.error(`'vertical-align' must be one of: 'bottom', 'center', 'top' but found '${d["vertical-align"]}' instead.`);if(_=i.parse(d["vertical-align"],1,Fe),!_)return null}let T=s[s.length-1];T.scale=g,T.font=m,T.textColor=v,T.verticalAlign=_}else{let g=i.parse(e[h],1,Oe);if(!g)return null;let m=g.type.kind;if(m!=="string"&&m!=="value"&&m!=="null"&&m!=="resolvedImage")return i.error("Formatted text type must be 'string', 'value', 'image' or 'null'.");l=!0,s.push({content:g,scale:null,font:null,textColor:null,verticalAlign:null})}}return new dn(s)}evaluate(e){return new xi(this.sections.map((i=>{let o=i.content.evaluate(e);return St(o)===On?new Wa("",o,null,null,null,i.verticalAlign?i.verticalAlign.evaluate(e):null):new Wa(an(o),null,i.scale?i.scale.evaluate(e):null,i.font?i.font.evaluate(e).join(","):null,i.textColor?i.textColor.evaluate(e):null,i.verticalAlign?i.verticalAlign.evaluate(e):null)})))}eachChild(e){for(let i of this.sections)e(i.content),i.scale&&e(i.scale),i.font&&e(i.font),i.textColor&&e(i.textColor),i.verticalAlign&&e(i.verticalAlign)}outputDefined(){return!1}}class Hn{constructor(e){this.type=On,this.input=e}static parse(e,i){if(e.length!==2)return i.error("Expected two arguments.");let o=i.parse(e[1],1,Fe);return o?new Hn(o):i.error("No image name provided.")}evaluate(e){let i=this.input.evaluate(e),o=Ci.fromString(i);return o&&e.availableImages&&(o.available=e.availableImages.indexOf(i)>-1),o}eachChild(e){e(this.input)}outputDefined(){return!1}}class Di{constructor(e){this.type=be,this.input=e}static parse(e,i){if(e.length!==2)return i.error(`Expected 1 argument, but found ${e.length-1} instead.`);let o=i.parse(e[1],1);return o?o.type.kind!=="array"&&o.type.kind!=="string"&&o.type.kind!=="value"?i.error(`Expected argument of type string or array, but found ${rt(o.type)} instead.`):new Di(o):null}evaluate(e){let i=this.input.evaluate(e);if(typeof i=="string")return[...i].length;if(Array.isArray(i))return i.length;throw new at(`Expected value to be of type string or array, but found ${rt(St(i))} instead.`)}eachChild(e){e(this.input)}outputDefined(){return!1}}let Ki=8192;function Ms(r,e){let i=(180+r[0])/360,o=(180-180/Math.PI*Math.log(Math.tan(Math.PI/4+r[1]*Math.PI/360)))/360,s=Math.pow(2,e.z);return[Math.round(i*s*Ki),Math.round(o*s*Ki)]}function Ja(r,e){let i=Math.pow(2,e.z);return[(s=(r[0]/Ki+e.x)/i,360*s-180),(o=(r[1]/Ki+e.y)/i,360/Math.PI*Math.atan(Math.exp((180-360*o)*Math.PI/180))-90)];var o,s}function pn(r,e){r[0]=Math.min(r[0],e[0]),r[1]=Math.min(r[1],e[1]),r[2]=Math.max(r[2],e[0]),r[3]=Math.max(r[3],e[1])}function zo(r,e){return!(r[0]<=e[0]||r[2]>=e[2]||r[1]<=e[1]||r[3]>=e[3])}function Vh(r,e,i){let o=r[0]-e[0],s=r[1]-e[1],l=r[0]-i[0],h=r[1]-i[1];return o*h-l*s==0&&o*l<=0&&s*h<=0}function Es(r,e,i,o){return(s=[o[0]-i[0],o[1]-i[1]])[0]*(l=[e[0]-r[0],e[1]-r[1]])[1]-s[1]*l[0]!=0&&!(!xc(r,e,i,o)||!xc(i,o,r,e));var s,l}function jh(r,e,i){for(let o of i)for(let s=0;s(s=r)[1]!=(h=d[g+1])[1]>s[1]&&s[0]<(h[0]-l[0])*(s[1]-l[1])/(h[1]-l[1])+l[0]&&(o=!o)}var s,l,h;return o}function Uh(r,e){for(let i of e)if(pr(r,i))return!0;return!1}function Qa(r,e){for(let i of r)if(!pr(i,e))return!1;for(let i=0;i0&&d<0||h<0&&d>0}function Cs(r,e,i){let o=[];for(let s=0;si[2]){let s=.5*o,l=r[0]-i[0]>s?-o:i[0]-r[0]>s?o:0;l===0&&(l=r[0]-i[2]>s?-o:i[2]-r[0]>s?o:0),r[0]+=l}pn(e,r)}function Tc(r,e,i,o){let s=Math.pow(2,o.z)*Ki,l=[o.x*Ki,o.y*Ki],h=[];for(let d of r)for(let g of d){let m=[g.x+l[0],g.y+l[1]];wc(m,e,i,s),h.push(m)}return h}function Pc(r,e,i,o){let s=Math.pow(2,o.z)*Ki,l=[o.x*Ki,o.y*Ki],h=[];for(let g of r){let m=[];for(let v of g){let _=[v.x+l[0],v.y+l[1]];pn(e,_),m.push(_)}h.push(m)}if(e[2]-e[0]<=s/2){(d=e)[0]=d[1]=1/0,d[2]=d[3]=-1/0;for(let g of h)for(let m of g)wc(m,e,i,s)}var d;return h}class fn{constructor(e,i){this.type=je,this.geojson=e,this.geometries=i}static parse(e,i){if(e.length!==2)return i.error(`'within' expression requires exactly one argument, but found ${e.length-1} instead.`);if(Lr(e[1])){let o=e[1];if(o.type==="FeatureCollection"){let s=[];for(let l of o.features){let{type:h,coordinates:d}=l.geometry;h==="Polygon"&&s.push(d),h==="MultiPolygon"&&s.push(...d)}if(s.length)return new fn(o,{type:"MultiPolygon",coordinates:s})}else if(o.type==="Feature"){let s=o.geometry.type;if(s==="Polygon"||s==="MultiPolygon")return new fn(o,o.geometry)}else if(o.type==="Polygon"||o.type==="MultiPolygon")return new fn(o,o)}return i.error("'within' expression requires valid geojson object that contains polygon geometry type.")}evaluate(e){if(e.geometry()!=null&&e.canonicalID()!=null){if(e.geometryType()==="Point")return(function(i,o){let s=[1/0,1/0,-1/0,-1/0],l=[1/0,1/0,-1/0,-1/0],h=i.canonicalID();if(o.type==="Polygon"){let d=Cs(o.coordinates,l,h),g=Tc(i.geometry(),s,l,h);if(!zo(s,l))return!1;for(let m of g)if(!pr(m,d))return!1}if(o.type==="MultiPolygon"){let d=bc(o.coordinates,l,h),g=Tc(i.geometry(),s,l,h);if(!zo(s,l))return!1;for(let m of g)if(!Uh(m,d))return!1}return!0})(e,this.geometries);if(e.geometryType()==="LineString")return(function(i,o){let s=[1/0,1/0,-1/0,-1/0],l=[1/0,1/0,-1/0,-1/0],h=i.canonicalID();if(o.type==="Polygon"){let d=Cs(o.coordinates,l,h),g=Pc(i.geometry(),s,l,h);if(!zo(s,l))return!1;for(let m of g)if(!Qa(m,d))return!1}if(o.type==="MultiPolygon"){let d=bc(o.coordinates,l,h),g=Pc(i.geometry(),s,l,h);if(!zo(s,l))return!1;for(let m of g)if(!vc(m,d))return!1}return!0})(e,this.geometries)}return!1}eachChild(){}outputDefined(){return!0}}let el=class{constructor(r=[],e=(i,o)=>io?1:0){if(this.data=r,this.length=this.data.length,this.compare=e,this.length>0)for(let i=(this.length>>1)-1;i>=0;i--)this._down(i)}push(r){this.data.push(r),this._up(this.length++)}pop(){if(this.length===0)return;let r=this.data[0],e=this.data.pop();return--this.length>0&&(this.data[0]=e,this._down(0)),r}peek(){return this.data[0]}_up(r){let{data:e,compare:i}=this,o=e[r];for(;r>0;){let s=r-1>>1,l=e[s];if(i(o,l)>=0)break;e[r]=l,r=s}e[r]=o}_down(r){let{data:e,compare:i}=this,o=this.length>>1,s=e[r];for(;r=0)break;e[r]=e[l],r=l}e[r]=s}};function tl(r,e,i=0,o=r.length-1,s=Gh){for(;o>i;){if(o-i>600){let g=o-i+1,m=e-i+1,v=Math.log(g),_=.5*Math.exp(2*v/3),T=.5*Math.sqrt(v*_*(g-_)/g)*(m-g/2<0?-1:1);tl(r,e,Math.max(i,Math.floor(e-m*_/g+T)),Math.min(o,Math.floor(e+(g-m)*_/g+T)),s)}let l=r[e],h=i,d=o;for(Xn(r,i,e),s(r[o],l)>0&&Xn(r,i,o);h0;)d--}s(r[i],l)===0?Xn(r,i,d):(d++,Xn(r,d,o)),d<=e&&(i=d+1),e<=d&&(o=d-1)}}function Xn(r,e,i){let o=r[e];r[e]=r[i],r[i]=o}function Gh(r,e){return re?1:0}function As(r,e){if(r.length<=1)return[r];let i=[],o,s;for(let l of r){let h=Zh(l);h!==0&&(l.area=Math.abs(h),s===void 0&&(s=h<0),s===h<0?(o&&i.push(o),o=[l]):o.push(l))}if(o&&i.push(o),e>1)for(let l=0;l1?(m=e[g+1][0],v=e[g+1][1]):b>0&&(m+=_/this.kx*b,v+=T/this.ky*b)),_=this.wrap(i[0]-m)*this.kx,T=(i[1]-v)*this.ky;let I=_*_+T*T;I180;)e-=360;return e}}function Mc(r,e){return e[0]-r[0]}function Yn(r){return r[1]-r[0]+1}function rr(r,e){return r[1]>=r[0]&&r[1]r[1])return[null,null];let i=Yn(r);if(e){if(i===2)return[r,null];let s=Math.floor(i/2);return[[r[0],r[0]+s],[r[0]+s,r[1]]]}if(i===1)return[r,null];let o=Math.floor(i/2)-1;return[[r[0],r[0]+o],[r[0]+o+1,r[1]]]}function nl(r,e){if(!rr(e,r.length))return[1/0,1/0,-1/0,-1/0];let i=[1/0,1/0,-1/0,-1/0];for(let o=e[0];o<=e[1];++o)pn(i,r[o]);return i}function Ds(r){let e=[1/0,1/0,-1/0,-1/0];for(let i of r)for(let o of i)pn(e,o);return e}function ol(r){return r[0]!==-1/0&&r[1]!==-1/0&&r[2]!==1/0&&r[3]!==1/0}function sl(r,e,i){if(!ol(r)||!ol(e))return NaN;let o=0,s=0;return r[2]e[2]&&(o=r[0]-e[2]),r[1]>e[3]&&(s=r[1]-e[3]),r[3]=o)return o;if(zo(s,l)){if(Cc(r,e))return 0}else if(Cc(e,r))return 0;let h=1/0;for(let d of r)for(let g=0,m=d.length,v=m-1;g0;){let g=h.pop();if(g[0]>=l)continue;let m=g[1],v=e?50:100;if(Yn(m)<=v){if(!rr(m,r.length))return NaN;if(e){let _=Hh(r,m,i,o);if(isNaN(_)||_===0)return _;l=Math.min(l,_)}else for(let _=m[0];_<=m[1];++_){let T=Wh(r[_],i,o);if(l=Math.min(l,T),l===0)return 0}}else{let _=rl(m,e);Ac(h,l,o,r,d,_[0]),Ac(h,l,o,r,d,_[1])}}return l}function ks(r,e,i,o,s,l=1/0){let h=Math.min(l,s.distance(r[0],i[0]));if(h===0)return h;let d=new el([[0,[0,r.length-1],[0,i.length-1]]],Mc);for(;d.length>0;){let g=d.pop();if(g[0]>=h)continue;let m=g[1],v=g[2],_=e?50:100,T=o?50:100;if(Yn(m)<=_&&Yn(v)<=T){if(!rr(m,r.length)&&rr(v,i.length))return NaN;let b;if(e&&o)b=Ec(r,m,i,v,s),h=Math.min(h,b);else if(e&&!o){let I=r.slice(m[0],m[1]+1);for(let M=v[0];M<=v[1];++M)if(b=mn(i[M],I,s),h=Math.min(h,b),h===0)return h}else if(!e&&o){let I=i.slice(v[0],v[1]+1);for(let M=m[0];M<=m[1];++M)if(b=mn(r[M],I,s),h=Math.min(h,b),h===0)return h}else b=qh(r,m,i,v,s),h=Math.min(h,b)}else{let b=rl(m,e),I=rl(v,o);zs(d,h,s,r,i,b[0],I[0]),zs(d,h,s,r,i,b[0],I[1]),zs(d,h,s,r,i,b[1],I[0]),zs(d,h,s,r,i,b[1],I[1])}}return h}function ll(r){return r.type==="MultiPolygon"?r.coordinates.map((e=>({type:"Polygon",coordinates:e}))):r.type==="MultiLineString"?r.coordinates.map((e=>({type:"LineString",coordinates:e}))):r.type==="MultiPoint"?r.coordinates.map((e=>({type:"Point",coordinates:e}))):[r]}class gn{constructor(e,i){this.type=be,this.geojson=e,this.geometries=i}static parse(e,i){if(e.length!==2)return i.error(`'distance' expression requires exactly one argument, but found ${e.length-1} instead.`);if(Lr(e[1])){let o=e[1];if(o.type==="FeatureCollection")return new gn(o,o.features.map((s=>ll(s.geometry))).flat());if(o.type==="Feature")return new gn(o,ll(o.geometry));if("type"in o&&"coordinates"in o)return new gn(o,ll(o))}return i.error("'distance' expression requires valid geojson object that contains polygon geometry type.")}evaluate(e){if(e.geometry()!=null&&e.canonicalID()!=null){if(e.geometryType()==="Point")return(function(i,o){let s=i.geometry(),l=s.flat().map((g=>Ja([g.x,g.y],i.canonical)));if(s.length===0)return NaN;let h=new il(l[0][1]),d=1/0;for(let g of o){switch(g.type){case"Point":d=Math.min(d,ks(l,!1,[g.coordinates],!1,h,d));break;case"LineString":d=Math.min(d,ks(l,!1,g.coordinates,!0,h,d));break;case"Polygon":d=Math.min(d,Rs(l,!1,g.coordinates,h,d))}if(d===0)return d}return d})(e,this.geometries);if(e.geometryType()==="LineString")return(function(i,o){let s=i.geometry(),l=s.flat().map((g=>Ja([g.x,g.y],i.canonical)));if(s.length===0)return NaN;let h=new il(l[0][1]),d=1/0;for(let g of o){switch(g.type){case"Point":d=Math.min(d,ks(l,!0,[g.coordinates],!1,h,d));break;case"LineString":d=Math.min(d,ks(l,!0,g.coordinates,!0,h,d));break;case"Polygon":d=Math.min(d,Rs(l,!0,g.coordinates,h,d))}if(d===0)return d}return d})(e,this.geometries);if(e.geometryType()==="Polygon")return(function(i,o){let s=i.geometry();if(s.length===0||s[0].length===0)return NaN;let l=As(s,0).map((g=>g.map((m=>m.map((v=>Ja([v.x,v.y],i.canonical))))))),h=new il(l[0][0][0][1]),d=1/0;for(let g of o)for(let m of l){switch(g.type){case"Point":d=Math.min(d,Rs([g.coordinates],!1,m,h,d));break;case"LineString":d=Math.min(d,Rs(g.coordinates,!0,m,h,d));break;case"Polygon":d=Math.min(d,et(m,g.coordinates,h,d))}if(d===0)return d}return d})(e,this.geometries)}return NaN}eachChild(){}outputDefined(){return!0}}class ko{constructor(e){this.type=Oe,this.key=e}static parse(e,i){if(e.length!==2)return i.error(`Expected 1 argument, but found ${e.length-1} instead.`);let o=e[1];return o==null?i.error("Global state property must be defined."):typeof o!="string"?i.error(`Global state property must be string, but found ${typeof e[1]} instead.`):new ko(o)}evaluate(e){var i;let o=(i=e.globals)===null||i===void 0?void 0:i.globalState;return o&&Object.keys(o).length!==0?Eo(o,this.key):null}eachChild(){}outputDefined(){return!1}}let Kn={"==":Ya,"!=":yc,">":Wn,"<":Nh,">=":Ka,"<=":Ps,array:bi,at:qe,boolean:bi,case:Yi,coalesce:Ao,collator:Ss,format:dn,image:Hn,in:Ne,"index-of":$n,interpolate:Et,"interpolate-hcl":Et,"interpolate-lab":Et,length:Di,let:lt,literal:ir,match:He,number:bi,"number-format":Is,object:bi,slice:Zn,step:qn,string:bi,"to-boolean":dr,"to-color":dr,"to-number":dr,"to-string":dr,var:Gn,within:fn,distance:gn,"global-state":ko};class Vi{constructor(e,i,o,s){this.name=e,this.type=i,this._evaluate=o,this.args=s}evaluate(e){return this._evaluate(e,this.args)}eachChild(e){this.args.forEach(e)}outputDefined(){return!1}static parse(e,i){let o=e[0],s=Vi.definitions[o];if(!s)return i.error(`Unknown expression "${o}". If you wanted a literal array, use ["literal", [...]].`,0);let l=Array.isArray(s)?s[0]:s.type,h=Array.isArray(s)?[[s[1],s[2]]]:s.overloads,d=h.filter((([m])=>!Array.isArray(m)||m.length===e.length-1)),g=null;for(let[m,v]of d){g=new cn(i.registry,Ls,i.path,null,i.scope);let _=[],T=!1;for(let b=1;b{return T=_,Array.isArray(T)?`(${T.map(rt).join(", ")})`:`(${rt(T.type)}...)`;var T})).join(" | "),v=[];for(let _=1;_{i=e?i&&Ls(o):i&&o instanceof ir})),!!i&&Fs(r)&&Bs(r,["zoom","heatmap-density","elevation","line-progress","accumulated","is-supported-script"])}function Fs(r){if(r instanceof Vi&&(r.name==="get"&&r.args.length===1||r.name==="feature-state"||r.name==="has"&&r.args.length===1||r.name==="properties"||r.name==="geometry-type"||r.name==="id"||/^filter-/.test(r.name))||r instanceof fn||r instanceof gn)return!1;let e=!0;return r.eachChild((i=>{e&&!Fs(i)&&(e=!1)})),e}function Lo(r){if(r instanceof Vi&&r.name==="feature-state")return!1;let e=!0;return r.eachChild((i=>{e&&!Lo(i)&&(e=!1)})),e}function Bs(r,e){if(r instanceof Vi&&e.indexOf(r.name)>=0)return!1;let i=!0;return r.eachChild((o=>{i&&!Bs(o,e)&&(i=!1)})),i}function Rc(r){return{result:"success",value:r}}function Jn(r){return{result:"error",value:r}}function Qn(r){return r["property-type"]==="data-driven"||r["property-type"]==="cross-faded-data-driven"}function kc(r){return!!r.expression&&r.expression.parameters.indexOf("zoom")>-1}function hl(r){return!!r.expression&&r.expression.interpolated}function Ue(r){return r instanceof Number?"number":r instanceof String?"string":r instanceof Boolean?"boolean":Array.isArray(r)?"array":r===null?"null":typeof r}function Os(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)&&St(r)===ur}function Xh(r){return r}function Lc(r,e){let i=r.stops&&typeof r.stops[0][0]=="object",o=i||!(i||r.property!==void 0),s=r.type||(hl(e)?"exponential":"interval"),l=(function(v){switch(v.type){case"color":return Ve.parse;case"padding":return ei.parse;case"numberArray":return ft.parse;case"colorArray":return ke.parse;default:return null}})(e);if(l&&((r=nn({},r)).stops&&(r.stops=r.stops.map((v=>[v[0],l(v[1])]))),r.default=l(r.default?r.default:e.default)),r.colorSpace&&(h=r.colorSpace)!=="rgb"&&h!=="hcl"&&h!=="lab")throw new Error(`Unknown color space: "${r.colorSpace}"`);var h;let d=(function(v){switch(v){case"exponential":return Fc;case"interval":return Kh;case"categorical":return Yh;case"identity":return Jh;default:throw new Error(`Unknown function type "${v}"`)}})(s),g,m;if(s==="categorical"){g=Object.create(null);for(let v of r.stops)g[v[0]]=v[1];m=typeof r.stops[0][0]}if(i){let v={},_=[];for(let I=0;II[0])),evaluate:({zoom:I},M)=>Fc({stops:T,base:r.base},e,I).evaluate(I,M)}}if(o){let v=s==="exponential"?{name:"exponential",base:r.base!==void 0?r.base:1}:null;return{kind:"camera",interpolationType:v,interpolationFactor:Et.interpolationFactor.bind(void 0,v),zoomStops:r.stops.map((_=>_[0])),evaluate:({zoom:_})=>d(r,e,_,g,m)}}return{kind:"source",evaluate(v,_){let T=_&&_.properties?_.properties[r.property]:void 0;return T===void 0?Fo(r.default,e.default):d(r,e,T,g,m)}}}function Fo(r,e,i){return r!==void 0?r:e!==void 0?e:i!==void 0?i:void 0}function Yh(r,e,i,o,s){return Fo(typeof i===s?o[i]:void 0,r.default,e.default)}function Kh(r,e,i){if(Ue(i)!=="number")return Fo(r.default,e.default);let o=r.stops.length;if(o===1||i<=r.stops[0][0])return r.stops[0][1];if(i>=r.stops[o-1][0])return r.stops[o-1][1];let s=hn(r.stops.map((l=>l[0])),i);return r.stops[s][1]}function Fc(r,e,i){let o=r.base!==void 0?r.base:1;if(Ue(i)!=="number")return Fo(r.default,e.default);let s=r.stops.length;if(s===1||i<=r.stops[0][0])return r.stops[0][1];if(i>=r.stops[s-1][0])return r.stops[s-1][1];let l=hn(r.stops.map((v=>v[0])),i),h=(function(v,_,T,b){let I=b-T,M=v-T;return I===0?0:_===1?M/I:(Math.pow(_,M)-1)/(Math.pow(_,I)-1)})(i,o,r.stops[l][0],r.stops[l+1][0]),d=r.stops[l][1],g=r.stops[l+1][1],m=Ai[e.type]||Xh;return typeof d.evaluate=="function"?{evaluate(...v){let _=d.evaluate.apply(void 0,v),T=g.evaluate.apply(void 0,v);if(_!==void 0&&T!==void 0)return m(_,T,h,r.colorSpace)}}:m(d,g,h,r.colorSpace)}function Jh(r,e,i){switch(e.type){case"color":i=Ve.parse(i);break;case"formatted":i=xi.fromString(i.toString());break;case"resolvedImage":i=Ci.fromString(i.toString());break;case"padding":i=ei.parse(i);break;case"colorArray":i=ke.parse(i);break;case"numberArray":i=ft.parse(i);break;default:Ue(i)===e.type||e.type==="enum"&&e.values[i]||(i=void 0)}return Fo(i,r.default,e.default)}Vi.register(Kn,{error:[{kind:"error"},[Fe],(r,[e])=>{throw new at(e.evaluate(r))}],typeof:[Fe,[Oe],(r,[e])=>rt(St(e.evaluate(r)))],"to-rgba":[Yt(be,4),[Ei],(r,[e])=>{let[i,o,s,l]=e.evaluate(r).rgb;return[255*i,255*o,255*s,l]}],rgb:[Ei,[be,be,be],Dc],rgba:[Ei,[be,be,be,be],Dc],has:{type:je,overloads:[[[Fe],(r,[e])=>zc(e.evaluate(r),r.properties())],[[Fe,ur],(r,[e,i])=>zc(e.evaluate(r),i.evaluate(r))]]},get:{type:Oe,overloads:[[[Fe],(r,[e])=>cl(e.evaluate(r),r.properties())],[[Fe,ur],(r,[e,i])=>cl(e.evaluate(r),i.evaluate(r))]]},"feature-state":[Oe,[Fe],(r,[e])=>cl(e.evaluate(r),r.featureState||{})],properties:[ur,[],r=>r.properties()],"geometry-type":[Fe,[],r=>r.geometryType()],id:[Oe,[],r=>r.id()],zoom:[be,[],r=>r.globals.zoom],"heatmap-density":[be,[],r=>r.globals.heatmapDensity||0],elevation:[be,[],r=>r.globals.elevation||0],"line-progress":[be,[],r=>r.globals.lineProgress||0],accumulated:[Oe,[],r=>r.globals.accumulated===void 0?null:r.globals.accumulated],"+":[be,_n(be),(r,e)=>{let i=0;for(let o of e)i+=o.evaluate(r);return i}],"*":[be,_n(be),(r,e)=>{let i=1;for(let o of e)i*=o.evaluate(r);return i}],"-":{type:be,overloads:[[[be,be],(r,[e,i])=>e.evaluate(r)-i.evaluate(r)],[[be],(r,[e])=>-e.evaluate(r)]]},"/":[be,[be,be],(r,[e,i])=>e.evaluate(r)/i.evaluate(r)],"%":[be,[be,be],(r,[e,i])=>e.evaluate(r)%i.evaluate(r)],ln2:[be,[],()=>Math.LN2],pi:[be,[],()=>Math.PI],e:[be,[],()=>Math.E],"^":[be,[be,be],(r,[e,i])=>Math.pow(e.evaluate(r),i.evaluate(r))],sqrt:[be,[be],(r,[e])=>Math.sqrt(e.evaluate(r))],log10:[be,[be],(r,[e])=>Math.log(e.evaluate(r))/Math.LN10],ln:[be,[be],(r,[e])=>Math.log(e.evaluate(r))],log2:[be,[be],(r,[e])=>Math.log(e.evaluate(r))/Math.LN2],sin:[be,[be],(r,[e])=>Math.sin(e.evaluate(r))],cos:[be,[be],(r,[e])=>Math.cos(e.evaluate(r))],tan:[be,[be],(r,[e])=>Math.tan(e.evaluate(r))],asin:[be,[be],(r,[e])=>Math.asin(e.evaluate(r))],acos:[be,[be],(r,[e])=>Math.acos(e.evaluate(r))],atan:[be,[be],(r,[e])=>Math.atan(e.evaluate(r))],min:[be,_n(be),(r,e)=>Math.min(...e.map((i=>i.evaluate(r))))],max:[be,_n(be),(r,e)=>Math.max(...e.map((i=>i.evaluate(r))))],abs:[be,[be],(r,[e])=>Math.abs(e.evaluate(r))],round:[be,[be],(r,[e])=>{let i=e.evaluate(r);return i<0?-Math.round(-i):Math.round(i)}],floor:[be,[be],(r,[e])=>Math.floor(e.evaluate(r))],ceil:[be,[be],(r,[e])=>Math.ceil(e.evaluate(r))],"filter-==":[je,[Fe,Oe],(r,[e,i])=>r.properties()[e.value]===i.value],"filter-id-==":[je,[Oe],(r,[e])=>r.id()===e.value],"filter-type-==":[je,[Fe],(r,[e])=>r.geometryType()===e.value],"filter-<":[je,[Fe,Oe],(r,[e,i])=>{let o=r.properties()[e.value],s=i.value;return typeof o==typeof s&&o{let i=r.id(),o=e.value;return typeof i==typeof o&&i":[je,[Fe,Oe],(r,[e,i])=>{let o=r.properties()[e.value],s=i.value;return typeof o==typeof s&&o>s}],"filter-id->":[je,[Oe],(r,[e])=>{let i=r.id(),o=e.value;return typeof i==typeof o&&i>o}],"filter-<=":[je,[Fe,Oe],(r,[e,i])=>{let o=r.properties()[e.value],s=i.value;return typeof o==typeof s&&o<=s}],"filter-id-<=":[je,[Oe],(r,[e])=>{let i=r.id(),o=e.value;return typeof i==typeof o&&i<=o}],"filter->=":[je,[Fe,Oe],(r,[e,i])=>{let o=r.properties()[e.value],s=i.value;return typeof o==typeof s&&o>=s}],"filter-id->=":[je,[Oe],(r,[e])=>{let i=r.id(),o=e.value;return typeof i==typeof o&&i>=o}],"filter-has":[je,[Oe],(r,[e])=>e.value in r.properties()],"filter-has-id":[je,[],r=>r.id()!==null&&r.id()!==void 0],"filter-type-in":[je,[Yt(Fe)],(r,[e])=>e.value.indexOf(r.geometryType())>=0],"filter-id-in":[je,[Yt(Oe)],(r,[e])=>e.value.indexOf(r.id())>=0],"filter-in-small":[je,[Fe,Yt(Oe)],(r,[e,i])=>i.value.indexOf(r.properties()[e.value])>=0],"filter-in-large":[je,[Fe,Yt(Oe)],(r,[e,i])=>(function(o,s,l,h){for(;l<=h;){let d=l+h>>1;if(s[d]===o)return!0;s[d]>o?h=d-1:l=d+1}return!1})(r.properties()[e.value],i.value,0,i.value.length-1)],all:{type:je,overloads:[[[je,je],(r,[e,i])=>e.evaluate(r)&&i.evaluate(r)],[_n(je),(r,e)=>{for(let i of e)if(!i.evaluate(r))return!1;return!0}]]},any:{type:je,overloads:[[[je,je],(r,[e,i])=>e.evaluate(r)||i.evaluate(r)],[_n(je),(r,e)=>{for(let i of e)if(i.evaluate(r))return!0;return!1}]]},"!":[je,[je],(r,[e])=>!e.evaluate(r)],"is-supported-script":[je,[Fe],(r,[e])=>{let i=r.globals&&r.globals.isSupportedScript;return!i||i(e.evaluate(r))}],upcase:[Fe,[Fe],(r,[e])=>e.evaluate(r).toUpperCase()],downcase:[Fe,[Fe],(r,[e])=>e.evaluate(r).toLowerCase()],concat:[Fe,_n(Oe),(r,e)=>e.map((i=>an(i.evaluate(r)))).join("")],split:[Yt(Fe),[Fe,Fe],(r,[e,i])=>e.evaluate(r).split(i.evaluate(r))],join:[Fe,[Yt(Fe),Fe],(r,[e,i])=>e.evaluate(r).join(i.evaluate(r))],"resolved-locale":[Fe,[wo],(r,[e])=>e.evaluate(r).resolvedLocale()]});class Bo{constructor(e,i,o){this.expression=e,this._warningHistory={},this._evaluator=new Ha,this._defaultValue=i?(function(s){if(s.type==="color"&&Os(s.default))return new Ve(0,0,0,0);switch(s.type){case"color":return Ve.parse(s.default)||null;case"padding":return ei.parse(s.default)||null;case"numberArray":return ft.parse(s.default)||null;case"colorArray":return ke.parse(s.default)||null;case"variableAnchorOffsetCollection":return ci.parse(s.default)||null;case"projectionDefinition":return hi.parse(s.default)||null;default:return s.default===void 0?null:s.default}})(i):null,this._enumValues=i&&i.type==="enum"?i.values:null,this._globalState=o}evaluateWithoutErrorHandling(e,i,o,s,l,h){return this._globalState&&(e=to(e,this._globalState)),this._evaluator.globals=e,this._evaluator.feature=i,this._evaluator.featureState=o,this._evaluator.canonical=s,this._evaluator.availableImages=l||null,this._evaluator.formattedSection=h,this.expression.evaluate(this._evaluator)}evaluate(e,i,o,s,l,h){this._globalState&&(e=to(e,this._globalState)),this._evaluator.globals=e,this._evaluator.feature=i||null,this._evaluator.featureState=o||null,this._evaluator.canonical=s,this._evaluator.availableImages=l||null,this._evaluator.formattedSection=h||null;try{let d=this.expression.evaluate(this._evaluator);if(d==null||typeof d=="number"&&d!=d)return this._defaultValue;if(this._enumValues&&!(d in this._enumValues))throw new at(`Expected value to be one of ${Object.keys(this._enumValues).map((g=>JSON.stringify(g))).join(", ")}, but found ${JSON.stringify(d)} instead.`);return d}catch(d){return this._warningHistory[d.message]||(this._warningHistory[d.message]=!0,typeof console<"u"&&console.warn(d.message)),this._defaultValue}}}function Ns(r){return Array.isArray(r)&&r.length>0&&typeof r[0]=="string"&&r[0]in Kn}function Oo(r,e,i){let o=new cn(Kn,Ls,[],e?(function(l){let h={color:Ei,string:Fe,number:be,enum:Fe,boolean:je,formatted:To,padding:_s,numberArray:Po,colorArray:Bn,projectionDefinition:gs,resolvedImage:On,variableAnchorOffsetCollection:So};return l.type==="array"?Yt(h[l.value]||Oe,l.length):h[l.type]})(e):void 0),s=o.parse(r,void 0,void 0,void 0,e&&e.type==="string"?{typeAnnotation:"coerce"}:void 0);return s?Rc(new Bo(s,e,i)):Jn(o.errors)}class Vs{constructor(e,i,o){this.kind=e,this._styleExpression=i,this.isStateDependent=e!=="constant"&&!Lo(i.expression),this.globalStateRefs=eo(i.expression),this._globalState=o}evaluateWithoutErrorHandling(e,i,o,s,l,h){return this._globalState&&(e=to(e,this._globalState)),this._styleExpression.evaluateWithoutErrorHandling(e,i,o,s,l,h)}evaluate(e,i,o,s,l,h){return this._globalState&&(e=to(e,this._globalState)),this._styleExpression.evaluate(e,i,o,s,l,h)}}class js{constructor(e,i,o,s,l){this.kind=e,this.zoomStops=o,this._styleExpression=i,this.isStateDependent=e!=="camera"&&!Lo(i.expression),this.globalStateRefs=eo(i.expression),this.interpolationType=s,this._globalState=l}evaluateWithoutErrorHandling(e,i,o,s,l,h){return this._globalState&&(e=to(e,this._globalState)),this._styleExpression.evaluateWithoutErrorHandling(e,i,o,s,l,h)}evaluate(e,i,o,s,l,h){return this._globalState&&(e=to(e,this._globalState)),this._styleExpression.evaluate(e,i,o,s,l,h)}interpolationFactor(e,i,o){return this.interpolationType?Et.interpolationFactor(this.interpolationType,e,i,o):0}}function Bc(r,e,i){let o=Oo(r,e,i);if(o.result==="error")return o;let s=o.value.expression,l=Fs(s);if(!l&&!Qn(e))return Jn([new Xt("","data expressions not supported")]);let h=Bs(s,["zoom"]);if(!h&&!kc(e))return Jn([new Xt("","zoom expressions not supported")]);let d=yn(s);return d||h?d instanceof Xt?Jn([d]):d instanceof Et&&!hl(e)?Jn([new Xt("",'"interpolate" expressions cannot be used with this property')]):Rc(d?new js(l?"camera":"composite",o.value,d.labels,d instanceof Et?d.interpolation:void 0,i):new Vs(l?"constant":"source",o.value,i)):Jn([new Xt("",'"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.')])}class Us{constructor(e,i){this._parameters=e,this._specification=i,nn(this,Lc(this._parameters,this._specification))}static deserialize(e){return new Us(e._parameters,e._specification)}static serialize(e){return{_parameters:e._parameters,_specification:e._specification}}}function yn(r){let e=null;if(r instanceof lt)e=yn(r.result);else if(r instanceof Ao){for(let i of r.args)if(e=yn(i),e)break}else(r instanceof qn||r instanceof Et)&&r.input instanceof Vi&&r.input.name==="zoom"&&(e=r);return e instanceof Xt||r.eachChild((i=>{let o=yn(i);o instanceof Xt?e=o:!e&&o?e=new Xt("",'"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.'):e&&o&&e!==o&&(e=new Xt("",'Only one zoom-based "step" or "interpolate" subexpression may be used in an expression.'))})),e}function eo(r,e=new Set){return r instanceof ko&&e.add(r.key),r.eachChild((i=>{eo(i,e)})),e}function to(r,e){let{zoom:i,heatmapDensity:o,elevation:s,lineProgress:l,isSupportedScript:h,accumulated:d}=r??{};return{zoom:i,heatmapDensity:o,elevation:s,lineProgress:l,isSupportedScript:h,accumulated:d,globalState:e}}function ul(r){if(r===!0||r===!1)return!0;if(!Array.isArray(r)||r.length===0)return!1;switch(r[0]){case"has":return r.length>=2&&r[1]!=="$id"&&r[1]!=="$type";case"in":return r.length>=3&&(typeof r[1]!="string"||Array.isArray(r[2]));case"!in":case"!has":case"none":return!1;case"==":case"!=":case">":case">=":case"<":case"<=":return r.length!==3||Array.isArray(r[1])||Array.isArray(r[2]);case"any":case"all":for(let e of r.slice(1))if(!ul(e)&&typeof e!="boolean")return!1;return!0;default:return!0}}let Qh={type:"boolean",default:!1,transition:!1,"property-type":"data-driven",expression:{interpolated:!1,parameters:["zoom","feature"]}};function No(r,e){if(r==null)return{filter:()=>!0,needGeometry:!1,getGlobalStateRefs:()=>new Set};ul(r)||(r=Vo(r));let i=Oo(r,Qh,e);if(i.result==="error")throw new Error(i.value.map((o=>`${o.key}: ${o.message}`)).join(", "));return{filter:(o,s,l)=>i.value.evaluate(o,s,{},l),needGeometry:dl(r),getGlobalStateRefs:()=>eo(i.value.expression)}}function eu(r,e){return re?1:0}function dl(r){if(!Array.isArray(r))return!1;if(r[0]==="within"||r[0]==="distance")return!0;for(let e=1;e"||e==="<="||e===">="?pl(r[1],r[2],e):e==="any"?(i=r.slice(1),["any"].concat(i.map(Vo))):e==="all"?["all"].concat(r.slice(1).map(Vo)):e==="none"?["all"].concat(r.slice(1).map(Vo).map(jo)):e==="in"?Oc(r[1],r.slice(2)):e==="!in"?jo(Oc(r[1],r.slice(2))):e==="has"?fl(r[1]):e!=="!has"||jo(fl(r[1]));var i}function pl(r,e,i){switch(r){case"$type":return[`filter-type-${i}`,e];case"$id":return[`filter-id-${i}`,e];default:return[`filter-${i}`,r,e]}}function Oc(r,e){if(e.length===0)return!1;switch(r){case"$type":return["filter-type-in",["literal",e]];case"$id":return["filter-id-in",["literal",e]];default:return e.length>200&&!e.some((i=>typeof i!=typeof e[0]))?["filter-in-large",r,["literal",e.sort(eu)]]:["filter-in-small",r,["literal",e]]}}function fl(r){switch(r){case"$type":return!0;case"$id":return["filter-has-id"];default:return["filter-has",r]}}function jo(r){return["!",r]}function Gs(r){let e=typeof r;if(e==="number"||e==="boolean"||e==="string"||r==null)return JSON.stringify(r);if(Array.isArray(r)){let s="[";for(let l of r)s+=`${Gs(l)},`;return`${s}]`}let i=Object.keys(r).sort(),o="{";for(let s=0;so.maximum?[new _e(e,i,`${i} is greater than the maximum value ${o.maximum}`)]:[]}function Zs(r){let e=r.valueSpec,i=It(r.value.type),o,s,l,h={},d=i!=="categorical"&&r.value.property===void 0,g=!d,m=Ue(r.value.stops)==="array"&&Ue(r.value.stops[0])==="array"&&Ue(r.value.stops[0][0])==="object",v=wi({key:r.key,value:r.value,valueSpec:r.styleSpec.function,validateSpec:r.validateSpec,style:r.style,styleSpec:r.styleSpec,objectElementValidators:{stops:function(b){if(i==="identity")return[new _e(b.key,b.value,'identity function may not have a "stops" property')];let I=[],M=b.value;return I=I.concat($s({key:b.key,value:M,valueSpec:b.valueSpec,validateSpec:b.validateSpec,style:b.style,styleSpec:b.styleSpec,arrayElementValidator:_})),Ue(M)==="array"&&M.length===0&&I.push(new _e(b.key,M,"array must have at least one stop")),I},default:function(b){return b.validateSpec({key:b.key,value:b.value,valueSpec:e,validateSpec:b.validateSpec,style:b.style,styleSpec:b.styleSpec})}}});return i==="identity"&&d&&v.push(new _e(r.key,r.value,'missing required property "property"')),i==="identity"||r.value.stops||v.push(new _e(r.key,r.value,'missing required property "stops"')),i==="exponential"&&r.valueSpec.expression&&!hl(r.valueSpec)&&v.push(new _e(r.key,r.value,"exponential functions not supported")),r.styleSpec.$version>=8&&(g&&!Qn(r.valueSpec)?v.push(new _e(r.key,r.value,"property functions not supported")):d&&!kc(r.valueSpec)&&v.push(new _e(r.key,r.value,"zoom functions not supported"))),i!=="categorical"&&!m||r.value.property!==void 0||v.push(new _e(r.key,r.value,'"property" property is required')),v;function _(b){let I=[],M=b.value,A=b.key;if(Ue(M)!=="array")return[new _e(A,M,`array expected, ${Ue(M)} found`)];if(M.length!==2)return[new _e(A,M,`array length 2 expected, length ${M.length} found`)];if(m){if(Ue(M[0])!=="object")return[new _e(A,M,`object expected, ${Ue(M[0])} found`)];if(M[0].zoom===void 0)return[new _e(A,M,"object stop key must have zoom")];if(M[0].value===void 0)return[new _e(A,M,"object stop key must have value")];if(l&&l>It(M[0].zoom))return[new _e(A,M[0].zoom,"stop zoom values must appear in ascending order")];It(M[0].zoom)!==l&&(l=It(M[0].zoom),s=void 0,h={}),I=I.concat(wi({key:`${A}[0]`,value:M[0],valueSpec:{zoom:{}},validateSpec:b.validateSpec,style:b.style,styleSpec:b.styleSpec,objectElementValidators:{zoom:io,value:T}}))}else I=I.concat(T({key:`${A}[0]`,value:M[0],validateSpec:b.validateSpec,style:b.style,styleSpec:b.styleSpec},M));return Ns(vn(M[1]))?I.concat([new _e(`${A}[1]`,M[1],"expressions are not allowed in function stops.")]):I.concat(b.validateSpec({key:`${A}[1]`,value:M[1],valueSpec:e,validateSpec:b.validateSpec,style:b.style,styleSpec:b.styleSpec}))}function T(b,I){let M=Ue(b.value),A=It(b.value),D=b.value!==null?b.value:I;if(o){if(M!==o)return[new _e(b.key,D,`${M} stop domain type must match previous stop domain type ${o}`)]}else o=M;if(M!=="number"&&M!=="string"&&M!=="boolean")return[new _e(b.key,D,"stop domain value must be a number, string, or boolean")];if(M!=="number"&&i!=="categorical"){let L=`number expected, ${M} found`;return Qn(e)&&i===void 0&&(L+='\nIf you intended to use a categorical function, specify `"type": "categorical"`.'),[new _e(b.key,D,L)]}return i!=="categorical"||M!=="number"||isFinite(A)&&Math.floor(A)===A?i!=="categorical"&&M==="number"&&s!==void 0&&Anew _e(`${r.key}${o.key}`,r.value,o.message)));let i=e.value.expression||e.value._styleExpression.expression;if(r.expressionContext==="property"&&r.propertyKey==="text-font"&&!i.outputDefined())return[new _e(r.key,r.value,`Invalid data expression for "${r.propertyKey}". Output values must be contained as literals within the expression.`)];if(r.expressionContext==="property"&&r.propertyType==="layout"&&!Lo(i))return[new _e(r.key,r.value,'"feature-state" data expressions are not supported with layout properties.')];if(r.expressionContext==="filter"&&!Lo(i))return[new _e(r.key,r.value,'"feature-state" data expressions are not supported with filters.')];if(r.expressionContext&&r.expressionContext.indexOf("cluster")===0){if(!Bs(i,["zoom","feature-state"]))return[new _e(r.key,r.value,'"zoom" and "feature-state" expressions are not supported with cluster properties.')];if(r.expressionContext==="cluster-initial"&&!Fs(i))return[new _e(r.key,r.value,"Feature data expressions are not supported with initial expression part of cluster properties.")]}return[]}function Uo(r){let e=r.key,i=r.value,o=Ue(i);return o!=="string"?[new _e(e,i,`color expected, ${o} found`)]:Ve.parse(String(i))?[]:[new _e(e,i,`color expected, "${i}" found`)]}function xn(r){let e=r.key,i=r.value,o=r.valueSpec,s=[];return Array.isArray(o.values)?o.values.indexOf(It(i))===-1&&s.push(new _e(e,i,`expected one of [${o.values.join(", ")}], ${JSON.stringify(i)} found`)):Object.keys(o.values).indexOf(It(i))===-1&&s.push(new _e(e,i,`expected one of [${Object.keys(o.values).join(", ")}], ${JSON.stringify(i)} found`)),s}function ro(r){return ul(vn(r.value))?Fr(nn({},r,{expressionContext:"filter",valueSpec:{value:"boolean"}})):Vc(r)}function Vc(r){let e=r.value,i=r.key;if(Ue(e)!=="array")return[new _e(i,e,`array expected, ${Ue(e)} found`)];let o=r.styleSpec,s,l=[];if(e.length<1)return[new _e(i,e,"filter array must have at least 1 element")];switch(l=l.concat(xn({key:`${i}[0]`,value:e[0],valueSpec:o.filter_operator,style:r.style,styleSpec:r.styleSpec})),It(e[0])){case"<":case"<=":case">":case">=":e.length>=2&&It(e[1])==="$type"&&l.push(new _e(i,e,`"$type" cannot be use with operator "${e[0]}"`));case"==":case"!=":e.length!==3&&l.push(new _e(i,e,`filter array for operator "${e[0]}" must have 3 elements`));case"in":case"!in":e.length>=2&&(s=Ue(e[1]),s!=="string"&&l.push(new _e(`${i}[1]`,e[1],`string expected, ${s} found`)));for(let h=2;h{_ in s&&o.push(new _e(l,s[_],`"${_}" is prohibited for ref layers`))})),h.layers.forEach((_=>{It(_.id)===m&&(v=_)})),v?v.ref?o.push(new _e(l,s.ref,"ref cannot reference another ref layer")):g=It(v.type):o.push(new _e(l,s.ref,`ref layer "${m}" not found`))}else if(g!=="background")if(s.source){let v=h.sources&&h.sources[s.source],_=v&&It(v.type);v?_==="vector"&&g==="raster"?o.push(new _e(l,s.source,`layer "${s.id}" requires a raster source`)):_!=="raster-dem"&&g==="hillshade"||_!=="raster-dem"&&g==="color-relief"?o.push(new _e(l,s.source,`layer "${s.id}" requires a raster-dem source`)):_==="raster"&&g!=="raster"?o.push(new _e(l,s.source,`layer "${s.id}" requires a vector source`)):_!=="vector"||s["source-layer"]?_==="raster-dem"&&g!=="hillshade"&&g!=="color-relief"?o.push(new _e(l,s.source,"raster-dem source can only be used with layer type 'hillshade' or 'color-relief'.")):g!=="line"||!s.paint||!s.paint["line-gradient"]||_==="geojson"&&v.lineMetrics||o.push(new _e(l,s,`layer "${s.id}" specifies a line-gradient, which requires a GeoJSON source with \`lineMetrics\` enabled.`)):o.push(new _e(l,s,`layer "${s.id}" must specify a "source-layer"`)):o.push(new _e(l,s.source,`source "${s.source}" not found`))}else o.push(new _e(l,s,'missing required property "source"'));return g==="raster"&&(!((e=s.paint)===null||e===void 0)&&e.resampling)&&(!((i=s.paint)===null||i===void 0)&&i["raster-resampling"])&&o.push(new _e(l,s.paint,`layer "${s.id}" redundantly specifies "resampling" and "raster-resampling" paint properties, but only one is allowed. It is advised to use "resampling".`)),o=o.concat(wi({key:l,value:s,valueSpec:d.layer,style:r.style,styleSpec:r.styleSpec,validateSpec:r.validateSpec,objectElementValidators:{"*":()=>[],type:()=>r.validateSpec({key:`${l}.type`,value:s.type,valueSpec:d.layer.type,style:r.style,styleSpec:r.styleSpec,validateSpec:r.validateSpec,object:s,objectKey:"type"}),filter:ro,layout:v=>wi({layer:s,key:v.key,value:v.value,style:v.style,styleSpec:v.styleSpec,validateSpec:v.validateSpec,objectElementValidators:{"*":_=>Gc(nn({layerType:g},_))}}),paint:v=>wi({layer:s,key:v.key,value:v.value,style:v.style,styleSpec:v.styleSpec,validateSpec:v.validateSpec,objectElementValidators:{"*":_=>Uc(nn({layerType:g},_))}})}})),o}function Br(r){let e=r.value,i=r.key,o=Ue(e);return o!=="string"?[new _e(i,e,`string expected, ${o} found`)]:[]}let ml={promoteId:function({key:r,value:e}){if(Ue(e)==="string")return Br({key:r,value:e});{let i=[];for(let o in e)i.push(...Br({key:`${r}.${o}`,value:e[o]}));return i}}};function gl(r){let e=r.value,i=r.key,o=r.styleSpec,s=r.style,l=r.validateSpec;if(!e.type)return[new _e(i,e,'"type" is required')];let h=It(e.type),d;switch(h){case"vector":case"raster":return d=wi({key:i,value:e,valueSpec:o[`source_${h.replace("-","_")}`],style:r.style,styleSpec:o,objectElementValidators:ml,validateSpec:l}),d;case"raster-dem":return d=(function(g){var m;let v=(m=g.sourceName)!==null&&m!==void 0?m:"",_=g.value,T=g.styleSpec,b=T.source_raster_dem,I=g.style,M=[],A=Ue(_);if(_===void 0)return M;if(A!=="object")return M.push(new _e("source_raster_dem",_,`object expected, ${A} found`)),M;let D=It(_.encoding)==="custom",L=["redFactor","greenFactor","blueFactor","baseShift"],R=g.value.encoding?`"${g.value.encoding}"`:"Default";for(let F in _)!D&&L.includes(F)?M.push(new _e(F,_[F],`In "${v}": "${F}" is only valid when "encoding" is set to "custom". ${R} encoding found`)):b[F]?M=M.concat(g.validateSpec({key:F,value:_[F],valueSpec:b[F],validateSpec:g.validateSpec,style:I,styleSpec:T})):M.push(new _e(F,_[F],`unknown property "${F}"`));return M})({sourceName:i,value:e,style:r.style,styleSpec:o,validateSpec:l}),d;case"geojson":if(d=wi({key:i,value:e,valueSpec:o.source_geojson,style:s,styleSpec:o,validateSpec:l,objectElementValidators:ml}),e.cluster)for(let g in e.clusterProperties){let[m,v]=e.clusterProperties[g],_=typeof m=="string"?[m,["accumulated"],["get",g]]:m;d.push(...Fr({key:`${i}.${g}.map`,value:v,expressionContext:"cluster-map"})),d.push(...Fr({key:`${i}.${g}.reduce`,value:_,expressionContext:"cluster-reduce"}))}return d;case"video":return wi({key:i,value:e,valueSpec:o.source_video,style:s,validateSpec:l,styleSpec:o});case"image":return wi({key:i,value:e,valueSpec:o.source_image,style:s,validateSpec:l,styleSpec:o});case"canvas":return[new _e(i,null,"Please use runtime APIs to add canvas sources, rather than including them in stylesheets.","source.canvas")];default:return xn({key:`${i}.type`,value:e.type,valueSpec:{values:["vector","raster","raster-dem","geojson","video","image"]}})}}function Go(r){let e=r.value,i=r.styleSpec,o=i.light,s=r.style,l=[],h=Ue(e);if(e===void 0)return l;if(h!=="object")return l=l.concat([new _e("light",e,`object expected, ${h} found`)]),l;for(let d in e){let g=d.match(/^(.*)-transition$/);l=l.concat(g&&o[g[1]]&&o[g[1]].transition?r.validateSpec({key:d,value:e[d],valueSpec:i.transition,validateSpec:r.validateSpec,style:s,styleSpec:i}):o[d]?r.validateSpec({key:d,value:e[d],valueSpec:o[d],validateSpec:r.validateSpec,style:s,styleSpec:i}):[new _e(d,e[d],`unknown property "${d}"`)])}return l}function Zc(r){let e=r.value,i=r.styleSpec,o=i.sky,s=r.style,l=Ue(e);if(e===void 0)return[];if(l!=="object")return[new _e("sky",e,`object expected, ${l} found`)];let h=[];for(let d in e)h=h.concat(o[d]?r.validateSpec({key:d,value:e[d],valueSpec:o[d],style:s,styleSpec:i}):[new _e(d,e[d],`unknown property "${d}"`)]);return h}function _l(r){let e=r.value,i=r.styleSpec,o=i.terrain,s=r.style,l=[],h=Ue(e);if(e===void 0)return l;if(h!=="object")return l=l.concat([new _e("terrain",e,`object expected, ${h} found`)]),l;for(let d in e)l=l.concat(o[d]?r.validateSpec({key:d,value:e[d],valueSpec:o[d],validateSpec:r.validateSpec,style:s,styleSpec:i}):[new _e(d,e[d],`unknown property "${d}"`)]);return l}function yl(r){let e=[],i=r.value,o=r.key;if(Array.isArray(i)){let s=[],l=[];for(let h in i)i[h].id&&s.includes(i[h].id)&&e.push(new _e(o,i,`all the sprites' ids must be unique, but ${i[h].id} is duplicated`)),s.push(i[h].id),i[h].url&&l.includes(i[h].url)&&e.push(new _e(o,i,`all the sprites' URLs must be unique, but ${i[h].url} is duplicated`)),l.push(i[h].url),e=e.concat(wi({key:`${o}[${h}]`,value:i[h],valueSpec:{id:{type:"string",required:!0},url:{type:"string",required:!0}},validateSpec:r.validateSpec}));return e}return Br({key:o,value:i})}function qc(r){return!!r&&r.constructor===Object}function $o(r){return qc(r.value)?[]:[new _e(r.key,r.value,`object expected, ${Ue(r.value)} found`)]}let vl={"*":()=>[],array:$s,boolean:function(r){let e=r.value,i=r.key,o=Ue(e);return o!=="boolean"?[new _e(i,e,`boolean expected, ${o} found`)]:[]},number:io,color:Uo,constants:Nc,enum:xn,filter:ro,function:Zs,layer:$c,object:wi,source:gl,light:Go,sky:Zc,terrain:_l,projection:function(r){let e=r.value,i=r.styleSpec,o=i.projection,s=r.style,l=Ue(e);if(e===void 0)return[];if(l!=="object")return[new _e("projection",e,`object expected, ${l} found`)];let h=[];for(let d in e)h=h.concat(o[d]?r.validateSpec({key:d,value:e[d],valueSpec:o[d],style:s,styleSpec:i}):[new _e(d,e[d],`unknown property "${d}"`)]);return h},projectionDefinition:function(r){let e=r.key,i=r.value;i=i instanceof String?i.valueOf():i;let o=Ue(i);return o!=="array"||(function(s){return Array.isArray(s)&&s.length===3&&typeof s[0]=="string"&&typeof s[1]=="string"&&typeof s[2]=="number"})(i)||(function(s){return!!["interpolate","step","literal"].includes(s[0])})(i)?["array","string"].includes(o)?[]:[new _e(e,i,`projection expected, invalid type "${o}" found`)]:[new _e(e,i,`projection expected, invalid array ${JSON.stringify(i)} found`)]},string:Br,formatted:function(r){return Br(r).length===0?[]:Fr(r)},resolvedImage:function(r){return Br(r).length===0?[]:Fr(r)},padding:function(r){let e=r.key,i=r.value;if(Ue(i)==="array"){if(i.length<1||i.length>4)return[new _e(e,i,`padding requires 1 to 4 values; ${i.length} values found`)];let o={type:"number"},s=[];for(let l=0;l[]}})),r.constants&&(i=i.concat(Nc({key:"constants",value:r.constants}))),Wc(i)}function Ji(r){return function(e){return r(Object.assign({},e,{validateSpec:Zo}))}}function Wc(r){return[].concat(r).sort(((e,i)=>e.line-i.line))}function Qi(r){return function(...e){return Wc(r.apply(this,e))}}ji.source=Qi(Ji(gl)),ji.sprite=Qi(Ji(yl)),ji.glyphs=Qi(Ji(no)),ji.light=Qi(Ji(Go)),ji.sky=Qi(Ji(Zc)),ji.terrain=Qi(Ji(_l)),ji.state=Qi(Ji($o)),ji.layer=Qi(Ji($c)),ji.filter=Qi(Ji(ro)),ji.paintProperty=Qi(Ji(Uc)),ji.layoutProperty=Qi(Ji(Gc));let iu={type:"enum","property-type":"data-constant",expression:{interpolated:!1,parameters:["global-state"]},values:{visible:{},none:{}},transition:!1,default:"visible"};class ru{constructor(e,i){this._globalState=i,this.setValue(e)}evaluate(){var e;return(e=this._literalValue)!==null&&e!==void 0?e:this._compiledValue.evaluate({})}setValue(e){if(e==null||e==="visible"||e==="none")return this._literalValue=e==="none"?"none":"visible",this._compiledValue=void 0,void(this._globalStateRefs=new Set);let i=Oo(e,iu,this._globalState);if(i.result==="error")throw this._literalValue="visible",this._compiledValue=void 0,new Error(i.value.map((o=>`${o.key}: ${o.message}`)).join(", "));this._literalValue=void 0,this._compiledValue=i.value,this._globalStateRefs=eo(i.value.expression)}getGlobalStateRefs(){return this._globalStateRefs}}let qo=ce,nr=ji,zi=nr.light,Wo=nr.sky,Hc=nr.paintProperty,nu=nr.layoutProperty;function Xc(r,e){let i=!1;if(e?.length)for(let o of e)r.fire(new Fn(new Error(o.message))),i=!0;return i}class fr{constructor(e,i,o){let s=this.cells=[];if(e instanceof ArrayBuffer){this.arrayBuffer=e;let h=new Int32Array(this.arrayBuffer);e=h[0],this.d=(i=h[1])+2*(o=h[2]);for(let g=0;g=_[b+0]&&s>=_[b+1])?(d[T]=!0,h.push(v[T])):d[T]=!1}}}_forEachCell(e,i,o,s,l,h,d,g){let m=this._convertToCellCoord(e),v=this._convertToCellCoord(i),_=this._convertToCellCoord(o),T=this._convertToCellCoord(s);for(let b=m;b<=_;b++)for(let I=v;I<=T;I++){let M=this.d*I+b;if((!g||g(this._convertFromCellCoord(b),this._convertFromCellCoord(I),this._convertFromCellCoord(b+1),this._convertFromCellCoord(I+1)))&&l.call(this,e,i,o,s,M,h,d,g))return}}_convertFromCellCoord(e){return(e-this.padding)/this.scale}_convertToCellCoord(e){return Math.max(0,Math.min(this.d-1,Math.floor(e*this.scale)+this.padding))}toArrayBuffer(){if(this.arrayBuffer)return this.arrayBuffer;let e=this.cells,i=3+this.cells.length+1+1,o=0;for(let h of this.cells)o+=h.length;let s=new Int32Array(i+o+this.keys.length+this.bboxes.length);s[0]=this.extent,s[1]=this.n,s[2]=this.padding;let l=i;for(let h=0;ho?(this.lastIntegerZoom=o+1,this.lastIntegerZoomTime=i):this.lastFloorZoom{try{return new RegExp(`\\p{sc=${i}}`,"u").source}catch{return null}})).filter((i=>i));return new RegExp(e.join("|"),"u")}let wl=Qc(["Arab","Dupl","Mong","Ougr","Syrc"]);function Ws(r){return!wl.test(String.fromCodePoint(r))}function Tl(r){return!(bn(r)||(e=r,/[\xA7\xA9\xAE\xB1\xBC-\xBE\xD7\xF7\u2016\u2020\u2021\u2030\u2031\u203B\u203C\u2042\u2047-\u2049\u2051\u2100-\u218F\u221E\u2234\u2235\u2300-\u2307\u230C-\u231F\u2324-\u2328\u232B\u237D-\u239A\u23BE-\u23CD\u23CF\u23D1-\u23DB\u23E2-\u2422\u2424-\u24FF\u25A0-\u2619\u2620-\u2767\u2776-\u2793\u2B12-\u2B2F\u2B50-\u2B59\u2BB8-\u2BEB\u3000-\u303F\u30A0-\u30FF\uE000-\uF8FF\uFE30-\uFE6F\uFF00-\uFFEF\uFFFC\uFFFD]|[\uDB80-\uDBFF][\uDC00-\uDFFF]/gim.test(String.fromCodePoint(e))));var e}let eh=Qc(["Adlm","Arab","Armi","Avst","Chrs","Cprt","Egyp","Elym","Gara","Hatr","Hebr","Hung","Khar","Lydi","Mand","Mani","Mend","Merc","Mero","Narb","Nbat","Nkoo","Orkh","Palm","Phli","Phlp","Phnx","Prti","Rohg","Samr","Sarb","Sogo","Syrc","Thaa","Todr","Yezi"]);function Pl(r){return eh.test(String.fromCodePoint(r))}function th(r,e){return!(!e&&Pl(r)||/[\u0900-\u0DFF\u0F00-\u109F\u1780-\u17FF]/gim.test(String.fromCodePoint(r)))}function Sl(r){for(let e of r)if(Pl(e.codePointAt(0)))return!0;return!1}let gr=new class{constructor(){this.TIMEOUT=5e3,this.applyArabicShaping=null,this.processBidirectionalText=null,this.processStyledBidirectionalText=null,this.pluginStatus="unavailable",this.pluginURL=null,this.loadScriptResolve=()=>{}}setState(r){this.pluginStatus=r.pluginStatus,this.pluginURL=r.pluginURL}getState(){return{pluginStatus:this.pluginStatus,pluginURL:this.pluginURL}}setMethods(r){if(gr.isParsed())throw new Error("RTL text plugin already registered.");this.applyArabicShaping=r.applyArabicShaping,this.processBidirectionalText=r.processBidirectionalText,this.processStyledBidirectionalText=r.processStyledBidirectionalText,this.loadScriptResolve()}isParsed(){return this.applyArabicShaping!=null&&this.processBidirectionalText!=null&&this.processStyledBidirectionalText!=null}getRTLTextPluginStatus(){return this.pluginStatus}syncState(r,e){return p(this,void 0,void 0,(function*(){if(this.isParsed())return this.getState();if(r.pluginStatus!=="loading")return this.setState(r),r;let i=r.pluginURL,o=new Promise((l=>{this.loadScriptResolve=l}));e(i);let s=new Promise((l=>setTimeout((()=>l()),this.TIMEOUT)));if(yield Promise.race([o,s]),this.isParsed()){let l={pluginStatus:"loaded",pluginURL:i};return this.setState(l),l}throw this.setState({pluginStatus:"error",pluginURL:""}),new Error(`RTL Text Plugin failed to import scripts from ${i}`)}))}};class ct{constructor(e,i){this.isSupportedScript=ih,this.zoom=e,i?(this.now=i.now||0,this.fadeDuration=i.fadeDuration||0,this.zoomHistory=i.zoomHistory||new xl,this.transition=i.transition||{}):(this.now=0,this.fadeDuration=0,this.zoomHistory=new xl,this.transition={})}crossFadingFactor(){return this.fadeDuration===0?1:Math.min((this.now-this.zoomHistory.lastIntegerZoomTime)/this.fadeDuration,1)}getCrossfadeParameters(){let e=this.zoom,i=e-Math.floor(e),o=this.crossFadingFactor();return e>this.zoomHistory.lastIntegerZoom?{fromScale:2,toScale:1,t:i+(1-i)*o}:{fromScale:.5,toScale:1,t:1-(1-o)*i}}}function ih(r){return(function(e,i){for(let o of e)if(!th(o.codePointAt(0),i))return!1;return!0})(r,gr.getRTLTextPluginStatus()==="loaded")}let Hs="-transition";class Yo{constructor(e,i,o){this.property=e,this.value=i,this.expression=(function(s,l,h){if(Os(s))return new Us(s,l);if(Ns(s)){let d=Bc(s,l,h);if(d.result==="error")throw new Error(d.value.map((g=>`${g.key}: ${g.message}`)).join(", "));return d.value}{let d=s;return l.type==="color"&&typeof s=="string"?d=Ve.parse(s):l.type!=="padding"||typeof s!="number"&&!Array.isArray(s)?l.type!=="numberArray"||typeof s!="number"&&!Array.isArray(s)?l.type!=="colorArray"||typeof s!="string"&&!Array.isArray(s)?l.type==="variableAnchorOffsetCollection"&&Array.isArray(s)?d=ci.parse(s):l.type==="projectionDefinition"&&typeof s=="string"&&(d=hi.parse(s)):d=ke.parse(s):d=ft.parse(s):d=ei.parse(s),{globalStateRefs:new Set,_globalState:null,kind:"constant",evaluate:()=>d}}})(i===void 0?e.specification.default:i,e.specification,o)}isDataDriven(){return this.expression.kind==="source"||this.expression.kind==="composite"}getGlobalStateRefs(){return this.expression.globalStateRefs||new Set}possiblyEvaluate(e,i,o){return this.property.possiblyEvaluate(this,e,i,o)}}class Il{constructor(e,i){this.property=e,this.value=new Yo(e,void 0,i)}transitioned(e,i){return new El(this.property,this.value,i,Oi({},e.transition,this.transition),e.now)}untransitioned(){return new El(this.property,this.value,null,{},0)}}class Ml{constructor(e,i){this._properties=e,this._values=Object.create(e.defaultTransitionablePropertyValues),this._globalState=i}hasProperty(e){return e in this._properties.defaultTransitionablePropertyValues}getValue(e){return Re(this._values[e].value.value)}setValue(e,i){Object.hasOwn(this._values,e)||(this._values[e]=new Il(this._values[e].property,this._globalState)),this._values[e].value=new Yo(this._values[e].property,i===null?void 0:Re(i),this._globalState)}getTransition(e){return Re(this._values[e].transition)}setTransition(e,i){Object.hasOwn(this._values,e)||(this._values[e]=new Il(this._values[e].property,this._globalState)),this._values[e].transition=Re(i)||void 0}serialize(){let e={};for(let i of Object.keys(this._values)){let o=this.getValue(i);o!==void 0&&(e[i]=o);let s=this.getTransition(i);s!==void 0&&(e[`${i}${Hs}`]=s)}return e}transitioned(e,i){let o=new rh(this._properties);for(let s of Object.keys(this._values))o._values[s]=this._values[s].transitioned(e,i._values[s]);return o}untransitioned(){let e=new rh(this._properties);for(let i of Object.keys(this._values))e._values[i]=this._values[i].untransitioned();return e}}class El{constructor(e,i,o,s,l){this.property=e,this.value=i,this.begin=l+s.delay||0,this.end=this.begin+s.duration||0,e.specification.transition&&(s.delay||s.duration)&&(this.prior=o)}possiblyEvaluate(e,i,o){let s=e.now||0,l=this.value.possiblyEvaluate(e,i,o),h=this.prior;if(h){if(s>this.end)return this.prior=null,l;if(this.value.isDataDriven())return this.prior=null,l;if(ss.zoomHistory.lastIntegerZoom?{from:e,to:i}:{from:o,to:i}}interpolate(e){return e}}class nh{constructor(e){this.specification=e}possiblyEvaluate(e,i,o,s){if(e.value!==void 0){if(e.expression.kind==="constant"){let l=e.expression.evaluate(i,null,{},o,s);return this._calculate(l,l,l,i)}return this._calculate(e.expression.evaluate(new ct(Math.floor(i.zoom-1),i)),e.expression.evaluate(new ct(Math.floor(i.zoom),i)),e.expression.evaluate(new ct(Math.floor(i.zoom+1),i)),i)}}_calculate(e,i,o,s){return s.zoom>s.zoomHistory.lastIntegerZoom?{from:e,to:i}:{from:o,to:i}}interpolate(e){return e}}class oo{constructor(e){this.specification=e}possiblyEvaluate(e,i,o,s){return!!e.expression.evaluate(i,null,{},o,s)}interpolate(){return!1}}class ui{constructor(e){this.properties=e,this.defaultPropertyValues={},this.defaultTransitionablePropertyValues={},this.defaultTransitioningPropertyValues={},this.defaultPossiblyEvaluatedValues={},this.overridableProperties=[];for(let i in e){let o=e[i];o.specification.overridable&&this.overridableProperties.push(i);let s=this.defaultPropertyValues[i]=new Yo(o,void 0,void 0),l=this.defaultTransitionablePropertyValues[i]=new Il(o,void 0);this.defaultTransitioningPropertyValues[i]=l.untransitioned(),this.defaultPossiblyEvaluatedValues[i]=s.possiblyEvaluate({})}}}Pe("DataDrivenProperty",Ce),Pe("DataConstantProperty",Ie),Pe("CrossFadedDataDrivenProperty",Or),Pe("CrossFadedProperty",nh),Pe("ColorRampProperty",oo);let oh=" is a PAINT property not a LAYOUT property. Use get/setPaintProperty instead?",Xs=" is a LAYOUT property not a PAINT property. Use get/setLayoutProperty instead?";class Ui extends fs{constructor(e,i,o){if(super(),this.id=e.id,this.type=e.type,this._globalState=o,this._featureFilter={filter:()=>!0,needGeometry:!1,getGlobalStateRefs:()=>new Set},this._visibilityExpression=(function(s,l){return new ru(s,l)})(this.visibility,o),e.type!=="custom"&&(this.metadata=e.metadata,this.minzoom=e.minzoom,this.maxzoom=e.maxzoom,e.type!=="background"&&(this.source=e.source,this.sourceLayer=e["source-layer"],this.filter=e.filter,this._featureFilter=No(e.filter,o)),i.layout&&(this._unevaluatedLayout=new su(i.layout,o)),i.paint)){this._transitionablePaint=new Ml(i.paint,o);for(let s in e.paint)this.setPaintProperty(s,e.paint[s],{validate:!1});for(let s in e.layout)this.setLayoutProperty(s,e.layout[s],{validate:!1});this._transitioningPaint=this._transitionablePaint.untransitioned(),this.paint=new Ko(i.paint)}}setFilter(e){this.filter=e,this._featureFilter=No(e,this._globalState)}getCrossfadeParameters(){return this._crossfadeParameters}getLayoutProperty(e){var i;if(e==="visibility")return this.visibility;if(!((i=this._transitionablePaint)===null||i===void 0)&&i.hasProperty(e))throw new Error(e+oh);if(!this._unevaluatedLayout)throw new Error(`Cannot get layout property "${e}" on layer type "${this.type}" which has no layout properties.`);return this._unevaluatedLayout.getValue(e)}getLayoutAffectingGlobalStateRefs(){let e=new Set;for(let i of this._visibilityExpression.getGlobalStateRefs())e.add(i);if(this._unevaluatedLayout)for(let i in this._unevaluatedLayout._values){let o=this._unevaluatedLayout._values[i];for(let s of o.getGlobalStateRefs())e.add(s)}for(let i of this._featureFilter.getGlobalStateRefs())e.add(i);return e}getPaintAffectingGlobalStateRefs(){var e;let i=new globalThis.Map;if(this._transitionablePaint)for(let o in this._transitionablePaint._values){let s=this._transitionablePaint._values[o].value;for(let l of s.getGlobalStateRefs()){let h=(e=i.get(l))!==null&&e!==void 0?e:[];h.push({name:o,value:s.value}),i.set(l,h)}}return i}getVisibilityAffectingGlobalStateRefs(){return this._visibilityExpression.getGlobalStateRefs()}setLayoutProperty(e,i,o={}){var s;if(e==="visibility")return this.visibility=i,this._visibilityExpression.setValue(i),void this.recalculateVisibility();!((s=this._transitionablePaint)===null||s===void 0)&&s.hasProperty(e)?this.fire(new Fn(new Error(e+oh))):i!=null&&this._validate(nu,`layers.${this.id}.layout.${e}`,e,i,o)||this._unevaluatedLayout.setValue(e,i)}getPaintProperty(e){var i,o;if(e.endsWith(Hs)){let s=e.slice(0,-11);if(s==="visibility"||!((i=this._unevaluatedLayout)===null||i===void 0)&&i.hasProperty(s))throw new Error(e+Xs);return this._transitionablePaint.getTransition(s)}if(e==="visibility"||!((o=this._unevaluatedLayout)===null||o===void 0)&&o.hasProperty(e))throw new Error(e+Xs);return this._transitionablePaint.getValue(e)}setPaintProperty(e,i,o={}){var s;if(e==="visibility"||!((s=this._unevaluatedLayout)===null||s===void 0)&&s.hasProperty(e))return this.fire(new Fn(new Error(e+Xs))),!1;if(i!=null&&this._validate(Hc,`layers.${this.id}.paint.${e}`,e,i,o))return!1;if(e.endsWith(Hs))return this._transitionablePaint.setTransition(e.slice(0,-11),i||void 0),!1;{let l=this._transitionablePaint._values[e],h=l.property.specification["property-type"]==="cross-faded-data-driven",d=l.value.isDataDriven(),g=l.value;this._transitionablePaint.setValue(e,i),this._handleSpecialPaintPropertyUpdate(e);let m=this._transitionablePaint._values[e].value;return m.isDataDriven()||d||h||this._handleOverridablePaintPropertyUpdate(e,g,m)}}_handleSpecialPaintPropertyUpdate(e){}_handleOverridablePaintPropertyUpdate(e,i,o){return!1}isHidden(e=this.minzoom,i=!1){return!!(this.minzoom&&e<(i?Math.floor(this.minzoom):this.minzoom))||!!(this.maxzoom&&e>=this.maxzoom)||this._evaluatedVisibility==="none"}updateTransitions(e){this._transitioningPaint=this._transitionablePaint.transitioned(e,this._transitioningPaint)}hasTransition(){return this._transitioningPaint.hasTransition()}recalculateVisibility(){this._evaluatedVisibility=this._visibilityExpression.evaluate()}recalculate(e,i){e.getCrossfadeParameters&&(this._crossfadeParameters=e.getCrossfadeParameters()),this._unevaluatedLayout&&(this.layout=this._unevaluatedLayout.possiblyEvaluate(e,void 0,i)),this.paint=this._transitioningPaint.possiblyEvaluate(e,void 0,i)}serialize(){var e,i;let o={id:this.id,type:this.type,source:this.source,"source-layer":this.sourceLayer,metadata:this.metadata,minzoom:this.minzoom,maxzoom:this.maxzoom,filter:this.filter,layout:(e=this._unevaluatedLayout)===null||e===void 0?void 0:e.serialize(),paint:(i=this._transitionablePaint)===null||i===void 0?void 0:i.serialize()};return this.visibility&&(o.layout||(o.layout={}),o.layout.visibility=this.visibility),Kr(o,((s,l)=>!(s===void 0||l==="layout"&&!Object.keys(s).length||l==="paint"&&!Object.keys(s).length)))}_validate(e,i,o,s,l={}){return l?.validate!==!1&&Xc(this,e.call(nr,{key:i,layerType:this.type,objectKey:o,value:s,styleSpec:ce,style:{glyphs:!0,sprite:!0}}))}is3D(){return!1}isTileClipped(){return!1}hasOffscreenPass(){return!1}resize(){}isStateDependent(){for(let e in this.paint._values){let i=this.paint.get(e);if(i instanceof er&&Qn(i.property.specification)&&(i.value.kind==="source"||i.value.kind==="composite")&&i.value.isStateDependent)return!0}return!1}}let Cl;var au={get paint(){return Cl=Cl||new ui({"raster-opacity":new Ie(ce.paint_raster["raster-opacity"]),"raster-hue-rotate":new Ie(ce.paint_raster["raster-hue-rotate"]),"raster-brightness-min":new Ie(ce.paint_raster["raster-brightness-min"]),"raster-brightness-max":new Ie(ce.paint_raster["raster-brightness-max"]),"raster-saturation":new Ie(ce.paint_raster["raster-saturation"]),"raster-contrast":new Ie(ce.paint_raster["raster-contrast"]),resampling:new Ie(ce.paint_raster.resampling),"raster-resampling":new Ie(ce.paint_raster["raster-resampling"]),"raster-fade-duration":new Ie(ce.paint_raster["raster-fade-duration"])})}};class lu extends Ui{constructor(e,i){super(e,au,i)}}let cu={Int8:Int8Array,Uint8:Uint8Array,Int16:Int16Array,Uint16:Uint16Array,Int32:Int32Array,Uint32:Uint32Array,Float32:Float32Array};class Jo{constructor(e,i){this._structArray=e,this._pos1=i*this.size,this._pos2=this._pos1/2,this._pos4=this._pos1/4,this._pos8=this._pos1/8}}class mt{constructor(){this.isTransferred=!1,this.capacity=-1,this.resize(0)}static serialize(e,i){return e._trim(),i&&(e.isTransferred=!0,i.push(e.arrayBuffer)),{length:e.length,arrayBuffer:e.arrayBuffer}}static deserialize(e){let i=Object.create(this.prototype);return i.arrayBuffer=e.arrayBuffer,i.length=e.length,i.capacity=e.arrayBuffer.byteLength/i.bytesPerElement,i._refreshViews(),i}_trim(){this.length!==this.capacity&&(this.capacity=this.length,this.arrayBuffer=this.arrayBuffer.slice(0,this.length*this.bytesPerElement),this._refreshViews())}clear(){this.length=0}resize(e){this.reserve(e),this.length=e}reserve(e){if(e>this.capacity){this.capacity=Math.max(e,Math.floor(5*this.capacity),128),this.arrayBuffer=new ArrayBuffer(this.capacity*this.bytesPerElement);let i=this.uint8;this._refreshViews(),i&&this.uint8.set(i)}}_refreshViews(){throw new Error("_refreshViews() must be implemented by each concrete StructArray layout")}freeBufferAfterUpload(){this.arrayBuffer=new ArrayBuffer(0),this._refreshViews()}}function ht(r,e=1){let i=0,o=0;return{members:r.map((s=>{let l=cu[s.type].BYTES_PER_ELEMENT,h=i=sh(i,Math.max(e,l)),d=s.components||1;return o=Math.max(o,l),i+=l*d,{name:s.name,type:s.type,components:d,offset:h}})),size:sh(i,Math.max(o,e)),alignment:e}}function sh(r,e){return Math.ceil(r/e)*e}class Qo extends mt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(e,i){let o=this.length;return this.resize(o+1),this.emplace(o,e,i)}emplace(e,i,o){let s=2*e;return this.int16[s+0]=i,this.int16[s+1]=o,e}}Qo.prototype.bytesPerElement=4,Pe("StructArrayLayout2i4",Qo);class Ys extends mt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(e,i,o){let s=this.length;return this.resize(s+1),this.emplace(s,e,i,o)}emplace(e,i,o,s){let l=3*e;return this.int16[l+0]=i,this.int16[l+1]=o,this.int16[l+2]=s,e}}Ys.prototype.bytesPerElement=6,Pe("StructArrayLayout3i6",Ys);class Ks extends mt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(e,i,o,s){let l=this.length;return this.resize(l+1),this.emplace(l,e,i,o,s)}emplace(e,i,o,s,l){let h=4*e;return this.int16[h+0]=i,this.int16[h+1]=o,this.int16[h+2]=s,this.int16[h+3]=l,e}}Ks.prototype.bytesPerElement=8,Pe("StructArrayLayout4i8",Ks);class Js extends mt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(e,i,o,s,l,h){let d=this.length;return this.resize(d+1),this.emplace(d,e,i,o,s,l,h)}emplace(e,i,o,s,l,h,d){let g=6*e;return this.int16[g+0]=i,this.int16[g+1]=o,this.int16[g+2]=s,this.int16[g+3]=l,this.int16[g+4]=h,this.int16[g+5]=d,e}}Js.prototype.bytesPerElement=12,Pe("StructArrayLayout2i4i12",Js);class Al extends mt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(e,i,o,s,l,h){let d=this.length;return this.resize(d+1),this.emplace(d,e,i,o,s,l,h)}emplace(e,i,o,s,l,h,d){let g=4*e,m=8*e;return this.int16[g+0]=i,this.int16[g+1]=o,this.uint8[m+4]=s,this.uint8[m+5]=l,this.uint8[m+6]=h,this.uint8[m+7]=d,e}}Al.prototype.bytesPerElement=8,Pe("StructArrayLayout2i4ub8",Al);class es extends mt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(e,i){let o=this.length;return this.resize(o+1),this.emplace(o,e,i)}emplace(e,i,o){let s=2*e;return this.float32[s+0]=i,this.float32[s+1]=o,e}}es.prototype.bytesPerElement=8,Pe("StructArrayLayout2f8",es);class _r extends mt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(e,i,o,s,l,h,d,g,m,v){let _=this.length;return this.resize(_+1),this.emplace(_,e,i,o,s,l,h,d,g,m,v)}emplace(e,i,o,s,l,h,d,g,m,v,_){let T=10*e;return this.uint16[T+0]=i,this.uint16[T+1]=o,this.uint16[T+2]=s,this.uint16[T+3]=l,this.uint16[T+4]=h,this.uint16[T+5]=d,this.uint16[T+6]=g,this.uint16[T+7]=m,this.uint16[T+8]=v,this.uint16[T+9]=_,e}}_r.prototype.bytesPerElement=20,Pe("StructArrayLayout10ui20",_r);class Qs extends mt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(e,i,o,s,l,h,d,g){let m=this.length;return this.resize(m+1),this.emplace(m,e,i,o,s,l,h,d,g)}emplace(e,i,o,s,l,h,d,g,m){let v=8*e;return this.uint16[v+0]=i,this.uint16[v+1]=o,this.uint16[v+2]=s,this.uint16[v+3]=l,this.uint16[v+4]=h,this.uint16[v+5]=d,this.uint16[v+6]=g,this.uint16[v+7]=m,e}}Qs.prototype.bytesPerElement=16,Pe("StructArrayLayout8ui16",Qs);class ts extends mt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(e,i,o,s,l,h,d,g,m,v,_,T){let b=this.length;return this.resize(b+1),this.emplace(b,e,i,o,s,l,h,d,g,m,v,_,T)}emplace(e,i,o,s,l,h,d,g,m,v,_,T,b){let I=12*e;return this.int16[I+0]=i,this.int16[I+1]=o,this.int16[I+2]=s,this.int16[I+3]=l,this.uint16[I+4]=h,this.uint16[I+5]=d,this.uint16[I+6]=g,this.uint16[I+7]=m,this.int16[I+8]=v,this.int16[I+9]=_,this.int16[I+10]=T,this.int16[I+11]=b,e}}ts.prototype.bytesPerElement=24,Pe("StructArrayLayout4i4ui4i24",ts);class ea extends mt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(e,i,o){let s=this.length;return this.resize(s+1),this.emplace(s,e,i,o)}emplace(e,i,o,s){let l=3*e;return this.float32[l+0]=i,this.float32[l+1]=o,this.float32[l+2]=s,e}}ea.prototype.bytesPerElement=12,Pe("StructArrayLayout3f12",ea);class is extends mt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer)}emplaceBack(e){let i=this.length;return this.resize(i+1),this.emplace(i,e)}emplace(e,i){return this.uint32[1*e+0]=i,e}}is.prototype.bytesPerElement=4,Pe("StructArrayLayout1ul4",is);class Dl extends mt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(e,i,o,s,l,h,d,g,m){let v=this.length;return this.resize(v+1),this.emplace(v,e,i,o,s,l,h,d,g,m)}emplace(e,i,o,s,l,h,d,g,m,v){let _=10*e,T=5*e;return this.int16[_+0]=i,this.int16[_+1]=o,this.int16[_+2]=s,this.int16[_+3]=l,this.int16[_+4]=h,this.int16[_+5]=d,this.uint32[T+3]=g,this.uint16[_+8]=m,this.uint16[_+9]=v,e}}Dl.prototype.bytesPerElement=20,Pe("StructArrayLayout6i1ul2ui20",Dl);class so extends mt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(e,i,o,s,l,h){let d=this.length;return this.resize(d+1),this.emplace(d,e,i,o,s,l,h)}emplace(e,i,o,s,l,h,d){let g=6*e;return this.int16[g+0]=i,this.int16[g+1]=o,this.int16[g+2]=s,this.int16[g+3]=l,this.int16[g+4]=h,this.int16[g+5]=d,e}}so.prototype.bytesPerElement=12,Pe("StructArrayLayout2i2i2i12",so);class wn extends mt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(e,i,o,s,l){let h=this.length;return this.resize(h+1),this.emplace(h,e,i,o,s,l)}emplace(e,i,o,s,l,h){let d=4*e,g=8*e;return this.float32[d+0]=i,this.float32[d+1]=o,this.float32[d+2]=s,this.int16[g+6]=l,this.int16[g+7]=h,e}}wn.prototype.bytesPerElement=16,Pe("StructArrayLayout2f1f2i16",wn);class zl extends mt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(e,i,o,s,l,h){let d=this.length;return this.resize(d+1),this.emplace(d,e,i,o,s,l,h)}emplace(e,i,o,s,l,h,d){let g=16*e,m=4*e,v=8*e;return this.uint8[g+0]=i,this.uint8[g+1]=o,this.float32[m+1]=s,this.float32[m+2]=l,this.int16[v+6]=h,this.int16[v+7]=d,e}}zl.prototype.bytesPerElement=16,Pe("StructArrayLayout2ub2f2i16",zl);class rs extends mt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(e,i,o){let s=this.length;return this.resize(s+1),this.emplace(s,e,i,o)}emplace(e,i,o,s){let l=3*e;return this.uint16[l+0]=i,this.uint16[l+1]=o,this.uint16[l+2]=s,e}}rs.prototype.bytesPerElement=6,Pe("StructArrayLayout3ui6",rs);class Tn extends mt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(e,i,o,s,l,h,d,g,m,v,_,T,b,I,M,A,D){let L=this.length;return this.resize(L+1),this.emplace(L,e,i,o,s,l,h,d,g,m,v,_,T,b,I,M,A,D)}emplace(e,i,o,s,l,h,d,g,m,v,_,T,b,I,M,A,D,L){let R=24*e,F=12*e,O=48*e;return this.int16[R+0]=i,this.int16[R+1]=o,this.uint16[R+2]=s,this.uint16[R+3]=l,this.uint32[F+2]=h,this.uint32[F+3]=d,this.uint32[F+4]=g,this.uint16[R+10]=m,this.uint16[R+11]=v,this.uint16[R+12]=_,this.float32[F+7]=T,this.float32[F+8]=b,this.uint8[O+36]=I,this.uint8[O+37]=M,this.uint8[O+38]=A,this.uint32[F+10]=D,this.int16[R+22]=L,e}}Tn.prototype.bytesPerElement=48,Pe("StructArrayLayout2i2ui3ul3ui2f3ub1ul1i48",Tn);class Rl extends mt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(e,i,o,s,l,h,d,g,m,v,_,T,b,I,M,A,D,L,R,F,O,V,Y,J,re,te,ae,le){let ne=this.length;return this.resize(ne+1),this.emplace(ne,e,i,o,s,l,h,d,g,m,v,_,T,b,I,M,A,D,L,R,F,O,V,Y,J,re,te,ae,le)}emplace(e,i,o,s,l,h,d,g,m,v,_,T,b,I,M,A,D,L,R,F,O,V,Y,J,re,te,ae,le,ne){let ie=32*e,fe=16*e;return this.int16[ie+0]=i,this.int16[ie+1]=o,this.int16[ie+2]=s,this.int16[ie+3]=l,this.int16[ie+4]=h,this.int16[ie+5]=d,this.int16[ie+6]=g,this.int16[ie+7]=m,this.uint16[ie+8]=v,this.uint16[ie+9]=_,this.uint16[ie+10]=T,this.uint16[ie+11]=b,this.uint16[ie+12]=I,this.uint16[ie+13]=M,this.uint16[ie+14]=A,this.uint16[ie+15]=D,this.uint16[ie+16]=L,this.uint16[ie+17]=R,this.uint16[ie+18]=F,this.uint16[ie+19]=O,this.uint16[ie+20]=V,this.uint16[ie+21]=Y,this.uint16[ie+22]=J,this.uint32[fe+12]=re,this.float32[fe+13]=te,this.float32[fe+14]=ae,this.uint16[ie+30]=le,this.uint16[ie+31]=ne,e}}Rl.prototype.bytesPerElement=64,Pe("StructArrayLayout8i15ui1ul2f2ui64",Rl);class ta extends mt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(e){let i=this.length;return this.resize(i+1),this.emplace(i,e)}emplace(e,i){return this.float32[1*e+0]=i,e}}ta.prototype.bytesPerElement=4,Pe("StructArrayLayout1f4",ta);class ia extends mt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(e,i,o){let s=this.length;return this.resize(s+1),this.emplace(s,e,i,o)}emplace(e,i,o,s){let l=3*e;return this.uint16[6*e+0]=i,this.float32[l+1]=o,this.float32[l+2]=s,e}}ia.prototype.bytesPerElement=12,Pe("StructArrayLayout1ui2f12",ia);class kl extends mt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(e,i,o){let s=this.length;return this.resize(s+1),this.emplace(s,e,i,o)}emplace(e,i,o,s){let l=4*e;return this.uint32[2*e+0]=i,this.uint16[l+2]=o,this.uint16[l+3]=s,e}}kl.prototype.bytesPerElement=8,Pe("StructArrayLayout1ul2ui8",kl);class u extends mt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(e,i){let o=this.length;return this.resize(o+1),this.emplace(o,e,i)}emplace(e,i,o){let s=2*e;return this.uint16[s+0]=i,this.uint16[s+1]=o,e}}u.prototype.bytesPerElement=4,Pe("StructArrayLayout2ui4",u);class t extends mt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(e){let i=this.length;return this.resize(i+1),this.emplace(i,e)}emplace(e,i){return this.uint16[1*e+0]=i,e}}t.prototype.bytesPerElement=2,Pe("StructArrayLayout1ui2",t);class n extends mt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(e,i,o,s){let l=this.length;return this.resize(l+1),this.emplace(l,e,i,o,s)}emplace(e,i,o,s,l){let h=4*e;return this.float32[h+0]=i,this.float32[h+1]=o,this.float32[h+2]=s,this.float32[h+3]=l,e}}n.prototype.bytesPerElement=16,Pe("StructArrayLayout4f16",n);class a extends Jo{get anchorPointX(){return this._structArray.int16[this._pos2+0]}get anchorPointY(){return this._structArray.int16[this._pos2+1]}get x1(){return this._structArray.int16[this._pos2+2]}get y1(){return this._structArray.int16[this._pos2+3]}get x2(){return this._structArray.int16[this._pos2+4]}get y2(){return this._structArray.int16[this._pos2+5]}get featureIndex(){return this._structArray.uint32[this._pos4+3]}get sourceLayerIndex(){return this._structArray.uint16[this._pos2+8]}get bucketIndex(){return this._structArray.uint16[this._pos2+9]}get anchorPoint(){return new Te(this.anchorPointX,this.anchorPointY)}}a.prototype.size=20;class c extends Dl{get(e){return new a(this,e)}}Pe("CollisionBoxArray",c);class f extends Jo{get anchorX(){return this._structArray.int16[this._pos2+0]}get anchorY(){return this._structArray.int16[this._pos2+1]}get glyphStartIndex(){return this._structArray.uint16[this._pos2+2]}get numGlyphs(){return this._structArray.uint16[this._pos2+3]}get vertexStartIndex(){return this._structArray.uint32[this._pos4+2]}get lineStartIndex(){return this._structArray.uint32[this._pos4+3]}get lineLength(){return this._structArray.uint32[this._pos4+4]}get segment(){return this._structArray.uint16[this._pos2+10]}get lowerSize(){return this._structArray.uint16[this._pos2+11]}get upperSize(){return this._structArray.uint16[this._pos2+12]}get lineOffsetX(){return this._structArray.float32[this._pos4+7]}get lineOffsetY(){return this._structArray.float32[this._pos4+8]}get writingMode(){return this._structArray.uint8[this._pos1+36]}get placedOrientation(){return this._structArray.uint8[this._pos1+37]}set placedOrientation(e){this._structArray.uint8[this._pos1+37]=e}get hidden(){return this._structArray.uint8[this._pos1+38]}set hidden(e){this._structArray.uint8[this._pos1+38]=e}get crossTileID(){return this._structArray.uint32[this._pos4+10]}set crossTileID(e){this._structArray.uint32[this._pos4+10]=e}get associatedIconIndex(){return this._structArray.int16[this._pos2+22]}}f.prototype.size=48;class y extends Tn{get(e){return new f(this,e)}}Pe("PlacedSymbolArray",y);class x extends Jo{get anchorX(){return this._structArray.int16[this._pos2+0]}get anchorY(){return this._structArray.int16[this._pos2+1]}get rightJustifiedTextSymbolIndex(){return this._structArray.int16[this._pos2+2]}get centerJustifiedTextSymbolIndex(){return this._structArray.int16[this._pos2+3]}get leftJustifiedTextSymbolIndex(){return this._structArray.int16[this._pos2+4]}get verticalPlacedTextSymbolIndex(){return this._structArray.int16[this._pos2+5]}get placedIconSymbolIndex(){return this._structArray.int16[this._pos2+6]}get verticalPlacedIconSymbolIndex(){return this._structArray.int16[this._pos2+7]}get key(){return this._structArray.uint16[this._pos2+8]}get textBoxStartIndex(){return this._structArray.uint16[this._pos2+9]}get textBoxEndIndex(){return this._structArray.uint16[this._pos2+10]}get verticalTextBoxStartIndex(){return this._structArray.uint16[this._pos2+11]}get verticalTextBoxEndIndex(){return this._structArray.uint16[this._pos2+12]}get iconBoxStartIndex(){return this._structArray.uint16[this._pos2+13]}get iconBoxEndIndex(){return this._structArray.uint16[this._pos2+14]}get verticalIconBoxStartIndex(){return this._structArray.uint16[this._pos2+15]}get verticalIconBoxEndIndex(){return this._structArray.uint16[this._pos2+16]}get featureIndex(){return this._structArray.uint16[this._pos2+17]}get numHorizontalGlyphVertices(){return this._structArray.uint16[this._pos2+18]}get numVerticalGlyphVertices(){return this._structArray.uint16[this._pos2+19]}get numIconVertices(){return this._structArray.uint16[this._pos2+20]}get numVerticalIconVertices(){return this._structArray.uint16[this._pos2+21]}get useRuntimeCollisionCircles(){return this._structArray.uint16[this._pos2+22]}get crossTileID(){return this._structArray.uint32[this._pos4+12]}set crossTileID(e){this._structArray.uint32[this._pos4+12]=e}get textBoxScale(){return this._structArray.float32[this._pos4+13]}get collisionCircleDiameter(){return this._structArray.float32[this._pos4+14]}get textAnchorOffsetStartIndex(){return this._structArray.uint16[this._pos2+30]}get textAnchorOffsetEndIndex(){return this._structArray.uint16[this._pos2+31]}}x.prototype.size=64;class w extends Rl{get(e){return new x(this,e)}}Pe("SymbolInstanceArray",w);class P extends ta{getoffsetX(e){return this.float32[1*e+0]}}Pe("GlyphOffsetArray",P);class S extends Ys{getx(e){return this.int16[3*e+0]}gety(e){return this.int16[3*e+1]}gettileUnitDistanceFromAnchor(e){return this.int16[3*e+2]}}Pe("SymbolLineVertexArray",S);class E extends Jo{get textAnchor(){return this._structArray.uint16[this._pos2+0]}get textOffset0(){return this._structArray.float32[this._pos4+1]}get textOffset1(){return this._structArray.float32[this._pos4+2]}}E.prototype.size=12;class C extends ia{get(e){return new E(this,e)}}Pe("TextAnchorOffsetArray",C);class z extends Jo{get featureIndex(){return this._structArray.uint32[this._pos4+0]}get sourceLayerIndex(){return this._structArray.uint16[this._pos2+2]}get bucketIndex(){return this._structArray.uint16[this._pos2+3]}}z.prototype.size=8;class B extends kl{get(e){return new z(this,e)}}Pe("FeatureIndexArray",B);class N extends Qo{}class G extends Qo{}class j extends Qo{}class $ extends Js{}class X extends Al{}class Z extends es{}class U extends _r{}class H extends Qs{}class q extends ts{}class Q extends ea{}class oe extends is{}class se extends so{}class de extends zl{}class ue extends rs{}class Se extends u{}let ve=ht([{name:"a_pos",components:2,type:"Int16"}],4),{members:he}=ve;class we{constructor(e=[]){this._forceNewSegmentOnNextPrepare=!1,this.segments=e}prepareSegment(e,i,o,s){let l=this.segments[this.segments.length-1];return e>we.MAX_VERTEX_ARRAY_LENGTH&&Wt(`Max vertices per segment is ${we.MAX_VERTEX_ARRAY_LENGTH}: bucket requested ${e}. Consider using the \`fillLargeMeshArrays\` function if you require meshes with more than ${we.MAX_VERTEX_ARRAY_LENGTH} vertices.`),this._forceNewSegmentOnNextPrepare||!l||l.vertexLength+e>we.MAX_VERTEX_ARRAY_LENGTH||l.sortKey!==s?this.createNewSegment(i,o,s):l}createNewSegment(e,i,o){let s={vertexOffset:e.length,primitiveOffset:i.length,vertexLength:0,primitiveLength:0,vaos:{}};return o!==void 0&&(s.sortKey=o),this._forceNewSegmentOnNextPrepare=!1,this.segments.push(s),s}getOrCreateLatestSegment(e,i,o){return this.prepareSegment(0,e,i,o)}forceNewSegmentOnNextPrepare(){this._forceNewSegmentOnNextPrepare=!0}get(){return this.segments}destroy(){for(let e of this.segments)for(let i in e.vaos)e.vaos[i].destroy()}static simpleSegment(e,i,o,s){return new we([{vertexOffset:e,primitiveOffset:i,vertexLength:o,primitiveLength:s,vaos:{},sortKey:0}])}}function Ee(r,e){return 256*(r=li(Math.floor(r),0,255))+li(Math.floor(e),0,255)}we.MAX_VERTEX_ARRAY_LENGTH=Math.pow(2,16)-1,Pe("SegmentVector",we);let tt=ht([{name:"a_pattern_from",components:4,type:"Uint16"},{name:"a_pattern_to",components:4,type:"Uint16"},{name:"a_pixel_ratio_from",components:1,type:"Uint16"},{name:"a_pixel_ratio_to",components:1,type:"Uint16"}]),Mt=ht([{name:"a_dasharray_from",components:4,type:"Uint16"},{name:"a_dasharray_to",components:4,type:"Uint16"}]);var ot,Ct,Dt,ti={exports:{}},wt={exports:{}},di={exports:{}},Kt=(function(){if(Dt)return ti.exports;Dt=1;var r=(ot||(ot=1,wt.exports=function(i,o){var s,l,h,d,g,m,v,_;for(l=i.length-(s=3&i.length),h=o,g=3432918353,m=461845907,_=0;_>>16)*g&65535)<<16)&4294967295)<<15|v>>>17))*m+(((v>>>16)*m&65535)<<16)&4294967295)<<13|h>>>19))+((5*(h>>>16)&65535)<<16)&4294967295))+((58964+(d>>>16)&65535)<<16);switch(v=0,s){case 3:v^=(255&i.charCodeAt(_+2))<<16;case 2:v^=(255&i.charCodeAt(_+1))<<8;case 1:h^=v=(65535&(v=(v=(65535&(v^=255&i.charCodeAt(_)))*g+(((v>>>16)*g&65535)<<16)&4294967295)<<15|v>>>17))*m+(((v>>>16)*m&65535)<<16)&4294967295}return h^=i.length,h=2246822507*(65535&(h^=h>>>16))+((2246822507*(h>>>16)&65535)<<16)&4294967295,h=3266489909*(65535&(h^=h>>>13))+((3266489909*(h>>>16)&65535)<<16)&4294967295,(h^=h>>>16)>>>0}),wt.exports),e=(Ct||(Ct=1,di.exports=function(i,o){for(var s,l=i.length,h=o^l,d=0;l>=4;)s=1540483477*(65535&(s=255&i.charCodeAt(d)|(255&i.charCodeAt(++d))<<8|(255&i.charCodeAt(++d))<<16|(255&i.charCodeAt(++d))<<24))+((1540483477*(s>>>16)&65535)<<16),h=1540483477*(65535&h)+((1540483477*(h>>>16)&65535)<<16)^(s=1540483477*(65535&(s^=s>>>24))+((1540483477*(s>>>16)&65535)<<16)),l-=4,++d;switch(l){case 3:h^=(255&i.charCodeAt(d+2))<<16;case 2:h^=(255&i.charCodeAt(d+1))<<8;case 1:h=1540483477*(65535&(h^=255&i.charCodeAt(d)))+((1540483477*(h>>>16)&65535)<<16)}return h=1540483477*(65535&(h^=h>>>13))+((1540483477*(h>>>16)&65535)<<16),(h^=h>>>15)>>>0}),di.exports);return ti.exports=r,ti.exports.murmur3=r,ti.exports.murmur2=e,ti.exports})(),Nt=Sr(Kt);class ii{constructor(){this.ids=[],this.positions=[],this.indexed=!1}add(e,i,o,s){this.ids.push(Nr(e)),this.positions.push(i,o,s)}getPositions(e){if(!this.indexed)throw new Error("Trying to get index, but feature positions are not indexed");let i=Nr(e),o=0,s=this.ids.length-1;for(;o>1;this.ids[h]>=i?s=h:o=h+1}let l=[];for(;this.ids[o]===i;)l.push({index:this.positions[3*o],start:this.positions[3*o+1],end:this.positions[3*o+2]}),o++;return l}static serialize(e,i){let o=new Float64Array(e.ids),s=new Uint32Array(e.positions);return Vr(o,s,0,o.length-1),i&&i.push(o.buffer,s.buffer),{ids:o,positions:s}}static deserialize(e){let i=new ii;return i.ids=e.ids,i.positions=e.positions,i.indexed=!0,i}}function Nr(r){let e=+r;return!isNaN(e)&&e<=Number.MAX_SAFE_INTEGER?e:Nt(String(r))}function Vr(r,e,i,o){for(;i>1],l=i-1,h=o+1;for(;;){do l++;while(r[l]s);if(l>=h)break;jr(r,l,h),jr(e,3*l,3*h),jr(e,3*l+1,3*h+1),jr(e,3*l+2,3*h+2)}h-i`u_${s}`)),this.type=o}setUniform(e,i,o){e.set(o.constantOr(this.value))}getBinding(e,i,o){return this.type==="color"?new ra(e,i):new yr(e,i)}}class Gi{constructor(e,i){this.uniformNames=i.map((o=>`u_${o}`)),this.patternFrom=null,this.patternTo=null,this.pixelRatioFrom=1,this.pixelRatioTo=1}setConstantPatternPositions(e,i){this.pixelRatioFrom=i.pixelRatio,this.pixelRatioTo=e.pixelRatio,this.patternFrom=i.tlbr,this.patternTo=e.tlbr}setConstantDashPositions(e,i){this.dashTo=[0,e.y,e.height,e.width],this.dashFrom=[0,i.y,i.height,i.width]}setUniform(e,i,o,s){let l=null;s==="u_pattern_to"?l=this.patternTo:s==="u_pattern_from"?l=this.patternFrom:s==="u_dasharray_to"?l=this.dashTo:s==="u_dasharray_from"?l=this.dashFrom:s==="u_pixel_ratio_to"?l=this.pixelRatioTo:s==="u_pixel_ratio_from"&&(l=this.pixelRatioFrom),l!==null&&e.set(l)}getBinding(e,i,o){return o.startsWith("u_pattern")||o.startsWith("u_dasharray_")?new Ur(e,i):new yr(e,i)}}class gt{constructor(e,i,o,s){this.expression=e,this.type=o,this.maxValue=0,this.paintVertexAttributes=i.map((l=>({name:`a_${l}`,type:"Float32",components:o==="color"?2:1,offset:0}))),this.paintVertexArray=new s}populatePaintArray(e,i,o){let s=this.paintVertexArray.length,l=this.expression.evaluate(new ct(0,o),i,{},o.canonical,[],o.formattedSection);this.paintVertexArray.resize(e),this._setPaintValue(s,e,l)}updatePaintArray(e,i,o,s,l){let h=this.expression.evaluate(new ct(0,l),o,s);this._setPaintValue(e,i,h)}_setPaintValue(e,i,o){if(this.type==="color"){let s=ar(o);for(let l=e;l`u_${d}_t`)),this.type=o,this.useIntegerZoom=s,this.zoom=l,this.maxValue=0,this.paintVertexAttributes=i.map((d=>({name:`a_${d}`,type:"Float32",components:o==="color"?4:2,offset:0}))),this.paintVertexArray=new h}populatePaintArray(e,i,o){let s=this.expression.evaluate(new ct(this.zoom,o),i,{},o.canonical,[],o.formattedSection),l=this.expression.evaluate(new ct(this.zoom+1,o),i,{},o.canonical,[],o.formattedSection),h=this.paintVertexArray.length;this.paintVertexArray.resize(e),this._setPaintValue(h,e,s,l)}updatePaintArray(e,i,o,s,l){let h=this.expression.evaluate(new ct(this.zoom,l),o,s),d=this.expression.evaluate(new ct(this.zoom+1,l),o,s);this._setPaintValue(e,i,h,d)}_setPaintValue(e,i,o,s){if(this.type==="color"){let l=ar(o),h=ar(s);for(let d=e;d`#define HAS_UNIFORM_${s}`)))}return e}getBinderAttributes(){let e=[];for(let i in this.binders){let o=this.binders[i];if(o instanceof gt||o instanceof ut)for(let s of o.paintVertexAttributes)e.push(s.name);else if(o instanceof zt){let s=o.getVertexAttributes();for(let l of s)e.push(l.name)}}return e}getBinderUniforms(){let e=[];for(let i in this.binders){let o=this.binders[i];if(o instanceof Ri||o instanceof Gi||o instanceof ut)for(let s of o.uniformNames)e.push(s)}return e}getPaintVertexBuffers(){return this._buffers}getUniforms(e,i){let o=[];for(let s in this.binders){let l=this.binders[s];if(l instanceof Ri||l instanceof Gi||l instanceof ut){for(let h of l.uniformNames)if(i[h]){let d=l.getBinding(e,i[h],h);o.push({name:h,property:s,binding:d})}}}return o}setUniforms(e,i,o,s){for(let{name:l,property:h,binding:d}of i)this.binders[h].setUniform(d,s,o.get(h),l)}updatePaintBuffers(e){this._buffers=[];for(let i in this.binders){let o=this.binders[i];if(e&&o instanceof zt){let s=e.fromScale===2?o.zoomInPaintVertexBuffer:o.zoomOutPaintVertexBuffer;s&&this._buffers.push(s)}else(o instanceof gt||o instanceof ut)&&o.paintVertexBuffer&&this._buffers.push(o.paintVertexBuffer)}}upload(e){for(let i in this.binders){let o=this.binders[i];(o instanceof gt||o instanceof ut||o instanceof zt)&&o.upload(e)}this.updatePaintBuffers()}destroy(){for(let e in this.binders){let i=this.binders[e];(i instanceof gt||i instanceof ut||i instanceof zt)&&i.destroy()}}}class vr{constructor(e,i,o=()=>!0){this.programConfigurations={};for(let s of e)this.programConfigurations[s.id]=new na(s,i,o);this.needsUpload=!1,this._featureMap=new ii,this._bufferOffset=0}populatePaintArrays(e,i,o,s){for(let l in this.programConfigurations)this.programConfigurations[l].populatePaintArrays(e,i,s);i.id!==void 0&&this._featureMap.add(i.id,o,this._bufferOffset,e),this._bufferOffset=e,this.needsUpload=!0}updatePaintArrays(e,i,o,s){for(let l of o)this.needsUpload=this.programConfigurations[l.id].updatePaintArrays(e,this._featureMap,i,l,s)||this.needsUpload}get(e){return this.programConfigurations[e]}upload(e){if(this.needsUpload){for(let i in this.programConfigurations)this.programConfigurations[i].upload(e);this.needsUpload=!1}}destroy(){for(let e in this.programConfigurations)this.programConfigurations[e].destroy()}}function Ll(r,e){return{"text-opacity":["opacity"],"icon-opacity":["opacity"],"text-color":["fill_color"],"icon-color":["fill_color"],"text-halo-color":["halo_color"],"icon-halo-color":["halo_color"],"text-halo-blur":["halo_blur"],"icon-halo-blur":["halo_blur"],"text-halo-width":["halo_width"],"icon-halo-width":["halo_width"],"line-gap-width":["gapwidth"],"line-dasharray":["dasharray_to","dasharray_from"],"line-pattern":["pattern_to","pattern_from","pixel_ratio_to","pixel_ratio_from"],"fill-pattern":["pattern_to","pattern_from","pixel_ratio_to","pixel_ratio_from"],"fill-extrusion-pattern":["pattern_to","pattern_from","pixel_ratio_to","pixel_ratio_from"]}[r]||[r.replace(`${e}-`,"").replace(/-/g,"_")]}function ah(r,e,i){let o={color:{source:es,composite:n},number:{source:ta,composite:es}},s=(function(l){return{"line-pattern":{source:U,composite:U},"fill-pattern":{source:U,composite:U},"fill-extrusion-pattern":{source:U,composite:U},"line-dasharray":{source:H,composite:H}}[l]})(r);return s?.[i]||o[e][i]}Pe("ConstantBinder",Ri),Pe("CrossFadedConstantBinder",Gi),Pe("SourceExpressionBinder",gt),Pe("CrossFadedPatternBinder",_t),Pe("CrossFadedDasharrayBinder",Pn),Pe("CompositeExpressionBinder",ut),Pe("ProgramConfiguration",na,{omit:["_buffers"]}),Pe("ProgramConfigurationSet",vr);let Fl=Math.pow(2,14)-1,Gr=-Fl-1;function $r(r){let e=De/r.extent,i=r.loadGeometry();for(let o of i)for(let s of o){let l=Math.round(s.x*e),h=Math.round(s.y*e);s.x=li(l,Gr,Fl),s.y=li(h,Gr,Fl),(ls.x+1||hs.y+1)&&Wt("Geometry exceeds allowed extent, reduce your vector tile buffer size")}return i}function Zr(r,e){return{type:r.type,id:r.id,properties:r.properties,geometry:e?$r(r):[]}}let Bl=-32768;function Ol(r,e,i,o,s){r.emplaceBack(Bl+8*e+o,Bl+8*i+s)}class oa{constructor(e){this.zoom=e.zoom,this.overscaling=e.overscaling,this.layers=e.layers,this.layerIds=this.layers.map((i=>i.id)),this.index=e.index,this.hasDependencies=!1,this.layoutVertexArray=new G,this.indexArray=new ue,this.segments=new we,this.programConfigurations=new vr(e.layers,e.zoom),this.stateDependentLayerIds=this.layers.filter((i=>i.isStateDependent())).map((i=>i.id))}populate(e,i,o){let s=this.layers[0],l=[],h=null,d=!1,g=s.type==="heatmap";if(s.type==="circle"){let v=s;h=v.layout.get("circle-sort-key"),d=!h.isConstant(),g||(g=v.paint.get("circle-pitch-alignment")==="map")}let m=g?i.subdivisionGranularity.circle:1;for(let{feature:v,id:_,index:T,sourceLayerIndex:b}of e){let I=this.layers[0]._featureFilter.needGeometry,M=Zr(v,I);if(!this.layers[0]._featureFilter.filter(new ct(this.zoom),M,o))continue;let A=d?h.evaluate(M,{},o):void 0,D={id:_,properties:v.properties,type:v.type,sourceLayerIndex:b,index:T,geometry:I?M.geometry:$r(v),patterns:{},sortKey:A};l.push(D)}d&&l.sort(((v,_)=>v.sortKey-_.sortKey));for(let v of l){let{geometry:_,index:T,sourceLayerIndex:b}=v,I=e[T].feature;this.addFeature(v,_,T,o,m),i.featureIndex.insert(I,_,T,b,this.index)}}update(e,i,o){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(e,i,this.stateDependentLayers,{imagePositions:o})}isEmpty(){return this.layoutVertexArray.length===0}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload}upload(e){this.uploaded||(this.layoutVertexBuffer=e.createVertexBuffer(this.layoutVertexArray,he),this.indexBuffer=e.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(e),this.uploaded=!0}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy())}addFeature(e,i,o,s,l=1){let h;switch(l){case 1:h=[0,7];break;case 3:h=[0,2,5,7];break;case 5:h=[0,1,3,4,6,7];break;case 7:h=[0,1,2,3,4,5,6,7];break;default:throw new Error(`Invalid circle bucket granularity: ${l}; valid values are 1, 3, 5, 7.`)}let d=h.length;for(let g of i)for(let m of g){let v=m.x,_=m.y;if(v<0||v>=De||_<0||_>=De)continue;let T=this.segments.prepareSegment(d*d,this.layoutVertexArray,this.indexArray,e.sortKey),b=T.vertexLength;for(let I=0;I1){if(hu(r,e))return!0;for(let o of e)if(uu(o,r,i))return!0}for(let o of r)if(uu(o,e,i))return!0;return!1}function hu(r,e){if(r.length===0||e.length===0)return!1;for(let i=0;i1?i:i.sub(e)._mult(s)._add(e))}function Td(r,e){let i,o,s,l=!1;for(let h of r){i=h;for(let d=0,g=i.length-1;de.y!=s.y>e.y&&e.x<(s.x-o.x)*(e.y-o.y)/(s.y-o.y)+o.x&&(l=!l)}return l}function aa(r,e){let i=!1;for(let o=0,s=r.length-1;oe.y!=h.y>e.y&&e.x<(h.x-l.x)*(e.y-l.y)/(h.y-l.y)+l.x&&(i=!i)}return i}function Yf(r,e,i){let o=i[0],s=i[2];if(r.xs.x&&e.x>s.x||r.ys.y&&e.y>s.y)return!1;let l=Mi(r,e,i[0]);return l!==Mi(r,e,i[1])||l!==Mi(r,e,i[2])||l!==Mi(r,e,i[3])}function la(r,e,i){let o=e.paint.get(r).value;return o.kind==="constant"?o.value:i.programConfigurations.get(e.id).getMaxValue(r)}function ch(r){return Math.sqrt(r[0]*r[0]+r[1]*r[1])}function hh(r,e,i,o,s){if(!e[0]&&!e[1])return r;let l=Te.convert(e)._mult(s);i==="viewport"&&l._rotate(-o);let h=[];for(let d of r)h.push(d.sub(l));return h}function Kf(r){let e=[];for(let i=0;idu(R,A,D,L)))})(m,l,d,g),I=v),Pd({queryGeometry:b,size:I,transform:l,unwrappedTileID:d,getElevation:g,pitchAlignment:T,pitchScale:_},s)}}class Md extends oa{}let Ed;Pe("HeatmapBucket",Md,{omit:["layers"]});var nm={get paint(){return Ed=Ed||new ui({"heatmap-radius":new Ce(ce.paint_heatmap["heatmap-radius"]),"heatmap-weight":new Ce(ce.paint_heatmap["heatmap-weight"]),"heatmap-intensity":new Ie(ce.paint_heatmap["heatmap-intensity"]),"heatmap-color":new oo(ce.paint_heatmap["heatmap-color"]),"heatmap-opacity":new Ie(ce.paint_heatmap["heatmap-opacity"])})}};function pu(r,{width:e,height:i},o,s){if(s){if(s instanceof Uint8ClampedArray)s=new Uint8Array(s.buffer);else if(s.length!==e*i*o)throw new RangeError(`mismatched image size. expected: ${s.length} but got: ${e*i*o}`)}else s=new Uint8Array(e*i*o);return r.width=e,r.height=i,r.data=s,r}function Cd(r,{width:e,height:i},o){if(e===r.width&&i===r.height)return;let s=pu({},{width:e,height:i},o);fu(r,s,{x:0,y:0},{x:0,y:0},{width:Math.min(r.width,e),height:Math.min(r.height,i)},o),r.width=e,r.height=i,r.data=s.data}function fu(r,e,i,o,s,l){if(s.width===0||s.height===0)return e;if(s.width>r.width||s.height>r.height||i.x>r.width-s.width||i.y>r.height-s.height)throw new RangeError("out of range source coordinates for image copy");if(s.width>e.width||s.height>e.height||o.x>e.width-s.width||o.y>e.height-s.height)throw new RangeError("out of range destination coordinates for image copy");let h=r.data,d=e.data;if(h===d)throw new Error("srcData equals dstData, so image is already copied");for(let g=0;g{e[r.evaluationKey]=g;let m=r.expression.evaluate(e);s.setPixel(h/4/i,d/4,m)};if(r.clips)for(let h=0,d=0;hthis.max&&(this.max=_),_=this.dim+1||i<-1||i>=this.dim+1)throw new RangeError(`Out of range source coordinates for DEM data. x: ${e}, y: ${i}, dim: ${this.dim}`);return(i+1)*this.stride+(e+1)}unpack(e,i,o){return e*this.redFactor+i*this.greenFactor+o*this.blueFactor-this.baseShift}pack(e){return Fd(e,this.getUnpackVector())}getPixels(){return new ki({width:this.stride,height:this.stride},new Uint8Array(this.data.buffer))}backfillBorder(e,i,o){if(this.dim!==e.dim)throw new Error("dem dimension mismatch");let s=i*this.dim,l=i*this.dim+this.dim,h=o*this.dim,d=o*this.dim+this.dim;switch(i){case-1:s=l-1;break;case 1:l=s+1}switch(o){case-1:h=d-1;break;case 1:d=h+1}let g=-i*this.dim,m=-o*this.dim;for(let v=h;v0)for(let h=e;h=e;h-=o)l=jd(h/o|0,r[h],r[h+1],l);return l&&ca(l,l.next)&&(Gl(l),l=l.next),l}function ns(r,e){if(!r)return r;e||(e=r);let i,o=r;do if(i=!1,o.steiner||!ca(o,o.next)&&At(o.prev,o,o.next)!==0)o=o.next;else{if(Gl(o),o=e=o.prev,o===o.next)break;i=!0}while(i||o!==e);return e}function Vl(r,e,i,o,s,l,h){if(!r)return;!h&&l&&(function(g,m,v,_){let T=g;do T.z===0&&(T.z=yu(T.x,T.y,m,v,_)),T.prevZ=T.prev,T.nextZ=T.next,T=T.next;while(T!==g);T.prevZ.nextZ=null,T.prevZ=null,(function(b){let I,M=1;do{let A,D=b;b=null;let L=null;for(I=0;D;){I++;let R=D,F=0;for(let V=0;V0||O>0&&R;)F!==0&&(O===0||!R||D.z<=R.z)?(A=D,D=D.nextZ,F--):(A=R,R=R.nextZ,O--),L?L.nextZ=A:b=A,A.prevZ=L,L=A;D=R}L.nextZ=null,M*=2}while(I>1)})(T)})(r,o,s,l);let d=r;for(;r.prev!==r.next;){let g=r.prev,m=r.next;if(l?pm(r,o,s,l):dm(r))e.push(g.i,r.i,m.i),Gl(r),r=m.next,d=m.next;else if((r=m)===d){h?h===1?Vl(r=fm(ns(r),e),e,i,o,s,l,2):h===2&&mm(r,e,i,o,s,l):Vl(ns(r),e,i,o,s,l,1);break}}}function dm(r){let e=r.prev,i=r,o=r.next;if(At(e,i,o)>=0)return!1;let s=e.x,l=i.x,h=o.x,d=e.y,g=i.y,m=o.y,v=Math.min(s,l,h),_=Math.min(d,g,m),T=Math.max(s,l,h),b=Math.max(d,g,m),I=o.next;for(;I!==e;){if(I.x>=v&&I.x<=T&&I.y>=_&&I.y<=b&&jl(s,d,l,g,h,m,I.x,I.y)&&At(I.prev,I,I.next)>=0)return!1;I=I.next}return!0}function pm(r,e,i,o){let s=r.prev,l=r,h=r.next;if(At(s,l,h)>=0)return!1;let d=s.x,g=l.x,m=h.x,v=s.y,_=l.y,T=h.y,b=Math.min(d,g,m),I=Math.min(v,_,T),M=Math.max(d,g,m),A=Math.max(v,_,T),D=yu(b,I,e,i,o),L=yu(M,A,e,i,o),R=r.prevZ,F=r.nextZ;for(;R&&R.z>=D&&F&&F.z<=L;){if(R.x>=b&&R.x<=M&&R.y>=I&&R.y<=A&&R!==s&&R!==h&&jl(d,v,g,_,m,T,R.x,R.y)&&At(R.prev,R,R.next)>=0||(R=R.prevZ,F.x>=b&&F.x<=M&&F.y>=I&&F.y<=A&&F!==s&&F!==h&&jl(d,v,g,_,m,T,F.x,F.y)&&At(F.prev,F,F.next)>=0))return!1;F=F.nextZ}for(;R&&R.z>=D;){if(R.x>=b&&R.x<=M&&R.y>=I&&R.y<=A&&R!==s&&R!==h&&jl(d,v,g,_,m,T,R.x,R.y)&&At(R.prev,R,R.next)>=0)return!1;R=R.prevZ}for(;F&&F.z<=L;){if(F.x>=b&&F.x<=M&&F.y>=I&&F.y<=A&&F!==s&&F!==h&&jl(d,v,g,_,m,T,F.x,F.y)&&At(F.prev,F,F.next)>=0)return!1;F=F.nextZ}return!0}function fm(r,e){let i=r;do{let o=i.prev,s=i.next.next;!ca(o,s)&&Nd(o,i,i.next,s)&&Ul(o,s)&&Ul(s,o)&&(e.push(o.i,i.i,s.i),Gl(i),Gl(i.next),i=r=s),i=i.next}while(i!==r);return ns(i)}function mm(r,e,i,o,s,l){let h=r;do{let d=h.next.next;for(;d!==h.prev;){if(h.i!==d.i&&xm(h,d)){let g=Vd(h,d);return h=ns(h,h.next),g=ns(g,g.next),Vl(h,e,i,o,s,l,0),void Vl(g,e,i,o,s,l,0)}d=d.next}h=h.next}while(h!==r)}function gm(r,e){let i=r.x-e.x;return i===0&&(i=r.y-e.y,i===0)&&(i=(r.next.y-r.y)/(r.next.x-r.x)-(e.next.y-e.y)/(e.next.x-e.x)),i}function _m(r,e){let i=(function(s,l){let h=l,d=s.x,g=s.y,m,v=-1/0;if(ca(s,h))return h;do{if(ca(s,h.next))return h.next;if(g<=h.y&&g>=h.next.y&&h.next.y!==h.y){let M=h.x+(g-h.y)*(h.next.x-h.x)/(h.next.y-h.y);if(M<=d&&M>v&&(v=M,m=h.x=h.x&&h.x>=T&&d!==h.x&&Od(gm.x||h.x===m.x&&ym(m,h)))&&(m=h,I=M)}h=h.next}while(h!==_);return m})(r,e);if(!i)return e;let o=Vd(i,r);return ns(o,o.next),ns(i,i.next)}function ym(r,e){return At(r.prev,r,e.prev)<0&&At(e.next,r,r.next)<0}function yu(r,e,i,o,s){return(r=1431655765&((r=858993459&((r=252645135&((r=16711935&((r=(r-i)*s|0)|r<<8))|r<<4))|r<<2))|r<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=(e-o)*s|0)|e<<8))|e<<4))|e<<2))|e<<1))<<1}function vm(r){let e=r,i=r;do(e.x=(r-h)*(l-d)&&(r-h)*(o-d)>=(i-h)*(e-d)&&(i-h)*(l-d)>=(s-h)*(o-d)}function jl(r,e,i,o,s,l,h,d){return!(r===h&&e===d)&&Od(r,e,i,o,s,l,h,d)}function xm(r,e){return r.next.i!==e.i&&r.prev.i!==e.i&&!(function(i,o){let s=i;do{if(s.i!==i.i&&s.next.i!==i.i&&s.i!==o.i&&s.next.i!==o.i&&Nd(s,s.next,i,o))return!0;s=s.next}while(s!==i);return!1})(r,e)&&(Ul(r,e)&&Ul(e,r)&&(function(i,o){let s=i,l=!1,h=(i.x+o.x)/2,d=(i.y+o.y)/2;do s.y>d!=s.next.y>d&&s.next.y!==s.y&&h<(s.next.x-s.x)*(d-s.y)/(s.next.y-s.y)+s.x&&(l=!l),s=s.next;while(s!==i);return l})(r,e)&&(At(r.prev,r,e.prev)||At(r,e.prev,e))||ca(r,e)&&At(r.prev,r,r.next)>0&&At(e.prev,e,e.next)>0)}function At(r,e,i){return(e.y-r.y)*(i.x-e.x)-(e.x-r.x)*(i.y-e.y)}function ca(r,e){return r.x===e.x&&r.y===e.y}function Nd(r,e,i,o){let s=ph(At(r,e,i)),l=ph(At(r,e,o)),h=ph(At(i,o,r)),d=ph(At(i,o,e));return s!==l&&h!==d||!(s!==0||!dh(r,i,e))||!(l!==0||!dh(r,o,e))||!(h!==0||!dh(i,r,o))||!(d!==0||!dh(i,e,o))}function dh(r,e,i){return e.x<=Math.max(r.x,i.x)&&e.x>=Math.min(r.x,i.x)&&e.y<=Math.max(r.y,i.y)&&e.y>=Math.min(r.y,i.y)}function ph(r){return r>0?1:r<0?-1:0}function Ul(r,e){return At(r.prev,r,r.next)<0?At(r,e,r.next)>=0&&At(r,r.prev,e)>=0:At(r,e,r.prev)<0||At(r,r.next,e)<0}function Vd(r,e){let i=vu(r.i,r.x,r.y),o=vu(e.i,e.x,e.y),s=r.next,l=e.prev;return r.next=e,e.prev=r,i.next=s,s.prev=i,o.next=i,i.prev=o,l.next=o,o.prev=l,o}function jd(r,e,i,o){let s=vu(r,e,i);return o?(s.next=o.next,s.prev=o,o.next.prev=s,o.next=s):(s.prev=s,s.next=s),s}function Gl(r){r.next.prev=r.prev,r.prev.next=r.next,r.prevZ&&(r.prevZ.nextZ=r.nextZ),r.nextZ&&(r.nextZ.prevZ=r.prevZ)}function vu(r,e,i){return{i:r,x:e,y:i,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}class ha{constructor(e,i){if(i>e)throw new Error("Min granularity must not be greater than base granularity.");this._baseZoomGranularity=e,this._minGranularity=i}getGranularityForZoomLevel(e){return Math.max(Math.floor(this._baseZoomGranularity/(1<32767||i>32767)throw new Error("Vertex coordinates are out of signed 16 bit integer range.");let o=0|Math.round(e),s=0|Math.round(i),l=this._getKey(o,s);if(this._vertexDictionary.has(l))return this._vertexDictionary.get(l);let h=this._vertexBuffer.length/2;return this._vertexDictionary.set(l,h),this._vertexBuffer.push(o,s),h}_subdivideTrianglesScanline(e){if(this._granularity<2)return(function(s,l){let h=[];for(let d=0;d0?(h.push(g),h.push(v),h.push(m)):(h.push(g),h.push(m),h.push(v))}return h})(this._vertexBuffer,e);let i=[],o=e.length;for(let s=0;s=1||O<=0)||D&&(ml)){_>=s&&_<=l&&h.push(o[(d+1)%3]);continue}!D&&F>0&&h.push(this._vertexToIndex(g+I*F,m+M*F));let V=g+I*Math.max(F,0),Y=g+I*Math.min(O,1);A||this._generateIntraEdgeVertices(h,g,m,v,_,V,Y),!D&&O<1&&h.push(this._vertexToIndex(g+I*O,m+M*O)),(D||_>=s&&_<=l)&&h.push(o[(d+1)%3]),!D&&(_<=s||_>=l)&&this._generateInterEdgeVertices(h,g,m,v,_,T,b,Y,s,l)}return h}_generateIntraEdgeVertices(e,i,o,s,l,h,d){let g=s-i,m=l-o,v=m===0,_=v?Math.min(i,s):Math.min(h,d),T=v?Math.max(i,s):Math.max(h,d),b=Math.floor(_/this._granularityCellSize)+1,I=Math.ceil(T/this._granularityCellSize)-1;if(v?i=b;M--){let A=M*this._granularityCellSize;e.push(this._vertexToIndex(A,o+m*(A-i)/g))}}_generateInterEdgeVertices(e,i,o,s,l,h,d,g,m,v){let _=l-o,T=h-s,b=d-l,I=(m-l)/b,M=(v-l)/b,A=Math.min(I,M),D=Math.max(I,M),L=s+T*A,R=Math.floor(Math.min(L,g)/this._granularityCellSize)+1,F=Math.ceil(Math.max(L,g)/this._granularityCellSize)-1,O=g=1||D<=0){let J=o-d,re=h+(i-h)*Math.min((m-d)/J,(v-d)/J);R=Math.floor(Math.min(re,g)/this._granularityCellSize)+1,F=Math.ceil(Math.max(re,g)/this._granularityCellSize)-1,O=g0?v:m;if(O)for(let J=R;J<=F;J++)e.push(this._vertexToIndex(J*this._granularityCellSize,Y));else for(let J=F;J>=R;J--)e.push(this._vertexToIndex(J*this._granularityCellSize,Y))}_generateOutline(e){let i=[];for(let o of e){let s=os(o,this._granularity,!0),l=this._pointArrayToIndices(s),h=[];for(let d=1;dl!=(h===ua)?(e.push(i),e.push(o),e.push(this._vertexToIndex(s,h)),e.push(o),e.push(this._vertexToIndex(l,h)),e.push(this._vertexToIndex(s,h))):(e.push(o),e.push(i),e.push(this._vertexToIndex(s,h)),e.push(this._vertexToIndex(l,h)),e.push(o),e.push(this._vertexToIndex(s,h)))}_fillPoles(e,i,o){let s=this._vertexBuffer,l=De,h=e.length;for(let d=2;d80*_){A=m[0],D=m[1];let R=A,F=D;for(let O=_;OR&&(R=V),Y>F&&(F=Y)}L=Math.max(R-A,F-D),L=L!==0?32767/L:0}return Vl(I,M,_,A,D,L,0),M})(o,s),g=this._convertIndices(o,d);l=this._subdivideTrianglesScanline(g)}catch(d){console.error(d)}let h=[];return i&&(h=this._generateOutline(e)),this._ensureNoPoleVertices(),this._handlePoles(l),{verticesFlattened:this._vertexBuffer,indicesTriangles:l,indicesLineList:h}}_convertIndices(e,i){let o=[];for(let s of i)o.push(this._vertexToIndex(e[2*s],e[2*s+1]));return o}_pointArrayToIndices(e){let i=[];for(let o of e)i.push(this._vertexToIndex(o.x,o.y));return i}}function Ud(r,e,i,o=!0){return new bm(i,e).subdividePolygonInternal(r,o)}function os(r,e,i=!1){if(!r||r.length<1)return[];if(r.length<2)return[];let o=r[0],s=r[r.length-1],l=i&&(o.x!==s.x||o.y!==s.y);if(e<2)return l?[...r,r[0]]:[...r];let h=Math.floor(De/e),d=[];d.push(new Te(r[0].x,r[0].y));let g=r.length,m=l?g:g-1;for(let v=0;v0?(Math.floor(Y/h)+1)*h:(Math.ceil(Y/h)-1)*h,ae=F>0?(Math.floor(J/h)+1)*h:(Math.ceil(J/h)-1)*h,le=Math.abs(Y-te),ne=Math.abs(J-ae),ie=Math.abs(Y-M),fe=Math.abs(J-A),xe=D?le/O:Number.POSITIVE_INFINITY,ye=L?ne/V:Number.POSITIVE_INFINITY;if((ie<=le||!D)&&(fe<=ne||!L))break;if(xe=0?h-1:l-1,m=(d+1)%l,v=r[2*e[g]],_=r[2*e[m]],T=r[2*e[h]],b=r[2*e[h]+1],I=r[2*e[d]+1],M=!1;if(v<_)M=!0;else if(v>_)M=!1;else{let A=I-b,D=-(r[2*e[d]]-T),L=b((_-T)*A+(r[2*e[m]+1]-b)*D)*L&&(M=!0)}if(M){let A=e[g],D=e[h],L=e[d];A!==D&&A!==L&&D!==L&&i.push(L,D,A),h--,h<0&&(h=l-1)}else{let A=e[m],D=e[h],L=e[d];A!==D&&A!==L&&D!==L&&i.push(L,D,A),d++,d>=l&&(d=0)}if(g===m)break}}function Gd(r,e,i,o,s,l,h,d,g){let m=s.length/2,v=h&&d&&g;if(mwe.MAX_VERTEX_ARRAY_LENGTH&&(F=_.createNewSegment(T,b),R=L.count,te=!0,ae=!0,le=!0,O=0);let ne=Zl(D,I,A,L,Y,te,F),ie=Zl(D,I,A,L,J,ae,F),fe=Zl(D,I,A,L,re,le,F);b.emplaceBack(O+ne-R,O+ie-R,O+fe-R),F.primitiveLength++}})(e,i,o,s,l,r),v&&(function(_,T,b,I,M,A){let D=[];for(let V=0;Vwe.MAX_VERTEX_ARRAY_LENGTH&&(F=_.createNewSegment(T,b),R=L.count,te=!0,ae=!0,O=0);let le=Zl(D,I,A,L,J,te,F),ne=Zl(D,I,A,L,re,ae,F);b.emplaceBack(O+le-R,O+ne-R),F.primitiveLength++}})(h,i,d,s,g,r),e.forceNewSegmentOnNextPrepare(),h?.forceNewSegmentOnNextPrepare()}function Zl(r,e,i,o,s,l,h){if(l){let d=o.count;return i(e[2*s],e[2*s+1]),r[s]=o.count,o.count++,h.vertexLength++,d}return r[s]}class xu{constructor(e){this.zoom=e.zoom,this.overscaling=e.overscaling,this.layers=e.layers,this.layerIds=this.layers.map((i=>i.id)),this.index=e.index,this.hasDependencies=!1,this.patternFeatures=[],this.layoutVertexArray=new j,this.indexArray=new ue,this.indexArray2=new Se,this.programConfigurations=new vr(e.layers,e.zoom),this.segments=new we,this.segments2=new we,this.stateDependentLayerIds=this.layers.filter((i=>i.isStateDependent())).map((i=>i.id))}populate(e,i,o){this.hasDependencies=uh("fill",this.layers,i);let s=this.layers[0].layout.get("fill-sort-key"),l=!s.isConstant(),h=[];for(let{feature:d,id:g,index:m,sourceLayerIndex:v}of e){let _=this.layers[0]._featureFilter.needGeometry,T=Zr(d,_);if(!this.layers[0]._featureFilter.filter(new ct(this.zoom),T,o))continue;let b=l?s.evaluate(T,{},o,i.availableImages):void 0,I={id:g,properties:d.properties,type:d.type,sourceLayerIndex:v,index:m,geometry:_?T.geometry:$r(d),patterns:{},sortKey:b};h.push(I)}l&&h.sort(((d,g)=>d.sortKey-g.sortKey));for(let d of h){let{geometry:g,index:m,sourceLayerIndex:v}=d;if(this.hasDependencies){let _=_u("fill",this.layers,d,{zoom:this.zoom},i);this.patternFeatures.push(_)}else this.addFeature(d,g,m,o,{},i.subdivisionGranularity);i.featureIndex.insert(e[m].feature,g,m,v,this.index)}}update(e,i,o){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(e,i,this.stateDependentLayers,{imagePositions:o})}addFeatures(e,i,o){for(let s of this.patternFeatures)this.addFeature(s,s.geometry,s.index,i,o,e.subdivisionGranularity)}isEmpty(){return this.layoutVertexArray.length===0}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload}upload(e){this.uploaded||(this.layoutVertexBuffer=e.createVertexBuffer(this.layoutVertexArray,um),this.indexBuffer=e.createIndexBuffer(this.indexArray),this.indexBuffer2=e.createIndexBuffer(this.indexArray2)),this.programConfigurations.upload(e),this.uploaded=!0}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.indexBuffer2.destroy(),this.programConfigurations.destroy(),this.segments.destroy(),this.segments2.destroy())}addFeature(e,i,o,s,l,h){for(let d of As(i,500)){let g=Ud(d,s,h.fill.getGranularityForZoomLevel(s.z)),m=this.layoutVertexArray;Gd(((v,_)=>{m.emplaceBack(v,_)}),this.segments,this.layoutVertexArray,this.indexArray,g.verticesFlattened,g.indicesTriangles,this.segments2,this.indexArray2,g.indicesLineList)}this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,e,o,{imagePositions:l,canonical:s})}}let $d,Zd;Pe("FillBucket",xu,{omit:["layers","patternFeatures"]});var Tm={get paint(){return Zd=Zd||new ui({"fill-antialias":new Ie(ce.paint_fill["fill-antialias"]),"fill-opacity":new Ce(ce.paint_fill["fill-opacity"]),"fill-color":new Ce(ce.paint_fill["fill-color"]),"fill-outline-color":new Ce(ce.paint_fill["fill-outline-color"]),"fill-translate":new Ie(ce.paint_fill["fill-translate"]),"fill-translate-anchor":new Ie(ce.paint_fill["fill-translate-anchor"]),"fill-pattern":new Or(ce.paint_fill["fill-pattern"])})},get layout(){return $d=$d||new ui({"fill-sort-key":new Ce(ce.layout_fill["fill-sort-key"])})}};class Pm extends Ui{constructor(e,i){super(e,Tm,i)}recalculate(e,i){super.recalculate(e,i);let o=this.paint._values["fill-outline-color"];o.value.kind==="constant"&&o.value.value===void 0&&(this.paint._values["fill-outline-color"]=this.paint._values["fill-color"])}createBucket(e){return new xu(e)}queryRadius(){return ch(this.paint.get("fill-translate"))}queryIntersectsFeature({queryGeometry:e,geometry:i,transform:o,pixelsToTileUnits:s}){return bd(hh(e,this.paint.get("fill-translate"),this.paint.get("fill-translate-anchor"),-o.bearingInRadians,s),i)}isTileClipped(){return!0}}let Sm=ht([{name:"a_pos",components:2,type:"Int16"},{name:"a_normal_ed",components:4,type:"Int16"}],4),Im=ht([{name:"a_centroid",components:2,type:"Int16"}],4),{members:Mm}=Sm;class ql{constructor(e,i,o,s,l){this.properties={},this.extent=o,this.type=0,this.id=void 0,this._pbf=e,this._geometry=-1,this._keys=s,this._values=l,e.readFields(Em,this,i)}loadGeometry(){let e=this._pbf;e.pos=this._geometry;let i=e.readVarint()+e.pos,o=[],s,l=1,h=0,d=0,g=0;for(;e.pos>3}if(h--,l===1||l===2)d+=e.readSVarint(),g+=e.readSVarint(),l===1&&(s&&o.push(s),s=[]),s&&s.push(new Te(d,g));else{if(l!==7)throw new Error(`unknown command ${l}`);s&&s.push(s[0].clone())}}return s&&o.push(s),o}bbox(){let e=this._pbf;e.pos=this._geometry;let i=e.readVarint()+e.pos,o=1,s=0,l=0,h=0,d=1/0,g=-1/0,m=1/0,v=-1/0;for(;e.pos>3}if(s--,o===1||o===2)l+=e.readSVarint(),h+=e.readSVarint(),lg&&(g=l),hv&&(v=h);else if(o!==7)throw new Error(`unknown command ${o}`)}return[d,m,g,v]}toGeoJSON(e,i,o){let s=this.extent*Math.pow(2,o),l=this.extent*e,h=this.extent*i,d=this.loadGeometry();function g(T){return[360*(T.x+l)/s-180,360/Math.PI*Math.atan(Math.exp((1-2*(T.y+h)/s)*Math.PI))-90]}function m(T){return T.map(g)}let v;if(this.type===1){let T=[];for(let I of d)T.push(I[0]);let b=m(T);v=T.length===1?{type:"Point",coordinates:b[0]}:{type:"MultiPoint",coordinates:b}}else if(this.type===2){let T=d.map(m);v=T.length===1?{type:"LineString",coordinates:T[0]}:{type:"MultiLineString",coordinates:T}}else{if(this.type!==3)throw new Error("unknown feature type");{let T=qd(d),b=[];for(let I of T)b.push(I.map(m));v=b.length===1?{type:"Polygon",coordinates:b[0]}:{type:"MultiPolygon",coordinates:b}}}let _={type:"Feature",geometry:v,properties:this.properties};return this.id!=null&&(_.id=this.id),_}}function Em(r,e,i){r===1?e.id=i.readVarint():r===2?(function(o,s){let l=o.readVarint()+o.pos;for(;o.pos=this._features.length)throw new Error("feature index out of bounds");this._pbf.pos=this._features[e];let i=this._pbf.readVarint()+this._pbf.pos;return new ql(this._pbf,i,this.extent,this._keys,this._values)}}function Dm(r,e,i){r===15?e.version=i.readVarint():r===1?e.name=i.readString():r===5?e.extent=i.readVarint():r===2?e._features.push(i.pos):r===3?e._keys.push(i.readString()):r===4&&e._values.push((function(o){let s=null,l=o.readVarint()+o.pos;for(;o.pos>3;s=h===1?o.readString():h===2?o.readFloat():h===3?o.readDouble():h===4?o.readVarint64():h===5?o.readVarint():h===6?o.readSVarint():h===7?o.readBoolean():null}if(s==null)throw new Error("unknown feature value");return s})(i))}class Wd{constructor(e,i){this.layers=e.readFields(zm,{},i)}}function zm(r,e,i){if(r===3){let o=new Am(i,i.readVarint()+i.pos);o.length&&(e[o.name]=o)}}let bu=Math.pow(2,13);function Wl(r,e,i,o,s,l,h,d){r.emplaceBack(e,i,2*Math.floor(o*bu)+h,s*bu*2,l*bu*2,Math.round(d))}class wu{constructor(e){this.zoom=e.zoom,this.overscaling=e.overscaling,this.layers=e.layers,this.layerIds=this.layers.map((i=>i.id)),this.index=e.index,this.hasDependencies=!1,this.layoutVertexArray=new $,this.centroidVertexArray=new N,this.indexArray=new ue,this.programConfigurations=new vr(e.layers,e.zoom),this.segments=new we,this.stateDependentLayerIds=this.layers.filter((i=>i.isStateDependent())).map((i=>i.id))}populate(e,i,o){this.features=[],this.hasDependencies=uh("fill-extrusion",this.layers,i);for(let{feature:s,id:l,index:h,sourceLayerIndex:d}of e){let g=this.layers[0]._featureFilter.needGeometry,m=Zr(s,g);if(!this.layers[0]._featureFilter.filter(new ct(this.zoom),m,o))continue;let v={id:l,sourceLayerIndex:d,index:h,geometry:g?m.geometry:$r(s),properties:s.properties,type:s.type,patterns:{}};this.hasDependencies?this.features.push(_u("fill-extrusion",this.layers,v,{zoom:this.zoom},i)):this.addFeature(v,v.geometry,h,o,{},i.subdivisionGranularity),i.featureIndex.insert(s,v.geometry,h,d,this.index,!0)}}addFeatures(e,i,o){for(let s of this.features){let{geometry:l}=s;this.addFeature(s,l,s.index,i,o,e.subdivisionGranularity)}}update(e,i,o){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(e,i,this.stateDependentLayers,{imagePositions:o})}isEmpty(){return this.layoutVertexArray.length===0&&this.centroidVertexArray.length===0}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload}upload(e){this.uploaded||(this.layoutVertexBuffer=e.createVertexBuffer(this.layoutVertexArray,Mm),this.centroidVertexBuffer=e.createVertexBuffer(this.centroidVertexArray,Im.members,!0),this.indexBuffer=e.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(e),this.uploaded=!0}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy(),this.centroidVertexBuffer.destroy())}addFeature(e,i,o,s,l,h){for(let d of As(i,500)){let g={x:0,y:0,sampleCount:0},m=this.layoutVertexArray.length;this.processPolygon(g,s,e,d,h);let v=this.layoutVertexArray.length-m,_=Math.floor(g.x/g.sampleCount),T=Math.floor(g.y/g.sampleCount);for(let b=0;b{Wl(v,_,T,0,0,1,1,0)}),this.segments,this.layoutVertexArray,this.indexArray,m.verticesFlattened,m.indicesTriangles)}_generateSideFaces(e,i){let o=0;for(let s=1;swe.MAX_VERTEX_ARRAY_LENGTH&&(i.segment=this.segments.prepareSegment(4,this.layoutVertexArray,this.indexArray));let d=l.sub(h)._perp()._unit(),g=h.dist(l);o+g>32768&&(o=0),Wl(this.layoutVertexArray,l.x,l.y,d.x,d.y,0,0,o),Wl(this.layoutVertexArray,l.x,l.y,d.x,d.y,0,1,o),o+=g,Wl(this.layoutVertexArray,h.x,h.y,d.x,d.y,0,0,o),Wl(this.layoutVertexArray,h.x,h.y,d.x,d.y,0,1,o);let m=i.segment.vertexLength;this.indexArray.emplaceBack(m,m+2,m+1),this.indexArray.emplaceBack(m+1,m+2,m+3),i.segment.vertexLength+=4,i.segment.primitiveLength+=2}}}function Rm(r,e){for(let i=0;iDe)||r.y===e.y&&(r.y<0||r.y>De)}function Hd(r){return r.every((e=>e.x<0))||r.every((e=>e.x>De))||r.every((e=>e.y<0))||r.every((e=>e.y>De))}let Xd;Pe("FillExtrusionBucket",wu,{omit:["layers","features"]});var Lm={get paint(){return Xd=Xd||new ui({"fill-extrusion-opacity":new Ie(ce["paint_fill-extrusion"]["fill-extrusion-opacity"]),"fill-extrusion-color":new Ce(ce["paint_fill-extrusion"]["fill-extrusion-color"]),"fill-extrusion-translate":new Ie(ce["paint_fill-extrusion"]["fill-extrusion-translate"]),"fill-extrusion-translate-anchor":new Ie(ce["paint_fill-extrusion"]["fill-extrusion-translate-anchor"]),"fill-extrusion-pattern":new Or(ce["paint_fill-extrusion"]["fill-extrusion-pattern"]),"fill-extrusion-height":new Ce(ce["paint_fill-extrusion"]["fill-extrusion-height"]),"fill-extrusion-base":new Ce(ce["paint_fill-extrusion"]["fill-extrusion-base"]),"fill-extrusion-vertical-gradient":new Ie(ce["paint_fill-extrusion"]["fill-extrusion-vertical-gradient"])})}};class Fm extends Ui{constructor(e,i){super(e,Lm,i)}createBucket(e){return new wu(e)}queryRadius(){return ch(this.paint.get("fill-extrusion-translate"))}is3D(){return!0}queryIntersectsFeature({queryGeometry:e,feature:i,featureState:o,geometry:s,transform:l,pixelsToTileUnits:h,pixelPosMatrix:d}){let g=hh(e,this.paint.get("fill-extrusion-translate"),this.paint.get("fill-extrusion-translate-anchor"),-l.bearingInRadians,h),m=this.paint.get("fill-extrusion-height").evaluate(i,o),v=this.paint.get("fill-extrusion-base").evaluate(i,o),_=(function(b,I){let M=[];for(let A of b){let D=[A.x,A.y,0,1];Ze(D,D,I),M.push(new Te(D[0]/D[3],D[1]/D[3]))}return M})(g,d),T=(function(b,I,M,A){let D=[],L=[],R=A[8]*I,F=A[9]*I,O=A[10]*I,V=A[11]*I,Y=A[8]*M,J=A[9]*M,re=A[10]*M,te=A[11]*M;for(let ae of b){let le=[],ne=[];for(let ie of ae){let fe=ie.x,xe=ie.y,ye=A[0]*fe+A[4]*xe+A[12],me=A[1]*fe+A[5]*xe+A[13],Ae=A[2]*fe+A[6]*xe+A[14],Ye=A[3]*fe+A[7]*xe+A[15],Je=Ae+O,nt=Ye+V,si=ye+Y,Tt=me+J,Ft=Ae+re,Ut=Ye+te,pt=new Te((ye+R)/nt,(me+F)/nt);pt.z=Je/nt,le.push(pt);let Qt=new Te(si/Ut,Tt/Ut);Qt.z=Ft/Ut,ne.push(Qt)}D.push(le),L.push(ne)}return[D,L]})(s,v,m,d);return(function(b,I,M){let A=1/0;bd(M,I)&&(A=Yd(M,I[0]));for(let D=0;D>4;if(s!==1)throw new Error(`Got v${s} data when expected v1.`);let l=Kd[15&o];if(!l)throw new Error("Unrecognized array type.");let[h]=new Uint16Array(e,2,1),[d]=new Uint32Array(e,4,1);return new mh(d,h,l,e)}constructor(e,i=64,o=Float64Array,s){if(isNaN(e)||e<0)throw new Error(`Unpexpected numItems value: ${e}.`);this.numItems=+e,this.nodeSize=Math.min(Math.max(+i,2),65535),this.ArrayType=o,this.IndexArrayType=e<65536?Uint16Array:Uint32Array;let l=Kd.indexOf(this.ArrayType),h=2*e*this.ArrayType.BYTES_PER_ELEMENT,d=e*this.IndexArrayType.BYTES_PER_ELEMENT,g=(8-d%8)%8;if(l<0)throw new Error(`Unexpected typed array class: ${o}.`);s&&s instanceof ArrayBuffer?(this.data=s,this.ids=new this.IndexArrayType(this.data,8,e),this.coords=new this.ArrayType(this.data,8+d+g,2*e),this._pos=2*e,this._finished=!0):(this.data=new ArrayBuffer(8+h+d+g),this.ids=new this.IndexArrayType(this.data,8,e),this.coords=new this.ArrayType(this.data,8+d+g,2*e),this._pos=0,this._finished=!1,new Uint8Array(this.data,0,2).set([219,16+l]),new Uint16Array(this.data,2,1)[0]=i,new Uint32Array(this.data,4,1)[0]=e)}add(e,i){let o=this._pos>>1;return this.ids[o]=o,this.coords[this._pos++]=e,this.coords[this._pos++]=i,o}finish(){let e=this._pos>>1;if(e!==this.numItems)throw new Error(`Added ${e} items when expected ${this.numItems}.`);return Tu(this.ids,this.coords,this.nodeSize,0,this.numItems-1,0),this._finished=!0,this}range(e,i,o,s){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");let{ids:l,coords:h,nodeSize:d}=this,g=[0,l.length-1,0],m=[];for(;g.length;){let v=g.pop()||0,_=g.pop()||0,T=g.pop()||0;if(_-T<=d){for(let A=T;A<=_;A++){let D=h[2*A],L=h[2*A+1];D>=e&&D<=o&&L>=i&&L<=s&&m.push(l[A])}continue}let b=T+_>>1,I=h[2*b],M=h[2*b+1];I>=e&&I<=o&&M>=i&&M<=s&&m.push(l[b]),(v===0?e<=I:i<=M)&&(g.push(T),g.push(b-1),g.push(1-v)),(v===0?o>=I:s>=M)&&(g.push(b+1),g.push(_),g.push(1-v))}return m}within(e,i,o){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");let{ids:s,coords:l,nodeSize:h}=this,d=[0,s.length-1,0],g=[],m=o*o;for(;d.length;){let v=d.pop()||0,_=d.pop()||0,T=d.pop()||0;if(_-T<=h){for(let A=T;A<=_;A++)Qd(l[2*A],l[2*A+1],e,i)<=m&&g.push(s[A]);continue}let b=T+_>>1,I=l[2*b],M=l[2*b+1];Qd(I,M,e,i)<=m&&g.push(s[b]),(v===0?e-o<=I:i-o<=M)&&(d.push(T),d.push(b-1),d.push(1-v)),(v===0?e+o>=I:i+o>=M)&&(d.push(b+1),d.push(_),d.push(1-v))}return g}}function Tu(r,e,i,o,s,l){if(s-o<=i)return;let h=o+s>>1;Jd(r,e,h,o,s,l),Tu(r,e,i,o,h-1,1-l),Tu(r,e,i,h+1,s,1-l)}function Jd(r,e,i,o,s,l){for(;s>o;){if(s-o>600){let m=s-o+1,v=i-o+1,_=Math.log(m),T=.5*Math.exp(2*_/3),b=.5*Math.sqrt(_*T*(m-T)/m)*(v-m/2<0?-1:1);Jd(r,e,i,Math.max(o,Math.floor(i-v*T/m+b)),Math.min(s,Math.floor(i+(m-v)*T/m+b)),l)}let h=e[2*i+l],d=o,g=s;for(Xl(r,e,o,i),e[2*s+l]>h&&Xl(r,e,o,s);dh;)g--}e[2*o+l]===h?Xl(r,e,o,g):(g++,Xl(r,e,g,s)),g<=i&&(o=g+1),i<=g&&(s=g-1)}}function Xl(r,e,i,o){Pu(r,i,o),Pu(e,2*i,2*o),Pu(e,2*i+1,2*o+1)}function Pu(r,e,i){let o=r[e];r[e]=r[i],r[i]=o}function Qd(r,e,i,o){let s=r-i,l=e-o;return s*s+l*l}function Su(r,e,i,o){let s=o,l=e+(i-e>>1),h,d=i-e,g=r[e],m=r[e+1],v=r[i],_=r[i+1];for(let T=e+3;Ts)h=T,s=b;else if(b===s){let I=Math.abs(T-l);Io&&(h-e>3&&Su(r,e,h,o),r[h+2]=s,i-h>3&&Su(r,h,i,o))}function Bm(r,e,i,o,s,l){let h=s-i,d=l-o;if(h!==0||d!==0){let g=((r-i)*h+(e-o)*d)/(h*h+d*d);g>1?(i=s,o=l):g>0&&(i+=h*g,o+=d*g)}return h=r-i,d=e-o,h*h+d*d}function Jt(r,e,i,o){let s={type:e,geom:i},l={id:r??null,type:s.type,geometry:s.geom,tags:o,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0};switch(s.type){case"Point":case"MultiPoint":Yl(l,s.geom);break;case"LineString":Yl(l,s.geom.points);break;case"Polygon":Yl(l,s.geom[0].points);break;case"MultiLineString":for(let h of s.geom)Yl(l,h.points);break;case"MultiPolygon":for(let h of s.geom)Yl(l,h[0].points)}return l}function Iu(r){r.points.length>64&&(r.points=new Float64Array(r.points))}function Yl(r,e){for(let i=0;i0&&(h+=o?(s*v-m*l)/2:Math.sqrt(Math.pow(m-s,2)+Math.pow(v-l,2))),s=m,l=v}let d=e.points.length-3;e.points[2]=1,i>0&&Su(e.points,0,d,i),e.points[d+2]=1,Iu(e),e.size=Math.abs(h),e.start=0,e.end=e.size}function Cu(r,e,i,o){for(let s=0;s1?1:i}function _h(r){let e={type:"Feature",geometry:Om(r),properties:r.tags};return r.id!=null&&(e.id=r.id),e}function Om(r){let{type:e,geometry:i}=r;switch(e){case"Point":return{type:e,coordinates:ep(i[0],i[1])};case"MultiPoint":return{type:e,coordinates:yh(i)};case"LineString":return{type:e,coordinates:yh(i.points)};case"MultiLineString":case"Polygon":return{type:e,coordinates:i.map((o=>yh(o.points)))};case"MultiPolygon":return{type:e,coordinates:i.map((o=>o.map((s=>yh(s.points)))))}}}function yh(r){let e=[];for(let i=0;i=(i/=e)&&h=o)return null;let g=[];for(let m of r){let v=s===pi.X?m.minX:m.minY,_=s===pi.X?m.maxX:m.maxY;if(v>=i&&_=o))switch(m.type){case"Point":case"MultiPoint":Nm(m,g,i,o,s);continue;case"LineString":Vm(m,g,i,o,s,d);continue;case"MultiLineString":jm(m,g,i,o,s);continue;case"Polygon":Um(m,g,i,o,s);continue;case"MultiPolygon":Gm(m,g,i,o,s);continue}}return g.length?g:null}function Nm(r,e,i,o,s){let l=[];(function(h,d,g,m,v){for(let _=0;_=g&&T<=m&&fa(d,h[_],h[_+1],h[_+2])}})(r.geometry,l,i,o,s),l.length&&e.push(Jt(r.id,l.length===3?"Point":"MultiPoint",l,r.tags))}function Vm(r,e,i,o,s,l){let h=[];if(rp(r.geometry,h,i,o,s,!1,l.lineMetrics),h.length)if(l.lineMetrics)for(let d of h)e.push(Jt(r.id,"LineString",d,r.tags));else e.push(h.length>1?Jt(r.id,"MultiLineString",h,r.tags):Jt(r.id,"LineString",h[0],r.tags))}function jm(r,e,i,o,s){let l=[];Au(r.geometry,l,i,o,s,!1),l.length&&e.push(l.length!==1?Jt(r.id,"MultiLineString",l,r.tags):Jt(r.id,"LineString",l[0],r.tags))}function Um(r,e,i,o,s){let l=[];Au(r.geometry,l,i,o,s,!0),l.length&&e.push(Jt(r.id,"Polygon",l,r.tags))}function Gm(r,e,i,o,s){let l=[];for(let h of r.geometry){let d=[];Au(h,d,i,o,s,!0),d.length&&l.push(d)}l.length&&e.push(Jt(r.id,"MultiPolygon",l,r.tags))}function rp(r,e,i,o,s,l,h){let d=np(r),g=s===pi.X?$m:Zm,m,v,_=r.start;for(let A=0;Ai&&(v=g(d,D,L,F,O,i),h&&(d.start=_+m*v)):V>o?Y=i&&(v=g(d,D,L,F,O,i),J=!0),Y>o&&V<=o&&(v=g(d,D,L,F,O,o),J=!0),!l&&J&&(h&&(d.end=_+m*v),e.push(d),d=np(r)),h&&(_+=m)}let T=r.points.length-3,b=r.points[T],I=r.points[T+1],M=s===pi.X?b:I;M>=i&&M<=o&&fa(d.points,b,I,r.points[T+2]),T=d.points.length-3,l&&T>=3&&(d.points[T]!==d.points[0]||d.points[T+1]!==d.points[1])&&fa(d.points,d.points[0],d.points[1],d.points[2]),d.points.length&&(Iu(d),e.push(d))}function np(r){return{points:[],size:r.size,start:r.start,end:r.end}}function Au(r,e,i,o,s,l){for(let h of r)rp(h,e,i,o,s,l,!1)}function fa(r,e,i,o){r.push(e,i,o)}function $m(r,e,i,o,s,l){let h=(l-e)/(o-e);return fa(r.points,l,i+(s-i)*h,1),h}function Zm(r,e,i,o,s,l){let h=(l-i)/(s-i);return fa(r.points,e+(o-e)*h,l,1),h}function Du(r,e){let i=e.buffer/e.extent,o=r,s=Sn(r,1,-1-i,i,pi.X,-1,2,e),l=Sn(r,1,1-i,2+i,pi.X,-1,2,e);return(s||l)&&(o=Sn(r,1,-i,1+i,pi.X,-1,2,e)||[],s&&(o=op(s,1).concat(o)),l&&(o=o.concat(op(l,-1)))),o}function op(r,e){let i=[];for(let o of r)switch(o.type){case"Point":case"MultiPoint":{let s=qm(o.geometry,e);i.push(Jt(o.id,o.type,s,o.tags));continue}case"LineString":{let s=zu(o.geometry,e);i.push(Jt(o.id,o.type,s,o.tags));continue}case"MultiLineString":case"Polygon":{let s=[];for(let l of o.geometry)s.push(zu(l,e));i.push(Jt(o.id,o.type,s,o.tags));continue}case"MultiPolygon":{let s=[];for(let l of o.geometry){let h=[];for(let d of l)h.push(zu(d,e));s.push(h)}i.push(Jt(o.id,o.type,s,o.tags));continue}}return i}function qm(r,e){let i=[];for(let o=0;o0||e.addOrUpdateProperties?.length>0;if(o){let l=r[0],h=Mu({type:"FeatureCollection",features:[{type:"Feature",id:l.id,geometry:e.newGeometry,properties:s?sp(l.tags,e):l.tags}]},i);return h=Du(h,i),h}if(s){let l=[];for(let h of r){let d={...h};d.tags=sp(d.tags,e),l.push(d)}return l}return r}function sp(r,e){if(e.removeAllProperties)return{};let i={...r||{}};if(e.removeProperties)for(let o of e.removeProperties)delete i[o];if(e.addOrUpdateProperties)for(let{key:o,value:s}of e.addOrUpdateProperties)i[o]=s;return i}(function(r){r[r.X=0]="X",r[r.Y=1]="Y"})(pi||(pi={}));let Ru={minZoom:0,maxZoom:16,minPoints:2,radius:40,extent:512,nodeSize:64,log:!1,generateId:!1,reduce:null,map:r=>r};class Hm{constructor(e){this.options=Object.assign(Object.create(Ru),e),this.trees=new Array(this.options.maxZoom+1),this.stride=this.options.reduce?7:6,this.clusterProps=[],this.points=[]}load(e){let i=[];for(let o of e){if(!o.geometry)continue;let[s,l]=o.geometry.coordinates,[h,d]=[da(s),pa(l)];i.push({id:o.id,type:"Point",geometry:[h,d],tags:o.properties})}this.createIndex(i)}initialize(e){let i=[];for(let o of e)o.type==="Point"&&i.push(o);this.createIndex(i)}updateIndex(e,i,o){this.options=Object.assign(Object.create(Ru),o.clusterOptions),this.initialize(e)}createIndex(e){let{log:i,minZoom:o,maxZoom:s}=this.options;i&&console.time("total time");let l=`prepare ${e.length} points`;i&&console.time(l),this.points=e;let h=[];for(let g=0;g=o;g--){let m=Date.now();d=this.trees[g]=this.createTree(this.cluster(d,g)),i&&console.log("z%d: %d clusters in %dms",g,d.numItems,Date.now()-m)}i&&console.timeEnd("total time")}getClusters(e,i){return this.getClustersInternal(e,i).map((o=>_h(o)))}getClustersInternal(e,i){let o=((e[0]+180)%360+360)%360-180,s=Math.max(-90,Math.min(90,e[1])),l=e[2]===180?180:((e[2]+180)%360+360)%360-180,h=Math.max(-90,Math.min(90,e[3]));if(e[2]-e[0]>=360)o=-180,l=180;else if(o>l){let _=this.getClustersInternal([o,s,180,h],i),T=this.getClustersInternal([-180,s,l,h],i);return _.concat(T)}let d=this.trees[this.limitZoom(i)],g=d.range(da(o),pa(h),da(l),pa(s)),m=d.flatData,v=[];for(let _ of g){let T=this.stride*_;v.push(m[T+5]>1?Xm(m,T,this.clusterProps):this.points[m[T+3]])}return v}getChildren(e){let i=this.getOriginId(e),o=this.getOriginZoom(e),s=new Error("No cluster with the specified id: "+e),l=this.trees[o];if(!l)throw s;let h=l.flatData;if(i*this.stride>=h.length)throw s;let d=this.options.radius/(this.options.extent*Math.pow(2,o-1)),g=l.within(h[i*this.stride],h[i*this.stride+1],d),m=[];for(let v of g){let _=v*this.stride;h[_+4]===e&&m.push(h[_+5]>1?Ym(h,_,this.clusterProps):_h(this.points[h[_+3]]))}if(m.length===0)throw s;return m}getLeaves(e,i,o){let s=[];return this.appendLeaves(s,e,i=i||10,o=o||0,0),s}getTile(e,i,o){let s=this.trees[this.limitZoom(e)];if(!s)return null;let l=Math.pow(2,e),{extent:h,radius:d}=this.options,g=d/h,m=(o-g)/l,v=(o+1+g)/l,_={transformed:!0,features:[],source:null,x:i,y:o,z:e};return this.addTileFeatures(s.range((i-g)/l,m,(i+1+g)/l,v),s.flatData,i,o,l,_),i===0&&this.addTileFeatures(s.range(1-g/l,m,1,v),s.flatData,l,o,l,_),i===l-1&&this.addTileFeatures(s.range(0,m,g/l,v),s.flatData,-1,o,l,_),_}getClusterExpansionZoom(e){return this.getOriginZoom(e)}appendLeaves(e,i,o,s,l){let h=this.getChildren(i);for(let d of h){let g=d.properties;if(g?.cluster?l+g.point_count<=s?l+=g.point_count:l=this.appendLeaves(e,g.cluster_id,o,s,l):l1,v,_,T;if(m)v=ku(i,g,this.clusterProps),_=i[g],T=i[g+1];else{let M=this.points[i[g+3]];v=M.tags,[_,T]=M.geometry}let b={type:1,geometry:[[Math.round(this.options.extent*(_*l-o)),Math.round(this.options.extent*(T*l-s))]],tags:v},I;I=m||this.options.generateId?i[g+3]:this.points[i[g+3]].id,I!==void 0&&(b.id=I),h.features.push(b)}}limitZoom(e){return Math.max(this.options.minZoom,Math.min(Math.floor(+e),this.options.maxZoom+1))}cluster(e,i){let{radius:o,extent:s,reduce:l,minPoints:h}=this.options,d=o/(s*Math.pow(2,i)),g=e.flatData,m=[],v=this.stride;for(let _=0;_i&&(A+=g[L+5])}if(A>M&&A>=h){let D,L=T*M,R=b*M,F=-1,O=(_/v<<5)+(i+1)+this.points.length;for(let V of I){let Y=V*v;if(g[Y+2]<=i)continue;g[Y+2]=i;let J=g[Y+5];L+=g[Y]*J,R+=g[Y+1]*J,g[Y+4]=O,l&&(D||(D=this.map(g,_,!0),F=this.clusterProps.length,this.clusterProps.push(D)),l(D,this.map(g,Y)))}g[_+4]=O,m.push(L/A,R/A,1/0,O,-1,A),l&&m.push(F)}else{for(let D=0;D1)for(let D of I){let L=D*v;if(!(g[L+2]<=i)){g[L+2]=i;for(let R=0;R>5}getOriginZoom(e){return(e-this.points.length)%32}map(e,i,o){if(e[i+5]>1){let h=this.clusterProps[e[i+6]];return o?Object.assign({},h):h}let s=this.points[e[i+3]].tags,l=this.options.map(s);return o&&l===s?Object.assign({},l):l}}function Xm(r,e,i){return{id:r[e+3],type:"Point",tags:ku(r,e,i),geometry:[r[e],r[e+1]]}}function Ym(r,e,i){return{type:"Feature",id:r[e+3],properties:ku(r,e,i),geometry:{type:"Point",coordinates:[tp(r[e]),ip(r[e+1])]}}}function ku(r,e,i){let o=r[e+5],s=o>=1e4?`${Math.round(o/1e3)}k`:o>=1e3?Math.round(o/100)/10+"k":o,l=r[e+6],h=l===-1?{}:Object.assign({},i[l]);return Object.assign(h,{cluster:!0,cluster_id:r[e+3],point_count:o,point_count_abbreviated:s})}let Lu="geojsonvt_clip_start",Fu="geojsonvt_clip_end";function ap(r,e,i,o,s){let l=e===s.maxZoom?0:s.tolerance/((1<0&&e.size<(s?h:o))return void(i.numPoints+=e.points.length/3);let d=[];for(let g=0;gh)&&(i.numSimplified++,d.push(e.points[g],e.points[g+1])),i.numPoints++;s&&(function(g,m){let v=0;for(let _=0,T=g.length,b=T-2;_0===m)for(let _=0,T=g.length;_1&&(console.log("invalidating tiles"),console.time("invalidating")),this.invalidateTiles(i),o.debug>1&&console.timeEnd("invalidating");let[s,l,h]=[0,0,0],d=ap(e,s,l,h,o);d.source=e;let g=vh(s,l,h);if(this.tiles[g]=d,this.tileCoords.push({z:s,x:l,y:h,id:g}),o.debug){let m=`z${s}`;this.stats[m]=(this.stats[m]||0)+1,this.total++}}getClusterExpansionZoom(e){return null}getChildren(e){return null}getLeaves(e,i,o){return null}getTile(e,i,o){let{extent:s,debug:l}=this.options,h=1<1&&console.log("drilling down to z%d-%d-%d",e,i,o);let g,m=e,v=i,_=o;for(;!g&&m>0;)m--,v>>=1,_>>=1,g=this.tiles[vh(m,v,_)];return g?.source?(l>1&&(console.log("found parent tile z%d-%d-%d",m,v,_),console.time("drilling down")),this.splitTile(g.source,m,v,_,e,i,o),l>1&&console.timeEnd("drilling down"),this.tiles[d]?lp(this.tiles[d],s):null):null}splitTile(e,i,o,s,l,h,d){let g=[e,i,o,s],m=this.options,v=m.debug;for(;g.length;){s=g.pop(),o=g.pop(),i=g.pop(),e=g.pop();let _=1<1&&console.time("creation"),b=this.tiles[T]=ap(e,i,o,s,m),this.tileCoords.push({z:i,x:o,y:s,id:T}),v)){v>1&&(console.log("tile z%d-%d-%d (features: %d, points: %d, simplified: %d)",i,o,s,b.numFeatures,b.numPoints,b.numSimplified),console.timeEnd("creation"));let J=`z${i}`;this.stats[J]=(this.stats[J]||0)+1,this.total++}if(b.source=e,l==null){if(i===m.indexMaxZoom||b.numPoints<=m.indexMaxPoints)continue}else{if(i===m.maxZoom||i===l)continue;if(l!=null){let J=l-i;if(o!==h>>J||s!==d>>J)continue}}if(b.source=null,!e.length)continue;v>1&&console.time("clipping");let I=.5*m.buffer/m.extent,M=.5-I,A=.5+I,D=1+I,L=null,R=null,F=null,O=null,V=Sn(e,_,o-I,o+A,pi.X,b.minX,b.maxX,m),Y=Sn(e,_,o+M,o+D,pi.X,b.minX,b.maxX,m);V&&(L=Sn(V,_,s-I,s+A,pi.Y,b.minY,b.maxY,m),R=Sn(V,_,s+M,s+D,pi.Y,b.minY,b.maxY,m)),Y&&(F=Sn(Y,_,s-I,s+A,pi.Y,b.minY,b.maxY,m),O=Sn(Y,_,s+M,s+D,pi.Y,b.minY,b.maxY,m)),v>1&&console.timeEnd("clipping"),g.push(L||[],i+1,2*o,2*s),g.push(R||[],i+1,2*o,2*s+1),g.push(F||[],i+1,2*o+1,2*s),g.push(O||[],i+1,2*o+1,2*s+1)}}invalidateTiles(e){if(!e.length)return;let i=this.options,{debug:o}=i,s=1/0,l=-1/0,h=1/0,d=-1/0;for(let v of e)s=Math.min(s,v.minX),l=Math.max(l,v.maxX),h=Math.min(h,v.minY),d=Math.max(d,v.maxY);let g=i.buffer/i.extent,m=new Set;for(let v in this.tiles){let _=this.tiles[v],T=1<<_.z,b=(_.x-g)/T,I=(_.x+1+g)/T,M=(_.y-g)/T,A=(_.y+1+g)/T;if(l=I||d=A)continue;let D=!1;for(let L of e)if(L.maxX>=b&&L.minX=M&&L.minY1&&console.log("invalidate tile z%d-%d-%d (features: %d, points: %d, simplified: %d)",_.z,_.x,_.y,_.numFeatures,_.numPoints,_.numSimplified);let L=`z${_.z}`;this.stats[L]=(this.stats[L]||0)-1,this.total--}delete this.tiles[v],m.add(v)}}m.size&&(this.tileCoords=this.tileCoords.filter((v=>!m.has(v.id))))}}function vh(r,e,i){return 32*((1<i.id)),this.index=e.index,this.hasDependencies=!1,this.patternFeatures=[],this.lineClipsArray=[],this.gradients={};for(let i of this.layers)this.gradients[i.id]={};this.layoutVertexArray=new X,this.layoutVertexArray2=new Z,this.indexArray=new ue,this.programConfigurations=new vr(e.layers,e.zoom),this.segments=new we,this.maxLineLength=0,this.stateDependentLayerIds=this.layers.filter((i=>i.isStateDependent())).map((i=>i.id))}populate(e,i,o){this.hasDependencies=uh("line",this.layers,i)||this.hasLineDasharray(this.layers);let s=this.layers[0].layout.get("line-sort-key"),l=!s.isConstant(),h=[];for(let{feature:d,id:g,index:m,sourceLayerIndex:v}of e){let _=this.layers[0]._featureFilter.needGeometry,T=Zr(d,_);if(!this.layers[0]._featureFilter.filter(new ct(this.zoom),T,o))continue;let b=l?s.evaluate(T,{},o):void 0,I={id:g,properties:d.properties,type:d.type,sourceLayerIndex:v,index:m,geometry:_?T.geometry:$r(d),patterns:{},dashes:{},sortKey:b};h.push(I)}l&&h.sort(((d,g)=>d.sortKey-g.sortKey));for(let d of h){let{geometry:g,index:m,sourceLayerIndex:v}=d;this.hasDependencies?(uh("line",this.layers,i)?_u("line",this.layers,d,{zoom:this.zoom},i):this.hasLineDasharray(this.layers)&&this.addLineDashDependencies(this.layers,d,this.zoom,i),this.patternFeatures.push(d)):this.addFeature(d,g,m,o,{},{},i.subdivisionGranularity),i.featureIndex.insert(e[m].feature,g,m,v,this.index)}}update(e,i,o,s){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(e,i,this.stateDependentLayers,{imagePositions:o,dashPositions:s})}addFeatures(e,i,o,s){for(let l of this.patternFeatures)this.addFeature(l,l.geometry,l.index,i,o,s,e.subdivisionGranularity)}isEmpty(){return this.layoutVertexArray.length===0}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload}upload(e){this.uploaded||(this.layoutVertexArray2.length!==0&&(this.layoutVertexBuffer2=e.createVertexBuffer(this.layoutVertexArray2,og)),this.layoutVertexBuffer=e.createVertexBuffer(this.layoutVertexArray,rg),this.indexBuffer=e.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(e),this.uploaded=!0}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy())}lineFeatureClips(e){if(e.properties&&Object.hasOwn(e.properties,Lu)&&Object.hasOwn(e.properties,Fu))return{start:+e.properties[Lu],end:+e.properties[Fu]}}addFeature(e,i,o,s,l,h,d){let g=this.layers[0].layout,m=g.get("line-join").evaluate(e,{}),v=g.get("line-cap").evaluate(e,{}),_=g.get("line-miter-limit").evaluate(e,{}),T=g.get("line-round-limit").evaluate(e,{});this.lineClips=this.lineFeatureClips(e);for(let b of i)this.addLine(b,e,m,v,_,T,s,d);this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,e,o,{imagePositions:l,dashPositions:h,canonical:s})}addLine(e,i,o,s,l,h,d,g){if(this.distance=0,this.scaledDistance=0,this.totalDistance=0,e=os(e,d?g.line.getGranularityForZoomLevel(d.z):1),this.lineClips){this.lineClipsArray.push(this.lineClips);for(let R=0;R=2&&e[v-1].equals(e[v-2]);)v--;let _=0;for(;_0;if(re&&R>_){let ne=I.dist(M);if(ne>2*T){let ie=I.sub(I.sub(M)._mult(T/ne)._round());this.updateDistance(M,ie),this.addCurrentVertex(ie,D,0,0,b),M=ie}}let ae=M&&A,le=ae?o:m?"butt":s;if(ae&&le==="round"&&(Yl&&(le="bevel"),le==="bevel"&&(Y>2&&(le="flipbevel"),Y100)F=L.mult(-1);else{let ne=Y*D.add(L).mag()/D.sub(L).mag();F._perp()._mult(ne*(te?-1:1))}this.addCurrentVertex(I,F,0,0,b),this.addCurrentVertex(I,F.mult(-1),0,0,b)}else if(le==="bevel"||le==="fakeround"){let ne=-Math.sqrt(Y*Y-1),ie=te?ne:0,fe=te?0:ne;if(M&&this.addCurrentVertex(I,D,ie,fe,b),le==="fakeround"){let xe=Math.round(180*J/Math.PI/20);for(let ye=1;ye2*T){let ie=I.add(A.sub(I)._mult(T/ne)._round());this.updateDistance(I,ie),this.addCurrentVertex(ie,L,0,0,b),I=ie}}}}addCurrentVertex(e,i,o,s,l,h=!1){let d=i.y*s-i.x,g=-i.y-i.x*s;this.addHalfVertex(e,i.x+i.y*o,i.y-i.x*o,h,!1,o,l),this.addHalfVertex(e,d,g,h,!0,-s,l),this.distance>hp/2&&this.totalDistance===0&&(this.distance=0,this.updateScaledDistance(),this.addCurrentVertex(e,i,o,s,l,h))}addHalfVertex({x:e,y:i},o,s,l,h,d,g){let m=.5*(this.lineClips?this.scaledDistance*(hp-1):this.scaledDistance);this.layoutVertexArray.emplaceBack((e<<1)+(l?1:0),(i<<1)+(h?1:0),Math.round(63*o)+128,Math.round(63*s)+128,1+(d===0?0:d<0?-1:1)|(63&m)<<2,m>>6),this.lineClips&&this.layoutVertexArray2.emplaceBack((this.scaledDistance-this.lineClips.start)/(this.lineClips.end-this.lineClips.start),this.lineClipsArray.length);let v=g.vertexLength++;this.e1>=0&&this.e2>=0&&(this.indexArray.emplaceBack(this.e1,v,this.e2),g.primitiveLength++),h?this.e2=v:this.e1=v}updateScaledDistance(){this.scaledDistance=this.lineClips?this.lineClips.start+(this.lineClips.end-this.lineClips.start)*this.distance/this.totalDistance:this.distance}updateDistance(e,i){this.distance+=e.dist(i),this.updateScaledDistance()}hasLineDasharray(e){for(let i of e){let o=i.paint.get("line-dasharray");if(o&&!o.isConstant())return!0}return!1}addLineDashDependencies(e,i,o,s){for(let l of e){let h=l.paint.get("line-dasharray");if(!h||h.value.kind==="constant")continue;let d=l.layout.get("line-cap").evaluate(i,{})==="round",g={dasharray:h.value.evaluate({zoom:o-1},i,{}),round:d},m={dasharray:h.value.evaluate({zoom:o},i,{}),round:d},v={dasharray:h.value.evaluate({zoom:o+1},i,{}),round:d},_=`${g.dasharray.join(",")},${g.round}`,T=`${m.dasharray.join(",")},${m.round}`,b=`${v.dasharray.join(",")},${v.round}`;s.dashDependencies[_]=g,s.dashDependencies[T]=m,s.dashDependencies[b]=v,i.dashes[l.id]={min:_,mid:T,max:b}}}}let up,dp;Pe("LineBucket",Ou,{omit:["layers","patternFeatures"]});var pp={get paint(){return dp=dp||new ui({"line-opacity":new Ce(ce.paint_line["line-opacity"]),"line-color":new Ce(ce.paint_line["line-color"]),"line-translate":new Ie(ce.paint_line["line-translate"]),"line-translate-anchor":new Ie(ce.paint_line["line-translate-anchor"]),"line-width":new Ce(ce.paint_line["line-width"]),"line-gap-width":new Ce(ce.paint_line["line-gap-width"]),"line-offset":new Ce(ce.paint_line["line-offset"]),"line-blur":new Ce(ce.paint_line["line-blur"]),"line-dasharray":new Or(ce.paint_line["line-dasharray"]),"line-pattern":new Or(ce.paint_line["line-pattern"]),"line-gradient":new oo(ce.paint_line["line-gradient"])})},get layout(){return up=up||new ui({"line-cap":new Ce(ce.layout_line["line-cap"]),"line-join":new Ce(ce.layout_line["line-join"]),"line-miter-limit":new Ce(ce.layout_line["line-miter-limit"]),"line-round-limit":new Ce(ce.layout_line["line-round-limit"]),"line-sort-key":new Ce(ce.layout_line["line-sort-key"])})}};class ag extends Ce{possiblyEvaluate(e,i){return i=new ct(Math.floor(i.zoom),{now:i.now,fadeDuration:i.fadeDuration,zoomHistory:i.zoomHistory,transition:i.transition}),super.possiblyEvaluate(e,i)}evaluate(e,i,o,s){return i=Oi({},i,{zoom:Math.floor(i.zoom)}),super.evaluate(e,i,o,s)}}let xh;class lg extends Ui{constructor(e,i){super(e,pp,i),this.gradientVersion=0,xh||(xh=new ag(pp.paint.properties["line-width"].specification),xh.useIntegerZoom=!0)}_handleSpecialPaintPropertyUpdate(e){if(e==="line-gradient"){let i=this.gradientExpression();this.stepInterpolant=!!(function(o){return o._styleExpression!==void 0})(i)&&i._styleExpression.expression instanceof qn,this.gradientVersion=(this.gradientVersion+1)%Number.MAX_SAFE_INTEGER}}gradientExpression(){return this._transitionablePaint._values["line-gradient"].value.expression}recalculate(e,i){super.recalculate(e,i),this.paint._values["line-floorwidth"]=xh.possiblyEvaluate(this._transitioningPaint._values["line-width"].value,e)}createBucket(e){return new Ou(e)}queryRadius(e){let i=e,o=fp(la("line-width",this,i),la("line-gap-width",this,i)),s=la("line-offset",this,i);return o/2+Math.abs(s)+ch(this.paint.get("line-translate"))}queryIntersectsFeature({queryGeometry:e,feature:i,featureState:o,geometry:s,transform:l,pixelsToTileUnits:h}){let d=hh(e,this.paint.get("line-translate"),this.paint.get("line-translate-anchor"),-l.bearingInRadians,h),g=h/2*fp(this.paint.get("line-width").evaluate(i,o),this.paint.get("line-gap-width").evaluate(i,o)),m=this.paint.get("line-offset").evaluate(i,o);return m&&(s=(function(v,_){let T=[];for(let b of v){let I=Kf(b),M=[];for(let A=0;A=3){for(let I of b)if(aa(v,I))return!0}if(Hf(v,b,T))return!0}return!1})(d,s,g)}isTileClipped(){return!0}}function fp(r,e){return e>0?e+2*r:r}let cg=ht([{name:"a_pos_offset",components:4,type:"Int16"},{name:"a_data",components:4,type:"Uint16"},{name:"a_pixeloffset",components:4,type:"Int16"}],4),hg=ht([{name:"a_projected_pos",components:3,type:"Float32"}],4);ht([{name:"a_fade_opacity",components:1,type:"Uint32"}],4);let ug=ht([{name:"a_placed",components:2,type:"Uint8"},{name:"a_shift",components:2,type:"Float32"},{name:"a_box_real",components:2,type:"Int16"}]);ht([{type:"Int16",name:"anchorPointX"},{type:"Int16",name:"anchorPointY"},{type:"Int16",name:"x1"},{type:"Int16",name:"y1"},{type:"Int16",name:"x2"},{type:"Int16",name:"y2"},{type:"Uint32",name:"featureIndex"},{type:"Uint16",name:"sourceLayerIndex"},{type:"Uint16",name:"bucketIndex"}]);let mp=ht([{name:"a_pos",components:2,type:"Int16"},{name:"a_anchor_pos",components:2,type:"Int16"},{name:"a_extrude",components:2,type:"Int16"}],4),dg=ht([{name:"a_pos",components:2,type:"Float32"},{name:"a_radius",components:1,type:"Float32"},{name:"a_flags",components:2,type:"Int16"}],4);function pg(r,e,i){let o=e.layout.get("text-transform").evaluate(i,{});return o==="uppercase"?r=r.toLocaleUpperCase():o==="lowercase"&&(r=r.toLocaleLowerCase()),gr.applyArabicShaping&&(r=gr.applyArabicShaping(r)),r}function fg(r,e,i){for(let o of r.sections)o.text=pg(o.text,e,i);return r}ht([{name:"triangle",components:3,type:"Uint16"}]),ht([{type:"Int16",name:"anchorX"},{type:"Int16",name:"anchorY"},{type:"Uint16",name:"glyphStartIndex"},{type:"Uint16",name:"numGlyphs"},{type:"Uint32",name:"vertexStartIndex"},{type:"Uint32",name:"lineStartIndex"},{type:"Uint32",name:"lineLength"},{type:"Uint16",name:"segment"},{type:"Uint16",name:"lowerSize"},{type:"Uint16",name:"upperSize"},{type:"Float32",name:"lineOffsetX"},{type:"Float32",name:"lineOffsetY"},{type:"Uint8",name:"writingMode"},{type:"Uint8",name:"placedOrientation"},{type:"Uint8",name:"hidden"},{type:"Uint32",name:"crossTileID"},{type:"Int16",name:"associatedIconIndex"}]),ht([{type:"Int16",name:"anchorX"},{type:"Int16",name:"anchorY"},{type:"Int16",name:"rightJustifiedTextSymbolIndex"},{type:"Int16",name:"centerJustifiedTextSymbolIndex"},{type:"Int16",name:"leftJustifiedTextSymbolIndex"},{type:"Int16",name:"verticalPlacedTextSymbolIndex"},{type:"Int16",name:"placedIconSymbolIndex"},{type:"Int16",name:"verticalPlacedIconSymbolIndex"},{type:"Uint16",name:"key"},{type:"Uint16",name:"textBoxStartIndex"},{type:"Uint16",name:"textBoxEndIndex"},{type:"Uint16",name:"verticalTextBoxStartIndex"},{type:"Uint16",name:"verticalTextBoxEndIndex"},{type:"Uint16",name:"iconBoxStartIndex"},{type:"Uint16",name:"iconBoxEndIndex"},{type:"Uint16",name:"verticalIconBoxStartIndex"},{type:"Uint16",name:"verticalIconBoxEndIndex"},{type:"Uint16",name:"featureIndex"},{type:"Uint16",name:"numHorizontalGlyphVertices"},{type:"Uint16",name:"numVerticalGlyphVertices"},{type:"Uint16",name:"numIconVertices"},{type:"Uint16",name:"numVerticalIconVertices"},{type:"Uint16",name:"useRuntimeCollisionCircles"},{type:"Uint32",name:"crossTileID"},{type:"Float32",name:"textBoxScale"},{type:"Float32",name:"collisionCircleDiameter"},{type:"Uint16",name:"textAnchorOffsetStartIndex"},{type:"Uint16",name:"textAnchorOffsetEndIndex"}]),ht([{type:"Float32",name:"offsetX"}]),ht([{type:"Int16",name:"x"},{type:"Int16",name:"y"},{type:"Int16",name:"tileUnitDistanceFromAnchor"}]),ht([{type:"Uint16",name:"textAnchor"},{type:"Float32",components:2,name:"textOffset"}]);var Vt=24;let Kl={"!":"\uFE15","#":"\uFF03",$:"\uFF04","%":"\uFF05","&":"\uFF06","(":"\uFE35",")":"\uFE36","*":"\uFF0A","+":"\uFF0B",",":"\uFE10","-":"\uFE32",".":"\u30FB","/":"\uFF0F",":":"\uFE13",";":"\uFE14","<":"\uFE3F","=":"\uFF1D",">":"\uFE40","?":"\uFE16","@":"\uFF20","[":"\uFE47","\\":"\uFF3C","]":"\uFE48","^":"\uFF3E",_:"\uFE33","`":"\uFF40","{":"\uFE37","|":"\u2015","}":"\uFE38","~":"\uFF5E","\xA2":"\uFFE0","\xA3":"\uFFE1","\xA5":"\uFFE5","\xA6":"\uFFE4","\xAC":"\uFFE2","\xAF":"\uFFE3","\u2013":"\uFE32","\u2014":"\uFE31","\u2018":"\uFE43","\u2019":"\uFE44","\u201C":"\uFE41","\u201D":"\uFE42","\u2026":"\uFE19","\u22EF":"\uFE19","\u2027":"\u30FB","\u20A9":"\uFFE6","\u3001":"\uFE11","\u3002":"\uFE12","\u3008":"\uFE3F","\u3009":"\uFE40","\u300A":"\uFE3D","\u300B":"\uFE3E","\u300C":"\uFE41","\u300D":"\uFE42","\u300E":"\uFE43","\u300F":"\uFE44","\u3010":"\uFE3B","\u3011":"\uFE3C","\u3014":"\uFE39","\u3015":"\uFE3A","\u3016":"\uFE17","\u3017":"\uFE18","\uFF01":"\uFE15","\uFF08":"\uFE35","\uFF09":"\uFE36","\uFF0C":"\uFE10","\uFF0D":"\uFE32","\uFF0E":"\u30FB","\uFF1A":"\uFE13","\uFF1B":"\uFE14","\uFF1C":"\uFE3F","\uFF1E":"\uFE40","\uFF1F":"\uFE16","\uFF3B":"\uFE47","\uFF3D":"\uFE48","\uFF3F":"\uFE33","\uFF5B":"\uFE37","\uFF5C":"\u2015","\uFF5D":"\uFE38","\uFF5F":"\uFE35","\uFF60":"\uFE36","\uFF61":"\uFE12","\uFF62":"\uFE41","\uFF63":"\uFE42"},mg={10:!0,32:!0,38:!0,41:!0,43:!0,45:!0,47:!0,173:!0,183:!0,8203:!0,8208:!0,8211:!0,8231:!0},gg={40:!0};function gp(r,e,i,o,s,l){if("fontStack"in e){let h=i[e.fontStack],d=h?.[r];return d?d.metrics.advance*e.scale+s:0}{let h=o[e.imageName];return h?h.displaySize[0]*e.scale*Vt/l+s:0}}function _p(r,e,i,o){let s=Math.pow(r-e,2);return o?rMath.max(e,this.sections[i].scale)),0)}getMaxImageSize(e){let i=0,o=0;for(let s=0;so)))}addImageSection(e){let i=e.image?e.image.name:"";if(i.length===0)return void Wt("Can't add FormattedSection with an empty image.");let o=this.getNextImageSectionCharCode();o?(this.text+=String.fromCharCode(o),this.sections.push({scale:1,verticalAlign:e.verticalAlign||"bottom",imageName:i}),this.sectionIndex.push(this.sections.length-1)):Wt("Reached maximum number of images 6401")}getNextImageSectionCharCode(){return this.imageSectionID?this.imageSectionID>=63743?null:++this.imageSectionID:(this.imageSectionID=57344,this.imageSectionID)}determineLineBreaks(e,i,o,s,l){let h=[],d=this.determineAverageLineWidth(e,i,o,s,l),g=this.hasZeroWidthSpaces(),m=0,v=0,_=this.text[Symbol.iterator](),T=_.next(),b=this.text[Symbol.iterator]();b.next();let I=b.next(),M=this.text[Symbol.iterator]();M.next(),M.next();let A=M.next();for(;!T.done;){let D=this.getSection(v),L=T.value.codePointAt(0);if(Jc(L)||(m+=gp(L,D,o,s,e,l)),!I.done){let R=ou(L),F=I.value.codePointAt(0);(mg[L]||R||"imageName"in D||!A.done&&gg[F])&&h.push(yp(v+1,m,d,h,_g(L,F,R&&g),!1))}v++,T=_.next(),I=b.next(),A=M.next()}return vp(yp(this.length(),m,d,h,0,!0))}determineAverageLineWidth(e,i,o,s,l){let h=0,d=0;for(let g of this.text){let m=this.getSection(d);h+=gp(g.codePointAt(0),m,o,s,e,l),d++}return h/Math.max(1,Math.ceil(h/i))}}let Nu=4294967296,xp=1/Nu,bp=typeof TextDecoder>"u"?null:new TextDecoder("utf-8");class bh{constructor(e=new Uint8Array(16)){this.buf=ArrayBuffer.isView(e)?e:new Uint8Array(e),this.dataView=new DataView(this.buf.buffer),this.pos=0,this.type=0,this.length=this.buf.length}readFields(e,i,o=this.length){for(;this.pos>3,h=this.pos;this.type=7&s,e(l,i,this),this.pos===h&&this.skip(s)}return i}readMessage(e,i){return this.readFields(e,i,this.readVarint()+this.pos)}readFixed32(){let e=this.dataView.getUint32(this.pos,!0);return this.pos+=4,e}readSFixed32(){let e=this.dataView.getInt32(this.pos,!0);return this.pos+=4,e}readFixed64(){let e=this.dataView.getUint32(this.pos,!0)+this.dataView.getUint32(this.pos+4,!0)*Nu;return this.pos+=8,e}readSFixed64(){let e=this.dataView.getUint32(this.pos,!0)+this.dataView.getInt32(this.pos+4,!0)*Nu;return this.pos+=8,e}readFloat(){let e=this.dataView.getFloat32(this.pos,!0);return this.pos+=4,e}readDouble(){let e=this.dataView.getFloat64(this.pos,!0);return this.pos+=8,e}readVarint(e){let i=this.buf,o,s;return s=i[this.pos++],o=127&s,s<128?o:(s=i[this.pos++],o|=(127&s)<<7,s<128?o:(s=i[this.pos++],o|=(127&s)<<14,s<128?o:(s=i[this.pos++],o|=(127&s)<<21,s<128?o:(s=i[this.pos],o|=(15&s)<<28,(function(l,h,d){let g=d.buf,m,v;if(v=g[d.pos++],m=(112&v)>>4,v<128||(v=g[d.pos++],m|=(127&v)<<3,v<128)||(v=g[d.pos++],m|=(127&v)<<10,v<128)||(v=g[d.pos++],m|=(127&v)<<17,v<128)||(v=g[d.pos++],m|=(127&v)<<24,v<128)||(v=g[d.pos++],m|=(1&v)<<31,v<128))return ga(l,m,h);throw new Error("Expected varint not more than 10 bytes")})(o,e,this)))))}readVarint64(){return this.readVarint(!0)}readSVarint(){let e=this.readVarint();return e%2==1?(e+1)/-2:e/2}readBoolean(){return!!this.readVarint()}readString(){let e=this.readVarint()+this.pos,i=this.pos;return this.pos=e,e-i>=12&&bp?bp.decode(this.buf.subarray(i,e)):(function(o,s,l){let h="",d=s;for(;d239?4:g>223?3:g>191?2:1;if(d+b>l)break;b===1?g<128&&(T=g):b===2?(m=o[d+1],(192&m)==128&&(T=(31&g)<<6|63&m,T<=127&&(T=null))):b===3?(m=o[d+1],v=o[d+2],(192&m)==128&&(192&v)==128&&(T=(15&g)<<12|(63&m)<<6|63&v,(T<=2047||T>=55296&&T<=57343)&&(T=null))):b===4&&(m=o[d+1],v=o[d+2],_=o[d+3],(192&m)==128&&(192&v)==128&&(192&_)==128&&(T=(15&g)<<18|(63&m)<<12|(63&v)<<6|63&_,(T<=65535||T>=1114112)&&(T=null))),T===null?(T=65533,b=1):T>65535&&(T-=65536,h+=String.fromCharCode(T>>>10&1023|55296),T=56320|1023&T),h+=String.fromCharCode(T),d+=b}return h})(this.buf,i,e)}readBytes(){let e=this.readVarint()+this.pos,i=this.buf.subarray(this.pos,e);return this.pos=e,i}readPackedVarint(e=[],i){let o=this.readPackedEnd();for(;this.pos127;);else if(i===2)this.pos=this.readVarint()+this.pos;else if(i===5)this.pos+=4;else{if(i!==1)throw new Error(`Unimplemented type: ${i}`);this.pos+=8}}writeTag(e,i){this.writeVarint(e<<3|i)}realloc(e){let i=this.length||16;for(;i268435455||e<0?(function(i,o){let s,l;if(i>=0?(s=i%4294967296|0,l=i/4294967296|0):(s=~(-i%4294967296),l=~(-i/4294967296),4294967295^s?s=s+1|0:(s=0,l=l+1|0)),i>=18446744073709552e3||i<-18446744073709552e3)throw new Error("Given varint doesn't fit into 10 bytes");o.realloc(10),(function(h,d,g){g.buf[g.pos++]=127&h|128,h>>>=7,g.buf[g.pos++]=127&h|128,h>>>=7,g.buf[g.pos++]=127&h|128,h>>>=7,g.buf[g.pos++]=127&h|128,g.buf[g.pos]=127&(h>>>=7)})(s,0,o),(function(h,d){let g=(7&h)<<4;d.buf[d.pos++]|=g|((h>>>=3)?128:0),h&&(d.buf[d.pos++]=127&h|((h>>>=7)?128:0),h&&(d.buf[d.pos++]=127&h|((h>>>=7)?128:0),h&&(d.buf[d.pos++]=127&h|((h>>>=7)?128:0),h&&(d.buf[d.pos++]=127&h|((h>>>=7)?128:0),h&&(d.buf[d.pos++]=127&h)))))})(l,o)})(e,this):(this.realloc(4),this.buf[this.pos++]=127&e|(e>127?128:0),e<=127||(this.buf[this.pos++]=127&(e>>>=7)|(e>127?128:0),e<=127||(this.buf[this.pos++]=127&(e>>>=7)|(e>127?128:0),e<=127||(this.buf[this.pos++]=e>>>7&127))))}writeSVarint(e){this.writeVarint(e<0?2*-e-1:2*e)}writeBoolean(e){this.writeVarint(+e)}writeString(e){e=String(e),this.realloc(4*e.length),this.pos++;let i=this.pos;this.pos=(function(s,l,h){for(let d,g,m=0;m55295&&d<57344){if(!g){d>56319||m+1===l.length?(s[h++]=239,s[h++]=191,s[h++]=189):g=d;continue}if(d<56320){s[h++]=239,s[h++]=191,s[h++]=189,g=d;continue}d=g-55296<<10|d-56320|65536,g=null}else g&&(s[h++]=239,s[h++]=191,s[h++]=189,g=null);d<128?s[h++]=d:(d<2048?s[h++]=d>>6|192:(d<65536?s[h++]=d>>12|224:(s[h++]=d>>18|240,s[h++]=d>>12&63|128),s[h++]=d>>6&63|128),s[h++]=63&d|128)}return h})(this.buf,e,this.pos);let o=this.pos-i;o>=128&&wp(i,o,this),this.pos=i-1,this.writeVarint(o),this.pos+=o}writeFloat(e){this.realloc(4),this.dataView.setFloat32(this.pos,e,!0),this.pos+=4}writeDouble(e){this.realloc(8),this.dataView.setFloat64(this.pos,e,!0),this.pos+=8}writeBytes(e){let i=e.length;this.writeVarint(i),this.realloc(i);for(let o=0;o=128&&wp(o,s,this),this.pos=o-1,this.writeVarint(s),this.pos+=s}writeMessage(e,i,o){this.writeTag(e,2),this.writeRawMessage(i,o)}writePackedVarint(e,i){i.length&&this.writeMessage(e,yg,i)}writePackedSVarint(e,i){i.length&&this.writeMessage(e,vg,i)}writePackedBoolean(e,i){i.length&&this.writeMessage(e,wg,i)}writePackedFloat(e,i){i.length&&this.writeMessage(e,xg,i)}writePackedDouble(e,i){i.length&&this.writeMessage(e,bg,i)}writePackedFixed32(e,i){i.length&&this.writeMessage(e,Tg,i)}writePackedSFixed32(e,i){i.length&&this.writeMessage(e,Pg,i)}writePackedFixed64(e,i){i.length&&this.writeMessage(e,Sg,i)}writePackedSFixed64(e,i){i.length&&this.writeMessage(e,Ig,i)}writeBytesField(e,i){this.writeTag(e,2),this.writeBytes(i)}writeFixed32Field(e,i){this.writeTag(e,5),this.writeFixed32(i)}writeSFixed32Field(e,i){this.writeTag(e,5),this.writeSFixed32(i)}writeFixed64Field(e,i){this.writeTag(e,1),this.writeFixed64(i)}writeSFixed64Field(e,i){this.writeTag(e,1),this.writeSFixed64(i)}writeVarintField(e,i){this.writeTag(e,0),this.writeVarint(i)}writeSVarintField(e,i){this.writeTag(e,0),this.writeSVarint(i)}writeStringField(e,i){this.writeTag(e,2),this.writeString(i)}writeFloatField(e,i){this.writeTag(e,5),this.writeFloat(i)}writeDoubleField(e,i){this.writeTag(e,1),this.writeDouble(i)}writeBooleanField(e,i){this.writeVarintField(e,+i)}}function ga(r,e,i){return i?4294967296*e+(r>>>0):4294967296*(e>>>0)+(r>>>0)}function wp(r,e,i){let o=e<=16383?1:e<=2097151?2:e<=268435455?3:Math.floor(Math.log(e)/(7*Math.LN2));i.realloc(o);for(let s=i.pos-1;s>=r;s--)i.buf[s+o]=i.buf[s]}function yg(r,e){for(let i=0;id.h-h.h));let o=[{x:0,y:0,w:Math.max(Math.ceil(Math.sqrt(e/.95)),i),h:1/0}],s=0,l=0;for(let h of r)for(let d=o.length-1;d>=0;d--){let g=o[d];if(!(h.w>g.w||h.h>g.h)){if(h.x=g.x,h.y=g.y,l=Math.max(l,h.y+h.h),s=Math.max(s,h.x+h.w),h.w===g.w&&h.h===g.h){let m=o.pop();m&&dM.toCodeUnitIndex(Y)));let V=L(M.toString(),D);for(let Y of V){let J=[...Y].map((()=>0));A.push(new ma(Y,M.sections,J))}}else if(R){A=[],D=D.map((re=>M.toCodeUnitIndex(re)));let V=0,Y=[];for(let re of M.text)Y.push(...Array(re.length).fill(M.sectionIndex[V])),V++;let J=R(M.text,Y,D);for(let re of J){let te=[],ae="";for(let le of re[0])te.push(re[1][ae.length]),ae+=le;A.push(new ma(re[0],M.sections,te))}}else A=(function(V,Y){let J=[],re=0;for(let te of Y)J.push(V.substring(re,te)),re=te;return rem){let v=Math.ceil(l/m);s*=v/h,h=v}return{x1:o,y1:s,x2:o+l,y2:s+h}}function Mp(r,e,i,o,s,l){let h=r.image,d;if(h.content){let A=h.content,D=h.pixelRatio||1;d=[A[0]/D,A[1]/D,h.displaySize[0]-A[2]/D,h.displaySize[1]-A[3]/D]}let g=e.left*l,m=e.right*l,v,_,T,b;i==="width"||i==="both"?(b=s[0]+g-o[3],_=s[0]+m+o[1]):(b=s[0]+(g+m-h.displaySize[0])/2,_=b+h.displaySize[0]);let I=e.top*l,M=e.bottom*l;return i==="height"||i==="both"?(v=s[1]+I-o[0],T=s[1]+M+o[2]):(v=s[1]+(I+M-h.displaySize[1])/2,T=v+h.displaySize[1]),{image:h,top:v,right:_,bottom:T,left:b,collisionPadding:d}}Pe("ImagePosition",Vu),Pe("ImageAtlas",Pp),k.ax=void 0,(ao=k.ax||(k.ax={}))[ao.none=0]="none",ao[ao.horizontal=1]="horizontal",ao[ao.vertical=2]="vertical",ao[ao.horizontalOnly=3]="horizontalOnly";let In=128,lo=32640;function Ep(r,e){let{expression:i}=e;if(i.kind==="constant")return{kind:"constant",layoutSize:i.evaluate(new ct(r+1))};if(i.kind==="source")return{kind:"source"};{let{zoomStops:o,interpolationType:s}=i,l=0;for(;lh.id)),this.index=e.index,this.pixelRatio=e.pixelRatio,this.sourceLayerIndex=e.sourceLayerIndex,this.hasDependencies=!1,this.hasRTLText=!1,this.sortKeyRanges=[],this.collisionCircleArray=[];let i=this.layers[0]._unevaluatedLayout._values;this.textSizeData=Ep(this.zoom,i["text-size"]),this.iconSizeData=Ep(this.zoom,i["icon-size"]);let o=this.layers[0].layout,s=o.get("symbol-sort-key"),l=o.get("symbol-z-order");this.canOverlap=Uu(o,"text-overlap","text-allow-overlap")!=="never"||Uu(o,"icon-overlap","icon-allow-overlap")!=="never"||o.get("text-ignore-placement")||o.get("icon-ignore-placement"),this.sortFeaturesByKey=l!=="viewport-y"&&!s.isConstant(),this.sortFeaturesByY=(l==="viewport-y"||l==="auto"&&!this.sortFeaturesByKey)&&this.canOverlap,o.get("symbol-placement")==="point"&&(this.writingModes=o.get("text-writing-mode").map((h=>k.ax[h]))),this.stateDependentLayerIds=this.layers.filter((h=>h.isStateDependent())).map((h=>h.id)),this.sourceID=e.sourceID}createArrays(){this.text=new $u(new vr(this.layers,this.zoom,(e=>e.startsWith("text")))),this.icon=new $u(new vr(this.layers,this.zoom,(e=>e.startsWith("icon")))),this.glyphOffsetArray=new P,this.lineVertexArray=new S,this.symbolInstances=new w,this.textAnchorOffsets=new C}calculateGlyphDependencies(e,i,o,s,l){for(let h of e)if(i[h.codePointAt(0)]=!0,(o||s)&&l){let d=Kl[h];d&&(i[d.codePointAt(0)]=!0)}}populate(e,i,o){var s;let l=this.layers[0],h=l.layout,d=h.get("text-font"),g=h.get("text-field"),m=h.get("icon-image"),v=(g.value.kind!=="constant"||g.value.value instanceof xi&&!g.value.value.isEmpty()||g.value.value.toString().length>0)&&(d.value.kind!=="constant"||d.value.value.length>0),_=m.value.kind!=="constant"||!!m.value.value||Object.keys(m.parameters).length>0,T=h.get("symbol-sort-key");if(this.features=[],!v&&!_)return;let b=i.iconDependencies,I=i.glyphDependencies,M=i.availableImages,A=new ct(this.zoom);for(let{feature:D,id:L,index:R,sourceLayerIndex:F}of e){let O=l._featureFilter.needGeometry,V=Zr(D,O);if(!l._featureFilter.filter(A,V,o))continue;let Y,J;if(O||(V.geometry=$r(D)),v){let te=l.getValueAndResolveTokens("text-field",V,o,M),ae=xi.factory(te);this.hasRTLText||(this.hasRTLText=Bg(ae)),(!this.hasRTLText||gr.getRTLTextPluginStatus()==="unavailable"||this.hasRTLText&&gr.isParsed())&&(Y=fg(ae,l,V))}if(_){let te=l.getValueAndResolveTokens("icon-image",V,o,M);J=te instanceof Ci?te:Ci.fromString(te)}if(!Y&&!J)continue;let re=this.sortFeaturesByKey?T.evaluate(V,{},o):void 0;if(this.features.push({id:L,text:Y,icon:J,index:R,sourceLayerIndex:F,geometry:V.geometry,properties:D.properties,type:ql.types[D.type],sortKey:re}),J&&(b[J.name]=!0),Y){let te=d.evaluate(V,{},o).join(","),ae=h.get("text-rotation-alignment")!=="viewport"&&h.get("symbol-placement")!=="point";this.allowVerticalPlacement=(s=this.writingModes)===null||s===void 0?void 0:s.includes(k.ax.vertical);for(let le of Y.sections)if(le.image)b[le.image.name]=!0;else{let ne=bl(Y.toString()),ie=le.fontStack||te;I[ie]||(I[ie]={}),this.calculateGlyphDependencies(le.text,I[ie],ae,this.allowVerticalPlacement,ne)}}}h.get("symbol-placement")==="line"&&(this.features=(function(D){let L={},R={},F=[],O=0;function V(te){F.push(D[te]),O++}function Y(te,ae,le){let ne=R[te];return delete R[te],R[ae]=ne,F[ne].geometry[0].pop(),F[ne].geometry[0]=F[ne].geometry[0].concat(le[0]),ne}function J(te,ae,le){let ne=L[ae];return delete L[ae],L[te]=ne,F[ne].geometry[0].shift(),F[ne].geometry[0]=le[0].concat(F[ne].geometry[0]),ne}function re(te,ae,le){let ne=le?ae[0][ae[0].length-1]:ae[0][0];return`${te}:${ne.x}:${ne.y}`}for(let te=0;tete.geometry))})(this.features)),this.sortFeaturesByKey&&this.features.sort(((D,L)=>D.sortKey-L.sortKey))}update(e,i,o){this.stateDependentLayers.length&&(this.text.programConfigurations.updatePaintArrays(e,i,this.layers,{imagePositions:o}),this.icon.programConfigurations.updatePaintArrays(e,i,this.layers,{imagePositions:o}))}isEmpty(){return this.symbolInstances.length===0&&!this.hasRTLText}uploadPending(){return!this.uploaded||this.text.programConfigurations.needsUpload||this.icon.programConfigurations.needsUpload}upload(e){!this.uploaded&&this.hasDebugData()&&(this.textCollisionBox.upload(e),this.iconCollisionBox.upload(e)),this.text.upload(e,this.sortFeaturesByY,!this.uploaded,this.text.programConfigurations.needsUpload),this.icon.upload(e,this.sortFeaturesByY,!this.uploaded,this.icon.programConfigurations.needsUpload),this.uploaded=!0}destroyDebugData(){this.textCollisionBox.destroy(),this.iconCollisionBox.destroy()}destroy(){this.text.destroy(),this.icon.destroy(),this.hasDebugData()&&this.destroyDebugData()}addToLineVertexArray(e,i){let o=this.lineVertexArray.length;if(e.segment!==void 0){let s=e.dist(i[e.segment+1]),l=e.dist(i[e.segment]),h={};for(let d=e.segment+1;d=0;d--)h[d]={x:i[d].x,y:i[d].y,tileUnitDistanceFromAnchor:l},d>0&&(l+=i[d-1].dist(i[d]));for(let d=0;d0}hasIconData(){return this.icon.segments.get().length>0}hasDebugData(){return this.textCollisionBox&&this.iconCollisionBox}hasTextCollisionBoxData(){return this.hasDebugData()&&this.textCollisionBox.segments.get().length>0}hasIconCollisionBoxData(){return this.hasDebugData()&&this.iconCollisionBox.segments.get().length>0}addIndicesForPlacedSymbol(e,i){let o=e.placedSymbolArray.get(i),s=o.vertexStartIndex+4*o.numGlyphs;for(let l=o.vertexStartIndex;ls[d]-s[g]||l[g]-l[d])),h}addToSortKeyRanges(e,i){let o=this.sortKeyRanges[this.sortKeyRanges.length-1];o?.sortKey===i?o.symbolInstanceEnd=e+1:this.sortKeyRanges.push({sortKey:i,symbolInstanceStart:e,symbolInstanceEnd:e+1})}sortFeatures(e){if(this.sortFeaturesByY&&this.sortedAngle!==e&&!(this.text.segments.get().length>1||this.icon.segments.get().length>1)){this.symbolInstanceIndexes=this.getSortedSymbolIndexes(e),this.sortedAngle=e,this.text.indexArray.clear(),this.icon.indexArray.clear(),this.featureSortOrder=[];for(let i of this.symbolInstanceIndexes){let o=this.symbolInstances.get(i);this.featureSortOrder.push(o.featureIndex);let s=[o.rightJustifiedTextSymbolIndex,o.centerJustifiedTextSymbolIndex,o.leftJustifiedTextSymbolIndex];for(let l=0;l=0&&s.indexOf(h)===l&&this.addIndicesForPlacedSymbol(this.text,h)}o.verticalPlacedTextSymbolIndex>=0&&this.addIndicesForPlacedSymbol(this.text,o.verticalPlacedTextSymbolIndex),o.placedIconSymbolIndex>=0&&this.addIndicesForPlacedSymbol(this.icon,o.placedIconSymbolIndex),o.verticalPlacedIconSymbolIndex>=0&&this.addIndicesForPlacedSymbol(this.icon,o.verticalPlacedIconSymbolIndex)}this.text.indexBuffer&&this.text.indexBuffer.updateData(this.text.indexArray),this.icon.indexBuffer&&this.icon.indexBuffer.updateData(this.icon.indexArray)}}}let Cp,Ap;Pe("SymbolBucket",_a,{omit:["layers","collisionBoxArray","features","compareText"]}),_a.MAX_GLYPHS=65535,_a.addDynamicAttributes=Gu;var qu={get paint(){return Ap=Ap||new ui({"icon-opacity":new Ce(ce.paint_symbol["icon-opacity"]),"icon-color":new Ce(ce.paint_symbol["icon-color"]),"icon-halo-color":new Ce(ce.paint_symbol["icon-halo-color"]),"icon-halo-width":new Ce(ce.paint_symbol["icon-halo-width"]),"icon-halo-blur":new Ce(ce.paint_symbol["icon-halo-blur"]),"icon-translate":new Ie(ce.paint_symbol["icon-translate"]),"icon-translate-anchor":new Ie(ce.paint_symbol["icon-translate-anchor"]),"text-opacity":new Ce(ce.paint_symbol["text-opacity"]),"text-color":new Ce(ce.paint_symbol["text-color"],{runtimeType:Ei,getOverride:r=>r.textColor,hasOverride:r=>!!r.textColor}),"text-halo-color":new Ce(ce.paint_symbol["text-halo-color"]),"text-halo-width":new Ce(ce.paint_symbol["text-halo-width"]),"text-halo-blur":new Ce(ce.paint_symbol["text-halo-blur"]),"text-translate":new Ie(ce.paint_symbol["text-translate"]),"text-translate-anchor":new Ie(ce.paint_symbol["text-translate-anchor"])})},get layout(){return Cp=Cp||new ui({"symbol-placement":new Ie(ce.layout_symbol["symbol-placement"]),"symbol-spacing":new Ie(ce.layout_symbol["symbol-spacing"]),"symbol-avoid-edges":new Ie(ce.layout_symbol["symbol-avoid-edges"]),"symbol-sort-key":new Ce(ce.layout_symbol["symbol-sort-key"]),"symbol-z-order":new Ie(ce.layout_symbol["symbol-z-order"]),"icon-allow-overlap":new Ie(ce.layout_symbol["icon-allow-overlap"]),"icon-overlap":new Ie(ce.layout_symbol["icon-overlap"]),"icon-ignore-placement":new Ie(ce.layout_symbol["icon-ignore-placement"]),"icon-optional":new Ie(ce.layout_symbol["icon-optional"]),"icon-rotation-alignment":new Ie(ce.layout_symbol["icon-rotation-alignment"]),"icon-size":new Ce(ce.layout_symbol["icon-size"]),"icon-text-fit":new Ie(ce.layout_symbol["icon-text-fit"]),"icon-text-fit-padding":new Ie(ce.layout_symbol["icon-text-fit-padding"]),"icon-image":new Ce(ce.layout_symbol["icon-image"]),"icon-rotate":new Ce(ce.layout_symbol["icon-rotate"]),"icon-padding":new Ce(ce.layout_symbol["icon-padding"]),"icon-keep-upright":new Ie(ce.layout_symbol["icon-keep-upright"]),"icon-offset":new Ce(ce.layout_symbol["icon-offset"]),"icon-anchor":new Ce(ce.layout_symbol["icon-anchor"]),"icon-pitch-alignment":new Ie(ce.layout_symbol["icon-pitch-alignment"]),"text-pitch-alignment":new Ie(ce.layout_symbol["text-pitch-alignment"]),"text-rotation-alignment":new Ie(ce.layout_symbol["text-rotation-alignment"]),"text-field":new Ce(ce.layout_symbol["text-field"]),"text-font":new Ce(ce.layout_symbol["text-font"]),"text-size":new Ce(ce.layout_symbol["text-size"]),"text-max-width":new Ce(ce.layout_symbol["text-max-width"]),"text-line-height":new Ie(ce.layout_symbol["text-line-height"]),"text-letter-spacing":new Ce(ce.layout_symbol["text-letter-spacing"]),"text-justify":new Ce(ce.layout_symbol["text-justify"]),"text-radial-offset":new Ce(ce.layout_symbol["text-radial-offset"]),"text-variable-anchor":new Ie(ce.layout_symbol["text-variable-anchor"]),"text-variable-anchor-offset":new Ce(ce.layout_symbol["text-variable-anchor-offset"]),"text-anchor":new Ce(ce.layout_symbol["text-anchor"]),"text-max-angle":new Ie(ce.layout_symbol["text-max-angle"]),"text-writing-mode":new Ie(ce.layout_symbol["text-writing-mode"]),"text-rotate":new Ce(ce.layout_symbol["text-rotate"]),"text-padding":new Ie(ce.layout_symbol["text-padding"]),"text-keep-upright":new Ie(ce.layout_symbol["text-keep-upright"]),"text-transform":new Ce(ce.layout_symbol["text-transform"]),"text-offset":new Ce(ce.layout_symbol["text-offset"]),"text-allow-overlap":new Ie(ce.layout_symbol["text-allow-overlap"]),"text-overlap":new Ie(ce.layout_symbol["text-overlap"]),"text-ignore-placement":new Ie(ce.layout_symbol["text-ignore-placement"]),"text-optional":new Ie(ce.layout_symbol["text-optional"])})}};class Dp{constructor(e){if(e.property.overrides===void 0)throw new Error("overrides must be provided to instantiate FormatSectionOverride class");this.type=e.property.overrides?e.property.overrides.runtimeType:zr,this.defaultValue=e}evaluate(e){if(e.formattedSection){let i=this.defaultValue.property.overrides;if(i?.hasOverride(e.formattedSection))return i.getOverride(e.formattedSection)}return e.feature&&e.featureState?this.defaultValue.evaluate(e.feature,e.featureState):this.defaultValue.property.specification.default}eachChild(e){this.defaultValue.isConstant()||e(this.defaultValue.value._styleExpression.expression)}outputDefined(){return!1}serialize(){return null}}Pe("FormatSectionOverride",Dp,{omit:["defaultValue"]});class Ph extends Ui{constructor(e,i){super(e,qu,i)}recalculate(e,i){if(super.recalculate(e,i),this.layout.get("icon-rotation-alignment")==="auto"&&(this.layout._values["icon-rotation-alignment"]=this.layout.get("symbol-placement")!=="point"?"map":"viewport"),this.layout.get("text-rotation-alignment")==="auto"&&(this.layout._values["text-rotation-alignment"]=this.layout.get("symbol-placement")!=="point"?"map":"viewport"),this.layout.get("text-pitch-alignment")==="auto"&&(this.layout._values["text-pitch-alignment"]=this.layout.get("text-rotation-alignment")==="map"?"map":"viewport"),this.layout.get("icon-pitch-alignment")==="auto"&&(this.layout._values["icon-pitch-alignment"]=this.layout.get("icon-rotation-alignment")),this.layout.get("symbol-placement")==="point"){let o=this.layout.get("text-writing-mode");if(o){let s=[];for(let l of o)s.includes(l)||s.push(l);this.layout._values["text-writing-mode"]=s}else this.layout._values["text-writing-mode"]=["horizontal"]}this._setPaintOverrides()}getValueAndResolveTokens(e,i,o,s){let l=this.layout.get(e).evaluate(i,{},o,s),h=this._unevaluatedLayout._values[e];return h.isDataDriven()||Ns(h.value)||!l?l:(function(d,g){return g.replace(/{([^{}]+)}/g,((m,v)=>d&&v in d?String(d[v]):""))})(i.properties,l)}createBucket(e){return new _a(e)}queryRadius(){return 0}queryIntersectsFeature(){throw new Error("Should take a different path in FeatureIndex")}_setPaintOverrides(){for(let e of qu.paint.overridableProperties){if(!Ph.hasPaintOverride(this.layout,e))continue;let i=this.paint.get(e),o=new Dp(i),s=new Bo(o,i.property.specification),l=null;l=i.value.kind==="constant"||i.value.kind==="source"?new Vs("source",s):new js("composite",s,i.value.zoomStops),this.paint._values[e]=new er(i.property,l,i.parameters)}}_handleOverridablePaintPropertyUpdate(e,i,o){return!(!this.layout||i.isDataDriven()||o.isDataDriven())&&Ph.hasPaintOverride(this.layout,e)}static hasPaintOverride(e,i){let o=e.get("text-field"),s=qu.paint.properties[i],l=!1,h=d=>{var g;for(let m of d)if(!((g=s.overrides)===null||g===void 0)&&g.hasOverride(m))return void(l=!0)};if(o.value.kind==="constant"&&o.value.value instanceof xi)h(o.value.value.sections);else if(o.value.kind==="source"||o.value.kind==="composite"){let d=m=>{l||(m instanceof ir&&St(m.value)===To?h(m.value.sections):m instanceof dn?h(m.sections):m.eachChild(d))},g=o.value;g._styleExpression&&d(g._styleExpression.expression)}return l}}let zp;var Og={get paint(){return zp=zp||new ui({"background-color":new Ie(ce.paint_background["background-color"]),"background-pattern":new nh(ce.paint_background["background-pattern"]),"background-opacity":new Ie(ce.paint_background["background-opacity"])})}};class Ng extends Ui{constructor(e,i){super(e,Og,i)}}class Vg extends Ui{constructor(e,i){super(e,{},i),this.onAdd=o=>{this.implementation.onAdd&&this.implementation.onAdd(o,o.painter.context.gl)},this.onRemove=o=>{this.implementation.onRemove&&this.implementation.onRemove(o,o.painter.context.gl)},this.implementation=e}is3D(){return this.implementation.renderingMode==="3d"}hasOffscreenPass(){return this.implementation.prerender!==void 0}recalculate(){}updateTransitions(){}hasTransition(){return!1}serialize(){throw new Error("Custom layers cannot be serialized")}}class jg{constructor(e){this._methodToThrottle=e,this._triggered=!1,this._channel=new MessageChannel,this._channel.port2.onmessage=()=>{this._triggered=!1,this._methodToThrottle()}}trigger(){var e;this._triggered||(this._triggered=!0,(e=this._channel)===null||e===void 0||e.port1.postMessage(!0))}remove(){delete this._channel,this._methodToThrottle=()=>{}}}let Ug={once:!0},Wu=63710088e-1;class co{constructor(e,i){if(isNaN(e)||isNaN(i))throw new Error(`Invalid LngLat object: (${e}, ${i})`);if(this.lng=+e,this.lat=+i,this.lat>90||this.lat<-90)throw new Error("Invalid LngLat latitude value: must be between -90 and 90")}wrap(){return new co(zn(this.lng,-180,180),this.lat)}toArray(){return[this.lng,this.lat]}toString(){return`LngLat(${this.lng}, ${this.lat})`}distanceTo(e){let i=Math.PI/180,o=this.lat*i,s=e.lat*i,l=Math.sin(o)*Math.sin(s)+Math.cos(o)*Math.cos(s)*Math.cos((e.lng-this.lng)*i);return Wu*Math.acos(Math.min(l,1))}static convert(e){if(e instanceof co)return e;if(Array.isArray(e)&&(e.length===2||e.length===3))return new co(Number(e[0]),Number(e[1]));if(!Array.isArray(e)&&typeof e=="object"&&e!==null)return new co(Number("lng"in e?e.lng:e.lon),Number(e.lat));throw new Error("`LngLatLike` argument must be specified as a LngLat instance, an object {lng: , lat: }, an object {lon: , lat: }, or an array of [, ]")}}let Rp=2*Math.PI*Wu;function kp(r){return Rp*Math.cos(r*Math.PI/180)}function Lp(r){return(180+r)/360}function Fp(r){return(180-180/Math.PI*Math.log(Math.tan(Math.PI/4+r*Math.PI/360)))/360}function Bp(r,e){return r/kp(e)}function Op(r){return 360*r-180}function Sh(r){return 360/Math.PI*Math.atan(Math.exp((180-360*r)*Math.PI/180))-90}function Np(r,e){return r*kp(Sh(e))}class Jl{constructor(e,i,o=0){this.x=+e,this.y=+i,this.z=+o}static fromLngLat(e,i=0){let o=co.convert(e);return new Jl(Lp(o.lng),Fp(o.lat),Bp(i,o.lat))}toLngLat(){return new co(Op(this.x),Sh(this.y))}toAltitude(){return Np(this.z,this.y)}meterInMercatorCoordinateUnits(){return 1/Rp*(e=Sh(this.y),1/Math.cos(e*Math.PI/180));var e}}function Vp(r,e,i){var o=2*Math.PI*6378137/256/Math.pow(2,i);return[r*o-2*Math.PI*6378137/2,e*o-2*Math.PI*6378137/2]}class Hu{constructor(e,i,o){if(!(function(s,l,h){return!(s<0||s>25||h<0||h>=Math.pow(2,s)||l<0||l>=Math.pow(2,s))})(e,i,o))throw new Error(`x=${i}, y=${o}, z=${e} outside of bounds. 0<=x<${Math.pow(2,e)}, 0<=y<${Math.pow(2,e)} 0<=z<=25 `);this.z=e,this.x=i,this.y=o,this.key=ya(0,e,e,i,o)}equals(e){return this.z===e.z&&this.x===e.x&&this.y===e.y}url(e,i,o){let s=(h=this.y,d=this.z,g=Vp(256*(l=this.x),256*(h=Math.pow(2,d)-h-1),d),m=Vp(256*(l+1),256*(h+1),d),g[0]+","+g[1]+","+m[0]+","+m[1]);var l,h,d,g,m;let v=(function(_,T,b){let I="";for(let M=_;M>0;M--){let A=1<1?"@2x":"").replace(/{quadkey}/g,v).replace(/{bbox-epsg-3857}/g,s)}isChildOf(e){let i=this.z-e.z;return i>0&&e.x===this.x>>i&&e.y===this.y>>i}getTilePoint(e){let i=Math.pow(2,this.z);return new Te((e.x*i-this.x)*De,(e.y*i-this.y)*De)}toString(){return`${this.z}/${this.x}/${this.y}`}}class jp{constructor(e,i){this.wrap=e,this.canonical=i,this.key=ya(e,i.z,i.z,i.x,i.y)}}class $i{constructor(e,i,o,s,l){if(this.terrainRttPosMatrix32f=null,e= z; overscaledZ = ${e}; z = ${o}`);this.overscaledZ=e,this.wrap=i,this.canonical=new Hu(o,+s,+l),this.key=ya(i,e,o,s,l)}clone(){return new $i(this.overscaledZ,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y)}equals(e){return this.overscaledZ===e.overscaledZ&&this.wrap===e.wrap&&this.canonical.equals(e.canonical)}scaledTo(e){if(e>this.overscaledZ)throw new Error(`targetZ > this.overscaledZ; targetZ = ${e}; overscaledZ = ${this.overscaledZ}`);let i=this.canonical.z-e;return e>this.canonical.z?new $i(e,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y):new $i(e,this.wrap,e,this.canonical.x>>i,this.canonical.y>>i)}isOverscaled(){return this.overscaledZ>this.canonical.z}calculateScaledKey(e,i){if(e>this.overscaledZ)throw new Error(`targetZ > this.overscaledZ; targetZ = ${e}; overscaledZ = ${this.overscaledZ}`);let o=this.canonical.z-e;return e>this.canonical.z?ya(this.wrap*+i,e,this.canonical.z,this.canonical.x,this.canonical.y):ya(this.wrap*+i,e,e,this.canonical.x>>o,this.canonical.y>>o)}isChildOf(e){if(e.wrap!==this.wrap||this.overscaledZ-e.overscaledZ<=0)return!1;if(e.overscaledZ===0)return this.overscaledZ>0;let i=this.canonical.z-e.canonical.z;return!(i<0)&&e.canonical.x===this.canonical.x>>i&&e.canonical.y===this.canonical.y>>i}children(e){if(this.overscaledZ>=e)return[new $i(this.overscaledZ+1,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y)];let i=this.canonical.z+1,o=2*this.canonical.x,s=2*this.canonical.y;return[new $i(i,this.wrap,i,o,s),new $i(i,this.wrap,i,o+1,s),new $i(i,this.wrap,i,o,s+1),new $i(i,this.wrap,i,o+1,s+1)]}isLessThan(e){return this.wrape.wrap)&&(this.overscaledZe.overscaledZ)&&(this.canonical.xe.canonical.x)&&this.canonical.y=0&&e=0&&i=m)return null;let _=this.canonical.x+s,T=this.wrap;return _<0?(T-=Math.ceil(-_/m),_=(_%m+m)%m):_>=m&&(T+=Math.floor(_/m),_%=m),{tileID:new $i(this.overscaledZ,T,g,_,v),x:h,y:d}}}function ya(r,e,i,o,s){(r*=2)<0&&(r=-1*r-1);let l=1<this.maxX||this.minY>this.maxY)&&(this.minX=1/0,this.maxX=-1/0,this.minY=1/0,this.maxY=-1/0),this}shrinkBy(e){return this.expandBy(-e)}map(e){let i=new ss;return i.extend(e(new Te(this.minX,this.minY))),i.extend(e(new Te(this.maxX,this.minY))),i.extend(e(new Te(this.minX,this.maxY))),i.extend(e(new Te(this.maxX,this.maxY))),i}static fromPoints(e){let i=new ss;for(let o of e)i.extend(o);return i}contains(e){return e.x>=this.minX&&e.x<=this.maxX&&e.y>=this.minY&&e.y<=this.maxY}empty(){return this.minX>this.maxX}width(){return this.maxX-this.minX}height(){return this.maxY-this.minY}covers(e){return!this.empty()&&!e.empty()&&e.minX>=this.minX&&e.maxX<=this.maxX&&e.minY>=this.minY&&e.maxY<=this.maxY}intersects(e){return!this.empty()&&!e.empty()&&e.minX<=this.maxX&&e.maxX>=this.minX&&e.minY<=this.maxY&&e.maxY>=this.minY}}class Up{constructor(e){this._stringToNumber={},this._numberToString=[];for(let i=0;i=this._numberToString.length)throw new Error(`Out of bounds. Index requested n=${e} can't be >= this._numberToString.length ${this._numberToString.length}`);return this._numberToString[e]}}class Gp{constructor(e,i,o,s,l){this.type="Feature",this._vectorTileFeature=e,this._x=o,this._y=s,this._z=i,this.properties=e.properties,this.id=l}projectPoint(e,i,o,s){return[360*(e.x+i)/s-180,360/Math.PI*Math.atan(Math.exp((1-2*(e.y+o)/s)*Math.PI))-90]}projectLine(e,i,o,s){return e.map((l=>this.projectPoint(l,i,o,s)))}get geometry(){if(this._geometry)return this._geometry;let e=this._vectorTileFeature,i=e.extent*Math.pow(2,this._z),o=e.extent*this._x,s=e.extent*this._y,l=e.loadGeometry();switch(e.type){case 1:{let h=[];for(let g of l)h.push(g[0]);let d=this.projectLine(h,o,s,i);this._geometry=h.length===1?{type:"Point",coordinates:d[0]}:{type:"MultiPoint",coordinates:d};break}case 2:{let h=l.map((d=>this.projectLine(d,o,s,i)));this._geometry=h.length===1?{type:"LineString",coordinates:h[0]}:{type:"MultiLineString",coordinates:h};break}case 3:{let h=qd(l),d=[];for(let g of h)d.push(g.map((m=>this.projectLine(m,o,s,i))));this._geometry=d.length===1?{type:"Polygon",coordinates:d[0]}:{type:"MultiPolygon",coordinates:d};break}default:throw new Error(`unknown feature type: ${e.type}`)}return this._geometry}set geometry(e){this._geometry=e}toJSON(){let e={geometry:this.geometry};for(let i in this)i!=="_geometry"&&i!=="_vectorTileFeature"&&i!=="_x"&&i!=="_y"&&i!=="_z"&&(e[i]=this[i]);return e}}class va{constructor(e,i,o){this._name=e,this.dataBuffer=i,typeof o=="number"?this._size=o:(this.nullabilityBuffer=o,this._size=o.size())}getValue(e){return this.nullabilityBuffer&&!this.nullabilityBuffer.get(e)?null:this.getValueFromBuffer(e)}has(e){return this.nullabilityBuffer?.get(e)||!this.nullabilityBuffer}get name(){return this._name}get size(){return this._size}}class Ih extends va{}class Xu extends Ih{getValueFromBuffer(e){return this.dataBuffer[e]}}class Yu extends Ih{getValueFromBuffer(e){return this.dataBuffer[e]}}class $p extends va{constructor(e,i,o,s){super(e,i,s),this.delta=o}}class Ku extends $p{constructor(e,i,o,s){super(e,Int32Array.of(i),o,s)}getValueFromBuffer(e){return this.dataBuffer[0]+e*this.delta}}class Ju extends va{constructor(e,i,o,s){super(e,s?Int32Array.of(i):Uint32Array.of(i),o)}getValueFromBuffer(e){return this.dataBuffer[0]}}class Gg{constructor(e,i,o,s,l=4096){this._name=e,this._geometryVector=i,this._idVector=o,this._propertyVectors=s,this._extent=l}get name(){return this._name}get idVector(){return this._idVector}get geometryVector(){return this._geometryVector}get propertyVectors(){return this._propertyVectors}getPropertyVector(e){return this.propertyVectorsMap||(this.propertyVectorsMap=new Map(this._propertyVectors.map((i=>[i.name,i])))),this.propertyVectorsMap.get(e)}get numFeatures(){return this.geometryVector.numGeometries}get extent(){return this._extent}getFeatures(){let e=[],i=this.geometryVector.getGeometries();for(let o=0;o>>32-r;let ed=Qu,Mn=256;function td(r,e){return r-r%e}function $g(r){let e=r>>>0;return((255&e)<<24|(65280&e)<<8|e>>>8&65280|e>>>24&255)>>>0}let id=(function(){if(!Number.isFinite(65536))return 65536;let r=td(Math.floor(65536),Mn);return r===0?Mn:r})(),Zg=3*id/Mn+id|0;function qp(){let r=new Uint8Array(Zg);return{dataToBePacked:new Array(33),dataPointers:new Int32Array(33),byteContainer:r,byteContainerI32:new Int32Array(r.buffer,r.byteOffset,r.byteLength>>>2),exceptionSizes:new Int32Array(33)}}function qg(r,e,i,o,s){switch(s){case 1:(function(l,h,d,g){let m=g,v=h;for(let _=0;_<8;_++){let T=l[v++]>>>0;d[m++]=T>>>0&1,d[m++]=T>>>1&1,d[m++]=T>>>2&1,d[m++]=T>>>3&1,d[m++]=T>>>4&1,d[m++]=T>>>5&1,d[m++]=T>>>6&1,d[m++]=T>>>7&1,d[m++]=T>>>8&1,d[m++]=T>>>9&1,d[m++]=T>>>10&1,d[m++]=T>>>11&1,d[m++]=T>>>12&1,d[m++]=T>>>13&1,d[m++]=T>>>14&1,d[m++]=T>>>15&1,d[m++]=T>>>16&1,d[m++]=T>>>17&1,d[m++]=T>>>18&1,d[m++]=T>>>19&1,d[m++]=T>>>20&1,d[m++]=T>>>21&1,d[m++]=T>>>22&1,d[m++]=T>>>23&1,d[m++]=T>>>24&1,d[m++]=T>>>25&1,d[m++]=T>>>26&1,d[m++]=T>>>27&1,d[m++]=T>>>28&1,d[m++]=T>>>29&1,d[m++]=T>>>30&1,d[m++]=T>>>31&1}})(r,e,i,o);break;case 2:(function(l,h,d,g){let m=g,v=h;for(let _=0;_<8;_++){let T=l[v++]>>>0,b=l[v++]>>>0;d[m++]=T>>>0&3,d[m++]=T>>>2&3,d[m++]=T>>>4&3,d[m++]=T>>>6&3,d[m++]=T>>>8&3,d[m++]=T>>>10&3,d[m++]=T>>>12&3,d[m++]=T>>>14&3,d[m++]=T>>>16&3,d[m++]=T>>>18&3,d[m++]=T>>>20&3,d[m++]=T>>>22&3,d[m++]=T>>>24&3,d[m++]=T>>>26&3,d[m++]=T>>>28&3,d[m++]=T>>>30&3,d[m++]=b>>>0&3,d[m++]=b>>>2&3,d[m++]=b>>>4&3,d[m++]=b>>>6&3,d[m++]=b>>>8&3,d[m++]=b>>>10&3,d[m++]=b>>>12&3,d[m++]=b>>>14&3,d[m++]=b>>>16&3,d[m++]=b>>>18&3,d[m++]=b>>>20&3,d[m++]=b>>>22&3,d[m++]=b>>>24&3,d[m++]=b>>>26&3,d[m++]=b>>>28&3,d[m++]=b>>>30&3}})(r,e,i,o);break;case 3:(function(l,h,d,g){let m=g,v=h;for(let _=0;_<8;_++){let T=l[v++]>>>0,b=l[v++]>>>0,I=l[v++]>>>0;d[m++]=T>>>0&7,d[m++]=T>>>3&7,d[m++]=T>>>6&7,d[m++]=T>>>9&7,d[m++]=T>>>12&7,d[m++]=T>>>15&7,d[m++]=T>>>18&7,d[m++]=T>>>21&7,d[m++]=T>>>24&7,d[m++]=T>>>27&7,d[m++]=7&(T>>>30|(1&b)<<2),d[m++]=b>>>1&7,d[m++]=b>>>4&7,d[m++]=b>>>7&7,d[m++]=b>>>10&7,d[m++]=b>>>13&7,d[m++]=b>>>16&7,d[m++]=b>>>19&7,d[m++]=b>>>22&7,d[m++]=b>>>25&7,d[m++]=b>>>28&7,d[m++]=7&(b>>>31|(3&I)<<1),d[m++]=I>>>2&7,d[m++]=I>>>5&7,d[m++]=I>>>8&7,d[m++]=I>>>11&7,d[m++]=I>>>14&7,d[m++]=I>>>17&7,d[m++]=I>>>20&7,d[m++]=I>>>23&7,d[m++]=I>>>26&7,d[m++]=I>>>29&7}})(r,e,i,o);break;case 4:(function(l,h,d,g){let m=g,v=h;for(let _=0;_<8;_++){let T=l[v++]>>>0,b=l[v++]>>>0,I=l[v++]>>>0,M=l[v++]>>>0;d[m++]=T>>>0&15,d[m++]=T>>>4&15,d[m++]=T>>>8&15,d[m++]=T>>>12&15,d[m++]=T>>>16&15,d[m++]=T>>>20&15,d[m++]=T>>>24&15,d[m++]=T>>>28&15,d[m++]=b>>>0&15,d[m++]=b>>>4&15,d[m++]=b>>>8&15,d[m++]=b>>>12&15,d[m++]=b>>>16&15,d[m++]=b>>>20&15,d[m++]=b>>>24&15,d[m++]=b>>>28&15,d[m++]=I>>>0&15,d[m++]=I>>>4&15,d[m++]=I>>>8&15,d[m++]=I>>>12&15,d[m++]=I>>>16&15,d[m++]=I>>>20&15,d[m++]=I>>>24&15,d[m++]=I>>>28&15,d[m++]=M>>>0&15,d[m++]=M>>>4&15,d[m++]=M>>>8&15,d[m++]=M>>>12&15,d[m++]=M>>>16&15,d[m++]=M>>>20&15,d[m++]=M>>>24&15,d[m++]=M>>>28&15}})(r,e,i,o);break;case 5:(function(l,h,d,g){let m=g,v=h;for(let _=0;_<8;_++){let T=l[v++]>>>0,b=l[v++]>>>0,I=l[v++]>>>0,M=l[v++]>>>0,A=l[v++]>>>0;d[m++]=T>>>0&31,d[m++]=T>>>5&31,d[m++]=T>>>10&31,d[m++]=T>>>15&31,d[m++]=T>>>20&31,d[m++]=T>>>25&31,d[m++]=31&(T>>>30|(7&b)<<2),d[m++]=b>>>3&31,d[m++]=b>>>8&31,d[m++]=b>>>13&31,d[m++]=b>>>18&31,d[m++]=b>>>23&31,d[m++]=31&(b>>>28|(1&I)<<4),d[m++]=I>>>1&31,d[m++]=I>>>6&31,d[m++]=I>>>11&31,d[m++]=I>>>16&31,d[m++]=I>>>21&31,d[m++]=I>>>26&31,d[m++]=31&(I>>>31|(15&M)<<1),d[m++]=M>>>4&31,d[m++]=M>>>9&31,d[m++]=M>>>14&31,d[m++]=M>>>19&31,d[m++]=M>>>24&31,d[m++]=31&(M>>>29|(3&A)<<3),d[m++]=A>>>2&31,d[m++]=A>>>7&31,d[m++]=A>>>12&31,d[m++]=A>>>17&31,d[m++]=A>>>22&31,d[m++]=A>>>27&31}})(r,e,i,o);break;case 6:(function(l,h,d,g){let m=g,v=h;for(let _=0;_<8;_++){let T=l[v++]>>>0,b=l[v++]>>>0,I=l[v++]>>>0,M=l[v++]>>>0,A=l[v++]>>>0,D=l[v++]>>>0;d[m++]=T>>>0&63,d[m++]=T>>>6&63,d[m++]=T>>>12&63,d[m++]=T>>>18&63,d[m++]=T>>>24&63,d[m++]=63&(T>>>30|(15&b)<<2),d[m++]=b>>>4&63,d[m++]=b>>>10&63,d[m++]=b>>>16&63,d[m++]=b>>>22&63,d[m++]=63&(b>>>28|(3&I)<<4),d[m++]=I>>>2&63,d[m++]=I>>>8&63,d[m++]=I>>>14&63,d[m++]=I>>>20&63,d[m++]=I>>>26&63,d[m++]=M>>>0&63,d[m++]=M>>>6&63,d[m++]=M>>>12&63,d[m++]=M>>>18&63,d[m++]=M>>>24&63,d[m++]=63&(M>>>30|(15&A)<<2),d[m++]=A>>>4&63,d[m++]=A>>>10&63,d[m++]=A>>>16&63,d[m++]=A>>>22&63,d[m++]=63&(A>>>28|(3&D)<<4),d[m++]=D>>>2&63,d[m++]=D>>>8&63,d[m++]=D>>>14&63,d[m++]=D>>>20&63,d[m++]=D>>>26&63}})(r,e,i,o);break;case 7:(function(l,h,d,g){let m=g,v=h;for(let _=0;_<8;_++){let T=l[v++]>>>0,b=l[v++]>>>0,I=l[v++]>>>0,M=l[v++]>>>0,A=l[v++]>>>0,D=l[v++]>>>0,L=l[v++]>>>0;d[m++]=T>>>0&127,d[m++]=T>>>7&127,d[m++]=T>>>14&127,d[m++]=T>>>21&127,d[m++]=127&(T>>>28|(7&b)<<4),d[m++]=b>>>3&127,d[m++]=b>>>10&127,d[m++]=b>>>17&127,d[m++]=b>>>24&127,d[m++]=127&(b>>>31|(63&I)<<1),d[m++]=I>>>6&127,d[m++]=I>>>13&127,d[m++]=I>>>20&127,d[m++]=127&(I>>>27|(3&M)<<5),d[m++]=M>>>2&127,d[m++]=M>>>9&127,d[m++]=M>>>16&127,d[m++]=M>>>23&127,d[m++]=127&(M>>>30|(31&A)<<2),d[m++]=A>>>5&127,d[m++]=A>>>12&127,d[m++]=A>>>19&127,d[m++]=127&(A>>>26|(1&D)<<6),d[m++]=D>>>1&127,d[m++]=D>>>8&127,d[m++]=D>>>15&127,d[m++]=D>>>22&127,d[m++]=127&(D>>>29|(15&L)<<3),d[m++]=L>>>4&127,d[m++]=L>>>11&127,d[m++]=L>>>18&127,d[m++]=L>>>25&127}})(r,e,i,o);break;case 8:(function(l,h,d,g){let m=g,v=h;for(let _=0;_<8;_++){let T=l[v++]>>>0,b=l[v++]>>>0,I=l[v++]>>>0,M=l[v++]>>>0,A=l[v++]>>>0,D=l[v++]>>>0,L=l[v++]>>>0,R=l[v++]>>>0;d[m++]=T>>>0&255,d[m++]=T>>>8&255,d[m++]=T>>>16&255,d[m++]=T>>>24&255,d[m++]=b>>>0&255,d[m++]=b>>>8&255,d[m++]=b>>>16&255,d[m++]=b>>>24&255,d[m++]=I>>>0&255,d[m++]=I>>>8&255,d[m++]=I>>>16&255,d[m++]=I>>>24&255,d[m++]=M>>>0&255,d[m++]=M>>>8&255,d[m++]=M>>>16&255,d[m++]=M>>>24&255,d[m++]=A>>>0&255,d[m++]=A>>>8&255,d[m++]=A>>>16&255,d[m++]=A>>>24&255,d[m++]=D>>>0&255,d[m++]=D>>>8&255,d[m++]=D>>>16&255,d[m++]=D>>>24&255,d[m++]=L>>>0&255,d[m++]=L>>>8&255,d[m++]=L>>>16&255,d[m++]=L>>>24&255,d[m++]=R>>>0&255,d[m++]=R>>>8&255,d[m++]=R>>>16&255,d[m++]=R>>>24&255}})(r,e,i,o);break;case 16:(function(l,h,d,g){let m=g,v=h;for(let _=0;_<128;_++){let T=l[v++]>>>0;d[m++]=65535&T,d[m++]=T>>>16&65535}})(r,e,i,o);break;default:(function(l,h,d,g,m){let v=ed[m]>>>0,_=h,T=0,b=l[_]>>>0,I=g;for(let M=0;M<8;M++){for(let A=0;A<32;A++)if(T+m<=32)d[I+A]=b>>>T&v,T+=m,T===32&&(T=0,_++,A!==31&&(b=l[_]>>>0));else{let D=32-T,L=b>>>T;_++,b=l[_]>>>0;let R=m-D;d[I+A]=(L|(b&-1>>>32-R>>>0)<>>0)}})(r,e,i,o,s)}return e+(s<<3)|0}function Wg(r,e,i,o){if(i+2>e)throw new Error(`FastPFOR decode: byteContainer underflow at block=${o} (need 2 bytes for [bitWidth, exceptionCount], bytePos=${i}, byteSize=${e})`);let s=r[i++],l=r[i++];if(s>32)throw new Error(`FastPFOR decode: invalid bitWidth=${s} at block=${o} (expected 0..32). This likely indicates corrupted or truncated input.`);return{bitWidth:s,exceptionCount:l,bytePosIn:i}}function Hg(r,e,i,o,s,l,h,d,g){let{maxBits:m,exceptionBitWidth:v,bytePosIn:_}=(function(A,D,L,R,F,O){if(L+1>D)throw new Error(`FastPFOR decode: exception header underflow at block=${O} (need 1 byte for maxBits, bytePos=${L}, byteSize=${D})`);let V=A[L++];if(V32)throw new Error(`FastPFOR decode: invalid maxBits=${V} at block=${O} (bitWidth=${R}, expected ${R}..32)`);let Y=V-R|0;if(Y<1||Y>32)throw new Error(`FastPFOR decode: invalid exceptionBitWidth=${Y} at block=${O} (bitWidth=${R}, maxBits=${V})`);if(L+F>D)throw new Error(`FastPFOR decode: exception positions underflow at block=${O} (need=${F}, have=${D-L})`);return{maxBits:V,exceptionBitWidth:Y,bytePosIn:L}})(s,l,h,i,o,g);if(h=_,v===1){let A=1<M)throw new Error(`FastPFOR decode: exception stream overflow for exceptionBitWidth=${v} (ptr=${I}, need ${o}, size=${M}) at block ${g}`);for(let A=0;Ar.length-1)throw new Error(`FastPFOR decode: invalid whereMeta=${d} at pageStart=${h} (expected > 0 and pageStart+whereMeta < encoded.length=${r.length})`);let g=h+1|0,m=h+d|0,v=r[m]>>>0,_=v+3>>>2,T=m+1,b=T+_;if(b>=r.length)throw new Error(`FastPFOR decode: invalid byteSize=${v} (metaInts=${_}, pageStart=${h}, packedEnd=${m}, byteContainerStart=${T}) causes bitmapPos=${b} out of bounds (encoded.length=${r.length})`);let I=(function(D,L,R,F){F.byteContainer.length>>2;if(3&O.byteOffset)for(let J=0;J>>8&255,O[te+2|0]=re>>>16&255,O[te+3|0]=re>>>24&255}else{let J=F.byteContainerI32;(!J||J.buffer!==O.buffer||J.byteOffset!==O.byteOffset||J.length>>2)),J.set(D.subarray(L,L+V))}let Y=3&R;if(Y>0){let J=0|D[L+V|0],re=V<<2;for(let te=0;te>>(te<<3)&255}return O})(r,T,v,l),M=v,A=(function(D,L,R){let F=0|D[L++],O=R.dataToBePacked;for(let V=2;V<=32;V=V+1|0){if(!(F>>>V-1&1))continue;if(L>=D.length)throw new Error(`FastPFOR decode: truncated exception stream header (bitWidth=${V}, streamWordIndex=${L}, needWords=1, availableWords=${D.length-L}, encodedWords=${D.length})`);let Y=D[L++]>>>0,J=td(Y+31,32),re=Y*V+31>>>5;if(L+re>D.length)throw new Error(`FastPFOR decode: truncated exception stream (bitWidth=${V}, size=${Y}, streamWordIndex=${L}, needWords=${re}, availableWords=${D.length-L}, encodedWords=${D.length})`);let te=O[V];(!te||te.length>>5)|0,R.exceptionSizes[V]=Y}return L})(r,b,l);return l.dataPointers.fill(0),(function(D,L,R,F,O,V,Y,J,re,te){let ae=0|R,le=0;for(let ne=0;ne0&&(le=Hg(O,ye,fe,xe,J,re,le,te,ne))}if(ae!==F)throw new Error(`FastPFOR decode: packed region mismatch (pageStart=${L}, packedStart=${R}, consumedPackedEnd=${ae}, expectedPackedEnd=${F}, packedWords=${F-R}, encoded.length=${D.length})`)})(r,h,g,m,e,0|o,s/Mn|0,I,M,l),A}function Yg(r,e,i,o,s){switch(s){case 2:return void(function(m,v,_,T){let b=T,I=m[v]>>>0,M=m[v+1]>>>0;_[b++]=I>>>0&3,_[b++]=I>>>2&3,_[b++]=I>>>4&3,_[b++]=I>>>6&3,_[b++]=I>>>8&3,_[b++]=I>>>10&3,_[b++]=I>>>12&3,_[b++]=I>>>14&3,_[b++]=I>>>16&3,_[b++]=I>>>18&3,_[b++]=I>>>20&3,_[b++]=I>>>22&3,_[b++]=I>>>24&3,_[b++]=I>>>26&3,_[b++]=I>>>28&3,_[b++]=I>>>30&3,_[b++]=M>>>0&3,_[b++]=M>>>2&3,_[b++]=M>>>4&3,_[b++]=M>>>6&3,_[b++]=M>>>8&3,_[b++]=M>>>10&3,_[b++]=M>>>12&3,_[b++]=M>>>14&3,_[b++]=M>>>16&3,_[b++]=M>>>18&3,_[b++]=M>>>20&3,_[b++]=M>>>22&3,_[b++]=M>>>24&3,_[b++]=M>>>26&3,_[b++]=M>>>28&3,_[b]=M>>>30&3})(r,e,i,o);case 3:return void(function(m,v,_,T){let b=T,I=m[v]>>>0,M=m[v+1]>>>0,A=m[v+2]>>>0;_[b++]=I>>>0&7,_[b++]=I>>>3&7,_[b++]=I>>>6&7,_[b++]=I>>>9&7,_[b++]=I>>>12&7,_[b++]=I>>>15&7,_[b++]=I>>>18&7,_[b++]=I>>>21&7,_[b++]=I>>>24&7,_[b++]=I>>>27&7,_[b++]=7&(I>>>30|(1&M)<<2),_[b++]=M>>>1&7,_[b++]=M>>>4&7,_[b++]=M>>>7&7,_[b++]=M>>>10&7,_[b++]=M>>>13&7,_[b++]=M>>>16&7,_[b++]=M>>>19&7,_[b++]=M>>>22&7,_[b++]=M>>>25&7,_[b++]=M>>>28&7,_[b++]=7&(M>>>31|(3&A)<<1),_[b++]=A>>>2&7,_[b++]=A>>>5&7,_[b++]=A>>>8&7,_[b++]=A>>>11&7,_[b++]=A>>>14&7,_[b++]=A>>>17&7,_[b++]=A>>>20&7,_[b++]=A>>>23&7,_[b++]=A>>>26&7,_[b]=A>>>29&7})(r,e,i,o);case 4:return void(function(m,v,_,T){let b=T,I=m[v]>>>0,M=m[v+1]>>>0,A=m[v+2]>>>0,D=m[v+3]>>>0;_[b++]=I>>>0&15,_[b++]=I>>>4&15,_[b++]=I>>>8&15,_[b++]=I>>>12&15,_[b++]=I>>>16&15,_[b++]=I>>>20&15,_[b++]=I>>>24&15,_[b++]=I>>>28&15,_[b++]=M>>>0&15,_[b++]=M>>>4&15,_[b++]=M>>>8&15,_[b++]=M>>>12&15,_[b++]=M>>>16&15,_[b++]=M>>>20&15,_[b++]=M>>>24&15,_[b++]=M>>>28&15,_[b++]=A>>>0&15,_[b++]=A>>>4&15,_[b++]=A>>>8&15,_[b++]=A>>>12&15,_[b++]=A>>>16&15,_[b++]=A>>>20&15,_[b++]=A>>>24&15,_[b++]=A>>>28&15,_[b++]=D>>>0&15,_[b++]=D>>>4&15,_[b++]=D>>>8&15,_[b++]=D>>>12&15,_[b++]=D>>>16&15,_[b++]=D>>>20&15,_[b++]=D>>>24&15,_[b]=D>>>28&15})(r,e,i,o);case 5:return void(function(m,v,_,T){let b=T,I=m[v]>>>0,M=m[v+1]>>>0,A=m[v+2]>>>0,D=m[v+3]>>>0,L=m[v+4]>>>0;_[b++]=I>>>0&31,_[b++]=I>>>5&31,_[b++]=I>>>10&31,_[b++]=I>>>15&31,_[b++]=I>>>20&31,_[b++]=I>>>25&31,_[b++]=31&(I>>>30|(7&M)<<2),_[b++]=M>>>3&31,_[b++]=M>>>8&31,_[b++]=M>>>13&31,_[b++]=M>>>18&31,_[b++]=M>>>23&31,_[b++]=31&(M>>>28|(1&A)<<4),_[b++]=A>>>1&31,_[b++]=A>>>6&31,_[b++]=A>>>11&31,_[b++]=A>>>16&31,_[b++]=A>>>21&31,_[b++]=A>>>26&31,_[b++]=31&(A>>>31|(15&D)<<1),_[b++]=D>>>4&31,_[b++]=D>>>9&31,_[b++]=D>>>14&31,_[b++]=D>>>19&31,_[b++]=D>>>24&31,_[b++]=31&(D>>>29|(3&L)<<3),_[b++]=L>>>2&31,_[b++]=L>>>7&31,_[b++]=L>>>12&31,_[b++]=L>>>17&31,_[b++]=L>>>22&31,_[b]=L>>>27&31})(r,e,i,o);case 6:return void(function(m,v,_,T){let b=T,I=m[v]>>>0,M=m[v+1]>>>0,A=m[v+2]>>>0,D=m[v+3]>>>0,L=m[v+4]>>>0,R=m[v+5]>>>0;_[b++]=I>>>0&63,_[b++]=I>>>6&63,_[b++]=I>>>12&63,_[b++]=I>>>18&63,_[b++]=I>>>24&63,_[b++]=63&(I>>>30|(15&M)<<2),_[b++]=M>>>4&63,_[b++]=M>>>10&63,_[b++]=M>>>16&63,_[b++]=M>>>22&63,_[b++]=63&(M>>>28|(3&A)<<4),_[b++]=A>>>2&63,_[b++]=A>>>8&63,_[b++]=A>>>14&63,_[b++]=A>>>20&63,_[b++]=A>>>26&63,_[b++]=D>>>0&63,_[b++]=D>>>6&63,_[b++]=D>>>12&63,_[b++]=D>>>18&63,_[b++]=D>>>24&63,_[b++]=63&(D>>>30|(15&L)<<2),_[b++]=L>>>4&63,_[b++]=L>>>10&63,_[b++]=L>>>16&63,_[b++]=L>>>22&63,_[b++]=63&(L>>>28|(3&R)<<4),_[b++]=R>>>2&63,_[b++]=R>>>8&63,_[b++]=R>>>14&63,_[b++]=R>>>20&63,_[b]=R>>>26&63})(r,e,i,o);case 7:return void(function(m,v,_,T){let b=T,I=m[v]>>>0,M=m[v+1]>>>0,A=m[v+2]>>>0,D=m[v+3]>>>0,L=m[v+4]>>>0,R=m[v+5]>>>0,F=m[v+6]>>>0;_[b++]=I>>>0&127,_[b++]=I>>>7&127,_[b++]=I>>>14&127,_[b++]=I>>>21&127,_[b++]=127&(I>>>28|(7&M)<<4),_[b++]=M>>>3&127,_[b++]=M>>>10&127,_[b++]=M>>>17&127,_[b++]=M>>>24&127,_[b++]=127&(M>>>31|(63&A)<<1),_[b++]=A>>>6&127,_[b++]=A>>>13&127,_[b++]=A>>>20&127,_[b++]=127&(A>>>27|(3&D)<<5),_[b++]=D>>>2&127,_[b++]=D>>>9&127,_[b++]=D>>>16&127,_[b++]=D>>>23&127,_[b++]=127&(D>>>30|(31&L)<<2),_[b++]=L>>>5&127,_[b++]=L>>>12&127,_[b++]=L>>>19&127,_[b++]=127&(L>>>26|(1&R)<<6),_[b++]=R>>>1&127,_[b++]=R>>>8&127,_[b++]=R>>>15&127,_[b++]=R>>>22&127,_[b++]=127&(R>>>29|(15&F)<<3),_[b++]=F>>>4&127,_[b++]=F>>>11&127,_[b++]=F>>>18&127,_[b]=F>>>25&127})(r,e,i,o);case 8:return void(function(m,v,_,T){let b=T,I=m[v]>>>0,M=m[v+1]>>>0,A=m[v+2]>>>0,D=m[v+3]>>>0,L=m[v+4]>>>0,R=m[v+5]>>>0,F=m[v+6]>>>0,O=m[v+7]>>>0;_[b++]=I>>>0&255,_[b++]=I>>>8&255,_[b++]=I>>>16&255,_[b++]=I>>>24&255,_[b++]=M>>>0&255,_[b++]=M>>>8&255,_[b++]=M>>>16&255,_[b++]=M>>>24&255,_[b++]=A>>>0&255,_[b++]=A>>>8&255,_[b++]=A>>>16&255,_[b++]=A>>>24&255,_[b++]=D>>>0&255,_[b++]=D>>>8&255,_[b++]=D>>>16&255,_[b++]=D>>>24&255,_[b++]=L>>>0&255,_[b++]=L>>>8&255,_[b++]=L>>>16&255,_[b++]=L>>>24&255,_[b++]=R>>>0&255,_[b++]=R>>>8&255,_[b++]=R>>>16&255,_[b++]=R>>>24&255,_[b++]=F>>>0&255,_[b++]=F>>>8&255,_[b++]=F>>>16&255,_[b++]=F>>>24&255,_[b++]=O>>>0&255,_[b++]=O>>>8&255,_[b++]=O>>>16&255,_[b]=O>>>24&255})(r,e,i,o);case 9:return void(function(m,v,_,T){let b=T,I=m[v]>>>0,M=m[v+1]>>>0,A=m[v+2]>>>0,D=m[v+3]>>>0,L=m[v+4]>>>0,R=m[v+5]>>>0,F=m[v+6]>>>0,O=m[v+7]>>>0,V=m[v+8]>>>0;_[b++]=I>>>0&511,_[b++]=I>>>9&511,_[b++]=I>>>18&511,_[b++]=511&(I>>>27|(15&M)<<5),_[b++]=M>>>4&511,_[b++]=M>>>13&511,_[b++]=M>>>22&511,_[b++]=511&(M>>>31|(255&A)<<1),_[b++]=A>>>8&511,_[b++]=A>>>17&511,_[b++]=511&(A>>>26|(7&D)<<6),_[b++]=D>>>3&511,_[b++]=D>>>12&511,_[b++]=D>>>21&511,_[b++]=511&(D>>>30|(127&L)<<2),_[b++]=L>>>7&511,_[b++]=L>>>16&511,_[b++]=511&(L>>>25|(3&R)<<7),_[b++]=R>>>2&511,_[b++]=R>>>11&511,_[b++]=R>>>20&511,_[b++]=511&(R>>>29|(63&F)<<3),_[b++]=F>>>6&511,_[b++]=F>>>15&511,_[b++]=511&(F>>>24|(1&O)<<8),_[b++]=O>>>1&511,_[b++]=O>>>10&511,_[b++]=O>>>19&511,_[b++]=511&(O>>>28|(31&V)<<4),_[b++]=V>>>5&511,_[b++]=V>>>14&511,_[b]=V>>>23&511})(r,e,i,o);case 10:return void(function(m,v,_,T){let b=T,I=m[v]>>>0,M=m[v+1]>>>0,A=m[v+2]>>>0,D=m[v+3]>>>0,L=m[v+4]>>>0,R=m[v+5]>>>0,F=m[v+6]>>>0,O=m[v+7]>>>0,V=m[v+8]>>>0,Y=m[v+9]>>>0;_[b++]=I>>>0&1023,_[b++]=I>>>10&1023,_[b++]=I>>>20&1023,_[b++]=1023&(I>>>30|(255&M)<<2),_[b++]=M>>>8&1023,_[b++]=M>>>18&1023,_[b++]=1023&(M>>>28|(63&A)<<4),_[b++]=A>>>6&1023,_[b++]=A>>>16&1023,_[b++]=1023&(A>>>26|(15&D)<<6),_[b++]=D>>>4&1023,_[b++]=D>>>14&1023,_[b++]=1023&(D>>>24|(3&L)<<8),_[b++]=L>>>2&1023,_[b++]=L>>>12&1023,_[b++]=L>>>22&1023,_[b++]=R>>>0&1023,_[b++]=R>>>10&1023,_[b++]=R>>>20&1023,_[b++]=1023&(R>>>30|(255&F)<<2),_[b++]=F>>>8&1023,_[b++]=F>>>18&1023,_[b++]=1023&(F>>>28|(63&O)<<4),_[b++]=O>>>6&1023,_[b++]=O>>>16&1023,_[b++]=1023&(O>>>26|(15&V)<<6),_[b++]=V>>>4&1023,_[b++]=V>>>14&1023,_[b++]=1023&(V>>>24|(3&Y)<<8),_[b++]=Y>>>2&1023,_[b++]=Y>>>12&1023,_[b]=Y>>>22&1023})(r,e,i,o);case 11:return void(function(m,v,_,T){let b=T,I=m[v]>>>0,M=m[v+1]>>>0,A=m[v+2]>>>0,D=m[v+3]>>>0,L=m[v+4]>>>0,R=m[v+5]>>>0,F=m[v+6]>>>0,O=m[v+7]>>>0,V=m[v+8]>>>0,Y=m[v+9]>>>0,J=m[v+10]>>>0;_[b++]=I>>>0&2047,_[b++]=I>>>11&2047,_[b++]=2047&(I>>>22|(1&M)<<10),_[b++]=M>>>1&2047,_[b++]=M>>>12&2047,_[b++]=2047&(M>>>23|(3&A)<<9),_[b++]=A>>>2&2047,_[b++]=A>>>13&2047,_[b++]=2047&(A>>>24|(7&D)<<8),_[b++]=D>>>3&2047,_[b++]=D>>>14&2047,_[b++]=2047&(D>>>25|(15&L)<<7),_[b++]=L>>>4&2047,_[b++]=L>>>15&2047,_[b++]=2047&(L>>>26|(31&R)<<6),_[b++]=R>>>5&2047,_[b++]=R>>>16&2047,_[b++]=2047&(R>>>27|(63&F)<<5),_[b++]=F>>>6&2047,_[b++]=F>>>17&2047,_[b++]=2047&(F>>>28|(127&O)<<4),_[b++]=O>>>7&2047,_[b++]=O>>>18&2047,_[b++]=2047&(O>>>29|(255&V)<<3),_[b++]=V>>>8&2047,_[b++]=V>>>19&2047,_[b++]=2047&(V>>>30|(511&Y)<<2),_[b++]=Y>>>9&2047,_[b++]=Y>>>20&2047,_[b++]=2047&(Y>>>31|(1023&J)<<1),_[b++]=J>>>10&2047,_[b]=J>>>21&2047})(r,e,i,o);case 12:return void(function(m,v,_,T){let b=T,I=m[v]>>>0,M=m[v+1]>>>0,A=m[v+2]>>>0,D=m[v+3]>>>0,L=m[v+4]>>>0,R=m[v+5]>>>0,F=m[v+6]>>>0,O=m[v+7]>>>0,V=m[v+8]>>>0,Y=m[v+9]>>>0,J=m[v+10]>>>0,re=m[v+11]>>>0;_[b++]=I>>>0&4095,_[b++]=I>>>12&4095,_[b++]=4095&(I>>>24|(15&M)<<8),_[b++]=M>>>4&4095,_[b++]=M>>>16&4095,_[b++]=4095&(M>>>28|(255&A)<<4),_[b++]=A>>>8&4095,_[b++]=A>>>20&4095,_[b++]=D>>>0&4095,_[b++]=D>>>12&4095,_[b++]=4095&(D>>>24|(15&L)<<8),_[b++]=L>>>4&4095,_[b++]=L>>>16&4095,_[b++]=4095&(L>>>28|(255&R)<<4),_[b++]=R>>>8&4095,_[b++]=R>>>20&4095,_[b++]=F>>>0&4095,_[b++]=F>>>12&4095,_[b++]=4095&(F>>>24|(15&O)<<8),_[b++]=O>>>4&4095,_[b++]=O>>>16&4095,_[b++]=4095&(O>>>28|(255&V)<<4),_[b++]=V>>>8&4095,_[b++]=V>>>20&4095,_[b++]=Y>>>0&4095,_[b++]=Y>>>12&4095,_[b++]=4095&(Y>>>24|(15&J)<<8),_[b++]=J>>>4&4095,_[b++]=J>>>16&4095,_[b++]=4095&(J>>>28|(255&re)<<4),_[b++]=re>>>8&4095,_[b]=re>>>20&4095})(r,e,i,o);case 16:return void(function(m,v,_,T){let b=T,I=m[v]>>>0,M=m[v+1]>>>0,A=m[v+2]>>>0,D=m[v+3]>>>0,L=m[v+4]>>>0,R=m[v+5]>>>0,F=m[v+6]>>>0,O=m[v+7]>>>0,V=m[v+8]>>>0,Y=m[v+9]>>>0,J=m[v+10]>>>0,re=m[v+11]>>>0,te=m[v+12]>>>0,ae=m[v+13]>>>0,le=m[v+14]>>>0,ne=m[v+15]>>>0;_[b++]=I>>>0&65535,_[b++]=I>>>16&65535,_[b++]=M>>>0&65535,_[b++]=M>>>16&65535,_[b++]=A>>>0&65535,_[b++]=A>>>16&65535,_[b++]=D>>>0&65535,_[b++]=D>>>16&65535,_[b++]=L>>>0&65535,_[b++]=L>>>16&65535,_[b++]=R>>>0&65535,_[b++]=R>>>16&65535,_[b++]=F>>>0&65535,_[b++]=F>>>16&65535,_[b++]=O>>>0&65535,_[b++]=O>>>16&65535,_[b++]=V>>>0&65535,_[b++]=V>>>16&65535,_[b++]=Y>>>0&65535,_[b++]=Y>>>16&65535,_[b++]=J>>>0&65535,_[b++]=J>>>16&65535,_[b++]=re>>>0&65535,_[b++]=re>>>16&65535,_[b++]=te>>>0&65535,_[b++]=te>>>16&65535,_[b++]=ae>>>0&65535,_[b++]=ae>>>16&65535,_[b++]=le>>>0&65535,_[b++]=le>>>16&65535,_[b++]=ne>>>0&65535,_[b]=ne>>>16&65535})(r,e,i,o);case 32:for(let m=0;m<32;m=m+1|0)i[o+m|0]=0|r[e+m|0];return}let l=ed[s]>>>0,h=e,d=0,g=r[h]>>>0;for(let m=0;m<32;m++)if(d+s<=32)i[o+m]=g>>>d&l,d+=s,d===32&&(d=0,h++,m!==31&&(g=r[h]>>>0));else{let v=32-d,_=g>>>d;h++,g=r[h]>>>0,i[o+m]=(_|(g&ed[s-v]>>>0)<=64)throw new Error("Varint too long")}return e.set(s),i}function Jg(r,e){let i,o;return o=r[e.get()],e.increment(),i=127&o,o<128?i:(o=r[e.get()],e.increment(),i|=(127&o)<<7,o<128?i:(o=r[e.get()],e.increment(),i|=(127&o)<<14,o<128?i:(o=r[e.get()],e.increment(),i|=(127&o)<<21,o<128?i:(o=r[e.get()],i|=(15&o)<<28,(function(s,l,h){let d,g;if(g=l[h.get()],h.increment(),d=(112&g)>>4,g<128||(g=l[h.get()],h.increment(),d|=(127&g)<<3,g<128)||(g=l[h.get()],h.increment(),d|=(127&g)<<10,g<128)||(g=l[h.get()],h.increment(),d|=(127&g)<<17,g<128)||(g=l[h.get()],h.increment(),d|=(127&g)<<24,g<128)||(g=l[h.get()],h.increment(),d|=(1&g)<<31,g<128))return 4294967296*d+(s>>>0);throw new Error("Expected varint not more than 10 bytes")})(i,r,e)))))}function st(r){return r>>>1^-(1&r)}function Ti(r){return r>>1n^-(1n&r)}function ba(r){return r%2==1?(r+1)/-2:r/2}function rd(r,e,i){if(i===void 0){i=0;for(let l=0;l=4)for(;o=4)for(;o=4)for(let o=r[0];i>4],d=null;switch(h){case ni.DATA:d={dictionaryType:Object.values(xr)[15&l]};break;case ni.OFFSET:d={offsetType:Object.values(as)[15&l]};break;case ni.LENGTH:d={lengthType:Object.values(Zi)[15&l]}}s.increment();let g=o[s.get()],m=Object.values(Ge)[g>>5],v=Object.values(Ge)[g>>2&7],_=Object.values(ho)[3&g];s.increment();let T=fi(o,s,2),b=T[0];return{physicalStreamType:h,logicalStreamType:d,logicalLevelTechnique1:m,logicalLevelTechnique2:v,physicalLevelTechnique:_,numValues:b,byteLength:T[1],decompressedCount:b}})(r,e);return i.logicalLevelTechnique1===Ge.MORTON?(function(o,s,l){let h=fi(s,l,2);return{physicalStreamType:o.physicalStreamType,logicalStreamType:o.logicalStreamType,logicalLevelTechnique1:o.logicalLevelTechnique1,logicalLevelTechnique2:o.logicalLevelTechnique2,physicalLevelTechnique:o.physicalLevelTechnique,numValues:o.numValues,byteLength:o.byteLength,decompressedCount:o.decompressedCount,numBits:h[0],coordinateShift:h[1]}})(i,r,e):Ge.RLE!==i.logicalLevelTechnique1&&Ge.RLE!==i.logicalLevelTechnique2||ho.NONE===i.physicalLevelTechnique?i:(function(o,s,l){let h=fi(s,l,2);return{physicalStreamType:o.physicalStreamType,logicalStreamType:o.logicalStreamType,logicalLevelTechnique1:o.logicalLevelTechnique1,logicalLevelTechnique2:o.logicalLevelTechnique2,physicalLevelTechnique:o.physicalLevelTechnique,numValues:o.numValues,byteLength:o.byteLength,decompressedCount:h[1],runs:h[0],numRleValues:h[1]}})(i,r,e)}(function(r){r.PRESENT="PRESENT",r.DATA="DATA",r.OFFSET="OFFSET",r.LENGTH="LENGTH"})(ni||(ni={})),(function(r){r.NONE="NONE",r.SINGLE="SINGLE",r.SHARED="SHARED",r.VERTEX="VERTEX",r.MORTON="MORTON",r.FSST="FSST"})(xr||(xr={})),(function(r){r.VERTEX="VERTEX",r.INDEX="INDEX",r.STRING="STRING",r.KEY="KEY"})(as||(as={})),(function(r){r.VAR_BINARY="VAR_BINARY",r.GEOMETRIES="GEOMETRIES",r.PARTS="PARTS",r.RINGS="RINGS",r.TRIANGLES="TRIANGLES",r.SYMBOL="SYMBOL",r.DICTIONARY="DICTIONARY"})(Zi||(Zi={})),(function(r){r[r.FLAT=0]="FLAT",r[r.CONST=1]="CONST",r[r.SEQUENCE=2]="SEQUENCE",r[r.DICTIONARY=3]="DICTIONARY",r[r.FSST_DICTIONARY=4]="FSST_DICTIONARY"})(dt||(dt={}));class br{constructor(e,i){this.values=e,this._size=i}get(e){let i=Math.floor(e/8);return(this.values[i]>>e%8&1)==1}set(e,i){let o=Math.floor(e/8);this.values[o]=this.values[o]|(i?1:0)<>e%8&1}size(){return this._size}getBuffer(){return this.values}}function wa(r,e,i){if(!e)return r;let o=e.size(),s=new r.constructor(o),l=0;for(let h=0;h=4)for(;b>>0;for(let T=1;T>>0;return _})(h.logicalLevelTechnique2===Ge.RLE?rd(l,h.runs,h.numRleValues):l);break;case Ge.RLE:m=rd(l,h.runs,h.numRleValues);break;case Ge.MORTON:od(l),m=l;break;case Ge.COMPONENTWISE_DELTA:m=(function(v){if(v.length<2)return new Uint32Array(v);let _=new Uint32Array(v.length);_[0]=st(v[0])>>>0,_[1]=st(v[1])>>>0;for(let T=2;T>>0,_[T+1]=_[T-1]+st(v[T+1])>>>0;return _})(l);break;case Ge.NONE:m=l;break;default:throw new Error(`The specified Logical level technique is not supported: ${h.logicalLevelTechnique1}`)}return g?wa(m,g,0):m})(Ta(r,e,i),i,0,s)}function po(r,e,i){return(function(o,s){if(s.logicalLevelTechnique1===Ge.DELTA&&s.logicalLevelTechnique2===Ge.NONE)return(function(l){let h=new Int32Array(l.length+1);h[0]=0,h[1]=st(l[0]);let d=h[1];for(let g=2;g!==h.length;++g)d+=st(l[g-1]),h[g]=h[g-1]+d;return new Uint32Array(h)})(o);if(s.logicalLevelTechnique1===Ge.RLE&&s.logicalLevelTechnique2===Ge.NONE)return(function(l,h,d){let g=new Uint32Array(d+1);g[0]=0;let m=1,v=g[0];for(let _=0;_>>2,M=(function(D,L){if(L<=D.encodedWords.length)return D.encodedWords;let R=new Uint32Array(Math.max(16,2*L));return D.encodedWords=R,R})(T,I);(function(D,L,R,F){if(L<0||R<0||L+R>D.length)throw new RangeError(`decodeBigEndianInt32sInto: out of bounds (offset=${L}, byteLength=${R}, bytes.length=${D.length})`);let O=Math.floor(R/4),V=R%4!=0,Y=V?O+1:O;if(F.length0){let J=D.byteOffset+L;if(3&J)for(let re=0;re0){let J=0|D[F];if(F=F+1|0,255&J)throw new Error(`FastPFOR decode: invalid alignedLength=${J} (expected multiple of 256)`);if(O+J>V.length)throw new Error(`FastPFOR decode: output buffer too small (outPos=${O}, alignedLength=${J}, out.length=${V.length})`);F=(function(re,te,ae,le,ne,ie){let fe=le+td(ne,Mn),xe=le,ye=ae;for(;xe!==fe;){let me=Math.min(id,fe-xe);ye=Xg(re,te,ye,xe,me,ie),xe=xe+me|0}return ye})(D,V,F,O,J,Y),O=O+J|0}return(function(J,re,te,ae,le,ne){if(ne===0)return re;let ie=0,fe=re,xe=re+te,ye=le,me=le,Ae=le+ne,Ye=0,Je=0;for(;fe>>ie&255;if(ie+=8,fe+=ie>>>5,ie&=31,Ye|=(127&nt)<28)throw new Error(`FastPFOR VByte: unterminated value (expected MSB=1 terminator within 5 bytes; shift=${Je}, partial=${Ye}, decoded=${me-ye}/${ne}, inPos=${fe}, inEnd=${xe})`)}if(me!==Ae)throw new Error(`FastPFOR VByte: truncated stream (decoded=${me-ye}, expected=${ne}, consumedWords=${fe-re}/${te}, vbyteStart=${re}, vbyteEnd=${xe})`)})(D,F,D.length-F|0,V,O,L-O|0),V})(M.subarray(0,I),m,T.decoderWorkspace);return _.add(v),A})(s,l,h,d,(function(g=16){if(g<0)throw new RangeError(`initialEncodedWordCapacity must be >= 0, got ${g}`);let m=Math.max(16,0|g);return{encodedWords:new Uint32Array(m),decoderWorkspace:qp()}})(h>>>2))})(r,i.numValues,i.byteLength,e);case ho.VARINT:return fi(r,e,i.numValues);case ho.NONE:{let s=e.get();e.add(i.byteLength);let l=r.subarray(s,e.get());return new Uint32Array(l)}default:throw new Error(`Specified physicalLevelTechnique ${o} is not supported (yet).`)}}function ad(r,e,i){let o=Ta(r,e,i);return o.length===1?o[0]:(function(s){return s[1]})(o)}function Kp(r,e,i){return(function(o){if(o.length===2){let s=st(o[1]);return[s,s]}return[st(o[2]),st(o[3])]})(Ta(r,e,i))}function Jp(r,e,i){return(function(o){if(o.length===2){let s=Ti(o[1]);return[s,s]}return[Ti(o[2]),Ti(o[3])]})(xa(r,e,i.numValues))}function Qp(r,e,i,o){return(function(s,l,h){let d;switch(l.logicalLevelTechnique1){case Ge.DELTA:d=(function(g){let m=new BigUint64Array(g.length);m[0]=BigInt.asUintN(64,Ti(g[0]));for(let v=1;v>1,e)-i}}function nf(r,e){let i=0;for(let o=0;o>o;return i}function Pa(r,e,i,o,s,l,h){return r===uo.MORTON?(function(d,g,m,v,_,T){let b=new Array(_?v+1:v);for(let I=0;I[O])),o+=R,s+=R}break;case jt.LINESTRING:{let R,F;A?(R=b[s]-b[s-1],s++):R=T[o]-T[o-1],o++,M?(F=Sa(D,d,R,!1),d+=2*R):(F=Pa(e.vertexBufferType,D,I,g,R,!1,m),g+=R),i[h++]=[F],_&&l++}break;case jt.POLYGON:{let R=T[o]-T[o-1];o++;let F=new Array(R-1),O,V=b[s]-b[s-1];if(s++,M){O=Sa(D,d,V,!0),d+=2*V;for(let Y=0;Y0&&M.push(M[0]),T.push(M)}e[v]=T,l&&m++}break;case jt.MULTIPOLYGON:{let _=l[m]-l[m-1];m++;let T=[];for(let b=0;b<_;b++){let I=o[d]-o[d-1];d++;for(let M=0;M0&&D.push(D[0]),T.push(D)}}e[v]=T}}return e}[Symbol.iterator](){return null}}function cf(r,e,i,o,s,l){return new Qg(r,e,i,o,s,l)}class Qg extends lf{constructor(e,i,o,s,l,h){super(o,s,l,h),this._numGeometries=e,this._geometryType=i}geometryType(e){return this._geometryType}get numGeometries(){return this._numGeometries}containsSingleGeometryType(){return!0}}function hf(r,e,i,o,s){return new e_(r,e,i,o,s)}class e_ extends lf{constructor(e,i,o,s,l){super(i,o,s,l),this._geometryTypes=e}geometryType(e){return this._geometryTypes[e]}get numGeometries(){return this._geometryTypes.length}containsSingleGeometryType(){return!1}}function t_(r,e,i,o,s){let l=Pi(r,i),h,d,g,m;if(Mh(l,o,r,i)===dt.CONST){let L=ad(r,i,l),R,F,O,V;for(let Y=0;Yi?e[l++]:1);return o}function uf(r,e,i,o){let s=new Uint32Array(e[e.length-1]+1),l=0;s[0]=l;let h=1,d=0;for(let g=0;g=T);){let b=h[m.increment()];if(b<=127){let I=b+3,M=h[m.increment()],A=Math.min(_+I,d);v.fill(M,_,A),_=A}else{let I=256-b;for(let M=0;M=12?n_.decode(r.subarray(e,i)):(function(o,s,l){let h="",d=s;for(;d239?4:g>223?3:g>191?2:1;if(d+b>l)break;b===1?g<128&&(T=g):b===2?(m=o[d+1],(192&m)==128&&(T=(31&g)<<6|63&m,T<=127&&(T=null))):b===3?(m=o[d+1],v=o[d+2],(192&m)==128&&(192&v)==128&&(T=(15&g)<<12|(63&m)<<6|63&v,(T<=2047||T>=55296&&T<=57343)&&(T=null))):b===4&&(m=o[d+1],v=o[d+2],_=o[d+3],(192&m)==128&&(192&v)==128&&(192&_)==128&&(T=(15&g)<<18|(63&m)<<12|(63&v)<<6|63&_,(T<=65535||T>=1114112)&&(T=null))),T===null?(T=65533,b=1):T>65535&&(T-=65536,h+=String.fromCharCode(T>>>10&1023|55296),T=56320|1023&T),h+=String.fromCharCode(T),d+=b}return h})(r,e,i)}class ud extends va{constructor(e,i,o,s){super(e,o,s),this.offsetBuffer=i}}class pf extends ud{constructor(e,i,o,s){super(e,i,o,s??i.length-1)}getValueFromBuffer(e){return hd(this.dataBuffer,this.offsetBuffer[e],this.offsetBuffer[e+1])}}class Ia extends ud{constructor(e,i,o,s,l){super(e,o,s,l??i.length),this.indexBuffer=i,this.indexBuffer=i}getValueFromBuffer(e){let i=this.indexBuffer[e];return hd(this.dataBuffer,this.offsetBuffer[i],this.offsetBuffer[i+1])}}class ff extends ud{constructor(e,i,o,s,l,h,d){super(e,o,s,d),this.indexBuffer=i,this.symbolOffsetBuffer=l,this.symbolTableBuffer=h}getValueFromBuffer(e){this.decodedDictionary==null&&(this.symbolLengthBuffer==null&&(this.symbolLengthBuffer=this.offsetToLengthBuffer(this.symbolOffsetBuffer)),this.decodedDictionary=(function(o,s,l){let h=[],d=new Array(s.length).fill(0);for(let g=1;g=10}function _f(r){return r===30}function s_(r){if(r.type==="scalarType"){let e=r.scalarType;if(e.type==="physicalType")switch(e.physicalType){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:default:return!1;case 9:return!0}if(e.type==="logicalType")return!1}else if(r.type==="complexType"){let e=r.complexType;if(e.type==="physicalType")switch(e.physicalType){case 0:case 1:return!0;default:return!1}}return console.warn("Unexpected column type in hasStreamCount",r),!1}function a_(r){return r.type==="complexType"&&r.complexType?.type==="physicalType"&&r.complexType.physicalType===0}let l_=new TextDecoder;function dd(r,e){let i=fi(r,e,1)[0];if(i===0)return"";let o=e.get(),s=r.subarray(o,o+i);return e.add(i),l_.decode(s)}function yf(r,e){let i=fi(r,e,1)[0]>>>0;if(i<10||i>30)throw new Error(`Unsupported field type code ${i}. Supported: 10-29(scalars), 30(STRUCT)`);let o=mf(i);if(gf(i)&&(o.name=dd(r,e)),_f(i)){let s=fi(r,e,1)[0]>>>0;o.complexType.children=new Array(s);for(let l=0;l>>0,o=mf(i);if(!o)throw new Error(`Unsupported column type code ${i}. Supported: 0-3(ID), 4(GEOMETRY), 10-29(scalars), 30(STRUCT)`);if(gf(i)?o.name=dd(r,e):i>=0&&i<=3?o.name="id":i===4&&(o.name="geometry"),_f(i)){let s=fi(r,e,1)[0]>>>0,l=o.complexType;l.children=new Array(s);for(let h=0;h>>0,l=fi(r,e,1)[0]>>>0;o.columns=new Array(l);for(let h=0;h=4)for(;O>>0,v=h.get()+m;if(v>o.length)throw new Error(`Block overruns tile: ${v} > ${o.length}`);if(fi(o,h,1)[0]>>>0!=1){h.set(v);continue}let[_,T]=h_(o,h),b=_.featureTables[0],I=null,M=null,A=[],D=0;for(let R of b.columns){let F=R.name;if((g=R).type==="scalarType"&&g.scalarType?.type==="logicalType"&&g.scalarType.logicalType===0){let O=null;if(R.nullable){let Y=Pi(o,h),J=h.get(),re=Ql(o,Y.numValues,Y.byteLength,h);h.set(J+Y.byteLength),O=new br(re,Y.numValues)}let V=Pi(o,h);D=O?O.size():V.decompressedCount,I=u_(o,R,h,F,V,O??D,l)}else if(a_(R)){let O=fi(o,h,1)[0];if(D===0){let V=h.get();D=Pi(o,h).decompressedCount,h.set(V)}M=t_(o,O,h,D)}else{let O=s_(R)?fi(o,h,1)[0]:1;if(O===0)continue;let V=o_(o,h,R,O,D);if(V)if(Array.isArray(V))for(let Y of V)A.push(Y);else A.push(V)}}let L=new Gg(b.name,M,I,A,T);d.push(L),h.set(v)}var g;return d})(new Uint8Array(e));this.layers=i.reduce(((o,s)=>Object.assign(Object.assign({},o),{[s.name]:new p_(s)})),{})}}class f_{constructor(e,i){this.feature=e,this.type=e.type,this.properties=e.tags?e.tags:{},this.extent=i,"id"in e&&(typeof e.id=="string"?this.id=parseInt(e.id,10):typeof e.id!="number"||isNaN(e.id)||(this.id=e.id))}loadGeometry(){let e=[],i=this.feature.type===1?[this.feature.geometry]:this.feature.geometry;for(let o of i){let s=[];for(let l of o)s.push(new Te(l[0],l[1]));e.push(s)}return e}}let tc="_geojsonTileLayer";function m_(r,e,i=""){e.writeVarintField(15,r.version||1),e.writeStringField(1,r.name||""),e.writeVarintField(5,r.extent||4096);let o={jsonPrefix:i,keys:[],values:[],keycache:{},valuecache:{}};for(let h=0;h>31}function y_(r,e){let i=r.loadGeometry(),o=r.type,s=0,l=0;for(let h of i){let d=1;o===1&&(d=h.length),e.writeVarint(pd(1,d));let g=o===3?h.length-1:h.length;for(let m=0;m=0&&v[3]>=0&&g.insert(d,v[0],v[1],v[2],v[3])}}loadVTLayers(){return this.vtLayers||(this.vtLayers=this.encoding!=="mlt"?new Wd(new bh(this.rawTileData)).layers:new vf(this.rawTileData).layers,this.sourceLayerCoder=new Up(this.vtLayers?Object.keys(this.vtLayers).sort():[tc])),this.vtLayers}query(e,i,o,s){this.loadVTLayers();let l=e.params,h=De/e.tileSize/e.scale,d=No(l.filter,l.globalState),g=e.queryGeometry,m=e.queryPadding*h,v=ss.fromPoints(g),_=this.grid.query(v.minX-m,v.minY-m,v.maxX+m,v.maxY+m),T=ss.fromPoints(e.cameraQueryGeometry).expandBy(m),b=this.grid3D.query(T.minX,T.minY,T.maxX,T.maxY,((A,D,L,R)=>(function(F,O,V,Y,J){for(let te of F)if(O<=te.x&&V<=te.y&&Y>=te.x&&J>=te.y)return!0;let re=[new Te(O,V),new Te(O,J),new Te(Y,J),new Te(Y,V)];if(F.length>2){for(let te of re)if(aa(F,te))return!0}for(let te=0;te(L||(L=$r(R)),F.queryIntersectsFeature({queryGeometry:g,feature:R,featureState:O,geometry:L,zoom:this.z,transform:e.transform,pixelsToTileUnits:h,pixelPosMatrix:e.pixelPosMatrix,unwrappedTileID:this.tileID.toUnwrapped(),getElevation:e.getElevation}))))}return I}loadMatchingFeature(e,i,o,s,l,h,d,g,m,v,_){let T=this.bucketLayerIDs[i];if(h&&!T.some((A=>h.has(A))))return;let b=this.sourceLayerCoder.decode(o),I=this.vtLayers[b].feature(s);if(l.needGeometry){let A=Zr(I,!0);if(!l.filter(new ct(this.tileID.overscaledZ),A,this.tileID.canonical))return}else if(!l.filter(new ct(this.tileID.overscaledZ),I))return;let M=this.getId(I,b);for(let A of T){if(h&&!h.has(A))continue;let D=g[A];if(!D)continue;let L={};M&&v&&(L=v.getState(D.sourceLayer||tc,M));let R=Oi({},m[A]);R.paint=wf(R.paint,D.paint,I,L,d),R.layout=wf(R.layout,D.layout,I,L,d);let F=!_||_(I,D,L);if(!F)continue;let O=new Gp(I,this.z,this.x,this.y,M);O.layer=R;let V=e[A];V===void 0&&(V=e[A]=[]),V.push({featureIndex:s,feature:O,intersectionZ:F})}}lookupSymbolFeatures(e,i,o,s,l,h,d,g){let m={};this.loadVTLayers();let v=No(l.filterSpec,l.globalState);for(let _ of e)this.loadMatchingFeature(m,o,s,_,v,h,d,g,i);return m}hasLayer(e){for(let i of this.bucketLayerIDs)for(let o of i)if(e===o)return!0;return!1}getId(e,i){var o;let s=e.id;return this.promoteId&&(s=e.properties[typeof this.promoteId=="string"?this.promoteId:this.promoteId[i]],typeof s=="boolean"&&(s=Number(s)),s===void 0&&(!((o=e.properties)===null||o===void 0)&&o.cluster)&&this.promoteId&&(s=Number(e.properties.cluster_id))),s}}function wf(r,e,i,o,s){return Er(r,((l,h)=>{let d=e instanceof Ko?e.get(h):null;return d?.evaluate?d.evaluate(i,o,s):d}))}function x_(r,e){return e-r}function Tf(r,e,i,o,s){let l=[];for(let h of r){let d;for(let g=0;g=o&&v.x>=o||(m.x>=o?m=new Te(o,m.y+(o-m.x)/(v.x-m.x)*(v.y-m.y))._round():v.x>=o&&(v=new Te(o,m.y+(o-m.x)/(v.x-m.x)*(v.y-m.y))._round()),m.y>=s&&v.y>=s||(m.y>=s?m=new Te(m.x+(s-m.y)/(v.y-m.y)*(v.x-m.x),s)._round():v.y>=s&&(v=new Te(m.x+(s-m.y)/(v.y-m.y)*(v.x-m.x),s)._round()),d&&m.equals(d[d.length-1])||(d=[m],l.push(d)),d.push(v)))))}}return l}function Pf(r,e,i,o,s){switch(e){case 1:return(function(l,h,d,g){let m=[];for(let v of l)for(let _ of v){let T=g===0?_.x:_.y;T>=h&&T<=d&&m.push([_])}return m})(r,i,o,s);case 2:return Sf(r,i,o,s,!1);case 3:return Sf(r,i,o,s,!0)}return[]}function b_(r,e,i,o,s){let l=o===0?w_:T_,h=[],d=[];for(let v=0;ve&&h.push(l(_,T,e)):b>i?I=e&&(h.push(l(_,T,e)),M=!0),I>i&&b<=i&&(h.push(l(_,T,i)),M=!0),!s&&M&&(d.push(h),h=[])}let g=r.length-1,m=o===0?r[g].x:r[g].y;return m>=e&&m<=i&&h.push(r[g]),s&&h.length>0&&!h[0].equals(h[h.length-1])&&h.push(new Te(h[0].x,h[0].y)),h.length>0&&d.push(h),d}function Sf(r,e,i,o,s){let l=[];for(let h of r){let d=b_(h,e,i,o,s);d.length>0&&l.push(...d)}return l}function w_(r,e,i){return new Te(i,r.y+(i-r.x)/(e.x-r.x)*(e.y-r.y))}function T_(r,e,i){return new Te(r.x+(i-r.y)/(e.y-r.y)*(e.x-r.x),i)}Pe("FeatureIndex",bf,{omit:["rawTileData","sourceLayerCoder"]});class fo extends Te{constructor(e,i,o,s){super(e,i),this.angle=o,s!==void 0&&(this.segment=s)}clone(){return new fo(this.x,this.y,this.angle,this.segment)}}function If(r,e,i,o,s){if(e.segment===void 0||i===0)return!0;let l=e,h=e.segment+1,d=0;for(;d>-i/2;){if(h--,h<0)return!1;d-=r[h].dist(l),l=r[h]}d+=r[h].dist(r[h+1]),h++;let g=[],m=0;for(;do;)m-=g.shift().angleDelta;if(m>s)return!1;h++,d+=v.dist(_)}return!0}function Mf(r){let e=0;for(let i=0;im){let I=(m-g)/b,M=Ai.number(_.x,T.x,I),A=Ai.number(_.y,T.y,I),D=new fo(M,A,T.angleTo(_),v);return D._round(),!h||If(r,D,d,h,e)?D:void 0}g+=b}}function S_(r,e,i,o,s,l,h,d,g){let m=Ef(o,l,h),v=Cf(o,s),_=v*h,T=r[0].x===0||r[0].x===g||r[0].y===0||r[0].y===g;return e-_=0&&F=0&&O=0&&T+m<=v){let V=new fo(F,O,L,I);V._round(),o&&!If(r,V,l,o,s)||b.push(V)}}_+=D}return d||b.length||h||(b=Af(r,_/2,i,o,s,l,h,!0,g)),b}function Df(r,e,i,o){let s=[],l=r.image,h=l.pixelRatio,d=l.paddedRect.w-2,g=l.paddedRect.h-2,m={x1:r.left,y1:r.top,x2:r.right,y2:r.bottom},v=l.stretchX||[[0,d]],_=l.stretchY||[[0,g]],T=(ie,fe)=>ie+fe[1]-fe[0],b=v.reduce(T,0),I=_.reduce(T,0),M=d-b,A=g-I,D=0,L=b,R=0,F=I,O=0,V=M,Y=0,J=A;if(l.content&&o){let ie=l.content,fe=ie[2]-ie[0],xe=ie[3]-ie[1];(l.textFitWidth||l.textFitHeight)&&(m=Ip(r)),D=Eh(v,0,ie[0]),R=Eh(_,0,ie[1]),L=Eh(v,ie[0],ie[2]),F=Eh(_,ie[1],ie[3]),O=ie[0]-D,Y=ie[1]-R,V=fe-L,J=xe-F}let re=m.x1,te=m.y1,ae=m.x2-re,le=m.y2-te,ne=(ie,fe,xe,ye)=>{let me=Ch(ie.stretch-D,L,ae,re),Ae=Ah(ie.fixed-O,V,ie.stretch,b),Ye=Ch(fe.stretch-R,F,le,te),Je=Ah(fe.fixed-Y,J,fe.stretch,I),nt=Ch(xe.stretch-D,L,ae,re),si=Ah(xe.fixed-O,V,xe.stretch,b),Tt=Ch(ye.stretch-R,F,le,te),Ft=Ah(ye.fixed-Y,J,ye.stretch,I),Ut=new Te(me,Ye),pt=new Te(nt,Ye),Qt=new Te(nt,Tt),mi=new Te(me,Tt),gi=new Te(Ae/h,Je/h),Li=new Te(si/h,Ft/h),ai=e*Math.PI/180;if(ai){let Gt=Math.sin(ai),yt=Math.cos(ai),Rt=[yt,-Gt,Gt,yt];Ut._matMult(Rt),pt._matMult(Rt),mi._matMult(Rt),Qt._matMult(Rt)}let Fi=ie.stretch+ie.fixed,lr=fe.stretch+fe.fixed;return{tl:Ut,tr:pt,bl:mi,br:Qt,tex:{x:l.paddedRect.x+1+Fi,y:l.paddedRect.y+1+lr,w:xe.stretch+xe.fixed-Fi,h:ye.stretch+ye.fixed-lr},writingMode:void 0,glyphOffset:[0,0],sectionIndex:0,pixelOffsetTL:gi,pixelOffsetBR:Li,minFontScaleX:V/h/ae,minFontScaleY:J/h/le,isSDF:i}};if(o&&(l.stretchX||l.stretchY)){let ie=zf(v,M,b),fe=zf(_,A,I);for(let xe=0;xe0&&(M=Math.max(10,M),this.circleDiameter=M)}else{let T=!((_=h.image)===null||_===void 0)&&_.content&&(h.image.textFitWidth||h.image.textFitHeight)?Ip(h):{x1:h.left,y1:h.top,x2:h.right,y2:h.bottom};T.y1=T.y1*d-g[0],T.y2=T.y2*d+g[2],T.x1=T.x1*d-g[3],T.x2=T.x2*d+g[1];let b=h.collisionPadding;if(b&&(T.x1-=b[0]*d,T.y1-=b[1]*d,T.x2+=b[2]*d,T.y2+=b[3]*d),v){let I=new Te(T.x1,T.y1),M=new Te(T.x2,T.y1),A=new Te(T.x1,T.y2),D=new Te(T.x2,T.y2),L=v*Math.PI/180;I._rotate(L),M._rotate(L),A._rotate(L),D._rotate(L),T.x1=Math.min(I.x,M.x,A.x,D.x),T.x2=Math.max(I.x,M.x,A.x,D.x),T.y1=Math.min(I.y,M.y,A.y,D.y),T.y2=Math.max(I.y,M.y,A.y,D.y)}e.emplaceBack(i.x,i.y,T.x1,T.y1,T.x2,T.y2,o,s,l)}this.boxEndIndex=e.length}}class I_{constructor(e=[],i=(o,s)=>os?1:0){if(this.data=e,this.length=this.data.length,this.compare=i,this.length>0)for(let o=(this.length>>1)-1;o>=0;o--)this._down(o)}push(e){this.data.push(e),this._up(this.length++)}pop(){if(this.length===0)return;let e=this.data[0],i=this.data.pop();return--this.length>0&&(this.data[0]=i,this._down(0)),e}peek(){return this.data[0]}_up(e){let{data:i,compare:o}=this,s=i[e];for(;e>0;){let l=e-1>>1,h=i[l];if(o(s,h)>=0)break;i[e]=h,e=l}i[e]=s}_down(e){let{data:i,compare:o}=this,s=this.length>>1,l=i[e];for(;e=0)break;i[e]=i[h],e=h}i[e]=l}}function M_(r,e=1){let i=ss.fromPoints(r[0]),o=Math.min(i.width(),i.height()),s=o/2,l=new I_([],E_),{minX:h,minY:d,maxX:g,maxY:m}=i;if(o===0)return new Te(h,d);for(let T=h;T_.d||!_.d)&&(_=T),T.max-_.d<=e||(s=T.h/2,l.push(new Ma(T.p.x-s,T.p.y-s,s,r)),l.push(new Ma(T.p.x+s,T.p.y-s,s,r)),l.push(new Ma(T.p.x-s,T.p.y+s,s,r)),l.push(new Ma(T.p.x+s,T.p.y+s,s,r)))}return v.d>0&&_.d-v.d<=e?v.p:_.p}function E_(r,e){return e.max-r.max}class Ma{constructor(e,i,o,s){this.p=new Te(e,i),this.h=o,this.d=(function(l,h){let d=!1,g=1/0;for(let m of h)for(let v=0,_=m.length,T=_-1;v<_;T=v++){let b=m[v],I=m[T];b.y>l.y!=I.y>l.y&&l.x<(I.x-b.x)*(l.y-b.y)/(I.y-b.y)+b.x&&(d=!d),g=Math.min(g,wd(l,b,I))}return(d?1:-1)*Math.sqrt(g)})(this.p,s),this.max=this.d+this.h*Math.SQRT2}}var oi;k.aM=void 0,(oi=k.aM||(k.aM={}))[oi.center=1]="center",oi[oi.left=2]="left",oi[oi.right=3]="right",oi[oi.top=4]="top",oi[oi.bottom=5]="bottom",oi[oi["top-left"]=6]="top-left",oi[oi["top-right"]=7]="top-right",oi[oi["bottom-left"]=8]="bottom-left",oi[oi["bottom-right"]=9]="bottom-right";let fd=Number.POSITIVE_INFINITY;function Rf(r,e){return e[1]!==fd?(function(i,o,s){let l=0,h=0;switch(o=Math.abs(o),s=Math.abs(s),i){case"top-right":case"top-left":case"top":h=s-7;break;case"bottom-right":case"bottom-left":case"bottom":h=7-s}switch(i){case"top-right":case"bottom-right":case"right":l=-o;break;case"top-left":case"bottom-left":case"left":l=o}return[l,h]})(r,e[0],e[1]):(function(i,o){let s=0,l=0;o<0&&(o=0);let h=o/Math.SQRT2;switch(i){case"top-right":case"top-left":l=h-7;break;case"bottom-right":case"bottom-left":l=7-h;break;case"bottom":l=7-o;break;case"top":l=o-7}switch(i){case"top-right":case"bottom-right":s=-h;break;case"top-left":case"bottom-left":s=h;break;case"left":s=o;break;case"right":s=-o}return[s,l]})(r,e[0])}function kf(r,e,i){var o;let s=r.layout,l=(o=s.get("text-variable-anchor-offset"))===null||o===void 0?void 0:o.evaluate(e,{},i);if(l){let d=l.values,g=[];for(let m=0;mT*Vt));v.startsWith("top")?_[1]-=7:v.startsWith("bottom")&&(_[1]+=7),g[m+1]=_}return new ci(g)}let h=s.get("text-variable-anchor");if(h){let d;d=r._unevaluatedLayout.getValue("text-radial-offset")!==void 0?[s.get("text-radial-offset").evaluate(e,{},i)*Vt,fd]:s.get("text-offset").evaluate(e,{},i).map((m=>m*Vt));let g=[];for(let m of h)g.push(m,Rf(m,d));return new ci(g)}return null}function md(r){switch(r){case"right":case"top-right":case"bottom-right":return"right";case"left":case"top-left":case"bottom-left":return"left"}return"center"}function C_(r,e,i,o,s,l,h,d,g,m,v,_){let T=l.textMaxSize.evaluate(e,{});T===void 0&&(T=h);let b=r.layers[0].layout,I=b.get("icon-offset").evaluate(e,{},v),M=Ff(i.horizontal),A=h/24,D=r.tilePixelRatio*A,L=r.tilePixelRatio*T/24,R=r.tilePixelRatio*d,F=r.tilePixelRatio*b.get("symbol-spacing"),O=b.get("text-padding")*r.tilePixelRatio,V=(function(xe,ye,me,Ae=1){let Ye=xe.get("icon-padding").evaluate(ye,{},me),Je=Ye?.values;return[Je[0]*Ae,Je[1]*Ae,Je[2]*Ae,Je[3]*Ae]})(b,e,v,r.tilePixelRatio),Y=b.get("text-max-angle")/180*Math.PI,J=b.get("text-rotation-alignment")!=="viewport"&&b.get("symbol-placement")!=="point",re=b.get("icon-rotation-alignment")==="map"&&b.get("symbol-placement")!=="point",te=b.get("symbol-placement"),ae=F/2,le=b.get("icon-text-fit"),ne;o&&le!=="none"&&(r.allowVerticalPlacement&&i.vertical&&(ne=Mp(o,i.vertical,le,b.get("icon-text-fit-padding"),I,A)),M&&(o=Mp(o,M,le,b.get("icon-text-fit-padding"),I,A)));let ie=v?_.line.getGranularityForZoomLevel(v.z):1,fe=(xe,ye)=>{ye.x<0||ye.x>=De||ye.y<0||ye.y>=De||(function(me,Ae,Ye,Je,nt,si,Tt,Ft,Ut,pt,Qt,mi,gi,Li,ai,Fi,lr,Gt,yt,Rt,Pt,$t,En,wr,ic){let mo=me.addToLineVertexArray(Ae,Ye),ls,Ea,Ca,Aa,Bf=0,Of=0,Nf=0,Vf=0,gd=-1,_d=-1,Cn={},jf=Nt("");if(me.allowVerticalPlacement&&Je.vertical){let _i=Ft.layout.get("text-rotate").evaluate(Pt,{},wr)+90;Ca=new Dh(Ut,Ae,pt,Qt,mi,Je.vertical,gi,Li,ai,_i),Tt&&(Aa=new Dh(Ut,Ae,pt,Qt,mi,Tt,lr,Gt,ai,_i))}if(nt){let _i=Ft.layout.get("icon-rotate").evaluate(Pt,{}),tr=Ft.layout.get("icon-text-fit")!=="none",cs=Df(nt,_i,En,tr),Pr=Tt?Df(Tt,_i,En,tr):void 0;Ea=new Dh(Ut,Ae,pt,Qt,mi,nt,lr,Gt,!1,_i),Bf=4*cs.length;let hs=me.iconSizeData,qr=null;hs.kind==="source"?(qr=[In*Ft.layout.get("icon-size").evaluate(Pt,{})],qr[0]>lo&&Wt(`${me.layerIds[0]}: Value for "icon-size" is >= 255. Reduce your "icon-size".`)):hs.kind==="composite"&&(qr=[In*$t.compositeIconSizes[0].evaluate(Pt,{},wr),In*$t.compositeIconSizes[1].evaluate(Pt,{},wr)],(qr[0]>lo||qr[1]>lo)&&Wt(`${me.layerIds[0]}: Value for "icon-size" is >= 255. Reduce your "icon-size".`)),me.addSymbols(me.icon,cs,qr,Rt,yt,Pt,k.ax.none,Ae,mo.lineStartIndex,mo.lineLength,-1,wr),gd=me.icon.placedSymbolArray.length-1,Pr&&(Of=4*Pr.length,me.addSymbols(me.icon,Pr,qr,Rt,yt,Pt,k.ax.vertical,Ae,mo.lineStartIndex,mo.lineLength,-1,wr),_d=me.icon.placedSymbolArray.length-1)}let Uf=Object.keys(Je.horizontal);for(let _i of Uf){let tr=Je.horizontal[_i];if(!ls){jf=Nt(tr.text);let Pr=Ft.layout.get("text-rotate").evaluate(Pt,{},wr);ls=new Dh(Ut,Ae,pt,Qt,mi,tr,gi,Li,ai,Pr)}let cs=tr.positionedLines.length===1;if(Nf+=Lf(me,Ae,tr,si,Ft,ai,Pt,Fi,mo,Je.vertical?k.ax.horizontal:k.ax.horizontalOnly,cs?Uf:[_i],Cn,gd,$t,wr),cs)break}Je.vertical&&(Vf+=Lf(me,Ae,Je.vertical,si,Ft,ai,Pt,Fi,mo,k.ax.vertical,["vertical"],Cn,_d,$t,wr));let D_=ls?ls.boxStartIndex:me.collisionBoxArray.length,z_=ls?ls.boxEndIndex:me.collisionBoxArray.length,R_=Ca?Ca.boxStartIndex:me.collisionBoxArray.length,k_=Ca?Ca.boxEndIndex:me.collisionBoxArray.length,L_=Ea?Ea.boxStartIndex:me.collisionBoxArray.length,F_=Ea?Ea.boxEndIndex:me.collisionBoxArray.length,B_=Aa?Aa.boxStartIndex:me.collisionBoxArray.length,O_=Aa?Aa.boxEndIndex:me.collisionBoxArray.length,Tr=-1,zh=(_i,tr)=>_i?.circleDiameter?Math.max(_i.circleDiameter,tr):tr;Tr=zh(ls,Tr),Tr=zh(Ca,Tr),Tr=zh(Ea,Tr),Tr=zh(Aa,Tr);let Gf=Tr>-1?1:0;Gf&&(Tr*=ic/Vt),me.glyphOffsetArray.length>=_a.MAX_GLYPHS&&Wt("Too many glyphs being rendered in a tile. See https://github.com/mapbox/mapbox-gl-js/issues/2907"),Pt.sortKey!==void 0&&me.addToSortKeyRanges(me.symbolInstances.length,Pt.sortKey);let N_=kf(Ft,Pt,wr),[V_,j_]=(function(_i,tr){let cs=_i.length,Pr=tr?.values;if(Pr?.length>0)for(let hs=0;hs=0?Cn.right:-1,Cn.center>=0?Cn.center:-1,Cn.left>=0?Cn.left:-1,Cn.vertical||-1,gd,_d,jf,D_,z_,R_,k_,L_,F_,B_,O_,pt,Nf,Vf,Bf,Of,Gf,0,gi,Tr,V_,j_)})(r,ye,xe,i,o,s,ne,r.layers[0],r.collisionBoxArray,e.index,e.sourceLayerIndex,r.index,D,[O,O,O,O],J,g,R,V,re,I,e,l,m,v,h)};if(te==="line")for(let xe of Tf(e.geometry,0,0,De,De)){let ye=os(xe,ie),me=S_(ye,F,Y,i.vertical||M,o,24,L,r.overscaling,De);for(let Ae of me)M&&A_(r,M.text,ae,Ae)||fe(ye,Ae)}else if(te==="line-center"){for(let xe of e.geometry)if(xe.length>1){let ye=os(xe,ie),me=P_(ye,Y,i.vertical||M,o,24,L);me&&fe(ye,me)}}else if(e.type==="Polygon")for(let xe of As(e.geometry,0)){let ye=M_(xe,16);fe(os(xe[0],ie,!0),new fo(ye.x,ye.y,0))}else if(e.type==="LineString")for(let xe of e.geometry){let ye=os(xe,ie);fe(ye,new fo(ye[0].x,ye[0].y,0))}else if(e.type==="Point")for(let xe of e.geometry)for(let ye of xe)fe([ye],new fo(ye.x,ye.y,0))}function Lf(r,e,i,o,s,l,h,d,g,m,v,_,T,b,I){let M=(function(L,R,F,O,V,Y,J,re){let te=O.layout.get("text-rotate").evaluate(Y,{})*Math.PI/180,ae=[];for(let le of R.positionedLines)for(let ne of le.positionedGlyphs){if(!ne.rect)continue;let ie=ne.rect||{},fe=4,xe=!0,ye=1,me=0,Ae=(V||re)&&ne.vertical,Ye=ne.metrics.advance*ne.scale/2;if(re&&R.verticalizable&&(me=le.lineOffset/2-(ne.imageName?-(Vt-ne.metrics.width*ne.scale)/2:(ne.scale-1)*Vt)),ne.imageName){let Gt=J[ne.imageName];xe=Gt.sdf,ye=Gt.pixelRatio,fe=1/ye}let Je=V?[ne.x+Ye,ne.y]:[0,0],nt=V?[0,0]:[ne.x+Ye+F[0],ne.y+F[1]-me],si=[0,0];Ae&&(si=nt,nt=[0,0]);let Tt=ne.metrics.isDoubleResolution?2:1,Ft=(ne.metrics.left-fe)*ne.scale-Ye+nt[0],Ut=(-ne.metrics.top-fe)*ne.scale+nt[1],pt=Ft+ie.w/Tt*ne.scale/ye,Qt=Ut+ie.h/Tt*ne.scale/ye,mi=new Te(Ft,Ut),gi=new Te(pt,Ut),Li=new Te(Ft,Qt),ai=new Te(pt,Qt);if(Ae){let Gt=new Te(-Ye,Ye- -17),yt=-Math.PI/2,Rt=12-Ye,Pt=new Te(22-Rt,-(ne.imageName?Rt:0)),$t=new Te(...si);mi._rotateAround(yt,Gt)._add(Pt)._add($t),gi._rotateAround(yt,Gt)._add(Pt)._add($t),Li._rotateAround(yt,Gt)._add(Pt)._add($t),ai._rotateAround(yt,Gt)._add(Pt)._add($t)}if(te){let Gt=Math.sin(te),yt=Math.cos(te),Rt=[yt,-Gt,Gt,yt];mi._matMult(Rt),gi._matMult(Rt),Li._matMult(Rt),ai._matMult(Rt)}let Fi=new Te(0,0),lr=new Te(0,0);ae.push({tl:mi,tr:gi,bl:Li,br:ai,tex:ie,writingMode:R.writingMode,glyphOffset:Je,sectionIndex:ne.sectionIndex,isSDF:xe,pixelOffsetTL:Fi,pixelOffsetBR:lr,minFontScaleX:0,minFontScaleY:0})}return ae})(0,i,d,s,l,h,o,r.allowVerticalPlacement),A=r.textSizeData,D=null;A.kind==="source"?(D=[In*s.layout.get("text-size").evaluate(h,{})],D[0]>lo&&Wt(`${r.layerIds[0]}: Value for "text-size" is >= 255. Reduce your "text-size".`)):A.kind==="composite"&&(D=[In*b.compositeTextSizes[0].evaluate(h,{},I),In*b.compositeTextSizes[1].evaluate(h,{},I)],(D[0]>lo||D[1]>lo)&&Wt(`${r.layerIds[0]}: Value for "text-size" is >= 255. Reduce your "text-size".`)),r.addSymbols(r.text,M,D,d,l,h,m,e,g.lineStartIndex,g.lineLength,T,I);for(let L of v)_[L]=r.text.placedSymbolArray.length-1;return 4*M.length}function Ff(r){for(let e in r)return r[e];return null}function A_(r,e,i,o){let s=r.compareText;if(e in s){let l=s[e];for(let h=l.length-1;h>=0;h--)if(o.dist(l[h])this.process())),this.subscription=us(this.target,"message",(i=>this.receive(i)),!1),this.globalScope=Ht(self)?r:window}registerMessageHandler(r,e){this.messageHandlers[r]=e}unregisterMessageHandler(r){delete this.messageHandlers[r]}sendAsync(r,e){return new Promise(((i,o)=>{let s=Math.round(1e18*Math.random()).toString(36).substring(0,10),l=e?us(e.signal,"abort",(()=>{l?.unsubscribe(),delete this.resolveRejects[s];let g={id:s,type:"",origin:location.origin,targetMapId:r.targetMapId,sourceMapId:this.mapId};this.target.postMessage(g)}),Ug):null;this.resolveRejects[s]={resolve:g=>{l?.unsubscribe(),i(g)},reject:g=>{l?.unsubscribe(),o(g)}};let h=[],d=Object.assign(Object.assign({},r),{id:s,sourceMapId:this.mapId,origin:location.origin,data:mr(r.data,h)});this.target.postMessage(d,{transfer:h})}))}receive(r){let e=r.data,i=e.id,o=["file://","resource://android","null"],s=[e.origin,location.origin],l=e.origin===location.origin,h=s.some((d=>o.includes(d)));if((l||h)&&(!e.targetMapId||this.mapId===e.targetMapId)){if(e.type===""){delete this.tasks[i];let d=this.abortControllers[i];return delete this.abortControllers[i],void(d&&d.abort())}if(Ht(self)||e.mustQueue)return this.tasks[i]=e,this.taskQueue.push(i),void this.invoker.trigger();this.processTask(i,e)}}process(){if(this.taskQueue.length===0)return;let r=this.taskQueue.shift(),e=this.tasks[r];delete this.tasks[r],this.taskQueue.length>0&&this.invoker.trigger(),e&&this.processTask(r,e)}processTask(r,e){return p(this,void 0,void 0,(function*(){if(e.type===""){let s=this.resolveRejects[r];return delete this.resolveRejects[r],s?void(e.error?s.reject(xt(Xo(e.error))):s.resolve(Xo(e.data))):void 0}if(!this.messageHandlers[e.type])return void this.completeTask(r,new Error(`Could not find a registered handler for ${e.type}, map ID: ${this.mapId}, available handlers: ${Object.keys(this.messageHandlers).join(", ")}`));let i=Xo(e.data),o=new AbortController;this.abortControllers[r]=o;try{let s=yield this.messageHandlers[e.type](e.sourceMapId,i,o);this.completeTask(r,null,s)}catch(s){this.completeTask(r,xt(s))}}))}completeTask(r,e,i){let o=[];delete this.abortControllers[r];let s={id:r,type:"",sourceMapId:this.mapId,origin:location.origin,error:e?mr(e):null,data:mr(i,o)};this.target.postMessage(s,{transfer:o})}remove(){this.invoker.remove(),this.subscription.unsubscribe()}},k.O=function(){var r=new kt(16);return kt!=Float32Array&&(r[1]=0,r[2]=0,r[3]=0,r[4]=0,r[6]=0,r[7]=0,r[8]=0,r[9]=0,r[11]=0,r[12]=0,r[13]=0,r[14]=0),r[0]=1,r[5]=1,r[10]=1,r[15]=1,r},k.P=Te,k.Q=function(r,e,i){var o,s,l,h,d,g,m,v,_,T,b,I,M=i[0],A=i[1],D=i[2];return e===r?(r[12]=e[0]*M+e[4]*A+e[8]*D+e[12],r[13]=e[1]*M+e[5]*A+e[9]*D+e[13],r[14]=e[2]*M+e[6]*A+e[10]*D+e[14],r[15]=e[3]*M+e[7]*A+e[11]*D+e[15]):(s=e[1],l=e[2],h=e[3],d=e[4],g=e[5],m=e[6],v=e[7],_=e[8],T=e[9],b=e[10],I=e[11],r[0]=o=e[0],r[1]=s,r[2]=l,r[3]=h,r[4]=d,r[5]=g,r[6]=m,r[7]=v,r[8]=_,r[9]=T,r[10]=b,r[11]=I,r[12]=o*M+d*A+_*D+e[12],r[13]=s*M+g*A+T*D+e[13],r[14]=l*M+m*A+b*D+e[14],r[15]=h*M+v*A+I*D+e[15]),r},k.R=ki,k.S=function(r,e,i){var o=i[0],s=i[1],l=i[2];return r[0]=e[0]*o,r[1]=e[1]*o,r[2]=e[2]*o,r[3]=e[3]*o,r[4]=e[4]*s,r[5]=e[5]*s,r[6]=e[6]*s,r[7]=e[7]*s,r[8]=e[8]*l,r[9]=e[9]*l,r[10]=e[10]*l,r[11]=e[11]*l,r[12]=e[12],r[13]=e[13],r[14]=e[14],r[15]=e[15],r},k.T=gu,k.U=function(r,e,i){var o=e[0],s=e[1],l=e[2],h=e[3],d=e[4],g=e[5],m=e[6],v=e[7],_=e[8],T=e[9],b=e[10],I=e[11],M=e[12],A=e[13],D=e[14],L=e[15],R=i[0],F=i[1],O=i[2],V=i[3];return r[0]=R*o+F*d+O*_+V*M,r[1]=R*s+F*g+O*T+V*A,r[2]=R*l+F*m+O*b+V*D,r[3]=R*h+F*v+O*I+V*L,r[4]=(R=i[4])*o+(F=i[5])*d+(O=i[6])*_+(V=i[7])*M,r[5]=R*s+F*g+O*T+V*A,r[6]=R*l+F*m+O*b+V*D,r[7]=R*h+F*v+O*I+V*L,r[8]=(R=i[8])*o+(F=i[9])*d+(O=i[10])*_+(V=i[11])*M,r[9]=R*s+F*g+O*T+V*A,r[10]=R*l+F*m+O*b+V*D,r[11]=R*h+F*v+O*I+V*L,r[12]=(R=i[12])*o+(F=i[13])*d+(O=i[14])*_+(V=i[15])*M,r[13]=R*s+F*g+O*T+V*A,r[14]=R*l+F*m+O*b+V*D,r[15]=R*h+F*v+O*I+V*L,r},k.V=function(r,e){let i={};for(let o of e)o in r&&(i[o]=r[o]);return i},k.W=co,k.X=zn,k.Y=Fp,k.Z=Lp,k._=p,k.a=xo,k.a$=function(r){var e=new kt(3);return e[0]=r[0],e[1]=r[1],e[2]=r[2],e},k.a0=Hr,k.a1=Ii,k.a2=Ra,k.a3=$i,k.a4=Op,k.a5=Sh,k.a6=De,k.a7=Jl,k.a8=ss,k.a9=25,k.aA=function(r){var e=r[0],i=r[1];return Math.sqrt(e*e+i*i)},k.aB=function(r){return r[0]=0,r[1]=0,r},k.aC=function(r,e,i){return r[0]=e[0]*i,r[1]=e[1]*i,r},k.aD=Gu,k.aE=Ze,k.aF=function(r,e,i,o){let s=e.y-r.y,l=e.x-r.x,h=o.y-i.y,d=o.x-i.x,g=h*l-d*s;if(g===0)return null;let m=(d*(r.y-i.y)-h*(r.x-i.x))/g;return new Te(r.x+m*l,r.y+m*s)},k.aG=Tf,k.aH=sa,k.aI=function(r){let e=1/0,i=1/0,o=-1/0,s=-1/0;for(let l of r)e=Math.min(e,l.x),i=Math.min(i,l.y),o=Math.max(o,l.x),s=Math.max(s,l.y);return[e,i,o,s]},k.aJ=Vt,k.aK=vt,k.aL=function(r,e,i,o,s=!1){if(!i[0]&&!i[1])return[0,0];let l=s?o==="map"?-r.bearingInRadians:0:o==="viewport"?r.bearingInRadians:0;if(l){let h=Math.sin(l),d=Math.cos(l);i=[i[0]*d-i[1]*h,i[0]*h+i[1]*d]}return[s?i[0]:vt(e,i[0],r.zoom),s?i[1]:vt(e,i[1],r.zoom)]},k.aN=Uu,k.aO=md,k.aP=ju,k.aQ=r=>r.type==="symbol",k.aR=mh,k.aS=ht,k.aT=fh,k.aU=N,k.aV=we,k.aW=ue,k.aX=Qr,k.aY=Np,k.aZ=K,k.a_=W,k.aa=Hu,k.ab=r=>{let e=window.document.createElement("video");return e.muted=!0,new Promise((i=>{e.onloadstart=()=>{i(e)};for(let o of r){let s=window.document.createElement("source");Hi(o)||(e.crossOrigin="Anonymous"),s.src=o,e.appendChild(s)}}))},k.ac=_e,k.ad=function(){return vo++},k.ae=c,k.af=_a,k.ag=tc,k.ah=No,k.ai=Zr,k.aj=Gp,k.ak=function(r){let e={};if(r.replace(/(?:^|(?:\s*\,\s*))([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)(?:\=(?:([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)|(?:\"((?:[^"\\]|\\.)*)\")))?/g,((i,o,s,l)=>{let h=s||l;return e[o]=!h||h.toLowerCase(),""})),e["max-age"]){let i=parseInt(e["max-age"],10);isNaN(i)?delete e["max-age"]:e["max-age"]=i}return e},k.al=li,k.am=85.051129,k.an=Ar,k.ao=function(r){return Math.pow(2,r)},k.ap=Dn,k.aq=Bp,k.ar=function(r){return Math.log(r)/Math.LN2},k.as=function(r){var e=r[0],i=r[1];return e*e+i*i},k.at=function(r){if(!r.length)return new Set;let e=Math.max(...r.map((g=>g.canonical.z))),i=1/0,o=-1/0,s=1/0,l=-1/0,h=[];for(let g of r){let{x:m,y:v,z:_}=g.canonical,T=Math.pow(2,e-_),b=m*T,I=v*T;h.push({id:g,x:b,y:I}),bo&&(o=b),Il&&(l=I)}let d=new Set;for(let g of h)g.x!==i&&g.x!==o&&g.y!==s&&g.y!==l||d.add(g.id);return d},k.au=function(r,e){let i=Math.abs(2*r.wrap)-+(r.wrap<0),o=Math.abs(2*e.wrap)-+(e.wrap<0);return r.overscaledZ-e.overscaledZ||o-i||e.canonical.y-r.canonical.y||e.canonical.x-r.canonical.x},k.av=class{constructor(r,e){this.max=r,this.onRemove=e,this.reset()}reset(){for(let r in this.data)for(let e of this.data[r])e.timeout&&clearTimeout(e.timeout),this.onRemove(e.value);return this.data={},this.order=[],this}add(r,e,i){let o=r.wrapped().key;this.data[o]===void 0&&(this.data[o]=[]);let s={value:e,timeout:void 0};if(i!==void 0&&(s.timeout=setTimeout((()=>{this.remove(r,s)}),i)),this.data[o].push(s),this.order.push(o),this.order.length>this.max){let l=this._getAndRemoveByKey(this.order[0]);l&&this.onRemove(l)}return this}has(r){return r.wrapped().key in this.data}getAndRemove(r){return this.has(r)?this._getAndRemoveByKey(r.wrapped().key):null}_getAndRemoveByKey(r){let e=this.data[r].shift();return e.timeout&&clearTimeout(e.timeout),this.data[r].length===0&&delete this.data[r],this.order.splice(this.order.indexOf(r),1),e.value}getByKey(r){let e=this.data[r];return e?e[0].value:null}get(r){return this.has(r)?this.data[r.wrapped().key][0].value:null}remove(r,e){if(!this.has(r))return this;let i=r.wrapped().key,o=e===void 0?0:this.data[i].indexOf(e),s=this.data[i][o];return this.data[i].splice(o,1),s.timeout&&clearTimeout(s.timeout),this.data[i].length===0&&delete this.data[i],this.onRemove(s.value),this.order.splice(this.order.indexOf(i),1),this}setMaxSize(r){for(this.max=r;this.order.length>this.max;){let e=this._getAndRemoveByKey(this.order[0]);e&&this.onRemove(e)}return this}filter(r){let e=[];for(let i in this.data)for(let o of this.data[i])r(o.value)||e.push(o);for(let i of e)this.remove(i.value.tileID,i)}},k.aw=function(r,e){let i=0,o=0;if(r.kind==="constant")o=r.layoutSize;else if(r.kind!=="source"){let{interpolationType:s,minZoom:l,maxZoom:h}=r,d=s?li(Et.interpolationFactor(s,e,l,h),0,1):0;r.kind==="camera"?o=Ai.number(r.minSize,r.maxSize,d):i=d}return{uSizeT:i,uSize:o}},k.ay=function(r,{uSize:e,uSizeT:i},{lowerSize:o,upperSize:s}){return r.kind==="source"?o/In:r.kind==="composite"?Ai.number(o/In,s/In,i):e},k.az=Be,k.b=Jr,k.b$=ra,k.b0=function(r,e,i){return r[0]=e[0]-i[0],r[1]=e[1]-i[1],r[2]=e[2]-i[2],r},k.b1=function(r,e){var i=e[0],o=e[1],s=e[2],l=i*i+o*o+s*s;return l>0&&(l=1/Math.sqrt(l)),r[0]=e[0]*l,r[1]=e[1]*l,r[2]=e[2]*l,r},k.b2=ee,k.b3=function(r,e){return r[0]*e[0]+r[1]*e[1]+r[2]*e[2]},k.b4=function(r,e,i){return r[0]=e[0]*i[0],r[1]=e[1]*i[1],r[2]=e[2]*i[2],r[3]=e[3]*i[3],r},k.b5=_o,k.b6=function(r,e,i){let o=e[0]*i[0]+e[1]*i[1]+e[2]*i[2];return o===0?null:(-(r[0]*i[0]+r[1]*i[1]+r[2]*i[2])-i[3])/o},k.b7=Me,k.b8=function(r,e,i){return r[0]=e[0]*i,r[1]=e[1]*i,r[2]=e[2]*i,r[3]=e[3]*i,r},k.b9=function(r,e){return r[0]*e[0]+r[1]*e[1]+r[2]*e[2]+r[3]},k.bA=$e,k.bB=function(r,e,i){var o=i[0],s=i[1],l=i[2],h=i[3],d=e[0],g=e[1],m=e[2],v=s*m-l*g,_=l*d-o*m,T=o*g-s*d;return r[0]=d+h*(v+=v)+s*(T+=T)-l*(_+=_),r[1]=g+h*_+l*v-o*T,r[2]=m+h*T+o*_-s*v,r},k.bC=function(r,e,i){let o=(s=[r[0],r[1],r[2],e[0],e[1],e[2],i[0],i[1],i[2]])[0]*((v=s[8])*(h=s[4])-(d=s[5])*(m=s[7]))+s[1]*(-v*(l=s[3])+d*(g=s[6]))+s[2]*(m*l-h*g);var s,l,h,d,g,m,v;if(o===0)return null;let _=ee([],[e[0],e[1],e[2]],[i[0],i[1],i[2]]),T=ee([],[i[0],i[1],i[2]],[r[0],r[1],r[2]]),b=ee([],[r[0],r[1],r[2]],[e[0],e[1],e[2]]),I=K([],_,-r[3]);return W(I,I,K([],T,-e[3])),W(I,I,K([],b,-i[3])),K(I,I,1/o),I},k.bD=Wu,k.bE=function(){return new Float64Array(4)},k.bF=function(r,e,i,o){var s=[],l=[];return s[0]=e[0]-i[0],s[1]=e[1]-i[1],s[2]=e[2]-i[2],l[0]=s[0]*Math.cos(o)-s[1]*Math.sin(o),l[1]=s[0]*Math.sin(o)+s[1]*Math.cos(o),l[2]=s[2],r[0]=l[0]+i[0],r[1]=l[1]+i[1],r[2]=l[2]+i[2],r},k.bG=function(r,e,i,o){var s=[],l=[];return s[0]=e[0]-i[0],s[1]=e[1]-i[1],s[2]=e[2]-i[2],l[0]=s[0],l[1]=s[1]*Math.cos(o)-s[2]*Math.sin(o),l[2]=s[1]*Math.sin(o)+s[2]*Math.cos(o),r[0]=l[0]+i[0],r[1]=l[1]+i[1],r[2]=l[2]+i[2],r},k.bH=function(r,e,i,o){var s=[],l=[];return s[0]=e[0]-i[0],s[1]=e[1]-i[1],s[2]=e[2]-i[2],l[0]=s[2]*Math.sin(o)+s[0]*Math.cos(o),l[1]=s[1],l[2]=s[2]*Math.cos(o)-s[0]*Math.sin(o),r[0]=l[0]+i[0],r[1]=l[1]+i[1],r[2]=l[2]+i[2],r},k.bI=function(r,e,i){var o=Math.sin(i),s=Math.cos(i),l=e[0],h=e[1],d=e[2],g=e[3],m=e[8],v=e[9],_=e[10],T=e[11];return e!==r&&(r[4]=e[4],r[5]=e[5],r[6]=e[6],r[7]=e[7],r[12]=e[12],r[13]=e[13],r[14]=e[14],r[15]=e[15]),r[0]=l*s-m*o,r[1]=h*s-v*o,r[2]=d*s-_*o,r[3]=g*s-T*o,r[8]=l*o+m*s,r[9]=h*o+v*s,r[10]=d*o+_*s,r[11]=g*o+T*s,r},k.bJ=function(r,e){let i=Wi(r,360),o=Wi(e,360),s=o-i,l=o>i?s-360:s+360;return Math.abs(s)0?h:-h},k.bM=function(r,e){let i=Wi(r,2*Math.PI),o=Wi(e,2*Math.PI);return Math.min(Math.abs(i-o),Math.abs(i-o+2*Math.PI),Math.abs(i-o-2*Math.PI))},k.bN=function(){let r={},e=ce.$version;for(let i in ce.$root){let o=ce.$root[i];if(o.required){let s=null;s=i==="version"?e:o.type==="array"?[]:{},s!=null&&(r[i]=s)}}return r},k.bO=Fa,k.bP=xl,k.bQ=function r(e,i){if(Array.isArray(e)){if(!Array.isArray(i)||e.length!==i.length)return!1;for(let o=0;or.type==="raster",k.bV=Re,k.bW=function(r,e){if(!r)return[{command:"setStyle",args:[e]}];let i=[];try{if(!it(r.version,e.version))return[{command:"setStyle",args:[e]}];it(r.center,e.center)||i.push({command:"setCenter",args:[e.center]}),it(r.state,e.state)||i.push({command:"setGlobalState",args:[e.state]}),it(r.centerAltitude,e.centerAltitude)||i.push({command:"setCenterAltitude",args:[e.centerAltitude]}),it(r.zoom,e.zoom)||i.push({command:"setZoom",args:[e.zoom]}),it(r.bearing,e.bearing)||i.push({command:"setBearing",args:[e.bearing]}),it(r.pitch,e.pitch)||i.push({command:"setPitch",args:[e.pitch]}),it(r.roll,e.roll)||i.push({command:"setRoll",args:[e.roll]}),it(r.sprite,e.sprite)||i.push({command:"setSprite",args:[e.sprite]}),it(r.glyphs,e.glyphs)||i.push({command:"setGlyphs",args:[e.glyphs]}),it(r.transition,e.transition)||i.push({command:"setTransition",args:[e.transition]}),it(r.light,e.light)||i.push({command:"setLight",args:[e.light]}),it(r.terrain,e.terrain)||i.push({command:"setTerrain",args:[e.terrain]}),it(r.sky,e.sky)||i.push({command:"setSky",args:[e.sky]}),it(r.projection,e.projection)||i.push({command:"setProjection",args:[e.projection]});let o={},s=[];(function(h,d,g,m){let v;for(v in d=d||{},h=h||{})Object.prototype.hasOwnProperty.call(h,v)&&(Object.prototype.hasOwnProperty.call(d,v)||nc(v,g,m));for(v in d)Object.prototype.hasOwnProperty.call(d,v)&&(Object.prototype.hasOwnProperty.call(h,v)?it(h[v],d[v])||(h[v].type==="geojson"&&d[v].type==="geojson"&&Fh(h,d,v)?vi(g,{command:"setGeoJSONSourceData",args:[v,d[v].data]}):oc(v,d,g,m)):rn(v,d,g))})(r.sources,e.sources,s,o);let l=[];r.layers&&r.layers.forEach((h=>{"source"in h&&o[h.source]?i.push({command:"removeLayer",args:[h.id]}):l.push(h)})),i=i.concat(s),(function(h,d,g){d=d||[];let m=(h=h||[]).map(Na),v=d.map(Na),_=h.reduce(sc,{}),T=d.reduce(sc,{}),b=m.slice(),I=Object.create(null),M,A,D,L,R;for(let F=0,O=0;Fpe?(s=Math.acos(l),h=Math.sin(s),d=Math.sin((1-o)*s)/h,g=Math.sin(o*s)/h):(d=1-o,g=o),r[0]=d*m+g*b,r[1]=d*v+g*I,r[2]=d*_+g*M,r[3]=d*T+g*A,r},k.bm=function(r){let e=new Float64Array(9);var i,o,s,l,h,d,g,m,v,_,T,b,I,M,A,D,L,R;_=(s=(o=r)[0])*(g=s+s),T=(l=o[1])*g,I=(h=o[2])*g,M=h*(m=l+l),D=(d=o[3])*g,L=d*m,R=d*(v=h+h),(i=e)[0]=1-(b=l*m)-(A=h*v),i[3]=T-R,i[6]=I+L,i[1]=T+R,i[4]=1-_-A,i[7]=M-D,i[2]=I-L,i[5]=M+D,i[8]=1-_-b;let F=Qr(-Math.asin(li(e[2],-1,1))),O,V;return Math.hypot(e[5],e[8])<.001?(O=0,V=-Qr(Math.atan2(e[3],e[4]))):(O=Qr(e[5]===0&&e[8]===0?0:Math.atan2(e[5],e[8])),V=Qr(e[1]===0&&e[0]===0?0:Math.atan2(e[1],e[0]))),{roll:O,pitch:F+90,bearing:V}},k.bn=function(r,e){return r.roll==e.roll&&r.pitch==e.pitch&&r.bearing==e.bearing},k.bo=Ve,k.bp=yr,k.bq=ua,k.br=$l,k.bs=ha,k.bt=Bi,k.bu=Mr,k.bv=hi,k.bw=function(r,e,i,o,s){return Bi(o,s,li((r-e)/(i-e),0,1))},k.bx=function(r,e,i,o){return r[0]=e[0]+i[0]*o,r[1]=e[1]+i[1]*o,r[2]=e[2]+i[2]*o,r},k.by=Wi,k.bz=function(){return new Float64Array(3)},k.c=Dr,k.c$=Oo,k.c0=class extends ri{constructor(r,e){super(r,e),this.current=sr}set(r){if(r[12]!==this.current[12]||r[0]!==this.current[0])return this.current=r,void this.gl.uniformMatrix4fv(this.location,!1,r);for(let e=1;e<16;e++)if(r[e]!==this.current[e]){this.current=r,this.gl.uniformMatrix4fv(this.location,!1,r);break}}},k.c1=Ur,k.c2=class extends ri{constructor(r,e){super(r,e),this.current=[0,0,0]}set(r){r[0]===this.current[0]&&r[1]===this.current[1]&&r[2]===this.current[2]||(this.current=r,this.gl.uniform3f(this.location,r[0],r[1],r[2]))}},k.c3=class extends ri{constructor(r,e){super(r,e),this.current=[0,0]}set(r){r[0]===this.current[0]&&r[1]===this.current[1]||(this.current=r,this.gl.uniform2f(this.location,r[0],r[1]))}},k.c4=Xr,k.c5=function(r,e){var i=Math.sin(e),o=Math.cos(e);return r[0]=o,r[1]=i,r[2]=0,r[3]=-i,r[4]=o,r[5]=0,r[6]=0,r[7]=0,r[8]=1,r},k.c6=function(r,e,i){var o=e[0],s=e[1],l=e[2];return r[0]=o*i[0]+s*i[3]+l*i[6],r[1]=o*i[1]+s*i[4]+l*i[7],r[2]=o*i[2]+s*i[5]+l*i[8],r},k.c7=function(r,e,i,o,s,l,h){var d=1/(e-i),g=1/(o-s),m=1/(l-h);return r[0]=-2*d,r[1]=0,r[2]=0,r[3]=0,r[4]=0,r[5]=-2*g,r[6]=0,r[7]=0,r[8]=0,r[9]=0,r[10]=2*m,r[11]=0,r[12]=(e+i)*d,r[13]=(s+o)*g,r[14]=(h+l)*m,r[15]=1,r},k.c8=class extends ri{constructor(r,e){super(r,e),this.current=new Array}set(r){if(r!=this.current){this.current=r;let e=new Float32Array(4*r.length);for(let i=0;i25||o<0||o>=1||i<0||i>=1)},k.cE=function(r,e){return r[0]=e[0],r[1]=0,r[2]=0,r[3]=0,r[4]=0,r[5]=e[1],r[6]=0,r[7]=0,r[8]=0,r[9]=0,r[10]=e[2],r[11]=0,r[12]=0,r[13]=0,r[14]=0,r[15]=1,r},k.cF=class extends Ys{},k.cG=kn,k.cH=function(r,e){Dr.REGISTERED_PROTOCOLS[r]=e},k.cI=function(r){delete Dr.REGISTERED_PROTOCOLS[r]},k.cJ=function(r,e){let i={};for(let s=0;sfe*Vt))}let ae=g?"center":s.get("text-justify").evaluate(_,{},r.canonical),le=s.get("symbol-placement")==="point"?s.get("text-max-width").evaluate(_,{},r.canonical)*Vt:1/0,ne=()=>{r.bucket.allowVerticalPlacement&&bl(V)&&(A.vertical=wh(D,r.glyphMap,r.glyphPositions,r.imagePositions,T,le,d,re,"left",J,R,k.ax.vertical,!0,I,b))};if(!g&&te){let ie=new Set;if(ae==="auto")for(let xe=0;xem_(d,g,l)),o.layers[h])})(r,i,e),i.finish()},k.cT=function(r,e,i,o,s,l){let h=Pf(r,e,i,s,0);return h=Pf(h,e,o,l,1),h},k.cU=class{constructor(r){this.maxEntries=r,this.map=new Map}get(r){let e=this.map.get(r);return e!==void 0&&(this.map.delete(r),this.map.set(r,e)),e}set(r,e){if(this.map.has(r))this.map.delete(r);else if(this.map.size>=this.maxEntries){let i=this.map.keys().next().value;this.map.delete(i)}this.map.set(r,e)}clear(){this.map.clear()}},k.cV=Wd,k.cW=bh,k.cX=vf,k.cY=function(r,e,i,o,s){return p(this,void 0,void 0,(function*(){if(Ii())try{return yield Ra(r,e,i,o,s)}catch{}return(function(l,h,d,g,m){let v=l.width,_=l.height;Cr&&Rn||(Cr=new OffscreenCanvas(v,_),Rn=Cr.getContext("2d",{willReadFrequently:!0})),Cr.width=v,Cr.height=_,Rn.drawImage(l,0,0,v,_);let T=Rn.getImageData(h,d,g,m);return Rn.clearRect(0,0,v,_),T.data})(r,e,i,o,s)}))},k.cZ=Ld,k.c_=class{constructor(r,e){this.layers={[tc]:this},this.name=tc,this.version=e?e.version:1,this.extent=e?e.extent:4096,this.length=r.length,this.features=r}feature(r){return new f_(this.features[r],this.extent)}},k.ca=class extends wn{},k.cb=dg,k.cc=class extends rs{},k.cd=mu,k.ce=function(r){return r<=1?1:Math.pow(2,Math.ceil(Math.log(r)/Math.LN2))},k.cf=Dd,k.cg=function(r,e,i){var o=e[0],s=e[1],l=e[2],h=i[3]*o+i[7]*s+i[11]*l+i[15];return r[0]=(i[0]*o+i[4]*s+i[8]*l+i[12])/(h=h||1),r[1]=(i[1]*o+i[5]*s+i[9]*l+i[13])/h,r[2]=(i[2]*o+i[6]*s+i[10]*l+i[14])/h,r},k.ch=class extends Ks{},k.ci=class extends t{},k.cj=function(r,e){return r[0]===e[0]&&r[1]===e[1]&&r[2]===e[2]&&r[3]===e[3]&&r[4]===e[4]&&r[5]===e[5]&&r[6]===e[6]&&r[7]===e[7]&&r[8]===e[8]&&r[9]===e[9]&&r[10]===e[10]&&r[11]===e[11]&&r[12]===e[12]&&r[13]===e[13]&&r[14]===e[14]&&r[15]===e[15]},k.ck=function(r,e){var i=r[0],o=r[1],s=r[2],l=r[3],h=r[4],d=r[5],g=r[6],m=r[7],v=r[8],_=r[9],T=r[10],b=r[11],I=r[12],M=r[13],A=r[14],D=r[15],L=e[0],R=e[1],F=e[2],O=e[3],V=e[4],Y=e[5],J=e[6],re=e[7],te=e[8],ae=e[9],le=e[10],ne=e[11],ie=e[12],fe=e[13],xe=e[14],ye=e[15];return Math.abs(i-L)<=pe*Math.max(1,Math.abs(i),Math.abs(L))&&Math.abs(o-R)<=pe*Math.max(1,Math.abs(o),Math.abs(R))&&Math.abs(s-F)<=pe*Math.max(1,Math.abs(s),Math.abs(F))&&Math.abs(l-O)<=pe*Math.max(1,Math.abs(l),Math.abs(O))&&Math.abs(h-V)<=pe*Math.max(1,Math.abs(h),Math.abs(V))&&Math.abs(d-Y)<=pe*Math.max(1,Math.abs(d),Math.abs(Y))&&Math.abs(g-J)<=pe*Math.max(1,Math.abs(g),Math.abs(J))&&Math.abs(m-re)<=pe*Math.max(1,Math.abs(m),Math.abs(re))&&Math.abs(v-te)<=pe*Math.max(1,Math.abs(v),Math.abs(te))&&Math.abs(_-ae)<=pe*Math.max(1,Math.abs(_),Math.abs(ae))&&Math.abs(T-le)<=pe*Math.max(1,Math.abs(T),Math.abs(le))&&Math.abs(b-ne)<=pe*Math.max(1,Math.abs(b),Math.abs(ne))&&Math.abs(I-ie)<=pe*Math.max(1,Math.abs(I),Math.abs(ie))&&Math.abs(M-fe)<=pe*Math.max(1,Math.abs(M),Math.abs(fe))&&Math.abs(A-xe)<=pe*Math.max(1,Math.abs(A),Math.abs(xe))&&Math.abs(D-ye)<=pe*Math.max(1,Math.abs(D),Math.abs(ye))},k.cl=function(r,e){return r[0]=e[0],r[1]=e[1],r[2]=e[2],r[3]=e[3],r[4]=e[4],r[5]=e[5],r[6]=e[6],r[7]=e[7],r[8]=e[8],r[9]=e[9],r[10]=e[10],r[11]=e[11],r[12]=e[12],r[13]=e[13],r[14]=e[14],r[15]=e[15],r},k.cm=r=>r.type==="circle",k.cn=r=>r.type==="heatmap",k.co=r=>r.type==="line",k.cp=r=>r.type==="fill",k.cq=r=>r.type==="fill-extrusion",k.cr=r=>r.type==="hillshade",k.cs=r=>r.type==="color-relief",k.ct=r=>r.type==="background",k.cu=r=>r.type==="custom",k.cv=Yr,k.cw=function(r,e,i){if(e<=0)return r;let o=1/e;return i===void 0||Math.abs(i)<1e-10?Math.round(r*o)/o:(i>0?Math.ceil(r*o-1e-9):Math.floor(r*o+1e-10))/o},k.cx=function(r,e,i){let o=Ke(e.x-i.x,e.y-i.y),s=Ke(r.x-i.x,r.y-i.y);var l,h;return Qr(Math.atan2(o[0]*s[1]-o[1]*s[0],(l=o)[0]*(h=s)[0]+l[1]*h[1]))},k.cy=yo,k.cz=function(r,e){var i;if(!La[e])return!1;let o=r?.target,s=((i=o?.ownerDocument)===null||i===void 0?void 0:i.defaultView)||window;return r instanceof s.MouseEvent||r instanceof s.WheelEvent},k.d=xt,k.d0=class{constructor(r,e){let i=(e=this.options=Object.assign({},tg,e)).debug;if(i&&console.time("preprocess data"),e.maxZoom<0||e.maxZoom>24)throw new Error("maxZoom should be in the 0-24 range");if(e.promoteId&&e.generateId)throw new Error("promoteId and generateId cannot be used together.");let o=Mu(r,e);i&&(console.timeEnd("preprocess data"),console.log("index: maxZoom: %d, maxPoints: %d",e.indexMaxZoom,e.indexMaxPoints),console.time("generate tiles")),o=Du(o,e),e.updateable&&(this.source=o),this.initializeIndex(o,e)}initializeIndex(r,e){this.tileIndex=e.cluster?new Hm(e.clusterOptions):new eg(e),r.length&&this.tileIndex.initialize(r)}getTile(r,e,i){return e=+e,i=+i,(r=+r)<0||r>24?null:this.tileIndex.getTile(r,e,i)}updateData(r,e){let i=this.options;if(!i.updateable)throw new Error("to update tile geojson `updateable` option must be set to true");let{affected:o,source:s}=(function(l,h,d){let g=(function(v,_){return v?{removeAll:v.removeAll,remove:new Set(v.remove||[]),add:new Map(v.add?.map((T=>[_.promoteId?T.properties[_.promoteId]:T.id,T]))),update:new Map(v.update?.map((T=>[T.id,T])))}:{remove:new Set,add:new Map,update:new Map}})(h,d),m=[];if(g.removeAll&&(m=l,l=[]),g.remove.size||g.add.size){let v=[];for(let _ of l)(g.remove.has(_.id)||g.add.has(_.id))&&v.push(_);if(v.length){m.push(...v);let _=new Set(v.map((T=>T.id)));l=l.filter((T=>!_.has(T.id)))}if(g.add.size){let _=Mu({type:"FeatureCollection",features:Array.from(g.add.values())},d);_=Du(_,d),m.push(..._),l.push(..._)}}if(g.update.size){let v=new Map,_=[];for(let T of l)g.update.has(T.id)?v.set(T.id,[...v.get(T.id)||[],T]):_.push(T);for(let[T,b]of g.update){let I=v.get(T);if(!I||I.length===0)continue;let M=Wm(I,b,d);m.push(...I,...M),_.push(...M)}l=_}return{affected:m,source:l}})(this.source,r,i);e&&({affected:o,source:s}=this.filterUpdate(s,o,e)),o.length&&(this.source=s,this.tileIndex.updateIndex(s,o,i))}filterUpdate(r,e,i){let o=new Set;for(let s of r)s.id!=null&&(i(_h(s))||(e.push(s),o.add(s.id)));return{affected:e,source:r=r.filter((s=>!o.has(s.id)))}}getData(){if(!this.options.updateable)throw new Error("to retrieve data the `updateable` option must be set to true");return{type:"FeatureCollection",features:this.source.map((r=>_h(r)))}}updateClusterOptions(r,e){let i=this.options.cluster;this.options.cluster=r,this.options.clusterOptions=e,i!=r?this.initializeIndex(this.source,this.options):this.tileIndex.updateIndex(this.source,[],this.options)}getClusterExpansionZoom(r){return this.tileIndex.getClusterExpansionZoom(r)}getClusterChildren(r){return this.tileIndex.getChildren(r)}getClusterLeaves(r,e,i){return this.tileIndex.getLeaves(r,e,i)}},k.d1=gr,k.e=Oi,k.f=Hi,k.g=hr,k.h=r=>p(void 0,void 0,void 0,(function*(){if(r.byteLength===0)return createImageBitmap(new ImageData(1,1));let e=new Blob([new Uint8Array(r)],{type:"image/png"});try{return createImageBitmap(e)}catch(i){throw new Error(`Could not load image because of ${xt(i).message}. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported.`)}})),k.i=Ht,k.j=r=>new Promise(((e,i)=>{let o=new Image;o.onload=()=>{e(o),URL.revokeObjectURL(o.src),o.onload=null,window.requestAnimationFrame((()=>o.src=za))},o.onerror=()=>i(new Error("Could not load image. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported."));let s=new Blob([new Uint8Array(r)],{type:"image/png"});o.src=r.byteLength?URL.createObjectURL(s):za})),k.k=(r,e)=>en(Oi(r,{type:"json"}),e),k.l=Fn,k.m=en,k.n=bo,k.o=(r,e)=>en(Oi(r,{type:"arrayBuffer"}),e),k.p=Tp,k.q=function(r){return new bh(r).readFields(Mg,[])},k.r=function(r){return/[\u02EA\u02EB\u1100-\u11FF\u2E80-\u2FDF\u3000-\u30FF\u3105-\u312F\u3131-\u318E\u31A0-\u4DBF\u4E00-\uA48C\uA490-\uA4C6\uA960-\uA97C\uAC00-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFE10-\uFE1F\uFE30-\uFE4F\uFF00-\uFFEF]|\uD81B[\uDFE0-\uDFFF]|[\uD81C-\uD822\uD840-\uD868\uD86A-\uD86D\uD86F-\uD872\uD874-\uD879\uD880-\uD883\uD885-\uD88C][\uDC00-\uDFFF]|\uD823[\uDC00-\uDCD5\uDCFF-\uDD1E\uDD80-\uDDF2]|\uD82B[\uDFF0-\uDFFF]|\uD82C[\uDC00-\uDEFB]|\uD83C[\uDE00-\uDEFF]|\uD869[\uDC00-\uDEDF\uDF00-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEAD\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0\uDFF0-\uDFFF]|\uD87B[\uDC00-\uDE5D]|\uD87E[\uDC00-\uDE1D]|\uD884[\uDC00-\uDF4A\uDF50-\uDFFF]|\uD88D[\uDC00-\uDC79]/gim.test(String.fromCodePoint(r))},k.s=us,k.t=Nl,k.u=ui,k.v=qo,k.w=Wt,k.x=ce,k.y=Ml,k.z=zi})),Zt("worker",["./shared"],(function(k){"use strict";class p{constructor(W,K){this.keyCache={},W&&this.replace(W,K)}replace(W,K){this._layerConfigs={},this._layers={},this.update(W,[],K)}update(W,K,ee){for(let Me of W){this._layerConfigs[Me.id]=Me;let Ze=this._layers[Me.id]=k.bT(Me,ee);Ze._featureFilter=k.ah(Ze.filter,ee),this.keyCache[Me.id]&&delete this.keyCache[Me.id]}for(let Me of K)delete this.keyCache[Me],delete this._layerConfigs[Me],delete this._layers[Me];this.familiesBySource={};let ge=k.cJ(Object.values(this._layerConfigs),this.keyCache);for(let Me of ge){let Ze=Me.map((vt=>this._layers[vt.id])),ze=Ze[0];if(ze.isHidden())continue;let $e=ze.source||"",Be=this.familiesBySource[$e];Be||(Be=this.familiesBySource[$e]={});let Ke=ze.sourceLayer||k.ag,De=Be[Ke];De||(De=Be[Ke]=[]),De.push(Ze)}}}class Te{constructor(W){let K={},ee=[];for(let ze in W){let $e=W[ze],Be=K[ze]={};for(let Ke in $e){let De=$e[+Ke];if(!De||De.bitmap.width===0||De.bitmap.height===0)continue;let vt={x:0,y:0,w:De.bitmap.width+2,h:De.bitmap.height+2};ee.push(vt),Be[Ke]={rect:vt,metrics:De.metrics}}}let{w:ge,h:Me}=k.p(ee),Ze=new k.t({width:ge||1,height:Me||1});for(let ze in W){let $e=W[ze];for(let Be in $e){let Ke=$e[+Be];if(!Ke||Ke.bitmap.width===0||Ke.bitmap.height===0)continue;let De=K[ze][Be].rect;k.t.copy(Ke.bitmap,Ze,{x:0,y:0},{x:De.x+1,y:De.y+1},Ke.bitmap)}}this.image=Ze,this.positions=K}}k.cK("GlyphAtlas",Te);class Sr{constructor(W){this.tileID=new k.a3(W.tileID.overscaledZ,W.tileID.wrap,W.tileID.canonical.z,W.tileID.canonical.x,W.tileID.canonical.y),this.uid=W.uid,this.zoom=W.zoom,this.pixelRatio=W.pixelRatio,this.tileSize=W.tileSize,this.source=W.source,this.overscaling=this.tileID.overscaleFactor(),this.showCollisionBoxes=W.showCollisionBoxes,this.collectResourceTiming=!!W.collectResourceTiming,this.returnDependencies=!!W.returnDependencies,this.promoteId=W.promoteId,this.inFlightDependencies=[]}parse(W,K,ee,ge,Me){return k._(this,void 0,void 0,(function*(){this.status="parsing",this.data=W,this.collisionBoxArray=new k.ae;let Ze=new k.cL(Object.keys(W.layers).sort()),ze=new k.cM(this.tileID,this.promoteId);ze.bucketLayerIDs=[];let $e={},Be={featureIndex:ze,iconDependencies:{},patternDependencies:{},glyphDependencies:{},dashDependencies:{},availableImages:ee,subdivisionGranularity:Me},Ke=K.familiesBySource[this.source];for(let Re in Ke){let Bt=W.layers[Re];if(!Bt)continue;Bt.version===1&&k.w(`Vector tile source "${this.source}" layer "${Re}" does not use vector tile spec v2 and therefore may have some rendering errors.`);let Wt=Ze.encode(Re),Mi=[];for(let Ht=0;HtJr.id))))}}let De=k.bY(Be.glyphDependencies,(Re=>Object.keys(Re).map(Number)));for(let Re of this.inFlightDependencies)Re?.abort();this.inFlightDependencies=[];let vt=Promise.resolve({});if(Object.keys(De).length){let Re=new AbortController;this.inFlightDependencies.push(Re),vt=ge.sendAsync({type:"GG",data:{stacks:De,source:this.source,tileID:this.tileID,type:"glyphs"}},Re)}let xt=Object.keys(Be.iconDependencies),Wi=Promise.resolve({});if(xt.length){let Re=new AbortController;this.inFlightDependencies.push(Re),Wi=ge.sendAsync({type:"GI",data:{icons:xt,source:this.source,tileID:this.tileID,type:"icons"}},Re)}let Bi=Object.keys(Be.patternDependencies),Mr=Promise.resolve({});if(Bi.length){let Re=new AbortController;this.inFlightDependencies.push(Re),Mr=ge.sendAsync({type:"GI",data:{icons:Bi,source:this.source,tileID:this.tileID,type:"patterns"}},Re)}let Yr=Be.dashDependencies,yo=Promise.resolve({});if(Object.keys(Yr).length){let Re=new AbortController;this.inFlightDependencies.push(Re),yo=ge.sendAsync({type:"GDA",data:{dashes:Yr}},Re)}let[li,zn,Oi,vo]=yield Promise.all([vt,Wi,Mr,yo]),Er=new Te(li),Kr=new k.cN(zn,Oi);for(let Re in $e){let Bt=$e[Re];Bt instanceof k.af?(Si(Bt.layers,this.zoom,ee),k.cO({bucket:Bt,glyphMap:li,glyphPositions:Er.positions,imageMap:zn,imagePositions:Kr.iconPositions,showCollisionBoxes:this.showCollisionBoxes,canonical:this.tileID.canonical,subdivisionGranularity:Be.subdivisionGranularity})):Bt.hasDependencies&&(Bt instanceof k.cP||Bt instanceof k.cQ||Bt instanceof k.cR)&&(Si(Bt.layers,this.zoom,ee),Bt.addFeatures(Be,this.tileID.canonical,Kr.patternPositions,vo))}return this.status="done",{buckets:Object.values($e).filter((Re=>!Re.isEmpty())),featureIndex:ze,collisionBoxArray:this.collisionBoxArray,glyphAtlasImage:Er.image,imageAtlas:Kr,dashPositions:vo,glyphMap:this.returnDependencies?li:null,iconMap:this.returnDependencies?zn:null,glyphPositions:this.returnDependencies?Er.positions:null}}))}}function Si(We,W,K){let ee=new k.J(W);for(let ge of We)ge.recalculate(ee,K)}class Wr{constructor(){this.loading={},this.loaded={},this.parsing={}}startLoading(W,K){this.loading[W]=K}finishLoading(W){delete this.loading[W]}abort(W){let K=this.loading[W];K?.abort&&(K.abort.abort(),delete this.loading[W])}setParsing(W,K){this.parsing[W]=K}consumeParsing(W){let K=this.parsing[W];if(K)return delete this.parsing[W],K}clearParsing(W){delete this.parsing[W]}markLoaded(W,K){this.loaded[W]=K}getLoaded(W){let K=this.loaded[W];if(K)return K}removeLoaded(W){delete this.loaded[W]}clearLoaded(){this.loaded={}}}class An{constructor(W){this.start=`${W}#start`,this.end=`${W}#end`,this.measure=W,performance.mark(this.start)}finish(){performance.mark(this.end);let W=performance.getEntriesByName(this.measure);return W.length===0&&(performance.measure(this.measure,this.start,this.end),W=performance.getEntriesByName(this.measure),performance.clearMarks(this.start),performance.clearMarks(this.end),performance.clearMeasures(this.measure)),W}}class qt{constructor(W,K,ee,ge,Me){this.type=W,this.properties=ee||{},this.extent=Me,this.pointsArray=K,this.id=ge}loadGeometry(){return this.pointsArray.map((W=>W.map((K=>new k.P(K.x,K.y)))))}}class Ir{constructor(W,K,ee){this.version=2,this._myFeatures=W,this.name=K,this.length=W.length,this.extent=ee}feature(W){return this._myFeatures[W]}}class Xe{constructor(){this.layers={}}addLayer(W){this.layers[W.name]=W}}function Hr(We){let W=k.cS(We);return W.byteOffset===0&&W.byteLength===W.buffer.byteLength||(W=new Uint8Array(W)),{vectorTile:We,rawData:W.buffer}}function Ii(We,W,K){let{extent:ee}=We,ge=Math.pow(2,K.z-W.z),Me=(K.x-W.x*ge)*ee,Ze=(K.y-W.y*ge)*ee,ze=[];for(let $e=0;$e0&&Ke.addLayer(Bi)}let vt=Hr(Ke);return this.overzoomedTileResultCache.set($e,vt),vt}reloadTile(W){return k._(this,void 0,void 0,(function*(){let K=W.uid,ee=this.tileState.getLoaded(K);if(!ee)throw new Error("Should not be trying to reload a tile that was never loaded or has been removed");if(ee.showCollisionBoxes=W.showCollisionBoxes,ee.status==="parsing"){let ge=this.tileState.consumeParsing(K);return yield this._parseWorkerTile(ee,W,ge)}if(ee.status==="done"&&ee.vectorTile)return yield this._parseWorkerTile(ee,W)}))}abortTile(W){return k._(this,void 0,void 0,(function*(){this.tileState.abort(W.uid)}))}removeTile(W){return k._(this,void 0,void 0,(function*(){this.tileState.removeLoaded(W.uid)}))}}class kt{constructor(){this.loaded={}}loadTile(W){return k._(this,void 0,void 0,(function*(){let{uid:K,encoding:ee,rawImageData:ge,redFactor:Me,greenFactor:Ze,blueFactor:ze,baseShift:$e}=W,Be=ge.width+2,Ke=ge.height+2,De=k.b(ge)?new k.R({width:Be,height:Ke},yield k.cY(ge,-1,-1,Be,Ke)):ge,vt=new k.cZ(K,De,ee,Me,Ze,ze,$e);return this.loaded||(this.loaded={}),this.loaded[K]=vt,vt}))}removeTile(W){let K=this.loaded,ee=W.uid;K?.[ee]&&delete K[ee]}}class Xr{constructor(W,K,ee,ge=Dn){this.actor=W,this.layerIndex=K,this.availableImages=ee,this.tileState=new Wr,this._createGeoJSONIndex=ge}loadVectorTile(W){if(!this._geoJSONIndex)throw new Error("Unable to parse the data into a cluster or geojson");let{z:K,x:ee,y:ge}=W.tileID.canonical,Me=this._geoJSONIndex.getTile(K,ee,ge);return Me?Hr(new k.c_(Me.features,{version:2,extent:k.a6})):null}loadTile(W){return k._(this,void 0,void 0,(function*(){let{uid:K}=W,ee=new Sr(W);ee.abort=new AbortController;try{let ge=this.loadVectorTile(W);if(!ge)return null;let{vectorTile:Me,rawData:Ze}=ge;ee.vectorTile=Me,this.tileState.markLoaded(K,ee);let ze={rawData:Ze};this.tileState.setParsing(K,ze);try{return yield this._parseWorkerTile(ee,W,ze)}finally{this.tileState.clearParsing(K)}}catch(ge){throw ee.status="done",this.tileState.markLoaded(K,ee),ge}}))}_reloadLoadedTile(W){return k._(this,void 0,void 0,(function*(){let K=W.uid,ee=this.tileState.getLoaded(K);if(!ee)throw new Error("Should not be trying to reload a tile that was never loaded or has been removed");if(ee.showCollisionBoxes=W.showCollisionBoxes,ee.status==="parsing"){let ge=this.tileState.consumeParsing(K);return yield this._parseWorkerTile(ee,W,ge)}if(ee.status==="done"&&ee.vectorTile)return yield this._parseWorkerTile(ee,W)}))}_parseWorkerTile(W,K,ee){return k._(this,void 0,void 0,(function*(){let ge=yield W.parse(W.vectorTile,this.layerIndex,this.availableImages,this.actor,K.subdivisionGranularity);if(ee){let{rawData:Me}=ee;ge=k.e({rawTileData:Me.slice(0),encoding:"mvt"},ge)}return ge}))}abortTile(W){return k._(this,void 0,void 0,(function*(){this.tileState.abort(W.uid)}))}removeTile(W){return k._(this,void 0,void 0,(function*(){this.tileState.removeLoaded(W.uid)}))}loadData(W){return k._(this,void 0,void 0,(function*(){var K;(K=this._pendingRequest)===null||K===void 0||K.abort();let ee=this._startRequestTiming(W);this._pendingRequest=new AbortController;try{yield this.loadAndProcessGeoJSON(W,this._pendingRequest),delete this._pendingRequest,this.tileState.clearLoaded();let ge={};return W.request&&(ge.data=W.data),this._finishRequestTiming(ee,W,ge),ge}catch(ge){if(delete this._pendingRequest,!k.$(ge))throw ge;return{abandoned:!0}}}))}_startRequestTiming(W){var K;if(!((K=W.request)===null||K===void 0)&&K.collectResourceTiming)return new An(W.request.url)}_finishRequestTiming(W,K,ee){let ge=W?.finish();ge&&(ee.resourceTiming={[K.source]:JSON.parse(JSON.stringify(ge))})}reloadTile(W){return this.tileState.getLoaded(W.uid)?this._reloadLoadedTile(W):this.loadTile(W)}loadAndProcessGeoJSON(W,K){return k._(this,void 0,void 0,(function*(){var ee;if(W.request&&(W.data=(yield k.k(W.request,K)).data),W.data)return W.data=this._filterGeoJSON(W.data,W.filter),void(this._geoJSONIndex=this._createGeoJSONIndex(W.data,W));if(W.dataDiff)return(ee=this._geoJSONIndex)!==null&&ee!==void 0||(this._geoJSONIndex=this._createGeoJSONIndex({type:"FeatureCollection",features:[]},W)),void this._geoJSONIndex.updateData(W.dataDiff,this._getFilterPredicate(W.filter));if(W.updateCluster&&this._geoJSONIndex.updateClusterOptions(W.geojsonVtOptions.cluster,go(W)),this._geoJSONIndex==null)throw new Error(`Input data given to '${W.source}' is not a valid GeoJSON object.`)}))}_filterGeoJSON(W,K){if(W.type!=="FeatureCollection")return W;let ee=this._getFilterPredicate(K);return ee?{type:"FeatureCollection",features:W.features.filter((ge=>ee(ge)))}:W}_getFilterPredicate(W){if(typeof W!="boolean"&&!W?.length)return;let K=k.c$(W,{type:"boolean","property-type":"data-driven",overridable:!1,transition:!1});if(K.result==="error")throw new Error(K.value.map((ee=>`${ee.key}: ${ee.message}`)).join(", "));return ee=>K.value.evaluate({zoom:0},ee)}removeSource(W){return k._(this,void 0,void 0,(function*(){var K;(K=this._pendingRequest)===null||K===void 0||K.abort()}))}getClusterExpansionZoom(W){return this._geoJSONIndex.getClusterExpansionZoom(W.clusterId)}getClusterChildren(W){return this._geoJSONIndex.getClusterChildren(W.clusterId)}getClusterLeaves(W){return this._geoJSONIndex.getClusterLeaves(W.clusterId,W.limit,W.offset)}}function Dn(We,W){let K=k.e(W.geojsonVtOptions||{},{updateable:!0,clusterOptions:go(W)});return new k.d0(We,K)}function go({geojsonVtOptions:We,clusterProperties:W}){if(!W||!We.clusterOptions)return We.clusterOptions;let K={},ee={},ge={accumulated:null,zoom:0},Me={properties:null},Ze=Object.keys(W);for(let ze of Ze){let[$e,Be]=W[ze],Ke=k.c$(Be),De=k.c$(typeof $e=="string"?[$e,["accumulated"],["get",ze]]:$e);K[ze]=Ke.value,ee[ze]=De.value}return We.clusterOptions.map=ze=>{Me.properties=ze;let $e={};for(let Be of Ze)$e[Be]=K[Be].evaluate(ge,Me);return $e},We.clusterOptions.reduce=(ze,$e)=>{Me.properties=$e;for(let Be of Ze)ge.accumulated=ze[Be],ze[Be]=ee[Be].evaluate(ge,Me)},We.clusterOptions}class _o{constructor(W){this.self=W,this.actor=new k.N(W),this.layerIndexes={},this.availableImages={},this.workerSources={},this.demWorkerSources={},this.externalWorkerSourceTypes={},this.globalStates=new Map,this.self.registerWorkerSource=(K,ee)=>{if(this.externalWorkerSourceTypes[K])throw new Error(`Worker source with name "${K}" already registered.`);this.externalWorkerSourceTypes[K]=ee},this.self.addProtocol=k.cH,this.self.removeProtocol=k.cI,this.self.registerRTLTextPlugin=K=>{k.d1.setMethods(K)},this.self.makeRequest=k.m,this.actor.registerMessageHandler("LDT",((K,ee)=>this._getDEMWorkerSource(K,ee.source).loadTile(ee))),this.actor.registerMessageHandler("RDT",((K,ee)=>k._(this,void 0,void 0,(function*(){this._getDEMWorkerSource(K,ee.source).removeTile(ee)})))),this.actor.registerMessageHandler("GCEZ",((K,ee)=>k._(this,void 0,void 0,(function*(){return this._getWorkerSource(K,ee.type,ee.source).getClusterExpansionZoom(ee)})))),this.actor.registerMessageHandler("GCC",((K,ee)=>k._(this,void 0,void 0,(function*(){return this._getWorkerSource(K,ee.type,ee.source).getClusterChildren(ee)})))),this.actor.registerMessageHandler("GCL",((K,ee)=>k._(this,void 0,void 0,(function*(){return this._getWorkerSource(K,ee.type,ee.source).getClusterLeaves(ee)})))),this.actor.registerMessageHandler("LD",((K,ee)=>this._getWorkerSource(K,ee.type,ee.source).loadData(ee))),this.actor.registerMessageHandler("LT",((K,ee)=>this._getWorkerSource(K,ee.type,ee.source).loadTile(ee))),this.actor.registerMessageHandler("RT",((K,ee)=>this._getWorkerSource(K,ee.type,ee.source).reloadTile(ee))),this.actor.registerMessageHandler("AT",((K,ee)=>this._getWorkerSource(K,ee.type,ee.source).abortTile(ee))),this.actor.registerMessageHandler("RMT",((K,ee)=>this._getWorkerSource(K,ee.type,ee.source).removeTile(ee))),this.actor.registerMessageHandler("RS",((K,ee)=>k._(this,void 0,void 0,(function*(){var ge,Me;if(!(!((Me=(ge=this.workerSources[K])===null||ge===void 0?void 0:ge[ee.type])===null||Me===void 0)&&Me[ee.source]))return;let Ze=this.workerSources[K][ee.type][ee.source];delete this.workerSources[K][ee.type][ee.source],Ze.removeSource!==void 0&&Ze.removeSource(ee)})))),this.actor.registerMessageHandler("RM",(K=>k._(this,void 0,void 0,(function*(){delete this.layerIndexes[K],delete this.availableImages[K],delete this.workerSources[K],delete this.demWorkerSources[K],this.globalStates.delete(K)})))),this.actor.registerMessageHandler("SR",((K,ee)=>k._(this,void 0,void 0,(function*(){this.referrer=ee})))),this.actor.registerMessageHandler("SRPS",((K,ee)=>this._syncRTLPluginState(K,ee))),this.actor.registerMessageHandler("IS",((K,ee)=>k._(this,void 0,void 0,(function*(){this.self.importScripts(ee)})))),this.actor.registerMessageHandler("SI",((K,ee)=>this._setImages(K,ee))),this.actor.registerMessageHandler("UL",((K,ee)=>k._(this,void 0,void 0,(function*(){this._getLayerIndex(K).update(ee.layers,ee.removedIds,this._getGlobalState(K))})))),this.actor.registerMessageHandler("UGS",((K,ee)=>k._(this,void 0,void 0,(function*(){let ge=this._getGlobalState(K);for(let Me in ee)ge[Me]=ee[Me]})))),this.actor.registerMessageHandler("SL",((K,ee)=>k._(this,void 0,void 0,(function*(){this._getLayerIndex(K).replace(ee,this._getGlobalState(K))}))))}_getGlobalState(W){let K=this.globalStates.get(W);return K||(K={},this.globalStates.set(W,K)),K}_setImages(W,K){return k._(this,void 0,void 0,(function*(){this.availableImages[W]=K;for(let ee in this.workerSources[W]){let ge=this.workerSources[W][ee];for(let Me in ge)ge[Me].availableImages=K}}))}_syncRTLPluginState(W,K){return k._(this,void 0,void 0,(function*(){return yield k.d1.syncState(K,this.self.importScripts)}))}_getAvailableImages(W){let K=this.availableImages[W];return K||(K=[]),K}_getLayerIndex(W){let K=this.layerIndexes[W];return K||(K=this.layerIndexes[W]=new p),K}_getWorkerSource(W,K,ee){var ge,Me;if((ge=this.workerSources)[W]||(ge[W]={}),(Me=this.workerSources[W])[K]||(Me[K]={}),!this.workerSources[W][K][ee]){let Ze={sendAsync:(ze,$e)=>(ze.targetMapId=W,this.actor.sendAsync(ze,$e))};switch(K){case"vector":this.workerSources[W][K][ee]=new pe(Ze,this._getLayerIndex(W),this._getAvailableImages(W));break;case"geojson":this.workerSources[W][K][ee]=new Xr(Ze,this._getLayerIndex(W),this._getAvailableImages(W));break;default:this.workerSources[W][K][ee]=new this.externalWorkerSourceTypes[K](Ze,this._getLayerIndex(W),this._getAvailableImages(W))}}return this.workerSources[W][K][ee]}_getDEMWorkerSource(W,K){var ee,ge;return(ee=this.demWorkerSources)[W]||(ee[W]={}),(ge=this.demWorkerSources[W])[K]||(ge[K]=new kt),this.demWorkerSources[W][K]}}return k.i(self)&&(self.worker=new _o(self)),_o})),Zt("index",["exports","./shared"],(function(k,p){"use strict";var Te="5.24.0";function Sr(){var u=new p.A(4);return p.A!=Float32Array&&(u[1]=0,u[2]=0),u[0]=1,u[3]=1,u}let Si,Wr,An,qt={frame(u,t,n,a){let c=a||window,f=c.requestAnimationFrame((x=>{y(),t(x)})),{unsubscribe:y}=p.s(u.signal,"abort",(()=>{y(),c.cancelAnimationFrame(f),n(new p.a(u.signal.reason))}),!1)},frameAsync(u,t){return new Promise(((n,a)=>{this.frame(u,n,a,t)}))},getImageData(u,t=0){return this.getImageCanvasContext(u).getImageData(-t,-t,u.width+2*t,u.height+2*t)},getImageCanvasContext(u){let t=window.document.createElement("canvas"),n=t.getContext("2d",{willReadFrequently:!0});if(!n)throw new Error("failed to create canvas 2d context");return t.width=u.width,t.height=u.height,n.drawImage(u,0,0,u.width,u.height),n},resolveURL:u=>(Si||(Si=document.createElement("a")),Si.href=u,Si.href),hardwareConcurrency:typeof navigator<"u"&&navigator.hardwareConcurrency||4,get prefersReducedMotion(){return An!==void 0?An:!!matchMedia&&(Wr!=null||(Wr=matchMedia("(prefers-reduced-motion: reduce)")),Wr.matches)},set prefersReducedMotion(u){An=u}},Ir=new class{constructor(){this._frozenAt=null}getCurrentTime(){return this._frozenAt!==null?this._frozenAt:performance.now()}setNow(u){this._frozenAt=u}restoreNow(){this._frozenAt=null}isFrozen(){return this._frozenAt!==null}};function Xe(){return Ir.getCurrentTime()}var Hr,Ii;class pe{static create(t,n,a){let c=window.document.createElement(t);return n!==void 0&&(c.className=n),a&&a.appendChild(c),c}static createNS(t,n){return window.document.createElementNS(t,n)}static disableDrag(){pe.docStyle&&pe.selectProp&&(pe.userSelect=pe.docStyle[pe.selectProp],pe.docStyle[pe.selectProp]="none")}static enableDrag(){pe.docStyle&&pe.selectProp&&(pe.docStyle[pe.selectProp]=pe.userSelect)}static suppressClickInternal(t){t.preventDefault(),t.stopPropagation(),window.removeEventListener("click",pe.suppressClickInternal,!0)}static suppressClick(){window.addEventListener("click",pe.suppressClickInternal,!0),window.setTimeout((()=>{window.removeEventListener("click",pe.suppressClickInternal,!0)}),0)}static getScale(t){let n=t.getBoundingClientRect();return{x:n.width/t.offsetWidth||1,y:n.height/t.offsetHeight||1,boundingClientRect:n}}static getPoint(t,n,a){let c=n.boundingClientRect;return new p.P((a.clientX-c.left)/n.x-t.clientLeft,(a.clientY-c.top)/n.y-t.clientTop)}static mousePos(t,n){let a=pe.getScale(t);return pe.getPoint(t,a,n)}static touchPos(t,n){let a=[],c=pe.getScale(t);for(let f of n)a.push(pe.getPoint(t,c,f));return a}static sanitize(t){let n=new DOMParser().parseFromString(t,"text/html").body||document.createElement("body"),a=n.querySelectorAll("script");for(let c of a)c.remove();return pe.clean(n),n.innerHTML}static isPossiblyDangerous(t,n){let a=n.replace(/\s+/g,"").toLowerCase();return!(!["src","href","xlink:href"].includes(t)||!a.includes("javascript:")&&!a.includes("data:"))||!!t.startsWith("on")||void 0}static clean(t){let n=t.children;for(let a of n)pe.removeAttributes(a),pe.clean(a)}static removeAttributes(t){for(let{name:n,value:a}of t.attributes)pe.isPossiblyDangerous(n,a)&&t.removeAttribute(n)}}pe.docStyle=typeof window<"u"&&((Hr=window.document)===null||Hr===void 0?void 0:Hr.documentElement.style),pe.selectProp=!pe.docStyle||"userSelect"in pe.docStyle?"userSelect":"webkitUserSelect",(function(u){let t,n,a,c;u.resetRequestQueue=()=>{t=[],n=0,a=0,c={}},u.addThrottleControl=w=>{let P=a++;return c[P]=w,P},u.removeThrottleControl=w=>{delete c[w],y()},u.getImage=(w,P,S=!0)=>new Promise(((E,C)=>{w.headers||(w.headers={}),w.headers.accept="image/webp,*/*",p.e(w,{type:"image"}),t.push({abortController:P,requestParameters:w,supportImageRefresh:S,state:"queued",onError:z=>{C(z)},onSuccess:z=>{E(z)}}),y()}));let f=w=>p._(this,void 0,void 0,(function*(){w.state="running";let{requestParameters:P,supportImageRefresh:S,onError:E,onSuccess:C,abortController:z}=w,B=S===!1&&!p.i(self)&&!p.g(P.url)&&(!P.headers||Object.keys(P.headers).reduce(((j,$)=>j&&$==="accept"),!0));n++;let N=B?x(P,z):p.m(P,z);try{let j=yield N;delete w.abortController,w.state="completed",j.data instanceof HTMLImageElement||p.b(j.data)?C(j):j.data&&C({data:yield(G=j.data,typeof createImageBitmap=="function"?p.h(G):p.j(G)),cacheControl:j.cacheControl,expires:j.expires})}catch(j){delete w.abortController,E(p.d(j))}finally{n--,y()}var G})),y=()=>{let w=(()=>{for(let P of Object.keys(c))if(c[P]())return!0;return!1})()?p.c.MAX_PARALLEL_IMAGE_REQUESTS_PER_FRAME:p.c.MAX_PARALLEL_IMAGE_REQUESTS;for(let P=n;P0;P++){let S=t.shift();S.abortController.signal.aborted?P--:f(S)}},x=(w,P)=>new Promise(((S,E)=>{let C=new Image,z=w.url,B=w.credentials;B&&B==="include"?C.crossOrigin="use-credentials":(B&&B==="same-origin"||!p.f(z))&&(C.crossOrigin="anonymous"),P.signal.addEventListener("abort",(()=>{C.src="",E(new p.a(P.signal.reason))})),C.fetchPriority="high",C.onload=()=>{C.onerror=C.onload=null,S({data:C})},C.onerror=()=>{C.onerror=C.onload=null,P.signal.aborted||E(new Error("Could not load image. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported."))},C.src=z}))})(Ii||(Ii={})),Ii.resetRequestQueue();class kt{constructor(t){this._transformRequestFn=t??null}transformRequest(t,n){return this._transformRequestFn&&this._transformRequestFn(t,n)||{url:t}}setTransformRequest(t){this._transformRequestFn=t}}function Xr(u){let t=[];if(typeof u=="string")t.push({id:"default",url:u});else if(u&&u.length>0){let n=[];for(let{id:a,url:c}of u){let f=`${a}${c}`;n.includes(f)||(n.push(f),t.push({id:a,url:c}))}}return t}function Dn(u,t,n){try{let a=new URL(u);return a.pathname+=`${t}${n}`,a.toString()}catch{throw new Error(`Invalid sprite URL "${u}", must be absolute. Modify style specification directly or use TransformStyleFunction to correct the issue dynamically`)}}function go(u){let{userImage:t}=u;return!(!t?.render||!t.render()||(u.data.replace(new Uint8Array(t.data.buffer)),0))}class _o extends p.E{constructor(){super(),this.images={},this.updatedImages={},this.callbackDispatchedThisFrame={},this.loaded=!1,this.requestors=[],this.patterns={},this.atlasImage=new p.R({width:1,height:1}),this.dirty=!0}destroy(){this.atlasTexture&&(this.atlasTexture.destroy(),this.atlasTexture=null);for(let t of Object.keys(this.images))this.removeImage(t);this.patterns={},this.atlasImage=new p.R({width:1,height:1}),this.dirty=!0}isLoaded(){return this.loaded}setLoaded(t){if(this.loaded!==t&&(this.loaded=t,t)){for(let{ids:n,promiseResolve:a}of this.requestors)a(this._getImagesForIds(n));this.requestors=[]}}getImage(t){let n=this.images[t];if(n&&!n.data&&n.spriteData){let a=n.spriteData;n.data=new p.R({width:a.width,height:a.height},a.context.getImageData(a.x,a.y,a.width,a.height).data),n.spriteData=null}return n}addImage(t,n){if(this.images[t])throw new Error(`Image id ${t} already exist, use updateImage instead`);this._validate(t,n)&&(this.images[t]=n)}_validate(t,n){let a=!0,c=n.data||n.spriteData;return this._validateStretch(n.stretchX,c?.width)||(this.fire(new p.l(new Error(`Image "${t}" has invalid "stretchX" value`))),a=!1),this._validateStretch(n.stretchY,c?.height)||(this.fire(new p.l(new Error(`Image "${t}" has invalid "stretchY" value`))),a=!1),this._validateContent(n.content,n)||(this.fire(new p.l(new Error(`Image "${t}" has invalid "content" value`))),a=!1),a}_validateStretch(t,n){if(!t)return!0;let a=0;for(let c of t){if(c[0]=t[1]))}updateImage(t,n,a=!0){let c=this.getImage(t);if(a&&(c.data.width!==n.data.width||c.data.height!==n.data.height))throw new Error(`size mismatch between old image (${c.data.width}x${c.data.height}) and new image (${n.data.width}x${n.data.height}).`);n.version=c.version+1,this.images[t]=n,this.updatedImages[t]=!0}removeImage(t){var n;let a=this.images[t];delete this.images[t],delete this.patterns[t],!((n=a.userImage)===null||n===void 0)&&n.onRemove&&a.userImage.onRemove()}listImages(){return Object.keys(this.images)}getImages(t){return new Promise(((n,a)=>{let c=!0;if(!this.isLoaded())for(let f of t)this.images[f]||(c=!1);this.isLoaded()||c?n(this._getImagesForIds(t)):this.requestors.push({ids:t,promiseResolve:n})}))}_getImagesForIds(t){var n;let a={};for(let c of t){let f=this.getImage(c);f||(this.fire(new p.n("styleimagemissing",{id:c})),f=this.getImage(c)),f?a[c]={data:f.data.clone(),pixelRatio:f.pixelRatio,sdf:f.sdf,version:f.version,stretchX:f.stretchX,stretchY:f.stretchY,content:f.content,textFitWidth:f.textFitWidth,textFitHeight:f.textFitHeight,hasRenderCallback:!!(!((n=f.userImage)===null||n===void 0)&&n.render)}:p.w(`Image "${c}" could not be loaded. Please make sure you have added the image with map.addImage() or a "sprite" property in your style. You can provide missing images by listening for the "styleimagemissing" map event.`)}return a}getPixelSize(){let{width:t,height:n}=this.atlasImage;return{width:t,height:n}}getPattern(t){let n=this.patterns[t],a=this.getImage(t);if(!a)return null;if(n&&n.position.version===a.version)return n.position;if(n)n.position.version=a.version;else{let c={w:a.data.width+2,h:a.data.height+2,x:0,y:0},f=new p.I(c,a);this.patterns[t]={bin:c,position:f}}return this._updatePatternAtlas(),this.patterns[t].position}bind(t){let n=t.gl;this.atlasTexture?this.dirty&&(this.atlasTexture.update(this.atlasImage),this.dirty=!1):this.atlasTexture=new p.T(t,this.atlasImage,n.RGBA),this.atlasTexture.bind(n.LINEAR,n.CLAMP_TO_EDGE)}_updatePatternAtlas(){let t=[];for(let f in this.patterns)t.push(this.patterns[f].bin);let{w:n,h:a}=p.p(t),c=this.atlasImage;c.resize({width:n||1,height:a||1});for(let f in this.patterns){let{bin:y}=this.patterns[f],x=y.x+1,w=y.y+1,P=this.getImage(f).data,S=P.width,E=P.height;p.R.copy(P,c,{x:0,y:0},{x,y:w},{width:S,height:E}),p.R.copy(P,c,{x:0,y:E-1},{x,y:w-1},{width:S,height:1}),p.R.copy(P,c,{x:0,y:0},{x,y:w+E},{width:S,height:1}),p.R.copy(P,c,{x:S-1,y:0},{x:x-1,y:w},{width:1,height:E}),p.R.copy(P,c,{x:0,y:0},{x:x+S,y:w},{width:1,height:E})}this.dirty=!0}beginFrame(){this.callbackDispatchedThisFrame={}}dispatchRenderCallbacks(t){for(let n of t){if(this.callbackDispatchedThisFrame[n])continue;this.callbackDispatchedThisFrame[n]=!0;let a=this.getImage(n);a||p.w(`Image with ID: "${n}" was not found`),go(a)&&this.updateImage(n,a)}}cloneImages(){let t={};for(let n in this.images){let a=this.images[n];t[n]=Object.assign(Object.assign({},a),{data:a.data?a.data.clone():null})}return t}}let We=1e20,W=new Float64Array(256);for(let u=0;u<256;u++){let t=.5-Math.pow(u/255,.45454545454545453);W[u]=t*Math.abs(t)}function K(u,t,n,a,c,f,y,x,w){for(let P=t;P-1);w++,f[w]=x,y[w]=P,y[w+1]=We}for(let x=0,w=0;x/[-\w]+/.test(c)?c:`'${CSS.escape(c)}'`)).join(",");return new Me.TinySDF({fontSize:48,buffer:6,radius:16,cutoff:.25,fontFamily:a,fontWeight:this._fontWeight(n[0]),fontStyle:this._fontStyle(n[0]),lang:this.lang})}_fontStyle(t){return/italic/i.test(t)?"italic":/oblique/i.test(t)?"oblique":"normal"}_fontWeight(t){let n={thin:100,hairline:100,"extra light":200,"ultra light":200,light:300,normal:400,regular:400,medium:500,semibold:600,demibold:600,bold:700,"extra bold":800,"ultra bold":800,black:900,heavy:900,"extra black":950,"ultra black":950},a;for(let[c,f]of Object.entries(n))new RegExp(`\\b${c}\\b`,"i").test(t)&&(a=`${f}`);return a}destroy(){for(let t in this.entries){let n=this.entries[t];n.tinySDF=null,n.ideographTinySDF=null,n.glyphs={},n.requests={},n.ranges={}}this.entries={}}}Me.loadGlyphRange=function(u,t,n,a){return p._(this,void 0,void 0,(function*(){let c=256*t,f=c+255,y=yield a.transformRequest(n.replace("{fontstack}",u).replace("{range}",`${c}-${f}`),"Glyphs"),x=yield p.o(y,new AbortController);if(!x?.data)throw new Error(`Could not load glyph range. range: ${t}, ${c}-${f}`);let w={};for(let P of p.q(x.data))w[P.id]=P;return w}))},Me.TinySDF=class{constructor({fontSize:u=24,buffer:t=3,radius:n=8,cutoff:a=.25,fontFamily:c="sans-serif",fontWeight:f="normal",fontStyle:y="normal",lang:x=null}={}){this.buffer=t,this.radius=n,this.cutoff=a,this.lang=x;let w=this.size=u+4*t,P=this._createCanvas(w),S=this.ctx=P.getContext("2d",{willReadFrequently:!0});S.font=`${y} ${f} ${u}px ${c}`,S.textBaseline="alphabetic",S.textAlign="left",S.fillStyle="black",this.gridOuter=new Float64Array(w*w),this.gridInner=new Float64Array(w*w),this.f=new Float64Array(w),this.z=new Float64Array(w+1),this.v=new Uint16Array(w)}_createCanvas(u){if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(u,u);let t=document.createElement("canvas");return t.width=t.height=u,t}draw(u){let{width:t,actualBoundingBoxAscent:n,actualBoundingBoxDescent:a,actualBoundingBoxLeft:c,actualBoundingBoxRight:f}=this.ctx.measureText(u),y=Math.ceil(n),x=Math.floor(c),w=Math.max(0,Math.min(this.size-this.buffer,Math.ceil(f)-x)),P=Math.max(0,Math.min(this.size-this.buffer,y+Math.ceil(a))),S=w+2*this.buffer,E=P+2*this.buffer,C=Math.max(S*E,0),z=new Uint8ClampedArray(C),B={data:z,width:S,height:E,glyphWidth:w,glyphHeight:P,glyphTop:y,glyphLeft:x,glyphAdvance:t};if(w===0||P===0)return B;let{ctx:N,buffer:G,gridInner:j,gridOuter:$}=this;this.lang&&(N.lang=this.lang),N.clearRect(G,G,w,P),N.fillText(u,G-x,G+y);let X=N.getImageData(G,G,w,P);$.fill(We,0,C),j.fill(0,0,C);let Z=3;for(let q=0;q1&&(w=t[++x]);let S=Math.abs(P-w.left),E=Math.abs(P-w.right),C=Math.min(S,E),z,B=f/a*(c+1);if(w.isDash){let N=c-Math.abs(B);z=Math.sqrt(C*C+N*N)}else z=c-Math.sqrt(C*C+B*B);this.data[y+P]=Math.max(0,Math.min(255,z+128))}}}addRegularDash(t){for(let x=t.length-1;x>=0;--x){let w=t[x],P=t[x+1];w.zeroLength?t.splice(x,1):P&&P.isDash===w.isDash&&(P.left=w.left,t.splice(x,1))}let n=t[0],a=t[t.length-1];n.isDash===a.isDash&&(n.left=a.left-this.width,a.right=n.right+this.width);let c=this.width*this.nextRow,f=0,y=t[f];for(let x=0;x1&&(y=t[++f]);let w=Math.abs(x-y.left),P=Math.abs(x-y.right),S=Math.min(w,P);this.data[c+x]=Math.max(0,Math.min(255,(y.isDash?S:-S)+128))}}addDash(t,n){let a=n?7:0,c=2*a+1;if(this.nextRow+c>this.height)return p.w("LineAtlas out of space"),null;let f=0;for(let x of t)f+=x;if(f!==0){let x=this.width/f,w=this.getDashRanges(t,this.width,x);n?this.addRoundDash(w,x,a):this.addRegularDash(w)}let y={y:this.nextRow+a,height:2*a,width:f};return this.nextRow+=c,this.dirty=!0,y}bind(t){let n=t.gl;this.texture?(n.bindTexture(n.TEXTURE_2D,this.texture),this.dirty&&(this.dirty=!1,n.texSubImage2D(n.TEXTURE_2D,0,0,0,this.width,this.height,n.ALPHA,n.UNSIGNED_BYTE,this.data))):(this.texture=n.createTexture(),n.bindTexture(n.TEXTURE_2D,this.texture),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_S,n.REPEAT),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_T,n.REPEAT),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,n.LINEAR),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MAG_FILTER,n.LINEAR),n.texImage2D(n.TEXTURE_2D,0,n.ALPHA,this.width,this.height,0,n.ALPHA,n.UNSIGNED_BYTE,this.data))}}let vt="maplibre_preloaded_worker_pool";class xt{constructor(){this.active={}}acquire(t){if(!this.workers)for(this.workers=[];this.workers.lengthp.m(t,n)))),Mr}function zn(u,t){let n=p.O();return p.Q(n,n,[1,1,0]),p.S(n,n,[.5*u.width,.5*u.height,1]),u.calculatePosMatrix?p.U(n,n,u.calculatePosMatrix(t.toUnwrapped())):n}function Oi(u,t,n,a,c,f,y){var x;let w=(function(C,z,B){if(C)for(let N of C){let G=z[N];if(G?.source===B&&G.type==="fill-extrusion")return!0}else for(let N in z){let G=z[N];if(G.source===B&&G.type==="fill-extrusion")return!0}return!1})((x=c?.layers)!==null&&x!==void 0?x:null,t,u.id),P=f.maxPitchScaleFactor(),S=u.tilesIn(a,P,w);S.sort(vo);let E=[];for(let C of S)E.push({wrappedTileID:C.tileID.wrapped().key,queryResults:C.tile.queryRenderedFeatures(t,n,u.getState(),C.queryGeometry,C.cameraQueryGeometry,C.scale,c,f,P,zn(f,C.tileID),y?(z,B)=>y(C.tileID,z,B):void 0)});return(function(C,z){for(let B in C)for(let N of C[B])Er(N,z);return C})((function(C){let z={},B={};for(let{queryResults:N,wrappedTileID:G}of C){B[G]||(B[G]={});let j=B[G];for(let $ in N){let X=N[$];j[$]||(j[$]={});let Z=j[$];z[$]||(z[$]=[]);for(let U of X)Z[U.featureIndex]||(Z[U.featureIndex]=!0,z[$].push(U))}}return z})(E),u)}function vo(u,t){let n=u.tileID,a=t.tileID;return n.overscaledZ-a.overscaledZ||n.canonical.y-a.canonical.y||n.wrap-a.wrap||n.canonical.x-a.canonical.x}function Er(u,t){let n=u.feature,a=t.getFeatureState(n.layer["source-layer"],n.id);n.source=n.layer.source,n.layer["source-layer"]&&(n.sourceLayer=n.layer["source-layer"]),n.state=a}function Kr(u,t,n,a){return p._(this,void 0,void 0,(function*(){let c=u;if(u.url?c=(yield p.k(yield t.transformRequest(u.url,"Source"),n)).data:yield qt.frameAsync(n,a),!c)return null;let f=p.V(p.e(c,u),["tiles","minzoom","maxzoom","attribution","bounds","scheme","tileSize","encoding"]);return"vector_layers"in c&&c.vector_layers&&(f.vectorLayerIds=c.vector_layers.map((y=>y.id))),f}))}class Re{constructor(t,n){t&&(n?this.setSouthWest(t).setNorthEast(n):Array.isArray(t)&&(t.length===4?this.setSouthWest([t[0],t[1]]).setNorthEast([t[2],t[3]]):this.setSouthWest(t[0]).setNorthEast(t[1])))}setNorthEast(t){return this._ne=t instanceof p.W?new p.W(t.lng,t.lat):p.W.convert(t),this}setSouthWest(t){return this._sw=t instanceof p.W?new p.W(t.lng,t.lat):p.W.convert(t),this}extend(t){let n=this._sw,a=this._ne,c,f;if(t instanceof p.W)c=t,f=t;else{if(!(t instanceof Re))return Array.isArray(t)?t.length===4||t.every(Array.isArray)?this.extend(Re.convert(t)):this.extend(p.W.convert(t)):t&&("lng"in t||"lon"in t)&&"lat"in t?this.extend(p.W.convert(t)):this;if(c=t._sw,f=t._ne,!c||!f)return this}return n||a?(n.lng=Math.min(c.lng,n.lng),n.lat=Math.min(c.lat,n.lat),a.lng=Math.max(f.lng,a.lng),a.lat=Math.max(f.lat,a.lat)):(this._sw=new p.W(c.lng,c.lat),this._ne=new p.W(f.lng,f.lat)),this}getCenter(){return new p.W((this._sw.lng+this._ne.lng)/2,(this._sw.lat+this._ne.lat)/2)}getSouthWest(){return this._sw}getNorthEast(){return this._ne}getNorthWest(){return new p.W(this.getWest(),this.getNorth())}getSouthEast(){return new p.W(this.getEast(),this.getSouth())}getWest(){return this._sw.lng}getSouth(){return this._sw.lat}getEast(){return this._ne.lng}getNorth(){return this._ne.lat}toArray(){return[this._sw.toArray(),this._ne.toArray()]}toString(){return`LngLatBounds(${this._sw.toString()}, ${this._ne.toString()})`}isEmpty(){return!(this._sw&&this._ne)}contains(t){let{lng:n,lat:a}=p.W.convert(t),c=this._sw.lng<=n&&n<=this._ne.lng;return this._sw.lng>this._ne.lng&&(c=this._sw.lng>=n&&n>=this._ne.lng),this._sw.lat<=a&&a<=this._ne.lat&&c}intersects(t){if(!((t=Re.convert(t)).getNorth()>=this.getSouth()&&t.getSouth()<=this.getNorth()))return!1;let n=Math.abs(this.getEast()-this.getWest()),a=Math.abs(t.getEast()-t.getWest());if(n>=360||a>=360)return!0;let c=p.X(this.getWest(),-180,180),f=p.X(this.getEast(),-180,180),y=p.X(t.getWest(),-180,180),x=p.X(t.getEast(),-180,180),w=c>f,P=y>x;return!(!w||!P)||(w?x>=c||y<=f:P?f>=y||c<=x:y<=f&&x>=c)}static convert(t){return t instanceof Re?t:t&&new Re(t)}static fromLngLat(t,n=0){let a=360*n/40075017,c=a/Math.cos(Math.PI/180*t.lat);return new Re(new p.W(t.lng-c,t.lat-a),new p.W(t.lng+c,t.lat+a))}adjustAntiMeridian(){let t=new p.W(this._sw.lng,this._sw.lat),n=new p.W(this._ne.lng,this._ne.lat);return new Re(t,t.lng>n.lng?new p.W(n.lng+360,n.lat):n)}}class Bt{constructor(t,n,a){this.bounds=Re.convert(this.validateBounds(t)),this.minzoom=n||0,this.maxzoom=a||24}validateBounds(t){return Array.isArray(t)&&t.length===4?[Math.max(-180,t[0]),Math.max(-90,t[1]),Math.min(180,t[2]),Math.min(90,t[3])]:[-180,-90,180,90]}contains(t){let n=Math.pow(2,t.z),a=Math.floor(p.Z(this.bounds.getWest())*n),c=Math.floor(p.Y(this.bounds.getNorth())*n),f=Math.ceil(p.Z(this.bounds.getEast())*n),y=Math.ceil(p.Y(this.bounds.getSouth())*n);return t.x>=a&&t.x=c&&t.y{this._options.tiles=t})),this}setUrl(t){return this.setSourceProperty((()=>{this.url=t,this._options.url=t})),this}onRemove(){this._tileJSONRequest&&(this._tileJSONRequest.abort(),this._tileJSONRequest=null)}serialize(){return p.e({},this._options)}loadTile(t){return p._(this,void 0,void 0,(function*(){let n=t.tileID.canonical.url(this.tiles,this.map.getPixelRatio(),this.scheme),a={request:yield this.map._requestManager.transformRequest(n,"Tile"),uid:t.uid,tileID:t.tileID,zoom:t.tileID.overscaledZ,tileSize:this.tileSize*t.tileID.overscaleFactor(),type:this.type,source:this.id,pixelRatio:this.map.getPixelRatio(),showCollisionBoxes:this.map.showCollisionBoxes,promoteId:this.promoteId,subdivisionGranularity:this.map.style.projection.subdivisionGranularity,encoding:this.encoding,overzoomParameters:yield this._getOverzoomParameters(t),etag:t.etag};a.request.collectResourceTiming=this._collectResourceTiming;let c="RT";if(t.actor&&t.state!=="expired"){if(t.state==="loading")return new Promise(((f,y)=>{t.reloadPromise={resolve:f,reject:y}}))}else t.actor=this.dispatcher.getActor(),c="LT";t.abortController=new AbortController;try{let f=yield t.actor.sendAsync({type:c,data:a},t.abortController);if(delete t.abortController,t.aborted)return;this._afterTileLoadWorkerResponse(t,f);let y={};return f?.etagUnmodified&&(y.unmodified=!0),y}catch(f){if(delete t.abortController,t.aborted)return;if(f&&f.status!==404)throw f;this._afterTileLoadWorkerResponse(t,null)}}))}_getOverzoomParameters(t){return p._(this,void 0,void 0,(function*(){if(t.tileID.canonical.z<=this.maxzoom||this.map._zoomLevelsToOverscale===void 0)return;let n=t.tileID.scaledTo(this.maxzoom).canonical,a=n.url(this.tiles,this.map.getPixelRatio(),this.scheme);return{maxZoomTileID:n,overzoomRequest:yield this.map._requestManager.transformRequest(a,"Tile")}}))}_afterTileLoadWorkerResponse(t,n){if(n?.resourceTiming&&(t.resourceTiming=n.resourceTiming),n&&this.map._refreshExpiredTiles&&t.setExpiryData(n),t.etag=n?.etag,t.loadVectorData(n,this.map.painter),t.reloadPromise){let a=t.reloadPromise;t.reloadPromise=null,this.loadTile(t).then(a.resolve).catch(a.reject)}}abortTile(t){return p._(this,void 0,void 0,(function*(){t.abortController&&(t.abortController.abort(),delete t.abortController),t.actor&&(yield t.actor.sendAsync({type:"AT",data:{uid:t.uid,type:this.type,source:this.id}}))}))}unloadTile(t){return p._(this,void 0,void 0,(function*(){t.unloadVectorData(),t.actor&&(yield t.actor.sendAsync({type:"RMT",data:{uid:t.uid,type:this.type,source:this.id}}))}))}hasTransition(){return!1}}class Mi extends p.E{constructor(t,n,a,c){super(),this.id=t,this.dispatcher=a,this.setEventedParent(c),this.type="raster",this.minzoom=0,this.maxzoom=22,this.roundZoom=!0,this.scheme="xyz",this.tileSize=512,this._loaded=!1,this._options=p.e({type:"raster"},n),p.e(this,p.V(n,["url","scheme","tileSize"]))}load(){return p._(this,arguments,void 0,(function*(t=!1){this._loaded=!1,this.fire(new p.n("dataloading",{dataType:"source"})),this._tileJSONRequest=new AbortController;try{let n=yield Kr(this._options,this.map._requestManager,this._tileJSONRequest,this.map._ownerWindow);this._tileJSONRequest=null,this._loaded=!0,n&&(p.e(this,n),n.bounds&&(this.tileBounds=new Bt(n.bounds,this.minzoom,this.maxzoom)),this.fire(new p.n("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new p.n("data",{dataType:"source",sourceDataType:"content",sourceDataChanged:t})))}catch(n){this._tileJSONRequest=null,this._loaded=!0,p.$(n)||this.fire(new p.l(p.d(n)))}}))}loaded(){return this._loaded}onAdd(t){this.map=t,this.load()}onRemove(){this._tileJSONRequest&&(this._tileJSONRequest.abort(),this._tileJSONRequest=null)}setSourceProperty(t){this._tileJSONRequest&&(this._tileJSONRequest.abort(),this._tileJSONRequest=null),t(),this.load(!0)}setTiles(t){return this.setSourceProperty((()=>{this._options.tiles=t})),this}setUrl(t){return this.setSourceProperty((()=>{this.url=t,this._options.url=t})),this}serialize(){return p.e({},this._options)}hasTile(t){return!this.tileBounds||this.tileBounds.contains(t.canonical)}loadTile(t){return p._(this,void 0,void 0,(function*(){let n=t.tileID.canonical.url(this.tiles,this.map.getPixelRatio(),this.scheme);t.abortController=new AbortController;try{let a=yield Ii.getImage(yield this.map._requestManager.transformRequest(n,"Tile"),t.abortController,this.map._refreshExpiredTiles);if(delete t.abortController,t.aborted)return void(t.state="unloaded");if(a?.data){this.map._refreshExpiredTiles&&(a.cacheControl||a.expires)&&t.setExpiryData({cacheControl:a.cacheControl,expires:a.expires});let c=this.map.painter.context,f=c.gl,y=a.data;t.texture=this.map.painter.getTileTexture(y.width),t.texture?t.texture.update(y,{useMipmap:!0}):(t.texture=new p.T(c,y,f.RGBA,{useMipmap:!0}),t.texture.bind(f.LINEAR,f.CLAMP_TO_EDGE,f.LINEAR_MIPMAP_NEAREST)),t.state="loaded"}}catch(a){if(delete t.abortController,t.aborted)t.state="unloaded";else if(a)throw t.state="errored",a}}))}abortTile(t){return p._(this,void 0,void 0,(function*(){t.abortController&&(t.abortController.abort(),delete t.abortController)}))}unloadTile(t){return p._(this,void 0,void 0,(function*(){t.texture&&this.map.painter.saveTileTexture(t.texture)}))}hasTransition(){return!1}}class Ht extends Mi{constructor(t,n,a,c){super(t,n,a,c),this.type="raster-dem",this.maxzoom=22,this._options=p.e({type:"raster-dem"},n),this.encoding=n.encoding||"mapbox",this.redFactor=n.redFactor,this.greenFactor=n.greenFactor,this.blueFactor=n.blueFactor,this.baseShift=n.baseShift}loadTile(t){return p._(this,void 0,void 0,(function*(){let n=t.tileID.canonical.url(this.tiles,this.map.getPixelRatio(),this.scheme),a=yield this.map._requestManager.transformRequest(n,"Tile");t.neighboringTiles=this._getNeighboringTiles(t.tileID),t.abortController=new AbortController;try{let c=yield Ii.getImage(a,t.abortController,this.map._refreshExpiredTiles);if(delete t.abortController,t.aborted)return void(t.state="unloaded");if(c?.data){let f=c.data;this.map._refreshExpiredTiles&&(c.cacheControl||c.expires)&&t.setExpiryData({cacheControl:c.cacheControl,expires:c.expires});let y=p.b(f)&&p.a0()?f:yield this.readImageNow(f),x={type:this.type,uid:t.uid,source:this.id,rawImageData:y,encoding:this.encoding,redFactor:this.redFactor,greenFactor:this.greenFactor,blueFactor:this.blueFactor,baseShift:this.baseShift};if(t.actor&&t.state!=="expired"&&t.state!=="reloading")return;t.actor&&t.state!=="expired"||(t.actor=this.dispatcher.getActor()),t.dem=yield t.actor.sendAsync({type:"LDT",data:x}),t.needsHillshadePrepare=!0,t.needsTerrainPrepare=!0,t.state="loaded"}}catch(c){if(delete t.abortController,t.aborted)t.state="unloaded";else if(c)throw t.state="errored",c}}))}readImageNow(t){return p._(this,void 0,void 0,(function*(){if(typeof VideoFrame<"u"&&p.a1()){let n=t.width+2,a=t.height+2;try{return new p.R({width:n,height:a},yield p.a2(t,-1,-1,n,a))}catch{}}return qt.getImageData(t,1)}))}_getNeighboringTiles(t){let n=t.canonical,a=Math.pow(2,n.z),c=(n.x-1+a)%a,f=n.x===0?t.wrap-1:t.wrap,y=(n.x+1+a)%a,x=n.x+1===a?t.wrap+1:t.wrap,w={};return w[new p.a3(t.overscaledZ,f,n.z,c,n.y).key]={backfilled:!1},w[new p.a3(t.overscaledZ,x,n.z,y,n.y).key]={backfilled:!1},n.y>0&&(w[new p.a3(t.overscaledZ,f,n.z,c,n.y-1).key]={backfilled:!1},w[new p.a3(t.overscaledZ,t.wrap,n.z,n.x,n.y-1).key]={backfilled:!1},w[new p.a3(t.overscaledZ,x,n.z,y,n.y-1).key]={backfilled:!1}),n.y+1f.key===a));c>-1&&u.addOrUpdateProperties.splice(c,1)}return(u.removeAllProperties||t.removeAllProperties)&&(n.removeAllProperties=!0),(u.removeProperties||t.removeProperties)&&(n.removeProperties=[...u.removeProperties||[],...t.removeProperties||[]]),(u.addOrUpdateProperties||t.addOrUpdateProperties)&&(n.addOrUpdateProperties=[...u.addOrUpdateProperties||[],...t.addOrUpdateProperties||[]]),(u.newGeometry||t.newGeometry)&&(n.newGeometry=t.newGeometry||u.newGeometry),n}function za(u){var t,n;if(!u)return{};let a={};return a.removeAll=u.removeAll,a.remove=new Set(u.remove||[]),a.add=new Map((t=u.add)===null||t===void 0?void 0:t.map((c=>[c.id,c]))),a.update=new Map((n=u.update)===null||n===void 0?void 0:n.map((c=>[c.id,c]))),a}function Ra(u){return u&&u.length!==0?typeof u[0]=="number"?[u]:u.flatMap((t=>Ra(t))):[]}function Cr(u){return u.type==="GeometryCollection"?u.geometries.flatMap((t=>Cr(t))):Ra(u.coordinates)}function Rn(u){let t=new Re,n;switch(u.type){case"FeatureCollection":n=u.features.flatMap((a=>Cr(a.geometry)));break;case"Feature":n=Cr(u.geometry);break;default:n=Cr(u)}if(n.length===0)return t;for(let a of n){let[c,f]=a;t.extend([c,f])}return t}class us extends p.E{constructor(t,n,a,c){super(),this.id=t,this.type="geojson",this.minzoom=0,this.maxzoom=18,this.tileSize=512,this.isTileClipped=!0,this.reparseOverscaled=!0,this._removed=!1,this._isUpdatingWorker=!1,this._pendingWorkerUpdate={data:n.data},this.actor=a.getActor(),this.setEventedParent(c),this._data=typeof n.data=="string"?{url:n.data}:{geojson:n.data},this._options=p.e({},n),this._collectResourceTiming=n.collectResourceTiming,n.maxzoom!==void 0&&(this.maxzoom=n.maxzoom),n.type&&(this.type=n.type),n.attribution&&(this.attribution=n.attribution),this.promoteId=n.promoteId,n.clusterMaxZoom!==void 0&&this.maxzoom<=n.clusterMaxZoom&&p.w(`The maxzoom value "${this.maxzoom}" is expected to be greater than the clusterMaxZoom value "${n.clusterMaxZoom}".`),this.workerOptions=p.e({source:this.id,geojsonVtOptions:{buffer:this._pixelsToTileUnits(n.buffer!==void 0?n.buffer:128),tolerance:this._pixelsToTileUnits(n.tolerance!==void 0?n.tolerance:.375),extent:p.a6,maxZoom:this.maxzoom,lineMetrics:n.lineMetrics||!1,generateId:n.generateId||!1,promoteId:typeof n.promoteId=="string"?n.promoteId:void 0,cluster:n.cluster||!1,clusterOptions:{maxZoom:this._getClusterMaxZoom(n.clusterMaxZoom),minPoints:Math.max(2,n.clusterMinPoints||2),extent:p.a6,radius:this._pixelsToTileUnits(n.clusterRadius||50),log:!1,generateId:n.generateId||!1}},clusterProperties:n.clusterProperties,filter:n.filter},n.workerOptions)}_hasPendingWorkerUpdate(){return this._pendingWorkerUpdate.data!==void 0||this._pendingWorkerUpdate.diff!==void 0||this._pendingWorkerUpdate.updateCluster}_pixelsToTileUnits(t){return t*(p.a6/this.tileSize)}_getClusterMaxZoom(t){let n=t?Math.round(t):this.maxzoom-1;return Number.isInteger(t)||t===void 0||p.w(`Integer expected for option 'clusterMaxZoom': provided value "${t}" rounded to "${n}"`),n}load(){return p._(this,void 0,void 0,(function*(){yield this._updateWorkerData()}))}onAdd(t){this.map=t,this.load()}setData(t,n){this._data=typeof t=="string"?{url:t}:{geojson:t},this._pendingWorkerUpdate={data:t};let a=this._updateWorkerData();return n?a:this}updateData(t,n){this._pendingWorkerUpdate.diff=(function(c,f){if(!c)return f||{};if(!f)return c||{};let y=za(c),x=za(f);(function(P,S){S.removeAll&&(P.add.clear(),P.update.clear(),P.remove.clear(),S.remove.clear());for(let E of S.remove)P.add.delete(E),P.update.delete(E);for(let[E,C]of S.update){let z=P.update.get(E);z&&(S.update.set(E,Jr(z,C)),P.update.delete(E))}})(y,x);let w={};if((y.removeAll||x.removeAll)&&(w.removeAll=!0),w.remove=new Set([...y.remove,...x.remove]),w.add=new Map([...y.add,...x.add]),w.update=new Map([...y.update,...x.update]),w.remove.size&&w.add.size)for(let P of w.add.keys())w.remove.delete(P);return(function(P){let S={};return P.removeAll&&(S.removeAll=P.removeAll),P.remove&&(S.remove=Array.from(P.remove)),P.add&&(S.add=Array.from(P.add.values())),P.update&&(S.update=Array.from(P.update.values())),S})(w)})(this._pendingWorkerUpdate.diff,t);let a=this._updateWorkerData();return n?a:this}getData(){return p._(this,void 0,void 0,(function*(){return this._data.url&&(yield this.once("data")),this._data.geojson?this._data.geojson:{type:"FeatureCollection",features:Array.from(this._data.updateable.values())}}))}getBounds(){return p._(this,void 0,void 0,(function*(){return Rn(yield this.getData())}))}setClusterOptions(t){return this.workerOptions.geojsonVtOptions.cluster=t.cluster,t.clusterRadius!==void 0&&(this.workerOptions.geojsonVtOptions.clusterOptions.radius=this._pixelsToTileUnits(t.clusterRadius)),t.clusterMaxZoom!==void 0&&(this.workerOptions.geojsonVtOptions.clusterOptions.maxZoom=this._getClusterMaxZoom(t.clusterMaxZoom)),this._pendingWorkerUpdate.updateCluster=!0,this._updateWorkerData(),this}getClusterExpansionZoom(t){return this.actor.sendAsync({type:"GCEZ",data:{type:this.type,clusterId:t,source:this.id}})}getClusterChildren(t){return this.actor.sendAsync({type:"GCC",data:{type:this.type,clusterId:t,source:this.id}})}getClusterLeaves(t,n,a){return this.actor.sendAsync({type:"GCL",data:{type:this.type,source:this.id,clusterId:t,limit:n,offset:a}})}_updateWorkerData(){return p._(this,void 0,void 0,(function*(){if(this._isUpdatingWorker)return;if(!this._hasPendingWorkerUpdate())return void p.w(`No pending worker updates for GeoJSONSource ${this.id}.`);let{data:t,diff:n,updateCluster:a}=this._pendingWorkerUpdate,c=this._getLoadGeoJSONParameters(t,n,a);t!==void 0?this._pendingWorkerUpdate.data=void 0:n?this._pendingWorkerUpdate.diff=void 0:a&&(this._pendingWorkerUpdate.updateCluster=void 0),yield this._dispatchWorkerUpdate(c)}))}_getLoadGeoJSONParameters(t,n,a){return p._(this,void 0,void 0,(function*(){let c=p.e({type:this.type},this.workerOptions);return typeof t=="string"?(c.request=yield this.map._requestManager.transformRequest(qt.resolveURL(t),"Source"),c.request.collectResourceTiming=this._collectResourceTiming,c):t!==void 0?(c.data=t,c):n?(c.dataDiff=n,c):a?(c.updateCluster=!0,c):void 0}))}_dispatchWorkerUpdate(t){return p._(this,void 0,void 0,(function*(){this._isUpdatingWorker=!0,this.fire(new p.n("dataloading",{dataType:"source"}));try{let n=yield t,a=yield this.actor.sendAsync({type:"LD",data:n});if(this._isUpdatingWorker=!1,this._removed||a.abandoned)return void this.fire(new p.n("dataabort",{dataType:"source"}));a.data&&(this._data={geojson:a.data});let c=this._applyDiffToSource(n.dataDiff),f=this._getShouldReloadTileOptions(c),y={dataType:"source"};this._applyResourceTiming(y,a),this.fire(new p.n("data",Object.assign(Object.assign({},y),{sourceDataType:"metadata"}))),this.fire(new p.n("data",Object.assign(Object.assign({},y),{sourceDataType:"content",shouldReloadTileOptions:f})))}catch(n){if(this._isUpdatingWorker=!1,this._removed)return void this.fire(new p.n("dataabort",{dataType:"source"}));this.fire(new p.l(p.d(n)))}finally{this._hasPendingWorkerUpdate()&&this._updateWorkerData()}}))}_applyResourceTiming(t,n){var a;if(!this._collectResourceTiming)return;let c=(a=n.resourceTiming)===null||a===void 0?void 0:a[this.id];if(!c)return;let f=c.slice(0);f?.length&&p.e(t,{resourceTiming:f})}_applyDiffToSource(t){if(!t)return;let n=typeof this.promoteId=="string"?this.promoteId:void 0;if(!this._data.url&&!this._data.updateable){let c=(function(f,y){let x=new Map;if(f==null||f.type==null)return x;if(f.type==="Feature"){let w=yi(f,y);return w==null?void 0:(x.set(w,f),x)}if(f.type==="FeatureCollection"){let w=new Set;for(let P of f.features){let S=yi(P,y);if(S==null||w.has(S))return;w.add(S),x.set(S,P)}return x}})(this._data.geojson,n);if(!c)throw new Error(`GeoJSONSource "${this.id}": GeoJSON data is not compatible with updateData`);this._data={updateable:c}}if(!this._data.updateable)return;let a=(function(c,f,y){var x,w;let P=[];if(f.removeAll)c.clear();else if(f.remove)for(let S of f.remove){let E=c.get(S);E&&(P.push(E.geometry),c.delete(S))}if(f.add)for(let S of f.add){let E=yi(S,y);if(E==null)continue;let C=c.get(E);C&&P.push(C.geometry),P.push(S.geometry),c.set(E,S)}if(f.update)for(let S of f.update){let E=c.get(S.id);if(!E)continue;let C=!!S.newGeometry,z=S.removeAllProperties||((x=S.removeProperties)===null||x===void 0?void 0:x.length)>0||((w=S.addOrUpdateProperties)===null||w===void 0?void 0:w.length)>0;if(!C&&!z)continue;P.push(E.geometry);let B=Object.assign({},E);if(c.set(S.id,B),C&&(P.push(S.newGeometry),B.geometry=S.newGeometry),z){if(B.properties=S.removeAllProperties?{}:Object.assign({},B.properties||{}),S.removeProperties)for(let N of S.removeProperties)delete B.properties[N];if(S.addOrUpdateProperties)for(let{key:N,value:G}of S.addOrUpdateProperties)B.properties[N]=G}}return P})(this._data.updateable,t,n);return t.removeAll||this._options.cluster?void 0:a}_getShouldReloadTileOptions(t){if(t)return{affectedBounds:t.filter(Boolean).map((n=>Rn(n)))}}shouldReloadTile(t,{affectedBounds:n}){if(t.state==="loading")return!0;if(t.state==="unloaded")return!1;let{buffer:a,extent:c}=this.workerOptions.geojsonVtOptions,f=(function({x:y,y:x,z:w},P=0){let S=p.a4((y-P)/Math.pow(2,w)),E=p.a5((x+1+P)/Math.pow(2,w)),C=p.a4((y+1+P)/Math.pow(2,w)),z=p.a5((x-P)/Math.pow(2,w));return new Re([S,E],[C,z])})(t.tileID.canonical,a/c);for(let y of n)if(f.intersects(y))return!0;return!1}loaded(){return!this._isUpdatingWorker&&!this._hasPendingWorkerUpdate()}loadTile(t){return p._(this,void 0,void 0,(function*(){let n=t.actor?"RT":"LT";t.actor=this.actor;let a={type:this.type,uid:t.uid,tileID:t.tileID,zoom:t.tileID.overscaledZ,maxZoom:this.maxzoom,tileSize:this.tileSize,source:this.id,pixelRatio:this.map.getPixelRatio(),showCollisionBoxes:this.map.showCollisionBoxes,promoteId:this.promoteId,subdivisionGranularity:this.map.style.projection.subdivisionGranularity};t.abortController=new AbortController;let c=yield this.actor.sendAsync({type:n,data:a},t.abortController);delete t.abortController,t.unloadVectorData(),t.aborted||t.loadVectorData(c,this.map.painter,n==="RT")}))}abortTile(t){return p._(this,void 0,void 0,(function*(){t.abortController&&(t.abortController.abort(),delete t.abortController),t.aborted=!0}))}unloadTile(t){return p._(this,void 0,void 0,(function*(){t.unloadVectorData(),yield this.actor.sendAsync({type:"RMT",data:{uid:t.uid,type:this.type,source:this.id}})}))}onRemove(){this._removed=!0,this.actor.sendAsync({type:"RS",data:{type:this.type,source:this.id}})}serialize(){return p.e({},this._options,{type:this.type,data:this._data.updateable?{type:"FeatureCollection",features:Array.from(this._data.updateable.values())}:this._data.url||this._data.geojson})}hasTransition(){return!1}}class Ar extends p.E{constructor(t,n,a,c){super(),this.flippedWindingOrder=!1,this.id=t,this.dispatcher=a,this.coordinates=n.coordinates,this.type="image",this.minzoom=0,this.maxzoom=22,this.tileSize=512,this.tiles={},this._loaded=!1,this.setEventedParent(c),this.options=n}load(t){return p._(this,void 0,void 0,(function*(){this._loaded=!1,this.fire(new p.n("dataloading",{dataType:"source"})),this.url=this.options.url,this._request=new AbortController;try{let n=yield Ii.getImage(yield this.map._requestManager.transformRequest(this.url,"Image"),this._request);this._request=null,this._loaded=!0,n?.data&&(this.image=n.data,t&&(this.coordinates=t),this._finishLoading())}catch(n){this._request=null,this._loaded=!0,p.$(n)||this.fire(new p.l(p.d(n)))}}))}loaded(){return this._loaded}updateImage(t){return t.url?(this._request&&(this._request.abort(),this._request=null),this.options.url=t.url,this.load(t.coordinates).finally((()=>this.texture=null)),this):this}_finishLoading(){this.map&&(this.setCoordinates(this.coordinates),this.fire(new p.n("data",{dataType:"source",sourceDataType:"metadata"})))}onAdd(t){this.map=t,this.load()}onRemove(){this._request&&(this._request.abort(),this._request=null)}setCoordinates(t){this.coordinates=t;let n=t.map(p.a7.fromLngLat);var a;return this.tileID=(function(c){let f=p.a8.fromPoints(c),y=f.width(),x=f.height(),w=Math.max(y,x),P=Math.max(0,Math.floor(-Math.log(w)/Math.LN2)),S=Math.pow(2,P);return new p.aa(P,Math.floor((f.minX+f.maxX)/2*S),Math.floor((f.minY+f.maxY)/2*S))})(n),this.terrainTileRanges=this._getOverlappingTileRanges(n),this.minzoom=this.maxzoom=this.tileID.z,this.tileCoords=n.map((c=>this.tileID.getTilePoint(c)._round())),this.flippedWindingOrder=((a=this.tileCoords)[1].x-a[0].x)*(a[2].y-a[0].y)-(a[1].y-a[0].y)*(a[2].x-a[0].x)<0,this.fire(new p.n("data",{dataType:"source",sourceDataType:"content"})),this}prepare(){if(Object.keys(this.tiles).length===0||!this.image)return;let t=this.map.painter.context,n=t.gl;this.texture||(this.texture=new p.T(t,this.image,n.RGBA),this.texture.bind(n.LINEAR,n.CLAMP_TO_EDGE));let a=!1;for(let c in this.tiles){let f=this.tiles[c];f.state!=="loaded"&&(f.state="loaded",f.texture=this.texture,a=!0)}a&&this.fire(new p.n("data",{dataType:"source",sourceDataType:"idle",sourceId:this.id}))}loadTile(t){return p._(this,void 0,void 0,(function*(){var n;!((n=this.tileID)===null||n===void 0)&&n.equals(t.tileID.canonical)?(this.tiles[String(t.tileID.wrap)]=t,t.buckets={}):t.state="errored"}))}serialize(){return{type:"image",url:this.options.url,coordinates:this.coordinates}}hasTransition(){return!1}_getOverlappingTileRanges(t){let{minX:n,minY:a,maxX:c,maxY:f}=p.a8.fromPoints(t),y={};for(let x=0;x<=p.a9;x++){let w=Math.pow(2,x),P=Math.floor(n*w),S=Math.floor(a*w),E=Math.floor(c*w),C=Math.floor(f*w),z=(P%w+w)%w,B=E%w,N=Math.floor(P/w),G=Math.floor(E/w);y[x]={minWrap:N,maxWrap:G,minTileXWrapped:z,maxTileXWrapped:B,minTileY:S,maxTileY:C}}return y}}class Qr extends Ar{constructor(t,n,a,c){super(t,n,a,c),this._onPlayingHandler=()=>{var f;(f=this.map)===null||f===void 0||f.triggerRepaint()},this.roundZoom=!0,this.type="video",this.options=n}load(){return p._(this,void 0,void 0,(function*(){this._loaded=!1;let t=this.options;this.urls=[];for(let n of t.urls)this.urls.push((yield this.map._requestManager.transformRequest(n,"Source")).url);try{let n=yield p.ab(this.urls);if(this._loaded=!0,!n)return;this.video=n,this.video.loop=!0,this.video.addEventListener("playing",this._onPlayingHandler),this.map&&this.video.play(),this._finishLoading()}catch(n){this.fire(new p.l(p.d(n)))}}))}pause(){this.video&&this.video.pause()}play(){this.video&&this.video.play()}seek(t){if(this.video){let n=this.video.seekable;tn.end(0)?this.fire(new p.l(new p.ac(`sources.${this.id}`,null,`Playback for this video can be set only between the ${n.start(0)} and ${n.end(0)}-second mark.`))):this.video.currentTime=t}}getVideo(){return this.video}onAdd(t){this.map||(this.map=t,this.load(),this.video&&(this.video.play(),this.setCoordinates(this.coordinates)))}onRemove(){super.onRemove(),this.video&&(this.video.removeEventListener("playing",this._onPlayingHandler),this.video.pause())}prepare(){if(Object.keys(this.tiles).length===0||this.video.readyState<2)return;let t=this.map.painter.context,n=t.gl;this.texture?this.video.paused||(this.texture.bind(n.LINEAR,n.CLAMP_TO_EDGE),n.texSubImage2D(n.TEXTURE_2D,0,0,0,n.RGBA,n.UNSIGNED_BYTE,this.video)):(this.texture=new p.T(t,this.video,n.RGBA),this.texture.bind(n.LINEAR,n.CLAMP_TO_EDGE));let a=!1;for(let c in this.tiles){let f=this.tiles[c];f.state!=="loaded"&&(f.state="loaded",f.texture=this.texture,a=!0)}a&&this.fire(new p.n("data",{dataType:"source",sourceDataType:"idle",sourceId:this.id}))}serialize(){return{type:"video",urls:this.urls,coordinates:this.coordinates}}hasTransition(){return this.video&&!this.video.paused}}class ka extends Ar{constructor(t,n,a,c){super(t,n,a,c),n.coordinates?Array.isArray(n.coordinates)&&n.coordinates.length===4&&!n.coordinates.some((f=>!Array.isArray(f)||f.length!==2||f.some((y=>typeof y!="number"))))||this.fire(new p.l(new p.ac(`sources.${t}`,null,'"coordinates" property must be an array of 4 longitude/latitude array pairs'))):this.fire(new p.l(new p.ac(`sources.${t}`,null,'missing required property "coordinates"'))),n.animate&&typeof n.animate!="boolean"&&this.fire(new p.l(new p.ac(`sources.${t}`,null,'optional "animate" property must be a boolean value'))),n.canvas?typeof n.canvas=="string"||n.canvas instanceof HTMLCanvasElement||this.fire(new p.l(new p.ac(`sources.${t}`,null,'"canvas" must be either a string representing the ID of the canvas element from which to read, or an HTMLCanvasElement instance'))):this.fire(new p.l(new p.ac(`sources.${t}`,null,'missing required property "canvas"'))),this.options=n,this.animate=n.animate===void 0||n.animate}load(){return p._(this,void 0,void 0,(function*(){this._loaded=!0,this.canvas||(this.canvas=this.options.canvas instanceof HTMLCanvasElement?this.options.canvas:document.getElementById(this.options.canvas)),this.width=this.canvas.width,this.height=this.canvas.height,this._hasInvalidDimensions()?this.fire(new p.l(new Error("Canvas dimensions cannot be less than or equal to zero."))):(this.play=function(){this._playing=!0,this.map.triggerRepaint()},this.pause=function(){this._playing&&(this.prepare(),this._playing=!1)},this._finishLoading())}))}getCanvas(){return this.canvas}onAdd(t){this.map=t,this.load(),this.canvas&&this.animate&&this.play()}onRemove(){this.pause()}prepare(){let t=!1;if(this.canvas.width!==this.width&&(this.width=this.canvas.width,t=!0),this.canvas.height!==this.height&&(this.height=this.canvas.height,t=!0),this._hasInvalidDimensions()||Object.keys(this.tiles).length===0)return;let n=this.map.painter.context,a=n.gl;this.texture?(t||this._playing)&&this.texture.update(this.canvas,{premultiply:!0}):(this.texture=new p.T(n,this.canvas,a.RGBA,{premultiply:!0}),this.texture.bind(a.LINEAR,a.CLAMP_TO_EDGE));let c=!1;for(let f in this.tiles){let y=this.tiles[f];y.state!=="loaded"&&(y.state="loaded",y.texture=this.texture,c=!0)}c&&this.fire(new p.n("data",{dataType:"source",sourceDataType:"idle",sourceId:this.id}))}serialize(){return{type:"canvas",animate:this.animate,canvas:this.options.canvas,coordinates:this.coordinates}}hasTransition(){return this._playing}_hasInvalidDimensions(){for(let t of[this.canvas.width,this.canvas.height])if(isNaN(t)||t<=0)return!0;return!1}}let La={},ds=u=>{switch(u){case"geojson":return us;case"image":return Ar;case"raster":return Mi;case"raster-dem":return Ht;case"vector":return Wt;case"video":return Qr;case"canvas":return ka}return La[u]},xo="RTLPluginLoaded";class rc extends p.E{constructor(){super(...arguments),this.status="unavailable",this.url=null,this.dispatcher=li()}_syncState(t){return this.status=t,this.dispatcher.broadcast("SRPS",{pluginStatus:t,pluginURL:this.url}).catch((n=>{throw this.status="error",n}))}getRTLTextPluginStatus(){return this.status}clearRTLTextPlugin(){this.status="unavailable",this.url=null}setRTLTextPlugin(t){return p._(this,arguments,void 0,(function*(n,a=!1){if(this.url)throw new Error("setRTLTextPlugin cannot be called multiple times.");if(this.url=qt.resolveURL(n),!this.url)throw new Error(`requested url ${n} is invalid`);if(this.status==="unavailable"){if(!a)return this._requestImport();this.status="deferred",this._syncState(this.status)}else if(this.status==="requested")return this._requestImport()}))}_requestImport(){return p._(this,void 0,void 0,(function*(){yield this._syncState("loading"),this.status="loaded",this.fire(new p.n(xo))}))}lazyLoad(){this.status==="unavailable"?this.status="requested":this.status==="deferred"&&this._requestImport()}}let ps=null;function Dr(){return ps||(ps=new rc),ps}var hr,Ni;(function(u){u[u.Base=0]="Base",u[u.Parent=1]="Parent"})(hr||(hr={})),(function(u){u[u.Departing=0]="Departing",u[u.Incoming=1]="Incoming"})(Ni||(Ni={}));class kn{constructor(t,n){this.timeAdded=0,this.fadeEndTime=0,this.fadeOpacity=1,this.tileID=t,this.uid=p.ad(),this.uses=0,this.tileSize=n,this.buckets={},this.expirationTime=null,this.queryPadding=0,this.hasSymbolBuckets=!1,this.hasRTLText=!1,this.dependencies={},this.rtt=[],this.rttFingerprint={},this.expiredRequestCount=0,this.state="loading"}isRenderable(t){return this.hasData()&&(!this.fadeEndTime||this.fadeOpacity>0)&&(t||!this.holdingForSymbolFade())}setCrossFadeLogic({fadingRole:t,fadingDirection:n,fadingParentID:a,fadeEndTime:c}){this.resetFadeLogic(),this.fadingRole=t,this.fadingDirection=n,this.fadingParentID=a,this.fadeEndTime=c}setSelfFadeLogic(t){this.resetFadeLogic(),this.selfFading=!0,this.fadeEndTime=t}resetFadeLogic(){this.fadingRole=null,this.fadingDirection=null,this.fadingParentID=null,this.selfFading=!1,this.timeAdded=Xe(),this.fadeEndTime=0,this.fadeOpacity=1}wasRequested(){return this.state==="errored"||this.state==="loaded"||this.state==="reloading"}clearTextures(t){this.demTexture&&t.saveTileTexture(this.demTexture),this.demTexture=null}loadVectorData(t,n,a){if(t?.etagUnmodified!==!0)if(this.hasData()&&this.unloadVectorData(),this.state="loaded",t){t.featureIndex&&(this.latestFeatureIndex=t.featureIndex,t.rawTileData?(this.latestRawTileData=t.rawTileData,this.latestEncoding=t.encoding,this.latestFeatureIndex.rawTileData=t.rawTileData,this.latestFeatureIndex.encoding=t.encoding):this.latestRawTileData&&(this.latestFeatureIndex.rawTileData=this.latestRawTileData,this.latestFeatureIndex.encoding=this.latestEncoding)),this.collisionBoxArray=t.collisionBoxArray,this.buckets=(function(c,f){let y={};if(!f)return y;for(let x of c){let w=x.layerIds.map((P=>f.getLayer(P))).filter(Boolean);if(w.length!==0){x.layers=w,x.stateDependentLayerIds&&(x.stateDependentLayers=x.stateDependentLayerIds.map((P=>w.filter((S=>S.id===P))[0])));for(let P of w)y[P.id]=x}}return y})(t.buckets,n?.style),this.hasSymbolBuckets=!1;for(let c in this.buckets){let f=this.buckets[c];if(f instanceof p.af){if(this.hasSymbolBuckets=!0,!a)break;f.justReloaded=!0}}if(this.hasRTLText=!1,this.hasSymbolBuckets)for(let c in this.buckets){let f=this.buckets[c];if(f instanceof p.af&&f.hasRTLText){this.hasRTLText=!0,Dr().lazyLoad();break}}this.queryPadding=0;for(let c in this.buckets){let f=this.buckets[c];this.queryPadding=Math.max(this.queryPadding,n.style.getLayer(c).queryRadius(f))}t.imageAtlas&&(this.imageAtlas=t.imageAtlas),t.glyphAtlasImage&&(this.glyphAtlasImage=t.glyphAtlasImage),this.dashPositions=t.dashPositions}else this.collisionBoxArray=new p.ae;else this.state="loaded"}unloadVectorData(){for(let t in this.buckets)this.buckets[t].destroy();this.buckets={},this.imageAtlasTexture&&this.imageAtlasTexture.destroy(),this.glyphAtlasTexture&&this.glyphAtlasTexture.destroy(),this.imageAtlas=null,this.dashPositions=null,this.latestFeatureIndex=null,this.state="unloaded"}getBucket(t){return this.buckets[t.id]}upload(t){for(let a in this.buckets){let c=this.buckets[a];c.uploadPending()&&c.upload(t)}let n=t.gl;this.imageAtlas&&!this.imageAtlas.uploaded&&(this.imageAtlasTexture=new p.T(t,this.imageAtlas.image,n.RGBA),this.imageAtlas.uploaded=!0),this.glyphAtlasImage&&(this.glyphAtlasTexture=new p.T(t,this.glyphAtlasImage,n.ALPHA),this.glyphAtlasImage=null)}prepare(t){this.imageAtlas&&this.imageAtlas.patchUpdatedImages(t,this.imageAtlasTexture)}queryRenderedFeatures(t,n,a,c,f,y,x,w,P,S,E){var C;return!((C=this.latestFeatureIndex)===null||C===void 0)&&C.rawTileData?this.latestFeatureIndex.query({queryGeometry:c,cameraQueryGeometry:f,scale:y,tileSize:this.tileSize,pixelPosMatrix:S,transform:w,params:x,queryPadding:this.queryPadding*P,getElevation:E},t,n,a):{}}querySourceFeatures(t,n){let a=this.latestFeatureIndex;if(!a?.rawTileData)return;let c=a.loadVTLayers(),f=n?.sourceLayer?n.sourceLayer:"",y=c[p.ag]||c[f];if(!y)return;let x=p.ah(n?.filter,n?.globalState),{z:w,x:P,y:S}=this.tileID.canonical,E={z:w,x:P,y:S};for(let C=0;Ca)c=!1;else if(n)if(this.expirationTime({zoom:0,x:0,y:0,wrap:U,fullyVisible:!1}),X=[],Z=[];if(u.renderWorldCopies&&y.allowWorldCopies())for(let U=1;U<=3;U++)X.push($(-U)),X.push($(U));for(X.push($(0));X.length>0;){let U=X.pop(),H=U.x,q=U.y,Q=U.fullyVisible,oe={x:H,y:q,z:U.zoom},se=y.getTileBoundingVolume(oe,U.wrap,u.elevation,t);if(!Q){let ve=ce(n,se,a);if(ve===0)continue;Q=ve===2}let de=y.distanceToTile2d(c.x,c.y,oe,se),ue=w;x&&(ue=(t.calculateTileZoom||it)(u.zoom+p.ar(u.tileSize/t.tileSize),de,G,j,u.fov)),ue=(t.roundZoom?Math.round:Math.floor)(ue),ue=Math.max(0,ue);let Se=Math.min(ue,S);if(U.wrap=y.getWrap(f,oe,U.wrap),U.zoom>=Se){if(U.zoom>1),wrap:U.wrap,fullyVisible:Q})}return Z.sort(((U,H)=>U.distanceSq-H.distanceSq)).map((U=>U.tileID))}let nc=p.a8.fromPoints([new p.P(0,0),new p.P(p.a6,p.a6)]);function oc(u){return u==="raster"||u==="image"||u==="video"}function Fh(u,t,n,a,c,f,y){if(!t.hasData())return!1;let{tileID:x,fadingRole:w,fadingDirection:P,fadingParentID:S}=t;if(w===hr.Base&&P===Ni.Incoming&&S)return n[S.key]=S,!0;let E=Math.max(x.overscaledZ-c,f);for(let C=x.overscaledZ-1;C>=E;C--){let z=x.scaledTo(C),B=u.getLoadedTile(z);if(B)return t.setCrossFadeLogic({fadingRole:hr.Base,fadingDirection:Ni.Incoming,fadingParentID:B.tileID,fadeEndTime:a+y}),B.setCrossFadeLogic({fadingRole:hr.Parent,fadingDirection:Ni.Departing,fadeEndTime:a+y}),n[z.key]=z,!0}return!1}function ms(u,t,n,a,c,f){if(!t.hasData())return!1;let y=t.tileID.children(c),x=Na(u,t,y,n,a,c,f);if(x)return!0;for(let w of y)Na(u,t,w.children(c),n,a,c,f)&&(x=!0);return x}function Na(u,t,n,a,c,f,y){if(n[0].overscaledZ>=f)return!1;let x=!1;for(let w of n){let P=u.getLoadedTile(w);if(!P)continue;let{fadingRole:S,fadingDirection:E,fadingParentID:C}=P;S===hr.Base&&E===Ni.Departing&&C||(P.setCrossFadeLogic({fadingRole:hr.Base,fadingDirection:Ni.Departing,fadingParentID:t.tileID,fadeEndTime:c+y}),t.setCrossFadeLogic({fadingRole:hr.Parent,fadingDirection:Ni.Incoming,fadeEndTime:c+y})),a[w.key]=w,x=!0}return x}function sc(u,t,n,a){let c=u.tileID;return!!u.selfFading||!u.hasData()&&!!t.has(c)&&(u.setSelfFadeLogic(n+a),!0)}function _e(u,t){var n;u.needsHillshadePrepare=!0,u.needsTerrainPrepare=!0;let a=t.tileID.canonical.x-u.tileID.canonical.x,c=t.tileID.canonical.y-u.tileID.canonical.y,f=Math.pow(2,u.tileID.canonical.z),y=t.tileID.key;a===0&&c===0||Math.abs(c)>1||(Math.abs(a)>1&&(Math.abs(a+f)===1?a+=f:Math.abs(a-f)===1&&(a-=f)),t.dem&&u.dem&&(u.dem.backfillBorder(t.dem,a,c),!((n=u.neighboringTiles)===null||n===void 0)&&n[y]&&(u.neighboringTiles[y].backfilled=!0)))}class nn{constructor(){this._tiles={}}handleWrapJump(t){let n={};for(let a in this._tiles){let c=this._tiles[a];c.tileID=c.tileID.unwrapTo(c.tileID.wrap+t),n[c.tileID.key]=c}this._tiles=n}setFeatureState(t,n){for(let a in this._tiles)this._tiles[a].setFeatureState(t,n)}getAllTiles(){return Object.values(this._tiles)}getAllIds(t=!1){return t?Object.values(this._tiles).map((n=>n.tileID)).sort(p.au).map((n=>n.key)):Object.keys(this._tiles)}getTileById(t){return this._tiles[t]}setTile(t,n){this._tiles[t]=n}deleteTileById(t){delete this._tiles[t]}getLoadedTile(t){let n=this.getTileById(t.key);return n?.hasData()?n:null}isIdRenderable(t,n=!1){var a;return(a=this.getTileById(t))===null||a===void 0?void 0:a.isRenderable(n)}getRenderableIds(t=0,n){let a=[];for(let c of this.getAllIds())this.isIdRenderable(c,n)&&a.push(this.getTileById(c));return n?a.sort(((c,f)=>{let y=c.tileID,x=f.tileID,w=new p.P(y.canonical.x,y.canonical.y)._rotate(-t),P=new p.P(x.canonical.x,x.canonical.y)._rotate(-t);return y.overscaledZ-x.overscaledZ||P.y-w.y||P.x-w.x})).map((c=>c.tileID.key)):a.map((c=>c.tileID)).sort(p.au).map((c=>c.key))}}class Xt extends p.E{constructor(t,n,a){super(),this.id=t,this.dispatcher=a,this.on("data",(c=>{this._dataHandler(c)})),this.on("dataloading",(()=>{this._sourceErrored=!1})),this.on("error",(()=>{this._sourceErrored=this._source.loaded()})),this._source=((c,f,y,x)=>{let w=new(ds(f.type))(c,f,y,x);if(w.id!==c)throw new Error(`Expected Source id to be ${c} instead of ${w.id}`);return w})(t,n,a,this),this._inViewTiles=new nn,this._outOfViewCache=new p.av(0,(c=>this._unloadTile(c))),this._timers={},this._maxTileCacheSize=null,this._maxTileCacheZoomLevels=null,this._rasterFadeDuration=0,this._maxFadingAncestorLevels=5,this._state=new Fa,this._didEmitContent=!1,this._updated=!1}onAdd(t){var n;this.map=t,this._maxTileCacheSize=t?t._maxTileCacheSize:null,this._maxTileCacheZoomLevels=t?t._maxTileCacheZoomLevels:null,!((n=this._source)===null||n===void 0)&&n.onAdd&&this._source.onAdd(t)}onRemove(t){var n;for(let a of this._inViewTiles.getAllTiles())a.unloadVectorData();this.clearTiles(),!((n=this._source)===null||n===void 0)&&n.onRemove&&this._source.onRemove(t),this._inViewTiles=new nn}loaded(){if(this._sourceErrored)return!0;if(!this._sourceLoaded||!this._source.loaded())return!1;if(!(this.used===void 0&&this.usedForTerrain===void 0||this.used||this.usedForTerrain))return!0;if(!this._updated)return!1;for(let t of this._inViewTiles.getAllTiles())if(t.state!=="loaded"&&t.state!=="errored")return!1;return!0}getSource(){return this._source}getState(){return this._state}pause(){this._paused=!0}resume(){if(!this._paused)return;let t=this._shouldReloadOnResume;this._paused=!1,this._shouldReloadOnResume=!1,t&&this.reload(),this.transform&&this.update(this.transform,this.terrain)}_loadTile(t,n,a){return p._(this,void 0,void 0,(function*(){try{let c=yield this._source.loadTile(t);this._tileLoaded(t,n,a,c)}catch(c){t.state="errored",c.status!==404?this._source.fire(new p.l(p.d(c),{tile:t})):this.update(this.transform,this.terrain)}}))}_unloadTile(t){this._source.unloadTile&&this._source.unloadTile(t)}_abortTile(t){this._source.abortTile&&this._source.abortTile(t),this._source.fire(new p.n("dataabort",{tile:t,coord:t.tileID,dataType:"source"}))}serialize(){return this._source.serialize()}prepare(t){this._source.prepare&&this._source.prepare(),this._state.coalesceChanges(this._inViewTiles,this.map?this.map.painter:null);for(let n of this._inViewTiles.getAllTiles())n.upload(t),n.prepare(this.map.style.imageManager)}getIds(){return this._inViewTiles.getAllIds(!0)}getRenderableIds(t){var n;return this._inViewTiles.getRenderableIds((n=this.transform)===null||n===void 0?void 0:n.bearingInRadians,t)}hasRenderableParent(t){let n=t.overscaledZ-1;if(n>=this._source.minzoom){let a=this.getLoadedTile(t.scaledTo(n));if(a)return this._inViewTiles.isIdRenderable(a.tileID.key)}return!1}reload(t,n=void 0){if(this._paused)this._shouldReloadOnResume=!0;else{this._outOfViewCache.reset();for(let a of this._inViewTiles.getAllIds()){let c=this._inViewTiles.getTileById(a);n&&!this._source.shouldReloadTile(c,n)||(t?this._reloadTile(a,"expired"):c.state!=="errored"&&this._reloadTile(a,"reloading"))}}}_reloadTile(t,n){return p._(this,void 0,void 0,(function*(){let a=this._inViewTiles.getTileById(t);a&&(a.state!=="loading"&&(a.state=n),yield this._loadTile(a,t,n))}))}_tileLoaded(t,n,a,c){t.timeAdded=Xe(),t.selfFading&&(t.fadeEndTime=t.timeAdded+this._rasterFadeDuration),a==="expired"&&(t.refreshedUponExpiration=!0),this._setTileReloadTimer(n,t),c?.unmodified||(this.getSource().type==="raster-dem"&&t.dem&&(function(f,y){var x,w,P;let S=y.getRenderableIds();for(let E of S){if(!(!((x=f.neighboringTiles)===null||x===void 0)&&x[E]))continue;let C=y.getTileById(E);f.neighboringTiles[E].backfilled||_e(f,C),!((P=(w=C.neighboringTiles)===null||w===void 0?void 0:w[f.tileID.key])===null||P===void 0)&&P.backfilled||_e(C,f)}})(t,this._inViewTiles),this._state.initializeTileState(t,this.map?this.map.painter:null),t.aborted||this._source.fire(new p.n("data",{dataType:"source",tile:t,coord:t.tileID})))}getTile(t){return this.getTileByID(t.key)}getTileByID(t){return this._inViewTiles.getTileById(t)}_retainLoadedChildren(t,n){let a=this._getLoadedDescendents(n),c=new Set;for(let f of n){let y=a[f.key];if(!y?.length){c.add(f);continue}let x=f.overscaledZ+Xt.maxOverzooming,w=y.filter((E=>E.tileID.overscaledZ<=x));if(!w.length){c.add(f);continue}let P=Math.min(...w.map((E=>E.tileID.overscaledZ))),S=w.filter((E=>E.tileID.overscaledZ===P)).map((E=>E.tileID));for(let E of S)t[E.key]=E;this._areDescendentsComplete(S,P,f.overscaledZ)||c.add(f)}return c}_getLoadedDescendents(t){var n;let a={};for(let c of this._inViewTiles.getAllTiles().filter((f=>f.hasData())))for(let f of t)c.tileID.isChildOf(f)&&(a[n=f.key]||(a[n]=[]),a[f.key].push(c));return a}_areDescendentsComplete(t,n,a){return t.length===1&&t[0].isOverscaled()?t[0].overscaledZ===n:Math.pow(4,n-a)===t.length}getLoadedTile(t){return this._inViewTiles.getLoadedTile(t)}updateCacheSize(t){let n=Math.ceil(t.width/this._source.tileSize)+1,a=Math.ceil(t.height/this._source.tileSize)+1,c=Math.floor(n*a*(this._maxTileCacheZoomLevels===null?p.c.MAX_TILE_CACHE_ZOOM_LEVELS:this._maxTileCacheZoomLevels)),f=typeof this._maxTileCacheSize=="number"?Math.min(this._maxTileCacheSize,c):c;this._outOfViewCache.setMaxSize(f)}handleWrapJump(t){let n=Math.round((t-(this._prevLng===void 0?t:this._prevLng))/360);this._prevLng=t,n&&(this._inViewTiles.handleWrapJump(n),this._resetTileReloadTimers())}update(t,n){if(!this._sourceLoaded||this._paused)return;let a;this.transform=t,this.terrain=n,this.updateCacheSize(t),this.handleWrapJump(this.transform.center.lng),this.used||this.usedForTerrain?this._source.tileID?a=t.getVisibleUnwrappedCoordinates(this._source.tileID).map((w=>new p.a3(w.canonical.z,w.wrap,w.canonical.z,w.canonical.x,w.canonical.y))):(a=rn(t,{tileSize:this.usedForTerrain?this.tileSize:this._source.tileSize,minzoom:this._source.minzoom,maxzoom:this._source.type==="vector"&&this.map._zoomLevelsToOverscale!==void 0?t.maxZoom-this.map._zoomLevelsToOverscale:this._source.maxzoom,roundZoom:!this.usedForTerrain&&this._source.roundZoom,reparseOverscaled:this._source.reparseOverscaled,terrain:n,calculateTileZoom:this._source.calculateTileZoom}),this._source.hasTile&&(a=a.filter((w=>this._source.hasTile(w))))):a=[],this.usedForTerrain&&(a=this._addTerrainIdealTiles(a));let c=a.length===0&&!this._updated&&this._didEmitContent;this._updated=!0,c&&this.fire(new p.n("data",{sourceDataType:"idle",dataType:"source",sourceId:this.id}));let f=vi(t,this._source),y=this._updateRetainedTiles(a,f),x=oc(this._source.type);x&&this._rasterFadeDuration>0&&!n&&(function(w,P,S,E,C,z,B){let N=Xe(),G=p.at(P);for(let j of P){let $=w.getTileById(j.key);$.fadingDirection!==Ni.Departing&&$.fadeOpacity!==0||$.resetFadeLogic(),Fh(w,$,S,N,E,C,B)||ms(w,$,S,N,z,B)||sc($,G,N,B)||$.resetFadeLogic()}})(this._inViewTiles,a,y,this._maxFadingAncestorLevels,this._source.minzoom,this._source.maxzoom,this._rasterFadeDuration),x?this._cleanUpRasterTiles(y):this._cleanUpVectorTiles(y)}_cleanUpRasterTiles(t){for(let n of this._inViewTiles.getAllIds())t[n]||this._removeTile(n)}_cleanUpVectorTiles(t){for(let n of this._inViewTiles.getAllIds()){let a=this._inViewTiles.getTileById(n);t[n]?a.clearSymbolFadeHold():a.hasSymbolBuckets?a.holdingForSymbolFade()?a.symbolFadeFinished()&&this._removeTile(n):a.setSymbolHoldDuration(this.map._fadeDuration):this._removeTile(n)}}_addTerrainIdealTiles(t){let n=[];for(let a of t)if(a.canonical.z>this._source.minzoom){let c=a.scaledTo(a.canonical.z-1);n.push(c);let f=a.scaledTo(Math.max(this._source.minzoom,Math.min(a.canonical.z,5)));n.push(f)}return t.concat(n)}releaseSymbolFadeTiles(){for(let t of this._inViewTiles.getAllIds())this._inViewTiles.getTileById(t).holdingForSymbolFade()&&this._removeTile(t)}_updateRetainedTiles(t,n){var a;let c=new Set;for(let P of t)this._addTile(P).hasData()||c.add(P);let f=t.reduce(((P,S)=>(P[S.key]=S,P)),{}),y=this._retainLoadedChildren(f,c),x={},w=Math.max(n-Xt.maxUnderzooming,this._source.minzoom);for(let P of y){let S=this._inViewTiles.getTileById(P.key),E=S?.wasRequested();for(let C=P.overscaledZ-1;C>=w;--C){let z=P.scaledTo(C);if(x[z.key])break;if(x[z.key]=!0,S=this.getTile(z),!S&&E&&(S=this._addTile(z)),S){let B=S.hasData();if((B||!(!((a=this.map)===null||a===void 0)&&a.cancelPendingTileRequestsWhileZooming)||E)&&(f[z.key]=z),E=S.wasRequested(),B)break}}}return f}_addTile(t){let n=this._inViewTiles.getTileById(t.key);if(n)return n;n=this._outOfViewCache.getAndRemove(t),n&&(n.resetFadeLogic(),this._setTileReloadTimer(t.key,n),n.tileID=t,this._state.initializeTileState(n,this.map?this.map.painter:null));let a=n;return n||(n=new kn(t,this._source.tileSize*t.overscaleFactor()),this._loadTile(n,t.key,n.state)),n.uses++,this._inViewTiles.setTile(t.key,n),a||this._source.fire(new p.n("dataloading",{tile:n,coord:n.tileID,dataType:"source"})),n}_setTileReloadTimer(t,n){this._clearTileReloadTimer(t);let a=n.getExpiryTimeout();a&&(this._timers[t]=setTimeout((()=>{this._reloadTile(t,"expired"),delete this._timers[t]}),a))}_clearTileReloadTimer(t){let n=this._timers[t];n&&(clearTimeout(n),delete this._timers[t])}_resetTileReloadTimers(){for(let t in this._timers)clearTimeout(this._timers[t]),delete this._timers[t];for(let t of this._inViewTiles.getAllIds()){let n=this._inViewTiles.getTileById(t);this._setTileReloadTimer(t,n)}}refreshTiles(t){for(let n of this._inViewTiles.getAllIds()){let a=this._inViewTiles.getTileById(n);(this._inViewTiles.isIdRenderable(n)||a.state=="errored")&&t.some((c=>c.equals(a.tileID.canonical)))&&this._reloadTile(n,"expired")}}_removeTile(t){let n=this._inViewTiles.getTileById(t);n&&(n.uses--,this._inViewTiles.deleteTileById(t),this._clearTileReloadTimer(t),n.uses>0||(n.hasData()&&n.state!=="reloading"?this._outOfViewCache.add(n.tileID,n,n.getExpiryTimeout()):(n.aborted=!0,this._abortTile(n),this._unloadTile(n))))}_dataHandler(t){t.dataType==="source"&&(t.sourceDataType!=="metadata"?t.sourceDataType==="content"&&this._sourceLoaded&&!this._paused&&(this.reload(t.sourceDataChanged,t.shouldReloadTileOptions),this.transform&&this.update(this.transform,this.terrain),this._didEmitContent=!0):this._sourceLoaded=!0)}clearTiles(){this._shouldReloadOnResume=!1,this._paused=!1;for(let t of this._inViewTiles.getAllIds())this._removeTile(t);this._outOfViewCache.reset()}tilesIn(t,n,a){let c=[],f=this.transform;if(!f)return c;let y=f.getCoveringTilesDetailsProvider().allowWorldCopies(),x=a?f.getCameraQueryGeometry(t):t,w=z=>f.screenPointToMercatorCoordinate(z,this.terrain),P=this.transformBbox(t,w,!y),S=this.transformBbox(x,w,!y),E=this.getIds(),C=p.a8.fromPoints(S);for(let z of E){let B=this._inViewTiles.getTileById(z);if(B.holdingForSymbolFade())continue;let N=y?[B.tileID]:[B.tileID.unwrapTo(-1),B.tileID.unwrapTo(0)],G=Math.pow(2,f.zoom-B.tileID.overscaledZ),j=n*B.queryPadding*p.a6/B.tileSize/G;for(let $ of N){let X=C.map((Z=>$.getTilePoint(new p.a7(Z.x,Z.y))));if(X.expandBy(j),X.intersects(nc)){let Z=P.map((H=>$.getTilePoint(H))),U=S.map((H=>$.getTilePoint(H)));c.push({tile:B,tileID:y?$:$.unwrapTo(0),queryGeometry:Z,cameraQueryGeometry:U,scale:G})}}}return c}transformBbox(t,n,a){let c=t.map(n);if(a){let f=p.a8.fromPoints(t);f.shrinkBy(.001*Math.min(f.width(),f.height()));let y=f.map(n);p.a8.fromPoints(c).covers(y)||(c=c.map((x=>x.x>.5?new p.a7(x.x-1,x.y,x.z):x)))}return c}getVisibleCoordinates(t){let n=this.getRenderableIds(t).map((a=>this._inViewTiles.getTileById(a).tileID));return this.transform&&this.transform.populateCache(n),n}hasTransition(){return!!this._source.hasTransition()||oc(this._source.type)&&(function(t,n){if(n<=0)return!1;let a=Xe();for(let c of t.getAllTiles())if(c.fadeEndTime>=a)return!0;return!1})(this._inViewTiles,this._rasterFadeDuration)}setRasterFadeDuration(t){this._rasterFadeDuration=t}setFeatureState(t,n,a){t||(t=p.ag),this._state.updateState(t,n,a)}removeFeatureState(t,n,a){t||(t=p.ag),this._state.removeFeatureState(t,n,a)}getFeatureState(t,n){return t||(t=p.ag),this._state.getState(t,n)}setDependencies(t,n,a){let c=this._inViewTiles.getTileById(t);c&&c.setDependencies(n,a)}reloadTilesForDependencies(t,n){for(let a of this._inViewTiles.getAllIds())this._inViewTiles.getTileById(a).hasDependency(t,n)&&this._reloadTile(a,"reloading");this._outOfViewCache.filter((a=>!a.hasDependency(t,n)))}areTilesLoaded(){for(let t of this._inViewTiles.getAllTiles())if(t.state!=="loaded"&&t.state!=="errored")return!1;return!0}}Xt.maxUnderzooming=10,Xt.maxOverzooming=3;class Va{constructor(t,n){this.reset(t,n)}reset(t,n){this.points=t||[],this._distances=[0];for(let a=1;a0?(c-y)/x:0;return this.points[f].mult(1-w).add(this.points[n].mult(w))}}function zr(u,t){let n=!0;return u==="always"||u!=="never"&&t!=="never"||(n=!1),n}class be{constructor(t,n,a){let c=this.boxCells=[],f=this.circleCells=[];this.xCellCount=Math.ceil(t/a),this.yCellCount=Math.ceil(n/a);for(let y=0;ythis.width||c<0||n>this.height)return[];let w=[];if(t<=0&&n<=0&&this.width<=a&&this.height<=c){if(f)return[{key:null,x1:t,y1:n,x2:a,y2:c}];for(let P=0;P0}hitTestCircle(t,n,a,c,f){let y=t-a,x=t+a,w=n-a,P=n+a;if(x<0||y>this.width||P<0||w>this.height)return!1;let S=[];return this._forEachCell(y,w,x,P,this._queryCellCircle,S,{hitTest:!0,overlapMode:c,circle:{x:t,y:n,radius:a},seenUids:{box:{},circle:{}}},f),S.length>0}_queryCell(t,n,a,c,f,y,x,w){let{seenUids:P,hitTest:S,overlapMode:E}=x,C=this.boxCells[f],z=1e-6;if(C!==null){let N=this.bboxes;for(let G of C)if(!P.box[G]){P.box[G]=!0;let j=4*G,$=this.boxKeys[G];if(t<=N[j+2]+z&&n<=N[j+3]+z&&a>=N[j+0]-z&&c>=N[j+1]-z&&(!w||w($))&&(!S||!zr(E,$.overlapMode))&&(y.push({key:$,x1:N[j],y1:N[j+1],x2:N[j+2],y2:N[j+3]}),S))return!0}}let B=this.circleCells[f];if(B!==null){let N=this.circles;for(let G of B)if(!P.circle[G]){P.circle[G]=!0;let j=3*G,$=this.circleKeys[G];if(this._circleAndRectCollide(N[j],N[j+1],N[j+2],t,n,a,c)&&(!w||w($))&&(!S||!zr(E,$.overlapMode))){let X=N[j],Z=N[j+1],U=N[j+2];if(y.push({key:$,x1:X-U,y1:Z-U,x2:X+U,y2:Z+U}),S)return!0}}}return!1}_queryCellCircle(t,n,a,c,f,y,x,w){let{circle:P,seenUids:S,overlapMode:E}=x,C=this.boxCells[f];if(C!==null){let B=this.bboxes;for(let N of C)if(!S.box[N]){S.box[N]=!0;let G=4*N,j=this.boxKeys[N];if(this._circleAndRectCollide(P.x,P.y,P.radius,B[G+0],B[G+1],B[G+2],B[G+3])&&(!w||w(j))&&!zr(E,j.overlapMode))return y.push(!0),!0}}let z=this.circleCells[f];if(z!==null){let B=this.circles;for(let N of z)if(!S.circle[N]){S.circle[N]=!0;let G=3*N,j=this.circleKeys[N];if(this._circlesCollide(B[G],B[G+1],B[G+2],P.x,P.y,P.radius)&&(!w||w(j))&&!zr(E,j.overlapMode))return y.push(!0),!0}}}_forEachCell(t,n,a,c,f,y,x,w){let P=this._convertToXCellCoord(t),S=this._convertToYCellCoord(n),E=this._convertToXCellCoord(a),C=this._convertToYCellCoord(c);for(let z=P;z<=E;z++)for(let B=S;B<=C;B++)if(f.call(this,t,n,a,c,this.xCellCount*B+z,y,x,w))return}_convertToXCellCoord(t){return Math.max(0,Math.min(this.xCellCount-1,Math.floor(t*this.xScale)))}_convertToYCellCoord(t){return Math.max(0,Math.min(this.yCellCount-1,Math.floor(t*this.yScale)))}_circlesCollide(t,n,a,c,f,y){let x=c-t,w=f-n,P=a+y;return P*P>x*x+w*w}_circleAndRectCollide(t,n,a,c,f,y,x){let w=(y-c)/2,P=Math.abs(t-(c+w));if(P>w+a)return!1;let S=(x-f)/2,E=Math.abs(n-(f+S));if(E>S+a)return!1;if(P<=w||E<=S)return!0;let C=P-w,z=E-S;return C*C+z*z<=a*a}}function Fe(u,t){let n=1/(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]),a=1/(t[8]*t[8]+t[9]*t[9]+t[10]*t[10]),c=t[0]*n,f=t[4]*n,y=t[8]*a,x=t[1]*n,w=t[5]*n,P=t[9]*a,S=t[2]*n,E=t[6]*n,C=t[10]*a;u[0]=c,u[1]=f,u[2]=y,u[4]=x,u[5]=w,u[6]=P,u[8]=S,u[9]=E,u[10]=C;let z=t[12],B=t[13],N=t[14];return u[12]=-c*z-x*B-S*N,u[13]=-f*z-w*B-E*N,u[14]=-y*z-P*B-C*N,u[3]=0,u[7]=0,u[11]=0,u[15]=1,u}let je=p.O();function Ei(u,t,n){let a=p.O();if(!u){let{vecSouth:E,vecEast:C}=ur(t),z=Sr();z[0]=C[0],z[1]=C[1],z[2]=E[0],z[3]=E[1],c=z,(S=(y=(f=z)[0])*(P=f[3])-(w=f[2])*(x=f[1]))&&(c[0]=P*(S=1/S),c[1]=-x*S,c[2]=-w*S,c[3]=y*S),a[0]=z[0],a[1]=z[1],a[4]=z[2],a[5]=z[3]}var c,f,y,x,w,P,S;return p.S(a,a,[1/n,1/n,1]),a}function gs(u,t,n,a){if(u){let c=p.O();if(!t){let{vecSouth:f,vecEast:y}=ur(n);c[0]=y[0],c[1]=y[1],c[4]=f[0],c[5]=f[1]}return p.S(c,c,[a,a,1]),c}return n.pixelsToClipSpaceMatrix}function ur(u){let t=Math.cos(u.rollInRadians),n=Math.sin(u.rollInRadians),a=Math.cos(u.pitchInRadians),c=Math.cos(u.bearingInRadians),f=Math.sin(u.bearingInRadians),y=p.az();y[0]=-c*a*n-f*t,y[1]=-f*a*n+c*t;let x=p.aA(y);x<1e-9?p.aB(y):p.aC(y,y,1/x);let w=p.az();w[0]=c*a*t-f*n,w[1]=f*a*t+c*n;let P=p.aA(w);return P<1e-9?p.aB(w):p.aC(w,w,1/P),{vecEast:w,vecSouth:y}}function Oe(u,t,n,a){let c;a?(c=[u,t,a(u,t),1],p.aE(c,c,n)):(c=[u,t,0,1],vs(c,c,n));let f=c[3];return{point:new p.P(c[0]/f,c[1]/f),signedDistanceFromCamera:f,isOccluded:!1}}function wo(u,t){return .5+u/t*.5}function To(u,t){return u.x>=-t[0]&&u.x<=t[0]&&u.y>=-t[1]&&u.y<=t[1]}function _s(u,t,n,a,c,f,y,x,w,P,S,E,C){let z=n?u.textSizeData:u.iconSizeData,B=p.aw(z,t.transform.zoom),N=[256/t.width*2+1,256/t.height*2+1],G=n?u.text.dynamicLayoutVertexArray:u.icon.dynamicLayoutVertexArray;G.clear();let j=u.lineVertexArray,$=n?u.text.placedSymbolArray:u.icon.placedSymbolArray,X=t.transform.width/t.transform.height,Z=!1;for(let U=0;U<$.length;U++){let H=$.get(U);if(H.hidden||H.writingMode===p.ax.vertical&&!Z){sn(H.numGlyphs,G);continue}Z=!1;let q=new p.P(H.anchorX,H.anchorY),Q={getElevation:C,pitchedLabelPlaneMatrix:a,lineVertexArray:j,pitchWithMap:f,projectionCache:{projections:{},offsets:{},cachedAnchorPoint:void 0,anyProjectionOccluded:!1},transform:t.transform,tileAnchorPoint:q,unwrappedTileID:w,width:P,height:S,translation:E},oe=Nn(H.anchorX,H.anchorY,Q);if(!To(oe.point,N)){sn(H.numGlyphs,G);continue}let se=wo(t.transform.cameraToCenterDistance,oe.signedDistanceFromCamera),de=p.ay(z,B,H),ue=f?de*t.transform.getPitchedTextCorrection(H.anchorX,H.anchorY,w)/se:de*se,Se=On({projectionContext:Q,pitchedLabelPlaneMatrixInverse:c,symbol:H,fontSize:ue,flip:!1,keepUpright:y,glyphOffsetArray:u.glyphOffsetArray,dynamicLayoutVertexArray:G,aspectRatio:X,rotateToLine:x});Z=Se.useVertical,(Se.notEnoughRoom||Z||Se.needsFlipping&&On({projectionContext:Q,pitchedLabelPlaneMatrixInverse:c,symbol:H,fontSize:ue,flip:!0,keepUpright:y,glyphOffsetArray:u.glyphOffsetArray,dynamicLayoutVertexArray:G,aspectRatio:X,rotateToLine:x}).notEnoughRoom)&&sn(H.numGlyphs,G)}n?u.text.dynamicLayoutVertexBuffer.updateData(G):u.icon.dynamicLayoutVertexBuffer.updateData(G)}function Bn(u,t,n,a,c,f,y,x){let w=f.glyphStartIndex+f.numGlyphs,P=f.lineStartIndex,S=f.lineStartIndex+f.lineLength,E=t.getoffsetX(f.glyphStartIndex),C=t.getoffsetX(w-1),z=Xi(u*E,n,a,c,f.segment,P,S,x,y);if(!z)return null;let B=Xi(u*C,n,a,c,f.segment,P,S,x,y);return B?x.projectionCache.anyProjectionOccluded?null:{first:z,last:B}:null}function Po(u,t,n,a){return u===p.ax.horizontal&&Math.abs(n.y-t.y)>Math.abs(n.x-t.x)*a?{useVertical:!0}:(u===p.ax.vertical?t.yn.x)?{needsFlipping:!0}:null}function On(u){let{projectionContext:t,pitchedLabelPlaneMatrixInverse:n,symbol:a,fontSize:c,flip:f,keepUpright:y,glyphOffsetArray:x,dynamicLayoutVertexArray:w,aspectRatio:P,rotateToLine:S}=u,E=c/24,C=a.lineOffsetX*E,z=a.lineOffsetY*E,B;if(a.numGlyphs>1){let N=a.glyphStartIndex+a.numGlyphs,G=a.lineStartIndex,j=a.lineStartIndex+a.lineLength,$=Bn(E,x,C,z,f,a,S,t);if(!$)return{notEnoughRoom:!0};let X=ys($.first.point.x,$.first.point.y,t,n),Z=ys($.last.point.x,$.last.point.y,t,n);if(y&&!f){let U=Po(a.writingMode,X,Z,P);if(U)return U}B=[$.first];for(let U=a.glyphStartIndex+1;U0?X.point:So(t.tileAnchorPoint,$,G,1,t),U=ys(G.x,G.y,t,n),H=ys(Z.x,Z.y,t,n),q=Po(a.writingMode,U,H,P);if(q)return q}let N=Xi(E*x.getoffsetX(a.glyphStartIndex),C,z,f,a.segment,a.lineStartIndex,a.lineStartIndex+a.lineLength,t,S);if(!N||t.projectionCache.anyProjectionOccluded)return{notEnoughRoom:!0};B=[N]}for(let N of B)p.aD(w,N.point,N.angle);return{}}function So(u,t,n,a,c){let f=u.add(u.sub(t)._unit()),y=rt(f.x,f.y,c).point,x=n.sub(y);return n.add(x._mult(a/x.mag()))}function Yt(u,t,n){let a=t.projectionCache;if(a.projections[u])return a.projections[u];let c=new p.P(t.lineVertexArray.getx(u),t.lineVertexArray.gety(u)),f=rt(c.x,c.y,t);if(f.signedDistanceFromCamera>0)return a.projections[u]=f.point,a.anyProjectionOccluded||(a.anyProjectionOccluded=f.isOccluded),f.point;let y=u-n.direction;return So(n.distanceFromAnchor===0?t.tileAnchorPoint:new p.P(t.lineVertexArray.getx(y),t.lineVertexArray.gety(y)),c,n.previousVertex,n.absOffsetX-n.distanceFromAnchor+1,t)}function rt(u,t,n){let a=u+n.translation[0],c=t+n.translation[1],f;return n.pitchWithMap?(f=Oe(a,c,n.pitchedLabelPlaneMatrix,n.getElevation),f.isOccluded=!1):(f=n.transform.projectTileCoordinates(a,c,n.unwrappedTileID,n.getElevation),f.point.x=(.5*f.point.x+.5)*n.width,f.point.y=(.5*-f.point.y+.5)*n.height),f}function ys(u,t,n,a){if(n.pitchWithMap){let c=[u,t,0,1];return p.aE(c,c,a),n.transform.projectTileCoordinates(c[0]/c[3],c[1]/c[3],n.unwrappedTileID,n.getElevation).point}return{x:u/n.width*2-1,y:1-t/n.height*2}}function Nn(u,t,n){return n.transform.projectTileCoordinates(u,t,n.unwrappedTileID,n.getElevation)}function Io(u,t,n){return u._unit()._perp()._mult(t*n)}function on(u,t,n,a,c,f,y,x,w){if(x.projectionCache.offsets[u])return x.projectionCache.offsets[u];let P=n.add(t);if(u+w.direction=c)return x.projectionCache.offsets[u]=P,P;let S=Yt(u+w.direction,x,w),E=Io(S.sub(n),y,w.direction),C=n.add(E),z=S.add(E);return x.projectionCache.offsets[u]=p.aF(f,P,C,z)||P,x.projectionCache.offsets[u]}function Xi(u,t,n,a,c,f,y,x,w){let P=a?u-t:u+t,S=P>0?1:-1,E=0;a&&(S*=-1,E=Math.PI),S<0&&(E+=Math.PI);let C,z=S>0?f+c:f+c+1;x.projectionCache.cachedAnchorPoint?C=x.projectionCache.cachedAnchorPoint:(C=rt(x.tileAnchorPoint.x,x.tileAnchorPoint.y,x).point,x.projectionCache.cachedAnchorPoint=C);let B,N,G=C,j=C,$=0,X=0,Z=Math.abs(P),U=[],H;for(;$+X<=Z;){if(z+=S,z=y)return null;$+=X,j=G,N=B;let oe={absOffsetX:Z,direction:S,distanceFromAnchor:$,previousVertex:j};if(G=Yt(z,x,oe),n===0)U.push(j),H=G.sub(j);else{let se,de=G.sub(j);se=de.mag()===0?Io(Yt(z+S,x,oe).sub(G),n,S):Io(de,n,S),N||(N=j.add(se)),B=on(z,se,G,f,y,N,n,x,oe),U.push(N),H=B.sub(N)}X=H.mag()}let q=H._mult((Z-$)/X)._add(N||j),Q=E+Math.atan2(G.y-j.y,G.x-j.x);return U.push(q),{point:q,angle:w?Q:0,path:U}}let ac=new Float32Array([-1/0,-1/0,0,-1/0,-1/0,0,-1/0,-1/0,0,-1/0,-1/0,0]);function sn(u,t){for(let n=0;n=1;Ee--)ve.push(ue.path[Ee]);for(let Ee=1;Eett.signedDistanceFromCamera<=0))?[]:Ee.map((tt=>tt.point))}let we=[];if(ve.length>0){let Ee=ve[0].clone(),tt=ve[0].clone();for(let Mt=1;Mt=oe.x&&tt.x<=se.x&&Ee.y>=oe.y&&tt.y<=se.y?[ve]:tt.xse.x||tt.yse.y?[]:p.aG([ve],oe.x,oe.y,se.x,se.y)}for(let Ee of we){de.reset(Ee,.25*Q);let tt=0;tt=de.length<=.5*Q?1:Math.ceil(de.paddedLength/he)+1;for(let Mt=0;Mt{let w=Oe(x.x,x.y,y,f.getElevation),P=f.transform.projectTileCoordinates(w.point.x,w.point.y,f.unwrappedTileID,f.getElevation);return P.point.x=(.5*P.point.x+.5)*f.width,P.point.y=(.5*-P.point.y+.5)*f.height,P}))})(t,n);return(function(c){let f=0,y=0,x=0,w=0;for(let P=0;Py&&(y=w,f=x));return c.slice(f,f+y)})(a)}queryRenderedSymbols(t){if(t.length===0||this.grid.keysLength()===0&&this.ignoredGrid.keysLength()===0)return{};let n=[],a=new p.a8;for(let E of t){let C=new p.P(E.x+bt,E.y+bt);a.extend(C),n.push(C)}let{minX:c,minY:f,maxX:y,maxY:x}=a,w=this.grid.query(c,f,y,x).concat(this.ignoredGrid.query(c,f,y,x)),P={},S={};for(let E of w){let C=E.key;if(P[C.bucketInstanceId]===void 0&&(P[C.bucketInstanceId]={}),P[C.bucketInstanceId][C.featureIndex])continue;let z=[new p.P(E.x1,E.y1),new p.P(E.x2,E.y1),new p.P(E.x2,E.y2),new p.P(E.x1,E.y2)];p.aH(n,z)&&(P[C.bucketInstanceId][C.featureIndex]=!0,S[C.bucketInstanceId]===void 0&&(S[C.bucketInstanceId]=[]),S[C.bucketInstanceId].push(C.featureIndex))}return S}insertCollisionBox(t,n,a,c,f,y){(a?this.ignoredGrid:this.grid).insert({bucketInstanceId:c,featureIndex:f,collisionGroupID:y,overlapMode:n},t[0],t[1],t[2],t[3])}insertCollisionCircles(t,n,a,c,f,y){let x=a?this.ignoredGrid:this.grid,w={bucketInstanceId:c,featureIndex:f,collisionGroupID:y,overlapMode:n};for(let P=0;P=this.screenRightBoundary||cthis.screenBottomBoundary}isInsideGrid(t,n,a,c){return a>=0&&t=0&&nthis.projectAndGetPerspectiveRatio(he.x,he.y,c,P,E)));Se=ve.some((he=>!he.isOccluded)),ue=ve.map((he=>new p.P(he.x,he.y)))}else Se=!0;return{box:p.aI(ue),allPointsOccluded:!Se}}}class cc{constructor(t,n,a,c){this.opacity=t?Math.max(0,Math.min(1,t.opacity+(t.placed?n:-n))):c&&a?1:0,this.placed=a}isHidden(){return this.opacity===0&&!this.placed}}class Mo{constructor(t,n,a,c,f){this.text=new cc(t?t.text:null,n,a,f),this.icon=new cc(t?t.icon:null,n,c,f)}isHidden(){return this.text.isHidden()&&this.icon.isHidden()}}class hc{constructor(t,n,a){this.text=t,this.icon=n,this.skipFade=a}}class uc{constructor(t,n,a,c,f){this.bucketInstanceId=t,this.featureIndex=n,this.sourceLayerIndex=a,this.bucketIndex=c,this.tileID=f}}class dc{constructor(t){this.crossSourceCollisions=t,this.maxGroupID=0,this.collisionGroups={}}get(t){if(this.crossSourceCollisions)return{ID:0,predicate:null};if(!this.collisionGroups[t]){let n=++this.maxGroupID;this.collisionGroups[t]={ID:n,predicate:a=>a.collisionGroupID===n}}return this.collisionGroups[t]}}function xs(u,t,n,a,c){let{horizontalAlign:f,verticalAlign:y}=p.aP(u);return new p.P(-(f-.5)*t+a[0]*c,-(y-.5)*n+a[1]*c)}class ja{constructor(t,n,a,c,f){this.transform=t.clone(),this.terrain=n,this.collisionIndex=new lc(this.transform),this.placements={},this.opacities={},this.variableOffsets={},this.stale=!1,this.commitTime=0,this.fadeDuration=a,this.retainedQueryData={},this.collisionGroups=new dc(c),this.collisionCircleArrays={},this.collisionBoxArrays=new Map,this.prevPlacement=f,f&&(f.prevPlacement=void 0),this.placedOrientations={}}_getTerrainElevationFunc(t){let n=this.terrain;return n?(a,c)=>n.getElevation(t,a,c):null}getBucketParts(t,n,a,c){let f=a.getBucket(n),y=a.latestFeatureIndex;if(!f||!y||n.id!==f.layerIds[0])return;let x=a.collisionBoxArray,w=f.layers[0].layout,P=f.layers[0].paint,S=Math.pow(2,this.transform.zoom-a.tileID.overscaledZ),E=a.tileSize/p.a6,C=a.tileID.toUnwrapped(),z=w.get("text-rotation-alignment")==="map",B=p.aK(a,1,this.transform.zoom),N=p.aL(this.collisionIndex.transform,a,P.get("text-translate"),P.get("text-translate-anchor")),G=p.aL(this.collisionIndex.transform,a,P.get("icon-translate"),P.get("icon-translate-anchor")),j=Ei(z,this.transform,B);this.retainedQueryData[f.bucketInstanceId]=new uc(f.bucketInstanceId,y,f.sourceLayerIndex,f.index,a.tileID);let $={bucket:f,layout:w,translationText:N,translationIcon:G,unwrappedTileID:C,pitchedLabelPlaneMatrix:j,scale:S,textPixelRatio:E,holdingForFade:a.holdingForSymbolFade(),collisionBoxArray:x,partiallyEvaluatedTextSize:p.aw(f.textSizeData,this.transform.zoom),collisionGroup:this.collisionGroups.get(f.sourceID)};if(c)for(let X of f.sortKeyRanges){let{sortKey:Z,symbolInstanceStart:U,symbolInstanceEnd:H}=X;t.push({sortKey:Z,symbolInstanceStart:U,symbolInstanceEnd:H,parameters:$})}else t.push({symbolInstanceStart:0,symbolInstanceEnd:f.symbolInstances.length,parameters:$})}attemptAnchorPlacement(t,n,a,c,f,y,x,w,P,S,E,C,z,B,N,G,j,$,X,Z){var U,H,q;let Q=p.aM[t.textAnchor],oe=[t.textOffset0,t.textOffset1],se=xs(Q,a,c,oe,f),de=this.collisionIndex.placeCollisionBox(n,C,w,P,S,x,y,G,E.predicate,X,se,Z);if((!$||this.collisionIndex.placeCollisionBox($,C,w,P,S,x,y,j,E.predicate,X,se,Z).placeable)&&de.placeable){let ue;if(!((U=this.prevPlacement)===null||U===void 0)&&U.variableOffsets[z.crossTileID]&&(!((q=(H=this.prevPlacement)===null||H===void 0?void 0:H.placements[z.crossTileID])===null||q===void 0)&&q.text)&&(ue=this.prevPlacement.variableOffsets[z.crossTileID].anchor),z.crossTileID===0)throw new Error("symbolInstance.crossTileID can't be 0");return this.variableOffsets[z.crossTileID]={textOffset:oe,width:a,height:c,anchor:Q,textBoxScale:f,prevAnchor:ue},this.markUsedJustification(B,Q,z,N),B.allowVerticalPlacement&&(this.markUsedOrientation(B,N,z),this.placedOrientations[z.crossTileID]=N),{shift:se,placedGlyphBoxes:de}}}placeLayerBucketPart(t,n,a){let{bucket:c,layout:f,translationText:y,translationIcon:x,unwrappedTileID:w,pitchedLabelPlaneMatrix:P,textPixelRatio:S,holdingForFade:E,collisionBoxArray:C,partiallyEvaluatedTextSize:z,collisionGroup:B}=t.parameters,N=f.get("text-optional"),G=f.get("icon-optional"),j=p.aN(f,"text-overlap","text-allow-overlap"),$=j==="always",X=p.aN(f,"icon-overlap","icon-allow-overlap"),Z=X==="always",U=f.get("text-rotation-alignment")==="map",H=f.get("text-pitch-alignment")==="map",q=f.get("icon-text-fit")!=="none",Q=f.get("symbol-z-order")==="viewport-y",oe=$&&(Z||!c.hasIconData()||G),se=Z&&($||!c.hasTextData()||N);!c.collisionArrays&&C&&c.deserializeCollisionBoxes(C);let de=this.retainedQueryData[c.bucketInstanceId].tileID,ue=this._getTerrainElevationFunc(de),Se=this.transform.getFastPathSimpleProjectionMatrix(de),ve=(he,we,Ee)=>{var tt,Mt;if(n[he.crossTileID])return;if(E)return void(this.placements[he.crossTileID]=new hc(!1,!1,!1));let ot=!1,Ct=!1,Dt=!0,ti=null,wt={box:null,placeable:!1,offscreen:null,occluded:!1},di={placeable:!1},Kt=null,Nt=null,ii=null,Nr=0,Vr=0,jr=0;we.textFeatureIndex?Nr=we.textFeatureIndex:he.useRuntimeCollisionCircles&&(Nr=he.featureIndex),we.verticalTextFeatureIndex&&(Vr=we.verticalTextFeatureIndex);let ri=we.textBox;if(ri){let sr=gt=>{let ut=p.ax.horizontal;if(c.allowVerticalPlacement&&!gt&&this.prevPlacement){let zt=this.prevPlacement.placedOrientations[he.crossTileID];zt&&(this.placedOrientations[he.crossTileID]=zt,ut=zt,this.markUsedOrientation(c,ut,he))}return ut},ar=(gt,ut)=>{if(c.allowVerticalPlacement&&he.numVerticalGlyphVertices>0&&we.verticalTextBox){for(let zt of c.writingModes)if(zt===p.ax.vertical?(wt=ut(),di=wt):wt=gt(),wt?.placeable)break}else wt=gt()},Ri=he.textAnchorOffsetStartIndex,Gi=he.textAnchorOffsetEndIndex;if(Gi===Ri){let gt=(ut,zt)=>{let _t=this.collisionIndex.placeCollisionBox(ut,j,S,de,w,H,U,y,B.predicate,ue,void 0,Se);return _t?.placeable&&(this.markUsedOrientation(c,zt,he),this.placedOrientations[he.crossTileID]=zt),_t};ar((()=>gt(ri,p.ax.horizontal)),(()=>{let ut=we.verticalTextBox;return c.allowVerticalPlacement&&he.numVerticalGlyphVertices>0&&ut?gt(ut,p.ax.vertical):{box:null,offscreen:null}})),sr(wt?.placeable)}else{let gt=p.aM[(Mt=(tt=this.prevPlacement)===null||tt===void 0?void 0:tt.variableOffsets[he.crossTileID])===null||Mt===void 0?void 0:Mt.anchor],ut=(_t,Pn,na)=>{let vr=_t.x2-_t.x1,Ll=_t.y2-_t.y1,ah=he.textBoxScale,Fl=q&&X==="never"?Pn:null,Gr=null,$r=j==="never"?1:2,Zr="never";gt&&$r++;for(let Bl=0;Bl<$r;Bl++){for(let Ol=Ri;Olut(ri,we.iconBox,p.ax.horizontal)),(()=>{let _t=we.verticalTextBox;return c.allowVerticalPlacement&&!wt?.placeable&&he.numVerticalGlyphVertices>0&&_t?ut(_t,we.verticalIconBox,p.ax.vertical):{box:null,occluded:!0,offscreen:null}})),wt&&(ot=wt.placeable,Dt=wt.offscreen);let zt=sr(wt?.placeable);if(!ot&&this.prevPlacement){let _t=this.prevPlacement.variableOffsets[he.crossTileID];_t&&(this.variableOffsets[he.crossTileID]=_t,this.markUsedJustification(c,_t.anchor,he,zt))}}}if(Kt=wt,ot=Kt?.placeable,Dt=Kt?.offscreen,he.useRuntimeCollisionCircles&&he.centerJustifiedTextSymbolIndex>=0){let sr=c.text.placedSymbolArray.get(he.centerJustifiedTextSymbolIndex),ar=p.ay(c.textSizeData,z,sr),Ri=f.get("text-padding");Nt=this.collisionIndex.placeCollisionCircles(j,sr,c.lineVertexArray,c.glyphOffsetArray,ar,w,P,a,H,B.predicate,he.collisionCircleDiameter,Ri,y,ue),Nt.circles.length&&Nt.collisionDetected&&!a&&p.w("Collisions detected, but collision boxes are not shown"),ot=$||Nt.circles.length>0&&!Nt.collisionDetected,Dt&&(Dt=Nt.offscreen)}if(we.iconFeatureIndex&&(jr=we.iconFeatureIndex),we.iconBox){let sr=ar=>this.collisionIndex.placeCollisionBox(ar,X,S,de,w,H,U,x,B.predicate,ue,q&&ti?ti:void 0,Se);di&&di.placeable&&we.verticalIconBox?(ii=sr(we.verticalIconBox),Ct=ii.placeable):(ii=sr(we.iconBox),Ct=ii.placeable),Dt&&(Dt=ii.offscreen)}let yr=N||he.numHorizontalGlyphVertices===0&&he.numVerticalGlyphVertices===0,Ur=G||he.numIconVertices===0;yr||Ur?Ur?yr||Ct&&(Ct=ot):ot=Ct&&ot:Ct=ot=Ct&&ot;let ra=Ct&&ii.placeable;if(ot&&Kt.placeable&&this.collisionIndex.insertCollisionBox(Kt.box,j,f.get("text-ignore-placement"),c.bucketInstanceId,di&&di.placeable&&Vr?Vr:Nr,B.ID),ra&&this.collisionIndex.insertCollisionBox(ii.box,X,f.get("icon-ignore-placement"),c.bucketInstanceId,jr,B.ID),Nt&&ot&&this.collisionIndex.insertCollisionCircles(Nt.circles,j,f.get("text-ignore-placement"),c.bucketInstanceId,Nr,B.ID),a&&this.storeCollisionData(c.bucketInstanceId,Ee,we,Kt,ii,Nt),he.crossTileID===0)throw new Error("symbolInstance.crossTileID can't be 0");if(c.bucketInstanceId===0)throw new Error("bucket.bucketInstanceId can't be 0");this.placements[he.crossTileID]=new hc((ot||oe)&&!Kt?.occluded,(Ct||se)&&!ii?.occluded,Dt||c.justReloaded),n[he.crossTileID]=!0};if(Q){if(t.symbolInstanceStart!==0)throw new Error("bucket.bucketInstanceId should be 0");let he=c.getSortedSymbolIndexes(-this.transform.bearingInRadians);for(let we=he.length-1;we>=0;--we){let Ee=he[we];ve(c.symbolInstances.get(Ee),c.collisionArrays[Ee],Ee)}}else for(let he=t.symbolInstanceStart;he=0&&(t.text.placedSymbolArray.get(x).crossTileID=f>=0&&x!==f?0:a.crossTileID)}markUsedOrientation(t,n,a){let c=n===p.ax.horizontal||n===p.ax.horizontalOnly?n:0,f=n===p.ax.vertical?n:0,y=[a.leftJustifiedTextSymbolIndex,a.centerJustifiedTextSymbolIndex,a.rightJustifiedTextSymbolIndex];for(let x of y)t.text.placedSymbolArray.get(x).placedOrientation=c;a.verticalPlacedTextSymbolIndex&&(t.text.placedSymbolArray.get(a.verticalPlacedTextSymbolIndex).placedOrientation=f)}commit(t){this.commitTime=t,this.zoomAtLastRecencyCheck=this.transform.zoom;let n=this.prevPlacement,a=!1;this.prevZoomAdjustment=n?n.zoomAdjustment(this.transform.zoom):0;let c=n?n.symbolFadeChange(t):1,f=n?n.opacities:{},y=n?n.variableOffsets:{},x=n?n.placedOrientations:{};for(let w in this.placements){let P=this.placements[w],S=f[w];S?(this.opacities[w]=new Mo(S,c,P.text,P.icon),a||(a=P.text!==S.text.placed),a||(a=P.icon!==S.icon.placed)):(this.opacities[w]=new Mo(null,c,P.text,P.icon,P.skipFade),a||(a=P.text||P.icon))}for(let w in f){let P=f[w];if(!this.opacities[w]){let S=new Mo(P,c,!1,!1);S.isHidden()||(this.opacities[w]=S,a||(a=P.text.placed),a||(a=P.icon.placed))}}for(let w in y)this.variableOffsets[w]||!this.opacities[w]||this.opacities[w].isHidden()||(this.variableOffsets[w]=y[w]);for(let w in x)this.placedOrientations[w]||!this.opacities[w]||this.opacities[w].isHidden()||(this.placedOrientations[w]=x[w]);if(n&&n.lastPlacementChangeTime===void 0)throw new Error("Last placement time for previous placement is not defined");a?this.lastPlacementChangeTime=t:typeof this.lastPlacementChangeTime!="number"&&(this.lastPlacementChangeTime=n?n.lastPlacementChangeTime:t)}updateLayerOpacities(t,n){let a={};for(let c of n){let f=c.getBucket(t);f&&c.latestFeatureIndex&&t.id===f.layerIds[0]&&this.updateBucketOpacities(f,c.tileID,a,c.collisionBoxArray)}}updateBucketOpacities(t,n,a,c){t.hasTextData()&&(t.text.opacityVertexArray.clear(),t.text.hasVisibleVertices=!1),t.hasIconData()&&(t.icon.opacityVertexArray.clear(),t.icon.hasVisibleVertices=!1),t.hasIconCollisionBoxData()&&t.iconCollisionBox.collisionVertexArray.clear(),t.hasTextCollisionBoxData()&&t.textCollisionBox.collisionVertexArray.clear();let f=t.layers[0],y=f.layout,x=new Mo(null,0,!1,!1,!0),w=y.get("text-allow-overlap"),P=y.get("icon-allow-overlap"),S=f._unevaluatedLayout.hasValue("text-variable-anchor")||f._unevaluatedLayout.hasValue("text-variable-anchor-offset"),E=y.get("text-rotation-alignment")==="map",C=y.get("text-pitch-alignment")==="map",z=y.get("icon-text-fit")!=="none",B=new Mo(null,0,w&&(P||!t.hasIconData()||y.get("icon-optional")),P&&(w||!t.hasTextData()||y.get("text-optional")),!0);!t.collisionArrays&&c&&(t.hasIconCollisionBoxData()||t.hasTextCollisionBoxData())&&t.deserializeCollisionBoxes(c);let N=(j,$,X)=>{for(let Z=0;Z<$/4;Z++)j.opacityVertexArray.emplaceBack(X);j.hasVisibleVertices||(j.hasVisibleVertices=X!==Co)},G=this.collisionBoxArrays.get(t.bucketInstanceId);for(let j=0;j0,Q=this.placedOrientations[$.crossTileID],oe=Q===p.ax.vertical,se=Q===p.ax.horizontal||Q===p.ax.horizontalOnly;if(X>0||Z>0){let ue=Za(H.text);N(t.text,X,oe?Co:ue),N(t.text,Z,se?Co:ue);let Se=H.text.isHidden(),ve=[$.rightJustifiedTextSymbolIndex,$.centerJustifiedTextSymbolIndex,$.leftJustifiedTextSymbolIndex];for(let Ee of ve)Ee>=0&&(t.text.placedSymbolArray.get(Ee).hidden=Se||oe?1:0);$.verticalPlacedTextSymbolIndex>=0&&(t.text.placedSymbolArray.get($.verticalPlacedTextSymbolIndex).hidden=Se||se?1:0);let he=this.variableOffsets[$.crossTileID];he&&this.markUsedJustification(t,he.anchor,$,Q);let we=this.placedOrientations[$.crossTileID];we&&(this.markUsedJustification(t,"left",$,we),this.markUsedOrientation(t,we,$))}if(q){let ue=Za(H.icon),Se=!(z&&$.verticalPlacedIconSymbolIndex&&oe);$.placedIconSymbolIndex>=0&&(N(t.icon,$.numIconVertices,Se?ue:Co),t.icon.placedSymbolArray.get($.placedIconSymbolIndex).hidden=H.icon.isHidden()),$.verticalPlacedIconSymbolIndex>=0&&(N(t.icon,$.numVerticalIconVertices,Se?Co:ue),t.icon.placedSymbolArray.get($.verticalPlacedIconSymbolIndex).hidden=H.icon.isHidden())}let de=G?.has(j)?G.get(j):{text:null,icon:null};if(t.hasIconCollisionBoxData()||t.hasTextCollisionBoxData()){let ue=t.collisionArrays[j];if(ue){let Se=new p.P(0,0);if(ue.textBox||ue.verticalTextBox){let ve=!0;if(S){let he=this.variableOffsets[U];he?(Se=xs(he.anchor,he.width,he.height,he.textOffset,he.textBoxScale),E&&Se._rotate(C?-this.transform.bearingInRadians:this.transform.bearingInRadians)):ve=!1}if(ue.textBox||ue.verticalTextBox){let he;ue.textBox&&(he=oe),ue.verticalTextBox&&(he=se),Ua(t.textCollisionBox.collisionVertexArray,H.text.placed,!ve||he,de.text,Se.x,Se.y)}}if(ue.iconBox||ue.verticalIconBox){let ve=!!(!se&&ue.verticalIconBox),he;ue.iconBox&&(he=ve),ue.verticalIconBox&&(he=!ve),Ua(t.iconCollisionBox.collisionVertexArray,H.icon.placed,he,de.icon,z?Se.x:0,z?Se.y:0)}}}}if(t.sortFeatures(-this.transform.bearingInRadians),this.retainedQueryData[t.bucketInstanceId]&&(this.retainedQueryData[t.bucketInstanceId].featureSortOrder=t.featureSortOrder),t.hasTextData()&&t.text.opacityVertexBuffer&&t.text.opacityVertexBuffer.updateData(t.text.opacityVertexArray),t.hasIconData()&&t.icon.opacityVertexBuffer&&t.icon.opacityVertexBuffer.updateData(t.icon.opacityVertexArray),t.hasIconCollisionBoxData()&&t.iconCollisionBox.collisionVertexBuffer&&t.iconCollisionBox.collisionVertexBuffer.updateData(t.iconCollisionBox.collisionVertexArray),t.hasTextCollisionBoxData()&&t.textCollisionBox.collisionVertexBuffer&&t.textCollisionBox.collisionVertexBuffer.updateData(t.textCollisionBox.collisionVertexArray),t.text.opacityVertexArray.length!==t.text.layoutVertexArray.length/4)throw new Error(`bucket.text.opacityVertexArray.length (= ${t.text.opacityVertexArray.length}) !== bucket.text.layoutVertexArray.length (= ${t.text.layoutVertexArray.length}) / 4`);if(t.icon.opacityVertexArray.length!==t.icon.layoutVertexArray.length/4)throw new Error(`bucket.icon.opacityVertexArray.length (= ${t.icon.opacityVertexArray.length}) !== bucket.icon.layoutVertexArray.length (= ${t.icon.layoutVertexArray.length}) / 4`);t.bucketInstanceId in this.collisionCircleArrays&&(t.collisionCircleArray=this.collisionCircleArrays[t.bucketInstanceId],delete this.collisionCircleArrays[t.bucketInstanceId])}symbolFadeChange(t){return this.fadeDuration===0?1:(t-this.commitTime)/this.fadeDuration+this.prevZoomAdjustment}zoomAdjustment(t){return Math.max(0,(this.transform.zoom-t)/1.5)}hasTransitions(t){return this.stale||t-this.lastPlacementChangeTimet}setStale(){this.stale=!0}}function Ua(u,t,n,a,c,f){a&&a.length!==0||(a=[0,0,0,0]);let y=a[0]-bt,x=a[1]-bt,w=a[2]-bt,P=a[3]-bt;u.emplaceBack(t?1:0,n?1:0,c||0,f||0,y,x),u.emplaceBack(t?1:0,n?1:0,c||0,f||0,w,x),u.emplaceBack(t?1:0,n?1:0,c||0,f||0,w,P),u.emplaceBack(t?1:0,n?1:0,c||0,f||0,y,P)}let Ga=Math.pow(2,25),$a=Math.pow(2,24),Bh=Math.pow(2,17),Eo=Math.pow(2,16),bs=Math.pow(2,9),pc=Math.pow(2,8),Vn=Math.pow(2,1);function Za(u){if(u.opacity===0&&!u.placed)return 0;if(u.opacity===1&&u.placed)return 4294967295;let t=u.placed?1:0,n=Math.floor(127*u.opacity);return n*Ga+t*$a+n*Bh+t*Eo+n*bs+t*pc+n*Vn+t}let Co=0;class Rr{constructor(t){this._sortAcrossTiles=t.layout.get("symbol-z-order")!=="viewport-y"&&!t.layout.get("symbol-sort-key").isConstant(),this._currentTileIndex=0,this._currentPartIndex=0,this._seenCrossTileIDs={},this._bucketParts=[]}continuePlacement(t,n,a,c,f){let y=this._bucketParts;for(;this._currentTileIndexx.sortKey-w.sortKey)));this._currentPartIndex!this._forceFullPlacement&&Xe()-c>2;for(;this._currentPlacementIndex>=0;){let y=n[t[this._currentPlacementIndex]],x=this.placement.collisionIndex.transform.zoom;if(p.aQ(y)&&y.layout&&(!y.minzoom||y.minzoom<=x)&&(!y.maxzoom||y.maxzoom>x)){if(this._inProgressLayer||(this._inProgressLayer=new Rr(y)),this._inProgressLayer.continuePlacement(a[y.source],this.placement,this._showCollisionBoxes,y,f))return;delete this._inProgressLayer}this._currentPlacementIndex--}this._done=!0}commit(t){return this.placement.commit(t),this.placement}}let Ve=512/p.a6/2;class qa{constructor(t,n,a){this.tileID=t,this.bucketInstanceId=a,this._symbolsByKey={};let c=new Map;for(let f=0;f({x:Math.floor(w.anchorX*Ve),y:Math.floor(w.anchorY*Ve)}))),crossTileIDs:y.map((w=>w.crossTileID))};if(x.positions.length>128){let w=new p.aR(x.positions.length,16,Uint16Array);for(let{x:P,y:S}of x.positions)w.add(P,S);w.finish(),delete x.positions,x.index=w}this._symbolsByKey[f]=x}}getScaledCoordinates(t,n){let{x:a,y:c,z:f}=this.tileID.canonical,{x:y,y:x,z:w}=n.canonical,P=Ve/Math.pow(2,w-f),S=(x*p.a6+t.anchorY)*P,E=c*p.a6*Ve;return{x:Math.floor((y*p.a6+t.anchorX)*P-a*p.a6*Ve),y:Math.floor(S-E)}}findMatches(t,n,a){let c=this.tileID.canonical.zt))}}class Oh{constructor(){this.maxCrossTileID=0}generate(){return++this.maxCrossTileID}}class Wa{constructor(){this.indexes={},this.usedCrossTileIDs={},this.lng=0}handleWrapJump(t){let n=Math.round((t-this.lng)/360);if(n!==0)for(let a in this.indexes){let c=this.indexes[a],f={};for(let y in c){let x=c[y];x.tileID=x.tileID.unwrapTo(x.tileID.wrap+n),f[x.tileID.key]=x}this.indexes[a]=f}this.lng=t}addBucket(t,n,a){var c,f,y;if(!((c=this.indexes[t.overscaledZ])===null||c===void 0)&&c[t.key]){if(this.indexes[t.overscaledZ][t.key].bucketInstanceId===n.bucketInstanceId)return!1;this.removeBucketCrossTileIDs(t.overscaledZ,this.indexes[t.overscaledZ][t.key])}for(let w=0;wt.overscaledZ)for(let S in P){let E=P[S];E.tileID.isChildOf(t)&&E.findMatches(n.symbolInstances,t,x)}else{let S=P[t.scaledTo(Number(w)).key];S&&S.findMatches(n.symbolInstances,t,x)}}for(let w=0;w{Da();(function(Le,Qe){typeof yd=="object"&&typeof vd<"u"?vd.exports=Qe():typeof define=="function"&&define.amd?define(Qe):(Le=typeof globalThis<"u"?globalThis:Le||self,Le.maplibregl=Qe())})(yd,(function(){"use strict";var Le={},Qe={};function Zt(k,p,Te){if(Qe[k]=Te,k==="index"){var Sr="var sharedModule = {}; ("+Qe.shared+")(sharedModule); ("+Qe.worker+")(sharedModule);",Si={};return Qe.shared(Si),Qe.index(Le,Si),typeof window<"u"&&Le.setWorkerUrl(window.URL.createObjectURL(new Blob([Sr],{type:"text/javascript"}))),Le}}Zt("shared",["exports"],(function(k){"use strict";function p(r,e,i,o){return new(i||(i=Promise))((function(s,l){function h(m){try{g(o.next(m))}catch(v){l(v)}}function d(m){try{g(o.throw(m))}catch(v){l(v)}}function g(m){var v;m.done?s(m.value):(v=m.value,v instanceof i?v:new i((function(_){_(v)}))).then(h,d)}g((o=o.apply(r,e||[])).next())}))}function Te(r,e){this.x=r,this.y=e}function Sr(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var Si,Wr;typeof SuppressedError=="function"&&SuppressedError,Te.prototype={clone(){return new Te(this.x,this.y)},add(r){return this.clone()._add(r)},sub(r){return this.clone()._sub(r)},multByPoint(r){return this.clone()._multByPoint(r)},divByPoint(r){return this.clone()._divByPoint(r)},mult(r){return this.clone()._mult(r)},div(r){return this.clone()._div(r)},rotate(r){return this.clone()._rotate(r)},rotateAround(r,e){return this.clone()._rotateAround(r,e)},matMult(r){return this.clone()._matMult(r)},unit(){return this.clone()._unit()},perp(){return this.clone()._perp()},round(){return this.clone()._round()},mag(){return Math.sqrt(this.x*this.x+this.y*this.y)},equals(r){return this.x===r.x&&this.y===r.y},dist(r){return Math.sqrt(this.distSqr(r))},distSqr(r){let e=r.x-this.x,i=r.y-this.y;return e*e+i*i},angle(){return Math.atan2(this.y,this.x)},angleTo(r){return Math.atan2(this.y-r.y,this.x-r.x)},angleWith(r){return this.angleWithSep(r.x,r.y)},angleWithSep(r,e){return Math.atan2(this.x*e-this.y*r,this.x*r+this.y*e)},_matMult(r){let e=r[2]*this.x+r[3]*this.y;return this.x=r[0]*this.x+r[1]*this.y,this.y=e,this},_add(r){return this.x+=r.x,this.y+=r.y,this},_sub(r){return this.x-=r.x,this.y-=r.y,this},_mult(r){return this.x*=r,this.y*=r,this},_div(r){return this.x/=r,this.y/=r,this},_multByPoint(r){return this.x*=r.x,this.y*=r.y,this},_divByPoint(r){return this.x/=r.x,this.y/=r.y,this},_unit(){return this._div(this.mag()),this},_perp(){let r=this.y;return this.y=this.x,this.x=-r,this},_rotate(r){let e=Math.cos(r),i=Math.sin(r),o=i*this.x+e*this.y;return this.x=e*this.x-i*this.y,this.y=o,this},_rotateAround(r,e){let i=Math.cos(r),o=Math.sin(r),s=e.y+o*(this.x-e.x)+i*(this.y-e.y);return this.x=e.x+i*(this.x-e.x)-o*(this.y-e.y),this.y=s,this},_round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this},constructor:Te},Te.convert=function(r){if(r instanceof Te)return r;if(Array.isArray(r))return new Te(+r[0],+r[1]);if(r.x!==void 0&&r.y!==void 0)return new Te(+r.x,+r.y);throw new Error("Expected [x, y] or {x, y} point format")};var An=(function(){if(Wr)return Si;function r(e,i,o,s){this.cx=3*e,this.bx=3*(o-e)-this.cx,this.ax=1-this.cx-this.bx,this.cy=3*i,this.by=3*(s-i)-this.cy,this.ay=1-this.cy-this.by,this.p1x=e,this.p1y=i,this.p2x=o,this.p2y=s}return Wr=1,Si=r,r.prototype={sampleCurveX:function(e){return((this.ax*e+this.bx)*e+this.cx)*e},sampleCurveY:function(e){return((this.ay*e+this.by)*e+this.cy)*e},sampleCurveDerivativeX:function(e){return(3*this.ax*e+2*this.bx)*e+this.cx},solveCurveX:function(e,i){if(i===void 0&&(i=1e-6),e<0)return 0;if(e>1)return 1;for(var o=e,s=0;s<8;s++){var l=this.sampleCurveX(o)-e;if(Math.abs(l)l?d=o:g=o,o=.5*(g-d)+d;return o},solve:function(e,i){return this.sampleCurveY(this.solveCurveX(e,i))}},Si})(),qt=Sr(An);let Ir,Xe;function Hr(){return Ir!=null||(Ir=typeof OffscreenCanvas<"u"&&new OffscreenCanvas(1,1).getContext("2d")&&typeof createImageBitmap=="function"),Ir}function Ii(){if(Xe==null&&(Xe=!1,Hr())){let e=new OffscreenCanvas(5,5).getContext("2d",{willReadFrequently:!0});if(e){for(let o=0;o<25;o++){let s=4*o;e.fillStyle=`rgb(${s},${s+1},${s+2})`,e.fillRect(o%5,Math.floor(o/5),1,1)}let i=e.getImageData(0,0,5,5).data;for(let o=0;o<100;o++)if(o%4!=3&&i[o]!==o){Xe=!0;break}}}return Xe||!1}var pe=1e-6,kt=typeof Float32Array<"u"?Float32Array:Array;function Xr(){var r=new kt(9);return kt!=Float32Array&&(r[1]=0,r[2]=0,r[3]=0,r[5]=0,r[6]=0,r[7]=0),r[0]=1,r[4]=1,r[8]=1,r}function Dn(r){return r[0]=1,r[1]=0,r[2]=0,r[3]=0,r[4]=0,r[5]=1,r[6]=0,r[7]=0,r[8]=0,r[9]=0,r[10]=1,r[11]=0,r[12]=0,r[13]=0,r[14]=0,r[15]=1,r}function go(){var r=new kt(3);return kt!=Float32Array&&(r[0]=0,r[1]=0,r[2]=0),r}function _o(r){var e=r[0],i=r[1],o=r[2];return Math.sqrt(e*e+i*i+o*o)}function We(r,e,i){var o=new kt(3);return o[0]=r,o[1]=e,o[2]=i,o}function W(r,e,i){return r[0]=e[0]+i[0],r[1]=e[1]+i[1],r[2]=e[2]+i[2],r}function K(r,e,i){return r[0]=e[0]*i,r[1]=e[1]*i,r[2]=e[2]*i,r}function ee(r,e,i){var o=e[0],s=e[1],l=e[2],h=i[0],d=i[1],g=i[2];return r[0]=s*g-l*d,r[1]=l*h-o*g,r[2]=o*d-s*h,r}var ge,Me=_o;function Ze(r,e,i){var o=e[0],s=e[1],l=e[2],h=e[3];return r[0]=i[0]*o+i[4]*s+i[8]*l+i[12]*h,r[1]=i[1]*o+i[5]*s+i[9]*l+i[13]*h,r[2]=i[2]*o+i[6]*s+i[10]*l+i[14]*h,r[3]=i[3]*o+i[7]*s+i[11]*l+i[15]*h,r}function ze(){var r=new kt(4);return kt!=Float32Array&&(r[0]=0,r[1]=0,r[2]=0),r[3]=1,r}function $e(r,e,i,o){var s=arguments.length>4&&arguments[4]!==void 0?arguments[4]:"zyx",l=Math.PI/360;e*=l,o*=l,i*=l;var h=Math.sin(e),d=Math.cos(e),g=Math.sin(i),m=Math.cos(i),v=Math.sin(o),_=Math.cos(o);switch(s){case"xyz":r[0]=h*m*_+d*g*v,r[1]=d*g*_-h*m*v,r[2]=d*m*v+h*g*_,r[3]=d*m*_-h*g*v;break;case"xzy":r[0]=h*m*_-d*g*v,r[1]=d*g*_-h*m*v,r[2]=d*m*v+h*g*_,r[3]=d*m*_+h*g*v;break;case"yxz":r[0]=h*m*_+d*g*v,r[1]=d*g*_-h*m*v,r[2]=d*m*v-h*g*_,r[3]=d*m*_+h*g*v;break;case"yzx":r[0]=h*m*_+d*g*v,r[1]=d*g*_+h*m*v,r[2]=d*m*v-h*g*_,r[3]=d*m*_-h*g*v;break;case"zxy":r[0]=h*m*_-d*g*v,r[1]=d*g*_+h*m*v,r[2]=d*m*v+h*g*_,r[3]=d*m*_-h*g*v;break;case"zyx":r[0]=h*m*_-d*g*v,r[1]=d*g*_+h*m*v,r[2]=d*m*v-h*g*_,r[3]=d*m*_+h*g*v;break;default:throw new Error("Unknown angle order "+s)}return r}function Be(){var r=new kt(2);return kt!=Float32Array&&(r[0]=0,r[1]=0),r}function Ke(r,e){var i=new kt(2);return i[0]=r,i[1]=e,i}go(),ge=new kt(4),kt!=Float32Array&&(ge[0]=0,ge[1]=0,ge[2]=0,ge[3]=0),go(),We(1,0,0),We(0,1,0),ze(),ze(),Xr(),Be();let De=8192;function vt(r,e,i){return e*(De/(r.tileSize*Math.pow(2,i-r.tileID.overscaledZ)))}function xt(r){return r instanceof Error?r:new Error(typeof r=="string"?r:String(r))}function Wi(r,e){return(r%e+e)%e}function Bi(r,e,i){return r*(1-i)+e*i}function Mr(r){if(r<=0)return 0;if(r>=1)return 1;let e=r*r,i=e*r;return 4*(r<.5?i:3*(r-e)+i-.75)}function Yr(r,e,i,o){let s=new qt(r,e,i,o);return l=>s.solve(l)}let yo=Yr(.25,.1,.25,1);function li(r,e,i){return Math.min(i,Math.max(e,r))}function zn(r,e,i){let o=i-e,s=((r-e)%o+o)%o+e;return s===e?i:s}function Oi(r,...e){for(let i of e)for(let o in i)r[o]=i[o];return r}let vo=1;function Er(r,e,i){let o={};for(let s in r)o[s]=e.call(this,r[s],s,r);return o}function Kr(r,e,i){let o={};for(let s in r)e.call(this,r[s],s,r)&&(o[s]=r[s]);return o}function Re(r){return Array.isArray(r)?r.map(Re):typeof r=="object"&&r?Er(r,Re):r}let Bt={};function Wt(r){Bt[r]||(typeof console<"u"&&console.warn(r),Bt[r]=!0)}function Mi(r,e,i){return(i.y-r.y)*(e.x-r.x)>(e.y-r.y)*(i.x-r.x)}function Ht(r){return typeof WorkerGlobalScope<"u"&&r!==void 0&&r instanceof WorkerGlobalScope}let yi=null;function Jr(r){return typeof ImageBitmap<"u"&&r instanceof ImageBitmap}let za="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVQYV2NgAAIAAAUAAarVyFEAAAAASUVORK5CYII=";function Ra(r,e,i,o,s){return p(this,void 0,void 0,(function*(){if(typeof VideoFrame>"u")throw new Error("VideoFrame not supported");let l=new VideoFrame(r,{timestamp:0});try{let h=l?.format;if(!h||!h.startsWith("BGR")&&!h.startsWith("RGB"))throw new Error(`Unrecognized format ${h}`);let d=h.startsWith("BGR"),g=new Uint8ClampedArray(o*s*4);if(yield l.copyTo(g,(function(m,v,_,T,b){let I=4*Math.max(-v,0),M=(Math.max(0,_)-_)*T*4+I,A=4*T,D=Math.max(0,v),L=Math.max(0,_);return{rect:{x:D,y:L,width:Math.min(m.width,v+T)-D,height:Math.min(m.height,_+b)-L},layout:[{offset:M,stride:A}]}})(r,e,i,o,s)),d)for(let m=0;m{r.removeEventListener(e,i,o)}}}function Ar(r){return r*Math.PI/180}function Qr(r){return r/Math.PI*180}let ka={touchstart:!0,touchmove:!0,touchmoveWindow:!0,touchend:!0,touchcancel:!0},La={dblclick:!0,click:!0,mouseover:!0,mouseout:!0,mousedown:!0,mousemove:!0,mousemoveWindow:!0,mouseup:!0,mouseupWindow:!0,contextmenu:!0,wheel:!0},ds="AbortError";class xo extends Error{constructor(e=ds){super(e instanceof Error?e.message:e),this.name=ds,e instanceof Error&&e.stack&&(this.stack=e.stack)}}function rc(r){return r instanceof Error&&r.name===ds}function ps(r){if(r.aborted)throw new xo(r.reason)}let Dr={MAX_PARALLEL_IMAGE_REQUESTS:16,MAX_PARALLEL_IMAGE_REQUESTS_PER_FRAME:8,MAX_TILE_CACHE_ZOOM_LEVELS:5,REGISTERED_PROTOCOLS:{},WORKER_URL:""};function hr(r){return Dr.REGISTERED_PROTOCOLS[r.substring(0,r.indexOf("://"))]}let Ni="global-dispatcher";class kn extends Error{constructor(e,i,o,s){super(`AJAXError: ${i} (${e}): ${o}`),this.status=e,this.statusText=i,this.url=o,this.body=s}}let Fa=()=>{var r;return Ht(self)?(r=self.worker)===null||r===void 0?void 0:r.referrer:(window.location.protocol==="blob:"?window.parent:window).location.href},en=function(r,e){return p(this,void 0,void 0,(function*(){var i,o;if(r.url.includes("://")&&!/^https?:|^file:/.test(r.url)){let s=hr(r.url);if(s){let l=yield s(r,e);return l.data||r.type!=="arrayBuffer"?l:Oi(l,{data:new ArrayBuffer(0)})}if(Ht(self)&&(!((i=self.worker)===null||i===void 0)&&i.actor))return self.worker.actor.sendAsync({type:"GR",data:r,targetMapId:Ni},e)}if(!(s=>{var l;return s.startsWith("file:")||((l=Fa())===null||l===void 0?void 0:l.startsWith("file:"))&&!/^\w+:/.test(s)})(r.url)){if(fetch&&Request&&AbortController&&Object.hasOwn(Request.prototype,"signal"))return(function(s,l){return p(this,void 0,void 0,(function*(){let h=new Request(s.url,{method:s.method||"GET",body:s.body,credentials:s.credentials,headers:s.headers,cache:s.cache,referrer:Fa(),referrerPolicy:s.referrerPolicy,signal:l.signal}),d,g;s.type!=="json"||h.headers.has("Accept")||h.headers.set("Accept","application/json");try{d=yield fetch(h)}catch(v){throw rc(v)?v:new kn(0,xt(v).message,s.url,new Blob)}if(!d.ok){let v=yield d.blob();throw new kn(d.status,d.statusText,s.url,v)}g=s.type==="arrayBuffer"||s.type==="image"?d.arrayBuffer():s.type==="json"?d.json():d.text();let m=yield g;return ps(l.signal),{data:m,cacheControl:d.headers.get("Cache-Control"),expires:d.headers.get("Expires"),etag:d.headers.get("ETag")}}))})(r,e);if(Ht(self)&&(!((o=self.worker)===null||o===void 0)&&o.actor))return self.worker.actor.sendAsync({type:"GR",data:r,mustQueue:!0,targetMapId:Ni},e)}return(function(s,l){return new Promise(((h,d)=>{var g;let m=new XMLHttpRequest;m.open(s.method||"GET",s.url,!0),s.type!=="arrayBuffer"&&s.type!=="image"||(m.responseType="arraybuffer");for(let v in s.headers)m.setRequestHeader(v,s.headers[v]);s.type==="json"&&(m.responseType="text",!((g=s.headers)===null||g===void 0)&&g.Accept||m.setRequestHeader("Accept","application/json")),m.withCredentials=s.credentials==="include",m.onerror=()=>{d(new Error(m.statusText))},m.onload=()=>{if(!l.signal.aborted)if((m.status>=200&&m.status<300||m.status===0)&&m.response!==null){let v=m.response;if(s.type==="json")try{v=JSON.parse(m.response)}catch(_){return void d(_)}h({data:v,cacheControl:m.getResponseHeader("Cache-Control"),expires:m.getResponseHeader("Expires"),etag:m.getResponseHeader("ETag")})}else{let v=new Blob([m.response],{type:m.getResponseHeader("Content-Type")});d(new kn(m.status,m.statusText,s.url,v))}},l.signal.addEventListener("abort",(()=>{m.abort(),d(new xo(l.signal.reason))})),m.send(s.body)}))})(r,e)}))};function Hi(r){if(!r||r.indexOf("://")<=0||r.startsWith("data:image/")||r.startsWith("blob:"))return!0;let e=new URL(r),i=window.location;return e.protocol===i.protocol&&e.host===i.host}function Ln(r,e,i){var o;!((o=i[r])===null||o===void 0)&&o.includes(e)||(i[r]||(i[r]=[]),i[r].push(e))}function tn(r,e,i){if(i?.[r]){let o=i[r].indexOf(e);o!==-1&&i[r].splice(o,1)}}class bo{constructor(e,i={}){Oi(this,i),this.type=e}}class Fn extends bo{constructor(e,i={}){super("error",Oi({error:e},i))}}class fs{on(e,i){return this._listeners||(this._listeners={}),Ln(e,i,this._listeners),{unsubscribe:()=>{this.off(e,i)}}}off(e,i){return tn(e,i,this._listeners),tn(e,i,this._oneTimeListeners),this}once(e,i){return i?(this._oneTimeListeners||(this._oneTimeListeners={}),Ln(e,i,this._oneTimeListeners),this):new Promise((o=>this.once(e,o)))}fire(e,i){var o,s;typeof e=="string"&&(e=new bo(e,i||{}));let l=e.type;if(this.listens(l)){e.target=this;let h=!((o=this._listeners)===null||o===void 0)&&o[l]?this._listeners[l].slice():[];for(let m of h)m.call(this,e);let d=!((s=this._oneTimeListeners)===null||s===void 0)&&s[l]?this._oneTimeListeners[l].slice():[];for(let m of d)tn(l,m,this._oneTimeListeners),m.call(this,e);let g=this._eventedParent;g&&(Oi(e,typeof this._eventedParentData=="function"?this._eventedParentData():this._eventedParentData),g.fire(e))}else e instanceof Fn&&console.error(e.error);return this}listens(e){var i,o,s,l,h;return((o=(i=this._listeners)===null||i===void 0?void 0:i[e])===null||o===void 0?void 0:o.length)>0||((l=(s=this._oneTimeListeners)===null||s===void 0?void 0:s[e])===null||l===void 0?void 0:l.length)>0||((h=this._eventedParent)===null||h===void 0?void 0:h.listens(e))}setEventedParent(e,i){return this._eventedParent=e,this._eventedParentData=i,this}}var ce={$version:8,$root:{version:{required:!0,type:"enum",values:[8]},name:{type:"string"},metadata:{type:"*"},center:{type:"array",value:"number",length:2},centerAltitude:{type:"number"},zoom:{type:"number"},bearing:{type:"number",default:0,period:360,units:"degrees"},pitch:{type:"number",default:0,units:"degrees"},roll:{type:"number",default:0,units:"degrees"},state:{type:"state",default:{}},light:{type:"light"},sky:{type:"sky"},projection:{type:"projection"},terrain:{type:"terrain"},sources:{required:!0,type:"sources"},sprite:{type:"sprite"},glyphs:{type:"string"},"font-faces":{type:"fontFaces"},transition:{type:"transition"},layers:{required:!0,type:"array",value:"layer"}},sources:{"*":{type:"source"}},source:["source_vector","source_raster","source_raster_dem","source_geojson","source_video","source_image"],source_vector:{type:{required:!0,type:"enum",values:{vector:{}}},url:{type:"string"},tiles:{type:"array",value:"string"},bounds:{type:"array",value:"number",length:4,default:[-180,-85.051129,180,85.051129]},scheme:{type:"enum",values:{xyz:{},tms:{}},default:"xyz"},minzoom:{type:"number",default:0},maxzoom:{type:"number",default:22},attribution:{type:"string"},promoteId:{type:"promoteId"},volatile:{type:"boolean",default:!1},encoding:{type:"enum",values:{mvt:{},mlt:{}},default:"mvt"},"*":{type:"*"}},source_raster:{type:{required:!0,type:"enum",values:{raster:{}}},url:{type:"string"},tiles:{type:"array",value:"string"},bounds:{type:"array",value:"number",length:4,default:[-180,-85.051129,180,85.051129]},minzoom:{type:"number",default:0},maxzoom:{type:"number",default:22},tileSize:{type:"number",default:512,units:"pixels"},scheme:{type:"enum",values:{xyz:{},tms:{}},default:"xyz"},attribution:{type:"string"},volatile:{type:"boolean",default:!1},"*":{type:"*"}},source_raster_dem:{type:{required:!0,type:"enum",values:{"raster-dem":{}}},url:{type:"string"},tiles:{type:"array",value:"string"},bounds:{type:"array",value:"number",length:4,default:[-180,-85.051129,180,85.051129]},minzoom:{type:"number",default:0},maxzoom:{type:"number",default:22},tileSize:{type:"number",default:512,units:"pixels"},attribution:{type:"string"},encoding:{type:"enum",values:{terrarium:{},mapbox:{},custom:{}},default:"mapbox"},redFactor:{type:"number",default:1},blueFactor:{type:"number",default:1},greenFactor:{type:"number",default:1},baseShift:{type:"number",default:0},volatile:{type:"boolean",default:!1},"*":{type:"*"}},source_geojson:{type:{required:!0,type:"enum",values:{geojson:{}}},data:{required:!0,type:"*"},maxzoom:{type:"number",default:18},attribution:{type:"string"},buffer:{type:"number",default:128,maximum:512,minimum:0},filter:{type:"filter"},tolerance:{type:"number",default:.375},cluster:{type:"boolean",default:!1},clusterRadius:{type:"number",default:50,minimum:0},clusterMaxZoom:{type:"number"},clusterMinPoints:{type:"number"},clusterProperties:{type:"*"},lineMetrics:{type:"boolean",default:!1},generateId:{type:"boolean",default:!1},promoteId:{type:"promoteId"}},source_video:{type:{required:!0,type:"enum",values:{video:{}}},urls:{required:!0,type:"array",value:"string"},coordinates:{required:!0,type:"array",length:4,value:{type:"array",length:2,value:"number"}}},source_image:{type:{required:!0,type:"enum",values:{image:{}}},url:{required:!0,type:"string"},coordinates:{required:!0,type:"array",length:4,value:{type:"array",length:2,value:"number"}}},layer:{id:{type:"string",required:!0},type:{type:"enum",values:{fill:{},line:{},symbol:{},circle:{},heatmap:{},"fill-extrusion":{},raster:{},hillshade:{},"color-relief":{},background:{}},required:!0},metadata:{type:"*"},source:{type:"string"},"source-layer":{type:"string"},minzoom:{type:"number",minimum:0,maximum:24},maxzoom:{type:"number",minimum:0,maximum:24},filter:{type:"filter"},layout:{type:"layout"},paint:{type:"paint"}},layout:["layout_fill","layout_line","layout_circle","layout_heatmap","layout_fill-extrusion","layout_symbol","layout_raster","layout_hillshade","layout_color-relief","layout_background"],layout_background:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible",expression:{interpolated:!1,parameters:["global-state"]},"property-type":"data-constant"}},layout_fill:{"fill-sort-key":{type:"number",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible",expression:{interpolated:!1,parameters:["global-state"]},"property-type":"data-constant"}},layout_circle:{"circle-sort-key":{type:"number",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible",expression:{interpolated:!1,parameters:["global-state"]},"property-type":"data-constant"}},layout_heatmap:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible",expression:{interpolated:!1,parameters:["global-state"]},"property-type":"data-constant"}},"layout_fill-extrusion":{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible",expression:{interpolated:!1,parameters:["global-state"]},"property-type":"data-constant"}},layout_line:{"line-cap":{type:"enum",values:{butt:{},round:{},square:{}},default:"butt",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"line-join":{type:"enum",values:{bevel:{},round:{},miter:{}},default:"miter",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"line-miter-limit":{type:"number",default:2,requires:[{"line-join":"miter"}],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"line-round-limit":{type:"number",default:1.05,requires:[{"line-join":"round"}],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"line-sort-key":{type:"number",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible",expression:{interpolated:!1,parameters:["global-state"]},"property-type":"data-constant"}},layout_symbol:{"symbol-placement":{type:"enum",values:{point:{},line:{},"line-center":{}},default:"point",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"symbol-spacing":{type:"number",default:250,minimum:1,units:"pixels",requires:[{"symbol-placement":"line"}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"symbol-avoid-edges":{type:"boolean",default:!1,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"symbol-sort-key":{type:"number",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"symbol-z-order":{type:"enum",values:{auto:{},"viewport-y":{},source:{}},default:"auto",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-allow-overlap":{type:"boolean",default:!1,requires:["icon-image",{"!":"icon-overlap"}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-overlap":{type:"enum",values:{never:{},always:{},cooperative:{}},requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-ignore-placement":{type:"boolean",default:!1,requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-optional":{type:"boolean",default:!1,requires:["icon-image","text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-rotation-alignment":{type:"enum",values:{map:{},viewport:{},auto:{}},default:"auto",requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-size":{type:"number",default:1,minimum:0,units:"factor of the original icon size",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-text-fit":{type:"enum",values:{none:{},width:{},height:{},both:{}},default:"none",requires:["icon-image","text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-text-fit-padding":{type:"array",value:"number",length:4,default:[0,0,0,0],units:"pixels",requires:["icon-image","text-field",{"icon-text-fit":["both","width","height"]}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"icon-image":{type:"resolvedImage",tokens:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-rotate":{type:"number",default:0,period:360,units:"degrees",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-padding":{type:"padding",default:[2],units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-keep-upright":{type:"boolean",default:!1,requires:["icon-image",{"icon-rotation-alignment":"map"},{"symbol-placement":["line","line-center"]}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-offset":{type:"array",value:"number",length:2,default:[0,0],requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-anchor":{type:"enum",values:{center:{},left:{},right:{},top:{},bottom:{},"top-left":{},"top-right":{},"bottom-left":{},"bottom-right":{}},default:"center",requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-pitch-alignment":{type:"enum",values:{map:{},viewport:{},auto:{}},default:"auto",requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-pitch-alignment":{type:"enum",values:{map:{},viewport:{},auto:{}},default:"auto",requires:["text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-rotation-alignment":{type:"enum",values:{map:{},viewport:{},"viewport-glyph":{},auto:{}},default:"auto",requires:["text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-field":{type:"formatted",default:"",tokens:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-font":{type:"array",value:"string",default:["Open Sans Regular","Arial Unicode MS Regular"],requires:["text-field"],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-size":{type:"number",default:16,minimum:0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-max-width":{type:"number",default:10,minimum:0,units:"ems",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-line-height":{type:"number",default:1.2,units:"ems",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"text-letter-spacing":{type:"number",default:0,units:"ems",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-justify":{type:"enum",values:{auto:{},left:{},center:{},right:{}},default:"center",requires:["text-field"],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-radial-offset":{type:"number",units:"ems",default:0,requires:["text-field"],"property-type":"data-driven",expression:{interpolated:!0,parameters:["zoom","feature"]}},"text-variable-anchor":{type:"array",value:"enum",values:{center:{},left:{},right:{},top:{},bottom:{},"top-left":{},"top-right":{},"bottom-left":{},"bottom-right":{}},requires:["text-field",{"symbol-placement":["point"]}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-variable-anchor-offset":{type:"variableAnchorOffsetCollection",requires:["text-field",{"symbol-placement":["point"]}],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-anchor":{type:"enum",values:{center:{},left:{},right:{},top:{},bottom:{},"top-left":{},"top-right":{},"bottom-left":{},"bottom-right":{}},default:"center",requires:["text-field",{"!":"text-variable-anchor"}],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-max-angle":{type:"number",default:45,units:"degrees",requires:["text-field",{"symbol-placement":["line","line-center"]}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"text-writing-mode":{type:"array",value:"enum",values:{horizontal:{},vertical:{}},requires:["text-field",{"symbol-placement":["point"]}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-rotate":{type:"number",default:0,period:360,units:"degrees",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-padding":{type:"number",default:2,minimum:0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"text-keep-upright":{type:"boolean",default:!0,requires:["text-field",{"text-rotation-alignment":"map"},{"symbol-placement":["line","line-center"]}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-transform":{type:"enum",values:{none:{},uppercase:{},lowercase:{}},default:"none",requires:["text-field"],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-offset":{type:"array",value:"number",units:"ems",length:2,default:[0,0],requires:["text-field",{"!":"text-radial-offset"}],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-allow-overlap":{type:"boolean",default:!1,requires:["text-field",{"!":"text-overlap"}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-overlap":{type:"enum",values:{never:{},always:{},cooperative:{}},requires:["text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-ignore-placement":{type:"boolean",default:!1,requires:["text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-optional":{type:"boolean",default:!1,requires:["text-field","icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible",expression:{interpolated:!1,parameters:["global-state"]},"property-type":"data-constant"}},layout_raster:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible",expression:{interpolated:!1,parameters:["global-state"]},"property-type":"data-constant"}},layout_hillshade:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible",expression:{interpolated:!1,parameters:["global-state"]},"property-type":"data-constant"}},"layout_color-relief":{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible",expression:{interpolated:!1,parameters:["global-state"]},"property-type":"data-constant"}},filter:{type:"boolean",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},filter_operator:{type:"enum",values:{"==":{},"!=":{},">":{},">=":{},"<":{},"<=":{},in:{},"!in":{},all:{},any:{},none:{},has:{},"!has":{}}},geometry_type:{type:"enum",values:{Point:{},LineString:{},Polygon:{}}},function:{expression:{type:"expression"},stops:{type:"array",value:"function_stop"},base:{type:"number",default:1,minimum:0},property:{type:"string",default:"$zoom"},type:{type:"enum",values:{identity:{},exponential:{},interval:{},categorical:{}},default:"exponential"},colorSpace:{type:"enum",values:{rgb:{},lab:{},hcl:{}},default:"rgb"},default:{type:"*",required:!1}},function_stop:{type:"array",minimum:0,maximum:24,value:["number","color"],length:2},expression:{type:"array",value:"expression_name",minimum:1},light:{anchor:{type:"enum",default:"viewport",values:{map:{},viewport:{}},"property-type":"data-constant",transition:!1,expression:{interpolated:!1,parameters:["zoom"]}},position:{type:"array",default:[1.15,210,30],length:3,value:"number","property-type":"data-constant",transition:!0,expression:{interpolated:!0,parameters:["zoom"]}},color:{type:"color","property-type":"data-constant",default:"#ffffff",expression:{interpolated:!0,parameters:["zoom"]},transition:!0},intensity:{type:"number","property-type":"data-constant",default:.5,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0}},sky:{"sky-color":{type:"color","property-type":"data-constant",default:"#88C6FC",expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"horizon-color":{type:"color","property-type":"data-constant",default:"#ffffff",expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"fog-color":{type:"color","property-type":"data-constant",default:"#ffffff",expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"fog-ground-blend":{type:"number","property-type":"data-constant",default:.5,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"horizon-fog-blend":{type:"number","property-type":"data-constant",default:.8,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"sky-horizon-blend":{type:"number","property-type":"data-constant",default:.8,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"atmosphere-blend":{type:"number","property-type":"data-constant",default:.8,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0}},terrain:{source:{type:"string",required:!0},exaggeration:{type:"number",minimum:0,default:1}},projection:{type:{type:"projectionDefinition",default:"mercator","property-type":"data-constant",transition:!1,expression:{interpolated:!0,parameters:["zoom"]}}},paint:["paint_fill","paint_line","paint_circle","paint_heatmap","paint_fill-extrusion","paint_symbol","paint_raster","paint_hillshade","paint_color-relief","paint_background"],paint_fill:{"fill-antialias":{type:"boolean",default:!0,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"fill-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"fill-pattern"}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-outline-color":{type:"color",transition:!0,requires:[{"!":"fill-pattern"},{"fill-antialias":!0}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"fill-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["fill-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"fill-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"}},"paint_fill-extrusion":{"fill-extrusion-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"fill-extrusion-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"fill-extrusion-pattern"}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"fill-extrusion-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["fill-extrusion-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"fill-extrusion-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"},"fill-extrusion-height":{type:"number",default:0,minimum:0,units:"meters",transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-base":{type:"number",default:0,minimum:0,units:"meters",transition:!0,requires:["fill-extrusion-height"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-vertical-gradient":{type:"boolean",default:!0,transition:!1,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"}},paint_line:{"line-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"line-pattern"}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"line-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["line-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"line-width":{type:"number",default:1,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-gap-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-offset":{type:"number",default:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-blur":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-dasharray":{type:"array",value:"number",minimum:0,transition:!0,units:"line widths",requires:[{"!":"line-pattern"}],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"},"line-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"},"line-gradient":{type:"color",transition:!1,requires:[{"!":"line-dasharray"},{"!":"line-pattern"},{source:"geojson",has:{lineMetrics:!0}}],expression:{interpolated:!0,parameters:["line-progress"]},"property-type":"color-ramp"}},paint_circle:{"circle-radius":{type:"number",default:5,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-color":{type:"color",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-blur":{type:"number",default:0,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"circle-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["circle-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"circle-pitch-scale":{type:"enum",values:{map:{},viewport:{}},default:"map",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"circle-pitch-alignment":{type:"enum",values:{map:{},viewport:{}},default:"viewport",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"circle-stroke-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-stroke-color":{type:"color",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-stroke-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"}},paint_heatmap:{"heatmap-radius":{type:"number",default:30,minimum:1,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"heatmap-weight":{type:"number",default:1,minimum:0,transition:!1,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"heatmap-intensity":{type:"number",default:1,minimum:0,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"heatmap-color":{type:"color",default:["interpolate",["linear"],["heatmap-density"],0,"rgba(0, 0, 255, 0)",.1,"royalblue",.3,"cyan",.5,"lime",.7,"yellow",1,"red"],transition:!1,expression:{interpolated:!0,parameters:["heatmap-density"]},"property-type":"color-ramp"},"heatmap-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"}},paint_symbol:{"icon-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-color":{type:"color",default:"#000000",transition:!0,requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-halo-color":{type:"color",default:"rgba(0, 0, 0, 0)",transition:!0,requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-halo-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-halo-blur":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"icon-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["icon-image","icon-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-color":{type:"color",default:"#000000",transition:!0,overridable:!0,requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-halo-color":{type:"color",default:"rgba(0, 0, 0, 0)",transition:!0,requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-halo-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-halo-blur":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"text-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["text-field","text-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"}},paint_raster:{"raster-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-hue-rotate":{type:"number",default:0,period:360,transition:!0,units:"degrees",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-brightness-min":{type:"number",default:0,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-brightness-max":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-saturation":{type:"number",default:0,minimum:-1,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-contrast":{type:"number",default:0,minimum:-1,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},resampling:{type:"enum",values:{linear:{},nearest:{}},default:"linear",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"raster-resampling":{type:"enum",values:{linear:{},nearest:{}},default:"linear",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"raster-fade-duration":{type:"number",default:300,minimum:0,transition:!1,units:"milliseconds",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"}},paint_hillshade:{"hillshade-illumination-direction":{type:"numberArray",default:335,minimum:0,maximum:359,transition:!1,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-illumination-altitude":{type:"numberArray",default:45,minimum:0,maximum:90,transition:!1,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-illumination-anchor":{type:"enum",values:{map:{},viewport:{}},default:"viewport",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-exaggeration":{type:"number",default:.5,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-shadow-color":{type:"colorArray",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-highlight-color":{type:"colorArray",default:"#FFFFFF",transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-accent-color":{type:"color",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-method":{type:"enum",values:{standard:{},basic:{},combined:{},igor:{},multidirectional:{}},default:"standard",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},resampling:{type:"enum",values:{linear:{},nearest:{}},default:"linear",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"}},"paint_color-relief":{"color-relief-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"color-relief-color":{type:"color",transition:!1,expression:{interpolated:!0,parameters:["elevation"]},"property-type":"color-ramp"},resampling:{type:"enum",values:{linear:{},nearest:{}},default:"linear",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"}},paint_background:{"background-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"background-pattern"}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"background-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"cross-faded"},"background-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"}},transition:{duration:{type:"number",default:300,minimum:0,units:"milliseconds"},delay:{type:"number",default:0,minimum:0,units:"milliseconds"}},"property-type":{"data-driven":{type:"property-type"},"cross-faded":{type:"property-type"},"cross-faded-data-driven":{type:"property-type"},"color-ramp":{type:"property-type"},"data-constant":{type:"property-type"},constant:{type:"property-type"}},promoteId:{"*":{type:"string"}},interpolation:{type:"array",value:"interpolation_name",minimum:1},interpolation_name:{type:"enum",values:{linear:{syntax:{overloads:[{parameters:[],"output-type":"interpolation"}],parameters:[]}},exponential:{syntax:{overloads:[{parameters:["base"],"output-type":"interpolation"}],parameters:[{name:"base",type:"number literal"}]}},"cubic-bezier":{syntax:{overloads:[{parameters:["x1","y1","x2","y2"],"output-type":"interpolation"}],parameters:[{name:"x1",type:"number literal"},{name:"y1",type:"number literal"},{name:"x2",type:"number literal"},{name:"y2",type:"number literal"}]}}}}};let Ba=["type","source","source-layer","minzoom","maxzoom","filter","layout"];function Oa(r,e){let i={};for(let o in r)o!=="ref"&&(i[o]=r[o]);return Ba.forEach((o=>{o in e&&(i[o]=e[o])})),i}function it(r,e){if(Array.isArray(r)){if(!Array.isArray(e)||r.length!==e.length)return!1;for(let i=0;i`:r.itemType.kind==="value"?"array":`array<${e}>`}return r.kind}let ys=[zr,be,Fe,je,Ei,gs,To,ur,Yt(Oe),_s,Po,Bn,On,So];function Nn(r,e){if(e.kind==="error")return null;if(r.kind==="array"){if(e.kind==="array"&&(e.N===0&&e.itemType.kind==="value"||!Nn(r.itemType,e.itemType))&&(typeof r.N!="number"||r.N===e.N))return null}else{if(r.kind===e.kind)return null;if(r.kind==="value"){for(let i of ys)if(!Nn(i,e))return null}}return`Expected ${rt(r)} but found ${rt(e)} instead.`}function Io(r,e){return e.some((i=>i.kind===r.kind))}function on(r,e){return e.some((i=>i==="null"?r===null:i==="array"?Array.isArray(r):i==="object"?r&&!Array.isArray(r)&&typeof r=="object":i===typeof r))}function Xi(r,e){return r.kind==="array"&&e.kind==="array"?r.itemType.kind===e.itemType.kind&&typeof r.N=="number":r.kind===e.kind}let ac=.96422,sn=.82521,vs=4/29,bt=6/29,lc=3*bt*bt,cc=bt*bt*bt,Mo=Math.PI/180,hc=180/Math.PI;function uc(r){return(r%=360)<0&&(r+=360),r}function dc([r,e,i,o]){let s,l,h=ja((.2225045*(r=xs(r))+.7168786*(e=xs(e))+.0606169*(i=xs(i)))/1);r===e&&e===i?s=l=h:(s=ja((.4360747*r+.3850649*e+.1430804*i)/ac),l=ja((.0139322*r+.0971045*e+.7141733*i)/sn));let d=116*h-16;return[d<0?0:d,500*(s-h),200*(h-l),o]}function xs(r){return r<=.04045?r/12.92:Math.pow((r+.055)/1.055,2.4)}function ja(r){return r>cc?Math.pow(r,1/3):r/lc+vs}function Ua([r,e,i,o]){let s=(r+16)/116,l=isNaN(e)?s:s+e/500,h=isNaN(i)?s:s-i/200;return s=1*$a(s),l=ac*$a(l),h=sn*$a(h),[Ga(3.1338561*l-1.6168667*s-.4906146*h),Ga(-.9787684*l+1.9161415*s+.033454*h),Ga(.0719453*l-.2289914*s+1.4052427*h),o]}function Ga(r){return(r=r<=.00304?12.92*r:1.055*Math.pow(r,1/2.4)-.055)<0?0:r>1?1:r}function $a(r){return r>bt?r*r*r:lc*(r-vs)}let Bh=Object.hasOwn||function(r,e){return Object.prototype.hasOwnProperty.call(r,e)};function Eo(r,e){return Bh(r,e)?r[e]:void 0}function bs(r){return parseInt(r.padEnd(2,r),16)/255}function pc(r,e){return Vn(e?r/100:r,0,1)}function Vn(r,e,i){return Math.min(Math.max(e,r),i)}function Za(r){return!r.some(Number.isNaN)}let Co={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]};function Rr(r,e,i){return r+i*(e-r)}function jn(r,e,i){return r.map(((o,s)=>Rr(o,e[s],i)))}class Ve{constructor(e,i,o,s=1,l=!0){this.r=e,this.g=i,this.b=o,this.a=s,l||(this.r*=s,this.g*=s,this.b*=s,s||this.overwriteGetter("rgb",[e,i,o,s]))}static parse(e){if(e instanceof Ve)return e;if(typeof e!="string")return;let i=(function(o){if((o=o.toLowerCase().trim())==="transparent")return[0,0,0,0];let s=Eo(Co,o);if(s){let[h,d,g]=s;return[h/255,d/255,g/255,1]}if(o.startsWith("#")&&/^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/.test(o)){let h=o.length<6?1:2,d=1;return[bs(o.slice(d,d+=h)),bs(o.slice(d,d+=h)),bs(o.slice(d,d+=h)),bs(o.slice(d,d+h)||"ff")]}if(o.startsWith("rgb")){let h=o.match(/^rgba?\(\s*([\de.+-]+)(%)?(?:\s+|\s*(,)\s*)([\de.+-]+)(%)?(?:\s+|\s*(,)\s*)([\de.+-]+)(%)?(?:\s*([,\/])\s*([\de.+-]+)(%)?)?\s*\)$/);if(h){let[d,g,m,v,_,T,b,I,M,A,D,L]=h,R=[v||" ",b||" ",A].join("");if(R===" "||R===" /"||R===",,"||R===",,,"){let F=[m,T,M].join(""),O=F==="%%%"?100:F===""?255:0;if(O){let V=[Vn(+g/O,0,1),Vn(+_/O,0,1),Vn(+I/O,0,1),D?pc(+D,L):1];if(Za(V))return V}}return}}let l=o.match(/^hsla?\(\s*([\de.+-]+)(?:deg)?(?:\s+|\s*(,)\s*)([\de.+-]+)%(?:\s+|\s*(,)\s*)([\de.+-]+)%(?:\s*([,\/])\s*([\de.+-]+)(%)?)?\s*\)$/);if(l){let[h,d,g,m,v,_,T,b,I]=l,M=[g||" ",v||" ",T].join("");if(M===" "||M===" /"||M===",,"||M===",,,"){let A=[+d,Vn(+m,0,100),Vn(+_,0,100),b?pc(+b,I):1];if(Za(A))return(function([D,L,R,F]){function O(V){let Y=(V+D/30)%12,J=L*Math.min(R,1-R);return R-J*Math.max(-1,Math.min(Y-3,9-Y,1))}return D=uc(D),L/=100,R/=100,[O(0),O(8),O(4),F]})(A)}}})(e);return i?new Ve(...i,!1):void 0}get rgb(){let{r:e,g:i,b:o,a:s}=this,l=s||1/0;return this.overwriteGetter("rgb",[e/l,i/l,o/l,s])}get hcl(){return this.overwriteGetter("hcl",(function(e){let[i,o,s,l]=dc(e),h=Math.sqrt(o*o+s*s);return[Math.round(1e4*h)?uc(Math.atan2(s,o)*hc):NaN,h,i,l]})(this.rgb))}get lab(){return this.overwriteGetter("lab",dc(this.rgb))}overwriteGetter(e,i){return Object.defineProperty(this,e,{value:i}),i}toString(){let[e,i,o,s]=this.rgb;return`rgba(${[e,i,o].map((l=>Math.round(255*l))).join(",")},${s})`}static interpolate(e,i,o,s="rgb"){switch(s){case"rgb":{let[l,h,d,g]=jn(e.rgb,i.rgb,o);return new Ve(l,h,d,g,!1)}case"hcl":{let[l,h,d,g]=e.hcl,[m,v,_,T]=i.hcl,b,I;if(isNaN(l)||isNaN(m))isNaN(l)?isNaN(m)?b=NaN:(b=m,d!==1&&d!==0||(I=v)):(b=l,_!==1&&_!==0||(I=h));else{let R=m-l;m>l&&R>180?R-=360:m180&&(R+=360),b=l+o*R}let[M,A,D,L]=(function([R,F,O,V]){return R=isNaN(R)?0:R*Mo,Ua([O,Math.cos(R)*F,Math.sin(R)*F,V])})([b,I??Rr(h,v,o),Rr(d,_,o),Rr(g,T,o)]);return new Ve(M,A,D,L,!1)}case"lab":{let[l,h,d,g]=Ua(jn(e.lab,i.lab,o));return new Ve(l,h,d,g,!1)}}}}Ve.black=new Ve(0,0,0,1),Ve.white=new Ve(1,1,1,1),Ve.transparent=new Ve(0,0,0,0),Ve.red=new Ve(1,0,0,1);class qa{constructor(e,i,o){this.sensitivity=e?i?"variant":"case":i?"accent":"base",this.locale=o,this.collator=new Intl.Collator(this.locale?this.locale:[],{sensitivity:this.sensitivity,usage:"search"})}compare(e,i){return this.collator.compare(e,i)}resolvedLocale(){return new Intl.Collator(this.locale?this.locale:[]).resolvedOptions().locale}}let Oh=["bottom","center","top"];class Wa{constructor(e,i,o,s,l,h){this.text=e,this.image=i,this.scale=o,this.fontStack=s,this.textColor=l,this.verticalAlign=h}}class xi{constructor(e){this.sections=e}static fromString(e){return new xi([new Wa(e,null,null,null,null,null)])}isEmpty(){return this.sections.length===0||!this.sections.some((e=>e.text.length!==0||e.image&&e.image.name.length!==0))}static factory(e){return e instanceof xi?e:xi.fromString(e)}toString(){return this.sections.length===0?"":this.sections.map((e=>e.text)).join("")}}class ei{constructor(e){this.values=e.slice()}static parse(e){if(e instanceof ei)return e;if(typeof e=="number")return new ei([e,e,e,e]);if(Array.isArray(e)&&!(e.length<1||e.length>4)){for(let i of e)if(typeof i!="number")return;switch(e.length){case 1:e=[e[0],e[0],e[0],e[0]];break;case 2:e=[e[0],e[1],e[0],e[1]];break;case 3:e=[e[0],e[1],e[2],e[1]]}return new ei(e)}}toString(){return JSON.stringify(this.values)}static interpolate(e,i,o){return new ei(jn(e.values,i.values,o))}}class ft{constructor(e){this.values=e.slice()}static parse(e){if(e instanceof ft)return e;if(typeof e=="number")return new ft([e]);if(Array.isArray(e)){for(let i of e)if(typeof i!="number")return;return new ft(e)}}toString(){return JSON.stringify(this.values)}static interpolate(e,i,o){return new ft(jn(e.values,i.values,o))}}class ke{constructor(e){this.values=e.slice()}static parse(e){if(e instanceof ke)return e;if(typeof e=="string"){let o=Ve.parse(e);return o?new ke([o]):void 0}if(!Array.isArray(e))return;let i=[];for(let o of e){if(typeof o!="string")return;let s=Ve.parse(o);if(!s)return;i.push(s)}return new ke(i)}toString(){return JSON.stringify(this.values)}static interpolate(e,i,o,s="rgb"){let l=[];if(e.values.length!=i.values.length)throw new Error(`colorArray: Arrays have mismatched length (${e.values.length} vs. ${i.values.length}), cannot interpolate.`);for(let h=0;h=0&&r<=255&&typeof e=="number"&&e>=0&&e<=255&&typeof i=="number"&&i>=0&&i<=255?o===void 0||typeof o=="number"&&o>=0&&o<=1?null:`Invalid rgba value [${[r,e,i,o].join(", ")}]: 'a' must be between 0 and 1.`:`Invalid rgba value [${(typeof o=="number"?[r,e,i,o]:[r,e,i]).join(", ")}]: 'r', 'g', and 'b' must be between 0 and 255.`}function Lr(r){if(r===null||typeof r=="string"||typeof r=="boolean"||typeof r=="number"||r instanceof hi||r instanceof Ve||r instanceof qa||r instanceof xi||r instanceof ei||r instanceof ft||r instanceof ke||r instanceof ci||r instanceof Ci)return!0;if(Array.isArray(r)){for(let e of r)if(!Lr(e))return!1;return!0}if(typeof r=="object"){for(let e in r)if(!Lr(r[e]))return!1;return!0}return!1}function St(r){if(r===null)return zr;if(typeof r=="string")return Fe;if(typeof r=="boolean")return je;if(typeof r=="number")return be;if(r instanceof Ve)return Ei;if(r instanceof hi)return gs;if(r instanceof qa)return wo;if(r instanceof xi)return To;if(r instanceof ei)return _s;if(r instanceof ft)return Po;if(r instanceof ke)return Bn;if(r instanceof ci)return So;if(r instanceof Ci)return On;if(Array.isArray(r)){let e=r.length,i;for(let o of r){let s=St(o);if(i){if(i===s)continue;i=Oe;break}i=s}return Yt(i||Oe,e)}return ur}function an(r){let e=typeof r;return r===null?"":e==="string"||e==="number"||e==="boolean"?String(r):r instanceof Ve||r instanceof hi||r instanceof xi||r instanceof ei||r instanceof ft||r instanceof ke||r instanceof ci||r instanceof Ci?r.toString():JSON.stringify(r)}class ir{constructor(e,i){this.type=e,this.value=i}static parse(e,i){if(e.length!==2)return i.error(`'literal' expression requires exactly one argument, but found ${e.length-1} instead.`);if(!Lr(e[1]))return i.error("invalid value");let o=e[1],s=St(o),l=i.expectedType;return s.kind!=="array"||s.N!==0||!l||l.kind!=="array"||typeof l.N=="number"&&l.N!==0||(s=l),new ir(s,o)}evaluate(){return this.value}eachChild(){}outputDefined(){return!0}}let ws={string:Fe,number:be,boolean:je,object:ur};class bi{constructor(e,i){this.type=e,this.args=i}static parse(e,i){if(e.length<2)return i.error("Expected at least one argument.");let o,s=1,l=e[0];if(l==="array"){let d,g;if(e.length>2){let m=e[1];if(typeof m!="string"||!(m in ws)||m==="object")return i.error('The item type argument of "array" must be one of string, number, boolean',1);d=ws[m],s++}else d=Oe;if(e.length>3){if(e[2]!==null&&(typeof e[2]!="number"||e[2]<0||e[2]!==Math.floor(e[2])))return i.error('The length argument to "array" must be a positive integer literal',2);g=e[2],s++}o=Yt(d,g)}else{if(!ws[l])throw new Error(`Types doesn't contain name = ${l}`);o=ws[l]}let h=[];for(;se.outputDefined()))}}let ln={"to-boolean":je,"to-color":Ei,"to-number":be,"to-string":Fe};class dr{constructor(e,i){this.type=e,this.args=i}static parse(e,i){if(e.length<2)return i.error("Expected at least one argument.");let o=e[0];if(!ln[o])throw new Error(`Can't parse ${o} as it is not part of the known types`);if((o==="to-boolean"||o==="to-string")&&e.length!==2)return i.error("Expected one argument.");let s=ln[o],l=[];for(let h=1;h4?`Invalid rgba value ${JSON.stringify(i)}: expected an array containing either three or four numeric values.`:Un(i[0],i[1],i[2],i[3]),!o))return new Ve(i[0]/255,i[1]/255,i[2]/255,i[3])}throw new at(o||`Could not parse color from value '${typeof i=="string"?i:JSON.stringify(i)}'`)}case"padding":{let i;for(let o of this.args){i=o.evaluate(e);let s=ei.parse(i);if(s)return s}throw new at(`Could not parse padding from value '${typeof i=="string"?i:JSON.stringify(i)}'`)}case"numberArray":{let i;for(let o of this.args){i=o.evaluate(e);let s=ft.parse(i);if(s)return s}throw new at(`Could not parse numberArray from value '${typeof i=="string"?i:JSON.stringify(i)}'`)}case"colorArray":{let i;for(let o of this.args){i=o.evaluate(e);let s=ke.parse(i);if(s)return s}throw new at(`Could not parse colorArray from value '${typeof i=="string"?i:JSON.stringify(i)}'`)}case"variableAnchorOffsetCollection":{let i;for(let o of this.args){i=o.evaluate(e);let s=ci.parse(i);if(s)return s}throw new at(`Could not parse variableAnchorOffsetCollection from value '${typeof i=="string"?i:JSON.stringify(i)}'`)}case"number":{let i=null;for(let o of this.args){if(i=o.evaluate(e),i===null)return 0;let s=Number(i);if(!isNaN(s))return s}throw new at(`Could not convert ${JSON.stringify(i)} to number.`)}case"formatted":return xi.fromString(an(this.args[0].evaluate(e)));case"resolvedImage":return Ci.fromString(an(this.args[0].evaluate(e)));case"projectionDefinition":return this.args[0].evaluate(e);default:return an(this.args[0].evaluate(e))}}eachChild(e){this.args.forEach(e)}outputDefined(){return this.args.every((e=>e.outputDefined()))}}let fc=["Unknown","Point","LineString","Polygon"];class Ha{constructor(){this.globals=null,this.feature=null,this.featureState=null,this.formattedSection=null,this._parseColorCache=new Map,this.availableImages=null,this.canonical=null}id(){return this.feature&&"id"in this.feature?this.feature.id:null}geometryType(){return this.feature?typeof this.feature.type=="number"?fc[this.feature.type]:this.feature.type:null}geometry(){return this.feature&&"geometry"in this.feature?this.feature.geometry:null}canonicalID(){return this.canonical}properties(){return this.feature&&this.feature.properties||{}}parseColor(e){let i=this._parseColorCache.get(e);return i||(i=Ve.parse(e),this._parseColorCache.set(e,i)),i}}class cn{constructor(e,i,o=[],s,l=new Va,h=[]){this.registry=e,this.path=o,this.key=o.map((d=>`[${d}]`)).join(""),this.scope=l,this.errors=h,this.expectedType=s,this._isConstant=i}parse(e,i,o,s,l={}){return i?this.concat(i,o,s)._parse(e,l):this._parse(e,l)}_parse(e,i){function o(s,l,h){return h==="assert"?new bi(l,[s]):h==="coerce"?new dr(l,[s]):s}if(e!==null&&typeof e!="string"&&typeof e!="boolean"&&typeof e!="number"||(e=["literal",e]),Array.isArray(e)){if(e.length===0)return this.error('Expected an array with at least one element. If you wanted a literal array, use ["literal", []].');let s=e[0];if(typeof s!="string")return this.error(`Expression name must be a string, but found ${typeof s} instead. If you wanted a literal array, use ["literal", [...]].`,0),null;let l=this.registry[s];if(l){let h=l.parse(e,this);if(!h)return null;if(this.expectedType){let d=this.expectedType,g=h.type;if(d.kind!=="string"&&d.kind!=="number"&&d.kind!=="boolean"&&d.kind!=="object"&&d.kind!=="array"||g.kind!=="value"){if(d.kind==="projectionDefinition"&&["string","array"].includes(g.kind)||["color","formatted","resolvedImage"].includes(d.kind)&&["value","string"].includes(g.kind)||["padding","numberArray"].includes(d.kind)&&["value","number","array"].includes(g.kind)||d.kind==="colorArray"&&["value","string","array"].includes(g.kind)||d.kind==="variableAnchorOffsetCollection"&&["value","array"].includes(g.kind))h=o(h,d,i.typeAnnotation||"coerce");else if(this.checkSubtype(d,g))return null}else h=o(h,d,i.typeAnnotation||"assert")}if(!(h instanceof ir)&&h.type.kind!=="resolvedImage"&&this._isConstant(h)){let d=new Ha;try{h=new ir(h.type,h.evaluate(d))}catch(g){return this.error(g.message),null}}return h}return this.error(`Unknown expression "${s}". If you wanted a literal array, use ["literal", [...]].`,0)}return this.error(e===void 0?"'undefined' value invalid. Use null instead.":typeof e=="object"?'Bare objects invalid. Use ["literal", {...}] instead.':`Expected an array, but found ${typeof e} instead.`)}concat(e,i,o){let s=typeof e=="number"?this.path.concat(e):this.path,l=o?this.scope.concat(o):this.scope;return new cn(this.registry,this._isConstant,s,i||null,l,this.errors)}error(e,...i){let o=`${this.key}${i.map((s=>`[${s}]`)).join("")}`;this.errors.push(new Xt(o,e))}checkSubtype(e,i){let o=Nn(e,i);return o&&this.error(o),o}}class lt{constructor(e,i){this.type=i.type,this.bindings=[].concat(e),this.result=i}evaluate(e){return this.result.evaluate(e)}eachChild(e){for(let i of this.bindings)e(i[1]);e(this.result)}static parse(e,i){if(e.length<4)return i.error(`Expected at least 3 arguments, but found ${e.length-1} instead.`);let o=[];for(let l=1;l=o.length)throw new at(`Array index out of bounds: ${i} > ${o.length-1}.`);if(i!==Math.floor(i))throw new at(`Array index must be an integer, but found ${i} instead.`);return o[i]}eachChild(e){e(this.index),e(this.input)}outputDefined(){return!1}}class Ne{constructor(e,i){this.type=je,this.needle=e,this.haystack=i}static parse(e,i){if(e.length!==3)return i.error(`Expected 2 arguments, but found ${e.length-1} instead.`);let o=i.parse(e[1],1,Oe),s=i.parse(e[2],2,Oe);return o&&s?Io(o.type,[je,Fe,be,zr,Oe])?new Ne(o,s):i.error(`Expected first argument to be of type boolean, string, number or null, but found ${rt(o.type)} instead`):null}evaluate(e){let i=this.needle.evaluate(e),o=this.haystack.evaluate(e);if(!o)return!1;if(!on(i,["boolean","string","number","null"]))throw new at(`Expected first argument to be of type boolean, string, number or null, but found ${rt(St(i))} instead.`);if(!on(o,["string","array"]))throw new at(`Expected second argument to be of type array or string, but found ${rt(St(o))} instead.`);return o.indexOf(i)>=0}eachChild(e){e(this.needle),e(this.haystack)}outputDefined(){return!0}}class $n{constructor(e,i,o){this.type=be,this.needle=e,this.haystack=i,this.fromIndex=o}static parse(e,i){if(e.length<=2||e.length>=5)return i.error(`Expected 2 or 3 arguments, but found ${e.length-1} instead.`);let o=i.parse(e[1],1,Oe),s=i.parse(e[2],2,Oe);if(!o||!s)return null;if(!Io(o.type,[je,Fe,be,zr,Oe]))return i.error(`Expected first argument to be of type boolean, string, number or null, but found ${rt(o.type)} instead`);if(e.length===4){let l=i.parse(e[3],3,be);return l?new $n(o,s,l):null}return new $n(o,s)}evaluate(e){let i=this.needle.evaluate(e),o=this.haystack.evaluate(e);if(!on(i,["boolean","string","number","null"]))throw new at(`Expected first argument to be of type boolean, string, number or null, but found ${rt(St(i))} instead.`);let s;if(this.fromIndex&&(s=this.fromIndex.evaluate(e)),on(o,["string"])){let l=o.indexOf(i,s);return l===-1?-1:[...o.slice(0,l)].length}if(on(o,["array"]))return o.indexOf(i,s);throw new at(`Expected second argument to be of type array or string, but found ${rt(St(o))} instead.`)}eachChild(e){e(this.needle),e(this.haystack),this.fromIndex&&e(this.fromIndex)}outputDefined(){return!1}}class He{constructor(e,i,o,s,l,h){this.inputType=e,this.type=i,this.input=o,this.cases=s,this.outputs=l,this.otherwise=h}static parse(e,i){if(e.length<5)return i.error(`Expected at least 4 arguments, but found only ${e.length-1}.`);if(e.length%2!=1)return i.error("Expected an even number of arguments.");let o,s;i.expectedType&&i.expectedType.kind!=="value"&&(s=i.expectedType);let l={},h=[];for(let m=2;mNumber.MAX_SAFE_INTEGER)return T.error(`Branch labels must be integers no larger than ${Number.MAX_SAFE_INTEGER}.`);if(typeof I=="number"&&Math.floor(I)!==I)return T.error("Numeric branch labels must be integer values.");if(o){if(T.checkSubtype(o,St(I)))return null}else o=St(I);if(l[String(I)]!==void 0)return T.error("Branch labels must be unique.");l[String(I)]=h.length}let b=i.parse(_,m,s);if(!b)return null;s=s||b.type,h.push(b)}let d=i.parse(e[1],1,Oe);if(!d)return null;let g=i.parse(e[e.length-1],e.length-1,s);return g?d.type.kind!=="value"&&i.concat(1).checkSubtype(o,d.type)?null:new He(o,s,d,l,h,g):null}evaluate(e){let i=this.input.evaluate(e);return(St(i)===this.inputType&&this.outputs[this.cases[i]]||this.otherwise).evaluate(e)}eachChild(e){e(this.input),this.outputs.forEach(e),e(this.otherwise)}outputDefined(){return this.outputs.every((e=>e.outputDefined()))&&this.otherwise.outputDefined()}}class Yi{constructor(e,i,o){this.type=e,this.branches=i,this.otherwise=o}static parse(e,i){if(e.length<4)return i.error(`Expected at least 3 arguments, but found only ${e.length-1}.`);if(e.length%2!=0)return i.error("Expected an odd number of arguments.");let o;i.expectedType&&i.expectedType.kind!=="value"&&(o=i.expectedType);let s=[];for(let h=1;hi.outputDefined()))&&this.otherwise.outputDefined()}}class Zn{constructor(e,i,o,s){this.type=e,this.input=i,this.beginIndex=o,this.endIndex=s}static parse(e,i){if(e.length<=2||e.length>=5)return i.error(`Expected 2 or 3 arguments, but found ${e.length-1} instead.`);let o=i.parse(e[1],1,Oe),s=i.parse(e[2],2,be);if(!o||!s)return null;if(!Io(o.type,[Yt(Oe),Fe,Oe]))return i.error(`Expected first argument to be of type array or string, but found ${rt(o.type)} instead`);if(e.length===4){let l=i.parse(e[3],3,be);return l?new Zn(o.type,o,s,l):null}return new Zn(o.type,o,s)}evaluate(e){let i=this.input.evaluate(e),o=this.beginIndex.evaluate(e),s;if(this.endIndex&&(s=this.endIndex.evaluate(e)),on(i,["string"]))return[...i].slice(o,s).join("");if(on(i,["array"]))return i.slice(o,s);throw new at(`Expected first argument to be of type array or string, but found ${rt(St(i))} instead.`)}eachChild(e){e(this.input),e(this.beginIndex),this.endIndex&&e(this.endIndex)}outputDefined(){return!1}}function hn(r,e){let i=r.length-1,o,s,l=0,h=i,d=0;for(;l<=h;)if(d=Math.floor((l+h)/2),o=r[d],s=r[d+1],o<=e){if(d===i||ee))throw new at("Input is not a number.");h=d-1}return 0}class qn{constructor(e,i,o){this.type=e,this.input=i,this.labels=[],this.outputs=[];for(let[s,l]of o)this.labels.push(s),this.outputs.push(l)}static parse(e,i){if(e.length-1<4)return i.error(`Expected at least 4 arguments, but found only ${e.length-1}.`);if((e.length-1)%2!=0)return i.error("Expected an even number of arguments.");let o=i.parse(e[1],1,be);if(!o)return null;let s=[],l=null;i.expectedType&&i.expectedType.kind!=="value"&&(l=i.expectedType);for(let h=1;h=d)return i.error('Input/output pairs for "step" expressions must be arranged with input values in strictly ascending order.',m);let _=i.parse(g,v,l);if(!_)return null;l=l||_.type,s.push([d,_])}return new qn(l,o,s)}evaluate(e){let i=this.labels,o=this.outputs;if(i.length===1)return o[0].evaluate(e);let s=this.input.evaluate(e);if(s<=i[0])return o[0].evaluate(e);let l=i.length;return s>=i[l-1]?o[l-1].evaluate(e):o[hn(i,s)].evaluate(e)}eachChild(e){e(this.input);for(let i of this.outputs)e(i)}outputDefined(){return this.outputs.every((e=>e.outputDefined()))}}function Xa(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var Ts,mc,gc=(function(){if(mc)return Ts;function r(e,i,o,s){this.cx=3*e,this.bx=3*(o-e)-this.cx,this.ax=1-this.cx-this.bx,this.cy=3*i,this.by=3*(s-i)-this.cy,this.ay=1-this.cy-this.by,this.p1x=e,this.p1y=i,this.p2x=o,this.p2y=s}return mc=1,Ts=r,r.prototype={sampleCurveX:function(e){return((this.ax*e+this.bx)*e+this.cx)*e},sampleCurveY:function(e){return((this.ay*e+this.by)*e+this.cy)*e},sampleCurveDerivativeX:function(e){return(3*this.ax*e+2*this.bx)*e+this.cx},solveCurveX:function(e,i){if(i===void 0&&(i=1e-6),e<0)return 0;if(e>1)return 1;for(var o=e,s=0;s<8;s++){var l=this.sampleCurveX(o)-e;if(Math.abs(l)l?d=o:g=o,o=.5*(g-d)+d;return o},solve:function(e,i){return this.sampleCurveY(this.solveCurveX(e,i))}},Ts})(),_c=Xa(gc);class Et{constructor(e,i,o,s,l){this.type=e,this.operator=i,this.interpolation=o,this.input=s,this.labels=[],this.outputs=[];for(let[h,d]of l)this.labels.push(h),this.outputs.push(d)}static interpolationFactor(e,i,o,s){let l=0;if(e.name==="exponential")l=Ot(i,e.base,o,s);else if(e.name==="linear")l=Ot(i,1,o,s);else if(e.name==="cubic-bezier"){let h=e.controlPoints;l=new _c(h[0],h[1],h[2],h[3]).solve(Ot(i,1,o,s))}return l}static parse(e,i){let[o,s,l,...h]=e;if(!Array.isArray(s)||s.length===0)return i.error("Expected an interpolation type expression.",1);if(s[0]==="linear")s={name:"linear"};else if(s[0]==="exponential"){let m=s[1];if(typeof m!="number")return i.error("Exponential interpolation requires a numeric base.",1,1);s={name:"exponential",base:m}}else{if(s[0]!=="cubic-bezier")return i.error(`Unknown interpolation type ${String(s[0])}`,1,0);{let m=s.slice(1);if(m.length!==4||m.some((v=>typeof v!="number"||v<0||v>1)))return i.error("Cubic bezier interpolation requires four numeric arguments with values between 0 and 1.",1);s={name:"cubic-bezier",controlPoints:m}}}if(e.length-1<4)return i.error(`Expected at least 4 arguments, but found only ${e.length-1}.`);if((e.length-1)%2!=0)return i.error("Expected an even number of arguments.");if(l=i.parse(l,2,be),!l)return null;let d=[],g=null;o!=="interpolate-hcl"&&o!=="interpolate-lab"||i.expectedType==Bn?i.expectedType&&i.expectedType.kind!=="value"&&(g=i.expectedType):g=Ei;for(let m=0;m=v)return i.error('Input/output pairs for "interpolate" expressions must be arranged with input values in strictly ascending order.',T);let I=i.parse(_,b,g);if(!I)return null;g=g||I.type,d.push([v,I])}return Xi(g,be)||Xi(g,gs)||Xi(g,Ei)||Xi(g,_s)||Xi(g,Po)||Xi(g,Bn)||Xi(g,So)||Xi(g,Yt(be))?new Et(g,o,s,l,d):i.error(`Type ${rt(g)} is not interpolatable.`)}evaluate(e){let i=this.labels,o=this.outputs;if(i.length===1)return o[0].evaluate(e);let s=this.input.evaluate(e);if(s<=i[0])return o[0].evaluate(e);let l=i.length;if(s>=i[l-1])return o[l-1].evaluate(e);let h=hn(i,s),d=Et.interpolationFactor(this.interpolation,s,i[h],i[h+1]),g=o[h].evaluate(e),m=o[h+1].evaluate(e);switch(this.operator){case"interpolate":switch(this.type.kind){case"number":return Rr(g,m,d);case"color":return Ve.interpolate(g,m,d);case"padding":return ei.interpolate(g,m,d);case"colorArray":return ke.interpolate(g,m,d);case"numberArray":return ft.interpolate(g,m,d);case"variableAnchorOffsetCollection":return ci.interpolate(g,m,d);case"array":return jn(g,m,d);case"projectionDefinition":return hi.interpolate(g,m,d)}case"interpolate-hcl":switch(this.type.kind){case"color":return Ve.interpolate(g,m,d,"hcl");case"colorArray":return ke.interpolate(g,m,d,"hcl")}case"interpolate-lab":switch(this.type.kind){case"color":return Ve.interpolate(g,m,d,"lab");case"colorArray":return ke.interpolate(g,m,d,"lab")}}}eachChild(e){e(this.input);for(let i of this.outputs)e(i)}outputDefined(){return this.outputs.every((e=>e.outputDefined()))}}function Ot(r,e,i,o){let s=o-i,l=r-i;return s===0?0:e===1?l/s:(Math.pow(e,l)-1)/(Math.pow(e,s)-1)}let Ai={color:Ve.interpolate,number:Rr,padding:ei.interpolate,numberArray:ft.interpolate,colorArray:ke.interpolate,variableAnchorOffsetCollection:ci.interpolate,array:jn};class Ao{constructor(e,i){this.type=e,this.args=i}static parse(e,i){if(e.length<2)return i.error("Expected at least one argument.");let o=null,s=i.expectedType;s&&s.kind!=="value"&&(o=s);let l=[];for(let d of e.slice(1)){let g=i.parse(d,1+l.length,o,void 0,{typeAnnotation:"omit"});if(!g)return null;o=o||g.type,l.push(g)}if(!o)throw new Error("No output type");let h=s&&l.some((d=>Nn(s,d.type)));return new Ao(h?Oe:o,l)}evaluate(e){let i,o=null,s=0;for(let l of this.args)if(s++,o=l.evaluate(e),o&&o instanceof Ci&&!o.available&&(i||(i=o.name),o=null,s===this.args.length&&(o=i)),o!==null)break;return o}eachChild(e){this.args.forEach(e)}outputDefined(){return this.args.every((e=>e.outputDefined()))}}function Do(r,e){return r==="=="||r==="!="?e.kind==="boolean"||e.kind==="string"||e.kind==="number"||e.kind==="null"||e.kind==="value":e.kind==="string"||e.kind==="number"||e.kind==="value"}function Lt(r,e,i,o){return o.compare(e,i)===0}function un(r,e,i){let o=r!=="=="&&r!=="!=";return class qf{constructor(l,h,d){this.type=je,this.lhs=l,this.rhs=h,this.collator=d,this.hasUntypedArgument=l.type.kind==="value"||h.type.kind==="value"}static parse(l,h){if(l.length!==3&&l.length!==4)return h.error("Expected two or three arguments.");let d=l[0],g=h.parse(l[1],1,Oe);if(!g)return null;if(!Do(d,g.type))return h.concat(1).error(`"${d}" comparisons are not supported for type '${rt(g.type)}'.`);let m=h.parse(l[2],2,Oe);if(!m)return null;if(!Do(d,m.type))return h.concat(2).error(`"${d}" comparisons are not supported for type '${rt(m.type)}'.`);if(g.type.kind!==m.type.kind&&g.type.kind!=="value"&&m.type.kind!=="value")return h.error(`Cannot compare types '${rt(g.type)}' and '${rt(m.type)}'.`);o&&(g.type.kind==="value"&&m.type.kind!=="value"?g=new bi(m.type,[g]):g.type.kind!=="value"&&m.type.kind==="value"&&(m=new bi(g.type,[m])));let v=null;if(l.length===4){if(g.type.kind!=="string"&&m.type.kind!=="string"&&g.type.kind!=="value"&&m.type.kind!=="value")return h.error("Cannot use collator to compare non-string types.");if(v=h.parse(l[3],3,wo),!v)return null}return new qf(g,m,v)}evaluate(l){let h=this.lhs.evaluate(l),d=this.rhs.evaluate(l);if(o&&this.hasUntypedArgument){let g=St(h),m=St(d);if(g.kind!==m.kind||g.kind!=="string"&&g.kind!=="number")throw new at(`Expected arguments for "${r}" to be (string, string) or (number, number), but found (${g.kind}, ${m.kind}) instead.`)}if(this.collator&&!o&&this.hasUntypedArgument){let g=St(h),m=St(d);if(g.kind!=="string"||m.kind!=="string")return e(l,h,d)}return this.collator?i(l,h,d,this.collator.evaluate(l)):e(l,h,d)}eachChild(l){l(this.lhs),l(this.rhs),this.collator&&l(this.collator)}outputDefined(){return!0}}}let Ya=un("==",(function(r,e,i){return e===i}),Lt),yc=un("!=",(function(r,e,i){return e!==i}),(function(r,e,i,o){return!Lt(0,e,i,o)})),Nh=un("<",(function(r,e,i){return e",(function(r,e,i){return e>i}),(function(r,e,i,o){return o.compare(e,i)>0})),Ps=un("<=",(function(r,e,i){return e<=i}),(function(r,e,i,o){return o.compare(e,i)<=0})),Ka=un(">=",(function(r,e,i){return e>=i}),(function(r,e,i,o){return o.compare(e,i)>=0}));class Ss{constructor(e,i,o){this.type=wo,this.locale=o,this.caseSensitive=e,this.diacriticSensitive=i}static parse(e,i){if(e.length!==2)return i.error("Expected one argument.");let o=e[1];if(typeof o!="object"||Array.isArray(o))return i.error("Collator options argument must be an object.");let s=i.parse(o["case-sensitive"]!==void 0&&o["case-sensitive"],1,je);if(!s)return null;let l=i.parse(o["diacritic-sensitive"]!==void 0&&o["diacritic-sensitive"],1,je);if(!l)return null;let h=null;return o.locale&&(h=i.parse(o.locale,1,Fe),!h)?null:new Ss(s,l,h)}evaluate(e){return new qa(this.caseSensitive.evaluate(e),this.diacriticSensitive.evaluate(e),this.locale?this.locale.evaluate(e):null)}eachChild(e){e(this.caseSensitive),e(this.diacriticSensitive),this.locale&&e(this.locale)}outputDefined(){return!1}}class Is{constructor(e,i,o,s,l,h){this.type=Fe,this.number=e,this.locale=i,this.currency=o,this.unit=s,this.minFractionDigits=l,this.maxFractionDigits=h}static parse(e,i){if(e.length!==3)return i.error("Expected two arguments.");let o=i.parse(e[1],1,be);if(!o)return null;let s=e[2];if(typeof s!="object"||Array.isArray(s))return i.error("NumberFormat options argument must be an object.");let l=null;if(s.locale&&(l=i.parse(s.locale,1,Fe),!l))return null;let h=null;if(s.currency&&(h=i.parse(s.currency,1,Fe),!h))return null;let d=null;if(s.unit&&(d=i.parse(s.unit,1,Fe),!d))return null;if(h&&d)return i.error("NumberFormat options `currency` and `unit` are mutually exclusive");let g=null;if(s["min-fraction-digits"]&&(g=i.parse(s["min-fraction-digits"],1,be),!g))return null;let m=null;return s["max-fraction-digits"]&&(m=i.parse(s["max-fraction-digits"],1,be),!m)?null:new Is(o,l,h,d,g,m)}evaluate(e){return new Intl.NumberFormat(this.locale?this.locale.evaluate(e):[],{style:this.currency?"currency":this.unit?"unit":"decimal",currency:this.currency?this.currency.evaluate(e):void 0,unit:this.unit?this.unit.evaluate(e):void 0,minimumFractionDigits:this.minFractionDigits?this.minFractionDigits.evaluate(e):void 0,maximumFractionDigits:this.maxFractionDigits?this.maxFractionDigits.evaluate(e):void 0}).format(this.number.evaluate(e))}eachChild(e){e(this.number),this.locale&&e(this.locale),this.currency&&e(this.currency),this.unit&&e(this.unit),this.minFractionDigits&&e(this.minFractionDigits),this.maxFractionDigits&&e(this.maxFractionDigits)}outputDefined(){return!1}}class dn{constructor(e){this.type=To,this.sections=e}static parse(e,i){if(e.length<2)return i.error("Expected at least one argument.");let o=e[1];if(!Array.isArray(o)&&typeof o=="object")return i.error("First argument must be an image or text section.");let s=[],l=!1;for(let h=1;h<=e.length-1;++h){let d=e[h];if(l&&typeof d=="object"&&!Array.isArray(d)){l=!1;let g=null;if(d["font-scale"]&&(g=i.parse(d["font-scale"],1,be),!g))return null;let m=null;if(d["text-font"]&&(m=i.parse(d["text-font"],1,Yt(Fe)),!m))return null;let v=null;if(d["text-color"]&&(v=i.parse(d["text-color"],1,Ei),!v))return null;let _=null;if(d["vertical-align"]){if(typeof d["vertical-align"]=="string"&&!Oh.includes(d["vertical-align"]))return i.error(`'vertical-align' must be one of: 'bottom', 'center', 'top' but found '${d["vertical-align"]}' instead.`);if(_=i.parse(d["vertical-align"],1,Fe),!_)return null}let T=s[s.length-1];T.scale=g,T.font=m,T.textColor=v,T.verticalAlign=_}else{let g=i.parse(e[h],1,Oe);if(!g)return null;let m=g.type.kind;if(m!=="string"&&m!=="value"&&m!=="null"&&m!=="resolvedImage")return i.error("Formatted text type must be 'string', 'value', 'image' or 'null'.");l=!0,s.push({content:g,scale:null,font:null,textColor:null,verticalAlign:null})}}return new dn(s)}evaluate(e){return new xi(this.sections.map((i=>{let o=i.content.evaluate(e);return St(o)===On?new Wa("",o,null,null,null,i.verticalAlign?i.verticalAlign.evaluate(e):null):new Wa(an(o),null,i.scale?i.scale.evaluate(e):null,i.font?i.font.evaluate(e).join(","):null,i.textColor?i.textColor.evaluate(e):null,i.verticalAlign?i.verticalAlign.evaluate(e):null)})))}eachChild(e){for(let i of this.sections)e(i.content),i.scale&&e(i.scale),i.font&&e(i.font),i.textColor&&e(i.textColor),i.verticalAlign&&e(i.verticalAlign)}outputDefined(){return!1}}class Hn{constructor(e){this.type=On,this.input=e}static parse(e,i){if(e.length!==2)return i.error("Expected two arguments.");let o=i.parse(e[1],1,Fe);return o?new Hn(o):i.error("No image name provided.")}evaluate(e){let i=this.input.evaluate(e),o=Ci.fromString(i);return o&&e.availableImages&&(o.available=e.availableImages.indexOf(i)>-1),o}eachChild(e){e(this.input)}outputDefined(){return!1}}class Di{constructor(e){this.type=be,this.input=e}static parse(e,i){if(e.length!==2)return i.error(`Expected 1 argument, but found ${e.length-1} instead.`);let o=i.parse(e[1],1);return o?o.type.kind!=="array"&&o.type.kind!=="string"&&o.type.kind!=="value"?i.error(`Expected argument of type string or array, but found ${rt(o.type)} instead.`):new Di(o):null}evaluate(e){let i=this.input.evaluate(e);if(typeof i=="string")return[...i].length;if(Array.isArray(i))return i.length;throw new at(`Expected value to be of type string or array, but found ${rt(St(i))} instead.`)}eachChild(e){e(this.input)}outputDefined(){return!1}}let Ki=8192;function Ms(r,e){let i=(180+r[0])/360,o=(180-180/Math.PI*Math.log(Math.tan(Math.PI/4+r[1]*Math.PI/360)))/360,s=Math.pow(2,e.z);return[Math.round(i*s*Ki),Math.round(o*s*Ki)]}function Ja(r,e){let i=Math.pow(2,e.z);return[(s=(r[0]/Ki+e.x)/i,360*s-180),(o=(r[1]/Ki+e.y)/i,360/Math.PI*Math.atan(Math.exp((180-360*o)*Math.PI/180))-90)];var o,s}function pn(r,e){r[0]=Math.min(r[0],e[0]),r[1]=Math.min(r[1],e[1]),r[2]=Math.max(r[2],e[0]),r[3]=Math.max(r[3],e[1])}function zo(r,e){return!(r[0]<=e[0]||r[2]>=e[2]||r[1]<=e[1]||r[3]>=e[3])}function Vh(r,e,i){let o=r[0]-e[0],s=r[1]-e[1],l=r[0]-i[0],h=r[1]-i[1];return o*h-l*s==0&&o*l<=0&&s*h<=0}function Es(r,e,i,o){return(s=[o[0]-i[0],o[1]-i[1]])[0]*(l=[e[0]-r[0],e[1]-r[1]])[1]-s[1]*l[0]!=0&&!(!xc(r,e,i,o)||!xc(i,o,r,e));var s,l}function jh(r,e,i){for(let o of i)for(let s=0;s(s=r)[1]!=(h=d[g+1])[1]>s[1]&&s[0]<(h[0]-l[0])*(s[1]-l[1])/(h[1]-l[1])+l[0]&&(o=!o)}var s,l,h;return o}function Uh(r,e){for(let i of e)if(pr(r,i))return!0;return!1}function Qa(r,e){for(let i of r)if(!pr(i,e))return!1;for(let i=0;i0&&d<0||h<0&&d>0}function Cs(r,e,i){let o=[];for(let s=0;si[2]){let s=.5*o,l=r[0]-i[0]>s?-o:i[0]-r[0]>s?o:0;l===0&&(l=r[0]-i[2]>s?-o:i[2]-r[0]>s?o:0),r[0]+=l}pn(e,r)}function Tc(r,e,i,o){let s=Math.pow(2,o.z)*Ki,l=[o.x*Ki,o.y*Ki],h=[];for(let d of r)for(let g of d){let m=[g.x+l[0],g.y+l[1]];wc(m,e,i,s),h.push(m)}return h}function Pc(r,e,i,o){let s=Math.pow(2,o.z)*Ki,l=[o.x*Ki,o.y*Ki],h=[];for(let g of r){let m=[];for(let v of g){let _=[v.x+l[0],v.y+l[1]];pn(e,_),m.push(_)}h.push(m)}if(e[2]-e[0]<=s/2){(d=e)[0]=d[1]=1/0,d[2]=d[3]=-1/0;for(let g of h)for(let m of g)wc(m,e,i,s)}var d;return h}class fn{constructor(e,i){this.type=je,this.geojson=e,this.geometries=i}static parse(e,i){if(e.length!==2)return i.error(`'within' expression requires exactly one argument, but found ${e.length-1} instead.`);if(Lr(e[1])){let o=e[1];if(o.type==="FeatureCollection"){let s=[];for(let l of o.features){let{type:h,coordinates:d}=l.geometry;h==="Polygon"&&s.push(d),h==="MultiPolygon"&&s.push(...d)}if(s.length)return new fn(o,{type:"MultiPolygon",coordinates:s})}else if(o.type==="Feature"){let s=o.geometry.type;if(s==="Polygon"||s==="MultiPolygon")return new fn(o,o.geometry)}else if(o.type==="Polygon"||o.type==="MultiPolygon")return new fn(o,o)}return i.error("'within' expression requires valid geojson object that contains polygon geometry type.")}evaluate(e){if(e.geometry()!=null&&e.canonicalID()!=null){if(e.geometryType()==="Point")return(function(i,o){let s=[1/0,1/0,-1/0,-1/0],l=[1/0,1/0,-1/0,-1/0],h=i.canonicalID();if(o.type==="Polygon"){let d=Cs(o.coordinates,l,h),g=Tc(i.geometry(),s,l,h);if(!zo(s,l))return!1;for(let m of g)if(!pr(m,d))return!1}if(o.type==="MultiPolygon"){let d=bc(o.coordinates,l,h),g=Tc(i.geometry(),s,l,h);if(!zo(s,l))return!1;for(let m of g)if(!Uh(m,d))return!1}return!0})(e,this.geometries);if(e.geometryType()==="LineString")return(function(i,o){let s=[1/0,1/0,-1/0,-1/0],l=[1/0,1/0,-1/0,-1/0],h=i.canonicalID();if(o.type==="Polygon"){let d=Cs(o.coordinates,l,h),g=Pc(i.geometry(),s,l,h);if(!zo(s,l))return!1;for(let m of g)if(!Qa(m,d))return!1}if(o.type==="MultiPolygon"){let d=bc(o.coordinates,l,h),g=Pc(i.geometry(),s,l,h);if(!zo(s,l))return!1;for(let m of g)if(!vc(m,d))return!1}return!0})(e,this.geometries)}return!1}eachChild(){}outputDefined(){return!0}}let el=class{constructor(r=[],e=(i,o)=>io?1:0){if(this.data=r,this.length=this.data.length,this.compare=e,this.length>0)for(let i=(this.length>>1)-1;i>=0;i--)this._down(i)}push(r){this.data.push(r),this._up(this.length++)}pop(){if(this.length===0)return;let r=this.data[0],e=this.data.pop();return--this.length>0&&(this.data[0]=e,this._down(0)),r}peek(){return this.data[0]}_up(r){let{data:e,compare:i}=this,o=e[r];for(;r>0;){let s=r-1>>1,l=e[s];if(i(o,l)>=0)break;e[r]=l,r=s}e[r]=o}_down(r){let{data:e,compare:i}=this,o=this.length>>1,s=e[r];for(;r=0)break;e[r]=e[l],r=l}e[r]=s}};function tl(r,e,i=0,o=r.length-1,s=Gh){for(;o>i;){if(o-i>600){let g=o-i+1,m=e-i+1,v=Math.log(g),_=.5*Math.exp(2*v/3),T=.5*Math.sqrt(v*_*(g-_)/g)*(m-g/2<0?-1:1);tl(r,e,Math.max(i,Math.floor(e-m*_/g+T)),Math.min(o,Math.floor(e+(g-m)*_/g+T)),s)}let l=r[e],h=i,d=o;for(Xn(r,i,e),s(r[o],l)>0&&Xn(r,i,o);h0;)d--}s(r[i],l)===0?Xn(r,i,d):(d++,Xn(r,d,o)),d<=e&&(i=d+1),e<=d&&(o=d-1)}}function Xn(r,e,i){let o=r[e];r[e]=r[i],r[i]=o}function Gh(r,e){return re?1:0}function As(r,e){if(r.length<=1)return[r];let i=[],o,s;for(let l of r){let h=Zh(l);h!==0&&(l.area=Math.abs(h),s===void 0&&(s=h<0),s===h<0?(o&&i.push(o),o=[l]):o.push(l))}if(o&&i.push(o),e>1)for(let l=0;l1?(m=e[g+1][0],v=e[g+1][1]):b>0&&(m+=_/this.kx*b,v+=T/this.ky*b)),_=this.wrap(i[0]-m)*this.kx,T=(i[1]-v)*this.ky;let I=_*_+T*T;I180;)e-=360;return e}}function Mc(r,e){return e[0]-r[0]}function Yn(r){return r[1]-r[0]+1}function rr(r,e){return r[1]>=r[0]&&r[1]r[1])return[null,null];let i=Yn(r);if(e){if(i===2)return[r,null];let s=Math.floor(i/2);return[[r[0],r[0]+s],[r[0]+s,r[1]]]}if(i===1)return[r,null];let o=Math.floor(i/2)-1;return[[r[0],r[0]+o],[r[0]+o+1,r[1]]]}function nl(r,e){if(!rr(e,r.length))return[1/0,1/0,-1/0,-1/0];let i=[1/0,1/0,-1/0,-1/0];for(let o=e[0];o<=e[1];++o)pn(i,r[o]);return i}function Ds(r){let e=[1/0,1/0,-1/0,-1/0];for(let i of r)for(let o of i)pn(e,o);return e}function ol(r){return r[0]!==-1/0&&r[1]!==-1/0&&r[2]!==1/0&&r[3]!==1/0}function sl(r,e,i){if(!ol(r)||!ol(e))return NaN;let o=0,s=0;return r[2]e[2]&&(o=r[0]-e[2]),r[1]>e[3]&&(s=r[1]-e[3]),r[3]=o)return o;if(zo(s,l)){if(Cc(r,e))return 0}else if(Cc(e,r))return 0;let h=1/0;for(let d of r)for(let g=0,m=d.length,v=m-1;g0;){let g=h.pop();if(g[0]>=l)continue;let m=g[1],v=e?50:100;if(Yn(m)<=v){if(!rr(m,r.length))return NaN;if(e){let _=Hh(r,m,i,o);if(isNaN(_)||_===0)return _;l=Math.min(l,_)}else for(let _=m[0];_<=m[1];++_){let T=Wh(r[_],i,o);if(l=Math.min(l,T),l===0)return 0}}else{let _=rl(m,e);Ac(h,l,o,r,d,_[0]),Ac(h,l,o,r,d,_[1])}}return l}function ks(r,e,i,o,s,l=1/0){let h=Math.min(l,s.distance(r[0],i[0]));if(h===0)return h;let d=new el([[0,[0,r.length-1],[0,i.length-1]]],Mc);for(;d.length>0;){let g=d.pop();if(g[0]>=h)continue;let m=g[1],v=g[2],_=e?50:100,T=o?50:100;if(Yn(m)<=_&&Yn(v)<=T){if(!rr(m,r.length)&&rr(v,i.length))return NaN;let b;if(e&&o)b=Ec(r,m,i,v,s),h=Math.min(h,b);else if(e&&!o){let I=r.slice(m[0],m[1]+1);for(let M=v[0];M<=v[1];++M)if(b=mn(i[M],I,s),h=Math.min(h,b),h===0)return h}else if(!e&&o){let I=i.slice(v[0],v[1]+1);for(let M=m[0];M<=m[1];++M)if(b=mn(r[M],I,s),h=Math.min(h,b),h===0)return h}else b=qh(r,m,i,v,s),h=Math.min(h,b)}else{let b=rl(m,e),I=rl(v,o);zs(d,h,s,r,i,b[0],I[0]),zs(d,h,s,r,i,b[0],I[1]),zs(d,h,s,r,i,b[1],I[0]),zs(d,h,s,r,i,b[1],I[1])}}return h}function ll(r){return r.type==="MultiPolygon"?r.coordinates.map((e=>({type:"Polygon",coordinates:e}))):r.type==="MultiLineString"?r.coordinates.map((e=>({type:"LineString",coordinates:e}))):r.type==="MultiPoint"?r.coordinates.map((e=>({type:"Point",coordinates:e}))):[r]}class gn{constructor(e,i){this.type=be,this.geojson=e,this.geometries=i}static parse(e,i){if(e.length!==2)return i.error(`'distance' expression requires exactly one argument, but found ${e.length-1} instead.`);if(Lr(e[1])){let o=e[1];if(o.type==="FeatureCollection")return new gn(o,o.features.map((s=>ll(s.geometry))).flat());if(o.type==="Feature")return new gn(o,ll(o.geometry));if("type"in o&&"coordinates"in o)return new gn(o,ll(o))}return i.error("'distance' expression requires valid geojson object that contains polygon geometry type.")}evaluate(e){if(e.geometry()!=null&&e.canonicalID()!=null){if(e.geometryType()==="Point")return(function(i,o){let s=i.geometry(),l=s.flat().map((g=>Ja([g.x,g.y],i.canonical)));if(s.length===0)return NaN;let h=new il(l[0][1]),d=1/0;for(let g of o){switch(g.type){case"Point":d=Math.min(d,ks(l,!1,[g.coordinates],!1,h,d));break;case"LineString":d=Math.min(d,ks(l,!1,g.coordinates,!0,h,d));break;case"Polygon":d=Math.min(d,Rs(l,!1,g.coordinates,h,d))}if(d===0)return d}return d})(e,this.geometries);if(e.geometryType()==="LineString")return(function(i,o){let s=i.geometry(),l=s.flat().map((g=>Ja([g.x,g.y],i.canonical)));if(s.length===0)return NaN;let h=new il(l[0][1]),d=1/0;for(let g of o){switch(g.type){case"Point":d=Math.min(d,ks(l,!0,[g.coordinates],!1,h,d));break;case"LineString":d=Math.min(d,ks(l,!0,g.coordinates,!0,h,d));break;case"Polygon":d=Math.min(d,Rs(l,!0,g.coordinates,h,d))}if(d===0)return d}return d})(e,this.geometries);if(e.geometryType()==="Polygon")return(function(i,o){let s=i.geometry();if(s.length===0||s[0].length===0)return NaN;let l=As(s,0).map((g=>g.map((m=>m.map((v=>Ja([v.x,v.y],i.canonical))))))),h=new il(l[0][0][0][1]),d=1/0;for(let g of o)for(let m of l){switch(g.type){case"Point":d=Math.min(d,Rs([g.coordinates],!1,m,h,d));break;case"LineString":d=Math.min(d,Rs(g.coordinates,!0,m,h,d));break;case"Polygon":d=Math.min(d,et(m,g.coordinates,h,d))}if(d===0)return d}return d})(e,this.geometries)}return NaN}eachChild(){}outputDefined(){return!0}}class ko{constructor(e){this.type=Oe,this.key=e}static parse(e,i){if(e.length!==2)return i.error(`Expected 1 argument, but found ${e.length-1} instead.`);let o=e[1];return o==null?i.error("Global state property must be defined."):typeof o!="string"?i.error(`Global state property must be string, but found ${typeof e[1]} instead.`):new ko(o)}evaluate(e){var i;let o=(i=e.globals)===null||i===void 0?void 0:i.globalState;return o&&Object.keys(o).length!==0?Eo(o,this.key):null}eachChild(){}outputDefined(){return!1}}let Kn={"==":Ya,"!=":yc,">":Wn,"<":Nh,">=":Ka,"<=":Ps,array:bi,at:qe,boolean:bi,case:Yi,coalesce:Ao,collator:Ss,format:dn,image:Hn,in:Ne,"index-of":$n,interpolate:Et,"interpolate-hcl":Et,"interpolate-lab":Et,length:Di,let:lt,literal:ir,match:He,number:bi,"number-format":Is,object:bi,slice:Zn,step:qn,string:bi,"to-boolean":dr,"to-color":dr,"to-number":dr,"to-string":dr,var:Gn,within:fn,distance:gn,"global-state":ko};class Vi{constructor(e,i,o,s){this.name=e,this.type=i,this._evaluate=o,this.args=s}evaluate(e){return this._evaluate(e,this.args)}eachChild(e){this.args.forEach(e)}outputDefined(){return!1}static parse(e,i){let o=e[0],s=Vi.definitions[o];if(!s)return i.error(`Unknown expression "${o}". If you wanted a literal array, use ["literal", [...]].`,0);let l=Array.isArray(s)?s[0]:s.type,h=Array.isArray(s)?[[s[1],s[2]]]:s.overloads,d=h.filter((([m])=>!Array.isArray(m)||m.length===e.length-1)),g=null;for(let[m,v]of d){g=new cn(i.registry,Ls,i.path,null,i.scope);let _=[],T=!1;for(let b=1;b{return T=_,Array.isArray(T)?`(${T.map(rt).join(", ")})`:`(${rt(T.type)}...)`;var T})).join(" | "),v=[];for(let _=1;_{i=e?i&&Ls(o):i&&o instanceof ir})),!!i&&Fs(r)&&Bs(r,["zoom","heatmap-density","elevation","line-progress","accumulated","is-supported-script"])}function Fs(r){if(r instanceof Vi&&(r.name==="get"&&r.args.length===1||r.name==="feature-state"||r.name==="has"&&r.args.length===1||r.name==="properties"||r.name==="geometry-type"||r.name==="id"||/^filter-/.test(r.name))||r instanceof fn||r instanceof gn)return!1;let e=!0;return r.eachChild((i=>{e&&!Fs(i)&&(e=!1)})),e}function Lo(r){if(r instanceof Vi&&r.name==="feature-state")return!1;let e=!0;return r.eachChild((i=>{e&&!Lo(i)&&(e=!1)})),e}function Bs(r,e){if(r instanceof Vi&&e.indexOf(r.name)>=0)return!1;let i=!0;return r.eachChild((o=>{i&&!Bs(o,e)&&(i=!1)})),i}function Rc(r){return{result:"success",value:r}}function Jn(r){return{result:"error",value:r}}function Qn(r){return r["property-type"]==="data-driven"||r["property-type"]==="cross-faded-data-driven"}function kc(r){return!!r.expression&&r.expression.parameters.indexOf("zoom")>-1}function hl(r){return!!r.expression&&r.expression.interpolated}function Ue(r){return r instanceof Number?"number":r instanceof String?"string":r instanceof Boolean?"boolean":Array.isArray(r)?"array":r===null?"null":typeof r}function Os(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)&&St(r)===ur}function Xh(r){return r}function Lc(r,e){let i=r.stops&&typeof r.stops[0][0]=="object",o=i||!(i||r.property!==void 0),s=r.type||(hl(e)?"exponential":"interval"),l=(function(v){switch(v.type){case"color":return Ve.parse;case"padding":return ei.parse;case"numberArray":return ft.parse;case"colorArray":return ke.parse;default:return null}})(e);if(l&&((r=nn({},r)).stops&&(r.stops=r.stops.map((v=>[v[0],l(v[1])]))),r.default=l(r.default?r.default:e.default)),r.colorSpace&&(h=r.colorSpace)!=="rgb"&&h!=="hcl"&&h!=="lab")throw new Error(`Unknown color space: "${r.colorSpace}"`);var h;let d=(function(v){switch(v){case"exponential":return Fc;case"interval":return Kh;case"categorical":return Yh;case"identity":return Jh;default:throw new Error(`Unknown function type "${v}"`)}})(s),g,m;if(s==="categorical"){g=Object.create(null);for(let v of r.stops)g[v[0]]=v[1];m=typeof r.stops[0][0]}if(i){let v={},_=[];for(let I=0;II[0])),evaluate:({zoom:I},M)=>Fc({stops:T,base:r.base},e,I).evaluate(I,M)}}if(o){let v=s==="exponential"?{name:"exponential",base:r.base!==void 0?r.base:1}:null;return{kind:"camera",interpolationType:v,interpolationFactor:Et.interpolationFactor.bind(void 0,v),zoomStops:r.stops.map((_=>_[0])),evaluate:({zoom:_})=>d(r,e,_,g,m)}}return{kind:"source",evaluate(v,_){let T=_&&_.properties?_.properties[r.property]:void 0;return T===void 0?Fo(r.default,e.default):d(r,e,T,g,m)}}}function Fo(r,e,i){return r!==void 0?r:e!==void 0?e:i!==void 0?i:void 0}function Yh(r,e,i,o,s){return Fo(typeof i===s?o[i]:void 0,r.default,e.default)}function Kh(r,e,i){if(Ue(i)!=="number")return Fo(r.default,e.default);let o=r.stops.length;if(o===1||i<=r.stops[0][0])return r.stops[0][1];if(i>=r.stops[o-1][0])return r.stops[o-1][1];let s=hn(r.stops.map((l=>l[0])),i);return r.stops[s][1]}function Fc(r,e,i){let o=r.base!==void 0?r.base:1;if(Ue(i)!=="number")return Fo(r.default,e.default);let s=r.stops.length;if(s===1||i<=r.stops[0][0])return r.stops[0][1];if(i>=r.stops[s-1][0])return r.stops[s-1][1];let l=hn(r.stops.map((v=>v[0])),i),h=(function(v,_,T,b){let I=b-T,M=v-T;return I===0?0:_===1?M/I:(Math.pow(_,M)-1)/(Math.pow(_,I)-1)})(i,o,r.stops[l][0],r.stops[l+1][0]),d=r.stops[l][1],g=r.stops[l+1][1],m=Ai[e.type]||Xh;return typeof d.evaluate=="function"?{evaluate(...v){let _=d.evaluate.apply(void 0,v),T=g.evaluate.apply(void 0,v);if(_!==void 0&&T!==void 0)return m(_,T,h,r.colorSpace)}}:m(d,g,h,r.colorSpace)}function Jh(r,e,i){switch(e.type){case"color":i=Ve.parse(i);break;case"formatted":i=xi.fromString(i.toString());break;case"resolvedImage":i=Ci.fromString(i.toString());break;case"padding":i=ei.parse(i);break;case"colorArray":i=ke.parse(i);break;case"numberArray":i=ft.parse(i);break;default:Ue(i)===e.type||e.type==="enum"&&e.values[i]||(i=void 0)}return Fo(i,r.default,e.default)}Vi.register(Kn,{error:[{kind:"error"},[Fe],(r,[e])=>{throw new at(e.evaluate(r))}],typeof:[Fe,[Oe],(r,[e])=>rt(St(e.evaluate(r)))],"to-rgba":[Yt(be,4),[Ei],(r,[e])=>{let[i,o,s,l]=e.evaluate(r).rgb;return[255*i,255*o,255*s,l]}],rgb:[Ei,[be,be,be],Dc],rgba:[Ei,[be,be,be,be],Dc],has:{type:je,overloads:[[[Fe],(r,[e])=>zc(e.evaluate(r),r.properties())],[[Fe,ur],(r,[e,i])=>zc(e.evaluate(r),i.evaluate(r))]]},get:{type:Oe,overloads:[[[Fe],(r,[e])=>cl(e.evaluate(r),r.properties())],[[Fe,ur],(r,[e,i])=>cl(e.evaluate(r),i.evaluate(r))]]},"feature-state":[Oe,[Fe],(r,[e])=>cl(e.evaluate(r),r.featureState||{})],properties:[ur,[],r=>r.properties()],"geometry-type":[Fe,[],r=>r.geometryType()],id:[Oe,[],r=>r.id()],zoom:[be,[],r=>r.globals.zoom],"heatmap-density":[be,[],r=>r.globals.heatmapDensity||0],elevation:[be,[],r=>r.globals.elevation||0],"line-progress":[be,[],r=>r.globals.lineProgress||0],accumulated:[Oe,[],r=>r.globals.accumulated===void 0?null:r.globals.accumulated],"+":[be,_n(be),(r,e)=>{let i=0;for(let o of e)i+=o.evaluate(r);return i}],"*":[be,_n(be),(r,e)=>{let i=1;for(let o of e)i*=o.evaluate(r);return i}],"-":{type:be,overloads:[[[be,be],(r,[e,i])=>e.evaluate(r)-i.evaluate(r)],[[be],(r,[e])=>-e.evaluate(r)]]},"/":[be,[be,be],(r,[e,i])=>e.evaluate(r)/i.evaluate(r)],"%":[be,[be,be],(r,[e,i])=>e.evaluate(r)%i.evaluate(r)],ln2:[be,[],()=>Math.LN2],pi:[be,[],()=>Math.PI],e:[be,[],()=>Math.E],"^":[be,[be,be],(r,[e,i])=>Math.pow(e.evaluate(r),i.evaluate(r))],sqrt:[be,[be],(r,[e])=>Math.sqrt(e.evaluate(r))],log10:[be,[be],(r,[e])=>Math.log(e.evaluate(r))/Math.LN10],ln:[be,[be],(r,[e])=>Math.log(e.evaluate(r))],log2:[be,[be],(r,[e])=>Math.log(e.evaluate(r))/Math.LN2],sin:[be,[be],(r,[e])=>Math.sin(e.evaluate(r))],cos:[be,[be],(r,[e])=>Math.cos(e.evaluate(r))],tan:[be,[be],(r,[e])=>Math.tan(e.evaluate(r))],asin:[be,[be],(r,[e])=>Math.asin(e.evaluate(r))],acos:[be,[be],(r,[e])=>Math.acos(e.evaluate(r))],atan:[be,[be],(r,[e])=>Math.atan(e.evaluate(r))],min:[be,_n(be),(r,e)=>Math.min(...e.map((i=>i.evaluate(r))))],max:[be,_n(be),(r,e)=>Math.max(...e.map((i=>i.evaluate(r))))],abs:[be,[be],(r,[e])=>Math.abs(e.evaluate(r))],round:[be,[be],(r,[e])=>{let i=e.evaluate(r);return i<0?-Math.round(-i):Math.round(i)}],floor:[be,[be],(r,[e])=>Math.floor(e.evaluate(r))],ceil:[be,[be],(r,[e])=>Math.ceil(e.evaluate(r))],"filter-==":[je,[Fe,Oe],(r,[e,i])=>r.properties()[e.value]===i.value],"filter-id-==":[je,[Oe],(r,[e])=>r.id()===e.value],"filter-type-==":[je,[Fe],(r,[e])=>r.geometryType()===e.value],"filter-<":[je,[Fe,Oe],(r,[e,i])=>{let o=r.properties()[e.value],s=i.value;return typeof o==typeof s&&o{let i=r.id(),o=e.value;return typeof i==typeof o&&i":[je,[Fe,Oe],(r,[e,i])=>{let o=r.properties()[e.value],s=i.value;return typeof o==typeof s&&o>s}],"filter-id->":[je,[Oe],(r,[e])=>{let i=r.id(),o=e.value;return typeof i==typeof o&&i>o}],"filter-<=":[je,[Fe,Oe],(r,[e,i])=>{let o=r.properties()[e.value],s=i.value;return typeof o==typeof s&&o<=s}],"filter-id-<=":[je,[Oe],(r,[e])=>{let i=r.id(),o=e.value;return typeof i==typeof o&&i<=o}],"filter->=":[je,[Fe,Oe],(r,[e,i])=>{let o=r.properties()[e.value],s=i.value;return typeof o==typeof s&&o>=s}],"filter-id->=":[je,[Oe],(r,[e])=>{let i=r.id(),o=e.value;return typeof i==typeof o&&i>=o}],"filter-has":[je,[Oe],(r,[e])=>e.value in r.properties()],"filter-has-id":[je,[],r=>r.id()!==null&&r.id()!==void 0],"filter-type-in":[je,[Yt(Fe)],(r,[e])=>e.value.indexOf(r.geometryType())>=0],"filter-id-in":[je,[Yt(Oe)],(r,[e])=>e.value.indexOf(r.id())>=0],"filter-in-small":[je,[Fe,Yt(Oe)],(r,[e,i])=>i.value.indexOf(r.properties()[e.value])>=0],"filter-in-large":[je,[Fe,Yt(Oe)],(r,[e,i])=>(function(o,s,l,h){for(;l<=h;){let d=l+h>>1;if(s[d]===o)return!0;s[d]>o?h=d-1:l=d+1}return!1})(r.properties()[e.value],i.value,0,i.value.length-1)],all:{type:je,overloads:[[[je,je],(r,[e,i])=>e.evaluate(r)&&i.evaluate(r)],[_n(je),(r,e)=>{for(let i of e)if(!i.evaluate(r))return!1;return!0}]]},any:{type:je,overloads:[[[je,je],(r,[e,i])=>e.evaluate(r)||i.evaluate(r)],[_n(je),(r,e)=>{for(let i of e)if(i.evaluate(r))return!0;return!1}]]},"!":[je,[je],(r,[e])=>!e.evaluate(r)],"is-supported-script":[je,[Fe],(r,[e])=>{let i=r.globals&&r.globals.isSupportedScript;return!i||i(e.evaluate(r))}],upcase:[Fe,[Fe],(r,[e])=>e.evaluate(r).toUpperCase()],downcase:[Fe,[Fe],(r,[e])=>e.evaluate(r).toLowerCase()],concat:[Fe,_n(Oe),(r,e)=>e.map((i=>an(i.evaluate(r)))).join("")],split:[Yt(Fe),[Fe,Fe],(r,[e,i])=>e.evaluate(r).split(i.evaluate(r))],join:[Fe,[Yt(Fe),Fe],(r,[e,i])=>e.evaluate(r).join(i.evaluate(r))],"resolved-locale":[Fe,[wo],(r,[e])=>e.evaluate(r).resolvedLocale()]});class Bo{constructor(e,i,o){this.expression=e,this._warningHistory={},this._evaluator=new Ha,this._defaultValue=i?(function(s){if(s.type==="color"&&Os(s.default))return new Ve(0,0,0,0);switch(s.type){case"color":return Ve.parse(s.default)||null;case"padding":return ei.parse(s.default)||null;case"numberArray":return ft.parse(s.default)||null;case"colorArray":return ke.parse(s.default)||null;case"variableAnchorOffsetCollection":return ci.parse(s.default)||null;case"projectionDefinition":return hi.parse(s.default)||null;default:return s.default===void 0?null:s.default}})(i):null,this._enumValues=i&&i.type==="enum"?i.values:null,this._globalState=o}evaluateWithoutErrorHandling(e,i,o,s,l,h){return this._globalState&&(e=to(e,this._globalState)),this._evaluator.globals=e,this._evaluator.feature=i,this._evaluator.featureState=o,this._evaluator.canonical=s,this._evaluator.availableImages=l||null,this._evaluator.formattedSection=h,this.expression.evaluate(this._evaluator)}evaluate(e,i,o,s,l,h){this._globalState&&(e=to(e,this._globalState)),this._evaluator.globals=e,this._evaluator.feature=i||null,this._evaluator.featureState=o||null,this._evaluator.canonical=s,this._evaluator.availableImages=l||null,this._evaluator.formattedSection=h||null;try{let d=this.expression.evaluate(this._evaluator);if(d==null||typeof d=="number"&&d!=d)return this._defaultValue;if(this._enumValues&&!(d in this._enumValues))throw new at(`Expected value to be one of ${Object.keys(this._enumValues).map((g=>JSON.stringify(g))).join(", ")}, but found ${JSON.stringify(d)} instead.`);return d}catch(d){return this._warningHistory[d.message]||(this._warningHistory[d.message]=!0,typeof console<"u"&&console.warn(d.message)),this._defaultValue}}}function Ns(r){return Array.isArray(r)&&r.length>0&&typeof r[0]=="string"&&r[0]in Kn}function Oo(r,e,i){let o=new cn(Kn,Ls,[],e?(function(l){let h={color:Ei,string:Fe,number:be,enum:Fe,boolean:je,formatted:To,padding:_s,numberArray:Po,colorArray:Bn,projectionDefinition:gs,resolvedImage:On,variableAnchorOffsetCollection:So};return l.type==="array"?Yt(h[l.value]||Oe,l.length):h[l.type]})(e):void 0),s=o.parse(r,void 0,void 0,void 0,e&&e.type==="string"?{typeAnnotation:"coerce"}:void 0);return s?Rc(new Bo(s,e,i)):Jn(o.errors)}class Vs{constructor(e,i,o){this.kind=e,this._styleExpression=i,this.isStateDependent=e!=="constant"&&!Lo(i.expression),this.globalStateRefs=eo(i.expression),this._globalState=o}evaluateWithoutErrorHandling(e,i,o,s,l,h){return this._globalState&&(e=to(e,this._globalState)),this._styleExpression.evaluateWithoutErrorHandling(e,i,o,s,l,h)}evaluate(e,i,o,s,l,h){return this._globalState&&(e=to(e,this._globalState)),this._styleExpression.evaluate(e,i,o,s,l,h)}}class js{constructor(e,i,o,s,l){this.kind=e,this.zoomStops=o,this._styleExpression=i,this.isStateDependent=e!=="camera"&&!Lo(i.expression),this.globalStateRefs=eo(i.expression),this.interpolationType=s,this._globalState=l}evaluateWithoutErrorHandling(e,i,o,s,l,h){return this._globalState&&(e=to(e,this._globalState)),this._styleExpression.evaluateWithoutErrorHandling(e,i,o,s,l,h)}evaluate(e,i,o,s,l,h){return this._globalState&&(e=to(e,this._globalState)),this._styleExpression.evaluate(e,i,o,s,l,h)}interpolationFactor(e,i,o){return this.interpolationType?Et.interpolationFactor(this.interpolationType,e,i,o):0}}function Bc(r,e,i){let o=Oo(r,e,i);if(o.result==="error")return o;let s=o.value.expression,l=Fs(s);if(!l&&!Qn(e))return Jn([new Xt("","data expressions not supported")]);let h=Bs(s,["zoom"]);if(!h&&!kc(e))return Jn([new Xt("","zoom expressions not supported")]);let d=yn(s);return d||h?d instanceof Xt?Jn([d]):d instanceof Et&&!hl(e)?Jn([new Xt("",'"interpolate" expressions cannot be used with this property')]):Rc(d?new js(l?"camera":"composite",o.value,d.labels,d instanceof Et?d.interpolation:void 0,i):new Vs(l?"constant":"source",o.value,i)):Jn([new Xt("",'"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.')])}class Us{constructor(e,i){this._parameters=e,this._specification=i,nn(this,Lc(this._parameters,this._specification))}static deserialize(e){return new Us(e._parameters,e._specification)}static serialize(e){return{_parameters:e._parameters,_specification:e._specification}}}function yn(r){let e=null;if(r instanceof lt)e=yn(r.result);else if(r instanceof Ao){for(let i of r.args)if(e=yn(i),e)break}else(r instanceof qn||r instanceof Et)&&r.input instanceof Vi&&r.input.name==="zoom"&&(e=r);return e instanceof Xt||r.eachChild((i=>{let o=yn(i);o instanceof Xt?e=o:!e&&o?e=new Xt("",'"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.'):e&&o&&e!==o&&(e=new Xt("",'Only one zoom-based "step" or "interpolate" subexpression may be used in an expression.'))})),e}function eo(r,e=new Set){return r instanceof ko&&e.add(r.key),r.eachChild((i=>{eo(i,e)})),e}function to(r,e){let{zoom:i,heatmapDensity:o,elevation:s,lineProgress:l,isSupportedScript:h,accumulated:d}=r??{};return{zoom:i,heatmapDensity:o,elevation:s,lineProgress:l,isSupportedScript:h,accumulated:d,globalState:e}}function ul(r){if(r===!0||r===!1)return!0;if(!Array.isArray(r)||r.length===0)return!1;switch(r[0]){case"has":return r.length>=2&&r[1]!=="$id"&&r[1]!=="$type";case"in":return r.length>=3&&(typeof r[1]!="string"||Array.isArray(r[2]));case"!in":case"!has":case"none":return!1;case"==":case"!=":case">":case">=":case"<":case"<=":return r.length!==3||Array.isArray(r[1])||Array.isArray(r[2]);case"any":case"all":for(let e of r.slice(1))if(!ul(e)&&typeof e!="boolean")return!1;return!0;default:return!0}}let Qh={type:"boolean",default:!1,transition:!1,"property-type":"data-driven",expression:{interpolated:!1,parameters:["zoom","feature"]}};function No(r,e){if(r==null)return{filter:()=>!0,needGeometry:!1,getGlobalStateRefs:()=>new Set};ul(r)||(r=Vo(r));let i=Oo(r,Qh,e);if(i.result==="error")throw new Error(i.value.map((o=>`${o.key}: ${o.message}`)).join(", "));return{filter:(o,s,l)=>i.value.evaluate(o,s,{},l),needGeometry:dl(r),getGlobalStateRefs:()=>eo(i.value.expression)}}function eu(r,e){return re?1:0}function dl(r){if(!Array.isArray(r))return!1;if(r[0]==="within"||r[0]==="distance")return!0;for(let e=1;e"||e==="<="||e===">="?pl(r[1],r[2],e):e==="any"?(i=r.slice(1),["any"].concat(i.map(Vo))):e==="all"?["all"].concat(r.slice(1).map(Vo)):e==="none"?["all"].concat(r.slice(1).map(Vo).map(jo)):e==="in"?Oc(r[1],r.slice(2)):e==="!in"?jo(Oc(r[1],r.slice(2))):e==="has"?fl(r[1]):e!=="!has"||jo(fl(r[1]));var i}function pl(r,e,i){switch(r){case"$type":return[`filter-type-${i}`,e];case"$id":return[`filter-id-${i}`,e];default:return[`filter-${i}`,r,e]}}function Oc(r,e){if(e.length===0)return!1;switch(r){case"$type":return["filter-type-in",["literal",e]];case"$id":return["filter-id-in",["literal",e]];default:return e.length>200&&!e.some((i=>typeof i!=typeof e[0]))?["filter-in-large",r,["literal",e.sort(eu)]]:["filter-in-small",r,["literal",e]]}}function fl(r){switch(r){case"$type":return!0;case"$id":return["filter-has-id"];default:return["filter-has",r]}}function jo(r){return["!",r]}function Gs(r){let e=typeof r;if(e==="number"||e==="boolean"||e==="string"||r==null)return JSON.stringify(r);if(Array.isArray(r)){let s="[";for(let l of r)s+=`${Gs(l)},`;return`${s}]`}let i=Object.keys(r).sort(),o="{";for(let s=0;so.maximum?[new _e(e,i,`${i} is greater than the maximum value ${o.maximum}`)]:[]}function Zs(r){let e=r.valueSpec,i=It(r.value.type),o,s,l,h={},d=i!=="categorical"&&r.value.property===void 0,g=!d,m=Ue(r.value.stops)==="array"&&Ue(r.value.stops[0])==="array"&&Ue(r.value.stops[0][0])==="object",v=wi({key:r.key,value:r.value,valueSpec:r.styleSpec.function,validateSpec:r.validateSpec,style:r.style,styleSpec:r.styleSpec,objectElementValidators:{stops:function(b){if(i==="identity")return[new _e(b.key,b.value,'identity function may not have a "stops" property')];let I=[],M=b.value;return I=I.concat($s({key:b.key,value:M,valueSpec:b.valueSpec,validateSpec:b.validateSpec,style:b.style,styleSpec:b.styleSpec,arrayElementValidator:_})),Ue(M)==="array"&&M.length===0&&I.push(new _e(b.key,M,"array must have at least one stop")),I},default:function(b){return b.validateSpec({key:b.key,value:b.value,valueSpec:e,validateSpec:b.validateSpec,style:b.style,styleSpec:b.styleSpec})}}});return i==="identity"&&d&&v.push(new _e(r.key,r.value,'missing required property "property"')),i==="identity"||r.value.stops||v.push(new _e(r.key,r.value,'missing required property "stops"')),i==="exponential"&&r.valueSpec.expression&&!hl(r.valueSpec)&&v.push(new _e(r.key,r.value,"exponential functions not supported")),r.styleSpec.$version>=8&&(g&&!Qn(r.valueSpec)?v.push(new _e(r.key,r.value,"property functions not supported")):d&&!kc(r.valueSpec)&&v.push(new _e(r.key,r.value,"zoom functions not supported"))),i!=="categorical"&&!m||r.value.property!==void 0||v.push(new _e(r.key,r.value,'"property" property is required')),v;function _(b){let I=[],M=b.value,A=b.key;if(Ue(M)!=="array")return[new _e(A,M,`array expected, ${Ue(M)} found`)];if(M.length!==2)return[new _e(A,M,`array length 2 expected, length ${M.length} found`)];if(m){if(Ue(M[0])!=="object")return[new _e(A,M,`object expected, ${Ue(M[0])} found`)];if(M[0].zoom===void 0)return[new _e(A,M,"object stop key must have zoom")];if(M[0].value===void 0)return[new _e(A,M,"object stop key must have value")];if(l&&l>It(M[0].zoom))return[new _e(A,M[0].zoom,"stop zoom values must appear in ascending order")];It(M[0].zoom)!==l&&(l=It(M[0].zoom),s=void 0,h={}),I=I.concat(wi({key:`${A}[0]`,value:M[0],valueSpec:{zoom:{}},validateSpec:b.validateSpec,style:b.style,styleSpec:b.styleSpec,objectElementValidators:{zoom:io,value:T}}))}else I=I.concat(T({key:`${A}[0]`,value:M[0],validateSpec:b.validateSpec,style:b.style,styleSpec:b.styleSpec},M));return Ns(vn(M[1]))?I.concat([new _e(`${A}[1]`,M[1],"expressions are not allowed in function stops.")]):I.concat(b.validateSpec({key:`${A}[1]`,value:M[1],valueSpec:e,validateSpec:b.validateSpec,style:b.style,styleSpec:b.styleSpec}))}function T(b,I){let M=Ue(b.value),A=It(b.value),D=b.value!==null?b.value:I;if(o){if(M!==o)return[new _e(b.key,D,`${M} stop domain type must match previous stop domain type ${o}`)]}else o=M;if(M!=="number"&&M!=="string"&&M!=="boolean")return[new _e(b.key,D,"stop domain value must be a number, string, or boolean")];if(M!=="number"&&i!=="categorical"){let L=`number expected, ${M} found`;return Qn(e)&&i===void 0&&(L+='\nIf you intended to use a categorical function, specify `"type": "categorical"`.'),[new _e(b.key,D,L)]}return i!=="categorical"||M!=="number"||isFinite(A)&&Math.floor(A)===A?i!=="categorical"&&M==="number"&&s!==void 0&&Anew _e(`${r.key}${o.key}`,r.value,o.message)));let i=e.value.expression||e.value._styleExpression.expression;if(r.expressionContext==="property"&&r.propertyKey==="text-font"&&!i.outputDefined())return[new _e(r.key,r.value,`Invalid data expression for "${r.propertyKey}". Output values must be contained as literals within the expression.`)];if(r.expressionContext==="property"&&r.propertyType==="layout"&&!Lo(i))return[new _e(r.key,r.value,'"feature-state" data expressions are not supported with layout properties.')];if(r.expressionContext==="filter"&&!Lo(i))return[new _e(r.key,r.value,'"feature-state" data expressions are not supported with filters.')];if(r.expressionContext&&r.expressionContext.indexOf("cluster")===0){if(!Bs(i,["zoom","feature-state"]))return[new _e(r.key,r.value,'"zoom" and "feature-state" expressions are not supported with cluster properties.')];if(r.expressionContext==="cluster-initial"&&!Fs(i))return[new _e(r.key,r.value,"Feature data expressions are not supported with initial expression part of cluster properties.")]}return[]}function Uo(r){let e=r.key,i=r.value,o=Ue(i);return o!=="string"?[new _e(e,i,`color expected, ${o} found`)]:Ve.parse(String(i))?[]:[new _e(e,i,`color expected, "${i}" found`)]}function xn(r){let e=r.key,i=r.value,o=r.valueSpec,s=[];return Array.isArray(o.values)?o.values.indexOf(It(i))===-1&&s.push(new _e(e,i,`expected one of [${o.values.join(", ")}], ${JSON.stringify(i)} found`)):Object.keys(o.values).indexOf(It(i))===-1&&s.push(new _e(e,i,`expected one of [${Object.keys(o.values).join(", ")}], ${JSON.stringify(i)} found`)),s}function ro(r){return ul(vn(r.value))?Fr(nn({},r,{expressionContext:"filter",valueSpec:{value:"boolean"}})):Vc(r)}function Vc(r){let e=r.value,i=r.key;if(Ue(e)!=="array")return[new _e(i,e,`array expected, ${Ue(e)} found`)];let o=r.styleSpec,s,l=[];if(e.length<1)return[new _e(i,e,"filter array must have at least 1 element")];switch(l=l.concat(xn({key:`${i}[0]`,value:e[0],valueSpec:o.filter_operator,style:r.style,styleSpec:r.styleSpec})),It(e[0])){case"<":case"<=":case">":case">=":e.length>=2&&It(e[1])==="$type"&&l.push(new _e(i,e,`"$type" cannot be use with operator "${e[0]}"`));case"==":case"!=":e.length!==3&&l.push(new _e(i,e,`filter array for operator "${e[0]}" must have 3 elements`));case"in":case"!in":e.length>=2&&(s=Ue(e[1]),s!=="string"&&l.push(new _e(`${i}[1]`,e[1],`string expected, ${s} found`)));for(let h=2;h{_ in s&&o.push(new _e(l,s[_],`"${_}" is prohibited for ref layers`))})),h.layers.forEach((_=>{It(_.id)===m&&(v=_)})),v?v.ref?o.push(new _e(l,s.ref,"ref cannot reference another ref layer")):g=It(v.type):o.push(new _e(l,s.ref,`ref layer "${m}" not found`))}else if(g!=="background")if(s.source){let v=h.sources&&h.sources[s.source],_=v&&It(v.type);v?_==="vector"&&g==="raster"?o.push(new _e(l,s.source,`layer "${s.id}" requires a raster source`)):_!=="raster-dem"&&g==="hillshade"||_!=="raster-dem"&&g==="color-relief"?o.push(new _e(l,s.source,`layer "${s.id}" requires a raster-dem source`)):_==="raster"&&g!=="raster"?o.push(new _e(l,s.source,`layer "${s.id}" requires a vector source`)):_!=="vector"||s["source-layer"]?_==="raster-dem"&&g!=="hillshade"&&g!=="color-relief"?o.push(new _e(l,s.source,"raster-dem source can only be used with layer type 'hillshade' or 'color-relief'.")):g!=="line"||!s.paint||!s.paint["line-gradient"]||_==="geojson"&&v.lineMetrics||o.push(new _e(l,s,`layer "${s.id}" specifies a line-gradient, which requires a GeoJSON source with \`lineMetrics\` enabled.`)):o.push(new _e(l,s,`layer "${s.id}" must specify a "source-layer"`)):o.push(new _e(l,s.source,`source "${s.source}" not found`))}else o.push(new _e(l,s,'missing required property "source"'));return g==="raster"&&(!((e=s.paint)===null||e===void 0)&&e.resampling)&&(!((i=s.paint)===null||i===void 0)&&i["raster-resampling"])&&o.push(new _e(l,s.paint,`layer "${s.id}" redundantly specifies "resampling" and "raster-resampling" paint properties, but only one is allowed. It is advised to use "resampling".`)),o=o.concat(wi({key:l,value:s,valueSpec:d.layer,style:r.style,styleSpec:r.styleSpec,validateSpec:r.validateSpec,objectElementValidators:{"*":()=>[],type:()=>r.validateSpec({key:`${l}.type`,value:s.type,valueSpec:d.layer.type,style:r.style,styleSpec:r.styleSpec,validateSpec:r.validateSpec,object:s,objectKey:"type"}),filter:ro,layout:v=>wi({layer:s,key:v.key,value:v.value,style:v.style,styleSpec:v.styleSpec,validateSpec:v.validateSpec,objectElementValidators:{"*":_=>Gc(nn({layerType:g},_))}}),paint:v=>wi({layer:s,key:v.key,value:v.value,style:v.style,styleSpec:v.styleSpec,validateSpec:v.validateSpec,objectElementValidators:{"*":_=>Uc(nn({layerType:g},_))}})}})),o}function Br(r){let e=r.value,i=r.key,o=Ue(e);return o!=="string"?[new _e(i,e,`string expected, ${o} found`)]:[]}let ml={promoteId:function({key:r,value:e}){if(Ue(e)==="string")return Br({key:r,value:e});{let i=[];for(let o in e)i.push(...Br({key:`${r}.${o}`,value:e[o]}));return i}}};function gl(r){let e=r.value,i=r.key,o=r.styleSpec,s=r.style,l=r.validateSpec;if(!e.type)return[new _e(i,e,'"type" is required')];let h=It(e.type),d;switch(h){case"vector":case"raster":return d=wi({key:i,value:e,valueSpec:o[`source_${h.replace("-","_")}`],style:r.style,styleSpec:o,objectElementValidators:ml,validateSpec:l}),d;case"raster-dem":return d=(function(g){var m;let v=(m=g.sourceName)!==null&&m!==void 0?m:"",_=g.value,T=g.styleSpec,b=T.source_raster_dem,I=g.style,M=[],A=Ue(_);if(_===void 0)return M;if(A!=="object")return M.push(new _e("source_raster_dem",_,`object expected, ${A} found`)),M;let D=It(_.encoding)==="custom",L=["redFactor","greenFactor","blueFactor","baseShift"],R=g.value.encoding?`"${g.value.encoding}"`:"Default";for(let F in _)!D&&L.includes(F)?M.push(new _e(F,_[F],`In "${v}": "${F}" is only valid when "encoding" is set to "custom". ${R} encoding found`)):b[F]?M=M.concat(g.validateSpec({key:F,value:_[F],valueSpec:b[F],validateSpec:g.validateSpec,style:I,styleSpec:T})):M.push(new _e(F,_[F],`unknown property "${F}"`));return M})({sourceName:i,value:e,style:r.style,styleSpec:o,validateSpec:l}),d;case"geojson":if(d=wi({key:i,value:e,valueSpec:o.source_geojson,style:s,styleSpec:o,validateSpec:l,objectElementValidators:ml}),e.cluster)for(let g in e.clusterProperties){let[m,v]=e.clusterProperties[g],_=typeof m=="string"?[m,["accumulated"],["get",g]]:m;d.push(...Fr({key:`${i}.${g}.map`,value:v,expressionContext:"cluster-map"})),d.push(...Fr({key:`${i}.${g}.reduce`,value:_,expressionContext:"cluster-reduce"}))}return d;case"video":return wi({key:i,value:e,valueSpec:o.source_video,style:s,validateSpec:l,styleSpec:o});case"image":return wi({key:i,value:e,valueSpec:o.source_image,style:s,validateSpec:l,styleSpec:o});case"canvas":return[new _e(i,null,"Please use runtime APIs to add canvas sources, rather than including them in stylesheets.","source.canvas")];default:return xn({key:`${i}.type`,value:e.type,valueSpec:{values:["vector","raster","raster-dem","geojson","video","image"]}})}}function Go(r){let e=r.value,i=r.styleSpec,o=i.light,s=r.style,l=[],h=Ue(e);if(e===void 0)return l;if(h!=="object")return l=l.concat([new _e("light",e,`object expected, ${h} found`)]),l;for(let d in e){let g=d.match(/^(.*)-transition$/);l=l.concat(g&&o[g[1]]&&o[g[1]].transition?r.validateSpec({key:d,value:e[d],valueSpec:i.transition,validateSpec:r.validateSpec,style:s,styleSpec:i}):o[d]?r.validateSpec({key:d,value:e[d],valueSpec:o[d],validateSpec:r.validateSpec,style:s,styleSpec:i}):[new _e(d,e[d],`unknown property "${d}"`)])}return l}function Zc(r){let e=r.value,i=r.styleSpec,o=i.sky,s=r.style,l=Ue(e);if(e===void 0)return[];if(l!=="object")return[new _e("sky",e,`object expected, ${l} found`)];let h=[];for(let d in e)h=h.concat(o[d]?r.validateSpec({key:d,value:e[d],valueSpec:o[d],style:s,styleSpec:i}):[new _e(d,e[d],`unknown property "${d}"`)]);return h}function _l(r){let e=r.value,i=r.styleSpec,o=i.terrain,s=r.style,l=[],h=Ue(e);if(e===void 0)return l;if(h!=="object")return l=l.concat([new _e("terrain",e,`object expected, ${h} found`)]),l;for(let d in e)l=l.concat(o[d]?r.validateSpec({key:d,value:e[d],valueSpec:o[d],validateSpec:r.validateSpec,style:s,styleSpec:i}):[new _e(d,e[d],`unknown property "${d}"`)]);return l}function yl(r){let e=[],i=r.value,o=r.key;if(Array.isArray(i)){let s=[],l=[];for(let h in i)i[h].id&&s.includes(i[h].id)&&e.push(new _e(o,i,`all the sprites' ids must be unique, but ${i[h].id} is duplicated`)),s.push(i[h].id),i[h].url&&l.includes(i[h].url)&&e.push(new _e(o,i,`all the sprites' URLs must be unique, but ${i[h].url} is duplicated`)),l.push(i[h].url),e=e.concat(wi({key:`${o}[${h}]`,value:i[h],valueSpec:{id:{type:"string",required:!0},url:{type:"string",required:!0}},validateSpec:r.validateSpec}));return e}return Br({key:o,value:i})}function qc(r){return!!r&&r.constructor===Object}function $o(r){return qc(r.value)?[]:[new _e(r.key,r.value,`object expected, ${Ue(r.value)} found`)]}let vl={"*":()=>[],array:$s,boolean:function(r){let e=r.value,i=r.key,o=Ue(e);return o!=="boolean"?[new _e(i,e,`boolean expected, ${o} found`)]:[]},number:io,color:Uo,constants:Nc,enum:xn,filter:ro,function:Zs,layer:$c,object:wi,source:gl,light:Go,sky:Zc,terrain:_l,projection:function(r){let e=r.value,i=r.styleSpec,o=i.projection,s=r.style,l=Ue(e);if(e===void 0)return[];if(l!=="object")return[new _e("projection",e,`object expected, ${l} found`)];let h=[];for(let d in e)h=h.concat(o[d]?r.validateSpec({key:d,value:e[d],valueSpec:o[d],style:s,styleSpec:i}):[new _e(d,e[d],`unknown property "${d}"`)]);return h},projectionDefinition:function(r){let e=r.key,i=r.value;i=i instanceof String?i.valueOf():i;let o=Ue(i);return o!=="array"||(function(s){return Array.isArray(s)&&s.length===3&&typeof s[0]=="string"&&typeof s[1]=="string"&&typeof s[2]=="number"})(i)||(function(s){return!!["interpolate","step","literal"].includes(s[0])})(i)?["array","string"].includes(o)?[]:[new _e(e,i,`projection expected, invalid type "${o}" found`)]:[new _e(e,i,`projection expected, invalid array ${JSON.stringify(i)} found`)]},string:Br,formatted:function(r){return Br(r).length===0?[]:Fr(r)},resolvedImage:function(r){return Br(r).length===0?[]:Fr(r)},padding:function(r){let e=r.key,i=r.value;if(Ue(i)==="array"){if(i.length<1||i.length>4)return[new _e(e,i,`padding requires 1 to 4 values; ${i.length} values found`)];let o={type:"number"},s=[];for(let l=0;l[]}})),r.constants&&(i=i.concat(Nc({key:"constants",value:r.constants}))),Wc(i)}function Ji(r){return function(e){return r(Object.assign({},e,{validateSpec:Zo}))}}function Wc(r){return[].concat(r).sort(((e,i)=>e.line-i.line))}function Qi(r){return function(...e){return Wc(r.apply(this,e))}}ji.source=Qi(Ji(gl)),ji.sprite=Qi(Ji(yl)),ji.glyphs=Qi(Ji(no)),ji.light=Qi(Ji(Go)),ji.sky=Qi(Ji(Zc)),ji.terrain=Qi(Ji(_l)),ji.state=Qi(Ji($o)),ji.layer=Qi(Ji($c)),ji.filter=Qi(Ji(ro)),ji.paintProperty=Qi(Ji(Uc)),ji.layoutProperty=Qi(Ji(Gc));let iu={type:"enum","property-type":"data-constant",expression:{interpolated:!1,parameters:["global-state"]},values:{visible:{},none:{}},transition:!1,default:"visible"};class ru{constructor(e,i){this._globalState=i,this.setValue(e)}evaluate(){var e;return(e=this._literalValue)!==null&&e!==void 0?e:this._compiledValue.evaluate({})}setValue(e){if(e==null||e==="visible"||e==="none")return this._literalValue=e==="none"?"none":"visible",this._compiledValue=void 0,void(this._globalStateRefs=new Set);let i=Oo(e,iu,this._globalState);if(i.result==="error")throw this._literalValue="visible",this._compiledValue=void 0,new Error(i.value.map((o=>`${o.key}: ${o.message}`)).join(", "));this._literalValue=void 0,this._compiledValue=i.value,this._globalStateRefs=eo(i.value.expression)}getGlobalStateRefs(){return this._globalStateRefs}}let qo=ce,nr=ji,zi=nr.light,Wo=nr.sky,Hc=nr.paintProperty,nu=nr.layoutProperty;function Xc(r,e){let i=!1;if(e?.length)for(let o of e)r.fire(new Fn(new Error(o.message))),i=!0;return i}class fr{constructor(e,i,o){let s=this.cells=[];if(e instanceof ArrayBuffer){this.arrayBuffer=e;let h=new Int32Array(this.arrayBuffer);e=h[0],this.d=(i=h[1])+2*(o=h[2]);for(let g=0;g=_[b+0]&&s>=_[b+1])?(d[T]=!0,h.push(v[T])):d[T]=!1}}}_forEachCell(e,i,o,s,l,h,d,g){let m=this._convertToCellCoord(e),v=this._convertToCellCoord(i),_=this._convertToCellCoord(o),T=this._convertToCellCoord(s);for(let b=m;b<=_;b++)for(let I=v;I<=T;I++){let M=this.d*I+b;if((!g||g(this._convertFromCellCoord(b),this._convertFromCellCoord(I),this._convertFromCellCoord(b+1),this._convertFromCellCoord(I+1)))&&l.call(this,e,i,o,s,M,h,d,g))return}}_convertFromCellCoord(e){return(e-this.padding)/this.scale}_convertToCellCoord(e){return Math.max(0,Math.min(this.d-1,Math.floor(e*this.scale)+this.padding))}toArrayBuffer(){if(this.arrayBuffer)return this.arrayBuffer;let e=this.cells,i=3+this.cells.length+1+1,o=0;for(let h of this.cells)o+=h.length;let s=new Int32Array(i+o+this.keys.length+this.bboxes.length);s[0]=this.extent,s[1]=this.n,s[2]=this.padding;let l=i;for(let h=0;ho?(this.lastIntegerZoom=o+1,this.lastIntegerZoomTime=i):this.lastFloorZoom{try{return new RegExp(`\\p{sc=${i}}`,"u").source}catch{return null}})).filter((i=>i));return new RegExp(e.join("|"),"u")}let wl=Qc(["Arab","Dupl","Mong","Ougr","Syrc"]);function Ws(r){return!wl.test(String.fromCodePoint(r))}function Tl(r){return!(bn(r)||(e=r,/[\xA7\xA9\xAE\xB1\xBC-\xBE\xD7\xF7\u2016\u2020\u2021\u2030\u2031\u203B\u203C\u2042\u2047-\u2049\u2051\u2100-\u218F\u221E\u2234\u2235\u2300-\u2307\u230C-\u231F\u2324-\u2328\u232B\u237D-\u239A\u23BE-\u23CD\u23CF\u23D1-\u23DB\u23E2-\u2422\u2424-\u24FF\u25A0-\u2619\u2620-\u2767\u2776-\u2793\u2B12-\u2B2F\u2B50-\u2B59\u2BB8-\u2BEB\u3000-\u303F\u30A0-\u30FF\uE000-\uF8FF\uFE30-\uFE6F\uFF00-\uFFEF\uFFFC\uFFFD]|[\uDB80-\uDBFF][\uDC00-\uDFFF]/gim.test(String.fromCodePoint(e))));var e}let eh=Qc(["Adlm","Arab","Armi","Avst","Chrs","Cprt","Egyp","Elym","Gara","Hatr","Hebr","Hung","Khar","Lydi","Mand","Mani","Mend","Merc","Mero","Narb","Nbat","Nkoo","Orkh","Palm","Phli","Phlp","Phnx","Prti","Rohg","Samr","Sarb","Sogo","Syrc","Thaa","Todr","Yezi"]);function Pl(r){return eh.test(String.fromCodePoint(r))}function th(r,e){return!(!e&&Pl(r)||/[\u0900-\u0DFF\u0F00-\u109F\u1780-\u17FF]/gim.test(String.fromCodePoint(r)))}function Sl(r){for(let e of r)if(Pl(e.codePointAt(0)))return!0;return!1}let gr=new class{constructor(){this.TIMEOUT=5e3,this.applyArabicShaping=null,this.processBidirectionalText=null,this.processStyledBidirectionalText=null,this.pluginStatus="unavailable",this.pluginURL=null,this.loadScriptResolve=()=>{}}setState(r){this.pluginStatus=r.pluginStatus,this.pluginURL=r.pluginURL}getState(){return{pluginStatus:this.pluginStatus,pluginURL:this.pluginURL}}setMethods(r){if(gr.isParsed())throw new Error("RTL text plugin already registered.");this.applyArabicShaping=r.applyArabicShaping,this.processBidirectionalText=r.processBidirectionalText,this.processStyledBidirectionalText=r.processStyledBidirectionalText,this.loadScriptResolve()}isParsed(){return this.applyArabicShaping!=null&&this.processBidirectionalText!=null&&this.processStyledBidirectionalText!=null}getRTLTextPluginStatus(){return this.pluginStatus}syncState(r,e){return p(this,void 0,void 0,(function*(){if(this.isParsed())return this.getState();if(r.pluginStatus!=="loading")return this.setState(r),r;let i=r.pluginURL,o=new Promise((l=>{this.loadScriptResolve=l}));e(i);let s=new Promise((l=>setTimeout((()=>l()),this.TIMEOUT)));if(yield Promise.race([o,s]),this.isParsed()){let l={pluginStatus:"loaded",pluginURL:i};return this.setState(l),l}throw this.setState({pluginStatus:"error",pluginURL:""}),new Error(`RTL Text Plugin failed to import scripts from ${i}`)}))}};class ct{constructor(e,i){this.isSupportedScript=ih,this.zoom=e,i?(this.now=i.now||0,this.fadeDuration=i.fadeDuration||0,this.zoomHistory=i.zoomHistory||new xl,this.transition=i.transition||{}):(this.now=0,this.fadeDuration=0,this.zoomHistory=new xl,this.transition={})}crossFadingFactor(){return this.fadeDuration===0?1:Math.min((this.now-this.zoomHistory.lastIntegerZoomTime)/this.fadeDuration,1)}getCrossfadeParameters(){let e=this.zoom,i=e-Math.floor(e),o=this.crossFadingFactor();return e>this.zoomHistory.lastIntegerZoom?{fromScale:2,toScale:1,t:i+(1-i)*o}:{fromScale:.5,toScale:1,t:1-(1-o)*i}}}function ih(r){return(function(e,i){for(let o of e)if(!th(o.codePointAt(0),i))return!1;return!0})(r,gr.getRTLTextPluginStatus()==="loaded")}let Hs="-transition";class Yo{constructor(e,i,o){this.property=e,this.value=i,this.expression=(function(s,l,h){if(Os(s))return new Us(s,l);if(Ns(s)){let d=Bc(s,l,h);if(d.result==="error")throw new Error(d.value.map((g=>`${g.key}: ${g.message}`)).join(", "));return d.value}{let d=s;return l.type==="color"&&typeof s=="string"?d=Ve.parse(s):l.type!=="padding"||typeof s!="number"&&!Array.isArray(s)?l.type!=="numberArray"||typeof s!="number"&&!Array.isArray(s)?l.type!=="colorArray"||typeof s!="string"&&!Array.isArray(s)?l.type==="variableAnchorOffsetCollection"&&Array.isArray(s)?d=ci.parse(s):l.type==="projectionDefinition"&&typeof s=="string"&&(d=hi.parse(s)):d=ke.parse(s):d=ft.parse(s):d=ei.parse(s),{globalStateRefs:new Set,_globalState:null,kind:"constant",evaluate:()=>d}}})(i===void 0?e.specification.default:i,e.specification,o)}isDataDriven(){return this.expression.kind==="source"||this.expression.kind==="composite"}getGlobalStateRefs(){return this.expression.globalStateRefs||new Set}possiblyEvaluate(e,i,o){return this.property.possiblyEvaluate(this,e,i,o)}}class Il{constructor(e,i){this.property=e,this.value=new Yo(e,void 0,i)}transitioned(e,i){return new El(this.property,this.value,i,Oi({},e.transition,this.transition),e.now)}untransitioned(){return new El(this.property,this.value,null,{},0)}}class Ml{constructor(e,i){this._properties=e,this._values=Object.create(e.defaultTransitionablePropertyValues),this._globalState=i}hasProperty(e){return e in this._properties.defaultTransitionablePropertyValues}getValue(e){return Re(this._values[e].value.value)}setValue(e,i){Object.hasOwn(this._values,e)||(this._values[e]=new Il(this._values[e].property,this._globalState)),this._values[e].value=new Yo(this._values[e].property,i===null?void 0:Re(i),this._globalState)}getTransition(e){return Re(this._values[e].transition)}setTransition(e,i){Object.hasOwn(this._values,e)||(this._values[e]=new Il(this._values[e].property,this._globalState)),this._values[e].transition=Re(i)||void 0}serialize(){let e={};for(let i of Object.keys(this._values)){let o=this.getValue(i);o!==void 0&&(e[i]=o);let s=this.getTransition(i);s!==void 0&&(e[`${i}${Hs}`]=s)}return e}transitioned(e,i){let o=new rh(this._properties);for(let s of Object.keys(this._values))o._values[s]=this._values[s].transitioned(e,i._values[s]);return o}untransitioned(){let e=new rh(this._properties);for(let i of Object.keys(this._values))e._values[i]=this._values[i].untransitioned();return e}}class El{constructor(e,i,o,s,l){this.property=e,this.value=i,this.begin=l+s.delay||0,this.end=this.begin+s.duration||0,e.specification.transition&&(s.delay||s.duration)&&(this.prior=o)}possiblyEvaluate(e,i,o){let s=e.now||0,l=this.value.possiblyEvaluate(e,i,o),h=this.prior;if(h){if(s>this.end)return this.prior=null,l;if(this.value.isDataDriven())return this.prior=null,l;if(ss.zoomHistory.lastIntegerZoom?{from:e,to:i}:{from:o,to:i}}interpolate(e){return e}}class nh{constructor(e){this.specification=e}possiblyEvaluate(e,i,o,s){if(e.value!==void 0){if(e.expression.kind==="constant"){let l=e.expression.evaluate(i,null,{},o,s);return this._calculate(l,l,l,i)}return this._calculate(e.expression.evaluate(new ct(Math.floor(i.zoom-1),i)),e.expression.evaluate(new ct(Math.floor(i.zoom),i)),e.expression.evaluate(new ct(Math.floor(i.zoom+1),i)),i)}}_calculate(e,i,o,s){return s.zoom>s.zoomHistory.lastIntegerZoom?{from:e,to:i}:{from:o,to:i}}interpolate(e){return e}}class oo{constructor(e){this.specification=e}possiblyEvaluate(e,i,o,s){return!!e.expression.evaluate(i,null,{},o,s)}interpolate(){return!1}}class ui{constructor(e){this.properties=e,this.defaultPropertyValues={},this.defaultTransitionablePropertyValues={},this.defaultTransitioningPropertyValues={},this.defaultPossiblyEvaluatedValues={},this.overridableProperties=[];for(let i in e){let o=e[i];o.specification.overridable&&this.overridableProperties.push(i);let s=this.defaultPropertyValues[i]=new Yo(o,void 0,void 0),l=this.defaultTransitionablePropertyValues[i]=new Il(o,void 0);this.defaultTransitioningPropertyValues[i]=l.untransitioned(),this.defaultPossiblyEvaluatedValues[i]=s.possiblyEvaluate({})}}}Pe("DataDrivenProperty",Ce),Pe("DataConstantProperty",Ie),Pe("CrossFadedDataDrivenProperty",Or),Pe("CrossFadedProperty",nh),Pe("ColorRampProperty",oo);let oh=" is a PAINT property not a LAYOUT property. Use get/setPaintProperty instead?",Xs=" is a LAYOUT property not a PAINT property. Use get/setLayoutProperty instead?";class Ui extends fs{constructor(e,i,o){if(super(),this.id=e.id,this.type=e.type,this._globalState=o,this._featureFilter={filter:()=>!0,needGeometry:!1,getGlobalStateRefs:()=>new Set},this._visibilityExpression=(function(s,l){return new ru(s,l)})(this.visibility,o),e.type!=="custom"&&(this.metadata=e.metadata,this.minzoom=e.minzoom,this.maxzoom=e.maxzoom,e.type!=="background"&&(this.source=e.source,this.sourceLayer=e["source-layer"],this.filter=e.filter,this._featureFilter=No(e.filter,o)),i.layout&&(this._unevaluatedLayout=new su(i.layout,o)),i.paint)){this._transitionablePaint=new Ml(i.paint,o);for(let s in e.paint)this.setPaintProperty(s,e.paint[s],{validate:!1});for(let s in e.layout)this.setLayoutProperty(s,e.layout[s],{validate:!1});this._transitioningPaint=this._transitionablePaint.untransitioned(),this.paint=new Ko(i.paint)}}setFilter(e){this.filter=e,this._featureFilter=No(e,this._globalState)}getCrossfadeParameters(){return this._crossfadeParameters}getLayoutProperty(e){var i;if(e==="visibility")return this.visibility;if(!((i=this._transitionablePaint)===null||i===void 0)&&i.hasProperty(e))throw new Error(e+oh);if(!this._unevaluatedLayout)throw new Error(`Cannot get layout property "${e}" on layer type "${this.type}" which has no layout properties.`);return this._unevaluatedLayout.getValue(e)}getLayoutAffectingGlobalStateRefs(){let e=new Set;for(let i of this._visibilityExpression.getGlobalStateRefs())e.add(i);if(this._unevaluatedLayout)for(let i in this._unevaluatedLayout._values){let o=this._unevaluatedLayout._values[i];for(let s of o.getGlobalStateRefs())e.add(s)}for(let i of this._featureFilter.getGlobalStateRefs())e.add(i);return e}getPaintAffectingGlobalStateRefs(){var e;let i=new globalThis.Map;if(this._transitionablePaint)for(let o in this._transitionablePaint._values){let s=this._transitionablePaint._values[o].value;for(let l of s.getGlobalStateRefs()){let h=(e=i.get(l))!==null&&e!==void 0?e:[];h.push({name:o,value:s.value}),i.set(l,h)}}return i}getVisibilityAffectingGlobalStateRefs(){return this._visibilityExpression.getGlobalStateRefs()}setLayoutProperty(e,i,o={}){var s;if(e==="visibility")return this.visibility=i,this._visibilityExpression.setValue(i),void this.recalculateVisibility();!((s=this._transitionablePaint)===null||s===void 0)&&s.hasProperty(e)?this.fire(new Fn(new Error(e+oh))):i!=null&&this._validate(nu,`layers.${this.id}.layout.${e}`,e,i,o)||this._unevaluatedLayout.setValue(e,i)}getPaintProperty(e){var i,o;if(e.endsWith(Hs)){let s=e.slice(0,-11);if(s==="visibility"||!((i=this._unevaluatedLayout)===null||i===void 0)&&i.hasProperty(s))throw new Error(e+Xs);return this._transitionablePaint.getTransition(s)}if(e==="visibility"||!((o=this._unevaluatedLayout)===null||o===void 0)&&o.hasProperty(e))throw new Error(e+Xs);return this._transitionablePaint.getValue(e)}setPaintProperty(e,i,o={}){var s;if(e==="visibility"||!((s=this._unevaluatedLayout)===null||s===void 0)&&s.hasProperty(e))return this.fire(new Fn(new Error(e+Xs))),!1;if(i!=null&&this._validate(Hc,`layers.${this.id}.paint.${e}`,e,i,o))return!1;if(e.endsWith(Hs))return this._transitionablePaint.setTransition(e.slice(0,-11),i||void 0),!1;{let l=this._transitionablePaint._values[e],h=l.property.specification["property-type"]==="cross-faded-data-driven",d=l.value.isDataDriven(),g=l.value;this._transitionablePaint.setValue(e,i),this._handleSpecialPaintPropertyUpdate(e);let m=this._transitionablePaint._values[e].value;return m.isDataDriven()||d||h||this._handleOverridablePaintPropertyUpdate(e,g,m)}}_handleSpecialPaintPropertyUpdate(e){}_handleOverridablePaintPropertyUpdate(e,i,o){return!1}isHidden(e=this.minzoom,i=!1){return!!(this.minzoom&&e<(i?Math.floor(this.minzoom):this.minzoom))||!!(this.maxzoom&&e>=this.maxzoom)||this._evaluatedVisibility==="none"}updateTransitions(e){this._transitioningPaint=this._transitionablePaint.transitioned(e,this._transitioningPaint)}hasTransition(){return this._transitioningPaint.hasTransition()}recalculateVisibility(){this._evaluatedVisibility=this._visibilityExpression.evaluate()}recalculate(e,i){e.getCrossfadeParameters&&(this._crossfadeParameters=e.getCrossfadeParameters()),this._unevaluatedLayout&&(this.layout=this._unevaluatedLayout.possiblyEvaluate(e,void 0,i)),this.paint=this._transitioningPaint.possiblyEvaluate(e,void 0,i)}serialize(){var e,i;let o={id:this.id,type:this.type,source:this.source,"source-layer":this.sourceLayer,metadata:this.metadata,minzoom:this.minzoom,maxzoom:this.maxzoom,filter:this.filter,layout:(e=this._unevaluatedLayout)===null||e===void 0?void 0:e.serialize(),paint:(i=this._transitionablePaint)===null||i===void 0?void 0:i.serialize()};return this.visibility&&(o.layout||(o.layout={}),o.layout.visibility=this.visibility),Kr(o,((s,l)=>!(s===void 0||l==="layout"&&!Object.keys(s).length||l==="paint"&&!Object.keys(s).length)))}_validate(e,i,o,s,l={}){return l?.validate!==!1&&Xc(this,e.call(nr,{key:i,layerType:this.type,objectKey:o,value:s,styleSpec:ce,style:{glyphs:!0,sprite:!0}}))}is3D(){return!1}isTileClipped(){return!1}hasOffscreenPass(){return!1}resize(){}isStateDependent(){for(let e in this.paint._values){let i=this.paint.get(e);if(i instanceof er&&Qn(i.property.specification)&&(i.value.kind==="source"||i.value.kind==="composite")&&i.value.isStateDependent)return!0}return!1}}let Cl;var au={get paint(){return Cl=Cl||new ui({"raster-opacity":new Ie(ce.paint_raster["raster-opacity"]),"raster-hue-rotate":new Ie(ce.paint_raster["raster-hue-rotate"]),"raster-brightness-min":new Ie(ce.paint_raster["raster-brightness-min"]),"raster-brightness-max":new Ie(ce.paint_raster["raster-brightness-max"]),"raster-saturation":new Ie(ce.paint_raster["raster-saturation"]),"raster-contrast":new Ie(ce.paint_raster["raster-contrast"]),resampling:new Ie(ce.paint_raster.resampling),"raster-resampling":new Ie(ce.paint_raster["raster-resampling"]),"raster-fade-duration":new Ie(ce.paint_raster["raster-fade-duration"])})}};class lu extends Ui{constructor(e,i){super(e,au,i)}}let cu={Int8:Int8Array,Uint8:Uint8Array,Int16:Int16Array,Uint16:Uint16Array,Int32:Int32Array,Uint32:Uint32Array,Float32:Float32Array};class Jo{constructor(e,i){this._structArray=e,this._pos1=i*this.size,this._pos2=this._pos1/2,this._pos4=this._pos1/4,this._pos8=this._pos1/8}}class mt{constructor(){this.isTransferred=!1,this.capacity=-1,this.resize(0)}static serialize(e,i){return e._trim(),i&&(e.isTransferred=!0,i.push(e.arrayBuffer)),{length:e.length,arrayBuffer:e.arrayBuffer}}static deserialize(e){let i=Object.create(this.prototype);return i.arrayBuffer=e.arrayBuffer,i.length=e.length,i.capacity=e.arrayBuffer.byteLength/i.bytesPerElement,i._refreshViews(),i}_trim(){this.length!==this.capacity&&(this.capacity=this.length,this.arrayBuffer=this.arrayBuffer.slice(0,this.length*this.bytesPerElement),this._refreshViews())}clear(){this.length=0}resize(e){this.reserve(e),this.length=e}reserve(e){if(e>this.capacity){this.capacity=Math.max(e,Math.floor(5*this.capacity),128),this.arrayBuffer=new ArrayBuffer(this.capacity*this.bytesPerElement);let i=this.uint8;this._refreshViews(),i&&this.uint8.set(i)}}_refreshViews(){throw new Error("_refreshViews() must be implemented by each concrete StructArray layout")}freeBufferAfterUpload(){this.arrayBuffer=new ArrayBuffer(0),this._refreshViews()}}function ht(r,e=1){let i=0,o=0;return{members:r.map((s=>{let l=cu[s.type].BYTES_PER_ELEMENT,h=i=sh(i,Math.max(e,l)),d=s.components||1;return o=Math.max(o,l),i+=l*d,{name:s.name,type:s.type,components:d,offset:h}})),size:sh(i,Math.max(o,e)),alignment:e}}function sh(r,e){return Math.ceil(r/e)*e}class Qo extends mt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(e,i){let o=this.length;return this.resize(o+1),this.emplace(o,e,i)}emplace(e,i,o){let s=2*e;return this.int16[s+0]=i,this.int16[s+1]=o,e}}Qo.prototype.bytesPerElement=4,Pe("StructArrayLayout2i4",Qo);class Ys extends mt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(e,i,o){let s=this.length;return this.resize(s+1),this.emplace(s,e,i,o)}emplace(e,i,o,s){let l=3*e;return this.int16[l+0]=i,this.int16[l+1]=o,this.int16[l+2]=s,e}}Ys.prototype.bytesPerElement=6,Pe("StructArrayLayout3i6",Ys);class Ks extends mt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(e,i,o,s){let l=this.length;return this.resize(l+1),this.emplace(l,e,i,o,s)}emplace(e,i,o,s,l){let h=4*e;return this.int16[h+0]=i,this.int16[h+1]=o,this.int16[h+2]=s,this.int16[h+3]=l,e}}Ks.prototype.bytesPerElement=8,Pe("StructArrayLayout4i8",Ks);class Js extends mt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(e,i,o,s,l,h){let d=this.length;return this.resize(d+1),this.emplace(d,e,i,o,s,l,h)}emplace(e,i,o,s,l,h,d){let g=6*e;return this.int16[g+0]=i,this.int16[g+1]=o,this.int16[g+2]=s,this.int16[g+3]=l,this.int16[g+4]=h,this.int16[g+5]=d,e}}Js.prototype.bytesPerElement=12,Pe("StructArrayLayout2i4i12",Js);class Al extends mt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(e,i,o,s,l,h){let d=this.length;return this.resize(d+1),this.emplace(d,e,i,o,s,l,h)}emplace(e,i,o,s,l,h,d){let g=4*e,m=8*e;return this.int16[g+0]=i,this.int16[g+1]=o,this.uint8[m+4]=s,this.uint8[m+5]=l,this.uint8[m+6]=h,this.uint8[m+7]=d,e}}Al.prototype.bytesPerElement=8,Pe("StructArrayLayout2i4ub8",Al);class es extends mt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(e,i){let o=this.length;return this.resize(o+1),this.emplace(o,e,i)}emplace(e,i,o){let s=2*e;return this.float32[s+0]=i,this.float32[s+1]=o,e}}es.prototype.bytesPerElement=8,Pe("StructArrayLayout2f8",es);class _r extends mt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(e,i,o,s,l,h,d,g,m,v){let _=this.length;return this.resize(_+1),this.emplace(_,e,i,o,s,l,h,d,g,m,v)}emplace(e,i,o,s,l,h,d,g,m,v,_){let T=10*e;return this.uint16[T+0]=i,this.uint16[T+1]=o,this.uint16[T+2]=s,this.uint16[T+3]=l,this.uint16[T+4]=h,this.uint16[T+5]=d,this.uint16[T+6]=g,this.uint16[T+7]=m,this.uint16[T+8]=v,this.uint16[T+9]=_,e}}_r.prototype.bytesPerElement=20,Pe("StructArrayLayout10ui20",_r);class Qs extends mt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(e,i,o,s,l,h,d,g){let m=this.length;return this.resize(m+1),this.emplace(m,e,i,o,s,l,h,d,g)}emplace(e,i,o,s,l,h,d,g,m){let v=8*e;return this.uint16[v+0]=i,this.uint16[v+1]=o,this.uint16[v+2]=s,this.uint16[v+3]=l,this.uint16[v+4]=h,this.uint16[v+5]=d,this.uint16[v+6]=g,this.uint16[v+7]=m,e}}Qs.prototype.bytesPerElement=16,Pe("StructArrayLayout8ui16",Qs);class ts extends mt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(e,i,o,s,l,h,d,g,m,v,_,T){let b=this.length;return this.resize(b+1),this.emplace(b,e,i,o,s,l,h,d,g,m,v,_,T)}emplace(e,i,o,s,l,h,d,g,m,v,_,T,b){let I=12*e;return this.int16[I+0]=i,this.int16[I+1]=o,this.int16[I+2]=s,this.int16[I+3]=l,this.uint16[I+4]=h,this.uint16[I+5]=d,this.uint16[I+6]=g,this.uint16[I+7]=m,this.int16[I+8]=v,this.int16[I+9]=_,this.int16[I+10]=T,this.int16[I+11]=b,e}}ts.prototype.bytesPerElement=24,Pe("StructArrayLayout4i4ui4i24",ts);class ea extends mt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(e,i,o){let s=this.length;return this.resize(s+1),this.emplace(s,e,i,o)}emplace(e,i,o,s){let l=3*e;return this.float32[l+0]=i,this.float32[l+1]=o,this.float32[l+2]=s,e}}ea.prototype.bytesPerElement=12,Pe("StructArrayLayout3f12",ea);class is extends mt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer)}emplaceBack(e){let i=this.length;return this.resize(i+1),this.emplace(i,e)}emplace(e,i){return this.uint32[1*e+0]=i,e}}is.prototype.bytesPerElement=4,Pe("StructArrayLayout1ul4",is);class Dl extends mt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(e,i,o,s,l,h,d,g,m){let v=this.length;return this.resize(v+1),this.emplace(v,e,i,o,s,l,h,d,g,m)}emplace(e,i,o,s,l,h,d,g,m,v){let _=10*e,T=5*e;return this.int16[_+0]=i,this.int16[_+1]=o,this.int16[_+2]=s,this.int16[_+3]=l,this.int16[_+4]=h,this.int16[_+5]=d,this.uint32[T+3]=g,this.uint16[_+8]=m,this.uint16[_+9]=v,e}}Dl.prototype.bytesPerElement=20,Pe("StructArrayLayout6i1ul2ui20",Dl);class so extends mt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(e,i,o,s,l,h){let d=this.length;return this.resize(d+1),this.emplace(d,e,i,o,s,l,h)}emplace(e,i,o,s,l,h,d){let g=6*e;return this.int16[g+0]=i,this.int16[g+1]=o,this.int16[g+2]=s,this.int16[g+3]=l,this.int16[g+4]=h,this.int16[g+5]=d,e}}so.prototype.bytesPerElement=12,Pe("StructArrayLayout2i2i2i12",so);class wn extends mt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(e,i,o,s,l){let h=this.length;return this.resize(h+1),this.emplace(h,e,i,o,s,l)}emplace(e,i,o,s,l,h){let d=4*e,g=8*e;return this.float32[d+0]=i,this.float32[d+1]=o,this.float32[d+2]=s,this.int16[g+6]=l,this.int16[g+7]=h,e}}wn.prototype.bytesPerElement=16,Pe("StructArrayLayout2f1f2i16",wn);class zl extends mt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(e,i,o,s,l,h){let d=this.length;return this.resize(d+1),this.emplace(d,e,i,o,s,l,h)}emplace(e,i,o,s,l,h,d){let g=16*e,m=4*e,v=8*e;return this.uint8[g+0]=i,this.uint8[g+1]=o,this.float32[m+1]=s,this.float32[m+2]=l,this.int16[v+6]=h,this.int16[v+7]=d,e}}zl.prototype.bytesPerElement=16,Pe("StructArrayLayout2ub2f2i16",zl);class rs extends mt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(e,i,o){let s=this.length;return this.resize(s+1),this.emplace(s,e,i,o)}emplace(e,i,o,s){let l=3*e;return this.uint16[l+0]=i,this.uint16[l+1]=o,this.uint16[l+2]=s,e}}rs.prototype.bytesPerElement=6,Pe("StructArrayLayout3ui6",rs);class Tn extends mt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(e,i,o,s,l,h,d,g,m,v,_,T,b,I,M,A,D){let L=this.length;return this.resize(L+1),this.emplace(L,e,i,o,s,l,h,d,g,m,v,_,T,b,I,M,A,D)}emplace(e,i,o,s,l,h,d,g,m,v,_,T,b,I,M,A,D,L){let R=24*e,F=12*e,O=48*e;return this.int16[R+0]=i,this.int16[R+1]=o,this.uint16[R+2]=s,this.uint16[R+3]=l,this.uint32[F+2]=h,this.uint32[F+3]=d,this.uint32[F+4]=g,this.uint16[R+10]=m,this.uint16[R+11]=v,this.uint16[R+12]=_,this.float32[F+7]=T,this.float32[F+8]=b,this.uint8[O+36]=I,this.uint8[O+37]=M,this.uint8[O+38]=A,this.uint32[F+10]=D,this.int16[R+22]=L,e}}Tn.prototype.bytesPerElement=48,Pe("StructArrayLayout2i2ui3ul3ui2f3ub1ul1i48",Tn);class Rl extends mt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(e,i,o,s,l,h,d,g,m,v,_,T,b,I,M,A,D,L,R,F,O,V,Y,J,re,te,ae,le){let ne=this.length;return this.resize(ne+1),this.emplace(ne,e,i,o,s,l,h,d,g,m,v,_,T,b,I,M,A,D,L,R,F,O,V,Y,J,re,te,ae,le)}emplace(e,i,o,s,l,h,d,g,m,v,_,T,b,I,M,A,D,L,R,F,O,V,Y,J,re,te,ae,le,ne){let ie=32*e,fe=16*e;return this.int16[ie+0]=i,this.int16[ie+1]=o,this.int16[ie+2]=s,this.int16[ie+3]=l,this.int16[ie+4]=h,this.int16[ie+5]=d,this.int16[ie+6]=g,this.int16[ie+7]=m,this.uint16[ie+8]=v,this.uint16[ie+9]=_,this.uint16[ie+10]=T,this.uint16[ie+11]=b,this.uint16[ie+12]=I,this.uint16[ie+13]=M,this.uint16[ie+14]=A,this.uint16[ie+15]=D,this.uint16[ie+16]=L,this.uint16[ie+17]=R,this.uint16[ie+18]=F,this.uint16[ie+19]=O,this.uint16[ie+20]=V,this.uint16[ie+21]=Y,this.uint16[ie+22]=J,this.uint32[fe+12]=re,this.float32[fe+13]=te,this.float32[fe+14]=ae,this.uint16[ie+30]=le,this.uint16[ie+31]=ne,e}}Rl.prototype.bytesPerElement=64,Pe("StructArrayLayout8i15ui1ul2f2ui64",Rl);class ta extends mt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(e){let i=this.length;return this.resize(i+1),this.emplace(i,e)}emplace(e,i){return this.float32[1*e+0]=i,e}}ta.prototype.bytesPerElement=4,Pe("StructArrayLayout1f4",ta);class ia extends mt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(e,i,o){let s=this.length;return this.resize(s+1),this.emplace(s,e,i,o)}emplace(e,i,o,s){let l=3*e;return this.uint16[6*e+0]=i,this.float32[l+1]=o,this.float32[l+2]=s,e}}ia.prototype.bytesPerElement=12,Pe("StructArrayLayout1ui2f12",ia);class kl extends mt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(e,i,o){let s=this.length;return this.resize(s+1),this.emplace(s,e,i,o)}emplace(e,i,o,s){let l=4*e;return this.uint32[2*e+0]=i,this.uint16[l+2]=o,this.uint16[l+3]=s,e}}kl.prototype.bytesPerElement=8,Pe("StructArrayLayout1ul2ui8",kl);class u extends mt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(e,i){let o=this.length;return this.resize(o+1),this.emplace(o,e,i)}emplace(e,i,o){let s=2*e;return this.uint16[s+0]=i,this.uint16[s+1]=o,e}}u.prototype.bytesPerElement=4,Pe("StructArrayLayout2ui4",u);class t extends mt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(e){let i=this.length;return this.resize(i+1),this.emplace(i,e)}emplace(e,i){return this.uint16[1*e+0]=i,e}}t.prototype.bytesPerElement=2,Pe("StructArrayLayout1ui2",t);class n extends mt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(e,i,o,s){let l=this.length;return this.resize(l+1),this.emplace(l,e,i,o,s)}emplace(e,i,o,s,l){let h=4*e;return this.float32[h+0]=i,this.float32[h+1]=o,this.float32[h+2]=s,this.float32[h+3]=l,e}}n.prototype.bytesPerElement=16,Pe("StructArrayLayout4f16",n);class a extends Jo{get anchorPointX(){return this._structArray.int16[this._pos2+0]}get anchorPointY(){return this._structArray.int16[this._pos2+1]}get x1(){return this._structArray.int16[this._pos2+2]}get y1(){return this._structArray.int16[this._pos2+3]}get x2(){return this._structArray.int16[this._pos2+4]}get y2(){return this._structArray.int16[this._pos2+5]}get featureIndex(){return this._structArray.uint32[this._pos4+3]}get sourceLayerIndex(){return this._structArray.uint16[this._pos2+8]}get bucketIndex(){return this._structArray.uint16[this._pos2+9]}get anchorPoint(){return new Te(this.anchorPointX,this.anchorPointY)}}a.prototype.size=20;class c extends Dl{get(e){return new a(this,e)}}Pe("CollisionBoxArray",c);class f extends Jo{get anchorX(){return this._structArray.int16[this._pos2+0]}get anchorY(){return this._structArray.int16[this._pos2+1]}get glyphStartIndex(){return this._structArray.uint16[this._pos2+2]}get numGlyphs(){return this._structArray.uint16[this._pos2+3]}get vertexStartIndex(){return this._structArray.uint32[this._pos4+2]}get lineStartIndex(){return this._structArray.uint32[this._pos4+3]}get lineLength(){return this._structArray.uint32[this._pos4+4]}get segment(){return this._structArray.uint16[this._pos2+10]}get lowerSize(){return this._structArray.uint16[this._pos2+11]}get upperSize(){return this._structArray.uint16[this._pos2+12]}get lineOffsetX(){return this._structArray.float32[this._pos4+7]}get lineOffsetY(){return this._structArray.float32[this._pos4+8]}get writingMode(){return this._structArray.uint8[this._pos1+36]}get placedOrientation(){return this._structArray.uint8[this._pos1+37]}set placedOrientation(e){this._structArray.uint8[this._pos1+37]=e}get hidden(){return this._structArray.uint8[this._pos1+38]}set hidden(e){this._structArray.uint8[this._pos1+38]=e}get crossTileID(){return this._structArray.uint32[this._pos4+10]}set crossTileID(e){this._structArray.uint32[this._pos4+10]=e}get associatedIconIndex(){return this._structArray.int16[this._pos2+22]}}f.prototype.size=48;class y extends Tn{get(e){return new f(this,e)}}Pe("PlacedSymbolArray",y);class x extends Jo{get anchorX(){return this._structArray.int16[this._pos2+0]}get anchorY(){return this._structArray.int16[this._pos2+1]}get rightJustifiedTextSymbolIndex(){return this._structArray.int16[this._pos2+2]}get centerJustifiedTextSymbolIndex(){return this._structArray.int16[this._pos2+3]}get leftJustifiedTextSymbolIndex(){return this._structArray.int16[this._pos2+4]}get verticalPlacedTextSymbolIndex(){return this._structArray.int16[this._pos2+5]}get placedIconSymbolIndex(){return this._structArray.int16[this._pos2+6]}get verticalPlacedIconSymbolIndex(){return this._structArray.int16[this._pos2+7]}get key(){return this._structArray.uint16[this._pos2+8]}get textBoxStartIndex(){return this._structArray.uint16[this._pos2+9]}get textBoxEndIndex(){return this._structArray.uint16[this._pos2+10]}get verticalTextBoxStartIndex(){return this._structArray.uint16[this._pos2+11]}get verticalTextBoxEndIndex(){return this._structArray.uint16[this._pos2+12]}get iconBoxStartIndex(){return this._structArray.uint16[this._pos2+13]}get iconBoxEndIndex(){return this._structArray.uint16[this._pos2+14]}get verticalIconBoxStartIndex(){return this._structArray.uint16[this._pos2+15]}get verticalIconBoxEndIndex(){return this._structArray.uint16[this._pos2+16]}get featureIndex(){return this._structArray.uint16[this._pos2+17]}get numHorizontalGlyphVertices(){return this._structArray.uint16[this._pos2+18]}get numVerticalGlyphVertices(){return this._structArray.uint16[this._pos2+19]}get numIconVertices(){return this._structArray.uint16[this._pos2+20]}get numVerticalIconVertices(){return this._structArray.uint16[this._pos2+21]}get useRuntimeCollisionCircles(){return this._structArray.uint16[this._pos2+22]}get crossTileID(){return this._structArray.uint32[this._pos4+12]}set crossTileID(e){this._structArray.uint32[this._pos4+12]=e}get textBoxScale(){return this._structArray.float32[this._pos4+13]}get collisionCircleDiameter(){return this._structArray.float32[this._pos4+14]}get textAnchorOffsetStartIndex(){return this._structArray.uint16[this._pos2+30]}get textAnchorOffsetEndIndex(){return this._structArray.uint16[this._pos2+31]}}x.prototype.size=64;class w extends Rl{get(e){return new x(this,e)}}Pe("SymbolInstanceArray",w);class P extends ta{getoffsetX(e){return this.float32[1*e+0]}}Pe("GlyphOffsetArray",P);class S extends Ys{getx(e){return this.int16[3*e+0]}gety(e){return this.int16[3*e+1]}gettileUnitDistanceFromAnchor(e){return this.int16[3*e+2]}}Pe("SymbolLineVertexArray",S);class E extends Jo{get textAnchor(){return this._structArray.uint16[this._pos2+0]}get textOffset0(){return this._structArray.float32[this._pos4+1]}get textOffset1(){return this._structArray.float32[this._pos4+2]}}E.prototype.size=12;class C extends ia{get(e){return new E(this,e)}}Pe("TextAnchorOffsetArray",C);class z extends Jo{get featureIndex(){return this._structArray.uint32[this._pos4+0]}get sourceLayerIndex(){return this._structArray.uint16[this._pos2+2]}get bucketIndex(){return this._structArray.uint16[this._pos2+3]}}z.prototype.size=8;class B extends kl{get(e){return new z(this,e)}}Pe("FeatureIndexArray",B);class N extends Qo{}class G extends Qo{}class j extends Qo{}class $ extends Js{}class X extends Al{}class Z extends es{}class U extends _r{}class H extends Qs{}class q extends ts{}class Q extends ea{}class oe extends is{}class se extends so{}class de extends zl{}class ue extends rs{}class Se extends u{}let ve=ht([{name:"a_pos",components:2,type:"Int16"}],4),{members:he}=ve;class we{constructor(e=[]){this._forceNewSegmentOnNextPrepare=!1,this.segments=e}prepareSegment(e,i,o,s){let l=this.segments[this.segments.length-1];return e>we.MAX_VERTEX_ARRAY_LENGTH&&Wt(`Max vertices per segment is ${we.MAX_VERTEX_ARRAY_LENGTH}: bucket requested ${e}. Consider using the \`fillLargeMeshArrays\` function if you require meshes with more than ${we.MAX_VERTEX_ARRAY_LENGTH} vertices.`),this._forceNewSegmentOnNextPrepare||!l||l.vertexLength+e>we.MAX_VERTEX_ARRAY_LENGTH||l.sortKey!==s?this.createNewSegment(i,o,s):l}createNewSegment(e,i,o){let s={vertexOffset:e.length,primitiveOffset:i.length,vertexLength:0,primitiveLength:0,vaos:{}};return o!==void 0&&(s.sortKey=o),this._forceNewSegmentOnNextPrepare=!1,this.segments.push(s),s}getOrCreateLatestSegment(e,i,o){return this.prepareSegment(0,e,i,o)}forceNewSegmentOnNextPrepare(){this._forceNewSegmentOnNextPrepare=!0}get(){return this.segments}destroy(){for(let e of this.segments)for(let i in e.vaos)e.vaos[i].destroy()}static simpleSegment(e,i,o,s){return new we([{vertexOffset:e,primitiveOffset:i,vertexLength:o,primitiveLength:s,vaos:{},sortKey:0}])}}function Ee(r,e){return 256*(r=li(Math.floor(r),0,255))+li(Math.floor(e),0,255)}we.MAX_VERTEX_ARRAY_LENGTH=Math.pow(2,16)-1,Pe("SegmentVector",we);let tt=ht([{name:"a_pattern_from",components:4,type:"Uint16"},{name:"a_pattern_to",components:4,type:"Uint16"},{name:"a_pixel_ratio_from",components:1,type:"Uint16"},{name:"a_pixel_ratio_to",components:1,type:"Uint16"}]),Mt=ht([{name:"a_dasharray_from",components:4,type:"Uint16"},{name:"a_dasharray_to",components:4,type:"Uint16"}]);var ot,Ct,Dt,ti={exports:{}},wt={exports:{}},di={exports:{}},Kt=(function(){if(Dt)return ti.exports;Dt=1;var r=(ot||(ot=1,wt.exports=function(i,o){var s,l,h,d,g,m,v,_;for(l=i.length-(s=3&i.length),h=o,g=3432918353,m=461845907,_=0;_>>16)*g&65535)<<16)&4294967295)<<15|v>>>17))*m+(((v>>>16)*m&65535)<<16)&4294967295)<<13|h>>>19))+((5*(h>>>16)&65535)<<16)&4294967295))+((58964+(d>>>16)&65535)<<16);switch(v=0,s){case 3:v^=(255&i.charCodeAt(_+2))<<16;case 2:v^=(255&i.charCodeAt(_+1))<<8;case 1:h^=v=(65535&(v=(v=(65535&(v^=255&i.charCodeAt(_)))*g+(((v>>>16)*g&65535)<<16)&4294967295)<<15|v>>>17))*m+(((v>>>16)*m&65535)<<16)&4294967295}return h^=i.length,h=2246822507*(65535&(h^=h>>>16))+((2246822507*(h>>>16)&65535)<<16)&4294967295,h=3266489909*(65535&(h^=h>>>13))+((3266489909*(h>>>16)&65535)<<16)&4294967295,(h^=h>>>16)>>>0}),wt.exports),e=(Ct||(Ct=1,di.exports=function(i,o){for(var s,l=i.length,h=o^l,d=0;l>=4;)s=1540483477*(65535&(s=255&i.charCodeAt(d)|(255&i.charCodeAt(++d))<<8|(255&i.charCodeAt(++d))<<16|(255&i.charCodeAt(++d))<<24))+((1540483477*(s>>>16)&65535)<<16),h=1540483477*(65535&h)+((1540483477*(h>>>16)&65535)<<16)^(s=1540483477*(65535&(s^=s>>>24))+((1540483477*(s>>>16)&65535)<<16)),l-=4,++d;switch(l){case 3:h^=(255&i.charCodeAt(d+2))<<16;case 2:h^=(255&i.charCodeAt(d+1))<<8;case 1:h=1540483477*(65535&(h^=255&i.charCodeAt(d)))+((1540483477*(h>>>16)&65535)<<16)}return h=1540483477*(65535&(h^=h>>>13))+((1540483477*(h>>>16)&65535)<<16),(h^=h>>>15)>>>0}),di.exports);return ti.exports=r,ti.exports.murmur3=r,ti.exports.murmur2=e,ti.exports})(),Nt=Sr(Kt);class ii{constructor(){this.ids=[],this.positions=[],this.indexed=!1}add(e,i,o,s){this.ids.push(Nr(e)),this.positions.push(i,o,s)}getPositions(e){if(!this.indexed)throw new Error("Trying to get index, but feature positions are not indexed");let i=Nr(e),o=0,s=this.ids.length-1;for(;o>1;this.ids[h]>=i?s=h:o=h+1}let l=[];for(;this.ids[o]===i;)l.push({index:this.positions[3*o],start:this.positions[3*o+1],end:this.positions[3*o+2]}),o++;return l}static serialize(e,i){let o=new Float64Array(e.ids),s=new Uint32Array(e.positions);return Vr(o,s,0,o.length-1),i&&i.push(o.buffer,s.buffer),{ids:o,positions:s}}static deserialize(e){let i=new ii;return i.ids=e.ids,i.positions=e.positions,i.indexed=!0,i}}function Nr(r){let e=+r;return!isNaN(e)&&e<=Number.MAX_SAFE_INTEGER?e:Nt(String(r))}function Vr(r,e,i,o){for(;i>1],l=i-1,h=o+1;for(;;){do l++;while(r[l]s);if(l>=h)break;jr(r,l,h),jr(e,3*l,3*h),jr(e,3*l+1,3*h+1),jr(e,3*l+2,3*h+2)}h-i`u_${s}`)),this.type=o}setUniform(e,i,o){e.set(o.constantOr(this.value))}getBinding(e,i,o){return this.type==="color"?new ra(e,i):new yr(e,i)}}class Gi{constructor(e,i){this.uniformNames=i.map((o=>`u_${o}`)),this.patternFrom=null,this.patternTo=null,this.pixelRatioFrom=1,this.pixelRatioTo=1}setConstantPatternPositions(e,i){this.pixelRatioFrom=i.pixelRatio,this.pixelRatioTo=e.pixelRatio,this.patternFrom=i.tlbr,this.patternTo=e.tlbr}setConstantDashPositions(e,i){this.dashTo=[0,e.y,e.height,e.width],this.dashFrom=[0,i.y,i.height,i.width]}setUniform(e,i,o,s){let l=null;s==="u_pattern_to"?l=this.patternTo:s==="u_pattern_from"?l=this.patternFrom:s==="u_dasharray_to"?l=this.dashTo:s==="u_dasharray_from"?l=this.dashFrom:s==="u_pixel_ratio_to"?l=this.pixelRatioTo:s==="u_pixel_ratio_from"&&(l=this.pixelRatioFrom),l!==null&&e.set(l)}getBinding(e,i,o){return o.startsWith("u_pattern")||o.startsWith("u_dasharray_")?new Ur(e,i):new yr(e,i)}}class gt{constructor(e,i,o,s){this.expression=e,this.type=o,this.maxValue=0,this.paintVertexAttributes=i.map((l=>({name:`a_${l}`,type:"Float32",components:o==="color"?2:1,offset:0}))),this.paintVertexArray=new s}populatePaintArray(e,i,o){let s=this.paintVertexArray.length,l=this.expression.evaluate(new ct(0,o),i,{},o.canonical,[],o.formattedSection);this.paintVertexArray.resize(e),this._setPaintValue(s,e,l)}updatePaintArray(e,i,o,s,l){let h=this.expression.evaluate(new ct(0,l),o,s);this._setPaintValue(e,i,h)}_setPaintValue(e,i,o){if(this.type==="color"){let s=ar(o);for(let l=e;l`u_${d}_t`)),this.type=o,this.useIntegerZoom=s,this.zoom=l,this.maxValue=0,this.paintVertexAttributes=i.map((d=>({name:`a_${d}`,type:"Float32",components:o==="color"?4:2,offset:0}))),this.paintVertexArray=new h}populatePaintArray(e,i,o){let s=this.expression.evaluate(new ct(this.zoom,o),i,{},o.canonical,[],o.formattedSection),l=this.expression.evaluate(new ct(this.zoom+1,o),i,{},o.canonical,[],o.formattedSection),h=this.paintVertexArray.length;this.paintVertexArray.resize(e),this._setPaintValue(h,e,s,l)}updatePaintArray(e,i,o,s,l){let h=this.expression.evaluate(new ct(this.zoom,l),o,s),d=this.expression.evaluate(new ct(this.zoom+1,l),o,s);this._setPaintValue(e,i,h,d)}_setPaintValue(e,i,o,s){if(this.type==="color"){let l=ar(o),h=ar(s);for(let d=e;d`#define HAS_UNIFORM_${s}`)))}return e}getBinderAttributes(){let e=[];for(let i in this.binders){let o=this.binders[i];if(o instanceof gt||o instanceof ut)for(let s of o.paintVertexAttributes)e.push(s.name);else if(o instanceof zt){let s=o.getVertexAttributes();for(let l of s)e.push(l.name)}}return e}getBinderUniforms(){let e=[];for(let i in this.binders){let o=this.binders[i];if(o instanceof Ri||o instanceof Gi||o instanceof ut)for(let s of o.uniformNames)e.push(s)}return e}getPaintVertexBuffers(){return this._buffers}getUniforms(e,i){let o=[];for(let s in this.binders){let l=this.binders[s];if(l instanceof Ri||l instanceof Gi||l instanceof ut){for(let h of l.uniformNames)if(i[h]){let d=l.getBinding(e,i[h],h);o.push({name:h,property:s,binding:d})}}}return o}setUniforms(e,i,o,s){for(let{name:l,property:h,binding:d}of i)this.binders[h].setUniform(d,s,o.get(h),l)}updatePaintBuffers(e){this._buffers=[];for(let i in this.binders){let o=this.binders[i];if(e&&o instanceof zt){let s=e.fromScale===2?o.zoomInPaintVertexBuffer:o.zoomOutPaintVertexBuffer;s&&this._buffers.push(s)}else(o instanceof gt||o instanceof ut)&&o.paintVertexBuffer&&this._buffers.push(o.paintVertexBuffer)}}upload(e){for(let i in this.binders){let o=this.binders[i];(o instanceof gt||o instanceof ut||o instanceof zt)&&o.upload(e)}this.updatePaintBuffers()}destroy(){for(let e in this.binders){let i=this.binders[e];(i instanceof gt||i instanceof ut||i instanceof zt)&&i.destroy()}}}class vr{constructor(e,i,o=()=>!0){this.programConfigurations={};for(let s of e)this.programConfigurations[s.id]=new na(s,i,o);this.needsUpload=!1,this._featureMap=new ii,this._bufferOffset=0}populatePaintArrays(e,i,o,s){for(let l in this.programConfigurations)this.programConfigurations[l].populatePaintArrays(e,i,s);i.id!==void 0&&this._featureMap.add(i.id,o,this._bufferOffset,e),this._bufferOffset=e,this.needsUpload=!0}updatePaintArrays(e,i,o,s){for(let l of o)this.needsUpload=this.programConfigurations[l.id].updatePaintArrays(e,this._featureMap,i,l,s)||this.needsUpload}get(e){return this.programConfigurations[e]}upload(e){if(this.needsUpload){for(let i in this.programConfigurations)this.programConfigurations[i].upload(e);this.needsUpload=!1}}destroy(){for(let e in this.programConfigurations)this.programConfigurations[e].destroy()}}function Ll(r,e){return{"text-opacity":["opacity"],"icon-opacity":["opacity"],"text-color":["fill_color"],"icon-color":["fill_color"],"text-halo-color":["halo_color"],"icon-halo-color":["halo_color"],"text-halo-blur":["halo_blur"],"icon-halo-blur":["halo_blur"],"text-halo-width":["halo_width"],"icon-halo-width":["halo_width"],"line-gap-width":["gapwidth"],"line-dasharray":["dasharray_to","dasharray_from"],"line-pattern":["pattern_to","pattern_from","pixel_ratio_to","pixel_ratio_from"],"fill-pattern":["pattern_to","pattern_from","pixel_ratio_to","pixel_ratio_from"],"fill-extrusion-pattern":["pattern_to","pattern_from","pixel_ratio_to","pixel_ratio_from"]}[r]||[r.replace(`${e}-`,"").replace(/-/g,"_")]}function ah(r,e,i){let o={color:{source:es,composite:n},number:{source:ta,composite:es}},s=(function(l){return{"line-pattern":{source:U,composite:U},"fill-pattern":{source:U,composite:U},"fill-extrusion-pattern":{source:U,composite:U},"line-dasharray":{source:H,composite:H}}[l]})(r);return s?.[i]||o[e][i]}Pe("ConstantBinder",Ri),Pe("CrossFadedConstantBinder",Gi),Pe("SourceExpressionBinder",gt),Pe("CrossFadedPatternBinder",_t),Pe("CrossFadedDasharrayBinder",Pn),Pe("CompositeExpressionBinder",ut),Pe("ProgramConfiguration",na,{omit:["_buffers"]}),Pe("ProgramConfigurationSet",vr);let Fl=Math.pow(2,14)-1,Gr=-Fl-1;function $r(r){let e=De/r.extent,i=r.loadGeometry();for(let o of i)for(let s of o){let l=Math.round(s.x*e),h=Math.round(s.y*e);s.x=li(l,Gr,Fl),s.y=li(h,Gr,Fl),(ls.x+1||hs.y+1)&&Wt("Geometry exceeds allowed extent, reduce your vector tile buffer size")}return i}function Zr(r,e){return{type:r.type,id:r.id,properties:r.properties,geometry:e?$r(r):[]}}let Bl=-32768;function Ol(r,e,i,o,s){r.emplaceBack(Bl+8*e+o,Bl+8*i+s)}class oa{constructor(e){this.zoom=e.zoom,this.overscaling=e.overscaling,this.layers=e.layers,this.layerIds=this.layers.map((i=>i.id)),this.index=e.index,this.hasDependencies=!1,this.layoutVertexArray=new G,this.indexArray=new ue,this.segments=new we,this.programConfigurations=new vr(e.layers,e.zoom),this.stateDependentLayerIds=this.layers.filter((i=>i.isStateDependent())).map((i=>i.id))}populate(e,i,o){let s=this.layers[0],l=[],h=null,d=!1,g=s.type==="heatmap";if(s.type==="circle"){let v=s;h=v.layout.get("circle-sort-key"),d=!h.isConstant(),g||(g=v.paint.get("circle-pitch-alignment")==="map")}let m=g?i.subdivisionGranularity.circle:1;for(let{feature:v,id:_,index:T,sourceLayerIndex:b}of e){let I=this.layers[0]._featureFilter.needGeometry,M=Zr(v,I);if(!this.layers[0]._featureFilter.filter(new ct(this.zoom),M,o))continue;let A=d?h.evaluate(M,{},o):void 0,D={id:_,properties:v.properties,type:v.type,sourceLayerIndex:b,index:T,geometry:I?M.geometry:$r(v),patterns:{},sortKey:A};l.push(D)}d&&l.sort(((v,_)=>v.sortKey-_.sortKey));for(let v of l){let{geometry:_,index:T,sourceLayerIndex:b}=v,I=e[T].feature;this.addFeature(v,_,T,o,m),i.featureIndex.insert(I,_,T,b,this.index)}}update(e,i,o){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(e,i,this.stateDependentLayers,{imagePositions:o})}isEmpty(){return this.layoutVertexArray.length===0}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload}upload(e){this.uploaded||(this.layoutVertexBuffer=e.createVertexBuffer(this.layoutVertexArray,he),this.indexBuffer=e.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(e),this.uploaded=!0}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy())}addFeature(e,i,o,s,l=1){let h;switch(l){case 1:h=[0,7];break;case 3:h=[0,2,5,7];break;case 5:h=[0,1,3,4,6,7];break;case 7:h=[0,1,2,3,4,5,6,7];break;default:throw new Error(`Invalid circle bucket granularity: ${l}; valid values are 1, 3, 5, 7.`)}let d=h.length;for(let g of i)for(let m of g){let v=m.x,_=m.y;if(v<0||v>=De||_<0||_>=De)continue;let T=this.segments.prepareSegment(d*d,this.layoutVertexArray,this.indexArray,e.sortKey),b=T.vertexLength;for(let I=0;I1){if(hu(r,e))return!0;for(let o of e)if(uu(o,r,i))return!0}for(let o of r)if(uu(o,e,i))return!0;return!1}function hu(r,e){if(r.length===0||e.length===0)return!1;for(let i=0;i1?i:i.sub(e)._mult(s)._add(e))}function Td(r,e){let i,o,s,l=!1;for(let h of r){i=h;for(let d=0,g=i.length-1;de.y!=s.y>e.y&&e.x<(s.x-o.x)*(e.y-o.y)/(s.y-o.y)+o.x&&(l=!l)}return l}function aa(r,e){let i=!1;for(let o=0,s=r.length-1;oe.y!=h.y>e.y&&e.x<(h.x-l.x)*(e.y-l.y)/(h.y-l.y)+l.x&&(i=!i)}return i}function Kf(r,e,i){let o=i[0],s=i[2];if(r.xs.x&&e.x>s.x||r.ys.y&&e.y>s.y)return!1;let l=Mi(r,e,i[0]);return l!==Mi(r,e,i[1])||l!==Mi(r,e,i[2])||l!==Mi(r,e,i[3])}function la(r,e,i){let o=e.paint.get(r).value;return o.kind==="constant"?o.value:i.programConfigurations.get(e.id).getMaxValue(r)}function ch(r){return Math.sqrt(r[0]*r[0]+r[1]*r[1])}function hh(r,e,i,o,s){if(!e[0]&&!e[1])return r;let l=Te.convert(e)._mult(s);i==="viewport"&&l._rotate(-o);let h=[];for(let d of r)h.push(d.sub(l));return h}function Jf(r){let e=[];for(let i=0;idu(R,A,D,L)))})(m,l,d,g),I=v),Pd({queryGeometry:b,size:I,transform:l,unwrappedTileID:d,getElevation:g,pitchAlignment:T,pitchScale:_},s)}}class Md extends oa{}let Ed;Pe("HeatmapBucket",Md,{omit:["layers"]});var om={get paint(){return Ed=Ed||new ui({"heatmap-radius":new Ce(ce.paint_heatmap["heatmap-radius"]),"heatmap-weight":new Ce(ce.paint_heatmap["heatmap-weight"]),"heatmap-intensity":new Ie(ce.paint_heatmap["heatmap-intensity"]),"heatmap-color":new oo(ce.paint_heatmap["heatmap-color"]),"heatmap-opacity":new Ie(ce.paint_heatmap["heatmap-opacity"])})}};function pu(r,{width:e,height:i},o,s){if(s){if(s instanceof Uint8ClampedArray)s=new Uint8Array(s.buffer);else if(s.length!==e*i*o)throw new RangeError(`mismatched image size. expected: ${s.length} but got: ${e*i*o}`)}else s=new Uint8Array(e*i*o);return r.width=e,r.height=i,r.data=s,r}function Cd(r,{width:e,height:i},o){if(e===r.width&&i===r.height)return;let s=pu({},{width:e,height:i},o);fu(r,s,{x:0,y:0},{x:0,y:0},{width:Math.min(r.width,e),height:Math.min(r.height,i)},o),r.width=e,r.height=i,r.data=s.data}function fu(r,e,i,o,s,l){if(s.width===0||s.height===0)return e;if(s.width>r.width||s.height>r.height||i.x>r.width-s.width||i.y>r.height-s.height)throw new RangeError("out of range source coordinates for image copy");if(s.width>e.width||s.height>e.height||o.x>e.width-s.width||o.y>e.height-s.height)throw new RangeError("out of range destination coordinates for image copy");let h=r.data,d=e.data;if(h===d)throw new Error("srcData equals dstData, so image is already copied");for(let g=0;g{e[r.evaluationKey]=g;let m=r.expression.evaluate(e);s.setPixel(h/4/i,d/4,m)};if(r.clips)for(let h=0,d=0;hthis.max&&(this.max=_),_=this.dim+1||i<-1||i>=this.dim+1)throw new RangeError(`Out of range source coordinates for DEM data. x: ${e}, y: ${i}, dim: ${this.dim}`);return(i+1)*this.stride+(e+1)}unpack(e,i,o){return e*this.redFactor+i*this.greenFactor+o*this.blueFactor-this.baseShift}pack(e){return Fd(e,this.getUnpackVector())}getPixels(){return new ki({width:this.stride,height:this.stride},new Uint8Array(this.data.buffer))}backfillBorder(e,i,o){if(this.dim!==e.dim)throw new Error("dem dimension mismatch");let s=i*this.dim,l=i*this.dim+this.dim,h=o*this.dim,d=o*this.dim+this.dim;switch(i){case-1:s=l-1;break;case 1:l=s+1}switch(o){case-1:h=d-1;break;case 1:d=h+1}let g=-i*this.dim,m=-o*this.dim;for(let v=h;v0)for(let h=e;h=e;h-=o)l=jd(h/o|0,r[h],r[h+1],l);return l&&ca(l,l.next)&&(Gl(l),l=l.next),l}function ns(r,e){if(!r)return r;e||(e=r);let i,o=r;do if(i=!1,o.steiner||!ca(o,o.next)&&At(o.prev,o,o.next)!==0)o=o.next;else{if(Gl(o),o=e=o.prev,o===o.next)break;i=!0}while(i||o!==e);return e}function Vl(r,e,i,o,s,l,h){if(!r)return;!h&&l&&(function(g,m,v,_){let T=g;do T.z===0&&(T.z=yu(T.x,T.y,m,v,_)),T.prevZ=T.prev,T.nextZ=T.next,T=T.next;while(T!==g);T.prevZ.nextZ=null,T.prevZ=null,(function(b){let I,M=1;do{let A,D=b;b=null;let L=null;for(I=0;D;){I++;let R=D,F=0;for(let V=0;V0||O>0&&R;)F!==0&&(O===0||!R||D.z<=R.z)?(A=D,D=D.nextZ,F--):(A=R,R=R.nextZ,O--),L?L.nextZ=A:b=A,A.prevZ=L,L=A;D=R}L.nextZ=null,M*=2}while(I>1)})(T)})(r,o,s,l);let d=r;for(;r.prev!==r.next;){let g=r.prev,m=r.next;if(l?fm(r,o,s,l):pm(r))e.push(g.i,r.i,m.i),Gl(r),r=m.next,d=m.next;else if((r=m)===d){h?h===1?Vl(r=mm(ns(r),e),e,i,o,s,l,2):h===2&&gm(r,e,i,o,s,l):Vl(ns(r),e,i,o,s,l,1);break}}}function pm(r){let e=r.prev,i=r,o=r.next;if(At(e,i,o)>=0)return!1;let s=e.x,l=i.x,h=o.x,d=e.y,g=i.y,m=o.y,v=Math.min(s,l,h),_=Math.min(d,g,m),T=Math.max(s,l,h),b=Math.max(d,g,m),I=o.next;for(;I!==e;){if(I.x>=v&&I.x<=T&&I.y>=_&&I.y<=b&&jl(s,d,l,g,h,m,I.x,I.y)&&At(I.prev,I,I.next)>=0)return!1;I=I.next}return!0}function fm(r,e,i,o){let s=r.prev,l=r,h=r.next;if(At(s,l,h)>=0)return!1;let d=s.x,g=l.x,m=h.x,v=s.y,_=l.y,T=h.y,b=Math.min(d,g,m),I=Math.min(v,_,T),M=Math.max(d,g,m),A=Math.max(v,_,T),D=yu(b,I,e,i,o),L=yu(M,A,e,i,o),R=r.prevZ,F=r.nextZ;for(;R&&R.z>=D&&F&&F.z<=L;){if(R.x>=b&&R.x<=M&&R.y>=I&&R.y<=A&&R!==s&&R!==h&&jl(d,v,g,_,m,T,R.x,R.y)&&At(R.prev,R,R.next)>=0||(R=R.prevZ,F.x>=b&&F.x<=M&&F.y>=I&&F.y<=A&&F!==s&&F!==h&&jl(d,v,g,_,m,T,F.x,F.y)&&At(F.prev,F,F.next)>=0))return!1;F=F.nextZ}for(;R&&R.z>=D;){if(R.x>=b&&R.x<=M&&R.y>=I&&R.y<=A&&R!==s&&R!==h&&jl(d,v,g,_,m,T,R.x,R.y)&&At(R.prev,R,R.next)>=0)return!1;R=R.prevZ}for(;F&&F.z<=L;){if(F.x>=b&&F.x<=M&&F.y>=I&&F.y<=A&&F!==s&&F!==h&&jl(d,v,g,_,m,T,F.x,F.y)&&At(F.prev,F,F.next)>=0)return!1;F=F.nextZ}return!0}function mm(r,e){let i=r;do{let o=i.prev,s=i.next.next;!ca(o,s)&&Nd(o,i,i.next,s)&&Ul(o,s)&&Ul(s,o)&&(e.push(o.i,i.i,s.i),Gl(i),Gl(i.next),i=r=s),i=i.next}while(i!==r);return ns(i)}function gm(r,e,i,o,s,l){let h=r;do{let d=h.next.next;for(;d!==h.prev;){if(h.i!==d.i&&bm(h,d)){let g=Vd(h,d);return h=ns(h,h.next),g=ns(g,g.next),Vl(h,e,i,o,s,l,0),void Vl(g,e,i,o,s,l,0)}d=d.next}h=h.next}while(h!==r)}function _m(r,e){let i=r.x-e.x;return i===0&&(i=r.y-e.y,i===0)&&(i=(r.next.y-r.y)/(r.next.x-r.x)-(e.next.y-e.y)/(e.next.x-e.x)),i}function ym(r,e){let i=(function(s,l){let h=l,d=s.x,g=s.y,m,v=-1/0;if(ca(s,h))return h;do{if(ca(s,h.next))return h.next;if(g<=h.y&&g>=h.next.y&&h.next.y!==h.y){let M=h.x+(g-h.y)*(h.next.x-h.x)/(h.next.y-h.y);if(M<=d&&M>v&&(v=M,m=h.x=h.x&&h.x>=T&&d!==h.x&&Od(gm.x||h.x===m.x&&vm(m,h)))&&(m=h,I=M)}h=h.next}while(h!==_);return m})(r,e);if(!i)return e;let o=Vd(i,r);return ns(o,o.next),ns(i,i.next)}function vm(r,e){return At(r.prev,r,e.prev)<0&&At(e.next,r,r.next)<0}function yu(r,e,i,o,s){return(r=1431655765&((r=858993459&((r=252645135&((r=16711935&((r=(r-i)*s|0)|r<<8))|r<<4))|r<<2))|r<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=(e-o)*s|0)|e<<8))|e<<4))|e<<2))|e<<1))<<1}function xm(r){let e=r,i=r;do(e.x=(r-h)*(l-d)&&(r-h)*(o-d)>=(i-h)*(e-d)&&(i-h)*(l-d)>=(s-h)*(o-d)}function jl(r,e,i,o,s,l,h,d){return!(r===h&&e===d)&&Od(r,e,i,o,s,l,h,d)}function bm(r,e){return r.next.i!==e.i&&r.prev.i!==e.i&&!(function(i,o){let s=i;do{if(s.i!==i.i&&s.next.i!==i.i&&s.i!==o.i&&s.next.i!==o.i&&Nd(s,s.next,i,o))return!0;s=s.next}while(s!==i);return!1})(r,e)&&(Ul(r,e)&&Ul(e,r)&&(function(i,o){let s=i,l=!1,h=(i.x+o.x)/2,d=(i.y+o.y)/2;do s.y>d!=s.next.y>d&&s.next.y!==s.y&&h<(s.next.x-s.x)*(d-s.y)/(s.next.y-s.y)+s.x&&(l=!l),s=s.next;while(s!==i);return l})(r,e)&&(At(r.prev,r,e.prev)||At(r,e.prev,e))||ca(r,e)&&At(r.prev,r,r.next)>0&&At(e.prev,e,e.next)>0)}function At(r,e,i){return(e.y-r.y)*(i.x-e.x)-(e.x-r.x)*(i.y-e.y)}function ca(r,e){return r.x===e.x&&r.y===e.y}function Nd(r,e,i,o){let s=ph(At(r,e,i)),l=ph(At(r,e,o)),h=ph(At(i,o,r)),d=ph(At(i,o,e));return s!==l&&h!==d||!(s!==0||!dh(r,i,e))||!(l!==0||!dh(r,o,e))||!(h!==0||!dh(i,r,o))||!(d!==0||!dh(i,e,o))}function dh(r,e,i){return e.x<=Math.max(r.x,i.x)&&e.x>=Math.min(r.x,i.x)&&e.y<=Math.max(r.y,i.y)&&e.y>=Math.min(r.y,i.y)}function ph(r){return r>0?1:r<0?-1:0}function Ul(r,e){return At(r.prev,r,r.next)<0?At(r,e,r.next)>=0&&At(r,r.prev,e)>=0:At(r,e,r.prev)<0||At(r,r.next,e)<0}function Vd(r,e){let i=vu(r.i,r.x,r.y),o=vu(e.i,e.x,e.y),s=r.next,l=e.prev;return r.next=e,e.prev=r,i.next=s,s.prev=i,o.next=i,i.prev=o,l.next=o,o.prev=l,o}function jd(r,e,i,o){let s=vu(r,e,i);return o?(s.next=o.next,s.prev=o,o.next.prev=s,o.next=s):(s.prev=s,s.next=s),s}function Gl(r){r.next.prev=r.prev,r.prev.next=r.next,r.prevZ&&(r.prevZ.nextZ=r.nextZ),r.nextZ&&(r.nextZ.prevZ=r.prevZ)}function vu(r,e,i){return{i:r,x:e,y:i,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}class ha{constructor(e,i){if(i>e)throw new Error("Min granularity must not be greater than base granularity.");this._baseZoomGranularity=e,this._minGranularity=i}getGranularityForZoomLevel(e){return Math.max(Math.floor(this._baseZoomGranularity/(1<32767||i>32767)throw new Error("Vertex coordinates are out of signed 16 bit integer range.");let o=0|Math.round(e),s=0|Math.round(i),l=this._getKey(o,s);if(this._vertexDictionary.has(l))return this._vertexDictionary.get(l);let h=this._vertexBuffer.length/2;return this._vertexDictionary.set(l,h),this._vertexBuffer.push(o,s),h}_subdivideTrianglesScanline(e){if(this._granularity<2)return(function(s,l){let h=[];for(let d=0;d0?(h.push(g),h.push(v),h.push(m)):(h.push(g),h.push(m),h.push(v))}return h})(this._vertexBuffer,e);let i=[],o=e.length;for(let s=0;s=1||O<=0)||D&&(ml)){_>=s&&_<=l&&h.push(o[(d+1)%3]);continue}!D&&F>0&&h.push(this._vertexToIndex(g+I*F,m+M*F));let V=g+I*Math.max(F,0),Y=g+I*Math.min(O,1);A||this._generateIntraEdgeVertices(h,g,m,v,_,V,Y),!D&&O<1&&h.push(this._vertexToIndex(g+I*O,m+M*O)),(D||_>=s&&_<=l)&&h.push(o[(d+1)%3]),!D&&(_<=s||_>=l)&&this._generateInterEdgeVertices(h,g,m,v,_,T,b,Y,s,l)}return h}_generateIntraEdgeVertices(e,i,o,s,l,h,d){let g=s-i,m=l-o,v=m===0,_=v?Math.min(i,s):Math.min(h,d),T=v?Math.max(i,s):Math.max(h,d),b=Math.floor(_/this._granularityCellSize)+1,I=Math.ceil(T/this._granularityCellSize)-1;if(v?i=b;M--){let A=M*this._granularityCellSize;e.push(this._vertexToIndex(A,o+m*(A-i)/g))}}_generateInterEdgeVertices(e,i,o,s,l,h,d,g,m,v){let _=l-o,T=h-s,b=d-l,I=(m-l)/b,M=(v-l)/b,A=Math.min(I,M),D=Math.max(I,M),L=s+T*A,R=Math.floor(Math.min(L,g)/this._granularityCellSize)+1,F=Math.ceil(Math.max(L,g)/this._granularityCellSize)-1,O=g=1||D<=0){let J=o-d,re=h+(i-h)*Math.min((m-d)/J,(v-d)/J);R=Math.floor(Math.min(re,g)/this._granularityCellSize)+1,F=Math.ceil(Math.max(re,g)/this._granularityCellSize)-1,O=g0?v:m;if(O)for(let J=R;J<=F;J++)e.push(this._vertexToIndex(J*this._granularityCellSize,Y));else for(let J=F;J>=R;J--)e.push(this._vertexToIndex(J*this._granularityCellSize,Y))}_generateOutline(e){let i=[];for(let o of e){let s=os(o,this._granularity,!0),l=this._pointArrayToIndices(s),h=[];for(let d=1;dl!=(h===ua)?(e.push(i),e.push(o),e.push(this._vertexToIndex(s,h)),e.push(o),e.push(this._vertexToIndex(l,h)),e.push(this._vertexToIndex(s,h))):(e.push(o),e.push(i),e.push(this._vertexToIndex(s,h)),e.push(this._vertexToIndex(l,h)),e.push(o),e.push(this._vertexToIndex(s,h)))}_fillPoles(e,i,o){let s=this._vertexBuffer,l=De,h=e.length;for(let d=2;d80*_){A=m[0],D=m[1];let R=A,F=D;for(let O=_;OR&&(R=V),Y>F&&(F=Y)}L=Math.max(R-A,F-D),L=L!==0?32767/L:0}return Vl(I,M,_,A,D,L,0),M})(o,s),g=this._convertIndices(o,d);l=this._subdivideTrianglesScanline(g)}catch(d){console.error(d)}let h=[];return i&&(h=this._generateOutline(e)),this._ensureNoPoleVertices(),this._handlePoles(l),{verticesFlattened:this._vertexBuffer,indicesTriangles:l,indicesLineList:h}}_convertIndices(e,i){let o=[];for(let s of i)o.push(this._vertexToIndex(e[2*s],e[2*s+1]));return o}_pointArrayToIndices(e){let i=[];for(let o of e)i.push(this._vertexToIndex(o.x,o.y));return i}}function Ud(r,e,i,o=!0){return new wm(i,e).subdividePolygonInternal(r,o)}function os(r,e,i=!1){if(!r||r.length<1)return[];if(r.length<2)return[];let o=r[0],s=r[r.length-1],l=i&&(o.x!==s.x||o.y!==s.y);if(e<2)return l?[...r,r[0]]:[...r];let h=Math.floor(De/e),d=[];d.push(new Te(r[0].x,r[0].y));let g=r.length,m=l?g:g-1;for(let v=0;v0?(Math.floor(Y/h)+1)*h:(Math.ceil(Y/h)-1)*h,ae=F>0?(Math.floor(J/h)+1)*h:(Math.ceil(J/h)-1)*h,le=Math.abs(Y-te),ne=Math.abs(J-ae),ie=Math.abs(Y-M),fe=Math.abs(J-A),xe=D?le/O:Number.POSITIVE_INFINITY,ye=L?ne/V:Number.POSITIVE_INFINITY;if((ie<=le||!D)&&(fe<=ne||!L))break;if(xe=0?h-1:l-1,m=(d+1)%l,v=r[2*e[g]],_=r[2*e[m]],T=r[2*e[h]],b=r[2*e[h]+1],I=r[2*e[d]+1],M=!1;if(v<_)M=!0;else if(v>_)M=!1;else{let A=I-b,D=-(r[2*e[d]]-T),L=b((_-T)*A+(r[2*e[m]+1]-b)*D)*L&&(M=!0)}if(M){let A=e[g],D=e[h],L=e[d];A!==D&&A!==L&&D!==L&&i.push(L,D,A),h--,h<0&&(h=l-1)}else{let A=e[m],D=e[h],L=e[d];A!==D&&A!==L&&D!==L&&i.push(L,D,A),d++,d>=l&&(d=0)}if(g===m)break}}function Gd(r,e,i,o,s,l,h,d,g){let m=s.length/2,v=h&&d&&g;if(mwe.MAX_VERTEX_ARRAY_LENGTH&&(F=_.createNewSegment(T,b),R=L.count,te=!0,ae=!0,le=!0,O=0);let ne=Zl(D,I,A,L,Y,te,F),ie=Zl(D,I,A,L,J,ae,F),fe=Zl(D,I,A,L,re,le,F);b.emplaceBack(O+ne-R,O+ie-R,O+fe-R),F.primitiveLength++}})(e,i,o,s,l,r),v&&(function(_,T,b,I,M,A){let D=[];for(let V=0;Vwe.MAX_VERTEX_ARRAY_LENGTH&&(F=_.createNewSegment(T,b),R=L.count,te=!0,ae=!0,O=0);let le=Zl(D,I,A,L,J,te,F),ne=Zl(D,I,A,L,re,ae,F);b.emplaceBack(O+le-R,O+ne-R),F.primitiveLength++}})(h,i,d,s,g,r),e.forceNewSegmentOnNextPrepare(),h?.forceNewSegmentOnNextPrepare()}function Zl(r,e,i,o,s,l,h){if(l){let d=o.count;return i(e[2*s],e[2*s+1]),r[s]=o.count,o.count++,h.vertexLength++,d}return r[s]}class xu{constructor(e){this.zoom=e.zoom,this.overscaling=e.overscaling,this.layers=e.layers,this.layerIds=this.layers.map((i=>i.id)),this.index=e.index,this.hasDependencies=!1,this.patternFeatures=[],this.layoutVertexArray=new j,this.indexArray=new ue,this.indexArray2=new Se,this.programConfigurations=new vr(e.layers,e.zoom),this.segments=new we,this.segments2=new we,this.stateDependentLayerIds=this.layers.filter((i=>i.isStateDependent())).map((i=>i.id))}populate(e,i,o){this.hasDependencies=uh("fill",this.layers,i);let s=this.layers[0].layout.get("fill-sort-key"),l=!s.isConstant(),h=[];for(let{feature:d,id:g,index:m,sourceLayerIndex:v}of e){let _=this.layers[0]._featureFilter.needGeometry,T=Zr(d,_);if(!this.layers[0]._featureFilter.filter(new ct(this.zoom),T,o))continue;let b=l?s.evaluate(T,{},o,i.availableImages):void 0,I={id:g,properties:d.properties,type:d.type,sourceLayerIndex:v,index:m,geometry:_?T.geometry:$r(d),patterns:{},sortKey:b};h.push(I)}l&&h.sort(((d,g)=>d.sortKey-g.sortKey));for(let d of h){let{geometry:g,index:m,sourceLayerIndex:v}=d;if(this.hasDependencies){let _=_u("fill",this.layers,d,{zoom:this.zoom},i);this.patternFeatures.push(_)}else this.addFeature(d,g,m,o,{},i.subdivisionGranularity);i.featureIndex.insert(e[m].feature,g,m,v,this.index)}}update(e,i,o){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(e,i,this.stateDependentLayers,{imagePositions:o})}addFeatures(e,i,o){for(let s of this.patternFeatures)this.addFeature(s,s.geometry,s.index,i,o,e.subdivisionGranularity)}isEmpty(){return this.layoutVertexArray.length===0}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload}upload(e){this.uploaded||(this.layoutVertexBuffer=e.createVertexBuffer(this.layoutVertexArray,dm),this.indexBuffer=e.createIndexBuffer(this.indexArray),this.indexBuffer2=e.createIndexBuffer(this.indexArray2)),this.programConfigurations.upload(e),this.uploaded=!0}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.indexBuffer2.destroy(),this.programConfigurations.destroy(),this.segments.destroy(),this.segments2.destroy())}addFeature(e,i,o,s,l,h){for(let d of As(i,500)){let g=Ud(d,s,h.fill.getGranularityForZoomLevel(s.z)),m=this.layoutVertexArray;Gd(((v,_)=>{m.emplaceBack(v,_)}),this.segments,this.layoutVertexArray,this.indexArray,g.verticesFlattened,g.indicesTriangles,this.segments2,this.indexArray2,g.indicesLineList)}this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,e,o,{imagePositions:l,canonical:s})}}let $d,Zd;Pe("FillBucket",xu,{omit:["layers","patternFeatures"]});var Pm={get paint(){return Zd=Zd||new ui({"fill-antialias":new Ie(ce.paint_fill["fill-antialias"]),"fill-opacity":new Ce(ce.paint_fill["fill-opacity"]),"fill-color":new Ce(ce.paint_fill["fill-color"]),"fill-outline-color":new Ce(ce.paint_fill["fill-outline-color"]),"fill-translate":new Ie(ce.paint_fill["fill-translate"]),"fill-translate-anchor":new Ie(ce.paint_fill["fill-translate-anchor"]),"fill-pattern":new Or(ce.paint_fill["fill-pattern"])})},get layout(){return $d=$d||new ui({"fill-sort-key":new Ce(ce.layout_fill["fill-sort-key"])})}};class Sm extends Ui{constructor(e,i){super(e,Pm,i)}recalculate(e,i){super.recalculate(e,i);let o=this.paint._values["fill-outline-color"];o.value.kind==="constant"&&o.value.value===void 0&&(this.paint._values["fill-outline-color"]=this.paint._values["fill-color"])}createBucket(e){return new xu(e)}queryRadius(){return ch(this.paint.get("fill-translate"))}queryIntersectsFeature({queryGeometry:e,geometry:i,transform:o,pixelsToTileUnits:s}){return bd(hh(e,this.paint.get("fill-translate"),this.paint.get("fill-translate-anchor"),-o.bearingInRadians,s),i)}isTileClipped(){return!0}}let Im=ht([{name:"a_pos",components:2,type:"Int16"},{name:"a_normal_ed",components:4,type:"Int16"}],4),Mm=ht([{name:"a_centroid",components:2,type:"Int16"}],4),{members:Em}=Im;class ql{constructor(e,i,o,s,l){this.properties={},this.extent=o,this.type=0,this.id=void 0,this._pbf=e,this._geometry=-1,this._keys=s,this._values=l,e.readFields(Cm,this,i)}loadGeometry(){let e=this._pbf;e.pos=this._geometry;let i=e.readVarint()+e.pos,o=[],s,l=1,h=0,d=0,g=0;for(;e.pos>3}if(h--,l===1||l===2)d+=e.readSVarint(),g+=e.readSVarint(),l===1&&(s&&o.push(s),s=[]),s&&s.push(new Te(d,g));else{if(l!==7)throw new Error(`unknown command ${l}`);s&&s.push(s[0].clone())}}return s&&o.push(s),o}bbox(){let e=this._pbf;e.pos=this._geometry;let i=e.readVarint()+e.pos,o=1,s=0,l=0,h=0,d=1/0,g=-1/0,m=1/0,v=-1/0;for(;e.pos>3}if(s--,o===1||o===2)l+=e.readSVarint(),h+=e.readSVarint(),lg&&(g=l),hv&&(v=h);else if(o!==7)throw new Error(`unknown command ${o}`)}return[d,m,g,v]}toGeoJSON(e,i,o){let s=this.extent*Math.pow(2,o),l=this.extent*e,h=this.extent*i,d=this.loadGeometry();function g(T){return[360*(T.x+l)/s-180,360/Math.PI*Math.atan(Math.exp((1-2*(T.y+h)/s)*Math.PI))-90]}function m(T){return T.map(g)}let v;if(this.type===1){let T=[];for(let I of d)T.push(I[0]);let b=m(T);v=T.length===1?{type:"Point",coordinates:b[0]}:{type:"MultiPoint",coordinates:b}}else if(this.type===2){let T=d.map(m);v=T.length===1?{type:"LineString",coordinates:T[0]}:{type:"MultiLineString",coordinates:T}}else{if(this.type!==3)throw new Error("unknown feature type");{let T=qd(d),b=[];for(let I of T)b.push(I.map(m));v=b.length===1?{type:"Polygon",coordinates:b[0]}:{type:"MultiPolygon",coordinates:b}}}let _={type:"Feature",geometry:v,properties:this.properties};return this.id!=null&&(_.id=this.id),_}}function Cm(r,e,i){r===1?e.id=i.readVarint():r===2?(function(o,s){let l=o.readVarint()+o.pos;for(;o.pos=this._features.length)throw new Error("feature index out of bounds");this._pbf.pos=this._features[e];let i=this._pbf.readVarint()+this._pbf.pos;return new ql(this._pbf,i,this.extent,this._keys,this._values)}}function zm(r,e,i){r===15?e.version=i.readVarint():r===1?e.name=i.readString():r===5?e.extent=i.readVarint():r===2?e._features.push(i.pos):r===3?e._keys.push(i.readString()):r===4&&e._values.push((function(o){let s=null,l=o.readVarint()+o.pos;for(;o.pos>3;s=h===1?o.readString():h===2?o.readFloat():h===3?o.readDouble():h===4?o.readVarint64():h===5?o.readVarint():h===6?o.readSVarint():h===7?o.readBoolean():null}if(s==null)throw new Error("unknown feature value");return s})(i))}class Wd{constructor(e,i){this.layers=e.readFields(Rm,{},i)}}function Rm(r,e,i){if(r===3){let o=new Dm(i,i.readVarint()+i.pos);o.length&&(e[o.name]=o)}}let bu=Math.pow(2,13);function Wl(r,e,i,o,s,l,h,d){r.emplaceBack(e,i,2*Math.floor(o*bu)+h,s*bu*2,l*bu*2,Math.round(d))}class wu{constructor(e){this.zoom=e.zoom,this.overscaling=e.overscaling,this.layers=e.layers,this.layerIds=this.layers.map((i=>i.id)),this.index=e.index,this.hasDependencies=!1,this.layoutVertexArray=new $,this.centroidVertexArray=new N,this.indexArray=new ue,this.programConfigurations=new vr(e.layers,e.zoom),this.segments=new we,this.stateDependentLayerIds=this.layers.filter((i=>i.isStateDependent())).map((i=>i.id))}populate(e,i,o){this.features=[],this.hasDependencies=uh("fill-extrusion",this.layers,i);for(let{feature:s,id:l,index:h,sourceLayerIndex:d}of e){let g=this.layers[0]._featureFilter.needGeometry,m=Zr(s,g);if(!this.layers[0]._featureFilter.filter(new ct(this.zoom),m,o))continue;let v={id:l,sourceLayerIndex:d,index:h,geometry:g?m.geometry:$r(s),properties:s.properties,type:s.type,patterns:{}};this.hasDependencies?this.features.push(_u("fill-extrusion",this.layers,v,{zoom:this.zoom},i)):this.addFeature(v,v.geometry,h,o,{},i.subdivisionGranularity),i.featureIndex.insert(s,v.geometry,h,d,this.index,!0)}}addFeatures(e,i,o){for(let s of this.features){let{geometry:l}=s;this.addFeature(s,l,s.index,i,o,e.subdivisionGranularity)}}update(e,i,o){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(e,i,this.stateDependentLayers,{imagePositions:o})}isEmpty(){return this.layoutVertexArray.length===0&&this.centroidVertexArray.length===0}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload}upload(e){this.uploaded||(this.layoutVertexBuffer=e.createVertexBuffer(this.layoutVertexArray,Em),this.centroidVertexBuffer=e.createVertexBuffer(this.centroidVertexArray,Mm.members,!0),this.indexBuffer=e.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(e),this.uploaded=!0}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy(),this.centroidVertexBuffer.destroy())}addFeature(e,i,o,s,l,h){for(let d of As(i,500)){let g={x:0,y:0,sampleCount:0},m=this.layoutVertexArray.length;this.processPolygon(g,s,e,d,h);let v=this.layoutVertexArray.length-m,_=Math.floor(g.x/g.sampleCount),T=Math.floor(g.y/g.sampleCount);for(let b=0;b{Wl(v,_,T,0,0,1,1,0)}),this.segments,this.layoutVertexArray,this.indexArray,m.verticesFlattened,m.indicesTriangles)}_generateSideFaces(e,i){let o=0;for(let s=1;swe.MAX_VERTEX_ARRAY_LENGTH&&(i.segment=this.segments.prepareSegment(4,this.layoutVertexArray,this.indexArray));let d=l.sub(h)._perp()._unit(),g=h.dist(l);o+g>32768&&(o=0),Wl(this.layoutVertexArray,l.x,l.y,d.x,d.y,0,0,o),Wl(this.layoutVertexArray,l.x,l.y,d.x,d.y,0,1,o),o+=g,Wl(this.layoutVertexArray,h.x,h.y,d.x,d.y,0,0,o),Wl(this.layoutVertexArray,h.x,h.y,d.x,d.y,0,1,o);let m=i.segment.vertexLength;this.indexArray.emplaceBack(m,m+2,m+1),this.indexArray.emplaceBack(m+1,m+2,m+3),i.segment.vertexLength+=4,i.segment.primitiveLength+=2}}}function km(r,e){for(let i=0;iDe)||r.y===e.y&&(r.y<0||r.y>De)}function Hd(r){return r.every((e=>e.x<0))||r.every((e=>e.x>De))||r.every((e=>e.y<0))||r.every((e=>e.y>De))}let Xd;Pe("FillExtrusionBucket",wu,{omit:["layers","features"]});var Fm={get paint(){return Xd=Xd||new ui({"fill-extrusion-opacity":new Ie(ce["paint_fill-extrusion"]["fill-extrusion-opacity"]),"fill-extrusion-color":new Ce(ce["paint_fill-extrusion"]["fill-extrusion-color"]),"fill-extrusion-translate":new Ie(ce["paint_fill-extrusion"]["fill-extrusion-translate"]),"fill-extrusion-translate-anchor":new Ie(ce["paint_fill-extrusion"]["fill-extrusion-translate-anchor"]),"fill-extrusion-pattern":new Or(ce["paint_fill-extrusion"]["fill-extrusion-pattern"]),"fill-extrusion-height":new Ce(ce["paint_fill-extrusion"]["fill-extrusion-height"]),"fill-extrusion-base":new Ce(ce["paint_fill-extrusion"]["fill-extrusion-base"]),"fill-extrusion-vertical-gradient":new Ie(ce["paint_fill-extrusion"]["fill-extrusion-vertical-gradient"])})}};class Bm extends Ui{constructor(e,i){super(e,Fm,i)}createBucket(e){return new wu(e)}queryRadius(){return ch(this.paint.get("fill-extrusion-translate"))}is3D(){return!0}queryIntersectsFeature({queryGeometry:e,feature:i,featureState:o,geometry:s,transform:l,pixelsToTileUnits:h,pixelPosMatrix:d}){let g=hh(e,this.paint.get("fill-extrusion-translate"),this.paint.get("fill-extrusion-translate-anchor"),-l.bearingInRadians,h),m=this.paint.get("fill-extrusion-height").evaluate(i,o),v=this.paint.get("fill-extrusion-base").evaluate(i,o),_=(function(b,I){let M=[];for(let A of b){let D=[A.x,A.y,0,1];Ze(D,D,I),M.push(new Te(D[0]/D[3],D[1]/D[3]))}return M})(g,d),T=(function(b,I,M,A){let D=[],L=[],R=A[8]*I,F=A[9]*I,O=A[10]*I,V=A[11]*I,Y=A[8]*M,J=A[9]*M,re=A[10]*M,te=A[11]*M;for(let ae of b){let le=[],ne=[];for(let ie of ae){let fe=ie.x,xe=ie.y,ye=A[0]*fe+A[4]*xe+A[12],me=A[1]*fe+A[5]*xe+A[13],Ae=A[2]*fe+A[6]*xe+A[14],Ye=A[3]*fe+A[7]*xe+A[15],Je=Ae+O,nt=Ye+V,si=ye+Y,Tt=me+J,Ft=Ae+re,Ut=Ye+te,pt=new Te((ye+R)/nt,(me+F)/nt);pt.z=Je/nt,le.push(pt);let Qt=new Te(si/Ut,Tt/Ut);Qt.z=Ft/Ut,ne.push(Qt)}D.push(le),L.push(ne)}return[D,L]})(s,v,m,d);return(function(b,I,M){let A=1/0;bd(M,I)&&(A=Yd(M,I[0]));for(let D=0;D>4;if(s!==1)throw new Error(`Got v${s} data when expected v1.`);let l=Kd[15&o];if(!l)throw new Error("Unrecognized array type.");let[h]=new Uint16Array(e,2,1),[d]=new Uint32Array(e,4,1);return new mh(d,h,l,e)}constructor(e,i=64,o=Float64Array,s){if(isNaN(e)||e<0)throw new Error(`Unpexpected numItems value: ${e}.`);this.numItems=+e,this.nodeSize=Math.min(Math.max(+i,2),65535),this.ArrayType=o,this.IndexArrayType=e<65536?Uint16Array:Uint32Array;let l=Kd.indexOf(this.ArrayType),h=2*e*this.ArrayType.BYTES_PER_ELEMENT,d=e*this.IndexArrayType.BYTES_PER_ELEMENT,g=(8-d%8)%8;if(l<0)throw new Error(`Unexpected typed array class: ${o}.`);s&&s instanceof ArrayBuffer?(this.data=s,this.ids=new this.IndexArrayType(this.data,8,e),this.coords=new this.ArrayType(this.data,8+d+g,2*e),this._pos=2*e,this._finished=!0):(this.data=new ArrayBuffer(8+h+d+g),this.ids=new this.IndexArrayType(this.data,8,e),this.coords=new this.ArrayType(this.data,8+d+g,2*e),this._pos=0,this._finished=!1,new Uint8Array(this.data,0,2).set([219,16+l]),new Uint16Array(this.data,2,1)[0]=i,new Uint32Array(this.data,4,1)[0]=e)}add(e,i){let o=this._pos>>1;return this.ids[o]=o,this.coords[this._pos++]=e,this.coords[this._pos++]=i,o}finish(){let e=this._pos>>1;if(e!==this.numItems)throw new Error(`Added ${e} items when expected ${this.numItems}.`);return Tu(this.ids,this.coords,this.nodeSize,0,this.numItems-1,0),this._finished=!0,this}range(e,i,o,s){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");let{ids:l,coords:h,nodeSize:d}=this,g=[0,l.length-1,0],m=[];for(;g.length;){let v=g.pop()||0,_=g.pop()||0,T=g.pop()||0;if(_-T<=d){for(let A=T;A<=_;A++){let D=h[2*A],L=h[2*A+1];D>=e&&D<=o&&L>=i&&L<=s&&m.push(l[A])}continue}let b=T+_>>1,I=h[2*b],M=h[2*b+1];I>=e&&I<=o&&M>=i&&M<=s&&m.push(l[b]),(v===0?e<=I:i<=M)&&(g.push(T),g.push(b-1),g.push(1-v)),(v===0?o>=I:s>=M)&&(g.push(b+1),g.push(_),g.push(1-v))}return m}within(e,i,o){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");let{ids:s,coords:l,nodeSize:h}=this,d=[0,s.length-1,0],g=[],m=o*o;for(;d.length;){let v=d.pop()||0,_=d.pop()||0,T=d.pop()||0;if(_-T<=h){for(let A=T;A<=_;A++)Qd(l[2*A],l[2*A+1],e,i)<=m&&g.push(s[A]);continue}let b=T+_>>1,I=l[2*b],M=l[2*b+1];Qd(I,M,e,i)<=m&&g.push(s[b]),(v===0?e-o<=I:i-o<=M)&&(d.push(T),d.push(b-1),d.push(1-v)),(v===0?e+o>=I:i+o>=M)&&(d.push(b+1),d.push(_),d.push(1-v))}return g}}function Tu(r,e,i,o,s,l){if(s-o<=i)return;let h=o+s>>1;Jd(r,e,h,o,s,l),Tu(r,e,i,o,h-1,1-l),Tu(r,e,i,h+1,s,1-l)}function Jd(r,e,i,o,s,l){for(;s>o;){if(s-o>600){let m=s-o+1,v=i-o+1,_=Math.log(m),T=.5*Math.exp(2*_/3),b=.5*Math.sqrt(_*T*(m-T)/m)*(v-m/2<0?-1:1);Jd(r,e,i,Math.max(o,Math.floor(i-v*T/m+b)),Math.min(s,Math.floor(i+(m-v)*T/m+b)),l)}let h=e[2*i+l],d=o,g=s;for(Xl(r,e,o,i),e[2*s+l]>h&&Xl(r,e,o,s);dh;)g--}e[2*o+l]===h?Xl(r,e,o,g):(g++,Xl(r,e,g,s)),g<=i&&(o=g+1),i<=g&&(s=g-1)}}function Xl(r,e,i,o){Pu(r,i,o),Pu(e,2*i,2*o),Pu(e,2*i+1,2*o+1)}function Pu(r,e,i){let o=r[e];r[e]=r[i],r[i]=o}function Qd(r,e,i,o){let s=r-i,l=e-o;return s*s+l*l}function Su(r,e,i,o){let s=o,l=e+(i-e>>1),h,d=i-e,g=r[e],m=r[e+1],v=r[i],_=r[i+1];for(let T=e+3;Ts)h=T,s=b;else if(b===s){let I=Math.abs(T-l);Io&&(h-e>3&&Su(r,e,h,o),r[h+2]=s,i-h>3&&Su(r,h,i,o))}function Om(r,e,i,o,s,l){let h=s-i,d=l-o;if(h!==0||d!==0){let g=((r-i)*h+(e-o)*d)/(h*h+d*d);g>1?(i=s,o=l):g>0&&(i+=h*g,o+=d*g)}return h=r-i,d=e-o,h*h+d*d}function Jt(r,e,i,o){let s={type:e,geom:i},l={id:r??null,type:s.type,geometry:s.geom,tags:o,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0};switch(s.type){case"Point":case"MultiPoint":Yl(l,s.geom);break;case"LineString":Yl(l,s.geom.points);break;case"Polygon":Yl(l,s.geom[0].points);break;case"MultiLineString":for(let h of s.geom)Yl(l,h.points);break;case"MultiPolygon":for(let h of s.geom)Yl(l,h[0].points)}return l}function Iu(r){r.points.length>64&&(r.points=new Float64Array(r.points))}function Yl(r,e){for(let i=0;i0&&(h+=o?(s*v-m*l)/2:Math.sqrt(Math.pow(m-s,2)+Math.pow(v-l,2))),s=m,l=v}let d=e.points.length-3;e.points[2]=1,i>0&&Su(e.points,0,d,i),e.points[d+2]=1,Iu(e),e.size=Math.abs(h),e.start=0,e.end=e.size}function Cu(r,e,i,o){for(let s=0;s1?1:i}function _h(r){let e={type:"Feature",geometry:Nm(r),properties:r.tags};return r.id!=null&&(e.id=r.id),e}function Nm(r){let{type:e,geometry:i}=r;switch(e){case"Point":return{type:e,coordinates:ep(i[0],i[1])};case"MultiPoint":return{type:e,coordinates:yh(i)};case"LineString":return{type:e,coordinates:yh(i.points)};case"MultiLineString":case"Polygon":return{type:e,coordinates:i.map((o=>yh(o.points)))};case"MultiPolygon":return{type:e,coordinates:i.map((o=>o.map((s=>yh(s.points)))))}}}function yh(r){let e=[];for(let i=0;i=(i/=e)&&h=o)return null;let g=[];for(let m of r){let v=s===pi.X?m.minX:m.minY,_=s===pi.X?m.maxX:m.maxY;if(v>=i&&_=o))switch(m.type){case"Point":case"MultiPoint":Vm(m,g,i,o,s);continue;case"LineString":jm(m,g,i,o,s,d);continue;case"MultiLineString":Um(m,g,i,o,s);continue;case"Polygon":Gm(m,g,i,o,s);continue;case"MultiPolygon":$m(m,g,i,o,s);continue}}return g.length?g:null}function Vm(r,e,i,o,s){let l=[];(function(h,d,g,m,v){for(let _=0;_=g&&T<=m&&fa(d,h[_],h[_+1],h[_+2])}})(r.geometry,l,i,o,s),l.length&&e.push(Jt(r.id,l.length===3?"Point":"MultiPoint",l,r.tags))}function jm(r,e,i,o,s,l){let h=[];if(rp(r.geometry,h,i,o,s,!1,l.lineMetrics),h.length)if(l.lineMetrics)for(let d of h)e.push(Jt(r.id,"LineString",d,r.tags));else e.push(h.length>1?Jt(r.id,"MultiLineString",h,r.tags):Jt(r.id,"LineString",h[0],r.tags))}function Um(r,e,i,o,s){let l=[];Au(r.geometry,l,i,o,s,!1),l.length&&e.push(l.length!==1?Jt(r.id,"MultiLineString",l,r.tags):Jt(r.id,"LineString",l[0],r.tags))}function Gm(r,e,i,o,s){let l=[];Au(r.geometry,l,i,o,s,!0),l.length&&e.push(Jt(r.id,"Polygon",l,r.tags))}function $m(r,e,i,o,s){let l=[];for(let h of r.geometry){let d=[];Au(h,d,i,o,s,!0),d.length&&l.push(d)}l.length&&e.push(Jt(r.id,"MultiPolygon",l,r.tags))}function rp(r,e,i,o,s,l,h){let d=np(r),g=s===pi.X?Zm:qm,m,v,_=r.start;for(let A=0;Ai&&(v=g(d,D,L,F,O,i),h&&(d.start=_+m*v)):V>o?Y=i&&(v=g(d,D,L,F,O,i),J=!0),Y>o&&V<=o&&(v=g(d,D,L,F,O,o),J=!0),!l&&J&&(h&&(d.end=_+m*v),e.push(d),d=np(r)),h&&(_+=m)}let T=r.points.length-3,b=r.points[T],I=r.points[T+1],M=s===pi.X?b:I;M>=i&&M<=o&&fa(d.points,b,I,r.points[T+2]),T=d.points.length-3,l&&T>=3&&(d.points[T]!==d.points[0]||d.points[T+1]!==d.points[1])&&fa(d.points,d.points[0],d.points[1],d.points[2]),d.points.length&&(Iu(d),e.push(d))}function np(r){return{points:[],size:r.size,start:r.start,end:r.end}}function Au(r,e,i,o,s,l){for(let h of r)rp(h,e,i,o,s,l,!1)}function fa(r,e,i,o){r.push(e,i,o)}function Zm(r,e,i,o,s,l){let h=(l-e)/(o-e);return fa(r.points,l,i+(s-i)*h,1),h}function qm(r,e,i,o,s,l){let h=(l-i)/(s-i);return fa(r.points,e+(o-e)*h,l,1),h}function Du(r,e){let i=e.buffer/e.extent,o=r,s=Sn(r,1,-1-i,i,pi.X,-1,2,e),l=Sn(r,1,1-i,2+i,pi.X,-1,2,e);return(s||l)&&(o=Sn(r,1,-i,1+i,pi.X,-1,2,e)||[],s&&(o=op(s,1).concat(o)),l&&(o=o.concat(op(l,-1)))),o}function op(r,e){let i=[];for(let o of r)switch(o.type){case"Point":case"MultiPoint":{let s=Wm(o.geometry,e);i.push(Jt(o.id,o.type,s,o.tags));continue}case"LineString":{let s=zu(o.geometry,e);i.push(Jt(o.id,o.type,s,o.tags));continue}case"MultiLineString":case"Polygon":{let s=[];for(let l of o.geometry)s.push(zu(l,e));i.push(Jt(o.id,o.type,s,o.tags));continue}case"MultiPolygon":{let s=[];for(let l of o.geometry){let h=[];for(let d of l)h.push(zu(d,e));s.push(h)}i.push(Jt(o.id,o.type,s,o.tags));continue}}return i}function Wm(r,e){let i=[];for(let o=0;o0||e.addOrUpdateProperties?.length>0;if(o){let l=r[0],h=Mu({type:"FeatureCollection",features:[{type:"Feature",id:l.id,geometry:e.newGeometry,properties:s?sp(l.tags,e):l.tags}]},i);return h=Du(h,i),h}if(s){let l=[];for(let h of r){let d={...h};d.tags=sp(d.tags,e),l.push(d)}return l}return r}function sp(r,e){if(e.removeAllProperties)return{};let i={...r||{}};if(e.removeProperties)for(let o of e.removeProperties)delete i[o];if(e.addOrUpdateProperties)for(let{key:o,value:s}of e.addOrUpdateProperties)i[o]=s;return i}(function(r){r[r.X=0]="X",r[r.Y=1]="Y"})(pi||(pi={}));let Ru={minZoom:0,maxZoom:16,minPoints:2,radius:40,extent:512,nodeSize:64,log:!1,generateId:!1,reduce:null,map:r=>r};class Xm{constructor(e){this.options=Object.assign(Object.create(Ru),e),this.trees=new Array(this.options.maxZoom+1),this.stride=this.options.reduce?7:6,this.clusterProps=[],this.points=[]}load(e){let i=[];for(let o of e){if(!o.geometry)continue;let[s,l]=o.geometry.coordinates,[h,d]=[da(s),pa(l)];i.push({id:o.id,type:"Point",geometry:[h,d],tags:o.properties})}this.createIndex(i)}initialize(e){let i=[];for(let o of e)o.type==="Point"&&i.push(o);this.createIndex(i)}updateIndex(e,i,o){this.options=Object.assign(Object.create(Ru),o.clusterOptions),this.initialize(e)}createIndex(e){let{log:i,minZoom:o,maxZoom:s}=this.options;i&&console.time("total time");let l=`prepare ${e.length} points`;i&&console.time(l),this.points=e;let h=[];for(let g=0;g=o;g--){let m=Date.now();d=this.trees[g]=this.createTree(this.cluster(d,g)),i&&console.log("z%d: %d clusters in %dms",g,d.numItems,Date.now()-m)}i&&console.timeEnd("total time")}getClusters(e,i){return this.getClustersInternal(e,i).map((o=>_h(o)))}getClustersInternal(e,i){let o=((e[0]+180)%360+360)%360-180,s=Math.max(-90,Math.min(90,e[1])),l=e[2]===180?180:((e[2]+180)%360+360)%360-180,h=Math.max(-90,Math.min(90,e[3]));if(e[2]-e[0]>=360)o=-180,l=180;else if(o>l){let _=this.getClustersInternal([o,s,180,h],i),T=this.getClustersInternal([-180,s,l,h],i);return _.concat(T)}let d=this.trees[this.limitZoom(i)],g=d.range(da(o),pa(h),da(l),pa(s)),m=d.flatData,v=[];for(let _ of g){let T=this.stride*_;v.push(m[T+5]>1?Ym(m,T,this.clusterProps):this.points[m[T+3]])}return v}getChildren(e){let i=this.getOriginId(e),o=this.getOriginZoom(e),s=new Error("No cluster with the specified id: "+e),l=this.trees[o];if(!l)throw s;let h=l.flatData;if(i*this.stride>=h.length)throw s;let d=this.options.radius/(this.options.extent*Math.pow(2,o-1)),g=l.within(h[i*this.stride],h[i*this.stride+1],d),m=[];for(let v of g){let _=v*this.stride;h[_+4]===e&&m.push(h[_+5]>1?Km(h,_,this.clusterProps):_h(this.points[h[_+3]]))}if(m.length===0)throw s;return m}getLeaves(e,i,o){let s=[];return this.appendLeaves(s,e,i=i||10,o=o||0,0),s}getTile(e,i,o){let s=this.trees[this.limitZoom(e)];if(!s)return null;let l=Math.pow(2,e),{extent:h,radius:d}=this.options,g=d/h,m=(o-g)/l,v=(o+1+g)/l,_={transformed:!0,features:[],source:null,x:i,y:o,z:e};return this.addTileFeatures(s.range((i-g)/l,m,(i+1+g)/l,v),s.flatData,i,o,l,_),i===0&&this.addTileFeatures(s.range(1-g/l,m,1,v),s.flatData,l,o,l,_),i===l-1&&this.addTileFeatures(s.range(0,m,g/l,v),s.flatData,-1,o,l,_),_}getClusterExpansionZoom(e){return this.getOriginZoom(e)}appendLeaves(e,i,o,s,l){let h=this.getChildren(i);for(let d of h){let g=d.properties;if(g?.cluster?l+g.point_count<=s?l+=g.point_count:l=this.appendLeaves(e,g.cluster_id,o,s,l):l1,v,_,T;if(m)v=ku(i,g,this.clusterProps),_=i[g],T=i[g+1];else{let M=this.points[i[g+3]];v=M.tags,[_,T]=M.geometry}let b={type:1,geometry:[[Math.round(this.options.extent*(_*l-o)),Math.round(this.options.extent*(T*l-s))]],tags:v},I;I=m||this.options.generateId?i[g+3]:this.points[i[g+3]].id,I!==void 0&&(b.id=I),h.features.push(b)}}limitZoom(e){return Math.max(this.options.minZoom,Math.min(Math.floor(+e),this.options.maxZoom+1))}cluster(e,i){let{radius:o,extent:s,reduce:l,minPoints:h}=this.options,d=o/(s*Math.pow(2,i)),g=e.flatData,m=[],v=this.stride;for(let _=0;_i&&(A+=g[L+5])}if(A>M&&A>=h){let D,L=T*M,R=b*M,F=-1,O=(_/v<<5)+(i+1)+this.points.length;for(let V of I){let Y=V*v;if(g[Y+2]<=i)continue;g[Y+2]=i;let J=g[Y+5];L+=g[Y]*J,R+=g[Y+1]*J,g[Y+4]=O,l&&(D||(D=this.map(g,_,!0),F=this.clusterProps.length,this.clusterProps.push(D)),l(D,this.map(g,Y)))}g[_+4]=O,m.push(L/A,R/A,1/0,O,-1,A),l&&m.push(F)}else{for(let D=0;D1)for(let D of I){let L=D*v;if(!(g[L+2]<=i)){g[L+2]=i;for(let R=0;R>5}getOriginZoom(e){return(e-this.points.length)%32}map(e,i,o){if(e[i+5]>1){let h=this.clusterProps[e[i+6]];return o?Object.assign({},h):h}let s=this.points[e[i+3]].tags,l=this.options.map(s);return o&&l===s?Object.assign({},l):l}}function Ym(r,e,i){return{id:r[e+3],type:"Point",tags:ku(r,e,i),geometry:[r[e],r[e+1]]}}function Km(r,e,i){return{type:"Feature",id:r[e+3],properties:ku(r,e,i),geometry:{type:"Point",coordinates:[tp(r[e]),ip(r[e+1])]}}}function ku(r,e,i){let o=r[e+5],s=o>=1e4?`${Math.round(o/1e3)}k`:o>=1e3?Math.round(o/100)/10+"k":o,l=r[e+6],h=l===-1?{}:Object.assign({},i[l]);return Object.assign(h,{cluster:!0,cluster_id:r[e+3],point_count:o,point_count_abbreviated:s})}let Lu="geojsonvt_clip_start",Fu="geojsonvt_clip_end";function ap(r,e,i,o,s){let l=e===s.maxZoom?0:s.tolerance/((1<0&&e.size<(s?h:o))return void(i.numPoints+=e.points.length/3);let d=[];for(let g=0;gh)&&(i.numSimplified++,d.push(e.points[g],e.points[g+1])),i.numPoints++;s&&(function(g,m){let v=0;for(let _=0,T=g.length,b=T-2;_0===m)for(let _=0,T=g.length;_1&&(console.log("invalidating tiles"),console.time("invalidating")),this.invalidateTiles(i),o.debug>1&&console.timeEnd("invalidating");let[s,l,h]=[0,0,0],d=ap(e,s,l,h,o);d.source=e;let g=vh(s,l,h);if(this.tiles[g]=d,this.tileCoords.push({z:s,x:l,y:h,id:g}),o.debug){let m=`z${s}`;this.stats[m]=(this.stats[m]||0)+1,this.total++}}getClusterExpansionZoom(e){return null}getChildren(e){return null}getLeaves(e,i,o){return null}getTile(e,i,o){let{extent:s,debug:l}=this.options,h=1<1&&console.log("drilling down to z%d-%d-%d",e,i,o);let g,m=e,v=i,_=o;for(;!g&&m>0;)m--,v>>=1,_>>=1,g=this.tiles[vh(m,v,_)];return g?.source?(l>1&&(console.log("found parent tile z%d-%d-%d",m,v,_),console.time("drilling down")),this.splitTile(g.source,m,v,_,e,i,o),l>1&&console.timeEnd("drilling down"),this.tiles[d]?lp(this.tiles[d],s):null):null}splitTile(e,i,o,s,l,h,d){let g=[e,i,o,s],m=this.options,v=m.debug;for(;g.length;){s=g.pop(),o=g.pop(),i=g.pop(),e=g.pop();let _=1<1&&console.time("creation"),b=this.tiles[T]=ap(e,i,o,s,m),this.tileCoords.push({z:i,x:o,y:s,id:T}),v)){v>1&&(console.log("tile z%d-%d-%d (features: %d, points: %d, simplified: %d)",i,o,s,b.numFeatures,b.numPoints,b.numSimplified),console.timeEnd("creation"));let J=`z${i}`;this.stats[J]=(this.stats[J]||0)+1,this.total++}if(b.source=e,l==null){if(i===m.indexMaxZoom||b.numPoints<=m.indexMaxPoints)continue}else{if(i===m.maxZoom||i===l)continue;if(l!=null){let J=l-i;if(o!==h>>J||s!==d>>J)continue}}if(b.source=null,!e.length)continue;v>1&&console.time("clipping");let I=.5*m.buffer/m.extent,M=.5-I,A=.5+I,D=1+I,L=null,R=null,F=null,O=null,V=Sn(e,_,o-I,o+A,pi.X,b.minX,b.maxX,m),Y=Sn(e,_,o+M,o+D,pi.X,b.minX,b.maxX,m);V&&(L=Sn(V,_,s-I,s+A,pi.Y,b.minY,b.maxY,m),R=Sn(V,_,s+M,s+D,pi.Y,b.minY,b.maxY,m)),Y&&(F=Sn(Y,_,s-I,s+A,pi.Y,b.minY,b.maxY,m),O=Sn(Y,_,s+M,s+D,pi.Y,b.minY,b.maxY,m)),v>1&&console.timeEnd("clipping"),g.push(L||[],i+1,2*o,2*s),g.push(R||[],i+1,2*o,2*s+1),g.push(F||[],i+1,2*o+1,2*s),g.push(O||[],i+1,2*o+1,2*s+1)}}invalidateTiles(e){if(!e.length)return;let i=this.options,{debug:o}=i,s=1/0,l=-1/0,h=1/0,d=-1/0;for(let v of e)s=Math.min(s,v.minX),l=Math.max(l,v.maxX),h=Math.min(h,v.minY),d=Math.max(d,v.maxY);let g=i.buffer/i.extent,m=new Set;for(let v in this.tiles){let _=this.tiles[v],T=1<<_.z,b=(_.x-g)/T,I=(_.x+1+g)/T,M=(_.y-g)/T,A=(_.y+1+g)/T;if(l=I||d=A)continue;let D=!1;for(let L of e)if(L.maxX>=b&&L.minX=M&&L.minY1&&console.log("invalidate tile z%d-%d-%d (features: %d, points: %d, simplified: %d)",_.z,_.x,_.y,_.numFeatures,_.numPoints,_.numSimplified);let L=`z${_.z}`;this.stats[L]=(this.stats[L]||0)-1,this.total--}delete this.tiles[v],m.add(v)}}m.size&&(this.tileCoords=this.tileCoords.filter((v=>!m.has(v.id))))}}function vh(r,e,i){return 32*((1<i.id)),this.index=e.index,this.hasDependencies=!1,this.patternFeatures=[],this.lineClipsArray=[],this.gradients={};for(let i of this.layers)this.gradients[i.id]={};this.layoutVertexArray=new X,this.layoutVertexArray2=new Z,this.indexArray=new ue,this.programConfigurations=new vr(e.layers,e.zoom),this.segments=new we,this.maxLineLength=0,this.stateDependentLayerIds=this.layers.filter((i=>i.isStateDependent())).map((i=>i.id))}populate(e,i,o){this.hasDependencies=uh("line",this.layers,i)||this.hasLineDasharray(this.layers);let s=this.layers[0].layout.get("line-sort-key"),l=!s.isConstant(),h=[];for(let{feature:d,id:g,index:m,sourceLayerIndex:v}of e){let _=this.layers[0]._featureFilter.needGeometry,T=Zr(d,_);if(!this.layers[0]._featureFilter.filter(new ct(this.zoom),T,o))continue;let b=l?s.evaluate(T,{},o):void 0,I={id:g,properties:d.properties,type:d.type,sourceLayerIndex:v,index:m,geometry:_?T.geometry:$r(d),patterns:{},dashes:{},sortKey:b};h.push(I)}l&&h.sort(((d,g)=>d.sortKey-g.sortKey));for(let d of h){let{geometry:g,index:m,sourceLayerIndex:v}=d;this.hasDependencies?(uh("line",this.layers,i)?_u("line",this.layers,d,{zoom:this.zoom},i):this.hasLineDasharray(this.layers)&&this.addLineDashDependencies(this.layers,d,this.zoom,i),this.patternFeatures.push(d)):this.addFeature(d,g,m,o,{},{},i.subdivisionGranularity),i.featureIndex.insert(e[m].feature,g,m,v,this.index)}}update(e,i,o,s){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(e,i,this.stateDependentLayers,{imagePositions:o,dashPositions:s})}addFeatures(e,i,o,s){for(let l of this.patternFeatures)this.addFeature(l,l.geometry,l.index,i,o,s,e.subdivisionGranularity)}isEmpty(){return this.layoutVertexArray.length===0}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload}upload(e){this.uploaded||(this.layoutVertexArray2.length!==0&&(this.layoutVertexBuffer2=e.createVertexBuffer(this.layoutVertexArray2,sg)),this.layoutVertexBuffer=e.createVertexBuffer(this.layoutVertexArray,ng),this.indexBuffer=e.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(e),this.uploaded=!0}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy())}lineFeatureClips(e){if(e.properties&&Object.hasOwn(e.properties,Lu)&&Object.hasOwn(e.properties,Fu))return{start:+e.properties[Lu],end:+e.properties[Fu]}}addFeature(e,i,o,s,l,h,d){let g=this.layers[0].layout,m=g.get("line-join").evaluate(e,{}),v=g.get("line-cap").evaluate(e,{}),_=g.get("line-miter-limit").evaluate(e,{}),T=g.get("line-round-limit").evaluate(e,{});this.lineClips=this.lineFeatureClips(e);for(let b of i)this.addLine(b,e,m,v,_,T,s,d);this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,e,o,{imagePositions:l,dashPositions:h,canonical:s})}addLine(e,i,o,s,l,h,d,g){if(this.distance=0,this.scaledDistance=0,this.totalDistance=0,e=os(e,d?g.line.getGranularityForZoomLevel(d.z):1),this.lineClips){this.lineClipsArray.push(this.lineClips);for(let R=0;R=2&&e[v-1].equals(e[v-2]);)v--;let _=0;for(;_0;if(re&&R>_){let ne=I.dist(M);if(ne>2*T){let ie=I.sub(I.sub(M)._mult(T/ne)._round());this.updateDistance(M,ie),this.addCurrentVertex(ie,D,0,0,b),M=ie}}let ae=M&&A,le=ae?o:m?"butt":s;if(ae&&le==="round"&&(Yl&&(le="bevel"),le==="bevel"&&(Y>2&&(le="flipbevel"),Y100)F=L.mult(-1);else{let ne=Y*D.add(L).mag()/D.sub(L).mag();F._perp()._mult(ne*(te?-1:1))}this.addCurrentVertex(I,F,0,0,b),this.addCurrentVertex(I,F.mult(-1),0,0,b)}else if(le==="bevel"||le==="fakeround"){let ne=-Math.sqrt(Y*Y-1),ie=te?ne:0,fe=te?0:ne;if(M&&this.addCurrentVertex(I,D,ie,fe,b),le==="fakeround"){let xe=Math.round(180*J/Math.PI/20);for(let ye=1;ye2*T){let ie=I.add(A.sub(I)._mult(T/ne)._round());this.updateDistance(I,ie),this.addCurrentVertex(ie,L,0,0,b),I=ie}}}}addCurrentVertex(e,i,o,s,l,h=!1){let d=i.y*s-i.x,g=-i.y-i.x*s;this.addHalfVertex(e,i.x+i.y*o,i.y-i.x*o,h,!1,o,l),this.addHalfVertex(e,d,g,h,!0,-s,l),this.distance>hp/2&&this.totalDistance===0&&(this.distance=0,this.updateScaledDistance(),this.addCurrentVertex(e,i,o,s,l,h))}addHalfVertex({x:e,y:i},o,s,l,h,d,g){let m=.5*(this.lineClips?this.scaledDistance*(hp-1):this.scaledDistance);this.layoutVertexArray.emplaceBack((e<<1)+(l?1:0),(i<<1)+(h?1:0),Math.round(63*o)+128,Math.round(63*s)+128,1+(d===0?0:d<0?-1:1)|(63&m)<<2,m>>6),this.lineClips&&this.layoutVertexArray2.emplaceBack((this.scaledDistance-this.lineClips.start)/(this.lineClips.end-this.lineClips.start),this.lineClipsArray.length);let v=g.vertexLength++;this.e1>=0&&this.e2>=0&&(this.indexArray.emplaceBack(this.e1,v,this.e2),g.primitiveLength++),h?this.e2=v:this.e1=v}updateScaledDistance(){this.scaledDistance=this.lineClips?this.lineClips.start+(this.lineClips.end-this.lineClips.start)*this.distance/this.totalDistance:this.distance}updateDistance(e,i){this.distance+=e.dist(i),this.updateScaledDistance()}hasLineDasharray(e){for(let i of e){let o=i.paint.get("line-dasharray");if(o&&!o.isConstant())return!0}return!1}addLineDashDependencies(e,i,o,s){for(let l of e){let h=l.paint.get("line-dasharray");if(!h||h.value.kind==="constant")continue;let d=l.layout.get("line-cap").evaluate(i,{})==="round",g={dasharray:h.value.evaluate({zoom:o-1},i,{}),round:d},m={dasharray:h.value.evaluate({zoom:o},i,{}),round:d},v={dasharray:h.value.evaluate({zoom:o+1},i,{}),round:d},_=`${g.dasharray.join(",")},${g.round}`,T=`${m.dasharray.join(",")},${m.round}`,b=`${v.dasharray.join(",")},${v.round}`;s.dashDependencies[_]=g,s.dashDependencies[T]=m,s.dashDependencies[b]=v,i.dashes[l.id]={min:_,mid:T,max:b}}}}let up,dp;Pe("LineBucket",Ou,{omit:["layers","patternFeatures"]});var pp={get paint(){return dp=dp||new ui({"line-opacity":new Ce(ce.paint_line["line-opacity"]),"line-color":new Ce(ce.paint_line["line-color"]),"line-translate":new Ie(ce.paint_line["line-translate"]),"line-translate-anchor":new Ie(ce.paint_line["line-translate-anchor"]),"line-width":new Ce(ce.paint_line["line-width"]),"line-gap-width":new Ce(ce.paint_line["line-gap-width"]),"line-offset":new Ce(ce.paint_line["line-offset"]),"line-blur":new Ce(ce.paint_line["line-blur"]),"line-dasharray":new Or(ce.paint_line["line-dasharray"]),"line-pattern":new Or(ce.paint_line["line-pattern"]),"line-gradient":new oo(ce.paint_line["line-gradient"])})},get layout(){return up=up||new ui({"line-cap":new Ce(ce.layout_line["line-cap"]),"line-join":new Ce(ce.layout_line["line-join"]),"line-miter-limit":new Ce(ce.layout_line["line-miter-limit"]),"line-round-limit":new Ce(ce.layout_line["line-round-limit"]),"line-sort-key":new Ce(ce.layout_line["line-sort-key"])})}};class lg extends Ce{possiblyEvaluate(e,i){return i=new ct(Math.floor(i.zoom),{now:i.now,fadeDuration:i.fadeDuration,zoomHistory:i.zoomHistory,transition:i.transition}),super.possiblyEvaluate(e,i)}evaluate(e,i,o,s){return i=Oi({},i,{zoom:Math.floor(i.zoom)}),super.evaluate(e,i,o,s)}}let xh;class cg extends Ui{constructor(e,i){super(e,pp,i),this.gradientVersion=0,xh||(xh=new lg(pp.paint.properties["line-width"].specification),xh.useIntegerZoom=!0)}_handleSpecialPaintPropertyUpdate(e){if(e==="line-gradient"){let i=this.gradientExpression();this.stepInterpolant=!!(function(o){return o._styleExpression!==void 0})(i)&&i._styleExpression.expression instanceof qn,this.gradientVersion=(this.gradientVersion+1)%Number.MAX_SAFE_INTEGER}}gradientExpression(){return this._transitionablePaint._values["line-gradient"].value.expression}recalculate(e,i){super.recalculate(e,i),this.paint._values["line-floorwidth"]=xh.possiblyEvaluate(this._transitioningPaint._values["line-width"].value,e)}createBucket(e){return new Ou(e)}queryRadius(e){let i=e,o=fp(la("line-width",this,i),la("line-gap-width",this,i)),s=la("line-offset",this,i);return o/2+Math.abs(s)+ch(this.paint.get("line-translate"))}queryIntersectsFeature({queryGeometry:e,feature:i,featureState:o,geometry:s,transform:l,pixelsToTileUnits:h}){let d=hh(e,this.paint.get("line-translate"),this.paint.get("line-translate-anchor"),-l.bearingInRadians,h),g=h/2*fp(this.paint.get("line-width").evaluate(i,o),this.paint.get("line-gap-width").evaluate(i,o)),m=this.paint.get("line-offset").evaluate(i,o);return m&&(s=(function(v,_){let T=[];for(let b of v){let I=Jf(b),M=[];for(let A=0;A=3){for(let I of b)if(aa(v,I))return!0}if(Xf(v,b,T))return!0}return!1})(d,s,g)}isTileClipped(){return!0}}function fp(r,e){return e>0?e+2*r:r}let hg=ht([{name:"a_pos_offset",components:4,type:"Int16"},{name:"a_data",components:4,type:"Uint16"},{name:"a_pixeloffset",components:4,type:"Int16"}],4),ug=ht([{name:"a_projected_pos",components:3,type:"Float32"}],4);ht([{name:"a_fade_opacity",components:1,type:"Uint32"}],4);let dg=ht([{name:"a_placed",components:2,type:"Uint8"},{name:"a_shift",components:2,type:"Float32"},{name:"a_box_real",components:2,type:"Int16"}]);ht([{type:"Int16",name:"anchorPointX"},{type:"Int16",name:"anchorPointY"},{type:"Int16",name:"x1"},{type:"Int16",name:"y1"},{type:"Int16",name:"x2"},{type:"Int16",name:"y2"},{type:"Uint32",name:"featureIndex"},{type:"Uint16",name:"sourceLayerIndex"},{type:"Uint16",name:"bucketIndex"}]);let mp=ht([{name:"a_pos",components:2,type:"Int16"},{name:"a_anchor_pos",components:2,type:"Int16"},{name:"a_extrude",components:2,type:"Int16"}],4),pg=ht([{name:"a_pos",components:2,type:"Float32"},{name:"a_radius",components:1,type:"Float32"},{name:"a_flags",components:2,type:"Int16"}],4);function fg(r,e,i){let o=e.layout.get("text-transform").evaluate(i,{});return o==="uppercase"?r=r.toLocaleUpperCase():o==="lowercase"&&(r=r.toLocaleLowerCase()),gr.applyArabicShaping&&(r=gr.applyArabicShaping(r)),r}function mg(r,e,i){for(let o of r.sections)o.text=fg(o.text,e,i);return r}ht([{name:"triangle",components:3,type:"Uint16"}]),ht([{type:"Int16",name:"anchorX"},{type:"Int16",name:"anchorY"},{type:"Uint16",name:"glyphStartIndex"},{type:"Uint16",name:"numGlyphs"},{type:"Uint32",name:"vertexStartIndex"},{type:"Uint32",name:"lineStartIndex"},{type:"Uint32",name:"lineLength"},{type:"Uint16",name:"segment"},{type:"Uint16",name:"lowerSize"},{type:"Uint16",name:"upperSize"},{type:"Float32",name:"lineOffsetX"},{type:"Float32",name:"lineOffsetY"},{type:"Uint8",name:"writingMode"},{type:"Uint8",name:"placedOrientation"},{type:"Uint8",name:"hidden"},{type:"Uint32",name:"crossTileID"},{type:"Int16",name:"associatedIconIndex"}]),ht([{type:"Int16",name:"anchorX"},{type:"Int16",name:"anchorY"},{type:"Int16",name:"rightJustifiedTextSymbolIndex"},{type:"Int16",name:"centerJustifiedTextSymbolIndex"},{type:"Int16",name:"leftJustifiedTextSymbolIndex"},{type:"Int16",name:"verticalPlacedTextSymbolIndex"},{type:"Int16",name:"placedIconSymbolIndex"},{type:"Int16",name:"verticalPlacedIconSymbolIndex"},{type:"Uint16",name:"key"},{type:"Uint16",name:"textBoxStartIndex"},{type:"Uint16",name:"textBoxEndIndex"},{type:"Uint16",name:"verticalTextBoxStartIndex"},{type:"Uint16",name:"verticalTextBoxEndIndex"},{type:"Uint16",name:"iconBoxStartIndex"},{type:"Uint16",name:"iconBoxEndIndex"},{type:"Uint16",name:"verticalIconBoxStartIndex"},{type:"Uint16",name:"verticalIconBoxEndIndex"},{type:"Uint16",name:"featureIndex"},{type:"Uint16",name:"numHorizontalGlyphVertices"},{type:"Uint16",name:"numVerticalGlyphVertices"},{type:"Uint16",name:"numIconVertices"},{type:"Uint16",name:"numVerticalIconVertices"},{type:"Uint16",name:"useRuntimeCollisionCircles"},{type:"Uint32",name:"crossTileID"},{type:"Float32",name:"textBoxScale"},{type:"Float32",name:"collisionCircleDiameter"},{type:"Uint16",name:"textAnchorOffsetStartIndex"},{type:"Uint16",name:"textAnchorOffsetEndIndex"}]),ht([{type:"Float32",name:"offsetX"}]),ht([{type:"Int16",name:"x"},{type:"Int16",name:"y"},{type:"Int16",name:"tileUnitDistanceFromAnchor"}]),ht([{type:"Uint16",name:"textAnchor"},{type:"Float32",components:2,name:"textOffset"}]);var Vt=24;let Kl={"!":"\uFE15","#":"\uFF03",$:"\uFF04","%":"\uFF05","&":"\uFF06","(":"\uFE35",")":"\uFE36","*":"\uFF0A","+":"\uFF0B",",":"\uFE10","-":"\uFE32",".":"\u30FB","/":"\uFF0F",":":"\uFE13",";":"\uFE14","<":"\uFE3F","=":"\uFF1D",">":"\uFE40","?":"\uFE16","@":"\uFF20","[":"\uFE47","\\":"\uFF3C","]":"\uFE48","^":"\uFF3E",_:"\uFE33","`":"\uFF40","{":"\uFE37","|":"\u2015","}":"\uFE38","~":"\uFF5E","\xA2":"\uFFE0","\xA3":"\uFFE1","\xA5":"\uFFE5","\xA6":"\uFFE4","\xAC":"\uFFE2","\xAF":"\uFFE3","\u2013":"\uFE32","\u2014":"\uFE31","\u2018":"\uFE43","\u2019":"\uFE44","\u201C":"\uFE41","\u201D":"\uFE42","\u2026":"\uFE19","\u22EF":"\uFE19","\u2027":"\u30FB","\u20A9":"\uFFE6","\u3001":"\uFE11","\u3002":"\uFE12","\u3008":"\uFE3F","\u3009":"\uFE40","\u300A":"\uFE3D","\u300B":"\uFE3E","\u300C":"\uFE41","\u300D":"\uFE42","\u300E":"\uFE43","\u300F":"\uFE44","\u3010":"\uFE3B","\u3011":"\uFE3C","\u3014":"\uFE39","\u3015":"\uFE3A","\u3016":"\uFE17","\u3017":"\uFE18","\uFF01":"\uFE15","\uFF08":"\uFE35","\uFF09":"\uFE36","\uFF0C":"\uFE10","\uFF0D":"\uFE32","\uFF0E":"\u30FB","\uFF1A":"\uFE13","\uFF1B":"\uFE14","\uFF1C":"\uFE3F","\uFF1E":"\uFE40","\uFF1F":"\uFE16","\uFF3B":"\uFE47","\uFF3D":"\uFE48","\uFF3F":"\uFE33","\uFF5B":"\uFE37","\uFF5C":"\u2015","\uFF5D":"\uFE38","\uFF5F":"\uFE35","\uFF60":"\uFE36","\uFF61":"\uFE12","\uFF62":"\uFE41","\uFF63":"\uFE42"},gg={10:!0,32:!0,38:!0,41:!0,43:!0,45:!0,47:!0,173:!0,183:!0,8203:!0,8208:!0,8211:!0,8231:!0},_g={40:!0};function gp(r,e,i,o,s,l){if("fontStack"in e){let h=i[e.fontStack],d=h?.[r];return d?d.metrics.advance*e.scale+s:0}{let h=o[e.imageName];return h?h.displaySize[0]*e.scale*Vt/l+s:0}}function _p(r,e,i,o){let s=Math.pow(r-e,2);return o?rMath.max(e,this.sections[i].scale)),0)}getMaxImageSize(e){let i=0,o=0;for(let s=0;so)))}addImageSection(e){let i=e.image?e.image.name:"";if(i.length===0)return void Wt("Can't add FormattedSection with an empty image.");let o=this.getNextImageSectionCharCode();o?(this.text+=String.fromCharCode(o),this.sections.push({scale:1,verticalAlign:e.verticalAlign||"bottom",imageName:i}),this.sectionIndex.push(this.sections.length-1)):Wt("Reached maximum number of images 6401")}getNextImageSectionCharCode(){return this.imageSectionID?this.imageSectionID>=63743?null:++this.imageSectionID:(this.imageSectionID=57344,this.imageSectionID)}determineLineBreaks(e,i,o,s,l){let h=[],d=this.determineAverageLineWidth(e,i,o,s,l),g=this.hasZeroWidthSpaces(),m=0,v=0,_=this.text[Symbol.iterator](),T=_.next(),b=this.text[Symbol.iterator]();b.next();let I=b.next(),M=this.text[Symbol.iterator]();M.next(),M.next();let A=M.next();for(;!T.done;){let D=this.getSection(v),L=T.value.codePointAt(0);if(Jc(L)||(m+=gp(L,D,o,s,e,l)),!I.done){let R=ou(L),F=I.value.codePointAt(0);(gg[L]||R||"imageName"in D||!A.done&&_g[F])&&h.push(yp(v+1,m,d,h,yg(L,F,R&&g),!1))}v++,T=_.next(),I=b.next(),A=M.next()}return vp(yp(this.length(),m,d,h,0,!0))}determineAverageLineWidth(e,i,o,s,l){let h=0,d=0;for(let g of this.text){let m=this.getSection(d);h+=gp(g.codePointAt(0),m,o,s,e,l),d++}return h/Math.max(1,Math.ceil(h/i))}}let Nu=4294967296,xp=1/Nu,bp=typeof TextDecoder>"u"?null:new TextDecoder("utf-8");class bh{constructor(e=new Uint8Array(16)){this.buf=ArrayBuffer.isView(e)?e:new Uint8Array(e),this.dataView=new DataView(this.buf.buffer),this.pos=0,this.type=0,this.length=this.buf.length}readFields(e,i,o=this.length){for(;this.pos>3,h=this.pos;this.type=7&s,e(l,i,this),this.pos===h&&this.skip(s)}return i}readMessage(e,i){return this.readFields(e,i,this.readVarint()+this.pos)}readFixed32(){let e=this.dataView.getUint32(this.pos,!0);return this.pos+=4,e}readSFixed32(){let e=this.dataView.getInt32(this.pos,!0);return this.pos+=4,e}readFixed64(){let e=this.dataView.getUint32(this.pos,!0)+this.dataView.getUint32(this.pos+4,!0)*Nu;return this.pos+=8,e}readSFixed64(){let e=this.dataView.getUint32(this.pos,!0)+this.dataView.getInt32(this.pos+4,!0)*Nu;return this.pos+=8,e}readFloat(){let e=this.dataView.getFloat32(this.pos,!0);return this.pos+=4,e}readDouble(){let e=this.dataView.getFloat64(this.pos,!0);return this.pos+=8,e}readVarint(e){let i=this.buf,o,s;return s=i[this.pos++],o=127&s,s<128?o:(s=i[this.pos++],o|=(127&s)<<7,s<128?o:(s=i[this.pos++],o|=(127&s)<<14,s<128?o:(s=i[this.pos++],o|=(127&s)<<21,s<128?o:(s=i[this.pos],o|=(15&s)<<28,(function(l,h,d){let g=d.buf,m,v;if(v=g[d.pos++],m=(112&v)>>4,v<128||(v=g[d.pos++],m|=(127&v)<<3,v<128)||(v=g[d.pos++],m|=(127&v)<<10,v<128)||(v=g[d.pos++],m|=(127&v)<<17,v<128)||(v=g[d.pos++],m|=(127&v)<<24,v<128)||(v=g[d.pos++],m|=(1&v)<<31,v<128))return ga(l,m,h);throw new Error("Expected varint not more than 10 bytes")})(o,e,this)))))}readVarint64(){return this.readVarint(!0)}readSVarint(){let e=this.readVarint();return e%2==1?(e+1)/-2:e/2}readBoolean(){return!!this.readVarint()}readString(){let e=this.readVarint()+this.pos,i=this.pos;return this.pos=e,e-i>=12&&bp?bp.decode(this.buf.subarray(i,e)):(function(o,s,l){let h="",d=s;for(;d239?4:g>223?3:g>191?2:1;if(d+b>l)break;b===1?g<128&&(T=g):b===2?(m=o[d+1],(192&m)==128&&(T=(31&g)<<6|63&m,T<=127&&(T=null))):b===3?(m=o[d+1],v=o[d+2],(192&m)==128&&(192&v)==128&&(T=(15&g)<<12|(63&m)<<6|63&v,(T<=2047||T>=55296&&T<=57343)&&(T=null))):b===4&&(m=o[d+1],v=o[d+2],_=o[d+3],(192&m)==128&&(192&v)==128&&(192&_)==128&&(T=(15&g)<<18|(63&m)<<12|(63&v)<<6|63&_,(T<=65535||T>=1114112)&&(T=null))),T===null?(T=65533,b=1):T>65535&&(T-=65536,h+=String.fromCharCode(T>>>10&1023|55296),T=56320|1023&T),h+=String.fromCharCode(T),d+=b}return h})(this.buf,i,e)}readBytes(){let e=this.readVarint()+this.pos,i=this.buf.subarray(this.pos,e);return this.pos=e,i}readPackedVarint(e=[],i){let o=this.readPackedEnd();for(;this.pos127;);else if(i===2)this.pos=this.readVarint()+this.pos;else if(i===5)this.pos+=4;else{if(i!==1)throw new Error(`Unimplemented type: ${i}`);this.pos+=8}}writeTag(e,i){this.writeVarint(e<<3|i)}realloc(e){let i=this.length||16;for(;i268435455||e<0?(function(i,o){let s,l;if(i>=0?(s=i%4294967296|0,l=i/4294967296|0):(s=~(-i%4294967296),l=~(-i/4294967296),4294967295^s?s=s+1|0:(s=0,l=l+1|0)),i>=18446744073709552e3||i<-18446744073709552e3)throw new Error("Given varint doesn't fit into 10 bytes");o.realloc(10),(function(h,d,g){g.buf[g.pos++]=127&h|128,h>>>=7,g.buf[g.pos++]=127&h|128,h>>>=7,g.buf[g.pos++]=127&h|128,h>>>=7,g.buf[g.pos++]=127&h|128,g.buf[g.pos]=127&(h>>>=7)})(s,0,o),(function(h,d){let g=(7&h)<<4;d.buf[d.pos++]|=g|((h>>>=3)?128:0),h&&(d.buf[d.pos++]=127&h|((h>>>=7)?128:0),h&&(d.buf[d.pos++]=127&h|((h>>>=7)?128:0),h&&(d.buf[d.pos++]=127&h|((h>>>=7)?128:0),h&&(d.buf[d.pos++]=127&h|((h>>>=7)?128:0),h&&(d.buf[d.pos++]=127&h)))))})(l,o)})(e,this):(this.realloc(4),this.buf[this.pos++]=127&e|(e>127?128:0),e<=127||(this.buf[this.pos++]=127&(e>>>=7)|(e>127?128:0),e<=127||(this.buf[this.pos++]=127&(e>>>=7)|(e>127?128:0),e<=127||(this.buf[this.pos++]=e>>>7&127))))}writeSVarint(e){this.writeVarint(e<0?2*-e-1:2*e)}writeBoolean(e){this.writeVarint(+e)}writeString(e){e=String(e),this.realloc(4*e.length),this.pos++;let i=this.pos;this.pos=(function(s,l,h){for(let d,g,m=0;m55295&&d<57344){if(!g){d>56319||m+1===l.length?(s[h++]=239,s[h++]=191,s[h++]=189):g=d;continue}if(d<56320){s[h++]=239,s[h++]=191,s[h++]=189,g=d;continue}d=g-55296<<10|d-56320|65536,g=null}else g&&(s[h++]=239,s[h++]=191,s[h++]=189,g=null);d<128?s[h++]=d:(d<2048?s[h++]=d>>6|192:(d<65536?s[h++]=d>>12|224:(s[h++]=d>>18|240,s[h++]=d>>12&63|128),s[h++]=d>>6&63|128),s[h++]=63&d|128)}return h})(this.buf,e,this.pos);let o=this.pos-i;o>=128&&wp(i,o,this),this.pos=i-1,this.writeVarint(o),this.pos+=o}writeFloat(e){this.realloc(4),this.dataView.setFloat32(this.pos,e,!0),this.pos+=4}writeDouble(e){this.realloc(8),this.dataView.setFloat64(this.pos,e,!0),this.pos+=8}writeBytes(e){let i=e.length;this.writeVarint(i),this.realloc(i);for(let o=0;o=128&&wp(o,s,this),this.pos=o-1,this.writeVarint(s),this.pos+=s}writeMessage(e,i,o){this.writeTag(e,2),this.writeRawMessage(i,o)}writePackedVarint(e,i){i.length&&this.writeMessage(e,vg,i)}writePackedSVarint(e,i){i.length&&this.writeMessage(e,xg,i)}writePackedBoolean(e,i){i.length&&this.writeMessage(e,Tg,i)}writePackedFloat(e,i){i.length&&this.writeMessage(e,bg,i)}writePackedDouble(e,i){i.length&&this.writeMessage(e,wg,i)}writePackedFixed32(e,i){i.length&&this.writeMessage(e,Pg,i)}writePackedSFixed32(e,i){i.length&&this.writeMessage(e,Sg,i)}writePackedFixed64(e,i){i.length&&this.writeMessage(e,Ig,i)}writePackedSFixed64(e,i){i.length&&this.writeMessage(e,Mg,i)}writeBytesField(e,i){this.writeTag(e,2),this.writeBytes(i)}writeFixed32Field(e,i){this.writeTag(e,5),this.writeFixed32(i)}writeSFixed32Field(e,i){this.writeTag(e,5),this.writeSFixed32(i)}writeFixed64Field(e,i){this.writeTag(e,1),this.writeFixed64(i)}writeSFixed64Field(e,i){this.writeTag(e,1),this.writeSFixed64(i)}writeVarintField(e,i){this.writeTag(e,0),this.writeVarint(i)}writeSVarintField(e,i){this.writeTag(e,0),this.writeSVarint(i)}writeStringField(e,i){this.writeTag(e,2),this.writeString(i)}writeFloatField(e,i){this.writeTag(e,5),this.writeFloat(i)}writeDoubleField(e,i){this.writeTag(e,1),this.writeDouble(i)}writeBooleanField(e,i){this.writeVarintField(e,+i)}}function ga(r,e,i){return i?4294967296*e+(r>>>0):4294967296*(e>>>0)+(r>>>0)}function wp(r,e,i){let o=e<=16383?1:e<=2097151?2:e<=268435455?3:Math.floor(Math.log(e)/(7*Math.LN2));i.realloc(o);for(let s=i.pos-1;s>=r;s--)i.buf[s+o]=i.buf[s]}function vg(r,e){for(let i=0;id.h-h.h));let o=[{x:0,y:0,w:Math.max(Math.ceil(Math.sqrt(e/.95)),i),h:1/0}],s=0,l=0;for(let h of r)for(let d=o.length-1;d>=0;d--){let g=o[d];if(!(h.w>g.w||h.h>g.h)){if(h.x=g.x,h.y=g.y,l=Math.max(l,h.y+h.h),s=Math.max(s,h.x+h.w),h.w===g.w&&h.h===g.h){let m=o.pop();m&&dM.toCodeUnitIndex(Y)));let V=L(M.toString(),D);for(let Y of V){let J=[...Y].map((()=>0));A.push(new ma(Y,M.sections,J))}}else if(R){A=[],D=D.map((re=>M.toCodeUnitIndex(re)));let V=0,Y=[];for(let re of M.text)Y.push(...Array(re.length).fill(M.sectionIndex[V])),V++;let J=R(M.text,Y,D);for(let re of J){let te=[],ae="";for(let le of re[0])te.push(re[1][ae.length]),ae+=le;A.push(new ma(re[0],M.sections,te))}}else A=(function(V,Y){let J=[],re=0;for(let te of Y)J.push(V.substring(re,te)),re=te;return rem){let v=Math.ceil(l/m);s*=v/h,h=v}return{x1:o,y1:s,x2:o+l,y2:s+h}}function Mp(r,e,i,o,s,l){let h=r.image,d;if(h.content){let A=h.content,D=h.pixelRatio||1;d=[A[0]/D,A[1]/D,h.displaySize[0]-A[2]/D,h.displaySize[1]-A[3]/D]}let g=e.left*l,m=e.right*l,v,_,T,b;i==="width"||i==="both"?(b=s[0]+g-o[3],_=s[0]+m+o[1]):(b=s[0]+(g+m-h.displaySize[0])/2,_=b+h.displaySize[0]);let I=e.top*l,M=e.bottom*l;return i==="height"||i==="both"?(v=s[1]+I-o[0],T=s[1]+M+o[2]):(v=s[1]+(I+M-h.displaySize[1])/2,T=v+h.displaySize[1]),{image:h,top:v,right:_,bottom:T,left:b,collisionPadding:d}}Pe("ImagePosition",Vu),Pe("ImageAtlas",Pp),k.ax=void 0,(ao=k.ax||(k.ax={}))[ao.none=0]="none",ao[ao.horizontal=1]="horizontal",ao[ao.vertical=2]="vertical",ao[ao.horizontalOnly=3]="horizontalOnly";let In=128,lo=32640;function Ep(r,e){let{expression:i}=e;if(i.kind==="constant")return{kind:"constant",layoutSize:i.evaluate(new ct(r+1))};if(i.kind==="source")return{kind:"source"};{let{zoomStops:o,interpolationType:s}=i,l=0;for(;lh.id)),this.index=e.index,this.pixelRatio=e.pixelRatio,this.sourceLayerIndex=e.sourceLayerIndex,this.hasDependencies=!1,this.hasRTLText=!1,this.sortKeyRanges=[],this.collisionCircleArray=[];let i=this.layers[0]._unevaluatedLayout._values;this.textSizeData=Ep(this.zoom,i["text-size"]),this.iconSizeData=Ep(this.zoom,i["icon-size"]);let o=this.layers[0].layout,s=o.get("symbol-sort-key"),l=o.get("symbol-z-order");this.canOverlap=Uu(o,"text-overlap","text-allow-overlap")!=="never"||Uu(o,"icon-overlap","icon-allow-overlap")!=="never"||o.get("text-ignore-placement")||o.get("icon-ignore-placement"),this.sortFeaturesByKey=l!=="viewport-y"&&!s.isConstant(),this.sortFeaturesByY=(l==="viewport-y"||l==="auto"&&!this.sortFeaturesByKey)&&this.canOverlap,o.get("symbol-placement")==="point"&&(this.writingModes=o.get("text-writing-mode").map((h=>k.ax[h]))),this.stateDependentLayerIds=this.layers.filter((h=>h.isStateDependent())).map((h=>h.id)),this.sourceID=e.sourceID}createArrays(){this.text=new $u(new vr(this.layers,this.zoom,(e=>e.startsWith("text")))),this.icon=new $u(new vr(this.layers,this.zoom,(e=>e.startsWith("icon")))),this.glyphOffsetArray=new P,this.lineVertexArray=new S,this.symbolInstances=new w,this.textAnchorOffsets=new C}calculateGlyphDependencies(e,i,o,s,l){for(let h of e)if(i[h.codePointAt(0)]=!0,(o||s)&&l){let d=Kl[h];d&&(i[d.codePointAt(0)]=!0)}}populate(e,i,o){var s;let l=this.layers[0],h=l.layout,d=h.get("text-font"),g=h.get("text-field"),m=h.get("icon-image"),v=(g.value.kind!=="constant"||g.value.value instanceof xi&&!g.value.value.isEmpty()||g.value.value.toString().length>0)&&(d.value.kind!=="constant"||d.value.value.length>0),_=m.value.kind!=="constant"||!!m.value.value||Object.keys(m.parameters).length>0,T=h.get("symbol-sort-key");if(this.features=[],!v&&!_)return;let b=i.iconDependencies,I=i.glyphDependencies,M=i.availableImages,A=new ct(this.zoom);for(let{feature:D,id:L,index:R,sourceLayerIndex:F}of e){let O=l._featureFilter.needGeometry,V=Zr(D,O);if(!l._featureFilter.filter(A,V,o))continue;let Y,J;if(O||(V.geometry=$r(D)),v){let te=l.getValueAndResolveTokens("text-field",V,o,M),ae=xi.factory(te);this.hasRTLText||(this.hasRTLText=Og(ae)),(!this.hasRTLText||gr.getRTLTextPluginStatus()==="unavailable"||this.hasRTLText&&gr.isParsed())&&(Y=mg(ae,l,V))}if(_){let te=l.getValueAndResolveTokens("icon-image",V,o,M);J=te instanceof Ci?te:Ci.fromString(te)}if(!Y&&!J)continue;let re=this.sortFeaturesByKey?T.evaluate(V,{},o):void 0;if(this.features.push({id:L,text:Y,icon:J,index:R,sourceLayerIndex:F,geometry:V.geometry,properties:D.properties,type:ql.types[D.type],sortKey:re}),J&&(b[J.name]=!0),Y){let te=d.evaluate(V,{},o).join(","),ae=h.get("text-rotation-alignment")!=="viewport"&&h.get("symbol-placement")!=="point";this.allowVerticalPlacement=(s=this.writingModes)===null||s===void 0?void 0:s.includes(k.ax.vertical);for(let le of Y.sections)if(le.image)b[le.image.name]=!0;else{let ne=bl(Y.toString()),ie=le.fontStack||te;I[ie]||(I[ie]={}),this.calculateGlyphDependencies(le.text,I[ie],ae,this.allowVerticalPlacement,ne)}}}h.get("symbol-placement")==="line"&&(this.features=(function(D){let L={},R={},F=[],O=0;function V(te){F.push(D[te]),O++}function Y(te,ae,le){let ne=R[te];return delete R[te],R[ae]=ne,F[ne].geometry[0].pop(),F[ne].geometry[0]=F[ne].geometry[0].concat(le[0]),ne}function J(te,ae,le){let ne=L[ae];return delete L[ae],L[te]=ne,F[ne].geometry[0].shift(),F[ne].geometry[0]=le[0].concat(F[ne].geometry[0]),ne}function re(te,ae,le){let ne=le?ae[0][ae[0].length-1]:ae[0][0];return`${te}:${ne.x}:${ne.y}`}for(let te=0;tete.geometry))})(this.features)),this.sortFeaturesByKey&&this.features.sort(((D,L)=>D.sortKey-L.sortKey))}update(e,i,o){this.stateDependentLayers.length&&(this.text.programConfigurations.updatePaintArrays(e,i,this.layers,{imagePositions:o}),this.icon.programConfigurations.updatePaintArrays(e,i,this.layers,{imagePositions:o}))}isEmpty(){return this.symbolInstances.length===0&&!this.hasRTLText}uploadPending(){return!this.uploaded||this.text.programConfigurations.needsUpload||this.icon.programConfigurations.needsUpload}upload(e){!this.uploaded&&this.hasDebugData()&&(this.textCollisionBox.upload(e),this.iconCollisionBox.upload(e)),this.text.upload(e,this.sortFeaturesByY,!this.uploaded,this.text.programConfigurations.needsUpload),this.icon.upload(e,this.sortFeaturesByY,!this.uploaded,this.icon.programConfigurations.needsUpload),this.uploaded=!0}destroyDebugData(){this.textCollisionBox.destroy(),this.iconCollisionBox.destroy()}destroy(){this.text.destroy(),this.icon.destroy(),this.hasDebugData()&&this.destroyDebugData()}addToLineVertexArray(e,i){let o=this.lineVertexArray.length;if(e.segment!==void 0){let s=e.dist(i[e.segment+1]),l=e.dist(i[e.segment]),h={};for(let d=e.segment+1;d=0;d--)h[d]={x:i[d].x,y:i[d].y,tileUnitDistanceFromAnchor:l},d>0&&(l+=i[d-1].dist(i[d]));for(let d=0;d0}hasIconData(){return this.icon.segments.get().length>0}hasDebugData(){return this.textCollisionBox&&this.iconCollisionBox}hasTextCollisionBoxData(){return this.hasDebugData()&&this.textCollisionBox.segments.get().length>0}hasIconCollisionBoxData(){return this.hasDebugData()&&this.iconCollisionBox.segments.get().length>0}addIndicesForPlacedSymbol(e,i){let o=e.placedSymbolArray.get(i),s=o.vertexStartIndex+4*o.numGlyphs;for(let l=o.vertexStartIndex;ls[d]-s[g]||l[g]-l[d])),h}addToSortKeyRanges(e,i){let o=this.sortKeyRanges[this.sortKeyRanges.length-1];o?.sortKey===i?o.symbolInstanceEnd=e+1:this.sortKeyRanges.push({sortKey:i,symbolInstanceStart:e,symbolInstanceEnd:e+1})}sortFeatures(e){if(this.sortFeaturesByY&&this.sortedAngle!==e&&!(this.text.segments.get().length>1||this.icon.segments.get().length>1)){this.symbolInstanceIndexes=this.getSortedSymbolIndexes(e),this.sortedAngle=e,this.text.indexArray.clear(),this.icon.indexArray.clear(),this.featureSortOrder=[];for(let i of this.symbolInstanceIndexes){let o=this.symbolInstances.get(i);this.featureSortOrder.push(o.featureIndex);let s=[o.rightJustifiedTextSymbolIndex,o.centerJustifiedTextSymbolIndex,o.leftJustifiedTextSymbolIndex];for(let l=0;l=0&&s.indexOf(h)===l&&this.addIndicesForPlacedSymbol(this.text,h)}o.verticalPlacedTextSymbolIndex>=0&&this.addIndicesForPlacedSymbol(this.text,o.verticalPlacedTextSymbolIndex),o.placedIconSymbolIndex>=0&&this.addIndicesForPlacedSymbol(this.icon,o.placedIconSymbolIndex),o.verticalPlacedIconSymbolIndex>=0&&this.addIndicesForPlacedSymbol(this.icon,o.verticalPlacedIconSymbolIndex)}this.text.indexBuffer&&this.text.indexBuffer.updateData(this.text.indexArray),this.icon.indexBuffer&&this.icon.indexBuffer.updateData(this.icon.indexArray)}}}let Cp,Ap;Pe("SymbolBucket",_a,{omit:["layers","collisionBoxArray","features","compareText"]}),_a.MAX_GLYPHS=65535,_a.addDynamicAttributes=Gu;var qu={get paint(){return Ap=Ap||new ui({"icon-opacity":new Ce(ce.paint_symbol["icon-opacity"]),"icon-color":new Ce(ce.paint_symbol["icon-color"]),"icon-halo-color":new Ce(ce.paint_symbol["icon-halo-color"]),"icon-halo-width":new Ce(ce.paint_symbol["icon-halo-width"]),"icon-halo-blur":new Ce(ce.paint_symbol["icon-halo-blur"]),"icon-translate":new Ie(ce.paint_symbol["icon-translate"]),"icon-translate-anchor":new Ie(ce.paint_symbol["icon-translate-anchor"]),"text-opacity":new Ce(ce.paint_symbol["text-opacity"]),"text-color":new Ce(ce.paint_symbol["text-color"],{runtimeType:Ei,getOverride:r=>r.textColor,hasOverride:r=>!!r.textColor}),"text-halo-color":new Ce(ce.paint_symbol["text-halo-color"]),"text-halo-width":new Ce(ce.paint_symbol["text-halo-width"]),"text-halo-blur":new Ce(ce.paint_symbol["text-halo-blur"]),"text-translate":new Ie(ce.paint_symbol["text-translate"]),"text-translate-anchor":new Ie(ce.paint_symbol["text-translate-anchor"])})},get layout(){return Cp=Cp||new ui({"symbol-placement":new Ie(ce.layout_symbol["symbol-placement"]),"symbol-spacing":new Ie(ce.layout_symbol["symbol-spacing"]),"symbol-avoid-edges":new Ie(ce.layout_symbol["symbol-avoid-edges"]),"symbol-sort-key":new Ce(ce.layout_symbol["symbol-sort-key"]),"symbol-z-order":new Ie(ce.layout_symbol["symbol-z-order"]),"icon-allow-overlap":new Ie(ce.layout_symbol["icon-allow-overlap"]),"icon-overlap":new Ie(ce.layout_symbol["icon-overlap"]),"icon-ignore-placement":new Ie(ce.layout_symbol["icon-ignore-placement"]),"icon-optional":new Ie(ce.layout_symbol["icon-optional"]),"icon-rotation-alignment":new Ie(ce.layout_symbol["icon-rotation-alignment"]),"icon-size":new Ce(ce.layout_symbol["icon-size"]),"icon-text-fit":new Ie(ce.layout_symbol["icon-text-fit"]),"icon-text-fit-padding":new Ie(ce.layout_symbol["icon-text-fit-padding"]),"icon-image":new Ce(ce.layout_symbol["icon-image"]),"icon-rotate":new Ce(ce.layout_symbol["icon-rotate"]),"icon-padding":new Ce(ce.layout_symbol["icon-padding"]),"icon-keep-upright":new Ie(ce.layout_symbol["icon-keep-upright"]),"icon-offset":new Ce(ce.layout_symbol["icon-offset"]),"icon-anchor":new Ce(ce.layout_symbol["icon-anchor"]),"icon-pitch-alignment":new Ie(ce.layout_symbol["icon-pitch-alignment"]),"text-pitch-alignment":new Ie(ce.layout_symbol["text-pitch-alignment"]),"text-rotation-alignment":new Ie(ce.layout_symbol["text-rotation-alignment"]),"text-field":new Ce(ce.layout_symbol["text-field"]),"text-font":new Ce(ce.layout_symbol["text-font"]),"text-size":new Ce(ce.layout_symbol["text-size"]),"text-max-width":new Ce(ce.layout_symbol["text-max-width"]),"text-line-height":new Ie(ce.layout_symbol["text-line-height"]),"text-letter-spacing":new Ce(ce.layout_symbol["text-letter-spacing"]),"text-justify":new Ce(ce.layout_symbol["text-justify"]),"text-radial-offset":new Ce(ce.layout_symbol["text-radial-offset"]),"text-variable-anchor":new Ie(ce.layout_symbol["text-variable-anchor"]),"text-variable-anchor-offset":new Ce(ce.layout_symbol["text-variable-anchor-offset"]),"text-anchor":new Ce(ce.layout_symbol["text-anchor"]),"text-max-angle":new Ie(ce.layout_symbol["text-max-angle"]),"text-writing-mode":new Ie(ce.layout_symbol["text-writing-mode"]),"text-rotate":new Ce(ce.layout_symbol["text-rotate"]),"text-padding":new Ie(ce.layout_symbol["text-padding"]),"text-keep-upright":new Ie(ce.layout_symbol["text-keep-upright"]),"text-transform":new Ce(ce.layout_symbol["text-transform"]),"text-offset":new Ce(ce.layout_symbol["text-offset"]),"text-allow-overlap":new Ie(ce.layout_symbol["text-allow-overlap"]),"text-overlap":new Ie(ce.layout_symbol["text-overlap"]),"text-ignore-placement":new Ie(ce.layout_symbol["text-ignore-placement"]),"text-optional":new Ie(ce.layout_symbol["text-optional"])})}};class Dp{constructor(e){if(e.property.overrides===void 0)throw new Error("overrides must be provided to instantiate FormatSectionOverride class");this.type=e.property.overrides?e.property.overrides.runtimeType:zr,this.defaultValue=e}evaluate(e){if(e.formattedSection){let i=this.defaultValue.property.overrides;if(i?.hasOverride(e.formattedSection))return i.getOverride(e.formattedSection)}return e.feature&&e.featureState?this.defaultValue.evaluate(e.feature,e.featureState):this.defaultValue.property.specification.default}eachChild(e){this.defaultValue.isConstant()||e(this.defaultValue.value._styleExpression.expression)}outputDefined(){return!1}serialize(){return null}}Pe("FormatSectionOverride",Dp,{omit:["defaultValue"]});class Ph extends Ui{constructor(e,i){super(e,qu,i)}recalculate(e,i){if(super.recalculate(e,i),this.layout.get("icon-rotation-alignment")==="auto"&&(this.layout._values["icon-rotation-alignment"]=this.layout.get("symbol-placement")!=="point"?"map":"viewport"),this.layout.get("text-rotation-alignment")==="auto"&&(this.layout._values["text-rotation-alignment"]=this.layout.get("symbol-placement")!=="point"?"map":"viewport"),this.layout.get("text-pitch-alignment")==="auto"&&(this.layout._values["text-pitch-alignment"]=this.layout.get("text-rotation-alignment")==="map"?"map":"viewport"),this.layout.get("icon-pitch-alignment")==="auto"&&(this.layout._values["icon-pitch-alignment"]=this.layout.get("icon-rotation-alignment")),this.layout.get("symbol-placement")==="point"){let o=this.layout.get("text-writing-mode");if(o){let s=[];for(let l of o)s.includes(l)||s.push(l);this.layout._values["text-writing-mode"]=s}else this.layout._values["text-writing-mode"]=["horizontal"]}this._setPaintOverrides()}getValueAndResolveTokens(e,i,o,s){let l=this.layout.get(e).evaluate(i,{},o,s),h=this._unevaluatedLayout._values[e];return h.isDataDriven()||Ns(h.value)||!l?l:(function(d,g){return g.replace(/{([^{}]+)}/g,((m,v)=>d&&v in d?String(d[v]):""))})(i.properties,l)}createBucket(e){return new _a(e)}queryRadius(){return 0}queryIntersectsFeature(){throw new Error("Should take a different path in FeatureIndex")}_setPaintOverrides(){for(let e of qu.paint.overridableProperties){if(!Ph.hasPaintOverride(this.layout,e))continue;let i=this.paint.get(e),o=new Dp(i),s=new Bo(o,i.property.specification),l=null;l=i.value.kind==="constant"||i.value.kind==="source"?new Vs("source",s):new js("composite",s,i.value.zoomStops),this.paint._values[e]=new er(i.property,l,i.parameters)}}_handleOverridablePaintPropertyUpdate(e,i,o){return!(!this.layout||i.isDataDriven()||o.isDataDriven())&&Ph.hasPaintOverride(this.layout,e)}static hasPaintOverride(e,i){let o=e.get("text-field"),s=qu.paint.properties[i],l=!1,h=d=>{var g;for(let m of d)if(!((g=s.overrides)===null||g===void 0)&&g.hasOverride(m))return void(l=!0)};if(o.value.kind==="constant"&&o.value.value instanceof xi)h(o.value.value.sections);else if(o.value.kind==="source"||o.value.kind==="composite"){let d=m=>{l||(m instanceof ir&&St(m.value)===To?h(m.value.sections):m instanceof dn?h(m.sections):m.eachChild(d))},g=o.value;g._styleExpression&&d(g._styleExpression.expression)}return l}}let zp;var Ng={get paint(){return zp=zp||new ui({"background-color":new Ie(ce.paint_background["background-color"]),"background-pattern":new nh(ce.paint_background["background-pattern"]),"background-opacity":new Ie(ce.paint_background["background-opacity"])})}};class Vg extends Ui{constructor(e,i){super(e,Ng,i)}}class jg extends Ui{constructor(e,i){super(e,{},i),this.onAdd=o=>{this.implementation.onAdd&&this.implementation.onAdd(o,o.painter.context.gl)},this.onRemove=o=>{this.implementation.onRemove&&this.implementation.onRemove(o,o.painter.context.gl)},this.implementation=e}is3D(){return this.implementation.renderingMode==="3d"}hasOffscreenPass(){return this.implementation.prerender!==void 0}recalculate(){}updateTransitions(){}hasTransition(){return!1}serialize(){throw new Error("Custom layers cannot be serialized")}}class Ug{constructor(e){this._methodToThrottle=e,this._triggered=!1,this._channel=new MessageChannel,this._channel.port2.onmessage=()=>{this._triggered=!1,this._methodToThrottle()}}trigger(){var e;this._triggered||(this._triggered=!0,(e=this._channel)===null||e===void 0||e.port1.postMessage(!0))}remove(){delete this._channel,this._methodToThrottle=()=>{}}}let Gg={once:!0},Wu=63710088e-1;class co{constructor(e,i){if(isNaN(e)||isNaN(i))throw new Error(`Invalid LngLat object: (${e}, ${i})`);if(this.lng=+e,this.lat=+i,this.lat>90||this.lat<-90)throw new Error("Invalid LngLat latitude value: must be between -90 and 90")}wrap(){return new co(zn(this.lng,-180,180),this.lat)}toArray(){return[this.lng,this.lat]}toString(){return`LngLat(${this.lng}, ${this.lat})`}distanceTo(e){let i=Math.PI/180,o=this.lat*i,s=e.lat*i,l=Math.sin(o)*Math.sin(s)+Math.cos(o)*Math.cos(s)*Math.cos((e.lng-this.lng)*i);return Wu*Math.acos(Math.min(l,1))}static convert(e){if(e instanceof co)return e;if(Array.isArray(e)&&(e.length===2||e.length===3))return new co(Number(e[0]),Number(e[1]));if(!Array.isArray(e)&&typeof e=="object"&&e!==null)return new co(Number("lng"in e?e.lng:e.lon),Number(e.lat));throw new Error("`LngLatLike` argument must be specified as a LngLat instance, an object {lng: , lat: }, an object {lon: , lat: }, or an array of [, ]")}}let Rp=2*Math.PI*Wu;function kp(r){return Rp*Math.cos(r*Math.PI/180)}function Lp(r){return(180+r)/360}function Fp(r){return(180-180/Math.PI*Math.log(Math.tan(Math.PI/4+r*Math.PI/360)))/360}function Bp(r,e){return r/kp(e)}function Op(r){return 360*r-180}function Sh(r){return 360/Math.PI*Math.atan(Math.exp((180-360*r)*Math.PI/180))-90}function Np(r,e){return r*kp(Sh(e))}class Jl{constructor(e,i,o=0){this.x=+e,this.y=+i,this.z=+o}static fromLngLat(e,i=0){let o=co.convert(e);return new Jl(Lp(o.lng),Fp(o.lat),Bp(i,o.lat))}toLngLat(){return new co(Op(this.x),Sh(this.y))}toAltitude(){return Np(this.z,this.y)}meterInMercatorCoordinateUnits(){return 1/Rp*(e=Sh(this.y),1/Math.cos(e*Math.PI/180));var e}}function Vp(r,e,i){var o=2*Math.PI*6378137/256/Math.pow(2,i);return[r*o-2*Math.PI*6378137/2,e*o-2*Math.PI*6378137/2]}class Hu{constructor(e,i,o){if(!(function(s,l,h){return!(s<0||s>25||h<0||h>=Math.pow(2,s)||l<0||l>=Math.pow(2,s))})(e,i,o))throw new Error(`x=${i}, y=${o}, z=${e} outside of bounds. 0<=x<${Math.pow(2,e)}, 0<=y<${Math.pow(2,e)} 0<=z<=25 `);this.z=e,this.x=i,this.y=o,this.key=ya(0,e,e,i,o)}equals(e){return this.z===e.z&&this.x===e.x&&this.y===e.y}url(e,i,o){let s=(h=this.y,d=this.z,g=Vp(256*(l=this.x),256*(h=Math.pow(2,d)-h-1),d),m=Vp(256*(l+1),256*(h+1),d),g[0]+","+g[1]+","+m[0]+","+m[1]);var l,h,d,g,m;let v=(function(_,T,b){let I="";for(let M=_;M>0;M--){let A=1<1?"@2x":"").replace(/{quadkey}/g,v).replace(/{bbox-epsg-3857}/g,s)}isChildOf(e){let i=this.z-e.z;return i>0&&e.x===this.x>>i&&e.y===this.y>>i}getTilePoint(e){let i=Math.pow(2,this.z);return new Te((e.x*i-this.x)*De,(e.y*i-this.y)*De)}toString(){return`${this.z}/${this.x}/${this.y}`}}class jp{constructor(e,i){this.wrap=e,this.canonical=i,this.key=ya(e,i.z,i.z,i.x,i.y)}}class $i{constructor(e,i,o,s,l){if(this.terrainRttPosMatrix32f=null,e= z; overscaledZ = ${e}; z = ${o}`);this.overscaledZ=e,this.wrap=i,this.canonical=new Hu(o,+s,+l),this.key=ya(i,e,o,s,l)}clone(){return new $i(this.overscaledZ,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y)}equals(e){return this.overscaledZ===e.overscaledZ&&this.wrap===e.wrap&&this.canonical.equals(e.canonical)}scaledTo(e){if(e>this.overscaledZ)throw new Error(`targetZ > this.overscaledZ; targetZ = ${e}; overscaledZ = ${this.overscaledZ}`);let i=this.canonical.z-e;return e>this.canonical.z?new $i(e,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y):new $i(e,this.wrap,e,this.canonical.x>>i,this.canonical.y>>i)}isOverscaled(){return this.overscaledZ>this.canonical.z}calculateScaledKey(e,i){if(e>this.overscaledZ)throw new Error(`targetZ > this.overscaledZ; targetZ = ${e}; overscaledZ = ${this.overscaledZ}`);let o=this.canonical.z-e;return e>this.canonical.z?ya(this.wrap*+i,e,this.canonical.z,this.canonical.x,this.canonical.y):ya(this.wrap*+i,e,e,this.canonical.x>>o,this.canonical.y>>o)}isChildOf(e){if(e.wrap!==this.wrap||this.overscaledZ-e.overscaledZ<=0)return!1;if(e.overscaledZ===0)return this.overscaledZ>0;let i=this.canonical.z-e.canonical.z;return!(i<0)&&e.canonical.x===this.canonical.x>>i&&e.canonical.y===this.canonical.y>>i}children(e){if(this.overscaledZ>=e)return[new $i(this.overscaledZ+1,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y)];let i=this.canonical.z+1,o=2*this.canonical.x,s=2*this.canonical.y;return[new $i(i,this.wrap,i,o,s),new $i(i,this.wrap,i,o+1,s),new $i(i,this.wrap,i,o,s+1),new $i(i,this.wrap,i,o+1,s+1)]}isLessThan(e){return this.wrape.wrap)&&(this.overscaledZe.overscaledZ)&&(this.canonical.xe.canonical.x)&&this.canonical.y=0&&e=0&&i=m)return null;let _=this.canonical.x+s,T=this.wrap;return _<0?(T-=Math.ceil(-_/m),_=(_%m+m)%m):_>=m&&(T+=Math.floor(_/m),_%=m),{tileID:new $i(this.overscaledZ,T,g,_,v),x:h,y:d}}}function ya(r,e,i,o,s){(r*=2)<0&&(r=-1*r-1);let l=1<this.maxX||this.minY>this.maxY)&&(this.minX=1/0,this.maxX=-1/0,this.minY=1/0,this.maxY=-1/0),this}shrinkBy(e){return this.expandBy(-e)}map(e){let i=new ss;return i.extend(e(new Te(this.minX,this.minY))),i.extend(e(new Te(this.maxX,this.minY))),i.extend(e(new Te(this.minX,this.maxY))),i.extend(e(new Te(this.maxX,this.maxY))),i}static fromPoints(e){let i=new ss;for(let o of e)i.extend(o);return i}contains(e){return e.x>=this.minX&&e.x<=this.maxX&&e.y>=this.minY&&e.y<=this.maxY}empty(){return this.minX>this.maxX}width(){return this.maxX-this.minX}height(){return this.maxY-this.minY}covers(e){return!this.empty()&&!e.empty()&&e.minX>=this.minX&&e.maxX<=this.maxX&&e.minY>=this.minY&&e.maxY<=this.maxY}intersects(e){return!this.empty()&&!e.empty()&&e.minX<=this.maxX&&e.maxX>=this.minX&&e.minY<=this.maxY&&e.maxY>=this.minY}}class Up{constructor(e){this._stringToNumber={},this._numberToString=[];for(let i=0;i=this._numberToString.length)throw new Error(`Out of bounds. Index requested n=${e} can't be >= this._numberToString.length ${this._numberToString.length}`);return this._numberToString[e]}}class Gp{constructor(e,i,o,s,l){this.type="Feature",this._vectorTileFeature=e,this._x=o,this._y=s,this._z=i,this.properties=e.properties,this.id=l}projectPoint(e,i,o,s){return[360*(e.x+i)/s-180,360/Math.PI*Math.atan(Math.exp((1-2*(e.y+o)/s)*Math.PI))-90]}projectLine(e,i,o,s){return e.map((l=>this.projectPoint(l,i,o,s)))}get geometry(){if(this._geometry)return this._geometry;let e=this._vectorTileFeature,i=e.extent*Math.pow(2,this._z),o=e.extent*this._x,s=e.extent*this._y,l=e.loadGeometry();switch(e.type){case 1:{let h=[];for(let g of l)h.push(g[0]);let d=this.projectLine(h,o,s,i);this._geometry=h.length===1?{type:"Point",coordinates:d[0]}:{type:"MultiPoint",coordinates:d};break}case 2:{let h=l.map((d=>this.projectLine(d,o,s,i)));this._geometry=h.length===1?{type:"LineString",coordinates:h[0]}:{type:"MultiLineString",coordinates:h};break}case 3:{let h=qd(l),d=[];for(let g of h)d.push(g.map((m=>this.projectLine(m,o,s,i))));this._geometry=d.length===1?{type:"Polygon",coordinates:d[0]}:{type:"MultiPolygon",coordinates:d};break}default:throw new Error(`unknown feature type: ${e.type}`)}return this._geometry}set geometry(e){this._geometry=e}toJSON(){let e={geometry:this.geometry};for(let i in this)i!=="_geometry"&&i!=="_vectorTileFeature"&&i!=="_x"&&i!=="_y"&&i!=="_z"&&(e[i]=this[i]);return e}}class va{constructor(e,i,o){this._name=e,this.dataBuffer=i,typeof o=="number"?this._size=o:(this.nullabilityBuffer=o,this._size=o.size())}getValue(e){return this.nullabilityBuffer&&!this.nullabilityBuffer.get(e)?null:this.getValueFromBuffer(e)}has(e){return this.nullabilityBuffer?.get(e)||!this.nullabilityBuffer}get name(){return this._name}get size(){return this._size}}class Ih extends va{}class Xu extends Ih{getValueFromBuffer(e){return this.dataBuffer[e]}}class Yu extends Ih{getValueFromBuffer(e){return this.dataBuffer[e]}}class $p extends va{constructor(e,i,o,s){super(e,i,s),this.delta=o}}class Ku extends $p{constructor(e,i,o,s){super(e,Int32Array.of(i),o,s)}getValueFromBuffer(e){return this.dataBuffer[0]+e*this.delta}}class Ju extends va{constructor(e,i,o,s){super(e,s?Int32Array.of(i):Uint32Array.of(i),o)}getValueFromBuffer(e){return this.dataBuffer[0]}}class $g{constructor(e,i,o,s,l=4096){this._name=e,this._geometryVector=i,this._idVector=o,this._propertyVectors=s,this._extent=l}get name(){return this._name}get idVector(){return this._idVector}get geometryVector(){return this._geometryVector}get propertyVectors(){return this._propertyVectors}getPropertyVector(e){return this.propertyVectorsMap||(this.propertyVectorsMap=new Map(this._propertyVectors.map((i=>[i.name,i])))),this.propertyVectorsMap.get(e)}get numFeatures(){return this.geometryVector.numGeometries}get extent(){return this._extent}getFeatures(){let e=[],i=this.geometryVector.getGeometries();for(let o=0;o>>32-r;let ed=Qu,Mn=256;function td(r,e){return r-r%e}function Zg(r){let e=r>>>0;return((255&e)<<24|(65280&e)<<8|e>>>8&65280|e>>>24&255)>>>0}let id=(function(){if(!Number.isFinite(65536))return 65536;let r=td(Math.floor(65536),Mn);return r===0?Mn:r})(),qg=3*id/Mn+id|0;function qp(){let r=new Uint8Array(qg);return{dataToBePacked:new Array(33),dataPointers:new Int32Array(33),byteContainer:r,byteContainerI32:new Int32Array(r.buffer,r.byteOffset,r.byteLength>>>2),exceptionSizes:new Int32Array(33)}}function Wg(r,e,i,o,s){switch(s){case 1:(function(l,h,d,g){let m=g,v=h;for(let _=0;_<8;_++){let T=l[v++]>>>0;d[m++]=T>>>0&1,d[m++]=T>>>1&1,d[m++]=T>>>2&1,d[m++]=T>>>3&1,d[m++]=T>>>4&1,d[m++]=T>>>5&1,d[m++]=T>>>6&1,d[m++]=T>>>7&1,d[m++]=T>>>8&1,d[m++]=T>>>9&1,d[m++]=T>>>10&1,d[m++]=T>>>11&1,d[m++]=T>>>12&1,d[m++]=T>>>13&1,d[m++]=T>>>14&1,d[m++]=T>>>15&1,d[m++]=T>>>16&1,d[m++]=T>>>17&1,d[m++]=T>>>18&1,d[m++]=T>>>19&1,d[m++]=T>>>20&1,d[m++]=T>>>21&1,d[m++]=T>>>22&1,d[m++]=T>>>23&1,d[m++]=T>>>24&1,d[m++]=T>>>25&1,d[m++]=T>>>26&1,d[m++]=T>>>27&1,d[m++]=T>>>28&1,d[m++]=T>>>29&1,d[m++]=T>>>30&1,d[m++]=T>>>31&1}})(r,e,i,o);break;case 2:(function(l,h,d,g){let m=g,v=h;for(let _=0;_<8;_++){let T=l[v++]>>>0,b=l[v++]>>>0;d[m++]=T>>>0&3,d[m++]=T>>>2&3,d[m++]=T>>>4&3,d[m++]=T>>>6&3,d[m++]=T>>>8&3,d[m++]=T>>>10&3,d[m++]=T>>>12&3,d[m++]=T>>>14&3,d[m++]=T>>>16&3,d[m++]=T>>>18&3,d[m++]=T>>>20&3,d[m++]=T>>>22&3,d[m++]=T>>>24&3,d[m++]=T>>>26&3,d[m++]=T>>>28&3,d[m++]=T>>>30&3,d[m++]=b>>>0&3,d[m++]=b>>>2&3,d[m++]=b>>>4&3,d[m++]=b>>>6&3,d[m++]=b>>>8&3,d[m++]=b>>>10&3,d[m++]=b>>>12&3,d[m++]=b>>>14&3,d[m++]=b>>>16&3,d[m++]=b>>>18&3,d[m++]=b>>>20&3,d[m++]=b>>>22&3,d[m++]=b>>>24&3,d[m++]=b>>>26&3,d[m++]=b>>>28&3,d[m++]=b>>>30&3}})(r,e,i,o);break;case 3:(function(l,h,d,g){let m=g,v=h;for(let _=0;_<8;_++){let T=l[v++]>>>0,b=l[v++]>>>0,I=l[v++]>>>0;d[m++]=T>>>0&7,d[m++]=T>>>3&7,d[m++]=T>>>6&7,d[m++]=T>>>9&7,d[m++]=T>>>12&7,d[m++]=T>>>15&7,d[m++]=T>>>18&7,d[m++]=T>>>21&7,d[m++]=T>>>24&7,d[m++]=T>>>27&7,d[m++]=7&(T>>>30|(1&b)<<2),d[m++]=b>>>1&7,d[m++]=b>>>4&7,d[m++]=b>>>7&7,d[m++]=b>>>10&7,d[m++]=b>>>13&7,d[m++]=b>>>16&7,d[m++]=b>>>19&7,d[m++]=b>>>22&7,d[m++]=b>>>25&7,d[m++]=b>>>28&7,d[m++]=7&(b>>>31|(3&I)<<1),d[m++]=I>>>2&7,d[m++]=I>>>5&7,d[m++]=I>>>8&7,d[m++]=I>>>11&7,d[m++]=I>>>14&7,d[m++]=I>>>17&7,d[m++]=I>>>20&7,d[m++]=I>>>23&7,d[m++]=I>>>26&7,d[m++]=I>>>29&7}})(r,e,i,o);break;case 4:(function(l,h,d,g){let m=g,v=h;for(let _=0;_<8;_++){let T=l[v++]>>>0,b=l[v++]>>>0,I=l[v++]>>>0,M=l[v++]>>>0;d[m++]=T>>>0&15,d[m++]=T>>>4&15,d[m++]=T>>>8&15,d[m++]=T>>>12&15,d[m++]=T>>>16&15,d[m++]=T>>>20&15,d[m++]=T>>>24&15,d[m++]=T>>>28&15,d[m++]=b>>>0&15,d[m++]=b>>>4&15,d[m++]=b>>>8&15,d[m++]=b>>>12&15,d[m++]=b>>>16&15,d[m++]=b>>>20&15,d[m++]=b>>>24&15,d[m++]=b>>>28&15,d[m++]=I>>>0&15,d[m++]=I>>>4&15,d[m++]=I>>>8&15,d[m++]=I>>>12&15,d[m++]=I>>>16&15,d[m++]=I>>>20&15,d[m++]=I>>>24&15,d[m++]=I>>>28&15,d[m++]=M>>>0&15,d[m++]=M>>>4&15,d[m++]=M>>>8&15,d[m++]=M>>>12&15,d[m++]=M>>>16&15,d[m++]=M>>>20&15,d[m++]=M>>>24&15,d[m++]=M>>>28&15}})(r,e,i,o);break;case 5:(function(l,h,d,g){let m=g,v=h;for(let _=0;_<8;_++){let T=l[v++]>>>0,b=l[v++]>>>0,I=l[v++]>>>0,M=l[v++]>>>0,A=l[v++]>>>0;d[m++]=T>>>0&31,d[m++]=T>>>5&31,d[m++]=T>>>10&31,d[m++]=T>>>15&31,d[m++]=T>>>20&31,d[m++]=T>>>25&31,d[m++]=31&(T>>>30|(7&b)<<2),d[m++]=b>>>3&31,d[m++]=b>>>8&31,d[m++]=b>>>13&31,d[m++]=b>>>18&31,d[m++]=b>>>23&31,d[m++]=31&(b>>>28|(1&I)<<4),d[m++]=I>>>1&31,d[m++]=I>>>6&31,d[m++]=I>>>11&31,d[m++]=I>>>16&31,d[m++]=I>>>21&31,d[m++]=I>>>26&31,d[m++]=31&(I>>>31|(15&M)<<1),d[m++]=M>>>4&31,d[m++]=M>>>9&31,d[m++]=M>>>14&31,d[m++]=M>>>19&31,d[m++]=M>>>24&31,d[m++]=31&(M>>>29|(3&A)<<3),d[m++]=A>>>2&31,d[m++]=A>>>7&31,d[m++]=A>>>12&31,d[m++]=A>>>17&31,d[m++]=A>>>22&31,d[m++]=A>>>27&31}})(r,e,i,o);break;case 6:(function(l,h,d,g){let m=g,v=h;for(let _=0;_<8;_++){let T=l[v++]>>>0,b=l[v++]>>>0,I=l[v++]>>>0,M=l[v++]>>>0,A=l[v++]>>>0,D=l[v++]>>>0;d[m++]=T>>>0&63,d[m++]=T>>>6&63,d[m++]=T>>>12&63,d[m++]=T>>>18&63,d[m++]=T>>>24&63,d[m++]=63&(T>>>30|(15&b)<<2),d[m++]=b>>>4&63,d[m++]=b>>>10&63,d[m++]=b>>>16&63,d[m++]=b>>>22&63,d[m++]=63&(b>>>28|(3&I)<<4),d[m++]=I>>>2&63,d[m++]=I>>>8&63,d[m++]=I>>>14&63,d[m++]=I>>>20&63,d[m++]=I>>>26&63,d[m++]=M>>>0&63,d[m++]=M>>>6&63,d[m++]=M>>>12&63,d[m++]=M>>>18&63,d[m++]=M>>>24&63,d[m++]=63&(M>>>30|(15&A)<<2),d[m++]=A>>>4&63,d[m++]=A>>>10&63,d[m++]=A>>>16&63,d[m++]=A>>>22&63,d[m++]=63&(A>>>28|(3&D)<<4),d[m++]=D>>>2&63,d[m++]=D>>>8&63,d[m++]=D>>>14&63,d[m++]=D>>>20&63,d[m++]=D>>>26&63}})(r,e,i,o);break;case 7:(function(l,h,d,g){let m=g,v=h;for(let _=0;_<8;_++){let T=l[v++]>>>0,b=l[v++]>>>0,I=l[v++]>>>0,M=l[v++]>>>0,A=l[v++]>>>0,D=l[v++]>>>0,L=l[v++]>>>0;d[m++]=T>>>0&127,d[m++]=T>>>7&127,d[m++]=T>>>14&127,d[m++]=T>>>21&127,d[m++]=127&(T>>>28|(7&b)<<4),d[m++]=b>>>3&127,d[m++]=b>>>10&127,d[m++]=b>>>17&127,d[m++]=b>>>24&127,d[m++]=127&(b>>>31|(63&I)<<1),d[m++]=I>>>6&127,d[m++]=I>>>13&127,d[m++]=I>>>20&127,d[m++]=127&(I>>>27|(3&M)<<5),d[m++]=M>>>2&127,d[m++]=M>>>9&127,d[m++]=M>>>16&127,d[m++]=M>>>23&127,d[m++]=127&(M>>>30|(31&A)<<2),d[m++]=A>>>5&127,d[m++]=A>>>12&127,d[m++]=A>>>19&127,d[m++]=127&(A>>>26|(1&D)<<6),d[m++]=D>>>1&127,d[m++]=D>>>8&127,d[m++]=D>>>15&127,d[m++]=D>>>22&127,d[m++]=127&(D>>>29|(15&L)<<3),d[m++]=L>>>4&127,d[m++]=L>>>11&127,d[m++]=L>>>18&127,d[m++]=L>>>25&127}})(r,e,i,o);break;case 8:(function(l,h,d,g){let m=g,v=h;for(let _=0;_<8;_++){let T=l[v++]>>>0,b=l[v++]>>>0,I=l[v++]>>>0,M=l[v++]>>>0,A=l[v++]>>>0,D=l[v++]>>>0,L=l[v++]>>>0,R=l[v++]>>>0;d[m++]=T>>>0&255,d[m++]=T>>>8&255,d[m++]=T>>>16&255,d[m++]=T>>>24&255,d[m++]=b>>>0&255,d[m++]=b>>>8&255,d[m++]=b>>>16&255,d[m++]=b>>>24&255,d[m++]=I>>>0&255,d[m++]=I>>>8&255,d[m++]=I>>>16&255,d[m++]=I>>>24&255,d[m++]=M>>>0&255,d[m++]=M>>>8&255,d[m++]=M>>>16&255,d[m++]=M>>>24&255,d[m++]=A>>>0&255,d[m++]=A>>>8&255,d[m++]=A>>>16&255,d[m++]=A>>>24&255,d[m++]=D>>>0&255,d[m++]=D>>>8&255,d[m++]=D>>>16&255,d[m++]=D>>>24&255,d[m++]=L>>>0&255,d[m++]=L>>>8&255,d[m++]=L>>>16&255,d[m++]=L>>>24&255,d[m++]=R>>>0&255,d[m++]=R>>>8&255,d[m++]=R>>>16&255,d[m++]=R>>>24&255}})(r,e,i,o);break;case 16:(function(l,h,d,g){let m=g,v=h;for(let _=0;_<128;_++){let T=l[v++]>>>0;d[m++]=65535&T,d[m++]=T>>>16&65535}})(r,e,i,o);break;default:(function(l,h,d,g,m){let v=ed[m]>>>0,_=h,T=0,b=l[_]>>>0,I=g;for(let M=0;M<8;M++){for(let A=0;A<32;A++)if(T+m<=32)d[I+A]=b>>>T&v,T+=m,T===32&&(T=0,_++,A!==31&&(b=l[_]>>>0));else{let D=32-T,L=b>>>T;_++,b=l[_]>>>0;let R=m-D;d[I+A]=(L|(b&-1>>>32-R>>>0)<>>0)}})(r,e,i,o,s)}return e+(s<<3)|0}function Hg(r,e,i,o){if(i+2>e)throw new Error(`FastPFOR decode: byteContainer underflow at block=${o} (need 2 bytes for [bitWidth, exceptionCount], bytePos=${i}, byteSize=${e})`);let s=r[i++],l=r[i++];if(s>32)throw new Error(`FastPFOR decode: invalid bitWidth=${s} at block=${o} (expected 0..32). This likely indicates corrupted or truncated input.`);return{bitWidth:s,exceptionCount:l,bytePosIn:i}}function Xg(r,e,i,o,s,l,h,d,g){let{maxBits:m,exceptionBitWidth:v,bytePosIn:_}=(function(A,D,L,R,F,O){if(L+1>D)throw new Error(`FastPFOR decode: exception header underflow at block=${O} (need 1 byte for maxBits, bytePos=${L}, byteSize=${D})`);let V=A[L++];if(V32)throw new Error(`FastPFOR decode: invalid maxBits=${V} at block=${O} (bitWidth=${R}, expected ${R}..32)`);let Y=V-R|0;if(Y<1||Y>32)throw new Error(`FastPFOR decode: invalid exceptionBitWidth=${Y} at block=${O} (bitWidth=${R}, maxBits=${V})`);if(L+F>D)throw new Error(`FastPFOR decode: exception positions underflow at block=${O} (need=${F}, have=${D-L})`);return{maxBits:V,exceptionBitWidth:Y,bytePosIn:L}})(s,l,h,i,o,g);if(h=_,v===1){let A=1<M)throw new Error(`FastPFOR decode: exception stream overflow for exceptionBitWidth=${v} (ptr=${I}, need ${o}, size=${M}) at block ${g}`);for(let A=0;Ar.length-1)throw new Error(`FastPFOR decode: invalid whereMeta=${d} at pageStart=${h} (expected > 0 and pageStart+whereMeta < encoded.length=${r.length})`);let g=h+1|0,m=h+d|0,v=r[m]>>>0,_=v+3>>>2,T=m+1,b=T+_;if(b>=r.length)throw new Error(`FastPFOR decode: invalid byteSize=${v} (metaInts=${_}, pageStart=${h}, packedEnd=${m}, byteContainerStart=${T}) causes bitmapPos=${b} out of bounds (encoded.length=${r.length})`);let I=(function(D,L,R,F){F.byteContainer.length>>2;if(3&O.byteOffset)for(let J=0;J>>8&255,O[te+2|0]=re>>>16&255,O[te+3|0]=re>>>24&255}else{let J=F.byteContainerI32;(!J||J.buffer!==O.buffer||J.byteOffset!==O.byteOffset||J.length>>2)),J.set(D.subarray(L,L+V))}let Y=3&R;if(Y>0){let J=0|D[L+V|0],re=V<<2;for(let te=0;te>>(te<<3)&255}return O})(r,T,v,l),M=v,A=(function(D,L,R){let F=0|D[L++],O=R.dataToBePacked;for(let V=2;V<=32;V=V+1|0){if(!(F>>>V-1&1))continue;if(L>=D.length)throw new Error(`FastPFOR decode: truncated exception stream header (bitWidth=${V}, streamWordIndex=${L}, needWords=1, availableWords=${D.length-L}, encodedWords=${D.length})`);let Y=D[L++]>>>0,J=td(Y+31,32),re=Y*V+31>>>5;if(L+re>D.length)throw new Error(`FastPFOR decode: truncated exception stream (bitWidth=${V}, size=${Y}, streamWordIndex=${L}, needWords=${re}, availableWords=${D.length-L}, encodedWords=${D.length})`);let te=O[V];(!te||te.length>>5)|0,R.exceptionSizes[V]=Y}return L})(r,b,l);return l.dataPointers.fill(0),(function(D,L,R,F,O,V,Y,J,re,te){let ae=0|R,le=0;for(let ne=0;ne0&&(le=Xg(O,ye,fe,xe,J,re,le,te,ne))}if(ae!==F)throw new Error(`FastPFOR decode: packed region mismatch (pageStart=${L}, packedStart=${R}, consumedPackedEnd=${ae}, expectedPackedEnd=${F}, packedWords=${F-R}, encoded.length=${D.length})`)})(r,h,g,m,e,0|o,s/Mn|0,I,M,l),A}function Kg(r,e,i,o,s){switch(s){case 2:return void(function(m,v,_,T){let b=T,I=m[v]>>>0,M=m[v+1]>>>0;_[b++]=I>>>0&3,_[b++]=I>>>2&3,_[b++]=I>>>4&3,_[b++]=I>>>6&3,_[b++]=I>>>8&3,_[b++]=I>>>10&3,_[b++]=I>>>12&3,_[b++]=I>>>14&3,_[b++]=I>>>16&3,_[b++]=I>>>18&3,_[b++]=I>>>20&3,_[b++]=I>>>22&3,_[b++]=I>>>24&3,_[b++]=I>>>26&3,_[b++]=I>>>28&3,_[b++]=I>>>30&3,_[b++]=M>>>0&3,_[b++]=M>>>2&3,_[b++]=M>>>4&3,_[b++]=M>>>6&3,_[b++]=M>>>8&3,_[b++]=M>>>10&3,_[b++]=M>>>12&3,_[b++]=M>>>14&3,_[b++]=M>>>16&3,_[b++]=M>>>18&3,_[b++]=M>>>20&3,_[b++]=M>>>22&3,_[b++]=M>>>24&3,_[b++]=M>>>26&3,_[b++]=M>>>28&3,_[b]=M>>>30&3})(r,e,i,o);case 3:return void(function(m,v,_,T){let b=T,I=m[v]>>>0,M=m[v+1]>>>0,A=m[v+2]>>>0;_[b++]=I>>>0&7,_[b++]=I>>>3&7,_[b++]=I>>>6&7,_[b++]=I>>>9&7,_[b++]=I>>>12&7,_[b++]=I>>>15&7,_[b++]=I>>>18&7,_[b++]=I>>>21&7,_[b++]=I>>>24&7,_[b++]=I>>>27&7,_[b++]=7&(I>>>30|(1&M)<<2),_[b++]=M>>>1&7,_[b++]=M>>>4&7,_[b++]=M>>>7&7,_[b++]=M>>>10&7,_[b++]=M>>>13&7,_[b++]=M>>>16&7,_[b++]=M>>>19&7,_[b++]=M>>>22&7,_[b++]=M>>>25&7,_[b++]=M>>>28&7,_[b++]=7&(M>>>31|(3&A)<<1),_[b++]=A>>>2&7,_[b++]=A>>>5&7,_[b++]=A>>>8&7,_[b++]=A>>>11&7,_[b++]=A>>>14&7,_[b++]=A>>>17&7,_[b++]=A>>>20&7,_[b++]=A>>>23&7,_[b++]=A>>>26&7,_[b]=A>>>29&7})(r,e,i,o);case 4:return void(function(m,v,_,T){let b=T,I=m[v]>>>0,M=m[v+1]>>>0,A=m[v+2]>>>0,D=m[v+3]>>>0;_[b++]=I>>>0&15,_[b++]=I>>>4&15,_[b++]=I>>>8&15,_[b++]=I>>>12&15,_[b++]=I>>>16&15,_[b++]=I>>>20&15,_[b++]=I>>>24&15,_[b++]=I>>>28&15,_[b++]=M>>>0&15,_[b++]=M>>>4&15,_[b++]=M>>>8&15,_[b++]=M>>>12&15,_[b++]=M>>>16&15,_[b++]=M>>>20&15,_[b++]=M>>>24&15,_[b++]=M>>>28&15,_[b++]=A>>>0&15,_[b++]=A>>>4&15,_[b++]=A>>>8&15,_[b++]=A>>>12&15,_[b++]=A>>>16&15,_[b++]=A>>>20&15,_[b++]=A>>>24&15,_[b++]=A>>>28&15,_[b++]=D>>>0&15,_[b++]=D>>>4&15,_[b++]=D>>>8&15,_[b++]=D>>>12&15,_[b++]=D>>>16&15,_[b++]=D>>>20&15,_[b++]=D>>>24&15,_[b]=D>>>28&15})(r,e,i,o);case 5:return void(function(m,v,_,T){let b=T,I=m[v]>>>0,M=m[v+1]>>>0,A=m[v+2]>>>0,D=m[v+3]>>>0,L=m[v+4]>>>0;_[b++]=I>>>0&31,_[b++]=I>>>5&31,_[b++]=I>>>10&31,_[b++]=I>>>15&31,_[b++]=I>>>20&31,_[b++]=I>>>25&31,_[b++]=31&(I>>>30|(7&M)<<2),_[b++]=M>>>3&31,_[b++]=M>>>8&31,_[b++]=M>>>13&31,_[b++]=M>>>18&31,_[b++]=M>>>23&31,_[b++]=31&(M>>>28|(1&A)<<4),_[b++]=A>>>1&31,_[b++]=A>>>6&31,_[b++]=A>>>11&31,_[b++]=A>>>16&31,_[b++]=A>>>21&31,_[b++]=A>>>26&31,_[b++]=31&(A>>>31|(15&D)<<1),_[b++]=D>>>4&31,_[b++]=D>>>9&31,_[b++]=D>>>14&31,_[b++]=D>>>19&31,_[b++]=D>>>24&31,_[b++]=31&(D>>>29|(3&L)<<3),_[b++]=L>>>2&31,_[b++]=L>>>7&31,_[b++]=L>>>12&31,_[b++]=L>>>17&31,_[b++]=L>>>22&31,_[b]=L>>>27&31})(r,e,i,o);case 6:return void(function(m,v,_,T){let b=T,I=m[v]>>>0,M=m[v+1]>>>0,A=m[v+2]>>>0,D=m[v+3]>>>0,L=m[v+4]>>>0,R=m[v+5]>>>0;_[b++]=I>>>0&63,_[b++]=I>>>6&63,_[b++]=I>>>12&63,_[b++]=I>>>18&63,_[b++]=I>>>24&63,_[b++]=63&(I>>>30|(15&M)<<2),_[b++]=M>>>4&63,_[b++]=M>>>10&63,_[b++]=M>>>16&63,_[b++]=M>>>22&63,_[b++]=63&(M>>>28|(3&A)<<4),_[b++]=A>>>2&63,_[b++]=A>>>8&63,_[b++]=A>>>14&63,_[b++]=A>>>20&63,_[b++]=A>>>26&63,_[b++]=D>>>0&63,_[b++]=D>>>6&63,_[b++]=D>>>12&63,_[b++]=D>>>18&63,_[b++]=D>>>24&63,_[b++]=63&(D>>>30|(15&L)<<2),_[b++]=L>>>4&63,_[b++]=L>>>10&63,_[b++]=L>>>16&63,_[b++]=L>>>22&63,_[b++]=63&(L>>>28|(3&R)<<4),_[b++]=R>>>2&63,_[b++]=R>>>8&63,_[b++]=R>>>14&63,_[b++]=R>>>20&63,_[b]=R>>>26&63})(r,e,i,o);case 7:return void(function(m,v,_,T){let b=T,I=m[v]>>>0,M=m[v+1]>>>0,A=m[v+2]>>>0,D=m[v+3]>>>0,L=m[v+4]>>>0,R=m[v+5]>>>0,F=m[v+6]>>>0;_[b++]=I>>>0&127,_[b++]=I>>>7&127,_[b++]=I>>>14&127,_[b++]=I>>>21&127,_[b++]=127&(I>>>28|(7&M)<<4),_[b++]=M>>>3&127,_[b++]=M>>>10&127,_[b++]=M>>>17&127,_[b++]=M>>>24&127,_[b++]=127&(M>>>31|(63&A)<<1),_[b++]=A>>>6&127,_[b++]=A>>>13&127,_[b++]=A>>>20&127,_[b++]=127&(A>>>27|(3&D)<<5),_[b++]=D>>>2&127,_[b++]=D>>>9&127,_[b++]=D>>>16&127,_[b++]=D>>>23&127,_[b++]=127&(D>>>30|(31&L)<<2),_[b++]=L>>>5&127,_[b++]=L>>>12&127,_[b++]=L>>>19&127,_[b++]=127&(L>>>26|(1&R)<<6),_[b++]=R>>>1&127,_[b++]=R>>>8&127,_[b++]=R>>>15&127,_[b++]=R>>>22&127,_[b++]=127&(R>>>29|(15&F)<<3),_[b++]=F>>>4&127,_[b++]=F>>>11&127,_[b++]=F>>>18&127,_[b]=F>>>25&127})(r,e,i,o);case 8:return void(function(m,v,_,T){let b=T,I=m[v]>>>0,M=m[v+1]>>>0,A=m[v+2]>>>0,D=m[v+3]>>>0,L=m[v+4]>>>0,R=m[v+5]>>>0,F=m[v+6]>>>0,O=m[v+7]>>>0;_[b++]=I>>>0&255,_[b++]=I>>>8&255,_[b++]=I>>>16&255,_[b++]=I>>>24&255,_[b++]=M>>>0&255,_[b++]=M>>>8&255,_[b++]=M>>>16&255,_[b++]=M>>>24&255,_[b++]=A>>>0&255,_[b++]=A>>>8&255,_[b++]=A>>>16&255,_[b++]=A>>>24&255,_[b++]=D>>>0&255,_[b++]=D>>>8&255,_[b++]=D>>>16&255,_[b++]=D>>>24&255,_[b++]=L>>>0&255,_[b++]=L>>>8&255,_[b++]=L>>>16&255,_[b++]=L>>>24&255,_[b++]=R>>>0&255,_[b++]=R>>>8&255,_[b++]=R>>>16&255,_[b++]=R>>>24&255,_[b++]=F>>>0&255,_[b++]=F>>>8&255,_[b++]=F>>>16&255,_[b++]=F>>>24&255,_[b++]=O>>>0&255,_[b++]=O>>>8&255,_[b++]=O>>>16&255,_[b]=O>>>24&255})(r,e,i,o);case 9:return void(function(m,v,_,T){let b=T,I=m[v]>>>0,M=m[v+1]>>>0,A=m[v+2]>>>0,D=m[v+3]>>>0,L=m[v+4]>>>0,R=m[v+5]>>>0,F=m[v+6]>>>0,O=m[v+7]>>>0,V=m[v+8]>>>0;_[b++]=I>>>0&511,_[b++]=I>>>9&511,_[b++]=I>>>18&511,_[b++]=511&(I>>>27|(15&M)<<5),_[b++]=M>>>4&511,_[b++]=M>>>13&511,_[b++]=M>>>22&511,_[b++]=511&(M>>>31|(255&A)<<1),_[b++]=A>>>8&511,_[b++]=A>>>17&511,_[b++]=511&(A>>>26|(7&D)<<6),_[b++]=D>>>3&511,_[b++]=D>>>12&511,_[b++]=D>>>21&511,_[b++]=511&(D>>>30|(127&L)<<2),_[b++]=L>>>7&511,_[b++]=L>>>16&511,_[b++]=511&(L>>>25|(3&R)<<7),_[b++]=R>>>2&511,_[b++]=R>>>11&511,_[b++]=R>>>20&511,_[b++]=511&(R>>>29|(63&F)<<3),_[b++]=F>>>6&511,_[b++]=F>>>15&511,_[b++]=511&(F>>>24|(1&O)<<8),_[b++]=O>>>1&511,_[b++]=O>>>10&511,_[b++]=O>>>19&511,_[b++]=511&(O>>>28|(31&V)<<4),_[b++]=V>>>5&511,_[b++]=V>>>14&511,_[b]=V>>>23&511})(r,e,i,o);case 10:return void(function(m,v,_,T){let b=T,I=m[v]>>>0,M=m[v+1]>>>0,A=m[v+2]>>>0,D=m[v+3]>>>0,L=m[v+4]>>>0,R=m[v+5]>>>0,F=m[v+6]>>>0,O=m[v+7]>>>0,V=m[v+8]>>>0,Y=m[v+9]>>>0;_[b++]=I>>>0&1023,_[b++]=I>>>10&1023,_[b++]=I>>>20&1023,_[b++]=1023&(I>>>30|(255&M)<<2),_[b++]=M>>>8&1023,_[b++]=M>>>18&1023,_[b++]=1023&(M>>>28|(63&A)<<4),_[b++]=A>>>6&1023,_[b++]=A>>>16&1023,_[b++]=1023&(A>>>26|(15&D)<<6),_[b++]=D>>>4&1023,_[b++]=D>>>14&1023,_[b++]=1023&(D>>>24|(3&L)<<8),_[b++]=L>>>2&1023,_[b++]=L>>>12&1023,_[b++]=L>>>22&1023,_[b++]=R>>>0&1023,_[b++]=R>>>10&1023,_[b++]=R>>>20&1023,_[b++]=1023&(R>>>30|(255&F)<<2),_[b++]=F>>>8&1023,_[b++]=F>>>18&1023,_[b++]=1023&(F>>>28|(63&O)<<4),_[b++]=O>>>6&1023,_[b++]=O>>>16&1023,_[b++]=1023&(O>>>26|(15&V)<<6),_[b++]=V>>>4&1023,_[b++]=V>>>14&1023,_[b++]=1023&(V>>>24|(3&Y)<<8),_[b++]=Y>>>2&1023,_[b++]=Y>>>12&1023,_[b]=Y>>>22&1023})(r,e,i,o);case 11:return void(function(m,v,_,T){let b=T,I=m[v]>>>0,M=m[v+1]>>>0,A=m[v+2]>>>0,D=m[v+3]>>>0,L=m[v+4]>>>0,R=m[v+5]>>>0,F=m[v+6]>>>0,O=m[v+7]>>>0,V=m[v+8]>>>0,Y=m[v+9]>>>0,J=m[v+10]>>>0;_[b++]=I>>>0&2047,_[b++]=I>>>11&2047,_[b++]=2047&(I>>>22|(1&M)<<10),_[b++]=M>>>1&2047,_[b++]=M>>>12&2047,_[b++]=2047&(M>>>23|(3&A)<<9),_[b++]=A>>>2&2047,_[b++]=A>>>13&2047,_[b++]=2047&(A>>>24|(7&D)<<8),_[b++]=D>>>3&2047,_[b++]=D>>>14&2047,_[b++]=2047&(D>>>25|(15&L)<<7),_[b++]=L>>>4&2047,_[b++]=L>>>15&2047,_[b++]=2047&(L>>>26|(31&R)<<6),_[b++]=R>>>5&2047,_[b++]=R>>>16&2047,_[b++]=2047&(R>>>27|(63&F)<<5),_[b++]=F>>>6&2047,_[b++]=F>>>17&2047,_[b++]=2047&(F>>>28|(127&O)<<4),_[b++]=O>>>7&2047,_[b++]=O>>>18&2047,_[b++]=2047&(O>>>29|(255&V)<<3),_[b++]=V>>>8&2047,_[b++]=V>>>19&2047,_[b++]=2047&(V>>>30|(511&Y)<<2),_[b++]=Y>>>9&2047,_[b++]=Y>>>20&2047,_[b++]=2047&(Y>>>31|(1023&J)<<1),_[b++]=J>>>10&2047,_[b]=J>>>21&2047})(r,e,i,o);case 12:return void(function(m,v,_,T){let b=T,I=m[v]>>>0,M=m[v+1]>>>0,A=m[v+2]>>>0,D=m[v+3]>>>0,L=m[v+4]>>>0,R=m[v+5]>>>0,F=m[v+6]>>>0,O=m[v+7]>>>0,V=m[v+8]>>>0,Y=m[v+9]>>>0,J=m[v+10]>>>0,re=m[v+11]>>>0;_[b++]=I>>>0&4095,_[b++]=I>>>12&4095,_[b++]=4095&(I>>>24|(15&M)<<8),_[b++]=M>>>4&4095,_[b++]=M>>>16&4095,_[b++]=4095&(M>>>28|(255&A)<<4),_[b++]=A>>>8&4095,_[b++]=A>>>20&4095,_[b++]=D>>>0&4095,_[b++]=D>>>12&4095,_[b++]=4095&(D>>>24|(15&L)<<8),_[b++]=L>>>4&4095,_[b++]=L>>>16&4095,_[b++]=4095&(L>>>28|(255&R)<<4),_[b++]=R>>>8&4095,_[b++]=R>>>20&4095,_[b++]=F>>>0&4095,_[b++]=F>>>12&4095,_[b++]=4095&(F>>>24|(15&O)<<8),_[b++]=O>>>4&4095,_[b++]=O>>>16&4095,_[b++]=4095&(O>>>28|(255&V)<<4),_[b++]=V>>>8&4095,_[b++]=V>>>20&4095,_[b++]=Y>>>0&4095,_[b++]=Y>>>12&4095,_[b++]=4095&(Y>>>24|(15&J)<<8),_[b++]=J>>>4&4095,_[b++]=J>>>16&4095,_[b++]=4095&(J>>>28|(255&re)<<4),_[b++]=re>>>8&4095,_[b]=re>>>20&4095})(r,e,i,o);case 16:return void(function(m,v,_,T){let b=T,I=m[v]>>>0,M=m[v+1]>>>0,A=m[v+2]>>>0,D=m[v+3]>>>0,L=m[v+4]>>>0,R=m[v+5]>>>0,F=m[v+6]>>>0,O=m[v+7]>>>0,V=m[v+8]>>>0,Y=m[v+9]>>>0,J=m[v+10]>>>0,re=m[v+11]>>>0,te=m[v+12]>>>0,ae=m[v+13]>>>0,le=m[v+14]>>>0,ne=m[v+15]>>>0;_[b++]=I>>>0&65535,_[b++]=I>>>16&65535,_[b++]=M>>>0&65535,_[b++]=M>>>16&65535,_[b++]=A>>>0&65535,_[b++]=A>>>16&65535,_[b++]=D>>>0&65535,_[b++]=D>>>16&65535,_[b++]=L>>>0&65535,_[b++]=L>>>16&65535,_[b++]=R>>>0&65535,_[b++]=R>>>16&65535,_[b++]=F>>>0&65535,_[b++]=F>>>16&65535,_[b++]=O>>>0&65535,_[b++]=O>>>16&65535,_[b++]=V>>>0&65535,_[b++]=V>>>16&65535,_[b++]=Y>>>0&65535,_[b++]=Y>>>16&65535,_[b++]=J>>>0&65535,_[b++]=J>>>16&65535,_[b++]=re>>>0&65535,_[b++]=re>>>16&65535,_[b++]=te>>>0&65535,_[b++]=te>>>16&65535,_[b++]=ae>>>0&65535,_[b++]=ae>>>16&65535,_[b++]=le>>>0&65535,_[b++]=le>>>16&65535,_[b++]=ne>>>0&65535,_[b]=ne>>>16&65535})(r,e,i,o);case 32:for(let m=0;m<32;m=m+1|0)i[o+m|0]=0|r[e+m|0];return}let l=ed[s]>>>0,h=e,d=0,g=r[h]>>>0;for(let m=0;m<32;m++)if(d+s<=32)i[o+m]=g>>>d&l,d+=s,d===32&&(d=0,h++,m!==31&&(g=r[h]>>>0));else{let v=32-d,_=g>>>d;h++,g=r[h]>>>0,i[o+m]=(_|(g&ed[s-v]>>>0)<=64)throw new Error("Varint too long")}return e.set(s),i}function Qg(r,e){let i,o;return o=r[e.get()],e.increment(),i=127&o,o<128?i:(o=r[e.get()],e.increment(),i|=(127&o)<<7,o<128?i:(o=r[e.get()],e.increment(),i|=(127&o)<<14,o<128?i:(o=r[e.get()],e.increment(),i|=(127&o)<<21,o<128?i:(o=r[e.get()],i|=(15&o)<<28,(function(s,l,h){let d,g;if(g=l[h.get()],h.increment(),d=(112&g)>>4,g<128||(g=l[h.get()],h.increment(),d|=(127&g)<<3,g<128)||(g=l[h.get()],h.increment(),d|=(127&g)<<10,g<128)||(g=l[h.get()],h.increment(),d|=(127&g)<<17,g<128)||(g=l[h.get()],h.increment(),d|=(127&g)<<24,g<128)||(g=l[h.get()],h.increment(),d|=(1&g)<<31,g<128))return 4294967296*d+(s>>>0);throw new Error("Expected varint not more than 10 bytes")})(i,r,e)))))}function st(r){return r>>>1^-(1&r)}function Ti(r){return r>>1n^-(1n&r)}function ba(r){return r%2==1?(r+1)/-2:r/2}function rd(r,e,i){if(i===void 0){i=0;for(let l=0;l=4)for(;o=4)for(;o=4)for(let o=r[0];i>4],d=null;switch(h){case ni.DATA:d={dictionaryType:Object.values(xr)[15&l]};break;case ni.OFFSET:d={offsetType:Object.values(as)[15&l]};break;case ni.LENGTH:d={lengthType:Object.values(Zi)[15&l]}}s.increment();let g=o[s.get()],m=Object.values(Ge)[g>>5],v=Object.values(Ge)[g>>2&7],_=Object.values(ho)[3&g];s.increment();let T=fi(o,s,2),b=T[0];return{physicalStreamType:h,logicalStreamType:d,logicalLevelTechnique1:m,logicalLevelTechnique2:v,physicalLevelTechnique:_,numValues:b,byteLength:T[1],decompressedCount:b}})(r,e);return i.logicalLevelTechnique1===Ge.MORTON?(function(o,s,l){let h=fi(s,l,2);return{physicalStreamType:o.physicalStreamType,logicalStreamType:o.logicalStreamType,logicalLevelTechnique1:o.logicalLevelTechnique1,logicalLevelTechnique2:o.logicalLevelTechnique2,physicalLevelTechnique:o.physicalLevelTechnique,numValues:o.numValues,byteLength:o.byteLength,decompressedCount:o.decompressedCount,numBits:h[0],coordinateShift:h[1]}})(i,r,e):Ge.RLE!==i.logicalLevelTechnique1&&Ge.RLE!==i.logicalLevelTechnique2||ho.NONE===i.physicalLevelTechnique?i:(function(o,s,l){let h=fi(s,l,2);return{physicalStreamType:o.physicalStreamType,logicalStreamType:o.logicalStreamType,logicalLevelTechnique1:o.logicalLevelTechnique1,logicalLevelTechnique2:o.logicalLevelTechnique2,physicalLevelTechnique:o.physicalLevelTechnique,numValues:o.numValues,byteLength:o.byteLength,decompressedCount:h[1],runs:h[0],numRleValues:h[1]}})(i,r,e)}(function(r){r.PRESENT="PRESENT",r.DATA="DATA",r.OFFSET="OFFSET",r.LENGTH="LENGTH"})(ni||(ni={})),(function(r){r.NONE="NONE",r.SINGLE="SINGLE",r.SHARED="SHARED",r.VERTEX="VERTEX",r.MORTON="MORTON",r.FSST="FSST"})(xr||(xr={})),(function(r){r.VERTEX="VERTEX",r.INDEX="INDEX",r.STRING="STRING",r.KEY="KEY"})(as||(as={})),(function(r){r.VAR_BINARY="VAR_BINARY",r.GEOMETRIES="GEOMETRIES",r.PARTS="PARTS",r.RINGS="RINGS",r.TRIANGLES="TRIANGLES",r.SYMBOL="SYMBOL",r.DICTIONARY="DICTIONARY"})(Zi||(Zi={})),(function(r){r[r.FLAT=0]="FLAT",r[r.CONST=1]="CONST",r[r.SEQUENCE=2]="SEQUENCE",r[r.DICTIONARY=3]="DICTIONARY",r[r.FSST_DICTIONARY=4]="FSST_DICTIONARY"})(dt||(dt={}));class br{constructor(e,i){this.values=e,this._size=i}get(e){let i=Math.floor(e/8);return(this.values[i]>>e%8&1)==1}set(e,i){let o=Math.floor(e/8);this.values[o]=this.values[o]|(i?1:0)<>e%8&1}size(){return this._size}getBuffer(){return this.values}}function wa(r,e,i){if(!e)return r;let o=e.size(),s=new r.constructor(o),l=0;for(let h=0;h=4)for(;b>>0;for(let T=1;T>>0;return _})(h.logicalLevelTechnique2===Ge.RLE?rd(l,h.runs,h.numRleValues):l);break;case Ge.RLE:m=rd(l,h.runs,h.numRleValues);break;case Ge.MORTON:od(l),m=l;break;case Ge.COMPONENTWISE_DELTA:m=(function(v){if(v.length<2)return new Uint32Array(v);let _=new Uint32Array(v.length);_[0]=st(v[0])>>>0,_[1]=st(v[1])>>>0;for(let T=2;T>>0,_[T+1]=_[T-1]+st(v[T+1])>>>0;return _})(l);break;case Ge.NONE:m=l;break;default:throw new Error(`The specified Logical level technique is not supported: ${h.logicalLevelTechnique1}`)}return g?wa(m,g,0):m})(Ta(r,e,i),i,0,s)}function po(r,e,i){return(function(o,s){if(s.logicalLevelTechnique1===Ge.DELTA&&s.logicalLevelTechnique2===Ge.NONE)return(function(l){let h=new Int32Array(l.length+1);h[0]=0,h[1]=st(l[0]);let d=h[1];for(let g=2;g!==h.length;++g)d+=st(l[g-1]),h[g]=h[g-1]+d;return new Uint32Array(h)})(o);if(s.logicalLevelTechnique1===Ge.RLE&&s.logicalLevelTechnique2===Ge.NONE)return(function(l,h,d){let g=new Uint32Array(d+1);g[0]=0;let m=1,v=g[0];for(let _=0;_>>2,M=(function(D,L){if(L<=D.encodedWords.length)return D.encodedWords;let R=new Uint32Array(Math.max(16,2*L));return D.encodedWords=R,R})(T,I);(function(D,L,R,F){if(L<0||R<0||L+R>D.length)throw new RangeError(`decodeBigEndianInt32sInto: out of bounds (offset=${L}, byteLength=${R}, bytes.length=${D.length})`);let O=Math.floor(R/4),V=R%4!=0,Y=V?O+1:O;if(F.length0){let J=D.byteOffset+L;if(3&J)for(let re=0;re0){let J=0|D[F];if(F=F+1|0,255&J)throw new Error(`FastPFOR decode: invalid alignedLength=${J} (expected multiple of 256)`);if(O+J>V.length)throw new Error(`FastPFOR decode: output buffer too small (outPos=${O}, alignedLength=${J}, out.length=${V.length})`);F=(function(re,te,ae,le,ne,ie){let fe=le+td(ne,Mn),xe=le,ye=ae;for(;xe!==fe;){let me=Math.min(id,fe-xe);ye=Yg(re,te,ye,xe,me,ie),xe=xe+me|0}return ye})(D,V,F,O,J,Y),O=O+J|0}return(function(J,re,te,ae,le,ne){if(ne===0)return re;let ie=0,fe=re,xe=re+te,ye=le,me=le,Ae=le+ne,Ye=0,Je=0;for(;fe>>ie&255;if(ie+=8,fe+=ie>>>5,ie&=31,Ye|=(127&nt)<28)throw new Error(`FastPFOR VByte: unterminated value (expected MSB=1 terminator within 5 bytes; shift=${Je}, partial=${Ye}, decoded=${me-ye}/${ne}, inPos=${fe}, inEnd=${xe})`)}if(me!==Ae)throw new Error(`FastPFOR VByte: truncated stream (decoded=${me-ye}, expected=${ne}, consumedWords=${fe-re}/${te}, vbyteStart=${re}, vbyteEnd=${xe})`)})(D,F,D.length-F|0,V,O,L-O|0),V})(M.subarray(0,I),m,T.decoderWorkspace);return _.add(v),A})(s,l,h,d,(function(g=16){if(g<0)throw new RangeError(`initialEncodedWordCapacity must be >= 0, got ${g}`);let m=Math.max(16,0|g);return{encodedWords:new Uint32Array(m),decoderWorkspace:qp()}})(h>>>2))})(r,i.numValues,i.byteLength,e);case ho.VARINT:return fi(r,e,i.numValues);case ho.NONE:{let s=e.get();e.add(i.byteLength);let l=r.subarray(s,e.get());return new Uint32Array(l)}default:throw new Error(`Specified physicalLevelTechnique ${o} is not supported (yet).`)}}function ad(r,e,i){let o=Ta(r,e,i);return o.length===1?o[0]:(function(s){return s[1]})(o)}function Kp(r,e,i){return(function(o){if(o.length===2){let s=st(o[1]);return[s,s]}return[st(o[2]),st(o[3])]})(Ta(r,e,i))}function Jp(r,e,i){return(function(o){if(o.length===2){let s=Ti(o[1]);return[s,s]}return[Ti(o[2]),Ti(o[3])]})(xa(r,e,i.numValues))}function Qp(r,e,i,o){return(function(s,l,h){let d;switch(l.logicalLevelTechnique1){case Ge.DELTA:d=(function(g){let m=new BigUint64Array(g.length);m[0]=BigInt.asUintN(64,Ti(g[0]));for(let v=1;v>1,e)-i}}function nf(r,e){let i=0;for(let o=0;o>o;return i}function Pa(r,e,i,o,s,l,h){return r===uo.MORTON?(function(d,g,m,v,_,T){let b=new Array(_?v+1:v);for(let I=0;I[O])),o+=R,s+=R}break;case jt.LINESTRING:{let R,F;A?(R=b[s]-b[s-1],s++):R=T[o]-T[o-1],o++,M?(F=Sa(D,d,R,!1),d+=2*R):(F=Pa(e.vertexBufferType,D,I,g,R,!1,m),g+=R),i[h++]=[F],_&&l++}break;case jt.POLYGON:{let R=T[o]-T[o-1];o++;let F=new Array(R-1),O,V=b[s]-b[s-1];if(s++,M){O=Sa(D,d,V,!0),d+=2*V;for(let Y=0;Y0&&M.push(M[0]),T.push(M)}e[v]=T,l&&m++}break;case jt.MULTIPOLYGON:{let _=l[m]-l[m-1];m++;let T=[];for(let b=0;b<_;b++){let I=o[d]-o[d-1];d++;for(let M=0;M0&&D.push(D[0]),T.push(D)}}e[v]=T}}return e}[Symbol.iterator](){return null}}function cf(r,e,i,o,s,l){return new e_(r,e,i,o,s,l)}class e_ extends lf{constructor(e,i,o,s,l,h){super(o,s,l,h),this._numGeometries=e,this._geometryType=i}geometryType(e){return this._geometryType}get numGeometries(){return this._numGeometries}containsSingleGeometryType(){return!0}}function hf(r,e,i,o,s){return new t_(r,e,i,o,s)}class t_ extends lf{constructor(e,i,o,s,l){super(i,o,s,l),this._geometryTypes=e}geometryType(e){return this._geometryTypes[e]}get numGeometries(){return this._geometryTypes.length}containsSingleGeometryType(){return!1}}function i_(r,e,i,o,s){let l=Pi(r,i),h,d,g,m;if(Mh(l,o,r,i)===dt.CONST){let L=ad(r,i,l),R,F,O,V;for(let Y=0;Yi?e[l++]:1);return o}function uf(r,e,i,o){let s=new Uint32Array(e[e.length-1]+1),l=0;s[0]=l;let h=1,d=0;for(let g=0;g=T);){let b=h[m.increment()];if(b<=127){let I=b+3,M=h[m.increment()],A=Math.min(_+I,d);v.fill(M,_,A),_=A}else{let I=256-b;for(let M=0;M=12?o_.decode(r.subarray(e,i)):(function(o,s,l){let h="",d=s;for(;d239?4:g>223?3:g>191?2:1;if(d+b>l)break;b===1?g<128&&(T=g):b===2?(m=o[d+1],(192&m)==128&&(T=(31&g)<<6|63&m,T<=127&&(T=null))):b===3?(m=o[d+1],v=o[d+2],(192&m)==128&&(192&v)==128&&(T=(15&g)<<12|(63&m)<<6|63&v,(T<=2047||T>=55296&&T<=57343)&&(T=null))):b===4&&(m=o[d+1],v=o[d+2],_=o[d+3],(192&m)==128&&(192&v)==128&&(192&_)==128&&(T=(15&g)<<18|(63&m)<<12|(63&v)<<6|63&_,(T<=65535||T>=1114112)&&(T=null))),T===null?(T=65533,b=1):T>65535&&(T-=65536,h+=String.fromCharCode(T>>>10&1023|55296),T=56320|1023&T),h+=String.fromCharCode(T),d+=b}return h})(r,e,i)}class ud extends va{constructor(e,i,o,s){super(e,o,s),this.offsetBuffer=i}}class pf extends ud{constructor(e,i,o,s){super(e,i,o,s??i.length-1)}getValueFromBuffer(e){return hd(this.dataBuffer,this.offsetBuffer[e],this.offsetBuffer[e+1])}}class Ia extends ud{constructor(e,i,o,s,l){super(e,o,s,l??i.length),this.indexBuffer=i,this.indexBuffer=i}getValueFromBuffer(e){let i=this.indexBuffer[e];return hd(this.dataBuffer,this.offsetBuffer[i],this.offsetBuffer[i+1])}}class ff extends ud{constructor(e,i,o,s,l,h,d){super(e,o,s,d),this.indexBuffer=i,this.symbolOffsetBuffer=l,this.symbolTableBuffer=h}getValueFromBuffer(e){this.decodedDictionary==null&&(this.symbolLengthBuffer==null&&(this.symbolLengthBuffer=this.offsetToLengthBuffer(this.symbolOffsetBuffer)),this.decodedDictionary=(function(o,s,l){let h=[],d=new Array(s.length).fill(0);for(let g=1;g=10}function _f(r){return r===30}function a_(r){if(r.type==="scalarType"){let e=r.scalarType;if(e.type==="physicalType")switch(e.physicalType){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:default:return!1;case 9:return!0}if(e.type==="logicalType")return!1}else if(r.type==="complexType"){let e=r.complexType;if(e.type==="physicalType")switch(e.physicalType){case 0:case 1:return!0;default:return!1}}return console.warn("Unexpected column type in hasStreamCount",r),!1}function l_(r){return r.type==="complexType"&&r.complexType?.type==="physicalType"&&r.complexType.physicalType===0}let c_=new TextDecoder;function dd(r,e){let i=fi(r,e,1)[0];if(i===0)return"";let o=e.get(),s=r.subarray(o,o+i);return e.add(i),c_.decode(s)}function yf(r,e){let i=fi(r,e,1)[0]>>>0;if(i<10||i>30)throw new Error(`Unsupported field type code ${i}. Supported: 10-29(scalars), 30(STRUCT)`);let o=mf(i);if(gf(i)&&(o.name=dd(r,e)),_f(i)){let s=fi(r,e,1)[0]>>>0;o.complexType.children=new Array(s);for(let l=0;l>>0,o=mf(i);if(!o)throw new Error(`Unsupported column type code ${i}. Supported: 0-3(ID), 4(GEOMETRY), 10-29(scalars), 30(STRUCT)`);if(gf(i)?o.name=dd(r,e):i>=0&&i<=3?o.name="id":i===4&&(o.name="geometry"),_f(i)){let s=fi(r,e,1)[0]>>>0,l=o.complexType;l.children=new Array(s);for(let h=0;h>>0,l=fi(r,e,1)[0]>>>0;o.columns=new Array(l);for(let h=0;h=4)for(;O>>0,v=h.get()+m;if(v>o.length)throw new Error(`Block overruns tile: ${v} > ${o.length}`);if(fi(o,h,1)[0]>>>0!=1){h.set(v);continue}let[_,T]=u_(o,h),b=_.featureTables[0],I=null,M=null,A=[],D=0;for(let R of b.columns){let F=R.name;if((g=R).type==="scalarType"&&g.scalarType?.type==="logicalType"&&g.scalarType.logicalType===0){let O=null;if(R.nullable){let Y=Pi(o,h),J=h.get(),re=Ql(o,Y.numValues,Y.byteLength,h);h.set(J+Y.byteLength),O=new br(re,Y.numValues)}let V=Pi(o,h);D=O?O.size():V.decompressedCount,I=d_(o,R,h,F,V,O??D,l)}else if(l_(R)){let O=fi(o,h,1)[0];if(D===0){let V=h.get();D=Pi(o,h).decompressedCount,h.set(V)}M=i_(o,O,h,D)}else{let O=a_(R)?fi(o,h,1)[0]:1;if(O===0)continue;let V=s_(o,h,R,O,D);if(V)if(Array.isArray(V))for(let Y of V)A.push(Y);else A.push(V)}}let L=new $g(b.name,M,I,A,T);d.push(L),h.set(v)}var g;return d})(new Uint8Array(e));this.layers=i.reduce(((o,s)=>Object.assign(Object.assign({},o),{[s.name]:new f_(s)})),{})}}class m_{constructor(e,i){this.feature=e,this.type=e.type,this.properties=e.tags?e.tags:{},this.extent=i,"id"in e&&(typeof e.id=="string"?this.id=parseInt(e.id,10):typeof e.id!="number"||isNaN(e.id)||(this.id=e.id))}loadGeometry(){let e=[],i=this.feature.type===1?[this.feature.geometry]:this.feature.geometry;for(let o of i){let s=[];for(let l of o)s.push(new Te(l[0],l[1]));e.push(s)}return e}}let tc="_geojsonTileLayer";function g_(r,e,i=""){e.writeVarintField(15,r.version||1),e.writeStringField(1,r.name||""),e.writeVarintField(5,r.extent||4096);let o={jsonPrefix:i,keys:[],values:[],keycache:{},valuecache:{}};for(let h=0;h>31}function v_(r,e){let i=r.loadGeometry(),o=r.type,s=0,l=0;for(let h of i){let d=1;o===1&&(d=h.length),e.writeVarint(pd(1,d));let g=o===3?h.length-1:h.length;for(let m=0;m=0&&v[3]>=0&&g.insert(d,v[0],v[1],v[2],v[3])}}loadVTLayers(){return this.vtLayers||(this.vtLayers=this.encoding!=="mlt"?new Wd(new bh(this.rawTileData)).layers:new vf(this.rawTileData).layers,this.sourceLayerCoder=new Up(this.vtLayers?Object.keys(this.vtLayers).sort():[tc])),this.vtLayers}query(e,i,o,s){this.loadVTLayers();let l=e.params,h=De/e.tileSize/e.scale,d=No(l.filter,l.globalState),g=e.queryGeometry,m=e.queryPadding*h,v=ss.fromPoints(g),_=this.grid.query(v.minX-m,v.minY-m,v.maxX+m,v.maxY+m),T=ss.fromPoints(e.cameraQueryGeometry).expandBy(m),b=this.grid3D.query(T.minX,T.minY,T.maxX,T.maxY,((A,D,L,R)=>(function(F,O,V,Y,J){for(let te of F)if(O<=te.x&&V<=te.y&&Y>=te.x&&J>=te.y)return!0;let re=[new Te(O,V),new Te(O,J),new Te(Y,J),new Te(Y,V)];if(F.length>2){for(let te of re)if(aa(F,te))return!0}for(let te=0;te(L||(L=$r(R)),F.queryIntersectsFeature({queryGeometry:g,feature:R,featureState:O,geometry:L,zoom:this.z,transform:e.transform,pixelsToTileUnits:h,pixelPosMatrix:e.pixelPosMatrix,unwrappedTileID:this.tileID.toUnwrapped(),getElevation:e.getElevation}))))}return I}loadMatchingFeature(e,i,o,s,l,h,d,g,m,v,_){let T=this.bucketLayerIDs[i];if(h&&!T.some((A=>h.has(A))))return;let b=this.sourceLayerCoder.decode(o),I=this.vtLayers[b].feature(s);if(l.needGeometry){let A=Zr(I,!0);if(!l.filter(new ct(this.tileID.overscaledZ),A,this.tileID.canonical))return}else if(!l.filter(new ct(this.tileID.overscaledZ),I))return;let M=this.getId(I,b);for(let A of T){if(h&&!h.has(A))continue;let D=g[A];if(!D)continue;let L={};M&&v&&(L=v.getState(D.sourceLayer||tc,M));let R=Oi({},m[A]);R.paint=wf(R.paint,D.paint,I,L,d),R.layout=wf(R.layout,D.layout,I,L,d);let F=!_||_(I,D,L);if(!F)continue;let O=new Gp(I,this.z,this.x,this.y,M);O.layer=R;let V=e[A];V===void 0&&(V=e[A]=[]),V.push({featureIndex:s,feature:O,intersectionZ:F})}}lookupSymbolFeatures(e,i,o,s,l,h,d,g){let m={};this.loadVTLayers();let v=No(l.filterSpec,l.globalState);for(let _ of e)this.loadMatchingFeature(m,o,s,_,v,h,d,g,i);return m}hasLayer(e){for(let i of this.bucketLayerIDs)for(let o of i)if(e===o)return!0;return!1}getId(e,i){var o;let s=e.id;return this.promoteId&&(s=e.properties[typeof this.promoteId=="string"?this.promoteId:this.promoteId[i]],typeof s=="boolean"&&(s=Number(s)),s===void 0&&(!((o=e.properties)===null||o===void 0)&&o.cluster)&&this.promoteId&&(s=Number(e.properties.cluster_id))),s}}function wf(r,e,i,o,s){return Er(r,((l,h)=>{let d=e instanceof Ko?e.get(h):null;return d?.evaluate?d.evaluate(i,o,s):d}))}function b_(r,e){return e-r}function Tf(r,e,i,o,s){let l=[];for(let h of r){let d;for(let g=0;g=o&&v.x>=o||(m.x>=o?m=new Te(o,m.y+(o-m.x)/(v.x-m.x)*(v.y-m.y))._round():v.x>=o&&(v=new Te(o,m.y+(o-m.x)/(v.x-m.x)*(v.y-m.y))._round()),m.y>=s&&v.y>=s||(m.y>=s?m=new Te(m.x+(s-m.y)/(v.y-m.y)*(v.x-m.x),s)._round():v.y>=s&&(v=new Te(m.x+(s-m.y)/(v.y-m.y)*(v.x-m.x),s)._round()),d&&m.equals(d[d.length-1])||(d=[m],l.push(d)),d.push(v)))))}}return l}function Pf(r,e,i,o,s){switch(e){case 1:return(function(l,h,d,g){let m=[];for(let v of l)for(let _ of v){let T=g===0?_.x:_.y;T>=h&&T<=d&&m.push([_])}return m})(r,i,o,s);case 2:return Sf(r,i,o,s,!1);case 3:return Sf(r,i,o,s,!0)}return[]}function w_(r,e,i,o,s){let l=o===0?T_:P_,h=[],d=[];for(let v=0;ve&&h.push(l(_,T,e)):b>i?I=e&&(h.push(l(_,T,e)),M=!0),I>i&&b<=i&&(h.push(l(_,T,i)),M=!0),!s&&M&&(d.push(h),h=[])}let g=r.length-1,m=o===0?r[g].x:r[g].y;return m>=e&&m<=i&&h.push(r[g]),s&&h.length>0&&!h[0].equals(h[h.length-1])&&h.push(new Te(h[0].x,h[0].y)),h.length>0&&d.push(h),d}function Sf(r,e,i,o,s){let l=[];for(let h of r){let d=w_(h,e,i,o,s);d.length>0&&l.push(...d)}return l}function T_(r,e,i){return new Te(i,r.y+(i-r.x)/(e.x-r.x)*(e.y-r.y))}function P_(r,e,i){return new Te(r.x+(i-r.y)/(e.y-r.y)*(e.x-r.x),i)}Pe("FeatureIndex",bf,{omit:["rawTileData","sourceLayerCoder"]});class fo extends Te{constructor(e,i,o,s){super(e,i),this.angle=o,s!==void 0&&(this.segment=s)}clone(){return new fo(this.x,this.y,this.angle,this.segment)}}function If(r,e,i,o,s){if(e.segment===void 0||i===0)return!0;let l=e,h=e.segment+1,d=0;for(;d>-i/2;){if(h--,h<0)return!1;d-=r[h].dist(l),l=r[h]}d+=r[h].dist(r[h+1]),h++;let g=[],m=0;for(;do;)m-=g.shift().angleDelta;if(m>s)return!1;h++,d+=v.dist(_)}return!0}function Mf(r){let e=0;for(let i=0;im){let I=(m-g)/b,M=Ai.number(_.x,T.x,I),A=Ai.number(_.y,T.y,I),D=new fo(M,A,T.angleTo(_),v);return D._round(),!h||If(r,D,d,h,e)?D:void 0}g+=b}}function I_(r,e,i,o,s,l,h,d,g){let m=Ef(o,l,h),v=Cf(o,s),_=v*h,T=r[0].x===0||r[0].x===g||r[0].y===0||r[0].y===g;return e-_=0&&F=0&&O=0&&T+m<=v){let V=new fo(F,O,L,I);V._round(),o&&!If(r,V,l,o,s)||b.push(V)}}_+=D}return d||b.length||h||(b=Af(r,_/2,i,o,s,l,h,!0,g)),b}function Df(r,e,i,o){let s=[],l=r.image,h=l.pixelRatio,d=l.paddedRect.w-2,g=l.paddedRect.h-2,m={x1:r.left,y1:r.top,x2:r.right,y2:r.bottom},v=l.stretchX||[[0,d]],_=l.stretchY||[[0,g]],T=(ie,fe)=>ie+fe[1]-fe[0],b=v.reduce(T,0),I=_.reduce(T,0),M=d-b,A=g-I,D=0,L=b,R=0,F=I,O=0,V=M,Y=0,J=A;if(l.content&&o){let ie=l.content,fe=ie[2]-ie[0],xe=ie[3]-ie[1];(l.textFitWidth||l.textFitHeight)&&(m=Ip(r)),D=Eh(v,0,ie[0]),R=Eh(_,0,ie[1]),L=Eh(v,ie[0],ie[2]),F=Eh(_,ie[1],ie[3]),O=ie[0]-D,Y=ie[1]-R,V=fe-L,J=xe-F}let re=m.x1,te=m.y1,ae=m.x2-re,le=m.y2-te,ne=(ie,fe,xe,ye)=>{let me=Ch(ie.stretch-D,L,ae,re),Ae=Ah(ie.fixed-O,V,ie.stretch,b),Ye=Ch(fe.stretch-R,F,le,te),Je=Ah(fe.fixed-Y,J,fe.stretch,I),nt=Ch(xe.stretch-D,L,ae,re),si=Ah(xe.fixed-O,V,xe.stretch,b),Tt=Ch(ye.stretch-R,F,le,te),Ft=Ah(ye.fixed-Y,J,ye.stretch,I),Ut=new Te(me,Ye),pt=new Te(nt,Ye),Qt=new Te(nt,Tt),mi=new Te(me,Tt),gi=new Te(Ae/h,Je/h),Li=new Te(si/h,Ft/h),ai=e*Math.PI/180;if(ai){let Gt=Math.sin(ai),yt=Math.cos(ai),Rt=[yt,-Gt,Gt,yt];Ut._matMult(Rt),pt._matMult(Rt),mi._matMult(Rt),Qt._matMult(Rt)}let Fi=ie.stretch+ie.fixed,lr=fe.stretch+fe.fixed;return{tl:Ut,tr:pt,bl:mi,br:Qt,tex:{x:l.paddedRect.x+1+Fi,y:l.paddedRect.y+1+lr,w:xe.stretch+xe.fixed-Fi,h:ye.stretch+ye.fixed-lr},writingMode:void 0,glyphOffset:[0,0],sectionIndex:0,pixelOffsetTL:gi,pixelOffsetBR:Li,minFontScaleX:V/h/ae,minFontScaleY:J/h/le,isSDF:i}};if(o&&(l.stretchX||l.stretchY)){let ie=zf(v,M,b),fe=zf(_,A,I);for(let xe=0;xe0&&(M=Math.max(10,M),this.circleDiameter=M)}else{let T=!((_=h.image)===null||_===void 0)&&_.content&&(h.image.textFitWidth||h.image.textFitHeight)?Ip(h):{x1:h.left,y1:h.top,x2:h.right,y2:h.bottom};T.y1=T.y1*d-g[0],T.y2=T.y2*d+g[2],T.x1=T.x1*d-g[3],T.x2=T.x2*d+g[1];let b=h.collisionPadding;if(b&&(T.x1-=b[0]*d,T.y1-=b[1]*d,T.x2+=b[2]*d,T.y2+=b[3]*d),v){let I=new Te(T.x1,T.y1),M=new Te(T.x2,T.y1),A=new Te(T.x1,T.y2),D=new Te(T.x2,T.y2),L=v*Math.PI/180;I._rotate(L),M._rotate(L),A._rotate(L),D._rotate(L),T.x1=Math.min(I.x,M.x,A.x,D.x),T.x2=Math.max(I.x,M.x,A.x,D.x),T.y1=Math.min(I.y,M.y,A.y,D.y),T.y2=Math.max(I.y,M.y,A.y,D.y)}e.emplaceBack(i.x,i.y,T.x1,T.y1,T.x2,T.y2,o,s,l)}this.boxEndIndex=e.length}}class M_{constructor(e=[],i=(o,s)=>os?1:0){if(this.data=e,this.length=this.data.length,this.compare=i,this.length>0)for(let o=(this.length>>1)-1;o>=0;o--)this._down(o)}push(e){this.data.push(e),this._up(this.length++)}pop(){if(this.length===0)return;let e=this.data[0],i=this.data.pop();return--this.length>0&&(this.data[0]=i,this._down(0)),e}peek(){return this.data[0]}_up(e){let{data:i,compare:o}=this,s=i[e];for(;e>0;){let l=e-1>>1,h=i[l];if(o(s,h)>=0)break;i[e]=h,e=l}i[e]=s}_down(e){let{data:i,compare:o}=this,s=this.length>>1,l=i[e];for(;e=0)break;i[e]=i[h],e=h}i[e]=l}}function E_(r,e=1){let i=ss.fromPoints(r[0]),o=Math.min(i.width(),i.height()),s=o/2,l=new M_([],C_),{minX:h,minY:d,maxX:g,maxY:m}=i;if(o===0)return new Te(h,d);for(let T=h;T_.d||!_.d)&&(_=T),T.max-_.d<=e||(s=T.h/2,l.push(new Ma(T.p.x-s,T.p.y-s,s,r)),l.push(new Ma(T.p.x+s,T.p.y-s,s,r)),l.push(new Ma(T.p.x-s,T.p.y+s,s,r)),l.push(new Ma(T.p.x+s,T.p.y+s,s,r)))}return v.d>0&&_.d-v.d<=e?v.p:_.p}function C_(r,e){return e.max-r.max}class Ma{constructor(e,i,o,s){this.p=new Te(e,i),this.h=o,this.d=(function(l,h){let d=!1,g=1/0;for(let m of h)for(let v=0,_=m.length,T=_-1;v<_;T=v++){let b=m[v],I=m[T];b.y>l.y!=I.y>l.y&&l.x<(I.x-b.x)*(l.y-b.y)/(I.y-b.y)+b.x&&(d=!d),g=Math.min(g,wd(l,b,I))}return(d?1:-1)*Math.sqrt(g)})(this.p,s),this.max=this.d+this.h*Math.SQRT2}}var oi;k.aM=void 0,(oi=k.aM||(k.aM={}))[oi.center=1]="center",oi[oi.left=2]="left",oi[oi.right=3]="right",oi[oi.top=4]="top",oi[oi.bottom=5]="bottom",oi[oi["top-left"]=6]="top-left",oi[oi["top-right"]=7]="top-right",oi[oi["bottom-left"]=8]="bottom-left",oi[oi["bottom-right"]=9]="bottom-right";let fd=Number.POSITIVE_INFINITY;function Rf(r,e){return e[1]!==fd?(function(i,o,s){let l=0,h=0;switch(o=Math.abs(o),s=Math.abs(s),i){case"top-right":case"top-left":case"top":h=s-7;break;case"bottom-right":case"bottom-left":case"bottom":h=7-s}switch(i){case"top-right":case"bottom-right":case"right":l=-o;break;case"top-left":case"bottom-left":case"left":l=o}return[l,h]})(r,e[0],e[1]):(function(i,o){let s=0,l=0;o<0&&(o=0);let h=o/Math.SQRT2;switch(i){case"top-right":case"top-left":l=h-7;break;case"bottom-right":case"bottom-left":l=7-h;break;case"bottom":l=7-o;break;case"top":l=o-7}switch(i){case"top-right":case"bottom-right":s=-h;break;case"top-left":case"bottom-left":s=h;break;case"left":s=o;break;case"right":s=-o}return[s,l]})(r,e[0])}function kf(r,e,i){var o;let s=r.layout,l=(o=s.get("text-variable-anchor-offset"))===null||o===void 0?void 0:o.evaluate(e,{},i);if(l){let d=l.values,g=[];for(let m=0;mT*Vt));v.startsWith("top")?_[1]-=7:v.startsWith("bottom")&&(_[1]+=7),g[m+1]=_}return new ci(g)}let h=s.get("text-variable-anchor");if(h){let d;d=r._unevaluatedLayout.getValue("text-radial-offset")!==void 0?[s.get("text-radial-offset").evaluate(e,{},i)*Vt,fd]:s.get("text-offset").evaluate(e,{},i).map((m=>m*Vt));let g=[];for(let m of h)g.push(m,Rf(m,d));return new ci(g)}return null}function md(r){switch(r){case"right":case"top-right":case"bottom-right":return"right";case"left":case"top-left":case"bottom-left":return"left"}return"center"}function A_(r,e,i,o,s,l,h,d,g,m,v,_){let T=l.textMaxSize.evaluate(e,{});T===void 0&&(T=h);let b=r.layers[0].layout,I=b.get("icon-offset").evaluate(e,{},v),M=Ff(i.horizontal),A=h/24,D=r.tilePixelRatio*A,L=r.tilePixelRatio*T/24,R=r.tilePixelRatio*d,F=r.tilePixelRatio*b.get("symbol-spacing"),O=b.get("text-padding")*r.tilePixelRatio,V=(function(xe,ye,me,Ae=1){let Ye=xe.get("icon-padding").evaluate(ye,{},me),Je=Ye?.values;return[Je[0]*Ae,Je[1]*Ae,Je[2]*Ae,Je[3]*Ae]})(b,e,v,r.tilePixelRatio),Y=b.get("text-max-angle")/180*Math.PI,J=b.get("text-rotation-alignment")!=="viewport"&&b.get("symbol-placement")!=="point",re=b.get("icon-rotation-alignment")==="map"&&b.get("symbol-placement")!=="point",te=b.get("symbol-placement"),ae=F/2,le=b.get("icon-text-fit"),ne;o&&le!=="none"&&(r.allowVerticalPlacement&&i.vertical&&(ne=Mp(o,i.vertical,le,b.get("icon-text-fit-padding"),I,A)),M&&(o=Mp(o,M,le,b.get("icon-text-fit-padding"),I,A)));let ie=v?_.line.getGranularityForZoomLevel(v.z):1,fe=(xe,ye)=>{ye.x<0||ye.x>=De||ye.y<0||ye.y>=De||(function(me,Ae,Ye,Je,nt,si,Tt,Ft,Ut,pt,Qt,mi,gi,Li,ai,Fi,lr,Gt,yt,Rt,Pt,$t,En,wr,ic){let mo=me.addToLineVertexArray(Ae,Ye),ls,Ea,Ca,Aa,Bf=0,Of=0,Nf=0,Vf=0,gd=-1,_d=-1,Cn={},jf=Nt("");if(me.allowVerticalPlacement&&Je.vertical){let _i=Ft.layout.get("text-rotate").evaluate(Pt,{},wr)+90;Ca=new Dh(Ut,Ae,pt,Qt,mi,Je.vertical,gi,Li,ai,_i),Tt&&(Aa=new Dh(Ut,Ae,pt,Qt,mi,Tt,lr,Gt,ai,_i))}if(nt){let _i=Ft.layout.get("icon-rotate").evaluate(Pt,{}),tr=Ft.layout.get("icon-text-fit")!=="none",cs=Df(nt,_i,En,tr),Pr=Tt?Df(Tt,_i,En,tr):void 0;Ea=new Dh(Ut,Ae,pt,Qt,mi,nt,lr,Gt,!1,_i),Bf=4*cs.length;let hs=me.iconSizeData,qr=null;hs.kind==="source"?(qr=[In*Ft.layout.get("icon-size").evaluate(Pt,{})],qr[0]>lo&&Wt(`${me.layerIds[0]}: Value for "icon-size" is >= 255. Reduce your "icon-size".`)):hs.kind==="composite"&&(qr=[In*$t.compositeIconSizes[0].evaluate(Pt,{},wr),In*$t.compositeIconSizes[1].evaluate(Pt,{},wr)],(qr[0]>lo||qr[1]>lo)&&Wt(`${me.layerIds[0]}: Value for "icon-size" is >= 255. Reduce your "icon-size".`)),me.addSymbols(me.icon,cs,qr,Rt,yt,Pt,k.ax.none,Ae,mo.lineStartIndex,mo.lineLength,-1,wr),gd=me.icon.placedSymbolArray.length-1,Pr&&(Of=4*Pr.length,me.addSymbols(me.icon,Pr,qr,Rt,yt,Pt,k.ax.vertical,Ae,mo.lineStartIndex,mo.lineLength,-1,wr),_d=me.icon.placedSymbolArray.length-1)}let Uf=Object.keys(Je.horizontal);for(let _i of Uf){let tr=Je.horizontal[_i];if(!ls){jf=Nt(tr.text);let Pr=Ft.layout.get("text-rotate").evaluate(Pt,{},wr);ls=new Dh(Ut,Ae,pt,Qt,mi,tr,gi,Li,ai,Pr)}let cs=tr.positionedLines.length===1;if(Nf+=Lf(me,Ae,tr,si,Ft,ai,Pt,Fi,mo,Je.vertical?k.ax.horizontal:k.ax.horizontalOnly,cs?Uf:[_i],Cn,gd,$t,wr),cs)break}Je.vertical&&(Vf+=Lf(me,Ae,Je.vertical,si,Ft,ai,Pt,Fi,mo,k.ax.vertical,["vertical"],Cn,_d,$t,wr));let z_=ls?ls.boxStartIndex:me.collisionBoxArray.length,R_=ls?ls.boxEndIndex:me.collisionBoxArray.length,k_=Ca?Ca.boxStartIndex:me.collisionBoxArray.length,L_=Ca?Ca.boxEndIndex:me.collisionBoxArray.length,F_=Ea?Ea.boxStartIndex:me.collisionBoxArray.length,B_=Ea?Ea.boxEndIndex:me.collisionBoxArray.length,O_=Aa?Aa.boxStartIndex:me.collisionBoxArray.length,N_=Aa?Aa.boxEndIndex:me.collisionBoxArray.length,Tr=-1,zh=(_i,tr)=>_i?.circleDiameter?Math.max(_i.circleDiameter,tr):tr;Tr=zh(ls,Tr),Tr=zh(Ca,Tr),Tr=zh(Ea,Tr),Tr=zh(Aa,Tr);let Gf=Tr>-1?1:0;Gf&&(Tr*=ic/Vt),me.glyphOffsetArray.length>=_a.MAX_GLYPHS&&Wt("Too many glyphs being rendered in a tile. See https://github.com/mapbox/mapbox-gl-js/issues/2907"),Pt.sortKey!==void 0&&me.addToSortKeyRanges(me.symbolInstances.length,Pt.sortKey);let V_=kf(Ft,Pt,wr),[j_,U_]=(function(_i,tr){let cs=_i.length,Pr=tr?.values;if(Pr?.length>0)for(let hs=0;hs=0?Cn.right:-1,Cn.center>=0?Cn.center:-1,Cn.left>=0?Cn.left:-1,Cn.vertical||-1,gd,_d,jf,z_,R_,k_,L_,F_,B_,O_,N_,pt,Nf,Vf,Bf,Of,Gf,0,gi,Tr,j_,U_)})(r,ye,xe,i,o,s,ne,r.layers[0],r.collisionBoxArray,e.index,e.sourceLayerIndex,r.index,D,[O,O,O,O],J,g,R,V,re,I,e,l,m,v,h)};if(te==="line")for(let xe of Tf(e.geometry,0,0,De,De)){let ye=os(xe,ie),me=I_(ye,F,Y,i.vertical||M,o,24,L,r.overscaling,De);for(let Ae of me)M&&D_(r,M.text,ae,Ae)||fe(ye,Ae)}else if(te==="line-center"){for(let xe of e.geometry)if(xe.length>1){let ye=os(xe,ie),me=S_(ye,Y,i.vertical||M,o,24,L);me&&fe(ye,me)}}else if(e.type==="Polygon")for(let xe of As(e.geometry,0)){let ye=E_(xe,16);fe(os(xe[0],ie,!0),new fo(ye.x,ye.y,0))}else if(e.type==="LineString")for(let xe of e.geometry){let ye=os(xe,ie);fe(ye,new fo(ye[0].x,ye[0].y,0))}else if(e.type==="Point")for(let xe of e.geometry)for(let ye of xe)fe([ye],new fo(ye.x,ye.y,0))}function Lf(r,e,i,o,s,l,h,d,g,m,v,_,T,b,I){let M=(function(L,R,F,O,V,Y,J,re){let te=O.layout.get("text-rotate").evaluate(Y,{})*Math.PI/180,ae=[];for(let le of R.positionedLines)for(let ne of le.positionedGlyphs){if(!ne.rect)continue;let ie=ne.rect||{},fe=4,xe=!0,ye=1,me=0,Ae=(V||re)&&ne.vertical,Ye=ne.metrics.advance*ne.scale/2;if(re&&R.verticalizable&&(me=le.lineOffset/2-(ne.imageName?-(Vt-ne.metrics.width*ne.scale)/2:(ne.scale-1)*Vt)),ne.imageName){let Gt=J[ne.imageName];xe=Gt.sdf,ye=Gt.pixelRatio,fe=1/ye}let Je=V?[ne.x+Ye,ne.y]:[0,0],nt=V?[0,0]:[ne.x+Ye+F[0],ne.y+F[1]-me],si=[0,0];Ae&&(si=nt,nt=[0,0]);let Tt=ne.metrics.isDoubleResolution?2:1,Ft=(ne.metrics.left-fe)*ne.scale-Ye+nt[0],Ut=(-ne.metrics.top-fe)*ne.scale+nt[1],pt=Ft+ie.w/Tt*ne.scale/ye,Qt=Ut+ie.h/Tt*ne.scale/ye,mi=new Te(Ft,Ut),gi=new Te(pt,Ut),Li=new Te(Ft,Qt),ai=new Te(pt,Qt);if(Ae){let Gt=new Te(-Ye,Ye- -17),yt=-Math.PI/2,Rt=12-Ye,Pt=new Te(22-Rt,-(ne.imageName?Rt:0)),$t=new Te(...si);mi._rotateAround(yt,Gt)._add(Pt)._add($t),gi._rotateAround(yt,Gt)._add(Pt)._add($t),Li._rotateAround(yt,Gt)._add(Pt)._add($t),ai._rotateAround(yt,Gt)._add(Pt)._add($t)}if(te){let Gt=Math.sin(te),yt=Math.cos(te),Rt=[yt,-Gt,Gt,yt];mi._matMult(Rt),gi._matMult(Rt),Li._matMult(Rt),ai._matMult(Rt)}let Fi=new Te(0,0),lr=new Te(0,0);ae.push({tl:mi,tr:gi,bl:Li,br:ai,tex:ie,writingMode:R.writingMode,glyphOffset:Je,sectionIndex:ne.sectionIndex,isSDF:xe,pixelOffsetTL:Fi,pixelOffsetBR:lr,minFontScaleX:0,minFontScaleY:0})}return ae})(0,i,d,s,l,h,o,r.allowVerticalPlacement),A=r.textSizeData,D=null;A.kind==="source"?(D=[In*s.layout.get("text-size").evaluate(h,{})],D[0]>lo&&Wt(`${r.layerIds[0]}: Value for "text-size" is >= 255. Reduce your "text-size".`)):A.kind==="composite"&&(D=[In*b.compositeTextSizes[0].evaluate(h,{},I),In*b.compositeTextSizes[1].evaluate(h,{},I)],(D[0]>lo||D[1]>lo)&&Wt(`${r.layerIds[0]}: Value for "text-size" is >= 255. Reduce your "text-size".`)),r.addSymbols(r.text,M,D,d,l,h,m,e,g.lineStartIndex,g.lineLength,T,I);for(let L of v)_[L]=r.text.placedSymbolArray.length-1;return 4*M.length}function Ff(r){for(let e in r)return r[e];return null}function D_(r,e,i,o){let s=r.compareText;if(e in s){let l=s[e];for(let h=l.length-1;h>=0;h--)if(o.dist(l[h])this.process())),this.subscription=us(this.target,"message",(i=>this.receive(i)),!1),this.globalScope=Ht(self)?r:window}registerMessageHandler(r,e){this.messageHandlers[r]=e}unregisterMessageHandler(r){delete this.messageHandlers[r]}sendAsync(r,e){return new Promise(((i,o)=>{let s=Math.round(1e18*Math.random()).toString(36).substring(0,10),l=e?us(e.signal,"abort",(()=>{l?.unsubscribe(),delete this.resolveRejects[s];let g={id:s,type:"",origin:location.origin,targetMapId:r.targetMapId,sourceMapId:this.mapId};this.target.postMessage(g)}),Gg):null;this.resolveRejects[s]={resolve:g=>{l?.unsubscribe(),i(g)},reject:g=>{l?.unsubscribe(),o(g)}};let h=[],d=Object.assign(Object.assign({},r),{id:s,sourceMapId:this.mapId,origin:location.origin,data:mr(r.data,h)});this.target.postMessage(d,{transfer:h})}))}receive(r){let e=r.data,i=e.id,o=["file://","resource://android","null"],s=[e.origin,location.origin],l=e.origin===location.origin,h=s.some((d=>o.includes(d)));if((l||h)&&(!e.targetMapId||this.mapId===e.targetMapId)){if(e.type===""){delete this.tasks[i];let d=this.abortControllers[i];return delete this.abortControllers[i],void(d&&d.abort())}if(Ht(self)||e.mustQueue)return this.tasks[i]=e,this.taskQueue.push(i),void this.invoker.trigger();this.processTask(i,e)}}process(){if(this.taskQueue.length===0)return;let r=this.taskQueue.shift(),e=this.tasks[r];delete this.tasks[r],this.taskQueue.length>0&&this.invoker.trigger(),e&&this.processTask(r,e)}processTask(r,e){return p(this,void 0,void 0,(function*(){if(e.type===""){let s=this.resolveRejects[r];return delete this.resolveRejects[r],s?void(e.error?s.reject(xt(Xo(e.error))):s.resolve(Xo(e.data))):void 0}if(!this.messageHandlers[e.type])return void this.completeTask(r,new Error(`Could not find a registered handler for ${e.type}, map ID: ${this.mapId}, available handlers: ${Object.keys(this.messageHandlers).join(", ")}`));let i=Xo(e.data),o=new AbortController;this.abortControllers[r]=o;try{let s=yield this.messageHandlers[e.type](e.sourceMapId,i,o);this.completeTask(r,null,s)}catch(s){this.completeTask(r,xt(s))}}))}completeTask(r,e,i){let o=[];delete this.abortControllers[r];let s={id:r,type:"",sourceMapId:this.mapId,origin:location.origin,error:e?mr(e):null,data:mr(i,o)};this.target.postMessage(s,{transfer:o})}remove(){this.invoker.remove(),this.subscription.unsubscribe()}},k.O=function(){var r=new kt(16);return kt!=Float32Array&&(r[1]=0,r[2]=0,r[3]=0,r[4]=0,r[6]=0,r[7]=0,r[8]=0,r[9]=0,r[11]=0,r[12]=0,r[13]=0,r[14]=0),r[0]=1,r[5]=1,r[10]=1,r[15]=1,r},k.P=Te,k.Q=function(r,e,i){var o,s,l,h,d,g,m,v,_,T,b,I,M=i[0],A=i[1],D=i[2];return e===r?(r[12]=e[0]*M+e[4]*A+e[8]*D+e[12],r[13]=e[1]*M+e[5]*A+e[9]*D+e[13],r[14]=e[2]*M+e[6]*A+e[10]*D+e[14],r[15]=e[3]*M+e[7]*A+e[11]*D+e[15]):(s=e[1],l=e[2],h=e[3],d=e[4],g=e[5],m=e[6],v=e[7],_=e[8],T=e[9],b=e[10],I=e[11],r[0]=o=e[0],r[1]=s,r[2]=l,r[3]=h,r[4]=d,r[5]=g,r[6]=m,r[7]=v,r[8]=_,r[9]=T,r[10]=b,r[11]=I,r[12]=o*M+d*A+_*D+e[12],r[13]=s*M+g*A+T*D+e[13],r[14]=l*M+m*A+b*D+e[14],r[15]=h*M+v*A+I*D+e[15]),r},k.R=ki,k.S=function(r,e,i){var o=i[0],s=i[1],l=i[2];return r[0]=e[0]*o,r[1]=e[1]*o,r[2]=e[2]*o,r[3]=e[3]*o,r[4]=e[4]*s,r[5]=e[5]*s,r[6]=e[6]*s,r[7]=e[7]*s,r[8]=e[8]*l,r[9]=e[9]*l,r[10]=e[10]*l,r[11]=e[11]*l,r[12]=e[12],r[13]=e[13],r[14]=e[14],r[15]=e[15],r},k.T=gu,k.U=function(r,e,i){var o=e[0],s=e[1],l=e[2],h=e[3],d=e[4],g=e[5],m=e[6],v=e[7],_=e[8],T=e[9],b=e[10],I=e[11],M=e[12],A=e[13],D=e[14],L=e[15],R=i[0],F=i[1],O=i[2],V=i[3];return r[0]=R*o+F*d+O*_+V*M,r[1]=R*s+F*g+O*T+V*A,r[2]=R*l+F*m+O*b+V*D,r[3]=R*h+F*v+O*I+V*L,r[4]=(R=i[4])*o+(F=i[5])*d+(O=i[6])*_+(V=i[7])*M,r[5]=R*s+F*g+O*T+V*A,r[6]=R*l+F*m+O*b+V*D,r[7]=R*h+F*v+O*I+V*L,r[8]=(R=i[8])*o+(F=i[9])*d+(O=i[10])*_+(V=i[11])*M,r[9]=R*s+F*g+O*T+V*A,r[10]=R*l+F*m+O*b+V*D,r[11]=R*h+F*v+O*I+V*L,r[12]=(R=i[12])*o+(F=i[13])*d+(O=i[14])*_+(V=i[15])*M,r[13]=R*s+F*g+O*T+V*A,r[14]=R*l+F*m+O*b+V*D,r[15]=R*h+F*v+O*I+V*L,r},k.V=function(r,e){let i={};for(let o of e)o in r&&(i[o]=r[o]);return i},k.W=co,k.X=zn,k.Y=Fp,k.Z=Lp,k._=p,k.a=xo,k.a$=function(r){var e=new kt(3);return e[0]=r[0],e[1]=r[1],e[2]=r[2],e},k.a0=Hr,k.a1=Ii,k.a2=Ra,k.a3=$i,k.a4=Op,k.a5=Sh,k.a6=De,k.a7=Jl,k.a8=ss,k.a9=25,k.aA=function(r){var e=r[0],i=r[1];return Math.sqrt(e*e+i*i)},k.aB=function(r){return r[0]=0,r[1]=0,r},k.aC=function(r,e,i){return r[0]=e[0]*i,r[1]=e[1]*i,r},k.aD=Gu,k.aE=Ze,k.aF=function(r,e,i,o){let s=e.y-r.y,l=e.x-r.x,h=o.y-i.y,d=o.x-i.x,g=h*l-d*s;if(g===0)return null;let m=(d*(r.y-i.y)-h*(r.x-i.x))/g;return new Te(r.x+m*l,r.y+m*s)},k.aG=Tf,k.aH=sa,k.aI=function(r){let e=1/0,i=1/0,o=-1/0,s=-1/0;for(let l of r)e=Math.min(e,l.x),i=Math.min(i,l.y),o=Math.max(o,l.x),s=Math.max(s,l.y);return[e,i,o,s]},k.aJ=Vt,k.aK=vt,k.aL=function(r,e,i,o,s=!1){if(!i[0]&&!i[1])return[0,0];let l=s?o==="map"?-r.bearingInRadians:0:o==="viewport"?r.bearingInRadians:0;if(l){let h=Math.sin(l),d=Math.cos(l);i=[i[0]*d-i[1]*h,i[0]*h+i[1]*d]}return[s?i[0]:vt(e,i[0],r.zoom),s?i[1]:vt(e,i[1],r.zoom)]},k.aN=Uu,k.aO=md,k.aP=ju,k.aQ=r=>r.type==="symbol",k.aR=mh,k.aS=ht,k.aT=fh,k.aU=N,k.aV=we,k.aW=ue,k.aX=Qr,k.aY=Np,k.aZ=K,k.a_=W,k.aa=Hu,k.ab=r=>{let e=window.document.createElement("video");return e.muted=!0,new Promise((i=>{e.onloadstart=()=>{i(e)};for(let o of r){let s=window.document.createElement("source");Hi(o)||(e.crossOrigin="Anonymous"),s.src=o,e.appendChild(s)}}))},k.ac=_e,k.ad=function(){return vo++},k.ae=c,k.af=_a,k.ag=tc,k.ah=No,k.ai=Zr,k.aj=Gp,k.ak=function(r){let e={};if(r.replace(/(?:^|(?:\s*\,\s*))([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)(?:\=(?:([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)|(?:\"((?:[^"\\]|\\.)*)\")))?/g,((i,o,s,l)=>{let h=s||l;return e[o]=!h||h.toLowerCase(),""})),e["max-age"]){let i=parseInt(e["max-age"],10);isNaN(i)?delete e["max-age"]:e["max-age"]=i}return e},k.al=li,k.am=85.051129,k.an=Ar,k.ao=function(r){return Math.pow(2,r)},k.ap=Dn,k.aq=Bp,k.ar=function(r){return Math.log(r)/Math.LN2},k.as=function(r){var e=r[0],i=r[1];return e*e+i*i},k.at=function(r){if(!r.length)return new Set;let e=Math.max(...r.map((g=>g.canonical.z))),i=1/0,o=-1/0,s=1/0,l=-1/0,h=[];for(let g of r){let{x:m,y:v,z:_}=g.canonical,T=Math.pow(2,e-_),b=m*T,I=v*T;h.push({id:g,x:b,y:I}),bo&&(o=b),Il&&(l=I)}let d=new Set;for(let g of h)g.x!==i&&g.x!==o&&g.y!==s&&g.y!==l||d.add(g.id);return d},k.au=function(r,e){let i=Math.abs(2*r.wrap)-+(r.wrap<0),o=Math.abs(2*e.wrap)-+(e.wrap<0);return r.overscaledZ-e.overscaledZ||o-i||e.canonical.y-r.canonical.y||e.canonical.x-r.canonical.x},k.av=class{constructor(r,e){this.max=r,this.onRemove=e,this.reset()}reset(){for(let r in this.data)for(let e of this.data[r])e.timeout&&clearTimeout(e.timeout),this.onRemove(e.value);return this.data={},this.order=[],this}add(r,e,i){let o=r.wrapped().key;this.data[o]===void 0&&(this.data[o]=[]);let s={value:e,timeout:void 0};if(i!==void 0&&(s.timeout=setTimeout((()=>{this.remove(r,s)}),i)),this.data[o].push(s),this.order.push(o),this.order.length>this.max){let l=this._getAndRemoveByKey(this.order[0]);l&&this.onRemove(l)}return this}has(r){return r.wrapped().key in this.data}getAndRemove(r){return this.has(r)?this._getAndRemoveByKey(r.wrapped().key):null}_getAndRemoveByKey(r){let e=this.data[r].shift();return e.timeout&&clearTimeout(e.timeout),this.data[r].length===0&&delete this.data[r],this.order.splice(this.order.indexOf(r),1),e.value}getByKey(r){let e=this.data[r];return e?e[0].value:null}get(r){return this.has(r)?this.data[r.wrapped().key][0].value:null}remove(r,e){if(!this.has(r))return this;let i=r.wrapped().key,o=e===void 0?0:this.data[i].indexOf(e),s=this.data[i][o];return this.data[i].splice(o,1),s.timeout&&clearTimeout(s.timeout),this.data[i].length===0&&delete this.data[i],this.onRemove(s.value),this.order.splice(this.order.indexOf(i),1),this}setMaxSize(r){for(this.max=r;this.order.length>this.max;){let e=this._getAndRemoveByKey(this.order[0]);e&&this.onRemove(e)}return this}filter(r){let e=[];for(let i in this.data)for(let o of this.data[i])r(o.value)||e.push(o);for(let i of e)this.remove(i.value.tileID,i)}},k.aw=function(r,e){let i=0,o=0;if(r.kind==="constant")o=r.layoutSize;else if(r.kind!=="source"){let{interpolationType:s,minZoom:l,maxZoom:h}=r,d=s?li(Et.interpolationFactor(s,e,l,h),0,1):0;r.kind==="camera"?o=Ai.number(r.minSize,r.maxSize,d):i=d}return{uSizeT:i,uSize:o}},k.ay=function(r,{uSize:e,uSizeT:i},{lowerSize:o,upperSize:s}){return r.kind==="source"?o/In:r.kind==="composite"?Ai.number(o/In,s/In,i):e},k.az=Be,k.b=Jr,k.b$=ra,k.b0=function(r,e,i){return r[0]=e[0]-i[0],r[1]=e[1]-i[1],r[2]=e[2]-i[2],r},k.b1=function(r,e){var i=e[0],o=e[1],s=e[2],l=i*i+o*o+s*s;return l>0&&(l=1/Math.sqrt(l)),r[0]=e[0]*l,r[1]=e[1]*l,r[2]=e[2]*l,r},k.b2=ee,k.b3=function(r,e){return r[0]*e[0]+r[1]*e[1]+r[2]*e[2]},k.b4=function(r,e,i){return r[0]=e[0]*i[0],r[1]=e[1]*i[1],r[2]=e[2]*i[2],r[3]=e[3]*i[3],r},k.b5=_o,k.b6=function(r,e,i){let o=e[0]*i[0]+e[1]*i[1]+e[2]*i[2];return o===0?null:(-(r[0]*i[0]+r[1]*i[1]+r[2]*i[2])-i[3])/o},k.b7=Me,k.b8=function(r,e,i){return r[0]=e[0]*i,r[1]=e[1]*i,r[2]=e[2]*i,r[3]=e[3]*i,r},k.b9=function(r,e){return r[0]*e[0]+r[1]*e[1]+r[2]*e[2]+r[3]},k.bA=$e,k.bB=function(r,e,i){var o=i[0],s=i[1],l=i[2],h=i[3],d=e[0],g=e[1],m=e[2],v=s*m-l*g,_=l*d-o*m,T=o*g-s*d;return r[0]=d+h*(v+=v)+s*(T+=T)-l*(_+=_),r[1]=g+h*_+l*v-o*T,r[2]=m+h*T+o*_-s*v,r},k.bC=function(r,e,i){let o=(s=[r[0],r[1],r[2],e[0],e[1],e[2],i[0],i[1],i[2]])[0]*((v=s[8])*(h=s[4])-(d=s[5])*(m=s[7]))+s[1]*(-v*(l=s[3])+d*(g=s[6]))+s[2]*(m*l-h*g);var s,l,h,d,g,m,v;if(o===0)return null;let _=ee([],[e[0],e[1],e[2]],[i[0],i[1],i[2]]),T=ee([],[i[0],i[1],i[2]],[r[0],r[1],r[2]]),b=ee([],[r[0],r[1],r[2]],[e[0],e[1],e[2]]),I=K([],_,-r[3]);return W(I,I,K([],T,-e[3])),W(I,I,K([],b,-i[3])),K(I,I,1/o),I},k.bD=Wu,k.bE=function(){return new Float64Array(4)},k.bF=function(r,e,i,o){var s=[],l=[];return s[0]=e[0]-i[0],s[1]=e[1]-i[1],s[2]=e[2]-i[2],l[0]=s[0]*Math.cos(o)-s[1]*Math.sin(o),l[1]=s[0]*Math.sin(o)+s[1]*Math.cos(o),l[2]=s[2],r[0]=l[0]+i[0],r[1]=l[1]+i[1],r[2]=l[2]+i[2],r},k.bG=function(r,e,i,o){var s=[],l=[];return s[0]=e[0]-i[0],s[1]=e[1]-i[1],s[2]=e[2]-i[2],l[0]=s[0],l[1]=s[1]*Math.cos(o)-s[2]*Math.sin(o),l[2]=s[1]*Math.sin(o)+s[2]*Math.cos(o),r[0]=l[0]+i[0],r[1]=l[1]+i[1],r[2]=l[2]+i[2],r},k.bH=function(r,e,i,o){var s=[],l=[];return s[0]=e[0]-i[0],s[1]=e[1]-i[1],s[2]=e[2]-i[2],l[0]=s[2]*Math.sin(o)+s[0]*Math.cos(o),l[1]=s[1],l[2]=s[2]*Math.cos(o)-s[0]*Math.sin(o),r[0]=l[0]+i[0],r[1]=l[1]+i[1],r[2]=l[2]+i[2],r},k.bI=function(r,e,i){var o=Math.sin(i),s=Math.cos(i),l=e[0],h=e[1],d=e[2],g=e[3],m=e[8],v=e[9],_=e[10],T=e[11];return e!==r&&(r[4]=e[4],r[5]=e[5],r[6]=e[6],r[7]=e[7],r[12]=e[12],r[13]=e[13],r[14]=e[14],r[15]=e[15]),r[0]=l*s-m*o,r[1]=h*s-v*o,r[2]=d*s-_*o,r[3]=g*s-T*o,r[8]=l*o+m*s,r[9]=h*o+v*s,r[10]=d*o+_*s,r[11]=g*o+T*s,r},k.bJ=function(r,e){let i=Wi(r,360),o=Wi(e,360),s=o-i,l=o>i?s-360:s+360;return Math.abs(s)0?h:-h},k.bM=function(r,e){let i=Wi(r,2*Math.PI),o=Wi(e,2*Math.PI);return Math.min(Math.abs(i-o),Math.abs(i-o+2*Math.PI),Math.abs(i-o-2*Math.PI))},k.bN=function(){let r={},e=ce.$version;for(let i in ce.$root){let o=ce.$root[i];if(o.required){let s=null;s=i==="version"?e:o.type==="array"?[]:{},s!=null&&(r[i]=s)}}return r},k.bO=Fa,k.bP=xl,k.bQ=function r(e,i){if(Array.isArray(e)){if(!Array.isArray(i)||e.length!==i.length)return!1;for(let o=0;or.type==="raster",k.bV=Re,k.bW=function(r,e){if(!r)return[{command:"setStyle",args:[e]}];let i=[];try{if(!it(r.version,e.version))return[{command:"setStyle",args:[e]}];it(r.center,e.center)||i.push({command:"setCenter",args:[e.center]}),it(r.state,e.state)||i.push({command:"setGlobalState",args:[e.state]}),it(r.centerAltitude,e.centerAltitude)||i.push({command:"setCenterAltitude",args:[e.centerAltitude]}),it(r.zoom,e.zoom)||i.push({command:"setZoom",args:[e.zoom]}),it(r.bearing,e.bearing)||i.push({command:"setBearing",args:[e.bearing]}),it(r.pitch,e.pitch)||i.push({command:"setPitch",args:[e.pitch]}),it(r.roll,e.roll)||i.push({command:"setRoll",args:[e.roll]}),it(r.sprite,e.sprite)||i.push({command:"setSprite",args:[e.sprite]}),it(r.glyphs,e.glyphs)||i.push({command:"setGlyphs",args:[e.glyphs]}),it(r.transition,e.transition)||i.push({command:"setTransition",args:[e.transition]}),it(r.light,e.light)||i.push({command:"setLight",args:[e.light]}),it(r.terrain,e.terrain)||i.push({command:"setTerrain",args:[e.terrain]}),it(r.sky,e.sky)||i.push({command:"setSky",args:[e.sky]}),it(r.projection,e.projection)||i.push({command:"setProjection",args:[e.projection]});let o={},s=[];(function(h,d,g,m){let v;for(v in d=d||{},h=h||{})Object.prototype.hasOwnProperty.call(h,v)&&(Object.prototype.hasOwnProperty.call(d,v)||nc(v,g,m));for(v in d)Object.prototype.hasOwnProperty.call(d,v)&&(Object.prototype.hasOwnProperty.call(h,v)?it(h[v],d[v])||(h[v].type==="geojson"&&d[v].type==="geojson"&&Fh(h,d,v)?vi(g,{command:"setGeoJSONSourceData",args:[v,d[v].data]}):oc(v,d,g,m)):rn(v,d,g))})(r.sources,e.sources,s,o);let l=[];r.layers&&r.layers.forEach((h=>{"source"in h&&o[h.source]?i.push({command:"removeLayer",args:[h.id]}):l.push(h)})),i=i.concat(s),(function(h,d,g){d=d||[];let m=(h=h||[]).map(Na),v=d.map(Na),_=h.reduce(sc,{}),T=d.reduce(sc,{}),b=m.slice(),I=Object.create(null),M,A,D,L,R;for(let F=0,O=0;Fpe?(s=Math.acos(l),h=Math.sin(s),d=Math.sin((1-o)*s)/h,g=Math.sin(o*s)/h):(d=1-o,g=o),r[0]=d*m+g*b,r[1]=d*v+g*I,r[2]=d*_+g*M,r[3]=d*T+g*A,r},k.bm=function(r){let e=new Float64Array(9);var i,o,s,l,h,d,g,m,v,_,T,b,I,M,A,D,L,R;_=(s=(o=r)[0])*(g=s+s),T=(l=o[1])*g,I=(h=o[2])*g,M=h*(m=l+l),D=(d=o[3])*g,L=d*m,R=d*(v=h+h),(i=e)[0]=1-(b=l*m)-(A=h*v),i[3]=T-R,i[6]=I+L,i[1]=T+R,i[4]=1-_-A,i[7]=M-D,i[2]=I-L,i[5]=M+D,i[8]=1-_-b;let F=Qr(-Math.asin(li(e[2],-1,1))),O,V;return Math.hypot(e[5],e[8])<.001?(O=0,V=-Qr(Math.atan2(e[3],e[4]))):(O=Qr(e[5]===0&&e[8]===0?0:Math.atan2(e[5],e[8])),V=Qr(e[1]===0&&e[0]===0?0:Math.atan2(e[1],e[0]))),{roll:O,pitch:F+90,bearing:V}},k.bn=function(r,e){return r.roll==e.roll&&r.pitch==e.pitch&&r.bearing==e.bearing},k.bo=Ve,k.bp=yr,k.bq=ua,k.br=$l,k.bs=ha,k.bt=Bi,k.bu=Mr,k.bv=hi,k.bw=function(r,e,i,o,s){return Bi(o,s,li((r-e)/(i-e),0,1))},k.bx=function(r,e,i,o){return r[0]=e[0]+i[0]*o,r[1]=e[1]+i[1]*o,r[2]=e[2]+i[2]*o,r},k.by=Wi,k.bz=function(){return new Float64Array(3)},k.c=Dr,k.c$=Oo,k.c0=class extends ri{constructor(r,e){super(r,e),this.current=sr}set(r){if(r[12]!==this.current[12]||r[0]!==this.current[0])return this.current=r,void this.gl.uniformMatrix4fv(this.location,!1,r);for(let e=1;e<16;e++)if(r[e]!==this.current[e]){this.current=r,this.gl.uniformMatrix4fv(this.location,!1,r);break}}},k.c1=Ur,k.c2=class extends ri{constructor(r,e){super(r,e),this.current=[0,0,0]}set(r){r[0]===this.current[0]&&r[1]===this.current[1]&&r[2]===this.current[2]||(this.current=r,this.gl.uniform3f(this.location,r[0],r[1],r[2]))}},k.c3=class extends ri{constructor(r,e){super(r,e),this.current=[0,0]}set(r){r[0]===this.current[0]&&r[1]===this.current[1]||(this.current=r,this.gl.uniform2f(this.location,r[0],r[1]))}},k.c4=Xr,k.c5=function(r,e){var i=Math.sin(e),o=Math.cos(e);return r[0]=o,r[1]=i,r[2]=0,r[3]=-i,r[4]=o,r[5]=0,r[6]=0,r[7]=0,r[8]=1,r},k.c6=function(r,e,i){var o=e[0],s=e[1],l=e[2];return r[0]=o*i[0]+s*i[3]+l*i[6],r[1]=o*i[1]+s*i[4]+l*i[7],r[2]=o*i[2]+s*i[5]+l*i[8],r},k.c7=function(r,e,i,o,s,l,h){var d=1/(e-i),g=1/(o-s),m=1/(l-h);return r[0]=-2*d,r[1]=0,r[2]=0,r[3]=0,r[4]=0,r[5]=-2*g,r[6]=0,r[7]=0,r[8]=0,r[9]=0,r[10]=2*m,r[11]=0,r[12]=(e+i)*d,r[13]=(s+o)*g,r[14]=(h+l)*m,r[15]=1,r},k.c8=class extends ri{constructor(r,e){super(r,e),this.current=new Array}set(r){if(r!=this.current){this.current=r;let e=new Float32Array(4*r.length);for(let i=0;i25||o<0||o>=1||i<0||i>=1)},k.cE=function(r,e){return r[0]=e[0],r[1]=0,r[2]=0,r[3]=0,r[4]=0,r[5]=e[1],r[6]=0,r[7]=0,r[8]=0,r[9]=0,r[10]=e[2],r[11]=0,r[12]=0,r[13]=0,r[14]=0,r[15]=1,r},k.cF=class extends Ys{},k.cG=kn,k.cH=function(r,e){Dr.REGISTERED_PROTOCOLS[r]=e},k.cI=function(r){delete Dr.REGISTERED_PROTOCOLS[r]},k.cJ=function(r,e){let i={};for(let s=0;sfe*Vt))}let ae=g?"center":s.get("text-justify").evaluate(_,{},r.canonical),le=s.get("symbol-placement")==="point"?s.get("text-max-width").evaluate(_,{},r.canonical)*Vt:1/0,ne=()=>{r.bucket.allowVerticalPlacement&&bl(V)&&(A.vertical=wh(D,r.glyphMap,r.glyphPositions,r.imagePositions,T,le,d,re,"left",J,R,k.ax.vertical,!0,I,b))};if(!g&&te){let ie=new Set;if(ae==="auto")for(let xe=0;xeg_(d,g,l)),o.layers[h])})(r,i,e),i.finish()},k.cT=function(r,e,i,o,s,l){let h=Pf(r,e,i,s,0);return h=Pf(h,e,o,l,1),h},k.cU=class{constructor(r){this.maxEntries=r,this.map=new Map}get(r){let e=this.map.get(r);return e!==void 0&&(this.map.delete(r),this.map.set(r,e)),e}set(r,e){if(this.map.has(r))this.map.delete(r);else if(this.map.size>=this.maxEntries){let i=this.map.keys().next().value;this.map.delete(i)}this.map.set(r,e)}clear(){this.map.clear()}},k.cV=Wd,k.cW=bh,k.cX=vf,k.cY=function(r,e,i,o,s){return p(this,void 0,void 0,(function*(){if(Ii())try{return yield Ra(r,e,i,o,s)}catch{}return(function(l,h,d,g,m){let v=l.width,_=l.height;Cr&&Rn||(Cr=new OffscreenCanvas(v,_),Rn=Cr.getContext("2d",{willReadFrequently:!0})),Cr.width=v,Cr.height=_,Rn.drawImage(l,0,0,v,_);let T=Rn.getImageData(h,d,g,m);return Rn.clearRect(0,0,v,_),T.data})(r,e,i,o,s)}))},k.cZ=Ld,k.c_=class{constructor(r,e){this.layers={[tc]:this},this.name=tc,this.version=e?e.version:1,this.extent=e?e.extent:4096,this.length=r.length,this.features=r}feature(r){return new m_(this.features[r],this.extent)}},k.ca=class extends wn{},k.cb=pg,k.cc=class extends rs{},k.cd=mu,k.ce=function(r){return r<=1?1:Math.pow(2,Math.ceil(Math.log(r)/Math.LN2))},k.cf=Dd,k.cg=function(r,e,i){var o=e[0],s=e[1],l=e[2],h=i[3]*o+i[7]*s+i[11]*l+i[15];return r[0]=(i[0]*o+i[4]*s+i[8]*l+i[12])/(h=h||1),r[1]=(i[1]*o+i[5]*s+i[9]*l+i[13])/h,r[2]=(i[2]*o+i[6]*s+i[10]*l+i[14])/h,r},k.ch=class extends Ks{},k.ci=class extends t{},k.cj=function(r,e){return r[0]===e[0]&&r[1]===e[1]&&r[2]===e[2]&&r[3]===e[3]&&r[4]===e[4]&&r[5]===e[5]&&r[6]===e[6]&&r[7]===e[7]&&r[8]===e[8]&&r[9]===e[9]&&r[10]===e[10]&&r[11]===e[11]&&r[12]===e[12]&&r[13]===e[13]&&r[14]===e[14]&&r[15]===e[15]},k.ck=function(r,e){var i=r[0],o=r[1],s=r[2],l=r[3],h=r[4],d=r[5],g=r[6],m=r[7],v=r[8],_=r[9],T=r[10],b=r[11],I=r[12],M=r[13],A=r[14],D=r[15],L=e[0],R=e[1],F=e[2],O=e[3],V=e[4],Y=e[5],J=e[6],re=e[7],te=e[8],ae=e[9],le=e[10],ne=e[11],ie=e[12],fe=e[13],xe=e[14],ye=e[15];return Math.abs(i-L)<=pe*Math.max(1,Math.abs(i),Math.abs(L))&&Math.abs(o-R)<=pe*Math.max(1,Math.abs(o),Math.abs(R))&&Math.abs(s-F)<=pe*Math.max(1,Math.abs(s),Math.abs(F))&&Math.abs(l-O)<=pe*Math.max(1,Math.abs(l),Math.abs(O))&&Math.abs(h-V)<=pe*Math.max(1,Math.abs(h),Math.abs(V))&&Math.abs(d-Y)<=pe*Math.max(1,Math.abs(d),Math.abs(Y))&&Math.abs(g-J)<=pe*Math.max(1,Math.abs(g),Math.abs(J))&&Math.abs(m-re)<=pe*Math.max(1,Math.abs(m),Math.abs(re))&&Math.abs(v-te)<=pe*Math.max(1,Math.abs(v),Math.abs(te))&&Math.abs(_-ae)<=pe*Math.max(1,Math.abs(_),Math.abs(ae))&&Math.abs(T-le)<=pe*Math.max(1,Math.abs(T),Math.abs(le))&&Math.abs(b-ne)<=pe*Math.max(1,Math.abs(b),Math.abs(ne))&&Math.abs(I-ie)<=pe*Math.max(1,Math.abs(I),Math.abs(ie))&&Math.abs(M-fe)<=pe*Math.max(1,Math.abs(M),Math.abs(fe))&&Math.abs(A-xe)<=pe*Math.max(1,Math.abs(A),Math.abs(xe))&&Math.abs(D-ye)<=pe*Math.max(1,Math.abs(D),Math.abs(ye))},k.cl=function(r,e){return r[0]=e[0],r[1]=e[1],r[2]=e[2],r[3]=e[3],r[4]=e[4],r[5]=e[5],r[6]=e[6],r[7]=e[7],r[8]=e[8],r[9]=e[9],r[10]=e[10],r[11]=e[11],r[12]=e[12],r[13]=e[13],r[14]=e[14],r[15]=e[15],r},k.cm=r=>r.type==="circle",k.cn=r=>r.type==="heatmap",k.co=r=>r.type==="line",k.cp=r=>r.type==="fill",k.cq=r=>r.type==="fill-extrusion",k.cr=r=>r.type==="hillshade",k.cs=r=>r.type==="color-relief",k.ct=r=>r.type==="background",k.cu=r=>r.type==="custom",k.cv=Yr,k.cw=function(r,e,i){if(e<=0)return r;let o=1/e;return i===void 0||Math.abs(i)<1e-10?Math.round(r*o)/o:(i>0?Math.ceil(r*o-1e-9):Math.floor(r*o+1e-10))/o},k.cx=function(r,e,i){let o=Ke(e.x-i.x,e.y-i.y),s=Ke(r.x-i.x,r.y-i.y);var l,h;return Qr(Math.atan2(o[0]*s[1]-o[1]*s[0],(l=o)[0]*(h=s)[0]+l[1]*h[1]))},k.cy=yo,k.cz=function(r,e){var i;if(!La[e])return!1;let o=r?.target,s=((i=o?.ownerDocument)===null||i===void 0?void 0:i.defaultView)||window;return r instanceof s.MouseEvent||r instanceof s.WheelEvent},k.d=xt,k.d0=class{constructor(r,e){let i=(e=this.options=Object.assign({},ig,e)).debug;if(i&&console.time("preprocess data"),e.maxZoom<0||e.maxZoom>24)throw new Error("maxZoom should be in the 0-24 range");if(e.promoteId&&e.generateId)throw new Error("promoteId and generateId cannot be used together.");let o=Mu(r,e);i&&(console.timeEnd("preprocess data"),console.log("index: maxZoom: %d, maxPoints: %d",e.indexMaxZoom,e.indexMaxPoints),console.time("generate tiles")),o=Du(o,e),e.updateable&&(this.source=o),this.initializeIndex(o,e)}initializeIndex(r,e){this.tileIndex=e.cluster?new Xm(e.clusterOptions):new tg(e),r.length&&this.tileIndex.initialize(r)}getTile(r,e,i){return e=+e,i=+i,(r=+r)<0||r>24?null:this.tileIndex.getTile(r,e,i)}updateData(r,e){let i=this.options;if(!i.updateable)throw new Error("to update tile geojson `updateable` option must be set to true");let{affected:o,source:s}=(function(l,h,d){let g=(function(v,_){return v?{removeAll:v.removeAll,remove:new Set(v.remove||[]),add:new Map(v.add?.map((T=>[_.promoteId?T.properties[_.promoteId]:T.id,T]))),update:new Map(v.update?.map((T=>[T.id,T])))}:{remove:new Set,add:new Map,update:new Map}})(h,d),m=[];if(g.removeAll&&(m=l,l=[]),g.remove.size||g.add.size){let v=[];for(let _ of l)(g.remove.has(_.id)||g.add.has(_.id))&&v.push(_);if(v.length){m.push(...v);let _=new Set(v.map((T=>T.id)));l=l.filter((T=>!_.has(T.id)))}if(g.add.size){let _=Mu({type:"FeatureCollection",features:Array.from(g.add.values())},d);_=Du(_,d),m.push(..._),l.push(..._)}}if(g.update.size){let v=new Map,_=[];for(let T of l)g.update.has(T.id)?v.set(T.id,[...v.get(T.id)||[],T]):_.push(T);for(let[T,b]of g.update){let I=v.get(T);if(!I||I.length===0)continue;let M=Hm(I,b,d);m.push(...I,...M),_.push(...M)}l=_}return{affected:m,source:l}})(this.source,r,i);e&&({affected:o,source:s}=this.filterUpdate(s,o,e)),o.length&&(this.source=s,this.tileIndex.updateIndex(s,o,i))}filterUpdate(r,e,i){let o=new Set;for(let s of r)s.id!=null&&(i(_h(s))||(e.push(s),o.add(s.id)));return{affected:e,source:r=r.filter((s=>!o.has(s.id)))}}getData(){if(!this.options.updateable)throw new Error("to retrieve data the `updateable` option must be set to true");return{type:"FeatureCollection",features:this.source.map((r=>_h(r)))}}updateClusterOptions(r,e){let i=this.options.cluster;this.options.cluster=r,this.options.clusterOptions=e,i!=r?this.initializeIndex(this.source,this.options):this.tileIndex.updateIndex(this.source,[],this.options)}getClusterExpansionZoom(r){return this.tileIndex.getClusterExpansionZoom(r)}getClusterChildren(r){return this.tileIndex.getChildren(r)}getClusterLeaves(r,e,i){return this.tileIndex.getLeaves(r,e,i)}},k.d1=gr,k.e=Oi,k.f=Hi,k.g=hr,k.h=r=>p(void 0,void 0,void 0,(function*(){if(r.byteLength===0)return createImageBitmap(new ImageData(1,1));let e=new Blob([new Uint8Array(r)],{type:"image/png"});try{return createImageBitmap(e)}catch(i){throw new Error(`Could not load image because of ${xt(i).message}. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported.`)}})),k.i=Ht,k.j=r=>new Promise(((e,i)=>{let o=new Image;o.onload=()=>{e(o),URL.revokeObjectURL(o.src),o.onload=null,window.requestAnimationFrame((()=>o.src=za))},o.onerror=()=>i(new Error("Could not load image. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported."));let s=new Blob([new Uint8Array(r)],{type:"image/png"});o.src=r.byteLength?URL.createObjectURL(s):za})),k.k=(r,e)=>en(Oi(r,{type:"json"}),e),k.l=Fn,k.m=en,k.n=bo,k.o=(r,e)=>en(Oi(r,{type:"arrayBuffer"}),e),k.p=Tp,k.q=function(r){return new bh(r).readFields(Eg,[])},k.r=function(r){return/[\u02EA\u02EB\u1100-\u11FF\u2E80-\u2FDF\u3000-\u30FF\u3105-\u312F\u3131-\u318E\u31A0-\u4DBF\u4E00-\uA48C\uA490-\uA4C6\uA960-\uA97C\uAC00-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFE10-\uFE1F\uFE30-\uFE4F\uFF00-\uFFEF]|\uD81B[\uDFE0-\uDFFF]|[\uD81C-\uD822\uD840-\uD868\uD86A-\uD86D\uD86F-\uD872\uD874-\uD879\uD880-\uD883\uD885-\uD88C][\uDC00-\uDFFF]|\uD823[\uDC00-\uDCD5\uDCFF-\uDD1E\uDD80-\uDDF2]|\uD82B[\uDFF0-\uDFFF]|\uD82C[\uDC00-\uDEFB]|\uD83C[\uDE00-\uDEFF]|\uD869[\uDC00-\uDEDF\uDF00-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEAD\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0\uDFF0-\uDFFF]|\uD87B[\uDC00-\uDE5D]|\uD87E[\uDC00-\uDE1D]|\uD884[\uDC00-\uDF4A\uDF50-\uDFFF]|\uD88D[\uDC00-\uDC79]/gim.test(String.fromCodePoint(r))},k.s=us,k.t=Nl,k.u=ui,k.v=qo,k.w=Wt,k.x=ce,k.y=Ml,k.z=zi})),Zt("worker",["./shared"],(function(k){"use strict";class p{constructor(W,K){this.keyCache={},W&&this.replace(W,K)}replace(W,K){this._layerConfigs={},this._layers={},this.update(W,[],K)}update(W,K,ee){for(let Me of W){this._layerConfigs[Me.id]=Me;let Ze=this._layers[Me.id]=k.bT(Me,ee);Ze._featureFilter=k.ah(Ze.filter,ee),this.keyCache[Me.id]&&delete this.keyCache[Me.id]}for(let Me of K)delete this.keyCache[Me],delete this._layerConfigs[Me],delete this._layers[Me];this.familiesBySource={};let ge=k.cJ(Object.values(this._layerConfigs),this.keyCache);for(let Me of ge){let Ze=Me.map((vt=>this._layers[vt.id])),ze=Ze[0];if(ze.isHidden())continue;let $e=ze.source||"",Be=this.familiesBySource[$e];Be||(Be=this.familiesBySource[$e]={});let Ke=ze.sourceLayer||k.ag,De=Be[Ke];De||(De=Be[Ke]=[]),De.push(Ze)}}}class Te{constructor(W){let K={},ee=[];for(let ze in W){let $e=W[ze],Be=K[ze]={};for(let Ke in $e){let De=$e[+Ke];if(!De||De.bitmap.width===0||De.bitmap.height===0)continue;let vt={x:0,y:0,w:De.bitmap.width+2,h:De.bitmap.height+2};ee.push(vt),Be[Ke]={rect:vt,metrics:De.metrics}}}let{w:ge,h:Me}=k.p(ee),Ze=new k.t({width:ge||1,height:Me||1});for(let ze in W){let $e=W[ze];for(let Be in $e){let Ke=$e[+Be];if(!Ke||Ke.bitmap.width===0||Ke.bitmap.height===0)continue;let De=K[ze][Be].rect;k.t.copy(Ke.bitmap,Ze,{x:0,y:0},{x:De.x+1,y:De.y+1},Ke.bitmap)}}this.image=Ze,this.positions=K}}k.cK("GlyphAtlas",Te);class Sr{constructor(W){this.tileID=new k.a3(W.tileID.overscaledZ,W.tileID.wrap,W.tileID.canonical.z,W.tileID.canonical.x,W.tileID.canonical.y),this.uid=W.uid,this.zoom=W.zoom,this.pixelRatio=W.pixelRatio,this.tileSize=W.tileSize,this.source=W.source,this.overscaling=this.tileID.overscaleFactor(),this.showCollisionBoxes=W.showCollisionBoxes,this.collectResourceTiming=!!W.collectResourceTiming,this.returnDependencies=!!W.returnDependencies,this.promoteId=W.promoteId,this.inFlightDependencies=[]}parse(W,K,ee,ge,Me){return k._(this,void 0,void 0,(function*(){this.status="parsing",this.data=W,this.collisionBoxArray=new k.ae;let Ze=new k.cL(Object.keys(W.layers).sort()),ze=new k.cM(this.tileID,this.promoteId);ze.bucketLayerIDs=[];let $e={},Be={featureIndex:ze,iconDependencies:{},patternDependencies:{},glyphDependencies:{},dashDependencies:{},availableImages:ee,subdivisionGranularity:Me},Ke=K.familiesBySource[this.source];for(let Re in Ke){let Bt=W.layers[Re];if(!Bt)continue;Bt.version===1&&k.w(`Vector tile source "${this.source}" layer "${Re}" does not use vector tile spec v2 and therefore may have some rendering errors.`);let Wt=Ze.encode(Re),Mi=[];for(let Ht=0;HtJr.id))))}}let De=k.bY(Be.glyphDependencies,(Re=>Object.keys(Re).map(Number)));for(let Re of this.inFlightDependencies)Re?.abort();this.inFlightDependencies=[];let vt=Promise.resolve({});if(Object.keys(De).length){let Re=new AbortController;this.inFlightDependencies.push(Re),vt=ge.sendAsync({type:"GG",data:{stacks:De,source:this.source,tileID:this.tileID,type:"glyphs"}},Re)}let xt=Object.keys(Be.iconDependencies),Wi=Promise.resolve({});if(xt.length){let Re=new AbortController;this.inFlightDependencies.push(Re),Wi=ge.sendAsync({type:"GI",data:{icons:xt,source:this.source,tileID:this.tileID,type:"icons"}},Re)}let Bi=Object.keys(Be.patternDependencies),Mr=Promise.resolve({});if(Bi.length){let Re=new AbortController;this.inFlightDependencies.push(Re),Mr=ge.sendAsync({type:"GI",data:{icons:Bi,source:this.source,tileID:this.tileID,type:"patterns"}},Re)}let Yr=Be.dashDependencies,yo=Promise.resolve({});if(Object.keys(Yr).length){let Re=new AbortController;this.inFlightDependencies.push(Re),yo=ge.sendAsync({type:"GDA",data:{dashes:Yr}},Re)}let[li,zn,Oi,vo]=yield Promise.all([vt,Wi,Mr,yo]),Er=new Te(li),Kr=new k.cN(zn,Oi);for(let Re in $e){let Bt=$e[Re];Bt instanceof k.af?(Si(Bt.layers,this.zoom,ee),k.cO({bucket:Bt,glyphMap:li,glyphPositions:Er.positions,imageMap:zn,imagePositions:Kr.iconPositions,showCollisionBoxes:this.showCollisionBoxes,canonical:this.tileID.canonical,subdivisionGranularity:Be.subdivisionGranularity})):Bt.hasDependencies&&(Bt instanceof k.cP||Bt instanceof k.cQ||Bt instanceof k.cR)&&(Si(Bt.layers,this.zoom,ee),Bt.addFeatures(Be,this.tileID.canonical,Kr.patternPositions,vo))}return this.status="done",{buckets:Object.values($e).filter((Re=>!Re.isEmpty())),featureIndex:ze,collisionBoxArray:this.collisionBoxArray,glyphAtlasImage:Er.image,imageAtlas:Kr,dashPositions:vo,glyphMap:this.returnDependencies?li:null,iconMap:this.returnDependencies?zn:null,glyphPositions:this.returnDependencies?Er.positions:null}}))}}function Si(We,W,K){let ee=new k.J(W);for(let ge of We)ge.recalculate(ee,K)}class Wr{constructor(){this.loading={},this.loaded={},this.parsing={}}startLoading(W,K){this.loading[W]=K}finishLoading(W){delete this.loading[W]}abort(W){let K=this.loading[W];K?.abort&&(K.abort.abort(),delete this.loading[W])}setParsing(W,K){this.parsing[W]=K}consumeParsing(W){let K=this.parsing[W];if(K)return delete this.parsing[W],K}clearParsing(W){delete this.parsing[W]}markLoaded(W,K){this.loaded[W]=K}getLoaded(W){let K=this.loaded[W];if(K)return K}removeLoaded(W){delete this.loaded[W]}clearLoaded(){this.loaded={}}}class An{constructor(W){this.start=`${W}#start`,this.end=`${W}#end`,this.measure=W,performance.mark(this.start)}finish(){performance.mark(this.end);let W=performance.getEntriesByName(this.measure);return W.length===0&&(performance.measure(this.measure,this.start,this.end),W=performance.getEntriesByName(this.measure),performance.clearMarks(this.start),performance.clearMarks(this.end),performance.clearMeasures(this.measure)),W}}class qt{constructor(W,K,ee,ge,Me){this.type=W,this.properties=ee||{},this.extent=Me,this.pointsArray=K,this.id=ge}loadGeometry(){return this.pointsArray.map((W=>W.map((K=>new k.P(K.x,K.y)))))}}class Ir{constructor(W,K,ee){this.version=2,this._myFeatures=W,this.name=K,this.length=W.length,this.extent=ee}feature(W){return this._myFeatures[W]}}class Xe{constructor(){this.layers={}}addLayer(W){this.layers[W.name]=W}}function Hr(We){let W=k.cS(We);return W.byteOffset===0&&W.byteLength===W.buffer.byteLength||(W=new Uint8Array(W)),{vectorTile:We,rawData:W.buffer}}function Ii(We,W,K){let{extent:ee}=We,ge=Math.pow(2,K.z-W.z),Me=(K.x-W.x*ge)*ee,Ze=(K.y-W.y*ge)*ee,ze=[];for(let $e=0;$e0&&Ke.addLayer(Bi)}let vt=Hr(Ke);return this.overzoomedTileResultCache.set($e,vt),vt}reloadTile(W){return k._(this,void 0,void 0,(function*(){let K=W.uid,ee=this.tileState.getLoaded(K);if(!ee)throw new Error("Should not be trying to reload a tile that was never loaded or has been removed");if(ee.showCollisionBoxes=W.showCollisionBoxes,ee.status==="parsing"){let ge=this.tileState.consumeParsing(K);return yield this._parseWorkerTile(ee,W,ge)}if(ee.status==="done"&&ee.vectorTile)return yield this._parseWorkerTile(ee,W)}))}abortTile(W){return k._(this,void 0,void 0,(function*(){this.tileState.abort(W.uid)}))}removeTile(W){return k._(this,void 0,void 0,(function*(){this.tileState.removeLoaded(W.uid)}))}}class kt{constructor(){this.loaded={}}loadTile(W){return k._(this,void 0,void 0,(function*(){let{uid:K,encoding:ee,rawImageData:ge,redFactor:Me,greenFactor:Ze,blueFactor:ze,baseShift:$e}=W,Be=ge.width+2,Ke=ge.height+2,De=k.b(ge)?new k.R({width:Be,height:Ke},yield k.cY(ge,-1,-1,Be,Ke)):ge,vt=new k.cZ(K,De,ee,Me,Ze,ze,$e);return this.loaded||(this.loaded={}),this.loaded[K]=vt,vt}))}removeTile(W){let K=this.loaded,ee=W.uid;K?.[ee]&&delete K[ee]}}class Xr{constructor(W,K,ee,ge=Dn){this.actor=W,this.layerIndex=K,this.availableImages=ee,this.tileState=new Wr,this._createGeoJSONIndex=ge}loadVectorTile(W){if(!this._geoJSONIndex)throw new Error("Unable to parse the data into a cluster or geojson");let{z:K,x:ee,y:ge}=W.tileID.canonical,Me=this._geoJSONIndex.getTile(K,ee,ge);return Me?Hr(new k.c_(Me.features,{version:2,extent:k.a6})):null}loadTile(W){return k._(this,void 0,void 0,(function*(){let{uid:K}=W,ee=new Sr(W);ee.abort=new AbortController;try{let ge=this.loadVectorTile(W);if(!ge)return null;let{vectorTile:Me,rawData:Ze}=ge;ee.vectorTile=Me,this.tileState.markLoaded(K,ee);let ze={rawData:Ze};this.tileState.setParsing(K,ze);try{return yield this._parseWorkerTile(ee,W,ze)}finally{this.tileState.clearParsing(K)}}catch(ge){throw ee.status="done",this.tileState.markLoaded(K,ee),ge}}))}_reloadLoadedTile(W){return k._(this,void 0,void 0,(function*(){let K=W.uid,ee=this.tileState.getLoaded(K);if(!ee)throw new Error("Should not be trying to reload a tile that was never loaded or has been removed");if(ee.showCollisionBoxes=W.showCollisionBoxes,ee.status==="parsing"){let ge=this.tileState.consumeParsing(K);return yield this._parseWorkerTile(ee,W,ge)}if(ee.status==="done"&&ee.vectorTile)return yield this._parseWorkerTile(ee,W)}))}_parseWorkerTile(W,K,ee){return k._(this,void 0,void 0,(function*(){let ge=yield W.parse(W.vectorTile,this.layerIndex,this.availableImages,this.actor,K.subdivisionGranularity);if(ee){let{rawData:Me}=ee;ge=k.e({rawTileData:Me.slice(0),encoding:"mvt"},ge)}return ge}))}abortTile(W){return k._(this,void 0,void 0,(function*(){this.tileState.abort(W.uid)}))}removeTile(W){return k._(this,void 0,void 0,(function*(){this.tileState.removeLoaded(W.uid)}))}loadData(W){return k._(this,void 0,void 0,(function*(){var K;(K=this._pendingRequest)===null||K===void 0||K.abort();let ee=this._startRequestTiming(W);this._pendingRequest=new AbortController;try{yield this.loadAndProcessGeoJSON(W,this._pendingRequest),delete this._pendingRequest,this.tileState.clearLoaded();let ge={};return W.request&&(ge.data=W.data),this._finishRequestTiming(ee,W,ge),ge}catch(ge){if(delete this._pendingRequest,!k.$(ge))throw ge;return{abandoned:!0}}}))}_startRequestTiming(W){var K;if(!((K=W.request)===null||K===void 0)&&K.collectResourceTiming)return new An(W.request.url)}_finishRequestTiming(W,K,ee){let ge=W?.finish();ge&&(ee.resourceTiming={[K.source]:JSON.parse(JSON.stringify(ge))})}reloadTile(W){return this.tileState.getLoaded(W.uid)?this._reloadLoadedTile(W):this.loadTile(W)}loadAndProcessGeoJSON(W,K){return k._(this,void 0,void 0,(function*(){var ee;if(W.request&&(W.data=(yield k.k(W.request,K)).data),W.data)return W.data=this._filterGeoJSON(W.data,W.filter),void(this._geoJSONIndex=this._createGeoJSONIndex(W.data,W));if(W.dataDiff)return(ee=this._geoJSONIndex)!==null&&ee!==void 0||(this._geoJSONIndex=this._createGeoJSONIndex({type:"FeatureCollection",features:[]},W)),void this._geoJSONIndex.updateData(W.dataDiff,this._getFilterPredicate(W.filter));if(W.updateCluster&&this._geoJSONIndex.updateClusterOptions(W.geojsonVtOptions.cluster,go(W)),this._geoJSONIndex==null)throw new Error(`Input data given to '${W.source}' is not a valid GeoJSON object.`)}))}_filterGeoJSON(W,K){if(W.type!=="FeatureCollection")return W;let ee=this._getFilterPredicate(K);return ee?{type:"FeatureCollection",features:W.features.filter((ge=>ee(ge)))}:W}_getFilterPredicate(W){if(typeof W!="boolean"&&!W?.length)return;let K=k.c$(W,{type:"boolean","property-type":"data-driven",overridable:!1,transition:!1});if(K.result==="error")throw new Error(K.value.map((ee=>`${ee.key}: ${ee.message}`)).join(", "));return ee=>K.value.evaluate({zoom:0},ee)}removeSource(W){return k._(this,void 0,void 0,(function*(){var K;(K=this._pendingRequest)===null||K===void 0||K.abort()}))}getClusterExpansionZoom(W){return this._geoJSONIndex.getClusterExpansionZoom(W.clusterId)}getClusterChildren(W){return this._geoJSONIndex.getClusterChildren(W.clusterId)}getClusterLeaves(W){return this._geoJSONIndex.getClusterLeaves(W.clusterId,W.limit,W.offset)}}function Dn(We,W){let K=k.e(W.geojsonVtOptions||{},{updateable:!0,clusterOptions:go(W)});return new k.d0(We,K)}function go({geojsonVtOptions:We,clusterProperties:W}){if(!W||!We.clusterOptions)return We.clusterOptions;let K={},ee={},ge={accumulated:null,zoom:0},Me={properties:null},Ze=Object.keys(W);for(let ze of Ze){let[$e,Be]=W[ze],Ke=k.c$(Be),De=k.c$(typeof $e=="string"?[$e,["accumulated"],["get",ze]]:$e);K[ze]=Ke.value,ee[ze]=De.value}return We.clusterOptions.map=ze=>{Me.properties=ze;let $e={};for(let Be of Ze)$e[Be]=K[Be].evaluate(ge,Me);return $e},We.clusterOptions.reduce=(ze,$e)=>{Me.properties=$e;for(let Be of Ze)ge.accumulated=ze[Be],ze[Be]=ee[Be].evaluate(ge,Me)},We.clusterOptions}class _o{constructor(W){this.self=W,this.actor=new k.N(W),this.layerIndexes={},this.availableImages={},this.workerSources={},this.demWorkerSources={},this.externalWorkerSourceTypes={},this.globalStates=new Map,this.self.registerWorkerSource=(K,ee)=>{if(this.externalWorkerSourceTypes[K])throw new Error(`Worker source with name "${K}" already registered.`);this.externalWorkerSourceTypes[K]=ee},this.self.addProtocol=k.cH,this.self.removeProtocol=k.cI,this.self.registerRTLTextPlugin=K=>{k.d1.setMethods(K)},this.self.makeRequest=k.m,this.actor.registerMessageHandler("LDT",((K,ee)=>this._getDEMWorkerSource(K,ee.source).loadTile(ee))),this.actor.registerMessageHandler("RDT",((K,ee)=>k._(this,void 0,void 0,(function*(){this._getDEMWorkerSource(K,ee.source).removeTile(ee)})))),this.actor.registerMessageHandler("GCEZ",((K,ee)=>k._(this,void 0,void 0,(function*(){return this._getWorkerSource(K,ee.type,ee.source).getClusterExpansionZoom(ee)})))),this.actor.registerMessageHandler("GCC",((K,ee)=>k._(this,void 0,void 0,(function*(){return this._getWorkerSource(K,ee.type,ee.source).getClusterChildren(ee)})))),this.actor.registerMessageHandler("GCL",((K,ee)=>k._(this,void 0,void 0,(function*(){return this._getWorkerSource(K,ee.type,ee.source).getClusterLeaves(ee)})))),this.actor.registerMessageHandler("LD",((K,ee)=>this._getWorkerSource(K,ee.type,ee.source).loadData(ee))),this.actor.registerMessageHandler("LT",((K,ee)=>this._getWorkerSource(K,ee.type,ee.source).loadTile(ee))),this.actor.registerMessageHandler("RT",((K,ee)=>this._getWorkerSource(K,ee.type,ee.source).reloadTile(ee))),this.actor.registerMessageHandler("AT",((K,ee)=>this._getWorkerSource(K,ee.type,ee.source).abortTile(ee))),this.actor.registerMessageHandler("RMT",((K,ee)=>this._getWorkerSource(K,ee.type,ee.source).removeTile(ee))),this.actor.registerMessageHandler("RS",((K,ee)=>k._(this,void 0,void 0,(function*(){var ge,Me;if(!(!((Me=(ge=this.workerSources[K])===null||ge===void 0?void 0:ge[ee.type])===null||Me===void 0)&&Me[ee.source]))return;let Ze=this.workerSources[K][ee.type][ee.source];delete this.workerSources[K][ee.type][ee.source],Ze.removeSource!==void 0&&Ze.removeSource(ee)})))),this.actor.registerMessageHandler("RM",(K=>k._(this,void 0,void 0,(function*(){delete this.layerIndexes[K],delete this.availableImages[K],delete this.workerSources[K],delete this.demWorkerSources[K],this.globalStates.delete(K)})))),this.actor.registerMessageHandler("SR",((K,ee)=>k._(this,void 0,void 0,(function*(){this.referrer=ee})))),this.actor.registerMessageHandler("SRPS",((K,ee)=>this._syncRTLPluginState(K,ee))),this.actor.registerMessageHandler("IS",((K,ee)=>k._(this,void 0,void 0,(function*(){this.self.importScripts(ee)})))),this.actor.registerMessageHandler("SI",((K,ee)=>this._setImages(K,ee))),this.actor.registerMessageHandler("UL",((K,ee)=>k._(this,void 0,void 0,(function*(){this._getLayerIndex(K).update(ee.layers,ee.removedIds,this._getGlobalState(K))})))),this.actor.registerMessageHandler("UGS",((K,ee)=>k._(this,void 0,void 0,(function*(){let ge=this._getGlobalState(K);for(let Me in ee)ge[Me]=ee[Me]})))),this.actor.registerMessageHandler("SL",((K,ee)=>k._(this,void 0,void 0,(function*(){this._getLayerIndex(K).replace(ee,this._getGlobalState(K))}))))}_getGlobalState(W){let K=this.globalStates.get(W);return K||(K={},this.globalStates.set(W,K)),K}_setImages(W,K){return k._(this,void 0,void 0,(function*(){this.availableImages[W]=K;for(let ee in this.workerSources[W]){let ge=this.workerSources[W][ee];for(let Me in ge)ge[Me].availableImages=K}}))}_syncRTLPluginState(W,K){return k._(this,void 0,void 0,(function*(){return yield k.d1.syncState(K,this.self.importScripts)}))}_getAvailableImages(W){let K=this.availableImages[W];return K||(K=[]),K}_getLayerIndex(W){let K=this.layerIndexes[W];return K||(K=this.layerIndexes[W]=new p),K}_getWorkerSource(W,K,ee){var ge,Me;if((ge=this.workerSources)[W]||(ge[W]={}),(Me=this.workerSources[W])[K]||(Me[K]={}),!this.workerSources[W][K][ee]){let Ze={sendAsync:(ze,$e)=>(ze.targetMapId=W,this.actor.sendAsync(ze,$e))};switch(K){case"vector":this.workerSources[W][K][ee]=new pe(Ze,this._getLayerIndex(W),this._getAvailableImages(W));break;case"geojson":this.workerSources[W][K][ee]=new Xr(Ze,this._getLayerIndex(W),this._getAvailableImages(W));break;default:this.workerSources[W][K][ee]=new this.externalWorkerSourceTypes[K](Ze,this._getLayerIndex(W),this._getAvailableImages(W))}}return this.workerSources[W][K][ee]}_getDEMWorkerSource(W,K){var ee,ge;return(ee=this.demWorkerSources)[W]||(ee[W]={}),(ge=this.demWorkerSources[W])[K]||(ge[K]=new kt),this.demWorkerSources[W][K]}}return k.i(self)&&(self.worker=new _o(self)),_o})),Zt("index",["exports","./shared"],(function(k,p){"use strict";var Te="5.24.0";function Sr(){var u=new p.A(4);return p.A!=Float32Array&&(u[1]=0,u[2]=0),u[0]=1,u[3]=1,u}let Si,Wr,An,qt={frame(u,t,n,a){let c=a||window,f=c.requestAnimationFrame((x=>{y(),t(x)})),{unsubscribe:y}=p.s(u.signal,"abort",(()=>{y(),c.cancelAnimationFrame(f),n(new p.a(u.signal.reason))}),!1)},frameAsync(u,t){return new Promise(((n,a)=>{this.frame(u,n,a,t)}))},getImageData(u,t=0){return this.getImageCanvasContext(u).getImageData(-t,-t,u.width+2*t,u.height+2*t)},getImageCanvasContext(u){let t=window.document.createElement("canvas"),n=t.getContext("2d",{willReadFrequently:!0});if(!n)throw new Error("failed to create canvas 2d context");return t.width=u.width,t.height=u.height,n.drawImage(u,0,0,u.width,u.height),n},resolveURL:u=>(Si||(Si=document.createElement("a")),Si.href=u,Si.href),hardwareConcurrency:typeof navigator<"u"&&navigator.hardwareConcurrency||4,get prefersReducedMotion(){return An!==void 0?An:!!matchMedia&&(Wr!=null||(Wr=matchMedia("(prefers-reduced-motion: reduce)")),Wr.matches)},set prefersReducedMotion(u){An=u}},Ir=new class{constructor(){this._frozenAt=null}getCurrentTime(){return this._frozenAt!==null?this._frozenAt:performance.now()}setNow(u){this._frozenAt=u}restoreNow(){this._frozenAt=null}isFrozen(){return this._frozenAt!==null}};function Xe(){return Ir.getCurrentTime()}var Hr,Ii;class pe{static create(t,n,a){let c=window.document.createElement(t);return n!==void 0&&(c.className=n),a&&a.appendChild(c),c}static createNS(t,n){return window.document.createElementNS(t,n)}static disableDrag(){pe.docStyle&&pe.selectProp&&(pe.userSelect=pe.docStyle[pe.selectProp],pe.docStyle[pe.selectProp]="none")}static enableDrag(){pe.docStyle&&pe.selectProp&&(pe.docStyle[pe.selectProp]=pe.userSelect)}static suppressClickInternal(t){t.preventDefault(),t.stopPropagation(),window.removeEventListener("click",pe.suppressClickInternal,!0)}static suppressClick(){window.addEventListener("click",pe.suppressClickInternal,!0),window.setTimeout((()=>{window.removeEventListener("click",pe.suppressClickInternal,!0)}),0)}static getScale(t){let n=t.getBoundingClientRect();return{x:n.width/t.offsetWidth||1,y:n.height/t.offsetHeight||1,boundingClientRect:n}}static getPoint(t,n,a){let c=n.boundingClientRect;return new p.P((a.clientX-c.left)/n.x-t.clientLeft,(a.clientY-c.top)/n.y-t.clientTop)}static mousePos(t,n){let a=pe.getScale(t);return pe.getPoint(t,a,n)}static touchPos(t,n){let a=[],c=pe.getScale(t);for(let f of n)a.push(pe.getPoint(t,c,f));return a}static sanitize(t){let n=new DOMParser().parseFromString(t,"text/html").body||document.createElement("body"),a=n.querySelectorAll("script");for(let c of a)c.remove();return pe.clean(n),n.innerHTML}static isPossiblyDangerous(t,n){let a=n.replace(/\s+/g,"").toLowerCase();return!(!["src","href","xlink:href"].includes(t)||!a.includes("javascript:")&&!a.includes("data:"))||!!t.startsWith("on")||void 0}static clean(t){let n=t.children;for(let a of n)pe.removeAttributes(a),pe.clean(a)}static removeAttributes(t){for(let{name:n,value:a}of t.attributes)pe.isPossiblyDangerous(n,a)&&t.removeAttribute(n)}}pe.docStyle=typeof window<"u"&&((Hr=window.document)===null||Hr===void 0?void 0:Hr.documentElement.style),pe.selectProp=!pe.docStyle||"userSelect"in pe.docStyle?"userSelect":"webkitUserSelect",(function(u){let t,n,a,c;u.resetRequestQueue=()=>{t=[],n=0,a=0,c={}},u.addThrottleControl=w=>{let P=a++;return c[P]=w,P},u.removeThrottleControl=w=>{delete c[w],y()},u.getImage=(w,P,S=!0)=>new Promise(((E,C)=>{w.headers||(w.headers={}),w.headers.accept="image/webp,*/*",p.e(w,{type:"image"}),t.push({abortController:P,requestParameters:w,supportImageRefresh:S,state:"queued",onError:z=>{C(z)},onSuccess:z=>{E(z)}}),y()}));let f=w=>p._(this,void 0,void 0,(function*(){w.state="running";let{requestParameters:P,supportImageRefresh:S,onError:E,onSuccess:C,abortController:z}=w,B=S===!1&&!p.i(self)&&!p.g(P.url)&&(!P.headers||Object.keys(P.headers).reduce(((j,$)=>j&&$==="accept"),!0));n++;let N=B?x(P,z):p.m(P,z);try{let j=yield N;delete w.abortController,w.state="completed",j.data instanceof HTMLImageElement||p.b(j.data)?C(j):j.data&&C({data:yield(G=j.data,typeof createImageBitmap=="function"?p.h(G):p.j(G)),cacheControl:j.cacheControl,expires:j.expires})}catch(j){delete w.abortController,E(p.d(j))}finally{n--,y()}var G})),y=()=>{let w=(()=>{for(let P of Object.keys(c))if(c[P]())return!0;return!1})()?p.c.MAX_PARALLEL_IMAGE_REQUESTS_PER_FRAME:p.c.MAX_PARALLEL_IMAGE_REQUESTS;for(let P=n;P0;P++){let S=t.shift();S.abortController.signal.aborted?P--:f(S)}},x=(w,P)=>new Promise(((S,E)=>{let C=new Image,z=w.url,B=w.credentials;B&&B==="include"?C.crossOrigin="use-credentials":(B&&B==="same-origin"||!p.f(z))&&(C.crossOrigin="anonymous"),P.signal.addEventListener("abort",(()=>{C.src="",E(new p.a(P.signal.reason))})),C.fetchPriority="high",C.onload=()=>{C.onerror=C.onload=null,S({data:C})},C.onerror=()=>{C.onerror=C.onload=null,P.signal.aborted||E(new Error("Could not load image. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported."))},C.src=z}))})(Ii||(Ii={})),Ii.resetRequestQueue();class kt{constructor(t){this._transformRequestFn=t??null}transformRequest(t,n){return this._transformRequestFn&&this._transformRequestFn(t,n)||{url:t}}setTransformRequest(t){this._transformRequestFn=t}}function Xr(u){let t=[];if(typeof u=="string")t.push({id:"default",url:u});else if(u&&u.length>0){let n=[];for(let{id:a,url:c}of u){let f=`${a}${c}`;n.includes(f)||(n.push(f),t.push({id:a,url:c}))}}return t}function Dn(u,t,n){try{let a=new URL(u);return a.pathname+=`${t}${n}`,a.toString()}catch{throw new Error(`Invalid sprite URL "${u}", must be absolute. Modify style specification directly or use TransformStyleFunction to correct the issue dynamically`)}}function go(u){let{userImage:t}=u;return!(!t?.render||!t.render()||(u.data.replace(new Uint8Array(t.data.buffer)),0))}class _o extends p.E{constructor(){super(),this.images={},this.updatedImages={},this.callbackDispatchedThisFrame={},this.loaded=!1,this.requestors=[],this.patterns={},this.atlasImage=new p.R({width:1,height:1}),this.dirty=!0}destroy(){this.atlasTexture&&(this.atlasTexture.destroy(),this.atlasTexture=null);for(let t of Object.keys(this.images))this.removeImage(t);this.patterns={},this.atlasImage=new p.R({width:1,height:1}),this.dirty=!0}isLoaded(){return this.loaded}setLoaded(t){if(this.loaded!==t&&(this.loaded=t,t)){for(let{ids:n,promiseResolve:a}of this.requestors)a(this._getImagesForIds(n));this.requestors=[]}}getImage(t){let n=this.images[t];if(n&&!n.data&&n.spriteData){let a=n.spriteData;n.data=new p.R({width:a.width,height:a.height},a.context.getImageData(a.x,a.y,a.width,a.height).data),n.spriteData=null}return n}addImage(t,n){if(this.images[t])throw new Error(`Image id ${t} already exist, use updateImage instead`);this._validate(t,n)&&(this.images[t]=n)}_validate(t,n){let a=!0,c=n.data||n.spriteData;return this._validateStretch(n.stretchX,c?.width)||(this.fire(new p.l(new Error(`Image "${t}" has invalid "stretchX" value`))),a=!1),this._validateStretch(n.stretchY,c?.height)||(this.fire(new p.l(new Error(`Image "${t}" has invalid "stretchY" value`))),a=!1),this._validateContent(n.content,n)||(this.fire(new p.l(new Error(`Image "${t}" has invalid "content" value`))),a=!1),a}_validateStretch(t,n){if(!t)return!0;let a=0;for(let c of t){if(c[0]=t[1]))}updateImage(t,n,a=!0){let c=this.getImage(t);if(a&&(c.data.width!==n.data.width||c.data.height!==n.data.height))throw new Error(`size mismatch between old image (${c.data.width}x${c.data.height}) and new image (${n.data.width}x${n.data.height}).`);n.version=c.version+1,this.images[t]=n,this.updatedImages[t]=!0}removeImage(t){var n;let a=this.images[t];delete this.images[t],delete this.patterns[t],!((n=a.userImage)===null||n===void 0)&&n.onRemove&&a.userImage.onRemove()}listImages(){return Object.keys(this.images)}getImages(t){return new Promise(((n,a)=>{let c=!0;if(!this.isLoaded())for(let f of t)this.images[f]||(c=!1);this.isLoaded()||c?n(this._getImagesForIds(t)):this.requestors.push({ids:t,promiseResolve:n})}))}_getImagesForIds(t){var n;let a={};for(let c of t){let f=this.getImage(c);f||(this.fire(new p.n("styleimagemissing",{id:c})),f=this.getImage(c)),f?a[c]={data:f.data.clone(),pixelRatio:f.pixelRatio,sdf:f.sdf,version:f.version,stretchX:f.stretchX,stretchY:f.stretchY,content:f.content,textFitWidth:f.textFitWidth,textFitHeight:f.textFitHeight,hasRenderCallback:!!(!((n=f.userImage)===null||n===void 0)&&n.render)}:p.w(`Image "${c}" could not be loaded. Please make sure you have added the image with map.addImage() or a "sprite" property in your style. You can provide missing images by listening for the "styleimagemissing" map event.`)}return a}getPixelSize(){let{width:t,height:n}=this.atlasImage;return{width:t,height:n}}getPattern(t){let n=this.patterns[t],a=this.getImage(t);if(!a)return null;if(n&&n.position.version===a.version)return n.position;if(n)n.position.version=a.version;else{let c={w:a.data.width+2,h:a.data.height+2,x:0,y:0},f=new p.I(c,a);this.patterns[t]={bin:c,position:f}}return this._updatePatternAtlas(),this.patterns[t].position}bind(t){let n=t.gl;this.atlasTexture?this.dirty&&(this.atlasTexture.update(this.atlasImage),this.dirty=!1):this.atlasTexture=new p.T(t,this.atlasImage,n.RGBA),this.atlasTexture.bind(n.LINEAR,n.CLAMP_TO_EDGE)}_updatePatternAtlas(){let t=[];for(let f in this.patterns)t.push(this.patterns[f].bin);let{w:n,h:a}=p.p(t),c=this.atlasImage;c.resize({width:n||1,height:a||1});for(let f in this.patterns){let{bin:y}=this.patterns[f],x=y.x+1,w=y.y+1,P=this.getImage(f).data,S=P.width,E=P.height;p.R.copy(P,c,{x:0,y:0},{x,y:w},{width:S,height:E}),p.R.copy(P,c,{x:0,y:E-1},{x,y:w-1},{width:S,height:1}),p.R.copy(P,c,{x:0,y:0},{x,y:w+E},{width:S,height:1}),p.R.copy(P,c,{x:S-1,y:0},{x:x-1,y:w},{width:1,height:E}),p.R.copy(P,c,{x:0,y:0},{x:x+S,y:w},{width:1,height:E})}this.dirty=!0}beginFrame(){this.callbackDispatchedThisFrame={}}dispatchRenderCallbacks(t){for(let n of t){if(this.callbackDispatchedThisFrame[n])continue;this.callbackDispatchedThisFrame[n]=!0;let a=this.getImage(n);a||p.w(`Image with ID: "${n}" was not found`),go(a)&&this.updateImage(n,a)}}cloneImages(){let t={};for(let n in this.images){let a=this.images[n];t[n]=Object.assign(Object.assign({},a),{data:a.data?a.data.clone():null})}return t}}let We=1e20,W=new Float64Array(256);for(let u=0;u<256;u++){let t=.5-Math.pow(u/255,.45454545454545453);W[u]=t*Math.abs(t)}function K(u,t,n,a,c,f,y,x,w){for(let P=t;P-1);w++,f[w]=x,y[w]=P,y[w+1]=We}for(let x=0,w=0;x/[-\w]+/.test(c)?c:`'${CSS.escape(c)}'`)).join(",");return new Me.TinySDF({fontSize:48,buffer:6,radius:16,cutoff:.25,fontFamily:a,fontWeight:this._fontWeight(n[0]),fontStyle:this._fontStyle(n[0]),lang:this.lang})}_fontStyle(t){return/italic/i.test(t)?"italic":/oblique/i.test(t)?"oblique":"normal"}_fontWeight(t){let n={thin:100,hairline:100,"extra light":200,"ultra light":200,light:300,normal:400,regular:400,medium:500,semibold:600,demibold:600,bold:700,"extra bold":800,"ultra bold":800,black:900,heavy:900,"extra black":950,"ultra black":950},a;for(let[c,f]of Object.entries(n))new RegExp(`\\b${c}\\b`,"i").test(t)&&(a=`${f}`);return a}destroy(){for(let t in this.entries){let n=this.entries[t];n.tinySDF=null,n.ideographTinySDF=null,n.glyphs={},n.requests={},n.ranges={}}this.entries={}}}Me.loadGlyphRange=function(u,t,n,a){return p._(this,void 0,void 0,(function*(){let c=256*t,f=c+255,y=yield a.transformRequest(n.replace("{fontstack}",u).replace("{range}",`${c}-${f}`),"Glyphs"),x=yield p.o(y,new AbortController);if(!x?.data)throw new Error(`Could not load glyph range. range: ${t}, ${c}-${f}`);let w={};for(let P of p.q(x.data))w[P.id]=P;return w}))},Me.TinySDF=class{constructor({fontSize:u=24,buffer:t=3,radius:n=8,cutoff:a=.25,fontFamily:c="sans-serif",fontWeight:f="normal",fontStyle:y="normal",lang:x=null}={}){this.buffer=t,this.radius=n,this.cutoff=a,this.lang=x;let w=this.size=u+4*t,P=this._createCanvas(w),S=this.ctx=P.getContext("2d",{willReadFrequently:!0});S.font=`${y} ${f} ${u}px ${c}`,S.textBaseline="alphabetic",S.textAlign="left",S.fillStyle="black",this.gridOuter=new Float64Array(w*w),this.gridInner=new Float64Array(w*w),this.f=new Float64Array(w),this.z=new Float64Array(w+1),this.v=new Uint16Array(w)}_createCanvas(u){if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(u,u);let t=document.createElement("canvas");return t.width=t.height=u,t}draw(u){let{width:t,actualBoundingBoxAscent:n,actualBoundingBoxDescent:a,actualBoundingBoxLeft:c,actualBoundingBoxRight:f}=this.ctx.measureText(u),y=Math.ceil(n),x=Math.floor(c),w=Math.max(0,Math.min(this.size-this.buffer,Math.ceil(f)-x)),P=Math.max(0,Math.min(this.size-this.buffer,y+Math.ceil(a))),S=w+2*this.buffer,E=P+2*this.buffer,C=Math.max(S*E,0),z=new Uint8ClampedArray(C),B={data:z,width:S,height:E,glyphWidth:w,glyphHeight:P,glyphTop:y,glyphLeft:x,glyphAdvance:t};if(w===0||P===0)return B;let{ctx:N,buffer:G,gridInner:j,gridOuter:$}=this;this.lang&&(N.lang=this.lang),N.clearRect(G,G,w,P),N.fillText(u,G-x,G+y);let X=N.getImageData(G,G,w,P);$.fill(We,0,C),j.fill(0,0,C);let Z=3;for(let q=0;q1&&(w=t[++x]);let S=Math.abs(P-w.left),E=Math.abs(P-w.right),C=Math.min(S,E),z,B=f/a*(c+1);if(w.isDash){let N=c-Math.abs(B);z=Math.sqrt(C*C+N*N)}else z=c-Math.sqrt(C*C+B*B);this.data[y+P]=Math.max(0,Math.min(255,z+128))}}}addRegularDash(t){for(let x=t.length-1;x>=0;--x){let w=t[x],P=t[x+1];w.zeroLength?t.splice(x,1):P&&P.isDash===w.isDash&&(P.left=w.left,t.splice(x,1))}let n=t[0],a=t[t.length-1];n.isDash===a.isDash&&(n.left=a.left-this.width,a.right=n.right+this.width);let c=this.width*this.nextRow,f=0,y=t[f];for(let x=0;x1&&(y=t[++f]);let w=Math.abs(x-y.left),P=Math.abs(x-y.right),S=Math.min(w,P);this.data[c+x]=Math.max(0,Math.min(255,(y.isDash?S:-S)+128))}}addDash(t,n){let a=n?7:0,c=2*a+1;if(this.nextRow+c>this.height)return p.w("LineAtlas out of space"),null;let f=0;for(let x of t)f+=x;if(f!==0){let x=this.width/f,w=this.getDashRanges(t,this.width,x);n?this.addRoundDash(w,x,a):this.addRegularDash(w)}let y={y:this.nextRow+a,height:2*a,width:f};return this.nextRow+=c,this.dirty=!0,y}bind(t){let n=t.gl;this.texture?(n.bindTexture(n.TEXTURE_2D,this.texture),this.dirty&&(this.dirty=!1,n.texSubImage2D(n.TEXTURE_2D,0,0,0,this.width,this.height,n.ALPHA,n.UNSIGNED_BYTE,this.data))):(this.texture=n.createTexture(),n.bindTexture(n.TEXTURE_2D,this.texture),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_S,n.REPEAT),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_T,n.REPEAT),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,n.LINEAR),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MAG_FILTER,n.LINEAR),n.texImage2D(n.TEXTURE_2D,0,n.ALPHA,this.width,this.height,0,n.ALPHA,n.UNSIGNED_BYTE,this.data))}}let vt="maplibre_preloaded_worker_pool";class xt{constructor(){this.active={}}acquire(t){if(!this.workers)for(this.workers=[];this.workers.lengthp.m(t,n)))),Mr}function zn(u,t){let n=p.O();return p.Q(n,n,[1,1,0]),p.S(n,n,[.5*u.width,.5*u.height,1]),u.calculatePosMatrix?p.U(n,n,u.calculatePosMatrix(t.toUnwrapped())):n}function Oi(u,t,n,a,c,f,y){var x;let w=(function(C,z,B){if(C)for(let N of C){let G=z[N];if(G?.source===B&&G.type==="fill-extrusion")return!0}else for(let N in z){let G=z[N];if(G.source===B&&G.type==="fill-extrusion")return!0}return!1})((x=c?.layers)!==null&&x!==void 0?x:null,t,u.id),P=f.maxPitchScaleFactor(),S=u.tilesIn(a,P,w);S.sort(vo);let E=[];for(let C of S)E.push({wrappedTileID:C.tileID.wrapped().key,queryResults:C.tile.queryRenderedFeatures(t,n,u.getState(),C.queryGeometry,C.cameraQueryGeometry,C.scale,c,f,P,zn(f,C.tileID),y?(z,B)=>y(C.tileID,z,B):void 0)});return(function(C,z){for(let B in C)for(let N of C[B])Er(N,z);return C})((function(C){let z={},B={};for(let{queryResults:N,wrappedTileID:G}of C){B[G]||(B[G]={});let j=B[G];for(let $ in N){let X=N[$];j[$]||(j[$]={});let Z=j[$];z[$]||(z[$]=[]);for(let U of X)Z[U.featureIndex]||(Z[U.featureIndex]=!0,z[$].push(U))}}return z})(E),u)}function vo(u,t){let n=u.tileID,a=t.tileID;return n.overscaledZ-a.overscaledZ||n.canonical.y-a.canonical.y||n.wrap-a.wrap||n.canonical.x-a.canonical.x}function Er(u,t){let n=u.feature,a=t.getFeatureState(n.layer["source-layer"],n.id);n.source=n.layer.source,n.layer["source-layer"]&&(n.sourceLayer=n.layer["source-layer"]),n.state=a}function Kr(u,t,n,a){return p._(this,void 0,void 0,(function*(){let c=u;if(u.url?c=(yield p.k(yield t.transformRequest(u.url,"Source"),n)).data:yield qt.frameAsync(n,a),!c)return null;let f=p.V(p.e(c,u),["tiles","minzoom","maxzoom","attribution","bounds","scheme","tileSize","encoding"]);return"vector_layers"in c&&c.vector_layers&&(f.vectorLayerIds=c.vector_layers.map((y=>y.id))),f}))}class Re{constructor(t,n){t&&(n?this.setSouthWest(t).setNorthEast(n):Array.isArray(t)&&(t.length===4?this.setSouthWest([t[0],t[1]]).setNorthEast([t[2],t[3]]):this.setSouthWest(t[0]).setNorthEast(t[1])))}setNorthEast(t){return this._ne=t instanceof p.W?new p.W(t.lng,t.lat):p.W.convert(t),this}setSouthWest(t){return this._sw=t instanceof p.W?new p.W(t.lng,t.lat):p.W.convert(t),this}extend(t){let n=this._sw,a=this._ne,c,f;if(t instanceof p.W)c=t,f=t;else{if(!(t instanceof Re))return Array.isArray(t)?t.length===4||t.every(Array.isArray)?this.extend(Re.convert(t)):this.extend(p.W.convert(t)):t&&("lng"in t||"lon"in t)&&"lat"in t?this.extend(p.W.convert(t)):this;if(c=t._sw,f=t._ne,!c||!f)return this}return n||a?(n.lng=Math.min(c.lng,n.lng),n.lat=Math.min(c.lat,n.lat),a.lng=Math.max(f.lng,a.lng),a.lat=Math.max(f.lat,a.lat)):(this._sw=new p.W(c.lng,c.lat),this._ne=new p.W(f.lng,f.lat)),this}getCenter(){return new p.W((this._sw.lng+this._ne.lng)/2,(this._sw.lat+this._ne.lat)/2)}getSouthWest(){return this._sw}getNorthEast(){return this._ne}getNorthWest(){return new p.W(this.getWest(),this.getNorth())}getSouthEast(){return new p.W(this.getEast(),this.getSouth())}getWest(){return this._sw.lng}getSouth(){return this._sw.lat}getEast(){return this._ne.lng}getNorth(){return this._ne.lat}toArray(){return[this._sw.toArray(),this._ne.toArray()]}toString(){return`LngLatBounds(${this._sw.toString()}, ${this._ne.toString()})`}isEmpty(){return!(this._sw&&this._ne)}contains(t){let{lng:n,lat:a}=p.W.convert(t),c=this._sw.lng<=n&&n<=this._ne.lng;return this._sw.lng>this._ne.lng&&(c=this._sw.lng>=n&&n>=this._ne.lng),this._sw.lat<=a&&a<=this._ne.lat&&c}intersects(t){if(!((t=Re.convert(t)).getNorth()>=this.getSouth()&&t.getSouth()<=this.getNorth()))return!1;let n=Math.abs(this.getEast()-this.getWest()),a=Math.abs(t.getEast()-t.getWest());if(n>=360||a>=360)return!0;let c=p.X(this.getWest(),-180,180),f=p.X(this.getEast(),-180,180),y=p.X(t.getWest(),-180,180),x=p.X(t.getEast(),-180,180),w=c>f,P=y>x;return!(!w||!P)||(w?x>=c||y<=f:P?f>=y||c<=x:y<=f&&x>=c)}static convert(t){return t instanceof Re?t:t&&new Re(t)}static fromLngLat(t,n=0){let a=360*n/40075017,c=a/Math.cos(Math.PI/180*t.lat);return new Re(new p.W(t.lng-c,t.lat-a),new p.W(t.lng+c,t.lat+a))}adjustAntiMeridian(){let t=new p.W(this._sw.lng,this._sw.lat),n=new p.W(this._ne.lng,this._ne.lat);return new Re(t,t.lng>n.lng?new p.W(n.lng+360,n.lat):n)}}class Bt{constructor(t,n,a){this.bounds=Re.convert(this.validateBounds(t)),this.minzoom=n||0,this.maxzoom=a||24}validateBounds(t){return Array.isArray(t)&&t.length===4?[Math.max(-180,t[0]),Math.max(-90,t[1]),Math.min(180,t[2]),Math.min(90,t[3])]:[-180,-90,180,90]}contains(t){let n=Math.pow(2,t.z),a=Math.floor(p.Z(this.bounds.getWest())*n),c=Math.floor(p.Y(this.bounds.getNorth())*n),f=Math.ceil(p.Z(this.bounds.getEast())*n),y=Math.ceil(p.Y(this.bounds.getSouth())*n);return t.x>=a&&t.x=c&&t.y{this._options.tiles=t})),this}setUrl(t){return this.setSourceProperty((()=>{this.url=t,this._options.url=t})),this}onRemove(){this._tileJSONRequest&&(this._tileJSONRequest.abort(),this._tileJSONRequest=null)}serialize(){return p.e({},this._options)}loadTile(t){return p._(this,void 0,void 0,(function*(){let n=t.tileID.canonical.url(this.tiles,this.map.getPixelRatio(),this.scheme),a={request:yield this.map._requestManager.transformRequest(n,"Tile"),uid:t.uid,tileID:t.tileID,zoom:t.tileID.overscaledZ,tileSize:this.tileSize*t.tileID.overscaleFactor(),type:this.type,source:this.id,pixelRatio:this.map.getPixelRatio(),showCollisionBoxes:this.map.showCollisionBoxes,promoteId:this.promoteId,subdivisionGranularity:this.map.style.projection.subdivisionGranularity,encoding:this.encoding,overzoomParameters:yield this._getOverzoomParameters(t),etag:t.etag};a.request.collectResourceTiming=this._collectResourceTiming;let c="RT";if(t.actor&&t.state!=="expired"){if(t.state==="loading")return new Promise(((f,y)=>{t.reloadPromise={resolve:f,reject:y}}))}else t.actor=this.dispatcher.getActor(),c="LT";t.abortController=new AbortController;try{let f=yield t.actor.sendAsync({type:c,data:a},t.abortController);if(delete t.abortController,t.aborted)return;this._afterTileLoadWorkerResponse(t,f);let y={};return f?.etagUnmodified&&(y.unmodified=!0),y}catch(f){if(delete t.abortController,t.aborted)return;if(f&&f.status!==404)throw f;this._afterTileLoadWorkerResponse(t,null)}}))}_getOverzoomParameters(t){return p._(this,void 0,void 0,(function*(){if(t.tileID.canonical.z<=this.maxzoom||this.map._zoomLevelsToOverscale===void 0)return;let n=t.tileID.scaledTo(this.maxzoom).canonical,a=n.url(this.tiles,this.map.getPixelRatio(),this.scheme);return{maxZoomTileID:n,overzoomRequest:yield this.map._requestManager.transformRequest(a,"Tile")}}))}_afterTileLoadWorkerResponse(t,n){if(n?.resourceTiming&&(t.resourceTiming=n.resourceTiming),n&&this.map._refreshExpiredTiles&&t.setExpiryData(n),t.etag=n?.etag,t.loadVectorData(n,this.map.painter),t.reloadPromise){let a=t.reloadPromise;t.reloadPromise=null,this.loadTile(t).then(a.resolve).catch(a.reject)}}abortTile(t){return p._(this,void 0,void 0,(function*(){t.abortController&&(t.abortController.abort(),delete t.abortController),t.actor&&(yield t.actor.sendAsync({type:"AT",data:{uid:t.uid,type:this.type,source:this.id}}))}))}unloadTile(t){return p._(this,void 0,void 0,(function*(){t.unloadVectorData(),t.actor&&(yield t.actor.sendAsync({type:"RMT",data:{uid:t.uid,type:this.type,source:this.id}}))}))}hasTransition(){return!1}}class Mi extends p.E{constructor(t,n,a,c){super(),this.id=t,this.dispatcher=a,this.setEventedParent(c),this.type="raster",this.minzoom=0,this.maxzoom=22,this.roundZoom=!0,this.scheme="xyz",this.tileSize=512,this._loaded=!1,this._options=p.e({type:"raster"},n),p.e(this,p.V(n,["url","scheme","tileSize"]))}load(){return p._(this,arguments,void 0,(function*(t=!1){this._loaded=!1,this.fire(new p.n("dataloading",{dataType:"source"})),this._tileJSONRequest=new AbortController;try{let n=yield Kr(this._options,this.map._requestManager,this._tileJSONRequest,this.map._ownerWindow);this._tileJSONRequest=null,this._loaded=!0,n&&(p.e(this,n),n.bounds&&(this.tileBounds=new Bt(n.bounds,this.minzoom,this.maxzoom)),this.fire(new p.n("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new p.n("data",{dataType:"source",sourceDataType:"content",sourceDataChanged:t})))}catch(n){this._tileJSONRequest=null,this._loaded=!0,p.$(n)||this.fire(new p.l(p.d(n)))}}))}loaded(){return this._loaded}onAdd(t){this.map=t,this.load()}onRemove(){this._tileJSONRequest&&(this._tileJSONRequest.abort(),this._tileJSONRequest=null)}setSourceProperty(t){this._tileJSONRequest&&(this._tileJSONRequest.abort(),this._tileJSONRequest=null),t(),this.load(!0)}setTiles(t){return this.setSourceProperty((()=>{this._options.tiles=t})),this}setUrl(t){return this.setSourceProperty((()=>{this.url=t,this._options.url=t})),this}serialize(){return p.e({},this._options)}hasTile(t){return!this.tileBounds||this.tileBounds.contains(t.canonical)}loadTile(t){return p._(this,void 0,void 0,(function*(){let n=t.tileID.canonical.url(this.tiles,this.map.getPixelRatio(),this.scheme);t.abortController=new AbortController;try{let a=yield Ii.getImage(yield this.map._requestManager.transformRequest(n,"Tile"),t.abortController,this.map._refreshExpiredTiles);if(delete t.abortController,t.aborted)return void(t.state="unloaded");if(a?.data){this.map._refreshExpiredTiles&&(a.cacheControl||a.expires)&&t.setExpiryData({cacheControl:a.cacheControl,expires:a.expires});let c=this.map.painter.context,f=c.gl,y=a.data;t.texture=this.map.painter.getTileTexture(y.width),t.texture?t.texture.update(y,{useMipmap:!0}):(t.texture=new p.T(c,y,f.RGBA,{useMipmap:!0}),t.texture.bind(f.LINEAR,f.CLAMP_TO_EDGE,f.LINEAR_MIPMAP_NEAREST)),t.state="loaded"}}catch(a){if(delete t.abortController,t.aborted)t.state="unloaded";else if(a)throw t.state="errored",a}}))}abortTile(t){return p._(this,void 0,void 0,(function*(){t.abortController&&(t.abortController.abort(),delete t.abortController)}))}unloadTile(t){return p._(this,void 0,void 0,(function*(){t.texture&&this.map.painter.saveTileTexture(t.texture)}))}hasTransition(){return!1}}class Ht extends Mi{constructor(t,n,a,c){super(t,n,a,c),this.type="raster-dem",this.maxzoom=22,this._options=p.e({type:"raster-dem"},n),this.encoding=n.encoding||"mapbox",this.redFactor=n.redFactor,this.greenFactor=n.greenFactor,this.blueFactor=n.blueFactor,this.baseShift=n.baseShift}loadTile(t){return p._(this,void 0,void 0,(function*(){let n=t.tileID.canonical.url(this.tiles,this.map.getPixelRatio(),this.scheme),a=yield this.map._requestManager.transformRequest(n,"Tile");t.neighboringTiles=this._getNeighboringTiles(t.tileID),t.abortController=new AbortController;try{let c=yield Ii.getImage(a,t.abortController,this.map._refreshExpiredTiles);if(delete t.abortController,t.aborted)return void(t.state="unloaded");if(c?.data){let f=c.data;this.map._refreshExpiredTiles&&(c.cacheControl||c.expires)&&t.setExpiryData({cacheControl:c.cacheControl,expires:c.expires});let y=p.b(f)&&p.a0()?f:yield this.readImageNow(f),x={type:this.type,uid:t.uid,source:this.id,rawImageData:y,encoding:this.encoding,redFactor:this.redFactor,greenFactor:this.greenFactor,blueFactor:this.blueFactor,baseShift:this.baseShift};if(t.actor&&t.state!=="expired"&&t.state!=="reloading")return;t.actor&&t.state!=="expired"||(t.actor=this.dispatcher.getActor()),t.dem=yield t.actor.sendAsync({type:"LDT",data:x}),t.needsHillshadePrepare=!0,t.needsTerrainPrepare=!0,t.state="loaded"}}catch(c){if(delete t.abortController,t.aborted)t.state="unloaded";else if(c)throw t.state="errored",c}}))}readImageNow(t){return p._(this,void 0,void 0,(function*(){if(typeof VideoFrame<"u"&&p.a1()){let n=t.width+2,a=t.height+2;try{return new p.R({width:n,height:a},yield p.a2(t,-1,-1,n,a))}catch{}}return qt.getImageData(t,1)}))}_getNeighboringTiles(t){let n=t.canonical,a=Math.pow(2,n.z),c=(n.x-1+a)%a,f=n.x===0?t.wrap-1:t.wrap,y=(n.x+1+a)%a,x=n.x+1===a?t.wrap+1:t.wrap,w={};return w[new p.a3(t.overscaledZ,f,n.z,c,n.y).key]={backfilled:!1},w[new p.a3(t.overscaledZ,x,n.z,y,n.y).key]={backfilled:!1},n.y>0&&(w[new p.a3(t.overscaledZ,f,n.z,c,n.y-1).key]={backfilled:!1},w[new p.a3(t.overscaledZ,t.wrap,n.z,n.x,n.y-1).key]={backfilled:!1},w[new p.a3(t.overscaledZ,x,n.z,y,n.y-1).key]={backfilled:!1}),n.y+1f.key===a));c>-1&&u.addOrUpdateProperties.splice(c,1)}return(u.removeAllProperties||t.removeAllProperties)&&(n.removeAllProperties=!0),(u.removeProperties||t.removeProperties)&&(n.removeProperties=[...u.removeProperties||[],...t.removeProperties||[]]),(u.addOrUpdateProperties||t.addOrUpdateProperties)&&(n.addOrUpdateProperties=[...u.addOrUpdateProperties||[],...t.addOrUpdateProperties||[]]),(u.newGeometry||t.newGeometry)&&(n.newGeometry=t.newGeometry||u.newGeometry),n}function za(u){var t,n;if(!u)return{};let a={};return a.removeAll=u.removeAll,a.remove=new Set(u.remove||[]),a.add=new Map((t=u.add)===null||t===void 0?void 0:t.map((c=>[c.id,c]))),a.update=new Map((n=u.update)===null||n===void 0?void 0:n.map((c=>[c.id,c]))),a}function Ra(u){return u&&u.length!==0?typeof u[0]=="number"?[u]:u.flatMap((t=>Ra(t))):[]}function Cr(u){return u.type==="GeometryCollection"?u.geometries.flatMap((t=>Cr(t))):Ra(u.coordinates)}function Rn(u){let t=new Re,n;switch(u.type){case"FeatureCollection":n=u.features.flatMap((a=>Cr(a.geometry)));break;case"Feature":n=Cr(u.geometry);break;default:n=Cr(u)}if(n.length===0)return t;for(let a of n){let[c,f]=a;t.extend([c,f])}return t}class us extends p.E{constructor(t,n,a,c){super(),this.id=t,this.type="geojson",this.minzoom=0,this.maxzoom=18,this.tileSize=512,this.isTileClipped=!0,this.reparseOverscaled=!0,this._removed=!1,this._isUpdatingWorker=!1,this._pendingWorkerUpdate={data:n.data},this.actor=a.getActor(),this.setEventedParent(c),this._data=typeof n.data=="string"?{url:n.data}:{geojson:n.data},this._options=p.e({},n),this._collectResourceTiming=n.collectResourceTiming,n.maxzoom!==void 0&&(this.maxzoom=n.maxzoom),n.type&&(this.type=n.type),n.attribution&&(this.attribution=n.attribution),this.promoteId=n.promoteId,n.clusterMaxZoom!==void 0&&this.maxzoom<=n.clusterMaxZoom&&p.w(`The maxzoom value "${this.maxzoom}" is expected to be greater than the clusterMaxZoom value "${n.clusterMaxZoom}".`),this.workerOptions=p.e({source:this.id,geojsonVtOptions:{buffer:this._pixelsToTileUnits(n.buffer!==void 0?n.buffer:128),tolerance:this._pixelsToTileUnits(n.tolerance!==void 0?n.tolerance:.375),extent:p.a6,maxZoom:this.maxzoom,lineMetrics:n.lineMetrics||!1,generateId:n.generateId||!1,promoteId:typeof n.promoteId=="string"?n.promoteId:void 0,cluster:n.cluster||!1,clusterOptions:{maxZoom:this._getClusterMaxZoom(n.clusterMaxZoom),minPoints:Math.max(2,n.clusterMinPoints||2),extent:p.a6,radius:this._pixelsToTileUnits(n.clusterRadius||50),log:!1,generateId:n.generateId||!1}},clusterProperties:n.clusterProperties,filter:n.filter},n.workerOptions)}_hasPendingWorkerUpdate(){return this._pendingWorkerUpdate.data!==void 0||this._pendingWorkerUpdate.diff!==void 0||this._pendingWorkerUpdate.updateCluster}_pixelsToTileUnits(t){return t*(p.a6/this.tileSize)}_getClusterMaxZoom(t){let n=t?Math.round(t):this.maxzoom-1;return Number.isInteger(t)||t===void 0||p.w(`Integer expected for option 'clusterMaxZoom': provided value "${t}" rounded to "${n}"`),n}load(){return p._(this,void 0,void 0,(function*(){yield this._updateWorkerData()}))}onAdd(t){this.map=t,this.load()}setData(t,n){this._data=typeof t=="string"?{url:t}:{geojson:t},this._pendingWorkerUpdate={data:t};let a=this._updateWorkerData();return n?a:this}updateData(t,n){this._pendingWorkerUpdate.diff=(function(c,f){if(!c)return f||{};if(!f)return c||{};let y=za(c),x=za(f);(function(P,S){S.removeAll&&(P.add.clear(),P.update.clear(),P.remove.clear(),S.remove.clear());for(let E of S.remove)P.add.delete(E),P.update.delete(E);for(let[E,C]of S.update){let z=P.update.get(E);z&&(S.update.set(E,Jr(z,C)),P.update.delete(E))}})(y,x);let w={};if((y.removeAll||x.removeAll)&&(w.removeAll=!0),w.remove=new Set([...y.remove,...x.remove]),w.add=new Map([...y.add,...x.add]),w.update=new Map([...y.update,...x.update]),w.remove.size&&w.add.size)for(let P of w.add.keys())w.remove.delete(P);return(function(P){let S={};return P.removeAll&&(S.removeAll=P.removeAll),P.remove&&(S.remove=Array.from(P.remove)),P.add&&(S.add=Array.from(P.add.values())),P.update&&(S.update=Array.from(P.update.values())),S})(w)})(this._pendingWorkerUpdate.diff,t);let a=this._updateWorkerData();return n?a:this}getData(){return p._(this,void 0,void 0,(function*(){return this._data.url&&(yield this.once("data")),this._data.geojson?this._data.geojson:{type:"FeatureCollection",features:Array.from(this._data.updateable.values())}}))}getBounds(){return p._(this,void 0,void 0,(function*(){return Rn(yield this.getData())}))}setClusterOptions(t){return this.workerOptions.geojsonVtOptions.cluster=t.cluster,t.clusterRadius!==void 0&&(this.workerOptions.geojsonVtOptions.clusterOptions.radius=this._pixelsToTileUnits(t.clusterRadius)),t.clusterMaxZoom!==void 0&&(this.workerOptions.geojsonVtOptions.clusterOptions.maxZoom=this._getClusterMaxZoom(t.clusterMaxZoom)),this._pendingWorkerUpdate.updateCluster=!0,this._updateWorkerData(),this}getClusterExpansionZoom(t){return this.actor.sendAsync({type:"GCEZ",data:{type:this.type,clusterId:t,source:this.id}})}getClusterChildren(t){return this.actor.sendAsync({type:"GCC",data:{type:this.type,clusterId:t,source:this.id}})}getClusterLeaves(t,n,a){return this.actor.sendAsync({type:"GCL",data:{type:this.type,source:this.id,clusterId:t,limit:n,offset:a}})}_updateWorkerData(){return p._(this,void 0,void 0,(function*(){if(this._isUpdatingWorker)return;if(!this._hasPendingWorkerUpdate())return void p.w(`No pending worker updates for GeoJSONSource ${this.id}.`);let{data:t,diff:n,updateCluster:a}=this._pendingWorkerUpdate,c=this._getLoadGeoJSONParameters(t,n,a);t!==void 0?this._pendingWorkerUpdate.data=void 0:n?this._pendingWorkerUpdate.diff=void 0:a&&(this._pendingWorkerUpdate.updateCluster=void 0),yield this._dispatchWorkerUpdate(c)}))}_getLoadGeoJSONParameters(t,n,a){return p._(this,void 0,void 0,(function*(){let c=p.e({type:this.type},this.workerOptions);return typeof t=="string"?(c.request=yield this.map._requestManager.transformRequest(qt.resolveURL(t),"Source"),c.request.collectResourceTiming=this._collectResourceTiming,c):t!==void 0?(c.data=t,c):n?(c.dataDiff=n,c):a?(c.updateCluster=!0,c):void 0}))}_dispatchWorkerUpdate(t){return p._(this,void 0,void 0,(function*(){this._isUpdatingWorker=!0,this.fire(new p.n("dataloading",{dataType:"source"}));try{let n=yield t,a=yield this.actor.sendAsync({type:"LD",data:n});if(this._isUpdatingWorker=!1,this._removed||a.abandoned)return void this.fire(new p.n("dataabort",{dataType:"source"}));a.data&&(this._data={geojson:a.data});let c=this._applyDiffToSource(n.dataDiff),f=this._getShouldReloadTileOptions(c),y={dataType:"source"};this._applyResourceTiming(y,a),this.fire(new p.n("data",Object.assign(Object.assign({},y),{sourceDataType:"metadata"}))),this.fire(new p.n("data",Object.assign(Object.assign({},y),{sourceDataType:"content",shouldReloadTileOptions:f})))}catch(n){if(this._isUpdatingWorker=!1,this._removed)return void this.fire(new p.n("dataabort",{dataType:"source"}));this.fire(new p.l(p.d(n)))}finally{this._hasPendingWorkerUpdate()&&this._updateWorkerData()}}))}_applyResourceTiming(t,n){var a;if(!this._collectResourceTiming)return;let c=(a=n.resourceTiming)===null||a===void 0?void 0:a[this.id];if(!c)return;let f=c.slice(0);f?.length&&p.e(t,{resourceTiming:f})}_applyDiffToSource(t){if(!t)return;let n=typeof this.promoteId=="string"?this.promoteId:void 0;if(!this._data.url&&!this._data.updateable){let c=(function(f,y){let x=new Map;if(f==null||f.type==null)return x;if(f.type==="Feature"){let w=yi(f,y);return w==null?void 0:(x.set(w,f),x)}if(f.type==="FeatureCollection"){let w=new Set;for(let P of f.features){let S=yi(P,y);if(S==null||w.has(S))return;w.add(S),x.set(S,P)}return x}})(this._data.geojson,n);if(!c)throw new Error(`GeoJSONSource "${this.id}": GeoJSON data is not compatible with updateData`);this._data={updateable:c}}if(!this._data.updateable)return;let a=(function(c,f,y){var x,w;let P=[];if(f.removeAll)c.clear();else if(f.remove)for(let S of f.remove){let E=c.get(S);E&&(P.push(E.geometry),c.delete(S))}if(f.add)for(let S of f.add){let E=yi(S,y);if(E==null)continue;let C=c.get(E);C&&P.push(C.geometry),P.push(S.geometry),c.set(E,S)}if(f.update)for(let S of f.update){let E=c.get(S.id);if(!E)continue;let C=!!S.newGeometry,z=S.removeAllProperties||((x=S.removeProperties)===null||x===void 0?void 0:x.length)>0||((w=S.addOrUpdateProperties)===null||w===void 0?void 0:w.length)>0;if(!C&&!z)continue;P.push(E.geometry);let B=Object.assign({},E);if(c.set(S.id,B),C&&(P.push(S.newGeometry),B.geometry=S.newGeometry),z){if(B.properties=S.removeAllProperties?{}:Object.assign({},B.properties||{}),S.removeProperties)for(let N of S.removeProperties)delete B.properties[N];if(S.addOrUpdateProperties)for(let{key:N,value:G}of S.addOrUpdateProperties)B.properties[N]=G}}return P})(this._data.updateable,t,n);return t.removeAll||this._options.cluster?void 0:a}_getShouldReloadTileOptions(t){if(t)return{affectedBounds:t.filter(Boolean).map((n=>Rn(n)))}}shouldReloadTile(t,{affectedBounds:n}){if(t.state==="loading")return!0;if(t.state==="unloaded")return!1;let{buffer:a,extent:c}=this.workerOptions.geojsonVtOptions,f=(function({x:y,y:x,z:w},P=0){let S=p.a4((y-P)/Math.pow(2,w)),E=p.a5((x+1+P)/Math.pow(2,w)),C=p.a4((y+1+P)/Math.pow(2,w)),z=p.a5((x-P)/Math.pow(2,w));return new Re([S,E],[C,z])})(t.tileID.canonical,a/c);for(let y of n)if(f.intersects(y))return!0;return!1}loaded(){return!this._isUpdatingWorker&&!this._hasPendingWorkerUpdate()}loadTile(t){return p._(this,void 0,void 0,(function*(){let n=t.actor?"RT":"LT";t.actor=this.actor;let a={type:this.type,uid:t.uid,tileID:t.tileID,zoom:t.tileID.overscaledZ,maxZoom:this.maxzoom,tileSize:this.tileSize,source:this.id,pixelRatio:this.map.getPixelRatio(),showCollisionBoxes:this.map.showCollisionBoxes,promoteId:this.promoteId,subdivisionGranularity:this.map.style.projection.subdivisionGranularity};t.abortController=new AbortController;let c=yield this.actor.sendAsync({type:n,data:a},t.abortController);delete t.abortController,t.unloadVectorData(),t.aborted||t.loadVectorData(c,this.map.painter,n==="RT")}))}abortTile(t){return p._(this,void 0,void 0,(function*(){t.abortController&&(t.abortController.abort(),delete t.abortController),t.aborted=!0}))}unloadTile(t){return p._(this,void 0,void 0,(function*(){t.unloadVectorData(),yield this.actor.sendAsync({type:"RMT",data:{uid:t.uid,type:this.type,source:this.id}})}))}onRemove(){this._removed=!0,this.actor.sendAsync({type:"RS",data:{type:this.type,source:this.id}})}serialize(){return p.e({},this._options,{type:this.type,data:this._data.updateable?{type:"FeatureCollection",features:Array.from(this._data.updateable.values())}:this._data.url||this._data.geojson})}hasTransition(){return!1}}class Ar extends p.E{constructor(t,n,a,c){super(),this.flippedWindingOrder=!1,this.id=t,this.dispatcher=a,this.coordinates=n.coordinates,this.type="image",this.minzoom=0,this.maxzoom=22,this.tileSize=512,this.tiles={},this._loaded=!1,this.setEventedParent(c),this.options=n}load(t){return p._(this,void 0,void 0,(function*(){this._loaded=!1,this.fire(new p.n("dataloading",{dataType:"source"})),this.url=this.options.url,this._request=new AbortController;try{let n=yield Ii.getImage(yield this.map._requestManager.transformRequest(this.url,"Image"),this._request);this._request=null,this._loaded=!0,n?.data&&(this.image=n.data,t&&(this.coordinates=t),this._finishLoading())}catch(n){this._request=null,this._loaded=!0,p.$(n)||this.fire(new p.l(p.d(n)))}}))}loaded(){return this._loaded}updateImage(t){return t.url?(this._request&&(this._request.abort(),this._request=null),this.options.url=t.url,this.load(t.coordinates).finally((()=>this.texture=null)),this):this}_finishLoading(){this.map&&(this.setCoordinates(this.coordinates),this.fire(new p.n("data",{dataType:"source",sourceDataType:"metadata"})))}onAdd(t){this.map=t,this.load()}onRemove(){this._request&&(this._request.abort(),this._request=null)}setCoordinates(t){this.coordinates=t;let n=t.map(p.a7.fromLngLat);var a;return this.tileID=(function(c){let f=p.a8.fromPoints(c),y=f.width(),x=f.height(),w=Math.max(y,x),P=Math.max(0,Math.floor(-Math.log(w)/Math.LN2)),S=Math.pow(2,P);return new p.aa(P,Math.floor((f.minX+f.maxX)/2*S),Math.floor((f.minY+f.maxY)/2*S))})(n),this.terrainTileRanges=this._getOverlappingTileRanges(n),this.minzoom=this.maxzoom=this.tileID.z,this.tileCoords=n.map((c=>this.tileID.getTilePoint(c)._round())),this.flippedWindingOrder=((a=this.tileCoords)[1].x-a[0].x)*(a[2].y-a[0].y)-(a[1].y-a[0].y)*(a[2].x-a[0].x)<0,this.fire(new p.n("data",{dataType:"source",sourceDataType:"content"})),this}prepare(){if(Object.keys(this.tiles).length===0||!this.image)return;let t=this.map.painter.context,n=t.gl;this.texture||(this.texture=new p.T(t,this.image,n.RGBA),this.texture.bind(n.LINEAR,n.CLAMP_TO_EDGE));let a=!1;for(let c in this.tiles){let f=this.tiles[c];f.state!=="loaded"&&(f.state="loaded",f.texture=this.texture,a=!0)}a&&this.fire(new p.n("data",{dataType:"source",sourceDataType:"idle",sourceId:this.id}))}loadTile(t){return p._(this,void 0,void 0,(function*(){var n;!((n=this.tileID)===null||n===void 0)&&n.equals(t.tileID.canonical)?(this.tiles[String(t.tileID.wrap)]=t,t.buckets={}):t.state="errored"}))}serialize(){return{type:"image",url:this.options.url,coordinates:this.coordinates}}hasTransition(){return!1}_getOverlappingTileRanges(t){let{minX:n,minY:a,maxX:c,maxY:f}=p.a8.fromPoints(t),y={};for(let x=0;x<=p.a9;x++){let w=Math.pow(2,x),P=Math.floor(n*w),S=Math.floor(a*w),E=Math.floor(c*w),C=Math.floor(f*w),z=(P%w+w)%w,B=E%w,N=Math.floor(P/w),G=Math.floor(E/w);y[x]={minWrap:N,maxWrap:G,minTileXWrapped:z,maxTileXWrapped:B,minTileY:S,maxTileY:C}}return y}}class Qr extends Ar{constructor(t,n,a,c){super(t,n,a,c),this._onPlayingHandler=()=>{var f;(f=this.map)===null||f===void 0||f.triggerRepaint()},this.roundZoom=!0,this.type="video",this.options=n}load(){return p._(this,void 0,void 0,(function*(){this._loaded=!1;let t=this.options;this.urls=[];for(let n of t.urls)this.urls.push((yield this.map._requestManager.transformRequest(n,"Source")).url);try{let n=yield p.ab(this.urls);if(this._loaded=!0,!n)return;this.video=n,this.video.loop=!0,this.video.addEventListener("playing",this._onPlayingHandler),this.map&&this.video.play(),this._finishLoading()}catch(n){this.fire(new p.l(p.d(n)))}}))}pause(){this.video&&this.video.pause()}play(){this.video&&this.video.play()}seek(t){if(this.video){let n=this.video.seekable;tn.end(0)?this.fire(new p.l(new p.ac(`sources.${this.id}`,null,`Playback for this video can be set only between the ${n.start(0)} and ${n.end(0)}-second mark.`))):this.video.currentTime=t}}getVideo(){return this.video}onAdd(t){this.map||(this.map=t,this.load(),this.video&&(this.video.play(),this.setCoordinates(this.coordinates)))}onRemove(){super.onRemove(),this.video&&(this.video.removeEventListener("playing",this._onPlayingHandler),this.video.pause())}prepare(){if(Object.keys(this.tiles).length===0||this.video.readyState<2)return;let t=this.map.painter.context,n=t.gl;this.texture?this.video.paused||(this.texture.bind(n.LINEAR,n.CLAMP_TO_EDGE),n.texSubImage2D(n.TEXTURE_2D,0,0,0,n.RGBA,n.UNSIGNED_BYTE,this.video)):(this.texture=new p.T(t,this.video,n.RGBA),this.texture.bind(n.LINEAR,n.CLAMP_TO_EDGE));let a=!1;for(let c in this.tiles){let f=this.tiles[c];f.state!=="loaded"&&(f.state="loaded",f.texture=this.texture,a=!0)}a&&this.fire(new p.n("data",{dataType:"source",sourceDataType:"idle",sourceId:this.id}))}serialize(){return{type:"video",urls:this.urls,coordinates:this.coordinates}}hasTransition(){return this.video&&!this.video.paused}}class ka extends Ar{constructor(t,n,a,c){super(t,n,a,c),n.coordinates?Array.isArray(n.coordinates)&&n.coordinates.length===4&&!n.coordinates.some((f=>!Array.isArray(f)||f.length!==2||f.some((y=>typeof y!="number"))))||this.fire(new p.l(new p.ac(`sources.${t}`,null,'"coordinates" property must be an array of 4 longitude/latitude array pairs'))):this.fire(new p.l(new p.ac(`sources.${t}`,null,'missing required property "coordinates"'))),n.animate&&typeof n.animate!="boolean"&&this.fire(new p.l(new p.ac(`sources.${t}`,null,'optional "animate" property must be a boolean value'))),n.canvas?typeof n.canvas=="string"||n.canvas instanceof HTMLCanvasElement||this.fire(new p.l(new p.ac(`sources.${t}`,null,'"canvas" must be either a string representing the ID of the canvas element from which to read, or an HTMLCanvasElement instance'))):this.fire(new p.l(new p.ac(`sources.${t}`,null,'missing required property "canvas"'))),this.options=n,this.animate=n.animate===void 0||n.animate}load(){return p._(this,void 0,void 0,(function*(){this._loaded=!0,this.canvas||(this.canvas=this.options.canvas instanceof HTMLCanvasElement?this.options.canvas:document.getElementById(this.options.canvas)),this.width=this.canvas.width,this.height=this.canvas.height,this._hasInvalidDimensions()?this.fire(new p.l(new Error("Canvas dimensions cannot be less than or equal to zero."))):(this.play=function(){this._playing=!0,this.map.triggerRepaint()},this.pause=function(){this._playing&&(this.prepare(),this._playing=!1)},this._finishLoading())}))}getCanvas(){return this.canvas}onAdd(t){this.map=t,this.load(),this.canvas&&this.animate&&this.play()}onRemove(){this.pause()}prepare(){let t=!1;if(this.canvas.width!==this.width&&(this.width=this.canvas.width,t=!0),this.canvas.height!==this.height&&(this.height=this.canvas.height,t=!0),this._hasInvalidDimensions()||Object.keys(this.tiles).length===0)return;let n=this.map.painter.context,a=n.gl;this.texture?(t||this._playing)&&this.texture.update(this.canvas,{premultiply:!0}):(this.texture=new p.T(n,this.canvas,a.RGBA,{premultiply:!0}),this.texture.bind(a.LINEAR,a.CLAMP_TO_EDGE));let c=!1;for(let f in this.tiles){let y=this.tiles[f];y.state!=="loaded"&&(y.state="loaded",y.texture=this.texture,c=!0)}c&&this.fire(new p.n("data",{dataType:"source",sourceDataType:"idle",sourceId:this.id}))}serialize(){return{type:"canvas",animate:this.animate,canvas:this.options.canvas,coordinates:this.coordinates}}hasTransition(){return this._playing}_hasInvalidDimensions(){for(let t of[this.canvas.width,this.canvas.height])if(isNaN(t)||t<=0)return!0;return!1}}let La={},ds=u=>{switch(u){case"geojson":return us;case"image":return Ar;case"raster":return Mi;case"raster-dem":return Ht;case"vector":return Wt;case"video":return Qr;case"canvas":return ka}return La[u]},xo="RTLPluginLoaded";class rc extends p.E{constructor(){super(...arguments),this.status="unavailable",this.url=null,this.dispatcher=li()}_syncState(t){return this.status=t,this.dispatcher.broadcast("SRPS",{pluginStatus:t,pluginURL:this.url}).catch((n=>{throw this.status="error",n}))}getRTLTextPluginStatus(){return this.status}clearRTLTextPlugin(){this.status="unavailable",this.url=null}setRTLTextPlugin(t){return p._(this,arguments,void 0,(function*(n,a=!1){if(this.url)throw new Error("setRTLTextPlugin cannot be called multiple times.");if(this.url=qt.resolveURL(n),!this.url)throw new Error(`requested url ${n} is invalid`);if(this.status==="unavailable"){if(!a)return this._requestImport();this.status="deferred",this._syncState(this.status)}else if(this.status==="requested")return this._requestImport()}))}_requestImport(){return p._(this,void 0,void 0,(function*(){yield this._syncState("loading"),this.status="loaded",this.fire(new p.n(xo))}))}lazyLoad(){this.status==="unavailable"?this.status="requested":this.status==="deferred"&&this._requestImport()}}let ps=null;function Dr(){return ps||(ps=new rc),ps}var hr,Ni;(function(u){u[u.Base=0]="Base",u[u.Parent=1]="Parent"})(hr||(hr={})),(function(u){u[u.Departing=0]="Departing",u[u.Incoming=1]="Incoming"})(Ni||(Ni={}));class kn{constructor(t,n){this.timeAdded=0,this.fadeEndTime=0,this.fadeOpacity=1,this.tileID=t,this.uid=p.ad(),this.uses=0,this.tileSize=n,this.buckets={},this.expirationTime=null,this.queryPadding=0,this.hasSymbolBuckets=!1,this.hasRTLText=!1,this.dependencies={},this.rtt=[],this.rttFingerprint={},this.expiredRequestCount=0,this.state="loading"}isRenderable(t){return this.hasData()&&(!this.fadeEndTime||this.fadeOpacity>0)&&(t||!this.holdingForSymbolFade())}setCrossFadeLogic({fadingRole:t,fadingDirection:n,fadingParentID:a,fadeEndTime:c}){this.resetFadeLogic(),this.fadingRole=t,this.fadingDirection=n,this.fadingParentID=a,this.fadeEndTime=c}setSelfFadeLogic(t){this.resetFadeLogic(),this.selfFading=!0,this.fadeEndTime=t}resetFadeLogic(){this.fadingRole=null,this.fadingDirection=null,this.fadingParentID=null,this.selfFading=!1,this.timeAdded=Xe(),this.fadeEndTime=0,this.fadeOpacity=1}wasRequested(){return this.state==="errored"||this.state==="loaded"||this.state==="reloading"}clearTextures(t){this.demTexture&&t.saveTileTexture(this.demTexture),this.demTexture=null}loadVectorData(t,n,a){if(t?.etagUnmodified!==!0)if(this.hasData()&&this.unloadVectorData(),this.state="loaded",t){t.featureIndex&&(this.latestFeatureIndex=t.featureIndex,t.rawTileData?(this.latestRawTileData=t.rawTileData,this.latestEncoding=t.encoding,this.latestFeatureIndex.rawTileData=t.rawTileData,this.latestFeatureIndex.encoding=t.encoding):this.latestRawTileData&&(this.latestFeatureIndex.rawTileData=this.latestRawTileData,this.latestFeatureIndex.encoding=this.latestEncoding)),this.collisionBoxArray=t.collisionBoxArray,this.buckets=(function(c,f){let y={};if(!f)return y;for(let x of c){let w=x.layerIds.map((P=>f.getLayer(P))).filter(Boolean);if(w.length!==0){x.layers=w,x.stateDependentLayerIds&&(x.stateDependentLayers=x.stateDependentLayerIds.map((P=>w.filter((S=>S.id===P))[0])));for(let P of w)y[P.id]=x}}return y})(t.buckets,n?.style),this.hasSymbolBuckets=!1;for(let c in this.buckets){let f=this.buckets[c];if(f instanceof p.af){if(this.hasSymbolBuckets=!0,!a)break;f.justReloaded=!0}}if(this.hasRTLText=!1,this.hasSymbolBuckets)for(let c in this.buckets){let f=this.buckets[c];if(f instanceof p.af&&f.hasRTLText){this.hasRTLText=!0,Dr().lazyLoad();break}}this.queryPadding=0;for(let c in this.buckets){let f=this.buckets[c];this.queryPadding=Math.max(this.queryPadding,n.style.getLayer(c).queryRadius(f))}t.imageAtlas&&(this.imageAtlas=t.imageAtlas),t.glyphAtlasImage&&(this.glyphAtlasImage=t.glyphAtlasImage),this.dashPositions=t.dashPositions}else this.collisionBoxArray=new p.ae;else this.state="loaded"}unloadVectorData(){for(let t in this.buckets)this.buckets[t].destroy();this.buckets={},this.imageAtlasTexture&&this.imageAtlasTexture.destroy(),this.glyphAtlasTexture&&this.glyphAtlasTexture.destroy(),this.imageAtlas=null,this.dashPositions=null,this.latestFeatureIndex=null,this.state="unloaded"}getBucket(t){return this.buckets[t.id]}upload(t){for(let a in this.buckets){let c=this.buckets[a];c.uploadPending()&&c.upload(t)}let n=t.gl;this.imageAtlas&&!this.imageAtlas.uploaded&&(this.imageAtlasTexture=new p.T(t,this.imageAtlas.image,n.RGBA),this.imageAtlas.uploaded=!0),this.glyphAtlasImage&&(this.glyphAtlasTexture=new p.T(t,this.glyphAtlasImage,n.ALPHA),this.glyphAtlasImage=null)}prepare(t){this.imageAtlas&&this.imageAtlas.patchUpdatedImages(t,this.imageAtlasTexture)}queryRenderedFeatures(t,n,a,c,f,y,x,w,P,S,E){var C;return!((C=this.latestFeatureIndex)===null||C===void 0)&&C.rawTileData?this.latestFeatureIndex.query({queryGeometry:c,cameraQueryGeometry:f,scale:y,tileSize:this.tileSize,pixelPosMatrix:S,transform:w,params:x,queryPadding:this.queryPadding*P,getElevation:E},t,n,a):{}}querySourceFeatures(t,n){let a=this.latestFeatureIndex;if(!a?.rawTileData)return;let c=a.loadVTLayers(),f=n?.sourceLayer?n.sourceLayer:"",y=c[p.ag]||c[f];if(!y)return;let x=p.ah(n?.filter,n?.globalState),{z:w,x:P,y:S}=this.tileID.canonical,E={z:w,x:P,y:S};for(let C=0;Ca)c=!1;else if(n)if(this.expirationTime({zoom:0,x:0,y:0,wrap:U,fullyVisible:!1}),X=[],Z=[];if(u.renderWorldCopies&&y.allowWorldCopies())for(let U=1;U<=3;U++)X.push($(-U)),X.push($(U));for(X.push($(0));X.length>0;){let U=X.pop(),H=U.x,q=U.y,Q=U.fullyVisible,oe={x:H,y:q,z:U.zoom},se=y.getTileBoundingVolume(oe,U.wrap,u.elevation,t);if(!Q){let ve=ce(n,se,a);if(ve===0)continue;Q=ve===2}let de=y.distanceToTile2d(c.x,c.y,oe,se),ue=w;x&&(ue=(t.calculateTileZoom||it)(u.zoom+p.ar(u.tileSize/t.tileSize),de,G,j,u.fov)),ue=(t.roundZoom?Math.round:Math.floor)(ue),ue=Math.max(0,ue);let Se=Math.min(ue,S);if(U.wrap=y.getWrap(f,oe,U.wrap),U.zoom>=Se){if(U.zoom>1),wrap:U.wrap,fullyVisible:Q})}return Z.sort(((U,H)=>U.distanceSq-H.distanceSq)).map((U=>U.tileID))}let nc=p.a8.fromPoints([new p.P(0,0),new p.P(p.a6,p.a6)]);function oc(u){return u==="raster"||u==="image"||u==="video"}function Fh(u,t,n,a,c,f,y){if(!t.hasData())return!1;let{tileID:x,fadingRole:w,fadingDirection:P,fadingParentID:S}=t;if(w===hr.Base&&P===Ni.Incoming&&S)return n[S.key]=S,!0;let E=Math.max(x.overscaledZ-c,f);for(let C=x.overscaledZ-1;C>=E;C--){let z=x.scaledTo(C),B=u.getLoadedTile(z);if(B)return t.setCrossFadeLogic({fadingRole:hr.Base,fadingDirection:Ni.Incoming,fadingParentID:B.tileID,fadeEndTime:a+y}),B.setCrossFadeLogic({fadingRole:hr.Parent,fadingDirection:Ni.Departing,fadeEndTime:a+y}),n[z.key]=z,!0}return!1}function ms(u,t,n,a,c,f){if(!t.hasData())return!1;let y=t.tileID.children(c),x=Na(u,t,y,n,a,c,f);if(x)return!0;for(let w of y)Na(u,t,w.children(c),n,a,c,f)&&(x=!0);return x}function Na(u,t,n,a,c,f,y){if(n[0].overscaledZ>=f)return!1;let x=!1;for(let w of n){let P=u.getLoadedTile(w);if(!P)continue;let{fadingRole:S,fadingDirection:E,fadingParentID:C}=P;S===hr.Base&&E===Ni.Departing&&C||(P.setCrossFadeLogic({fadingRole:hr.Base,fadingDirection:Ni.Departing,fadingParentID:t.tileID,fadeEndTime:c+y}),t.setCrossFadeLogic({fadingRole:hr.Parent,fadingDirection:Ni.Incoming,fadeEndTime:c+y})),a[w.key]=w,x=!0}return x}function sc(u,t,n,a){let c=u.tileID;return!!u.selfFading||!u.hasData()&&!!t.has(c)&&(u.setSelfFadeLogic(n+a),!0)}function _e(u,t){var n;u.needsHillshadePrepare=!0,u.needsTerrainPrepare=!0;let a=t.tileID.canonical.x-u.tileID.canonical.x,c=t.tileID.canonical.y-u.tileID.canonical.y,f=Math.pow(2,u.tileID.canonical.z),y=t.tileID.key;a===0&&c===0||Math.abs(c)>1||(Math.abs(a)>1&&(Math.abs(a+f)===1?a+=f:Math.abs(a-f)===1&&(a-=f)),t.dem&&u.dem&&(u.dem.backfillBorder(t.dem,a,c),!((n=u.neighboringTiles)===null||n===void 0)&&n[y]&&(u.neighboringTiles[y].backfilled=!0)))}class nn{constructor(){this._tiles={}}handleWrapJump(t){let n={};for(let a in this._tiles){let c=this._tiles[a];c.tileID=c.tileID.unwrapTo(c.tileID.wrap+t),n[c.tileID.key]=c}this._tiles=n}setFeatureState(t,n){for(let a in this._tiles)this._tiles[a].setFeatureState(t,n)}getAllTiles(){return Object.values(this._tiles)}getAllIds(t=!1){return t?Object.values(this._tiles).map((n=>n.tileID)).sort(p.au).map((n=>n.key)):Object.keys(this._tiles)}getTileById(t){return this._tiles[t]}setTile(t,n){this._tiles[t]=n}deleteTileById(t){delete this._tiles[t]}getLoadedTile(t){let n=this.getTileById(t.key);return n?.hasData()?n:null}isIdRenderable(t,n=!1){var a;return(a=this.getTileById(t))===null||a===void 0?void 0:a.isRenderable(n)}getRenderableIds(t=0,n){let a=[];for(let c of this.getAllIds())this.isIdRenderable(c,n)&&a.push(this.getTileById(c));return n?a.sort(((c,f)=>{let y=c.tileID,x=f.tileID,w=new p.P(y.canonical.x,y.canonical.y)._rotate(-t),P=new p.P(x.canonical.x,x.canonical.y)._rotate(-t);return y.overscaledZ-x.overscaledZ||P.y-w.y||P.x-w.x})).map((c=>c.tileID.key)):a.map((c=>c.tileID)).sort(p.au).map((c=>c.key))}}class Xt extends p.E{constructor(t,n,a){super(),this.id=t,this.dispatcher=a,this.on("data",(c=>{this._dataHandler(c)})),this.on("dataloading",(()=>{this._sourceErrored=!1})),this.on("error",(()=>{this._sourceErrored=this._source.loaded()})),this._source=((c,f,y,x)=>{let w=new(ds(f.type))(c,f,y,x);if(w.id!==c)throw new Error(`Expected Source id to be ${c} instead of ${w.id}`);return w})(t,n,a,this),this._inViewTiles=new nn,this._outOfViewCache=new p.av(0,(c=>this._unloadTile(c))),this._timers={},this._maxTileCacheSize=null,this._maxTileCacheZoomLevels=null,this._rasterFadeDuration=0,this._maxFadingAncestorLevels=5,this._state=new Fa,this._didEmitContent=!1,this._updated=!1}onAdd(t){var n;this.map=t,this._maxTileCacheSize=t?t._maxTileCacheSize:null,this._maxTileCacheZoomLevels=t?t._maxTileCacheZoomLevels:null,!((n=this._source)===null||n===void 0)&&n.onAdd&&this._source.onAdd(t)}onRemove(t){var n;for(let a of this._inViewTiles.getAllTiles())a.unloadVectorData();this.clearTiles(),!((n=this._source)===null||n===void 0)&&n.onRemove&&this._source.onRemove(t),this._inViewTiles=new nn}loaded(){if(this._sourceErrored)return!0;if(!this._sourceLoaded||!this._source.loaded())return!1;if(!(this.used===void 0&&this.usedForTerrain===void 0||this.used||this.usedForTerrain))return!0;if(!this._updated)return!1;for(let t of this._inViewTiles.getAllTiles())if(t.state!=="loaded"&&t.state!=="errored")return!1;return!0}getSource(){return this._source}getState(){return this._state}pause(){this._paused=!0}resume(){if(!this._paused)return;let t=this._shouldReloadOnResume;this._paused=!1,this._shouldReloadOnResume=!1,t&&this.reload(),this.transform&&this.update(this.transform,this.terrain)}_loadTile(t,n,a){return p._(this,void 0,void 0,(function*(){try{let c=yield this._source.loadTile(t);this._tileLoaded(t,n,a,c)}catch(c){t.state="errored",c.status!==404?this._source.fire(new p.l(p.d(c),{tile:t})):this.update(this.transform,this.terrain)}}))}_unloadTile(t){this._source.unloadTile&&this._source.unloadTile(t)}_abortTile(t){this._source.abortTile&&this._source.abortTile(t),this._source.fire(new p.n("dataabort",{tile:t,coord:t.tileID,dataType:"source"}))}serialize(){return this._source.serialize()}prepare(t){this._source.prepare&&this._source.prepare(),this._state.coalesceChanges(this._inViewTiles,this.map?this.map.painter:null);for(let n of this._inViewTiles.getAllTiles())n.upload(t),n.prepare(this.map.style.imageManager)}getIds(){return this._inViewTiles.getAllIds(!0)}getRenderableIds(t){var n;return this._inViewTiles.getRenderableIds((n=this.transform)===null||n===void 0?void 0:n.bearingInRadians,t)}hasRenderableParent(t){let n=t.overscaledZ-1;if(n>=this._source.minzoom){let a=this.getLoadedTile(t.scaledTo(n));if(a)return this._inViewTiles.isIdRenderable(a.tileID.key)}return!1}reload(t,n=void 0){if(this._paused)this._shouldReloadOnResume=!0;else{this._outOfViewCache.reset();for(let a of this._inViewTiles.getAllIds()){let c=this._inViewTiles.getTileById(a);n&&!this._source.shouldReloadTile(c,n)||(t?this._reloadTile(a,"expired"):c.state!=="errored"&&this._reloadTile(a,"reloading"))}}}_reloadTile(t,n){return p._(this,void 0,void 0,(function*(){let a=this._inViewTiles.getTileById(t);a&&(a.state!=="loading"&&(a.state=n),yield this._loadTile(a,t,n))}))}_tileLoaded(t,n,a,c){t.timeAdded=Xe(),t.selfFading&&(t.fadeEndTime=t.timeAdded+this._rasterFadeDuration),a==="expired"&&(t.refreshedUponExpiration=!0),this._setTileReloadTimer(n,t),c?.unmodified||(this.getSource().type==="raster-dem"&&t.dem&&(function(f,y){var x,w,P;let S=y.getRenderableIds();for(let E of S){if(!(!((x=f.neighboringTiles)===null||x===void 0)&&x[E]))continue;let C=y.getTileById(E);f.neighboringTiles[E].backfilled||_e(f,C),!((P=(w=C.neighboringTiles)===null||w===void 0?void 0:w[f.tileID.key])===null||P===void 0)&&P.backfilled||_e(C,f)}})(t,this._inViewTiles),this._state.initializeTileState(t,this.map?this.map.painter:null),t.aborted||this._source.fire(new p.n("data",{dataType:"source",tile:t,coord:t.tileID})))}getTile(t){return this.getTileByID(t.key)}getTileByID(t){return this._inViewTiles.getTileById(t)}_retainLoadedChildren(t,n){let a=this._getLoadedDescendents(n),c=new Set;for(let f of n){let y=a[f.key];if(!y?.length){c.add(f);continue}let x=f.overscaledZ+Xt.maxOverzooming,w=y.filter((E=>E.tileID.overscaledZ<=x));if(!w.length){c.add(f);continue}let P=Math.min(...w.map((E=>E.tileID.overscaledZ))),S=w.filter((E=>E.tileID.overscaledZ===P)).map((E=>E.tileID));for(let E of S)t[E.key]=E;this._areDescendentsComplete(S,P,f.overscaledZ)||c.add(f)}return c}_getLoadedDescendents(t){var n;let a={};for(let c of this._inViewTiles.getAllTiles().filter((f=>f.hasData())))for(let f of t)c.tileID.isChildOf(f)&&(a[n=f.key]||(a[n]=[]),a[f.key].push(c));return a}_areDescendentsComplete(t,n,a){return t.length===1&&t[0].isOverscaled()?t[0].overscaledZ===n:Math.pow(4,n-a)===t.length}getLoadedTile(t){return this._inViewTiles.getLoadedTile(t)}updateCacheSize(t){let n=Math.ceil(t.width/this._source.tileSize)+1,a=Math.ceil(t.height/this._source.tileSize)+1,c=Math.floor(n*a*(this._maxTileCacheZoomLevels===null?p.c.MAX_TILE_CACHE_ZOOM_LEVELS:this._maxTileCacheZoomLevels)),f=typeof this._maxTileCacheSize=="number"?Math.min(this._maxTileCacheSize,c):c;this._outOfViewCache.setMaxSize(f)}handleWrapJump(t){let n=Math.round((t-(this._prevLng===void 0?t:this._prevLng))/360);this._prevLng=t,n&&(this._inViewTiles.handleWrapJump(n),this._resetTileReloadTimers())}update(t,n){if(!this._sourceLoaded||this._paused)return;let a;this.transform=t,this.terrain=n,this.updateCacheSize(t),this.handleWrapJump(this.transform.center.lng),this.used||this.usedForTerrain?this._source.tileID?a=t.getVisibleUnwrappedCoordinates(this._source.tileID).map((w=>new p.a3(w.canonical.z,w.wrap,w.canonical.z,w.canonical.x,w.canonical.y))):(a=rn(t,{tileSize:this.usedForTerrain?this.tileSize:this._source.tileSize,minzoom:this._source.minzoom,maxzoom:this._source.type==="vector"&&this.map._zoomLevelsToOverscale!==void 0?t.maxZoom-this.map._zoomLevelsToOverscale:this._source.maxzoom,roundZoom:!this.usedForTerrain&&this._source.roundZoom,reparseOverscaled:this._source.reparseOverscaled,terrain:n,calculateTileZoom:this._source.calculateTileZoom}),this._source.hasTile&&(a=a.filter((w=>this._source.hasTile(w))))):a=[],this.usedForTerrain&&(a=this._addTerrainIdealTiles(a));let c=a.length===0&&!this._updated&&this._didEmitContent;this._updated=!0,c&&this.fire(new p.n("data",{sourceDataType:"idle",dataType:"source",sourceId:this.id}));let f=vi(t,this._source),y=this._updateRetainedTiles(a,f),x=oc(this._source.type);x&&this._rasterFadeDuration>0&&!n&&(function(w,P,S,E,C,z,B){let N=Xe(),G=p.at(P);for(let j of P){let $=w.getTileById(j.key);$.fadingDirection!==Ni.Departing&&$.fadeOpacity!==0||$.resetFadeLogic(),Fh(w,$,S,N,E,C,B)||ms(w,$,S,N,z,B)||sc($,G,N,B)||$.resetFadeLogic()}})(this._inViewTiles,a,y,this._maxFadingAncestorLevels,this._source.minzoom,this._source.maxzoom,this._rasterFadeDuration),x?this._cleanUpRasterTiles(y):this._cleanUpVectorTiles(y)}_cleanUpRasterTiles(t){for(let n of this._inViewTiles.getAllIds())t[n]||this._removeTile(n)}_cleanUpVectorTiles(t){for(let n of this._inViewTiles.getAllIds()){let a=this._inViewTiles.getTileById(n);t[n]?a.clearSymbolFadeHold():a.hasSymbolBuckets?a.holdingForSymbolFade()?a.symbolFadeFinished()&&this._removeTile(n):a.setSymbolHoldDuration(this.map._fadeDuration):this._removeTile(n)}}_addTerrainIdealTiles(t){let n=[];for(let a of t)if(a.canonical.z>this._source.minzoom){let c=a.scaledTo(a.canonical.z-1);n.push(c);let f=a.scaledTo(Math.max(this._source.minzoom,Math.min(a.canonical.z,5)));n.push(f)}return t.concat(n)}releaseSymbolFadeTiles(){for(let t of this._inViewTiles.getAllIds())this._inViewTiles.getTileById(t).holdingForSymbolFade()&&this._removeTile(t)}_updateRetainedTiles(t,n){var a;let c=new Set;for(let P of t)this._addTile(P).hasData()||c.add(P);let f=t.reduce(((P,S)=>(P[S.key]=S,P)),{}),y=this._retainLoadedChildren(f,c),x={},w=Math.max(n-Xt.maxUnderzooming,this._source.minzoom);for(let P of y){let S=this._inViewTiles.getTileById(P.key),E=S?.wasRequested();for(let C=P.overscaledZ-1;C>=w;--C){let z=P.scaledTo(C);if(x[z.key])break;if(x[z.key]=!0,S=this.getTile(z),!S&&E&&(S=this._addTile(z)),S){let B=S.hasData();if((B||!(!((a=this.map)===null||a===void 0)&&a.cancelPendingTileRequestsWhileZooming)||E)&&(f[z.key]=z),E=S.wasRequested(),B)break}}}return f}_addTile(t){let n=this._inViewTiles.getTileById(t.key);if(n)return n;n=this._outOfViewCache.getAndRemove(t),n&&(n.resetFadeLogic(),this._setTileReloadTimer(t.key,n),n.tileID=t,this._state.initializeTileState(n,this.map?this.map.painter:null));let a=n;return n||(n=new kn(t,this._source.tileSize*t.overscaleFactor()),this._loadTile(n,t.key,n.state)),n.uses++,this._inViewTiles.setTile(t.key,n),a||this._source.fire(new p.n("dataloading",{tile:n,coord:n.tileID,dataType:"source"})),n}_setTileReloadTimer(t,n){this._clearTileReloadTimer(t);let a=n.getExpiryTimeout();a&&(this._timers[t]=setTimeout((()=>{this._reloadTile(t,"expired"),delete this._timers[t]}),a))}_clearTileReloadTimer(t){let n=this._timers[t];n&&(clearTimeout(n),delete this._timers[t])}_resetTileReloadTimers(){for(let t in this._timers)clearTimeout(this._timers[t]),delete this._timers[t];for(let t of this._inViewTiles.getAllIds()){let n=this._inViewTiles.getTileById(t);this._setTileReloadTimer(t,n)}}refreshTiles(t){for(let n of this._inViewTiles.getAllIds()){let a=this._inViewTiles.getTileById(n);(this._inViewTiles.isIdRenderable(n)||a.state=="errored")&&t.some((c=>c.equals(a.tileID.canonical)))&&this._reloadTile(n,"expired")}}_removeTile(t){let n=this._inViewTiles.getTileById(t);n&&(n.uses--,this._inViewTiles.deleteTileById(t),this._clearTileReloadTimer(t),n.uses>0||(n.hasData()&&n.state!=="reloading"?this._outOfViewCache.add(n.tileID,n,n.getExpiryTimeout()):(n.aborted=!0,this._abortTile(n),this._unloadTile(n))))}_dataHandler(t){t.dataType==="source"&&(t.sourceDataType!=="metadata"?t.sourceDataType==="content"&&this._sourceLoaded&&!this._paused&&(this.reload(t.sourceDataChanged,t.shouldReloadTileOptions),this.transform&&this.update(this.transform,this.terrain),this._didEmitContent=!0):this._sourceLoaded=!0)}clearTiles(){this._shouldReloadOnResume=!1,this._paused=!1;for(let t of this._inViewTiles.getAllIds())this._removeTile(t);this._outOfViewCache.reset()}tilesIn(t,n,a){let c=[],f=this.transform;if(!f)return c;let y=f.getCoveringTilesDetailsProvider().allowWorldCopies(),x=a?f.getCameraQueryGeometry(t):t,w=z=>f.screenPointToMercatorCoordinate(z,this.terrain),P=this.transformBbox(t,w,!y),S=this.transformBbox(x,w,!y),E=this.getIds(),C=p.a8.fromPoints(S);for(let z of E){let B=this._inViewTiles.getTileById(z);if(B.holdingForSymbolFade())continue;let N=y?[B.tileID]:[B.tileID.unwrapTo(-1),B.tileID.unwrapTo(0)],G=Math.pow(2,f.zoom-B.tileID.overscaledZ),j=n*B.queryPadding*p.a6/B.tileSize/G;for(let $ of N){let X=C.map((Z=>$.getTilePoint(new p.a7(Z.x,Z.y))));if(X.expandBy(j),X.intersects(nc)){let Z=P.map((H=>$.getTilePoint(H))),U=S.map((H=>$.getTilePoint(H)));c.push({tile:B,tileID:y?$:$.unwrapTo(0),queryGeometry:Z,cameraQueryGeometry:U,scale:G})}}}return c}transformBbox(t,n,a){let c=t.map(n);if(a){let f=p.a8.fromPoints(t);f.shrinkBy(.001*Math.min(f.width(),f.height()));let y=f.map(n);p.a8.fromPoints(c).covers(y)||(c=c.map((x=>x.x>.5?new p.a7(x.x-1,x.y,x.z):x)))}return c}getVisibleCoordinates(t){let n=this.getRenderableIds(t).map((a=>this._inViewTiles.getTileById(a).tileID));return this.transform&&this.transform.populateCache(n),n}hasTransition(){return!!this._source.hasTransition()||oc(this._source.type)&&(function(t,n){if(n<=0)return!1;let a=Xe();for(let c of t.getAllTiles())if(c.fadeEndTime>=a)return!0;return!1})(this._inViewTiles,this._rasterFadeDuration)}setRasterFadeDuration(t){this._rasterFadeDuration=t}setFeatureState(t,n,a){t||(t=p.ag),this._state.updateState(t,n,a)}removeFeatureState(t,n,a){t||(t=p.ag),this._state.removeFeatureState(t,n,a)}getFeatureState(t,n){return t||(t=p.ag),this._state.getState(t,n)}setDependencies(t,n,a){let c=this._inViewTiles.getTileById(t);c&&c.setDependencies(n,a)}reloadTilesForDependencies(t,n){for(let a of this._inViewTiles.getAllIds())this._inViewTiles.getTileById(a).hasDependency(t,n)&&this._reloadTile(a,"reloading");this._outOfViewCache.filter((a=>!a.hasDependency(t,n)))}areTilesLoaded(){for(let t of this._inViewTiles.getAllTiles())if(t.state!=="loaded"&&t.state!=="errored")return!1;return!0}}Xt.maxUnderzooming=10,Xt.maxOverzooming=3;class Va{constructor(t,n){this.reset(t,n)}reset(t,n){this.points=t||[],this._distances=[0];for(let a=1;a0?(c-y)/x:0;return this.points[f].mult(1-w).add(this.points[n].mult(w))}}function zr(u,t){let n=!0;return u==="always"||u!=="never"&&t!=="never"||(n=!1),n}class be{constructor(t,n,a){let c=this.boxCells=[],f=this.circleCells=[];this.xCellCount=Math.ceil(t/a),this.yCellCount=Math.ceil(n/a);for(let y=0;ythis.width||c<0||n>this.height)return[];let w=[];if(t<=0&&n<=0&&this.width<=a&&this.height<=c){if(f)return[{key:null,x1:t,y1:n,x2:a,y2:c}];for(let P=0;P0}hitTestCircle(t,n,a,c,f){let y=t-a,x=t+a,w=n-a,P=n+a;if(x<0||y>this.width||P<0||w>this.height)return!1;let S=[];return this._forEachCell(y,w,x,P,this._queryCellCircle,S,{hitTest:!0,overlapMode:c,circle:{x:t,y:n,radius:a},seenUids:{box:{},circle:{}}},f),S.length>0}_queryCell(t,n,a,c,f,y,x,w){let{seenUids:P,hitTest:S,overlapMode:E}=x,C=this.boxCells[f],z=1e-6;if(C!==null){let N=this.bboxes;for(let G of C)if(!P.box[G]){P.box[G]=!0;let j=4*G,$=this.boxKeys[G];if(t<=N[j+2]+z&&n<=N[j+3]+z&&a>=N[j+0]-z&&c>=N[j+1]-z&&(!w||w($))&&(!S||!zr(E,$.overlapMode))&&(y.push({key:$,x1:N[j],y1:N[j+1],x2:N[j+2],y2:N[j+3]}),S))return!0}}let B=this.circleCells[f];if(B!==null){let N=this.circles;for(let G of B)if(!P.circle[G]){P.circle[G]=!0;let j=3*G,$=this.circleKeys[G];if(this._circleAndRectCollide(N[j],N[j+1],N[j+2],t,n,a,c)&&(!w||w($))&&(!S||!zr(E,$.overlapMode))){let X=N[j],Z=N[j+1],U=N[j+2];if(y.push({key:$,x1:X-U,y1:Z-U,x2:X+U,y2:Z+U}),S)return!0}}}return!1}_queryCellCircle(t,n,a,c,f,y,x,w){let{circle:P,seenUids:S,overlapMode:E}=x,C=this.boxCells[f];if(C!==null){let B=this.bboxes;for(let N of C)if(!S.box[N]){S.box[N]=!0;let G=4*N,j=this.boxKeys[N];if(this._circleAndRectCollide(P.x,P.y,P.radius,B[G+0],B[G+1],B[G+2],B[G+3])&&(!w||w(j))&&!zr(E,j.overlapMode))return y.push(!0),!0}}let z=this.circleCells[f];if(z!==null){let B=this.circles;for(let N of z)if(!S.circle[N]){S.circle[N]=!0;let G=3*N,j=this.circleKeys[N];if(this._circlesCollide(B[G],B[G+1],B[G+2],P.x,P.y,P.radius)&&(!w||w(j))&&!zr(E,j.overlapMode))return y.push(!0),!0}}}_forEachCell(t,n,a,c,f,y,x,w){let P=this._convertToXCellCoord(t),S=this._convertToYCellCoord(n),E=this._convertToXCellCoord(a),C=this._convertToYCellCoord(c);for(let z=P;z<=E;z++)for(let B=S;B<=C;B++)if(f.call(this,t,n,a,c,this.xCellCount*B+z,y,x,w))return}_convertToXCellCoord(t){return Math.max(0,Math.min(this.xCellCount-1,Math.floor(t*this.xScale)))}_convertToYCellCoord(t){return Math.max(0,Math.min(this.yCellCount-1,Math.floor(t*this.yScale)))}_circlesCollide(t,n,a,c,f,y){let x=c-t,w=f-n,P=a+y;return P*P>x*x+w*w}_circleAndRectCollide(t,n,a,c,f,y,x){let w=(y-c)/2,P=Math.abs(t-(c+w));if(P>w+a)return!1;let S=(x-f)/2,E=Math.abs(n-(f+S));if(E>S+a)return!1;if(P<=w||E<=S)return!0;let C=P-w,z=E-S;return C*C+z*z<=a*a}}function Fe(u,t){let n=1/(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]),a=1/(t[8]*t[8]+t[9]*t[9]+t[10]*t[10]),c=t[0]*n,f=t[4]*n,y=t[8]*a,x=t[1]*n,w=t[5]*n,P=t[9]*a,S=t[2]*n,E=t[6]*n,C=t[10]*a;u[0]=c,u[1]=f,u[2]=y,u[4]=x,u[5]=w,u[6]=P,u[8]=S,u[9]=E,u[10]=C;let z=t[12],B=t[13],N=t[14];return u[12]=-c*z-x*B-S*N,u[13]=-f*z-w*B-E*N,u[14]=-y*z-P*B-C*N,u[3]=0,u[7]=0,u[11]=0,u[15]=1,u}let je=p.O();function Ei(u,t,n){let a=p.O();if(!u){let{vecSouth:E,vecEast:C}=ur(t),z=Sr();z[0]=C[0],z[1]=C[1],z[2]=E[0],z[3]=E[1],c=z,(S=(y=(f=z)[0])*(P=f[3])-(w=f[2])*(x=f[1]))&&(c[0]=P*(S=1/S),c[1]=-x*S,c[2]=-w*S,c[3]=y*S),a[0]=z[0],a[1]=z[1],a[4]=z[2],a[5]=z[3]}var c,f,y,x,w,P,S;return p.S(a,a,[1/n,1/n,1]),a}function gs(u,t,n,a){if(u){let c=p.O();if(!t){let{vecSouth:f,vecEast:y}=ur(n);c[0]=y[0],c[1]=y[1],c[4]=f[0],c[5]=f[1]}return p.S(c,c,[a,a,1]),c}return n.pixelsToClipSpaceMatrix}function ur(u){let t=Math.cos(u.rollInRadians),n=Math.sin(u.rollInRadians),a=Math.cos(u.pitchInRadians),c=Math.cos(u.bearingInRadians),f=Math.sin(u.bearingInRadians),y=p.az();y[0]=-c*a*n-f*t,y[1]=-f*a*n+c*t;let x=p.aA(y);x<1e-9?p.aB(y):p.aC(y,y,1/x);let w=p.az();w[0]=c*a*t-f*n,w[1]=f*a*t+c*n;let P=p.aA(w);return P<1e-9?p.aB(w):p.aC(w,w,1/P),{vecEast:w,vecSouth:y}}function Oe(u,t,n,a){let c;a?(c=[u,t,a(u,t),1],p.aE(c,c,n)):(c=[u,t,0,1],vs(c,c,n));let f=c[3];return{point:new p.P(c[0]/f,c[1]/f),signedDistanceFromCamera:f,isOccluded:!1}}function wo(u,t){return .5+u/t*.5}function To(u,t){return u.x>=-t[0]&&u.x<=t[0]&&u.y>=-t[1]&&u.y<=t[1]}function _s(u,t,n,a,c,f,y,x,w,P,S,E,C){let z=n?u.textSizeData:u.iconSizeData,B=p.aw(z,t.transform.zoom),N=[256/t.width*2+1,256/t.height*2+1],G=n?u.text.dynamicLayoutVertexArray:u.icon.dynamicLayoutVertexArray;G.clear();let j=u.lineVertexArray,$=n?u.text.placedSymbolArray:u.icon.placedSymbolArray,X=t.transform.width/t.transform.height,Z=!1;for(let U=0;U<$.length;U++){let H=$.get(U);if(H.hidden||H.writingMode===p.ax.vertical&&!Z){sn(H.numGlyphs,G);continue}Z=!1;let q=new p.P(H.anchorX,H.anchorY),Q={getElevation:C,pitchedLabelPlaneMatrix:a,lineVertexArray:j,pitchWithMap:f,projectionCache:{projections:{},offsets:{},cachedAnchorPoint:void 0,anyProjectionOccluded:!1},transform:t.transform,tileAnchorPoint:q,unwrappedTileID:w,width:P,height:S,translation:E},oe=Nn(H.anchorX,H.anchorY,Q);if(!To(oe.point,N)){sn(H.numGlyphs,G);continue}let se=wo(t.transform.cameraToCenterDistance,oe.signedDistanceFromCamera),de=p.ay(z,B,H),ue=f?de*t.transform.getPitchedTextCorrection(H.anchorX,H.anchorY,w)/se:de*se,Se=On({projectionContext:Q,pitchedLabelPlaneMatrixInverse:c,symbol:H,fontSize:ue,flip:!1,keepUpright:y,glyphOffsetArray:u.glyphOffsetArray,dynamicLayoutVertexArray:G,aspectRatio:X,rotateToLine:x});Z=Se.useVertical,(Se.notEnoughRoom||Z||Se.needsFlipping&&On({projectionContext:Q,pitchedLabelPlaneMatrixInverse:c,symbol:H,fontSize:ue,flip:!0,keepUpright:y,glyphOffsetArray:u.glyphOffsetArray,dynamicLayoutVertexArray:G,aspectRatio:X,rotateToLine:x}).notEnoughRoom)&&sn(H.numGlyphs,G)}n?u.text.dynamicLayoutVertexBuffer.updateData(G):u.icon.dynamicLayoutVertexBuffer.updateData(G)}function Bn(u,t,n,a,c,f,y,x){let w=f.glyphStartIndex+f.numGlyphs,P=f.lineStartIndex,S=f.lineStartIndex+f.lineLength,E=t.getoffsetX(f.glyphStartIndex),C=t.getoffsetX(w-1),z=Xi(u*E,n,a,c,f.segment,P,S,x,y);if(!z)return null;let B=Xi(u*C,n,a,c,f.segment,P,S,x,y);return B?x.projectionCache.anyProjectionOccluded?null:{first:z,last:B}:null}function Po(u,t,n,a){return u===p.ax.horizontal&&Math.abs(n.y-t.y)>Math.abs(n.x-t.x)*a?{useVertical:!0}:(u===p.ax.vertical?t.yn.x)?{needsFlipping:!0}:null}function On(u){let{projectionContext:t,pitchedLabelPlaneMatrixInverse:n,symbol:a,fontSize:c,flip:f,keepUpright:y,glyphOffsetArray:x,dynamicLayoutVertexArray:w,aspectRatio:P,rotateToLine:S}=u,E=c/24,C=a.lineOffsetX*E,z=a.lineOffsetY*E,B;if(a.numGlyphs>1){let N=a.glyphStartIndex+a.numGlyphs,G=a.lineStartIndex,j=a.lineStartIndex+a.lineLength,$=Bn(E,x,C,z,f,a,S,t);if(!$)return{notEnoughRoom:!0};let X=ys($.first.point.x,$.first.point.y,t,n),Z=ys($.last.point.x,$.last.point.y,t,n);if(y&&!f){let U=Po(a.writingMode,X,Z,P);if(U)return U}B=[$.first];for(let U=a.glyphStartIndex+1;U0?X.point:So(t.tileAnchorPoint,$,G,1,t),U=ys(G.x,G.y,t,n),H=ys(Z.x,Z.y,t,n),q=Po(a.writingMode,U,H,P);if(q)return q}let N=Xi(E*x.getoffsetX(a.glyphStartIndex),C,z,f,a.segment,a.lineStartIndex,a.lineStartIndex+a.lineLength,t,S);if(!N||t.projectionCache.anyProjectionOccluded)return{notEnoughRoom:!0};B=[N]}for(let N of B)p.aD(w,N.point,N.angle);return{}}function So(u,t,n,a,c){let f=u.add(u.sub(t)._unit()),y=rt(f.x,f.y,c).point,x=n.sub(y);return n.add(x._mult(a/x.mag()))}function Yt(u,t,n){let a=t.projectionCache;if(a.projections[u])return a.projections[u];let c=new p.P(t.lineVertexArray.getx(u),t.lineVertexArray.gety(u)),f=rt(c.x,c.y,t);if(f.signedDistanceFromCamera>0)return a.projections[u]=f.point,a.anyProjectionOccluded||(a.anyProjectionOccluded=f.isOccluded),f.point;let y=u-n.direction;return So(n.distanceFromAnchor===0?t.tileAnchorPoint:new p.P(t.lineVertexArray.getx(y),t.lineVertexArray.gety(y)),c,n.previousVertex,n.absOffsetX-n.distanceFromAnchor+1,t)}function rt(u,t,n){let a=u+n.translation[0],c=t+n.translation[1],f;return n.pitchWithMap?(f=Oe(a,c,n.pitchedLabelPlaneMatrix,n.getElevation),f.isOccluded=!1):(f=n.transform.projectTileCoordinates(a,c,n.unwrappedTileID,n.getElevation),f.point.x=(.5*f.point.x+.5)*n.width,f.point.y=(.5*-f.point.y+.5)*n.height),f}function ys(u,t,n,a){if(n.pitchWithMap){let c=[u,t,0,1];return p.aE(c,c,a),n.transform.projectTileCoordinates(c[0]/c[3],c[1]/c[3],n.unwrappedTileID,n.getElevation).point}return{x:u/n.width*2-1,y:1-t/n.height*2}}function Nn(u,t,n){return n.transform.projectTileCoordinates(u,t,n.unwrappedTileID,n.getElevation)}function Io(u,t,n){return u._unit()._perp()._mult(t*n)}function on(u,t,n,a,c,f,y,x,w){if(x.projectionCache.offsets[u])return x.projectionCache.offsets[u];let P=n.add(t);if(u+w.direction=c)return x.projectionCache.offsets[u]=P,P;let S=Yt(u+w.direction,x,w),E=Io(S.sub(n),y,w.direction),C=n.add(E),z=S.add(E);return x.projectionCache.offsets[u]=p.aF(f,P,C,z)||P,x.projectionCache.offsets[u]}function Xi(u,t,n,a,c,f,y,x,w){let P=a?u-t:u+t,S=P>0?1:-1,E=0;a&&(S*=-1,E=Math.PI),S<0&&(E+=Math.PI);let C,z=S>0?f+c:f+c+1;x.projectionCache.cachedAnchorPoint?C=x.projectionCache.cachedAnchorPoint:(C=rt(x.tileAnchorPoint.x,x.tileAnchorPoint.y,x).point,x.projectionCache.cachedAnchorPoint=C);let B,N,G=C,j=C,$=0,X=0,Z=Math.abs(P),U=[],H;for(;$+X<=Z;){if(z+=S,z=y)return null;$+=X,j=G,N=B;let oe={absOffsetX:Z,direction:S,distanceFromAnchor:$,previousVertex:j};if(G=Yt(z,x,oe),n===0)U.push(j),H=G.sub(j);else{let se,de=G.sub(j);se=de.mag()===0?Io(Yt(z+S,x,oe).sub(G),n,S):Io(de,n,S),N||(N=j.add(se)),B=on(z,se,G,f,y,N,n,x,oe),U.push(N),H=B.sub(N)}X=H.mag()}let q=H._mult((Z-$)/X)._add(N||j),Q=E+Math.atan2(G.y-j.y,G.x-j.x);return U.push(q),{point:q,angle:w?Q:0,path:U}}let ac=new Float32Array([-1/0,-1/0,0,-1/0,-1/0,0,-1/0,-1/0,0,-1/0,-1/0,0]);function sn(u,t){for(let n=0;n=1;Ee--)ve.push(ue.path[Ee]);for(let Ee=1;Eett.signedDistanceFromCamera<=0))?[]:Ee.map((tt=>tt.point))}let we=[];if(ve.length>0){let Ee=ve[0].clone(),tt=ve[0].clone();for(let Mt=1;Mt=oe.x&&tt.x<=se.x&&Ee.y>=oe.y&&tt.y<=se.y?[ve]:tt.xse.x||tt.yse.y?[]:p.aG([ve],oe.x,oe.y,se.x,se.y)}for(let Ee of we){de.reset(Ee,.25*Q);let tt=0;tt=de.length<=.5*Q?1:Math.ceil(de.paddedLength/he)+1;for(let Mt=0;Mt{let w=Oe(x.x,x.y,y,f.getElevation),P=f.transform.projectTileCoordinates(w.point.x,w.point.y,f.unwrappedTileID,f.getElevation);return P.point.x=(.5*P.point.x+.5)*f.width,P.point.y=(.5*-P.point.y+.5)*f.height,P}))})(t,n);return(function(c){let f=0,y=0,x=0,w=0;for(let P=0;Py&&(y=w,f=x));return c.slice(f,f+y)})(a)}queryRenderedSymbols(t){if(t.length===0||this.grid.keysLength()===0&&this.ignoredGrid.keysLength()===0)return{};let n=[],a=new p.a8;for(let E of t){let C=new p.P(E.x+bt,E.y+bt);a.extend(C),n.push(C)}let{minX:c,minY:f,maxX:y,maxY:x}=a,w=this.grid.query(c,f,y,x).concat(this.ignoredGrid.query(c,f,y,x)),P={},S={};for(let E of w){let C=E.key;if(P[C.bucketInstanceId]===void 0&&(P[C.bucketInstanceId]={}),P[C.bucketInstanceId][C.featureIndex])continue;let z=[new p.P(E.x1,E.y1),new p.P(E.x2,E.y1),new p.P(E.x2,E.y2),new p.P(E.x1,E.y2)];p.aH(n,z)&&(P[C.bucketInstanceId][C.featureIndex]=!0,S[C.bucketInstanceId]===void 0&&(S[C.bucketInstanceId]=[]),S[C.bucketInstanceId].push(C.featureIndex))}return S}insertCollisionBox(t,n,a,c,f,y){(a?this.ignoredGrid:this.grid).insert({bucketInstanceId:c,featureIndex:f,collisionGroupID:y,overlapMode:n},t[0],t[1],t[2],t[3])}insertCollisionCircles(t,n,a,c,f,y){let x=a?this.ignoredGrid:this.grid,w={bucketInstanceId:c,featureIndex:f,collisionGroupID:y,overlapMode:n};for(let P=0;P=this.screenRightBoundary||cthis.screenBottomBoundary}isInsideGrid(t,n,a,c){return a>=0&&t=0&&nthis.projectAndGetPerspectiveRatio(he.x,he.y,c,P,E)));Se=ve.some((he=>!he.isOccluded)),ue=ve.map((he=>new p.P(he.x,he.y)))}else Se=!0;return{box:p.aI(ue),allPointsOccluded:!Se}}}class cc{constructor(t,n,a,c){this.opacity=t?Math.max(0,Math.min(1,t.opacity+(t.placed?n:-n))):c&&a?1:0,this.placed=a}isHidden(){return this.opacity===0&&!this.placed}}class Mo{constructor(t,n,a,c,f){this.text=new cc(t?t.text:null,n,a,f),this.icon=new cc(t?t.icon:null,n,c,f)}isHidden(){return this.text.isHidden()&&this.icon.isHidden()}}class hc{constructor(t,n,a){this.text=t,this.icon=n,this.skipFade=a}}class uc{constructor(t,n,a,c,f){this.bucketInstanceId=t,this.featureIndex=n,this.sourceLayerIndex=a,this.bucketIndex=c,this.tileID=f}}class dc{constructor(t){this.crossSourceCollisions=t,this.maxGroupID=0,this.collisionGroups={}}get(t){if(this.crossSourceCollisions)return{ID:0,predicate:null};if(!this.collisionGroups[t]){let n=++this.maxGroupID;this.collisionGroups[t]={ID:n,predicate:a=>a.collisionGroupID===n}}return this.collisionGroups[t]}}function xs(u,t,n,a,c){let{horizontalAlign:f,verticalAlign:y}=p.aP(u);return new p.P(-(f-.5)*t+a[0]*c,-(y-.5)*n+a[1]*c)}class ja{constructor(t,n,a,c,f){this.transform=t.clone(),this.terrain=n,this.collisionIndex=new lc(this.transform),this.placements={},this.opacities={},this.variableOffsets={},this.stale=!1,this.commitTime=0,this.fadeDuration=a,this.retainedQueryData={},this.collisionGroups=new dc(c),this.collisionCircleArrays={},this.collisionBoxArrays=new Map,this.prevPlacement=f,f&&(f.prevPlacement=void 0),this.placedOrientations={}}_getTerrainElevationFunc(t){let n=this.terrain;return n?(a,c)=>n.getElevation(t,a,c):null}getBucketParts(t,n,a,c){let f=a.getBucket(n),y=a.latestFeatureIndex;if(!f||!y||n.id!==f.layerIds[0])return;let x=a.collisionBoxArray,w=f.layers[0].layout,P=f.layers[0].paint,S=Math.pow(2,this.transform.zoom-a.tileID.overscaledZ),E=a.tileSize/p.a6,C=a.tileID.toUnwrapped(),z=w.get("text-rotation-alignment")==="map",B=p.aK(a,1,this.transform.zoom),N=p.aL(this.collisionIndex.transform,a,P.get("text-translate"),P.get("text-translate-anchor")),G=p.aL(this.collisionIndex.transform,a,P.get("icon-translate"),P.get("icon-translate-anchor")),j=Ei(z,this.transform,B);this.retainedQueryData[f.bucketInstanceId]=new uc(f.bucketInstanceId,y,f.sourceLayerIndex,f.index,a.tileID);let $={bucket:f,layout:w,translationText:N,translationIcon:G,unwrappedTileID:C,pitchedLabelPlaneMatrix:j,scale:S,textPixelRatio:E,holdingForFade:a.holdingForSymbolFade(),collisionBoxArray:x,partiallyEvaluatedTextSize:p.aw(f.textSizeData,this.transform.zoom),collisionGroup:this.collisionGroups.get(f.sourceID)};if(c)for(let X of f.sortKeyRanges){let{sortKey:Z,symbolInstanceStart:U,symbolInstanceEnd:H}=X;t.push({sortKey:Z,symbolInstanceStart:U,symbolInstanceEnd:H,parameters:$})}else t.push({symbolInstanceStart:0,symbolInstanceEnd:f.symbolInstances.length,parameters:$})}attemptAnchorPlacement(t,n,a,c,f,y,x,w,P,S,E,C,z,B,N,G,j,$,X,Z){var U,H,q;let Q=p.aM[t.textAnchor],oe=[t.textOffset0,t.textOffset1],se=xs(Q,a,c,oe,f),de=this.collisionIndex.placeCollisionBox(n,C,w,P,S,x,y,G,E.predicate,X,se,Z);if((!$||this.collisionIndex.placeCollisionBox($,C,w,P,S,x,y,j,E.predicate,X,se,Z).placeable)&&de.placeable){let ue;if(!((U=this.prevPlacement)===null||U===void 0)&&U.variableOffsets[z.crossTileID]&&(!((q=(H=this.prevPlacement)===null||H===void 0?void 0:H.placements[z.crossTileID])===null||q===void 0)&&q.text)&&(ue=this.prevPlacement.variableOffsets[z.crossTileID].anchor),z.crossTileID===0)throw new Error("symbolInstance.crossTileID can't be 0");return this.variableOffsets[z.crossTileID]={textOffset:oe,width:a,height:c,anchor:Q,textBoxScale:f,prevAnchor:ue},this.markUsedJustification(B,Q,z,N),B.allowVerticalPlacement&&(this.markUsedOrientation(B,N,z),this.placedOrientations[z.crossTileID]=N),{shift:se,placedGlyphBoxes:de}}}placeLayerBucketPart(t,n,a){let{bucket:c,layout:f,translationText:y,translationIcon:x,unwrappedTileID:w,pitchedLabelPlaneMatrix:P,textPixelRatio:S,holdingForFade:E,collisionBoxArray:C,partiallyEvaluatedTextSize:z,collisionGroup:B}=t.parameters,N=f.get("text-optional"),G=f.get("icon-optional"),j=p.aN(f,"text-overlap","text-allow-overlap"),$=j==="always",X=p.aN(f,"icon-overlap","icon-allow-overlap"),Z=X==="always",U=f.get("text-rotation-alignment")==="map",H=f.get("text-pitch-alignment")==="map",q=f.get("icon-text-fit")!=="none",Q=f.get("symbol-z-order")==="viewport-y",oe=$&&(Z||!c.hasIconData()||G),se=Z&&($||!c.hasTextData()||N);!c.collisionArrays&&C&&c.deserializeCollisionBoxes(C);let de=this.retainedQueryData[c.bucketInstanceId].tileID,ue=this._getTerrainElevationFunc(de),Se=this.transform.getFastPathSimpleProjectionMatrix(de),ve=(he,we,Ee)=>{var tt,Mt;if(n[he.crossTileID])return;if(E)return void(this.placements[he.crossTileID]=new hc(!1,!1,!1));let ot=!1,Ct=!1,Dt=!0,ti=null,wt={box:null,placeable:!1,offscreen:null,occluded:!1},di={placeable:!1},Kt=null,Nt=null,ii=null,Nr=0,Vr=0,jr=0;we.textFeatureIndex?Nr=we.textFeatureIndex:he.useRuntimeCollisionCircles&&(Nr=he.featureIndex),we.verticalTextFeatureIndex&&(Vr=we.verticalTextFeatureIndex);let ri=we.textBox;if(ri){let sr=gt=>{let ut=p.ax.horizontal;if(c.allowVerticalPlacement&&!gt&&this.prevPlacement){let zt=this.prevPlacement.placedOrientations[he.crossTileID];zt&&(this.placedOrientations[he.crossTileID]=zt,ut=zt,this.markUsedOrientation(c,ut,he))}return ut},ar=(gt,ut)=>{if(c.allowVerticalPlacement&&he.numVerticalGlyphVertices>0&&we.verticalTextBox){for(let zt of c.writingModes)if(zt===p.ax.vertical?(wt=ut(),di=wt):wt=gt(),wt?.placeable)break}else wt=gt()},Ri=he.textAnchorOffsetStartIndex,Gi=he.textAnchorOffsetEndIndex;if(Gi===Ri){let gt=(ut,zt)=>{let _t=this.collisionIndex.placeCollisionBox(ut,j,S,de,w,H,U,y,B.predicate,ue,void 0,Se);return _t?.placeable&&(this.markUsedOrientation(c,zt,he),this.placedOrientations[he.crossTileID]=zt),_t};ar((()=>gt(ri,p.ax.horizontal)),(()=>{let ut=we.verticalTextBox;return c.allowVerticalPlacement&&he.numVerticalGlyphVertices>0&&ut?gt(ut,p.ax.vertical):{box:null,offscreen:null}})),sr(wt?.placeable)}else{let gt=p.aM[(Mt=(tt=this.prevPlacement)===null||tt===void 0?void 0:tt.variableOffsets[he.crossTileID])===null||Mt===void 0?void 0:Mt.anchor],ut=(_t,Pn,na)=>{let vr=_t.x2-_t.x1,Ll=_t.y2-_t.y1,ah=he.textBoxScale,Fl=q&&X==="never"?Pn:null,Gr=null,$r=j==="never"?1:2,Zr="never";gt&&$r++;for(let Bl=0;Bl<$r;Bl++){for(let Ol=Ri;Olut(ri,we.iconBox,p.ax.horizontal)),(()=>{let _t=we.verticalTextBox;return c.allowVerticalPlacement&&!wt?.placeable&&he.numVerticalGlyphVertices>0&&_t?ut(_t,we.verticalIconBox,p.ax.vertical):{box:null,occluded:!0,offscreen:null}})),wt&&(ot=wt.placeable,Dt=wt.offscreen);let zt=sr(wt?.placeable);if(!ot&&this.prevPlacement){let _t=this.prevPlacement.variableOffsets[he.crossTileID];_t&&(this.variableOffsets[he.crossTileID]=_t,this.markUsedJustification(c,_t.anchor,he,zt))}}}if(Kt=wt,ot=Kt?.placeable,Dt=Kt?.offscreen,he.useRuntimeCollisionCircles&&he.centerJustifiedTextSymbolIndex>=0){let sr=c.text.placedSymbolArray.get(he.centerJustifiedTextSymbolIndex),ar=p.ay(c.textSizeData,z,sr),Ri=f.get("text-padding");Nt=this.collisionIndex.placeCollisionCircles(j,sr,c.lineVertexArray,c.glyphOffsetArray,ar,w,P,a,H,B.predicate,he.collisionCircleDiameter,Ri,y,ue),Nt.circles.length&&Nt.collisionDetected&&!a&&p.w("Collisions detected, but collision boxes are not shown"),ot=$||Nt.circles.length>0&&!Nt.collisionDetected,Dt&&(Dt=Nt.offscreen)}if(we.iconFeatureIndex&&(jr=we.iconFeatureIndex),we.iconBox){let sr=ar=>this.collisionIndex.placeCollisionBox(ar,X,S,de,w,H,U,x,B.predicate,ue,q&&ti?ti:void 0,Se);di&&di.placeable&&we.verticalIconBox?(ii=sr(we.verticalIconBox),Ct=ii.placeable):(ii=sr(we.iconBox),Ct=ii.placeable),Dt&&(Dt=ii.offscreen)}let yr=N||he.numHorizontalGlyphVertices===0&&he.numVerticalGlyphVertices===0,Ur=G||he.numIconVertices===0;yr||Ur?Ur?yr||Ct&&(Ct=ot):ot=Ct&&ot:Ct=ot=Ct&&ot;let ra=Ct&&ii.placeable;if(ot&&Kt.placeable&&this.collisionIndex.insertCollisionBox(Kt.box,j,f.get("text-ignore-placement"),c.bucketInstanceId,di&&di.placeable&&Vr?Vr:Nr,B.ID),ra&&this.collisionIndex.insertCollisionBox(ii.box,X,f.get("icon-ignore-placement"),c.bucketInstanceId,jr,B.ID),Nt&&ot&&this.collisionIndex.insertCollisionCircles(Nt.circles,j,f.get("text-ignore-placement"),c.bucketInstanceId,Nr,B.ID),a&&this.storeCollisionData(c.bucketInstanceId,Ee,we,Kt,ii,Nt),he.crossTileID===0)throw new Error("symbolInstance.crossTileID can't be 0");if(c.bucketInstanceId===0)throw new Error("bucket.bucketInstanceId can't be 0");this.placements[he.crossTileID]=new hc((ot||oe)&&!Kt?.occluded,(Ct||se)&&!ii?.occluded,Dt||c.justReloaded),n[he.crossTileID]=!0};if(Q){if(t.symbolInstanceStart!==0)throw new Error("bucket.bucketInstanceId should be 0");let he=c.getSortedSymbolIndexes(-this.transform.bearingInRadians);for(let we=he.length-1;we>=0;--we){let Ee=he[we];ve(c.symbolInstances.get(Ee),c.collisionArrays[Ee],Ee)}}else for(let he=t.symbolInstanceStart;he=0&&(t.text.placedSymbolArray.get(x).crossTileID=f>=0&&x!==f?0:a.crossTileID)}markUsedOrientation(t,n,a){let c=n===p.ax.horizontal||n===p.ax.horizontalOnly?n:0,f=n===p.ax.vertical?n:0,y=[a.leftJustifiedTextSymbolIndex,a.centerJustifiedTextSymbolIndex,a.rightJustifiedTextSymbolIndex];for(let x of y)t.text.placedSymbolArray.get(x).placedOrientation=c;a.verticalPlacedTextSymbolIndex&&(t.text.placedSymbolArray.get(a.verticalPlacedTextSymbolIndex).placedOrientation=f)}commit(t){this.commitTime=t,this.zoomAtLastRecencyCheck=this.transform.zoom;let n=this.prevPlacement,a=!1;this.prevZoomAdjustment=n?n.zoomAdjustment(this.transform.zoom):0;let c=n?n.symbolFadeChange(t):1,f=n?n.opacities:{},y=n?n.variableOffsets:{},x=n?n.placedOrientations:{};for(let w in this.placements){let P=this.placements[w],S=f[w];S?(this.opacities[w]=new Mo(S,c,P.text,P.icon),a||(a=P.text!==S.text.placed),a||(a=P.icon!==S.icon.placed)):(this.opacities[w]=new Mo(null,c,P.text,P.icon,P.skipFade),a||(a=P.text||P.icon))}for(let w in f){let P=f[w];if(!this.opacities[w]){let S=new Mo(P,c,!1,!1);S.isHidden()||(this.opacities[w]=S,a||(a=P.text.placed),a||(a=P.icon.placed))}}for(let w in y)this.variableOffsets[w]||!this.opacities[w]||this.opacities[w].isHidden()||(this.variableOffsets[w]=y[w]);for(let w in x)this.placedOrientations[w]||!this.opacities[w]||this.opacities[w].isHidden()||(this.placedOrientations[w]=x[w]);if(n&&n.lastPlacementChangeTime===void 0)throw new Error("Last placement time for previous placement is not defined");a?this.lastPlacementChangeTime=t:typeof this.lastPlacementChangeTime!="number"&&(this.lastPlacementChangeTime=n?n.lastPlacementChangeTime:t)}updateLayerOpacities(t,n){let a={};for(let c of n){let f=c.getBucket(t);f&&c.latestFeatureIndex&&t.id===f.layerIds[0]&&this.updateBucketOpacities(f,c.tileID,a,c.collisionBoxArray)}}updateBucketOpacities(t,n,a,c){t.hasTextData()&&(t.text.opacityVertexArray.clear(),t.text.hasVisibleVertices=!1),t.hasIconData()&&(t.icon.opacityVertexArray.clear(),t.icon.hasVisibleVertices=!1),t.hasIconCollisionBoxData()&&t.iconCollisionBox.collisionVertexArray.clear(),t.hasTextCollisionBoxData()&&t.textCollisionBox.collisionVertexArray.clear();let f=t.layers[0],y=f.layout,x=new Mo(null,0,!1,!1,!0),w=y.get("text-allow-overlap"),P=y.get("icon-allow-overlap"),S=f._unevaluatedLayout.hasValue("text-variable-anchor")||f._unevaluatedLayout.hasValue("text-variable-anchor-offset"),E=y.get("text-rotation-alignment")==="map",C=y.get("text-pitch-alignment")==="map",z=y.get("icon-text-fit")!=="none",B=new Mo(null,0,w&&(P||!t.hasIconData()||y.get("icon-optional")),P&&(w||!t.hasTextData()||y.get("text-optional")),!0);!t.collisionArrays&&c&&(t.hasIconCollisionBoxData()||t.hasTextCollisionBoxData())&&t.deserializeCollisionBoxes(c);let N=(j,$,X)=>{for(let Z=0;Z<$/4;Z++)j.opacityVertexArray.emplaceBack(X);j.hasVisibleVertices||(j.hasVisibleVertices=X!==Co)},G=this.collisionBoxArrays.get(t.bucketInstanceId);for(let j=0;j0,Q=this.placedOrientations[$.crossTileID],oe=Q===p.ax.vertical,se=Q===p.ax.horizontal||Q===p.ax.horizontalOnly;if(X>0||Z>0){let ue=Za(H.text);N(t.text,X,oe?Co:ue),N(t.text,Z,se?Co:ue);let Se=H.text.isHidden(),ve=[$.rightJustifiedTextSymbolIndex,$.centerJustifiedTextSymbolIndex,$.leftJustifiedTextSymbolIndex];for(let Ee of ve)Ee>=0&&(t.text.placedSymbolArray.get(Ee).hidden=Se||oe?1:0);$.verticalPlacedTextSymbolIndex>=0&&(t.text.placedSymbolArray.get($.verticalPlacedTextSymbolIndex).hidden=Se||se?1:0);let he=this.variableOffsets[$.crossTileID];he&&this.markUsedJustification(t,he.anchor,$,Q);let we=this.placedOrientations[$.crossTileID];we&&(this.markUsedJustification(t,"left",$,we),this.markUsedOrientation(t,we,$))}if(q){let ue=Za(H.icon),Se=!(z&&$.verticalPlacedIconSymbolIndex&&oe);$.placedIconSymbolIndex>=0&&(N(t.icon,$.numIconVertices,Se?ue:Co),t.icon.placedSymbolArray.get($.placedIconSymbolIndex).hidden=H.icon.isHidden()),$.verticalPlacedIconSymbolIndex>=0&&(N(t.icon,$.numVerticalIconVertices,Se?Co:ue),t.icon.placedSymbolArray.get($.verticalPlacedIconSymbolIndex).hidden=H.icon.isHidden())}let de=G?.has(j)?G.get(j):{text:null,icon:null};if(t.hasIconCollisionBoxData()||t.hasTextCollisionBoxData()){let ue=t.collisionArrays[j];if(ue){let Se=new p.P(0,0);if(ue.textBox||ue.verticalTextBox){let ve=!0;if(S){let he=this.variableOffsets[U];he?(Se=xs(he.anchor,he.width,he.height,he.textOffset,he.textBoxScale),E&&Se._rotate(C?-this.transform.bearingInRadians:this.transform.bearingInRadians)):ve=!1}if(ue.textBox||ue.verticalTextBox){let he;ue.textBox&&(he=oe),ue.verticalTextBox&&(he=se),Ua(t.textCollisionBox.collisionVertexArray,H.text.placed,!ve||he,de.text,Se.x,Se.y)}}if(ue.iconBox||ue.verticalIconBox){let ve=!!(!se&&ue.verticalIconBox),he;ue.iconBox&&(he=ve),ue.verticalIconBox&&(he=!ve),Ua(t.iconCollisionBox.collisionVertexArray,H.icon.placed,he,de.icon,z?Se.x:0,z?Se.y:0)}}}}if(t.sortFeatures(-this.transform.bearingInRadians),this.retainedQueryData[t.bucketInstanceId]&&(this.retainedQueryData[t.bucketInstanceId].featureSortOrder=t.featureSortOrder),t.hasTextData()&&t.text.opacityVertexBuffer&&t.text.opacityVertexBuffer.updateData(t.text.opacityVertexArray),t.hasIconData()&&t.icon.opacityVertexBuffer&&t.icon.opacityVertexBuffer.updateData(t.icon.opacityVertexArray),t.hasIconCollisionBoxData()&&t.iconCollisionBox.collisionVertexBuffer&&t.iconCollisionBox.collisionVertexBuffer.updateData(t.iconCollisionBox.collisionVertexArray),t.hasTextCollisionBoxData()&&t.textCollisionBox.collisionVertexBuffer&&t.textCollisionBox.collisionVertexBuffer.updateData(t.textCollisionBox.collisionVertexArray),t.text.opacityVertexArray.length!==t.text.layoutVertexArray.length/4)throw new Error(`bucket.text.opacityVertexArray.length (= ${t.text.opacityVertexArray.length}) !== bucket.text.layoutVertexArray.length (= ${t.text.layoutVertexArray.length}) / 4`);if(t.icon.opacityVertexArray.length!==t.icon.layoutVertexArray.length/4)throw new Error(`bucket.icon.opacityVertexArray.length (= ${t.icon.opacityVertexArray.length}) !== bucket.icon.layoutVertexArray.length (= ${t.icon.layoutVertexArray.length}) / 4`);t.bucketInstanceId in this.collisionCircleArrays&&(t.collisionCircleArray=this.collisionCircleArrays[t.bucketInstanceId],delete this.collisionCircleArrays[t.bucketInstanceId])}symbolFadeChange(t){return this.fadeDuration===0?1:(t-this.commitTime)/this.fadeDuration+this.prevZoomAdjustment}zoomAdjustment(t){return Math.max(0,(this.transform.zoom-t)/1.5)}hasTransitions(t){return this.stale||t-this.lastPlacementChangeTimet}setStale(){this.stale=!0}}function Ua(u,t,n,a,c,f){a&&a.length!==0||(a=[0,0,0,0]);let y=a[0]-bt,x=a[1]-bt,w=a[2]-bt,P=a[3]-bt;u.emplaceBack(t?1:0,n?1:0,c||0,f||0,y,x),u.emplaceBack(t?1:0,n?1:0,c||0,f||0,w,x),u.emplaceBack(t?1:0,n?1:0,c||0,f||0,w,P),u.emplaceBack(t?1:0,n?1:0,c||0,f||0,y,P)}let Ga=Math.pow(2,25),$a=Math.pow(2,24),Bh=Math.pow(2,17),Eo=Math.pow(2,16),bs=Math.pow(2,9),pc=Math.pow(2,8),Vn=Math.pow(2,1);function Za(u){if(u.opacity===0&&!u.placed)return 0;if(u.opacity===1&&u.placed)return 4294967295;let t=u.placed?1:0,n=Math.floor(127*u.opacity);return n*Ga+t*$a+n*Bh+t*Eo+n*bs+t*pc+n*Vn+t}let Co=0;class Rr{constructor(t){this._sortAcrossTiles=t.layout.get("symbol-z-order")!=="viewport-y"&&!t.layout.get("symbol-sort-key").isConstant(),this._currentTileIndex=0,this._currentPartIndex=0,this._seenCrossTileIDs={},this._bucketParts=[]}continuePlacement(t,n,a,c,f){let y=this._bucketParts;for(;this._currentTileIndexx.sortKey-w.sortKey)));this._currentPartIndex!this._forceFullPlacement&&Xe()-c>2;for(;this._currentPlacementIndex>=0;){let y=n[t[this._currentPlacementIndex]],x=this.placement.collisionIndex.transform.zoom;if(p.aQ(y)&&y.layout&&(!y.minzoom||y.minzoom<=x)&&(!y.maxzoom||y.maxzoom>x)){if(this._inProgressLayer||(this._inProgressLayer=new Rr(y)),this._inProgressLayer.continuePlacement(a[y.source],this.placement,this._showCollisionBoxes,y,f))return;delete this._inProgressLayer}this._currentPlacementIndex--}this._done=!0}commit(t){return this.placement.commit(t),this.placement}}let Ve=512/p.a6/2;class qa{constructor(t,n,a){this.tileID=t,this.bucketInstanceId=a,this._symbolsByKey={};let c=new Map;for(let f=0;f({x:Math.floor(w.anchorX*Ve),y:Math.floor(w.anchorY*Ve)}))),crossTileIDs:y.map((w=>w.crossTileID))};if(x.positions.length>128){let w=new p.aR(x.positions.length,16,Uint16Array);for(let{x:P,y:S}of x.positions)w.add(P,S);w.finish(),delete x.positions,x.index=w}this._symbolsByKey[f]=x}}getScaledCoordinates(t,n){let{x:a,y:c,z:f}=this.tileID.canonical,{x:y,y:x,z:w}=n.canonical,P=Ve/Math.pow(2,w-f),S=(x*p.a6+t.anchorY)*P,E=c*p.a6*Ve;return{x:Math.floor((y*p.a6+t.anchorX)*P-a*p.a6*Ve),y:Math.floor(S-E)}}findMatches(t,n,a){let c=this.tileID.canonical.zt))}}class Oh{constructor(){this.maxCrossTileID=0}generate(){return++this.maxCrossTileID}}class Wa{constructor(){this.indexes={},this.usedCrossTileIDs={},this.lng=0}handleWrapJump(t){let n=Math.round((t-this.lng)/360);if(n!==0)for(let a in this.indexes){let c=this.indexes[a],f={};for(let y in c){let x=c[y];x.tileID=x.tileID.unwrapTo(x.tileID.wrap+n),f[x.tileID.key]=x}this.indexes[a]=f}this.lng=t}addBucket(t,n,a){var c,f,y;if(!((c=this.indexes[t.overscaledZ])===null||c===void 0)&&c[t.key]){if(this.indexes[t.overscaledZ][t.key].bucketInstanceId===n.bucketInstanceId)return!1;this.removeBucketCrossTileIDs(t.overscaledZ,this.indexes[t.overscaledZ][t.key])}for(let w=0;wt.overscaledZ)for(let S in P){let E=P[S];E.tileID.isChildOf(t)&&E.findMatches(n.symbolInstances,t,x)}else{let S=P[t.scaledTo(Number(w)).key];S&&S.findMatches(n.symbolInstances,t,x)}}for(let w=0;w({u_depth:new p.b_(se,de.u_depth),u_terrain:new p.b_(se,de.u_terrain),u_terrain_dim:new p.bp(se,de.u_terrain_dim),u_terrain_matrix:new p.c0(se,de.u_terrain_matrix),u_terrain_unpack:new p.c1(se,de.u_terrain_unpack),u_terrain_exaggeration:new p.bp(se,de.u_terrain_exaggeration)}))(t,oe),this.projectionUniforms=((se,de)=>({u_projection_matrix:new p.c0(se,de.u_projection_matrix),u_projection_tile_mercator_coords:new p.c1(se,de.u_projection_tile_mercator_coords),u_projection_clipping_plane:new p.c1(se,de.u_projection_clipping_plane),u_projection_transition:new p.bp(se,de.u_projection_transition),u_projection_fallback_matrix:new p.c0(se,de.u_projection_fallback_matrix)}))(t,oe),this.binderUniforms=a?a.getUniforms(t,oe):[]}draw(t,n,a,c,f,y,x,w,P,S,E,C,z,B,N,G,j,$,X){var Z;let U=t.gl;if(this.failedToCreate)return;if(t.program.set(this.program),t.setDepthMode(a),t.setStencilMode(c),t.setColorMode(f),t.setCullFace(y),w){t.activeTexture.set(U.TEXTURE2),U.bindTexture(U.TEXTURE_2D,w.depthTexture),t.activeTexture.set(U.TEXTURE3),U.bindTexture(U.TEXTURE_2D,w.texture);for(let q in this.terrainUniforms)this.terrainUniforms[q].set(w[q])}if(P)for(let q in P)this.projectionUniforms[jh[q]].set(P[q]);if(x)for(let q in this.fixedUniforms)this.fixedUniforms[q].set(x[q]);G&&G.setUniforms(t,this.binderUniforms,B,{zoom:N});let H=0;switch(n){case U.LINES:H=2;break;case U.TRIANGLES:H=3;break;case U.LINE_STRIP:H=1}for(let q of z.get())q.vaos||(q.vaos={}),(Z=q.vaos)[S]||(Z[S]=new Vh),q.vaos[S].bind(t,this,E,G?G.getPaintVertexBuffers():[],C,q.vertexOffset,j,$,X),U.drawElements(n,q.primitiveLength*H,U.UNSIGNED_SHORT,q.primitiveOffset*H*2)}}function Qa(u,t,n){let a=1/p.aK(n,1,t.transform.tileZoom),c=Math.pow(2,n.tileID.overscaledZ),f=n.tileSize*Math.pow(2,t.transform.tileZoom)/c,y=f*(n.tileID.canonical.x+n.tileID.wrap*c),x=f*n.tileID.canonical.y;return{u_image:0,u_texsize:n.imageAtlasTexture.size,u_scale:[a,u.fromScale,u.toScale],u_fade:u.t,u_pixel_coord_upper:[y>>16,x>>16],u_pixel_coord_lower:[65535&y,65535&x]}}let vc=(u,t,n,a)=>{let c=u.style.light,f=c.properties.get("position"),y=[f.x,f.y,f.z],x=p.c4();c.properties.get("anchor")==="viewport"&&p.c5(x,u.transform.bearingInRadians),p.c6(y,y,x);let w=u.transform.transformLightDirection(y),P=c.properties.get("color");return{u_lightpos:y,u_lightpos_globe:w,u_lightintensity:c.properties.get("intensity"),u_lightcolor:[P.r,P.g,P.b],u_vertical_gradient:+t,u_opacity:n,u_fill_translate:a}},xc=(u,t,n,a,c,f,y)=>p.e(vc(u,t,n,a),Qa(f,u,y),{u_height_factor:-Math.pow(2,c.overscaledZ)/y.tileSize/8}),Cs=(u,t,n,a)=>p.e(Qa(t,u,n),{u_fill_translate:a}),bc=(u,t)=>({u_world:u,u_fill_translate:t}),wc=(u,t,n,a,c)=>p.e(Cs(u,t,n,c),{u_world:a}),Tc=(u,t,n,a,c)=>{let f=u.transform,y,x,w=0;if(n.paint.get("circle-pitch-alignment")==="map"){let P=p.aK(t,1,f.zoom);y=!0,x=[P,P],w=P/(p.a6*Math.pow(2,t.tileID.overscaledZ))*2*Math.PI*c}else y=!1,x=f.pixelsToGLUnits;return{u_camera_to_center_distance:f.cameraToCenterDistance,u_scale_with_map:+(n.paint.get("circle-pitch-scale")==="map"),u_pitch_with_map:+y,u_device_pixel_ratio:u.pixelRatio,u_extrude_scale:x,u_globe_extrude_scale:w,u_translate:a}},Pc=u=>({u_pixel_extrude_scale:[1/u.width,1/u.height]}),fn=u=>({u_viewport_size:[u.width,u.height]}),el=(u,t=1)=>({u_color:u,u_overlay:0,u_overlay_scale:t}),tl=(u,t,n,a)=>{let c=p.aK(u,1,t)/(p.a6*Math.pow(2,u.tileID.overscaledZ))*2*Math.PI*a;return{u_extrude_scale:p.aK(u,1,t),u_intensity:n,u_globe_extrude_scale:c}},Xn=(u,t,n,a)=>{let c=p.O();p.c7(c,0,u.width,u.height,0,0,1);let f=u.context.gl;return{u_matrix:c,u_world:[f.drawingBufferWidth,f.drawingBufferHeight],u_image:n,u_color_ramp:a,u_opacity:t.paint.get("heatmap-opacity")}},Gh=(u,t,n)=>{let a=n.paint.get("hillshade-accent-color"),c;switch(n.paint.get("hillshade-method")){case"basic":c=4;break;case"combined":c=1;break;case"igor":c=2;break;case"multidirectional":c=3;break;default:c=0}let f=n.getIlluminationProperties();for(let y=0;y{let n=t.stride,a=p.O();return p.c7(a,0,p.a6,-p.a6,0,0,1),p.Q(a,a,[0,-p.a6,0]),{u_matrix:a,u_image:1,u_dimension:[n,n],u_zoom:u.overscaledZ,u_unpack:t.getUnpackVector()}};function $h(u,t){let n=Math.pow(2,t.canonical.z),a=t.canonical.y;return[new p.a7(0,a/n).toLngLat().lat,new p.a7(0,(a+1)/n).toLngLat().lat]}let Zh=(u,t,n=0)=>({u_image:0,u_unpack:t.getUnpackVector(),u_dimension:[t.stride,t.stride],u_elevation_stops:1,u_color_stops:4,u_color_ramp_size:n,u_opacity:u.paint.get("color-relief-opacity")}),Ro=(u,t,n,a)=>{let c=u.transform;return{u_translation:rr(u,t,n),u_ratio:a/p.aK(t,1,c.zoom),u_device_pixel_ratio:u.pixelRatio,u_units_to_pixels:[1/c.pixelsToGLUnits[0],1/c.pixelsToGLUnits[1]]}},Sc=(u,t,n,a,c)=>p.e(Ro(u,t,n,a),{u_image:0,u_image_height:c}),Ic=(u,t,n,a,c)=>{let f=u.transform,y=Yn(t,f);return{u_translation:rr(u,t,n),u_texsize:t.imageAtlasTexture.size,u_ratio:a/p.aK(t,1,f.zoom),u_device_pixel_ratio:u.pixelRatio,u_image:0,u_scale:[y,c.fromScale,c.toScale],u_fade:c.t,u_units_to_pixels:[1/f.pixelsToGLUnits[0],1/f.pixelsToGLUnits[1]]}},il=(u,t,n,a,c)=>{let f=Yn(t,u.transform);return p.e(Ro(u,t,n,a),{u_tileratio:f,u_crossfade_from:c.fromScale,u_crossfade_to:c.toScale,u_image:0,u_mix:c.t,u_lineatlas_width:u.lineAtlas.width,u_lineatlas_height:u.lineAtlas.height})},Mc=(u,t,n,a,c,f)=>{let y=Yn(t,u.transform);return p.e(Ro(u,t,n,a),{u_image:0,u_image_height:f,u_tileratio:y,u_crossfade_from:c.fromScale,u_crossfade_to:c.toScale,u_image_dash:1,u_mix:c.t,u_lineatlas_width:u.lineAtlas.width,u_lineatlas_height:u.lineAtlas.height})};function Yn(u,t){return 1/p.aK(u,1,t.tileZoom)}function rr(u,t,n){return p.aL(u.transform,t,n.paint.get("line-translate"),n.paint.get("line-translate-anchor"))}let rl=(u,t,n,a,c)=>{return{u_tl_parent:u,u_scale_parent:t,u_buffer_scale:1,u_fade_t:n.mix,u_opacity:n.opacity*a.paint.get("raster-opacity"),u_image0:0,u_image1:1,u_brightness_low:a.paint.get("raster-brightness-min"),u_brightness_high:a.paint.get("raster-brightness-max"),u_saturation_factor:(y=a.paint.get("raster-saturation"),y>0?1-1/(1.001-y):-y),u_contrast_factor:(f=a.paint.get("raster-contrast"),f>0?1/(1-f):1+f),u_spin_weights:nl(a.paint.get("raster-hue-rotate")),u_coords_top:[c[0].x,c[0].y,c[1].x,c[1].y],u_coords_bottom:[c[3].x,c[3].y,c[2].x,c[2].y]};var f,y};function nl(u){u*=Math.PI/180;let t=Math.sin(u),n=Math.cos(u);return[(2*n+1)/3,(-Math.sqrt(3)*t-n+1)/3,(Math.sqrt(3)*t-n+1)/3]}let Ds=(u,t,n,a,c,f,y,x,w,P,S,E,C)=>{let z=y.transform;return{u_is_size_zoom_constant:+(u==="constant"||u==="source"),u_is_size_feature_constant:+(u==="constant"||u==="camera"),u_size_t:t?t.uSizeT:0,u_size:t?t.uSize:0,u_camera_to_center_distance:z.cameraToCenterDistance,u_pitch:z.pitch/360*2*Math.PI,u_rotate_symbol:+n,u_aspect_ratio:z.width/z.height,u_fade_change:y.options.fadeDuration?y.symbolFadeChange:1,u_label_plane_matrix:x,u_coord_matrix:w,u_is_text:+S,u_pitch_with_map:+a,u_is_along_line:c,u_is_variable_anchor:f,u_texsize:E,u_texture:0,u_translation:P,u_pitched_scale:C}},ol=(u,t,n,a,c,f,y,x,w,P,S,E,C,z)=>{let B=y.transform;return p.e(Ds(u,t,n,a,c,f,y,x,w,P,S,E,z),{u_gamma_scale:a?Math.cos(B.pitch*Math.PI/180)*B.cameraToCenterDistance:1,u_device_pixel_ratio:y.pixelRatio,u_is_halo:C?1:0,u_is_plain:1})},sl=(u,t,n,a,c,f,y,x,w,P,S,E,C)=>p.e(ol(u,t,n,a,c,f,y,x,w,P,!0,S,!0,C),{u_texsize_icon:E,u_texture_icon:1}),mn=(u,t)=>({u_opacity:u,u_color:t}),al=(u,t,n,a,c)=>p.e((function(f,y,x,w){let P=x.imageManager.getPattern(f.from.toString()),S=x.imageManager.getPattern(f.to.toString()),{width:E,height:C}=x.imageManager.getPixelSize(),z=Math.pow(2,w.tileID.overscaledZ),B=w.tileSize*Math.pow(2,x.transform.tileZoom)/z,N=B*(w.tileID.canonical.x+w.tileID.wrap*z),G=B*w.tileID.canonical.y;return{u_image:0,u_pattern_tl_a:P.tl,u_pattern_br_a:P.br,u_pattern_tl_b:S.tl,u_pattern_br_b:S.br,u_texsize:[E,C],u_mix:y.t,u_pattern_size_a:P.displaySize,u_pattern_size_b:S.displaySize,u_scale_a:y.fromScale,u_scale_b:y.toScale,u_tile_units_to_pixels:1/p.aK(w,1,x.transform.tileZoom),u_pixel_coord_upper:[N>>16,G>>16],u_pixel_coord_lower:[65535&N,65535&G]}})(n,c,t,a),{u_opacity:u}),Ec=(u,t)=>{},qh={fillExtrusion:(u,t)=>({u_lightpos:new p.c2(u,t.u_lightpos),u_lightpos_globe:new p.c2(u,t.u_lightpos_globe),u_lightintensity:new p.bp(u,t.u_lightintensity),u_lightcolor:new p.c2(u,t.u_lightcolor),u_vertical_gradient:new p.bp(u,t.u_vertical_gradient),u_opacity:new p.bp(u,t.u_opacity),u_fill_translate:new p.c3(u,t.u_fill_translate)}),fillExtrusionPattern:(u,t)=>({u_lightpos:new p.c2(u,t.u_lightpos),u_lightpos_globe:new p.c2(u,t.u_lightpos_globe),u_lightintensity:new p.bp(u,t.u_lightintensity),u_lightcolor:new p.c2(u,t.u_lightcolor),u_vertical_gradient:new p.bp(u,t.u_vertical_gradient),u_height_factor:new p.bp(u,t.u_height_factor),u_opacity:new p.bp(u,t.u_opacity),u_fill_translate:new p.c3(u,t.u_fill_translate),u_image:new p.b_(u,t.u_image),u_texsize:new p.c3(u,t.u_texsize),u_pixel_coord_upper:new p.c3(u,t.u_pixel_coord_upper),u_pixel_coord_lower:new p.c3(u,t.u_pixel_coord_lower),u_scale:new p.c2(u,t.u_scale),u_fade:new p.bp(u,t.u_fade)}),fill:(u,t)=>({u_fill_translate:new p.c3(u,t.u_fill_translate)}),fillPattern:(u,t)=>({u_image:new p.b_(u,t.u_image),u_texsize:new p.c3(u,t.u_texsize),u_pixel_coord_upper:new p.c3(u,t.u_pixel_coord_upper),u_pixel_coord_lower:new p.c3(u,t.u_pixel_coord_lower),u_scale:new p.c2(u,t.u_scale),u_fade:new p.bp(u,t.u_fade),u_fill_translate:new p.c3(u,t.u_fill_translate)}),fillOutline:(u,t)=>({u_world:new p.c3(u,t.u_world),u_fill_translate:new p.c3(u,t.u_fill_translate)}),fillOutlinePattern:(u,t)=>({u_world:new p.c3(u,t.u_world),u_image:new p.b_(u,t.u_image),u_texsize:new p.c3(u,t.u_texsize),u_pixel_coord_upper:new p.c3(u,t.u_pixel_coord_upper),u_pixel_coord_lower:new p.c3(u,t.u_pixel_coord_lower),u_scale:new p.c2(u,t.u_scale),u_fade:new p.bp(u,t.u_fade),u_fill_translate:new p.c3(u,t.u_fill_translate)}),circle:(u,t)=>({u_camera_to_center_distance:new p.bp(u,t.u_camera_to_center_distance),u_scale_with_map:new p.b_(u,t.u_scale_with_map),u_pitch_with_map:new p.b_(u,t.u_pitch_with_map),u_extrude_scale:new p.c3(u,t.u_extrude_scale),u_device_pixel_ratio:new p.bp(u,t.u_device_pixel_ratio),u_globe_extrude_scale:new p.bp(u,t.u_globe_extrude_scale),u_translate:new p.c3(u,t.u_translate)}),collisionBox:(u,t)=>({u_pixel_extrude_scale:new p.c3(u,t.u_pixel_extrude_scale)}),collisionCircle:(u,t)=>({u_viewport_size:new p.c3(u,t.u_viewport_size)}),debug:(u,t)=>({u_color:new p.b$(u,t.u_color),u_overlay:new p.b_(u,t.u_overlay),u_overlay_scale:new p.bp(u,t.u_overlay_scale)}),depth:Ec,clippingMask:Ec,heatmap:(u,t)=>({u_extrude_scale:new p.bp(u,t.u_extrude_scale),u_intensity:new p.bp(u,t.u_intensity),u_globe_extrude_scale:new p.bp(u,t.u_globe_extrude_scale)}),heatmapTexture:(u,t)=>({u_matrix:new p.c0(u,t.u_matrix),u_world:new p.c3(u,t.u_world),u_image:new p.b_(u,t.u_image),u_color_ramp:new p.b_(u,t.u_color_ramp),u_opacity:new p.bp(u,t.u_opacity)}),hillshade:(u,t)=>({u_image:new p.b_(u,t.u_image),u_latrange:new p.c3(u,t.u_latrange),u_exaggeration:new p.bp(u,t.u_exaggeration),u_altitudes:new p.c9(u,t.u_altitudes),u_azimuths:new p.c9(u,t.u_azimuths),u_accent:new p.b$(u,t.u_accent),u_method:new p.b_(u,t.u_method),u_shadows:new p.c8(u,t.u_shadows),u_highlights:new p.c8(u,t.u_highlights)}),hillshadePrepare:(u,t)=>({u_matrix:new p.c0(u,t.u_matrix),u_image:new p.b_(u,t.u_image),u_dimension:new p.c3(u,t.u_dimension),u_zoom:new p.bp(u,t.u_zoom),u_unpack:new p.c1(u,t.u_unpack)}),colorRelief:(u,t)=>({u_image:new p.b_(u,t.u_image),u_unpack:new p.c1(u,t.u_unpack),u_dimension:new p.c3(u,t.u_dimension),u_elevation_stops:new p.b_(u,t.u_elevation_stops),u_color_stops:new p.b_(u,t.u_color_stops),u_color_ramp_size:new p.b_(u,t.u_color_ramp_size),u_opacity:new p.bp(u,t.u_opacity)}),line:(u,t)=>({u_translation:new p.c3(u,t.u_translation),u_ratio:new p.bp(u,t.u_ratio),u_device_pixel_ratio:new p.bp(u,t.u_device_pixel_ratio),u_units_to_pixels:new p.c3(u,t.u_units_to_pixels)}),lineGradient:(u,t)=>({u_translation:new p.c3(u,t.u_translation),u_ratio:new p.bp(u,t.u_ratio),u_device_pixel_ratio:new p.bp(u,t.u_device_pixel_ratio),u_units_to_pixels:new p.c3(u,t.u_units_to_pixels),u_image:new p.b_(u,t.u_image),u_image_height:new p.bp(u,t.u_image_height)}),linePattern:(u,t)=>({u_translation:new p.c3(u,t.u_translation),u_texsize:new p.c3(u,t.u_texsize),u_ratio:new p.bp(u,t.u_ratio),u_device_pixel_ratio:new p.bp(u,t.u_device_pixel_ratio),u_image:new p.b_(u,t.u_image),u_units_to_pixels:new p.c3(u,t.u_units_to_pixels),u_scale:new p.c2(u,t.u_scale),u_fade:new p.bp(u,t.u_fade)}),lineSDF:(u,t)=>({u_translation:new p.c3(u,t.u_translation),u_ratio:new p.bp(u,t.u_ratio),u_device_pixel_ratio:new p.bp(u,t.u_device_pixel_ratio),u_units_to_pixels:new p.c3(u,t.u_units_to_pixels),u_image:new p.b_(u,t.u_image),u_mix:new p.bp(u,t.u_mix),u_tileratio:new p.bp(u,t.u_tileratio),u_crossfade_from:new p.bp(u,t.u_crossfade_from),u_crossfade_to:new p.bp(u,t.u_crossfade_to),u_lineatlas_width:new p.bp(u,t.u_lineatlas_width),u_lineatlas_height:new p.bp(u,t.u_lineatlas_height)}),lineGradientSDF:(u,t)=>({u_translation:new p.c3(u,t.u_translation),u_ratio:new p.bp(u,t.u_ratio),u_device_pixel_ratio:new p.bp(u,t.u_device_pixel_ratio),u_units_to_pixels:new p.c3(u,t.u_units_to_pixels),u_image:new p.b_(u,t.u_image),u_image_height:new p.bp(u,t.u_image_height),u_tileratio:new p.bp(u,t.u_tileratio),u_crossfade_from:new p.bp(u,t.u_crossfade_from),u_crossfade_to:new p.bp(u,t.u_crossfade_to),u_image_dash:new p.b_(u,t.u_image_dash),u_mix:new p.bp(u,t.u_mix),u_lineatlas_width:new p.bp(u,t.u_lineatlas_width),u_lineatlas_height:new p.bp(u,t.u_lineatlas_height)}),raster:(u,t)=>({u_tl_parent:new p.c3(u,t.u_tl_parent),u_scale_parent:new p.bp(u,t.u_scale_parent),u_buffer_scale:new p.bp(u,t.u_buffer_scale),u_fade_t:new p.bp(u,t.u_fade_t),u_opacity:new p.bp(u,t.u_opacity),u_image0:new p.b_(u,t.u_image0),u_image1:new p.b_(u,t.u_image1),u_brightness_low:new p.bp(u,t.u_brightness_low),u_brightness_high:new p.bp(u,t.u_brightness_high),u_saturation_factor:new p.bp(u,t.u_saturation_factor),u_contrast_factor:new p.bp(u,t.u_contrast_factor),u_spin_weights:new p.c2(u,t.u_spin_weights),u_coords_top:new p.c1(u,t.u_coords_top),u_coords_bottom:new p.c1(u,t.u_coords_bottom)}),symbolIcon:(u,t)=>({u_is_size_zoom_constant:new p.b_(u,t.u_is_size_zoom_constant),u_is_size_feature_constant:new p.b_(u,t.u_is_size_feature_constant),u_size_t:new p.bp(u,t.u_size_t),u_size:new p.bp(u,t.u_size),u_camera_to_center_distance:new p.bp(u,t.u_camera_to_center_distance),u_pitch:new p.bp(u,t.u_pitch),u_rotate_symbol:new p.b_(u,t.u_rotate_symbol),u_aspect_ratio:new p.bp(u,t.u_aspect_ratio),u_fade_change:new p.bp(u,t.u_fade_change),u_label_plane_matrix:new p.c0(u,t.u_label_plane_matrix),u_coord_matrix:new p.c0(u,t.u_coord_matrix),u_is_text:new p.b_(u,t.u_is_text),u_pitch_with_map:new p.b_(u,t.u_pitch_with_map),u_is_along_line:new p.b_(u,t.u_is_along_line),u_is_variable_anchor:new p.b_(u,t.u_is_variable_anchor),u_texsize:new p.c3(u,t.u_texsize),u_texture:new p.b_(u,t.u_texture),u_translation:new p.c3(u,t.u_translation),u_pitched_scale:new p.bp(u,t.u_pitched_scale)}),symbolSDF:(u,t)=>({u_is_size_zoom_constant:new p.b_(u,t.u_is_size_zoom_constant),u_is_size_feature_constant:new p.b_(u,t.u_is_size_feature_constant),u_size_t:new p.bp(u,t.u_size_t),u_size:new p.bp(u,t.u_size),u_camera_to_center_distance:new p.bp(u,t.u_camera_to_center_distance),u_pitch:new p.bp(u,t.u_pitch),u_rotate_symbol:new p.b_(u,t.u_rotate_symbol),u_aspect_ratio:new p.bp(u,t.u_aspect_ratio),u_fade_change:new p.bp(u,t.u_fade_change),u_label_plane_matrix:new p.c0(u,t.u_label_plane_matrix),u_coord_matrix:new p.c0(u,t.u_coord_matrix),u_is_text:new p.b_(u,t.u_is_text),u_pitch_with_map:new p.b_(u,t.u_pitch_with_map),u_is_along_line:new p.b_(u,t.u_is_along_line),u_is_variable_anchor:new p.b_(u,t.u_is_variable_anchor),u_texsize:new p.c3(u,t.u_texsize),u_texture:new p.b_(u,t.u_texture),u_gamma_scale:new p.bp(u,t.u_gamma_scale),u_device_pixel_ratio:new p.bp(u,t.u_device_pixel_ratio),u_is_halo:new p.b_(u,t.u_is_halo),u_is_plain:new p.b_(u,t.u_is_plain),u_translation:new p.c3(u,t.u_translation),u_pitched_scale:new p.bp(u,t.u_pitched_scale)}),symbolTextAndIcon:(u,t)=>({u_is_size_zoom_constant:new p.b_(u,t.u_is_size_zoom_constant),u_is_size_feature_constant:new p.b_(u,t.u_is_size_feature_constant),u_size_t:new p.bp(u,t.u_size_t),u_size:new p.bp(u,t.u_size),u_camera_to_center_distance:new p.bp(u,t.u_camera_to_center_distance),u_pitch:new p.bp(u,t.u_pitch),u_rotate_symbol:new p.b_(u,t.u_rotate_symbol),u_aspect_ratio:new p.bp(u,t.u_aspect_ratio),u_fade_change:new p.bp(u,t.u_fade_change),u_label_plane_matrix:new p.c0(u,t.u_label_plane_matrix),u_coord_matrix:new p.c0(u,t.u_coord_matrix),u_is_text:new p.b_(u,t.u_is_text),u_pitch_with_map:new p.b_(u,t.u_pitch_with_map),u_is_along_line:new p.b_(u,t.u_is_along_line),u_is_variable_anchor:new p.b_(u,t.u_is_variable_anchor),u_texsize:new p.c3(u,t.u_texsize),u_texsize_icon:new p.c3(u,t.u_texsize_icon),u_texture:new p.b_(u,t.u_texture),u_texture_icon:new p.b_(u,t.u_texture_icon),u_gamma_scale:new p.bp(u,t.u_gamma_scale),u_device_pixel_ratio:new p.bp(u,t.u_device_pixel_ratio),u_is_halo:new p.b_(u,t.u_is_halo),u_translation:new p.c3(u,t.u_translation),u_pitched_scale:new p.bp(u,t.u_pitched_scale)}),background:(u,t)=>({u_opacity:new p.bp(u,t.u_opacity),u_color:new p.b$(u,t.u_color)}),backgroundPattern:(u,t)=>({u_opacity:new p.bp(u,t.u_opacity),u_image:new p.b_(u,t.u_image),u_pattern_tl_a:new p.c3(u,t.u_pattern_tl_a),u_pattern_br_a:new p.c3(u,t.u_pattern_br_a),u_pattern_tl_b:new p.c3(u,t.u_pattern_tl_b),u_pattern_br_b:new p.c3(u,t.u_pattern_br_b),u_texsize:new p.c3(u,t.u_texsize),u_mix:new p.bp(u,t.u_mix),u_pattern_size_a:new p.c3(u,t.u_pattern_size_a),u_pattern_size_b:new p.c3(u,t.u_pattern_size_b),u_scale_a:new p.bp(u,t.u_scale_a),u_scale_b:new p.bp(u,t.u_scale_b),u_pixel_coord_upper:new p.c3(u,t.u_pixel_coord_upper),u_pixel_coord_lower:new p.c3(u,t.u_pixel_coord_lower),u_tile_units_to_pixels:new p.bp(u,t.u_tile_units_to_pixels)}),terrain:(u,t)=>({u_texture:new p.b_(u,t.u_texture),u_ele_delta:new p.bp(u,t.u_ele_delta),u_fog_matrix:new p.c0(u,t.u_fog_matrix),u_fog_color:new p.b$(u,t.u_fog_color),u_fog_ground_blend:new p.bp(u,t.u_fog_ground_blend),u_fog_ground_blend_opacity:new p.bp(u,t.u_fog_ground_blend_opacity),u_horizon_color:new p.b$(u,t.u_horizon_color),u_horizon_fog_blend:new p.bp(u,t.u_horizon_fog_blend),u_is_globe_mode:new p.bp(u,t.u_is_globe_mode)}),terrainDepth:(u,t)=>({u_ele_delta:new p.bp(u,t.u_ele_delta)}),terrainCoords:(u,t)=>({u_texture:new p.b_(u,t.u_texture),u_terrain_coords_id:new p.bp(u,t.u_terrain_coords_id),u_ele_delta:new p.bp(u,t.u_ele_delta)}),projectionErrorMeasurement:(u,t)=>({u_input:new p.bp(u,t.u_input),u_output_expected:new p.bp(u,t.u_output_expected)}),atmosphere:(u,t)=>({u_sun_pos:new p.c2(u,t.u_sun_pos),u_atmosphere_blend:new p.bp(u,t.u_atmosphere_blend),u_globe_position:new p.c2(u,t.u_globe_position),u_globe_radius:new p.bp(u,t.u_globe_radius),u_inv_proj_matrix:new p.c0(u,t.u_inv_proj_matrix)}),sky:(u,t)=>({u_sky_color:new p.b$(u,t.u_sky_color),u_horizon_color:new p.b$(u,t.u_horizon_color),u_horizon:new p.c3(u,t.u_horizon),u_horizon_normal:new p.c3(u,t.u_horizon_normal),u_sky_horizon_blend:new p.bp(u,t.u_sky_horizon_blend),u_sky_blend:new p.bp(u,t.u_sky_blend)})};class Wh{constructor(t,n,a){this.context=t;let c=t.gl;this.buffer=c.createBuffer(),this.dynamicDraw=!!a,this.context.unbindVAO(),t.bindElementBuffer.set(this.buffer),c.bufferData(c.ELEMENT_ARRAY_BUFFER,n.arrayBuffer,this.dynamicDraw?c.DYNAMIC_DRAW:c.STATIC_DRAW),this.dynamicDraw||n.freeBufferAfterUpload()}bind(){this.context.bindElementBuffer.set(this.buffer)}updateData(t){let n=this.context.gl;if(!this.dynamicDraw)throw new Error("Attempted to update data while not in dynamic mode.");this.context.unbindVAO(),this.bind(),n.bufferSubData(n.ELEMENT_ARRAY_BUFFER,0,t.arrayBuffer)}destroy(){this.buffer&&(this.context.gl.deleteBuffer(this.buffer),delete this.buffer)}}let Hh={Int8:"BYTE",Uint8:"UNSIGNED_BYTE",Int16:"SHORT",Uint16:"UNSIGNED_SHORT",Int32:"INT",Uint32:"UNSIGNED_INT",Float32:"FLOAT"};class Cc{constructor(t,n,a,c){this.length=n.length,this.attributes=a,this.itemSize=n.bytesPerElement,this.dynamicDraw=c,this.context=t;let f=t.gl;this.buffer=f.createBuffer(),t.bindVertexBuffer.set(this.buffer),f.bufferData(f.ARRAY_BUFFER,n.arrayBuffer,this.dynamicDraw?f.DYNAMIC_DRAW:f.STATIC_DRAW),this.dynamicDraw||n.freeBufferAfterUpload()}bind(){this.context.bindVertexBuffer.set(this.buffer)}updateData(t){if(t.length!==this.length)throw new Error(`Length of new data is ${t.length}, which doesn't match current length of ${this.length}`);let n=this.context.gl;this.bind(),n.bufferSubData(n.ARRAY_BUFFER,0,t.arrayBuffer)}enableAttributes(t,n){for(let a of this.attributes){let c=n.attributes[a.name];c!==void 0&&t.enableVertexAttribArray(c)}}setVertexAttribPointers(t,n,a){for(let c of this.attributes){let f=n.attributes[c.name];f!==void 0&&t.vertexAttribPointer(f,c.components,t[Hh[c.type]],!1,this.itemSize,c.offset+this.itemSize*(a||0))}}destroy(){this.buffer&&(this.context.gl.deleteBuffer(this.buffer),delete this.buffer)}}class et{constructor(t){this.gl=t.gl,this.default=this.getDefault(),this.current=this.default,this.dirty=!1}get(){return this.current}set(t){}getDefault(){return this.default}setDefault(){this.set(this.default)}}class Ac extends et{getDefault(){return p.bo.transparent}set(t){let n=this.current;(t.r!==n.r||t.g!==n.g||t.b!==n.b||t.a!==n.a||this.dirty)&&(this.gl.clearColor(t.r,t.g,t.b,t.a),this.current=t,this.dirty=!1)}}class zs extends et{getDefault(){return 1}set(t){(t!==this.current||this.dirty)&&(this.gl.clearDepth(t),this.current=t,this.dirty=!1)}}class Rs extends et{getDefault(){return 0}set(t){(t!==this.current||this.dirty)&&(this.gl.clearStencil(t),this.current=t,this.dirty=!1)}}class ks extends et{getDefault(){return[!0,!0,!0,!0]}set(t){let n=this.current;(t[0]!==n[0]||t[1]!==n[1]||t[2]!==n[2]||t[3]!==n[3]||this.dirty)&&(this.gl.colorMask(t[0],t[1],t[2],t[3]),this.current=t,this.dirty=!1)}}class ll extends et{getDefault(){return!0}set(t){(t!==this.current||this.dirty)&&(this.gl.depthMask(t),this.current=t,this.dirty=!1)}}class gn extends et{getDefault(){return 255}set(t){(t!==this.current||this.dirty)&&(this.gl.stencilMask(t),this.current=t,this.dirty=!1)}}class ko extends et{getDefault(){return{func:this.gl.ALWAYS,ref:0,mask:255}}set(t){let n=this.current;(t.func!==n.func||t.ref!==n.ref||t.mask!==n.mask||this.dirty)&&(this.gl.stencilFunc(t.func,t.ref,t.mask),this.current=t,this.dirty=!1)}}class Kn extends et{getDefault(){let t=this.gl;return[t.KEEP,t.KEEP,t.KEEP]}set(t){let n=this.current;(t[0]!==n[0]||t[1]!==n[1]||t[2]!==n[2]||this.dirty)&&(this.gl.stencilOp(t[0],t[1],t[2]),this.current=t,this.dirty=!1)}}class Vi extends et{getDefault(){return!1}set(t){if(t===this.current&&!this.dirty)return;let n=this.gl;t?n.enable(n.STENCIL_TEST):n.disable(n.STENCIL_TEST),this.current=t,this.dirty=!1}}class Dc extends et{getDefault(){return[0,1]}set(t){let n=this.current;(t[0]!==n[0]||t[1]!==n[1]||this.dirty)&&(this.gl.depthRange(t[0],t[1]),this.current=t,this.dirty=!1)}}class zc extends et{getDefault(){return!1}set(t){if(t===this.current&&!this.dirty)return;let n=this.gl;t?n.enable(n.DEPTH_TEST):n.disable(n.DEPTH_TEST),this.current=t,this.dirty=!1}}class cl extends et{getDefault(){return this.gl.LESS}set(t){(t!==this.current||this.dirty)&&(this.gl.depthFunc(t),this.current=t,this.dirty=!1)}}class _n extends et{getDefault(){return!1}set(t){if(t===this.current&&!this.dirty)return;let n=this.gl;t?n.enable(n.BLEND):n.disable(n.BLEND),this.current=t,this.dirty=!1}}class Ls extends et{getDefault(){let t=this.gl;return[t.ONE,t.ZERO]}set(t){let n=this.current;(t[0]!==n[0]||t[1]!==n[1]||this.dirty)&&(this.gl.blendFunc(t[0],t[1]),this.current=t,this.dirty=!1)}}class Fs extends et{getDefault(){return p.bo.transparent}set(t){let n=this.current;(t.r!==n.r||t.g!==n.g||t.b!==n.b||t.a!==n.a||this.dirty)&&(this.gl.blendColor(t.r,t.g,t.b,t.a),this.current=t,this.dirty=!1)}}class Lo extends et{getDefault(){return this.gl.FUNC_ADD}set(t){(t!==this.current||this.dirty)&&(this.gl.blendEquation(t),this.current=t,this.dirty=!1)}}class Bs extends et{getDefault(){return!1}set(t){if(t===this.current&&!this.dirty)return;let n=this.gl;t?n.enable(n.CULL_FACE):n.disable(n.CULL_FACE),this.current=t,this.dirty=!1}}class Rc extends et{getDefault(){return this.gl.BACK}set(t){(t!==this.current||this.dirty)&&(this.gl.cullFace(t),this.current=t,this.dirty=!1)}}class Jn extends et{getDefault(){return this.gl.CCW}set(t){(t!==this.current||this.dirty)&&(this.gl.frontFace(t),this.current=t,this.dirty=!1)}}class Qn extends et{getDefault(){return null}set(t){(t!==this.current||this.dirty)&&(this.gl.useProgram(t),this.current=t,this.dirty=!1)}}class kc extends et{getDefault(){return this.gl.TEXTURE0}set(t){(t!==this.current||this.dirty)&&(this.gl.activeTexture(t),this.current=t,this.dirty=!1)}}class hl extends et{getDefault(){let t=this.gl;return[0,0,t.drawingBufferWidth,t.drawingBufferHeight]}set(t){let n=this.current;(t[0]!==n[0]||t[1]!==n[1]||t[2]!==n[2]||t[3]!==n[3]||this.dirty)&&(this.gl.viewport(t[0],t[1],t[2],t[3]),this.current=t,this.dirty=!1)}}class Ue extends et{getDefault(){return null}set(t){if(t===this.current&&!this.dirty)return;let n=this.gl;n.bindFramebuffer(n.FRAMEBUFFER,t),this.current=t,this.dirty=!1}}class Os extends et{getDefault(){return null}set(t){if(t===this.current&&!this.dirty)return;let n=this.gl;n.bindRenderbuffer(n.RENDERBUFFER,t),this.current=t,this.dirty=!1}}class Xh extends et{getDefault(){return null}set(t){if(t===this.current&&!this.dirty)return;let n=this.gl;n.bindTexture(n.TEXTURE_2D,t),this.current=t,this.dirty=!1}}class Lc extends et{getDefault(){return null}set(t){if(t===this.current&&!this.dirty)return;let n=this.gl;n.bindBuffer(n.ARRAY_BUFFER,t),this.current=t,this.dirty=!1}}class Fo extends et{getDefault(){return null}set(t){let n=this.gl;n.bindBuffer(n.ELEMENT_ARRAY_BUFFER,t),this.current=t,this.dirty=!1}}class Yh extends et{getDefault(){return null}set(t){var n;if(t===this.current&&!this.dirty)return;let a=this.gl;Yi(a)?a.bindVertexArray(t):(n=a.getExtension("OES_vertex_array_object"))===null||n===void 0||n.bindVertexArrayOES(t),this.current=t,this.dirty=!1}}class Kh extends et{getDefault(){return 4}set(t){if(t===this.current&&!this.dirty)return;let n=this.gl;n.pixelStorei(n.UNPACK_ALIGNMENT,t),this.current=t,this.dirty=!1}}class Fc extends et{getDefault(){return!1}set(t){if(t===this.current&&!this.dirty)return;let n=this.gl;n.pixelStorei(n.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t),this.current=t,this.dirty=!1}}class Jh extends et{getDefault(){return!1}set(t){if(t===this.current&&!this.dirty)return;let n=this.gl;n.pixelStorei(n.UNPACK_FLIP_Y_WEBGL,t),this.current=t,this.dirty=!1}}class Bo extends et{constructor(t,n){super(t),this.context=t,this.parent=n}getDefault(){return null}}class Ns extends Bo{setDirty(){this.dirty=!0}set(t){if(t===this.current&&!this.dirty)return;this.context.bindFramebuffer.set(this.parent);let n=this.gl;n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,t,0),this.current=t,this.dirty=!1}}class Oo extends Bo{set(t){if(t===this.current&&!this.dirty)return;this.context.bindFramebuffer.set(this.parent);let n=this.gl;n.framebufferRenderbuffer(n.FRAMEBUFFER,n.DEPTH_ATTACHMENT,n.RENDERBUFFER,t),this.current=t,this.dirty=!1}}class Vs extends Bo{set(t){if(t===this.current&&!this.dirty)return;this.context.bindFramebuffer.set(this.parent);let n=this.gl;n.framebufferRenderbuffer(n.FRAMEBUFFER,n.DEPTH_STENCIL_ATTACHMENT,n.RENDERBUFFER,t),this.current=t,this.dirty=!1}}let js="Framebuffer is not complete";class Bc{constructor(t,n,a,c,f){this.context=t,this.width=n,this.height=a;let y=t.gl,x=this.framebuffer=y.createFramebuffer();if(this.colorAttachment=new Ns(t,x),c)this.depthAttachment=f?new Vs(t,x):new Oo(t,x);else if(f)throw new Error("Stencil cannot be set without depth");if(y.checkFramebufferStatus(y.FRAMEBUFFER)!==y.FRAMEBUFFER_COMPLETE)throw new Error(js)}destroy(){let t=this.context.gl,n=this.colorAttachment.get();if(n&&t.deleteTexture(n),this.depthAttachment){let a=this.depthAttachment.get();a&&t.deleteRenderbuffer(a)}t.deleteFramebuffer(this.framebuffer)}}class Us{constructor(t){var n,a;if(this.gl=t,this.clearColor=new Ac(this),this.clearDepth=new zs(this),this.clearStencil=new Rs(this),this.colorMask=new ks(this),this.depthMask=new ll(this),this.stencilMask=new gn(this),this.stencilFunc=new ko(this),this.stencilOp=new Kn(this),this.stencilTest=new Vi(this),this.depthRange=new Dc(this),this.depthTest=new zc(this),this.depthFunc=new cl(this),this.blend=new _n(this),this.blendFunc=new Ls(this),this.blendColor=new Fs(this),this.blendEquation=new Lo(this),this.cullFace=new Bs(this),this.cullFaceSide=new Rc(this),this.frontFace=new Jn(this),this.program=new Qn(this),this.activeTexture=new kc(this),this.viewport=new hl(this),this.bindFramebuffer=new Ue(this),this.bindRenderbuffer=new Os(this),this.bindTexture=new Xh(this),this.bindVertexBuffer=new Lc(this),this.bindElementBuffer=new Fo(this),this.bindVertexArray=new Yh(this),this.pixelStoreUnpack=new Kh(this),this.pixelStoreUnpackPremultiplyAlpha=new Fc(this),this.pixelStoreUnpackFlipY=new Jh(this),this.extTextureFilterAnisotropic=t.getExtension("EXT_texture_filter_anisotropic"),this.extTextureFilterAnisotropic&&(this.extTextureFilterAnisotropicMax=t.getParameter(this.extTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT)),this.maxTextureSize=t.getParameter(t.MAX_TEXTURE_SIZE),Yi(t)){this.HALF_FLOAT=t.HALF_FLOAT;let c=t.getExtension("EXT_color_buffer_half_float");this.RGBA16F=(n=t.RGBA16F)!==null&&n!==void 0?n:c?.RGBA16F_EXT,this.RGB16F=(a=t.RGB16F)!==null&&a!==void 0?a:c?.RGB16F_EXT,t.getExtension("EXT_color_buffer_float")}else{t.getExtension("EXT_color_buffer_half_float"),t.getExtension("OES_texture_half_float_linear");let c=t.getExtension("OES_texture_half_float");this.HALF_FLOAT=c?.HALF_FLOAT_OES}}setDefault(){this.unbindVAO(),this.clearColor.setDefault(),this.clearDepth.setDefault(),this.clearStencil.setDefault(),this.colorMask.setDefault(),this.depthMask.setDefault(),this.stencilMask.setDefault(),this.stencilFunc.setDefault(),this.stencilOp.setDefault(),this.stencilTest.setDefault(),this.depthRange.setDefault(),this.depthTest.setDefault(),this.depthFunc.setDefault(),this.blend.setDefault(),this.blendFunc.setDefault(),this.blendColor.setDefault(),this.blendEquation.setDefault(),this.cullFace.setDefault(),this.cullFaceSide.setDefault(),this.frontFace.setDefault(),this.program.setDefault(),this.activeTexture.setDefault(),this.bindFramebuffer.setDefault(),this.pixelStoreUnpack.setDefault(),this.pixelStoreUnpackPremultiplyAlpha.setDefault(),this.pixelStoreUnpackFlipY.setDefault()}setDirty(){this.clearColor.dirty=!0,this.clearDepth.dirty=!0,this.clearStencil.dirty=!0,this.colorMask.dirty=!0,this.depthMask.dirty=!0,this.stencilMask.dirty=!0,this.stencilFunc.dirty=!0,this.stencilOp.dirty=!0,this.stencilTest.dirty=!0,this.depthRange.dirty=!0,this.depthTest.dirty=!0,this.depthFunc.dirty=!0,this.blend.dirty=!0,this.blendFunc.dirty=!0,this.blendColor.dirty=!0,this.blendEquation.dirty=!0,this.cullFace.dirty=!0,this.cullFaceSide.dirty=!0,this.frontFace.dirty=!0,this.program.dirty=!0,this.activeTexture.dirty=!0,this.viewport.dirty=!0,this.bindFramebuffer.dirty=!0,this.bindRenderbuffer.dirty=!0,this.bindTexture.dirty=!0,this.bindVertexBuffer.dirty=!0,this.bindElementBuffer.dirty=!0,this.bindVertexArray.dirty=!0,this.pixelStoreUnpack.dirty=!0,this.pixelStoreUnpackPremultiplyAlpha.dirty=!0,this.pixelStoreUnpackFlipY.dirty=!0}createIndexBuffer(t,n){return new Wh(this,t,n)}createVertexBuffer(t,n,a){return new Cc(this,t,n,a)}createRenderbuffer(t,n,a){let c=this.gl,f=c.createRenderbuffer();return this.bindRenderbuffer.set(f),c.renderbufferStorage(c.RENDERBUFFER,t,n,a),this.bindRenderbuffer.set(null),f}createFramebuffer(t,n,a,c){return new Bc(this,t,n,a,c)}clear({color:t,depth:n,stencil:a}){let c=this.gl,f=0;t&&(f|=c.COLOR_BUFFER_BIT,this.clearColor.set(t),this.colorMask.set([!0,!0,!0,!0])),n!==void 0&&(f|=c.DEPTH_BUFFER_BIT,this.depthRange.set([0,1]),this.clearDepth.set(n),this.depthMask.set(!0)),a!==void 0&&(f|=c.STENCIL_BUFFER_BIT,this.clearStencil.set(a),this.stencilMask.set(255)),c.clear(f)}setCullFace(t){t.enable===!1?this.cullFace.set(!1):(this.cullFace.set(!0),this.cullFaceSide.set(t.mode),this.frontFace.set(t.frontFace))}setDepthMode(t){t.func!==this.gl.ALWAYS||t.mask?(this.depthTest.set(!0),this.depthFunc.set(t.func),this.depthMask.set(t.mask),this.depthRange.set(t.range)):this.depthTest.set(!1)}setStencilMode(t){t.test.func!==this.gl.ALWAYS||t.mask?(this.stencilTest.set(!0),this.stencilMask.set(t.mask),this.stencilOp.set([t.fail,t.depthFail,t.pass]),this.stencilFunc.set({func:t.test.func,ref:t.ref,mask:t.test.mask})):this.stencilTest.set(!1)}setColorMode(t){p.bQ(t.blendFunction,lt.Replace)?this.blend.set(!1):(this.blend.set(!0),this.blendFunc.set(t.blendFunction),this.blendColor.set(t.blendColor)),this.colorMask.set(t.mask)}createVertexArray(){var t;return Yi(this.gl)?this.gl.createVertexArray():(t=this.gl.getExtension("OES_vertex_array_object"))===null||t===void 0?void 0:t.createVertexArrayOES()}deleteVertexArray(t){var n;Yi(this.gl)?this.gl.deleteVertexArray(t):(n=this.gl.getExtension("OES_vertex_array_object"))===null||n===void 0||n.deleteVertexArrayOES(t)}unbindVAO(){this.bindVertexArray.set(null)}}let yn;function eo(u,t,n,a,c){var f,y;let x=u.context,w=u.transform,P=x.gl,S=u.useProgram("collisionBox"),E=[],C=0,z=0;for(let X of a){let Z=t.getTile(X).getBucket(n);if(!Z)continue;let U=c?Z.textCollisionBox:Z.iconCollisionBox,H=Z.collisionCircleArray;H.length>0&&(E.push({circleArray:H,circleOffset:z,coord:X}),C+=H.length/4,z=C),U&&S.draw(x,P.LINES,Ne.disabled,He.disabled,u.colorModeForRenderPass(),qe.disabled,Pc(u.transform),(f=u.style.map.terrain)===null||f===void 0?void 0:f.getTerrainData(X),w.getProjectionData({overscaledTileID:X,applyGlobeMatrix:!0,applyTerrainMatrix:!0}),n.id,U.layoutVertexBuffer,U.indexBuffer,U.segments,null,u.transform.zoom,null,null,U.collisionVertexBuffer)}if(!c||!E.length)return;let B=u.useProgram("collisionCircle"),N=new p.ca;N.resize(4*C),N._trim();let G=0;for(let X of E)for(let Z=0;Z=0&&(N[j.associatedIconIndex]={shiftedAnchor:he,angle:we})}else sn(j.numGlyphs,z)}if(w){B.clear();let G=u.icon.placedSymbolArray;for(let j=0;ju.style.map.terrain.getElevation(ve,vr,Ll):null,na=n.layout.get("text-rotation-alignment")==="map";_s(we,u,c,ri,_t,X,P,na,ve.toUnwrapped(),j.width,j.height,Ur,Pn)}let Ri=c&&oe||ar,Gi=Z||Ri?to:X?ri:u.transform.clipSpaceToPixelsMatrix,gt=Mt&&n.paint.get(c?"text-halo-width":"icon-halo-width").constantOr(1)!==0,ut;ut=Mt?we.iconsInText?sl(ot.kind,ti,U,X,Z,Ri,u,Gi,yr,Ur,di,Nr,de):ol(ot.kind,ti,U,X,Z,Ri,u,Gi,yr,Ur,c,di,gt,de):Ds(ot.kind,ti,U,X,Z,Ri,u,Gi,yr,Ur,c,di,de);let zt={program:Dt,buffers:Ee,uniformValues:ut,projectionData:ra,atlasTexture:Kt,atlasTextureIcon:Vr,atlasInterpolation:Nt,atlasInterpolationIcon:ii,isSDF:Mt,hasHalo:gt};if(H&&we.canOverlap){q=!0;let _t=Ee.segments.get();for(let Pn of _t)se.push({segments:new p.aV([Pn]),sortKey:Pn.sortKey,state:zt,terrainData:wt})}else se.push({segments:Ee.segments,sortKey:0,state:zt,terrainData:wt})}q&&se.sort(((ve,he)=>ve.sortKey-he.sortKey));let ue=(B=n.paint.get(c?"text-halo-width":"icon-halo-width").constantOr(null))!==null&&B!==void 0?B:1/0,Se=n.layout.get("text-letter-spacing").constantOr(0)*p.aJ<0||ue>1;for(let ve of se){let he=ve.state;N.activeTexture.set(G.TEXTURE0),he.atlasTexture.bind(he.atlasInterpolation,G.CLAMP_TO_EDGE),he.atlasTextureIcon&&(N.activeTexture.set(G.TEXTURE1),he.atlasTextureIcon&&he.atlasTextureIcon.bind(he.atlasInterpolationIcon,G.CLAMP_TO_EDGE));let we=he.isSDF&&he.hasHalo;if(we){let Ee=he.uniformValues;Ee.u_is_halo=1,Se&&(Ee.u_is_plain=0,Vo(he.buffers,ve.segments,n,u,he.program,Q,S,E,Ee,he.projectionData,ve.terrainData),Ee.u_is_halo=0,Ee.u_is_plain=1)}Vo(he.buffers,ve.segments,n,u,he.program,Q,S,E,he.uniformValues,he.projectionData,ve.terrainData),we&&!Se&&(he.uniformValues.u_is_halo=0)}}function Vo(u,t,n,a,c,f,y,x,w,P,S){let E=a.context;c.draw(E,E.gl.TRIANGLES,f,y,x,qe.backCCW,w,S,P,n.id,u.layoutVertexBuffer,u.indexBuffer,t,n.paint,a.transform.zoom,u.programConfigurations.get(n.id),u.dynamicLayoutVertexBuffer,u.opacityVertexBuffer)}function pl(u,t,n,a,c){let f=u.context,y=f.gl,x=He.disabled,w=new lt([y.ONE,y.ONE],p.bo.transparent,[!0,!0,!0,!0]),P=t.getBucket(n);if(!P)return;let S=a.key,E=n.heatmapFbos.get(S);E||(E=fl(f,t.tileSize,t.tileSize),n.heatmapFbos.set(S,E)),f.bindFramebuffer.set(E.framebuffer),f.viewport.set([0,0,t.tileSize,t.tileSize]),f.clear({color:p.bo.transparent});let C=P.programConfigurations.get(n.id),z=u.useProgram("heatmap",C,!c),B=u.transform.getProjectionData({overscaledTileID:t.tileID,applyGlobeMatrix:!0,applyTerrainMatrix:!0}),N=u.style.map.terrain.getTerrainData(a);z.draw(f,y.TRIANGLES,Ne.disabled,x,w,qe.disabled,tl(t,u.transform.zoom,n.paint.get("heatmap-intensity"),1),N,B,n.id,P.layoutVertexBuffer,P.indexBuffer,P.segments,n.paint,u.transform.zoom,C)}function Oc(u,t,n,a,c){let f=u.context,y=f.gl,x=u.transform;f.setColorMode(u.colorModeForRenderPass());let w=jo(f,t),P=n.key,S=t.heatmapFbos.get(P);if(!S)return;f.activeTexture.set(y.TEXTURE0),y.bindTexture(y.TEXTURE_2D,S.colorAttachment.get()),f.activeTexture.set(y.TEXTURE1),w.bind(y.LINEAR,y.CLAMP_TO_EDGE);let E=x.getProjectionData({overscaledTileID:n,applyTerrainMatrix:c,applyGlobeMatrix:!a});u.useProgram("heatmapTexture").draw(f,y.TRIANGLES,Ne.disabled,He.disabled,u.colorModeForRenderPass(),qe.disabled,Xn(u,t,0,1),null,E,t.id,u.rasterBoundsBuffer,u.quadTriangleIndexBuffer,u.rasterBoundsSegments,t.paint,x.zoom),S.destroy(),t.heatmapFbos.delete(P)}function fl(u,t,n){var a,c;let f=u.gl,y=f.createTexture();f.bindTexture(f.TEXTURE_2D,y),f.texParameteri(f.TEXTURE_2D,f.TEXTURE_WRAP_S,f.CLAMP_TO_EDGE),f.texParameteri(f.TEXTURE_2D,f.TEXTURE_WRAP_T,f.CLAMP_TO_EDGE),f.texParameteri(f.TEXTURE_2D,f.TEXTURE_MIN_FILTER,f.LINEAR),f.texParameteri(f.TEXTURE_2D,f.TEXTURE_MAG_FILTER,f.LINEAR);let x=(a=u.HALF_FLOAT)!==null&&a!==void 0?a:f.UNSIGNED_BYTE,w=(c=u.RGBA16F)!==null&&c!==void 0?c:f.RGBA;f.texImage2D(f.TEXTURE_2D,0,w,t,n,0,f.RGBA,x,null);let P=u.createFramebuffer(t,n,!1,!1);return P.colorAttachment.set(y),P}function jo(u,t){return t.colorRampTexture||(t.colorRampTexture=new p.T(u,t.colorRamp,u.gl.RGBA)),t.colorRampTexture}function Gs(u,t,n,a,c,f,y,x){let w=256;if(c.stepInterpolant){let P=t.getSource().maxzoom,S=y.canonical.z===P?Math.ceil(1<u.options.anisotropicFilterPitch&&z.texParameterf(z.TEXTURE_2D,C.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,C.extTextureFilterAnisotropicMax);let ve=(S=u.style.map.terrain)===null||S===void 0?void 0:S.getTerrainData(q),he=N.getProjectionData({overscaledTileID:q,aligned:$,applyGlobeMatrix:!P,applyTerrainMatrix:!0}),we=rl(ue,de,Se.fadeMix,n,x),Ee=G.getMeshFromTileID(C,q.canonical,f,y,"raster");B.draw(C,z.TRIANGLES,Q,c?c[q.overscaledZ]:He.disabled,j,w?qe.frontCCW:qe.backCCW,we,ve,he,n.id,Ee.vertexBuffer,Ee.indexBuffer,Ee.segments)}}function Vc(u,t,n,a){let c={parentTile:null,parentScaleBy:1,parentTopLeft:[0,0],fadeValues:{tileOpacity:1,parentTileOpacity:1,fadeMix:{opacity:1,mix:0}}};if(n===0||a)return c;if(u.fadingParentID){let f=t.getLoadedTile(u.fadingParentID);if(!f)return c;let y=Math.pow(2,f.tileID.overscaledZ-u.tileID.overscaledZ),x=[u.tileID.canonical.x*y%1,u.tileID.canonical.y*y%1],w=(function(P,S,E){let C=Xe(),z=(C-S.timeAdded)/E,B=P.fadingDirection===Ni.Incoming,N=p.al((C-P.timeAdded)/E,0,1),G=p.al(1-z,0,1),j=B?N:G;return{tileOpacity:j,parentTileOpacity:B?G:N,fadeMix:{opacity:1,mix:1-j}}})(u,f,n);return{parentTile:f,parentScaleBy:y,parentTopLeft:x,fadeValues:w}}if(u.selfFading){let f=(function(y,x){let w=(Xe()-y.timeAdded)/x,P=p.al(w,0,1);return{tileOpacity:P,fadeMix:{opacity:P,mix:0}}})(u,n);return{parentTile:null,parentScaleBy:1,parentTopLeft:[0,0],fadeValues:f}}return c}let jc=new p.bo(1,0,0,1),Uc=new p.bo(0,1,0,1),Gc=new p.bo(0,0,1,1),$c=new p.bo(1,0,1,1),Br=new p.bo(0,1,1,1);function ml(u,t,n,a){Go(u,0,t+n/2,u.transform.width,n,a)}function gl(u,t,n,a){Go(u,t-n/2,0,n,u.transform.height,a)}function Go(u,t,n,a,c,f){let y=u.context,x=y.gl;x.enable(x.SCISSOR_TEST),x.scissor(t*u.pixelRatio,n*u.pixelRatio,a*u.pixelRatio,c*u.pixelRatio),y.clear({color:f}),x.disable(x.SCISSOR_TEST)}function Zc(u,t,n){var a;let c=u.context,f=c.gl,y=u.useProgram("debug"),x=Ne.disabled,w=He.disabled,P=u.colorModeForRenderPass(),S="$debug",E=(a=u.style.map.terrain)===null||a===void 0?void 0:a.getTerrainData(n);c.activeTexture.set(f.TEXTURE0);let C=t.getTileByID(n.key).latestRawTileData,z=Math.floor((C?.byteLength||0)/1024),B=t.getTile(n).tileSize,N=512/Math.min(B,512)*(n.overscaledZ/u.transform.zoom)*.5,G=n.canonical.toString();n.overscaledZ!==n.canonical.z&&(G+=` => ${n.overscaledZ}`),(function($,X){$.initDebugOverlayCanvas();let Z=$.debugOverlayCanvas,U=$.context.gl,H=$.debugOverlayCanvas.getContext("2d");H.clearRect(0,0,Z.width,Z.height),H.shadowColor="white",H.shadowBlur=2,H.lineWidth=1.5,H.strokeStyle="white",H.textBaseline="top",H.font="bold 36px Open Sans, sans-serif",H.fillText(X,5,5),H.strokeText(X,5,5),$.debugOverlayTexture.update(Z),$.debugOverlayTexture.bind(U.LINEAR,U.CLAMP_TO_EDGE)})(u,`${G} ${z}kB`);let j=u.transform.getProjectionData({overscaledTileID:n,applyGlobeMatrix:!0,applyTerrainMatrix:!0});y.draw(c,f.TRIANGLES,x,w,lt.alphaBlended,qe.disabled,el(p.bo.transparent,N),null,j,S,u.debugBuffer,u.quadTriangleIndexBuffer,u.debugSegments),y.draw(c,f.LINE_STRIP,x,w,P,qe.disabled,el(p.bo.red),E,j,S,u.debugBuffer,u.tileBorderIndexBuffer,u.debugSegments)}function _l(u,t,n,a){let{isRenderingGlobe:c}=a,f=u.context,y=f.gl,x=u.transform,w=u.colorModeForRenderPass(),P=u.getDepthModeFor3D(),S=u.useProgram("terrain");f.bindFramebuffer.set(null),f.viewport.set([0,0,u.width,u.height]);for(let E of n){let C=t.getTerrainMesh(E.tileID),z=u.renderToTexture.getTexture(E),B=t.getTerrainData(E.tileID);f.activeTexture.set(y.TEXTURE0),y.bindTexture(y.TEXTURE_2D,z.texture);let N=t.getMeshFrameDelta(x.zoom),G=x.calculateFogMatrix(E.tileID.toUnwrapped()),j=Es(N,G,u.style.sky,x.pitch,c),$=x.getProjectionData({overscaledTileID:E.tileID,applyTerrainMatrix:!1,applyGlobeMatrix:!0});S.draw(f,y.TRIANGLES,P,He.disabled,w,qe.backCCW,j,B,$,"terrain",C.vertexBuffer,C.indexBuffer,C.segments)}}function yl(u,t){if(!t.mesh){let n=new p.aU;n.emplaceBack(-1,-1),n.emplaceBack(1,-1),n.emplaceBack(1,1),n.emplaceBack(-1,1);let a=new p.aW;a.emplaceBack(0,1,2),a.emplaceBack(0,2,3),t.mesh=new at(u.createVertexBuffer(n,kr.members),u.createIndexBuffer(a),p.aV.simpleSegment(0,0,n.length,a.length))}return t.mesh}let qc={symbol:function(u,t,n,a,c,f){if(u.renderPass!=="translucent")return;let{isRenderingToTexture:y}=f,x=He.disabled,w=u.colorModeForRenderPass();(n._unevaluatedLayout.hasValue("text-variable-anchor")||n._unevaluatedLayout.hasValue("text-variable-anchor-offset"))&&(function(P,S,E,C,z,B,N,G,j){var $;let X=S.transform,Z=S.style.map.terrain,U=z==="map",H=B==="map";for(let q of P){let Q=C.getTile(q),oe=Q.getBucket(E);if(!(!(($=oe?.text)===null||$===void 0)&&$.segments.get().length))continue;let se=p.aw(oe.textSizeData,X.zoom),de=p.aK(Q,1,S.transform.zoom),ue=Ei(U,S.transform,de),Se=E.layout.get("icon-text-fit")!=="none"&&oe.hasIconData();if(se){let ve=Math.pow(2,X.zoom-Q.tileID.overscaledZ),he=Z?(we,Ee)=>Z.getElevation(q,we,Ee):null;No(oe,U,H,j,X,ue,ve,se,Se,p.aL(X,Q,N,G),q.toUnwrapped(),he)}}})(a,u,n,t,n.layout.get("text-rotation-alignment"),n.layout.get("text-pitch-alignment"),n.paint.get("text-translate"),n.paint.get("text-translate-anchor"),c),n.paint.get("icon-opacity").constantOr(1)!==0&&dl(u,t,n,a,!1,n.paint.get("icon-translate"),n.paint.get("icon-translate-anchor"),n.layout.get("icon-rotation-alignment"),n.layout.get("icon-pitch-alignment"),n.layout.get("icon-keep-upright"),x,w,y),n.paint.get("text-opacity").constantOr(1)!==0&&dl(u,t,n,a,!0,n.paint.get("text-translate"),n.paint.get("text-translate-anchor"),n.layout.get("text-rotation-alignment"),n.layout.get("text-pitch-alignment"),n.layout.get("text-keep-upright"),x,w,y),t.map.showCollisionBoxes&&(eo(u,t,n,a,!0),eo(u,t,n,a,!1))},circle:function(u,t,n,a,c){var f;if(u.renderPass!=="translucent")return;let{isRenderingToTexture:y}=c,x=n.paint.get("circle-opacity"),w=n.paint.get("circle-stroke-width"),P=n.paint.get("circle-stroke-opacity"),S=!n.layout.get("circle-sort-key").isConstant();if(x.constantOr(1)===0&&(w.constantOr(1)===0||P.constantOr(1)===0))return;let E=u.context,C=E.gl,z=u.transform,B=u.getDepthModeForSublayer(0,Ne.ReadOnly),N=He.disabled,G=u.colorModeForRenderPass(),j=[],$=z.getCircleRadiusCorrection();for(let X of a){let Z=t.getTile(X),U=Z.getBucket(n);if(!U)continue;let H=n.paint.get("circle-translate"),q=n.paint.get("circle-translate-anchor"),Q=p.aL(z,Z,H,q),oe=U.programConfigurations.get(n.id),se=u.useProgram("circle",oe),de=U.layoutVertexBuffer,ue=U.indexBuffer,Se=(f=u.style.map.terrain)===null||f===void 0?void 0:f.getTerrainData(X),ve={programConfiguration:oe,program:se,layoutVertexBuffer:de,indexBuffer:ue,uniformValues:Tc(u,Z,n,Q,$),terrainData:Se,projectionData:z.getProjectionData({overscaledTileID:X,applyGlobeMatrix:!y,applyTerrainMatrix:!0})};if(S){let he=U.segments.get();for(let we of he)j.push({segments:new p.aV([we]),sortKey:we.sortKey,state:ve})}else j.push({segments:U.segments,sortKey:0,state:ve})}S&&j.sort(((X,Z)=>X.sortKey-Z.sortKey));for(let X of j){let{programConfiguration:Z,program:U,layoutVertexBuffer:H,indexBuffer:q,uniformValues:Q,terrainData:oe,projectionData:se}=X.state;U.draw(E,C.TRIANGLES,B,N,G,qe.backCCW,Q,oe,se,n.id,H,q,X.segments,n.paint,u.transform.zoom,Z)}},heatmap:function(u,t,n,a,c){if(n.paint.get("heatmap-opacity")===0)return;let f=u.context,{isRenderingToTexture:y,isRenderingGlobe:x}=c;if(u.style.map.terrain){for(let w of a){let P=t.getTile(w);t.hasRenderableParent(w)||(u.renderPass==="offscreen"?pl(u,P,n,w,x):u.renderPass==="translucent"&&Oc(u,n,w,y,x))}f.viewport.set([0,0,u.width,u.height])}else u.renderPass==="offscreen"?(function(w,P,S,E){let C=w.context,z=C.gl,B=w.transform,N=He.disabled,G=new lt([z.ONE,z.ONE],p.bo.transparent,[!0,!0,!0,!0]);(function(j,$,X){let Z=j.gl;j.activeTexture.set(Z.TEXTURE1),j.viewport.set([0,0,$.width/4,$.height/4]);let U=X.heatmapFbos.get(p.cd);U?(Z.bindTexture(Z.TEXTURE_2D,U.colorAttachment.get()),j.bindFramebuffer.set(U.framebuffer)):(U=fl(j,$.width/4,$.height/4),X.heatmapFbos.set(p.cd,U))})(C,w,S),C.clear({color:p.bo.transparent});for(let j of E){if(P.hasRenderableParent(j))continue;let $=P.getTile(j),X=$.getBucket(S);if(!X)continue;let Z=X.programConfigurations.get(S.id),U=w.useProgram("heatmap",Z),H=B.getProjectionData({overscaledTileID:j,applyGlobeMatrix:!0,applyTerrainMatrix:!1}),q=B.getCircleRadiusCorrection();U.draw(C,z.TRIANGLES,Ne.disabled,N,G,qe.backCCW,tl($,B.zoom,S.paint.get("heatmap-intensity"),q),null,H,S.id,X.layoutVertexBuffer,X.indexBuffer,X.segments,S.paint,B.zoom,Z)}C.viewport.set([0,0,w.width,w.height])})(u,t,n,a):u.renderPass==="translucent"&&(function(w,P){let S=w.context,E=S.gl;S.setColorMode(w.colorModeForRenderPass());let C=P.heatmapFbos.get(p.cd);C&&(S.activeTexture.set(E.TEXTURE0),E.bindTexture(E.TEXTURE_2D,C.colorAttachment.get()),S.activeTexture.set(E.TEXTURE1),jo(S,P).bind(E.LINEAR,E.CLAMP_TO_EDGE),w.useProgram("heatmapTexture").draw(S,E.TRIANGLES,Ne.disabled,He.disabled,w.colorModeForRenderPass(),qe.disabled,Xn(w,P,0,1),null,null,P.id,w.viewportBuffer,w.quadTriangleIndexBuffer,w.viewportSegments,P.paint,w.transform.zoom))})(u,n)},line:function(u,t,n,a,c){var f;if(u.renderPass!=="translucent")return;let{isRenderingToTexture:y}=c,x=n.paint.get("line-opacity"),w=n.paint.get("line-width");if(x.constantOr(1)===0||w.constantOr(1)===0)return;let P=u.getDepthModeForSublayer(0,Ne.ReadOnly),S=u.colorModeForRenderPass(),E=n.paint.get("line-dasharray"),C=E.constantOr(1),z=n.paint.get("line-pattern"),B=z.constantOr(1),N=n.paint.get("line-gradient"),G=n.getCrossfadeParameters(),j;j=B?"linePattern":C&&N?"lineGradientSDF":C?"lineSDF":N?"lineGradient":"line";let $=u.context,X=$.gl,Z=u.transform,U=!0;for(let H of a){let q=t.getTile(H);if(B&&!q.patternsLoaded())continue;let Q=q.getBucket(n);if(!Q)continue;let oe=Q.programConfigurations.get(n.id),se=u.context.program.get(),de=u.useProgram(j,oe),ue=U||de.program!==se,Se=(f=u.style.map.terrain)===null||f===void 0?void 0:f.getTerrainData(H),ve=z.constantOr(null),he=E?.constantOr(null);if(ve&&q.imageAtlas){let ot=q.imageAtlas,Ct=ot.patternPositions[ve.to.toString()],Dt=ot.patternPositions[ve.from.toString()];Ct&&Dt&&oe.setConstantPatternPositions(Ct,Dt)}else if(he){let ot=n.layout.get("line-cap").constantOr(null)==="round",Ct=u.lineAtlas.getDash(he.to,ot),Dt=u.lineAtlas.getDash(he.from,ot);oe.setConstantDashPositions(Ct,Dt)}let we=Z.getProjectionData({overscaledTileID:H,applyGlobeMatrix:!y,applyTerrainMatrix:!0}),Ee=Z.getPixelScale(),tt;B?(tt=Ic(u,q,n,Ee,G),tu($,X,q,oe,G)):C&&N?(tt=Mc(u,q,n,Ee,G,Q.lineClipsArray.length),vn(u,t,$,X,n,Q,H,oe,G)):C?(tt=il(u,q,n,Ee,G),Nc(u,$,X,oe,ue,G)):N?(tt=Sc(u,q,n,Ee,Q.lineClipsArray.length),It(u,t,$,X,n,Q,H)):tt=Ro(u,q,n,Ee);let Mt=u.stencilModeForClipping(H);de.draw($,X.TRIANGLES,P,Mt,S,qe.disabled,tt,Se,we,n.id,Q.layoutVertexBuffer,Q.indexBuffer,Q.segments,n.paint,u.transform.zoom,oe,Q.layoutVertexBuffer2),U=!1}},fill:function(u,t,n,a,c){let f=n.paint.get("fill-color"),y=n.paint.get("fill-opacity");if(y.constantOr(1)===0)return;let{isRenderingToTexture:x}=c,w=u.colorModeForRenderPass(),P=n.paint.get("fill-pattern"),S=u.opaquePassEnabledForLayer()&&!P.constantOr(1)&&f.constantOr(p.bo.transparent).a===1&&y.constantOr(0)===1?"opaque":"translucent";if(u.renderPass===S){let E=u.getDepthModeForSublayer(1,u.renderPass==="opaque"?Ne.ReadWrite:Ne.ReadOnly);$s(u,t,n,a,E,w,!1,x)}if(u.renderPass==="translucent"&&n.paint.get("fill-antialias")){let E=u.getDepthModeForSublayer(n.getPaintProperty("fill-outline-color")?2:0,Ne.ReadOnly);$s(u,t,n,a,E,w,!0,x)}},fillExtrusion:function(u,t,n,a,c){let f=n.paint.get("fill-extrusion-opacity");if(f===0)return;let{isRenderingToTexture:y}=c;if(u.renderPass==="translucent"){let x=new Ne(u.context.gl.LEQUAL,Ne.ReadWrite,u.depthRangeFor3D);if(f!==1||n.paint.get("fill-extrusion-pattern").constantOr(1))io(u,t,n,a,x,He.disabled,lt.disabled,y),io(u,t,n,a,x,u.stencilModeFor3D(),u.colorModeForRenderPass(),y);else{let w=u.colorModeForRenderPass();io(u,t,n,a,x,He.disabled,w,y)}}},hillshade:function(u,t,n,a,c){if(u.renderPass!=="offscreen"&&u.renderPass!=="translucent")return;let{isRenderingToTexture:f}=c,y=u.context,x=u.style.projection.useSubdivision,w=u.getDepthModeForSublayer(0,Ne.ReadOnly),P=u.colorModeForRenderPass();if(u.renderPass==="offscreen")(function(S,E,C,z,B,N,G){let j=S.context,$=j.gl,X=z.paint.get("resampling")==="nearest"?$.NEAREST:$.LINEAR;for(let Z of C){let U=E.getTile(Z),H=U.dem;if(!H?.data||!U.needsHillshadePrepare)continue;let q=H.dim,Q=H.stride,oe=H.getPixels();if(j.activeTexture.set($.TEXTURE1),j.pixelStoreUnpackPremultiplyAlpha.set(!1),U.demTexture||(U.demTexture=S.getTileTexture(Q)),U.demTexture){let de=U.demTexture;de.update(oe,{premultiply:!1}),de.bind($.NEAREST,$.CLAMP_TO_EDGE)}else U.demTexture=new p.T(j,oe,$.RGBA,{premultiply:!1}),U.demTexture.bind($.NEAREST,$.CLAMP_TO_EDGE);j.activeTexture.set($.TEXTURE0);let se=U.fbo;if(!se){let de=new p.T(j,{width:q,height:q,data:null},$.RGBA);de.bind(X,$.CLAMP_TO_EDGE),se=U.fbo=j.createFramebuffer(q,q,!0,!1),se.colorAttachment.set(de.texture)}j.bindFramebuffer.set(se.framebuffer),j.viewport.set([0,0,q,q]),S.useProgram("hillshadePrepare").draw(j,$.TRIANGLES,B,N,G,qe.disabled,As(U.tileID,H),null,null,z.id,S.rasterBoundsBuffer,S.quadTriangleIndexBuffer,S.rasterBoundsSegments),U.needsHillshadePrepare=!1}})(u,t,a,n,w,He.disabled,P),y.viewport.set([0,0,u.width,u.height]);else if(u.renderPass==="translucent")if(x){let[S,E,C]=u.stencilConfigForOverlapTwoPass(a);Zs(u,t,n,C,S,w,P,!1,f),Zs(u,t,n,C,E,w,P,!0,f)}else{let[S,E]=u.getStencilConfigForOverlapAndUpdateStencilID(a);Zs(u,t,n,E,S,w,P,!1,f)}},colorRelief:function(u,t,n,a,c){if(u.renderPass!=="translucent"||!a.length)return;let{isRenderingToTexture:f}=c,y=u.style.projection.useSubdivision,x=u.getDepthModeForSublayer(0,Ne.ReadOnly),w=u.colorModeForRenderPass();if(y){let[P,S,E]=u.stencilConfigForOverlapTwoPass(a);Uo(u,t,n,E,P,x,w,!1,f),Uo(u,t,n,E,S,x,w,!0,f)}else{let[P,S]=u.getStencilConfigForOverlapAndUpdateStencilID(a);Uo(u,t,n,S,P,x,w,!1,f)}},raster:function(u,t,n,a,c){if(u.renderPass!=="translucent"||n.paint.get("raster-opacity")===0||!a.length)return;let{isRenderingToTexture:f}=c,y=t.getSource(),x=u.style.projection.useSubdivision;if(y instanceof Ar)ro(u,t,n,a,null,!1,!1,y.tileCoords,y.flippedWindingOrder,f);else if(x){let[w,P,S]=u.stencilConfigForOverlapTwoPass(a);ro(u,t,n,S,w,!1,!0,xn,!1,f),ro(u,t,n,S,P,!0,!0,xn,!1,f)}else{let[w,P]=u.getStencilConfigForOverlapAndUpdateStencilID(a);ro(u,t,n,P,w,!1,!0,xn,!1,f)}},background:function(u,t,n,a,c){var f;let y=n.paint.get("background-color"),x=n.paint.get("background-opacity");if(x===0)return;let{isRenderingToTexture:w}=c,P=u.context,S=P.gl,E=u.style.projection,C=u.transform,z=C.tileSize,B=n.paint.get("background-pattern");if(u.isPatternMissing(B))return;let N=!B&&y.a===1&&x===1&&u.opaquePassEnabledForLayer()?"opaque":"translucent";if(u.renderPass!==N)return;let G=He.disabled,j=u.getDepthModeForSublayer(0,N==="opaque"?Ne.ReadWrite:Ne.ReadOnly),$=u.colorModeForRenderPass(),X=u.useProgram(B?"backgroundPattern":"background"),Z=a||rn(C,{tileSize:z,terrain:u.style.map.terrain});B&&(P.activeTexture.set(S.TEXTURE0),u.imageManager.bind(u.context));let U=n.getCrossfadeParameters();for(let H of Z){let q=C.getProjectionData({overscaledTileID:H,applyGlobeMatrix:!w,applyTerrainMatrix:!0}),Q=B?al(x,u,B,{tileID:H,tileSize:z},U):mn(x,y),oe=(f=u.style.map.terrain)===null||f===void 0?void 0:f.getTerrainData(H),se=E.getMeshFromTileID(P,H.canonical,!1,!0,"raster");X.draw(P,S.TRIANGLES,j,G,$,qe.backCCW,Q,oe,q,n.id,se.vertexBuffer,se.indexBuffer,se.segments)}},sky:function(u,t){let n=u.context,a=n.gl,c=((S,E,C)=>{let z=Math.cos(E.rollInRadians),B=Math.sin(E.rollInRadians),N=tn(E),G=E.getProjectionData({overscaledTileID:null,applyGlobeMatrix:!0,applyTerrainMatrix:!0}).projectionTransition;return{u_sky_color:S.properties.get("sky-color"),u_horizon_color:S.properties.get("horizon-color"),u_horizon:[(E.width/2-N*B)*C,(E.height/2+N*z)*C],u_horizon_normal:[-B,z],u_sky_horizon_blend:S.properties.get("sky-horizon-blend")*E.height/2*C,u_sky_blend:G}})(t,u.style.map.transform,u.pixelRatio),f=new Ne(a.LEQUAL,Ne.ReadWrite,[0,1]),y=He.disabled,x=u.colorModeForRenderPass(),w=u.useProgram("sky"),P=yl(n,t);w.draw(n,a.TRIANGLES,f,y,x,qe.disabled,c,null,void 0,"sky",P.vertexBuffer,P.indexBuffer,P.segments)},atmosphere:function(u,t,n){let a=u.context,c=a.gl,f=u.useProgram("atmosphere"),y=new Ne(c.LEQUAL,Ne.ReadOnly,[0,1]),x=u.transform,w=(function(G,j){let $=G.properties.get("position"),X=[-$.x,-$.y,-$.z],Z=p.ap(new Float64Array(16));return G.properties.get("anchor")==="map"&&(p.be(Z,Z,j.rollInRadians),p.bf(Z,Z,-j.pitchInRadians),p.be(Z,Z,j.bearingInRadians),p.bf(Z,Z,j.center.lat*Math.PI/180),p.bI(Z,Z,-j.center.lng*Math.PI/180)),p.cg(X,X,Z),X})(n,u.transform),P=x.getProjectionData({overscaledTileID:null,applyGlobeMatrix:!0,applyTerrainMatrix:!0}),S=t.properties.get("atmosphere-blend")*P.projectionTransition;if(S===0)return;let E=Ai(x.worldSize,x.center.lat),C=x.inverseProjectionMatrix,z=new Float64Array(4);z[3]=1,p.aE(z,z,x.modelViewProjectionMatrix),z[0]/=z[3],z[1]/=z[3],z[2]/=z[3],z[3]=1,p.aE(z,z,C),z[0]/=z[3],z[1]/=z[3],z[2]/=z[3],z[3]=1;let B=((G,j,$,X,Z)=>({u_sun_pos:G,u_atmosphere_blend:j,u_globe_position:$,u_globe_radius:X,u_inv_proj_matrix:Z}))(w,S,[z[0],z[1],z[2]],E,C),N=yl(a,t);f.draw(a,c.TRIANGLES,y,He.disabled,lt.alphaBlended,qe.disabled,B,null,null,"atmosphere",N.vertexBuffer,N.indexBuffer,N.segments)},custom:function(u,t,n,a){let{isRenderingGlobe:c}=a,f=u.context,y=n.implementation,x=u.style.projection,w=u.transform,P=w.getProjectionDataForCustomLayer(c),S={farZ:w.farZ,nearZ:w.nearZ,fov:w.fov*Math.PI/180,modelViewProjectionMatrix:w.modelViewProjectionMatrix,projectionMatrix:w.projectionMatrix,shaderData:{variantName:x.shaderVariantName,vertexShaderPrelude:`const float PI = 3.141592653589793; uniform mat4 u_projection_matrix; -${x.shaderPreludeCode.vertexSource}`,define:x.shaderDefine},defaultProjectionData:P},E=y.renderingMode?y.renderingMode:"2d";if(u.renderPass==="offscreen"){let C=y.prerender;C&&(u.setCustomLayerDefaults(),f.setColorMode(u.colorModeForRenderPass()),C.call(y,f.gl,S),f.setDirty(),u.setBaseState())}else if(u.renderPass==="translucent"){u.setCustomLayerDefaults(),f.setColorMode(u.colorModeForRenderPass()),f.setStencilMode(He.disabled);let C=E==="3d"?u.getDepthModeFor3D():u.getDepthModeForSublayer(0,Ne.ReadOnly);f.setDepthMode(C),y.render(f.gl,S),f.setDirty(),u.setBaseState(),f.bindFramebuffer.set(null)}},debug:function(u,t,n){for(let a of n)Zc(u,t,a)},debugPadding:function(u){let t=u.transform.padding;ml(u,u.transform.height-(t.top||0),3,jc),ml(u,t.bottom||0,3,Uc),gl(u,t.left||0,3,Gc),gl(u,u.transform.width-(t.right||0),3,$c);let n=u.transform.centerPoint;(function(a,c,f,y){Go(a,c-1,f-10,2,20,y),Go(a,c-10,f-1,20,2,y)})(u,n.x,u.transform.height-n.y,Br)},terrainDepth:function(u,t){let n=u.context,a=n.gl,c=u.transform,f=lt.unblended,y=new Ne(a.LEQUAL,Ne.ReadWrite,[0,1]),x=t.tileManager.getRenderableTiles(),w=u.useProgram("terrainDepth");n.bindFramebuffer.set(t.getFramebuffer("depth").framebuffer),n.viewport.set([0,0,u.width/devicePixelRatio,u.height/devicePixelRatio]),n.clear({color:p.bo.transparent,depth:1});for(let P of x){let S=t.getTerrainMesh(P.tileID),E=t.getTerrainData(P.tileID),C=c.getProjectionData({overscaledTileID:P.tileID,applyTerrainMatrix:!1,applyGlobeMatrix:!0}),z={u_ele_delta:t.getMeshFrameDelta(c.zoom)};w.draw(n,a.TRIANGLES,y,He.disabled,f,qe.backCCW,z,E,C,"terrain",S.vertexBuffer,S.indexBuffer,S.segments)}n.bindFramebuffer.set(null),n.viewport.set([0,0,u.width,u.height])},terrainCoords:function(u,t){let n=u.context,a=n.gl,c=u.transform,f=lt.unblended,y=new Ne(a.LEQUAL,Ne.ReadWrite,[0,1]),x=t.getCoordsTexture(),w=t.tileManager.getRenderableTiles(),P=u.useProgram("terrainCoords");n.bindFramebuffer.set(t.getFramebuffer("coords").framebuffer),n.viewport.set([0,0,u.width/devicePixelRatio,u.height/devicePixelRatio]),n.clear({color:p.bo.transparent,depth:1}),t.coordsIndex=[];for(let S of w){let E=t.getTerrainMesh(S.tileID),C=t.getTerrainData(S.tileID);n.activeTexture.set(a.TEXTURE0),a.bindTexture(a.TEXTURE_2D,x.texture);let z={u_terrain_coords_id:(255-t.coordsIndex.length)/255,u_texture:0,u_ele_delta:t.getMeshFrameDelta(c.zoom)},B=c.getProjectionData({overscaledTileID:S.tileID,applyTerrainMatrix:!1,applyGlobeMatrix:!0});P.draw(n,a.TRIANGLES,y,He.disabled,f,qe.backCCW,z,C,B,"terrain",E.vertexBuffer,E.indexBuffer,E.segments),t.coordsIndex.push(S.tileID.key)}n.bindFramebuffer.set(null),n.viewport.set([0,0,u.width,u.height])}};class $o{constructor(t,n){this.drawFunctions=qc,this.context=new Us(t),this.transform=n,this._tileTextures={},this.terrainFacilitator={depthDirty:!0,coordsDirty:!1,matrix:p.ap(new Float64Array(16)),renderTime:0},this.setup(),this.numSublayers=Xt.maxOverzooming+Xt.maxUnderzooming+1,this.depthEpsilon=1/Math.pow(2,16),this.crossTileSymbolIndex=new xi}resize(t,n,a){if(this.width=Math.floor(t*a),this.height=Math.floor(n*a),this.pixelRatio=a,this.context.viewport.set([0,0,this.width,this.height]),this.style)for(let c of this.style._order)this.style._layers[c].resize()}setup(){let t=this.context,n=new p.aU;n.emplaceBack(0,0),n.emplaceBack(p.a6,0),n.emplaceBack(0,p.a6),n.emplaceBack(p.a6,p.a6),this.tileExtentBuffer=t.createVertexBuffer(n,kr.members),this.tileExtentSegments=p.aV.simpleSegment(0,0,4,2);let a=new p.aU;a.emplaceBack(0,0),a.emplaceBack(p.a6,0),a.emplaceBack(0,p.a6),a.emplaceBack(p.a6,p.a6),this.debugBuffer=t.createVertexBuffer(a,kr.members),this.debugSegments=p.aV.simpleSegment(0,0,4,5);let c=new p.ch;c.emplaceBack(0,0,0,0),c.emplaceBack(p.a6,0,p.a6,0),c.emplaceBack(0,p.a6,0,p.a6),c.emplaceBack(p.a6,p.a6,p.a6,p.a6),this.rasterBoundsBuffer=t.createVertexBuffer(c,zo.members),this.rasterBoundsSegments=p.aV.simpleSegment(0,0,4,2);let f=new p.aU;f.emplaceBack(0,0),f.emplaceBack(p.a6,0),f.emplaceBack(0,p.a6),f.emplaceBack(p.a6,p.a6),this.rasterBoundsBufferPosOnly=t.createVertexBuffer(f,kr.members),this.rasterBoundsSegmentsPosOnly=p.aV.simpleSegment(0,0,4,5);let y=new p.aU;y.emplaceBack(0,0),y.emplaceBack(1,0),y.emplaceBack(0,1),y.emplaceBack(1,1),this.viewportBuffer=t.createVertexBuffer(y,kr.members),this.viewportSegments=p.aV.simpleSegment(0,0,4,2);let x=new p.ci;x.emplaceBack(0),x.emplaceBack(1),x.emplaceBack(3),x.emplaceBack(2),x.emplaceBack(0),this.tileBorderIndexBuffer=t.createIndexBuffer(x);let w=new p.aW;w.emplaceBack(1,0,2),w.emplaceBack(1,2,3),this.quadTriangleIndexBuffer=t.createIndexBuffer(w);let P=this.context.gl;this.stencilClearMode=new He({func:P.ALWAYS,mask:0},0,255,P.ZERO,P.ZERO,P.ZERO),this.tileExtentMesh=new at(this.tileExtentBuffer,this.quadTriangleIndexBuffer,this.tileExtentSegments)}clearStencil(){let t=this.context,n=t.gl;this.nextStencilID=1,this.currentStencilSource=void 0;let a=p.O();p.c7(a,0,this.width,this.height,0,0,1),p.S(a,a,[n.drawingBufferWidth,n.drawingBufferHeight,0]);let c={mainMatrix:a,tileMercatorCoords:[0,0,1,1],clippingPlane:[0,0,0,0],projectionTransition:0,fallbackMatrix:a};this.useProgram("clippingMask",null,!0).draw(t,n.TRIANGLES,Ne.disabled,this.stencilClearMode,lt.disabled,qe.disabled,null,null,c,"$clipping",this.viewportBuffer,this.quadTriangleIndexBuffer,this.viewportSegments)}_renderTileClippingMasks(t,n,a){if(this.currentStencilSource===t.source||!t.isTileClipped()||!n?.length)return;this.currentStencilSource=t.source,this.nextStencilID+n.length>256&&this.clearStencil();let c=this.context;c.setColorMode(lt.disabled),c.setDepthMode(Ne.disabled);let f={};for(let y of n)f[y.key]=this.nextStencilID++;this._renderTileMasks(f,n,a,!0),this._renderTileMasks(f,n,a,!1),this._tileClippingMaskIDs=f}_renderTileMasks(t,n,a,c){var f;let y=this.context,x=y.gl,w=this.style.projection,P=this.transform,S=this.useProgram("clippingMask");for(let E of n){let C=t[E.key],z=(f=this.style.map.terrain)===null||f===void 0?void 0:f.getTerrainData(E),B=w.getMeshFromTileID(this.context,E.canonical,c,!0,"stencil"),N=P.getProjectionData({overscaledTileID:E,applyGlobeMatrix:!a,applyTerrainMatrix:!0});S.draw(y,x.TRIANGLES,Ne.disabled,new He({func:x.ALWAYS,mask:0},C,255,x.KEEP,x.KEEP,x.REPLACE),lt.disabled,a?qe.disabled:qe.backCCW,null,z,N,"$clipping",B.vertexBuffer,B.indexBuffer,B.segments)}}_renderTilesDepthBuffer(){var t;let n=this.context,a=n.gl,c=this.style.projection,f=this.transform,y=this.useProgram("depth"),x=this.getDepthModeFor3D(),w=rn(f,{tileSize:f.tileSize});for(let P of w){let S=(t=this.style.map.terrain)===null||t===void 0?void 0:t.getTerrainData(P),E=c.getMeshFromTileID(this.context,P.canonical,!0,!0,"raster"),C=f.getProjectionData({overscaledTileID:P,applyGlobeMatrix:!0,applyTerrainMatrix:!0});y.draw(n,a.TRIANGLES,x,He.disabled,lt.disabled,qe.backCCW,null,S,C,"$clipping",E.vertexBuffer,E.indexBuffer,E.segments)}}stencilModeFor3D(){this.currentStencilSource=void 0,this.nextStencilID+1>256&&this.clearStencil();let t=this.nextStencilID++,n=this.context.gl;return new He({func:n.NOTEQUAL,mask:255},t,255,n.KEEP,n.KEEP,n.REPLACE)}stencilModeForClipping(t){let n=this.context.gl;return new He({func:n.EQUAL,mask:255},this._tileClippingMaskIDs[t.key],0,n.KEEP,n.KEEP,n.REPLACE)}getStencilConfigForOverlapAndUpdateStencilID(t){let n=this.context.gl,a=t.sort(((y,x)=>x.overscaledZ-y.overscaledZ)),c=a[a.length-1].overscaledZ,f=a[0].overscaledZ-c+1;if(f>1){this.currentStencilSource=void 0,this.nextStencilID+f>256&&this.clearStencil();let y={};for(let x=0;xx.overscaledZ-y.overscaledZ)),c=a[a.length-1].overscaledZ,f=a[0].overscaledZ-c+1;if(this.clearStencil(),f>1){let y={},x={};for(let w=0;w0};for(let z in x){let B=x[z];B.used&&B.prepare(this.context),w[z]=B.getVisibleCoordinates(!1),P[z]=w[z].slice().reverse(),S[z]=B.getVisibleCoordinates(!0).reverse()}this.opaquePassCutoff=1/0;for(let z=0;zthis.useProgram(z)}),this.context.viewport.set([0,0,this.width,this.height]),this.context.bindFramebuffer.set(null),this.context.clear({color:n.showOverdrawInspector?p.bo.black:p.bo.transparent,depth:1}),this.clearStencil(),this.style.sky&&this.drawFunctions.sky(this,this.style.sky),this._showOverdrawInspector=n.showOverdrawInspector,this.depthRangeFor3D=[0,1-(t._order.length+2)*this.numSublayers*this.depthEpsilon],!this.renderToTexture)for(this.renderPass="opaque",this.currentLayer=y.length-1;this.currentLayer>=0;this.currentLayer--){let z=this.style._layers[y[this.currentLayer]],B=x[z.source],N=w[z.source];this._renderTileClippingMasks(z,N,!1),this.renderLayer(this,B,z,N,E)}this.renderPass="translucent";let C=!1;for(this.currentLayer=0;this.currentLayerU.source&&!U.isHidden(N)?[B.tileManagers[U.source]]:[])),$=j.filter((U=>U.getSource().type==="vector")),X=j.filter((U=>U.getSource().type!=="vector")),Z=U=>{(!G||G.getSource().maxzoom0?n.pop():null}isPatternMissing(t){if(!t)return!1;if(!t.from||!t.to)return!0;let n=this.imageManager.getPattern(t.from.toString()),a=this.imageManager.getPattern(t.to.toString());return!n||!a}useProgram(t,n,a=!1,c=[]){var f;this.cache||(this.cache={});let y=!!this.style.map.terrain,x=this.style.projection,w=a?ft.projectionMercator:x.shaderPreludeCode,P=a?ci:x.shaderDefine,S=t+(n?n.cacheKey:"")+`/${a?Ci:x.shaderVariantName}`+(this._showOverdrawInspector?"/overdraw":"")+(y?"/terrain":"")+(c?`/${c.join("/")}`:"");return(f=this.cache)[S]||(f[S]=new Uh(this.context,ft[t],n,qh[t],this._showOverdrawInspector,y,w,P,c)),this.cache[S]}setCustomLayerDefaults(){this.context.unbindVAO(),this.context.cullFace.setDefault(),this.context.activeTexture.setDefault(),this.context.pixelStoreUnpack.setDefault(),this.context.pixelStoreUnpackPremultiplyAlpha.setDefault(),this.context.pixelStoreUnpackFlipY.setDefault()}setBaseState(){let t=this.context.gl;this.context.cullFace.set(!1),this.context.viewport.set([0,0,this.width,this.height]),this.context.blendEquation.set(t.FUNC_ADD)}initDebugOverlayCanvas(){this.debugOverlayCanvas==null&&(this.debugOverlayCanvas=document.createElement("canvas"),this.debugOverlayCanvas.width=512,this.debugOverlayCanvas.height=512,this.debugOverlayTexture=new p.T(this.context,this.debugOverlayCanvas,this.context.gl.RGBA))}destroy(){var t,n;if(this._tileTextures){for(let a in this._tileTextures){let c=this._tileTextures[a];if(c)for(let f of c)f.destroy()}this._tileTextures={}}if(this.tileExtentBuffer&&this.tileExtentBuffer.destroy(),this.debugBuffer&&this.debugBuffer.destroy(),this.rasterBoundsBuffer&&this.rasterBoundsBuffer.destroy(),this.rasterBoundsBufferPosOnly&&this.rasterBoundsBufferPosOnly.destroy(),this.viewportBuffer&&this.viewportBuffer.destroy(),this.tileBorderIndexBuffer&&this.tileBorderIndexBuffer.destroy(),this.quadTriangleIndexBuffer&&this.quadTriangleIndexBuffer.destroy(),this.tileExtentMesh&&((t=this.tileExtentMesh.vertexBuffer)===null||t===void 0||t.destroy()),this.tileExtentMesh&&((n=this.tileExtentMesh.indexBuffer)===null||n===void 0||n.destroy()),this.debugOverlayTexture&&this.debugOverlayTexture.destroy(),this.cache){for(let a in this.cache){let c=this.cache[a];c?.program&&this.context.gl.deleteProgram(c.program)}this.cache={}}this.context&&this.context.setDefault()}overLimit(){let{drawingBufferWidth:t,drawingBufferHeight:n}=this.context.gl;return this.width!==t||this.height!==n}}function vl(u,t){let n,a=!1,c=null,f=()=>{c=null,a&&(u(...n),c=setTimeout(f,t),a=!1)};return(...y)=>(a=!0,n=y,c||f(),c)}$o.MAX_TEXTURE_POOL_SIZE_PER_BUCKET=50;class Zo{constructor(t){this._getCurrentHash=()=>{let n=window.location.hash.replace("#","");if(this._hashName){let a,c=n.split("&").map((f=>f.split("=")));for(let f of c)f[0]===this._hashName&&(a=f);return(a&&a[1]||"").split("/")}return n.split("/")},this._onHashChange=()=>{let n=this._getCurrentHash();if(!this._isValidHash(n))return!1;let a=this._map.dragRotate.isEnabled()&&this._map.touchZoomRotate.isEnabled()?+(n[3]||0):this._map.getBearing();return this._map.jumpTo({center:[+n[2],+n[1]],zoom:+n[0],bearing:a,pitch:+(n[4]||0)}),!0},this._updateHashUnthrottled=()=>{let n=window.location.href.replace(/(#.*)?$/,this.getHashString());window.history.replaceState(window.history.state,null,n)},this._removeHash=()=>{let n=this._getCurrentHash();if(n.length===0)return;let a=n.join("/"),c=a;c.split("&").length>0&&(c=c.split("&")[0]),this._hashName&&(c=`${this._hashName}=${a}`);let f=window.location.hash.replace(c,"");f.startsWith("#&")?f=f.slice(0,1)+f.slice(2):f==="#"&&(f="");let y=window.location.href.replace(/(#.+)?$/,f);y=y.replace("&&","&"),window.history.replaceState(window.history.state,null,y)},this._updateHash=vl(this._updateHashUnthrottled,300),this._hashName=t&&encodeURIComponent(t)}addTo(t){return this._map=t,addEventListener("hashchange",this._onHashChange,!1),this._map.on("moveend",this._updateHash),this}remove(){return removeEventListener("hashchange",this._onHashChange,!1),this._map.off("moveend",this._updateHash),clearTimeout(this._updateHash()),this._removeHash(),delete this._map,this}getHashString(t){let n=this._map.getCenter(),a=Math.round(100*this._map.getZoom())/100,c=Math.ceil((a*Math.LN2+Math.log(512/360/.5))/Math.LN10),f=Math.pow(10,c),y=Math.round(n.lng*f)/f,x=Math.round(n.lat*f)/f,w=this._map.getBearing(),P=this._map.getPitch(),S="";if(S+=t?`/${y}/${x}/${a}`:`${a}/${x}/${y}`,(w||P)&&(S+="/"+Math.round(10*w)/10),P&&(S+=`/${Math.round(P)}`),this._hashName){let E=this._hashName,C=!1,z=window.location.hash.slice(1).split("&").map((B=>{let N=B.split("=")[0];return N===E?(C=!0,`${N}=${S}`):B})).filter((B=>B));return C||z.push(`${E}=${S}`),`#${z.join("&")}`}return`#${S}`}_isValidHash(t){if(t.length<3||t.some(isNaN))return!1;try{new p.W(+t[2],+t[1])}catch{return!1}let n=+t[0],a=+(t[3]||0),c=+(t[4]||0);return n>=this._map.getMinZoom()&&n<=this._map.getMaxZoom()&&a>=-180&&a<=180&&c>=this._map.getMinPitch()&&c<=this._map.getMaxPitch()}}let no={linearity:.3,easing:p.cv(0,0,.3,1)},ji=p.e({deceleration:2500,maxSpeed:1400},no),Ji=p.e({deceleration:20,maxSpeed:1400},no),Wc=p.e({deceleration:1e3,maxSpeed:360},no),Qi=p.e({deceleration:1e3,maxSpeed:90},no),iu=p.e({deceleration:1e3,maxSpeed:360},no);class ru{constructor(t){this._map=t,this.clear()}clear(){this._inertiaBuffer=[]}record(t){this._drainInertiaBuffer(),this._inertiaBuffer.push({time:Xe(),settings:t})}_drainInertiaBuffer(){let t=this._inertiaBuffer,n=Xe();for(;t.length>0&&n-t[0].time>160;)t.shift()}_onMoveEnd(t){if(this._drainInertiaBuffer(),this._inertiaBuffer.length<2)return;let n={zoom:0,bearing:0,pitch:0,roll:0,pan:new p.P(0,0),pinchAround:void 0,around:void 0};for(let{settings:f}of this._inertiaBuffer)n.zoom+=f.zoomDelta||0,n.bearing+=f.bearingDelta||0,n.pitch+=f.pitchDelta||0,n.roll+=f.rollDelta||0,f.panDelta&&n.pan._add(f.panDelta),f.around&&(n.around=f.around),f.pinchAround&&(n.pinchAround=f.pinchAround);let a=this._inertiaBuffer[this._inertiaBuffer.length-1].time-this._inertiaBuffer[0].time,c={};if(n.pan.mag()){let f=nr(n.pan.mag(),a,p.e({},ji,t||{})),y=n.pan.mult(f.amount/n.pan.mag()),x=this._map.cameraHelper.handlePanInertia(y,this._map.transform);c.center=x.easingCenter,c.offset=x.easingOffset,qo(c,f)}if(n.zoom){let f=nr(n.zoom,a,Ji);c.zoom=p.cw(this._map.transform.zoom+f.amount,this._map.getZoomSnap(),f.amount),qo(c,f)}if(n.bearing){let f=nr(n.bearing,a,Wc);c.bearing=this._map.transform.bearing+p.al(f.amount,-179,179),qo(c,f)}if(n.pitch){let f=nr(n.pitch,a,Qi);c.pitch=this._map.transform.pitch+f.amount,qo(c,f)}if(n.roll){let f=nr(n.roll,a,iu);c.roll=this._map.transform.roll+p.al(f.amount,-179,179),qo(c,f)}if(c.zoom||c.bearing){let f=n.pinchAround===void 0?n.around:n.pinchAround;c.around=f?this._map.unproject(f):this._map.getCenter()}return this.clear(),p.e(c,{noMoveStart:!0})}}function qo(u,t){(!u.duration||u.durationn.unproject(w))),x=f.reduce(((w,P,S,E)=>w.add(P.div(E.length))),new p.P(0,0));super(t,{points:f,point:x,lngLats:y,lngLat:n.unproject(x),originalEvent:a}),this._defaultPrevented=!1}}class Hc extends p.n{preventDefault(){this._defaultPrevented=!0}get defaultPrevented(){return this._defaultPrevented}constructor(t,n,a){super(t,{originalEvent:a}),this._defaultPrevented=!1}}class nu{constructor(t,n){this._map=t,this._clickTolerance=n.clickTolerance}reset(){delete this._mousedownPos}wheel(t){return this._firePreventable(new Hc(t.type,this._map,t))}mousedown(t,n){return this._mousedownPos=n,this._firePreventable(new zi(t.type,this._map,t))}mouseup(t){this._map.fire(new zi(t.type,this._map,t))}click(t,n){this._mousedownPos&&this._mousedownPos.dist(n)>=this._clickTolerance||this._map.fire(new zi(t.type,this._map,t))}dblclick(t){return this._firePreventable(new zi(t.type,this._map,t))}mouseover(t){this._map.fire(new zi(t.type,this._map,t))}mouseout(t){this._map.fire(new zi(t.type,this._map,t))}touchstart(t){return this._firePreventable(new Wo(t.type,this._map,t))}touchmove(t){this._map.fire(new Wo(t.type,this._map,t))}touchend(t){this._map.fire(new Wo(t.type,this._map,t))}touchcancel(t){this._map.fire(new Wo(t.type,this._map,t))}_firePreventable(t){if(this._map.fire(t),t.defaultPrevented)return{}}isEnabled(){return!0}isActive(){return!1}enable(){}disable(){}}class Xc{constructor(t){this._map=t}reset(){this._delayContextMenu=!1,this._ignoreContextMenu=!0,delete this._contextMenuEvent}mousemove(t){this._map.fire(new zi(t.type,this._map,t))}mousedown(){this._delayContextMenu=!0,this._ignoreContextMenu=!1}mouseup(){this._delayContextMenu=!1,this._contextMenuEvent&&(this._map.fire(new zi("contextmenu",this._map,this._contextMenuEvent)),delete this._contextMenuEvent)}contextmenu(t){this._delayContextMenu?this._contextMenuEvent=t:this._ignoreContextMenu||this._map.fire(new zi(t.type,this._map,t)),this._map.listens("contextmenu")&&t.preventDefault()}isEnabled(){return!0}isActive(){return!1}enable(){}disable(){}}class fr{constructor(t){this._map=t}get transform(){return this._map._requestedCameraState||this._map.transform}get center(){return{lng:this.transform.center.lng,lat:this.transform.center.lat}}get zoom(){return this.transform.zoom}get pitch(){return this.transform.pitch}get bearing(){return this.transform.bearing}unproject(t){return this.transform.screenPointToLocation(p.P.convert(t),this._map.terrain)}}class or{constructor(t,n){this._map=t,this._tr=new fr(t),this._el=t.getCanvasContainer(),this._container=t.getContainer(),this._clickTolerance=n.clickTolerance||1,n.boxZoom&&typeof n.boxZoom=="object"&&(this._boxZoomEnd=n.boxZoom.boxZoomEnd)}isEnabled(){return!!this._enabled}isActive(){return!!this._active}enable(){this.isEnabled()||(this._enabled=!0)}disable(){this.isEnabled()&&(this._enabled=!1)}mousedown(t,n){this.isEnabled()&&t.shiftKey&&t.button===0&&(pe.disableDrag(),this._startPos=this._lastPos=n,this._active=!0)}mousemoveWindow(t,n){if(!this._active)return;let a=n;if(this._lastPos.equals(a)||!this._box&&a.dist(this._startPos)f.fitScreenCoordinates(a,c,this._tr.bearing,{linear:!0})};this._fireEvent("boxzoomcancel",t)}keydown(t){this._active&&t.keyCode===27&&(this.reset(),this._fireEvent("boxzoomcancel",t))}reset(){this._active=!1,this._container.classList.remove("maplibregl-crosshair"),this._box&&(this._box.remove(),this._box=null),pe.enableDrag(),delete this._startPos,delete this._lastPos}_fireEvent(t,n){return this._map.fire(new p.n(t,{originalEvent:n}))}}function Pe(u,t){if(u.length!==t.length)throw new Error(`The number of touches and points are not equal - touches ${u.length}, points ${t.length}`);let n={};for(let a=0;athis.numTouches)&&(this.aborted=!0),this.aborted||(this.startTime===void 0&&(this.startTime=t.timeStamp),a.length===this.numTouches&&(this.centroid=(function(c){let f=new p.P(0,0);for(let y of c)f._add(y);return f.div(c.length)})(n),this.touches=Pe(a,n)))}touchmove(t,n,a){if(this.aborted||!this.centroid)return;let c=Pe(a,n);for(let f in this.touches){let y=c[f];(!y||y.dist(this.touches[f])>30)&&(this.aborted=!0)}}touchend(t,n,a){if((!this.centroid||t.timeStamp-this.startTime>500)&&(this.aborted=!0),a.length===0){let c=!this.aborted&&this.centroid;if(this.reset(),c)return c}}}class Ho{constructor(t){this.singleTap=new Yc(t),this.numTaps=t.numTaps,this.reset()}reset(){this.lastTime=1/0,delete this.lastTap,this.count=0,this.singleTap.reset()}touchstart(t,n,a){this.singleTap.touchstart(t,n,a)}touchmove(t,n,a){this.singleTap.touchmove(t,n,a)}touchend(t,n,a){let c=this.singleTap.touchend(t,n,a);if(c){let f=t.timeStamp-this.lastTime<500,y=!this.lastTap||this.lastTap.dist(c)<30;if(f&&y||this.reset(),this.count++,this.lastTime=t.timeStamp,this.lastTap=c,this.count===this.numTaps)return this.reset(),c}}}class Kc{constructor(t){this._tr=new fr(t),this._zoomIn=new Ho({numTouches:1,numTaps:2}),this._zoomOut=new Ho({numTouches:2,numTaps:1}),this.reset()}reset(){this._active=!1,this._zoomIn.reset(),this._zoomOut.reset()}touchstart(t,n,a){this._zoomIn.touchstart(t,n,a),this._zoomOut.touchstart(t,n,a)}touchmove(t,n,a){this._zoomIn.touchmove(t,n,a),this._zoomOut.touchmove(t,n,a)}touchend(t,n,a){let c=this._zoomIn.touchend(t,n,a),f=this._zoomOut.touchend(t,n,a),y=this._tr;return c?(this._active=!0,t.preventDefault(),setTimeout((()=>this.reset()),0),{cameraAnimation:x=>x.easeTo({duration:300,zoom:p.cw(y.zoom+1,x.getZoomSnap()),around:y.unproject(c)},{originalEvent:t})}):f?(this._active=!0,t.preventDefault(),setTimeout((()=>this.reset()),0),{cameraAnimation:x=>x.easeTo({duration:300,zoom:p.cw(y.zoom-1,x.getZoomSnap()),around:y.unproject(f)},{originalEvent:t})}):void 0}touchcancel(){this.reset()}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}class mr{constructor(t){this._enabled=!!t.enable,this._moveStateManager=t.moveStateManager,this._clickTolerance=t.clickTolerance||1,this._moveFunction=t.move,this._activateOnStart=!!t.activateOnStart,t.assignEvents(this),this.reset()}reset(t){this._active=!1,this._moved=!1,delete this._lastPoint,this._moveStateManager.endMove(t)}_move(...t){let n=this._moveFunction(...t);if(n.bearingDelta||n.pitchDelta||n.rollDelta||n.around||n.panDelta)return this._active=!0,n}dragStart(t,n){this.isEnabled()&&!this._lastPoint&&this._moveStateManager.isValidStartEvent(t)&&(this._moveStateManager.startMove(t),this._lastPoint=Array.isArray(n)?n[0]:n,this._activateOnStart&&this._lastPoint&&(this._active=!0))}dragMove(t,n){if(!this.isEnabled())return;let a=this._lastPoint;if(!a)return;if(t.preventDefault(),!this._moveStateManager.isValidMoveEvent(t))return void this.reset(t);let c=Array.isArray(n)?n[0]:n;return!this._moved&&c.dist(a)!0}),n=new Jc){this.mouseMoveStateManager=t,this.oneFingerTouchMoveStateManager=n}_executeRelevantHandler(t,n,a){return t instanceof MouseEvent?n(t):typeof TouchEvent<"u"&&t instanceof TouchEvent?a(t):void 0}startMove(t){this._executeRelevantHandler(t,(n=>{this.mouseMoveStateManager.startMove(n)}),(n=>{this.oneFingerTouchMoveStateManager.startMove(n)}))}endMove(t){this._executeRelevantHandler(t,(n=>{this.mouseMoveStateManager.endMove(n)}),(n=>{this.oneFingerTouchMoveStateManager.endMove(n)}))}isValidStartEvent(t){return this._executeRelevantHandler(t,(n=>this.mouseMoveStateManager.isValidStartEvent(n)),(n=>this.oneFingerTouchMoveStateManager.isValidStartEvent(n)))}isValidMoveEvent(t){return this._executeRelevantHandler(t,(n=>this.mouseMoveStateManager.isValidMoveEvent(n)),(n=>this.oneFingerTouchMoveStateManager.isValidMoveEvent(n)))}isValidEndEvent(t){return this._executeRelevantHandler(t,(n=>this.mouseMoveStateManager.isValidEndEvent(n)),(n=>this.oneFingerTouchMoveStateManager.isValidEndEvent(n)))}}let qs=u=>{u.mousedown=u.dragStart,u.mousemoveWindow=u.dragMove,u.mouseup=u.dragEnd,u.contextmenu=t=>{t.preventDefault()}};class Qc{constructor(t,n){this._clickTolerance=t.clickTolerance||1,this._map=n,this.reset()}reset(){this._active=!1,this._touches={},this._sum=new p.P(0,0)}_shouldBePrevented(t){return t<(this._map.cooperativeGestures.isEnabled()?2:1)}touchstart(t,n,a){return this._calculateTransform(t,n,a)}touchmove(t,n,a){if(this._active){if(!this._shouldBePrevented(a.length))return t.preventDefault(),this._calculateTransform(t,n,a);this._map.cooperativeGestures.notifyGestureBlocked("touch_pan",t)}}touchend(t,n,a){this._calculateTransform(t,n,a),this._active&&this._shouldBePrevented(a.length)&&this.reset()}touchcancel(){this.reset()}_calculateTransform(t,n,a){a.length>0&&(this._active=!0);let c=Pe(a,n),f=new p.P(0,0),y=new p.P(0,0),x=0;for(let P in c){let S=c[P],E=this._touches[P];E&&(f._add(S),y._add(S.sub(E)),x++,c[P]=S)}if(this._touches=c,this._shouldBePrevented(x)||!y.mag())return;let w=y.div(x);return this._sum._add(w),this._sum.mag()Math.abs(u.x)}class gr extends wl{constructor(t){super(),this._currentTouchCount=0,this._map=t}reset(){super.reset(),this._valid=void 0,delete this._firstMove,delete this._lastPoints}touchstart(t,n,a){super.touchstart(t,n,a),this._currentTouchCount=a.length}_start(t){this._lastPoints=t,Sl(t[0].sub(t[1]))&&(this._valid=!1)}_move(t,n,a){if(this._map.cooperativeGestures.isEnabled()&&this._currentTouchCount<3)return;let c=t[0].sub(this._lastPoints[0]),f=t[1].sub(this._lastPoints[1]);return this._valid=this.gestureBeginsVertically(c,f,a.timeStamp),this._valid?(this._lastPoints=t,this._active=!0,{pitchDelta:(c.y+f.y)/2*-.5}):void 0}gestureBeginsVertically(t,n,a){if(this._valid!==void 0)return this._valid;let c=t.mag()>=2,f=n.mag()>=2;if(!c&&!f)return;if(!c||!f)return this._firstMove===void 0&&(this._firstMove=a),a-this._firstMove<100&&void 0;let y=t.y>0==n.y>0;return Sl(t)&&Sl(n)&&y}}let ct={panStep:100,bearingStep:15,pitchStep:10};class ih{constructor(t){this._tr=new fr(t);let n=ct;this._panStep=n.panStep,this._bearingStep=n.bearingStep,this._pitchStep=n.pitchStep,this._rotationDisabled=!1}reset(){this._active=!1}keydown(t){if(t.altKey||t.ctrlKey||t.metaKey)return;let n=0,a=0,c=0,f=0,y=0;switch(t.keyCode){case 61:case 107:case 171:case 187:n=1;break;case 189:case 109:case 173:n=-1;break;case 37:t.shiftKey?a=-1:(t.preventDefault(),f=-1);break;case 39:t.shiftKey?a=1:(t.preventDefault(),f=1);break;case 38:t.shiftKey?c=1:(t.preventDefault(),y=-1);break;case 40:t.shiftKey?c=-1:(t.preventDefault(),y=1);break;default:return}return this._rotationDisabled&&(a=0,c=0),{cameraAnimation:x=>{let w=this._tr;x.easeTo({duration:300,easeId:"keyboardHandler",easing:Hs,zoom:n?p.cw(w.zoom+n*(t.shiftKey?2:1),x.getZoomSnap()):w.zoom,bearing:w.bearing+a*this._bearingStep,pitch:w.pitch+c*this._pitchStep,offset:[-f*this._panStep,-y*this._panStep],center:w.center},{originalEvent:t})}}}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}disableRotation(){this._rotationDisabled=!0}enableRotation(){this._rotationDisabled=!1}}function Hs(u){return u*(2-u)}let Yo=4.000244140625,Il=1/450;class Ml{constructor(t,n){this._onTimeout=a=>{this._type="wheel",this._delta-=this._lastValue,this._active||this._start(a)},this._map=t,this._tr=new fr(t),this._triggerRenderFrame=n,this._delta=0,this._defaultZoomRate=.01,this._wheelZoomRate=Il}setZoomRate(t){this._defaultZoomRate=t}setWheelZoomRate(t){this._wheelZoomRate=t}isEnabled(){return!!this._enabled}isActive(){return!!this._active||this._finishTimeout!==void 0}isZooming(){return!!this._zooming}enable(t){this.isEnabled()||(this._enabled=!0,this._aroundCenter=!!t&&t.around==="center")}disable(){this.isEnabled()&&(this._enabled=!1)}_shouldBePrevented(t){return!!this._map.cooperativeGestures.isEnabled()&&!(t.ctrlKey||this._map.cooperativeGestures.isBypassed(t))}wheel(t){if(!this.isEnabled())return;if(this._shouldBePrevented(t))return void this._map.cooperativeGestures.notifyGestureBlocked("wheel_zoom",t);let n=t.deltaMode===WheelEvent.DOM_DELTA_LINE?40*t.deltaY:t.deltaY,a=Xe(),c=a-(this._lastWheelEventTime||0);this._lastWheelEventTime=a,n!==0&&n%Yo==0?this._type="wheel":n!==0&&Math.abs(n)<4?this._type="trackpad":c>400?(this._type=null,this._lastValue=n,this._timeout=setTimeout(this._onTimeout,40,t)):this._type||(this._type=Math.abs(c*n)<200?"trackpad":"wheel",this._timeout&&(clearTimeout(this._timeout),this._timeout=null,n+=this._lastValue)),t.shiftKey&&n&&(n/=4),this._type&&(this._lastWheelEvent=t,this._delta-=n,this._active||this._start(t)),t.preventDefault()}_start(t){if(!this._delta)return;this._needsRerender=!1,this._active=!0,this.isZooming()||(this._zooming=!0),this._finishTimeout&&(clearTimeout(this._finishTimeout),delete this._finishTimeout);let n=pe.mousePos(this._map.getCanvas(),t),a=this._tr;this._aroundPoint=this._aroundCenter?a.transform.locationToScreenPoint(p.W.convert(a.center)):n,this._needsRerender||(this._needsRerender=!0,this._triggerRenderFrame())}renderFrame(){if(!this._needsRerender||(this._needsRerender=!1,!this.isActive()))return;let t=this._tr.transform;if(typeof this._lastExpectedZoom=="number"){let x=t.zoom-this._lastExpectedZoom;typeof this._startZoom=="number"&&(this._startZoom+=x),typeof this._targetZoom=="number"&&(this._targetZoom+=x)}if(this._delta!==0){let x=this._type==="wheel"&&Math.abs(this._delta)>Yo?this._wheelZoomRate:this._defaultZoomRate,w=2/(1+Math.exp(-Math.abs(this._delta*x)));this._delta<0&&w!==0&&(w=1/w);let P=typeof this._targetZoom!="number"?t.scale:p.ao(this._targetZoom),S=t.applyConstrain(t.getCameraLngLat(),p.ar(P*w)).zoom,E=this._map.getZoomSnap();if(this._type==="wheel"&&E>0){let C=p.cw(t.zoom,E);this._targetZoom=p.cw(S,E,S-C)}else this._targetZoom=S;this._type==="wheel"&&(this._startZoom=t.zoom,this._easing=this._smoothOutEasing(200)),this._delta=0}let n=typeof this._targetZoom!="number"?t.zoom:this._targetZoom,a=this._startZoom,c=this._easing,f,y=!1;if(this._type==="wheel"&&a&&c){let x=Xe()-this._lastWheelEventTime,w=Math.min((x+5)/200,1),P=c(w);f=p.H.number(a,n,P),w<1?this._needsRerender=!0:y=!0}else f=n,y=!0;return this._active=!0,y&&(this._active=!1,this._finishTimeout=setTimeout((()=>{this._zooming=!1,this._triggerRenderFrame(),delete this._targetZoom,delete this._lastExpectedZoom,delete this._finishTimeout}),200)),this._lastExpectedZoom=f,{noInertia:!0,needsRenderFrame:!y,zoomDelta:f-t.zoom,around:this._aroundPoint,originalEvent:this._lastWheelEvent}}_smoothOutEasing(t){let n=p.cy;if(this._prevEase){let a=this._prevEase,c=(Xe()-a.start)/a.duration,f=a.easing(c+.01)-a.easing(c),y=.27/Math.sqrt(f*f+1e-4)*.01,x=Math.sqrt(.0729-y*y);n=p.cv(y,x,.25,1)}return this._prevEase={start:Xe(),duration:t,easing:n},n}reset(){this._active=!1,this._zooming=!1,delete this._targetZoom,delete this._lastExpectedZoom,this._finishTimeout&&(clearTimeout(this._finishTimeout),delete this._finishTimeout)}}class El{constructor(t,n){this._clickZoom=t,this._tapZoom=n}enable(){this._clickZoom.enable(),this._tapZoom.enable()}disable(){this._clickZoom.disable(),this._tapZoom.disable()}isEnabled(){return this._clickZoom.isEnabled()&&this._tapZoom.isEnabled()}isActive(){return this._clickZoom.isActive()||this._tapZoom.isActive()}}class rh{constructor(t){this._tr=new fr(t),this.reset()}reset(){this._active=!1}dblclick(t,n){return t.preventDefault(),{cameraAnimation:a=>{a.easeTo({duration:300,zoom:p.cw(this._tr.zoom+(t.shiftKey?-1:1),a.getZoomSnap()),around:this._tr.unproject(n)},{originalEvent:t})}}}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}class su{constructor(){this._tap=new Ho({numTouches:1,numTaps:1}),this._zoomRate=1,this.reset()}setZoomRate(t){this._zoomRate=t??1}reset(){this._active=!1,delete this._swipePoint,delete this._swipeTouch,delete this._tapTime,delete this._tapPoint,this._tap.reset()}touchstart(t,n,a){if(!this._swipePoint)if(this._tapTime){let c=n[0],f=t.timeStamp-this._tapTime<500,y=this._tapPoint.dist(c)<30;f&&y?a.length>0&&(this._swipePoint=c,this._swipeTouch=a[0].identifier):this.reset()}else this._tap.touchstart(t,n,a)}touchmove(t,n,a){if(this._tapTime){if(this._swipePoint){if(a[0].identifier!==this._swipeTouch)return;let c=n[0],f=c.y-this._swipePoint.y;return this._swipePoint=c,t.preventDefault(),this._active=!0,{zoomDelta:f/128*this._zoomRate}}}else this._tap.touchmove(t,n,a)}touchend(t,n,a){if(this._tapTime)this._swipePoint&&a.length===0&&this.reset();else{let c=this._tap.touchend(t,n,a);c&&(this._tapTime=t.timeStamp,this._tapPoint=c)}}touchcancel(){this.reset()}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}class er{constructor(t,n,a){this._el=t,this._mousePan=n,this._touchPan=a}enable(t){this._inertiaOptions=t||{},this._mousePan.enable(),this._touchPan.enable(),this._el.classList.add("maplibregl-touch-drag-pan")}disable(){this._mousePan.disable(),this._touchPan.disable(),this._el.classList.remove("maplibregl-touch-drag-pan")}isEnabled(){return this._mousePan.isEnabled()&&this._touchPan.isEnabled()}isActive(){return this._mousePan.isActive()||this._touchPan.isActive()}}class Ko{constructor(t,n,a,c){this._pitchWithRotate=t.pitchWithRotate,this._rollEnabled=t.rollEnabled,this._mouseRotate=n,this._mousePitch=a,this._mouseRoll=c}enable(){this._mouseRotate.enable(),this._pitchWithRotate&&this._mousePitch.enable(),this._rollEnabled&&this._mouseRoll.enable()}disable(){this._mouseRotate.disable(),this._mousePitch.disable(),this._mouseRoll.disable()}isEnabled(){return this._mouseRotate.isEnabled()&&(!this._pitchWithRotate||this._mousePitch.isEnabled())&&(!this._rollEnabled||this._mouseRoll.isEnabled())}isActive(){return this._mouseRotate.isActive()||this._mousePitch.isActive()||this._mouseRoll.isActive()}}class Ie{constructor(t,n,a,c){this._el=t,this._touchZoom=n,this._touchRotate=a,this._tapDragZoom=c,this._rotationDisabled=!1,this._enabled=!0}enable(t){this._touchZoom.enable(t),this._rotationDisabled||this._touchRotate.enable(t),this._tapDragZoom.enable(),this._el.classList.add("maplibregl-touch-zoom-rotate")}disable(){this._touchZoom.disable(),this._touchRotate.disable(),this._tapDragZoom.disable(),this._el.classList.remove("maplibregl-touch-zoom-rotate")}isEnabled(){return this._touchZoom.isEnabled()&&(this._rotationDisabled||this._touchRotate.isEnabled())&&this._tapDragZoom.isEnabled()}isActive(){return this._touchZoom.isActive()||this._touchRotate.isActive()||this._tapDragZoom.isActive()}setZoomRate(t){this._touchZoom.setZoomRate(t),this._tapDragZoom.setZoomRate(t)}setZoomThreshold(t){this._touchZoom.setZoomThreshold(t)}disableRotation(){this._rotationDisabled=!0,this._touchRotate.disable()}enableRotation(){this._rotationDisabled=!1,this._touchZoom.isEnabled()&&this._touchRotate.enable()}}class Ce{constructor(t,n){this._bypassKey=navigator.userAgent.includes("Mac")?"metaKey":"ctrlKey",this._map=t,this._options=n,this._enabled=!1}isActive(){return!1}reset(){}_setupUI(){if(this._container)return;let t=this._map.getCanvasContainer();t.classList.add("maplibregl-cooperative-gestures"),this._container=pe.create("div","maplibregl-cooperative-gesture-screen",t);let n=this._map._getUIString("CooperativeGesturesHandler.WindowsHelpText");this._bypassKey==="metaKey"&&(n=this._map._getUIString("CooperativeGesturesHandler.MacHelpText"));let a=this._map._getUIString("CooperativeGesturesHandler.MobileHelpText"),c=document.createElement("div");c.className="maplibregl-desktop-message",c.textContent=n,this._container.appendChild(c);let f=document.createElement("div");f.className="maplibregl-mobile-message",f.textContent=a,this._container.appendChild(f),this._container.setAttribute("aria-hidden","true")}_destroyUI(){this._container&&(this._container.remove(),this._map.getCanvasContainer().classList.remove("maplibregl-cooperative-gestures")),delete this._container}enable(){this._setupUI(),this._enabled=!0}disable(){this._enabled=!1,this._destroyUI()}isEnabled(){return this._enabled}isBypassed(t){return t[this._bypassKey]}notifyGestureBlocked(t,n){this._enabled&&(this._map.fire(new p.n("cooperativegestureprevented",{gestureType:t,originalEvent:n})),this._container.classList.add("maplibregl-show"),setTimeout((()=>{this._container.classList.remove("maplibregl-show")}),100))}}let Or=u=>u.zoom||u.drag||u.roll||u.pitch||u.rotate;class nh extends p.n{}function oo(u){var t;return((t=u.panDelta)===null||t===void 0?void 0:t.mag())||u.zoomDelta||u.bearingDelta||u.pitchDelta||u.rollDelta}class ui{get _ownerDocument(){var t;return((t=this._el)===null||t===void 0?void 0:t.ownerDocument)||document}get _ownerWindow(){var t,n;return((n=(t=this._el)===null||t===void 0?void 0:t.ownerDocument)===null||n===void 0?void 0:n.defaultView)||window}constructor(t,n){this.handleWindowEvent=c=>{this.handleEvent(c,`${c.type}Window`)},this.handleEvent=(c,f)=>{if(c.type==="blur")return void this.stop(!0);this._updatingCamera=!0;let y=c.type==="renderFrame"?void 0:c,x={needsRenderFrame:!1},w={},P={};for(let{handlerName:C,handler:z,allowed:B}of this._handlers){if(!z.isEnabled())continue;let N;if(this._blockedByActive(P,B,C))z.reset();else if(z[f||c.type]){if(p.cz(c,f||c.type)){let G=pe.mousePos(this._map.getCanvas(),c);N=z[f||c.type](c,G)}else if(p.cA(c,f||c.type)){let G=this._getMapTouches(c.touches),j=pe.touchPos(this._map.getCanvas(),G);N=z[f||c.type](c,j,G)}else p.cB(f||c.type)||(N=z[f||c.type](c));this.mergeHandlerResult(x,w,N,C,y),N?.needsRenderFrame&&this._triggerRenderFrame()}(N||z.isActive())&&(P[C]=z)}let S={};for(let C in this._previousActiveHandlers)P[C]||(S[C]=y);this._previousActiveHandlers=P,(Object.keys(S).length||oo(x))&&(this._changes.push([x,w,S]),this._triggerRenderFrame()),(Object.keys(P).length||oo(x))&&this._map._stop(!0),this._updatingCamera=!1;let{cameraAnimation:E}=x;E&&(this._inertia.clear(),this._fireEvents({},{},!0),this._changes=[],E(this._map))},this._map=t,this._el=this._map.getCanvasContainer(),this._handlers=[],this._handlersById={},this._changes=[],this._inertia=new ru(t),this._bearingSnap=n.bearingSnap,this._previousActiveHandlers={},this._eventsInProgress={},this._addDefaultHandlers(n);let a=this._el;this._listeners=[[a,"touchstart",{passive:!0}],[a,"touchmove",{passive:!1}],[a,"touchend",void 0],[a,"touchcancel",void 0],[a,"mousedown",void 0],[a,"mousemove",void 0],[a,"mouseup",void 0],[this._ownerDocument,"mousemove",{capture:!0}],[this._ownerDocument,"mouseup",void 0],[a,"mouseover",void 0],[a,"mouseout",void 0],[a,"dblclick",void 0],[a,"click",void 0],[a,"keydown",{capture:!1}],[a,"keyup",void 0],[a,"wheel",{passive:!1}],[a,"contextmenu",void 0],[this._ownerWindow,"blur",void 0]];for(let[c,f,y]of this._listeners)c.addEventListener(f,c===this._ownerDocument?this.handleWindowEvent:this.handleEvent,y)}destroy(){for(let[t,n,a]of this._listeners)t.removeEventListener(n,t===this._ownerDocument?this.handleWindowEvent:this.handleEvent,a)}_addDefaultHandlers(t){let n=this._map,a=n.getCanvasContainer();this._add("mapEvent",new nu(n,t));let c=n.boxZoom=new or(n,t);this._add("boxZoom",c),t.interactive&&t.boxZoom&&c.enable();let f=n.cooperativeGestures=new Ce(n,t.cooperativeGestures);this._add("cooperativeGestures",f),t.cooperativeGestures&&f.enable();let y=new Kc(n),x=new rh(n);n.doubleClickZoom=new El(x,y),this._add("tapZoom",y),this._add("clickZoom",x),t.interactive&&t.doubleClickZoom&&n.doubleClickZoom.enable();let w=new su;this._add("tapDragZoom",w);let P=n.touchPitch=new gr(n);this._add("touchPitch",P),t.interactive&&t.touchPitch&&n.touchPitch.enable(t.touchPitch);let S=()=>n.project(n.getCenter()),E=(function({enable:Z,clickTolerance:U,aroundCenter:H=!0,minPixelCenterThreshold:q=100,rotateDegreesPerPixelMoved:Q=.8},oe){let se=new bn({checkCorrectEvent:de=>de.button===0&&de.ctrlKey||de.button===2&&!de.ctrlKey});return new mr({clickTolerance:U,move:(de,ue)=>{let Se=oe();if(H&&Math.abs(Se.y-de.y)>q)return{bearingDelta:p.cx(new p.P(de.x,ue.y),ue,Se)};let ve=(ue.x-de.x)*Q;return H&&ue.yQ.button===0&&Q.ctrlKey||Q.button===2});return new mr({clickTolerance:U,move:(Q,oe)=>({pitchDelta:(oe.y-Q.y)*H}),moveStateManager:q,enable:Z,assignEvents:qs})})(t),z=(function({enable:Z,clickTolerance:U,rollDegreesPerPixelMoved:H=.3},q){let Q=new bn({checkCorrectEvent:oe=>oe.button===2&&oe.ctrlKey});return new mr({clickTolerance:U,move:(oe,se)=>{let de=q(),ue=(se.x-oe.x)*H;return se.yq.button===0&&!q.ctrlKey});return new mr({clickTolerance:U,move:(q,Q)=>({around:Q,panDelta:Q.sub(q)}),activateOnStart:!0,moveStateManager:H,enable:Z,assignEvents:qs})})(t),N=new Qc(t,n);n.dragPan=new er(a,B,N),this._add("mousePan",B),this._add("touchPan",N,["touchZoom","touchRotate"]),t.interactive&&t.dragPan&&n.dragPan.enable(t.dragPan);let G=new th,j=new eh;n.touchZoomRotate=new Ie(a,j,G,w),this._add("touchRotate",G,["touchPan","touchZoom"]),this._add("touchZoom",j,["touchPan","touchRotate"]),t.interactive&&t.touchZoomRotate&&n.touchZoomRotate.enable(t.touchZoomRotate),this._add("blockableMapEvent",new Xc(n));let $=n.scrollZoom=new Ml(n,(()=>this._triggerRenderFrame()));this._add("scrollZoom",$,["mousePan"]),t.interactive&&t.scrollZoom&&n.scrollZoom.enable(t.scrollZoom);let X=n.keyboard=new ih(n);this._add("keyboard",X),t.interactive&&t.keyboard&&n.keyboard.enable()}_add(t,n,a){this._handlers.push({handlerName:t,handler:n,allowed:a}),this._handlersById[t]=n}stop(t){if(!this._updatingCamera){for(let{handler:n}of this._handlers)n.reset();this._inertia.clear(),this._fireEvents({},{},t),this._changes=[]}}isActive(){for(let{handler:t}of this._handlers)if(t.isActive())return!0;return!1}isZooming(){return!!this._eventsInProgress.zoom||this._map.scrollZoom.isZooming()}isRotating(){return!!this._eventsInProgress.rotate}isMoving(){return!!Or(this._eventsInProgress)||this.isZooming()}_blockedByActive(t,n,a){for(let c in t)if(c!==a&&!n?.includes(c))return!0;return!1}_getMapTouches(t){let n=[];for(let a of t)this._el.contains(a.target)&&n.push(a);return n}mergeHandlerResult(t,n,a,c,f){if(!a)return;p.e(t,a);let y={handlerName:c,originalEvent:a.originalEvent||f};a.zoomDelta!==void 0&&(n.zoom=y),a.panDelta!==void 0&&(n.drag=y),a.rollDelta!==void 0&&(n.roll=y),a.pitchDelta!==void 0&&(n.pitch=y),a.bearingDelta!==void 0&&(n.rotate=y)}_applyChanges(){let t={},n={},a={};for(let[c,f,y]of this._changes)c.panDelta&&(t.panDelta=(t.panDelta||new p.P(0,0))._add(c.panDelta)),c.zoomDelta&&(t.zoomDelta=(t.zoomDelta||0)+c.zoomDelta),c.bearingDelta&&(t.bearingDelta=(t.bearingDelta||0)+c.bearingDelta),c.pitchDelta&&(t.pitchDelta=(t.pitchDelta||0)+c.pitchDelta),c.rollDelta&&(t.rollDelta=(t.rollDelta||0)+c.rollDelta),c.around!==void 0&&(t.around=c.around),c.pinchAround!==void 0&&(t.pinchAround=c.pinchAround),c.noInertia&&(t.noInertia=c.noInertia),p.e(n,f),p.e(a,y);this._updateMapTransform(t,n,a),this._changes=[]}_updateMapTransform(t,n,a){let c=this._map,f=c._getTransformForUpdate(),y=c.terrain;if(!(oo(t)||y&&this._terrainMovement))return void this._fireEvents(n,a,!0);c._stop(!0);let{panDelta:x,zoomDelta:w,bearingDelta:P,pitchDelta:S,rollDelta:E,around:C,pinchAround:z}=t;z!==void 0&&(C=z),C||(C=c.transform.centerPoint),y&&!f.isPointOnMapSurface(C)&&(C=f.centerPoint);let B={panDelta:x,zoomDelta:w,rollDelta:E,pitchDelta:S,bearingDelta:P,around:C};this._map.cameraHelper.useGlobeControls&&!f.isPointOnMapSurface(C)&&(C=f.centerPoint);let N=C.distSqr(f.centerPoint)<.01?f.center:f.screenPointToLocation(x?C.sub(x):C);this._handleMapControls({terrain:y,tr:f,deltasForHelper:B,preZoomAroundLoc:N,combinedEventsInProgress:n,panDelta:x}),c._applyUpdatedTransform(f),this._map._update(),t.noInertia||this._inertia.record(t),this._fireEvents(n,a,!0)}_handleMapControls({terrain:t,tr:n,deltasForHelper:a,preZoomAroundLoc:c,combinedEventsInProgress:f,panDelta:y}){let x=this._map.cameraHelper;if(x.handleMapControlsRollPitchBearingZoom(a,n),t)return x.useGlobeControls?(this._terrainMovement||!f.drag&&!f.zoom||(this._terrainMovement=!0,this._map._elevationFreeze=!0),void x.handleMapControlsPan(a,n,c)):this._terrainMovement||!f.drag&&!f.zoom?void(f.drag&&this._terrainMovement&&y?n.setCenter(n.screenPointToLocation(n.centerPoint.sub(y))):x.handleMapControlsPan(a,n,c)):(this._terrainMovement=!0,this._map._elevationFreeze=!0,void x.handleMapControlsPan(a,n,c));x.handleMapControlsPan(a,n,c)}_fireEvents(t,n,a){let c=Or(this._eventsInProgress),f=Or(t),y={};for(let E in t){let{originalEvent:C}=t[E];this._eventsInProgress[E]||(y[`${E}start`]=C),this._eventsInProgress[E]=t[E]}!c&&f&&this._fireEvent("movestart",f.originalEvent);for(let E in y)this._fireEvent(E,y[E]);f&&this._fireEvent("move",f.originalEvent);for(let E in t){let{originalEvent:C}=t[E];this._fireEvent(E,C)}let x={},w;for(let E in this._eventsInProgress){let{handlerName:C,originalEvent:z}=this._eventsInProgress[E];this._handlersById[C].isActive()||(delete this._eventsInProgress[E],w=n[C]||z,x[`${E}end`]=w)}for(let E in x)this._fireEvent(E,x[E]);let P=Or(this._eventsInProgress),S=(c||f)&&!P;if(S&&this._terrainMovement){this._map._elevationFreeze=!1,this._terrainMovement=!1;let E=this._map._getTransformForUpdate();this._map.getCenterClampedToGround()&&E.recalculateZoomAndCenter(this._map.terrain),this._map._applyUpdatedTransform(E)}if(a&&S){this._updatingCamera=!0;let E=this._inertia._onMoveEnd(this._map.dragPan._inertiaOptions),C=z=>z!==0&&-this._bearingSnap{delete this._frameId,this.handleEvent(new nh("renderFrame",{timeStamp:t})),this._applyChanges()}))}_triggerRenderFrame(){this._frameId===void 0&&(this._frameId=this._requestFrame())}}class oh extends p.E{constructor(t,n,a){super(),this._renderFrameCallback=()=>{let c=Math.min((Xe()-this._easeStart)/this._easeOptions.duration,1);this._onEaseFrame(this._easeOptions.easing(c)),c<1&&this._easeFrameId?this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback):this.stop()},this._moving=!1,this._zooming=!1,this.transform=t,this._bearingSnap=a.bearingSnap,this._zoomSnap=a.zoomSnap,this.cameraHelper=n,this.on("moveend",(()=>{delete this._requestedCameraState}))}migrateProjection(t,n){t.apply(this.transform,!0),this.transform=t,this.cameraHelper=n}getCenter(){return new p.W(this.transform.center.lng,this.transform.center.lat)}setCenter(t,n){return this.jumpTo({center:t},n)}getCenterElevation(){return this.transform.elevation}setCenterElevation(t,n){return this.jumpTo({elevation:t},n),this}getCenterClampedToGround(){return this._centerClampedToGround}setCenterClampedToGround(t){this._centerClampedToGround=t}panBy(t,n,a){return t=p.P.convert(t).mult(-1),this.panTo(this.transform.center,p.e({offset:t},n),a)}panTo(t,n,a){return this.easeTo(p.e({center:t},n),a)}getZoom(){return this.transform.zoom}setZoom(t,n){return this.jumpTo({zoom:t},n),this}zoomTo(t,n,a){return this.easeTo(p.e({zoom:t},n),a)}zoomIn(t,n){return this.zoomTo(p.cw(this.getZoom()+1,this._zoomSnap),t,n),this}zoomOut(t,n){return this.zoomTo(p.cw(this.getZoom()-1,this._zoomSnap),t,n),this}getVerticalFieldOfView(){return this.transform.fov}setVerticalFieldOfView(t,n){return t!=this.transform.fov&&(this.transform.setFov(t),this.fire(new p.n("movestart",n)).fire(new p.n("move",n)).fire(new p.n("moveend",n))),this}getBearing(){return this.transform.bearing}setZoomSnap(t){return this._zoomSnap=t,this}getZoomSnap(){return this._zoomSnap}setBearing(t,n){return this.jumpTo({bearing:t},n),this}getPadding(){return this.transform.padding}setPadding(t,n){return this.jumpTo({padding:t},n),this}rotateTo(t,n,a){return this.easeTo(p.e({bearing:t},n),a)}resetNorth(t,n){return this.rotateTo(0,p.e({duration:1e3},t),n),this}resetNorthPitch(t,n){return this.easeTo(p.e({bearing:0,pitch:0,roll:0,duration:1e3},t),n),this}snapToNorth(t,n){return Math.abs(this.getBearing()){N.easeFunc(G),this.terrain&&!t.freezeElevation&&this._updateElevation(G),this._applyUpdatedTransform(a),this._fireMoveEvents(n)}),(G=>{this.terrain&&t.freezeElevation&&this._finalizeElevation(),this._afterEase(n,G)}),t),this}_prepareEase(t,n,a={}){this._moving=!0,n||a.moving||this.fire(new p.n("movestart",t)),this._zooming&&!a.zooming&&this.fire(new p.n("zoomstart",t)),this._rotating&&!a.rotating&&this.fire(new p.n("rotatestart",t)),this._pitching&&!a.pitching&&this.fire(new p.n("pitchstart",t)),this._rolling&&!a.rolling&&this.fire(new p.n("rollstart",t))}_prepareElevation(t){this._elevationCenter=t,this._elevationStart=this.transform.elevation,this._elevationTarget=this.terrain.getElevationForLngLatZoom(t,this.transform.tileZoom),this._elevationFreeze=!0}_updateElevation(t){this._elevationStart!==void 0&&this._elevationCenter!==void 0||this._prepareElevation(this.transform.center),this.transform.setMinElevationForCurrentTile(this.terrain.getMinTileElevationForLngLatZoom(this._elevationCenter,this.transform.tileZoom));let n=this.terrain.getElevationForLngLatZoom(this._elevationCenter,this.transform.tileZoom);if(t<1&&n!==this._elevationTarget){let a=this._elevationTarget-this._elevationStart;this._elevationStart+=t*(a-(n-(a*t+this._elevationStart))/(1-t)),this._elevationTarget=n}this.transform.setElevation(p.H.number(this._elevationStart,this._elevationTarget,t))}_finalizeElevation(){this._elevationFreeze=!1,this.getCenterClampedToGround()&&this.transform.recalculateZoomAndCenter(this.terrain)}_getTransformForUpdate(){return this.transformCameraUpdate||this.terrain?(this._requestedCameraState||(this._requestedCameraState=this.transform.clone()),this._requestedCameraState):this.transform}_elevateCameraIfInsideTerrain(t){if(!this.terrain&&t.elevation>=0&&t.pitch<=90)return{};let n=t.getCameraLngLat(),a=t.getCameraAltitude(),c=this.terrain?this.terrain.getElevationForLngLatZoom(n,t.zoom):0;if(athis._elevateCameraIfInsideTerrain(c))),this.transformCameraUpdate&&n.push((c=>this.transformCameraUpdate(c))),!n.length)return;let a=t.clone();for(let c of n){let f=a.clone(),{center:y,zoom:x,roll:w,pitch:P,bearing:S,elevation:E}=c(f);y&&f.setCenter(y),E!==void 0&&f.setElevation(E),x!==void 0&&f.setZoom(x),w!==void 0&&f.setRoll(w),P!==void 0&&f.setPitch(P),S!==void 0&&f.setBearing(S),a.apply(f,!1)}this.transform.apply(a,!1)}_fireMoveEvents(t){this.fire(new p.n("move",t)),this._zooming&&this.fire(new p.n("zoom",t)),this._rotating&&this.fire(new p.n("rotate",t)),this._pitching&&this.fire(new p.n("pitch",t)),this._rolling&&this.fire(new p.n("roll",t))}_afterEase(t,n){if(this._easeId&&n&&this._easeId===n)return;delete this._easeId;let a=this._zooming,c=this._rotating,f=this._pitching,y=this._rolling;this._moving=!1,this._zooming=!1,this._rotating=!1,this._pitching=!1,this._rolling=!1,this._padding=!1,a&&this.fire(new p.n("zoomend",t)),c&&this.fire(new p.n("rotateend",t)),f&&this.fire(new p.n("pitchend",t)),y&&this.fire(new p.n("rollend",t)),this.fire(new p.n("moveend",t))}flyTo(t,n){if(!t.essential&&qt.prefersReducedMotion){let ue=p.V(t,["center","zoom","bearing","pitch","roll","elevation","padding"]);return this.jumpTo(ue,n)}this.stop(),"zoom"in(t=p.e({offset:[0,0],speed:1.2,curve:1.42,easing:p.cy},t))&&this._zoomSnap&&(t.zoom=p.cw(t.zoom,this._zoomSnap));let a=this._getTransformForUpdate(),c=a.bearing,f=a.pitch,y=a.roll,x=a.padding,w="bearing"in t?this._normalizeBearing(t.bearing,c):c,P="pitch"in t?+t.pitch:f,S="roll"in t?this._normalizeBearing(t.roll,y):y,E="padding"in t?t.padding:a.padding,C=p.P.convert(t.offset),z=a.centerPoint.add(C),B=a.screenPointToLocation(z),N=this.cameraHelper.handleFlyTo(a,{bearing:w,pitch:P,roll:S,padding:E,locationAtOffset:B,offsetAsPoint:C,center:t.center,minZoom:t.minZoom,zoom:t.zoom}),G=t.curve,j=Math.max(a.width,a.height),$=j/N.scaleOfZoom,X=N.pixelPathLength;typeof N.scaleOfMinZoom=="number"&&(G=Math.sqrt(j/N.scaleOfMinZoom/X*2));let Z=G*G;function U(ue){let Se=($*$-j*j+(ue?-1:1)*Z*Z*X*X)/(2*(ue?$:j)*Z*X);return Math.log(Math.sqrt(Se*Se+1)-Se)}function H(ue){return(Math.exp(ue)-Math.exp(-ue))/2}function q(ue){return(Math.exp(ue)+Math.exp(-ue))/2}let Q=U(!1),oe=function(ue){return q(Q)/q(Q+G*ue)},se=function(ue){return j*((q(Q)*(H(Se=Q+G*ue)/q(Se))-H(Q))/Z)/X;var Se},de=(U(!0)-Q)/G;if(Math.abs(X)<2e-6||!isFinite(de)){if(Math.abs(j-$)<1e-6)return this.easeTo(t,n);let ue=$0,oe=Se=>Math.exp(ue*G*Se)}return t.duration="duration"in t?+t.duration:1e3*de/("screenSpeed"in t?+t.screenSpeed/G:+t.speed),t.maxDuration&&t.duration>t.maxDuration&&(t.duration=0),this._zooming=!0,this._rotating=c!==w,this._pitching=P!==f,this._rolling=S!==y,this._padding=!a.isPaddingEqual(E),this._prepareEase(n,!1),this.terrain&&this._prepareElevation(N.targetCenter),this._ease((ue=>{let Se=ue*de,ve=1/oe(Se),he=se(Se);this._rotating&&a.setBearing(p.H.number(c,w,ue)),this._pitching&&a.setPitch(p.H.number(f,P,ue)),this._rolling&&a.setRoll(p.H.number(y,S,ue)),this._padding&&(a.interpolatePadding(x,E,ue),z=a.centerPoint.add(C)),N.easeFunc(ue,ve,he,z),this.terrain&&!t.freezeElevation&&this._updateElevation(ue),this._applyUpdatedTransform(a),this._fireMoveEvents(n)}),(()=>{this.terrain&&t.freezeElevation&&this._finalizeElevation(),this._afterEase(n)}),t),this}isEasing(){return!!this._easeFrameId}stop(){return this._stop()}_stop(t,n){var a;if(this._easeFrameId&&(this._cancelRenderFrame(this._easeFrameId),delete this._easeFrameId,delete this._onEaseFrame),this._onEaseEnd){let c=this._onEaseEnd;delete this._onEaseEnd,c.call(this,n)}return t||(a=this.handlers)===null||a===void 0||a.stop(!1),this}_ease(t,n,a){a.animate===!1||a.duration===0?(t(1),n()):(this._easeStart=Xe(),this._easeOptions=a,this._onEaseFrame=t,this._onEaseEnd=n,this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback))}_normalizeBearing(t,n){t=p.X(t,-180,180);let a=Math.abs(t-n);return Math.abs(t-360-n)MapLibre'};class Ui{constructor(t=Xs){this._toggleAttribution=()=>{this._container.classList.contains("maplibregl-compact")&&(this._container.classList.contains("maplibregl-compact-show")?(this._container.setAttribute("open",""),this._container.classList.remove("maplibregl-compact-show")):(this._container.classList.add("maplibregl-compact-show"),this._container.removeAttribute("open")))},this._updateData=n=>{!n||n.sourceDataType!=="metadata"&&n.sourceDataType!=="visibility"&&n.dataType!=="style"&&n.type!=="terrain"||this._updateAttributions()},this._updateCompact=()=>{this._map.getCanvasContainer().offsetWidth<=640||this._compact?this._compact===!1?this._container.setAttribute("open",""):this._container.classList.contains("maplibregl-compact")||this._container.classList.contains("maplibregl-attrib-empty")||(this._container.setAttribute("open",""),this._container.classList.add("maplibregl-compact","maplibregl-compact-show")):(this._container.setAttribute("open",""),this._container.classList.contains("maplibregl-compact")&&this._container.classList.remove("maplibregl-compact","maplibregl-compact-show"))},this._updateCompactMinimize=()=>{this._container.classList.contains("maplibregl-compact")&&this._container.classList.contains("maplibregl-compact-show")&&this._container.classList.remove("maplibregl-compact-show")},this.options=t}getDefaultPosition(){return"bottom-right"}onAdd(t){return this._map=t,this._compact=this.options.compact,this._container=pe.create("details","maplibregl-ctrl maplibregl-ctrl-attrib"),this._compactButton=pe.create("summary","maplibregl-ctrl-attrib-button",this._container),this._compactButton.addEventListener("click",this._toggleAttribution),this._setElementTitle(this._compactButton,"ToggleAttribution"),this._innerContainer=pe.create("div","maplibregl-ctrl-attrib-inner",this._container),this._updateAttributions(),this._updateCompact(),this._map.on("styledata",this._updateData),this._map.on("sourcedata",this._updateData),this._map.on("terrain",this._updateData),this._map.on("resize",this._updateCompact),this._map.on("drag",this._updateCompactMinimize),this._container}onRemove(){this._container.remove(),this._map.off("styledata",this._updateData),this._map.off("sourcedata",this._updateData),this._map.off("terrain",this._updateData),this._map.off("resize",this._updateCompact),this._map.off("drag",this._updateCompactMinimize),this._map=void 0,this._compact=void 0,this._attribHTML=void 0}_setElementTitle(t,n){let a=this._map._getUIString(`AttributionControl.${n}`);t.title=a,t.setAttribute("aria-label",a)}_updateAttributions(){if(!this._map.style)return;let t=[];if(this.options.customAttribution&&(Array.isArray(this.options.customAttribution)?t=t.concat(this.options.customAttribution.map((c=>typeof c!="string"?"":c))):typeof this.options.customAttribution=="string"&&t.push(this.options.customAttribution)),this._map.style.stylesheet){let c=this._map.style.stylesheet;this.styleOwner=c.owner,this.styleId=c.id}let n=this._map.style.tileManagers;for(let c in n){let f=n[c];if(f.used||f.usedForTerrain){let y=f.getSource();y.attribution&&!t.includes(y.attribution)&&t.push(y.attribution)}}t=t.filter((c=>String(c).trim())),t.sort(((c,f)=>c.length-f.length)),t=t.filter(((c,f)=>{for(let y=f+1;y{let n=this._container.children;if(n.length){let a=n[0];this._map.getCanvasContainer().offsetWidth<=640||this._compact?this._compact!==!1&&a.classList.add("maplibregl-compact"):a.classList.remove("maplibregl-compact")}},this.options=t}getDefaultPosition(){return"bottom-left"}onAdd(t){var n;this._map=t,this._compact=(n=this.options)===null||n===void 0?void 0:n.compact,this._container=pe.create("div","maplibregl-ctrl");let a=pe.create("a","maplibregl-ctrl-logo");return a.target="_blank",a.rel="noopener nofollow",a.href="https://maplibre.org/",a.setAttribute("aria-label",this._map._getUIString("LogoControl.Title")),a.setAttribute("rel","noopener nofollow"),this._container.appendChild(a),this._container.style.display="block",this._map.on("resize",this._updateCompact),this._updateCompact(),this._container}onRemove(){this._container.remove(),this._map.off("resize",this._updateCompact),this._map=void 0,this._compact=void 0}}class au{constructor(){this._queue=[],this._id=0,this._cleared=!1,this._currentlyRunning=!1}add(t){let n=++this._id;return this._queue.push({callback:t,id:n,cancelled:!1}),n}remove(t){let n=this._currentlyRunning,a=n?this._queue.concat(n):this._queue;for(let c of a)if(c.id===t)return void(c.cancelled=!0)}run(t=0){if(this._currentlyRunning)throw new Error("Attempting to run(), but is already running.");let n=this._currentlyRunning=this._queue;this._queue=[];for(let a of n)if(!a.cancelled&&(a.callback(t),this._cleared))break;this._cleared=!1,this._currentlyRunning=!1}clear(){this._currentlyRunning&&(this._cleared=!0),this._queue=[]}}var lu=p.aS([{name:"a_pos3d",type:"Int16",components:3}]);class cu extends p.E{constructor(t){super(),this._lastTilesetChange=Xe(),this.tileManager=t,this._tiles={},this._renderableTilesKeys=[],this._sourceTileCache={},this.minzoom=0,this.maxzoom=22,this.deltaZoom=1,this.tileSize=t._source.tileSize*2**this.deltaZoom,t.usedForTerrain=!0,t.tileSize=this.tileSize}destruct(){this.tileManager.usedForTerrain=!1,this.tileManager.tileSize=null}getSource(){return this.tileManager._source}update(t,n){this.tileManager.update(t,n),this._renderableTilesKeys=[];let a={};for(let c of rn(t,{tileSize:this.tileSize,minzoom:this.minzoom,maxzoom:this.maxzoom,reparseOverscaled:!1,terrain:n,calculateTileZoom:this.tileManager._source.calculateTileZoom}))a[c.key]=!0,this._renderableTilesKeys.push(c.key),this._tiles[c.key]||(c.terrainRttPosMatrix32f=new Float64Array(16),p.c7(c.terrainRttPosMatrix32f,0,p.a6,p.a6,0,0,1),this._tiles[c.key]=new kn(c,this.tileSize),this._lastTilesetChange=Xe());for(let c in this._tiles)a[c]||delete this._tiles[c]}freeRtt(t){for(let n in this._tiles){let a=this._tiles[n];(!t||a.tileID.equals(t)||a.tileID.isChildOf(t)||t.isChildOf(a.tileID))&&(a.rtt=[])}}getRenderableTiles(){return this._renderableTilesKeys.map((t=>this.getTileByID(t)))}getTileByID(t){return this._tiles[t]}getTerrainCoords(t,n){return n?this._getTerrainCoordsForTileRanges(t,n):this._getTerrainCoordsForRegularTile(t)}_getTerrainCoordsForRegularTile(t){let n={};for(let a of this._renderableTilesKeys){let c=this._tiles[a].tileID,f=t.clone(),y=p.bj();if(c.canonical.equals(t.canonical))p.c7(y,0,p.a6,p.a6,0,0,1);else if(c.canonical.isChildOf(t.canonical)){let x=c.canonical.z-t.canonical.z,w=c.canonical.x-(c.canonical.x>>x<>x<>x;p.c7(y,0,S,S,0,0,1),p.Q(y,y,[-w*S,-P*S,0])}else{if(!t.canonical.isChildOf(c.canonical))continue;{let x=t.canonical.z-c.canonical.z,w=t.canonical.x-(t.canonical.x>>x<>x<>x;p.c7(y,0,p.a6,p.a6,0,0,1),p.Q(y,y,[w*S,P*S,0]),p.S(y,y,[1/2**x,1/2**x,0])}}f.terrainRttPosMatrix32f=new Float32Array(y),n[a]=f}return n}_getTerrainCoordsForTileRanges(t,n){let a={};for(let c of this._renderableTilesKeys){let f=this._tiles[c].tileID;if(!this._isWithinTileRanges(f,n))continue;let y=t.clone(),x=p.bj();if(f.canonical.z===t.canonical.z){let w=t.canonical.x-f.canonical.x+t.wrap*(1<t.canonical.z){let w=f.canonical.z-t.canonical.z,P=f.canonical.x-(f.canonical.x>>w<>w<>w),C=t.canonical.y-(f.canonical.y>>w),z=p.a6>>w;p.c7(x,0,z,z,0,0,1),p.Q(x,x,[-P*z+E*p.a6,-S*z+C*p.a6,0])}else{let w=t.canonical.z-f.canonical.z,P=t.canonical.x-(t.canonical.x>>w<>w<>w)-f.canonical.x,C=(t.canonical.y>>w)-f.canonical.y,z=p.a6<f.maxzoom&&(y=f.maxzoom),y=f.minzoom&&!x?.dem;)x=this.findTileInCaches(t.scaledTo(y--).key);return x}findTileInCaches(t){let n=this.tileManager.getTileByID(t);return n||(n=this.tileManager._outOfViewCache.getByKey(t),n)}anyTilesAfterTime(t=Date.now()){return this._lastTilesetChange>=t}_isWithinTileRanges(t,n){let a=n[t.canonical.z];return!!a&&(t.wrap>a.minWrap||t.wrap=a.minTileXWrapped&&t.canonical.x<=a.maxTileXWrapped&&t.canonical.y>=a.minTileY&&t.canonical.y<=a.maxTileY)}}class Jo{constructor(t,n,a){this._meshCache={},this.painter=t,this.tileManager=new cu(n),this.options=a,this.exaggeration=typeof a.exaggeration=="number"?a.exaggeration:1,this.qualityFactor=2,this.meshSize=128,this._demMatrixCache={},this.coordsIndex=[],this._coordsTextureSize=1024}destroy(){this._fbo&&(this._fbo.destroy(),this._fbo=null),this._fboCoordsTexture&&(this._fboCoordsTexture.destroy(),this._fboCoordsTexture=null),this._fboDepthTexture&&(this._fboDepthTexture.destroy(),this._fboDepthTexture=null),this._emptyDemTexture&&(this._emptyDemTexture.destroy(),this._emptyDemTexture=null),this._emptyDepthTexture&&(this._emptyDepthTexture.destroy(),this._emptyDepthTexture=null),this._coordsTexture&&(this._coordsTexture.destroy(),this._coordsTexture=null);for(let t in this._meshCache)this._meshCache[t].destroy();this._meshCache={},this.tileManager.destruct()}getDEMElevation(t,n,a,c=p.a6){var f;let y=t.normalizeCoordinates(n,a,c);if(!y)return 0;let x=this.getTerrainData(y.tileID),w=(f=x.tile)===null||f===void 0?void 0:f.dem;if(!w)return 0;let P=p.cC([],[y.x/c*p.a6,y.y/c*p.a6],x.u_terrain_matrix),S=[P[0]*w.dim,P[1]*w.dim],E=Math.floor(S[0]),C=Math.floor(S[1]),z=S[0]-E,B=S[1]-C;return w.get(E,C)*(1-z)*(1-B)+w.get(E+1,C)*z*(1-B)+w.get(E,C+1)*(1-z)*B+w.get(E+1,C+1)*z*B}getElevationForLngLatZoom(t,n){if(!p.cD(n,t.wrap()))return 0;let{tileID:a,mercatorX:c,mercatorY:f}=this._getOverscaledTileIDFromLngLatZoom(t,n);return this.getElevation(a,c%p.a6,f%p.a6,p.a6)}getElevationForLngLat(t,n){let a=rn(n,{maxzoom:this.tileManager.maxzoom,minzoom:this.tileManager.minzoom,tileSize:512,terrain:this}),c=0;for(let f of a)f.canonical.z>c&&(c=Math.min(f.canonical.z,this.tileManager.maxzoom));return this.getElevationForLngLatZoom(t,c)}getElevation(t,n,a,c=p.a6){return this.getDEMElevation(t,n,a,c)*this.exaggeration}getTerrainData(t){var n,a;if(!this._emptyDemTexture){let y=this.painter.context,x=new p.R({width:1,height:1},new Uint8Array(4));this._emptyDepthTexture=new p.T(y,x,y.gl.RGBA,{premultiply:!1}),this._emptyDemUnpack=[0,0,0,0],this._emptyDemTexture=new p.T(y,new p.R({width:1,height:1}),y.gl.RGBA,{premultiply:!1}),this._emptyDemTexture.bind(y.gl.NEAREST,y.gl.CLAMP_TO_EDGE),this._emptyDemMatrix=p.ap([])}let c=this.tileManager.getSourceTile(t,!0);if(c?.dem&&(!c.demTexture||c.needsTerrainPrepare)){let y=this.painter.context;c.demTexture=this.painter.getTileTexture(c.dem.stride),c.demTexture?c.demTexture.update(c.dem.getPixels(),{premultiply:!1}):c.demTexture=new p.T(y,c.dem.getPixels(),y.gl.RGBA,{premultiply:!1}),c.demTexture.bind(y.gl.NEAREST,y.gl.CLAMP_TO_EDGE),c.needsTerrainPrepare=!1}let f=c&&c.toString()+c.tileID.key+t.key;if(f&&!this._demMatrixCache[f]){let y=this.tileManager.getSource().maxzoom,x=t.canonical.z-c.tileID.canonical.z;t.overscaledZ>t.canonical.z&&(t.canonical.z>=y?x=t.canonical.z-y:p.w("cannot calculate elevation if elevation maxzoom > source.maxzoom"));let w=t.canonical.x-(t.canonical.x>>x<>x<>8<<4|f>>8,n[y+3]=0;let a=new p.R({width:this._coordsTextureSize,height:this._coordsTextureSize},new Uint8Array(n.buffer)),c=new p.T(t,a,t.gl.RGBA,{premultiply:!1});return c.bind(t.gl.NEAREST,t.gl.CLAMP_TO_EDGE),this._coordsTexture=c,c}pointCoordinate(t){this.painter.maybeDrawDepth(!0),this.painter.maybeDrawCoords();let n=new Uint8Array(4),a=this.painter.context,c=a.gl,f=Math.round(t.x*this.painter.pixelRatio/devicePixelRatio),y=Math.round(t.y*this.painter.pixelRatio/devicePixelRatio),x=Math.round(this.painter.height/devicePixelRatio);a.bindFramebuffer.set(this.getFramebuffer("coords").framebuffer),c.readPixels(f,x-y-1,1,1,c.RGBA,c.UNSIGNED_BYTE,n),a.bindFramebuffer.set(null);let w=n[0]+(n[2]>>4<<8),P=n[1]+((15&n[2])<<8),S=this.coordsIndex[255-n[3]],E=S&&this.tileManager.getTileByID(S);if(!E)return null;let C=this._coordsTextureSize,z=(1<0,c=a&&t.canonical.y===0,f=a&&t.canonical.y===(1<t.id!==n)),this._recentlyUsed.push(t.id)}stampObject(t){t.stamp=++this._stamp}getOrCreateFreeObject(){for(let n of this._recentlyUsed)if(!this._objects[n].inUse)return this._objects[n];if(this._objects.length>=this._size)throw new Error("No free RenderPool available, call freeAllObjects() required!");let t=this._createObject(this._objects.length);return this._objects.push(t),t}freeObject(t){t.inUse=!1}freeAllObjects(){for(let t of this._objects)this.freeObject(t)}isFull(){return!(this._objects.length!t.inUse))===!1}}let ht={background:!0,fill:!0,line:!0,raster:!0,hillshade:!0,"color-relief":!0};class sh{constructor(t,n){this.painter=t,this.terrain=n,this.pool=new mt(t.context,30,n.tileManager.tileSize*n.qualityFactor)}destruct(){this.pool.destruct()}getTexture(t){return this.pool.getObjectForId(t.rtt[this._stacks.length-1].id).texture}prepareForRender(t,n){var a,c,f;this._stacks=[],this._prevType=null,this._rttTiles=[],this._renderableTiles=this.terrain.tileManager.getRenderableTiles(),this._renderableLayerIds=t._order.filter((y=>!t._layers[y].isHidden(n))),this._coordsAscending={};for(let y in t.tileManagers){this._coordsAscending[y]={};let x=t.tileManagers[y].getVisibleCoordinates(),w=t.tileManagers[y].getSource(),P=w instanceof Ar?w.terrainTileRanges:null;for(let S of x){let E=this.terrain.tileManager.getTerrainCoords(S,P);for(let C in E)(f=this._coordsAscending[y])[C]||(f[C]=[]),this._coordsAscending[y][C].push(E[C])}}this._rttFingerprints={};for(let y of t._order){let x=t._layers[y],w=x.source;if(ht[x.type]&&!this._rttFingerprints[w]){this._rttFingerprints[w]={};let P=(c=(a=t.tileManagers[w])===null||a===void 0?void 0:a.getState().revision)!==null&&c!==void 0?c:0;for(let S in this._coordsAscending[w])this._rttFingerprints[w][S]=`${this._coordsAscending[w][S].map((E=>E.key)).sort().join()}#${P}`}}for(let y of this._renderableTiles)for(let x in this._rttFingerprints){let w=this._rttFingerprints[x][y.tileID.key];w&&w!==y.rttFingerprint[x]&&(y.rtt=[])}}renderLayer(t,n){if(t.isHidden(this.painter.transform.zoom))return!1;let a=Object.assign(Object.assign({},n),{isRenderingToTexture:!0}),c=t.type,f=this.painter,y=this._renderableLayerIds[this._renderableLayerIds.length-1]===t.id;if(ht[c]&&(this._prevType&&ht[this._prevType]||this._stacks.push([]),this._prevType=c,this._stacks[this._stacks.length-1].push(t.id),!y))return!0;if(ht[this._prevType]||ht[c]&&y){this._prevType=c;let x=this._stacks.length-1,w=this._stacks[x]||[];for(let P of this._renderableTiles){if(this.pool.isFull()&&(_l(this.painter,this.terrain,this._rttTiles,a),this._rttTiles=[],this.pool.freeAllObjects()),this._rttTiles.push(P),P.rtt[x]){let E=this.pool.getObjectForId(P.rtt[x].id);if(E.stamp===P.rtt[x].stamp){this.pool.useObject(E);continue}}let S=this.pool.getOrCreateFreeObject();this.pool.useObject(S),this.pool.stampObject(S),P.rtt[x]={id:S.id,stamp:S.stamp},f.context.bindFramebuffer.set(S.fbo.framebuffer),f.context.clear({color:p.bo.transparent,stencil:0}),f.currentStencilSource=void 0;for(let E of w){let C=f.style._layers[E],z=C.source?this._coordsAscending[C.source][P.tileID.key]:[P.tileID];f.context.viewport.set([0,0,S.fbo.width,S.fbo.height]),f._renderTileClippingMasks(C,z,!0),f.renderLayer(f,f.style.tileManagers[C.source],C,z,a),C.source&&(P.rttFingerprint[C.source]=this._rttFingerprints[C.source][P.tileID.key])}}return _l(this.painter,this.terrain,this._rttTiles,a),this._rttTiles=[],this.pool.freeAllObjects(),ht[c]}return!1}}let Qo={"AttributionControl.ToggleAttribution":"Toggle attribution","AttributionControl.MapFeedback":"Map feedback","FullscreenControl.Enter":"Enter fullscreen","FullscreenControl.Exit":"Exit fullscreen","GeolocateControl.FindMyLocation":"Find my location","GeolocateControl.LocationNotAvailable":"Location not available","LogoControl.Title":"MapLibre logo","Map.Title":"Map","Marker.Title":"Map marker","NavigationControl.ResetBearing":"Drag to rotate map, click to reset north","NavigationControl.ZoomIn":"Zoom in","NavigationControl.ZoomOut":"Zoom out","Popup.Close":"Close popup","ScaleControl.Feet":"ft","ScaleControl.Meters":"m","ScaleControl.Kilometers":"km","ScaleControl.Miles":"mi","ScaleControl.NauticalMiles":"nm","GlobeControl.Enable":"Enable globe","GlobeControl.Disable":"Disable globe","TerrainControl.Enable":"Enable terrain","TerrainControl.Disable":"Disable terrain","CooperativeGesturesHandler.WindowsHelpText":"Use Ctrl + scroll to zoom the map","CooperativeGesturesHandler.MacHelpText":"Use \u2318 + scroll to zoom the map","CooperativeGesturesHandler.MobileHelpText":"Use two fingers to move the map"},Ys=Te,Ks={hash:!1,interactive:!0,bearingSnap:7,zoomSnap:0,attributionControl:Xs,maplibreLogo:!1,refreshExpiredTiles:!0,canvasContextAttributes:{antialias:!1,preserveDrawingBuffer:!1,powerPreference:"high-performance",failIfMajorPerformanceCaveat:!1,desynchronized:!1,contextType:void 0},scrollZoom:!0,minZoom:-2,maxZoom:22,minPitch:0,maxPitch:60,boxZoom:!0,dragRotate:!0,dragPan:!0,keyboard:!0,doubleClickZoom:!0,touchZoomRotate:!0,touchPitch:!0,cooperativeGestures:!1,trackResize:!0,center:[0,0],elevation:0,zoom:0,bearing:0,pitch:0,roll:0,renderWorldCopies:!0,maxTileCacheSize:null,maxTileCacheZoomLevels:p.c.MAX_TILE_CACHE_ZOOM_LEVELS,transformRequest:null,transformCameraUpdate:null,transformConstrain:null,fadeDuration:300,crossSourceCollisions:!0,clickTolerance:3,localIdeographFontFamily:"sans-serif",pitchWithRotate:!0,rollEnabled:!1,reduceMotion:void 0,validateStyle:!0,maxCanvasSize:[4096,4096],cancelPendingTileRequestsWhileZooming:!0,centerClampedToGround:!0,experimentalZoomLevelsToOverscale:void 0,anisotropicFilterPitch:20},Js=class extends oh{get _ownerWindow(){var u,t;return((t=(u=this._container)===null||u===void 0?void 0:u.ownerDocument)===null||t===void 0?void 0:t.defaultView)||window}constructor(u){var t,n,a;let c=Object.assign(Object.assign(Object.assign({},Ks),u),{canvasContextAttributes:Object.assign(Object.assign({},Ks.canvasContextAttributes),u.canvasContextAttributes)});if(c.minZoom!=null&&c.maxZoom!=null&&c.minZoom>c.maxZoom)throw new Error("maxZoom must be greater than or equal to minZoom");if(c.minPitch!=null&&c.maxPitch!=null&&c.minPitch>c.maxPitch)throw new Error("maxPitch must be greater than or equal to minPitch");if(c.minPitch!=null&&c.minPitch<0)throw new Error("minPitch must be greater than or equal to 0");if(c.maxPitch!=null&&c.maxPitch>180)throw new Error("maxPitch must be less than or equal to 180");let f=new ln,y=new cn;c.minZoom!==void 0&&f.setMinZoom(c.minZoom),c.maxZoom!==void 0&&f.setMaxZoom(c.maxZoom),c.minPitch!==void 0&&f.setMinPitch(c.minPitch),c.maxPitch!==void 0&&f.setMaxPitch(c.maxPitch),c.renderWorldCopies!==void 0&&f.setRenderWorldCopies(c.renderWorldCopies),c.transformConstrain!==null&&f.setConstrainOverride(c.transformConstrain),super(f,y,{bearingSnap:c.bearingSnap,zoomSnap:c.zoomSnap}),this._idleTriggered=!1,this._crossFadingFactor=1,this._renderTaskQueue=new au,this._controls=[],this._mapId=p.ad(),this._lostContextStyle={style:null,images:null},this._contextLost=w=>{if(w.preventDefault(),this._frameRequest&&(this._frameRequest.abort(),this._frameRequest=null),this.painter.destroy(),this._lostContextStyle=this._getStyleAndImages(),this.style){for(let P of Object.values(this.style._layers))if(P.type==="custom"&&console.warn(`Custom layer with id '${P.id}' cannot be restored after WebGL context loss. You will need to re-add it manually after context restoration.`),P._listeners)for(let[S]of Object.entries(P._listeners))console.warn(`Custom layer with id '${P.id}' had event listeners for event '${S}' which cannot be restored after WebGL context loss. You will need to re-add them manually after context restoration.`);this.style.destroy(),this.style=null,this.fire(new p.n("webglcontextlost",{originalEvent:w}))}else this.fire(new p.n("webglcontextlost",{originalEvent:w}))},this._contextRestored=w=>{this._lostContextStyle.style&&this.setStyle(this._lostContextStyle.style,{diff:!1}),this._lostContextStyle.images&&this.style&&(this.style.imageManager.images=this._lostContextStyle.images),this._lostContextStyle={style:null,images:null},this._setupPainter(),this.resize(),this._update(),this._resizeInternal(),this.fire(new p.n("webglcontextrestored",{originalEvent:w}))},this._onMapScroll=w=>{if(w.target===this._container)return this._container.scrollTop=0,this._container.scrollLeft=0,!1},this._onWindowOnline=()=>{this._update()},this._interactive=c.interactive,this._maxTileCacheSize=c.maxTileCacheSize,this._maxTileCacheZoomLevels=c.maxTileCacheZoomLevels,this._canvasContextAttributes=Object.assign({},c.canvasContextAttributes),this._trackResize=c.trackResize===!0,this._bearingSnap=c.bearingSnap,this._zoomSnap=c.zoomSnap,this._centerClampedToGround=c.centerClampedToGround,this._refreshExpiredTiles=c.refreshExpiredTiles===!0,this._fadeDuration=c.fadeDuration,this._crossSourceCollisions=c.crossSourceCollisions===!0,this._collectResourceTiming=c.collectResourceTiming===!0,this._locale=Object.assign(Object.assign({},Qo),c.locale),this._clickTolerance=c.clickTolerance,this._overridePixelRatio=c.pixelRatio,this._maxCanvasSize=c.maxCanvasSize,this._zoomLevelsToOverscale=c.experimentalZoomLevelsToOverscale,this.transformCameraUpdate=c.transformCameraUpdate,this.transformConstrain=c.transformConstrain,this.cancelPendingTileRequestsWhileZooming=c.cancelPendingTileRequestsWhileZooming===!0,this.setAnisotropicFilterPitch(c.anisotropicFilterPitch),c.reduceMotion!==void 0&&(qt.prefersReducedMotion=c.reduceMotion),this._imageQueueHandle=Ii.addThrottleControl((()=>this.isMoving())),this._requestManager=new kt(c.transformRequest),this._container=this._resolveContainer(c.container),c.maxBounds&&this.setMaxBounds(c.maxBounds),this._setupContainer(),this._setupPainter(),this.on("move",(()=>this._update(!1))),this.on("moveend",(()=>this._update(!1))),this.on("zoom",(()=>this._update(!0))),this.on("terrain",(()=>{this.painter.terrainFacilitator.depthDirty=!0,this._update(!0)})),this.once("idle",(()=>this._idleTriggered=!0)),typeof window<"u"&&(this._ownerWindow.addEventListener("online",this._onWindowOnline,!1),this._setupResizeObserver()),this.handlers=new ui(this,c),this._hash=c.hash?new Zo(typeof c.hash=="string"&&c.hash||void 0).addTo(this):void 0,!((t=this._hash)===null||t===void 0)&&t._onHashChange()||(this.jumpTo({center:c.center,elevation:c.elevation,zoom:c.zoom,bearing:c.bearing,pitch:c.pitch,roll:c.roll}),c.bounds&&(this.resize(),this.fitBounds(c.bounds,p.e({},c.fitBoundsOptions,{duration:0}))));let x=typeof c.style=="string"||((a=(n=c.style)===null||n===void 0?void 0:n.projection)===null||a===void 0?void 0:a.type)!=="globe";this.resize(null,x),this._localIdeographFontFamily=c.localIdeographFontFamily,this._validateStyle=c.validateStyle,c.style&&this.setStyle(c.style,{localIdeographFontFamily:c.localIdeographFontFamily}),c.attributionControl&&this.addControl(new Ui(typeof c.attributionControl=="boolean"?void 0:c.attributionControl)),c.maplibreLogo&&this.addControl(new Cl,c.logoPosition),this.on("style.load",(()=>{if(x||this._resizeTransform(),this.transform.unmodified){let w=p.V(this.style.stylesheet,["center","zoom","bearing","pitch","roll"]);this.jumpTo(w)}})),this.on("data",(w=>{this._update(w.dataType==="style"),this.fire(new p.n(`${w.dataType}data`,w))})),this.on("dataloading",(w=>{this.fire(new p.n(`${w.dataType}dataloading`,w))})),this.on("dataabort",(w=>{this.fire(new p.n("sourcedataabort",w))}))}_getMapId(){return this._mapId}setGlobalStateProperty(u,t){return this.style.setGlobalStateProperty(u,t),this._update(!0)}getGlobalState(){return this.style.getGlobalState()}addControl(u,t){if(t===void 0&&(t=u.getDefaultPosition?u.getDefaultPosition():"top-right"),!u?.onAdd)return this.fire(new p.l(new Error("Invalid argument to map.addControl(). Argument must be a control with onAdd and onRemove methods.")));let n=u.onAdd(this);this._controls.push(u);let a=this._controlPositions[t];return t.includes("bottom")?a.insertBefore(n,a.firstChild):a.appendChild(n),this}removeControl(u){if(!u?.onRemove)return this.fire(new p.l(new Error("Invalid argument to map.removeControl(). Argument must be a control with onAdd and onRemove methods.")));let t=this._controls.indexOf(u);return t>-1&&this._controls.splice(t,1),u.onRemove(this),this}hasControl(u){return this._controls.includes(u)}coveringTiles(u){return rn(this.transform,u)}calculateCameraOptionsFromTo(u,t,n,a){return a==null&&this.terrain&&(a=this.terrain.getElevationForLngLat(n,this.transform)),super.calculateCameraOptionsFromTo(u,t,n,a)}resize(u,t=!0){if(this._lostContextStyle.style!==null)return this;this._resizeInternal(t);let n=!this._moving;return n&&(this.stop(),this.fire(new p.n("movestart",u)).fire(new p.n("move",u))),this.fire(new p.n("resize",u)),n&&this.fire(new p.n("moveend",u)),this}_resizeInternal(u=!0){let[t,n]=this._containerDimensions(),a=this._getClampedPixelRatio(t,n);if(this._resizeCanvas(t,n,a),this.painter.resize(t,n,a),this.painter.overLimit()){let c=this.painter.context.gl;this._maxCanvasSize=[c.drawingBufferWidth,c.drawingBufferHeight];let f=this._getClampedPixelRatio(t,n);this._resizeCanvas(t,n,f),this.painter.resize(t,n,f)}this._resizeTransform(u)}_resizeTransform(u=!0){var t;let[n,a]=this._containerDimensions();this.transform.resize(n,a,u),(t=this._requestedCameraState)===null||t===void 0||t.resize(n,a,u)}_getClampedPixelRatio(u,t){let{0:n,1:a}=this._maxCanvasSize,c=this.getPixelRatio(),f=u*c,y=t*c;return Math.min(f>n?n/f:1,y>a?a/y:1)*c}getPixelRatio(){var u;return(u=this._overridePixelRatio)!==null&&u!==void 0?u:devicePixelRatio}setPixelRatio(u){this._overridePixelRatio=u,this.resize()}getBounds(){return this.transform.getBounds()}getMaxBounds(){return this.transform.getMaxBounds()}setMaxBounds(u){return this.transform.setMaxBounds(Re.convert(u)),this._update()}setMinZoom(u){if((u=u??-2)>=-2&&u<=this.transform.maxZoom){let t=this.transform.zoom,n=this._getTransformForUpdate();return n.setMinZoom(u),this._applyUpdatedTransform(n),this._update(),t!==this.transform.zoom&&this.fire(new p.n("zoomstart")).fire(new p.n("zoom")).fire(new p.n("zoomend")).fire(new p.n("movestart")).fire(new p.n("move")).fire(new p.n("moveend")),this}throw new Error("minZoom must be between -2 and the current maxZoom, inclusive")}getMinZoom(){return this.transform.minZoom}setMaxZoom(u){if((u=u??22)>=this.transform.minZoom){let t=this.transform.zoom,n=this._getTransformForUpdate();return n.setMaxZoom(u),this._applyUpdatedTransform(n),this._update(),t!==this.transform.zoom&&this.fire(new p.n("zoomstart")).fire(new p.n("zoom")).fire(new p.n("zoomend")).fire(new p.n("movestart")).fire(new p.n("move")).fire(new p.n("moveend")),this}throw new Error("maxZoom must be greater than the current minZoom")}getMaxZoom(){return this.transform.maxZoom}setMinPitch(u){if((u=u??0)<0)throw new Error("minPitch must be greater than or equal to 0");if(u>=0&&u<=this.transform.maxPitch){let t=this.transform.pitch,n=this._getTransformForUpdate();return n.setMinPitch(u),this._applyUpdatedTransform(n),this._update(),t!==this.transform.pitch&&this.fire(new p.n("pitchstart")).fire(new p.n("pitch")).fire(new p.n("pitchend")).fire(new p.n("movestart")).fire(new p.n("move")).fire(new p.n("moveend")),this}throw new Error("minPitch must be between 0 and the current maxPitch, inclusive")}getMinPitch(){return this.transform.minPitch}setMaxPitch(u){if((u=u??60)>180)throw new Error("maxPitch must be less than or equal to 180");if(u>=this.transform.minPitch){let t=this.transform.pitch,n=this._getTransformForUpdate();return n.setMaxPitch(u),this._applyUpdatedTransform(n),this._update(),t!==this.transform.pitch&&this.fire(new p.n("pitchstart")).fire(new p.n("pitch")).fire(new p.n("pitchend")).fire(new p.n("movestart")).fire(new p.n("move")).fire(new p.n("moveend")),this}throw new Error("maxPitch must be greater than the current minPitch")}getMaxPitch(){return this.transform.maxPitch}getAnisotropicFilterPitch(){return this._anisotropicFilterPitch}setAnisotropicFilterPitch(u){if((u=u??20)>180)throw new Error("anisotropicFilterPitch must be less than or equal to 180");if(u<0)throw new Error("anisotropicFilterPitch must be greater than or equal to 0");return this._anisotropicFilterPitch=u,this._update()}getRenderWorldCopies(){return this.transform.renderWorldCopies}setRenderWorldCopies(u){return this.transform.setRenderWorldCopies(u),this._update()}setTransformConstrain(u){return this.transform.setConstrainOverride(u),this._update()}project(u){return this.transform.locationToScreenPoint(p.W.convert(u),this.style&&this.terrain)}unproject(u){return this.transform.screenPointToLocation(p.P.convert(u),this.terrain)}isMoving(){var u;return this._moving||((u=this.handlers)===null||u===void 0?void 0:u.isMoving())}isZooming(){var u;return this._zooming||((u=this.handlers)===null||u===void 0?void 0:u.isZooming())}isRotating(){var u;return this._rotating||((u=this.handlers)===null||u===void 0?void 0:u.isRotating())}_createDelegatedListener(u,t,n){if(u==="mouseenter"||u==="mouseover"){let a=!1;return{layers:t,listener:n,delegates:{mousemove:f=>{let y=t.filter((w=>this.getLayer(w))),x=y.length!==0?this.queryRenderedFeatures(f.point,{layers:y}):[];x.length?a||(a=!0,n.call(this,new zi(u,this,f.originalEvent,{features:x}))):a=!1},mouseout:()=>{a=!1}}}}if(u==="mouseleave"||u==="mouseout"){let a=!1;return{layers:t,listener:n,delegates:{mousemove:y=>{let x=t.filter((w=>this.getLayer(w)));(x.length!==0?this.queryRenderedFeatures(y.point,{layers:x}):[]).length?a=!0:a&&(a=!1,n.call(this,new zi(u,this,y.originalEvent)))},mouseout:y=>{a&&(a=!1,n.call(this,new zi(u,this,y.originalEvent)))}}}}{let a=c=>{let f=t.filter((x=>this.getLayer(x))),y=f.length!==0?this.queryRenderedFeatures(c.point,{layers:f}):[];y.length&&(c.features=y,n.call(this,c),delete c.features)};return{layers:t,listener:n,delegates:{[u]:a}}}}_saveDelegatedListener(u,t){var n;this._delegatedListeners||(this._delegatedListeners={}),(n=this._delegatedListeners)[u]||(n[u]=[]),this._delegatedListeners[u].push(t)}_removeDelegatedListener(u,t,n){var a;if(!(!((a=this._delegatedListeners)===null||a===void 0)&&a[u]))return;let c=this._delegatedListeners[u];for(let f=0;ft.includes(x)))){for(let x in y.delegates)this.off(x,y.delegates[x]);return void c.splice(f,1)}}}on(u,t,n){if(n===void 0)return super.on(u,t);let a=typeof t=="string"?[t]:t,c=this._createDelegatedListener(u,a,n);this._saveDelegatedListener(u,c);for(let f in c.delegates)this.on(f,c.delegates[f]);return{unsubscribe:()=>{this._removeDelegatedListener(u,a,n)}}}once(u,t,n){if(n===void 0)return super.once(u,t);let a=typeof t=="string"?[t]:t,c=this._createDelegatedListener(u,a,n);for(let f in c.delegates){let y=c.delegates[f];c.delegates[f]=(...x)=>{this._removeDelegatedListener(u,a,n),y(...x)}}this._saveDelegatedListener(u,c);for(let f in c.delegates)this.once(f,c.delegates[f]);return this}off(u,t,n){return n===void 0?super.off(u,t):(this._removeDelegatedListener(u,typeof t=="string"?[t]:t,n),this)}queryRenderedFeatures(u,t){if(!this.style)return[];let n,a=u instanceof p.P||Array.isArray(u),c=a?u:[[0,0],[this.transform.width,this.transform.height]];if(t||(t=(a?{}:u)||{}),c instanceof p.P||typeof c[0]=="number")n=[p.P.convert(c)];else{let f=p.P.convert(c[0]),y=p.P.convert(c[1]);n=[f,new p.P(y.x,f.y),y,new p.P(f.x,y.y),f]}return this.style.queryRenderedFeatures(n,t,this.transform)}querySourceFeatures(u,t){return this.style.querySourceFeatures(u,t)}setStyle(u,t){return(t=p.e({},{localIdeographFontFamily:this._localIdeographFontFamily,validate:this._validateStyle},t)).diff!==!1&&t.localIdeographFontFamily===this._localIdeographFontFamily&&this.style&&u?(this._diffStyle(u,t),this):(this._localIdeographFontFamily=t.localIdeographFontFamily,this._updateStyle(u,t))}setTransformRequest(u){return this._requestManager.setTransformRequest(u),this}_getUIString(u){let t=this._locale[u];if(t==null)throw new Error(`Missing UI string '${u}'`);return t}_updateStyle(u,t){var n,a,c;if((n=this._diffStyleRequest)===null||n===void 0||n.abort(),this._diffStyleRequest=null,t.transformStyle&&this.style&&!this.style._loaded)return void this.style.once("style.load",(()=>this._updateStyle(u,t)));let f=this.style&&t.transformStyle?this.style.serialize():void 0;return this.style&&(this.style.setEventedParent(null),this.style._remove(!u)),u?(this.style=new pn(this,t||{}),this.style.setEventedParent(this,{style:this.style}),typeof u=="string"?this.style.loadURL(u,t,f):this.style.loadJSON(u,t,f),this):(this._frameRequest&&(this._frameRequest.abort(),this._frameRequest=null),(c=(a=this.style)===null||a===void 0?void 0:a.projection)===null||c===void 0||c.destroy(),delete this.style,this)}_lazyInitEmptyStyle(){this.style||(this.style=new pn(this,{}),this.style.setEventedParent(this,{style:this.style}),this.style.loadEmpty())}_diffStyle(u,t){return p._(this,void 0,void 0,(function*(){var n;if((n=this._diffStyleRequest)===null||n===void 0||n.abort(),typeof u=="string"){let a=u;this._diffStyleRequest=new AbortController;let c=this._diffStyleRequest;try{let f=yield this._requestManager.transformRequest(a,"Style");if(c.signal.aborted)return void(this._diffStyleRequest=null);let y=yield p.k(f,c);this._diffStyleRequest=null,this._updateDiff(y.data,t)}catch(f){this._diffStyleRequest=null,p.$(f)||this.fire(new p.l(p.d(f)))}}else typeof u=="object"&&(this._diffStyleRequest=null,this._updateDiff(u,t))}))}_updateDiff(u,t){try{this.style.setState(u,t)&&this._update(!0)}catch(n){p.w(`Unable to perform style diff: ${p.d(n).message}. Rebuilding the style from scratch.`),this._updateStyle(u,t)}}getStyle(){if(this.style)return this.style.serialize()}_getStyleAndImages(){return this.style?{style:this.style.serialize(),images:this.style.imageManager.cloneImages()}:{style:null,images:{}}}isStyleLoaded(){if(this.style)return this.style.loaded();p.w("There is no style added to the map.")}addSource(u,t){return this._lazyInitEmptyStyle(),this.style.addSource(u,t),this._update(!0)}isSourceLoaded(u){var t;let n=(t=this.style)===null||t===void 0?void 0:t.tileManagers[u];if(n!==void 0)return n.loaded();this.fire(new p.l(new Error(`There is no tile manager with ID '${u}'`)))}setTerrain(u){if(this.style._checkLoaded(),this._terrainDataCallback&&this.style.off("data",this._terrainDataCallback),u){let t=this.style.tileManagers[u.source];if(!t)throw new Error(`cannot load terrain, because there exists no source with ID: ${u.source}`);this.terrain===null&&t.reload();for(let n in this.style._layers){let a=this.style._layers[n];a.type==="hillshade"&&a.source===u.source&&p.w("You are using the same source for a hillshade layer and for 3D terrain. Please consider using two separate sources to improve rendering quality."),a.type==="color-relief"&&a.source===u.source&&p.w("You are using the same source for a color-relief layer and for 3D terrain. Please consider using two separate sources to improve rendering quality.")}this.terrain=new Jo(this.painter,t,u),this.painter.renderToTexture=new sh(this.painter,this.terrain),this.transform.setMinElevationForCurrentTile(this.terrain.getMinTileElevationForLngLatZoom(this.transform.center,this.transform.tileZoom)),this.transform.setElevation(this.terrain.getElevationForLngLatZoom(this.transform.center,this.transform.tileZoom)),this._terrainDataCallback=n=>{var a;n.dataType==="style"?this.terrain.tileManager.freeRtt():n.dataType==="source"&&n.tile&&(n.sourceId!==u.source||this._elevationFreeze||(this.transform.setMinElevationForCurrentTile(this.terrain.getMinTileElevationForLngLatZoom(this.transform.center,this.transform.tileZoom)),this._centerClampedToGround&&this.transform.setElevation(this.terrain.getElevationForLngLatZoom(this.transform.center,this.transform.tileZoom))),((a=n.source)===null||a===void 0?void 0:a.type)==="image"?this.terrain.tileManager.freeRtt():this.terrain.tileManager.freeRtt(n.tile.tileID))},this.style.on("data",this._terrainDataCallback)}else this.terrain&&this.terrain.destroy(),this.terrain=null,this.painter.renderToTexture&&this.painter.renderToTexture.destruct(),this.painter.renderToTexture=null,this.transform.setMinElevationForCurrentTile(0),this._centerClampedToGround&&this.transform.setElevation(0);return this.fire(new p.n("terrain",{terrain:u})),this}getTerrain(){var u,t;return(t=(u=this.terrain)===null||u===void 0?void 0:u.options)!==null&&t!==void 0?t:null}areTilesLoaded(){var u;let t=(u=this.style)===null||u===void 0?void 0:u.tileManagers;for(let n of Object.values(t))if(!n.areTilesLoaded())return!1;return!0}removeSource(u){return this.style.removeSource(u),this._update(!0)}getSource(u){return this.style.getSource(u)}setSourceTileLodParams(u,t,n){if(n){let a=this.getSource(n);if(!a)throw new Error(`There is no source with ID "${n}", cannot set LOD parameters`);a.calculateTileZoom=Oa(Math.max(1,u),Math.max(1,t))}else for(let a in this.style.tileManagers)this.style.tileManagers[a].getSource().calculateTileZoom=Oa(Math.max(1,u),Math.max(1,t));return this._update(!0),this}refreshTiles(u,t){let n=this.style.tileManagers[u];if(!n)throw new Error(`There is no tile manager with ID "${u}", cannot refresh tile`);t===void 0?n.reload(!0):n.refreshTiles(t.map((a=>new p.aa(a.z,a.x,a.y))))}addImage(u,t,n={}){let{pixelRatio:a=1,sdf:c=!1,stretchX:f,stretchY:y,content:x,textFitWidth:w,textFitHeight:P}=n;if(this._lazyInitEmptyStyle(),!(t instanceof HTMLImageElement||p.b(t))){if(t.width===void 0||t.height===void 0)return this.fire(new p.l(new Error("Invalid arguments to map.addImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, or object with `width`, `height`, and `data` properties with the same format as `ImageData`")));{let{width:S,height:E,data:C}=t,z=t;return this.style.addImage(u,{data:new p.R({width:S,height:E},new Uint8Array(C)),pixelRatio:a,stretchX:f,stretchY:y,content:x,textFitWidth:w,textFitHeight:P,sdf:c,version:0,userImage:z}),z.onAdd&&z.onAdd(this,u),this}}{let{width:S,height:E,data:C}=qt.getImageData(t);this.style.addImage(u,{data:new p.R({width:S,height:E},C),pixelRatio:a,stretchX:f,stretchY:y,content:x,textFitWidth:w,textFitHeight:P,sdf:c,version:0})}}updateImage(u,t){let n=this.style.getImage(u);if(!n)return this.fire(new p.l(new Error("The map has no image with that id. If you are adding a new image use `map.addImage(...)` instead.")));let a=t instanceof HTMLImageElement||p.b(t)?qt.getImageData(t):t,{width:c,height:f,data:y}=a;if(c===void 0||f===void 0)return this.fire(new p.l(new Error("Invalid arguments to map.updateImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, or object with `width`, `height`, and `data` properties with the same format as `ImageData`")));if(c!==n.data.width||f!==n.data.height)return this.fire(new p.l(new Error("The width and height of the updated image must be that same as the previous version of the image")));let x=!(t instanceof HTMLImageElement||p.b(t));return n.data.replace(y,x),this.style.updateImage(u,n),this}getImage(u){return this.style.getImage(u)}hasImage(u){return u?!!this.style.getImage(u):(this.fire(new p.l(new Error("Missing required image id"))),!1)}removeImage(u){this.style.removeImage(u)}loadImage(u){return p._(this,void 0,void 0,(function*(){return Ii.getImage(yield this._requestManager.transformRequest(u,"Image"),new AbortController)}))}listImages(){return this.style.listImages()}addLayer(u,t){return this._lazyInitEmptyStyle(),this.style.addLayer(u,t),this._update(!0)}moveLayer(u,t){return this.style.moveLayer(u,t),this._update(!0)}removeLayer(u){return this.style.removeLayer(u),this._update(!0)}getLayer(u){return this.style.getLayer(u)}getLayersOrder(){return this.style.getLayersOrder()}setLayerZoomRange(u,t,n){return this.style.setLayerZoomRange(u,t,n),this._update(!0)}setFilter(u,t,n={}){return this.style.setFilter(u,t,n),this._update(!0)}getFilter(u){return this.style.getFilter(u)}setPaintProperty(u,t,n,a={}){return this.style.setPaintProperty(u,t,n,a),this._update(!0)}getPaintProperty(u,t){return this.style.getPaintProperty(u,t)}setLayoutProperty(u,t,n,a={}){return this.style.setLayoutProperty(u,t,n,a),this._update(!0)}getLayoutProperty(u,t){return this.style.getLayoutProperty(u,t)}setGlyphs(u,t={}){return this._lazyInitEmptyStyle(),this.style.setGlyphs(u,t),this._update(!0)}getGlyphs(){return this.style.getGlyphsUrl()}addSprite(u,t,n={}){return this._lazyInitEmptyStyle(),this.style.addSprite(u,t,n,(a=>{a||this._update(!0)})),this}removeSprite(u){return this._lazyInitEmptyStyle(),this.style.removeSprite(u),this._update(!0)}getSprite(){return this.style.getSprite()}setSprite(u,t={}){return this._lazyInitEmptyStyle(),this.style.setSprite(u,t,(n=>{n||this._update(!0)})),this}setLight(u,t={}){return this._lazyInitEmptyStyle(),this.style.setLight(u,t),this._update(!0)}getLight(){return this.style.getLight()}setSky(u,t={}){return this._lazyInitEmptyStyle(),this.style.setSky(u,t),this._update(!0)}getSky(){return this.style.getSky()}setFeatureState(u,t){return this.style.setFeatureState(u,t),this._update()}removeFeatureState(u,t){return this.style.removeFeatureState(u,t),this._update()}getFeatureState(u){return this.style.getFeatureState(u)}getContainer(){return this._container}getCanvasContainer(){return this._canvasContainer}getCanvas(){return this._canvas}_containerDimensions(){let u=0,t=0;return this._container&&(u=this._container.clientWidth||400,t=this._container.clientHeight||300),[u,t]}_setupResizeObserver(){var u;let t=!1,n=vl((c=>{this._trackResize&&!this._removed&&(this.resize(c),this.redraw())}),50),a=(u=this._ownerWindow.ResizeObserver)!==null&&u!==void 0?u:ResizeObserver;this._resizeObserver=new a((c=>{t?n(c):t=!0})),this._resizeObserver.observe(this._container)}_resolveContainer(u){if(typeof u=="string"){let t=document.getElementById(u);if(!t)throw new Error(`Container '${u}' not found.`);return t}if(u instanceof HTMLElement||u&&typeof u=="object"&&u.nodeType===1)return u;throw new Error("Invalid type: 'container' must be a String or HTMLElement.")}_setupContainer(){let u=this._container;u.classList.add("maplibregl-map");let t=this._canvasContainer=pe.create("div","maplibregl-canvas-container",u);this._interactive&&t.classList.add("maplibregl-interactive"),this._canvas=pe.create("canvas","maplibregl-canvas",t),this._canvas.addEventListener("webglcontextlost",this._contextLost,!1),this._canvas.addEventListener("webglcontextrestored",this._contextRestored,!1),this._canvas.setAttribute("tabindex",this._interactive?"0":"-1"),this._canvas.setAttribute("aria-label",this._getUIString("Map.Title")),this._canvas.setAttribute("role","region");let n=this._containerDimensions(),a=this._getClampedPixelRatio(n[0],n[1]);this._resizeCanvas(n[0],n[1],a);let c=this._controlContainer=pe.create("div","maplibregl-control-container",u),f=this._controlPositions={};for(let y of["top-left","top-right","bottom-left","bottom-right"])f[y]=pe.create("div",`maplibregl-ctrl-${y} `,c);this._container.addEventListener("scroll",this._onMapScroll,!1)}_resizeCanvas(u,t,n){this._canvas.width=Math.floor(n*u),this._canvas.height=Math.floor(n*t),this._canvas.style.width=`${u}px`,this._canvas.style.height=`${t}px`}_setupPainter(){let u=Object.assign(Object.assign({},this._canvasContextAttributes),{alpha:!0,depth:!0,stencil:!0,premultipliedAlpha:!0}),t=null;this._canvas.addEventListener("webglcontextcreationerror",(a=>{t={requestedAttributes:u},a&&(t.statusMessage=a.statusMessage,t.type=a.type)}),{once:!0});let n=null;if(n=this._canvasContextAttributes.contextType?this._canvas.getContext(this._canvasContextAttributes.contextType,u):this._canvas.getContext("webgl2",u)||this._canvas.getContext("webgl",u),!n){let a="Failed to initialize WebGL";throw t?(t.message=a,new Error(JSON.stringify(t))):new Error(a)}this.painter=new $o(n,this.transform)}migrateProjection(u,t){super.migrateProjection(u,t),this.painter.transform=u,this.fire(new p.n("projectiontransition",{newProjection:this.style.projection.name}))}loaded(){return!this._styleDirty&&!this._sourcesDirty&&!!this.style&&this.style.loaded()}_update(u){var t;return!((t=this.style)===null||t===void 0)&&t._loaded?(this._styleDirty||(this._styleDirty=u),this._sourcesDirty=!0,this.triggerRepaint(),this):this}_requestRenderFrame(u){return this._update(),this._renderTaskQueue.add(u)}_cancelRenderFrame(u){this._renderTaskQueue.remove(u)}_render(u){var t,n,a,c,f,y;let x=this._idleTriggered?this._fadeDuration:0,w=((t=this.style.projection)===null||t===void 0?void 0:t.transitionState)>0;if(this.painter.context.setDirty(),this.painter.setBaseState(),this._renderTaskQueue.run(u),this._removed)return;let P=!1;if(this.style&&this._styleDirty){this._styleDirty=!1;let C=this.transform.zoom,z=Xe();this.style.zoomHistory.update(C,z);let B=new p.J(C,{now:z,fadeDuration:x,zoomHistory:this.style.zoomHistory,transition:this.style.getTransition()}),N=B.crossFadingFactor();N===1&&N===this._crossFadingFactor||(P=!0,this._crossFadingFactor=N),this.style.update(B)}let S=((n=this.style.projection)===null||n===void 0?void 0:n.transitionState)>0!==w;(a=this.style.projection)===null||a===void 0||a.setErrorQueryLatitudeDegrees(this.transform.center.lat),this.transform.setTransitionState((c=this.style.projection)===null||c===void 0?void 0:c.transitionState,(f=this.style.projection)===null||f===void 0?void 0:f.latitudeErrorCorrectionRadians),this.style&&(this._sourcesDirty||S)&&(this._sourcesDirty=!1,this.style._updateSources(this.transform)),this.terrain?(this.terrain.tileManager.update(this.transform,this.terrain),this.transform.setMinElevationForCurrentTile(this.terrain.getMinTileElevationForLngLatZoom(this.transform.center,this.transform.tileZoom)),!this._elevationFreeze&&this._centerClampedToGround&&this.transform.setElevation(this.terrain.getElevationForLngLatZoom(this.transform.center,this.transform.tileZoom))):(this.transform.setMinElevationForCurrentTile(0),this._centerClampedToGround&&this.transform.setElevation(0)),this._placementDirty=(y=this.style)===null||y===void 0?void 0:y._updatePlacement(this.transform,this.showCollisionBoxes,x,this._crossSourceCollisions,S),this.painter.render(this.style,{showTileBoundaries:this.showTileBoundaries,showOverdrawInspector:this._showOverdrawInspector,rotating:this.isRotating(),zooming:this.isZooming(),moving:this.isMoving(),fadeDuration:x,showPadding:this.showPadding,anisotropicFilterPitch:this.getAnisotropicFilterPitch()}),this.fire(new p.n("render")),this.loaded()&&!this._loaded&&(this._loaded=!0,this.fire(new p.n("load"))),this.style&&(this.style.hasTransitions()||P)&&(this._styleDirty=!0),this.style&&!this._placementDirty&&this.style._releaseSymbolFadeTiles();let E=this._sourcesDirty||this._styleDirty||this._placementDirty;return E||this._repaint?this.triggerRepaint():!this.isMoving()&&this.loaded()&&this.fire(new p.n("idle")),!this._loaded||this._fullyLoaded||E||(this._fullyLoaded=!0),this}redraw(){return this.style&&(this._frameRequest&&(this._frameRequest.abort(),this._frameRequest=null),this._render(0)),this}remove(){var u,t;this._hash&&this._hash.remove();for(let a of this._controls)a.onRemove(this);this._controls=[],this._frameRequest&&(this._frameRequest.abort(),this._frameRequest=null),this._renderTaskQueue.clear(),(u=this._diffStyleRequest)===null||u===void 0||u.abort(),this.painter.destroy(),this.handlers.destroy(),delete this.handlers,this.setStyle(null),typeof window<"u"&&this._ownerWindow.removeEventListener("online",this._onWindowOnline,!1),Ii.removeThrottleControl(this._imageQueueHandle),(t=this._resizeObserver)===null||t===void 0||t.disconnect();let n=this.painter.context.gl.getExtension("WEBGL_lose_context");n?.loseContext&&n.loseContext(),this._canvas.removeEventListener("webglcontextrestored",this._contextRestored,!1),this._canvas.removeEventListener("webglcontextlost",this._contextLost,!1),this._canvasContainer.remove(),this._controlContainer.remove(),this._container.removeEventListener("scroll",this._onMapScroll,!1),this._container.classList.remove("maplibregl-map"),this._removed=!0,this.fire(new p.n("remove"))}triggerRepaint(){this.style&&!this._frameRequest&&(this._frameRequest=new AbortController,qt.frame(this._frameRequest,(u=>{this._frameRequest=null;try{this._render(u)}catch(t){if(!p.$(t)&&!(function(n){return n.message===js})(t))throw t}}),(()=>{}),this._ownerWindow))}get showTileBoundaries(){return!!this._showTileBoundaries}set showTileBoundaries(u){this._showTileBoundaries!==u&&(this._showTileBoundaries=u,this._update())}get showPadding(){return!!this._showPadding}set showPadding(u){this._showPadding!==u&&(this._showPadding=u,this._update())}get showCollisionBoxes(){return!!this._showCollisionBoxes}set showCollisionBoxes(u){this._showCollisionBoxes!==u&&(this._showCollisionBoxes=u,u?this.style._generateCollisionBoxes():this._update())}get showOverdrawInspector(){return!!this._showOverdrawInspector}set showOverdrawInspector(u){this._showOverdrawInspector!==u&&(this._showOverdrawInspector=u,this._update())}get repaint(){return!!this._repaint}set repaint(u){this._repaint!==u&&(this._repaint=u,this.triggerRepaint())}get vertices(){return!!this._vertices}set vertices(u){this._vertices=u,this._update()}get version(){return Ys}getCameraTargetElevation(){return this.transform.elevation}getProjection(){return this.style.getProjection()}setProjection(u){return this._lazyInitEmptyStyle(),this.style.setProjection(u),this._update(!0)}},Al={showCompass:!0,showZoom:!0,visualizePitch:!1,visualizeRoll:!0};class es{constructor(t,n,a=!1){this.mousedown=f=>{this.startMove(f,pe.mousePos(this.element,f)),window.addEventListener("mousemove",this.mousemove),window.addEventListener("mouseup",this.mouseup)},this.mousemove=f=>{this.move(f,pe.mousePos(this.element,f))},this.mouseup=f=>{this._rotatePitchHandler.dragEnd(f),this.offTemp()},this.touchstart=f=>{f.targetTouches.length!==1?this.reset():(this._startPos=this._lastPos=pe.touchPos(this.element,f.targetTouches)[0],this.startMove(f,this._startPos),window.addEventListener("touchmove",this.touchmove,{passive:!1}),window.addEventListener("touchend",this.touchend))},this.touchmove=f=>{f.targetTouches.length!==1?this.reset():(this._lastPos=pe.touchPos(this.element,f.targetTouches)[0],this.move(f,this._lastPos))},this.touchend=f=>{f.targetTouches.length===0&&this._startPos&&this._lastPos&&this._startPos.dist(this._lastPos){this._rotatePitchHandler.reset(),delete this._startPos,delete this._lastPos,this.offTemp()},this._clickTolerance=10,this.element=n;let c=new bl;this._rotatePitchHandler=new mr({clickTolerance:3,move:(f,y)=>{let x=n.getBoundingClientRect(),w=new p.P((x.bottom-x.top)/2,(x.right-x.left)/2);return{bearingDelta:p.cx(new p.P(f.x,y.y),y,w),pitchDelta:a?-.5*(y.y-f.y):void 0}},moveStateManager:c,enable:!0,assignEvents:()=>{}}),this.map=t,n.addEventListener("mousedown",this.mousedown),n.addEventListener("touchstart",this.touchstart,{passive:!1}),n.addEventListener("touchcancel",this.reset)}startMove(t,n){this._rotatePitchHandler.dragStart(t,n),pe.disableDrag()}move(t,n){let a=this.map,{bearingDelta:c,pitchDelta:f}=this._rotatePitchHandler.dragMove(t,n)||{};c&&a.setBearing(a.getBearing()+c),f&&a.setPitch(a.getPitch()+f)}off(){let t=this.element;t.removeEventListener("mousedown",this.mousedown),t.removeEventListener("touchstart",this.touchstart),window.removeEventListener("touchmove",this.touchmove),window.removeEventListener("touchend",this.touchend),t.removeEventListener("touchcancel",this.reset),this.offTemp()}offTemp(){pe.enableDrag(),window.removeEventListener("mousemove",this.mousemove),window.removeEventListener("mouseup",this.mouseup),window.removeEventListener("touchmove",this.touchmove),window.removeEventListener("touchend",this.touchend)}}let _r;function Qs(u,t,n,a=!1){if(a||!n.getCoveringTilesDetailsProvider().allowWorldCopies())return u?.wrap();let c=new p.W(u.lng,u.lat);if(u=new p.W(u.lng,u.lat),t){let f=new p.W(u.lng-360,u.lat),y=new p.W(u.lng+360,u.lat),x=n.locationToScreenPoint(u).distSqr(t);n.locationToScreenPoint(f).distSqr(t)180;){let f=n.locationToScreenPoint(u);if(f.x>=0&&f.y>=0&&f.x<=n.width&&f.y<=n.height)break;u.lng>n.center.lng?u.lng-=360:u.lng+=360}return u.lng!==c.lng&&n.isPointOnMapSurface(n.locationToScreenPoint(u))?u:c}let ts={center:"translate(-50%,-50%)",top:"translate(-50%,0)","top-left":"translate(0,0)","top-right":"translate(-100%,0)",bottom:"translate(-50%,-100%)","bottom-left":"translate(0,-100%)","bottom-right":"translate(-100%,-100%)",left:"translate(0,-50%)",right:"translate(-100%,-50%)"};function ea(u,t,n){let a=u.classList;for(let c in ts)a.remove(`maplibregl-${n}-anchor-${c}`);a.add(`maplibregl-${n}-anchor-${t}`)}class is extends p.E{constructor(t){if(super(),this._onClick=n=>{this.fire(new p.n("click",{originalEvent:n}))},this._onKeyPress=n=>{n.code!=="Space"&&n.code!=="Enter"||this.togglePopup()},this._onMapClick=n=>{let a=n.originalEvent.target,c=this._element;this._popup&&(a===c||c.contains(a))&&this.togglePopup()},this._update=n=>{if(!this._map)return;let a=this._map.loaded()&&!this._map.isMoving();(n?.type==="terrain"||n?.type==="render"&&!a)&&this._map.once("render",this._update),this._lngLat=Qs(this._lngLat,this._flatPos,this._map.transform),this._flatPos=this._pos=this._map.project(this._lngLat)._add(this._offset),this._map.terrain&&(this._flatPos=this._map.transform.locationToScreenPoint(this._lngLat)._add(this._offset));let c="";this._rotationAlignment==="viewport"||this._rotationAlignment==="auto"?c=`rotateZ(${this._rotation}deg)`:this._rotationAlignment==="map"&&(c=`rotateZ(${this._rotation-this._map.getBearing()}deg)`);let f="";this._pitchAlignment==="viewport"||this._pitchAlignment==="auto"?f="rotateX(0deg)":this._pitchAlignment==="map"&&(f=`rotateX(${this._map.getPitch()}deg)`),this._subpixelPositioning||n&&n.type!=="moveend"||(this._pos=this._pos.round()),this._element.style.transform=`${ts[this._anchor]} translate(${this._pos.x}px, ${this._pos.y}px) ${f} ${c}`,qt.frameAsync(new AbortController,this._map._ownerWindow).then((()=>{this._updateOpacity(n?.type==="moveend")})).catch((()=>{}))},this._onMove=n=>{if(!this._isDragging){let a=this._clickTolerance||this._map._clickTolerance;this._isDragging=n.point.dist(this._pointerdownPos)>=a}this._isDragging&&(this._pos=n.point.sub(this._positionDelta),this._lngLat=this._map.unproject(this._pos),this.setLngLat(this._lngLat),this._element.style.pointerEvents="none",this._state==="pending"&&(this._state="active",this.fire(new p.n("dragstart"))),this.fire(new p.n("drag")))},this._onUp=()=>{this._element.style.pointerEvents="auto",this._positionDelta=null,this._pointerdownPos=null,this._isDragging=!1,this._map.off("mousemove",this._onMove),this._map.off("touchmove",this._onMove),this._state==="active"&&this.fire(new p.n("dragend")),this._state="inactive"},this._addDragHandler=n=>{this._element.contains(n.originalEvent.target)&&(n.preventDefault(),this._positionDelta=n.point.sub(this._pos).add(this._offset),this._pointerdownPos=n.point,this._state="pending",this._map.on("mousemove",this._onMove),this._map.on("touchmove",this._onMove),this._map.once("mouseup",this._onUp),this._map.once("touchend",this._onUp))},this._anchor=t?.anchor||"center",this._color=t?.color||"#3FB1CE",this._scale=t?.scale||1,this._draggable=t?.draggable||!1,this._clickTolerance=t?.clickTolerance||0,this._subpixelPositioning=t?.subpixelPositioning||!1,this._isDragging=!1,this._state="inactive",this._rotation=t?.rotation||0,this._rotationAlignment=t?.rotationAlignment||"auto",this._pitchAlignment=t?.pitchAlignment&&t.pitchAlignment!=="auto"?t.pitchAlignment:this._rotationAlignment,this.setOpacity(t?.opacity,t?.opacityWhenCovered),t?.element)this._element=t.element,this._offset=p.P.convert(t?.offset||[0,0]);else{this._defaultMarker=!0,this._element=pe.create("div");let n=pe.createNS("http://www.w3.org/2000/svg","svg"),a=41,c=27;n.setAttributeNS(null,"display","block"),n.setAttributeNS(null,"height",`${a}px`),n.setAttributeNS(null,"width",`${c}px`),n.setAttributeNS(null,"viewBox",`0 0 ${c} ${a}`);let f=pe.createNS("http://www.w3.org/2000/svg","g");f.setAttributeNS(null,"stroke","none"),f.setAttributeNS(null,"stroke-width","1"),f.setAttributeNS(null,"fill","none"),f.setAttributeNS(null,"fill-rule","evenodd");let y=pe.createNS("http://www.w3.org/2000/svg","g");y.setAttributeNS(null,"fill-rule","nonzero");let x=pe.createNS("http://www.w3.org/2000/svg","g");x.setAttributeNS(null,"transform","translate(3.0, 29.0)"),x.setAttributeNS(null,"fill","#000000");let w=[{rx:"10.5",ry:"5.25002273"},{rx:"10.5",ry:"5.25002273"},{rx:"9.5",ry:"4.77275007"},{rx:"8.5",ry:"4.29549936"},{rx:"7.5",ry:"3.81822308"},{rx:"6.5",ry:"3.34094679"},{rx:"5.5",ry:"2.86367051"},{rx:"4.5",ry:"2.38636864"}];for(let j of w){let $=pe.createNS("http://www.w3.org/2000/svg","ellipse");$.setAttributeNS(null,"opacity","0.04"),$.setAttributeNS(null,"cx","10.5"),$.setAttributeNS(null,"cy","5.80029008"),$.setAttributeNS(null,"rx",j.rx),$.setAttributeNS(null,"ry",j.ry),x.appendChild($)}let P=pe.createNS("http://www.w3.org/2000/svg","g");P.setAttributeNS(null,"fill",this._color);let S=pe.createNS("http://www.w3.org/2000/svg","path");S.setAttributeNS(null,"d","M27,13.5 C27,19.074644 20.250001,27.000002 14.75,34.500002 C14.016665,35.500004 12.983335,35.500004 12.25,34.500002 C6.7499993,27.000002 0,19.222562 0,13.5 C0,6.0441559 6.0441559,0 13.5,0 C20.955844,0 27,6.0441559 27,13.5 Z"),P.appendChild(S);let E=pe.createNS("http://www.w3.org/2000/svg","g");E.setAttributeNS(null,"opacity","0.25"),E.setAttributeNS(null,"fill","#000000");let C=pe.createNS("http://www.w3.org/2000/svg","path");C.setAttributeNS(null,"d","M13.5,0 C6.0441559,0 0,6.0441559 0,13.5 C0,19.222562 6.7499993,27 12.25,34.5 C13,35.522727 14.016664,35.500004 14.75,34.5 C20.250001,27 27,19.074644 27,13.5 C27,6.0441559 20.955844,0 13.5,0 Z M13.5,1 C20.415404,1 26,6.584596 26,13.5 C26,15.898657 24.495584,19.181431 22.220703,22.738281 C19.945823,26.295132 16.705119,30.142167 13.943359,33.908203 C13.743445,34.180814 13.612715,34.322738 13.5,34.441406 C13.387285,34.322738 13.256555,34.180814 13.056641,33.908203 C10.284481,30.127985 7.4148684,26.314159 5.015625,22.773438 C2.6163816,19.232715 1,15.953538 1,13.5 C1,6.584596 6.584596,1 13.5,1 Z"),E.appendChild(C);let z=pe.createNS("http://www.w3.org/2000/svg","g");z.setAttributeNS(null,"transform","translate(6.0, 7.0)"),z.setAttributeNS(null,"fill","#FFFFFF");let B=pe.createNS("http://www.w3.org/2000/svg","g");B.setAttributeNS(null,"transform","translate(8.0, 8.0)");let N=pe.createNS("http://www.w3.org/2000/svg","circle");N.setAttributeNS(null,"fill","#000000"),N.setAttributeNS(null,"opacity","0.25"),N.setAttributeNS(null,"cx","5.5"),N.setAttributeNS(null,"cy","5.5"),N.setAttributeNS(null,"r","5.4999962");let G=pe.createNS("http://www.w3.org/2000/svg","circle");G.setAttributeNS(null,"fill","#FFFFFF"),G.setAttributeNS(null,"cx","5.5"),G.setAttributeNS(null,"cy","5.5"),G.setAttributeNS(null,"r","5.4999962"),B.appendChild(N),B.appendChild(G),y.appendChild(x),y.appendChild(P),y.appendChild(E),y.appendChild(z),y.appendChild(B),n.appendChild(y),n.setAttributeNS(null,"height",a*this._scale+"px"),n.setAttributeNS(null,"width",c*this._scale+"px"),this._element.appendChild(n),this._offset=p.P.convert(t?.offset||[0,-14])}if(this._element.classList.add("maplibregl-marker"),this._element.addEventListener("dragstart",(n=>{n.preventDefault()})),this._element.addEventListener("mousedown",(n=>{n.preventDefault()})),ea(this._element,this._anchor,"marker"),t?.className)for(let n of t.className.split(" "))this._element.classList.add(n);this._popup=null}addTo(t){return this.remove(),this._map=t,this._element.hasAttribute("aria-label")||this._element.setAttribute("aria-label",t._getUIString("Marker.Title")),this._element.hasAttribute("role")||this._element.setAttribute("role","button"),t.getCanvasContainer().appendChild(this._element),t.on("move",this._update),t.on("moveend",this._update),t.on("terrain",this._update),t.on("projectiontransition",this._update),this._element.addEventListener("click",this._onClick),this.setDraggable(this._draggable),this._update(),this._map.on("click",this._onMapClick),this}remove(){return this._opacityTimeout&&(clearTimeout(this._opacityTimeout),delete this._opacityTimeout),this._map&&(this._map.off("click",this._onMapClick),this._map.off("move",this._update),this._map.off("moveend",this._update),this._map.off("terrain",this._update),this._map.off("projectiontransition",this._update),this._map.off("mousedown",this._addDragHandler),this._map.off("touchstart",this._addDragHandler),this._map.off("mouseup",this._onUp),this._map.off("touchend",this._onUp),this._map.off("mousemove",this._onMove),this._map.off("touchmove",this._onMove),delete this._map),this._element.removeEventListener("click",this._onClick),this._element.remove(),this._popup&&this._popup.remove(),this}getLngLat(){return this._lngLat}setLngLat(t){return this._lngLat=p.W.convert(t),this._pos=null,this._popup&&this._popup.setLngLat(this._lngLat),this._update(),this}getElement(){return this._element}setPopup(t){if(this._popup&&(this._popup.remove(),this._popup=null,this._element.removeEventListener("keypress",this._onKeyPress),this._originalTabIndex||this._element.removeAttribute("tabindex")),t){if(!("offset"in t.options)){let c=Math.abs(13.5)/Math.SQRT2;t.options.offset=this._defaultMarker?{top:[0,0],"top-left":[0,0],"top-right":[0,0],bottom:[0,-38.1],"bottom-left":[c,-1*(38.1-13.5+c)],"bottom-right":[-c,-1*(38.1-13.5+c)],left:[13.5,-1*(38.1-13.5)],right:[-13.5,-1*(38.1-13.5)]}:this._offset}this._popup=t,this._originalTabIndex=this._element.getAttribute("tabindex"),this._originalTabIndex||this._element.setAttribute("tabindex","0"),this._element.addEventListener("keypress",this._onKeyPress)}return this}setSubpixelPositioning(t){return this._subpixelPositioning=t,this}getPopup(){return this._popup}togglePopup(){let t=this._popup;return this._element.style.opacity===this._opacityWhenCovered?this:t?(t.isOpen()?t.remove():(t.setLngLat(this._lngLat),t.addTo(this._map)),this):this}_updateOpacity(t=!1){var n,a;let c=(n=this._map)===null||n===void 0?void 0:n.terrain,f=this._map.transform.isLocationOccluded(this._lngLat);if(!c||f){let z=f?this._opacityWhenCovered:this._opacity;return void(this._element.style.opacity!==z&&(this._element.style.opacity=z,this._element.classList.toggle("maplibregl-marker-covered",f)))}if(t)this._opacityTimeout=null;else{if(this._opacityTimeout)return;this._opacityTimeout=setTimeout((()=>{this._opacityTimeout=null}),100)}let y=this._map,x=y.terrain.depthAtPoint(this._pos),w=y.terrain.getElevationForLngLat(this._lngLat,y.transform);if(y.transform.lngLatToCameraDepth(this._lngLat,w)-x<.006)return this._element.style.opacity=this._opacity,void this._element.classList.remove("maplibregl-marker-covered");let P=-this._offset.y/y.transform.pixelsPerMeter,S=Math.sin(y.getPitch()*Math.PI/180)*P,E=y.terrain.depthAtPoint(new p.P(this._pos.x,this._pos.y-this._offset.y)),C=y.transform.lngLatToCameraDepth(this._lngLat,w+S)-E>.006;!((a=this._popup)===null||a===void 0)&&a.isOpen()&&C&&this._popup.remove(),this._element.style.opacity=C?this._opacityWhenCovered:this._opacity,this._element.classList.toggle("maplibregl-marker-covered",C)}getOffset(){return this._offset}setOffset(t){return this._offset=p.P.convert(t),this._update(),this}addClassName(t){this._element.classList.add(t)}removeClassName(t){this._element.classList.remove(t)}toggleClassName(t){return this._element.classList.toggle(t)}setDraggable(t){return this._draggable=!!t,this._map&&(t?(this._map.on("mousedown",this._addDragHandler),this._map.on("touchstart",this._addDragHandler)):(this._map.off("mousedown",this._addDragHandler),this._map.off("touchstart",this._addDragHandler))),this}isDraggable(){return this._draggable}setRotation(t){return this._rotation=t||0,this._update(),this}getRotation(){return this._rotation}setRotationAlignment(t){return this._rotationAlignment=t||"auto",this._update(),this}getRotationAlignment(){return this._rotationAlignment}setPitchAlignment(t){return this._pitchAlignment=t&&t!=="auto"?t:this._rotationAlignment,this._update(),this}getPitchAlignment(){return this._pitchAlignment}setOpacity(t,n){return(this._opacity===void 0||t===void 0&&n===void 0)&&(this._opacity="1",this._opacityWhenCovered="0.2"),t!==void 0&&(this._opacity=String(t)),n!==void 0&&(this._opacityWhenCovered=String(n)),this._map&&this._updateOpacity(!0),this}}let Dl={positionOptions:{enableHighAccuracy:!1,maximumAge:0,timeout:6e3},fitBoundsOptions:{maxZoom:15},trackUserLocation:!1,showAccuracyCircle:!0,showUserLocation:!0},so=0,wn=!1,zl={maxWidth:100,unit:"metric"};function rs(u,t,n){let a=n?.maxWidth||100,c=u._container.clientHeight/2,f=u._container.clientWidth/2,y=u.unproject([f-a/2,c]),x=u.unproject([f+a/2,c]),w=Math.round(u.project(x).x-u.project(y).x),P=Math.min(a,w,u._container.clientWidth),S=y.distanceTo(x);if(n?.unit==="imperial"){let E=3.2808*S;E>5280?Tn(t,P,E/5280,u._getUIString("ScaleControl.Miles")):Tn(t,P,E,u._getUIString("ScaleControl.Feet"))}else n?.unit==="nautical"?Tn(t,P,S/1852,u._getUIString("ScaleControl.NauticalMiles")):S>=1e3?Tn(t,P,S/1e3,u._getUIString("ScaleControl.Kilometers")):Tn(t,P,S,u._getUIString("ScaleControl.Meters"))}function Tn(u,t,n,a){let c=(function(f){let y=Math.pow(10,`${Math.floor(f)}`.length-1),x=f/y;return x=x>=10?10:x>=5?5:x>=3?3:x>=2?2:x>=1?1:(function(w){let P=Math.pow(10,Math.ceil(-Math.log(w)/Math.LN10));return Math.round(w*P)/P})(x),y*x})(n);u.style.width=t*(c/n)+"px",u.innerHTML=`${c} ${a}`}let Rl={closeButton:!0,closeOnClick:!0,focusAfterOpen:!0,className:"",maxWidth:"240px",subpixelPositioning:!1,locationOccludedOpacity:void 0,padding:void 0},ta=["a[href]","[tabindex]:not([tabindex='-1'])","[contenteditable]:not([contenteditable='false'])","button:not([disabled])","input:not([disabled])","select:not([disabled])","textarea:not([disabled])"].join(", ");function ia(u){if(u){if(typeof u=="number"){let t=Math.round(Math.abs(u)/Math.SQRT2);return{center:new p.P(0,0),top:new p.P(0,u),"top-left":new p.P(t,t),"top-right":new p.P(-t,t),bottom:new p.P(0,-u),"bottom-left":new p.P(t,-t),"bottom-right":new p.P(-t,-t),left:new p.P(u,0),right:new p.P(-u,0)}}if(u instanceof p.P||Array.isArray(u)){let t=p.P.convert(u);return{center:t,top:t,"top-left":t,"top-right":t,bottom:t,"bottom-left":t,"bottom-right":t,left:t,right:t}}return{center:p.P.convert(u.center||[0,0]),top:p.P.convert(u.top||[0,0]),"top-left":p.P.convert(u["top-left"]||[0,0]),"top-right":p.P.convert(u["top-right"]||[0,0]),bottom:p.P.convert(u.bottom||[0,0]),"bottom-left":p.P.convert(u["bottom-left"]||[0,0]),"bottom-right":p.P.convert(u["bottom-right"]||[0,0]),left:p.P.convert(u.left||[0,0]),right:p.P.convert(u.right||[0,0])}}return ia(new p.P(0,0))}let kl=Te;k.AJAXError=p.cG,k.EXTENT=p.a6,k.Event=p.n,k.Evented=p.E,k.LngLat=p.W,k.MercatorCoordinate=p.a7,k.Point=p.P,k.addProtocol=p.cH,k.config=p.c,k.removeProtocol=p.cI,k.AttributionControl=Ui,k.BoxZoomHandler=or,k.CanvasSource=ka,k.CooperativeGesturesHandler=Ce,k.DoubleClickZoomHandler=El,k.DragPanHandler=er,k.DragRotateHandler=Ko,k.EdgeInsets=Un,k.FullscreenControl=class extends p.E{constructor(u={}){var t;super(),this._onFullscreenChange=()=>{var n;let a=window.document.fullscreenElement||window.document.webkitFullscreenElement;for(;!((n=a?.shadowRoot)===null||n===void 0)&&n.fullscreenElement;)a=a.shadowRoot.fullscreenElement;a===this._container!==this._fullscreen&&this._handleFullscreenChange()},this._onClickFullscreen=()=>{this._isFullscreen()?this._exitFullscreen():this._requestFullscreen()},this._fullscreen=!1,this._pseudo=(t=u.pseudo)!==null&&t!==void 0&&t,u?.container&&(u.container instanceof HTMLElement?this._container=u.container:p.w("Full screen control 'container' must be a DOM element.")),"onfullscreenchange"in document?this._fullscreenchange="fullscreenchange":"onmozfullscreenchange"in document?this._fullscreenchange="mozfullscreenchange":"onwebkitfullscreenchange"in document?this._fullscreenchange="webkitfullscreenchange":"onmsfullscreenchange"in document&&(this._fullscreenchange="MSFullscreenChange")}onAdd(u){return this._map=u,this._container||(this._container=this._map.getContainer()),this._controlContainer=pe.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._setupUI(),this._controlContainer}onRemove(){this._controlContainer.remove(),this._map=null,window.document.removeEventListener(this._fullscreenchange,this._onFullscreenChange)}_setupUI(){let u=this._fullscreenButton=pe.create("button","maplibregl-ctrl-fullscreen",this._controlContainer);pe.create("span","maplibregl-ctrl-icon",u).setAttribute("aria-hidden","true"),u.type="button",this._updateTitle(),this._fullscreenButton.addEventListener("click",this._onClickFullscreen),window.document.addEventListener(this._fullscreenchange,this._onFullscreenChange)}_updateTitle(){let u=this._getTitle();this._fullscreenButton.setAttribute("aria-label",u),this._fullscreenButton.title=u}_getTitle(){return this._map._getUIString(this._isFullscreen()?"FullscreenControl.Exit":"FullscreenControl.Enter")}_isFullscreen(){return this._fullscreen}_handleFullscreenChange(){this._fullscreen=!this._fullscreen,this._fullscreenButton.classList.toggle("maplibregl-ctrl-shrink"),this._fullscreenButton.classList.toggle("maplibregl-ctrl-fullscreen"),this._updateTitle(),this._fullscreen?(this.fire(new p.n("fullscreenstart")),this._prevCooperativeGesturesEnabled=this._map.cooperativeGestures.isEnabled(),this._map.cooperativeGestures.disable()):(this.fire(new p.n("fullscreenend")),this._prevCooperativeGesturesEnabled&&this._map.cooperativeGestures.enable())}_exitFullscreen(){this._pseudo?this._togglePseudoFullScreen():window.document.exitFullscreen?window.document.exitFullscreen():window.document.webkitCancelFullScreen?window.document.webkitCancelFullScreen():this._togglePseudoFullScreen()}_requestFullscreen(){this._pseudo?this._togglePseudoFullScreen():this._container.requestFullscreen?this._container.requestFullscreen():this._container.webkitRequestFullscreen?this._container.webkitRequestFullscreen():this._togglePseudoFullScreen()}_togglePseudoFullScreen(){this._container.classList.toggle("maplibregl-pseudo-fullscreen"),this._handleFullscreenChange(),this._map.resize()}},k.GeoJSONSource=us,k.GeolocateControl=class extends p.E{constructor(u){super(),this._onSuccess=t=>{if(this._map){if(this._isOutOfMapMaxBounds(t))return this._setErrorState(),this.fire(new p.n("outofmaxbounds",t)),this._updateMarker(),void this._finish();if(this.options.trackUserLocation)switch(this._lastKnownPosition=t,this._watchState){case"WAITING_ACTIVE":case"ACTIVE_LOCK":case"ACTIVE_ERROR":this._watchState="ACTIVE_LOCK",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active-error"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active");break;case"BACKGROUND":case"BACKGROUND_ERROR":this._watchState="BACKGROUND",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background-error"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-background");break;default:throw new Error(`Unexpected watchState ${this._watchState}`)}this.options.showUserLocation&&this._watchState!=="OFF"&&this._updateMarker(t),this.options.trackUserLocation&&this._watchState!=="ACTIVE_LOCK"||this._updateCamera(t),this.options.showUserLocation&&this._dotElement.classList.remove("maplibregl-user-location-dot-stale"),this.fire(new p.n("geolocate",t)),this._finish()}},this._updateCamera=t=>{let n=new p.W(t.coords.longitude,t.coords.latitude),a=t.coords.accuracy,c=this._map.getBearing(),f=p.e({bearing:c},this.options.fitBoundsOptions),y=Re.fromLngLat(n,a);this._map.fitBounds(y,f,{geolocateSource:!0})},this._updateMarker=t=>{if(t){let n=new p.W(t.coords.longitude,t.coords.latitude);this._accuracyCircleMarker.setLngLat(n).addTo(this._map),this._userLocationDotMarker.setLngLat(n).addTo(this._map),this._accuracy=t.coords.accuracy,this._updateCircleRadiusIfNeeded()}else this._userLocationDotMarker.remove(),this._accuracyCircleMarker.remove()},this._onUpdate=()=>{this._updateCircleRadiusIfNeeded()},this._onError=t=>{if(this._map){if(t.code===1){this._watchState="OFF",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active-error"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background-error"),this._geolocateButton.disabled=!0;let n=this._map._getUIString("GeolocateControl.LocationNotAvailable");this._geolocateButton.title=n,this._geolocateButton.setAttribute("aria-label",n),this._geolocationWatchID!==void 0&&this._clearWatch()}else{if(t.code===3&&wn)return;this._setErrorState()}this._watchState!=="OFF"&&this.options.showUserLocation&&this._dotElement.classList.add("maplibregl-user-location-dot-stale"),this.fire(new p.n("error",t)),this._finish()}},this._finish=()=>{this._timeoutId&&clearTimeout(this._timeoutId),this._timeoutId=void 0},this._onMoveStart=t=>{if(!this._map)return;let n=t?.[0]instanceof ResizeObserverEntry;t.geolocateSource||this._watchState!=="ACTIVE_LOCK"||n||this._map.isZooming()||(this._watchState="BACKGROUND",this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this.fire(new p.n("trackuserlocationend")),this.fire(new p.n("userlocationlostfocus")))},this._setupUI=()=>{this._map&&(this._container.addEventListener("contextmenu",(t=>{t.preventDefault()})),this._geolocateButton=pe.create("button","maplibregl-ctrl-geolocate",this._container),pe.create("span","maplibregl-ctrl-icon",this._geolocateButton).setAttribute("aria-hidden","true"),this._geolocateButton.type="button",this._geolocateButton.disabled=!0)},this._finishSetupUI=t=>{if(this._map){if(t===!1){p.w("Geolocation support is not available so the GeolocateControl will be disabled.");let n=this._map._getUIString("GeolocateControl.LocationNotAvailable");this._geolocateButton.disabled=!0,this._geolocateButton.title=n,this._geolocateButton.setAttribute("aria-label",n)}else{let n=this._map._getUIString("GeolocateControl.FindMyLocation");this._geolocateButton.disabled=!1,this._geolocateButton.title=n,this._geolocateButton.setAttribute("aria-label",n)}this.options.trackUserLocation&&(this._geolocateButton.setAttribute("aria-pressed","false"),this._watchState="OFF"),this.options.showUserLocation&&(this._dotElement=pe.create("div","maplibregl-user-location-dot"),this._userLocationDotMarker=new is({element:this._dotElement}),this._circleElement=pe.create("div","maplibregl-user-location-accuracy-circle"),this._accuracyCircleMarker=new is({element:this._circleElement,pitchAlignment:"map"}),this.options.trackUserLocation&&(this._watchState="OFF"),this._map.on("zoom",this._onUpdate),this._map.on("move",this._onUpdate),this._map.on("rotate",this._onUpdate),this._map.on("pitch",this._onUpdate)),this._geolocateButton.addEventListener("click",(()=>this.trigger())),this._setup=!0,this.options.trackUserLocation&&this._map.on("movestart",this._onMoveStart)}},this.options=p.e({},Dl,u)}onAdd(u){return this._map=u,this._container=pe.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._setupUI(),(function(){return p._(this,arguments,void 0,(function*(t=!1){if(_r!==void 0&&!t)return _r;if(window.navigator.permissions===void 0)return _r=!!window.navigator.geolocation,_r;try{_r=(yield window.navigator.permissions.query({name:"geolocation"})).state!=="denied"}catch{_r=!!window.navigator.geolocation}return _r}))})().then((t=>this._finishSetupUI(t))),this._container}onRemove(){this._geolocationWatchID!==void 0&&(window.navigator.geolocation.clearWatch(this._geolocationWatchID),this._geolocationWatchID=void 0),this.options.showUserLocation&&this._userLocationDotMarker&&this._userLocationDotMarker.remove(),this.options.showAccuracyCircle&&this._accuracyCircleMarker&&this._accuracyCircleMarker.remove(),this._container.remove(),this._map.off("movestart",this._onMoveStart),this._map.off("zoom",this._onUpdate),this._map.off("move",this._onUpdate),this._map.off("rotate",this._onUpdate),this._map.off("pitch",this._onUpdate),this._map=void 0,so=0,wn=!1}_isOutOfMapMaxBounds(u){let t=this._map.getMaxBounds(),n=u.coords;return t&&(n.longitudet.getEast()||n.latitudet.getNorth())}_setErrorState(){switch(this._watchState){case"WAITING_ACTIVE":this._watchState="ACTIVE_ERROR",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active-error");break;case"ACTIVE_LOCK":this._watchState="ACTIVE_ERROR",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active-error"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting");break;case"BACKGROUND":this._watchState="BACKGROUND_ERROR",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-background-error"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting");break;case"ACTIVE_ERROR":case"BACKGROUND_ERROR":case"OFF":case void 0:break;default:throw new Error(`Unexpected watchState ${this._watchState}`)}}_updateCircleRadiusIfNeeded(){let u=this._userLocationDotMarker.getLngLat();if(!(this.options.showUserLocation&&this.options.showAccuracyCircle&&this._accuracy&&u))return;let t=this._map.project(u),n=this._map.unproject([t.x+100,t.y]),a=u.distanceTo(n)/100,c=2*this._accuracy/a;this._circleElement.style.width=`${c.toFixed(2)}px`,this._circleElement.style.height=`${c.toFixed(2)}px`}trigger(){if(!this._setup)return p.w("Geolocate control triggered before added to a map"),!1;if(this.options.trackUserLocation){switch(this._watchState){case"OFF":this._watchState="WAITING_ACTIVE",this.fire(new p.n("trackuserlocationstart"));break;case"WAITING_ACTIVE":case"ACTIVE_LOCK":case"ACTIVE_ERROR":case"BACKGROUND_ERROR":so--,wn=!1,this._watchState="OFF",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active-error"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background-error"),this.fire(new p.n("trackuserlocationend"));break;case"BACKGROUND":this._watchState="ACTIVE_LOCK",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background"),this._lastKnownPosition&&this._updateCamera(this._lastKnownPosition),this.fire(new p.n("trackuserlocationstart")),this.fire(new p.n("userlocationfocus"));break;default:throw new Error(`Unexpected watchState ${this._watchState}`)}switch(this._watchState){case"WAITING_ACTIVE":this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active");break;case"ACTIVE_LOCK":this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active");break;case"OFF":break;default:throw new Error(`Unexpected watchState ${this._watchState}`)}if(this._watchState==="OFF"&&this._geolocationWatchID!==void 0)this._clearWatch();else if(this._geolocationWatchID===void 0){let u;this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.setAttribute("aria-pressed","true"),so++,so>1?(u={maximumAge:6e5,timeout:0},wn=!0):(u=this.options.positionOptions,wn=!1),this._geolocationWatchID=window.navigator.geolocation.watchPosition(this._onSuccess,this._onError,u)}}else window.navigator.geolocation.getCurrentPosition(this._onSuccess,this._onError,this.options.positionOptions),this._timeoutId=setTimeout(this._finish,1e4);return!0}_clearWatch(){window.navigator.geolocation.clearWatch(this._geolocationWatchID),this._geolocationWatchID=void 0,this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.setAttribute("aria-pressed","false"),this.options.showUserLocation&&this._updateMarker(null)}},k.GlobeControl=class{constructor(){this._toggleProjection=()=>{var u;let t=(u=this._map.getProjection())===null||u===void 0?void 0:u.type;this._map.setProjection(t!=="mercator"&&t?{type:"mercator"}:{type:"globe"}),this._updateGlobeIcon()},this._updateGlobeIcon=()=>{var u;this._globeButton.classList.remove("maplibregl-ctrl-globe"),this._globeButton.classList.remove("maplibregl-ctrl-globe-enabled"),((u=this._map.getProjection())===null||u===void 0?void 0:u.type)==="globe"?(this._globeButton.classList.add("maplibregl-ctrl-globe-enabled"),this._globeButton.title=this._map._getUIString("GlobeControl.Disable")):(this._globeButton.classList.add("maplibregl-ctrl-globe"),this._globeButton.title=this._map._getUIString("GlobeControl.Enable"))}}onAdd(u){return this._map=u,this._container=pe.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._globeButton=pe.create("button","maplibregl-ctrl-globe",this._container),pe.create("span","maplibregl-ctrl-icon",this._globeButton).setAttribute("aria-hidden","true"),this._globeButton.type="button",this._globeButton.addEventListener("click",this._toggleProjection),this._updateGlobeIcon(),this._map.on("styledata",this._updateGlobeIcon),this._map.on("projectiontransition",this._updateGlobeIcon),this._container}onRemove(){this._container.remove(),this._map.off("styledata",this._updateGlobeIcon),this._map.off("projectiontransition",this._updateGlobeIcon),this._globeButton.removeEventListener("click",this._toggleProjection),this._map=void 0}},k.Hash=Zo,k.ImageSource=Ar,k.KeyboardHandler=ih,k.LngLatBounds=Re,k.LogoControl=Cl,k.Map=Js,k.MapLibreMap=Js,k.MapMouseEvent=zi,k.MapTouchEvent=Wo,k.MapWheelEvent=Hc,k.Marker=is,k.NavigationControl=class{constructor(u){this._updateZoomButtons=()=>{let t=this._map.getZoom(),n=t===this._map.getMaxZoom(),a=t===this._map.getMinZoom();this._zoomInButton.disabled=n,this._zoomOutButton.disabled=a,this._zoomInButton.setAttribute("aria-disabled",n.toString()),this._zoomOutButton.setAttribute("aria-disabled",a.toString())},this._rotateCompassArrow=()=>{this._compassIcon.style.transform=this.options.visualizePitch&&this.options.visualizeRoll?`scale(${1/Math.pow(Math.cos(this._map.transform.pitchInRadians),.5)}) rotateZ(${-this._map.transform.roll}deg) rotateX(${this._map.transform.pitch}deg) rotateZ(${-this._map.transform.bearing}deg)`:this.options.visualizePitch?`scale(${1/Math.pow(Math.cos(this._map.transform.pitchInRadians),.5)}) rotateX(${this._map.transform.pitch}deg) rotateZ(${-this._map.transform.bearing}deg)`:this.options.visualizeRoll?`rotate(${-this._map.transform.bearing-this._map.transform.roll}deg)`:`rotate(${-this._map.transform.bearing}deg)`},this._setButtonTitle=(t,n)=>{let a=this._map._getUIString(`NavigationControl.${n}`);t.title=a,t.setAttribute("aria-label",a)},this.options=p.e({},Al,u),this._container=pe.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._container.addEventListener("contextmenu",(t=>t.preventDefault())),this.options.showZoom&&(this._zoomInButton=this._createButton("maplibregl-ctrl-zoom-in",(t=>this._map.zoomIn({},{originalEvent:t}))),pe.create("span","maplibregl-ctrl-icon",this._zoomInButton).setAttribute("aria-hidden","true"),this._zoomOutButton=this._createButton("maplibregl-ctrl-zoom-out",(t=>this._map.zoomOut({},{originalEvent:t}))),pe.create("span","maplibregl-ctrl-icon",this._zoomOutButton).setAttribute("aria-hidden","true")),this.options.showCompass&&(this._compass=this._createButton("maplibregl-ctrl-compass",(t=>{this.options.visualizePitch?this._map.resetNorthPitch({},{originalEvent:t}):this._map.resetNorth({},{originalEvent:t})})),this._compassIcon=pe.create("span","maplibregl-ctrl-icon",this._compass),this._compassIcon.setAttribute("aria-hidden","true"))}onAdd(u){return this._map=u,this.options.showZoom&&(this._setButtonTitle(this._zoomInButton,"ZoomIn"),this._setButtonTitle(this._zoomOutButton,"ZoomOut"),this._map.on("zoom",this._updateZoomButtons),this._updateZoomButtons()),this.options.showCompass&&(this._setButtonTitle(this._compass,"ResetBearing"),this.options.visualizePitch&&this._map.on("pitch",this._rotateCompassArrow),this.options.visualizeRoll&&this._map.on("roll",this._rotateCompassArrow),this._map.on("rotate",this._rotateCompassArrow),this._rotateCompassArrow(),this._handler=new es(this._map,this._compass,this.options.visualizePitch)),this._container}onRemove(){this._container.remove(),this.options.showZoom&&this._map.off("zoom",this._updateZoomButtons),this.options.showCompass&&(this.options.visualizePitch&&this._map.off("pitch",this._rotateCompassArrow),this.options.visualizeRoll&&this._map.off("roll",this._rotateCompassArrow),this._map.off("rotate",this._rotateCompassArrow),this._handler.off(),delete this._handler),delete this._map}_createButton(u,t){let n=pe.create("button",u,this._container);return n.type="button",n.addEventListener("click",t),n}},k.Popup=class extends p.E{constructor(u){super(),this._updateOpacity=()=>{this.options.locationOccludedOpacity!==void 0&&(this._container.style.opacity=this._map.transform.isLocationOccluded(this.getLngLat())?`${this.options.locationOccludedOpacity}`:"")},this.remove=()=>(this._content&&this._content.remove(),this._container&&(this._container.remove(),delete this._container),this._map&&(this._map.off("move",this._update),this._map.off("move",this._onClose),this._map.off("click",this._onClose),this._map.off("remove",this.remove),this._map.off("terrain",this._update),this._map.off("projectiontransition",this._update),this._map.off("mousemove",this._update),this._map.off("mouseup",this._update),this._map.off("drag",this._update),this._map._canvasContainer.classList.remove("maplibregl-track-pointer"),delete this._map,this.fire(new p.n("close"))),this),this._update=t=>{if(!this._map||!this._lngLat&&!this._trackPointer||!this._content)return;if(!this._container){if(this._container=pe.create("div","maplibregl-popup",this._map.getContainer()),this._tip=pe.create("div","maplibregl-popup-tip",this._container),this._container.appendChild(this._content),this.options.className)for(let x of this.options.className.split(" "))this._container.classList.add(x);this._closeButton&&this._closeButton.setAttribute("aria-label",this._map._getUIString("Popup.Close")),this._trackPointer&&this._container.classList.add("maplibregl-popup-track-pointer")}let n;if(this.options.maxWidth&&this._container.style.maxWidth!==this.options.maxWidth&&(this._container.style.maxWidth=this.options.maxWidth),this._lngLat=Qs(this._lngLat,this._flatPos,this._map.transform,this._trackPointer),t&&"point"in t&&t.point&&(n=t.point),this._trackPointer&&!n)return;let a=this._flatPos=this._pos=this._trackPointer&&n?n:this._map.project(this._lngLat);this._map.terrain&&(this._flatPos=this._trackPointer&&n?n:this._map.transform.locationToScreenPoint(this._lngLat));let c=this.options.anchor,f=ia(this.options.offset);if(!c){let x=this._container.offsetWidth,w=this._container.offsetHeight,P=(function(E){var C,z,B,N;return E?{top:(C=E.top)!==null&&C!==void 0?C:0,right:(z=E.right)!==null&&z!==void 0?z:0,bottom:(B=E.bottom)!==null&&B!==void 0?B:0,left:(N=E.left)!==null&&N!==void 0?N:0}:{top:0,right:0,bottom:0,left:0}})(this.options.padding),S;S=a.y+f.bottom.ythis._map.transform.height-w-P.bottom?["bottom"]:[],a.xthis._map.transform.width-x/2-P.right&&S.push("right"),c=S.length===0?"bottom":S.join("-")}let y=a.add(f[c]);this.options.subpixelPositioning||(y=y.round()),this._container.style.transform=`${ts[c]} translate(${y.x}px,${y.y}px)`,ea(this._container,c,"popup"),this._updateOpacity()},this._onClose=()=>{this.remove()},this.options=p.e(Object.create(Rl),u)}addTo(u){return this._map&&this.remove(),this._map=u,this.options.closeOnClick&&this._map.on("click",this._onClose),this.options.closeOnMove&&this._map.on("move",this._onClose),this._map.on("remove",this.remove),this._map.on("terrain",this._update),this._map.on("projectiontransition",this._update),this._update(),this._focusFirstElement(),this._trackPointer?(this._map.on("mousemove",this._update),this._map.on("mouseup",this._update),this._container&&this._container.classList.add("maplibregl-popup-track-pointer"),this._map._canvasContainer.classList.add("maplibregl-track-pointer")):this._map.on("move",this._update),this.fire(new p.n("open")),this}isOpen(){return!!this._map}getLngLat(){return this._lngLat}setLngLat(u){return this._lngLat=p.W.convert(u),this._pos=null,this._flatPos=null,this._trackPointer=!1,this._update(),this._map&&(this._map.on("move",this._update),this._map.off("mousemove",this._update),this._container&&this._container.classList.remove("maplibregl-popup-track-pointer"),this._map._canvasContainer.classList.remove("maplibregl-track-pointer")),this}trackPointer(){return this._trackPointer=!0,this._pos=null,this._flatPos=null,this._update(),this._map&&(this._map.off("move",this._update),this._map.on("mousemove",this._update),this._map.on("drag",this._update),this._container&&this._container.classList.add("maplibregl-popup-track-pointer"),this._map._canvasContainer.classList.add("maplibregl-track-pointer")),this}getElement(){return this._container}setText(u){return this.setDOMContent(document.createTextNode(u))}setHTML(u){let t=document.createDocumentFragment(),n=document.createElement("body"),a;for(n.innerHTML=u;a=n.firstChild,a;)t.appendChild(a);return this.setDOMContent(t)}getMaxWidth(){var u;return(u=this._container)===null||u===void 0?void 0:u.style.maxWidth}setMaxWidth(u){return this.options.maxWidth=u,this._update(),this}setDOMContent(u){if(this._content)for(;this._content.hasChildNodes();)this._content.firstChild&&this._content.removeChild(this._content.firstChild);else this._content=pe.create("div","maplibregl-popup-content",this._container);return this._content.appendChild(u),this._createCloseButton(),this._update(),this._focusFirstElement(),this}addClassName(u){return this._container&&this._container.classList.add(u),this}removeClassName(u){return this._container&&this._container.classList.remove(u),this}setOffset(u){return this.options.offset=u,this._update(),this}toggleClassName(u){if(this._container)return this._container.classList.toggle(u)}setSubpixelPositioning(u){this.options.subpixelPositioning=u}setPadding(u){this.options.padding=u,this._update()}_createCloseButton(){this.options.closeButton&&(this._closeButton=pe.create("button","maplibregl-popup-close-button",this._content),this._closeButton.type="button",this._closeButton.innerHTML="×",this._closeButton.addEventListener("click",this._onClose))}_focusFirstElement(){if(!this.options.focusAfterOpen||!this._container)return;let u=this._container.querySelector(ta);u&&u.focus()}},k.RasterDEMTileSource=Ht,k.RasterTileSource=Mi,k.ScaleControl=class{constructor(u){this._onMove=()=>{rs(this._map,this._container,this.options)},this.setUnit=t=>{this.options.unit=t,rs(this._map,this._container,this.options)},this.options=Object.assign(Object.assign({},zl),u)}getDefaultPosition(){return"bottom-left"}onAdd(u){return this._map=u,this._container=pe.create("div","maplibregl-ctrl maplibregl-ctrl-scale",u.getContainer()),this._map.on("move",this._onMove),this._onMove(),this._container}onRemove(){this._container.remove(),this._map.off("move",this._onMove),this._map=void 0}},k.ScrollZoomHandler=Ml,k.Style=pn,k.TerrainControl=class{constructor(u){this._toggleTerrain=()=>{this._map.getTerrain()?this._map.setTerrain(null):this._map.setTerrain(this.options),this._updateTerrainIcon()},this._updateTerrainIcon=()=>{this._terrainButton.classList.remove("maplibregl-ctrl-terrain"),this._terrainButton.classList.remove("maplibregl-ctrl-terrain-enabled"),this._map.terrain?(this._terrainButton.classList.add("maplibregl-ctrl-terrain-enabled"),this._terrainButton.title=this._map._getUIString("TerrainControl.Disable")):(this._terrainButton.classList.add("maplibregl-ctrl-terrain"),this._terrainButton.title=this._map._getUIString("TerrainControl.Enable"))},this.options=u}onAdd(u){return this._map=u,this._container=pe.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._terrainButton=pe.create("button","maplibregl-ctrl-terrain",this._container),pe.create("span","maplibregl-ctrl-icon",this._terrainButton).setAttribute("aria-hidden","true"),this._terrainButton.type="button",this._terrainButton.addEventListener("click",this._toggleTerrain),this._updateTerrainIcon(),this._map.on("terrain",this._updateTerrainIcon),this._container}onRemove(){this._container.remove(),this._map.off("terrain",this._updateTerrainIcon),this._map=void 0}},k.TwoFingersTouchPitchHandler=gr,k.TwoFingersTouchRotateHandler=th,k.TwoFingersTouchZoomHandler=eh,k.TwoFingersTouchZoomRotateHandler=Ie,k.VectorTileSource=Wt,k.VideoSource=Qr,k.addSourceType=(u,t)=>p._(void 0,void 0,void 0,(function*(){if(ds(u))throw new Error(`A source type called "${u}" already exists.`);((n,a)=>{La[n]=a})(u,t)})),k.clearPrewarmedResources=function(){let u=Bi;u&&(u.isPreloaded()&&u.numActive()===1?(u.release(vt),Bi=null):console.warn("Could not clear WebWorkers since there are active Map instances that still reference it. The pre-warmed WebWorker pool can only be cleared when all map instances have been removed with map.remove()"))},k.createTileMesh=qn,k.getGlobalDispatcher=li,k.getMaxParallelImageRequests=function(){return p.c.MAX_PARALLEL_IMAGE_REQUESTS},k.getRTLTextPluginStatus=function(){return Dr().getRTLTextPluginStatus()},k.getVersion=function(){return kl},k.getWorkerCount=function(){return xt.workerCount},k.getWorkerUrl=function(){return p.c.WORKER_URL},k.importScriptInWorkers=function(u){return li().broadcast("IS",u)},k.isTimeFrozen=function(){return Ir.isFrozen()},k.now=Xe,k.prewarm=function(){Yr().acquire(vt)},k.restoreNow=function(){Ir.restoreNow()},k.setMaxParallelImageRequests=function(u){p.c.MAX_PARALLEL_IMAGE_REQUESTS=u},k.setNow=function(u){Ir.setNow(u)},k.setRTLTextPlugin=function(u,t){return Dr().setRTLTextPlugin(u,t)},k.setWorkerCount=function(u){xt.workerCount=u},k.setWorkerUrl=function(u){p.c.WORKER_URL=u}}));var cr=Le;return cr}))});Da();var G_=[["DUP","Democratic Unionist Party","DUP Civil Servant (Retired)"],["UUP","Ulster Unionist Party","Ulster Unionist","Official Unionist Party","Official Unionist","Shopkeeper, Ulster Unionist","Businssman Ulster Unionist"],["AP","Alliance Party","Alliance","Alliance Party of Northern Ireland"],["SDLP","Social Democratic and Labour Party"],["SF","Sinn F\xE9in","Sinn Fein"],["Ind U","Independent Unionist","Independent Progressive Unionist","Independent Liberal Unionist","Unofficial Unionist"],["Ind O","Independent Other"],["Ind N","Independent Nationalist","Ind Nat","unofficial (non-party) Sinn F\xE9in","Irish Republican"],["Ind","Independent","Non party/Independent","Non-party","Non party","NON-P","Independent - Northern Ireland independence","Non party/An Chomhdhail Phobail | People's Convention","Non party/Fathers Rights Responsibilities","Independent Farmer"],["GP","Green Party","Green","Green Party Northern Ireland","Green / Ecology","Green/Comhaontas Glas","Green Alliance/Comhaontas Glas","G.P."],["PBP","People Before Profit","People Before Profit Alliance","P.B.P.A."],["S-PBP","Solidarity\u2013People Before Profit","Solidarity-PBP","S.P.B.P."],["TUV","Traditional Unionist Voice"],["CCLA","Cross-Community Labour Alternative"],["CON","Conservative Party","Conservative","Conservatives","NI Conservatives"],["AO","Aont\xFA"],["FF","Fianna F\xE1il","Fianna Fail"],["FG","Fine Gael"],["LAB","Labour Party","Irish Labour","Labour","Irish Labour Party","Lab.","LAB.","Ir Lab"],["SD","Social Democrats"],["PUP","Progressive Unionist Party","Progressive Unionist"],["UKIP","UK Independence Party"],["WP","Workers' Party","Workers Party","Workers'","W.P."],["SFWP","Sinn F\xE9in The Workers' Party","Sinn F\xE9in Workers'"],["RC","Republican Clubs"],["VUPP","Vanguard Unionist Progressive Party"],["NILP","Northern Ireland Labour Party","NI Labour"],["LPNI","Labour Party of Northern Ireland"],["NALAB","Newtownabbey Labour"],["NILRC","Northern Ireland Labour Representation Committee"],["PD","Progressive Democrats","P.D."],["IIP","Irish Independence Party"],["UPNI","Unionist Party of Northern Ireland"],["CnaG","Cumann na nGaedheal"],["UDP","Ulster Democratic Party"],["UKUP","UK Unionist Party"],["Nat","Nationalist Party","Nationalist Party (Northern Ireland)"],["IPP","Irish Parliamentary Party","Irish Parliamentary"],["UPUP","Ulster Popular Unionist Party"],["SP","Socialist Party","S.P."],["IUA","Irish Unionist Alliance"],["NIWC","Northern Ireland Women's Coalition","NI Women's Coalition"],["LC","Labour Coalition"],["IRSP","Irish Republican Socialist Party"],["NLP","Natural Law Party","Natural Law"],["FP","Farmers' Party","Farmers"],["CnaP","Clann na Poblachta"],["INF","Irish National Federation"],["CPI","Communist Party of Ireland"],["RLP","Republican Labour Party","Republican Labour","Rep Lab"],["BNP","British National Party"],["CISTA","Cannabis Is Safer Than Alcohol"],["DL","Democratic Left","Democratic Left (Ireland)"],["INL","Irish National League"],["UUUP","United Ulster Unionist Party"],["CSP","Christian Solidarity Party","Comhar Criostai / Christian Solidarity","Comhar Criostai/Christian Solidarity","C.S.P."],["II","Independent Ireland"],["RNU","Republican Network for Unity"],["CnaT","Clann na Talmhan"],["AAA","Anti-Austerity Alliance","A.A.A."],["ULP","Ulster Liberal Party","Ulster Liberal"],["NP","National Party"],["RSF","Republican Sinn F\xE9in"],["TIP","The Irish People"],["UIM","Ulster Independence Movement"],["LIB","Liberal Party","Liberal"],["LU","Liberal Unionist"],["NIUP","Northern Ireland Unionist Party","NI Unionist Party"],["SEA","Socialist Environmental Alliance"],["IFP","Irish Freedom Party"],["DDI","Direct Democracy Ireland","D.D.I."],["SWP","Socialist Workers Party","Socialist Workers"],["AHB","Anti H-Block"],["Ind Lab","Independent Labour","Ind Lab"],["AFIL","All-for-Ireland League","All-for-Ireland"],["I4C","Independents 4 Change"],["IA","Independent Alliance"],["NCP","National Centre Party"],["UCUNF","Ulster Conservatives and Unionists \u2013 New Force"],["PDem","People's Democracy","People's Democracy (Ireland)"],["NDP","National Democratic Party"],["Eco","Ecology Party","Ecology","Ecology Party Ireland"],["Ind Rep","Independent Republican","Ind Rep"],["Ind FF","Independent Fianna F\xE1il","Independent Fianna Fail"],["Ind FG","Independent Fine Gael"],["Ind CON","Independent Conservative","Ind. Conservative"],["Ind Soc","Independent Socialist"],["IUP","Independent Unionist Party","Ind. Unionist Party"],["Prot U","Protestant Unionist Party","Protestant Unionist"],["PT SF","Pro-Treaty Sinn F\xE9in"],["AT SF","Anti-Treaty Sinn F\xE9in"],["DVP","Democrats and Veterans"],["WUAG","Workers and Unemployed Action Group"],["ULA","United Left Alliance"],["IHA","Independent Health Alliance"],["CC","Ceann Comhairle (Speaker)"],["RDT","Vote For Yourself / Rainbow Dream Ticket / Make Politicians History"],["Joint","Joint Panel Nomination (Pro/Anti Treaty)"],["ARG","An Rabharta Glas \u2013 Green Left","An Rabharta Glas \u2013 Green Left Lozenge"],["HRRA","Housing Rights and Reform Alliance"],["DLTU","Derry Labour and Trade Union Party"],["UCDP","Ulster Christian Democratic Party"],["SKIA","South Kerry Independent Alliance"],["ILPU","Irish Loyal and Patriotic Union"],["A\xC9","Aontacht Eireann (Irish Unity)"],["LTUG","Labour and Trade Union Group"],["3W","Third Way (UK organisation)"],["UIV","Ulster's Independent Voice"],["SRP","Socialist Republican Party"],["KIA","Kerry Independent Alliance"],["PPP","People's Progressive Party"],["CLP","Commonwealth Labour Party"],["UCP","Ulster Constitution Party"],["Unity","Unity (Northern Ireland)"],["PAW","Party for Animal Welfare"],["UPA","Ulster Protestant Action"],["UPL","Ulster Protestant League"],["SBU","South Belfast Unionists"],["Centre","Centre Party of Ireland"],["ISN","Irish Socialist Network"],["NDUK","National Democrats (UK)"],["DP","Democratic Partnership"],["NI1ST","Northern Ireland First"],["IDP","Irish Democratic Party"],["TTA","Town Tenants' Association","Town Tenants Association"],["VPP","Volunteer Political Party"],["NF","National Front","National Front (UK)"],["Socialist","Socialist","Socialist Lozenge"],["AWP","Animal Welfare Party"],["LRC","Labour Representation Committee","Labour Repr. Cmte."],["WSP","World Socialist Party"],["FOL","Federation of Labour"],["NIM","New Ireland Movement"],["U3W","Ulster Third Way"]],$_=["Non-transferable"];function Rh(Le){return String(Le??"").normalize("NFKD").replace(/[̀-ͯ]/g,"").replace(/\s+lozenge$/i,"").replace(/&/g," and ").replace(/[.'’`]/g,"").replace(/[–—\-_/,]/g," ").replace(/\s+/g," ").trim().toLowerCase()}var kh=new Map;for(let[Le,Qe,...Zt]of G_)for(let cr of[Le,Qe,...Zt]){let k=Rh(cr);k&&!kh.has(k)&&kh.set(k,{abbreviation:Le,fullName:Qe})}var Y_=new Set($_.map(Rh));function Z_(Le){let Qe=String(Le??"").trim();if(!Qe)return null;let Zt=kh.get(Rh(Qe));if(Zt)return Zt;let cr=Rh(Qe.replace(/\s*\([^)]*\)\s*$/,""));return kh.get(cr)||null}function K_(Le,Qe){let Zt=String(Le??"").trim(),cr=Z_(Zt);return!cr||cr.abbreviation===cr.fullName?Qe(Zt):`${Qe(cr.abbreviation)}`}Da();var W_=[{name:"ARMAGH AREA D",matches:Le=>qf(Le.NAME)&&Wf(Le.Area_SqKM,13.1719213882566)},{name:"DUNGANNON AREA C",matches:Le=>String(Le.OBJECTID??"").trim()==="1624"&&X_(Le.NAME)==="DUNGANNON AREA D"},{name:"LIMAVADY AREA C",matches:Le=>qf(Le.NAME)&&Wf(Le.Area_SqKM,8.44105398081151)}];function Cy(Le,Qe={}){if(!xd(Le))return Qe||{};let Zt=H_(Qe);return Zt?{...Qe||{},NAME:Zt,name:Qe?.name||Zt,label_name:Qe?.label_name||Zt}:Qe||{}}function Ay(Le,Qe){return xd(Le)?["case",Lh(13.1719213882566),"ARMAGH AREA D",["all",["==",["to-string",["get","OBJECTID"]],"1624"],["==",["upcase",["to-string",["get","NAME"]]],"DUNGANNON AREA D"]],"DUNGANNON AREA C",Lh(8.44105398081151),"LIMAVADY AREA C",Qe]:Qe}function Dy(Le){return xd(Le)?["any",Lh(13.1719213882566),["all",["==",["to-string",["get","OBJECTID"]],"1624"],["==",["upcase",["to-string",["get","NAME"]]],"DUNGANNON AREA D"]],Lh(8.44105398081151)]:null}function xd(Le){return Le?.sourceMapId==="deas-1972"||Le?.id==="deas-1972"||Le?.id==="deas-1972-vector-test"||Le?.sourceLayer==="deas_1972"}function H_(Le={}){return W_.find(Qe=>Qe.matches(Le||{}))?.name||""}function Lh(Le){return["all",["!",["has","NAME"]],["<",["abs",["-",["to-number",["get","Area_SqKM"],-999999],Le]],1e-4]]}function qf(Le){return Le==null||String(Le).trim()===""}function Wf(Le,Qe){let Zt=Number(Le);return Number.isFinite(Zt)&&Math.abs(Zt-Qe)<1e-4}function X_(Le){return String(Le??"").trim().toUpperCase()}export{K_ as a,q_ as b,Cy as c,Ay as d,Dy as e}; +${x.shaderPreludeCode.vertexSource}`,define:x.shaderDefine},defaultProjectionData:P},E=y.renderingMode?y.renderingMode:"2d";if(u.renderPass==="offscreen"){let C=y.prerender;C&&(u.setCustomLayerDefaults(),f.setColorMode(u.colorModeForRenderPass()),C.call(y,f.gl,S),f.setDirty(),u.setBaseState())}else if(u.renderPass==="translucent"){u.setCustomLayerDefaults(),f.setColorMode(u.colorModeForRenderPass()),f.setStencilMode(He.disabled);let C=E==="3d"?u.getDepthModeFor3D():u.getDepthModeForSublayer(0,Ne.ReadOnly);f.setDepthMode(C),y.render(f.gl,S),f.setDirty(),u.setBaseState(),f.bindFramebuffer.set(null)}},debug:function(u,t,n){for(let a of n)Zc(u,t,a)},debugPadding:function(u){let t=u.transform.padding;ml(u,u.transform.height-(t.top||0),3,jc),ml(u,t.bottom||0,3,Uc),gl(u,t.left||0,3,Gc),gl(u,u.transform.width-(t.right||0),3,$c);let n=u.transform.centerPoint;(function(a,c,f,y){Go(a,c-1,f-10,2,20,y),Go(a,c-10,f-1,20,2,y)})(u,n.x,u.transform.height-n.y,Br)},terrainDepth:function(u,t){let n=u.context,a=n.gl,c=u.transform,f=lt.unblended,y=new Ne(a.LEQUAL,Ne.ReadWrite,[0,1]),x=t.tileManager.getRenderableTiles(),w=u.useProgram("terrainDepth");n.bindFramebuffer.set(t.getFramebuffer("depth").framebuffer),n.viewport.set([0,0,u.width/devicePixelRatio,u.height/devicePixelRatio]),n.clear({color:p.bo.transparent,depth:1});for(let P of x){let S=t.getTerrainMesh(P.tileID),E=t.getTerrainData(P.tileID),C=c.getProjectionData({overscaledTileID:P.tileID,applyTerrainMatrix:!1,applyGlobeMatrix:!0}),z={u_ele_delta:t.getMeshFrameDelta(c.zoom)};w.draw(n,a.TRIANGLES,y,He.disabled,f,qe.backCCW,z,E,C,"terrain",S.vertexBuffer,S.indexBuffer,S.segments)}n.bindFramebuffer.set(null),n.viewport.set([0,0,u.width,u.height])},terrainCoords:function(u,t){let n=u.context,a=n.gl,c=u.transform,f=lt.unblended,y=new Ne(a.LEQUAL,Ne.ReadWrite,[0,1]),x=t.getCoordsTexture(),w=t.tileManager.getRenderableTiles(),P=u.useProgram("terrainCoords");n.bindFramebuffer.set(t.getFramebuffer("coords").framebuffer),n.viewport.set([0,0,u.width/devicePixelRatio,u.height/devicePixelRatio]),n.clear({color:p.bo.transparent,depth:1}),t.coordsIndex=[];for(let S of w){let E=t.getTerrainMesh(S.tileID),C=t.getTerrainData(S.tileID);n.activeTexture.set(a.TEXTURE0),a.bindTexture(a.TEXTURE_2D,x.texture);let z={u_terrain_coords_id:(255-t.coordsIndex.length)/255,u_texture:0,u_ele_delta:t.getMeshFrameDelta(c.zoom)},B=c.getProjectionData({overscaledTileID:S.tileID,applyTerrainMatrix:!1,applyGlobeMatrix:!0});P.draw(n,a.TRIANGLES,y,He.disabled,f,qe.backCCW,z,C,B,"terrain",E.vertexBuffer,E.indexBuffer,E.segments),t.coordsIndex.push(S.tileID.key)}n.bindFramebuffer.set(null),n.viewport.set([0,0,u.width,u.height])}};class $o{constructor(t,n){this.drawFunctions=qc,this.context=new Us(t),this.transform=n,this._tileTextures={},this.terrainFacilitator={depthDirty:!0,coordsDirty:!1,matrix:p.ap(new Float64Array(16)),renderTime:0},this.setup(),this.numSublayers=Xt.maxOverzooming+Xt.maxUnderzooming+1,this.depthEpsilon=1/Math.pow(2,16),this.crossTileSymbolIndex=new xi}resize(t,n,a){if(this.width=Math.floor(t*a),this.height=Math.floor(n*a),this.pixelRatio=a,this.context.viewport.set([0,0,this.width,this.height]),this.style)for(let c of this.style._order)this.style._layers[c].resize()}setup(){let t=this.context,n=new p.aU;n.emplaceBack(0,0),n.emplaceBack(p.a6,0),n.emplaceBack(0,p.a6),n.emplaceBack(p.a6,p.a6),this.tileExtentBuffer=t.createVertexBuffer(n,kr.members),this.tileExtentSegments=p.aV.simpleSegment(0,0,4,2);let a=new p.aU;a.emplaceBack(0,0),a.emplaceBack(p.a6,0),a.emplaceBack(0,p.a6),a.emplaceBack(p.a6,p.a6),this.debugBuffer=t.createVertexBuffer(a,kr.members),this.debugSegments=p.aV.simpleSegment(0,0,4,5);let c=new p.ch;c.emplaceBack(0,0,0,0),c.emplaceBack(p.a6,0,p.a6,0),c.emplaceBack(0,p.a6,0,p.a6),c.emplaceBack(p.a6,p.a6,p.a6,p.a6),this.rasterBoundsBuffer=t.createVertexBuffer(c,zo.members),this.rasterBoundsSegments=p.aV.simpleSegment(0,0,4,2);let f=new p.aU;f.emplaceBack(0,0),f.emplaceBack(p.a6,0),f.emplaceBack(0,p.a6),f.emplaceBack(p.a6,p.a6),this.rasterBoundsBufferPosOnly=t.createVertexBuffer(f,kr.members),this.rasterBoundsSegmentsPosOnly=p.aV.simpleSegment(0,0,4,5);let y=new p.aU;y.emplaceBack(0,0),y.emplaceBack(1,0),y.emplaceBack(0,1),y.emplaceBack(1,1),this.viewportBuffer=t.createVertexBuffer(y,kr.members),this.viewportSegments=p.aV.simpleSegment(0,0,4,2);let x=new p.ci;x.emplaceBack(0),x.emplaceBack(1),x.emplaceBack(3),x.emplaceBack(2),x.emplaceBack(0),this.tileBorderIndexBuffer=t.createIndexBuffer(x);let w=new p.aW;w.emplaceBack(1,0,2),w.emplaceBack(1,2,3),this.quadTriangleIndexBuffer=t.createIndexBuffer(w);let P=this.context.gl;this.stencilClearMode=new He({func:P.ALWAYS,mask:0},0,255,P.ZERO,P.ZERO,P.ZERO),this.tileExtentMesh=new at(this.tileExtentBuffer,this.quadTriangleIndexBuffer,this.tileExtentSegments)}clearStencil(){let t=this.context,n=t.gl;this.nextStencilID=1,this.currentStencilSource=void 0;let a=p.O();p.c7(a,0,this.width,this.height,0,0,1),p.S(a,a,[n.drawingBufferWidth,n.drawingBufferHeight,0]);let c={mainMatrix:a,tileMercatorCoords:[0,0,1,1],clippingPlane:[0,0,0,0],projectionTransition:0,fallbackMatrix:a};this.useProgram("clippingMask",null,!0).draw(t,n.TRIANGLES,Ne.disabled,this.stencilClearMode,lt.disabled,qe.disabled,null,null,c,"$clipping",this.viewportBuffer,this.quadTriangleIndexBuffer,this.viewportSegments)}_renderTileClippingMasks(t,n,a){if(this.currentStencilSource===t.source||!t.isTileClipped()||!n?.length)return;this.currentStencilSource=t.source,this.nextStencilID+n.length>256&&this.clearStencil();let c=this.context;c.setColorMode(lt.disabled),c.setDepthMode(Ne.disabled);let f={};for(let y of n)f[y.key]=this.nextStencilID++;this._renderTileMasks(f,n,a,!0),this._renderTileMasks(f,n,a,!1),this._tileClippingMaskIDs=f}_renderTileMasks(t,n,a,c){var f;let y=this.context,x=y.gl,w=this.style.projection,P=this.transform,S=this.useProgram("clippingMask");for(let E of n){let C=t[E.key],z=(f=this.style.map.terrain)===null||f===void 0?void 0:f.getTerrainData(E),B=w.getMeshFromTileID(this.context,E.canonical,c,!0,"stencil"),N=P.getProjectionData({overscaledTileID:E,applyGlobeMatrix:!a,applyTerrainMatrix:!0});S.draw(y,x.TRIANGLES,Ne.disabled,new He({func:x.ALWAYS,mask:0},C,255,x.KEEP,x.KEEP,x.REPLACE),lt.disabled,a?qe.disabled:qe.backCCW,null,z,N,"$clipping",B.vertexBuffer,B.indexBuffer,B.segments)}}_renderTilesDepthBuffer(){var t;let n=this.context,a=n.gl,c=this.style.projection,f=this.transform,y=this.useProgram("depth"),x=this.getDepthModeFor3D(),w=rn(f,{tileSize:f.tileSize});for(let P of w){let S=(t=this.style.map.terrain)===null||t===void 0?void 0:t.getTerrainData(P),E=c.getMeshFromTileID(this.context,P.canonical,!0,!0,"raster"),C=f.getProjectionData({overscaledTileID:P,applyGlobeMatrix:!0,applyTerrainMatrix:!0});y.draw(n,a.TRIANGLES,x,He.disabled,lt.disabled,qe.backCCW,null,S,C,"$clipping",E.vertexBuffer,E.indexBuffer,E.segments)}}stencilModeFor3D(){this.currentStencilSource=void 0,this.nextStencilID+1>256&&this.clearStencil();let t=this.nextStencilID++,n=this.context.gl;return new He({func:n.NOTEQUAL,mask:255},t,255,n.KEEP,n.KEEP,n.REPLACE)}stencilModeForClipping(t){let n=this.context.gl;return new He({func:n.EQUAL,mask:255},this._tileClippingMaskIDs[t.key],0,n.KEEP,n.KEEP,n.REPLACE)}getStencilConfigForOverlapAndUpdateStencilID(t){let n=this.context.gl,a=t.sort(((y,x)=>x.overscaledZ-y.overscaledZ)),c=a[a.length-1].overscaledZ,f=a[0].overscaledZ-c+1;if(f>1){this.currentStencilSource=void 0,this.nextStencilID+f>256&&this.clearStencil();let y={};for(let x=0;xx.overscaledZ-y.overscaledZ)),c=a[a.length-1].overscaledZ,f=a[0].overscaledZ-c+1;if(this.clearStencil(),f>1){let y={},x={};for(let w=0;w0};for(let z in x){let B=x[z];B.used&&B.prepare(this.context),w[z]=B.getVisibleCoordinates(!1),P[z]=w[z].slice().reverse(),S[z]=B.getVisibleCoordinates(!0).reverse()}this.opaquePassCutoff=1/0;for(let z=0;zthis.useProgram(z)}),this.context.viewport.set([0,0,this.width,this.height]),this.context.bindFramebuffer.set(null),this.context.clear({color:n.showOverdrawInspector?p.bo.black:p.bo.transparent,depth:1}),this.clearStencil(),this.style.sky&&this.drawFunctions.sky(this,this.style.sky),this._showOverdrawInspector=n.showOverdrawInspector,this.depthRangeFor3D=[0,1-(t._order.length+2)*this.numSublayers*this.depthEpsilon],!this.renderToTexture)for(this.renderPass="opaque",this.currentLayer=y.length-1;this.currentLayer>=0;this.currentLayer--){let z=this.style._layers[y[this.currentLayer]],B=x[z.source],N=w[z.source];this._renderTileClippingMasks(z,N,!1),this.renderLayer(this,B,z,N,E)}this.renderPass="translucent";let C=!1;for(this.currentLayer=0;this.currentLayerU.source&&!U.isHidden(N)?[B.tileManagers[U.source]]:[])),$=j.filter((U=>U.getSource().type==="vector")),X=j.filter((U=>U.getSource().type!=="vector")),Z=U=>{(!G||G.getSource().maxzoom0?n.pop():null}isPatternMissing(t){if(!t)return!1;if(!t.from||!t.to)return!0;let n=this.imageManager.getPattern(t.from.toString()),a=this.imageManager.getPattern(t.to.toString());return!n||!a}useProgram(t,n,a=!1,c=[]){var f;this.cache||(this.cache={});let y=!!this.style.map.terrain,x=this.style.projection,w=a?ft.projectionMercator:x.shaderPreludeCode,P=a?ci:x.shaderDefine,S=t+(n?n.cacheKey:"")+`/${a?Ci:x.shaderVariantName}`+(this._showOverdrawInspector?"/overdraw":"")+(y?"/terrain":"")+(c?`/${c.join("/")}`:"");return(f=this.cache)[S]||(f[S]=new Uh(this.context,ft[t],n,qh[t],this._showOverdrawInspector,y,w,P,c)),this.cache[S]}setCustomLayerDefaults(){this.context.unbindVAO(),this.context.cullFace.setDefault(),this.context.activeTexture.setDefault(),this.context.pixelStoreUnpack.setDefault(),this.context.pixelStoreUnpackPremultiplyAlpha.setDefault(),this.context.pixelStoreUnpackFlipY.setDefault()}setBaseState(){let t=this.context.gl;this.context.cullFace.set(!1),this.context.viewport.set([0,0,this.width,this.height]),this.context.blendEquation.set(t.FUNC_ADD)}initDebugOverlayCanvas(){this.debugOverlayCanvas==null&&(this.debugOverlayCanvas=document.createElement("canvas"),this.debugOverlayCanvas.width=512,this.debugOverlayCanvas.height=512,this.debugOverlayTexture=new p.T(this.context,this.debugOverlayCanvas,this.context.gl.RGBA))}destroy(){var t,n;if(this._tileTextures){for(let a in this._tileTextures){let c=this._tileTextures[a];if(c)for(let f of c)f.destroy()}this._tileTextures={}}if(this.tileExtentBuffer&&this.tileExtentBuffer.destroy(),this.debugBuffer&&this.debugBuffer.destroy(),this.rasterBoundsBuffer&&this.rasterBoundsBuffer.destroy(),this.rasterBoundsBufferPosOnly&&this.rasterBoundsBufferPosOnly.destroy(),this.viewportBuffer&&this.viewportBuffer.destroy(),this.tileBorderIndexBuffer&&this.tileBorderIndexBuffer.destroy(),this.quadTriangleIndexBuffer&&this.quadTriangleIndexBuffer.destroy(),this.tileExtentMesh&&((t=this.tileExtentMesh.vertexBuffer)===null||t===void 0||t.destroy()),this.tileExtentMesh&&((n=this.tileExtentMesh.indexBuffer)===null||n===void 0||n.destroy()),this.debugOverlayTexture&&this.debugOverlayTexture.destroy(),this.cache){for(let a in this.cache){let c=this.cache[a];c?.program&&this.context.gl.deleteProgram(c.program)}this.cache={}}this.context&&this.context.setDefault()}overLimit(){let{drawingBufferWidth:t,drawingBufferHeight:n}=this.context.gl;return this.width!==t||this.height!==n}}function vl(u,t){let n,a=!1,c=null,f=()=>{c=null,a&&(u(...n),c=setTimeout(f,t),a=!1)};return(...y)=>(a=!0,n=y,c||f(),c)}$o.MAX_TEXTURE_POOL_SIZE_PER_BUCKET=50;class Zo{constructor(t){this._getCurrentHash=()=>{let n=window.location.hash.replace("#","");if(this._hashName){let a,c=n.split("&").map((f=>f.split("=")));for(let f of c)f[0]===this._hashName&&(a=f);return(a&&a[1]||"").split("/")}return n.split("/")},this._onHashChange=()=>{let n=this._getCurrentHash();if(!this._isValidHash(n))return!1;let a=this._map.dragRotate.isEnabled()&&this._map.touchZoomRotate.isEnabled()?+(n[3]||0):this._map.getBearing();return this._map.jumpTo({center:[+n[2],+n[1]],zoom:+n[0],bearing:a,pitch:+(n[4]||0)}),!0},this._updateHashUnthrottled=()=>{let n=window.location.href.replace(/(#.*)?$/,this.getHashString());window.history.replaceState(window.history.state,null,n)},this._removeHash=()=>{let n=this._getCurrentHash();if(n.length===0)return;let a=n.join("/"),c=a;c.split("&").length>0&&(c=c.split("&")[0]),this._hashName&&(c=`${this._hashName}=${a}`);let f=window.location.hash.replace(c,"");f.startsWith("#&")?f=f.slice(0,1)+f.slice(2):f==="#"&&(f="");let y=window.location.href.replace(/(#.+)?$/,f);y=y.replace("&&","&"),window.history.replaceState(window.history.state,null,y)},this._updateHash=vl(this._updateHashUnthrottled,300),this._hashName=t&&encodeURIComponent(t)}addTo(t){return this._map=t,addEventListener("hashchange",this._onHashChange,!1),this._map.on("moveend",this._updateHash),this}remove(){return removeEventListener("hashchange",this._onHashChange,!1),this._map.off("moveend",this._updateHash),clearTimeout(this._updateHash()),this._removeHash(),delete this._map,this}getHashString(t){let n=this._map.getCenter(),a=Math.round(100*this._map.getZoom())/100,c=Math.ceil((a*Math.LN2+Math.log(512/360/.5))/Math.LN10),f=Math.pow(10,c),y=Math.round(n.lng*f)/f,x=Math.round(n.lat*f)/f,w=this._map.getBearing(),P=this._map.getPitch(),S="";if(S+=t?`/${y}/${x}/${a}`:`${a}/${x}/${y}`,(w||P)&&(S+="/"+Math.round(10*w)/10),P&&(S+=`/${Math.round(P)}`),this._hashName){let E=this._hashName,C=!1,z=window.location.hash.slice(1).split("&").map((B=>{let N=B.split("=")[0];return N===E?(C=!0,`${N}=${S}`):B})).filter((B=>B));return C||z.push(`${E}=${S}`),`#${z.join("&")}`}return`#${S}`}_isValidHash(t){if(t.length<3||t.some(isNaN))return!1;try{new p.W(+t[2],+t[1])}catch{return!1}let n=+t[0],a=+(t[3]||0),c=+(t[4]||0);return n>=this._map.getMinZoom()&&n<=this._map.getMaxZoom()&&a>=-180&&a<=180&&c>=this._map.getMinPitch()&&c<=this._map.getMaxPitch()}}let no={linearity:.3,easing:p.cv(0,0,.3,1)},ji=p.e({deceleration:2500,maxSpeed:1400},no),Ji=p.e({deceleration:20,maxSpeed:1400},no),Wc=p.e({deceleration:1e3,maxSpeed:360},no),Qi=p.e({deceleration:1e3,maxSpeed:90},no),iu=p.e({deceleration:1e3,maxSpeed:360},no);class ru{constructor(t){this._map=t,this.clear()}clear(){this._inertiaBuffer=[]}record(t){this._drainInertiaBuffer(),this._inertiaBuffer.push({time:Xe(),settings:t})}_drainInertiaBuffer(){let t=this._inertiaBuffer,n=Xe();for(;t.length>0&&n-t[0].time>160;)t.shift()}_onMoveEnd(t){if(this._drainInertiaBuffer(),this._inertiaBuffer.length<2)return;let n={zoom:0,bearing:0,pitch:0,roll:0,pan:new p.P(0,0),pinchAround:void 0,around:void 0};for(let{settings:f}of this._inertiaBuffer)n.zoom+=f.zoomDelta||0,n.bearing+=f.bearingDelta||0,n.pitch+=f.pitchDelta||0,n.roll+=f.rollDelta||0,f.panDelta&&n.pan._add(f.panDelta),f.around&&(n.around=f.around),f.pinchAround&&(n.pinchAround=f.pinchAround);let a=this._inertiaBuffer[this._inertiaBuffer.length-1].time-this._inertiaBuffer[0].time,c={};if(n.pan.mag()){let f=nr(n.pan.mag(),a,p.e({},ji,t||{})),y=n.pan.mult(f.amount/n.pan.mag()),x=this._map.cameraHelper.handlePanInertia(y,this._map.transform);c.center=x.easingCenter,c.offset=x.easingOffset,qo(c,f)}if(n.zoom){let f=nr(n.zoom,a,Ji);c.zoom=p.cw(this._map.transform.zoom+f.amount,this._map.getZoomSnap(),f.amount),qo(c,f)}if(n.bearing){let f=nr(n.bearing,a,Wc);c.bearing=this._map.transform.bearing+p.al(f.amount,-179,179),qo(c,f)}if(n.pitch){let f=nr(n.pitch,a,Qi);c.pitch=this._map.transform.pitch+f.amount,qo(c,f)}if(n.roll){let f=nr(n.roll,a,iu);c.roll=this._map.transform.roll+p.al(f.amount,-179,179),qo(c,f)}if(c.zoom||c.bearing){let f=n.pinchAround===void 0?n.around:n.pinchAround;c.around=f?this._map.unproject(f):this._map.getCenter()}return this.clear(),p.e(c,{noMoveStart:!0})}}function qo(u,t){(!u.duration||u.durationn.unproject(w))),x=f.reduce(((w,P,S,E)=>w.add(P.div(E.length))),new p.P(0,0));super(t,{points:f,point:x,lngLats:y,lngLat:n.unproject(x),originalEvent:a}),this._defaultPrevented=!1}}class Hc extends p.n{preventDefault(){this._defaultPrevented=!0}get defaultPrevented(){return this._defaultPrevented}constructor(t,n,a){super(t,{originalEvent:a}),this._defaultPrevented=!1}}class nu{constructor(t,n){this._map=t,this._clickTolerance=n.clickTolerance}reset(){delete this._mousedownPos}wheel(t){return this._firePreventable(new Hc(t.type,this._map,t))}mousedown(t,n){return this._mousedownPos=n,this._firePreventable(new zi(t.type,this._map,t))}mouseup(t){this._map.fire(new zi(t.type,this._map,t))}click(t,n){this._mousedownPos&&this._mousedownPos.dist(n)>=this._clickTolerance||this._map.fire(new zi(t.type,this._map,t))}dblclick(t){return this._firePreventable(new zi(t.type,this._map,t))}mouseover(t){this._map.fire(new zi(t.type,this._map,t))}mouseout(t){this._map.fire(new zi(t.type,this._map,t))}touchstart(t){return this._firePreventable(new Wo(t.type,this._map,t))}touchmove(t){this._map.fire(new Wo(t.type,this._map,t))}touchend(t){this._map.fire(new Wo(t.type,this._map,t))}touchcancel(t){this._map.fire(new Wo(t.type,this._map,t))}_firePreventable(t){if(this._map.fire(t),t.defaultPrevented)return{}}isEnabled(){return!0}isActive(){return!1}enable(){}disable(){}}class Xc{constructor(t){this._map=t}reset(){this._delayContextMenu=!1,this._ignoreContextMenu=!0,delete this._contextMenuEvent}mousemove(t){this._map.fire(new zi(t.type,this._map,t))}mousedown(){this._delayContextMenu=!0,this._ignoreContextMenu=!1}mouseup(){this._delayContextMenu=!1,this._contextMenuEvent&&(this._map.fire(new zi("contextmenu",this._map,this._contextMenuEvent)),delete this._contextMenuEvent)}contextmenu(t){this._delayContextMenu?this._contextMenuEvent=t:this._ignoreContextMenu||this._map.fire(new zi(t.type,this._map,t)),this._map.listens("contextmenu")&&t.preventDefault()}isEnabled(){return!0}isActive(){return!1}enable(){}disable(){}}class fr{constructor(t){this._map=t}get transform(){return this._map._requestedCameraState||this._map.transform}get center(){return{lng:this.transform.center.lng,lat:this.transform.center.lat}}get zoom(){return this.transform.zoom}get pitch(){return this.transform.pitch}get bearing(){return this.transform.bearing}unproject(t){return this.transform.screenPointToLocation(p.P.convert(t),this._map.terrain)}}class or{constructor(t,n){this._map=t,this._tr=new fr(t),this._el=t.getCanvasContainer(),this._container=t.getContainer(),this._clickTolerance=n.clickTolerance||1,n.boxZoom&&typeof n.boxZoom=="object"&&(this._boxZoomEnd=n.boxZoom.boxZoomEnd)}isEnabled(){return!!this._enabled}isActive(){return!!this._active}enable(){this.isEnabled()||(this._enabled=!0)}disable(){this.isEnabled()&&(this._enabled=!1)}mousedown(t,n){this.isEnabled()&&t.shiftKey&&t.button===0&&(pe.disableDrag(),this._startPos=this._lastPos=n,this._active=!0)}mousemoveWindow(t,n){if(!this._active)return;let a=n;if(this._lastPos.equals(a)||!this._box&&a.dist(this._startPos)f.fitScreenCoordinates(a,c,this._tr.bearing,{linear:!0})};this._fireEvent("boxzoomcancel",t)}keydown(t){this._active&&t.keyCode===27&&(this.reset(),this._fireEvent("boxzoomcancel",t))}reset(){this._active=!1,this._container.classList.remove("maplibregl-crosshair"),this._box&&(this._box.remove(),this._box=null),pe.enableDrag(),delete this._startPos,delete this._lastPos}_fireEvent(t,n){return this._map.fire(new p.n(t,{originalEvent:n}))}}function Pe(u,t){if(u.length!==t.length)throw new Error(`The number of touches and points are not equal - touches ${u.length}, points ${t.length}`);let n={};for(let a=0;athis.numTouches)&&(this.aborted=!0),this.aborted||(this.startTime===void 0&&(this.startTime=t.timeStamp),a.length===this.numTouches&&(this.centroid=(function(c){let f=new p.P(0,0);for(let y of c)f._add(y);return f.div(c.length)})(n),this.touches=Pe(a,n)))}touchmove(t,n,a){if(this.aborted||!this.centroid)return;let c=Pe(a,n);for(let f in this.touches){let y=c[f];(!y||y.dist(this.touches[f])>30)&&(this.aborted=!0)}}touchend(t,n,a){if((!this.centroid||t.timeStamp-this.startTime>500)&&(this.aborted=!0),a.length===0){let c=!this.aborted&&this.centroid;if(this.reset(),c)return c}}}class Ho{constructor(t){this.singleTap=new Yc(t),this.numTaps=t.numTaps,this.reset()}reset(){this.lastTime=1/0,delete this.lastTap,this.count=0,this.singleTap.reset()}touchstart(t,n,a){this.singleTap.touchstart(t,n,a)}touchmove(t,n,a){this.singleTap.touchmove(t,n,a)}touchend(t,n,a){let c=this.singleTap.touchend(t,n,a);if(c){let f=t.timeStamp-this.lastTime<500,y=!this.lastTap||this.lastTap.dist(c)<30;if(f&&y||this.reset(),this.count++,this.lastTime=t.timeStamp,this.lastTap=c,this.count===this.numTaps)return this.reset(),c}}}class Kc{constructor(t){this._tr=new fr(t),this._zoomIn=new Ho({numTouches:1,numTaps:2}),this._zoomOut=new Ho({numTouches:2,numTaps:1}),this.reset()}reset(){this._active=!1,this._zoomIn.reset(),this._zoomOut.reset()}touchstart(t,n,a){this._zoomIn.touchstart(t,n,a),this._zoomOut.touchstart(t,n,a)}touchmove(t,n,a){this._zoomIn.touchmove(t,n,a),this._zoomOut.touchmove(t,n,a)}touchend(t,n,a){let c=this._zoomIn.touchend(t,n,a),f=this._zoomOut.touchend(t,n,a),y=this._tr;return c?(this._active=!0,t.preventDefault(),setTimeout((()=>this.reset()),0),{cameraAnimation:x=>x.easeTo({duration:300,zoom:p.cw(y.zoom+1,x.getZoomSnap()),around:y.unproject(c)},{originalEvent:t})}):f?(this._active=!0,t.preventDefault(),setTimeout((()=>this.reset()),0),{cameraAnimation:x=>x.easeTo({duration:300,zoom:p.cw(y.zoom-1,x.getZoomSnap()),around:y.unproject(f)},{originalEvent:t})}):void 0}touchcancel(){this.reset()}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}class mr{constructor(t){this._enabled=!!t.enable,this._moveStateManager=t.moveStateManager,this._clickTolerance=t.clickTolerance||1,this._moveFunction=t.move,this._activateOnStart=!!t.activateOnStart,t.assignEvents(this),this.reset()}reset(t){this._active=!1,this._moved=!1,delete this._lastPoint,this._moveStateManager.endMove(t)}_move(...t){let n=this._moveFunction(...t);if(n.bearingDelta||n.pitchDelta||n.rollDelta||n.around||n.panDelta)return this._active=!0,n}dragStart(t,n){this.isEnabled()&&!this._lastPoint&&this._moveStateManager.isValidStartEvent(t)&&(this._moveStateManager.startMove(t),this._lastPoint=Array.isArray(n)?n[0]:n,this._activateOnStart&&this._lastPoint&&(this._active=!0))}dragMove(t,n){if(!this.isEnabled())return;let a=this._lastPoint;if(!a)return;if(t.preventDefault(),!this._moveStateManager.isValidMoveEvent(t))return void this.reset(t);let c=Array.isArray(n)?n[0]:n;return!this._moved&&c.dist(a)!0}),n=new Jc){this.mouseMoveStateManager=t,this.oneFingerTouchMoveStateManager=n}_executeRelevantHandler(t,n,a){return t instanceof MouseEvent?n(t):typeof TouchEvent<"u"&&t instanceof TouchEvent?a(t):void 0}startMove(t){this._executeRelevantHandler(t,(n=>{this.mouseMoveStateManager.startMove(n)}),(n=>{this.oneFingerTouchMoveStateManager.startMove(n)}))}endMove(t){this._executeRelevantHandler(t,(n=>{this.mouseMoveStateManager.endMove(n)}),(n=>{this.oneFingerTouchMoveStateManager.endMove(n)}))}isValidStartEvent(t){return this._executeRelevantHandler(t,(n=>this.mouseMoveStateManager.isValidStartEvent(n)),(n=>this.oneFingerTouchMoveStateManager.isValidStartEvent(n)))}isValidMoveEvent(t){return this._executeRelevantHandler(t,(n=>this.mouseMoveStateManager.isValidMoveEvent(n)),(n=>this.oneFingerTouchMoveStateManager.isValidMoveEvent(n)))}isValidEndEvent(t){return this._executeRelevantHandler(t,(n=>this.mouseMoveStateManager.isValidEndEvent(n)),(n=>this.oneFingerTouchMoveStateManager.isValidEndEvent(n)))}}let qs=u=>{u.mousedown=u.dragStart,u.mousemoveWindow=u.dragMove,u.mouseup=u.dragEnd,u.contextmenu=t=>{t.preventDefault()}};class Qc{constructor(t,n){this._clickTolerance=t.clickTolerance||1,this._map=n,this.reset()}reset(){this._active=!1,this._touches={},this._sum=new p.P(0,0)}_shouldBePrevented(t){return t<(this._map.cooperativeGestures.isEnabled()?2:1)}touchstart(t,n,a){return this._calculateTransform(t,n,a)}touchmove(t,n,a){if(this._active){if(!this._shouldBePrevented(a.length))return t.preventDefault(),this._calculateTransform(t,n,a);this._map.cooperativeGestures.notifyGestureBlocked("touch_pan",t)}}touchend(t,n,a){this._calculateTransform(t,n,a),this._active&&this._shouldBePrevented(a.length)&&this.reset()}touchcancel(){this.reset()}_calculateTransform(t,n,a){a.length>0&&(this._active=!0);let c=Pe(a,n),f=new p.P(0,0),y=new p.P(0,0),x=0;for(let P in c){let S=c[P],E=this._touches[P];E&&(f._add(S),y._add(S.sub(E)),x++,c[P]=S)}if(this._touches=c,this._shouldBePrevented(x)||!y.mag())return;let w=y.div(x);return this._sum._add(w),this._sum.mag()Math.abs(u.x)}class gr extends wl{constructor(t){super(),this._currentTouchCount=0,this._map=t}reset(){super.reset(),this._valid=void 0,delete this._firstMove,delete this._lastPoints}touchstart(t,n,a){super.touchstart(t,n,a),this._currentTouchCount=a.length}_start(t){this._lastPoints=t,Sl(t[0].sub(t[1]))&&(this._valid=!1)}_move(t,n,a){if(this._map.cooperativeGestures.isEnabled()&&this._currentTouchCount<3)return;let c=t[0].sub(this._lastPoints[0]),f=t[1].sub(this._lastPoints[1]);return this._valid=this.gestureBeginsVertically(c,f,a.timeStamp),this._valid?(this._lastPoints=t,this._active=!0,{pitchDelta:(c.y+f.y)/2*-.5}):void 0}gestureBeginsVertically(t,n,a){if(this._valid!==void 0)return this._valid;let c=t.mag()>=2,f=n.mag()>=2;if(!c&&!f)return;if(!c||!f)return this._firstMove===void 0&&(this._firstMove=a),a-this._firstMove<100&&void 0;let y=t.y>0==n.y>0;return Sl(t)&&Sl(n)&&y}}let ct={panStep:100,bearingStep:15,pitchStep:10};class ih{constructor(t){this._tr=new fr(t);let n=ct;this._panStep=n.panStep,this._bearingStep=n.bearingStep,this._pitchStep=n.pitchStep,this._rotationDisabled=!1}reset(){this._active=!1}keydown(t){if(t.altKey||t.ctrlKey||t.metaKey)return;let n=0,a=0,c=0,f=0,y=0;switch(t.keyCode){case 61:case 107:case 171:case 187:n=1;break;case 189:case 109:case 173:n=-1;break;case 37:t.shiftKey?a=-1:(t.preventDefault(),f=-1);break;case 39:t.shiftKey?a=1:(t.preventDefault(),f=1);break;case 38:t.shiftKey?c=1:(t.preventDefault(),y=-1);break;case 40:t.shiftKey?c=-1:(t.preventDefault(),y=1);break;default:return}return this._rotationDisabled&&(a=0,c=0),{cameraAnimation:x=>{let w=this._tr;x.easeTo({duration:300,easeId:"keyboardHandler",easing:Hs,zoom:n?p.cw(w.zoom+n*(t.shiftKey?2:1),x.getZoomSnap()):w.zoom,bearing:w.bearing+a*this._bearingStep,pitch:w.pitch+c*this._pitchStep,offset:[-f*this._panStep,-y*this._panStep],center:w.center},{originalEvent:t})}}}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}disableRotation(){this._rotationDisabled=!0}enableRotation(){this._rotationDisabled=!1}}function Hs(u){return u*(2-u)}let Yo=4.000244140625,Il=1/450;class Ml{constructor(t,n){this._onTimeout=a=>{this._type="wheel",this._delta-=this._lastValue,this._active||this._start(a)},this._map=t,this._tr=new fr(t),this._triggerRenderFrame=n,this._delta=0,this._defaultZoomRate=.01,this._wheelZoomRate=Il}setZoomRate(t){this._defaultZoomRate=t}setWheelZoomRate(t){this._wheelZoomRate=t}isEnabled(){return!!this._enabled}isActive(){return!!this._active||this._finishTimeout!==void 0}isZooming(){return!!this._zooming}enable(t){this.isEnabled()||(this._enabled=!0,this._aroundCenter=!!t&&t.around==="center")}disable(){this.isEnabled()&&(this._enabled=!1)}_shouldBePrevented(t){return!!this._map.cooperativeGestures.isEnabled()&&!(t.ctrlKey||this._map.cooperativeGestures.isBypassed(t))}wheel(t){if(!this.isEnabled())return;if(this._shouldBePrevented(t))return void this._map.cooperativeGestures.notifyGestureBlocked("wheel_zoom",t);let n=t.deltaMode===WheelEvent.DOM_DELTA_LINE?40*t.deltaY:t.deltaY,a=Xe(),c=a-(this._lastWheelEventTime||0);this._lastWheelEventTime=a,n!==0&&n%Yo==0?this._type="wheel":n!==0&&Math.abs(n)<4?this._type="trackpad":c>400?(this._type=null,this._lastValue=n,this._timeout=setTimeout(this._onTimeout,40,t)):this._type||(this._type=Math.abs(c*n)<200?"trackpad":"wheel",this._timeout&&(clearTimeout(this._timeout),this._timeout=null,n+=this._lastValue)),t.shiftKey&&n&&(n/=4),this._type&&(this._lastWheelEvent=t,this._delta-=n,this._active||this._start(t)),t.preventDefault()}_start(t){if(!this._delta)return;this._needsRerender=!1,this._active=!0,this.isZooming()||(this._zooming=!0),this._finishTimeout&&(clearTimeout(this._finishTimeout),delete this._finishTimeout);let n=pe.mousePos(this._map.getCanvas(),t),a=this._tr;this._aroundPoint=this._aroundCenter?a.transform.locationToScreenPoint(p.W.convert(a.center)):n,this._needsRerender||(this._needsRerender=!0,this._triggerRenderFrame())}renderFrame(){if(!this._needsRerender||(this._needsRerender=!1,!this.isActive()))return;let t=this._tr.transform;if(typeof this._lastExpectedZoom=="number"){let x=t.zoom-this._lastExpectedZoom;typeof this._startZoom=="number"&&(this._startZoom+=x),typeof this._targetZoom=="number"&&(this._targetZoom+=x)}if(this._delta!==0){let x=this._type==="wheel"&&Math.abs(this._delta)>Yo?this._wheelZoomRate:this._defaultZoomRate,w=2/(1+Math.exp(-Math.abs(this._delta*x)));this._delta<0&&w!==0&&(w=1/w);let P=typeof this._targetZoom!="number"?t.scale:p.ao(this._targetZoom),S=t.applyConstrain(t.getCameraLngLat(),p.ar(P*w)).zoom,E=this._map.getZoomSnap();if(this._type==="wheel"&&E>0){let C=p.cw(t.zoom,E);this._targetZoom=p.cw(S,E,S-C)}else this._targetZoom=S;this._type==="wheel"&&(this._startZoom=t.zoom,this._easing=this._smoothOutEasing(200)),this._delta=0}let n=typeof this._targetZoom!="number"?t.zoom:this._targetZoom,a=this._startZoom,c=this._easing,f,y=!1;if(this._type==="wheel"&&a&&c){let x=Xe()-this._lastWheelEventTime,w=Math.min((x+5)/200,1),P=c(w);f=p.H.number(a,n,P),w<1?this._needsRerender=!0:y=!0}else f=n,y=!0;return this._active=!0,y&&(this._active=!1,this._finishTimeout=setTimeout((()=>{this._zooming=!1,this._triggerRenderFrame(),delete this._targetZoom,delete this._lastExpectedZoom,delete this._finishTimeout}),200)),this._lastExpectedZoom=f,{noInertia:!0,needsRenderFrame:!y,zoomDelta:f-t.zoom,around:this._aroundPoint,originalEvent:this._lastWheelEvent}}_smoothOutEasing(t){let n=p.cy;if(this._prevEase){let a=this._prevEase,c=(Xe()-a.start)/a.duration,f=a.easing(c+.01)-a.easing(c),y=.27/Math.sqrt(f*f+1e-4)*.01,x=Math.sqrt(.0729-y*y);n=p.cv(y,x,.25,1)}return this._prevEase={start:Xe(),duration:t,easing:n},n}reset(){this._active=!1,this._zooming=!1,delete this._targetZoom,delete this._lastExpectedZoom,this._finishTimeout&&(clearTimeout(this._finishTimeout),delete this._finishTimeout)}}class El{constructor(t,n){this._clickZoom=t,this._tapZoom=n}enable(){this._clickZoom.enable(),this._tapZoom.enable()}disable(){this._clickZoom.disable(),this._tapZoom.disable()}isEnabled(){return this._clickZoom.isEnabled()&&this._tapZoom.isEnabled()}isActive(){return this._clickZoom.isActive()||this._tapZoom.isActive()}}class rh{constructor(t){this._tr=new fr(t),this.reset()}reset(){this._active=!1}dblclick(t,n){return t.preventDefault(),{cameraAnimation:a=>{a.easeTo({duration:300,zoom:p.cw(this._tr.zoom+(t.shiftKey?-1:1),a.getZoomSnap()),around:this._tr.unproject(n)},{originalEvent:t})}}}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}class su{constructor(){this._tap=new Ho({numTouches:1,numTaps:1}),this._zoomRate=1,this.reset()}setZoomRate(t){this._zoomRate=t??1}reset(){this._active=!1,delete this._swipePoint,delete this._swipeTouch,delete this._tapTime,delete this._tapPoint,this._tap.reset()}touchstart(t,n,a){if(!this._swipePoint)if(this._tapTime){let c=n[0],f=t.timeStamp-this._tapTime<500,y=this._tapPoint.dist(c)<30;f&&y?a.length>0&&(this._swipePoint=c,this._swipeTouch=a[0].identifier):this.reset()}else this._tap.touchstart(t,n,a)}touchmove(t,n,a){if(this._tapTime){if(this._swipePoint){if(a[0].identifier!==this._swipeTouch)return;let c=n[0],f=c.y-this._swipePoint.y;return this._swipePoint=c,t.preventDefault(),this._active=!0,{zoomDelta:f/128*this._zoomRate}}}else this._tap.touchmove(t,n,a)}touchend(t,n,a){if(this._tapTime)this._swipePoint&&a.length===0&&this.reset();else{let c=this._tap.touchend(t,n,a);c&&(this._tapTime=t.timeStamp,this._tapPoint=c)}}touchcancel(){this.reset()}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}class er{constructor(t,n,a){this._el=t,this._mousePan=n,this._touchPan=a}enable(t){this._inertiaOptions=t||{},this._mousePan.enable(),this._touchPan.enable(),this._el.classList.add("maplibregl-touch-drag-pan")}disable(){this._mousePan.disable(),this._touchPan.disable(),this._el.classList.remove("maplibregl-touch-drag-pan")}isEnabled(){return this._mousePan.isEnabled()&&this._touchPan.isEnabled()}isActive(){return this._mousePan.isActive()||this._touchPan.isActive()}}class Ko{constructor(t,n,a,c){this._pitchWithRotate=t.pitchWithRotate,this._rollEnabled=t.rollEnabled,this._mouseRotate=n,this._mousePitch=a,this._mouseRoll=c}enable(){this._mouseRotate.enable(),this._pitchWithRotate&&this._mousePitch.enable(),this._rollEnabled&&this._mouseRoll.enable()}disable(){this._mouseRotate.disable(),this._mousePitch.disable(),this._mouseRoll.disable()}isEnabled(){return this._mouseRotate.isEnabled()&&(!this._pitchWithRotate||this._mousePitch.isEnabled())&&(!this._rollEnabled||this._mouseRoll.isEnabled())}isActive(){return this._mouseRotate.isActive()||this._mousePitch.isActive()||this._mouseRoll.isActive()}}class Ie{constructor(t,n,a,c){this._el=t,this._touchZoom=n,this._touchRotate=a,this._tapDragZoom=c,this._rotationDisabled=!1,this._enabled=!0}enable(t){this._touchZoom.enable(t),this._rotationDisabled||this._touchRotate.enable(t),this._tapDragZoom.enable(),this._el.classList.add("maplibregl-touch-zoom-rotate")}disable(){this._touchZoom.disable(),this._touchRotate.disable(),this._tapDragZoom.disable(),this._el.classList.remove("maplibregl-touch-zoom-rotate")}isEnabled(){return this._touchZoom.isEnabled()&&(this._rotationDisabled||this._touchRotate.isEnabled())&&this._tapDragZoom.isEnabled()}isActive(){return this._touchZoom.isActive()||this._touchRotate.isActive()||this._tapDragZoom.isActive()}setZoomRate(t){this._touchZoom.setZoomRate(t),this._tapDragZoom.setZoomRate(t)}setZoomThreshold(t){this._touchZoom.setZoomThreshold(t)}disableRotation(){this._rotationDisabled=!0,this._touchRotate.disable()}enableRotation(){this._rotationDisabled=!1,this._touchZoom.isEnabled()&&this._touchRotate.enable()}}class Ce{constructor(t,n){this._bypassKey=navigator.userAgent.includes("Mac")?"metaKey":"ctrlKey",this._map=t,this._options=n,this._enabled=!1}isActive(){return!1}reset(){}_setupUI(){if(this._container)return;let t=this._map.getCanvasContainer();t.classList.add("maplibregl-cooperative-gestures"),this._container=pe.create("div","maplibregl-cooperative-gesture-screen",t);let n=this._map._getUIString("CooperativeGesturesHandler.WindowsHelpText");this._bypassKey==="metaKey"&&(n=this._map._getUIString("CooperativeGesturesHandler.MacHelpText"));let a=this._map._getUIString("CooperativeGesturesHandler.MobileHelpText"),c=document.createElement("div");c.className="maplibregl-desktop-message",c.textContent=n,this._container.appendChild(c);let f=document.createElement("div");f.className="maplibregl-mobile-message",f.textContent=a,this._container.appendChild(f),this._container.setAttribute("aria-hidden","true")}_destroyUI(){this._container&&(this._container.remove(),this._map.getCanvasContainer().classList.remove("maplibregl-cooperative-gestures")),delete this._container}enable(){this._setupUI(),this._enabled=!0}disable(){this._enabled=!1,this._destroyUI()}isEnabled(){return this._enabled}isBypassed(t){return t[this._bypassKey]}notifyGestureBlocked(t,n){this._enabled&&(this._map.fire(new p.n("cooperativegestureprevented",{gestureType:t,originalEvent:n})),this._container.classList.add("maplibregl-show"),setTimeout((()=>{this._container.classList.remove("maplibregl-show")}),100))}}let Or=u=>u.zoom||u.drag||u.roll||u.pitch||u.rotate;class nh extends p.n{}function oo(u){var t;return((t=u.panDelta)===null||t===void 0?void 0:t.mag())||u.zoomDelta||u.bearingDelta||u.pitchDelta||u.rollDelta}class ui{get _ownerDocument(){var t;return((t=this._el)===null||t===void 0?void 0:t.ownerDocument)||document}get _ownerWindow(){var t,n;return((n=(t=this._el)===null||t===void 0?void 0:t.ownerDocument)===null||n===void 0?void 0:n.defaultView)||window}constructor(t,n){this.handleWindowEvent=c=>{this.handleEvent(c,`${c.type}Window`)},this.handleEvent=(c,f)=>{if(c.type==="blur")return void this.stop(!0);this._updatingCamera=!0;let y=c.type==="renderFrame"?void 0:c,x={needsRenderFrame:!1},w={},P={};for(let{handlerName:C,handler:z,allowed:B}of this._handlers){if(!z.isEnabled())continue;let N;if(this._blockedByActive(P,B,C))z.reset();else if(z[f||c.type]){if(p.cz(c,f||c.type)){let G=pe.mousePos(this._map.getCanvas(),c);N=z[f||c.type](c,G)}else if(p.cA(c,f||c.type)){let G=this._getMapTouches(c.touches),j=pe.touchPos(this._map.getCanvas(),G);N=z[f||c.type](c,j,G)}else p.cB(f||c.type)||(N=z[f||c.type](c));this.mergeHandlerResult(x,w,N,C,y),N?.needsRenderFrame&&this._triggerRenderFrame()}(N||z.isActive())&&(P[C]=z)}let S={};for(let C in this._previousActiveHandlers)P[C]||(S[C]=y);this._previousActiveHandlers=P,(Object.keys(S).length||oo(x))&&(this._changes.push([x,w,S]),this._triggerRenderFrame()),(Object.keys(P).length||oo(x))&&this._map._stop(!0),this._updatingCamera=!1;let{cameraAnimation:E}=x;E&&(this._inertia.clear(),this._fireEvents({},{},!0),this._changes=[],E(this._map))},this._map=t,this._el=this._map.getCanvasContainer(),this._handlers=[],this._handlersById={},this._changes=[],this._inertia=new ru(t),this._bearingSnap=n.bearingSnap,this._previousActiveHandlers={},this._eventsInProgress={},this._addDefaultHandlers(n);let a=this._el;this._listeners=[[a,"touchstart",{passive:!0}],[a,"touchmove",{passive:!1}],[a,"touchend",void 0],[a,"touchcancel",void 0],[a,"mousedown",void 0],[a,"mousemove",void 0],[a,"mouseup",void 0],[this._ownerDocument,"mousemove",{capture:!0}],[this._ownerDocument,"mouseup",void 0],[a,"mouseover",void 0],[a,"mouseout",void 0],[a,"dblclick",void 0],[a,"click",void 0],[a,"keydown",{capture:!1}],[a,"keyup",void 0],[a,"wheel",{passive:!1}],[a,"contextmenu",void 0],[this._ownerWindow,"blur",void 0]];for(let[c,f,y]of this._listeners)c.addEventListener(f,c===this._ownerDocument?this.handleWindowEvent:this.handleEvent,y)}destroy(){for(let[t,n,a]of this._listeners)t.removeEventListener(n,t===this._ownerDocument?this.handleWindowEvent:this.handleEvent,a)}_addDefaultHandlers(t){let n=this._map,a=n.getCanvasContainer();this._add("mapEvent",new nu(n,t));let c=n.boxZoom=new or(n,t);this._add("boxZoom",c),t.interactive&&t.boxZoom&&c.enable();let f=n.cooperativeGestures=new Ce(n,t.cooperativeGestures);this._add("cooperativeGestures",f),t.cooperativeGestures&&f.enable();let y=new Kc(n),x=new rh(n);n.doubleClickZoom=new El(x,y),this._add("tapZoom",y),this._add("clickZoom",x),t.interactive&&t.doubleClickZoom&&n.doubleClickZoom.enable();let w=new su;this._add("tapDragZoom",w);let P=n.touchPitch=new gr(n);this._add("touchPitch",P),t.interactive&&t.touchPitch&&n.touchPitch.enable(t.touchPitch);let S=()=>n.project(n.getCenter()),E=(function({enable:Z,clickTolerance:U,aroundCenter:H=!0,minPixelCenterThreshold:q=100,rotateDegreesPerPixelMoved:Q=.8},oe){let se=new bn({checkCorrectEvent:de=>de.button===0&&de.ctrlKey||de.button===2&&!de.ctrlKey});return new mr({clickTolerance:U,move:(de,ue)=>{let Se=oe();if(H&&Math.abs(Se.y-de.y)>q)return{bearingDelta:p.cx(new p.P(de.x,ue.y),ue,Se)};let ve=(ue.x-de.x)*Q;return H&&ue.yQ.button===0&&Q.ctrlKey||Q.button===2});return new mr({clickTolerance:U,move:(Q,oe)=>({pitchDelta:(oe.y-Q.y)*H}),moveStateManager:q,enable:Z,assignEvents:qs})})(t),z=(function({enable:Z,clickTolerance:U,rollDegreesPerPixelMoved:H=.3},q){let Q=new bn({checkCorrectEvent:oe=>oe.button===2&&oe.ctrlKey});return new mr({clickTolerance:U,move:(oe,se)=>{let de=q(),ue=(se.x-oe.x)*H;return se.yq.button===0&&!q.ctrlKey});return new mr({clickTolerance:U,move:(q,Q)=>({around:Q,panDelta:Q.sub(q)}),activateOnStart:!0,moveStateManager:H,enable:Z,assignEvents:qs})})(t),N=new Qc(t,n);n.dragPan=new er(a,B,N),this._add("mousePan",B),this._add("touchPan",N,["touchZoom","touchRotate"]),t.interactive&&t.dragPan&&n.dragPan.enable(t.dragPan);let G=new th,j=new eh;n.touchZoomRotate=new Ie(a,j,G,w),this._add("touchRotate",G,["touchPan","touchZoom"]),this._add("touchZoom",j,["touchPan","touchRotate"]),t.interactive&&t.touchZoomRotate&&n.touchZoomRotate.enable(t.touchZoomRotate),this._add("blockableMapEvent",new Xc(n));let $=n.scrollZoom=new Ml(n,(()=>this._triggerRenderFrame()));this._add("scrollZoom",$,["mousePan"]),t.interactive&&t.scrollZoom&&n.scrollZoom.enable(t.scrollZoom);let X=n.keyboard=new ih(n);this._add("keyboard",X),t.interactive&&t.keyboard&&n.keyboard.enable()}_add(t,n,a){this._handlers.push({handlerName:t,handler:n,allowed:a}),this._handlersById[t]=n}stop(t){if(!this._updatingCamera){for(let{handler:n}of this._handlers)n.reset();this._inertia.clear(),this._fireEvents({},{},t),this._changes=[]}}isActive(){for(let{handler:t}of this._handlers)if(t.isActive())return!0;return!1}isZooming(){return!!this._eventsInProgress.zoom||this._map.scrollZoom.isZooming()}isRotating(){return!!this._eventsInProgress.rotate}isMoving(){return!!Or(this._eventsInProgress)||this.isZooming()}_blockedByActive(t,n,a){for(let c in t)if(c!==a&&!n?.includes(c))return!0;return!1}_getMapTouches(t){let n=[];for(let a of t)this._el.contains(a.target)&&n.push(a);return n}mergeHandlerResult(t,n,a,c,f){if(!a)return;p.e(t,a);let y={handlerName:c,originalEvent:a.originalEvent||f};a.zoomDelta!==void 0&&(n.zoom=y),a.panDelta!==void 0&&(n.drag=y),a.rollDelta!==void 0&&(n.roll=y),a.pitchDelta!==void 0&&(n.pitch=y),a.bearingDelta!==void 0&&(n.rotate=y)}_applyChanges(){let t={},n={},a={};for(let[c,f,y]of this._changes)c.panDelta&&(t.panDelta=(t.panDelta||new p.P(0,0))._add(c.panDelta)),c.zoomDelta&&(t.zoomDelta=(t.zoomDelta||0)+c.zoomDelta),c.bearingDelta&&(t.bearingDelta=(t.bearingDelta||0)+c.bearingDelta),c.pitchDelta&&(t.pitchDelta=(t.pitchDelta||0)+c.pitchDelta),c.rollDelta&&(t.rollDelta=(t.rollDelta||0)+c.rollDelta),c.around!==void 0&&(t.around=c.around),c.pinchAround!==void 0&&(t.pinchAround=c.pinchAround),c.noInertia&&(t.noInertia=c.noInertia),p.e(n,f),p.e(a,y);this._updateMapTransform(t,n,a),this._changes=[]}_updateMapTransform(t,n,a){let c=this._map,f=c._getTransformForUpdate(),y=c.terrain;if(!(oo(t)||y&&this._terrainMovement))return void this._fireEvents(n,a,!0);c._stop(!0);let{panDelta:x,zoomDelta:w,bearingDelta:P,pitchDelta:S,rollDelta:E,around:C,pinchAround:z}=t;z!==void 0&&(C=z),C||(C=c.transform.centerPoint),y&&!f.isPointOnMapSurface(C)&&(C=f.centerPoint);let B={panDelta:x,zoomDelta:w,rollDelta:E,pitchDelta:S,bearingDelta:P,around:C};this._map.cameraHelper.useGlobeControls&&!f.isPointOnMapSurface(C)&&(C=f.centerPoint);let N=C.distSqr(f.centerPoint)<.01?f.center:f.screenPointToLocation(x?C.sub(x):C);this._handleMapControls({terrain:y,tr:f,deltasForHelper:B,preZoomAroundLoc:N,combinedEventsInProgress:n,panDelta:x}),c._applyUpdatedTransform(f),this._map._update(),t.noInertia||this._inertia.record(t),this._fireEvents(n,a,!0)}_handleMapControls({terrain:t,tr:n,deltasForHelper:a,preZoomAroundLoc:c,combinedEventsInProgress:f,panDelta:y}){let x=this._map.cameraHelper;if(x.handleMapControlsRollPitchBearingZoom(a,n),t)return x.useGlobeControls?(this._terrainMovement||!f.drag&&!f.zoom||(this._terrainMovement=!0,this._map._elevationFreeze=!0),void x.handleMapControlsPan(a,n,c)):this._terrainMovement||!f.drag&&!f.zoom?void(f.drag&&this._terrainMovement&&y?n.setCenter(n.screenPointToLocation(n.centerPoint.sub(y))):x.handleMapControlsPan(a,n,c)):(this._terrainMovement=!0,this._map._elevationFreeze=!0,void x.handleMapControlsPan(a,n,c));x.handleMapControlsPan(a,n,c)}_fireEvents(t,n,a){let c=Or(this._eventsInProgress),f=Or(t),y={};for(let E in t){let{originalEvent:C}=t[E];this._eventsInProgress[E]||(y[`${E}start`]=C),this._eventsInProgress[E]=t[E]}!c&&f&&this._fireEvent("movestart",f.originalEvent);for(let E in y)this._fireEvent(E,y[E]);f&&this._fireEvent("move",f.originalEvent);for(let E in t){let{originalEvent:C}=t[E];this._fireEvent(E,C)}let x={},w;for(let E in this._eventsInProgress){let{handlerName:C,originalEvent:z}=this._eventsInProgress[E];this._handlersById[C].isActive()||(delete this._eventsInProgress[E],w=n[C]||z,x[`${E}end`]=w)}for(let E in x)this._fireEvent(E,x[E]);let P=Or(this._eventsInProgress),S=(c||f)&&!P;if(S&&this._terrainMovement){this._map._elevationFreeze=!1,this._terrainMovement=!1;let E=this._map._getTransformForUpdate();this._map.getCenterClampedToGround()&&E.recalculateZoomAndCenter(this._map.terrain),this._map._applyUpdatedTransform(E)}if(a&&S){this._updatingCamera=!0;let E=this._inertia._onMoveEnd(this._map.dragPan._inertiaOptions),C=z=>z!==0&&-this._bearingSnap{delete this._frameId,this.handleEvent(new nh("renderFrame",{timeStamp:t})),this._applyChanges()}))}_triggerRenderFrame(){this._frameId===void 0&&(this._frameId=this._requestFrame())}}class oh extends p.E{constructor(t,n,a){super(),this._renderFrameCallback=()=>{let c=Math.min((Xe()-this._easeStart)/this._easeOptions.duration,1);this._onEaseFrame(this._easeOptions.easing(c)),c<1&&this._easeFrameId?this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback):this.stop()},this._moving=!1,this._zooming=!1,this.transform=t,this._bearingSnap=a.bearingSnap,this._zoomSnap=a.zoomSnap,this.cameraHelper=n,this.on("moveend",(()=>{delete this._requestedCameraState}))}migrateProjection(t,n){t.apply(this.transform,!0),this.transform=t,this.cameraHelper=n}getCenter(){return new p.W(this.transform.center.lng,this.transform.center.lat)}setCenter(t,n){return this.jumpTo({center:t},n)}getCenterElevation(){return this.transform.elevation}setCenterElevation(t,n){return this.jumpTo({elevation:t},n),this}getCenterClampedToGround(){return this._centerClampedToGround}setCenterClampedToGround(t){this._centerClampedToGround=t}panBy(t,n,a){return t=p.P.convert(t).mult(-1),this.panTo(this.transform.center,p.e({offset:t},n),a)}panTo(t,n,a){return this.easeTo(p.e({center:t},n),a)}getZoom(){return this.transform.zoom}setZoom(t,n){return this.jumpTo({zoom:t},n),this}zoomTo(t,n,a){return this.easeTo(p.e({zoom:t},n),a)}zoomIn(t,n){return this.zoomTo(p.cw(this.getZoom()+1,this._zoomSnap),t,n),this}zoomOut(t,n){return this.zoomTo(p.cw(this.getZoom()-1,this._zoomSnap),t,n),this}getVerticalFieldOfView(){return this.transform.fov}setVerticalFieldOfView(t,n){return t!=this.transform.fov&&(this.transform.setFov(t),this.fire(new p.n("movestart",n)).fire(new p.n("move",n)).fire(new p.n("moveend",n))),this}getBearing(){return this.transform.bearing}setZoomSnap(t){return this._zoomSnap=t,this}getZoomSnap(){return this._zoomSnap}setBearing(t,n){return this.jumpTo({bearing:t},n),this}getPadding(){return this.transform.padding}setPadding(t,n){return this.jumpTo({padding:t},n),this}rotateTo(t,n,a){return this.easeTo(p.e({bearing:t},n),a)}resetNorth(t,n){return this.rotateTo(0,p.e({duration:1e3},t),n),this}resetNorthPitch(t,n){return this.easeTo(p.e({bearing:0,pitch:0,roll:0,duration:1e3},t),n),this}snapToNorth(t,n){return Math.abs(this.getBearing()){N.easeFunc(G),this.terrain&&!t.freezeElevation&&this._updateElevation(G),this._applyUpdatedTransform(a),this._fireMoveEvents(n)}),(G=>{this.terrain&&t.freezeElevation&&this._finalizeElevation(),this._afterEase(n,G)}),t),this}_prepareEase(t,n,a={}){this._moving=!0,n||a.moving||this.fire(new p.n("movestart",t)),this._zooming&&!a.zooming&&this.fire(new p.n("zoomstart",t)),this._rotating&&!a.rotating&&this.fire(new p.n("rotatestart",t)),this._pitching&&!a.pitching&&this.fire(new p.n("pitchstart",t)),this._rolling&&!a.rolling&&this.fire(new p.n("rollstart",t))}_prepareElevation(t){this._elevationCenter=t,this._elevationStart=this.transform.elevation,this._elevationTarget=this.terrain.getElevationForLngLatZoom(t,this.transform.tileZoom),this._elevationFreeze=!0}_updateElevation(t){this._elevationStart!==void 0&&this._elevationCenter!==void 0||this._prepareElevation(this.transform.center),this.transform.setMinElevationForCurrentTile(this.terrain.getMinTileElevationForLngLatZoom(this._elevationCenter,this.transform.tileZoom));let n=this.terrain.getElevationForLngLatZoom(this._elevationCenter,this.transform.tileZoom);if(t<1&&n!==this._elevationTarget){let a=this._elevationTarget-this._elevationStart;this._elevationStart+=t*(a-(n-(a*t+this._elevationStart))/(1-t)),this._elevationTarget=n}this.transform.setElevation(p.H.number(this._elevationStart,this._elevationTarget,t))}_finalizeElevation(){this._elevationFreeze=!1,this.getCenterClampedToGround()&&this.transform.recalculateZoomAndCenter(this.terrain)}_getTransformForUpdate(){return this.transformCameraUpdate||this.terrain?(this._requestedCameraState||(this._requestedCameraState=this.transform.clone()),this._requestedCameraState):this.transform}_elevateCameraIfInsideTerrain(t){if(!this.terrain&&t.elevation>=0&&t.pitch<=90)return{};let n=t.getCameraLngLat(),a=t.getCameraAltitude(),c=this.terrain?this.terrain.getElevationForLngLatZoom(n,t.zoom):0;if(athis._elevateCameraIfInsideTerrain(c))),this.transformCameraUpdate&&n.push((c=>this.transformCameraUpdate(c))),!n.length)return;let a=t.clone();for(let c of n){let f=a.clone(),{center:y,zoom:x,roll:w,pitch:P,bearing:S,elevation:E}=c(f);y&&f.setCenter(y),E!==void 0&&f.setElevation(E),x!==void 0&&f.setZoom(x),w!==void 0&&f.setRoll(w),P!==void 0&&f.setPitch(P),S!==void 0&&f.setBearing(S),a.apply(f,!1)}this.transform.apply(a,!1)}_fireMoveEvents(t){this.fire(new p.n("move",t)),this._zooming&&this.fire(new p.n("zoom",t)),this._rotating&&this.fire(new p.n("rotate",t)),this._pitching&&this.fire(new p.n("pitch",t)),this._rolling&&this.fire(new p.n("roll",t))}_afterEase(t,n){if(this._easeId&&n&&this._easeId===n)return;delete this._easeId;let a=this._zooming,c=this._rotating,f=this._pitching,y=this._rolling;this._moving=!1,this._zooming=!1,this._rotating=!1,this._pitching=!1,this._rolling=!1,this._padding=!1,a&&this.fire(new p.n("zoomend",t)),c&&this.fire(new p.n("rotateend",t)),f&&this.fire(new p.n("pitchend",t)),y&&this.fire(new p.n("rollend",t)),this.fire(new p.n("moveend",t))}flyTo(t,n){if(!t.essential&&qt.prefersReducedMotion){let ue=p.V(t,["center","zoom","bearing","pitch","roll","elevation","padding"]);return this.jumpTo(ue,n)}this.stop(),"zoom"in(t=p.e({offset:[0,0],speed:1.2,curve:1.42,easing:p.cy},t))&&this._zoomSnap&&(t.zoom=p.cw(t.zoom,this._zoomSnap));let a=this._getTransformForUpdate(),c=a.bearing,f=a.pitch,y=a.roll,x=a.padding,w="bearing"in t?this._normalizeBearing(t.bearing,c):c,P="pitch"in t?+t.pitch:f,S="roll"in t?this._normalizeBearing(t.roll,y):y,E="padding"in t?t.padding:a.padding,C=p.P.convert(t.offset),z=a.centerPoint.add(C),B=a.screenPointToLocation(z),N=this.cameraHelper.handleFlyTo(a,{bearing:w,pitch:P,roll:S,padding:E,locationAtOffset:B,offsetAsPoint:C,center:t.center,minZoom:t.minZoom,zoom:t.zoom}),G=t.curve,j=Math.max(a.width,a.height),$=j/N.scaleOfZoom,X=N.pixelPathLength;typeof N.scaleOfMinZoom=="number"&&(G=Math.sqrt(j/N.scaleOfMinZoom/X*2));let Z=G*G;function U(ue){let Se=($*$-j*j+(ue?-1:1)*Z*Z*X*X)/(2*(ue?$:j)*Z*X);return Math.log(Math.sqrt(Se*Se+1)-Se)}function H(ue){return(Math.exp(ue)-Math.exp(-ue))/2}function q(ue){return(Math.exp(ue)+Math.exp(-ue))/2}let Q=U(!1),oe=function(ue){return q(Q)/q(Q+G*ue)},se=function(ue){return j*((q(Q)*(H(Se=Q+G*ue)/q(Se))-H(Q))/Z)/X;var Se},de=(U(!0)-Q)/G;if(Math.abs(X)<2e-6||!isFinite(de)){if(Math.abs(j-$)<1e-6)return this.easeTo(t,n);let ue=$0,oe=Se=>Math.exp(ue*G*Se)}return t.duration="duration"in t?+t.duration:1e3*de/("screenSpeed"in t?+t.screenSpeed/G:+t.speed),t.maxDuration&&t.duration>t.maxDuration&&(t.duration=0),this._zooming=!0,this._rotating=c!==w,this._pitching=P!==f,this._rolling=S!==y,this._padding=!a.isPaddingEqual(E),this._prepareEase(n,!1),this.terrain&&this._prepareElevation(N.targetCenter),this._ease((ue=>{let Se=ue*de,ve=1/oe(Se),he=se(Se);this._rotating&&a.setBearing(p.H.number(c,w,ue)),this._pitching&&a.setPitch(p.H.number(f,P,ue)),this._rolling&&a.setRoll(p.H.number(y,S,ue)),this._padding&&(a.interpolatePadding(x,E,ue),z=a.centerPoint.add(C)),N.easeFunc(ue,ve,he,z),this.terrain&&!t.freezeElevation&&this._updateElevation(ue),this._applyUpdatedTransform(a),this._fireMoveEvents(n)}),(()=>{this.terrain&&t.freezeElevation&&this._finalizeElevation(),this._afterEase(n)}),t),this}isEasing(){return!!this._easeFrameId}stop(){return this._stop()}_stop(t,n){var a;if(this._easeFrameId&&(this._cancelRenderFrame(this._easeFrameId),delete this._easeFrameId,delete this._onEaseFrame),this._onEaseEnd){let c=this._onEaseEnd;delete this._onEaseEnd,c.call(this,n)}return t||(a=this.handlers)===null||a===void 0||a.stop(!1),this}_ease(t,n,a){a.animate===!1||a.duration===0?(t(1),n()):(this._easeStart=Xe(),this._easeOptions=a,this._onEaseFrame=t,this._onEaseEnd=n,this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback))}_normalizeBearing(t,n){t=p.X(t,-180,180);let a=Math.abs(t-n);return Math.abs(t-360-n)MapLibre'};class Ui{constructor(t=Xs){this._toggleAttribution=()=>{this._container.classList.contains("maplibregl-compact")&&(this._container.classList.contains("maplibregl-compact-show")?(this._container.setAttribute("open",""),this._container.classList.remove("maplibregl-compact-show")):(this._container.classList.add("maplibregl-compact-show"),this._container.removeAttribute("open")))},this._updateData=n=>{!n||n.sourceDataType!=="metadata"&&n.sourceDataType!=="visibility"&&n.dataType!=="style"&&n.type!=="terrain"||this._updateAttributions()},this._updateCompact=()=>{this._map.getCanvasContainer().offsetWidth<=640||this._compact?this._compact===!1?this._container.setAttribute("open",""):this._container.classList.contains("maplibregl-compact")||this._container.classList.contains("maplibregl-attrib-empty")||(this._container.setAttribute("open",""),this._container.classList.add("maplibregl-compact","maplibregl-compact-show")):(this._container.setAttribute("open",""),this._container.classList.contains("maplibregl-compact")&&this._container.classList.remove("maplibregl-compact","maplibregl-compact-show"))},this._updateCompactMinimize=()=>{this._container.classList.contains("maplibregl-compact")&&this._container.classList.contains("maplibregl-compact-show")&&this._container.classList.remove("maplibregl-compact-show")},this.options=t}getDefaultPosition(){return"bottom-right"}onAdd(t){return this._map=t,this._compact=this.options.compact,this._container=pe.create("details","maplibregl-ctrl maplibregl-ctrl-attrib"),this._compactButton=pe.create("summary","maplibregl-ctrl-attrib-button",this._container),this._compactButton.addEventListener("click",this._toggleAttribution),this._setElementTitle(this._compactButton,"ToggleAttribution"),this._innerContainer=pe.create("div","maplibregl-ctrl-attrib-inner",this._container),this._updateAttributions(),this._updateCompact(),this._map.on("styledata",this._updateData),this._map.on("sourcedata",this._updateData),this._map.on("terrain",this._updateData),this._map.on("resize",this._updateCompact),this._map.on("drag",this._updateCompactMinimize),this._container}onRemove(){this._container.remove(),this._map.off("styledata",this._updateData),this._map.off("sourcedata",this._updateData),this._map.off("terrain",this._updateData),this._map.off("resize",this._updateCompact),this._map.off("drag",this._updateCompactMinimize),this._map=void 0,this._compact=void 0,this._attribHTML=void 0}_setElementTitle(t,n){let a=this._map._getUIString(`AttributionControl.${n}`);t.title=a,t.setAttribute("aria-label",a)}_updateAttributions(){if(!this._map.style)return;let t=[];if(this.options.customAttribution&&(Array.isArray(this.options.customAttribution)?t=t.concat(this.options.customAttribution.map((c=>typeof c!="string"?"":c))):typeof this.options.customAttribution=="string"&&t.push(this.options.customAttribution)),this._map.style.stylesheet){let c=this._map.style.stylesheet;this.styleOwner=c.owner,this.styleId=c.id}let n=this._map.style.tileManagers;for(let c in n){let f=n[c];if(f.used||f.usedForTerrain){let y=f.getSource();y.attribution&&!t.includes(y.attribution)&&t.push(y.attribution)}}t=t.filter((c=>String(c).trim())),t.sort(((c,f)=>c.length-f.length)),t=t.filter(((c,f)=>{for(let y=f+1;y{let n=this._container.children;if(n.length){let a=n[0];this._map.getCanvasContainer().offsetWidth<=640||this._compact?this._compact!==!1&&a.classList.add("maplibregl-compact"):a.classList.remove("maplibregl-compact")}},this.options=t}getDefaultPosition(){return"bottom-left"}onAdd(t){var n;this._map=t,this._compact=(n=this.options)===null||n===void 0?void 0:n.compact,this._container=pe.create("div","maplibregl-ctrl");let a=pe.create("a","maplibregl-ctrl-logo");return a.target="_blank",a.rel="noopener nofollow",a.href="https://maplibre.org/",a.setAttribute("aria-label",this._map._getUIString("LogoControl.Title")),a.setAttribute("rel","noopener nofollow"),this._container.appendChild(a),this._container.style.display="block",this._map.on("resize",this._updateCompact),this._updateCompact(),this._container}onRemove(){this._container.remove(),this._map.off("resize",this._updateCompact),this._map=void 0,this._compact=void 0}}class au{constructor(){this._queue=[],this._id=0,this._cleared=!1,this._currentlyRunning=!1}add(t){let n=++this._id;return this._queue.push({callback:t,id:n,cancelled:!1}),n}remove(t){let n=this._currentlyRunning,a=n?this._queue.concat(n):this._queue;for(let c of a)if(c.id===t)return void(c.cancelled=!0)}run(t=0){if(this._currentlyRunning)throw new Error("Attempting to run(), but is already running.");let n=this._currentlyRunning=this._queue;this._queue=[];for(let a of n)if(!a.cancelled&&(a.callback(t),this._cleared))break;this._cleared=!1,this._currentlyRunning=!1}clear(){this._currentlyRunning&&(this._cleared=!0),this._queue=[]}}var lu=p.aS([{name:"a_pos3d",type:"Int16",components:3}]);class cu extends p.E{constructor(t){super(),this._lastTilesetChange=Xe(),this.tileManager=t,this._tiles={},this._renderableTilesKeys=[],this._sourceTileCache={},this.minzoom=0,this.maxzoom=22,this.deltaZoom=1,this.tileSize=t._source.tileSize*2**this.deltaZoom,t.usedForTerrain=!0,t.tileSize=this.tileSize}destruct(){this.tileManager.usedForTerrain=!1,this.tileManager.tileSize=null}getSource(){return this.tileManager._source}update(t,n){this.tileManager.update(t,n),this._renderableTilesKeys=[];let a={};for(let c of rn(t,{tileSize:this.tileSize,minzoom:this.minzoom,maxzoom:this.maxzoom,reparseOverscaled:!1,terrain:n,calculateTileZoom:this.tileManager._source.calculateTileZoom}))a[c.key]=!0,this._renderableTilesKeys.push(c.key),this._tiles[c.key]||(c.terrainRttPosMatrix32f=new Float64Array(16),p.c7(c.terrainRttPosMatrix32f,0,p.a6,p.a6,0,0,1),this._tiles[c.key]=new kn(c,this.tileSize),this._lastTilesetChange=Xe());for(let c in this._tiles)a[c]||delete this._tiles[c]}freeRtt(t){for(let n in this._tiles){let a=this._tiles[n];(!t||a.tileID.equals(t)||a.tileID.isChildOf(t)||t.isChildOf(a.tileID))&&(a.rtt=[])}}getRenderableTiles(){return this._renderableTilesKeys.map((t=>this.getTileByID(t)))}getTileByID(t){return this._tiles[t]}getTerrainCoords(t,n){return n?this._getTerrainCoordsForTileRanges(t,n):this._getTerrainCoordsForRegularTile(t)}_getTerrainCoordsForRegularTile(t){let n={};for(let a of this._renderableTilesKeys){let c=this._tiles[a].tileID,f=t.clone(),y=p.bj();if(c.canonical.equals(t.canonical))p.c7(y,0,p.a6,p.a6,0,0,1);else if(c.canonical.isChildOf(t.canonical)){let x=c.canonical.z-t.canonical.z,w=c.canonical.x-(c.canonical.x>>x<>x<>x;p.c7(y,0,S,S,0,0,1),p.Q(y,y,[-w*S,-P*S,0])}else{if(!t.canonical.isChildOf(c.canonical))continue;{let x=t.canonical.z-c.canonical.z,w=t.canonical.x-(t.canonical.x>>x<>x<>x;p.c7(y,0,p.a6,p.a6,0,0,1),p.Q(y,y,[w*S,P*S,0]),p.S(y,y,[1/2**x,1/2**x,0])}}f.terrainRttPosMatrix32f=new Float32Array(y),n[a]=f}return n}_getTerrainCoordsForTileRanges(t,n){let a={};for(let c of this._renderableTilesKeys){let f=this._tiles[c].tileID;if(!this._isWithinTileRanges(f,n))continue;let y=t.clone(),x=p.bj();if(f.canonical.z===t.canonical.z){let w=t.canonical.x-f.canonical.x+t.wrap*(1<t.canonical.z){let w=f.canonical.z-t.canonical.z,P=f.canonical.x-(f.canonical.x>>w<>w<>w),C=t.canonical.y-(f.canonical.y>>w),z=p.a6>>w;p.c7(x,0,z,z,0,0,1),p.Q(x,x,[-P*z+E*p.a6,-S*z+C*p.a6,0])}else{let w=t.canonical.z-f.canonical.z,P=t.canonical.x-(t.canonical.x>>w<>w<>w)-f.canonical.x,C=(t.canonical.y>>w)-f.canonical.y,z=p.a6<f.maxzoom&&(y=f.maxzoom),y=f.minzoom&&!x?.dem;)x=this.findTileInCaches(t.scaledTo(y--).key);return x}findTileInCaches(t){let n=this.tileManager.getTileByID(t);return n||(n=this.tileManager._outOfViewCache.getByKey(t),n)}anyTilesAfterTime(t=Date.now()){return this._lastTilesetChange>=t}_isWithinTileRanges(t,n){let a=n[t.canonical.z];return!!a&&(t.wrap>a.minWrap||t.wrap=a.minTileXWrapped&&t.canonical.x<=a.maxTileXWrapped&&t.canonical.y>=a.minTileY&&t.canonical.y<=a.maxTileY)}}class Jo{constructor(t,n,a){this._meshCache={},this.painter=t,this.tileManager=new cu(n),this.options=a,this.exaggeration=typeof a.exaggeration=="number"?a.exaggeration:1,this.qualityFactor=2,this.meshSize=128,this._demMatrixCache={},this.coordsIndex=[],this._coordsTextureSize=1024}destroy(){this._fbo&&(this._fbo.destroy(),this._fbo=null),this._fboCoordsTexture&&(this._fboCoordsTexture.destroy(),this._fboCoordsTexture=null),this._fboDepthTexture&&(this._fboDepthTexture.destroy(),this._fboDepthTexture=null),this._emptyDemTexture&&(this._emptyDemTexture.destroy(),this._emptyDemTexture=null),this._emptyDepthTexture&&(this._emptyDepthTexture.destroy(),this._emptyDepthTexture=null),this._coordsTexture&&(this._coordsTexture.destroy(),this._coordsTexture=null);for(let t in this._meshCache)this._meshCache[t].destroy();this._meshCache={},this.tileManager.destruct()}getDEMElevation(t,n,a,c=p.a6){var f;let y=t.normalizeCoordinates(n,a,c);if(!y)return 0;let x=this.getTerrainData(y.tileID),w=(f=x.tile)===null||f===void 0?void 0:f.dem;if(!w)return 0;let P=p.cC([],[y.x/c*p.a6,y.y/c*p.a6],x.u_terrain_matrix),S=[P[0]*w.dim,P[1]*w.dim],E=Math.floor(S[0]),C=Math.floor(S[1]),z=S[0]-E,B=S[1]-C;return w.get(E,C)*(1-z)*(1-B)+w.get(E+1,C)*z*(1-B)+w.get(E,C+1)*(1-z)*B+w.get(E+1,C+1)*z*B}getElevationForLngLatZoom(t,n){if(!p.cD(n,t.wrap()))return 0;let{tileID:a,mercatorX:c,mercatorY:f}=this._getOverscaledTileIDFromLngLatZoom(t,n);return this.getElevation(a,c%p.a6,f%p.a6,p.a6)}getElevationForLngLat(t,n){let a=rn(n,{maxzoom:this.tileManager.maxzoom,minzoom:this.tileManager.minzoom,tileSize:512,terrain:this}),c=0;for(let f of a)f.canonical.z>c&&(c=Math.min(f.canonical.z,this.tileManager.maxzoom));return this.getElevationForLngLatZoom(t,c)}getElevation(t,n,a,c=p.a6){return this.getDEMElevation(t,n,a,c)*this.exaggeration}getTerrainData(t){var n,a;if(!this._emptyDemTexture){let y=this.painter.context,x=new p.R({width:1,height:1},new Uint8Array(4));this._emptyDepthTexture=new p.T(y,x,y.gl.RGBA,{premultiply:!1}),this._emptyDemUnpack=[0,0,0,0],this._emptyDemTexture=new p.T(y,new p.R({width:1,height:1}),y.gl.RGBA,{premultiply:!1}),this._emptyDemTexture.bind(y.gl.NEAREST,y.gl.CLAMP_TO_EDGE),this._emptyDemMatrix=p.ap([])}let c=this.tileManager.getSourceTile(t,!0);if(c?.dem&&(!c.demTexture||c.needsTerrainPrepare)){let y=this.painter.context;c.demTexture=this.painter.getTileTexture(c.dem.stride),c.demTexture?c.demTexture.update(c.dem.getPixels(),{premultiply:!1}):c.demTexture=new p.T(y,c.dem.getPixels(),y.gl.RGBA,{premultiply:!1}),c.demTexture.bind(y.gl.NEAREST,y.gl.CLAMP_TO_EDGE),c.needsTerrainPrepare=!1}let f=c&&c.toString()+c.tileID.key+t.key;if(f&&!this._demMatrixCache[f]){let y=this.tileManager.getSource().maxzoom,x=t.canonical.z-c.tileID.canonical.z;t.overscaledZ>t.canonical.z&&(t.canonical.z>=y?x=t.canonical.z-y:p.w("cannot calculate elevation if elevation maxzoom > source.maxzoom"));let w=t.canonical.x-(t.canonical.x>>x<>x<>8<<4|f>>8,n[y+3]=0;let a=new p.R({width:this._coordsTextureSize,height:this._coordsTextureSize},new Uint8Array(n.buffer)),c=new p.T(t,a,t.gl.RGBA,{premultiply:!1});return c.bind(t.gl.NEAREST,t.gl.CLAMP_TO_EDGE),this._coordsTexture=c,c}pointCoordinate(t){this.painter.maybeDrawDepth(!0),this.painter.maybeDrawCoords();let n=new Uint8Array(4),a=this.painter.context,c=a.gl,f=Math.round(t.x*this.painter.pixelRatio/devicePixelRatio),y=Math.round(t.y*this.painter.pixelRatio/devicePixelRatio),x=Math.round(this.painter.height/devicePixelRatio);a.bindFramebuffer.set(this.getFramebuffer("coords").framebuffer),c.readPixels(f,x-y-1,1,1,c.RGBA,c.UNSIGNED_BYTE,n),a.bindFramebuffer.set(null);let w=n[0]+(n[2]>>4<<8),P=n[1]+((15&n[2])<<8),S=this.coordsIndex[255-n[3]],E=S&&this.tileManager.getTileByID(S);if(!E)return null;let C=this._coordsTextureSize,z=(1<0,c=a&&t.canonical.y===0,f=a&&t.canonical.y===(1<t.id!==n)),this._recentlyUsed.push(t.id)}stampObject(t){t.stamp=++this._stamp}getOrCreateFreeObject(){for(let n of this._recentlyUsed)if(!this._objects[n].inUse)return this._objects[n];if(this._objects.length>=this._size)throw new Error("No free RenderPool available, call freeAllObjects() required!");let t=this._createObject(this._objects.length);return this._objects.push(t),t}freeObject(t){t.inUse=!1}freeAllObjects(){for(let t of this._objects)this.freeObject(t)}isFull(){return!(this._objects.length!t.inUse))===!1}}let ht={background:!0,fill:!0,line:!0,raster:!0,hillshade:!0,"color-relief":!0};class sh{constructor(t,n){this.painter=t,this.terrain=n,this.pool=new mt(t.context,30,n.tileManager.tileSize*n.qualityFactor)}destruct(){this.pool.destruct()}getTexture(t){return this.pool.getObjectForId(t.rtt[this._stacks.length-1].id).texture}prepareForRender(t,n){var a,c,f;this._stacks=[],this._prevType=null,this._rttTiles=[],this._renderableTiles=this.terrain.tileManager.getRenderableTiles(),this._renderableLayerIds=t._order.filter((y=>!t._layers[y].isHidden(n))),this._coordsAscending={};for(let y in t.tileManagers){this._coordsAscending[y]={};let x=t.tileManagers[y].getVisibleCoordinates(),w=t.tileManagers[y].getSource(),P=w instanceof Ar?w.terrainTileRanges:null;for(let S of x){let E=this.terrain.tileManager.getTerrainCoords(S,P);for(let C in E)(f=this._coordsAscending[y])[C]||(f[C]=[]),this._coordsAscending[y][C].push(E[C])}}this._rttFingerprints={};for(let y of t._order){let x=t._layers[y],w=x.source;if(ht[x.type]&&!this._rttFingerprints[w]){this._rttFingerprints[w]={};let P=(c=(a=t.tileManagers[w])===null||a===void 0?void 0:a.getState().revision)!==null&&c!==void 0?c:0;for(let S in this._coordsAscending[w])this._rttFingerprints[w][S]=`${this._coordsAscending[w][S].map((E=>E.key)).sort().join()}#${P}`}}for(let y of this._renderableTiles)for(let x in this._rttFingerprints){let w=this._rttFingerprints[x][y.tileID.key];w&&w!==y.rttFingerprint[x]&&(y.rtt=[])}}renderLayer(t,n){if(t.isHidden(this.painter.transform.zoom))return!1;let a=Object.assign(Object.assign({},n),{isRenderingToTexture:!0}),c=t.type,f=this.painter,y=this._renderableLayerIds[this._renderableLayerIds.length-1]===t.id;if(ht[c]&&(this._prevType&&ht[this._prevType]||this._stacks.push([]),this._prevType=c,this._stacks[this._stacks.length-1].push(t.id),!y))return!0;if(ht[this._prevType]||ht[c]&&y){this._prevType=c;let x=this._stacks.length-1,w=this._stacks[x]||[];for(let P of this._renderableTiles){if(this.pool.isFull()&&(_l(this.painter,this.terrain,this._rttTiles,a),this._rttTiles=[],this.pool.freeAllObjects()),this._rttTiles.push(P),P.rtt[x]){let E=this.pool.getObjectForId(P.rtt[x].id);if(E.stamp===P.rtt[x].stamp){this.pool.useObject(E);continue}}let S=this.pool.getOrCreateFreeObject();this.pool.useObject(S),this.pool.stampObject(S),P.rtt[x]={id:S.id,stamp:S.stamp},f.context.bindFramebuffer.set(S.fbo.framebuffer),f.context.clear({color:p.bo.transparent,stencil:0}),f.currentStencilSource=void 0;for(let E of w){let C=f.style._layers[E],z=C.source?this._coordsAscending[C.source][P.tileID.key]:[P.tileID];f.context.viewport.set([0,0,S.fbo.width,S.fbo.height]),f._renderTileClippingMasks(C,z,!0),f.renderLayer(f,f.style.tileManagers[C.source],C,z,a),C.source&&(P.rttFingerprint[C.source]=this._rttFingerprints[C.source][P.tileID.key])}}return _l(this.painter,this.terrain,this._rttTiles,a),this._rttTiles=[],this.pool.freeAllObjects(),ht[c]}return!1}}let Qo={"AttributionControl.ToggleAttribution":"Toggle attribution","AttributionControl.MapFeedback":"Map feedback","FullscreenControl.Enter":"Enter fullscreen","FullscreenControl.Exit":"Exit fullscreen","GeolocateControl.FindMyLocation":"Find my location","GeolocateControl.LocationNotAvailable":"Location not available","LogoControl.Title":"MapLibre logo","Map.Title":"Map","Marker.Title":"Map marker","NavigationControl.ResetBearing":"Drag to rotate map, click to reset north","NavigationControl.ZoomIn":"Zoom in","NavigationControl.ZoomOut":"Zoom out","Popup.Close":"Close popup","ScaleControl.Feet":"ft","ScaleControl.Meters":"m","ScaleControl.Kilometers":"km","ScaleControl.Miles":"mi","ScaleControl.NauticalMiles":"nm","GlobeControl.Enable":"Enable globe","GlobeControl.Disable":"Disable globe","TerrainControl.Enable":"Enable terrain","TerrainControl.Disable":"Disable terrain","CooperativeGesturesHandler.WindowsHelpText":"Use Ctrl + scroll to zoom the map","CooperativeGesturesHandler.MacHelpText":"Use \u2318 + scroll to zoom the map","CooperativeGesturesHandler.MobileHelpText":"Use two fingers to move the map"},Ys=Te,Ks={hash:!1,interactive:!0,bearingSnap:7,zoomSnap:0,attributionControl:Xs,maplibreLogo:!1,refreshExpiredTiles:!0,canvasContextAttributes:{antialias:!1,preserveDrawingBuffer:!1,powerPreference:"high-performance",failIfMajorPerformanceCaveat:!1,desynchronized:!1,contextType:void 0},scrollZoom:!0,minZoom:-2,maxZoom:22,minPitch:0,maxPitch:60,boxZoom:!0,dragRotate:!0,dragPan:!0,keyboard:!0,doubleClickZoom:!0,touchZoomRotate:!0,touchPitch:!0,cooperativeGestures:!1,trackResize:!0,center:[0,0],elevation:0,zoom:0,bearing:0,pitch:0,roll:0,renderWorldCopies:!0,maxTileCacheSize:null,maxTileCacheZoomLevels:p.c.MAX_TILE_CACHE_ZOOM_LEVELS,transformRequest:null,transformCameraUpdate:null,transformConstrain:null,fadeDuration:300,crossSourceCollisions:!0,clickTolerance:3,localIdeographFontFamily:"sans-serif",pitchWithRotate:!0,rollEnabled:!1,reduceMotion:void 0,validateStyle:!0,maxCanvasSize:[4096,4096],cancelPendingTileRequestsWhileZooming:!0,centerClampedToGround:!0,experimentalZoomLevelsToOverscale:void 0,anisotropicFilterPitch:20},Js=class extends oh{get _ownerWindow(){var u,t;return((t=(u=this._container)===null||u===void 0?void 0:u.ownerDocument)===null||t===void 0?void 0:t.defaultView)||window}constructor(u){var t,n,a;let c=Object.assign(Object.assign(Object.assign({},Ks),u),{canvasContextAttributes:Object.assign(Object.assign({},Ks.canvasContextAttributes),u.canvasContextAttributes)});if(c.minZoom!=null&&c.maxZoom!=null&&c.minZoom>c.maxZoom)throw new Error("maxZoom must be greater than or equal to minZoom");if(c.minPitch!=null&&c.maxPitch!=null&&c.minPitch>c.maxPitch)throw new Error("maxPitch must be greater than or equal to minPitch");if(c.minPitch!=null&&c.minPitch<0)throw new Error("minPitch must be greater than or equal to 0");if(c.maxPitch!=null&&c.maxPitch>180)throw new Error("maxPitch must be less than or equal to 180");let f=new ln,y=new cn;c.minZoom!==void 0&&f.setMinZoom(c.minZoom),c.maxZoom!==void 0&&f.setMaxZoom(c.maxZoom),c.minPitch!==void 0&&f.setMinPitch(c.minPitch),c.maxPitch!==void 0&&f.setMaxPitch(c.maxPitch),c.renderWorldCopies!==void 0&&f.setRenderWorldCopies(c.renderWorldCopies),c.transformConstrain!==null&&f.setConstrainOverride(c.transformConstrain),super(f,y,{bearingSnap:c.bearingSnap,zoomSnap:c.zoomSnap}),this._idleTriggered=!1,this._crossFadingFactor=1,this._renderTaskQueue=new au,this._controls=[],this._mapId=p.ad(),this._lostContextStyle={style:null,images:null},this._contextLost=w=>{if(w.preventDefault(),this._frameRequest&&(this._frameRequest.abort(),this._frameRequest=null),this.painter.destroy(),this._lostContextStyle=this._getStyleAndImages(),this.style){for(let P of Object.values(this.style._layers))if(P.type==="custom"&&console.warn(`Custom layer with id '${P.id}' cannot be restored after WebGL context loss. You will need to re-add it manually after context restoration.`),P._listeners)for(let[S]of Object.entries(P._listeners))console.warn(`Custom layer with id '${P.id}' had event listeners for event '${S}' which cannot be restored after WebGL context loss. You will need to re-add them manually after context restoration.`);this.style.destroy(),this.style=null,this.fire(new p.n("webglcontextlost",{originalEvent:w}))}else this.fire(new p.n("webglcontextlost",{originalEvent:w}))},this._contextRestored=w=>{this._lostContextStyle.style&&this.setStyle(this._lostContextStyle.style,{diff:!1}),this._lostContextStyle.images&&this.style&&(this.style.imageManager.images=this._lostContextStyle.images),this._lostContextStyle={style:null,images:null},this._setupPainter(),this.resize(),this._update(),this._resizeInternal(),this.fire(new p.n("webglcontextrestored",{originalEvent:w}))},this._onMapScroll=w=>{if(w.target===this._container)return this._container.scrollTop=0,this._container.scrollLeft=0,!1},this._onWindowOnline=()=>{this._update()},this._interactive=c.interactive,this._maxTileCacheSize=c.maxTileCacheSize,this._maxTileCacheZoomLevels=c.maxTileCacheZoomLevels,this._canvasContextAttributes=Object.assign({},c.canvasContextAttributes),this._trackResize=c.trackResize===!0,this._bearingSnap=c.bearingSnap,this._zoomSnap=c.zoomSnap,this._centerClampedToGround=c.centerClampedToGround,this._refreshExpiredTiles=c.refreshExpiredTiles===!0,this._fadeDuration=c.fadeDuration,this._crossSourceCollisions=c.crossSourceCollisions===!0,this._collectResourceTiming=c.collectResourceTiming===!0,this._locale=Object.assign(Object.assign({},Qo),c.locale),this._clickTolerance=c.clickTolerance,this._overridePixelRatio=c.pixelRatio,this._maxCanvasSize=c.maxCanvasSize,this._zoomLevelsToOverscale=c.experimentalZoomLevelsToOverscale,this.transformCameraUpdate=c.transformCameraUpdate,this.transformConstrain=c.transformConstrain,this.cancelPendingTileRequestsWhileZooming=c.cancelPendingTileRequestsWhileZooming===!0,this.setAnisotropicFilterPitch(c.anisotropicFilterPitch),c.reduceMotion!==void 0&&(qt.prefersReducedMotion=c.reduceMotion),this._imageQueueHandle=Ii.addThrottleControl((()=>this.isMoving())),this._requestManager=new kt(c.transformRequest),this._container=this._resolveContainer(c.container),c.maxBounds&&this.setMaxBounds(c.maxBounds),this._setupContainer(),this._setupPainter(),this.on("move",(()=>this._update(!1))),this.on("moveend",(()=>this._update(!1))),this.on("zoom",(()=>this._update(!0))),this.on("terrain",(()=>{this.painter.terrainFacilitator.depthDirty=!0,this._update(!0)})),this.once("idle",(()=>this._idleTriggered=!0)),typeof window<"u"&&(this._ownerWindow.addEventListener("online",this._onWindowOnline,!1),this._setupResizeObserver()),this.handlers=new ui(this,c),this._hash=c.hash?new Zo(typeof c.hash=="string"&&c.hash||void 0).addTo(this):void 0,!((t=this._hash)===null||t===void 0)&&t._onHashChange()||(this.jumpTo({center:c.center,elevation:c.elevation,zoom:c.zoom,bearing:c.bearing,pitch:c.pitch,roll:c.roll}),c.bounds&&(this.resize(),this.fitBounds(c.bounds,p.e({},c.fitBoundsOptions,{duration:0}))));let x=typeof c.style=="string"||((a=(n=c.style)===null||n===void 0?void 0:n.projection)===null||a===void 0?void 0:a.type)!=="globe";this.resize(null,x),this._localIdeographFontFamily=c.localIdeographFontFamily,this._validateStyle=c.validateStyle,c.style&&this.setStyle(c.style,{localIdeographFontFamily:c.localIdeographFontFamily}),c.attributionControl&&this.addControl(new Ui(typeof c.attributionControl=="boolean"?void 0:c.attributionControl)),c.maplibreLogo&&this.addControl(new Cl,c.logoPosition),this.on("style.load",(()=>{if(x||this._resizeTransform(),this.transform.unmodified){let w=p.V(this.style.stylesheet,["center","zoom","bearing","pitch","roll"]);this.jumpTo(w)}})),this.on("data",(w=>{this._update(w.dataType==="style"),this.fire(new p.n(`${w.dataType}data`,w))})),this.on("dataloading",(w=>{this.fire(new p.n(`${w.dataType}dataloading`,w))})),this.on("dataabort",(w=>{this.fire(new p.n("sourcedataabort",w))}))}_getMapId(){return this._mapId}setGlobalStateProperty(u,t){return this.style.setGlobalStateProperty(u,t),this._update(!0)}getGlobalState(){return this.style.getGlobalState()}addControl(u,t){if(t===void 0&&(t=u.getDefaultPosition?u.getDefaultPosition():"top-right"),!u?.onAdd)return this.fire(new p.l(new Error("Invalid argument to map.addControl(). Argument must be a control with onAdd and onRemove methods.")));let n=u.onAdd(this);this._controls.push(u);let a=this._controlPositions[t];return t.includes("bottom")?a.insertBefore(n,a.firstChild):a.appendChild(n),this}removeControl(u){if(!u?.onRemove)return this.fire(new p.l(new Error("Invalid argument to map.removeControl(). Argument must be a control with onAdd and onRemove methods.")));let t=this._controls.indexOf(u);return t>-1&&this._controls.splice(t,1),u.onRemove(this),this}hasControl(u){return this._controls.includes(u)}coveringTiles(u){return rn(this.transform,u)}calculateCameraOptionsFromTo(u,t,n,a){return a==null&&this.terrain&&(a=this.terrain.getElevationForLngLat(n,this.transform)),super.calculateCameraOptionsFromTo(u,t,n,a)}resize(u,t=!0){if(this._lostContextStyle.style!==null)return this;this._resizeInternal(t);let n=!this._moving;return n&&(this.stop(),this.fire(new p.n("movestart",u)).fire(new p.n("move",u))),this.fire(new p.n("resize",u)),n&&this.fire(new p.n("moveend",u)),this}_resizeInternal(u=!0){let[t,n]=this._containerDimensions(),a=this._getClampedPixelRatio(t,n);if(this._resizeCanvas(t,n,a),this.painter.resize(t,n,a),this.painter.overLimit()){let c=this.painter.context.gl;this._maxCanvasSize=[c.drawingBufferWidth,c.drawingBufferHeight];let f=this._getClampedPixelRatio(t,n);this._resizeCanvas(t,n,f),this.painter.resize(t,n,f)}this._resizeTransform(u)}_resizeTransform(u=!0){var t;let[n,a]=this._containerDimensions();this.transform.resize(n,a,u),(t=this._requestedCameraState)===null||t===void 0||t.resize(n,a,u)}_getClampedPixelRatio(u,t){let{0:n,1:a}=this._maxCanvasSize,c=this.getPixelRatio(),f=u*c,y=t*c;return Math.min(f>n?n/f:1,y>a?a/y:1)*c}getPixelRatio(){var u;return(u=this._overridePixelRatio)!==null&&u!==void 0?u:devicePixelRatio}setPixelRatio(u){this._overridePixelRatio=u,this.resize()}getBounds(){return this.transform.getBounds()}getMaxBounds(){return this.transform.getMaxBounds()}setMaxBounds(u){return this.transform.setMaxBounds(Re.convert(u)),this._update()}setMinZoom(u){if((u=u??-2)>=-2&&u<=this.transform.maxZoom){let t=this.transform.zoom,n=this._getTransformForUpdate();return n.setMinZoom(u),this._applyUpdatedTransform(n),this._update(),t!==this.transform.zoom&&this.fire(new p.n("zoomstart")).fire(new p.n("zoom")).fire(new p.n("zoomend")).fire(new p.n("movestart")).fire(new p.n("move")).fire(new p.n("moveend")),this}throw new Error("minZoom must be between -2 and the current maxZoom, inclusive")}getMinZoom(){return this.transform.minZoom}setMaxZoom(u){if((u=u??22)>=this.transform.minZoom){let t=this.transform.zoom,n=this._getTransformForUpdate();return n.setMaxZoom(u),this._applyUpdatedTransform(n),this._update(),t!==this.transform.zoom&&this.fire(new p.n("zoomstart")).fire(new p.n("zoom")).fire(new p.n("zoomend")).fire(new p.n("movestart")).fire(new p.n("move")).fire(new p.n("moveend")),this}throw new Error("maxZoom must be greater than the current minZoom")}getMaxZoom(){return this.transform.maxZoom}setMinPitch(u){if((u=u??0)<0)throw new Error("minPitch must be greater than or equal to 0");if(u>=0&&u<=this.transform.maxPitch){let t=this.transform.pitch,n=this._getTransformForUpdate();return n.setMinPitch(u),this._applyUpdatedTransform(n),this._update(),t!==this.transform.pitch&&this.fire(new p.n("pitchstart")).fire(new p.n("pitch")).fire(new p.n("pitchend")).fire(new p.n("movestart")).fire(new p.n("move")).fire(new p.n("moveend")),this}throw new Error("minPitch must be between 0 and the current maxPitch, inclusive")}getMinPitch(){return this.transform.minPitch}setMaxPitch(u){if((u=u??60)>180)throw new Error("maxPitch must be less than or equal to 180");if(u>=this.transform.minPitch){let t=this.transform.pitch,n=this._getTransformForUpdate();return n.setMaxPitch(u),this._applyUpdatedTransform(n),this._update(),t!==this.transform.pitch&&this.fire(new p.n("pitchstart")).fire(new p.n("pitch")).fire(new p.n("pitchend")).fire(new p.n("movestart")).fire(new p.n("move")).fire(new p.n("moveend")),this}throw new Error("maxPitch must be greater than the current minPitch")}getMaxPitch(){return this.transform.maxPitch}getAnisotropicFilterPitch(){return this._anisotropicFilterPitch}setAnisotropicFilterPitch(u){if((u=u??20)>180)throw new Error("anisotropicFilterPitch must be less than or equal to 180");if(u<0)throw new Error("anisotropicFilterPitch must be greater than or equal to 0");return this._anisotropicFilterPitch=u,this._update()}getRenderWorldCopies(){return this.transform.renderWorldCopies}setRenderWorldCopies(u){return this.transform.setRenderWorldCopies(u),this._update()}setTransformConstrain(u){return this.transform.setConstrainOverride(u),this._update()}project(u){return this.transform.locationToScreenPoint(p.W.convert(u),this.style&&this.terrain)}unproject(u){return this.transform.screenPointToLocation(p.P.convert(u),this.terrain)}isMoving(){var u;return this._moving||((u=this.handlers)===null||u===void 0?void 0:u.isMoving())}isZooming(){var u;return this._zooming||((u=this.handlers)===null||u===void 0?void 0:u.isZooming())}isRotating(){var u;return this._rotating||((u=this.handlers)===null||u===void 0?void 0:u.isRotating())}_createDelegatedListener(u,t,n){if(u==="mouseenter"||u==="mouseover"){let a=!1;return{layers:t,listener:n,delegates:{mousemove:f=>{let y=t.filter((w=>this.getLayer(w))),x=y.length!==0?this.queryRenderedFeatures(f.point,{layers:y}):[];x.length?a||(a=!0,n.call(this,new zi(u,this,f.originalEvent,{features:x}))):a=!1},mouseout:()=>{a=!1}}}}if(u==="mouseleave"||u==="mouseout"){let a=!1;return{layers:t,listener:n,delegates:{mousemove:y=>{let x=t.filter((w=>this.getLayer(w)));(x.length!==0?this.queryRenderedFeatures(y.point,{layers:x}):[]).length?a=!0:a&&(a=!1,n.call(this,new zi(u,this,y.originalEvent)))},mouseout:y=>{a&&(a=!1,n.call(this,new zi(u,this,y.originalEvent)))}}}}{let a=c=>{let f=t.filter((x=>this.getLayer(x))),y=f.length!==0?this.queryRenderedFeatures(c.point,{layers:f}):[];y.length&&(c.features=y,n.call(this,c),delete c.features)};return{layers:t,listener:n,delegates:{[u]:a}}}}_saveDelegatedListener(u,t){var n;this._delegatedListeners||(this._delegatedListeners={}),(n=this._delegatedListeners)[u]||(n[u]=[]),this._delegatedListeners[u].push(t)}_removeDelegatedListener(u,t,n){var a;if(!(!((a=this._delegatedListeners)===null||a===void 0)&&a[u]))return;let c=this._delegatedListeners[u];for(let f=0;ft.includes(x)))){for(let x in y.delegates)this.off(x,y.delegates[x]);return void c.splice(f,1)}}}on(u,t,n){if(n===void 0)return super.on(u,t);let a=typeof t=="string"?[t]:t,c=this._createDelegatedListener(u,a,n);this._saveDelegatedListener(u,c);for(let f in c.delegates)this.on(f,c.delegates[f]);return{unsubscribe:()=>{this._removeDelegatedListener(u,a,n)}}}once(u,t,n){if(n===void 0)return super.once(u,t);let a=typeof t=="string"?[t]:t,c=this._createDelegatedListener(u,a,n);for(let f in c.delegates){let y=c.delegates[f];c.delegates[f]=(...x)=>{this._removeDelegatedListener(u,a,n),y(...x)}}this._saveDelegatedListener(u,c);for(let f in c.delegates)this.once(f,c.delegates[f]);return this}off(u,t,n){return n===void 0?super.off(u,t):(this._removeDelegatedListener(u,typeof t=="string"?[t]:t,n),this)}queryRenderedFeatures(u,t){if(!this.style)return[];let n,a=u instanceof p.P||Array.isArray(u),c=a?u:[[0,0],[this.transform.width,this.transform.height]];if(t||(t=(a?{}:u)||{}),c instanceof p.P||typeof c[0]=="number")n=[p.P.convert(c)];else{let f=p.P.convert(c[0]),y=p.P.convert(c[1]);n=[f,new p.P(y.x,f.y),y,new p.P(f.x,y.y),f]}return this.style.queryRenderedFeatures(n,t,this.transform)}querySourceFeatures(u,t){return this.style.querySourceFeatures(u,t)}setStyle(u,t){return(t=p.e({},{localIdeographFontFamily:this._localIdeographFontFamily,validate:this._validateStyle},t)).diff!==!1&&t.localIdeographFontFamily===this._localIdeographFontFamily&&this.style&&u?(this._diffStyle(u,t),this):(this._localIdeographFontFamily=t.localIdeographFontFamily,this._updateStyle(u,t))}setTransformRequest(u){return this._requestManager.setTransformRequest(u),this}_getUIString(u){let t=this._locale[u];if(t==null)throw new Error(`Missing UI string '${u}'`);return t}_updateStyle(u,t){var n,a,c;if((n=this._diffStyleRequest)===null||n===void 0||n.abort(),this._diffStyleRequest=null,t.transformStyle&&this.style&&!this.style._loaded)return void this.style.once("style.load",(()=>this._updateStyle(u,t)));let f=this.style&&t.transformStyle?this.style.serialize():void 0;return this.style&&(this.style.setEventedParent(null),this.style._remove(!u)),u?(this.style=new pn(this,t||{}),this.style.setEventedParent(this,{style:this.style}),typeof u=="string"?this.style.loadURL(u,t,f):this.style.loadJSON(u,t,f),this):(this._frameRequest&&(this._frameRequest.abort(),this._frameRequest=null),(c=(a=this.style)===null||a===void 0?void 0:a.projection)===null||c===void 0||c.destroy(),delete this.style,this)}_lazyInitEmptyStyle(){this.style||(this.style=new pn(this,{}),this.style.setEventedParent(this,{style:this.style}),this.style.loadEmpty())}_diffStyle(u,t){return p._(this,void 0,void 0,(function*(){var n;if((n=this._diffStyleRequest)===null||n===void 0||n.abort(),typeof u=="string"){let a=u;this._diffStyleRequest=new AbortController;let c=this._diffStyleRequest;try{let f=yield this._requestManager.transformRequest(a,"Style");if(c.signal.aborted)return void(this._diffStyleRequest=null);let y=yield p.k(f,c);this._diffStyleRequest=null,this._updateDiff(y.data,t)}catch(f){this._diffStyleRequest=null,p.$(f)||this.fire(new p.l(p.d(f)))}}else typeof u=="object"&&(this._diffStyleRequest=null,this._updateDiff(u,t))}))}_updateDiff(u,t){try{this.style.setState(u,t)&&this._update(!0)}catch(n){p.w(`Unable to perform style diff: ${p.d(n).message}. Rebuilding the style from scratch.`),this._updateStyle(u,t)}}getStyle(){if(this.style)return this.style.serialize()}_getStyleAndImages(){return this.style?{style:this.style.serialize(),images:this.style.imageManager.cloneImages()}:{style:null,images:{}}}isStyleLoaded(){if(this.style)return this.style.loaded();p.w("There is no style added to the map.")}addSource(u,t){return this._lazyInitEmptyStyle(),this.style.addSource(u,t),this._update(!0)}isSourceLoaded(u){var t;let n=(t=this.style)===null||t===void 0?void 0:t.tileManagers[u];if(n!==void 0)return n.loaded();this.fire(new p.l(new Error(`There is no tile manager with ID '${u}'`)))}setTerrain(u){if(this.style._checkLoaded(),this._terrainDataCallback&&this.style.off("data",this._terrainDataCallback),u){let t=this.style.tileManagers[u.source];if(!t)throw new Error(`cannot load terrain, because there exists no source with ID: ${u.source}`);this.terrain===null&&t.reload();for(let n in this.style._layers){let a=this.style._layers[n];a.type==="hillshade"&&a.source===u.source&&p.w("You are using the same source for a hillshade layer and for 3D terrain. Please consider using two separate sources to improve rendering quality."),a.type==="color-relief"&&a.source===u.source&&p.w("You are using the same source for a color-relief layer and for 3D terrain. Please consider using two separate sources to improve rendering quality.")}this.terrain=new Jo(this.painter,t,u),this.painter.renderToTexture=new sh(this.painter,this.terrain),this.transform.setMinElevationForCurrentTile(this.terrain.getMinTileElevationForLngLatZoom(this.transform.center,this.transform.tileZoom)),this.transform.setElevation(this.terrain.getElevationForLngLatZoom(this.transform.center,this.transform.tileZoom)),this._terrainDataCallback=n=>{var a;n.dataType==="style"?this.terrain.tileManager.freeRtt():n.dataType==="source"&&n.tile&&(n.sourceId!==u.source||this._elevationFreeze||(this.transform.setMinElevationForCurrentTile(this.terrain.getMinTileElevationForLngLatZoom(this.transform.center,this.transform.tileZoom)),this._centerClampedToGround&&this.transform.setElevation(this.terrain.getElevationForLngLatZoom(this.transform.center,this.transform.tileZoom))),((a=n.source)===null||a===void 0?void 0:a.type)==="image"?this.terrain.tileManager.freeRtt():this.terrain.tileManager.freeRtt(n.tile.tileID))},this.style.on("data",this._terrainDataCallback)}else this.terrain&&this.terrain.destroy(),this.terrain=null,this.painter.renderToTexture&&this.painter.renderToTexture.destruct(),this.painter.renderToTexture=null,this.transform.setMinElevationForCurrentTile(0),this._centerClampedToGround&&this.transform.setElevation(0);return this.fire(new p.n("terrain",{terrain:u})),this}getTerrain(){var u,t;return(t=(u=this.terrain)===null||u===void 0?void 0:u.options)!==null&&t!==void 0?t:null}areTilesLoaded(){var u;let t=(u=this.style)===null||u===void 0?void 0:u.tileManagers;for(let n of Object.values(t))if(!n.areTilesLoaded())return!1;return!0}removeSource(u){return this.style.removeSource(u),this._update(!0)}getSource(u){return this.style.getSource(u)}setSourceTileLodParams(u,t,n){if(n){let a=this.getSource(n);if(!a)throw new Error(`There is no source with ID "${n}", cannot set LOD parameters`);a.calculateTileZoom=Oa(Math.max(1,u),Math.max(1,t))}else for(let a in this.style.tileManagers)this.style.tileManagers[a].getSource().calculateTileZoom=Oa(Math.max(1,u),Math.max(1,t));return this._update(!0),this}refreshTiles(u,t){let n=this.style.tileManagers[u];if(!n)throw new Error(`There is no tile manager with ID "${u}", cannot refresh tile`);t===void 0?n.reload(!0):n.refreshTiles(t.map((a=>new p.aa(a.z,a.x,a.y))))}addImage(u,t,n={}){let{pixelRatio:a=1,sdf:c=!1,stretchX:f,stretchY:y,content:x,textFitWidth:w,textFitHeight:P}=n;if(this._lazyInitEmptyStyle(),!(t instanceof HTMLImageElement||p.b(t))){if(t.width===void 0||t.height===void 0)return this.fire(new p.l(new Error("Invalid arguments to map.addImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, or object with `width`, `height`, and `data` properties with the same format as `ImageData`")));{let{width:S,height:E,data:C}=t,z=t;return this.style.addImage(u,{data:new p.R({width:S,height:E},new Uint8Array(C)),pixelRatio:a,stretchX:f,stretchY:y,content:x,textFitWidth:w,textFitHeight:P,sdf:c,version:0,userImage:z}),z.onAdd&&z.onAdd(this,u),this}}{let{width:S,height:E,data:C}=qt.getImageData(t);this.style.addImage(u,{data:new p.R({width:S,height:E},C),pixelRatio:a,stretchX:f,stretchY:y,content:x,textFitWidth:w,textFitHeight:P,sdf:c,version:0})}}updateImage(u,t){let n=this.style.getImage(u);if(!n)return this.fire(new p.l(new Error("The map has no image with that id. If you are adding a new image use `map.addImage(...)` instead.")));let a=t instanceof HTMLImageElement||p.b(t)?qt.getImageData(t):t,{width:c,height:f,data:y}=a;if(c===void 0||f===void 0)return this.fire(new p.l(new Error("Invalid arguments to map.updateImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, or object with `width`, `height`, and `data` properties with the same format as `ImageData`")));if(c!==n.data.width||f!==n.data.height)return this.fire(new p.l(new Error("The width and height of the updated image must be that same as the previous version of the image")));let x=!(t instanceof HTMLImageElement||p.b(t));return n.data.replace(y,x),this.style.updateImage(u,n),this}getImage(u){return this.style.getImage(u)}hasImage(u){return u?!!this.style.getImage(u):(this.fire(new p.l(new Error("Missing required image id"))),!1)}removeImage(u){this.style.removeImage(u)}loadImage(u){return p._(this,void 0,void 0,(function*(){return Ii.getImage(yield this._requestManager.transformRequest(u,"Image"),new AbortController)}))}listImages(){return this.style.listImages()}addLayer(u,t){return this._lazyInitEmptyStyle(),this.style.addLayer(u,t),this._update(!0)}moveLayer(u,t){return this.style.moveLayer(u,t),this._update(!0)}removeLayer(u){return this.style.removeLayer(u),this._update(!0)}getLayer(u){return this.style.getLayer(u)}getLayersOrder(){return this.style.getLayersOrder()}setLayerZoomRange(u,t,n){return this.style.setLayerZoomRange(u,t,n),this._update(!0)}setFilter(u,t,n={}){return this.style.setFilter(u,t,n),this._update(!0)}getFilter(u){return this.style.getFilter(u)}setPaintProperty(u,t,n,a={}){return this.style.setPaintProperty(u,t,n,a),this._update(!0)}getPaintProperty(u,t){return this.style.getPaintProperty(u,t)}setLayoutProperty(u,t,n,a={}){return this.style.setLayoutProperty(u,t,n,a),this._update(!0)}getLayoutProperty(u,t){return this.style.getLayoutProperty(u,t)}setGlyphs(u,t={}){return this._lazyInitEmptyStyle(),this.style.setGlyphs(u,t),this._update(!0)}getGlyphs(){return this.style.getGlyphsUrl()}addSprite(u,t,n={}){return this._lazyInitEmptyStyle(),this.style.addSprite(u,t,n,(a=>{a||this._update(!0)})),this}removeSprite(u){return this._lazyInitEmptyStyle(),this.style.removeSprite(u),this._update(!0)}getSprite(){return this.style.getSprite()}setSprite(u,t={}){return this._lazyInitEmptyStyle(),this.style.setSprite(u,t,(n=>{n||this._update(!0)})),this}setLight(u,t={}){return this._lazyInitEmptyStyle(),this.style.setLight(u,t),this._update(!0)}getLight(){return this.style.getLight()}setSky(u,t={}){return this._lazyInitEmptyStyle(),this.style.setSky(u,t),this._update(!0)}getSky(){return this.style.getSky()}setFeatureState(u,t){return this.style.setFeatureState(u,t),this._update()}removeFeatureState(u,t){return this.style.removeFeatureState(u,t),this._update()}getFeatureState(u){return this.style.getFeatureState(u)}getContainer(){return this._container}getCanvasContainer(){return this._canvasContainer}getCanvas(){return this._canvas}_containerDimensions(){let u=0,t=0;return this._container&&(u=this._container.clientWidth||400,t=this._container.clientHeight||300),[u,t]}_setupResizeObserver(){var u;let t=!1,n=vl((c=>{this._trackResize&&!this._removed&&(this.resize(c),this.redraw())}),50),a=(u=this._ownerWindow.ResizeObserver)!==null&&u!==void 0?u:ResizeObserver;this._resizeObserver=new a((c=>{t?n(c):t=!0})),this._resizeObserver.observe(this._container)}_resolveContainer(u){if(typeof u=="string"){let t=document.getElementById(u);if(!t)throw new Error(`Container '${u}' not found.`);return t}if(u instanceof HTMLElement||u&&typeof u=="object"&&u.nodeType===1)return u;throw new Error("Invalid type: 'container' must be a String or HTMLElement.")}_setupContainer(){let u=this._container;u.classList.add("maplibregl-map");let t=this._canvasContainer=pe.create("div","maplibregl-canvas-container",u);this._interactive&&t.classList.add("maplibregl-interactive"),this._canvas=pe.create("canvas","maplibregl-canvas",t),this._canvas.addEventListener("webglcontextlost",this._contextLost,!1),this._canvas.addEventListener("webglcontextrestored",this._contextRestored,!1),this._canvas.setAttribute("tabindex",this._interactive?"0":"-1"),this._canvas.setAttribute("aria-label",this._getUIString("Map.Title")),this._canvas.setAttribute("role","region");let n=this._containerDimensions(),a=this._getClampedPixelRatio(n[0],n[1]);this._resizeCanvas(n[0],n[1],a);let c=this._controlContainer=pe.create("div","maplibregl-control-container",u),f=this._controlPositions={};for(let y of["top-left","top-right","bottom-left","bottom-right"])f[y]=pe.create("div",`maplibregl-ctrl-${y} `,c);this._container.addEventListener("scroll",this._onMapScroll,!1)}_resizeCanvas(u,t,n){this._canvas.width=Math.floor(n*u),this._canvas.height=Math.floor(n*t),this._canvas.style.width=`${u}px`,this._canvas.style.height=`${t}px`}_setupPainter(){let u=Object.assign(Object.assign({},this._canvasContextAttributes),{alpha:!0,depth:!0,stencil:!0,premultipliedAlpha:!0}),t=null;this._canvas.addEventListener("webglcontextcreationerror",(a=>{t={requestedAttributes:u},a&&(t.statusMessage=a.statusMessage,t.type=a.type)}),{once:!0});let n=null;if(n=this._canvasContextAttributes.contextType?this._canvas.getContext(this._canvasContextAttributes.contextType,u):this._canvas.getContext("webgl2",u)||this._canvas.getContext("webgl",u),!n){let a="Failed to initialize WebGL";throw t?(t.message=a,new Error(JSON.stringify(t))):new Error(a)}this.painter=new $o(n,this.transform)}migrateProjection(u,t){super.migrateProjection(u,t),this.painter.transform=u,this.fire(new p.n("projectiontransition",{newProjection:this.style.projection.name}))}loaded(){return!this._styleDirty&&!this._sourcesDirty&&!!this.style&&this.style.loaded()}_update(u){var t;return!((t=this.style)===null||t===void 0)&&t._loaded?(this._styleDirty||(this._styleDirty=u),this._sourcesDirty=!0,this.triggerRepaint(),this):this}_requestRenderFrame(u){return this._update(),this._renderTaskQueue.add(u)}_cancelRenderFrame(u){this._renderTaskQueue.remove(u)}_render(u){var t,n,a,c,f,y;let x=this._idleTriggered?this._fadeDuration:0,w=((t=this.style.projection)===null||t===void 0?void 0:t.transitionState)>0;if(this.painter.context.setDirty(),this.painter.setBaseState(),this._renderTaskQueue.run(u),this._removed)return;let P=!1;if(this.style&&this._styleDirty){this._styleDirty=!1;let C=this.transform.zoom,z=Xe();this.style.zoomHistory.update(C,z);let B=new p.J(C,{now:z,fadeDuration:x,zoomHistory:this.style.zoomHistory,transition:this.style.getTransition()}),N=B.crossFadingFactor();N===1&&N===this._crossFadingFactor||(P=!0,this._crossFadingFactor=N),this.style.update(B)}let S=((n=this.style.projection)===null||n===void 0?void 0:n.transitionState)>0!==w;(a=this.style.projection)===null||a===void 0||a.setErrorQueryLatitudeDegrees(this.transform.center.lat),this.transform.setTransitionState((c=this.style.projection)===null||c===void 0?void 0:c.transitionState,(f=this.style.projection)===null||f===void 0?void 0:f.latitudeErrorCorrectionRadians),this.style&&(this._sourcesDirty||S)&&(this._sourcesDirty=!1,this.style._updateSources(this.transform)),this.terrain?(this.terrain.tileManager.update(this.transform,this.terrain),this.transform.setMinElevationForCurrentTile(this.terrain.getMinTileElevationForLngLatZoom(this.transform.center,this.transform.tileZoom)),!this._elevationFreeze&&this._centerClampedToGround&&this.transform.setElevation(this.terrain.getElevationForLngLatZoom(this.transform.center,this.transform.tileZoom))):(this.transform.setMinElevationForCurrentTile(0),this._centerClampedToGround&&this.transform.setElevation(0)),this._placementDirty=(y=this.style)===null||y===void 0?void 0:y._updatePlacement(this.transform,this.showCollisionBoxes,x,this._crossSourceCollisions,S),this.painter.render(this.style,{showTileBoundaries:this.showTileBoundaries,showOverdrawInspector:this._showOverdrawInspector,rotating:this.isRotating(),zooming:this.isZooming(),moving:this.isMoving(),fadeDuration:x,showPadding:this.showPadding,anisotropicFilterPitch:this.getAnisotropicFilterPitch()}),this.fire(new p.n("render")),this.loaded()&&!this._loaded&&(this._loaded=!0,this.fire(new p.n("load"))),this.style&&(this.style.hasTransitions()||P)&&(this._styleDirty=!0),this.style&&!this._placementDirty&&this.style._releaseSymbolFadeTiles();let E=this._sourcesDirty||this._styleDirty||this._placementDirty;return E||this._repaint?this.triggerRepaint():!this.isMoving()&&this.loaded()&&this.fire(new p.n("idle")),!this._loaded||this._fullyLoaded||E||(this._fullyLoaded=!0),this}redraw(){return this.style&&(this._frameRequest&&(this._frameRequest.abort(),this._frameRequest=null),this._render(0)),this}remove(){var u,t;this._hash&&this._hash.remove();for(let a of this._controls)a.onRemove(this);this._controls=[],this._frameRequest&&(this._frameRequest.abort(),this._frameRequest=null),this._renderTaskQueue.clear(),(u=this._diffStyleRequest)===null||u===void 0||u.abort(),this.painter.destroy(),this.handlers.destroy(),delete this.handlers,this.setStyle(null),typeof window<"u"&&this._ownerWindow.removeEventListener("online",this._onWindowOnline,!1),Ii.removeThrottleControl(this._imageQueueHandle),(t=this._resizeObserver)===null||t===void 0||t.disconnect();let n=this.painter.context.gl.getExtension("WEBGL_lose_context");n?.loseContext&&n.loseContext(),this._canvas.removeEventListener("webglcontextrestored",this._contextRestored,!1),this._canvas.removeEventListener("webglcontextlost",this._contextLost,!1),this._canvasContainer.remove(),this._controlContainer.remove(),this._container.removeEventListener("scroll",this._onMapScroll,!1),this._container.classList.remove("maplibregl-map"),this._removed=!0,this.fire(new p.n("remove"))}triggerRepaint(){this.style&&!this._frameRequest&&(this._frameRequest=new AbortController,qt.frame(this._frameRequest,(u=>{this._frameRequest=null;try{this._render(u)}catch(t){if(!p.$(t)&&!(function(n){return n.message===js})(t))throw t}}),(()=>{}),this._ownerWindow))}get showTileBoundaries(){return!!this._showTileBoundaries}set showTileBoundaries(u){this._showTileBoundaries!==u&&(this._showTileBoundaries=u,this._update())}get showPadding(){return!!this._showPadding}set showPadding(u){this._showPadding!==u&&(this._showPadding=u,this._update())}get showCollisionBoxes(){return!!this._showCollisionBoxes}set showCollisionBoxes(u){this._showCollisionBoxes!==u&&(this._showCollisionBoxes=u,u?this.style._generateCollisionBoxes():this._update())}get showOverdrawInspector(){return!!this._showOverdrawInspector}set showOverdrawInspector(u){this._showOverdrawInspector!==u&&(this._showOverdrawInspector=u,this._update())}get repaint(){return!!this._repaint}set repaint(u){this._repaint!==u&&(this._repaint=u,this.triggerRepaint())}get vertices(){return!!this._vertices}set vertices(u){this._vertices=u,this._update()}get version(){return Ys}getCameraTargetElevation(){return this.transform.elevation}getProjection(){return this.style.getProjection()}setProjection(u){return this._lazyInitEmptyStyle(),this.style.setProjection(u),this._update(!0)}},Al={showCompass:!0,showZoom:!0,visualizePitch:!1,visualizeRoll:!0};class es{constructor(t,n,a=!1){this.mousedown=f=>{this.startMove(f,pe.mousePos(this.element,f)),window.addEventListener("mousemove",this.mousemove),window.addEventListener("mouseup",this.mouseup)},this.mousemove=f=>{this.move(f,pe.mousePos(this.element,f))},this.mouseup=f=>{this._rotatePitchHandler.dragEnd(f),this.offTemp()},this.touchstart=f=>{f.targetTouches.length!==1?this.reset():(this._startPos=this._lastPos=pe.touchPos(this.element,f.targetTouches)[0],this.startMove(f,this._startPos),window.addEventListener("touchmove",this.touchmove,{passive:!1}),window.addEventListener("touchend",this.touchend))},this.touchmove=f=>{f.targetTouches.length!==1?this.reset():(this._lastPos=pe.touchPos(this.element,f.targetTouches)[0],this.move(f,this._lastPos))},this.touchend=f=>{f.targetTouches.length===0&&this._startPos&&this._lastPos&&this._startPos.dist(this._lastPos){this._rotatePitchHandler.reset(),delete this._startPos,delete this._lastPos,this.offTemp()},this._clickTolerance=10,this.element=n;let c=new bl;this._rotatePitchHandler=new mr({clickTolerance:3,move:(f,y)=>{let x=n.getBoundingClientRect(),w=new p.P((x.bottom-x.top)/2,(x.right-x.left)/2);return{bearingDelta:p.cx(new p.P(f.x,y.y),y,w),pitchDelta:a?-.5*(y.y-f.y):void 0}},moveStateManager:c,enable:!0,assignEvents:()=>{}}),this.map=t,n.addEventListener("mousedown",this.mousedown),n.addEventListener("touchstart",this.touchstart,{passive:!1}),n.addEventListener("touchcancel",this.reset)}startMove(t,n){this._rotatePitchHandler.dragStart(t,n),pe.disableDrag()}move(t,n){let a=this.map,{bearingDelta:c,pitchDelta:f}=this._rotatePitchHandler.dragMove(t,n)||{};c&&a.setBearing(a.getBearing()+c),f&&a.setPitch(a.getPitch()+f)}off(){let t=this.element;t.removeEventListener("mousedown",this.mousedown),t.removeEventListener("touchstart",this.touchstart),window.removeEventListener("touchmove",this.touchmove),window.removeEventListener("touchend",this.touchend),t.removeEventListener("touchcancel",this.reset),this.offTemp()}offTemp(){pe.enableDrag(),window.removeEventListener("mousemove",this.mousemove),window.removeEventListener("mouseup",this.mouseup),window.removeEventListener("touchmove",this.touchmove),window.removeEventListener("touchend",this.touchend)}}let _r;function Qs(u,t,n,a=!1){if(a||!n.getCoveringTilesDetailsProvider().allowWorldCopies())return u?.wrap();let c=new p.W(u.lng,u.lat);if(u=new p.W(u.lng,u.lat),t){let f=new p.W(u.lng-360,u.lat),y=new p.W(u.lng+360,u.lat),x=n.locationToScreenPoint(u).distSqr(t);n.locationToScreenPoint(f).distSqr(t)180;){let f=n.locationToScreenPoint(u);if(f.x>=0&&f.y>=0&&f.x<=n.width&&f.y<=n.height)break;u.lng>n.center.lng?u.lng-=360:u.lng+=360}return u.lng!==c.lng&&n.isPointOnMapSurface(n.locationToScreenPoint(u))?u:c}let ts={center:"translate(-50%,-50%)",top:"translate(-50%,0)","top-left":"translate(0,0)","top-right":"translate(-100%,0)",bottom:"translate(-50%,-100%)","bottom-left":"translate(0,-100%)","bottom-right":"translate(-100%,-100%)",left:"translate(0,-50%)",right:"translate(-100%,-50%)"};function ea(u,t,n){let a=u.classList;for(let c in ts)a.remove(`maplibregl-${n}-anchor-${c}`);a.add(`maplibregl-${n}-anchor-${t}`)}class is extends p.E{constructor(t){if(super(),this._onClick=n=>{this.fire(new p.n("click",{originalEvent:n}))},this._onKeyPress=n=>{n.code!=="Space"&&n.code!=="Enter"||this.togglePopup()},this._onMapClick=n=>{let a=n.originalEvent.target,c=this._element;this._popup&&(a===c||c.contains(a))&&this.togglePopup()},this._update=n=>{if(!this._map)return;let a=this._map.loaded()&&!this._map.isMoving();(n?.type==="terrain"||n?.type==="render"&&!a)&&this._map.once("render",this._update),this._lngLat=Qs(this._lngLat,this._flatPos,this._map.transform),this._flatPos=this._pos=this._map.project(this._lngLat)._add(this._offset),this._map.terrain&&(this._flatPos=this._map.transform.locationToScreenPoint(this._lngLat)._add(this._offset));let c="";this._rotationAlignment==="viewport"||this._rotationAlignment==="auto"?c=`rotateZ(${this._rotation}deg)`:this._rotationAlignment==="map"&&(c=`rotateZ(${this._rotation-this._map.getBearing()}deg)`);let f="";this._pitchAlignment==="viewport"||this._pitchAlignment==="auto"?f="rotateX(0deg)":this._pitchAlignment==="map"&&(f=`rotateX(${this._map.getPitch()}deg)`),this._subpixelPositioning||n&&n.type!=="moveend"||(this._pos=this._pos.round()),this._element.style.transform=`${ts[this._anchor]} translate(${this._pos.x}px, ${this._pos.y}px) ${f} ${c}`,qt.frameAsync(new AbortController,this._map._ownerWindow).then((()=>{this._updateOpacity(n?.type==="moveend")})).catch((()=>{}))},this._onMove=n=>{if(!this._isDragging){let a=this._clickTolerance||this._map._clickTolerance;this._isDragging=n.point.dist(this._pointerdownPos)>=a}this._isDragging&&(this._pos=n.point.sub(this._positionDelta),this._lngLat=this._map.unproject(this._pos),this.setLngLat(this._lngLat),this._element.style.pointerEvents="none",this._state==="pending"&&(this._state="active",this.fire(new p.n("dragstart"))),this.fire(new p.n("drag")))},this._onUp=()=>{this._element.style.pointerEvents="auto",this._positionDelta=null,this._pointerdownPos=null,this._isDragging=!1,this._map.off("mousemove",this._onMove),this._map.off("touchmove",this._onMove),this._state==="active"&&this.fire(new p.n("dragend")),this._state="inactive"},this._addDragHandler=n=>{this._element.contains(n.originalEvent.target)&&(n.preventDefault(),this._positionDelta=n.point.sub(this._pos).add(this._offset),this._pointerdownPos=n.point,this._state="pending",this._map.on("mousemove",this._onMove),this._map.on("touchmove",this._onMove),this._map.once("mouseup",this._onUp),this._map.once("touchend",this._onUp))},this._anchor=t?.anchor||"center",this._color=t?.color||"#3FB1CE",this._scale=t?.scale||1,this._draggable=t?.draggable||!1,this._clickTolerance=t?.clickTolerance||0,this._subpixelPositioning=t?.subpixelPositioning||!1,this._isDragging=!1,this._state="inactive",this._rotation=t?.rotation||0,this._rotationAlignment=t?.rotationAlignment||"auto",this._pitchAlignment=t?.pitchAlignment&&t.pitchAlignment!=="auto"?t.pitchAlignment:this._rotationAlignment,this.setOpacity(t?.opacity,t?.opacityWhenCovered),t?.element)this._element=t.element,this._offset=p.P.convert(t?.offset||[0,0]);else{this._defaultMarker=!0,this._element=pe.create("div");let n=pe.createNS("http://www.w3.org/2000/svg","svg"),a=41,c=27;n.setAttributeNS(null,"display","block"),n.setAttributeNS(null,"height",`${a}px`),n.setAttributeNS(null,"width",`${c}px`),n.setAttributeNS(null,"viewBox",`0 0 ${c} ${a}`);let f=pe.createNS("http://www.w3.org/2000/svg","g");f.setAttributeNS(null,"stroke","none"),f.setAttributeNS(null,"stroke-width","1"),f.setAttributeNS(null,"fill","none"),f.setAttributeNS(null,"fill-rule","evenodd");let y=pe.createNS("http://www.w3.org/2000/svg","g");y.setAttributeNS(null,"fill-rule","nonzero");let x=pe.createNS("http://www.w3.org/2000/svg","g");x.setAttributeNS(null,"transform","translate(3.0, 29.0)"),x.setAttributeNS(null,"fill","#000000");let w=[{rx:"10.5",ry:"5.25002273"},{rx:"10.5",ry:"5.25002273"},{rx:"9.5",ry:"4.77275007"},{rx:"8.5",ry:"4.29549936"},{rx:"7.5",ry:"3.81822308"},{rx:"6.5",ry:"3.34094679"},{rx:"5.5",ry:"2.86367051"},{rx:"4.5",ry:"2.38636864"}];for(let j of w){let $=pe.createNS("http://www.w3.org/2000/svg","ellipse");$.setAttributeNS(null,"opacity","0.04"),$.setAttributeNS(null,"cx","10.5"),$.setAttributeNS(null,"cy","5.80029008"),$.setAttributeNS(null,"rx",j.rx),$.setAttributeNS(null,"ry",j.ry),x.appendChild($)}let P=pe.createNS("http://www.w3.org/2000/svg","g");P.setAttributeNS(null,"fill",this._color);let S=pe.createNS("http://www.w3.org/2000/svg","path");S.setAttributeNS(null,"d","M27,13.5 C27,19.074644 20.250001,27.000002 14.75,34.500002 C14.016665,35.500004 12.983335,35.500004 12.25,34.500002 C6.7499993,27.000002 0,19.222562 0,13.5 C0,6.0441559 6.0441559,0 13.5,0 C20.955844,0 27,6.0441559 27,13.5 Z"),P.appendChild(S);let E=pe.createNS("http://www.w3.org/2000/svg","g");E.setAttributeNS(null,"opacity","0.25"),E.setAttributeNS(null,"fill","#000000");let C=pe.createNS("http://www.w3.org/2000/svg","path");C.setAttributeNS(null,"d","M13.5,0 C6.0441559,0 0,6.0441559 0,13.5 C0,19.222562 6.7499993,27 12.25,34.5 C13,35.522727 14.016664,35.500004 14.75,34.5 C20.250001,27 27,19.074644 27,13.5 C27,6.0441559 20.955844,0 13.5,0 Z M13.5,1 C20.415404,1 26,6.584596 26,13.5 C26,15.898657 24.495584,19.181431 22.220703,22.738281 C19.945823,26.295132 16.705119,30.142167 13.943359,33.908203 C13.743445,34.180814 13.612715,34.322738 13.5,34.441406 C13.387285,34.322738 13.256555,34.180814 13.056641,33.908203 C10.284481,30.127985 7.4148684,26.314159 5.015625,22.773438 C2.6163816,19.232715 1,15.953538 1,13.5 C1,6.584596 6.584596,1 13.5,1 Z"),E.appendChild(C);let z=pe.createNS("http://www.w3.org/2000/svg","g");z.setAttributeNS(null,"transform","translate(6.0, 7.0)"),z.setAttributeNS(null,"fill","#FFFFFF");let B=pe.createNS("http://www.w3.org/2000/svg","g");B.setAttributeNS(null,"transform","translate(8.0, 8.0)");let N=pe.createNS("http://www.w3.org/2000/svg","circle");N.setAttributeNS(null,"fill","#000000"),N.setAttributeNS(null,"opacity","0.25"),N.setAttributeNS(null,"cx","5.5"),N.setAttributeNS(null,"cy","5.5"),N.setAttributeNS(null,"r","5.4999962");let G=pe.createNS("http://www.w3.org/2000/svg","circle");G.setAttributeNS(null,"fill","#FFFFFF"),G.setAttributeNS(null,"cx","5.5"),G.setAttributeNS(null,"cy","5.5"),G.setAttributeNS(null,"r","5.4999962"),B.appendChild(N),B.appendChild(G),y.appendChild(x),y.appendChild(P),y.appendChild(E),y.appendChild(z),y.appendChild(B),n.appendChild(y),n.setAttributeNS(null,"height",a*this._scale+"px"),n.setAttributeNS(null,"width",c*this._scale+"px"),this._element.appendChild(n),this._offset=p.P.convert(t?.offset||[0,-14])}if(this._element.classList.add("maplibregl-marker"),this._element.addEventListener("dragstart",(n=>{n.preventDefault()})),this._element.addEventListener("mousedown",(n=>{n.preventDefault()})),ea(this._element,this._anchor,"marker"),t?.className)for(let n of t.className.split(" "))this._element.classList.add(n);this._popup=null}addTo(t){return this.remove(),this._map=t,this._element.hasAttribute("aria-label")||this._element.setAttribute("aria-label",t._getUIString("Marker.Title")),this._element.hasAttribute("role")||this._element.setAttribute("role","button"),t.getCanvasContainer().appendChild(this._element),t.on("move",this._update),t.on("moveend",this._update),t.on("terrain",this._update),t.on("projectiontransition",this._update),this._element.addEventListener("click",this._onClick),this.setDraggable(this._draggable),this._update(),this._map.on("click",this._onMapClick),this}remove(){return this._opacityTimeout&&(clearTimeout(this._opacityTimeout),delete this._opacityTimeout),this._map&&(this._map.off("click",this._onMapClick),this._map.off("move",this._update),this._map.off("moveend",this._update),this._map.off("terrain",this._update),this._map.off("projectiontransition",this._update),this._map.off("mousedown",this._addDragHandler),this._map.off("touchstart",this._addDragHandler),this._map.off("mouseup",this._onUp),this._map.off("touchend",this._onUp),this._map.off("mousemove",this._onMove),this._map.off("touchmove",this._onMove),delete this._map),this._element.removeEventListener("click",this._onClick),this._element.remove(),this._popup&&this._popup.remove(),this}getLngLat(){return this._lngLat}setLngLat(t){return this._lngLat=p.W.convert(t),this._pos=null,this._popup&&this._popup.setLngLat(this._lngLat),this._update(),this}getElement(){return this._element}setPopup(t){if(this._popup&&(this._popup.remove(),this._popup=null,this._element.removeEventListener("keypress",this._onKeyPress),this._originalTabIndex||this._element.removeAttribute("tabindex")),t){if(!("offset"in t.options)){let c=Math.abs(13.5)/Math.SQRT2;t.options.offset=this._defaultMarker?{top:[0,0],"top-left":[0,0],"top-right":[0,0],bottom:[0,-38.1],"bottom-left":[c,-1*(38.1-13.5+c)],"bottom-right":[-c,-1*(38.1-13.5+c)],left:[13.5,-1*(38.1-13.5)],right:[-13.5,-1*(38.1-13.5)]}:this._offset}this._popup=t,this._originalTabIndex=this._element.getAttribute("tabindex"),this._originalTabIndex||this._element.setAttribute("tabindex","0"),this._element.addEventListener("keypress",this._onKeyPress)}return this}setSubpixelPositioning(t){return this._subpixelPositioning=t,this}getPopup(){return this._popup}togglePopup(){let t=this._popup;return this._element.style.opacity===this._opacityWhenCovered?this:t?(t.isOpen()?t.remove():(t.setLngLat(this._lngLat),t.addTo(this._map)),this):this}_updateOpacity(t=!1){var n,a;let c=(n=this._map)===null||n===void 0?void 0:n.terrain,f=this._map.transform.isLocationOccluded(this._lngLat);if(!c||f){let z=f?this._opacityWhenCovered:this._opacity;return void(this._element.style.opacity!==z&&(this._element.style.opacity=z,this._element.classList.toggle("maplibregl-marker-covered",f)))}if(t)this._opacityTimeout=null;else{if(this._opacityTimeout)return;this._opacityTimeout=setTimeout((()=>{this._opacityTimeout=null}),100)}let y=this._map,x=y.terrain.depthAtPoint(this._pos),w=y.terrain.getElevationForLngLat(this._lngLat,y.transform);if(y.transform.lngLatToCameraDepth(this._lngLat,w)-x<.006)return this._element.style.opacity=this._opacity,void this._element.classList.remove("maplibregl-marker-covered");let P=-this._offset.y/y.transform.pixelsPerMeter,S=Math.sin(y.getPitch()*Math.PI/180)*P,E=y.terrain.depthAtPoint(new p.P(this._pos.x,this._pos.y-this._offset.y)),C=y.transform.lngLatToCameraDepth(this._lngLat,w+S)-E>.006;!((a=this._popup)===null||a===void 0)&&a.isOpen()&&C&&this._popup.remove(),this._element.style.opacity=C?this._opacityWhenCovered:this._opacity,this._element.classList.toggle("maplibregl-marker-covered",C)}getOffset(){return this._offset}setOffset(t){return this._offset=p.P.convert(t),this._update(),this}addClassName(t){this._element.classList.add(t)}removeClassName(t){this._element.classList.remove(t)}toggleClassName(t){return this._element.classList.toggle(t)}setDraggable(t){return this._draggable=!!t,this._map&&(t?(this._map.on("mousedown",this._addDragHandler),this._map.on("touchstart",this._addDragHandler)):(this._map.off("mousedown",this._addDragHandler),this._map.off("touchstart",this._addDragHandler))),this}isDraggable(){return this._draggable}setRotation(t){return this._rotation=t||0,this._update(),this}getRotation(){return this._rotation}setRotationAlignment(t){return this._rotationAlignment=t||"auto",this._update(),this}getRotationAlignment(){return this._rotationAlignment}setPitchAlignment(t){return this._pitchAlignment=t&&t!=="auto"?t:this._rotationAlignment,this._update(),this}getPitchAlignment(){return this._pitchAlignment}setOpacity(t,n){return(this._opacity===void 0||t===void 0&&n===void 0)&&(this._opacity="1",this._opacityWhenCovered="0.2"),t!==void 0&&(this._opacity=String(t)),n!==void 0&&(this._opacityWhenCovered=String(n)),this._map&&this._updateOpacity(!0),this}}let Dl={positionOptions:{enableHighAccuracy:!1,maximumAge:0,timeout:6e3},fitBoundsOptions:{maxZoom:15},trackUserLocation:!1,showAccuracyCircle:!0,showUserLocation:!0},so=0,wn=!1,zl={maxWidth:100,unit:"metric"};function rs(u,t,n){let a=n?.maxWidth||100,c=u._container.clientHeight/2,f=u._container.clientWidth/2,y=u.unproject([f-a/2,c]),x=u.unproject([f+a/2,c]),w=Math.round(u.project(x).x-u.project(y).x),P=Math.min(a,w,u._container.clientWidth),S=y.distanceTo(x);if(n?.unit==="imperial"){let E=3.2808*S;E>5280?Tn(t,P,E/5280,u._getUIString("ScaleControl.Miles")):Tn(t,P,E,u._getUIString("ScaleControl.Feet"))}else n?.unit==="nautical"?Tn(t,P,S/1852,u._getUIString("ScaleControl.NauticalMiles")):S>=1e3?Tn(t,P,S/1e3,u._getUIString("ScaleControl.Kilometers")):Tn(t,P,S,u._getUIString("ScaleControl.Meters"))}function Tn(u,t,n,a){let c=(function(f){let y=Math.pow(10,`${Math.floor(f)}`.length-1),x=f/y;return x=x>=10?10:x>=5?5:x>=3?3:x>=2?2:x>=1?1:(function(w){let P=Math.pow(10,Math.ceil(-Math.log(w)/Math.LN10));return Math.round(w*P)/P})(x),y*x})(n);u.style.width=t*(c/n)+"px",u.innerHTML=`${c} ${a}`}let Rl={closeButton:!0,closeOnClick:!0,focusAfterOpen:!0,className:"",maxWidth:"240px",subpixelPositioning:!1,locationOccludedOpacity:void 0,padding:void 0},ta=["a[href]","[tabindex]:not([tabindex='-1'])","[contenteditable]:not([contenteditable='false'])","button:not([disabled])","input:not([disabled])","select:not([disabled])","textarea:not([disabled])"].join(", ");function ia(u){if(u){if(typeof u=="number"){let t=Math.round(Math.abs(u)/Math.SQRT2);return{center:new p.P(0,0),top:new p.P(0,u),"top-left":new p.P(t,t),"top-right":new p.P(-t,t),bottom:new p.P(0,-u),"bottom-left":new p.P(t,-t),"bottom-right":new p.P(-t,-t),left:new p.P(u,0),right:new p.P(-u,0)}}if(u instanceof p.P||Array.isArray(u)){let t=p.P.convert(u);return{center:t,top:t,"top-left":t,"top-right":t,bottom:t,"bottom-left":t,"bottom-right":t,left:t,right:t}}return{center:p.P.convert(u.center||[0,0]),top:p.P.convert(u.top||[0,0]),"top-left":p.P.convert(u["top-left"]||[0,0]),"top-right":p.P.convert(u["top-right"]||[0,0]),bottom:p.P.convert(u.bottom||[0,0]),"bottom-left":p.P.convert(u["bottom-left"]||[0,0]),"bottom-right":p.P.convert(u["bottom-right"]||[0,0]),left:p.P.convert(u.left||[0,0]),right:p.P.convert(u.right||[0,0])}}return ia(new p.P(0,0))}let kl=Te;k.AJAXError=p.cG,k.EXTENT=p.a6,k.Event=p.n,k.Evented=p.E,k.LngLat=p.W,k.MercatorCoordinate=p.a7,k.Point=p.P,k.addProtocol=p.cH,k.config=p.c,k.removeProtocol=p.cI,k.AttributionControl=Ui,k.BoxZoomHandler=or,k.CanvasSource=ka,k.CooperativeGesturesHandler=Ce,k.DoubleClickZoomHandler=El,k.DragPanHandler=er,k.DragRotateHandler=Ko,k.EdgeInsets=Un,k.FullscreenControl=class extends p.E{constructor(u={}){var t;super(),this._onFullscreenChange=()=>{var n;let a=window.document.fullscreenElement||window.document.webkitFullscreenElement;for(;!((n=a?.shadowRoot)===null||n===void 0)&&n.fullscreenElement;)a=a.shadowRoot.fullscreenElement;a===this._container!==this._fullscreen&&this._handleFullscreenChange()},this._onClickFullscreen=()=>{this._isFullscreen()?this._exitFullscreen():this._requestFullscreen()},this._fullscreen=!1,this._pseudo=(t=u.pseudo)!==null&&t!==void 0&&t,u?.container&&(u.container instanceof HTMLElement?this._container=u.container:p.w("Full screen control 'container' must be a DOM element.")),"onfullscreenchange"in document?this._fullscreenchange="fullscreenchange":"onmozfullscreenchange"in document?this._fullscreenchange="mozfullscreenchange":"onwebkitfullscreenchange"in document?this._fullscreenchange="webkitfullscreenchange":"onmsfullscreenchange"in document&&(this._fullscreenchange="MSFullscreenChange")}onAdd(u){return this._map=u,this._container||(this._container=this._map.getContainer()),this._controlContainer=pe.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._setupUI(),this._controlContainer}onRemove(){this._controlContainer.remove(),this._map=null,window.document.removeEventListener(this._fullscreenchange,this._onFullscreenChange)}_setupUI(){let u=this._fullscreenButton=pe.create("button","maplibregl-ctrl-fullscreen",this._controlContainer);pe.create("span","maplibregl-ctrl-icon",u).setAttribute("aria-hidden","true"),u.type="button",this._updateTitle(),this._fullscreenButton.addEventListener("click",this._onClickFullscreen),window.document.addEventListener(this._fullscreenchange,this._onFullscreenChange)}_updateTitle(){let u=this._getTitle();this._fullscreenButton.setAttribute("aria-label",u),this._fullscreenButton.title=u}_getTitle(){return this._map._getUIString(this._isFullscreen()?"FullscreenControl.Exit":"FullscreenControl.Enter")}_isFullscreen(){return this._fullscreen}_handleFullscreenChange(){this._fullscreen=!this._fullscreen,this._fullscreenButton.classList.toggle("maplibregl-ctrl-shrink"),this._fullscreenButton.classList.toggle("maplibregl-ctrl-fullscreen"),this._updateTitle(),this._fullscreen?(this.fire(new p.n("fullscreenstart")),this._prevCooperativeGesturesEnabled=this._map.cooperativeGestures.isEnabled(),this._map.cooperativeGestures.disable()):(this.fire(new p.n("fullscreenend")),this._prevCooperativeGesturesEnabled&&this._map.cooperativeGestures.enable())}_exitFullscreen(){this._pseudo?this._togglePseudoFullScreen():window.document.exitFullscreen?window.document.exitFullscreen():window.document.webkitCancelFullScreen?window.document.webkitCancelFullScreen():this._togglePseudoFullScreen()}_requestFullscreen(){this._pseudo?this._togglePseudoFullScreen():this._container.requestFullscreen?this._container.requestFullscreen():this._container.webkitRequestFullscreen?this._container.webkitRequestFullscreen():this._togglePseudoFullScreen()}_togglePseudoFullScreen(){this._container.classList.toggle("maplibregl-pseudo-fullscreen"),this._handleFullscreenChange(),this._map.resize()}},k.GeoJSONSource=us,k.GeolocateControl=class extends p.E{constructor(u){super(),this._onSuccess=t=>{if(this._map){if(this._isOutOfMapMaxBounds(t))return this._setErrorState(),this.fire(new p.n("outofmaxbounds",t)),this._updateMarker(),void this._finish();if(this.options.trackUserLocation)switch(this._lastKnownPosition=t,this._watchState){case"WAITING_ACTIVE":case"ACTIVE_LOCK":case"ACTIVE_ERROR":this._watchState="ACTIVE_LOCK",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active-error"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active");break;case"BACKGROUND":case"BACKGROUND_ERROR":this._watchState="BACKGROUND",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background-error"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-background");break;default:throw new Error(`Unexpected watchState ${this._watchState}`)}this.options.showUserLocation&&this._watchState!=="OFF"&&this._updateMarker(t),this.options.trackUserLocation&&this._watchState!=="ACTIVE_LOCK"||this._updateCamera(t),this.options.showUserLocation&&this._dotElement.classList.remove("maplibregl-user-location-dot-stale"),this.fire(new p.n("geolocate",t)),this._finish()}},this._updateCamera=t=>{let n=new p.W(t.coords.longitude,t.coords.latitude),a=t.coords.accuracy,c=this._map.getBearing(),f=p.e({bearing:c},this.options.fitBoundsOptions),y=Re.fromLngLat(n,a);this._map.fitBounds(y,f,{geolocateSource:!0})},this._updateMarker=t=>{if(t){let n=new p.W(t.coords.longitude,t.coords.latitude);this._accuracyCircleMarker.setLngLat(n).addTo(this._map),this._userLocationDotMarker.setLngLat(n).addTo(this._map),this._accuracy=t.coords.accuracy,this._updateCircleRadiusIfNeeded()}else this._userLocationDotMarker.remove(),this._accuracyCircleMarker.remove()},this._onUpdate=()=>{this._updateCircleRadiusIfNeeded()},this._onError=t=>{if(this._map){if(t.code===1){this._watchState="OFF",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active-error"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background-error"),this._geolocateButton.disabled=!0;let n=this._map._getUIString("GeolocateControl.LocationNotAvailable");this._geolocateButton.title=n,this._geolocateButton.setAttribute("aria-label",n),this._geolocationWatchID!==void 0&&this._clearWatch()}else{if(t.code===3&&wn)return;this._setErrorState()}this._watchState!=="OFF"&&this.options.showUserLocation&&this._dotElement.classList.add("maplibregl-user-location-dot-stale"),this.fire(new p.n("error",t)),this._finish()}},this._finish=()=>{this._timeoutId&&clearTimeout(this._timeoutId),this._timeoutId=void 0},this._onMoveStart=t=>{if(!this._map)return;let n=t?.[0]instanceof ResizeObserverEntry;t.geolocateSource||this._watchState!=="ACTIVE_LOCK"||n||this._map.isZooming()||(this._watchState="BACKGROUND",this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this.fire(new p.n("trackuserlocationend")),this.fire(new p.n("userlocationlostfocus")))},this._setupUI=()=>{this._map&&(this._container.addEventListener("contextmenu",(t=>{t.preventDefault()})),this._geolocateButton=pe.create("button","maplibregl-ctrl-geolocate",this._container),pe.create("span","maplibregl-ctrl-icon",this._geolocateButton).setAttribute("aria-hidden","true"),this._geolocateButton.type="button",this._geolocateButton.disabled=!0)},this._finishSetupUI=t=>{if(this._map){if(t===!1){p.w("Geolocation support is not available so the GeolocateControl will be disabled.");let n=this._map._getUIString("GeolocateControl.LocationNotAvailable");this._geolocateButton.disabled=!0,this._geolocateButton.title=n,this._geolocateButton.setAttribute("aria-label",n)}else{let n=this._map._getUIString("GeolocateControl.FindMyLocation");this._geolocateButton.disabled=!1,this._geolocateButton.title=n,this._geolocateButton.setAttribute("aria-label",n)}this.options.trackUserLocation&&(this._geolocateButton.setAttribute("aria-pressed","false"),this._watchState="OFF"),this.options.showUserLocation&&(this._dotElement=pe.create("div","maplibregl-user-location-dot"),this._userLocationDotMarker=new is({element:this._dotElement}),this._circleElement=pe.create("div","maplibregl-user-location-accuracy-circle"),this._accuracyCircleMarker=new is({element:this._circleElement,pitchAlignment:"map"}),this.options.trackUserLocation&&(this._watchState="OFF"),this._map.on("zoom",this._onUpdate),this._map.on("move",this._onUpdate),this._map.on("rotate",this._onUpdate),this._map.on("pitch",this._onUpdate)),this._geolocateButton.addEventListener("click",(()=>this.trigger())),this._setup=!0,this.options.trackUserLocation&&this._map.on("movestart",this._onMoveStart)}},this.options=p.e({},Dl,u)}onAdd(u){return this._map=u,this._container=pe.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._setupUI(),(function(){return p._(this,arguments,void 0,(function*(t=!1){if(_r!==void 0&&!t)return _r;if(window.navigator.permissions===void 0)return _r=!!window.navigator.geolocation,_r;try{_r=(yield window.navigator.permissions.query({name:"geolocation"})).state!=="denied"}catch{_r=!!window.navigator.geolocation}return _r}))})().then((t=>this._finishSetupUI(t))),this._container}onRemove(){this._geolocationWatchID!==void 0&&(window.navigator.geolocation.clearWatch(this._geolocationWatchID),this._geolocationWatchID=void 0),this.options.showUserLocation&&this._userLocationDotMarker&&this._userLocationDotMarker.remove(),this.options.showAccuracyCircle&&this._accuracyCircleMarker&&this._accuracyCircleMarker.remove(),this._container.remove(),this._map.off("movestart",this._onMoveStart),this._map.off("zoom",this._onUpdate),this._map.off("move",this._onUpdate),this._map.off("rotate",this._onUpdate),this._map.off("pitch",this._onUpdate),this._map=void 0,so=0,wn=!1}_isOutOfMapMaxBounds(u){let t=this._map.getMaxBounds(),n=u.coords;return t&&(n.longitudet.getEast()||n.latitudet.getNorth())}_setErrorState(){switch(this._watchState){case"WAITING_ACTIVE":this._watchState="ACTIVE_ERROR",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active-error");break;case"ACTIVE_LOCK":this._watchState="ACTIVE_ERROR",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active-error"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting");break;case"BACKGROUND":this._watchState="BACKGROUND_ERROR",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-background-error"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting");break;case"ACTIVE_ERROR":case"BACKGROUND_ERROR":case"OFF":case void 0:break;default:throw new Error(`Unexpected watchState ${this._watchState}`)}}_updateCircleRadiusIfNeeded(){let u=this._userLocationDotMarker.getLngLat();if(!(this.options.showUserLocation&&this.options.showAccuracyCircle&&this._accuracy&&u))return;let t=this._map.project(u),n=this._map.unproject([t.x+100,t.y]),a=u.distanceTo(n)/100,c=2*this._accuracy/a;this._circleElement.style.width=`${c.toFixed(2)}px`,this._circleElement.style.height=`${c.toFixed(2)}px`}trigger(){if(!this._setup)return p.w("Geolocate control triggered before added to a map"),!1;if(this.options.trackUserLocation){switch(this._watchState){case"OFF":this._watchState="WAITING_ACTIVE",this.fire(new p.n("trackuserlocationstart"));break;case"WAITING_ACTIVE":case"ACTIVE_LOCK":case"ACTIVE_ERROR":case"BACKGROUND_ERROR":so--,wn=!1,this._watchState="OFF",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active-error"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background-error"),this.fire(new p.n("trackuserlocationend"));break;case"BACKGROUND":this._watchState="ACTIVE_LOCK",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background"),this._lastKnownPosition&&this._updateCamera(this._lastKnownPosition),this.fire(new p.n("trackuserlocationstart")),this.fire(new p.n("userlocationfocus"));break;default:throw new Error(`Unexpected watchState ${this._watchState}`)}switch(this._watchState){case"WAITING_ACTIVE":this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active");break;case"ACTIVE_LOCK":this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active");break;case"OFF":break;default:throw new Error(`Unexpected watchState ${this._watchState}`)}if(this._watchState==="OFF"&&this._geolocationWatchID!==void 0)this._clearWatch();else if(this._geolocationWatchID===void 0){let u;this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.setAttribute("aria-pressed","true"),so++,so>1?(u={maximumAge:6e5,timeout:0},wn=!0):(u=this.options.positionOptions,wn=!1),this._geolocationWatchID=window.navigator.geolocation.watchPosition(this._onSuccess,this._onError,u)}}else window.navigator.geolocation.getCurrentPosition(this._onSuccess,this._onError,this.options.positionOptions),this._timeoutId=setTimeout(this._finish,1e4);return!0}_clearWatch(){window.navigator.geolocation.clearWatch(this._geolocationWatchID),this._geolocationWatchID=void 0,this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.setAttribute("aria-pressed","false"),this.options.showUserLocation&&this._updateMarker(null)}},k.GlobeControl=class{constructor(){this._toggleProjection=()=>{var u;let t=(u=this._map.getProjection())===null||u===void 0?void 0:u.type;this._map.setProjection(t!=="mercator"&&t?{type:"mercator"}:{type:"globe"}),this._updateGlobeIcon()},this._updateGlobeIcon=()=>{var u;this._globeButton.classList.remove("maplibregl-ctrl-globe"),this._globeButton.classList.remove("maplibregl-ctrl-globe-enabled"),((u=this._map.getProjection())===null||u===void 0?void 0:u.type)==="globe"?(this._globeButton.classList.add("maplibregl-ctrl-globe-enabled"),this._globeButton.title=this._map._getUIString("GlobeControl.Disable")):(this._globeButton.classList.add("maplibregl-ctrl-globe"),this._globeButton.title=this._map._getUIString("GlobeControl.Enable"))}}onAdd(u){return this._map=u,this._container=pe.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._globeButton=pe.create("button","maplibregl-ctrl-globe",this._container),pe.create("span","maplibregl-ctrl-icon",this._globeButton).setAttribute("aria-hidden","true"),this._globeButton.type="button",this._globeButton.addEventListener("click",this._toggleProjection),this._updateGlobeIcon(),this._map.on("styledata",this._updateGlobeIcon),this._map.on("projectiontransition",this._updateGlobeIcon),this._container}onRemove(){this._container.remove(),this._map.off("styledata",this._updateGlobeIcon),this._map.off("projectiontransition",this._updateGlobeIcon),this._globeButton.removeEventListener("click",this._toggleProjection),this._map=void 0}},k.Hash=Zo,k.ImageSource=Ar,k.KeyboardHandler=ih,k.LngLatBounds=Re,k.LogoControl=Cl,k.Map=Js,k.MapLibreMap=Js,k.MapMouseEvent=zi,k.MapTouchEvent=Wo,k.MapWheelEvent=Hc,k.Marker=is,k.NavigationControl=class{constructor(u){this._updateZoomButtons=()=>{let t=this._map.getZoom(),n=t===this._map.getMaxZoom(),a=t===this._map.getMinZoom();this._zoomInButton.disabled=n,this._zoomOutButton.disabled=a,this._zoomInButton.setAttribute("aria-disabled",n.toString()),this._zoomOutButton.setAttribute("aria-disabled",a.toString())},this._rotateCompassArrow=()=>{this._compassIcon.style.transform=this.options.visualizePitch&&this.options.visualizeRoll?`scale(${1/Math.pow(Math.cos(this._map.transform.pitchInRadians),.5)}) rotateZ(${-this._map.transform.roll}deg) rotateX(${this._map.transform.pitch}deg) rotateZ(${-this._map.transform.bearing}deg)`:this.options.visualizePitch?`scale(${1/Math.pow(Math.cos(this._map.transform.pitchInRadians),.5)}) rotateX(${this._map.transform.pitch}deg) rotateZ(${-this._map.transform.bearing}deg)`:this.options.visualizeRoll?`rotate(${-this._map.transform.bearing-this._map.transform.roll}deg)`:`rotate(${-this._map.transform.bearing}deg)`},this._setButtonTitle=(t,n)=>{let a=this._map._getUIString(`NavigationControl.${n}`);t.title=a,t.setAttribute("aria-label",a)},this.options=p.e({},Al,u),this._container=pe.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._container.addEventListener("contextmenu",(t=>t.preventDefault())),this.options.showZoom&&(this._zoomInButton=this._createButton("maplibregl-ctrl-zoom-in",(t=>this._map.zoomIn({},{originalEvent:t}))),pe.create("span","maplibregl-ctrl-icon",this._zoomInButton).setAttribute("aria-hidden","true"),this._zoomOutButton=this._createButton("maplibregl-ctrl-zoom-out",(t=>this._map.zoomOut({},{originalEvent:t}))),pe.create("span","maplibregl-ctrl-icon",this._zoomOutButton).setAttribute("aria-hidden","true")),this.options.showCompass&&(this._compass=this._createButton("maplibregl-ctrl-compass",(t=>{this.options.visualizePitch?this._map.resetNorthPitch({},{originalEvent:t}):this._map.resetNorth({},{originalEvent:t})})),this._compassIcon=pe.create("span","maplibregl-ctrl-icon",this._compass),this._compassIcon.setAttribute("aria-hidden","true"))}onAdd(u){return this._map=u,this.options.showZoom&&(this._setButtonTitle(this._zoomInButton,"ZoomIn"),this._setButtonTitle(this._zoomOutButton,"ZoomOut"),this._map.on("zoom",this._updateZoomButtons),this._updateZoomButtons()),this.options.showCompass&&(this._setButtonTitle(this._compass,"ResetBearing"),this.options.visualizePitch&&this._map.on("pitch",this._rotateCompassArrow),this.options.visualizeRoll&&this._map.on("roll",this._rotateCompassArrow),this._map.on("rotate",this._rotateCompassArrow),this._rotateCompassArrow(),this._handler=new es(this._map,this._compass,this.options.visualizePitch)),this._container}onRemove(){this._container.remove(),this.options.showZoom&&this._map.off("zoom",this._updateZoomButtons),this.options.showCompass&&(this.options.visualizePitch&&this._map.off("pitch",this._rotateCompassArrow),this.options.visualizeRoll&&this._map.off("roll",this._rotateCompassArrow),this._map.off("rotate",this._rotateCompassArrow),this._handler.off(),delete this._handler),delete this._map}_createButton(u,t){let n=pe.create("button",u,this._container);return n.type="button",n.addEventListener("click",t),n}},k.Popup=class extends p.E{constructor(u){super(),this._updateOpacity=()=>{this.options.locationOccludedOpacity!==void 0&&(this._container.style.opacity=this._map.transform.isLocationOccluded(this.getLngLat())?`${this.options.locationOccludedOpacity}`:"")},this.remove=()=>(this._content&&this._content.remove(),this._container&&(this._container.remove(),delete this._container),this._map&&(this._map.off("move",this._update),this._map.off("move",this._onClose),this._map.off("click",this._onClose),this._map.off("remove",this.remove),this._map.off("terrain",this._update),this._map.off("projectiontransition",this._update),this._map.off("mousemove",this._update),this._map.off("mouseup",this._update),this._map.off("drag",this._update),this._map._canvasContainer.classList.remove("maplibregl-track-pointer"),delete this._map,this.fire(new p.n("close"))),this),this._update=t=>{if(!this._map||!this._lngLat&&!this._trackPointer||!this._content)return;if(!this._container){if(this._container=pe.create("div","maplibregl-popup",this._map.getContainer()),this._tip=pe.create("div","maplibregl-popup-tip",this._container),this._container.appendChild(this._content),this.options.className)for(let x of this.options.className.split(" "))this._container.classList.add(x);this._closeButton&&this._closeButton.setAttribute("aria-label",this._map._getUIString("Popup.Close")),this._trackPointer&&this._container.classList.add("maplibregl-popup-track-pointer")}let n;if(this.options.maxWidth&&this._container.style.maxWidth!==this.options.maxWidth&&(this._container.style.maxWidth=this.options.maxWidth),this._lngLat=Qs(this._lngLat,this._flatPos,this._map.transform,this._trackPointer),t&&"point"in t&&t.point&&(n=t.point),this._trackPointer&&!n)return;let a=this._flatPos=this._pos=this._trackPointer&&n?n:this._map.project(this._lngLat);this._map.terrain&&(this._flatPos=this._trackPointer&&n?n:this._map.transform.locationToScreenPoint(this._lngLat));let c=this.options.anchor,f=ia(this.options.offset);if(!c){let x=this._container.offsetWidth,w=this._container.offsetHeight,P=(function(E){var C,z,B,N;return E?{top:(C=E.top)!==null&&C!==void 0?C:0,right:(z=E.right)!==null&&z!==void 0?z:0,bottom:(B=E.bottom)!==null&&B!==void 0?B:0,left:(N=E.left)!==null&&N!==void 0?N:0}:{top:0,right:0,bottom:0,left:0}})(this.options.padding),S;S=a.y+f.bottom.ythis._map.transform.height-w-P.bottom?["bottom"]:[],a.xthis._map.transform.width-x/2-P.right&&S.push("right"),c=S.length===0?"bottom":S.join("-")}let y=a.add(f[c]);this.options.subpixelPositioning||(y=y.round()),this._container.style.transform=`${ts[c]} translate(${y.x}px,${y.y}px)`,ea(this._container,c,"popup"),this._updateOpacity()},this._onClose=()=>{this.remove()},this.options=p.e(Object.create(Rl),u)}addTo(u){return this._map&&this.remove(),this._map=u,this.options.closeOnClick&&this._map.on("click",this._onClose),this.options.closeOnMove&&this._map.on("move",this._onClose),this._map.on("remove",this.remove),this._map.on("terrain",this._update),this._map.on("projectiontransition",this._update),this._update(),this._focusFirstElement(),this._trackPointer?(this._map.on("mousemove",this._update),this._map.on("mouseup",this._update),this._container&&this._container.classList.add("maplibregl-popup-track-pointer"),this._map._canvasContainer.classList.add("maplibregl-track-pointer")):this._map.on("move",this._update),this.fire(new p.n("open")),this}isOpen(){return!!this._map}getLngLat(){return this._lngLat}setLngLat(u){return this._lngLat=p.W.convert(u),this._pos=null,this._flatPos=null,this._trackPointer=!1,this._update(),this._map&&(this._map.on("move",this._update),this._map.off("mousemove",this._update),this._container&&this._container.classList.remove("maplibregl-popup-track-pointer"),this._map._canvasContainer.classList.remove("maplibregl-track-pointer")),this}trackPointer(){return this._trackPointer=!0,this._pos=null,this._flatPos=null,this._update(),this._map&&(this._map.off("move",this._update),this._map.on("mousemove",this._update),this._map.on("drag",this._update),this._container&&this._container.classList.add("maplibregl-popup-track-pointer"),this._map._canvasContainer.classList.add("maplibregl-track-pointer")),this}getElement(){return this._container}setText(u){return this.setDOMContent(document.createTextNode(u))}setHTML(u){let t=document.createDocumentFragment(),n=document.createElement("body"),a;for(n.innerHTML=u;a=n.firstChild,a;)t.appendChild(a);return this.setDOMContent(t)}getMaxWidth(){var u;return(u=this._container)===null||u===void 0?void 0:u.style.maxWidth}setMaxWidth(u){return this.options.maxWidth=u,this._update(),this}setDOMContent(u){if(this._content)for(;this._content.hasChildNodes();)this._content.firstChild&&this._content.removeChild(this._content.firstChild);else this._content=pe.create("div","maplibregl-popup-content",this._container);return this._content.appendChild(u),this._createCloseButton(),this._update(),this._focusFirstElement(),this}addClassName(u){return this._container&&this._container.classList.add(u),this}removeClassName(u){return this._container&&this._container.classList.remove(u),this}setOffset(u){return this.options.offset=u,this._update(),this}toggleClassName(u){if(this._container)return this._container.classList.toggle(u)}setSubpixelPositioning(u){this.options.subpixelPositioning=u}setPadding(u){this.options.padding=u,this._update()}_createCloseButton(){this.options.closeButton&&(this._closeButton=pe.create("button","maplibregl-popup-close-button",this._content),this._closeButton.type="button",this._closeButton.innerHTML="×",this._closeButton.addEventListener("click",this._onClose))}_focusFirstElement(){if(!this.options.focusAfterOpen||!this._container)return;let u=this._container.querySelector(ta);u&&u.focus()}},k.RasterDEMTileSource=Ht,k.RasterTileSource=Mi,k.ScaleControl=class{constructor(u){this._onMove=()=>{rs(this._map,this._container,this.options)},this.setUnit=t=>{this.options.unit=t,rs(this._map,this._container,this.options)},this.options=Object.assign(Object.assign({},zl),u)}getDefaultPosition(){return"bottom-left"}onAdd(u){return this._map=u,this._container=pe.create("div","maplibregl-ctrl maplibregl-ctrl-scale",u.getContainer()),this._map.on("move",this._onMove),this._onMove(),this._container}onRemove(){this._container.remove(),this._map.off("move",this._onMove),this._map=void 0}},k.ScrollZoomHandler=Ml,k.Style=pn,k.TerrainControl=class{constructor(u){this._toggleTerrain=()=>{this._map.getTerrain()?this._map.setTerrain(null):this._map.setTerrain(this.options),this._updateTerrainIcon()},this._updateTerrainIcon=()=>{this._terrainButton.classList.remove("maplibregl-ctrl-terrain"),this._terrainButton.classList.remove("maplibregl-ctrl-terrain-enabled"),this._map.terrain?(this._terrainButton.classList.add("maplibregl-ctrl-terrain-enabled"),this._terrainButton.title=this._map._getUIString("TerrainControl.Disable")):(this._terrainButton.classList.add("maplibregl-ctrl-terrain"),this._terrainButton.title=this._map._getUIString("TerrainControl.Enable"))},this.options=u}onAdd(u){return this._map=u,this._container=pe.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._terrainButton=pe.create("button","maplibregl-ctrl-terrain",this._container),pe.create("span","maplibregl-ctrl-icon",this._terrainButton).setAttribute("aria-hidden","true"),this._terrainButton.type="button",this._terrainButton.addEventListener("click",this._toggleTerrain),this._updateTerrainIcon(),this._map.on("terrain",this._updateTerrainIcon),this._container}onRemove(){this._container.remove(),this._map.off("terrain",this._updateTerrainIcon),this._map=void 0}},k.TwoFingersTouchPitchHandler=gr,k.TwoFingersTouchRotateHandler=th,k.TwoFingersTouchZoomHandler=eh,k.TwoFingersTouchZoomRotateHandler=Ie,k.VectorTileSource=Wt,k.VideoSource=Qr,k.addSourceType=(u,t)=>p._(void 0,void 0,void 0,(function*(){if(ds(u))throw new Error(`A source type called "${u}" already exists.`);((n,a)=>{La[n]=a})(u,t)})),k.clearPrewarmedResources=function(){let u=Bi;u&&(u.isPreloaded()&&u.numActive()===1?(u.release(vt),Bi=null):console.warn("Could not clear WebWorkers since there are active Map instances that still reference it. The pre-warmed WebWorker pool can only be cleared when all map instances have been removed with map.remove()"))},k.createTileMesh=qn,k.getGlobalDispatcher=li,k.getMaxParallelImageRequests=function(){return p.c.MAX_PARALLEL_IMAGE_REQUESTS},k.getRTLTextPluginStatus=function(){return Dr().getRTLTextPluginStatus()},k.getVersion=function(){return kl},k.getWorkerCount=function(){return xt.workerCount},k.getWorkerUrl=function(){return p.c.WORKER_URL},k.importScriptInWorkers=function(u){return li().broadcast("IS",u)},k.isTimeFrozen=function(){return Ir.isFrozen()},k.now=Xe,k.prewarm=function(){Yr().acquire(vt)},k.restoreNow=function(){Ir.restoreNow()},k.setMaxParallelImageRequests=function(u){p.c.MAX_PARALLEL_IMAGE_REQUESTS=u},k.setNow=function(u){Ir.setNow(u)},k.setRTLTextPlugin=function(u,t){return Dr().setRTLTextPlugin(u,t)},k.setWorkerCount=function(u){xt.workerCount=u},k.setWorkerUrl=function(u){p.c.WORKER_URL=u}}));var cr=Le;return cr}))});Da();var $_=[["DUP","Democratic Unionist Party","DUP Civil Servant (Retired)"],["UUP","Ulster Unionist Party","Ulster Unionist","Official Unionist Party","Official Unionist","Shopkeeper, Ulster Unionist","Businssman Ulster Unionist"],["AP","Alliance Party","Alliance","Alliance Party of Northern Ireland"],["SDLP","Social Democratic and Labour Party"],["SF","Sinn F\xE9in","Sinn Fein"],["Ind U","Independent Unionist","Independent Progressive Unionist","Independent Liberal Unionist","Unofficial Unionist"],["Ind O","Independent Other"],["Ind N","Independent Nationalist","Ind Nat","unofficial (non-party) Sinn F\xE9in","Irish Republican"],["Ind","Independent","Non party/Independent","Non-party","Non party","NON-P","Independent - Northern Ireland independence","Non party/An Chomhdhail Phobail | People's Convention","Non party/Fathers Rights Responsibilities","Independent Farmer"],["GP","Green Party","Green","Green Party Northern Ireland","Green / Ecology","Green/Comhaontas Glas","Green Alliance/Comhaontas Glas","G.P."],["PBP","People Before Profit","People Before Profit Alliance","P.B.P.A."],["S-PBP","Solidarity\u2013People Before Profit","Solidarity-PBP","S.P.B.P."],["TUV","Traditional Unionist Voice"],["CCLA","Cross-Community Labour Alternative"],["CON","Conservative Party","Conservative","Conservatives","NI Conservatives"],["AO","Aont\xFA"],["FF","Fianna F\xE1il","Fianna Fail"],["FG","Fine Gael"],["LAB","Labour Party","Irish Labour","Labour","Irish Labour Party","Lab.","LAB.","Ir Lab"],["SD","Social Democrats"],["PUP","Progressive Unionist Party","Progressive Unionist"],["UKIP","UK Independence Party"],["WP","Workers' Party","Workers Party","Workers'","W.P."],["SFWP","Sinn F\xE9in The Workers' Party","Sinn F\xE9in Workers'"],["RC","Republican Clubs"],["VUPP","Vanguard Unionist Progressive Party"],["NILP","Northern Ireland Labour Party","NI Labour"],["LPNI","Labour Party of Northern Ireland"],["NALAB","Newtownabbey Labour"],["NILRC","Northern Ireland Labour Representation Committee"],["PD","Progressive Democrats","P.D."],["IIP","Irish Independence Party"],["UPNI","Unionist Party of Northern Ireland"],["CnaG","Cumann na nGaedheal"],["UDP","Ulster Democratic Party"],["UKUP","UK Unionist Party"],["Nat","Nationalist Party","Nationalist Party (Northern Ireland)"],["IPP","Irish Parliamentary Party","Irish Parliamentary"],["UPUP","Ulster Popular Unionist Party"],["SP","Socialist Party","S.P."],["IUA","Irish Unionist Alliance"],["NIWC","Northern Ireland Women's Coalition","NI Women's Coalition"],["LC","Labour Coalition"],["IRSP","Irish Republican Socialist Party"],["NLP","Natural Law Party","Natural Law"],["FP","Farmers' Party","Farmers"],["CnaP","Clann na Poblachta"],["INF","Irish National Federation"],["CPI","Communist Party of Ireland"],["RLP","Republican Labour Party","Republican Labour","Rep Lab"],["BNP","British National Party"],["CISTA","Cannabis Is Safer Than Alcohol"],["DL","Democratic Left","Democratic Left (Ireland)"],["INL","Irish National League"],["UUUP","United Ulster Unionist Party"],["CSP","Christian Solidarity Party","Comhar Criostai / Christian Solidarity","Comhar Criostai/Christian Solidarity","C.S.P."],["II","Independent Ireland"],["RNU","Republican Network for Unity"],["CnaT","Clann na Talmhan"],["AAA","Anti-Austerity Alliance","A.A.A."],["ULP","Ulster Liberal Party","Ulster Liberal"],["NP","National Party"],["RSF","Republican Sinn F\xE9in"],["TIP","The Irish People"],["UIM","Ulster Independence Movement"],["LIB","Liberal Party","Liberal"],["LU","Liberal Unionist"],["NIUP","Northern Ireland Unionist Party","NI Unionist Party"],["SEA","Socialist Environmental Alliance"],["IFP","Irish Freedom Party"],["DDI","Direct Democracy Ireland","D.D.I."],["SWP","Socialist Workers Party","Socialist Workers"],["AHB","Anti H-Block"],["Ind Lab","Independent Labour","Ind Lab"],["AFIL","All-for-Ireland League","All-for-Ireland"],["I4C","Independents 4 Change"],["IA","Independent Alliance"],["NCP","National Centre Party"],["UCUNF","Ulster Conservatives and Unionists \u2013 New Force"],["PDem","People's Democracy","People's Democracy (Ireland)"],["NDP","National Democratic Party"],["Eco","Ecology Party","Ecology","Ecology Party Ireland"],["Ind Rep","Independent Republican","Ind Rep"],["Ind FF","Independent Fianna F\xE1il","Independent Fianna Fail"],["Ind FG","Independent Fine Gael"],["Ind CON","Independent Conservative","Ind. Conservative"],["Ind Soc","Independent Socialist"],["IUP","Independent Unionist Party","Ind. Unionist Party"],["Prot U","Protestant Unionist Party","Protestant Unionist"],["PT SF","Pro-Treaty Sinn F\xE9in"],["AT SF","Anti-Treaty Sinn F\xE9in"],["DVP","Democrats and Veterans"],["WUAG","Workers and Unemployed Action Group"],["ULA","United Left Alliance"],["IHA","Independent Health Alliance"],["CC","Ceann Comhairle (Speaker)"],["RDT","Vote For Yourself / Rainbow Dream Ticket / Make Politicians History"],["Joint","Joint Panel Nomination (Pro/Anti Treaty)"],["ARG","An Rabharta Glas \u2013 Green Left","An Rabharta Glas \u2013 Green Left Lozenge"],["HRRA","Housing Rights and Reform Alliance"],["DLTU","Derry Labour and Trade Union Party"],["UCDP","Ulster Christian Democratic Party"],["SKIA","South Kerry Independent Alliance"],["ILPU","Irish Loyal and Patriotic Union"],["A\xC9","Aontacht Eireann (Irish Unity)"],["LTUG","Labour and Trade Union Group"],["3W","Third Way (UK organisation)"],["UIV","Ulster's Independent Voice"],["SRP","Socialist Republican Party"],["KIA","Kerry Independent Alliance"],["PPP","People's Progressive Party"],["CLP","Commonwealth Labour Party"],["UCP","Ulster Constitution Party"],["Unity","Unity (Northern Ireland)"],["PAW","Party for Animal Welfare"],["UPA","Ulster Protestant Action"],["UPL","Ulster Protestant League"],["SBU","South Belfast Unionists"],["Centre","Centre Party of Ireland"],["ISN","Irish Socialist Network"],["NDUK","National Democrats (UK)"],["DP","Democratic Partnership"],["NI1ST","Northern Ireland First"],["IDP","Irish Democratic Party"],["TTA","Town Tenants' Association","Town Tenants Association"],["VPP","Volunteer Political Party"],["NF","National Front","National Front (UK)"],["Socialist","Socialist","Socialist Lozenge"],["AWP","Animal Welfare Party"],["LRC","Labour Representation Committee","Labour Repr. Cmte."],["WSP","World Socialist Party"],["FOL","Federation of Labour"],["NIM","New Ireland Movement"],["U3W","Ulster Third Way"]],Z_=["Non-transferable"];function Rh(Le){return String(Le??"").normalize("NFKD").replace(/[̀-ͯ]/g,"").replace(/\s+lozenge$/i,"").replace(/&/g," and ").replace(/[.'’`]/g,"").replace(/[–—\-_/,]/g," ").replace(/\s+/g," ").trim().toLowerCase()}var kh=new Map;for(let[Le,Qe,...Zt]of $_)for(let cr of[Le,Qe,...Zt]){let k=Rh(cr);k&&!kh.has(k)&&kh.set(k,{abbreviation:Le,fullName:Qe})}var Y_=new Set(Z_.map(Rh));function Zf(Le){let Qe=String(Le??"").trim();if(!Qe)return null;let Zt=kh.get(Rh(Qe));if(Zt)return Zt;let cr=Rh(Qe.replace(/\s*\([^)]*\)\s*$/,""));return kh.get(cr)||null}function K_(Le){return Zf(Le)?.abbreviation||String(Le??"").trim()}function J_(Le,Qe){let Zt=String(Le??"").trim(),cr=Zf(Zt);return!cr||cr.abbreviation===cr.fullName?Qe(Zt):`${Qe(cr.abbreviation)}`}Da();var W_=[{name:"ARMAGH AREA D",matches:Le=>Wf(Le.NAME)&&Hf(Le.Area_SqKM,13.1719213882566)},{name:"DUNGANNON AREA C",matches:Le=>String(Le.OBJECTID??"").trim()==="1624"&&X_(Le.NAME)==="DUNGANNON AREA D"},{name:"LIMAVADY AREA C",matches:Le=>Wf(Le.NAME)&&Hf(Le.Area_SqKM,8.44105398081151)}];function Ay(Le,Qe={}){if(!xd(Le))return Qe||{};let Zt=H_(Qe);return Zt?{...Qe||{},NAME:Zt,name:Qe?.name||Zt,label_name:Qe?.label_name||Zt}:Qe||{}}function Dy(Le,Qe){return xd(Le)?["case",Lh(13.1719213882566),"ARMAGH AREA D",["all",["==",["to-string",["get","OBJECTID"]],"1624"],["==",["upcase",["to-string",["get","NAME"]]],"DUNGANNON AREA D"]],"DUNGANNON AREA C",Lh(8.44105398081151),"LIMAVADY AREA C",Qe]:Qe}function zy(Le){return xd(Le)?["any",Lh(13.1719213882566),["all",["==",["to-string",["get","OBJECTID"]],"1624"],["==",["upcase",["to-string",["get","NAME"]]],"DUNGANNON AREA D"]],Lh(8.44105398081151)]:null}function xd(Le){return Le?.sourceMapId==="deas-1972"||Le?.id==="deas-1972"||Le?.id==="deas-1972-vector-test"||Le?.sourceLayer==="deas_1972"}function H_(Le={}){return W_.find(Qe=>Qe.matches(Le||{}))?.name||""}function Lh(Le){return["all",["!",["has","NAME"]],["<",["abs",["-",["to-number",["get","Area_SqKM"],-999999],Le]],1e-4]]}function Wf(Le){return Le==null||String(Le).trim()===""}function Hf(Le,Qe){let Zt=Number(Le);return Number.isFinite(Zt)&&Math.abs(Zt-Qe)<1e-4}function X_(Le){return String(Le??"").trim().toUpperCase()}export{K_ as a,J_ as b,q_ as c,Ay as d,Dy as e,zy as f}; /*! Bundled license information: maplibre-gl/dist/maplibre-gl.js: diff --git a/app/build/chunks/election-manager-MOZS4OJM.js b/app/build/chunks/election-manager-MOZS4OJM.js new file mode 100644 index 0000000000..7bb4513204 --- /dev/null +++ b/app/build/chunks/election-manager-MOZS4OJM.js @@ -0,0 +1,948 @@ +import{a as ue,b as ht,c as Ke,d as he,e as ye}from"./chunk-MJD6VXSO.js";import{b as We,d as dt,e as bt}from"./chunk-57HMLXXU.js";dt();var ke=We(Ke());dt();dt();var qe=new Map([["alliance","#f6cb2f"],["aontu","#44532a"],["conservative","#0087dc"],["dup","#d46a4c"],["fianna fail","#66bb66"],["fine gael","#6699ff"],["green","#22ac6f"],["green party","#22ac6f"],["independent","#b8b8b8"],["independent ireland","#3bee56"],["irish labour","#cc0000"],["labour","#cc0000"],["pbp","#ff0090"],["sdlp","#2aa82c"],["sinn fein","#326760"],["social democrats","#752f8b"],["solidarity pbp","#8e2420"],["solidarity-pbp","#8e2420"],["tuv","#0c3a6a"],["uup","#48a5ee"],["yes","#2aa82c"],["no","#d46a4c"],["remain","#2aa82c"],["leave","#d46a4c"]]);function q(r){return String(r??"").normalize("NFKD").replace(/[\u0300-\u036f]/g,"").replace(/\([^)]*\)/g," ").replace(/&/g," and ").replace(/[''`]/g,"").replace(/[-_/.,()]/g," ").replace(/\s+/g," ").trim().toLowerCase()}function He(r){return String(r??"").replace(/\u00c3\u00a1/g,"a").replace(/\u00c3\u00a9/g,"e").replace(/\u00c3\u0089/g,"E").replace(/\u00e2\u20ac\u2122/g,"'").replace(/\s+/g," ").trim()}function Tt(r){if(r==null||r==="")return null;let t=Number(String(r).replace(/,/g,"").replace(/%$/,""));return Number.isFinite(t)?t:null}function K(r){let t=Tt(r);return t===null?0:t}function Ut(r,t=2){let e=10**t;return Math.round(r*e)/e}function me(r){let t=He(r||"").trim();return t?t.replace(/^Sinn Fein$/i,"Sinn F\xE9in").replace(/^Fianna Fail$/i,"Fianna F\xE1il").replace(/^Labour$/i,"Irish Labour").replace(/^People Before Profit(?: Alliance)?$/i,"PBP"):""}function X(r,t="#6b7280"){return qe.get(q(r))||t}function Ue(r){let t=q(r);return t?/not elected|unelected|not deemed elected/.test(t)?"not-elected":/elected|made quota|counted as elected|deemed elected/.test(t)?"elected":/excluded|eliminated/.test(t)?"excluded":t:""}function zt(r={}){let t=Array.isArray(r.candidates)?r.candidates:[],e=Tt(r.seatsTotal??r.seatsWon),n=Ye(t,e),a=n.filter(s=>s.elected);return a.length?a.map(s=>({...s,colour:s.colour||X(s.party)})).sort((s,i)=>K(s.electedAt)-K(i.electedAt)||K(i.finalVotes)-K(s.finalVotes)).slice(0,e&&e>0?e:a.length):e&&e>0?[...n].filter(s=>!s.excluded).sort((s,i)=>K(i.finalVotes??i.firstPrefs)-K(s.finalVotes??s.firstPrefs)).slice(0,e).map(s=>({...s,elected:!0,status:s.status||"Deemed elected",colour:s.colour||X(s.party)})):[]}function ze(r={}){let t=Array.isArray(r.counts)?r.counts:[];return Math.max(1,...t.map(e=>Tt(e?.count)||0))}function Ye(r=[],t=null){let e=Tt(t);if(!e||e<=0||!Array.isArray(r)||!r.length)return r;let n=r.filter(l=>l.elected);if(n.length>=e)return r;let a=new Set(n.map(l=>l.id||`${l.name}|${l.party}`)),s=e-n.length,i=r.filter(l=>{let c=l.id||`${l.name}|${l.party}`;return a.has(c)||l.excluded||Ue(l.status)==="excluded"||l.autoReturnedCeannComhairle?!1:K(l.finalVotes??l.firstPrefs)>0}).sort((l,c)=>K(c.finalVotes??c.firstPrefs)-K(l.finalVotes??l.firstPrefs)||K(c.firstPrefs)-K(l.firstPrefs)||String(l.name||"").localeCompare(String(c.name||""))).slice(0,s);if(!i.length)return r;let o=new Set(i.map(l=>l.id||`${l.name}|${l.party}`));return r.map(l=>{let c=l.id||`${l.name}|${l.party}`;if(!o.has(c))return l;let u=ze(l),h=Array.isArray(l.counts)?l.counts.map(p=>Number(p?.count)===u?{...p,status:p.status||"Deemed elected"}:p):l.counts;return{...l,elected:!0,electedAt:l.electedAt||u,excluded:!1,excludedAt:null,status:"Deemed elected",counts:h}})}function tt(r=[]){let t=new Map,e=0;for(let n of r){for(let a of zt(n)){let s=a.party||n.winnerParty||n.leadingParty||"Independent/Other",i=q(s)||s;t.has(i)||t.set(i,{party:s,seats:0,stood:0,votes:0,colour:X(s)}),t.get(i).seats+=1}for(let a of n.candidates||[]){if(a.autoReturnedCeannComhairle)continue;let s=K(a.firstPrefs??a.votes),i=a.party||"Independent/Other",o=q(i)||i;t.has(o)||t.set(o,{party:i,seats:0,stood:0,votes:0,colour:X(i)}),t.get(o).stood+=1,t.get(o).votes+=s,e+=s}}return[...t.values()].map(n=>({...n,share:e?n.votes/e*100:null})).sort((n,a)=>a.seats-n.seats||a.votes-n.votes||n.party.localeCompare(a.party))}function lt(r=[]){let t=[];for(let e of r)for(let n of e.candidates||[])t.push({...n,constituency:e.constituency,firstPrefPct:e.validPoll?K(n.firstPrefs)/e.validPoll*100:null});return t.sort((e,n)=>+!!n.elected-+!!e.elected||K(n.firstPrefs)-K(e.firstPrefs))}function Bt(r=[]){let t=new Map,e=new Map,n=0;for(let s of r){n+=K(s.validPoll);for(let i of s.candidates||[]){let o=`${i.name}|${i.party}`,l=i.sourcePersonId||o;e.has(l)||e.set(l,{id:l,key:o,name:i.name,party:i.party,colour:i.colour||X(i.party),firstPrefs:0,finalVotes:0,electedCount:0,constituencies:new Set,appearances:[]});let c=e.get(l);c.firstPrefs+=K(i.firstPrefs),c.finalVotes+=K(i.finalVotes),i.elected&&(c.electedCount+=1),c.constituencies.add(s.constituency),c.appearances.push({constituency:s.constituency,firstPref:K(i.firstPrefs),finalVotes:K(i.finalVotes),status:i.elected?"Elected":i.status||""});let u=i.party||"Independent/Other",h=q(u);t.has(h)||t.set(h,{name:u,colour:i.colour||X(u),firstPrefs:0,finalVotes:0,stood:0,elected:0,constituencies:new Set,candidates:[]});let p=t.get(h);i.autoReturnedCeannComhairle||(p.firstPrefs+=K(i.firstPrefs),p.finalVotes+=K(i.finalVotes),p.stood+=1),i.elected&&(p.elected+=1),p.constituencies.add(s.constituency),p.candidates.push({id:l,name:i.name,constituency:s.constituency,firstPref:K(i.firstPrefs),finalVotes:K(i.finalVotes),status:i.elected?"Elected":i.status||""})}}let a=s=>({...s,constituencies:[...s.constituencies].sort((i,o)=>String(i).localeCompare(String(o))),shareOfTotal:n?s.firstPrefs/n*100:null});return{totalValid:n,parties:[...t.values()].map(a).sort((s,i)=>i.elected-s.elected||i.firstPrefs-s.firstPrefs),candidates:[...e.values()].map(a).sort((s,i)=>i.electedCount-s.electedCount||i.firstPrefs-s.firstPrefs)}}function Rt(r=[],t=[]){let e=new Map(t.map(n=>[q(n.constituency),n]));return r.map(n=>{let a=e.get(q(n.constituency)),s=new Map((a?.candidates||[]).map(o=>[pe(o),o])),i=(n.candidates||[]).map(o=>{let l=s.get(pe(o)),c=n.validPoll?K(o.firstPrefs)/n.validPoll*100:null,u=a?.validPoll&&l?K(l.firstPrefs)/a.validPoll*100:null;return{...o,previous:l?{firstPrefs:l.firstPrefs,firstPrefPct:u,finalVotes:l.finalVotes,elected:l.elected,status:l.status}:null,deltas:l?{firstPrefs:K(o.firstPrefs)-K(l.firstPrefs),firstPrefPct:c!==null&&u!==null?Ut(c-u,2):null,finalVotes:K(o.finalVotes)-K(l.finalVotes)}:null}});return{...n,candidates:i,previous:a?{leadingParty:a.leadingParty,winnerParty:a.winnerParty,leadingVotes:a.leadingVotes,leadingPct:a.leadingPct,turnoutPct:a.turnoutPct,seatsWon:a.seatsWon,validPoll:a.validPoll,candidates:a.candidates||[]}:null,deltas:a?{leadingVotes:K(n.leadingVotes)-K(a.leadingVotes),leadingPct:n.leadingPct!==null&&a.leadingPct!==null?Ut(n.leadingPct-a.leadingPct,2):null,turnoutPct:n.turnoutPct!==null&&a.turnoutPct!==null?Ut(n.turnoutPct-a.turnoutPct,2):null,seatsWon:K(n.seatsWon)-K(a.seatsWon),validPoll:K(n.validPoll)-K(a.validPoll)}:null}})}function fe(r,t=13){if(r<=0)return[];if(r===1)return[{x:0,y:0}];if(r===2)return[{x:0,y:0},{x:t,y:0}];if(r===3)return[{x:0,y:0},{x:t,y:0},{x:t*2,y:0}];if(r>12){let h=Math.PI,p=B=>{let M=1/(4*B-2);return Array.from({length:B},(C,N)=>{let k=.5+2*N*M;return Math.max(1,Math.floor(h*k/(2*M)))})},d=1,m=p(d);for(;m.reduce((B,M)=>B+M,0)B+M,0),F=r/x,P=m.map(B=>Math.max(1,Math.round(B*F))),A=P.reduce((B,M)=>B+M,0);for(;A>r;){let B=Xe(P,M=>M>1);if(B<0)break;P[B]-=1,A-=1}for(;A({idx:C,deficit:M-P[C]})).filter(M=>M.deficit>0).sort((M,C)=>C.deficit-M.deficit)[0];if(!B)break;P[B.idx]+=1,A+=1}let b=1/(4*d-2),T=t*1.02/(2*b),V=[];P.forEach((B,M)=>{let C=.5+2*M*b;if(B<=0)return;if(B===1){V.push({x:T,y:0});return}let N=Math.asin(b/C),k=(Math.PI-2*N)/(B-1);for(let j=0;jB.x)),w=Math.min(...V.map(B=>B.y));return V.forEach(B=>{B.x-=E,B.y-=w}),V.sort((B,M)=>B.x-M.x||B.y-M.y),V}let e=Math.ceil(r/2),n=r-e,a=[],i=-((e-1)*t)/2;for(let h=0;hh.x)),u=Math.min(...a.map(h=>h.y));return a.forEach(h=>{h.x-=c,h.y-=u}),a}function Xe(r,t){for(let e=r.length-1;e>=0;e-=1)if(t(r[e],e,r))return e;return-1}function pe(r={}){return q(r.name||r.candidateName||r.Candidate_Name||r.id||"")}dt();function Ze({entry:r=null,bundle:t=null,results:e=[],previousResults:n=[],selectedResult:a=null,view:s="party",mode:i="winner",overlayMode:o="circles",localMode:l="constituency",countDetailedView:c=!1}={}){let u=n.length?Rt(e,n):e,h=a?q(a.matchName||a.constituency||""):null,p=t?.partySummary?.length?t.partySummary:tt(u),d=lt(u),m=(t?.bodyGroup||r?.bodyGroup)==="local-government",x=u.some(F=>F.recallPetition);return{entry:r,bundle:t,title:t?.displayTitle||r?.displayTitle||t?.body||r?.body||"",date:t?.date||r?.date||"",body:t?.body||r?.body||"",bodyGroup:t?.bodyGroup||r?.bodyGroup||null,view:s,mode:i,overlayMode:o,localMode:l,countDetailedView:c,selectedKey:h,selectedResult:a,results:u,previousResults:n,partySummary:p,candidateSummary:d,entityIndex:t?.entityIndex||Bt(u),localGovernment:m,recallPetition:x,coverage:{matched:Number(t?.matchedCount||0),unmatched:Number(t?.unmatchedCount||0),total:Number(t?.totalConstituencies||u.length||0)},totals:Je(u,p)}}function ve(r,t=null,e=null){return Ze({entry:r.activeEntry,bundle:r.activeBundle,results:r.activeBundle?.results||[],previousResults:r.previousBundle?.results||[],selectedResult:t,view:e||r.activePanelView||"party",mode:r.activeMode,overlayMode:r.overlayMode,localMode:r.activeLocalMode,countDetailedView:r.countDetailedView})}function Yt(r=[]){let t=[];for(let e of r){let n=new Map,a=Number(e.validPoll||e.totalVotes||0);for(let s of e.candidates||[]){let i=s.party||"Independent/Other",o=q(i)||i;n.has(o)||n.set(o,{party:i,constituency:e.constituency||e.matchName||"",resultKey:q(e.matchName||e.constituency||""),colour:s.colour||X(i),stood:0,seats:0,firstPrefs:0,share:null});let l=n.get(o);l.stood+=1,l.firstPrefs+=Number(s.firstPrefs??s.votes??0)||0,s.elected&&(l.seats+=1)}for(let s of n.values())s.share=a?s.firstPrefs/a*100:null,t.push(s)}return t.sort((e,n)=>String(e.party).localeCompare(String(n.party))||String(e.constituency).localeCompare(String(n.constituency))||n.firstPrefs-e.firstPrefs)}function Xt(r=[]){let t=new Map;for(let e of r){let n=e.localBody||"Unknown council";t.has(n)||t.set(n,{council:n,deas:0,seats:0,validPoll:0,electorate:0,partySeats:new Map,partyVotes:new Map});let a=t.get(n);a.deas+=1,a.seats+=Number(e.seatsWon??e.seatsTotal??0)||0,a.validPoll+=Number(e.validPoll||e.totalVotes||0)||0,a.electorate+=Number(e.electorate||0)||0;for(let s of e.candidates||[]){let i=s.party||"Independent/Other";a.partyVotes.set(i,(a.partyVotes.get(i)||0)+(Number(s.firstPrefs??s.votes??0)||0)),s.elected&&a.partySeats.set(i,(a.partySeats.get(i)||0)+1)}}return[...t.values()].map(e=>{let n=[...e.partySeats.entries()].sort((a,s)=>s[1]-a[1]||(e.partyVotes.get(s[0])||0)-(e.partyVotes.get(a[0])||0))[0]||[...e.partyVotes.entries()].sort((a,s)=>s[1]-a[1])[0]||["",0];return{...e,leadingParty:n[0],colour:X(n[0]),turnoutPct:e.electorate?e.validPoll/e.electorate*100:null}}).sort((e,n)=>String(e.council).localeCompare(String(n.council)))}function mt(r,t){return r.reduce((e,n)=>{let a=Number(n?.[t]);return Number.isFinite(a)?e+a:e},0)}function Qe(r,t){let e=r.map(n=>Number(n?.[t])).filter(n=>Number.isFinite(n));return e.length?e.reduce((n,a)=>n+a,0)/e.length:null}function Je(r,t){let e=mt(r,"validPoll"),n=mt(r,"totalPoll"),a=mt(r,"electorate"),s=t.reduce((i,o)=>i+K(o.seats),0);return{constituencies:r.length,totalSeats:s,validPoll:e,totalPoll:n,electorate:a,turnoutPct:a&&n?n/a*100:Qe(r,"turnoutPct")}}function be(r){return new Qt(r)}function St(r,t,e){let n=Number(r);if(!Number.isFinite(n))return"#9ca3af";let a=Math.max(0,Math.min(1,(n-t)/(e-t||1)));return a<.2?"#fef3c7":a<.4?"#fde68a":a<.6?"#f59e0b":a<.8?"#d97706":"#92400e"}var Qt=class{constructor(t){this.host=t}viewModel(t=null,e=null){return ve(this.host,t,e)}renderOverallResults(t="party"){if(typeof this.host.renderMainCompatibleOverallResults=="function")return this.host.renderMainCompatibleOverallResults(t);let e=this.viewModel(null,t),n=e.results;if(e.recallPetition)return this.renderRecallPetitionOverview(n);if(e.localGovernment&&e.localMode==="district")return this.renderDistrictResults(t);let a=e.bundle?.partySummary?.length?e.bundle.partySummary:tt(n),s=this.withPartyDeltas(a),i=lt(n);return` +
    + ${this.renderViewTabs([["party","By Party"],["candidate","By Candidate"],["constituency",e.localGovernment?"By DEA":"By Constituency"],...e.localGovernment?[["local-party","By Local Party"]]:[]],t)} +
    +
    +
    ${this.host.activeBundle?.areaLabel?`${this.host.activeBundle.areaLabel}s`:e.localGovernment?"DEAs":"Constituencies"}
    ${W(n.length)}
    +
    Matched
    ${W(e.coverage.matched)}
    +
    Unmatched
    ${W(e.coverage.unmatched)}
    + ${e.totals.totalSeats?`
    Seats
    ${W(e.totals.totalSeats)}
    `:""} + ${e.totals.validPoll?`
    Valid poll
    ${W(e.totals.validPoll)}
    `:""} + ${e.totals.turnoutPct?`
    Turnout
    ${yt(e.totals.turnoutPct)}
    `:""} +
    +
    +
    + ${this.renderDataCoverageNotice()} + ${t==="candidate"?this.renderCandidateSummaryTable(i):t==="constituency"?this.renderConstituencySummaryTable(n):t==="local-party"?this.renderLocalPartySummaryTable(n):this.renderPartySummaryTable(s)} +
    + `}renderConstituencyResults(t,e="party"){if(typeof this.host.renderMainCompatibleConstituencyResults=="function")return this.host.renderMainCompatibleConstituencyResults(t,e);if(t.recallPetition)return this.renderRecallPetitionResult(t);let n=[...t.candidates||[]].sort((s,i)=>+!!i.elected-+!!s.elected||Number(i.finalVotes??i.firstPrefs??i.votes??0)-Number(s.finalVotes??s.firstPrefs??s.votes??0)),a=this.host.activeBundle?.areaLabel||(this.host.isLocalGovernmentElection()?"DEA":"Constituency");return` +
    + ${this.renderViewTabs([["party","By Party"],["counts","By Count"],["animation","Transfers"]],e)} +
    +
    ${a}
    ${I(t.constituency||"")}
    + ${this.host.isLocalGovernmentElection()&&t.localBody?`
    Council
    ${I(t.localBody)}
    `:""} + ${t.seatsTotal?`
    Seats
    ${W(t.seatsTotal)}
    `:""} + ${t.validPoll?`
    Valid poll
    ${W(t.validPoll)}
    `:""} + ${t.turnoutPct?`
    Turnout
    ${yt(t.turnoutPct)}
    `:""} + ${t.quota?`
    Quota
    ${W(t.quota)}
    `:""} + ${t.previous?`
    Previous winner
    ${I(t.previous.winnerParty||t.previous.leadingParty||"")}
    `:""} + ${t.deltas?.turnoutPct!==null&&t.deltas?.turnoutPct!==void 0?`
    Turnout change
    ${At(t.deltas.turnoutPct)}
    `:""} +
    + ${e==="counts"?this.renderCountTable(t,n):e==="animation"?this.renderAnimationNotice(t):n.length?this.renderCandidateResultTable(n):'

    No candidate-level result table is available for this entry.

    '} +
    + `}renderDistrictResults(t="party"){if(this.host.localBodyCount()>1)return this.renderCouncilResults(t);let e=this.host.currentResults(),n=this.withPartyDeltas(tt(e)),a=n.reduce((s,i)=>s+K(i.seats),0);return` +
    + ${this.renderViewTabs([["party","By Party"],["candidate","By Candidate"],["local-party","By Local Party"],["constituency","By DEA"]],t)} +
    +
    +
    District
    ${I(this.host.activeBundle.displayTitle||this.host.activeBundle.body)}
    +
    DEAs
    ${W(e.length)}
    + ${a?`
    Seats
    ${W(a)}
    `:""} + ${mt(e,"validPoll")?`
    Valid poll
    ${W(mt(e,"validPoll"))}
    `:""} +
    +
    +
    + ${this.renderDataCoverageNotice()} + ${t==="candidate"?this.renderCandidateSummaryTable(lt(e)):t==="local-party"?this.renderLocalPartySummaryTable(e):t==="constituency"?this.renderConstituencySummaryTable(e):this.renderDistrictPartyTable(n)} +
    + `}renderCouncilResults(t="party"){let e=this.host.currentResults(),n=this.withCouncilDeltas(Xt(e)),a=this.withPartyDeltas(tt(e));return` +
    + ${this.renderViewTabs([["party","By Party"],["council","By Council"],["candidate","By Candidate"],["local-party","By Local Party"],["constituency","By DEA"]],t)} +
    +
    +
    Councils
    ${W(n.length)}
    +
    DEAs
    ${W(e.length)}
    + ${a.reduce((s,i)=>s+K(i.seats),0)?`
    Seats
    ${W(a.reduce((s,i)=>s+K(i.seats),0))}
    `:""} + ${mt(e,"validPoll")?`
    Valid poll
    ${W(mt(e,"validPoll"))}
    `:""} +
    +
    +
    + ${this.renderDataCoverageNotice()} + ${t==="council"?this.renderCouncilSummaryTable(n):t==="candidate"?this.renderCandidateSummaryTable(lt(e)):t==="local-party"?this.renderLocalPartySummaryTable(e):t==="constituency"?this.renderConstituencySummaryTable(e):this.renderDistrictPartyTable(a)} +
    + `}renderPartySummaryTable(t=[]){return t.length?` +
    + + + ${t.map(e=>` + + + + `).join("")} +
    PartyStoodSeatsVotesShareChange
    ${W(e.stood)}${W(e.seats)}${W(e.votes)}${yt(e.share)}${tn(e.deltas?.seats,e.deltas?.votes)}
    +
    `:""}renderCandidateResultTable(t=[]){return` +
    + + + ${t.map(e=>` + + + + + `).join("")} +
    CandidatePartyFirst prefsChangeFinal votesStatus
    ${W(e.firstPrefs??e.votes??"")}${e.deltas?ot(e.deltas.firstPrefs):""}${W(e.finalVotes??e.firstPrefs??e.votes??"")}${e.elected?"Elected":I(e.status||"")}
    +
    `}renderCandidateSummaryTable(t=[]){return` +
    + + + ${t.map(e=>` + + + + + `).join("")} +
    CandidatePartyConstituency/DEAFirst prefs%ChangeStatus
    ${I(e.constituency||"")}${W(e.firstPrefs)}${yt(e.firstPrefPct)}${e.deltas?ot(e.deltas.firstPrefs):""}${e.elected?"Elected":I(e.status||"")}
    +
    `}renderConstituencySummaryTable(t=[]){return` +
    + + + ${t.map(e=>` + + + + `).join("")} +
    Constituency/DEAWinner/leadPartySeatsChangeTurnoutMajority
    ${I(e.winnerName||e.leadingName||"")}${ht(e.winnerParty||e.leadingParty||"",I)}${W(e.seatsWon??e.seatsTotal??"")}${e.deltas?ot(e.deltas.seatsWon):""}${yt(e.turnoutPct)}${W(e.majority)}
    +
    `}renderLocalPartySummaryTable(t=[]){let e=this.withLocalPartyDeltas(Yt(t));return e.length?` +
    + + + ${e.map(n=>` + + + + `).join("")} +
    PartyDEAStoodSeatsSeat changeFirst prefsVote changeDEA shareShare change
    ${W(n.stood)}${W(n.seats)}${n.deltas?ot(n.deltas.seats):""}${W(n.firstPrefs)}${n.deltas?ot(n.deltas.firstPrefs):""}${yt(n.share)}${n.deltas?.share!==null&&n.deltas?.share!==void 0?At(n.deltas.share):""}
    +
    `:'

    No local-party summary is available for this election.

    '}renderCouncilSummaryTable(t=[]){return` +
    + + + ${t.map(e=>` + + `).join("")} +
    CouncilDEAsLeading partySeatsSeat changeValid votesVote changeTurnoutTurnout change
    ${I(e.council)}${W(e.deas)}${ht(e.leadingParty||"",I)}${W(e.seats)}${e.deltas?ot(e.deltas.seats):""}${W(e.validPoll)}${e.deltas?ot(e.deltas.validPoll):""}${yt(e.turnoutPct)}${e.deltas?.turnoutPct!==null&&e.deltas?.turnoutPct!==void 0?At(e.deltas.turnoutPct):""}
    +
    `}renderDistrictPartyTable(t=[]){return` +
    + + + ${t.map(e=>` + + `).join("")} +
    PartyCandidatesSeatsSeat changeFirst prefsVote shareVote change
    ${W(e.stood)}${W(e.seats)}${e.deltas?ot(e.deltas.seats):""}${W(e.votes)}${yt(e.share)}${e.deltas?`${ot(e.deltas.votes)}${e.deltas.share!==null?` (${At(e.deltas.share)})`:""}`:""}
    +
    `}renderRecallPetitionOverview(t=[]){return` +
    +
    Petitions
    ${W(t.length)}
    Triggered
    ${W(t.filter(e=>Zt(e)).length)}
    Not triggered
    ${W(t.filter(e=>e.recallPetition&&!Zt(e)).length)}
    +
    ${t.map(e=>{let n=e.recallPetition||{},a=n.signed??n.signatures??e.leadingVotes??null,s=n.threshold??n.required??null,i=Number.isFinite(Number(a))&&Number.isFinite(Number(s))?Number(a)-Number(s):null;return``}).join("")}
    ConstituencySignedThresholdShortfall/SurplusOutcome
    ${W(a)}${W(s)}${i===null?"":ot(i)}${I(n.outcome||(Zt(e)?"By-election triggered":"Petition not successful"))}
    +
    `}renderCountTable(t,e=[]){let n=t.countNumbers?.length?t.countNumbers:[...new Set(e.flatMap(i=>(i.counts||[]).map(o=>o.count)))].sort((i,o)=>i-o);if(!n.length)return'

    No count-by-count data is available for this entry.

    ';let a=en(e,n),s=new Map((t.nonTransferable||[]).map(i=>[Number(i.count),i]));return` +
    +
    ${n.map(i=>``).join("")}${a.length?`${n.map(i=>``).join("")}`:""} + ${e.map(i=>this.renderCountCandidateRow(i,n,t)).join("")} + ${s.size?this.renderNonTransferableRow(s,n):""} +
    CandidatePartyCount ${W(i)}Status
    Count event${I(a.find(o=>o.count===i)?.label||"")}
    `}renderCountCandidateRow(t,e,n){let a=new Map((t.counts||[]).map(s=>[Number(s.count),s]));return`${I(t.name||"")}${ht(t.party||"",I)}${e.map(s=>{let i=a.get(Number(s));if(!i)return"";let o=i.total??i.firstPrefs,l=Number(i.transfers),c=this.host.countDetailedView?[n.validPoll&&Number.isFinite(Number(o))?`${yt(Number(o)/Number(n.validPoll)*100)} of valid poll`:"",Number.isFinite(l)&&l?`${ot(l)} transfer`:"",i.status?`${I(i.status)}`:""].filter(Boolean).join(""):"";return`${W(o)}${!this.host.countDetailedView&&l?` (${ot(l)})`:""}${c?`
    ${c}
    `:""}`}).join("")}${t.elected?"Elected":I(t.status||"")}${t.previous?`
    Previous: ${I(t.previous.status||"")}
    `:""}`}renderNonTransferableRow(t,e){return`Non-
    transferable${e.map(n=>{let a=t.get(Number(n));return a?`${W(a.total)}${this.host.countDetailedView&&Number.isFinite(Number(a.transfers))?`
    ${ot(a.transfers)} transfer
    `:""}`:""}).join("")}`}renderRecallPetitionResult(t){let e=t.recallPetition||{},n=e.signed??e.signatures??t.leadingVotes??null,a=e.threshold??e.required??null,s=e.electorate??t.electorate??null,i=e.triggered??(Number.isFinite(Number(n))&&Number.isFinite(Number(a))?Number(n)>=Number(a):null),o=Number.isFinite(Number(n))&&Number.isFinite(Number(a))?Number(a)-Number(n):null;return`
    Constituency
    ${I(t.constituency||"")}
    ${s?`
    Electorate
    ${W(s)}
    `:""}${a?`
    Threshold
    ${W(a)}
    `:""}${n?`
    Signed
    ${W(n)}
    `:""}${o!==null?`
    ${o<=0?"Above threshold":"Shortfall"}
    ${W(Math.abs(o))}
    `:""}${i!==null?`
    By-election triggered
    ${i?"Yes":"No"}
    `:""}${e.incumbent?`
    Incumbent
    ${I(e.incumbent)}
    `:""}${e.incumbentParty?`
    Incumbent party
    ${I(e.incumbentParty)}
    `:""}
    `}renderAnimationNotice(t){if(t.hasCountDetail&&t.animationPayload){let e=q(t.matchName||t.constituency||"");return`
    `}return'

    No transfer animation data is available for this entry.

    '}renderPartyEntity(t){return`
    Party Information

    ${I(t.name||"")}

    ${I(this.host.activeBundle.displayTitle||this.host.activeBundle.body)} - ${I(this.host.activeBundle.date)}

    Candidates stood${W(t.stood)}
    Candidates elected${W(t.elected)}
    First prefs${W(t.firstPrefs)}
    Final votes${W(t.finalVotes)}
    Constituencies/DEAs${W(t.constituencies?.length||0)}
    Share${yt(t.shareOfTotal)}
    ${this.renderCandidateSummaryTable((t.candidates||[]).map(e=>({...e,party:t.name,colour:t.colour,firstPrefs:e.firstPref})))}
    `}renderCandidateEntity(t){return`
    Candidate Information

    ${I(t.name||"")}

    ${I(t.party||"")}

    Appearances${W(t.appearances?.length||0)}
    Elected${W(t.electedCount)}
    First prefs${W(t.firstPrefs)}
    Final votes${W(t.finalVotes)}
    Constituencies/DEAs${W(t.constituencies?.length||0)}
    Share${yt(t.shareOfTotal)}
    ${(t.appearances||[]).map(e=>``).join("")}
    Constituency/DEAFirst prefsFinal votesStatus
    ${W(e.firstPref)}${W(e.finalVotes)}${I(e.status||"")}
    `}renderViewTabs(t,e){return`
    ${t.map(([n,a])=>``).join("")}
    `}renderDataCoverageNotice(){let t=Number(this.host.activeBundle?.unmatchedCount||0);return t?`
    ${W(t)} result ${t===1?"row is":"rows are"} not styled on the map because no exact converted geography match is available yet.
    `:""}withPartyDeltas(t=[]){let e=this.host.previousBundle?.results?.length?tt(this.host.previousBundle.results):[],n=new Map(e.map(a=>[q(a.party),a]));return t.map(a=>{let s=n.get(q(a.party));return{...a,previous:s,deltas:s?{seats:K(a.seats)-K(s.seats),votes:K(a.votes)-K(s.votes),share:a.share!==null&&s.share!==null?a.share-s.share:null}:null}})}withCouncilDeltas(t=[]){let e=this.host.previousBundle?.results?.length?Xt(this.host.previousBundle.results):[],n=new Map(e.map(a=>[q(a.council),a]));return t.map(a=>{let s=n.get(q(a.council));return{...a,previous:s,deltas:s?{seats:K(a.seats)-K(s.seats),validPoll:K(a.validPoll)-K(s.validPoll),turnoutPct:a.turnoutPct!==null&&s.turnoutPct!==null?a.turnoutPct-s.turnoutPct:null}:null}})}withLocalPartyDeltas(t=[]){let e=this.host.previousBundle?.results?.length?Yt(this.host.previousBundle.results):[],n=new Map(e.map(a=>[`${q(a.party)}|${q(a.constituency)}`,a]));return t.map(a=>{let s=n.get(`${q(a.party)}|${q(a.constituency)}`);return{...a,previous:s,deltas:s?{seats:K(a.seats)-K(s.seats),firstPrefs:K(a.firstPrefs)-K(s.firstPrefs),share:a.share!==null&&s.share!==null?a.share-s.share:null}:null}})}};function W(r){if(r==null||r==="")return"";let t=Number(r);return Number.isFinite(t)?t.toLocaleString():String(r)}function yt(r){if(r==null||r==="")return"";let t=Number(r);return Number.isFinite(t)?`${t.toFixed(2).replace(/\.00$/,"")}%`:String(r)}function ot(r){let t=Number(r);return Number.isFinite(t)?`${t>0?"+":""}${t.toLocaleString()}`:""}function At(r){let t=Number(r);return Number.isFinite(t)?`${t>0?"+":""}${t.toFixed(2).replace(/\.00$/,"")}%`:""}function tn(r,t){return[ot(r),ot(t)].filter(Boolean).join(" / ")}function en(r=[],t=[]){let e=[];for(let n of t){let a=[],s=[];for(let o of r){let l=(o.counts||[]).find(u=>Number(u.count)===Number(n)),c=q(l?.status||"");/not elected/.test(c)||(/elected|quota/.test(c)&&Number(o.electedAt)===Number(n)&&a.push(o.name),/excluded|eliminated/.test(c)&&Number(o.excludedAt)===Number(n)&&s.push(o.name))}let i=[];a.length&&i.push(`${a.length===1?a[0]:`${a.length} candidates`} elected`),s.length&&i.push(`${s.length===1?s[0]:`${s.length} candidates`} excluded`),i.length&&e.push({count:Number(n),label:i.join("; ")})}return e}function Zt(r={}){let t=r.recallPetition||{};if(typeof t.triggered=="boolean")return t.triggered;let e=Number(t.signed??t.signatures??r.leadingVotes),n=Number(t.threshold??t.required);return Number.isFinite(e)&&Number.isFinite(n)?e>=n:!1}function I(r){return String(r??"").replace(/[&<>"']/g,t=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[t])}dt();var wt=class{constructor(t){this.host=t,this.rendererId=t?.paneRendererId||"test2-main-pane-contract"}renderTitle(t=null){return t?.constituency?t.constituency:this.host.formatPaneElectionTitle()}renderHeaderRight(t=null,e="party"){let n=!!(t&&this.host.isCouncilAggregateResult?.(t)),a=!!(t&&!n&&this.host.isSingleSeatFptpResult?.(t)),s=!!this.host.isReferendumElection?.(t),i=(!t||n)&&this.host.isLocalGovernmentElection()?` +
    + + +
    + `:"",o=s?[["party","Full Results"]]:a?[["results","Results"]]:n?[["party","By Party"],["candidate","By Candidate"],["local-party","By Local Party"]]:[["party","By Party"],["counts",this.host.isForumResult(t)?"By Round":"By Count"]];return!a&&!n&&t&&this.host.resultHasAnimation(t)&&o.push(["animation",this.host.isForumResult(t)?"Allocation":"Transfers"]),t&&!o.some(([c])=>c==="trends")&&o.push(["trends","Trends"]),` + ${i} + ${(t?o:s?[["party","Full Results"],["constituency","By Constituency"],["trends","Trends"]]:[["party","By Party"],["candidate","By Candidate"],["local-party","By Local Party"],["trends","Trends"]]).map(([c,u])=>`${t&&!n&&c==="counts"?``:""}`).join("")} + + `}renderPanelContent(t=null,e="party"){let n=t?`${this.renderConstituencyResults(t,e)}${this.renderSourceNote(t)}`:this.renderOverallResults(e);return`
    ${n}
    `}renderSourceNote(t){let e=this.host.activeBundle?.provenance,n=t?.constituency||t?.localBody||"";if(!e||!n)return"";let a=e[n.toLowerCase().replace(/[^a-z0-9]+/g,"")],s=a?.source;if(!s?.url)return"";let i=(d,m)=>`${Nt(m)}`,o=i(s.url,s.title||s.publisher||s.host||"the source"),l=s.title&&s.publisher?` (${Nt(s.publisher)})`:"",c=s.scope==="this contest"||s.scope==="same section",u=s.checked&&c?`Source: ${o}${l}.`:s.checked?`Figures confirmed against ${o}${l}, a source for this election.`:a.status==="recorded"?`Imported from ${o}${l}.`:`Cited by Wikipedia: ${o}${l}. Not checked against these figures.`,h=s.archiveUrl?` ${i(s.archiveUrl,"Archived copy")}.`:"",p=a.relatedWikipedia?` ${i(a.relatedWikipedia,"Related Wikipedia article")}.`:"";return`
    ${u}${h}${p}
    `}renderOverallResults(t="party"){let e=this.host.currentResults();if(t==="trends")return this.host.renderTrendsPanel?.(null)||'

    No trend data is available.

    ';if(this.host.isTurnoutGeographyMode?.())return this.host.renderTurnoutGeographyPanel();if(e.some(i=>i.recallPetition))return this.host.renderRecallPetitionOverview(e);if(this.host.isLocalGovernmentElection()&&this.host.activeLocalMode==="district")return this.host.renderDistrictResults(t);let n=this.host.activeBundle.mainLikePartySummary?.length?this.host.activeBundle.mainLikePartySummary:this.host.activeBundle.partySummary?.length?this.host.activeBundle.partySummary:tt(e),a=this.host.withPartyDeltas(n,{mainLike:!!this.host.activeBundle.mainLikePartySummary?.length}),s=this.host.activeBundle.mainLikeCandidateSummary?.length?this.host.withCandidateDeltas(this.host.activeBundle.mainLikeCandidateSummary,{mainLike:!0}):this.host.withCandidateDeltas(lt(e));return this.host.isReferendumElection?.()?` + ${this.host.renderDataCoverageNotice()} + ${t==="constituency"?this.host.renderReferendumConstituencySummaryTable(e):this.host.renderMainParityPartyTable(a,e,{referendum:!0})} + ${this.host.renderMapDisplayControls()} + `:` + ${this.host.renderDataCoverageNotice()} + ${t==="candidate"?this.host.renderCandidateSummaryTable(s):t==="local-party"?this.host.renderLocalPartySummaryTable(e):this.host.renderMainParityPartyTable(a,e)} + ${this.host.renderMapDisplayControls()} + `}renderConstituencyResults(t,e="party"){if(e==="trends")return this.host.renderTrendsPanel?.(t)||'

    No trend data is available.

    ';if(this.host.isTurnoutGeographyMode?.())return this.host.renderTurnoutConstituencyDetail(t);if(this.host.isCouncilAggregateResult?.(t))return this.host.renderCouncilAggregateResults(t,e);if(t.recallPetition)return this.host.renderRecallPetitionResult(t);let n=[...t.candidates||[]].sort((s,i)=>{let o=+!!i.elected-+!!s.elected;return o||Number(i.finalVotes??i.firstPrefs??i.votes??0)-Number(s.finalVotes??s.firstPrefs??s.votes??0)});if(this.host.isReferendumElection?.(t))return this.host.renderReferendumResultTable(n,t);if(this.host.isSingleSeatFptpResult?.(t))return this.host.renderSingleSeatFptpResultsTable?.(n,t)||this.host.renderConstituencyCandidateTable(n,t);let a=e==="animation"&&!this.host.resultHasAnimation(t)?"counts":e;return` + ${a==="counts"?this.host.renderCountTable(t,n):a==="animation"?this.host.renderAnimationNotice(t):a==="party"?this.host.renderConstituencyPartyTable(n,t):this.host.renderConstituencyCandidateTable(n,t)} + `}renderEntityPanel(t,e){return t==="candidate"?this.host.renderCandidateEntity(e):this.host.renderPartyEntity(e)}};function Nt(r){return String(r??"").replace(/[&<>"']/g,t=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[t])}dt();var Jt=[1,2,5,10,20,25,50,100];function ge(r=[],t={}){let e=Math.max(1,Number(t.seriesLimit)||8),n=typeof t.abbreviate=="function"?t.abbreviate:d=>d,a=typeof t.bodyLabel=="function"?t.bodyLabel:d=>String(d?.body||""),s=new Map;for(let d of r){let m=d?.entry||{},x=m.key||`${m.body}|${m.date}`;s.has(x)||s.set(x,{key:x,entry:m,date:String(m.date||""),time:rn(m.date),year:String(m.date||"").slice(0,4),body:a(m)})}let i=[...s.values()].sort((d,m)=>d.date.localeCompare(m.date)||d.body.localeCompare(m.body)),o=new Map(i.map((d,m)=>[d.key,m])),l=new Map;for(let d of r){let m=d?.entry||{},x=m.key||`${m.body}|${m.date}`,F=o.get(x);if(F===void 0)continue;let P=ln(d.party);if(!P)continue;l.has(P)||l.set(P,{key:P,party:String(d.party||""),abbreviation:n(d.party)||String(d.party||""),colour:d.colour,values:new Array(i.length).fill(null),maxShare:0,latestShare:0,latestIndex:-1});let A=l.get(P),b=kt(d.share);A.values[F]={share:b,votes:kt(d.votes),seats:kt(d.seats)},A.maxShare=Math.max(A.maxShare,b),F>=A.latestIndex&&(A.latestIndex=F,A.latestShare=b)}let c=i.length-1,u=d=>c>=0&&d.values[c]?d.values[c].share:-1,h=[...l.values()].sort((d,m)=>u(m)-u(d)||m.maxShare-d.maxShare||d.party.localeCompare(m.party)).slice(0,e),p=new Map;for(let d of h)p.set(d.abbreviation,(p.get(d.abbreviation)||0)+1);for(let d of h)p.get(d.abbreviation)>1&&(d.abbreviation=d.party);return{elections:i,series:h,totalSeries:l.size}}function nn(r,t={}){let e=Math.max(240,Math.round(Number(t.width)||640)),n=e<560,a=Math.round(Number(t.height)||(n?216:256)),s=typeof t.measureText=="function"?t.measureText:te,{elections:i,series:o}=r,l=o.reduce((f,y)=>y.values.reduce((g,O)=>O?Math.max(g,O.share):g,f),0),c=l<=25?5:l<=60?10:20,u=Math.min(100,Math.max(c*2,Math.ceil(l/c)*c)),h=[];for(let f=0;f<=u;f+=c)h.push(f);let p=Math.max(...h.map(f=>s(`${f}%`,!1,11.5))),d=new Map(o.map(f=>[f.key,f])),m=(f,y)=>{let g=ee(f.latestShare);return y==="full"?{name:f.party,value:g}:y==="abbr"?{name:f.abbreviation,value:g}:{name:"",value:g}},x=(f,y)=>{let g=m(f,y);return(g.name?s(`${g.name} `,!1,12):0)+s(g.value,!0,12)},F="none",P=0;if(t.directLabels!==!1&&!n&&o.length){let f=e>=760?["full","abbr","value"]:["abbr","value"];for(let y of f)if(F=y,P=Math.max(...o.map(g=>x(g,y))),P<=e*.28)break}let A={top:12,right:F==="none"?14:Math.ceil(P)+14,bottom:26,left:Math.ceil(p)+10},b={left:A.left,right:e-A.right,top:A.top,bottom:a-A.bottom};b.width=Math.max(40,b.right-b.left),b.height=Math.max(40,b.bottom-b.top);let R=f=>b.bottom-kt(f)/u*b.height,T=i.map(f=>f.time),V=T.length>0&&T.every(f=>Number.isFinite(f)),E=V?Math.min(...T):0,w=V?Math.max(...T):0,B=w-E,M;i.length<=1?M=i.map(()=>b.left+b.width/2):V&&B>0?M=T.map(f=>b.left+(f-E)/B*b.width):M=i.map((f,y)=>b.left+y/(i.length-1)*b.width);for(let f=1;f0&&M.length>1){let f=b.width/(b.width+C);for(let y=0;y{if(!V||!M.length)return b.left;if(M.length===1)return M[0];if(f<=T[0])return M[0]-(T[0]-f)/B*b.width;for(let y=1;y0?(f-T[y-1])/g:1;return M[y-1]+(M[y]-M[y-1])*O}return M[M.length-1]+(f-T[T.length-1])/B*b.width},k=[];if(V&&i.length>1&&B>0){let f=new Date(E).getUTCFullYear(),y=new Date(w).getUTCFullYear(),g=Math.max(1,y-f),O=Jt.find(_=>b.width/(g/_)>=58)||Jt[Jt.length-1];for(let _=Math.ceil(f/O)*O;_<=y;_+=O){let G=N(Date.UTC(_,0,1));Gb.right+.5||k.push({year:_,x:G})}k.length||k.push({year:f,x:M[0]},{year:y,x:M[M.length-1]})}else i.forEach((f,y)=>{f.year&&k.push({year:Number(f.year),x:M[y]})});let j=o.map(f=>{let y=[],g=null,O=[],_=[];f.values.forEach((H,nt)=>{if(!H){g=null;return}let Q=M[nt],et=R(H.share);_.push({index:nt,x:Q,y:et,share:H.share}),g||(g=[],y.push(g)),g.push({x:Q,y:et});let at=f.values[nt-1],ut=f.values[nt+1];!at&&!ut&&O.push({index:nt,x:Q,y:et})});let G=[];for(let H=1;H_.pointY-G.pointY);let g=b.top+12/2,O=b.bottom+4;for(let _=0;_=0;_-=1){let G=_===y.length-1?O:y[_+1].y-14;y[_].y=Math.min(y[_].y,G)}for(let _=1;_5,D.push(_)}}return{width:e,height:a,narrow:n,pad:A,plot:b,yMax:u,yTicks:h,yFor:R,columns:M,xTicks:k,labelMode:F,series:j,labels:D}}function an(r,t,e={}){let{elections:n}=r,{width:a,height:s,plot:i}=t,o=it(e.ariaLabel||"Party vote share over time"),l=t.yTicks.map(d=>{let m=t.yFor(d).toFixed(1);return`${d}%`}).join(""),c=t.columns.map(d=>``).join(""),u=t.xTicks.map(d=>{let m=d.xi.right-16?"end":"middle";return`${d.year}`}).join(""),h=t.series.map(d=>{let m=it(d.colour),x=d.segments.map(b=>b.map((R,T)=>`${T===0?"M":"L"}${R.x.toFixed(1)} ${R.y.toFixed(1)}`).join("")).join(""),F=d.isolated.map(b=>``).join(""),P=d.bridges.length?``:"",A=d.markers.map(b=>{let R=n[b.index],T=it(`${d.party}: ${ee(b.share)} at ${[R.year,R.body].filter(Boolean).join(" ")}`);return`${T}`}).join("");return``+P+(x?``:"")+F+(x?``:"")+A+""}).join(""),p=t.labels.map(d=>{let m=it(d.colour),x=d.leader?``:"",F=d.name?`${it(d.name)} `:"";return`${x}${F}${it(d.value)}`}).join("");return`${l}${c}${h}${p}${u}`}function Pe(r,t,e={}){if(!r)return null;r.__trendChart?.destroy();let n=r.ownerDocument,a=n.createElement("div");a.className="trend-chart",a.innerHTML=` + +
    + + ${e.footnotes||""} + `,r.replaceChildren(a);let s=a.querySelector(".trend-chart__stage"),i=a.querySelector(".trend-tooltip"),o=a.querySelector(".test2-election-trends__legend"),l=on(a),c=typeof e.formatDate=="function"?e.formatDate:y=>y,u=new Map(t.series.map(y=>[y.key,y])),h={layout:null,svg:null,width:0,lockedParty:null,hoverParty:null,column:-1,pinned:!1,destroyed:!1},p=()=>h.hoverParty||h.lockedParty,d=()=>{let y=p();y?a.setAttribute("data-trend-focus",y):a.removeAttribute("data-trend-focus"),a.querySelectorAll("[data-party]").forEach(g=>{g.classList.toggle("is-focused",!!y&&g.getAttribute("data-party")===y)}),o.querySelectorAll("[data-party]").forEach(g=>{g.setAttribute("aria-pressed",h.lockedParty===g.getAttribute("data-party")?"true":"false")})},m=y=>{let g=h.layout;if(!g||!h.svg)return;let O=Number.isInteger(y)&&y>=0&&yz.classList.remove("is-active")),O<0){_.classList.remove("is-active"),i.hidden=!0,a.classList.remove("is-hovering");return}let G=g.columns[O].toFixed(1);_.setAttribute("x1",G),_.setAttribute("x2",G),_.classList.add("is-active"),h.svg.querySelectorAll(`.trend-marker[data-election-index="${O}"]`).forEach(z=>z.classList.add("is-active")),a.classList.add("is-hovering"),x(O)},x=y=>{let g=t.elections[y];if(!g){i.hidden=!0;return}let O=t.series.map(G=>({item:G,value:G.values[y]})).filter(G=>G.value).sort((G,z)=>z.value.share-G.value.share),_=p();i.innerHTML=` +
    ${it(c(g.date))}
    + ${g.body?`
    ${it(g.body)}
    `:""} + + ${O.map(G=>` + + + + `).join("")} +
    ${it(G.item.party)}${ee(G.value.share)}
    + `,i.hidden=!1,F(y)},F=y=>{let g=h.layout;if(!g)return;let O=a.getBoundingClientRect(),_=h.svg.getBoundingClientRect(),G=_.width/g.width||1,z=_.left-O.left+g.columns[y]*G,H=i.offsetWidth,nt=i.offsetHeight,Q=z+12;Q+H>O.width-4&&(Q=z-H-12),Q<4&&(Q=4);let et=_.top-O.top+g.plot.top*G;et=Math.max(0,Math.min(et,O.height-nt)),i.style.left=`${Math.round(Q)}px`,i.style.top=`${Math.round(et)}px`},P=y=>{let g=h.layout;if(!g||!g.columns.length)return-1;let O=h.svg.getBoundingClientRect(),_=O.width/g.width||1,G=(y-O.left)/_,z=-1,H=1/0;return g.columns.forEach((nt,Q)=>{let et=Math.abs(nt-G);et{let g=y.target instanceof Element?y.target.closest("[data-party]"):null;return g?g.getAttribute("data-party"):null},b=y=>{!y||!u.has(y)||(h.lockedParty=h.lockedParty===y?null:y,h.hoverParty=null,d(),h.column>=0&&x(h.column))},R=y=>{y.pointerType!=="touch"&&(h.hoverParty=A(y),d(),m(P(y.clientX)))},T=()=>{h.hoverParty=null,d(),h.pinned||m(-1)},V=y=>{y.pointerType==="touch"&&(h.pinned=!0,m(P(y.clientX)))},E=y=>{let g=A(y);g?b(g):h.lockedParty&&b(h.lockedParty)},w=y=>{!h.pinned||y.pointerType!=="touch"||y.target instanceof Node&&a.contains(y.target)||(h.pinned=!1,m(-1))},B=y=>{let g=h.layout?.columns.length||0;if(g)if(y.key==="ArrowRight"||y.key==="ArrowLeft"){y.preventDefault();let O=y.key==="ArrowRight"?1:-1,_=h.column<0?O>0?0:g-1:Math.min(g-1,Math.max(0,h.column+O));h.pinned=!0,m(_)}else y.key==="Escape"&&(h.pinned=!1,h.lockedParty=null,d(),m(-1))},M=y=>{let g=y.target instanceof Element?y.target.closest("button[data-party]"):null;g&&b(g.getAttribute("data-party"))},C=y=>{if(y.pointerType==="touch")return;let g=y.target instanceof Element?y.target.closest("button[data-party]"):null;h.hoverParty=g?g.getAttribute("data-party"):null,d()},N=()=>{h.hoverParty=null,d()},k=()=>{if(h.destroyed)return;let y=Math.round(s.clientWidth||r.clientWidth||640),g=typeof e.height=="function"?e.height(y):e.height;if(y===h.width&&g===h.height&&h.svg)return;h.width=y,h.height=g,h.layout=nn(t,{width:y,height:g,measureText:l}),s.innerHTML=an(t,h.layout,{ariaLabel:e.ariaLabel}),h.svg=s.querySelector("svg"),h.svg.addEventListener("pointermove",R),h.svg.addEventListener("pointerleave",T),h.svg.addEventListener("pointerdown",V),h.svg.addEventListener("click",E),h.svg.addEventListener("keydown",B),d();let O=h.column;h.column=-1,O>=0&&h.pinned?m(O):i.hidden=!0};o.addEventListener("click",M),o.addEventListener("pointerover",C),o.addEventListener("pointerout",N),n.addEventListener("pointerdown",w,!0);let j=null,D=0;typeof ResizeObserver=="function"&&(j=new ResizeObserver(()=>{D||(D=requestAnimationFrame(()=>{D=0,k()}))}),j.observe(s),e.fitTo instanceof Element&&j.observe(e.fitTo)),k();let f={render:k,focus(y){h.lockedParty=y&&u.has(y)?y:null,d()},destroy(){h.destroyed||(h.destroyed=!0,j?.disconnect(),D&&cancelAnimationFrame(D),o.removeEventListener("click",M),o.removeEventListener("pointerover",C),o.removeEventListener("pointerout",N),n.removeEventListener("pointerdown",w,!0),r.__trendChart===f&&delete r.__trendChart)}};return r.__trendChart=f,f}function sn(r){return r.series.map(t=>``).join("")}function on(r){try{let e=r.ownerDocument.createElement("canvas").getContext("2d");if(!e)return te;let n=getComputedStyle(r).fontFamily||"sans-serif";return(a,s=!1,i=12)=>(e.font=`${s?"600":"400"} ${i}px ${n}`,e.measureText(String(a)).width)}catch{return te}}function ee(r){let t=Number(r);return Number.isFinite(t)?`${t.toFixed(1)}%`:""}function te(r,t=!1,e=12){return String(r).length*e*(t?.6:.55)}function rn(r){let t=String(r||"").match(/^(\d{4})-(\d{2})-(\d{2})/);return t?Date.UTC(Number(t[1]),Number(t[2])-1,Number(t[3])):NaN}function kt(r){let t=Number(r);return Number.isFinite(t)?t:0}function ln(r){return String(r??"").normalize("NFKD").replace(/[̀-ͯ]/g,"").replace(/\([^)]*\)/g," ").replace(/&/g," and ").replace(/['’`]/g,"").replace(/[-_/.,()]/g," ").replace(/\s+/g," ").trim().toLowerCase()}function it(r){return String(r??"").replace(/[&<>"']/g,t=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[t])}var cn="/render/metadata/elections-test2.json?v=test-023";function Lt(){try{let r=new URLSearchParams(window.location.search).get("electionsApi");return r==="1"||r==="true"?!0:!(r==="0"||r==="false"||window.localStorage?.getItem("civgraph.electionsApi")==="0")}catch{return!0}}function $e(r){return Lt()?`/_api/elections?key=${encodeURIComponent(r.key)}&format=bundle&lite=1`:`${r.resultUrl}?v=test-023`}async function dn(r){try{let t=await fetch(`/render/metadata/election-provenance/${encodeURIComponent(r)}.json`,{cache:"force-cache"});return t.ok&&(await t.json())?.contests||null}catch{return null}}function ne(r,t,e){try{let n=JSON.stringify({source:"elections",metric:r,value:1,path:typeof window<"u"&&window.location&&window.location.pathname||"",event:{reason:String(t).slice(0,240),layerId:String(e||"")}}),a="/_api/rum";typeof navigator<"u"&&navigator.sendBeacon?navigator.sendBeacon(a,new Blob([n],{type:"application/json"})):fetch(a,{method:"POST",headers:{"Content-Type":"application/json"},body:n,keepalive:!0})}catch{}}var un=["winner","leadingParty","voteShare","turnout","majority","seats","quota"],Ce="test2-election-seat-source",Se="test2-election-seat-halo-layer",Ne="test2-election-seat-layer",hn="test2-election-seat-overlay",gt="test2-election-vote-bar-source",Pt="test2-election-vote-bar-layer",$t="test2-election-recall-label-source",Ct="test2-election-recall-label-layer",_t=12,yn=_t+1,Mt=4,ae=120,Ee=18,pn=4,mn=3,fn=160,vn=40,bn=260,gn=160,Pn=90,se=null,ft=Object.freeze({unmatchedFillColor:"#dfe4ec",unmatchedFillOpacity:.42,unmatchedStrokeColor:"#a1aab8",matchedFillOpacity:.6,matchedStrokeColor:"#333",strokeOpacity:.8,strokeWidth:1.5}),_e={winner:"Winner",leadingParty:"Leading party",voteShare:"Vote share",turnout:"Turnout",majority:"Majority",seats:"Seats",quota:"Quota"},le=new Map([["alliance","#f6cb2f"],["aontu","#44532a"],["conservative","#0087dc"],["dup","#d46a4c"],["fianna fail","#66bb66"],["fine gael","#6699ff"],["green","#22ac6f"],["green party","#22ac6f"],["independent","#b8b8b8"],["independent ireland","#3bee56"],["independent unionist","#aadfff"],["independent labour","#ff9999"],["independent nationalist","#cdffab"],["irish labour","#cc0000"],["labour","#cc0000"],["nationalist party","#32cd32"],["northern ireland labour party","#dc241f"],["pbp","#ff0090"],["people's democracy","#ff0000"],["republican clubs","#930c1a"],["republican labour party","#85de59"],["sdlp","#2aa82c"],["sinn fein","#326760"],["social democrats","#752f8b"],["solidarity pbp","#8e2420"],["solidarity-pbp","#8e2420"],["tuv","#0c3a6a"],["unionist party of northern ireland","#ffa07a"],["uup","#48a5ee"],["yes","#2aa82c"],["no","#d46a4c"]]),Me=new Map([["fianna fail","#66BB66"],["fine gael","#6699FF"],["sinn fein","#326760"],["labour","#CC0000"],["irish labour","#CC0000"],["the labour party","#CC0000"],["green comhaontas glas","#22AC6F"],["green party","#22AC6F"],["green","#22AC6F"],["social democrats","#752F8B"],["people before profit solidarity","#FF0090"],["pbp solidarity","#FF0090"],["solidarity people before profit","#8E2420"],["solidarity pbp","#8E2420"],["people before profit","#FF0090"],["aontu","#44532A"],["independent ireland","#3BEE56"],["progressive democrats","#1251A2"],["workers party republican clubs","#930C1A"],["independents 4 change","#FFC0CB"],["renua","#FFA500"],["independent","#DCDCDC"],["non party independent","#DCDCDC"],["yes","#43A047"],["no","#E53935"]]),Le=class{constructor({app:t,mapController:e,onError:n}={}){this.app=t,this.mapController=e,this.onError=n,this.catalogue=null,this.activeEntry=null,this.activeBundle=null,this.previousBundle=null,this.activeMode="winner",this.overlayMode="circles",this.activePanelView="party",this.activeSelectedResultKey=null,this.activeEntityKind=null,this.activeEntityKey=null,this.activeEntityReturnView="party",this.activeLocalMode="dea",this.activeGeographyModeId=null,this.countDetailedView=!1,this.bundleCache=new Map,this.trendSummaryCache=new Map,this.trendSummaryPromiseCache=new Map,this.trendRenderCache=new Map,this.trendChart=null,this.featureIndexCache=new Map,this.resultsByLayer=new Map,this.seatCircleClickBound=!1,this.seatCircleOverlay=null,this.seatCircleOverlayState={groups:[],dotCount:0},this.seatCircleMarkers=[],this.lastSeatCircleRenderMs=0,this.overlayRefreshPending=!1,this.seatCirclePositionUpdatePending=!1,this.overlayWorker=null,this.overlayWorkerSeq=0,this.overlayWorkerCallbacks=new Map,this.voteBarClickBound=!1,this.recallLabelClickBound=!1,this.overlayRefreshBound=!1,this.loadSerial=0,this.sharedRenderer=be(this),this.mainPaneContract=new wt(this)}async load(){let t=await fetch(cn,{cache:"force-cache"});if(!t.ok)throw new Error(`Failed to load the MapLibre election catalogue: ${t.status}`);return this.catalogue=await t.json(),this.catalogue}buildCatalogueCards(){return(this.catalogue?.elections||[]).map(t=>({...t,canonicalLayerId:this.getCanonicalLayerId(t),placeholder:!t.loadable&&!t.resultsOnly,displaySubtitle:this.getMainCatalogueSubtitle(t),displayProvider:this.getMainCatalogueProvider(t),displayTitle:t.displayTitle||t.body}))}getMainCatalogueProvider(t){return t?t.displayProvider&&t.displayProvider!==t.body?t.displayProvider:t.bodyGroup==="local-government"?"Local Government Districts":Ot(t.body):""}getMainCatalogueSubtitle(t){if(!t)return"";if(t.displaySubtitle)return t.displaySubtitle;let e=Array.isArray(t.constituencies)?t.constituencies:[];if(t.isByElection&&e.length)return e.join(", ");if(t.body==="European Parliament"&&e.filter(a=>a!=="Northern Ireland").length===0)return"Northern Ireland";if(t.bodyGroup==="local-government"){let a=Number(t.totalConstituencies??e.length);return`${Number.isFinite(a)?a:0} DEAs`}let n=Number(t.totalConstituencies??e.filter(a=>a!=="Northern Ireland").length);return`${Number.isFinite(n)?n:0} constituencies`}async loadElection(t,e){let n=++this.loadSerial,a=this.findEntry(t,e);if(!a)throw new Error(`Election not found: ${t} ${e}`);if(!a.loadable&&!a.resultsOnly)throw new Error(`${t} ${e} is in the election catalogue, but its geography is not converted for MapLibre yet.`);this.activeEntry&&(this.activeEntry.body!==t||this.activeEntry.date!==e)&&this.unloadElection(),this.renderLoadingPanel(a);let s=a.resultsOnly?Promise.resolve(null):this.app.loadMap(a.sourceMapId),i=this.loadBundle(a),o=this.loadPreviousBundle(a),l=i.then(h=>this.loadFeatureIndexForBundle(h)).catch(()=>null),[c,u]=await Promise.all([i,o,s,l]).then(([h,p])=>[h,p]);n===this.loadSerial&&(this.activeEntry=a,this.activeBundle=c,this.previousBundle=u,this.activeMode=a.stylingModes?.includes(this.activeMode)?this.activeMode:a.stylingModes?.find(h=>un.includes(h))||"winner",this.shouldRenderElectionOverlays()||(this.overlayMode="circles"),this.activePanelView="party",this.activeSelectedResultKey=null,this.activeEntityKind=null,this.activeEntityKey=null,this.activeEntityReturnView="party",this.activeLocalMode=a.bodyGroup==="local-government"?"dea":"constituency",this.activeGeographyModeId=this.defaultGeographyModeId(),this.countDetailedView=!1,this.indexBundle(c),await this.syncLocalGovernmentBackingLayers(),this.applyActiveStyle(),this.renderPanel(),await An(),await this.renderElectionOverlay(),this.updateElectionTimeline(),this.announceUnmatchedGeography(a),this.app.syncCatalogueMapState(),this.app.updateActiveLayers(),a.sourceMapId&&this.app.refitAfterElectionPane?.(a.sourceMapId),this.app.focusActiveElectionCatalogueEntry?.(a,{scroll:!1}),this.app.updateURLState())}unloadElection(t={}){let{unloadBackingLayer:e=!0}=t||{},n=this.activeEntry?.sourceMapId,a=e?this.getActiveElectionBackingLayerIds():[];n&&this.mapController.clearElectionStyle?.(n),this.activeBundle?.councilSourceMapId&&this.mapController.clearElectionStyle?.(this.activeBundle.councilSourceMapId),this.removeElectionOverlays(),this.resultsByLayer.clear(),this.activeEntry=null,this.activeBundle=null,this.previousBundle=null,this.activeSelectedResultKey=null,this.activeEntityKind=null,this.activeEntityKey=null,this.activeEntityReturnView="party",this.removePanel(),this.unloadElectionBackingLayers(a),this.app.updateTimeline(),this.app.syncCatalogueMapState(),this.app.updateActiveLayers(),this.app.updateMapList?.(),this.app.updateURLState()}getActiveElectionBackingLayerIds(t=this.activeEntry,e=this.activeBundle){let n=Array.isArray(e?.geographyModes)?e.geographyModes.flatMap(a=>[a.sourceMapId,a.layerId]):[];return[...new Set([t?.sourceMapId,e?.sourceMapId,e?.layerId,e?.councilSourceMapId,e?.councilLayerId,...n].filter(Boolean))]}unloadElectionBackingLayers(t=[]){for(let e of t)(this.mapController.getLayerState?.(e)||this.mapController.groupStates?.has(e)||this.mapController.isLayerLoaded?.(e))&&this.mapController.unloadLayer(e)}async syncLocalGovernmentBackingLayers(){if(!this.isLocalGovernmentElection())return;let t=this.activeEntry?.sourceMapId||this.activeBundle?.sourceMapId,e=this.activeBundle?.councilSourceMapId||this.activeEntry?.councilSourceMapId;if(this.activeLocalMode==="district"&&e){this.mapController.isLayerLoaded?.(e)||await this.mapController.loadLayer(e,{fit:!1}),t&&this.mapController.isLayerLoaded?.(t)&&(this.mapController.clearElectionStyle?.(t),this.mapController.hideLayer?.(t)),this.mapController.showLayer?.(e);return}e&&this.mapController.isLayerLoaded?.(e)&&(this.mapController.clearElectionStyle?.(e),this.mapController.hideLayer?.(e)),t&&this.mapController.isLayerLoaded?.(t)&&this.mapController.showLayer?.(t)}isElectionLoaded(t,e){return this.activeEntry?.body===t&&this.activeEntry?.date===e}getURLState(){return this.activeEntry?{layerId:this.getCanonicalLayerId(this.activeEntry),body:this.activeEntry.body,date:this.activeEntry.date,mode:this.activeMode,overlay:this.overlayMode,view:this.activePanelView,localMode:this.activeLocalMode,geographyMode:this.activeGeographyModeId,selected:this.activeSelectedResultKey,countDetail:this.countDetailedView,entityKind:this.activeEntityKind,entityKey:this.activeEntityKey,entityReturnView:this.activeEntityReturnView}:null}async restoreURLState(t){let e=t.get("electionBody"),n=t.get("electionDate"),a=t.get("election"),s=null;if(a&&!e&&!n){let P=a.split(":");if(P.length>=2){let A=P[0];n=P[1],s=P.length>2?P[2]:null;let b=T=>String(T||"").toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s]+/g,"-").replace(/-+/g,"-"),R=(this.catalogue?.elections||[]).find(T=>b(T.body)===A&&T.date===n);R&&(e=R.body)}}if(!e||!n){let A=(t.get("layers")||"").split(",").map(b=>b.trim()).filter(Boolean).map(b=>this.findEntryByCanonicalLayerId(b)).find(Boolean);A&&(e=A.body,n=A.date)}if(!e||!n)return;await this.loadElection(e,n);let i=t.get("electionGeographyMode");i&&this.geographyModes().some(P=>P.id===i)&&await this.switchGeographyMode(i);let o=t.get("electionMode");o&&this.activeEntry?.stylingModes?.includes(o)&&(this.activeMode=o,this.applyActiveStyle()),this.overlayMode=t.get("electionOverlay")==="bars"?"bars":this.overlayMode,this.activeLocalMode=t.get("electionLocalMode")==="district"?"district":this.activeLocalMode,await this.syncLocalGovernmentBackingLayers(),this.applyActiveStyle();let l=t.has("electionSelected")||!!s,c=t.get("electionSelected")||s||"",u=l?this.findResultByKey(c):null,h=!!u,d=t.has("electionView")?t.get("electionView"):null,m=h?d||"party":d&&d!=="counts"&&d!=="animation"?d:"party";this.countDetailedView=h&&t.get("electionCountDetail")==="1",h||(this.activeSelectedResultKey=null,this.activeEntityKind=null,this.activeEntityKey=null,this.activeEntityReturnView=null),await this.renderElectionOverlay(),this.renderPanel(h?u:null,m);let x=t.get("electionEntityKind"),F=t.get("electionEntityKey");h&&x&&F&&(this.activeEntityReturnView=t.get("electionEntityReturnView")||m||"party",this.renderEntityPanel(x,F,{updateURL:!1})),this.app.focusActiveElectionCatalogueEntry?.(this.activeEntry,{scroll:!1})}async loadBundle(t){if(this.bundleCache.has(t.key))return this.bundleCache.get(t.key);let e=await fetch($e(t),{cache:"force-cache"});if(!e.ok&&Lt()&&(console.warn(`[test2 elections] elections API returned ${e.status} for ${t.key}; falling back to the static bundle`),ne("elections-api-fallback",`bundle fetch returned ${e.status}`,t.key),e=await fetch(`${t.resultUrl}?v=test-023`,{cache:"force-cache"})),!e.ok)throw new Error(`Failed to load election results for ${t.body} ${t.date}: ${e.status}`);let n=await e.json();return n.provenance=await dn(t.key),Dt(this.bundleCache,t.key,n,pn),n}async loadTrendSummary(t){if(!t?.key||!t.resultUrl)return null;if(this.trendSummaryCache.has(t.key))return this.trendSummaryCache.get(t.key);if(this.trendSummaryPromiseCache.has(t.key))return this.trendSummaryPromiseCache.get(t.key);let e=(async()=>{let n=null;if(this.activeEntry?.key===t.key&&this.activeBundle)n=this.activeBundle;else if(this.bundleCache.has(t.key))n=this.bundleCache.get(t.key);else{let s=await fetch($e(t),{cache:"force-cache"});if(!s.ok&&Lt()&&(s=await fetch(`${t.resultUrl}?v=test-023`,{cache:"force-cache"})),!s.ok)throw new Error(`Failed to load trend data for ${t.body} ${t.date}: ${s.status}`);n=await s.json()}let a=this.buildTrendSummary(t,n);return Dt(this.trendSummaryCache,t.key,a,fn),a})();this.trendSummaryPromiseCache.set(t.key,e);try{return await e}finally{this.trendSummaryPromiseCache.delete(t.key)}}buildTrendSummary(t,e){let n=Array.isArray(e?.results)?e.results:[],a=o=>tt(o||[]).filter(l=>v(l.votes)>0||v(l.seats)>0).map(l=>({party:l.party,share:Number.isFinite(Number(l.share))?Number(l.share):0,votes:v(l.votes),seats:v(l.seats),colour:this.mainPanePartyColour(l.party,l.colour),entry:t})),s=new Map,i=new Map;for(let o of n){let l=a([o]);for(let u of vt(o))u&&s.set(u,l);let c=L(o.localBody||o.council||"");if(c){let u=i.get(c)||[];u.push(o),i.set(c,u)}}for(let[o,l]of i.entries())i.set(o,a(l));return{entry:t,overallRows:a(n),resultRowsByKey:s,localRowsByKey:i}}async loadPreviousBundle(t){if(!t?.previousKey)return null;let e=(this.catalogue?.elections||[]).find(n=>n.key===t.previousKey);if(!e?.resultUrl)return null;try{return await this.loadBundle(e)}catch(n){return console.warn("[test2 elections] Previous bundle unavailable",t.previousKey,n),null}}indexBundle(t){let e=new Map;for(let n of t.results||[])for(let a of vt(n))e.has(a)||e.set(a,n);t.layerId&&this.resultsByLayer.set(t.layerId,e),t.sourceMapId&&this.resultsByLayer.set(t.sourceMapId,e)}enrichFeature(t){if(!this.activeBundle||!t)return t;let e=this.resultsByLayer.get(t.mapId)||this.resultsByLayer.get(this.activeBundle.layerId)||this.resultsByLayer.get(this.activeBundle.sourceMapId),n=this.findResultForFeature(e,t);if(!n)return t;let a={...t.properties||{},Election:`${this.activeBundle.body} (${this.activeBundle.date})`,Constituency:n.constituency,"Winning party":n.winnerParty||"",Winner:n.winnerName||"","Leading party":n.leadingParty||"","Leading candidate":n.leadingName||"","Leading votes":S(n.leadingVotes),"Vote share":st(n.leadingPct),Turnout:st(n.turnoutPct),Majority:S(n.majority),"Majority share":st(n.majorityPct),"Seats won":S(n.seatsWon),Seats:S(n.seatsTotal),Quota:S(n.quota),Electorate:S(n.electorate),"Valid poll":S(n.validPoll)};return{...t,featureName:t.featureName||n.constituency,name:t.name||n.constituency,electionResult:n,properties:a}}findResultForFeature(t,e){if(!this.activeBundle||!e)return null;let n=this.getActiveElectionStyleLayer?.()||this.activeBundle,a=n?.labelProperty||this.activeBundle.labelProperty,s=he({id:n?.id||this.activeBundle.layerId,sourceMapId:n?.sourceMapId||this.activeBundle.sourceMapId,labelProperty:a},e.properties||{}),i=[e.featureName,e.name,s?.[a],s?.[this.activeBundle.councilLabelProperty],s?.[this.activeBundle.labelProperty],s?.name,s?.Name,s?.NAME,e.id];if(this.isLocalGovernmentElection()&&this.activeLocalMode==="district")for(let o of i){let l=this.findCouncilAggregateResultByName(o);if(l)return l}if(!t)return null;for(let o of i){let l=t.get(L(o));if(l)return l}return null}applyActiveStyle(){if(!this.activeEntry||!this.activeBundle)return;let t=this.getActiveElectionStyleLayer(),e=t?.sourceMapId||this.getActiveElectionStyleSourceMapId();if(!e)return;let n=this.buildColourExpression(this.activeMode,ft.unmatchedFillColor,t),a=t?.geometryType==="point";this.mapController.applyElectionStyle?.(e,{mode:this.activeMode,fillColorExpression:n,lineColorExpression:a?n:this.buildElectionMatchExpression(()=>ft.matchedStrokeColor,ft.unmatchedStrokeColor,t),fillOpacityExpression:a?void 0:this.buildElectionMatchExpression(()=>ft.matchedFillOpacity,ft.unmatchedFillOpacity,t),lineOpacity:a?void 0:ft.strokeOpacity,lineWidth:a?void 0:ft.strokeWidth,hideLabels:!0}),this.renderLegend()}getActiveElectionStyleSourceMapId(){if(this.isLocalGovernmentElection()&&this.activeLocalMode==="district")return this.activeBundle?.councilSourceMapId||this.activeEntry?.councilSourceMapId||this.activeEntry?.sourceMapId;let t=this.activeGeographyMode();return t?.sourceMapId?t.sourceMapId:this.activeEntry?.sourceMapId||this.activeBundle?.sourceMapId}getActiveElectionStyleLayer(){let t=this.getActiveElectionStyleSourceMapId();if(!t)return this.activeBundle;let e=this.mapController?.resolveLayer?.(t)||this.app?.metadataService?.getLayer?.(t)||null,n=this.activeGeographyMode();return n?.sourceMapId===t?e||{id:n.layerId,sourceMapId:t,labelProperty:n.labelProperty,geometryType:n.geometryType}:e||{id:this.isLocalGovernmentElection()&&this.activeLocalMode==="district"?this.activeBundle?.councilLayerId:this.activeBundle?.layerId,sourceMapId:t,labelProperty:this.isLocalGovernmentElection()&&this.activeLocalMode==="district"?this.activeBundle?.councilLabelProperty:this.activeBundle?.labelProperty,geometryType:this.isLocalGovernmentElection()&&this.activeLocalMode==="district"?this.activeBundle?.councilGeometryType:this.activeBundle?.geometryType}}buildElectionMatchInput(t=this.activeBundle){let e=t?.labelProperty||"name";return ye({id:t?.id||this.activeBundle?.layerId,sourceMapId:t?.sourceMapId||this.activeBundle?.sourceMapId,labelProperty:e},["to-string",["get",e]])}buildElectionMatchExpression(t,e,n=this.activeBundle,a=this.activeBundle?.results||[]){let s=[],i=new Set;for(let o of a||[])if(!(!o.matched&&!(this.isLocalGovernmentElection()&&this.activeLocalMode==="district")))for(let l of Sn(o))for(let c of Cn(l))i.has(c)||(i.add(c),s.push(c,t(o)));return s.length?["match",["to-string",this.buildElectionMatchInput(n)],...s,e]:e}buildColourExpression(t,e=ft.unmatchedFillColor,n=this.activeBundle){return this.isLocalGovernmentElection()&&this.activeLocalMode==="district"?this.buildCouncilColourExpression(t,e,n):this.buildElectionMatchExpression(a=>this.colourForMode(t,a),e,n,this.currentResults())}buildCouncilColourExpression(t,e,n=this.activeBundle){let s=Et(this.currentResults()).map(i=>({constituency:i.council,matchName:i.council,featureAliases:xe(i.council),matched:!0,winnerParty:i.leadingParty,leadingParty:i.leadingParty,leadingColour:this.mainPanePartyColour(i.leadingParty,i.colour),colour:this.mainPanePartyColour(i.leadingParty,i.colour),leadingPct:i.share,seatsWon:i.seats,seatsTotal:i.seats,turnoutPct:i.turnoutPct}));return this.buildElectionMatchExpression(i=>this.colourForMode(t,i),e,n,s)}colourForMode(t,e){return t==="winner"?this.partyColourForResult(e,e.winnerParty,e.colour,{preferElected:!0})||"#6b7280":t==="leadingParty"?this.partyColourForResult(e,e.leadingParty,e.leadingColour)||"#6b7280":t==="turnout"?St(e.turnoutPct,35,80):t==="voteShare"?St(e.leadingPct,10,70):t==="majority"?St(e.majorityPct,0,45):t==="seats"?St(e.seatsWon??e.seatsTotal,1,6):t==="quota"?St(e.quota,1e3,12e4):"#6b7280"}usesMainRoiPartyPalette(){let e=[this.activeBundle?.body,this.activeEntry?.body,this.activeBundle?.bodyGroup,this.activeEntry?.bodyGroup,this.activeBundle?.jurisdiction,this.activeEntry?.jurisdiction,this.activeBundle?.region,this.activeEntry?.region,this.activeBundle?.id,this.activeEntry?.id,this.activeEntry?.key].map(n=>L(n)).join(" ");return!!(e.includes("dail")||e.includes("president of ireland")||e.includes("referendum ireland")||e.includes("european parliament ireland")||e.includes("republic of ireland")&&e.includes("european parliament")||e.includes("irish local"))}getElectionWidePercentLabel(){return`% of ${this.usesMainRoiPartyPalette()?"ROI":"NI"}`}mainPanePartyColour(t,e=""){let n=String(e||"").trim();if(n)return n;let a=L(t);if(!a)return"#6b7280";let i=(this.usesMainRoiPartyPalette()?Me:le).get(a),o=X(t,""),l=le.get(a);return i||o||l?i||o||l:this.usesMainRoiPartyPalette()?Me.get(a)||X(t)||jt(t)||"#b0bec5":X(t)||jt(t)||"#6b7280"}partyColourForResult(t={},e="",n="",a={}){let s=L(e),o=(Array.isArray(t?.candidates)?t.candidates:[]).filter(u=>L(u.party)===s),c=(a.preferElected?o.find(u=>u.elected&&u.colour):null)||o.find(u=>u.name===t.leadingName&&u.colour)||o.find(u=>u.name===t.winnerName&&u.colour)||o.find(u=>u.colour);return this.mainPanePartyColour(e,c?.colour||n)}renderPanel(t=null,e=null){let n=this.ensurePanel(),a=document.getElementById("electionPaneContent"),s=document.getElementById("electionPaneTitle"),i=document.getElementById("electionPaneBack");if(!n||!a||!s||!this.activeEntry||!this.activeBundle)return;let o=this.normalizePanelView(e||this.activePanelView||"party",t);this.activePanelView=o,this.activeSelectedResultKey=t?L(t.matchName||t.constituency||""):null,this.activeEntityKind=null,this.activeEntityKey=null,t&&this.hydrateSelectedResult(t).catch(c=>console.warn("[test2 elections] Could not load constituency count detail",c)),this.renderPanelTitle(s,t),i?.classList.toggle("hidden",!t);let l=n.querySelector(".election-pane__header-right");if(l&&(l.innerHTML=this.mainPaneContract.renderHeaderRight(t,o)),a.innerHTML=this.mainPaneContract.renderPanelContent(t,o),n.classList.add("election-results-pane--open"),document.body.classList.add("test2-election-open"),i?.addEventListener("click",()=>this.renderPanel(null,"party")),n.querySelector("#electionCloseBtn, #test2ElectionClose")?.addEventListener("click",()=>this.unloadElection()),n.querySelector("#test2ElectionMode")?.addEventListener("change",c=>{this.activeMode=c.target.value,this.applyActiveStyle()}),n.querySelector("#test2ElectionGeography")?.addEventListener("change",c=>{this.switchGeographyMode(c.target.value)}),n.querySelector("#test2ElectionOverlay")?.addEventListener("change",async c=>{this.overlayMode=c.target.value==="bars"?"bars":"circles",await this.renderElectionOverlay(),this.app.updateURLState()}),n.querySelectorAll("[data-election-local-mode]").forEach(c=>{c.addEventListener("click",async()=>{this.activeLocalMode=c.dataset.electionLocalMode==="district"?"district":"dea",await this.syncLocalGovernmentBackingLayers(),this.applyActiveStyle(),this.renderPanel(null,this.activeLocalMode==="district"?"party":this.activePanelView),this.renderElectionOverlay().catch(u=>console.warn("[test2 elections] Overlay refresh failed",u)),this.app.updateURLState()})}),n.querySelector("#test2ElectionCountDetail")?.addEventListener("click",()=>{this.countDetailedView=!this.countDetailedView,this.renderPanel(t,"counts"),this.app.updateURLState()}),n.querySelectorAll("[data-election-view]").forEach(c=>{c.addEventListener("click",()=>{this.renderPanel(t,c.dataset.electionView||"party"),this.app.updateURLState()})}),n.querySelectorAll("[data-election-result-key]").forEach(c=>{c.addEventListener("click",()=>{let u=this.findResultByKey(c.dataset.electionResultKey);u&&(this.renderPanel(u,"party"),this.app.updateURLState())})}),n.querySelectorAll("[data-election-entity]").forEach(c=>{c.addEventListener("click",async()=>{let u=String(c.dataset.electionEntity||"").toLowerCase(),h=c.dataset.electionEntityKey;if(await this.app.openElectionEntityDetailInCatalogue?.(u,h)){this.app.updateURLState();return}if(u==="party"||u==="candidate"||u==="person"){console.warn("[test2 elections] Catalogue entity detail unavailable",u,h);return}this.renderEntityPanel(u,h),this.app.updateURLState()})}),n.querySelector("[data-election-selected-area]")?.addEventListener("click",async c=>{let u=c.currentTarget;await this.app.openElectionEntityDetailInCatalogue?.(u.dataset.electionSelectedAreaKind,u.dataset.electionSelectedAreaKey)&&this.app.updateURLState()}),n.querySelectorAll("[data-election-animation]").forEach(c=>{c.addEventListener("click",()=>{let u=this.findResultByKey(c.dataset.electionAnimation);u&&this.runAnimation(u)})}),t&&o==="animation"&&this.resultHasAnimation(t)&&window.requestAnimationFrame(()=>this.runAnimation(t)),o!=="trends"&&this.trendChart&&(this.trendChart.destroy(),this.trendChart=null),o==="trends"){let c=n.querySelector("#test2ElectionTrendsScope"),u=()=>{this.hydrateTrendsPanel(t,!!c?.checked).catch(h=>{let p=n.querySelector("#test2ElectionTrendsChart");p&&(p.innerHTML='

    Trend data could not be loaded.

    '),console.warn("[test2 elections] Trend render failed",h)})};c?.addEventListener("change",u),window.requestAnimationFrame(u)}this.renderLegend(),this.setupResultsTableControls(n)}normalizePanelView(t,e=null){let n=t||"party";return e&&this.isSingleSeatFptpResult(e)?n==="trends"?"trends":"results":this.isCouncilAggregateResult(e)?["party","candidate","local-party","trends"].includes(n)?n:"party":!e&&this.isLocalGovernmentElection()&&this.activeLocalMode==="district"?["party","candidate","local-party","trends"].includes(n)?n:"party":e||["party","candidate","local-party","constituency","trends"].includes(n)?n:"party"}renderPanelTitle(t,e=null){if(!t)return;if(!e?.constituency){t.textContent=this.mainPaneContract.renderTitle(e);return}let n=this.selectedResultEntityKind(e);t.innerHTML=` + + `}selectedResultEntityKind(){return this.isLocalGovernmentElection()?this.activeLocalMode==="district"?"lgd":"dea":"constituency"}isSingleSeatFptpResult(t={}){if(!t||t.recallPetition||this.isCouncilAggregateResult(t)||this.isForumResult(t))return!1;let e=L(t.contestType||this.activeBundle?.contestType||this.activeEntry?.contestType||"election");if(e&&e!=="election")return!1;let n=L(t.votingSystem||t.electionVotingSystem||t.system||this.activeBundle?.votingSystem||this.activeEntry?.votingSystem||"");if(n!=="fptp"&&n!=="first past the post"&&n!=="first past post")return!1;let a=[t.seatsTotal,t.seatsWon,t.seats,t.countInfo?.Number_Of_Seats,t.countInfo?.numberOfSeats,t.countInfo?.Seats].map(Y).filter(i=>i!==null&&i>0);return a.length?Math.max(...a)===1:(t.candidates||[]).filter(i=>i.elected?!0:It(i.status||i.Status)==="elected").length===1}isReferendumElection(t=null){return[t?.contestType,t?.type,t?.body,this.activeBundle?.contestType,this.activeEntry?.contestType,this.activeBundle?.body,this.activeEntry?.body,this.activeBundle?.key,this.activeEntry?.key].map(n=>L(n)).some(n=>n.includes("referendum"))}renderOverallResults(t="party"){return this.mainPaneContract.renderOverallResults(t)}renderMainCompatibleOverallResults(t="party"){return this.mainPaneContract.renderOverallResults(t)}renderConstituencyResults(t,e="party"){return this.mainPaneContract.renderConstituencyResults(t,e)}renderMainCompatibleConstituencyResults(t,e="party"){return this.mainPaneContract.renderConstituencyResults(t,e)}renderMainParityPartyTable(t=[],e=[],n={}){if(!t.length)return'
    No results data available.
    ';if(n.referendum||this.isReferendumElection())return this.renderReferendumFullResultsTable(t,e);let a=this.orderPartyRowsLikeMain(t),s=n.ignoreMainLikeTotals?null:n.totals||this.activeBundle?.mainLikeTotals||null,i=Number.isFinite(Number(s?.totalSeats))?Number(s.totalSeats):t.reduce((f,y)=>f+v(y.seats),0),o=Number.isFinite(Number(s?.validPoll))?Number(s.validPoll):U(e,"validPoll")||t.reduce((f,y)=>f+v(y.votes),0),l=Number.isFinite(Number(s?.totalPoll))?Number(s.totalPoll):U(e,"totalPoll")||o+U(e,"spoiled"),c=Number.isFinite(Number(s?.totalElectorate))?Number(s.totalElectorate):U(e,"electorate"),u=Number.isFinite(Number(s?.totalSpoiled))?Number(s.totalSpoiled):U(e,"spoiled"),h=c?Math.max(0,c-l):0,p=Array.isArray(n.previousResults)?n.previousResults:null,d=Array.isArray(n.previousRows)?n.previousRows:p?tt(p):this.previousBundle?.mainLikePartySummary?.length?this.previousBundle.mainLikePartySummary:this.previousBundle?.partySummary?.length?this.previousBundle.partySummary:this.previousBundle?.results?.length?tt(this.previousBundle.results):[],m=p?null:this.previousBundle?.mainLikeTotals||null,x=d.reduce((f,y)=>f+v(y.seats),0),F=Number.isFinite(Number(m?.totalSeats))&&Number(m.totalSeats)>0?Number(m.totalSeats):x,P=Number.isFinite(Number(m?.validPoll))?Number(m.validPoll):p?U(p,"validPoll")||d.reduce((f,y)=>f+v(y.votes),0):this.previousBundle?.results?.length?U(this.previousBundle.results,"validPoll")||d.reduce((f,y)=>f+v(y.votes),0):0,A=Number.isFinite(Number(m?.totalPoll))?Number(m.totalPoll):p?U(p,"totalPoll")||P+U(p,"spoiled"):this.previousBundle?.results?.length?U(this.previousBundle.results,"totalPoll")||P+U(this.previousBundle.results,"spoiled"):0,b=Number.isFinite(Number(m?.totalElectorate))?Number(m.totalElectorate):p?U(p,"electorate"):this.previousBundle?.results?.length?U(this.previousBundle.results,"electorate"):0,R=Number.isFinite(Number(m?.totalSpoiled))?Number(m.totalSpoiled):p?U(p,"spoiled"):this.previousBundle?.results?.length?U(this.previousBundle.results,"spoiled"):0,T=b?Math.max(0,b-A):0,V=(f,y)=>y?f/y*100:0,E=V(l,c),w=V(o,c),B=V(u,c),M=V(h,c),C=V(A,b),N=V(P,b),k=V(R,b),j=V(T,b),D=Number(n.constituencyCount??this.activeBundle?.matchedCount??e.length??0);return` +
    +
    + + + + + + + + + + + ${this.renderMainParityLeafTh("No.",2,"Candidates")} + ${this.renderMainParityLeafTh("+/-",3,"Candidates change")} + ${this.renderMainParityLeafTh("No.",4,"Seats")} + ${this.renderMainParityLeafTh("+/-",5,"Seats change")} + ${this.renderMainParityLeafTh("%",6,"Seats percentage")} + ${this.renderMainParityLeafTh("+/-",7,"Seats percentage change")} + ${this.renderMainParityLeafTh("No.",8,"First preference votes")} + ${this.renderMainParityLeafTh("+/-",9,"First preference votes change")} + ${this.renderMainParityLeafTh("%",10,"First preference vote share")} + ${this.renderMainParityLeafTh("+/-",11,"First preference vote share change")} + + + + ${a.map((f,y)=>{let g=V(v(f.seats),i),O=f.previous?V(v(f.previous.seats),F):null,_=Number.isFinite(Number(f.share))?Number(f.share):V(v(f.votes),o),G=f.previous?V(v(f.previous.votes),P):null;return` + + + ${this.renderElectionEntityButton("party",f.party,this.partyLabel(f.party),"election-cell-wrap")} + + + + + + + + + + + + `}).join("")} + ${this.renderMainParitySummaryRow("Valid votes",D,i,"100.00%",0,o,o-P,w,w-N)} + ${this.renderMainParitySummaryRow("Turnout",null,null,null,null,l,l-A,E,E-C)} + ${this.renderMainParitySummaryRow("Spoiled",null,null,null,null,u,u-R,B,B-k)} + ${this.renderMainParitySummaryRow("Did not vote",null,null,null,null,h,h-T,M,M-j)} + ${this.renderMainParitySummaryRow("Electorate",null,null,null,null,c,c-b,100,0)} + +
    #PartyCandidatesSeats1st preferences
    ${$(pt(y))}${S(f.stood)}${Z(f.deltas?.stood)}${S(f.seats)}${Z(f.deltas?.seats)}${J(g)}${rt(O===null?null:g-O)}${S(f.votes)}${Z(f.deltas?.votes)}${J(_)}${rt(G===null?f.deltas?.share:_-G)}
    +
    +
    + `}referendumStats(t={},e=[]){let n=t?.countInfo||{},a=t?.mainLikeTotals||{},s=e.reduce((m,x)=>m+v(x.votes??x.firstPrefs??x.finalVotes??x.total),0),i=Y(a.validPoll??t.validPoll??n.Valid_Poll)??(s||null),o=Y(a.totalElectorate??t.electorate??n.Total_Electorate),l=Y(a.totalPoll??t.totalPoll??n.Total_Poll),c=Y(t.turnoutPct??t.turnout_pct??n.Turnout_Pct),u=l&&l>0?l:o!==null&&c!==null?Math.round(o*c/100):null,h=Y(a.totalSpoiled??t.spoiled??n.Spoiled),p=h&&h>0?h:u!==null&&i!==null?Math.max(0,u-i):h,d=c??(o!==null&&u!==null&&o>0?u/o*100:null);return{validPoll:i,totalPoll:u,electorate:o,spoiled:p,turnoutPct:d}}referendumOutcomeRows(t=[],e=null){return t.map(n=>{let a=n.party||n.name||n.candidate||n.label||"",s=Y(n.votes??n.firstPrefs??n.finalVotes??n.total)??0,i=Y(n.share??n.firstPrefPct??n.constPct)??(e?s/e*100:null);return{outcome:a,votes:s,share:i,constituencies:Y(n.seats??n.constituenciesWon??n.constituencies),colour:this.mainPanePartyColour(a,n.colour),elected:!!n.elected||It(n.status||n.Status)==="elected"}}).filter(n=>n.outcome).sort((n,a)=>+!!a.elected!=+!!n.elected?+!!a.elected-+!!n.elected:v(a.votes)!==v(n.votes)?v(a.votes)-v(n.votes):String(n.outcome).localeCompare(String(a.outcome)))}referendumProposalResultText(t=null){return L(t?.outcome)==="yes"?"Proposal passed":"Proposal did not pass"}renderReferendumProposalRow(t=null,e=4){return t?` + + - + + ${$(this.referendumProposalResultText(t))} + + `:""}renderReferendumSummaryRow(t,e,n=null,a={}){if(e==null||e==="")return"";let s=a.strong?" election-cell-strong":"",i=Math.max(1,Number(a.labelColspan||2)),o=a.trailingCell?"":"";return` + + - + + ${$(t)} + ${S(e)} + ${n==null?"-":J(n)} + ${o} + + `}renderReferendumFullResultsTable(t=[],e=[]){let n=this.referendumStats({mainLikeTotals:this.activeBundle?.mainLikeTotals||{}},t),a=this.referendumOutcomeRows(t,n.validPoll);if(!a.length)return'
    No referendum result data available.
    ';let s=a[0]||null,i=n.electorate&&n.validPoll!==null?n.validPoll/n.electorate*100:null,o=n.totalPoll&&n.spoiled!==null?n.spoiled/n.totalPoll*100:null;return` +
    +
    + + + + + + + + + + + + + ${a.map((l,c)=>` + + + + + + + + + `).join("")} + ${this.renderReferendumProposalRow(s,4)} + ${this.renderReferendumSummaryRow("Valid votes",n.validPoll,i,{strong:!0})} + ${this.renderReferendumSummaryRow("Turnout",n.totalPoll,n.turnoutPct)} + ${this.renderReferendumSummaryRow("Spoiled",n.spoiled,o)} + ${this.renderReferendumSummaryRow("Electorate",n.electorate,100)} + +
    #OutcomeConstituenciesVotes%
    ${$(pt(c))}${this.renderElectionEntityButton("party",l.outcome,$(l.outcome),"election-cell-wrap")}${l.constituencies===null?"-":S(l.constituencies)}${S(l.votes)}${l.share===null?"-":J(l.share)}
    +
    +
    + `}renderReferendumResultTable(t=[],e={}){let n=this.referendumStats(e,t),a=this.referendumOutcomeRows(t,n.validPoll);if(!a.length)return'

    No referendum result table is available for this constituency.

    ';let s=a[0]||null,i=n.electorate&&n.validPoll!==null?n.validPoll/n.electorate*100:null,o=n.totalPoll&&n.spoiled!==null?n.spoiled/n.totalPoll*100:null;return` +
    + + + + + + + + + + + + + ${a.map((l,c)=>` + + + + + + + + + `).join("")} + ${this.renderReferendumProposalRow(s,4)} + ${this.renderReferendumSummaryRow("Valid votes",n.validPoll,i,{strong:!0,labelColspan:1,trailingCell:!0})} + ${this.renderReferendumSummaryRow("Turnout",n.totalPoll,n.turnoutPct,{labelColspan:1,trailingCell:!0})} + ${this.renderReferendumSummaryRow("Spoiled",n.spoiled,o,{labelColspan:1,trailingCell:!0})} + ${this.renderReferendumSummaryRow("Electorate",n.electorate,100,{labelColspan:1,trailingCell:!0})} + +
    #OutcomeVotes%Result
    ${$(pt(c))}${this.renderElectionEntityButton("party",l.outcome,$(l.outcome),"election-cell-wrap")}${S(l.votes)}${l.share===null?"-":J(l.share)}${l===s?`${$(this.referendumProposalResultText(s))}`:""}
    +
    + `}renderReferendumConstituencySummaryTable(t=[]){return t.length?` +
    + + + + + + + + + + + + + + + + + + ${t.map(n=>{let a=this.referendumStats(n,n.candidates||[]),s=this.referendumOutcomeRows(n.candidates||[],a.validPoll),i=s.find(u=>L(u.outcome)==="yes")||null,o=s.find(u=>L(u.outcome)==="no")||null,l=s[0]||null,c=i&&o?Math.abs(v(i.votes)-v(o.votes)):null;return{result:n,stats:a,outcomes:s,yes:i,no:o,winner:l,majority:c}}).sort((n,a)=>String(n.result.constituency||n.result.matchName||"").localeCompare(String(a.result.constituency||a.result.matchName||""),void 0,{numeric:!0,sensitivity:"base"})).map((n,a)=>{let s=n.result.constituency||n.result.matchName||n.result.featureName||"",i=n.winner;return` + + + + ${i?$(this.referendumProposalResultText(i)):"-"} + + + + + + + + + + `}).join("")} + +
    #ConstituencyResultYesYes %NoNo %MajoritySpoiledElectorateTurnout
    ${$(pt(a))}${n.yes?S(n.yes.votes):"-"}${n.yes?.share===null||n.yes?.share===void 0?"-":J(n.yes.share)}${n.no?S(n.no.votes):"-"}${n.no?.share===null||n.no?.share===void 0?"-":J(n.no.share)}${n.majority===null?"-":S(n.majority)}${n.stats.spoiled===null?"-":S(n.stats.spoiled)}${n.stats.electorate===null?"-":S(n.stats.electorate)}${n.stats.turnoutPct===null?"-":J(n.stats.turnoutPct)}
    +
    + `:'

    No constituency referendum results are available.

    '}renderConstituencyCandidateTable(t=[],e={}){if(!t.length)return'

    No candidate-level result table is available for this entry.

    ';let n=v(e.validPoll)||t.reduce((a,s)=>a+v(s.firstPrefs??s.votes),0);return` +
    + + + + + + + + + + + ${this.renderMainParityLeafTh("No.",3,"First preference votes")} + ${this.renderMainParityLeafTh("+/-",4,"First preference votes change")} + ${this.renderMainParityLeafTh("%",5,"First preference vote share")} + ${this.renderMainParityLeafTh("+/-",6,"First preference vote share change")} + ${this.renderMainParityLeafTh("No.",7,"Final count votes")} + ${this.renderMainParityLeafTh("Status",8,"Final count status")} + + + + ${t.map((a,s)=>{let i=v(a.firstPrefs??a.votes),o=Number.isFinite(Number(a.firstPrefPct))?Number(a.firstPrefPct):n?i/n*100:null,l=a.finalVotes??a.total??a.firstPrefs??a.votes,c=this.candidateDeltaForResultCandidate(a,e);return` + + + + ${this.renderElectionEntityButton("party",a.party,this.partyLabel(a.party),"election-cell-wrap")} + + + + + + + + `}).join("")} + +
    #CandidateParty1st preferencesFinal count
    ${$(pt(s))}${this.renderElectionEntityButton("candidate",`${a.name||a.candidate||a.id||""}|${a.party||""}`,a.name||a.candidate||"","election-cell-wrap")}${S(i)}${c.deltas?Z(c.deltas.firstPrefs):ct()}${o===null?"":J(o)}${c.deltas?.firstPrefPct!==null&&c.deltas?.firstPrefPct!==void 0?rt(c.deltas.firstPrefPct):ct()}${S(l)}${a.elected?"Elected":$(a.status||"")}
    +
    + `}renderSingleSeatFptpResultsTable(t=[],e={}){if(!t.length)return'

    No result table is available for this entry.

    ';let n=v(e.validPoll)||t.reduce((p,d)=>p+v(d.firstPrefs??d.votes??d.finalVotes??d.total),0),a=this.buildMainStyleConstituencyPartyRows(e,t).rows||[],s=new Map(a.map(p=>[L(p.party),p])),i=this.findPreviousSelectedResult(e),o=i?this.buildMainStyleConstituencyPartyRows(i,i.candidates||[]).rows||[]:[],l=new Map(o.map(p=>[L(p.party),p])),c=!!i,u=this.isWestminsterElection(),h=t.map((p,d)=>{let m=this.candidateDeltaForResultCandidate(p,e),x=v(p.firstPrefs??p.votes??p.finalVotes??p.total),F=Number.isFinite(Number(p.firstPrefPct))?Number(p.firstPrefPct):n?x/n*100:null,P=p.elected?"elected":It(p.status||p.Status),A=p.elected?"Elected":p.status||p.Status||(P==="elected"?"Elected":"Not elected"),b=m.deltas?.firstPrefs??null,R=m.deltas?.firstPrefPct??null,T=s.get(L(p.party)),V=l.get(L(p.party))||(c?{firstPrefs:0,pct:0}:null),E=T&&V?v(T.firstPrefs)-v(V.firstPrefs):null,w=T&&V&&T.pct!==null&&T.pct!==void 0&&V.pct!==null&&V.pct!==void 0?v(T.pct)-v(V.pct):null,B=kn(this.mainPanePartyColour(p.party,p.colour));return{candidate:p,index:d,votes:x,votePct:F,statusKind:P,statusText:A,candidateVoteDelta:b,candidatePctDelta:R,partyVoteDelta:E,partyPctDelta:w,colour:B,name:p.name||p.candidate||"",party:p.party||""}});return` +
    +
    + + + + + + + + ${u?'':''} + + + ${this.renderMainParityLeafTh("No.",3,"Votes")} + ${this.renderMainParityLeafTh("Party +/-",4,"Votes, party change")} + ${this.renderMainParityLeafTh("Candidate +/-",5,"Votes, candidate change")} + ${this.renderMainParityLeafTh("%",6,"Vote share")} + ${this.renderMainParityLeafTh("Party +/- %",7,"Vote share, party change")} + ${this.renderMainParityLeafTh("Candidate +/- %",8,"Vote share, candidate change")} + + + + ${h.map(p=>{let{candidate:d,index:m,votes:x,votePct:F,statusKind:P,statusText:A,partyVoteDelta:b,candidateVoteDelta:R,partyPctDelta:T,candidatePctDelta:V}=p;return` + + + + ${this.renderElectionEntityButton("party",p.party,this.partyLabel(p.party),"election-cell-wrap")} + + + + + + + ${u?``:``} + + `}).join("")} + +
    #CandidatePartyVotesElectedResult
    ${$(pt(m))}${this.renderElectionEntityButton("candidate",`${p.name||d.id||""}|${p.party||""}`,$(p.name),"election-cell-wrap")}${S(x)}${b==null?ct():Z(b)}${R==null?ct():Z(R)}${F===null?"":J(F)}${T==null?ct():rt(T)}${V==null?ct():rt(V)}${this.electedMark(P==="elected")}${$(A)}
    +
    + ${this.renderSingleSeatFptpVoteGraphic(h,n)} +
    + `}renderSingleSeatFptpVoteGraphic(t=[],e=0){let n=t.filter(i=>i.name||i.party||i.votes>0);if(!n.length)return"";let a=Math.max(1,...n.map(i=>v(i.votes))),s=n.reduce((i,o)=>i+v(o.votes),0);return` + + `}renderConstituencyPartyTable(t=[],e={}){if(!t.length)return'

    No party-level result table is available for this entry.

    ';let n=this.buildMainStyleConstituencyPartyRows(e,t),a=this.findPreviousSelectedResult(e),s=this.buildMainStyleConstituencyPartyRows(a,a?.candidates||[]),i=new Map(s.rows.map(P=>[L(P.party),P])),o=n.rows.map(P=>{let A=i.get(L(P.party))||{stood:0,seats:0,firstPrefs:0,pct:0};return{...P,stoodDelta:P.stood-v(A.stood),electedDelta:P.seats-v(A.seats),firstPrefsDelta:P.firstPrefs-v(A.firstPrefs),pctDelta:P.pct-v(A.pct)}}).sort((P,A)=>v(A.seats)!==v(P.seats)?v(A.seats)-v(P.seats):v(A.firstPrefs)!==v(P.firstPrefs)?v(A.firstPrefs)-v(P.firstPrefs):String(P.party||"").localeCompare(String(A.party||""))),l=Math.max(0,...o.map(P=>v(P.seats))),c=Math.max(0,...o.map(P=>v(P.firstPrefs))),u=(P,A)=>P!==null&&A!==null?P-A:null,h=u(n.validPoll,s.validPoll),p=u(n.totalPoll,s.totalPoll),d=u(n.spoiled,s.spoiled),m=u(n.didNotVote,s.didNotVote),x=u(n.electorate,s.electorate),F=(P,A)=>P!==null||A!==null;return` +
    + + + + + + + + + + + + + + + + + + ${o.map((P,A)=>{let b=P.seats===l&&l>0,R=P.firstPrefs===c&&c>0;return` + + + + + + + + + + + + + + `}).join("")} + + ${this.renderSelectedPartySummaryRow("Valid votes",n.totalStood,n.totalElected,n.validPoll,h,n.validPct,u(n.validPct,s.validPct))} + ${F(n.totalPoll,s.totalPoll)?this.renderSelectedPartySummaryRow("Turnout",null,null,n.totalPoll,p,n.turnoutPct,u(n.turnoutPct,s.turnoutPct)):""} + ${F(n.spoiled,s.spoiled)?this.renderSelectedPartySummaryRow("Spoiled",null,null,n.spoiled,d,n.spoiledPct,u(n.spoiledPct,s.spoiledPct)):""} + ${F(n.didNotVote,s.didNotVote)?this.renderSelectedPartySummaryRow("Did not vote",null,null,n.didNotVote,m,n.didNotVotePct,u(n.didNotVotePct,s.didNotVotePct)):""} + ${F(n.electorate,s.electorate)?this.renderSelectedPartySummaryRow("Electorate",null,null,n.electorate,x,100,0):""} + +
    #PartyStood+/-Elected+/-1st prefs+/-1st prefs %+/-
    ${$(pt(A))}${this.renderElectionEntityButton("party",P.party,this.partyLabel(P.party),"election-cell-wrap")}${S(P.stood)}${Z(P.stoodDelta)}${S(P.seats)}${Z(P.electedDelta)}${S(P.firstPrefs)}${Z(P.firstPrefsDelta)}${J(P.pct)}${Ae(P.pctDelta)}
    -No change in party control
    +
    + `}buildMainStyleConstituencyPartyRows(t={},e=[]){let n=Array.isArray(t?.countGroup)?t.countGroup:t?.animationPayload?.Constituency?.countGroup||[],a=t?.countInfo||{},s=v(a.Valid_Poll)||v(t?.validPoll),i=v(a.Total_Poll)||v(t?.totalPoll)||null,o=v(a.Total_Electorate)||v(t?.electorate)||null,l=v(a.Spoiled)||v(t?.spoiled)||null,c=o!==null&&i!==null?Math.max(0,o-i):null,u=new Map,h=new Set,p=new Set,d=new Map,m=new Map,x=n.length?n:e.map((R,T)=>({Candidate_Id:R.id||R.candidateId||String(T+1),candidateName:R.name||R.candidate||"",Count_Number:"1",Party_Name:R.party||"Independent/Other",Party_Colour:this.mainPanePartyColour(R.party,R.colour),Status:R.elected?"Elected":R.status||"",Total_Votes:R.firstPrefs??R.votes??0}));for(let R of x){if(!Nn(R))continue;let T=me(R.Party_Name)||"Independent/Other",V=String(R.Candidate_Id||""),E=v(R.Total_Votes),w=parseInt(R.Count_Number,10)||1;if(u.has(T)||u.set(T,{party:T,colour:this.mainPanePartyColour(T,R.Party_Colour),stood:0,seats:0,firstPrefs:0,pct:0}),m.has(V)||m.set(V,{party:T,excluded:!1}),w===1&&!h.has(V)){h.add(V);let M=u.get(T);M.firstPrefs+=E,M.stood+=1}(!d.has(V)||E>v(d.get(V)?.votes))&&d.set(V,{party:T,votes:E});let B=It(R.Status);B==="excluded"&&(m.get(V).excluded=!0),B==="elected"&&!p.has(V)&&(p.add(V),u.get(T).seats+=1)}let F=v(a.Number_Of_Seats??t?.seatsTotal??t?.seatsWon);F>0&&p.size!p.has(R)&&!m.get(R)?.excluded).sort((R,T)=>v(T[1]?.votes)-v(R[1]?.votes)).slice(0,F-p.size).forEach(([R,T])=>{p.add(R),u.has(T.party)&&(u.get(T.party).seats+=1)});let P=[...u.values()].map(R=>({...R,pct:s>0?R.firstPrefs/s*100:0})),A=P.reduce((R,T)=>R+v(T.stood),0),b=P.reduce((R,T)=>R+v(T.seats),0);return{rows:P,validPoll:s,totalPoll:i,electorate:o,spoiled:l,didNotVote:c,turnoutPct:o!==null&&i!==null&&o>0?i/o*100:null,validPct:o>0?s/o*100:0,spoiledPct:o!==null&&l!==null&&o>0?l/o*100:null,didNotVotePct:o!==null&&c!==null&&o>0?c/o*100:null,totalStood:A,totalElected:b}}findPreviousSelectedResult(t={}){let e=new Set(vt(t));return e.size&&(this.previousBundle?.results||[]).find(n=>vt(n).some(a=>e.has(a)))||null}renderSelectedPartySummaryRow(t,e,n,a,s,i,o){let l=s!=null,c=o!=null&&Number.isFinite(Number(o));return`-${$(t)}${e==null?"-":S(e)}${e==null?"-":Z(0)}${n==null?"-":S(n)}${n==null?"-":Z(0)}${a?S(a):"-"}${l?Z(s):"-"}${Number.isFinite(Number(i))?J(i):"-"}${c?Ae(o):"-"}`}renderMainParityLeafTh(t,e,n=""){let a=n||t;return`${$(t)}`}renderTwoLineHeader(t,e){return`${$(t)}${$(e)}`}renderElectionEntityButton(t,e,n,a=""){let s=$(t);return``}partyLabel(t){return ht(t,$)}partyCellAttrs(t,e=""){return` class="election-party-cell${e?` ${e}`:""}" style="--party-colour:${$(t||"transparent")}"`}colourTabStyle(t){return` style="--party-colour:${$(t||"transparent")}"`}isWestminsterElection(){return L(this.activeBundle?.body||this.activeEntry?.body||"")==="house of commons of the united kingdom"}electedMark(t){return t?'\u2713':'\u2715'}orderPartyRowsLikeMain(t=[]){return[...t].sort((e,n)=>{let a=v(n.seats)-v(e.seats);if(a)return a;let s=v(n.votes)-v(e.votes);return s||String(e.party||"").localeCompare(String(n.party||""),void 0,{numeric:!0,sensitivity:"base"})})}setupResultsTableControls(t){[...t?.querySelectorAll?.(".election-party-table, .election-count-table")||[]].forEach(n=>this.setupSingleResultsTableControls(n)),this.syncResultsTableStickyWidths(t),requestAnimationFrame(()=>this.syncResultsTableStickyWidths(t))}syncResultsTableStickyWidths(t){let e=[...t?.querySelectorAll?.(".election-party-table, .election-count-table")||[]];for(let n of e){let a=[...n.querySelectorAll("thead th, tbody td:nth-child(-n+4)")].filter(i=>{let o=getComputedStyle(i);return o.position==="sticky"&&o.left!=="auto"});if(!a.length)continue;a.forEach(i=>{i.style.position="static"});let s=a.map(i=>{let o=0;for(let l=i;l&&l!==n;l=l.offsetParent)o+=l.offsetLeft;return Math.max(0,Math.round(o))});a.forEach((i,o)=>{i.style.position="",i.style.left=`${s[o]}px`})}}setupSingleResultsTableControls(t){if(!t||t.dataset.tableControlsReady==="1")return;let e=t.querySelector("tbody"),n=[...t.querySelectorAll("thead th[data-leaf-col-idx]")],a=n.length?n:[...t.querySelectorAll("thead th")];if(!e||a.length===0)return;t.dataset.tableControlsReady="1";let s={col:null,dir:"default"},i=new Map,o=[...e.querySelectorAll("tr")].map((C,N)=>({row:C,idx:N})),l=o.filter(({row:C})=>!C.classList.contains("election-table-summary-row")&&!C.classList.contains("election-table-note-row")),c=o.filter(({row:C})=>!l.some(N=>N.row===C)),u=null,h=null,p=null,d=C=>{let N=String(C||"").replace(/,/g,"").replace(/%/g,"").replace(/[+\u2212]/g,j=>j==="\u2212"?"-":"+").trim();if(!N||N==="-"||N==="\uFFFD"||N.toLowerCase()==="n/a")return null;let k=Number(N);return Number.isFinite(k)?k:null},m=C=>{let N=String(C||"").trim().toLowerCase();if(!N)return null;let k=N.match(/^(\d+)(st|nd|rd|th)?$/);if(k)return Number(k[1]);let j=N.match(/count\s+(\d+)/);return j?Number(j[1]):null},x=(C,N)=>{let k=C.children[N];return k?k.textContent.trim():""},F=(C,N)=>{let k=Number(C?.dataset?.leafColIdx);return Number.isFinite(k)?k:N},P=(C,N)=>{let k=l.slice(0,40).map(({row:y})=>x(y,C)).filter(Boolean),j=k.filter(y=>d(y)!==null).length,D=k.filter(y=>m(y)!==null).length;return(N?.textContent||"").trim().toLowerCase().includes("rank")?"ordinal":k.length>0&&j/k.length>=.8?"numeric":k.length>0&&D/k.length>=.8?"ordinal":"text"},A=(C,N,k,j,D)=>{if(j==="default")return C.idx-N.idx;let f=x(C.row,k),y=x(N.row,k),g=0;if(D==="numeric"){let O=d(f),_=d(y);O!==null&&_!==null?g=O-_:O!==null?g=1:_!==null?g=-1:g=f.localeCompare(y,void 0,{numeric:!0,sensitivity:"base"})}else if(D==="ordinal"){let O=m(f),_=m(y);O!==null&&_!==null?g=O-_:g=f.localeCompare(y,void 0,{numeric:!0,sensitivity:"base"})}else g=f.localeCompare(y,void 0,{numeric:!0,sensitivity:"base"});return j==="asc"?g:-g},b=()=>{u&&u.remove(),h&&h.classList.remove("election-th-btn--open"),p&&(window.removeEventListener("resize",p),window.removeEventListener("scroll",p,!0)),u=null,h=null,p=null},R=(C,N,k)=>k{if(!C||!N)return;let k=8,j=4,D=Math.max(document.documentElement.clientWidth||0,window.innerWidth||0),f=Math.max(document.documentElement.clientHeight||0,window.innerHeight||0),y=document.querySelector(".app-header")?.getBoundingClientRect?.(),g=Math.max(k,Number.isFinite(y?.bottom)?Math.ceil(y.bottom)+k:k),O=Math.max(160,D-k*2),_=Math.max(96,f-g-k),G=Math.min(248,O),z=N.getBoundingClientRect();C.style.width=`${G}px`,C.style.maxWidth=`${O}px`,C.style.maxHeight=`${_}px`,C.style.overflow="hidden";let H=C.querySelector('[data-role="values"]');H&&(H.style.maxHeight="");let nt=C.getBoundingClientRect(),Q=Math.max(0,f-z.bottom-k-j),et=Math.max(0,z.top-g-j),ut=Math.min(nt.height||_,_)>Q&&et>Q,ce=Math.max(96,Math.min(_,(ut?et:Q)||_));if(C.style.maxHeight=`${ce}px`,H){let de=[...C.children],Oe=de.filter(Ht=>Ht!==H).reduce((Ht,je)=>Ht+je.getBoundingClientRect().height,0),Ge=Math.max(0,de.length-1)*6;H.style.maxHeight=`${Math.max(48,ce-Oe-Ge-2)}px`}let xt=C.getBoundingClientRect(),Fe=R(z.right-xt.width,k,D-xt.width-k),De=ut?z.top-xt.height-j:z.bottom+j,Ve=R(De,g,f-xt.height-k);C.style.left=`${Fe}px`,C.style.top=`${Ve}px`},V=C=>{let N=new Map;return l.forEach(({row:k})=>{let j=x(k,C);N.has(j)||N.set(j,j)}),[...N.values()].sort((k,j)=>k.localeCompare(j,void 0,{numeric:!0,sensitivity:"base"}))},E=()=>{let C=l.filter(({row:D})=>{for(let[f,y]of i.entries()){if(!(y instanceof Set)||y.size===0)continue;let g=x(D,f);if(!y.has(g))return!1}return!0}),N=s.col??F(a[0],0),k=a.find((D,f)=>F(D,f)===N)||a[0],j=P(N,k);C=[...C].sort((D,f)=>A(D,f,N,s.dir,j)),e.innerHTML="",C.forEach(({row:D})=>e.appendChild(D)),c.forEach(({row:D})=>e.appendChild(D)),requestAnimationFrame(()=>this.syncResultsTableStickyWidths(t.closest("#electionResultsPane")||t.parentElement)),a.forEach((D,f)=>{let y=D.querySelector("[data-table-filter-sort-indicator]");if(!y)return;let g=F(D,f),O=i.has(g)&&(i.get(g)?.size??0)>0,_=s.col===g&&s.dir!=="default";D.classList.toggle("election-th-btn--active",O||_),_&&s.dir==="asc"?y.innerHTML="↑":_&&s.dir==="desc"?y.innerHTML="↓":O?y.innerHTML="•":y.innerHTML="";let G=_?s.dir==="asc"?"sorted ascending":"sorted descending":O?"filtered":"";D.dataset.accessibleName||(D.dataset.accessibleName=D.getAttribute("aria-label")||D.querySelector(".election-th-label")?.textContent?.trim()||"column");let z=D.dataset.accessibleName;D.setAttribute("aria-label",`${z}${G?`, ${G}`:""}. Sort and filter`),D.tagName==="TH"&&!D.hasAttribute("scope")&&D.setAttribute("scope","col")})},w=(C,N)=>{b();let k=a[C],j=F(k,C),D=P(j,k),f=V(j),y=i.get(j),g=new Set(y instanceof Set?y:f),O=D==="numeric"?"Sort Smallest to Largest":D==="ordinal"?"Sort Lowest to Highest":"Sort A to Z",_=D==="numeric"?"Sort Largest to Smallest":D==="ordinal"?"Sort Highest to Lowest":"Sort Z to A",G=document.createElement("div");G.className="election-filter-menu",G.innerHTML=` + + + +
    + +
    + + +
    +
    + + `,document.body.appendChild(G),u=G,h=N,N.classList.add("election-th-btn--open");let z=G.querySelector('[data-role="values"]'),H=(Q="")=>{let et=Q.trim().toLowerCase();z.innerHTML="",f.filter(at=>!et||String(at).toLowerCase().includes(et)).forEach(at=>{let ut=document.createElement("label");ut.className="election-filter-menu__value",ut.innerHTML=`${$(at||"(Blank)")}`;let qt=ut.querySelector("input");qt.addEventListener("change",()=>{qt.checked?g.add(at):g.delete(at)}),z.appendChild(ut)})};H(),T(G,N),p=()=>T(G,N),window.addEventListener("resize",p),window.addEventListener("scroll",p,!0);let nt=G.querySelector(".election-filter-menu__search");nt?.addEventListener("input",()=>{H(nt.value||""),T(G,N)}),G.addEventListener("click",Q=>{let et=Q.target.closest("button[data-action]");if(!et)return;let at=et.dataset.action;at==="sort-asc"?(s.col=j,s.dir="asc",E(),b()):at==="sort-desc"?(s.col=j,s.dir="desc",E(),b()):at==="reset-sort"?(s.col=null,s.dir="default",E(),b()):at==="select-all"?(f.forEach(ut=>g.add(ut)),H(nt?.value||""),T(G,N)):at==="deselect-all"?(g.clear(),H(nt?.value||""),T(G,N)):at==="clear-filter"?(i.delete(j),E(),b()):at==="apply"&&(g.size===0||g.size===f.length?i.delete(j):i.set(j,new Set(g)),E(),b())})},B=C=>{u&&(u.contains(C.target)||h&&h.contains(C.target)||b())},M=C=>{C.key==="Escape"&&b()};document.addEventListener("click",B),document.addEventListener("keydown",M),a.forEach((C,N)=>{let k=C.innerHTML;C.innerHTML="";let j=document.createElement("div");j.className="election-th-controls",(C.classList.contains("election-col-compact")||C.classList.contains("election-col-int")||C.classList.contains("election-col-delta")||C.classList.contains("election-col-delta-small")||C.classList.contains("election-col-delta-votes")||C.classList.contains("election-col-pct")||C.classList.contains("election-col-pct-main")||C.classList.contains("election-col-pct-small")||C.classList.contains("election-col-pct-delta-main")||C.classList.contains("election-col-pct-delta-small")||C.classList.contains("election-col-count")||C.classList.contains("election-col-status-count")||C.classList.contains("election-col-votes"))&&j.classList.add("election-th-controls--compact");let D=document.createElement("span");if(D.className="election-th-label",D.innerHTML=k,j.appendChild(D),!C.classList.contains("election-colour-col")){let f=document.createElement("span");f.className="election-th-indicator",f.setAttribute("data-table-filter-sort-indicator","1"),f.setAttribute("aria-hidden","true"),j.appendChild(f),C.classList.add("election-th--menu"),C.setAttribute("tabindex","0"),C.setAttribute("aria-haspopup","dialog"),C.setAttribute("title","Sort and filter");let y=()=>{u&&h===C?b():w(N,C)};C.addEventListener("click",g=>{g.target.closest("a, button, input, select, label")||(g.preventDefault(),g.stopPropagation(),y())}),C.addEventListener("keydown",g=>{g.key!=="Enter"&&g.key!==" "||(g.preventDefault(),y())})}C.appendChild(j)}),t.addEventListener("test2:dispose-table-controls",()=>{b(),document.removeEventListener("click",B),document.removeEventListener("keydown",M)},{once:!0}),E()}renderMainParitySummaryRow(t,e,n,a,s,i,o,l,c){return`-${$(t)}${e==null?"-":S(e)}-${n==null?"-":S(n)}-${a||"-"}${s==null?"-":rt(s)}${i?S(i):"-"}${o==null?"-":Z(o)}${Number.isFinite(Number(l))?J(l):"-"}${c==null?"-":rt(c)}`}renderMapDisplayControls(){let t=this.activeGeographyMode(),e=t?.stylingModes||this.activeEntry?.stylingModes||[],n=this.geographyModes(),a=n.length>1?` + + `:"",s=this.shouldRenderElectionOverlays()?` + + `:"";return!e.length&&!s&&!a?"":` +
    + Map display +
    + ${a} + ${e.length?``:""} + ${s} +
    +
    + `}renderTurnoutGeographyPanel(){let t=this.activeGeographyMode(),e=[...this.currentResults()].sort((i,o)=>(Number(o.turnoutPct)||0)-(Number(i.turnoutPct)||0)),n=Number(t?.overallTurnoutPct),a=t?.sourceUrl?` Source (ARK).`:"",s=e.map(i=>` + + ${$(i.constituency||i.featureName||"")} + ${Number.isFinite(Number(i.turnoutPct))?st(Number(i.turnoutPct)):"-"} + `).join("");return` +
    +

    ${$(t?.note||"")}${a}

    +
    +
    + ${Number.isFinite(n)?`
    Overall turnout
    ${st(n)}
    `:""} +
    Constituencies
    ${S(e.length)}
    +
    +
    +
    + + + ${s} +
    ConstituencyTurnout
    + ${this.renderMapDisplayControls()} +
    + `}renderTurnoutConstituencyDetail(t){let e=Number(t?.turnoutPct),n=this.activeGeographyMode();return` +
    +
    +
    ${$(t?.constituency||t?.featureName||"Constituency")}
    ${Number.isFinite(e)?`${st(e)} turnout`:"Turnout not available"}
    +
    +

    ${$(n?.note||"")}

    +
    + `}formatPaneElectionTitle(){let t=Ot(this.activeBundle?.body||this.activeEntry?.body||""),e=ie(this.activeBundle?.date||this.activeEntry?.date||"");return[t,e].filter(Boolean).join(" - ")||this.activeBundle?.displayTitle||this.activeBundle?.body||""}isLocalGovernmentElection(){return(this.activeBundle?.bodyGroup||this.activeEntry?.bodyGroup)==="local-government"}geographyModes(){let t=this.activeBundle?.geographyModes;return Array.isArray(t)&&t.length>1?t:[]}defaultGeographyModeId(){let t=this.geographyModes();return t.length?t[0].id:null}activeGeographyMode(){let t=this.geographyModes();return t.length?t.find(e=>e.id===this.activeGeographyModeId)||t[0]:null}isTurnoutGeographyMode(){return this.activeGeographyMode()?.dataKind==="turnout"}async switchGeographyMode(t){let e=this.geographyModes(),n=e.find(i=>i.id===t)||e[0];if(!n)return;let a=this.getActiveElectionStyleSourceMapId();this.activeGeographyModeId=n.id;let s=n.stylingModes||[];this.activeMode=s.includes(this.activeMode)?this.activeMode:n.defaultMode||s[0]||"winner",this.activeSelectedResultKey=null,a&&a!==n.sourceMapId&&this.mapController.clearElectionStyle?.(a),await this.syncGeographyBackingLayers(),this.applyActiveStyle(),this.renderPanel(null,"party"),this.renderElectionOverlay().catch(i=>console.warn("[test2 elections] Overlay refresh failed",i)),this.app.updateURLState()}async syncGeographyBackingLayers(){let t=this.geographyModes();if(!t.length)return;let e=this.activeGeographyMode();for(let n of t)n.sourceMapId&&(n.id===e?.id?(this.mapController.isLayerLoaded?.(n.sourceMapId)||await this.mapController.loadLayer(n.sourceMapId,{fit:!1}),this.mapController.showLayer?.(n.sourceMapId)):this.mapController.isLayerLoaded?.(n.sourceMapId)&&(this.mapController.clearElectionStyle?.(n.sourceMapId),this.mapController.hideLayer?.(n.sourceMapId)))}localBodyCount(){return Number(this.activeBundle?.localBodies?.length||this.activeEntry?.localBodies?.length||0)}isForumResult(t=null){return!!(t?.forum||t?.forumSequence||t?.allocationRounds)}resultHasAnimation(t=null){if(!t)return!1;if(this.isForumResult(t))return!0;let e=t.animationPayload?.Constituency?.countGroup||[],n=t.animationPayload?e.length:t.animationRowCount||0,a=t.animationPayload?e.some(s=>Number(s.Count_Number)>1):!!t.animationHasMultipleCounts;return t.syntheticCountGroup&&n||a||Array.isArray(t.countNumbers)&&t.countNumbers.some(s=>Number(s)>1)?!0:!!(t.hasCountDetail&&(t.candidates||[]).some(s=>(s.counts||[]).some(i=>Number(i.count)>1)))}currentResults(){let t=this.activeGeographyMode();if(t&&t.dataKind==="turnout")return t.results||[];let e=this.activeBundle?.results||[],n=this.previousBundle?.results||[];return n.length?Rt(e,n):e}renderTrendsPanel(t=null){let e=t?.constituency||t?.localBody||"",n=e?`Party vote share in ${e}`:"Party vote share",a=oe(this.activeEntry||this.activeBundle||{}),s=re(this.activeEntry||this.activeBundle||{}),i=a||"comparable elections",o=s==="Republic of Ireland"?"the Republic of Ireland":s,l=o&&!i.toLowerCase().includes(String(s).toLowerCase())?` in ${o}`:"",c=`Share of the vote at ${i}${l}.`;return` + + `}async hydrateTrendsPanel(t=null,e=!1){let n=document.getElementById("test2ElectionTrendsChart");if(!n||!this.activeEntry)return;let a=new Set(t?vt(t):[]),s=L(t?.localBody||t?.council||""),i=oe(this.activeEntry),o=re(this.activeEntry),l=a.size?[...a].sort().join("|"):s||"overall",c=[this.activeEntry.key||`${this.activeEntry.body}|${this.activeEntry.date}`,e?"all":i,o||"anywhere",l].join("::");if(this.trendRenderCache.has(c)){let d=this.trendRenderCache.get(c);this.renderTrendChart(n,d.points,t,e,d.comparableCount);return}n.dataset.trendRequestKey=c,n.setAttribute("aria-busy","true"),n.innerHTML='';let u=(this.catalogue?.elections||[]).filter(d=>(d?.loadable||d?.resultsOnly)&&d.resultUrl&&L(d.contestType||"election")==="election").filter(d=>{let m=re(d);return o&&m&&m!==o||e&&o&&!m||!e&&d.isByElection?!1:e||oe(d)===i}).sort((d,m)=>String(d.date||"").localeCompare(String(m.date||""))),h=[],p=await wn(u.slice(-80),6,async d=>{try{return await this.loadTrendSummary(d)}catch{return null}});for(let d of p){if(!d)continue;let m=d.overallRows||[];if(a.size){m=[];for(let x of a)if(d.resultRowsByKey.has(x)){m=d.resultRowsByKey.get(x);break}!m.length&&s&&d.localRowsByKey.has(s)&&(m=d.localRowsByKey.get(s))}else s&&d.localRowsByKey.has(s)&&(m=d.localRowsByKey.get(s));for(let x of m)h.push(x)}Dt(this.trendRenderCache,c,{points:h,comparableCount:u.length},vn),n.dataset.trendRequestKey===c&&this.renderTrendChart(n,h,t,e,u.length)}renderTrendChart(t,e=[],n=null,a=!1,s=0){if(this.trendChart?.destroy(),this.trendChart=null,t.removeAttribute("aria-busy"),!e.length){t.innerHTML='

    No trend data is available for this selection.

    ';return}let i=ge(e,{abbreviate:d=>ue(d),bodyLabel:d=>Ot(d.body||d.displayProvider||d.displayTitle||"")}),o=n&&(n.constituency||n.featureName)||"",l=[];l.push(a?"All election types available for this geography. A line is dotted across elections where the party has no comparable result.":"Current election family only; by-elections are excluded. A line is dotted across elections where the party has no comparable result."),i.totalSeries>i.series.length&&l.push(`The ${i.series.length} largest parties at the most recent election are shown; ${i.totalSeries-i.series.length} others are not drawn.`),o&&s>i.elections.length+1&&l.push(`Showing ${i.elections.length} of ${s} comparable elections. ${o} appears under this name in those elections only; constituencies are renamed and redrawn, and a predecessor under a different name is not yet linked to it.`);let c=``,u=n?.constituency||n?.localBody||"overall results",h=t.closest(".election-pane__content"),p=d=>{let x=h?h.clientHeight-150:0,F=d<560?216:d>=900?320:256;return Math.max(200,Math.min(F,x||F))};this.trendChart=Pe(t,i,{ariaLabel:`Party vote share over time for ${u}`,formatDate:ie,footnotes:c,height:p,fitTo:h})}formatNumberForPane(t){return S(t)}formatPercentForPane(t){return st(t)}formatSignedPercentForPane(t){return Re(t)}withPartyDeltas(t=[],e={}){let n=Array.isArray(e.previousRows)?e.previousRows:Array.isArray(e.previousResults)?tt(e.previousResults):e.mainLike&&this.previousBundle?.mainLikePartySummary?.length?this.previousBundle.mainLikePartySummary:this.previousBundle?.results?.length?tt(this.previousBundle.results):[],a=new Map(n.map(i=>[L(i.party),i])),s=n.length>0;return t.map(i=>{let o=a.get(L(i.party))||(s?{stood:0,seats:0,votes:0,share:0}:null);return{...i,previous:o,deltas:o?{stood:v(i.stood)-v(o.stood),seats:v(i.seats)-v(o.seats),votes:v(i.votes)-v(o.votes),share:i.share!==null&&o.share!==null?i.share-o.share:null}:null}})}candidateDeltasEligible(t={}){let e=L(t?.contestType||this.activeBundle?.contestType||this.activeEntry?.contestType||"election");if(e&&e!=="election")return!1;let n=L([t?.body,t?.title,t?.type,t?.contestType,t?.votingSystem,this.activeBundle?.body,this.activeBundle?.type,this.activeBundle?.votingSystem,this.activeEntry?.body,this.activeEntry?.displayTitle,this.activeEntry?.key,this.activeEntry?.votingSystem].filter(Boolean).join(" "));return!(/referendum|recall petition/.test(n)||/northern ireland forum|regional list|party list dhondt|party-list-dhondt|ordinal/.test(n))}candidateDeltaAreaKey(t={},e={}){return L(t.constituency||t.area||t.dea||t.district||t.localBody||e?.constituency||e?.matchName||e?.name||"")}candidateDeltaLookupKey(t={},e={}){let n=L(t.name||t.candidateName||t.candidate||t.Candidate_Name||t.Candidate||""),a=this.candidateDeltaAreaKey(t,e);return[n,a].filter(Boolean).join("|")}candidateFirstPrefValue(t={}){return v(t.firstPrefs??t.votes??t.finalVotes??t.total??t.Total_Votes)}candidateFirstPrefPct(t={},e={}){let n=t.firstPrefPct??t.votePct??t.constPct??t.share;if(Number.isFinite(Number(n)))return Number(n);let a=v(e?.validPoll);return a?this.candidateFirstPrefValue(t)/a*100:null}buildCandidateDelta(t={},e=null,n={},a={}){if(!e)return{previous:null,deltas:null};let s=this.candidateFirstPrefPct(t,n),i=this.candidateFirstPrefPct(e,a);return{previous:e,deltas:{firstPrefs:this.candidateFirstPrefValue(t)-this.candidateFirstPrefValue(e),firstPrefPct:s!==null&&i!==null?s-i:null}}}candidateDeltaForResultCandidate(t={},e={}){if(!this.candidateDeltasEligible(e))return{previous:null,deltas:null};let n=this.findPreviousSelectedResult(e);if(!n)return{previous:null,deltas:null};let a={...t,constituency:t.constituency||t.area||e?.constituency||e?.matchName||e?.name||""},s=this.candidateDeltaLookupKey(a,e);if(!s)return{previous:null,deltas:null};let i=t.previous&&this.candidateDeltaLookupKey(t.previous,n)===s?t.previous:null,o=Array.isArray(n.candidates)?n.candidates:[],l=i||o.find(c=>this.candidateDeltaLookupKey(c,n)===s)||null;return this.buildCandidateDelta(a,l,e,n)}withCandidateDeltas(t=[],e={}){if(!this.candidateDeltasEligible(e.result||{}))return t.map(i=>({...i,previous:i.previous||null,deltas:null}));let n=new Map((Array.isArray(e.previousResults)?e.previousResults:[]).map(i=>[this.candidateDeltaAreaKey({},i),i]).filter(([i])=>i)),a=Array.isArray(e.previousRows)?e.previousRows:Array.isArray(e.previousResults)?lt(e.previousResults):e.mainLike&&this.previousBundle?.mainLikeCandidateSummary?.length?this.previousBundle.mainLikeCandidateSummary:this.previousBundle?.results?.length?lt(this.previousBundle.results):[],s=new Map(a.map(i=>[this.candidateDeltaLookupKey(i),i]).filter(([i])=>i));return t.map(i=>{let o=this.candidateDeltaLookupKey(i),c=(i.previous&&this.candidateDeltaLookupKey(i.previous)===o?i.previous:null)||s.get(o)||null,u=c?n.get(this.candidateDeltaAreaKey(c))||{}:{},h=this.buildCandidateDelta(i,c,e.result||{},u);return{...i,previous:h.previous,deltas:h.deltas}})}withCouncilDeltas(t=[]){let e=this.previousBundle?.results?.length?Et(this.previousBundle.results):[],n=new Map(e.map(a=>[L(a.council),a]));return t.map(a=>{let s=n.get(L(a.council));return{...a,previous:s,deltas:s?{seats:v(a.seats)-v(s.seats),validPoll:v(a.validPoll)-v(s.validPoll),turnoutPct:a.turnoutPct!==null&&s.turnoutPct!==null?a.turnoutPct-s.turnoutPct:null}:null}})}withLocalPartyDeltas(t=[],e={}){let n=Array.isArray(e.previousResults)?Ft(e.previousResults):this.previousBundle?.results?.length?Ft(this.previousBundle.results):[],a=new Map(n.map(i=>[`${L(i.party)}|${L(i.constituency)}`,i])),s=n.length>0;return t.map(i=>{let o=a.get(`${L(i.party)}|${L(i.constituency)}`)||(s?{stood:0,seats:0,seatShare:0,firstPrefs:0,share:0}:null);return{...i,previous:o,deltas:o?{stood:v(i.stood)-v(o.stood),seats:v(i.seats)-v(o.seats),seatShare:i.seatShare!==null&&o.seatShare!==null?i.seatShare-o.seatShare:null,firstPrefs:v(i.firstPrefs)-v(o.firstPrefs),share:i.share!==null&&o.share!==null?i.share-o.share:null}:null}})}renderDistrictResults(t="party"){let e=this.currentResults(),n=this.withPartyDeltas(tt(e)),a=this.withCandidateDeltas(lt(e)),s=this.withCouncilDeltas(Et(e)),i=n.reduce((h,p)=>h+v(p.seats),0),o=U(e,"validPoll"),l=U(e,"totalPoll"),c=U(e,"electorate"),u=U(e,"spoiled");return` +
    + ${this.renderViewTabs([["party","By Party"],["candidate","By Candidate"],["local-party","By Local Party"],["constituency","By DEA"]],t)} +
    +
    +
    District
    ${$(this.activeBundle.displayTitle||this.activeBundle.body)}
    + ${this.localBodyCount()>1?`
    Councils
    ${S(s.length)}
    `:""} +
    DEAs
    ${S(e.length)}
    + ${i?`
    Seats
    ${S(i)}
    `:""} + ${o?`
    Valid poll
    ${S(o)}
    `:""} + ${l?`
    Total poll
    ${S(l)}
    `:""} + ${u?`
    Spoiled
    ${S(u)}
    `:""} + ${c?`
    Electorate
    ${S(c)}
    `:""} + ${c&&l?`
    Turnout
    ${st(l/c*100)}
    `:""} +
    +
    +
    + ${this.renderDataCoverageNotice()} + ${t==="candidate"?this.renderCandidateSummaryTable(a):t==="local-party"?this.renderLocalPartySummaryTable(e):this.renderMainParityPartyTable(n,e)} +
    + `}isCouncilAggregateResult(t=null){return!t||!this.isLocalGovernmentElection()?!1:t.aggregateType==="council"||t.aggregateType==="district"}buildCouncilAggregateResult(t,e=null){let n=L(t);if(!n)return null;let a=this.currentResults().filter(c=>L(c.localBody||"")===n);if(!a.length)return null;let s=e||this.withCouncilDeltas(Et(this.currentResults())).find(c=>L(c.council)===n),i=tt(a),o=s?.leadingParty||i[0]?.party||"",l=this.mainPanePartyColour(o,s?.colour||i[0]?.colour||"");return{aggregateType:this.localBodyCount()>1?"council":"district",constituency:t,matchName:t,featureName:t,featureAliases:xe(t),localBody:t,matched:!0,memberResults:a,winnerParty:o,leadingParty:o,winnerName:o,leadingName:o,leadingColour:l,colour:l,leadingPct:s?.share??i[0]?.share??null,seatsWon:s?.seats??i.reduce((c,u)=>c+v(u.seats),0),seatsTotal:s?.seats??a.reduce((c,u)=>c+v(u.seatsTotal??u.seatsWon),0),validPoll:s?.validPoll??U(a,"validPoll"),totalPoll:U(a,"totalPoll"),electorate:s?.electorate??U(a,"electorate"),spoiled:U(a,"spoiled"),turnoutPct:s?.turnoutPct??_n(a,"turnoutPct"),deas:s?.deas??a.length,previous:s?.previous||null,deltas:s?.deltas||null}}buildCouncilAggregateResults(){return this.withCouncilDeltas(Et(this.currentResults())).map(t=>this.buildCouncilAggregateResult(t.council,t)).filter(Boolean)}findCouncilAggregateResultByName(t){let e=L(t);return e&&this.buildCouncilAggregateResults().find(n=>vt(n).includes(e))||null}previousResultsForCouncil(t){let e=L(t);return e?(this.previousBundle?.results||[]).filter(n=>L(n.localBody||"")===e):[]}renderCouncilAggregateResults(t,e="party"){let n=Array.isArray(t?.memberResults)?t.memberResults:[];if(!n.length)return'

    No council-level result data is available for this entry.

    ';let a=this.previousResultsForCouncil(t.constituency||t.localBody||t.matchName),s=this.withPartyDeltas(tt(n),{previousResults:a}),i=this.withCandidateDeltas(lt(n),{previousResults:a}),o=["party","candidate","local-party"].includes(e)?e:"party";return` + ${o==="candidate"?this.renderCandidateSummaryTable(i,{results:n,previousResults:a,widePercentLabel:"% of District"}):o==="local-party"?this.renderLocalPartySummaryTable(n,{previousResults:a,areaLabel:"DEA",districtPercentLabel:"% of District"}):this.renderMainParityPartyTable(s,n,{ignoreMainLikeTotals:!0,previousResults:a,constituencyCount:n.length,totalLabel:"Valid votes"})} + `}renderCouncilResults(t="party"){let e=this.currentResults(),n=this.withCouncilDeltas(Et(e)),a=this.withPartyDeltas(tt(e)),s=lt(e),i=Ft(e),o=a.reduce((u,h)=>u+v(h.seats),0),l=U(e,"validPoll"),c=U(e,"electorate");return` +
    + ${this.renderViewTabs([["party","By Party"],["council","By Council"],["candidate","By Candidate"],["local-party","By Local Party"],["constituency","By DEA"]],t)} +
    +
    +
    Councils
    ${S(n.length)}
    +
    DEAs
    ${S(e.length)}
    + ${o?`
    Seats
    ${S(o)}
    `:""} + ${l?`
    Valid poll
    ${S(l)}
    `:""} + ${c?`
    Electorate
    ${S(c)}
    `:""} +
    +
    +
    + ${this.renderDataCoverageNotice()} + ${t==="council"?this.renderCouncilSummaryTable(n):t==="candidate"?this.renderCandidateSummaryTable(s):t==="local-party"?this.renderLocalPartySummaryTable(e):t==="constituency"?this.renderConstituencySummaryTable(e):this.renderDistrictPartyTable(a)} +
    + `}renderCouncilSummaryTable(t=[]){return` +
    + + + + + + + + + + + + + ${this.renderMainParityLeafTh("No.",4,"Seats")} + ${this.renderMainParityLeafTh("+/-",5,"Seats change")} + ${this.renderMainParityLeafTh("No.",6,"Valid votes")} + ${this.renderMainParityLeafTh("+/-",7,"Valid votes change")} + ${this.renderMainParityLeafTh("%",8,"Turnout percentage")} + ${this.renderMainParityLeafTh("+/-",9,"Turnout change")} + + + + ${t.map((e,n)=>` + + + + + ${this.renderElectionEntityButton("party",e.leadingParty,this.partyLabel(e.leadingParty||""),"election-cell-wrap")} + + + + + + + + `).join("")} + +
    #CouncilDEAsLeading partySeatsValid votesTurnout
    ${$(pt(n))}${S(e.deas)}${S(e.seats)}${e.deltas?Z(e.deltas.seats):""}${S(e.validPoll)}${e.deltas?Z(e.deltas.validPoll):""}${st(e.turnoutPct)}${e.deltas?.turnoutPct!==null&&e.deltas?.turnoutPct!==void 0?rt(e.deltas.turnoutPct):""}
    +
    + `}renderDistrictPartyTable(t=[]){return` +
    + + + + ${t.map(e=>` + + + + + + + + + + `).join("")} + +
    PartyCandidatesSeatsSeat changeFirst prefsVote shareVote change
    ${S(e.stood)}${S(e.seats)}${e.deltas?Vt(e.deltas.seats):""}${S(e.votes)}${st(e.share)}${e.deltas?`${Vt(e.deltas.votes)}${e.deltas.share!==null?` (${Re(e.deltas.share)})`:""}`:""}
    +
    + `}renderRecallPetitionOverview(t=[]){return this.sharedRenderer.renderRecallPetitionOverview(t)}renderViewTabs(t,e){return this.sharedRenderer.renderViewTabs(t,e)}renderCandidateSummaryTable(t,e={}){if(!t.length)return'

    No candidate summary is available for this election.

    ';let n=this.isLocalGovernmentElection(),a=!n&&this.isWestminsterElection(),s=e.widePercentLabel||this.getElectionWidePercentLabel(),i=Array.isArray(e.results)?e.results:this.currentResults(),o=Array.isArray(e.previousResults)?e.previousResults:this.previousBundle?.results||[],l=U(i,"validPoll")||t.reduce((d,m)=>d+v(m.firstPrefs??m.votes),0),c=U(o,"validPoll")||(this.previousBundle?.mainLikeCandidateSummary||[]).reduce((d,m)=>d+v(m.firstPrefs??m.votes),0),u=[...t].sort((d,m)=>{let x=v(m.firstPrefPct)-v(d.firstPrefPct);return Math.abs(x)>1e-9?x:v(m.firstPrefs??m.votes)-v(d.firstPrefs??d.votes)||String(d.name||"").localeCompare(String(m.name||""),void 0,{numeric:!0,sensitivity:"base"})}),h=n?'Geography':'Constituency',p=n?7:a?5:6;return` +
    + + + + + + + ${h} + ${a?'':''} + + + + + ${n?'':""} + ${a?"":` + `} + + + + + + ${this.renderMainParityLeafTh("No.",p)} + ${this.renderMainParityLeafTh("+/-",p+1)} + ${this.renderMainParityLeafTh("%",p+2)} + ${this.renderMainParityLeafTh("+/-",p+3)} + ${this.renderMainParityLeafTh("%",p+4)} + ${this.renderMainParityLeafTh("+/-",p+5)} + + + + ${u.map((d,m)=>{let x=v(d.firstPrefs??d.votes),F=l>0?x/l*100:0,P=d.previous?v(d.previous.firstPrefs??d.previous.votes):null,A=d.previous&&c>0?P/c*100:null,b=d.deltas&&A!==null?F-A:null,R=d.elected?"Elected":d.excluded?"Excluded":d.status||"Not Elected",T=d.countDisplay||(d.electedAt||d.excludedAt||d.finalCount?`${d.electedAt||d.excludedAt||d.finalCount}/${d.countNumbers?.length||d.counts?.length||""}`.replace(/\/$/,""):""),V=d.localBody||d.council||d.district||"";return` + + + + ${this.renderElectionEntityButton("party",d.party,this.partyLabel(d.party),"election-cell-wrap")} + ${n?``:""} + + ${a?``:` + `} + + + + + + + + `}).join("")} + +
    #NamePartyElectedStatus1st preferences${$(s)}
    DistrictDEAOutcomeCountNo.%%
    ${$(pt(m))}${this.renderElectionEntityButton("candidate",`${d.name||d.id||""}|${d.party||""}`,$(d.name||""),"election-cell-wrap")}${$(V)}${this.electedMark(d.elected)}${R==="Elected"?"Elected":$(R)}${$(T)}${S(x)}${d.deltas?Z(d.deltas.firstPrefs):ct()}${J(d.firstPrefPct)}${d.deltas?.firstPrefPct!==null&&d.deltas?.firstPrefPct!==void 0?rt(d.deltas.firstPrefPct):ct()}${J(F)}${b!=null?rt(b):ct()}
    +
    + `}renderConstituencySummaryTable(t){return this.sharedRenderer.renderConstituencySummaryTable(t)}renderLocalPartySummaryTable(t,e={}){let n=this.withLocalPartyDeltas(Ft(t),e);if(!n.length)return'

    No local-party summary is available for this election.

    ';let a=e.areaLabel||(this.isLocalGovernmentElection()?"DEA":"Constituency"),s=this.isWestminsterElection()&&t.length>0&&t.every(o=>v(o.seatsTotal??o.seatsWon??1)<=1),i=s?8:10;return` +
    + + + + + + + + + + + + ${this.renderMainParityLeafTh("No.",4,"Candidates")} + ${this.renderMainParityLeafTh("+/-",5,"Candidates change")} + ${this.renderMainParityLeafTh("No.",6,"Seats")} + ${this.renderMainParityLeafTh("+/-",7,"Seats change")} + ${s?"":`${this.renderMainParityLeafTh("%",8,"Seats percentage")} + ${this.renderMainParityLeafTh("+/-",9,"Seats percentage change")}`} + ${this.renderMainParityLeafTh("No.",i,"First preference votes")} + ${this.renderMainParityLeafTh("+/-",i+1,"First preference votes change")} + ${this.renderMainParityLeafTh("%",i+2,"First preference vote share")} + ${this.renderMainParityLeafTh("+/-",i+3,"First preference vote share change")} + + + + ${n.map((o,l)=>` + + + + + + + + + + ${s?"":` + `} + + + + + + `).join("")} + +
    #Party${$(a)}CandidatesSeats1st preferences
    ${$(pt(l))}${this.renderElectionEntityButton("party",o.party,this.partyLabel(o.party),"election-cell-wrap")}${S(o.stood)}${o.deltas?Z(o.deltas.stood):""}${S(o.seats)}${o.deltas?Z(o.deltas.seats):""}${st(o.seatShare)}${o.deltas?.seatShare!==null&&o.deltas?.seatShare!==void 0?rt(o.deltas.seatShare):""}${S(o.firstPrefs)}${o.deltas?Z(o.deltas.firstPrefs):""}${st(o.share)}${o.deltas?.share!==null&&o.deltas?.share!==void 0?rt(o.deltas.share):""}
    +
    + `}renderDataCoverageNotice(){return this.sharedRenderer.renderDataCoverageNotice()}renderCountTable(t,e){let a=t.countNumbers?.length?t.countNumbers:[...new Set(e.flatMap(E=>(E.counts||[]).map(w=>w.count)))].sort((E,w)=>E-w);if(!a.length)return'

    No count-by-count data is available for this entry.

    ';let s=In(t),i=s?Gn(t,e,a):On(e,a),o=s?Fn(t,e,a):{nonTransferable:new Map((t.nonTransferable||[]).map(E=>[Number(E.count),E])),transferDenominators:new Map},l=o.nonTransferable,c=o.transferDenominators,u=a.filter(E=>{let w=Number(E);return w<=1?!1:i.some(M=>Number(M.count)===w)||e.some(M=>{let C=(M.counts||[]).find(N=>Number(N.count)===w);return Math.abs(Number(C?.transfers)||0)>1e-4})?!0:Math.abs(Number(l.get(w)?.transfers)||0)>1e-4}),h=u.length+1,p=E=>{let w=Number(E)||1;return w<=1?1:1+u.filter(B=>Number(B)<=w).length},d=[...e].sort((E,w)=>{if(!t.syntheticCountGroup){let B=+!!w.elected-+!!E.elected;if(B)return B;let M=Number(E.electedAt||E.finalCount||999),C=Number(w.electedAt||w.finalCount||999);if(E.elected&&w.elected&&M!==C)return M-C}return v(w.finalVotes??w.firstPrefs??w.votes)-v(E.finalVotes??E.firstPrefs??E.votes)||String(E.name||"").localeCompare(String(w.name||""),void 0,{numeric:!0,sensitivity:"base"})}),m=v(t.validPoll),x=v(t.totalPoll),F=v(t.electorate),P=v(t.spoiled),A=Math.max(0,F-x),b=t.previous||{},R=E=>x>0?E/x*100:0,T=E=>F>0?E/F*100:0,V=(E,w,B,M,C)=>` + + - + + ${$(E)} + - + - + ${Number.isFinite(Number(B))?Z(w-B):ct()} + ${J(M)} + ${this.countDetailedView?`${Number.isFinite(Number(C))?rt(M-C):ct()}`:""} + ${S(w)} + ${u.map(()=>this.countDetailedView?'----':'-').join("")} + + `;return` +
    + + + + + + + + + + + ${this.countDetailedView?``:""} + + ${u.map((E,w)=>{let B=i.find(C=>Number(C.count)===Number(E)),M=this.countDetailedView?9+w*4:8+w;return` + + ${this.countDetailedView?``:""} + `}).join("")} + + + + ${d.map((E,w)=>{let B=new Map((E.counts||[]).map(y=>[Number(y.count),y])),M=s?Dn(E,B,t,a):null,C=t.syntheticCountGroup?B.get(1):null,N=this.candidateDeltaForResultCandidate(E,t),k=t.syntheticCountGroup?v(C?.firstPrefs??C?.total):v(E.firstPrefs??E.votes),j=m>0?k/m*100:0,D=E.electedAt||E.excludedAt||E.finalCount||a[a.length-1],f=E.elected?`Elected
    Stage ${p(E.electedAt||E.finalCount||a[a.length-1])}/${h}`:E.excluded?`Excluded
    Stage ${p(E.excludedAt||E.finalCount||a[a.length-1])}/${h}`:`Not Elected
    Stage ${p(D)}/${h}`;return` + + + + + + + + + ${this.countDetailedView?``:""} + + ${u.map(y=>{let g=B.get(Number(y)),O=s?Wt(E,y,B,t,a,g):g;if(Vn(y,M))return this.countDetailedView?'':'';if(!O)return this.countDetailedView?'':'';let _=O.total??O.firstPrefs,G=Number(O.transfers),z=m>0?Number(_)/m*100:0,H=c.get(Number(y));return this.countDetailedView?``:``}).join("")} + + `}).join("")} + ${s||l.size?` + + + + + + + + + ${this.countDetailedView?'':""} + + ${u.map(E=>{let w=l.get(Number(E))||(s?{total:0,transfers:0}:null);if(!w)return this.countDetailedView?'':'';let B=c.get(Number(E));return this.countDetailedView?``:``}).join("")} + + `:""} + ${V("Valid votes",m,v(b.validPoll),R(m),R(v(b.validPoll)))} + ${V("Spoiled",P,v(b.spoiled),R(P),R(v(b.spoiled)))} + ${V("Turnout",x,v(b.totalPoll),T(x),T(v(b.totalPoll)))} + ${V("Did not vote",A,Math.max(0,v(b.electorate)-v(b.totalPoll)),T(A),T(Math.max(0,v(b.electorate)-v(b.totalPoll))))} + ${V("Electorate",F,v(b.electorate),100,100)} + +
    #NamePartyStatus${this.renderTwoLineHeader("1st","pref +/-")}${this.renderTwoLineHeader("1st","pref %")}${this.renderTwoLineHeader("1st","pref +/- %")}${this.renderTwoLineHeader("1st","pref")}${this.renderTwoLineHeader(this.countDetailedView?`Stage ${S(E)}`:"Stage",this.countDetailedView&&B?B.label:S(p(E)))}${this.renderTwoLineHeader(`Stage ${S(E)}`,"%")}${this.renderTwoLineHeader(`Stage ${S(E)}`,"+/- %")}${this.renderTwoLineHeader(`Stage ${S(E)}`,"+/-")}
    ${$(pt(w))}${this.renderElectionEntityButton("candidate",`${E.name||E.id||""}|${E.party||""}`,$(E.name||""),"election-cell-wrap election-cell-wrap--count-name")}${this.renderElectionEntityButton("party",E.party,this.partyLabel(E.party||""),"election-cell-wrap election-cell-wrap--count-party")}${f}${!t.syntheticCountGroup&&N.deltas?Z(N.deltas.firstPrefs):ct()}${J(j)}${!t.syntheticCountGroup&&N.deltas?.firstPrefPct!==null&&N.deltas?.firstPrefPct!==void 0?rt(N.deltas.firstPrefPct):ct()}${S(k)}----- --- ${S(_)}${J(z)}${Be(G,H)}${G?Z(G):"-"}${S(_)}
    -Non-
    transferable
    ------ --- ${S(w.total)}${m>0?J(Number(w.total)/m*100):"-"}${Be(w.transfers,B)}${w.transfers?Z(w.transfers):"-"}${S(w.total)}
    +
    + `}renderRecallPetitionResult(t){return this.sharedRenderer.renderRecallPetitionResult(t)}renderAnimationNotice(t){return this.resultHasAnimation(t)&&(t.animationPayload||t.animationRowCount)?` +
    +
    Loading transfer animation...
    + +
    + `:this.sharedRenderer.renderAnimationNotice(t)}async ensureAnimationPayload(t,e=this.activeBundle){if(!t||t.animationPayload)return t?.animationPayload||null;if(!Lt())return null;let n=e?.key,a=(e?.results||[]).indexOf(t);if(!n||a<0)return null;try{let s=await fetch(`/_api/elections?key=${encodeURIComponent(n)}&constituency=${a}`,{cache:"force-cache"});if(!s.ok)return ne("elections-api-animation-failed",`constituency fetch returned ${s.status}`,`${n}#${a}`),null;let i=await s.json();return i?.animationPayload&&(t.animationPayload=i.animationPayload,Array.isArray(t.countGroup)||(t.countGroup=i.animationPayload?.Constituency?.countGroup||[])),t.animationPayload||null}catch(s){return console.warn("[test2 elections] Could not load animation payload:",s),ne("elections-api-animation-failed",s&&s.message?s.message:String(s),n),null}}async hydrateSelectedResult(t){if(!t||!Lt())return;this.countDetailRequested||(this.countDetailRequested=new WeakSet);let e=[],n=(s,i)=>{!s||Array.isArray(s.countGroup)||this.countDetailRequested.has(s)||(this.countDetailRequested.add(s),e.push(this.ensureAnimationPayload(s,i)))};if(n(t,this.activeBundle),n(this.findPreviousSelectedResult(t),this.previousBundle),!e.length)return;await Promise.all(e),this.activeSelectedResultKey===L(t.matchName||t.constituency||"")&&!this.activeEntityKind&&this.renderPanel(t,this.activePanelView)}fitAnimationToPane(){let e=document.getElementById("electionAnimationContainer"),n=document.getElementById("animation"),a=document.getElementById("electionPaneContent");if(!e||!n||!a)return;let s=e.querySelector(".ev-animation-top-row"),i=()=>{e.style.transform="",e.style.transformOrigin="",e.style.width="",e.style.marginRight="",e.style.marginBottom="",n.style.transform="",n.style.marginRight="",n.style.marginBottom="";let o=window.$?.(n)?.data?.("boundingBox"),l=getComputedStyle(e),c=(parseFloat(l.paddingLeft)||0)+(parseFloat(l.paddingRight)||0),u=(parseFloat(l.borderLeftWidth)||0)+(parseFloat(l.borderRightWidth)||0),h=Math.max((Number(o?.width)||0)+40,n.offsetWidth||0,n.scrollWidth||0),p=Math.ceil(Math.max(h,s?.scrollWidth||0)+c+u);if(!p)return;let d=a.getBoundingClientRect(),m=parseFloat(getComputedStyle(a).paddingRight)||0,x=Math.max(0,d.right-m-e.getBoundingClientRect().left-4),F=Math.min(1,x/p);if(F>=1)return;let P=Math.max(.45,F);e.style.width=`${p}px`,e.style.maxWidth="none";let A=e.offsetHeight;e.style.transformOrigin="0 0",e.style.transform=`scale(${P})`,e.style.marginRight=`${-p*(1-P)}px`,e.style.marginBottom=`${-A*(1-P)}px`};if(i(),this.animationResizeObserver?.disconnect(),typeof ResizeObserver=="function"){let o=0;this.animationResizeObserver=new ResizeObserver(()=>{cancelAnimationFrame(o),o=requestAnimationFrame(i)}),this.animationResizeObserver.observe(a)}}async runAnimation(t){let e=document.getElementById("electionAnimationContainer"),n=document.getElementById("test2ElectionAnimationStatus");if(e&&(await this.ensureAnimationPayload(t),!!t?.animationPayload)){try{await Bn()}catch(a){n&&(n.textContent=`The election animation engine could not load: ${a.message}`);return}if(typeof window.$?.preloadElectionData!="function"||typeof window.animateStages!="function"){n&&(n.textContent="The election animation engine is not available on this route.");return}e.style.display="block",n&&(n.textContent="");try{window.$.preloadElectionData(t.animationPayload),window.animateStages({date:this.activeBundle?.date,electedBody:this.activeBundle?.body,constituency:t.constituency,maxWidth:Math.max(320,(document.getElementById("electionPaneContent")?.clientWidth||0)-16)}),this.fitAnimationToPane()}catch(a){console.error("[test2 elections] Animation failed",a),n&&(n.textContent=`Animation failed: ${a.message}`)}finally{window.$?.clearPreloadedData?.()}}}renderEntityPanel(t,e,n={}){let a=this.activeBundle?.entityIndex||Bt(this.currentResults()),s=t==="candidate"?(a.candidates||[]).find(u=>[u.id,u.key,u.personId].some(h=>h!=null&&String(h)===String(e))):(a.parties||[]).find(u=>L(u.name)===L(e));if(!s)return;let i=this.ensurePanel(),o=document.getElementById("electionPaneContent"),l=document.getElementById("electionPaneTitle"),c=document.getElementById("electionPaneBack");!i||!o||!l||(this.activeEntityKind=t,this.activeEntityKey=e,this.activeEntityReturnView=this.activePanelView||"party",this.activeSelectedResultKey=null,l.textContent=s.name||s.id||"Election entity",c?.classList.remove("hidden"),o.innerHTML=this.mainPaneContract.renderEntityPanel(t,s),c?.addEventListener("click",()=>{let u=this.activeEntityReturnView||"party";this.activeEntityKind=null,this.activeEntityKey=null,this.renderPanel(null,u),this.app.updateURLState()}),o.querySelectorAll("[data-election-result-key]").forEach(u=>{u.addEventListener("click",()=>{let h=this.findResultByKey(u.dataset.electionResultKey);h&&(this.renderPanel(h,"party"),this.app.updateURLState())})}),n.updateURL!==!1&&this.app.updateURLState())}renderPartyEntity(t){let e=this.getElectionWidePercentLabel();return` +
    +
    + +
    +
    Party Information
    +

    ${$(t.name||"")}

    +

    ${$(Ot(this.activeBundle.body||this.activeBundle.displayTitle||""))} - ${$(ie(this.activeBundle.date||""))}

    +
    +
    +
    +
    Candidates stood${S(t.stood)}
    +
    Candidates elected${S(t.elected)}
    +
    1st prefs${S(t.firstPrefs)}
    +
    ${$(e)}${st(t.shareOfTotal)}
    +
    Final-round votes${S(t.finalVotes)}
    +
    Constituencies${S(t.constituencies?.length||0)}
    +
    +
    + + + ${(t.candidates||[]).map(n=>``).join("")} +
    CandidateConstituency1st prefs1st prefs %Final votesStatus
    ${$(n.name||"")}${$(n.constituency||"")}${S(n.firstPref)}${st(n.firstPrefPct)}${S(n.finalVotes)}${$(n.status||"")}
    +
    +
    + `}renderCandidateEntity(t){let e=this.getElectionWidePercentLabel();return` +
    +
    + +
    +
    Candidate Information
    +

    ${$(t.name||"")}

    +

    ${$(t.party||"")}

    +
    +
    +
    +
    1st prefs${S(t.firstPrefs)}
    +
    ${$(e)}${st(t.shareOfTotal)}
    +
    Final-round votes${S(t.finalVotes)}
    +
    Constituency count${S(t.constituencies?.length||0)}
    +
    Election wins${S(t.electedCount)}
    +
    Total valid poll${S(this.activeBundle?.mainLikeTotals?.validPoll||U(this.currentResults(),"validPoll"))}
    +
    +
    + + + + + + + + + ${this.renderMainParityLeafTh("No.",1,"First preference votes")} + ${this.renderMainParityLeafTh("%",2,"First preference vote share")} + ${this.renderMainParityLeafTh("No.",3,"Final count votes")} + ${this.renderMainParityLeafTh("Status",4,"Final count status")} + + + + ${(t.appearances||[]).map(n=>` + + `).join("")} + +
    Constituency / DEA1st preferencesFinal count
    ${S(n.firstPref)}${st(n.firstPrefPct)}${S(n.finalVotes)}${$(n.status||"")}
    +
    +
    + `}showFeatureResults(t){return!this.activeBundle||!t?!1:t.electionResult?(this.renderPanel(t.electionResult),!0):this.isFeatureFromActiveElection(t)?(this.renderPanel(null,this.activePanelView||"party"),!0):!1}isFeatureFromActiveElection(t){if(!this.activeBundle||!t)return!1;let e=L(t.mapId||t.sourceMapId||t.layerId||"");return e?[this.activeBundle.layerId,this.activeBundle.sourceMapId,this.activeBundle.councilLayerId,this.activeBundle.councilSourceMapId,this.activeEntry?.sourceMapId,this.activeEntry?.layerId,this.activeEntry?.councilSourceMapId,this.activeEntry?.councilLayerId].some(n=>L(n||"")===e):!1}findResultByKey(t){let e=L(t);return e&&(this.currentResults().find(n=>vt(n).includes(e))||(this.isLocalGovernmentElection()?this.findCouncilAggregateResultByName(e):null))||null}renderLegend(){let t=document.getElementById("test2ElectionLegend");if(!t||!this.activeBundle)return;let e=this.activeMode;if(["winner","leadingParty"].includes(e)){let n=new Map;for(let a of this.activeBundle.results||[]){let s=e==="winner"?a.winnerParty:a.leadingParty;s&&n.set(s,this.mainPanePartyColour(s))}t.innerHTML=[...n.entries()].slice(0,12).map(([a,s])=>` + ${$(a)} + `).join("");return}t.innerHTML=` + + ${$(_e[e]||e)}: low to high + `}ensurePanel(){let t=document.getElementById("electionResultsPane");return t?((!t.querySelector("#electionPaneTitle")||!t.querySelector("#electionPaneContent")||!t.querySelector("#electionPaneHeaderRight"))&&(t.innerHTML=` + +
    + +

    Election results

    +
    +
    +
    + `),t):null}renderLoadingPanel(t){let e=this.ensurePanel(),n=document.getElementById("electionPaneTitle"),a=document.getElementById("electionPaneContent"),s=document.getElementById("electionPaneBack");if(!e||!n||!a)return;n.textContent=t?.displayTitle||t?.body||"Election results",s?.classList.add("hidden");let i=e.querySelector(".election-pane__header-right");i&&(i.innerHTML='Loading election'),a.innerHTML=` +
    + Loading election results + Preparing the map layer, result bundle, labels, and seat circles. +
    + `,e.classList.add("election-results-pane--open"),document.body.classList.add("test2-election-open")}removePanel(){let t=document.getElementById("electionResultsPane");t?.classList.remove("election-results-pane--open"),t&&(t.innerHTML=""),document.body.classList.remove("test2-election-open")}async renderElectionOverlay(){if(this.removeElectionOverlays(),!!this.activeBundle&&!this.activeEntry?.resultsOnly){if(this.shouldRenderRecallLabels()){await this.renderRecallLabels();return}if(this.shouldRenderElectionOverlays()){if(this.bindOverlayRefresh(),this.overlayMode==="bars"){await this.renderVoteBars();return}await this.renderSeatCircles()}}}removeElectionOverlays(){this.removeSeatCircles(),this.removeVoteBars(),this.removeRecallLabels()}async renderSeatCircles(){let t=performance.now();if(this.lastSeatCircleRenderMs=0,!this.activeBundle||!this.shouldRenderElectionOverlays())return;let e=await this.loadFeatureIndex(),n=this.buildFeatureCentreLookup(e?.items||[]),a=this.mapController.map,s=this.buildSeatCircleGroups(n),i=await this.filterOverlayGroupsByCollisionAsync(s),o=this.ensureSeatCircleOverlay();if(o){o.innerHTML="",this.removeLegacySeatCircleLayers(),this.removeSeatCircleMarkers(),this.seatCircleOverlayState={groups:[],dotCount:0};for(let l of i){let{result:c,center:u,seats:h,positions:p,groupWidth:d,groupHeight:m}=l,x=a.project(u);if(!Number.isFinite(x?.x)||!Number.isFinite(x?.y))continue;let F=Math.min(...p.map(N=>N.x)),P=Math.min(...p.map(N=>N.y)),b=Math.max(...p.map(N=>N.x))-F+_t,R=Math.max(0,(d-b)/2),T=c.syntheticNonGeographic?Ee+4:0,V=L(c.matchName||c.constituency||""),E=c.aggregateType||"",w=document.createElement("div");w.className=`election-seat-circle test2-election-seat-circle${c.syntheticNonGeographic?" test2-election-seat-circle--synthetic":""}`,w.tabIndex=0,w.role="button",w.dataset.resultKey=V,w.dataset.aggregateType=E,w.dataset.constituency=c.constituency||c.matchName||"",w.dataset.lng=String(u[0]),w.dataset.lat=String(u[1]),w.dataset.nonGeographic=c.syntheticNonGeographic?"true":"false",w.setAttribute("aria-label",`Show election result for ${c.constituency||c.matchName||"selected constituency"}`),w.style.width=`${d}px`,w.style.height=`${m}px`;let B=document.createElement("div");if(B.className="seat-group",B.style.position="relative",B.style.width=`${d}px`,B.style.height=`${m}px`,c.syntheticNonGeographic){let N=document.createElement("div");N.className="test2-election-synthetic-label",N.textContent=c.featureName||c.matchName||c.constituency||"Non-geographical constituency",N.title="Non-geographical constituency",N.style.position="absolute",N.style.left="0",N.style.top="0",N.style.width=`${d}px`,B.appendChild(N)}h.forEach((N,k)=>{let j=p[k];if(!j)return;let D=document.createElement("div");D.className="seat-dot test2-election-seat-dot",D.style.position="absolute",D.style.left=`${R+j.x-F}px`,D.style.top=`${T+j.y-P}px`,D.style.width=`${_t}px`,D.style.height=`${_t}px`,D.style.background=N.colour||this.mainPanePartyColour(N.party||c.winnerParty||c.leadingParty),D.title=`${N.name||"Elected candidate"} (${N.party||c.winnerParty||c.leadingParty||"Unknown party"})`,B.appendChild(D)}),w.appendChild(B);let M=()=>this.handleSeatCircleActivation(V,E);w.addEventListener("click",M),w.addEventListener("keydown",N=>{(N.key==="Enter"||N.key===" ")&&(N.preventDefault(),M())});let C=new ke.default.Marker({element:w,anchor:"center"}).setLngLat(u).addTo(a);this.seatCircleMarkers.push(C),this.seatCircleOverlayState.groups.push({key:V,aggregateType:E,constituency:c.constituency||c.matchName||"",seats:h.length,lng:Number(u[0]),lat:Number(u[1]),width:d,height:m,x:x.x,y:x.y}),this.seatCircleOverlayState.dotCount+=h.length}this.lastSeatCircleRenderMs=Math.round(performance.now()-t)}}ensureSeatCircleOverlay(){if(this.seatCircleOverlay?.isConnected)return this.seatCircleOverlay;let t=this.mapController?.map?.getContainer?.()||document.getElementById("map");if(!t)return null;let e=document.createElement("div");return e.id=hn,e.className="test2-election-seat-overlay",e.setAttribute("aria-label","Election seat circles"),t.appendChild(e),this.seatCircleOverlay=e,e}handleSeatCircleActivation(t,e=""){if(e==="council"||e==="district"){this.activeLocalMode="district";let a=this.findCouncilAggregateResultByName(t);this.renderPanel(a||null,"party"),this.app.updateURLState();return}let n=(this.activeBundle?.results||[]).find(a=>L(a.matchName||a.constituency)===t);n&&this.renderPanel(n)}removeLegacySeatCircleLayers(){let t=this.mapController?.map;t&&(t.getLayer(Ne)&&t.removeLayer(Ne),t.getLayer(Se)&&t.removeLayer(Se),t.getSource(Ce)&&t.removeSource(Ce))}getSeatCircleOverlayState(){return{groups:[...this.seatCircleOverlayState?.groups||[]],dotCount:Number(this.seatCircleOverlayState?.dotCount||0)}}async waitForSeatCircleOverlay(){return this.seatCircleMarkers?.length||this.seatCircleOverlayState?.dotCount?this.getSeatCircleOverlayState():(await this.renderSeatCircles(),this.getSeatCircleOverlayState())}removeSeatCircles(){this.removeLegacySeatCircleLayers(),this.removeSeatCircleMarkers(),this.seatCircleOverlay&&(this.seatCircleOverlay.remove(),this.seatCircleOverlay=null),this.seatCircleOverlayState={groups:[],dotCount:0}}removeSeatCircleMarkers(){for(let t of this.seatCircleMarkers||[])t.remove();this.seatCircleMarkers=[]}async renderVoteBars(){if(!this.activeBundle||!this.shouldRenderElectionOverlays())return;let t=await this.loadFeatureIndex(),e=this.buildFeatureCentreLookup(t?.items||[]),n=[];for(let i of this.activeBundle.results||[]){let o=i.anchor?.center||this.findCentreForResult(e,i);if(!o)continue;let l=Number(o[0]),c=Number(o[1]);if(!Number.isFinite(l)||!Number.isFinite(c))continue;let u=Math.max(8,Math.min(80,Number(i.leadingPct||i.majorityPct||0))),h=Math.max(.35,Math.cos(c*Math.PI/180)),p=(.008+u*55e-5)/h;n.push({type:"Feature",geometry:{type:"LineString",coordinates:[[l-p,c],[l+p,c]]},properties:{constituency:i.constituency||i.matchName||"",party:i.leadingParty||i.winnerParty||"",colour:this.mainPanePartyColour(i.leadingParty||i.winnerParty),share:u,resultKey:L(i.matchName||i.constituency||"")}})}if(!n.length)return;let a=this.mapController.map,s={type:"FeatureCollection",features:n};a.getSource(gt)?a.getSource(gt).setData(s):a.addSource(gt,{type:"geojson",data:s}),a.getSource(gt)._data=s,a.getLayer(Pt)||a.addLayer({id:Pt,type:"line",source:gt,paint:{"line-color":["coalesce",["get","colour"],"#6b7280"],"line-width":["interpolate",["linear"],["zoom"],5,4,9,8,12,13],"line-opacity":.92},layout:{"line-cap":"round"}}),this.voteBarClickBound||(this.voteBarClickBound=!0,a.on("click",Pt,i=>{let o=i.features?.[0]?.properties?.resultKey,l=(this.activeBundle?.results||[]).find(c=>L(c.matchName||c.constituency)===o);l&&this.renderPanel(l)}),a.on("mouseenter",Pt,()=>{this.mapController?.setMapCursor?.("pointer")}),a.on("mouseleave",Pt,()=>{this.mapController?.setMapCursor?.("")}))}buildSeatCircleGroups(t){return this.activeBundle?.bodyGroup==="local-government"&&this.activeLocalMode==="district"?this.buildLocalAggregateSeatCircleGroups(t):(this.activeBundle?.results||[]).map(e=>this.createSeatCircleGroup(e,this.seatCandidatesForResult(e),e.anchor?.center||this.findCentreForResult(t,e),e.anchor?.bounds||null,Number(e.anchor?.area||0))).filter(Boolean)}buildLocalAggregateSeatCircleGroups(t){let e=new Map;for(let n of this.activeBundle?.results||[]){let a=this.localBodyCount()>1?n.localBody||"Unknown council":this.activeBundle.displayTitle||this.activeBundle.body||"District";e.has(a)||e.set(a,{result:{constituency:a,matchName:a,localBody:a,aggregateType:this.localBodyCount()>1?"council":"district",winnerParty:"",leadingParty:""},results:[],seats:[],bounds:null,centerAccumulator:{lng:0,lat:0,weight:0},area:0});let s=e.get(a);s.results.push(n),s.seats.push(...this.seatCandidatesForResult(n)),s.bounds=Mn(s.bounds,n.anchor?.bounds||null);let i=n.anchor?.center||this.findCentreForResult(t,n),o=Math.max(1,Number(n.anchor?.area||1));Array.isArray(i)&&i.length>=2&&Number.isFinite(Number(i[0]))&&Number.isFinite(Number(i[1]))&&(s.centerAccumulator.lng+=Number(i[0])*o,s.centerAccumulator.lat+=Number(i[1])*o,s.centerAccumulator.weight+=o),s.area+=Number(n.anchor?.area||0)}return[...e.values()].map(n=>{let a=tt(n.results)[0]||null,s=this.buildCouncilAggregateResult(n.result.constituency||n.result.matchName);s?n.result={...s,aggregateType:n.result.aggregateType}:(n.result.winnerParty=a?.party||"",n.result.leadingParty=a?.party||"");let o=(s?this.findCentreForResult(t,s):null)||Ln(n.bounds)||(n.centerAccumulator.weight?[n.centerAccumulator.lng/n.centerAccumulator.weight,n.centerAccumulator.lat/n.centerAccumulator.weight]:null);return this.createSeatCircleGroup(n.result,n.seats,o,n.bounds,n.area)}).filter(Boolean)}createSeatCircleGroup(t,e,n,a,s){if(!n||!e?.length)return null;let i=fe(e.length,yn),o=Math.max(...i.map(d=>d.x))-Math.min(...i.map(d=>d.x))+_t,l=Math.max(...i.map(d=>d.y))-Math.min(...i.map(d=>d.y))+_t,c=t.syntheticNonGeographic&&(t.featureName||t.matchName||t.constituency)||"",u=c?Math.min(180,Math.max(72,c.length*6.8+16)):0,h=Math.max(o,u),p=l+(c?Ee+4:0);return{result:t,center:n,bounds:a,seats:e,positions:i,groupWidth:h,groupHeight:p,area:Number(s||0)}}bindOverlayRefresh(){let t=this.mapController?.map;if(!t||this.overlayRefreshBound)return;this.overlayRefreshBound=!0;let e=()=>this.scheduleElectionOverlayRefresh(),n=()=>this.scheduleSeatCirclePositionUpdate();t.on("move",n),t.on("zoom",n),t.on("zoomend",e),t.on("moveend",e)}limitSeatCircleGroups(t=[]){let e=this.getSeatCircleGroupLimit();return t.length<=e?t:[...t].sort((n,a)=>{let s=+!!a.result?.syntheticNonGeographic-+!!n.result?.syntheticNonGeographic,i=(a.seats?.length||0)-(n.seats?.length||0);return s||i||(a.area||0)-(n.area||0)}).slice(0,e)}getSeatCircleGroupLimit(){let t=Number(window.innerWidth||1024),e=Number(navigator.deviceMemory||4);return t<700||e<=2?Pn:t<1100||e<=4?gn:bn}scheduleSeatCirclePositionUpdate(){this.seatCirclePositionUpdatePending||!this.seatCircleMarkers?.length||(this.seatCirclePositionUpdatePending=!0,requestAnimationFrame(()=>{this.seatCirclePositionUpdatePending=!1,this.updateSeatCircleOverlayPositions()}))}updateSeatCircleOverlayPositions(){let t=this.mapController?.map;if(!t||!this.seatCircleMarkers?.length)return this.getSeatCircleOverlayState();let e=new Map((this.seatCircleOverlayState?.groups||[]).map(n=>[`${n.key||""}|${n.aggregateType||""}|${n.constituency||""}`,n]));for(let n of this.seatCircleMarkers){let a=n.getElement(),s=Number(a.dataset.lng),i=Number(a.dataset.lat);if(!Number.isFinite(s)||!Number.isFinite(i))continue;let o=t.project([s,i]);if(!Number.isFinite(o?.x)||!Number.isFinite(o?.y))continue;n.setLngLat([s,i]);let l=`${a.dataset.resultKey||""}|${a.dataset.aggregateType||""}|${a.dataset.constituency||""}`,c=e.get(l);c&&(c.x=o.x,c.y=o.y)}return this.getSeatCircleOverlayState()}scheduleElectionOverlayRefresh(){this.overlayRefreshPending||!this.activeBundle||!this.shouldRenderElectionOverlays()||(this.overlayRefreshPending=!0,requestAnimationFrame(()=>{this.overlayRefreshPending=!1,!(!this.activeBundle||!this.shouldRenderElectionOverlays())&&this.renderElectionOverlay().catch(t=>console.warn("[test2 elections] Overlay refresh failed",t))}))}async filterOverlayGroupsByCollisionAsync(t=[]){let e=()=>this.limitSeatCircleGroups(this.filterOverlayGroupsByCollision(t)),n=this.mapController?.map;if(!n||t.length<=1||!this.getOverlayWorker())return e();let s=t.map((o,l)=>{let c=n.project(o.center),u=Te(n,o.bounds);return{index:l,x:c?.x,y:c?.y,bounds:u,width:o.groupWidth,height:o.groupHeight,pixelArea:u?Math.abs(u.maxX-u.minX)*Math.abs(u.maxY-u.minY):0,seats:o.seats?.length||0,area:o.area||0,synthetic:!!o.result?.syntheticNonGeographic}}).filter(o=>Number.isFinite(o.x)&&Number.isFinite(o.y));if(!s.length)return[];let i=await this.runOverlayWorker(s,{limit:this.getSeatCircleGroupLimit(),margin:Mt,minTotalExtent:ae}).catch(()=>null);return Array.isArray(i)?i.map(o=>t[o]).filter(Boolean):e()}getOverlayWorker(){if(this.overlayWorker)return this.overlayWorker;if(typeof Worker>"u")return null;try{let t=new Worker("/app/src/overlay-worker.js",{type:"module"});return t.addEventListener("message",e=>{let{id:n,selectedIndexes:a}=e.data||{},s=this.overlayWorkerCallbacks.get(n);s&&(clearTimeout(s.timer),this.overlayWorkerCallbacks.delete(n),s.resolve(a||[]))}),t.addEventListener("error",e=>{for(let[n,a]of this.overlayWorkerCallbacks)clearTimeout(a.timer),a.reject(e.error||new Error("Election overlay worker failed")),this.overlayWorkerCallbacks.delete(n);this.overlayWorker?.terminate?.(),this.overlayWorker=null}),this.overlayWorker=t,t}catch{return this.overlayWorker=null,null}}runOverlayWorker(t,e){let n=this.getOverlayWorker();if(!n)return Promise.reject(new Error("Election overlay worker unavailable"));let a=++this.overlayWorkerSeq;return new Promise((s,i)=>{let o=setTimeout(()=>{this.overlayWorkerCallbacks.delete(a),i(new Error("Election overlay worker timed out"))},700);this.overlayWorkerCallbacks.set(a,{resolve:s,reject:i,timer:o}),n.postMessage({id:a,type:"filterSeatCircleGroups",groups:t,options:e})})}filterOverlayGroupsByCollision(t=[]){let e=this.mapController?.map;if(!e||t.length<=1)return t;let n=t.map(o=>{let l=e.project(o.center),c=Te(e,o.bounds);return{...o,point:l,bounds:c,width:o.groupWidth,height:o.groupHeight,pixelArea:c?Math.abs(c.maxX-c.minX)*Math.abs(c.maxY-c.minY):0}}).filter(o=>Number.isFinite(o.point?.x)&&Number.isFinite(o.point?.y));if(!n.length)return[];let a=n.reduce((o,l)=>Tn(o,l.bounds||xn(l.point)),null);if(!a||Math.abs(a.maxX-a.minX)+!!c.result?.syntheticNonGeographic-+!!l.result?.syntheticNonGeographic||c.pixelArea-l.pixelArea)){let l=o.width/2+Mt,c=o.height/2+Mt;s.some(h=>{let p=h.width/2+Mt,d=h.height/2+Mt;return Math.abs(o.point.x-h.point.x){let o=i.features?.[0]?.properties?.resultKey,l=(this.activeBundle?.results||[]).find(c=>L(c.matchName||c.constituency)===o);l&&this.renderPanel(l)}),a.on("mouseenter",Ct,()=>{this.mapController?.setMapCursor?.("pointer")}),a.on("mouseleave",Ct,()=>{this.mapController?.setMapCursor?.("")}))}removeRecallLabels(){let t=this.mapController?.map;t&&(t.getLayer(Ct)&&t.removeLayer(Ct),t.getSource($t)&&t.removeSource($t))}shouldRenderElectionOverlays(){let t=L(this.activeBundle?.body||this.activeEntry?.body||""),e=L(this.activeBundle?.type||this.activeEntry?.type||"");return!t.includes("referendum")&&!t.includes("recall petition")&&!e.includes("referendum")&&!e.includes("recall")}shouldRenderRecallLabels(){let t=L(this.activeBundle?.body||this.activeEntry?.body||""),e=L(this.activeBundle?.type||this.activeEntry?.type||"");return t.includes("recall petition")||e.includes("recall")||!!(this.activeBundle?.results||[]).some(n=>n.recallPetition)}shouldRenderSeatCircles(){return this.shouldRenderElectionOverlays()}async loadFeatureIndex(){let t=this.getActiveElectionStyleLayer?.();return t?this.loadFeatureIndexForLayer(t):this.loadFeatureIndexForBundle(this.activeBundle)}async loadFeatureIndexForBundle(t){if(!t)return null;let e=this.app.metadataService.getLayer(t.layerId)||this.app.metadataService.getLayer(t.sourceMapId);return this.loadFeatureIndexForLayer(e)}async loadFeatureIndexForLayer(t){let n=(t?.featureIndexUrl?t:this.app.metadataService.getLayer(t?.id)||this.app.metadataService.getLayer(t?.sourceMapId)||t)?.featureIndexUrl;if(!n)return null;if(this.featureIndexCache.has(n))return this.featureIndexCache.get(n);let a=await fetch(n,{cache:"force-cache"});if(!a.ok)return null;let s=await a.json(),i={...s,items:s.items||s.features||(Array.isArray(s)?s:[])};return Dt(this.featureIndexCache,n,i,mn),i}buildFeatureCentreLookup(t){let e=new Map;for(let n of t){let a=Array.isArray(n.center)?n.center:null;if(!(!a||a.length<2))for(let s of[n.name,n.label,n.title,...n.aliases||[]].map(L).filter(Boolean))e.has(s)||e.set(s,a)}return e}findCentreForResult(t,e){for(let n of vt(e)){let a=t.get(n);if(a)return a}return null}seatCandidatesForResult(t){if(!this.shouldRenderElectionOverlays())return[];let e=zt(t);if(e.length)return e;if(Number(t.seatsTotal)===1||Number(t.seatsWon)===1){let a=(t.candidates||[]).find(s=>L(s.name)===L(t.winnerName))||(t.candidates||[])[0];return[{name:t.winnerName||a?.name||t.leadingName||"",party:t.winnerParty||a?.party||t.leadingParty||"",colour:this.mainPanePartyColour(t.winnerParty||a?.party||t.leadingParty)}]}let n=Math.max(0,Number(t.seatsWon||t.seatsTotal||0));return Array.from({length:n},(a,s)=>({name:s===0&&(t.winnerName||t.leadingName)||"",party:t.winnerParty||t.leadingParty||"",colour:this.mainPanePartyColour(t.winnerParty||t.leadingParty)}))}announceUnmatchedGeography(t){if(t?.resultsOnly){let c="There is no boundary map for this election yet, so its results are shown in the election pane without a map layer.",u=document.getElementById("announcer");u&&(u.textContent=c),console.info("[civgraph] %s",c);return}let e=Number(t?.unmatchedCount)||0;if(!e)return;let n=Number(t?.totalConstituencies)||Number(t?.matchedCount)+e||0,a=Array.isArray(t?.unmatchedConstituencySample)?t.unmatchedConstituencySample.filter(Boolean).slice(0,3):[],s=n?` of ${n}`:"",i=a.length?` For example: ${a.join(", ")}.`:"",o=`${e}${s} constituencies in this election could not be matched to a boundary and are drawn without results.${i}`,l=document.getElementById("announcer");l&&(l.textContent=o),console.info("[civgraph] %s",o)}updateElectionTimeline(){if(!this.activeEntry||!this.catalogue?.elections)return;let t=this.catalogue.elections.filter(n=>(n.loadable||n.resultsOnly)&&n.body===this.activeEntry.body).sort((n,a)=>String(n.date).localeCompare(String(a.date))),e=t.findIndex(n=>n.body===this.activeEntry.body&&n.date===this.activeEntry.date);this.app.setTimelineItems(t.map(n=>({label:n.date,body:n.body,date:n.date})),e>=0?e:t.length-1,async n=>{await this.loadElection(n.body,n.date)})}findEntry(t,e){return(this.catalogue?.elections||[]).find(n=>n.body===t&&n.date===e)||null}getCanonicalLayerId(t=this.activeEntry){return!t?.body||!t?.date?"":`election-${$n(t.body)}-${t.date}`}findEntryByCanonicalLayerId(t){return t&&(this.catalogue?.elections||[]).find(e=>this.getCanonicalLayerId(e)===t)||null}isCanonicalElectionLayerId(t){return!!this.findEntryByCanonicalLayerId(t)}};function $n(r){return String(r||"").toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s]+/g,"-").replace(/-+/g,"-")}function vt(r){return[r.matchName,r.featureName,r.constituency,...r.featureAliases||[],...r.featureNames||[],...(r.featureMatches||[]).flatMap(t=>[t?.name,...t?.aliases||[]])].map(L).filter(Boolean)}function xe(r=""){let t=new Set([r]),e=L(r);return(e==="armagh banbridge and craigavon"||e==="armagh city banbridge and craigavon")&&(t.add("Armagh, Banbridge and Craigavon"),t.add("Armagh Banbridge Craigavon"),t.add("Armagh City, Banbridge and Craigavon"),t.add("Armagh City Banbridge Craigavon")),[...t].map(n=>String(n||"").trim()).filter(Boolean)}function Cn(r){let t=String(r??"");return t?[t,`${t} +`,`${t}\r +`,`${t}\r`,`${t} `]:[t]}function Sn(r){let t=[];for(let n of r.featureMatches||[])t.push(n?.name,...n?.aliases||[]);t.push(r.matchName,r.featureName,...r.featureNames||[],...r.featureAliases||[]);let e=new Set;return t.map(n=>String(n||"").trim()).filter(n=>{let a=L(n);return!a||e.has(a)?!1:(e.add(a),!0)})}function Nn(r={}){let t=String(r.Candidate_Id||"").trim();if(!t||t.toLowerCase()==="nontransferable")return!1;let e=En(r);return!(!e||e.toLowerCase()==="party"||String(r.Party_Name||"").trim().toLowerCase()==="party")}function En(r={}){return String(r.candidateName||`${r.Firstname||""} ${r.Surname||""}`.trim()||"").replace(/[�]+/g,"").replace(/\s{2,}/g," ").trim()}function It(r){let t=String(r||"").toLowerCase();return t?t.includes("not elected")?"not_elected":t.includes("excluded")?"excluded":t.includes("elected")||t.includes("made quota")||t.includes("counted as elected")||t.includes("deemed elected")?"elected":"unknown":"unknown"}function U(r,t){return r.reduce((e,n)=>{let a=Number(n?.[t]);return Number.isFinite(a)?e+a:e},0)}function _n(r,t){let e=r.map(n=>Number(n?.[t])).filter(n=>Number.isFinite(n));return e.length?e.reduce((n,a)=>n+a,0)/e.length:null}function Ft(r=[]){let t=[];for(let e of r){let n=new Map,a=Number(e.validPoll||e.totalVotes||0);for(let s of e.candidates||[]){let i=s.party||"Independent/Other",o=L(i)||i;n.has(o)||n.set(o,{party:i,constituency:e.constituency||e.matchName||"",resultKey:L(e.matchName||e.constituency||""),colour:s.colour||X(i)||jt(i),stood:0,seats:0,firstPrefs:0,seatShare:null,share:null});let l=n.get(o);l.stood+=1,l.firstPrefs+=Number(s.firstPrefs??s.votes??0)||0,s.elected&&(l.seats+=1)}for(let s of n.values())s.seatShare=Number(e.seatsTotal)?s.seats/Number(e.seatsTotal)*100:null,s.share=a?s.firstPrefs/a*100:null,t.push(s)}return t.sort((e,n)=>v(n.share)-v(e.share)||v(n.firstPrefs)-v(e.firstPrefs)||String(e.party).localeCompare(String(n.party))||String(e.constituency).localeCompare(String(n.constituency)))}function Et(r=[]){let t=new Map;for(let e of r){let n=e.localBody||"Unknown council";t.has(n)||t.set(n,{council:n,deas:0,seats:0,validPoll:0,electorate:0,partySeats:new Map,partyVotes:new Map,partyColours:new Map});let a=t.get(n);a.deas+=1,a.seats+=Number(e.seatsWon??e.seatsTotal??0)||0,a.validPoll+=Number(e.validPoll||e.totalVotes||0)||0,a.electorate+=Number(e.electorate||0)||0;for(let s of e.candidates||[]){let i=s.party||"Independent/Other";a.partyVotes.set(i,(a.partyVotes.get(i)||0)+(Number(s.firstPrefs??s.votes??0)||0)),s.colour&&!a.partyColours.has(i)&&a.partyColours.set(i,s.colour),s.elected&&a.partySeats.set(i,(a.partySeats.get(i)||0)+1)}}return[...t.values()].map(e=>{let n=[...e.partySeats.entries()].sort((a,s)=>s[1]-a[1]||(e.partyVotes.get(s[0])||0)-(e.partyVotes.get(a[0])||0))[0]||[...e.partyVotes.entries()].sort((a,s)=>s[1]-a[1])[0]||["",0];return{...e,leadingParty:n[0],colour:e.partyColours.get(n[0])||jt(n[0]),share:e.validPoll?(e.partyVotes.get(n[0])||0)/e.validPoll*100:null,turnoutPct:e.electorate?e.validPoll/e.electorate*100:null}}).sort((e,n)=>String(e.council).localeCompare(String(n.council)))}function Te(r,t){let e=Number(t?.west),n=Number(t?.south),a=Number(t?.east),s=Number(t?.north);if(!r||![e,n,a,s].every(Number.isFinite))return null;let i=r.project([a,s]),o=r.project([e,n]);return{minX:Math.min(i.x,o.x),maxX:Math.max(i.x,o.x),minY:Math.min(i.y,o.y),maxY:Math.max(i.y,o.y)}}function Mn(r,t){if(!t)return r;if(!r)return{...t};let e=Math.min(Number(r.west),Number(t.west)),n=Math.min(Number(r.south),Number(t.south)),a=Math.max(Number(r.east),Number(t.east)),s=Math.max(Number(r.north),Number(t.north));return[e,n,a,s].every(Number.isFinite)?{west:e,south:n,east:a,north:s}:r||t||null}function Ln(r){let t=Number(r?.west),e=Number(r?.south),n=Number(r?.east),a=Number(r?.north);return[t,e,n,a].every(Number.isFinite)?[(t+n)/2,(e+a)/2]:null}function xn(r){return{minX:r.x,maxX:r.x,minY:r.y,maxY:r.y}}function Tn(r,t){return t?r?{minX:Math.min(r.minX,t.minX),maxX:Math.max(r.maxX,t.maxX),minY:Math.min(r.minY,t.minY),maxY:Math.max(r.maxY,t.maxY)}:{...t}:r}function Bn(){if(typeof window.$?.preloadElectionData=="function"&&typeof window.animateStages=="function")return Promise.resolve();if(!se){let r=e=>`${e}?v=${bt[e]}`;se=[r("/app/js/jquery-shim.js"),r("/app/election-viewer-package/js/stages2.js"),r("/app/election-viewer-package/js/animation_preview.js"),r("/app/election-viewer-package/js/animation_preview_manager.js"),r("/app/election-viewer-package/js/election_viewer.js")].reduce((e,n)=>e.then(()=>Rn(n)),Promise.resolve())}return se}function Rn(r){return[...document.querySelectorAll("script[data-test2-runtime-src]")].find(e=>e.dataset.test2RuntimeSrc===r)?Promise.resolve():new Promise((e,n)=>{let a=document.createElement("script");a.src=r,a.dataset.test2RuntimeSrc=r,a.onload=()=>e(),a.onerror=()=>n(new Error(r)),document.head.appendChild(a)})}function An(){return new Promise(r=>requestAnimationFrame(()=>r()))}function Dt(r,t,e,n){if(!r||!t)return e;for(r.has(t)&&r.delete(t),r.set(t,e);r.size>n;){let a=r.keys().next().value;r.delete(a)}return e}async function wn(r,t,e){let n=Array.isArray(r)?r:[],a=Math.max(1,Number(t)||1),s=new Array(n.length),i=0,o=Array.from({length:Math.min(a,n.length)},async()=>{for(;iNumber(n)>1)}function Fn(r={},t=[],e=[]){let n=new Map((r.nonTransferable||[]).map(l=>[Number(l.count),l])),a=new Map,s=new Map,i=0,o=Kt(e);for(let l of o){let c=n.get(l),u=0,h=0,p=0;for(let x of t||[]){let F=new Map((x.counts||[]).map(R=>[Number(R.count),R])),P=F.get(l),A=Wt(x,l,F,r,o,P),b=Y(A?.transfers);b!==null&&(u+=b,b>0&&(h+=b),b<0&&(p+=Math.abs(b)))}let d=Y(c?.transfers);if(d===null&&l>1){let x=-u;d=x>1e-4?x:0}let m=Y(c?.total);m===null&&(m=l<=1?0:i+Math.max(0,d||0)),i=m,a.set(l,{count:l,total:m,transfers:d||0,inferred:!c}),s.set(l,{positive:h+Math.max(0,d||0),negativeAbs:p})}return{nonTransferable:a,transferDenominators:s}}function Be(r,t){let e=Y(r);if(e===null||Math.abs(e)<=1e-4)return"-";let n=t&&typeof t=="object"?e<0?Y(t.negativeAbs):Y(t.positive):Y(t);return n===null||n<=0?"-":rt(e/n*100)}function Dn(r={},t=new Map,e={},n=[]){let a=Y(e.quota??e.Quota??e.countInfo?.Quota??r.quota),s=Kt(n.length?n:[...t.keys()]),i=null;return s.forEach(o=>{if(i!==null||o<=1)return;let l=Wt(r,o,t,e,s,t.get(o));if(!l)return;let c=Y(l.total??l.firstPrefs),u=Y(l.transfers);if(c===null||u===null||u>=-.01)return;let h=c<=.01,p=a!==null&&a>0&&Math.abs(c-a)<=.01;(h||p)&&(i=o)}),i}function Wt(r={},t,e=new Map,n={},a=[],s=null){let i=Number(t);if(!Number.isFinite(i)||i<=1)return s||null;let o=Y(s?.transfers);if(o!==null&&o<-.01)return s;let l=Kt(a.length?a:[...e.keys()]),c=Ie(l,i);if(c===null)return s||null;let u=Number(r.excludedAt||r.electedAt||0);if(!u||u!==c)return s||null;let h=e.get(u),p=Y(h?.total??h?.firstPrefs);if(p===null||p<=.01)return s||null;if(r.excludedAt&&Number(r.excludedAt)===u)return{...s||{},count:i,total:0,transfers:-p,status:"Excluded transfer"};if(r.electedAt&&Number(r.electedAt)===u){let d=Y(n.quota??n.Quota??n.countInfo?.Quota??r.quota);return d===null||d<=0||p<=d+.01?s||null:{...s||{},count:i,total:d,transfers:d-p,status:"Surplus transfer"}}return s||null}function Kt(r=[]){return[...new Set(r.map(Number).filter(Number.isFinite))].sort((t,e)=>t-e)}function Ie(r=[],t){let e=null;for(let n of r){let a=Number(n);if(!Number.isFinite(a)||a>=Number(t))break;e=a}return e}function Vn(r,t){return t!=null&&Number(r)>Number(t)}function S(r){if(r==null||r==="")return"";let t=Number(r);return Number.isFinite(t)?t.toLocaleString():String(r)}function st(r){if(r==null||r==="")return"";let t=Number(r);return Number.isFinite(t)?`${t.toFixed(2).replace(/\.00$/,"")}%`:String(r)}function Vt(r){let t=Number(r);return Number.isFinite(t)?`${t>0?"+":""}${t.toLocaleString()}`:""}function Re(r){let t=Number(r);return Number.isFinite(t)?`${t>0?"+":""}${t.toFixed(2).replace(/\.00$/,"")}%`:""}function J(r){let t=Number(r);return Number.isFinite(t)?`${t.toFixed(2)}%`:""}function Z(r){let t=Number(r);return Number.isFinite(t)?`${t>0?"+":""}${t.toLocaleString("en-GB")}`:""}function rt(r){let t=Number(r);return Number.isFinite(t)?`${t>0?"+":""}${t.toFixed(2)}%`:""}function Ae(r){let t=Number(r);return Number.isFinite(t)?`${t>0?"+":""}${t.toFixed(2)}`:""}function ct(){return'N/A'}function pt(r){return String(Number(r)+1)}function Ot(r){let t=String(r||"");return new Map([["D\xE1il \xC9ireann","D\xE1il"],["D\xC3\xA1il \xC3\u2030ireann","D\xE1il"],["House of Commons of the United Kingdom","Westminster"],["Northern Ireland Assembly","Assembly"],["Northern Ireland Constitutional Convention","Convention"],["Northern Ireland Forum for Political Dialogue","Forum"],["European Parliament (Ireland)","European (Republic of Ireland)"],["European Parliament","European"],["President of Ireland","President"],["Referendum (Ireland)","Referendum"]]).get(t)||t}function ie(r){let t=String(r||"").match(/^(\d{4})-(\d{2})-(\d{2})/);if(!t)return String(r||"");let[,e,n,a]=t,s=new Date(`${e}-${n}-${a}T00:00:00Z`);return Number.isNaN(s.getTime())?String(r||""):s.toLocaleDateString("en-GB",{day:"2-digit",month:"short",year:"numeric",timeZone:"UTC"})}function oe(r={}){let t=L(r.body||r.displayTitle||""),e=L(r.bodyGroup||""),n=L(r.displayProvider||"");return e==="local-government"||/local government|local election/.test(t)||/local government/.test(n)?"local elections":/house of commons|westminster|uk parliament/.test(t)?"UK general elections in Northern Ireland":/dail|dail eireann|dáil|irish general/.test(t)?"Irish general elections":/assembly|forum|constitutional convention|parliament of northern ireland/.test(t)?"devolved elections":/european/.test(t)&&(/ireland|republic/.test(t)||/republic/.test(n))?"European elections in the Republic of Ireland":/european/.test(t)?"European elections in Northern Ireland":/president/.test(t)?"Irish presidential elections":e||t||"elections"}function re(r={}){let t=L(r.body||r.displayTitle||""),e=L(r.bodyGroup||""),n=L(`${r.displayProvider||""} ${r.provider||""} ${r.region||""} ${r.jurisdiction||""}`),a=`${t} ${e} ${n}`,s=(Array.isArray(r.constituencies)?r.constituencies:[]).map(i=>L(i)).filter(Boolean);if(/northern ireland/.test(a)||/house of commons|westminster|uk parliament|assembly|forum|constitutional convention|parliament of northern ireland/.test(a)||s.length&&s.every(i=>i==="northern ireland"))return"Northern Ireland";if(/republic of ireland|irish general|dail|dail eireann|dáil|president of ireland|irish presidential/.test(a))return"Republic of Ireland";if(/european/.test(t))return/northern ireland/.test(a)?"Northern Ireland":/\bireland\b/.test(t)||/republic/.test(a)||/ireland national/.test(a)?"Republic of Ireland":"Northern Ireland";if(e==="local-government"||/local election|local government/.test(a)){if(/local government districts|districts|northern/.test(a))return"Northern Ireland";if(/local authorities|republic/.test(a))return"Republic of Ireland"}return/referendum/.test(t)&&/ireland/.test(a)?"Republic of Ireland":null}function On(r=[],t=[]){let e=[];for(let n of t){let a=[],s=[];for(let o of r){let l=(o.counts||[]).find(u=>Number(u.count)===Number(n)),c=L(l?.status||"");/not elected/.test(c)||(/elected|quota/.test(c)&&Number(o.electedAt)===Number(n)&&a.push(o.name),/excluded|eliminated/.test(c)&&Number(o.excludedAt)===Number(n)&&s.push(o.name))}let i=[];a.length&&i.push(`${a.length===1?a[0]:`${a.length} candidates`} elected`),s.length&&i.push(`${s.length===1?s[0]:`${s.length} candidates`} excluded`),i.length&&e.push({count:Number(n),label:i.join("; ")})}return e}function Gn(r={},t=[],e=[]){let n=[],a=Kt(e);for(let s of a){if(Number(s)<=1)continue;let i=[],o=[];for(let c of t||[]){let u=new Map((c.counts||[]).map(m=>[Number(m.count),m])),h=Wt(c,s,u,r,a,u.get(Number(s))),p=Y(h?.transfers);if(p===null||p>=-.01)continue;let d=Wn(c.name);d&&(jn(c,h,r,s,a)==="elected"?i.push(d):o.push(d))}let l=[];i.length&&l.push(`${we(i)} elected`),o.length&&l.push(`${we(o)} excluded`),l.length&&n.push({count:Number(s),label:l.join("; ")})}return n}function jn(r={},t={},e={},n,a=[]){let s=L(t?.status||r.status||"");if(s.includes("excluded")||s.includes("eliminated"))return"excluded";if(s.includes("elected")||s.includes("surplus")||s.includes("quota"))return"elected";let i=Y(t?.total??t?.firstPrefs);if(i!==null&&i<=.01)return"excluded";let o=Y(e.quota??e.Quota??e.countInfo?.Quota??r.quota);if(o!==null&&o>0&&i!==null&&Math.abs(i-o)<=.01)return"elected";let l=Ie(a,Number(n));return Number(r.excludedAt||0)===l||Number(r.excludedAt||0)===Number(n)?"excluded":Number(r.electedAt||0)===l||Number(r.electedAt||0)===Number(n)?"elected":"excluded"}function Wn(r=""){let t=String(r||"").replace(/\([^)]*\)/g," ").trim().split(/\s+/).filter(Boolean);if(!t.length)return"";let e=t[t.length-1],n=t[t.length-2]||"";return/^(o|ó|ua|mac|mc|nic|ní)$/i.test(n)?`${n} ${e}`:e}function we(r=[]){let t=new Set;return r.filter(e=>{let n=L(e);return!n||t.has(n)?!1:(t.add(n),!0)}).join(", ")}function Gt(r={}){let t=r.recallPetition||{};if(typeof t.triggered=="boolean")return t.triggered;let e=Number(t.signed??t.signatures??r.leadingVotes),n=Number(t.threshold??t.required);return Number.isFinite(e)&&Number.isFinite(n)?e>=n:!1}function $(r){return String(r??"").replace(/[&<>"']/g,t=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[t])}export{Le as Test2ElectionManager}; diff --git a/app/build/chunks/election-manager-ZWKCF5OK.js b/app/build/chunks/election-manager-ZWKCF5OK.js deleted file mode 100644 index d44e5df1e0..0000000000 --- a/app/build/chunks/election-manager-ZWKCF5OK.js +++ /dev/null @@ -1,947 +0,0 @@ -import{a as ot,b as De,c as oe,d as re}from"./chunk-V4IEUOVV.js";import{b as Fe,d as ct,e as $t}from"./chunk-2YPEAJVR.js";ct();var xe=Fe(De());ct();ct();var Ve=new Map([["alliance","#f6cb2f"],["aontu","#44532a"],["conservative","#0087dc"],["dup","#d46a4c"],["fianna fail","#66bb66"],["fine gael","#6699ff"],["green","#22ac6f"],["green party","#22ac6f"],["independent","#b8b8b8"],["independent ireland","#3bee56"],["irish labour","#cc0000"],["labour","#cc0000"],["pbp","#ff0090"],["sdlp","#2aa82c"],["sinn fein","#326760"],["social democrats","#752f8b"],["solidarity pbp","#8e2420"],["solidarity-pbp","#8e2420"],["tuv","#0c3a6a"],["uup","#48a5ee"],["yes","#2aa82c"],["no","#d46a4c"],["remain","#2aa82c"],["leave","#d46a4c"]]);function j(r){return String(r??"").normalize("NFKD").replace(/[\u0300-\u036f]/g,"").replace(/\([^)]*\)/g," ").replace(/&/g," and ").replace(/[''`]/g,"").replace(/[-_/.,()]/g," ").replace(/\s+/g," ").trim().toLowerCase()}function Oe(r){return String(r??"").replace(/\u00c3\u00a1/g,"a").replace(/\u00c3\u00a9/g,"e").replace(/\u00c3\u0089/g,"E").replace(/\u00e2\u20ac\u2122/g,"'").replace(/\s+/g," ").trim()}function xt(r){if(r==null||r==="")return null;let t=Number(String(r).replace(/,/g,"").replace(/%$/,""));return Number.isFinite(t)?t:null}function F(r){let t=xt(r);return t===null?0:t}function Ut(r,t=2){let e=10**t;return Math.round(r*e)/e}function ce(r){let t=Oe(r||"").trim();return t?t.replace(/^Sinn Fein$/i,"Sinn F\xE9in").replace(/^Fianna Fail$/i,"Fianna F\xE1il").replace(/^Labour$/i,"Irish Labour").replace(/^People Before Profit(?: Alliance)?$/i,"PBP"):""}function U(r,t="#6b7280"){return Ve.get(j(r))||t}function Ge(r){let t=j(r);return t?/not elected|unelected|not deemed elected/.test(t)?"not-elected":/elected|made quota|counted as elected|deemed elected/.test(t)?"elected":/excluded|eliminated/.test(t)?"excluded":t:""}function zt(r={}){let t=Array.isArray(r.candidates)?r.candidates:[],e=xt(r.seatsTotal??r.seatsWon),n=Ke(t,e),a=n.filter(s=>s.elected);return a.length?a.map(s=>({...s,colour:s.colour||U(s.party)})).sort((s,i)=>F(s.electedAt)-F(i.electedAt)||F(i.finalVotes)-F(s.finalVotes)).slice(0,e&&e>0?e:a.length):e&&e>0?[...n].filter(s=>!s.excluded).sort((s,i)=>F(i.finalVotes??i.firstPrefs)-F(s.finalVotes??s.firstPrefs)).slice(0,e).map(s=>({...s,elected:!0,status:s.status||"Deemed elected",colour:s.colour||U(s.party)})):[]}function je(r={}){let t=Array.isArray(r.counts)?r.counts:[];return Math.max(1,...t.map(e=>xt(e?.count)||0))}function Ke(r=[],t=null){let e=xt(t);if(!e||e<=0||!Array.isArray(r)||!r.length)return r;let n=r.filter(l=>l.elected);if(n.length>=e)return r;let a=new Set(n.map(l=>l.id||`${l.name}|${l.party}`)),s=e-n.length,i=r.filter(l=>{let c=l.id||`${l.name}|${l.party}`;return a.has(c)||l.excluded||Ge(l.status)==="excluded"||l.autoReturnedCeannComhairle?!1:F(l.finalVotes??l.firstPrefs)>0}).sort((l,c)=>F(c.finalVotes??c.firstPrefs)-F(l.finalVotes??l.firstPrefs)||F(c.firstPrefs)-F(l.firstPrefs)||String(l.name||"").localeCompare(String(c.name||""))).slice(0,s);if(!i.length)return r;let o=new Set(i.map(l=>l.id||`${l.name}|${l.party}`));return r.map(l=>{let c=l.id||`${l.name}|${l.party}`;if(!o.has(c))return l;let d=je(l),y=Array.isArray(l.counts)?l.counts.map(u=>Number(u?.count)===d?{...u,status:u.status||"Deemed elected"}:u):l.counts;return{...l,elected:!0,electedAt:l.electedAt||d,excluded:!1,excludedAt:null,status:"Deemed elected",counts:y}})}function Q(r=[]){let t=new Map,e=0;for(let n of r){for(let a of zt(n)){let s=a.party||n.winnerParty||n.leadingParty||"Independent/Other",i=j(s)||s;t.has(i)||t.set(i,{party:s,seats:0,stood:0,votes:0,colour:U(s)}),t.get(i).seats+=1}for(let a of n.candidates||[]){if(a.autoReturnedCeannComhairle)continue;let s=F(a.firstPrefs??a.votes),i=a.party||"Independent/Other",o=j(i)||i;t.has(o)||t.set(o,{party:i,seats:0,stood:0,votes:0,colour:U(i)}),t.get(o).stood+=1,t.get(o).votes+=s,e+=s}}return[...t.values()].map(n=>({...n,share:e?n.votes/e*100:null})).sort((n,a)=>a.seats-n.seats||a.votes-n.votes||n.party.localeCompare(a.party))}function nt(r=[]){let t=[];for(let e of r)for(let n of e.candidates||[])t.push({...n,constituency:e.constituency,firstPrefPct:e.validPoll?F(n.firstPrefs)/e.validPoll*100:null});return t.sort((e,n)=>+!!n.elected-+!!e.elected||F(n.firstPrefs)-F(e.firstPrefs))}function Tt(r=[]){let t=new Map,e=new Map,n=0;for(let s of r){n+=F(s.validPoll);for(let i of s.candidates||[]){let o=`${i.name}|${i.party}`,l=i.sourcePersonId||o;e.has(l)||e.set(l,{id:l,key:o,name:i.name,party:i.party,colour:i.colour||U(i.party),firstPrefs:0,finalVotes:0,electedCount:0,constituencies:new Set,appearances:[]});let c=e.get(l);c.firstPrefs+=F(i.firstPrefs),c.finalVotes+=F(i.finalVotes),i.elected&&(c.electedCount+=1),c.constituencies.add(s.constituency),c.appearances.push({constituency:s.constituency,firstPref:F(i.firstPrefs),finalVotes:F(i.finalVotes),status:i.elected?"Elected":i.status||""});let d=i.party||"Independent/Other",y=j(d);t.has(y)||t.set(y,{name:d,colour:i.colour||U(d),firstPrefs:0,finalVotes:0,stood:0,elected:0,constituencies:new Set,candidates:[]});let u=t.get(y);i.autoReturnedCeannComhairle||(u.firstPrefs+=F(i.firstPrefs),u.finalVotes+=F(i.finalVotes),u.stood+=1),i.elected&&(u.elected+=1),u.constituencies.add(s.constituency),u.candidates.push({id:l,name:i.name,constituency:s.constituency,firstPref:F(i.firstPrefs),finalVotes:F(i.finalVotes),status:i.elected?"Elected":i.status||""})}}let a=s=>({...s,constituencies:[...s.constituencies].sort((i,o)=>String(i).localeCompare(String(o))),shareOfTotal:n?s.firstPrefs/n*100:null});return{totalValid:n,parties:[...t.values()].map(a).sort((s,i)=>i.elected-s.elected||i.firstPrefs-s.firstPrefs),candidates:[...e.values()].map(a).sort((s,i)=>i.electedCount-s.electedCount||i.firstPrefs-s.firstPrefs)}}function Bt(r=[],t=[]){let e=new Map(t.map(n=>[j(n.constituency),n]));return r.map(n=>{let a=e.get(j(n.constituency)),s=new Map((a?.candidates||[]).map(o=>[le(o),o])),i=(n.candidates||[]).map(o=>{let l=s.get(le(o)),c=n.validPoll?F(o.firstPrefs)/n.validPoll*100:null,d=a?.validPoll&&l?F(l.firstPrefs)/a.validPoll*100:null;return{...o,previous:l?{firstPrefs:l.firstPrefs,firstPrefPct:d,finalVotes:l.finalVotes,elected:l.elected,status:l.status}:null,deltas:l?{firstPrefs:F(o.firstPrefs)-F(l.firstPrefs),firstPrefPct:c!==null&&d!==null?Ut(c-d,2):null,finalVotes:F(o.finalVotes)-F(l.finalVotes)}:null}});return{...n,candidates:i,previous:a?{leadingParty:a.leadingParty,winnerParty:a.winnerParty,leadingVotes:a.leadingVotes,leadingPct:a.leadingPct,turnoutPct:a.turnoutPct,seatsWon:a.seatsWon,validPoll:a.validPoll,candidates:a.candidates||[]}:null,deltas:a?{leadingVotes:F(n.leadingVotes)-F(a.leadingVotes),leadingPct:n.leadingPct!==null&&a.leadingPct!==null?Ut(n.leadingPct-a.leadingPct,2):null,turnoutPct:n.turnoutPct!==null&&a.turnoutPct!==null?Ut(n.turnoutPct-a.turnoutPct,2):null,seatsWon:F(n.seatsWon)-F(a.seatsWon),validPoll:F(n.validPoll)-F(a.validPoll)}:null}})}function de(r,t=13){if(r<=0)return[];if(r===1)return[{x:0,y:0}];if(r===2)return[{x:0,y:0},{x:t,y:0}];if(r===3)return[{x:0,y:0},{x:t,y:0},{x:t*2,y:0}];if(r>12){let y=Math.PI,u=C=>{let R=1/(4*C-2);return Array.from({length:C},(f,g)=>{let A=.5+2*g*R;return Math.max(1,Math.floor(y*A/(2*R)))})},h=1,v=u(h);for(;v.reduce((C,R)=>C+R,0)C+R,0),V=r/E,b=v.map(C=>Math.max(1,Math.round(C*V))),k=b.reduce((C,R)=>C+R,0);for(;k>r;){let C=We(b,R=>R>1);if(C<0)break;b[C]-=1,k-=1}for(;k({idx:f,deficit:R-b[f]})).filter(R=>R.deficit>0).sort((R,f)=>f.deficit-R.deficit)[0];if(!C)break;b[C.idx]+=1,k+=1}let M=1/(4*h-2),T=t*1.02/(2*M),B=[];b.forEach((C,R)=>{let f=.5+2*R*M;if(C<=0)return;if(C===1){B.push({x:T,y:0});return}let g=Math.asin(M/f),A=(Math.PI-2*g)/(C-1);for(let O=0;OC.x)),P=Math.min(...B.map(C=>C.y));return B.forEach(C=>{C.x-=S,C.y-=P}),B.sort((C,R)=>C.x-R.x||C.y-R.y),B}let e=Math.ceil(r/2),n=r-e,a=[],i=-((e-1)*t)/2;for(let y=0;yy.x)),d=Math.min(...a.map(y=>y.y));return a.forEach(y=>{y.x-=c,y.y-=d}),a}function We(r,t){for(let e=r.length-1;e>=0;e-=1)if(t(r[e],e,r))return e;return-1}function le(r={}){return j(r.name||r.candidateName||r.Candidate_Name||r.id||"")}ct();function qe({entry:r=null,bundle:t=null,results:e=[],previousResults:n=[],selectedResult:a=null,view:s="party",mode:i="winner",overlayMode:o="circles",localMode:l="constituency",countDetailedView:c=!1}={}){let d=n.length?Bt(e,n):e,y=a?j(a.matchName||a.constituency||""):null,u=t?.partySummary?.length?t.partySummary:Q(d),h=nt(d),v=(t?.bodyGroup||r?.bodyGroup)==="local-government",E=d.some(V=>V.recallPetition);return{entry:r,bundle:t,title:t?.displayTitle||r?.displayTitle||t?.body||r?.body||"",date:t?.date||r?.date||"",body:t?.body||r?.body||"",bodyGroup:t?.bodyGroup||r?.bodyGroup||null,view:s,mode:i,overlayMode:o,localMode:l,countDetailedView:c,selectedKey:y,selectedResult:a,results:d,previousResults:n,partySummary:u,candidateSummary:h,entityIndex:t?.entityIndex||Tt(d),localGovernment:v,recallPetition:E,coverage:{matched:Number(t?.matchedCount||0),unmatched:Number(t?.unmatchedCount||0),total:Number(t?.totalConstituencies||d.length||0)},totals:Ue(d,u)}}function ue(r,t=null,e=null){return qe({entry:r.activeEntry,bundle:r.activeBundle,results:r.activeBundle?.results||[],previousResults:r.previousBundle?.results||[],selectedResult:t,view:e||r.activePanelView||"party",mode:r.activeMode,overlayMode:r.overlayMode,localMode:r.activeLocalMode,countDetailedView:r.countDetailedView})}function Yt(r=[]){let t=[];for(let e of r){let n=new Map,a=Number(e.validPoll||e.totalVotes||0);for(let s of e.candidates||[]){let i=s.party||"Independent/Other",o=j(i)||i;n.has(o)||n.set(o,{party:i,constituency:e.constituency||e.matchName||"",resultKey:j(e.matchName||e.constituency||""),colour:s.colour||U(i),stood:0,seats:0,firstPrefs:0,share:null});let l=n.get(o);l.stood+=1,l.firstPrefs+=Number(s.firstPrefs??s.votes??0)||0,s.elected&&(l.seats+=1)}for(let s of n.values())s.share=a?s.firstPrefs/a*100:null,t.push(s)}return t.sort((e,n)=>String(e.party).localeCompare(String(n.party))||String(e.constituency).localeCompare(String(n.constituency))||n.firstPrefs-e.firstPrefs)}function Xt(r=[]){let t=new Map;for(let e of r){let n=e.localBody||"Unknown council";t.has(n)||t.set(n,{council:n,deas:0,seats:0,validPoll:0,electorate:0,partySeats:new Map,partyVotes:new Map});let a=t.get(n);a.deas+=1,a.seats+=Number(e.seatsWon??e.seatsTotal??0)||0,a.validPoll+=Number(e.validPoll||e.totalVotes||0)||0,a.electorate+=Number(e.electorate||0)||0;for(let s of e.candidates||[]){let i=s.party||"Independent/Other";a.partyVotes.set(i,(a.partyVotes.get(i)||0)+(Number(s.firstPrefs??s.votes??0)||0)),s.elected&&a.partySeats.set(i,(a.partySeats.get(i)||0)+1)}}return[...t.values()].map(e=>{let n=[...e.partySeats.entries()].sort((a,s)=>s[1]-a[1]||(e.partyVotes.get(s[0])||0)-(e.partyVotes.get(a[0])||0))[0]||[...e.partyVotes.entries()].sort((a,s)=>s[1]-a[1])[0]||["",0];return{...e,leadingParty:n[0],colour:U(n[0]),turnoutPct:e.electorate?e.validPoll/e.electorate*100:null}}).sort((e,n)=>String(e.council).localeCompare(String(n.council)))}function ht(r,t){return r.reduce((e,n)=>{let a=Number(n?.[t]);return Number.isFinite(a)?e+a:e},0)}function He(r,t){let e=r.map(n=>Number(n?.[t])).filter(n=>Number.isFinite(n));return e.length?e.reduce((n,a)=>n+a,0)/e.length:null}function Ue(r,t){let e=ht(r,"validPoll"),n=ht(r,"totalPoll"),a=ht(r,"electorate"),s=t.reduce((i,o)=>i+F(o.seats),0);return{constituencies:r.length,totalSeats:s,validPoll:e,totalPoll:n,electorate:a,turnoutPct:a&&n?n/a*100:He(r,"turnoutPct")}}function he(r){return new Zt(r)}function Ct(r,t,e){let n=Number(r);if(!Number.isFinite(n))return"#9ca3af";let a=Math.max(0,Math.min(1,(n-t)/(e-t||1)));return a<.2?"#fef3c7":a<.4?"#fde68a":a<.6?"#f59e0b":a<.8?"#d97706":"#92400e"}var Zt=class{constructor(t){this.host=t}viewModel(t=null,e=null){return ue(this.host,t,e)}renderOverallResults(t="party"){if(typeof this.host.renderMainCompatibleOverallResults=="function")return this.host.renderMainCompatibleOverallResults(t);let e=this.viewModel(null,t),n=e.results;if(e.recallPetition)return this.renderRecallPetitionOverview(n);if(e.localGovernment&&e.localMode==="district")return this.renderDistrictResults(t);let a=e.bundle?.partySummary?.length?e.bundle.partySummary:Q(n),s=this.withPartyDeltas(a),i=nt(n);return` -
    - ${this.renderViewTabs([["party","By Party"],["candidate","By Candidate"],["constituency",e.localGovernment?"By DEA":"By Constituency"],...e.localGovernment?[["local-party","By Local Party"]]:[]],t)} -
    -
    -
    ${this.host.activeBundle?.areaLabel?`${this.host.activeBundle.areaLabel}s`:e.localGovernment?"DEAs":"Constituencies"}
    ${w(n.length)}
    -
    Matched
    ${w(e.coverage.matched)}
    -
    Unmatched
    ${w(e.coverage.unmatched)}
    - ${e.totals.totalSeats?`
    Seats
    ${w(e.totals.totalSeats)}
    `:""} - ${e.totals.validPoll?`
    Valid poll
    ${w(e.totals.validPoll)}
    `:""} - ${e.totals.turnoutPct?`
    Turnout
    ${rt(e.totals.turnoutPct)}
    `:""} -
    -
    -
    - ${this.renderDataCoverageNotice()} - ${t==="candidate"?this.renderCandidateSummaryTable(i):t==="constituency"?this.renderConstituencySummaryTable(n):t==="local-party"?this.renderLocalPartySummaryTable(n):this.renderPartySummaryTable(s)} -
    - `}renderConstituencyResults(t,e="party"){if(typeof this.host.renderMainCompatibleConstituencyResults=="function")return this.host.renderMainCompatibleConstituencyResults(t,e);if(t.recallPetition)return this.renderRecallPetitionResult(t);let n=[...t.candidates||[]].sort((s,i)=>+!!i.elected-+!!s.elected||Number(i.finalVotes??i.firstPrefs??i.votes??0)-Number(s.finalVotes??s.firstPrefs??s.votes??0)),a=this.host.activeBundle?.areaLabel||(this.host.isLocalGovernmentElection()?"DEA":"Constituency");return` -
    - ${this.renderViewTabs([["party","By Party"],["counts","By Count"],["animation","Transfers"]],e)} -
    -
    ${a}
    ${L(t.constituency||"")}
    - ${this.host.isLocalGovernmentElection()&&t.localBody?`
    Council
    ${L(t.localBody)}
    `:""} - ${t.seatsTotal?`
    Seats
    ${w(t.seatsTotal)}
    `:""} - ${t.validPoll?`
    Valid poll
    ${w(t.validPoll)}
    `:""} - ${t.turnoutPct?`
    Turnout
    ${rt(t.turnoutPct)}
    `:""} - ${t.quota?`
    Quota
    ${w(t.quota)}
    `:""} - ${t.previous?`
    Previous winner
    ${L(t.previous.winnerParty||t.previous.leadingParty||"")}
    `:""} - ${t.deltas?.turnoutPct!==null&&t.deltas?.turnoutPct!==void 0?`
    Turnout change
    ${Rt(t.deltas.turnoutPct)}
    `:""} -
    - ${e==="counts"?this.renderCountTable(t,n):e==="animation"?this.renderAnimationNotice(t):n.length?this.renderCandidateResultTable(n):'

    No candidate-level result table is available for this entry.

    '} -
    - `}renderDistrictResults(t="party"){if(this.host.localBodyCount()>1)return this.renderCouncilResults(t);let e=this.host.currentResults(),n=this.withPartyDeltas(Q(e)),a=n.reduce((s,i)=>s+F(i.seats),0);return` -
    - ${this.renderViewTabs([["party","By Party"],["candidate","By Candidate"],["local-party","By Local Party"],["constituency","By DEA"]],t)} -
    -
    -
    District
    ${L(this.host.activeBundle.displayTitle||this.host.activeBundle.body)}
    -
    DEAs
    ${w(e.length)}
    - ${a?`
    Seats
    ${w(a)}
    `:""} - ${ht(e,"validPoll")?`
    Valid poll
    ${w(ht(e,"validPoll"))}
    `:""} -
    -
    -
    - ${this.renderDataCoverageNotice()} - ${t==="candidate"?this.renderCandidateSummaryTable(nt(e)):t==="local-party"?this.renderLocalPartySummaryTable(e):t==="constituency"?this.renderConstituencySummaryTable(e):this.renderDistrictPartyTable(n)} -
    - `}renderCouncilResults(t="party"){let e=this.host.currentResults(),n=this.withCouncilDeltas(Xt(e)),a=this.withPartyDeltas(Q(e));return` -
    - ${this.renderViewTabs([["party","By Party"],["council","By Council"],["candidate","By Candidate"],["local-party","By Local Party"],["constituency","By DEA"]],t)} -
    -
    -
    Councils
    ${w(n.length)}
    -
    DEAs
    ${w(e.length)}
    - ${a.reduce((s,i)=>s+F(i.seats),0)?`
    Seats
    ${w(a.reduce((s,i)=>s+F(i.seats),0))}
    `:""} - ${ht(e,"validPoll")?`
    Valid poll
    ${w(ht(e,"validPoll"))}
    `:""} -
    -
    -
    - ${this.renderDataCoverageNotice()} - ${t==="council"?this.renderCouncilSummaryTable(n):t==="candidate"?this.renderCandidateSummaryTable(nt(e)):t==="local-party"?this.renderLocalPartySummaryTable(e):t==="constituency"?this.renderConstituencySummaryTable(e):this.renderDistrictPartyTable(a)} -
    - `}renderPartySummaryTable(t=[]){return t.length?` -
    - - - ${t.map(e=>` - - - - `).join("")} -
    PartyStoodSeatsVotesShareChange
    ${w(e.stood)}${w(e.seats)}${w(e.votes)}${rt(e.share)}${ze(e.deltas?.seats,e.deltas?.votes)}
    -
    `:""}renderCandidateResultTable(t=[]){return` -
    - - - ${t.map(e=>` - - - - - `).join("")} -
    CandidatePartyFirst prefsChangeFinal votesStatus
    ${w(e.firstPrefs??e.votes??"")}${e.deltas?tt(e.deltas.firstPrefs):""}${w(e.finalVotes??e.firstPrefs??e.votes??"")}${e.elected?"Elected":L(e.status||"")}
    -
    `}renderCandidateSummaryTable(t=[]){return` -
    - - - ${t.map(e=>` - - - - - `).join("")} -
    CandidatePartyConstituency/DEAFirst prefs%ChangeStatus
    ${L(e.constituency||"")}${w(e.firstPrefs)}${rt(e.firstPrefPct)}${e.deltas?tt(e.deltas.firstPrefs):""}${e.elected?"Elected":L(e.status||"")}
    -
    `}renderConstituencySummaryTable(t=[]){return` -
    - - - ${t.map(e=>` - - - - `).join("")} -
    Constituency/DEAWinner/leadPartySeatsChangeTurnoutMajority
    ${L(e.winnerName||e.leadingName||"")}${ot(e.winnerParty||e.leadingParty||"",L)}${w(e.seatsWon??e.seatsTotal??"")}${e.deltas?tt(e.deltas.seatsWon):""}${rt(e.turnoutPct)}${w(e.majority)}
    -
    `}renderLocalPartySummaryTable(t=[]){let e=this.withLocalPartyDeltas(Yt(t));return e.length?` -
    - - - ${e.map(n=>` - - - - `).join("")} -
    PartyDEAStoodSeatsSeat changeFirst prefsVote changeDEA shareShare change
    ${w(n.stood)}${w(n.seats)}${n.deltas?tt(n.deltas.seats):""}${w(n.firstPrefs)}${n.deltas?tt(n.deltas.firstPrefs):""}${rt(n.share)}${n.deltas?.share!==null&&n.deltas?.share!==void 0?Rt(n.deltas.share):""}
    -
    `:'

    No local-party summary is available for this election.

    '}renderCouncilSummaryTable(t=[]){return` -
    - - - ${t.map(e=>` - - `).join("")} -
    CouncilDEAsLeading partySeatsSeat changeValid votesVote changeTurnoutTurnout change
    ${L(e.council)}${w(e.deas)}${ot(e.leadingParty||"",L)}${w(e.seats)}${e.deltas?tt(e.deltas.seats):""}${w(e.validPoll)}${e.deltas?tt(e.deltas.validPoll):""}${rt(e.turnoutPct)}${e.deltas?.turnoutPct!==null&&e.deltas?.turnoutPct!==void 0?Rt(e.deltas.turnoutPct):""}
    -
    `}renderDistrictPartyTable(t=[]){return` -
    - - - ${t.map(e=>` - - `).join("")} -
    PartyCandidatesSeatsSeat changeFirst prefsVote shareVote change
    ${w(e.stood)}${w(e.seats)}${e.deltas?tt(e.deltas.seats):""}${w(e.votes)}${rt(e.share)}${e.deltas?`${tt(e.deltas.votes)}${e.deltas.share!==null?` (${Rt(e.deltas.share)})`:""}`:""}
    -
    `}renderRecallPetitionOverview(t=[]){return` -
    -
    Petitions
    ${w(t.length)}
    Triggered
    ${w(t.filter(e=>Qt(e)).length)}
    Not triggered
    ${w(t.filter(e=>e.recallPetition&&!Qt(e)).length)}
    -
    ${t.map(e=>{let n=e.recallPetition||{},a=n.signed??n.signatures??e.leadingVotes??null,s=n.threshold??n.required??null,i=Number.isFinite(Number(a))&&Number.isFinite(Number(s))?Number(a)-Number(s):null;return``}).join("")}
    ConstituencySignedThresholdShortfall/SurplusOutcome
    ${w(a)}${w(s)}${i===null?"":tt(i)}${L(n.outcome||(Qt(e)?"By-election triggered":"Petition not successful"))}
    -
    `}renderCountTable(t,e=[]){let n=t.countNumbers?.length?t.countNumbers:[...new Set(e.flatMap(i=>(i.counts||[]).map(o=>o.count)))].sort((i,o)=>i-o);if(!n.length)return'

    No count-by-count data is available for this entry.

    ';let a=Ye(e,n),s=new Map((t.nonTransferable||[]).map(i=>[Number(i.count),i]));return` -
    -
    ${n.map(i=>``).join("")}${a.length?`${n.map(i=>``).join("")}`:""} - ${e.map(i=>this.renderCountCandidateRow(i,n,t)).join("")} - ${s.size?this.renderNonTransferableRow(s,n):""} -
    CandidatePartyCount ${w(i)}Status
    Count event${L(a.find(o=>o.count===i)?.label||"")}
    `}renderCountCandidateRow(t,e,n){let a=new Map((t.counts||[]).map(s=>[Number(s.count),s]));return`${L(t.name||"")}${ot(t.party||"",L)}${e.map(s=>{let i=a.get(Number(s));if(!i)return"";let o=i.total??i.firstPrefs,l=Number(i.transfers),c=this.host.countDetailedView?[n.validPoll&&Number.isFinite(Number(o))?`${rt(Number(o)/Number(n.validPoll)*100)} of valid poll`:"",Number.isFinite(l)&&l?`${tt(l)} transfer`:"",i.status?`${L(i.status)}`:""].filter(Boolean).join(""):"";return`${w(o)}${!this.host.countDetailedView&&l?` (${tt(l)})`:""}${c?`
    ${c}
    `:""}`}).join("")}${t.elected?"Elected":L(t.status||"")}${t.previous?`
    Previous: ${L(t.previous.status||"")}
    `:""}`}renderNonTransferableRow(t,e){return`Non-
    transferable${e.map(n=>{let a=t.get(Number(n));return a?`${w(a.total)}${this.host.countDetailedView&&Number.isFinite(Number(a.transfers))?`
    ${tt(a.transfers)} transfer
    `:""}`:""}).join("")}`}renderRecallPetitionResult(t){let e=t.recallPetition||{},n=e.signed??e.signatures??t.leadingVotes??null,a=e.threshold??e.required??null,s=e.electorate??t.electorate??null,i=e.triggered??(Number.isFinite(Number(n))&&Number.isFinite(Number(a))?Number(n)>=Number(a):null),o=Number.isFinite(Number(n))&&Number.isFinite(Number(a))?Number(a)-Number(n):null;return`
    Constituency
    ${L(t.constituency||"")}
    ${s?`
    Electorate
    ${w(s)}
    `:""}${a?`
    Threshold
    ${w(a)}
    `:""}${n?`
    Signed
    ${w(n)}
    `:""}${o!==null?`
    ${o<=0?"Above threshold":"Shortfall"}
    ${w(Math.abs(o))}
    `:""}${i!==null?`
    By-election triggered
    ${i?"Yes":"No"}
    `:""}${e.incumbent?`
    Incumbent
    ${L(e.incumbent)}
    `:""}${e.incumbentParty?`
    Incumbent party
    ${L(e.incumbentParty)}
    `:""}
    `}renderAnimationNotice(t){if(t.hasCountDetail&&t.animationPayload){let e=j(t.matchName||t.constituency||"");return`
    `}return'

    No transfer animation data is available for this entry.

    '}renderPartyEntity(t){return`
    Party Information

    ${L(t.name||"")}

    ${L(this.host.activeBundle.displayTitle||this.host.activeBundle.body)} - ${L(this.host.activeBundle.date)}

    Candidates stood${w(t.stood)}
    Candidates elected${w(t.elected)}
    First prefs${w(t.firstPrefs)}
    Final votes${w(t.finalVotes)}
    Constituencies/DEAs${w(t.constituencies?.length||0)}
    Share${rt(t.shareOfTotal)}
    ${this.renderCandidateSummaryTable((t.candidates||[]).map(e=>({...e,party:t.name,colour:t.colour,firstPrefs:e.firstPref})))}
    `}renderCandidateEntity(t){return`
    Candidate Information

    ${L(t.name||"")}

    ${L(t.party||"")}

    Appearances${w(t.appearances?.length||0)}
    Elected${w(t.electedCount)}
    First prefs${w(t.firstPrefs)}
    Final votes${w(t.finalVotes)}
    Constituencies/DEAs${w(t.constituencies?.length||0)}
    Share${rt(t.shareOfTotal)}
    ${(t.appearances||[]).map(e=>``).join("")}
    Constituency/DEAFirst prefsFinal votesStatus
    ${w(e.firstPref)}${w(e.finalVotes)}${L(e.status||"")}
    `}renderViewTabs(t,e){return`
    ${t.map(([n,a])=>``).join("")}
    `}renderDataCoverageNotice(){let t=Number(this.host.activeBundle?.unmatchedCount||0);return t?`
    ${w(t)} result ${t===1?"row is":"rows are"} not styled on the map because no exact converted geography match is available yet.
    `:""}withPartyDeltas(t=[]){let e=this.host.previousBundle?.results?.length?Q(this.host.previousBundle.results):[],n=new Map(e.map(a=>[j(a.party),a]));return t.map(a=>{let s=n.get(j(a.party));return{...a,previous:s,deltas:s?{seats:F(a.seats)-F(s.seats),votes:F(a.votes)-F(s.votes),share:a.share!==null&&s.share!==null?a.share-s.share:null}:null}})}withCouncilDeltas(t=[]){let e=this.host.previousBundle?.results?.length?Xt(this.host.previousBundle.results):[],n=new Map(e.map(a=>[j(a.council),a]));return t.map(a=>{let s=n.get(j(a.council));return{...a,previous:s,deltas:s?{seats:F(a.seats)-F(s.seats),validPoll:F(a.validPoll)-F(s.validPoll),turnoutPct:a.turnoutPct!==null&&s.turnoutPct!==null?a.turnoutPct-s.turnoutPct:null}:null}})}withLocalPartyDeltas(t=[]){let e=this.host.previousBundle?.results?.length?Yt(this.host.previousBundle.results):[],n=new Map(e.map(a=>[`${j(a.party)}|${j(a.constituency)}`,a]));return t.map(a=>{let s=n.get(`${j(a.party)}|${j(a.constituency)}`);return{...a,previous:s,deltas:s?{seats:F(a.seats)-F(s.seats),firstPrefs:F(a.firstPrefs)-F(s.firstPrefs),share:a.share!==null&&s.share!==null?a.share-s.share:null}:null}})}};function w(r){if(r==null||r==="")return"";let t=Number(r);return Number.isFinite(t)?t.toLocaleString():String(r)}function rt(r){if(r==null||r==="")return"";let t=Number(r);return Number.isFinite(t)?`${t.toFixed(2).replace(/\.00$/,"")}%`:String(r)}function tt(r){let t=Number(r);return Number.isFinite(t)?`${t>0?"+":""}${t.toLocaleString()}`:""}function Rt(r){let t=Number(r);return Number.isFinite(t)?`${t>0?"+":""}${t.toFixed(2).replace(/\.00$/,"")}%`:""}function ze(r,t){return[tt(r),tt(t)].filter(Boolean).join(" / ")}function Ye(r=[],t=[]){let e=[];for(let n of t){let a=[],s=[];for(let o of r){let l=(o.counts||[]).find(d=>Number(d.count)===Number(n)),c=j(l?.status||"");/not elected/.test(c)||(/elected|quota/.test(c)&&Number(o.electedAt)===Number(n)&&a.push(o.name),/excluded|eliminated/.test(c)&&Number(o.excludedAt)===Number(n)&&s.push(o.name))}let i=[];a.length&&i.push(`${a.length===1?a[0]:`${a.length} candidates`} elected`),s.length&&i.push(`${s.length===1?s[0]:`${s.length} candidates`} excluded`),i.length&&e.push({count:Number(n),label:i.join("; ")})}return e}function Qt(r={}){let t=r.recallPetition||{};if(typeof t.triggered=="boolean")return t.triggered;let e=Number(t.signed??t.signatures??r.leadingVotes),n=Number(t.threshold??t.required);return Number.isFinite(e)&&Number.isFinite(n)?e>=n:!1}function L(r){return String(r??"").replace(/[&<>"']/g,t=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[t])}ct();var At=class{constructor(t){this.host=t,this.rendererId=t?.paneRendererId||"test2-main-pane-contract"}renderTitle(t=null){return t?.constituency?t.constituency:this.host.formatPaneElectionTitle()}renderHeaderRight(t=null,e="party"){let n=!!(t&&this.host.isCouncilAggregateResult?.(t)),a=!!(t&&!n&&this.host.isSingleSeatFptpResult?.(t)),s=!!this.host.isReferendumElection?.(t),i=(!t||n)&&this.host.isLocalGovernmentElection()?` -
    - - -
    - `:"",o=s?[["party","Full Results"]]:a?[["results","Results"]]:n?[["party","By Party"],["candidate","By Candidate"],["local-party","By Local Party"]]:[["party","By Party"],["counts",this.host.isForumResult(t)?"By Round":"By Count"]];return!a&&!n&&t&&this.host.resultHasAnimation(t)&&o.push(["animation",this.host.isForumResult(t)?"Allocation":"Transfers"]),t&&!o.some(([c])=>c==="trends")&&o.push(["trends","Trends"]),` - ${i} - ${(t?o:s?[["party","Full Results"],["constituency","By Constituency"],["trends","Trends"]]:[["party","By Party"],["candidate","By Candidate"],["local-party","By Local Party"],["trends","Trends"]]).map(([c,d])=>`${t&&!n&&c==="counts"?``:""}`).join("")} - - `}renderPanelContent(t=null,e="party"){let n=t?`${this.renderConstituencyResults(t,e)}${this.renderSourceNote(t)}`:this.renderOverallResults(e);return`
    ${n}
    `}renderSourceNote(t){let e=this.host.activeBundle?.provenance,n=t?.constituency||t?.localBody||"";if(!e||!n)return"";let a=e[n.toLowerCase().replace(/[^a-z0-9]+/g,"")],s=a?.source;if(!s?.url)return"";let i=(h,v)=>`${St(v)}`,o=i(s.url,s.title||s.publisher||s.host||"the source"),l=s.title&&s.publisher?` (${St(s.publisher)})`:"",c=s.scope==="this contest"||s.scope==="same section",d=s.checked&&c?`Source: ${o}${l}.`:s.checked?`Figures confirmed against ${o}${l}, a source for this election.`:a.status==="recorded"?`Imported from ${o}${l}.`:`Cited by Wikipedia: ${o}${l}. Not checked against these figures.`,y=s.archiveUrl?` ${i(s.archiveUrl,"Archived copy")}.`:"",u=a.relatedWikipedia?` ${i(a.relatedWikipedia,"Related Wikipedia article")}.`:"";return`
    ${d}${y}${u}
    `}renderOverallResults(t="party"){let e=this.host.currentResults();if(t==="trends")return this.host.renderTrendsPanel?.(null)||'

    No trend data is available.

    ';if(this.host.isTurnoutGeographyMode?.())return this.host.renderTurnoutGeographyPanel();if(e.some(i=>i.recallPetition))return this.host.renderRecallPetitionOverview(e);if(this.host.isLocalGovernmentElection()&&this.host.activeLocalMode==="district")return this.host.renderDistrictResults(t);let n=this.host.activeBundle.mainLikePartySummary?.length?this.host.activeBundle.mainLikePartySummary:this.host.activeBundle.partySummary?.length?this.host.activeBundle.partySummary:Q(e),a=this.host.withPartyDeltas(n,{mainLike:!!this.host.activeBundle.mainLikePartySummary?.length}),s=this.host.activeBundle.mainLikeCandidateSummary?.length?this.host.withCandidateDeltas(this.host.activeBundle.mainLikeCandidateSummary,{mainLike:!0}):this.host.withCandidateDeltas(nt(e));return this.host.isReferendumElection?.()?` - ${this.host.renderDataCoverageNotice()} - ${t==="constituency"?this.host.renderReferendumConstituencySummaryTable(e):this.host.renderMainParityPartyTable(a,e,{referendum:!0})} - ${this.host.renderMapDisplayControls()} - `:` - ${this.host.renderDataCoverageNotice()} - ${t==="candidate"?this.host.renderCandidateSummaryTable(s):t==="local-party"?this.host.renderLocalPartySummaryTable(e):this.host.renderMainParityPartyTable(a,e)} - ${this.host.renderMapDisplayControls()} - `}renderConstituencyResults(t,e="party"){if(e==="trends")return this.host.renderTrendsPanel?.(t)||'

    No trend data is available.

    ';if(this.host.isTurnoutGeographyMode?.())return this.host.renderTurnoutConstituencyDetail(t);if(this.host.isCouncilAggregateResult?.(t))return this.host.renderCouncilAggregateResults(t,e);if(t.recallPetition)return this.host.renderRecallPetitionResult(t);let n=[...t.candidates||[]].sort((s,i)=>{let o=+!!i.elected-+!!s.elected;return o||Number(i.finalVotes??i.firstPrefs??i.votes??0)-Number(s.finalVotes??s.firstPrefs??s.votes??0)});if(this.host.isReferendumElection?.(t))return this.host.renderReferendumResultTable(n,t);if(this.host.isSingleSeatFptpResult?.(t))return this.host.renderSingleSeatFptpResultsTable?.(n,t)||this.host.renderConstituencyCandidateTable(n,t);let a=e==="animation"&&!this.host.resultHasAnimation(t)?"counts":e;return` - ${a==="counts"?this.host.renderCountTable(t,n):a==="animation"?this.host.renderAnimationNotice(t):a==="party"?this.host.renderConstituencyPartyTable(n,t):this.host.renderConstituencyCandidateTable(n,t)} - `}renderEntityPanel(t,e){return t==="candidate"?this.host.renderCandidateEntity(e):this.host.renderPartyEntity(e)}};function St(r){return String(r??"").replace(/[&<>"']/g,t=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[t])}var Xe="/render/metadata/elections-test2.json?v=test-023";function Vt(){try{let r=new URLSearchParams(window.location.search).get("electionsApi");return r==="1"||r==="true"?!0:!(r==="0"||r==="false"||window.localStorage?.getItem("civgraph.electionsApi")==="0")}catch{return!0}}function ye(r){return Vt()?`/_api/elections?key=${encodeURIComponent(r.key)}&format=bundle&lite=1`:`${r.resultUrl}?v=test-023`}async function Qe(r){try{let t=await fetch(`/render/metadata/election-provenance/${encodeURIComponent(r)}.json`,{cache:"force-cache"});return t.ok&&(await t.json())?.contests||null}catch{return null}}function Jt(r,t,e){try{let n=JSON.stringify({source:"elections",metric:r,value:1,path:typeof window<"u"&&window.location&&window.location.pathname||"",event:{reason:String(t).slice(0,240),layerId:String(e||"")}}),a="/_api/rum";typeof navigator<"u"&&navigator.sendBeacon?navigator.sendBeacon(a,new Blob([n],{type:"application/json"})):fetch(a,{method:"POST",headers:{"Content-Type":"application/json"},body:n,keepalive:!0})}catch{}}var Ze=["winner","leadingParty","voteShare","turnout","majority","seats","quota"],pe="test2-election-seat-source",me="test2-election-seat-halo-layer",fe="test2-election-seat-layer",Je="test2-election-seat-overlay",ft="test2-election-vote-bar-source",vt="test2-election-vote-bar-layer",bt="test2-election-recall-label-source",gt="test2-election-recall-label-layer",Et=12,tn=Et+1,Mt=4,te=120,ve=18,en=4,nn=3,an=160,sn=40,on=260,rn=160,ln=90,ee=null,yt=Object.freeze({unmatchedFillColor:"#dfe4ec",unmatchedFillOpacity:.42,unmatchedStrokeColor:"#a1aab8",matchedFillOpacity:.6,matchedStrokeColor:"#333",strokeOpacity:.8,strokeWidth:1.5}),be={winner:"Winner",leadingParty:"Leading party",voteShare:"Vote share",turnout:"Turnout",majority:"Majority",seats:"Seats",quota:"Quota"},ae=new Map([["alliance","#f6cb2f"],["aontu","#44532a"],["conservative","#0087dc"],["dup","#d46a4c"],["fianna fail","#66bb66"],["fine gael","#6699ff"],["green","#22ac6f"],["green party","#22ac6f"],["independent","#b8b8b8"],["independent ireland","#3bee56"],["independent unionist","#aadfff"],["independent labour","#ff9999"],["independent nationalist","#cdffab"],["irish labour","#cc0000"],["labour","#cc0000"],["nationalist party","#32cd32"],["northern ireland labour party","#dc241f"],["pbp","#ff0090"],["people's democracy","#ff0000"],["republican clubs","#930c1a"],["republican labour party","#85de59"],["sdlp","#2aa82c"],["sinn fein","#326760"],["social democrats","#752f8b"],["solidarity pbp","#8e2420"],["solidarity-pbp","#8e2420"],["tuv","#0c3a6a"],["unionist party of northern ireland","#ffa07a"],["uup","#48a5ee"],["yes","#2aa82c"],["no","#d46a4c"]]),ge=new Map([["fianna fail","#66BB66"],["fine gael","#6699FF"],["sinn fein","#326760"],["labour","#CC0000"],["irish labour","#CC0000"],["the labour party","#CC0000"],["green comhaontas glas","#22AC6F"],["green party","#22AC6F"],["green","#22AC6F"],["social democrats","#752F8B"],["people before profit solidarity","#FF0090"],["pbp solidarity","#FF0090"],["solidarity people before profit","#8E2420"],["solidarity pbp","#8E2420"],["people before profit","#FF0090"],["aontu","#44532A"],["independent ireland","#3BEE56"],["progressive democrats","#1251A2"],["workers party republican clubs","#930C1A"],["independents 4 change","#FFC0CB"],["renua","#FFA500"],["independent","#DCDCDC"],["non party independent","#DCDCDC"],["yes","#43A047"],["no","#E53935"]]),Pe=class{constructor({app:t,mapController:e,onError:n}={}){this.app=t,this.mapController=e,this.onError=n,this.catalogue=null,this.activeEntry=null,this.activeBundle=null,this.previousBundle=null,this.activeMode="winner",this.overlayMode="circles",this.activePanelView="party",this.activeSelectedResultKey=null,this.activeEntityKind=null,this.activeEntityKey=null,this.activeEntityReturnView="party",this.activeLocalMode="dea",this.activeGeographyModeId=null,this.countDetailedView=!1,this.bundleCache=new Map,this.trendSummaryCache=new Map,this.trendSummaryPromiseCache=new Map,this.trendRenderCache=new Map,this.featureIndexCache=new Map,this.resultsByLayer=new Map,this.seatCircleClickBound=!1,this.seatCircleOverlay=null,this.seatCircleOverlayState={groups:[],dotCount:0},this.seatCircleMarkers=[],this.lastSeatCircleRenderMs=0,this.overlayRefreshPending=!1,this.seatCirclePositionUpdatePending=!1,this.overlayWorker=null,this.overlayWorkerSeq=0,this.overlayWorkerCallbacks=new Map,this.voteBarClickBound=!1,this.recallLabelClickBound=!1,this.overlayRefreshBound=!1,this.loadSerial=0,this.sharedRenderer=he(this),this.mainPaneContract=new At(this)}async load(){let t=await fetch(Xe,{cache:"force-cache"});if(!t.ok)throw new Error(`Failed to load the MapLibre election catalogue: ${t.status}`);return this.catalogue=await t.json(),this.catalogue}buildCatalogueCards(){return(this.catalogue?.elections||[]).map(t=>({...t,canonicalLayerId:this.getCanonicalLayerId(t),placeholder:!t.loadable&&!t.resultsOnly,displaySubtitle:this.getMainCatalogueSubtitle(t),displayProvider:this.getMainCatalogueProvider(t),displayTitle:t.displayTitle||t.body}))}getMainCatalogueProvider(t){return t?t.displayProvider&&t.displayProvider!==t.body?t.displayProvider:t.bodyGroup==="local-government"?"Local Government Districts":Ot(t.body):""}getMainCatalogueSubtitle(t){if(!t)return"";if(t.displaySubtitle)return t.displaySubtitle;let e=Array.isArray(t.constituencies)?t.constituencies:[];if(t.isByElection&&e.length)return e.join(", ");if(t.body==="European Parliament"&&e.filter(a=>a!=="Northern Ireland").length===0)return"Northern Ireland";if(t.bodyGroup==="local-government"){let a=Number(t.totalConstituencies??e.length);return`${Number.isFinite(a)?a:0} DEAs`}let n=Number(t.totalConstituencies??e.filter(a=>a!=="Northern Ireland").length);return`${Number.isFinite(n)?n:0} constituencies`}async loadElection(t,e){let n=++this.loadSerial,a=this.findEntry(t,e);if(!a)throw new Error(`Election not found: ${t} ${e}`);if(!a.loadable&&!a.resultsOnly)throw new Error(`${t} ${e} is in the election catalogue, but its geography is not converted for MapLibre yet.`);this.activeEntry&&(this.activeEntry.body!==t||this.activeEntry.date!==e)&&this.unloadElection(),this.renderLoadingPanel(a);let s=a.resultsOnly?Promise.resolve(null):this.app.loadMap(a.sourceMapId),i=this.loadBundle(a),o=this.loadPreviousBundle(a),l=i.then(y=>this.loadFeatureIndexForBundle(y)).catch(()=>null),[c,d]=await Promise.all([i,o,s,l]).then(([y,u])=>[y,u]);n===this.loadSerial&&(this.activeEntry=a,this.activeBundle=c,this.previousBundle=d,this.activeMode=a.stylingModes?.includes(this.activeMode)?this.activeMode:a.stylingModes?.find(y=>Ze.includes(y))||"winner",this.shouldRenderElectionOverlays()||(this.overlayMode="circles"),this.activePanelView="party",this.activeSelectedResultKey=null,this.activeEntityKind=null,this.activeEntityKey=null,this.activeEntityReturnView="party",this.activeLocalMode=a.bodyGroup==="local-government"?"dea":"constituency",this.activeGeographyModeId=this.defaultGeographyModeId(),this.countDetailedView=!1,this.indexBundle(c),await this.syncLocalGovernmentBackingLayers(),this.applyActiveStyle(),this.renderPanel(),await $n(),await this.renderElectionOverlay(),this.updateElectionTimeline(),this.announceUnmatchedGeography(a),this.app.syncCatalogueMapState(),this.app.updateActiveLayers(),a.sourceMapId&&this.app.refitAfterElectionPane?.(a.sourceMapId),this.app.focusActiveElectionCatalogueEntry?.(a,{scroll:!1}),this.app.updateURLState())}unloadElection(t={}){let{unloadBackingLayer:e=!0}=t||{},n=this.activeEntry?.sourceMapId,a=e?this.getActiveElectionBackingLayerIds():[];n&&this.mapController.clearElectionStyle?.(n),this.activeBundle?.councilSourceMapId&&this.mapController.clearElectionStyle?.(this.activeBundle.councilSourceMapId),this.removeElectionOverlays(),this.resultsByLayer.clear(),this.activeEntry=null,this.activeBundle=null,this.previousBundle=null,this.activeSelectedResultKey=null,this.activeEntityKind=null,this.activeEntityKey=null,this.activeEntityReturnView="party",this.removePanel(),this.unloadElectionBackingLayers(a),this.app.updateTimeline(),this.app.syncCatalogueMapState(),this.app.updateActiveLayers(),this.app.updateMapList?.(),this.app.updateURLState()}getActiveElectionBackingLayerIds(t=this.activeEntry,e=this.activeBundle){let n=Array.isArray(e?.geographyModes)?e.geographyModes.flatMap(a=>[a.sourceMapId,a.layerId]):[];return[...new Set([t?.sourceMapId,e?.sourceMapId,e?.layerId,e?.councilSourceMapId,e?.councilLayerId,...n].filter(Boolean))]}unloadElectionBackingLayers(t=[]){for(let e of t)(this.mapController.getLayerState?.(e)||this.mapController.groupStates?.has(e)||this.mapController.isLayerLoaded?.(e))&&this.mapController.unloadLayer(e)}async syncLocalGovernmentBackingLayers(){if(!this.isLocalGovernmentElection())return;let t=this.activeEntry?.sourceMapId||this.activeBundle?.sourceMapId,e=this.activeBundle?.councilSourceMapId||this.activeEntry?.councilSourceMapId;if(this.activeLocalMode==="district"&&e){this.mapController.isLayerLoaded?.(e)||await this.mapController.loadLayer(e,{fit:!1}),t&&this.mapController.isLayerLoaded?.(t)&&(this.mapController.clearElectionStyle?.(t),this.mapController.hideLayer?.(t)),this.mapController.showLayer?.(e);return}e&&this.mapController.isLayerLoaded?.(e)&&(this.mapController.clearElectionStyle?.(e),this.mapController.hideLayer?.(e)),t&&this.mapController.isLayerLoaded?.(t)&&this.mapController.showLayer?.(t)}isElectionLoaded(t,e){return this.activeEntry?.body===t&&this.activeEntry?.date===e}getURLState(){return this.activeEntry?{layerId:this.getCanonicalLayerId(this.activeEntry),body:this.activeEntry.body,date:this.activeEntry.date,mode:this.activeMode,overlay:this.overlayMode,view:this.activePanelView,localMode:this.activeLocalMode,geographyMode:this.activeGeographyModeId,selected:this.activeSelectedResultKey,countDetail:this.countDetailedView,entityKind:this.activeEntityKind,entityKey:this.activeEntityKey,entityReturnView:this.activeEntityReturnView}:null}async restoreURLState(t){let e=t.get("electionBody"),n=t.get("electionDate"),a=t.get("election"),s=null;if(a&&!e&&!n){let b=a.split(":");if(b.length>=2){let k=b[0];n=b[1],s=b.length>2?b[2]:null;let M=T=>String(T||"").toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s]+/g,"-").replace(/-+/g,"-"),_=(this.catalogue?.elections||[]).find(T=>M(T.body)===k&&T.date===n);_&&(e=_.body)}}if(!e||!n){let k=(t.get("layers")||"").split(",").map(M=>M.trim()).filter(Boolean).map(M=>this.findEntryByCanonicalLayerId(M)).find(Boolean);k&&(e=k.body,n=k.date)}if(!e||!n)return;await this.loadElection(e,n);let i=t.get("electionGeographyMode");i&&this.geographyModes().some(b=>b.id===i)&&await this.switchGeographyMode(i);let o=t.get("electionMode");o&&this.activeEntry?.stylingModes?.includes(o)&&(this.activeMode=o,this.applyActiveStyle()),this.overlayMode=t.get("electionOverlay")==="bars"?"bars":this.overlayMode,this.activeLocalMode=t.get("electionLocalMode")==="district"?"district":this.activeLocalMode,await this.syncLocalGovernmentBackingLayers(),this.applyActiveStyle();let l=t.has("electionSelected")||!!s,c=t.get("electionSelected")||s||"",d=l?this.findResultByKey(c):null,y=!!d,h=t.has("electionView")?t.get("electionView"):null,v=y?h||"party":h&&h!=="counts"&&h!=="animation"?h:"party";this.countDetailedView=y&&t.get("electionCountDetail")==="1",y||(this.activeSelectedResultKey=null,this.activeEntityKind=null,this.activeEntityKey=null,this.activeEntityReturnView=null),await this.renderElectionOverlay(),this.renderPanel(y?d:null,v);let E=t.get("electionEntityKind"),V=t.get("electionEntityKey");y&&E&&V&&(this.activeEntityReturnView=t.get("electionEntityReturnView")||v||"party",this.renderEntityPanel(E,V,{updateURL:!1})),this.app.focusActiveElectionCatalogueEntry?.(this.activeEntry,{scroll:!1})}async loadBundle(t){if(this.bundleCache.has(t.key))return this.bundleCache.get(t.key);let e=await fetch(ye(t),{cache:"force-cache"});if(!e.ok&&Vt()&&(console.warn(`[test2 elections] elections API returned ${e.status} for ${t.key}; falling back to the static bundle`),Jt("elections-api-fallback",`bundle fetch returned ${e.status}`,t.key),e=await fetch(`${t.resultUrl}?v=test-023`,{cache:"force-cache"})),!e.ok)throw new Error(`Failed to load election results for ${t.body} ${t.date}: ${e.status}`);let n=await e.json();return n.provenance=await Qe(t.key),It(this.bundleCache,t.key,n,en),n}async loadTrendSummary(t){if(!t?.key||!t.resultUrl)return null;if(this.trendSummaryCache.has(t.key))return this.trendSummaryCache.get(t.key);if(this.trendSummaryPromiseCache.has(t.key))return this.trendSummaryPromiseCache.get(t.key);let e=(async()=>{let n=null;if(this.activeEntry?.key===t.key&&this.activeBundle)n=this.activeBundle;else if(this.bundleCache.has(t.key))n=this.bundleCache.get(t.key);else{let s=await fetch(ye(t),{cache:"force-cache"});if(!s.ok)throw new Error(`Failed to load trend data for ${t.body} ${t.date}: ${s.status}`);n=await s.json()}let a=this.buildTrendSummary(t,n);return It(this.trendSummaryCache,t.key,a,an),a})();this.trendSummaryPromiseCache.set(t.key,e);try{return await e}finally{this.trendSummaryPromiseCache.delete(t.key)}}buildTrendSummary(t,e){let n=Array.isArray(e?.results)?e.results:[],a=o=>Q(o||[]).filter(l=>p(l.votes)>0||p(l.seats)>0).map(l=>({party:l.party,share:Number.isFinite(Number(l.share))?Number(l.share):0,votes:p(l.votes),seats:p(l.seats),colour:this.mainPanePartyColour(l.party,l.colour),entry:t})),s=new Map,i=new Map;for(let o of n){let l=a([o]);for(let d of pt(o))d&&s.set(d,l);let c=N(o.localBody||o.council||"");if(c){let d=i.get(c)||[];d.push(o),i.set(c,d)}}for(let[o,l]of i.entries())i.set(o,a(l));return{entry:t,overallRows:a(n),resultRowsByKey:s,localRowsByKey:i}}async loadPreviousBundle(t){if(!t?.previousKey)return null;let e=(this.catalogue?.elections||[]).find(n=>n.key===t.previousKey);if(!e?.resultUrl)return null;try{return await this.loadBundle(e)}catch(n){return console.warn("[test2 elections] Previous bundle unavailable",t.previousKey,n),null}}indexBundle(t){let e=new Map;for(let n of t.results||[])for(let a of pt(n))e.has(a)||e.set(a,n);t.layerId&&this.resultsByLayer.set(t.layerId,e),t.sourceMapId&&this.resultsByLayer.set(t.sourceMapId,e)}enrichFeature(t){if(!this.activeBundle||!t)return t;let e=this.resultsByLayer.get(t.mapId)||this.resultsByLayer.get(this.activeBundle.layerId)||this.resultsByLayer.get(this.activeBundle.sourceMapId),n=this.findResultForFeature(e,t);if(!n)return t;let a={...t.properties||{},Election:`${this.activeBundle.body} (${this.activeBundle.date})`,Constituency:n.constituency,"Winning party":n.winnerParty||"",Winner:n.winnerName||"","Leading party":n.leadingParty||"","Leading candidate":n.leadingName||"","Leading votes":$(n.leadingVotes),"Vote share":Z(n.leadingPct),Turnout:Z(n.turnoutPct),Majority:$(n.majority),"Majority share":Z(n.majorityPct),"Seats won":$(n.seatsWon),Seats:$(n.seatsTotal),Quota:$(n.quota),Electorate:$(n.electorate),"Valid poll":$(n.validPoll)};return{...t,featureName:t.featureName||n.constituency,name:t.name||n.constituency,electionResult:n,properties:a}}findResultForFeature(t,e){if(!this.activeBundle||!e)return null;let n=this.getActiveElectionStyleLayer?.()||this.activeBundle,a=n?.labelProperty||this.activeBundle.labelProperty,s=oe({id:n?.id||this.activeBundle.layerId,sourceMapId:n?.sourceMapId||this.activeBundle.sourceMapId,labelProperty:a},e.properties||{}),i=[e.featureName,e.name,s?.[a],s?.[this.activeBundle.councilLabelProperty],s?.[this.activeBundle.labelProperty],s?.name,s?.Name,s?.NAME,e.id];if(this.isLocalGovernmentElection()&&this.activeLocalMode==="district")for(let o of i){let l=this.findCouncilAggregateResultByName(o);if(l)return l}if(!t)return null;for(let o of i){let l=t.get(N(o));if(l)return l}return null}applyActiveStyle(){if(!this.activeEntry||!this.activeBundle)return;let t=this.getActiveElectionStyleLayer(),e=t?.sourceMapId||this.getActiveElectionStyleSourceMapId();if(!e)return;let n=this.buildColourExpression(this.activeMode,yt.unmatchedFillColor,t),a=t?.geometryType==="point";this.mapController.applyElectionStyle?.(e,{mode:this.activeMode,fillColorExpression:n,lineColorExpression:a?n:this.buildElectionMatchExpression(()=>yt.matchedStrokeColor,yt.unmatchedStrokeColor,t),fillOpacityExpression:a?void 0:this.buildElectionMatchExpression(()=>yt.matchedFillOpacity,yt.unmatchedFillOpacity,t),lineOpacity:a?void 0:yt.strokeOpacity,lineWidth:a?void 0:yt.strokeWidth,hideLabels:!0}),this.renderLegend()}getActiveElectionStyleSourceMapId(){if(this.isLocalGovernmentElection()&&this.activeLocalMode==="district")return this.activeBundle?.councilSourceMapId||this.activeEntry?.councilSourceMapId||this.activeEntry?.sourceMapId;let t=this.activeGeographyMode();return t?.sourceMapId?t.sourceMapId:this.activeEntry?.sourceMapId||this.activeBundle?.sourceMapId}getActiveElectionStyleLayer(){let t=this.getActiveElectionStyleSourceMapId();if(!t)return this.activeBundle;let e=this.mapController?.resolveLayer?.(t)||this.app?.metadataService?.getLayer?.(t)||null,n=this.activeGeographyMode();return n?.sourceMapId===t?e||{id:n.layerId,sourceMapId:t,labelProperty:n.labelProperty,geometryType:n.geometryType}:e||{id:this.isLocalGovernmentElection()&&this.activeLocalMode==="district"?this.activeBundle?.councilLayerId:this.activeBundle?.layerId,sourceMapId:t,labelProperty:this.isLocalGovernmentElection()&&this.activeLocalMode==="district"?this.activeBundle?.councilLabelProperty:this.activeBundle?.labelProperty,geometryType:this.isLocalGovernmentElection()&&this.activeLocalMode==="district"?this.activeBundle?.councilGeometryType:this.activeBundle?.geometryType}}buildElectionMatchInput(t=this.activeBundle){let e=t?.labelProperty||"name";return re({id:t?.id||this.activeBundle?.layerId,sourceMapId:t?.sourceMapId||this.activeBundle?.sourceMapId,labelProperty:e},["to-string",["get",e]])}buildElectionMatchExpression(t,e,n=this.activeBundle,a=this.activeBundle?.results||[]){let s=[],i=new Set;for(let o of a||[])if(!(!o.matched&&!(this.isLocalGovernmentElection()&&this.activeLocalMode==="district")))for(let l of un(o))for(let c of dn(l))i.has(c)||(i.add(c),s.push(c,t(o)));return s.length?["match",["to-string",this.buildElectionMatchInput(n)],...s,e]:e}buildColourExpression(t,e=yt.unmatchedFillColor,n=this.activeBundle){return this.isLocalGovernmentElection()&&this.activeLocalMode==="district"?this.buildCouncilColourExpression(t,e,n):this.buildElectionMatchExpression(a=>this.colourForMode(t,a),e,n,this.currentResults())}buildCouncilColourExpression(t,e,n=this.activeBundle){let s=Nt(this.currentResults()).map(i=>({constituency:i.council,matchName:i.council,featureAliases:$e(i.council),matched:!0,winnerParty:i.leadingParty,leadingParty:i.leadingParty,leadingColour:this.mainPanePartyColour(i.leadingParty,i.colour),colour:this.mainPanePartyColour(i.leadingParty,i.colour),leadingPct:i.share,seatsWon:i.seats,seatsTotal:i.seats,turnoutPct:i.turnoutPct}));return this.buildElectionMatchExpression(i=>this.colourForMode(t,i),e,n,s)}colourForMode(t,e){return t==="winner"?this.partyColourForResult(e,e.winnerParty,e.colour,{preferElected:!0})||"#6b7280":t==="leadingParty"?this.partyColourForResult(e,e.leadingParty,e.leadingColour)||"#6b7280":t==="turnout"?Ct(e.turnoutPct,35,80):t==="voteShare"?Ct(e.leadingPct,10,70):t==="majority"?Ct(e.majorityPct,0,45):t==="seats"?Ct(e.seatsWon??e.seatsTotal,1,6):t==="quota"?Ct(e.quota,1e3,12e4):"#6b7280"}usesMainRoiPartyPalette(){let e=[this.activeBundle?.body,this.activeEntry?.body,this.activeBundle?.bodyGroup,this.activeEntry?.bodyGroup,this.activeBundle?.jurisdiction,this.activeEntry?.jurisdiction,this.activeBundle?.region,this.activeEntry?.region,this.activeBundle?.id,this.activeEntry?.id,this.activeEntry?.key].map(n=>N(n)).join(" ");return!!(e.includes("dail")||e.includes("president of ireland")||e.includes("referendum ireland")||e.includes("european parliament ireland")||e.includes("republic of ireland")&&e.includes("european parliament")||e.includes("irish local"))}getElectionWidePercentLabel(){return`% of ${this.usesMainRoiPartyPalette()?"ROI":"NI"}`}mainPanePartyColour(t,e=""){let n=String(e||"").trim();if(n)return n;let a=N(t);if(!a)return"#6b7280";let i=(this.usesMainRoiPartyPalette()?ge:ae).get(a),o=U(t,""),l=ae.get(a);return i||o||l?i||o||l:this.usesMainRoiPartyPalette()?ge.get(a)||U(t)||jt(t)||"#b0bec5":U(t)||jt(t)||"#6b7280"}partyColourForResult(t={},e="",n="",a={}){let s=N(e),o=(Array.isArray(t?.candidates)?t.candidates:[]).filter(d=>N(d.party)===s),c=(a.preferElected?o.find(d=>d.elected&&d.colour):null)||o.find(d=>d.name===t.leadingName&&d.colour)||o.find(d=>d.name===t.winnerName&&d.colour)||o.find(d=>d.colour);return this.mainPanePartyColour(e,c?.colour||n)}renderPanel(t=null,e=null){let n=this.ensurePanel(),a=document.getElementById("electionPaneContent"),s=document.getElementById("electionPaneTitle"),i=document.getElementById("electionPaneBack");if(!n||!a||!s||!this.activeEntry||!this.activeBundle)return;let o=this.normalizePanelView(e||this.activePanelView||"party",t);this.activePanelView=o,this.activeSelectedResultKey=t?N(t.matchName||t.constituency||""):null,this.activeEntityKind=null,this.activeEntityKey=null,t&&this.hydrateSelectedResult(t).catch(c=>console.warn("[test2 elections] Could not load constituency count detail",c)),this.renderPanelTitle(s,t),i?.classList.toggle("hidden",!t);let l=n.querySelector(".election-pane__header-right");if(l&&(l.innerHTML=this.mainPaneContract.renderHeaderRight(t,o)),a.innerHTML=this.mainPaneContract.renderPanelContent(t,o),n.classList.add("election-results-pane--open"),document.body.classList.add("test2-election-open"),i?.addEventListener("click",()=>this.renderPanel(null,"party")),n.querySelector("#electionCloseBtn, #test2ElectionClose")?.addEventListener("click",()=>this.unloadElection()),n.querySelector("#test2ElectionMode")?.addEventListener("change",c=>{this.activeMode=c.target.value,this.applyActiveStyle()}),n.querySelector("#test2ElectionGeography")?.addEventListener("change",c=>{this.switchGeographyMode(c.target.value)}),n.querySelector("#test2ElectionOverlay")?.addEventListener("change",async c=>{this.overlayMode=c.target.value==="bars"?"bars":"circles",await this.renderElectionOverlay(),this.app.updateURLState()}),n.querySelectorAll("[data-election-local-mode]").forEach(c=>{c.addEventListener("click",async()=>{this.activeLocalMode=c.dataset.electionLocalMode==="district"?"district":"dea",await this.syncLocalGovernmentBackingLayers(),this.applyActiveStyle(),this.renderPanel(null,this.activeLocalMode==="district"?"party":this.activePanelView),this.renderElectionOverlay().catch(d=>console.warn("[test2 elections] Overlay refresh failed",d)),this.app.updateURLState()})}),n.querySelector("#test2ElectionCountDetail")?.addEventListener("click",()=>{this.countDetailedView=!this.countDetailedView,this.renderPanel(t,"counts"),this.app.updateURLState()}),n.querySelectorAll("[data-election-view]").forEach(c=>{c.addEventListener("click",()=>{this.renderPanel(t,c.dataset.electionView||"party"),this.app.updateURLState()})}),n.querySelectorAll("[data-election-result-key]").forEach(c=>{c.addEventListener("click",()=>{let d=this.findResultByKey(c.dataset.electionResultKey);d&&(this.renderPanel(d,"party"),this.app.updateURLState())})}),n.querySelectorAll("[data-election-entity]").forEach(c=>{c.addEventListener("click",async()=>{let d=String(c.dataset.electionEntity||"").toLowerCase(),y=c.dataset.electionEntityKey;if(await this.app.openElectionEntityDetailInCatalogue?.(d,y)){this.app.updateURLState();return}if(d==="party"||d==="candidate"||d==="person"){console.warn("[test2 elections] Catalogue entity detail unavailable",d,y);return}this.renderEntityPanel(d,y),this.app.updateURLState()})}),n.querySelector("[data-election-selected-area]")?.addEventListener("click",async c=>{let d=c.currentTarget;await this.app.openElectionEntityDetailInCatalogue?.(d.dataset.electionSelectedAreaKind,d.dataset.electionSelectedAreaKey)&&this.app.updateURLState()}),n.querySelectorAll("[data-election-animation]").forEach(c=>{c.addEventListener("click",()=>{let d=this.findResultByKey(c.dataset.electionAnimation);d&&this.runAnimation(d)})}),t&&o==="animation"&&this.resultHasAnimation(t)&&window.requestAnimationFrame(()=>this.runAnimation(t)),o==="trends"){let c=n.querySelector("#test2ElectionTrendsScope"),d=()=>{this.hydrateTrendsPanel(t,!!c?.checked).catch(y=>{let u=n.querySelector("#test2ElectionTrendsChart");u&&(u.innerHTML='

    Trend data could not be loaded.

    '),console.warn("[test2 elections] Trend render failed",y)})};c?.addEventListener("change",d),window.requestAnimationFrame(d)}this.renderLegend(),this.setupResultsTableControls(n)}normalizePanelView(t,e=null){let n=t||"party";return e&&this.isSingleSeatFptpResult(e)?n==="trends"?"trends":"results":this.isCouncilAggregateResult(e)?["party","candidate","local-party","trends"].includes(n)?n:"party":!e&&this.isLocalGovernmentElection()&&this.activeLocalMode==="district"?["party","candidate","local-party","trends"].includes(n)?n:"party":e||["party","candidate","local-party","constituency","trends"].includes(n)?n:"party"}renderPanelTitle(t,e=null){if(!t)return;if(!e?.constituency){t.textContent=this.mainPaneContract.renderTitle(e);return}let n=this.selectedResultEntityKind(e);t.innerHTML=` - - `}selectedResultEntityKind(){return this.isLocalGovernmentElection()?this.activeLocalMode==="district"?"lgd":"dea":"constituency"}isSingleSeatFptpResult(t={}){if(!t||t.recallPetition||this.isCouncilAggregateResult(t)||this.isForumResult(t))return!1;let e=N(t.contestType||this.activeBundle?.contestType||this.activeEntry?.contestType||"election");if(e&&e!=="election")return!1;let n=N(t.votingSystem||t.electionVotingSystem||t.system||this.activeBundle?.votingSystem||this.activeEntry?.votingSystem||"");if(n!=="fptp"&&n!=="first past the post"&&n!=="first past post")return!1;let a=[t.seatsTotal,t.seatsWon,t.seats,t.countInfo?.Number_Of_Seats,t.countInfo?.numberOfSeats,t.countInfo?.Seats].map(q).filter(i=>i!==null&&i>0);return a.length?Math.max(...a)===1:(t.candidates||[]).filter(i=>i.elected?!0:wt(i.status||i.Status)==="elected").length===1}isReferendumElection(t=null){return[t?.contestType,t?.type,t?.body,this.activeBundle?.contestType,this.activeEntry?.contestType,this.activeBundle?.body,this.activeEntry?.body,this.activeBundle?.key,this.activeEntry?.key].map(n=>N(n)).some(n=>n.includes("referendum"))}renderOverallResults(t="party"){return this.mainPaneContract.renderOverallResults(t)}renderMainCompatibleOverallResults(t="party"){return this.mainPaneContract.renderOverallResults(t)}renderConstituencyResults(t,e="party"){return this.mainPaneContract.renderConstituencyResults(t,e)}renderMainCompatibleConstituencyResults(t,e="party"){return this.mainPaneContract.renderConstituencyResults(t,e)}renderMainParityPartyTable(t=[],e=[],n={}){if(!t.length)return'
    No results data available.
    ';if(n.referendum||this.isReferendumElection())return this.renderReferendumFullResultsTable(t,e);let a=this.orderPartyRowsLikeMain(t),s=n.ignoreMainLikeTotals?null:n.totals||this.activeBundle?.mainLikeTotals||null,i=Number.isFinite(Number(s?.totalSeats))?Number(s.totalSeats):t.reduce((x,D)=>x+p(D.seats),0),o=Number.isFinite(Number(s?.validPoll))?Number(s.validPoll):K(e,"validPoll")||t.reduce((x,D)=>x+p(D.votes),0),l=Number.isFinite(Number(s?.totalPoll))?Number(s.totalPoll):K(e,"totalPoll")||o+K(e,"spoiled"),c=Number.isFinite(Number(s?.totalElectorate))?Number(s.totalElectorate):K(e,"electorate"),d=Number.isFinite(Number(s?.totalSpoiled))?Number(s.totalSpoiled):K(e,"spoiled"),y=c?Math.max(0,c-l):0,u=Array.isArray(n.previousResults)?n.previousResults:null,h=Array.isArray(n.previousRows)?n.previousRows:u?Q(u):this.previousBundle?.mainLikePartySummary?.length?this.previousBundle.mainLikePartySummary:this.previousBundle?.partySummary?.length?this.previousBundle.partySummary:this.previousBundle?.results?.length?Q(this.previousBundle.results):[],v=u?null:this.previousBundle?.mainLikeTotals||null,E=h.reduce((x,D)=>x+p(D.seats),0),V=Number.isFinite(Number(v?.totalSeats))&&Number(v.totalSeats)>0?Number(v.totalSeats):E,b=Number.isFinite(Number(v?.validPoll))?Number(v.validPoll):u?K(u,"validPoll")||h.reduce((x,D)=>x+p(D.votes),0):this.previousBundle?.results?.length?K(this.previousBundle.results,"validPoll")||h.reduce((x,D)=>x+p(D.votes),0):0,k=Number.isFinite(Number(v?.totalPoll))?Number(v.totalPoll):u?K(u,"totalPoll")||b+K(u,"spoiled"):this.previousBundle?.results?.length?K(this.previousBundle.results,"totalPoll")||b+K(this.previousBundle.results,"spoiled"):0,M=Number.isFinite(Number(v?.totalElectorate))?Number(v.totalElectorate):u?K(u,"electorate"):this.previousBundle?.results?.length?K(this.previousBundle.results,"electorate"):0,_=Number.isFinite(Number(v?.totalSpoiled))?Number(v.totalSpoiled):u?K(u,"spoiled"):this.previousBundle?.results?.length?K(this.previousBundle.results,"spoiled"):0,T=M?Math.max(0,M-k):0,B=(x,D)=>D?x/D*100:0,S=B(l,c),P=B(o,c),C=B(d,c),R=B(y,c),f=B(k,M),g=B(b,M),A=B(_,M),O=B(T,M),I=Number(n.constituencyCount??this.activeBundle?.matchedCount??e.length??0);return` -
    -
    - - - - - - - - - - - ${this.renderMainParityLeafTh("No.",2,"Candidates")} - ${this.renderMainParityLeafTh("+/-",3,"Candidates change")} - ${this.renderMainParityLeafTh("No.",4,"Seats")} - ${this.renderMainParityLeafTh("+/-",5,"Seats change")} - ${this.renderMainParityLeafTh("%",6,"Seats percentage")} - ${this.renderMainParityLeafTh("+/-",7,"Seats percentage change")} - ${this.renderMainParityLeafTh("No.",8,"First preference votes")} - ${this.renderMainParityLeafTh("+/-",9,"First preference votes change")} - ${this.renderMainParityLeafTh("%",10,"First preference vote share")} - ${this.renderMainParityLeafTh("+/-",11,"First preference vote share change")} - - - - ${a.map((x,D)=>{let G=B(p(x.seats),i),z=x.previous?B(p(x.previous.seats),V):null,W=Number.isFinite(Number(x.share))?Number(x.share):B(p(x.votes),o),H=x.previous?B(p(x.previous.votes),b):null;return` - - - ${this.renderElectionEntityButton("party",x.party,this.partyLabel(x.party),"election-cell-wrap")} - - - - - - - - - - - - `}).join("")} - ${this.renderMainParitySummaryRow("Valid votes",I,i,"100.00%",0,o,o-b,P,P-g)} - ${this.renderMainParitySummaryRow("Turnout",null,null,null,null,l,l-k,S,S-f)} - ${this.renderMainParitySummaryRow("Spoiled",null,null,null,null,d,d-_,C,C-A)} - ${this.renderMainParitySummaryRow("Did not vote",null,null,null,null,y,y-T,R,R-O)} - ${this.renderMainParitySummaryRow("Electorate",null,null,null,null,c,c-M,100,0)} - -
    #PartyCandidatesSeats1st preferences
    ${m(lt(D))}${$(x.stood)}${Y(x.deltas?.stood)}${$(x.seats)}${Y(x.deltas?.seats)}${X(G)}${et(z===null?null:G-z)}${$(x.votes)}${Y(x.deltas?.votes)}${X(W)}${et(H===null?x.deltas?.share:W-H)}
    -
    -
    - `}referendumStats(t={},e=[]){let n=t?.countInfo||{},a=t?.mainLikeTotals||{},s=e.reduce((v,E)=>v+p(E.votes??E.firstPrefs??E.finalVotes??E.total),0),i=q(a.validPoll??t.validPoll??n.Valid_Poll)??(s||null),o=q(a.totalElectorate??t.electorate??n.Total_Electorate),l=q(a.totalPoll??t.totalPoll??n.Total_Poll),c=q(t.turnoutPct??t.turnout_pct??n.Turnout_Pct),d=l&&l>0?l:o!==null&&c!==null?Math.round(o*c/100):null,y=q(a.totalSpoiled??t.spoiled??n.Spoiled),u=y&&y>0?y:d!==null&&i!==null?Math.max(0,d-i):y,h=c??(o!==null&&d!==null&&o>0?d/o*100:null);return{validPoll:i,totalPoll:d,electorate:o,spoiled:u,turnoutPct:h}}referendumOutcomeRows(t=[],e=null){return t.map(n=>{let a=n.party||n.name||n.candidate||n.label||"",s=q(n.votes??n.firstPrefs??n.finalVotes??n.total)??0,i=q(n.share??n.firstPrefPct??n.constPct)??(e?s/e*100:null);return{outcome:a,votes:s,share:i,constituencies:q(n.seats??n.constituenciesWon??n.constituencies),colour:this.mainPanePartyColour(a,n.colour),elected:!!n.elected||wt(n.status||n.Status)==="elected"}}).filter(n=>n.outcome).sort((n,a)=>+!!a.elected!=+!!n.elected?+!!a.elected-+!!n.elected:p(a.votes)!==p(n.votes)?p(a.votes)-p(n.votes):String(n.outcome).localeCompare(String(a.outcome)))}referendumProposalResultText(t=null){return N(t?.outcome)==="yes"?"Proposal passed":"Proposal did not pass"}renderReferendumProposalRow(t=null,e=4){return t?` - - - - - ${m(this.referendumProposalResultText(t))} - - `:""}renderReferendumSummaryRow(t,e,n=null,a={}){if(e==null||e==="")return"";let s=a.strong?" election-cell-strong":"",i=Math.max(1,Number(a.labelColspan||2)),o=a.trailingCell?"":"";return` - - - - - ${m(t)} - ${$(e)} - ${n==null?"-":X(n)} - ${o} - - `}renderReferendumFullResultsTable(t=[],e=[]){let n=this.referendumStats({mainLikeTotals:this.activeBundle?.mainLikeTotals||{}},t),a=this.referendumOutcomeRows(t,n.validPoll);if(!a.length)return'
    No referendum result data available.
    ';let s=a[0]||null,i=n.electorate&&n.validPoll!==null?n.validPoll/n.electorate*100:null,o=n.totalPoll&&n.spoiled!==null?n.spoiled/n.totalPoll*100:null;return` -
    -
    - - - - - - - - - - - - - ${a.map((l,c)=>` - - - - - - - - - `).join("")} - ${this.renderReferendumProposalRow(s,4)} - ${this.renderReferendumSummaryRow("Valid votes",n.validPoll,i,{strong:!0})} - ${this.renderReferendumSummaryRow("Turnout",n.totalPoll,n.turnoutPct)} - ${this.renderReferendumSummaryRow("Spoiled",n.spoiled,o)} - ${this.renderReferendumSummaryRow("Electorate",n.electorate,100)} - -
    #OutcomeConstituenciesVotes%
    ${m(lt(c))}${this.renderElectionEntityButton("party",l.outcome,m(l.outcome),"election-cell-wrap")}${l.constituencies===null?"-":$(l.constituencies)}${$(l.votes)}${l.share===null?"-":X(l.share)}
    -
    -
    - `}renderReferendumResultTable(t=[],e={}){let n=this.referendumStats(e,t),a=this.referendumOutcomeRows(t,n.validPoll);if(!a.length)return'

    No referendum result table is available for this constituency.

    ';let s=a[0]||null,i=n.electorate&&n.validPoll!==null?n.validPoll/n.electorate*100:null,o=n.totalPoll&&n.spoiled!==null?n.spoiled/n.totalPoll*100:null;return` -
    - - - - - - - - - - - - - ${a.map((l,c)=>` - - - - - - - - - `).join("")} - ${this.renderReferendumProposalRow(s,4)} - ${this.renderReferendumSummaryRow("Valid votes",n.validPoll,i,{strong:!0,labelColspan:1,trailingCell:!0})} - ${this.renderReferendumSummaryRow("Turnout",n.totalPoll,n.turnoutPct,{labelColspan:1,trailingCell:!0})} - ${this.renderReferendumSummaryRow("Spoiled",n.spoiled,o,{labelColspan:1,trailingCell:!0})} - ${this.renderReferendumSummaryRow("Electorate",n.electorate,100,{labelColspan:1,trailingCell:!0})} - -
    #OutcomeVotes%Result
    ${m(lt(c))}${this.renderElectionEntityButton("party",l.outcome,m(l.outcome),"election-cell-wrap")}${$(l.votes)}${l.share===null?"-":X(l.share)}${l===s?`${m(this.referendumProposalResultText(s))}`:""}
    -
    - `}renderReferendumConstituencySummaryTable(t=[]){return t.length?` -
    - - - - - - - - - - - - - - - - - - ${t.map(n=>{let a=this.referendumStats(n,n.candidates||[]),s=this.referendumOutcomeRows(n.candidates||[],a.validPoll),i=s.find(d=>N(d.outcome)==="yes")||null,o=s.find(d=>N(d.outcome)==="no")||null,l=s[0]||null,c=i&&o?Math.abs(p(i.votes)-p(o.votes)):null;return{result:n,stats:a,outcomes:s,yes:i,no:o,winner:l,majority:c}}).sort((n,a)=>String(n.result.constituency||n.result.matchName||"").localeCompare(String(a.result.constituency||a.result.matchName||""),void 0,{numeric:!0,sensitivity:"base"})).map((n,a)=>{let s=n.result.constituency||n.result.matchName||n.result.featureName||"",i=n.winner;return` - - - - ${i?m(this.referendumProposalResultText(i)):"-"} - - - - - - - - - - `}).join("")} - -
    #ConstituencyResultYesYes %NoNo %MajoritySpoiledElectorateTurnout
    ${m(lt(a))}${n.yes?$(n.yes.votes):"-"}${n.yes?.share===null||n.yes?.share===void 0?"-":X(n.yes.share)}${n.no?$(n.no.votes):"-"}${n.no?.share===null||n.no?.share===void 0?"-":X(n.no.share)}${n.majority===null?"-":$(n.majority)}${n.stats.spoiled===null?"-":$(n.stats.spoiled)}${n.stats.electorate===null?"-":$(n.stats.electorate)}${n.stats.turnoutPct===null?"-":X(n.stats.turnoutPct)}
    -
    - `:'

    No constituency referendum results are available.

    '}renderConstituencyCandidateTable(t=[],e={}){if(!t.length)return'

    No candidate-level result table is available for this entry.

    ';let n=p(e.validPoll)||t.reduce((a,s)=>a+p(s.firstPrefs??s.votes),0);return` -
    - - - - - - - - - - - ${this.renderMainParityLeafTh("No.",3,"First preference votes")} - ${this.renderMainParityLeafTh("+/-",4,"First preference votes change")} - ${this.renderMainParityLeafTh("%",5,"First preference vote share")} - ${this.renderMainParityLeafTh("+/-",6,"First preference vote share change")} - ${this.renderMainParityLeafTh("No.",7,"Final count votes")} - ${this.renderMainParityLeafTh("Status",8,"Final count status")} - - - - ${t.map((a,s)=>{let i=p(a.firstPrefs??a.votes),o=Number.isFinite(Number(a.firstPrefPct))?Number(a.firstPrefPct):n?i/n*100:null,l=a.finalVotes??a.total??a.firstPrefs??a.votes,c=this.candidateDeltaForResultCandidate(a,e);return` - - - - ${this.renderElectionEntityButton("party",a.party,this.partyLabel(a.party),"election-cell-wrap")} - - - - - - - - `}).join("")} - -
    #CandidateParty1st preferencesFinal count
    ${m(lt(s))}${this.renderElectionEntityButton("candidate",`${a.name||a.candidate||a.id||""}|${a.party||""}`,a.name||a.candidate||"","election-cell-wrap")}${$(i)}${c.deltas?Y(c.deltas.firstPrefs):at()}${o===null?"":X(o)}${c.deltas?.firstPrefPct!==null&&c.deltas?.firstPrefPct!==void 0?et(c.deltas.firstPrefPct):at()}${$(l)}${a.elected?"Elected":m(a.status||"")}
    -
    - `}renderSingleSeatFptpResultsTable(t=[],e={}){if(!t.length)return'

    No result table is available for this entry.

    ';let n=p(e.validPoll)||t.reduce((u,h)=>u+p(h.firstPrefs??h.votes??h.finalVotes??h.total),0),a=this.buildMainStyleConstituencyPartyRows(e,t).rows||[],s=new Map(a.map(u=>[N(u.party),u])),i=this.findPreviousSelectedResult(e),o=i?this.buildMainStyleConstituencyPartyRows(i,i.candidates||[]).rows||[]:[],l=new Map(o.map(u=>[N(u.party),u])),c=!!i,d=this.isWestminsterElection(),y=t.map((u,h)=>{let v=this.candidateDeltaForResultCandidate(u,e),E=p(u.firstPrefs??u.votes??u.finalVotes??u.total),V=Number.isFinite(Number(u.firstPrefPct))?Number(u.firstPrefPct):n?E/n*100:null,b=u.elected?"elected":wt(u.status||u.Status),k=u.elected?"Elected":u.status||u.Status||(b==="elected"?"Elected":"Not elected"),M=v.deltas?.firstPrefs??null,_=v.deltas?.firstPrefPct??null,T=s.get(N(u.party)),B=l.get(N(u.party))||(c?{firstPrefs:0,pct:0}:null),S=T&&B?p(T.firstPrefs)-p(B.firstPrefs):null,P=T&&B&&T.pct!==null&&T.pct!==void 0&&B.pct!==null&&B.pct!==void 0?p(T.pct)-p(B.pct):null,C=_t(this.mainPanePartyColour(u.party,u.colour));return{candidate:u,index:h,votes:E,votePct:V,statusKind:b,statusText:k,candidateVoteDelta:M,candidatePctDelta:_,partyVoteDelta:S,partyPctDelta:P,colour:C,name:u.name||u.candidate||"",party:u.party||""}});return` -
    -
    - - - - - - - - ${d?'':''} - - - ${this.renderMainParityLeafTh("No.",3,"Votes")} - ${this.renderMainParityLeafTh("Party +/-",4,"Votes, party change")} - ${this.renderMainParityLeafTh("Candidate +/-",5,"Votes, candidate change")} - ${this.renderMainParityLeafTh("%",6,"Vote share")} - ${this.renderMainParityLeafTh("Party +/- %",7,"Vote share, party change")} - ${this.renderMainParityLeafTh("Candidate +/- %",8,"Vote share, candidate change")} - - - - ${y.map(u=>{let{candidate:h,index:v,votes:E,votePct:V,statusKind:b,statusText:k,partyVoteDelta:M,candidateVoteDelta:_,partyPctDelta:T,candidatePctDelta:B}=u;return` - - - - ${this.renderElectionEntityButton("party",u.party,this.partyLabel(u.party),"election-cell-wrap")} - - - - - - - ${d?``:``} - - `}).join("")} - -
    #CandidatePartyVotesElectedResult
    ${m(lt(v))}${this.renderElectionEntityButton("candidate",`${u.name||h.id||""}|${u.party||""}`,m(u.name),"election-cell-wrap")}${$(E)}${M==null?at():Y(M)}${_==null?at():Y(_)}${V===null?"":X(V)}${T==null?at():et(T)}${B==null?at():et(B)}${this.electedMark(b==="elected")}${m(k)}
    -
    - ${this.renderSingleSeatFptpVoteGraphic(y,n)} -
    - `}renderSingleSeatFptpVoteGraphic(t=[],e=0){let n=t.filter(i=>i.name||i.party||i.votes>0);if(!n.length)return"";let a=Math.max(1,...n.map(i=>p(i.votes))),s=n.reduce((i,o)=>i+p(o.votes),0);return` - - `}renderConstituencyPartyTable(t=[],e={}){if(!t.length)return'

    No party-level result table is available for this entry.

    ';let n=this.buildMainStyleConstituencyPartyRows(e,t),a=this.findPreviousSelectedResult(e),s=this.buildMainStyleConstituencyPartyRows(a,a?.candidates||[]),i=new Map(s.rows.map(b=>[N(b.party),b])),o=n.rows.map(b=>{let k=i.get(N(b.party))||{stood:0,seats:0,firstPrefs:0,pct:0};return{...b,stoodDelta:b.stood-p(k.stood),electedDelta:b.seats-p(k.seats),firstPrefsDelta:b.firstPrefs-p(k.firstPrefs),pctDelta:b.pct-p(k.pct)}}).sort((b,k)=>p(k.seats)!==p(b.seats)?p(k.seats)-p(b.seats):p(k.firstPrefs)!==p(b.firstPrefs)?p(k.firstPrefs)-p(b.firstPrefs):String(b.party||"").localeCompare(String(k.party||""))),l=Math.max(0,...o.map(b=>p(b.seats))),c=Math.max(0,...o.map(b=>p(b.firstPrefs))),d=(b,k)=>b!==null&&k!==null?b-k:null,y=d(n.validPoll,s.validPoll),u=d(n.totalPoll,s.totalPoll),h=d(n.spoiled,s.spoiled),v=d(n.didNotVote,s.didNotVote),E=d(n.electorate,s.electorate),V=(b,k)=>b!==null||k!==null;return` -
    - - - - - - - - - - - - - - - - - - ${o.map((b,k)=>{let M=b.seats===l&&l>0,_=b.firstPrefs===c&&c>0;return` - - - - - - - - - - - - - - `}).join("")} - - ${this.renderSelectedPartySummaryRow("Valid votes",n.totalStood,n.totalElected,n.validPoll,y,n.validPct,d(n.validPct,s.validPct))} - ${V(n.totalPoll,s.totalPoll)?this.renderSelectedPartySummaryRow("Turnout",null,null,n.totalPoll,u,n.turnoutPct,d(n.turnoutPct,s.turnoutPct)):""} - ${V(n.spoiled,s.spoiled)?this.renderSelectedPartySummaryRow("Spoiled",null,null,n.spoiled,h,n.spoiledPct,d(n.spoiledPct,s.spoiledPct)):""} - ${V(n.didNotVote,s.didNotVote)?this.renderSelectedPartySummaryRow("Did not vote",null,null,n.didNotVote,v,n.didNotVotePct,d(n.didNotVotePct,s.didNotVotePct)):""} - ${V(n.electorate,s.electorate)?this.renderSelectedPartySummaryRow("Electorate",null,null,n.electorate,E,100,0):""} - -
    #PartyStood+/-Elected+/-1st prefs+/-1st prefs %+/-
    ${m(lt(k))}${this.renderElectionEntityButton("party",b.party,this.partyLabel(b.party),"election-cell-wrap")}${$(b.stood)}${Y(b.stoodDelta)}${$(b.seats)}${Y(b.electedDelta)}${$(b.firstPrefs)}${Y(b.firstPrefsDelta)}${X(b.pct)}${Ee(b.pctDelta)}
    -No change in party control
    -
    - `}buildMainStyleConstituencyPartyRows(t={},e=[]){let n=Array.isArray(t?.countGroup)?t.countGroup:t?.animationPayload?.Constituency?.countGroup||[],a=t?.countInfo||{},s=p(a.Valid_Poll)||p(t?.validPoll),i=p(a.Total_Poll)||p(t?.totalPoll)||null,o=p(a.Total_Electorate)||p(t?.electorate)||null,l=p(a.Spoiled)||p(t?.spoiled)||null,c=o!==null&&i!==null?Math.max(0,o-i):null,d=new Map,y=new Set,u=new Set,h=new Map,v=new Map,E=n.length?n:e.map((_,T)=>({Candidate_Id:_.id||_.candidateId||String(T+1),candidateName:_.name||_.candidate||"",Count_Number:"1",Party_Name:_.party||"Independent/Other",Party_Colour:this.mainPanePartyColour(_.party,_.colour),Status:_.elected?"Elected":_.status||"",Total_Votes:_.firstPrefs??_.votes??0}));for(let _ of E){if(!hn(_))continue;let T=ce(_.Party_Name)||"Independent/Other",B=String(_.Candidate_Id||""),S=p(_.Total_Votes),P=parseInt(_.Count_Number,10)||1;if(d.has(T)||d.set(T,{party:T,colour:this.mainPanePartyColour(T,_.Party_Colour),stood:0,seats:0,firstPrefs:0,pct:0}),v.has(B)||v.set(B,{party:T,excluded:!1}),P===1&&!y.has(B)){y.add(B);let R=d.get(T);R.firstPrefs+=S,R.stood+=1}(!h.has(B)||S>p(h.get(B)?.votes))&&h.set(B,{party:T,votes:S});let C=wt(_.Status);C==="excluded"&&(v.get(B).excluded=!0),C==="elected"&&!u.has(B)&&(u.add(B),d.get(T).seats+=1)}let V=p(a.Number_Of_Seats??t?.seatsTotal??t?.seatsWon);V>0&&u.size!u.has(_)&&!v.get(_)?.excluded).sort((_,T)=>p(T[1]?.votes)-p(_[1]?.votes)).slice(0,V-u.size).forEach(([_,T])=>{u.add(_),d.has(T.party)&&(d.get(T.party).seats+=1)});let b=[...d.values()].map(_=>({..._,pct:s>0?_.firstPrefs/s*100:0})),k=b.reduce((_,T)=>_+p(T.stood),0),M=b.reduce((_,T)=>_+p(T.seats),0);return{rows:b,validPoll:s,totalPoll:i,electorate:o,spoiled:l,didNotVote:c,turnoutPct:o!==null&&i!==null&&o>0?i/o*100:null,validPct:o>0?s/o*100:0,spoiledPct:o!==null&&l!==null&&o>0?l/o*100:null,didNotVotePct:o!==null&&c!==null&&o>0?c/o*100:null,totalStood:k,totalElected:M}}findPreviousSelectedResult(t={}){let e=new Set(pt(t));return e.size&&(this.previousBundle?.results||[]).find(n=>pt(n).some(a=>e.has(a)))||null}renderSelectedPartySummaryRow(t,e,n,a,s,i,o){let l=s!=null,c=o!=null&&Number.isFinite(Number(o));return`-${m(t)}${e==null?"-":$(e)}${e==null?"-":Y(0)}${n==null?"-":$(n)}${n==null?"-":Y(0)}${a?$(a):"-"}${l?Y(s):"-"}${Number.isFinite(Number(i))?X(i):"-"}${c?Ee(o):"-"}`}renderMainParityLeafTh(t,e,n=""){let a=n||t;return`${m(t)}`}renderTwoLineHeader(t,e){return`${m(t)}${m(e)}`}renderElectionEntityButton(t,e,n,a=""){let s=m(t);return``}partyLabel(t){return ot(t,m)}partyCellAttrs(t,e=""){return` class="election-party-cell${e?` ${e}`:""}" style="--party-colour:${m(t||"transparent")}"`}colourTabStyle(t){return` style="--party-colour:${m(t||"transparent")}"`}isWestminsterElection(){return N(this.activeBundle?.body||this.activeEntry?.body||"")==="house of commons of the united kingdom"}electedMark(t){return t?'\u2713':'\u2715'}orderPartyRowsLikeMain(t=[]){return[...t].sort((e,n)=>{let a=p(n.seats)-p(e.seats);if(a)return a;let s=p(n.votes)-p(e.votes);return s||String(e.party||"").localeCompare(String(n.party||""),void 0,{numeric:!0,sensitivity:"base"})})}setupResultsTableControls(t){[...t?.querySelectorAll?.(".election-party-table, .election-count-table")||[]].forEach(n=>this.setupSingleResultsTableControls(n)),this.syncResultsTableStickyWidths(t),requestAnimationFrame(()=>this.syncResultsTableStickyWidths(t))}syncResultsTableStickyWidths(t){let e=[...t?.querySelectorAll?.(".election-party-table, .election-count-table")||[]];for(let n of e){let a=[...n.querySelectorAll("thead th, tbody td:nth-child(-n+4)")].filter(i=>{let o=getComputedStyle(i);return o.position==="sticky"&&o.left!=="auto"});if(!a.length)continue;a.forEach(i=>{i.style.position="static"});let s=a.map(i=>{let o=0;for(let l=i;l&&l!==n;l=l.offsetParent)o+=l.offsetLeft;return Math.max(0,Math.round(o))});a.forEach((i,o)=>{i.style.position="",i.style.left=`${s[o]}px`})}}setupSingleResultsTableControls(t){if(!t||t.dataset.tableControlsReady==="1")return;let e=t.querySelector("tbody"),n=[...t.querySelectorAll("thead th[data-leaf-col-idx]")],a=n.length?n:[...t.querySelectorAll("thead th")];if(!e||a.length===0)return;t.dataset.tableControlsReady="1";let s={col:null,dir:"default"},i=new Map,o=[...e.querySelectorAll("tr")].map((f,g)=>({row:f,idx:g})),l=o.filter(({row:f})=>!f.classList.contains("election-table-summary-row")&&!f.classList.contains("election-table-note-row")),c=o.filter(({row:f})=>!l.some(g=>g.row===f)),d=null,y=null,u=null,h=f=>{let g=String(f||"").replace(/,/g,"").replace(/%/g,"").replace(/[+\u2212]/g,O=>O==="\u2212"?"-":"+").trim();if(!g||g==="-"||g==="\uFFFD"||g.toLowerCase()==="n/a")return null;let A=Number(g);return Number.isFinite(A)?A:null},v=f=>{let g=String(f||"").trim().toLowerCase();if(!g)return null;let A=g.match(/^(\d+)(st|nd|rd|th)?$/);if(A)return Number(A[1]);let O=g.match(/count\s+(\d+)/);return O?Number(O[1]):null},E=(f,g)=>{let A=f.children[g];return A?A.textContent.trim():""},V=(f,g)=>{let A=Number(f?.dataset?.leafColIdx);return Number.isFinite(A)?A:g},b=(f,g)=>{let A=l.slice(0,40).map(({row:D})=>E(D,f)).filter(Boolean),O=A.filter(D=>h(D)!==null).length,I=A.filter(D=>v(D)!==null).length;return(g?.textContent||"").trim().toLowerCase().includes("rank")?"ordinal":A.length>0&&O/A.length>=.8?"numeric":A.length>0&&I/A.length>=.8?"ordinal":"text"},k=(f,g,A,O,I)=>{if(O==="default")return f.idx-g.idx;let x=E(f.row,A),D=E(g.row,A),G=0;if(I==="numeric"){let z=h(x),W=h(D);z!==null&&W!==null?G=z-W:z!==null?G=1:W!==null?G=-1:G=x.localeCompare(D,void 0,{numeric:!0,sensitivity:"base"})}else if(I==="ordinal"){let z=v(x),W=v(D);z!==null&&W!==null?G=z-W:G=x.localeCompare(D,void 0,{numeric:!0,sensitivity:"base"})}else G=x.localeCompare(D,void 0,{numeric:!0,sensitivity:"base"});return O==="asc"?G:-G},M=()=>{d&&d.remove(),y&&y.classList.remove("election-th-btn--open"),u&&(window.removeEventListener("resize",u),window.removeEventListener("scroll",u,!0)),d=null,y=null,u=null},_=(f,g,A)=>A{if(!f||!g)return;let A=8,O=4,I=Math.max(document.documentElement.clientWidth||0,window.innerWidth||0),x=Math.max(document.documentElement.clientHeight||0,window.innerHeight||0),D=document.querySelector(".app-header")?.getBoundingClientRect?.(),G=Math.max(A,Number.isFinite(D?.bottom)?Math.ceil(D.bottom)+A:A),z=Math.max(160,I-A*2),W=Math.max(96,x-G-A),H=Math.min(248,z),st=g.getBoundingClientRect();f.style.width=`${H}px`,f.style.maxWidth=`${z}px`,f.style.maxHeight=`${W}px`,f.style.overflow="hidden";let it=f.querySelector('[data-role="values"]');it&&(it.style.maxHeight="");let Pt=f.getBoundingClientRect(),mt=Math.max(0,x-st.bottom-A-O),ut=Math.max(0,st.top-G-O),dt=Math.min(Pt.height||W,W)>mt&&ut>mt,se=Math.max(96,Math.min(W,(dt?ut:mt)||W));if(f.style.maxHeight=`${se}px`,it){let ie=[...f.children],we=ie.filter(Ht=>Ht!==it).reduce((Ht,Ie)=>Ht+Ie.getBoundingClientRect().height,0),ke=Math.max(0,ie.length-1)*6;it.style.maxHeight=`${Math.max(48,se-we-ke-2)}px`}let Lt=f.getBoundingClientRect(),Be=_(st.right-Lt.width,A,I-Lt.width-A),Re=dt?st.top-Lt.height-O:st.bottom+O,Ae=_(Re,G,x-Lt.height-A);f.style.left=`${Be}px`,f.style.top=`${Ae}px`},B=f=>{let g=new Map;return l.forEach(({row:A})=>{let O=E(A,f);g.has(O)||g.set(O,O)}),[...g.values()].sort((A,O)=>A.localeCompare(O,void 0,{numeric:!0,sensitivity:"base"}))},S=()=>{let f=l.filter(({row:I})=>{for(let[x,D]of i.entries()){if(!(D instanceof Set)||D.size===0)continue;let G=E(I,x);if(!D.has(G))return!1}return!0}),g=s.col??V(a[0],0),A=a.find((I,x)=>V(I,x)===g)||a[0],O=b(g,A);f=[...f].sort((I,x)=>k(I,x,g,s.dir,O)),e.innerHTML="",f.forEach(({row:I})=>e.appendChild(I)),c.forEach(({row:I})=>e.appendChild(I)),requestAnimationFrame(()=>this.syncResultsTableStickyWidths(t.closest("#electionResultsPane")||t.parentElement)),a.forEach((I,x)=>{let D=I.querySelector("[data-table-filter-sort-indicator]");if(!D)return;let G=V(I,x),z=i.has(G)&&(i.get(G)?.size??0)>0,W=s.col===G&&s.dir!=="default";I.classList.toggle("election-th-btn--active",z||W),W&&s.dir==="asc"?D.innerHTML="↑":W&&s.dir==="desc"?D.innerHTML="↓":z?D.innerHTML="•":D.innerHTML="";let H=W?s.dir==="asc"?"sorted ascending":"sorted descending":z?"filtered":"";I.dataset.accessibleName||(I.dataset.accessibleName=I.getAttribute("aria-label")||I.querySelector(".election-th-label")?.textContent?.trim()||"column");let st=I.dataset.accessibleName;I.setAttribute("aria-label",`${st}${H?`, ${H}`:""}. Sort and filter`),I.tagName==="TH"&&!I.hasAttribute("scope")&&I.setAttribute("scope","col")})},P=(f,g)=>{M();let A=a[f],O=V(A,f),I=b(O,A),x=B(O),D=i.get(O),G=new Set(D instanceof Set?D:x),z=I==="numeric"?"Sort Smallest to Largest":I==="ordinal"?"Sort Lowest to Highest":"Sort A to Z",W=I==="numeric"?"Sort Largest to Smallest":I==="ordinal"?"Sort Highest to Lowest":"Sort Z to A",H=document.createElement("div");H.className="election-filter-menu",H.innerHTML=` - - - -
    - -
    - - -
    -
    - - `,document.body.appendChild(H),d=H,y=g,g.classList.add("election-th-btn--open");let st=H.querySelector('[data-role="values"]'),it=(mt="")=>{let ut=mt.trim().toLowerCase();st.innerHTML="",x.filter(J=>!ut||String(J).toLowerCase().includes(ut)).forEach(J=>{let dt=document.createElement("label");dt.className="election-filter-menu__value",dt.innerHTML=`${m(J||"(Blank)")}`;let qt=dt.querySelector("input");qt.addEventListener("change",()=>{qt.checked?G.add(J):G.delete(J)}),st.appendChild(dt)})};it(),T(H,g),u=()=>T(H,g),window.addEventListener("resize",u),window.addEventListener("scroll",u,!0);let Pt=H.querySelector(".election-filter-menu__search");Pt?.addEventListener("input",()=>{it(Pt.value||""),T(H,g)}),H.addEventListener("click",mt=>{let ut=mt.target.closest("button[data-action]");if(!ut)return;let J=ut.dataset.action;J==="sort-asc"?(s.col=O,s.dir="asc",S(),M()):J==="sort-desc"?(s.col=O,s.dir="desc",S(),M()):J==="reset-sort"?(s.col=null,s.dir="default",S(),M()):J==="select-all"?(x.forEach(dt=>G.add(dt)),it(Pt?.value||""),T(H,g)):J==="deselect-all"?(G.clear(),it(Pt?.value||""),T(H,g)):J==="clear-filter"?(i.delete(O),S(),M()):J==="apply"&&(G.size===0||G.size===x.length?i.delete(O):i.set(O,new Set(G)),S(),M())})},C=f=>{d&&(d.contains(f.target)||y&&y.contains(f.target)||M())},R=f=>{f.key==="Escape"&&M()};document.addEventListener("click",C),document.addEventListener("keydown",R),a.forEach((f,g)=>{let A=f.innerHTML;f.innerHTML="";let O=document.createElement("div");O.className="election-th-controls",(f.classList.contains("election-col-compact")||f.classList.contains("election-col-int")||f.classList.contains("election-col-delta")||f.classList.contains("election-col-delta-small")||f.classList.contains("election-col-delta-votes")||f.classList.contains("election-col-pct")||f.classList.contains("election-col-pct-main")||f.classList.contains("election-col-pct-small")||f.classList.contains("election-col-pct-delta-main")||f.classList.contains("election-col-pct-delta-small")||f.classList.contains("election-col-count")||f.classList.contains("election-col-status-count")||f.classList.contains("election-col-votes"))&&O.classList.add("election-th-controls--compact");let I=document.createElement("span");if(I.className="election-th-label",I.innerHTML=A,O.appendChild(I),!f.classList.contains("election-colour-col")){let x=document.createElement("span");x.className="election-th-indicator",x.setAttribute("data-table-filter-sort-indicator","1"),x.setAttribute("aria-hidden","true"),O.appendChild(x),f.classList.add("election-th--menu"),f.setAttribute("tabindex","0"),f.setAttribute("aria-haspopup","dialog"),f.setAttribute("title","Sort and filter");let D=()=>{d&&y===f?M():P(g,f)};f.addEventListener("click",G=>{G.target.closest("a, button, input, select, label")||(G.preventDefault(),G.stopPropagation(),D())}),f.addEventListener("keydown",G=>{G.key!=="Enter"&&G.key!==" "||(G.preventDefault(),D())})}f.appendChild(O)}),t.addEventListener("test2:dispose-table-controls",()=>{M(),document.removeEventListener("click",C),document.removeEventListener("keydown",R)},{once:!0}),S()}renderMainParitySummaryRow(t,e,n,a,s,i,o,l,c){return`-${m(t)}${e==null?"-":$(e)}-${n==null?"-":$(n)}-${a||"-"}${s==null?"-":et(s)}${i?$(i):"-"}${o==null?"-":Y(o)}${Number.isFinite(Number(l))?X(l):"-"}${c==null?"-":et(c)}`}renderMapDisplayControls(){let t=this.activeGeographyMode(),e=t?.stylingModes||this.activeEntry?.stylingModes||[],n=this.geographyModes(),a=n.length>1?` - - `:"",s=this.shouldRenderElectionOverlays()?` - - `:"";return!e.length&&!s&&!a?"":` -
    - Map display -
    - ${a} - ${e.length?``:""} - ${s} -
    -
    - `}renderTurnoutGeographyPanel(){let t=this.activeGeographyMode(),e=[...this.currentResults()].sort((i,o)=>(Number(o.turnoutPct)||0)-(Number(i.turnoutPct)||0)),n=Number(t?.overallTurnoutPct),a=t?.sourceUrl?` Source (ARK).`:"",s=e.map(i=>` - - ${m(i.constituency||i.featureName||"")} - ${Number.isFinite(Number(i.turnoutPct))?Z(Number(i.turnoutPct)):"-"} - `).join("");return` -
    -

    ${m(t?.note||"")}${a}

    -
    -
    - ${Number.isFinite(n)?`
    Overall turnout
    ${Z(n)}
    `:""} -
    Constituencies
    ${$(e.length)}
    -
    -
    -
    - - - ${s} -
    ConstituencyTurnout
    - ${this.renderMapDisplayControls()} -
    - `}renderTurnoutConstituencyDetail(t){let e=Number(t?.turnoutPct),n=this.activeGeographyMode();return` -
    -
    -
    ${m(t?.constituency||t?.featureName||"Constituency")}
    ${Number.isFinite(e)?`${Z(e)} turnout`:"Turnout not available"}
    -
    -

    ${m(n?.note||"")}

    -
    - `}formatPaneElectionTitle(){let t=Ot(this.activeBundle?.body||this.activeEntry?.body||""),e=Me(this.activeBundle?.date||this.activeEntry?.date||"");return[t,e].filter(Boolean).join(" - ")||this.activeBundle?.displayTitle||this.activeBundle?.body||""}isLocalGovernmentElection(){return(this.activeBundle?.bodyGroup||this.activeEntry?.bodyGroup)==="local-government"}geographyModes(){let t=this.activeBundle?.geographyModes;return Array.isArray(t)&&t.length>1?t:[]}defaultGeographyModeId(){let t=this.geographyModes();return t.length?t[0].id:null}activeGeographyMode(){let t=this.geographyModes();return t.length?t.find(e=>e.id===this.activeGeographyModeId)||t[0]:null}isTurnoutGeographyMode(){return this.activeGeographyMode()?.dataKind==="turnout"}async switchGeographyMode(t){let e=this.geographyModes(),n=e.find(i=>i.id===t)||e[0];if(!n)return;let a=this.getActiveElectionStyleSourceMapId();this.activeGeographyModeId=n.id;let s=n.stylingModes||[];this.activeMode=s.includes(this.activeMode)?this.activeMode:n.defaultMode||s[0]||"winner",this.activeSelectedResultKey=null,a&&a!==n.sourceMapId&&this.mapController.clearElectionStyle?.(a),await this.syncGeographyBackingLayers(),this.applyActiveStyle(),this.renderPanel(null,"party"),this.renderElectionOverlay().catch(i=>console.warn("[test2 elections] Overlay refresh failed",i)),this.app.updateURLState()}async syncGeographyBackingLayers(){let t=this.geographyModes();if(!t.length)return;let e=this.activeGeographyMode();for(let n of t)n.sourceMapId&&(n.id===e?.id?(this.mapController.isLayerLoaded?.(n.sourceMapId)||await this.mapController.loadLayer(n.sourceMapId,{fit:!1}),this.mapController.showLayer?.(n.sourceMapId)):this.mapController.isLayerLoaded?.(n.sourceMapId)&&(this.mapController.clearElectionStyle?.(n.sourceMapId),this.mapController.hideLayer?.(n.sourceMapId)))}localBodyCount(){return Number(this.activeBundle?.localBodies?.length||this.activeEntry?.localBodies?.length||0)}isForumResult(t=null){return!!(t?.forum||t?.forumSequence||t?.allocationRounds)}resultHasAnimation(t=null){if(!t)return!1;if(this.isForumResult(t))return!0;let e=t.animationPayload?.Constituency?.countGroup||[],n=t.animationPayload?e.length:t.animationRowCount||0,a=t.animationPayload?e.some(s=>Number(s.Count_Number)>1):!!t.animationHasMultipleCounts;return t.syntheticCountGroup&&n||a||Array.isArray(t.countNumbers)&&t.countNumbers.some(s=>Number(s)>1)?!0:!!(t.hasCountDetail&&(t.candidates||[]).some(s=>(s.counts||[]).some(i=>Number(i.count)>1)))}currentResults(){let t=this.activeGeographyMode();if(t&&t.dataKind==="turnout")return t.results||[];let e=this.activeBundle?.results||[],n=this.previousBundle?.results||[];return n.length?Bt(e,n):e}renderTrendsPanel(t=null){let e=t?.constituency||t?.localBody||"",n=e?`Trend: ${e}`:"Election trends",a=Gt(this.activeEntry||this.activeBundle||{}),s=ne(this.activeEntry||this.activeBundle||{}),i=a?`Showing comparable ${a} contests${s?` in ${s}`:""} by default.`:`Showing comparable contests${s?` in ${s}`:""} by default.`;return` - - `}async hydrateTrendsPanel(t=null,e=!1){let n=document.getElementById("test2ElectionTrendsChart");if(!n||!this.activeEntry)return;let a=new Set(t?pt(t):[]),s=N(t?.localBody||t?.council||""),i=Gt(this.activeEntry),o=ne(this.activeEntry),l=a.size?[...a].sort().join("|"):s||"overall",c=[this.activeEntry.key||`${this.activeEntry.body}|${this.activeEntry.date}`,e?"all":i,o||"anywhere",l].join("::");if(this.trendRenderCache.has(c)){n.innerHTML=this.trendRenderCache.get(c);return}n.dataset.trendRequestKey=c,n.textContent="Loading trend data...";let d=(this.catalogue?.elections||[]).filter(v=>(v?.loadable||v?.resultsOnly)&&v.resultUrl&&N(v.contestType||"election")==="election").filter(v=>{let E=ne(v);return o&&E&&E!==o||e&&o&&!E||!e&&v.isByElection?!1:e||Gt(v)===i}).sort((v,E)=>String(v.date||"").localeCompare(String(E.date||""))),y=[],u=await Cn(d.slice(-80),6,async v=>{try{return await this.loadTrendSummary(v)}catch{return null}});for(let v of u){if(!v)continue;let E=v.overallRows||[];if(a.size){E=[];for(let V of a)if(v.resultRowsByKey.has(V)){E=v.resultRowsByKey.get(V);break}!E.length&&s&&v.localRowsByKey.has(s)&&(E=v.localRowsByKey.get(s))}else s&&v.localRowsByKey.has(s)&&(E=v.localRowsByKey.get(s));for(let V of E)y.push(V)}let h=this.renderTrendChart(y,t,e,d.length);It(this.trendRenderCache,c,h,sn),n.dataset.trendRequestKey===c&&(n.innerHTML=h)}renderTrendChart(t=[],e=null,n=!1,a=0){if(!t.length)return'

    No trend data is available for this selection.

    ';let s=new Map,i=[],o=new Map;for(let P of t){let C=P.entry?.key||`${P.entry?.body}|${P.entry?.date}`;o.has(C)||(o.set(C,P.entry),i.push(C));let R=N(P.party);s.has(R)||s.set(R,{party:P.party,colour:P.colour,points:new Map,maxShare:0,latestShare:0});let f=s.get(R);f.points.set(C,P),f.maxShare=Math.max(f.maxShare,p(P.share)),f.latestShare=p(P.share)}let l=[...s.values()].sort((P,C)=>p(C.latestShare)-p(P.latestShare)||p(C.maxShare)-p(P.maxShare)).slice(0,8),c=e&&(e.constituency||e.featureName)||"",d=c&&a>i.length+1?``:"",y=860,u=330,h={left:46,right:24,top:22,bottom:70},v=y-h.left-h.right,E=u-h.top-h.bottom,V=Math.max(40,Math.ceil(Math.max(...l.flatMap(P=>[...P.points.values()].map(C=>p(C.share))))/10)*10),b=P=>h.left+(i.length<=1?v/2:P/(i.length-1)*v),k=P=>h.top+E-p(P)/V*E,M=[0,10,20,30,40,50,60].filter(P=>P<=V).map(P=>{let C=k(P);return`${P}%`}).join(""),_=i.map((P,C)=>{if(i.length>14&&C%Math.ceil(i.length/10)!==0&&C!==i.length-1)return"";let R=o.get(P);return`${m(_e(R))}`}).join(""),T=l.map(P=>{let C=i.map((g,A)=>({key:g,index:A,point:P.points.get(g)})).filter(g=>g.point),R=C.map(g=>`${b(g.index).toFixed(1)},${k(g.point.share).toFixed(1)}`).join(" "),f=C.map(g=>Ln(_n(g.point.entry),b(g.index),k(g.point.share),_t(P.colour),`${P.party}: ${X(g.point.share)} at ${_e(g.point.entry)}`)).join("");return`${f}`}).join(""),B=l.map(P=>` - - ${m(P.party)} - - `).join(""),S=e?.constituency||e?.localBody||"overall results";return` - - - ${M} - - ${T} - ${_} - - - ${d} - `}formatNumberForPane(t){return $(t)}formatPercentForPane(t){return Z(t)}formatSignedPercentForPane(t){return Ne(t)}withPartyDeltas(t=[],e={}){let n=Array.isArray(e.previousRows)?e.previousRows:Array.isArray(e.previousResults)?Q(e.previousResults):e.mainLike&&this.previousBundle?.mainLikePartySummary?.length?this.previousBundle.mainLikePartySummary:this.previousBundle?.results?.length?Q(this.previousBundle.results):[],a=new Map(n.map(i=>[N(i.party),i])),s=n.length>0;return t.map(i=>{let o=a.get(N(i.party))||(s?{stood:0,seats:0,votes:0,share:0}:null);return{...i,previous:o,deltas:o?{stood:p(i.stood)-p(o.stood),seats:p(i.seats)-p(o.seats),votes:p(i.votes)-p(o.votes),share:i.share!==null&&o.share!==null?i.share-o.share:null}:null}})}candidateDeltasEligible(t={}){let e=N(t?.contestType||this.activeBundle?.contestType||this.activeEntry?.contestType||"election");if(e&&e!=="election")return!1;let n=N([t?.body,t?.title,t?.type,t?.contestType,t?.votingSystem,this.activeBundle?.body,this.activeBundle?.type,this.activeBundle?.votingSystem,this.activeEntry?.body,this.activeEntry?.displayTitle,this.activeEntry?.key,this.activeEntry?.votingSystem].filter(Boolean).join(" "));return!(/referendum|recall petition/.test(n)||/northern ireland forum|regional list|party list dhondt|party-list-dhondt|ordinal/.test(n))}candidateDeltaAreaKey(t={},e={}){return N(t.constituency||t.area||t.dea||t.district||t.localBody||e?.constituency||e?.matchName||e?.name||"")}candidateDeltaLookupKey(t={},e={}){let n=N(t.name||t.candidateName||t.candidate||t.Candidate_Name||t.Candidate||""),a=this.candidateDeltaAreaKey(t,e);return[n,a].filter(Boolean).join("|")}candidateFirstPrefValue(t={}){return p(t.firstPrefs??t.votes??t.finalVotes??t.total??t.Total_Votes)}candidateFirstPrefPct(t={},e={}){let n=t.firstPrefPct??t.votePct??t.constPct??t.share;if(Number.isFinite(Number(n)))return Number(n);let a=p(e?.validPoll);return a?this.candidateFirstPrefValue(t)/a*100:null}buildCandidateDelta(t={},e=null,n={},a={}){if(!e)return{previous:null,deltas:null};let s=this.candidateFirstPrefPct(t,n),i=this.candidateFirstPrefPct(e,a);return{previous:e,deltas:{firstPrefs:this.candidateFirstPrefValue(t)-this.candidateFirstPrefValue(e),firstPrefPct:s!==null&&i!==null?s-i:null}}}candidateDeltaForResultCandidate(t={},e={}){if(!this.candidateDeltasEligible(e))return{previous:null,deltas:null};let n=this.findPreviousSelectedResult(e);if(!n)return{previous:null,deltas:null};let a={...t,constituency:t.constituency||t.area||e?.constituency||e?.matchName||e?.name||""},s=this.candidateDeltaLookupKey(a,e);if(!s)return{previous:null,deltas:null};let i=t.previous&&this.candidateDeltaLookupKey(t.previous,n)===s?t.previous:null,o=Array.isArray(n.candidates)?n.candidates:[],l=i||o.find(c=>this.candidateDeltaLookupKey(c,n)===s)||null;return this.buildCandidateDelta(a,l,e,n)}withCandidateDeltas(t=[],e={}){if(!this.candidateDeltasEligible(e.result||{}))return t.map(i=>({...i,previous:i.previous||null,deltas:null}));let n=new Map((Array.isArray(e.previousResults)?e.previousResults:[]).map(i=>[this.candidateDeltaAreaKey({},i),i]).filter(([i])=>i)),a=Array.isArray(e.previousRows)?e.previousRows:Array.isArray(e.previousResults)?nt(e.previousResults):e.mainLike&&this.previousBundle?.mainLikeCandidateSummary?.length?this.previousBundle.mainLikeCandidateSummary:this.previousBundle?.results?.length?nt(this.previousBundle.results):[],s=new Map(a.map(i=>[this.candidateDeltaLookupKey(i),i]).filter(([i])=>i));return t.map(i=>{let o=this.candidateDeltaLookupKey(i),c=(i.previous&&this.candidateDeltaLookupKey(i.previous)===o?i.previous:null)||s.get(o)||null,d=c?n.get(this.candidateDeltaAreaKey(c))||{}:{},y=this.buildCandidateDelta(i,c,e.result||{},d);return{...i,previous:y.previous,deltas:y.deltas}})}withCouncilDeltas(t=[]){let e=this.previousBundle?.results?.length?Nt(this.previousBundle.results):[],n=new Map(e.map(a=>[N(a.council),a]));return t.map(a=>{let s=n.get(N(a.council));return{...a,previous:s,deltas:s?{seats:p(a.seats)-p(s.seats),validPoll:p(a.validPoll)-p(s.validPoll),turnoutPct:a.turnoutPct!==null&&s.turnoutPct!==null?a.turnoutPct-s.turnoutPct:null}:null}})}withLocalPartyDeltas(t=[],e={}){let n=Array.isArray(e.previousResults)?kt(e.previousResults):this.previousBundle?.results?.length?kt(this.previousBundle.results):[],a=new Map(n.map(i=>[`${N(i.party)}|${N(i.constituency)}`,i])),s=n.length>0;return t.map(i=>{let o=a.get(`${N(i.party)}|${N(i.constituency)}`)||(s?{stood:0,seats:0,seatShare:0,firstPrefs:0,share:0}:null);return{...i,previous:o,deltas:o?{stood:p(i.stood)-p(o.stood),seats:p(i.seats)-p(o.seats),seatShare:i.seatShare!==null&&o.seatShare!==null?i.seatShare-o.seatShare:null,firstPrefs:p(i.firstPrefs)-p(o.firstPrefs),share:i.share!==null&&o.share!==null?i.share-o.share:null}:null}})}renderDistrictResults(t="party"){let e=this.currentResults(),n=this.withPartyDeltas(Q(e)),a=this.withCandidateDeltas(nt(e)),s=this.withCouncilDeltas(Nt(e)),i=n.reduce((y,u)=>y+p(u.seats),0),o=K(e,"validPoll"),l=K(e,"totalPoll"),c=K(e,"electorate"),d=K(e,"spoiled");return` -
    - ${this.renderViewTabs([["party","By Party"],["candidate","By Candidate"],["local-party","By Local Party"],["constituency","By DEA"]],t)} -
    -
    -
    District
    ${m(this.activeBundle.displayTitle||this.activeBundle.body)}
    - ${this.localBodyCount()>1?`
    Councils
    ${$(s.length)}
    `:""} -
    DEAs
    ${$(e.length)}
    - ${i?`
    Seats
    ${$(i)}
    `:""} - ${o?`
    Valid poll
    ${$(o)}
    `:""} - ${l?`
    Total poll
    ${$(l)}
    `:""} - ${d?`
    Spoiled
    ${$(d)}
    `:""} - ${c?`
    Electorate
    ${$(c)}
    `:""} - ${c&&l?`
    Turnout
    ${Z(l/c*100)}
    `:""} -
    -
    -
    - ${this.renderDataCoverageNotice()} - ${t==="candidate"?this.renderCandidateSummaryTable(a):t==="local-party"?this.renderLocalPartySummaryTable(e):this.renderMainParityPartyTable(n,e)} -
    - `}isCouncilAggregateResult(t=null){return!t||!this.isLocalGovernmentElection()?!1:t.aggregateType==="council"||t.aggregateType==="district"}buildCouncilAggregateResult(t,e=null){let n=N(t);if(!n)return null;let a=this.currentResults().filter(c=>N(c.localBody||"")===n);if(!a.length)return null;let s=e||this.withCouncilDeltas(Nt(this.currentResults())).find(c=>N(c.council)===n),i=Q(a),o=s?.leadingParty||i[0]?.party||"",l=this.mainPanePartyColour(o,s?.colour||i[0]?.colour||"");return{aggregateType:this.localBodyCount()>1?"council":"district",constituency:t,matchName:t,featureName:t,featureAliases:$e(t),localBody:t,matched:!0,memberResults:a,winnerParty:o,leadingParty:o,winnerName:o,leadingName:o,leadingColour:l,colour:l,leadingPct:s?.share??i[0]?.share??null,seatsWon:s?.seats??i.reduce((c,d)=>c+p(d.seats),0),seatsTotal:s?.seats??a.reduce((c,d)=>c+p(d.seatsTotal??d.seatsWon),0),validPoll:s?.validPoll??K(a,"validPoll"),totalPoll:K(a,"totalPoll"),electorate:s?.electorate??K(a,"electorate"),spoiled:K(a,"spoiled"),turnoutPct:s?.turnoutPct??pn(a,"turnoutPct"),deas:s?.deas??a.length,previous:s?.previous||null,deltas:s?.deltas||null}}buildCouncilAggregateResults(){return this.withCouncilDeltas(Nt(this.currentResults())).map(t=>this.buildCouncilAggregateResult(t.council,t)).filter(Boolean)}findCouncilAggregateResultByName(t){let e=N(t);return e&&this.buildCouncilAggregateResults().find(n=>pt(n).includes(e))||null}previousResultsForCouncil(t){let e=N(t);return e?(this.previousBundle?.results||[]).filter(n=>N(n.localBody||"")===e):[]}renderCouncilAggregateResults(t,e="party"){let n=Array.isArray(t?.memberResults)?t.memberResults:[];if(!n.length)return'

    No council-level result data is available for this entry.

    ';let a=this.previousResultsForCouncil(t.constituency||t.localBody||t.matchName),s=this.withPartyDeltas(Q(n),{previousResults:a}),i=this.withCandidateDeltas(nt(n),{previousResults:a}),o=["party","candidate","local-party"].includes(e)?e:"party";return` - ${o==="candidate"?this.renderCandidateSummaryTable(i,{results:n,previousResults:a,widePercentLabel:"% of District"}):o==="local-party"?this.renderLocalPartySummaryTable(n,{previousResults:a,areaLabel:"DEA",districtPercentLabel:"% of District"}):this.renderMainParityPartyTable(s,n,{ignoreMainLikeTotals:!0,previousResults:a,constituencyCount:n.length,totalLabel:"Valid votes"})} - `}renderCouncilResults(t="party"){let e=this.currentResults(),n=this.withCouncilDeltas(Nt(e)),a=this.withPartyDeltas(Q(e)),s=nt(e),i=kt(e),o=a.reduce((d,y)=>d+p(y.seats),0),l=K(e,"validPoll"),c=K(e,"electorate");return` -
    - ${this.renderViewTabs([["party","By Party"],["council","By Council"],["candidate","By Candidate"],["local-party","By Local Party"],["constituency","By DEA"]],t)} -
    -
    -
    Councils
    ${$(n.length)}
    -
    DEAs
    ${$(e.length)}
    - ${o?`
    Seats
    ${$(o)}
    `:""} - ${l?`
    Valid poll
    ${$(l)}
    `:""} - ${c?`
    Electorate
    ${$(c)}
    `:""} -
    -
    -
    - ${this.renderDataCoverageNotice()} - ${t==="council"?this.renderCouncilSummaryTable(n):t==="candidate"?this.renderCandidateSummaryTable(s):t==="local-party"?this.renderLocalPartySummaryTable(e):t==="constituency"?this.renderConstituencySummaryTable(e):this.renderDistrictPartyTable(a)} -
    - `}renderCouncilSummaryTable(t=[]){return` -
    - - - - - - - - - - - - - ${this.renderMainParityLeafTh("No.",4,"Seats")} - ${this.renderMainParityLeafTh("+/-",5,"Seats change")} - ${this.renderMainParityLeafTh("No.",6,"Valid votes")} - ${this.renderMainParityLeafTh("+/-",7,"Valid votes change")} - ${this.renderMainParityLeafTh("%",8,"Turnout percentage")} - ${this.renderMainParityLeafTh("+/-",9,"Turnout change")} - - - - ${t.map((e,n)=>` - - - - - ${this.renderElectionEntityButton("party",e.leadingParty,this.partyLabel(e.leadingParty||""),"election-cell-wrap")} - - - - - - - - `).join("")} - -
    #CouncilDEAsLeading partySeatsValid votesTurnout
    ${m(lt(n))}${$(e.deas)}${$(e.seats)}${e.deltas?Y(e.deltas.seats):""}${$(e.validPoll)}${e.deltas?Y(e.deltas.validPoll):""}${Z(e.turnoutPct)}${e.deltas?.turnoutPct!==null&&e.deltas?.turnoutPct!==void 0?et(e.deltas.turnoutPct):""}
    -
    - `}renderDistrictPartyTable(t=[]){return` -
    - - - - ${t.map(e=>` - - - - - - - - - - `).join("")} - -
    PartyCandidatesSeatsSeat changeFirst prefsVote shareVote change
    ${$(e.stood)}${$(e.seats)}${e.deltas?Ft(e.deltas.seats):""}${$(e.votes)}${Z(e.share)}${e.deltas?`${Ft(e.deltas.votes)}${e.deltas.share!==null?` (${Ne(e.deltas.share)})`:""}`:""}
    -
    - `}renderRecallPetitionOverview(t=[]){return this.sharedRenderer.renderRecallPetitionOverview(t)}renderViewTabs(t,e){return this.sharedRenderer.renderViewTabs(t,e)}renderCandidateSummaryTable(t,e={}){if(!t.length)return'

    No candidate summary is available for this election.

    ';let n=this.isLocalGovernmentElection(),a=!n&&this.isWestminsterElection(),s=e.widePercentLabel||this.getElectionWidePercentLabel(),i=Array.isArray(e.results)?e.results:this.currentResults(),o=Array.isArray(e.previousResults)?e.previousResults:this.previousBundle?.results||[],l=K(i,"validPoll")||t.reduce((h,v)=>h+p(v.firstPrefs??v.votes),0),c=K(o,"validPoll")||(this.previousBundle?.mainLikeCandidateSummary||[]).reduce((h,v)=>h+p(v.firstPrefs??v.votes),0),d=[...t].sort((h,v)=>{let E=p(v.firstPrefPct)-p(h.firstPrefPct);return Math.abs(E)>1e-9?E:p(v.firstPrefs??v.votes)-p(h.firstPrefs??h.votes)||String(h.name||"").localeCompare(String(v.name||""),void 0,{numeric:!0,sensitivity:"base"})}),y=n?'Geography':'Constituency',u=n?7:a?5:6;return` -
    - - - - - - - ${y} - ${a?'':''} - - - - - ${n?'':""} - ${a?"":` - `} - - - - - - ${this.renderMainParityLeafTh("No.",u)} - ${this.renderMainParityLeafTh("+/-",u+1)} - ${this.renderMainParityLeafTh("%",u+2)} - ${this.renderMainParityLeafTh("+/-",u+3)} - ${this.renderMainParityLeafTh("%",u+4)} - ${this.renderMainParityLeafTh("+/-",u+5)} - - - - ${d.map((h,v)=>{let E=p(h.firstPrefs??h.votes),V=l>0?E/l*100:0,b=h.previous?p(h.previous.firstPrefs??h.previous.votes):null,k=h.previous&&c>0?b/c*100:null,M=h.deltas&&k!==null?V-k:null,_=h.elected?"Elected":h.excluded?"Excluded":h.status||"Not Elected",T=h.countDisplay||(h.electedAt||h.excludedAt||h.finalCount?`${h.electedAt||h.excludedAt||h.finalCount}/${h.countNumbers?.length||h.counts?.length||""}`.replace(/\/$/,""):""),B=h.localBody||h.council||h.district||"";return` - - - - ${this.renderElectionEntityButton("party",h.party,this.partyLabel(h.party),"election-cell-wrap")} - ${n?``:""} - - ${a?``:` - `} - - - - - - - - `}).join("")} - -
    #NamePartyElectedStatus1st preferences${m(s)}
    DistrictDEAOutcomeCountNo.%%
    ${m(lt(v))}${this.renderElectionEntityButton("candidate",`${h.name||h.id||""}|${h.party||""}`,m(h.name||""),"election-cell-wrap")}${m(B)}${this.electedMark(h.elected)}${_==="Elected"?"Elected":m(_)}${m(T)}${$(E)}${h.deltas?Y(h.deltas.firstPrefs):at()}${X(h.firstPrefPct)}${h.deltas?.firstPrefPct!==null&&h.deltas?.firstPrefPct!==void 0?et(h.deltas.firstPrefPct):at()}${X(V)}${M!=null?et(M):at()}
    -
    - `}renderConstituencySummaryTable(t){return this.sharedRenderer.renderConstituencySummaryTable(t)}renderLocalPartySummaryTable(t,e={}){let n=this.withLocalPartyDeltas(kt(t),e);if(!n.length)return'

    No local-party summary is available for this election.

    ';let a=e.areaLabel||(this.isLocalGovernmentElection()?"DEA":"Constituency"),s=this.isWestminsterElection()&&t.length>0&&t.every(o=>p(o.seatsTotal??o.seatsWon??1)<=1),i=s?8:10;return` -
    - - - - - - - - - - - - ${this.renderMainParityLeafTh("No.",4,"Candidates")} - ${this.renderMainParityLeafTh("+/-",5,"Candidates change")} - ${this.renderMainParityLeafTh("No.",6,"Seats")} - ${this.renderMainParityLeafTh("+/-",7,"Seats change")} - ${s?"":`${this.renderMainParityLeafTh("%",8,"Seats percentage")} - ${this.renderMainParityLeafTh("+/-",9,"Seats percentage change")}`} - ${this.renderMainParityLeafTh("No.",i,"First preference votes")} - ${this.renderMainParityLeafTh("+/-",i+1,"First preference votes change")} - ${this.renderMainParityLeafTh("%",i+2,"First preference vote share")} - ${this.renderMainParityLeafTh("+/-",i+3,"First preference vote share change")} - - - - ${n.map((o,l)=>` - - - - - - - - - - ${s?"":` - `} - - - - - - `).join("")} - -
    #Party${m(a)}CandidatesSeats1st preferences
    ${m(lt(l))}${this.renderElectionEntityButton("party",o.party,this.partyLabel(o.party),"election-cell-wrap")}${$(o.stood)}${o.deltas?Y(o.deltas.stood):""}${$(o.seats)}${o.deltas?Y(o.deltas.seats):""}${Z(o.seatShare)}${o.deltas?.seatShare!==null&&o.deltas?.seatShare!==void 0?et(o.deltas.seatShare):""}${$(o.firstPrefs)}${o.deltas?Y(o.deltas.firstPrefs):""}${Z(o.share)}${o.deltas?.share!==null&&o.deltas?.share!==void 0?et(o.deltas.share):""}
    -
    - `}renderDataCoverageNotice(){return this.sharedRenderer.renderDataCoverageNotice()}renderCountTable(t,e){let a=t.countNumbers?.length?t.countNumbers:[...new Set(e.flatMap(S=>(S.counts||[]).map(P=>P.count)))].sort((S,P)=>S-P);if(!a.length)return'

    No count-by-count data is available for this entry.

    ';let s=Sn(t),i=s?Tn(t,e,a):xn(e,a),o=s?Nn(t,e,a):{nonTransferable:new Map((t.nonTransferable||[]).map(S=>[Number(S.count),S])),transferDenominators:new Map},l=o.nonTransferable,c=o.transferDenominators,d=a.filter(S=>{let P=Number(S);return P<=1?!1:i.some(R=>Number(R.count)===P)||e.some(R=>{let f=(R.counts||[]).find(g=>Number(g.count)===P);return Math.abs(Number(f?.transfers)||0)>1e-4})?!0:Math.abs(Number(l.get(P)?.transfers)||0)>1e-4}),y=d.length+1,u=S=>{let P=Number(S)||1;return P<=1?1:1+d.filter(C=>Number(C)<=P).length},h=[...e].sort((S,P)=>{if(!t.syntheticCountGroup){let C=+!!P.elected-+!!S.elected;if(C)return C;let R=Number(S.electedAt||S.finalCount||999),f=Number(P.electedAt||P.finalCount||999);if(S.elected&&P.elected&&R!==f)return R-f}return p(P.finalVotes??P.firstPrefs??P.votes)-p(S.finalVotes??S.firstPrefs??S.votes)||String(S.name||"").localeCompare(String(P.name||""),void 0,{numeric:!0,sensitivity:"base"})}),v=p(t.validPoll),E=p(t.totalPoll),V=p(t.electorate),b=p(t.spoiled),k=Math.max(0,V-E),M=t.previous||{},_=S=>E>0?S/E*100:0,T=S=>V>0?S/V*100:0,B=(S,P,C,R,f)=>` - - - - - ${m(S)} - - - - - ${Number.isFinite(Number(C))?Y(P-C):at()} - ${X(R)} - ${this.countDetailedView?`${Number.isFinite(Number(f))?et(R-f):at()}`:""} - ${$(P)} - ${d.map(()=>this.countDetailedView?'----':'-').join("")} - - `;return` -
    - - - - - - - - - - - ${this.countDetailedView?``:""} - - ${d.map((S,P)=>{let C=i.find(f=>Number(f.count)===Number(S)),R=this.countDetailedView?9+P*4:8+P;return` - - ${this.countDetailedView?``:""} - `}).join("")} - - - - ${h.map((S,P)=>{let C=new Map((S.counts||[]).map(D=>[Number(D.count),D])),R=s?En(S,C,t,a):null,f=t.syntheticCountGroup?C.get(1):null,g=this.candidateDeltaForResultCandidate(S,t),A=t.syntheticCountGroup?p(f?.firstPrefs??f?.total):p(S.firstPrefs??S.votes),O=v>0?A/v*100:0,I=S.electedAt||S.excludedAt||S.finalCount||a[a.length-1],x=S.elected?`Elected
    Stage ${u(S.electedAt||S.finalCount||a[a.length-1])}/${y}`:S.excluded?`Excluded
    Stage ${u(S.excludedAt||S.finalCount||a[a.length-1])}/${y}`:`Not Elected
    Stage ${u(I)}/${y}`;return` - - - - - - - - - ${this.countDetailedView?``:""} - - ${d.map(D=>{let G=C.get(Number(D)),z=s?Kt(S,D,C,t,a,G):G;if(Mn(D,R))return this.countDetailedView?'':'';if(!z)return this.countDetailedView?'':'';let W=z.total??z.firstPrefs,H=Number(z.transfers),st=v>0?Number(W)/v*100:0,it=c.get(Number(D));return this.countDetailedView?``:``}).join("")} - - `}).join("")} - ${s||l.size?` - - - - - - - - - ${this.countDetailedView?'':""} - - ${d.map(S=>{let P=l.get(Number(S))||(s?{total:0,transfers:0}:null);if(!P)return this.countDetailedView?'':'';let C=c.get(Number(S));return this.countDetailedView?``:``}).join("")} - - `:""} - ${B("Valid votes",v,p(M.validPoll),_(v),_(p(M.validPoll)))} - ${B("Spoiled",b,p(M.spoiled),_(b),_(p(M.spoiled)))} - ${B("Turnout",E,p(M.totalPoll),T(E),T(p(M.totalPoll)))} - ${B("Did not vote",k,Math.max(0,p(M.electorate)-p(M.totalPoll)),T(k),T(Math.max(0,p(M.electorate)-p(M.totalPoll))))} - ${B("Electorate",V,p(M.electorate),100,100)} - -
    #NamePartyStatus${this.renderTwoLineHeader("1st","pref +/-")}${this.renderTwoLineHeader("1st","pref %")}${this.renderTwoLineHeader("1st","pref +/- %")}${this.renderTwoLineHeader("1st","pref")}${this.renderTwoLineHeader(this.countDetailedView?`Stage ${$(S)}`:"Stage",this.countDetailedView&&C?C.label:$(u(S)))}${this.renderTwoLineHeader(`Stage ${$(S)}`,"%")}${this.renderTwoLineHeader(`Stage ${$(S)}`,"+/- %")}${this.renderTwoLineHeader(`Stage ${$(S)}`,"+/-")}
    ${m(lt(P))}${this.renderElectionEntityButton("candidate",`${S.name||S.id||""}|${S.party||""}`,m(S.name||""),"election-cell-wrap election-cell-wrap--count-name")}${this.renderElectionEntityButton("party",S.party,this.partyLabel(S.party||""),"election-cell-wrap election-cell-wrap--count-party")}${x}${!t.syntheticCountGroup&&g.deltas?Y(g.deltas.firstPrefs):at()}${X(O)}${!t.syntheticCountGroup&&g.deltas?.firstPrefPct!==null&&g.deltas?.firstPrefPct!==void 0?et(g.deltas.firstPrefPct):at()}${$(A)}----- --- ${$(W)}${X(st)}${Se(H,it)}${H?Y(H):"-"}${$(W)}
    -Non-
    transferable
    ------ --- ${$(P.total)}${v>0?X(Number(P.total)/v*100):"-"}${Se(P.transfers,C)}${P.transfers?Y(P.transfers):"-"}${$(P.total)}
    -
    - `}renderRecallPetitionResult(t){return this.sharedRenderer.renderRecallPetitionResult(t)}renderAnimationNotice(t){return this.resultHasAnimation(t)&&(t.animationPayload||t.animationRowCount)?` -
    -
    Loading transfer animation...
    - -
    - `:this.sharedRenderer.renderAnimationNotice(t)}async ensureAnimationPayload(t,e=this.activeBundle){if(!t||t.animationPayload)return t?.animationPayload||null;if(!Vt())return null;let n=e?.key,a=(e?.results||[]).indexOf(t);if(!n||a<0)return null;try{let s=await fetch(`/_api/elections?key=${encodeURIComponent(n)}&constituency=${a}`,{cache:"force-cache"});if(!s.ok)return Jt("elections-api-animation-failed",`constituency fetch returned ${s.status}`,`${n}#${a}`),null;let i=await s.json();return i?.animationPayload&&(t.animationPayload=i.animationPayload,Array.isArray(t.countGroup)||(t.countGroup=i.animationPayload?.Constituency?.countGroup||[])),t.animationPayload||null}catch(s){return console.warn("[test2 elections] Could not load animation payload:",s),Jt("elections-api-animation-failed",s&&s.message?s.message:String(s),n),null}}async hydrateSelectedResult(t){if(!t||!Vt())return;this.countDetailRequested||(this.countDetailRequested=new WeakSet);let e=[],n=(s,i)=>{!s||Array.isArray(s.countGroup)||this.countDetailRequested.has(s)||(this.countDetailRequested.add(s),e.push(this.ensureAnimationPayload(s,i)))};if(n(t,this.activeBundle),n(this.findPreviousSelectedResult(t),this.previousBundle),!e.length)return;await Promise.all(e),this.activeSelectedResultKey===N(t.matchName||t.constituency||"")&&!this.activeEntityKind&&this.renderPanel(t,this.activePanelView)}fitAnimationToPane(){let e=document.getElementById("electionAnimationContainer"),n=document.getElementById("animation"),a=document.getElementById("electionPaneContent");if(!e||!n||!a)return;let s=e.querySelector(".ev-animation-top-row"),i=()=>{e.style.transform="",e.style.transformOrigin="",e.style.width="",e.style.marginRight="",e.style.marginBottom="",n.style.transform="",n.style.marginRight="",n.style.marginBottom="";let o=window.$?.(n)?.data?.("boundingBox"),l=getComputedStyle(e),c=(parseFloat(l.paddingLeft)||0)+(parseFloat(l.paddingRight)||0),d=(parseFloat(l.borderLeftWidth)||0)+(parseFloat(l.borderRightWidth)||0),y=Math.max((Number(o?.width)||0)+40,n.offsetWidth||0,n.scrollWidth||0),u=Math.ceil(Math.max(y,s?.scrollWidth||0)+c+d);if(!u)return;let h=a.getBoundingClientRect(),v=parseFloat(getComputedStyle(a).paddingRight)||0,E=Math.max(0,h.right-v-e.getBoundingClientRect().left-4),V=Math.min(1,E/u);if(V>=1)return;let b=Math.max(.45,V);e.style.width=`${u}px`,e.style.maxWidth="none";let k=e.offsetHeight;e.style.transformOrigin="0 0",e.style.transform=`scale(${b})`,e.style.marginRight=`${-u*(1-b)}px`,e.style.marginBottom=`${-k*(1-b)}px`};if(i(),this.animationResizeObserver?.disconnect(),typeof ResizeObserver=="function"){let o=0;this.animationResizeObserver=new ResizeObserver(()=>{cancelAnimationFrame(o),o=requestAnimationFrame(i)}),this.animationResizeObserver.observe(a)}}async runAnimation(t){let e=document.getElementById("electionAnimationContainer"),n=document.getElementById("test2ElectionAnimationStatus");if(e&&(await this.ensureAnimationPayload(t),!!t?.animationPayload)){try{await gn()}catch(a){n&&(n.textContent=`The election animation engine could not load: ${a.message}`);return}if(typeof window.$?.preloadElectionData!="function"||typeof window.animateStages!="function"){n&&(n.textContent="The election animation engine is not available on this route.");return}e.style.display="block",n&&(n.textContent="");try{window.$.preloadElectionData(t.animationPayload),window.animateStages({date:this.activeBundle?.date,electedBody:this.activeBundle?.body,constituency:t.constituency,maxWidth:Math.max(320,(document.getElementById("electionPaneContent")?.clientWidth||0)-16)}),this.fitAnimationToPane()}catch(a){console.error("[test2 elections] Animation failed",a),n&&(n.textContent=`Animation failed: ${a.message}`)}finally{window.$?.clearPreloadedData?.()}}}renderEntityPanel(t,e,n={}){let a=this.activeBundle?.entityIndex||Tt(this.currentResults()),s=t==="candidate"?(a.candidates||[]).find(d=>[d.id,d.key,d.personId].some(y=>y!=null&&String(y)===String(e))):(a.parties||[]).find(d=>N(d.name)===N(e));if(!s)return;let i=this.ensurePanel(),o=document.getElementById("electionPaneContent"),l=document.getElementById("electionPaneTitle"),c=document.getElementById("electionPaneBack");!i||!o||!l||(this.activeEntityKind=t,this.activeEntityKey=e,this.activeEntityReturnView=this.activePanelView||"party",this.activeSelectedResultKey=null,l.textContent=s.name||s.id||"Election entity",c?.classList.remove("hidden"),o.innerHTML=this.mainPaneContract.renderEntityPanel(t,s),c?.addEventListener("click",()=>{let d=this.activeEntityReturnView||"party";this.activeEntityKind=null,this.activeEntityKey=null,this.renderPanel(null,d),this.app.updateURLState()}),o.querySelectorAll("[data-election-result-key]").forEach(d=>{d.addEventListener("click",()=>{let y=this.findResultByKey(d.dataset.electionResultKey);y&&(this.renderPanel(y,"party"),this.app.updateURLState())})}),n.updateURL!==!1&&this.app.updateURLState())}renderPartyEntity(t){let e=this.getElectionWidePercentLabel();return` -
    -
    - -
    -
    Party Information
    -

    ${m(t.name||"")}

    -

    ${m(Ot(this.activeBundle.body||this.activeBundle.displayTitle||""))} - ${m(Me(this.activeBundle.date||""))}

    -
    -
    -
    -
    Candidates stood${$(t.stood)}
    -
    Candidates elected${$(t.elected)}
    -
    1st prefs${$(t.firstPrefs)}
    -
    ${m(e)}${Z(t.shareOfTotal)}
    -
    Final-round votes${$(t.finalVotes)}
    -
    Constituencies${$(t.constituencies?.length||0)}
    -
    -
    - - - ${(t.candidates||[]).map(n=>``).join("")} -
    CandidateConstituency1st prefs1st prefs %Final votesStatus
    ${m(n.name||"")}${m(n.constituency||"")}${$(n.firstPref)}${Z(n.firstPrefPct)}${$(n.finalVotes)}${m(n.status||"")}
    -
    -
    - `}renderCandidateEntity(t){let e=this.getElectionWidePercentLabel();return` -
    -
    - -
    -
    Candidate Information
    -

    ${m(t.name||"")}

    -

    ${m(t.party||"")}

    -
    -
    -
    -
    1st prefs${$(t.firstPrefs)}
    -
    ${m(e)}${Z(t.shareOfTotal)}
    -
    Final-round votes${$(t.finalVotes)}
    -
    Constituency count${$(t.constituencies?.length||0)}
    -
    Election wins${$(t.electedCount)}
    -
    Total valid poll${$(this.activeBundle?.mainLikeTotals?.validPoll||K(this.currentResults(),"validPoll"))}
    -
    -
    - - - - - - - - - ${this.renderMainParityLeafTh("No.",1,"First preference votes")} - ${this.renderMainParityLeafTh("%",2,"First preference vote share")} - ${this.renderMainParityLeafTh("No.",3,"Final count votes")} - ${this.renderMainParityLeafTh("Status",4,"Final count status")} - - - - ${(t.appearances||[]).map(n=>` - - `).join("")} - -
    Constituency / DEA1st preferencesFinal count
    ${$(n.firstPref)}${Z(n.firstPrefPct)}${$(n.finalVotes)}${m(n.status||"")}
    -
    -
    - `}showFeatureResults(t){return!this.activeBundle||!t?!1:t.electionResult?(this.renderPanel(t.electionResult),!0):this.isFeatureFromActiveElection(t)?(this.renderPanel(null,this.activePanelView||"party"),!0):!1}isFeatureFromActiveElection(t){if(!this.activeBundle||!t)return!1;let e=N(t.mapId||t.sourceMapId||t.layerId||"");return e?[this.activeBundle.layerId,this.activeBundle.sourceMapId,this.activeBundle.councilLayerId,this.activeBundle.councilSourceMapId,this.activeEntry?.sourceMapId,this.activeEntry?.layerId,this.activeEntry?.councilSourceMapId,this.activeEntry?.councilLayerId].some(n=>N(n||"")===e):!1}findResultByKey(t){let e=N(t);return e&&(this.currentResults().find(n=>pt(n).includes(e))||(this.isLocalGovernmentElection()?this.findCouncilAggregateResultByName(e):null))||null}renderLegend(){let t=document.getElementById("test2ElectionLegend");if(!t||!this.activeBundle)return;let e=this.activeMode;if(["winner","leadingParty"].includes(e)){let n=new Map;for(let a of this.activeBundle.results||[]){let s=e==="winner"?a.winnerParty:a.leadingParty;s&&n.set(s,this.mainPanePartyColour(s))}t.innerHTML=[...n.entries()].slice(0,12).map(([a,s])=>` - ${m(a)} - `).join("");return}t.innerHTML=` - - ${m(be[e]||e)}: low to high - `}ensurePanel(){let t=document.getElementById("electionResultsPane");return t?((!t.querySelector("#electionPaneTitle")||!t.querySelector("#electionPaneContent")||!t.querySelector("#electionPaneHeaderRight"))&&(t.innerHTML=` - -
    - -

    Election results

    -
    -
    -
    - `),t):null}renderLoadingPanel(t){let e=this.ensurePanel(),n=document.getElementById("electionPaneTitle"),a=document.getElementById("electionPaneContent"),s=document.getElementById("electionPaneBack");if(!e||!n||!a)return;n.textContent=t?.displayTitle||t?.body||"Election results",s?.classList.add("hidden");let i=e.querySelector(".election-pane__header-right");i&&(i.innerHTML='Loading election'),a.innerHTML=` -
    - Loading election results - Preparing the map layer, result bundle, labels, and seat circles. -
    - `,e.classList.add("election-results-pane--open"),document.body.classList.add("test2-election-open")}removePanel(){let t=document.getElementById("electionResultsPane");t?.classList.remove("election-results-pane--open"),t&&(t.innerHTML=""),document.body.classList.remove("test2-election-open")}async renderElectionOverlay(){if(this.removeElectionOverlays(),!!this.activeBundle&&!this.activeEntry?.resultsOnly){if(this.shouldRenderRecallLabels()){await this.renderRecallLabels();return}if(this.shouldRenderElectionOverlays()){if(this.bindOverlayRefresh(),this.overlayMode==="bars"){await this.renderVoteBars();return}await this.renderSeatCircles()}}}removeElectionOverlays(){this.removeSeatCircles(),this.removeVoteBars(),this.removeRecallLabels()}async renderSeatCircles(){let t=performance.now();if(this.lastSeatCircleRenderMs=0,!this.activeBundle||!this.shouldRenderElectionOverlays())return;let e=await this.loadFeatureIndex(),n=this.buildFeatureCentreLookup(e?.items||[]),a=this.mapController.map,s=this.buildSeatCircleGroups(n),i=await this.filterOverlayGroupsByCollisionAsync(s),o=this.ensureSeatCircleOverlay();if(o){o.innerHTML="",this.removeLegacySeatCircleLayers(),this.removeSeatCircleMarkers(),this.seatCircleOverlayState={groups:[],dotCount:0};for(let l of i){let{result:c,center:d,seats:y,positions:u,groupWidth:h,groupHeight:v}=l,E=a.project(d);if(!Number.isFinite(E?.x)||!Number.isFinite(E?.y))continue;let V=Math.min(...u.map(g=>g.x)),b=Math.min(...u.map(g=>g.y)),M=Math.max(...u.map(g=>g.x))-V+Et,_=Math.max(0,(h-M)/2),T=c.syntheticNonGeographic?ve+4:0,B=N(c.matchName||c.constituency||""),S=c.aggregateType||"",P=document.createElement("div");P.className=`election-seat-circle test2-election-seat-circle${c.syntheticNonGeographic?" test2-election-seat-circle--synthetic":""}`,P.tabIndex=0,P.role="button",P.dataset.resultKey=B,P.dataset.aggregateType=S,P.dataset.constituency=c.constituency||c.matchName||"",P.dataset.lng=String(d[0]),P.dataset.lat=String(d[1]),P.dataset.nonGeographic=c.syntheticNonGeographic?"true":"false",P.setAttribute("aria-label",`Show election result for ${c.constituency||c.matchName||"selected constituency"}`),P.style.width=`${h}px`,P.style.height=`${v}px`;let C=document.createElement("div");if(C.className="seat-group",C.style.position="relative",C.style.width=`${h}px`,C.style.height=`${v}px`,c.syntheticNonGeographic){let g=document.createElement("div");g.className="test2-election-synthetic-label",g.textContent=c.featureName||c.matchName||c.constituency||"Non-geographical constituency",g.title="Non-geographical constituency",g.style.position="absolute",g.style.left="0",g.style.top="0",g.style.width=`${h}px`,C.appendChild(g)}y.forEach((g,A)=>{let O=u[A];if(!O)return;let I=document.createElement("div");I.className="seat-dot test2-election-seat-dot",I.style.position="absolute",I.style.left=`${_+O.x-V}px`,I.style.top=`${T+O.y-b}px`,I.style.width=`${Et}px`,I.style.height=`${Et}px`,I.style.background=g.colour||this.mainPanePartyColour(g.party||c.winnerParty||c.leadingParty),I.title=`${g.name||"Elected candidate"} (${g.party||c.winnerParty||c.leadingParty||"Unknown party"})`,C.appendChild(I)}),P.appendChild(C);let R=()=>this.handleSeatCircleActivation(B,S);P.addEventListener("click",R),P.addEventListener("keydown",g=>{(g.key==="Enter"||g.key===" ")&&(g.preventDefault(),R())});let f=new xe.default.Marker({element:P,anchor:"center"}).setLngLat(d).addTo(a);this.seatCircleMarkers.push(f),this.seatCircleOverlayState.groups.push({key:B,aggregateType:S,constituency:c.constituency||c.matchName||"",seats:y.length,lng:Number(d[0]),lat:Number(d[1]),width:h,height:v,x:E.x,y:E.y}),this.seatCircleOverlayState.dotCount+=y.length}this.lastSeatCircleRenderMs=Math.round(performance.now()-t)}}ensureSeatCircleOverlay(){if(this.seatCircleOverlay?.isConnected)return this.seatCircleOverlay;let t=this.mapController?.map?.getContainer?.()||document.getElementById("map");if(!t)return null;let e=document.createElement("div");return e.id=Je,e.className="test2-election-seat-overlay",e.setAttribute("aria-label","Election seat circles"),t.appendChild(e),this.seatCircleOverlay=e,e}handleSeatCircleActivation(t,e=""){if(e==="council"||e==="district"){this.activeLocalMode="district";let a=this.findCouncilAggregateResultByName(t);this.renderPanel(a||null,"party"),this.app.updateURLState();return}let n=(this.activeBundle?.results||[]).find(a=>N(a.matchName||a.constituency)===t);n&&this.renderPanel(n)}removeLegacySeatCircleLayers(){let t=this.mapController?.map;t&&(t.getLayer(fe)&&t.removeLayer(fe),t.getLayer(me)&&t.removeLayer(me),t.getSource(pe)&&t.removeSource(pe))}getSeatCircleOverlayState(){return{groups:[...this.seatCircleOverlayState?.groups||[]],dotCount:Number(this.seatCircleOverlayState?.dotCount||0)}}async waitForSeatCircleOverlay(){return this.seatCircleMarkers?.length||this.seatCircleOverlayState?.dotCount?this.getSeatCircleOverlayState():(await this.renderSeatCircles(),this.getSeatCircleOverlayState())}removeSeatCircles(){this.removeLegacySeatCircleLayers(),this.removeSeatCircleMarkers(),this.seatCircleOverlay&&(this.seatCircleOverlay.remove(),this.seatCircleOverlay=null),this.seatCircleOverlayState={groups:[],dotCount:0}}removeSeatCircleMarkers(){for(let t of this.seatCircleMarkers||[])t.remove();this.seatCircleMarkers=[]}async renderVoteBars(){if(!this.activeBundle||!this.shouldRenderElectionOverlays())return;let t=await this.loadFeatureIndex(),e=this.buildFeatureCentreLookup(t?.items||[]),n=[];for(let i of this.activeBundle.results||[]){let o=i.anchor?.center||this.findCentreForResult(e,i);if(!o)continue;let l=Number(o[0]),c=Number(o[1]);if(!Number.isFinite(l)||!Number.isFinite(c))continue;let d=Math.max(8,Math.min(80,Number(i.leadingPct||i.majorityPct||0))),y=Math.max(.35,Math.cos(c*Math.PI/180)),u=(.008+d*55e-5)/y;n.push({type:"Feature",geometry:{type:"LineString",coordinates:[[l-u,c],[l+u,c]]},properties:{constituency:i.constituency||i.matchName||"",party:i.leadingParty||i.winnerParty||"",colour:this.mainPanePartyColour(i.leadingParty||i.winnerParty),share:d,resultKey:N(i.matchName||i.constituency||"")}})}if(!n.length)return;let a=this.mapController.map,s={type:"FeatureCollection",features:n};a.getSource(ft)?a.getSource(ft).setData(s):a.addSource(ft,{type:"geojson",data:s}),a.getSource(ft)._data=s,a.getLayer(vt)||a.addLayer({id:vt,type:"line",source:ft,paint:{"line-color":["coalesce",["get","colour"],"#6b7280"],"line-width":["interpolate",["linear"],["zoom"],5,4,9,8,12,13],"line-opacity":.92},layout:{"line-cap":"round"}}),this.voteBarClickBound||(this.voteBarClickBound=!0,a.on("click",vt,i=>{let o=i.features?.[0]?.properties?.resultKey,l=(this.activeBundle?.results||[]).find(c=>N(c.matchName||c.constituency)===o);l&&this.renderPanel(l)}),a.on("mouseenter",vt,()=>{this.mapController?.setMapCursor?.("pointer")}),a.on("mouseleave",vt,()=>{this.mapController?.setMapCursor?.("")}))}buildSeatCircleGroups(t){return this.activeBundle?.bodyGroup==="local-government"&&this.activeLocalMode==="district"?this.buildLocalAggregateSeatCircleGroups(t):(this.activeBundle?.results||[]).map(e=>this.createSeatCircleGroup(e,this.seatCandidatesForResult(e),e.anchor?.center||this.findCentreForResult(t,e),e.anchor?.bounds||null,Number(e.anchor?.area||0))).filter(Boolean)}buildLocalAggregateSeatCircleGroups(t){let e=new Map;for(let n of this.activeBundle?.results||[]){let a=this.localBodyCount()>1?n.localBody||"Unknown council":this.activeBundle.displayTitle||this.activeBundle.body||"District";e.has(a)||e.set(a,{result:{constituency:a,matchName:a,localBody:a,aggregateType:this.localBodyCount()>1?"council":"district",winnerParty:"",leadingParty:""},results:[],seats:[],bounds:null,centerAccumulator:{lng:0,lat:0,weight:0},area:0});let s=e.get(a);s.results.push(n),s.seats.push(...this.seatCandidatesForResult(n)),s.bounds=mn(s.bounds,n.anchor?.bounds||null);let i=n.anchor?.center||this.findCentreForResult(t,n),o=Math.max(1,Number(n.anchor?.area||1));Array.isArray(i)&&i.length>=2&&Number.isFinite(Number(i[0]))&&Number.isFinite(Number(i[1]))&&(s.centerAccumulator.lng+=Number(i[0])*o,s.centerAccumulator.lat+=Number(i[1])*o,s.centerAccumulator.weight+=o),s.area+=Number(n.anchor?.area||0)}return[...e.values()].map(n=>{let a=Q(n.results)[0]||null,s=this.buildCouncilAggregateResult(n.result.constituency||n.result.matchName);s?n.result={...s,aggregateType:n.result.aggregateType}:(n.result.winnerParty=a?.party||"",n.result.leadingParty=a?.party||"");let o=(s?this.findCentreForResult(t,s):null)||fn(n.bounds)||(n.centerAccumulator.weight?[n.centerAccumulator.lng/n.centerAccumulator.weight,n.centerAccumulator.lat/n.centerAccumulator.weight]:null);return this.createSeatCircleGroup(n.result,n.seats,o,n.bounds,n.area)}).filter(Boolean)}createSeatCircleGroup(t,e,n,a,s){if(!n||!e?.length)return null;let i=de(e.length,tn),o=Math.max(...i.map(h=>h.x))-Math.min(...i.map(h=>h.x))+Et,l=Math.max(...i.map(h=>h.y))-Math.min(...i.map(h=>h.y))+Et,c=t.syntheticNonGeographic&&(t.featureName||t.matchName||t.constituency)||"",d=c?Math.min(180,Math.max(72,c.length*6.8+16)):0,y=Math.max(o,d),u=l+(c?ve+4:0);return{result:t,center:n,bounds:a,seats:e,positions:i,groupWidth:y,groupHeight:u,area:Number(s||0)}}bindOverlayRefresh(){let t=this.mapController?.map;if(!t||this.overlayRefreshBound)return;this.overlayRefreshBound=!0;let e=()=>this.scheduleElectionOverlayRefresh(),n=()=>this.scheduleSeatCirclePositionUpdate();t.on("move",n),t.on("zoom",n),t.on("zoomend",e),t.on("moveend",e)}limitSeatCircleGroups(t=[]){let e=this.getSeatCircleGroupLimit();return t.length<=e?t:[...t].sort((n,a)=>{let s=+!!a.result?.syntheticNonGeographic-+!!n.result?.syntheticNonGeographic,i=(a.seats?.length||0)-(n.seats?.length||0);return s||i||(a.area||0)-(n.area||0)}).slice(0,e)}getSeatCircleGroupLimit(){let t=Number(window.innerWidth||1024),e=Number(navigator.deviceMemory||4);return t<700||e<=2?ln:t<1100||e<=4?rn:on}scheduleSeatCirclePositionUpdate(){this.seatCirclePositionUpdatePending||!this.seatCircleMarkers?.length||(this.seatCirclePositionUpdatePending=!0,requestAnimationFrame(()=>{this.seatCirclePositionUpdatePending=!1,this.updateSeatCircleOverlayPositions()}))}updateSeatCircleOverlayPositions(){let t=this.mapController?.map;if(!t||!this.seatCircleMarkers?.length)return this.getSeatCircleOverlayState();let e=new Map((this.seatCircleOverlayState?.groups||[]).map(n=>[`${n.key||""}|${n.aggregateType||""}|${n.constituency||""}`,n]));for(let n of this.seatCircleMarkers){let a=n.getElement(),s=Number(a.dataset.lng),i=Number(a.dataset.lat);if(!Number.isFinite(s)||!Number.isFinite(i))continue;let o=t.project([s,i]);if(!Number.isFinite(o?.x)||!Number.isFinite(o?.y))continue;n.setLngLat([s,i]);let l=`${a.dataset.resultKey||""}|${a.dataset.aggregateType||""}|${a.dataset.constituency||""}`,c=e.get(l);c&&(c.x=o.x,c.y=o.y)}return this.getSeatCircleOverlayState()}scheduleElectionOverlayRefresh(){this.overlayRefreshPending||!this.activeBundle||!this.shouldRenderElectionOverlays()||(this.overlayRefreshPending=!0,requestAnimationFrame(()=>{this.overlayRefreshPending=!1,!(!this.activeBundle||!this.shouldRenderElectionOverlays())&&this.renderElectionOverlay().catch(t=>console.warn("[test2 elections] Overlay refresh failed",t))}))}async filterOverlayGroupsByCollisionAsync(t=[]){let e=()=>this.limitSeatCircleGroups(this.filterOverlayGroupsByCollision(t)),n=this.mapController?.map;if(!n||t.length<=1||!this.getOverlayWorker())return e();let s=t.map((o,l)=>{let c=n.project(o.center),d=Ce(n,o.bounds);return{index:l,x:c?.x,y:c?.y,bounds:d,width:o.groupWidth,height:o.groupHeight,pixelArea:d?Math.abs(d.maxX-d.minX)*Math.abs(d.maxY-d.minY):0,seats:o.seats?.length||0,area:o.area||0,synthetic:!!o.result?.syntheticNonGeographic}}).filter(o=>Number.isFinite(o.x)&&Number.isFinite(o.y));if(!s.length)return[];let i=await this.runOverlayWorker(s,{limit:this.getSeatCircleGroupLimit(),margin:Mt,minTotalExtent:te}).catch(()=>null);return Array.isArray(i)?i.map(o=>t[o]).filter(Boolean):e()}getOverlayWorker(){if(this.overlayWorker)return this.overlayWorker;if(typeof Worker>"u")return null;try{let t=new Worker("/app/src/overlay-worker.js",{type:"module"});return t.addEventListener("message",e=>{let{id:n,selectedIndexes:a}=e.data||{},s=this.overlayWorkerCallbacks.get(n);s&&(clearTimeout(s.timer),this.overlayWorkerCallbacks.delete(n),s.resolve(a||[]))}),t.addEventListener("error",e=>{for(let[n,a]of this.overlayWorkerCallbacks)clearTimeout(a.timer),a.reject(e.error||new Error("Election overlay worker failed")),this.overlayWorkerCallbacks.delete(n);this.overlayWorker?.terminate?.(),this.overlayWorker=null}),this.overlayWorker=t,t}catch{return this.overlayWorker=null,null}}runOverlayWorker(t,e){let n=this.getOverlayWorker();if(!n)return Promise.reject(new Error("Election overlay worker unavailable"));let a=++this.overlayWorkerSeq;return new Promise((s,i)=>{let o=setTimeout(()=>{this.overlayWorkerCallbacks.delete(a),i(new Error("Election overlay worker timed out"))},700);this.overlayWorkerCallbacks.set(a,{resolve:s,reject:i,timer:o}),n.postMessage({id:a,type:"filterSeatCircleGroups",groups:t,options:e})})}filterOverlayGroupsByCollision(t=[]){let e=this.mapController?.map;if(!e||t.length<=1)return t;let n=t.map(o=>{let l=e.project(o.center),c=Ce(e,o.bounds);return{...o,point:l,bounds:c,width:o.groupWidth,height:o.groupHeight,pixelArea:c?Math.abs(c.maxX-c.minX)*Math.abs(c.maxY-c.minY):0}}).filter(o=>Number.isFinite(o.point?.x)&&Number.isFinite(o.point?.y));if(!n.length)return[];let a=n.reduce((o,l)=>bn(o,l.bounds||vn(l.point)),null);if(!a||Math.abs(a.maxX-a.minX)+!!c.result?.syntheticNonGeographic-+!!l.result?.syntheticNonGeographic||c.pixelArea-l.pixelArea)){let l=o.width/2+Mt,c=o.height/2+Mt;s.some(y=>{let u=y.width/2+Mt,h=y.height/2+Mt;return Math.abs(o.point.x-y.point.x){let o=i.features?.[0]?.properties?.resultKey,l=(this.activeBundle?.results||[]).find(c=>N(c.matchName||c.constituency)===o);l&&this.renderPanel(l)}),a.on("mouseenter",gt,()=>{this.mapController?.setMapCursor?.("pointer")}),a.on("mouseleave",gt,()=>{this.mapController?.setMapCursor?.("")}))}removeRecallLabels(){let t=this.mapController?.map;t&&(t.getLayer(gt)&&t.removeLayer(gt),t.getSource(bt)&&t.removeSource(bt))}shouldRenderElectionOverlays(){let t=N(this.activeBundle?.body||this.activeEntry?.body||""),e=N(this.activeBundle?.type||this.activeEntry?.type||"");return!t.includes("referendum")&&!t.includes("recall petition")&&!e.includes("referendum")&&!e.includes("recall")}shouldRenderRecallLabels(){let t=N(this.activeBundle?.body||this.activeEntry?.body||""),e=N(this.activeBundle?.type||this.activeEntry?.type||"");return t.includes("recall petition")||e.includes("recall")||!!(this.activeBundle?.results||[]).some(n=>n.recallPetition)}shouldRenderSeatCircles(){return this.shouldRenderElectionOverlays()}async loadFeatureIndex(){let t=this.getActiveElectionStyleLayer?.();return t?this.loadFeatureIndexForLayer(t):this.loadFeatureIndexForBundle(this.activeBundle)}async loadFeatureIndexForBundle(t){if(!t)return null;let e=this.app.metadataService.getLayer(t.layerId)||this.app.metadataService.getLayer(t.sourceMapId);return this.loadFeatureIndexForLayer(e)}async loadFeatureIndexForLayer(t){let n=(t?.featureIndexUrl?t:this.app.metadataService.getLayer(t?.id)||this.app.metadataService.getLayer(t?.sourceMapId)||t)?.featureIndexUrl;if(!n)return null;if(this.featureIndexCache.has(n))return this.featureIndexCache.get(n);let a=await fetch(n,{cache:"force-cache"});if(!a.ok)return null;let s=await a.json(),i={...s,items:s.items||s.features||(Array.isArray(s)?s:[])};return It(this.featureIndexCache,n,i,nn),i}buildFeatureCentreLookup(t){let e=new Map;for(let n of t){let a=Array.isArray(n.center)?n.center:null;if(!(!a||a.length<2))for(let s of[n.name,n.label,n.title,...n.aliases||[]].map(N).filter(Boolean))e.has(s)||e.set(s,a)}return e}findCentreForResult(t,e){for(let n of pt(e)){let a=t.get(n);if(a)return a}return null}seatCandidatesForResult(t){if(!this.shouldRenderElectionOverlays())return[];let e=zt(t);if(e.length)return e;if(Number(t.seatsTotal)===1||Number(t.seatsWon)===1){let a=(t.candidates||[]).find(s=>N(s.name)===N(t.winnerName))||(t.candidates||[])[0];return[{name:t.winnerName||a?.name||t.leadingName||"",party:t.winnerParty||a?.party||t.leadingParty||"",colour:this.mainPanePartyColour(t.winnerParty||a?.party||t.leadingParty)}]}let n=Math.max(0,Number(t.seatsWon||t.seatsTotal||0));return Array.from({length:n},(a,s)=>({name:s===0&&(t.winnerName||t.leadingName)||"",party:t.winnerParty||t.leadingParty||"",colour:this.mainPanePartyColour(t.winnerParty||t.leadingParty)}))}announceUnmatchedGeography(t){if(t?.resultsOnly){let c="There is no boundary map for this election yet, so its results are shown in the election pane without a map layer.",d=document.getElementById("announcer");d&&(d.textContent=c),console.info("[civgraph] %s",c);return}let e=Number(t?.unmatchedCount)||0;if(!e)return;let n=Number(t?.totalConstituencies)||Number(t?.matchedCount)+e||0,a=Array.isArray(t?.unmatchedConstituencySample)?t.unmatchedConstituencySample.filter(Boolean).slice(0,3):[],s=n?` of ${n}`:"",i=a.length?` For example: ${a.join(", ")}.`:"",o=`${e}${s} constituencies in this election could not be matched to a boundary and are drawn without results.${i}`,l=document.getElementById("announcer");l&&(l.textContent=o),console.info("[civgraph] %s",o)}updateElectionTimeline(){if(!this.activeEntry||!this.catalogue?.elections)return;let t=this.catalogue.elections.filter(n=>(n.loadable||n.resultsOnly)&&n.body===this.activeEntry.body).sort((n,a)=>String(n.date).localeCompare(String(a.date))),e=t.findIndex(n=>n.body===this.activeEntry.body&&n.date===this.activeEntry.date);this.app.setTimelineItems(t.map(n=>({label:n.date,body:n.body,date:n.date})),e>=0?e:t.length-1,async n=>{await this.loadElection(n.body,n.date)})}findEntry(t,e){return(this.catalogue?.elections||[]).find(n=>n.body===t&&n.date===e)||null}getCanonicalLayerId(t=this.activeEntry){return!t?.body||!t?.date?"":`election-${cn(t.body)}-${t.date}`}findEntryByCanonicalLayerId(t){return t&&(this.catalogue?.elections||[]).find(e=>this.getCanonicalLayerId(e)===t)||null}isCanonicalElectionLayerId(t){return!!this.findEntryByCanonicalLayerId(t)}};function cn(r){return String(r||"").toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s]+/g,"-").replace(/-+/g,"-")}function pt(r){return[r.matchName,r.featureName,r.constituency,...r.featureAliases||[],...r.featureNames||[],...(r.featureMatches||[]).flatMap(t=>[t?.name,...t?.aliases||[]])].map(N).filter(Boolean)}function $e(r=""){let t=new Set([r]),e=N(r);return(e==="armagh banbridge and craigavon"||e==="armagh city banbridge and craigavon")&&(t.add("Armagh, Banbridge and Craigavon"),t.add("Armagh Banbridge Craigavon"),t.add("Armagh City, Banbridge and Craigavon"),t.add("Armagh City Banbridge Craigavon")),[...t].map(n=>String(n||"").trim()).filter(Boolean)}function dn(r){let t=String(r??"");return t?[t,`${t} -`,`${t}\r -`,`${t}\r`,`${t} `]:[t]}function un(r){let t=[];for(let n of r.featureMatches||[])t.push(n?.name,...n?.aliases||[]);t.push(r.matchName,r.featureName,...r.featureNames||[],...r.featureAliases||[]);let e=new Set;return t.map(n=>String(n||"").trim()).filter(n=>{let a=N(n);return!a||e.has(a)?!1:(e.add(a),!0)})}function hn(r={}){let t=String(r.Candidate_Id||"").trim();if(!t||t.toLowerCase()==="nontransferable")return!1;let e=yn(r);return!(!e||e.toLowerCase()==="party"||String(r.Party_Name||"").trim().toLowerCase()==="party")}function yn(r={}){return String(r.candidateName||`${r.Firstname||""} ${r.Surname||""}`.trim()||"").replace(/[�]+/g,"").replace(/\s{2,}/g," ").trim()}function wt(r){let t=String(r||"").toLowerCase();return t?t.includes("not elected")?"not_elected":t.includes("excluded")?"excluded":t.includes("elected")||t.includes("made quota")||t.includes("counted as elected")||t.includes("deemed elected")?"elected":"unknown":"unknown"}function K(r,t){return r.reduce((e,n)=>{let a=Number(n?.[t]);return Number.isFinite(a)?e+a:e},0)}function pn(r,t){let e=r.map(n=>Number(n?.[t])).filter(n=>Number.isFinite(n));return e.length?e.reduce((n,a)=>n+a,0)/e.length:null}function kt(r=[]){let t=[];for(let e of r){let n=new Map,a=Number(e.validPoll||e.totalVotes||0);for(let s of e.candidates||[]){let i=s.party||"Independent/Other",o=N(i)||i;n.has(o)||n.set(o,{party:i,constituency:e.constituency||e.matchName||"",resultKey:N(e.matchName||e.constituency||""),colour:s.colour||U(i)||jt(i),stood:0,seats:0,firstPrefs:0,seatShare:null,share:null});let l=n.get(o);l.stood+=1,l.firstPrefs+=Number(s.firstPrefs??s.votes??0)||0,s.elected&&(l.seats+=1)}for(let s of n.values())s.seatShare=Number(e.seatsTotal)?s.seats/Number(e.seatsTotal)*100:null,s.share=a?s.firstPrefs/a*100:null,t.push(s)}return t.sort((e,n)=>p(n.share)-p(e.share)||p(n.firstPrefs)-p(e.firstPrefs)||String(e.party).localeCompare(String(n.party))||String(e.constituency).localeCompare(String(n.constituency)))}function Nt(r=[]){let t=new Map;for(let e of r){let n=e.localBody||"Unknown council";t.has(n)||t.set(n,{council:n,deas:0,seats:0,validPoll:0,electorate:0,partySeats:new Map,partyVotes:new Map,partyColours:new Map});let a=t.get(n);a.deas+=1,a.seats+=Number(e.seatsWon??e.seatsTotal??0)||0,a.validPoll+=Number(e.validPoll||e.totalVotes||0)||0,a.electorate+=Number(e.electorate||0)||0;for(let s of e.candidates||[]){let i=s.party||"Independent/Other";a.partyVotes.set(i,(a.partyVotes.get(i)||0)+(Number(s.firstPrefs??s.votes??0)||0)),s.colour&&!a.partyColours.has(i)&&a.partyColours.set(i,s.colour),s.elected&&a.partySeats.set(i,(a.partySeats.get(i)||0)+1)}}return[...t.values()].map(e=>{let n=[...e.partySeats.entries()].sort((a,s)=>s[1]-a[1]||(e.partyVotes.get(s[0])||0)-(e.partyVotes.get(a[0])||0))[0]||[...e.partyVotes.entries()].sort((a,s)=>s[1]-a[1])[0]||["",0];return{...e,leadingParty:n[0],colour:e.partyColours.get(n[0])||jt(n[0]),share:e.validPoll?(e.partyVotes.get(n[0])||0)/e.validPoll*100:null,turnoutPct:e.electorate?e.validPoll/e.electorate*100:null}}).sort((e,n)=>String(e.council).localeCompare(String(n.council)))}function Ce(r,t){let e=Number(t?.west),n=Number(t?.south),a=Number(t?.east),s=Number(t?.north);if(!r||![e,n,a,s].every(Number.isFinite))return null;let i=r.project([a,s]),o=r.project([e,n]);return{minX:Math.min(i.x,o.x),maxX:Math.max(i.x,o.x),minY:Math.min(i.y,o.y),maxY:Math.max(i.y,o.y)}}function mn(r,t){if(!t)return r;if(!r)return{...t};let e=Math.min(Number(r.west),Number(t.west)),n=Math.min(Number(r.south),Number(t.south)),a=Math.max(Number(r.east),Number(t.east)),s=Math.max(Number(r.north),Number(t.north));return[e,n,a,s].every(Number.isFinite)?{west:e,south:n,east:a,north:s}:r||t||null}function fn(r){let t=Number(r?.west),e=Number(r?.south),n=Number(r?.east),a=Number(r?.north);return[t,e,n,a].every(Number.isFinite)?[(t+n)/2,(e+a)/2]:null}function vn(r){return{minX:r.x,maxX:r.x,minY:r.y,maxY:r.y}}function bn(r,t){return t?r?{minX:Math.min(r.minX,t.minX),maxX:Math.max(r.maxX,t.maxX),minY:Math.min(r.minY,t.minY),maxY:Math.max(r.maxY,t.maxY)}:{...t}:r}function gn(){if(typeof window.$?.preloadElectionData=="function"&&typeof window.animateStages=="function")return Promise.resolve();if(!ee){let r=e=>`${e}?v=${$t[e]}`;ee=[r("/app/js/jquery-shim.js"),r("/app/election-viewer-package/js/stages2.js"),r("/app/election-viewer-package/js/animation_preview.js"),r("/app/election-viewer-package/js/animation_preview_manager.js"),r("/app/election-viewer-package/js/election_viewer.js")].reduce((e,n)=>e.then(()=>Pn(n)),Promise.resolve())}return ee}function Pn(r){return[...document.querySelectorAll("script[data-test2-runtime-src]")].find(e=>e.dataset.test2RuntimeSrc===r)?Promise.resolve():new Promise((e,n)=>{let a=document.createElement("script");a.src=r,a.dataset.test2RuntimeSrc=r,a.onload=()=>e(),a.onerror=()=>n(new Error(r)),document.head.appendChild(a)})}function $n(){return new Promise(r=>requestAnimationFrame(()=>r()))}function It(r,t,e,n){if(!r||!t)return e;for(r.has(t)&&r.delete(t),r.set(t,e);r.size>n;){let a=r.keys().next().value;r.delete(a)}return e}async function Cn(r,t,e){let n=Array.isArray(r)?r:[],a=Math.max(1,Number(t)||1),s=new Array(n.length),i=0,o=Array.from({length:Math.min(a,n.length)},async()=>{for(;iNumber(n)>1)}function Nn(r={},t=[],e=[]){let n=new Map((r.nonTransferable||[]).map(l=>[Number(l.count),l])),a=new Map,s=new Map,i=0,o=Wt(e);for(let l of o){let c=n.get(l),d=0,y=0,u=0;for(let E of t||[]){let V=new Map((E.counts||[]).map(_=>[Number(_.count),_])),b=V.get(l),k=Kt(E,l,V,r,o,b),M=q(k?.transfers);M!==null&&(d+=M,M>0&&(y+=M),M<0&&(u+=Math.abs(M)))}let h=q(c?.transfers);if(h===null&&l>1){let E=-d;h=E>1e-4?E:0}let v=q(c?.total);v===null&&(v=l<=1?0:i+Math.max(0,h||0)),i=v,a.set(l,{count:l,total:v,transfers:h||0,inferred:!c}),s.set(l,{positive:y+Math.max(0,h||0),negativeAbs:u})}return{nonTransferable:a,transferDenominators:s}}function Se(r,t){let e=q(r);if(e===null||Math.abs(e)<=1e-4)return"-";let n=t&&typeof t=="object"?e<0?q(t.negativeAbs):q(t.positive):q(t);return n===null||n<=0?"-":et(e/n*100)}function En(r={},t=new Map,e={},n=[]){let a=q(e.quota??e.Quota??e.countInfo?.Quota??r.quota),s=Wt(n.length?n:[...t.keys()]),i=null;return s.forEach(o=>{if(i!==null||o<=1)return;let l=Kt(r,o,t,e,s,t.get(o));if(!l)return;let c=q(l.total??l.firstPrefs),d=q(l.transfers);if(c===null||d===null||d>=-.01)return;let y=c<=.01,u=a!==null&&a>0&&Math.abs(c-a)<=.01;(y||u)&&(i=o)}),i}function Kt(r={},t,e=new Map,n={},a=[],s=null){let i=Number(t);if(!Number.isFinite(i)||i<=1)return s||null;let o=q(s?.transfers);if(o!==null&&o<-.01)return s;let l=Wt(a.length?a:[...e.keys()]),c=Te(l,i);if(c===null)return s||null;let d=Number(r.excludedAt||r.electedAt||0);if(!d||d!==c)return s||null;let y=e.get(d),u=q(y?.total??y?.firstPrefs);if(u===null||u<=.01)return s||null;if(r.excludedAt&&Number(r.excludedAt)===d)return{...s||{},count:i,total:0,transfers:-u,status:"Excluded transfer"};if(r.electedAt&&Number(r.electedAt)===d){let h=q(n.quota??n.Quota??n.countInfo?.Quota??r.quota);return h===null||h<=0||u<=h+.01?s||null:{...s||{},count:i,total:h,transfers:h-u,status:"Surplus transfer"}}return s||null}function Wt(r=[]){return[...new Set(r.map(Number).filter(Number.isFinite))].sort((t,e)=>t-e)}function Te(r=[],t){let e=null;for(let n of r){let a=Number(n);if(!Number.isFinite(a)||a>=Number(t))break;e=a}return e}function Mn(r,t){return t!=null&&Number(r)>Number(t)}function $(r){if(r==null||r==="")return"";let t=Number(r);return Number.isFinite(t)?t.toLocaleString():String(r)}function Z(r){if(r==null||r==="")return"";let t=Number(r);return Number.isFinite(t)?`${t.toFixed(2).replace(/\.00$/,"")}%`:String(r)}function Ft(r){let t=Number(r);return Number.isFinite(t)?`${t>0?"+":""}${t.toLocaleString()}`:""}function Ne(r){let t=Number(r);return Number.isFinite(t)?`${t>0?"+":""}${t.toFixed(2).replace(/\.00$/,"")}%`:""}function X(r){let t=Number(r);return Number.isFinite(t)?`${t.toFixed(2)}%`:""}function Y(r){let t=Number(r);return Number.isFinite(t)?`${t>0?"+":""}${t.toLocaleString("en-GB")}`:""}function et(r){let t=Number(r);return Number.isFinite(t)?`${t>0?"+":""}${t.toFixed(2)}%`:""}function Ee(r){let t=Number(r);return Number.isFinite(t)?`${t>0?"+":""}${t.toFixed(2)}`:""}function at(){return'N/A'}function lt(r){return String(Number(r)+1)}function Ot(r){let t=String(r||"");return new Map([["D\xE1il \xC9ireann","D\xE1il"],["D\xC3\xA1il \xC3\u2030ireann","D\xE1il"],["House of Commons of the United Kingdom","Westminster"],["Northern Ireland Assembly","Assembly"],["Northern Ireland Constitutional Convention","Convention"],["Northern Ireland Forum for Political Dialogue","Forum"],["European Parliament (Ireland)","European (Republic of Ireland)"],["European Parliament","European"],["President of Ireland","President"],["Referendum (Ireland)","Referendum"]]).get(t)||t}function Me(r){let t=String(r||"").match(/^(\d{4})-(\d{2})-(\d{2})/);if(!t)return String(r||"");let[,e,n,a]=t,s=new Date(`${e}-${n}-${a}T00:00:00Z`);return Number.isNaN(s.getTime())?String(r||""):s.toLocaleDateString("en-GB",{day:"2-digit",month:"short",year:"numeric",timeZone:"UTC"})}function Gt(r={}){let t=N(r.body||r.displayTitle||""),e=N(r.bodyGroup||""),n=N(r.displayProvider||"");return e==="local-government"||/local government|local election/.test(t)||/local government/.test(n)?"local elections":/house of commons|westminster|uk parliament/.test(t)?"UK general elections in Northern Ireland":/dail|dail eireann|dáil|irish general/.test(t)?"Irish general elections":/assembly|forum|constitutional convention|parliament of northern ireland/.test(t)?"devolved elections":/european/.test(t)&&(/ireland|republic/.test(t)||/republic/.test(n))?"European elections in the Republic of Ireland":/european/.test(t)?"European elections in Northern Ireland":/president/.test(t)?"Irish presidential elections":e||t||"elections"}function ne(r={}){let t=N(r.body||r.displayTitle||""),e=N(r.bodyGroup||""),n=N(`${r.displayProvider||""} ${r.provider||""} ${r.region||""} ${r.jurisdiction||""}`),a=`${t} ${e} ${n}`,s=(Array.isArray(r.constituencies)?r.constituencies:[]).map(i=>N(i)).filter(Boolean);if(/northern ireland/.test(a)||/house of commons|westminster|uk parliament|assembly|forum|constitutional convention|parliament of northern ireland/.test(a)||s.length&&s.every(i=>i==="northern ireland"))return"Northern Ireland";if(/republic of ireland|irish general|dail|dail eireann|dáil|president of ireland|irish presidential/.test(a))return"Republic of Ireland";if(/european/.test(t))return/northern ireland/.test(a)?"Northern Ireland":/\bireland\b/.test(t)||/republic/.test(a)||/ireland national/.test(a)?"Republic of Ireland":"Northern Ireland";if(e==="local-government"||/local election|local government/.test(a)){if(/local government districts|districts|northern/.test(a))return"Northern Ireland";if(/local authorities|republic/.test(a))return"Republic of Ireland"}return/referendum/.test(t)&&/ireland/.test(a)?"Republic of Ireland":null}function _e(r={}){let e=String(r.date||"").slice(0,4)||"",n=Ot(r.body||r.displayProvider||r.displayTitle||"");return[e,n].filter(Boolean).join(" ")}function _n(r={}){let t=Gt(r);return/westminster|uk general/.test(t)?"triangle":/local/.test(t)?"square":/european/.test(t)?"diamond":/devolved/.test(t)?"circle":/irish general/.test(t)?"pentagon":"circle"}function Ln(r,t,e,n,a){let s=m(_t(n)),i=m(a||""),o=Number(t).toFixed(1),l=Number(e).toFixed(1);return r==="triangle"?`${i}`:r==="square"?`${i}`:r==="diamond"?`${i}`:r==="pentagon"?`${i}`:`${i}`}function xn(r=[],t=[]){let e=[];for(let n of t){let a=[],s=[];for(let o of r){let l=(o.counts||[]).find(d=>Number(d.count)===Number(n)),c=N(l?.status||"");/not elected/.test(c)||(/elected|quota/.test(c)&&Number(o.electedAt)===Number(n)&&a.push(o.name),/excluded|eliminated/.test(c)&&Number(o.excludedAt)===Number(n)&&s.push(o.name))}let i=[];a.length&&i.push(`${a.length===1?a[0]:`${a.length} candidates`} elected`),s.length&&i.push(`${s.length===1?s[0]:`${s.length} candidates`} excluded`),i.length&&e.push({count:Number(n),label:i.join("; ")})}return e}function Tn(r={},t=[],e=[]){let n=[],a=Wt(e);for(let s of a){if(Number(s)<=1)continue;let i=[],o=[];for(let c of t||[]){let d=new Map((c.counts||[]).map(v=>[Number(v.count),v])),y=Kt(c,s,d,r,a,d.get(Number(s))),u=q(y?.transfers);if(u===null||u>=-.01)continue;let h=Rn(c.name);h&&(Bn(c,y,r,s,a)==="elected"?i.push(h):o.push(h))}let l=[];i.length&&l.push(`${Le(i)} elected`),o.length&&l.push(`${Le(o)} excluded`),l.length&&n.push({count:Number(s),label:l.join("; ")})}return n}function Bn(r={},t={},e={},n,a=[]){let s=N(t?.status||r.status||"");if(s.includes("excluded")||s.includes("eliminated"))return"excluded";if(s.includes("elected")||s.includes("surplus")||s.includes("quota"))return"elected";let i=q(t?.total??t?.firstPrefs);if(i!==null&&i<=.01)return"excluded";let o=q(e.quota??e.Quota??e.countInfo?.Quota??r.quota);if(o!==null&&o>0&&i!==null&&Math.abs(i-o)<=.01)return"elected";let l=Te(a,Number(n));return Number(r.excludedAt||0)===l||Number(r.excludedAt||0)===Number(n)?"excluded":Number(r.electedAt||0)===l||Number(r.electedAt||0)===Number(n)?"elected":"excluded"}function Rn(r=""){let t=String(r||"").replace(/\([^)]*\)/g," ").trim().split(/\s+/).filter(Boolean);if(!t.length)return"";let e=t[t.length-1],n=t[t.length-2]||"";return/^(o|ó|ua|mac|mc|nic|ní)$/i.test(n)?`${n} ${e}`:e}function Le(r=[]){let t=new Set;return r.filter(e=>{let n=N(e);return!n||t.has(n)?!1:(t.add(n),!0)}).join(", ")}function Dt(r={}){let t=r.recallPetition||{};if(typeof t.triggered=="boolean")return t.triggered;let e=Number(t.signed??t.signatures??r.leadingVotes),n=Number(t.threshold??t.required);return Number.isFinite(e)&&Number.isFinite(n)?e>=n:!1}function m(r){return String(r??"").replace(/[&<>"']/g,t=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[t])}export{Pe as Test2ElectionManager}; diff --git a/app/build/metafile.json b/app/build/metafile.json index c87e7158a4..3fae09ab28 100644 --- a/app/build/metafile.json +++ b/app/build/metafile.json @@ -201,7 +201,7 @@ ] }, "app/src/test2.css": { - "bytes": 46041, + "bytes": 57308, "imports": [] }, "": { @@ -236,7 +236,7 @@ "format": "esm" }, "src/feature-loader.js": { - "bytes": 16953, + "bytes": 16494, "imports": [ { "path": "", @@ -269,7 +269,7 @@ "format": "esm" }, "src/cdn-url.js": { - "bytes": 1397, + "bytes": 1366, "imports": [ { "path": "", @@ -280,7 +280,7 @@ "format": "esm" }, "src/party-names.mjs": { - "bytes": 11023, + "bytes": 10794, "imports": [ { "path": "", @@ -291,7 +291,7 @@ "format": "esm" }, "src/ui-controller.js": { - "bytes": 637134, + "bytes": 630947, "imports": [ { "path": "src/map-relations.mjs", @@ -353,7 +353,7 @@ "format": "esm" }, "render/src/config.js": { - "bytes": 848, + "bytes": 824, "imports": [ { "path": "", @@ -434,7 +434,7 @@ "format": "esm" }, "render/src/point-cloud-layer.js": { - "bytes": 7008, + "bytes": 6842, "imports": [ { "path": "node_modules/maplibre-gl/dist/maplibre-gl.js", @@ -450,7 +450,7 @@ "format": "esm" }, "render/src/point-cloud-stream-layer.js": { - "bytes": 34805, + "bytes": 34086, "imports": [ { "path": "node_modules/maplibre-gl/dist/maplibre-gl.js", @@ -503,7 +503,7 @@ "format": "esm" }, "render/src/map-controller.js": { - "bytes": 94277, + "bytes": 91918, "imports": [ { "path": "node_modules/maplibre-gl/dist/maplibre-gl.js", @@ -554,7 +554,7 @@ "format": "esm" }, "app/src/settle.js": { - "bytes": 2433, + "bytes": 2380, "imports": [ { "path": "", @@ -606,7 +606,7 @@ "format": "esm" }, "src/election-domain.mjs": { - "bytes": 55473, + "bytes": 54169, "imports": [ { "path": "", @@ -633,7 +633,7 @@ "format": "esm" }, "src/election-renderer.mjs": { - "bytes": 38454, + "bytes": 37953, "imports": [ { "path": "src/election-domain.mjs", @@ -659,7 +659,7 @@ "format": "esm" }, "src/election-main-pane-contract.mjs": { - "bytes": 10324, + "bytes": 10135, "imports": [ { "path": "src/election-domain.mjs", @@ -674,8 +674,19 @@ ], "format": "esm" }, + "src/election-trend-chart.mjs": { + "bytes": 32235, + "imports": [ + { + "path": "", + "kind": "import-statement", + "external": true + } + ], + "format": "esm" + }, "app/src/election-manager.js": { - "bytes": 289816, + "bytes": 281046, "imports": [ { "path": "render/src/feature-property-repairs.js", @@ -707,6 +718,11 @@ "kind": "import-statement", "original": "../../src/party-names.mjs" }, + { + "path": "src/election-trend-chart.mjs", + "kind": "import-statement", + "original": "../../src/election-trend-chart.mjs" + }, { "path": "", "kind": "import-statement", @@ -716,7 +732,7 @@ "format": "esm" }, "app/src/app.js": { - "bytes": 169760, + "bytes": 170132, "imports": [ { "path": "src/data-service.js", @@ -802,11 +818,11 @@ "app/build/app.bundle.js": { "imports": [ { - "path": "app/build/chunks/chunk-2YPEAJVR.js", + "path": "app/build/chunks/chunk-57HMLXXU.js", "kind": "import-statement" }, { - "path": "app/build/chunks/app-5QB5UQHT.js", + "path": "app/build/chunks/app-RDZI4COH.js", "kind": "dynamic-import" } ], @@ -826,14 +842,14 @@ }, "bytes": 757 }, - "app/build/chunks/election-manager-ZWKCF5OK.js": { + "app/build/chunks/election-manager-MOZS4OJM.js": { "imports": [ { - "path": "app/build/chunks/chunk-V4IEUOVV.js", + "path": "app/build/chunks/chunk-MJD6VXSO.js", "kind": "import-statement" }, { - "path": "app/build/chunks/chunk-2YPEAJVR.js", + "path": "app/build/chunks/chunk-57HMLXXU.js", "kind": "import-statement" } ], @@ -843,35 +859,38 @@ "entryPoint": "app/src/election-manager.js", "inputs": { "app/src/election-manager.js": { - "bytesInOutput": 163758 + "bytesInOutput": 161310 }, "src/election-renderer.mjs": { - "bytesInOutput": 27290 + "bytesInOutput": 27294 }, "src/election-domain.mjs": { - "bytesInOutput": 8253 + "bytesInOutput": 8254 }, "src/election-view-model.mjs": { - "bytesInOutput": 3395 + "bytesInOutput": 3396 }, "src/election-main-pane-contract.mjs": { - "bytesInOutput": 6031 + "bytesInOutput": 6032 + }, + "src/election-trend-chart.mjs": { + "bytesInOutput": 14432 } }, - "bytes": 208885 + "bytes": 220884 }, - "app/build/chunks/app-5QB5UQHT.js": { + "app/build/chunks/app-RDZI4COH.js": { "imports": [ { - "path": "app/build/chunks/chunk-V4IEUOVV.js", + "path": "app/build/chunks/chunk-MJD6VXSO.js", "kind": "import-statement" }, { - "path": "app/build/chunks/chunk-2YPEAJVR.js", + "path": "app/build/chunks/chunk-57HMLXXU.js", "kind": "import-statement" }, { - "path": "app/build/chunks/election-manager-ZWKCF5OK.js", + "path": "app/build/chunks/election-manager-MOZS4OJM.js", "kind": "dynamic-import" } ], @@ -879,7 +898,7 @@ "entryPoint": "app/src/app.js", "inputs": { "app/src/app.js": { - "bytesInOutput": 90381 + "bytesInOutput": 90480 }, "src/data-service.js": { "bytesInOutput": 9499 @@ -891,7 +910,7 @@ "bytesInOutput": 6264 }, "src/ui-controller.js": { - "bytesInOutput": 341460 + "bytesInOutput": 344890 }, "src/storage-keys.mjs": { "bytesInOutput": 383 @@ -939,12 +958,12 @@ "bytesInOutput": 362 } }, - "bytes": 587017 + "bytes": 590546 }, - "app/build/chunks/chunk-V4IEUOVV.js": { + "app/build/chunks/chunk-MJD6VXSO.js": { "imports": [ { - "path": "app/build/chunks/chunk-2YPEAJVR.js", + "path": "app/build/chunks/chunk-57HMLXXU.js", "kind": "import-statement" } ], @@ -953,22 +972,23 @@ "b", "c", "d", - "e" + "e", + "f" ], "inputs": { "node_modules/maplibre-gl/dist/maplibre-gl.js": { "bytesInOutput": 1044249 }, "src/party-names.mjs": { - "bytesInOutput": 7170 + "bytesInOutput": 7237 }, "render/src/feature-property-repairs.js": { "bytesInOutput": 1438 } }, - "bytes": 1053175 + "bytes": 1053250 }, - "app/build/chunks/chunk-2YPEAJVR.js": { + "app/build/chunks/chunk-57HMLXXU.js": { "imports": [], "exports": [ "a", @@ -1187,10 +1207,10 @@ "bytesInOutput": 69917 }, "app/src/test2.css": { - "bytesInOutput": 35895 + "bytesInOutput": 46235 } }, - "bytes": 105813 + "bytes": 116153 } } } \ No newline at end of file diff --git a/app/build/performance-dashboard.json b/app/build/performance-dashboard.json index 2c8ec481eb..60f626e410 100644 --- a/app/build/performance-dashboard.json +++ b/app/build/performance-dashboard.json @@ -1,6 +1,6 @@ { "schemaVersion": 1, - "generatedAt": "2026-09-18T13:00:29.544Z", + "generatedAt": "2026-09-19T13:33:03.200Z", "summary": "Performance budgets pass", "budgets": { "entryJsBytes": 81920, @@ -27,44 +27,44 @@ "css": { "name": "app.bundle.css", "path": "app/build/app.bundle.css", - "bytes": 105972, - "label": "103.5 KB" + "bytes": 116153, + "label": "113.4 KB" } }, "lazy": { "jsCount": 4, "cssCount": 0, - "jsBytes": 1855610, + "jsBytes": 1865935, "cssBytes": 0 }, "largestOutputs": [ { - "name": "chunk-V4IEUOVV.js", - "path": "app/build/chunks/chunk-V4IEUOVV.js", - "bytes": 1053174, + "name": "chunk-MJD6VXSO.js", + "path": "app/build/chunks/chunk-MJD6VXSO.js", + "bytes": 1053249, "label": "1.0 MB" }, { - "name": "app-7CXG5JVM.js", - "path": "app/build/chunks/app-7CXG5JVM.js", - "bytes": 592291, - "label": "578.4 KB" + "name": "app-RDZI4COH.js", + "path": "app/build/chunks/app-RDZI4COH.js", + "bytes": 590542, + "label": "576.7 KB" }, { - "name": "election-manager-ZWKCF5OK.js", - "path": "app/build/chunks/election-manager-ZWKCF5OK.js", - "bytes": 208885, - "label": "204.0 KB" + "name": "election-manager-MOZS4OJM.js", + "path": "app/build/chunks/election-manager-MOZS4OJM.js", + "bytes": 220884, + "label": "215.7 KB" }, { "name": "app.bundle.css", "path": "app/build/app.bundle.css", - "bytes": 105972, - "label": "103.5 KB" + "bytes": 116153, + "label": "113.4 KB" }, { - "name": "chunk-2YPEAJVR.js", - "path": "app/build/chunks/chunk-2YPEAJVR.js", + "name": "chunk-57HMLXXU.js", + "path": "app/build/chunks/chunk-57HMLXXU.js", "bytes": 1260, "label": "1.2 KB" }, @@ -88,15 +88,15 @@ { "name": "Entry CSS", "status": "pass", - "value": 105972, + "value": 116153, "maxBytes": 163840, - "valueLabel": "103.5 KB / 160.0 KB", + "valueLabel": "113.4 KB / 160.0 KB", "path": "app/build/app.bundle.css" }, { "name": "Split JS chunks", "status": "pass", - "value": 1855610, + "value": 1865935, "maxBytes": 3891200, "valueLabel": "1.8 MB / 3.7 MB", "path": "app/build/chunks" @@ -104,10 +104,10 @@ { "name": "Largest lazy JS chunk", "status": "pass", - "value": 1053174, + "value": 1053249, "maxBytes": 1228800, - "valueLabel": "chunk-V4IEUOVV.js 1.0 MB / 1.2 MB", - "path": "app/build/chunks/chunk-V4IEUOVV.js" + "valueLabel": "chunk-MJD6VXSO.js 1.0 MB / 1.2 MB", + "path": "app/build/chunks/chunk-MJD6VXSO.js" }, { "name": "Startup runtime split", diff --git a/app/src/app.js b/app/src/app.js index 649ea9a6ea..dcb056c426 100644 --- a/app/src/app.js +++ b/app/src/app.js @@ -2642,6 +2642,10 @@ class Test2App { const play = document.getElementById('timelinePlay'); const stop = document.getElementById('timelineStop'); if (!play || !stop) return; + // The playback buttons animate boundary layers through time. An election has nothing to + // animate, so canAnimateTimeline() always refuses while one is open; rather than sit + // there greyed out, the pair is hidden until the election is closed. + play.parentElement?.classList.toggle('timeline-playback-group--hidden', Boolean(this.elections?.activeEntry)); const canAnimate = this.canAnimateTimeline(); const { playing, paused, atEnd, originalLayerId } = this.timelineAnimation; play.disabled = !canAnimate; diff --git a/app/src/election-manager.js b/app/src/election-manager.js index 43da200cb6..cfa567caf8 100644 --- a/app/src/election-manager.js +++ b/app/src/election-manager.js @@ -18,7 +18,8 @@ import { partyColour as electionPartyColour, seatPositions } from '../../src/election-domain.mjs'; -import { partyLabelHtml } from '../../src/party-names.mjs'; +import { partyAbbreviation, partyLabelHtml } from '../../src/party-names.mjs'; +import { buildTrendChartModel, mountTrendChart } from '../../src/election-trend-chart.mjs'; const ELECTION_MANIFEST_URL = '/render/metadata/elections-test2.json?v=test-023'; @@ -240,6 +241,7 @@ export class Test2ElectionManager { this.trendSummaryCache = new Map(); this.trendSummaryPromiseCache = new Map(); this.trendRenderCache = new Map(); + this.trendChart = null; this.featureIndexCache = new Map(); this.resultsByLayer = new Map(); this.seatCircleClickBound = false; @@ -557,7 +559,12 @@ export class Test2ElectionManager { } else if (this.bundleCache.has(entry.key)) { bundle = this.bundleCache.get(entry.key); } else { - const response = await fetch(electionBundleUrl(entry), { cache: 'force-cache' }); + let response = await fetch(electionBundleUrl(entry), { cache: 'force-cache' }); + // Same fallback as loadBundle: the static bundles are always deployed, so an API + // miss (or a local static server with no API at all) still yields a full history. + if (!response.ok && useElectionsApi()) { + response = await fetch(`${entry.resultUrl}?v=test-023`, { cache: 'force-cache' }); + } if (!response.ok) throw new Error(`Failed to load trend data for ${entry.body} ${entry.date}: ${response.status}`); bundle = await response.json(); } @@ -1011,6 +1018,10 @@ export class Test2ElectionManager { if (selectedResult && nextView === 'animation' && this.resultHasAnimation(selectedResult)) { window.requestAnimationFrame(() => this.runAnimation(selectedResult)); } + if (nextView !== 'trends' && this.trendChart) { + this.trendChart.destroy(); + this.trendChart = null; + } if (nextView === 'trends') { const scopeToggle = pane.querySelector('#test2ElectionTrendsScope'); const renderTrends = () => { @@ -2553,12 +2564,13 @@ export class Test2ElectionManager { renderTrendsPanel(selectedResult = null) { const area = selectedResult?.constituency || selectedResult?.localBody || ''; - const title = area ? `Trend: ${area}` : 'Election trends'; + const title = area ? `Party vote share in ${area}` : 'Party vote share'; const family = electionTrendFamily(this.activeEntry || this.activeBundle || {}); const jurisdiction = electionTrendJurisdiction(this.activeEntry || this.activeBundle || {}); - const scopeText = family - ? `Showing comparable ${family} contests${jurisdiction ? ` in ${jurisdiction}` : ''} by default.` - : `Showing comparable contests${jurisdiction ? ` in ${jurisdiction}` : ''} by default.`; + const familyText = family || 'comparable elections'; + const place = jurisdiction === 'Republic of Ireland' ? 'the Republic of Ireland' : jurisdiction; + const placeText = place && !familyText.toLowerCase().includes(String(jurisdiction).toLowerCase()) ? ` in ${place}` : ''; + const scopeText = `Share of the vote at ${familyText}${placeText}.`; return ` `; @@ -2593,11 +2605,13 @@ export class Test2ElectionManager { selectedKeyLabel ].join('::'); if (this.trendRenderCache.has(renderCacheKey)) { - chart.innerHTML = this.trendRenderCache.get(renderCacheKey); + const cached = this.trendRenderCache.get(renderCacheKey); + this.renderTrendChart(chart, cached.points, selectedResult, includeAllTypes, cached.comparableCount); return; } chart.dataset.trendRequestKey = renderCacheKey; - chart.textContent = 'Loading trend data...'; + chart.setAttribute('aria-busy', 'true'); + chart.innerHTML = ''; const entries = (this.catalogue?.elections || []) .filter((entry) => (entry?.loadable || entry?.resultsOnly) && entry.resultUrl && normalizeName(entry.contestType || 'election') === 'election') .filter((entry) => { @@ -2646,36 +2660,29 @@ export class Test2ElectionManager { } for (const row of rows) points.push(row); } - const markup = this.renderTrendChart(points, selectedResult, includeAllTypes, entries.length); - rememberLimitedCache(this.trendRenderCache, renderCacheKey, markup, ELECTION_TREND_RENDER_CACHE_LIMIT); + rememberLimitedCache(this.trendRenderCache, renderCacheKey, { points, comparableCount: entries.length }, ELECTION_TREND_RENDER_CACHE_LIMIT); if (chart.dataset.trendRequestKey === renderCacheKey) { - chart.innerHTML = markup; + this.renderTrendChart(chart, points, selectedResult, includeAllTypes, entries.length); } } - renderTrendChart(points = [], selectedResult = null, includeAllTypes = false, comparableCount = 0) { + /** + * Mount the trends chart into its container. The drawing itself lives in + * src/election-trend-chart.mjs; this method only decides the caption text and the notes + * that explain the data, then hands over the points. + */ + renderTrendChart(chart, points = [], selectedResult = null, includeAllTypes = false, comparableCount = 0) { + this.trendChart?.destroy(); + this.trendChart = null; + chart.removeAttribute('aria-busy'); if (!points.length) { - return '

    No trend data is available for this selection.

    '; - } - const byParty = new Map(); - const electionOrder = []; - const electionByKey = new Map(); - for (const point of points) { - const entryKey = point.entry?.key || `${point.entry?.body}|${point.entry?.date}`; - if (!electionByKey.has(entryKey)) { - electionByKey.set(entryKey, point.entry); - electionOrder.push(entryKey); - } - const partyKey = normalizeName(point.party); - if (!byParty.has(partyKey)) byParty.set(partyKey, { party: point.party, colour: point.colour, points: new Map(), maxShare: 0, latestShare: 0 }); - const series = byParty.get(partyKey); - series.points.set(entryKey, point); - series.maxShare = Math.max(series.maxShare, numberOrZero(point.share)); - series.latestShare = numberOrZero(point.share); + chart.innerHTML = '

    No trend data is available for this selection.

    '; + return; } - const series = [...byParty.values()] - .sort((a, b) => numberOrZero(b.latestShare) - numberOrZero(a.latestShare) || numberOrZero(b.maxShare) - numberOrZero(a.maxShare)) - .slice(0, 8); + const model = buildTrendChartModel(points, { + abbreviate: (party) => partyAbbreviation(party), + bodyLabel: (entry) => shortElectionBody(entry.body || entry.displayProvider || entry.displayTitle || '') + }); // Why a constituency series can be short, said out loud. // // A point is matched to a constituency by NAME, and constituencies are renamed and @@ -2687,60 +2694,37 @@ export class Test2ElectionManager { // registry, and that does not exist yet. Until it does, a chart that explains its own // gap is far better than one that appears broken. const selectionName = selectedResult ? (selectedResult.constituency || selectedResult.featureName || '') : ''; - const shortSeriesNote = (selectionName && comparableCount > electionOrder.length + 1) - ? `' - : ''; - - const width = 860; - const height = 330; - const pad = { left: 46, right: 24, top: 22, bottom: 70 }; - const plotWidth = width - pad.left - pad.right; - const plotHeight = height - pad.top - pad.bottom; - const maxShare = Math.max(40, Math.ceil(Math.max(...series.flatMap((item) => [...item.points.values()].map((point) => numberOrZero(point.share)))) / 10) * 10); - const xFor = (index) => pad.left + (electionOrder.length <= 1 ? plotWidth / 2 : (index / (electionOrder.length - 1)) * plotWidth); - const yFor = (share) => pad.top + plotHeight - (numberOrZero(share) / maxShare) * plotHeight; - const grid = [0, 10, 20, 30, 40, 50, 60].filter((value) => value <= maxShare).map((value) => { - const y = yFor(value); - return `${value}%`; - }).join(''); - const xLabels = electionOrder.map((key, index) => { - if (electionOrder.length > 14 && index % Math.ceil(electionOrder.length / 10) !== 0 && index !== electionOrder.length - 1) return ''; - const entry = electionByKey.get(key); - return `${escapeHtml(shortTrendLabel(entry))}`; - }).join(''); - const seriesMarkup = series.map((item) => { - const orderedPoints = electionOrder - .map((key, index) => ({ key, index, point: item.points.get(key) })) - .filter((row) => row.point); - const linePoints = orderedPoints.map((row) => `${xFor(row.index).toFixed(1)},${yFor(row.point.share).toFixed(1)}`).join(' '); - const markers = orderedPoints.map((row) => trendMarkerSvg( - trendMarkerKind(row.point.entry), - xFor(row.index), - yFor(row.point.share), - safeCssColour(item.colour), - `${item.party}: ${formatFixedPercent(row.point.share)} at ${shortTrendLabel(row.point.entry)}` - )).join(''); - return `${markers}`; - }).join(''); - const legend = series.map((item) => ` - - ${escapeHtml(item.party)} - - `).join(''); + const notes = []; + notes.push(includeAllTypes + ? 'All election types available for this geography. A line is dotted across elections where the party has no comparable result.' + : 'Current election family only; by-elections are excluded. A line is dotted across elections where the party has no comparable result.'); + if (model.totalSeries > model.series.length) { + notes.push(`The ${model.series.length} largest parties at the most recent election are shown; ${model.totalSeries - model.series.length} others are not drawn.`); + } + if (selectionName && comparableCount > model.elections.length + 1) { + notes.push(`Showing ${model.elections.length} of ${comparableCount} comparable elections. ` + + `${selectionName} appears under this name in those elections only; constituencies are ` + + 'renamed and redrawn, and a predecessor under a different name is not yet linked to it.'); + } + const footnotes = ``; const geography = selectedResult?.constituency || selectedResult?.localBody || 'overall results'; - return ` - - - ${grid} - - ${seriesMarkup} - ${xLabels} - - - ${shortSeriesNote} - `; + // Fit the drawing to the pane. The lower pane is short by default and the reader can drag + // it taller; the chart follows, between a floor that keeps the grid legible and a ceiling + // that stops it sprawling. + const paneContent = chart.closest('.election-pane__content'); + const chartHeight = (width) => { + const chrome = 150; // Title, caption, key and footnotes above and below the drawing. + const available = paneContent ? paneContent.clientHeight - chrome : 0; + const ceiling = width < 560 ? 216 : width >= 900 ? 320 : 256; + return Math.max(200, Math.min(ceiling, available || ceiling)); + }; + this.trendChart = mountTrendChart(chart, model, { + ariaLabel: `Party vote share over time for ${geography}`, + formatDate: formatElectionDate, + footnotes, + height: chartHeight, + fitTo: paneContent + }); } formatNumberForPane(value) { @@ -5381,17 +5365,19 @@ function formatMainDelta(value) { return `${number > 0 ? '+' : ''}${number.toLocaleString('en-GB')}`; } +// Share changes carry `election-delta--share` so the pane can colour them alone: a table where +// every count change is also green or red says nothing about which change matters. function formatMainPercentDelta(value) { const number = Number(value); if (!Number.isFinite(number)) return ''; - const className = number > 0 ? 'election-delta election-delta--pos' : number < 0 ? 'election-delta election-delta--neg' : 'election-delta'; + const className = number > 0 ? 'election-delta election-delta--share election-delta--pos' : number < 0 ? 'election-delta election-delta--share election-delta--neg' : 'election-delta election-delta--share'; return `${number > 0 ? '+' : ''}${number.toFixed(2)}%`; } function formatMainSelectedPercentDelta(value) { const number = Number(value); if (!Number.isFinite(number)) return ''; - const className = number > 0 ? 'election-delta election-delta--pos' : number < 0 ? 'election-delta election-delta--neg' : 'election-delta'; + const className = number > 0 ? 'election-delta election-delta--share election-delta--pos' : number < 0 ? 'election-delta election-delta--share election-delta--neg' : 'election-delta election-delta--share'; return `${number > 0 ? '+' : ''}${number.toFixed(2)}`; } @@ -5476,47 +5462,6 @@ function electionTrendJurisdiction(entry = {}) { return null; } -function shortTrendLabel(entry = {}) { - const date = String(entry.date || ''); - const year = date.slice(0, 4) || ''; - const body = shortElectionBody(entry.body || entry.displayProvider || entry.displayTitle || ''); - return [year, body].filter(Boolean).join(' '); -} - -function trendMarkerKind(entry = {}) { - const family = electionTrendFamily(entry); - if (/westminster|uk general/.test(family)) return 'triangle'; - if (/local/.test(family)) return 'square'; - if (/european/.test(family)) return 'diamond'; - if (/devolved/.test(family)) return 'circle'; - if (/irish general/.test(family)) return 'pentagon'; - return 'circle'; -} - -function trendMarkerSvg(kind, x, y, colour, label) { - const safeColour = escapeHtml(safeCssColour(colour)); - const safeLabel = escapeHtml(label || ''); - const cx = Number(x).toFixed(1); - const cy = Number(y).toFixed(1); - if (kind === 'triangle') { - return `${safeLabel}`; - } - if (kind === 'square') { - return `${safeLabel}`; - } - if (kind === 'diamond') { - return `${safeLabel}`; - } - if (kind === 'pentagon') { - const points = [0, 1, 2, 3, 4].map((index) => { - const angle = -Math.PI / 2 + index * 2 * Math.PI / 5; - return `${(Number(x) + Math.cos(angle) * 7).toFixed(1)},${(Number(y) + Math.sin(angle) * 7).toFixed(1)}`; - }).join(' '); - return `${safeLabel}`; - } - return `${safeLabel}`; -} - function inferCountEvents(candidates = [], countNumbers = []) { const events = []; for (const count of countNumbers) { diff --git a/app/src/test2.css b/app/src/test2.css index 91afda42fc..c4e43aeb87 100644 --- a/app/src/test2.css +++ b/app/src/test2.css @@ -121,6 +121,11 @@ body.app-shell .app-main { flex: 0 0 auto; } +/* Hidden while an election is open: there is no boundary sequence to play. */ +.pane--map > #timelineSlider.timeline-slider .timeline-playback-group--hidden { + display: none; +} + .pane--map > #timelineSlider.timeline-slider .timeline-btn--play.is-playing, .pane--map > #timelineSlider.timeline-slider .timeline-btn--play.is-replay { color: #fff; @@ -1297,109 +1302,358 @@ body.test2-election-pane-resizing * { } .test2-election-trends { + --trend-surface: var(--color-surface, #fff); + --trend-text: var(--color-text, #111827); + --trend-muted: var(--color-text-muted, #6b7280); + --trend-grid: rgba(15, 23, 42, .09); + --trend-baseline: rgba(15, 23, 42, .3); + --trend-crosshair: rgba(15, 23, 42, .4); + --trend-hover: rgba(15, 23, 42, .06); display: grid; - gap: 10px; - padding: 10px; - border: 1px solid var(--color-border, #d8e0ea); + gap: 6px; + padding: 10px 12px 6px; border-radius: 6px; - background: var(--color-surface, #fff); + background: var(--trend-surface); + color: var(--trend-text); + font-family: var(--font-sans, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif); } .test2-election-trends__header { display: flex; - align-items: start; + align-items: flex-start; justify-content: space-between; - gap: 14px; + gap: 12px 18px; flex-wrap: wrap; } .test2-election-trends__header h3 { margin: 0; - color: var(--color-text, #111827); + color: var(--trend-text); font-size: 15px; - line-height: 1.2; + font-weight: 700; + line-height: 1.25; + letter-spacing: -0.01em; } -.test2-election-trends__header p, -.test2-election-trends__note { - margin: 3px 0 0; - color: var(--color-text-muted, #64748b); - font-size: 12px; +.test2-election-trends__header p { + margin: 2px 0 0; + color: var(--trend-muted); + font-size: 12.5px; + line-height: 1.4; } .test2-election-trends__scope { display: inline-flex; align-items: center; - gap: 7px; - color: var(--color-text, #111827); + gap: 6px; + color: var(--trend-muted); font-size: 12px; - font-weight: 700; + font-weight: 500; + cursor: pointer; + white-space: nowrap; +} + +.test2-election-trends__scope input { + margin: 0; + accent-color: var(--color-accent, #2563eb); } .test2-election-trends__chart { + min-width: 0; max-width: 100%; - overflow-x: auto; } +.test2-election-trends__loading, +.test2-election-trends__chart > .election-no-data { + margin: 0; + padding: 18px 0; + color: var(--trend-muted); + font-size: 12.5px; +} + +.trend-chart { + position: relative; + display: grid; + gap: 4px; +} + +/* Compact key. Doubles as the touch-friendly party focus control. */ .test2-election-trends__legend { display: flex; align-items: center; - gap: 10px; flex-wrap: wrap; - margin-bottom: 4px; - color: var(--color-text, #111827); - font-size: 12px; - font-weight: 700; + gap: 0 6px; + margin: 0 0 0 -4px; + font-size: 11.5px; + line-height: 1.25; } .test2-election-trends__legend-item { display: inline-flex; align-items: center; - gap: 4px; + gap: 5px; + margin: 0; + padding: 2px 4px; + border: 0; + border-radius: 4px; + background: none; + color: var(--trend-text); + font: inherit; + font-size: 11.5px; + cursor: pointer; + transition: opacity .15s ease, background-color .15s ease; } -.test2-election-trends__legend-item span { - width: 18px; - height: 4px; - border: 1px solid rgba(15, 23, 42, .35); - border-radius: 999px; +.test2-election-trends__legend-item:hover { + background: var(--trend-hover); +} + +.test2-election-trends__legend-item:focus-visible { + outline: 2px solid var(--color-accent, #2563eb); + outline-offset: 1px; +} + +.test2-election-trends__legend-item[aria-pressed="true"] { + font-weight: 700; +} + +.test2-election-trends__legend-swatch { + flex: 0 0 auto; + width: 14px; + height: 3px; + border-radius: 2px; +} + +.trend-chart__stage { + position: relative; + min-width: 0; } .test2-election-trends__svg { + display: block; width: 100%; - min-width: 680px; height: auto; - display: block; + overflow: visible; + font-family: inherit; + touch-action: pan-y; + outline: none; + -webkit-user-select: none; + user-select: none; + -webkit-tap-highlight-color: transparent; +} + +.test2-election-trends__svg:focus-visible { + outline: 2px solid var(--color-accent, #2563eb); + outline-offset: 4px; + border-radius: 2px; } .trend-grid { - stroke: var(--color-border, #d8e0ea); + stroke: var(--trend-grid); stroke-width: 1; + shape-rendering: crispEdges; } -.trend-axis, -.trend-axis-line { - fill: var(--color-text-muted, #64748b); - stroke: var(--color-text-muted, #64748b); - font-size: 11px; +.trend-grid--baseline { + stroke: var(--trend-baseline); } -.trend-axis-line { - stroke-width: 1.2; +.trend-election-tick { + stroke: var(--trend-baseline); + stroke-width: 1; + shape-rendering: crispEdges; +} + +.trend-axis { + fill: var(--trend-muted); + font-size: 11.5px; + font-variant-numeric: tabular-nums; +} + +.trend-series { + transition: opacity .15s ease; } .trend-line { fill: none; stroke: var(--trend-colour, #64748b); - stroke-width: 3.5; + stroke-width: 2.25; stroke-linecap: round; stroke-linejoin: round; + transition: stroke-width .15s ease; +} + +.trend-hit { + fill: none; + stroke: transparent; + stroke-width: 14; + stroke-linecap: round; + stroke-linejoin: round; + pointer-events: stroke; + cursor: pointer; +} + +.trend-dot { + fill: var(--trend-colour, #64748b); +} + +.trend-gap { + fill: none; + stroke: var(--trend-colour, #64748b); + stroke-width: 1.25; + stroke-dasharray: 2 4; + stroke-linecap: round; + opacity: .5; } .trend-marker { fill: var(--trend-colour, #64748b); - stroke: #111827; - stroke-width: 2.3; + stroke: var(--trend-surface); + stroke-width: 1.5; + opacity: 0; + pointer-events: none; + transition: opacity .12s ease; +} + +.trend-marker.is-active, +.trend-series.is-focused .trend-marker { + opacity: 1; +} + +.trend-series.is-focused .trend-line { + stroke-width: 3; +} + +.trend-chart[data-trend-focus] .trend-series:not(.is-focused) { + opacity: .16; +} + +.trend-chart[data-trend-focus] .trend-label:not(.is-focused) { + opacity: .28; +} + +.trend-chart[data-trend-focus] .test2-election-trends__legend-item:not(.is-focused) { + opacity: .45; +} + +.trend-label { + cursor: pointer; + transition: opacity .15s ease; +} + +.trend-label text { + fill: var(--trend-colour, #64748b); + font-size: 12px; + font-variant-numeric: tabular-nums; + paint-order: stroke; + stroke: var(--trend-surface); + stroke-width: 3px; + stroke-linejoin: round; +} + +.trend-label__value { + font-weight: 600; +} + +.trend-label-leader { + stroke: var(--trend-colour, #64748b); + stroke-width: 1; + opacity: .55; +} + +.trend-crosshair { + display: none; + stroke: var(--trend-crosshair); + stroke-width: 1; + stroke-dasharray: 3 3; + pointer-events: none; + shape-rendering: crispEdges; +} + +.trend-crosshair.is-active { + display: block; +} + +.trend-tooltip { + position: absolute; + z-index: 5; + min-width: 150px; + max-width: 250px; + padding: 7px 10px 8px; + border: 1px solid var(--color-border, #d8e0ea); + border-radius: 6px; + background: var(--trend-surface); + color: var(--trend-text); + box-shadow: 0 4px 14px rgba(15, 23, 42, .14); + font-size: 12px; + line-height: 1.35; + pointer-events: none; +} + +.trend-tooltip__title { + font-weight: 700; +} + +.trend-tooltip__subtitle { + color: var(--trend-muted); + font-size: 11px; +} + +.trend-tooltip__table { + width: 100%; + margin-top: 4px; + border-collapse: collapse; +} + +.trend-tooltip__table td { + padding: 1px 0; + white-space: nowrap; +} + +.trend-tooltip__table tr.is-focused td { + font-weight: 700; +} + +.trend-tooltip__value { + padding-left: 14px !important; + text-align: right; + font-variant-numeric: tabular-nums; + font-weight: 600; +} + +.trend-tooltip__swatch { + display: inline-block; + width: 10px; + height: 3px; + margin: 0 6px 3px 0; + border-radius: 2px; + vertical-align: middle; +} + +.test2-election-trends__notes { + display: grid; + gap: 2px; +} + +.test2-election-trends__note { + margin: 0; + color: var(--trend-muted); + font-size: 11px; + line-height: 1.4; +} + +@media (max-width: 640px) { + .test2-election-trends { + padding: 10px 8px 6px; + } + + .test2-election-trends__header h3 { + font-size: 14px; + } + + .trend-tooltip { + max-width: 200px; + } } @media (max-width: 1100px) { @@ -1435,35 +1689,22 @@ body.test2-election-pane-resizing * { [data-theme="dark"] .test2-source-panel__group, [data-theme="dark"] .test2-election-table th, [data-theme="dark"] .test2-election-table__summary, -[data-theme="dark"] .test2-election-trends__legend, [data-theme="dark"] .test2-fptp-vote-graphic__title { background: var(--color-surface-elevated, #1c2128); border-color: var(--color-border, #3d444d); color: var(--color-text, #f7fafc); } -[data-theme="dark"] .test2-election-trends__header h3, -[data-theme="dark"] .test2-election-trends__scope { - color: var(--color-text, #f7fafc); +[data-theme="dark"] .test2-election-trends { + --trend-muted: var(--color-text-muted, #a8b3c5); + --trend-grid: rgba(255, 255, 255, .1); + --trend-baseline: rgba(255, 255, 255, .32); + --trend-crosshair: rgba(255, 255, 255, .45); + --trend-hover: rgba(255, 255, 255, .08); } -[data-theme="dark"] .test2-election-trends__header p, -[data-theme="dark"] .test2-election-trends__note { - color: var(--color-text-muted, #a8b3c5); -} - -[data-theme="dark"] .trend-grid { - stroke: #3d444d; -} - -[data-theme="dark"] .trend-axis, -[data-theme="dark"] .trend-axis-line { - fill: #a8b3c5; - stroke: #a8b3c5; -} - -[data-theme="dark"] .trend-marker { - stroke: #f7fafc; +[data-theme="dark"] .trend-tooltip { + box-shadow: 0 4px 16px rgba(0, 0, 0, .5); } [data-theme="dark"] .test2-election-table td, @@ -1513,35 +1754,22 @@ body.test2-election-pane-resizing * { :root:not([data-theme="light"]) .test2-source-panel__group, :root:not([data-theme="light"]) .test2-election-table th, :root:not([data-theme="light"]) .test2-election-table__summary, - :root:not([data-theme="light"]) .test2-election-trends__legend, :root:not([data-theme="light"]) .test2-fptp-vote-graphic__title { background: var(--color-surface-elevated, #1c2128); border-color: var(--color-border, #3d444d); color: var(--color-text, #f7fafc); } - :root:not([data-theme="light"]) .test2-election-trends__header h3, - :root:not([data-theme="light"]) .test2-election-trends__scope { - color: var(--color-text, #f7fafc); + :root:not([data-theme="light"]) .test2-election-trends { + --trend-muted: var(--color-text-muted, #a8b3c5); + --trend-grid: rgba(255, 255, 255, .1); + --trend-baseline: rgba(255, 255, 255, .32); + --trend-crosshair: rgba(255, 255, 255, .45); + --trend-hover: rgba(255, 255, 255, .08); } - :root:not([data-theme="light"]) .test2-election-trends__header p, - :root:not([data-theme="light"]) .test2-election-trends__note { - color: var(--color-text-muted, #a8b3c5); - } - - :root:not([data-theme="light"]) .trend-grid { - stroke: #3d444d; - } - - :root:not([data-theme="light"]) .trend-axis, - :root:not([data-theme="light"]) .trend-axis-line { - fill: #a8b3c5; - stroke: #a8b3c5; - } - - :root:not([data-theme="light"]) .trend-marker { - stroke: #f7fafc; + :root:not([data-theme="light"]) .trend-tooltip { + box-shadow: 0 4px 16px rgba(0, 0, 0, .5); } :root:not([data-theme="light"]) .test2-election-table td, @@ -1931,3 +2159,234 @@ body.test2-election-pane-resizing * { color: var(--color-text-muted, #a8b3c5); } } + +/* ------------------------------------------------------------------------------------------ + Election pane tables (By Party, By Candidate, By Local Party), restyled to sit with the + Trends chart: white surface, hairline row rules, no vertical grid, quiet bold headers, + plain dark links, softer change colours. Scoped to the map app's election pane so the + shared table rules in assets/css/main.css keep serving the rest of the site unchanged. + ------------------------------------------------------------------------------------------ */ +.election-pane__content { + --table-surface: var(--color-surface, #fff); + --table-text: var(--color-text, #111827); + --table-muted: var(--color-text-muted, #6b7280); + --table-rule: rgba(15, 23, 42, .1); + --table-header-rule: rgba(15, 23, 42, .35); + --table-hover: rgba(15, 23, 42, .045); + --table-pos: #1f7a46; + --table-neg: #b83a2c; + --table-link: var(--color-primary, #1a4b8c); + --table-link-rule: rgba(26, 75, 140, .35); +} + +.election-pane__content .election-party-wrapper, +.election-pane__content .election-count-wrapper { + border: 0; + border-radius: 0; + background: var(--table-surface); +} + +.election-pane__content .election-party-table, +.election-pane__content .election-count-table { + background: var(--table-surface); + color: var(--table-text); + font-family: var(--font-sans, 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif); + font-size: 0.76rem; + line-height: 1.3; +} + +.election-pane__content .election-party-table th, +.election-pane__content .election-party-table td, +.election-pane__content .election-count-table th, +.election-pane__content .election-count-table td { + border: 0; + border-bottom: 1px solid var(--table-rule); + padding: 6px 8px; + background: var(--table-surface); + color: var(--table-text); +} + +/* Header rows: no fill, bold labels, one firmer rule under the last header row. */ +.election-pane__content .election-party-table th, +.election-pane__content .election-count-table th, +.election-pane__content .election-party-table th:first-child, +.election-pane__content .election-count-table th:first-child, +.election-pane__content .election-party-table--grouped thead tr:nth-child(1) th, +.election-pane__content .election-count-table--grouped thead tr:nth-child(1) th, +.election-pane__content .election-party-table--grouped thead tr:nth-child(2) th, +.election-pane__content .election-count-table--grouped thead tr:nth-child(2) th, +.election-pane__content .election-party-table--grouped thead tr:nth-child(3) th, +.election-pane__content .election-count-table--grouped thead tr:nth-child(3) th { + background: var(--table-surface); + color: var(--table-text); + font-weight: 700; + border-bottom: 0; + box-shadow: 0 1px 0 var(--table-rule); +} + +.election-pane__content .election-party-table--grouped thead tr:nth-child(1) th:not([rowspan]), +.election-pane__content .election-count-table--grouped thead tr:nth-child(1) th:not([rowspan]), +.election-pane__content .election-count-table--grouped thead tr:nth-child(2) th:not([rowspan]) { + color: var(--table-muted); + font-weight: 600; + font-size: 0.72rem; + letter-spacing: .02em; + text-transform: uppercase; +} + +.election-pane__content .election-party-table thead tr:last-child th, +.election-pane__content .election-count-table thead tr:last-child th, +.election-pane__content .election-party-table thead th[rowspan], +.election-pane__content .election-count-table thead th[rowspan] { + box-shadow: 0 1.5px 0 var(--table-header-rule); +} + +.election-pane__content .election-th-indicator { + color: var(--color-accent, #2563eb); +} + +/* Cell fills and rules. The shared sheet pins frozen columns with their own grey fills and + shadows through many specific selectors (and dark-theme copies of each), so this layer + states the fill once, with !important, for every body cell except the party colour tab. */ +.election-pane__content .election-party-table tbody td:not(.election-colour-col), +.election-pane__content .election-count-table tbody td:not(.election-colour-col) { + background: var(--table-surface) !important; + border: 0 !important; + box-shadow: inset 0 -1px 0 var(--table-rule) !important; + color: var(--table-text); +} + +.election-pane__content .election-party-table thead th, +.election-pane__content .election-count-table thead th { + border: 0 !important; + box-shadow: inset 0 -1px 0 var(--table-rule) !important; +} + +.election-pane__content .election-party-table thead tr:last-child th, +.election-pane__content .election-count-table thead tr:last-child th, +.election-pane__content .election-party-table thead th[rowspan], +.election-pane__content .election-count-table thead th[rowspan] { + box-shadow: inset 0 -1.5px 0 var(--table-header-rule) !important; +} + +/* No zebra striping; a light wash on hover only. */ +.election-pane__content .election-party-table tbody tr:hover td:not(.election-colour-col), +.election-pane__content .election-count-table tbody tr:hover td:not(.election-colour-col) { + background: var(--table-hover) !important; +} + +/* Totals row: bold, upright, closed with a firmer rule above. */ +.election-pane__content .election-table-summary-row td:not(.election-colour-col) { + color: var(--table-text); + font-style: normal; + font-weight: 600; + box-shadow: inset 0 1.5px 0 var(--table-header-rule), inset 0 -1px 0 var(--table-rule) !important; +} + +/* Text reads from the left; numbers stay on the right. */ +.election-pane__content .election-party-table tbody td:has(.election-entity-link), +.election-pane__content .election-count-table tbody td:has(.election-entity-link), +.election-pane__content td.election-party-cell { + text-align: left; +} + +/* One link per row: the row's own name (candidate, party or constituency) in dark text with a + quiet underline. The other linked cells in the row are plain until hovered. */ +.election-pane__content .election-entity-link { + color: var(--table-text); + text-decoration: underline; + text-decoration-color: var(--table-link-rule); + text-decoration-thickness: 1px; + text-underline-offset: 2px; +} + +.election-pane__content .election-count-table .election-entity-link:not([data-election-entity-kind="candidate"]), +.election-pane__content .election-results-table--district .election-entity-link[data-election-entity-kind="party"] { + text-decoration-color: transparent; +} + +.election-pane__content .election-entity-link:hover, +.election-pane__content .election-entity-link:focus-visible { + color: var(--table-link); + text-decoration-color: currentColor; +} + +.election-pane__content .election-party-table .election-rank-col, +.election-pane__content .election-count-table .election-rank-col { + color: var(--table-muted); + font-variant-numeric: tabular-nums; +} + +.election-pane__content td.election-party-cell::before { + width: 3px; + top: 5px; + bottom: 5px; + border-radius: 2px; +} + +/* Changes: counts and votes in muted grey with their sign; only the share change is coloured. */ +.election-pane__content .election-delta, +.election-pane__content .count-transfer--pos, +.election-pane__content .count-transfer--neg, +.election-pane__content .election-delta--neutral, +.election-pane__content .election-na { + color: var(--table-muted); +} + +.election-pane__content .election-delta--share.election-delta--pos { + color: var(--table-pos); +} + +.election-pane__content .election-delta--share.election-delta--neg { + color: var(--table-neg); +} + +.election-pane__content .election-na em { + font-style: normal; +} + +/* Elected: a filled dot rather than a green tick; the label stays for screen readers. */ +.election-pane__content .election-elected-mark { + display: inline-block; + width: 8px; + height: 8px; + border-radius: 50%; + overflow: hidden; + color: transparent; + font-size: 0; + line-height: 0; + vertical-align: middle; +} + +.election-pane__content .election-elected-mark--yes { + background: var(--table-text); +} + +.election-pane__content .election-elected-mark--no { + background: transparent; + box-shadow: inset 0 0 0 1px var(--table-rule); +} + +[data-theme="dark"] .election-pane__content { + --table-link: #8fb4ff; + --table-link-rule: rgba(143, 180, 255, .4); + --table-muted: var(--color-text-muted, #a8b3c5); + --table-rule: rgba(255, 255, 255, .1); + --table-header-rule: rgba(255, 255, 255, .38); + --table-hover: rgba(255, 255, 255, .06); + --table-pos: #4ade80; + --table-neg: #f87171; +} + +@media (prefers-color-scheme: dark) { + :root:not([data-theme="light"]) .election-pane__content { + --table-link: #8fb4ff; + --table-link-rule: rgba(143, 180, 255, .4); + --table-muted: var(--color-text-muted, #a8b3c5); + --table-rule: rgba(255, 255, 255, .1); + --table-header-rule: rgba(255, 255, 255, .38); + --table-hover: rgba(255, 255, 255, .06); + --table-pos: #4ade80; + --table-neg: #f87171; + } +} diff --git a/assets/css/main.css b/assets/css/main.css index d767b23e4b..cee4d43ecf 100644 --- a/assets/css/main.css +++ b/assets/css/main.css @@ -677,6 +677,198 @@ button.catalogue-flat__toc-toplink { cursor: pointer; } +/* Section switcher above the contents box: one segmented bar, the active section filled + with the site gradient. The links inside keep .catalogue-flat__toc-toplink for the click + handling; everything visual comes from the tab class. */ +.catalogue-flat__sections { + position: sticky; + /* Just below the sticky title-and-search shell; the value is measured by the controller. */ + top: calc(var(--catalogue-sticky-shell-height, 110px) - var(--space-5, 20px)); + z-index: 6; + display: grid; + grid-auto-flow: column; + grid-auto-columns: 1fr; + gap: 4px; + margin: 8px 6px 2px; + padding: 4px; + background: var(--color-surface-elevated, #f7fafc); + border: 1px solid var(--color-border, #e2e8f0); + border-radius: 12px; + box-shadow: 0 2px 8px rgba(15, 23, 42, .06); +} + +.catalogue-flat__sections .catalogue-flat__section-tab { + display: inline-flex; + align-items: center; + justify-content: center; + gap: 8px; + min-height: 36px; + padding: 6px 10px; + border: 0; + border-radius: 9px; + background: var(--color-surface, #fff); + color: var(--color-text, #1a202c); + font-family: inherit; + font-size: 13px; + font-weight: 600; + letter-spacing: 0; + text-transform: none; + text-decoration: none; + line-height: 1; + cursor: pointer; + box-shadow: 0 1px 0 rgba(15, 23, 42, .04); + transition: background-color .15s ease, color .15s ease; +} + +.catalogue-flat__sections .catalogue-flat__section-tab:hover { + background: var(--color-gray-100, #edf2f7); + text-decoration: none; +} + +.catalogue-flat__sections .catalogue-flat__section-tab:focus-visible { + outline: 2px solid var(--color-accent, #2563eb); + outline-offset: 2px; +} + +.catalogue-flat__sections .catalogue-flat__section-tab[aria-current="true"] { + background: linear-gradient(135deg, #12a35f 0%, #0b8a6a 55%, #0a6f79 100%); + color: #fff; + box-shadow: 0 1px 2px rgba(10, 111, 121, .35); +} + +.catalogue-flat__section-icon { + flex: 0 0 auto; + width: 16px; + height: 16px; +} + +/* Section and category headings inside the catalogue: icon beside the title. */ +.category-group-title, +.category-section__header { + display: flex; + align-items: center; + gap: 8px; +} + +.category-group-title { + margin: 20px 0 10px; + font-size: 1rem; + font-weight: 800; + color: var(--color-text, #1a202c); +} + +.category-group-title--pane { + margin: 4px 0 12px; +} + +.category-section__header { + margin: 16px 0 8px; +} + +.category-section__title { + margin: 0; + font-size: 0.95rem; + font-weight: 700; + color: var(--color-text, #1a202c); +} + +.category-section__icon { + display: inline-flex; + align-items: center; + color: var(--color-primary, #1a365d); +} + +.category-group-title .catalogue-flat__section-icon, +.category-section__icon .catalogue-flat__section-icon { + width: 18px; + height: 18px; + color: var(--color-primary, #1a365d); +} + +[data-theme="dark"] .category-group-title .catalogue-flat__section-icon, +[data-theme="dark"] .category-section__icon .catalogue-flat__section-icon { + color: #8fb4ff; +} + +@media (prefers-color-scheme: dark) { + :root:not([data-theme="light"]) .category-group-title .catalogue-flat__section-icon, + :root:not([data-theme="light"]) .category-section__icon .catalogue-flat__section-icon { + color: #8fb4ff; + } +} + +.catalogue-flat__toc-toplinks--stats-only { + justify-content: flex-end; + margin-bottom: 4px; +} + +.catalogue-flat__toc-toplinks--stats-only:empty, +.catalogue-flat__toc-toplinks--stats-only:has(.catalogue-flat__toc-stats:empty) { + display: none; +} + +@media (max-width: 480px) { + .catalogue-flat__sections .catalogue-flat__section-tab { + gap: 6px; + padding: 6px 6px; + font-size: 12px; + } +} + +[data-theme="dark"] .catalogue-flat__sections { + background: var(--color-surface-elevated, #1c2128); + border-color: var(--color-border, #3d444d); +} + +[data-theme="dark"] .catalogue-flat__toc-heading .catalogue-flat__section-icon { + color: #8fb4ff; +} + +[data-theme="dark"] .catalogue-flat__sections .catalogue-flat__section-tab, +[data-theme="dark"] .catalogue-flat__sections button.catalogue-flat__section-tab { + background: var(--color-surface, #0f1419); + color: var(--color-text, #f7fafc); +} + +[data-theme="dark"] .catalogue-flat__sections .catalogue-flat__section-tab:hover, +[data-theme="dark"] .catalogue-flat__sections button.catalogue-flat__section-tab:hover { + background: #232a33; +} + +[data-theme="dark"] .catalogue-flat__sections .catalogue-flat__section-tab[aria-current="true"], +[data-theme="dark"] .catalogue-flat__sections button.catalogue-flat__section-tab[aria-current="true"] { + background: linear-gradient(135deg, #12a35f 0%, #0b8a6a 55%, #0a6f79 100%); + color: #fff; +} + +@media (prefers-color-scheme: dark) { + :root:not([data-theme="light"]) .catalogue-flat__sections { + background: var(--color-surface-elevated, #1c2128); + border-color: var(--color-border, #3d444d); + } + + :root:not([data-theme="light"]) .catalogue-flat__toc-heading .catalogue-flat__section-icon { + color: #8fb4ff; + } + + :root:not([data-theme="light"]) .catalogue-flat__sections .catalogue-flat__section-tab, + :root:not([data-theme="light"]) .catalogue-flat__sections button.catalogue-flat__section-tab { + background: var(--color-surface, #0f1419); + color: var(--color-text, #f7fafc); + } + + :root:not([data-theme="light"]) .catalogue-flat__sections .catalogue-flat__section-tab:hover, + :root:not([data-theme="light"]) .catalogue-flat__sections button.catalogue-flat__section-tab:hover { + background: #232a33; + } + + :root:not([data-theme="light"]) .catalogue-flat__sections .catalogue-flat__section-tab[aria-current="true"], + :root:not([data-theme="light"]) .catalogue-flat__sections button.catalogue-flat__section-tab[aria-current="true"] { + background: linear-gradient(135deg, #12a35f 0%, #0b8a6a 55%, #0a6f79 100%); + color: #fff; + } +} + .catalogue-flat__toc-title { margin: 0 0 var(--space-3) 0; font-size: var(--text-base, 1rem); @@ -799,17 +991,36 @@ button.catalogue-flat__toc-toplink { } .catalogue-flat__toc-heading-row td { - padding-top: 12px; - padding-bottom: 4px; + padding-top: 10px; + padding-bottom: 6px; +} + +/* Each section after the first starts with a rule and a clear gap above it. */ +.catalogue-flat__toc-heading-row:not(:first-child) td { + padding-top: 20px; + border-top: 1px solid var(--color-border, #e2e8f0); +} + +.catalogue-flat__toc-heading-row + tr td, +.catalogue-flat__toc-decade-row td { + padding-bottom: 14px; } .catalogue-flat__toc-heading { - display: inline-block; + display: inline-flex; + align-items: center; + gap: 8px; font-size: 0.95rem; font-weight: 800; color: var(--color-text, #1a202c); } +.catalogue-flat__toc-heading .catalogue-flat__section-icon { + width: 17px; + height: 17px; + color: var(--color-primary, #1a365d); +} + .catalogue-flat__toc-subheading-row td { padding-top: 10px; padding-bottom: 4px; @@ -3121,10 +3332,16 @@ button.catalogue-flat__toc-toplink { } .book-card__thumbnail-icon { + display: inline-flex; font-size: 14px; line-height: 1; } +.book-card__thumbnail-icon .catalogue-flat__section-icon { + width: 16px; + height: 16px; +} + .book-card__thumbnail-label { font-size: 9px; line-height: 1.1; @@ -3186,6 +3403,85 @@ button.catalogue-flat__toc-toplink { margin: 0; } +/* ------------------------------------------------------------------------------------------ + Books section layout. The category heading spans the card grid (it used to take the first + grid cell, pushing the first card to the right column); the thumbnail fallback really hides + once an image is present; and each card is a compact row -- cover at the left, title, + author and date and the actions at the right -- instead of a tall stack. + ------------------------------------------------------------------------------------------ */ +.category-section > .category-section__header { + grid-column: 1 / -1; + margin: 6px 0 2px; +} + +.category-section:has(> .book-card) { + grid-template-columns: repeat(auto-fill, minmax(320px, 1fr)); + gap: 10px; + margin-bottom: 18px; +} + +.book-card__thumbnail-fallback[hidden] { + display: none !important; +} + +#catalogueFlatView .category-section > .book-card, +.category-section > .book-card { + display: flex; + flex-direction: row; + flex-wrap: nowrap; + align-items: flex-start; + gap: 12px; + padding: 12px; + min-height: 0; + border-radius: 10px; +} + +.category-section > .book-card .thumb-zone { + align-self: flex-start; + margin: 0; +} + +.category-section > .book-card .book-card__content { + flex: 1 1 auto; + min-width: 0; + gap: 4px; +} + +.category-section > .book-card .book-card__title { + font-size: 0.9rem; + line-height: 1.3; + display: -webkit-box; + -webkit-box-orient: vertical; + -webkit-line-clamp: 3; + overflow: hidden; +} + +.book-card__meta { + margin: 0; + font-size: var(--text-xs); + line-height: 1.4; + color: var(--color-text-muted); +} + +.book-card__meta .book-card__author { + color: var(--color-primary-light); +} + +.book-card__meta .book-card__author:empty { + display: none; +} + +.book-card__meta .book-card__author:not(:empty) + .book-card__date:not(:empty)::before { + content: '\00b7'; + margin: 0 6px; + color: var(--color-text-muted); +} + +.category-section > .book-card .book-card__actions { + margin-top: 6px; + gap: 6px; +} + #catalogueListView { display: flex; flex-direction: column; @@ -3198,6 +3494,16 @@ button.catalogue-flat__toc-toplink { min-height: 0; } +/* The catalogue list is as tall as its content, not the pane. With flex sizing the view was + clipped to the pane height and its content simply overflowed, which is invisible until + something inside is position: sticky: a sticky child is confined to its parent's box, so + the section bar scrolled away after the first screenful. The book viewer keeps the bounded + height because it scrolls internally. */ +.catalogue-flat-view:not(.catalogue-flat-view--book-viewer) { + flex: 0 0 auto; + min-height: auto; +} + .catalogue-flat-view--book-viewer { display: flex; min-height: 0; diff --git a/assets/pages/css/about.css b/assets/pages/css/about.css index 53daf9f7c3..3e498df9d5 100644 --- a/assets/pages/css/about.css +++ b/assets/pages/css/about.css @@ -8,9 +8,10 @@ .hero__grid--single { grid-template-columns: 1fr; } .hero--interior .lede { max-width: 60ch; } -/* Text-led page: give the prose a comfortable measure and a little more air. */ +/* The prose runs the full width of the same wide wrapper the Home page uses, so the two + pages line up; only a little more air between sections. */ main > .wrap > section > p, -main > .wrap > section > ul { max-width: 68ch; } +main > .wrap > section > ul { max-width: none; } main > .wrap > section > h2 { margin-top: 2.6rem; } /* .shot-hero exists on the Home page to pull the lead screenshot UP into the gradient @@ -21,7 +22,7 @@ main > .wrap > section > h2 { margin-top: 2.6rem; } /* Numbered method steps. The review asked for the digitising process as a step by step example rather than narrative prose, so it is an
      and reads as a procedure. */ -.method-steps { counter-reset: step; list-style: none; padding-left: 0; max-width: 68ch; } +.method-steps { counter-reset: step; list-style: none; padding-left: 0; } .method-steps > li { counter-increment: step; position: relative; @@ -51,7 +52,6 @@ main > .wrap > section > h2 { margin-top: 2.6rem; } background: var(--color-gray-50); padding: 1.15rem 1.35rem; margin: 1.5rem 0 2rem; - max-width: 68ch; } .correction-box h3 { margin: 0 0 .5rem; @@ -65,7 +65,7 @@ main > .wrap > section > h2 { margin-top: 2.6rem; } /* Source categories. The review asked for the breadth of sources to be shown rather than asserted, as grouped categories with examples. Generated from the catalogue's provider field, so it stays true: 58 organisations across 75 provider strings. */ -.sources-list { margin: 1.1rem 0 1.4rem; padding: 0; list-style: none; max-width: 72ch; } +.sources-list { margin: 1.1rem 0 1.4rem; padding: 0; list-style: none; } .sources-list > li { padding: .55rem 0 .55rem 1rem; border-left: 2px solid var(--color-border); @@ -83,7 +83,7 @@ main > .wrap > section > h2 { margin-top: 2.6rem; } /* Named projects. Distinct from the broad "ways to contribute" list above it: that list answers "how can I help", this one answers "what specifically needs doing". */ -.project-list { list-style: none; padding: 0; margin: 1rem 0 1.3rem; max-width: 70ch; } +.project-list { list-style: none; padding: 0; margin: 1rem 0 1.3rem; } .project-list > li { border: 1px solid var(--color-border); border-radius: var(--radius-md); diff --git a/docs/election-trends-chart-and-catalogue-ui.md b/docs/election-trends-chart-and-catalogue-ui.md new file mode 100644 index 0000000000..a5a31e2230 --- /dev/null +++ b/docs/election-trends-chart-and-catalogue-ui.md @@ -0,0 +1,200 @@ +# Election Trends chart redesign, election tables, catalogue section bar and Books layout + +Everything this change touches, file by file, with the reasoning. Written for review of +the pull request that introduces it. + +## Summary + +1. The Trends tab of the election pane draws a newsroom-style line chart of party vote share + over time (Datawrapper-like), replacing the marker-heavy chart. +2. The By Party, By Candidate and By Local Party tables in the election pane are restyled to + sit with the chart. +3. The timeline play and stop buttons are hidden while an election is open, since they only + ever animate boundary layers. +4. The About page uses the same wide wrapper as Home and its prose fills it. +5. The maps catalogue gets a pinned section bar (Elections, Maps, Books, Tables) with Lucide + icons, icons on the headings inside the contents box, Lucide icons in place of the emoji in + the Books section, and a compact row layout for book cards. + +The election data pipeline, the comparable-election filter, the map, URL and hash state, +selectors, overlays, party colours, the shared table styles used elsewhere on the site and the +Browse page are unchanged. + +## Files + +| File | Change | +|---|---| +| `src/election-trend-chart.mjs` | **New.** Pure `buildTrendChartModel`, `layoutTrendChart` and `renderTrendChartSvg` builders plus `mountTrendChart`, which binds hover, tooltip, party focus, keyboard and resize handling. No DOM dependency in the builders, so they run in Node. | +| `app/src/election-manager.js` | Trends panel markup; `hydrateTrendsPanel` caches points instead of markup and mounts the chart; the old inline SVG renderer, `trendMarkerSvg`, `trendMarkerKind` and `shortTrendLabel` are removed; `loadTrendSummary` falls back to the static bundle when the elections API is unavailable, the same way `loadBundle` already did; share-change cells carry `election-delta--share`; imports the new module and `partyAbbreviation`. | +| `app/src/app.js` | `updateTimelineAnimationButtons` hides the playback group while an election is open. | +| `app/src/test2.css` | Trends chart styles (light and dark); a scoped layer restyling the election pane tables; the hidden playback group rule. | +| `src/ui-controller.js` | The four catalogue section links move out of the contents box into a `nav.catalogue-flat__sections` segmented bar with Lucide icons; the active tab is remembered on the controller across re-renders; the shell height is published as a custom property for the pinned bar; the scroll-to-target offset includes the bar; all catalogue Lucide icons live in one `LUCIDE_ICON_PATHS` map with `lucideIcon()` and `bookCategoryIcon()`; the Elections and Maps headings inside the box carry icons; Books category headings and card badges use Lucide icons by category id instead of the emoji from `data/database/books.json`; book cards put author and date on one `book-card__meta` line and move the transcription notice into the Markdown button's tooltip. | +| `maps/index.html` | A "Tables" heading with the table icon at the top of the Tables pane. Cache tokens refreshed by the build. | +| `assets/css/main.css` | Segmented bar styles, pinned position and dark theme; spacing and rules between the box's sections; heading icon sizing and colours; the catalogue list sized to its content (see "Why the flat view is no longer flex-sized"); Books grid with the heading spanning the row, the cover fallback hidden once a cover exists, and row-layout cards. | +| `assets/pages/css/about.css` | Prose, lists and boxes no longer capped at about 68 characters. | +| `pages/about.html` | Uses `wrap--wide` like Home; the About stylesheet link carries a content-hash `?v=` so browsers pick up changes. | +| `app/build/*`, `sw.js` | Rebuilt bundle and refreshed cache tokens, via the project's own build scripts. | +| `docs/election-trends-chart-and-catalogue-ui.md` | This file. | + +## 1. Election Trends chart + +### Visual treatment + +- Thin 2.25 px party lines in Civgraph's existing party colours, no outlines, no permanent + markers. +- White surface, faint horizontal grid, a baseline, no other axis chrome. +- Real time axis with upright year labels at a sensible interval; a small tick marks each + election. Elections on the same day (local and European in the Republic, for example) are + nudged apart by a minimum column gap so they stay distinguishable. +- Percentages on the y-axis. The top gridline is a round number at or just above the highest + value, capped at 100. +- Direct labels at the end of each line with the party's latest share. As width shrinks the + label uses the full name, then the abbreviation, then the value only, then disappears below + 560 px (the key and the tooltip carry the names). Labels are pushed apart so they never + overlap; a short leader joins a label that had to move away from its line. Two parties whose + abbreviations collide ("Independent" and "Non party/Independent" are both "Ind") keep their + full names. +- Real gaps where a party has no comparable result: the solid line stops, a faint dotted bridge + crosses the missing elections so the fragments still read as one series, and an isolated + single result is drawn as a dot. No value is drawn for an election the party did not contest. + +### Interaction + +- Hover or touch shows a dashed crosshair at the nearest election, markers on every line at + that election, and a tooltip with the date, the body and every charted party's share in + descending order. On touch the crosshair stays pinned until a tap elsewhere. +- Hover, click or tap on a line, its label or its key entry emphasises that party and fades the + rest; clicking again, clicking empty chart space, or Escape resets. The key is a row of + buttons, so this works on touch and by keyboard. Arrow keys move the crosshair when the chart + is focused. +- The chart re-renders at the container's real width, so text never scales, and follows the + pane when it is resized, between 200 px and 320 px tall. + +### Data + +- Same `loadTrendSummary` and `buildTrendSummary` path, same comparable-election filter, same + by-election exclusion, same scope toggle. +- Series selection: up to eight parties; those standing at the most recent election first, + ordered by their share there, then any others by their peak. The footnote says how many were + left out. The previous ranking led with the last-known share, which put 1918 Unionist and + Nationalist single points ahead of every current party. +- `loadTrendSummary` now falls back to the static election JSON when the `_api` route answers + with an error, matching `loadBundle`. Without it a static server showed only the active and + previous elections in the chart. + +### Test hooks kept + +`#test2ElectionTrendsChart svg`, `.test2-election-trends__svg`, +`.test2-election-trends__legend-item` and `.trend-marker title` all still exist, so the +existing Playwright specs pass unchanged. + +## 2. Election pane tables + +A layer at the end of `app/src/test2.css`, scoped to `.election-pane__content`, so the shared +table rules in `assets/css/main.css` keep serving Browse and the catalogue detail pages +unchanged: + +- White surface, hairline rules between rows, no vertical grid, a firmer rule under the header + and above the totals row; frozen columns in the same white with the same rules. +- Bold header labels; group headings in small muted caps; no filled header background. +- No zebra striping; a light wash on the hovered row. +- The site font at a slightly smaller size instead of the condensed face. +- Only the share change is coloured green or red; vote and seat changes are muted grey with + their sign. `formatMainPercentDelta` and `formatMainSelectedPercentDelta` add + `election-delta--share` for this. +- One link per row (the candidate, the party, or the constituency in By Local Party) in dark + text with a thin underline; the other linked cells show the link on hover. +- Party colour as a slim rounded tab; Elected as a filled dot instead of a green tick; N/A + upright and muted. +- Dark-theme tokens for all of the above. + +Several of these rules carry `!important`. The shared stylesheet pins frozen columns with +their own fills and shadows through many specific selectors, each with a dark-theme copy; +stating the fill once, with `!important`, for every body cell except the party colour tab was +the alternative to enumerating all of them. + +## 3. Timeline playback buttons + +`canAnimateTimeline` already returned false whenever an election was open, so the play and +stop buttons sat disabled for the whole election experience. They now hide instead +(`timeline-playback-group--hidden`) and return when the election is closed. + +## 4. About page + +The Home page's content sits in `.wrap--wide` (1120 px). About used the 860 px `.wrap` and +capped its paragraphs at 68 characters. Both wrappers on About are now `wrap--wide` and the +caps are removed, so the text runs the same width as the "Why Civgraph exists" prose on Home. +The About stylesheet is linked with a content-hash `?v=` because it was previously linked +bare, and browsers kept serving the old copy. + +## 5. Maps catalogue + +### Section bar + +Elections, Maps, Books and Tables were a row of uppercase text links inside the contents box. +They are now a segmented bar above it: four equal pills, the active one filled with the site +gradient, each with a Lucide icon (vote, map, book-open, table). The links keep their +`catalogue-flat__toc-toplink` class and data attributes, so `handleFlatTocClick`, the Tables +tab switch and `_markActiveToplink` are unchanged. + +Two things had to change for the bar to work well: + +- **The active tab is remembered on the controller.** The flat view is re-rendered whenever a + section is expanded, which used to wipe `aria-current`. `_markActiveToplink` now records the + target and the markup reads it back. +- **The bar is pinned under the search shell.** It is `position: sticky` with a `top` equal + to the shell's measured height, published as `--catalogue-sticky-shell-height` by + `_syncCatalogueShellHeight` (kept in sync with a `ResizeObserver`, since the title wraps at + narrow widths). `_catalogueStickyHeight` adds the bar to the scroll-to-target offset so a + section heading lands below it rather than behind it. + +### Why the flat view is no longer flex-sized + +`#catalogueListView` is `height: 100%` and `.catalogue-flat-view` was `flex: 1 1 auto; +min-height: 0`, so the view was clipped to the pane height and its content simply overflowed. +That is invisible until something inside is sticky: a sticky child is confined to its parent's +box, so the bar scrolled away after the first screenful. The view (except the book viewer, +which scrolls internally) is now sized to its content. + +### Headings and icons + +The Elections and Maps headings inside the box carry the same icons, and each section after +the first starts with a rule and a clear gap. The Tables pane gets a heading with the table +icon. Icons take a light blue in dark mode. + +### Books + +`data/database/books.json` carries an emoji per category. Those are no longer read for +display; `BOOK_CATEGORY_ICONS` maps category id to a Lucide icon (clipboard-list, landmark, +vote, chart-column, scale, library; book-open for anything unlisted) and it is used for the +category headings and the card thumbnail badge. + +Layout fixes in the Books grid: + +- The category heading occupied the first cell of the two-column grid, so the first card + jumped to the right column. It now spans the row. +- The thumbnail fallback badge was `display: inline-flex`, which beat the `hidden` attribute, + so cover and badge drew on top of each other. `[hidden]` now wins. +- Cards stacked cover, title, author, date, buttons and the transcription notice vertically. + They are now rows: cover at the left, title, author and date on one line, then the buttons. + The notice moved into the Markdown button's tooltip. +- The grid fits as many 320 px columns as the pane allows. + +## Verification + +- `npx playwright test tests/browser/app.spec.js tests/browser/election-layout.spec.js -g Trends`: passes. +- The election tests in `app.spec.js` pass; the party and person link test needs the browse + detail shards (`node scripts/build-browse-indexes.mjs`), which are a gitignored build output. +- Catalogue, Tables and Books tests in `app.spec.js`: pass. +- `npx eslint src/election-trend-chart.mjs app/src/election-manager.js app/src/app.js src/ui-controller.js`: no new warnings. +- `node scripts/validate-app-shell-cache-tokens.mjs`: PASS after each rebuild. +- Shared CSS within its 225 KB budget. +- Checked in a browser at 1920, 1600, 1280, 1000, 700 and 390 px widths, light and dark, with + touch emulation for the phone width. + +## Known, left alone + +- Clicking Maps in the section bar lands part-way into that section rather than on its + heading. This behaves the same before the change. +- The Dáil candidate table is wider than the pane and scrolls sideways with its name columns + pinned, as before. diff --git a/maps/index.html b/maps/index.html index d62237d249..506d9e82de 100644 --- a/maps/index.html +++ b/maps/index.html @@ -54,7 +54,7 @@ - + - - - + + + - + @@ -364,6 +364,7 @@

      Maps of Irish administrative geography and
      +

      Tables

      @@ -724,7 +725,7 @@

      Feature Details

      and animation code are loaded lazily by the /app module bundle. --> - + - + @@ -71,10 +71,10 @@
      -

      About Civgraph

      Civgraph brings together the civic record of Ireland, tied to people, places and events.

      +

      About Civgraph

      Civgraph brings together the civic record of Ireland, tied to people, places and events.

      -
      +

      Civgraph aspires to bring together a wide range of information of all kinds: elections and the candidates; censuses and statistics; deprivation measures; opinion polls; geology and terrain; Parliamentary debates; how politicians voted; archives and scanned books; and political and administrative boundaries. Most of this already exists somewhere public, scattered across portals, archives and old reports, in formats that cannot be easily compared, with some of it not online at all before.

      Civgraph includes multiple layers, such as the original sources, kept whole and verbatim, as texts, maps and tables, scanned or digital; the data derived from them in cleaned, labelled and linked formats, encompassing people, places, geographies and statistics; and tools which take that data as an input and turn it into something usable. The tools are part of the project, not an extension of it.

      Some of those tools exist today. The longer aim is that the whole linked record can be queried and analysed by anyone, and that any practically possible tool can be built on it.

      diff --git a/src/election-trend-chart.mjs b/src/election-trend-chart.mjs new file mode 100644 index 0000000000..3db516f29e --- /dev/null +++ b/src/election-trend-chart.mjs @@ -0,0 +1,778 @@ +/** + * Election trends chart: party vote share over time, drawn the way a newsroom would. + * + * The election manager owns the DATA -- which elections are comparable, which rows belong to + * the selected constituency, what colour a party is -- and hands this module a flat list of + * points. Everything from there is presentation: a multi-series line chart on a real time axis + * with thin lines, a faint horizontal grid, year labels that are never rotated, direct labels + * at the end of each line carrying the latest share, a crosshair with a tooltip at the nearest + * election, and one-tap party focus that fades everything else. + * + * The pure builders (`buildTrendChartModel`, `layoutTrendChart`, `renderTrendChartSvg`) have no + * DOM dependency so they can be exercised in Node. `mountTrendChart` is the browser half. + * + * Gaps are real. A party with no comparable result at an election gets a break in its line, + * not a segment drawn across the hole; the data model is the manager's and is not merged here. + */ + +const SERIES_LIMIT = 8; +const LINE_WIDTH = 2.25; +const LABEL_FONT_SIZE = 12; +const AXIS_FONT_SIZE = 11.5; +const LABEL_GAP = 14; // Minimum vertical distance between two direct labels. +const MIN_COLUMN_GAP = 7; // Minimum horizontal distance between two election columns. +const MIN_TICK_SPACING = 58; // Minimum horizontal distance between two year labels. +const YEAR_STEPS = [1, 2, 5, 10, 20, 25, 50, 100]; + +/* ------------------------------------------------------------------------------------------ */ +/* Model */ +/* ------------------------------------------------------------------------------------------ */ + +/** + * Turn the manager's flat point list into ordered elections and ranked series. + * + * @param {Array<{party:string, share:number, colour:string, entry:object}>} points + * @param {{ seriesLimit?: number, abbreviate?: (party:string)=>string, bodyLabel?: (entry:object)=>string }} [options] + */ +export function buildTrendChartModel(points = [], options = {}) { + const seriesLimit = Math.max(1, Number(options.seriesLimit) || SERIES_LIMIT); + const abbreviate = typeof options.abbreviate === 'function' ? options.abbreviate : (party) => party; + const bodyLabel = typeof options.bodyLabel === 'function' ? options.bodyLabel : (entry) => String(entry?.body || ''); + + const electionByKey = new Map(); + for (const point of points) { + const entry = point?.entry || {}; + const key = entry.key || `${entry.body}|${entry.date}`; + if (!electionByKey.has(key)) { + electionByKey.set(key, { + key, + entry, + date: String(entry.date || ''), + time: parseDateUtc(entry.date), + year: String(entry.date || '').slice(0, 4), + body: bodyLabel(entry) + }); + } + } + const elections = [...electionByKey.values()] + .sort((a, b) => a.date.localeCompare(b.date) || a.body.localeCompare(b.body)); + const indexByKey = new Map(elections.map((election, index) => [election.key, index])); + + const byParty = new Map(); + for (const point of points) { + const entry = point?.entry || {}; + const electionKey = entry.key || `${entry.body}|${entry.date}`; + const index = indexByKey.get(electionKey); + if (index === undefined) continue; + const partyKey = normalizeName(point.party); + if (!partyKey) continue; + if (!byParty.has(partyKey)) { + byParty.set(partyKey, { + key: partyKey, + party: String(point.party || ''), + abbreviation: abbreviate(point.party) || String(point.party || ''), + colour: point.colour, + values: new Array(elections.length).fill(null), + maxShare: 0, + latestShare: 0, + latestIndex: -1 + }); + } + const series = byParty.get(partyKey); + const share = finiteOrZero(point.share); + series.values[index] = { share, votes: finiteOrZero(point.votes), seats: finiteOrZero(point.seats) }; + series.maxShare = Math.max(series.maxShare, share); + if (index >= series.latestIndex) { + series.latestIndex = index; + series.latestShare = share; + } + } + + // Ranking: parties standing at the most recent election first, by their share there, so + // the chart reads as a tracker of the parties a reader knows; then everything else by its + // peak, so a party that mattered once still earns a line when there is room. + const lastIndex = elections.length - 1; + const currentShare = (item) => (lastIndex >= 0 && item.values[lastIndex] ? item.values[lastIndex].share : -1); + const series = [...byParty.values()] + .sort((a, b) => currentShare(b) - currentShare(a) || b.maxShare - a.maxShare || a.party.localeCompare(b.party)) + .slice(0, seriesLimit); + + // Two parties that abbreviate the same way ("Independent" and "Non party/Independent" are + // both "Ind") keep their full names, otherwise a short label would point at the wrong line. + const abbreviationCounts = new Map(); + for (const item of series) abbreviationCounts.set(item.abbreviation, (abbreviationCounts.get(item.abbreviation) || 0) + 1); + for (const item of series) { + if (abbreviationCounts.get(item.abbreviation) > 1) item.abbreviation = item.party; + } + + return { elections, series, totalSeries: byParty.size }; +} + +/* ------------------------------------------------------------------------------------------ */ +/* Layout */ +/* ------------------------------------------------------------------------------------------ */ + +/** + * Compute every coordinate the renderer needs for a given pixel width. + * + * @param {ReturnType} model + * @param {{ width:number, height?:number, measureText?:(text:string, bold?:boolean)=>number, directLabels?:boolean }} options + */ +export function layoutTrendChart(model, options = {}) { + const width = Math.max(240, Math.round(Number(options.width) || 640)); + const narrow = width < 560; + const height = Math.round(Number(options.height) || (narrow ? 216 : 256)); + const measure = typeof options.measureText === 'function' ? options.measureText : estimateTextWidth; + const { elections, series } = model; + + // Y scale: share of the vote, from zero to a round number at or just above the highest point. + const maxShare = series.reduce((max, item) => item.values.reduce((inner, value) => (value ? Math.max(inner, value.share) : inner), max), 0); + const yStep = maxShare <= 25 ? 5 : maxShare <= 60 ? 10 : 20; + const yMax = Math.min(100, Math.max(yStep * 2, Math.ceil(maxShare / yStep) * yStep)); + const yTicks = []; + for (let value = 0; value <= yMax; value += yStep) yTicks.push(value); + const yLabelWidth = Math.max(...yTicks.map((value) => measure(`${value}%`, false, AXIS_FONT_SIZE))); + + // Direct labels: the fullest form that fits in a modest share of the width, else shorter. + const seriesByKey = new Map(series.map((item) => [item.key, item])); + const labelTextFor = (item, mode) => { + const value = formatShare(item.latestShare); + if (mode === 'full') return { name: item.party, value }; + if (mode === 'abbr') return { name: item.abbreviation, value }; + return { name: '', value }; + }; + const labelWidthFor = (item, mode) => { + const text = labelTextFor(item, mode); + return (text.name ? measure(`${text.name} `, false, LABEL_FONT_SIZE) : 0) + measure(text.value, true, LABEL_FONT_SIZE); + }; + let labelMode = 'none'; + let labelWidth = 0; + if (options.directLabels !== false && !narrow && series.length) { + const modes = width >= 760 ? ['full', 'abbr', 'value'] : ['abbr', 'value']; + for (const mode of modes) { + labelMode = mode; + labelWidth = Math.max(...series.map((item) => labelWidthFor(item, mode))); + if (labelWidth <= width * 0.28) break; + } + } + + const pad = { + top: 12, + right: labelMode === 'none' ? 14 : Math.ceil(labelWidth) + 14, + bottom: 26, + left: Math.ceil(yLabelWidth) + 10 + }; + const plot = { + left: pad.left, + right: width - pad.right, + top: pad.top, + bottom: height - pad.bottom + }; + plot.width = Math.max(40, plot.right - plot.left); + plot.height = Math.max(40, plot.bottom - plot.top); + + const yFor = (share) => plot.bottom - (finiteOrZero(share) / yMax) * plot.height; + + // X scale: real time, then nudged so no two elections share a pixel column. + const times = elections.map((election) => election.time); + const timed = times.length > 0 && times.every((time) => Number.isFinite(time)); + const minTime = timed ? Math.min(...times) : 0; + const maxTime = timed ? Math.max(...times) : 0; + const span = maxTime - minTime; + let columns; + if (elections.length <= 1) { + columns = elections.map(() => plot.left + plot.width / 2); + } else if (timed && span > 0) { + columns = times.map((time) => plot.left + ((time - minTime) / span) * plot.width); + } else { + columns = elections.map((election, index) => plot.left + (index / (elections.length - 1)) * plot.width); + } + for (let index = 1; index < columns.length; index += 1) { + columns[index] = Math.max(columns[index], columns[index - 1] + MIN_COLUMN_GAP); + } + const overshoot = columns.length ? columns[columns.length - 1] - plot.right : 0; + if (overshoot > 0 && columns.length > 1) { + const scale = plot.width / (plot.width + overshoot); + for (let index = 0; index < columns.length; index += 1) { + columns[index] = plot.left + (columns[index] - plot.left) * scale; + } + } + + // Piecewise-linear map from a moment in time to a pixel column, through the election anchors. + const xForTime = (time) => { + if (!timed || !columns.length) return plot.left; + if (columns.length === 1) return columns[0]; + if (time <= times[0]) return columns[0] - ((times[0] - time) / span) * plot.width; + for (let index = 1; index < times.length; index += 1) { + if (time <= times[index]) { + const gap = times[index] - times[index - 1]; + const ratio = gap > 0 ? (time - times[index - 1]) / gap : 1; + return columns[index - 1] + (columns[index] - columns[index - 1]) * ratio; + } + } + return columns[columns.length - 1] + ((time - times[times.length - 1]) / span) * plot.width; + }; + + const xTicks = []; + if (timed && elections.length > 1 && span > 0) { + const minYear = new Date(minTime).getUTCFullYear(); + const maxYear = new Date(maxTime).getUTCFullYear(); + const spanYears = Math.max(1, maxYear - minYear); + const step = YEAR_STEPS.find((candidate) => (plot.width / (spanYears / candidate)) >= MIN_TICK_SPACING) || YEAR_STEPS[YEAR_STEPS.length - 1]; + for (let year = Math.ceil(minYear / step) * step; year <= maxYear; year += step) { + const x = xForTime(Date.UTC(year, 0, 1)); + if (x < plot.left - 0.5 || x > plot.right + 0.5) continue; + xTicks.push({ year, x }); + } + if (!xTicks.length) { + xTicks.push({ year: minYear, x: columns[0] }, { year: maxYear, x: columns[columns.length - 1] }); + } + } else { + elections.forEach((election, index) => { + if (election.year) xTicks.push({ year: Number(election.year), x: columns[index] }); + }); + } + + // Series geometry: segments broken at every missing election, isolated points, label anchors. + const seriesLayout = series.map((item) => { + const segments = []; + let current = null; + const isolated = []; + const markers = []; + item.values.forEach((value, index) => { + if (!value) { + current = null; + return; + } + const x = columns[index]; + const y = yFor(value.share); + markers.push({ index, x, y, share: value.share }); + if (!current) { + current = []; + segments.push(current); + } + current.push({ x, y }); + const previous = item.values[index - 1]; + const next = item.values[index + 1]; + if (!previous && !next) isolated.push({ index, x, y }); + }); + // A faint dotted bridge across each gap keeps the series legible without claiming a value + // for the elections the party has no comparable result at. + const bridges = []; + for (let index = 1; index < segments.length; index += 1) { + const from = segments[index - 1][segments[index - 1].length - 1]; + const to = segments[index][0]; + bridges.push({ from, to }); + } + const last = markers.length ? markers[markers.length - 1] : null; + return { + bridges, + key: item.key, + party: item.party, + abbreviation: item.abbreviation, + colour: item.colour, + latestShare: item.latestShare, + latestIndex: item.latestIndex, + segments, + isolated, + markers, + last + }; + }); + + // Direct labels sit at the end of each line, pushed apart so they never overlap, with a + // short leader whenever one had to move away from its point. + const labels = []; + if (labelMode !== 'none') { + const groups = new Map(); + for (const item of seriesLayout) { + if (!item.last) continue; + const anchorX = Math.round(item.last.x); + if (!groups.has(anchorX)) groups.set(anchorX, []); + const source = seriesByKey.get(item.key); + const text = labelTextFor(source, labelMode); + const textWidth = labelWidthFor(source, labelMode); + groups.get(anchorX).push({ + key: item.key, + colour: item.colour, + name: text.name, + value: text.value, + width: textWidth, + pointX: item.last.x, + pointY: item.last.y, + y: item.last.y + }); + } + for (const group of groups.values()) { + group.sort((a, b) => a.pointY - b.pointY); + const top = plot.top + LABEL_FONT_SIZE / 2; + const bottom = plot.bottom + 4; + for (let index = 0; index < group.length; index += 1) { + const floor = index === 0 ? top : group[index - 1].y + LABEL_GAP; + group[index].y = Math.max(group[index].y, floor); + } + for (let index = group.length - 1; index >= 0; index -= 1) { + const ceiling = index === group.length - 1 ? bottom : group[index + 1].y - LABEL_GAP; + group[index].y = Math.min(group[index].y, ceiling); + } + for (let index = 1; index < group.length; index += 1) { + group[index].y = Math.max(group[index].y, group[index - 1].y + LABEL_GAP); + } + for (const label of group) { + label.x = Math.min(label.pointX + 8, width - label.width - 2); + label.leader = Math.abs(label.y - label.pointY) > 5; + labels.push(label); + } + } + } + + return { + width, + height, + narrow, + pad, + plot, + yMax, + yTicks, + yFor, + columns, + xTicks, + labelMode, + series: seriesLayout, + labels + }; +} + +/* ------------------------------------------------------------------------------------------ */ +/* Markup */ +/* ------------------------------------------------------------------------------------------ */ + +/** + * SVG markup for a laid-out chart. Static: interaction state is applied by the mount code. + */ +export function renderTrendChartSvg(model, layout, options = {}) { + const { elections } = model; + const { width, height, plot } = layout; + const ariaLabel = escapeHtml(options.ariaLabel || 'Party vote share over time'); + + const grid = layout.yTicks.map((value) => { + const y = layout.yFor(value).toFixed(1); + const baseline = value === 0 ? ' trend-grid--baseline' : ''; + return `` + + `${value}%`; + }).join(''); + + const electionTicks = layout.columns.map((x) => ( + `` + )).join(''); + + const xLabels = layout.xTicks.map((tick) => { + const anchor = tick.x < plot.left + 16 ? 'start' : tick.x > plot.right - 16 ? 'end' : 'middle'; + const x = anchor === 'start' ? Math.max(tick.x - 2, 2) : anchor === 'end' ? Math.min(tick.x + 2, width - 2) : tick.x; + return `${tick.year}`; + }).join(''); + + const seriesMarkup = layout.series.map((item) => { + const colour = escapeHtml(item.colour); + const path = item.segments + .map((segment) => segment.map((point, index) => `${index === 0 ? 'M' : 'L'}${point.x.toFixed(1)} ${point.y.toFixed(1)}`).join('')) + .join(''); + const dots = item.isolated.map((point) => ( + `` + )).join(''); + const gaps = item.bridges.length + ? `` + : ''; + const markers = item.markers.map((marker) => { + const election = elections[marker.index]; + const title = escapeHtml(`${item.party}: ${formatShare(marker.share)} at ${[election.year, election.body].filter(Boolean).join(' ')}`); + return `${title}`; + }).join(''); + return `` + + gaps + + (path ? `` : '') + + dots + + (path ? `` : '') + + markers + + ''; + }).join(''); + + const labels = layout.labels.map((label) => { + const colour = escapeHtml(label.colour); + const leader = label.leader + ? `` + : ''; + const name = label.name ? `${escapeHtml(label.name)} ` : ''; + return `${leader}` + + `${name}${escapeHtml(label.value)}` + + ''; + }).join(''); + + return `` + + `${grid}${electionTicks}` + + `` + + `${seriesMarkup}` + + `${labels}` + + `${xLabels}` + + ''; +} + +/* ------------------------------------------------------------------------------------------ */ +/* Browser mount */ +/* ------------------------------------------------------------------------------------------ */ + +/** + * Render the chart into `container` and wire up the interactions. Returns a controller with + * `destroy()`; mounting again into the same container destroys the previous instance. + * + * @param {HTMLElement} container + * @param {ReturnType} model + * @param {{ ariaLabel?:string, footnotes?:string, formatDate?:(date:string)=>string, height?:number }} [options] + */ +export function mountTrendChart(container, model, options = {}) { + if (!container) return null; + container.__trendChart?.destroy(); + + const doc = container.ownerDocument; + const root = doc.createElement('div'); + root.className = 'trend-chart'; + root.innerHTML = ` + +
      + + ${options.footnotes || ''} + `; + container.replaceChildren(root); + + const stage = root.querySelector('.trend-chart__stage'); + const tooltip = root.querySelector('.trend-tooltip'); + const legend = root.querySelector('.test2-election-trends__legend'); + const measureText = createTextMeasurer(root); + const formatDate = typeof options.formatDate === 'function' ? options.formatDate : (value) => value; + const seriesByKey = new Map(model.series.map((item) => [item.key, item])); + + const state = { + layout: null, + svg: null, + width: 0, + lockedParty: null, + hoverParty: null, + column: -1, + pinned: false, + destroyed: false + }; + + const effectiveFocus = () => state.hoverParty || state.lockedParty; + + const applyFocus = () => { + const focus = effectiveFocus(); + if (focus) root.setAttribute('data-trend-focus', focus); + else root.removeAttribute('data-trend-focus'); + root.querySelectorAll('[data-party]').forEach((node) => { + node.classList.toggle('is-focused', Boolean(focus) && node.getAttribute('data-party') === focus); + }); + legend.querySelectorAll('[data-party]').forEach((button) => { + button.setAttribute('aria-pressed', state.lockedParty === button.getAttribute('data-party') ? 'true' : 'false'); + }); + }; + + const setColumn = (index) => { + const layout = state.layout; + if (!layout || !state.svg) return; + const next = Number.isInteger(index) && index >= 0 && index < layout.columns.length ? index : -1; + state.column = next; + const crosshair = state.svg.querySelector('.trend-crosshair'); + state.svg.querySelectorAll('.trend-marker.is-active').forEach((node) => node.classList.remove('is-active')); + if (next < 0) { + crosshair.classList.remove('is-active'); + tooltip.hidden = true; + root.classList.remove('is-hovering'); + return; + } + const x = layout.columns[next].toFixed(1); + crosshair.setAttribute('x1', x); + crosshair.setAttribute('x2', x); + crosshair.classList.add('is-active'); + state.svg.querySelectorAll(`.trend-marker[data-election-index="${next}"]`).forEach((node) => node.classList.add('is-active')); + root.classList.add('is-hovering'); + renderTooltip(next); + }; + + const renderTooltip = (index) => { + const election = model.elections[index]; + if (!election) { + tooltip.hidden = true; + return; + } + const rows = model.series + .map((item) => ({ item, value: item.values[index] })) + .filter((row) => row.value) + .sort((a, b) => b.value.share - a.value.share); + const focus = effectiveFocus(); + tooltip.innerHTML = ` +
      ${escapeHtml(formatDate(election.date))}
      + ${election.body ? `
      ${escapeHtml(election.body)}
      ` : ''} + + ${rows.map((row) => ` + + + + `).join('')} +
      ${escapeHtml(row.item.party)}${formatShare(row.value.share)}
      + `; + tooltip.hidden = false; + positionTooltip(index); + }; + + const positionTooltip = (index) => { + const layout = state.layout; + if (!layout) return; + const rootRect = root.getBoundingClientRect(); + const svgRect = state.svg.getBoundingClientRect(); + const scale = svgRect.width / layout.width || 1; + const columnX = (svgRect.left - rootRect.left) + layout.columns[index] * scale; + const tipWidth = tooltip.offsetWidth; + const tipHeight = tooltip.offsetHeight; + let left = columnX + 12; + if (left + tipWidth > rootRect.width - 4) left = columnX - tipWidth - 12; + if (left < 4) left = 4; + let top = (svgRect.top - rootRect.top) + layout.plot.top * scale; + top = Math.max(0, Math.min(top, rootRect.height - tipHeight)); + tooltip.style.left = `${Math.round(left)}px`; + tooltip.style.top = `${Math.round(top)}px`; + }; + + const nearestColumn = (clientX) => { + const layout = state.layout; + if (!layout || !layout.columns.length) return -1; + const rect = state.svg.getBoundingClientRect(); + const scale = rect.width / layout.width || 1; + const x = (clientX - rect.left) / scale; + let best = -1; + let bestDistance = Infinity; + layout.columns.forEach((column, index) => { + const distance = Math.abs(column - x); + if (distance < bestDistance) { + bestDistance = distance; + best = index; + } + }); + return best; + }; + + const partyFromEvent = (event) => { + const target = event.target instanceof Element ? event.target.closest('[data-party]') : null; + return target ? target.getAttribute('data-party') : null; + }; + + const togglePartyLock = (party) => { + if (!party || !seriesByKey.has(party)) return; + state.lockedParty = state.lockedParty === party ? null : party; + state.hoverParty = null; + applyFocus(); + if (state.column >= 0) renderTooltip(state.column); + }; + + const onPointerMove = (event) => { + if (event.pointerType === 'touch') return; + state.hoverParty = partyFromEvent(event); + applyFocus(); + setColumn(nearestColumn(event.clientX)); + }; + + const onPointerLeave = () => { + state.hoverParty = null; + applyFocus(); + if (!state.pinned) setColumn(-1); + }; + + const onPointerDown = (event) => { + if (event.pointerType !== 'touch') return; + state.pinned = true; + setColumn(nearestColumn(event.clientX)); + }; + + const onClick = (event) => { + const party = partyFromEvent(event); + if (party) { + togglePartyLock(party); + } else if (state.lockedParty) { + // A click on empty chart space releases the focused party. + togglePartyLock(state.lockedParty); + } + }; + + // A touch outside the chart releases a pinned crosshair. + const onDocumentPointerDown = (event) => { + if (!state.pinned || event.pointerType !== 'touch') return; + if (event.target instanceof Node && root.contains(event.target)) return; + state.pinned = false; + setColumn(-1); + }; + + const onKeyDown = (event) => { + const count = state.layout?.columns.length || 0; + if (!count) return; + if (event.key === 'ArrowRight' || event.key === 'ArrowLeft') { + event.preventDefault(); + const delta = event.key === 'ArrowRight' ? 1 : -1; + const next = state.column < 0 ? (delta > 0 ? 0 : count - 1) : Math.min(count - 1, Math.max(0, state.column + delta)); + state.pinned = true; + setColumn(next); + } else if (event.key === 'Escape') { + state.pinned = false; + state.lockedParty = null; + applyFocus(); + setColumn(-1); + } + }; + + const onLegendClick = (event) => { + const button = event.target instanceof Element ? event.target.closest('button[data-party]') : null; + if (button) togglePartyLock(button.getAttribute('data-party')); + }; + const onLegendPointerOver = (event) => { + if (event.pointerType === 'touch') return; + const button = event.target instanceof Element ? event.target.closest('button[data-party]') : null; + state.hoverParty = button ? button.getAttribute('data-party') : null; + applyFocus(); + }; + const onLegendPointerOut = () => { + state.hoverParty = null; + applyFocus(); + }; + + const render = () => { + if (state.destroyed) return; + const width = Math.round(stage.clientWidth || container.clientWidth || 640); + const height = typeof options.height === 'function' ? options.height(width) : options.height; + if (width === state.width && height === state.height && state.svg) return; + state.width = width; + state.height = height; + state.layout = layoutTrendChart(model, { width, height, measureText }); + stage.innerHTML = renderTrendChartSvg(model, state.layout, { ariaLabel: options.ariaLabel }); + state.svg = stage.querySelector('svg'); + state.svg.addEventListener('pointermove', onPointerMove); + state.svg.addEventListener('pointerleave', onPointerLeave); + state.svg.addEventListener('pointerdown', onPointerDown); + state.svg.addEventListener('click', onClick); + state.svg.addEventListener('keydown', onKeyDown); + applyFocus(); + const column = state.column; + state.column = -1; + if (column >= 0 && state.pinned) setColumn(column); + else tooltip.hidden = true; + }; + + legend.addEventListener('click', onLegendClick); + legend.addEventListener('pointerover', onLegendPointerOver); + legend.addEventListener('pointerout', onLegendPointerOut); + doc.addEventListener('pointerdown', onDocumentPointerDown, true); + + let observer = null; + let frame = 0; + if (typeof ResizeObserver === 'function') { + observer = new ResizeObserver(() => { + if (frame) return; + frame = requestAnimationFrame(() => { + frame = 0; + render(); + }); + }); + observer.observe(stage); + if (options.fitTo instanceof Element) observer.observe(options.fitTo); + } + render(); + + const controller = { + render, + focus(party) { + state.lockedParty = party && seriesByKey.has(party) ? party : null; + applyFocus(); + }, + destroy() { + if (state.destroyed) return; + state.destroyed = true; + observer?.disconnect(); + if (frame) cancelAnimationFrame(frame); + legend.removeEventListener('click', onLegendClick); + legend.removeEventListener('pointerover', onLegendPointerOver); + legend.removeEventListener('pointerout', onLegendPointerOut); + doc.removeEventListener('pointerdown', onDocumentPointerDown, true); + if (container.__trendChart === controller) delete container.__trendChart; + } + }; + container.__trendChart = controller; + return controller; +} + +function legendMarkup(model) { + return model.series.map((item) => ( + `' + )).join(''); +} + +function createTextMeasurer(root) { + try { + const canvas = root.ownerDocument.createElement('canvas'); + const context = canvas.getContext('2d'); + if (!context) return estimateTextWidth; + const family = getComputedStyle(root).fontFamily || 'sans-serif'; + return (text, bold = false, size = LABEL_FONT_SIZE) => { + context.font = `${bold ? '600' : '400'} ${size}px ${family}`; + return context.measureText(String(text)).width; + }; + } catch { + return estimateTextWidth; + } +} + +/* ------------------------------------------------------------------------------------------ */ +/* Helpers */ +/* ------------------------------------------------------------------------------------------ */ + +export function formatShare(value) { + const number = Number(value); + return Number.isFinite(number) ? `${number.toFixed(1)}%` : ''; +} + +function estimateTextWidth(text, bold = false, size = LABEL_FONT_SIZE) { + return String(text).length * size * (bold ? 0.6 : 0.55); +} + +function parseDateUtc(value) { + const match = String(value || '').match(/^(\d{4})-(\d{2})-(\d{2})/); + if (!match) return NaN; + return Date.UTC(Number(match[1]), Number(match[2]) - 1, Number(match[3])); +} + +function finiteOrZero(value) { + const number = Number(value); + return Number.isFinite(number) ? number : 0; +} + +function normalizeName(value) { + return String(value ?? '') + .normalize('NFKD') + .replace(/[̀-ͯ]/g, '') + .replace(/\([^)]*\)/g, ' ') + .replace(/&/g, ' and ') + .replace(/['’`]/g, '') + .replace(/[-_/.,()]/g, ' ') + .replace(/\s+/g, ' ') + .trim() + .toLowerCase(); +} + +function escapeHtml(value) { + return String(value ?? '').replace(/[&<>"']/g, (char) => ({ + '&': '&', + '<': '<', + '>': '>', + '"': '"', + "'": ''' + }[char])); +} diff --git a/src/ui-controller.js b/src/ui-controller.js index 6624e5704d..481add83ec 100644 --- a/src/ui-controller.js +++ b/src/ui-controller.js @@ -11,6 +11,42 @@ import { formatElectionDate, shortBodyName, renderElectionConstituencyFeatureLin import { cdnUrl } from './cdn-url.js'; import { partyLabelHtml } from './party-names.mjs'; +/** + * Lucide icons used by the catalogue: the section bar, the headings inside the contents box, + * and the Books categories, which previously relied on emoji from data/database/books.json. + * Inline paths keep this a zero-dependency module; each string is the icon's Lucide markup. + */ +const LUCIDE_ICON_PATHS = { + vote: '', + map: '', + 'book-open': '', + table: '', + 'clipboard-list': '', + landmark: '', + 'chart-column': '', + scale: '', + library: '' +}; + +/** Book category id -> Lucide icon name. Anything unlisted gets an open book. */ +const BOOK_CATEGORY_ICONS = { + 'boundary-reports': 'clipboard-list', + 'parliamentary-debates': 'landmark', + 'election-results': 'vote', + 'census-reports': 'chart-column', + legislation: 'scale', + other: 'library' +}; + +function lucideIcon(name, className = 'catalogue-flat__section-icon') { + const paths = LUCIDE_ICON_PATHS[name] || LUCIDE_ICON_PATHS['book-open']; + return ``; +} + +function bookCategoryIcon(category) { + return lucideIcon(BOOK_CATEGORY_ICONS[category?.id] || 'book-open'); +} + class UIController { constructor() { this.splitStates = [ @@ -1552,20 +1588,18 @@ class UIController { ` : ''; const markdownViewButton = book.markdownFile - ? `` + ? `` : ''; return ` ${this.renderBookThumbnail(book, category, fallbackLabel)}

      ${this.escapeHtml(book.title)}

      -

      ${this.escapeHtml((book.authors || []).join(', '))}

      -

      ${this.escapeHtml(book.dateDisplay || book.date || '')}

      +

      ${this.escapeHtml((book.authors || []).join(', '))}${this.escapeHtml(book.dateDisplay || book.date || '')}

      ${pdfViewButton} ${markdownViewButton} ${book.archiveUrl ? `Archive.org` : ''}
      - ${book.transcriptionNotice ? `

      ${this.escapeHtml(book.transcriptionNotice)}

      ` : ''}
      `; } @@ -2147,7 +2181,7 @@ class UIController { ${imageHtml} - ${this.escapeHtml(category?.icon || '[book]')} + ${bookCategoryIcon(category)} ${this.escapeHtml(fallbackLabel)} @@ -2932,8 +2966,7 @@ class UIController { if (!targetEl || !pane) return false; const paneRect = pane.getBoundingClientRect(); const targetRect = targetEl.getBoundingClientRect(); - const stickyShell = pane.querySelector('.catalogue-sticky-shell'); - const stickyHeight = stickyShell?.getBoundingClientRect?.().height || 0; + const stickyHeight = this._catalogueStickyHeight(pane); const offset = Math.max(12, stickyHeight + 10); const nextTop = pane.scrollTop + targetRect.top - paneRect.top - offset; const reduceMotion = typeof window !== 'undefined' @@ -2954,8 +2987,7 @@ class UIController { if (!targetEl || !pane) return false; const paneRect = pane.getBoundingClientRect(); const targetRect = targetEl.getBoundingClientRect(); - const stickyShell = pane.querySelector('.catalogue-sticky-shell'); - const stickyHeight = stickyShell?.getBoundingClientRect?.().height || 0; + const stickyHeight = this._catalogueStickyHeight(pane); return targetRect.top >= paneRect.top + stickyHeight && targetRect.top <= paneRect.bottom - 12; } @@ -2971,7 +3003,39 @@ class UIController { * `aria-current` rather than `aria-selected`: three of the four are links to * anchors, not tabs in a tablist, and aria-selected on a link is invalid. */ + /** + * The section bar is position: sticky under the title-and-search shell, which is sticky + * too and whose height depends on how the title wraps. The shell's measured height is + * published as a custom property on the scroller so the bar's `top` can follow it. + */ + /** Height of everything pinned to the top of the catalogue scroller: the shell plus the section bar. */ + _catalogueStickyHeight(pane) { + const shell = pane?.querySelector?.('.catalogue-sticky-shell'); + const sections = pane?.querySelector?.('.catalogue-flat__sections'); + const shellHeight = shell?.getBoundingClientRect?.().height || 0; + const sectionsHeight = sections && getComputedStyle(sections).position === 'sticky' + ? (sections.getBoundingClientRect().height || 0) + 8 + : 0; + return shellHeight + sectionsHeight; + } + + _syncCatalogueShellHeight() { + const pane = this.getCataloguePaneScroller?.(); + const shell = pane?.querySelector?.('.catalogue-sticky-shell'); + if (!pane || !shell) return; + const apply = () => { + const height = Math.round(shell.getBoundingClientRect().height); + if (height > 0) pane.style.setProperty('--catalogue-sticky-shell-height', `${height}px`); + }; + apply(); + if (!this._catalogueShellResizeObserver && typeof ResizeObserver === 'function') { + this._catalogueShellResizeObserver = new ResizeObserver(apply); + this._catalogueShellResizeObserver.observe(shell); + } + } + _markActiveToplink(activeEl) { + this._activeSectionTab = activeEl?.dataset?.catalogueTarget || activeEl?.dataset?.tabTarget || this._activeSectionTab; const links = document.querySelectorAll('.catalogue-flat__toc-toplink'); links.forEach((el) => { if (el === activeEl) el.setAttribute('aria-current', 'true'); @@ -3425,7 +3489,7 @@ class UIController { // Create books group header const booksGroupHeader = document.createElement('div'); booksGroupHeader.className = 'category-group-header'; - booksGroupHeader.innerHTML = `

      Books & Documents

      `; + booksGroupHeader.innerHTML = `

      ${lucideIcon('book-open')}Books & Documents

      `; container.appendChild(booksGroupHeader); // Group books by category @@ -3452,7 +3516,7 @@ class UIController { catSection.className = 'category-section'; catSection.innerHTML = `
      - ${cat.icon || '[book]'} + ${bookCategoryIcon(cat)}

      ${this.escapeHtml(cat.name)}

      `; @@ -4599,15 +4663,28 @@ class UIController { addFlatTocTarget('flat-section-maps', 'maps-index'); addFlatTocTarget('flat-section-books', 'books'); + // Section switcher: a segmented bar above the contents box rather than a row of text + // links inside it. The links keep their classes and data attributes, so click handling + // and aria-current marking are unchanged; only the wrapper and the icons are new. + const SECTION_ICONS = { + elections: lucideIcon('vote'), + maps: lucideIcon('map'), + books: lucideIcon('book-open'), + tables: lucideIcon('table') + }; + // The flat view is re-rendered whenever a section is expanded, so the active tab is + // remembered on the controller rather than read back from the old markup. + const activeSectionTab = this._activeSectionTab || 'flat-section-elections'; + const current = (key) => (activeSectionTab === key ? ' aria-current="true"' : ''); let tocHtml = ` +
      -