@thibezer/ui-components-kit 2.8.1 → 2.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +65 -0
- package/README.md +3 -3
- package/dist/canvas.cjs +70 -70
- package/dist/canvas.js +3125 -2473
- package/dist/components/ui-barra-ferramentas/ferramentas-comum.d.ts +24 -1
- package/dist/components/ui-barra-ferramentas/paleta-atalhos.d.ts +10 -3
- package/dist/components/ui-barra-ferramentas/ribbon-render.d.ts +10 -2
- package/dist/components/ui-barra-ferramentas/ribbon-teclado.d.ts +10 -3
- package/dist/components/ui-barra-ferramentas/tipos.d.ts +31 -0
- package/dist/components/ui-barra-ferramentas/ui-paleta-ferramentas.d.ts +12 -0
- package/dist/components/ui-barra-ferramentas/ui-ribbon.d.ts +16 -0
- package/dist/components/ui-canvas-cad/ui-canvas-cad.d.ts +15 -0
- package/dist/core.cjs +1 -1
- package/dist/core.js +1 -1
- package/dist/custom-elements.json +8934 -8415
- package/dist/data.cjs +1 -1
- package/dist/data.js +1 -1
- package/dist/gerencigeo-canvas/curva_leaflet.d.ts +2 -2
- package/dist/gerencigeo-canvas/feature_curvas.d.ts +3 -1
- package/dist/gerencigeo-canvas/feature_lod.d.ts +38 -0
- package/dist/gerencigeo-canvas/feature_metricas.d.ts +9 -0
- package/dist/gerencigeo-canvas/feature_simplificacao.d.ts +16 -8
- package/dist/gerencigeo-canvas/index.d.ts +7 -0
- package/dist/gerencigeo-canvas/layer_hit_test.d.ts +22 -0
- package/dist/gerencigeo-canvas/layer_manager.d.ts +5 -0
- package/dist/gerencigeo-canvas/motor/dados-camada.d.ts +39 -0
- package/dist/gerencigeo-canvas/motor/estilo.d.ts +28 -0
- package/dist/gerencigeo-canvas/motor/geometria-px.d.ts +27 -0
- package/dist/gerencigeo-canvas/motor/index.d.ts +5 -0
- package/dist/gerencigeo-canvas/motor/motor-formas.d.ts +107 -0
- package/dist/gerencigeo-canvas/motor/tipos.d.ts +100 -0
- package/dist/gerencigeo-canvas/renderers/canvas_formas_leaflet.d.ts +87 -0
- package/dist/gerencigeo-canvas/renderers/feicoes_canvas_renderer.d.ts +58 -0
- package/dist/gerencigeo-canvas/renderers/feicoes_despachante.d.ts +31 -0
- package/dist/gerencigeo-canvas/renderers/feicoes_renderer.d.ts +48 -9
- package/dist/gerencigeo-canvas/renderers/marcadores_feicoes.d.ts +11 -0
- package/dist/gerencigeo-canvas/renderers/marcas_lod_layer.d.ts +19 -0
- package/dist/gerencigeo-canvas/renderers/renderizador_feicoes_tipos.d.ts +44 -0
- package/dist/gerencigeo-canvas/renderers/renderizador_formas.d.ts +95 -0
- package/dist/gerencigeo-canvas/renderers/selecao_visual.d.ts +6 -0
- package/dist/gerencigeo-canvas/types.d.ts +2 -0
- package/dist/index.cjs +1 -1
- package/dist/index.js +3 -3
- package/dist/motor-BB6tB6U-.cjs +1 -0
- package/dist/motor-CFI84lM2.js +1301 -0
- package/dist/motor.cjs +1 -0
- package/dist/motor.d.ts +7 -0
- package/dist/motor.js +52 -0
- package/dist/register.cjs +1 -1
- package/dist/register.js +3 -3
- package/dist/svg-seguro-ChVJ2L2z.js +74 -0
- package/dist/svg-seguro-J2RM1Ssf.cjs +1 -0
- package/dist/tabela.cjs +1 -1
- package/dist/tabela.js +1 -1
- package/dist/tipos-elementos.d.ts +13 -0
- package/dist/tipos-vue.d.ts +8 -0
- package/dist/tools.cjs +1 -1
- package/dist/tools.js +1 -1
- package/dist/{ui-linha-C6HBnsaw.cjs → ui-linha-BYAX4W6x.cjs} +5 -5
- package/dist/{ui-linha-nCDh2wPm.js → ui-linha-aqLlaYi7.js} +57 -51
- package/dist/ui-paleta-ferramentas-BXXrI1Y7.js +1233 -0
- package/dist/ui-paleta-ferramentas-CsPMTY0G.cjs +21 -0
- package/dist/{ui-tabela-propriedades-DzZlyNZ_.cjs → ui-tabela-propriedades-CjK2gG14.cjs} +1 -1
- package/dist/{ui-tabela-propriedades-D9Echt2X.js → ui-tabela-propriedades-DoL4SE0r.js} +1 -1
- package/package.json +6 -1
- package/dist/svg-seguro-BsbNQqpd.js +0 -50
- package/dist/svg-seguro-C76iLlAZ.cjs +0 -1
- package/dist/ui-paleta-ferramentas-Ksh6gMW3.js +0 -890
- package/dist/ui-paleta-ferramentas-bDLPbiGA.cjs +0 -21
package/dist/canvas.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var _i=Object.defineProperty;var Ti=(a,e,t)=>e in a?_i(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t;var f=(a,e,t)=>Ti(a,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});;/* empty css */const b=require("leaflet"),M=require("./leaflet-DcO7uRC-.cjs"),m=require("./motor-BB6tB6U-.cjs"),ct=require("./listener-bag-D5omxZ9h.cjs"),lo=require("./ssr-safe-CiHD1adl.cjs"),lt={perimetroWeight:1,fechamentoWeight:1,vizinhoWeight:1,bancoWeight:1,markerSizeBase:10,markerStyleM:"circle-dot",markerSizeM:14,markerStyleP:"circle",markerSizeP:10,markerStyleV:"cross",markerSizeV:8,enableAnimations:!1,preferCanvas:!0,crosshair:!1,satOpacity:1,magnetSnap:!1},ne=class ne{constructor(){f(this,"config");this.config=this.loadConfig()}static getInstance(){return ne.instance||(ne.instance=new ne),ne.instance}loadConfig(){try{const e=typeof localStorage<"u"?localStorage.getItem("gerencigeo_mapa_config"):null;if(e)return{...lt,...JSON.parse(e)}}catch(e){console.error("Erro ao carregar configurações do mapa",e)}return{...lt}}saveConfig(e){this.config={...this.config,...e},typeof localStorage<"u"&&localStorage.setItem("gerencigeo_mapa_config",JSON.stringify(this.config))}getConfig(){return this.config=this.loadConfig(),{...this.config}}};f(ne,"instance");let Re=ne;const Pt="sob-demanda",Fi=700;function Be(a){const e=typeof a=="string"?a.trim().toLowerCase():"";return e==="automatico"||e==="desligado"||e==="sob-demanda"?e:Pt}const ke=new WeakMap;function qi(a){const e=a&&typeof a=="object"?a.options:void 0;return!!e&&e.closeButton!==void 0&&e.autoPan!==void 0}function Ct(a,e){const t=a?ke.get(a):void 0;return t?t.liberar(e):e()}class Oi{constructor(e,t=Pt){f(this,"liberados",0);f(this,"emClique",!1);f(this,"pendentes",new Map);f(this,"instalado",!0);f(this,"original");f(this,"container",null);f(this,"marcarClique",()=>{this.emClique=!0,queueMicrotask(()=>{this.emClique=!1})});var i;this.map=e,this.modoAtual=t,this.original=e.addLayer;const o=this;e.addLayer=function(n){return qi(n)?o.aoAbrir(this,n):o.original.call(this,n)},this.container=typeof e.getContainer=="function"?e.getContainer():null,(i=this.container)==null||i.addEventListener("click",this.marcarClique,!0),ke.set(e,this)}get modo(){return this.modoAtual}definirModo(e){this.modoAtual=Be(e),this.modoAtual!=="sob-demanda"&&this.cancelarPendentes()}liberar(e){this.liberados++;try{return e()}finally{this.liberados--}}destruir(){var e;this.instalado&&(this.instalado=!1,this.cancelarPendentes(),(e=this.container)==null||e.removeEventListener("click",this.marcarClique,!0),delete this.map.addLayer,ke.get(this.map)===this&&ke.delete(this.map))}aoAbrir(e,t){return this.modoAtual==="automatico"?this.original.call(e,t):this.emClique&&this.liberados===0?(this.modoAtual==="sob-demanda"&&this.aguardarDuploClique(t),e):(t.options&&(t.options.autoPan=!1),this.original.call(e,t))}aguardarDuploClique(e){const t=e&&typeof e=="object"?e._source:null;if(!t||typeof t.on!="function"||typeof t.off!="function"||this.pendentes.has(t))return;let o;const i=()=>{t.off("dblclick",n),o!==void 0&&clearTimeout(o),this.pendentes.delete(t)},n=r=>{i(),this.liberar(()=>{var s;return(s=t.openPopup)==null?void 0:s.call(t,typeof t.getLatLng=="function"||r==null?void 0:r.latlng)})};o=setTimeout(i,Fi),t.on("dblclick",n),this.pendentes.set(t,i)}cancelarPendentes(){for(const e of[...this.pendentes.values()])e();this.pendentes.clear()}}async function $i(a,e,t,o){const i=a.getSize(),n=a.getBounds(),r=n.getSouthWest(),s=n.getNorthEast(),c=`${r.lng},${r.lat},${s.lng},${s.lat}`;let l=0,d=0;try{if(e.containerPoint)l=Math.round(e.containerPoint.x),d=Math.round(e.containerPoint.y);else if(e.layerPoint){const y=a.layerPointToContainerPoint(e.layerPoint);l=Math.round(y.x),d=Math.round(y.y)}}catch{l=0,d=0}const h=`https://acervofundiario.incra.gov.br/i3geo/ogc.php?SERVICE=WMS&VERSION=1.1.1&REQUEST=GetFeatureInfo&FORMAT=image/png&TRANSPARENT=true&QUERY_LAYERS=certificada_sigef_particular_pr&LAYERS=certificada_sigef_particular_pr&INFO_FORMAT=application/json&X=${l}&Y=${d}&WIDTH=${i.x}&HEIGHT=${i.y}&SRS=EPSG:4326&BBOX=${c}`,u=a.getContainer();u.style.cursor="wait";const g=b.popup({className:"compact-sigef-popup",maxWidth:250}).setLatLng(e.latlng).setContent(`
|
|
2
2
|
<div style="font-family:var(--ui-fonte-base, sans-serif); display:flex; align-items:center; gap:8px; color:rgba(255,255,255,0.9); font-size:12px;">
|
|
3
3
|
<svg style="animation:spin 1s linear infinite; width:14px; height:14px; flex-shrink:0;" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
|
|
4
4
|
<circle cx="12" cy="12" r="10" stroke="rgba(255,255,255,0.2)" stroke-width="4" fill="none"></circle>
|
|
@@ -6,19 +6,19 @@
|
|
|
6
6
|
</svg>
|
|
7
7
|
Consultando...
|
|
8
8
|
</div>
|
|
9
|
-
`);
|
|
9
|
+
`);Ct(a,()=>g.openOn(a)),o.currentAbortController&&o.currentAbortController.abort(),o.currentAbortController=new AbortController;const v=o.currentAbortController.signal,p=setTimeout(()=>{o.currentAbortController&&o.currentAbortController.abort()},8e3);try{const A=typeof window<"u"&&(window.location.origin.includes("localhost")||window.location.origin.includes("127.0.0.1")||window.location.origin.includes("[::1]"))?`${t}/proxy/sigef?url=${encodeURIComponent(h)}`:`${window.location.origin}/api.php?action=proxy_sigef&url=${encodeURIComponent(h)}`,w=await fetch(A,{signal:v});clearTimeout(p);let x=null;if(w.ok){const k=await w.text();try{x=JSON.parse(k)}catch{x=null}}if(x&&x.features&&x.features.length>0){const k=x.features[0],C=k.properties||{},L=String(k.id||C.parcela_codigo||C.co_parcela||C.id_parcela||""),P=String(C.nome_area||C.nome_imovel||"Imóvel Sem Nome");if(L){const z=encodeURIComponent(L),I=`https://sigef.incra.gov.br/geo/exportar/parcela/shp/${z}/`,S=`https://sigef.incra.gov.br/geo/parcela/detalhe/${z}/`,E=document.createElement("div");E.style.cssText="font-family:var(--ui-fonte-base, sans-serif); color:rgba(255, 255, 255, 0.9); line-height:1.4; min-width:180px;",E.innerHTML=`
|
|
10
10
|
<div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:6px; padding-bottom:5px; border-bottom:1px solid rgba(255, 255, 255, 0.1);">
|
|
11
11
|
<span style="font-weight:700; font-size:11px; color:#10b981; text-transform:uppercase; letter-spacing:0.5px;">SIGEF</span>
|
|
12
|
-
<span style="font-size:10px; color:rgba(255, 255, 255, 0.5);">${
|
|
12
|
+
<span style="font-size:10px; color:rgba(255, 255, 255, 0.5);">${M.escapeHtml(C.situacao_informada||C.status||"Certificada")}</span>
|
|
13
13
|
</div>
|
|
14
|
-
<div style="font-weight:700; font-size:12px; margin-bottom:4px; color:#ffffff; word-break:break-word;">${
|
|
15
|
-
<div style="font-size:11px; color:rgba(255, 255, 255, 0.7); margin-bottom:2px;">Cód: <span style="font-family:var(--ui-fonte-codigo, monospace);">${
|
|
14
|
+
<div style="font-weight:700; font-size:12px; margin-bottom:4px; color:#ffffff; word-break:break-word;">${M.escapeHtml(P)}</div>
|
|
15
|
+
<div style="font-size:11px; color:rgba(255, 255, 255, 0.7); margin-bottom:2px;">Cód: <span style="font-family:var(--ui-fonte-codigo, monospace);">${M.escapeHtml(C.codigo_imovel||"N/A")}</span></div>
|
|
16
16
|
<div style="display:flex; gap:12px; font-size:11px; color:rgba(255, 255, 255, 0.7); margin-bottom:6px;">
|
|
17
|
-
<span>Mat: <strong style="color:#ffffff;">${
|
|
18
|
-
<span>${
|
|
17
|
+
<span>Mat: <strong style="color:#ffffff;">${M.escapeHtml(C.registro_matricula||C.matricula||"N/A")}</strong></span>
|
|
18
|
+
<span>${M.escapeHtml(C.data_submissao||"")}</span>
|
|
19
19
|
</div>
|
|
20
20
|
<div style="display:flex; flex-direction:column; gap:5px; padding-top:6px; border-top:1px solid rgba(255, 255, 255, 0.1);">
|
|
21
|
-
<a href="${
|
|
21
|
+
<a href="${I}" target="_blank" rel="noopener noreferrer" style="display:flex; align-items:center; justify-content:center; gap:5px; padding:5px 8px; background:rgba(16, 185, 129, 0.15); border:1px solid rgba(16, 185, 129, 0.3); color:#34d399; font-size:11px; font-weight:700; border-radius:5px; text-decoration:none; cursor:pointer;">
|
|
22
22
|
<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
|
|
23
23
|
Baixar Shapefile
|
|
24
24
|
</a>
|
|
@@ -26,12 +26,12 @@
|
|
|
26
26
|
<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
|
|
27
27
|
Importar Confrontante (CSV)
|
|
28
28
|
</button>
|
|
29
|
-
<a href="${
|
|
29
|
+
<a href="${S}" target="_blank" rel="noopener noreferrer" style="display:flex; align-items:center; justify-content:center; gap:4px; padding:4px 6px; background:rgba(255, 255, 255, 0.05); border:1px solid rgba(255, 255, 255, 0.1); color:rgba(255, 255, 255, 0.7); font-size:10px; font-weight:600; border-radius:5px; text-decoration:none; cursor:pointer;">
|
|
30
30
|
<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></svg>
|
|
31
31
|
Abrir no SIGEF
|
|
32
32
|
</a>
|
|
33
33
|
</div>
|
|
34
|
-
`;const
|
|
34
|
+
`;const D=E.querySelector(".btn-importar-confrontante-sigef");D&&D.addEventListener("click",()=>{window.dispatchEvent(new CustomEvent("gerencigeo:importar_vizinho_sigef",{detail:{uuid:L,nome:P}}))}),g.setContent(E)}else g.setContent(`
|
|
35
35
|
<div style="font-family:var(--ui-fonte-base, sans-serif); font-size:12px; color:#b45309; padding:2px 0;">
|
|
36
36
|
Lote identificado, mas código da parcela indisponível.
|
|
37
37
|
</div>
|
|
@@ -39,71 +39,71 @@
|
|
|
39
39
|
<div style="font-family:var(--ui-fonte-base, sans-serif); font-size:12px; color:rgba(255, 255, 255, 0.7); padding:2px 0;">
|
|
40
40
|
Nenhum imóvel SIGEF certificado neste ponto.
|
|
41
41
|
</div>
|
|
42
|
-
`)}catch(
|
|
42
|
+
`)}catch(y){y.name==="AbortError"?g.setContent(`
|
|
43
43
|
<div style="font-family:var(--ui-fonte-base, sans-serif); font-size:12px; color:#f59e0b; padding:2px 0;">
|
|
44
44
|
Consulta cancelada ou tempo limite de resposta esgotado.
|
|
45
45
|
</div>
|
|
46
|
-
`):(console.warn("Erro ao consultar SIGEF:",
|
|
46
|
+
`):(console.warn("Erro ao consultar SIGEF:",y),g.setContent(`
|
|
47
47
|
<div style="font-family:var(--ui-fonte-base, sans-serif); font-size:12px; color:#f59e0b; padding:2px 0;">
|
|
48
48
|
Serviço de consulta SIGEF indisponível nesta área.
|
|
49
49
|
</div>
|
|
50
|
-
`))}finally{u.style.cursor=""}}function fa(a,t){if(!a)return;const e=Math.floor(a.getZoom()),o=Math.max(e,12),i=Math.min(e+1,19),n=t.pad(.2),r=["mt0","mt1","mt2","mt3"];let s=0;const c=32;for(let l=o;l<=i&&s<c;l++){const d=n.getNorthWest(),h=n.getSouthEast(),u=Je(d.lng,l),g=Je(h.lng,l),m=Qe(d.lat,l),f=Qe(h.lat,l);for(let b=u;b<=g&&s<c;b++)for(let A=m;A<=f&&s<c;A++){const C=`https://${r[(b+A)%r.length]}.google.com/vt/lyrs=s,h&x=${b}&y=${A}&z=${l}`,k=new Image;k.src=C,s++}}}function Je(a,t){return Math.floor((a+180)/360*Math.pow(2,t))}function Qe(a,t){const e=a*Math.PI/180;return Math.floor((1-Math.log(Math.tan(e)+1/Math.cos(e))/Math.PI)/2*Math.pow(2,t))}const ma={zoomSnap:.25,zoomDelta:.5,wheelPxPerZoomLevel:90};class To{constructor(t){p(this,"map",null);p(this,"configManager",Ut.getInstance());p(this,"config",this.configManager.getConfig());p(this,"apiBaseUrl","/api");p(this,"bancoPontosGroup",v.layerGroup());p(this,"pontosVizinhosGroup",v.layerGroup());p(this,"controller");p(this,"containerElement",null);p(this,"bc");p(this,"sigefState",{});p(this,"popups",null);p(this,"modoPopups",_e);this.controller=t}definirModoPopups(t){var e;this.modoPopups=Wt(t),(e=this.popups)==null||e.definirModo(this.modoPopups)}init(t){var o;if(this.map){(o=this.popups)==null||o.destruir(),this.popups=null;try{this.map.off(),this.map.remove()}catch{}finally{this.map=null}}const e=typeof t=="string"?document.getElementById(t):t;if(!e)return null;if(this.containerElement=e,e._leaflet_id)try{delete e._leaflet_id}catch{e._leaflet_id=void 0}if(this.map=v.map(e,{maxZoom:24,scrollWheelZoom:!0,preferCanvas:this.config.preferCanvas!==void 0?this.config.preferCanvas:!0,zoomControl:!1,...ma}).setView([-23.7661,-53.3204],14),this.popups=new ua(this.map,this.modoPopups),this.listenConfigBroadcast(),this.applyMapStyles(),!this.map.getPane("sigefPane")){const i=this.map.createPane("sigefPane");i.style.zIndex="390"}if(!this.map.getPane("perimetroPane")){const i=this.map.createPane("perimetroPane");i.style.zIndex="520"}if(!this.map.getPane("verticesPane")){const i=this.map.createPane("verticesPane");i.style.zIndex="650"}return v.control.scale({metric:!0,imperial:!1,position:"bottomleft"}).addTo(this.map),this.map.on("click",i=>{if(this.controller.modoCliqueSequencialAtivo||this.controller.canvasInteracao&&this.controller.canvasInteracao.selectionHappened)return;(this.controller.layerManager?this.controller.layerManager.isLayerActiveAndSelectable("sigef"):!1)&&this.consultarSigef(i)}),setTimeout(()=>{this.invalidateSize()},250),this.map}invalidateSize(t=!1){var e,o;if(this.map)try{const i=(o=(e=this.map).getContainer)==null?void 0:o.call(e);if(!i||!i.parentNode)return;this.map.invalidateSize({animate:t,pan:!1})}catch{}}applyMapStyles(){const t=this.containerElement||document.getElementById("mapa-triagem");t&&(t.style.cursor=this.config.crosshair?"crosshair":"")}listenConfigBroadcast(){if(!(typeof BroadcastChannel>"u"))try{this.bc=new BroadcastChannel("gerencigeo_map_config"),this.bc.onmessage=t=>{t.data==="RELOAD_REQUIRED"&&(this.config=this.configManager.getConfig(),this.applyMapStyles(),window.dispatchEvent(new CustomEvent("gerencigeo:map_config_changed",{detail:this.config})))}}catch{}}destroy(){var t;if(this.sigefState.currentAbortController&&(this.sigefState.currentAbortController.abort(),this.sigefState.currentAbortController=void 0),this.bc){try{this.bc.close()}catch{}this.bc=void 0}if(this.map){(t=this.popups)==null||t.destruir(),this.popups=null;try{this.map.off(),this.map.remove()}catch{}finally{this.map=null}}if(this.containerElement&&this.containerElement._leaflet_id)try{delete this.containerElement._leaflet_id}catch{this.containerElement._leaflet_id=void 0}}preCarregarTilesRegiao(t){fa(this.map,t)}async consultarSigef(t){this.map&&await pa(this.map,t,this.apiBaseUrl,this.sigefState)}}function to(a){if(!a)return!1;const t=a;return t.tagName==="INPUT"||t.tagName==="TEXTAREA"||t.tagName==="SELECT"||t.isContentEditable===!0}function De(a){var o,i;const t=(o=a==null?void 0:a.composedPath)==null?void 0:o.call(a)[0];if(t instanceof Element)return to(t);let e=typeof document>"u"?null:document.activeElement;for(;(i=e==null?void 0:e.shadowRoot)!=null&&i.activeElement;)e=e.shadowRoot.activeElement;return to(e)}const Do=["verticesPane","perimetroPane","overlayPane","markerPane","pane-vertices","pane-perimetro","pane-vizinhos","pane-homologados","pane-homologados-pontos"];class ga{constructor(t,e,o){p(this,"map");p(this,"mapContainer");p(this,"ctx");p(this,"selectionDiv",null);p(this,"isSelecting",!1);p(this,"selectStartPos",{x:0,y:0});p(this,"selectStartPoint",null);this.map=t,this.mapContainer=e,this.ctx=o,this.criarDivSelecao()}criarDivSelecao(){this.selectionDiv||(this.selectionDiv=document.createElement("div"),this.selectionDiv.className="cad-selection-box",this.selectionDiv.style.position="absolute",this.selectionDiv.style.zIndex="9999",this.selectionDiv.style.pointerEvents="none",this.selectionDiv.style.display="none",this.selectionDiv.style.borderRadius="2px",this.mapContainer.style.position="relative",this.mapContainer.appendChild(this.selectionDiv))}setPanesPointerEvents(t){Do.forEach(e=>{const o=this.map.getPane(e);o&&(o.style.pointerEvents=t)})}iniciarSelecao(t){const e=this.mapContainer.getBoundingClientRect(),o=t.clientX-e.left,i=t.clientY-e.top;this.isSelecting=!0,this.selectStartPos={x:o,y:i},this.selectStartPoint=this.map.mouseEventToContainerPoint(t),this.selectionDiv&&(this.selectionDiv.style.left=`${o}px`,this.selectionDiv.style.top=`${i}px`,this.selectionDiv.style.width="0px",this.selectionDiv.style.height="0px",this.selectionDiv.style.display="block"),this.setPanesPointerEvents("none")}atualizarSelecao(t){if(!this.isSelecting||!this.selectionDiv)return;const e=this.mapContainer.getBoundingClientRect(),o=t.clientX-e.left,i=t.clientY-e.top,n=Math.abs(o-this.selectStartPos.x),r=Math.abs(i-this.selectStartPos.y),s=Math.min(o,this.selectStartPos.x),c=Math.min(i,this.selectStartPos.y);this.selectionDiv.style.left=`${Math.round(s)}px`,this.selectionDiv.style.top=`${Math.round(c)}px`,this.selectionDiv.style.width=`${Math.round(n)}px`,this.selectionDiv.style.height=`${Math.round(r)}px`,o>=this.selectStartPos.x?(this.selectionDiv.style.background="rgba(14, 116, 144, 0.22)",this.selectionDiv.style.border="1px solid #06b6d4"):(this.selectionDiv.style.background="rgba(16, 185, 129, 0.22)",this.selectionDiv.style.border="1px dashed #10b981")}finalizarSelecao(t,e,o){var M,C,k,P,y,x,E,z,L;if(!this.isSelecting)return!1;this.isSelecting=!1,this.selectionDiv&&(this.selectionDiv.style.display="none"),this.map.closePopup();try{this.setPanesPointerEvents("auto"),(M=this.ctx.layerManager)==null||M.ensurePanes()}catch{}const i=this.mapContainer.getBoundingClientRect(),n=t.clientX-i.left,r=t.clientY-i.top,s=this.map.mouseEventToContainerPoint(t),c=Math.abs(n-this.selectStartPos.x),l=Math.abs(r-this.selectStartPos.y);if(c<4&&l<4){const w=t.target;if(w&&((C=w.classList)!=null&&C.contains("leaflet-container")||w.id==="mapa-triagem"||(k=w.closest)!=null&&k.call(w,".leaflet-pane"))){const I=((P=w.closest)==null?void 0:P.call(w,".custom-leaflet-marker"))||((y=w.closest)==null?void 0:y.call(w,".custom-div-icon")),_=t.ctrlKey||t.metaKey||t.shiftKey;!I&&!_&&o()}return!1}if(!this.selectStartPoint)return!1;const d={x1:Math.min(this.selectStartPoint.x,s.x),y1:Math.min(this.selectStartPoint.y,s.y),x2:Math.max(this.selectStartPoint.x,s.x),y2:Math.max(this.selectStartPoint.y,s.y)},h=s.x>=this.selectStartPoint.x?"window":"crossing";(E=(x=this.ctx).selecionarFeicoesNaCaixa)==null||E.call(x,d,h,t.ctrlKey||t.metaKey);const u=((z=this.ctx.mapaController)==null?void 0:z.getMarkers())||[],g=((L=this.ctx.mapaController)==null?void 0:L.getVizinhosMarkers())||[],m=[],f=[],b=!this.ctx.layerManager||this.ctx.layerManager.isLayerActiveAndSelectable("vertices"),A=!this.ctx.layerManager||this.ctx.layerManager.isLayerActiveAndSelectable("vizinhos");return b&&u.forEach(w=>{const I=w.pontoId;if(!I)return;const _=this.map.latLngToContainerPoint(w.getLatLng());_.x>=d.x1&&_.x<=d.x2&&_.y>=d.y1&&_.y<=d.y2&&m.push(I)}),A&&g.forEach(w=>{const I=w.pontoId;if(!I)return;const _=this.map.latLngToContainerPoint(w.getLatLng());_.x>=d.x1&&_.x<=d.x2&&_.y>=d.y1&&_.y<=d.y2&&f.push(I)}),t.ctrlKey||t.metaKey?(m.forEach(w=>{this.ctx.selectedPontoIds.includes(w)?this.ctx.selectedPontoIds=this.ctx.selectedPontoIds.filter(I=>I!==w):this.ctx.selectedPontoIds.push(w)}),f.forEach(w=>{this.ctx.selectedVizinhoPontoIds.includes(w)?this.ctx.selectedVizinhoPontoIds=this.ctx.selectedVizinhoPontoIds.filter(I=>I!==w):this.ctx.selectedVizinhoPontoIds.push(w)})):(this.ctx.selectedPontoIds=m,this.ctx.selectedVizinhoPontoIds=f),this.ctx.selectedPontoIds.length>0&&(this.ctx.lastSelectedPontoId=this.ctx.selectedPontoIds[this.ctx.selectedPontoIds.length-1]),e(),!0}cancelarSelecao(){this.isSelecting&&(this.isSelecting=!1,this.selectionDiv&&(this.selectionDiv.style.display="none"),this.setPanesPointerEvents("auto"),this.ctx.layerManager&&this.ctx.layerManager.ensurePanes())}destruir(){this.selectionDiv&&this.selectionDiv.parentNode&&(this.selectionDiv.parentNode.removeChild(this.selectionDiv),this.selectionDiv=null),this.setPanesPointerEvents("auto")}}function Pe(a){return`pane-${a}`}const $o=["poligono","linha","ponto","texto"];function qo(a,t){return`${Pe(a)}-${t}`}function nt(a,t,e){const o=a.getPane(Pe(t))??a.createPane(Pe(t)),i=qo(t,e);if(!a.getPane(i)){const n=a.createPane(i,o);n.style.zIndex=String(($o.indexOf(e)+1)*100)}return i}const eo="ui-canvas-hit-test-estilo",Ot=6,Fo=4,va=4,Dt={poligono:1,linha:2,ponto:3,texto:3};function No(a){var i;const t=a.getRootNode(),e=t instanceof ShadowRoot?t:document.head;if((i=e.querySelector)!=null&&i.call(e,`#${eo}`))return;const o=document.createElement("style");o.id=eo,o.textContent=".leaflet-pane > canvas { pointer-events: none !important; }",e.appendChild(o)}function re(a,t){var e,o;return t+(((e=a.options)==null?void 0:e.stroke)===!1?0:(((o=a.options)==null?void 0:o.weight)??0)/2)}function ya(a,t,e){let o=1/0;for(const i of a){for(let n=1;n<i.length;n++)o=Math.min(o,v.LineUtil.pointToSegmentDistance(t,i[n-1],i[n]));e&&i.length>2&&(o=Math.min(o,v.LineUtil.pointToSegmentDistance(t,i[i.length-1],i[0])))}return o}function ba(a){const t=a._pxBounds;return t?(t.max.x-t.min.x)*(t.max.y-t.min.y):0}function xa(a,t,e){var o,i,n;if(!((o=a.options)!=null&&o.interactive))return null;if(a._point&&a._radius!==void 0){const r=a._radius,s=a._radiusY??a._radius,c=a._point.distanceTo(t),l=(r+s)/2,d=e==="ponto"?Fo:re(a,Ot);return a.options.fill!==!1&&e==="poligono"?c<=l+1?0:null:e==="ponto"?c<=l+d?c:null:Math.abs(c-l)<=d?Math.abs(c-l):null}if(a._parts){const r=a instanceof v.Polygon,s=ya(a._parts,t,r);return e==="linha"?s<=re(a,Ot)?s:null:r&&((i=a._containsPoint)!=null&&i.call(a,t))?0:s<=re(a,Ot)?s:null}return(n=a._containsPoint)!=null&&n.call(a,t)?0:null}function Pa(a){const t=[];for(let e=a._drawFirst;e;e=e.next)t.push(e.layer);return t}function $e(a,t,e){const o=a._paneRenderers;if(!o)return[];const i=t.filter(r=>r.visivel&&r.interativo&&!r.bloqueada).sort((r,s)=>s.zIndex-r.zIndex),n=[];for(const r of i)for(const s of $o){const c=o[qo(r.id,s)];if(c)for(const l of Pa(c).reverse()){const d=xa(l,e,s);d!==null&&n.push({camada:r,tipo:s,alvo:l,distancia:d,area:ba(l)})}}return n.sort((r,s)=>Dt[r.tipo]!==Dt[s.tipo]?Dt[s.tipo]-Dt[r.tipo]:r.camada.zIndex!==s.camada.zIndex?s.camada.zIndex-r.camada.zIndex:r.tipo==="poligono"&&r.area!==s.area?r.area-s.area:0)}const Ce=new WeakMap;function Ca(a,t,e){const o=e.map(r=>v.Util.stamp(r.alvo)),i=Ce.get(a);let n=0;return i&&Math.hypot(i.x-t.x,i.y-t.y)<=va&&i.ids.length===o.length&&i.ids.every((r,s)=>r===o[s])&&(n=(i.indice+1)%e.length),Ce.set(a,{x:t.x,y:t.y,ids:o,indice:n}),e[n]}function Oo(a,t,e){const o=a.mouseEventToLayerPoint(e),i=$e(a,t,o);return i.length===0?(Ce.delete(a),!1):(Ca(a,o,i).alvo.fire(e.type,{originalEvent:e,latlng:a.mouseEventToLatLng(e),layerPoint:o,containerPoint:a.mouseEventToContainerPoint(e)},!0),!0)}function La(a,t,e){return $e(a,t,a.mouseEventToLayerPoint(e))[0]??null}class Ro{constructor(t){p(this,"ctx");p(this,"map",null);p(this,"mapContainer",null);p(this,"selecaoBox",null);p(this,"isPanning",!1);p(this,"lastMousePos",{x:0,y:0});p(this,"lastMiddleClickTime",0);p(this,"touchStartPos",{x:0,y:0});p(this,"isTouchPanning",!1);p(this,"removerSupressao",null);p(this,"selectionHappened",!1);p(this,"panHappened",!1);p(this,"handleTouchStart",t=>{!this.map||!this.mapContainer||(t.touches.length===1?(this.isTouchPanning=!0,this.touchStartPos={x:t.touches[0].clientX,y:t.touches[0].clientY}):t.touches.length===2&&(this.isTouchPanning=!1))});p(this,"handleTouchMove",t=>{if(!(!this.map||!this.mapContainer))if(t.touches.length===1&&this.isTouchPanning){t.preventDefault(),this.panHappened=!0;const e=this.touchStartPos.x-t.touches[0].clientX,o=this.touchStartPos.y-t.touches[0].clientY;this.map.panBy([e,o],{animate:!1}),this.touchStartPos={x:t.touches[0].clientX,y:t.touches[0].clientY}}else t.touches.length===2&&(this.panHappened=!0)});p(this,"handleTouchEnd",()=>{this.isTouchPanning=!1,setTimeout(()=>{this.panHappened=!1},120)});p(this,"handleContextMenu",t=>{var e,o;t.preventDefault(),(o=(e=this.ctx).aoMenuContexto)==null||o.call(e,t)});p(this,"handleClick",t=>{var e,o,i,n;!this.map||!this.ctx.layerManager||(o=(e=this.ctx).ferramentaAtiva)!=null&&o.call(e)||(n=(i=t.target)==null?void 0:i.closest)!=null&&n.call(i,".leaflet-marker-icon")||Oo(this.map,this.ctx.layerManager.getLayers(),t)});p(this,"handleMouseDown",t=>{var e,o,i,n,r;if(!(!this.map||!this.mapContainer)){if(this.cancelarSupressaoClique(),t.button===1){if(t.preventDefault(),Date.now()-this.lastMiddleClickTime<300){this.lastMiddleClickTime=0,this.zoomExtents();return}this.isPanning=!0,this.panHappened=!1,this.lastMousePos={x:t.clientX,y:t.clientY},this.mapContainer.style.cursor="grabbing";return}if(t.button===0){if((o=(e=t.target)==null?void 0:e.closest)!=null&&o.call(e,".cad-vertex-handle, .cad-vertex-ghost, #cm-vertex-edit-hud, #cm-draw-hud")||(n=(i=this.ctx).ferramentaAtiva)!=null&&n.call(i)||(this.selectionHappened=!1,this.ctx.mapaController&&this.ctx.mapaController.modoCliqueSequencialAtivo))return;(r=this.selecaoBox)==null||r.iniciarSelecao(t)}}});p(this,"handleMouseMove",t=>{var e;if(!(!this.map||!this.mapContainer)){if(this.isPanning){const o=this.lastMousePos.x-t.clientX,i=this.lastMousePos.y-t.clientY;(Math.abs(o)>1||Math.abs(i)>1)&&(this.panHappened=!0),this.map.panBy([o,i],{animate:!1}),this.lastMousePos={x:t.clientX,y:t.clientY};return}(e=this.selecaoBox)==null||e.atualizarSelecao(t)}});p(this,"handleMouseUp",t=>{this.isPanning&&(this.isPanning=!1,t.button===1&&!this.panHappened&&(this.lastMiddleClickTime=Date.now()),this.mapContainer&&(this.mapContainer.style.cursor="grab"),setTimeout(()=>{this.panHappened=!1},120)),this.selecaoBox&&this.selecaoBox.isSelecting&&this.selecaoBox.finalizarSelecao(t,()=>this.notificarSelecao(),()=>this.limparSelecao())&&(this.selectionHappened=!0,this.suprimirProximoClique())});p(this,"handleKeyDown",t=>{var e;if(t.key==="Escape"){if(De(t))return;(e=this.selecaoBox)==null||e.cancelarSelecao(),this.limparSelecao()}});this.ctx={selectedPontoIds:[],selectedVizinhoPontoIds:[],lastSelectedPontoId:null,pontosList:[],...t}}ativar(t,e){this.ctx.mapaController=t,e&&(this.ctx.containerHost=e),this.map=t.getMap(),this.map&&(this.mapContainer=this.map.getContainer(),this.mapContainer&&(this.map.dragging.disable(),this.map.doubleClickZoom.disable(),this.selecaoBox=new ga(this.map,this.mapContainer,this.ctx),No(this.mapContainer),this.mapContainer.addEventListener("click",this.handleClick),this.mapContainer.addEventListener("mousedown",this.handleMouseDown),this.mapContainer.addEventListener("mousemove",this.handleMouseMove),window.addEventListener("mouseup",this.handleMouseUp),this.mapContainer.addEventListener("contextmenu",this.handleContextMenu),window.addEventListener("keydown",this.handleKeyDown),this.mapContainer.addEventListener("touchstart",this.handleTouchStart,{passive:!1}),this.mapContainer.addEventListener("touchmove",this.handleTouchMove,{passive:!1}),this.mapContainer.addEventListener("touchend",this.handleTouchEnd),this.mapContainer.addEventListener("touchcancel",this.handleTouchEnd)))}desativar(){this.mapContainer&&(this.mapContainer.removeEventListener("click",this.handleClick),this.mapContainer.removeEventListener("mousedown",this.handleMouseDown),this.mapContainer.removeEventListener("mousemove",this.handleMouseMove),this.mapContainer.removeEventListener("contextmenu",this.handleContextMenu),this.mapContainer.removeEventListener("touchstart",this.handleTouchStart),this.mapContainer.removeEventListener("touchmove",this.handleTouchMove),this.mapContainer.removeEventListener("touchend",this.handleTouchEnd),this.mapContainer.removeEventListener("touchcancel",this.handleTouchEnd)),window.removeEventListener("mouseup",this.handleMouseUp),window.removeEventListener("keydown",this.handleKeyDown),this.cancelarSupressaoClique(),this.selecaoBox&&(this.selecaoBox.destruir(),this.selecaoBox=null),this.map&&(this.map.dragging.enable(),this.map.doubleClickZoom.enable())}suprimirProximoClique(){this.cancelarSupressaoClique(),this.removerSupressao=()=>window.removeEventListener("click",t,!0);const t=e=>{e.stopImmediatePropagation(),e.preventDefault(),this.cancelarSupressaoClique()};window.addEventListener("click",t,!0)}cancelarSupressaoClique(){var t;(t=this.removerSupressao)==null||t.call(this),this.removerSupressao=null}limparSelecao(){var t,e,o,i;(e=(t=this.ctx).aoLimparSelecao)==null||e.call(t),this.ctx.mapaController&&this.ctx.mapaController.context.selectedSegmentoId&&this.ctx.mapaController.selectSegmento(null),(this.ctx.selectedPontoIds.length>0||this.ctx.selectedVizinhoPontoIds.length>0)&&(this.ctx.selectedPontoIds=[],this.ctx.selectedVizinhoPontoIds=[],this.ctx.lastSelectedPontoId=null,this.ctx.mapaController&&(this.ctx.mapaController.context.selectedPontoIds=[],(i=(o=this.ctx.mapaController).atualizarDestaqueMarcadores)==null||i.call(o)),this.notificarSelecao())}notificarSelecao(){var t,e;this.ctx.mapaController&&(this.ctx.mapaController.context.selectedPontoIds=[...this.ctx.selectedPontoIds],(e=(t=this.ctx.mapaController).atualizarDestaqueMarcadores)==null||e.call(t)),this.ctx.atualizarDestaqueLinhasTabela&&this.ctx.atualizarDestaqueLinhasTabela(),this.ctx.onSelectionChange&&this.ctx.onSelectionChange(this.ctx.selectedPontoIds,this.ctx.selectedVizinhoPontoIds),window.dispatchEvent(new CustomEvent("gerencigeo:ponto-selecionado",{detail:{selectedPontoIds:this.ctx.selectedPontoIds,selectedVizinhoPontoIds:this.ctx.selectedVizinhoPontoIds,lastSelectedPontoId:this.ctx.lastSelectedPontoId}}))}zoomExtents(){if(!this.ctx.pontosList||this.ctx.pontosList.length===0)return;const t=this.ctx.pontosList.filter(e=>e.tipo_ponto!=="B"&&e.tipo!=="B");t.length>0&&this.ctx.mapaController&&this.ctx.mapaController.fitBounds(t)}destroy(){this.desativar()}}class O{static register(t,e){this.renderers.set(t.toLowerCase(),e)}static get(t){return this.renderers.get(t.toLowerCase())}static has(t){return this.renderers.has(t.toLowerCase())}static getRegisteredTypes(){return Array.from(this.renderers.keys())}}p(O,"renderers",new Map);class Bo{render(t,e,o){var c,l,d;const i=((c=t.dados)==null?void 0:c.url)||"https://{s}.google.com/vt/lyrs=s,h&x={x}&y={y}&z={z}",n=((l=t.dados)==null?void 0:l.subdomains)||["mt0","mt1","mt2","mt3"],r=((d=t.dados)==null?void 0:d.attribution)||"Google Satélite";return v.tileLayer(i,{maxZoom:24,maxNativeZoom:20,subdomains:n,attribution:r,keepBuffer:16,updateWhenZooming:!1,updateWhenIdle:!0,className:"smooth-zoom-layer",opacity:t.opacidade!==void 0?t.opacidade:1,pane:`pane-${t.id}`})}update(t,e,o){e instanceof v.TileLayer&&o.opacidade!==void 0&&e.setOpacity(o.opacidade)}destroy(t,e){e.hasLayer(t)&&e.removeLayer(t)}}class Ho{render(t,e,o){var l,d,h,u;const i=((l=t.dados)==null?void 0:l.url)||"https://acervofundiario.incra.gov.br/i3geo/ogc.php",n=((d=t.dados)==null?void 0:d.layers)||"certificada_sigef_particular_pr",r=((h=t.dados)==null?void 0:h.format)||"image/png",s=((u=t.dados)==null?void 0:u.attribution)||"INCRA/SIGEF";return v.tileLayer.wms(i,{layers:n,format:r,transparent:!0,version:"1.1.1",pane:`pane-${t.id}`,attribution:s,className:"sigef-wms-layer",keepBuffer:8,updateWhenZooming:!1,updateWhenIdle:!0,opacity:t.opacidade!==void 0?t.opacidade:.85})}update(t,e,o){e instanceof v.TileLayer.WMS&&o.opacidade!==void 0&&e.setOpacity(o.opacidade)}destroy(t,e){e.hasLayer(t)&&e.removeLayer(t)}}function Vo(a,t,e){const o=a.estilo.espessuraLinha||e.config.perimetroWeight||2,i=e.graphicScale.lineScaleMultiplier||1;if(a.estilo.scaleMode==="world"){const n=a.estilo.dimensaoMetros||.3,r=t.getCenter(),s=t.getZoom(),c=40075016686e-3*Math.abs(Math.cos(r.lat*Math.PI/180))/Math.pow(2,s+8),l=n/(c>0?c:1);return Math.max(1,Math.round(l*i))}return Math.max(1,Math.round(o*i))}function ut(a,t,e,o,i){const n=Math.max(Math.round(e+3),4);v.polyline(t,{color:"#080d0a",weight:n,opacity:.85,lineCap:"round",lineJoin:"round",dashArray:i,pane:o,interactive:!1}).addTo(a)}function oo(a,t,e,o,i){var m,f,b,A,M,C,k,P;const n=a.id==="homologados",r=((m=a.dados)==null?void 0:m.conexoes)??(Array.isArray(a.dados)&&a.dados.length>0&&"origemId"in a.dados[0]?a.dados:null),s=((f=a.dados)==null?void 0:f.segmentos)||o.segmentos||[],c=((b=a.dados)==null?void 0:b.pontos)||(n?o.bancoPontos||[]:o.pontos)||[],l=Vo(a,e,o),d=a.opacidade!==void 0?a.opacidade:1,h=a.interativo&&!a.bloqueada,u=[];c.forEach(y=>{const x=S.parseCoordenada(y.lat??y.latitude??y.y,y.lon??y.lng??y.longitude??y.x);x&&u.push({...y,lat:x.lat,lon:x.lon})});const g=y=>{const x=u.find(E=>String(E.id)===String(y));if(x)return x;if(o.pontos){const E=o.pontos.find(z=>String(z.id)===String(y));if(E){const z=S.parseCoordenada(E.lat,E.lon);if(z)return{...E,lat:z.lat,lon:z.lon}}}return null};if(r&&Array.isArray(r)){r.forEach(y=>{var z,L,w,I,_,N,T;const x=g(y.origemId),E=g(y.destinoId);if(x&&E&&x.lat&&x.lon&&E.lat&&E.lon){const W=y.tipoLinha==="tracejada"||((z=y.estilo)==null?void 0:z.tipoLinha)==="tracejada",D=((L=y.estilo)==null?void 0:L.cor)||((w=y.estilo)==null?void 0:w.color)||a.estilo.corPrimaria||"#00f5a0",F=((I=y.estilo)==null?void 0:I.espessura)||((_=y.estilo)==null?void 0:_.weight)||l,$=[[x.lat,x.lon],[E.lat,E.lon]],R=W?"6, 6":a.estilo.dashArray;ut(t,$,F,i,R);const q=v.polyline($,{color:D,weight:F,opacity:((N=y.estilo)==null?void 0:N.opacidade)??d,dashArray:R,pane:i,interactive:h});if(h){const B=y.acoes||a.acoes||((T=a.dados)==null?void 0:T.acoes)||[],V=`${y.origemId}-${y.destinoId}`,J=S.renderPopupAcoesHtml(B,V);q.bindPopup(`
|
|
50
|
+
`))}finally{u.style.cursor=""}}function Ni(a,e){if(!a)return;const t=Math.floor(a.getZoom()),o=Math.max(t,12),i=Math.min(t+1,19),n=e.pad(.2),r=["mt0","mt1","mt2","mt3"];let s=0;const c=32;for(let l=o;l<=i&&s<c;l++){const d=n.getNorthWest(),h=n.getSouthEast(),u=$t(d.lng,l),g=$t(h.lng,l),v=Nt(d.lat,l),p=Nt(h.lat,l);for(let y=u;y<=g&&s<c;y++)for(let A=v;A<=p&&s<c;A++){const x=`https://${r[(y+A)%r.length]}.google.com/vt/lyrs=s,h&x=${y}&y=${A}&z=${l}`,k=new Image;k.src=x,s++}}}function $t(a,e){return Math.floor((a+180)/360*Math.pow(2,e))}function Nt(a,e){const t=a*Math.PI/180;return Math.floor((1-Math.log(Math.tan(t)+1/Math.cos(t))/Math.PI)/2*Math.pow(2,e))}const Ri={zoomSnap:.25,zoomDelta:.5,wheelPxPerZoomLevel:90};class ho{constructor(e){f(this,"map",null);f(this,"configManager",Re.getInstance());f(this,"config",this.configManager.getConfig());f(this,"apiBaseUrl","/api");f(this,"bancoPontosGroup",b.layerGroup());f(this,"pontosVizinhosGroup",b.layerGroup());f(this,"controller");f(this,"containerElement",null);f(this,"bc");f(this,"sigefState",{});f(this,"popups",null);f(this,"modoPopups",Pt);this.controller=e}definirModoPopups(e){var t;this.modoPopups=Be(e),(t=this.popups)==null||t.definirModo(this.modoPopups)}init(e){var o;if(this.map){(o=this.popups)==null||o.destruir(),this.popups=null;try{this.map.off(),this.map.remove()}catch{}finally{this.map=null}}const t=typeof e=="string"?document.getElementById(e):e;if(!t)return null;if(this.containerElement=t,t._leaflet_id)try{delete t._leaflet_id}catch{t._leaflet_id=void 0}if(this.map=b.map(t,{maxZoom:24,scrollWheelZoom:!0,preferCanvas:this.config.preferCanvas!==void 0?this.config.preferCanvas:!0,zoomControl:!1,...Ri}).setView([-23.7661,-53.3204],14),this.popups=new Oi(this.map,this.modoPopups),this.listenConfigBroadcast(),this.applyMapStyles(),!this.map.getPane("sigefPane")){const i=this.map.createPane("sigefPane");i.style.zIndex="390"}if(!this.map.getPane("perimetroPane")){const i=this.map.createPane("perimetroPane");i.style.zIndex="520"}if(!this.map.getPane("verticesPane")){const i=this.map.createPane("verticesPane");i.style.zIndex="650"}return b.control.scale({metric:!0,imperial:!1,position:"bottomleft"}).addTo(this.map),this.map.on("click",i=>{if(this.controller.modoCliqueSequencialAtivo||this.controller.canvasInteracao&&this.controller.canvasInteracao.selectionHappened)return;(this.controller.layerManager?this.controller.layerManager.isLayerActiveAndSelectable("sigef"):!1)&&this.consultarSigef(i)}),setTimeout(()=>{this.invalidateSize()},250),this.map}invalidateSize(e=!1){var t,o;if(this.map)try{const i=(o=(t=this.map).getContainer)==null?void 0:o.call(t);if(!i||!i.parentNode)return;this.map.invalidateSize({animate:e,pan:!1})}catch{}}applyMapStyles(){const e=this.containerElement||document.getElementById("mapa-triagem");e&&(e.style.cursor=this.config.crosshair?"crosshair":"")}listenConfigBroadcast(){if(!(typeof BroadcastChannel>"u"))try{this.bc=new BroadcastChannel("gerencigeo_map_config"),this.bc.onmessage=e=>{e.data==="RELOAD_REQUIRED"&&(this.config=this.configManager.getConfig(),this.applyMapStyles(),window.dispatchEvent(new CustomEvent("gerencigeo:map_config_changed",{detail:this.config})))}}catch{}}destroy(){var e;if(this.sigefState.currentAbortController&&(this.sigefState.currentAbortController.abort(),this.sigefState.currentAbortController=void 0),this.bc){try{this.bc.close()}catch{}this.bc=void 0}if(this.map){(e=this.popups)==null||e.destruir(),this.popups=null;try{this.map.off(),this.map.remove()}catch{}finally{this.map=null}}if(this.containerElement&&this.containerElement._leaflet_id)try{delete this.containerElement._leaflet_id}catch{this.containerElement._leaflet_id=void 0}}preCarregarTilesRegiao(e){Ni(this.map,e)}async consultarSigef(e){this.map&&await $i(this.map,e,this.apiBaseUrl,this.sigefState)}}function Rt(a){if(!a)return!1;const e=a;return e.tagName==="INPUT"||e.tagName==="TEXTAREA"||e.tagName==="SELECT"||e.isContentEditable===!0}function Lt(a){var o,i;const e=(o=a==null?void 0:a.composedPath)==null?void 0:o.call(a)[0];if(e instanceof Element)return Rt(e);let t=typeof document>"u"?null:document.activeElement;for(;(i=t==null?void 0:t.shadowRoot)!=null&&i.activeElement;)t=t.shadowRoot.activeElement;return Rt(t)}const uo=["verticesPane","perimetroPane","overlayPane","markerPane","pane-vertices","pane-perimetro","pane-vizinhos","pane-homologados","pane-homologados-pontos"];class Bi{constructor(e,t,o){f(this,"map");f(this,"mapContainer");f(this,"ctx");f(this,"selectionDiv",null);f(this,"isSelecting",!1);f(this,"selectStartPos",{x:0,y:0});f(this,"selectStartPoint",null);this.map=e,this.mapContainer=t,this.ctx=o,this.criarDivSelecao()}criarDivSelecao(){this.selectionDiv||(this.selectionDiv=document.createElement("div"),this.selectionDiv.className="cad-selection-box",this.selectionDiv.style.position="absolute",this.selectionDiv.style.zIndex="9999",this.selectionDiv.style.pointerEvents="none",this.selectionDiv.style.display="none",this.selectionDiv.style.borderRadius="2px",this.mapContainer.style.position="relative",this.mapContainer.appendChild(this.selectionDiv))}setPanesPointerEvents(e){uo.forEach(t=>{const o=this.map.getPane(t);o&&(o.style.pointerEvents=e)})}iniciarSelecao(e){const t=this.mapContainer.getBoundingClientRect(),o=e.clientX-t.left,i=e.clientY-t.top;this.isSelecting=!0,this.selectStartPos={x:o,y:i},this.selectStartPoint=this.map.mouseEventToContainerPoint(e),this.selectionDiv&&(this.selectionDiv.style.left=`${o}px`,this.selectionDiv.style.top=`${i}px`,this.selectionDiv.style.width="0px",this.selectionDiv.style.height="0px",this.selectionDiv.style.display="block"),this.setPanesPointerEvents("none")}atualizarSelecao(e){if(!this.isSelecting||!this.selectionDiv)return;const t=this.mapContainer.getBoundingClientRect(),o=e.clientX-t.left,i=e.clientY-t.top,n=Math.abs(o-this.selectStartPos.x),r=Math.abs(i-this.selectStartPos.y),s=Math.min(o,this.selectStartPos.x),c=Math.min(i,this.selectStartPos.y);this.selectionDiv.style.left=`${Math.round(s)}px`,this.selectionDiv.style.top=`${Math.round(c)}px`,this.selectionDiv.style.width=`${Math.round(n)}px`,this.selectionDiv.style.height=`${Math.round(r)}px`,o>=this.selectStartPos.x?(this.selectionDiv.style.background="rgba(14, 116, 144, 0.22)",this.selectionDiv.style.border="1px solid #06b6d4"):(this.selectionDiv.style.background="rgba(16, 185, 129, 0.22)",this.selectionDiv.style.border="1px dashed #10b981")}finalizarSelecao(e,t,o){var w,x,k,C,L,P,z,I,S;if(!this.isSelecting)return!1;this.isSelecting=!1,this.selectionDiv&&(this.selectionDiv.style.display="none"),this.map.closePopup();try{this.setPanesPointerEvents("auto"),(w=this.ctx.layerManager)==null||w.ensurePanes()}catch{}const i=this.mapContainer.getBoundingClientRect(),n=e.clientX-i.left,r=e.clientY-i.top,s=this.map.mouseEventToContainerPoint(e),c=Math.abs(n-this.selectStartPos.x),l=Math.abs(r-this.selectStartPos.y);if(c<4&&l<4){const E=e.target;if(E&&((x=E.classList)!=null&&x.contains("leaflet-container")||E.id==="mapa-triagem"||(k=E.closest)!=null&&k.call(E,".leaflet-pane"))){const D=((C=E.closest)==null?void 0:C.call(E,".custom-leaflet-marker"))||((L=E.closest)==null?void 0:L.call(E,".custom-div-icon")),_=e.ctrlKey||e.metaKey||e.shiftKey;!D&&!_&&o()}return!1}if(!this.selectStartPoint)return!1;const d={x1:Math.min(this.selectStartPoint.x,s.x),y1:Math.min(this.selectStartPoint.y,s.y),x2:Math.max(this.selectStartPoint.x,s.x),y2:Math.max(this.selectStartPoint.y,s.y)},h=s.x>=this.selectStartPoint.x?"window":"crossing";(z=(P=this.ctx).selecionarFeicoesNaCaixa)==null||z.call(P,d,h,e.ctrlKey||e.metaKey);const u=((I=this.ctx.mapaController)==null?void 0:I.getMarkers())||[],g=((S=this.ctx.mapaController)==null?void 0:S.getVizinhosMarkers())||[],v=[],p=[],y=!this.ctx.layerManager||this.ctx.layerManager.isLayerActiveAndSelectable("vertices"),A=!this.ctx.layerManager||this.ctx.layerManager.isLayerActiveAndSelectable("vizinhos");return y&&u.forEach(E=>{const D=E.pontoId;if(!D)return;const _=this.map.latLngToContainerPoint(E.getLatLng());_.x>=d.x1&&_.x<=d.x2&&_.y>=d.y1&&_.y<=d.y2&&v.push(D)}),A&&g.forEach(E=>{const D=E.pontoId;if(!D)return;const _=this.map.latLngToContainerPoint(E.getLatLng());_.x>=d.x1&&_.x<=d.x2&&_.y>=d.y1&&_.y<=d.y2&&p.push(D)}),e.ctrlKey||e.metaKey?(v.forEach(E=>{this.ctx.selectedPontoIds.includes(E)?this.ctx.selectedPontoIds=this.ctx.selectedPontoIds.filter(D=>D!==E):this.ctx.selectedPontoIds.push(E)}),p.forEach(E=>{this.ctx.selectedVizinhoPontoIds.includes(E)?this.ctx.selectedVizinhoPontoIds=this.ctx.selectedVizinhoPontoIds.filter(D=>D!==E):this.ctx.selectedVizinhoPontoIds.push(E)})):(this.ctx.selectedPontoIds=v,this.ctx.selectedVizinhoPontoIds=p),this.ctx.selectedPontoIds.length>0&&(this.ctx.lastSelectedPontoId=this.ctx.selectedPontoIds[this.ctx.selectedPontoIds.length-1]),t(),!0}cancelarSelecao(){this.isSelecting&&(this.isSelecting=!1,this.selectionDiv&&(this.selectionDiv.style.display="none"),this.setPanesPointerEvents("auto"),this.ctx.layerManager&&this.ctx.layerManager.ensurePanes())}destruir(){this.selectionDiv&&this.selectionDiv.parentNode&&(this.selectionDiv.parentNode.removeChild(this.selectionDiv),this.selectionDiv=null),this.setPanesPointerEvents("auto")}}function ce(a){return`pane-${a}`}const po=["poligono","linha","ponto","texto"];function fo(a,e){return`${ce(a)}-${e}`}function U(a,e,t){const o=a.getPane(ce(e))??a.createPane(ce(e)),i=fo(e,t);if(!a.getPane(i)){const n=a.createPane(i,o);n.style.zIndex=String((po.indexOf(t)+1)*100)}return i}const Bt="ui-canvas-hit-test-estilo",Ie=6,mo=4,Vi=4,Se={poligono:1,linha:2,ponto:3,texto:3};function go(a){var i;const e=a.getRootNode(),t=e instanceof ShadowRoot?e:document.head;if((i=t.querySelector)!=null&&i.call(t,`#${Bt}`))return;const o=document.createElement("style");o.id=Bt,o.textContent=".leaflet-pane > canvas { pointer-events: none !important; }",t.appendChild(o)}const Ve=new WeakMap;function St(a,e,t){let o=Ve.get(a);o||(o=new Map,Ve.set(a,o)),o.set(e,t)}function Mt(a,e,t){const o=Ve.get(a);(o==null?void 0:o.get(e))===t&&o.delete(e)}function Ke(a,e){var t,o;return e+(((t=a.options)==null?void 0:t.stroke)===!1?0:(((o=a.options)==null?void 0:o.weight)??0)/2)}function Hi(a,e,t){let o=1/0;for(const i of a){for(let n=1;n<i.length;n++)o=Math.min(o,b.LineUtil.pointToSegmentDistance(e,i[n-1],i[n]));t&&i.length>2&&(o=Math.min(o,b.LineUtil.pointToSegmentDistance(e,i[i.length-1],i[0])))}return o}function Gi(a){const e=a._pxBounds;return e?(e.max.x-e.min.x)*(e.max.y-e.min.y):0}function ji(a,e,t){var o,i,n;if(!((o=a.options)!=null&&o.interactive))return null;if(a._point&&a._radius!==void 0){const r=a._radius,s=a._radiusY??a._radius,c=a._point.distanceTo(e),l=(r+s)/2,d=t==="ponto"?mo:Ke(a,Ie);return a.options.fill!==!1&&t==="poligono"?c<=l+1?0:null:t==="ponto"?c<=l+d?c:null:Math.abs(c-l)<=d?Math.abs(c-l):null}if(a._parts){const r=a instanceof b.Polygon,s=Hi(a._parts,e,r);return t==="linha"?s<=Ke(a,Ie)?s:null:r&&((i=a._containsPoint)!=null&&i.call(a,e))?0:s<=Ke(a,Ie)?s:null}return(n=a._containsPoint)!=null&&n.call(a,e)?0:null}function Ui(a){const e=[];for(let t=a._drawFirst;t;t=t.next)e.push(t.layer);return e}function At(a,e,t){var r;const o=a._paneRenderers;if(!o)return[];const i=e.filter(s=>s.visivel&&s.interativo&&!s.bloqueada).sort((s,c)=>c.zIndex-s.zIndex),n=[];for(const s of i){for(const l of po){const d=o[fo(s.id,l)];if(d)for(const h of Ui(d).reverse()){const u=ji(h,t,l);u!==null&&n.push({camada:s,tipo:l,alvo:h,distancia:u,area:Gi(h)})}}const c=(r=Ve.get(a))==null?void 0:r.get(s.id);if(c)try{for(const l of c.consultar(t))n.push({camada:s,tipo:l.tipo,alvo:c.alvo,distancia:l.distancia,area:l.area,feicao:l.feicao,chave:l.chave})}catch{}}return n.sort((s,c)=>Se[s.tipo]!==Se[c.tipo]?Se[c.tipo]-Se[s.tipo]:s.camada.zIndex!==c.camada.zIndex?c.camada.zIndex-s.camada.zIndex:s.tipo==="poligono"&&s.area!==c.area?s.area-c.area:0)}const dt=new WeakMap;function Wi(a,e,t){const o=t.map(r=>r.chave===void 0?String(b.Util.stamp(r.alvo)):`${b.Util.stamp(r.alvo)}:${r.chave}`),i=dt.get(a);let n=0;return i&&Math.hypot(i.x-e.x,i.y-e.y)<=Vi&&i.ids.length===o.length&&i.ids.every((r,s)=>r===o[s])&&(n=(i.indice+1)%t.length),dt.set(a,{x:e.x,y:e.y,ids:o,indice:n}),t[n]}function vo(a,e,t){const o=a.mouseEventToLayerPoint(t),i=At(a,e,o);if(i.length===0)return dt.delete(a),!1;const n=Wi(a,o,i);return n.alvo.fire(t.type,{originalEvent:t,latlng:a.mouseEventToLatLng(t),layerPoint:o,containerPoint:a.mouseEventToContainerPoint(t),...n.feicao!==void 0?{feicaoHit:n.feicao}:{}},!0),!0}function Zi(a,e,t){return At(a,e,a.mouseEventToLayerPoint(t))[0]??null}class yo{constructor(e){f(this,"ctx");f(this,"map",null);f(this,"mapContainer",null);f(this,"selecaoBox",null);f(this,"isPanning",!1);f(this,"lastMousePos",{x:0,y:0});f(this,"lastMiddleClickTime",0);f(this,"touchStartPos",{x:0,y:0});f(this,"isTouchPanning",!1);f(this,"removerSupressao",null);f(this,"selectionHappened",!1);f(this,"panHappened",!1);f(this,"handleTouchStart",e=>{!this.map||!this.mapContainer||(e.touches.length===1?(this.isTouchPanning=!0,this.touchStartPos={x:e.touches[0].clientX,y:e.touches[0].clientY}):e.touches.length===2&&(this.isTouchPanning=!1))});f(this,"handleTouchMove",e=>{if(!(!this.map||!this.mapContainer))if(e.touches.length===1&&this.isTouchPanning){e.preventDefault(),this.panHappened=!0;const t=this.touchStartPos.x-e.touches[0].clientX,o=this.touchStartPos.y-e.touches[0].clientY;this.map.panBy([t,o],{animate:!1}),this.touchStartPos={x:e.touches[0].clientX,y:e.touches[0].clientY}}else e.touches.length===2&&(this.panHappened=!0)});f(this,"handleTouchEnd",()=>{this.isTouchPanning=!1,setTimeout(()=>{this.panHappened=!1},120)});f(this,"handleContextMenu",e=>{var t,o;e.preventDefault(),(o=(t=this.ctx).aoMenuContexto)==null||o.call(t,e)});f(this,"handleClick",e=>{var t,o,i,n;!this.map||!this.ctx.layerManager||(o=(t=this.ctx).ferramentaAtiva)!=null&&o.call(t)||(n=(i=e.target)==null?void 0:i.closest)!=null&&n.call(i,".leaflet-marker-icon")||vo(this.map,this.ctx.layerManager.getLayers(),e)});f(this,"handleMouseDown",e=>{var t,o,i,n,r;if(!(!this.map||!this.mapContainer)){if(this.cancelarSupressaoClique(),e.button===1){if(e.preventDefault(),Date.now()-this.lastMiddleClickTime<300){this.lastMiddleClickTime=0,this.zoomExtents();return}this.isPanning=!0,this.panHappened=!1,this.lastMousePos={x:e.clientX,y:e.clientY},this.mapContainer.style.cursor="grabbing";return}if(e.button===0){if((o=(t=e.target)==null?void 0:t.closest)!=null&&o.call(t,".cad-vertex-handle, .cad-vertex-ghost, #cm-vertex-edit-hud, #cm-draw-hud")||(n=(i=this.ctx).ferramentaAtiva)!=null&&n.call(i)||(this.selectionHappened=!1,this.ctx.mapaController&&this.ctx.mapaController.modoCliqueSequencialAtivo))return;(r=this.selecaoBox)==null||r.iniciarSelecao(e)}}});f(this,"handleMouseMove",e=>{var t;if(!(!this.map||!this.mapContainer)){if(this.isPanning){const o=this.lastMousePos.x-e.clientX,i=this.lastMousePos.y-e.clientY;(Math.abs(o)>1||Math.abs(i)>1)&&(this.panHappened=!0),this.map.panBy([o,i],{animate:!1}),this.lastMousePos={x:e.clientX,y:e.clientY};return}(t=this.selecaoBox)==null||t.atualizarSelecao(e)}});f(this,"handleMouseUp",e=>{this.isPanning&&(this.isPanning=!1,e.button===1&&!this.panHappened&&(this.lastMiddleClickTime=Date.now()),this.mapContainer&&(this.mapContainer.style.cursor="grab"),setTimeout(()=>{this.panHappened=!1},120)),this.selecaoBox&&this.selecaoBox.isSelecting&&this.selecaoBox.finalizarSelecao(e,()=>this.notificarSelecao(),()=>this.limparSelecao())&&(this.selectionHappened=!0,this.suprimirProximoClique())});f(this,"handleKeyDown",e=>{var t;if(e.key==="Escape"){if(Lt(e))return;(t=this.selecaoBox)==null||t.cancelarSelecao(),this.limparSelecao()}});this.ctx={selectedPontoIds:[],selectedVizinhoPontoIds:[],lastSelectedPontoId:null,pontosList:[],...e}}ativar(e,t){this.ctx.mapaController=e,t&&(this.ctx.containerHost=t),this.map=e.getMap(),this.map&&(this.mapContainer=this.map.getContainer(),this.mapContainer&&(this.map.dragging.disable(),this.map.doubleClickZoom.disable(),this.selecaoBox=new Bi(this.map,this.mapContainer,this.ctx),go(this.mapContainer),this.mapContainer.addEventListener("click",this.handleClick),this.mapContainer.addEventListener("mousedown",this.handleMouseDown),this.mapContainer.addEventListener("mousemove",this.handleMouseMove),window.addEventListener("mouseup",this.handleMouseUp),this.mapContainer.addEventListener("contextmenu",this.handleContextMenu),window.addEventListener("keydown",this.handleKeyDown),this.mapContainer.addEventListener("touchstart",this.handleTouchStart,{passive:!1}),this.mapContainer.addEventListener("touchmove",this.handleTouchMove,{passive:!1}),this.mapContainer.addEventListener("touchend",this.handleTouchEnd),this.mapContainer.addEventListener("touchcancel",this.handleTouchEnd)))}desativar(){this.mapContainer&&(this.mapContainer.removeEventListener("click",this.handleClick),this.mapContainer.removeEventListener("mousedown",this.handleMouseDown),this.mapContainer.removeEventListener("mousemove",this.handleMouseMove),this.mapContainer.removeEventListener("contextmenu",this.handleContextMenu),this.mapContainer.removeEventListener("touchstart",this.handleTouchStart),this.mapContainer.removeEventListener("touchmove",this.handleTouchMove),this.mapContainer.removeEventListener("touchend",this.handleTouchEnd),this.mapContainer.removeEventListener("touchcancel",this.handleTouchEnd)),window.removeEventListener("mouseup",this.handleMouseUp),window.removeEventListener("keydown",this.handleKeyDown),this.cancelarSupressaoClique(),this.selecaoBox&&(this.selecaoBox.destruir(),this.selecaoBox=null),this.map&&(this.map.dragging.enable(),this.map.doubleClickZoom.enable())}suprimirProximoClique(){this.cancelarSupressaoClique(),this.removerSupressao=()=>window.removeEventListener("click",e,!0);const e=t=>{t.stopImmediatePropagation(),t.preventDefault(),this.cancelarSupressaoClique()};window.addEventListener("click",e,!0)}cancelarSupressaoClique(){var e;(e=this.removerSupressao)==null||e.call(this),this.removerSupressao=null}limparSelecao(){var e,t,o,i;(t=(e=this.ctx).aoLimparSelecao)==null||t.call(e),this.ctx.mapaController&&this.ctx.mapaController.context.selectedSegmentoId&&this.ctx.mapaController.selectSegmento(null),(this.ctx.selectedPontoIds.length>0||this.ctx.selectedVizinhoPontoIds.length>0)&&(this.ctx.selectedPontoIds=[],this.ctx.selectedVizinhoPontoIds=[],this.ctx.lastSelectedPontoId=null,this.ctx.mapaController&&(this.ctx.mapaController.context.selectedPontoIds=[],(i=(o=this.ctx.mapaController).atualizarDestaqueMarcadores)==null||i.call(o)),this.notificarSelecao())}notificarSelecao(){var e,t;this.ctx.mapaController&&(this.ctx.mapaController.context.selectedPontoIds=[...this.ctx.selectedPontoIds],(t=(e=this.ctx.mapaController).atualizarDestaqueMarcadores)==null||t.call(e)),this.ctx.atualizarDestaqueLinhasTabela&&this.ctx.atualizarDestaqueLinhasTabela(),this.ctx.onSelectionChange&&this.ctx.onSelectionChange(this.ctx.selectedPontoIds,this.ctx.selectedVizinhoPontoIds),window.dispatchEvent(new CustomEvent("gerencigeo:ponto-selecionado",{detail:{selectedPontoIds:this.ctx.selectedPontoIds,selectedVizinhoPontoIds:this.ctx.selectedVizinhoPontoIds,lastSelectedPontoId:this.ctx.lastSelectedPontoId}}))}zoomExtents(){if(!this.ctx.pontosList||this.ctx.pontosList.length===0)return;const e=this.ctx.pontosList.filter(t=>t.tipo_ponto!=="B"&&t.tipo!=="B");e.length>0&&this.ctx.mapaController&&this.ctx.mapaController.fitBounds(e)}destroy(){this.desativar()}}class N{static register(e,t){this.renderers.set(e.toLowerCase(),t)}static get(e){return this.renderers.get(e.toLowerCase())}static has(e){return this.renderers.has(e.toLowerCase())}static getRegisteredTypes(){return Array.from(this.renderers.keys())}}f(N,"renderers",new Map);class bo{render(e,t,o){var c,l,d;const i=((c=e.dados)==null?void 0:c.url)||"https://{s}.google.com/vt/lyrs=s,h&x={x}&y={y}&z={z}",n=((l=e.dados)==null?void 0:l.subdomains)||["mt0","mt1","mt2","mt3"],r=((d=e.dados)==null?void 0:d.attribution)||"Google Satélite";return b.tileLayer(i,{maxZoom:24,maxNativeZoom:20,subdomains:n,attribution:r,keepBuffer:16,updateWhenZooming:!1,updateWhenIdle:!0,className:"smooth-zoom-layer",opacity:e.opacidade!==void 0?e.opacidade:1,pane:`pane-${e.id}`})}update(e,t,o){t instanceof b.TileLayer&&o.opacidade!==void 0&&t.setOpacity(o.opacidade)}destroy(e,t){t.hasLayer(e)&&t.removeLayer(e)}}class xo{render(e,t,o){var l,d,h,u;const i=((l=e.dados)==null?void 0:l.url)||"https://acervofundiario.incra.gov.br/i3geo/ogc.php",n=((d=e.dados)==null?void 0:d.layers)||"certificada_sigef_particular_pr",r=((h=e.dados)==null?void 0:h.format)||"image/png",s=((u=e.dados)==null?void 0:u.attribution)||"INCRA/SIGEF";return b.tileLayer.wms(i,{layers:n,format:r,transparent:!0,version:"1.1.1",pane:`pane-${e.id}`,attribution:s,className:"sigef-wms-layer",keepBuffer:8,updateWhenZooming:!1,updateWhenIdle:!0,opacity:e.opacidade!==void 0?e.opacidade:.85})}update(e,t,o){t instanceof b.TileLayer.WMS&&o.opacidade!==void 0&&t.setOpacity(o.opacidade)}destroy(e,t){t.hasLayer(e)&&t.removeLayer(e)}}function Po(a,e,t){const o=a.estilo.espessuraLinha||t.config.perimetroWeight||2,i=t.graphicScale.lineScaleMultiplier||1;if(a.estilo.scaleMode==="world"){const n=a.estilo.dimensaoMetros||.3,r=e.getCenter(),s=e.getZoom(),c=40075016686e-3*Math.abs(Math.cos(r.lat*Math.PI/180))/Math.pow(2,s+8),l=n/(c>0?c:1);return Math.max(1,Math.round(l*i))}return Math.max(1,Math.round(o*i))}function re(a,e,t,o,i){const n=Math.max(Math.round(t+3),4);b.polyline(e,{color:"#080d0a",weight:n,opacity:.85,lineCap:"round",lineJoin:"round",dashArray:i,pane:o,interactive:!1}).addTo(a)}function Vt(a,e,t,o,i){var v,p,y,A,w,x,k,C;const n=a.id==="homologados",r=((v=a.dados)==null?void 0:v.conexoes)??(Array.isArray(a.dados)&&a.dados.length>0&&"origemId"in a.dados[0]?a.dados:null),s=((p=a.dados)==null?void 0:p.segmentos)||o.segmentos||[],c=((y=a.dados)==null?void 0:y.pontos)||(n?o.bancoPontos||[]:o.pontos)||[],l=Po(a,t,o),d=a.opacidade!==void 0?a.opacidade:1,h=a.interativo&&!a.bloqueada,u=[];c.forEach(L=>{const P=M.parseCoordenada(L.lat??L.latitude??L.y,L.lon??L.lng??L.longitude??L.x);P&&u.push({...L,lat:P.lat,lon:P.lon})});const g=L=>{const P=u.find(z=>String(z.id)===String(L));if(P)return P;if(o.pontos){const z=o.pontos.find(I=>String(I.id)===String(L));if(z){const I=M.parseCoordenada(z.lat,z.lon);if(I)return{...z,lat:I.lat,lon:I.lon}}}return null};if(r&&Array.isArray(r)){r.forEach(L=>{var I,S,E,D,_,R,O;const P=g(L.origemId),z=g(L.destinoId);if(P&&z&&P.lat&&P.lon&&z.lat&&z.lon){const B=L.tipoLinha==="tracejada"||((I=L.estilo)==null?void 0:I.tipoLinha)==="tracejada",T=((S=L.estilo)==null?void 0:S.cor)||((E=L.estilo)==null?void 0:E.color)||a.estilo.corPrimaria||"#00f5a0",$=((D=L.estilo)==null?void 0:D.espessura)||((_=L.estilo)==null?void 0:_.weight)||l,F=[[P.lat,P.lon],[z.lat,z.lon]],V=B?"6, 6":a.estilo.dashArray;re(e,F,$,i,V);const q=b.polyline(F,{color:T,weight:$,opacity:((R=L.estilo)==null?void 0:R.opacidade)??d,dashArray:V,pane:i,interactive:h});if(h){const H=L.acoes||a.acoes||((O=a.dados)==null?void 0:O.acoes)||[],j=`${L.origemId}-${L.destinoId}`,Y=M.renderPopupAcoesHtml(H,j);q.bindPopup(`
|
|
51
51
|
<div style="font-family:sans-serif; color:rgba(255, 255, 255, 0.9); line-height:1.3;">
|
|
52
|
-
<div style="font-weight:700; font-size:12px; margin-bottom:3px; color:#ffffff;">Conexão ${
|
|
53
|
-
<div style="font-size:11px; color:rgba(255, 255, 255, 0.65);">Tipo: ${
|
|
54
|
-
${
|
|
52
|
+
<div style="font-weight:700; font-size:12px; margin-bottom:3px; color:#ffffff;">Conexão ${M.escapeHtml(String(L.origemId))} ↔ ${M.escapeHtml(String(L.destinoId))}</div>
|
|
53
|
+
<div style="font-size:11px; color:rgba(255, 255, 255, 0.65);">Tipo: ${M.escapeHtml(L.tipoLinha||"contínua")}</div>
|
|
54
|
+
${Y}
|
|
55
55
|
</div>
|
|
56
|
-
`,{className:"compact-popup",maxWidth:220}),q.on("popupopen",
|
|
56
|
+
`,{className:"compact-popup",maxWidth:220}),q.on("popupopen",te=>{if(o.modoSequencial){q.closePopup();return}M.bindPopupAcoesEvents(te.popup,L,o,q)})}q.addTo(e)}});return}if((A=a.dados)!=null&&A.polilinhaSequencial||((w=a.dados)==null?void 0:w.fechar)!==void 0&&u.length>=2){const L=((x=a.dados)==null?void 0:x.chaveGrupo)||o.chaveGrupo,P=M.agruparPontosPorChave(u,L),z=((k=a.dados)==null?void 0:k.fechar)!==!1,I=a.estilo.corPrimaria||"#00f5a0";Object.entries(P).forEach(([S,E])=>{const D=M.ordenarPontosPorSequencia(E);if(D.length<2)return;const _=D.map(O=>[O.lat,O.lon]);re(e,_,l,i,a.estilo.dashArray);const R=b.polyline(_,{color:I,weight:l,opacity:d,dashArray:a.estilo.dashArray,pane:i,interactive:h});if(h&&R.bindPopup(`
|
|
57
57
|
<div style="font-family:sans-serif; color:rgba(255, 255, 255, 0.9); line-height:1.3;">
|
|
58
|
-
<div style="font-weight:700; font-size:12px; margin-bottom:3px; color:#ffffff;">Polilinha: Grupo ${
|
|
59
|
-
<div style="font-size:11px; color:rgba(255, 255, 255, 0.65);">Vértices: ${
|
|
58
|
+
<div style="font-weight:700; font-size:12px; margin-bottom:3px; color:#ffffff;">Polilinha: Grupo ${M.escapeHtml(S)}</div>
|
|
59
|
+
<div style="font-size:11px; color:rgba(255, 255, 255, 0.65);">Vértices: ${D.length}</div>
|
|
60
60
|
</div>
|
|
61
|
-
`,{className:"compact-popup",maxWidth:220}),
|
|
61
|
+
`,{className:"compact-popup",maxWidth:220}),R.addTo(e),z&&_.length>=3){const O=_[_.length-1],B=_[0],T=[O,B];re(e,T,l,i,"4, 4"),b.polyline(T,{color:I,weight:l,opacity:d,dashArray:"4, 4",pane:i,interactive:h}).addTo(e)}});return}if(!n&&s&&s.length>0)s.forEach(L=>{var I;const P=u.find(S=>String(S.id)===String(L.ponto_inicio_id)),z=u.find(S=>String(S.id)===String(L.ponto_fim_id));if(P&&z&&P.lat&&P.lon&&z.lat&&z.lon){const S=L.tipo_limite_sigef||L.tipo_limite||"",E=L.metodo_posicionamento_sigef||L.metodo_posicionamento||"",D=S==="LA1"?"#10b981":S==="LN1"?"#3b82f6":"#00f5a0",_=L.id!=null?L.id:`${L.ponto_inicio_id}-${L.ponto_fim_id}`,R=o.selectedSegmentoId!=null&&(String(o.selectedSegmentoId)===String(L.id)||String(o.selectedSegmentoId)===String(_)),O=R?"#facc15":a.estilo.corPrimaria||D,B=[[P.lat,P.lon],[z.lat,z.lon]],T=R?l+3:l,$=S==="LN1"?"6, 6":a.estilo.dashArray;re(e,B,R?T+2:T,i,$);const F=b.polyline(B,{color:O,weight:T,opacity:R?1:d,dashArray:$,pane:i,interactive:h});if(F.segmentoId=_,F.segmento=L,h){F.on("click",j=>{j&&j.originalEvent&&j.originalEvent.stopPropagation(),o.onSegmentoClick&&o.onSegmentoClick(_,L,{lat:(P.lat+z.lat)/2,lon:(P.lon+z.lon)/2})});const V=L.acoes||a.acoes||((I=a.dados)==null?void 0:I.acoes)||[],q=`${L.ponto_inicio_id}-${L.ponto_fim_id}`,H=M.renderPopupAcoesHtml(V,q);F.bindPopup(`
|
|
62
62
|
<div style="font-family:sans-serif; color:rgba(255, 255, 255, 0.9); line-height:1.3;">
|
|
63
|
-
<div style="font-weight:700; font-size:12px; margin-bottom:3px; color:#ffffff;">${
|
|
64
|
-
<div style="font-size:11px; color:rgba(255, 255, 255, 0.65);">Limite: ${
|
|
65
|
-
${
|
|
63
|
+
<div style="font-weight:700; font-size:12px; margin-bottom:3px; color:#ffffff;">${M.escapeHtml(P.nome_vertice)} ↔ ${M.escapeHtml(z.nome_vertice)}</div>
|
|
64
|
+
<div style="font-size:11px; color:rgba(255, 255, 255, 0.65);">Limite: ${M.escapeHtml(S||"N/A")} · ${M.escapeHtml(E||"N/A")}</div>
|
|
65
|
+
${H}
|
|
66
66
|
</div>
|
|
67
|
-
`,{className:"compact-popup",maxWidth:220})
|
|
68
|
-
<div ${i?`id="${
|
|
69
|
-
<svg width="${
|
|
70
|
-
${A}${
|
|
67
|
+
`,{className:"compact-popup",maxWidth:220}),F.on("popupopen",j=>{if(o.modoSequencial){F.closePopup();return}M.bindPopupAcoesEvents(j.popup,L,o,F)})}F.addTo(e)}});else if(u&&u.length>=2){const L=u.filter(E=>E.lat&&E.lon&&E.tipo_ponto!=="B"&&E.tipo!=="B"&&E.ignorar_poligono!==1),P=((C=a.dados)==null?void 0:C.chaveGrupo)||o.chaveGrupo,z=M.agruparPontosPorChave(L,P),I=a.estilo.corPrimaria||(n?"#f59e0b":"#10b981"),S=a.estilo.dashArray||(n?"6, 8":void 0);Object.values(z).forEach(E=>{const D=M.ordenarPontosPorSequencia(E);if(D.length<2)return;const _=D.map(O=>[O.lat,O.lon]);if(re(e,_,l,i,S),b.polyline(_,{color:I,weight:l,opacity:d,dashArray:S,pane:i,interactive:h}).addTo(e),_.length>=3){const O=_[_.length-1],B=_[0],T=n?"6, 8":"4, 4",$=[O,B];re(e,$,l,i,T),b.polyline($,{color:I,weight:l,opacity:d,dashArray:T,pane:i,interactive:h}).addTo(e)}})}}class Co{constructor(){f(this,"zoomListenerMap",new WeakMap)}render(e,t,o){const i=b.layerGroup(),n=U(t,e.id,"linha");Vt(e,i,t,o,n);const r=()=>{if(e.estilo.scaleMode==="world"){const s=Po(e,t,o);i.eachLayer(c=>{c.setStyle&&c.setStyle({weight:s})})}};return t.on("zoomend",r),this.zoomListenerMap.set(i,r),i}update(e,t,o,i,n){(o.opacidade!==void 0||o.estilo!==void 0||o.dados!==void 0||o.interativo!==void 0||o.bloqueada!==void 0)&&(t.clearLayers(),Vt(e,t,n,i,U(n,e.id,"linha")))}destroy(e,t){const o=this.zoomListenerMap.get(e);o&&(t.off("zoomend",o),this.zoomListenerMap.delete(e)),e.clearLayers(),t.hasLayer(e)&&t.removeLayer(e)}}const He=300;function Ge(a){return a>He?"compacta":"normal"}function wt(a,e){if(a<=He)return 1;const t=Math.max(.7,1-.3*Math.log10(a/He)),o=e>=18?1:e>=16?.92:e>=14?.82:.72;return Math.max(.6,t*o)}function Lo(a){if(!a)return"#00f5a0";const e=a.trim();if(e.startsWith("#")||e.startsWith("rgb")||e.startsWith("hsl")||e.startsWith("var("))return e;if(e.includes("bg-[#")&&e.includes("]")){const o=e.match(/bg-\[(#[a-fA-F0-9]+)\]/);if(o)return o[1]}const t={"bg-mint-vibrant":"#00f5a0","bg-indigo-500":"#6366f1","bg-rose-500":"#f43f5e","bg-amber-500":"#f59e0b","bg-forest-deep":"#06130b","bg-purple-500":"#a855f7","bg-blue-500":"#3b82f6","bg-emerald-500":"#10b981"};for(const[o,i]of Object.entries(t))if(e.includes(o))return i;return"#00f5a0"}function Ht(a){return a.replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[e])}const Je={diamond:"6,0.8 11.2,6 6,11.2 0.8,6",triangle:"6,1 11.4,10.6 0.6,10.6"},Qe={cross:["M6 1.2V10.8","M1.2 6H10.8"],x:["M2 2L10 10","M10 2L2 10"]};function ye(a,e,t,o="",i="",n=!1,r={}){const s=n||o.includes("ponto-selecionado")||o.includes("cad-marker-selected"),c=r.densidade==="compacta",l=Ht(Lo(t)),d=e+6,h=s?`color-mix(in srgb, ${l} 38%, #000000)`:l,u=s?1:c?.72:.9,g=s?"rgba(255,255,255,0.95)":c?"rgba(0,0,0,0.55)":"rgba(0,0,0,0.7)",v=s?1.3:c?.8:1,p=s?"rgba(255,255,255,0.9)":"rgba(0,0,0,0.6)",y=(P,z,I,S="")=>`class="${P}" stroke="${z}" stroke-width="${I}" vector-effect="non-scaling-stroke" ${S}`,A=a in Je?`<polygon points="${Je[a]}" style="fill:${h}" fill-opacity="${u}" stroke-linejoin="round" ${y("cad-pt-contorno",g,v)} />`:a in Qe?Qe[a].map(P=>`<path d="${P}" fill="none" stroke-linecap="round" ${y("cad-pt-halo",p,c?2.6:3.4)} /><path d="${P}" fill="none" stroke-linecap="round" ${y("cad-pt-traco",s?h:l,c?1.3:1.8,`stroke-opacity="${s?1:c?.9:1}"`)} />`).join(""):a==="square"?`<rect x="1.2" y="1.2" width="9.6" height="9.6" rx="1.4" style="fill:${h}" fill-opacity="${u}" ${y("cad-pt-contorno",g,v)} />`:`<circle cx="6" cy="6" r="5.2" style="fill:${h}" fill-opacity="${u}" ${y("cad-pt-contorno",g,v)} />`,w=!c&&!s&&!(a in Qe)?a in Je?"":a==="square"?'<rect x="2.2" y="2.2" width="7.6" height="7.6" rx="0.9" fill="none" stroke="rgba(255,255,255,0.45)" stroke-width="0.8" vector-effect="non-scaling-stroke" />':'<circle cx="6" cy="6" r="4.3" fill="none" stroke="rgba(255,255,255,0.45)" stroke-width="0.8" vector-effect="non-scaling-stroke" />':"",x=a==="circle-dot"?'<circle cx="6" cy="6" r="1.7" fill="#ffffff" stroke="rgba(0,0,0,0.45)" stroke-width="0.6" vector-effect="non-scaling-stroke" />':"",k=`cad-pt ${c?"cad-pt-compacto":""} ${t} ${o} ${s?"ponto-selecionado":""}`.replace(/\s+/g," ").trim(),C=e;return`
|
|
68
|
+
<div ${i?`id="${Ht(i)}"`:""} class="${k}" style="display:flex; align-items:center; justify-content:center; width:${d}px; height:${d}px; position:relative; pointer-events:auto; background:none !important;">
|
|
69
|
+
<svg width="${C}" height="${C}" viewBox="0 0 12 12" xmlns="http://www.w3.org/2000/svg" style="overflow:visible; display:block;">
|
|
70
|
+
${A}${w}${x}
|
|
71
71
|
</svg>
|
|
72
72
|
</div>
|
|
73
|
-
`}class
|
|
73
|
+
`}class So{constructor(){f(this,"zoomListenerMap",new WeakMap)}render(e,t,o){const i=b.layerGroup(),n=U(t,e.id,"ponto");this.rebuildPoints(e,i,t,o,n);const r=()=>{i.eachLayer(s=>{if(!(s.setIcon&&s.baseSize&&s.shapeStyle&&s.markerBg&&s.pontoId!==void 0))return;const c=s.densTotal||0;if(e.estilo.scaleMode!=="world"&&Ge(c)!=="compacta")return;const l=this.calculateSize(e,t,o,s.baseSize,c);l!==s.tamanhoPx&&(s.tamanhoPx=l,s.setIcon(this.criarIcone(e,o,s.shapeStyle,l,s.markerBg,s.pontoId,!!s.isSelected,c)))})};return t.on("zoomend",r),this.zoomListenerMap.set(i,r),i}criarIcone(e,t,o,i,n,r,s,c){const l=t.config.enableAnimations?"cad-pt-anim":"",d=ye(o,i,n,l,`map-marker-${e.id}-${r}`,s,{densidade:Ge(c)});return b.divIcon({html:d,className:`custom-leaflet-marker ${s?"cad-marker-selected":""}`.trim(),iconSize:[i+6,i+6]})}calculateSize(e,t,o,i,n=0){const r=o.graphicScale.markerScaleMultiplier||1;if(e.estilo.scaleMode==="world"){const c=e.estilo.dimensaoMetros||.25,l=t.getCenter(),d=t.getZoom(),h=40075016686e-3*Math.abs(Math.cos(l.lat*Math.PI/180))/Math.pow(2,d+8),u=c/(h>0?h:1);return Math.max(3,Math.round(u*r))}const s=wt(n,t.getZoom());return Math.max(s<1?5:4,Math.round(i*r*s))}rebuildPoints(e,t,o,i,n){var g;const s=e.id==="homologados-pontos"?i.bancoPontos||[]:((g=e.dados)==null?void 0:g.pontos)||i.pontos||[],c=e.interativo&&!e.bloqueada,l=e.id==="vizinhos",d=e.id==="homologados"||e.id==="homologados-pontos",h=i.selectedPontoIds||[],u=s.length;s.forEach(v=>{var A;const p=v.lat??v.latitude,y=v.lon??v.lng??v.longitude;if(p!==void 0&&y!==void 0&&p!==0&&y!==0&&!isNaN(Number(p))&&!isNaN(Number(y))){const w=v.tipo_ponto==="B"||v.tipo==="B",x=v.tipo_ponto==="M"||v.tipo==="M";let k=e.estilo.estiloMarcador||"x",C=e.estilo.corPrimaria||"bg-mint-vibrant",L=e.estilo.tamanhoMarcador||7;d?(k="circle",C=e.estilo.corPrimaria||"#f59e0b",L=8):l?(k=x?"circle-dot":e.estilo.estiloMarcador||"cross",C=e.estilo.corPrimaria||"#a855f7",L=x?10:8):x?(C="#6366f1",k="circle-dot",L=10):w&&(C="#f43f5e",k="square",L=9);const P=!!(v.selecionado||h.length>0&&(h.includes(v.id)||h.includes(String(v.id))||h.includes(Number(v.id)))),z=this.calculateSize(e,o,i,L,u),I=this.criarIcone(e,i,k,z,C,v.id,P,u),S=b.marker([Number(p),Number(y)],{icon:I,pane:n,interactive:c});if(P&&S.setZIndexOffset(2e3),S.pontoId=v.id,S.layerId=e.id,S.isVizinho=l,S.baseSize=L,S.shapeStyle=k,S.markerBg=C,S.isSelected=P,S.densTotal=u,S.tamanhoPx=z,c){const E=d?"Vértice Homologado SIGEF":l?"Confrontante (Importado)":x?"Base Homologada PPP":w?"Base de Campo (Translação)":"Vértice de Perímetro",D=v.acoes||e.acoes||((A=e.dados)==null?void 0:A.acoes)||[],_=M.renderPopupAcoesHtml(D,v.id);S.bindPopup(`
|
|
74
74
|
<div style="font-family:var(--ui-fonte-base, sans-serif); color:rgba(255, 255, 255, 0.9); line-height:1.3;">
|
|
75
|
-
<div style="font-weight:700; font-size:13px; margin-bottom:4px; color:#ffffff;">${
|
|
76
|
-
<div style="font-size:11px; color:rgba(255, 255, 255, 0.65);">${
|
|
77
|
-
<div style="font-size:11px; color:rgba(255, 255, 255, 0.45); font-family:var(--ui-fonte-codigo, monospace); margin-top:4px;">Lat ${Number(
|
|
75
|
+
<div style="font-weight:700; font-size:13px; margin-bottom:4px; color:#ffffff;">${M.escapeHtml(v.nome_vertice||String(v.id))}</div>
|
|
76
|
+
<div style="font-size:11px; color:rgba(255, 255, 255, 0.65);">${M.escapeHtml(E)} · ${M.escapeHtml(v.tipo_ponto||v.tipo||"Vértice")}</div>
|
|
77
|
+
<div style="font-size:11px; color:rgba(255, 255, 255, 0.45); font-family:var(--ui-fonte-codigo, monospace); margin-top:4px;">Lat ${Number(p).toFixed(6)} Lon ${Number(y).toFixed(6)}</div>
|
|
78
78
|
${_}
|
|
79
79
|
</div>
|
|
80
|
-
`,{className:"compact-popup",maxWidth:240}),
|
|
80
|
+
`,{className:"compact-popup",maxWidth:240}),D&&D.length>0&&S.on("popupopen",R=>{M.bindPopupAcoesEvents(R.popup,v,i,S)}),S.on("click",()=>{i.onMarkerClick&&i.onMarkerClick(v.id,l,v,{lat:Number(p),lon:Number(y)})})}S.addTo(t)}})}update(e,t,o,i,n){(o.opacidade!==void 0||o.estilo!==void 0||o.dados!==void 0||o.interativo!==void 0||o.bloqueada!==void 0)&&(t.clearLayers(),this.rebuildPoints(e,t,n,i,U(n,e.id,"ponto")))}destroy(e,t){const o=this.zoomListenerMap.get(e);o&&(t.off("zoomend",o),this.zoomListenerMap.delete(e)),e.clearLayers(),t.hasLayer(e)&&t.removeLayer(e)}}class Mo{render(e,t,o){const i=b.layerGroup();return this.rebuildPolygons(e,i,o,t),i}rebuildPolygons(e,t,o,i){var g,v;const n=U(i,e.id,"poligono"),r=U(i,e.id,"ponto"),c=(((g=e.dados)==null?void 0:g.poligonos)??(Array.isArray(e.dados)?e.dados:null))||((v=e.dados)==null?void 0:v.confrontantes)||o.confrontantes||[],l=e.interativo&&!e.bloqueada,d=e.estilo.corPrimaria||"#a855f7",h=e.estilo.espessuraLinha||1,u=e.opacidade!==void 0?e.opacidade:.8;c.forEach(p=>{var P,z,I,S,E,D,_,R,O,B;if(!p)return;const y=((P=p.estilo)==null?void 0:P.cor)||((z=p.estilo)==null?void 0:z.color)||d,A=((I=p.estilo)==null?void 0:I.espessura)||((S=p.estilo)==null?void 0:S.weight)||h,w=((E=p.estilo)==null?void 0:E.opacidade)??u,x=((D=p.estilo)==null?void 0:D.fillColor)||y,k=((_=p.estilo)==null?void 0:_.fillOpacity)??Math.min(.14,w*.1),C=((R=p.estilo)==null?void 0:R.dashArray)||e.estilo.dashArray||"4, 6";if(p.coordenadas&&Array.isArray(p.coordenadas)&&p.coordenadas.length>=3){const T=Array.isArray(p.coordenadas[0])&&Array.isArray(p.coordenadas[0][0]);let $;if(T?$=p.coordenadas.map(F=>F.map(V=>{const q=M.parseCoordenada(V[0],V[1]);return q?[q.lat,q.lon]:null}).filter(Boolean)):$=p.coordenadas.map(F=>{const V=M.parseCoordenada(F[0],F[1]);return V?[V.lat,V.lon]:null}).filter(Boolean),$&&(T?((O=$[0])==null?void 0:O.length)>=3:$.length>=3)){const F=b.polygon($,{color:y,weight:A,opacity:w,dashArray:C,fillColor:x,fillOpacity:k,lineJoin:"round",pane:n,interactive:l});if(F.poligonoId=p.id,F.layerId=e.id,l){let V="";p.metadados&&Object.keys(p.metadados).length>0&&(V=Object.entries(p.metadados).map(([q,H])=>`<div style="font-size:11px;"><strong>${M.escapeHtml(q)}:</strong> ${M.escapeHtml(String(H))}</div>`).join("")),F.bindPopup(`
|
|
81
81
|
<div style="font-family:var(--ui-fonte-base, sans-serif); color:rgba(255, 255, 255, 0.9); line-height:1.3; min-width:180px;">
|
|
82
|
-
<div style="font-weight:700; font-size:12px; color:#c084fc; margin-bottom:3px; border-bottom:1px solid rgba(255,255,255,0.1); padding-bottom:3px;">Polígono ${
|
|
83
|
-
${
|
|
82
|
+
<div style="font-weight:700; font-size:12px; color:#c084fc; margin-bottom:3px; border-bottom:1px solid rgba(255,255,255,0.1); padding-bottom:3px;">Polígono ${M.escapeHtml(String(p.id??""))}</div>
|
|
83
|
+
${V||`<div style="font-size:11px;">Área vetorial definida por ${p.coordenadas.length} vértices</div>`}
|
|
84
84
|
</div>
|
|
85
|
-
`,{className:"compact-popup",maxWidth:220})
|
|
85
|
+
`,{className:"compact-popup",maxWidth:220}),F.on("popupopen",()=>{o.modoSequencial&&F.closePopup()})}F.addTo(t);return}}const L=p.wkt||p.poligono_wkt;if(L){const T=[...L.matchAll(/\(([^()]+)\)/g)];if(T.length>0){const $=M.escapeHtml(p.nome_propriedade||`Polígono ${String(p.id||"")}`),F=M.escapeHtml(p.nome||"Proprietário"),V=[];if(T.forEach(q=>{const H=q[1].split(",").map(j=>{const Y=j.trim().split(/\s+/);if(Y.length<2)return null;const te=M.parseCoordenada(Y[1],Y[0]);return te?[te.lat,te.lon]:null}).filter(j=>j!==null);H.length>=3&&V.push(H)}),V.length>0){const q=V.length===1?V[0]:V,H=b.polygon(q,{color:y,weight:A,opacity:w,dashArray:C,fillColor:x,fillOpacity:k,lineJoin:"round",pane:n,interactive:l});if(H.poligonoId=p.id,H.layerId=e.id,l){const j=p.acoes||e.acoes||((B=e.dados)==null?void 0:B.acoes)||[],Y=M.renderPopupAcoesHtml(j,p.id);H.bindPopup(`
|
|
86
86
|
<div style="font-family:var(--ui-fonte-base, sans-serif); color:rgba(255, 255, 255, 0.9); line-height:1.3; min-width:180px;">
|
|
87
|
-
<div style="font-weight:700; font-size:12px; color:#c084fc; margin-bottom:3px; border-bottom:1px solid rgba(255,255,255,0.1); padding-bottom:3px;">${
|
|
88
|
-
<div style="font-size:11px; margin-bottom:2px;"><strong>Identificador:</strong> ${
|
|
89
|
-
${
|
|
90
|
-
${
|
|
87
|
+
<div style="font-weight:700; font-size:12px; color:#c084fc; margin-bottom:3px; border-bottom:1px solid rgba(255,255,255,0.1); padding-bottom:3px;">${$}</div>
|
|
88
|
+
<div style="font-size:11px; margin-bottom:2px;"><strong>Identificador:</strong> ${M.escapeHtml(String(p.id??""))}</div>
|
|
89
|
+
${p.nome?`<div style="font-size:11px;"><strong>Proprietário:</strong> ${F}</div>`:""}
|
|
90
|
+
${Y}
|
|
91
91
|
</div>
|
|
92
|
-
`,{className:"compact-popup",maxWidth:220}),
|
|
92
|
+
`,{className:"compact-popup",maxWidth:220}),H.on("popupopen",te=>{if(o.modoSequencial){H.closePopup();return}M.bindPopupAcoesEvents(te.popup,p,o,H)})}H.addTo(t)}}}p.pontos&&p.pontos.length>0&&p.pontos.forEach(T=>{var F;const $=M.parseCoordenada(T.lat??T.latitude??T.y,T.lon??T.lng??T.longitude??T.x);if($){const V=b.divIcon({html:'<div class="cad-pt" style="width:12px; height:12px; display:flex; align-items:center; justify-content:center;"><svg width="8" height="8" viewBox="0 0 12 12" style="overflow:visible; display:block;"><circle cx="6" cy="6" r="5.2" fill="#a855f7" fill-opacity="0.85" stroke="rgba(0,0,0,0.65)" stroke-width="1" vector-effect="non-scaling-stroke" /><circle cx="6" cy="6" r="4.3" fill="none" stroke="rgba(255,255,255,0.5)" stroke-width="0.8" vector-effect="non-scaling-stroke" /></svg></div>',className:"custom-leaflet-marker",iconSize:[12,12]}),q=b.marker([$.lat,$.lon],{icon:V,pane:r,interactive:l});if(q.pontoId=T.id,q.isVizinho=!0,q.layerId=e.id,l){const H=T.acoes||p.acoes||e.acoes||((F=e.dados)==null?void 0:F.acoes)||[],j=M.renderPopupAcoesHtml(H,T.id);q.bindPopup(`
|
|
93
93
|
<div style="font-family:var(--ui-fonte-base, sans-serif); color:rgba(255, 255, 255, 0.9); line-height:1.3; min-width:170px;">
|
|
94
|
-
<div style="font-weight:700; font-size:12px; color:#c084fc; margin-bottom:3px;">${
|
|
95
|
-
<div style="font-size:11px; color:rgba(255, 255, 255, 0.65);">Confrontante: ${
|
|
96
|
-
<div style="font-size:10px; color:rgba(255, 255, 255, 0.45); font-family:var(--ui-fonte-codigo, monospace); margin-top:3px;">Lat ${
|
|
97
|
-
${
|
|
94
|
+
<div style="font-weight:700; font-size:12px; color:#c084fc; margin-bottom:3px;">${M.escapeHtml(T.nome_vertice||String(T.id))}</div>
|
|
95
|
+
<div style="font-size:11px; color:rgba(255, 255, 255, 0.65);">Confrontante: ${M.escapeHtml(p.nome||"Desconhecido")}</div>
|
|
96
|
+
<div style="font-size:10px; color:rgba(255, 255, 255, 0.45); font-family:var(--ui-fonte-codigo, monospace); margin-top:3px;">Lat ${$.lat.toFixed(6)} Lon ${$.lon.toFixed(6)}</div>
|
|
97
|
+
${j}
|
|
98
98
|
</div>
|
|
99
|
-
`,{className:"compact-popup",maxWidth:220}),q.on("click",()=>{o.modoSequencial&&q.closePopup(),o.onMarkerClick&&o.onMarkerClick(D.id,!0,D,{lat:F.lat,lon:F.lon})}),q.on("popupopen",J=>{if(o.modoSequencial){q.closePopup();return}S.bindPopupAcoesEvents(J.popup,D,o,q)})}q.addTo(e)}})})}update(t,e,o,i,n){o.opacidade!==void 0&&o.estilo===void 0&&o.dados===void 0&&o.interativo===void 0&&o.bloqueada===void 0||(o.opacidade!==void 0||o.estilo!==void 0||o.dados!==void 0||o.interativo!==void 0||o.bloqueada!==void 0)&&(e.clearLayers(),this.rebuildPolygons(t,e,i,n))}destroy(t,e){t.clearLayers(),e.hasLayer(t)&&e.removeLayer(t)}}class Xo{constructor(){p(this,"moveListenerMap",new WeakMap)}render(t,e,o){const i=v.layerGroup(),n=`pane-${t.id}`,r=()=>{if(i.clearLayers(),!t.visivel)return;if(e.getZoom()>20){const c=e.getBounds(),l=c.getSouth(),d=c.getNorth(),h=c.getWest(),u=c.getEast(),g=e.getCenter(),m=8999e-9,f=Math.cos(g.lat*Math.PI/180),b=m/(f>.1?f:1),A=Math.floor((d-l)/m),M=Math.floor((u-h)/b);if(A<200&&M<200){const C=Math.ceil(l/m)*m;for(let P=C;P<=d;P+=m)v.polyline([[P,h],[P,u]],{color:t.estilo.corPrimaria||"rgba(0, 245, 160, 0.18)",weight:t.estilo.espessuraLinha||.6,interactive:!1,pane:n}).addTo(i);const k=Math.ceil(h/b)*b;for(let P=k;P<=u;P+=b)v.polyline([[l,P],[d,P]],{color:t.estilo.corPrimaria||"rgba(0, 245, 160, 0.18)",weight:t.estilo.espessuraLinha||.6,interactive:!1,pane:n}).addTo(i)}}};return r(),e.on("zoomend moveend",r),this.moveListenerMap.set(i,r),i}update(t,e){t.visivel||e.clearLayers()}destroy(t,e){const o=this.moveListenerMap.get(t);o&&(e.off("zoomend moveend",o),this.moveListenerMap.delete(t)),t.clearLayers(),e.hasLayer(t)&&e.removeLayer(t)}}function j(a){return a.partes&&a.partes.length>1?a.partes:[a.coordenadas]}function wt(a){return a.tipo==="LineString"&&!!a.partes&&a.partes.length>1}function yt(a){return a.length>1?{tipo:"LineString",coordenadas:a[0],partes:a}:{tipo:"LineString",coordenadas:a[0]}}const Le=63710088e-1,it=a=>a*Math.PI/180;function rt(a,t){const e=it(t[0]-a[0]),o=it(t[1]-a[1]),i=Math.sin(e/2)**2+Math.cos(it(a[0]))*Math.cos(it(t[0]))*Math.sin(o/2)**2;return 2*Le*Math.asin(Math.min(1,Math.sqrt(i)))}function Et(a,t=!1){let e=0;for(let o=1;o<a.length;o++)e+=rt(a[o-1],a[o]);return t&&a.length>2&&(e+=rt(a[a.length-1],a[0])),e}function ao(a){const t=it(a.reduce((i,n)=>i+n[0],0)/a.length),e=a.map(i=>[it(i[1])*Math.cos(t)*Le,it(i[0])*Le]);let o=0;for(let i=0;i<e.length;i++){const[n,r]=e[i],[s,c]=e[(i+1)%e.length];o+=n*c-s*r}return Math.abs(o)/2}function Zo(a){const[t,...e]=a;return t?Math.max(0,ao(t)-e.reduce((o,i)=>o+ao(i),0)):0}const Sa=new Intl.NumberFormat("pt-BR",{minimumFractionDigits:4,maximumFractionDigits:4}),no=new Intl.NumberFormat("pt-BR",{minimumFractionDigits:2,maximumFractionDigits:2});function st(a){return`${Sa.format(a/1e4)} ha`}function G(a){return a>=1e3?`${no.format(a/1e3)} km`:`${no.format(a)} m`}function Q(a){return a.tipo==="Polygon"?Zo(a.aneis):a.tipo==="Circle"?Math.PI*a.raioMetros**2:null}function tt(a){return a.tipo==="LineString"?j(a).reduce((t,e)=>t+Et(e),0):a.tipo==="Polygon"?Et(a.aneis[0]??[],!0):a.tipo==="Circle"?2*Math.PI*a.raioMetros:null}function Yo(a,t){var i;const e=t??"name";if(e==="area"){const n=Q(a.geometria);return n===null?"":st(n)}if(e==="extensao"){const n=tt(a.geometria);return n===null?"":G(n)}if(e==="id")return a.id;const o=(i=a.propriedades)==null?void 0:i[e];return o!=null&&o!==""?String(o):t?"":a.id}function Fe(a){let t;switch(a.tipo){case"Point":case"Text":t=[a.coordenada];break;case"LineString":t=j(a).flat();break;case"Polygon":t=a.aneis.flat();break;case"Circle":{const i=a.raioMetros/111320,n=i/Math.max(.01,Math.cos(it(a.centro[0])));t=[[a.centro[0]-i,a.centro[1]-n],[a.centro[0]+i,a.centro[1]+n]];break}}const e=t.map(i=>i[0]),o=t.map(i=>i[1]);return[[Math.min(...e),Math.min(...o)],[Math.max(...e),Math.max(...o)]]}const $t=16,Ma=256;function Se(a){const[[t,e],[o,i]]=Fe(a.geometria);return{minLon:e,minLat:t,maxLon:i,maxLat:o}}function mt(a,t){return a.minLon<=t.maxLon&&a.maxLon>=t.minLon&&a.minLat<=t.maxLat&&a.maxLat>=t.minLat}function ro(a){let t=1/0,e=1/0,o=-1/0,i=-1/0;for(const n of a)n.minLon<t&&(t=n.minLon),n.minLat<e&&(e=n.minLat),n.maxLon>o&&(o=n.maxLon),n.maxLat>i&&(i=n.maxLat);return{minLon:t,minLat:e,maxLon:o,maxLat:i}}function so(a){const t=a.length,e=Math.ceil(t/$t),i=Math.ceil(Math.sqrt(e))*$t,n=[...a].sort((s,c)=>s.minLon+s.maxLon-(c.minLon+c.maxLon)),r=[];for(let s=0;s<t;s+=i){const c=n.slice(s,s+i).sort((l,d)=>l.minLat+l.maxLat-(d.minLat+d.maxLat));for(let l=0;l<c.length;l+=$t)r.push(c.slice(l,l+$t))}return r}function Aa(a){if(a.length===0)return null;let t=so(a).map(e=>({...ro(e),folhas:e}));for(;t.length>1;)t=so(t).map(e=>({...ro(e),filhos:e}));return t[0]}class Ko{constructor(){p(this,"raiz",null);p(this,"itens",new Map);p(this,"delta",new Map);p(this,"obsoletos",new Set)}get tamanho(){return this.itens.size}construir(t){this.itens.clear();for(const e of t)e.excluida||this.itens.set(e.id,{id:e.id,...Se(e)});this.remontar()}inserir(t){this.atualizar(t)}atualizar(t){if(t.excluida){this.remover(t.id);return}const e={id:t.id,...Se(t)};this.itens.has(t.id)&&this.obsoletos.add(t.id),this.itens.set(t.id,e),this.delta.set(t.id,e),this.compactarSeNecessario()}remover(t){this.itens.delete(t)&&(this.obsoletos.add(t),this.delta.delete(t),this.compactarSeNecessario())}limpar(){this.itens.clear(),this.remontar()}consultar(t){const e=[],o=this.raiz?[this.raiz]:[];for(;o.length>0;){const i=o.pop();if(mt(i,t))if(i.folhas)for(const n of i.folhas)!this.obsoletos.has(n.id)&&mt(n,t)&&e.push(n.id);else i.filhos&&o.push(...i.filhos)}for(const i of this.delta.values())mt(i,t)&&e.push(i.id);return e}intersecta(t){return this.consultar(t).length>0}caixaDe(t){return this.itens.get(t)}compactarSeNecessario(){this.delta.size+this.obsoletos.size>Math.max(Ma,this.itens.size*.1)&&this.remontar()}remontar(){this.raiz=Aa([...this.itens.values()]),this.delta.clear(),this.obsoletos.clear()}}const Yt=12,Ne=40,wa=1.2;function Jo(a){return a>=Yt?0:360/(256*2**a)*wa}function Ea(a,t,e){const o=e[1]-t[1],i=e[0]-t[0],n=o*o+i*i;let r=n===0?0:((a[1]-t[1])*o+(a[0]-t[0])*i)/n;return r=Math.max(0,Math.min(1,r)),Math.hypot(a[1]-(t[1]+r*o),a[0]-(t[0]+r*i))}function Oe(a,t){if(t<=0||a.length<3)return a;const e=new Uint8Array(a.length);e[0]=1,e[a.length-1]=1;const o=[[0,a.length-1]];for(;o.length>0;){const[i,n]=o.pop();let r=0,s=-1;for(let c=i+1;c<n;c++){const l=Ea(a[c],a[i],a[n]);l>r&&(r=l,s=c)}s!==-1&&r>t&&(e[s]=1,o.push([i,s],[s,n]))}return a.filter((i,n)=>e[n]===1)}function Qo(a,t){if(t<=0||a.length<4)return a;const e=[...a,a[0]],o=Oe(e,t);return o.pop(),o.length>=3?o:a}function Re(a){return(a.tipo==="LineString"||a.tipo==="Polygon")&&a.curva?0:a.tipo==="LineString"?j(a).reduce((t,e)=>t+e.length,0):a.tipo==="Polygon"?a.aneis.reduce((t,e)=>t+e.length,0):0}function ti(a,t){const e=Jo(t);return e===0||Re(a)<Ne?a:a.tipo==="LineString"?yt(j(a).map(o=>Oe(o,e))):a.tipo==="Polygon"?{tipo:"Polygon",aneis:a.aneis.map(o=>Qo(o,e))}:a}const ka=new Set(["previa","prévia","preview","rascunho","draft","proposta"]);function Y(a){var e,o;const t=[a.status,(e=a.propriedades)==null?void 0:e.status,(o=a.propriedades)==null?void 0:o.tipo_geometria];for(const i of t)if(typeof i=="string"&&ka.has(i.trim().toLowerCase()))return"previa";return"oficial"}function at(a){var e;const t=a.entidadeId??((e=a.propriedades)==null?void 0:e.entidadeId);return typeof t=="string"||typeof t=="number"?String(t):a.id}const le=(a,t)=>`${a}\0${t}`;class ae{constructor(){p(this,"global",!1);p(this,"individuais",new Set)}alternarIndividual(t,e){const o=le(t,e);return this.individuais.has(o)?this.individuais.delete(o):this.individuais.add(o),this.individuais.has(o)}definirIndividual(t,e,o){const i=le(t,e);o?this.individuais.add(i):this.individuais.delete(i)}individualAtiva(t,e){return this.individuais.has(le(t,e))}static oficiais(t){const e=new Set;for(const o of t)!o.excluida&&Y(o)==="oficial"&&e.add(at(o));return e}visivel(t,e){if(Y(t)==="oficial")return!0;const o=at(t);return this.global||!e.has(o)||this.individualAtiva(t.camadaId,o)}previaSolicitada(t){return this.global||this.individualAtiva(t.camadaId,at(t))}}const za=24,Ia=2,co=a=>typeof a=="number"&&Number.isFinite(a),de=a=>Array.isArray(a)&&a.length===2&&co(a[0])&&co(a[1]);function Be(a,t){return[2*a[0]-t[0],2*a[1]-t[1]]}function ei(a){return a.some(t=>t.entrada!==void 0||t.saida!==void 0)}function It(a,t){return[a.saida??a.ponto,t.entrada??t.ponto]}function oi(a,t){const e=[];for(let o=0;o<a-1;o++)e.push([o,o+1]);return t&&a>2&&e.push([a-1,0]),e}function He(a,t,e,o,i){const n=1-i,r=n*n*n,s=3*n*n*i,c=3*n*i*i,l=i*i*i;return[r*a[0]+s*t[0]+c*e[0]+l*o[0],r*a[1]+s*t[1]+c*e[1]+l*o[1]]}function bt(a,t=!1,e=za){if(a.length===0)return[];const o=[[a[0].ponto[0],a[0].ponto[1]]];for(const[i,n]of oi(a.length,t)){const r=a[i],s=a[n];if(!(r.saida===void 0&&s.entrada===void 0)){const[l,d]=It(r,s);for(let h=1;h<e;h++)o.push(He(r.ponto,l,d,s.ponto,h/e))}n!==0&&o.push([s.ponto[0],s.ponto[1]])}return o}function ii(a,t){if(a.length===0)return[];const e=[{cmd:"M",pts:[a[0].ponto]}];for(const[o,i]of oi(a.length,t)){const n=a[o],r=a[i];if(n.saida===void 0&&r.entrada===void 0)e.push({cmd:"L",pts:[r.ponto]});else{const[s,c]=It(n,r);e.push({cmd:"C",pts:[s,c,r.ponto]})}}return e}function _a(a,t,e){const o=n=>String(Math.round(n*100)/100),i=ii(a,t).map(n=>n.cmd+n.pts.map(r=>{const s=e(r);return`${o(s.x)} ${o(s.y)}`}).join(" ")).join("");return i&&t?`${i}Z`:i}function Ta(a,t=Ia){if(!Array.isArray(a)||a.length<t)return null;const e=[];for(const o of a){if(!o||typeof o!="object"||!de(o.ponto))return null;const i=o,n={ponto:[i.ponto[0],i.ponto[1]]};de(i.entrada)&&(n.entrada=[i.entrada[0],i.entrada[1]]),de(i.saida)&&(n.saida=[i.saida[0],i.saida[1]]),e.push(n)}return ei(e)?e:null}function lo(a,t){return a.map(e=>{const o={ponto:t(e.ponto)};return e.entrada&&(o.entrada=t(e.entrada)),e.saida&&(o.saida=t(e.saida)),o})}function ai(a,t){var r,s;const e=a._nosCurva,o=a._renderer,i=a._map;if(!e||e.length<2||!o||!i)return!1;const n=c=>i.latLngToLayerPoint([c[0],c[1]]);if(o._ctx&&o._fillStroke){if(!o._drawing||!((r=a._parts)!=null&&r.length))return!0;const c=o._ctx;c.beginPath();for(const l of ii(e,t)){const d=l.pts.map(n);l.cmd==="M"?c.moveTo(d[0].x,d[0].y):l.cmd==="L"?c.lineTo(d[0].x,d[0].y):c.bezierCurveTo(d[0].x,d[0].y,d[1].x,d[1].y,d[2].x,d[2].y)}return t&&c.closePath(),o._fillStroke(c,a),!0}return o._setPath?(o._setPath(a,(s=a._parts)!=null&&s.length?_a(e,t,n):"M0 0"),!0):!1}class ni extends v.Polyline{constructor(){super(...arguments);p(this,"_nosCurva",null)}definirCurva(e){this._nosCurva=e}_updatePath(){ai(this,!1)||v.Polyline.prototype._updatePath.call(this)}}class ri extends v.Polygon{constructor(){super(...arguments);p(this,"_nosCurva",null)}definirCurva(e){this._nosCurva=e}_updatePath(){ai(this,!0)||v.Polygon.prototype._updatePath.call(this)}}function Kt(a){return a.tipo==="LineString"?a.curva&&a.curva.length>=2&&!(a.partes&&a.partes.length>1)?a.curva:null:a.tipo==="Polygon"&&a.curva&&a.curva.length>=3&&a.aneis.length===1?a.curva:null}function si(a,t){const e=Kt(a);if(!e)return null;const o=a.tipo==="Polygon"?new ri(a.aneis[0],t):new ni(a.coordenadas,t);return o.definirCurva(e),o}function Da(a,t){a.definirCurva(Kt(t)),a.setLatLngs(t.tipo==="Polygon"?t.aneis[0]:t.coordenadas)}const kt=55,ci=17,li=8;function Jt(a,t){return t<ci&&a>li}function di(a){let t=0,e=0;for(const o of a)t+=o.coordenada[0],e+=o.coordenada[1];return[t/a.length,e/a.length]}function $a(a,t,e){if(!Jt(a.length,t))return{clusters:[],isolados:a};const o=new Map;for(const r of a){const{x:s,y:c}=e(r.coordenada),l=`${t}:${Math.floor(s/kt)}:${Math.floor(c/kt)}`,d=o.get(l);d?d.push(r):o.set(l,[r])}const i=[],n=[];for(const[r,s]of o)s.length===1?n.push(s[0]):i.push({chave:r,coordenada:di(s),membros:s});return{clusters:i,isolados:n}}class hi{constructor(t,e){p(this,"celulas",new Map);p(this,"celulaDe",new Map);p(this,"multiplas",new Set);this.zoom=t,this.projetar=e}get total(){return this.celulaDe.size}chaveDoPonto(t){return this.celulaDe.get(t)}celula(t){return this.celulas.get(t)}*celulasAgrupadas(){for(const t of this.multiplas){const e=this.celulas.get(t);e&&(yield[t,e])}}emCluster(t){var o;const e=this.celulaDe.get(t);return e!==void 0&&(((o=this.celulas.get(e))==null?void 0:o.membros.size)??0)>=2}inserir(t){this.remover(t.id);const{x:e,y:o}=this.projetar(t.coordenada),i=`${this.zoom}:${Math.floor(e/kt)}:${Math.floor(o/kt)}`;let n=this.celulas.get(i);return n||(n={membros:new Map,somaLat:0,somaLon:0},this.celulas.set(i,n)),n.membros.set(t.id,t),n.somaLat+=t.coordenada[0],n.somaLon+=t.coordenada[1],n.membros.size>=2&&this.multiplas.add(i),this.celulaDe.set(t.id,i),i}remover(t){const e=this.celulaDe.get(t);if(e===void 0)return;this.celulaDe.delete(t);const o=this.celulas.get(e),i=o==null?void 0:o.membros.get(t);return o&&i&&(o.membros.delete(t),o.somaLat-=i.coordenada[0],o.somaLon-=i.coordenada[1],o.membros.size<2&&this.multiplas.delete(e),o.membros.size===0&&this.celulas.delete(e)),e}}const Rt={tower:'<path d="M12 2 L8 22 M12 2 L16 22 M9.5 12 H14.5 M8.7 17 H15.3 M12 2 L9.5 12 L14.5 12 Z" />',tree:'<path d="M12 22 V14 M12 3 L5 14 H19 Z" />',warning:'<path d="M12 3 L22 20 H2 Z M12 9 V14 M12 17 V17.5" />',water:'<path d="M12 3 C12 3 5 11 5 15.5 A7 7 0 0 0 19 15.5 C19 11 12 3 12 3 Z" />',boundary:'<path d="M12 2 L22 12 L12 22 L2 12 Z" />'},he="#38bdf8",qa=/^(#[0-9a-f]{3,8}|(rgb|hsl)a?\([0-9.,%\s\/-]+\)|[a-z]{3,20})$/i;function Z(a,t){return a&&qa.test(a.trim())?a.trim():t}const ft="#38bdf8",Fa=150,Na=100,Me=300,ho=.75,Oa=.3,ue=typeof requestAnimationFrame=="function"?a=>{requestAnimationFrame(a)}:a=>{setTimeout(a,16)};class ui{constructor(){p(this,"estados",new WeakMap);p(this,"selecionadas",new WeakMap);p(this,"tokenLote",new WeakMap)}render(t,e,o){const i=v.layerGroup();return this.sincronizar(t,i,e,o,!0),i}update(t,e,o,i,n){if(o.dados===void 0&&o.estilo===void 0&&o.interativo===void 0&&o.bloqueada===void 0)return;const r=o.estilo!==void 0||o.interativo!==void 0||o.bloqueada!==void 0;this.sincronizar(t,e,n,i,r)}destroy(t,e){const o=this.estados.get(t);o&&(o.vivo=!1,e.off("moveend zoomend",o.aoMover)),t.clearLayers(),this.estados.delete(t),this.tokenLote.set(t,(this.tokenLote.get(t)??0)+1),e.hasLayer(t)&&e.removeLayer(t)}reavaliarVersoes(t){const e=this.estados.get(t);e&&(e.revisao++,e.revisaoBase++,this.reconciliar(t,e,!1,null))}feicaoVisivel(t,e){const o=this.estados.get(t),i=o==null?void 0:o.context.regraVersoes;return!o||!i||i.visivel(e,o.oficiais)}consultarProximas(t,e){const o=this.estados.get(t);if(!o)return[];const i=[];for(const n of o.indice.consultar(e)){const r=o.loja.get(n);r&&!r.oculta&&i.push(r)}return i}previsualizar(t,e){var r;const o=this.estados.get(t),i=o==null?void 0:o.entradas.get(e.id);if(!o||!i)return;const n=o.map._loaded?o.map.getZoom():0;this.remendar(i.layer,this.paraDesenho(e,n),o.layerDef,o.interativo,!!((r=this.selecionadas.get(o.layerDef))!=null&&r.has(e.id)))}estatisticas(t){const e=this.estados.get(t);return e?{total:e.loja.size,materializadas:e.entradas.size,clusters:e.clusters.size}:null}feicoesDe(t){const e=t.dados,o=Array.isArray(e)?e:e==null?void 0:e.feicoes;return Array.isArray(o)?o:[]}obterEstado(t,e,o,i){let n=this.estados.get(t);if(!n){const r={layerDef:e,interativo:!1,map:o,context:i,loja:new Map,indice:new Ko,revisao:0,revisaoBase:0,listaSincronizada:null,oficiais:new Set,contOficiais:new Map,nPrevias:0,entradas:new Map,clusters:new Map,nPontos:0,nPontosRev:-1,agrupador:null,agrupadorRev:-1,culling:!1,agendado:!1,vivo:!0,aoMover:()=>{r.agendado||!r.vivo||(r.agendado=!0,ue(()=>{r.agendado=!1,r.vivo&&this.reconciliar(t,r,!1,null)}))}};o.on("moveend zoomend",r.aoMover),this.estados.set(t,r),n=r}return n.layerDef=e,n.map=o,n.context=i,n.interativo=e.interativo&&!e.bloqueada,n}sincronizar(t,e,o,i,n){var m;const r=this.obterEstado(e,t,o,i),s=this.feicoesDe(t),c=(m=t.dados)==null?void 0:m.delta;if(!n&&this.aplicarDelta(e,r,s,c))return;const l=s.filter(f=>!f.excluida),d=new Set,h=new Set;for(const f of l)h.add(f.id),r.loja.get(f.id)!==f&&d.add(f.id);const u=[...r.loja.keys()].filter(f=>!h.has(f));if(d.size>0||u.length>0){if(r.revisao++,r.revisaoBase++,r.loja.size===0||d.size+u.length>l.length*Oa)r.indice.construir(l);else{for(const f of l)d.has(f.id)&&r.indice.atualizar(f);for(const f of u)r.indice.remover(f)}r.loja=new Map(l.map(f=>[f.id,f])),this.recontarOficiais(r,l)}r.listaSincronizada=s;const g=this.selecionadas.get(t);if(g)for(const f of[...g])h.has(f)||g.delete(f);this.reconciliar(e,r,n,d)}recontarOficiais(t,e){t.contOficiais=new Map,t.nPrevias=0;for(const o of e){if(o.excluida)continue;if(Y(o)!=="oficial"){t.nPrevias++;continue}const i=at(o);t.contOficiais.set(i,(t.contOficiais.get(i)??0)+1)}t.oficiais=new Set(t.contOficiais.keys())}aplicarDelta(t,e,o,i){if(!i||i.base!==e.listaSincronizada)return!1;const{loja:n}=e,r=this.selecionadas.get(e.layerDef),s=m=>m.geometria.tipo==="Point"&&this.desenhavel(e,m),c=new Map,l=(m,f)=>{if(!m||m.excluida||Y(m)!=="oficial")return;const b=at(m);c.has(b)||c.set(b,e.oficiais.has(b));const A=(e.contOficiais.get(b)??0)+f;A<=0?(e.contOficiais.delete(b),e.oficiais.delete(b)):(e.contOficiais.set(b,A),e.oficiais.add(b))},d=[],h=[],u=m=>{const f=n.get(m);f&&(Y(f)==="previa"&&e.nPrevias--,l(f,-1),s(f)&&e.nPontos--,n.delete(m),e.indice.remover(m),r==null||r.delete(m),h.push(m))};for(const m of i.removidas)u(m);for(const m of i.mudadas){if(m.excluida){u(m.id);continue}const f=n.get(m.id);Y(m)==="previa"&&e.nPrevias++,f&&(Y(f)==="previa"&&e.nPrevias--,l(f,-1),s(f)&&e.nPontos--),n.set(m.id,m),e.indice.atualizar(m),l(m,1),s(m)&&e.nPontos++,d.push(m.id)}let g=!1;if(e.nPrevias>0)for(const[m,f]of c)f!==e.oficiais.has(m)&&(g=!0);return e.listaSincronizada=o,e.revisao++,g&&e.revisaoBase++,this.reconciliarParcial(t,e,d,h,g),!0}ressimplificar(t,e){return t.zoomDesenho===e||Re(t.feicao.geometria)<Ne?!1:e<Yt||t.zoomDesenho<Yt}paraDesenho(t,e){const o=ti(t.geometria,e);return o===t.geometria?t:{...t,geometria:o}}desenhavel(t,e){if(e.oculta)return!1;const o=t.context.regraVersoes;return!o||o.visivel(e,t.oficiais)}estaCarregado(t){return!!t._loaded}caixaDe(t){return{minLon:t.getWest(),minLat:t.getSouth(),maxLon:t.getEast(),maxLat:t.getNorth()}}materializar(t,e,o,i,n,r){const s=this.formaDe(o),c=e.entradas.get(o.id),l=this.paraDesenho(o,i);if(c&&c.forma===s){(r||c.feicao!==o||this.ressimplificar(c,i))&&(this.remendar(c.layer,l,e.layerDef,e.interativo,n),c.feicao=o,c.zoomDesenho=i);return}c&&t.removeLayer(c.layer);const d=this.criar(l,e.layerDef,e.map,e.interativo,n);this.ligarEventos(d,o.id,e.layerDef,e.entradas,e.context),this.aplicarRotulo(d,o),t.addLayer(d),e.entradas.set(o.id,{layer:d,forma:s,feicao:o,zoomDesenho:i})}tirarEntrada(t,e,o){const i=e.entradas.get(o);i&&(t.removeLayer(i.layer),e.entradas.delete(o))}colocarCluster(t,e,o,i){const n=e.clusters.get(o);if((n==null?void 0:n.assinatura)===i.assinatura)return;n&&t.removeLayer(n.marker);const r=this.criarMarcadorCluster(i.coordenada,i.total,()=>{var s,c;return Array.from(((c=(s=e.agrupador)==null?void 0:s.celula(o))==null?void 0:c.membros.values())??[])},e);t.addLayer(r),e.clusters.set(o,{marker:r,assinatura:i.assinatura})}tirarCluster(t,e,o){const i=e.clusters.get(o);i&&(t.removeLayer(i.marker),e.clusters.delete(o))}agrupadorAtivo(t,e){const o=r=>this.desenhavel(t,r);if(t.nPontosRev!==t.revisaoBase){let r=0;for(const s of t.loja.values())s.geometria.tipo==="Point"&&o(s)&&r++;t.nPontos=r,t.nPontosRev=t.revisaoBase}if(!Jt(t.nPontos,e))return t.agrupador=null,null;const i=t.agrupador;if(i&&i.zoom===e&&t.agrupadorRev===t.revisaoBase)return i;const n=new hi(e,r=>t.map.project(v.latLng(r[0],r[1]),e));for(const r of t.loja.values())r.geometria.tipo==="Point"&&o(r)&&n.inserir({id:r.id,coordenada:r.geometria.coordenada});return t.agrupador=n,t.agrupadorRev=t.revisaoBase,n}reconciliar(t,e,o,i){var A;const{map:n,layerDef:r,loja:s}=e,c=this.selecionadas.get(r),l=this.estaCarregado(n),d=l?n.getZoom():0,h=l&&s.size>Me?n.getBounds().pad(ho):null,u=h?this.caixaDe(h):null;e.culling=h!==null;const g=u?e.indice.consultar(u):s.keys(),m=new Set(g);if(c)for(const M of c)s.has(M)&&m.add(M);for(const M of[...m]){const C=s.get(M);C&&!this.desenhavel(e,C)&&m.delete(M)}const f=new Map,b=l?this.agrupadorAtivo(e,d):null;if(b||(e.agrupador=null),b){for(const C of[...m])b.emCluster(C)&&m.delete(C);const M=new Map;if(c)for(const C of c){const k=b.chaveDoPonto(C),P=k===void 0||(A=b.celula(k))==null?void 0:A.membros.get(C);if(k!==void 0&&P){const y=M.get(k);y?y.push(P):M.set(k,[P])}}for(const[C,k]of b.celulasAgrupadas()){const P=M.get(C);if(P)for(const E of P)m.add(E.id);const y=k.membros.size,x=y-((P==null?void 0:P.length)??0);if(x===1)for(const E of k.membros.values()){if(c!=null&&c.has(E.id))continue;const z=e.indice.caixaDe(E.id);(!u||z&&mt(z,u))&&m.add(E.id);break}if(!(h&&!h.contains([k.somaLat/y,k.somaLon/y]))&&x>=2){let E=k.somaLat,z=k.somaLon;if(P)for(const w of P)E-=w.coordenada[0],z-=w.coordenada[1];const L=[E/x,z/x];f.set(C,{coordenada:L,total:y,assinatura:`${C}:${y}:${x}:${L[0].toFixed(7)}:${L[1].toFixed(7)}`})}}}for(const M of m){const C=s.get(M);C&&this.materializar(t,e,C,d,!!(c!=null&&c.has(M)),o||!!(i!=null&&i.has(M)))}for(const M of[...e.entradas.keys()])m.has(M)&&s.has(M)||this.tirarEntrada(t,e,M);for(const[M,C]of f)this.colocarCluster(t,e,M,C);for(const M of[...e.clusters.keys()])f.has(M)||this.tirarCluster(t,e,M)}reconciliarParcial(t,e,o,i,n){const{map:r,layerDef:s,loja:c}=e,l=this.estaCarregado(r),d=l?r.getZoom():0,h=l&&c.size>Me,u=l&&Jt(e.nPontos,d),g=e.agrupador;if(n||h!==e.culling||u!==(g!==null)||g!==null&&(g.zoom!==d||e.agrupadorRev!==e.revisaoBase)){this.reconciliar(t,e,!1,new Set(o));return}const m=this.selecionadas.get(s),f=y=>this.desenhavel(e,y),b=h?r.getBounds().pad(ho):null,A=b?this.caixaDe(b):null,M=(y,x)=>{const E=c.get(y);if(!E||!f(E)){this.tirarEntrada(t,e,y);return}const z=!!(m!=null&&m.has(y));if(!z&&A){const L=e.indice.caixaDe(y);if(!L||!mt(L,A)){this.tirarEntrada(t,e,y);return}}this.materializar(t,e,E,d,z,x)},C=new Set,k=[];for(const y of i){this.tirarEntrada(t,e,y);const x=g==null?void 0:g.remover(y);x!==void 0&&C.add(x)}for(const y of o){const x=c.get(y);if(!x)continue;const E=g==null?void 0:g.remover(y);E!==void 0&&C.add(E),g&&x.geometria.tipo==="Point"&&f(x)?C.add(g.inserir({id:y,coordenada:x.geometria.coordenada})):k.push(y)}for(const y of k)M(y,!0);if(!g)return;const P=new Set(o);for(const y of C){const x=g.celula(y);if(!x||x.membros.size<2){if(this.tirarCluster(t,e,y),x)for(const T of x.membros.keys())M(T,P.has(T));continue}const E=x.membros.size;let z=x.somaLat,L=x.somaLon,w=0;for(const T of x.membros.values())m!=null&&m.has(T.id)&&(w++,z-=T.coordenada[0],L-=T.coordenada[1]);const I=E-w;for(const T of x.membros.values())m!=null&&m.has(T.id)||I===1?M(T.id,P.has(T.id)):this.tirarEntrada(t,e,T.id);const _=[x.somaLat/E,x.somaLon/E];if(b&&!b.contains(_)||I<2){this.tirarCluster(t,e,y);continue}const N=[z/I,L/I];this.colocarCluster(t,e,y,{coordenada:N,total:E,assinatura:`${y}:${E}:${I}:${N[0].toFixed(7)}:${N[1].toFixed(7)}`})}}criarMarcadorCluster(t,e,o,i){const n=e<10?30:e<100?38:46,r=Z(i.layerDef.estilo.corPrimaria,he),s=v.divIcon({className:"custom-leaflet-marker cad-feicao-cluster",iconSize:[n,n],html:`<div style="width:${n}px;height:${n}px;border-radius:50%;background:${r};opacity:.9;border:2px solid rgba(255,255,255,.85);display:flex;align-items:center;justify-content:center;color:#fff;font:700 12px sans-serif;text-shadow:0 0 2px #000">${e}</div>`}),c=v.marker(t,{icon:s,pane:nt(i.map,i.layerDef.id,"ponto"),keyboard:!1});return c.bindTooltip(`${e} feições agrupadas`,{direction:"top"}),c.on("click",()=>{const l=o();l.length>0&&i.map.fitBounds(v.latLngBounds(l.map(d=>d.coordenada)),{padding:[60,60],maxZoom:18})}),c}aplicarSelecao(t,e){const o=this.estados.get(t);if(!o)return;const i=this.selecionadas.get(o.layerDef)??new Set,n=new Set(e);this.selecionadas.set(o.layerDef,n);const r=[];for(const d of n)i.has(d)||r.push(d);for(const d of i)n.has(d)||r.push(d);if(r.length===0)return;const s=o.entradas,c=d=>{const h=s.get(d);if(!h)return;const u=n.has(d);this.remendar(h.layer,this.paraDesenho(h.feicao,h.zoomDesenho),o.layerDef,o.interativo,u),u&&"bringToFront"in h.layer&&h.layer.bringToFront()},l=(this.tokenLote.get(t)??0)+1;if(this.tokenLote.set(t,l),r.length<=Fa)r.forEach(c);else{const h=!!o.map._loaded?o.map.getBounds():null,u=b=>{var M;const A=(M=s.get(b))==null?void 0:M.layer;return h?A!=null&&A.getBounds?h.intersects(A.getBounds()):A!=null&&A.getLatLng?h.contains(A.getLatLng()):!0:!0},g=r.filter(u),m=r.filter(b=>!u(b));g.forEach(c);const f=()=>{this.tokenLote.get(t)===l&&(m.splice(0,Na).forEach(c),m.length>0&&ue(f))};m.length>0&&ue(f)}this.reconciliar(t,o,!1,null)}formaDe(t){var o;const e=t.geometria;return e.tipo==="Point"?`Point:${(o=t.estilo)!=null&&o.icone&&Rt[t.estilo.icone]?t.estilo.icone:""}`:Kt(e)?`${e.tipo}:curva`:e.tipo}paneDe(t){switch(t.geometria.tipo){case"Polygon":case"Circle":return"poligono";case"LineString":return"linha";case"Point":return"ponto";default:return"texto"}}estiloVetor(t,e,o,i=!1){const n=t.estilo??{},r=Z(n.corTraco??e.estilo.corPrimaria,he),s=t.geometria.tipo==="Polygon"||t.geometria.tipo==="Circle",c=t.geometria.tipo==="Point",l=c&&Z(n.corContorno,"")||r,d=c&&typeof n.espessuraContorno=="number"&&Number.isFinite(n.espessuraContorno)&&n.espessuraContorno>=0?n.espessuraContorno:void 0,h=d??n.espessuraTraco??e.estilo.espessuraLinha??2,u=n.opacidadePreenchimento??(s?.2:.85);return{color:i?ft:l,stroke:!(d===0&&!i),weight:i?h+2:h,dashArray:n.dashArray??(Y(t)==="previa"?"6 4":e.estilo.dashArray),fill:s||t.geometria.tipo==="Point",fillColor:Z(n.corPreenchimento,r),fillOpacity:i?Math.min(1,u+.18):u,lineJoin:"round",interactive:o}}criar(t,e,o,i,n){var d,h;const r=nt(o,e.id,this.paneDe(t)),s=t.geometria,c=this.estiloVetor(t,e,i,n),l=si(s,{...c,pane:r});if(l)return l;switch(s.tipo){case"Polygon":return v.polygon(s.aneis.length===1?s.aneis[0]:s.aneis,{...c,pane:r});case"Circle":return v.circle(s.centro,{...c,radius:s.raioMetros,pane:r});case"LineString":return v.polyline(s.partes&&s.partes.length>1?j(s):s.coordenadas,{...c,pane:r});case"Point":{const u=(d=t.estilo)==null?void 0:d.icone;return u&&Rt[u]?v.marker(s.coordenada,{icon:this.iconeSvg(t,e,n),pane:r,interactive:i}):v.circleMarker(s.coordenada,{...c,radius:(((h=t.estilo)==null?void 0:h.tamanhoIcone)??e.estilo.tamanhoMarcador??8)/2,pane:r})}default:return v.marker(s.coordenada,{icon:this.iconeTexto(t,e,n),pane:r,interactive:i,draggable:i&&!t.bloqueada})}}remendar(t,e,o,i,n){var c,l,d;const r=e.geometria,s=this.estiloVetor(e,o,i,n);(t instanceof ni||t instanceof ri)&&Kt(r)?(Da(t,r),t.setStyle(s)):r.tipo==="Polygon"?(t.setLatLngs(r.aneis.length===1?r.aneis[0]:r.aneis),t.setStyle(s)):r.tipo==="LineString"?(t.setLatLngs(r.partes&&r.partes.length>1?j(r):r.coordenadas),t.setStyle(s)):r.tipo==="Circle"?(t.setLatLng(r.centro),t.setRadius(r.raioMetros),t.setStyle(s)):r.tipo==="Point"&&t instanceof v.CircleMarker?(t.setLatLng(r.coordenada),t.setRadius((((c=e.estilo)==null?void 0:c.tamanhoIcone)??o.estilo.tamanhoMarcador??8)/2),t.setStyle(s)):t instanceof v.Marker&&(t.setLatLng(r.tipo==="Point"||r.tipo==="Text"?r.coordenada:t.getLatLng()),t.setIcon(r.tipo==="Text"?this.iconeTexto(e,o,n):this.iconeSvg(e,o,n)),r.tipo==="Text"&&(i&&!e.bloqueada?(l=t.dragging)==null||l.enable():(d=t.dragging)==null||d.disable())),this.aplicarRotulo(t,e)}iconeSvg(t,e,o=!1){const i=t.estilo??{},n=i.tamanhoIcone??e.estilo.tamanhoMarcador,r=typeof n=="number"&&Number.isFinite(n)&&n>0?n:22,s=o?ft:Z(i.corTraco??i.corPreenchimento??e.estilo.corPrimaria,he),c=Number.isFinite(i.rotacaoIcone)?i.rotacaoIcone:0,l=Rt[i.icone??""]??"";return v.divIcon({className:`custom-leaflet-marker${o?" cad-feicao-selecionada":""}`,iconSize:[r,r],html:`<svg width="${r}" height="${r}" viewBox="0 0 24 24" fill="${s}" fill-opacity="0.25" stroke="${s}" stroke-width="1.6" stroke-linejoin="round" stroke-linecap="round" style="transform:rotate(${c}deg);overflow:visible;display:block${o?`;filter:drop-shadow(0 0 3px ${ft})`:""}">${l}</svg>`})}iconeTexto(t,e,o=!1){const i=t.estilo??{},n=t.geometria.tipo==="Text"?t.geometria.texto:"",r=o?ft:Z(i.corTraco??e.estilo.corPrimaria,"#ffffff"),s=Number.isFinite(i.tamanhoFonte)?i.tamanhoFonte:13,l=`display:inline-block;white-space:nowrap;transform:translate(-50%,-50%) rotate(${Number.isFinite(i.rotacaoIcone)?i.rotacaoIcone:0}deg);color:${r};font-size:${s}px;font-weight:600;`,d=Z(i.corFundo,"");if(d){const u=Z(i.corBorda,""),g=typeof i.opacidadeFundo=="number"&&Number.isFinite(i.opacidadeFundo)?Math.min(1,Math.max(0,i.opacidadeFundo)):.85,m=typeof i.raioBorda=="number"&&Number.isFinite(i.raioBorda)?Math.min(50,Math.max(0,i.raioBorda)):4,f=o?`1px solid ${ft}`:u?`1px solid ${u}`:"none";return v.divIcon({className:`custom-leaflet-marker cad-feicao-texto cad-feicao-selo${o?" cad-feicao-selecionada":""}`,iconSize:void 0,html:`<span style="${l}position:relative;padding:2px 6px;border-radius:${m}px;border:${f}"><span style="position:absolute;top:0;right:0;bottom:0;left:0;border-radius:inherit;background:${d};opacity:${g}"></span><span style="position:relative">${S.escapeHtml(n)}</span></span>`})}const h=i.halo?"text-shadow:-1px -1px 0 #000,1px -1px 0 #000,-1px 1px 0 #000,1px 1px 0 #000;":"";return v.divIcon({className:`custom-leaflet-marker cad-feicao-texto${o?" cad-feicao-selecionada":""}`,iconSize:void 0,html:`<span style="${l}${h}">${S.escapeHtml(n)}</span>`})}aplicarRotulo(t,e){const o=e.estilo;if(!(o!=null&&o.mostrarRotulo)||e.geometria.tipo==="Text"){t.unbindTooltip();return}const i=Yo(e,o.campoRotulo);if(!i){t.unbindTooltip();return}const n=document.createElement("span");n.textContent=i,t.getTooltip()?t.setTooltipContent(n):t.bindTooltip(n,{permanent:!0,direction:"center",className:"cad-feicao-rotulo",interactive:!1})}ligarEventos(t,e,o,i,n){t.on("click",r=>{var l;const s=i.get(e);if(!s)return;const c=r==null?void 0:r.originalEvent;(l=n.onLayerAction)==null||l.call(n,"feicao-clique",{camadaId:o.id,feicao:s.feicao,aditivo:!!(c&&(c.ctrlKey||c.metaKey||c.shiftKey))})}),t instanceof v.Marker&&t.on("dragend",()=>{var l;const r=i.get(e);if(!r||r.feicao.geometria.tipo!=="Text")return;const{lat:s,lng:c}=t.getLatLng();r.feicao={...r.feicao,geometria:{...r.feicao.geometria,coordenada:[s,c]}},(l=n.onLayerAction)==null||l.call(n,"feicao-movida",{camadaId:o.id,feicao:r.feicao})})}}O.register("tile",new Bo);O.register("wms",new Ho);O.register("vetorial-linhas",new Go);O.register("vetorial-pontos",new Uo);O.register("vetorial-poligonos",new Wo);O.register("grid",new Xo);O.register("feicoes",new ui);const Ae=[{id:"satelite",nome:"Satélite Google Híbrido",categoria:"base",tipo:"tile",visivel:!0,opacidade:1,zIndex:200,interativo:!1,bloqueada:!1,estilo:{scaleMode:"screen"}},{id:"sigef",nome:"Acervo Fundiário SIGEF (INCRA)",categoria:"wms",tipo:"wms",visivel:!0,opacidade:.85,zIndex:390,interativo:!0,bloqueada:!1,estilo:{scaleMode:"screen"}},{id:"homologados",nome:"Poligonal Homologada (Banco)",categoria:"referencia",tipo:"vetorial-linhas",visivel:!0,opacidade:.9,zIndex:420,interativo:!0,bloqueada:!1,estilo:{corPrimaria:"#f59e0b",espessuraLinha:1,dashArray:"6, 8",scaleMode:"screen"}},{id:"homologados-pontos",nome:"Marcos Homologados (Banco)",categoria:"referencia",tipo:"vetorial-pontos",visivel:!0,opacidade:1,zIndex:430,interativo:!0,bloqueada:!1,estilo:{tamanhoMarcador:8,estiloMarcador:"circle",scaleMode:"screen"}},{id:"perimetro",nome:"Divisas e Poligonal do Imóvel",categoria:"levantamento",tipo:"vetorial-linhas",visivel:!0,opacidade:1,zIndex:520,interativo:!0,bloqueada:!1,estilo:{corPrimaria:"#00f5a0",espessuraLinha:1,scaleMode:"screen",dimensaoMetros:.3}},{id:"vizinhos",nome:"Imóveis Confrontantes (WKT/CSV)",categoria:"referencia",tipo:"vetorial-poligonos",visivel:!0,opacidade:.8,zIndex:440,interativo:!0,bloqueada:!1,estilo:{corPrimaria:"#a855f7",espessuraLinha:1,dashArray:"4, 6",scaleMode:"screen"}},{id:"vertices",nome:"Vértices e Marcos do Levantamento",categoria:"levantamento",tipo:"vetorial-pontos",visivel:!0,opacidade:1,zIndex:650,interativo:!0,bloqueada:!1,estilo:{tamanhoMarcador:8,scaleMode:"screen",dimensaoMetros:.25}},{id:"grade",nome:"Grade de Coordenadas UTM",categoria:"referencia",tipo:"grid",visivel:!0,opacidade:.5,zIndex:700,interativo:!1,bloqueada:!1,estilo:{corPrimaria:"rgba(0, 245, 160, 0.18)",espessuraLinha:.6,scaleMode:"screen"}}],Ra=new Set(["tile","wms","grid"]);class pi{constructor(t){p(this,"layers",[]);p(this,"layerInstances",new Map);p(this,"map",null);p(this,"context",null);p(this,"listeners",[]);p(this,"renderPendente",!1);this.layers=(t||Ae).map(e=>({...e,estilo:{...e.estilo}}))}descartarCamadasPadrao(){if(this.map)return;const t=new Set(Ae.map(e=>e.id));this.layers=this.layers.filter(e=>!t.has(e.id)||e.tipo==="feicoes")}attachMap(t,e){this.map=t,this.context=e,this.ensurePanes(),this.renderAllLayers()}ensurePanes(){this.map&&this.layers.forEach(t=>{const e=`pane-${t.id}`;let o=this.map.getPane(e);o||(o=this.map.createPane(e)),o&&(o.style.zIndex=String(t.zIndex),o.style.pointerEvents=t.interativo&&!t.bloqueada&&t.visivel?"auto":"none")})}renderAllLayers(t=!1){this.renderPendente=!1,!(!this.map||!this.context)&&(this.layers.forEach(e=>{if(!(t&&Ra.has(e.tipo)&&e.visivel&&this.layerInstances.has(e.id))){if(this.layerInstances.has(e.id)){const o=this.layerInstances.get(e.id),i=O.get(e.tipo);i&&i.destroy(o,this.map),this.layerInstances.delete(e.id)}if(e.visivel){const o=O.get(e.tipo);if(o){const i=o.render(e,this.map,this.context);i&&(i.addTo(this.map),this.layerInstances.set(e.id,i))}}}}),this.notifyChange())}flushRender(){this.renderPendente&&this.renderAllLayers(!0)}agendarRender(){this.renderPendente||(this.renderPendente=!0,queueMicrotask(()=>this.flushRender()))}setLayerVisibility(t,e){this.flushRender();const o=this.layers.find(r=>r.id===t);if(!o||o.visivel===e||(o.visivel=e,!this.map||!this.context))return;const i=`pane-${o.id}`,n=this.map.getPane(i);if(n&&(n.style.display=e?"":"none",n.style.pointerEvents=o.visivel&&o.interativo&&!o.bloqueada?"auto":"none"),e){if(!this.layerInstances.has(t)){const r=O.get(o.tipo);if(r){const s=r.render(o,this.map,this.context);s&&(s.addTo(this.map),this.layerInstances.set(t,s))}}}else if(this.layerInstances.has(t)){const r=this.layerInstances.get(t),s=O.get(o.tipo);s&&s.destroy(r,this.map),this.layerInstances.delete(t)}this.notifyChange()}setLayerOpacity(t,e){this.flushRender();const o=this.layers.find(n=>n.id===t);if(!o)return;if(o.opacidade=Math.max(0,Math.min(1,e)),this.map){const n=this.map.getPane(`pane-${t}`);n&&(n.style.opacity=String(o.opacidade))}const i=this.layerInstances.get(t);if(i&&this.map&&this.context){const n=O.get(o.tipo);n&&n.update(o,i,{opacidade:o.opacidade},this.context,this.map)}this.notifyChange()}setLayerZIndex(t,e){const o=this.layers.find(i=>i.id===t);if(o){if(o.zIndex=e,this.map){const i=this.map.getPane(`pane-${t}`);i&&(i.style.zIndex=String(e))}this.notifyChange()}}setLayerBlocked(t,e){const o=this.layers.find(i=>i.id===t);if(o){if(o.bloqueada=e,this.map){const i=this.map.getPane(`pane-${t}`);i&&(i.style.pointerEvents=o.visivel&&o.interativo&&!e?"auto":"none")}this.notifyChange()}}setLayerScaleMode(t,e){this.flushRender();const o=this.layers.find(n=>n.id===t);if(!o)return;o.estilo.scaleMode=e;const i=this.layerInstances.get(t);if(i&&this.map&&this.context){const n=O.get(o.tipo);n&&n.update(o,i,{estilo:o.estilo},this.context,this.map)}this.notifyChange()}setGraphicScale(t){this.context&&(this.context.graphicScale={...this.context.graphicScale,...t},this.agendarRender())}updateContext(t){this.context&&(this.context={...this.context,...t},this.agendarRender())}getLayers(){return[...this.layers]}getActiveSelectableLayers(){return this.layers.filter(t=>t.visivel&&t.interativo&&!t.bloqueada)}isLayerActiveAndSelectable(t){const e=this.layers.find(o=>o.id===t);return!!(e&&e.visivel&&e.interativo&&!e.bloqueada)}exportState(){return this.layers.map(t=>({id:t.id,visivel:t.visivel,opacidade:t.opacidade,zIndex:t.zIndex,bloqueada:t.bloqueada,estilo:{...t.estilo}}))}importState(t){!t||!Array.isArray(t)||(t.forEach(e=>{const o=this.layers.find(i=>i.id===e.id);o&&(e.visivel!==void 0&&(o.visivel=e.visivel),e.opacidade!==void 0&&(o.opacidade=e.opacidade),e.zIndex!==void 0&&(o.zIndex=e.zIndex),e.bloqueada!==void 0&&(o.bloqueada=e.bloqueada),e.estilo&&(o.estilo={...o.estilo,...e.estilo}))}),this.ensurePanes(),this.renderAllLayers())}onChange(t){return this.listeners.push(t),()=>{this.listeners=this.listeners.filter(e=>e!==t)}}notifyChange(){const t=this.getLayers();this.listeners.forEach(e=>{try{e(t)}catch(o){console.error("Erro no listener de camadas:",o)}})}getAllLayerInstances(){return this.flushRender(),Array.from(this.layerInstances.values())}getLayerInstance(t){return this.flushRender(),this.layerInstances.get(t)}getLayer(t){return this.layers.find(e=>e.id===t)}getLayerDef(t){return this.layers.find(e=>e.id===t)}getOrCreateLayer(t,e,o){let i=this.layers.find(n=>n.id===t);return i||(i={id:t,nome:o,categoria:"custom",tipo:e,visivel:!0,opacidade:1,zIndex:600,interativo:!0,bloqueada:!1,estilo:{scaleMode:"screen"}},this.layers.push(i),this.ensurePanes()),i}setLayerData(t,e){this.flushRender();const o=this.layers.find(n=>n.id===t);if(!o)return;o.dados=e;const i=this.layerInstances.get(t);if(i&&this.map&&this.context){const n=O.get(o.tipo);n&&n.update(o,i,{dados:e},this.context,this.map)}else if(o.visivel&&this.map&&this.context){const n=O.get(o.tipo);if(n){const r=n.render(o,this.map,this.context);r&&(r.addTo(this.map),this.layerInstances.set(t,r))}}this.notifyChange()}clearLayers(t){this.flushRender(),(t&&t.length>0?t:Array.from(this.layerInstances.keys())).forEach(o=>{if(this.layerInstances.has(o)){const i=this.layerInstances.get(o),n=this.layers.find(r=>r.id===o);if(n){const r=O.get(n.tipo);r&&r.destroy(i,this.map)}this.layerInstances.delete(o)}}),this.notifyChange()}destroy(){this.renderPendente=!1,this.map&&(this.layerInstances.forEach((t,e)=>{const o=this.layers.find(i=>i.id===e);if(o){const i=O.get(o.tipo);i&&i.destroy(t,this.map)}}),this.layerInstances.clear()),this.listeners=[]}}function fi(a,t){var r,s;if(t==null)return null;const e=String(t).trim(),o=c=>c?(c.lon=c.lng,c):null,n=a.getMarkers().find(c=>{var g,m,f,b;const l=c.pontoId,d=c.elementoId??c.id??((g=c.options)==null?void 0:g.pontoId)??((m=c.options)==null?void 0:m.id),h=(f=c.elemento)==null?void 0:f.nome_vertice,u=(b=c.elemento)==null?void 0:b.codigo_completo;return String(l)===e||String(d)===e||h&&String(h).toLowerCase()===e.toLowerCase()||u&&String(u).toLowerCase()===e.toLowerCase()});if(n&&typeof n.getLatLng=="function")return o(n.getLatLng());if(a.layerManager)for(const c of a.layerManager.getAllLayerInstances()){let l=null;const d=h=>{var m,f,b,A,M;if(l)return;const u=h.pontoId??h.elementoId??h.id??((m=h.options)==null?void 0:m.id)??((f=h.options)==null?void 0:f.pontoId),g=((b=h.elemento)==null?void 0:b.nome)??((A=h.elemento)==null?void 0:A.nome_vertice)??((M=h.options)==null?void 0:M.nome);(String(u)===e||g&&String(g).toLowerCase()===e.toLowerCase())&&(typeof h.getLatLng=="function"?l=h.getLatLng():typeof h.getBounds=="function"&&(l=h.getBounds().getCenter()))};if(d(c),typeof c.eachLayer=="function"&&c.eachLayer(d),l)return o(l)}if(a.context.pontos&&a.context.pontos.length>0){const c=a.context.pontos.find(l=>String(l.id)===e||l.nome_vertice&&String(l.nome_vertice).toLowerCase()===e.toLowerCase());if(c){const l=c.lat??c.latitude??c.y,d=c.lon??c.lng??c.longitude??c.x,h=S.parseCoordenada(l,d);if(h)return o(v.latLng(h.lat,h.lon))}}if(a.context.bancoPontos&&a.context.bancoPontos.length>0){const c=a.context.bancoPontos.find(l=>String(l.id)===e||l.codigo_completo&&String(l.codigo_completo).toLowerCase()===e.toLowerCase()||l.nome_vertice&&String(l.nome_vertice).toLowerCase()===e.toLowerCase());if(c){const l=c.lat??c.latitude??c.y,d=c.lon??c.lng??c.longitude??c.x,h=S.parseCoordenada(l,d);if(h)return o(v.latLng(h.lat,h.lon))}}if(a.context.confrontantes&&a.context.confrontantes.length>0){const c=a.context.confrontantes.find(l=>String(l.id)===e||l.nome&&String(l.nome).toLowerCase()===e.toLowerCase()||l.nome_propriedade&&String(l.nome_propriedade).toLowerCase()===e.toLowerCase());if(c){if(c.pontos&&c.pontos.length>0){let l=0,d=0,h=0;for(const u of c.pontos){const g=u.lat??u.latitude??u.y,m=u.lon??u.lng??u.longitude??u.x,f=S.parseCoordenada(g,m);f&&(l+=f.lat,d+=f.lon,h++)}if(h>0)return o(v.latLng(l/h,d/h))}if(c.poligono_wkt){const l=S.extrairCentroDeWkt(c.poligono_wkt);if(l)return o(v.latLng(l.lat,l.lon))}}}if(a.context.segmentos&&a.context.segmentos.length>0){const c=a.context.segmentos.find(l=>String(l.id)===e||`${l.ponto_inicio_id}-${l.ponto_fim_id}`===e);if(c){const l=(r=a.context.pontos)==null?void 0:r.find(h=>String(h.id)===String(c.ponto_inicio_id)),d=(s=a.context.pontos)==null?void 0:s.find(h=>String(h.id)===String(c.ponto_fim_id));if(l&&d){const h=S.parseCoordenada(l.lat??l.latitude,l.lon??l.longitude),u=S.parseCoordenada(d.lat??d.latitude,d.lon??d.longitude);if(h&&u)return o(v.latLng((h.lat+u.lat)/2,(h.lon+u.lon)/2))}}}if(a.layerManager){for(const c of a.layerManager.getLayers())if(c.dados){if(Array.isArray(c.dados.pontos)){const l=c.dados.pontos.find(d=>String(d.id)===e||d.nome_vertice&&String(d.nome_vertice)===e);if(l){const d=S.parseCoordenada(l.lat,l.lon);if(d)return o(v.latLng(d.lat,d.lon))}}if(Array.isArray(c.dados.poligonos)){const l=c.dados.poligonos.find(d=>String(d.id)===e);if(l){if(l.wkt){const d=S.extrairCentroDeWkt(l.wkt);if(d)return o(v.latLng(d.lat,d.lon))}if(Array.isArray(l.coordenadas)&&l.coordenadas.length>0){let d=0,h=0,u=0;for(const g of l.coordenadas){const m=S.parseCoordenada(g[0],g[1])||S.parseCoordenada(g[1],g[0]);m&&(d+=m.lat,h+=m.lon,u++)}if(u>0)return o(v.latLng(d/u,h/u))}}}}}return null}function Ba(a,t,e,o){var g,m;we(t,a.getMap());const i=a.getMap();if(!i)return;const n=fi(a,e);if(!n){console.warn(`[ui-canvas-cad] Elemento com identificador "${e}" não encontrado para destaque.`);return}const r=(o==null?void 0:o.pan)===!0,s=o==null?void 0:o.zoom;r?s!==void 0?typeof i.flyTo=="function"?i.flyTo(n,s,{animate:!0}):i.setView(n,s,{animate:!0}):typeof i.panTo=="function"?i.panTo(n,{animate:!0}):i.setView(n,i.getZoom(),{animate:!0}):s!==void 0&&i.setZoom(s,{animate:!0});const c=(o==null?void 0:o.cor)||"#00f5a0",l="pane-destaque";let d=i.getPane(l);d||(d=i.createPane(l)),d&&(d.style.zIndex="850",d.style.pointerEvents="none");const h=v.divIcon({className:"cad-destaque-marker-container",html:`
|
|
100
|
-
<div class="cad-pulse-highlight" style="--cad-pulse-cor: ${
|
|
99
|
+
`,{className:"compact-popup",maxWidth:220}),q.on("click",()=>{o.modoSequencial&&q.closePopup(),o.onMarkerClick&&o.onMarkerClick(T.id,!0,T,{lat:$.lat,lon:$.lon})}),q.on("popupopen",Y=>{if(o.modoSequencial){q.closePopup();return}M.bindPopupAcoesEvents(Y.popup,T,o,q)})}q.addTo(t)}})})}update(e,t,o,i,n){o.opacidade!==void 0&&o.estilo===void 0&&o.dados===void 0&&o.interativo===void 0&&o.bloqueada===void 0||(o.opacidade!==void 0||o.estilo!==void 0||o.dados!==void 0||o.interativo!==void 0||o.bloqueada!==void 0)&&(t.clearLayers(),this.rebuildPolygons(e,t,i,n))}destroy(e,t){e.clearLayers(),t.hasLayer(e)&&t.removeLayer(e)}}class Ao{constructor(){f(this,"moveListenerMap",new WeakMap)}render(e,t,o){const i=b.layerGroup(),n=`pane-${e.id}`,r=()=>{if(i.clearLayers(),!e.visivel)return;if(t.getZoom()>20){const c=t.getBounds(),l=c.getSouth(),d=c.getNorth(),h=c.getWest(),u=c.getEast(),g=t.getCenter(),v=8999e-9,p=Math.cos(g.lat*Math.PI/180),y=v/(p>.1?p:1),A=Math.floor((d-l)/v),w=Math.floor((u-h)/y);if(A<200&&w<200){const x=Math.ceil(l/v)*v;for(let C=x;C<=d;C+=v)b.polyline([[C,h],[C,u]],{color:e.estilo.corPrimaria||"rgba(0, 245, 160, 0.18)",weight:e.estilo.espessuraLinha||.6,interactive:!1,pane:n}).addTo(i);const k=Math.ceil(h/y)*y;for(let C=k;C<=u;C+=y)b.polyline([[l,C],[d,C]],{color:e.estilo.corPrimaria||"rgba(0, 245, 160, 0.18)",weight:e.estilo.espessuraLinha||.6,interactive:!1,pane:n}).addTo(i)}}};return r(),t.on("zoomend moveend",r),this.moveListenerMap.set(i,r),i}update(e,t){e.visivel||t.clearLayers()}destroy(e,t){const o=this.moveListenerMap.get(e);o&&(t.off("zoomend moveend",o),this.moveListenerMap.delete(e)),e.clearLayers(),t.hasLayer(e)&&t.removeLayer(e)}}function wo(a,e){var r,s;const t=a._nosCurva,o=a._renderer,i=a._map;if(!t||t.length<2||!o||!i)return!1;const n=c=>i.latLngToLayerPoint([c[0],c[1]]);if(o._ctx&&o._fillStroke){if(!o._drawing||!((r=a._parts)!=null&&r.length))return!0;const c=o._ctx;c.beginPath();for(const l of m.passosDaCurva(t,e)){const d=l.pts.map(n);l.cmd==="M"?c.moveTo(d[0].x,d[0].y):l.cmd==="L"?c.lineTo(d[0].x,d[0].y):c.bezierCurveTo(d[0].x,d[0].y,d[1].x,d[1].y,d[2].x,d[2].y)}return e&&c.closePath(),o._fillStroke(c,a),!0}return o._setPath?(o._setPath(a,(s=a._parts)!=null&&s.length?m.caminhoSvg(t,e,n):"M0 0"),!0):!1}class Eo extends b.Polyline{constructor(){super(...arguments);f(this,"_nosCurva",null)}definirCurva(t){this._nosCurva=t}_updatePath(){wo(this,!1)||b.Polyline.prototype._updatePath.call(this)}}class zo extends b.Polygon{constructor(){super(...arguments);f(this,"_nosCurva",null)}definirCurva(t){this._nosCurva=t}_updatePath(){wo(this,!0)||b.Polygon.prototype._updatePath.call(this)}}function Et(a,e){const t=m.nosDaGeometria(a);if(!t)return null;const o=a.tipo==="Polygon"?new zo(a.aneis[0],e):new Eo(a.coordenadas,e);return o.definirCurva(t),o}function ko(a,e){a.definirCurva(m.nosDaGeometria(e)),a.setLatLngs(e.tipo==="Polygon"?e.aneis[0]:e.coordenadas)}function le(a){const{lat:e,lng:t}=m.metrosPorGrau(a[0]);return{lat0:a[0],lon0:a[1],mLat:e,mLng:Math.max(t,1)}}function ht(a,e){return[(a[1]-e.lon0)*e.mLng,(a[0]-e.lat0)*e.mLat]}function de(a,e){return[e.lat0+a[1]/e.mLat,e.lon0+a[0]/e.mLng]}function zt(a,e){const t=o=>{let i=!1;for(let n=0,r=o.length-1;n<o.length;r=n++){const[s,c]=o[n],[l,d]=o[r];s>a[0]!=l>a[0]&&a[1]<(d-c)*(a[0]-s)/(l-s)+c&&(i=!i)}return i};return!e[0]||!t(e[0])?!1:!e.slice(1).some(t)}function Io(a,e,t,o){const i=e[0]-a[0],n=e[1]-a[1],r=o[0]-t[0],s=o[1]-t[1],c=i*s-n*r;if(Math.abs(c)<1e-12)return null;const l=((t[0]-a[0])*s-(t[1]-a[1])*r)/c,d=((t[0]-a[0])*n-(t[1]-a[1])*i)/c;return l<0||l>1||d<0||d>=1?null:{t:l,u:d}}function je(a){let e=0;for(let t=0;t<a.length;t++){const[o,i]=a[t],[n,r]=a[(t+1)%a.length];e+=o*r-n*i}return Math.abs(e)/2}function Do(a,e){if(a.length<3||e.length<2)return null;const t=le(a[0]),o=a.map(r=>ht(r,t)),i=e.map(r=>ht(r,t)),n=_o(o,i,0);return n&&n.length>=2?n.map(r=>r.map(s=>de(s,t))):null}function _o(a,e,t){if(t>8)return null;const o=a.length,i=[];for(let C=0;C<e.length-1;C++)for(let L=0;L<o;L++){const P=Io(e[C],e[C+1],a[L],a[(L+1)%o]);P&&i.push({tLinha:C+P.t,tAnel:L+P.u,ponto:[e[C][0]+P.t*(e[C+1][0]-e[C][0]),e[C][1]+P.t*(e[C+1][1]-e[C][1])]})}if(i.sort((C,L)=>C.tLinha-L.tLinha),i.length<2)return null;const[n,r]=i,s=[];for(let C=Math.floor(n.tLinha)+1;C<=Math.floor(r.tLinha);C++)C>n.tLinha&&C<r.tLinha&&s.push(e[C]);const c=[n.ponto,...s,r.ponto];let l=n,d=r,h=c;n.tAnel>r.tAnel&&(l=r,d=n,h=[...c].reverse());const u=Math.floor(l.tAnel),g=Math.floor(d.tAnel),v=h.slice(1,-1),p=[l.ponto];for(let C=u+1;C<=g;C++)p.push(a[C%o]);p.push(d.ponto,...[...v].reverse());const y=[d.ponto];for(let C=g+1;C<=u+o;C++)y.push(a[C%o]);y.push(l.ponto,...v);const w=je(a)*1e-9,x=[p,y].filter(C=>C.length>=3&&je(C)>w);if(x.length<2)return null;const k=[r.ponto,...e.slice(Math.floor(r.tLinha)+1)];if(i.length>2&&k.length>=2){const C=[];for(const L of x){const P=_o(L,k,t+1);P?C.push(...P):C.push(L)}return C}return x}function he(a,e){return a.map(t=>ht(t,e))}const Q=(a,e)=>Math.hypot(a[0]-e[0],a[1]-e[1]);function To(a,e=0){if(a.length===0||a.some(n=>n.length<2))return null;const t=le(a[0][0]),o=a.slice(1).map(n=>he(n,t));let i=he(a[0],t);for(;o.length>0;){let n=null;if(o.forEach((d,h)=>{const u=i[0],g=i[i.length-1],v=[{inverter:!1,noFim:!0,d:Q(g,d[0])},{inverter:!0,noFim:!0,d:Q(g,d[d.length-1])},{inverter:!1,noFim:!1,d:Q(u,d[d.length-1])},{inverter:!0,noFim:!1,d:Q(u,d[0])}];for(const p of v)(!n||p.d<n.d)&&(n={idx:h,...p})}),!n||n.d>e)return null;const{idx:r,inverter:s,noFim:c}=n;let l=o.splice(r,1)[0];s&&(l=[...l].reverse()),i=c?[...i,...Q(i[i.length-1],l[0])>0?l:l.slice(1)]:[...l,...Q(l[l.length-1],i[0])>0?i:i.slice(1)]}return i.map(n=>de(n,t))}function Xi(a,e,t,o){const i=Io(a,e,t,o);return!!i&&i.t>1e-9&&i.t<1-1e-9&&i.u>1e-9}function Yi(a,e){for(let t=0;t<a.length;t++)for(let o=0;o<e.length;o++)if(Xi(a[t],a[(t+1)%a.length],e[o],e[(o+1)%e.length]))return!0;return!1}function Fo(a,e,t=0){if(a.length<3||e.length<3)return null;const o=le(a[0]),i=he(a,o),n=he(e,o);if(Yi(i,n))return null;let r={i:0,j:0,d:1/0};for(let d=0;d<i.length;d++)for(let h=0;h<n.length;h++){const u=Q(i[d],n[h]);u<r.d&&(r={i:d,j:h,d:u})}if(r.d>t)return null;const{i:s,j:c}=r,l=[];for(let d=0;d<=i.length;d++)l.push(i[(s+d)%i.length]);for(let d=0;d<=n.length;d++)l.push(n[(c+d)%n.length]);return l.map(d=>de(d,o))}const Gt=16;function jt(a,e,t,o){const i=[];for(let n=0;n<=Gt;n++){const r=t+(o-t)*n/Gt;i.push([a[0]+e*Math.cos(r),a[1]+e*Math.sin(r)])}return i}function Me(a,e){const t=Q(a,e)||1;return[-(e[1]-a[1])/t,(e[0]-a[0])/t]}function et(a,e,t){const o=a.length,i=[],n=o;for(let r=0;r<n;r++){const s=t?a[(r-1+o)%o]:a[Math.max(0,r-1)],c=a[r],l=t?a[(r+1)%o]:a[Math.min(o-1,r+1)],d=r===0&&!t?Me(c,l):Me(s,c),h=r===o-1&&!t?Me(s,c):Me(c,l);let u=d[0]+h[0],g=d[1]+h[1];const v=Math.hypot(u,g);if(v<1e-9){i.push([c[0]+d[0]*e,c[1]+d[1]*e]);continue}u/=v,g/=v;const p=u*d[0]+g*d[1],y=Math.min(1/Math.max(p,.5),2);i.push([c[0]+u*e*y,c[1]+g*e*y])}return i}function Ki(a){let e=0;for(let t=0;t<a.length;t++){const[o,i]=a[t],[n,r]=a[(t+1)%a.length];e+=(n-o)*(r+i)}return e>0}function qo(a,e){if(!Number.isFinite(e)||e===0)return null;if(a.tipo==="Point"||a.tipo==="Text"||a.tipo==="Circle"){const t=a.tipo==="Circle"?a.centro:a.coordenada,o=a.tipo==="Circle"?a.raioMetros+e:e;if(o<=0)return null;const i=le(t),n=64;return Array.from({length:n},(r,s)=>[o*Math.cos(2*Math.PI*s/n),o*Math.sin(2*Math.PI*s/n)]).map(r=>de(r,i))}if(a.tipo==="LineString"){if(e<0||a.coordenadas.length<2||m.ehMultilinha(a))return null;const t=le(a.coordenadas[0]),o=he(a.coordenadas,t),i=et(o,e,!1),n=et([...o].reverse(),e,!1),r=o[o.length-1],s=o[0],c=Math.atan2(r[1]-o[o.length-2][1],r[0]-o[o.length-2][0]),l=Math.atan2(s[1]-o[1][1],s[0]-o[1][0]),d=jt(r,e,c+Math.PI/2,c-Math.PI/2),h=jt(s,e,l+Math.PI/2,l-Math.PI/2);return[...i,...d,...n,...h].map(u=>de(u,t))}if(a.tipo==="Polygon"){const t=a.aneis[0];if(!t||t.length<3)return null;const o=le(t[0]);let i=he(t,o);Ki(i)&&(i=[...i].reverse());const r=et(i,-e,!0);return r.length<3||e<0&&je(r)>=je(i)?null:r.map(s=>de(s,o))}return null}function Oo(a,e,t){const o=i=>{const n=m.metrosPorGrau(i[0]),r=t/n.lat,s=e/Math.max(n.lng,1);return[i[0]+r,i[1]+s]};switch(a.tipo){case"Point":return{tipo:"Point",coordenada:o(a.coordenada)};case"Text":return{...a,coordenada:o(a.coordenada)};case"Circle":return{...a,centro:o(a.centro)};case"LineString":{const i=m.criarLinha(m.partesDaLinha(a).map(n=>n.map(o)));return a.curva?{...i,curva:m.moverNos(a.curva,o)}:i}case"Polygon":{const i={tipo:"Polygon",aneis:a.aneis.map(n=>n.map(o))};return a.curva?{...i,curva:m.moverNos(a.curva,o)}:i}}}const Ut={m:1,km:1e3,ft:.3048,mi:1609.344},Wt={m2:1,ha:1e4,km2:1e6,ac:4046.8564224,alqueire:24200};function Ji(a,e,t){return a*Ut[e]/Ut[t]}function Qi(a,e,t){return a*Wt[e]/Wt[t]}function ea(a,e,t=2){const o=e==="lat"?a<0?"S":"N":a<0?"O":"L",i=Math.abs(a);let n=Math.floor(i),r=Math.floor((i-n)*60),s=Number(((i-n-r/60)*3600).toFixed(t));s>=60&&(s=0,r+=1),r>=60&&(r=0,n+=1);const c=s.toFixed(t).padStart(t?t+3:2,"0");return`${n}°${String(r).padStart(2,"0")}'${c}"${o}`}function ta(a){var u;if(typeof a!="string")return null;const e=a.trim().toUpperCase().replace(",","."),t=(u=/[NSLEOW]$/.exec(e))==null?void 0:u[0],o=e.replace(/[NSLEOW]$/,"").trim(),i=o.match(/-?\d+(?:\.\d+)?/g);if(!i||i.length===0||i.length>3||!/^[-\d\s°'"′″.]+$/.test(o))return null;const[n,r="0",s="0"]=i,c=Math.abs(Number(n)),l=Number(r),d=Number(s);if(l<0||l>=60||d<0||d>=60)return null;let h=c+l/60+d/3600;return(n.startsWith("-")||t==="S"||t==="O"||t==="W")&&(h=-h),h}function oa(a,e){return m.distanciaMetros(a,e)}function De(a,e,t){return{...a,id:e,geometria:t??JSON.parse(JSON.stringify(a.geometria)),estilo:a.estilo?{...a.estilo}:void 0,propriedades:{...a.propriedades}}}const $o=5e3;function Pe(a){return a.tipo==="Polygon"?3:a.tipo==="LineString"?2:1}function No(a,e=!1){if(a.bloqueada||e)return"bloqueada";const t=a.geometria;return t.tipo!=="Point"&&t.tipo!=="LineString"&&t.tipo!=="Polygon"&&t.tipo!=="Circle"?"tipo-nao-suportado":t.tipo==="Polygon"&&t.aneis.length!==1?"poligono-com-furos":m.ehMultilinha(t)?"multiparte":X(t).length>$o?"muitos-vertices":null}function X(a){return a.tipo==="Point"?[a.coordenada]:a.tipo==="LineString"?a.coordenadas:a.tipo==="Polygon"?a.aneis[0]??[]:[]}function Ce(a,e){return a.tipo==="Point"?{tipo:"Point",coordenada:e[0]}:a.tipo==="LineString"?{tipo:"LineString",coordenadas:e}:a.tipo==="Polygon"?{tipo:"Polygon",aneis:[e]}:a}function ia(a,e,t){const o=X(a).slice();return e<0||e>=o.length?a:(o[e]=t,Ce(a,o))}function Ro(a,e,t){if(a.tipo!=="LineString"&&a.tipo!=="Polygon")return a;const o=X(a).slice();return e<0||e>=o.length?a:(o.splice(e+1,0,t),Ce(a,o))}function Bo(a,e){if(a.tipo!=="LineString"&&a.tipo!=="Polygon")return null;const t=X(a);return e<0||e>=t.length||t.length<=Pe(a)?null:Ce(a,t.filter((o,i)=>i!==e))}function kt(a,e){return[(a[0]+e[0])/2,(a[1]+e[1])/2]}function It(a){const e=X(a).length,t=[];if(a.tipo!=="LineString"&&a.tipo!=="Polygon")return t;for(let o=0;o<e-1;o++)t.push([o,o+1]);return a.tipo==="Polygon"&&e>2&&t.push([e-1,0]),t}function W(a){return(a.tipo==="LineString"||a.tipo==="Polygon")&&a.curva&&a.curva.length>=Pe(a)?a.curva:null}const Vo=.5;function Ho(a,e){return[a[0],a[1]+e/Math.max(m.metrosPorGrau(a[0]).lng,1)]}function me(a){var e;return a.tipo==="Circle"?[a.centro,Ho(a.centro,a.raioMetros)]:((e=W(a))==null?void 0:e.map(t=>t.ponto))??X(a)}function ue(a,e){const t=a.tipo==="Polygon",o=m.amostrarCurva(e,t);return t?{tipo:"Polygon",aneis:[o],curva:e}:{tipo:"LineString",coordenadas:o,curva:e}}function Go(a,e){if(a.tipo==="Circle")return e.length<2?a:{...a,centro:e[0],raioMetros:Math.max(Vo,m.distanciaMetros(e[0],e[1]))};const t=W(a);if(!t||t.length!==e.length)return Ce(a,e);const o=t.map((i,n)=>{const r=e[n][0]-i.ponto[0],s=e[n][1]-i.ponto[1],c=d=>[d[0]+r,d[1]+s],l={ponto:e[n]};return i.entrada&&(l.entrada=c(i.entrada)),i.saida&&(l.saida=c(i.saida)),l});return ue(a,o)}function se(a,e,t){return[a[0]+(e[0]-a[0])*t,a[1]+(e[1]-a[1])*t]}function aa(a,e,t){const[o,i]=m.controlesDoSegmento(a,e);let n=.5,r=1/0;for(let s=1;s<64;s++){const c=s/64,l=m.pontoDaCubica(a.ponto,o,i,e.ponto,c),d=(l[0]-t[0])**2+(l[1]-t[1])**2;d<r&&(r=d,n=c)}return n}function _e(a,e,t){const o=W(a);if(!o){const r=X(a);return kt(r[e],r[t])}const[i,n]=m.controlesDoSegmento(o[e],o[t]);return m.pontoDaCubica(o[e].ponto,i,n,o[t].ponto,.5)}function jo(a){const e=W(a);if(!e)return It(a);const t=[];for(let o=0;o<e.length-1;o++)t.push([o,o+1]);return a.tipo==="Polygon"&&e.length>2&&t.push([e.length-1,0]),t}function Uo(a,e,t){const o=W(a);if(!o)return Ro(a,e,t);if(e<0||e>=o.length)return a;const i=(e+1)%o.length,n=o[e],r=o[i],s=n.saida===void 0&&r.entrada===void 0;let c,l=n,d=r;if(s)c={ponto:t};else{const u=aa(n,r,t),[g,v]=m.controlesDoSegmento(n,r),p=se(n.ponto,g,u),y=se(g,v,u),A=se(v,r.ponto,u),w=se(p,y,u),x=se(y,A,u);c={ponto:se(w,x,u),entrada:w,saida:x},l={...n,saida:p},d={...r,entrada:A}}const h=o.slice();return h[e]=l,h[i]=d,h.splice(e+1,0,c),ue(a,h)}function Wo(a,e){const t=W(a);return t?e<0||e>=t.length||t.length<=Pe(a)?null:ue(a,t.filter((o,i)=>i!==e)):Bo(a,e)}function Zo(a){return a.tipo!=="LineString"&&a.tipo!=="Polygon"?null:W(a)??X(a).map(e=>({ponto:[e[0],e[1]]}))}function Xo(a,e,t,o,i=!0){const n=Zo(a);if(!n||e<0||e>=n.length)return a;const r={...n[e],[t]:o};i&&(r[t==="saida"?"entrada":"saida"]=m.espelhoDaAlca(r.ponto,o));const s=n.slice();return s[e]=r,ue(a,s)}function Yo(a,e){const t=Zo(a);if(!t||e<0||e>=t.length)return a;const o=t[e],i=t.slice();if(o.entrada||o.saida)return i[e]={ponto:o.ponto},ue(a,i);const n=a.tipo==="Polygon",r=t.length,s=e>0?t[e-1]:n?t[r-1]:null,c=e<r-1?t[e+1]:n?t[0]:null;if(!s&&!c)return a;const l=o.ponto;let d,h;if(s&&c)d=(c.ponto[0]-s.ponto[0])/6,h=(c.ponto[1]-s.ponto[1])/6;else{const u=(c??s).ponto,g=c?1:-1;d=(u[0]-l[0])/3*g,h=(u[1]-l[1])/3*g}return i[e]={ponto:l,saida:[l[0]+d,l[1]+h],entrada:[l[0]-d,l[1]-h]},ue(a,i)}const Ko=6,tt=(a,e)=>Math.hypot(a.x-e.x,a.y-e.y);function Zt(a,e,t){const o=t.x-e.x,i=t.y-e.y,n=o*o+i*i,r=n===0?0:Math.max(0,Math.min(1,((a.x-e.x)*o+(a.y-e.y)*i)/n));return Math.hypot(a.x-(e.x+r*o),a.y-(e.y+r*i))}function na(a,e){const t=a.geometria;if(t.tipo!=="Polygon")return 0;let o=1/0,i=-1/0,n=1/0,r=-1/0;for(const s of t.aneis[0]){const c=e(s);c.x<o&&(o=c.x),c.x>i&&(i=c.x),c.y<n&&(n=c.y),c.y>r&&(r=c.y)}return(i-o)*(r-n)}function Le(a,e,t,o=Ko){let i=null,n=null,r=null;for(const s of e){if(s.excluida||s.oculta)continue;const c=s.geometria;if(c.tipo==="Point"||c.tipo==="Text"){const l=tt(a,t(c.coordenada));l<=o+2&&(!i||l<i.d)&&(i={f:s,d:l})}else if(c.tipo==="LineString"){let l=1/0;for(const d of m.partesDaLinha(c)){const h=d.map(t);for(let u=1;u<h.length;u++)l=Math.min(l,Zt(a,h[u-1],h[u]))}l<=o&&(!n||l<n.d)&&(n={f:s,d:l})}else if(c.tipo==="Circle"){const l=t(c.centro),d=t([c.centro[0]+c.raioMetros/111320,c.centro[1]]),h=tt(l,d);if(tt(a,l)<=h){const u=Math.PI*h*h;(!r||u<r.a)&&(r={f:s,a:u})}}else{const l=c.aneis[0].map(t);let d=1/0;for(const[u,g]of It(c))d=Math.min(d,Zt(a,l[u],l[g]));if(zt([a.y,a.x],[l.map(u=>[u.y,u.x]),...c.aneis.slice(1).map(u=>u.map(t).map(g=>[g.y,g.x]))])||d<=o){const u=na(s,t);(!r||u<r.a)&&(r={f:s,a:u})}}}return(i==null?void 0:i.f)??(n==null?void 0:n.f)??(r==null?void 0:r.f)??null}const Ae=.1,ra=2,sa=typeof requestAnimationFrame=="function"?a=>{requestAnimationFrame(a)}:a=>{setTimeout(a,16)};class ca extends b.Layer{constructor(t,o){super();f(this,"canvas",null);f(this,"agendado",!1);f(this,"vivo",!1);f(this,"nomePane");f(this,"obterMarcas");f(this,"ultimaPintura",0);this.nomePane=t,this.obterMarcas=o}onAdd(t){const o=t.getPane(this.nomePane);if(!o)return this;const i=b.DomUtil.create("canvas","leaflet-zoom-animated cad-marcas-lod");return i.style.pointerEvents="none",i.setAttribute("aria-hidden","true"),o.appendChild(i),this.canvas=i,this.vivo=!0,t.on("zoomstart",this.esconder,this),t.on("resize",this.solicitarRedesenho,this),this.solicitarRedesenho(),this}onRemove(t){var o;return this.vivo=!1,t.off("zoomstart",this.esconder,this),t.off("resize",this.solicitarRedesenho,this),(o=this.canvas)==null||o.remove(),this.canvas=null,this}solicitarRedesenho(){this.agendado||!this.vivo||(this.agendado=!0,sa(()=>{this.agendado=!1,this.vivo&&this.redesenhar()}))}esconder(){this.canvas&&(this.canvas.style.display="none")}redesenhar(){const t=this._map,o=this.canvas;if(!(!t||!o))try{const i=t.getSize(),n=Math.ceil(i.x*(1+2*Ae)),r=Math.ceil(i.y*(1+2*Ae));if(!(n>0&&r>0))return;const s=Math.min(ra,typeof window<"u"&&window.devicePixelRatio||1),c=t.containerPointToLayerPoint([-i.x*Ae,-i.y*Ae]).round();(o.width!==Math.round(n*s)||o.height!==Math.round(r*s))&&(o.width=Math.round(n*s),o.height=Math.round(r*s)),o.style.width=`${n}px`,o.style.height=`${r}px`,b.DomUtil.setPosition(o,c),o.style.display="";const l=o.getContext("2d");if(!l)return;l.setTransform(s,0,0,s,0,0),l.clearRect(0,0,n,r);const d=t.getPixelOrigin().add(c);this.ultimaPintura=m.pintarMarcas(l,this.obterMarcas(),t.getZoom(),d.x,d.y,n,r)}catch{}}}const Jo=new WeakMap,Ue={tower:'<path d="M12 2 L8 22 M12 2 L16 22 M9.5 12 H14.5 M8.7 17 H15.3 M12 2 L9.5 12 L14.5 12 Z" />',tree:'<path d="M12 22 V14 M12 3 L5 14 H19 Z" />',warning:'<path d="M12 3 L22 20 H2 Z M12 9 V14 M12 17 V17.5" />',water:'<path d="M12 3 C12 3 5 11 5 15.5 A7 7 0 0 0 19 15.5 C19 11 12 3 12 3 Z" />',boundary:'<path d="M12 2 L22 12 L12 22 L2 12 Z" />'};function Te(a,e,t=!1){const o=a.estilo??{},i=o.tamanhoIcone??e.tamanhoMarcador,n=typeof i=="number"&&Number.isFinite(i)&&i>0?i:22,r=t?m.COR_SELECAO:m.corSegura(o.corTraco??o.corPreenchimento??e.corPrimaria,m.COR_PADRAO),s=Number.isFinite(o.rotacaoIcone)?o.rotacaoIcone:0,c=Ue[o.icone??""]??"";return b.divIcon({className:`custom-leaflet-marker${t?" cad-feicao-selecionada":""}`,iconSize:[n,n],html:`<svg width="${n}" height="${n}" viewBox="0 0 24 24" fill="${r}" fill-opacity="0.25" stroke="${r}" stroke-width="1.6" stroke-linejoin="round" stroke-linecap="round" style="transform:rotate(${s}deg);overflow:visible;display:block${t?`;filter:drop-shadow(0 0 3px ${m.COR_SELECAO})`:""}">${c}</svg>`})}function Fe(a,e,t=!1){const o=a.estilo??{},i=a.geometria.tipo==="Text"?a.geometria.texto:"",n=t?m.COR_SELECAO:m.corSegura(o.corTraco??e.corPrimaria,"#ffffff"),r=Number.isFinite(o.tamanhoFonte)?o.tamanhoFonte:13,c=`display:inline-block;white-space:nowrap;transform:translate(-50%,-50%) rotate(${Number.isFinite(o.rotacaoIcone)?o.rotacaoIcone:0}deg);color:${n};font-size:${r}px;font-weight:600;`,l=m.corSegura(o.corFundo,"");if(l){const h=m.corSegura(o.corBorda,""),u=typeof o.opacidadeFundo=="number"&&Number.isFinite(o.opacidadeFundo)?Math.min(1,Math.max(0,o.opacidadeFundo)):.85,g=typeof o.raioBorda=="number"&&Number.isFinite(o.raioBorda)?Math.min(50,Math.max(0,o.raioBorda)):4,v=t?`1px solid ${m.COR_SELECAO}`:h?`1px solid ${h}`:"none";return b.divIcon({className:`custom-leaflet-marker cad-feicao-texto cad-feicao-selo${t?" cad-feicao-selecionada":""}`,iconSize:void 0,html:`<span style="${c}position:relative;padding:2px 6px;border-radius:${g}px;border:${v}"><span style="position:absolute;top:0;right:0;bottom:0;left:0;border-radius:inherit;background:${l};opacity:${u}"></span><span style="position:relative">${M.escapeHtml(i)}</span></span>`})}const d=o.halo?"text-shadow:-1px -1px 0 #000,1px -1px 0 #000,-1px 1px 0 #000,1px 1px 0 #000;":"";return b.divIcon({className:`custom-leaflet-marker cad-feicao-texto${t?" cad-feicao-selecionada":""}`,iconSize:void 0,html:`<span style="${c}${d}">${M.escapeHtml(i)}</span>`})}function Qo(a,e){const t=a<10?30:a<100?38:46,o=m.corSegura(e.corPrimaria,m.COR_PADRAO);return b.divIcon({className:"custom-leaflet-marker cad-feicao-cluster",iconSize:[t,t],html:`<div style="width:${t}px;height:${t}px;border-radius:50%;background:${o};opacity:.9;border:2px solid rgba(255,255,255,.85);display:flex;align-items:center;justify-content:center;color:#fff;font:700 12px sans-serif;text-shadow:0 0 2px #000">${a}</div>`})}function ut(a,e){return{color:a.cor,stroke:a.traco,weight:a.peso,dashArray:a.dash,fill:a.preencher,fillColor:a.corPreenchimento,fillOpacity:a.opacidadePreenchimento,lineJoin:"round",interactive:e}}const la=150,da=100,qe=300,ot=.75,ha=20,ua=.3,it=typeof requestAnimationFrame=="function"?a=>{requestAnimationFrame(a)}:a=>{setTimeout(a,16)};class ei{constructor(){f(this,"estados",new WeakMap);f(this,"selecionadas",Jo);f(this,"tokenLote",new WeakMap)}render(e,t,o){const i=b.layerGroup();return this.sincronizar(e,i,t,o,!0),i}update(e,t,o,i,n){if(o.dados===void 0&&o.estilo===void 0&&o.interativo===void 0&&o.bloqueada===void 0)return;const r=o.estilo!==void 0||o.interativo!==void 0||o.bloqueada!==void 0;this.sincronizar(e,t,n,i,r)}destroy(e,t){const o=this.estados.get(e);o&&(o.vivo=!1,t.off("moveend zoomend",o.aoMover),this.descartarMarcas(o)),e.clearLayers(),this.estados.delete(e),this.tokenLote.set(e,(this.tokenLote.get(e)??0)+1),t.hasLayer(e)&&t.removeLayer(e)}reavaliarVersoes(e){const t=this.estados.get(e);t&&(t.revisao++,t.revisaoBase++,this.reconciliar(e,t,!1,null))}feicaoVisivel(e,t){const o=this.estados.get(e),i=o==null?void 0:o.context.regraVersoes;return!o||!i||i.visivel(t,o.oficiais)}consultarProximas(e,t){const o=this.estados.get(e);if(!o)return[];const i=[];for(const n of o.indice.consultar(t)){const r=o.loja.get(n);r&&!r.oculta&&i.push(r)}return i}previsualizar(e,t){var r;const o=this.estados.get(e),i=o==null?void 0:o.entradas.get(t.id);if(!o||!i)return;const n=o.map._loaded?o.map.getZoom():0;this.remendar(i.layer,this.paraDesenho(t,n),o.layerDef,o.interativo,!!((r=this.selecionadas.get(o.layerDef))!=null&&r.has(t.id)))}estatisticas(e){const t=this.estados.get(e);return t?{total:t.loja.size,materializadas:t.entradas.size,marcasLOD:t.marcas.size,clusters:t.clusters.size,avaliacoesLOD:t.avaliacoesLOD}:null}idsDesenhados(e){const t=this.estados.get(e);return t?{materializadas:[...t.entradas.keys()].sort(),marcas:[...t.marcas.keys()].sort()}:null}feicoesDe(e){const t=e.dados,o=Array.isArray(t)?t:t==null?void 0:t.feicoes;return Array.isArray(o)?o:[]}obterEstado(e,t,o,i){let n=this.estados.get(e);if(!n){const r={layerDef:t,interativo:!1,map:o,context:i,loja:new Map,indice:new m.IndiceEspacial,revisao:0,revisaoBase:0,listaSincronizada:null,oficiais:new Set,contOficiais:new Map,nPrevias:0,contPrevias:new Map,entradas:new Map,marcas:new Map,camadaMarcas:null,fonteHit:null,lod:new Map,zoomLod:-1,avaliacoesLOD:0,clusters:new Map,nPontos:0,nPontosRev:-1,agrupador:null,agrupadorRev:-1,culling:!1,agendado:!1,vivo:!0,aoMover:()=>{r.agendado||!r.vivo||(r.agendado=!0,it(()=>{r.agendado=!1,r.vivo&&this.reconciliar(e,r,!1,null)}))}};o.on("moveend zoomend",r.aoMover),this.estados.set(e,r),n=r}return n.layerDef=t,n.map=o,n.context=i,n.interativo=t.interativo&&!t.bloqueada,n}sincronizar(e,t,o,i,n){var v;const r=this.obterEstado(t,e,o,i),s=this.feicoesDe(e),c=(v=e.dados)==null?void 0:v.delta;if(!n&&this.aplicarDelta(t,r,s,c))return;const l=s.filter(p=>!p.excluida),d=new Set,h=new Set;for(const p of l)h.add(p.id),r.loja.get(p.id)!==p&&d.add(p.id);const u=[...r.loja.keys()].filter(p=>!h.has(p));if(d.size>0||u.length>0){if(r.revisao++,r.revisaoBase++,r.lod.clear(),r.loja.size===0||d.size+u.length>l.length*ua)r.indice.construir(l);else{for(const p of l)d.has(p.id)&&r.indice.atualizar(p);for(const p of u)r.indice.remover(p)}r.loja=new Map(l.map(p=>[p.id,p])),this.recontarOficiais(r,l)}r.listaSincronizada=s;const g=this.selecionadas.get(e);if(g)for(const p of[...g])h.has(p)||g.delete(p);this.reconciliar(t,r,n,d)}recontarOficiais(e,t){e.contOficiais=new Map,e.contPrevias=new Map,e.nPrevias=0;for(const o of t){if(o.excluida)continue;if(m.statusDe(o)!=="oficial"){e.nPrevias++;const n=m.entidadeDe(o);e.contPrevias.set(n,(e.contPrevias.get(n)??0)+1);continue}const i=m.entidadeDe(o);e.contOficiais.set(i,(e.contOficiais.get(i)??0)+1)}e.oficiais=new Set(e.contOficiais.keys())}aplicarDelta(e,t,o,i){if(!i||i.base!==t.listaSincronizada)return!1;const{loja:n}=t,r=this.selecionadas.get(t.layerDef),s=p=>p.geometria.tipo==="Point"&&this.desenhavel(t,p),c=new Map,l=(p,y)=>{if(!p||p.excluida||m.statusDe(p)!=="oficial")return;const A=m.entidadeDe(p);c.has(A)||c.set(A,t.oficiais.has(A));const w=(t.contOficiais.get(A)??0)+y;w<=0?(t.contOficiais.delete(A),t.oficiais.delete(A)):(t.contOficiais.set(A,w),t.oficiais.add(A))},d=[],h=[],u=(p,y)=>{const A=m.entidadeDe(p),w=(t.contPrevias.get(A)??0)+y;w<=0?t.contPrevias.delete(A):t.contPrevias.set(A,w)},g=p=>{const y=n.get(p);y&&(t.lod.delete(p),m.statusDe(y)==="previa"&&(t.nPrevias--,u(y,-1)),l(y,-1),s(y)&&t.nPontos--,n.delete(p),t.indice.remover(p),r==null||r.delete(p),h.push(p))};for(const p of i.removidas)g(p);for(const p of i.mudadas){if(p.excluida){g(p.id);continue}const y=n.get(p.id);t.lod.delete(p.id),m.statusDe(p)==="previa"&&(t.nPrevias++,u(p,1)),y&&(m.statusDe(y)==="previa"&&(t.nPrevias--,u(y,-1)),l(y,-1),s(y)&&t.nPontos--),n.set(p.id,p),t.indice.atualizar(p),l(p,1),s(p)&&t.nPontos++,d.push(p.id)}let v=!1;if(t.nPrevias>0)for(const[p,y]of c)y!==t.oficiais.has(p)&&(v=!0);return t.listaSincronizada=o,t.revisao++,v&&t.revisaoBase++,this.reconciliarParcial(e,t,d,h,v),!0}ressimplificar(e,t){return e.zoomDesenho===t||m.vertices(e.feicao.geometria)<m.MIN_VERTICES_SIMPLIFICAR?!1:t<m.ZOOM_SEM_SIMPLIFICACAO||e.zoomDesenho<m.ZOOM_SEM_SIMPLIFICACAO}paraDesenho(e,t){const o=m.simplificarGeometria(e.geometria,t);return o===e.geometria?e:{...e,geometria:o}}desenhavel(e,t){if(t.oculta)return!1;const o=e.context.regraVersoes;return!o||o.visivel(t,e.oficiais)}estaCarregado(e){return!!e._loaded}caixaDe(e){return{minLon:e.getWest(),minLat:e.getSouth(),maxLon:e.getEast(),maxLat:e.getNorth()}}comoMarca(e,t,o,i){var c;if(o<0||i)return!1;const n=t.geometria.tipo;if(n==="Point"||n==="Text"||(c=t.estilo)!=null&&c.mostrarRotulo)return!1;if(e.contPrevias.size>0){const l=m.entidadeDe(t);if(e.contPrevias.has(l)&&e.oficiais.has(l))return!1}o!==e.zoomLod&&(e.lod.clear(),e.zoomLod=o);const r=e.lod.get(t.id);if(r!==void 0)return r;e.avaliacoesLOD++;const s=m.ehMarca(e.indice.caixaDe(t.id),o);return e.lod.set(t.id,s),s}novaMarca(e,t,o){const i=e.indice.caixaDe(t.id);if(!i)return null;const n=t.estilo??{},r=m.corSegura(n.corPreenchimento??n.corTraco??e.layerDef.estilo.corPrimaria,m.COR_PADRAO);return{id:t.id,lat:(i.minLat+i.maxLat)/2,lon:(i.minLon+i.maxLon)/2,cor:r,lado:m.ladoMarca(m.diagonalPx(i,o)),fonte:t}}colocarFeicao(e,t,o,i,n,r,s){if(this.comoMarca(t,o,n,r)){this.tirarEntrada(e,t,o.id);const c=t.marcas.get(o.id);if(!c||c.fonte!==o){const l=this.novaMarca(t,o,n);l&&t.marcas.set(o.id,l)}return}t.marcas.delete(o.id),this.materializar(e,t,o,i,r,s)}sincronizarMarcas(e){if(e.marcas.size===0){e.camadaMarcas&&this.descartarMarcas(e);return}if(!e.camadaMarcas){const t=U(e.map,e.layerDef.id,"poligono"),o=new ca(t,()=>e.marcas.values());e.camadaMarcas=o,o.addTo(e.map),o.on("click",i=>{var s,c;const{feicaoHit:n,originalEvent:r}=i;!n||!e.vivo||(c=(s=e.context).onLayerAction)==null||c.call(s,"feicao-clique",{camadaId:e.layerDef.id,feicao:n,aditivo:!!(r&&(r.ctrlKey||r.metaKey||r.shiftKey))})}),e.fonteHit=this.fonteDeMarcas(e,o),St(e.map,e.layerDef.id,e.fonteHit)}e.camadaMarcas.solicitarRedesenho()}fonteDeMarcas(e,t){return{alvo:t,consultar:o=>{const{map:i}=e;if(!e.vivo||!e.interativo||!e.layerDef.visivel||e.marcas.size===0||!this.estaCarregado(i))return[];const n=i.layerPointToContainerPoint(o),r=8,s=i.containerPointToLatLng([n.x-r,n.y+r]),c=i.containerPointToLatLng([n.x+r,n.y-r]),l={minLat:Math.min(s.lat,c.lat),maxLat:Math.max(s.lat,c.lat),minLon:Math.min(s.lng,c.lng),maxLon:Math.max(s.lng,c.lng)},d=[];for(const v of e.indice.consultar(l)){const p=e.marcas.has(v)?e.loja.get(v):void 0;p&&d.push(p)}const h=v=>{const p=i.latLngToContainerPoint(v);return{x:p.x,y:p.y}},u=i.getZoom(),g=[];for(let v=0;v<ha&&d.length>0;v++){const p=Le({x:n.x,y:n.y},d,h);if(!p)break;d.splice(d.indexOf(p),1);const y=m.diagonalPx(e.indice.caixaDe(p.id)??l,u);g.push({feicao:p,chave:p.id,tipo:p.geometria.tipo==="LineString"?"linha":"poligono",distancia:0,area:Number.isFinite(y)?y*y/2:0})}return g}}}descartarMarcas(e){e.fonteHit&&Mt(e.map,e.layerDef.id,e.fonteHit),e.fonteHit=null,e.camadaMarcas&&(e.map.removeLayer(e.camadaMarcas),e.camadaMarcas=null),e.marcas.clear()}materializar(e,t,o,i,n,r){try{this.materializarFeicao(e,t,o,i,n,r)}catch{this.tirarEntrada(e,t,o.id)}}materializarFeicao(e,t,o,i,n,r){const s=this.formaDe(o),c=t.entradas.get(o.id);if(c&&c.forma===s){const h=c.feicao!==o||this.ressimplificar(c,i);r===!0||h?(this.remendar(c.layer,this.paraDesenho(o,i),t.layerDef,t.interativo,n),c.feicao=o,c.zoomDesenho=i):r==="estilo"&&this.restilizar(c.layer,o,t.layerDef,t.interativo,n);return}const l=this.paraDesenho(o,i);c&&e.removeLayer(c.layer);const d=this.criar(l,t.layerDef,t.map,t.interativo,n);this.ligarEventos(d,o.id,t.layerDef,t.entradas,t.context),this.aplicarRotulo(d,o),e.addLayer(d),t.entradas.set(o.id,{layer:d,forma:s,feicao:o,zoomDesenho:i})}tirarEntrada(e,t,o){const i=t.entradas.get(o);i&&(e.removeLayer(i.layer),t.entradas.delete(o))}colocarCluster(e,t,o,i){const n=t.clusters.get(o);if((n==null?void 0:n.assinatura)===i.assinatura)return;n&&e.removeLayer(n.marker);const r=this.criarMarcadorCluster(i.coordenada,i.total,()=>{var s,c;return Array.from(((c=(s=t.agrupador)==null?void 0:s.celula(o))==null?void 0:c.membros.values())??[])},t);e.addLayer(r),t.clusters.set(o,{marker:r,assinatura:i.assinatura})}tirarCluster(e,t,o){const i=t.clusters.get(o);i&&(e.removeLayer(i.marker),t.clusters.delete(o))}agrupadorAtivo(e,t){const o=r=>this.desenhavel(e,r);if(e.nPontosRev!==e.revisaoBase){let r=0;for(const s of e.loja.values())s.geometria.tipo==="Point"&&o(s)&&r++;e.nPontos=r,e.nPontosRev=e.revisaoBase}if(!m.deveAgrupar(e.nPontos,t))return e.agrupador=null,null;const i=e.agrupador;if(i&&i.zoom===t&&e.agrupadorRev===e.revisaoBase)return i;const n=new m.AgrupadorCluster(t,r=>e.map.project(b.latLng(r[0],r[1]),t));for(const r of e.loja.values())r.geometria.tipo==="Point"&&o(r)&&n.inserir({id:r.id,coordenada:r.geometria.coordenada});return e.agrupador=n,e.agrupadorRev=e.revisaoBase,n}reconciliar(e,t,o,i){var w;const{map:n,layerDef:r,loja:s}=t,c=this.selecionadas.get(r),l=this.estaCarregado(n),d=l?n.getZoom():0,h=l&&s.size>qe?n.getBounds().pad(ot):null,u=h?this.caixaDe(h):null;t.culling=h!==null;const g=u?t.indice.consultar(u):s.keys(),v=new Set(g);if(c)for(const x of c)s.has(x)&&v.add(x);for(const x of[...v]){const k=s.get(x);k&&!this.desenhavel(t,k)&&v.delete(x)}const p=new Map,y=l?this.agrupadorAtivo(t,d):null;if(y||(t.agrupador=null),y){for(const k of[...v])y.emCluster(k)&&v.delete(k);const x=new Map;if(c)for(const k of c){const C=y.chaveDoPonto(k),L=C===void 0||(w=y.celula(C))==null?void 0:w.membros.get(k);if(C!==void 0&&L){const P=x.get(C);P?P.push(L):x.set(C,[L])}}for(const[k,C]of y.celulasAgrupadas()){const L=x.get(k);if(L)for(const I of L)v.add(I.id);const P=C.membros.size,z=P-((L==null?void 0:L.length)??0);if(z===1)for(const I of C.membros.values()){if(c!=null&&c.has(I.id))continue;const S=t.indice.caixaDe(I.id);(!u||S&&m.caixasSeTocam(S,u))&&v.add(I.id);break}if(!(h&&!h.contains([C.somaLat/P,C.somaLon/P]))&&z>=2){let I=C.somaLat,S=C.somaLon;if(L)for(const D of L)I-=D.coordenada[0],S-=D.coordenada[1];const E=[I/z,S/z];p.set(k,{coordenada:E,total:P,assinatura:`${k}:${P}:${z}:${E[0].toFixed(7)}:${E[1].toFixed(7)}`})}}}const A=l?d:-1;for(const x of v){const k=s.get(x);k&&this.colocarFeicao(e,t,k,d,A,!!(c!=null&&c.has(x)),o||!!(i!=null&&i.has(x)))}for(const x of[...t.entradas.keys()])v.has(x)&&s.has(x)||this.tirarEntrada(e,t,x);for(const x of[...t.marcas.keys()])(!v.has(x)||!s.has(x))&&t.marcas.delete(x);this.sincronizarMarcas(t);for(const[x,k]of p)this.colocarCluster(e,t,x,k);for(const x of[...t.clusters.keys()])p.has(x)||this.tirarCluster(e,t,x)}reconciliarParcial(e,t,o,i,n){this.reconciliarParcialInterno(e,t,o,i,n),this.sincronizarMarcas(t)}reconciliarParcialInterno(e,t,o,i,n){const{map:r,layerDef:s,loja:c}=t,l=this.estaCarregado(r),d=l?r.getZoom():0,h=l&&c.size>qe,u=l&&m.deveAgrupar(t.nPontos,d),g=t.agrupador;if(n||h!==t.culling||u!==(g!==null)||g!==null&&(g.zoom!==d||t.agrupadorRev!==t.revisaoBase)){this.reconciliar(e,t,!1,new Set(o));return}const v=this.selecionadas.get(s),p=P=>this.desenhavel(t,P),y=h?r.getBounds().pad(ot):null,A=y?this.caixaDe(y):null,w=l?d:-1,x=(P,z)=>{const I=c.get(P);if(!I||!p(I)){this.tirarEntrada(e,t,P),t.marcas.delete(P);return}const S=!!(v!=null&&v.has(P));if(!S&&A){const E=t.indice.caixaDe(P);if(!E||!m.caixasSeTocam(E,A)){this.tirarEntrada(e,t,P),t.marcas.delete(P);return}}this.colocarFeicao(e,t,I,d,w,S,z)},k=new Set,C=[];for(const P of i){this.tirarEntrada(e,t,P),t.marcas.delete(P);const z=g==null?void 0:g.remover(P);z!==void 0&&k.add(z)}for(const P of o){t.marcas.delete(P);const z=c.get(P);if(!z)continue;const I=g==null?void 0:g.remover(P);I!==void 0&&k.add(I),g&&z.geometria.tipo==="Point"&&p(z)?k.add(g.inserir({id:P,coordenada:z.geometria.coordenada})):C.push(P)}for(const P of C)x(P,!0);if(!g)return;const L=new Set(o);for(const P of k){const z=g.celula(P);if(!z||z.membros.size<2){if(this.tirarCluster(e,t,P),z)for(const B of z.membros.keys())x(B,L.has(B));continue}const I=z.membros.size;let S=z.somaLat,E=z.somaLon,D=0;for(const B of z.membros.values())v!=null&&v.has(B.id)&&(D++,S-=B.coordenada[0],E-=B.coordenada[1]);const _=I-D;for(const B of z.membros.values())v!=null&&v.has(B.id)||_===1?x(B.id,L.has(B.id)):this.tirarEntrada(e,t,B.id);const R=[z.somaLat/I,z.somaLon/I];if(y&&!y.contains(R)||_<2){this.tirarCluster(e,t,P);continue}const O=[S/_,E/_];this.colocarCluster(e,t,P,{coordenada:O,total:I,assinatura:`${P}:${I}:${_}:${O[0].toFixed(7)}:${O[1].toFixed(7)}`})}}criarMarcadorCluster(e,t,o,i){const n=Qo(t,i.layerDef.estilo),r=b.marker(e,{icon:n,pane:U(i.map,i.layerDef.id,"ponto"),keyboard:!1});return r.bindTooltip(`${t} feições agrupadas`,{direction:"top"}),r.on("click",()=>{const s=o();s.length>0&&i.map.fitBounds(b.latLngBounds(s.map(c=>c.coordenada)),{padding:[60,60],maxZoom:18})}),r}aplicarSelecao(e,t){const o=this.estados.get(e);if(!o)return;const i=this.selecionadas.get(o.layerDef)??new Set,n=new Set(t);this.selecionadas.set(o.layerDef,n);const r=[];for(const y of n)i.has(y)||r.push(y);for(const y of i)n.has(y)||r.push(y);if(r.length===0)return;const{map:s,loja:c}=o,l=this.estaCarregado(s),d=l?s.getZoom():0,h=l?d:-1,u=l&&c.size>qe?this.caixaDe(s.getBounds().pad(ot)):null,g=o.agrupador!==null&&r.some(y=>{var A;return((A=c.get(y))==null?void 0:A.geometria.tipo)==="Point"}),v=y=>{const A=c.get(y);if(!A)return;const w=n.has(y);if(!this.desenhavel(o,A)){this.tirarEntrada(e,o,y),o.marcas.delete(y);return}if(!w&&u){const k=o.indice.caixaDe(y);if(!k||!m.caixasSeTocam(k,u)){this.tirarEntrada(e,o,y),o.marcas.delete(y);return}}this.colocarFeicao(e,o,A,d,h,w,"estilo");const x=w?o.entradas.get(y):void 0;x&&"bringToFront"in x.layer&&x.layer.bringToFront()},p=(this.tokenLote.get(e)??0)+1;if(this.tokenLote.set(e,p),r.length<=la)r.forEach(v);else{const y=l?this.caixaDe(s.getBounds()):null,A=C=>{if(!y)return!0;const L=o.indice.caixaDe(C);return!L||m.caixasSeTocam(L,y)},w=r.filter(A),x=r.filter(C=>!A(C));w.forEach(v);const k=()=>{this.tokenLote.get(e)!==p||!o.vivo||(x.splice(0,da).forEach(v),x.length>0?it(k):this.sincronizarMarcas(o))};x.length>0&&it(k)}g?this.reconciliar(e,o,!1,null):this.sincronizarMarcas(o)}formaDe(e){var o;const t=e.geometria;return t.tipo==="Point"?`Point:${(o=e.estilo)!=null&&o.icone&&Ue[e.estilo.icone]?e.estilo.icone:""}`:m.nosDaGeometria(t)?`${t.tipo}:curva`:t.tipo}paneDe(e){switch(e.geometria.tipo){case"Polygon":case"Circle":return"poligono";case"LineString":return"linha";case"Point":return"ponto";default:return"texto"}}estiloVetor(e,t,o,i=!1){return ut(m.estiloVetorDe(e,t.estilo,i),o)}criar(e,t,o,i,n){var d;const r=U(o,t.id,this.paneDe(e)),s=e.geometria,c=this.estiloVetor(e,t,i,n),l=Et(s,{...c,pane:r});if(l)return l;switch(s.tipo){case"Polygon":return b.polygon(s.aneis.length===1?s.aneis[0]:s.aneis,{...c,pane:r});case"Circle":return b.circle(s.centro,{...c,radius:s.raioMetros,pane:r});case"LineString":return b.polyline(s.partes&&s.partes.length>1?m.partesDaLinha(s):s.coordenadas,{...c,pane:r});case"Point":{const h=(d=e.estilo)==null?void 0:d.icone;return h&&Ue[h]?b.marker(s.coordenada,{icon:this.iconeSvg(e,t,n),pane:r,interactive:i}):b.circleMarker(s.coordenada,{...c,radius:m.raioPontoPx(e,t.estilo),pane:r})}default:return b.marker(s.coordenada,{icon:this.iconeTexto(e,t,n),pane:r,interactive:i,draggable:i&&!e.bloqueada})}}remendar(e,t,o,i,n){var c,l;const r=t.geometria,s=this.estiloVetor(t,o,i,n);(e instanceof Eo||e instanceof zo)&&m.nosDaGeometria(r)?(ko(e,r),e.setStyle(s)):r.tipo==="Polygon"?(e.setLatLngs(r.aneis.length===1?r.aneis[0]:r.aneis),e.setStyle(s)):r.tipo==="LineString"?(e.setLatLngs(r.partes&&r.partes.length>1?m.partesDaLinha(r):r.coordenadas),e.setStyle(s)):r.tipo==="Circle"?(e.setLatLng(r.centro),e.setRadius(r.raioMetros),e.setStyle(s)):r.tipo==="Point"&&e instanceof b.CircleMarker?(e.setLatLng(r.coordenada),e.setRadius(m.raioPontoPx(t,o.estilo)),e.setStyle(s)):e instanceof b.Marker&&(e.setLatLng(r.tipo==="Point"||r.tipo==="Text"?r.coordenada:e.getLatLng()),e.setIcon(r.tipo==="Text"?this.iconeTexto(t,o,n):this.iconeSvg(t,o,n)),r.tipo==="Text"&&(i&&!t.bloqueada?(c=e.dragging)==null||c.enable():(l=e.dragging)==null||l.disable())),this.aplicarRotulo(e,t)}restilizar(e,t,o,i,n){e instanceof b.Marker?e.setIcon(t.geometria.tipo==="Text"?this.iconeTexto(t,o,n):this.iconeSvg(t,o,n)):e instanceof b.Path&&e.setStyle(this.estiloVetor(t,o,i,n))}iconeSvg(e,t,o=!1){return Te(e,t.estilo,o)}iconeTexto(e,t,o=!1){return Fe(e,t.estilo,o)}aplicarRotulo(e,t){const o=t.estilo;if(!(o!=null&&o.mostrarRotulo)||t.geometria.tipo==="Text"){e.unbindTooltip();return}const i=m.textoRotulo(t,o.campoRotulo);if(!i){e.unbindTooltip();return}const n=document.createElement("span");n.textContent=i,e.getTooltip()?e.setTooltipContent(n):e.bindTooltip(n,{permanent:!0,direction:"center",className:"cad-feicao-rotulo",interactive:!1})}ligarEventos(e,t,o,i,n){e.on("click",r=>{var l;const s=i.get(t);if(!s)return;const c=r==null?void 0:r.originalEvent;(l=n.onLayerAction)==null||l.call(n,"feicao-clique",{camadaId:o.id,feicao:s.feicao,aditivo:!!(c&&(c.ctrlKey||c.metaKey||c.shiftKey))})}),e instanceof b.Marker&&e.on("dragend",()=>{var l;const r=i.get(t);if(!r||r.feicao.geometria.tipo!=="Text")return;const{lat:s,lng:c}=e.getLatLng();r.feicao={...r.feicao,geometria:{...r.feicao.geometria,coordenada:[s,c]}},(l=n.onLayerAction)==null||l.call(n,"feicao-movida",{camadaId:o.id,feicao:r.feicao})})}}const pa="rgba(255,255,255,0.9)";function ti(a){if(!a)return[];const e=a.split(/[\s,]+/).map(Number).filter(t=>Number.isFinite(t)&&t>=0);return e.length>0&&e.some(t=>t>0)?e.length%2===1?[...e,...e]:e:[]}const K=a=>Number.isFinite(a),fa=new Set(["marca","poligono","circulo","linha","ponto"]);function pt(a){let e=0;if(a)for(const t of a.itens)fa.has(t.forma)&&e++;return e}class Dt{constructor(e){f(this,"destaques",new Set);f(this,"destruido",!1);f(this,"ultima",{itens:0,marcas:0,preenchimentos:0,tracos:0,chamadas:0});this.alvos=e}destacar(e){this.destaques=new Set(e)}limpar(){const e=this.alvos.sobreposicao();e&&this.limparSuperficie(e)}destruir(){this.destruido=!0,this.destaques.clear()}desenhar(e,t,o={}){const i={itens:0,marcas:0,preenchimentos:0,tracos:0,chamadas:0};if(this.destruido||!e)return i;const n=o.alvo==="sobreposicao",r=t&&K(t.dpr)&&t.dpr>0?t.dpr:1;if(n){const s=this.alvos.sobreposicao();s&&o.limpar!==!1&&this.limparSuperficie(s,r)}for(const s of e.camadas){const c=n?this.alvos.sobreposicao():this.alvos.camada(s.camadaId);if(!c)continue;!n&&o.limpar!==!1?this.limparSuperficie(c,r):c.ctx.setTransform(r,0,0,r,0,0);const l=o.recorte;l&&(c.ctx.save(),c.ctx.beginPath(),c.ctx.rect(l.x,l.y,l.largura,l.altura),c.ctx.clip());try{this.pintarCamada(c,s,e.origem,n,i)}finally{l&&c.ctx.restore()}}return this.ultima=i,i}limparSuperficie(e,t){const o=t??e.dpr;e.ctx.setTransform(1,0,0,1,0,0),e.ctx.clearRect(0,0,Math.ceil(e.largura*o),Math.ceil(e.altura*o)),e.ctx.setTransform(o,0,0,o,0,0)}pintarCamada(e,t,o,i,n){const r=e.ctx,s=[],c=[],l=[],d=[];for(const h of t.itens)switch(h.forma){case"marca":s.push(h);break;case"poligono":case"circulo":c.push(h);break;case"linha":l.push(h);break;case"ponto":d.push(h);break}if(n.itens+=s.length+c.length+l.length+d.length,r.lineJoin="round",r.lineCap="round",i)for(const h of[...c,...l,...d])(h.destaque||this.destaques.has(h.id))&&this.halo(r,h,o,n);this.pintarMarcas(r,s,o,n),this.pintarGrupos(r,c,o,n,!0),this.pintarGrupos(r,l,o,n,!1),this.pintarGrupos(r,d,o,n,!0),r.globalAlpha=1,r.setLineDash([])}agrupar(e){const t=new Map;for(const o of e){const i=t.get(o.estilo);i?i.push(o):t.set(o.estilo,[o])}return t}pintarMarcas(e,t,o,i){for(const[n,r]of this.agrupar(t)){e.fillStyle=n.corPreenchimento,e.globalAlpha=n.opacidadePreenchimento,i.chamadas+=2;for(const s of r){const c=s.geometriaEmPx[0];if(!c)continue;const l=c[0]-o.x,d=c[1]-o.y;if(!(K(l)&&K(d)))continue;const h=s.raioPx>=2?2:1;e.fillRect(Math.round(l-h/2),Math.round(d-h/2),h,h),i.marcas++,i.chamadas++}}}caminho(e,t,o){if(t.forma==="circulo"||t.forma==="ponto"){const n=t.geometriaEmPx[0];if(!n)return;const r=n[0]-o.x,s=n[1]-o.y;K(r)&&K(s)&&K(t.raioPx)&&(e.moveTo(r+t.raioPx,s),e.arc(r,s,t.raioPx,0,Math.PI*2));return}const i=t.forma==="poligono";for(const n of t.geometriaEmPx){const r=n.length>>1;if(r<2)continue;let s=!1;for(let c=0;c<r;c++){const l=n[c*2]-o.x,d=n[c*2+1]-o.y;K(l)&&K(d)&&(s?e.lineTo(l,d):(e.moveTo(l,d),s=!0))}s&&i&&e.closePath()}}pintarGrupos(e,t,o,i,n){for(const[r,s]of this.agrupar(t)){const c=n&&r.preencher&&r.opacidadePreenchimento>0,l=r.traco&&r.peso>0;if(!(!c&&!l)){c&&(e.fillStyle=r.corPreenchimento),l&&(e.strokeStyle=r.cor,e.lineWidth=r.peso,e.setLineDash(ti(r.dash))),i.chamadas+=3;for(const d of s)e.beginPath(),this.caminho(e,d,o),c&&(e.globalAlpha=r.opacidadePreenchimento,e.fill(),i.preenchimentos++,i.chamadas++),l&&(e.globalAlpha=1,e.stroke(),i.tracos++,i.chamadas++)}}}halo(e,t,o,i){e.strokeStyle=pa,e.lineWidth=Math.max(t.estilo.peso,1)+4,e.globalAlpha=.9,e.setLineDash([]),e.beginPath(),this.caminho(e,t,o),e.stroke(),i.tracos++,i.chamadas+=4}}function oi(a,e,t,o){const i=[],n=Math.abs(t),r=Math.abs(o);return n>0&&i.push({x:t>0?a-n:0,y:0,largura:n,altura:e}),r>0&&i.push({x:t>0?0:n,y:o>0?e-r:0,largura:a-n,altura:r}),i}const Xe=class Xe extends b.Canvas{constructor(t,o){super(t);f(this,"aoPintar");f(this,"incremental");f(this,"limiteProprio");f(this,"itens",0);f(this,"conteudoValido",!1);f(this,"branco",!0);f(this,"mundoMin",null);f(this,"regioesDaVez",null);f(this,"falhas",0);f(this,"ultimoErro",null);this.aoPintar=o,this.incremental=!!t.incremental,this.limiteProprio=t.limiteRepintar}get limiteRepintar(){const t=this.limiteProprio??Xe.limiteRepintar;return t>0?t:0}onAdd(t){return super.onAdd(t),this.regioesDaVez=null,this.pintar(),this}_update(){const t=this,o=t._map;if(!o||o._animatingZoom&&t._bounds)return;const i=t._bounds?{mundo:this.mundoMin,x:t._bounds.getSize().x,y:t._bounds.getSize().y,zoom:t._zoom}:null;b.Renderer.prototype._update.call(this);const n=t._bounds,r=o.getPixelOrigin(),s={x:r.x+n.min.x,y:r.y+n.min.y},c=t._container,l=t._ctx,d=n.getSize(),h=b.Browser.retina?2:1;b.DomUtil.setPosition(c,n.min);const u=this.incremental&&this.conteudoValido&&!!i&&i.zoom===t._zoom&&i.x===d.x&&i.y===d.y&&c.width===h*d.x&&c.height===h*d.y;let g=null,v=!1;if(u&&i&&i.mundo){const p=s.x-i.mundo.x,y=s.y-i.mundo.y;!this.branco&&this.itens<=this.limiteRepintar?v=!0:Math.abs(p)<d.x&&Math.abs(y)<d.y&&((p!==0||y!==0)&&!this.branco&&(l.save(),l.setTransform(1,0,0,1,0,0),l.globalCompositeOperation="copy",l.drawImage(c,-p*h,-y*h),l.restore()),g=oi(d.x,d.y,p,y))}!g&&!v&&((!this.branco||c.width!==h*d.x||c.height!==h*d.y)&&(c.width=h*d.x,c.height=h*d.y),this.branco=!0,c.style.width=`${d.x}px`,c.style.height=`${d.y}px`,this.conteudoValido=!1),this.regioesDaVez=g,this.mundoMin=s,l.setTransform(1,0,0,1,0,0),this.fire("update")}_updatePaths(){this._postponeUpdatePaths||this.pintarQuadro(this.regioesDaVez)}pintar(){this.pintarQuadro(null)}pintarQuadro(t){const o=this.quadroAtual(t);if(this.regioesDaVez=null,!!o)try{const i=this.aoPintar(o),n=typeof i=="number"?i>0?i:0:i===!1?0:Number.POSITIVE_INFINITY;this.itens=t?(this.branco?0:this.itens)+n:n,this.branco=this.itens===0,this.conteudoValido=!0}catch(i){this.conteudoValido=!1,this.branco=!1,this.itens=Number.POSITIVE_INFINITY,this.falhas++,this.ultimoErro=i}}quadroAtual(t=null){const o=this,i=o._map,n=o._bounds,r=o._ctx;if(!i||!n||!r)return null;try{const s=n.getSize(),c=i.getPixelOrigin(),l=i.layerPointToLatLng(n.min),d=i.layerPointToLatLng(n.max);return{ctx:r,dpr:b.Browser.retina?2:1,larguraPx:s.x,alturaPx:s.y,origemPx:{x:c.x+n.min.x,y:c.y+n.min.y},caixa:{minLat:d.lat,maxLat:l.lat,minLon:l.lng,maxLon:d.lng},zoom:i.getZoom(),regioes:t,branco:this.branco}}catch{return null}}};f(Xe,"limiteRepintar",500);let be=Xe;const ft="cad-formas-sobreposicao",ma="7000",we=8,ga=8,va=20,mt=typeof requestAnimationFrame=="function"?a=>{requestAnimationFrame(a)}:a=>{setTimeout(a,16)},ya=new Set(["icone","texto","cluster","rotulo","curva"]),ee=new WeakMap;function ae(a){return{caixa:a.caixa,zoom:a.zoom,larguraPx:a.larguraPx,alturaPx:a.alturaPx,dpr:a.dpr,origemPx:a.origemPx}}const ba=a=>!!a._loaded;function xa(a){const e=ee.get(a);if(e)return e;const t={estados:new Set,quadro:null,agendado:!1,noMapa:!1};return t.pintor=new Dt({camada:()=>null,sobreposicao:()=>t.quadro?{ctx:t.quadro.ctx,largura:t.quadro.larguraPx,altura:t.quadro.alturaPx,dpr:t.quadro.dpr}:null}),t.canvas=new be({pane:ft,padding:.1},o=>{t.quadro=o;const i=ae(o),n=[];for(const r of[...t.estados].sort((s,c)=>s.layerDef.zIndex-c.layerDef.zIndex)){if(!r.vivo||!r.layerDef.visivel)continue;const s=r.motor.listaSobreposicao(r.layerDef.id,i);s&&s.itens.length>0&&n.push(s)}return o.branco&&n.length===0?!1:(t.pintor.desenhar({vista:i,origem:o.origemPx,camadas:n},i,{alvo:"sobreposicao"}),n.length>0)}),ee.set(a,t),t}function Pa(a,e){e.noMapa||(e.noMapa=!0,a.whenReady(()=>{if(!a.getPane(ft)){const t=a.createPane(ft);t.style.zIndex=ma,t.style.pointerEvents="none"}ee.get(a)===e&&a.addLayer(e.canvas)}))}function Ee(a){a.agendado||(a.agendado=!0,mt(()=>{a.agendado=!1,a.noMapa&&a.canvas.pintar()}))}class ii{constructor(){f(this,"estados",new WeakMap);f(this,"selecionadas",Jo)}render(e,t,o){const i=b.layerGroup(),n=new m.MotorFormas,r=o.regraVersoes;r&&n.definirRegra((d,h)=>r.visivel(d,h)),n.definirCamada(this.defMotor(e)),n.definirFeicoes(e.id,this.feicoesDe(e));const s=this.selecionadas.get(e);s&&n.selecionar(e.id,s);const c={layerDef:e,map:t,context:o,grupo:i,motor:n,interativo:e.interativo&&!e.bloqueada,quadro:null,dom:new Map,fonteHit:null,agendado:!1,agendadoDom:!1,vivo:!0,ultima:null};c.pintor=new Dt({camada:()=>c.quadro?{ctx:c.quadro.ctx,largura:c.quadro.larguraPx,altura:c.quadro.alturaPx,dpr:c.quadro.dpr}:null,sobreposicao:()=>null}),t.getPane(ce(e.id))||t.createPane(ce(e.id)),c.base=new be({pane:ce(e.id),padding:.1,incremental:!0},d=>this.pintarBase(c,d)),this.estados.set(i,c),t.whenReady(()=>{c.vivo&&i.addLayer(c.base)});const l=xa(t);return l.estados.add(c),Pa(t,l),this.registrarHit(c),i}update(e,t,o,i,n){var s;const r=this.estados.get(t);if(r&&(r.layerDef=e,r.context=i,r.interativo=e.interativo&&!e.bloqueada,!(o.dados===void 0&&o.estilo===void 0&&o.interativo===void 0&&o.bloqueada===void 0))){if(r.motor.definirCamada(this.defMotor(e)),o.dados!==void 0){const c=this.feicoesDe(e),l=(s=e.dados)==null?void 0:s.delta;l?r.motor.aplicarDelta(e.id,c,l):r.motor.definirFeicoes(e.id,c);const d=this.selecionadas.get(e);if(d)for(const h of[...d])r.motor.feicao(e.id,h)||d.delete(h)}if(o.estilo!==void 0||o.interativo!==void 0||o.bloqueada!==void 0){for(const c of r.dom.values())r.grupo.removeLayer(c.layer);r.dom.clear()}this.pedirBase(r)}}destroy(e,t){const o=e,i=this.estados.get(o);if(i){i.vivo=!1,i.fonteHit&&Mt(i.map,i.layerDef.id,i.fonteHit),i.fonteHit=null;const n=ee.get(i.map);n&&(n.estados.delete(i),Ee(n)),i.pintor.destruir(),i.dom.clear()}o.clearLayers(),this.estados.delete(o),t.hasLayer(o)&&t.removeLayer(o)}reavaliarVersoes(e){const t=this.estados.get(e);t&&(t.motor.reavaliarVersoes(t.layerDef.id),this.pedirBase(t))}feicaoVisivel(e,t){const o=this.estados.get(e);return!o||o.motor.feicaoVisivel(o.layerDef.id,t)}consultarProximas(e,t){const o=this.estados.get(e);return o?o.motor.consultarCaixa(o.layerDef.id,t):[]}previsualizar(e,t){const o=this.estados.get(e);if(!o)return;const i=o.layerDef.id,n=!o.motor.temPrevia(i,t.id);o.motor.previsualizar(i,t),n&&this.pedirBase(o);const r=ee.get(o.map);r&&Ee(r)}aplicarSelecao(e,t){const o=this.estados.get(e);if(!o)return;const i=o.layerDef.id;this.selecionadas.set(o.layerDef,new Set(t));const{entrou:n,saiu:r}=o.motor.selecionar(i,t);if(n.length===0&&r.length===0)return;const s=[...n,...r];for(const l of s)this.atualizarSelecaoDom(o,l);o.motor.selecaoAfetaAgrupamento(i,s)&&this.pedirDom(o);const c=ee.get(o.map);c&&Ee(c)}estatisticas(e){const t=this.estados.get(e);if(!t)return null;const o=this.listaAtual(t),i=(o==null?void 0:o.estatisticas)??t.motor.estatisticas(t.layerDef.id);return i?{total:i.total,materializadas:i.desenhadas+i.marcadoresDom,marcasLOD:i.marcasLOD,clusters:i.clusters,avaliacoesLOD:i.avaliacoesLOD,desenhadas:i.desenhadas,marcadoresDom:i.marcadoresDom,canvases:2,renderizador:"canvas"}:null}idsDesenhados(e){const t=this.estados.get(e);if(!t)return null;const o=this.listaAtual(t);if(!o)return{materializadas:[],marcas:[]};const i=t.motor.selecionadas(t.layerDef.id),n=new Set,r=new Set;for(const l of o.itens)l.forma==="cluster"||l.forma==="rotulo"||(l.forma==="marca"?i.has(l.id)?n.add(l.id):r.add(l.id):n.add(l.id));const s=t.base.quadroAtual(),c=s?t.motor.listaSobreposicao(t.layerDef.id,ae(s)):null;for(const l of(c==null?void 0:c.itens)??[])n.add(l.id);return{materializadas:[...n].sort(),marcas:[...r].sort()}}redesenharAgora(e){var o;const t=this.estados.get(e);t&&(t.base.pintar(),(o=ee.get(t.map))==null||o.canvas.pintar())}defMotor(e){return{id:e.id,zIndex:e.zIndex,opacidade:e.opacidade,visivel:e.visivel,interativo:e.interativo,bloqueada:e.bloqueada,estilo:e.estilo??{}}}feicoesDe(e){const t=e.dados,o=Array.isArray(t)?t:t==null?void 0:t.feicoes;return Array.isArray(o)?o:[]}pedirBase(e){e.agendado||!e.vivo||(e.agendado=!0,mt(()=>{e.agendado=!1,e.vivo&&e.base.pintar()}))}pedirDom(e){e.agendadoDom||!e.vivo||(e.agendadoDom=!0,mt(()=>{if(e.agendadoDom=!1,!e.vivo)return;const t=e.base.quadroAtual();if(!t)return;const o=e.motor.listaDesenho(ae(t),{camadas:[e.layerDef.id],parte:"dom"}).camadas[0];o&&this.sincronizarDom(e,o)}))}listaAtual(e){const t=e.base.quadroAtual();return t?e.motor.listaDesenho(ae(t),{camadas:[e.layerDef.id]}).camadas[0]??null:e.ultima}vistaDaFaixa(e,t){const o=ga,[i,n]=m.latLonDoMundo(e.origemPx.x+t.x-o,e.origemPx.y+t.y-o,e.zoom),[r,s]=m.latLonDoMundo(e.origemPx.x+t.x+t.largura+o,e.origemPx.y+t.y+t.altura+o,e.zoom);return{...ae(e),larguraPx:t.largura,alturaPx:t.altura,caixa:{minLat:r,maxLat:i,minLon:n,maxLon:s}}}pintarBase(e,t){if(!e.vivo)return!t.branco;e.quadro=t;const o=e.layerDef.id;let i;if(t.regioes){i=0;for(const s of t.regioes){const c=this.vistaDaFaixa(t,s),l=e.motor.listaDesenho(c,{camadas:[o],parte:"canvas"}),d=pt(l.camadas[0]);d!==0&&(e.pintor.desenhar(l,c,{limpar:!1,recorte:s}),i+=d)}const r=e.motor.listaDesenho(ae(t),{camadas:[o],parte:"dom"}).camadas[0];r&&this.sincronizarDom(e,r)}else{const r=ae(t),s=e.motor.listaDesenho(r,{camadas:[o]}),c=s.camadas[0]??null,l=pt(c);c?l===0&&t.branco?i=0:(e.pintor.desenhar(s,r),i=l):i=!t.branco,e.ultima=c,c&&this.sincronizarDom(e,c)}const n=ee.get(e.map);return n&&Ee(n),i}acao(e,t,o){var n,r;if(!t)return;const i=o==null?void 0:o.originalEvent;(r=(n=e.context).onLayerAction)==null||r.call(n,"feicao-clique",{camadaId:e.layerDef.id,feicao:e.motor.feicao(e.layerDef.id,t.id)??t,aditivo:!!(i&&(i.ctrlKey||i.metaKey||i.shiftKey))})}sincronizarDom(e,t){const o=new Set;for(const i of t.itens){if(!ya.has(i.forma))continue;const n=`${i.forma}:${i.id}`;o.add(n);try{this.colocarDom(e,n,i)}catch{const r=e.dom.get(n);r&&e.grupo.removeLayer(r.layer),e.dom.delete(n)}}for(const[i,n]of e.dom)o.has(i)||(e.grupo.removeLayer(n.layer),e.dom.delete(i))}colocarDom(e,t,o){var d,h;const{map:i,layerDef:n,grupo:r}=e,s=o.feicao??null,c=e.dom.get(t),l=n.estilo??{};if(o.forma==="icone"&&s&&o.coordenada){if(c){c.fonte!==s?(c.layer.setLatLng(o.coordenada),c.layer.setIcon(Te(s,l,o.selecionada)),c.fonte=s,c.selecionada=o.selecionada):c.selecionada!==o.selecionada&&this.trocarIcone(c,s,l,o.selecionada);return}const u=b.marker(o.coordenada,{icon:Te(s,l,o.selecionada),pane:U(i,n.id,"ponto"),interactive:e.interativo,keyboard:!1});u.on("click",g=>this.acao(e,s,g)),r.addLayer(u),e.dom.set(t,{layer:u,fonte:s,selecionada:o.selecionada,assinatura:""});return}if(o.forma==="texto"&&s&&o.coordenada){if(c){if(c.fonte!==s){const g=c.layer;g.setLatLng(o.coordenada),g.setIcon(Fe(s,l,o.selecionada)),e.interativo&&!s.bloqueada?(d=g.dragging)==null||d.enable():(h=g.dragging)==null||h.disable(),c.fonte=s,c.selecionada=o.selecionada}else c.selecionada!==o.selecionada&&this.trocarIcone(c,s,l,o.selecionada);return}const u=b.marker(o.coordenada,{icon:Fe(s,l,o.selecionada),pane:U(i,n.id,"texto"),interactive:e.interativo,draggable:e.interativo&&!s.bloqueada,keyboard:!1});u.on("click",g=>this.acao(e,s,g)),u.on("dragend",()=>{var A,w;const g=e.motor.feicao(n.id,s.id)??s;if(g.geometria.tipo!=="Text")return;const{lat:v,lng:p}=u.getLatLng(),y={...g,geometria:{...g.geometria,coordenada:[v,p]}};(w=(A=e.context).onLayerAction)==null||w.call(A,"feicao-movida",{camadaId:n.id,feicao:y})}),r.addLayer(u),e.dom.set(t,{layer:u,fonte:s,selecionada:o.selecionada,assinatura:""});return}if(o.forma==="cluster"&&o.coordenada){const u=o.total??0,g=`${o.id}:${u}:${o.restantes??0}:${o.coordenada[0].toFixed(7)}:${o.coordenada[1].toFixed(7)}`;if((c==null?void 0:c.assinatura)===g)return;c&&r.removeLayer(c.layer);const v=b.marker(o.coordenada,{icon:Qo(u,l),pane:U(i,n.id,"ponto"),keyboard:!1});v.bindTooltip(`${u} feições agrupadas`,{direction:"top"}),v.on("click",()=>{const p=e.motor.membrosDoCluster(n.id,o.id);p.length>0&&i.fitBounds(b.latLngBounds(p.map(y=>y.coordenada)),{padding:[60,60],maxZoom:18})}),r.addLayer(v),e.dom.set(t,{layer:v,fonte:null,selecionada:!1,assinatura:g});return}if(o.forma==="rotulo"&&o.coordenada&&o.texto){const u=`${o.texto}:${o.coordenada[0]}:${o.coordenada[1]}`;if((c==null?void 0:c.assinatura)===u)return;c&&r.removeLayer(c.layer);const g=document.createElement("span");g.textContent=o.texto;const v=b.marker(o.coordenada,{icon:b.divIcon({className:"cad-feicao-rotulo-ancora",iconSize:[0,0]}),pane:U(i,n.id,"texto"),interactive:!1,keyboard:!1});v.bindTooltip(g,{permanent:!0,direction:"center",className:"cad-feicao-rotulo",interactive:!1}),r.addLayer(v),e.dom.set(t,{layer:v,fonte:null,selecionada:!1,assinatura:u});return}if(o.forma==="curva"&&s){const u=s.geometria,g=p=>ut(m.estiloVetorDe(s,l,p),e.interativo);if(c){const p=c.layer;c.fonte!==s?(ko(p,u),p.setStyle(g(o.selecionada)),c.fonte=s,c.selecionada=o.selecionada):c.selecionada!==o.selecionada&&(p.setStyle(g(o.selecionada)),c.selecionada=o.selecionada);return}const v=Et(u,{...g(o.selecionada),pane:U(i,n.id,u.tipo==="Polygon"?"poligono":"linha")});if(!v||!m.nosDaGeometria(u))return;v.on("click",p=>this.acao(e,s,p)),r.addLayer(v),e.dom.set(t,{layer:v,fonte:s,selecionada:o.selecionada,assinatura:""})}}trocarIcone(e,t,o,i){e.layer.setIcon(t.geometria.tipo==="Text"?Fe(t,o,i):Te(t,o,i)),e.selecionada=i}atualizarSelecaoDom(e,t){const o=e.motor.feicao(e.layerDef.id,t);if(!o)return;const i=e.motor.selecionadas(e.layerDef.id).has(t),n=e.layerDef.estilo??{};for(const s of[`icone:${t}`,`texto:${t}`]){const c=e.dom.get(s);c&&c.selecionada!==i&&this.trocarIcone(c,o,n,i)}const r=e.dom.get(`curva:${t}`);r&&r.selecionada!==i&&(r.layer.setStyle(ut(m.estiloVetorDe(o,n,i),e.interativo)),r.selecionada=i)}registrarHit(e){const t={alvo:e.base,consultar:o=>{const{map:i,layerDef:n,motor:r}=e;if(!e.vivo||!e.interativo||!n.visivel||!ba(i))return[];const s=i.layerPointToContainerPoint(o),c=i.containerPointToLatLng([s.x-we,s.y+we]),l=i.containerPointToLatLng([s.x+we,s.y-we]),d={minLat:Math.min(c.lat,l.lat),maxLat:Math.max(c.lat,l.lat),minLon:Math.min(c.lng,l.lng),maxLon:Math.max(c.lng,l.lng)},h=r.consultarCaixa(n.id,d).filter(v=>{var y;if(!r.feicaoVisivel(n.id,v))return!1;const p=v.geometria;return p.tipo==="Text"||m.nosDaGeometria(p)?!1:p.tipo==="Point"?!((y=v.estilo)!=null&&y.icone)&&!r.pontoAgrupado(n.id,v.id):!0}),u=v=>{const p=i.latLngToContainerPoint(v);return{x:p.x,y:p.y}},g=[];for(let v=0;v<va&&h.length>0;v++){const p=Le({x:s.x,y:s.y},h,u);if(!p)break;h.splice(h.indexOf(p),1);const y=r.caixaDe(n.id,p.id),A=y?(()=>{const w=i.latLngToContainerPoint([y.minLat,y.minLon]),x=i.latLngToContainerPoint([y.maxLat,y.maxLon]);return Math.abs(x.x-w.x)*Math.abs(x.y-w.y)})():0;g.push({feicao:p,chave:p.id,distancia:0,area:Number.isFinite(A)?A:0,tipo:p.geometria.tipo==="Point"?"ponto":p.geometria.tipo==="LineString"?"linha":"poligono"})}return g}};e.fonteHit=t,St(e.map,e.layerDef.id,t),e.base.on("click",o=>{var s,c;const{feicaoHit:i,originalEvent:n}=o;if(!i||!e.vivo)return;const r=n;(c=(s=e.context).onLayerAction)==null||c.call(s,"feicao-clique",{camadaId:e.layerDef.id,feicao:i,aditivo:!!(r&&(r.ctrlKey||r.metaKey||r.shiftKey))})})}}function ge(a){return String(a??"").trim().toLowerCase()==="canvas"?"canvas":"leaflet"}class ai{constructor(e=new ei,t=new ii){f(this,"roteamento",new WeakMap);this.leaflet=e,this.canvas=t}modo(e){var t;try{return ge((t=e.renderizador)==null?void 0:t.call(e))}catch{return"leaflet"}}de(e){return this.roteamento.get(e)??this.leaflet}modoDe(e){return this.roteamento.get(e)===this.canvas?"canvas":"leaflet"}render(e,t,o){const i=this.modo(o)==="canvas"?this.canvas:this.leaflet,n=i.render(e,t,o);return n&&this.roteamento.set(n,i),n}update(e,t,o,i,n){this.de(t).update(e,t,o,i,n)}destroy(e,t){this.de(e).destroy(e,t),this.roteamento.delete(e)}reavaliarVersoes(e){this.de(e).reavaliarVersoes(e)}feicaoVisivel(e,t){return this.de(e).feicaoVisivel(e,t)}consultarProximas(e,t){return this.de(e).consultarProximas(e,t)}previsualizar(e,t){this.de(e).previsualizar(e,t)}estatisticas(e){const t=this.de(e).estatisticas(e);return t?{renderizador:this.modoDe(e),...t}:null}idsDesenhados(e){return this.de(e).idsDesenhados(e)}aplicarSelecao(e,t){this.de(e).aplicarSelecao(e,t)}}N.register("tile",new bo);N.register("wms",new xo);N.register("vetorial-linhas",new Co);N.register("vetorial-pontos",new So);N.register("vetorial-poligonos",new Mo);N.register("grid",new Ao);N.register("feicoes",new ai);const gt=[{id:"satelite",nome:"Satélite Google Híbrido",categoria:"base",tipo:"tile",visivel:!0,opacidade:1,zIndex:200,interativo:!1,bloqueada:!1,estilo:{scaleMode:"screen"}},{id:"sigef",nome:"Acervo Fundiário SIGEF (INCRA)",categoria:"wms",tipo:"wms",visivel:!0,opacidade:.85,zIndex:390,interativo:!0,bloqueada:!1,estilo:{scaleMode:"screen"}},{id:"homologados",nome:"Poligonal Homologada (Banco)",categoria:"referencia",tipo:"vetorial-linhas",visivel:!0,opacidade:.9,zIndex:420,interativo:!0,bloqueada:!1,estilo:{corPrimaria:"#f59e0b",espessuraLinha:1,dashArray:"6, 8",scaleMode:"screen"}},{id:"homologados-pontos",nome:"Marcos Homologados (Banco)",categoria:"referencia",tipo:"vetorial-pontos",visivel:!0,opacidade:1,zIndex:430,interativo:!0,bloqueada:!1,estilo:{tamanhoMarcador:8,estiloMarcador:"circle",scaleMode:"screen"}},{id:"perimetro",nome:"Divisas e Poligonal do Imóvel",categoria:"levantamento",tipo:"vetorial-linhas",visivel:!0,opacidade:1,zIndex:520,interativo:!0,bloqueada:!1,estilo:{corPrimaria:"#00f5a0",espessuraLinha:1,scaleMode:"screen",dimensaoMetros:.3}},{id:"vizinhos",nome:"Imóveis Confrontantes (WKT/CSV)",categoria:"referencia",tipo:"vetorial-poligonos",visivel:!0,opacidade:.8,zIndex:440,interativo:!0,bloqueada:!1,estilo:{corPrimaria:"#a855f7",espessuraLinha:1,dashArray:"4, 6",scaleMode:"screen"}},{id:"vertices",nome:"Vértices e Marcos do Levantamento",categoria:"levantamento",tipo:"vetorial-pontos",visivel:!0,opacidade:1,zIndex:650,interativo:!0,bloqueada:!1,estilo:{tamanhoMarcador:8,scaleMode:"screen",dimensaoMetros:.25}},{id:"grade",nome:"Grade de Coordenadas UTM",categoria:"referencia",tipo:"grid",visivel:!0,opacidade:.5,zIndex:700,interativo:!1,bloqueada:!1,estilo:{corPrimaria:"rgba(0, 245, 160, 0.18)",espessuraLinha:.6,scaleMode:"screen"}}],Ca=new Set(["tile","wms","grid"]);class ni{constructor(e){f(this,"layers",[]);f(this,"layerInstances",new Map);f(this,"map",null);f(this,"context",null);f(this,"listeners",[]);f(this,"renderPendente",!1);this.layers=(e||gt).map(t=>({...t,estilo:{...t.estilo}}))}descartarCamadasPadrao(){if(this.map)return;const e=new Set(gt.map(t=>t.id));this.layers=this.layers.filter(t=>!e.has(t.id)||t.tipo==="feicoes")}attachMap(e,t){this.map=e,this.context=t,this.ensurePanes(),this.renderAllLayers()}ensurePanes(){this.map&&this.layers.forEach(e=>{const t=`pane-${e.id}`;let o=this.map.getPane(t);o||(o=this.map.createPane(t)),o&&(o.style.zIndex=String(e.zIndex),o.style.pointerEvents=e.interativo&&!e.bloqueada&&e.visivel?"auto":"none")})}renderAllLayers(e=!1){this.renderPendente=!1,!(!this.map||!this.context)&&(this.layers.forEach(t=>{if(!(e&&Ca.has(t.tipo)&&t.visivel&&this.layerInstances.has(t.id))){if(this.layerInstances.has(t.id)){const o=this.layerInstances.get(t.id),i=N.get(t.tipo);i&&i.destroy(o,this.map),this.layerInstances.delete(t.id)}if(t.visivel){const o=N.get(t.tipo);if(o){const i=o.render(t,this.map,this.context);i&&(i.addTo(this.map),this.layerInstances.set(t.id,i))}}}}),this.notifyChange())}recriarCamadasDoTipo(e){if(this.flushRender(),!this.map||!this.context)return;const t=N.get(e);if(t){for(const o of this.layers){if(o.tipo!==e)continue;const i=this.layerInstances.get(o.id);if(i&&(t.destroy(i,this.map),this.layerInstances.delete(o.id)),!o.visivel)continue;const n=t.render(o,this.map,this.context);n&&(n.addTo(this.map),this.layerInstances.set(o.id,n))}this.notifyChange()}}flushRender(){this.renderPendente&&this.renderAllLayers(!0)}agendarRender(){this.renderPendente||(this.renderPendente=!0,queueMicrotask(()=>this.flushRender()))}setLayerVisibility(e,t){this.flushRender();const o=this.layers.find(r=>r.id===e);if(!o||o.visivel===t||(o.visivel=t,!this.map||!this.context))return;const i=`pane-${o.id}`,n=this.map.getPane(i);if(n&&(n.style.display=t?"":"none",n.style.pointerEvents=o.visivel&&o.interativo&&!o.bloqueada?"auto":"none"),t){if(!this.layerInstances.has(e)){const r=N.get(o.tipo);if(r){const s=r.render(o,this.map,this.context);s&&(s.addTo(this.map),this.layerInstances.set(e,s))}}}else if(this.layerInstances.has(e)){const r=this.layerInstances.get(e),s=N.get(o.tipo);s&&s.destroy(r,this.map),this.layerInstances.delete(e)}this.notifyChange()}setLayerOpacity(e,t){this.flushRender();const o=this.layers.find(n=>n.id===e);if(!o)return;if(o.opacidade=Math.max(0,Math.min(1,t)),this.map){const n=this.map.getPane(`pane-${e}`);n&&(n.style.opacity=String(o.opacidade))}const i=this.layerInstances.get(e);if(i&&this.map&&this.context){const n=N.get(o.tipo);n&&n.update(o,i,{opacidade:o.opacidade},this.context,this.map)}this.notifyChange()}setLayerZIndex(e,t){const o=this.layers.find(i=>i.id===e);if(o){if(o.zIndex=t,this.map){const i=this.map.getPane(`pane-${e}`);i&&(i.style.zIndex=String(t))}this.notifyChange()}}setLayerBlocked(e,t){const o=this.layers.find(i=>i.id===e);if(o){if(o.bloqueada=t,this.map){const i=this.map.getPane(`pane-${e}`);i&&(i.style.pointerEvents=o.visivel&&o.interativo&&!t?"auto":"none")}this.notifyChange()}}setLayerScaleMode(e,t){this.flushRender();const o=this.layers.find(n=>n.id===e);if(!o)return;o.estilo.scaleMode=t;const i=this.layerInstances.get(e);if(i&&this.map&&this.context){const n=N.get(o.tipo);n&&n.update(o,i,{estilo:o.estilo},this.context,this.map)}this.notifyChange()}setGraphicScale(e){this.context&&(this.context.graphicScale={...this.context.graphicScale,...e},this.agendarRender())}updateContext(e){this.context&&(this.context={...this.context,...e},this.agendarRender())}getLayers(){return[...this.layers]}getActiveSelectableLayers(){return this.layers.filter(e=>e.visivel&&e.interativo&&!e.bloqueada)}isLayerActiveAndSelectable(e){const t=this.layers.find(o=>o.id===e);return!!(t&&t.visivel&&t.interativo&&!t.bloqueada)}exportState(){return this.layers.map(e=>({id:e.id,visivel:e.visivel,opacidade:e.opacidade,zIndex:e.zIndex,bloqueada:e.bloqueada,estilo:{...e.estilo}}))}importState(e){!e||!Array.isArray(e)||(e.forEach(t=>{const o=this.layers.find(i=>i.id===t.id);o&&(t.visivel!==void 0&&(o.visivel=t.visivel),t.opacidade!==void 0&&(o.opacidade=t.opacidade),t.zIndex!==void 0&&(o.zIndex=t.zIndex),t.bloqueada!==void 0&&(o.bloqueada=t.bloqueada),t.estilo&&(o.estilo={...o.estilo,...t.estilo}))}),this.ensurePanes(),this.renderAllLayers())}onChange(e){return this.listeners.push(e),()=>{this.listeners=this.listeners.filter(t=>t!==e)}}notifyChange(){const e=this.getLayers();this.listeners.forEach(t=>{try{t(e)}catch(o){console.error("Erro no listener de camadas:",o)}})}getAllLayerInstances(){return this.flushRender(),Array.from(this.layerInstances.values())}getLayerInstance(e){return this.flushRender(),this.layerInstances.get(e)}getLayer(e){return this.layers.find(t=>t.id===e)}getLayerDef(e){return this.layers.find(t=>t.id===e)}getOrCreateLayer(e,t,o){let i=this.layers.find(n=>n.id===e);return i||(i={id:e,nome:o,categoria:"custom",tipo:t,visivel:!0,opacidade:1,zIndex:600,interativo:!0,bloqueada:!1,estilo:{scaleMode:"screen"}},this.layers.push(i),this.ensurePanes()),i}setLayerData(e,t){this.flushRender();const o=this.layers.find(n=>n.id===e);if(!o)return;o.dados=t;const i=this.layerInstances.get(e);if(i&&this.map&&this.context){const n=N.get(o.tipo);n&&n.update(o,i,{dados:t},this.context,this.map)}else if(o.visivel&&this.map&&this.context){const n=N.get(o.tipo);if(n){const r=n.render(o,this.map,this.context);r&&(r.addTo(this.map),this.layerInstances.set(e,r))}}this.notifyChange()}clearLayers(e){this.flushRender(),(e&&e.length>0?e:Array.from(this.layerInstances.keys())).forEach(o=>{if(this.layerInstances.has(o)){const i=this.layerInstances.get(o),n=this.layers.find(r=>r.id===o);if(n){const r=N.get(n.tipo);r&&r.destroy(i,this.map)}this.layerInstances.delete(o)}}),this.notifyChange()}destroy(){this.renderPendente=!1,this.map&&(this.layerInstances.forEach((e,t)=>{const o=this.layers.find(i=>i.id===t);if(o){const i=N.get(o.tipo);i&&i.destroy(e,this.map)}}),this.layerInstances.clear()),this.listeners=[]}}function ri(a,e){var r,s;if(e==null)return null;const t=String(e).trim(),o=c=>c?(c.lon=c.lng,c):null,n=a.getMarkers().find(c=>{var g,v,p,y;const l=c.pontoId,d=c.elementoId??c.id??((g=c.options)==null?void 0:g.pontoId)??((v=c.options)==null?void 0:v.id),h=(p=c.elemento)==null?void 0:p.nome_vertice,u=(y=c.elemento)==null?void 0:y.codigo_completo;return String(l)===t||String(d)===t||h&&String(h).toLowerCase()===t.toLowerCase()||u&&String(u).toLowerCase()===t.toLowerCase()});if(n&&typeof n.getLatLng=="function")return o(n.getLatLng());if(a.layerManager)for(const c of a.layerManager.getAllLayerInstances()){let l=null;const d=h=>{var v,p,y,A,w;if(l)return;const u=h.pontoId??h.elementoId??h.id??((v=h.options)==null?void 0:v.id)??((p=h.options)==null?void 0:p.pontoId),g=((y=h.elemento)==null?void 0:y.nome)??((A=h.elemento)==null?void 0:A.nome_vertice)??((w=h.options)==null?void 0:w.nome);(String(u)===t||g&&String(g).toLowerCase()===t.toLowerCase())&&(typeof h.getLatLng=="function"?l=h.getLatLng():typeof h.getBounds=="function"&&(l=h.getBounds().getCenter()))};if(d(c),typeof c.eachLayer=="function"&&c.eachLayer(d),l)return o(l)}if(a.context.pontos&&a.context.pontos.length>0){const c=a.context.pontos.find(l=>String(l.id)===t||l.nome_vertice&&String(l.nome_vertice).toLowerCase()===t.toLowerCase());if(c){const l=c.lat??c.latitude??c.y,d=c.lon??c.lng??c.longitude??c.x,h=M.parseCoordenada(l,d);if(h)return o(b.latLng(h.lat,h.lon))}}if(a.context.bancoPontos&&a.context.bancoPontos.length>0){const c=a.context.bancoPontos.find(l=>String(l.id)===t||l.codigo_completo&&String(l.codigo_completo).toLowerCase()===t.toLowerCase()||l.nome_vertice&&String(l.nome_vertice).toLowerCase()===t.toLowerCase());if(c){const l=c.lat??c.latitude??c.y,d=c.lon??c.lng??c.longitude??c.x,h=M.parseCoordenada(l,d);if(h)return o(b.latLng(h.lat,h.lon))}}if(a.context.confrontantes&&a.context.confrontantes.length>0){const c=a.context.confrontantes.find(l=>String(l.id)===t||l.nome&&String(l.nome).toLowerCase()===t.toLowerCase()||l.nome_propriedade&&String(l.nome_propriedade).toLowerCase()===t.toLowerCase());if(c){if(c.pontos&&c.pontos.length>0){let l=0,d=0,h=0;for(const u of c.pontos){const g=u.lat??u.latitude??u.y,v=u.lon??u.lng??u.longitude??u.x,p=M.parseCoordenada(g,v);p&&(l+=p.lat,d+=p.lon,h++)}if(h>0)return o(b.latLng(l/h,d/h))}if(c.poligono_wkt){const l=M.extrairCentroDeWkt(c.poligono_wkt);if(l)return o(b.latLng(l.lat,l.lon))}}}if(a.context.segmentos&&a.context.segmentos.length>0){const c=a.context.segmentos.find(l=>String(l.id)===t||`${l.ponto_inicio_id}-${l.ponto_fim_id}`===t);if(c){const l=(r=a.context.pontos)==null?void 0:r.find(h=>String(h.id)===String(c.ponto_inicio_id)),d=(s=a.context.pontos)==null?void 0:s.find(h=>String(h.id)===String(c.ponto_fim_id));if(l&&d){const h=M.parseCoordenada(l.lat??l.latitude,l.lon??l.longitude),u=M.parseCoordenada(d.lat??d.latitude,d.lon??d.longitude);if(h&&u)return o(b.latLng((h.lat+u.lat)/2,(h.lon+u.lon)/2))}}}if(a.layerManager){for(const c of a.layerManager.getLayers())if(c.dados){if(Array.isArray(c.dados.pontos)){const l=c.dados.pontos.find(d=>String(d.id)===t||d.nome_vertice&&String(d.nome_vertice)===t);if(l){const d=M.parseCoordenada(l.lat,l.lon);if(d)return o(b.latLng(d.lat,d.lon))}}if(Array.isArray(c.dados.poligonos)){const l=c.dados.poligonos.find(d=>String(d.id)===t);if(l){if(l.wkt){const d=M.extrairCentroDeWkt(l.wkt);if(d)return o(b.latLng(d.lat,d.lon))}if(Array.isArray(l.coordenadas)&&l.coordenadas.length>0){let d=0,h=0,u=0;for(const g of l.coordenadas){const v=M.parseCoordenada(g[0],g[1])||M.parseCoordenada(g[1],g[0]);v&&(d+=v.lat,h+=v.lon,u++)}if(u>0)return o(b.latLng(d/u,h/u))}}}}}return null}function La(a,e,t,o){var g,v;vt(e,a.getMap());const i=a.getMap();if(!i)return;const n=ri(a,t);if(!n){console.warn(`[ui-canvas-cad] Elemento com identificador "${t}" não encontrado para destaque.`);return}const r=(o==null?void 0:o.pan)===!0,s=o==null?void 0:o.zoom;r?s!==void 0?typeof i.flyTo=="function"?i.flyTo(n,s,{animate:!0}):i.setView(n,s,{animate:!0}):typeof i.panTo=="function"?i.panTo(n,{animate:!0}):i.setView(n,i.getZoom(),{animate:!0}):s!==void 0&&i.setZoom(s,{animate:!0});const c=(o==null?void 0:o.cor)||"#00f5a0",l="pane-destaque";let d=i.getPane(l);d||(d=i.createPane(l)),d&&(d.style.zIndex="850",d.style.pointerEvents="none");const h=b.divIcon({className:"cad-destaque-marker-container",html:`
|
|
100
|
+
<div class="cad-pulse-highlight" style="--cad-pulse-cor: ${M.escapeHtml(c)};">
|
|
101
101
|
<div class="cad-pulse-core"></div>
|
|
102
102
|
<div class="cad-pulse-ring ring-1"></div>
|
|
103
103
|
<div class="cad-pulse-ring ring-2"></div>
|
|
104
104
|
</div>
|
|
105
|
-
`,iconSize:[52,52],iconAnchor:[26,26]});t.destaqueMarker=v.marker(n,{icon:h,pane:l,interactive:!1,keyboard:!1}),t.destaqueMarker.addTo(i);const u=(m=(g=t.destaqueMarker).getElement)==null?void 0:m.call(g);u&&(u.style.pointerEvents="none"),o!=null&&o.duracaoMs&&o.duracaoMs>0&&(t.destaqueTimeoutId=window.setTimeout(()=>{we(t,i)},o.duracaoMs))}function we(a,t){a.destaqueTimeoutId!==null&&(window.clearTimeout(a.destaqueTimeoutId),a.destaqueTimeoutId=null),a.destaqueMarker&&(t&&t.hasLayer(a.destaqueMarker)?t.removeLayer(a.destaqueMarker):typeof a.destaqueMarker.remove=="function"&&a.destaqueMarker.remove(),a.destaqueMarker=null)}function Ha(a,t){const e=new Map;a.forEach(i=>{const n=i.lat??i.latitude??i.y,r=i.lon??i.lng??i.longitude??i.x,s=S.parseCoordenada(n,r);s&&(i.lat=s.lat,i.lon=s.lon);const c=i.confrontante_id??i.id_confrontante??0;e.has(c)||e.set(c,[]),e.get(c).push(i)});const o=new Map;return t.forEach(i=>{const n=i.id!==void 0&&i.id!==null?i.id:0;o.set(n,{...i,pontos:[]})}),e.forEach((i,n)=>{var r,s;if(o.has(n)){const c=o.get(n);c.pontos=i}else o.set(n,{id:n,nome:((r=i[0])==null?void 0:r.nome_confrontante)||"Confrontante",nome_propriedade:((s=i[0])==null?void 0:s.nome_propriedade)||"",pontos:i})}),Array.from(o.values()).filter(i=>i.pontos&&i.pontos.length>0||!!i.poligono_wkt)}function Va(a,t){const e=new Map;return t.forEach(o=>{o.id!==void 0&&o.id!==null&&o.pontos&&o.pontos.length>0&&e.set(o.id,o.pontos)}),a.map(o=>{const i=o.id!==void 0&&o.id!==null?o.id:void 0;return i!==void 0&&(!o.pontos||o.pontos.length===0)&&e.has(i)?{...o,pontos:e.get(i)}:{...o}})}function Ga(a,t,e=!1){let o=[...a];e&&t&&t.forEach(n=>{n.pontos&&o.push(...n.pontos)});const i=o.map(n=>{const r=n.lat??n.latitude??n.y,s=n.lon??n.lng??n.longitude??n.x,c=S.parseCoordenada(r,s);return c?v.latLng(c.lat,c.lon):null}).filter(n=>n!==null);return i.length===1?{single:i[0]}:i.length>1?{bounds:v.latLngBounds(i)}:null}function ja(a,t){var n;(n=t==null?void 0:t.flushRender)==null||n.call(t);const e=[],o=new Set,i=r=>{r instanceof v.Marker&&r.pontoId!==void 0&&!o.has(r)&&(o.add(r),e.push(r))};return a&&a.eachLayer(r=>{i(r),typeof r.eachLayer=="function"&&r.eachLayer(i)}),t&&t.getAllLayerInstances().forEach(r=>{i(r),typeof r.eachLayer=="function"&&r.eachLayer(i)}),e}function Ua(a,t,e="vertices",o){const i=t||[];a.layerManager.getOrCreateLayer(e,"vetorial-pontos","Pontos / Vértices"),e==="vertices"&&(a.context.pontos=i,a.canvasInteracao.ctx.pontosList=i,o&&(a.customMarkerClickCallback=n=>{const r=i.find(s=>String(s.id)===String(n))||{id:n,lat:0,lon:0};o(r)})),a.layerManager.setLayerData(e,{pontos:i,onClique:o}),a.layerManager.setLayerVisibility(e,!0)}function Wa(a,t,e="linhas"){const o=t||[];a.layerManager.getOrCreateLayer(e,"vetorial-linhas","Conexões / Linhas"),(e==="linhas"||e==="perimetro")&&(a.context.segmentos=o.map(i=>({ponto_inicio_id:Number(i.origemId)||0,ponto_fim_id:Number(i.destinoId)||0,tipo_limite_sigef:i.tipoLinha==="tracejada"?"LN1":"LA1"}))),a.layerManager.setLayerData(e,{conexoes:o}),a.layerManager.setLayerVisibility(e,!0)}function Xa(a,t,e=!0,o="polilinha",i){const n=t||[];a.layerManager.getOrCreateLayer(o,"vetorial-linhas","Polilinhas"),(o==="polilinha"||o==="perimetro")&&(a.context.pontos=n,a.context.segmentos=[],a.canvasInteracao.ctx.pontosList=n);const r=i||a.chaveGrupo||a.context.chaveGrupo;a.layerManager.setLayerData(o,{pontos:n,fechar:e!==!1,polilinhaSequencial:!0,chaveGrupo:r}),a.layerManager.setLayerVisibility(o,!0)}function Za(a,t,e="poligonos"){const o=t||[];a.layerManager.getOrCreateLayer(e,"vetorial-poligonos","Polígonos"),a.layerManager.setLayerData(e,{poligonos:o}),a.layerManager.setLayerVisibility(e,!0)}function Ya(a,t,e){const o=t||[];if(e!=null){const i=e||[];a.context.pontos=i,a.canvasInteracao.ctx.pontosList=i}a.context.segmentos=o,a.layerManager.updateContext({segmentos:o,...e!=null?{pontos:a.context.pontos}:{}})}function Ka(a,t=!1){a.context.pontos=[],a.context.segmentos=[],a.context.confrontantes=[],a.canvasInteracao.ctx.pontosList=[],a.canvasInteracao.limparSelecao();const e={pontos:[],segmentos:[],confrontantes:[]};t||(a.context.bancoPontos=[],e.bancoPontos=[]),a.layerManager.updateContext(e)}function uo(a){return a!=null&&!isNaN(Number(a))&&String(a).trim()!==""?Number(a):a}function Ja(a,t){var s,c;const e=a.core.map,o=a.layerManager.getLayerDef(t.layerId),i=t.baseSize||8,n=((s=a.context.graphicScale)==null?void 0:s.markerScaleMultiplier)||1;if(e&&((c=o==null?void 0:o.estilo)==null?void 0:c.scaleMode)==="world"){const l=o.estilo.dimensaoMetros||.25,d=e.getCenter(),h=e.getZoom(),u=40075016686e-3*Math.abs(Math.cos(d.lat*Math.PI/180))/Math.pow(2,h+8),g=l/(u>0?u:1);return Math.max(3,Math.round(g*n))}const r=qe(t.densTotal||0,(e==null?void 0:e.getZoom())??18);return Math.max(r<1?5:4,Math.round(i*n*r))}function Qa(a,t,e,o,i){const n=Ja(a,e),r=a.context.config.enableAnimations?"cad-pt-anim":"",s=At(e.shapeStyle,n,e.markerBg,r,`map-marker-${e.layerId||"pts"}-${o}`,i,{densidade:Zt(e.densTotal||0)});e.tamanhoPx=n,t.setIcon(v.divIcon({html:s,className:`custom-leaflet-marker ${i?"cad-marker-selected ponto-selecionado":""}`,iconSize:[n+6,n+6]}))}function tn(a){const t=a.context.selectedPontoIds||[],e=a.canvasInteracao.ctx.selectedVizinhoPontoIds||[],o=new Set([...t.map(String),...e.map(String)]);for(const i of a.getMarkers()){const n=i,r=n.pontoId;if(r==null)continue;const s=o.has(String(r));if(n.isSelected===s)continue;n.isSelected=s,i.setZIndexOffset(s?2e3:0),n.shapeStyle&&n.baseSize&&n.markerBg&&Qa(a,i,n,r,s);const c=i.getElement();c&&(s?c.classList.add("cad-marker-selected","ponto-selecionado"):c.classList.remove("cad-marker-selected","ponto-selecionado"))}}class ne{constructor(t){p(this,"core");p(this,"layerManager");p(this,"canvasInteracao");p(this,"context");p(this,"modoCliqueSequencialAtivo",!1);p(this,"chaveGrupo");p(this,"zonaProjecao",22);p(this,"levantamentoId",null);p(this,"customMarkerClickCallback");p(this,"customPopupActionCallback");p(this,"destaqueState",{destaqueMarker:null,destaqueTimeoutId:null});this.core=new To(this),this.layerManager=new pi(t),this.canvasInteracao=new Ro({mapaController:this,layerManager:this.layerManager}),this.context={pontos:[],segmentos:[],bancoPontos:[],confrontantes:[],zonaProjecao:22,config:this.core.config,graphicScale:{markerScaleMultiplier:1,lineScaleMultiplier:1,scaleModeGlobal:"screen"},onMarkerClick:(e,o)=>{if(this.modoCliqueSequencialAtivo||this.context.modoSequencial)return;const i=uo(e);if(this.customMarkerClickCallback)try{this.customMarkerClickCallback(i,o)}catch(n){console.error("Erro no customMarkerClickCallback:",n)}o?this.canvasInteracao.ctx.selectedVizinhoPontoIds=[i]:(this.canvasInteracao.ctx.selectedPontoIds=[i],this.canvasInteracao.ctx.lastSelectedPontoId=i),this.context.selectedPontoIds=[...this.canvasInteracao.ctx.selectedPontoIds],this.atualizarDestaqueMarcadores(),window.dispatchEvent(new CustomEvent("gerencigeo:ponto-selecionado",{detail:{selectedPontoIds:[i],lastSelectedPontoId:i,isVizinho:o}}))},onPopupAcao:(e,o,i)=>{if(this.customPopupActionCallback)try{this.customPopupActionCallback(e,o,i)}catch(n){console.error("Erro no customPopupActionCallback:",n)}}}}init(t,e){const o=this.core.init(t);return o&&(this.layerManager.attachMap(o,this.context),this.canvasInteracao.ativar(this,e)),o}invalidateSize(){try{this.core&&(typeof this.core.invalidateSize=="function"?this.core.invalidateSize():this.core.map&&typeof this.core.map.invalidateSize=="function"&&this.core.map.invalidateSize())}catch{}}setPontos(t){const e=t||[];this.context.pontos=e,this.canvasInteracao.ctx.pontosList=e,this.layerManager.updateContext({pontos:e})}setSegmentos(t){const e=t||[];this.context.segmentos=e,this.layerManager.updateContext({segmentos:e})}setBancoPontos(t){const e=t||[];this.context.bancoPontos=e,this.layerManager.updateContext({bancoPontos:e})}setConfrontantes(t){const e=t||[];this.context.confrontantes=e,this.layerManager.updateContext({confrontantes:e})}plotarPontos(t,e="vertices",o){Ua(this,t,e,o)}plotarConexoes(t,e="linhas"){Wa(this,t,e)}plotarPolilinhaSequencial(t,e=!0,o="polilinha",i){Xa(this,t,e,o,i)}plotarPoligonos(t,e="poligonos"){Za(this,t,e)}limparCamadas(t){this.layerManager.clearLayers(t),(!t||t.length===0)&&this.canvasInteracao.limparSelecao()}obterMarcadores(t){if(t){const e=[],o=this.layerManager.getLayerInstance(t);if(o){const i=n=>{n instanceof v.Marker&&e.push(n)};i(o),typeof o.eachLayer=="function"&&o.eachLayer(i)}return e}return this.getMarkers()}plotPontos(t,e){e&&(this.customMarkerClickCallback=e),this.setPontos(t||[])}plotSegmentos(t,e){Ya(this,t,e)}plotPolilinhaTemporaria(t){const e=t||[];this.context.pontos=e,this.context.segmentos=[],this.canvasInteracao.ctx.pontosList=e,this.layerManager.updateContext({pontos:e,segmentos:[]})}plotPoligonalHomologada(t){const e=t||[];this.setBancoPontos(e),this.layerManager.setLayerVisibility("homologados",!0),this.layerManager.setLayerVisibility("homologados-pontos",!0)}plotPontosVizinhos(t){const e=Ha(t||[],this.context.confrontantes||[]);this.setConfrontantes(e),this.layerManager.setLayerVisibility("vizinhos",!0)}plotPoligonosVizinhos(t){const e=Va(t||[],this.context.confrontantes||[]);this.setConfrontantes(e),this.layerManager.setLayerVisibility("vizinhos",!0)}clearOverlays(t=!1){Ka(this,t)}setGraphicScale(t){this.layerManager.setGraphicScale(t)}exportState(){return this.layerManager.exportState()}importState(t){this.layerManager.importState(t)}selectPonto(t,e){if(!this.core.map)return;const o=String(t),i=this.getMarkers().find(r=>String(r.pontoId)===o);if(i&&e!==void 0){const r=this.core.map;r.setView(i.getLatLng(),e),Te(r,()=>i.openPopup())}const n=uo(t);this.canvasInteracao.ctx.selectedPontoIds=[n],this.canvasInteracao.ctx.lastSelectedPontoId=n,this.context.selectedPontoIds=[n],this.atualizarDestaqueMarcadores()}atualizarDestaqueMarcadores(){tn(this)}selectSegmento(t){const e=t!=null?String(t):null;(this.context.selectedSegmentoId??null)!==e&&(this.context.selectedSegmentoId=e,this.layerManager.updateContext({selectedSegmentoId:e}))}fitBounds(t,e=[40,40],o=!1){if(!this.core.map)return;const i=Ga(t||this.context.pontos||[],this.context.confrontantes,o);if(i){i.single?this.core.map.setView(i.single,18):i.bounds&&(this.core.map.fitBounds(i.bounds,{padding:e}),this.core.map.once("moveend",()=>{this.core.preCarregarTilesRegiao(i.bounds)}));try{this.core.map.invalidateSize()}catch{}}}getMarkers(){return ja(this.core.map,this.layerManager)}getVizinhosMarkers(){return this.getMarkers().filter(t=>!!t.isVizinho)}get destaqueAtivo(){return this.destaqueState.destaqueMarker!==null}localizarCoordenadasElemento(t){return fi(this,t)}destacarElemento(t,e){Ba(this,this.destaqueState,t,e)}limparDestaque(){we(this.destaqueState,this.getMap())}destroy(){if(this.limparDestaque(),this.canvasInteracao.desativar(),this.layerManager.destroy(),this.core.destroy(),this.core.map)try{this.core.map.off(),this.core.map.remove()}catch{}finally{this.core.map=null}}getMap(){return this.core.map}}function mi(a,t,e,o){if(!a)return;if(a.querySelectorAll(".layer-item").length===t.length){t.forEach(n=>{var s,c;const r=a.querySelector(`.layer-item[data-layer-id="${n.id}"]`);if(r){const l=r.querySelector(".layer-chk-visibility");l&&l.checked!==n.visivel&&(l.checked=n.visivel);const d=r.querySelector(".layer-opacity-slider"),h=r.querySelector(".opacity-percent-label"),u=Math.round(n.opacidade*100);d&&parseInt(d.value,10)!==u&&(d.value=String(u)),h&&(h.textContent=`${u}%`);const g=r.querySelector(".btn-lock-layer");g&&(g.classList.toggle("active",!!n.bloqueada),g.title=n.bloqueada?"Desbloquear Camada":"Bloquear Camada");const m=r.querySelector(".btn-toggle-scale-mode");m&&((s=n.estilo)!=null&&s.scaleMode)&&(m.textContent=((c=n.estilo)==null?void 0:c.scaleMode)==="world"?"Métrico":"Tela")}});return}a.innerHTML=`
|
|
106
|
-
${
|
|
105
|
+
`,iconSize:[52,52],iconAnchor:[26,26]});e.destaqueMarker=b.marker(n,{icon:h,pane:l,interactive:!1,keyboard:!1}),e.destaqueMarker.addTo(i);const u=(v=(g=e.destaqueMarker).getElement)==null?void 0:v.call(g);u&&(u.style.pointerEvents="none"),o!=null&&o.duracaoMs&&o.duracaoMs>0&&(e.destaqueTimeoutId=window.setTimeout(()=>{vt(e,i)},o.duracaoMs))}function vt(a,e){a.destaqueTimeoutId!==null&&(window.clearTimeout(a.destaqueTimeoutId),a.destaqueTimeoutId=null),a.destaqueMarker&&(e&&e.hasLayer(a.destaqueMarker)?e.removeLayer(a.destaqueMarker):typeof a.destaqueMarker.remove=="function"&&a.destaqueMarker.remove(),a.destaqueMarker=null)}function Sa(a,e){const t=new Map;a.forEach(i=>{const n=i.lat??i.latitude??i.y,r=i.lon??i.lng??i.longitude??i.x,s=M.parseCoordenada(n,r);s&&(i.lat=s.lat,i.lon=s.lon);const c=i.confrontante_id??i.id_confrontante??0;t.has(c)||t.set(c,[]),t.get(c).push(i)});const o=new Map;return e.forEach(i=>{const n=i.id!==void 0&&i.id!==null?i.id:0;o.set(n,{...i,pontos:[]})}),t.forEach((i,n)=>{var r,s;if(o.has(n)){const c=o.get(n);c.pontos=i}else o.set(n,{id:n,nome:((r=i[0])==null?void 0:r.nome_confrontante)||"Confrontante",nome_propriedade:((s=i[0])==null?void 0:s.nome_propriedade)||"",pontos:i})}),Array.from(o.values()).filter(i=>i.pontos&&i.pontos.length>0||!!i.poligono_wkt)}function Ma(a,e){const t=new Map;return e.forEach(o=>{o.id!==void 0&&o.id!==null&&o.pontos&&o.pontos.length>0&&t.set(o.id,o.pontos)}),a.map(o=>{const i=o.id!==void 0&&o.id!==null?o.id:void 0;return i!==void 0&&(!o.pontos||o.pontos.length===0)&&t.has(i)?{...o,pontos:t.get(i)}:{...o}})}function Aa(a,e,t=!1){let o=[...a];t&&e&&e.forEach(n=>{n.pontos&&o.push(...n.pontos)});const i=o.map(n=>{const r=n.lat??n.latitude??n.y,s=n.lon??n.lng??n.longitude??n.x,c=M.parseCoordenada(r,s);return c?b.latLng(c.lat,c.lon):null}).filter(n=>n!==null);return i.length===1?{single:i[0]}:i.length>1?{bounds:b.latLngBounds(i)}:null}function wa(a,e){var n;(n=e==null?void 0:e.flushRender)==null||n.call(e);const t=[],o=new Set,i=r=>{r instanceof b.Marker&&r.pontoId!==void 0&&!o.has(r)&&(o.add(r),t.push(r))};return a&&a.eachLayer(r=>{i(r),typeof r.eachLayer=="function"&&r.eachLayer(i)}),e&&e.getAllLayerInstances().forEach(r=>{i(r),typeof r.eachLayer=="function"&&r.eachLayer(i)}),t}function Ea(a,e,t="vertices",o){const i=e||[];a.layerManager.getOrCreateLayer(t,"vetorial-pontos","Pontos / Vértices"),t==="vertices"&&(a.context.pontos=i,a.canvasInteracao.ctx.pontosList=i,o&&(a.customMarkerClickCallback=n=>{const r=i.find(s=>String(s.id)===String(n))||{id:n,lat:0,lon:0};o(r)})),a.layerManager.setLayerData(t,{pontos:i,onClique:o}),a.layerManager.setLayerVisibility(t,!0)}function za(a,e,t="linhas"){const o=e||[];a.layerManager.getOrCreateLayer(t,"vetorial-linhas","Conexões / Linhas"),(t==="linhas"||t==="perimetro")&&(a.context.segmentos=o.map(i=>({ponto_inicio_id:Number(i.origemId)||0,ponto_fim_id:Number(i.destinoId)||0,tipo_limite_sigef:i.tipoLinha==="tracejada"?"LN1":"LA1"}))),a.layerManager.setLayerData(t,{conexoes:o}),a.layerManager.setLayerVisibility(t,!0)}function ka(a,e,t=!0,o="polilinha",i){const n=e||[];a.layerManager.getOrCreateLayer(o,"vetorial-linhas","Polilinhas"),(o==="polilinha"||o==="perimetro")&&(a.context.pontos=n,a.context.segmentos=[],a.canvasInteracao.ctx.pontosList=n);const r=i||a.chaveGrupo||a.context.chaveGrupo;a.layerManager.setLayerData(o,{pontos:n,fechar:t!==!1,polilinhaSequencial:!0,chaveGrupo:r}),a.layerManager.setLayerVisibility(o,!0)}function Ia(a,e,t="poligonos"){const o=e||[];a.layerManager.getOrCreateLayer(t,"vetorial-poligonos","Polígonos"),a.layerManager.setLayerData(t,{poligonos:o}),a.layerManager.setLayerVisibility(t,!0)}function Da(a,e,t){const o=e||[];if(t!=null){const i=t||[];a.context.pontos=i,a.canvasInteracao.ctx.pontosList=i}a.context.segmentos=o,a.layerManager.updateContext({segmentos:o,...t!=null?{pontos:a.context.pontos}:{}})}function _a(a,e=!1){a.context.pontos=[],a.context.segmentos=[],a.context.confrontantes=[],a.canvasInteracao.ctx.pontosList=[],a.canvasInteracao.limparSelecao();const t={pontos:[],segmentos:[],confrontantes:[]};e||(a.context.bancoPontos=[],t.bancoPontos=[]),a.layerManager.updateContext(t)}function Xt(a){return a!=null&&!isNaN(Number(a))&&String(a).trim()!==""?Number(a):a}function Ta(a,e){var s,c;const t=a.core.map,o=a.layerManager.getLayerDef(e.layerId),i=e.baseSize||8,n=((s=a.context.graphicScale)==null?void 0:s.markerScaleMultiplier)||1;if(t&&((c=o==null?void 0:o.estilo)==null?void 0:c.scaleMode)==="world"){const l=o.estilo.dimensaoMetros||.25,d=t.getCenter(),h=t.getZoom(),u=40075016686e-3*Math.abs(Math.cos(d.lat*Math.PI/180))/Math.pow(2,h+8),g=l/(u>0?u:1);return Math.max(3,Math.round(g*n))}const r=wt(e.densTotal||0,(t==null?void 0:t.getZoom())??18);return Math.max(r<1?5:4,Math.round(i*n*r))}function Fa(a,e,t,o,i){const n=Ta(a,t),r=a.context.config.enableAnimations?"cad-pt-anim":"",s=ye(t.shapeStyle,n,t.markerBg,r,`map-marker-${t.layerId||"pts"}-${o}`,i,{densidade:Ge(t.densTotal||0)});t.tamanhoPx=n,e.setIcon(b.divIcon({html:s,className:`custom-leaflet-marker ${i?"cad-marker-selected ponto-selecionado":""}`,iconSize:[n+6,n+6]}))}function qa(a){const e=a.context.selectedPontoIds||[],t=a.canvasInteracao.ctx.selectedVizinhoPontoIds||[],o=new Set([...e.map(String),...t.map(String)]);for(const i of a.getMarkers()){const n=i,r=n.pontoId;if(r==null)continue;const s=o.has(String(r));if(n.isSelected===s)continue;n.isSelected=s,i.setZIndexOffset(s?2e3:0),n.shapeStyle&&n.baseSize&&n.markerBg&&Fa(a,i,n,r,s);const c=i.getElement();c&&(s?c.classList.add("cad-marker-selected","ponto-selecionado"):c.classList.remove("cad-marker-selected","ponto-selecionado"))}}class Ye{constructor(e){f(this,"core");f(this,"layerManager");f(this,"canvasInteracao");f(this,"context");f(this,"modoCliqueSequencialAtivo",!1);f(this,"chaveGrupo");f(this,"zonaProjecao",22);f(this,"levantamentoId",null);f(this,"customMarkerClickCallback");f(this,"customPopupActionCallback");f(this,"destaqueState",{destaqueMarker:null,destaqueTimeoutId:null});this.core=new ho(this),this.layerManager=new ni(e),this.canvasInteracao=new yo({mapaController:this,layerManager:this.layerManager}),this.context={pontos:[],segmentos:[],bancoPontos:[],confrontantes:[],zonaProjecao:22,config:this.core.config,graphicScale:{markerScaleMultiplier:1,lineScaleMultiplier:1,scaleModeGlobal:"screen"},onMarkerClick:(t,o)=>{if(this.modoCliqueSequencialAtivo||this.context.modoSequencial)return;const i=Xt(t);if(this.customMarkerClickCallback)try{this.customMarkerClickCallback(i,o)}catch(n){console.error("Erro no customMarkerClickCallback:",n)}o?this.canvasInteracao.ctx.selectedVizinhoPontoIds=[i]:(this.canvasInteracao.ctx.selectedPontoIds=[i],this.canvasInteracao.ctx.lastSelectedPontoId=i),this.context.selectedPontoIds=[...this.canvasInteracao.ctx.selectedPontoIds],this.atualizarDestaqueMarcadores(),window.dispatchEvent(new CustomEvent("gerencigeo:ponto-selecionado",{detail:{selectedPontoIds:[i],lastSelectedPontoId:i,isVizinho:o}}))},onPopupAcao:(t,o,i)=>{if(this.customPopupActionCallback)try{this.customPopupActionCallback(t,o,i)}catch(n){console.error("Erro no customPopupActionCallback:",n)}}}}init(e,t){const o=this.core.init(e);return o&&(this.layerManager.attachMap(o,this.context),this.canvasInteracao.ativar(this,t)),o}invalidateSize(){try{this.core&&(typeof this.core.invalidateSize=="function"?this.core.invalidateSize():this.core.map&&typeof this.core.map.invalidateSize=="function"&&this.core.map.invalidateSize())}catch{}}setPontos(e){const t=e||[];this.context.pontos=t,this.canvasInteracao.ctx.pontosList=t,this.layerManager.updateContext({pontos:t})}setSegmentos(e){const t=e||[];this.context.segmentos=t,this.layerManager.updateContext({segmentos:t})}setBancoPontos(e){const t=e||[];this.context.bancoPontos=t,this.layerManager.updateContext({bancoPontos:t})}setConfrontantes(e){const t=e||[];this.context.confrontantes=t,this.layerManager.updateContext({confrontantes:t})}plotarPontos(e,t="vertices",o){Ea(this,e,t,o)}plotarConexoes(e,t="linhas"){za(this,e,t)}plotarPolilinhaSequencial(e,t=!0,o="polilinha",i){ka(this,e,t,o,i)}plotarPoligonos(e,t="poligonos"){Ia(this,e,t)}limparCamadas(e){this.layerManager.clearLayers(e),(!e||e.length===0)&&this.canvasInteracao.limparSelecao()}obterMarcadores(e){if(e){const t=[],o=this.layerManager.getLayerInstance(e);if(o){const i=n=>{n instanceof b.Marker&&t.push(n)};i(o),typeof o.eachLayer=="function"&&o.eachLayer(i)}return t}return this.getMarkers()}plotPontos(e,t){t&&(this.customMarkerClickCallback=t),this.setPontos(e||[])}plotSegmentos(e,t){Da(this,e,t)}plotPolilinhaTemporaria(e){const t=e||[];this.context.pontos=t,this.context.segmentos=[],this.canvasInteracao.ctx.pontosList=t,this.layerManager.updateContext({pontos:t,segmentos:[]})}plotPoligonalHomologada(e){const t=e||[];this.setBancoPontos(t),this.layerManager.setLayerVisibility("homologados",!0),this.layerManager.setLayerVisibility("homologados-pontos",!0)}plotPontosVizinhos(e){const t=Sa(e||[],this.context.confrontantes||[]);this.setConfrontantes(t),this.layerManager.setLayerVisibility("vizinhos",!0)}plotPoligonosVizinhos(e){const t=Ma(e||[],this.context.confrontantes||[]);this.setConfrontantes(t),this.layerManager.setLayerVisibility("vizinhos",!0)}clearOverlays(e=!1){_a(this,e)}setGraphicScale(e){this.layerManager.setGraphicScale(e)}exportState(){return this.layerManager.exportState()}importState(e){this.layerManager.importState(e)}selectPonto(e,t){if(!this.core.map)return;const o=String(e),i=this.getMarkers().find(r=>String(r.pontoId)===o);if(i&&t!==void 0){const r=this.core.map;r.setView(i.getLatLng(),t),Ct(r,()=>i.openPopup())}const n=Xt(e);this.canvasInteracao.ctx.selectedPontoIds=[n],this.canvasInteracao.ctx.lastSelectedPontoId=n,this.context.selectedPontoIds=[n],this.atualizarDestaqueMarcadores()}atualizarDestaqueMarcadores(){qa(this)}selectSegmento(e){const t=e!=null?String(e):null;(this.context.selectedSegmentoId??null)!==t&&(this.context.selectedSegmentoId=t,this.layerManager.updateContext({selectedSegmentoId:t}))}fitBounds(e,t=[40,40],o=!1){if(!this.core.map)return;const i=Aa(e||this.context.pontos||[],this.context.confrontantes,o);if(i){i.single?this.core.map.setView(i.single,18):i.bounds&&(this.core.map.fitBounds(i.bounds,{padding:t}),this.core.map.once("moveend",()=>{this.core.preCarregarTilesRegiao(i.bounds)}));try{this.core.map.invalidateSize()}catch{}}}getMarkers(){return wa(this.core.map,this.layerManager)}getVizinhosMarkers(){return this.getMarkers().filter(e=>!!e.isVizinho)}get destaqueAtivo(){return this.destaqueState.destaqueMarker!==null}localizarCoordenadasElemento(e){return ri(this,e)}destacarElemento(e,t){La(this,this.destaqueState,e,t)}limparDestaque(){vt(this.destaqueState,this.getMap())}destroy(){if(this.limparDestaque(),this.canvasInteracao.desativar(),this.layerManager.destroy(),this.core.destroy(),this.core.map)try{this.core.map.off(),this.core.map.remove()}catch{}finally{this.core.map=null}}getMap(){return this.core.map}}function si(a,e,t,o){if(!a)return;if(a.querySelectorAll(".layer-item").length===e.length){e.forEach(n=>{var s,c;const r=a.querySelector(`.layer-item[data-layer-id="${n.id}"]`);if(r){const l=r.querySelector(".layer-chk-visibility");l&&l.checked!==n.visivel&&(l.checked=n.visivel);const d=r.querySelector(".layer-opacity-slider"),h=r.querySelector(".opacity-percent-label"),u=Math.round(n.opacidade*100);d&&parseInt(d.value,10)!==u&&(d.value=String(u)),h&&(h.textContent=`${u}%`);const g=r.querySelector(".btn-lock-layer");g&&(g.classList.toggle("active",!!n.bloqueada),g.title=n.bloqueada?"Desbloquear Camada":"Bloquear Camada");const v=r.querySelector(".btn-toggle-scale-mode");v&&((s=n.estilo)!=null&&s.scaleMode)&&(v.textContent=((c=n.estilo)==null?void 0:c.scaleMode)==="world"?"Métrico":"Tela")}});return}a.innerHTML=`
|
|
106
|
+
${e.map(n=>{var r,s;return`
|
|
107
107
|
<div class="layer-item" data-layer-id="${n.id}">
|
|
108
108
|
<div class="layer-item-row">
|
|
109
109
|
<label class="layer-item-label">
|
|
@@ -128,10 +128,10 @@
|
|
|
128
128
|
</div>
|
|
129
129
|
</div>
|
|
130
130
|
`}).join("")}
|
|
131
|
-
`,e.cleanup(),a.querySelectorAll(".layer-chk-visibility").forEach(n=>{e.add(n,"change",r=>{const s=r.target.getAttribute("data-layer-id"),c=r.target.checked;s&&o.setLayerVisibility(s,c)})}),a.querySelectorAll(".layer-opacity-slider").forEach(n=>{e.add(n,"input",r=>{const s=r.target.getAttribute("data-layer-id"),c=parseInt(r.target.value,10),l=c/100,d=r.target.closest(".layer-item"),h=d==null?void 0:d.querySelector(".opacity-percent-label");h&&(h.textContent=`${c}%`),s&&o.setLayerOpacity(s,l)})}),a.querySelectorAll(".btn-lock-layer").forEach(n=>{e.add(n,"click",r=>{const s=r.currentTarget.getAttribute("data-layer-id");if(s){const c=t.find(l=>l.id===s);c&&o.setLayerBlocked(s,!c.bloqueada)}})}),a.querySelectorAll(".btn-toggle-scale-mode").forEach(n=>{e.add(n,"click",r=>{var c;const s=r.currentTarget.getAttribute("data-layer-id");if(s){const l=t.find(d=>d.id===s);if(l){const d=((c=l.estilo)==null?void 0:c.scaleMode)==="world"?"screen":"world";o.setLayerScaleMode(s,d)}}})})}function en(a){return a.context.selectedPontoIds||a.canvasInteracao.ctx.selectedPontoIds||[]}function gi(a,t){a.canvasInteracao.ctx.selectedPontoIds=[...t],a.context.selectedPontoIds=[...t]}function Ve(a){const t=a;return(t==null?void 0:t.originalEvent)||t||{}}function on(a){const t=a,e=Ve(a),o=typeof e.composedPath=="function"?e.composedPath():[];return o.length>0?o[0]:e.target||(t==null?void 0:t.target)||null}function an(a,t,e){var n,r,s,c;if(t)return{x:Math.round(t.x),y:Math.round(t.y)};const o=a;if(o!=null&&o.containerPoint||o!=null&&o.layerPoint)return{x:Math.round(((n=o.containerPoint)==null?void 0:n.x)??((r=o.layerPoint)==null?void 0:r.x)??0),y:Math.round(((s=o.containerPoint)==null?void 0:s.y)??((c=o.layerPoint)==null?void 0:c.y)??0)};const i=Ve(a);return{x:Math.round((i.clientX??0)-e.left),y:Math.round((i.clientY??0)-e.top)}}function nn(a,t){const e=t||(a==null?void 0:a.latlng);return e&&typeof e.lat=="number"?{lat:e.lat,lng:e.lng??e.lon??0}:null}function vi(a,t,e,o){var m,f;if(a.modoSequencial||a.controller.canvasInteracao.selectionHappened||a.controller.canvasInteracao.panHappened||a.mouseMovedSinceDown)return!1;const i=Ve(t),n=on(t);if(n){const b='.custom-leaflet-marker, .leaflet-marker-icon, .leaflet-interactive, .compact-popup, .leaflet-popup, .ui-popup-btn, .cad-btn-tool, .qgis-layer-panel, [class*="leaflet-marker"], [class*="leaflet-popup"]';if(((m=n.matches)==null?void 0:m.call(n,b))||((f=n.closest)==null?void 0:f.call(n,b)))return!1}const r=a.controller.getMap();if(!r||!a.mapContainer)return!1;const s=an(t,o,a.mapContainer.getBoundingClientRect()),l=nn(t,e)??r.containerPointToLatLng(v.point(s.x,s.y)),d=l.lat,h=l.lng,u=a.controller.layerManager?a.controller.layerManager.getLayers().filter(b=>b.visivel).map(b=>b.id):[],g=i;return a.host.dispatchEvent(new CustomEvent("ui-canvas-clique",{detail:{coordenadas:{lat:d,lng:h},pontoPixel:s,eventoOriginal:g,lat:d,lon:h,lng:h,camadasAtivas:u},bubbles:!0,composed:!0})),!0}function yi(a,t,e,o){const i=o||a.obterElementoPorId(e);a.host.dispatchEvent(new CustomEvent("ui-acao-popup",{detail:{acaoId:t,elementoId:e,elemento:i??{id:e}},bubbles:!0,composed:!0})),a.fecharPopup()}function bi(a,t,e,o,i,n,r){let s=o||a.obterElementoPorId(t),c=i;if(!c&&s){const l=s,d=l.lat??l.latitude??0,h=l.lon??l.lng??l.longitude??0;c={lat:Number(d),lon:Number(h)}}if(c||(c={lat:0,lon:0}),a.modoSequencial){a.fecharPopup(),a.host.dispatchEvent(new CustomEvent("ui-clique-sequencial",{detail:{id:t,elemento:s??{id:t,lat:c.lat,lon:c.lon},coordenadas:c},bubbles:!0,composed:!0}));return}if(r)try{const l=t!=null&&!isNaN(Number(t))&&String(t).trim()!==""?Number(t):t;r(l,e)}catch(l){console.error("Erro no callback de clique de marcador:",l)}if(n)try{n(t,e,s,c)}catch(l){console.error("Erro no handler anterior de marker click:",l)}a.controller.context.selectedSegmentoId&&a.controller.selectSegmento(null),a.host.dispatchEvent(new CustomEvent("ui-ponto-selecionado",{detail:{selectedIds:[t],lastSelectedId:t,isVizinho:e},bubbles:!0,composed:!0})),a.host.dispatchEvent(new CustomEvent("ui-elemento-selecionado",{detail:{id:t,elemento:s,tipo:e?"vizinho":"vertice",coordenadas:c},bubbles:!0,composed:!0}))}function xi(a,t,e,o,i){if(a.modoSequencial){a.fecharPopup();return}if(a.controller.canvasInteracao.ctx.selectedPontoIds=[],a.controller.canvasInteracao.ctx.selectedVizinhoPontoIds=[],a.controller.canvasInteracao.ctx.lastSelectedPontoId=null,gi(a.controller,[]),a.controller.atualizarDestaqueMarcadores(),a.controller.selectSegmento(t),i)try{i(t,e)}catch(n){console.error("Erro no callback de clique de segmento:",n)}a.host.dispatchEvent(new CustomEvent("ui-segmento-selecionado",{detail:{segmentoId:t,segmento:e,pontoInicioId:e==null?void 0:e.ponto_inicio_id,pontoFimId:e==null?void 0:e.ponto_fim_id,coordenadas:o},bubbles:!0,composed:!0})),a.host.dispatchEvent(new CustomEvent("ui-elemento-selecionado",{detail:{id:t,elemento:e,tipo:"segmento",coordenadas:o},bubbles:!0,composed:!0}))}function Pi(a,t){let e=null,o=null,i=0,n=0;function r(){var d;try{if(!a.isConnected)return;const h=t.getMap();if(!h)return;const u=(d=h.getContainer)==null?void 0:d.call(h);if(!u||!u.parentNode)return;t.invalidateSize()}catch{}}function s(d=25){o!==null&&(window.clearTimeout(o),o=null),o=window.setTimeout(()=>{o=null,r()},d)}function c(){l(),!(typeof ResizeObserver>"u")&&(e=new ResizeObserver(d=>{for(const h of d){let u=0,g=0;h.contentRect?(u=h.contentRect.width,g=h.contentRect.height):h.borderBoxSize&&h.borderBoxSize.length>0?(u=h.borderBoxSize[0].inlineSize,g=h.borderBoxSize[0].blockSize):(u=a.clientWidth||a.offsetWidth,g=a.clientHeight||a.offsetHeight),u>0&&g>0&&(Math.abs(u-i)>=.5||Math.abs(g-n)>=.5)&&(i=u,n=g,s(25))}}),e.observe(a))}function l(){e&&(e.disconnect(),e=null),o!==null&&(window.clearTimeout(o),o=null)}return{observe:c,disconnect:l,invalidateSizeSafely:r}}class rn{constructor(t){p(this,"canal",null);p(this,"contexto");this.contexto=t}conectar(t){this.desconectar();const e=t!==void 0?t:this.contexto.host.getAttribute("canal-configuracao");if(!(!e||typeof BroadcastChannel>"u"))try{this.canal=new BroadcastChannel(e),this.canal.onmessage=o=>{this.processarMensagem(o.data)}}catch(o){console.warn(`[ui-canvas-cad] Erro ao conectar ao BroadcastChannel "${e}":`,o)}}processarMensagem(t){if(!t||typeof t!="object")return;const e=t,o=e.tipo||"ESTILOS_ALTERADOS",i=e.configuracoes||e;if(i.crosshair!==void 0){const n=!!i.crosshair;this.contexto.mapContainer&&(this.contexto.mapContainer.style.cursor=n?"crosshair":"");const r=this.contexto.controller.getMap();if(r){const s=r.getContainer();s&&(s.style.cursor=n?"crosshair":"")}this.contexto.controller.core.config.crosshair=n}if(i.opacidadeBase!==void 0){const n=parseFloat(i.opacidadeBase);isNaN(n)||this.contexto.setLayerOpacity("satelite",n)}if(i.satOpacity!==void 0){const n=parseFloat(i.satOpacity);isNaN(n)||this.contexto.setLayerOpacity("satelite",n)}i.opacidades&&typeof i.opacidades=="object"&&Object.entries(i.opacidades).forEach(([n,r])=>{const s=parseFloat(String(r));isNaN(s)||this.contexto.setLayerOpacity(n,s)}),this.contexto.host.dispatchEvent(new CustomEvent("ui-config-aplicada",{detail:{tipo:o,configuracoes:i},bubbles:!0,composed:!0}))}desconectar(){if(this.canal){try{this.canal.close()}catch{}this.canal=null}}}class sn{constructor(t){p(this,"contexto");p(this,"uiListeners",new be.ListenerBag);p(this,"isLayersPanelOpen",!1);p(this,"mouseMovedSinceDown",!1);p(this,"mouseDownPos",{x:0,y:0});this.contexto=t}get estaPainelAberto(){return this.isLayersPanelOpen}get houveMovimentoMouse(){return this.mouseMovedSinceDown}toggleLayersPanel(){this.isLayersPanelOpen=!this.isLayersPanelOpen,this.contexto.layersPanel&&(this.isLayersPanelOpen?this.contexto.layersPanel.classList.remove("collapsed"):this.contexto.layersPanel.classList.add("collapsed"));const t=this.contexto.shadow.getElementById("btn-toggle-layers");t==null||t.classList.toggle("active",this.isLayersPanelOpen)}closeLayersPanel(){var e;this.isLayersPanelOpen=!1,(e=this.contexto.layersPanel)==null||e.classList.add("collapsed");const t=this.contexto.shadow.getElementById("btn-toggle-layers");t==null||t.classList.remove("active")}vincularEventos(){this.uiListeners.cleanup();const t=this.contexto.shadow.getElementById("btn-toggle-layers"),e=this.contexto.shadow.getElementById("btn-close-layers"),o=this.contexto.shadow.getElementById("btn-zoom-extents"),i=this.contexto.shadow.getElementById("btn-clear-selection"),n=this.contexto.shadow.getElementById("btn-toggle-snap");this.uiListeners.add(t,"click",()=>{this.contexto.onToggleCamadas?this.contexto.onToggleCamadas():this.toggleLayersPanel()}),this.uiListeners.add(e,"click",()=>{this.contexto.onCloseCamadas?this.contexto.onCloseCamadas():this.closeLayersPanel()}),this.uiListeners.add(o,"click",()=>{var r,s;(s=(r=this.contexto).onZoomExtents)==null||s.call(r)}),this.uiListeners.add(i,"click",()=>{var r,s;(s=(r=this.contexto).onLimparSelecao)==null||s.call(r)}),this.uiListeners.add(n,"click",()=>{var r,s;(s=(r=this.contexto).onToggleSnap)==null||s.call(r)}),this.contexto.mapContainer&&(this.uiListeners.add(this.contexto.mapContainer,"mousedown",r=>{r.button===0&&(this.mouseDownPos={x:r.clientX,y:r.clientY},this.mouseMovedSinceDown=!1)}),this.uiListeners.add(this.contexto.mapContainer,"mousemove",r=>{Math.hypot(r.clientX-this.mouseDownPos.x,r.clientY-this.mouseDownPos.y)>=4&&(this.mouseMovedSinceDown=!0)}),this.uiListeners.add(this.contexto.mapContainer,"click",r=>{var s,c;r.button===0&&(this.mouseMovedSinceDown||(c=(s=this.contexto).onTratarCliqueCanvas)==null||c.call(s,r))})),this.uiListeners.add(this.contexto.shadow,"click",r=>{var l,d,h;const s=r.composedPath?r.composedPath()[0]:r.target,c=(l=s==null?void 0:s.closest)==null?void 0:l.call(s,".ui-popup-btn");if(c){r.preventDefault(),r.stopPropagation();const u=c.getAttribute("data-acao-id"),g=c.getAttribute("data-elemento-id");u&&g!==null&&((h=(d=this.contexto).onDispararAcaoPopup)==null||h.call(d,u,g))}})}limpar(){this.uiListeners.cleanup()}}class cn{constructor(t){p(this,"contexto");p(this,"_pontos",[]);p(this,"_segmentos",[]);p(this,"_bancoPontos",[]);p(this,"_confrontantes",[]);p(this,"customMarkerClickHandler");this.contexto=t}get pontos(){return this._pontos}set pontos(t){this._pontos=t||[],this.contexto.obterController().setPontos(this._pontos)}get segmentos(){return this._segmentos}set segmentos(t){this._segmentos=t||[],this.contexto.obterController().setSegmentos(this._segmentos)}get bancoPontos(){return this._bancoPontos}set bancoPontos(t){this._bancoPontos=t||[],this.contexto.obterController().setBancoPontos(this._bancoPontos)}get confrontantes(){return this._confrontantes}set confrontantes(t){this._confrontantes=t||[],this.contexto.obterController().setConfrontantes(this._confrontantes)}sincronizarInicial(){const t=this.contexto.obterController();this._pontos.length>0&&t.setPontos(this._pontos),this._segmentos.length>0&&t.setSegmentos(this._segmentos),this._bancoPontos.length>0&&t.setBancoPontos(this._bancoPontos),this._confrontantes.length>0&&t.setConfrontantes(this._confrontantes)}obterElementoPorId(t){return this._pontos.find(e=>String(e.id)===String(t))||this._bancoPontos.find(e=>String(e.id)===String(t))||this._confrontantes.find(e=>String(e.id)===String(t))}plotarPontos(t,e="vertices",o){const i=t||[];e==="vertices"&&(this._pontos=i),this.contexto.obterController().plotarPontos(i,e,o)}plotarConexoes(t,e="linhas"){const o=t||[];this.contexto.obterController().plotarConexoes(o,e)}plotarPolilinhaSequencial(t,e=!0,o="polilinha",i){const n=t||[];(o==="polilinha"||o==="perimetro")&&(this._pontos=n,this._segmentos=[]);const r=i??this.contexto.obterChaveGrupo();this.contexto.obterController().plotarPolilinhaSequencial(n,e,o,r)}plotarPoligonos(t,e="poligonos"){const o=t||[];this.contexto.obterController().plotarPoligonos(o,e)}limparCamadas(t){!t||t.length===0?(this._pontos=[],this._segmentos=[],this._confrontantes=[]):(t.includes("vertices")&&(this._pontos=[]),(t.includes("linhas")||t.includes("perimetro")||t.includes("polilinha"))&&(this._segmentos=[]),(t.includes("poligonos")||t.includes("vizinhos"))&&(this._confrontantes=[])),this.contexto.obterController().limparCamadas(t)}obterMarcadores(t){return this.contexto.obterController().obterMarcadores(t)}plotPontos(t,e){e&&(this.customMarkerClickHandler=e);const o=t||[];this._pontos=o,this.contexto.obterController().plotPontos(o,e)}plotSegmentos(t,e){const o=t||[];e!=null&&(this._pontos=e||[]),this._segmentos=o,this.contexto.obterController().plotSegmentos(o,e)}plotPolilinhaTemporaria(t){const e=t||[];this._pontos=e,this._segmentos=[],this.contexto.obterController().plotPolilinhaTemporaria(e)}plotPoligonalHomologada(t){const e=t||[];this._bancoPontos=e,this.contexto.obterController().plotPoligonalHomologada(e),this.contexto.setLayerVisibility("homologados",!0),this.contexto.setLayerVisibility("homologados-pontos",!0)}plotPontosVizinhos(t){const e=t||[],o=this.contexto.obterController();o.plotPontosVizinhos(e),this._confrontantes=o.context.confrontantes||[]}plotPoligonosVizinhos(t){const e=t||[],o=this.contexto.obterController();o.plotPoligonosVizinhos(e),this._confrontantes=o.context.confrontantes||[]}clearOverlays(t=!1){this._pontos=[],this._segmentos=[],this._confrontantes=[],t||(this._bancoPontos=[]),this.contexto.obterController().clearOverlays(t)}getMarkers(){return this.contexto.obterController().getMarkers()}getVizinhosMarkers(){return this.contexto.obterController().getVizinhosMarkers()}}const ln=':host{display:block;width:100%;height:520px;position:relative;border-radius:var(--ui-raio-lg, 10px);overflow:hidden;box-shadow:0 10px 30px -5px #0009;border:1px solid rgba(255,255,255,.1);background:#080d0a;color:#fff;font-family:var(--ui-fonte-base, "Inter", sans-serif);user-select:none;-webkit-user-select:none}*,*:before,*:after{box-sizing:border-box}.cad-root{position:relative;width:100%;height:100%;display:flex;overflow:hidden}.cad-map-container{width:100%;height:100%;background:#080d0a;z-index:1}.qgis-layer-panel{position:absolute;top:12px;left:12px;z-index:var(--ui-z-workspace-hud, 500);width:290px;max-height:calc(100% - 24px);background:#0a120eeb;backdrop-filter:blur(16px);-webkit-backdrop-filter:blur(16px);border:1px solid rgba(255,255,255,.15);border-radius:8px;box-shadow:0 20px 40px #000000b3;display:flex;flex-direction:column;transition:transform .25s cubic-bezier(.16,1,.3,1),opacity .25s ease;overflow:hidden}.qgis-layer-panel.collapsed{transform:translate(-310px);opacity:0;pointer-events:none}.layer-panel-header{padding:10px 14px;background:#ffffff08;border-bottom:1px solid rgba(255,255,255,.08);display:flex;align-items:center;justify-content:space-between}.layer-panel-title{font-size:12px;font-weight:700;letter-spacing:.5px;color:#00f5a0;display:flex;align-items:center;gap:6px;text-transform:uppercase}.layer-panel-close{background:transparent;border:none;color:#ffffff80;cursor:pointer;padding:2px;border-radius:var(--ui-raio-sm, 4px);display:flex;align-items:center;justify-content:center;transition:all .15s}.layer-panel-close:hover{color:#fff;background:#ffffff1a}.layer-panel-body{padding:8px 10px;overflow-y:auto;display:flex;flex-direction:column;gap:2px;max-height:400px}.layer-panel-body::-webkit-scrollbar{width:5px}.layer-panel-body::-webkit-scrollbar-track{background:transparent}.layer-panel-body::-webkit-scrollbar-thumb{background:#fff3;border-radius:var(--ui-raio-sm, 4px)}.layer-panel-body::-webkit-scrollbar-thumb:hover{background:#00f5a066}.layer-item{background:transparent;border:none;border-bottom:1px solid rgba(255,255,255,.08);border-radius:0;padding:4px;display:flex;flex-direction:column;gap:3px;transition:background .15s ease}.layer-item:last-child{border-bottom:none}.layer-item:hover{background:#ffffff08;border-radius:var(--ui-raio-sm, 4px)}.layer-item-row{display:flex;align-items:center;justify-content:space-between;min-height:18px}.layer-item-label{display:flex;align-items:center;gap:7px;font-size:11px;font-weight:600;line-height:1.2;color:#ffffffe6;cursor:pointer;-webkit-user-select:none;user-select:none}.layer-chk-visibility{-moz-appearance:none;appearance:none;-webkit-appearance:none;width:14px;height:14px;border:1px solid rgba(255,255,255,.4);border-radius:3px;background:#0006;cursor:pointer;display:inline-flex;align-items:center;justify-content:center;position:relative;transition:all .15s ease;flex-shrink:0;margin:0}.layer-chk-visibility:hover{border-color:#00f5a0}.layer-chk-visibility:checked{background:#00f5a0;border-color:#00f5a0}.layer-chk-visibility:checked:after{content:"";width:3.5px;height:7px;border:solid #04150c;border-width:0 1.5px 1.5px 0;transform:rotate(45deg) translateY(-.5px);display:block}.layer-item-actions{display:flex;align-items:center;gap:4px}.btn-layer-action{background:transparent;border:none;color:#fff6;cursor:pointer;padding:2px;border-radius:3px;display:flex;align-items:center;justify-content:center;transition:all .15s}.btn-layer-action:hover{color:#00f5a0;background:#ffffff14}.btn-layer-action.active{color:#f43f5e;background:#f43f5e26}.layer-controls-row{display:flex;align-items:center;justify-content:space-between;gap:8px;font-size:9.5px;line-height:1;color:#ffffff80;padding-left:21px}.layer-opacity-slider{flex:1;height:3px;margin:0;border-radius:2px;background:#ffffff26;accent-color:#00f5a0;cursor:pointer}.scale-mode-pill{font-size:8.5px;font-weight:600;padding:1px 6px;border-radius:6px;background:#ffffff0f;color:#ffffffb3;cursor:pointer;border:1px solid rgba(255,255,255,.1);transition:all .15s;line-height:1.2}.scale-mode-pill:hover{border-color:#00f5a0;color:#00f5a0;background:#00f5a01a}:host([sem-painel-camadas]) .qgis-layer-panel,:host([sem-painel-camadas]) #btn-toggle-layers,:host([sem-barra-rapida]) .cad-quick-toolbar{display:none!important}.cad-quick-toolbar{position:absolute;top:12px;right:12px;z-index:var(--ui-z-workspace-hud, 500);display:flex;flex-direction:column;gap:6px;background:#0c1510eb;backdrop-filter:blur(14px);-webkit-backdrop-filter:blur(14px);border:1px solid rgba(255,255,255,.15);border-radius:8px;padding:5px;box-shadow:0 10px 25px -5px #0009}.cad-btn-tool{background:transparent;border:none;color:#fff9;cursor:pointer;padding:7px;border-radius:5px;display:flex;align-items:center;justify-content:center;transition:all .15s}.cad-btn-tool:hover{background:#ffffff1a;color:#fff}.cad-btn-tool.active{background:#00f5a026;color:#00f5a0;border:1px solid rgba(0,245,160,.3)}.cad-selection-box{pointer-events:none;box-sizing:border-box}.custom-leaflet-marker{cursor:pointer}.custom-leaflet-marker:hover{z-index:1800!important}.custom-leaflet-marker .cad-pt svg{transition:transform .12s ease-out}.custom-leaflet-marker:hover .cad-pt svg{transform:scale(1.3)}.leaflet-popup-content-wrapper{background:#0f1712!important;color:#f8fafc!important;border:1px solid rgba(255,255,255,.15)!important;border-radius:8px!important;box-shadow:0 10px 25px #0009!important;padding:0!important;backdrop-filter:blur(16px)!important;-webkit-backdrop-filter:blur(16px)!important}.leaflet-popup-tip{background:#0f1712!important;border:1px solid rgba(255,255,255,.15)!important;box-shadow:none!important}.leaflet-popup-close-button{color:#fff9!important;padding:6px!important;transition:color .15s ease}.leaflet-popup-close-button:hover{color:#fff!important}.leaflet-popup-content{margin:12px 14px!important;line-height:1.4;font-family:inherit;color:#f8fafc}.compact-popup .leaflet-popup-content{margin:10px 12px!important}.ui-popup-actions-footer{display:flex;gap:6px;margin-top:8px;padding-top:8px;border-top:1px solid rgba(255,255,255,.1);justify-content:flex-end;align-items:center;flex-wrap:wrap}.ui-popup-btn{display:inline-flex;align-items:center;justify-content:center;font-family:inherit;font-size:11px;font-weight:500;padding:4px 9px;border-radius:var(--ui-raio-borda, 6px);cursor:pointer;transition:all .15s ease;border:1px solid transparent;outline:none;line-height:1.25;-webkit-user-select:none;user-select:none}.ui-popup-btn-primary{background:var(--ui-cor-primaria, #00f5a0);color:#080d0a;font-weight:600;border-color:var(--ui-cor-primaria, #00f5a0)}.ui-popup-btn-primary:hover{filter:brightness(1.1);box-shadow:0 0 10px #00f5a059}.ui-popup-btn-secondary{background:#ffffff14;color:#fff;border-color:#ffffff2e}.ui-popup-btn-secondary:hover{background:#ffffff29;border-color:#ffffff4d}.ui-popup-btn-destrutivo{background:#ef444426;color:#f87171;border-color:#ef444459}.ui-popup-btn-destrutivo:hover{background:#ef444440;border-color:#ef444499;color:#fff}@media (max-width: 520px){.qgis-layer-panel{top:8px;left:8px;right:8px;width:auto;max-height:calc(100% - 16px)}.qgis-layer-panel.collapsed{transform:translateY(-115%)}.layer-panel-close{min-width:36px;min-height:36px;font-size:16px}.layer-action-btn{min-width:32px;min-height:32px}}.cad-destaque-marker-container{pointer-events:none!important;background:transparent!important;border:none!important;overflow:visible!important}.cad-destaque-marker-container *{pointer-events:none!important}.cad-pulse-highlight{position:relative;width:52px;height:52px;display:flex;align-items:center;justify-content:center;pointer-events:none!important;user-select:none;-webkit-user-select:none}.cad-pulse-core{position:absolute;width:12px;height:12px;border-radius:50%;background-color:var(--cad-pulse-cor, #00f5a0);border:2px solid #ffffff;box-sizing:border-box;pointer-events:none!important}.cad-pulse-ring{position:absolute;width:100%;height:100%;border-radius:50%;border:2px solid var(--cad-pulse-cor, #00f5a0);background-color:color-mix(in srgb,var(--cad-pulse-cor, #00f5a0) 14%,transparent);box-sizing:border-box;pointer-events:none!important;opacity:0;animation:cad-pulse-ping 1.8s cubic-bezier(0,0,.2,1) infinite}.cad-pulse-ring.ring-2{animation-delay:.9s}@keyframes cad-pulse-ping{0%{transform:scale(.3);opacity:.9}70%{opacity:.35}to{transform:scale(1);opacity:0}}@media (prefers-reduced-motion: reduce){.cad-pulse-ring{animation:none;opacity:.6;transform:scale(.6)}}.cad-marker-selected,.ponto-selecionado{z-index:2000!important}@media (prefers-reduced-motion: reduce){.custom-leaflet-marker .cad-pt svg{transition:none}}.ui-popup-actions-footer{margin-top:8px;padding-top:6px;border-top:1px solid rgba(255,255,255,.12);display:flex;gap:6px;flex-wrap:wrap}.ui-popup-btn{display:inline-flex;align-items:center;justify-content:center;padding:4px 8px;font-size:11px;font-weight:600;border-radius:var(--ui-raio-sm, 4px);border:1px solid rgba(255,255,255,.15);background:#ffffff14;color:#fff;cursor:pointer;line-height:1.2;transition:all .15s ease;-webkit-user-select:none;user-select:none}.ui-popup-btn:hover{background:#ffffff2e;border-color:#ffffff4d}.ui-popup-btn-primary{background:#00f5a0;color:#06130b;border-color:#00f5a0}.ui-popup-btn-primary:hover{background:#10ffad;box-shadow:0 0 8px #00f5a066}.ui-popup-btn-danger{background:#f43f5e33;color:#f43f5e;border-color:#f43f5e66}.ui-popup-btn-danger:hover{background:#f43f5e59;color:#fff}.cad-draw-toolbar{right:auto;left:12px;max-height:calc(100% - 24px);overflow-y:auto}.cad-draw-btn{font:600 11px var(--ui-fonte-base, sans-serif);padding:5px 9px;white-space:nowrap;justify-content:flex-start}.cad-ferramenta-ativa .leaflet-marker-icon{pointer-events:none!important}.cad-sr-only{position:absolute;width:1px;height:1px;margin:-1px;padding:0;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap;border:0}';function dn(){return`
|
|
131
|
+
`,t.cleanup(),a.querySelectorAll(".layer-chk-visibility").forEach(n=>{t.add(n,"change",r=>{const s=r.target.getAttribute("data-layer-id"),c=r.target.checked;s&&o.setLayerVisibility(s,c)})}),a.querySelectorAll(".layer-opacity-slider").forEach(n=>{t.add(n,"input",r=>{const s=r.target.getAttribute("data-layer-id"),c=parseInt(r.target.value,10),l=c/100,d=r.target.closest(".layer-item"),h=d==null?void 0:d.querySelector(".opacity-percent-label");h&&(h.textContent=`${c}%`),s&&o.setLayerOpacity(s,l)})}),a.querySelectorAll(".btn-lock-layer").forEach(n=>{t.add(n,"click",r=>{const s=r.currentTarget.getAttribute("data-layer-id");if(s){const c=e.find(l=>l.id===s);c&&o.setLayerBlocked(s,!c.bloqueada)}})}),a.querySelectorAll(".btn-toggle-scale-mode").forEach(n=>{t.add(n,"click",r=>{var c;const s=r.currentTarget.getAttribute("data-layer-id");if(s){const l=e.find(d=>d.id===s);if(l){const d=((c=l.estilo)==null?void 0:c.scaleMode)==="world"?"screen":"world";o.setLayerScaleMode(s,d)}}})})}function Oa(a){return a.context.selectedPontoIds||a.canvasInteracao.ctx.selectedPontoIds||[]}function ci(a,e){a.canvasInteracao.ctx.selectedPontoIds=[...e],a.context.selectedPontoIds=[...e]}function _t(a){const e=a;return(e==null?void 0:e.originalEvent)||e||{}}function $a(a){const e=a,t=_t(a),o=typeof t.composedPath=="function"?t.composedPath():[];return o.length>0?o[0]:t.target||(e==null?void 0:e.target)||null}function Na(a,e,t){var n,r,s,c;if(e)return{x:Math.round(e.x),y:Math.round(e.y)};const o=a;if(o!=null&&o.containerPoint||o!=null&&o.layerPoint)return{x:Math.round(((n=o.containerPoint)==null?void 0:n.x)??((r=o.layerPoint)==null?void 0:r.x)??0),y:Math.round(((s=o.containerPoint)==null?void 0:s.y)??((c=o.layerPoint)==null?void 0:c.y)??0)};const i=_t(a);return{x:Math.round((i.clientX??0)-t.left),y:Math.round((i.clientY??0)-t.top)}}function Ra(a,e){const t=e||(a==null?void 0:a.latlng);return t&&typeof t.lat=="number"?{lat:t.lat,lng:t.lng??t.lon??0}:null}function li(a,e,t,o){var v,p;if(a.modoSequencial||a.controller.canvasInteracao.selectionHappened||a.controller.canvasInteracao.panHappened||a.mouseMovedSinceDown)return!1;const i=_t(e),n=$a(e);if(n){const y='.custom-leaflet-marker, .leaflet-marker-icon, .leaflet-interactive, .compact-popup, .leaflet-popup, .ui-popup-btn, .cad-btn-tool, .qgis-layer-panel, [class*="leaflet-marker"], [class*="leaflet-popup"]';if(((v=n.matches)==null?void 0:v.call(n,y))||((p=n.closest)==null?void 0:p.call(n,y)))return!1}const r=a.controller.getMap();if(!r||!a.mapContainer)return!1;const s=Na(e,o,a.mapContainer.getBoundingClientRect()),l=Ra(e,t)??r.containerPointToLatLng(b.point(s.x,s.y)),d=l.lat,h=l.lng,u=a.controller.layerManager?a.controller.layerManager.getLayers().filter(y=>y.visivel).map(y=>y.id):[],g=i;return a.host.dispatchEvent(new CustomEvent("ui-canvas-clique",{detail:{coordenadas:{lat:d,lng:h},pontoPixel:s,eventoOriginal:g,lat:d,lon:h,lng:h,camadasAtivas:u},bubbles:!0,composed:!0})),!0}function di(a,e,t,o){const i=o||a.obterElementoPorId(t);a.host.dispatchEvent(new CustomEvent("ui-acao-popup",{detail:{acaoId:e,elementoId:t,elemento:i??{id:t}},bubbles:!0,composed:!0})),a.fecharPopup()}function hi(a,e,t,o,i,n,r){let s=o||a.obterElementoPorId(e),c=i;if(!c&&s){const l=s,d=l.lat??l.latitude??0,h=l.lon??l.lng??l.longitude??0;c={lat:Number(d),lon:Number(h)}}if(c||(c={lat:0,lon:0}),a.modoSequencial){a.fecharPopup(),a.host.dispatchEvent(new CustomEvent("ui-clique-sequencial",{detail:{id:e,elemento:s??{id:e,lat:c.lat,lon:c.lon},coordenadas:c},bubbles:!0,composed:!0}));return}if(r)try{const l=e!=null&&!isNaN(Number(e))&&String(e).trim()!==""?Number(e):e;r(l,t)}catch(l){console.error("Erro no callback de clique de marcador:",l)}if(n)try{n(e,t,s,c)}catch(l){console.error("Erro no handler anterior de marker click:",l)}a.controller.context.selectedSegmentoId&&a.controller.selectSegmento(null),a.host.dispatchEvent(new CustomEvent("ui-ponto-selecionado",{detail:{selectedIds:[e],lastSelectedId:e,isVizinho:t},bubbles:!0,composed:!0})),a.host.dispatchEvent(new CustomEvent("ui-elemento-selecionado",{detail:{id:e,elemento:s,tipo:t?"vizinho":"vertice",coordenadas:c},bubbles:!0,composed:!0}))}function ui(a,e,t,o,i){if(a.modoSequencial){a.fecharPopup();return}if(a.controller.canvasInteracao.ctx.selectedPontoIds=[],a.controller.canvasInteracao.ctx.selectedVizinhoPontoIds=[],a.controller.canvasInteracao.ctx.lastSelectedPontoId=null,ci(a.controller,[]),a.controller.atualizarDestaqueMarcadores(),a.controller.selectSegmento(e),i)try{i(e,t)}catch(n){console.error("Erro no callback de clique de segmento:",n)}a.host.dispatchEvent(new CustomEvent("ui-segmento-selecionado",{detail:{segmentoId:e,segmento:t,pontoInicioId:t==null?void 0:t.ponto_inicio_id,pontoFimId:t==null?void 0:t.ponto_fim_id,coordenadas:o},bubbles:!0,composed:!0})),a.host.dispatchEvent(new CustomEvent("ui-elemento-selecionado",{detail:{id:e,elemento:t,tipo:"segmento",coordenadas:o},bubbles:!0,composed:!0}))}function pi(a,e){let t=null,o=null,i=0,n=0;function r(){var d;try{if(!a.isConnected)return;const h=e.getMap();if(!h)return;const u=(d=h.getContainer)==null?void 0:d.call(h);if(!u||!u.parentNode)return;e.invalidateSize()}catch{}}function s(d=25){o!==null&&(window.clearTimeout(o),o=null),o=window.setTimeout(()=>{o=null,r()},d)}function c(){l(),!(typeof ResizeObserver>"u")&&(t=new ResizeObserver(d=>{for(const h of d){let u=0,g=0;h.contentRect?(u=h.contentRect.width,g=h.contentRect.height):h.borderBoxSize&&h.borderBoxSize.length>0?(u=h.borderBoxSize[0].inlineSize,g=h.borderBoxSize[0].blockSize):(u=a.clientWidth||a.offsetWidth,g=a.clientHeight||a.offsetHeight),u>0&&g>0&&(Math.abs(u-i)>=.5||Math.abs(g-n)>=.5)&&(i=u,n=g,s(25))}}),t.observe(a))}function l(){t&&(t.disconnect(),t=null),o!==null&&(window.clearTimeout(o),o=null)}return{observe:c,disconnect:l,invalidateSizeSafely:r}}class Ba{constructor(e){f(this,"canal",null);f(this,"contexto");this.contexto=e}conectar(e){this.desconectar();const t=e!==void 0?e:this.contexto.host.getAttribute("canal-configuracao");if(!(!t||typeof BroadcastChannel>"u"))try{this.canal=new BroadcastChannel(t),this.canal.onmessage=o=>{this.processarMensagem(o.data)}}catch(o){console.warn(`[ui-canvas-cad] Erro ao conectar ao BroadcastChannel "${t}":`,o)}}processarMensagem(e){if(!e||typeof e!="object")return;const t=e,o=t.tipo||"ESTILOS_ALTERADOS",i=t.configuracoes||t;if(i.crosshair!==void 0){const n=!!i.crosshair;this.contexto.mapContainer&&(this.contexto.mapContainer.style.cursor=n?"crosshair":"");const r=this.contexto.controller.getMap();if(r){const s=r.getContainer();s&&(s.style.cursor=n?"crosshair":"")}this.contexto.controller.core.config.crosshair=n}if(i.opacidadeBase!==void 0){const n=parseFloat(i.opacidadeBase);isNaN(n)||this.contexto.setLayerOpacity("satelite",n)}if(i.satOpacity!==void 0){const n=parseFloat(i.satOpacity);isNaN(n)||this.contexto.setLayerOpacity("satelite",n)}i.opacidades&&typeof i.opacidades=="object"&&Object.entries(i.opacidades).forEach(([n,r])=>{const s=parseFloat(String(r));isNaN(s)||this.contexto.setLayerOpacity(n,s)}),this.contexto.host.dispatchEvent(new CustomEvent("ui-config-aplicada",{detail:{tipo:o,configuracoes:i},bubbles:!0,composed:!0}))}desconectar(){if(this.canal){try{this.canal.close()}catch{}this.canal=null}}}class Va{constructor(e){f(this,"contexto");f(this,"uiListeners",new ct.ListenerBag);f(this,"isLayersPanelOpen",!1);f(this,"mouseMovedSinceDown",!1);f(this,"mouseDownPos",{x:0,y:0});this.contexto=e}get estaPainelAberto(){return this.isLayersPanelOpen}get houveMovimentoMouse(){return this.mouseMovedSinceDown}toggleLayersPanel(){this.isLayersPanelOpen=!this.isLayersPanelOpen,this.contexto.layersPanel&&(this.isLayersPanelOpen?this.contexto.layersPanel.classList.remove("collapsed"):this.contexto.layersPanel.classList.add("collapsed"));const e=this.contexto.shadow.getElementById("btn-toggle-layers");e==null||e.classList.toggle("active",this.isLayersPanelOpen)}closeLayersPanel(){var t;this.isLayersPanelOpen=!1,(t=this.contexto.layersPanel)==null||t.classList.add("collapsed");const e=this.contexto.shadow.getElementById("btn-toggle-layers");e==null||e.classList.remove("active")}vincularEventos(){this.uiListeners.cleanup();const e=this.contexto.shadow.getElementById("btn-toggle-layers"),t=this.contexto.shadow.getElementById("btn-close-layers"),o=this.contexto.shadow.getElementById("btn-zoom-extents"),i=this.contexto.shadow.getElementById("btn-clear-selection"),n=this.contexto.shadow.getElementById("btn-toggle-snap");this.uiListeners.add(e,"click",()=>{this.contexto.onToggleCamadas?this.contexto.onToggleCamadas():this.toggleLayersPanel()}),this.uiListeners.add(t,"click",()=>{this.contexto.onCloseCamadas?this.contexto.onCloseCamadas():this.closeLayersPanel()}),this.uiListeners.add(o,"click",()=>{var r,s;(s=(r=this.contexto).onZoomExtents)==null||s.call(r)}),this.uiListeners.add(i,"click",()=>{var r,s;(s=(r=this.contexto).onLimparSelecao)==null||s.call(r)}),this.uiListeners.add(n,"click",()=>{var r,s;(s=(r=this.contexto).onToggleSnap)==null||s.call(r)}),this.contexto.mapContainer&&(this.uiListeners.add(this.contexto.mapContainer,"mousedown",r=>{r.button===0&&(this.mouseDownPos={x:r.clientX,y:r.clientY},this.mouseMovedSinceDown=!1)}),this.uiListeners.add(this.contexto.mapContainer,"mousemove",r=>{Math.hypot(r.clientX-this.mouseDownPos.x,r.clientY-this.mouseDownPos.y)>=4&&(this.mouseMovedSinceDown=!0)}),this.uiListeners.add(this.contexto.mapContainer,"click",r=>{var s,c;r.button===0&&(this.mouseMovedSinceDown||(c=(s=this.contexto).onTratarCliqueCanvas)==null||c.call(s,r))})),this.uiListeners.add(this.contexto.shadow,"click",r=>{var l,d,h;const s=r.composedPath?r.composedPath()[0]:r.target,c=(l=s==null?void 0:s.closest)==null?void 0:l.call(s,".ui-popup-btn");if(c){r.preventDefault(),r.stopPropagation();const u=c.getAttribute("data-acao-id"),g=c.getAttribute("data-elemento-id");u&&g!==null&&((h=(d=this.contexto).onDispararAcaoPopup)==null||h.call(d,u,g))}})}limpar(){this.uiListeners.cleanup()}}class Ha{constructor(e){f(this,"contexto");f(this,"_pontos",[]);f(this,"_segmentos",[]);f(this,"_bancoPontos",[]);f(this,"_confrontantes",[]);f(this,"customMarkerClickHandler");this.contexto=e}get pontos(){return this._pontos}set pontos(e){this._pontos=e||[],this.contexto.obterController().setPontos(this._pontos)}get segmentos(){return this._segmentos}set segmentos(e){this._segmentos=e||[],this.contexto.obterController().setSegmentos(this._segmentos)}get bancoPontos(){return this._bancoPontos}set bancoPontos(e){this._bancoPontos=e||[],this.contexto.obterController().setBancoPontos(this._bancoPontos)}get confrontantes(){return this._confrontantes}set confrontantes(e){this._confrontantes=e||[],this.contexto.obterController().setConfrontantes(this._confrontantes)}sincronizarInicial(){const e=this.contexto.obterController();this._pontos.length>0&&e.setPontos(this._pontos),this._segmentos.length>0&&e.setSegmentos(this._segmentos),this._bancoPontos.length>0&&e.setBancoPontos(this._bancoPontos),this._confrontantes.length>0&&e.setConfrontantes(this._confrontantes)}obterElementoPorId(e){return this._pontos.find(t=>String(t.id)===String(e))||this._bancoPontos.find(t=>String(t.id)===String(e))||this._confrontantes.find(t=>String(t.id)===String(e))}plotarPontos(e,t="vertices",o){const i=e||[];t==="vertices"&&(this._pontos=i),this.contexto.obterController().plotarPontos(i,t,o)}plotarConexoes(e,t="linhas"){const o=e||[];this.contexto.obterController().plotarConexoes(o,t)}plotarPolilinhaSequencial(e,t=!0,o="polilinha",i){const n=e||[];(o==="polilinha"||o==="perimetro")&&(this._pontos=n,this._segmentos=[]);const r=i??this.contexto.obterChaveGrupo();this.contexto.obterController().plotarPolilinhaSequencial(n,t,o,r)}plotarPoligonos(e,t="poligonos"){const o=e||[];this.contexto.obterController().plotarPoligonos(o,t)}limparCamadas(e){!e||e.length===0?(this._pontos=[],this._segmentos=[],this._confrontantes=[]):(e.includes("vertices")&&(this._pontos=[]),(e.includes("linhas")||e.includes("perimetro")||e.includes("polilinha"))&&(this._segmentos=[]),(e.includes("poligonos")||e.includes("vizinhos"))&&(this._confrontantes=[])),this.contexto.obterController().limparCamadas(e)}obterMarcadores(e){return this.contexto.obterController().obterMarcadores(e)}plotPontos(e,t){t&&(this.customMarkerClickHandler=t);const o=e||[];this._pontos=o,this.contexto.obterController().plotPontos(o,t)}plotSegmentos(e,t){const o=e||[];t!=null&&(this._pontos=t||[]),this._segmentos=o,this.contexto.obterController().plotSegmentos(o,t)}plotPolilinhaTemporaria(e){const t=e||[];this._pontos=t,this._segmentos=[],this.contexto.obterController().plotPolilinhaTemporaria(t)}plotPoligonalHomologada(e){const t=e||[];this._bancoPontos=t,this.contexto.obterController().plotPoligonalHomologada(t),this.contexto.setLayerVisibility("homologados",!0),this.contexto.setLayerVisibility("homologados-pontos",!0)}plotPontosVizinhos(e){const t=e||[],o=this.contexto.obterController();o.plotPontosVizinhos(t),this._confrontantes=o.context.confrontantes||[]}plotPoligonosVizinhos(e){const t=e||[],o=this.contexto.obterController();o.plotPoligonosVizinhos(t),this._confrontantes=o.context.confrontantes||[]}clearOverlays(e=!1){this._pontos=[],this._segmentos=[],this._confrontantes=[],e||(this._bancoPontos=[]),this.contexto.obterController().clearOverlays(e)}getMarkers(){return this.contexto.obterController().getMarkers()}getVizinhosMarkers(){return this.contexto.obterController().getVizinhosMarkers()}}const Ga=':host{display:block;width:100%;height:520px;position:relative;border-radius:var(--ui-raio-lg, 10px);overflow:hidden;box-shadow:0 10px 30px -5px #0009;border:1px solid rgba(255,255,255,.1);background:#080d0a;color:#fff;font-family:var(--ui-fonte-base, "Inter", sans-serif);user-select:none;-webkit-user-select:none}*,*:before,*:after{box-sizing:border-box}.cad-root{position:relative;width:100%;height:100%;display:flex;overflow:hidden}.cad-map-container{width:100%;height:100%;background:#080d0a;z-index:1}.qgis-layer-panel{position:absolute;top:12px;left:12px;z-index:var(--ui-z-workspace-hud, 500);width:290px;max-height:calc(100% - 24px);background:#0a120eeb;backdrop-filter:blur(16px);-webkit-backdrop-filter:blur(16px);border:1px solid rgba(255,255,255,.15);border-radius:8px;box-shadow:0 20px 40px #000000b3;display:flex;flex-direction:column;transition:transform .25s cubic-bezier(.16,1,.3,1),opacity .25s ease;overflow:hidden}.qgis-layer-panel.collapsed{transform:translate(-310px);opacity:0;pointer-events:none}.layer-panel-header{padding:10px 14px;background:#ffffff08;border-bottom:1px solid rgba(255,255,255,.08);display:flex;align-items:center;justify-content:space-between}.layer-panel-title{font-size:12px;font-weight:700;letter-spacing:.5px;color:#00f5a0;display:flex;align-items:center;gap:6px;text-transform:uppercase}.layer-panel-close{background:transparent;border:none;color:#ffffff80;cursor:pointer;padding:2px;border-radius:var(--ui-raio-sm, 4px);display:flex;align-items:center;justify-content:center;transition:all .15s}.layer-panel-close:hover{color:#fff;background:#ffffff1a}.layer-panel-body{padding:8px 10px;overflow-y:auto;display:flex;flex-direction:column;gap:2px;max-height:400px}.layer-panel-body::-webkit-scrollbar{width:5px}.layer-panel-body::-webkit-scrollbar-track{background:transparent}.layer-panel-body::-webkit-scrollbar-thumb{background:#fff3;border-radius:var(--ui-raio-sm, 4px)}.layer-panel-body::-webkit-scrollbar-thumb:hover{background:#00f5a066}.layer-item{background:transparent;border:none;border-bottom:1px solid rgba(255,255,255,.08);border-radius:0;padding:4px;display:flex;flex-direction:column;gap:3px;transition:background .15s ease}.layer-item:last-child{border-bottom:none}.layer-item:hover{background:#ffffff08;border-radius:var(--ui-raio-sm, 4px)}.layer-item-row{display:flex;align-items:center;justify-content:space-between;min-height:18px}.layer-item-label{display:flex;align-items:center;gap:7px;font-size:11px;font-weight:600;line-height:1.2;color:#ffffffe6;cursor:pointer;-webkit-user-select:none;user-select:none}.layer-chk-visibility{-moz-appearance:none;appearance:none;-webkit-appearance:none;width:14px;height:14px;border:1px solid rgba(255,255,255,.4);border-radius:3px;background:#0006;cursor:pointer;display:inline-flex;align-items:center;justify-content:center;position:relative;transition:all .15s ease;flex-shrink:0;margin:0}.layer-chk-visibility:hover{border-color:#00f5a0}.layer-chk-visibility:checked{background:#00f5a0;border-color:#00f5a0}.layer-chk-visibility:checked:after{content:"";width:3.5px;height:7px;border:solid #04150c;border-width:0 1.5px 1.5px 0;transform:rotate(45deg) translateY(-.5px);display:block}.layer-item-actions{display:flex;align-items:center;gap:4px}.btn-layer-action{background:transparent;border:none;color:#fff6;cursor:pointer;padding:2px;border-radius:3px;display:flex;align-items:center;justify-content:center;transition:all .15s}.btn-layer-action:hover{color:#00f5a0;background:#ffffff14}.btn-layer-action.active{color:#f43f5e;background:#f43f5e26}.layer-controls-row{display:flex;align-items:center;justify-content:space-between;gap:8px;font-size:9.5px;line-height:1;color:#ffffff80;padding-left:21px}.layer-opacity-slider{flex:1;height:3px;margin:0;border-radius:2px;background:#ffffff26;accent-color:#00f5a0;cursor:pointer}.scale-mode-pill{font-size:8.5px;font-weight:600;padding:1px 6px;border-radius:6px;background:#ffffff0f;color:#ffffffb3;cursor:pointer;border:1px solid rgba(255,255,255,.1);transition:all .15s;line-height:1.2}.scale-mode-pill:hover{border-color:#00f5a0;color:#00f5a0;background:#00f5a01a}:host([sem-painel-camadas]) .qgis-layer-panel,:host([sem-painel-camadas]) #btn-toggle-layers,:host([sem-barra-rapida]) .cad-quick-toolbar{display:none!important}.cad-quick-toolbar{position:absolute;top:12px;right:12px;z-index:var(--ui-z-workspace-hud, 500);display:flex;flex-direction:column;gap:6px;background:#0c1510eb;backdrop-filter:blur(14px);-webkit-backdrop-filter:blur(14px);border:1px solid rgba(255,255,255,.15);border-radius:8px;padding:5px;box-shadow:0 10px 25px -5px #0009}.cad-btn-tool{background:transparent;border:none;color:#fff9;cursor:pointer;padding:7px;border-radius:5px;display:flex;align-items:center;justify-content:center;transition:all .15s}.cad-btn-tool:hover{background:#ffffff1a;color:#fff}.cad-btn-tool.active{background:#00f5a026;color:#00f5a0;border:1px solid rgba(0,245,160,.3)}.cad-selection-box{pointer-events:none;box-sizing:border-box}.custom-leaflet-marker{cursor:pointer}.custom-leaflet-marker:hover{z-index:1800!important}.custom-leaflet-marker .cad-pt svg{transition:transform .12s ease-out}.custom-leaflet-marker:hover .cad-pt svg{transform:scale(1.3)}.leaflet-popup-content-wrapper{background:#0f1712!important;color:#f8fafc!important;border:1px solid rgba(255,255,255,.15)!important;border-radius:8px!important;box-shadow:0 10px 25px #0009!important;padding:0!important;backdrop-filter:blur(16px)!important;-webkit-backdrop-filter:blur(16px)!important}.leaflet-popup-tip{background:#0f1712!important;border:1px solid rgba(255,255,255,.15)!important;box-shadow:none!important}.leaflet-popup-close-button{color:#fff9!important;padding:6px!important;transition:color .15s ease}.leaflet-popup-close-button:hover{color:#fff!important}.leaflet-popup-content{margin:12px 14px!important;line-height:1.4;font-family:inherit;color:#f8fafc}.compact-popup .leaflet-popup-content{margin:10px 12px!important}.ui-popup-actions-footer{display:flex;gap:6px;margin-top:8px;padding-top:8px;border-top:1px solid rgba(255,255,255,.1);justify-content:flex-end;align-items:center;flex-wrap:wrap}.ui-popup-btn{display:inline-flex;align-items:center;justify-content:center;font-family:inherit;font-size:11px;font-weight:500;padding:4px 9px;border-radius:var(--ui-raio-borda, 6px);cursor:pointer;transition:all .15s ease;border:1px solid transparent;outline:none;line-height:1.25;-webkit-user-select:none;user-select:none}.ui-popup-btn-primary{background:var(--ui-cor-primaria, #00f5a0);color:#080d0a;font-weight:600;border-color:var(--ui-cor-primaria, #00f5a0)}.ui-popup-btn-primary:hover{filter:brightness(1.1);box-shadow:0 0 10px #00f5a059}.ui-popup-btn-secondary{background:#ffffff14;color:#fff;border-color:#ffffff2e}.ui-popup-btn-secondary:hover{background:#ffffff29;border-color:#ffffff4d}.ui-popup-btn-destrutivo{background:#ef444426;color:#f87171;border-color:#ef444459}.ui-popup-btn-destrutivo:hover{background:#ef444440;border-color:#ef444499;color:#fff}@media (max-width: 520px){.qgis-layer-panel{top:8px;left:8px;right:8px;width:auto;max-height:calc(100% - 16px)}.qgis-layer-panel.collapsed{transform:translateY(-115%)}.layer-panel-close{min-width:36px;min-height:36px;font-size:16px}.layer-action-btn{min-width:32px;min-height:32px}}.cad-destaque-marker-container{pointer-events:none!important;background:transparent!important;border:none!important;overflow:visible!important}.cad-destaque-marker-container *{pointer-events:none!important}.cad-pulse-highlight{position:relative;width:52px;height:52px;display:flex;align-items:center;justify-content:center;pointer-events:none!important;user-select:none;-webkit-user-select:none}.cad-pulse-core{position:absolute;width:12px;height:12px;border-radius:50%;background-color:var(--cad-pulse-cor, #00f5a0);border:2px solid #ffffff;box-sizing:border-box;pointer-events:none!important}.cad-pulse-ring{position:absolute;width:100%;height:100%;border-radius:50%;border:2px solid var(--cad-pulse-cor, #00f5a0);background-color:color-mix(in srgb,var(--cad-pulse-cor, #00f5a0) 14%,transparent);box-sizing:border-box;pointer-events:none!important;opacity:0;animation:cad-pulse-ping 1.8s cubic-bezier(0,0,.2,1) infinite}.cad-pulse-ring.ring-2{animation-delay:.9s}@keyframes cad-pulse-ping{0%{transform:scale(.3);opacity:.9}70%{opacity:.35}to{transform:scale(1);opacity:0}}@media (prefers-reduced-motion: reduce){.cad-pulse-ring{animation:none;opacity:.6;transform:scale(.6)}}.cad-marker-selected,.ponto-selecionado{z-index:2000!important}@media (prefers-reduced-motion: reduce){.custom-leaflet-marker .cad-pt svg{transition:none}}.ui-popup-actions-footer{margin-top:8px;padding-top:6px;border-top:1px solid rgba(255,255,255,.12);display:flex;gap:6px;flex-wrap:wrap}.ui-popup-btn{display:inline-flex;align-items:center;justify-content:center;padding:4px 8px;font-size:11px;font-weight:600;border-radius:var(--ui-raio-sm, 4px);border:1px solid rgba(255,255,255,.15);background:#ffffff14;color:#fff;cursor:pointer;line-height:1.2;transition:all .15s ease;-webkit-user-select:none;user-select:none}.ui-popup-btn:hover{background:#ffffff2e;border-color:#ffffff4d}.ui-popup-btn-primary{background:#00f5a0;color:#06130b;border-color:#00f5a0}.ui-popup-btn-primary:hover{background:#10ffad;box-shadow:0 0 8px #00f5a066}.ui-popup-btn-danger{background:#f43f5e33;color:#f43f5e;border-color:#f43f5e66}.ui-popup-btn-danger:hover{background:#f43f5e59;color:#fff}.cad-draw-toolbar{right:auto;left:12px;max-height:calc(100% - 24px);overflow-y:auto}.cad-draw-btn{font:600 11px var(--ui-fonte-base, sans-serif);padding:5px 9px;white-space:nowrap;justify-content:flex-start}.cad-ferramenta-ativa .leaflet-marker-icon{pointer-events:none!important}.cad-sr-only{position:absolute;width:1px;height:1px;margin:-1px;padding:0;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap;border:0}';function ja(){return`
|
|
132
132
|
<style>
|
|
133
|
-
${
|
|
134
|
-
${
|
|
133
|
+
${M.leafletCss}
|
|
134
|
+
${Ga}
|
|
135
135
|
</style>
|
|
136
136
|
<div class="cad-root" id="cad-root" role="region" aria-label="Mapa CAD">
|
|
137
137
|
<div class="cad-map-container" id="cad-map-container"></div>
|
|
@@ -163,38 +163,38 @@
|
|
|
163
163
|
</button>
|
|
164
164
|
</div>
|
|
165
165
|
</div>
|
|
166
|
-
`}function hn(a,t,e,o){if(e!==o){if(t==="sat-opacity"){const i=parseFloat(o);isNaN(i)||a.setLayerOpacity("satelite",i)}else if(t==="scale-mode")(o==="world"||o==="screen")&&(a.setLayerScaleMode("perimetro",o),a.setLayerScaleMode("vertices",o));else if(t==="modo-sequencial")a.host.modoSequencial=o!==null&&o!=="false";else if(t==="chave-grupo")a.host.chaveGrupo=o||void 0;else if(t==="zona-projecao"||t==="fuso"){const i=parseInt(o,10);!isNaN(i)&&i>0&&(a.atualizarZonaProjecao(i),t==="fuso"&&a.host.getAttribute("zona-projecao")!==o?a.host.setAttribute("zona-projecao",o):t==="zona-projecao"&&a.host.hasAttribute("fuso")&&a.host.getAttribute("fuso")!==o&&a.host.setAttribute("fuso",o),a.controller.zonaProjecao=i,a.controller.context.zonaProjecao=i)}else if(t==="canal-configuracao")a.broadcastConfig.conectar(o);else if(t==="crosshair"){const i=o!==null&&o!=="false";a.mapContainer&&(a.mapContainer.style.cursor=i?"crosshair":"");const n=a.controller.getMap();if(n){const r=n.getContainer();r&&(r.style.cursor=i?"crosshair":"")}a.controller.core.config.crosshair=i}}}function Ci(a){const t=a;if(!t||!t._leaflet_id)return!1;try{delete t._leaflet_id}catch{t._leaflet_id=void 0}return!0}function un(a){if(!a.mapContainer)return;if(a.controller.getMap()||Ci(a.mapContainer),a.controller.init(a.mapContainer,a.shadow),a.toolbarPainel.vincularEventos(),a.renderLayersUI(),a.host.hasAttribute("modo-sequencial")&&(a.controller.modoCliqueSequencialAtivo=!0,a.controller.context.modoSequencial=!0),a.host.hasAttribute("chave-grupo")){const o=a.host.getAttribute("chave-grupo");o&&(a.host.chaveGrupo=o)}if(a.host.hasAttribute("zona-projecao")||a.host.hasAttribute("fuso")){const o=a.host.zonaProjecao;a.controller.zonaProjecao=o,a.controller.context.zonaProjecao=o}if(a.host.hasAttribute("crosshair")){const o=a.host.getAttribute("crosshair")!=="false";a.mapContainer&&(a.mapContainer.style.cursor=o?"crosshair":""),a.controller.core.config.crosshair=o}a.colecoesDados.sincronizarInicial(),a.controller.layerManager.onChange(o=>{a.renderLayersUI(),a.host.dispatchEvent(new CustomEvent("ui-camadas-alteradas",{detail:{layers:o},bubbles:!0,composed:!0}))});const t=a.controller.context.onMarkerClick;a.controller.context.onMarkerClick=(o,i,n,r)=>{bi(a.obterContextoEventos(),o,i,n,r,t,a.colecoesDados.customMarkerClickHandler)},a.controller.context.onSegmentoClick=(o,i,n)=>{xi(a.obterContextoEventos(),o,i,n)},a.controller.context.onPopupAcao=(o,i,n)=>{a.dispararAcaoPopup(o,i,n)};const e=a.controller.getMap();e&&e.on("click",o=>{a.toolbarPainel.houveMovimentoMouse||a.tratarCliqueLivreCanvas(o,o.latlng,o.containerPoint)}),setTimeout(()=>{a.invalidateSizeSafely()},150)}function pn(a){a.querySelectorAll(".cad-quick-toolbar .cad-btn-tool, .layer-panel-close").forEach(t=>{const e=t.getAttribute("title");e&&!t.hasAttribute("aria-label")&&t.setAttribute("aria-label",e)})}function po(a,t){const e=a.getElementById("btn-toggle-snap");e==null||e.classList.toggle("active",t),e==null||e.setAttribute("aria-pressed",String(t))}function fn(a){return a<=0?"Nenhuma feição selecionada":a===1?"1 feição selecionada":`${a} feições selecionadas`}function mn(a){return a?`Ferramenta ${a} ativa`:"Ferramenta desativada"}function fo(a,t){const e=a.getElementById("cad-status");e&&e.textContent!==t&&(e.textContent=t)}function gn(a,t){const e=i=>{var r;const n=(r=i.detail)==null?void 0:r.feicoes;fo(t,fn(Array.isArray(n)?n.length:0))},o=i=>{var r;const n=((r=i.detail)==null?void 0:r.ferramenta)??null;fo(t,mn(n))};return a.addEventListener("cad-selecao",e),a.addEventListener("cad-ferramenta",o),()=>{a.removeEventListener("cad-selecao",e),a.removeEventListener("cad-ferramenta",o)}}function X(a,t){let e,o;if(Array.isArray(a))[e,o]=a;else if(a&&typeof a=="object"){const n=a;e=n.lat??n.latitude,o=n.lng??n.lon??n.longitude}else return null;const i=S.parseCoordenada(e,o,t);return!i||!Number.isFinite(i.lat)||!Number.isFinite(i.lon)?null:[i.lat,i.lon]}function vn(a,t){return a[0]===t[0]&&a[1]===t[1]}function Ge(a,t){const e=a.map(o=>X(o,t)).filter(o=>o!==null);return e.length>1&&vn(e[0],e[e.length-1])&&e.pop(),e.length>=3?e:null}function Ee(a,t){const e=a.map(o=>X(o,t)).filter(o=>o!==null);return e.length>=2?e:null}function Li(a,t){if(!Array.isArray(a)||a.length===0)return null;const o=(Array.isArray(a[0])&&Array.isArray(a[0][0])?a:[a]).map(i=>Ge(i,t));return o.some(i=>i===null)?null:o}function yn(a,t){const e=S.parseCoordenada(a.lat,a.lon);return e?{id:String(a.id),camadaId:t,geometria:{tipo:"Point",coordenada:[e.lat,e.lon]},propriedades:{...a}}:null}function bn(a,t,e){const o=t.get(String(a.ponto_inicio_id)),i=t.get(String(a.ponto_fim_id));if(!o||!i)return null;const n=S.parseCoordenada(o.lat,o.lon),r=S.parseCoordenada(i.lat,i.lon);if(!n||!r)return null;const s=(a.tipo_limite_sigef??a.tipo_limite)==="LN1";return{id:String(a.id??`${a.ponto_inicio_id}-${a.ponto_fim_id}`),camadaId:e,geometria:{tipo:"LineString",coordenadas:[[n.lat,n.lon],[r.lat,r.lon]]},estilo:s?{dashArray:"6, 6"}:void 0,propriedades:{...a}}}function xn(a,t){if(!a.poligono_wkt)return null;const e=/POLYGON\s*\(\s*\(\s*(.*?)\s*\)\s*\)/i.exec(a.poligono_wkt);if(!e)return null;const o=e[1].split(",").map(n=>{const[r,s]=n.trim().split(/\s+/);return[s,r]}),i=Ge(o);return i?{id:String(a.id??a.nome??""),camadaId:t,geometria:{tipo:"Polygon",aneis:[i]},propriedades:{nome:a.nome,nome_propriedade:a.nome_propriedade}}:null}function mo(a,t){const e=Ta(a);if(!e)return null;const o=[];for(const i of e){const n=X(i.ponto,t);if(!n)return null;const r={ponto:n},s=i.entrada&&X(i.entrada,{...t,aceitarOrigem:!0}),c=i.saida&&X(i.saida,{...t,aceitarOrigem:!0});s&&(r.entrada=s),c&&(r.saida=c),o.push(r)}return o}const Pn=new Set(["Point","LineString","Polygon","Circle","Text"]);function Bt(a,t,e){if(!a||typeof a!="object")return null;const o=a,i=o.geometria;if(!i||!Pn.has(i.tipo)||o.id===void 0||o.id===null||o.id==="")return null;let n=null;switch(i.tipo){case"Point":{const s=X(i.coordenada,e);s&&(n={tipo:"Point",coordenada:s});break}case"Text":{const s=X(i.coordenada,e);s&&typeof i.texto=="string"&&i.texto&&(n={tipo:"Text",coordenada:s,texto:i.texto});break}case"LineString":{const s=Array.isArray(i.partes)?i.partes.map(l=>Array.isArray(l)?Ee(l,e):null).filter(l=>l!==null):[];if(s.length>0)n=yt(s);else{const l=Array.isArray(i.coordenadas)?Ee(i.coordenadas,e):null;l&&(n=yt([l]))}const c=s.length<=1?mo(i.curva,e):null;n&&n.tipo==="LineString"&&c&&c.length>=2&&(n={tipo:"LineString",coordenadas:bt(c,!1),curva:c});break}case"Polygon":{const s=Array.isArray(i.aneis)?Li(i.aneis,e):null;s&&(n={tipo:"Polygon",aneis:s});const c=s&&s.length===1?mo(i.curva,e):null;n&&c&&c.length>=3&&(n={tipo:"Polygon",aneis:[bt(c,!0)],curva:c});break}case"Circle":{const s=X(i.centro,e),c=Number(i.raioMetros);s&&Number.isFinite(c)&&c>0&&(n={tipo:"Circle",centro:s,raioMetros:c});break}}if(!n)return null;const r={id:String(o.id),camadaId:t,geometria:n,estilo:o.estilo&&typeof o.estilo=="object"?{...o.estilo}:void 0,propriedades:o.propriedades&&typeof o.propriedades=="object"?{...o.propriedades}:{},bloqueada:!!o.bloqueada,status:"oficial",excluida:!!o.excluida};return o.oculta&&(r.oculta=!0),(typeof o.entidadeId=="string"||typeof o.entidadeId=="number")&&(r.entidadeId=String(o.entidadeId)),r.status=Y({...r,status:o.status}),r}const pe="cad-cursores",Cn=/^#[0-9a-f]{3,8}$/i,Ln="#94a3b8";function Qt(a){return typeof a=="string"&&Cn.test(a.trim())?a.trim():Ln}const Sn='<svg width="18" height="18" viewBox="0 0 24 24" style="display:block;filter:drop-shadow(0 1px 1px rgba(0,0,0,.6))"><path d="M3 2 L3 19 L8 14.5 L11.5 22 L14.5 20.5 L11 13.5 L18 13 Z" fill="currentColor" stroke="#fff" stroke-width="1.2" stroke-linejoin="round"/></svg>';function go(a){const t=document.createElement("div");t.style.cssText=`color:${Qt(a.cor)};position:relative;pointer-events:none`,t.innerHTML=Sn;const e=document.createElement("span");return e.textContent=String(a.nome??a.id),e.style.cssText=`position:absolute;left:16px;top:14px;white-space:nowrap;font:600 11px sans-serif;color:#fff;background:${Qt(a.cor)};padding:1px 5px;border-radius:3px;max-width:160px;overflow:hidden;text-overflow:ellipsis`,t.appendChild(e),v.divIcon({className:"custom-leaflet-marker cad-cursor-remoto",iconSize:[18,18],iconAnchor:[3,2],html:t})}class Si{constructor(t){p(this,"marcadores",new Map);this.obterMapa=t}get quantidade(){return this.marcadores.size}atualizar(t,e){const o=this.obterMapa();if(!o||!t||t.id===void 0||t.id===null||t.id===""||!Number.isFinite(e==null?void 0:e[0])||!Number.isFinite(e==null?void 0:e[1]))return!1;const i=String(t.id),n=`${t.nome??""}\0${Qt(t.cor)}`,r=this.marcadores.get(i);if(r)return r.marker.setLatLng(e),r.assinatura!==n&&(r.marker.setIcon(go(t)),r.assinatura=n),!0;o.getPane(pe)||(o.createPane(pe).style.zIndex="9500");const s=v.marker(e,{icon:go(t),pane:pe,interactive:!1,keyboard:!1}).addTo(o);return this.marcadores.set(i,{marker:s,assinatura:n}),!0}remover(t){const e=this.marcadores.get(String(t));return e?(e.marker.remove(),this.marcadores.delete(String(t)),!0):!1}limpar(){for(const t of this.marcadores.values())t.marker.remove();this.marcadores.clear()}}const qt=a=>`${a.camadaId}\0${a.id}`;class Mi{constructor(t){p(this,"itens",new Map);this.dep=t}get quantidade(){return this.itens.size}contem(t){return this.itens.has(qt(t))}obter(){const t=[];for(const e of this.itens.values()){const o=this.dep.obterFeicao(e);o&&t.push(o)}return t}selecionar(t,e=!1){const o=this.assinatura(),i=new Set;e||this.itens.forEach(n=>i.add(n.camadaId)),e||this.itens.clear();for(const n of t)this.alcancavel(n)&&(this.itens.set(qt(n),{camadaId:n.camadaId,id:n.id}),i.add(n.camadaId));this.finalizar(o,i)}alternar(t){const e=this.assinatura(),o=qt(t);this.itens.has(o)?this.itens.delete(o):this.alcancavel(t)&&this.itens.set(o,{camadaId:t.camadaId,id:t.id}),this.finalizar(e,new Set([t.camadaId]))}alternarVarias(t){const e=this.assinatura(),o=new Set;for(const i of t){const n=qt(i);this.itens.has(n)?this.itens.delete(n):this.alcancavel(i)&&this.itens.set(n,{camadaId:i.camadaId,id:i.id}),o.add(i.camadaId)}this.finalizar(e,o)}alcancavel(t){const e=this.dep.obterFeicao(t);return!!e&&(!this.dep.selecionavel||this.dep.selecionavel(e))}limpar(){if(this.itens.size===0)return;const t=this.assinatura(),e=new Set([...this.itens.values()].map(o=>o.camadaId));this.itens.clear(),this.finalizar(t,e)}reconciliar(){const t=this.assinatura(),e=new Set;for(const[o,i]of this.itens){const n=this.dep.obterFeicao(i);(!n||n.excluida||this.dep.visivel&&!this.dep.visivel(n))&&(this.itens.delete(o),e.add(i.camadaId))}e.size!==0&&this.finalizar(t,e)}assinatura(){return[...this.itens.keys()].join("|")}finalizar(t,e){for(const i of e){const n=new Set;for(const r of this.itens.values())r.camadaId===i&&n.add(r.id);this.dep.aplicarVisual(i,n)}if(this.assinatura()===t)return;const o=this.obter();this.dep.aoSelecionar(o),o.length<=1&&this.dep.aoSelecionarUma(o[0]??null)}}const Mn={Point:"Ponto",LineString:"Linha",Polygon:"Polígono",Circle:"Círculo",Text:"Texto"},An=new Set(["name","nome","category","categoria","description","descricao","author","autor","date","data","created_at","criadoEm"]),vo=6;function Ct(a,t){var e;for(const o of t){const i=(e=a.propriedades)==null?void 0:e[o];if(i!=null&&String(i)!=="")return String(i)}return""}function wn(a){const t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(a),e=t?new Date(Number(t[1]),Number(t[2])-1,Number(t[3])):new Date(a);return Number.isNaN(e.getTime())?a:e.toLocaleDateString("pt-BR")}function En(a){const t=typeof a=="object"?JSON.stringify(a):String(a);return t.length>80?`${t.slice(0,77)}...`:t}function zt(a){const t=a.geometria;switch(t.tipo){case"Point":case"Text":return t.coordenada;case"Circle":return t.centro;case"LineString":return t.coordenadas[Math.floor(t.coordenadas.length/2)];case"Polygon":{const e=t.aneis[0],o=e.reduce((n,r)=>n+r[0],0)/e.length,i=e.reduce((n,r)=>n+r[1],0)/e.length;return[o,i]}}}function kn(a){const t=a.geometria,e=[],o=Q(t),i=tt(t);if(t.tipo==="Polygon")e.push(["Área",st(o??0)],["Perímetro",G(i??0)]),e.push(["Vértices",String(t.aneis.reduce((s,c)=>s+c.length,0))]);else if(t.tipo==="LineString"){const s=j(t);e.push(["Extensão",G(i??0)],["Vértices",String(s.reduce((c,l)=>c+l.length,0))]),s.length>1&&e.push(["Partes",String(s.length)])}else t.tipo==="Circle"&&e.push(["Raio",G(t.raioMetros)],["Área",st(o??0)]);const[n,r]=zt(a);return e.push(["Coordenadas",`${n.toFixed(6)}, ${r.toFixed(6)}`]),e}class Ai{constructor(t){p(this,"popup",null);p(this,"feicaoAtual",null);p(this,"margens",{topo:20,base:20,esquerda:20,direita:20});this.dep=t}definirMargens(t){this.margens={...this.margens,...t}}get aberto(){return this.feicaoAtual}abrir(t){const e=this.dep.obterMapa();if(!e)return;this.fechar(),this.feicaoAtual=t,this.popup=v.popup({className:"compact-popup",maxWidth:280,closeOnClick:!1,autoClose:!1,autoPanPaddingTopLeft:v.point(this.margens.esquerda,this.margens.topo),autoPanPaddingBottomRight:v.point(this.margens.direita,this.margens.base)}).setLatLng(zt(t)).setContent(this.montar(t));const o=this.popup;this.dep.liberar?this.dep.liberar(()=>o.openOn(e)):o.openOn(e)}atualizar(t){var e;!this.popup||((e=this.feicaoAtual)==null?void 0:e.id)!==t.id||this.feicaoAtual.camadaId!==t.camadaId||(this.feicaoAtual=t,this.popup.setLatLng(zt(t)).setContent(this.montar(t)))}fechar(){const t=this.popup;this.popup=null,this.feicaoAtual=null,t==null||t.close()}montar(t){var f;const e=this.dep.obterCamada(t.camadaId),o=Z(((f=t.estilo)==null?void 0:f.corTraco)??(e==null?void 0:e.estilo.corPrimaria),"#38bdf8"),i=(b,A="",M)=>{const C=document.createElement(b);return A&&(C.style.cssText=A),M!==void 0&&(C.textContent=M),C},n=i("div","font-family:var(--ui-fonte-base,sans-serif);color:rgba(255,255,255,.9);line-height:1.35;min-width:200px;border-left:3px solid "+o+";padding-left:8px");n.className="cad-feicao-popup",n.appendChild(i("div","font-weight:700;font-size:13px;margin-bottom:1px",Ct(t,["name","nome"])||t.id));const r=Ct(t,["category","categoria"]),s=[Mn[t.geometria.tipo],(e==null?void 0:e.nome)??t.camadaId,r].filter(Boolean).join(" · ");n.appendChild(i("div","font-size:11px;color:rgba(255,255,255,.6);margin-bottom:4px",s));const c=Ct(t,["description","descricao"]);c&&n.appendChild(i("div","font-size:11px;margin-bottom:4px",c));const l=b=>{const A=i("div","font-size:11px;margin-bottom:4px");for(const[M,C]of b){const k=i("div");k.appendChild(i("strong","",`${M}: `)),k.appendChild(document.createTextNode(C)),A.appendChild(k)}return A};n.appendChild(l(kn(t)));const d=Object.entries(t.propriedades??{}).filter(([b,A])=>!An.has(b)&&A!==void 0&&A!==null&&A!=="");d.length>0&&(n.appendChild(l(d.slice(0,vo).map(([b,A])=>[b,En(A)]))),d.length>vo&&n.appendChild(i("div","font-size:10px;color:rgba(255,255,255,.55);margin-bottom:4px",`${d.length} atributos`)));const h=Ct(t,["author","autor"]),u=Ct(t,["date","data","created_at","criadoEm"]);if(h||u){const b=[h,u?wn(u):""].filter(Boolean).join(" · ");n.appendChild(i("div","font-size:10px;color:rgba(255,255,255,.55);margin-bottom:4px",b))}const g=i("div","display:flex;gap:4px;flex-wrap:wrap;margin-top:6px"),m=[["inspecionar","Inspecionar"],["zoom","Zoom"]];(t.geometria.tipo==="LineString"||t.geometria.tipo==="Polygon"||t.geometria.tipo==="Point")&&m.push(["vertices","Vértices"]),t.geometria.tipo==="Point"&&m.push(["copiar","Copiar"]);for(const[b,A]of m){const M=i("button","font-size:11px;padding:2px 8px;border-radius:4px;border:1px solid rgba(255,255,255,.25);background:rgba(255,255,255,.08);color:inherit;cursor:pointer",A);M.type="button",M.dataset.acao=b,M.addEventListener("click",C=>{C.stopPropagation(),this.dep.aoAcao(b,this.feicaoAtual??t)}),g.appendChild(M)}return n.appendChild(g),n}}class zn{constructor(t){p(this,"_ligado",!0);p(this,"_altSegurado",!1);p(this,"atalhoS",!0);p(this,"conectado",!1);p(this,"aoTeclaBaixo",t=>{if(t.key==="Alt"){this.definirAlt(!0);return}this.atalhoS&&(t.key==="s"||t.key==="S")&&!t.ctrlKey&&!t.metaKey&&!t.altKey&&!De(t)&&this.alternar()});p(this,"aoTeclaCima",t=>{t.key==="Alt"&&this.definirAlt(!1)});p(this,"aoPerderFoco",()=>{this.definirAlt(!1)});this.contexto=t}get ativo(){return this._ligado&&!this._altSegurado}get ligado(){return this._ligado}definir(t){this._ligado!==t&&(this._ligado=t,this.notificar())}alternar(){this.definir(!this._ligado)}conectar(){if(this.conectado)return;this.conectado=!0;const t=this.contexto.alvo??window;t.addEventListener("keydown",this.aoTeclaBaixo),t.addEventListener("keyup",this.aoTeclaCima),t.addEventListener("blur",this.aoPerderFoco)}desconectar(){if(!this.conectado)return;this.conectado=!1;const t=this.contexto.alvo??window;t.removeEventListener("keydown",this.aoTeclaBaixo),t.removeEventListener("keyup",this.aoTeclaCima),t.removeEventListener("blur",this.aoPerderFoco),this._altSegurado=!1}definirAlt(t){this._altSegurado!==t&&(this._altSegurado=t,this.notificar())}notificar(){this.contexto.aoMudar({ativo:this.ativo,ligado:this._ligado,temporario:this._altSegurado})}}const te=63710088e-1,yo=111320,ee=a=>a*Math.PI/180;function gt(a){return{lat0:a[0],lon0:a[1],cos0:Math.cos(ee(a[0]))}}function ke(a,t){return[ee(a[1]-t.lon0)*t.cos0*te,ee(a[0]-t.lat0)*te]}function vt(a,t){return[t.lat0+a[1]/te*(180/Math.PI),t.lon0+a[0]/(te*t.cos0)*(180/Math.PI)]}function je(a,t){const e=o=>{let i=!1;for(let n=0,r=o.length-1;n<o.length;r=n++){const[s,c]=o[n],[l,d]=o[r];s>a[0]!=l>a[0]&&a[1]<(d-c)*(a[0]-s)/(l-s)+c&&(i=!i)}return i};return!t[0]||!e(t[0])?!1:!t.slice(1).some(e)}function wi(a,t,e,o){const i=t[0]-a[0],n=t[1]-a[1],r=o[0]-e[0],s=o[1]-e[1],c=i*s-n*r;if(Math.abs(c)<1e-12)return null;const l=((e[0]-a[0])*s-(e[1]-a[1])*r)/c,d=((e[0]-a[0])*n-(e[1]-a[1])*i)/c;return l<0||l>1||d<0||d>=1?null:{t:l,u:d}}function oe(a){let t=0;for(let e=0;e<a.length;e++){const[o,i]=a[e],[n,r]=a[(e+1)%a.length];t+=o*r-n*i}return Math.abs(t)/2}function Ei(a,t){if(a.length<3||t.length<2)return null;const e=gt(a[0]),o=a.map(r=>ke(r,e)),i=t.map(r=>ke(r,e)),n=ki(o,i,0);return n&&n.length>=2?n.map(r=>r.map(s=>vt(s,e))):null}function ki(a,t,e){if(e>8)return null;const o=a.length,i=[];for(let P=0;P<t.length-1;P++)for(let y=0;y<o;y++){const x=wi(t[P],t[P+1],a[y],a[(y+1)%o]);x&&i.push({tLinha:P+x.t,tAnel:y+x.u,ponto:[t[P][0]+x.t*(t[P+1][0]-t[P][0]),t[P][1]+x.t*(t[P+1][1]-t[P][1])]})}if(i.sort((P,y)=>P.tLinha-y.tLinha),i.length<2)return null;const[n,r]=i,s=[];for(let P=Math.floor(n.tLinha)+1;P<=Math.floor(r.tLinha);P++)P>n.tLinha&&P<r.tLinha&&s.push(t[P]);const c=[n.ponto,...s,r.ponto];let l=n,d=r,h=c;n.tAnel>r.tAnel&&(l=r,d=n,h=[...c].reverse());const u=Math.floor(l.tAnel),g=Math.floor(d.tAnel),m=h.slice(1,-1),f=[l.ponto];for(let P=u+1;P<=g;P++)f.push(a[P%o]);f.push(d.ponto,...[...m].reverse());const b=[d.ponto];for(let P=g+1;P<=u+o;P++)b.push(a[P%o]);b.push(l.ponto,...m);const M=oe(a)*1e-9,C=[f,b].filter(P=>P.length>=3&&oe(P)>M);if(C.length<2)return null;const k=[r.ponto,...t.slice(Math.floor(r.tLinha)+1)];if(i.length>2&&k.length>=2){const P=[];for(const y of C){const x=ki(y,k,e+1);x?P.push(...x):P.push(y)}return P}return C}function xt(a,t){return a.map(e=>ke(e,t))}const ot=(a,t)=>Math.hypot(a[0]-t[0],a[1]-t[1]);function zi(a,t=0){if(a.length===0||a.some(n=>n.length<2))return null;const e=gt(a[0][0]),o=a.slice(1).map(n=>xt(n,e));let i=xt(a[0],e);for(;o.length>0;){let n=null;if(o.forEach((d,h)=>{const u=i[0],g=i[i.length-1],m=[{inverter:!1,noFim:!0,d:ot(g,d[0])},{inverter:!0,noFim:!0,d:ot(g,d[d.length-1])},{inverter:!1,noFim:!1,d:ot(u,d[d.length-1])},{inverter:!0,noFim:!1,d:ot(u,d[0])}];for(const f of m)(!n||f.d<n.d)&&(n={idx:h,...f})}),!n||n.d>t)return null;const{idx:r,inverter:s,noFim:c}=n;let l=o.splice(r,1)[0];s&&(l=[...l].reverse()),i=c?[...i,...ot(i[i.length-1],l[0])>0?l:l.slice(1)]:[...l,...ot(l[l.length-1],i[0])>0?i:i.slice(1)]}return i.map(n=>vt(n,e))}function In(a,t,e,o){const i=wi(a,t,e,o);return!!i&&i.t>1e-9&&i.t<1-1e-9&&i.u>1e-9}function _n(a,t){for(let e=0;e<a.length;e++)for(let o=0;o<t.length;o++)if(In(a[e],a[(e+1)%a.length],t[o],t[(o+1)%t.length]))return!0;return!1}function Ii(a,t,e=0){if(a.length<3||t.length<3)return null;const o=gt(a[0]),i=xt(a,o),n=xt(t,o);if(_n(i,n))return null;let r={i:0,j:0,d:1/0};for(let d=0;d<i.length;d++)for(let h=0;h<n.length;h++){const u=ot(i[d],n[h]);u<r.d&&(r={i:d,j:h,d:u})}if(r.d>e)return null;const{i:s,j:c}=r,l=[];for(let d=0;d<=i.length;d++)l.push(i[(s+d)%i.length]);for(let d=0;d<=n.length;d++)l.push(n[(c+d)%n.length]);return l.map(d=>vt(d,o))}const bo=16;function xo(a,t,e,o){const i=[];for(let n=0;n<=bo;n++){const r=e+(o-e)*n/bo;i.push([a[0]+t*Math.cos(r),a[1]+t*Math.sin(r)])}return i}function Ft(a,t){const e=ot(a,t)||1;return[-(t[1]-a[1])/e,(t[0]-a[0])/e]}function fe(a,t,e){const o=a.length,i=[],n=o;for(let r=0;r<n;r++){const s=e?a[(r-1+o)%o]:a[Math.max(0,r-1)],c=a[r],l=e?a[(r+1)%o]:a[Math.min(o-1,r+1)],d=r===0&&!e?Ft(c,l):Ft(s,c),h=r===o-1&&!e?Ft(s,c):Ft(c,l);let u=d[0]+h[0],g=d[1]+h[1];const m=Math.hypot(u,g);if(m<1e-9){i.push([c[0]+d[0]*t,c[1]+d[1]*t]);continue}u/=m,g/=m;const f=u*d[0]+g*d[1],b=Math.min(1/Math.max(f,.5),2);i.push([c[0]+u*t*b,c[1]+g*t*b])}return i}function Tn(a){let t=0;for(let e=0;e<a.length;e++){const[o,i]=a[e],[n,r]=a[(e+1)%a.length];t+=(n-o)*(r+i)}return t>0}function _i(a,t){if(!Number.isFinite(t)||t===0)return null;if(a.tipo==="Point"||a.tipo==="Text"||a.tipo==="Circle"){const e=a.tipo==="Circle"?a.centro:a.coordenada,o=a.tipo==="Circle"?a.raioMetros+t:t;if(o<=0)return null;const i=gt(e),n=64;return Array.from({length:n},(r,s)=>[o*Math.cos(2*Math.PI*s/n),o*Math.sin(2*Math.PI*s/n)]).map(r=>vt(r,i))}if(a.tipo==="LineString"){if(t<0||a.coordenadas.length<2||wt(a))return null;const e=gt(a.coordenadas[0]),o=xt(a.coordenadas,e),i=fe(o,t,!1),n=fe([...o].reverse(),t,!1),r=o[o.length-1],s=o[0],c=Math.atan2(r[1]-o[o.length-2][1],r[0]-o[o.length-2][0]),l=Math.atan2(s[1]-o[1][1],s[0]-o[1][0]),d=xo(r,t,c+Math.PI/2,c-Math.PI/2),h=xo(s,t,l+Math.PI/2,l-Math.PI/2);return[...i,...d,...n,...h].map(u=>vt(u,e))}if(a.tipo==="Polygon"){const e=a.aneis[0];if(!e||e.length<3)return null;const o=gt(e[0]);let i=xt(e,o);Tn(i)&&(i=[...i].reverse());const r=fe(i,-t,!0);return r.length<3||t<0&&oe(r)>=oe(i)?null:r.map(s=>vt(s,o))}return null}function Ti(a,t,e){const o=i=>{const n=e/yo,r=t/(yo*Math.max(.01,Math.cos(ee(i[0]))));return[i[0]+n,i[1]+r]};switch(a.tipo){case"Point":return{tipo:"Point",coordenada:o(a.coordenada)};case"Text":return{...a,coordenada:o(a.coordenada)};case"Circle":return{...a,centro:o(a.centro)};case"LineString":{const i=yt(j(a).map(n=>n.map(o)));return a.curva?{...i,curva:lo(a.curva,o)}:i}case"Polygon":{const i={tipo:"Polygon",aneis:a.aneis.map(n=>n.map(o))};return a.curva?{...i,curva:lo(a.curva,o)}:i}}}const Po={m:1,km:1e3,ft:.3048,mi:1609.344},Co={m2:1,ha:1e4,km2:1e6,ac:4046.8564224,alqueire:24200};function Dn(a,t,e){return a*Po[t]/Po[e]}function $n(a,t,e){return a*Co[t]/Co[e]}function qn(a,t,e=2){const o=t==="lat"?a<0?"S":"N":a<0?"O":"L",i=Math.abs(a);let n=Math.floor(i),r=Math.floor((i-n)*60),s=Number(((i-n-r/60)*3600).toFixed(e));s>=60&&(s=0,r+=1),r>=60&&(r=0,n+=1);const c=s.toFixed(e).padStart(e?e+3:2,"0");return`${n}°${String(r).padStart(2,"0")}'${c}"${o}`}function Fn(a){var u;if(typeof a!="string")return null;const t=a.trim().toUpperCase().replace(",","."),e=(u=/[NSLEOW]$/.exec(t))==null?void 0:u[0],o=t.replace(/[NSLEOW]$/,"").trim(),i=o.match(/-?\d+(?:\.\d+)?/g);if(!i||i.length===0||i.length>3||!/^[-\d\s°'"′″.]+$/.test(o))return null;const[n,r="0",s="0"]=i,c=Math.abs(Number(n)),l=Number(r),d=Number(s);if(l<0||l>=60||d<0||d>=60)return null;let h=c+l/60+d/3600;return(n.startsWith("-")||e==="S"||e==="O"||e==="W")&&(h=-h),h}function Nn(a,t){return rt(a,t)}function Ht(a,t,e){return{...a,id:t,geometria:e??JSON.parse(JSON.stringify(a.geometria)),estilo:a.estilo?{...a.estilo}:void 0,propriedades:{...a.propriedades}}}const H="feicoes";class On{constructor(t){this.p=t}dividirComLinha(t){const e=this.p.obterLayerManager(),o=l=>(this.p.emitir("cad-divisao-falhou",{motivo:l}),!1),i=this.p.selecionadas().filter(l=>l.geometria.tipo==="Polygon");let n=i;if(n.length===0){n=[];for(const l of e.getActiveSelectableLayers())l.tipo===H&&n.push(...this.p.lista(l.id).filter(d=>d.geometria.tipo==="Polygon"&&this.p.desenhada(d)))}if(n.length===0)return o(i.length===0&&this.p.selecionadas().some(l=>wt(l.geometria))?"multiparte":"nenhum-poligono");const r=l=>{var d;return!!l.bloqueada||!!((d=e.getLayerDef(l.camadaId))!=null&&d.bloqueada)},s=n.filter(l=>!r(l)&&l.geometria.tipo==="Polygon"&&l.geometria.aneis.length===1);if(s.length===0)return o(n.some(r)?"bloqueada":"poligono-com-furos");let c=!1;for(const l of s){if(l.geometria.tipo!=="Polygon")continue;const d=Ei(l.geometria.aneis[0],t);if(!d)continue;this.p.divisaoAtiva()&&this.p.estaSelecionada({camadaId:l.camadaId,id:l.id})&&this.p.encerrarDesenho(),this.p.removerFeicao(l.camadaId,l.id);const h=[];if(d.forEach((u,g)=>{const m=Ht(l,this.p.idLivre(l.camadaId,`${l.id}-${g+1}`),{tipo:"Polygon",aneis:[u]}),f=this.p.adicionarFeicao(l.camadaId,m);f&&h.push(f)}),h.length!==d.length){for(const u of h)this.p.removerFeicao(u.camadaId,u.id);return this.p.adicionarFeicao(l.camadaId,l),o("geometria-invalida")}if(this.p.emitir("cad-feicao-dividida",{origem:l,partes:h}),c=!0,i.length===0)break}return c||o("sem-intersecao")}gerarBuffer(t,e,o,i={}){const n=this.p.buscar(t,e);if(!n)return null;const r=_i(n.geometria,o);if(!r)return null;const s=i.camadaDestino??t,c=this.p.adicionarFeicao(s,{id:i.id??this.p.idLivre(s,`${e}-buffer`),geometria:{tipo:"Polygon",aneis:[r]},estilo:n.estilo?{...n.estilo}:void 0,propriedades:{...n.propriedades,origem:e}});return c&&this.p.emitir("cad-feicao-criada",{camadaId:s,feicao:c}),c}duplicarFeicao(t,e,o={},i={}){const n=this.p.buscar(t,e);if(!n)return null;const r=Ti(n.geometria,o.lesteM??0,o.norteM??0),s=this.p.adicionarFeicao(t,Ht(n,i.id??this.p.idLivre(t,`${e}-copia`),r));return s&&this.p.emitir("cad-feicao-criada",{camadaId:t,feicao:s}),s}juntarFeicoes(t,e,o={}){const i=h=>(this.p.emitir("cad-uniao-falhou",{motivo:h}),null),n=e.map(h=>this.p.buscar(t,h));if(n.length<2||n.some(h=>!h))return i("feicoes-insuficientes");const r=n;if(new Set(r.map(h=>h.id)).size!==r.length)return i("feicoes-insuficientes");const s=this.p.obterLayerManager();if(r.some(h=>{var u;return h.excluida||h.bloqueada||((u=s.getLayerDef(h.camadaId))==null?void 0:u.bloqueada)}))return i("bloqueada");const c=o.toleranciaM??0;let l=null;if(r.every(h=>h.geometria.tipo==="LineString")){if(r.some(g=>wt(g.geometria)))return i("multiparte");const h=r.map(g=>g.geometria.coordenadas),u=zi(h,c);u&&(l=yt([u]))}else if(r.every(h=>h.geometria.tipo==="Polygon"&&h.geometria.aneis.length===1)){let h=r[0].geometria.aneis[0];for(const u of r.slice(1))h=h?Ii(h,u.geometria.aneis[0],c):null;h&&(l={tipo:"Polygon",aneis:[h]})}else return i("tipos-incompativeis");if(!l)return i("sem-ligacao");for(const h of r)this.p.removerFeicao(t,h.id);const d=this.p.adicionarFeicao(t,Ht(r[0],o.id??this.p.idLivre(t,`${r[0].id}-uniao`),l));if(!d){for(const h of r)this.p.adicionarFeicao(t,h);return i("geometria-invalida")}return this.p.emitir("cad-feicao-unida",{origens:r,resultado:d}),d}}class Rn{constructor(t,e){p(this,"cacheOficiais",new WeakMap);this.p=t,this.regra=e}oficiaisDe(t){const e=this.p.lista(t);let o=this.cacheOficiais.get(e);return o||(o=ae.oficiais(e),this.cacheOficiais.set(e,o)),o}visivelPorVersao(t){const e=this.p.obterLayerManager().getLayerInstance(t.camadaId),o=O.get(H);return e&&o?o.feicaoVisivel(e,t):this.regra.visivel(t,this.oficiaisDe(t.camadaId))}desenhada(t){return!t.excluida&&!t.oculta&&this.visivelPorVersao(t)}aplicarVersoes(){const t=this.p.obterLayerManager(),e=O.get(H);for(const o of t.getLayers()){if(o.tipo!==H)continue;const i=t.getLayerInstance(o.id);i&&e&&e.reavaliarVersoes(i)}this.p.aposDados()}get previasGlobais(){return this.regra.global}definirPreviasGlobais(t){const e=!!t;this.regra.global!==e&&(this.regra.global=e,this.aplicarVersoes(),this.p.emitir("cad-previas",{global:e}))}alternarPreviasGlobais(){this.definirPreviasGlobais(!this.regra.global)}alternarPrevia(t,e){const o=this.p.buscar(t,e);if(!o)return null;const i=at(o),n=this.regra.alternarIndividual(t,i);return this.aplicarVersoes(),this.p.emitir("cad-previas",{camadaId:t,entidadeId:i,ativa:n}),n}previaSolicitada(t,e){const o=this.p.buscar(t,e);return!!o&&this.regra.previaSolicitada(o)}garantirVisivel(t){const e=this.p.obterLayerManager(),o=e.getLayerDef(t.camadaId);if(o&&!o.visivel&&e.setLayerVisibility(t.camadaId,!0),!this.visivelPorVersao(t)){const i=at(t);this.regra.definirIndividual(t.camadaId,i,!0),this.aplicarVersoes(),this.p.emitir("cad-previas",{camadaId:t.camadaId,entidadeId:i,ativa:!0})}}}class Bn{constructor(t){this.p=t}limitesDe(t){let e=1/0,o=1/0,i=-1/0,n=-1/0;for(const r of t){const[[s,c],[l,d]]=Fe(r.geometria);s<e&&(e=s),c<o&&(o=c),l>i&&(i=l),d>n&&(n=d)}return Number.isFinite(e)?[[e,o],[i,n]]:null}enquadrar(t){const e=this.p.obterMapa(),o=this.limitesDe(t);return!e||!o?!1:(o[0][0]===o[1][0]&&o[0][1]===o[1][1]?e.flyTo([o[0][0],o[0][1]],Math.max(e.getZoom(),17)):e.fitBounds(o,{padding:[60,60],maxZoom:18}),!0)}zoomParaFeicao(t,e){const o=this.p.buscar(t,e);return!o||o.excluida?!1:(this.p.garantirVisivel(o),this.enquadrar([o]))}zoomParaFeicoes(t){const e=[];for(const o of Array.isArray(t)?t:[]){const i=this.p.buscar(o.camadaId,o.id);i&&!i.excluida&&(this.p.garantirVisivel(i),e.push(i))}return e.length>0&&this.enquadrar(e)}ajustarTudo(){const t=[];for(const e of this.p.obterLayerManager().getLayers())e.tipo!==H||!e.visivel||t.push(...this.p.lista(e.id).filter(o=>this.p.desenhada(o)));return this.enquadrar(t)}ajustarCamada(t){const e=this.p.obterLayerManager(),o=e.getLayerDef(t);return!o||o.tipo!==H?!1:(o.visivel||e.setLayerVisibility(t,!0),this.enquadrar(this.p.lista(t).filter(i=>this.p.desenhada(i))))}}const Lo=36,Hn=.45;function Vn(a,t){const e=Math.abs(t[0]-a[0]),o=Math.abs(t[1]-a[1]);if(e===0&&o===0)return null;const i=[];for(let n=0;n<Lo;n++){const r=n*2*Math.PI/Lo;i.push([a[0]+e*Math.sin(r),a[1]+o*Math.cos(r)])}return i}function Di(a,t){const e=Math.cos(a[0]*Math.PI/180)||1,o=t[0]-a[0],i=(t[1]-a[1])*e,n=Math.hypot(o,i);return n===0?null:{raio:n,inicio:Math.atan2(o,i),cosLat:e}}function Gn(a,t,e=6){const o=Di(a,t);if(!o||e<3)return null;const i=[];for(let n=0;n<e;n++){const r=o.inicio+n*2*Math.PI/e;i.push([a[0]+o.raio*Math.sin(r),a[1]+o.raio*Math.cos(r)/o.cosLat])}return i}function jn(a,t,e=5){const o=Di(a,t);if(!o||e<3)return null;const i=e*2,n=[];for(let r=0;r<i;r++){const s=r%2===0?o.raio:o.raio*Hn,c=o.inicio+r*2*Math.PI/i;n.push([a[0]+s*Math.sin(c),a[1]+s*Math.cos(c)/o.cosLat])}return n}const ie=["ponto","linha","poligono","retangulo","elipse","poligono-regular","estrela","circulo","texto","caneta","medir-distancia","medir-area","dividir","selecao-laco","conta-gotas"],ze=2;function Ue(a){return typeof a=="string"&&ie.includes(a)}function Mt(a){return a.map(t=>{const e={ponto:t.ponto};return t.alca&&(e.saida=t.alca,e.entrada=Be(t.ponto,t.alca)),e})}function $i(a){return bt(Mt(a),!1)}function me(a,t){const e=ei(a);if(t){const i=e?bt(a,!0):a.map(n=>n.ponto);return e?{tipo:"Polygon",aneis:[i],curva:a}:{tipo:"Polygon",aneis:[i]}}const o=e?bt(a,!1):a.map(i=>i.ponto);return e?{tipo:"LineString",coordenadas:o,curva:a}:{tipo:"LineString",coordenadas:o}}const Un=(a,t)=>a[0]===t[0]&&a[1]===t[1],So={elipse:Vn,"poligono-regular":(a,t)=>Gn(a,t,6),estrela:(a,t)=>jn(a,t,5)};class Vt{constructor(t,e=!1){p(this,"pontos",[]);p(this,"cursor",null);p(this,"ancoras",[]);this.ferramenta=t,this.fechar=e}get nos(){return this.ferramenta==="caneta"?this.ancoras.length:this.pontos.length}get ehSequencial(){return["linha","poligono","caneta","medir-distancia","medir-area","dividir","selecao-laco"].includes(this.ferramenta)}get ehArea(){return this.ferramenta==="poligono"||this.ferramenta==="medir-area"||this.ferramenta==="selecao-laco"||this.ferramenta==="caneta"&&this.fechar}get fechaNoPrimeiro(){return this.nos>=3&&(this.ehArea||this.ferramenta==="caneta")}get primeiro(){var t;return(this.ferramenta==="caneta"?(t=this.ancoras[0])==null?void 0:t.ponto:this.pontos[0])??null}get minimo(){return this.ehArea?3:2}get podeConcluir(){return this.ehSequencial&&this.nos>=this.minimo}mover(t){this.cursor=t}clicar(t){switch(this.ferramenta){case"ponto":return{concluida:{tipo:"Point",coordenada:t}};case"texto":return{concluida:{tipo:"Text",coordenada:t,texto:""}};case"retangulo":return this.pontos.length===0?(this.pontos.push(t),{}):{concluida:this.retangulo(this.pontos[0],t)??void 0};case"circulo":if(this.pontos.length===0)return this.pontos.push(t),{};{const e=rt(this.pontos[0],t);return e>=ze?{concluida:{tipo:"Circle",centro:this.pontos[0],raioMetros:e}}:{}}case"elipse":case"poligono-regular":case"estrela":{if(this.pontos.length===0)return this.pontos.push(t),{};const e=So[this.ferramenta](this.pontos[0],t);return e?{concluida:{tipo:"Polygon",aneis:[e]}}:{}}case"caneta":return this.ancoras.push({ponto:t}),{};case"conta-gotas":return{};default:return this.pontos.length>0&&Un(this.pontos[this.pontos.length-1],t)?{}:(this.pontos.push(t),{})}}definirAlca(t){const e=this.ancoras[this.ancoras.length-1];this.ferramenta==="caneta"&&e&&(e.alca=t)}desfazer(){const t=this.ferramenta==="caneta"?this.ancoras:this.pontos;return t.length===0?!1:(t.pop(),!0)}vertices(){return this.ferramenta==="caneta"?$i(this.ancoras):this.pontos}retangulo(t,e){return t[0]===e[0]||t[1]===e[1]?null:{tipo:"Polygon",aneis:[[[t[0],t[1]],[t[0],e[1]],[e[0],e[1]],[e[0],t[1]]]]}}previa(){const t=this.cursor;switch(this.ferramenta){case"retangulo":return this.pontos.length===1&&t?this.retangulo(this.pontos[0],t):null;case"circulo":{if(this.pontos.length!==1||!t)return null;const e=rt(this.pontos[0],t);return e>=ze?{tipo:"Circle",centro:this.pontos[0],raioMetros:e}:null}case"caneta":{if(this.ancoras.length===0)return null;const e=Mt(t?[...this.ancoras,{ponto:t}]:this.ancoras);return e.length<2?null:me(e,this.ehArea&&e.length>=3)}case"elipse":case"poligono-regular":case"estrela":{if(this.pontos.length!==1||!t)return null;const e=So[this.ferramenta](this.pontos[0],t);return e?{tipo:"Polygon",aneis:[e]}:null}case"ponto":case"texto":case"conta-gotas":return null;default:{const e=t?[...this.pontos,t]:[...this.pontos];return e.length<2?null:this.ehArea&&e.length>=3?{tipo:"Polygon",aneis:[e]}:{tipo:"LineString",coordenadas:e}}}}concluir(){if(!this.podeConcluir)return null;if(this.ferramenta==="caneta")return me(Mt(this.ancoras),this.ehArea);const t=this.vertices();return this.ehArea?{tipo:"Polygon",aneis:[t]}:{tipo:"LineString",coordenadas:t}}concluirFechando(){return this.fechaNoPrimeiro?this.ferramenta==="caneta"?me(Mt(this.ancoras),!0):{tipo:"Polygon",aneis:[this.vertices()]}:null}comprimentoMetros(){const t=this.cursor&&this.nos>0?[...this.vertices(),this.cursor]:this.vertices();return Et(t,!1)}}const qi={topo:0,base:16,esquerda:0,direita:0},Fi=16,Ni=.92,Gt={topo:"--cad-hud-topo",base:"--cad-hud-base",esquerda:"--cad-hud-esquerda",direita:"--cad-hud-direita"},We="position:absolute;box-sizing:border-box;z-index:10000;left:calc(var(--cad-hud-esquerda,0px) + (100% - var(--cad-hud-esquerda,0px) - var(--cad-hud-direita,0px)) / 2);bottom:var(--cad-hud-base,16px);transform:translateX(-50%);width:max-content;max-width:min(92%, calc(100% - var(--cad-hud-esquerda,0px) - var(--cad-hud-direita,0px) - 16px));max-height:calc(100% - var(--cad-hud-topo,0px) - var(--cad-hud-base,16px) - 8px);overflow:hidden;display:flex;flex-wrap:wrap;";function Wn(a,t,e={}){const o={...qi,...e},i=Math.max(0,a-o.esquerda-o.direita);return{centroX:o.esquerda+i/2,base:o.base,larguraMax:Math.max(0,Math.min(a*Ni,i-Fi)),alturaMax:Math.max(0,t-o.topo-o.base-8)}}function Oi(a,t){for(const e of Object.keys(Gt)){const o=t[e];typeof o=="number"&&Number.isFinite(o)&&o>=0?a.style.setProperty(Gt[e],`${o}px`):a.style.removeProperty(Gt[e])}}const Ri="cm-draw-hud",Ie="cad-ferramenta-ativa",et="cad-desenho",lt="#22d3ee",Xn=4,Zn=450,Yn=10,Kn={ponto:"Ponto",linha:"Linha",poligono:"Polígono",retangulo:"Retângulo",elipse:"Elipse","poligono-regular":"Polígono regular (hexágono)",estrela:"Estrela",circulo:"Círculo",texto:"Texto",caneta:"Caneta (Bézier)","medir-distancia":"Medir distância","medir-area":"Medir área",dividir:"Dividir polígono","selecao-laco":"Seleção por laço","conta-gotas":"Conta-gotas"},Jn={ponto:"Clique para colocar",linha:"Clique nos vértices · Enter ou duplo clique conclui",poligono:"Clique nos vértices · Enter ou duplo clique conclui",retangulo:"Clique nos dois cantos",elipse:"Clique no centro e depois no canto da caixa","poligono-regular":"Clique no centro e depois num vértice",estrela:"Clique no centro e depois numa ponta",circulo:"Clique no centro e depois num ponto da borda",texto:"Clique onde o texto vai",caneta:"Clique e arraste para curvar · Enter conclui · 1º ponto fecha","medir-distancia":"Clique nos pontos · Enter conclui","medir-area":"Clique nos vértices · Enter conclui",dividir:"Desenhe a linha de corte · Enter aplica","selecao-laco":"Desenhe o laço · Enter ou 1º ponto fecha e seleciona","conta-gotas":"Clique numa feição para copiar o estilo"};class Bi{constructor(t){p(this,"sessao",null);p(this,"fechar",!1);p(this,"grupo",null);p(this,"previa",null);p(this,"marcas",null);p(this,"medicao",null);p(this,"marcadorSnap",null);p(this,"hud",null);p(this,"campoTexto",null);p(this,"arrastando",!1);p(this,"ultimoClique",null);p(this,"aoClicar",t=>{var n;const e=this.sessao;if(!e||e.ferramenta==="caneta"||this.campoTexto||((n=t.originalEvent)==null?void 0:n.button)!==void 0&&t.originalEvent.button!==0)return;const o=this.coordenada(t);if(e.ferramenta==="conta-gotas"){this.dep.aoAmostrar(o,t.originalEvent);return}if(e.ehSequencial&&this.repetido(t)||this.fechaNoPrimeiroVertice(t))return;const i=e.clicar(o);if(i.concluida){i.concluida.tipo==="Text"?this.pedirTexto(o):this.finalizar(i.concluida);return}this.atualizar()});p(this,"aoPressionar",t=>{var o;const e=this.sessao;!e||e.ferramenta!=="caneta"||((o=t.originalEvent)==null?void 0:o.button)!==0||this.repetido(t)||this.fechaNoPrimeiroVertice(t)||(e.clicar(this.coordenada(t)),this.arrastando=!0,this.atualizar())});p(this,"aoSoltar",()=>{this.arrastando=!1});p(this,"aoMover",t=>{const e=this.sessao;if(!e)return;const o=this.coordenada(t);e.mover(o),this.arrastando&&e.definirAlca(o),this.atualizar()});p(this,"aoDuploClique",()=>{this.concluir()});p(this,"aoTecla",t=>{const e=this.sessao;if(!e)return;const o=De(t);if(t.key==="Escape"){if(o&&!this.campoTexto)return;this.campoTexto?this.cancelarTexto():e.nos>0?this.reiniciar():this.desativar(),t.preventDefault();return}o||(t.key==="Enter"?(this.concluir(),t.preventDefault()):(t.key==="Backspace"||(t.ctrlKey||t.metaKey)&&t.key.toLowerCase()==="z")&&(e.desfazer()&&this.atualizar(),t.preventDefault()))});this.dep=t}get ferramenta(){var t;return((t=this.sessao)==null?void 0:t.ferramenta)??null}get ativo(){return this.sessao!==null}get nos(){var t;return((t=this.sessao)==null?void 0:t.nos)??0}desfazerVertice(){var t;return(t=this.sessao)!=null&&t.desfazer()?(this.atualizar(),!0):!1}ativar(t,e={}){var r;const o=(r=this.sessao)==null?void 0:r.ferramenta;this.desligar(),o&&this.dep.aoDesativar(o),this.limparMedicao();const i=this.dep.map;this.fechar=!!e.fechar,this.sessao=new Vt(t,this.fechar),i.getPane(et)||(i.createPane(et).style.zIndex="8500"),this.grupo=v.layerGroup().addTo(i),this.marcas=v.layerGroup().addTo(this.grupo);const n=i.getContainer();n.classList.add(Ie),n.style.cursor=t==="conta-gotas"?"copy":"crosshair",i.on("click",this.aoClicar),i.on("dblclick",this.aoDuploClique),i.on("mousemove",this.aoMover),i.on("mousedown",this.aoPressionar),i.on("mouseup",this.aoSoltar),window.addEventListener("keydown",this.aoTecla),this.montarHud(),this.atualizar()}desativar(){var e;const t=(e=this.sessao)==null?void 0:e.ferramenta;t&&(this.desligar(),this.dep.aoDesativar(t))}limparMedicao(){var t;(t=this.medicao)==null||t.remove(),this.medicao=null}desligar(){var o,i;const t=this.dep.map;t.off("click",this.aoClicar),t.off("dblclick",this.aoDuploClique),t.off("mousemove",this.aoMover),t.off("mousedown",this.aoPressionar),t.off("mouseup",this.aoSoltar),window.removeEventListener("keydown",this.aoTecla);const e=t.getContainer();e.classList.remove(Ie),e.style.cursor="",(o=this.grupo)==null||o.remove(),this.grupo=null,this.previa=null,this.marcas=null,this.marcadorSnap=null,(i=this.hud)==null||i.remove(),this.hud=null,this.campoTexto=null,this.sessao=null,this.arrastando=!1,this.ultimoClique=null}coordenada(t){const e=[t.latlng.lat,t.latlng.lng];if(!this.dep.snapAtivo())return this.esconderSnap(),e;const o=this.dep.buscarSnap(e);return o?(this.mostrarSnap(o.coordenada),o.coordenada):(this.esconderSnap(),e)}repetido(t){const e=this.ultimoClique,o=Date.now(),i=t.containerPoint,n=!!e&&Math.hypot(e.x-i.x,e.y-i.y)<=Xn&&o-e.t<=Zn;return this.ultimoClique={x:i.x,y:i.y,t:o},n}fechaNoPrimeiroVertice(t){const e=this.sessao,o=e==null?void 0:e.primeiro;if(!e||!o||!e.fechaNoPrimeiro)return!1;const i=this.dep.map.latLngToContainerPoint(o);if(Math.hypot(i.x-t.containerPoint.x,i.y-t.containerPoint.y)>Yn)return!1;const n=e.concluirFechando();return n&&this.finalizar(n),!!n}concluir(){const t=this.sessao;if(!t)return;const e=t.concluir();e&&this.finalizar(e)}botaoDireito(){const t=this.sessao;if(t){if(this.campoTexto){this.cancelarTexto();return}t.podeConcluir?this.concluir():t.nos>0&&t.desfazer()?this.atualizar():this.desativar()}}reiniciar(){var e;const t=(e=this.sessao)==null?void 0:e.ferramenta;t&&(this.sessao=new Vt(t,this.fechar),this.ultimoClique=null,this.arrastando=!1,this.atualizar())}finalizar(t){const e=this.sessao.ferramenta,o=e==="medir-distancia"||e==="medir-area"?this.mostrarMedicao(t,e):null;this.sessao=new Vt(e,this.fechar),this.ultimoClique=null,this.atualizar(),o&&this.dep.aoMedir(o),this.dep.aoGeometria(e,t)}pedirTexto(t){var o,i;if(!this.hud||(i=(o=this.dep).aoSolicitarTexto)!=null&&i.call(o,t)||!this.hud)return;const e=document.createElement("input");e.type="text",e.placeholder="Texto…",e.style.cssText="padding:3px 6px;border-radius:4px;border:1px solid #475569;background:#0f172a;color:#fff;min-width:160px",e.addEventListener("keydown",n=>{if(n.stopPropagation(),n.key==="Enter"){const r=e.value.trim();this.cancelarTexto(),r&&this.finalizar({tipo:"Text",coordenada:t,texto:r})}else n.key==="Escape"&&this.cancelarTexto()}),this.campoTexto=e,this.hud.insertBefore(e,this.hud.querySelector('[data-campo="dica"]')),e.focus()}cancelarTexto(){var t;(t=this.campoTexto)==null||t.remove(),this.campoTexto=null}atualizar(){const t=this.sessao;if(!t||!this.grupo||!this.marcas)return;this.previa&&(this.grupo.removeLayer(this.previa),this.previa=null);const e=t.previa();e&&(this.previa=this.desenharGeometria(e,!0),this.grupo.addLayer(this.previa)),this.marcas.clearLayers();const o=t.ferramenta==="caneta"?t.ancoras.map(i=>i.ponto):t.pontos;if(t.ferramenta==="caneta")for(const i of t.ancoras){if(!i.alca)continue;const n=Be(i.ponto,i.alca);this.marcas.addLayer(v.polyline([n,i.alca],{pane:et,color:lt,weight:1,opacity:.8,interactive:!1}));for(const r of[n,i.alca])this.marcas.addLayer(v.circleMarker(r,{pane:et,radius:3,color:lt,weight:1,fillColor:"#fff",fillOpacity:1,interactive:!1}))}for(const i of o)this.marcas.addLayer(v.circleMarker(i,{pane:et,radius:4,color:"#111",weight:1,fillColor:lt,fillOpacity:1,interactive:!1}));this.atualizarHud(e)}desenharGeometria(t,e){const o={pane:et,color:lt,weight:2,dashArray:e?"6 4":void 0,fillColor:lt,fillOpacity:.15,interactive:!1},i=si(t,o);if(i)return i;if(t.tipo==="Polygon")return v.polygon(t.aneis,o);if(t.tipo==="Circle")return v.circle(t.centro,{...o,radius:t.raioMetros});if(t.tipo==="LineString")return v.polyline(t.coordenadas,o);const n=(t.tipo==="Point",t.coordenada);return v.circleMarker(n,{...o,radius:5})}mostrarMedicao(t,e){this.limparMedicao();const o=v.layerGroup().addTo(this.dep.map);this.medicao=o,o.addLayer(this.desenharGeometria(t,!1));const i=t.tipo==="Polygon"?t.aneis[0]:t.tipo==="LineString"?t.coordenadas:[],n=t.tipo==="Polygon",r=(l,d)=>{const h=document.createElement("div");h.textContent=d,h.style.cssText="white-space:nowrap;font:600 11px sans-serif;color:#fff;background:rgba(15,23,42,.85);padding:1px 5px;border-radius:3px;transform:translate(-50%,-50%)",o.addLayer(v.marker(l,{pane:et,interactive:!1,keyboard:!1,icon:v.divIcon({className:"custom-leaflet-marker",iconSize:void 0,html:h})}))},s=n?i.length:i.length-1;for(let l=0;l<s;l++){const d=i[l],h=i[(l+1)%i.length];r([(d[0]+h[0])/2,(d[1]+h[1])/2],G(rt(d,h)))}const c={tipo:e==="medir-area"?"area":"distancia",pontos:i,comprimentoM:Et(i,!1)};if(t.tipo==="Polygon")c.areaM2=Q(t)??0,c.perimetroM=tt(t)??0;else if(e==="medir-distancia"&&i.length>=3){const l={tipo:"Polygon",aneis:[i]};c.areaM2=Q(l)??0,c.perimetroM=tt(l)??0}return c}mostrarSnap(t){this.grupo&&(this.marcadorSnap?this.marcadorSnap.setLatLng(t):this.marcadorSnap=v.marker(t,{pane:et,interactive:!1,keyboard:!1,icon:v.divIcon({className:"custom-leaflet-marker cm-snap",iconSize:[18,18],html:'<div style="width:18px;height:18px;box-sizing:border-box;border:2px solid #22d3ee;transform:rotate(45deg);border-radius:2px"></div>'})}).addTo(this.grupo))}esconderSnap(){var t;this.marcadorSnap&&((t=this.grupo)==null||t.removeLayer(this.marcadorSnap),this.marcadorSnap=null)}montarHud(){const t=this.sessao;if(!t)return;const e=document.createElement("div");e.id=Ri,e.style.cssText=We+"gap:10px;align-items:center;padding:6px 12px;border-radius:8px;background:rgba(15,23,42,.92);color:#fff;font:12px var(--ui-fonte-base,sans-serif);border:1px solid rgba(255,255,255,.2);pointer-events:auto";const o=s=>{const c=document.createElement("span");return c.dataset.campo=s,c},i=document.createElement("strong");i.textContent=Kn[t.ferramenta];const n=o("dica");n.style.opacity=".7",n.textContent=Jn[t.ferramenta];const r=(s,c,l=!1)=>{const d=document.createElement("button");return d.type="button",d.textContent=s,d.style.cssText=`padding:3px 10px;border-radius:4px;border:1px solid ${l?lt:"rgba(255,255,255,.3)"};background:${l?lt:"transparent"};color:${l?"#111":"#fff"};cursor:pointer;font-weight:600`,d.addEventListener("click",c),d};e.append(i,o("nos"),o("medida"),n),t.ehSequencial&&e.append(r("Concluir",()=>this.concluir(),!0)),e.append(r("Sair",()=>this.desativar())),v.DomEvent.disableClickPropagation(e),v.DomEvent.disableScrollPropagation(e),this.dep.map.getContainer().appendChild(e),this.hud=e}atualizarHud(t){const e=this.sessao;if(!this.hud||!e)return;const o=this.hud.querySelector('[data-campo="nos"]'),i=this.hud.querySelector('[data-campo="medida"]');if(o&&(o.textContent=e.nos>0?`Nós: ${e.nos}`:""),!i)return;let n="";if((t==null?void 0:t.tipo)==="Polygon")n=`Área: ${st(Q(t)??0)} · Perímetro: ${G(tt(t)??0)}`;else if((t==null?void 0:t.tipo)==="LineString"){if(n=`Extensão: ${G(e.comprimentoMetros())}`,e.ferramenta==="medir-distancia"&&e.nos>=3&&t.coordenadas.length>=3){const r={tipo:"Polygon",aneis:[t.coordenadas]};n+=` · Área: ${st(Q(r)??0)} · Perímetro: ${G(tt(r)??0)}`}}else(t==null?void 0:t.tipo)==="Circle"&&(n=`Raio: ${G(t.raioMetros)}`);i.textContent=n}clicarEm(t){const e=this.sessao;if(!e)return;const o=e.clicar(t);o.concluida?o.concluida.tipo==="Text"?this.pedirTexto(t):this.finalizar(o.concluida):this.atualizar()}moverPara(t){var e;(e=this.sessao)==null||e.mover(t),this.atualizar()}}const Hi=5e3;function _t(a){return a.tipo==="Polygon"?3:a.tipo==="LineString"?2:1}function Vi(a,t=!1){if(a.bloqueada||t)return"bloqueada";const e=a.geometria;return e.tipo!=="Point"&&e.tipo!=="LineString"&&e.tipo!=="Polygon"&&e.tipo!=="Circle"?"tipo-nao-suportado":e.tipo==="Polygon"&&e.aneis.length!==1?"poligono-com-furos":wt(e)?"multiparte":K(e).length>Hi?"muitos-vertices":null}function K(a){return a.tipo==="Point"?[a.coordenada]:a.tipo==="LineString"?a.coordenadas:a.tipo==="Polygon"?a.aneis[0]??[]:[]}function Tt(a,t){return a.tipo==="Point"?{tipo:"Point",coordenada:t[0]}:a.tipo==="LineString"?{tipo:"LineString",coordenadas:t}:a.tipo==="Polygon"?{tipo:"Polygon",aneis:[t]}:a}function Qn(a,t,e){const o=K(a).slice();return t<0||t>=o.length?a:(o[t]=e,Tt(a,o))}function Gi(a,t,e){if(a.tipo!=="LineString"&&a.tipo!=="Polygon")return a;const o=K(a).slice();return t<0||t>=o.length?a:(o.splice(t+1,0,e),Tt(a,o))}function ji(a,t){if(a.tipo!=="LineString"&&a.tipo!=="Polygon")return null;const e=K(a);return t<0||t>=e.length||e.length<=_t(a)?null:Tt(a,e.filter((o,i)=>i!==t))}function Xe(a,t){return[(a[0]+t[0])/2,(a[1]+t[1])/2]}function Ze(a){const t=K(a).length,e=[];if(a.tipo!=="LineString"&&a.tipo!=="Polygon")return e;for(let o=0;o<t-1;o++)e.push([o,o+1]);return a.tipo==="Polygon"&&t>2&&e.push([t-1,0]),e}function U(a){return(a.tipo==="LineString"||a.tipo==="Polygon")&&a.curva&&a.curva.length>=_t(a)?a.curva:null}const tr=63710088e-1*Math.PI/180,Ui=.5;function Wi(a,t){const e=Math.max(.01,Math.cos(a[0]*Math.PI/180));return[a[0],a[1]+t/(tr*e)]}function St(a){var t;return a.tipo==="Circle"?[a.centro,Wi(a.centro,a.raioMetros)]:((t=U(a))==null?void 0:t.map(e=>e.ponto))??K(a)}function Pt(a,t){const e=a.tipo==="Polygon",o=bt(t,e);return e?{tipo:"Polygon",aneis:[o],curva:t}:{tipo:"LineString",coordenadas:o,curva:t}}function Xi(a,t){if(a.tipo==="Circle")return t.length<2?a:{...a,centro:t[0],raioMetros:Math.max(Ui,rt(t[0],t[1]))};const e=U(a);if(!e||e.length!==t.length)return Tt(a,t);const o=e.map((i,n)=>{const r=t[n][0]-i.ponto[0],s=t[n][1]-i.ponto[1],c=d=>[d[0]+r,d[1]+s],l={ponto:t[n]};return i.entrada&&(l.entrada=c(i.entrada)),i.saida&&(l.saida=c(i.saida)),l});return Pt(a,o)}function pt(a,t,e){return[a[0]+(t[0]-a[0])*e,a[1]+(t[1]-a[1])*e]}function er(a,t,e){const[o,i]=It(a,t);let n=.5,r=1/0;for(let s=1;s<64;s++){const c=s/64,l=He(a.ponto,o,i,t.ponto,c),d=(l[0]-e[0])**2+(l[1]-e[1])**2;d<r&&(r=d,n=c)}return n}function jt(a,t,e){const o=U(a);if(!o){const r=K(a);return Xe(r[t],r[e])}const[i,n]=It(o[t],o[e]);return He(o[t].ponto,i,n,o[e].ponto,.5)}function Zi(a){const t=U(a);if(!t)return Ze(a);const e=[];for(let o=0;o<t.length-1;o++)e.push([o,o+1]);return a.tipo==="Polygon"&&t.length>2&&e.push([t.length-1,0]),e}function Yi(a,t,e){const o=U(a);if(!o)return Gi(a,t,e);if(t<0||t>=o.length)return a;const i=(t+1)%o.length,n=o[t],r=o[i],s=n.saida===void 0&&r.entrada===void 0;let c,l=n,d=r;if(s)c={ponto:e};else{const u=er(n,r,e),[g,m]=It(n,r),f=pt(n.ponto,g,u),b=pt(g,m,u),A=pt(m,r.ponto,u),M=pt(f,b,u),C=pt(b,A,u);c={ponto:pt(M,C,u),entrada:M,saida:C},l={...n,saida:f},d={...r,entrada:A}}const h=o.slice();return h[t]=l,h[i]=d,h.splice(t+1,0,c),Pt(a,h)}function Ki(a,t){const e=U(a);return e?t<0||t>=e.length||e.length<=_t(a)?null:Pt(a,e.filter((o,i)=>i!==t)):ji(a,t)}function Ji(a){return a.tipo!=="LineString"&&a.tipo!=="Polygon"?null:U(a)??K(a).map(t=>({ponto:[t[0],t[1]]}))}function Qi(a,t,e,o,i=!0){const n=Ji(a);if(!n||t<0||t>=n.length)return a;const r={...n[t],[e]:o};i&&(r[e==="saida"?"entrada":"saida"]=Be(r.ponto,o));const s=n.slice();return s[t]=r,Pt(a,s)}function ta(a,t){const e=Ji(a);if(!e||t<0||t>=e.length)return a;const o=e[t],i=e.slice();if(o.entrada||o.saida)return i[t]={ponto:o.ponto},Pt(a,i);const n=a.tipo==="Polygon",r=e.length,s=t>0?e[t-1]:n?e[r-1]:null,c=t<r-1?e[t+1]:n?e[0]:null;if(!s&&!c)return a;const l=o.ponto;let d,h;if(s&&c)d=(c.ponto[0]-s.ponto[0])/6,h=(c.ponto[1]-s.ponto[1])/6;else{const u=(c??s).ponto,g=c?1:-1;d=(u[0]-l[0])/3*g,h=(u[1]-l[1])/3*g}return i[t]={ponto:l,saida:[l[0]+d,l[1]+h],entrada:[l[0]-d,l[1]-h]},Pt(a,i)}const ea=6,ge=(a,t)=>Math.hypot(a.x-t.x,a.y-t.y);function Mo(a,t,e){const o=e.x-t.x,i=e.y-t.y,n=o*o+i*i,r=n===0?0:Math.max(0,Math.min(1,((a.x-t.x)*o+(a.y-t.y)*i)/n));return Math.hypot(a.x-(t.x+r*o),a.y-(t.y+r*i))}function or(a,t){const e=a.geometria;if(e.tipo!=="Polygon")return 0;const o=e.aneis[0].map(t),i=o.map(r=>r.x),n=o.map(r=>r.y);return(Math.max(...i)-Math.min(...i))*(Math.max(...n)-Math.min(...n))}function Ye(a,t,e,o=ea){let i=null,n=null,r=null;for(const s of t){if(s.excluida||s.oculta)continue;const c=s.geometria;if(c.tipo==="Point"||c.tipo==="Text"){const l=ge(a,e(c.coordenada));l<=o+2&&(!i||l<i.d)&&(i={f:s,d:l})}else if(c.tipo==="LineString"){let l=1/0;for(const d of j(c)){const h=d.map(e);for(let u=1;u<h.length;u++)l=Math.min(l,Mo(a,h[u-1],h[u]))}l<=o&&(!n||l<n.d)&&(n={f:s,d:l})}else if(c.tipo==="Circle"){const l=e(c.centro),d=e([c.centro[0]+c.raioMetros/111320,c.centro[1]]),h=ge(l,d);if(ge(a,l)<=h){const u=Math.PI*h*h;(!r||u<r.a)&&(r={f:s,a:u})}}else{const l=c.aneis[0].map(e);let d=1/0;for(const[u,g]of Ze(c))d=Math.min(d,Mo(a,l[u],l[g]));if(je([a.y,a.x],[l.map(u=>[u.y,u.x]),...c.aneis.slice(1).map(u=>u.map(e).map(g=>[g.y,g.x]))])||d<=o){const u=or(s,e);(!r||u<r.a)&&(r={f:s,a:u})}}}return(i==null?void 0:i.f)??(n==null?void 0:n.f)??(r==null?void 0:r.f)??null}const ir=new Set(["ponto","linha","poligono","retangulo","elipse","poligono-regular","estrela","circulo","texto","caneta"]);class ar{constructor(t){p(this,"desenho",null);p(this,"camadaDesenho",null);p(this,"estiloDesenho",{});p(this,"sequenciaId",0);this.p=t}get controle(){return this.desenho}get ativo(){var t;return!!((t=this.desenho)!=null&&t.ativo)}botaoDireito(){var t;(t=this.desenho)==null||t.botaoDireito()}destruir(){var t;(t=this.desenho)==null||t.desativar(),this.desenho=null}get ferramentaAtiva(){var t;return((t=this.desenho)==null?void 0:t.ferramenta)??null}definirCamadaDesenho(t){this.camadaDesenho=t||null}get camadaDeDesenho(){return this.camadaDesenho}definirEstiloDesenho(t){this.estiloDesenho={...t}}obterEstiloDesenho(){return{...this.estiloDesenho}}alternarFerramenta(t){var e;return((e=this.desenho)==null?void 0:e.ferramenta)===t?(this.desenho.desativar(),{ok:!0}):this.ativarFerramenta(t)}ativarFerramenta(t,e={}){var n,r;if(!Ue(t))return{ok:!1,motivo:"ferramenta-invalida"};const o=this.p.obterMapa();if(!o)return{ok:!1,motivo:"sem-mapa"};if(ir.has(t)){const s=this.motivoCamadaDesenhoInvalida();if(s)return this.p.emitir("cad-desenho-recusado",{ferramenta:t,motivo:s}),{ok:!1,motivo:s}}this.p.prepararDesenho(),this.desenho||(this.desenho=new Bi({map:o,buscarSnap:s=>this.p.buscarSnapEm(s),snapAtivo:()=>this.p.snapAtivo(),aoGeometria:(s,c)=>this.concluirFerramenta(s,c),aoMedir:s=>this.p.emitir("cad-medicao",s),aoAmostrar:s=>this.amostrarEstilo(s),aoSolicitarTexto:s=>this.solicitarTexto(s),aoDesativar:()=>{var s,c;this.p.emitir("cad-ferramenta",{ferramenta:null}),(c=(s=this.p).aoFerramenta)==null||c.call(s,null)}})),this.desenho.ativar(t,e),this.p.emitir("cad-ferramenta",{ferramenta:t}),(r=(n=this.p).aoFerramenta)==null||r.call(n,t);const i=e.iniciarEm?this.p.normalizarCoordenada(e.iniciarEm):null;return i&&this.desenho.clicarEm(i),{ok:!0}}desativarFerramenta(){var t;(t=this.desenho)==null||t.desativar()}limparMedicao(){var t;(t=this.desenho)==null||t.limparMedicao()}get nosDesenho(){var t;return((t=this.desenho)==null?void 0:t.nos)??0}desfazerVerticeDesenho(){var t;return((t=this.desenho)==null?void 0:t.desfazerVertice())??!1}motivoCamadaDesenhoInvalida(){if(!this.camadaDesenho)return"sem-camada";const t=this.p.obterLayerManager().getLayerDef(this.camadaDesenho);return t&&t.tipo!==H?"camada-invalida":t!=null&&t.bloqueada?"camada-bloqueada":null}novoId(t,e){const o=new Set(this.p.lista(e).map(n=>n.id));let i;do this.sequenciaId++,i=`${t}-${Date.now().toString(36)}${this.sequenciaId.toString(36)}`;while(o.has(i));return i}solicitarTexto(t){const e={coordenada:t,camadaId:this.camadaDesenho,concluir:o=>{const i=typeof o=="string"?o.trim():"";return i?this.concluirFerramenta("texto",{tipo:"Text",coordenada:t,texto:i}):null}};return this.p.emitir("cad-texto-solicitado",e,!0)===!0}concluirFerramenta(t,e){if(t==="dividir")return e.tipo==="LineString"&&this.p.dividirComLinha(e.coordenadas),null;if(t==="medir-distancia"||t==="medir-area")return null;if(t==="selecao-laco")return e.tipo==="Polygon"&&this.p.selecionarNoLaco(e.aneis[0]),null;const o=this.camadaDesenho;if(!o)return null;const i=Object.keys(this.estiloDesenho).length>0,n=this.p.adicionarFeicao(o,{id:this.novoId(t,o),geometria:e,estilo:i?{...this.estiloDesenho}:void 0,propriedades:{}});return n?this.p.emitir("cad-feicao-criada",{camadaId:o,feicao:n}):this.p.emitir("cad-desenho-recusado",{ferramenta:t,motivo:"geometria-invalida"}),n}amostrarEstilo(t){const e=this.p.obterMapa();if(!e)return;const o=e.latLngToContainerPoint(t),i=this.p.candidatasEm(t,8),n=Ye({x:o.x,y:o.y},i,d=>e.latLngToContainerPoint(d));if(!n){this.p.emitir("cad-conta-gotas",{cor:"",feicao:null,estilo:{}});return}const r=this.p.obterLayerManager().getLayerDef(n.camadaId),s=n.estilo??{},c={},l=s.corTraco??(r==null?void 0:r.estilo.corPrimaria);l&&(c.corTraco=l),s.corPreenchimento&&(c.corPreenchimento=s.corPreenchimento),s.espessuraTraco!==void 0&&(c.espessuraTraco=s.espessuraTraco),s.opacidadePreenchimento!==void 0&&(c.opacidadePreenchimento=s.opacidadePreenchimento),s.dashArray&&(c.dashArray=s.dashArray),this.estiloDesenho={...this.estiloDesenho,...c},this.p.emitir("cad-conta-gotas",{cor:l??s.corPreenchimento??"",feicao:n,estilo:c})}}class nr{constructor(t){p(this,"posicoes",new Map);this.p=t}lista(t){var o;const e=(o=this.p.obterLayerManager().getLayerDef(t))==null?void 0:o.dados;return Array.isArray(e==null?void 0:e.feicoes)?e.feicoes:[]}posicaoDe(t){const e=this.lista(t),o=this.posicoes.get(t);if(o&&o.lista===e)return o.pos;const i=new Map;for(let n=0;n<e.length;n++)i.set(e[n].id,n);return this.posicoes.set(t,{lista:e,pos:i}),i}buscar(t,e){const o=this.lista(t),i=this.posicaoDe(t).get(e),n=i===void 0?void 0:o[i];if(n&&n.id===e)return n;if(i===void 0)return;this.posicoes.delete(t);const r=this.posicaoDe(t).get(e);return r===void 0?void 0:o[r]}garantirCamada(t,e){const o=this.p.obterLayerManager(),i=o.getLayerDef(t);if(i&&i.tipo!==H)return!1;const n=o.getOrCreateLayer(t,H,(e==null?void 0:e.nome)??t);return e!=null&&e.nome&&(n.nome=e.nome),e!=null&&e.estilo&&(n.estilo={...n.estilo,...e.estilo}),(e==null?void 0:e.interativo)!==void 0&&(n.interativo=e.interativo),(e==null?void 0:e.zIndex)!==void 0&&o.setLayerZIndex(t,e.zIndex),(e==null?void 0:e.opacidade)!==void 0&&o.setLayerOpacity(t,e.opacidade),o.ensurePanes(),!0}definirFeicoes(t,e,o){if(!this.garantirCamada(t,o))return{aceitas:0,recusadas:["camada existente não é de feições"]};const i=[],n=new Map;return(Array.isArray(e)?e:[]).forEach((r,s)=>{const c=Bt(r,t,this.p.opcoesNormalizacao());c?n.set(c.id,c):i.push(String((r==null?void 0:r.id)??`#${s}`))}),this.p.obterLayerManager().setLayerData(t,{feicoes:[...n.values()]}),this.p.aposDados(),{aceitas:n.size,recusadas:i}}adicionarFeicao(t,e,o){return this.aplicar(t,{adicionar:[e]},o).adicionadas[0]??null}atualizarFeicao(t,e,o,i){return this.aplicar(t,{atualizar:[{...o,id:e}]},i).atualizadas[0]??null}substituir(t,e){this.p.obterLayerManager().getLayerDef(t)&&this.aplicar(t,{adicionar:[e]})}removerFeicao(t,e){return this.aplicar(t,{remover:[e]}).resultado.removidas>0}aplicarLote(t,e,o){return this.aplicar(t,e,o).resultado}mesclar(t,e,o,i){const n=i&&e.propriedades&&typeof e.propriedades=="object"?{...e.propriedades}:{...t.propriedades,...e.propriedades};return Bt({...t,...e,id:t.id,estilo:{...t.estilo,...e.estilo},propriedades:n},o,this.p.opcoesNormalizacao())}aplicar(t,e,o={}){const i={adicionadas:0,atualizadas:0,removidas:0,recusadas:[]},n=[],r=[],s=Array.isArray(e==null?void 0:e.adicionar)?e.adicionar:[],c=Array.isArray(e==null?void 0:e.atualizar)?e.atualizar:[],l=Array.isArray(e==null?void 0:e.remover)?e.remover:[],d=(L,w)=>String((L==null?void 0:L.id)??`#${w}`),h=[],u=L=>(i.recusadas.push(...h),L),g=[];s.forEach((L,w)=>{const I=Bt(L,t,this.p.opcoesNormalizacao());I?g.push(I):h.push(d(L,w))});const m=this.p.obterLayerManager(),f=m.getLayerDef(t);if(!(!f||f.tipo===H)||!f&&g.length===0)return c.forEach((L,w)=>i.recusadas.push(d(L,w))),g.forEach(L=>h.push(L.id)),u({resultado:i,adicionadas:n,atualizadas:r});if((g.length>0||f)&&!this.garantirCamada(t,o))return g.forEach(L=>h.push(L.id)),u({resultado:i,adicionadas:n,atualizadas:r});const A=this.lista(t),M=this.posicaoDe(t),C=A.slice(),k=[],P=[];let y=!1;for(const L of l){const w=String(L),I=M.get(w);I===void 0||C[I]===null||(C[I]=null,k.push(w),i.removidas++,y=!0)}c.forEach((L,w)=>{const I=L&&typeof L=="object"&&L.id!==void 0&&L.id!==null?String(L.id):"",_=M.get(I),N=_===void 0?null:C[_],T=N?this.mesclar(N,L,t,!!o.substituirPropriedades):null;if(!T||_===void 0){i.recusadas.push(I||d(L,w));return}C[_]=T,P.push(T),r.push(T),i.atualizadas++});for(const L of g){const w=M.get(L.id);w!==void 0&&C[w]!==null?C[w]=L:(M.set(L.id,C.length),C.push(L)),P.push(L),n.push(L),i.adicionadas++}if(P.length===0&&k.length===0)return u({resultado:i,adicionadas:n,atualizadas:r});const x=y?C.filter(L=>L!==null):C,z={feicoes:x,delta:{base:A,mudadas:P,removidas:k}};return m.setLayerData(t,z),delete z.delta,y?this.posicoes.delete(t):this.posicoes.set(t,{lista:x,pos:M}),this.p.aposDados(),u({resultado:i,adicionadas:n,atualizadas:r})}}const oa="cm-vertex-edit-hud",dt="cad-edicao-vertices",Ao="#facc15",wo="#f472b6";class ia{constructor(t){p(this,"feicaoAtual",null);p(this,"pts",[]);p(this,"alcas",[]);p(this,"fantasmas",[]);p(this,"alcasBezier",[]);p(this,"marcadorSnap",null);p(this,"hud",null);p(this,"grupo",null);this.dep=t}get ativo(){return this.feicaoAtual!==null}get ehCirculo(){var t;return((t=this.feicaoAtual)==null?void 0:t.geometria.tipo)==="Circle"}get feicao(){return this.feicaoAtual}iniciar(t){this.parar(),this.feicaoAtual=t,this.pts=St(t.geometria).map(o=>[o[0],o[1]]);const e=this.dep.map;if(!e.getPane(dt)){const o=e.createPane(dt);o.style.zIndex="9000"}this.grupo=v.layerGroup().addTo(e),this.montarHud(),this.reconstruir()}parar(){var e,o;const t=this.feicaoAtual;t&&(this.feicaoAtual=null,this.alcas=[],this.fantasmas=[],this.alcasBezier=[],(e=this.grupo)==null||e.remove(),this.grupo=null,this.marcadorSnap=null,(o=this.hud)==null||o.remove(),this.hud=null,this.dep.aoEncerrar(t))}sincronizar(t){!this.feicaoAtual||this.feicaoAtual.id!==t.id||(this.feicaoAtual=t,this.pts=St(t.geometria).map(e=>[e[0],e[1]]),this.reconstruir())}atualizarSnapNoHud(){var e;const t=(e=this.hud)==null?void 0:e.querySelector('[data-campo="snap"]');t&&(t.textContent=`Snap: ${this.dep.snapLigado()?"ligado":"desligado"} (S)`)}geometriaAtual(){return Xi(this.feicaoAtual.geometria,this.pts)}feicaoComPontos(){return{...this.feicaoAtual,geometria:this.geometriaAtual()}}reconstruir(){var e;if((e=this.grupo)==null||e.clearLayers(),this.alcas=[],this.fantasmas=[],this.alcasBezier=[],!this.feicaoAtual||!this.grupo)return;const t=this.feicaoAtual.geometria;if(this.pts.forEach((o,i)=>{const n=this.criarAlca(o,i);this.alcas.push(n),this.grupo.addLayer(n)}),this.criarAlcasBezier(),t.tipo!=="Point")for(const[o,i]of Zi(this.geometriaAtual())){const n=this.criarFantasma(o,i);this.fantasmas.push(n),this.grupo.addLayer(n.marker)}this.atualizarHud()}icone(t,e,o){return v.divIcon({className:`custom-leaflet-marker ${t}`,iconSize:[e,e],html:`<div style="width:${e}px;height:${e}px;box-sizing:border-box;${o}"></div>`})}criarAlca(t,e){const o=v.marker(t,{icon:this.icone("cad-vertex-handle",12,`background:${Ao};border:2px solid #111;border-radius:${this.ehCirculo&&e===1?"50%":"2px"};cursor:${this.ehCirculo&&e===1?"ew-resize":"move"}`),draggable:!0,pane:dt,keyboard:!1});return o.on("drag",()=>this.aoArrastar(o,e)),o.on("dragend",()=>{this.esconderSnap(),this.confirmar(this.feicaoComPontos())}),o.on("contextmenu",i=>{v.DomEvent.preventDefault(i.originalEvent),v.DomEvent.stopPropagation(i.originalEvent),this.excluir(e)}),o.on("dblclick",i=>{v.DomEvent.stopPropagation(i.originalEvent),this.alternarSuave(e)}),o}criarAlcasBezier(){const t=this.feicaoAtual&&U(this.feicaoAtual.geometria);t&&t.forEach((e,o)=>this.completarAlcasDoNo(o))}completarAlcasDoNo(t){var o;const e=this.feicaoAtual&&((o=U(this.feicaoAtual.geometria))==null?void 0:o[t]);if(!(!e||!this.grupo))for(const i of["entrada","saida"]){const n=e[i];if(!n||this.alcasBezier.some(l=>l.i===t&&l.qual===i))continue;const r=v.polyline([e.ponto,n],{pane:dt,color:wo,weight:1,opacity:.8,interactive:!1}),s=v.marker(n,{icon:this.icone("cad-bezier-handle",10,`background:#fff;border:2px solid ${wo};border-radius:50%;cursor:move`),draggable:!0,pane:dt,keyboard:!1}),c={marker:s,haste:r,i:t,qual:i};s.on("drag",l=>{const d=l.originalEvent;this.aoArrastarAlca(c,!(d!=null&&d.shiftKey))}),s.on("dragend",()=>this.confirmar(this.feicaoAtual)),this.alcasBezier.push(c),this.grupo.addLayer(r),this.grupo.addLayer(s)}}sincronizarAlcasBezier(){var e;const t=this.feicaoAtual&&U(this.feicaoAtual.geometria);if(t)for(const o of this.alcasBezier){const i=(e=t[o.i])==null?void 0:e[o.qual];i&&((o.marker.getLatLng().lat!==i[0]||o.marker.getLatLng().lng!==i[1])&&o.marker.setLatLng(i),o.haste.setLatLngs([t[o.i].ponto,i]))}}aoArrastarAlca(t,e){const o=this.feicaoAtual;if(!o)return;const{lat:i,lng:n}=t.marker.getLatLng(),r=Qi(o.geometria,t.i,t.qual,[i,n],e);this.feicaoAtual={...o,geometria:r},this.completarAlcasDoNo(t.i),this.sincronizarAlcasBezier(),this.dep.previsualizar(this.feicaoAtual),this.atualizarHud()}alternarSuave(t){const e=this.feicaoAtual;if(!e)return;const o=ta(e.geometria,t);o!==e.geometria&&(this.feicaoAtual={...e,geometria:o},this.reconstruir(),this.dep.previsualizar(this.feicaoAtual),this.confirmar(this.feicaoAtual))}criarFantasma(t,e){const o=v.marker(jt(this.geometriaAtual(),t,e),{icon:this.icone("cad-vertex-ghost",9,`background:${Ao};opacity:.45;border:1px solid #111;border-radius:50%;cursor:copy`),pane:dt,keyboard:!1});return o.on("click",i=>{v.DomEvent.stopPropagation(i.originalEvent),this.inserir(t,o.getLatLng())}),{marker:o,i:t,j:e}}aoArrastar(t,e){var r;const o=this.feicaoAtual;if(!o)return;let i=[t.getLatLng().lat,t.getLatLng().lng];const n=this.dep.snapLigado()?this.dep.buscarSnap(i,{feicaoId:o.id,camadaId:o.camadaId,vertice:e}):null;if(n?(i=n.coordenada,t.setLatLng(i),this.mostrarSnap(i)):this.esconderSnap(),o.geometria.tipo==="Circle"&&e===0){const s=i[0]-this.pts[0][0],c=i[1]-this.pts[0][1];this.pts[1]=[this.pts[1][0]+s,this.pts[1][1]+c],(r=this.alcas[1])==null||r.setLatLng(this.pts[1])}this.pts[e]=i;for(const s of this.fantasmas)(s.i===e||s.j===e)&&s.marker.setLatLng(jt(this.geometriaAtual(),s.i,s.j));this.dep.previsualizar(this.feicaoComPontos()),this.atualizarAlcasDoNo(e),this.atualizarHud()}atualizarAlcasDoNo(t){const e=U(this.geometriaAtual());if(e)for(const o of this.alcasBezier){if(o.i!==t)continue;const i=e[t][o.qual];i&&(o.marker.setLatLng(i),o.haste.setLatLngs([e[t].ponto,i]))}}inserir(t,e){if(!this.feicaoAtual)return;const i=Yi(this.geometriaAtual(),t,[e.lat,e.lng]);this.pts=St(i).map(r=>[r[0],r[1]]),this.reconstruir();const n=this.feicaoComPontos();this.dep.previsualizar(n),this.confirmar(n)}confirmar(t){this.feicaoAtual=t,this.dep.aoGesto(t)}excluir(t){if(!this.feicaoAtual)return;const o=Ki(this.geometriaAtual(),t);if(!o)return;this.pts=St(o).map(n=>[n[0],n[1]]),this.reconstruir();const i=this.feicaoComPontos();this.dep.previsualizar(i),this.confirmar(i)}excluirVertice(t){const e=this.pts.length;return this.excluir(t),this.pts.length<e}inserirVerticeApos(t){if(t<0||t>=this.pts.length)return;const e=(t+1)%this.pts.length,o=jt(this.geometriaAtual(),t,e);this.inserir(t,v.latLng(o[0],o[1]))}mostrarSnap(t){this.grupo&&(this.marcadorSnap?this.marcadorSnap.setLatLng(t):this.marcadorSnap=v.marker(t,{icon:v.divIcon({className:"custom-leaflet-marker cm-snap",iconSize:[18,18],html:'<div style="width:18px;height:18px;box-sizing:border-box;border:2px solid #22d3ee;transform:rotate(45deg);border-radius:2px"></div>'}),interactive:!1,pane:dt,keyboard:!1}).addTo(this.grupo))}esconderSnap(){var t;this.marcadorSnap&&((t=this.grupo)==null||t.removeLayer(this.marcadorSnap),this.marcadorSnap=null)}montarHud(){const t=this.dep.map.getContainer(),e=document.createElement("div");e.id=oa,e.style.cssText=We+"gap:12px;align-items:center;padding:6px 12px;border-radius:8px;background:rgba(15,23,42,.92);color:#fff;font:12px var(--ui-fonte-base,sans-serif);border:1px solid rgba(255,255,255,.2);pointer-events:auto";const o=c=>{const l=document.createElement("span");return l.dataset.campo=c,l},i=document.createElement("strong");i.textContent=this.ehCirculo?"Editando círculo":"Editando vértices";const n=o("snap");n.style.cursor="pointer",n.title="Alternar snap (S). Alt desliga temporariamente.",n.addEventListener("click",()=>this.dep.alternarSnap());const r=document.createElement("button");r.type="button",r.textContent="Concluir",r.style.cssText="padding:3px 10px;border-radius:4px;border:1px solid #facc15;background:#facc15;color:#111;font-weight:600;cursor:pointer",r.addEventListener("click",()=>this.parar());const s=o("dica");s.style.opacity=".7",s.textContent="Duplo clique no nó: curva ↔ canto · Alças: Shift solta a simetria",e.append(i,o("nos"),o("medida"),n,s,r),v.DomEvent.disableClickPropagation(e),v.DomEvent.disableScrollPropagation(e),t.appendChild(e),this.hud=e,this.atualizarSnapNoHud()}atualizarHud(){if(!this.hud||!this.feicaoAtual)return;const t=this.geometriaAtual(),e=this.hud.querySelector('[data-campo="nos"]'),o=this.hud.querySelector('[data-campo="medida"]');e&&(e.textContent=t.tipo==="Circle"?"Centro move · borda muda o raio":`Nós: ${this.pts.length} (mín. ${_t(t)})`),o&&(t.tipo==="Polygon"?o.textContent=`Área: ${st(Q(t)??0)} · Perímetro: ${G(tt(t)??0)}`:t.tipo==="LineString"?o.textContent=`Extensão: ${G(tt(t)??0)}`:t.tipo==="Point"?o.textContent=`${t.coordenada[0].toFixed(6)}, ${t.coordenada[1].toFixed(6)}`:t.tipo==="Circle"&&(o.textContent=`Raio: ${G(t.raioMetros)} · Área: ${st(Q(t)??0)}`))}vertices(){return this.pts.map(t=>[t[0],t[1]])}get totalAlcasBezier(){return this.alcasBezier.length}arrastarAlcaPara(t,e,o,i=!1){const n=this.alcasBezier.find(r=>r.i===t&&r.qual===e);n&&(n.marker.setLatLng(o),this.aoArrastarAlca(n,!i),this.confirmar(this.feicaoAtual))}alternarSuavidadeDoNo(t){this.alternarSuave(t)}arrastarPara(t,e){const o=this.alcas[t];o&&(o.setLatLng(e),this.aoArrastar(o,t),o.fire("dragend"))}}class rr{constructor(t){p(this,"editor",null);this.p=t}get editando(){var t;return!!((t=this.editor)!=null&&t.ativo)}get editorAtual(){return this.editor}get feicao(){var t;return(t=this.editor)!=null&&t.ativo?this.editor.feicao:null}sincronizar(t){var e;(e=this.editor)==null||e.sincronizar(t)}atualizarSnapNoHud(){var t;(t=this.editor)==null||t.atualizarSnapNoHud()}iniciarEdicao(t,e){var d;const o=this.p.buscar(t,e);if(!o||o.excluida)return{ok:!1,motivo:"inexistente"};const i=this.p.obterLayerManager().getLayerDef(t),n=Vi(o,!!(i!=null&&i.bloqueada));if(n)return this.p.emitir("cad-edicao-recusada",{motivo:n,feicao:o}),{ok:!1,motivo:n};const r=this.p.obterMapa();if(!r)return{ok:!1,motivo:"sem-mapa"};this.p.desativarFerramenta(),(d=this.editor)==null||d.parar(),this.p.aplicarMargensHud(),this.p.selecionarUma({camadaId:t,id:e}),this.p.fecharPopup();const s=this.p.obterLayerManager(),c=O.get(H),l=new ia({map:r,snapLigado:()=>this.p.snapAtivo(),alternarSnap:()=>this.p.alternarSnap(),buscarSnap:(h,u)=>this.p.buscarSnapEm(h,u),previsualizar:h=>{const u=s.getLayerInstance(h.camadaId);u&&c&&c.previsualizar(u,h)},aoGesto:h=>{this.p.substituir(h.camadaId,h),this.p.emitir("cad-feicao-atualizada",{camadaId:h.camadaId,feicao:h})},aoEncerrar:h=>{this.editor=null;const u=this.p.buscar(h.camadaId,h.id)??h;this.p.emitir("cad-edicao-concluida",{feicao:u}),this.p.reabrirPopupDaSelecao()}});return this.editor=l,l.iniciar(o),this.p.emitir("cad-edicao-iniciada",{feicao:o}),{ok:!0}}parar(){var t;(t=this.editor)==null||t.parar()}}const Ke=10,ve=(a,t)=>Math.hypot(a.x-t.x,a.y-t.y);function sr(a,t,e){const o=e.x-t.x,i=e.y-t.y,n=o*o+i*i,r=n===0?0:Math.max(0,Math.min(1,((a.x-t.x)*o+(a.y-t.y)*i)/n));return{t:r,d:Math.hypot(a.x-(t.x+r*o),a.y-(t.y+r*i))}}function aa(a,t,e,o={},i){const n=o.toleranciaPx??Ke,r=o.vertice!==!1,s=o.meio!==!1,c=o.aresta!==!1;let l=null,d=null,h=null;const u=(g,m)=>!g||m.distanciaPx<g.distanciaPx?m:g;for(const g of t){if(g.excluida||g.oculta)continue;const m=!!i&&i.feicaoId===g.id&&(i.camadaId===void 0||i.camadaId===g.camadaId),f=g.geometria,b={feicaoId:g.id,camadaId:g.camadaId};if(f.tipo==="Point"||f.tipo==="Text"||f.tipo==="Circle"){if(!r||m)continue;const C=f.tipo==="Circle"?f.centro:f.coordenada,k=ve(a,e(C));k<=n&&(l=u(l,{tipo:"vertice",coordenada:C,distanciaPx:k,...b}));continue}if(m&&(f.tipo==="LineString"||f.tipo==="Polygon")&&f.curva)continue;const A=f.tipo==="LineString"?j(f).map(C=>({pts:C,fechado:!1})):[{pts:K(f),fechado:f.tipo==="Polygon"}],M=m?i.vertice:void 0;for(const{pts:C,fechado:k}of A){const P=C.map(e);if(r)for(let x=0;x<C.length;x++){if(x===M)continue;const E=ve(a,P[x]);E<=n&&(l=u(l,{tipo:"vertice",coordenada:C[x],distanciaPx:E,...b}))}if(!s&&!c)continue;const y=[];for(let x=0;x<C.length-1;x++)y.push([x,x+1]);k&&C.length>2&&y.push([C.length-1,0]);for(const[x,E]of y)if(!(M!==void 0&&(x===M||E===M))&&!(m&&M===void 0)){if(s){const z=Xe(C[x],C[E]),L=ve(a,e(z));L<=n&&(d=u(d,{tipo:"meio",coordenada:z,distanciaPx:L,...b}))}if(c){const{t:z,d:L}=sr(a,P[x],P[E]);if(L<=n){const w=[C[x][0]+z*(C[E][0]-C[x][0]),C[x][1]+z*(C[E][1]-C[x][1])];h=u(h,{tipo:"aresta",coordenada:w,distanciaPx:L,...b})}}}}}return l??d??h}class cr{constructor(t){this.p=t}candidatasEm(t,e){const o=this.p.obterMapa(),i=this.p.obterLayerManager(),n=O.get(H);if(!o||!n)return[];const r=o.latLngToContainerPoint(t),s=o.containerPointToLatLng([r.x-e,r.y+e]),c=o.containerPointToLatLng([r.x+e,r.y-e]),l={minLon:Math.min(s.lng,c.lng),maxLon:Math.max(s.lng,c.lng),minLat:Math.min(s.lat,c.lat),maxLat:Math.max(s.lat,c.lat)},d=[];for(const h of i.getLayers()){if(h.tipo!==H||!h.visivel)continue;const u=i.getLayerInstance(h.id);u&&d.push(...n.consultarProximas(u,l).filter(g=>this.p.desenhada(g)))}return d}buscarSnapEm(t,e){const o=this.p.obterMapa();if(!o)return null;const i=o.latLngToContainerPoint(t),n=this.candidatasEm(t,Ke);return aa({x:i.x,y:i.y},n,r=>o.latLngToContainerPoint(r),{},e)}feicaoSob(t,e){const o=this.p.obterMapa();if(!o)return null;const i=o.getContainer().getBoundingClientRect(),n=v.point(t-i.left,e-i.top),r=o.containerPointToLatLng(n),s=[r.lat,r.lng];return{feicao:Ye({x:n.x,y:n.y},this.candidatasEm(s,8),l=>o.latLngToContainerPoint(l)),coordenada:s}}}class lr{constructor(t){p(this,"hoverId",null);p(this,"hoverAgendado",!1);this.p=t}aoMoverMouse(t){if(t.buttons!==0||this.p.interacaoAtiva()){this.hoverId!==null&&(this.hoverId=null,this.p.emitir("cad-feicao-hover",{feicao:null}));return}if(this.hoverAgendado)return;this.hoverAgendado=!0;const{clientX:o,clientY:i}=t;let n=!1;const r=()=>{if(n)return;n=!0,this.hoverAgendado=!1;const s=this.p.feicaoSob(o,i),c=s!=null&&s.feicao?`${s.feicao.camadaId}\0${s.feicao.id}`:null;c!==this.hoverId&&(this.hoverId=c,this.p.emitir("cad-feicao-hover",{feicao:(s==null?void 0:s.feicao)??null}))};typeof requestAnimationFrame=="function"&&requestAnimationFrame(r),setTimeout(r,100)}menuContexto(t){if(this.p.botaoDireitoDaFerramenta())return;const e=this.p.feicaoSob(t.clientX,t.clientY);e&&this.p.emitir("cad-feicao-menu",{feicao:e.feicao,coordenada:e.coordenada,x:t.clientX,y:t.clientY})}duploClique(t){if(this.p.interacaoAtiva()||!this.p.abrirPopup)return;const e=this.p.feicaoSob(t.clientX,t.clientY);e!=null&&e.feicao&&this.p.abrirPopup(e.feicao)}limpar(){this.hoverId=null}}const dr=111320;function Lt(a,t){return a.x>=t.x1&&a.x<=t.x2&&a.y>=t.y1&&a.y<=t.y2}function Eo(a,t,e){let o=0,i=1;const n=t.x-a.x,r=t.y-a.y,s=[-n,n,-r,r],c=[a.x-e.x1,e.x2-a.x,a.y-e.y1,e.y2-a.y];for(let l=0;l<4;l++)if(s[l]===0){if(c[l]<0)return!1}else{const d=c[l]/s[l];if(s[l]<0){if(d>i)return!1;d>o&&(o=d)}else{if(d<o)return!1;d<i&&(i=d)}}return!0}function ko(a,t){let e=!1;for(let o=0,i=t.length-1;o<t.length;i=o++){const n=t[o],r=t[i];n.y>a.y!=r.y>a.y&&a.x<(r.x-n.x)*(a.y-n.y)/(r.y-n.y)+n.x&&(e=!e)}return e}function zo(a,t,e){for(let o=1;o<a.length;o++)if(Eo(a[o-1],a[o],t))return!0;return e&&a.length>2&&Eo(a[a.length-1],a[0],t)}function hr(a,t,e){const o=e(a),i=e([a[0]+t/dr,a[1]]);return Math.hypot(i.x-o.x,i.y-o.y)}function na(a,t,e,o){if(a.oculta)return!1;const i=a.geometria,n=o==="window";switch(i.tipo){case"Point":case"Text":return Lt(e(i.coordenada),t);case"LineString":{const r=j(i).map(s=>s.map(e));return n?r.every(s=>s.every(c=>Lt(c,t))):r.some(s=>s.some(c=>Lt(c,t))||zo(s,t,!1))}case"Polygon":{const r=i.aneis.map(l=>l.map(e)),s=r[0];if(!s)return!1;if(n)return s.every(l=>Lt(l,t));if(r.some(l=>l.some(d=>Lt(d,t))||zo(l,t,!0)))return!0;const c={x:t.x1,y:t.y1};return ko(c,s)&&!r.slice(1).some(l=>ko(c,l))}case"Circle":{const r=e(i.centro),s=hr(i.centro,i.raioMetros,e);if(n)return r.x-s>=t.x1&&r.x+s<=t.x2&&r.y-s>=t.y1&&r.y+s<=t.y2;const c=Math.max(t.x1,Math.min(r.x,t.x2)),l=Math.max(t.y1,Math.min(r.y,t.y2));return Math.hypot(r.x-c,r.y-l)<=s}}}function ra(a,t){if(t.length<3||a.oculta)return!1;const e=i=>je(i,[t]),o=a.geometria;switch(o.tipo){case"Point":case"Text":return e(o.coordenada);case"Circle":return e(o.centro);case"LineString":return j(o).some(i=>i.some(e));case"Polygon":{const i=o.aneis[0]??[];if(i.some(e))return!0;if(i.length<3)return!1;const n=i.reduce((r,s)=>[r[0]+s[0],r[1]+s[1]],[0,0]);return e([n[0]/i.length,n[1]/i.length])}}}class ur{constructor(t){this.p=t}selecionarNoLaco(t){const e=[];for(const o of this.p.obterLayerManager().getActiveSelectableLayers())if(o.tipo===H)for(const i of this.p.lista(o.id))this.p.desenhada(i)&&ra(i,t)&&e.push({camadaId:o.id,id:i.id});this.p.desativarFerramenta(),this.p.selecionar(e)}selecionarNaCaixa(t,e,o){const i=this.p.obterMapa();if(!i)return;const n=s=>i.latLngToContainerPoint(s),r=[];for(const s of this.p.obterLayerManager().getActiveSelectableLayers())if(s.tipo===H)for(const c of this.p.lista(s.id))this.p.desenhada(c)&&na(c,t,n,e)&&r.push({camadaId:s.id,id:c.id});o?this.p.alternarVarias(r):this.p.selecionar(r)}}class pr{constructor(t){p(this,"operacoes");p(this,"selecao");p(this,"popup");p(this,"edicao");p(this,"consulta");p(this,"ponteiro");p(this,"regiao");p(this,"snap");p(this,"ferramentas");p(this,"versoes");p(this,"camera");p(this,"repositorio");p(this,"cursores");p(this,"margensHud",{});p(this,"aceitarOrigem",!1);p(this,"opcoesPopup",{copiarParaAreaDeTransferencia:!0});this.contexto=t,this.repositorio=new nr({obterLayerManager:()=>this.contexto.obterLayerManager(),opcoesNormalizacao:()=>this.opcoesNormalizacao(),aposDados:()=>this.aposDados()}),this.consulta=new cr({obterMapa:()=>this.contexto.obterMapa(),obterLayerManager:()=>this.contexto.obterLayerManager(),desenhada:e=>this.desenhada(e)}),this.ponteiro=new lr({emitir:(e,o)=>this.contexto.emitir(e,o),feicaoSob:(e,o)=>this.consulta.feicaoSob(e,o),interacaoAtiva:()=>this.ferramentas.ativo||this.edicao.editando,botaoDireitoDaFerramenta:()=>this.ferramentas.ativo?(this.ferramentas.botaoDireito(),!0):!1,abrirPopup:e=>this.popup.abrir(e)}),this.regiao=new ur({obterMapa:()=>this.contexto.obterMapa(),obterLayerManager:()=>this.contexto.obterLayerManager(),lista:e=>this.lista(e),desenhada:e=>this.desenhada(e),desativarFerramenta:()=>this.ferramentas.desativarFerramenta(),selecionar:e=>this.selecao.selecionar(e),alternarVarias:e=>this.selecao.alternarVarias(e)}),this.edicao=new rr({obterMapa:()=>this.contexto.obterMapa(),obterLayerManager:()=>this.contexto.obterLayerManager(),emitir:(e,o)=>this.contexto.emitir(e,o),buscar:(e,o)=>this.buscar(e,o),substituir:(e,o)=>this.substituir(e,o),desativarFerramenta:()=>this.ferramentas.desativarFerramenta(),aplicarMargensHud:()=>this.aplicarMargensHud(),selecionarUma:e=>this.selecao.selecionar([e]),fecharPopup:()=>this.popup.fechar(),reabrirPopupDaSelecao:()=>{if(this.modoPopups()!=="automatico")return;const e=this.selecao.obter();e.length===1&&this.popup.abrir(e[0])},snapAtivo:()=>this.snap.ativo,alternarSnap:()=>this.snap.alternar(),buscarSnapEm:(e,o)=>this.buscarSnapEm(e,o)}),this.versoes=new Rn({obterLayerManager:()=>this.contexto.obterLayerManager(),emitir:(e,o)=>this.contexto.emitir(e,o),buscar:(e,o)=>this.buscar(e,o),lista:e=>this.lista(e),aposDados:()=>this.aposDados()},t.regra??new ae),this.ferramentas=new ar({obterMapa:()=>this.contexto.obterMapa(),obterLayerManager:()=>this.contexto.obterLayerManager(),emitir:(e,o,i)=>this.contexto.emitir(e,o,i),aoFerramenta:e=>{var o,i;return(i=(o=this.contexto).aoFerramenta)==null?void 0:i.call(o,e)},lista:e=>this.lista(e),adicionarFeicao:(e,o)=>this.adicionarFeicao(e,o),buscarSnapEm:e=>this.buscarSnapEm(e),snapAtivo:()=>this.snap.ativo,prepararDesenho:()=>{this.edicao.parar(),this.popup.fechar(),this.aplicarMargensHud()},normalizarCoordenada:e=>X(e,this.opcoesNormalizacao()),dividirComLinha:e=>this.dividirComLinha(e),selecionarNoLaco:e=>this.selecionarNoLaco(e),candidatasEm:(e,o)=>this.candidatasEm(e,o)}),this.camera=new Bn({obterMapa:()=>this.contexto.obterMapa(),obterLayerManager:()=>this.contexto.obterLayerManager(),buscar:(e,o)=>this.buscar(e,o),lista:e=>this.lista(e),desenhada:e=>this.desenhada(e),garantirVisivel:e=>this.versoes.garantirVisivel(e)}),this.operacoes=new On({emitir:(e,o)=>this.contexto.emitir(e,o),obterLayerManager:()=>this.contexto.obterLayerManager(),buscar:(e,o)=>this.buscar(e,o),lista:e=>this.lista(e),desenhada:e=>this.desenhada(e),idLivre:(e,o)=>this.idLivre(e,o),adicionarFeicao:(e,o)=>this.adicionarFeicao(e,o),removerFeicao:(e,o)=>this.removerFeicao(e,o),selecionadas:()=>this.selecao.obter(),estaSelecionada:e=>this.selecao.contem(e),divisaoAtiva:()=>this.ferramentas.ferramentaAtiva==="dividir",encerrarDesenho:()=>this.ferramentas.desativarFerramenta()}),this.cursores=new Si(()=>this.contexto.obterMapa()),this.snap=new zn({aoMudar:e=>{var o,i;this.contexto.emitir("cad-snap",e),this.edicao.atualizarSnapNoHud(),(i=(o=this.contexto).aoSnapMudar)==null||i.call(o,e.ligado)}}),this.popup=new Ai({obterMapa:()=>this.contexto.obterMapa(),obterCamada:e=>this.contexto.obterLayerManager().getLayerDef(e),aoAcao:(e,o)=>this.tratarAcaoPopup(e,o),liberar:e=>this.contexto.liberarPopups?this.contexto.liberarPopups(e):e()}),this.selecao=new Mi({obterFeicao:e=>this.buscar(e.camadaId,e.id),aplicarVisual:(e,o)=>{const i=this.contexto.obterLayerManager().getLayerInstance(e),n=O.get(H);i&&n&&n.aplicarSelecao(i,o)},aoSelecionar:e=>{if(this.contexto.emitir("cad-selecao",{feicoes:e}),this.edicao.editando){const o=this.edicao.feicao;e.length===1&&e[0].id===o.id&&e[0].camadaId===o.camadaId||this.edicao.parar();return}e.length===1&&this.modoPopups()==="automatico"?this.popup.abrir(e[0]):this.popup.fechar()},aoSelecionarUma:e=>this.contexto.emitir("cad-feicao-selecionada",{feicao:e}),visivel:e=>this.selecionavelAgora(e),selecionavel:e=>!e.oculta})}aposDados(){if(this.selecao.reconciliar(),this.edicao.editando){const o=this.edicao.feicao,i=this.buscar(o.camadaId,o.id);!i||i.excluida?this.edicao.parar():i!==o&&this.edicao.sincronizar(i)}const t=this.popup.aberto;if(!t)return;const e=this.buscar(t.camadaId,t.id);e&&!e.excluida?this.popup.atualizar(e):this.popup.fechar()}lista(t){return this.repositorio.lista(t)}buscar(t,e){return this.repositorio.buscar(t,e)}opcoesNormalizacao(){return{aceitarOrigem:this.aceitarOrigem}}definirFeicoes(t,e,o){return this.repositorio.definirFeicoes(t,e,o)}adicionarFeicao(t,e,o){return this.repositorio.adicionarFeicao(t,e,o)}atualizarFeicao(t,e,o,i){return this.repositorio.atualizarFeicao(t,e,o,i)}substituir(t,e){this.repositorio.substituir(t,e)}removerFeicao(t,e){return this.repositorio.removerFeicao(t,e)}aplicarLote(t,e,o){return this.repositorio.aplicarLote(t,e,o)}obterFeicoes(t){return this.lista(t).map(e=>({...e}))}tratarAcaoCamada(t,e){if(t==="feicao-movida")return this.substituir(e.camadaId,e.feicao),"cad-feicao-atualizada";if(t==="feicao-clique"){if(this.ferramentas.ativo)return null;const o={camadaId:e.camadaId,id:e.feicao.id};return e.aditivo?this.selecao.alternar(o):this.selecao.selecionar([o]),"cad-feicao-clique"}return null}selecionarFeicoes(t,e=!1){this.selecao.selecionar(Array.isArray(t)?t:[],e)}alternarSelecaoFeicao(t){this.selecao.alternar(t)}limparSelecaoFeicoes(){this.selecao.limpar()}aoPedirLimpeza(){this.ferramentas.ativo||(this.edicao.editando?this.edicao.parar():this.selecao.limpar())}obterFeicoesSelecionadas(){return this.selecao.obter()}selecionarNoLaco(t){this.regiao.selecionarNoLaco(t)}selecionarNaCaixa(t,e,o){this.regiao.selecionarNaCaixa(t,e,o)}definirMargensPopup(t){this.popup.definirMargens(t)}fecharPopup(){this.popup.fechar()}modoPopups(){var t,e;return((e=(t=this.contexto).modoPopups)==null?void 0:e.call(t))??"automatico"}abrirPopupFeicao(t,e){if(typeof t!="string"||typeof e!="string")return!1;const o=this.buscar(t,e);return!o||o.excluida||!this.desenhada(o)?!1:(this.popup.abrir(o),!0)}aoDuploClique(t){this.modoPopups()!=="desligado"&&this.ponteiro.duploClique(t)}definirOpcoesPopup(t){this.opcoesPopup={...this.opcoesPopup,...t}}obterOpcoesPopup(){return{...this.opcoesPopup}}definirMargensHud(t){this.margensHud={...this.margensHud,...t},this.aplicarMargensHud()}aplicarMargensHud(){const t=this.contexto.obterMapa();t&&Oi(t.getContainer(),this.margensHud)}get regraVersoes(){return this.versoes.regra}visivelPorVersao(t){return this.versoes.visivelPorVersao(t)}desenhada(t){return this.versoes.desenhada(t)}selecionavelAgora(t){const e=this.edicao.feicao;return e&&e.id===t.id&&e.camadaId===t.camadaId?!0:!t.oculta&&this.visivelPorVersao(t)}get previasGlobais(){return this.versoes.previasGlobais}definirPreviasGlobais(t){this.versoes.definirPreviasGlobais(t)}alternarPreviasGlobais(){this.versoes.alternarPreviasGlobais()}alternarPrevia(t,e){return this.versoes.alternarPrevia(t,e)}previaSolicitada(t,e){return this.versoes.previaSolicitada(t,e)}atualizarCursorRemoto(t,e){const o=X(e,this.opcoesNormalizacao());return!!o&&this.cursores.atualizar(t,o)}removerCursorRemoto(t){return this.cursores.remover(t)}limparCursoresRemotos(){this.cursores.limpar()}get cursoresRemotos(){return this.cursores.quantidade}zoomParaFeicao(t,e){return this.camera.zoomParaFeicao(t,e)}zoomParaFeicoes(t){return this.camera.zoomParaFeicoes(t)}ajustarTudo(){return this.camera.ajustarTudo()}ajustarCamada(t){return this.camera.ajustarCamada(t)}aoMoverMouse(t){this.ponteiro.aoMoverMouse(t)}menuContexto(t){this.ponteiro.menuContexto(t)}destruir(){this.ferramentas.destruir(),this.cursores.limpar(),this.ponteiro.limpar()}tratarAcaoPopup(t,e){var o,i,n;if(t==="zoom"&&this.zoomParaFeicao(e.camadaId,e.id),t==="vertices"&&this.iniciarEdicao(e.camadaId,e.id),t==="copiar"&&this.opcoesPopup.copiarParaAreaDeTransferencia){const[r,s]=zt(e);(n=(i=(o=globalThis.navigator)==null?void 0:o.clipboard)==null?void 0:i.writeText(`${r.toFixed(6)}, ${s.toFixed(6)}`))==null||n.catch(()=>{})}this.contexto.emitir("cad-feicao-acao",{acao:t,feicao:e})}get snapLigado(){return this.snap.ligado}get snapAtivo(){return this.snap.ativo}definirSnap(t){this.snap.definir(!!t)}alternarSnap(){this.snap.alternar()}conectarTeclado(){this.snap.conectar()}desconectarTeclado(){this.snap.desconectar()}candidatasEm(t,e){return this.consulta.candidatasEm(t,e)}buscarSnapEm(t,e){return this.consulta.buscarSnapEm(t,e)}get editor(){return this.edicao.editorAtual}get editando(){return this.edicao.editando}iniciarEdicao(t,e){return this.edicao.iniciarEdicao(t,e)}pararEdicao(){this.edicao.parar()}get desenho(){return this.ferramentas.controle}amostrarEstilo(t){this.ferramentas.amostrarEstilo(t)}get ferramentaAtiva(){return this.ferramentas.ferramentaAtiva}definirCamadaDesenho(t){this.ferramentas.definirCamadaDesenho(t)}get camadaDeDesenho(){return this.ferramentas.camadaDeDesenho}definirEstiloDesenho(t){this.ferramentas.definirEstiloDesenho(t)}obterEstiloDesenho(){return this.ferramentas.obterEstiloDesenho()}alternarFerramenta(t){return this.ferramentas.alternarFerramenta(t)}ativarFerramenta(t,e={}){return this.ferramentas.ativarFerramenta(t,e)}desativarFerramenta(){this.ferramentas.desativarFerramenta()}limparMedicao(){this.ferramentas.limparMedicao()}get nosDesenho(){return this.ferramentas.nosDesenho}desfazerVerticeDesenho(){return this.ferramentas.desfazerVerticeDesenho()}definirAtalhoSnap(t){this.snap.atalhoS=t}idLivre(t,e){const o=new Set(this.lista(t).map(n=>n.id));if(!o.has(e))return e;let i=2;for(;o.has(`${e}_${i}`);)i++;return`${e}_${i}`}dividirComLinha(t){return this.operacoes.dividirComLinha(t)}gerarBuffer(t,e,o,i={}){return this.operacoes.gerarBuffer(t,e,o,i)}duplicarFeicao(t,e,o={},i={}){return this.operacoes.duplicarFeicao(t,e,o,i)}juntarFeicoes(t,e,o={}){return this.operacoes.juntarFeicoes(t,e,o)}}const Io={ponto:"Ponto",linha:"Linha",poligono:"Polígono",retangulo:"Retângulo",elipse:"Elipse","poligono-regular":"Hexágono",estrela:"Estrela",circulo:"Círculo",texto:"Texto",caneta:"Caneta","medir-distancia":"Medir","medir-area":"Área",dividir:"Dividir","selecao-laco":"Laço","conta-gotas":"Cor"};function ye(a){if(!a)return[];const t=a.split(/[\s,]+/).map(o=>o.trim().toLowerCase()).filter(Boolean);if(t.includes("todas"))return[...ie];const e=new Set(t.filter(Ue));return ie.filter(o=>e.has(o))}class fr{constructor(t){p(this,"barra",null);this.ctx=t}montar(t){var o;if((o=this.barra)==null||o.remove(),this.barra=null,t.length===0)return;const e=document.createElement("div");e.className="cad-quick-toolbar cad-draw-toolbar",e.setAttribute("role","toolbar"),e.setAttribute("aria-label","Ferramentas de desenho");for(const i of t){const n=document.createElement("button");n.type="button",n.className="cad-btn-tool cad-draw-btn",n.dataset.ferramenta=i,n.textContent=Io[i],n.title=Io[i],n.setAttribute("aria-pressed","false"),n.addEventListener("click",()=>this.ctx.aoEscolher(i)),e.appendChild(n)}this.ctx.raiz.appendChild(e),this.barra=e}marcar(t){var e;(e=this.barra)==null||e.querySelectorAll("[data-ferramenta]").forEach(o=>{const i=o.dataset.ferramenta===t;o.classList.toggle("active",i),o.setAttribute("aria-pressed",String(i))})}desmontar(){var t;(t=this.barra)==null||t.remove(),this.barra=null}}const mr="data-cad-estilos-externos";function gr(a){try{return Array.from(a.cssRules,t=>t.cssText).join(`
|
|
167
|
-
`)}catch{return""}}function
|
|
168
|
-
`),this.shadow.appendChild(e),this.fallback=e}remover(){var e;const t=this.shadow;this.adotadas.length>0&&Array.isArray(t.adoptedStyleSheets)&&(t.adoptedStyleSheets=t.adoptedStyleSheets.filter(o=>!this.adotadas.includes(o))),this.adotadas=[],(e=this.fallback)==null||e.remove(),this.fallback=null}}class sa extends _o.SafeHTMLElement{constructor(){super();p(this,"shadow");p(this,"mapContainer",null);p(this,"layersPanel",null);p(this,"controller");p(this,"controladorTamanho");p(this,"toolbarPainel");p(this,"broadcastConfig");p(this,"colecoesDados");p(this,"feicoes");p(this,"barraFerramentas");p(this,"hoverListeners",new be.ListenerBag);p(this,"desligarAnuncios",null);p(this,"layerItemListeners",new be.ListenerBag);p(this,"initTimeout");p(this,"estilosExternos");p(this,"lastPopupActionEmit");p(this,"lastCanvasClickTime",0);p(this,"_chaveGrupo");p(this,"_zonaProjecao",22);this.shadow=this.attachShadow({mode:"open"}),this.controller=new ne,this.controladorTamanho=Pi(this,this.controller),this.shadow.innerHTML=dn(),this.estilosExternos=new yr(this.shadow),this.mapContainer=this.shadow.getElementById("cad-map-container"),this.layersPanel=this.shadow.getElementById("qgis-layer-panel"),this.toolbarPainel=new sn({shadow:this.shadow,mapContainer:this.mapContainer,layersPanel:this.layersPanel,onToggleCamadas:()=>this.toggleLayersPanel(),onCloseCamadas:()=>this.closeLayersPanel(),onZoomExtents:()=>this.zoomExtents(),onLimparSelecao:()=>this.limparSelecao(),onToggleSnap:()=>this.feicoes.alternarSnap(),onTratarCliqueCanvas:n=>this.tratarCliqueLivreCanvas(n),onDispararAcaoPopup:(n,r)=>this.dispararAcaoPopup(n,r)}),this.broadcastConfig=new rn({host:this,controller:this.controller,mapContainer:this.mapContainer,setLayerOpacity:(n,r)=>this.setLayerOpacity(n,r)}),this.colecoesDados=new cn({obterController:()=>this.controller,obterChaveGrupo:()=>this.chaveGrupo,setLayerVisibility:(n,r)=>this.setLayerVisibility(n,r)});const e=new ae,o=this.controller.context,i=this.controller.canvasInteracao.ctx;Object.assign(o,{regraVersoes:e}),this.feicoes=new pr({obterLayerManager:()=>this.controller.layerManager,obterMapa:()=>this.controller.getMap(),regra:e,modoPopups:()=>this.popups,liberarPopups:n=>Te(this.controller.getMap(),n),aoFerramenta:n=>{this.barraFerramentas.marcar(n)},aoSnapMudar:n=>{po(this.shadow,n)},emitir:(n,r,s)=>{const c=new CustomEvent(n,{detail:r,bubbles:!0,composed:!0,cancelable:!!s});return this.dispatchEvent(c),c.defaultPrevented}}),Object.assign(o,{onLayerAction:(n,r)=>{const s=this.feicoes.tratarAcaoCamada(n,r);s&&this.dispatchEvent(new CustomEvent(s,{detail:r,bubbles:!0,composed:!0}))}}),this.barraFerramentas=new fr({raiz:this.shadow.getElementById("cad-root"),aoEscolher:n=>{this.feicoes.alternarFerramenta(n)}}),this.barraFerramentas.montar(ye(this.getAttribute("ferramentas"))),Object.assign(i,{aoMenuContexto:n=>this.feicoes.menuContexto(n),ferramentaAtiva:()=>this.feicoes.ferramentaAtiva!==null,aoLimparSelecao:()=>this.feicoes.aoPedirLimpeza(),selecionarFeicoesNaCaixa:(n,r,s)=>this.feicoes.selecionarNaCaixa(n,r,s)}),pn(this.shadow),po(this.shadow,!0)}static get observedAttributes(){return["sat-opacity","scale-mode","crosshair","modo-sequencial","chave-grupo","zona-projecao","fuso","canal-configuracao","ferramentas","sem-atalho-snap","aceitar-origem","sem-camadas-padrao","sem-painel-camadas","sem-barra-rapida","popups"]}connectedCallback(){var o;const e=this.getAttribute("zona-projecao")||this.getAttribute("fuso");if(e){const i=parseInt(e,10);!isNaN(i)&&i>0&&(this._zonaProjecao=i,this.controller.zonaProjecao=i,this.controller.context.zonaProjecao=i)}this.controller.core.definirModoPopups(this.popups),this.controladorTamanho.observe(),this.feicoes.conectarTeclado(),this.hoverListeners.cleanup(),this.mapContainer&&(this.hoverListeners.add(this.mapContainer,"mousemove",i=>this.feicoes.aoMoverMouse(i)),this.hoverListeners.add(this.mapContainer,"dblclick",i=>this.feicoes.aoDuploClique(i))),this.barraFerramentas.montar(ye(this.getAttribute("ferramentas"))),this.broadcastConfig.conectar(),(o=this.desligarAnuncios)==null||o.call(this),this.desligarAnuncios=gn(this,this.shadow),this.estilosExternos.aplicar(),this.initTimeout=window.setTimeout(()=>{this.initTimeout=void 0,this.inicializarAgora()},0)}destroy(){var e;this.initTimeout&&(window.clearTimeout(this.initTimeout),this.initTimeout=void 0),this.controladorTamanho.disconnect(),this.estilosExternos.limpar(),this.feicoes.pararEdicao(),this.feicoes.desativarFerramenta(),this.feicoes.limparMedicao(),this.feicoes.desconectarTeclado(),this.feicoes.destruir(),this.hoverListeners.cleanup(),(e=this.desligarAnuncios)==null||e.call(this),this.desligarAnuncios=null,this.broadcastConfig.desconectar(),this.limparDestaque(),this.toolbarPainel.limpar(),this.layerItemListeners.cleanup(),this.controller.destroy(),Ci(this.mapContainer)}disconnectedCallback(){this.destroy()}invalidateSizeSafely(){this.controladorTamanho.invalidateSizeSafely()}attributeChangedCallback(e,o,i){var n,r,s,c,l,d;if(e==="sem-atalho-snap"){(n=this.feicoes)==null||n.definirAtalhoSnap(i===null);return}if(!(e==="sem-camadas-padrao"||e==="sem-barra-rapida")){if(e==="sem-painel-camadas"){i!==null&&((r=this.toolbarPainel)==null||r.closeLayersPanel());return}if(e==="popups"){(s=this.controller)==null||s.core.definirModoPopups(Wt(i));return}if(e==="aceitar-origem"){this.feicoes&&(this.feicoes.aceitarOrigem=i!==null&&i!=="false");return}if(e==="ferramentas"){(c=this.barraFerramentas)==null||c.montar(ye(i)),(d=this.barraFerramentas)==null||d.marcar(((l=this.feicoes)==null?void 0:l.ferramentaAtiva)??null);return}hn({host:this,controller:this.controller,mapContainer:this.mapContainer,broadcastConfig:this.broadcastConfig,setLayerOpacity:(h,u)=>this.setLayerOpacity(h,u),setLayerScaleMode:(h,u)=>this.setLayerScaleMode(h,u),atualizarZonaProjecao:h=>{this._zonaProjecao=h}},e,o,i)}}inicializarAgora(){this.initTimeout!==void 0&&(window.clearTimeout(this.initTimeout),this.initTimeout=void 0);const e=this.controller.getMap();return e||(this.hasAttribute("sem-camadas-padrao")&&this.controller.layerManager.descartarCamadasPadrao(),this.initCAD(),this.controller.getMap())}definirEstilosExternos(e){this.estilosExternos.definir(e)}initCAD(){un({host:this,shadow:this.shadow,mapContainer:this.mapContainer,controller:this.controller,toolbarPainel:this.toolbarPainel,colecoesDados:this.colecoesDados,obterContextoEventos:()=>this.obterContextoEventos(),renderLayersUI:()=>this.renderLayersUI(),invalidateSizeSafely:()=>this.invalidateSizeSafely(),tratarCliqueLivreCanvas:(e,o,i)=>this.tratarCliqueLivreCanvas(e,o,i),dispararAcaoPopup:(e,o,i)=>this.dispararAcaoPopup(e,o,i)})}obterContextoEventos(){return{host:this,controller:this.controller,mapContainer:this.mapContainer,modoSequencial:this.modoSequencial,mouseMovedSinceDown:this.toolbarPainel.houveMovimentoMouse,obterElementoPorId:e=>this.colecoesDados.obterElementoPorId(e),fecharPopup:()=>{var e;(e=this.controller.getMap())==null||e.closePopup()}}}tratarCliqueLivreCanvas(e,o,i){const n=Date.now();n-this.lastCanvasClickTime<50||(this.lastCanvasClickTime=n,vi(this.obterContextoEventos(),e,o,i))}dispararAcaoPopup(e,o,i){const n=Date.now();this.lastPopupActionEmit&&this.lastPopupActionEmit.acaoId===e&&this.lastPopupActionEmit.elementoId===o&&n-this.lastPopupActionEmit.time<50||(this.lastPopupActionEmit={acaoId:e,elementoId:o,time:n},yi(this.obterContextoEventos(),e,o,i))}toggleLayersPanel(){this.hasAttribute("sem-painel-camadas")||this.toolbarPainel.toggleLayersPanel()}closeLayersPanel(){this.toolbarPainel.closeLayersPanel()}renderLayersUI(){const e=this.shadow.getElementById("layers-list-container");mi(e,this.controller.layerManager.getLayers(),this.layerItemListeners,{setLayerVisibility:(o,i)=>this.setLayerVisibility(o,i),setLayerOpacity:(o,i)=>this.setLayerOpacity(o,i),setLayerBlocked:(o,i)=>this.controller.layerManager.setLayerBlocked(o,i),setLayerScaleMode:(o,i)=>this.setLayerScaleMode(o,i)})}get pontos(){return this.colecoesDados.pontos}set pontos(e){this.colecoesDados.pontos=e}get segmentos(){return this.colecoesDados.segmentos}set segmentos(e){this.colecoesDados.segmentos=e}get bancoPontos(){return this.colecoesDados.bancoPontos}set bancoPontos(e){this.colecoesDados.bancoPontos=e}get pontosHomologados(){return this.bancoPontos}set pontosHomologados(e){this.bancoPontos=e}get confrontantes(){return this.colecoesDados.confrontantes}set confrontantes(e){this.colecoesDados.confrontantes=e}get vizinhos(){return this.confrontantes}set vizinhos(e){this.confrontantes=e}get aceitarOrigem(){return this.hasAttribute("aceitar-origem")&&this.getAttribute("aceitar-origem")!=="false"}set aceitarOrigem(e){e?this.setAttribute("aceitar-origem",""):this.removeAttribute("aceitar-origem")}get popups(){return Wt(this.getAttribute("popups"))}set popups(e){this.setAttribute("popups",String(e))}get modoSequencial(){return this.hasAttribute("modo-sequencial")}set modoSequencial(e){var i;const o=!!e;o?this.hasAttribute("modo-sequencial")||this.setAttribute("modo-sequencial",""):this.hasAttribute("modo-sequencial")&&this.removeAttribute("modo-sequencial"),this.controller.modoCliqueSequencialAtivo=o,this.controller.context.modoSequencial=o,o&&((i=this.controller.getMap())==null||i.closePopup())}get chaveGrupo(){return this.getAttribute("chave-grupo")||this._chaveGrupo}set chaveGrupo(e){this._chaveGrupo=e,e?this.getAttribute("chave-grupo")!==e&&this.setAttribute("chave-grupo",e):this.hasAttribute("chave-grupo")&&this.removeAttribute("chave-grupo"),this.controller.chaveGrupo=e,this.controller.context.chaveGrupo=e,this.controller.layerManager.updateContext({chaveGrupo:e})}get zonaProjecao(){return this._zonaProjecao??22}set zonaProjecao(e){const o=typeof e=="number"?Math.floor(e):parseInt(String(e),10);if(!isNaN(o)&&o>0){this._zonaProjecao=o;const i=String(o);this.getAttribute("zona-projecao")!==i&&this.setAttribute("zona-projecao",i),this.hasAttribute("fuso")&&this.getAttribute("fuso")!==i&&this.setAttribute("fuso",i),this.controller.zonaProjecao=o,this.controller.context.zonaProjecao=o}}get canalConfiguracao(){return this.getAttribute("canal-configuracao")}set canalConfiguracao(e){e?this.setAttribute("canal-configuracao",e):this.removeAttribute("canal-configuracao")}fitBounds(e,o=[40,40],i=!1){this.controller.fitBounds(e,o,i)}zoomExtents(){this.controller.canvasInteracao.zoomExtents()}selectPonto(e,o){this.controller.selectPonto(e,o)}selecionarPonto(e,o){this.controller.selectPonto(e,o)}get pontosSelecionados(){return en(this.controller)}set pontosSelecionados(e){const o=Array.isArray(e)?e:[];gi(this.controller,o),this.controller.atualizarDestaqueMarcadores()}atualizarDestaqueMarcadores(){this.controller.atualizarDestaqueMarcadores()}selectSegmento(e){this.controller.selectSegmento(e)}get segmentoSelecionado(){return this.controller.context.selectedSegmentoId||null}set segmentoSelecionado(e){this.controller.selectSegmento(e)}limparSelecao(){this.controller.canvasInteracao.limparSelecao(),this.feicoes.limparSelecaoFeicoes()}setLayerVisibility(e,o){this.controller.layerManager.setLayerVisibility(e,o)}setLayerOpacity(e,o){this.controller.layerManager.setLayerOpacity(e,o)}setLayerScaleMode(e,o){this.controller.layerManager.setLayerScaleMode(e,o)}setGraphicScale(e){this.controller.setGraphicScale(e)}exportState(){return this.controller.exportState()}importState(e){this.controller.importState(e)}invalidateSize(){this.invalidateSizeSafely()}get destaqueAtivo(){return this.controller.destaqueAtivo}destacarElemento(e,o){this.inicializarAgora(),this.controller.destacarElemento(e,o)}limparDestaque(){this.controller.limparDestaque()}plotarPontos(e,o="vertices",i){this.colecoesDados.plotarPontos(e,o,i)}plotarConexoes(e,o="linhas"){this.colecoesDados.plotarConexoes(e,o)}plotarPolilinhaSequencial(e,o=!0,i="polilinha",n){this.colecoesDados.plotarPolilinhaSequencial(e,o,i,n)}plotarPoligonos(e,o="poligonos"){this.colecoesDados.plotarPoligonos(e,o)}limparCamadas(e){this.colecoesDados.limparCamadas(e)}obterMarcadores(e){return this.colecoesDados.obterMarcadores(e)}plotPontos(e,o){this.colecoesDados.plotPontos(e,o)}plotSegmentos(e,o){this.colecoesDados.plotSegmentos(e,o)}plotPolilinhaTemporaria(e){this.colecoesDados.plotPolilinhaTemporaria(e)}plotPoligonalHomologada(e){this.colecoesDados.plotPoligonalHomologada(e)}plotPontosVizinhos(e){this.colecoesDados.plotPontosVizinhos(e)}plotPoligonosVizinhos(e){this.colecoesDados.plotPoligonosVizinhos(e)}clearOverlays(e=!1){this.colecoesDados.clearOverlays(e)}getMarkers(){return this.colecoesDados.getMarkers()}getVizinhosMarkers(){return this.colecoesDados.getVizinhosMarkers()}definirFeicoes(e,o,i){return this.feicoes.definirFeicoes(e,o,i)}adicionarFeicao(e,o,i){return this.feicoes.adicionarFeicao(e,o,i)}atualizarFeicao(e,o,i,n){return this.feicoes.atualizarFeicao(e,o,i,n)}aplicarLote(e,o,i){return this.feicoes.aplicarLote(e,o,i)}removerFeicao(e,o){return this.feicoes.removerFeicao(e,o)}obterFeicoes(e){return this.feicoes.obterFeicoes(e)}selecionarFeicoes(e,o=!1){this.feicoes.selecionarFeicoes(e,o)}selecionarFeicao(e,o){this.feicoes.selecionarFeicoes([{camadaId:e,id:o}])}alternarSelecaoFeicao(e,o){this.feicoes.alternarSelecaoFeicao({camadaId:e,id:o})}limparSelecaoFeicoes(){this.feicoes.limparSelecaoFeicoes()}obterFeicoesSelecionadas(){return this.feicoes.obterFeicoesSelecionadas()}editarVertices(e,o){return this.feicoes.iniciarEdicao(e,o)}pararEdicaoVertices(){this.feicoes.pararEdicao()}get editandoVertices(){return this.feicoes.editando}get snapLigado(){return this.feicoes.snapLigado}definirSnap(e){this.feicoes.definirSnap(e)}alternarSnap(){this.feicoes.alternarSnap()}definirCamadaDesenho(e){this.feicoes.definirCamadaDesenho(e)}get camadaDesenho(){return this.feicoes.camadaDeDesenho}definirEstiloDesenho(e){this.feicoes.definirEstiloDesenho(e)}obterEstiloDesenho(){return this.feicoes.obterEstiloDesenho()}definirFerramenta(e,o){return e===null?(this.feicoes.desativarFerramenta(),{ok:!0}):this.feicoes.ativarFerramenta(e,o)}get ferramentaAtiva(){return this.feicoes.ferramentaAtiva}limparMedicao(){this.feicoes.limparMedicao()}get nosDesenho(){return this.feicoes.nosDesenho}desfazerVerticeDesenho(){return this.feicoes.desfazerVerticeDesenho()}definirAtalhoSnap(e){this.feicoes.definirAtalhoSnap(e)}gerarBuffer(e,o,i,n){return this.feicoes.gerarBuffer(e,o,i,n)}duplicarFeicao(e,o,i,n){return this.feicoes.duplicarFeicao(e,o,i,n)}juntarFeicoes(e,o,i){return this.feicoes.juntarFeicoes(e,o,i)}zoomParaFeicao(e,o){return this.feicoes.zoomParaFeicao(e,o)}zoomParaFeicoes(e){return this.feicoes.zoomParaFeicoes(e)}ajustarTudo(){return this.feicoes.ajustarTudo()}ajustarCamada(e){return this.feicoes.ajustarCamada(e)}get previasGlobais(){return this.feicoes.previasGlobais}definirPreviasGlobais(e){this.feicoes.definirPreviasGlobais(e)}alternarPreviasGlobais(){this.feicoes.alternarPreviasGlobais()}alternarPrevia(e,o){return this.feicoes.alternarPrevia(e,o)}previaSolicitada(e,o){return this.feicoes.previaSolicitada(e,o)}atualizarCursorRemoto(e,o){return this.feicoes.atualizarCursorRemoto(e,o)}removerCursorRemoto(e){return this.feicoes.removerCursorRemoto(e)}limparCursoresRemotos(){this.feicoes.limparCursoresRemotos()}fecharPopupFeicao(){this.feicoes.fecharPopup()}abrirPopupFeicao(e,o){return this.feicoes.abrirPopupFeicao(e,o)}definirOpcoesPopup(e){this.feicoes.definirOpcoesPopup(e)}definirMargensPopup(e){this.feicoes.definirMargensPopup(e)}definirMargensHud(e){this.feicoes.definirMargensHud(e)}getMap(){return this.controller.getMap()}getController(){return this.controller}getLayerManager(){return this.controller.layerManager}}_o.definirCustomElement("ui-canvas-cad",sa);class br{constructor(t,e){p(this,"polylines",[]);p(this,"bancoPontosAtivo",!1);p(this,"core");this.core=t}setBancoPontosAtivo(t){this.bancoPontosAtivo=t}plotSegmentos(t,e){this.core.map&&t.forEach(o=>{const i=e.find(r=>String(r.id)===String(o.ponto_inicio_id)),n=e.find(r=>String(r.id)===String(o.ponto_fim_id));if(i&&n&&i.lat&&i.lon&&n.lat&&n.lon){const r=o.tipo_limite_sigef||o.tipo_limite||"",s=o.metodo_posicionamento_sigef||o.metodo_posicionamento||"",c=this.bancoPontosAtivo?"#94a3b8":r==="LA1"?"#10b981":"#3b82f6",l=this.core.config.perimetroWeight,d=this.bancoPontosAtivo?.4:1,h=[[i.lat,i.lon],[n.lat,n.lon]],u=v.polyline(h,{color:"#080d0a",weight:l+3,opacity:.85,lineCap:"round",lineJoin:"round",dashArray:r==="LN1"?"6, 6":void 0,pane:"perimetroPane",interactive:!1}).addTo(this.core.map);this.polylines.push(u);const g=v.polyline(h,{color:c,weight:l,opacity:d,dashArray:r==="LN1"?"6, 6":void 0,pane:"perimetroPane"}).bindPopup(`
|
|
166
|
+
`}function Ua(a,e,t,o){if(t!==o){if(e==="sat-opacity"){const i=parseFloat(o);isNaN(i)||a.setLayerOpacity("satelite",i)}else if(e==="scale-mode")(o==="world"||o==="screen")&&(a.setLayerScaleMode("perimetro",o),a.setLayerScaleMode("vertices",o));else if(e==="modo-sequencial")a.host.modoSequencial=o!==null&&o!=="false";else if(e==="chave-grupo")a.host.chaveGrupo=o||void 0;else if(e==="zona-projecao"||e==="fuso"){const i=parseInt(o,10);!isNaN(i)&&i>0&&(a.atualizarZonaProjecao(i),e==="fuso"&&a.host.getAttribute("zona-projecao")!==o?a.host.setAttribute("zona-projecao",o):e==="zona-projecao"&&a.host.hasAttribute("fuso")&&a.host.getAttribute("fuso")!==o&&a.host.setAttribute("fuso",o),a.controller.zonaProjecao=i,a.controller.context.zonaProjecao=i)}else if(e==="canal-configuracao")a.broadcastConfig.conectar(o);else if(e==="crosshair"){const i=o!==null&&o!=="false";a.mapContainer&&(a.mapContainer.style.cursor=i?"crosshair":"");const n=a.controller.getMap();if(n){const r=n.getContainer();r&&(r.style.cursor=i?"crosshair":"")}a.controller.core.config.crosshair=i}}}function fi(a){const e=a;if(!e||!e._leaflet_id)return!1;try{delete e._leaflet_id}catch{e._leaflet_id=void 0}return!0}function Wa(a){if(!a.mapContainer)return;if(a.controller.getMap()||fi(a.mapContainer),a.controller.init(a.mapContainer,a.shadow),a.toolbarPainel.vincularEventos(),a.renderLayersUI(),a.host.hasAttribute("modo-sequencial")&&(a.controller.modoCliqueSequencialAtivo=!0,a.controller.context.modoSequencial=!0),a.host.hasAttribute("chave-grupo")){const o=a.host.getAttribute("chave-grupo");o&&(a.host.chaveGrupo=o)}if(a.host.hasAttribute("zona-projecao")||a.host.hasAttribute("fuso")){const o=a.host.zonaProjecao;a.controller.zonaProjecao=o,a.controller.context.zonaProjecao=o}if(a.host.hasAttribute("crosshair")){const o=a.host.getAttribute("crosshair")!=="false";a.mapContainer&&(a.mapContainer.style.cursor=o?"crosshair":""),a.controller.core.config.crosshair=o}a.colecoesDados.sincronizarInicial(),a.controller.layerManager.onChange(o=>{a.renderLayersUI(),a.host.dispatchEvent(new CustomEvent("ui-camadas-alteradas",{detail:{layers:o},bubbles:!0,composed:!0}))});const e=a.controller.context.onMarkerClick;a.controller.context.onMarkerClick=(o,i,n,r)=>{hi(a.obterContextoEventos(),o,i,n,r,e,a.colecoesDados.customMarkerClickHandler)},a.controller.context.onSegmentoClick=(o,i,n)=>{ui(a.obterContextoEventos(),o,i,n)},a.controller.context.onPopupAcao=(o,i,n)=>{a.dispararAcaoPopup(o,i,n)};const t=a.controller.getMap();t&&t.on("click",o=>{a.toolbarPainel.houveMovimentoMouse||a.tratarCliqueLivreCanvas(o,o.latlng,o.containerPoint)}),setTimeout(()=>{a.invalidateSizeSafely()},150)}function Za(a){a.querySelectorAll(".cad-quick-toolbar .cad-btn-tool, .layer-panel-close").forEach(e=>{const t=e.getAttribute("title");t&&!e.hasAttribute("aria-label")&&e.setAttribute("aria-label",t)})}function Yt(a,e){const t=a.getElementById("btn-toggle-snap");t==null||t.classList.toggle("active",e),t==null||t.setAttribute("aria-pressed",String(e))}function Xa(a){return a<=0?"Nenhuma feição selecionada":a===1?"1 feição selecionada":`${a} feições selecionadas`}function Ya(a){return a?`Ferramenta ${a} ativa`:"Ferramenta desativada"}function Kt(a,e){const t=a.getElementById("cad-status");t&&t.textContent!==e&&(t.textContent=e)}function Ka(a,e){const t=i=>{var r;const n=(r=i.detail)==null?void 0:r.feicoes;Kt(e,Xa(Array.isArray(n)?n.length:0))},o=i=>{var r;const n=((r=i.detail)==null?void 0:r.ferramenta)??null;Kt(e,Ya(n))};return a.addEventListener("cad-selecao",t),a.addEventListener("cad-ferramenta",o),()=>{a.removeEventListener("cad-selecao",t),a.removeEventListener("cad-ferramenta",o)}}function Z(a,e){let t,o;if(Array.isArray(a))[t,o]=a;else if(a&&typeof a=="object"){const n=a;t=n.lat??n.latitude,o=n.lng??n.lon??n.longitude}else return null;const i=M.parseCoordenada(t,o,e);return!i||!Number.isFinite(i.lat)||!Number.isFinite(i.lon)?null:[i.lat,i.lon]}function Ja(a,e){return a[0]===e[0]&&a[1]===e[1]}function Tt(a,e){const t=a.map(o=>Z(o,e)).filter(o=>o!==null);return t.length>1&&Ja(t[0],t[t.length-1])&&t.pop(),t.length>=3?t:null}function yt(a,e){const t=a.map(o=>Z(o,e)).filter(o=>o!==null);return t.length>=2?t:null}function mi(a,e){if(!Array.isArray(a)||a.length===0)return null;const o=(Array.isArray(a[0])&&Array.isArray(a[0][0])?a:[a]).map(i=>Tt(i,e));return o.some(i=>i===null)?null:o}function Qa(a,e){const t=M.parseCoordenada(a.lat,a.lon);return t?{id:String(a.id),camadaId:e,geometria:{tipo:"Point",coordenada:[t.lat,t.lon]},propriedades:{...a}}:null}function en(a,e,t){const o=e.get(String(a.ponto_inicio_id)),i=e.get(String(a.ponto_fim_id));if(!o||!i)return null;const n=M.parseCoordenada(o.lat,o.lon),r=M.parseCoordenada(i.lat,i.lon);if(!n||!r)return null;const s=(a.tipo_limite_sigef??a.tipo_limite)==="LN1";return{id:String(a.id??`${a.ponto_inicio_id}-${a.ponto_fim_id}`),camadaId:t,geometria:{tipo:"LineString",coordenadas:[[n.lat,n.lon],[r.lat,r.lon]]},estilo:s?{dashArray:"6, 6"}:void 0,propriedades:{...a}}}function tn(a,e){if(!a.poligono_wkt)return null;const t=/POLYGON\s*\(\s*\(\s*(.*?)\s*\)\s*\)/i.exec(a.poligono_wkt);if(!t)return null;const o=t[1].split(",").map(n=>{const[r,s]=n.trim().split(/\s+/);return[s,r]}),i=Tt(o);return i?{id:String(a.id??a.nome??""),camadaId:e,geometria:{tipo:"Polygon",aneis:[i]},propriedades:{nome:a.nome,nome_propriedade:a.nome_propriedade}}:null}function Jt(a,e){const t=m.normalizarNos(a);if(!t)return null;const o=[];for(const i of t){const n=Z(i.ponto,e);if(!n)return null;const r={ponto:n},s=i.entrada&&Z(i.entrada,{...e,aceitarOrigem:!0}),c=i.saida&&Z(i.saida,{...e,aceitarOrigem:!0});s&&(r.entrada=s),c&&(r.saida=c),o.push(r)}return o}const on=new Set(["Point","LineString","Polygon","Circle","Text"]);function Oe(a,e,t){if(!a||typeof a!="object")return null;const o=a,i=o.geometria;if(!i||!on.has(i.tipo)||o.id===void 0||o.id===null||o.id==="")return null;let n=null;switch(i.tipo){case"Point":{const s=Z(i.coordenada,t);s&&(n={tipo:"Point",coordenada:s});break}case"Text":{const s=Z(i.coordenada,t);s&&typeof i.texto=="string"&&i.texto&&(n={tipo:"Text",coordenada:s,texto:i.texto});break}case"LineString":{const s=Array.isArray(i.partes)?i.partes.map(l=>Array.isArray(l)?yt(l,t):null).filter(l=>l!==null):[];if(s.length>0)n=m.criarLinha(s);else{const l=Array.isArray(i.coordenadas)?yt(i.coordenadas,t):null;l&&(n=m.criarLinha([l]))}const c=s.length<=1?Jt(i.curva,t):null;n&&n.tipo==="LineString"&&c&&c.length>=2&&(n={tipo:"LineString",coordenadas:m.amostrarCurva(c,!1),curva:c});break}case"Polygon":{const s=Array.isArray(i.aneis)?mi(i.aneis,t):null;s&&(n={tipo:"Polygon",aneis:s});const c=s&&s.length===1?Jt(i.curva,t):null;n&&c&&c.length>=3&&(n={tipo:"Polygon",aneis:[m.amostrarCurva(c,!0)],curva:c});break}case"Circle":{const s=Z(i.centro,t),c=Number(i.raioMetros);s&&Number.isFinite(c)&&c>0&&(n={tipo:"Circle",centro:s,raioMetros:c});break}}if(!n)return null;const r={id:String(o.id),camadaId:e,geometria:n,estilo:o.estilo&&typeof o.estilo=="object"?{...o.estilo}:void 0,propriedades:o.propriedades&&typeof o.propriedades=="object"?{...o.propriedades}:{},bloqueada:!!o.bloqueada,status:"oficial",excluida:!!o.excluida};return o.oculta&&(r.oculta=!0),(typeof o.entidadeId=="string"||typeof o.entidadeId=="number")&&(r.entidadeId=String(o.entidadeId)),r.status=m.statusDe({...r,status:o.status}),r}const at="cad-cursores",an=/^#[0-9a-f]{3,8}$/i,nn="#94a3b8";function We(a){return typeof a=="string"&&an.test(a.trim())?a.trim():nn}const rn='<svg width="18" height="18" viewBox="0 0 24 24" style="display:block;filter:drop-shadow(0 1px 1px rgba(0,0,0,.6))"><path d="M3 2 L3 19 L8 14.5 L11.5 22 L14.5 20.5 L11 13.5 L18 13 Z" fill="currentColor" stroke="#fff" stroke-width="1.2" stroke-linejoin="round"/></svg>';function Qt(a){const e=document.createElement("div");e.style.cssText=`color:${We(a.cor)};position:relative;pointer-events:none`,e.innerHTML=rn;const t=document.createElement("span");return t.textContent=String(a.nome??a.id),t.style.cssText=`position:absolute;left:16px;top:14px;white-space:nowrap;font:600 11px sans-serif;color:#fff;background:${We(a.cor)};padding:1px 5px;border-radius:3px;max-width:160px;overflow:hidden;text-overflow:ellipsis`,e.appendChild(t),b.divIcon({className:"custom-leaflet-marker cad-cursor-remoto",iconSize:[18,18],iconAnchor:[3,2],html:e})}class gi{constructor(e){f(this,"marcadores",new Map);this.obterMapa=e}get quantidade(){return this.marcadores.size}atualizar(e,t){const o=this.obterMapa();if(!o||!e||e.id===void 0||e.id===null||e.id===""||!Number.isFinite(t==null?void 0:t[0])||!Number.isFinite(t==null?void 0:t[1]))return!1;const i=String(e.id),n=`${e.nome??""}\0${We(e.cor)}`,r=this.marcadores.get(i);if(r)return r.marker.setLatLng(t),r.assinatura!==n&&(r.marker.setIcon(Qt(e)),r.assinatura=n),!0;o.getPane(at)||(o.createPane(at).style.zIndex="9500");const s=b.marker(t,{icon:Qt(e),pane:at,interactive:!1,keyboard:!1}).addTo(o);return this.marcadores.set(i,{marker:s,assinatura:n}),!0}remover(e){const t=this.marcadores.get(String(e));return t?(t.marker.remove(),this.marcadores.delete(String(e)),!0):!1}limpar(){for(const e of this.marcadores.values())e.marker.remove();this.marcadores.clear()}}const ze=a=>`${a.camadaId}\0${a.id}`;class vi{constructor(e){f(this,"itens",new Map);this.dep=e}get quantidade(){return this.itens.size}contem(e){return this.itens.has(ze(e))}obter(){const e=[];for(const t of this.itens.values()){const o=this.dep.obterFeicao(t);o&&e.push(o)}return e}selecionar(e,t=!1){const o=this.assinatura(),i=new Set;t||this.itens.forEach(n=>i.add(n.camadaId)),t||this.itens.clear();for(const n of e)this.alcancavel(n)&&(this.itens.set(ze(n),{camadaId:n.camadaId,id:n.id}),i.add(n.camadaId));this.finalizar(o,i)}alternar(e){const t=this.assinatura(),o=ze(e);this.itens.has(o)?this.itens.delete(o):this.alcancavel(e)&&this.itens.set(o,{camadaId:e.camadaId,id:e.id}),this.finalizar(t,new Set([e.camadaId]))}alternarVarias(e){const t=this.assinatura(),o=new Set;for(const i of e){const n=ze(i);this.itens.has(n)?this.itens.delete(n):this.alcancavel(i)&&this.itens.set(n,{camadaId:i.camadaId,id:i.id}),o.add(i.camadaId)}this.finalizar(t,o)}alcancavel(e){const t=this.dep.obterFeicao(e);return!!t&&(!this.dep.selecionavel||this.dep.selecionavel(t))}limpar(){if(this.itens.size===0)return;const e=this.assinatura(),t=new Set([...this.itens.values()].map(o=>o.camadaId));this.itens.clear(),this.finalizar(e,t)}reconciliar(){const e=this.assinatura(),t=new Set;for(const[o,i]of this.itens){const n=this.dep.obterFeicao(i);(!n||n.excluida||this.dep.visivel&&!this.dep.visivel(n))&&(this.itens.delete(o),t.add(i.camadaId))}t.size!==0&&this.finalizar(e,t)}assinatura(){return[...this.itens.keys()].join("|")}finalizar(e,t){for(const i of t){const n=new Set;for(const r of this.itens.values())r.camadaId===i&&n.add(r.id);this.dep.aplicarVisual(i,n)}if(this.assinatura()===e)return;const o=this.obter();this.dep.aoSelecionar(o),o.length<=1&&this.dep.aoSelecionarUma(o[0]??null)}}const sn={Point:"Ponto",LineString:"Linha",Polygon:"Polígono",Circle:"Círculo",Text:"Texto"},cn=new Set(["name","nome","category","categoria","description","descricao","author","autor","date","data","created_at","criadoEm"]),eo=6;function pe(a,e){var t;for(const o of e){const i=(t=a.propriedades)==null?void 0:t[o];if(i!=null&&String(i)!=="")return String(i)}return""}function ln(a){const e=/^(\d{4})-(\d{2})-(\d{2})$/.exec(a),t=e?new Date(Number(e[1]),Number(e[2])-1,Number(e[3])):new Date(a);return Number.isNaN(t.getTime())?a:t.toLocaleDateString("pt-BR")}function dn(a){const e=typeof a=="object"?JSON.stringify(a):String(a);return e.length>80?`${e.slice(0,77)}...`:e}function xe(a){const e=a.geometria;switch(e.tipo){case"Point":case"Text":return e.coordenada;case"Circle":return e.centro;case"LineString":return e.coordenadas[Math.floor(e.coordenadas.length/2)];case"Polygon":{const t=e.aneis[0],o=t.reduce((n,r)=>n+r[0],0)/t.length,i=t.reduce((n,r)=>n+r[1],0)/t.length;return[o,i]}}}function hn(a){const e=a.geometria,t=[],o=m.areaDaGeometria(e),i=m.extensaoDaGeometria(e);if(e.tipo==="Polygon")t.push(["Área",m.formatarArea(o??0)],["Perímetro",m.formatarExtensao(i??0)]),t.push(["Vértices",String(e.aneis.reduce((s,c)=>s+c.length,0))]);else if(e.tipo==="LineString"){const s=m.partesDaLinha(e);t.push(["Extensão",m.formatarExtensao(i??0)],["Vértices",String(s.reduce((c,l)=>c+l.length,0))]),s.length>1&&t.push(["Partes",String(s.length)])}else e.tipo==="Circle"&&t.push(["Raio",m.formatarExtensao(e.raioMetros)],["Área",m.formatarArea(o??0)]);const[n,r]=xe(a);return t.push(["Coordenadas",`${n.toFixed(6)}, ${r.toFixed(6)}`]),t}class yi{constructor(e){f(this,"popup",null);f(this,"feicaoAtual",null);f(this,"margens",{topo:20,base:20,esquerda:20,direita:20});this.dep=e}definirMargens(e){this.margens={...this.margens,...e}}get aberto(){return this.feicaoAtual}abrir(e){const t=this.dep.obterMapa();if(!t)return;this.fechar(),this.feicaoAtual=e,this.popup=b.popup({className:"compact-popup",maxWidth:280,closeOnClick:!1,autoClose:!1,autoPanPaddingTopLeft:b.point(this.margens.esquerda,this.margens.topo),autoPanPaddingBottomRight:b.point(this.margens.direita,this.margens.base)}).setLatLng(xe(e)).setContent(this.montar(e));const o=this.popup;this.dep.liberar?this.dep.liberar(()=>o.openOn(t)):o.openOn(t)}atualizar(e){var t;!this.popup||((t=this.feicaoAtual)==null?void 0:t.id)!==e.id||this.feicaoAtual.camadaId!==e.camadaId||(this.feicaoAtual=e,this.popup.setLatLng(xe(e)).setContent(this.montar(e)))}fechar(){const e=this.popup;this.popup=null,this.feicaoAtual=null,e==null||e.close()}montar(e){var p;const t=this.dep.obterCamada(e.camadaId),o=m.corSegura(((p=e.estilo)==null?void 0:p.corTraco)??(t==null?void 0:t.estilo.corPrimaria),"#38bdf8"),i=(y,A="",w)=>{const x=document.createElement(y);return A&&(x.style.cssText=A),w!==void 0&&(x.textContent=w),x},n=i("div","font-family:var(--ui-fonte-base,sans-serif);color:rgba(255,255,255,.9);line-height:1.35;min-width:200px;border-left:3px solid "+o+";padding-left:8px");n.className="cad-feicao-popup",n.appendChild(i("div","font-weight:700;font-size:13px;margin-bottom:1px",pe(e,["name","nome"])||e.id));const r=pe(e,["category","categoria"]),s=[sn[e.geometria.tipo],(t==null?void 0:t.nome)??e.camadaId,r].filter(Boolean).join(" · ");n.appendChild(i("div","font-size:11px;color:rgba(255,255,255,.6);margin-bottom:4px",s));const c=pe(e,["description","descricao"]);c&&n.appendChild(i("div","font-size:11px;margin-bottom:4px",c));const l=y=>{const A=i("div","font-size:11px;margin-bottom:4px");for(const[w,x]of y){const k=i("div");k.appendChild(i("strong","",`${w}: `)),k.appendChild(document.createTextNode(x)),A.appendChild(k)}return A};n.appendChild(l(hn(e)));const d=Object.entries(e.propriedades??{}).filter(([y,A])=>!cn.has(y)&&A!==void 0&&A!==null&&A!=="");d.length>0&&(n.appendChild(l(d.slice(0,eo).map(([y,A])=>[y,dn(A)]))),d.length>eo&&n.appendChild(i("div","font-size:10px;color:rgba(255,255,255,.55);margin-bottom:4px",`${d.length} atributos`)));const h=pe(e,["author","autor"]),u=pe(e,["date","data","created_at","criadoEm"]);if(h||u){const y=[h,u?ln(u):""].filter(Boolean).join(" · ");n.appendChild(i("div","font-size:10px;color:rgba(255,255,255,.55);margin-bottom:4px",y))}const g=i("div","display:flex;gap:4px;flex-wrap:wrap;margin-top:6px"),v=[["inspecionar","Inspecionar"],["zoom","Zoom"]];(e.geometria.tipo==="LineString"||e.geometria.tipo==="Polygon"||e.geometria.tipo==="Point")&&v.push(["vertices","Vértices"]),e.geometria.tipo==="Point"&&v.push(["copiar","Copiar"]);for(const[y,A]of v){const w=i("button","font-size:11px;padding:2px 8px;border-radius:4px;border:1px solid rgba(255,255,255,.25);background:rgba(255,255,255,.08);color:inherit;cursor:pointer",A);w.type="button",w.dataset.acao=y,w.addEventListener("click",x=>{x.stopPropagation(),this.dep.aoAcao(y,this.feicaoAtual??e)}),g.appendChild(w)}return n.appendChild(g),n}}class un{constructor(e){f(this,"_ligado",!0);f(this,"_altSegurado",!1);f(this,"atalhoS",!0);f(this,"conectado",!1);f(this,"aoTeclaBaixo",e=>{if(e.key==="Alt"){this.definirAlt(!0);return}this.atalhoS&&(e.key==="s"||e.key==="S")&&!e.ctrlKey&&!e.metaKey&&!e.altKey&&!Lt(e)&&this.alternar()});f(this,"aoTeclaCima",e=>{e.key==="Alt"&&this.definirAlt(!1)});f(this,"aoPerderFoco",()=>{this.definirAlt(!1)});this.contexto=e}get ativo(){return this._ligado&&!this._altSegurado}get ligado(){return this._ligado}definir(e){this._ligado!==e&&(this._ligado=e,this.notificar())}alternar(){this.definir(!this._ligado)}conectar(){if(this.conectado)return;this.conectado=!0;const e=this.contexto.alvo??window;e.addEventListener("keydown",this.aoTeclaBaixo),e.addEventListener("keyup",this.aoTeclaCima),e.addEventListener("blur",this.aoPerderFoco)}desconectar(){if(!this.conectado)return;this.conectado=!1;const e=this.contexto.alvo??window;e.removeEventListener("keydown",this.aoTeclaBaixo),e.removeEventListener("keyup",this.aoTeclaCima),e.removeEventListener("blur",this.aoPerderFoco),this._altSegurado=!1}definirAlt(e){this._altSegurado!==e&&(this._altSegurado=e,this.notificar())}notificar(){this.contexto.aoMudar({ativo:this.ativo,ligado:this._ligado,temporario:this._altSegurado})}}const G="feicoes";class pn{constructor(e){this.p=e}dividirComLinha(e){const t=this.p.obterLayerManager(),o=l=>(this.p.emitir("cad-divisao-falhou",{motivo:l}),!1),i=this.p.selecionadas().filter(l=>l.geometria.tipo==="Polygon");let n=i;if(n.length===0){n=[];for(const l of t.getActiveSelectableLayers())l.tipo===G&&n.push(...this.p.lista(l.id).filter(d=>d.geometria.tipo==="Polygon"&&this.p.desenhada(d)))}if(n.length===0)return o(i.length===0&&this.p.selecionadas().some(l=>m.ehMultilinha(l.geometria))?"multiparte":"nenhum-poligono");const r=l=>{var d;return!!l.bloqueada||!!((d=t.getLayerDef(l.camadaId))!=null&&d.bloqueada)},s=n.filter(l=>!r(l)&&l.geometria.tipo==="Polygon"&&l.geometria.aneis.length===1);if(s.length===0)return o(n.some(r)?"bloqueada":"poligono-com-furos");let c=!1;for(const l of s){if(l.geometria.tipo!=="Polygon")continue;const d=Do(l.geometria.aneis[0],e);if(!d)continue;this.p.divisaoAtiva()&&this.p.estaSelecionada({camadaId:l.camadaId,id:l.id})&&this.p.encerrarDesenho(),this.p.removerFeicao(l.camadaId,l.id);const h=[];if(d.forEach((u,g)=>{const v=De(l,this.p.idLivre(l.camadaId,`${l.id}-${g+1}`),{tipo:"Polygon",aneis:[u]}),p=this.p.adicionarFeicao(l.camadaId,v);p&&h.push(p)}),h.length!==d.length){for(const u of h)this.p.removerFeicao(u.camadaId,u.id);return this.p.adicionarFeicao(l.camadaId,l),o("geometria-invalida")}if(this.p.emitir("cad-feicao-dividida",{origem:l,partes:h}),c=!0,i.length===0)break}return c||o("sem-intersecao")}gerarBuffer(e,t,o,i={}){const n=this.p.buscar(e,t);if(!n)return null;const r=qo(n.geometria,o);if(!r)return null;const s=i.camadaDestino??e,c=this.p.adicionarFeicao(s,{id:i.id??this.p.idLivre(s,`${t}-buffer`),geometria:{tipo:"Polygon",aneis:[r]},estilo:n.estilo?{...n.estilo}:void 0,propriedades:{...n.propriedades,origem:t}});return c&&this.p.emitir("cad-feicao-criada",{camadaId:s,feicao:c}),c}duplicarFeicao(e,t,o={},i={}){const n=this.p.buscar(e,t);if(!n)return null;const r=Oo(n.geometria,o.lesteM??0,o.norteM??0),s=this.p.adicionarFeicao(e,De(n,i.id??this.p.idLivre(e,`${t}-copia`),r));return s&&this.p.emitir("cad-feicao-criada",{camadaId:e,feicao:s}),s}juntarFeicoes(e,t,o={}){const i=h=>(this.p.emitir("cad-uniao-falhou",{motivo:h}),null),n=t.map(h=>this.p.buscar(e,h));if(n.length<2||n.some(h=>!h))return i("feicoes-insuficientes");const r=n;if(new Set(r.map(h=>h.id)).size!==r.length)return i("feicoes-insuficientes");const s=this.p.obterLayerManager();if(r.some(h=>{var u;return h.excluida||h.bloqueada||((u=s.getLayerDef(h.camadaId))==null?void 0:u.bloqueada)}))return i("bloqueada");const c=o.toleranciaM??0;let l=null;if(r.every(h=>h.geometria.tipo==="LineString")){if(r.some(g=>m.ehMultilinha(g.geometria)))return i("multiparte");const h=r.map(g=>g.geometria.coordenadas),u=To(h,c);u&&(l=m.criarLinha([u]))}else if(r.every(h=>h.geometria.tipo==="Polygon"&&h.geometria.aneis.length===1)){let h=r[0].geometria.aneis[0];for(const u of r.slice(1))h=h?Fo(h,u.geometria.aneis[0],c):null;h&&(l={tipo:"Polygon",aneis:[h]})}else return i("tipos-incompativeis");if(!l)return i("sem-ligacao");for(const h of r)this.p.removerFeicao(e,h.id);const d=this.p.adicionarFeicao(e,De(r[0],o.id??this.p.idLivre(e,`${r[0].id}-uniao`),l));if(!d){for(const h of r)this.p.adicionarFeicao(e,h);return i("geometria-invalida")}return this.p.emitir("cad-feicao-unida",{origens:r,resultado:d}),d}}class fn{constructor(e,t){f(this,"cacheOficiais",new WeakMap);this.p=e,this.regra=t}oficiaisDe(e){const t=this.p.lista(e);let o=this.cacheOficiais.get(t);return o||(o=m.RegraVersoes.oficiais(t),this.cacheOficiais.set(t,o)),o}visivelPorVersao(e){const t=this.p.obterLayerManager().getLayerInstance(e.camadaId),o=N.get(G);return t&&o?o.feicaoVisivel(t,e):this.regra.visivel(e,this.oficiaisDe(e.camadaId))}desenhada(e){return!e.excluida&&!e.oculta&&this.visivelPorVersao(e)}aplicarVersoes(){const e=this.p.obterLayerManager(),t=N.get(G);for(const o of e.getLayers()){if(o.tipo!==G)continue;const i=e.getLayerInstance(o.id);i&&t&&t.reavaliarVersoes(i)}this.p.aposDados()}get previasGlobais(){return this.regra.global}definirPreviasGlobais(e){const t=!!e;this.regra.global!==t&&(this.regra.global=t,this.aplicarVersoes(),this.p.emitir("cad-previas",{global:t}))}alternarPreviasGlobais(){this.definirPreviasGlobais(!this.regra.global)}alternarPrevia(e,t){const o=this.p.buscar(e,t);if(!o)return null;const i=m.entidadeDe(o),n=this.regra.alternarIndividual(e,i);return this.aplicarVersoes(),this.p.emitir("cad-previas",{camadaId:e,entidadeId:i,ativa:n}),n}previaSolicitada(e,t){const o=this.p.buscar(e,t);return!!o&&this.regra.previaSolicitada(o)}garantirVisivel(e){const t=this.p.obterLayerManager(),o=t.getLayerDef(e.camadaId);if(o&&!o.visivel&&t.setLayerVisibility(e.camadaId,!0),!this.visivelPorVersao(e)){const i=m.entidadeDe(e);this.regra.definirIndividual(e.camadaId,i,!0),this.aplicarVersoes(),this.p.emitir("cad-previas",{camadaId:e.camadaId,entidadeId:i,ativa:!0})}}}class mn{constructor(e){this.p=e}limitesDe(e){let t=1/0,o=1/0,i=-1/0,n=-1/0;for(const r of e){const[[s,c],[l,d]]=m.limitesDaGeometria(r.geometria);s<t&&(t=s),c<o&&(o=c),l>i&&(i=l),d>n&&(n=d)}return Number.isFinite(t)?[[t,o],[i,n]]:null}enquadrar(e){const t=this.p.obterMapa(),o=this.limitesDe(e);return!t||!o?!1:(o[0][0]===o[1][0]&&o[0][1]===o[1][1]?t.flyTo([o[0][0],o[0][1]],Math.max(t.getZoom(),17)):t.fitBounds(o,{padding:[60,60],maxZoom:18}),!0)}zoomParaFeicao(e,t){const o=this.p.buscar(e,t);return!o||o.excluida?!1:(this.p.garantirVisivel(o),this.enquadrar([o]))}zoomParaFeicoes(e){const t=[];for(const o of Array.isArray(e)?e:[]){const i=this.p.buscar(o.camadaId,o.id);i&&!i.excluida&&(this.p.garantirVisivel(i),t.push(i))}return t.length>0&&this.enquadrar(t)}ajustarTudo(){const e=[];for(const t of this.p.obterLayerManager().getLayers())t.tipo!==G||!t.visivel||e.push(...this.p.lista(t.id).filter(o=>this.p.desenhada(o)));return this.enquadrar(e)}ajustarCamada(e){const t=this.p.obterLayerManager(),o=t.getLayerDef(e);return!o||o.tipo!==G?!1:(o.visivel||t.setLayerVisibility(e,!0),this.enquadrar(this.p.lista(e).filter(i=>this.p.desenhada(i))))}}const to=36,gn=.45;function vn(a,e){const t=Math.abs(e[0]-a[0]),o=Math.abs(e[1]-a[1]);if(t===0&&o===0)return null;const i=[];for(let n=0;n<to;n++){const r=n*2*Math.PI/to;i.push([a[0]+t*Math.sin(r),a[1]+o*Math.cos(r)])}return i}function bi(a,e){const t=Math.cos(a[0]*Math.PI/180)||1,o=e[0]-a[0],i=(e[1]-a[1])*t,n=Math.hypot(o,i);return n===0?null:{raio:n,inicio:Math.atan2(o,i),cosLat:t}}function yn(a,e,t=6){const o=bi(a,e);if(!o||t<3)return null;const i=[];for(let n=0;n<t;n++){const r=o.inicio+n*2*Math.PI/t;i.push([a[0]+o.raio*Math.sin(r),a[1]+o.raio*Math.cos(r)/o.cosLat])}return i}function bn(a,e,t=5){const o=bi(a,e);if(!o||t<3)return null;const i=t*2,n=[];for(let r=0;r<i;r++){const s=r%2===0?o.raio:o.raio*gn,c=o.inicio+r*2*Math.PI/i;n.push([a[0]+s*Math.sin(c),a[1]+s*Math.cos(c)/o.cosLat])}return n}const Ze=["ponto","linha","poligono","retangulo","elipse","poligono-regular","estrela","circulo","texto","caneta","medir-distancia","medir-area","dividir","selecao-laco","conta-gotas"],bt=2;function Ft(a){return typeof a=="string"&&Ze.includes(a)}function ve(a){return a.map(e=>{const t={ponto:e.ponto};return e.alca&&(t.saida=e.alca,t.entrada=m.espelhoDaAlca(e.ponto,e.alca)),t})}function xi(a){return m.amostrarCurva(ve(a),!1)}function nt(a,e){const t=m.temAlcas(a);if(e){const i=t?m.amostrarCurva(a,!0):a.map(n=>n.ponto);return t?{tipo:"Polygon",aneis:[i],curva:a}:{tipo:"Polygon",aneis:[i]}}const o=t?m.amostrarCurva(a,!1):a.map(i=>i.ponto);return t?{tipo:"LineString",coordenadas:o,curva:a}:{tipo:"LineString",coordenadas:o}}const xn=(a,e)=>a[0]===e[0]&&a[1]===e[1],oo={elipse:vn,"poligono-regular":(a,e)=>yn(a,e,6),estrela:(a,e)=>bn(a,e,5)};class $e{constructor(e,t=!1){f(this,"pontos",[]);f(this,"cursor",null);f(this,"ancoras",[]);this.ferramenta=e,this.fechar=t}get nos(){return this.ferramenta==="caneta"?this.ancoras.length:this.pontos.length}get ehSequencial(){return["linha","poligono","caneta","medir-distancia","medir-area","dividir","selecao-laco"].includes(this.ferramenta)}get ehArea(){return this.ferramenta==="poligono"||this.ferramenta==="medir-area"||this.ferramenta==="selecao-laco"||this.ferramenta==="caneta"&&this.fechar}get fechaNoPrimeiro(){return this.nos>=3&&(this.ehArea||this.ferramenta==="caneta")}get primeiro(){var e;return(this.ferramenta==="caneta"?(e=this.ancoras[0])==null?void 0:e.ponto:this.pontos[0])??null}get minimo(){return this.ehArea?3:2}get podeConcluir(){return this.ehSequencial&&this.nos>=this.minimo}mover(e){this.cursor=e}clicar(e){switch(this.ferramenta){case"ponto":return{concluida:{tipo:"Point",coordenada:e}};case"texto":return{concluida:{tipo:"Text",coordenada:e,texto:""}};case"retangulo":return this.pontos.length===0?(this.pontos.push(e),{}):{concluida:this.retangulo(this.pontos[0],e)??void 0};case"circulo":if(this.pontos.length===0)return this.pontos.push(e),{};{const t=m.distanciaMetros(this.pontos[0],e);return t>=bt?{concluida:{tipo:"Circle",centro:this.pontos[0],raioMetros:t}}:{}}case"elipse":case"poligono-regular":case"estrela":{if(this.pontos.length===0)return this.pontos.push(e),{};const t=oo[this.ferramenta](this.pontos[0],e);return t?{concluida:{tipo:"Polygon",aneis:[t]}}:{}}case"caneta":return this.ancoras.push({ponto:e}),{};case"conta-gotas":return{};default:return this.pontos.length>0&&xn(this.pontos[this.pontos.length-1],e)?{}:(this.pontos.push(e),{})}}definirAlca(e){const t=this.ancoras[this.ancoras.length-1];this.ferramenta==="caneta"&&t&&(t.alca=e)}desfazer(){const e=this.ferramenta==="caneta"?this.ancoras:this.pontos;return e.length===0?!1:(e.pop(),!0)}vertices(){return this.ferramenta==="caneta"?xi(this.ancoras):this.pontos}retangulo(e,t){return e[0]===t[0]||e[1]===t[1]?null:{tipo:"Polygon",aneis:[[[e[0],e[1]],[e[0],t[1]],[t[0],t[1]],[t[0],e[1]]]]}}previa(){const e=this.cursor;switch(this.ferramenta){case"retangulo":return this.pontos.length===1&&e?this.retangulo(this.pontos[0],e):null;case"circulo":{if(this.pontos.length!==1||!e)return null;const t=m.distanciaMetros(this.pontos[0],e);return t>=bt?{tipo:"Circle",centro:this.pontos[0],raioMetros:t}:null}case"caneta":{if(this.ancoras.length===0)return null;const t=ve(e?[...this.ancoras,{ponto:e}]:this.ancoras);return t.length<2?null:nt(t,this.ehArea&&t.length>=3)}case"elipse":case"poligono-regular":case"estrela":{if(this.pontos.length!==1||!e)return null;const t=oo[this.ferramenta](this.pontos[0],e);return t?{tipo:"Polygon",aneis:[t]}:null}case"ponto":case"texto":case"conta-gotas":return null;default:{const t=e?[...this.pontos,e]:[...this.pontos];return t.length<2?null:this.ehArea&&t.length>=3?{tipo:"Polygon",aneis:[t]}:{tipo:"LineString",coordenadas:t}}}}concluir(){if(!this.podeConcluir)return null;if(this.ferramenta==="caneta")return nt(ve(this.ancoras),this.ehArea);const e=this.vertices();return this.ehArea?{tipo:"Polygon",aneis:[e]}:{tipo:"LineString",coordenadas:e}}concluirFechando(){return this.fechaNoPrimeiro?this.ferramenta==="caneta"?nt(ve(this.ancoras),!0):{tipo:"Polygon",aneis:[this.vertices()]}:null}comprimentoMetros(){const e=this.cursor&&this.nos>0?[...this.vertices(),this.cursor]:this.vertices();return m.comprimentoMetros(e,!1)}}const Pi={topo:0,base:16,esquerda:0,direita:0},Ci=16,Li=.92,Ne={topo:"--cad-hud-topo",base:"--cad-hud-base",esquerda:"--cad-hud-esquerda",direita:"--cad-hud-direita"},qt="position:absolute;box-sizing:border-box;z-index:10000;left:calc(var(--cad-hud-esquerda,0px) + (100% - var(--cad-hud-esquerda,0px) - var(--cad-hud-direita,0px)) / 2);bottom:var(--cad-hud-base,16px);transform:translateX(-50%);width:max-content;max-width:min(92%, calc(100% - var(--cad-hud-esquerda,0px) - var(--cad-hud-direita,0px) - 16px));max-height:calc(100% - var(--cad-hud-topo,0px) - var(--cad-hud-base,16px) - 8px);overflow:hidden;display:flex;flex-wrap:wrap;";function Pn(a,e,t={}){const o={...Pi,...t},i=Math.max(0,a-o.esquerda-o.direita);return{centroX:o.esquerda+i/2,base:o.base,larguraMax:Math.max(0,Math.min(a*Li,i-Ci)),alturaMax:Math.max(0,e-o.topo-o.base-8)}}function Si(a,e){for(const t of Object.keys(Ne)){const o=e[t];typeof o=="number"&&Number.isFinite(o)&&o>=0?a.style.setProperty(Ne[t],`${o}px`):a.style.removeProperty(Ne[t])}}const Mi="cm-draw-hud",xt="cad-ferramenta-ativa",J="cad-desenho",oe="#22d3ee",Cn=4,Ln=450,Sn=10,Mn={ponto:"Ponto",linha:"Linha",poligono:"Polígono",retangulo:"Retângulo",elipse:"Elipse","poligono-regular":"Polígono regular (hexágono)",estrela:"Estrela",circulo:"Círculo",texto:"Texto",caneta:"Caneta (Bézier)","medir-distancia":"Medir distância","medir-area":"Medir área",dividir:"Dividir polígono","selecao-laco":"Seleção por laço","conta-gotas":"Conta-gotas"},An={ponto:"Clique para colocar",linha:"Clique nos vértices · Enter ou duplo clique conclui",poligono:"Clique nos vértices · Enter ou duplo clique conclui",retangulo:"Clique nos dois cantos",elipse:"Clique no centro e depois no canto da caixa","poligono-regular":"Clique no centro e depois num vértice",estrela:"Clique no centro e depois numa ponta",circulo:"Clique no centro e depois num ponto da borda",texto:"Clique onde o texto vai",caneta:"Clique e arraste para curvar · Enter conclui · 1º ponto fecha","medir-distancia":"Clique nos pontos · Enter conclui","medir-area":"Clique nos vértices · Enter conclui",dividir:"Desenhe a linha de corte · Enter aplica","selecao-laco":"Desenhe o laço · Enter ou 1º ponto fecha e seleciona","conta-gotas":"Clique numa feição para copiar o estilo"};class Ai{constructor(e){f(this,"sessao",null);f(this,"fechar",!1);f(this,"grupo",null);f(this,"previa",null);f(this,"marcas",null);f(this,"medicao",null);f(this,"marcadorSnap",null);f(this,"hud",null);f(this,"campoTexto",null);f(this,"arrastando",!1);f(this,"ultimoClique",null);f(this,"aoClicar",e=>{var n;const t=this.sessao;if(!t||t.ferramenta==="caneta"||this.campoTexto||((n=e.originalEvent)==null?void 0:n.button)!==void 0&&e.originalEvent.button!==0)return;const o=this.coordenada(e);if(t.ferramenta==="conta-gotas"){this.dep.aoAmostrar(o,e.originalEvent);return}if(t.ehSequencial&&this.repetido(e)||this.fechaNoPrimeiroVertice(e))return;const i=t.clicar(o);if(i.concluida){i.concluida.tipo==="Text"?this.pedirTexto(o):this.finalizar(i.concluida);return}this.atualizar()});f(this,"aoPressionar",e=>{var o;const t=this.sessao;!t||t.ferramenta!=="caneta"||((o=e.originalEvent)==null?void 0:o.button)!==0||this.repetido(e)||this.fechaNoPrimeiroVertice(e)||(t.clicar(this.coordenada(e)),this.arrastando=!0,this.atualizar())});f(this,"aoSoltar",()=>{this.arrastando=!1});f(this,"aoMover",e=>{const t=this.sessao;if(!t)return;const o=this.coordenada(e);t.mover(o),this.arrastando&&t.definirAlca(o),this.atualizar()});f(this,"aoDuploClique",()=>{this.concluir()});f(this,"aoTecla",e=>{const t=this.sessao;if(!t)return;const o=Lt(e);if(e.key==="Escape"){if(o&&!this.campoTexto)return;this.campoTexto?this.cancelarTexto():t.nos>0?this.reiniciar():this.desativar(),e.preventDefault();return}o||(e.key==="Enter"?(this.concluir(),e.preventDefault()):(e.key==="Backspace"||(e.ctrlKey||e.metaKey)&&e.key.toLowerCase()==="z")&&(t.desfazer()&&this.atualizar(),e.preventDefault()))});this.dep=e}get ferramenta(){var e;return((e=this.sessao)==null?void 0:e.ferramenta)??null}get ativo(){return this.sessao!==null}get nos(){var e;return((e=this.sessao)==null?void 0:e.nos)??0}desfazerVertice(){var e;return(e=this.sessao)!=null&&e.desfazer()?(this.atualizar(),!0):!1}ativar(e,t={}){var r;const o=(r=this.sessao)==null?void 0:r.ferramenta;this.desligar(),o&&this.dep.aoDesativar(o),this.limparMedicao();const i=this.dep.map;this.fechar=!!t.fechar,this.sessao=new $e(e,this.fechar),i.getPane(J)||(i.createPane(J).style.zIndex="8500"),this.grupo=b.layerGroup().addTo(i),this.marcas=b.layerGroup().addTo(this.grupo);const n=i.getContainer();n.classList.add(xt),n.style.cursor=e==="conta-gotas"?"copy":"crosshair",i.on("click",this.aoClicar),i.on("dblclick",this.aoDuploClique),i.on("mousemove",this.aoMover),i.on("mousedown",this.aoPressionar),i.on("mouseup",this.aoSoltar),window.addEventListener("keydown",this.aoTecla),this.montarHud(),this.atualizar()}desativar(){var t;const e=(t=this.sessao)==null?void 0:t.ferramenta;e&&(this.desligar(),this.dep.aoDesativar(e))}limparMedicao(){var e;(e=this.medicao)==null||e.remove(),this.medicao=null}desligar(){var o,i;const e=this.dep.map;e.off("click",this.aoClicar),e.off("dblclick",this.aoDuploClique),e.off("mousemove",this.aoMover),e.off("mousedown",this.aoPressionar),e.off("mouseup",this.aoSoltar),window.removeEventListener("keydown",this.aoTecla);const t=e.getContainer();t.classList.remove(xt),t.style.cursor="",(o=this.grupo)==null||o.remove(),this.grupo=null,this.previa=null,this.marcas=null,this.marcadorSnap=null,(i=this.hud)==null||i.remove(),this.hud=null,this.campoTexto=null,this.sessao=null,this.arrastando=!1,this.ultimoClique=null}coordenada(e){const t=[e.latlng.lat,e.latlng.lng];if(!this.dep.snapAtivo())return this.esconderSnap(),t;const o=this.dep.buscarSnap(t);return o?(this.mostrarSnap(o.coordenada),o.coordenada):(this.esconderSnap(),t)}repetido(e){const t=this.ultimoClique,o=Date.now(),i=e.containerPoint,n=!!t&&Math.hypot(t.x-i.x,t.y-i.y)<=Cn&&o-t.t<=Ln;return this.ultimoClique={x:i.x,y:i.y,t:o},n}fechaNoPrimeiroVertice(e){const t=this.sessao,o=t==null?void 0:t.primeiro;if(!t||!o||!t.fechaNoPrimeiro)return!1;const i=this.dep.map.latLngToContainerPoint(o);if(Math.hypot(i.x-e.containerPoint.x,i.y-e.containerPoint.y)>Sn)return!1;const n=t.concluirFechando();return n&&this.finalizar(n),!!n}concluir(){const e=this.sessao;if(!e)return;const t=e.concluir();t&&this.finalizar(t)}botaoDireito(){const e=this.sessao;if(e){if(this.campoTexto){this.cancelarTexto();return}e.podeConcluir?this.concluir():e.nos>0&&e.desfazer()?this.atualizar():this.desativar()}}reiniciar(){var t;const e=(t=this.sessao)==null?void 0:t.ferramenta;e&&(this.sessao=new $e(e,this.fechar),this.ultimoClique=null,this.arrastando=!1,this.atualizar())}finalizar(e){const t=this.sessao.ferramenta,o=t==="medir-distancia"||t==="medir-area"?this.mostrarMedicao(e,t):null;this.sessao=new $e(t,this.fechar),this.ultimoClique=null,this.atualizar(),o&&this.dep.aoMedir(o),this.dep.aoGeometria(t,e)}pedirTexto(e){var o,i;if(!this.hud||(i=(o=this.dep).aoSolicitarTexto)!=null&&i.call(o,e)||!this.hud)return;const t=document.createElement("input");t.type="text",t.placeholder="Texto…",t.style.cssText="padding:3px 6px;border-radius:4px;border:1px solid #475569;background:#0f172a;color:#fff;min-width:160px",t.addEventListener("keydown",n=>{if(n.stopPropagation(),n.key==="Enter"){const r=t.value.trim();this.cancelarTexto(),r&&this.finalizar({tipo:"Text",coordenada:e,texto:r})}else n.key==="Escape"&&this.cancelarTexto()}),this.campoTexto=t,this.hud.insertBefore(t,this.hud.querySelector('[data-campo="dica"]')),t.focus()}cancelarTexto(){var e;(e=this.campoTexto)==null||e.remove(),this.campoTexto=null}atualizar(){const e=this.sessao;if(!e||!this.grupo||!this.marcas)return;this.previa&&(this.grupo.removeLayer(this.previa),this.previa=null);const t=e.previa();t&&(this.previa=this.desenharGeometria(t,!0),this.grupo.addLayer(this.previa)),this.marcas.clearLayers();const o=e.ferramenta==="caneta"?e.ancoras.map(i=>i.ponto):e.pontos;if(e.ferramenta==="caneta")for(const i of e.ancoras){if(!i.alca)continue;const n=m.espelhoDaAlca(i.ponto,i.alca);this.marcas.addLayer(b.polyline([n,i.alca],{pane:J,color:oe,weight:1,opacity:.8,interactive:!1}));for(const r of[n,i.alca])this.marcas.addLayer(b.circleMarker(r,{pane:J,radius:3,color:oe,weight:1,fillColor:"#fff",fillOpacity:1,interactive:!1}))}for(const i of o)this.marcas.addLayer(b.circleMarker(i,{pane:J,radius:4,color:"#111",weight:1,fillColor:oe,fillOpacity:1,interactive:!1}));this.atualizarHud(t)}desenharGeometria(e,t){const o={pane:J,color:oe,weight:2,dashArray:t?"6 4":void 0,fillColor:oe,fillOpacity:.15,interactive:!1},i=Et(e,o);if(i)return i;if(e.tipo==="Polygon")return b.polygon(e.aneis,o);if(e.tipo==="Circle")return b.circle(e.centro,{...o,radius:e.raioMetros});if(e.tipo==="LineString")return b.polyline(e.coordenadas,o);const n=(e.tipo==="Point",e.coordenada);return b.circleMarker(n,{...o,radius:5})}mostrarMedicao(e,t){this.limparMedicao();const o=b.layerGroup().addTo(this.dep.map);this.medicao=o,o.addLayer(this.desenharGeometria(e,!1));const i=e.tipo==="Polygon"?e.aneis[0]:e.tipo==="LineString"?e.coordenadas:[],n=e.tipo==="Polygon",r=(l,d)=>{const h=document.createElement("div");h.textContent=d,h.style.cssText="white-space:nowrap;font:600 11px sans-serif;color:#fff;background:rgba(15,23,42,.85);padding:1px 5px;border-radius:3px;transform:translate(-50%,-50%)",o.addLayer(b.marker(l,{pane:J,interactive:!1,keyboard:!1,icon:b.divIcon({className:"custom-leaflet-marker",iconSize:void 0,html:h})}))},s=n?i.length:i.length-1;for(let l=0;l<s;l++){const d=i[l],h=i[(l+1)%i.length];r([(d[0]+h[0])/2,(d[1]+h[1])/2],m.formatarExtensao(m.distanciaMetros(d,h)))}const c={tipo:t==="medir-area"?"area":"distancia",pontos:i,comprimentoM:m.comprimentoMetros(i,!1)};if(e.tipo==="Polygon")c.areaM2=m.areaDaGeometria(e)??0,c.perimetroM=m.extensaoDaGeometria(e)??0;else if(t==="medir-distancia"&&i.length>=3){const l={tipo:"Polygon",aneis:[i]};c.areaM2=m.areaDaGeometria(l)??0,c.perimetroM=m.extensaoDaGeometria(l)??0}return c}mostrarSnap(e){this.grupo&&(this.marcadorSnap?this.marcadorSnap.setLatLng(e):this.marcadorSnap=b.marker(e,{pane:J,interactive:!1,keyboard:!1,icon:b.divIcon({className:"custom-leaflet-marker cm-snap",iconSize:[18,18],html:'<div style="width:18px;height:18px;box-sizing:border-box;border:2px solid #22d3ee;transform:rotate(45deg);border-radius:2px"></div>'})}).addTo(this.grupo))}esconderSnap(){var e;this.marcadorSnap&&((e=this.grupo)==null||e.removeLayer(this.marcadorSnap),this.marcadorSnap=null)}montarHud(){const e=this.sessao;if(!e)return;const t=document.createElement("div");t.id=Mi,t.style.cssText=qt+"gap:10px;align-items:center;padding:6px 12px;border-radius:8px;background:rgba(15,23,42,.92);color:#fff;font:12px var(--ui-fonte-base,sans-serif);border:1px solid rgba(255,255,255,.2);pointer-events:auto";const o=s=>{const c=document.createElement("span");return c.dataset.campo=s,c},i=document.createElement("strong");i.textContent=Mn[e.ferramenta];const n=o("dica");n.style.opacity=".7",n.textContent=An[e.ferramenta];const r=(s,c,l=!1)=>{const d=document.createElement("button");return d.type="button",d.textContent=s,d.style.cssText=`padding:3px 10px;border-radius:4px;border:1px solid ${l?oe:"rgba(255,255,255,.3)"};background:${l?oe:"transparent"};color:${l?"#111":"#fff"};cursor:pointer;font-weight:600`,d.addEventListener("click",c),d};t.append(i,o("nos"),o("medida"),n),e.ehSequencial&&t.append(r("Concluir",()=>this.concluir(),!0)),t.append(r("Sair",()=>this.desativar())),b.DomEvent.disableClickPropagation(t),b.DomEvent.disableScrollPropagation(t),this.dep.map.getContainer().appendChild(t),this.hud=t}atualizarHud(e){const t=this.sessao;if(!this.hud||!t)return;const o=this.hud.querySelector('[data-campo="nos"]'),i=this.hud.querySelector('[data-campo="medida"]');if(o&&(o.textContent=t.nos>0?`Nós: ${t.nos}`:""),!i)return;let n="";if((e==null?void 0:e.tipo)==="Polygon")n=`Área: ${m.formatarArea(m.areaDaGeometria(e)??0)} · Perímetro: ${m.formatarExtensao(m.extensaoDaGeometria(e)??0)}`;else if((e==null?void 0:e.tipo)==="LineString"){if(n=`Extensão: ${m.formatarExtensao(t.comprimentoMetros())}`,t.ferramenta==="medir-distancia"&&t.nos>=3&&e.coordenadas.length>=3){const r={tipo:"Polygon",aneis:[e.coordenadas]};n+=` · Área: ${m.formatarArea(m.areaDaGeometria(r)??0)} · Perímetro: ${m.formatarExtensao(m.extensaoDaGeometria(r)??0)}`}}else(e==null?void 0:e.tipo)==="Circle"&&(n=`Raio: ${m.formatarExtensao(e.raioMetros)}`);i.textContent=n}clicarEm(e){const t=this.sessao;if(!t)return;const o=t.clicar(e);o.concluida?o.concluida.tipo==="Text"?this.pedirTexto(e):this.finalizar(o.concluida):this.atualizar()}moverPara(e){var t;(t=this.sessao)==null||t.mover(e),this.atualizar()}}const wn=new Set(["ponto","linha","poligono","retangulo","elipse","poligono-regular","estrela","circulo","texto","caneta"]);class En{constructor(e){f(this,"desenho",null);f(this,"camadaDesenho",null);f(this,"estiloDesenho",{});f(this,"sequenciaId",0);this.p=e}get controle(){return this.desenho}get ativo(){var e;return!!((e=this.desenho)!=null&&e.ativo)}botaoDireito(){var e;(e=this.desenho)==null||e.botaoDireito()}destruir(){var e;(e=this.desenho)==null||e.desativar(),this.desenho=null}get ferramentaAtiva(){var e;return((e=this.desenho)==null?void 0:e.ferramenta)??null}definirCamadaDesenho(e){this.camadaDesenho=e||null}get camadaDeDesenho(){return this.camadaDesenho}definirEstiloDesenho(e){this.estiloDesenho={...e}}obterEstiloDesenho(){return{...this.estiloDesenho}}alternarFerramenta(e){var t;return((t=this.desenho)==null?void 0:t.ferramenta)===e?(this.desenho.desativar(),{ok:!0}):this.ativarFerramenta(e)}ativarFerramenta(e,t={}){var n,r;if(!Ft(e))return{ok:!1,motivo:"ferramenta-invalida"};const o=this.p.obterMapa();if(!o)return{ok:!1,motivo:"sem-mapa"};if(wn.has(e)){const s=this.motivoCamadaDesenhoInvalida();if(s)return this.p.emitir("cad-desenho-recusado",{ferramenta:e,motivo:s}),{ok:!1,motivo:s}}this.p.prepararDesenho(),this.desenho||(this.desenho=new Ai({map:o,buscarSnap:s=>this.p.buscarSnapEm(s),snapAtivo:()=>this.p.snapAtivo(),aoGeometria:(s,c)=>this.concluirFerramenta(s,c),aoMedir:s=>this.p.emitir("cad-medicao",s),aoAmostrar:s=>this.amostrarEstilo(s),aoSolicitarTexto:s=>this.solicitarTexto(s),aoDesativar:()=>{var s,c;this.p.emitir("cad-ferramenta",{ferramenta:null}),(c=(s=this.p).aoFerramenta)==null||c.call(s,null)}})),this.desenho.ativar(e,t),this.p.emitir("cad-ferramenta",{ferramenta:e}),(r=(n=this.p).aoFerramenta)==null||r.call(n,e);const i=t.iniciarEm?this.p.normalizarCoordenada(t.iniciarEm):null;return i&&this.desenho.clicarEm(i),{ok:!0}}desativarFerramenta(){var e;(e=this.desenho)==null||e.desativar()}limparMedicao(){var e;(e=this.desenho)==null||e.limparMedicao()}get nosDesenho(){var e;return((e=this.desenho)==null?void 0:e.nos)??0}desfazerVerticeDesenho(){var e;return((e=this.desenho)==null?void 0:e.desfazerVertice())??!1}motivoCamadaDesenhoInvalida(){if(!this.camadaDesenho)return"sem-camada";const e=this.p.obterLayerManager().getLayerDef(this.camadaDesenho);return e&&e.tipo!==G?"camada-invalida":e!=null&&e.bloqueada?"camada-bloqueada":null}novoId(e,t){const o=new Set(this.p.lista(t).map(n=>n.id));let i;do this.sequenciaId++,i=`${e}-${Date.now().toString(36)}${this.sequenciaId.toString(36)}`;while(o.has(i));return i}solicitarTexto(e){const t={coordenada:e,camadaId:this.camadaDesenho,concluir:o=>{const i=typeof o=="string"?o.trim():"";return i?this.concluirFerramenta("texto",{tipo:"Text",coordenada:e,texto:i}):null}};return this.p.emitir("cad-texto-solicitado",t,!0)===!0}concluirFerramenta(e,t){if(e==="dividir")return t.tipo==="LineString"&&this.p.dividirComLinha(t.coordenadas),null;if(e==="medir-distancia"||e==="medir-area")return null;if(e==="selecao-laco")return t.tipo==="Polygon"&&this.p.selecionarNoLaco(t.aneis[0]),null;const o=this.camadaDesenho;if(!o)return null;const i=Object.keys(this.estiloDesenho).length>0,n=this.p.adicionarFeicao(o,{id:this.novoId(e,o),geometria:t,estilo:i?{...this.estiloDesenho}:void 0,propriedades:{}});return n?this.p.emitir("cad-feicao-criada",{camadaId:o,feicao:n}):this.p.emitir("cad-desenho-recusado",{ferramenta:e,motivo:"geometria-invalida"}),n}amostrarEstilo(e){const t=this.p.obterMapa();if(!t)return;const o=t.latLngToContainerPoint(e),i=this.p.candidatasEm(e,8),n=Le({x:o.x,y:o.y},i,d=>t.latLngToContainerPoint(d));if(!n){this.p.emitir("cad-conta-gotas",{cor:"",feicao:null,estilo:{}});return}const r=this.p.obterLayerManager().getLayerDef(n.camadaId),s=n.estilo??{},c={},l=s.corTraco??(r==null?void 0:r.estilo.corPrimaria);l&&(c.corTraco=l),s.corPreenchimento&&(c.corPreenchimento=s.corPreenchimento),s.espessuraTraco!==void 0&&(c.espessuraTraco=s.espessuraTraco),s.opacidadePreenchimento!==void 0&&(c.opacidadePreenchimento=s.opacidadePreenchimento),s.dashArray&&(c.dashArray=s.dashArray),this.estiloDesenho={...this.estiloDesenho,...c},this.p.emitir("cad-conta-gotas",{cor:l??s.corPreenchimento??"",feicao:n,estilo:c})}}class zn{constructor(e){f(this,"posicoes",new Map);this.p=e}lista(e){var o;const t=(o=this.p.obterLayerManager().getLayerDef(e))==null?void 0:o.dados;return Array.isArray(t==null?void 0:t.feicoes)?t.feicoes:[]}posicaoDe(e){const t=this.lista(e),o=this.posicoes.get(e);if(o&&o.lista===t)return o.pos;const i=new Map;for(let n=0;n<t.length;n++)i.set(t[n].id,n);return this.posicoes.set(e,{lista:t,pos:i}),i}buscar(e,t){const o=this.lista(e),i=this.posicaoDe(e).get(t),n=i===void 0?void 0:o[i];if(n&&n.id===t)return n;if(i===void 0)return;this.posicoes.delete(e);const r=this.posicaoDe(e).get(t);return r===void 0?void 0:o[r]}garantirCamada(e,t){const o=this.p.obterLayerManager(),i=o.getLayerDef(e);if(i&&i.tipo!==G)return!1;const n=o.getOrCreateLayer(e,G,(t==null?void 0:t.nome)??e);return t!=null&&t.nome&&(n.nome=t.nome),t!=null&&t.estilo&&(n.estilo={...n.estilo,...t.estilo}),(t==null?void 0:t.interativo)!==void 0&&(n.interativo=t.interativo),(t==null?void 0:t.zIndex)!==void 0&&o.setLayerZIndex(e,t.zIndex),(t==null?void 0:t.opacidade)!==void 0&&o.setLayerOpacity(e,t.opacidade),o.ensurePanes(),!0}definirFeicoes(e,t,o){if(!this.garantirCamada(e,o))return{aceitas:0,recusadas:["camada existente não é de feições"]};const i=[],n=new Map;return(Array.isArray(t)?t:[]).forEach((r,s)=>{const c=Oe(r,e,this.p.opcoesNormalizacao());c?n.set(c.id,c):i.push(String((r==null?void 0:r.id)??`#${s}`))}),this.p.obterLayerManager().setLayerData(e,{feicoes:[...n.values()]}),this.p.aposDados(),{aceitas:n.size,recusadas:i}}adicionarFeicao(e,t,o){return this.aplicar(e,{adicionar:[t]},o).adicionadas[0]??null}atualizarFeicao(e,t,o,i){return this.aplicar(e,{atualizar:[{...o,id:t}]},i).atualizadas[0]??null}substituir(e,t){this.p.obterLayerManager().getLayerDef(e)&&this.aplicar(e,{adicionar:[t]})}removerFeicao(e,t){return this.aplicar(e,{remover:[t]}).resultado.removidas>0}aplicarLote(e,t,o){return this.aplicar(e,t,o).resultado}mesclar(e,t,o,i){const n=i&&t.propriedades&&typeof t.propriedades=="object"?{...t.propriedades}:{...e.propriedades,...t.propriedades};return Oe({...e,...t,id:e.id,estilo:{...e.estilo,...t.estilo},propriedades:n},o,this.p.opcoesNormalizacao())}aplicar(e,t,o={}){const i={adicionadas:0,atualizadas:0,removidas:0,recusadas:[]},n=[],r=[],s=Array.isArray(t==null?void 0:t.adicionar)?t.adicionar:[],c=Array.isArray(t==null?void 0:t.atualizar)?t.atualizar:[],l=Array.isArray(t==null?void 0:t.remover)?t.remover:[],d=(S,E)=>String((S==null?void 0:S.id)??`#${E}`),h=[],u=S=>(i.recusadas.push(...h),S),g=[];s.forEach((S,E)=>{const D=Oe(S,e,this.p.opcoesNormalizacao());D?g.push(D):h.push(d(S,E))});const v=this.p.obterLayerManager(),p=v.getLayerDef(e);if(!(!p||p.tipo===G)||!p&&g.length===0)return c.forEach((S,E)=>i.recusadas.push(d(S,E))),g.forEach(S=>h.push(S.id)),u({resultado:i,adicionadas:n,atualizadas:r});if((g.length>0||p)&&!this.garantirCamada(e,o))return g.forEach(S=>h.push(S.id)),u({resultado:i,adicionadas:n,atualizadas:r});const A=this.lista(e),w=this.posicaoDe(e),x=A.slice(),k=[],C=[];let L=!1;for(const S of l){const E=String(S),D=w.get(E);D===void 0||x[D]===null||(x[D]=null,k.push(E),i.removidas++,L=!0)}c.forEach((S,E)=>{const D=S&&typeof S=="object"&&S.id!==void 0&&S.id!==null?String(S.id):"",_=w.get(D),R=_===void 0?null:x[_],O=R?this.mesclar(R,S,e,!!o.substituirPropriedades):null;if(!O||_===void 0){i.recusadas.push(D||d(S,E));return}x[_]=O,C.push(O),r.push(O),i.atualizadas++});for(const S of g){const E=w.get(S.id);E!==void 0&&x[E]!==null?x[E]=S:(w.set(S.id,x.length),x.push(S)),C.push(S),n.push(S),i.adicionadas++}if(C.length===0&&k.length===0)return u({resultado:i,adicionadas:n,atualizadas:r});const P=L?x.filter(S=>S!==null):x,I={feicoes:P,delta:{base:A,mudadas:C,removidas:k}};return v.setLayerData(e,I),delete I.delta,L?this.posicoes.delete(e):this.posicoes.set(e,{lista:P,pos:w}),this.p.aposDados(),u({resultado:i,adicionadas:n,atualizadas:r})}}const wi="cm-vertex-edit-hud",ie="cad-edicao-vertices",io="#facc15",ao="#f472b6";class Ei{constructor(e){f(this,"feicaoAtual",null);f(this,"pts",[]);f(this,"alcas",[]);f(this,"fantasmas",[]);f(this,"alcasBezier",[]);f(this,"marcadorSnap",null);f(this,"hud",null);f(this,"grupo",null);this.dep=e}get ativo(){return this.feicaoAtual!==null}get ehCirculo(){var e;return((e=this.feicaoAtual)==null?void 0:e.geometria.tipo)==="Circle"}get feicao(){return this.feicaoAtual}iniciar(e){this.parar(),this.feicaoAtual=e,this.pts=me(e.geometria).map(o=>[o[0],o[1]]);const t=this.dep.map;if(!t.getPane(ie)){const o=t.createPane(ie);o.style.zIndex="9000"}this.grupo=b.layerGroup().addTo(t),this.montarHud(),this.reconstruir()}parar(){var t,o;const e=this.feicaoAtual;e&&(this.feicaoAtual=null,this.alcas=[],this.fantasmas=[],this.alcasBezier=[],(t=this.grupo)==null||t.remove(),this.grupo=null,this.marcadorSnap=null,(o=this.hud)==null||o.remove(),this.hud=null,this.dep.aoEncerrar(e))}sincronizar(e){!this.feicaoAtual||this.feicaoAtual.id!==e.id||(this.feicaoAtual=e,this.pts=me(e.geometria).map(t=>[t[0],t[1]]),this.reconstruir())}atualizarSnapNoHud(){var t;const e=(t=this.hud)==null?void 0:t.querySelector('[data-campo="snap"]');e&&(e.textContent=`Snap: ${this.dep.snapLigado()?"ligado":"desligado"} (S)`)}geometriaAtual(){return Go(this.feicaoAtual.geometria,this.pts)}feicaoComPontos(){return{...this.feicaoAtual,geometria:this.geometriaAtual()}}reconstruir(){var t;if((t=this.grupo)==null||t.clearLayers(),this.alcas=[],this.fantasmas=[],this.alcasBezier=[],!this.feicaoAtual||!this.grupo)return;const e=this.feicaoAtual.geometria;if(this.pts.forEach((o,i)=>{const n=this.criarAlca(o,i);this.alcas.push(n),this.grupo.addLayer(n)}),this.criarAlcasBezier(),e.tipo!=="Point")for(const[o,i]of jo(this.geometriaAtual())){const n=this.criarFantasma(o,i);this.fantasmas.push(n),this.grupo.addLayer(n.marker)}this.atualizarHud()}icone(e,t,o){return b.divIcon({className:`custom-leaflet-marker ${e}`,iconSize:[t,t],html:`<div style="width:${t}px;height:${t}px;box-sizing:border-box;${o}"></div>`})}criarAlca(e,t){const o=b.marker(e,{icon:this.icone("cad-vertex-handle",12,`background:${io};border:2px solid #111;border-radius:${this.ehCirculo&&t===1?"50%":"2px"};cursor:${this.ehCirculo&&t===1?"ew-resize":"move"}`),draggable:!0,pane:ie,keyboard:!1});return o.on("drag",()=>this.aoArrastar(o,t)),o.on("dragend",()=>{this.esconderSnap(),this.confirmar(this.feicaoComPontos())}),o.on("contextmenu",i=>{b.DomEvent.preventDefault(i.originalEvent),b.DomEvent.stopPropagation(i.originalEvent),this.excluir(t)}),o.on("dblclick",i=>{b.DomEvent.stopPropagation(i.originalEvent),this.alternarSuave(t)}),o}criarAlcasBezier(){const e=this.feicaoAtual&&W(this.feicaoAtual.geometria);e&&e.forEach((t,o)=>this.completarAlcasDoNo(o))}completarAlcasDoNo(e){var o;const t=this.feicaoAtual&&((o=W(this.feicaoAtual.geometria))==null?void 0:o[e]);if(!(!t||!this.grupo))for(const i of["entrada","saida"]){const n=t[i];if(!n||this.alcasBezier.some(l=>l.i===e&&l.qual===i))continue;const r=b.polyline([t.ponto,n],{pane:ie,color:ao,weight:1,opacity:.8,interactive:!1}),s=b.marker(n,{icon:this.icone("cad-bezier-handle",10,`background:#fff;border:2px solid ${ao};border-radius:50%;cursor:move`),draggable:!0,pane:ie,keyboard:!1}),c={marker:s,haste:r,i:e,qual:i};s.on("drag",l=>{const d=l.originalEvent;this.aoArrastarAlca(c,!(d!=null&&d.shiftKey))}),s.on("dragend",()=>this.confirmar(this.feicaoAtual)),this.alcasBezier.push(c),this.grupo.addLayer(r),this.grupo.addLayer(s)}}sincronizarAlcasBezier(){var t;const e=this.feicaoAtual&&W(this.feicaoAtual.geometria);if(e)for(const o of this.alcasBezier){const i=(t=e[o.i])==null?void 0:t[o.qual];i&&((o.marker.getLatLng().lat!==i[0]||o.marker.getLatLng().lng!==i[1])&&o.marker.setLatLng(i),o.haste.setLatLngs([e[o.i].ponto,i]))}}aoArrastarAlca(e,t){const o=this.feicaoAtual;if(!o)return;const{lat:i,lng:n}=e.marker.getLatLng(),r=Xo(o.geometria,e.i,e.qual,[i,n],t);this.feicaoAtual={...o,geometria:r},this.completarAlcasDoNo(e.i),this.sincronizarAlcasBezier(),this.dep.previsualizar(this.feicaoAtual),this.atualizarHud()}alternarSuave(e){const t=this.feicaoAtual;if(!t)return;const o=Yo(t.geometria,e);o!==t.geometria&&(this.feicaoAtual={...t,geometria:o},this.reconstruir(),this.dep.previsualizar(this.feicaoAtual),this.confirmar(this.feicaoAtual))}criarFantasma(e,t){const o=b.marker(_e(this.geometriaAtual(),e,t),{icon:this.icone("cad-vertex-ghost",9,`background:${io};opacity:.45;border:1px solid #111;border-radius:50%;cursor:copy`),pane:ie,keyboard:!1});return o.on("click",i=>{b.DomEvent.stopPropagation(i.originalEvent),this.inserir(e,o.getLatLng())}),{marker:o,i:e,j:t}}aoArrastar(e,t){var r;const o=this.feicaoAtual;if(!o)return;let i=[e.getLatLng().lat,e.getLatLng().lng];const n=this.dep.snapLigado()?this.dep.buscarSnap(i,{feicaoId:o.id,camadaId:o.camadaId,vertice:t}):null;if(n?(i=n.coordenada,e.setLatLng(i),this.mostrarSnap(i)):this.esconderSnap(),o.geometria.tipo==="Circle"&&t===0){const s=i[0]-this.pts[0][0],c=i[1]-this.pts[0][1];this.pts[1]=[this.pts[1][0]+s,this.pts[1][1]+c],(r=this.alcas[1])==null||r.setLatLng(this.pts[1])}this.pts[t]=i;for(const s of this.fantasmas)(s.i===t||s.j===t)&&s.marker.setLatLng(_e(this.geometriaAtual(),s.i,s.j));this.dep.previsualizar(this.feicaoComPontos()),this.atualizarAlcasDoNo(t),this.atualizarHud()}atualizarAlcasDoNo(e){const t=W(this.geometriaAtual());if(t)for(const o of this.alcasBezier){if(o.i!==e)continue;const i=t[e][o.qual];i&&(o.marker.setLatLng(i),o.haste.setLatLngs([t[e].ponto,i]))}}inserir(e,t){if(!this.feicaoAtual)return;const i=Uo(this.geometriaAtual(),e,[t.lat,t.lng]);this.pts=me(i).map(r=>[r[0],r[1]]),this.reconstruir();const n=this.feicaoComPontos();this.dep.previsualizar(n),this.confirmar(n)}confirmar(e){this.feicaoAtual=e,this.dep.aoGesto(e)}excluir(e){if(!this.feicaoAtual)return;const o=Wo(this.geometriaAtual(),e);if(!o)return;this.pts=me(o).map(n=>[n[0],n[1]]),this.reconstruir();const i=this.feicaoComPontos();this.dep.previsualizar(i),this.confirmar(i)}excluirVertice(e){const t=this.pts.length;return this.excluir(e),this.pts.length<t}inserirVerticeApos(e){if(e<0||e>=this.pts.length)return;const t=(e+1)%this.pts.length,o=_e(this.geometriaAtual(),e,t);this.inserir(e,b.latLng(o[0],o[1]))}mostrarSnap(e){this.grupo&&(this.marcadorSnap?this.marcadorSnap.setLatLng(e):this.marcadorSnap=b.marker(e,{icon:b.divIcon({className:"custom-leaflet-marker cm-snap",iconSize:[18,18],html:'<div style="width:18px;height:18px;box-sizing:border-box;border:2px solid #22d3ee;transform:rotate(45deg);border-radius:2px"></div>'}),interactive:!1,pane:ie,keyboard:!1}).addTo(this.grupo))}esconderSnap(){var e;this.marcadorSnap&&((e=this.grupo)==null||e.removeLayer(this.marcadorSnap),this.marcadorSnap=null)}montarHud(){const e=this.dep.map.getContainer(),t=document.createElement("div");t.id=wi,t.style.cssText=qt+"gap:12px;align-items:center;padding:6px 12px;border-radius:8px;background:rgba(15,23,42,.92);color:#fff;font:12px var(--ui-fonte-base,sans-serif);border:1px solid rgba(255,255,255,.2);pointer-events:auto";const o=c=>{const l=document.createElement("span");return l.dataset.campo=c,l},i=document.createElement("strong");i.textContent=this.ehCirculo?"Editando círculo":"Editando vértices";const n=o("snap");n.style.cursor="pointer",n.title="Alternar snap (S). Alt desliga temporariamente.",n.addEventListener("click",()=>this.dep.alternarSnap());const r=document.createElement("button");r.type="button",r.textContent="Concluir",r.style.cssText="padding:3px 10px;border-radius:4px;border:1px solid #facc15;background:#facc15;color:#111;font-weight:600;cursor:pointer",r.addEventListener("click",()=>this.parar());const s=o("dica");s.style.opacity=".7",s.textContent="Duplo clique no nó: curva ↔ canto · Alças: Shift solta a simetria",t.append(i,o("nos"),o("medida"),n,s,r),b.DomEvent.disableClickPropagation(t),b.DomEvent.disableScrollPropagation(t),e.appendChild(t),this.hud=t,this.atualizarSnapNoHud()}atualizarHud(){if(!this.hud||!this.feicaoAtual)return;const e=this.geometriaAtual(),t=this.hud.querySelector('[data-campo="nos"]'),o=this.hud.querySelector('[data-campo="medida"]');t&&(t.textContent=e.tipo==="Circle"?"Centro move · borda muda o raio":`Nós: ${this.pts.length} (mín. ${Pe(e)})`),o&&(e.tipo==="Polygon"?o.textContent=`Área: ${m.formatarArea(m.areaDaGeometria(e)??0)} · Perímetro: ${m.formatarExtensao(m.extensaoDaGeometria(e)??0)}`:e.tipo==="LineString"?o.textContent=`Extensão: ${m.formatarExtensao(m.extensaoDaGeometria(e)??0)}`:e.tipo==="Point"?o.textContent=`${e.coordenada[0].toFixed(6)}, ${e.coordenada[1].toFixed(6)}`:e.tipo==="Circle"&&(o.textContent=`Raio: ${m.formatarExtensao(e.raioMetros)} · Área: ${m.formatarArea(m.areaDaGeometria(e)??0)}`))}vertices(){return this.pts.map(e=>[e[0],e[1]])}get totalAlcasBezier(){return this.alcasBezier.length}arrastarAlcaPara(e,t,o,i=!1){const n=this.alcasBezier.find(r=>r.i===e&&r.qual===t);n&&(n.marker.setLatLng(o),this.aoArrastarAlca(n,!i),this.confirmar(this.feicaoAtual))}alternarSuavidadeDoNo(e){this.alternarSuave(e)}arrastarPara(e,t){const o=this.alcas[e];o&&(o.setLatLng(t),this.aoArrastar(o,e),o.fire("dragend"))}}class kn{constructor(e){f(this,"editor",null);this.p=e}get editando(){var e;return!!((e=this.editor)!=null&&e.ativo)}get editorAtual(){return this.editor}get feicao(){var e;return(e=this.editor)!=null&&e.ativo?this.editor.feicao:null}sincronizar(e){var t;(t=this.editor)==null||t.sincronizar(e)}atualizarSnapNoHud(){var e;(e=this.editor)==null||e.atualizarSnapNoHud()}iniciarEdicao(e,t){var d;const o=this.p.buscar(e,t);if(!o||o.excluida)return{ok:!1,motivo:"inexistente"};const i=this.p.obterLayerManager().getLayerDef(e),n=No(o,!!(i!=null&&i.bloqueada));if(n)return this.p.emitir("cad-edicao-recusada",{motivo:n,feicao:o}),{ok:!1,motivo:n};const r=this.p.obterMapa();if(!r)return{ok:!1,motivo:"sem-mapa"};this.p.desativarFerramenta(),(d=this.editor)==null||d.parar(),this.p.aplicarMargensHud(),this.p.selecionarUma({camadaId:e,id:t}),this.p.fecharPopup();const s=this.p.obterLayerManager(),c=N.get(G),l=new Ei({map:r,snapLigado:()=>this.p.snapAtivo(),alternarSnap:()=>this.p.alternarSnap(),buscarSnap:(h,u)=>this.p.buscarSnapEm(h,u),previsualizar:h=>{const u=s.getLayerInstance(h.camadaId);u&&c&&c.previsualizar(u,h)},aoGesto:h=>{this.p.substituir(h.camadaId,h),this.p.emitir("cad-feicao-atualizada",{camadaId:h.camadaId,feicao:h})},aoEncerrar:h=>{this.editor=null;const u=this.p.buscar(h.camadaId,h.id)??h;this.p.emitir("cad-edicao-concluida",{feicao:u}),this.p.reabrirPopupDaSelecao()}});return this.editor=l,l.iniciar(o),this.p.emitir("cad-edicao-iniciada",{feicao:o}),{ok:!0}}parar(){var e;(e=this.editor)==null||e.parar()}}const Ot=10,rt=(a,e)=>Math.hypot(a.x-e.x,a.y-e.y);function In(a,e,t){const o=t.x-e.x,i=t.y-e.y,n=o*o+i*i,r=n===0?0:Math.max(0,Math.min(1,((a.x-e.x)*o+(a.y-e.y)*i)/n));return{t:r,d:Math.hypot(a.x-(e.x+r*o),a.y-(e.y+r*i))}}function zi(a,e,t,o={},i){const n=o.toleranciaPx??Ot,r=o.vertice!==!1,s=o.meio!==!1,c=o.aresta!==!1;let l=null,d=null,h=null;const u=(g,v)=>!g||v.distanciaPx<g.distanciaPx?v:g;for(const g of e){if(g.excluida||g.oculta)continue;const v=!!i&&i.feicaoId===g.id&&(i.camadaId===void 0||i.camadaId===g.camadaId),p=g.geometria,y={feicaoId:g.id,camadaId:g.camadaId};if(p.tipo==="Point"||p.tipo==="Text"||p.tipo==="Circle"){if(!r||v)continue;const x=p.tipo==="Circle"?p.centro:p.coordenada,k=rt(a,t(x));k<=n&&(l=u(l,{tipo:"vertice",coordenada:x,distanciaPx:k,...y}));continue}if(v&&(p.tipo==="LineString"||p.tipo==="Polygon")&&p.curva)continue;const A=p.tipo==="LineString"?m.partesDaLinha(p).map(x=>({pts:x,fechado:!1})):[{pts:X(p),fechado:p.tipo==="Polygon"}],w=v?i.vertice:void 0;for(const{pts:x,fechado:k}of A){const C=x.map(t);if(r)for(let P=0;P<x.length;P++){if(P===w)continue;const z=rt(a,C[P]);z<=n&&(l=u(l,{tipo:"vertice",coordenada:x[P],distanciaPx:z,...y}))}if(!s&&!c)continue;const L=[];for(let P=0;P<x.length-1;P++)L.push([P,P+1]);k&&x.length>2&&L.push([x.length-1,0]);for(const[P,z]of L)if(!(w!==void 0&&(P===w||z===w))&&!(v&&w===void 0)){if(s){const I=kt(x[P],x[z]),S=rt(a,t(I));S<=n&&(d=u(d,{tipo:"meio",coordenada:I,distanciaPx:S,...y}))}if(c){const{t:I,d:S}=In(a,C[P],C[z]);if(S<=n){const E=[x[P][0]+I*(x[z][0]-x[P][0]),x[P][1]+I*(x[z][1]-x[P][1])];h=u(h,{tipo:"aresta",coordenada:E,distanciaPx:S,...y})}}}}}return l??d??h}class Dn{constructor(e){this.p=e}candidatasEm(e,t){const o=this.p.obterMapa(),i=this.p.obterLayerManager(),n=N.get(G);if(!o||!n)return[];const r=o.latLngToContainerPoint(e),s=o.containerPointToLatLng([r.x-t,r.y+t]),c=o.containerPointToLatLng([r.x+t,r.y-t]),l={minLon:Math.min(s.lng,c.lng),maxLon:Math.max(s.lng,c.lng),minLat:Math.min(s.lat,c.lat),maxLat:Math.max(s.lat,c.lat)},d=[];for(const h of i.getLayers()){if(h.tipo!==G||!h.visivel)continue;const u=i.getLayerInstance(h.id);u&&d.push(...n.consultarProximas(u,l).filter(g=>this.p.desenhada(g)))}return d}buscarSnapEm(e,t){const o=this.p.obterMapa();if(!o)return null;const i=o.latLngToContainerPoint(e),n=this.candidatasEm(e,Ot);return zi({x:i.x,y:i.y},n,r=>o.latLngToContainerPoint(r),{},t)}feicaoSob(e,t){const o=this.p.obterMapa();if(!o)return null;const i=o.getContainer().getBoundingClientRect(),n=b.point(e-i.left,t-i.top),r=o.containerPointToLatLng(n),s=[r.lat,r.lng];return{feicao:Le({x:n.x,y:n.y},this.candidatasEm(s,8),l=>o.latLngToContainerPoint(l)),coordenada:s}}}class _n{constructor(e){f(this,"hoverId",null);f(this,"hoverAgendado",!1);this.p=e}aoMoverMouse(e){if(e.buttons!==0||this.p.interacaoAtiva()){this.hoverId!==null&&(this.hoverId=null,this.p.emitir("cad-feicao-hover",{feicao:null}));return}if(this.hoverAgendado)return;this.hoverAgendado=!0;const{clientX:o,clientY:i}=e;let n=!1;const r=()=>{if(n)return;n=!0,this.hoverAgendado=!1;const s=this.p.feicaoSob(o,i),c=s!=null&&s.feicao?`${s.feicao.camadaId}\0${s.feicao.id}`:null;c!==this.hoverId&&(this.hoverId=c,this.p.emitir("cad-feicao-hover",{feicao:(s==null?void 0:s.feicao)??null}))};typeof requestAnimationFrame=="function"&&requestAnimationFrame(r),setTimeout(r,100)}menuContexto(e){if(this.p.botaoDireitoDaFerramenta())return;const t=this.p.feicaoSob(e.clientX,e.clientY);t&&this.p.emitir("cad-feicao-menu",{feicao:t.feicao,coordenada:t.coordenada,x:e.clientX,y:e.clientY})}duploClique(e){if(this.p.interacaoAtiva()||!this.p.abrirPopup)return;const t=this.p.feicaoSob(e.clientX,e.clientY);t!=null&&t.feicao&&this.p.abrirPopup(t.feicao)}limpar(){this.hoverId=null}}const Tn=111320;function fe(a,e){return a.x>=e.x1&&a.x<=e.x2&&a.y>=e.y1&&a.y<=e.y2}function no(a,e,t){let o=0,i=1;const n=e.x-a.x,r=e.y-a.y,s=[-n,n,-r,r],c=[a.x-t.x1,t.x2-a.x,a.y-t.y1,t.y2-a.y];for(let l=0;l<4;l++)if(s[l]===0){if(c[l]<0)return!1}else{const d=c[l]/s[l];if(s[l]<0){if(d>i)return!1;d>o&&(o=d)}else{if(d<o)return!1;d<i&&(i=d)}}return!0}function ro(a,e){let t=!1;for(let o=0,i=e.length-1;o<e.length;i=o++){const n=e[o],r=e[i];n.y>a.y!=r.y>a.y&&a.x<(r.x-n.x)*(a.y-n.y)/(r.y-n.y)+n.x&&(t=!t)}return t}function so(a,e,t){for(let o=1;o<a.length;o++)if(no(a[o-1],a[o],e))return!0;return t&&a.length>2&&no(a[a.length-1],a[0],e)}function Fn(a,e,t){const o=t(a),i=t([a[0]+e/Tn,a[1]]);return Math.hypot(i.x-o.x,i.y-o.y)}function ki(a,e,t,o){if(a.oculta)return!1;const i=a.geometria,n=o==="window";switch(i.tipo){case"Point":case"Text":return fe(t(i.coordenada),e);case"LineString":{const r=m.partesDaLinha(i).map(s=>s.map(t));return n?r.every(s=>s.every(c=>fe(c,e))):r.some(s=>s.some(c=>fe(c,e))||so(s,e,!1))}case"Polygon":{const r=i.aneis.map(l=>l.map(t)),s=r[0];if(!s)return!1;if(n)return s.every(l=>fe(l,e));if(r.some(l=>l.some(d=>fe(d,e))||so(l,e,!0)))return!0;const c={x:e.x1,y:e.y1};return ro(c,s)&&!r.slice(1).some(l=>ro(c,l))}case"Circle":{const r=t(i.centro),s=Fn(i.centro,i.raioMetros,t);if(n)return r.x-s>=e.x1&&r.x+s<=e.x2&&r.y-s>=e.y1&&r.y+s<=e.y2;const c=Math.max(e.x1,Math.min(r.x,e.x2)),l=Math.max(e.y1,Math.min(r.y,e.y2));return Math.hypot(r.x-c,r.y-l)<=s}}}function Ii(a,e){if(e.length<3||a.oculta)return!1;const t=i=>zt(i,[e]),o=a.geometria;switch(o.tipo){case"Point":case"Text":return t(o.coordenada);case"Circle":return t(o.centro);case"LineString":return m.partesDaLinha(o).some(i=>i.some(t));case"Polygon":{const i=o.aneis[0]??[];if(i.some(t))return!0;if(i.length<3)return!1;const n=i.reduce((r,s)=>[r[0]+s[0],r[1]+s[1]],[0,0]);return t([n[0]/i.length,n[1]/i.length])}}}class qn{constructor(e){this.p=e}selecionarNoLaco(e){const t=[];for(const o of this.p.obterLayerManager().getActiveSelectableLayers())if(o.tipo===G)for(const i of this.p.lista(o.id))this.p.desenhada(i)&&Ii(i,e)&&t.push({camadaId:o.id,id:i.id});this.p.desativarFerramenta(),this.p.selecionar(t)}selecionarNaCaixa(e,t,o){const i=this.p.obterMapa();if(!i)return;const n=s=>i.latLngToContainerPoint(s),r=[];for(const s of this.p.obterLayerManager().getActiveSelectableLayers())if(s.tipo===G)for(const c of this.p.lista(s.id))this.p.desenhada(c)&&ki(c,e,n,t)&&r.push({camadaId:s.id,id:c.id});o?this.p.alternarVarias(r):this.p.selecionar(r)}}class On{constructor(e){f(this,"operacoes");f(this,"selecao");f(this,"popup");f(this,"edicao");f(this,"consulta");f(this,"ponteiro");f(this,"regiao");f(this,"snap");f(this,"ferramentas");f(this,"versoes");f(this,"camera");f(this,"repositorio");f(this,"cursores");f(this,"margensHud",{});f(this,"aceitarOrigem",!1);f(this,"opcoesPopup",{copiarParaAreaDeTransferencia:!0});this.contexto=e,this.repositorio=new zn({obterLayerManager:()=>this.contexto.obterLayerManager(),opcoesNormalizacao:()=>this.opcoesNormalizacao(),aposDados:()=>this.aposDados()}),this.consulta=new Dn({obterMapa:()=>this.contexto.obterMapa(),obterLayerManager:()=>this.contexto.obterLayerManager(),desenhada:t=>this.desenhada(t)}),this.ponteiro=new _n({emitir:(t,o)=>this.contexto.emitir(t,o),feicaoSob:(t,o)=>this.consulta.feicaoSob(t,o),interacaoAtiva:()=>this.ferramentas.ativo||this.edicao.editando,botaoDireitoDaFerramenta:()=>this.ferramentas.ativo?(this.ferramentas.botaoDireito(),!0):!1,abrirPopup:t=>this.popup.abrir(t)}),this.regiao=new qn({obterMapa:()=>this.contexto.obterMapa(),obterLayerManager:()=>this.contexto.obterLayerManager(),lista:t=>this.lista(t),desenhada:t=>this.desenhada(t),desativarFerramenta:()=>this.ferramentas.desativarFerramenta(),selecionar:t=>this.selecao.selecionar(t),alternarVarias:t=>this.selecao.alternarVarias(t)}),this.edicao=new kn({obterMapa:()=>this.contexto.obterMapa(),obterLayerManager:()=>this.contexto.obterLayerManager(),emitir:(t,o)=>this.contexto.emitir(t,o),buscar:(t,o)=>this.buscar(t,o),substituir:(t,o)=>this.substituir(t,o),desativarFerramenta:()=>this.ferramentas.desativarFerramenta(),aplicarMargensHud:()=>this.aplicarMargensHud(),selecionarUma:t=>this.selecao.selecionar([t]),fecharPopup:()=>this.popup.fechar(),reabrirPopupDaSelecao:()=>{if(this.modoPopups()!=="automatico")return;const t=this.selecao.obter();t.length===1&&this.popup.abrir(t[0])},snapAtivo:()=>this.snap.ativo,alternarSnap:()=>this.snap.alternar(),buscarSnapEm:(t,o)=>this.buscarSnapEm(t,o)}),this.versoes=new fn({obterLayerManager:()=>this.contexto.obterLayerManager(),emitir:(t,o)=>this.contexto.emitir(t,o),buscar:(t,o)=>this.buscar(t,o),lista:t=>this.lista(t),aposDados:()=>this.aposDados()},e.regra??new m.RegraVersoes),this.ferramentas=new En({obterMapa:()=>this.contexto.obterMapa(),obterLayerManager:()=>this.contexto.obterLayerManager(),emitir:(t,o,i)=>this.contexto.emitir(t,o,i),aoFerramenta:t=>{var o,i;return(i=(o=this.contexto).aoFerramenta)==null?void 0:i.call(o,t)},lista:t=>this.lista(t),adicionarFeicao:(t,o)=>this.adicionarFeicao(t,o),buscarSnapEm:t=>this.buscarSnapEm(t),snapAtivo:()=>this.snap.ativo,prepararDesenho:()=>{this.edicao.parar(),this.popup.fechar(),this.aplicarMargensHud()},normalizarCoordenada:t=>Z(t,this.opcoesNormalizacao()),dividirComLinha:t=>this.dividirComLinha(t),selecionarNoLaco:t=>this.selecionarNoLaco(t),candidatasEm:(t,o)=>this.candidatasEm(t,o)}),this.camera=new mn({obterMapa:()=>this.contexto.obterMapa(),obterLayerManager:()=>this.contexto.obterLayerManager(),buscar:(t,o)=>this.buscar(t,o),lista:t=>this.lista(t),desenhada:t=>this.desenhada(t),garantirVisivel:t=>this.versoes.garantirVisivel(t)}),this.operacoes=new pn({emitir:(t,o)=>this.contexto.emitir(t,o),obterLayerManager:()=>this.contexto.obterLayerManager(),buscar:(t,o)=>this.buscar(t,o),lista:t=>this.lista(t),desenhada:t=>this.desenhada(t),idLivre:(t,o)=>this.idLivre(t,o),adicionarFeicao:(t,o)=>this.adicionarFeicao(t,o),removerFeicao:(t,o)=>this.removerFeicao(t,o),selecionadas:()=>this.selecao.obter(),estaSelecionada:t=>this.selecao.contem(t),divisaoAtiva:()=>this.ferramentas.ferramentaAtiva==="dividir",encerrarDesenho:()=>this.ferramentas.desativarFerramenta()}),this.cursores=new gi(()=>this.contexto.obterMapa()),this.snap=new un({aoMudar:t=>{var o,i;this.contexto.emitir("cad-snap",t),this.edicao.atualizarSnapNoHud(),(i=(o=this.contexto).aoSnapMudar)==null||i.call(o,t.ligado)}}),this.popup=new yi({obterMapa:()=>this.contexto.obterMapa(),obterCamada:t=>this.contexto.obterLayerManager().getLayerDef(t),aoAcao:(t,o)=>this.tratarAcaoPopup(t,o),liberar:t=>this.contexto.liberarPopups?this.contexto.liberarPopups(t):t()}),this.selecao=new vi({obterFeicao:t=>this.buscar(t.camadaId,t.id),aplicarVisual:(t,o)=>{const i=this.contexto.obterLayerManager().getLayerInstance(t),n=N.get(G);i&&n&&n.aplicarSelecao(i,o)},aoSelecionar:t=>{if(this.contexto.emitir("cad-selecao",{feicoes:t}),this.edicao.editando){const o=this.edicao.feicao;t.length===1&&t[0].id===o.id&&t[0].camadaId===o.camadaId||this.edicao.parar();return}t.length===1&&this.modoPopups()==="automatico"?this.popup.abrir(t[0]):this.popup.fechar()},aoSelecionarUma:t=>this.contexto.emitir("cad-feicao-selecionada",{feicao:t}),visivel:t=>this.selecionavelAgora(t),selecionavel:t=>!t.oculta})}aposDados(){if(this.selecao.reconciliar(),this.edicao.editando){const o=this.edicao.feicao,i=this.buscar(o.camadaId,o.id);!i||i.excluida?this.edicao.parar():i!==o&&this.edicao.sincronizar(i)}const e=this.popup.aberto;if(!e)return;const t=this.buscar(e.camadaId,e.id);t&&!t.excluida?this.popup.atualizar(t):this.popup.fechar()}lista(e){return this.repositorio.lista(e)}buscar(e,t){return this.repositorio.buscar(e,t)}opcoesNormalizacao(){return{aceitarOrigem:this.aceitarOrigem}}definirFeicoes(e,t,o){return this.repositorio.definirFeicoes(e,t,o)}adicionarFeicao(e,t,o){return this.repositorio.adicionarFeicao(e,t,o)}atualizarFeicao(e,t,o,i){return this.repositorio.atualizarFeicao(e,t,o,i)}substituir(e,t){this.repositorio.substituir(e,t)}removerFeicao(e,t){return this.repositorio.removerFeicao(e,t)}aplicarLote(e,t,o){return this.repositorio.aplicarLote(e,t,o)}obterFeicoes(e){return this.lista(e).map(t=>({...t}))}tratarAcaoCamada(e,t){if(e==="feicao-movida")return this.substituir(t.camadaId,t.feicao),"cad-feicao-atualizada";if(e==="feicao-clique"){if(this.ferramentas.ativo)return null;const o={camadaId:t.camadaId,id:t.feicao.id};return t.aditivo?this.selecao.alternar(o):this.selecao.selecionar([o]),"cad-feicao-clique"}return null}selecionarFeicoes(e,t=!1){this.selecao.selecionar(Array.isArray(e)?e:[],t)}alternarSelecaoFeicao(e){this.selecao.alternar(e)}limparSelecaoFeicoes(){this.selecao.limpar()}aoPedirLimpeza(){this.ferramentas.ativo||(this.edicao.editando?this.edicao.parar():this.selecao.limpar())}obterFeicoesSelecionadas(){return this.selecao.obter()}selecionarNoLaco(e){this.regiao.selecionarNoLaco(e)}selecionarNaCaixa(e,t,o){this.regiao.selecionarNaCaixa(e,t,o)}definirMargensPopup(e){this.popup.definirMargens(e)}fecharPopup(){this.popup.fechar()}modoPopups(){var e,t;return((t=(e=this.contexto).modoPopups)==null?void 0:t.call(e))??"automatico"}abrirPopupFeicao(e,t){if(typeof e!="string"||typeof t!="string")return!1;const o=this.buscar(e,t);return!o||o.excluida||!this.desenhada(o)?!1:(this.popup.abrir(o),!0)}aoDuploClique(e){this.modoPopups()!=="desligado"&&this.ponteiro.duploClique(e)}definirOpcoesPopup(e){this.opcoesPopup={...this.opcoesPopup,...e}}obterOpcoesPopup(){return{...this.opcoesPopup}}definirMargensHud(e){this.margensHud={...this.margensHud,...e},this.aplicarMargensHud()}aplicarMargensHud(){const e=this.contexto.obterMapa();e&&Si(e.getContainer(),this.margensHud)}get regraVersoes(){return this.versoes.regra}visivelPorVersao(e){return this.versoes.visivelPorVersao(e)}desenhada(e){return this.versoes.desenhada(e)}selecionavelAgora(e){const t=this.edicao.feicao;return t&&t.id===e.id&&t.camadaId===e.camadaId?!0:!e.oculta&&this.visivelPorVersao(e)}get previasGlobais(){return this.versoes.previasGlobais}definirPreviasGlobais(e){this.versoes.definirPreviasGlobais(e)}alternarPreviasGlobais(){this.versoes.alternarPreviasGlobais()}alternarPrevia(e,t){return this.versoes.alternarPrevia(e,t)}previaSolicitada(e,t){return this.versoes.previaSolicitada(e,t)}atualizarCursorRemoto(e,t){const o=Z(t,this.opcoesNormalizacao());return!!o&&this.cursores.atualizar(e,o)}removerCursorRemoto(e){return this.cursores.remover(e)}limparCursoresRemotos(){this.cursores.limpar()}get cursoresRemotos(){return this.cursores.quantidade}zoomParaFeicao(e,t){return this.camera.zoomParaFeicao(e,t)}zoomParaFeicoes(e){return this.camera.zoomParaFeicoes(e)}ajustarTudo(){return this.camera.ajustarTudo()}ajustarCamada(e){return this.camera.ajustarCamada(e)}aoMoverMouse(e){this.ponteiro.aoMoverMouse(e)}menuContexto(e){this.ponteiro.menuContexto(e)}destruir(){this.ferramentas.destruir(),this.cursores.limpar(),this.ponteiro.limpar()}tratarAcaoPopup(e,t){var o,i,n;if(e==="zoom"&&this.zoomParaFeicao(t.camadaId,t.id),e==="vertices"&&this.iniciarEdicao(t.camadaId,t.id),e==="copiar"&&this.opcoesPopup.copiarParaAreaDeTransferencia){const[r,s]=xe(t);(n=(i=(o=globalThis.navigator)==null?void 0:o.clipboard)==null?void 0:i.writeText(`${r.toFixed(6)}, ${s.toFixed(6)}`))==null||n.catch(()=>{})}this.contexto.emitir("cad-feicao-acao",{acao:e,feicao:t})}get snapLigado(){return this.snap.ligado}get snapAtivo(){return this.snap.ativo}definirSnap(e){this.snap.definir(!!e)}alternarSnap(){this.snap.alternar()}conectarTeclado(){this.snap.conectar()}desconectarTeclado(){this.snap.desconectar()}candidatasEm(e,t){return this.consulta.candidatasEm(e,t)}buscarSnapEm(e,t){return this.consulta.buscarSnapEm(e,t)}get editor(){return this.edicao.editorAtual}get editando(){return this.edicao.editando}iniciarEdicao(e,t){return this.edicao.iniciarEdicao(e,t)}pararEdicao(){this.edicao.parar()}get desenho(){return this.ferramentas.controle}amostrarEstilo(e){this.ferramentas.amostrarEstilo(e)}get ferramentaAtiva(){return this.ferramentas.ferramentaAtiva}definirCamadaDesenho(e){this.ferramentas.definirCamadaDesenho(e)}get camadaDeDesenho(){return this.ferramentas.camadaDeDesenho}definirEstiloDesenho(e){this.ferramentas.definirEstiloDesenho(e)}obterEstiloDesenho(){return this.ferramentas.obterEstiloDesenho()}alternarFerramenta(e){return this.ferramentas.alternarFerramenta(e)}ativarFerramenta(e,t={}){return this.ferramentas.ativarFerramenta(e,t)}desativarFerramenta(){this.ferramentas.desativarFerramenta()}limparMedicao(){this.ferramentas.limparMedicao()}get nosDesenho(){return this.ferramentas.nosDesenho}desfazerVerticeDesenho(){return this.ferramentas.desfazerVerticeDesenho()}definirAtalhoSnap(e){this.snap.atalhoS=e}idLivre(e,t){const o=new Set(this.lista(e).map(n=>n.id));if(!o.has(t))return t;let i=2;for(;o.has(`${t}_${i}`);)i++;return`${t}_${i}`}dividirComLinha(e){return this.operacoes.dividirComLinha(e)}gerarBuffer(e,t,o,i={}){return this.operacoes.gerarBuffer(e,t,o,i)}duplicarFeicao(e,t,o={},i={}){return this.operacoes.duplicarFeicao(e,t,o,i)}juntarFeicoes(e,t,o={}){return this.operacoes.juntarFeicoes(e,t,o)}}const co={ponto:"Ponto",linha:"Linha",poligono:"Polígono",retangulo:"Retângulo",elipse:"Elipse","poligono-regular":"Hexágono",estrela:"Estrela",circulo:"Círculo",texto:"Texto",caneta:"Caneta","medir-distancia":"Medir","medir-area":"Área",dividir:"Dividir","selecao-laco":"Laço","conta-gotas":"Cor"};function st(a){if(!a)return[];const e=a.split(/[\s,]+/).map(o=>o.trim().toLowerCase()).filter(Boolean);if(e.includes("todas"))return[...Ze];const t=new Set(e.filter(Ft));return Ze.filter(o=>t.has(o))}class $n{constructor(e){f(this,"barra",null);this.ctx=e}montar(e){var o;if((o=this.barra)==null||o.remove(),this.barra=null,e.length===0)return;const t=document.createElement("div");t.className="cad-quick-toolbar cad-draw-toolbar",t.setAttribute("role","toolbar"),t.setAttribute("aria-label","Ferramentas de desenho");for(const i of e){const n=document.createElement("button");n.type="button",n.className="cad-btn-tool cad-draw-btn",n.dataset.ferramenta=i,n.textContent=co[i],n.title=co[i],n.setAttribute("aria-pressed","false"),n.addEventListener("click",()=>this.ctx.aoEscolher(i)),t.appendChild(n)}this.ctx.raiz.appendChild(t),this.barra=t}marcar(e){var t;(t=this.barra)==null||t.querySelectorAll("[data-ferramenta]").forEach(o=>{const i=o.dataset.ferramenta===e;o.classList.toggle("active",i),o.setAttribute("aria-pressed",String(i))})}desmontar(){var e;(e=this.barra)==null||e.remove(),this.barra=null}}const Nn="data-cad-estilos-externos";function Rn(a){try{return Array.from(a.cssRules,e=>e.cssText).join(`
|
|
167
|
+
`)}catch{return""}}function Bn(a){return typeof a=="string"?a.trim()?[a]:[]:Array.isArray(a)?a.map(e=>typeof e=="string"?e:Rn(e)).filter(e=>e.trim()!==""):[]}class Vn{constructor(e){f(this,"textos",[]);f(this,"adotadas",[]);f(this,"fallback",null);this.shadow=e}get pedido(){return this.textos}definir(e){this.textos=Bn(e),this.aplicar()}limpar(){this.remover()}aplicar(){if(this.remover(),this.textos.length===0)return;const e=this.shadow;if(typeof CSSStyleSheet<"u"&&Array.isArray(e.adoptedStyleSheets))try{this.adotadas=this.textos.map(o=>{const i=new CSSStyleSheet;return i.replaceSync(o),i}),e.adoptedStyleSheets=[...e.adoptedStyleSheets,...this.adotadas];return}catch{this.adotadas=[]}const t=document.createElement("style");t.setAttribute(Nn,""),t.textContent=this.textos.join(`
|
|
168
|
+
`),this.shadow.appendChild(t),this.fallback=t}remover(){var t;const e=this.shadow;this.adotadas.length>0&&Array.isArray(e.adoptedStyleSheets)&&(e.adoptedStyleSheets=e.adoptedStyleSheets.filter(o=>!this.adotadas.includes(o))),this.adotadas=[],(t=this.fallback)==null||t.remove(),this.fallback=null}}class Di extends lo.SafeHTMLElement{constructor(){super();f(this,"shadow");f(this,"mapContainer",null);f(this,"layersPanel",null);f(this,"controller");f(this,"controladorTamanho");f(this,"toolbarPainel");f(this,"broadcastConfig");f(this,"colecoesDados");f(this,"feicoes");f(this,"barraFerramentas");f(this,"hoverListeners",new ct.ListenerBag);f(this,"desligarAnuncios",null);f(this,"layerItemListeners",new ct.ListenerBag);f(this,"initTimeout");f(this,"estilosExternos");f(this,"lastPopupActionEmit");f(this,"lastCanvasClickTime",0);f(this,"_chaveGrupo");f(this,"_zonaProjecao",22);this.shadow=this.attachShadow({mode:"open"}),this.controller=new Ye,this.controladorTamanho=pi(this,this.controller),this.shadow.innerHTML=ja(),this.estilosExternos=new Vn(this.shadow),this.mapContainer=this.shadow.getElementById("cad-map-container"),this.layersPanel=this.shadow.getElementById("qgis-layer-panel"),this.toolbarPainel=new Va({shadow:this.shadow,mapContainer:this.mapContainer,layersPanel:this.layersPanel,onToggleCamadas:()=>this.toggleLayersPanel(),onCloseCamadas:()=>this.closeLayersPanel(),onZoomExtents:()=>this.zoomExtents(),onLimparSelecao:()=>this.limparSelecao(),onToggleSnap:()=>this.feicoes.alternarSnap(),onTratarCliqueCanvas:n=>this.tratarCliqueLivreCanvas(n),onDispararAcaoPopup:(n,r)=>this.dispararAcaoPopup(n,r)}),this.broadcastConfig=new Ba({host:this,controller:this.controller,mapContainer:this.mapContainer,setLayerOpacity:(n,r)=>this.setLayerOpacity(n,r)}),this.colecoesDados=new Ha({obterController:()=>this.controller,obterChaveGrupo:()=>this.chaveGrupo,setLayerVisibility:(n,r)=>this.setLayerVisibility(n,r)});const t=new m.RegraVersoes,o=this.controller.context,i=this.controller.canvasInteracao.ctx;Object.assign(o,{regraVersoes:t,renderizador:()=>this.renderizador}),this.feicoes=new On({obterLayerManager:()=>this.controller.layerManager,obterMapa:()=>this.controller.getMap(),regra:t,modoPopups:()=>this.popups,liberarPopups:n=>Ct(this.controller.getMap(),n),aoFerramenta:n=>{this.barraFerramentas.marcar(n)},aoSnapMudar:n=>{Yt(this.shadow,n)},emitir:(n,r,s)=>{const c=new CustomEvent(n,{detail:r,bubbles:!0,composed:!0,cancelable:!!s});return this.dispatchEvent(c),c.defaultPrevented}}),Object.assign(o,{onLayerAction:(n,r)=>{const s=this.feicoes.tratarAcaoCamada(n,r);s&&this.dispatchEvent(new CustomEvent(s,{detail:r,bubbles:!0,composed:!0}))}}),this.barraFerramentas=new $n({raiz:this.shadow.getElementById("cad-root"),aoEscolher:n=>{this.feicoes.alternarFerramenta(n)}}),this.barraFerramentas.montar(st(this.getAttribute("ferramentas"))),Object.assign(i,{aoMenuContexto:n=>this.feicoes.menuContexto(n),ferramentaAtiva:()=>this.feicoes.ferramentaAtiva!==null,aoLimparSelecao:()=>this.feicoes.aoPedirLimpeza(),selecionarFeicoesNaCaixa:(n,r,s)=>this.feicoes.selecionarNaCaixa(n,r,s)}),Za(this.shadow),Yt(this.shadow,!0)}static get observedAttributes(){return["sat-opacity","scale-mode","crosshair","modo-sequencial","chave-grupo","zona-projecao","fuso","canal-configuracao","ferramentas","sem-atalho-snap","aceitar-origem","sem-camadas-padrao","sem-painel-camadas","sem-barra-rapida","popups","renderizador"]}connectedCallback(){var o;const t=this.getAttribute("zona-projecao")||this.getAttribute("fuso");if(t){const i=parseInt(t,10);!isNaN(i)&&i>0&&(this._zonaProjecao=i,this.controller.zonaProjecao=i,this.controller.context.zonaProjecao=i)}this.controller.core.definirModoPopups(this.popups),this.controladorTamanho.observe(),this.feicoes.conectarTeclado(),this.hoverListeners.cleanup(),this.mapContainer&&(this.hoverListeners.add(this.mapContainer,"mousemove",i=>this.feicoes.aoMoverMouse(i)),this.hoverListeners.add(this.mapContainer,"dblclick",i=>this.feicoes.aoDuploClique(i))),this.barraFerramentas.montar(st(this.getAttribute("ferramentas"))),this.broadcastConfig.conectar(),(o=this.desligarAnuncios)==null||o.call(this),this.desligarAnuncios=Ka(this,this.shadow),this.estilosExternos.aplicar(),this.initTimeout=window.setTimeout(()=>{this.initTimeout=void 0,this.inicializarAgora()},0)}destroy(){var t;this.initTimeout&&(window.clearTimeout(this.initTimeout),this.initTimeout=void 0),this.controladorTamanho.disconnect(),this.estilosExternos.limpar(),this.feicoes.pararEdicao(),this.feicoes.desativarFerramenta(),this.feicoes.limparMedicao(),this.feicoes.desconectarTeclado(),this.feicoes.destruir(),this.hoverListeners.cleanup(),(t=this.desligarAnuncios)==null||t.call(this),this.desligarAnuncios=null,this.broadcastConfig.desconectar(),this.limparDestaque(),this.toolbarPainel.limpar(),this.layerItemListeners.cleanup(),this.controller.destroy(),fi(this.mapContainer)}disconnectedCallback(){this.destroy()}invalidateSizeSafely(){this.controladorTamanho.invalidateSizeSafely()}attributeChangedCallback(t,o,i){var n,r,s,c,l,d,h;if(t==="sem-atalho-snap"){(n=this.feicoes)==null||n.definirAtalhoSnap(i===null);return}if(!(t==="sem-camadas-padrao"||t==="sem-barra-rapida")){if(t==="sem-painel-camadas"){i!==null&&((r=this.toolbarPainel)==null||r.closeLayersPanel());return}if(t==="popups"){(s=this.controller)==null||s.core.definirModoPopups(Be(i));return}if(t==="renderizador"){ge(o)!==ge(i)&&((c=this.controller)==null||c.layerManager.recriarCamadasDoTipo("feicoes"));return}if(t==="aceitar-origem"){this.feicoes&&(this.feicoes.aceitarOrigem=i!==null&&i!=="false");return}if(t==="ferramentas"){(l=this.barraFerramentas)==null||l.montar(st(i)),(h=this.barraFerramentas)==null||h.marcar(((d=this.feicoes)==null?void 0:d.ferramentaAtiva)??null);return}Ua({host:this,controller:this.controller,mapContainer:this.mapContainer,broadcastConfig:this.broadcastConfig,setLayerOpacity:(u,g)=>this.setLayerOpacity(u,g),setLayerScaleMode:(u,g)=>this.setLayerScaleMode(u,g),atualizarZonaProjecao:u=>{this._zonaProjecao=u}},t,o,i)}}inicializarAgora(){this.initTimeout!==void 0&&(window.clearTimeout(this.initTimeout),this.initTimeout=void 0);const t=this.controller.getMap();return t||(this.hasAttribute("sem-camadas-padrao")&&this.controller.layerManager.descartarCamadasPadrao(),this.initCAD(),this.controller.getMap())}definirEstilosExternos(t){this.estilosExternos.definir(t)}initCAD(){Wa({host:this,shadow:this.shadow,mapContainer:this.mapContainer,controller:this.controller,toolbarPainel:this.toolbarPainel,colecoesDados:this.colecoesDados,obterContextoEventos:()=>this.obterContextoEventos(),renderLayersUI:()=>this.renderLayersUI(),invalidateSizeSafely:()=>this.invalidateSizeSafely(),tratarCliqueLivreCanvas:(t,o,i)=>this.tratarCliqueLivreCanvas(t,o,i),dispararAcaoPopup:(t,o,i)=>this.dispararAcaoPopup(t,o,i)})}obterContextoEventos(){return{host:this,controller:this.controller,mapContainer:this.mapContainer,modoSequencial:this.modoSequencial,mouseMovedSinceDown:this.toolbarPainel.houveMovimentoMouse,obterElementoPorId:t=>this.colecoesDados.obterElementoPorId(t),fecharPopup:()=>{var t;(t=this.controller.getMap())==null||t.closePopup()}}}tratarCliqueLivreCanvas(t,o,i){const n=Date.now();n-this.lastCanvasClickTime<50||(this.lastCanvasClickTime=n,li(this.obterContextoEventos(),t,o,i))}dispararAcaoPopup(t,o,i){const n=Date.now();this.lastPopupActionEmit&&this.lastPopupActionEmit.acaoId===t&&this.lastPopupActionEmit.elementoId===o&&n-this.lastPopupActionEmit.time<50||(this.lastPopupActionEmit={acaoId:t,elementoId:o,time:n},di(this.obterContextoEventos(),t,o,i))}toggleLayersPanel(){this.hasAttribute("sem-painel-camadas")||this.toolbarPainel.toggleLayersPanel()}closeLayersPanel(){this.toolbarPainel.closeLayersPanel()}renderLayersUI(){const t=this.shadow.getElementById("layers-list-container");si(t,this.controller.layerManager.getLayers(),this.layerItemListeners,{setLayerVisibility:(o,i)=>this.setLayerVisibility(o,i),setLayerOpacity:(o,i)=>this.setLayerOpacity(o,i),setLayerBlocked:(o,i)=>this.controller.layerManager.setLayerBlocked(o,i),setLayerScaleMode:(o,i)=>this.setLayerScaleMode(o,i)})}get pontos(){return this.colecoesDados.pontos}set pontos(t){this.colecoesDados.pontos=t}get segmentos(){return this.colecoesDados.segmentos}set segmentos(t){this.colecoesDados.segmentos=t}get bancoPontos(){return this.colecoesDados.bancoPontos}set bancoPontos(t){this.colecoesDados.bancoPontos=t}get pontosHomologados(){return this.bancoPontos}set pontosHomologados(t){this.bancoPontos=t}get confrontantes(){return this.colecoesDados.confrontantes}set confrontantes(t){this.colecoesDados.confrontantes=t}get vizinhos(){return this.confrontantes}set vizinhos(t){this.confrontantes=t}get aceitarOrigem(){return this.hasAttribute("aceitar-origem")&&this.getAttribute("aceitar-origem")!=="false"}set aceitarOrigem(t){t?this.setAttribute("aceitar-origem",""):this.removeAttribute("aceitar-origem")}get popups(){return Be(this.getAttribute("popups"))}set popups(t){this.setAttribute("popups",String(t))}get renderizador(){return ge(this.getAttribute("renderizador"))}set renderizador(t){this.setAttribute("renderizador",String(t))}estatisticasFeicoes(t){const o=this.controller.layerManager.getLayerInstance(t),i=N.get("feicoes");return o&&i?i.estatisticas(o):null}get modoSequencial(){return this.hasAttribute("modo-sequencial")}set modoSequencial(t){var i;const o=!!t;o?this.hasAttribute("modo-sequencial")||this.setAttribute("modo-sequencial",""):this.hasAttribute("modo-sequencial")&&this.removeAttribute("modo-sequencial"),this.controller.modoCliqueSequencialAtivo=o,this.controller.context.modoSequencial=o,o&&((i=this.controller.getMap())==null||i.closePopup())}get chaveGrupo(){return this.getAttribute("chave-grupo")||this._chaveGrupo}set chaveGrupo(t){this._chaveGrupo=t,t?this.getAttribute("chave-grupo")!==t&&this.setAttribute("chave-grupo",t):this.hasAttribute("chave-grupo")&&this.removeAttribute("chave-grupo"),this.controller.chaveGrupo=t,this.controller.context.chaveGrupo=t,this.controller.layerManager.updateContext({chaveGrupo:t})}get zonaProjecao(){return this._zonaProjecao??22}set zonaProjecao(t){const o=typeof t=="number"?Math.floor(t):parseInt(String(t),10);if(!isNaN(o)&&o>0){this._zonaProjecao=o;const i=String(o);this.getAttribute("zona-projecao")!==i&&this.setAttribute("zona-projecao",i),this.hasAttribute("fuso")&&this.getAttribute("fuso")!==i&&this.setAttribute("fuso",i),this.controller.zonaProjecao=o,this.controller.context.zonaProjecao=o}}get canalConfiguracao(){return this.getAttribute("canal-configuracao")}set canalConfiguracao(t){t?this.setAttribute("canal-configuracao",t):this.removeAttribute("canal-configuracao")}fitBounds(t,o=[40,40],i=!1){this.controller.fitBounds(t,o,i)}zoomExtents(){this.controller.canvasInteracao.zoomExtents()}selectPonto(t,o){this.controller.selectPonto(t,o)}selecionarPonto(t,o){this.controller.selectPonto(t,o)}get pontosSelecionados(){return Oa(this.controller)}set pontosSelecionados(t){const o=Array.isArray(t)?t:[];ci(this.controller,o),this.controller.atualizarDestaqueMarcadores()}atualizarDestaqueMarcadores(){this.controller.atualizarDestaqueMarcadores()}selectSegmento(t){this.controller.selectSegmento(t)}get segmentoSelecionado(){return this.controller.context.selectedSegmentoId||null}set segmentoSelecionado(t){this.controller.selectSegmento(t)}limparSelecao(){this.controller.canvasInteracao.limparSelecao(),this.feicoes.limparSelecaoFeicoes()}setLayerVisibility(t,o){this.controller.layerManager.setLayerVisibility(t,o)}setLayerOpacity(t,o){this.controller.layerManager.setLayerOpacity(t,o)}setLayerScaleMode(t,o){this.controller.layerManager.setLayerScaleMode(t,o)}setGraphicScale(t){this.controller.setGraphicScale(t)}exportState(){return this.controller.exportState()}importState(t){this.controller.importState(t)}invalidateSize(){this.invalidateSizeSafely()}get destaqueAtivo(){return this.controller.destaqueAtivo}destacarElemento(t,o){this.inicializarAgora(),this.controller.destacarElemento(t,o)}limparDestaque(){this.controller.limparDestaque()}plotarPontos(t,o="vertices",i){this.colecoesDados.plotarPontos(t,o,i)}plotarConexoes(t,o="linhas"){this.colecoesDados.plotarConexoes(t,o)}plotarPolilinhaSequencial(t,o=!0,i="polilinha",n){this.colecoesDados.plotarPolilinhaSequencial(t,o,i,n)}plotarPoligonos(t,o="poligonos"){this.colecoesDados.plotarPoligonos(t,o)}limparCamadas(t){this.colecoesDados.limparCamadas(t)}obterMarcadores(t){return this.colecoesDados.obterMarcadores(t)}plotPontos(t,o){this.colecoesDados.plotPontos(t,o)}plotSegmentos(t,o){this.colecoesDados.plotSegmentos(t,o)}plotPolilinhaTemporaria(t){this.colecoesDados.plotPolilinhaTemporaria(t)}plotPoligonalHomologada(t){this.colecoesDados.plotPoligonalHomologada(t)}plotPontosVizinhos(t){this.colecoesDados.plotPontosVizinhos(t)}plotPoligonosVizinhos(t){this.colecoesDados.plotPoligonosVizinhos(t)}clearOverlays(t=!1){this.colecoesDados.clearOverlays(t)}getMarkers(){return this.colecoesDados.getMarkers()}getVizinhosMarkers(){return this.colecoesDados.getVizinhosMarkers()}definirFeicoes(t,o,i){return this.feicoes.definirFeicoes(t,o,i)}adicionarFeicao(t,o,i){return this.feicoes.adicionarFeicao(t,o,i)}atualizarFeicao(t,o,i,n){return this.feicoes.atualizarFeicao(t,o,i,n)}aplicarLote(t,o,i){return this.feicoes.aplicarLote(t,o,i)}removerFeicao(t,o){return this.feicoes.removerFeicao(t,o)}obterFeicoes(t){return this.feicoes.obterFeicoes(t)}selecionarFeicoes(t,o=!1){this.feicoes.selecionarFeicoes(t,o)}selecionarFeicao(t,o){this.feicoes.selecionarFeicoes([{camadaId:t,id:o}])}alternarSelecaoFeicao(t,o){this.feicoes.alternarSelecaoFeicao({camadaId:t,id:o})}limparSelecaoFeicoes(){this.feicoes.limparSelecaoFeicoes()}obterFeicoesSelecionadas(){return this.feicoes.obterFeicoesSelecionadas()}editarVertices(t,o){return this.feicoes.iniciarEdicao(t,o)}pararEdicaoVertices(){this.feicoes.pararEdicao()}get editandoVertices(){return this.feicoes.editando}get snapLigado(){return this.feicoes.snapLigado}definirSnap(t){this.feicoes.definirSnap(t)}alternarSnap(){this.feicoes.alternarSnap()}definirCamadaDesenho(t){this.feicoes.definirCamadaDesenho(t)}get camadaDesenho(){return this.feicoes.camadaDeDesenho}definirEstiloDesenho(t){this.feicoes.definirEstiloDesenho(t)}obterEstiloDesenho(){return this.feicoes.obterEstiloDesenho()}definirFerramenta(t,o){return t===null?(this.feicoes.desativarFerramenta(),{ok:!0}):this.feicoes.ativarFerramenta(t,o)}get ferramentaAtiva(){return this.feicoes.ferramentaAtiva}limparMedicao(){this.feicoes.limparMedicao()}get nosDesenho(){return this.feicoes.nosDesenho}desfazerVerticeDesenho(){return this.feicoes.desfazerVerticeDesenho()}definirAtalhoSnap(t){this.feicoes.definirAtalhoSnap(t)}gerarBuffer(t,o,i,n){return this.feicoes.gerarBuffer(t,o,i,n)}duplicarFeicao(t,o,i,n){return this.feicoes.duplicarFeicao(t,o,i,n)}juntarFeicoes(t,o,i){return this.feicoes.juntarFeicoes(t,o,i)}zoomParaFeicao(t,o){return this.feicoes.zoomParaFeicao(t,o)}zoomParaFeicoes(t){return this.feicoes.zoomParaFeicoes(t)}ajustarTudo(){return this.feicoes.ajustarTudo()}ajustarCamada(t){return this.feicoes.ajustarCamada(t)}get previasGlobais(){return this.feicoes.previasGlobais}definirPreviasGlobais(t){this.feicoes.definirPreviasGlobais(t)}alternarPreviasGlobais(){this.feicoes.alternarPreviasGlobais()}alternarPrevia(t,o){return this.feicoes.alternarPrevia(t,o)}previaSolicitada(t,o){return this.feicoes.previaSolicitada(t,o)}atualizarCursorRemoto(t,o){return this.feicoes.atualizarCursorRemoto(t,o)}removerCursorRemoto(t){return this.feicoes.removerCursorRemoto(t)}limparCursoresRemotos(){this.feicoes.limparCursoresRemotos()}fecharPopupFeicao(){this.feicoes.fecharPopup()}abrirPopupFeicao(t,o){return this.feicoes.abrirPopupFeicao(t,o)}definirOpcoesPopup(t){this.feicoes.definirOpcoesPopup(t)}definirMargensPopup(t){this.feicoes.definirMargensPopup(t)}definirMargensHud(t){this.feicoes.definirMargensHud(t)}getMap(){return this.controller.getMap()}getController(){return this.controller}getLayerManager(){return this.controller.layerManager}}lo.definirCustomElement("ui-canvas-cad",Di);class Hn{constructor(e,t){f(this,"polylines",[]);f(this,"bancoPontosAtivo",!1);f(this,"core");this.core=e}setBancoPontosAtivo(e){this.bancoPontosAtivo=e}plotSegmentos(e,t){this.core.map&&e.forEach(o=>{const i=t.find(r=>String(r.id)===String(o.ponto_inicio_id)),n=t.find(r=>String(r.id)===String(o.ponto_fim_id));if(i&&n&&i.lat&&i.lon&&n.lat&&n.lon){const r=o.tipo_limite_sigef||o.tipo_limite||"",s=o.metodo_posicionamento_sigef||o.metodo_posicionamento||"",c=this.bancoPontosAtivo?"#94a3b8":r==="LA1"?"#10b981":"#3b82f6",l=this.core.config.perimetroWeight,d=this.bancoPontosAtivo?.4:1,h=[[i.lat,i.lon],[n.lat,n.lon]],u=b.polyline(h,{color:"#080d0a",weight:l+3,opacity:.85,lineCap:"round",lineJoin:"round",dashArray:r==="LN1"?"6, 6":void 0,pane:"perimetroPane",interactive:!1}).addTo(this.core.map);this.polylines.push(u);const g=b.polyline(h,{color:c,weight:l,opacity:d,dashArray:r==="LN1"?"6, 6":void 0,pane:"perimetroPane"}).bindPopup(`
|
|
169
169
|
<div style="font-family:sans-serif; color:rgba(255, 255, 255, 0.9); line-height:1.3;">
|
|
170
|
-
<div style="font-weight:700; font-size:12px; margin-bottom:3px; color:#ffffff;">${
|
|
171
|
-
<div style="font-size:11px; color:rgba(255, 255, 255, 0.65);">Limite: ${
|
|
170
|
+
<div style="font-weight:700; font-size:12px; margin-bottom:3px; color:#ffffff;">${M.escapeHtml(i.nome_vertice)} ↔ ${M.escapeHtml(n.nome_vertice)}</div>
|
|
171
|
+
<div style="font-size:11px; color:rgba(255, 255, 255, 0.65);">Limite: ${M.escapeHtml(r)} · ${M.escapeHtml(s)}</div>
|
|
172
172
|
</div>
|
|
173
|
-
`,{className:"compact-popup",maxWidth:220}).addTo(this.core.map);this.polylines.push(g)}})}plotPolilinhaTemporaria(
|
|
173
|
+
`,{className:"compact-popup",maxWidth:220}).addTo(this.core.map);this.polylines.push(g)}})}plotPolilinhaTemporaria(e){var c,l,d;if(!this.core.map)return;const t=e.filter(h=>h.lat&&h.lon&&h.lat!==0&&h.lon!==0&&h.tipo_ponto!=="B"&&h.tipo!=="B"&&h.ignorar_poligono!==1);if(t.length<2)return;const o=((c=this.core.controller)==null?void 0:c.chaveGrupo)||((d=(l=this.core.controller)==null?void 0:l.context)==null?void 0:d.chaveGrupo),i=M.agruparPontosPorChave(t,o),n=this.bancoPontosAtivo?"#94a3b8":"#10b981",r=this.core.config.fechamentoWeight||2,s=this.bancoPontosAtivo?.4:1;Object.values(i).forEach(h=>{const u=M.ordenarPontosPorSequencia(h);if(u.length<2)return;for(let w=0;w<u.length-1;w++){const x=u[w],k=u[w+1],C=[[x.lat,x.lon],[k.lat,k.lon]],L=b.polyline(C,{color:"#080d0a",weight:r+3,opacity:.85,lineCap:"round",lineJoin:"round",pane:"perimetroPane",interactive:!1}).addTo(this.core.map);this.polylines.push(L);const P=b.polyline(C,{color:n,weight:r,opacity:s,pane:"perimetroPane"}).addTo(this.core.map);this.polylines.push(P)}const g=u[u.length-1],v=u[0],p=[[g.lat,g.lon],[v.lat,v.lon]],y=b.polyline(p,{color:"#080d0a",weight:r+2.5,opacity:.75,dashArray:"4, 4",pane:"perimetroPane",interactive:!1}).addTo(this.core.map);this.polylines.push(y);const A=b.polyline(p,{color:n,weight:r,opacity:s,dashArray:"4, 4",pane:"perimetroPane"}).addTo(this.core.map);this.polylines.push(A)})}plotPoligonalHomologada(e){var n,r,s;if(!this.core.map||!this.core.bancoPontosGroup)return;this.core.bancoPontosGroup.clearLayers();const t=e.filter(c=>c.lat&&c.lon&&c.lat!==0&&c.lon!==0);if(t.length===0)return;this.bancoPontosAtivo=!0,t.forEach(c=>{const l=`
|
|
174
174
|
<div class="w-4.5 h-4.5 bg-amber-500 text-slate-950 border-2 border-slate-900 rounded-full flex items-center justify-center text-[7px] font-black font-mono shadow-md hover:scale-125 transition-transform" id="banco-marker-${c.id}">
|
|
175
175
|
H
|
|
176
176
|
</div>
|
|
177
|
-
`,d=
|
|
177
|
+
`,d=b.divIcon({html:l,className:"banco-leaflet-marker",iconSize:[18,18]}),h=`
|
|
178
178
|
<div style="font-family:sans-serif; color:rgba(255, 255, 255, 0.9); line-height:1.35; min-width:180px;">
|
|
179
179
|
<div style="font-weight:800; font-size:11px; color:#fbbf24; text-transform:uppercase; letter-spacing:0.5px; border-bottom:1px solid rgba(255, 255, 255, 0.1); padding-bottom:3px; margin-bottom:5px;">Vértice Homologado SIGEF</div>
|
|
180
|
-
<div style="font-weight:700; font-size:13px; margin-bottom:3px; color:#ffffff;">${
|
|
180
|
+
<div style="font-weight:700; font-size:13px; margin-bottom:3px; color:#ffffff;">${M.escapeHtml(c.codigo_completo||c.nome_vertice)}</div>
|
|
181
181
|
<div style="font-size:11px; color:rgba(255, 255, 255, 0.7); font-family:monospace;">Este (E): ${c.este?c.este.toFixed(2):"N/A"} m</div>
|
|
182
182
|
<div style="font-size:11px; color:rgba(255, 255, 255, 0.7); font-family:monospace; margin-bottom:3px;">Norte (N): ${c.norte?c.norte.toFixed(2):"N/A"} m</div>
|
|
183
183
|
<div style="font-size:11px; color:rgba(255, 255, 255, 0.7); margin-bottom:2px;">Alt (h): <strong>${c.altitude?c.altitude.toFixed(2):"N/A"} m</strong></div>
|
|
184
|
-
<div style="font-size:10px; color:rgba(255, 255, 255, 0.45);">Método: ${
|
|
185
|
-
${c.confrontante_descritivo?`<div style="font-size:10px; color:rgba(255, 255, 255, 0.65); border-top:1px solid rgba(255, 255, 255, 0.1); padding-top:4px; margin-top:4px; word-break:break-word;"><strong>Conf:</strong> ${
|
|
184
|
+
<div style="font-size:10px; color:rgba(255, 255, 255, 0.45);">Método: ${M.escapeHtml(c.metodo_posicionamento)||"N/A"} · Limite: ${M.escapeHtml(c.tipo_limite)||"N/A"}</div>
|
|
185
|
+
${c.confrontante_descritivo?`<div style="font-size:10px; color:rgba(255, 255, 255, 0.65); border-top:1px solid rgba(255, 255, 255, 0.1); padding-top:4px; margin-top:4px; word-break:break-word;"><strong>Conf:</strong> ${M.escapeHtml(c.confrontante_descritivo)}</div>`:""}
|
|
186
186
|
</div>
|
|
187
|
-
`;
|
|
187
|
+
`;b.marker([c.lat,c.lon],{icon:d,pane:"verticesPane"}).bindPopup(h,{className:"compact-popup",maxWidth:220}).addTo(this.core.bancoPontosGroup)});const o=((n=this.core.controller)==null?void 0:n.chaveGrupo)||((s=(r=this.core.controller)==null?void 0:r.context)==null?void 0:s.chaveGrupo),i=M.agruparPontosPorChave(t,o);for(const c in i){const l=M.ordenarPontosPorSequencia(i[c]);if(l.length>=2){const d=l.map(h=>b.latLng(h.lat,h.lon));d.push(b.latLng(l[0].lat,l[0].lon)),b.polyline(d,{color:"#f59e0b",weight:this.core.config.bancoWeight,dashArray:"6, 8",pane:"perimetroPane"}).addTo(this.core.bancoPontosGroup)}}}clearLinhas(){this.core.map&&this.polylines.forEach(e=>this.core.map.removeLayer(e)),this.core.bancoPontosGroup&&this.core.bancoPontosGroup.clearLayers(),this.polylines=[]}}class Gn{constructor(e,t){f(this,"markers",[]);f(this,"vizinhosMarkers",[]);f(this,"vizinhosPoligonos",[]);f(this,"core");f(this,"controller");this.core=e,this.controller=t}plotPontos(e,t){this.core.map&&e.forEach(o=>{var i,n,r;if(o.lat&&o.lon&&o.lat!==0&&o.lon!==0){const s=o.tipo_ponto==="B"||o.tipo==="B",c=o.tipo_ponto==="M"||o.tipo==="M";let l="bg-mint-vibrant",d="x",h=7;c?(l="bg-indigo-500",h=9):s&&(l="bg-rose-500",h=9);const u=this.core.config.enableAnimations?"transition-all duration-150":"",g=(n=(i=this.controller)==null?void 0:i.linhas)!=null&&n.bancoPontosAtivo?"opacity-40 hover:opacity-100":"",v=ye(d,h,l,`${u} ${g}`,`map-marker-${o.id}`),p=b.divIcon({html:v,className:"custom-leaflet-marker flex items-center justify-center",iconSize:[h+6,h+6]}),y=c?"Base Homologada PPP":s?"Base de Campo (Translação)":"Vértice de Perímetro",A=b.marker([o.lat,o.lon],{icon:p,pane:"verticesPane"});A.pontoId=o.id,(r=this.controller)!=null&&r.modoCliqueSequencialAtivo||A.bindPopup(`
|
|
188
188
|
<div style="font-family:var(--ui-fonte-base, sans-serif); color:rgba(255, 255, 255, 0.9); line-height:1.3;">
|
|
189
|
-
<div style="font-weight:700; font-size:13px; margin-bottom:4px; color:#ffffff;">${
|
|
190
|
-
<div style="font-size:11px; color:rgba(255, 255, 255, 0.65);">${
|
|
189
|
+
<div style="font-weight:700; font-size:13px; margin-bottom:4px; color:#ffffff;">${M.escapeHtml(o.nome_vertice)}</div>
|
|
190
|
+
<div style="font-size:11px; color:rgba(255, 255, 255, 0.65);">${M.escapeHtml(y)} · ${M.escapeHtml(o.tipo_ponto||o.tipo)}</div>
|
|
191
191
|
<div style="font-size:11px; color:rgba(255, 255, 255, 0.45); font-family:var(--ui-fonte-codigo, monospace); margin-top:4px;">Lat ${o.lat.toFixed(6)} Lon ${o.lon.toFixed(6)}</div>
|
|
192
192
|
</div>
|
|
193
|
-
`,{className:"compact-popup",maxWidth:220}),A.addTo(this.core.map),A.setZIndexOffset(1e3),A.on("click",()=>{
|
|
193
|
+
`,{className:"compact-popup",maxWidth:220}),A.addTo(this.core.map),A.setZIndexOffset(1e3),A.on("click",()=>{t(o.id)}),this.markers.push(A)}})}plotPontosVizinhos(e){if(!this.core.map||!this.core.pontosVizinhosGroup)return;this.core.map.hasLayer(this.core.pontosVizinhosGroup)||this.core.pontosVizinhosGroup.addTo(this.core.map),this.vizinhosMarkers&&this.vizinhosMarkers.length>0&&(this.vizinhosMarkers.forEach(o=>{o.off(),o.unbindPopup()}),this.vizinhosMarkers=[]),this.core.pontosVizinhosGroup.clearLayers();const t=new Map;(e||[]).forEach(o=>{const i=o.lat??o.latitude??o.y,n=o.lon??o.lng??o.longitude??o.x,r=typeof i=="string"?parseFloat(i.replace(",",".")):Number(i),s=typeof n=="string"?parseFloat(n.replace(",",".")):Number(n);if(r!==void 0&&s!==void 0&&!isNaN(r)&&!isNaN(s)&&r!==0&&s!==0){o.lat=r,o.lon=s;const c=o.confrontante_id!==void 0&&o.confrontante_id!==null?String(o.confrontante_id):"0";t.has(c)||t.set(c,[]),t.get(c).push(o)}}),t.forEach(o=>{if(o.length>=2){o.sort((n,r)=>Number(n.id)-Number(r.id));const i=o.map(n=>b.latLng(n.lat,n.lon));o.length>2&&i.push(b.latLng(o[0].lat,o[0].lon)),b.polyline(i,{color:"#a855f7",weight:this.core.config.vizinhoWeight,dashArray:"4, 6",pane:"overlayPane"}).addTo(this.core.pontosVizinhosGroup)}o.forEach(i=>{var u,g;const n=document.createElement("div");n.className="p-2 font-sans text-xs bg-[#0c1510] text-white min-w-[200px] rounded",n.innerHTML=`
|
|
194
194
|
<div class="font-bold text-purple-400 mb-1 border-b border-white/10 pb-1">Confrontante (Importado)</div>
|
|
195
|
-
<div class="mb-1"><strong>Vértice:</strong> <span class="font-mono">${
|
|
196
|
-
<div class="mb-1"><strong>Proprietário:</strong> ${
|
|
197
|
-
<div class="mb-1"><strong>Propriedade:</strong> ${
|
|
195
|
+
<div class="mb-1"><strong>Vértice:</strong> <span class="font-mono">${M.escapeHtml(i.nome_vertice||"")}</span></div>
|
|
196
|
+
<div class="mb-1"><strong>Proprietário:</strong> ${M.escapeHtml(i.nome_confrontante||"")||"Desconhecido"}</div>
|
|
197
|
+
<div class="mb-1"><strong>Propriedade:</strong> ${M.escapeHtml(i.nome_propriedade||"")||"Desconhecida"}</div>
|
|
198
198
|
<div class="mb-1"><strong>Coordenadas:</strong> ${i.lat.toFixed(7)}, ${i.lon.toFixed(7)}</div>
|
|
199
199
|
<div class="text-[10px] text-white/50 border-t border-white/5 pt-1 mt-1 font-mono uppercase tracking-wider mb-2">Pontos Imutáveis do Vizinho</div>
|
|
200
200
|
<div style="display:flex; gap:6px; border-top:1px solid rgba(255,255,255,0.1); padding-top:6px;">
|
|
@@ -205,10 +205,10 @@
|
|
|
205
205
|
Ocultar
|
|
206
206
|
</button>
|
|
207
207
|
</div>
|
|
208
|
-
`,(u=n.querySelector(".btn-integrar"))==null||u.addEventListener("click",()=>{window.dispatchEvent(new CustomEvent("gerencigeo:integrar_vizinho",{detail:{pontoId:i.id}}))}),(g=n.querySelector(".btn-ocultar"))==null||g.addEventListener("click",()=>{window.dispatchEvent(new CustomEvent("gerencigeo:ocultar_vizinho",{detail:{pontoId:i.id}}))});let r=this.core.config.markerStyleV||"cross",s=this.core.config.markerSizeV||8;i.tipo_ponto==="M"||i.tipo==="M"||i.tipo==="B"?(r=this.core.config.markerStyleM||"circle-dot",s=this.core.config.markerSizeM||14):(i.tipo_ponto==="P"||i.tipo==="P"||i.tipo==="O")&&(r=this.core.config.markerStyleP||"circle",s=this.core.config.markerSizeP||10);const c=this.core.config.enableAnimations?"transition-all duration-150":"",l=
|
|
208
|
+
`,(u=n.querySelector(".btn-integrar"))==null||u.addEventListener("click",()=>{window.dispatchEvent(new CustomEvent("gerencigeo:integrar_vizinho",{detail:{pontoId:i.id}}))}),(g=n.querySelector(".btn-ocultar"))==null||g.addEventListener("click",()=>{window.dispatchEvent(new CustomEvent("gerencigeo:ocultar_vizinho",{detail:{pontoId:i.id}}))});let r=this.core.config.markerStyleV||"cross",s=this.core.config.markerSizeV||8;i.tipo_ponto==="M"||i.tipo==="M"||i.tipo==="B"?(r=this.core.config.markerStyleM||"circle-dot",s=this.core.config.markerSizeM||14):(i.tipo_ponto==="P"||i.tipo==="P"||i.tipo==="O")&&(r=this.core.config.markerStyleP||"circle",s=this.core.config.markerSizeP||10);const c=this.core.config.enableAnimations?"transition-all duration-150":"",l=ye(r,s,"bg-[#a855f7]",c,`map-marker-vizinho-${i.id}`),d=b.divIcon({html:l,className:"custom-leaflet-marker flex items-center justify-center",iconSize:[s+4,s+4]}),h=b.marker([i.lat,i.lon],{icon:d,pane:"overlayPane"}).bindPopup(n,{className:"custom-leaflet-popup"});h.pontoId=i.id,h.isVizinho=!0,h.addTo(this.core.pontosVizinhosGroup),this.vizinhosMarkers.push(h)})})}plotPoligonosVizinhos(e){!this.core.map||!this.core.pontosVizinhosGroup||(this.core.map.hasLayer(this.core.pontosVizinhosGroup)||this.core.pontosVizinhosGroup.addTo(this.core.map),this.vizinhosPoligonos.length>0&&(this.vizinhosPoligonos.forEach(t=>t.off()),this.vizinhosPoligonos=[]),(e||[]).forEach(t=>{if(!t||!t.poligono_wkt)return;const o=/POLYGON\s*\(\s*\(\s*(.*?)\s*\)\s*\)/i.exec(t.poligono_wkt);if(!o)return;const i=o[1].split(",").map(c=>{const l=c.trim().split(/\s+/),d=parseFloat(l[0]),h=parseFloat(l[1]);return!isNaN(h)&&!isNaN(d)?[h,d]:null}).filter(c=>c!==null);if(i.length<3)return;const n=M.escapeHtml(t.nome_propriedade||"Propriedade Vizinha"),r=M.escapeHtml(t.nome||"Desconhecido"),s=b.polygon(i,{color:"#a855f7",weight:this.core.config.vizinhoWeight,dashArray:"4, 6",fillColor:"#a855f7",fillOpacity:.05,pane:"overlayPane"}).bindPopup(`
|
|
209
209
|
<div class="p-2 font-sans text-xs bg-[#0c1510] text-white min-w-[200px] rounded">
|
|
210
210
|
<div class="font-bold text-purple-400 mb-1 border-b border-white/10 pb-1">Limite do Vizinho (Importado)</div>
|
|
211
211
|
<div class="mb-1"><strong>Propriedade:</strong> ${n}</div>
|
|
212
212
|
<div class="mb-1"><strong>Proprietário:</strong> ${r}</div>
|
|
213
213
|
</div>
|
|
214
|
-
`,{className:"custom-leaflet-popup"});s.addTo(this.core.pontosVizinhosGroup),this.vizinhosPoligonos.push(s)}))}clearMarkers(){this.markers&&(this.markers.forEach(
|
|
214
|
+
`,{className:"custom-leaflet-popup"});s.addTo(this.core.pontosVizinhosGroup),this.vizinhosPoligonos.push(s)}))}clearMarkers(){this.markers&&(this.markers.forEach(e=>{e.off(),e.unbindPopup(),this.core.map&&this.core.map.removeLayer(e)}),this.markers=[]),this.vizinhosMarkers&&(this.vizinhosMarkers.forEach(e=>{e.off(),e.unbindPopup()}),this.vizinhosMarkers=[]),this.vizinhosPoligonos&&(this.vizinhosPoligonos.forEach(e=>e.off()),this.vizinhosPoligonos=[]),this.core.pontosVizinhosGroup&&this.core.pontosVizinhosGroup.clearLayers()}}exports.agruparPontosPorChave=M.agruparPontosPorChave;exports.bindPopupAcoesEvents=M.bindPopupAcoesEvents;exports.escapeHtml=M.escapeHtml;exports.extrairCentroDeWkt=M.extrairCentroDeWkt;exports.formatUTM=M.formatUTM;exports.ordenarPontosPorSequencia=M.ordenarPontosPorSequencia;exports.parseCoordenada=M.parseCoordenada;exports.renderPopupAcoesHtml=M.renderPopupAcoesHtml;exports.AgrupadorCluster=m.AgrupadorCluster;exports.CELULA_CLUSTER_PX=m.CELULA_CLUSTER_PX;exports.COR_PADRAO=m.COR_PADRAO;exports.COR_SELECAO=m.COR_SELECAO;exports.DadosCamada=m.DadosCamada;exports.IndiceEspacial=m.IndiceEspacial;exports.InternadorEstilos=m.InternadorEstilos;exports.LIMITE_MARCA_PX=m.LIMITE_MARCA_PX;exports.MAX_PONTOS_SEM_CLUSTER=m.MAX_PONTOS_SEM_CLUSTER;exports.MIN_VERTICES_SIMPLIFICAR=m.MIN_VERTICES_SIMPLIFICAR;exports.MotorFormas=m.MotorFormas;exports.OPACIDADE_MARCA=m.OPACIDADE_MARCA;exports.RegraVersoes=m.RegraVersoes;exports.ZOOM_DESMEMBRAR=m.ZOOM_DESMEMBRAR;exports.ZOOM_SEM_SIMPLIFICACAO=m.ZOOM_SEM_SIMPLIFICACAO;exports.agruparMarcasPorCor=m.agruparMarcasPorCor;exports.agruparPontos=m.agruparPontos;exports.areaDaGeometria=m.areaDaGeometria;exports.areaMetros2=m.areaMetros2;exports.caixaDaFeicao=m.caixaDaFeicao;exports.caixaPx=m.caixaPx;exports.caixasSeTocam=m.caixasSeTocam;exports.centroDe=m.centroDe;exports.comprimentoMetros=m.comprimentoMetros;exports.corSegura=m.corSegura;exports.criarLinha=m.criarLinha;exports.deveAgrupar=m.deveAgrupar;exports.diagonalPx=m.diagonalPx;exports.distanciaMetros=m.distanciaMetros;exports.ehMarca=m.ehMarca;exports.ehMultilinha=m.ehMultilinha;exports.entidadeDe=m.entidadeDe;exports.escalaDoZoom=m.escalaDoZoom;exports.escalaLatitude=m.escalaLatitude;exports.estiloVetorDe=m.estiloVetorDe;exports.extensaoDaGeometria=m.extensaoDaGeometria;exports.formatarArea=m.formatarArea;exports.formatarExtensao=m.formatarExtensao;exports.ladoMarca=m.ladoMarca;exports.latLonDoMundo=m.latLonDoMundo;exports.limitesDaGeometria=m.limitesDaGeometria;exports.metrosPorGrau=m.metrosPorGrau;exports.metrosPorPixel=m.metrosPorPixel;exports.partesDaLinha=m.partesDaLinha;exports.pintarMarcas=m.pintarMarcas;exports.projetarCentro=m.projetarCentro;exports.projetarEm=m.projetarEm;exports.projetarMercator=m.projetarMercator;exports.projetarVertices=m.projetarVertices;exports.raioCirculoPx=m.raioCirculoPx;exports.raioPontoPx=m.raioPontoPx;exports.simplificarAnel=m.simplificarAnel;exports.simplificarGeometria=m.simplificarGeometria;exports.simplificarLinha=m.simplificarLinha;exports.simplificarPx=m.simplificarPx;exports.statusDe=m.statusDe;exports.textoRotulo=m.textoRotulo;exports.toleranciaPorZoom=m.toleranciaPorZoom;exports.vertices=m.vertices;exports.CADMapaController=Ye;exports.CAD_INTERACTIVE_PANES=uo;exports.CLASSE_FERRAMENTA_ATIVA=xt;exports.CSS_POSICAO_HUD=qt;exports.CanvasCADController=Ye;exports.CanvasFormas=be;exports.CanvasInteracao=yo;exports.CanvasLayerManager=ni;exports.ControleDesenho=Ai;exports.CursoresRemotos=gi;exports.DEFAULT_CONFIG=lt;exports.DEFAULT_LAYERS=gt;exports.DespachanteFeicoes=ai;exports.EditorVertices=Ei;exports.FERRAMENTAS=Ze;exports.FOLGA_HUD=Ci;exports.FRACAO_LARGURA_HUD=Li;exports.FeicaoPopup=yi;exports.FeicoesCanvasRenderer=ii;exports.FeicoesLayerRenderer=ei;exports.GerenciGeoMapaController=Ye;exports.GridLayerRenderer=Ao;exports.ICONES_FEICAO=Ue;exports.ID_HUD_DESENHO=Mi;exports.ID_HUD_EDICAO=wi;exports.LIMIAR_DENSIDADE_ALTA=He;exports.LIMITE_CULLING=qe;exports.LayerRendererFactory=N;exports.MARGEM_HUD_PADRAO=Pi;exports.MAX_VERTICES_EDICAO=$o;exports.MapaConfigManager=Re;exports.MapaCore=ho;exports.MapaLinhas=Hn;exports.MapaMarcadores=Gn;exports.PROPRIEDADES_HUD=Ne;exports.PintorCanvas2D=Dt;exports.RAIO_MINIMO_CIRCULO_M=bt;exports.RAIO_MINIMO_EDICAO_CIRCULO_M=Vo;exports.SelecaoFeicoes=vi;exports.SessaoDesenho=$e;exports.TOLERANCIA_AMOSTRA_PX=Ko;exports.TOLERANCIA_LINHA_PX=Ie;exports.TOLERANCIA_PONTO_PX=mo;exports.TOLERANCIA_SNAP_PX=Ot;exports.TileLayerRenderer=bo;exports.UICanvasCAD=Di;exports.VectorLinesLayerRenderer=Co;exports.VectorPointsLayerRenderer=So;exports.VectorPolygonsLayerRenderer=Mo;exports.WmsLayerRenderer=xo;exports.alternarSuavidade=Yo;exports.amostrarBezier=xi;exports.aplicarMargensHud=Si;exports.buscarSnap=zi;exports.clonarFeicao=De;exports.comPontos=Go;exports.comVertices=Ce;exports.confrontanteParaFeicao=tn;exports.consultarFeicoesNoPonto=At;exports.contarItensCanvas=pt;exports.converterArea=Qi;exports.converterComprimento=Ji;exports.coordenadaDeReferencia=xe;exports.corHexSegura=We;exports.criarControladorTamanho=pi;exports.ddParaDms=ea;exports.deslocarGeometria=Oo;exports.distanciaEntre=oa;exports.dividirPoligonoComLinha=Do;exports.dmsParaDd=ta;exports.ehFerramenta=Ft;exports.extrairCorPonto=Lo;exports.fatorDensidade=wt;exports.feicaoNaCaixa=ki;exports.feicaoNoLaco=Ii;exports.feicaoNoPonto=Le;exports.feicaoNoTopo=Zi;exports.garantirCanvasSemEventos=go;exports.gerarBuffer=qo;exports.getPointShapeHtml=ye;exports.inserirPonto=Uo;exports.inserirVertice=Ro;exports.juntarLinhas=To;exports.juntarPoligonos=Fo;exports.lerModoRenderizador=ge;exports.minimoVertices=Pe;exports.modoDensidade=Ge;exports.moverAlca=Xo;exports.moverVertice=ia;exports.normalizarAnel=Tt;exports.normalizarCoordenada=Z;exports.normalizarFeicaoEntrada=Oe;exports.normalizarLinha=yt;exports.normalizarPoligono=mi;exports.nosDe=W;exports.nosDeAncoras=ve;exports.parseDash=ti;exports.pontoDaBordaDoCirculo=Ho;exports.pontoMedio=kt;exports.pontoMedioDoSegmento=_e;exports.pontoNoPoligono=zt;exports.pontoParaFeicao=Qa;exports.pontosDe=me;exports.posicaoHud=Pn;exports.processarAcaoPopup=di;exports.processarCliqueLivreCanvas=li;exports.regioesExpostas=oi;exports.registrarFonteHit=St;exports.removerFonteHit=Mt;exports.removerPonto=Wo;exports.removerVertice=Bo;exports.renderizarPainelCamadas=si;exports.resolverCliqueCentral=vo;exports.segmentoParaFeicao=en;exports.segmentosDe=It;exports.segmentosDoEditor=jo;exports.tratarCliqueMarcador=hi;exports.tratarCliqueSegmento=ui;exports.verificarEditavel=No;exports.verticesDe=X;
|