@thibezer/ui-components-kit 2.8.1 → 2.8.2
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 +22 -103
- package/README.md +8 -32
- package/dist/botao.cjs +1 -1
- package/dist/botao.js +1 -1
- package/dist/camadas.cjs +110 -114
- package/dist/camadas.js +1177 -1343
- package/dist/campo-texto.cjs +1 -1
- package/dist/campo-texto.js +1 -1
- package/dist/canvas.cjs +63 -64
- package/dist/canvas.js +3544 -4025
- package/dist/card.cjs +1 -1
- package/dist/card.js +1 -1
- package/dist/components/ui-avatar/ui-avatar.d.ts +0 -11
- package/dist/components/ui-badge/ui-badge.d.ts +0 -2
- package/dist/components/ui-barra-ferramentas/ferramentas-comum.d.ts +22 -1
- package/dist/components/ui-barra-ferramentas/tipos.d.ts +31 -0
- package/dist/components/ui-barra-ferramentas/ui-paleta-ferramentas.d.ts +17 -1
- package/dist/components/ui-barra-ferramentas/ui-ribbon.d.ts +17 -0
- package/dist/components/ui-camadas/camadas-arraste-controles.d.ts +0 -2
- package/dist/components/ui-camadas/camadas-arvore-renderer.d.ts +11 -4
- package/dist/components/ui-camadas/camadas-drag-drop.d.ts +1 -13
- package/dist/components/ui-camadas/camadas-host.d.ts +0 -1
- package/dist/components/ui-camadas/camadas-mapas-base.d.ts +1 -3
- package/dist/components/ui-camadas/camadas-selecao.d.ts +0 -12
- package/dist/components/ui-camadas/ui-camadas.d.ts +5 -8
- package/dist/components/ui-canvas-cad/cad-atributos-sync.d.ts +1 -2
- package/dist/components/ui-canvas-cad/cad-broadcast.d.ts +1 -1
- package/dist/components/ui-canvas-cad/cad-eventos-canvas.d.ts +8 -3
- package/dist/components/ui-canvas-cad/cad-feicoes.d.ts +106 -39
- package/dist/components/ui-canvas-cad/cad-inicializador.d.ts +1 -3
- package/dist/components/ui-canvas-cad/ui-canvas-cad.d.ts +1 -15
- package/dist/components/ui-checkbox/ui-checkbox.d.ts +1 -4
- package/dist/components/ui-cores/tipos.d.ts +0 -2
- package/dist/components/ui-cores/ui-controle-cores.d.ts +3 -8
- package/dist/components/ui-cores/ui-seletor-cor.d.ts +1 -3
- package/dist/components/ui-mapa/ui-mapa-linha.d.ts +5 -12
- package/dist/components/ui-mapa/ui-mapa-marcador.d.ts +6 -15
- package/dist/components/ui-mapa/ui-mapa.d.ts +1 -14
- package/dist/components/ui-modal/modal-acessibilidade.d.ts +5 -5
- package/dist/components/ui-modal/ui-modal.d.ts +11 -1
- package/dist/components/ui-radio/radio-grupo-registry.d.ts +0 -10
- package/dist/components/ui-radio/ui-radio.d.ts +2 -9
- package/dist/components/ui-skeleton/ui-skeleton.d.ts +0 -9
- package/dist/components/ui-switch/ui-switch.d.ts +1 -3
- package/dist/components/ui-tabela/ui-tabela.d.ts +19 -1
- package/dist/components/ui-tooltip/ui-tooltip.d.ts +1 -24
- package/dist/core/index.d.ts +0 -1
- package/dist/core.cjs +1 -1
- package/dist/core.js +18 -28
- package/dist/cores.cjs +1 -1
- package/dist/cores.js +1 -1
- package/dist/custom-elements.json +13585 -18764
- package/dist/data.cjs +1 -1
- package/dist/data.js +2 -2
- package/dist/feedback.cjs +1 -1
- package/dist/feedback.js +2 -2
- package/dist/form-validacao-BIOXxt-1.js +140 -0
- package/dist/form-validacao-ytRYSF3E.cjs +1 -0
- package/dist/forms.cjs +1 -1
- package/dist/forms.js +2 -2
- package/dist/gerencigeo-canvas/canvas_interacao.d.ts +1 -0
- package/dist/gerencigeo-canvas/feature_metricas.d.ts +9 -0
- package/dist/gerencigeo-canvas/feature_popup.d.ts +0 -2
- package/dist/gerencigeo-canvas/mapa_core.d.ts +0 -6
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +0 -3
- package/dist/index.js +176 -179
- package/dist/mapa.cjs +16 -11
- package/dist/mapa.js +170 -242
- package/dist/modal.cjs +1 -1
- package/dist/modal.js +1 -1
- package/dist/register.cjs +1 -1
- package/dist/register.js +11 -11
- 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 +20 -48
- package/dist/tipos-react.d.ts +0 -2
- package/dist/tipos-vue.d.ts +15 -44
- package/dist/tools.cjs +1 -1
- package/dist/tools.js +1 -1
- package/dist/ui-badge-BxT-sDmV.cjs +28 -0
- package/dist/ui-badge-C0eKBI8E.js +183 -0
- package/dist/ui-botao-BOOnP8ds.cjs +12 -0
- package/dist/ui-botao-DfqSivHl.js +165 -0
- package/dist/ui-botao-OGJV6Vfk.js +165 -0
- package/dist/ui-botao-psS1juof.cjs +12 -0
- package/dist/ui-campo-texto-Cnn2UAkS.cjs +16 -0
- package/dist/{ui-campo-texto-B_OHVGiN.js → ui-campo-texto-Uu2dJE_0.js} +51 -51
- package/dist/ui-card-B86lJXTP.cjs +20 -0
- package/dist/{ui-card-BNYCQ7g-.js → ui-card-C_o5_0cB.js} +42 -50
- package/dist/ui-controle-cores-BS0WYPdi.js +572 -0
- package/dist/ui-controle-cores-Er6ZcQ7U.cjs +111 -0
- package/dist/ui-kit.css +1 -1
- package/dist/ui-modal-CvGFGh1h.cjs +18 -0
- package/dist/{ui-modal-BkYvNP0G.js → ui-modal-DBOtSTbR.js} +140 -116
- package/dist/ui-paleta-ferramentas-CEZYcN4J.js +624 -0
- package/dist/ui-paleta-ferramentas-CU4icLl0.js +1171 -0
- package/dist/{ui-paleta-ferramentas-bDLPbiGA.cjs → ui-paleta-ferramentas-Ccmo-rB5.cjs} +7 -7
- package/dist/ui-paleta-ferramentas-DLwZHIDv.cjs +21 -0
- package/dist/{ui-paleta-ferramentas-Ksh6gMW3.js → ui-paleta-ferramentas-DNN5i6nL.js} +329 -359
- package/dist/ui-paleta-ferramentas-Dbj1kBS9.cjs +18 -0
- package/dist/ui-paleta-ferramentas-DbwdWVtT.js +1173 -0
- package/dist/ui-paleta-ferramentas-bvqxj1Yd.cjs +21 -0
- package/dist/ui-segmented-D6b6zxVs.cjs +19 -0
- package/dist/ui-segmented-DyF5YLsV.js +418 -0
- package/dist/ui-segmented-rn9RxRGM.cjs +19 -0
- package/dist/{ui-linha-nCDh2wPm.js → ui-segmented-wUraId2e.js} +105 -200
- package/dist/ui-skeleton-DI4_9WOX.js +428 -0
- package/dist/{ui-skeleton-DiOxTBZK.cjs → ui-skeleton-SPYqku8P.cjs} +10 -10
- package/dist/{ui-skeleton-B2Rgrv8o.js → ui-skeleton-W9uwIceA.js} +191 -254
- package/dist/ui-skeleton-elhKIh2B.cjs +33 -0
- package/dist/{ui-switch-DO1R0Ce7.js → ui-switch-BcOqOkiV.js} +128 -187
- package/dist/ui-switch-D7iPKDj-.cjs +53 -0
- package/dist/ui-tabela-propriedades-BBr5sqki.cjs +145 -0
- package/dist/{ui-tabela-propriedades-DzZlyNZ_.cjs → ui-tabela-propriedades-BecPqC-e.cjs} +10 -10
- package/dist/{ui-tabela-propriedades-D9Echt2X.js → ui-tabela-propriedades-BokvDD3b.js} +826 -845
- package/dist/ui-tabela-propriedades-Boy7I5yW.js +2412 -0
- package/dist/ui-tabela-propriedades-C-PeuW1i.cjs +141 -0
- package/dist/ui-tabela-propriedades-Df9ajC6M.js +2648 -0
- package/dist/ui-toast-Bp_NlM5G.js +156 -0
- package/dist/ui-toast-DGTZKne5.cjs +20 -0
- package/dist/zero-js-triggers-C_KrvFOQ.js +244 -0
- package/dist/zero-js-triggers-C_gtaojZ.cjs +1 -0
- package/package.json +3 -3
- package/dist/acessibilidade-CSzX-DkG.cjs +0 -1
- package/dist/acessibilidade-CUlSXc2X.js +0 -38
- package/dist/altura-controle-ukMRPckR.cjs +0 -1
- package/dist/altura-controle-vxQiXG4q.js +0 -62
- package/dist/components/ui-barra-ferramentas/paleta-atalhos.d.ts +0 -16
- package/dist/components/ui-barra-ferramentas/paleta-pressao-longa.d.ts +0 -24
- package/dist/components/ui-barra-ferramentas/ribbon-render.d.ts +0 -14
- package/dist/components/ui-barra-ferramentas/ribbon-teclado.d.ts +0 -17
- package/dist/components/ui-camadas/camadas-colecao.d.ts +0 -27
- package/dist/components/ui-camadas/camadas-drop-ops.d.ts +0 -31
- package/dist/components/ui-camadas/camadas-hierarquia.d.ts +0 -10
- package/dist/components/ui-camadas/camadas-lembranca.d.ts +0 -34
- package/dist/components/ui-camadas/camadas-render.d.ts +0 -15
- package/dist/components/ui-camadas/camadas-renomear.d.ts +0 -12
- package/dist/components/ui-camadas/camadas-selecao-api.d.ts +0 -17
- package/dist/components/ui-camadas/camadas-thumb.d.ts +0 -1
- package/dist/components/ui-canvas-cad/cad-acessibilidade.d.ts +0 -15
- package/dist/components/ui-canvas-cad/cad-evento-coordenadas.d.ts +0 -22
- package/dist/components/ui-canvas-cad/cad-feicoes-camera.d.ts +0 -26
- package/dist/components/ui-canvas-cad/cad-feicoes-consulta.d.ts +0 -21
- package/dist/components/ui-canvas-cad/cad-feicoes-dados.d.ts +0 -39
- package/dist/components/ui-canvas-cad/cad-feicoes-desenho.d.ts +0 -68
- package/dist/components/ui-canvas-cad/cad-feicoes-edicao.d.ts +0 -37
- package/dist/components/ui-canvas-cad/cad-feicoes-operacoes.d.ts +0 -48
- package/dist/components/ui-canvas-cad/cad-feicoes-ponteiro.d.ts +0 -28
- package/dist/components/ui-canvas-cad/cad-feicoes-selecao-regiao.d.ts +0 -22
- package/dist/components/ui-canvas-cad/cad-feicoes-tipos.d.ts +0 -53
- package/dist/components/ui-canvas-cad/cad-feicoes-versoes.d.ts +0 -33
- package/dist/components/ui-canvas-cad/cad-leaflet-adaptador.d.ts +0 -5
- package/dist/components/ui-canvas-cad/cad-selecao-pontos.d.ts +0 -5
- package/dist/components/ui-canvas-cad/tipos.d.ts +0 -37
- package/dist/components/ui-linha/index.d.ts +0 -1
- package/dist/components/ui-linha/ui-linha.d.ts +0 -48
- package/dist/components/ui-mapa/mapa-atributos.d.ts +0 -14
- package/dist/components/ui-mapa/mapa-basemaps.d.ts +0 -7
- package/dist/components/ui-mapa/mapa-icones.d.ts +0 -4
- package/dist/components/ui-mapa/mapa-leaflet.d.ts +0 -5
- package/dist/components/ui-mapa/mapa-vinculo-pai.d.ts +0 -22
- package/dist/components/ui-mapa/tipos.d.ts +0 -13
- package/dist/components/ui-modal/modal-foco.d.ts +0 -28
- package/dist/components/ui-tabela/tabela-estados.d.ts +0 -16
- package/dist/components/ui-tabela/tabela-rolagem.d.ts +0 -44
- package/dist/components/ui-tabela/tabela-teclado.d.ts +0 -16
- package/dist/components/ui-tooltip/tooltip-popover.d.ts +0 -7
- package/dist/components/ui-tooltip/tooltip-posicionamento.d.ts +0 -29
- package/dist/core/altura-controle.d.ts +0 -34
- package/dist/core/opcoes.d.ts +0 -9
- package/dist/core/rotulo-controle.d.ts +0 -13
- package/dist/form-validacao-BlQFxUVj.js +0 -104
- package/dist/form-validacao-DIeyQVH5.cjs +0 -1
- package/dist/gerencigeo-canvas/popup_gate.d.ts +0 -30
- package/dist/gerencigeo-canvas/zoom_opcoes.d.ts +0 -10
- package/dist/opcoes-CJYLi6kd.js +0 -12
- package/dist/opcoes-CkyDxBuQ.cjs +0 -1
- package/dist/ui-badge-BWhoGgo9.js +0 -197
- package/dist/ui-badge-SIR81R9l.cjs +0 -28
- package/dist/ui-botao-D24oXySA.cjs +0 -12
- package/dist/ui-botao-Dsj08jjw.js +0 -165
- package/dist/ui-campo-texto-DauJCde3.cjs +0 -16
- package/dist/ui-card-BrjBL-yo.cjs +0 -20
- package/dist/ui-controle-cores-DgEza3wF.js +0 -612
- package/dist/ui-controle-cores-uY__TgwW.cjs +0 -117
- package/dist/ui-linha-C6HBnsaw.cjs +0 -19
- package/dist/ui-modal-CUNbpbZ1.cjs +0 -18
- package/dist/ui-switch-D9a8XlVX.cjs +0 -53
package/dist/canvas.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var tn=Object.defineProperty;var en=(n,t,e)=>t in n?tn(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e;var p=(n,t,e)=>en(n,typeof t!="symbol"?t+"":t,e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});;/* empty css */const y=require("leaflet"),S=require("./leaflet-DcO7uRC-.cjs"),ye=require("./listener-bag-D5omxZ9h.cjs"),Ao=require("./ssr-safe-CiHD1adl.cjs"),xe={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},ht=class ht{constructor(){p(this,"config");this.config=this.loadConfig()}static getInstance(){return ht.instance||(ht.instance=new ht),ht.instance}loadConfig(){try{const t=typeof localStorage<"u"?localStorage.getItem("gerencigeo_mapa_config"):null;if(t)return{...xe,...JSON.parse(t)}}catch(t){console.error("Erro ao carregar configurações do mapa",t)}return{...xe}}saveConfig(t){this.config={...this.config,...t},typeof localStorage<"u"&&localStorage.setItem("gerencigeo_mapa_config",JSON.stringify(this.config))}getConfig(){return this.config=this.loadConfig(),{...this.config}}};p(ht,"instance");let Ut=ht;async function on(n,t,e,o){const i=n.getSize(),a=n.getBounds(),s=a.getSouthWest(),r=a.getNorthEast(),c=`${s.lng},${s.lat},${r.lng},${r.lat}`;let l=0,d=0;try{if(t.containerPoint)l=Math.round(t.containerPoint.x),d=Math.round(t.containerPoint.y);else if(t.layerPoint){const x=n.layerPointToContainerPoint(t.layerPoint);l=Math.round(x.x),d=Math.round(x.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=n.getContainer();u.style.cursor="wait";const f=y.popup({className:"compact-sigef-popup",maxWidth:250}).setLatLng(t.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
|
+
`).openOn(n);o.currentAbortController&&o.currentAbortController.abort(),o.currentAbortController=new AbortController;const m=o.currentAbortController.signal,g=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]"))?`${e}/proxy/sigef?url=${encodeURIComponent(h)}`:`${window.location.origin}/api.php?action=proxy_sigef&url=${encodeURIComponent(h)}`,M=await fetch(A,{signal:m});clearTimeout(g);let C=null;if(M.ok){const z=await M.text();try{C=JSON.parse(z)}catch{C=null}}if(C&&C.features&&C.features.length>0){const z=C.features[0],P=z.properties||{},v=String(z.id||P.parcela_codigo||P.co_parcela||P.id_parcela||""),b=String(P.nome_area||P.nome_imovel||"Imóvel Sem Nome");if(v){const w=encodeURIComponent(v),E=`https://sigef.incra.gov.br/geo/exportar/parcela/shp/${w}/`,L=`https://sigef.incra.gov.br/geo/parcela/detalhe/${w}/`,k=document.createElement("div");k.style.cssText="font-family:var(--ui-fonte-base, sans-serif); color:rgba(255, 255, 255, 0.9); line-height:1.4; min-width:180px;",k.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
12
|
<span style="font-size:10px; color:rgba(255, 255, 255, 0.5);">${S.escapeHtml(P.situacao_informada||P.status||"Certificada")}</span>
|
|
13
13
|
</div>
|
|
14
|
-
<div style="font-weight:700; font-size:12px; margin-bottom:4px; color:#ffffff; word-break:break-word;">${S.escapeHtml(
|
|
14
|
+
<div style="font-weight:700; font-size:12px; margin-bottom:4px; color:#ffffff; word-break:break-word;">${S.escapeHtml(b)}</div>
|
|
15
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);">${S.escapeHtml(P.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
17
|
<span>Mat: <strong style="color:#ffffff;">${S.escapeHtml(P.registro_matricula||P.matricula||"N/A")}</strong></span>
|
|
18
18
|
<span>${S.escapeHtml(P.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="${E}" 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>
|
|
@@ -31,109 +31,109 @@
|
|
|
31
31
|
Abrir no SIGEF
|
|
32
32
|
</a>
|
|
33
33
|
</div>
|
|
34
|
-
`;const I=
|
|
34
|
+
`;const I=k.querySelector(".btn-importar-confrontante-sigef");I&&I.addEventListener("click",()=>{window.dispatchEvent(new CustomEvent("gerencigeo:importar_vizinho_sigef",{detail:{uuid:v,nome:b}}))}),f.setContent(k)}else f.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>
|
|
38
|
-
`)}else
|
|
38
|
+
`)}else f.setContent(`
|
|
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(x){x.name==="AbortError"?f.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:",x),f.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 nn(n,t){if(!n)return;const e=Math.floor(n.getZoom()),o=Math.max(e,12),i=Math.min(e+1,19),a=t.pad(.2),s=["mt0","mt1","mt2","mt3"];let r=0;const c=32;for(let l=o;l<=i&&r<c;l++){const d=a.getNorthWest(),h=a.getSouthEast(),u=Xe(d.lng,l),f=Xe(h.lng,l),m=Ze(d.lat,l),g=Ze(h.lat,l);for(let x=u;x<=f&&r<c;x++)for(let A=m;A<=g&&r<c;A++){const C=`https://${s[(x+A)%s.length]}.google.com/vt/lyrs=s,h&x=${x}&y=${A}&z=${l}`,z=new Image;z.src=C,r++}}}function Xe(n,t){return Math.floor((n+180)/360*Math.pow(2,t))}function Ze(n,t){const e=n*Math.PI/180;return Math.floor((1-Math.log(Math.tan(e)+1/Math.cos(e))/Math.PI)/2*Math.pow(2,t))}class wo{constructor(t){p(this,"map",null);p(this,"configManager",Ut.getInstance());p(this,"config",this.configManager.getConfig());p(this,"apiBaseUrl","/api");p(this,"bancoPontosGroup",y.layerGroup());p(this,"pontosVizinhosGroup",y.layerGroup());p(this,"controller");p(this,"containerElement",null);p(this,"bc");p(this,"sigefState",{});this.controller=t}init(t){if(this.map)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=y.map(e,{maxZoom:24,scrollWheelZoom:!0,preferCanvas:this.config.preferCanvas!==void 0?this.config.preferCanvas:!0,zoomControl:!1}).setView([-23.7661,-53.3204],14),this.listenConfigBroadcast(),this.applyMapStyles(),!this.map.getPane("sigefPane")){const o=this.map.createPane("sigefPane");o.style.zIndex="390"}if(!this.map.getPane("perimetroPane")){const o=this.map.createPane("perimetroPane");o.style.zIndex="520"}if(!this.map.getPane("verticesPane")){const o=this.map.createPane("verticesPane");o.style.zIndex="650"}return y.control.scale({metric:!0,imperial:!1,position:"bottomleft"}).addTo(this.map),this.map.on("click",o=>{if(this.controller.modoCliqueSequencialAtivo||this.controller.canvasInteracao&&this.controller.canvasInteracao.selectionHappened)return;(this.controller.layerManager?this.controller.layerManager.isLayerActiveAndSelectable("sigef"):!1)&&this.consultarSigef(o)}),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(){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)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){nn(this.map,t)}async consultarSigef(t){this.map&&await on(this.map,t,this.apiBaseUrl,this.sigefState)}}function Ye(n){if(!n)return!1;const t=n;return t.tagName==="INPUT"||t.tagName==="TEXTAREA"||t.tagName==="SELECT"||t.isContentEditable===!0}function Ie(n){var o,i;const t=(o=n==null?void 0:n.composedPath)==null?void 0:o.call(n)[0];if(t instanceof Element)return Ye(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 Ye(e)}const ko=["verticesPane","perimetroPane","overlayPane","markerPane","pane-vertices","pane-perimetro","pane-vizinhos","pane-homologados","pane-homologados-pontos"];class an{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){ko.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,a=Math.abs(o-this.selectStartPos.x),s=Math.abs(i-this.selectStartPos.y),r=Math.min(o,this.selectStartPos.x),c=Math.min(i,this.selectStartPos.y);this.selectionDiv.style.left=`${Math.round(r)}px`,this.selectionDiv.style.top=`${Math.round(c)}px`,this.selectionDiv.style.width=`${Math.round(a)}px`,this.selectionDiv.style.height=`${Math.round(s)}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,z,P,v,b,w,E,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(),a=t.clientX-i.left,s=t.clientY-i.top,r=this.map.mouseEventToContainerPoint(t),c=Math.abs(a-this.selectStartPos.x),l=Math.abs(s-this.selectStartPos.y);if(c<4&&l<4){const k=t.target;if(k&&((C=k.classList)!=null&&C.contains("leaflet-container")||k.id==="mapa-triagem"||(z=k.closest)!=null&&z.call(k,".leaflet-pane"))){const I=((P=k.closest)==null?void 0:P.call(k,".custom-leaflet-marker"))||((v=k.closest)==null?void 0:v.call(k,".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,r.x),y1:Math.min(this.selectStartPoint.y,r.y),x2:Math.max(this.selectStartPoint.x,r.x),y2:Math.max(this.selectStartPoint.y,r.y)},h=r.x>=this.selectStartPoint.x?"window":"crossing";(w=(b=this.ctx).selecionarFeicoesNaCaixa)==null||w.call(b,d,h,t.ctrlKey||t.metaKey);const u=((E=this.ctx.mapaController)==null?void 0:E.getMarkers())||[],f=((L=this.ctx.mapaController)==null?void 0:L.getVizinhosMarkers())||[],m=[],g=[],x=!this.ctx.layerManager||this.ctx.layerManager.isLayerActiveAndSelectable("vertices"),A=!this.ctx.layerManager||this.ctx.layerManager.isLayerActiveAndSelectable("vizinhos");return x&&u.forEach(k=>{const I=k.pontoId;if(!I)return;const _=this.map.latLngToContainerPoint(k.getLatLng());_.x>=d.x1&&_.x<=d.x2&&_.y>=d.y1&&_.y<=d.y2&&m.push(I)}),A&&f.forEach(k=>{const I=k.pontoId;if(!I)return;const _=this.map.latLngToContainerPoint(k.getLatLng());_.x>=d.x1&&_.x<=d.x2&&_.y>=d.y1&&_.y<=d.y2&&g.push(I)}),t.ctrlKey||t.metaKey?(m.forEach(k=>{this.ctx.selectedPontoIds.includes(k)?this.ctx.selectedPontoIds=this.ctx.selectedPontoIds.filter(I=>I!==k):this.ctx.selectedPontoIds.push(k)}),g.forEach(k=>{this.ctx.selectedVizinhoPontoIds.includes(k)?this.ctx.selectedVizinhoPontoIds=this.ctx.selectedVizinhoPontoIds.filter(I=>I!==k):this.ctx.selectedVizinhoPontoIds.push(k)})):(this.ctx.selectedPontoIds=m,this.ctx.selectedVizinhoPontoIds=g),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 be(n){return`pane-${n}`}const zo=["poligono","linha","ponto","texto"];function Eo(n,t){return`${be(n)}-${t}`}function at(n,t,e){const o=n.getPane(be(t))??n.createPane(be(t)),i=Eo(t,e);if(!n.getPane(i)){const a=n.createPane(i,o);a.style.zIndex=String((zo.indexOf(e)+1)*100)}return i}const Ke="ui-canvas-hit-test-estilo",Ft=6,Io=4,sn=4,$t={poligono:1,linha:2,ponto:3,texto:3};function _o(n){var i;const t=n.getRootNode(),e=t instanceof ShadowRoot?t:document.head;if((i=e.querySelector)!=null&&i.call(e,`#${Ke}`))return;const o=document.createElement("style");o.id=Ke,o.textContent=".leaflet-pane > canvas { pointer-events: none !important; }",e.appendChild(o)}function ae(n,t){var e,o;return t+(((e=n.options)==null?void 0:e.stroke)===!1?0:(((o=n.options)==null?void 0:o.weight)??0)/2)}function rn(n,t,e){let o=1/0;for(const i of n){for(let a=1;a<i.length;a++)o=Math.min(o,y.LineUtil.pointToSegmentDistance(t,i[a-1],i[a]));e&&i.length>2&&(o=Math.min(o,y.LineUtil.pointToSegmentDistance(t,i[i.length-1],i[0])))}return o}function cn(n){const t=n._pxBounds;return t?(t.max.x-t.min.x)*(t.max.y-t.min.y):0}function ln(n,t,e){var o,i,a;if(!((o=n.options)!=null&&o.interactive))return null;if(n._point&&n._radius!==void 0){const s=n._radius,r=n._radiusY??n._radius,c=n._point.distanceTo(t),l=(s+r)/2,d=e==="ponto"?Io:ae(n,Ft);return n.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(n._parts){const s=n instanceof y.Polygon,r=rn(n._parts,t,s);return e==="linha"?r<=ae(n,Ft)?r:null:s&&((i=n._containsPoint)!=null&&i.call(n,t))?0:r<=ae(n,Ft)?r:null}return(a=n._containsPoint)!=null&&a.call(n,t)?0:null}function dn(n){const t=[];for(let e=n._drawFirst;e;e=e.next)t.push(e.layer);return t}function _e(n,t,e){const o=n._paneRenderers;if(!o)return[];const i=t.filter(s=>s.visivel&&s.interativo&&!s.bloqueada).sort((s,r)=>r.zIndex-s.zIndex),a=[];for(const s of i)for(const r of zo){const c=o[Eo(s.id,r)];if(c)for(const l of dn(c).reverse()){const d=ln(l,e,r);d!==null&&a.push({camada:s,tipo:r,alvo:l,distancia:d,area:cn(l)})}}return a.sort((s,r)=>$t[s.tipo]!==$t[r.tipo]?$t[r.tipo]-$t[s.tipo]:s.camada.zIndex!==r.camada.zIndex?r.camada.zIndex-s.camada.zIndex:s.tipo==="poligono"&&s.area!==r.area?s.area-r.area:0)}const Pe=new WeakMap;function hn(n,t,e){const o=e.map(s=>y.Util.stamp(s.alvo)),i=Pe.get(n);let a=0;return i&&Math.hypot(i.x-t.x,i.y-t.y)<=sn&&i.ids.length===o.length&&i.ids.every((s,r)=>s===o[r])&&(a=(i.indice+1)%e.length),Pe.set(n,{x:t.x,y:t.y,ids:o,indice:a}),e[a]}function To(n,t,e){const o=n.mouseEventToLayerPoint(e),i=_e(n,t,o);return i.length===0?(Pe.delete(n),!1):(hn(n,o,i).alvo.fire(e.type,{originalEvent:e,latlng:n.mouseEventToLatLng(e),layerPoint:o,containerPoint:n.mouseEventToContainerPoint(e)},!0),!0)}function un(n,t,e){return _e(n,t,n.mouseEventToLayerPoint(e))[0]??null}class Do{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,"touchStartDist",0);p(this,"isTouchPanning",!1);p(this,"removerSupressao",null);p(this,"selectionHappened",!1);p(this,"panHappened",!1);p(this,"handleTouchStart",t=>{if(!(!this.map||!this.mapContainer)){if(t.touches.length===1)this.isTouchPanning=!0,this.touchStartPos={x:t.touches[0].clientX,y:t.touches[0].clientY};else if(t.touches.length===2){this.isTouchPanning=!1;const e=t.touches[0].clientX-t.touches[1].clientX,o=t.touches[0].clientY-t.touches[1].clientY;this.touchStartDist=Math.hypot(e,o)}}});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 if(t.touches.length===2&&this.touchStartDist>0){t.preventDefault(),this.panHappened=!0;const e=t.touches[0].clientX-t.touches[1].clientX,o=t.touches[0].clientY-t.touches[1].clientY,i=Math.hypot(e,o);Math.abs(i-this.touchStartDist)>25&&(i>this.touchStartDist?this.map.zoomIn(1):this.map.zoomOut(1),this.touchStartDist=i)}}});p(this,"handleTouchEnd",()=>{this.isTouchPanning=!1,this.touchStartDist=0,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,a;!this.map||!this.ctx.layerManager||(o=(e=this.ctx).ferramentaAtiva)!=null&&o.call(e)||(a=(i=t.target)==null?void 0:i.closest)!=null&&a.call(i,".leaflet-marker-icon")||To(this.map,this.ctx.layerManager.getLayers(),t)});p(this,"handleMouseDown",t=>{var e,o,i,a,s;if(!(!this.map||!this.mapContainer)){if(this.cancelarSupressaoClique(),t.button===1){t.preventDefault();const r=Date.now();if(r-this.lastMiddleClickTime<300){this.zoomExtents();return}this.lastMiddleClickTime=r,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")||(a=(i=this.ctx).ferramentaAtiva)!=null&&a.call(i)||(this.selectionHappened=!1,this.ctx.mapaController&&this.ctx.mapaController.modoCliqueSequencialAtivo))return;(s=this.selecaoBox)==null||s.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,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(Ie(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 an(this.map,this.mapContainer,this.ctx),_o(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 F{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(F,"renderers",new Map);class $o{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}",a=((l=t.dados)==null?void 0:l.subdomains)||["mt0","mt1","mt2","mt3"],s=((d=t.dados)==null?void 0:d.attribution)||"Google Satélite";return y.tileLayer(i,{maxZoom:24,maxNativeZoom:20,subdomains:a,attribution:s,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 y.TileLayer&&o.opacidade!==void 0&&e.setOpacity(o.opacidade)}destroy(t,e){e.hasLayer(t)&&e.removeLayer(t)}}class qo{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",a=((d=t.dados)==null?void 0:d.layers)||"certificada_sigef_particular_pr",s=((h=t.dados)==null?void 0:h.format)||"image/png",r=((u=t.dados)==null?void 0:u.attribution)||"INCRA/SIGEF";return y.tileLayer.wms(i,{layers:a,format:s,transparent:!0,version:"1.1.1",pane:`pane-${t.id}`,attribution:r,className:"sigef-wms-layer",keepBuffer:8,updateWhenZooming:!1,updateWhenIdle:!0,opacity:t.opacidade!==void 0?t.opacidade:.85})}update(t,e,o){e instanceof y.TileLayer.WMS&&o.opacidade!==void 0&&e.setOpacity(o.opacidade)}destroy(t,e){e.hasLayer(t)&&e.removeLayer(t)}}function No(n,t,e){const o=n.estilo.espessuraLinha||e.config.perimetroWeight||2,i=e.graphicScale.lineScaleMultiplier||1;if(n.estilo.scaleMode==="world"){const a=n.estilo.dimensaoMetros||.3,s=t.getCenter(),r=t.getZoom(),c=40075016686e-3*Math.abs(Math.cos(s.lat*Math.PI/180))/Math.pow(2,r+8),l=a/(c>0?c:1);return Math.max(1,Math.round(l*i))}return Math.max(1,Math.round(o*i))}function ut(n,t,e,o,i){const a=Math.max(Math.round(e+3),4);y.polyline(t,{color:"#080d0a",weight:a,opacity:.85,lineCap:"round",lineJoin:"round",dashArray:i,pane:o,interactive:!1}).addTo(n)}function Je(n,t,e,o,i){var m,g,x,A,M,C,z,P;const a=n.id==="homologados",s=((m=n.dados)==null?void 0:m.conexoes)??(Array.isArray(n.dados)&&n.dados.length>0&&"origemId"in n.dados[0]?n.dados:null),r=((g=n.dados)==null?void 0:g.segmentos)||o.segmentos||[],c=((x=n.dados)==null?void 0:x.pontos)||(a?o.bancoPontos||[]:o.pontos)||[],l=No(n,e,o),d=n.opacidade!==void 0?n.opacidade:1,h=n.interativo&&!n.bloqueada,u=[];c.forEach(v=>{const b=S.parseCoordenada(v.lat??v.latitude??v.y,v.lon??v.lng??v.longitude??v.x);b&&u.push({...v,lat:b.lat,lon:b.lon})});const f=v=>{const b=u.find(w=>String(w.id)===String(v));if(b)return b;if(o.pontos){const w=o.pontos.find(E=>String(E.id)===String(v));if(w){const E=S.parseCoordenada(w.lat,w.lon);if(E)return{...w,lat:E.lat,lon:E.lon}}}return null};if(s&&Array.isArray(s)){s.forEach(v=>{var E,L,k,I,_,O,T;const b=f(v.origemId),w=f(v.destinoId);if(b&&w&&b.lat&&b.lon&&w.lat&&w.lon){const X=v.tipoLinha==="tracejada"||((E=v.estilo)==null?void 0:E.tipoLinha)==="tracejada",D=((L=v.estilo)==null?void 0:L.cor)||((k=v.estilo)==null?void 0:k.color)||n.estilo.corPrimaria||"#00f5a0",N=((I=v.estilo)==null?void 0:I.espessura)||((_=v.estilo)==null?void 0:_.weight)||l,$=[[b.lat,b.lon],[w.lat,w.lon]],R=X?"6, 6":n.estilo.dashArray;ut(t,$,N,i,R);const q=y.polyline($,{color:D,weight:N,opacity:((O=v.estilo)==null?void 0:O.opacidade)??d,dashArray:R,pane:i,interactive:h});if(h){const B=v.acoes||n.acoes||((T=n.dados)==null?void 0:T.acoes)||[],V=`${v.origemId}-${v.destinoId}`,Q=S.renderPopupAcoesHtml(B,V);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 ${S.escapeHtml(String(
|
|
53
|
-
<div style="font-size:11px; color:rgba(255, 255, 255, 0.65);">Tipo: ${S.escapeHtml(
|
|
54
|
-
${
|
|
52
|
+
<div style="font-weight:700; font-size:12px; margin-bottom:3px; color:#ffffff;">Conexão ${S.escapeHtml(String(v.origemId))} ↔ ${S.escapeHtml(String(v.destinoId))}</div>
|
|
53
|
+
<div style="font-size:11px; color:rgba(255, 255, 255, 0.65);">Tipo: ${S.escapeHtml(v.tipoLinha||"contínua")}</div>
|
|
54
|
+
${Q}
|
|
55
55
|
</div>
|
|
56
|
-
`,{className:"compact-popup",maxWidth:220}),q.on("popupopen",ct=>{if(o.modoSequencial){q.closePopup();return}S.bindPopupAcoesEvents(ct.popup,
|
|
56
|
+
`,{className:"compact-popup",maxWidth:220}),q.on("popupopen",ct=>{if(o.modoSequencial){q.closePopup();return}S.bindPopupAcoesEvents(ct.popup,v,o,q)})}q.addTo(t)}});return}if((A=n.dados)!=null&&A.polilinhaSequencial||((M=n.dados)==null?void 0:M.fechar)!==void 0&&u.length>=2){const v=((C=n.dados)==null?void 0:C.chaveGrupo)||o.chaveGrupo,b=S.agruparPontosPorChave(u,v),w=((z=n.dados)==null?void 0:z.fechar)!==!1,E=n.estilo.corPrimaria||"#00f5a0";Object.entries(b).forEach(([L,k])=>{const I=S.ordenarPontosPorSequencia(k);if(I.length<2)return;const _=I.map(T=>[T.lat,T.lon]);ut(t,_,l,i,n.estilo.dashArray);const O=y.polyline(_,{color:E,weight:l,opacity:d,dashArray:n.estilo.dashArray,pane:i,interactive:h});if(h&&O.bindPopup(`
|
|
57
57
|
<div style="font-family:sans-serif; color:rgba(255, 255, 255, 0.9); line-height:1.3;">
|
|
58
58
|
<div style="font-weight:700; font-size:12px; margin-bottom:3px; color:#ffffff;">Polilinha: Grupo ${S.escapeHtml(L)}</div>
|
|
59
59
|
<div style="font-size:11px; color:rgba(255, 255, 255, 0.65);">Vértices: ${I.length}</div>
|
|
60
60
|
</div>
|
|
61
|
-
`,{className:"compact-popup",maxWidth:220}),
|
|
61
|
+
`,{className:"compact-popup",maxWidth:220}),O.addTo(t),w&&_.length>=3){const T=_[_.length-1],X=_[0],D=[T,X];ut(t,D,l,i,"4, 4"),y.polyline(D,{color:E,weight:l,opacity:d,dashArray:"4, 4",pane:i,interactive:h}).addTo(t)}});return}if(!a&&r&&r.length>0)r.forEach(v=>{var E;const b=u.find(L=>String(L.id)===String(v.ponto_inicio_id)),w=u.find(L=>String(L.id)===String(v.ponto_fim_id));if(b&&w&&b.lat&&b.lon&&w.lat&&w.lon){const L=v.tipo_limite_sigef||v.tipo_limite||"",k=v.metodo_posicionamento_sigef||v.metodo_posicionamento||"",I=L==="LA1"?"#10b981":L==="LN1"?"#3b82f6":"#00f5a0",_=v.id!=null?v.id:`${v.ponto_inicio_id}-${v.ponto_fim_id}`,O=o.selectedSegmentoId!=null&&(String(o.selectedSegmentoId)===String(v.id)||String(o.selectedSegmentoId)===String(_)),T=O?"#facc15":n.estilo.corPrimaria||I,X=[[b.lat,b.lon],[w.lat,w.lon]],D=O?l+3:l,N=L==="LN1"?"6, 6":n.estilo.dashArray;ut(t,X,O?D+2:D,i,N);const $=y.polyline(X,{color:T,weight:D,opacity:O?1:d,dashArray:N,pane:i,interactive:h});if($.segmentoId=_,$.segmento=v,h){$.on("click",V=>{V&&V.originalEvent&&V.originalEvent.stopPropagation(),o.onSegmentoClick&&o.onSegmentoClick(_,v,{lat:(b.lat+w.lat)/2,lon:(b.lon+w.lon)/2})});const R=v.acoes||n.acoes||((E=n.dados)==null?void 0:E.acoes)||[],q=`${v.ponto_inicio_id}-${v.ponto_fim_id}`,B=S.renderPopupAcoesHtml(R,q);$.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;">${S.escapeHtml(
|
|
64
|
-
<div style="font-size:11px; color:rgba(255, 255, 255, 0.65);">Limite: ${S.escapeHtml(L||"N/A")} · ${S.escapeHtml(
|
|
63
|
+
<div style="font-weight:700; font-size:12px; margin-bottom:3px; color:#ffffff;">${S.escapeHtml(b.nome_vertice)} ↔ ${S.escapeHtml(w.nome_vertice)}</div>
|
|
64
|
+
<div style="font-size:11px; color:rgba(255, 255, 255, 0.65);">Limite: ${S.escapeHtml(L||"N/A")} · ${S.escapeHtml(k||"N/A")}</div>
|
|
65
65
|
${B}
|
|
66
66
|
</div>
|
|
67
|
-
`,{className:"compact-popup",maxWidth:220}),$.on("popupopen",V=>{if(o.modoSequencial){$.closePopup();return}S.bindPopupAcoesEvents(V.popup,
|
|
68
|
-
<div ${i?`id="${
|
|
67
|
+
`,{className:"compact-popup",maxWidth:220}),$.on("popupopen",V=>{if(o.modoSequencial){$.closePopup();return}S.bindPopupAcoesEvents(V.popup,v,o,$)})}$.addTo(t)}});else if(u&&u.length>=2){const v=u.filter(k=>k.lat&&k.lon&&k.tipo_ponto!=="B"&&k.tipo!=="B"&&k.ignorar_poligono!==1),b=((P=n.dados)==null?void 0:P.chaveGrupo)||o.chaveGrupo,w=S.agruparPontosPorChave(v,b),E=n.estilo.corPrimaria||(a?"#f59e0b":"#10b981"),L=n.estilo.dashArray||(a?"6, 8":void 0);Object.values(w).forEach(k=>{const I=S.ordenarPontosPorSequencia(k);if(I.length<2)return;const _=I.map(T=>[T.lat,T.lon]);if(ut(t,_,l,i,L),y.polyline(_,{color:E,weight:l,opacity:d,dashArray:L,pane:i,interactive:h}).addTo(t),_.length>=3){const T=_[_.length-1],X=_[0],D=a?"6, 8":"4, 4",N=[T,X];ut(t,N,l,i,D),y.polyline(N,{color:E,weight:l,opacity:d,dashArray:D,pane:i,interactive:h}).addTo(t)}})}}class Oo{constructor(){p(this,"zoomListenerMap",new WeakMap)}render(t,e,o){const i=y.layerGroup(),a=at(e,t.id,"linha");Je(t,i,e,o,a);const s=()=>{if(t.estilo.scaleMode==="world"){const r=No(t,e,o);i.eachLayer(c=>{c.setStyle&&c.setStyle({weight:r})})}};return e.on("zoomend",s),this.zoomListenerMap.set(i,s),i}update(t,e,o,i,a){(o.opacidade!==void 0||o.estilo!==void 0||o.dados!==void 0||o.interativo!==void 0||o.bloqueada!==void 0)&&(e.clearLayers(),Je(t,e,a,i,at(a,t.id,"linha")))}destroy(t,e){const o=this.zoomListenerMap.get(t);o&&(e.off("zoomend",o),this.zoomListenerMap.delete(t)),t.clearLayers(),e.hasLayer(t)&&e.removeLayer(t)}}const Wt=300;function Xt(n){return n>Wt?"compacta":"normal"}function Te(n,t){if(n<=Wt)return 1;const e=Math.max(.7,1-.3*Math.log10(n/Wt)),o=t>=18?1:t>=16?.92:t>=14?.82:.72;return Math.max(.6,e*o)}function Fo(n){if(!n)return"#00f5a0";const t=n.trim();if(t.startsWith("#")||t.startsWith("rgb")||t.startsWith("hsl")||t.startsWith("var("))return t;if(t.includes("bg-[#")&&t.includes("]")){const o=t.match(/bg-\[(#[a-fA-F0-9]+)\]/);if(o)return o[1]}const e={"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(e))if(t.includes(o))return i;return"#00f5a0"}function Qe(n){return n.replace(/[&<>"']/g,t=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[t])}const se={diamond:"6,0.8 11.2,6 6,11.2 0.8,6",triangle:"6,1 11.4,10.6 0.6,10.6"},re={cross:["M6 1.2V10.8","M1.2 6H10.8"],x:["M2 2L10 10","M10 2L2 10"]};function wt(n,t,e,o="",i="",a=!1,s={}){const r=a||o.includes("ponto-selecionado")||o.includes("cad-marker-selected"),c=s.densidade==="compacta",l=Qe(Fo(e)),d=t+6,h=r?`color-mix(in srgb, ${l} 38%, #000000)`:l,u=r?1:c?.72:.9,f=r?"rgba(255,255,255,0.95)":c?"rgba(0,0,0,0.55)":"rgba(0,0,0,0.7)",m=r?1.3:c?.8:1,g=r?"rgba(255,255,255,0.9)":"rgba(0,0,0,0.6)",x=(b,w,E,L="")=>`class="${b}" stroke="${w}" stroke-width="${E}" vector-effect="non-scaling-stroke" ${L}`,A=n in se?`<polygon points="${se[n]}" style="fill:${h}" fill-opacity="${u}" stroke-linejoin="round" ${x("cad-pt-contorno",f,m)} />`:n in re?re[n].map(b=>`<path d="${b}" fill="none" stroke-linecap="round" ${x("cad-pt-halo",g,c?2.6:3.4)} /><path d="${b}" fill="none" stroke-linecap="round" ${x("cad-pt-traco",r?h:l,c?1.3:1.8,`stroke-opacity="${r?1:c?.9:1}"`)} />`).join(""):n==="square"?`<rect x="1.2" y="1.2" width="9.6" height="9.6" rx="1.4" style="fill:${h}" fill-opacity="${u}" ${x("cad-pt-contorno",f,m)} />`:`<circle cx="6" cy="6" r="5.2" style="fill:${h}" fill-opacity="${u}" ${x("cad-pt-contorno",f,m)} />`,M=!c&&!r&&!(n in re)?n in se?"":n==="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" />':"",C=n==="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" />':"",z=`cad-pt ${c?"cad-pt-compacto":""} ${e} ${o} ${r?"ponto-selecionado":""}`.replace(/\s+/g," ").trim(),P=t;return`
|
|
68
|
+
<div ${i?`id="${Qe(i)}"`:""} class="${z}" style="display:flex; align-items:center; justify-content:center; width:${d}px; height:${d}px; position:relative; pointer-events:auto; background:none !important;">
|
|
69
69
|
<svg width="${P}" height="${P}" viewBox="0 0 12 12" xmlns="http://www.w3.org/2000/svg" style="overflow:visible; display:block;">
|
|
70
70
|
${A}${M}${C}
|
|
71
71
|
</svg>
|
|
72
72
|
</div>
|
|
73
|
-
`}class
|
|
73
|
+
`}class Ro{constructor(){p(this,"zoomListenerMap",new WeakMap)}render(t,e,o){const i=y.layerGroup(),a=at(e,t.id,"ponto");this.rebuildPoints(t,i,e,o,a);const s=()=>{i.eachLayer(r=>{if(!(r.setIcon&&r.baseSize&&r.shapeStyle&&r.markerBg&&r.pontoId!==void 0))return;const c=r.densTotal||0;if(t.estilo.scaleMode!=="world"&&Xt(c)!=="compacta")return;const l=this.calculateSize(t,e,o,r.baseSize,c);l!==r.tamanhoPx&&(r.tamanhoPx=l,r.setIcon(this.criarIcone(t,o,r.shapeStyle,l,r.markerBg,r.pontoId,!!r.isSelected,c)))})};return e.on("zoomend",s),this.zoomListenerMap.set(i,s),i}criarIcone(t,e,o,i,a,s,r,c){const l=e.config.enableAnimations?"cad-pt-anim":"",d=wt(o,i,a,l,`map-marker-${t.id}-${s}`,r,{densidade:Xt(c)});return y.divIcon({html:d,className:`custom-leaflet-marker ${r?"cad-marker-selected":""}`.trim(),iconSize:[i+6,i+6]})}calculateSize(t,e,o,i,a=0){const s=o.graphicScale.markerScaleMultiplier||1;if(t.estilo.scaleMode==="world"){const c=t.estilo.dimensaoMetros||.25,l=e.getCenter(),d=e.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*s))}const r=Te(a,e.getZoom());return Math.max(r<1?5:4,Math.round(i*s*r))}rebuildPoints(t,e,o,i,a){var f;const r=t.id==="homologados-pontos"?i.bancoPontos||[]:((f=t.dados)==null?void 0:f.pontos)||i.pontos||[],c=t.interativo&&!t.bloqueada,l=t.id==="vizinhos",d=t.id==="homologados"||t.id==="homologados-pontos",h=i.selectedPontoIds||[],u=r.length;r.forEach(m=>{var A;const g=m.lat??m.latitude,x=m.lon??m.lng??m.longitude;if(g!==void 0&&x!==void 0&&g!==0&&x!==0&&!isNaN(Number(g))&&!isNaN(Number(x))){const M=m.tipo_ponto==="B"||m.tipo==="B",C=m.tipo_ponto==="M"||m.tipo==="M";let z=t.estilo.estiloMarcador||"x",P=t.estilo.corPrimaria||"bg-mint-vibrant",v=t.estilo.tamanhoMarcador||7;d?(z="circle",P=t.estilo.corPrimaria||"#f59e0b",v=8):l?(z=C?"circle-dot":t.estilo.estiloMarcador||"cross",P=t.estilo.corPrimaria||"#a855f7",v=C?10:8):C?(P="#6366f1",z="circle-dot",v=10):M&&(P="#f43f5e",z="square",v=9);const b=!!(m.selecionado||h.length>0&&(h.includes(m.id)||h.includes(String(m.id))||h.includes(Number(m.id)))),w=this.calculateSize(t,o,i,v,u),E=this.criarIcone(t,i,z,w,P,m.id,b,u),L=y.marker([Number(g),Number(x)],{icon:E,pane:a,interactive:c});if(b&&L.setZIndexOffset(2e3),L.pontoId=m.id,L.layerId=t.id,L.isVizinho=l,L.baseSize=v,L.shapeStyle=z,L.markerBg=P,L.isSelected=b,L.densTotal=u,L.tamanhoPx=w,c){const k=d?"Vértice Homologado SIGEF":l?"Confrontante (Importado)":C?"Base Homologada PPP":M?"Base de Campo (Translação)":"Vértice de Perímetro",I=m.acoes||t.acoes||((A=t.dados)==null?void 0:A.acoes)||[],_=S.renderPopupAcoesHtml(I,m.id);L.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
75
|
<div style="font-weight:700; font-size:13px; margin-bottom:4px; color:#ffffff;">${S.escapeHtml(m.nome_vertice||String(m.id))}</div>
|
|
76
|
-
<div style="font-size:11px; color:rgba(255, 255, 255, 0.65);">${S.escapeHtml(
|
|
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(
|
|
76
|
+
<div style="font-size:11px; color:rgba(255, 255, 255, 0.65);">${S.escapeHtml(k)} · ${S.escapeHtml(m.tipo_ponto||m.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(g).toFixed(6)} Lon ${Number(x).toFixed(6)}</div>
|
|
78
78
|
${_}
|
|
79
79
|
</div>
|
|
80
|
-
`,{className:"compact-popup",maxWidth:240}),I&&I.length>0&&L.on("popupopen",
|
|
80
|
+
`,{className:"compact-popup",maxWidth:240}),I&&I.length>0&&L.on("popupopen",O=>{S.bindPopupAcoesEvents(O.popup,m,i,L)}),L.on("click",()=>{i.onMarkerClick&&i.onMarkerClick(m.id,l,m,{lat:Number(g),lon:Number(x)})})}L.addTo(e)}})}update(t,e,o,i,a){(o.opacidade!==void 0||o.estilo!==void 0||o.dados!==void 0||o.interativo!==void 0||o.bloqueada!==void 0)&&(e.clearLayers(),this.rebuildPoints(t,e,a,i,at(a,t.id,"ponto")))}destroy(t,e){const o=this.zoomListenerMap.get(t);o&&(e.off("zoomend",o),this.zoomListenerMap.delete(t)),t.clearLayers(),e.hasLayer(t)&&e.removeLayer(t)}}class Bo{render(t,e,o){const i=y.layerGroup();return this.rebuildPolygons(t,i,o,e),i}rebuildPolygons(t,e,o,i){var f,m;const a=at(i,t.id,"poligono"),s=at(i,t.id,"ponto"),c=(((f=t.dados)==null?void 0:f.poligonos)??(Array.isArray(t.dados)?t.dados:null))||((m=t.dados)==null?void 0:m.confrontantes)||o.confrontantes||[],l=t.interativo&&!t.bloqueada,d=t.estilo.corPrimaria||"#a855f7",h=t.estilo.espessuraLinha||1,u=t.opacidade!==void 0?t.opacidade:.8;c.forEach(g=>{var b,w,E,L,k,I,_,O,T,X;if(!g)return;const x=((b=g.estilo)==null?void 0:b.cor)||((w=g.estilo)==null?void 0:w.color)||d,A=((E=g.estilo)==null?void 0:E.espessura)||((L=g.estilo)==null?void 0:L.weight)||h,M=((k=g.estilo)==null?void 0:k.opacidade)??u,C=((I=g.estilo)==null?void 0:I.fillColor)||x,z=((_=g.estilo)==null?void 0:_.fillOpacity)??Math.min(.14,M*.1),P=((O=g.estilo)==null?void 0:O.dashArray)||t.estilo.dashArray||"4, 6";if(g.coordenadas&&Array.isArray(g.coordenadas)&&g.coordenadas.length>=3){const D=Array.isArray(g.coordenadas[0])&&Array.isArray(g.coordenadas[0][0]);let N;if(D?N=g.coordenadas.map($=>$.map(R=>{const q=S.parseCoordenada(R[0],R[1]);return q?[q.lat,q.lon]:null}).filter(Boolean)):N=g.coordenadas.map($=>{const R=S.parseCoordenada($[0],$[1]);return R?[R.lat,R.lon]:null}).filter(Boolean),N&&(D?((T=N[0])==null?void 0:T.length)>=3:N.length>=3)){const $=y.polygon(N,{color:x,weight:A,opacity:M,dashArray:P,fillColor:C,fillOpacity:z,lineJoin:"round",pane:a,interactive:l});if($.poligonoId=g.id,$.layerId=t.id,l){let R="";g.metadados&&Object.keys(g.metadados).length>0&&(R=Object.entries(g.metadados).map(([q,B])=>`<div style="font-size:11px;"><strong>${S.escapeHtml(q)}:</strong> ${S.escapeHtml(String(B))}</div>`).join("")),$.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 ${S.escapeHtml(String(
|
|
83
|
-
${R||`<div style="font-size:11px;">Área vetorial definida por ${
|
|
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 ${S.escapeHtml(String(g.id??""))}</div>
|
|
83
|
+
${R||`<div style="font-size:11px;">Área vetorial definida por ${g.coordenadas.length} vértices</div>`}
|
|
84
84
|
</div>
|
|
85
|
-
`,{className:"compact-popup",maxWidth:220}),$.on("popupopen",()=>{o.modoSequencial&&$.closePopup()})}$.addTo(e);return}}const
|
|
85
|
+
`,{className:"compact-popup",maxWidth:220}),$.on("popupopen",()=>{o.modoSequencial&&$.closePopup()})}$.addTo(e);return}}const v=g.wkt||g.poligono_wkt;if(v){const D=[...v.matchAll(/\(([^()]+)\)/g)];if(D.length>0){const N=S.escapeHtml(g.nome_propriedade||`Polígono ${String(g.id||"")}`),$=S.escapeHtml(g.nome||"Proprietário"),R=[];if(D.forEach(q=>{const B=q[1].split(",").map(V=>{const Q=V.trim().split(/\s+/);if(Q.length<2)return null;const ct=S.parseCoordenada(Q[1],Q[0]);return ct?[ct.lat,ct.lon]:null}).filter(V=>V!==null);B.length>=3&&R.push(B)}),R.length>0){const q=R.length===1?R[0]:R,B=y.polygon(q,{color:x,weight:A,opacity:M,dashArray:P,fillColor:C,fillOpacity:z,lineJoin:"round",pane:a,interactive:l});if(B.poligonoId=g.id,B.layerId=t.id,l){const V=g.acoes||t.acoes||((X=t.dados)==null?void 0:X.acoes)||[],Q=S.renderPopupAcoesHtml(V,g.id);B.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> ${S.escapeHtml(String(
|
|
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;">${N}</div>
|
|
88
|
+
<div style="font-size:11px; margin-bottom:2px;"><strong>Identificador:</strong> ${S.escapeHtml(String(g.id??""))}</div>
|
|
89
|
+
${g.nome?`<div style="font-size:11px;"><strong>Proprietário:</strong> ${$}</div>`:""}
|
|
90
|
+
${Q}
|
|
91
91
|
</div>
|
|
92
|
-
`,{className:"compact-popup",maxWidth:220}),B.on("popupopen",ct=>{if(o.modoSequencial){B.closePopup();return}S.bindPopupAcoesEvents(ct.popup,
|
|
92
|
+
`,{className:"compact-popup",maxWidth:220}),B.on("popupopen",ct=>{if(o.modoSequencial){B.closePopup();return}S.bindPopupAcoesEvents(ct.popup,g,o,B)})}B.addTo(e)}}}g.pontos&&g.pontos.length>0&&g.pontos.forEach(D=>{var $;const N=S.parseCoordenada(D.lat??D.latitude??D.y,D.lon??D.lng??D.longitude??D.x);if(N){const R=y.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=y.marker([N.lat,N.lon],{icon:R,pane:s,interactive:l});if(q.pontoId=D.id,q.isVizinho=!0,q.layerId=t.id,l){const B=D.acoes||g.acoes||t.acoes||(($=t.dados)==null?void 0:$.acoes)||[],V=S.renderPopupAcoesHtml(B,D.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
94
|
<div style="font-weight:700; font-size:12px; color:#c084fc; margin-bottom:3px;">${S.escapeHtml(D.nome_vertice||String(D.id))}</div>
|
|
95
|
-
<div style="font-size:11px; color:rgba(255, 255, 255, 0.65);">Confrontante: ${S.escapeHtml(
|
|
96
|
-
<div style="font-size:10px; color:rgba(255, 255, 255, 0.45); font-family:var(--ui-fonte-codigo, monospace); margin-top:3px;">Lat ${
|
|
95
|
+
<div style="font-size:11px; color:rgba(255, 255, 255, 0.65);">Confrontante: ${S.escapeHtml(g.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 ${N.lat.toFixed(6)} Lon ${N.lon.toFixed(6)}</div>
|
|
97
97
|
${V}
|
|
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:`
|
|
99
|
+
`,{className:"compact-popup",maxWidth:220}),q.on("click",()=>{o.modoSequencial&&q.closePopup(),o.onMarkerClick&&o.onMarkerClick(D.id,!0,D,{lat:N.lat,lon:N.lon})}),q.on("popupopen",Q=>{if(o.modoSequencial){q.closePopup();return}S.bindPopupAcoesEvents(Q.popup,D,o,q)})}q.addTo(e)}})})}update(t,e,o,i,a){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,a))}destroy(t,e){t.clearLayers(),e.hasLayer(t)&&e.removeLayer(t)}}class Ho{constructor(){p(this,"moveListenerMap",new WeakMap)}render(t,e,o){const i=y.layerGroup(),a=`pane-${t.id}`,s=()=>{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(),f=e.getCenter(),m=8999e-9,g=Math.cos(f.lat*Math.PI/180),x=m/(g>.1?g:1),A=Math.floor((d-l)/m),M=Math.floor((u-h)/x);if(A<200&&M<200){const C=Math.ceil(l/m)*m;for(let P=C;P<=d;P+=m)y.polyline([[P,h],[P,u]],{color:t.estilo.corPrimaria||"rgba(0, 245, 160, 0.18)",weight:t.estilo.espessuraLinha||.6,interactive:!1,pane:a}).addTo(i);const z=Math.ceil(h/x)*x;for(let P=z;P<=u;P+=x)y.polyline([[l,P],[d,P]],{color:t.estilo.corPrimaria||"rgba(0, 245, 160, 0.18)",weight:t.estilo.espessuraLinha||.6,interactive:!1,pane:a}).addTo(i)}}};return s(),e.on("zoomend moveend",s),this.moveListenerMap.set(i,s),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 U(n){return n.partes&&n.partes.length>1?n.partes:[n.coordenadas]}function kt(n){return n.tipo==="LineString"&&!!n.partes&&n.partes.length>1}function yt(n){return n.length>1?{tipo:"LineString",coordenadas:n[0],partes:n}:{tipo:"LineString",coordenadas:n[0]}}const Mt=6378137,Zt=1/298.257222101,to=Zt*(2-Zt),j=n=>n*Math.PI/180;function De(n){const t=Math.sin(j(n)),e=1-to*t*t;return{N:Mt/Math.sqrt(e),M:Mt*(1-to)/(e*Math.sqrt(e))}}function ie(n){const{M:t,N:e}=De(n);return{lat:j(1)*t,lng:j(1)*e*Math.cos(j(n))}}function pn(n,t){const e=Mt*(1-Zt),o=Zt,i=j(t[1]-n[1]),a=Math.atan((1-o)*Math.tan(j(n[0]))),s=Math.atan((1-o)*Math.tan(j(t[0]))),r=Math.sin(a),c=Math.cos(a),l=Math.sin(s),d=Math.cos(s);let h=i,u=0,f=0,m=0,g=0,x=0;for(let P=0;P<100;P++){const v=Math.sin(h),b=Math.cos(h);if(u=Math.hypot(d*v,c*l-r*d*b),u===0)return 0;f=r*l+c*d*b,m=Math.atan2(u,f);const w=c*d*v/u;g=1-w*w,x=g===0?0:f-2*r*l/g;const E=o/16*g*(4+o*(4-3*g)),L=h;if(h=i+(1-E)*o*w*(m+E*u*(x+E*f*(-1+2*x*x))),Math.abs(h-L)<1e-12)break}const A=g*(Mt*Mt-e*e)/(e*e),M=1+A/16384*(4096+A*(-768+A*(320-175*A))),C=A/1024*(256+A*(-128+A*(74-47*A))),z=C*u*(x+C/4*(f*(-1+2*x*x)-C/6*x*(-3+4*u*u)*(-3+4*x*x)));return e*M*(m-z)}function st(n,t){const e=t[0]-n[0],o=t[1]-n[1];if(Math.abs(e)<.1&&Math.abs(o)<.1){const{M:i,N:a}=De((n[0]+t[0])/2),s=j(e)*i,r=j(o)*a*Math.cos(j((n[0]+t[0])/2));return Math.hypot(r,s)}return pn(n,t)}function zt(n,t=!1){let e=0;for(let o=1;o<n.length;o++)e+=st(n[o-1],n[o]);return t&&n.length>2&&(e+=st(n[n.length-1],n[0])),e}function eo(n){const t=n.length;if(t<3)return 0;let e=0,o=0;for(let r=0;r<t;r++){const c=n[(r-1+t)%t],l=n[r],d=n[(r+1)%t];e+=j(d[1]-c[1])*Math.sin(j(l[0])),o+=l[0]}const{M:i,N:a}=De(o/t),s=Math.abs(e*i*a/2);return Number.isFinite(s)?s:0}function Vo(n){const[t,...e]=n;return t?Math.max(0,eo(t)-e.reduce((o,i)=>o+eo(i),0)):0}const fn=new Intl.NumberFormat("pt-BR",{minimumFractionDigits:4,maximumFractionDigits:4}),oo=new Intl.NumberFormat("pt-BR",{minimumFractionDigits:2,maximumFractionDigits:2});function rt(n){return`${fn.format(n/1e4)} ha`}function G(n){return n>=1e3?`${oo.format(n/1e3)} km`:`${oo.format(n)} m`}function tt(n){return n.tipo==="Polygon"?Vo(n.aneis):n.tipo==="Circle"?Math.PI*n.raioMetros**2:null}function et(n){return n.tipo==="LineString"?U(n).reduce((t,e)=>t+zt(e),0):n.tipo==="Polygon"?zt(n.aneis[0]??[],!0):n.tipo==="Circle"?2*Math.PI*n.raioMetros:null}function Go(n,t){var i;const e=t??"name";if(e==="area"){const a=tt(n.geometria);return a===null?"":rt(a)}if(e==="extensao"){const a=et(n.geometria);return a===null?"":G(a)}if(e==="id")return n.id;const o=(i=n.propriedades)==null?void 0:i[e];return o!=null&&o!==""?String(o):t?"":n.id}function $e(n){let t;switch(n.tipo){case"Point":case"Text":t=[n.coordenada];break;case"LineString":t=U(n).flat();break;case"Polygon":t=n.aneis.flat();break;case"Circle":{const i=n.raioMetros/111320,a=i/Math.max(.01,Math.cos(j(n.centro[0])));t=[[n.centro[0]-i,n.centro[1]-a],[n.centro[0]+i,n.centro[1]+a]];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 qt=16,mn=256;function Ce(n){const[[t,e],[o,i]]=$e(n.geometria);return{minLon:e,minLat:t,maxLon:i,maxLat:o}}function mt(n,t){return n.minLon<=t.maxLon&&n.maxLon>=t.minLon&&n.minLat<=t.maxLat&&n.maxLat>=t.minLat}function io(n){let t=1/0,e=1/0,o=-1/0,i=-1/0;for(const a of n)a.minLon<t&&(t=a.minLon),a.minLat<e&&(e=a.minLat),a.maxLon>o&&(o=a.maxLon),a.maxLat>i&&(i=a.maxLat);return{minLon:t,minLat:e,maxLon:o,maxLat:i}}function no(n){const t=n.length,e=Math.ceil(t/qt),i=Math.ceil(Math.sqrt(e))*qt,a=[...n].sort((r,c)=>r.minLon+r.maxLon-(c.minLon+c.maxLon)),s=[];for(let r=0;r<t;r+=i){const c=a.slice(r,r+i).sort((l,d)=>l.minLat+l.maxLat-(d.minLat+d.maxLat));for(let l=0;l<c.length;l+=qt)s.push(c.slice(l,l+qt))}return s}function gn(n){if(n.length===0)return null;let t=no(n).map(e=>({...io(e),folhas:e}));for(;t.length>1;)t=no(t).map(e=>({...io(e),filhos:e}));return t[0]}class jo{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,...Ce(e)});this.remontar()}inserir(t){this.atualizar(t)}atualizar(t){if(t.excluida){this.remover(t.id);return}const e={id:t.id,...Ce(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 a of i.folhas)!this.obsoletos.has(a.id)&&mt(a,t)&&e.push(a.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(mn,this.itens.size*.1)&&this.remontar()}remontar(){this.raiz=gn([...this.itens.values()]),this.delta.clear(),this.obsoletos.clear()}}const Yt=12,qe=40,vn=1.2;function Uo(n){return n>=Yt?0:360/(256*2**n)*vn}function yn(n,t,e){const o=e[1]-t[1],i=e[0]-t[0],a=o*o+i*i;let s=a===0?0:((n[1]-t[1])*o+(n[0]-t[0])*i)/a;return s=Math.max(0,Math.min(1,s)),Math.hypot(n[1]-(t[1]+s*o),n[0]-(t[0]+s*i))}function Ne(n,t){if(t<=0||n.length<3)return n;const e=new Uint8Array(n.length);e[0]=1,e[n.length-1]=1;const o=[[0,n.length-1]];for(;o.length>0;){const[i,a]=o.pop();let s=0,r=-1;for(let c=i+1;c<a;c++){const l=yn(n[c],n[i],n[a]);l>s&&(s=l,r=c)}r!==-1&&s>t&&(e[r]=1,o.push([i,r],[r,a]))}return n.filter((i,a)=>e[a]===1)}function Wo(n,t){if(t<=0||n.length<4)return n;const e=[...n,n[0]],o=Ne(e,t);return o.pop(),o.length>=3?o:n}function Oe(n){return(n.tipo==="LineString"||n.tipo==="Polygon")&&n.curva?0:n.tipo==="LineString"?U(n).reduce((t,e)=>t+e.length,0):n.tipo==="Polygon"?n.aneis.reduce((t,e)=>t+e.length,0):0}function Xo(n,t){const e=Uo(t);return e===0||Oe(n)<qe?n:n.tipo==="LineString"?yt(U(n).map(o=>Ne(o,e))):n.tipo==="Polygon"?{tipo:"Polygon",aneis:n.aneis.map(o=>Wo(o,e))}:n}const xn=new Set(["previa","prévia","preview","rascunho","draft","proposta"]);function K(n){var e,o;const t=[n.status,(e=n.propriedades)==null?void 0:e.status,(o=n.propriedades)==null?void 0:o.tipo_geometria];for(const i of t)if(typeof i=="string"&&xn.has(i.trim().toLowerCase()))return"previa";return"oficial"}function nt(n){var e;const t=n.entidadeId??((e=n.propriedades)==null?void 0:e.entidadeId);return typeof t=="string"||typeof t=="number"?String(t):n.id}const ce=(n,t)=>`${n}\0${t}`;class Kt{constructor(){p(this,"global",!1);p(this,"individuais",new Set)}alternarIndividual(t,e){const o=ce(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=ce(t,e);o?this.individuais.add(i):this.individuais.delete(i)}individualAtiva(t,e){return this.individuais.has(ce(t,e))}static oficiais(t){const e=new Set;for(const o of t)!o.excluida&&K(o)==="oficial"&&e.add(nt(o));return e}visivel(t,e){if(K(t)==="oficial")return!0;const o=nt(t);return this.global||!e.has(o)||this.individualAtiva(t.camadaId,o)}previaSolicitada(t){return this.global||this.individualAtiva(t.camadaId,nt(t))}}const bn=24,Pn=2,ao=n=>typeof n=="number"&&Number.isFinite(n),le=n=>Array.isArray(n)&&n.length===2&&ao(n[0])&&ao(n[1]);function Fe(n,t){return[2*n[0]-t[0],2*n[1]-t[1]]}function Zo(n){return n.some(t=>t.entrada!==void 0||t.saida!==void 0)}function _t(n,t){return[n.saida??n.ponto,t.entrada??t.ponto]}function Yo(n,t){const e=[];for(let o=0;o<n-1;o++)e.push([o,o+1]);return t&&n>2&&e.push([n-1,0]),e}function Re(n,t,e,o,i){const a=1-i,s=a*a*a,r=3*a*a*i,c=3*a*i*i,l=i*i*i;return[s*n[0]+r*t[0]+c*e[0]+l*o[0],s*n[1]+r*t[1]+c*e[1]+l*o[1]]}function xt(n,t=!1,e=bn){if(n.length===0)return[];const o=[[n[0].ponto[0],n[0].ponto[1]]];for(const[i,a]of Yo(n.length,t)){const s=n[i],r=n[a];if(!(s.saida===void 0&&r.entrada===void 0)){const[l,d]=_t(s,r);for(let h=1;h<e;h++)o.push(Re(s.ponto,l,d,r.ponto,h/e))}a!==0&&o.push([r.ponto[0],r.ponto[1]])}return o}function Ko(n,t){if(n.length===0)return[];const e=[{cmd:"M",pts:[n[0].ponto]}];for(const[o,i]of Yo(n.length,t)){const a=n[o],s=n[i];if(a.saida===void 0&&s.entrada===void 0)e.push({cmd:"L",pts:[s.ponto]});else{const[r,c]=_t(a,s);e.push({cmd:"C",pts:[r,c,s.ponto]})}}return e}function Cn(n,t,e){const o=a=>String(Math.round(a*100)/100),i=Ko(n,t).map(a=>a.cmd+a.pts.map(s=>{const r=e(s);return`${o(r.x)} ${o(r.y)}`}).join(" ")).join("");return i&&t?`${i}Z`:i}function Ln(n,t=Pn){if(!Array.isArray(n)||n.length<t)return null;const e=[];for(const o of n){if(!o||typeof o!="object"||!le(o.ponto))return null;const i=o,a={ponto:[i.ponto[0],i.ponto[1]]};le(i.entrada)&&(a.entrada=[i.entrada[0],i.entrada[1]]),le(i.saida)&&(a.saida=[i.saida[0],i.saida[1]]),e.push(a)}return Zo(e)?e:null}function so(n,t){return n.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 Jo(n,t){var s,r;const e=n._nosCurva,o=n._renderer,i=n._map;if(!e||e.length<2||!o||!i)return!1;const a=c=>i.latLngToLayerPoint([c[0],c[1]]);if(o._ctx&&o._fillStroke){if(!o._drawing||!((s=n._parts)!=null&&s.length))return!0;const c=o._ctx;c.beginPath();for(const l of Ko(e,t)){const d=l.pts.map(a);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,n),!0}return o._setPath?(o._setPath(n,(r=n._parts)!=null&&r.length?Cn(e,t,a):"M0 0"),!0):!1}class Qo extends y.Polyline{constructor(){super(...arguments);p(this,"_nosCurva",null)}definirCurva(e){this._nosCurva=e}_updatePath(){Jo(this,!1)||y.Polyline.prototype._updatePath.call(this)}}class ti extends y.Polygon{constructor(){super(...arguments);p(this,"_nosCurva",null)}definirCurva(e){this._nosCurva=e}_updatePath(){Jo(this,!0)||y.Polygon.prototype._updatePath.call(this)}}function Jt(n){return n.tipo==="LineString"?n.curva&&n.curva.length>=2&&!(n.partes&&n.partes.length>1)?n.curva:null:n.tipo==="Polygon"&&n.curva&&n.curva.length>=3&&n.aneis.length===1?n.curva:null}function ei(n,t){const e=Jt(n);if(!e)return null;const o=n.tipo==="Polygon"?new ti(n.aneis[0],t):new Qo(n.coordenadas,t);return o.definirCurva(e),o}function Sn(n,t){n.definirCurva(Jt(t)),n.setLatLngs(t.tipo==="Polygon"?t.aneis[0]:t.coordenadas)}const Et=55,oi=17,ii=8;function Qt(n,t){return t<oi&&n>ii}function ni(n){let t=0,e=0;for(const o of n)t+=o.coordenada[0],e+=o.coordenada[1];return[t/n.length,e/n.length]}function Mn(n,t,e){if(!Qt(n.length,t))return{clusters:[],isolados:n};const o=new Map;for(const s of n){const{x:r,y:c}=e(s.coordenada),l=`${t}:${Math.floor(r/Et)}:${Math.floor(c/Et)}`,d=o.get(l);d?d.push(s):o.set(l,[s])}const i=[],a=[];for(const[s,r]of o)r.length===1?a.push(r[0]):i.push({chave:s,coordenada:ni(r),membros:r});return{clusters:i,isolados:a}}class ai{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/Et)}:${Math.floor(o/Et)}`;let a=this.celulas.get(i);return a||(a={membros:new Map,somaLat:0,somaLon:0},this.celulas.set(i,a)),a.membros.set(t.id,t),a.somaLat+=t.coordenada[0],a.somaLon+=t.coordenada[1],a.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" />'},de="#38bdf8",An=/^(#[0-9a-f]{3,8}|(rgb|hsl)a?\([0-9.,%\s\/-]+\)|[a-z]{3,20})$/i;function Y(n,t){return n&&An.test(n.trim())?n.trim():t}const ft="#38bdf8",wn=150,kn=100,Le=300,ro=.75,zn=.3,he=typeof requestAnimationFrame=="function"?n=>{requestAnimationFrame(n)}:n=>{setTimeout(n,16)};class si{constructor(){p(this,"estados",new WeakMap);p(this,"selecionadas",new WeakMap);p(this,"tokenLote",new WeakMap)}render(t,e,o){const i=y.layerGroup();return this.sincronizar(t,i,e,o,!0),i}update(t,e,o,i,a){if(o.dados===void 0&&o.estilo===void 0&&o.interativo===void 0&&o.bloqueada===void 0)return;const s=o.estilo!==void 0||o.interativo!==void 0||o.bloqueada!==void 0;this.sincronizar(t,e,a,i,s)}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 a of o.indice.consultar(e)){const s=o.loja.get(a);s&&!s.oculta&&i.push(s)}return i}previsualizar(t,e){var s;const o=this.estados.get(t),i=o==null?void 0:o.entradas.get(e.id);if(!o||!i)return;const a=o.map._loaded?o.map.getZoom():0;this.remendar(i.layer,this.paraDesenho(e,a),o.layerDef,o.interativo,!!((s=this.selecionadas.get(o.layerDef))!=null&&s.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 a=this.estados.get(t);if(!a){const s={layerDef:e,interativo:!1,map:o,context:i,loja:new Map,indice:new jo,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:()=>{s.agendado||!s.vivo||(s.agendado=!0,he(()=>{s.agendado=!1,s.vivo&&this.reconciliar(t,s,!1,null)}))}};o.on("moveend zoomend",s.aoMover),this.estados.set(t,s),a=s}return a.layerDef=e,a.map=o,a.context=i,a.interativo=e.interativo&&!e.bloqueada,a}sincronizar(t,e,o,i,a){var m;const s=this.obterEstado(e,t,o,i),r=this.feicoesDe(t),c=(m=t.dados)==null?void 0:m.delta;if(!a&&this.aplicarDelta(e,s,r,c))return;const l=r.filter(g=>!g.excluida),d=new Set,h=new Set;for(const g of l)h.add(g.id),s.loja.get(g.id)!==g&&d.add(g.id);const u=[...s.loja.keys()].filter(g=>!h.has(g));if(d.size>0||u.length>0){if(s.revisao++,s.revisaoBase++,s.loja.size===0||d.size+u.length>l.length*zn)s.indice.construir(l);else{for(const g of l)d.has(g.id)&&s.indice.atualizar(g);for(const g of u)s.indice.remover(g)}s.loja=new Map(l.map(g=>[g.id,g])),this.recontarOficiais(s,l)}s.listaSincronizada=r;const f=this.selecionadas.get(t);if(f)for(const g of[...f])h.has(g)||f.delete(g);this.reconciliar(e,s,a,d)}recontarOficiais(t,e){t.contOficiais=new Map,t.nPrevias=0;for(const o of e){if(o.excluida)continue;if(K(o)!=="oficial"){t.nPrevias++;continue}const i=nt(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:a}=e,s=this.selecionadas.get(e.layerDef),r=m=>m.geometria.tipo==="Point"&&this.desenhavel(e,m),c=new Map,l=(m,g)=>{if(!m||m.excluida||K(m)!=="oficial")return;const x=nt(m);c.has(x)||c.set(x,e.oficiais.has(x));const A=(e.contOficiais.get(x)??0)+g;A<=0?(e.contOficiais.delete(x),e.oficiais.delete(x)):(e.contOficiais.set(x,A),e.oficiais.add(x))},d=[],h=[],u=m=>{const g=a.get(m);g&&(K(g)==="previa"&&e.nPrevias--,l(g,-1),r(g)&&e.nPontos--,a.delete(m),e.indice.remover(m),s==null||s.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 g=a.get(m.id);K(m)==="previa"&&e.nPrevias++,g&&(K(g)==="previa"&&e.nPrevias--,l(g,-1),r(g)&&e.nPontos--),a.set(m.id,m),e.indice.atualizar(m),l(m,1),r(m)&&e.nPontos++,d.push(m.id)}let f=!1;if(e.nPrevias>0)for(const[m,g]of c)g!==e.oficiais.has(m)&&(f=!0);return e.listaSincronizada=o,e.revisao++,f&&e.revisaoBase++,this.reconciliarParcial(t,e,d,h,f),!0}ressimplificar(t,e){return t.zoomDesenho===e||Oe(t.feicao.geometria)<qe?!1:e<Yt||t.zoomDesenho<Yt}paraDesenho(t,e){const o=Xo(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,a,s){const r=this.formaDe(o),c=e.entradas.get(o.id),l=this.paraDesenho(o,i);if(c&&c.forma===r){(s||c.feicao!==o||this.ressimplificar(c,i))&&(this.remendar(c.layer,l,e.layerDef,e.interativo,a),c.feicao=o,c.zoomDesenho=i);return}c&&t.removeLayer(c.layer);const d=this.criar(l,e.layerDef,e.map,e.interativo,a);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:r,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 a=e.clusters.get(o);if((a==null?void 0:a.assinatura)===i.assinatura)return;a&&t.removeLayer(a.marker);const s=this.criarMarcadorCluster(i.coordenada,i.total,()=>{var r,c;return Array.from(((c=(r=e.agrupador)==null?void 0:r.celula(o))==null?void 0:c.membros.values())??[])},e);t.addLayer(s),e.clusters.set(o,{marker:s,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=s=>this.desenhavel(t,s);if(t.nPontosRev!==t.revisaoBase){let s=0;for(const r of t.loja.values())r.geometria.tipo==="Point"&&o(r)&&s++;t.nPontos=s,t.nPontosRev=t.revisaoBase}if(!Qt(t.nPontos,e))return t.agrupador=null,null;const i=t.agrupador;if(i&&i.zoom===e&&t.agrupadorRev===t.revisaoBase)return i;const a=new ai(e,s=>t.map.project(y.latLng(s[0],s[1]),e));for(const s of t.loja.values())s.geometria.tipo==="Point"&&o(s)&&a.inserir({id:s.id,coordenada:s.geometria.coordenada});return t.agrupador=a,t.agrupadorRev=t.revisaoBase,a}reconciliar(t,e,o,i){var A;const{map:a,layerDef:s,loja:r}=e,c=this.selecionadas.get(s),l=this.estaCarregado(a),d=l?a.getZoom():0,h=l&&r.size>Le?a.getBounds().pad(ro):null,u=h?this.caixaDe(h):null;e.culling=h!==null;const f=u?e.indice.consultar(u):r.keys(),m=new Set(f);if(c)for(const M of c)r.has(M)&&m.add(M);for(const M of[...m]){const C=r.get(M);C&&!this.desenhavel(e,C)&&m.delete(M)}const g=new Map,x=l?this.agrupadorAtivo(e,d):null;if(x||(e.agrupador=null),x){for(const C of[...m])x.emCluster(C)&&m.delete(C);const M=new Map;if(c)for(const C of c){const z=x.chaveDoPonto(C),P=z===void 0||(A=x.celula(z))==null?void 0:A.membros.get(C);if(z!==void 0&&P){const v=M.get(z);v?v.push(P):M.set(z,[P])}}for(const[C,z]of x.celulasAgrupadas()){const P=M.get(C);if(P)for(const w of P)m.add(w.id);const v=z.membros.size,b=v-((P==null?void 0:P.length)??0);if(b===1)for(const w of z.membros.values()){if(c!=null&&c.has(w.id))continue;const E=e.indice.caixaDe(w.id);(!u||E&&mt(E,u))&&m.add(w.id);break}if(!(h&&!h.contains([z.somaLat/v,z.somaLon/v]))&&b>=2){let w=z.somaLat,E=z.somaLon;if(P)for(const k of P)w-=k.coordenada[0],E-=k.coordenada[1];const L=[w/b,E/b];g.set(C,{coordenada:L,total:v,assinatura:`${C}:${v}:${b}:${L[0].toFixed(7)}:${L[1].toFixed(7)}`})}}}for(const M of m){const C=r.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)&&r.has(M)||this.tirarEntrada(t,e,M);for(const[M,C]of g)this.colocarCluster(t,e,M,C);for(const M of[...e.clusters.keys()])g.has(M)||this.tirarCluster(t,e,M)}reconciliarParcial(t,e,o,i,a){const{map:s,layerDef:r,loja:c}=e,l=this.estaCarregado(s),d=l?s.getZoom():0,h=l&&c.size>Le,u=l&&Qt(e.nPontos,d),f=e.agrupador;if(a||h!==e.culling||u!==(f!==null)||f!==null&&(f.zoom!==d||e.agrupadorRev!==e.revisaoBase)){this.reconciliar(t,e,!1,new Set(o));return}const m=this.selecionadas.get(r),g=v=>this.desenhavel(e,v),x=h?s.getBounds().pad(ro):null,A=x?this.caixaDe(x):null,M=(v,b)=>{const w=c.get(v);if(!w||!g(w)){this.tirarEntrada(t,e,v);return}const E=!!(m!=null&&m.has(v));if(!E&&A){const L=e.indice.caixaDe(v);if(!L||!mt(L,A)){this.tirarEntrada(t,e,v);return}}this.materializar(t,e,w,d,E,b)},C=new Set,z=[];for(const v of i){this.tirarEntrada(t,e,v);const b=f==null?void 0:f.remover(v);b!==void 0&&C.add(b)}for(const v of o){const b=c.get(v);if(!b)continue;const w=f==null?void 0:f.remover(v);w!==void 0&&C.add(w),f&&b.geometria.tipo==="Point"&&g(b)?C.add(f.inserir({id:v,coordenada:b.geometria.coordenada})):z.push(v)}for(const v of z)M(v,!0);if(!f)return;const P=new Set(o);for(const v of C){const b=f.celula(v);if(!b||b.membros.size<2){if(this.tirarCluster(t,e,v),b)for(const T of b.membros.keys())M(T,P.has(T));continue}const w=b.membros.size;let E=b.somaLat,L=b.somaLon,k=0;for(const T of b.membros.values())m!=null&&m.has(T.id)&&(k++,E-=T.coordenada[0],L-=T.coordenada[1]);const I=w-k;for(const T of b.membros.values())m!=null&&m.has(T.id)||I===1?M(T.id,P.has(T.id)):this.tirarEntrada(t,e,T.id);const _=[b.somaLat/w,b.somaLon/w];if(x&&!x.contains(_)||I<2){this.tirarCluster(t,e,v);continue}const O=[E/I,L/I];this.colocarCluster(t,e,v,{coordenada:O,total:w,assinatura:`${v}:${w}:${I}:${O[0].toFixed(7)}:${O[1].toFixed(7)}`})}}criarMarcadorCluster(t,e,o,i){const a=e<10?30:e<100?38:46,s=Y(i.layerDef.estilo.corPrimaria,de),r=y.divIcon({className:"custom-leaflet-marker cad-feicao-cluster",iconSize:[a,a],html:`<div style="width:${a}px;height:${a}px;border-radius:50%;background:${s};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=y.marker(t,{icon:r,pane:at(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(y.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,a=new Set(e);this.selecionadas.set(o.layerDef,a);const s=[];for(const d of a)i.has(d)||s.push(d);for(const d of i)a.has(d)||s.push(d);if(s.length===0)return;const r=o.entradas,c=d=>{const h=r.get(d);if(!h)return;const u=a.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),s.length<=wn)s.forEach(c);else{const h=!!o.map._loaded?o.map.getBounds():null,u=x=>{var M;const A=(M=r.get(x))==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},f=s.filter(u),m=s.filter(x=>!u(x));f.forEach(c);const g=()=>{this.tokenLote.get(t)===l&&(m.splice(0,kn).forEach(c),m.length>0&&he(g))};m.length>0&&he(g)}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:""}`:Jt(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 a=t.estilo??{},s=Y(a.corTraco??e.estilo.corPrimaria,de),r=t.geometria.tipo==="Polygon"||t.geometria.tipo==="Circle",c=t.geometria.tipo==="Point",l=c&&Y(a.corContorno,"")||s,d=c&&typeof a.espessuraContorno=="number"&&Number.isFinite(a.espessuraContorno)&&a.espessuraContorno>=0?a.espessuraContorno:void 0,h=d??a.espessuraTraco??e.estilo.espessuraLinha??2,u=a.opacidadePreenchimento??(r?.2:.85);return{color:i?ft:l,stroke:!(d===0&&!i),weight:i?h+2:h,dashArray:a.dashArray??(K(t)==="previa"?"6 4":e.estilo.dashArray),fill:r||t.geometria.tipo==="Point",fillColor:Y(a.corPreenchimento,s),fillOpacity:i?Math.min(1,u+.18):u,lineJoin:"round",interactive:o}}criar(t,e,o,i,a){var d,h;const s=at(o,e.id,this.paneDe(t)),r=t.geometria,c=this.estiloVetor(t,e,i,a),l=ei(r,{...c,pane:s});if(l)return l;switch(r.tipo){case"Polygon":return y.polygon(r.aneis.length===1?r.aneis[0]:r.aneis,{...c,pane:s});case"Circle":return y.circle(r.centro,{...c,radius:r.raioMetros,pane:s});case"LineString":return y.polyline(r.partes&&r.partes.length>1?U(r):r.coordenadas,{...c,pane:s});case"Point":{const u=(d=t.estilo)==null?void 0:d.icone;return u&&Rt[u]?y.marker(r.coordenada,{icon:this.iconeSvg(t,e,a),pane:s,interactive:i}):y.circleMarker(r.coordenada,{...c,radius:(((h=t.estilo)==null?void 0:h.tamanhoIcone)??e.estilo.tamanhoMarcador??8)/2,pane:s})}default:return y.marker(r.coordenada,{icon:this.iconeTexto(t,e,a),pane:s,interactive:i,draggable:i&&!t.bloqueada})}}remendar(t,e,o,i,a){var c,l,d;const s=e.geometria,r=this.estiloVetor(e,o,i,a);(t instanceof Qo||t instanceof ti)&&Jt(s)?(Sn(t,s),t.setStyle(r)):s.tipo==="Polygon"?(t.setLatLngs(s.aneis.length===1?s.aneis[0]:s.aneis),t.setStyle(r)):s.tipo==="LineString"?(t.setLatLngs(s.partes&&s.partes.length>1?U(s):s.coordenadas),t.setStyle(r)):s.tipo==="Circle"?(t.setLatLng(s.centro),t.setRadius(s.raioMetros),t.setStyle(r)):s.tipo==="Point"&&t instanceof y.CircleMarker?(t.setLatLng(s.coordenada),t.setRadius((((c=e.estilo)==null?void 0:c.tamanhoIcone)??o.estilo.tamanhoMarcador??8)/2),t.setStyle(r)):t instanceof y.Marker&&(t.setLatLng(s.tipo==="Point"||s.tipo==="Text"?s.coordenada:t.getLatLng()),t.setIcon(s.tipo==="Text"?this.iconeTexto(e,o,a):this.iconeSvg(e,o,a)),s.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??{},a=i.tamanhoIcone??e.estilo.tamanhoMarcador,s=typeof a=="number"&&Number.isFinite(a)&&a>0?a:22,r=o?ft:Y(i.corTraco??i.corPreenchimento??e.estilo.corPrimaria,de),c=Number.isFinite(i.rotacaoIcone)?i.rotacaoIcone:0,l=Rt[i.icone??""]??"";return y.divIcon({className:`custom-leaflet-marker${o?" cad-feicao-selecionada":""}`,iconSize:[s,s],html:`<svg width="${s}" height="${s}" 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(${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??{},a=t.geometria.tipo==="Text"?t.geometria.texto:"",s=o?ft:Y(i.corTraco??e.estilo.corPrimaria,"#ffffff"),r=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:${s};font-size:${r}px;font-weight:600;`,d=Y(i.corFundo,"");if(d){const u=Y(i.corBorda,""),f=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,g=o?`1px solid ${ft}`:u?`1px solid ${u}`:"none";return y.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:${g}"><span style="position:absolute;top:0;right:0;bottom:0;left:0;border-radius:inherit;background:${d};opacity:${f}"></span><span style="position:relative">${S.escapeHtml(a)}</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 y.divIcon({className:`custom-leaflet-marker cad-feicao-texto${o?" cad-feicao-selecionada":""}`,iconSize:void 0,html:`<span style="${l}${h}">${S.escapeHtml(a)}</span>`})}aplicarRotulo(t,e){const o=e.estilo;if(!(o!=null&&o.mostrarRotulo)||e.geometria.tipo==="Text"){t.unbindTooltip();return}const i=Go(e,o.campoRotulo);if(!i){t.unbindTooltip();return}const a=document.createElement("span");a.textContent=i,t.getTooltip()?t.setTooltipContent(a):t.bindTooltip(a,{permanent:!0,direction:"center",className:"cad-feicao-rotulo",interactive:!1})}ligarEventos(t,e,o,i,a){t.on("click",s=>{var l;const r=i.get(e);if(!r)return;const c=s==null?void 0:s.originalEvent;(l=a.onLayerAction)==null||l.call(a,"feicao-clique",{camadaId:o.id,feicao:r.feicao,aditivo:!!(c&&(c.ctrlKey||c.metaKey||c.shiftKey))})}),t instanceof y.Marker&&t.on("dragend",()=>{var l;const s=i.get(e);if(!s||s.feicao.geometria.tipo!=="Text")return;const{lat:r,lng:c}=t.getLatLng();s.feicao={...s.feicao,geometria:{...s.feicao.geometria,coordenada:[r,c]}},(l=a.onLayerAction)==null||l.call(a,"feicao-movida",{camadaId:o.id,feicao:s.feicao})})}}F.register("tile",new $o);F.register("wms",new qo);F.register("vetorial-linhas",new Oo);F.register("vetorial-pontos",new Ro);F.register("vetorial-poligonos",new Bo);F.register("grid",new Ho);F.register("feicoes",new si);const Se=[{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"}}],En=new Set(["tile","wms","grid"]);class ri{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||Se).map(e=>({...e,estilo:{...e.estilo}}))}descartarCamadasPadrao(){if(this.map)return;const t=new Set(Se.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&&En.has(e.tipo)&&e.visivel&&this.layerInstances.has(e.id))){if(this.layerInstances.has(e.id)){const o=this.layerInstances.get(e.id),i=F.get(e.tipo);i&&i.destroy(o,this.map),this.layerInstances.delete(e.id)}if(e.visivel){const o=F.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(s=>s.id===t);if(!o||o.visivel===e||(o.visivel=e,!this.map||!this.context))return;const i=`pane-${o.id}`,a=this.map.getPane(i);if(a&&(a.style.display=e?"":"none",a.style.pointerEvents=o.visivel&&o.interativo&&!o.bloqueada?"auto":"none"),e){if(!this.layerInstances.has(t)){const s=F.get(o.tipo);if(s){const r=s.render(o,this.map,this.context);r&&(r.addTo(this.map),this.layerInstances.set(t,r))}}}else if(this.layerInstances.has(t)){const s=this.layerInstances.get(t),r=F.get(o.tipo);r&&r.destroy(s,this.map),this.layerInstances.delete(t)}this.notifyChange()}setLayerOpacity(t,e){this.flushRender();const o=this.layers.find(a=>a.id===t);if(!o)return;if(o.opacidade=Math.max(0,Math.min(1,e)),this.map){const a=this.map.getPane(`pane-${t}`);a&&(a.style.opacity=String(o.opacidade))}const i=this.layerInstances.get(t);if(i&&this.map&&this.context){const a=F.get(o.tipo);a&&a.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(a=>a.id===t);if(!o)return;o.estilo.scaleMode=e;const i=this.layerInstances.get(t);if(i&&this.map&&this.context){const a=F.get(o.tipo);a&&a.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(a=>a.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(a=>a.id===t);if(!o)return;o.dados=e;const i=this.layerInstances.get(t);if(i&&this.map&&this.context){const a=F.get(o.tipo);a&&a.update(o,i,{dados:e},this.context,this.map)}else if(o.visivel&&this.map&&this.context){const a=F.get(o.tipo);if(a){const s=a.render(o,this.map,this.context);s&&(s.addTo(this.map),this.layerInstances.set(t,s))}}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),a=this.layers.find(s=>s.id===o);if(a){const s=F.get(a.tipo);s&&s.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=F.get(o.tipo);i&&i.destroy(t,this.map)}}),this.layerInstances.clear()),this.listeners=[]}}function ci(n,t){var s,r;if(t==null)return null;const e=String(t).trim(),o=c=>c?(c.lon=c.lng,c):null,a=n.getMarkers().find(c=>{var f,m,g,x;const l=c.pontoId,d=c.elementoId??c.id??((f=c.options)==null?void 0:f.pontoId)??((m=c.options)==null?void 0:m.id),h=(g=c.elemento)==null?void 0:g.nome_vertice,u=(x=c.elemento)==null?void 0:x.codigo_completo;return String(l)===e||String(d)===e||h&&String(h).toLowerCase()===e.toLowerCase()||u&&String(u).toLowerCase()===e.toLowerCase()});if(a&&typeof a.getLatLng=="function")return o(a.getLatLng());if(n.layerManager)for(const c of n.layerManager.getAllLayerInstances()){let l=null;const d=h=>{var m,g,x,A,M;if(l)return;const u=h.pontoId??h.elementoId??h.id??((m=h.options)==null?void 0:m.id)??((g=h.options)==null?void 0:g.pontoId),f=((x=h.elemento)==null?void 0:x.nome)??((A=h.elemento)==null?void 0:A.nome_vertice)??((M=h.options)==null?void 0:M.nome);(String(u)===e||f&&String(f).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(n.context.pontos&&n.context.pontos.length>0){const c=n.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(y.latLng(h.lat,h.lon))}}if(n.context.bancoPontos&&n.context.bancoPontos.length>0){const c=n.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(y.latLng(h.lat,h.lon))}}if(n.context.confrontantes&&n.context.confrontantes.length>0){const c=n.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 f=u.lat??u.latitude??u.y,m=u.lon??u.lng??u.longitude??u.x,g=S.parseCoordenada(f,m);g&&(l+=g.lat,d+=g.lon,h++)}if(h>0)return o(y.latLng(l/h,d/h))}if(c.poligono_wkt){const l=S.extrairCentroDeWkt(c.poligono_wkt);if(l)return o(y.latLng(l.lat,l.lon))}}}if(n.context.segmentos&&n.context.segmentos.length>0){const c=n.context.segmentos.find(l=>String(l.id)===e||`${l.ponto_inicio_id}-${l.ponto_fim_id}`===e);if(c){const l=(s=n.context.pontos)==null?void 0:s.find(h=>String(h.id)===String(c.ponto_inicio_id)),d=(r=n.context.pontos)==null?void 0:r.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(y.latLng((h.lat+u.lat)/2,(h.lon+u.lon)/2))}}}if(n.layerManager){for(const c of n.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(y.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(y.latLng(d.lat,d.lon))}if(Array.isArray(l.coordenadas)&&l.coordenadas.length>0){let d=0,h=0,u=0;for(const f of l.coordenadas){const m=S.parseCoordenada(f[0],f[1])||S.parseCoordenada(f[1],f[0]);m&&(d+=m.lat,h+=m.lon,u++)}if(u>0)return o(y.latLng(d/u,h/u))}}}}}return null}function In(n,t,e,o){var f,m;Me(t,n.getMap());const i=n.getMap();if(!i)return;const a=ci(n,e);if(!a){console.warn(`[ui-canvas-cad] Elemento com identificador "${e}" não encontrado para destaque.`);return}const s=(o==null?void 0:o.pan)===!0,r=o==null?void 0:o.zoom;s?r!==void 0?typeof i.flyTo=="function"?i.flyTo(a,r,{animate:!0}):i.setView(a,r,{animate:!0}):typeof i.panTo=="function"?i.panTo(a,{animate:!0}):i.setView(a,i.getZoom(),{animate:!0}):r!==void 0&&i.setZoom(r,{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=y.divIcon({className:"cad-destaque-marker-container",html:`
|
|
100
100
|
<div class="cad-pulse-highlight" style="--cad-pulse-cor: ${S.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
|
-
${t.map(
|
|
107
|
-
<div class="layer-item" data-layer-id="${
|
|
105
|
+
`,iconSize:[52,52],iconAnchor:[26,26]});t.destaqueMarker=y.marker(a,{icon:h,pane:l,interactive:!1,keyboard:!1}),t.destaqueMarker.addTo(i);const u=(m=(f=t.destaqueMarker).getElement)==null?void 0:m.call(f);u&&(u.style.pointerEvents="none"),o!=null&&o.duracaoMs&&o.duracaoMs>0&&(t.destaqueTimeoutId=window.setTimeout(()=>{Me(t,i)},o.duracaoMs))}function Me(n,t){n.destaqueTimeoutId!==null&&(window.clearTimeout(n.destaqueTimeoutId),n.destaqueTimeoutId=null),n.destaqueMarker&&(t&&t.hasLayer(n.destaqueMarker)?t.removeLayer(n.destaqueMarker):typeof n.destaqueMarker.remove=="function"&&n.destaqueMarker.remove(),n.destaqueMarker=null)}function _n(n,t){const e=new Map;n.forEach(i=>{const a=i.lat??i.latitude??i.y,s=i.lon??i.lng??i.longitude??i.x,r=S.parseCoordenada(a,s);r&&(i.lat=r.lat,i.lon=r.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 a=i.id!==void 0&&i.id!==null?i.id:0;o.set(a,{...i,pontos:[]})}),e.forEach((i,a)=>{var s,r;if(o.has(a)){const c=o.get(a);c.pontos=i}else o.set(a,{id:a,nome:((s=i[0])==null?void 0:s.nome_confrontante)||"Confrontante",nome_propriedade:((r=i[0])==null?void 0:r.nome_propriedade)||"",pontos:i})}),Array.from(o.values()).filter(i=>i.pontos&&i.pontos.length>0||!!i.poligono_wkt)}function Tn(n,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)}),n.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 Dn(n,t,e=!1){let o=[...n];e&&t&&t.forEach(a=>{a.pontos&&o.push(...a.pontos)});const i=o.map(a=>{const s=a.lat??a.latitude??a.y,r=a.lon??a.lng??a.longitude??a.x,c=S.parseCoordenada(s,r);return c?y.latLng(c.lat,c.lon):null}).filter(a=>a!==null);return i.length===1?{single:i[0]}:i.length>1?{bounds:y.latLngBounds(i)}:null}function $n(n,t){var a;(a=t==null?void 0:t.flushRender)==null||a.call(t);const e=[],o=new Set,i=s=>{s instanceof y.Marker&&s.pontoId!==void 0&&!o.has(s)&&(o.add(s),e.push(s))};return n&&n.eachLayer(s=>{i(s),typeof s.eachLayer=="function"&&s.eachLayer(i)}),t&&t.getAllLayerInstances().forEach(s=>{i(s),typeof s.eachLayer=="function"&&s.eachLayer(i)}),e}function qn(n,t,e="vertices",o){const i=t||[];n.layerManager.getOrCreateLayer(e,"vetorial-pontos","Pontos / Vértices"),e==="vertices"&&(n.context.pontos=i,n.canvasInteracao.ctx.pontosList=i,o&&(n.customMarkerClickCallback=a=>{const s=i.find(r=>String(r.id)===String(a))||{id:a,lat:0,lon:0};o(s)})),n.layerManager.setLayerData(e,{pontos:i,onClique:o}),n.layerManager.setLayerVisibility(e,!0)}function Nn(n,t,e="linhas"){const o=t||[];n.layerManager.getOrCreateLayer(e,"vetorial-linhas","Conexões / Linhas"),(e==="linhas"||e==="perimetro")&&(n.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"}))),n.layerManager.setLayerData(e,{conexoes:o}),n.layerManager.setLayerVisibility(e,!0)}function On(n,t,e=!0,o="polilinha",i){const a=t||[];n.layerManager.getOrCreateLayer(o,"vetorial-linhas","Polilinhas"),(o==="polilinha"||o==="perimetro")&&(n.context.pontos=a,n.context.segmentos=[],n.canvasInteracao.ctx.pontosList=a);const s=i||n.chaveGrupo||n.context.chaveGrupo;n.layerManager.setLayerData(o,{pontos:a,fechar:e!==!1,polilinhaSequencial:!0,chaveGrupo:s}),n.layerManager.setLayerVisibility(o,!0)}function Fn(n,t,e="poligonos"){const o=t||[];n.layerManager.getOrCreateLayer(e,"vetorial-poligonos","Polígonos"),n.layerManager.setLayerData(e,{poligonos:o}),n.layerManager.setLayerVisibility(e,!0)}function Rn(n,t,e){const o=t||[];if(e!=null){const i=e||[];n.context.pontos=i,n.canvasInteracao.ctx.pontosList=i}n.context.segmentos=o,n.layerManager.updateContext({segmentos:o,...e!=null?{pontos:n.context.pontos}:{}})}function Bn(n,t=!1){n.context.pontos=[],n.context.segmentos=[],n.context.confrontantes=[],n.canvasInteracao.ctx.pontosList=[],n.canvasInteracao.limparSelecao();const e={pontos:[],segmentos:[],confrontantes:[]};t||(n.context.bancoPontos=[],e.bancoPontos=[]),n.layerManager.updateContext(e)}function co(n){return n!=null&&!isNaN(Number(n))&&String(n).trim()!==""?Number(n):n}function Hn(n,t){var r,c;const e=n.core.map,o=n.layerManager.getLayerDef(t.layerId),i=t.baseSize||8,a=((r=n.context.graphicScale)==null?void 0:r.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),f=l/(u>0?u:1);return Math.max(3,Math.round(f*a))}const s=Te(t.densTotal||0,(e==null?void 0:e.getZoom())??18);return Math.max(s<1?5:4,Math.round(i*a*s))}function Vn(n,t,e,o,i){const a=Hn(n,e),s=n.context.config.enableAnimations?"cad-pt-anim":"",r=wt(e.shapeStyle,a,e.markerBg,s,`map-marker-${e.layerId||"pts"}-${o}`,i,{densidade:Xt(e.densTotal||0)});e.tamanhoPx=a,t.setIcon(y.divIcon({html:r,className:`custom-leaflet-marker ${i?"cad-marker-selected ponto-selecionado":""}`,iconSize:[a+6,a+6]}))}function Gn(n){const t=n.context.selectedPontoIds||[],e=n.canvasInteracao.ctx.selectedVizinhoPontoIds||[],o=new Set([...t.map(String),...e.map(String)]);for(const i of n.getMarkers()){const a=i,s=a.pontoId;if(s==null)continue;const r=o.has(String(s));if(a.isSelected===r)continue;a.isSelected=r,i.setZIndexOffset(r?2e3:0),a.shapeStyle&&a.baseSize&&a.markerBg&&Vn(n,i,a,s,r);const c=i.getElement();c&&(r?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 wo(this),this.layerManager=new ri(t),this.canvasInteracao=new Do({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=co(e);if(this.customMarkerClickCallback)try{this.customMarkerClickCallback(i,o)}catch(a){console.error("Erro no customMarkerClickCallback:",a)}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(a){console.error("Erro no customPopupActionCallback:",a)}}}}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){qn(this,t,e,o)}plotarConexoes(t,e="linhas"){Nn(this,t,e)}plotarPolilinhaSequencial(t,e=!0,o="polilinha",i){On(this,t,e,o,i)}plotarPoligonos(t,e="poligonos"){Fn(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=a=>{a instanceof y.Marker&&e.push(a)};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){Rn(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=_n(t||[],this.context.confrontantes||[]);this.setConfrontantes(e),this.layerManager.setLayerVisibility("vizinhos",!0)}plotPoligonosVizinhos(t){const e=Tn(t||[],this.context.confrontantes||[]);this.setConfrontantes(e),this.layerManager.setLayerVisibility("vizinhos",!0)}clearOverlays(t=!1){Bn(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(s=>String(s.pontoId)===o);if(i){const s=e!==void 0?e:this.core.map.getZoom();this.core.map.setView(i.getLatLng(),s),i.openPopup()}const a=co(t);this.canvasInteracao.ctx.selectedPontoIds=[a],this.canvasInteracao.ctx.lastSelectedPontoId=a,this.context.selectedPontoIds=[a],this.atualizarDestaqueMarcadores()}atualizarDestaqueMarcadores(){Gn(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=Dn(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 $n(this.core.map,this.layerManager)}getVizinhosMarkers(){return this.getMarkers().filter(t=>!!t.isVizinho)}get destaqueAtivo(){return this.destaqueState.destaqueMarker!==null}localizarCoordenadasElemento(t){return ci(this,t)}destacarElemento(t,e){In(this,this.destaqueState,t,e)}limparDestaque(){Me(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 li(n,t,e,o){if(!n)return;if(n.querySelectorAll(".layer-item").length===t.length){t.forEach(a=>{var r,c;const s=n.querySelector(`.layer-item[data-layer-id="${a.id}"]`);if(s){const l=s.querySelector(".layer-chk-visibility");l&&l.checked!==a.visivel&&(l.checked=a.visivel);const d=s.querySelector(".layer-opacity-slider"),h=s.querySelector(".opacity-percent-label"),u=Math.round(a.opacidade*100);d&&parseInt(d.value,10)!==u&&(d.value=String(u)),h&&(h.textContent=`${u}%`);const f=s.querySelector(".btn-lock-layer");f&&(f.classList.toggle("active",!!a.bloqueada),f.title=a.bloqueada?"Desbloquear Camada":"Bloquear Camada");const m=s.querySelector(".btn-toggle-scale-mode");m&&((r=a.estilo)!=null&&r.scaleMode)&&(m.textContent=((c=a.estilo)==null?void 0:c.scaleMode)==="world"?"Métrico":"Tela")}});return}n.innerHTML=`
|
|
106
|
+
${t.map(a=>{var s,r;return`
|
|
107
|
+
<div class="layer-item" data-layer-id="${a.id}">
|
|
108
108
|
<div class="layer-item-row">
|
|
109
109
|
<label class="layer-item-label">
|
|
110
|
-
<input type="checkbox" class="layer-chk-visibility" data-layer-id="${
|
|
111
|
-
<span>${
|
|
110
|
+
<input type="checkbox" class="layer-chk-visibility" data-layer-id="${a.id}" ${a.visivel?"checked":""} />
|
|
111
|
+
<span>${a.nome}</span>
|
|
112
112
|
</label>
|
|
113
113
|
<div class="layer-item-actions">
|
|
114
|
-
<button class="btn-layer-action btn-lock-layer ${
|
|
115
|
-
${
|
|
114
|
+
<button class="btn-layer-action btn-lock-layer ${a.bloqueada?"active":""}" data-layer-id="${a.id}" type="button" title="${a.bloqueada?"Desbloquear Camada":"Bloquear Camada"}">
|
|
115
|
+
${a.bloqueada?'<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>':'<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 9.9-1"/></svg>'}
|
|
116
116
|
</button>
|
|
117
|
-
${(
|
|
118
|
-
<span class="scale-mode-pill btn-toggle-scale-mode" data-layer-id="${
|
|
119
|
-
${((
|
|
117
|
+
${(s=a.estilo)!=null&&s.scaleMode?`
|
|
118
|
+
<span class="scale-mode-pill btn-toggle-scale-mode" data-layer-id="${a.id}" title="Alternar modo de escala">
|
|
119
|
+
${((r=a.estilo)==null?void 0:r.scaleMode)==="world"?"Métrico":"Tela"}
|
|
120
120
|
</span>
|
|
121
121
|
`:""}
|
|
122
122
|
</div>
|
|
123
123
|
</div>
|
|
124
124
|
<div class="layer-controls-row">
|
|
125
125
|
<span>Opacidade</span>
|
|
126
|
-
<input type="range" min="0" max="100" value="${Math.round(
|
|
127
|
-
<span class="opacity-percent-label" style="font-family:var(--ui-fonte-codigo, monospace); font-size:9px; width:28px; text-align:right;">${Math.round(
|
|
126
|
+
<input type="range" min="0" max="100" value="${Math.round(a.opacidade*100)}" class="layer-opacity-slider" data-layer-id="${a.id}" />
|
|
127
|
+
<span class="opacity-percent-label" style="font-family:var(--ui-fonte-codigo, monospace); font-size:9px; width:28px; text-align:right;">${Math.round(a.opacidade*100)}%</span>
|
|
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
|
+
`,e.cleanup(),n.querySelectorAll(".layer-chk-visibility").forEach(a=>{e.add(a,"change",s=>{const r=s.target.getAttribute("data-layer-id"),c=s.target.checked;r&&o.setLayerVisibility(r,c)})}),n.querySelectorAll(".layer-opacity-slider").forEach(a=>{e.add(a,"input",s=>{const r=s.target.getAttribute("data-layer-id"),c=parseInt(s.target.value,10),l=c/100,d=s.target.closest(".layer-item"),h=d==null?void 0:d.querySelector(".opacity-percent-label");h&&(h.textContent=`${c}%`),r&&o.setLayerOpacity(r,l)})}),n.querySelectorAll(".btn-lock-layer").forEach(a=>{e.add(a,"click",s=>{const r=s.currentTarget.getAttribute("data-layer-id");if(r){const c=t.find(l=>l.id===r);c&&o.setLayerBlocked(r,!c.bloqueada)}})}),n.querySelectorAll(".btn-toggle-scale-mode").forEach(a=>{e.add(a,"click",s=>{var c;const r=s.currentTarget.getAttribute("data-layer-id");if(r){const l=t.find(d=>d.id===r);if(l){const d=((c=l.estilo)==null?void 0:c.scaleMode)==="world"?"screen":"world";o.setLayerScaleMode(r,d)}}})})}function di(n,t,e,o){var x,A,M,C,z,P;if(n.modoSequencial||n.controller.canvasInteracao.selectionHappened||n.controller.canvasInteracao.panHappened||n.mouseMovedSinceDown)return!1;const i=(t==null?void 0:t.originalEvent)||t,a=typeof(i==null?void 0:i.composedPath)=="function"?i.composedPath():[],s=a.length>0?a[0]:(i==null?void 0:i.target)||(t==null?void 0:t.target);if(s){const v='.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(((x=s.matches)==null?void 0:x.call(s,v))||((A=s.closest)==null?void 0:A.call(s,v)))return!1}const r=n.controller.getMap();if(!r||!n.mapContainer)return!1;let c,l;if(o)c=Math.round(o.x),l=Math.round(o.y);else if(t!=null&&t.containerPoint||t!=null&&t.layerPoint)c=Math.round(((M=t.containerPoint)==null?void 0:M.x)??((C=t.layerPoint)==null?void 0:C.x)??0),l=Math.round(((z=t.containerPoint)==null?void 0:z.y)??((P=t.layerPoint)==null?void 0:P.y)??0);else{const v=n.mapContainer.getBoundingClientRect(),b=(i==null?void 0:i.clientX)??0,w=(i==null?void 0:i.clientY)??0;c=Math.round(b-v.left),l=Math.round(w-v.top)}const d={x:c,y:l};let h,u;const f=e||(t==null?void 0:t.latlng);if(f&&typeof f.lat=="number")h=f.lat,u=f.lng??f.lon??0;else{const v=r.containerPointToLatLng(y.point(d.x,d.y));h=v.lat,u=v.lng}const m=n.controller.layerManager?n.controller.layerManager.getLayers().filter(v=>v.visivel).map(v=>v.id):[],g=i;return n.host.dispatchEvent(new CustomEvent("ui-canvas-clique",{detail:{coordenadas:{lat:h,lng:u},pontoPixel:d,eventoOriginal:g,lat:h,lon:u,lng:u,camadasAtivas:m},bubbles:!0,composed:!0})),!0}function hi(n,t,e,o){const i=o||n.obterElementoPorId(e);n.host.dispatchEvent(new CustomEvent("ui-acao-popup",{detail:{acaoId:t,elementoId:e,elemento:i??{id:e}},bubbles:!0,composed:!0})),n.fecharPopup()}function ui(n,t,e,o,i,a,s){let r=o||n.obterElementoPorId(t),c=i;if(!c&&r){const l=r.lat??r.latitude??0,d=r.lon??r.lng??r.longitude??0;c={lat:Number(l),lon:Number(d)}}if(c||(c={lat:0,lon:0}),n.modoSequencial){n.fecharPopup(),n.host.dispatchEvent(new CustomEvent("ui-clique-sequencial",{detail:{id:t,elemento:r??{id:t,lat:c.lat,lon:c.lon},coordenadas:c},bubbles:!0,composed:!0}));return}if(s)try{const l=t!=null&&!isNaN(Number(t))&&String(t).trim()!==""?Number(t):t;s(l,e)}catch(l){console.error("Erro no callback de clique de marcador:",l)}if(a)try{a(t,e,r,c)}catch(l){console.error("Erro no handler anterior de marker click:",l)}n.controller.context.selectedSegmentoId&&n.controller.selectSegmento(null),n.host.dispatchEvent(new CustomEvent("ui-ponto-selecionado",{detail:{selectedIds:[t],lastSelectedId:t,isVizinho:e},bubbles:!0,composed:!0})),n.host.dispatchEvent(new CustomEvent("ui-elemento-selecionado",{detail:{id:t,elemento:r,tipo:e?"vizinho":"vertice",coordenadas:c},bubbles:!0,composed:!0}))}function pi(n,t,e,o,i){if(n.modoSequencial){n.fecharPopup();return}if(n.controller.canvasInteracao.ctx.selectedPontoIds=[],n.controller.canvasInteracao.ctx.selectedVizinhoPontoIds=[],n.controller.canvasInteracao.ctx.lastSelectedPontoId=null,n.controller.context.selectedPontoIds=[],n.controller.atualizarDestaqueMarcadores(),n.controller.selectSegmento(t),i)try{i(t,e)}catch(a){console.error("Erro no callback de clique de segmento:",a)}n.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})),n.host.dispatchEvent(new CustomEvent("ui-elemento-selecionado",{detail:{id:t,elemento:e,tipo:"segmento",coordenadas:o},bubbles:!0,composed:!0}))}function fi(n,t){let e=null,o=null,i=0,a=0;function s(){var d;try{if(!n.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 r(d=25){o!==null&&(window.clearTimeout(o),o=null),o=window.setTimeout(()=>{o=null,s()},d)}function c(){l(),!(typeof ResizeObserver>"u")&&(e=new ResizeObserver(d=>{for(const h of d){let u=0,f=0;h.contentRect?(u=h.contentRect.width,f=h.contentRect.height):h.borderBoxSize&&h.borderBoxSize.length>0?(u=h.borderBoxSize[0].inlineSize,f=h.borderBoxSize[0].blockSize):(u=n.clientWidth||n.offsetWidth,f=n.clientHeight||n.offsetHeight),u>0&&f>0&&(Math.abs(u-i)>=.5||Math.abs(f-a)>=.5)&&(i=u,a=f,r(25))}}),e.observe(n))}function l(){e&&(e.disconnect(),e=null),o!==null&&(window.clearTimeout(o),o=null)}return{observe:c,disconnect:l,invalidateSizeSafely:s}}class jn{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.tipo||"ESTILOS_ALTERADOS",o=t.configuracoes||t;if(o.crosshair!==void 0){const i=!!o.crosshair;this.contexto.mapContainer&&(this.contexto.mapContainer.style.cursor=i?"crosshair":"");const a=this.contexto.controller.getMap();if(a){const s=a.getContainer();s&&(s.style.cursor=i?"crosshair":"")}this.contexto.controller.core.config.crosshair=i}if(o.opacidadeBase!==void 0){const i=parseFloat(o.opacidadeBase);isNaN(i)||this.contexto.setLayerOpacity("satelite",i)}if(o.satOpacity!==void 0){const i=parseFloat(o.satOpacity);isNaN(i)||this.contexto.setLayerOpacity("satelite",i)}o.opacidades&&typeof o.opacidades=="object"&&Object.entries(o.opacidades).forEach(([i,a])=>{const s=parseFloat(a);isNaN(s)||this.contexto.setLayerOpacity(i,s)}),this.contexto.host.dispatchEvent(new CustomEvent("ui-config-aplicada",{detail:{tipo:e,configuracoes:o},bubbles:!0,composed:!0}))}desconectar(){if(this.canal){try{this.canal.close()}catch{}this.canal=null}}}class Un{constructor(t){p(this,"contexto");p(this,"uiListeners",new ye.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"),a=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 s,r;(r=(s=this.contexto).onZoomExtents)==null||r.call(s)}),this.uiListeners.add(i,"click",()=>{var s,r;(r=(s=this.contexto).onLimparSelecao)==null||r.call(s)}),this.uiListeners.add(a,"click",()=>{var s,r;(r=(s=this.contexto).onToggleSnap)==null||r.call(s)}),this.contexto.mapContainer&&(this.uiListeners.add(this.contexto.mapContainer,"mousedown",s=>{s.button===0&&(this.mouseDownPos={x:s.clientX,y:s.clientY},this.mouseMovedSinceDown=!1)}),this.uiListeners.add(this.contexto.mapContainer,"mousemove",s=>{Math.hypot(s.clientX-this.mouseDownPos.x,s.clientY-this.mouseDownPos.y)>=4&&(this.mouseMovedSinceDown=!0)}),this.uiListeners.add(this.contexto.mapContainer,"click",s=>{var r,c;s.button===0&&(this.mouseMovedSinceDown||(c=(r=this.contexto).onTratarCliqueCanvas)==null||c.call(r,s))})),this.uiListeners.add(this.contexto.shadow,"click",s=>{var l,d,h;const r=s.composedPath?s.composedPath()[0]:s.target,c=(l=r==null?void 0:r.closest)==null?void 0:l.call(r,".ui-popup-btn");if(c){s.preventDefault(),s.stopPropagation();const u=c.getAttribute("data-acao-id"),f=c.getAttribute("data-elemento-id");u&&f!==null&&((h=(d=this.contexto).onDispararAcaoPopup)==null||h.call(d,u,f))}})}limpar(){this.uiListeners.cleanup()}}class Wn{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 a=t||[];(o==="polilinha"||o==="perimetro")&&(this._pontos=a,this._segmentos=[]);const s=i??this.contexto.obterChaveGrupo();this.contexto.obterController().plotarPolilinhaSequencial(a,e,o,s)}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 Xn=':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}';function Zn(){return`
|
|
132
132
|
<style>
|
|
133
133
|
${S.leafletCss}
|
|
134
|
-
${
|
|
134
|
+
${Xn}
|
|
135
135
|
</style>
|
|
136
|
-
<div class="cad-root" id="cad-root"
|
|
136
|
+
<div class="cad-root" id="cad-root">
|
|
137
137
|
<div class="cad-map-container" id="cad-map-container"></div>
|
|
138
138
|
<div class="qgis-layer-panel collapsed" id="qgis-layer-panel">
|
|
139
139
|
<div class="layer-panel-header">
|
|
@@ -147,8 +147,7 @@
|
|
|
147
147
|
</div>
|
|
148
148
|
<div class="layer-panel-body" id="layers-list-container"></div>
|
|
149
149
|
</div>
|
|
150
|
-
<div class="cad-
|
|
151
|
-
<div class="cad-quick-toolbar" role="toolbar" aria-label="Controles do mapa">
|
|
150
|
+
<div class="cad-quick-toolbar">
|
|
152
151
|
<button class="cad-btn-tool" id="btn-toggle-layers" type="button" title="Camadas">
|
|
153
152
|
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polygon points="12 2 2 7 12 12 22 7 12 2"/><polyline points="2 17 12 22 22 17"/><polyline points="2 12 12 17 22 12"/></svg>
|
|
154
153
|
</button>
|
|
@@ -163,18 +162,18 @@
|
|
|
163
162
|
</button>
|
|
164
163
|
</div>
|
|
165
164
|
</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(`
|
|
165
|
+
`}function Yn(n,t,e,o){if(e!==o){if(t==="sat-opacity"){const i=parseFloat(o);isNaN(i)||n.setLayerOpacity("satelite",i)}else if(t==="scale-mode")(o==="world"||o==="screen")&&(n.setLayerScaleMode("perimetro",o),n.setLayerScaleMode("vertices",o));else if(t==="modo-sequencial")n.host.modoSequencial=o!==null&&o!=="false";else if(t==="chave-grupo")n.host.chaveGrupo=o||void 0;else if(t==="zona-projecao"||t==="fuso"){const i=parseInt(o,10);!isNaN(i)&&i>0&&(n.atualizarZonaProjecao(i),t==="fuso"&&n.host.getAttribute("zona-projecao")!==o?n.host.setAttribute("zona-projecao",o):t==="zona-projecao"&&n.host.hasAttribute("fuso")&&n.host.getAttribute("fuso")!==o&&n.host.setAttribute("fuso",o),n.controller.zonaProjecao=i,n.controller.context.zonaProjecao=i)}else if(t==="canal-configuracao")n.broadcastConfig.conectar(o);else if(t==="crosshair"){const i=o!==null&&o!=="false";n.mapContainer&&(n.mapContainer.style.cursor=i?"crosshair":"");const a=n.controller.getMap();if(a){const s=a.getContainer();s&&(s.style.cursor=i?"crosshair":"")}n.controller.core.config.crosshair=i}}}function Kn(n){if(!n.mapContainer)return;if(n.mapContainer._leaflet_id&&!n.controller.getMap())try{delete n.mapContainer._leaflet_id}catch{n.mapContainer._leaflet_id=void 0}if(n.controller.init(n.mapContainer,n.shadow),n.toolbarPainel.vincularEventos(),n.renderLayersUI(),n.host.hasAttribute("modo-sequencial")&&(n.controller.modoCliqueSequencialAtivo=!0,n.controller.context.modoSequencial=!0),n.host.hasAttribute("chave-grupo")){const o=n.host.getAttribute("chave-grupo");o&&(n.host.chaveGrupo=o)}if(n.host.hasAttribute("zona-projecao")||n.host.hasAttribute("fuso")){const o=n.host.zonaProjecao;n.controller.zonaProjecao=o,n.controller.context.zonaProjecao=o}if(n.host.hasAttribute("crosshair")){const o=n.host.getAttribute("crosshair")!=="false";n.mapContainer&&(n.mapContainer.style.cursor=o?"crosshair":""),n.controller.core.config.crosshair=o}n.colecoesDados.sincronizarInicial(),n.controller.layerManager.onChange(o=>{n.renderLayersUI(),n.host.dispatchEvent(new CustomEvent("ui-camadas-alteradas",{detail:{layers:o},bubbles:!0,composed:!0}))});const t=n.controller.context.onMarkerClick;n.controller.context.onMarkerClick=(o,i,a,s)=>{ui(n.obterContextoEventos(),o,i,a,s,t,n.colecoesDados.customMarkerClickHandler)},n.controller.context.onSegmentoClick=(o,i,a)=>{pi(n.obterContextoEventos(),o,i,a)},n.controller.context.onPopupAcao=(o,i,a)=>{n.dispararAcaoPopup(o,i,a)};const e=n.controller.getMap();e&&e.on("click",o=>{n.toolbarPainel.houveMovimentoMouse||n.tratarCliqueLivreCanvas(o,o.latlng,o.containerPoint)}),setTimeout(()=>{n.invalidateSizeSafely()},150)}function Z(n,t){let e,o;if(Array.isArray(n))[e,o]=n;else if(n&&typeof n=="object"){const a=n;e=a.lat??a.latitude,o=a.lng??a.lon??a.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 Jn(n,t){return n[0]===t[0]&&n[1]===t[1]}function Be(n,t){const e=n.map(o=>Z(o,t)).filter(o=>o!==null);return e.length>1&&Jn(e[0],e[e.length-1])&&e.pop(),e.length>=3?e:null}function Ae(n,t){const e=n.map(o=>Z(o,t)).filter(o=>o!==null);return e.length>=2?e:null}function mi(n,t){if(!Array.isArray(n)||n.length===0)return null;const o=(Array.isArray(n[0])&&Array.isArray(n[0][0])?n:[n]).map(i=>Be(i,t));return o.some(i=>i===null)?null:o}function Qn(n,t){const e=S.parseCoordenada(n.lat,n.lon);return e?{id:String(n.id),camadaId:t,geometria:{tipo:"Point",coordenada:[e.lat,e.lon]},propriedades:{...n}}:null}function ta(n,t,e){const o=t.get(String(n.ponto_inicio_id)),i=t.get(String(n.ponto_fim_id));if(!o||!i)return null;const a=S.parseCoordenada(o.lat,o.lon),s=S.parseCoordenada(i.lat,i.lon);if(!a||!s)return null;const r=(n.tipo_limite_sigef??n.tipo_limite)==="LN1";return{id:String(n.id??`${n.ponto_inicio_id}-${n.ponto_fim_id}`),camadaId:e,geometria:{tipo:"LineString",coordenadas:[[a.lat,a.lon],[s.lat,s.lon]]},estilo:r?{dashArray:"6, 6"}:void 0,propriedades:{...n}}}function ea(n,t){if(!n.poligono_wkt)return null;const e=/POLYGON\s*\(\s*\(\s*(.*?)\s*\)\s*\)/i.exec(n.poligono_wkt);if(!e)return null;const o=e[1].split(",").map(a=>{const[s,r]=a.trim().split(/\s+/);return[r,s]}),i=Be(o);return i?{id:String(n.id??n.nome??""),camadaId:t,geometria:{tipo:"Polygon",aneis:[i]},propriedades:{nome:n.nome,nome_propriedade:n.nome_propriedade}}:null}function lo(n,t){const e=Ln(n);if(!e)return null;const o=[];for(const i of e){const a=Z(i.ponto,t);if(!a)return null;const s={ponto:a},r=i.entrada&&Z(i.entrada,{...t,aceitarOrigem:!0}),c=i.saida&&Z(i.saida,{...t,aceitarOrigem:!0});r&&(s.entrada=r),c&&(s.saida=c),o.push(s)}return o}const oa=new Set(["Point","LineString","Polygon","Circle","Text"]);function Bt(n,t,e){if(!n||typeof n!="object")return null;const o=n,i=o.geometria;if(!i||!oa.has(i.tipo)||o.id===void 0||o.id===null||o.id==="")return null;let a=null;switch(i.tipo){case"Point":{const r=Z(i.coordenada,e);r&&(a={tipo:"Point",coordenada:r});break}case"Text":{const r=Z(i.coordenada,e);r&&typeof i.texto=="string"&&i.texto&&(a={tipo:"Text",coordenada:r,texto:i.texto});break}case"LineString":{const r=Array.isArray(i.partes)?i.partes.map(l=>Array.isArray(l)?Ae(l,e):null).filter(l=>l!==null):[];if(r.length>0)a=yt(r);else{const l=Array.isArray(i.coordenadas)?Ae(i.coordenadas,e):null;l&&(a=yt([l]))}const c=r.length<=1?lo(i.curva,e):null;a&&a.tipo==="LineString"&&c&&c.length>=2&&(a={tipo:"LineString",coordenadas:xt(c,!1),curva:c});break}case"Polygon":{const r=Array.isArray(i.aneis)?mi(i.aneis,e):null;r&&(a={tipo:"Polygon",aneis:r});const c=r&&r.length===1?lo(i.curva,e):null;a&&c&&c.length>=3&&(a={tipo:"Polygon",aneis:[xt(c,!0)],curva:c});break}case"Circle":{const r=Z(i.centro,e),c=Number(i.raioMetros);r&&Number.isFinite(c)&&c>0&&(a={tipo:"Circle",centro:r,raioMetros:c});break}}if(!a)return null;const s={id:String(o.id),camadaId:t,geometria:a,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&&(s.oculta=!0),(typeof o.entidadeId=="string"||typeof o.entidadeId=="number")&&(s.entidadeId=String(o.entidadeId)),s.status=K({...s,status:o.status}),s}const ue="cad-cursores",ia=/^#[0-9a-f]{3,8}$/i,na="#94a3b8";function te(n){return typeof n=="string"&&ia.test(n.trim())?n.trim():na}const aa='<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 ho(n){const t=document.createElement("div");t.style.cssText=`color:${te(n.cor)};position:relative;pointer-events:none`,t.innerHTML=aa;const e=document.createElement("span");return e.textContent=String(n.nome??n.id),e.style.cssText=`position:absolute;left:16px;top:14px;white-space:nowrap;font:600 11px sans-serif;color:#fff;background:${te(n.cor)};padding:1px 5px;border-radius:3px;max-width:160px;overflow:hidden;text-overflow:ellipsis`,t.appendChild(e),y.divIcon({className:"custom-leaflet-marker cad-cursor-remoto",iconSize:[18,18],iconAnchor:[3,2],html:t})}class gi{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),a=`${t.nome??""}\0${te(t.cor)}`,s=this.marcadores.get(i);if(s)return s.marker.setLatLng(e),s.assinatura!==a&&(s.marker.setIcon(ho(t)),s.assinatura=a),!0;o.getPane(ue)||(o.createPane(ue).style.zIndex="9500");const r=y.marker(e,{icon:ho(t),pane:ue,interactive:!1,keyboard:!1}).addTo(o);return this.marcadores.set(i,{marker:r,assinatura:a}),!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 Nt=n=>`${n.camadaId}\0${n.id}`;class vi{constructor(t){p(this,"itens",new Map);this.dep=t}get quantidade(){return this.itens.size}contem(t){return this.itens.has(Nt(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(a=>i.add(a.camadaId)),e||this.itens.clear();for(const a of t)this.alcancavel(a)&&(this.itens.set(Nt(a),{camadaId:a.camadaId,id:a.id}),i.add(a.camadaId));this.finalizar(o,i)}alternar(t){const e=this.assinatura(),o=Nt(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 a=Nt(i);this.itens.has(a)?this.itens.delete(a):this.alcancavel(i)&&this.itens.set(a,{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 a=this.dep.obterFeicao(i);(!a||a.excluida||this.dep.visivel&&!this.dep.visivel(a))&&(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 a=new Set;for(const s of this.itens.values())s.camadaId===i&&a.add(s.id);this.dep.aplicarVisual(i,a)}if(this.assinatura()===t)return;const o=this.obter();this.dep.aoSelecionar(o),o.length<=1&&this.dep.aoSelecionarUma(o[0]??null)}}function gt(n){const{lat:t,lng:e}=ie(n[0]);return{lat0:n[0],lon0:n[1],mLat:t,mLng:Math.max(e,1)}}function we(n,t){return[(n[1]-t.lon0)*t.mLng,(n[0]-t.lat0)*t.mLat]}function vt(n,t){return[t.lat0+n[1]/t.mLat,t.lon0+n[0]/t.mLng]}function He(n,t){const e=o=>{let i=!1;for(let a=0,s=o.length-1;a<o.length;s=a++){const[r,c]=o[a],[l,d]=o[s];r>n[0]!=l>n[0]&&n[1]<(d-c)*(n[0]-r)/(l-r)+c&&(i=!i)}return i};return!t[0]||!e(t[0])?!1:!t.slice(1).some(e)}function yi(n,t,e,o){const i=t[0]-n[0],a=t[1]-n[1],s=o[0]-e[0],r=o[1]-e[1],c=i*r-a*s;if(Math.abs(c)<1e-12)return null;const l=((e[0]-n[0])*r-(e[1]-n[1])*s)/c,d=((e[0]-n[0])*a-(e[1]-n[1])*i)/c;return l<0||l>1||d<0||d>=1?null:{t:l,u:d}}function ee(n){let t=0;for(let e=0;e<n.length;e++){const[o,i]=n[e],[a,s]=n[(e+1)%n.length];t+=o*s-a*i}return Math.abs(t)/2}function xi(n,t){if(n.length<3||t.length<2)return null;const e=gt(n[0]),o=n.map(s=>we(s,e)),i=t.map(s=>we(s,e)),a=bi(o,i,0);return a&&a.length>=2?a.map(s=>s.map(r=>vt(r,e))):null}function bi(n,t,e){if(e>8)return null;const o=n.length,i=[];for(let P=0;P<t.length-1;P++)for(let v=0;v<o;v++){const b=yi(t[P],t[P+1],n[v],n[(v+1)%o]);b&&i.push({tLinha:P+b.t,tAnel:v+b.u,ponto:[t[P][0]+b.t*(t[P+1][0]-t[P][0]),t[P][1]+b.t*(t[P+1][1]-t[P][1])]})}if(i.sort((P,v)=>P.tLinha-v.tLinha),i.length<2)return null;const[a,s]=i,r=[];for(let P=Math.floor(a.tLinha)+1;P<=Math.floor(s.tLinha);P++)P>a.tLinha&&P<s.tLinha&&r.push(t[P]);const c=[a.ponto,...r,s.ponto];let l=a,d=s,h=c;a.tAnel>s.tAnel&&(l=s,d=a,h=[...c].reverse());const u=Math.floor(l.tAnel),f=Math.floor(d.tAnel),m=h.slice(1,-1),g=[l.ponto];for(let P=u+1;P<=f;P++)g.push(n[P%o]);g.push(d.ponto,...[...m].reverse());const x=[d.ponto];for(let P=f+1;P<=u+o;P++)x.push(n[P%o]);x.push(l.ponto,...m);const M=ee(n)*1e-9,C=[g,x].filter(P=>P.length>=3&&ee(P)>M);if(C.length<2)return null;const z=[s.ponto,...t.slice(Math.floor(s.tLinha)+1)];if(i.length>2&&z.length>=2){const P=[];for(const v of C){const b=bi(v,z,e+1);b?P.push(...b):P.push(v)}return P}return C}function bt(n,t){return n.map(e=>we(e,t))}const it=(n,t)=>Math.hypot(n[0]-t[0],n[1]-t[1]);function Pi(n,t=0){if(n.length===0||n.some(a=>a.length<2))return null;const e=gt(n[0][0]),o=n.slice(1).map(a=>bt(a,e));let i=bt(n[0],e);for(;o.length>0;){let a=null;if(o.forEach((d,h)=>{const u=i[0],f=i[i.length-1],m=[{inverter:!1,noFim:!0,d:it(f,d[0])},{inverter:!0,noFim:!0,d:it(f,d[d.length-1])},{inverter:!1,noFim:!1,d:it(u,d[d.length-1])},{inverter:!0,noFim:!1,d:it(u,d[0])}];for(const g of m)(!a||g.d<a.d)&&(a={idx:h,...g})}),!a||a.d>t)return null;const{idx:s,inverter:r,noFim:c}=a;let l=o.splice(s,1)[0];r&&(l=[...l].reverse()),i=c?[...i,...it(i[i.length-1],l[0])>0?l:l.slice(1)]:[...l,...it(l[l.length-1],i[0])>0?i:i.slice(1)]}return i.map(a=>vt(a,e))}function sa(n,t,e,o){const i=yi(n,t,e,o);return!!i&&i.t>1e-9&&i.t<1-1e-9&&i.u>1e-9}function ra(n,t){for(let e=0;e<n.length;e++)for(let o=0;o<t.length;o++)if(sa(n[e],n[(e+1)%n.length],t[o],t[(o+1)%t.length]))return!0;return!1}function Ci(n,t,e=0){if(n.length<3||t.length<3)return null;const o=gt(n[0]),i=bt(n,o),a=bt(t,o);if(ra(i,a))return null;let s={i:0,j:0,d:1/0};for(let d=0;d<i.length;d++)for(let h=0;h<a.length;h++){const u=it(i[d],a[h]);u<s.d&&(s={i:d,j:h,d:u})}if(s.d>e)return null;const{i:r,j:c}=s,l=[];for(let d=0;d<=i.length;d++)l.push(i[(r+d)%i.length]);for(let d=0;d<=a.length;d++)l.push(a[(c+d)%a.length]);return l.map(d=>vt(d,o))}const uo=16;function po(n,t,e,o){const i=[];for(let a=0;a<=uo;a++){const s=e+(o-e)*a/uo;i.push([n[0]+t*Math.cos(s),n[1]+t*Math.sin(s)])}return i}function Ot(n,t){const e=it(n,t)||1;return[-(t[1]-n[1])/e,(t[0]-n[0])/e]}function pe(n,t,e){const o=n.length,i=[],a=o;for(let s=0;s<a;s++){const r=e?n[(s-1+o)%o]:n[Math.max(0,s-1)],c=n[s],l=e?n[(s+1)%o]:n[Math.min(o-1,s+1)],d=s===0&&!e?Ot(c,l):Ot(r,c),h=s===o-1&&!e?Ot(r,c):Ot(c,l);let u=d[0]+h[0],f=d[1]+h[1];const m=Math.hypot(u,f);if(m<1e-9){i.push([c[0]+d[0]*t,c[1]+d[1]*t]);continue}u/=m,f/=m;const g=u*d[0]+f*d[1],x=Math.min(1/Math.max(g,.5),2);i.push([c[0]+u*t*x,c[1]+f*t*x])}return i}function ca(n){let t=0;for(let e=0;e<n.length;e++){const[o,i]=n[e],[a,s]=n[(e+1)%n.length];t+=(a-o)*(s+i)}return t>0}function Li(n,t){if(!Number.isFinite(t)||t===0)return null;if(n.tipo==="Point"||n.tipo==="Text"||n.tipo==="Circle"){const e=n.tipo==="Circle"?n.centro:n.coordenada,o=n.tipo==="Circle"?n.raioMetros+t:t;if(o<=0)return null;const i=gt(e),a=64;return Array.from({length:a},(s,r)=>[o*Math.cos(2*Math.PI*r/a),o*Math.sin(2*Math.PI*r/a)]).map(s=>vt(s,i))}if(n.tipo==="LineString"){if(t<0||n.coordenadas.length<2||kt(n))return null;const e=gt(n.coordenadas[0]),o=bt(n.coordenadas,e),i=pe(o,t,!1),a=pe([...o].reverse(),t,!1),s=o[o.length-1],r=o[0],c=Math.atan2(s[1]-o[o.length-2][1],s[0]-o[o.length-2][0]),l=Math.atan2(r[1]-o[1][1],r[0]-o[1][0]),d=po(s,t,c+Math.PI/2,c-Math.PI/2),h=po(r,t,l+Math.PI/2,l-Math.PI/2);return[...i,...d,...a,...h].map(u=>vt(u,e))}if(n.tipo==="Polygon"){const e=n.aneis[0];if(!e||e.length<3)return null;const o=gt(e[0]);let i=bt(e,o);ca(i)&&(i=[...i].reverse());const s=pe(i,-t,!0);return s.length<3||t<0&&ee(s)>=ee(i)?null:s.map(r=>vt(r,o))}return null}function Si(n,t,e){const o=i=>{const a=ie(i[0]),s=e/a.lat,r=t/Math.max(a.lng,1);return[i[0]+s,i[1]+r]};switch(n.tipo){case"Point":return{tipo:"Point",coordenada:o(n.coordenada)};case"Text":return{...n,coordenada:o(n.coordenada)};case"Circle":return{...n,centro:o(n.centro)};case"LineString":{const i=yt(U(n).map(a=>a.map(o)));return n.curva?{...i,curva:so(n.curva,o)}:i}case"Polygon":{const i={tipo:"Polygon",aneis:n.aneis.map(a=>a.map(o))};return n.curva?{...i,curva:so(n.curva,o)}:i}}}const fo={m:1,km:1e3,ft:.3048,mi:1609.344},mo={m2:1,ha:1e4,km2:1e6,ac:4046.8564224,alqueire:24200};function la(n,t,e){return n*fo[t]/fo[e]}function da(n,t,e){return n*mo[t]/mo[e]}function ha(n,t,e=2){const o=t==="lat"?n<0?"S":"N":n<0?"O":"L",i=Math.abs(n);let a=Math.floor(i),s=Math.floor((i-a)*60),r=Number(((i-a-s/60)*3600).toFixed(e));r>=60&&(r=0,s+=1),s>=60&&(s=0,a+=1);const c=r.toFixed(e).padStart(e?e+3:2,"0");return`${a}°${String(s).padStart(2,"0")}'${c}"${o}`}function ua(n){var u;if(typeof n!="string")return null;const t=n.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[a,s="0",r="0"]=i,c=Math.abs(Number(a)),l=Number(s),d=Number(r);if(l<0||l>=60||d<0||d>=60)return null;let h=c+l/60+d/3600;return(a.startsWith("-")||e==="S"||e==="O"||e==="W")&&(h=-h),h}function pa(n,t){return st(n,t)}function Ht(n,t,e){return{...n,id:t,geometria:e??JSON.parse(JSON.stringify(n.geometria)),estilo:n.estilo?{...n.estilo}:void 0,propriedades:{...n.propriedades}}}const fa=111320;function Ct(n,t){return n.x>=t.x1&&n.x<=t.x2&&n.y>=t.y1&&n.y<=t.y2}function go(n,t,e){let o=0,i=1;const a=t.x-n.x,s=t.y-n.y,r=[-a,a,-s,s],c=[n.x-e.x1,e.x2-n.x,n.y-e.y1,e.y2-n.y];for(let l=0;l<4;l++)if(r[l]===0){if(c[l]<0)return!1}else{const d=c[l]/r[l];if(r[l]<0){if(d>i)return!1;d>o&&(o=d)}else{if(d<o)return!1;d<i&&(i=d)}}return!0}function vo(n,t){let e=!1;for(let o=0,i=t.length-1;o<t.length;i=o++){const a=t[o],s=t[i];a.y>n.y!=s.y>n.y&&n.x<(s.x-a.x)*(n.y-a.y)/(s.y-a.y)+a.x&&(e=!e)}return e}function yo(n,t,e){for(let o=1;o<n.length;o++)if(go(n[o-1],n[o],t))return!0;return e&&n.length>2&&go(n[n.length-1],n[0],t)}function ma(n,t,e){const o=e(n),i=e([n[0]+t/fa,n[1]]);return Math.hypot(i.x-o.x,i.y-o.y)}function Mi(n,t,e,o){if(n.oculta)return!1;const i=n.geometria,a=o==="window";switch(i.tipo){case"Point":case"Text":return Ct(e(i.coordenada),t);case"LineString":{const s=U(i).map(r=>r.map(e));return a?s.every(r=>r.every(c=>Ct(c,t))):s.some(r=>r.some(c=>Ct(c,t))||yo(r,t,!1))}case"Polygon":{const s=i.aneis.map(l=>l.map(e)),r=s[0];if(!r)return!1;if(a)return r.every(l=>Ct(l,t));if(s.some(l=>l.some(d=>Ct(d,t))||yo(l,t,!0)))return!0;const c={x:t.x1,y:t.y1};return vo(c,r)&&!s.slice(1).some(l=>vo(c,l))}case"Circle":{const s=e(i.centro),r=ma(i.centro,i.raioMetros,e);if(a)return s.x-r>=t.x1&&s.x+r<=t.x2&&s.y-r>=t.y1&&s.y+r<=t.y2;const c=Math.max(t.x1,Math.min(s.x,t.x2)),l=Math.max(t.y1,Math.min(s.y,t.y2));return Math.hypot(s.x-c,s.y-l)<=r}}}function Ai(n,t){if(t.length<3||n.oculta)return!1;const e=i=>He(i,[t]),o=n.geometria;switch(o.tipo){case"Point":case"Text":return e(o.coordenada);case"Circle":return e(o.centro);case"LineString":return U(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 a=i.reduce((s,r)=>[s[0]+r[0],s[1]+r[1]],[0,0]);return e([a[0]/i.length,a[1]/i.length])}}}const ga={Point:"Ponto",LineString:"Linha",Polygon:"Polígono",Circle:"Círculo",Text:"Texto"},va=new Set(["name","nome","category","categoria","description","descricao","author","autor","date","data","created_at","criadoEm"]),xo=6;function Lt(n,t){var e;for(const o of t){const i=(e=n.propriedades)==null?void 0:e[o];if(i!=null&&String(i)!=="")return String(i)}return""}function ya(n){const t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(n),e=t?new Date(Number(t[1]),Number(t[2])-1,Number(t[3])):new Date(n);return Number.isNaN(e.getTime())?n:e.toLocaleDateString("pt-BR")}function xa(n){const t=typeof n=="object"?JSON.stringify(n):String(n);return t.length>80?`${t.slice(0,77)}...`:t}function It(n){const t=n.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((a,s)=>a+s[0],0)/e.length,i=e.reduce((a,s)=>a+s[1],0)/e.length;return[o,i]}}}function ba(n){const t=n.geometria,e=[],o=tt(t),i=et(t);if(t.tipo==="Polygon")e.push(["Área",rt(o??0)],["Perímetro",G(i??0)]),e.push(["Vértices",String(t.aneis.reduce((r,c)=>r+c.length,0))]);else if(t.tipo==="LineString"){const r=U(t);e.push(["Extensão",G(i??0)],["Vértices",String(r.reduce((c,l)=>c+l.length,0))]),r.length>1&&e.push(["Partes",String(r.length)])}else t.tipo==="Circle"&&e.push(["Raio",G(t.raioMetros)],["Área",rt(o??0)]);const[a,s]=It(n);return e.push(["Coordenadas",`${a.toFixed(6)}, ${s.toFixed(6)}`]),e}class wi{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();e&&(this.fechar(),this.feicaoAtual=t,this.popup=y.popup({className:"compact-popup",maxWidth:280,closeOnClick:!1,autoClose:!1,autoPanPaddingTopLeft:y.point(this.margens.esquerda,this.margens.topo),autoPanPaddingBottomRight:y.point(this.margens.direita,this.margens.base)}).setLatLng(It(t)).setContent(this.montar(t)),this.popup.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(It(t)).setContent(this.montar(t)))}fechar(){const t=this.popup;this.popup=null,this.feicaoAtual=null,t==null||t.close()}montar(t){var g;const e=this.dep.obterCamada(t.camadaId),o=Y(((g=t.estilo)==null?void 0:g.corTraco)??(e==null?void 0:e.estilo.corPrimaria),"#38bdf8"),i=(x,A="",M)=>{const C=document.createElement(x);return A&&(C.style.cssText=A),M!==void 0&&(C.textContent=M),C},a=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");a.className="cad-feicao-popup",a.appendChild(i("div","font-weight:700;font-size:13px;margin-bottom:1px",Lt(t,["name","nome"])||t.id));const s=Lt(t,["category","categoria"]),r=[ga[t.geometria.tipo],(e==null?void 0:e.nome)??t.camadaId,s].filter(Boolean).join(" · ");a.appendChild(i("div","font-size:11px;color:rgba(255,255,255,.6);margin-bottom:4px",r));const c=Lt(t,["description","descricao"]);c&&a.appendChild(i("div","font-size:11px;margin-bottom:4px",c));const l=x=>{const A=i("div","font-size:11px;margin-bottom:4px");for(const[M,C]of x){const z=i("div");z.appendChild(i("strong","",`${M}: `)),z.appendChild(document.createTextNode(C)),A.appendChild(z)}return A};a.appendChild(l(ba(t)));const d=Object.entries(t.propriedades??{}).filter(([x,A])=>!va.has(x)&&A!==void 0&&A!==null&&A!=="");d.length>0&&(a.appendChild(l(d.slice(0,xo).map(([x,A])=>[x,xa(A)]))),d.length>xo&&a.appendChild(i("div","font-size:10px;color:rgba(255,255,255,.55);margin-bottom:4px",`${d.length} atributos`)));const h=Lt(t,["author","autor"]),u=Lt(t,["date","data","created_at","criadoEm"]);if(h||u){const x=[h,u?ya(u):""].filter(Boolean).join(" · ");a.appendChild(i("div","font-size:10px;color:rgba(255,255,255,.55);margin-bottom:4px",x))}const f=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[x,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=x,M.addEventListener("click",C=>{C.stopPropagation(),this.dep.aoAcao(x,this.feicaoAtual??t)}),f.appendChild(M)}return a.appendChild(f),a}}const ki=5e3;function Tt(n){return n.tipo==="Polygon"?3:n.tipo==="LineString"?2:1}function zi(n,t=!1){if(n.bloqueada||t)return"bloqueada";const e=n.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":kt(e)?"multiparte":J(e).length>ki?"muitos-vertices":null}function J(n){return n.tipo==="Point"?[n.coordenada]:n.tipo==="LineString"?n.coordenadas:n.tipo==="Polygon"?n.aneis[0]??[]:[]}function Dt(n,t){return n.tipo==="Point"?{tipo:"Point",coordenada:t[0]}:n.tipo==="LineString"?{tipo:"LineString",coordenadas:t}:n.tipo==="Polygon"?{tipo:"Polygon",aneis:[t]}:n}function Pa(n,t,e){const o=J(n).slice();return t<0||t>=o.length?n:(o[t]=e,Dt(n,o))}function Ei(n,t,e){if(n.tipo!=="LineString"&&n.tipo!=="Polygon")return n;const o=J(n).slice();return t<0||t>=o.length?n:(o.splice(t+1,0,e),Dt(n,o))}function Ii(n,t){if(n.tipo!=="LineString"&&n.tipo!=="Polygon")return null;const e=J(n);return t<0||t>=e.length||e.length<=Tt(n)?null:Dt(n,e.filter((o,i)=>i!==t))}function Ve(n,t){return[(n[0]+t[0])/2,(n[1]+t[1])/2]}function Ge(n){const t=J(n).length,e=[];if(n.tipo!=="LineString"&&n.tipo!=="Polygon")return e;for(let o=0;o<t-1;o++)e.push([o,o+1]);return n.tipo==="Polygon"&&t>2&&e.push([t-1,0]),e}function W(n){return(n.tipo==="LineString"||n.tipo==="Polygon")&&n.curva&&n.curva.length>=Tt(n)?n.curva:null}const _i=.5;function Ti(n,t){return[n[0],n[1]+t/Math.max(ie(n[0]).lng,1)]}function St(n){var t;return n.tipo==="Circle"?[n.centro,Ti(n.centro,n.raioMetros)]:((t=W(n))==null?void 0:t.map(e=>e.ponto))??J(n)}function Pt(n,t){const e=n.tipo==="Polygon",o=xt(t,e);return e?{tipo:"Polygon",aneis:[o],curva:t}:{tipo:"LineString",coordenadas:o,curva:t}}function Di(n,t){if(n.tipo==="Circle")return t.length<2?n:{...n,centro:t[0],raioMetros:Math.max(_i,st(t[0],t[1]))};const e=W(n);if(!e||e.length!==t.length)return Dt(n,t);const o=e.map((i,a)=>{const s=t[a][0]-i.ponto[0],r=t[a][1]-i.ponto[1],c=d=>[d[0]+s,d[1]+r],l={ponto:t[a]};return i.entrada&&(l.entrada=c(i.entrada)),i.saida&&(l.saida=c(i.saida)),l});return Pt(n,o)}function pt(n,t,e){return[n[0]+(t[0]-n[0])*e,n[1]+(t[1]-n[1])*e]}function Ca(n,t,e){const[o,i]=_t(n,t);let a=.5,s=1/0;for(let r=1;r<64;r++){const c=r/64,l=Re(n.ponto,o,i,t.ponto,c),d=(l[0]-e[0])**2+(l[1]-e[1])**2;d<s&&(s=d,a=c)}return a}function Vt(n,t,e){const o=W(n);if(!o){const s=J(n);return Ve(s[t],s[e])}const[i,a]=_t(o[t],o[e]);return Re(o[t].ponto,i,a,o[e].ponto,.5)}function $i(n){const t=W(n);if(!t)return Ge(n);const e=[];for(let o=0;o<t.length-1;o++)e.push([o,o+1]);return n.tipo==="Polygon"&&t.length>2&&e.push([t.length-1,0]),e}function qi(n,t,e){const o=W(n);if(!o)return Ei(n,t,e);if(t<0||t>=o.length)return n;const i=(t+1)%o.length,a=o[t],s=o[i],r=a.saida===void 0&&s.entrada===void 0;let c,l=a,d=s;if(r)c={ponto:e};else{const u=Ca(a,s,e),[f,m]=_t(a,s),g=pt(a.ponto,f,u),x=pt(f,m,u),A=pt(m,s.ponto,u),M=pt(g,x,u),C=pt(x,A,u);c={ponto:pt(M,C,u),entrada:M,saida:C},l={...a,saida:g},d={...s,entrada:A}}const h=o.slice();return h[t]=l,h[i]=d,h.splice(t+1,0,c),Pt(n,h)}function Ni(n,t){const e=W(n);return e?t<0||t>=e.length||e.length<=Tt(n)?null:Pt(n,e.filter((o,i)=>i!==t)):Ii(n,t)}function Oi(n){return n.tipo!=="LineString"&&n.tipo!=="Polygon"?null:W(n)??J(n).map(t=>({ponto:[t[0],t[1]]}))}function Fi(n,t,e,o,i=!0){const a=Oi(n);if(!a||t<0||t>=a.length)return n;const s={...a[t],[e]:o};i&&(s[e==="saida"?"entrada":"saida"]=Fe(s.ponto,o));const r=a.slice();return r[t]=s,Pt(n,r)}function Ri(n,t){const e=Oi(n);if(!e||t<0||t>=e.length)return n;const o=e[t],i=e.slice();if(o.entrada||o.saida)return i[t]={ponto:o.ponto},Pt(n,i);const a=n.tipo==="Polygon",s=e.length,r=t>0?e[t-1]:a?e[s-1]:null,c=t<s-1?e[t+1]:a?e[0]:null;if(!r&&!c)return n;const l=o.ponto;let d,h;if(r&&c)d=(c.ponto[0]-r.ponto[0])/6,h=(c.ponto[1]-r.ponto[1])/6;else{const u=(c??r).ponto,f=c?1:-1;d=(u[0]-l[0])/3*f,h=(u[1]-l[1])/3*f}return i[t]={ponto:l,saida:[l[0]+d,l[1]+h],entrada:[l[0]-d,l[1]-h]},Pt(n,i)}const Bi={topo:0,base:16,esquerda:0,direita:0},Hi=16,Vi=.92,Gt={topo:"--cad-hud-topo",base:"--cad-hud-base",esquerda:"--cad-hud-esquerda",direita:"--cad-hud-direita"},je="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 La(n,t,e={}){const o={...Bi,...e},i=Math.max(0,n-o.esquerda-o.direita);return{centroX:o.esquerda+i/2,base:o.base,larguraMax:Math.max(0,Math.min(n*Vi,i-Hi)),alturaMax:Math.max(0,t-o.topo-o.base-8)}}function Gi(n,t){for(const e of Object.keys(Gt)){const o=t[e];typeof o=="number"&&Number.isFinite(o)&&o>=0?n.style.setProperty(Gt[e],`${o}px`):n.style.removeProperty(Gt[e])}}const ji="cm-vertex-edit-hud",lt="cad-edicao-vertices",bo="#facc15",Po="#f472b6";class Ui{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(lt)){const o=e.createPane(lt);o.style.zIndex="9000"}this.grupo=y.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 Di(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 a=this.criarAlca(o,i);this.alcas.push(a),this.grupo.addLayer(a)}),this.criarAlcasBezier(),t.tipo!=="Point")for(const[o,i]of $i(this.geometriaAtual())){const a=this.criarFantasma(o,i);this.fantasmas.push(a),this.grupo.addLayer(a.marker)}this.atualizarHud()}icone(t,e,o){return y.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=y.marker(t,{icon:this.icone("cad-vertex-handle",12,`background:${bo};border:2px solid #111;border-radius:${this.ehCirculo&&e===1?"50%":"2px"};cursor:${this.ehCirculo&&e===1?"ew-resize":"move"}`),draggable:!0,pane:lt,keyboard:!1});return o.on("drag",()=>this.aoArrastar(o,e)),o.on("dragend",()=>{this.esconderSnap(),this.confirmar(this.feicaoComPontos())}),o.on("contextmenu",i=>{y.DomEvent.preventDefault(i.originalEvent),y.DomEvent.stopPropagation(i.originalEvent),this.excluir(e)}),o.on("dblclick",i=>{y.DomEvent.stopPropagation(i.originalEvent),this.alternarSuave(e)}),o}criarAlcasBezier(){const t=this.feicaoAtual&&W(this.feicaoAtual.geometria);t&&t.forEach((e,o)=>this.completarAlcasDoNo(o))}completarAlcasDoNo(t){var o;const e=this.feicaoAtual&&((o=W(this.feicaoAtual.geometria))==null?void 0:o[t]);if(!(!e||!this.grupo))for(const i of["entrada","saida"]){const a=e[i];if(!a||this.alcasBezier.some(l=>l.i===t&&l.qual===i))continue;const s=y.polyline([e.ponto,a],{pane:lt,color:Po,weight:1,opacity:.8,interactive:!1}),r=y.marker(a,{icon:this.icone("cad-bezier-handle",10,`background:#fff;border:2px solid ${Po};border-radius:50%;cursor:move`),draggable:!0,pane:lt,keyboard:!1}),c={marker:r,haste:s,i:t,qual:i};r.on("drag",l=>{const d=l.originalEvent;this.aoArrastarAlca(c,!(d!=null&&d.shiftKey))}),r.on("dragend",()=>this.confirmar(this.feicaoAtual)),this.alcasBezier.push(c),this.grupo.addLayer(s),this.grupo.addLayer(r)}}sincronizarAlcasBezier(){var e;const t=this.feicaoAtual&&W(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:a}=t.marker.getLatLng(),s=Fi(o.geometria,t.i,t.qual,[i,a],e);this.feicaoAtual={...o,geometria:s},this.completarAlcasDoNo(t.i),this.sincronizarAlcasBezier(),this.dep.previsualizar(this.feicaoAtual),this.atualizarHud()}alternarSuave(t){const e=this.feicaoAtual;if(!e)return;const o=Ri(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=y.marker(Vt(this.geometriaAtual(),t,e),{icon:this.icone("cad-vertex-ghost",9,`background:${bo};opacity:.45;border:1px solid #111;border-radius:50%;cursor:copy`),pane:lt,keyboard:!1});return o.on("click",i=>{y.DomEvent.stopPropagation(i.originalEvent),this.inserir(t,o.getLatLng())}),{marker:o,i:t,j:e}}aoArrastar(t,e){var s;const o=this.feicaoAtual;if(!o)return;let i=[t.getLatLng().lat,t.getLatLng().lng];const a=this.dep.snapLigado()?this.dep.buscarSnap(i,{feicaoId:o.id,camadaId:o.camadaId,vertice:e}):null;if(a?(i=a.coordenada,t.setLatLng(i),this.mostrarSnap(i)):this.esconderSnap(),o.geometria.tipo==="Circle"&&e===0){const r=i[0]-this.pts[0][0],c=i[1]-this.pts[0][1];this.pts[1]=[this.pts[1][0]+r,this.pts[1][1]+c],(s=this.alcas[1])==null||s.setLatLng(this.pts[1])}this.pts[e]=i;for(const r of this.fantasmas)(r.i===e||r.j===e)&&r.marker.setLatLng(Vt(this.geometriaAtual(),r.i,r.j));this.dep.previsualizar(this.feicaoComPontos()),this.atualizarAlcasDoNo(e),this.atualizarHud()}atualizarAlcasDoNo(t){const e=W(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=qi(this.geometriaAtual(),t,[e.lat,e.lng]);this.pts=St(i).map(s=>[s[0],s[1]]),this.reconstruir();const a=this.feicaoComPontos();this.dep.previsualizar(a),this.confirmar(a)}confirmar(t){this.feicaoAtual=t,this.dep.aoGesto(t)}excluir(t){if(!this.feicaoAtual)return;const o=Ni(this.geometriaAtual(),t);if(!o)return;this.pts=St(o).map(a=>[a[0],a[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=Vt(this.geometriaAtual(),t,e);this.inserir(t,y.latLng(o[0],o[1]))}mostrarSnap(t){this.grupo&&(this.marcadorSnap?this.marcadorSnap.setLatLng(t):this.marcadorSnap=y.marker(t,{icon:y.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:lt,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=ji,e.style.cssText=je+"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 a=o("snap");a.style.cursor="pointer",a.title="Alternar snap (S). Alt desliga temporariamente.",a.addEventListener("click",()=>this.dep.alternarSnap());const s=document.createElement("button");s.type="button",s.textContent="Concluir",s.style.cssText="padding:3px 10px;border-radius:4px;border:1px solid #facc15;background:#facc15;color:#111;font-weight:600;cursor:pointer",s.addEventListener("click",()=>this.parar());const r=o("dica");r.style.opacity=".7",r.textContent="Duplo clique no nó: curva ↔ canto · Alças: Shift solta a simetria",e.append(i,o("nos"),o("medida"),a,r,s),y.DomEvent.disableClickPropagation(e),y.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. ${Tt(t)})`),o&&(t.tipo==="Polygon"?o.textContent=`Área: ${rt(tt(t)??0)} · Perímetro: ${G(et(t)??0)}`:t.tipo==="LineString"?o.textContent=`Extensão: ${G(et(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: ${rt(tt(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 a=this.alcasBezier.find(s=>s.i===t&&s.qual===e);a&&(a.marker.setLatLng(o),this.aoArrastarAlca(a,!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"))}}const Ue=10,fe=(n,t)=>Math.hypot(n.x-t.x,n.y-t.y);function Sa(n,t,e){const o=e.x-t.x,i=e.y-t.y,a=o*o+i*i,s=a===0?0:Math.max(0,Math.min(1,((n.x-t.x)*o+(n.y-t.y)*i)/a));return{t:s,d:Math.hypot(n.x-(t.x+s*o),n.y-(t.y+s*i))}}function Wi(n,t,e,o={},i){const a=o.toleranciaPx??Ue,s=o.vertice!==!1,r=o.meio!==!1,c=o.aresta!==!1;let l=null,d=null,h=null;const u=(f,m)=>!f||m.distanciaPx<f.distanciaPx?m:f;for(const f of t){if(f.excluida||f.oculta)continue;const m=!!i&&i.feicaoId===f.id&&(i.camadaId===void 0||i.camadaId===f.camadaId),g=f.geometria,x={feicaoId:f.id,camadaId:f.camadaId};if(g.tipo==="Point"||g.tipo==="Text"||g.tipo==="Circle"){if(!s||m)continue;const C=g.tipo==="Circle"?g.centro:g.coordenada,z=fe(n,e(C));z<=a&&(l=u(l,{tipo:"vertice",coordenada:C,distanciaPx:z,...x}));continue}if(m&&(g.tipo==="LineString"||g.tipo==="Polygon")&&g.curva)continue;const A=g.tipo==="LineString"?U(g).map(C=>({pts:C,fechado:!1})):[{pts:J(g),fechado:g.tipo==="Polygon"}],M=m?i.vertice:void 0;for(const{pts:C,fechado:z}of A){const P=C.map(e);if(s)for(let b=0;b<C.length;b++){if(b===M)continue;const w=fe(n,P[b]);w<=a&&(l=u(l,{tipo:"vertice",coordenada:C[b],distanciaPx:w,...x}))}if(!r&&!c)continue;const v=[];for(let b=0;b<C.length-1;b++)v.push([b,b+1]);z&&C.length>2&&v.push([C.length-1,0]);for(const[b,w]of v)if(!(M!==void 0&&(b===M||w===M))&&!(m&&M===void 0)){if(r){const E=Ve(C[b],C[w]),L=fe(n,e(E));L<=a&&(d=u(d,{tipo:"meio",coordenada:E,distanciaPx:L,...x}))}if(c){const{t:E,d:L}=Sa(n,P[b],P[w]);if(L<=a){const k=[C[b][0]+E*(C[w][0]-C[b][0]),C[b][1]+E*(C[w][1]-C[b][1])];h=u(h,{tipo:"aresta",coordenada:k,distanciaPx:L,...x})}}}}}return l??d??h}class Ma{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&&!Ie(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 Co=36,Aa=.45;function wa(n,t){const e=Math.abs(t[0]-n[0]),o=Math.abs(t[1]-n[1]);if(e===0&&o===0)return null;const i=[];for(let a=0;a<Co;a++){const s=a*2*Math.PI/Co;i.push([n[0]+e*Math.sin(s),n[1]+o*Math.cos(s)])}return i}function Xi(n,t){const e=Math.cos(n[0]*Math.PI/180)||1,o=t[0]-n[0],i=(t[1]-n[1])*e,a=Math.hypot(o,i);return a===0?null:{raio:a,inicio:Math.atan2(o,i),cosLat:e}}function ka(n,t,e=6){const o=Xi(n,t);if(!o||e<3)return null;const i=[];for(let a=0;a<e;a++){const s=o.inicio+a*2*Math.PI/e;i.push([n[0]+o.raio*Math.sin(s),n[1]+o.raio*Math.cos(s)/o.cosLat])}return i}function za(n,t,e=5){const o=Xi(n,t);if(!o||e<3)return null;const i=e*2,a=[];for(let s=0;s<i;s++){const r=s%2===0?o.raio:o.raio*Aa,c=o.inicio+s*2*Math.PI/i;a.push([n[0]+r*Math.sin(c),n[1]+r*Math.cos(c)/o.cosLat])}return a}const oe=["ponto","linha","poligono","retangulo","elipse","poligono-regular","estrela","circulo","texto","caneta","medir-distancia","medir-area","dividir","selecao-laco","conta-gotas"],ke=2;function We(n){return typeof n=="string"&&oe.includes(n)}function At(n){return n.map(t=>{const e={ponto:t.ponto};return t.alca&&(e.saida=t.alca,e.entrada=Fe(t.ponto,t.alca)),e})}function Zi(n){return xt(At(n),!1)}function me(n,t){const e=Zo(n);if(t){const i=e?xt(n,!0):n.map(a=>a.ponto);return e?{tipo:"Polygon",aneis:[i],curva:n}:{tipo:"Polygon",aneis:[i]}}const o=e?xt(n,!1):n.map(i=>i.ponto);return e?{tipo:"LineString",coordenadas:o,curva:n}:{tipo:"LineString",coordenadas:o}}const Ea=(n,t)=>n[0]===t[0]&&n[1]===t[1],Lo={elipse:wa,"poligono-regular":(n,t)=>ka(n,t,6),estrela:(n,t)=>za(n,t,5)};class jt{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=st(this.pontos[0],t);return e>=ke?{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=Lo[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&&Ea(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"?Zi(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=st(this.pontos[0],t);return e>=ke?{tipo:"Circle",centro:this.pontos[0],raioMetros:e}:null}case"caneta":{if(this.ancoras.length===0)return null;const e=At(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=Lo[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(At(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(At(this.ancoras),!0):{tipo:"Polygon",aneis:[this.vertices()]}:null}comprimentoMetros(){const t=this.cursor&&this.nos>0?[...this.vertices(),this.cursor]:this.vertices();return zt(t,!1)}}const Yi="cm-draw-hud",ze="cad-ferramenta-ativa",ot="cad-desenho",dt="#22d3ee",Ia=4,_a=450,Ta=10,Da={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"},$a={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 Ki{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 a;const e=this.sessao;if(!e||e.ferramenta==="caneta"||this.campoTexto||((a=t.originalEvent)==null?void 0:a.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=Ie(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 s;const o=(s=this.sessao)==null?void 0:s.ferramenta;this.desligar(),o&&this.dep.aoDesativar(o),this.limparMedicao();const i=this.dep.map;this.fechar=!!e.fechar,this.sessao=new jt(t,this.fechar),i.getPane(ot)||(i.createPane(ot).style.zIndex="8500"),this.grupo=y.layerGroup().addTo(i),this.marcas=y.layerGroup().addTo(this.grupo);const a=i.getContainer();a.classList.add(ze),a.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(ze),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,a=!!e&&Math.hypot(e.x-i.x,e.y-i.y)<=Ia&&o-e.t<=_a;return this.ultimoClique={x:i.x,y:i.y,t:o},a}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)>Ta)return!1;const a=e.concluirFechando();return a&&this.finalizar(a),!!a}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 jt(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 jt(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",a=>{if(a.stopPropagation(),a.key==="Enter"){const s=e.value.trim();this.cancelarTexto(),s&&this.finalizar({tipo:"Text",coordenada:t,texto:s})}else a.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 a=Fe(i.ponto,i.alca);this.marcas.addLayer(y.polyline([a,i.alca],{pane:ot,color:dt,weight:1,opacity:.8,interactive:!1}));for(const s of[a,i.alca])this.marcas.addLayer(y.circleMarker(s,{pane:ot,radius:3,color:dt,weight:1,fillColor:"#fff",fillOpacity:1,interactive:!1}))}for(const i of o)this.marcas.addLayer(y.circleMarker(i,{pane:ot,radius:4,color:"#111",weight:1,fillColor:dt,fillOpacity:1,interactive:!1}));this.atualizarHud(e)}desenharGeometria(t,e){const o={pane:ot,color:dt,weight:2,dashArray:e?"6 4":void 0,fillColor:dt,fillOpacity:.15,interactive:!1},i=ei(t,o);if(i)return i;if(t.tipo==="Polygon")return y.polygon(t.aneis,o);if(t.tipo==="Circle")return y.circle(t.centro,{...o,radius:t.raioMetros});if(t.tipo==="LineString")return y.polyline(t.coordenadas,o);const a=(t.tipo==="Point",t.coordenada);return y.circleMarker(a,{...o,radius:5})}mostrarMedicao(t,e){this.limparMedicao();const o=y.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:[],a=t.tipo==="Polygon",s=(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(y.marker(l,{pane:ot,interactive:!1,keyboard:!1,icon:y.divIcon({className:"custom-leaflet-marker",iconSize:void 0,html:h})}))},r=a?i.length:i.length-1;for(let l=0;l<r;l++){const d=i[l],h=i[(l+1)%i.length];s([(d[0]+h[0])/2,(d[1]+h[1])/2],G(st(d,h)))}const c={tipo:e==="medir-area"?"area":"distancia",pontos:i,comprimentoM:zt(i,!1)};if(t.tipo==="Polygon")c.areaM2=tt(t)??0,c.perimetroM=et(t)??0;else if(e==="medir-distancia"&&i.length>=3){const l={tipo:"Polygon",aneis:[i]};c.areaM2=tt(l)??0,c.perimetroM=et(l)??0}return c}mostrarSnap(t){this.grupo&&(this.marcadorSnap?this.marcadorSnap.setLatLng(t):this.marcadorSnap=y.marker(t,{pane:ot,interactive:!1,keyboard:!1,icon:y.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=Yi,e.style.cssText=je+"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=r=>{const c=document.createElement("span");return c.dataset.campo=r,c},i=document.createElement("strong");i.textContent=Da[t.ferramenta];const a=o("dica");a.style.opacity=".7",a.textContent=$a[t.ferramenta];const s=(r,c,l=!1)=>{const d=document.createElement("button");return d.type="button",d.textContent=r,d.style.cssText=`padding:3px 10px;border-radius:4px;border:1px solid ${l?dt:"rgba(255,255,255,.3)"};background:${l?dt:"transparent"};color:${l?"#111":"#fff"};cursor:pointer;font-weight:600`,d.addEventListener("click",c),d};e.append(i,o("nos"),o("medida"),a),t.ehSequencial&&e.append(s("Concluir",()=>this.concluir(),!0)),e.append(s("Sair",()=>this.desativar())),y.DomEvent.disableClickPropagation(e),y.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 a="";if((t==null?void 0:t.tipo)==="Polygon")a=`Área: ${rt(tt(t)??0)} · Perímetro: ${G(et(t)??0)}`;else if((t==null?void 0:t.tipo)==="LineString"){if(a=`Extensão: ${G(e.comprimentoMetros())}`,e.ferramenta==="medir-distancia"&&e.nos>=3&&t.coordenadas.length>=3){const s={tipo:"Polygon",aneis:[t.coordenadas]};a+=` · Área: ${rt(tt(s)??0)} · Perímetro: ${G(et(s)??0)}`}}else(t==null?void 0:t.tipo)==="Circle"&&(a=`Raio: ${G(t.raioMetros)}`);i.textContent=a}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 Ji=6,ge=(n,t)=>Math.hypot(n.x-t.x,n.y-t.y);function So(n,t,e){const o=e.x-t.x,i=e.y-t.y,a=o*o+i*i,s=a===0?0:Math.max(0,Math.min(1,((n.x-t.x)*o+(n.y-t.y)*i)/a));return Math.hypot(n.x-(t.x+s*o),n.y-(t.y+s*i))}function qa(n,t){const e=n.geometria;if(e.tipo!=="Polygon")return 0;const o=e.aneis[0].map(t),i=o.map(s=>s.x),a=o.map(s=>s.y);return(Math.max(...i)-Math.min(...i))*(Math.max(...a)-Math.min(...a))}function Ee(n,t,e,o=Ji){let i=null,a=null,s=null;for(const r of t){if(r.excluida||r.oculta)continue;const c=r.geometria;if(c.tipo==="Point"||c.tipo==="Text"){const l=ge(n,e(c.coordenada));l<=o+2&&(!i||l<i.d)&&(i={f:r,d:l})}else if(c.tipo==="LineString"){let l=1/0;for(const d of U(c)){const h=d.map(e);for(let u=1;u<h.length;u++)l=Math.min(l,So(n,h[u-1],h[u]))}l<=o&&(!a||l<a.d)&&(a={f:r,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(n,l)<=h){const u=Math.PI*h*h;(!s||u<s.a)&&(s={f:r,a:u})}}else{const l=c.aneis[0].map(e);let d=1/0;for(const[u,f]of Ge(c))d=Math.min(d,So(n,l[u],l[f]));if(He([n.y,n.x],[l.map(u=>[u.y,u.x]),...c.aneis.slice(1).map(u=>u.map(e).map(f=>[f.y,f.x]))])||d<=o){const u=qa(r,e);(!s||u<s.a)&&(s={f:r,a:u})}}}return(i==null?void 0:i.f)??(a==null?void 0:a.f)??(s==null?void 0:s.f)??null}const H="feicoes",Na=new Set(["ponto","linha","poligono","retangulo","elipse","poligono-regular","estrela","circulo","texto","caneta"]);class Oa{constructor(t){p(this,"selecao");p(this,"popup");p(this,"editor",null);p(this,"snap");p(this,"desenho",null);p(this,"camadaDesenho",null);p(this,"estiloDesenho",{});p(this,"sequenciaId",0);p(this,"regra");p(this,"cacheOficiais",new WeakMap);p(this,"posicoes",new Map);p(this,"cursores");p(this,"hoverId",null);p(this,"hoverAgendado",!1);p(this,"margensHud",{});p(this,"aceitarOrigem",!1);p(this,"opcoesPopup",{copiarParaAreaDeTransferencia:!0});this.contexto=t,this.regra=t.regra??new Kt,this.cursores=new gi(()=>this.contexto.obterMapa()),this.snap=new Ma({aoMudar:e=>{var o,i,a;this.contexto.emitir("cad-snap",e),(o=this.editor)==null||o.atualizarSnapNoHud(),(a=(i=this.contexto).aoSnapMudar)==null||a.call(i,e.ligado)}}),this.popup=new wi({obterMapa:()=>this.contexto.obterMapa(),obterCamada:e=>this.contexto.obterLayerManager().getLayerDef(e),aoAcao:(e,o)=>this.tratarAcaoPopup(e,o)}),this.selecao=new vi({obterFeicao:e=>this.buscar(e.camadaId,e.id),aplicarVisual:(e,o)=>{const i=this.contexto.obterLayerManager().getLayerInstance(e),a=F.get(H);i&&a&&a.aplicarSelecao(i,o)},aoSelecionar:e=>{var o;if(this.contexto.emitir("cad-selecao",{feicoes:e}),(o=this.editor)!=null&&o.ativo){const i=this.editor.feicao;e.length===1&&e[0].id===i.id&&e[0].camadaId===i.camadaId||this.editor.parar();return}e.length===1?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(){var o;if(this.selecao.reconciliar(),(o=this.editor)!=null&&o.ativo){const i=this.editor.feicao,a=this.buscar(i.camadaId,i.id);!a||a.excluida?this.editor.parar():a!==i&&this.editor.sincronizar(a)}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){var o;const e=(o=this.contexto.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 a=0;a<e.length;a++)i.set(e[a].id,a);return this.posicoes.set(t,{lista:e,pos:i}),i}buscar(t,e){const o=this.lista(t),i=this.posicaoDe(t).get(e),a=i===void 0?void 0:o[i];if(a&&a.id===e)return a;if(i===void 0)return;this.posicoes.delete(t);const s=this.posicaoDe(t).get(e);return s===void 0?void 0:o[s]}garantirCamada(t,e){const o=this.contexto.obterLayerManager(),i=o.getLayerDef(t);if(i&&i.tipo!==H)return!1;const a=o.getOrCreateLayer(t,H,(e==null?void 0:e.nome)??t);return e!=null&&e.nome&&(a.nome=e.nome),e!=null&&e.estilo&&(a.estilo={...a.estilo,...e.estilo}),(e==null?void 0:e.interativo)!==void 0&&(a.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}opcoesNormalizacao(){return{aceitarOrigem:this.aceitarOrigem}}definirFeicoes(t,e,o){if(!this.garantirCamada(t,o))return{aceitas:0,recusadas:["camada existente não é de feições"]};const i=[],a=new Map;return(Array.isArray(e)?e:[]).forEach((s,r)=>{const c=Bt(s,t,this.opcoesNormalizacao());c?a.set(c.id,c):i.push(String((s==null?void 0:s.id)??`#${r}`))}),this.contexto.obterLayerManager().setLayerData(t,{feicoes:[...a.values()]}),this.aposDados(),{aceitas:a.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.contexto.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 a=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:a},o,this.opcoesNormalizacao())}aplicar(t,e,o={}){const i={adicionadas:0,atualizadas:0,removidas:0,recusadas:[]},a=[],s=[],r=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,k)=>String((L==null?void 0:L.id)??`#${k}`),h=[],u=L=>(i.recusadas.push(...h),L),f=[];r.forEach((L,k)=>{const I=Bt(L,t,this.opcoesNormalizacao());I?f.push(I):h.push(d(L,k))});const m=this.contexto.obterLayerManager(),g=m.getLayerDef(t);if(!(!g||g.tipo===H)||!g&&f.length===0)return c.forEach((L,k)=>i.recusadas.push(d(L,k))),f.forEach(L=>h.push(L.id)),u({resultado:i,adicionadas:a,atualizadas:s});if((f.length>0||g)&&!this.garantirCamada(t,o))return f.forEach(L=>h.push(L.id)),u({resultado:i,adicionadas:a,atualizadas:s});const A=this.lista(t),M=this.posicaoDe(t),C=A.slice(),z=[],P=[];let v=!1;for(const L of l){const k=String(L),I=M.get(k);I===void 0||C[I]===null||(C[I]=null,z.push(k),i.removidas++,v=!0)}c.forEach((L,k)=>{const I=L&&typeof L=="object"&&L.id!==void 0&&L.id!==null?String(L.id):"",_=M.get(I),O=_===void 0?null:C[_],T=O?this.mesclar(O,L,t,!!o.substituirPropriedades):null;if(!T||_===void 0){i.recusadas.push(I||d(L,k));return}C[_]=T,P.push(T),s.push(T),i.atualizadas++});for(const L of f){const k=M.get(L.id);k!==void 0&&C[k]!==null?C[k]=L:(M.set(L.id,C.length),C.push(L)),P.push(L),a.push(L),i.adicionadas++}if(P.length===0&&z.length===0)return u({resultado:i,adicionadas:a,atualizadas:s});const b=v?C.filter(L=>L!==null):C,E={feicoes:b,delta:{base:A,mudadas:P,removidas:z}};return m.setLayerData(t,E),delete E.delta,v?this.posicoes.delete(t):this.posicoes.set(t,{lista:b,pos:M}),this.aposDados(),u({resultado:i,adicionadas:a,atualizadas:s})}obterFeicoes(t){return this.lista(t).map(e=>({...e}))}tratarAcaoCamada(t,e){var o;if(t==="feicao-movida")return this.substituir(e.camadaId,e.feicao),"cad-feicao-atualizada";if(t==="feicao-clique"){if((o=this.desenho)!=null&&o.ativo)return null;const i={camadaId:e.camadaId,id:e.feicao.id};return e.aditivo?this.selecao.alternar(i):this.selecao.selecionar([i]),"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(){var t,e;(t=this.desenho)!=null&&t.ativo||((e=this.editor)!=null&&e.ativo?this.editor.parar():this.selecao.limpar())}obterFeicoesSelecionadas(){return this.selecao.obter()}selecionarNoLaco(t){var o;const e=[];for(const i of this.contexto.obterLayerManager().getActiveSelectableLayers())if(i.tipo===H)for(const a of this.lista(i.id))this.desenhada(a)&&Ai(a,t)&&e.push({camadaId:i.id,id:a.id});(o=this.desenho)==null||o.desativar(),this.selecao.selecionar(e)}selecionarNaCaixa(t,e,o){const i=this.contexto.obterMapa();if(!i)return;const a=r=>i.latLngToContainerPoint(r),s=[];for(const r of this.contexto.obterLayerManager().getActiveSelectableLayers())if(r.tipo===H)for(const c of this.lista(r.id))this.desenhada(c)&&Mi(c,t,a,e)&&s.push({camadaId:r.id,id:c.id});o?this.selecao.alternarVarias(s):this.selecao.selecionar(s)}definirMargensPopup(t){this.popup.definirMargens(t)}fecharPopup(){this.popup.fechar()}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&&Gi(t.getContainer(),this.margensHud)}get regraVersoes(){return this.regra}oficiaisDe(t){const e=this.lista(t);let o=this.cacheOficiais.get(e);return o||(o=Kt.oficiais(e),this.cacheOficiais.set(e,o)),o}visivelPorVersao(t){const e=this.contexto.obterLayerManager().getLayerInstance(t.camadaId),o=F.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)}selecionavelAgora(t){var o;const e=(o=this.editor)!=null&&o.ativo?this.editor.feicao:null;return e&&e.id===t.id&&e.camadaId===t.camadaId?!0:!t.oculta&&this.visivelPorVersao(t)}aplicarVersoes(){const t=this.contexto.obterLayerManager(),e=F.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.aposDados()}get previasGlobais(){return this.regra.global}definirPreviasGlobais(t){const e=!!t;this.regra.global!==e&&(this.regra.global=e,this.aplicarVersoes(),this.contexto.emitir("cad-previas",{global:e}))}alternarPreviasGlobais(){this.definirPreviasGlobais(!this.regra.global)}alternarPrevia(t,e){const o=this.buscar(t,e);if(!o)return null;const i=nt(o),a=this.regra.alternarIndividual(t,i);return this.aplicarVersoes(),this.contexto.emitir("cad-previas",{camadaId:t,entidadeId:i,ativa:a}),a}previaSolicitada(t,e){const o=this.buscar(t,e);return!!o&&this.regra.previaSolicitada(o)}atualizarCursorRemoto(t,e){const o=Z(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}garantirVisivel(t){const e=this.contexto.obterLayerManager(),o=e.getLayerDef(t.camadaId);if(o&&!o.visivel&&e.setLayerVisibility(t.camadaId,!0),!this.visivelPorVersao(t)){const i=nt(t);this.regra.definirIndividual(t.camadaId,i,!0),this.aplicarVersoes(),this.contexto.emitir("cad-previas",{camadaId:t.camadaId,entidadeId:i,ativa:!0})}}limitesDe(t){let e=1/0,o=1/0,i=-1/0,a=-1/0;for(const s of t){const[[r,c],[l,d]]=$e(s.geometria);r<e&&(e=r),c<o&&(o=c),l>i&&(i=l),d>a&&(a=d)}return Number.isFinite(e)?[[e,o],[i,a]]:null}enquadrar(t){const e=this.contexto.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.buscar(t,e);return!o||o.excluida?!1:(this.garantirVisivel(o),this.enquadrar([o]))}zoomParaFeicoes(t){const e=[];for(const o of Array.isArray(t)?t:[]){const i=this.buscar(o.camadaId,o.id);i&&!i.excluida&&(this.garantirVisivel(i),e.push(i))}return e.length>0&&this.enquadrar(e)}ajustarTudo(){const t=[];for(const e of this.contexto.obterLayerManager().getLayers())e.tipo!==H||!e.visivel||t.push(...this.lista(e.id).filter(o=>this.desenhada(o)));return this.enquadrar(t)}ajustarCamada(t){const e=this.contexto.obterLayerManager(),o=e.getLayerDef(t);return!o||o.tipo!==H?!1:(o.visivel||e.setLayerVisibility(t,!0),this.enquadrar(this.lista(t).filter(i=>this.desenhada(i))))}feicaoSob(t,e){const o=this.contexto.obterMapa();if(!o)return null;const i=o.getContainer().getBoundingClientRect(),a=y.point(t-i.left,e-i.top),s=o.containerPointToLatLng(a),r=[s.lat,s.lng];return{feicao:Ee({x:a.x,y:a.y},this.candidatasEm(r,8),l=>o.latLngToContainerPoint(l)),coordenada:r}}aoMoverMouse(t){var r,c;if(t.buttons!==0||!!((r=this.desenho)!=null&&r.ativo)||!!((c=this.editor)!=null&&c.ativo)){this.hoverId!==null&&(this.hoverId=null,this.contexto.emitir("cad-feicao-hover",{feicao:null}));return}if(this.hoverAgendado)return;this.hoverAgendado=!0;const{clientX:o,clientY:i}=t;let a=!1;const s=()=>{if(a)return;a=!0,this.hoverAgendado=!1;const l=this.feicaoSob(o,i),d=l!=null&&l.feicao?`${l.feicao.camadaId}\0${l.feicao.id}`:null;d!==this.hoverId&&(this.hoverId=d,this.contexto.emitir("cad-feicao-hover",{feicao:(l==null?void 0:l.feicao)??null}))};typeof requestAnimationFrame=="function"&&requestAnimationFrame(s),setTimeout(s,100)}menuContexto(t){var o;if((o=this.desenho)!=null&&o.ativo){this.desenho.botaoDireito();return}const e=this.feicaoSob(t.clientX,t.clientY);e&&this.contexto.emitir("cad-feicao-menu",{feicao:e.feicao,coordenada:e.coordenada,x:t.clientX,y:t.clientY})}destruir(){var t;(t=this.desenho)==null||t.desativar(),this.desenho=null,this.cursores.limpar(),this.hoverId=null}tratarAcaoPopup(t,e){var o,i,a;if(t==="zoom"&&this.zoomParaFeicao(e.camadaId,e.id),t==="vertices"&&this.iniciarEdicao(e.camadaId,e.id),t==="copiar"&&this.opcoesPopup.copiarParaAreaDeTransferencia){const[s,r]=It(e);(a=(i=(o=globalThis.navigator)==null?void 0:o.clipboard)==null?void 0:i.writeText(`${s.toFixed(6)}, ${r.toFixed(6)}`))==null||a.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){const o=this.contexto.obterMapa(),i=this.contexto.obterLayerManager(),a=F.get(H);if(!o||!a)return[];const s=o.latLngToContainerPoint(t),r=o.containerPointToLatLng([s.x-e,s.y+e]),c=o.containerPointToLatLng([s.x+e,s.y-e]),l={minLon:Math.min(r.lng,c.lng),maxLon:Math.max(r.lng,c.lng),minLat:Math.min(r.lat,c.lat),maxLat:Math.max(r.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(...a.consultarProximas(u,l).filter(f=>this.desenhada(f)))}return d}buscarSnapEm(t,e){const o=this.contexto.obterMapa();if(!o)return null;const i=o.latLngToContainerPoint(t),a=this.candidatasEm(t,Ue);return Wi({x:i.x,y:i.y},a,s=>o.latLngToContainerPoint(s),{},e)}get editando(){var t;return!!((t=this.editor)!=null&&t.ativo)}iniciarEdicao(t,e){var d,h;const o=this.buscar(t,e);if(!o||o.excluida)return{ok:!1,motivo:"inexistente"};const i=this.contexto.obterLayerManager().getLayerDef(t),a=zi(o,!!(i!=null&&i.bloqueada));if(a)return this.contexto.emitir("cad-edicao-recusada",{motivo:a,feicao:o}),{ok:!1,motivo:a};const s=this.contexto.obterMapa();if(!s)return{ok:!1,motivo:"sem-mapa"};(d=this.desenho)==null||d.desativar(),(h=this.editor)==null||h.parar(),this.aplicarMargensHud(),this.selecao.selecionar([{camadaId:t,id:e}]),this.popup.fechar();const r=this.contexto.obterLayerManager(),c=F.get(H),l=new Ui({map:s,snapLigado:()=>this.snap.ativo,alternarSnap:()=>this.snap.alternar(),buscarSnap:(u,f)=>this.buscarSnapEm(u,f),previsualizar:u=>{const f=r.getLayerInstance(u.camadaId);f&&c&&c.previsualizar(f,u)},aoGesto:u=>{this.substituir(u.camadaId,u),this.contexto.emitir("cad-feicao-atualizada",{camadaId:u.camadaId,feicao:u})},aoEncerrar:u=>{this.editor=null;const f=this.buscar(u.camadaId,u.id)??u;this.contexto.emitir("cad-edicao-concluida",{feicao:f});const m=this.selecao.obter();m.length===1&&this.popup.abrir(m[0])}});return this.editor=l,l.iniciar(o),this.contexto.emitir("cad-edicao-iniciada",{feicao:o}),{ok:!0}}pararEdicao(){var t;(t=this.editor)==null||t.parar()}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 a,s,r;if(!We(t))return{ok:!1,motivo:"ferramenta-invalida"};const o=this.contexto.obterMapa();if(!o)return{ok:!1,motivo:"sem-mapa"};if(Na.has(t)){const c=this.motivoCamadaDesenhoInvalida();if(c)return this.contexto.emitir("cad-desenho-recusado",{ferramenta:t,motivo:c}),{ok:!1,motivo:c}}(a=this.editor)==null||a.parar(),this.popup.fechar(),this.aplicarMargensHud(),this.desenho||(this.desenho=new Ki({map:o,buscarSnap:c=>this.buscarSnapEm(c),snapAtivo:()=>this.snap.ativo,aoGeometria:(c,l)=>this.concluirFerramenta(c,l),aoMedir:c=>this.contexto.emitir("cad-medicao",c),aoAmostrar:c=>this.amostrarEstilo(c),aoSolicitarTexto:c=>this.solicitarTexto(c),aoDesativar:()=>{var c,l;this.contexto.emitir("cad-ferramenta",{ferramenta:null}),(l=(c=this.contexto).aoFerramenta)==null||l.call(c,null)}})),this.desenho.ativar(t,e),this.contexto.emitir("cad-ferramenta",{ferramenta:t}),(r=(s=this.contexto).aoFerramenta)==null||r.call(s,t);const i=e.iniciarEm?Z(e.iniciarEm,this.opcoesNormalizacao()):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}definirAtalhoSnap(t){this.snap.atalhoS=t}motivoCamadaDesenhoInvalida(){if(!this.camadaDesenho)return"sem-camada";const t=this.contexto.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.lista(e).map(a=>a.id));let i;do this.sequenciaId++,i=`${t}-${Date.now().toString(36)}${this.sequenciaId.toString(36)}`;while(o.has(i));return i}idLivre(t,e){const o=new Set(this.lista(t).map(a=>a.id));if(!o.has(e))return e;let i=2;for(;o.has(`${e}_${i}`);)i++;return`${e}_${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.contexto.emitir("cad-texto-solicitado",e,!0)===!0}concluirFerramenta(t,e){if(t==="dividir")return e.tipo==="LineString"&&this.dividirComLinha(e.coordenadas),null;if(t==="medir-distancia"||t==="medir-area")return null;if(t==="selecao-laco")return e.tipo==="Polygon"&&this.selecionarNoLaco(e.aneis[0]),null;const o=this.camadaDesenho;if(!o)return null;const i=Object.keys(this.estiloDesenho).length>0,a=this.adicionarFeicao(o,{id:this.novoId(t,o),geometria:e,estilo:i?{...this.estiloDesenho}:void 0,propriedades:{}});return a?this.contexto.emitir("cad-feicao-criada",{camadaId:o,feicao:a}):this.contexto.emitir("cad-desenho-recusado",{ferramenta:t,motivo:"geometria-invalida"}),a}amostrarEstilo(t){const e=this.contexto.obterMapa();if(!e)return;const o=e.latLngToContainerPoint(t),i=this.candidatasEm(t,8),a=Ee({x:o.x,y:o.y},i,d=>e.latLngToContainerPoint(d));if(!a){this.contexto.emitir("cad-conta-gotas",{cor:"",feicao:null,estilo:{}});return}const s=this.contexto.obterLayerManager().getLayerDef(a.camadaId),r=a.estilo??{},c={},l=r.corTraco??(s==null?void 0:s.estilo.corPrimaria);l&&(c.corTraco=l),r.corPreenchimento&&(c.corPreenchimento=r.corPreenchimento),r.espessuraTraco!==void 0&&(c.espessuraTraco=r.espessuraTraco),r.opacidadePreenchimento!==void 0&&(c.opacidadePreenchimento=r.opacidadePreenchimento),r.dashArray&&(c.dashArray=r.dashArray),this.estiloDesenho={...this.estiloDesenho,...c},this.contexto.emitir("cad-conta-gotas",{cor:l??r.corPreenchimento??"",feicao:a,estilo:c})}dividirComLinha(t){var l;const e=this.contexto.obterLayerManager(),o=d=>(this.contexto.emitir("cad-divisao-falhou",{motivo:d}),!1),i=this.selecao.obter().filter(d=>d.geometria.tipo==="Polygon");let a=i;if(a.length===0){a=[];for(const d of e.getActiveSelectableLayers())d.tipo===H&&a.push(...this.lista(d.id).filter(h=>h.geometria.tipo==="Polygon"&&this.desenhada(h)))}if(a.length===0)return o(i.length===0&&this.selecao.obter().some(d=>kt(d.geometria))?"multiparte":"nenhum-poligono");const s=d=>{var h;return!!d.bloqueada||!!((h=e.getLayerDef(d.camadaId))!=null&&h.bloqueada)},r=a.filter(d=>!s(d)&&d.geometria.tipo==="Polygon"&&d.geometria.aneis.length===1);if(r.length===0)return o(a.some(s)?"bloqueada":"poligono-com-furos");let c=!1;for(const d of r){if(d.geometria.tipo!=="Polygon")continue;const h=xi(d.geometria.aneis[0],t);if(!h)continue;((l=this.desenho)==null?void 0:l.ferramenta)==="dividir"&&this.selecao.contem({camadaId:d.camadaId,id:d.id})&&this.desenho.desativar(),this.removerFeicao(d.camadaId,d.id);const u=[];if(h.forEach((f,m)=>{const g=Ht(d,this.idLivre(d.camadaId,`${d.id}-${m+1}`),{tipo:"Polygon",aneis:[f]}),x=this.adicionarFeicao(d.camadaId,g);x&&u.push(x)}),u.length!==h.length){for(const f of u)this.removerFeicao(f.camadaId,f.id);return this.adicionarFeicao(d.camadaId,d),o("geometria-invalida")}if(this.contexto.emitir("cad-feicao-dividida",{origem:d,partes:u}),c=!0,i.length===0)break}return c||o("sem-intersecao")}gerarBuffer(t,e,o,i={}){const a=this.buscar(t,e);if(!a)return null;const s=Li(a.geometria,o);if(!s)return null;const r=i.camadaDestino??t,c=this.adicionarFeicao(r,{id:i.id??this.idLivre(r,`${e}-buffer`),geometria:{tipo:"Polygon",aneis:[s]},estilo:a.estilo?{...a.estilo}:void 0,propriedades:{...a.propriedades,origem:e}});return c&&this.contexto.emitir("cad-feicao-criada",{camadaId:r,feicao:c}),c}duplicarFeicao(t,e,o={},i={}){const a=this.buscar(t,e);if(!a)return null;const s=Si(a.geometria,o.lesteM??0,o.norteM??0),r=this.adicionarFeicao(t,Ht(a,i.id??this.idLivre(t,`${e}-copia`),s));return r&&this.contexto.emitir("cad-feicao-criada",{camadaId:t,feicao:r}),r}juntarFeicoes(t,e,o={}){const i=h=>(this.contexto.emitir("cad-uniao-falhou",{motivo:h}),null),a=e.map(h=>this.buscar(t,h));if(a.length<2||a.some(h=>!h))return i("feicoes-insuficientes");const s=a;if(new Set(s.map(h=>h.id)).size!==s.length)return i("feicoes-insuficientes");const r=this.contexto.obterLayerManager();if(s.some(h=>{var u;return h.excluida||h.bloqueada||((u=r.getLayerDef(h.camadaId))==null?void 0:u.bloqueada)}))return i("bloqueada");const c=o.toleranciaM??0;let l=null;if(s.every(h=>h.geometria.tipo==="LineString")){if(s.some(f=>kt(f.geometria)))return i("multiparte");const h=s.map(f=>f.geometria.coordenadas),u=Pi(h,c);u&&(l=yt([u]))}else if(s.every(h=>h.geometria.tipo==="Polygon"&&h.geometria.aneis.length===1)){let h=s[0].geometria.aneis[0];for(const u of s.slice(1))h=h?Ci(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 s)this.removerFeicao(t,h.id);const d=this.adicionarFeicao(t,Ht(s[0],o.id??this.idLivre(t,`${s[0].id}-uniao`),l));if(!d){for(const h of s)this.adicionarFeicao(t,h);return i("geometria-invalida")}return this.contexto.emitir("cad-feicao-unida",{origens:s,resultado:d}),d}}const Mo={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 ve(n){if(!n)return[];const t=n.split(/[\s,]+/).map(o=>o.trim().toLowerCase()).filter(Boolean);if(t.includes("todas"))return[...oe];const e=new Set(t.filter(We));return oe.filter(o=>e.has(o))}class Fa{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 a=document.createElement("button");a.type="button",a.className="cad-btn-tool cad-draw-btn",a.dataset.ferramenta=i,a.textContent=Mo[i],a.title=Mo[i],a.setAttribute("aria-pressed","false"),a.addEventListener("click",()=>this.ctx.aoEscolher(i)),e.appendChild(a)}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 Ra="data-cad-estilos-externos";function Ba(n){try{return Array.from(n.cssRules,t=>t.cssText).join(`
|
|
166
|
+
`)}catch{return""}}function Ha(n){return typeof n=="string"?n.trim()?[n]:[]:Array.isArray(n)?n.map(t=>typeof t=="string"?t:Ba(t)).filter(t=>t.trim()!==""):[]}class Va{constructor(t){p(this,"textos",[]);p(this,"adotadas",[]);p(this,"fallback",null);this.shadow=t}get pedido(){return this.textos}definir(t){this.textos=Ha(t),this.aplicar()}limpar(){this.remover()}aplicar(){if(this.remover(),this.textos.length===0)return;const t=this.shadow;if(typeof CSSStyleSheet<"u"&&Array.isArray(t.adoptedStyleSheets))try{this.adotadas=this.textos.map(o=>{const i=new CSSStyleSheet;return i.replaceSync(o),i}),t.adoptedStyleSheets=[...t.adoptedStyleSheets,...this.adotadas];return}catch{this.adotadas=[]}const e=document.createElement("style");e.setAttribute(Ra,""),e.textContent=this.textos.join(`
|
|
167
|
+
`),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 Qi extends Ao.SafeHTMLElement{constructor(){var a;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 ye.ListenerBag);p(this,"layerItemListeners",new ye.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=fi(this,this.controller),this.shadow.innerHTML=Zn(),this.estilosExternos=new Va(this.shadow),this.mapContainer=this.shadow.getElementById("cad-map-container"),this.layersPanel=this.shadow.getElementById("qgis-layer-panel"),this.toolbarPainel=new Un({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:s=>this.tratarCliqueLivreCanvas(s),onDispararAcaoPopup:(s,r)=>this.dispararAcaoPopup(s,r)}),this.broadcastConfig=new jn({host:this,controller:this.controller,mapContainer:this.mapContainer,setLayerOpacity:(s,r)=>this.setLayerOpacity(s,r)}),this.colecoesDados=new Wn({obterController:()=>this.controller,obterChaveGrupo:()=>this.chaveGrupo,setLayerVisibility:(s,r)=>this.setLayerVisibility(s,r)});const e=new Kt,o=this.controller.context,i=this.controller.canvasInteracao.ctx;Object.assign(o,{regraVersoes:e}),this.feicoes=new Oa({obterLayerManager:()=>this.controller.layerManager,obterMapa:()=>this.controller.getMap(),regra:e,aoFerramenta:s=>{this.barraFerramentas.marcar(s)},aoSnapMudar:s=>{var r;(r=this.shadow.getElementById("btn-toggle-snap"))==null||r.classList.toggle("active",s)},emitir:(s,r,c)=>{const l=new CustomEvent(s,{detail:r,bubbles:!0,composed:!0,cancelable:!!c});return this.dispatchEvent(l),l.defaultPrevented}}),Object.assign(o,{onLayerAction:(s,r)=>{const c=this.feicoes.tratarAcaoCamada(s,r);c&&this.dispatchEvent(new CustomEvent(c,{detail:r,bubbles:!0,composed:!0}))}}),this.barraFerramentas=new Fa({raiz:this.shadow.getElementById("cad-root"),aoEscolher:s=>{this.feicoes.alternarFerramenta(s)}}),this.barraFerramentas.montar(ve(this.getAttribute("ferramentas"))),Object.assign(i,{aoMenuContexto:s=>this.feicoes.menuContexto(s),ferramentaAtiva:()=>this.feicoes.ferramentaAtiva!==null,aoLimparSelecao:()=>this.feicoes.aoPedirLimpeza(),selecionarFeicoesNaCaixa:(s,r,c)=>this.feicoes.selecionarNaCaixa(s,r,c)}),(a=this.shadow.getElementById("btn-toggle-snap"))==null||a.classList.add("active")}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"]}connectedCallback(){const e=this.getAttribute("zona-projecao")||this.getAttribute("fuso");if(e){const o=parseInt(e,10);!isNaN(o)&&o>0&&(this._zonaProjecao=o,this.controller.zonaProjecao=o,this.controller.context.zonaProjecao=o)}this.controladorTamanho.observe(),this.feicoes.conectarTeclado(),this.hoverListeners.cleanup(),this.mapContainer&&this.hoverListeners.add(this.mapContainer,"mousemove",o=>this.feicoes.aoMoverMouse(o)),this.barraFerramentas.montar(ve(this.getAttribute("ferramentas"))),this.broadcastConfig.conectar(),this.estilosExternos.aplicar(),this.initTimeout=window.setTimeout(()=>{this.initTimeout=void 0,this.inicializarAgora()},0)}destroy(){if(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(),this.broadcastConfig.desconectar(),this.limparDestaque(),this.toolbarPainel.limpar(),this.layerItemListeners.cleanup(),this.controller.destroy(),this.mapContainer&&this.mapContainer._leaflet_id)try{delete this.mapContainer._leaflet_id}catch{this.mapContainer._leaflet_id=void 0}}disconnectedCallback(){this.destroy()}invalidateSizeSafely(){this.controladorTamanho.invalidateSizeSafely()}attributeChangedCallback(e,o,i){var a,s,r,c,l;if(e==="sem-atalho-snap"){(a=this.feicoes)==null||a.definirAtalhoSnap(i===null);return}if(!(e==="sem-camadas-padrao"||e==="sem-barra-rapida")){if(e==="sem-painel-camadas"){i!==null&&((s=this.toolbarPainel)==null||s.closeLayersPanel());return}if(e==="aceitar-origem"){this.feicoes&&(this.feicoes.aceitarOrigem=i!==null&&i!=="false");return}if(e==="ferramentas"){(r=this.barraFerramentas)==null||r.montar(ve(i)),(l=this.barraFerramentas)==null||l.marcar(((c=this.feicoes)==null?void 0:c.ferramentaAtiva)??null);return}Yn({host:this,controller:this.controller,mapContainer:this.mapContainer,broadcastConfig:this.broadcastConfig,setLayerOpacity:(d,h)=>this.setLayerOpacity(d,h),setLayerScaleMode:(d,h)=>this.setLayerScaleMode(d,h),atualizarZonaProjecao:d=>{this._zonaProjecao=d}},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(){Kn({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 a=Date.now();a-this.lastCanvasClickTime<50||(this.lastCanvasClickTime=a,di(this.obterContextoEventos(),e,o,i))}dispararAcaoPopup(e,o,i){const a=Date.now();this.lastPopupActionEmit&&this.lastPopupActionEmit.acaoId===e&&this.lastPopupActionEmit.elementoId===o&&a-this.lastPopupActionEmit.time<50||(this.lastPopupActionEmit={acaoId:e,elementoId:o,time:a},hi(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");li(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 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 this.controller.context.selectedPontoIds||this.controller.canvasInteracao.ctx.selectedPontoIds||[]}set pontosSelecionados(e){const o=Array.isArray(e)?e:[];this.controller.canvasInteracao.ctx.selectedPontoIds=o,this.controller.context.selectedPontoIds=[...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",a){this.colecoesDados.plotarPolilinhaSequencial(e,o,i,a)}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,a){return this.feicoes.atualizarFeicao(e,o,i,a)}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,a){return this.feicoes.gerarBuffer(e,o,i,a)}duplicarFeicao(e,o,i,a){return this.feicoes.duplicarFeicao(e,o,i,a)}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()}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}}Ao.definirCustomElement("ui-canvas-cad",Qi);class Ga{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(s=>String(s.id)===String(o.ponto_inicio_id)),a=e.find(s=>String(s.id)===String(o.ponto_fim_id));if(i&&a&&i.lat&&i.lon&&a.lat&&a.lon){const s=o.tipo_limite_sigef||o.tipo_limite||"",r=o.metodo_posicionamento_sigef||o.metodo_posicionamento||"",c=this.bancoPontosAtivo?"#94a3b8":s==="LA1"?"#10b981":"#3b82f6",l=this.core.config.perimetroWeight,d=this.bancoPontosAtivo?.4:1,h=[[i.lat,i.lon],[a.lat,a.lon]],u=y.polyline(h,{color:"#080d0a",weight:l+3,opacity:.85,lineCap:"round",lineJoin:"round",dashArray:s==="LN1"?"6, 6":void 0,pane:"perimetroPane",interactive:!1}).addTo(this.core.map);this.polylines.push(u);const f=y.polyline(h,{color:c,weight:l,opacity:d,dashArray:s==="LN1"?"6, 6":void 0,pane:"perimetroPane"}).bindPopup(`
|
|
169
168
|
<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;">${S.escapeHtml(i.nome_vertice)} ↔ ${S.escapeHtml(
|
|
171
|
-
<div style="font-size:11px; color:rgba(255, 255, 255, 0.65);">Limite: ${S.escapeHtml(
|
|
169
|
+
<div style="font-weight:700; font-size:12px; margin-bottom:3px; color:#ffffff;">${S.escapeHtml(i.nome_vertice)} ↔ ${S.escapeHtml(a.nome_vertice)}</div>
|
|
170
|
+
<div style="font-size:11px; color:rgba(255, 255, 255, 0.65);">Limite: ${S.escapeHtml(s)} · ${S.escapeHtml(r)}</div>
|
|
172
171
|
</div>
|
|
173
|
-
`,{className:"compact-popup",maxWidth:220}).addTo(this.core.map);this.polylines.push(
|
|
172
|
+
`,{className:"compact-popup",maxWidth:220}).addTo(this.core.map);this.polylines.push(f)}})}plotPolilinhaTemporaria(t){var c,l,d;if(!this.core.map)return;const e=t.filter(h=>h.lat&&h.lon&&h.lat!==0&&h.lon!==0&&h.tipo_ponto!=="B"&&h.tipo!=="B"&&h.ignorar_poligono!==1);if(e.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=S.agruparPontosPorChave(e,o),a=this.bancoPontosAtivo?"#94a3b8":"#10b981",s=this.core.config.fechamentoWeight||2,r=this.bancoPontosAtivo?.4:1;Object.values(i).forEach(h=>{const u=S.ordenarPontosPorSequencia(h);if(u.length<2)return;for(let M=0;M<u.length-1;M++){const C=u[M],z=u[M+1],P=[[C.lat,C.lon],[z.lat,z.lon]],v=y.polyline(P,{color:"#080d0a",weight:s+3,opacity:.85,lineCap:"round",lineJoin:"round",pane:"perimetroPane",interactive:!1}).addTo(this.core.map);this.polylines.push(v);const b=y.polyline(P,{color:a,weight:s,opacity:r,pane:"perimetroPane"}).addTo(this.core.map);this.polylines.push(b)}const f=u[u.length-1],m=u[0],g=[[f.lat,f.lon],[m.lat,m.lon]],x=y.polyline(g,{color:"#080d0a",weight:s+2.5,opacity:.75,dashArray:"4, 4",pane:"perimetroPane",interactive:!1}).addTo(this.core.map);this.polylines.push(x);const A=y.polyline(g,{color:a,weight:s,opacity:r,dashArray:"4, 4",pane:"perimetroPane"}).addTo(this.core.map);this.polylines.push(A)})}plotPoligonalHomologada(t){var a,s,r;if(!this.core.map||!this.core.bancoPontosGroup)return;this.core.bancoPontosGroup.clearLayers();const e=t.filter(c=>c.lat&&c.lon&&c.lat!==0&&c.lon!==0);if(e.length===0)return;this.bancoPontosAtivo=!0,e.forEach(c=>{const l=`
|
|
174
173
|
<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
174
|
H
|
|
176
175
|
</div>
|
|
177
|
-
`,d=
|
|
176
|
+
`,d=y.divIcon({html:l,className:"banco-leaflet-marker",iconSize:[18,18]}),h=`
|
|
178
177
|
<div style="font-family:sans-serif; color:rgba(255, 255, 255, 0.9); line-height:1.35; min-width:180px;">
|
|
179
178
|
<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
179
|
<div style="font-weight:700; font-size:13px; margin-bottom:3px; color:#ffffff;">${S.escapeHtml(c.codigo_completo||c.nome_vertice)}</div>
|
|
@@ -184,13 +183,13 @@
|
|
|
184
183
|
<div style="font-size:10px; color:rgba(255, 255, 255, 0.45);">Método: ${S.escapeHtml(c.metodo_posicionamento)||"N/A"} · Limite: ${S.escapeHtml(c.tipo_limite)||"N/A"}</div>
|
|
185
184
|
${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> ${S.escapeHtml(c.confrontante_descritivo)}</div>`:""}
|
|
186
185
|
</div>
|
|
187
|
-
`;
|
|
186
|
+
`;y.marker([c.lat,c.lon],{icon:d,pane:"verticesPane"}).bindPopup(h,{className:"compact-popup",maxWidth:220}).addTo(this.core.bancoPontosGroup)});const o=((a=this.core.controller)==null?void 0:a.chaveGrupo)||((r=(s=this.core.controller)==null?void 0:s.context)==null?void 0:r.chaveGrupo),i=S.agruparPontosPorChave(e,o);for(const c in i){const l=S.ordenarPontosPorSequencia(i[c]);if(l.length>=2){const d=l.map(h=>y.latLng(h.lat,h.lon));d.push(y.latLng(l[0].lat,l[0].lon)),y.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(t=>this.core.map.removeLayer(t)),this.core.bancoPontosGroup&&this.core.bancoPontosGroup.clearLayers(),this.polylines=[]}}class ja{constructor(t,e){p(this,"markers",[]);p(this,"vizinhosMarkers",[]);p(this,"vizinhosPoligonos",[]);p(this,"core");p(this,"controller");this.core=t,this.controller=e}plotPontos(t,e){this.core.map&&t.forEach(o=>{var i,a,s;if(o.lat&&o.lon&&o.lat!==0&&o.lon!==0){const r=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):r&&(l="bg-rose-500",h=9);const u=this.core.config.enableAnimations?"transition-all duration-150":"",f=(a=(i=this.controller)==null?void 0:i.linhas)!=null&&a.bancoPontosAtivo?"opacity-40 hover:opacity-100":"",m=wt(d,h,l,`${u} ${f}`,`map-marker-${o.id}`),g=y.divIcon({html:m,className:"custom-leaflet-marker flex items-center justify-center",iconSize:[h+6,h+6]}),x=c?"Base Homologada PPP":r?"Base de Campo (Translação)":"Vértice de Perímetro",A=y.marker([o.lat,o.lon],{icon:g,pane:"verticesPane"});A.pontoId=o.id,(s=this.controller)!=null&&s.modoCliqueSequencialAtivo||A.bindPopup(`
|
|
188
187
|
<div style="font-family:var(--ui-fonte-base, sans-serif); color:rgba(255, 255, 255, 0.9); line-height:1.3;">
|
|
189
188
|
<div style="font-weight:700; font-size:13px; margin-bottom:4px; color:#ffffff;">${S.escapeHtml(o.nome_vertice)}</div>
|
|
190
|
-
<div style="font-size:11px; color:rgba(255, 255, 255, 0.65);">${S.escapeHtml(
|
|
189
|
+
<div style="font-size:11px; color:rgba(255, 255, 255, 0.65);">${S.escapeHtml(x)} · ${S.escapeHtml(o.tipo_ponto||o.tipo)}</div>
|
|
191
190
|
<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
191
|
</div>
|
|
193
|
-
`,{className:"compact-popup",maxWidth:220}),A.addTo(this.core.map),A.setZIndexOffset(1e3),A.on("click",()=>{e(o.id)}),this.markers.push(A)}})}plotPontosVizinhos(t){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 e=new Map;(t||[]).forEach(o=>{const i=o.lat??o.latitude??o.y,
|
|
192
|
+
`,{className:"compact-popup",maxWidth:220}),A.addTo(this.core.map),A.setZIndexOffset(1e3),A.on("click",()=>{e(o.id)}),this.markers.push(A)}})}plotPontosVizinhos(t){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 e=new Map;(t||[]).forEach(o=>{const i=o.lat??o.latitude??o.y,a=o.lon??o.lng??o.longitude??o.x,s=typeof i=="string"?parseFloat(i.replace(",",".")):Number(i),r=typeof a=="string"?parseFloat(a.replace(",",".")):Number(a);if(s!==void 0&&r!==void 0&&!isNaN(s)&&!isNaN(r)&&s!==0&&r!==0){o.lat=s,o.lon=r;const c=o.confrontante_id!==void 0&&o.confrontante_id!==null?String(o.confrontante_id):"0";e.has(c)||e.set(c,[]),e.get(c).push(o)}}),e.forEach(o=>{if(o.length>=2){o.sort((a,s)=>Number(a.id)-Number(s.id));const i=o.map(a=>y.latLng(a.lat,a.lon));o.length>2&&i.push(y.latLng(o[0].lat,o[0].lon)),y.polyline(i,{color:"#a855f7",weight:this.core.config.vizinhoWeight,dashArray:"4, 6",pane:"overlayPane"}).addTo(this.core.pontosVizinhosGroup)}o.forEach(i=>{var u,f;const a=document.createElement("div");a.className="p-2 font-sans text-xs bg-[#0c1510] text-white min-w-[200px] rounded",a.innerHTML=`
|
|
194
193
|
<div class="font-bold text-purple-400 mb-1 border-b border-white/10 pb-1">Confrontante (Importado)</div>
|
|
195
194
|
<div class="mb-1"><strong>Vértice:</strong> <span class="font-mono">${S.escapeHtml(i.nome_vertice||"")}</span></div>
|
|
196
195
|
<div class="mb-1"><strong>Proprietário:</strong> ${S.escapeHtml(i.nome_confrontante||"")||"Desconhecido"}</div>
|
|
@@ -205,10 +204,10 @@
|
|
|
205
204
|
Ocultar
|
|
206
205
|
</button>
|
|
207
206
|
</div>
|
|
208
|
-
`,(u=
|
|
207
|
+
`,(u=a.querySelector(".btn-integrar"))==null||u.addEventListener("click",()=>{window.dispatchEvent(new CustomEvent("gerencigeo:integrar_vizinho",{detail:{pontoId:i.id}}))}),(f=a.querySelector(".btn-ocultar"))==null||f.addEventListener("click",()=>{window.dispatchEvent(new CustomEvent("gerencigeo:ocultar_vizinho",{detail:{pontoId:i.id}}))});let s=this.core.config.markerStyleV||"cross",r=this.core.config.markerSizeV||8;i.tipo_ponto==="M"||i.tipo==="M"||i.tipo==="B"?(s=this.core.config.markerStyleM||"circle-dot",r=this.core.config.markerSizeM||14):(i.tipo_ponto==="P"||i.tipo==="P"||i.tipo==="O")&&(s=this.core.config.markerStyleP||"circle",r=this.core.config.markerSizeP||10);const c=this.core.config.enableAnimations?"transition-all duration-150":"",l=wt(s,r,"bg-[#a855f7]",c,`map-marker-vizinho-${i.id}`),d=y.divIcon({html:l,className:"custom-leaflet-marker flex items-center justify-center",iconSize:[r+4,r+4]}),h=y.marker([i.lat,i.lon],{icon:d,pane:"overlayPane"}).bindPopup(a,{className:"custom-leaflet-popup"});h.pontoId=i.id,h.isVizinho=!0,h.addTo(this.core.pontosVizinhosGroup),this.vizinhosMarkers.push(h)})})}plotPoligonosVizinhos(t){!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(e=>e.off()),this.vizinhosPoligonos=[]),(t||[]).forEach(e=>{if(!e||!e.poligono_wkt)return;const o=/POLYGON\s*\(\s*\(\s*(.*?)\s*\)\s*\)/i.exec(e.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 a=S.escapeHtml(e.nome_propriedade||"Propriedade Vizinha"),s=S.escapeHtml(e.nome||"Desconhecido"),r=y.polygon(i,{color:"#a855f7",weight:this.core.config.vizinhoWeight,dashArray:"4, 6",fillColor:"#a855f7",fillOpacity:.05,pane:"overlayPane"}).bindPopup(`
|
|
209
208
|
<div class="p-2 font-sans text-xs bg-[#0c1510] text-white min-w-[200px] rounded">
|
|
210
209
|
<div class="font-bold text-purple-400 mb-1 border-b border-white/10 pb-1">Limite do Vizinho (Importado)</div>
|
|
211
|
-
<div class="mb-1"><strong>Propriedade:</strong> ${
|
|
212
|
-
<div class="mb-1"><strong>Proprietário:</strong> ${
|
|
210
|
+
<div class="mb-1"><strong>Propriedade:</strong> ${a}</div>
|
|
211
|
+
<div class="mb-1"><strong>Proprietário:</strong> ${s}</div>
|
|
213
212
|
</div>
|
|
214
|
-
`,{className:"custom-leaflet-popup"});
|
|
213
|
+
`,{className:"custom-leaflet-popup"});r.addTo(this.core.pontosVizinhosGroup),this.vizinhosPoligonos.push(r)}))}clearMarkers(){this.markers&&(this.markers.forEach(t=>{t.off(),t.unbindPopup(),this.core.map&&this.core.map.removeLayer(t)}),this.markers=[]),this.vizinhosMarkers&&(this.vizinhosMarkers.forEach(t=>{t.off(),t.unbindPopup()}),this.vizinhosMarkers=[]),this.vizinhosPoligonos&&(this.vizinhosPoligonos.forEach(t=>t.off()),this.vizinhosPoligonos=[]),this.core.pontosVizinhosGroup&&this.core.pontosVizinhosGroup.clearLayers()}}exports.agruparPontosPorChave=S.agruparPontosPorChave;exports.bindPopupAcoesEvents=S.bindPopupAcoesEvents;exports.escapeHtml=S.escapeHtml;exports.extrairCentroDeWkt=S.extrairCentroDeWkt;exports.formatUTM=S.formatUTM;exports.ordenarPontosPorSequencia=S.ordenarPontosPorSequencia;exports.parseCoordenada=S.parseCoordenada;exports.renderPopupAcoesHtml=S.renderPopupAcoesHtml;exports.AgrupadorCluster=ai;exports.CADMapaController=ne;exports.CAD_INTERACTIVE_PANES=ko;exports.CELULA_CLUSTER_PX=Et;exports.CLASSE_FERRAMENTA_ATIVA=ze;exports.COR_SELECAO=ft;exports.CSS_POSICAO_HUD=je;exports.CanvasCADController=ne;exports.CanvasInteracao=Do;exports.CanvasLayerManager=ri;exports.ControleDesenho=Ki;exports.CursoresRemotos=gi;exports.DEFAULT_CONFIG=xe;exports.DEFAULT_LAYERS=Se;exports.EditorVertices=Ui;exports.FERRAMENTAS=oe;exports.FOLGA_HUD=Hi;exports.FRACAO_LARGURA_HUD=Vi;exports.FeicaoPopup=wi;exports.FeicoesLayerRenderer=si;exports.GerenciGeoMapaController=ne;exports.GridLayerRenderer=Ho;exports.ICONES_FEICAO=Rt;exports.ID_HUD_DESENHO=Yi;exports.ID_HUD_EDICAO=ji;exports.IndiceEspacial=jo;exports.LIMIAR_DENSIDADE_ALTA=Wt;exports.LIMITE_CULLING=Le;exports.LayerRendererFactory=F;exports.MARGEM_HUD_PADRAO=Bi;exports.MAX_PONTOS_SEM_CLUSTER=ii;exports.MAX_VERTICES_EDICAO=ki;exports.MIN_VERTICES_SIMPLIFICAR=qe;exports.MapaConfigManager=Ut;exports.MapaCore=wo;exports.MapaLinhas=Ga;exports.MapaMarcadores=ja;exports.PROPRIEDADES_HUD=Gt;exports.RAIO_MINIMO_CIRCULO_M=ke;exports.RAIO_MINIMO_EDICAO_CIRCULO_M=_i;exports.RegraVersoes=Kt;exports.SelecaoFeicoes=vi;exports.SessaoDesenho=jt;exports.TOLERANCIA_AMOSTRA_PX=Ji;exports.TOLERANCIA_LINHA_PX=Ft;exports.TOLERANCIA_PONTO_PX=Io;exports.TOLERANCIA_SNAP_PX=Ue;exports.TileLayerRenderer=$o;exports.UICanvasCAD=Qi;exports.VectorLinesLayerRenderer=Oo;exports.VectorPointsLayerRenderer=Ro;exports.VectorPolygonsLayerRenderer=Bo;exports.WmsLayerRenderer=qo;exports.ZOOM_DESMEMBRAR=oi;exports.ZOOM_SEM_SIMPLIFICACAO=Yt;exports.agruparPontos=Mn;exports.alternarSuavidade=Ri;exports.amostrarBezier=Zi;exports.aplicarMargensHud=Gi;exports.areaDaGeometria=tt;exports.areaMetros2=Vo;exports.buscarSnap=Wi;exports.caixaDaFeicao=Ce;exports.caixasSeTocam=mt;exports.centroDe=ni;exports.clonarFeicao=Ht;exports.comPontos=Di;exports.comVertices=Dt;exports.comprimentoMetros=zt;exports.confrontanteParaFeicao=ea;exports.consultarFeicoesNoPonto=_e;exports.converterArea=da;exports.converterComprimento=la;exports.coordenadaDeReferencia=It;exports.corHexSegura=te;exports.corSegura=Y;exports.criarControladorTamanho=fi;exports.criarLinha=yt;exports.ddParaDms=ha;exports.deslocarGeometria=Si;exports.deveAgrupar=Qt;exports.distanciaEntre=pa;exports.distanciaMetros=st;exports.dividirPoligonoComLinha=xi;exports.dmsParaDd=ua;exports.ehFerramenta=We;exports.ehMultilinha=kt;exports.entidadeDe=nt;exports.extensaoDaGeometria=et;exports.extrairCorPonto=Fo;exports.fatorDensidade=Te;exports.feicaoNaCaixa=Mi;exports.feicaoNoLaco=Ai;exports.feicaoNoPonto=Ee;exports.feicaoNoTopo=un;exports.formatarArea=rt;exports.formatarExtensao=G;exports.garantirCanvasSemEventos=_o;exports.gerarBuffer=Li;exports.getPointShapeHtml=wt;exports.inserirPonto=qi;exports.inserirVertice=Ei;exports.juntarLinhas=Pi;exports.juntarPoligonos=Ci;exports.limitesDaGeometria=$e;exports.metrosPorGrau=ie;exports.minimoVertices=Tt;exports.modoDensidade=Xt;exports.moverAlca=Fi;exports.moverVertice=Pa;exports.normalizarAnel=Be;exports.normalizarCoordenada=Z;exports.normalizarFeicaoEntrada=Bt;exports.normalizarLinha=Ae;exports.normalizarPoligono=mi;exports.nosDe=W;exports.nosDeAncoras=At;exports.partesDaLinha=U;exports.pontoDaBordaDoCirculo=Ti;exports.pontoMedio=Ve;exports.pontoMedioDoSegmento=Vt;exports.pontoNoPoligono=He;exports.pontoParaFeicao=Qn;exports.pontosDe=St;exports.posicaoHud=La;exports.processarAcaoPopup=hi;exports.processarCliqueLivreCanvas=di;exports.removerPonto=Ni;exports.removerVertice=Ii;exports.renderizarPainelCamadas=li;exports.resolverCliqueCentral=To;exports.segmentoParaFeicao=ta;exports.segmentosDe=Ge;exports.segmentosDoEditor=$i;exports.simplificarAnel=Wo;exports.simplificarGeometria=Xo;exports.simplificarLinha=Ne;exports.statusDe=K;exports.textoRotulo=Go;exports.toleranciaPorZoom=Uo;exports.tratarCliqueMarcador=ui;exports.tratarCliqueSegmento=pi;exports.verificarEditavel=zi;exports.vertices=Oe;exports.verticesDe=J;
|