@thibezer/ui-components-kit 2.0.0 → 2.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +54 -0
- package/README.md +760 -739
- package/dist/camadas.cjs +72 -72
- package/dist/camadas.js +700 -667
- package/dist/canvas.cjs +99 -140
- package/dist/canvas.js +5125 -1192
- package/dist/components/ui-camadas/camadas-persistencia.d.ts +4 -0
- package/dist/components/ui-camadas/ui-camadas.d.ts +10 -0
- package/dist/components/ui-canvas-cad/cad-estilos-externos.d.ts +16 -0
- package/dist/components/ui-canvas-cad/cad-eventos-canvas.d.ts +4 -0
- package/dist/components/ui-canvas-cad/cad-feicoes.d.ts +262 -0
- package/dist/components/ui-canvas-cad/cad-ferramentas-barra.d.ts +15 -0
- package/dist/components/ui-canvas-cad/cad-snap.d.ts +32 -0
- package/dist/components/ui-canvas-cad/cad-toolbar-painel.d.ts +1 -0
- package/dist/components/ui-canvas-cad/ui-canvas-cad.d.ts +143 -0
- package/dist/components/ui-lista-flutuante/lista-flutuante-posicionamento.d.ts +2 -0
- package/dist/components/ui-lista-flutuante/ui-lista-flutuante.d.ts +1 -0
- package/dist/components/ui-seletor-mapa-base/ui-seletor-mapa-base.d.ts +3 -0
- package/dist/components/ui-tabela/tabela-atributos-sync.d.ts +3 -0
- package/dist/components/ui-tabela/tabela-localizador.d.ts +8 -1
- package/dist/components/ui-tabela/tabela-orquestrador-dados.d.ts +4 -0
- package/dist/components/ui-tabela/tabela-selecao.d.ts +19 -9
- package/dist/components/ui-tabela/tipos.d.ts +6 -0
- package/dist/components/ui-tabela/ui-tabela.d.ts +41 -2
- package/dist/components/ui-tabela-propriedades/avaliador-expressao.d.ts +0 -5
- package/dist/components/ui-tabela-propriedades/propriedades-dom-utils.d.ts +17 -1
- package/dist/components/ui-tabela-propriedades/propriedades-flutuante.d.ts +2 -0
- package/dist/components/ui-tabela-propriedades/propriedades-gerenciador-valores.d.ts +10 -1
- package/dist/components/ui-tabela-propriedades/propriedades-render-arvore.d.ts +3 -1
- package/dist/components/ui-tabela-propriedades/ui-tabela-propriedades.d.ts +5 -1
- package/dist/core/alvo-digitavel.d.ts +1 -0
- package/dist/core/index.d.ts +1 -0
- package/dist/core/svg-seguro.d.ts +10 -0
- package/dist/core.cjs +1 -1
- package/dist/core.js +12 -10
- package/dist/custom-elements.json +14782 -10666
- package/dist/data.cjs +1 -1
- package/dist/data.js +51 -46
- package/dist/forms.cjs +1 -1
- package/dist/forms.js +1 -1
- package/dist/gerencigeo-canvas/canvas_interacao.d.ts +18 -0
- package/dist/gerencigeo-canvas/feature_adapters.d.ts +35 -0
- package/dist/gerencigeo-canvas/feature_algoritmos.d.ts +45 -0
- package/dist/gerencigeo-canvas/feature_amostra.d.ts +4 -0
- package/dist/gerencigeo-canvas/feature_caixa.d.ts +19 -0
- package/dist/gerencigeo-canvas/feature_cluster.d.ts +61 -0
- package/dist/gerencigeo-canvas/feature_cursores.d.ts +17 -0
- package/dist/gerencigeo-canvas/feature_desenho.d.ts +53 -0
- package/dist/gerencigeo-canvas/feature_desenho_controle.d.ts +91 -0
- package/dist/gerencigeo-canvas/feature_edicao_ops.d.ts +19 -0
- package/dist/gerencigeo-canvas/feature_editor_vertices.d.ts +62 -0
- package/dist/gerencigeo-canvas/feature_formas.d.ts +7 -0
- package/dist/gerencigeo-canvas/feature_hud.d.ts +23 -0
- package/dist/gerencigeo-canvas/feature_indice.d.ts +36 -0
- package/dist/gerencigeo-canvas/feature_metricas.d.ts +16 -0
- package/dist/gerencigeo-canvas/feature_popup.d.ts +31 -0
- package/dist/gerencigeo-canvas/feature_selecao.d.ts +38 -0
- package/dist/gerencigeo-canvas/feature_simplificacao.d.ts +14 -0
- package/dist/gerencigeo-canvas/feature_snap.d.ts +25 -0
- package/dist/gerencigeo-canvas/feature_types.d.ts +86 -0
- package/dist/gerencigeo-canvas/feature_versoes.d.ts +19 -0
- package/dist/gerencigeo-canvas/index.d.ts +21 -0
- package/dist/gerencigeo-canvas/layer_hit_test.d.ts +30 -0
- package/dist/gerencigeo-canvas/layer_manager.d.ts +11 -3
- package/dist/gerencigeo-canvas/layer_pane_ops.d.ts +9 -0
- package/dist/gerencigeo-canvas/mapa_controller.d.ts +1 -0
- package/dist/gerencigeo-canvas/mapa_pontos_shapes.d.ts +24 -5
- package/dist/gerencigeo-canvas/renderers/feicoes_renderer.d.ts +89 -0
- package/dist/gerencigeo-canvas/renderers/vector_points_renderer.d.ts +1 -0
- package/dist/gerencigeo-canvas/renderers/vector_polygons_renderer.d.ts +2 -2
- package/dist/gerencigeo-canvas/types.d.ts +12 -0
- package/dist/gerencigeo-canvas/utils.d.ts +3 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +111 -106
- package/dist/leaflet-DcO7uRC-.cjs +1 -0
- package/dist/{leaflet-DkaFZYc5.js → leaflet-PPDKB6Dd.js} +37 -37
- package/dist/mapa.cjs +1 -1
- package/dist/mapa.js +1 -1
- package/dist/register.cjs +1 -1
- package/dist/register.js +3 -3
- package/dist/seletor-mapa-base.cjs +13 -13
- package/dist/seletor-mapa-base.js +101 -51
- package/dist/svg-seguro-BsbNQqpd.js +50 -0
- package/dist/svg-seguro-C76iLlAZ.cjs +1 -0
- package/dist/tabela.cjs +1 -1
- package/dist/tabela.js +41 -36
- package/dist/tipos-elementos.d.ts +17 -4
- package/dist/tipos-vue.d.ts +15 -4
- package/dist/tools.cjs +1 -1
- package/dist/tools.js +1 -1
- package/dist/{ui-paleta-ferramentas-BIytXQLh.js → ui-paleta-ferramentas-CEZYcN4J.js} +18 -27
- package/dist/{ui-paleta-ferramentas-DqLY51qa.cjs → ui-paleta-ferramentas-Dbj1kBS9.cjs} +6 -6
- package/dist/{ui-switch-DWLgVVnT.js → ui-switch-BcOqOkiV.js} +124 -96
- package/dist/ui-switch-D7iPKDj-.cjs +53 -0
- package/dist/ui-tabela-propriedades-BBr5sqki.cjs +145 -0
- package/dist/{ui-tabela-propriedades-BNcE6VLX.js → ui-tabela-propriedades-Boy7I5yW.js} +1304 -1072
- package/package.json +169 -169
- package/dist/leaflet-Cw6tqYFh.cjs +0 -1
- package/dist/ui-switch-yZIn3IW0.cjs +0 -53
- package/dist/ui-tabela-propriedades-D3pyQvyy.cjs +0 -145
package/dist/canvas.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var Pi=Object.defineProperty;var Ci=(n,t,e)=>t in n?Pi(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e;var p=(n,t,e)=>Ci(n,typeof t!="symbol"?t+"":t,e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});;/* empty css */const y=require("leaflet"),L=require("./leaflet-DcO7uRC-.cjs"),se=require("./listener-bag-D5omxZ9h.cjs"),lo=require("./ssr-safe-CiHD1adl.cjs"),re={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},at=class at{constructor(){p(this,"config");this.config=this.loadConfig()}static getInstance(){return at.instance||(at.instance=new at),at.instance}loadConfig(){try{const t=typeof localStorage<"u"?localStorage.getItem("gerencigeo_mapa_config"):null;if(t)return{...re,...JSON.parse(t)}}catch(t){console.error("Erro ao carregar configurações do mapa",t)}return{...re}}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(at,"instance");let Nt=at;async function Si(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 b=n.layerPointToContainerPoint(t.layerPoint);l=Math.round(b.x),d=Math.round(b.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 m=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
|
-
`).openOn(n);o.currentAbortController&&o.currentAbortController.abort(),o.currentAbortController=new AbortController;const
|
|
9
|
+
`).openOn(n);o.currentAbortController&&o.currentAbortController.abort(),o.currentAbortController=new AbortController;const f=o.currentAbortController.signal,g=setTimeout(()=>{o.currentAbortController&&o.currentAbortController.abort()},8e3);try{const w=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(w,{signal:f});clearTimeout(g);let C=null;if(M.ok){const E=await M.text();try{C=JSON.parse(E)}catch{C=null}}if(C&&C.features&&C.features.length>0){const E=C.features[0],P=E.properties||{},v=String(E.id||P.parcela_codigo||P.co_parcela||P.id_parcela||""),x=String(P.nome_area||P.nome_imovel||"Imóvel Sem Nome");if(v){const k=encodeURIComponent(v),z=`https://sigef.incra.gov.br/geo/exportar/parcela/shp/${k}/`,S=`https://sigef.incra.gov.br/geo/parcela/detalhe/${k}/`,A=document.createElement("div");A.style.cssText="font-family:var(--ui-fonte-base, sans-serif); color:rgba(255, 255, 255, 0.9); line-height:1.4; min-width:180px;",A.innerHTML=`
|
|
10
10
|
<div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:6px; padding-bottom:5px; border-bottom:1px solid rgba(255, 255, 255, 0.1);">
|
|
11
11
|
<span style="font-weight:700; font-size:11px; color:#10b981; text-transform:uppercase; letter-spacing:0.5px;">SIGEF</span>
|
|
12
|
-
<span style="font-size:10px; color:rgba(255, 255, 255, 0.5);">${
|
|
12
|
+
<span style="font-size:10px; color:rgba(255, 255, 255, 0.5);">${L.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;">${
|
|
15
|
-
<div style="font-size:11px; color:rgba(255, 255, 255, 0.7); margin-bottom:2px;">Cód: <span style="font-family:var(--ui-fonte-codigo, monospace);">${
|
|
14
|
+
<div style="font-weight:700; font-size:12px; margin-bottom:4px; color:#ffffff; word-break:break-word;">${L.escapeHtml(x)}</div>
|
|
15
|
+
<div style="font-size:11px; color:rgba(255, 255, 255, 0.7); margin-bottom:2px;">Cód: <span style="font-family:var(--ui-fonte-codigo, monospace);">${L.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
|
-
<span>Mat: <strong style="color:#ffffff;">${
|
|
18
|
-
<span>${
|
|
17
|
+
<span>Mat: <strong style="color:#ffffff;">${L.escapeHtml(P.registro_matricula||P.matricula||"N/A")}</strong></span>
|
|
18
|
+
<span>${L.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="${z}" target="_blank" rel="noopener noreferrer" style="display:flex; align-items:center; justify-content:center; gap:5px; padding:5px 8px; background:rgba(16, 185, 129, 0.15); border:1px solid rgba(16, 185, 129, 0.3); color:#34d399; font-size:11px; font-weight:700; border-radius:5px; text-decoration:none; cursor:pointer;">
|
|
22
22
|
<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
|
|
23
23
|
Baixar Shapefile
|
|
24
24
|
</a>
|
|
@@ -26,158 +26,112 @@
|
|
|
26
26
|
<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
|
|
27
27
|
Importar Confrontante (CSV)
|
|
28
28
|
</button>
|
|
29
|
-
<a href="${
|
|
29
|
+
<a href="${S}" target="_blank" rel="noopener noreferrer" style="display:flex; align-items:center; justify-content:center; gap:4px; padding:4px 6px; background:rgba(255, 255, 255, 0.05); border:1px solid rgba(255, 255, 255, 0.1); color:rgba(255, 255, 255, 0.7); font-size:10px; font-weight:600; border-radius:5px; text-decoration:none; cursor:pointer;">
|
|
30
30
|
<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></svg>
|
|
31
31
|
Abrir no SIGEF
|
|
32
32
|
</a>
|
|
33
33
|
</div>
|
|
34
|
-
`;const
|
|
34
|
+
`;const I=A.querySelector(".btn-importar-confrontante-sigef");I&&I.addEventListener("click",()=>{window.dispatchEvent(new CustomEvent("gerencigeo:importar_vizinho_sigef",{detail:{uuid:v,nome:x}}))}),m.setContent(A)}else m.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 m.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(b){b.name==="AbortError"?m.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:",b),m.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{f.style.cursor=""}}function At(n,t){if(!n)return;const e=Math.floor(n.getZoom()),o=Math.max(e,12),i=Math.min(e+1,19),s=t.pad(.2),a=["mt0","mt1","mt2","mt3"];let c=0;const r=32;for(let l=o;l<=i&&c<r;l++){const p=s.getNorthWest(),d=s.getSouthEast(),f=Q(p.lng,l),h=Q(d.lng,l),b=tt(p.lat,l),S=tt(d.lat,l);for(let x=f;x<=h&&c<r;x++)for(let M=b;M<=S&&c<r;M++){const z=`https://${a[(x+M)%a.length]}.google.com/vt/lyrs=s,h&x=${x}&y=${M}&z=${l}`,A=new Image;A.src=z,c++}}}function Q(n,t){return Math.floor((n+180)/360*Math.pow(2,t))}function tt(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 rt{constructor(t){u(this,"map",null);u(this,"configManager",U.getInstance());u(this,"config",this.configManager.getConfig());u(this,"apiBaseUrl","/api");u(this,"bancoPontosGroup",y.layerGroup());u(this,"pontosVizinhosGroup",y.layerGroup());u(this,"controller");u(this,"containerElement",null);u(this,"bc");u(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="450"}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){At(this.map,t)}async consultarSigef(t){this.map&&await It(this.map,t,this.apiBaseUrl,this.sigefState)}}const lt=["verticesPane","perimetroPane","overlayPane","markerPane","pane-vertices","pane-perimetro","pane-vizinhos","pane-homologados","pane-homologados-pontos"];class Et{constructor(t,e,o){u(this,"map");u(this,"mapContainer");u(this,"ctx");u(this,"selectionDiv",null);u(this,"isSelecting",!1);u(this,"selectStartPos",{x:0,y:0});u(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){lt.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,s=Math.abs(o-this.selectStartPos.x),a=Math.abs(i-this.selectStartPos.y),c=Math.min(o,this.selectStartPos.x),r=Math.min(i,this.selectStartPos.y);this.selectionDiv.style.left=`${Math.round(c)}px`,this.selectionDiv.style.top=`${Math.round(r)}px`,this.selectionDiv.style.width=`${Math.round(s)}px`,this.selectionDiv.style.height=`${Math.round(a)}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,I,z,A,C,m;if(!this.isSelecting)return!1;this.isSelecting=!1,this.selectionDiv&&(this.selectionDiv.style.display="none"),this.map.closePopup(),setTimeout(()=>{try{this.setPanesPointerEvents("auto"),this.ctx.layerManager&&this.ctx.layerManager.ensurePanes()}catch{}},80);const i=this.mapContainer.getBoundingClientRect(),s=t.clientX-i.left,a=t.clientY-i.top,c=this.map.mouseEventToContainerPoint(t),r=Math.abs(s-this.selectStartPos.x),l=Math.abs(a-this.selectStartPos.y);if(r<4&&l<4){const v=t.target;return v&&((M=v.classList)!=null&&M.contains("leaflet-container")||v.id==="mapa-triagem"||(I=v.closest)!=null&&I.call(v,".leaflet-pane"))&&((z=v.closest)!=null&&z.call(v,".custom-leaflet-marker")||(A=v.closest)!=null&&A.call(v,".custom-div-icon")||o()),!1}if(!this.selectStartPoint)return!1;const p={x1:Math.min(this.selectStartPoint.x,c.x),y1:Math.min(this.selectStartPoint.y,c.y),x2:Math.max(this.selectStartPoint.x,c.x),y2:Math.max(this.selectStartPoint.y,c.y)},d=((C=this.ctx.mapaController)==null?void 0:C.getMarkers())||[],f=((m=this.ctx.mapaController)==null?void 0:m.getVizinhosMarkers())||[],h=[],b=[],S=!this.ctx.layerManager||this.ctx.layerManager.isLayerActiveAndSelectable("vertices"),x=!this.ctx.layerManager||this.ctx.layerManager.isLayerActiveAndSelectable("vizinhos");return S&&d.forEach(v=>{const P=v.pontoId;if(!P)return;const k=this.map.latLngToContainerPoint(v.getLatLng());k.x>=p.x1&&k.x<=p.x2&&k.y>=p.y1&&k.y<=p.y2&&h.push(P)}),x&&f.forEach(v=>{const P=v.pontoId;if(!P)return;const k=this.map.latLngToContainerPoint(v.getLatLng());k.x>=p.x1&&k.x<=p.x2&&k.y>=p.y1&&k.y<=p.y2&&b.push(P)}),t.ctrlKey||t.metaKey?(h.forEach(v=>{this.ctx.selectedPontoIds.includes(v)?this.ctx.selectedPontoIds=this.ctx.selectedPontoIds.filter(P=>P!==v):this.ctx.selectedPontoIds.push(v)}),b.forEach(v=>{this.ctx.selectedVizinhoPontoIds.includes(v)?this.ctx.selectedVizinhoPontoIds=this.ctx.selectedVizinhoPontoIds.filter(P=>P!==v):this.ctx.selectedVizinhoPontoIds.push(v)})):(this.ctx.selectedPontoIds=h,this.ctx.selectedVizinhoPontoIds=b),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")}}class ct{constructor(t){u(this,"ctx");u(this,"map",null);u(this,"mapContainer",null);u(this,"selecaoBox",null);u(this,"isPanning",!1);u(this,"lastMousePos",{x:0,y:0});u(this,"lastMiddleClickTime",0);u(this,"touchStartPos",{x:0,y:0});u(this,"touchStartDist",0);u(this,"isTouchPanning",!1);u(this,"selectionHappened",!1);u(this,"panHappened",!1);u(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)}}});u(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)}}});u(this,"handleTouchEnd",()=>{this.isTouchPanning=!1,this.touchStartDist=0,setTimeout(()=>{this.panHappened=!1},120)});u(this,"handleContextMenu",t=>{t.preventDefault()});u(this,"handleMouseDown",t=>{var e;if(!(!this.map||!this.mapContainer)){if(t.button===1){t.preventDefault();const o=Date.now();if(o-this.lastMiddleClickTime<300){this.zoomExtents();return}this.lastMiddleClickTime=o,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(this.selectionHappened=!1,this.ctx.mapaController&&this.ctx.mapaController.modoCliqueSequencialAtivo)return;(e=this.selecaoBox)==null||e.iniciarSelecao(t)}}});u(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)}});u(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,setTimeout(()=>{this.selectionHappened=!1},120))});u(this,"handleKeyDown",t=>{var e;if(t.key==="Escape"){const o=document.activeElement;if(o&&(o.tagName==="INPUT"||o.tagName==="TEXTAREA"||o.tagName==="SELECT"||o.isContentEditable))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 Et(this.map,this.mapContainer,this.ctx),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("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.selecaoBox&&(this.selecaoBox.destruir(),this.selecaoBox=null),this.map&&(this.map.dragging.enable(),this.map.doubleClickZoom.enable())}limparSelecao(){var t,e;(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=[],(e=(t=this.ctx.mapaController).atualizarDestaqueMarcadores)==null||e.call(t)),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 G{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())}}u(G,"renderers",new Map);class dt{render(t,e,o){var r,l,p;const i=((r=t.dados)==null?void 0:r.url)||"https://{s}.google.com/vt/lyrs=s,h&x={x}&y={y}&z={z}",s=((l=t.dados)==null?void 0:l.subdomains)||["mt0","mt1","mt2","mt3"],a=((p=t.dados)==null?void 0:p.attribution)||"Google Satélite";return y.tileLayer(i,{maxZoom:24,maxNativeZoom:20,subdomains:s,attribution:a,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 pt{render(t,e,o){var l,p,d,f;const i=((l=t.dados)==null?void 0:l.url)||"https://acervofundiario.incra.gov.br/i3geo/ogc.php",s=((p=t.dados)==null?void 0:p.layers)||"certificada_sigef_particular_pr",a=((d=t.dados)==null?void 0:d.format)||"image/png",c=((f=t.dados)==null?void 0:f.attribution)||"INCRA/SIGEF";return y.tileLayer.wms(i,{layers:s,format:a,transparent:!0,version:"1.1.1",pane:`pane-${t.id}`,attribution:c,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 ht(n,t,e){const o=n.estilo.espessuraLinha||e.config.perimetroWeight||2,i=e.graphicScale.lineScaleMultiplier||1;if(n.estilo.scaleMode==="world"){const s=n.estilo.dimensaoMetros||.3,a=t.getCenter(),c=t.getZoom(),r=40075016686e-3*Math.abs(Math.cos(a.lat*Math.PI/180))/Math.pow(2,c+8),l=s/(r>0?r:1);return Math.max(1,Math.round(l*i))}return Math.max(1,Math.round(o*i))}function et(n,t,e,o,i){var b,S,x,M,I,z,A,C;const s=n.id==="homologados",a=((b=n.dados)==null?void 0:b.conexoes)??(Array.isArray(n.dados)&&n.dados.length>0&&"origemId"in n.dados[0]?n.dados:null),c=((S=n.dados)==null?void 0:S.segmentos)||o.segmentos||[],r=((x=n.dados)==null?void 0:x.pontos)||(s?o.bancoPontos||[]:o.pontos)||[],l=ht(n,e,o),p=n.opacidade!==void 0?n.opacidade:1,d=n.interativo&&!n.bloqueada,f=[];r.forEach(m=>{const v=g.parseCoordenada(m.lat??m.latitude??m.y,m.lon??m.lng??m.longitude??m.x);v&&f.push({...m,lat:v.lat,lon:v.lon})});const h=m=>{const v=f.find(P=>String(P.id)===String(m));if(v)return v;if(o.pontos){const P=o.pontos.find(k=>String(k.id)===String(m));if(P){const k=g.parseCoordenada(P.lat,P.lon);if(k)return{...P,lat:k.lat,lon:k.lon}}}return null};if(a&&Array.isArray(a)){a.forEach(m=>{var k,_,L,N,q,H,w;const v=h(m.origemId),P=h(m.destinoId);if(v&&P&&v.lat&&v.lon&&P.lat&&P.lon){const $=m.tipoLinha==="tracejada"||((k=m.estilo)==null?void 0:k.tipoLinha)==="tracejada",T=((_=m.estilo)==null?void 0:_.cor)||((L=m.estilo)==null?void 0:L.color)||n.estilo.corPrimaria||"#00f5a0",B=((N=m.estilo)==null?void 0:N.espessura)||((q=m.estilo)==null?void 0:q.weight)||l,E=y.polyline([[v.lat,v.lon],[P.lat,P.lon]],{color:T,weight:B,opacity:((H=m.estilo)==null?void 0:H.opacidade)??p,dashArray:$?"6, 6":n.estilo.dashArray,pane:i,interactive:d});if(d){const V=m.acoes||n.acoes||((w=n.dados)==null?void 0:w.acoes)||[],O=`${m.origemId}-${m.destinoId}`,j=g.renderPopupAcoesHtml(V,O);E.bindPopup(`
|
|
51
|
-
<div style="font-family:
|
|
52
|
-
<div style="font-weight:700; font-size:12px; margin-bottom:3px; color:#ffffff;">Conexão ${
|
|
53
|
-
<div style="font-size:11px; color:rgba(255, 255, 255, 0.65);">Tipo: ${
|
|
54
|
-
${
|
|
50
|
+
`))}finally{u.style.cursor=""}}function Li(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=De(d.lng,l),m=De(h.lng,l),f=qe(d.lat,l),g=qe(h.lat,l);for(let b=u;b<=m&&r<c;b++)for(let w=f;w<=g&&r<c;w++){const C=`https://${s[(b+w)%s.length]}.google.com/vt/lyrs=s,h&x=${b}&y=${w}&z=${l}`,E=new Image;E.src=C,r++}}}function De(n,t){return Math.floor((n+180)/360*Math.pow(2,t))}function qe(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 ho{constructor(t){p(this,"map",null);p(this,"configManager",Nt.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){Li(this.map,t)}async consultarSigef(t){this.map&&await Si(this.map,t,this.apiBaseUrl,this.sigefState)}}function Ne(n){if(!n)return!1;const t=n;return t.tagName==="INPUT"||t.tagName==="TEXTAREA"||t.tagName==="SELECT"||t.isContentEditable===!0}function Pe(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 Ne(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 Ne(e)}const uo=["verticesPane","perimetroPane","overlayPane","markerPane","pane-vertices","pane-perimetro","pane-vizinhos","pane-homologados","pane-homologados-pontos"];class Mi{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){uo.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,E,P,v,x,k,z,S;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 A=t.target;if(A&&((C=A.classList)!=null&&C.contains("leaflet-container")||A.id==="mapa-triagem"||(E=A.closest)!=null&&E.call(A,".leaflet-pane"))){const I=((P=A.closest)==null?void 0:P.call(A,".custom-leaflet-marker"))||((v=A.closest)==null?void 0:v.call(A,".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";(k=(x=this.ctx).selecionarFeicoesNaCaixa)==null||k.call(x,d,h,t.ctrlKey||t.metaKey);const u=((z=this.ctx.mapaController)==null?void 0:z.getMarkers())||[],m=((S=this.ctx.mapaController)==null?void 0:S.getVizinhosMarkers())||[],f=[],g=[],b=!this.ctx.layerManager||this.ctx.layerManager.isLayerActiveAndSelectable("vertices"),w=!this.ctx.layerManager||this.ctx.layerManager.isLayerActiveAndSelectable("vizinhos");return b&&u.forEach(A=>{const I=A.pontoId;if(!I)return;const _=this.map.latLngToContainerPoint(A.getLatLng());_.x>=d.x1&&_.x<=d.x2&&_.y>=d.y1&&_.y<=d.y2&&f.push(I)}),w&&m.forEach(A=>{const I=A.pontoId;if(!I)return;const _=this.map.latLngToContainerPoint(A.getLatLng());_.x>=d.x1&&_.x<=d.x2&&_.y>=d.y1&&_.y<=d.y2&&g.push(I)}),t.ctrlKey||t.metaKey?(f.forEach(A=>{this.ctx.selectedPontoIds.includes(A)?this.ctx.selectedPontoIds=this.ctx.selectedPontoIds.filter(I=>I!==A):this.ctx.selectedPontoIds.push(A)}),g.forEach(A=>{this.ctx.selectedVizinhoPontoIds.includes(A)?this.ctx.selectedVizinhoPontoIds=this.ctx.selectedVizinhoPontoIds.filter(I=>I!==A):this.ctx.selectedVizinhoPontoIds.push(A)})):(this.ctx.selectedPontoIds=f,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 ce(n){return`pane-${n}`}const po=["poligono","linha","ponto","texto"];function fo(n,t){return`${ce(n)}-${t}`}function it(n,t,e){const o=n.getPane(ce(t))??n.createPane(ce(t)),i=fo(t,e);if(!n.getPane(i)){const a=n.createPane(i,o);a.style.zIndex=String((po.indexOf(e)+1)*100)}return i}const Oe="ui-canvas-hit-test-estilo",It=6,mo=4,wi=4,At={poligono:1,linha:2,ponto:3,texto:3};function go(n){var i;const t=n.getRootNode(),e=t instanceof ShadowRoot?t:document.head;if((i=e.querySelector)!=null&&i.call(e,`#${Oe}`))return;const o=document.createElement("style");o.id=Oe,o.textContent=".leaflet-pane > canvas { pointer-events: none !important; }",e.appendChild(o)}function Zt(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 Ai(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 ki(n){const t=n._pxBounds;return t?(t.max.x-t.min.x)*(t.max.y-t.min.y):0}function Ei(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"?mo:Zt(n,It);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=Ai(n._parts,t,s);return e==="linha"?r<=Zt(n,It)?r:null:s&&((i=n._containsPoint)!=null&&i.call(n,t))?0:r<=Zt(n,It)?r:null}return(a=n._containsPoint)!=null&&a.call(n,t)?0:null}function zi(n){const t=[];for(let e=n._drawFirst;e;e=e.next)t.push(e.layer);return t}function Ce(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 po){const c=o[fo(s.id,r)];if(c)for(const l of zi(c).reverse()){const d=Ei(l,e,r);d!==null&&a.push({camada:s,tipo:r,alvo:l,distancia:d,area:ki(l)})}}return a.sort((s,r)=>At[s.tipo]!==At[r.tipo]?At[r.tipo]-At[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 le=new WeakMap;function Ii(n,t,e){const o=e.map(s=>y.Util.stamp(s.alvo)),i=le.get(n);let a=0;return i&&Math.hypot(i.x-t.x,i.y-t.y)<=wi&&i.ids.length===o.length&&i.ids.every((s,r)=>s===o[r])&&(a=(i.indice+1)%e.length),le.set(n,{x:t.x,y:t.y,ids:o,indice:a}),e[a]}function vo(n,t,e){const o=n.mouseEventToLayerPoint(e),i=Ce(n,t,o);return i.length===0?(le.delete(n),!1):(Ii(n,o,i).alvo.fire(e.type,{originalEvent:e,latlng:n.mouseEventToLatLng(e),layerPoint:o,containerPoint:n.mouseEventToContainerPoint(e)},!0),!0)}function _i(n,t,e){return Ce(n,t,n.mouseEventToLayerPoint(e))[0]??null}class yo{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")||vo(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(Pe(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 Mi(this.map,this.mapContainer,this.ctx),go(this.mapContainer),this.mapContainer.addEventListener("click",this.handleClick),this.mapContainer.addEventListener("mousedown",this.handleMouseDown),this.mapContainer.addEventListener("mousemove",this.handleMouseMove),window.addEventListener("mouseup",this.handleMouseUp),this.mapContainer.addEventListener("contextmenu",this.handleContextMenu),window.addEventListener("keydown",this.handleKeyDown),this.mapContainer.addEventListener("touchstart",this.handleTouchStart,{passive:!1}),this.mapContainer.addEventListener("touchmove",this.handleTouchMove,{passive:!1}),this.mapContainer.addEventListener("touchend",this.handleTouchEnd),this.mapContainer.addEventListener("touchcancel",this.handleTouchEnd)))}desativar(){this.mapContainer&&(this.mapContainer.removeEventListener("click",this.handleClick),this.mapContainer.removeEventListener("mousedown",this.handleMouseDown),this.mapContainer.removeEventListener("mousemove",this.handleMouseMove),this.mapContainer.removeEventListener("contextmenu",this.handleContextMenu),this.mapContainer.removeEventListener("touchstart",this.handleTouchStart),this.mapContainer.removeEventListener("touchmove",this.handleTouchMove),this.mapContainer.removeEventListener("touchend",this.handleTouchEnd),this.mapContainer.removeEventListener("touchcancel",this.handleTouchEnd)),window.removeEventListener("mouseup",this.handleMouseUp),window.removeEventListener("keydown",this.handleKeyDown),this.cancelarSupressaoClique(),this.selecaoBox&&(this.selecaoBox.destruir(),this.selecaoBox=null),this.map&&(this.map.dragging.enable(),this.map.doubleClickZoom.enable())}suprimirProximoClique(){this.cancelarSupressaoClique(),this.removerSupressao=()=>window.removeEventListener("click",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 xo{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 bo{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 Po(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 ct(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 Fe(n,t,e,o,i){var f,g,b,w,M,C,E,P;const a=n.id==="homologados",s=((f=n.dados)==null?void 0:f.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=((b=n.dados)==null?void 0:b.pontos)||(a?o.bancoPontos||[]:o.pontos)||[],l=Po(n,e,o),d=n.opacidade!==void 0?n.opacidade:1,h=n.interativo&&!n.bloqueada,u=[];c.forEach(v=>{const x=L.parseCoordenada(v.lat??v.latitude??v.y,v.lon??v.lng??v.longitude??v.x);x&&u.push({...v,lat:x.lat,lon:x.lon})});const m=v=>{const x=u.find(k=>String(k.id)===String(v));if(x)return x;if(o.pontos){const k=o.pontos.find(z=>String(z.id)===String(v));if(k){const z=L.parseCoordenada(k.lat,k.lon);if(z)return{...k,lat:z.lat,lon:z.lon}}}return null};if(s&&Array.isArray(s)){s.forEach(v=>{var z,S,A,I,_,O,T;const x=m(v.origemId),k=m(v.destinoId);if(x&&k&&x.lat&&x.lon&&k.lat&&k.lon){const U=v.tipoLinha==="tracejada"||((z=v.estilo)==null?void 0:z.tipoLinha)==="tracejada",$=((S=v.estilo)==null?void 0:S.cor)||((A=v.estilo)==null?void 0:A.color)||n.estilo.corPrimaria||"#00f5a0",N=((I=v.estilo)==null?void 0:I.espessura)||((_=v.estilo)==null?void 0:_.weight)||l,D=[[x.lat,x.lon],[k.lat,k.lon]],R=U?"6, 6":n.estilo.dashArray;ct(t,D,N,i,R);const q=y.polyline(D,{color:$,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}`,Y=L.renderPopupAcoesHtml(B,V);q.bindPopup(`
|
|
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 ${L.escapeHtml(String(v.origemId))} ↔ ${L.escapeHtml(String(v.destinoId))}</div>
|
|
53
|
+
<div style="font-size:11px; color:rgba(255, 255, 255, 0.65);">Tipo: ${L.escapeHtml(v.tipoLinha||"contínua")}</div>
|
|
54
|
+
${Y}
|
|
55
55
|
</div>
|
|
56
|
-
`,{className:"compact-popup",maxWidth:220}),
|
|
57
|
-
<div style="font-family:
|
|
58
|
-
<div style="font-weight:700; font-size:12px; margin-bottom:3px; color:#ffffff;">Polilinha: Grupo ${
|
|
59
|
-
<div style="font-size:11px; color:rgba(255, 255, 255, 0.65);">Vértices: ${
|
|
56
|
+
`,{className:"compact-popup",maxWidth:220}),q.on("popupopen",nt=>{if(o.modoSequencial){q.closePopup();return}L.bindPopupAcoesEvents(nt.popup,v,o,q)})}q.addTo(t)}});return}if((w=n.dados)!=null&&w.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,x=L.agruparPontosPorChave(u,v),k=((E=n.dados)==null?void 0:E.fechar)!==!1,z=n.estilo.corPrimaria||"#00f5a0";Object.entries(x).forEach(([S,A])=>{const I=L.ordenarPontosPorSequencia(A);if(I.length<2)return;const _=I.map(T=>[T.lat,T.lon]);ct(t,_,l,i,n.estilo.dashArray);const O=y.polyline(_,{color:z,weight:l,opacity:d,dashArray:n.estilo.dashArray,pane:i,interactive:h});if(h&&O.bindPopup(`
|
|
57
|
+
<div style="font-family:sans-serif; color:rgba(255, 255, 255, 0.9); line-height:1.3;">
|
|
58
|
+
<div style="font-weight:700; font-size:12px; margin-bottom:3px; color:#ffffff;">Polilinha: Grupo ${L.escapeHtml(S)}</div>
|
|
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}),
|
|
62
|
-
<div style="font-family:
|
|
63
|
-
<div style="font-weight:700; font-size:12px; margin-bottom:3px; color:#ffffff;">${
|
|
64
|
-
<div style="font-size:11px; color:rgba(255, 255, 255, 0.65);">Limite: ${
|
|
65
|
-
${
|
|
61
|
+
`,{className:"compact-popup",maxWidth:220}),O.addTo(t),k&&_.length>=3){const T=_[_.length-1],U=_[0],$=[T,U];ct(t,$,l,i,"4, 4"),y.polyline($,{color:z,weight:l,opacity:d,dashArray:"4, 4",pane:i,interactive:h}).addTo(t)}});return}if(!a&&r&&r.length>0)r.forEach(v=>{var z;const x=u.find(S=>String(S.id)===String(v.ponto_inicio_id)),k=u.find(S=>String(S.id)===String(v.ponto_fim_id));if(x&&k&&x.lat&&x.lon&&k.lat&&k.lon){const S=v.tipo_limite_sigef||v.tipo_limite||"",A=v.metodo_posicionamento_sigef||v.metodo_posicionamento||"",I=S==="LA1"?"#10b981":S==="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,U=[[x.lat,x.lon],[k.lat,k.lon]],$=O?l+3:l,N=S==="LN1"?"6, 6":n.estilo.dashArray;ct(t,U,O?$+2:$,i,N);const D=y.polyline(U,{color:T,weight:$,opacity:O?1:d,dashArray:N,pane:i,interactive:h});if(D.segmentoId=_,D.segmento=v,h){D.on("click",V=>{V&&V.originalEvent&&V.originalEvent.stopPropagation(),o.onSegmentoClick&&o.onSegmentoClick(_,v,{lat:(x.lat+k.lat)/2,lon:(x.lon+k.lon)/2})});const R=v.acoes||n.acoes||((z=n.dados)==null?void 0:z.acoes)||[],q=`${v.ponto_inicio_id}-${v.ponto_fim_id}`,B=L.renderPopupAcoesHtml(R,q);D.bindPopup(`
|
|
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;">${L.escapeHtml(x.nome_vertice)} ↔ ${L.escapeHtml(k.nome_vertice)}</div>
|
|
64
|
+
<div style="font-size:11px; color:rgba(255, 255, 255, 0.65);">Limite: ${L.escapeHtml(S||"N/A")} · ${L.escapeHtml(A||"N/A")}</div>
|
|
65
|
+
${B}
|
|
66
66
|
</div>
|
|
67
|
-
`,{className:"compact-popup",maxWidth:220}),
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
<div style="width:${b}px; height:${b}px; background-color:#ffffff; border-radius:50%; box-shadow:0 0 2px rgba(0,0,0,0.8);"></div>
|
|
75
|
-
</div>
|
|
76
|
-
</div>
|
|
77
|
-
`}case"diamond":return`
|
|
78
|
-
<div id="${i}" class="${h}" style="${f}">
|
|
79
|
-
<svg width="${l+2}" height="${l+2}" viewBox="0 0 12 12" fill="none" xmlns="http://www.w3.org/2000/svg" style="overflow:visible; ${a?`filter: drop-shadow(0 0 3px #ffffff) drop-shadow(0 0 6px ${c});`:"filter: drop-shadow(0 1px 2px rgba(0,0,0,0.7));"}">
|
|
80
|
-
<polygon points="6,1 11,6 6,11 1,6" fill="${c}" stroke="#000000" stroke-width="1.2" stroke-linejoin="round" />
|
|
81
|
-
${a?'<polygon points="6,2.5 9.5,6 6,9.5 2.5,6" fill="none" stroke="#ffffff" stroke-width="1" />':""}
|
|
82
|
-
</svg>
|
|
83
|
-
</div>
|
|
84
|
-
`;case"cross":return`
|
|
85
|
-
<div id="${i}" class="${h}" style="${f}">
|
|
86
|
-
<svg width="${l+4}" height="${l+4}" viewBox="0 0 12 12" fill="none" xmlns="http://www.w3.org/2000/svg" style="overflow:visible; ${a?`filter: drop-shadow(0 0 3px #ffffff) drop-shadow(0 0 6px ${c});`:"filter: drop-shadow(0 1px 2px rgba(0,0,0,0.7));"}">
|
|
87
|
-
${a?'<circle cx="6" cy="6" r="5.5" stroke="#ffffff" stroke-width="1.2" stroke-dasharray="2 2" fill="none" />':""}
|
|
88
|
-
<!-- Halo escuro de contraste para satélite -->
|
|
89
|
-
<line x1="6" y1="1" x2="6" y2="11" stroke="#000000" stroke-width="3" stroke-linecap="round" />
|
|
90
|
-
<line x1="1" y1="6" x2="11" y2="6" stroke="#000000" stroke-width="3" stroke-linecap="round" />
|
|
91
|
-
<!-- Traço colorido do marcador -->
|
|
92
|
-
<line x1="6" y1="1" x2="6" y2="11" stroke="${c}" stroke-width="${a?"2.2":"1.6"}" stroke-linecap="round" />
|
|
93
|
-
<line x1="1" y1="6" x2="11" y2="6" stroke="${c}" stroke-width="${a?"2.2":"1.6"}" stroke-linecap="round" />
|
|
94
|
-
</svg>
|
|
95
|
-
</div>
|
|
96
|
-
`;case"x":return`
|
|
97
|
-
<div id="${i}" class="${h}" style="${f}">
|
|
98
|
-
<svg width="${l+4}" height="${l+4}" viewBox="0 0 12 12" fill="none" xmlns="http://www.w3.org/2000/svg" style="overflow:visible; ${a?`filter: drop-shadow(0 0 3px #ffffff) drop-shadow(0 0 6px ${c});`:"filter: drop-shadow(0 1px 2px rgba(0,0,0,0.7));"}">
|
|
99
|
-
${a?'<circle cx="6" cy="6" r="5.5" stroke="#ffffff" stroke-width="1.2" stroke-dasharray="2 2" fill="none" />':""}
|
|
100
|
-
<!-- Halo escuro de contraste para satélite -->
|
|
101
|
-
<line x1="2" y1="2" x2="10" y2="10" stroke="#000000" stroke-width="3" stroke-linecap="round" />
|
|
102
|
-
<line x1="10" y1="2" x2="2" y2="10" stroke="#000000" stroke-width="3" stroke-linecap="round" />
|
|
103
|
-
<!-- Traço colorido do marcador -->
|
|
104
|
-
<line x1="2" y1="2" x2="10" y2="10" stroke="${c}" stroke-width="${a?"2.2":"1.6"}" stroke-linecap="round" />
|
|
105
|
-
<line x1="10" y1="2" x2="2" y2="10" stroke="${c}" stroke-width="${a?"2.2":"1.6"}" stroke-linecap="round" />
|
|
106
|
-
</svg>
|
|
107
|
-
</div>
|
|
108
|
-
`;case"triangle":return`
|
|
109
|
-
<div id="${i}" class="${h}" style="${f}">
|
|
110
|
-
<svg width="${l+2}" height="${l+2}" viewBox="0 0 12 12" fill="none" xmlns="http://www.w3.org/2000/svg" style="overflow:visible; ${a?`filter: drop-shadow(0 0 3px #ffffff) drop-shadow(0 0 6px ${c});`:"filter: drop-shadow(0 1px 2px rgba(0,0,0,0.7));"}">
|
|
111
|
-
<polygon points="6,1.5 11,10.5 1,10.5" fill="${c}" stroke="#000000" stroke-width="1.2" stroke-linejoin="round" />
|
|
112
|
-
${a?'<polygon points="6,3.5 9.5,9.5 2.5,9.5" fill="none" stroke="#ffffff" stroke-width="1" />':""}
|
|
113
|
-
</svg>
|
|
114
|
-
</div>
|
|
115
|
-
`;case"circle":default:return`
|
|
116
|
-
<div id="${i}" class="${h}" style="${f}">
|
|
117
|
-
<div style="width:${l}px; height:${l}px; background-color:${c}; border-radius:50%; border:1px solid rgba(0,0,0,0.35); box-sizing:border-box; ${p}"></div>
|
|
118
|
-
</div>
|
|
119
|
-
`}}class gt{constructor(){u(this,"zoomListenerMap",new WeakMap)}render(t,e,o){const i=y.layerGroup(),s=`pane-${t.id}`;this.rebuildPoints(t,i,e,o,s);const a=()=>{t.estilo.scaleMode==="world"&&i.eachLayer(c=>{if(c.setIcon&&c.baseSize&&c.shapeStyle&&c.markerBg&&c.pontoId!==void 0){const r=this.calculateSize(t,e,o,c.baseSize),l=o.config.enableAnimations?"transition-all duration-150":"",p=W(c.shapeStyle,r,c.markerBg,l,`map-marker-${t.id}-${c.pontoId}`,!!c.isSelected),d=y.divIcon({html:p,className:"custom-leaflet-marker flex items-center justify-center",iconSize:[r+6,r+6]});c.setIcon(d)}})};return e.on("zoomend",a),this.zoomListenerMap.set(i,a),i}calculateSize(t,e,o,i){const s=o.graphicScale.markerScaleMultiplier||1;if(t.estilo.scaleMode==="world"){const a=t.estilo.dimensaoMetros||.25,c=e.getCenter(),r=e.getZoom(),l=40075016686e-3*Math.abs(Math.cos(c.lat*Math.PI/180))/Math.pow(2,r+8),p=a/(l>0?l:1);return Math.max(3,Math.round(p*s))}return Math.max(4,Math.round(i*s))}rebuildPoints(t,e,o,i,s){var f;const c=t.id==="homologados-pontos"?i.bancoPontos||[]:((f=t.dados)==null?void 0:f.pontos)||i.pontos||[],r=t.interativo&&!t.bloqueada,l=t.id==="vizinhos",p=t.id==="homologados"||t.id==="homologados-pontos",d=i.selectedPontoIds||[];c.forEach(h=>{var x;const b=h.lat??h.latitude,S=h.lon??h.lng??h.longitude;if(b!==void 0&&S!==void 0&&b!==0&&S!==0&&!isNaN(Number(b))&&!isNaN(Number(S))){const M=h.tipo_ponto==="B"||h.tipo==="B",I=h.tipo_ponto==="M"||h.tipo==="M";let z=t.estilo.estiloMarcador||"x",A=t.estilo.corPrimaria||"bg-mint-vibrant",C=t.estilo.tamanhoMarcador||7;p?(z="circle",A=t.estilo.corPrimaria||"#f59e0b",C=8):l?(z=I?"circle-dot":t.estilo.estiloMarcador||"cross",A=t.estilo.corPrimaria||"#a855f7",C=I?10:8):I?(A="#6366f1",z="circle-dot",C=10):M&&(A="#f43f5e",z="square",C=9);const m=!!(h.selecionado||d.length>0&&(d.includes(h.id)||d.includes(String(h.id))||d.includes(Number(h.id)))),v=this.calculateSize(t,o,i,C),P=i.config.enableAnimations?"transition-all duration-150":"",k=W(z,v,A,P,`map-marker-${t.id}-${h.id}`,m),_=y.divIcon({html:k,className:`custom-leaflet-marker flex items-center justify-center ${m?"cad-marker-selected":""}`,iconSize:[v+6,v+6]}),L=y.marker([Number(b),Number(S)],{icon:_,pane:s,interactive:r});if(m&&L.setZIndexOffset(2e3),L.pontoId=h.id,L.layerId=t.id,L.isVizinho=l,L.baseSize=C,L.shapeStyle=z,L.markerBg=A,L.isSelected=m,r){const N=p?"Vértice Homologado SIGEF":l?"Confrontante (Importado)":I?"Base Homologada PPP":M?"Base de Campo (Translação)":"Vértice de Perímetro",q=h.acoes||t.acoes||((x=t.dados)==null?void 0:x.acoes)||[],H=g.renderPopupAcoesHtml(q,h.id);L.bindPopup(`
|
|
67
|
+
`,{className:"compact-popup",maxWidth:220}),D.on("popupopen",V=>{if(o.modoSequencial){D.closePopup();return}L.bindPopupAcoesEvents(V.popup,v,o,D)})}D.addTo(t)}});else if(u&&u.length>=2){const v=u.filter(A=>A.lat&&A.lon&&A.tipo_ponto!=="B"&&A.tipo!=="B"&&A.ignorar_poligono!==1),x=((P=n.dados)==null?void 0:P.chaveGrupo)||o.chaveGrupo,k=L.agruparPontosPorChave(v,x),z=n.estilo.corPrimaria||(a?"#f59e0b":"#10b981"),S=n.estilo.dashArray||(a?"6, 8":void 0);Object.values(k).forEach(A=>{const I=L.ordenarPontosPorSequencia(A);if(I.length<2)return;const _=I.map(T=>[T.lat,T.lon]);if(ct(t,_,l,i,S),y.polyline(_,{color:z,weight:l,opacity:d,dashArray:S,pane:i,interactive:h}).addTo(t),_.length>=3){const T=_[_.length-1],U=_[0],$=a?"6, 8":"4, 4",N=[T,U];ct(t,N,l,i,$),y.polyline(N,{color:z,weight:l,opacity:d,dashArray:$,pane:i,interactive:h}).addTo(t)}})}}class Co{constructor(){p(this,"zoomListenerMap",new WeakMap)}render(t,e,o){const i=y.layerGroup(),a=it(e,t.id,"linha");Fe(t,i,e,o,a);const s=()=>{if(t.estilo.scaleMode==="world"){const r=Po(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(),Fe(t,e,a,i,it(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 Ot=300;function Ft(n){return n>Ot?"compacta":"normal"}function Se(n,t){if(n<=Ot)return 1;const e=Math.max(.7,1-.3*Math.log10(n/Ot)),o=t>=18?1:t>=16?.92:t>=14?.82:.72;return Math.max(.6,e*o)}function So(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 Re(n){return n.replace(/[&<>"']/g,t=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[t])}const Yt={diamond:"6,0.8 11.2,6 6,11.2 0.8,6",triangle:"6,1 11.4,10.6 0.6,10.6"},Kt={cross:["M6 1.2V10.8","M1.2 6H10.8"],x:["M2 2L10 10","M10 2L2 10"]};function Pt(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=Re(So(e)),d=t+6,h=r?`color-mix(in srgb, ${l} 38%, #000000)`:l,u=r?1:c?.72:.9,m=r?"rgba(255,255,255,0.95)":c?"rgba(0,0,0,0.55)":"rgba(0,0,0,0.7)",f=r?1.3:c?.8:1,g=r?"rgba(255,255,255,0.9)":"rgba(0,0,0,0.6)",b=(x,k,z,S="")=>`class="${x}" stroke="${k}" stroke-width="${z}" vector-effect="non-scaling-stroke" ${S}`,w=n in Yt?`<polygon points="${Yt[n]}" style="fill:${h}" fill-opacity="${u}" stroke-linejoin="round" ${b("cad-pt-contorno",m,f)} />`:n in Kt?Kt[n].map(x=>`<path d="${x}" fill="none" stroke-linecap="round" ${b("cad-pt-halo",g,c?2.6:3.4)} /><path d="${x}" fill="none" stroke-linecap="round" ${b("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}" ${b("cad-pt-contorno",m,f)} />`:`<circle cx="6" cy="6" r="5.2" style="fill:${h}" fill-opacity="${u}" ${b("cad-pt-contorno",m,f)} />`,M=!c&&!r&&!(n in Kt)?n in Yt?"":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" />':"",E=`cad-pt ${c?"cad-pt-compacto":""} ${e} ${o} ${r?"ponto-selecionado":""}`.replace(/\s+/g," ").trim(),P=t;return`
|
|
68
|
+
<div ${i?`id="${Re(i)}"`:""} class="${E}" style="display:flex; align-items:center; justify-content:center; width:${d}px; height:${d}px; position:relative; pointer-events:auto; background:none !important;">
|
|
69
|
+
<svg width="${P}" height="${P}" viewBox="0 0 12 12" xmlns="http://www.w3.org/2000/svg" style="overflow:visible; display:block;">
|
|
70
|
+
${w}${M}${C}
|
|
71
|
+
</svg>
|
|
72
|
+
</div>
|
|
73
|
+
`}class Lo{constructor(){p(this,"zoomListenerMap",new WeakMap)}render(t,e,o){const i=y.layerGroup(),a=it(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"&&Ft(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=Pt(o,i,a,l,`map-marker-${t.id}-${s}`,r,{densidade:Ft(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=Se(a,e.getZoom());return Math.max(r<1?5:4,Math.round(i*s*r))}rebuildPoints(t,e,o,i,a){var m;const r=t.id==="homologados-pontos"?i.bancoPontos||[]:((m=t.dados)==null?void 0:m.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(f=>{var w;const g=f.lat??f.latitude,b=f.lon??f.lng??f.longitude;if(g!==void 0&&b!==void 0&&g!==0&&b!==0&&!isNaN(Number(g))&&!isNaN(Number(b))){const M=f.tipo_ponto==="B"||f.tipo==="B",C=f.tipo_ponto==="M"||f.tipo==="M";let E=t.estilo.estiloMarcador||"x",P=t.estilo.corPrimaria||"bg-mint-vibrant",v=t.estilo.tamanhoMarcador||7;d?(E="circle",P=t.estilo.corPrimaria||"#f59e0b",v=8):l?(E=C?"circle-dot":t.estilo.estiloMarcador||"cross",P=t.estilo.corPrimaria||"#a855f7",v=C?10:8):C?(P="#6366f1",E="circle-dot",v=10):M&&(P="#f43f5e",E="square",v=9);const x=!!(f.selecionado||h.length>0&&(h.includes(f.id)||h.includes(String(f.id))||h.includes(Number(f.id)))),k=this.calculateSize(t,o,i,v,u),z=this.criarIcone(t,i,E,k,P,f.id,x,u),S=y.marker([Number(g),Number(b)],{icon:z,pane:a,interactive:c});if(x&&S.setZIndexOffset(2e3),S.pontoId=f.id,S.layerId=t.id,S.isVizinho=l,S.baseSize=v,S.shapeStyle=E,S.markerBg=P,S.isSelected=x,S.densTotal=u,S.tamanhoPx=k,c){const A=d?"Vértice Homologado SIGEF":l?"Confrontante (Importado)":C?"Base Homologada PPP":M?"Base de Campo (Translação)":"Vértice de Perímetro",I=f.acoes||t.acoes||((w=t.dados)==null?void 0:w.acoes)||[],_=L.renderPopupAcoesHtml(I,f.id);S.bindPopup(`
|
|
120
74
|
<div style="font-family:var(--ui-fonte-base, sans-serif); color:rgba(255, 255, 255, 0.9); line-height:1.3;">
|
|
121
|
-
<div style="font-weight:700; font-size:13px; margin-bottom:4px; color:#ffffff;">${
|
|
122
|
-
<div style="font-size:11px; color:rgba(255, 255, 255, 0.65);">${
|
|
123
|
-
<div style="font-size:11px; color:rgba(255, 255, 255, 0.45); font-family:var(--ui-fonte-codigo, monospace); margin-top:4px;">Lat ${Number(
|
|
124
|
-
${
|
|
75
|
+
<div style="font-weight:700; font-size:13px; margin-bottom:4px; color:#ffffff;">${L.escapeHtml(f.nome_vertice||String(f.id))}</div>
|
|
76
|
+
<div style="font-size:11px; color:rgba(255, 255, 255, 0.65);">${L.escapeHtml(A)} · ${L.escapeHtml(f.tipo_ponto||f.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(b).toFixed(6)}</div>
|
|
78
|
+
${_}
|
|
125
79
|
</div>
|
|
126
|
-
`,{className:"compact-popup",maxWidth:240}),
|
|
80
|
+
`,{className:"compact-popup",maxWidth:240}),I&&I.length>0&&S.on("popupopen",O=>{L.bindPopupAcoesEvents(O.popup,f,i,S)}),S.on("click",()=>{i.onMarkerClick&&i.onMarkerClick(f.id,l,f,{lat:Number(g),lon:Number(b)})})}S.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,it(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 Mo{render(t,e,o){const i=y.layerGroup();return this.rebuildPolygons(t,i,o,e),i}rebuildPolygons(t,e,o,i){var m,f;const a=it(i,t.id,"poligono"),s=it(i,t.id,"ponto"),c=(((m=t.dados)==null?void 0:m.poligonos)??(Array.isArray(t.dados)?t.dados:null))||((f=t.dados)==null?void 0:f.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 x,k,z,S,A,I,_,O,T,U;if(!g)return;const b=((x=g.estilo)==null?void 0:x.cor)||((k=g.estilo)==null?void 0:k.color)||d,w=((z=g.estilo)==null?void 0:z.espessura)||((S=g.estilo)==null?void 0:S.weight)||h,M=((A=g.estilo)==null?void 0:A.opacidade)??u,C=((I=g.estilo)==null?void 0:I.fillColor)||b,E=((_=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 $=Array.isArray(g.coordenadas[0])&&Array.isArray(g.coordenadas[0][0]);let N;if($?N=g.coordenadas.map(D=>D.map(R=>{const q=L.parseCoordenada(R[0],R[1]);return q?[q.lat,q.lon]:null}).filter(Boolean)):N=g.coordenadas.map(D=>{const R=L.parseCoordenada(D[0],D[1]);return R?[R.lat,R.lon]:null}).filter(Boolean),N&&($?((T=N[0])==null?void 0:T.length)>=3:N.length>=3)){const D=y.polygon(N,{color:b,weight:w,opacity:M,dashArray:P,fillColor:C,fillOpacity:E,lineJoin:"round",pane:a,interactive:l});if(D.poligonoId=g.id,D.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>${L.escapeHtml(q)}:</strong> ${L.escapeHtml(String(B))}</div>`).join("")),D.bindPopup(`
|
|
127
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;">
|
|
128
|
-
<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 ${
|
|
129
|
-
${
|
|
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 ${L.escapeHtml(String(g.id??""))}</div>
|
|
83
|
+
${R||`<div style="font-size:11px;">Área vetorial definida por ${g.coordenadas.length} vértices</div>`}
|
|
130
84
|
</div>
|
|
131
|
-
`,{className:"compact-popup",maxWidth:220}),
|
|
85
|
+
`,{className:"compact-popup",maxWidth:220}),D.on("popupopen",()=>{o.modoSequencial&&D.closePopup()})}D.addTo(e);return}}const v=g.wkt||g.poligono_wkt;if(v){const $=[...v.matchAll(/\(([^()]+)\)/g)];if($.length>0){const N=L.escapeHtml(g.nome_propriedade||`Polígono ${String(g.id||"")}`),D=L.escapeHtml(g.nome||"Proprietário"),R=[];if($.forEach(q=>{const B=q[1].split(",").map(V=>{const Y=V.trim().split(/\s+/);if(Y.length<2)return null;const nt=L.parseCoordenada(Y[1],Y[0]);return nt?[nt.lat,nt.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:b,weight:w,opacity:M,dashArray:P,fillColor:C,fillOpacity:E,lineJoin:"round",pane:a,interactive:l});if(B.poligonoId=g.id,B.layerId=t.id,l){const V=g.acoes||t.acoes||((U=t.dados)==null?void 0:U.acoes)||[],Y=L.renderPopupAcoesHtml(V,g.id);B.bindPopup(`
|
|
132
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;">
|
|
133
|
-
<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;">${
|
|
134
|
-
<div style="font-size:11px; margin-bottom:2px;"><strong>Identificador:</strong> ${
|
|
135
|
-
${
|
|
136
|
-
${
|
|
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> ${L.escapeHtml(String(g.id??""))}</div>
|
|
89
|
+
${g.nome?`<div style="font-size:11px;"><strong>Proprietário:</strong> ${D}</div>`:""}
|
|
90
|
+
${Y}
|
|
137
91
|
</div>
|
|
138
|
-
`,{className:"compact-popup",maxWidth:220}),
|
|
92
|
+
`,{className:"compact-popup",maxWidth:220}),B.on("popupopen",nt=>{if(o.modoSequencial){B.closePopup();return}L.bindPopupAcoesEvents(nt.popup,g,o,B)})}B.addTo(e)}}}g.pontos&&g.pontos.length>0&&g.pontos.forEach($=>{var D;const N=L.parseCoordenada($.lat??$.latitude??$.y,$.lon??$.lng??$.longitude??$.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=$.id,q.isVizinho=!0,q.layerId=t.id,l){const B=$.acoes||g.acoes||t.acoes||((D=t.dados)==null?void 0:D.acoes)||[],V=L.renderPopupAcoesHtml(B,$.id);q.bindPopup(`
|
|
139
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;">
|
|
140
|
-
<div style="font-weight:700; font-size:12px; color:#c084fc; margin-bottom:3px;">${
|
|
141
|
-
<div style="font-size:11px; color:rgba(255, 255, 255, 0.65);">Confrontante: ${
|
|
142
|
-
<div style="font-size:10px; color:rgba(255, 255, 255, 0.45); font-family:var(--ui-fonte-codigo, monospace); margin-top:3px;">Lat ${
|
|
143
|
-
${
|
|
94
|
+
<div style="font-weight:700; font-size:12px; color:#c084fc; margin-bottom:3px;">${L.escapeHtml($.nome_vertice||String($.id))}</div>
|
|
95
|
+
<div style="font-size:11px; color:rgba(255, 255, 255, 0.65);">Confrontante: ${L.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
|
+
${V}
|
|
144
98
|
</div>
|
|
145
|
-
`,{className:"compact-popup",maxWidth:220}),E.on("click",()=>{o.modoSequencial&&E.closePopup(),o.onMarkerClick&&o.onMarkerClick(w.id,!0,w,{lat:$.lat,lon:$.lon})}),E.on("popupopen",j=>{if(o.modoSequencial){E.closePopup();return}g.bindPopupAcoesEvents(j.popup,w,o,E)})}E.addTo(e)}})})}update(t,e,o,i){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,`pane-${t.id}`))}destroy(t,e){t.clearLayers(),e.hasLayer(t)&&e.removeLayer(t)}}class vt{constructor(){u(this,"moveListenerMap",new WeakMap)}render(t,e,o){const i=y.layerGroup(),s=`pane-${t.id}`,a=()=>{if(i.clearLayers(),!t.visivel)return;if(e.getZoom()>20){const r=e.getBounds(),l=r.getSouth(),p=r.getNorth(),d=r.getWest(),f=r.getEast(),h=e.getCenter(),b=8999e-9,S=Math.cos(h.lat*Math.PI/180),x=b/(S>.1?S:1),M=Math.floor((p-l)/b),I=Math.floor((f-d)/x);if(M<200&&I<200){const z=Math.ceil(l/b)*b;for(let C=z;C<=p;C+=b)y.polyline([[C,d],[C,f]],{color:t.estilo.corPrimaria||"rgba(0, 245, 160, 0.18)",weight:t.estilo.espessuraLinha||.6,interactive:!1,pane:s}).addTo(i);const A=Math.ceil(d/x)*x;for(let C=A;C<=f;C+=x)y.polyline([[l,C],[p,C]],{color:t.estilo.corPrimaria||"rgba(0, 245, 160, 0.18)",weight:t.estilo.espessuraLinha||.6,interactive:!1,pane:s}).addTo(i)}}};return a(),e.on("zoomend moveend",a),this.moveListenerMap.set(i,a),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 _t(){G.register("tile",new dt),G.register("wms",new pt),G.register("vetorial-linhas",new ft),G.register("vetorial-pontos",new gt),G.register("vetorial-poligonos",new mt),G.register("grid",new vt)}_t();const yt=[{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:2,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:450,interativo:!0,bloqueada:!1,estilo:{corPrimaria:"#00f5a0",espessuraLinha:2,scaleMode:"screen",dimensaoMetros:.3}},{id:"vizinhos",nome:"Imóveis Confrontantes (WKT/CSV)",categoria:"referencia",tipo:"vetorial-poligonos",visivel:!0,opacidade:.8,zIndex:500,interativo:!0,bloqueada:!1,estilo:{corPrimaria:"#a855f7",espessuraLinha:1.5,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"}}];function $t(n){return n.map(t=>({id:t.id,visivel:t.visivel,opacidade:t.opacidade,zIndex:t.zIndex,bloqueada:t.bloqueada,estilo:{...t.estilo}}))}function qt(n,t){!t||!Array.isArray(t)||t.forEach(e=>{const o=n.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}))})}function Tt(n,t,e,o,i){n.dados=t;const s=i.get(n.id);if(s&&e&&o){const a=G.get(n.tipo);a&&a.update(n,s,{dados:t},o,e)}else if(e&&o&&n.visivel){const a=G.get(n.tipo);if(a){const c=a.render(n,e,o);c&&(c.addTo(e),i.set(n.id,c))}}}function F(n){return`pane-${n}`}function J(n){return n.visivel&&n.interativo&&!n.bloqueada?"auto":"none"}function Bt(n,t){t.forEach(e=>{const o=F(e.id),i=n.getPane(o)??n.createPane(o);i&&(i.style.zIndex=String(e.zIndex),i.style.pointerEvents=J(e))})}function Nt(n,t){const e=n.getPane(F(t.id));e&&(e.style.display=t.visivel?"":"none",e.style.pointerEvents=J(t))}function Ht(n,t){const e=n.getPane(F(t.id));e&&(e.style.opacity=String(t.opacidade))}function Vt(n,t){const e=n.getPane(F(t.id));e&&(e.style.zIndex=String(t.zIndex))}function Gt(n,t){const e=n.getPane(F(t.id));e&&(e.style.pointerEvents=J(t))}function ot(n,t,e,o){const i=G.get(n.tipo);if(!i)return;const s=i.render(n,t,e);s&&(s.addTo(t),o.set(n.id,s))}function Y(n,t,e){const o=e.get(n.id);if(!o)return;const i=G.get(n.tipo);i&&i.destroy(o,t),e.delete(n.id)}function it(n,t,e,o,i){const s=i.get(n.id);if(!s)return;const a=G.get(n.tipo);a&&a.update(n,s,t,o,e)}class bt{constructor(t){u(this,"layers",[]);u(this,"layerInstances",new Map);u(this,"map",null);u(this,"context",null);u(this,"listeners",[]);this.layers=(t||yt).map(e=>({...e,estilo:{...e.estilo}}))}attachMap(t,e){this.map=t,this.context=e,this.ensurePanes(),this.renderAllLayers()}ensurePanes(){this.map&&Bt(this.map,this.layers)}renderAllLayers(){!this.map||!this.context||(this.layers.forEach(t=>{Y(t,this.map,this.layerInstances),t.visivel&&ot(t,this.map,this.context,this.layerInstances)}),this.notifyChange())}setLayerVisibility(t,e){const o=this.layers.find(i=>i.id===t);!o||o.visivel===e||(o.visivel=e,!(!this.map||!this.context)&&(Nt(this.map,o),e?this.layerInstances.has(t)||ot(o,this.map,this.context,this.layerInstances):Y(o,this.map,this.layerInstances),this.notifyChange()))}setLayerOpacity(t,e){const o=this.layers.find(i=>i.id===t);o&&(o.opacidade=Math.max(0,Math.min(1,e)),this.map&&(Ht(this.map,o),this.context&&it(o,{opacidade:o.opacidade},this.map,this.context,this.layerInstances)),this.notifyChange())}setLayerZIndex(t,e){const o=this.layers.find(i=>i.id===t);o&&(o.zIndex=e,this.map&&Vt(this.map,o),this.notifyChange())}setLayerBlocked(t,e){const o=this.layers.find(i=>i.id===t);o&&(o.bloqueada=e,this.map&&Gt(this.map,o),this.notifyChange())}setLayerScaleMode(t,e){const o=this.layers.find(i=>i.id===t);o&&(o.estilo.scaleMode=e,this.map&&this.context&&it(o,{estilo:o.estilo},this.map,this.context,this.layerInstances),this.notifyChange())}setGraphicScale(t){this.context&&(this.context.graphicScale={...this.context.graphicScale,...t},this.renderAllLayers())}updateContext(t){this.context&&(this.context={...this.context,...t},this.renderAllLayers())}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 $t(this.layers)}importState(t){!t||!Array.isArray(t)||(qt(this.layers,t),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 Array.from(this.layerInstances.values())}getLayerInstance(t){return 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(s=>s.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){const o=this.layers.find(i=>i.id===t);o&&(Tt(o,e,this.map,this.context,this.layerInstances),this.notifyChange())}clearLayers(t){(t&&t.length>0?t:Array.from(this.layerInstances.keys())).forEach(o=>{const i=this.layers.find(s=>s.id===o);i?Y(i,this.map,this.layerInstances):this.layerInstances.delete(o)}),this.notifyChange()}destroy(){this.map&&(this.layers.forEach(t=>Y(t,this.map,this.layerInstances)),this.layerInstances.clear()),this.listeners=[]}}function xt(n,t){var a,c;if(t==null)return null;const e=String(t).trim(),o=r=>r?(r.lon=r.lng,r):null,s=n.getMarkers().find(r=>{var h,b,S,x;const l=r.pontoId,p=r.elementoId??r.id??((h=r.options)==null?void 0:h.pontoId)??((b=r.options)==null?void 0:b.id),d=(S=r.elemento)==null?void 0:S.nome_vertice,f=(x=r.elemento)==null?void 0:x.codigo_completo;return String(l)===e||String(p)===e||d&&String(d).toLowerCase()===e.toLowerCase()||f&&String(f).toLowerCase()===e.toLowerCase()});if(s&&typeof s.getLatLng=="function")return o(s.getLatLng());if(n.layerManager)for(const r of n.layerManager.getAllLayerInstances()){let l=null;const p=d=>{var b,S,x,M,I;if(l)return;const f=d.pontoId??d.elementoId??d.id??((b=d.options)==null?void 0:b.id)??((S=d.options)==null?void 0:S.pontoId),h=((x=d.elemento)==null?void 0:x.nome)??((M=d.elemento)==null?void 0:M.nome_vertice)??((I=d.options)==null?void 0:I.nome);(String(f)===e||h&&String(h).toLowerCase()===e.toLowerCase())&&(typeof d.getLatLng=="function"?l=d.getLatLng():typeof d.getBounds=="function"&&(l=d.getBounds().getCenter()))};if(p(r),typeof r.eachLayer=="function"&&r.eachLayer(p),l)return o(l)}if(n.context.pontos&&n.context.pontos.length>0){const r=n.context.pontos.find(l=>String(l.id)===e||l.nome_vertice&&String(l.nome_vertice).toLowerCase()===e.toLowerCase());if(r){const l=r.lat??r.latitude??r.y,p=r.lon??r.lng??r.longitude??r.x,d=g.parseCoordenada(l,p);if(d)return o(y.latLng(d.lat,d.lon))}}if(n.context.bancoPontos&&n.context.bancoPontos.length>0){const r=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(r){const l=r.lat??r.latitude??r.y,p=r.lon??r.lng??r.longitude??r.x,d=g.parseCoordenada(l,p);if(d)return o(y.latLng(d.lat,d.lon))}}if(n.context.confrontantes&&n.context.confrontantes.length>0){const r=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(r){if(r.pontos&&r.pontos.length>0){let l=0,p=0,d=0;for(const f of r.pontos){const h=f.lat??f.latitude??f.y,b=f.lon??f.lng??f.longitude??f.x,S=g.parseCoordenada(h,b);S&&(l+=S.lat,p+=S.lon,d++)}if(d>0)return o(y.latLng(l/d,p/d))}if(r.poligono_wkt){const l=g.extrairCentroDeWkt(r.poligono_wkt);if(l)return o(y.latLng(l.lat,l.lon))}}}if(n.context.segmentos&&n.context.segmentos.length>0){const r=n.context.segmentos.find(l=>String(l.id)===e||`${l.ponto_inicio_id}-${l.ponto_fim_id}`===e);if(r){const l=(a=n.context.pontos)==null?void 0:a.find(d=>String(d.id)===String(r.ponto_inicio_id)),p=(c=n.context.pontos)==null?void 0:c.find(d=>String(d.id)===String(r.ponto_fim_id));if(l&&p){const d=g.parseCoordenada(l.lat??l.latitude,l.lon??l.longitude),f=g.parseCoordenada(p.lat??p.latitude,p.lon??p.longitude);if(d&&f)return o(y.latLng((d.lat+f.lat)/2,(d.lon+f.lon)/2))}}}if(n.layerManager){for(const r of n.layerManager.getLayers())if(r.dados){if(Array.isArray(r.dados.pontos)){const l=r.dados.pontos.find(p=>String(p.id)===e||p.nome_vertice&&String(p.nome_vertice)===e);if(l){const p=g.parseCoordenada(l.lat,l.lon);if(p)return o(y.latLng(p.lat,p.lon))}}if(Array.isArray(r.dados.poligonos)){const l=r.dados.poligonos.find(p=>String(p.id)===e);if(l){if(l.wkt){const p=g.extrairCentroDeWkt(l.wkt);if(p)return o(y.latLng(p.lat,p.lon))}if(Array.isArray(l.coordenadas)&&l.coordenadas.length>0){let p=0,d=0,f=0;for(const h of l.coordenadas){const b=g.parseCoordenada(h[0],h[1])||g.parseCoordenada(h[1],h[0]);b&&(p+=b.lat,d+=b.lon,f++)}if(f>0)return o(y.latLng(p/f,d/f))}}}}}return null}function Ot(n,t,e,o){var h,b;K(t,n.getMap());const i=n.getMap();if(!i)return;const s=xt(n,e);if(!s){console.warn(`[ui-canvas-cad] Elemento com identificador "${e}" não encontrado para destaque.`);return}const a=(o==null?void 0:o.pan)===!0,c=o==null?void 0:o.zoom;a?c!==void 0?typeof i.flyTo=="function"?i.flyTo(s,c,{animate:!0}):i.setView(s,c,{animate:!0}):typeof i.panTo=="function"?i.panTo(s,{animate:!0}):i.setView(s,i.getZoom(),{animate:!0}):c!==void 0&&i.setZoom(c,{animate:!0});const r=(o==null?void 0:o.cor)||"#00f5a0",l="pane-destaque";let p=i.getPane(l);p||(p=i.createPane(l)),p&&(p.style.zIndex="850",p.style.pointerEvents="none");const d=y.divIcon({className:"cad-destaque-marker-container",html:`
|
|
146
|
-
<div class="cad-pulse-highlight" style="--cad-pulse-cor: ${
|
|
99
|
+
`,{className:"compact-popup",maxWidth:220}),q.on("click",()=>{o.modoSequencial&&q.closePopup(),o.onMarkerClick&&o.onMarkerClick($.id,!0,$,{lat:N.lat,lon:N.lon})}),q.on("popupopen",Y=>{if(o.modoSequencial){q.closePopup();return}L.bindPopupAcoesEvents(Y.popup,$,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 wo{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(),m=e.getCenter(),f=8999e-9,g=Math.cos(m.lat*Math.PI/180),b=f/(g>.1?g:1),w=Math.floor((d-l)/f),M=Math.floor((u-h)/b);if(w<200&&M<200){const C=Math.ceil(l/f)*f;for(let P=C;P<=d;P+=f)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 E=Math.ceil(h/b)*b;for(let P=E;P<=u;P+=b)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 G(n){return n.partes&&n.partes.length>1?n.partes:[n.coordenadas]}function Ct(n){return n.tipo==="LineString"&&!!n.partes&&n.partes.length>1}function ft(n){return n.length>1?{tipo:"LineString",coordenadas:n[0],partes:n}:{tipo:"LineString",coordenadas:n[0]}}const de=63710088e-1,Q=n=>n*Math.PI/180;function st(n,t){const e=Q(t[0]-n[0]),o=Q(t[1]-n[1]),i=Math.sin(e/2)**2+Math.cos(Q(n[0]))*Math.cos(Q(t[0]))*Math.sin(o/2)**2;return 2*de*Math.asin(Math.min(1,Math.sqrt(i)))}function St(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 Be(n){const t=Q(n.reduce((i,a)=>i+a[0],0)/n.length),e=n.map(i=>[Q(i[1])*Math.cos(t)*de,Q(i[0])*de]);let o=0;for(let i=0;i<e.length;i++){const[a,s]=e[i],[r,c]=e[(i+1)%e.length];o+=a*c-r*s}return Math.abs(o)/2}function Ao(n){const[t,...e]=n;return t?Math.max(0,Be(t)-e.reduce((o,i)=>o+Be(i),0)):0}const Ti=new Intl.NumberFormat("pt-BR",{minimumFractionDigits:4,maximumFractionDigits:4}),He=new Intl.NumberFormat("pt-BR",{minimumFractionDigits:2,maximumFractionDigits:2});function rt(n){return`${Ti.format(n/1e4)} ha`}function j(n){return n>=1e3?`${He.format(n/1e3)} km`:`${He.format(n)} m`}function tt(n){return n.tipo==="Polygon"?Ao(n.aneis):n.tipo==="Circle"?Math.PI*n.raioMetros**2:null}function K(n){return n.tipo==="LineString"?G(n).reduce((t,e)=>t+St(e),0):n.tipo==="Polygon"?St(n.aneis[0]??[],!0):n.tipo==="Circle"?2*Math.PI*n.raioMetros:null}function ko(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=K(n.geometria);return a===null?"":j(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 Le(n){let t;switch(n.tipo){case"Point":case"Text":t=[n.coordenada];break;case"LineString":t=G(n).flat();break;case"Polygon":t=n.aneis.flat();break;case"Circle":{const i=n.raioMetros/111320,a=i/Math.max(.01,Math.cos(Q(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 kt=16,$i=256;function he(n){const[[t,e],[o,i]]=Le(n.geometria);return{minLon:e,minLat:t,maxLon:i,maxLat:o}}function ht(n,t){return n.minLon<=t.maxLon&&n.maxLon>=t.minLon&&n.minLat<=t.maxLat&&n.maxLat>=t.minLat}function Ve(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 Ge(n){const t=n.length,e=Math.ceil(t/kt),i=Math.ceil(Math.sqrt(e))*kt,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+=kt)s.push(c.slice(l,l+kt))}return s}function Di(n){if(n.length===0)return null;let t=Ge(n).map(e=>({...Ve(e),folhas:e}));for(;t.length>1;)t=Ge(t).map(e=>({...Ve(e),filhos:e}));return t[0]}class Eo{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,...he(e)});this.remontar()}inserir(t){this.atualizar(t)}atualizar(t){if(t.excluida){this.remover(t.id);return}const e={id:t.id,...he(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(ht(i,t))if(i.folhas)for(const a of i.folhas)!this.obsoletos.has(a.id)&&ht(a,t)&&e.push(a.id);else i.filhos&&o.push(...i.filhos)}for(const i of this.delta.values())ht(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($i,this.itens.size*.1)&&this.remontar()}remontar(){this.raiz=Di([...this.itens.values()]),this.delta.clear(),this.obsoletos.clear()}}const Rt=12,Me=40,qi=1.2;function zo(n){return n>=Rt?0:360/(256*2**n)*qi}function Ni(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 we(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=Ni(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 Io(n,t){if(t<=0||n.length<4)return n;const e=[...n,n[0]],o=we(e,t);return o.pop(),o.length>=3?o:n}function Ae(n){return n.tipo==="LineString"?G(n).reduce((t,e)=>t+e.length,0):n.tipo==="Polygon"?n.aneis.reduce((t,e)=>t+e.length,0):0}function _o(n,t){const e=zo(t);return e===0||Ae(n)<Me?n:n.tipo==="LineString"?ft(G(n).map(o=>we(o,e))):n.tipo==="Polygon"?{tipo:"Polygon",aneis:n.aneis.map(o=>Io(o,e))}:n}const Oi=new Set(["previa","prévia","preview","rascunho","draft","proposta"]);function Z(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"&&Oi.has(i.trim().toLowerCase()))return"previa";return"oficial"}function et(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 Jt=(n,t)=>`${n}\0${t}`;class Bt{constructor(){p(this,"global",!1);p(this,"individuais",new Set)}alternarIndividual(t,e){const o=Jt(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=Jt(t,e);o?this.individuais.add(i):this.individuais.delete(i)}individualAtiva(t,e){return this.individuais.has(Jt(t,e))}static oficiais(t){const e=new Set;for(const o of t)!o.excluida&&Z(o)==="oficial"&&e.add(et(o));return e}visivel(t,e){if(Z(t)==="oficial")return!0;const o=et(t);return this.global||!e.has(o)||this.individualAtiva(t.camadaId,o)}previaSolicitada(t){return this.global||this.individualAtiva(t.camadaId,et(t))}}const Lt=55,To=17,$o=8;function Ht(n,t){return t<To&&n>$o}function Do(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 Fi(n,t,e){if(!Ht(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/Lt)}:${Math.floor(c/Lt)}`,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:Do(r),membros:r});return{clusters:i,isolados:a}}class qo{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/Lt)}:${Math.floor(o/Lt)}`;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 _t={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" />'},Qt="#38bdf8",Ri=/^(#[0-9a-f]{3,8}|(rgb|hsl)a?\([0-9.,%\s\/-]+\)|[a-z]{3,20})$/i;function X(n,t){return n&&Ri.test(n.trim())?n.trim():t}const dt="#38bdf8",Bi=150,Hi=100,ue=300,je=.75,Vi=.3,te=typeof requestAnimationFrame=="function"?n=>{requestAnimationFrame(n)}:n=>{setTimeout(n,16)};class No{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 Eo,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,te(()=>{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 f;const s=this.obterEstado(e,t,o,i),r=this.feicoesDe(t),c=(f=t.dados)==null?void 0:f.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*Vi)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 m=this.selecionadas.get(t);if(m)for(const g of[...m])h.has(g)||m.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(Z(o)!=="oficial"){t.nPrevias++;continue}const i=et(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=f=>f.geometria.tipo==="Point"&&this.desenhavel(e,f),c=new Map,l=(f,g)=>{if(!f||f.excluida||Z(f)!=="oficial")return;const b=et(f);c.has(b)||c.set(b,e.oficiais.has(b));const w=(e.contOficiais.get(b)??0)+g;w<=0?(e.contOficiais.delete(b),e.oficiais.delete(b)):(e.contOficiais.set(b,w),e.oficiais.add(b))},d=[],h=[],u=f=>{const g=a.get(f);g&&(Z(g)==="previa"&&e.nPrevias--,l(g,-1),r(g)&&e.nPontos--,a.delete(f),e.indice.remover(f),s==null||s.delete(f),h.push(f))};for(const f of i.removidas)u(f);for(const f of i.mudadas){if(f.excluida){u(f.id);continue}const g=a.get(f.id);Z(f)==="previa"&&e.nPrevias++,g&&(Z(g)==="previa"&&e.nPrevias--,l(g,-1),r(g)&&e.nPontos--),a.set(f.id,f),e.indice.atualizar(f),l(f,1),r(f)&&e.nPontos++,d.push(f.id)}let m=!1;if(e.nPrevias>0)for(const[f,g]of c)g!==e.oficiais.has(f)&&(m=!0);return e.listaSincronizada=o,e.revisao++,m&&e.revisaoBase++,this.reconciliarParcial(t,e,d,h,m),!0}ressimplificar(t,e){return t.zoomDesenho===e||Ae(t.feicao.geometria)<Me?!1:e<Rt||t.zoomDesenho<Rt}paraDesenho(t,e){const o=_o(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(!Ht(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 qo(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 w;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>ue?a.getBounds().pad(je):null,u=h?this.caixaDe(h):null;e.culling=h!==null;const m=u?e.indice.consultar(u):r.keys(),f=new Set(m);if(c)for(const M of c)r.has(M)&&f.add(M);for(const M of[...f]){const C=r.get(M);C&&!this.desenhavel(e,C)&&f.delete(M)}const g=new Map,b=l?this.agrupadorAtivo(e,d):null;if(b||(e.agrupador=null),b){for(const C of[...f])b.emCluster(C)&&f.delete(C);const M=new Map;if(c)for(const C of c){const E=b.chaveDoPonto(C),P=E===void 0||(w=b.celula(E))==null?void 0:w.membros.get(C);if(E!==void 0&&P){const v=M.get(E);v?v.push(P):M.set(E,[P])}}for(const[C,E]of b.celulasAgrupadas()){const P=M.get(C);if(P)for(const k of P)f.add(k.id);const v=E.membros.size,x=v-((P==null?void 0:P.length)??0);if(x===1)for(const k of E.membros.values()){if(c!=null&&c.has(k.id))continue;const z=e.indice.caixaDe(k.id);(!u||z&&ht(z,u))&&f.add(k.id);break}if(!(h&&!h.contains([E.somaLat/v,E.somaLon/v]))&&x>=2){let k=E.somaLat,z=E.somaLon;if(P)for(const A of P)k-=A.coordenada[0],z-=A.coordenada[1];const S=[k/x,z/x];g.set(C,{coordenada:S,total:v,assinatura:`${C}:${v}:${x}:${S[0].toFixed(7)}:${S[1].toFixed(7)}`})}}}for(const M of f){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()])f.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>ue,u=l&&Ht(e.nPontos,d),m=e.agrupador;if(a||h!==e.culling||u!==(m!==null)||m!==null&&(m.zoom!==d||e.agrupadorRev!==e.revisaoBase)){this.reconciliar(t,e,!1,new Set(o));return}const f=this.selecionadas.get(r),g=v=>this.desenhavel(e,v),b=h?s.getBounds().pad(je):null,w=b?this.caixaDe(b):null,M=(v,x)=>{const k=c.get(v);if(!k||!g(k)){this.tirarEntrada(t,e,v);return}const z=!!(f!=null&&f.has(v));if(!z&&w){const S=e.indice.caixaDe(v);if(!S||!ht(S,w)){this.tirarEntrada(t,e,v);return}}this.materializar(t,e,k,d,z,x)},C=new Set,E=[];for(const v of i){this.tirarEntrada(t,e,v);const x=m==null?void 0:m.remover(v);x!==void 0&&C.add(x)}for(const v of o){const x=c.get(v);if(!x)continue;const k=m==null?void 0:m.remover(v);k!==void 0&&C.add(k),m&&x.geometria.tipo==="Point"&&g(x)?C.add(m.inserir({id:v,coordenada:x.geometria.coordenada})):E.push(v)}for(const v of E)M(v,!0);if(!m)return;const P=new Set(o);for(const v of C){const x=m.celula(v);if(!x||x.membros.size<2){if(this.tirarCluster(t,e,v),x)for(const T of x.membros.keys())M(T,P.has(T));continue}const k=x.membros.size;let z=x.somaLat,S=x.somaLon,A=0;for(const T of x.membros.values())f!=null&&f.has(T.id)&&(A++,z-=T.coordenada[0],S-=T.coordenada[1]);const I=k-A;for(const T of x.membros.values())f!=null&&f.has(T.id)||I===1?M(T.id,P.has(T.id)):this.tirarEntrada(t,e,T.id);const _=[x.somaLat/k,x.somaLon/k];if(b&&!b.contains(_)||I<2){this.tirarCluster(t,e,v);continue}const O=[z/I,S/I];this.colocarCluster(t,e,v,{coordenada:O,total:k,assinatura:`${v}:${k}:${I}:${O[0].toFixed(7)}:${O[1].toFixed(7)}`})}}criarMarcadorCluster(t,e,o,i){const a=e<10?30:e<100?38:46,s=X(i.layerDef.estilo.corPrimaria,Qt),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:it(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<=Bi)s.forEach(c);else{const h=!!o.map._loaded?o.map.getBounds():null,u=b=>{var M;const w=(M=r.get(b))==null?void 0:M.layer;return h?w!=null&&w.getBounds?h.intersects(w.getBounds()):w!=null&&w.getLatLng?h.contains(w.getLatLng()):!0:!0},m=s.filter(u),f=s.filter(b=>!u(b));m.forEach(c);const g=()=>{this.tokenLote.get(t)===l&&(f.splice(0,Hi).forEach(c),f.length>0&&te(g))};f.length>0&&te(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&&_t[t.estilo.icone]?t.estilo.icone:""}`: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=X(a.corTraco??e.estilo.corPrimaria,Qt),r=t.geometria.tipo==="Polygon"||t.geometria.tipo==="Circle",c=t.geometria.tipo==="Point",l=c&&X(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?dt:l,stroke:!(d===0&&!i),weight:i?h+2:h,dashArray:a.dashArray??(Z(t)==="previa"?"6 4":e.estilo.dashArray),fill:r||t.geometria.tipo==="Point",fillColor:X(a.corPreenchimento,s),fillOpacity:i?Math.min(1,u+.18):u,lineJoin:"round",interactive:o}}criar(t,e,o,i,a){var l,d;const s=it(o,e.id,this.paneDe(t)),r=t.geometria,c=this.estiloVetor(t,e,i,a);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?G(r):r.coordenadas,{...c,pane:s});case"Point":{const h=(l=t.estilo)==null?void 0:l.icone;return h&&_t[h]?y.marker(r.coordenada,{icon:this.iconeSvg(t,e,a),pane:s,interactive:i}):y.circleMarker(r.coordenada,{...c,radius:(((d=t.estilo)==null?void 0:d.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);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?G(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?dt:X(i.corTraco??i.corPreenchimento??e.estilo.corPrimaria,Qt),c=Number.isFinite(i.rotacaoIcone)?i.rotacaoIcone:0,l=_t[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 ${dt})`:""}">${l}</svg>`})}iconeTexto(t,e,o=!1){const i=t.estilo??{},a=t.geometria.tipo==="Text"?t.geometria.texto:"",s=o?dt:X(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=X(i.corFundo,"");if(d){const u=X(i.corBorda,""),m=typeof i.opacidadeFundo=="number"&&Number.isFinite(i.opacidadeFundo)?Math.min(1,Math.max(0,i.opacidadeFundo)):.85,f=typeof i.raioBorda=="number"&&Number.isFinite(i.raioBorda)?Math.min(50,Math.max(0,i.raioBorda)):4,g=o?`1px solid ${dt}`: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:${f}px;border:${g}"><span style="position:absolute;top:0;right:0;bottom:0;left:0;border-radius:inherit;background:${d};opacity:${m}"></span><span style="position:relative">${L.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}">${L.escapeHtml(a)}</span>`})}aplicarRotulo(t,e){const o=e.estilo;if(!(o!=null&&o.mostrarRotulo)||e.geometria.tipo==="Text"){t.unbindTooltip();return}const i=ko(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 xo);F.register("wms",new bo);F.register("vetorial-linhas",new Co);F.register("vetorial-pontos",new Lo);F.register("vetorial-poligonos",new Mo);F.register("grid",new wo);F.register("feicoes",new No);const pe=[{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"}}],Gi=new Set(["tile","wms","grid"]);class Oo{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||pe).map(e=>({...e,estilo:{...e.estilo}}))}descartarCamadasPadrao(){if(this.map)return;const t=new Set(pe.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&&Gi.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 Fo(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 m,f,g,b;const l=c.pontoId,d=c.elementoId??c.id??((m=c.options)==null?void 0:m.pontoId)??((f=c.options)==null?void 0:f.id),h=(g=c.elemento)==null?void 0:g.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(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 f,g,b,w,M;if(l)return;const u=h.pontoId??h.elementoId??h.id??((f=h.options)==null?void 0:f.id)??((g=h.options)==null?void 0:g.pontoId),m=((b=h.elemento)==null?void 0:b.nome)??((w=h.elemento)==null?void 0:w.nome_vertice)??((M=h.options)==null?void 0:M.nome);(String(u)===e||m&&String(m).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=L.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=L.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 m=u.lat??u.latitude??u.y,f=u.lon??u.lng??u.longitude??u.x,g=L.parseCoordenada(m,f);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=L.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=L.parseCoordenada(l.lat??l.latitude,l.lon??l.longitude),u=L.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=L.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=L.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 m of l.coordenadas){const f=L.parseCoordenada(m[0],m[1])||L.parseCoordenada(m[1],m[0]);f&&(d+=f.lat,h+=f.lon,u++)}if(u>0)return o(y.latLng(d/u,h/u))}}}}}return null}function ji(n,t,e,o){var m,f;fe(t,n.getMap());const i=n.getMap();if(!i)return;const a=Fo(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
|
+
<div class="cad-pulse-highlight" style="--cad-pulse-cor: ${L.escapeHtml(c)};">
|
|
147
101
|
<div class="cad-pulse-core"></div>
|
|
148
102
|
<div class="cad-pulse-ring ring-1"></div>
|
|
149
103
|
<div class="cad-pulse-ring ring-2"></div>
|
|
150
104
|
</div>
|
|
151
|
-
`,iconSize:[52,52],iconAnchor:[26,26]});t.destaqueMarker=y.marker(s,{icon:d,pane:l,interactive:!1,keyboard:!1}),t.destaqueMarker.addTo(i);const f=(b=(h=t.destaqueMarker).getElement)==null?void 0:b.call(h);f&&(f.style.pointerEvents="none"),o!=null&&o.duracaoMs&&o.duracaoMs>0&&(t.destaqueTimeoutId=window.setTimeout(()=>{K(t,i)},o.duracaoMs))}function K(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 jt(n,t){const e=new Map;n.forEach(i=>{const s=i.lat??i.latitude??i.y,a=i.lon??i.lng??i.longitude??i.x,c=g.parseCoordenada(s,a);c&&(i.lat=c.lat,i.lon=c.lon);const r=i.confrontante_id??i.id_confrontante??0;e.has(r)||e.set(r,[]),e.get(r).push(i)});const o=new Map;return t.forEach(i=>{const s=i.id!==void 0&&i.id!==null?i.id:0;o.set(s,{...i,pontos:[]})}),e.forEach((i,s)=>{var a,c;if(o.has(s)){const r=o.get(s);r.pontos=i}else o.set(s,{id:s,nome:((a=i[0])==null?void 0:a.nome_confrontante)||"Confrontante",nome_propriedade:((c=i[0])==null?void 0:c.nome_propriedade)||"",pontos:i})}),Array.from(o.values()).filter(i=>i.pontos&&i.pontos.length>0||!!i.poligono_wkt)}function Dt(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 Rt(n,t,e=!1){let o=[...n];e&&t&&t.forEach(s=>{s.pontos&&o.push(...s.pontos)});const i=o.map(s=>{const a=s.lat??s.latitude??s.y,c=s.lon??s.lng??s.longitude??s.x,r=g.parseCoordenada(a,c);return r?y.latLng(r.lat,r.lon):null}).filter(s=>s!==null);return i.length===1?{single:i[0]}:i.length>1?{bounds:y.latLngBounds(i)}:null}function Wt(n,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 Ft(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=s=>{const a=i.find(c=>String(c.id)===String(s))||{id:s,lat:0,lon:0};o(a)})),n.layerManager.setLayerData(e,{pontos:i,onClique:o}),n.layerManager.setLayerVisibility(e,!0)}function Yt(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 Ut(n,t,e=!0,o="polilinha",i){const s=t||[];n.layerManager.getOrCreateLayer(o,"vetorial-linhas","Polilinhas"),(o==="polilinha"||o==="perimetro")&&(n.context.pontos=s,n.context.segmentos=[],n.canvasInteracao.ctx.pontosList=s);const a=i||n.chaveGrupo||n.context.chaveGrupo;n.layerManager.setLayerData(o,{pontos:s,fechar:e!==!1,polilinhaSequencial:!0,chaveGrupo:a}),n.layerManager.setLayerVisibility(o,!0)}function Zt(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 Xt(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 Kt(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 nt(n){return n!=null&&!isNaN(Number(n))&&String(n).trim()!==""?Number(n):n}function Jt(n,t){var a,c;const e=n.core.map,o=n.layerManager.getLayerDef(t.layerId),i=t.baseSize||8,s=((a=n.context.graphicScale)==null?void 0:a.markerScaleMultiplier)||1;if(e&&((c=o==null?void 0:o.estilo)==null?void 0:c.scaleMode)==="world"){const r=o.estilo.dimensaoMetros||.25,l=e.getCenter(),p=e.getZoom(),d=40075016686e-3*Math.abs(Math.cos(l.lat*Math.PI/180))/Math.pow(2,p+8),f=r/(d>0?d:1);return Math.max(3,Math.round(f*s))}return Math.max(4,Math.round(i*s))}function Qt(n,t,e,o,i){const s=Jt(n,e),a=n.context.config.enableAnimations?"transition-all duration-150":"",c=W(e.shapeStyle,s,e.markerBg,a,`map-marker-${e.layerId||"pts"}-${o}`,i);t.setIcon(y.divIcon({html:c,className:`custom-leaflet-marker flex items-center justify-center ${i?"cad-marker-selected ponto-selecionado":""}`,iconSize:[s+6,s+6]}))}function te(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 s=i,a=s.pontoId;if(a==null)continue;const c=o.has(String(a));if(s.isSelected===c)continue;s.isSelected=c,i.setZIndexOffset(c?2e3:0),s.shapeStyle&&s.baseSize&&s.markerBg&&Qt(n,i,s,a,c);const r=i.getElement();r&&(c?r.classList.add("cad-marker-selected","ponto-selecionado"):r.classList.remove("cad-marker-selected","ponto-selecionado"))}}class Z{constructor(t){u(this,"core");u(this,"layerManager");u(this,"canvasInteracao");u(this,"context");u(this,"modoCliqueSequencialAtivo",!1);u(this,"chaveGrupo");u(this,"zonaProjecao",22);u(this,"levantamentoId",null);u(this,"customMarkerClickCallback");u(this,"customPopupActionCallback");u(this,"destaqueState",{destaqueMarker:null,destaqueTimeoutId:null});this.core=new rt(this),this.layerManager=new bt(t),this.canvasInteracao=new ct({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=nt(e);if(this.customMarkerClickCallback)try{this.customMarkerClickCallback(i,o)}catch(s){console.error("Erro no customMarkerClickCallback:",s)}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(s){console.error("Erro no customPopupActionCallback:",s)}}}}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){Ft(this,t,e,o)}plotarConexoes(t,e="linhas"){Yt(this,t,e)}plotarPolilinhaSequencial(t,e=!0,o="polilinha",i){Ut(this,t,e,o,i)}plotarPoligonos(t,e="poligonos"){Zt(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=s=>{s instanceof y.Marker&&e.push(s)};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){Xt(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=jt(t||[],this.context.confrontantes||[]);this.setConfrontantes(e),this.layerManager.setLayerVisibility("vizinhos",!0)}plotPoligonosVizinhos(t){const e=Dt(t||[],this.context.confrontantes||[]);this.setConfrontantes(e),this.layerManager.setLayerVisibility("vizinhos",!0)}clearOverlays(t=!1){Kt(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(a=>String(a.pontoId)===o);if(i){const a=e!==void 0?e:this.core.map.getZoom();this.core.map.setView(i.getLatLng(),a),i.openPopup()}const s=nt(t);this.canvasInteracao.ctx.selectedPontoIds=[s],this.canvasInteracao.ctx.lastSelectedPontoId=s,this.context.selectedPontoIds=[s],this.atualizarDestaqueMarcadores()}atualizarDestaqueMarcadores(){te(this)}fitBounds(t,e=[40,40],o=!1){if(!this.core.map)return;const i=Rt(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 Wt(this.core.map,this.layerManager)}getVizinhosMarkers(){return this.getMarkers().filter(t=>!!t.isVizinho)}get destaqueAtivo(){return this.destaqueState.destaqueMarker!==null}localizarCoordenadasElemento(t){return xt(this,t)}destacarElemento(t,e){Ot(this,this.destaqueState,t,e)}limparDestaque(){K(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 Pt(n,t,e,o){if(!n)return;if(n.querySelectorAll(".layer-item").length===t.length){t.forEach(s=>{var c,r;const a=n.querySelector(`.layer-item[data-layer-id="${s.id}"]`);if(a){const l=a.querySelector(".layer-chk-visibility");l&&l.checked!==s.visivel&&(l.checked=s.visivel);const p=a.querySelector(".layer-opacity-slider"),d=a.querySelector(".opacity-percent-label"),f=Math.round(s.opacidade*100);p&&parseInt(p.value,10)!==f&&(p.value=String(f)),d&&(d.textContent=`${f}%`);const h=a.querySelector(".btn-lock-layer");h&&(h.classList.toggle("active",!!s.bloqueada),h.title=s.bloqueada?"Desbloquear Camada":"Bloquear Camada");const b=a.querySelector(".btn-toggle-scale-mode");b&&((c=s.estilo)!=null&&c.scaleMode)&&(b.textContent=((r=s.estilo)==null?void 0:r.scaleMode)==="world"?"Métrico":"Tela")}});return}n.innerHTML=`
|
|
152
|
-
${t.map(
|
|
153
|
-
<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=(f=(m=t.destaqueMarker).getElement)==null?void 0:f.call(m);u&&(u.style.pointerEvents="none"),o!=null&&o.duracaoMs&&o.duracaoMs>0&&(t.destaqueTimeoutId=window.setTimeout(()=>{fe(t,i)},o.duracaoMs))}function fe(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 Ui(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=L.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 Wi(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 Xi(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=L.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 Zi(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 Yi(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 Ki(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 Ji(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 Qi(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 tn(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 en(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 Ue(n){return n!=null&&!isNaN(Number(n))&&String(n).trim()!==""?Number(n):n}function on(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),m=l/(u>0?u:1);return Math.max(3,Math.round(m*a))}const s=Se(t.densTotal||0,(e==null?void 0:e.getZoom())??18);return Math.max(s<1?5:4,Math.round(i*a*s))}function nn(n,t,e,o,i){const a=on(n,e),s=n.context.config.enableAnimations?"cad-pt-anim":"",r=Pt(e.shapeStyle,a,e.markerBg,s,`map-marker-${e.layerId||"pts"}-${o}`,i,{densidade:Ft(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 an(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&&nn(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 Xt{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 ho(this),this.layerManager=new Oo(t),this.canvasInteracao=new yo({mapaController:this,layerManager:this.layerManager}),this.context={pontos:[],segmentos:[],bancoPontos:[],confrontantes:[],zonaProjecao:22,config:this.core.config,graphicScale:{markerScaleMultiplier:1,lineScaleMultiplier:1,scaleModeGlobal:"screen"},onMarkerClick:(e,o)=>{if(this.modoCliqueSequencialAtivo||this.context.modoSequencial)return;const i=Ue(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){Yi(this,t,e,o)}plotarConexoes(t,e="linhas"){Ki(this,t,e)}plotarPolilinhaSequencial(t,e=!0,o="polilinha",i){Ji(this,t,e,o,i)}plotarPoligonos(t,e="poligonos"){Qi(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){tn(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=Ui(t||[],this.context.confrontantes||[]);this.setConfrontantes(e),this.layerManager.setLayerVisibility("vizinhos",!0)}plotPoligonosVizinhos(t){const e=Wi(t||[],this.context.confrontantes||[]);this.setConfrontantes(e),this.layerManager.setLayerVisibility("vizinhos",!0)}clearOverlays(t=!1){en(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=Ue(t);this.canvasInteracao.ctx.selectedPontoIds=[a],this.canvasInteracao.ctx.lastSelectedPontoId=a,this.context.selectedPontoIds=[a],this.atualizarDestaqueMarcadores()}atualizarDestaqueMarcadores(){an(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=Xi(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 Zi(this.core.map,this.layerManager)}getVizinhosMarkers(){return this.getMarkers().filter(t=>!!t.isVizinho)}get destaqueAtivo(){return this.destaqueState.destaqueMarker!==null}localizarCoordenadasElemento(t){return Fo(this,t)}destacarElemento(t,e){ji(this,this.destaqueState,t,e)}limparDestaque(){fe(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 Ro(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 m=s.querySelector(".btn-lock-layer");m&&(m.classList.toggle("active",!!a.bloqueada),m.title=a.bloqueada?"Desbloquear Camada":"Bloquear Camada");const f=s.querySelector(".btn-toggle-scale-mode");f&&((r=a.estilo)!=null&&r.scaleMode)&&(f.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}">
|
|
154
108
|
<div class="layer-item-row">
|
|
155
109
|
<label class="layer-item-label">
|
|
156
|
-
<input type="checkbox" class="layer-chk-visibility" data-layer-id="${
|
|
157
|
-
<span>${
|
|
110
|
+
<input type="checkbox" class="layer-chk-visibility" data-layer-id="${a.id}" ${a.visivel?"checked":""} />
|
|
111
|
+
<span>${a.nome}</span>
|
|
158
112
|
</label>
|
|
159
113
|
<div class="layer-item-actions">
|
|
160
|
-
<button class="btn-layer-action btn-lock-layer ${
|
|
161
|
-
${
|
|
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>'}
|
|
162
116
|
</button>
|
|
163
|
-
${(a
|
|
164
|
-
<span class="scale-mode-pill btn-toggle-scale-mode" data-layer-id="${
|
|
165
|
-
${((
|
|
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"}
|
|
166
120
|
</span>
|
|
167
121
|
`:""}
|
|
168
122
|
</div>
|
|
169
123
|
</div>
|
|
170
124
|
<div class="layer-controls-row">
|
|
171
125
|
<span>Opacidade</span>
|
|
172
|
-
<input type="range" min="0" max="100" value="${Math.round(
|
|
173
|
-
<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>
|
|
174
128
|
</div>
|
|
175
129
|
</div>
|
|
176
130
|
`}).join("")}
|
|
177
|
-
`,e.cleanup(),n.querySelectorAll(".layer-chk-visibility").forEach(s=>{e.add(s,"change",a=>{const c=a.target.getAttribute("data-layer-id"),r=a.target.checked;c&&o.setLayerVisibility(c,r)})}),n.querySelectorAll(".layer-opacity-slider").forEach(s=>{e.add(s,"input",a=>{const c=a.target.getAttribute("data-layer-id"),r=parseInt(a.target.value,10),l=r/100,p=a.target.closest(".layer-item"),d=p==null?void 0:p.querySelector(".opacity-percent-label");d&&(d.textContent=`${r}%`),c&&o.setLayerOpacity(c,l)})}),n.querySelectorAll(".btn-lock-layer").forEach(s=>{e.add(s,"click",a=>{const c=a.currentTarget.getAttribute("data-layer-id");if(c){const r=t.find(l=>l.id===c);r&&o.setLayerBlocked(c,!r.bloqueada)}})}),n.querySelectorAll(".btn-toggle-scale-mode").forEach(s=>{e.add(s,"click",a=>{var r;const c=a.currentTarget.getAttribute("data-layer-id");if(c){const l=t.find(p=>p.id===c);if(l){const p=((r=l.estilo)==null?void 0:r.scaleMode)==="world"?"screen":"world";o.setLayerScaleMode(c,p)}}})})}function Ct(n,t,e,o){var x,M,I,z,A,C;if(n.modoSequencial||n.controller.canvasInteracao.selectionHappened||n.controller.canvasInteracao.panHappened||n.mouseMovedSinceDown)return!1;const i=(t==null?void 0:t.originalEvent)||t,s=typeof(i==null?void 0:i.composedPath)=="function"?i.composedPath():[],a=s.length>0?s[0]:(i==null?void 0:i.target)||(t==null?void 0:t.target);if(a){const m='.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=a.matches)==null?void 0:x.call(a,m))||((M=a.closest)==null?void 0:M.call(a,m)))return!1}const c=n.controller.getMap();if(!c||!n.mapContainer)return!1;let r,l;if(o)r=Math.round(o.x),l=Math.round(o.y);else if(t!=null&&t.containerPoint||t!=null&&t.layerPoint)r=Math.round(((I=t.containerPoint)==null?void 0:I.x)??((z=t.layerPoint)==null?void 0:z.x)??0),l=Math.round(((A=t.containerPoint)==null?void 0:A.y)??((C=t.layerPoint)==null?void 0:C.y)??0);else{const m=n.mapContainer.getBoundingClientRect(),v=(i==null?void 0:i.clientX)??0,P=(i==null?void 0:i.clientY)??0;r=Math.round(v-m.left),l=Math.round(P-m.top)}const p={x:r,y:l};let d,f;const h=e||(t==null?void 0:t.latlng);if(h&&typeof h.lat=="number")d=h.lat,f=h.lng??h.lon??0;else{const m=c.containerPointToLatLng(y.point(p.x,p.y));d=m.lat,f=m.lng}const b=n.controller.layerManager?n.controller.layerManager.getLayers().filter(m=>m.visivel).map(m=>m.id):[],S=i;return n.host.dispatchEvent(new CustomEvent("ui-canvas-clique",{detail:{coordenadas:{lat:d,lng:f},pontoPixel:p,eventoOriginal:S,lat:d,lon:f,lng:f,camadasAtivas:b},bubbles:!0,composed:!0})),!0}function wt(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 St(n,t,e,o,i,s,a){let c=o||n.obterElementoPorId(t),r=i;if(!r&&c){const l=c.lat??c.latitude??0,p=c.lon??c.lng??c.longitude??0;r={lat:Number(l),lon:Number(p)}}if(r||(r={lat:0,lon:0}),n.modoSequencial){n.fecharPopup(),n.host.dispatchEvent(new CustomEvent("ui-clique-sequencial",{detail:{id:t,elemento:c??{id:t,lat:r.lat,lon:r.lon},coordenadas:r},bubbles:!0,composed:!0}));return}if(a)try{const l=t!=null&&!isNaN(Number(t))&&String(t).trim()!==""?Number(t):t;a(l,e)}catch(l){console.error("Erro no callback de clique de marcador:",l)}if(s)try{s(t,e,c,r)}catch(l){console.error("Erro no handler anterior de marker click:",l)}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:c,tipo:e?"vizinho":"vertice",coordenadas:r},bubbles:!0,composed:!0}))}function Mt(n,t){let e=null,o=null,i=0,s=0;function a(){var p;try{if(!n.isConnected)return;const d=t.getMap();if(!d)return;const f=(p=d.getContainer)==null?void 0:p.call(d);if(!f||!f.parentNode)return;t.invalidateSize()}catch{}}function c(p=25){o!==null&&(window.clearTimeout(o),o=null),o=window.setTimeout(()=>{o=null,a()},p)}function r(){l(),!(typeof ResizeObserver>"u")&&(e=new ResizeObserver(p=>{for(const d of p){let f=0,h=0;d.contentRect?(f=d.contentRect.width,h=d.contentRect.height):d.borderBoxSize&&d.borderBoxSize.length>0?(f=d.borderBoxSize[0].inlineSize,h=d.borderBoxSize[0].blockSize):(f=n.clientWidth||n.offsetWidth,h=n.clientHeight||n.offsetHeight),f>0&&h>0&&(Math.abs(f-i)>=.5||Math.abs(h-s)>=.5)&&(i=f,s=h,c(25))}}),e.observe(n))}function l(){e&&(e.disconnect(),e=null),o!==null&&(window.clearTimeout(o),o=null)}return{observe:r,disconnect:l,invalidateSizeSafely:a}}class ee{constructor(t){u(this,"canal",null);u(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 s=this.contexto.controller.getMap();if(s){const a=s.getContainer();a&&(a.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,s])=>{const a=parseFloat(s);isNaN(a)||this.contexto.setLayerOpacity(i,a)}),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 oe{constructor(t){u(this,"contexto");u(this,"uiListeners",new st.ListenerBag);u(this,"isLayersPanelOpen",!1);u(this,"mouseMovedSinceDown",!1);u(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");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,a;(a=(s=this.contexto).onZoomExtents)==null||a.call(s)}),this.uiListeners.add(i,"click",()=>{var s,a;(a=(s=this.contexto).onLimparSelecao)==null||a.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 a,c;s.button===0&&(this.mouseMovedSinceDown||(c=(a=this.contexto).onTratarCliqueCanvas)==null||c.call(a,s))})),this.uiListeners.add(this.contexto.shadow,"click",s=>{var r,l,p;const a=s.composedPath?s.composedPath()[0]:s.target,c=(r=a==null?void 0:a.closest)==null?void 0:r.call(a,".ui-popup-btn");if(c){s.preventDefault(),s.stopPropagation();const d=c.getAttribute("data-acao-id"),f=c.getAttribute("data-elemento-id");d&&f!==null&&((p=(l=this.contexto).onDispararAcaoPopup)==null||p.call(l,d,f))}})}limpar(){this.uiListeners.cleanup()}}class ie{constructor(t){u(this,"contexto");u(this,"_pontos",[]);u(this,"_segmentos",[]);u(this,"_bancoPontos",[]);u(this,"_confrontantes",[]);u(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 s=t||[];(o==="polilinha"||o==="perimetro")&&(this._pontos=s,this._segmentos=[]);const a=i??this.contexto.obterChaveGrupo();this.contexto.obterController().plotarPolilinhaSequencial(s,e,o,a)}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 ne=':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}.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{filter:brightness(1.25);transform:scale(1.15);transition:transform .15s ease}.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:14px;height:14px;border-radius:50%;background-color:var(--cad-pulse-cor, #00f5a0);box-shadow:0 0 10px var(--cad-pulse-cor, #00f5a0),0 0 20px var(--cad-pulse-cor, #00f5a0);pointer-events:none!important;animation:cad-pulse-glow 1.4s ease-in-out infinite alternate}.cad-pulse-ring{position:absolute;width:100%;height:100%;border-radius:50%;border:2.5px solid var(--cad-pulse-cor, #00f5a0);box-shadow:0 0 10px var(--cad-pulse-cor, #00f5a0);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:.6s}@keyframes cad-pulse-ping{0%{transform:scale(.35);opacity:.95}60%{opacity:.5}to{transform:scale(2.5);opacity:0}}@keyframes cad-pulse-glow{0%{transform:scale(.85);opacity:.8}to{transform:scale(1.15);opacity:1;box-shadow:0 0 14px var(--cad-pulse-cor, #00f5a0),0 0 26px var(--cad-pulse-cor, #00f5a0)}}.cad-marker-selected,.ponto-selecionado{z-index:2000!important}.cad-marker-selected>div,.ponto-selecionado>div{animation:cad-ponto-pulse 1.8s ease-in-out infinite alternate!important}@keyframes cad-ponto-pulse{0%{filter:drop-shadow(0 0 3px #ffffff) drop-shadow(0 0 6px #00f5a0)}to{filter:drop-shadow(0 0 6px #ffffff) drop-shadow(0 0 16px #00f5a0)}}.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}';function se(){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 Bo(n,t,e,o){var b,w,M,C,E,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(((b=s.matches)==null?void 0:b.call(s,v))||((w=s.closest)==null?void 0:w.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(((E=t.containerPoint)==null?void 0:E.y)??((P=t.layerPoint)==null?void 0:P.y)??0);else{const v=n.mapContainer.getBoundingClientRect(),x=(i==null?void 0:i.clientX)??0,k=(i==null?void 0:i.clientY)??0;c=Math.round(x-v.left),l=Math.round(k-v.top)}const d={x:c,y:l};let h,u;const m=e||(t==null?void 0:t.latlng);if(m&&typeof m.lat=="number")h=m.lat,u=m.lng??m.lon??0;else{const v=r.containerPointToLatLng(y.point(d.x,d.y));h=v.lat,u=v.lng}const f=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:f},bubbles:!0,composed:!0})),!0}function Ho(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 Vo(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 Go(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 jo(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,m=0;h.contentRect?(u=h.contentRect.width,m=h.contentRect.height):h.borderBoxSize&&h.borderBoxSize.length>0?(u=h.borderBoxSize[0].inlineSize,m=h.borderBoxSize[0].blockSize):(u=n.clientWidth||n.offsetWidth,m=n.clientHeight||n.offsetHeight),u>0&&m>0&&(Math.abs(u-i)>=.5||Math.abs(m-a)>=.5)&&(i=u,a=m,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 sn{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 rn{constructor(t){p(this,"contexto");p(this,"uiListeners",new se.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"),m=c.getAttribute("data-elemento-id");u&&m!==null&&((h=(d=this.contexto).onDispararAcaoPopup)==null||h.call(d,u,m))}})}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 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 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}';function dn(){return`
|
|
178
132
|
<style>
|
|
179
|
-
${
|
|
180
|
-
${
|
|
133
|
+
${L.leafletCss}
|
|
134
|
+
${ln}
|
|
181
135
|
</style>
|
|
182
136
|
<div class="cad-root" id="cad-root">
|
|
183
137
|
<div class="cad-map-container" id="cad-map-container"></div>
|
|
@@ -200,41 +154,46 @@
|
|
|
200
154
|
<button class="cad-btn-tool" id="btn-zoom-extents" type="button" title="Enquadrar">
|
|
201
155
|
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><line x1="22" y1="12" x2="18" y2="12"/><line x1="6" y1="12" x2="2" y2="12"/><line x1="12" y1="6" x2="12" y2="2"/><line x1="12" y1="22" x2="12" y2="18"/></svg>
|
|
202
156
|
</button>
|
|
157
|
+
<button class="cad-btn-tool" id="btn-toggle-snap" type="button" title="Snap (S) — Alt desliga temporariamente" aria-pressed="true">
|
|
158
|
+
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M6 3v8a6 6 0 0 0 12 0V3"/><line x1="6" y1="7" x2="10" y2="7"/><line x1="14" y1="7" x2="18" y2="7"/></svg>
|
|
159
|
+
</button>
|
|
203
160
|
<button class="cad-btn-tool" id="btn-clear-selection" type="button" title="Limpar seleção">
|
|
204
161
|
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="3" width="18" height="18" rx="2" stroke-dasharray="3 3"/><line x1="9" y1="9" x2="15" y2="15"/><line x1="15" y1="9" x2="9" y2="15"/></svg>
|
|
205
162
|
</button>
|
|
206
163
|
</div>
|
|
207
164
|
</div>
|
|
208
|
-
`}function ae(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 s=n.controller.getMap();if(s){const a=s.getContainer();a&&(a.style.cursor=i?"crosshair":"")}n.controller.core.config.crosshair=i}}}function re(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,s,a)=>{St(n.obterContextoEventos(),o,i,s,a,t,n.colecoesDados.customMarkerClickHandler)},n.controller.context.onPopupAcao=(o,i,s)=>{n.dispararAcaoPopup(o,i,s)};const e=n.controller.getMap();e&&e.on("click",o=>{n.toolbarPainel.houveMovimentoMouse||n.tratarCliqueLivreCanvas(o,o.latlng,o.containerPoint)}),setTimeout(()=>{n.invalidateSizeSafely()},150)}class Lt extends at.SafeHTMLElement{constructor(){super();u(this,"shadow");u(this,"mapContainer",null);u(this,"layersPanel",null);u(this,"controller");u(this,"controladorTamanho");u(this,"toolbarPainel");u(this,"broadcastConfig");u(this,"colecoesDados");u(this,"layerItemListeners",new st.ListenerBag);u(this,"initTimeout");u(this,"lastPopupActionEmit");u(this,"lastCanvasClickTime",0);u(this,"_chaveGrupo");u(this,"_zonaProjecao",22);this.shadow=this.attachShadow({mode:"open"}),this.controller=new Z,this.controladorTamanho=Mt(this,this.controller),this.shadow.innerHTML=se(),this.mapContainer=this.shadow.getElementById("cad-map-container"),this.layersPanel=this.shadow.getElementById("qgis-layer-panel"),this.toolbarPainel=new oe({shadow:this.shadow,mapContainer:this.mapContainer,layersPanel:this.layersPanel,onToggleCamadas:()=>this.toggleLayersPanel(),onCloseCamadas:()=>this.closeLayersPanel(),onZoomExtents:()=>this.zoomExtents(),onLimparSelecao:()=>this.limparSelecao(),onTratarCliqueCanvas:e=>this.tratarCliqueLivreCanvas(e),onDispararAcaoPopup:(e,o)=>this.dispararAcaoPopup(e,o)}),this.broadcastConfig=new ee({host:this,controller:this.controller,mapContainer:this.mapContainer,setLayerOpacity:(e,o)=>this.setLayerOpacity(e,o)}),this.colecoesDados=new ie({obterController:()=>this.controller,obterChaveGrupo:()=>this.chaveGrupo,setLayerVisibility:(e,o)=>this.setLayerVisibility(e,o)})}static get observedAttributes(){return["sat-opacity","scale-mode","crosshair","modo-sequencial","chave-grupo","zona-projecao","fuso","canal-configuracao"]}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.broadcastConfig.conectar(),this.initTimeout=window.setTimeout(()=>this.initCAD(),0)}destroy(){if(this.initTimeout&&(window.clearTimeout(this.initTimeout),this.initTimeout=void 0),this.controladorTamanho.disconnect(),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){ae({host:this,controller:this.controller,mapContainer:this.mapContainer,broadcastConfig:this.broadcastConfig,setLayerOpacity:(s,a)=>this.setLayerOpacity(s,a),setLayerScaleMode:(s,a)=>this.setLayerScaleMode(s,a),atualizarZonaProjecao:s=>{this._zonaProjecao=s}},e,o,i)}initCAD(){re({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 s=Date.now();s-this.lastCanvasClickTime<50||(this.lastCanvasClickTime=s,Ct(this.obterContextoEventos(),e,o,i))}dispararAcaoPopup(e,o,i){const s=Date.now();this.lastPopupActionEmit&&this.lastPopupActionEmit.acaoId===e&&this.lastPopupActionEmit.elementoId===o&&s-this.lastPopupActionEmit.time<50||(this.lastPopupActionEmit={acaoId:e,elementoId:o,time:s},wt(this.obterContextoEventos(),e,o,i))}toggleLayersPanel(){this.toolbarPainel.toggleLayersPanel()}closeLayersPanel(){this.toolbarPainel.closeLayersPanel()}renderLayersUI(){const e=this.shadow.getElementById("layers-list-container");Pt(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 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()}limparSelecao(){this.controller.canvasInteracao.limparSelecao()}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.controller.getMap()&&this.mapContainer&&this.initCAD(),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",s){this.colecoesDados.plotarPolilinhaSequencial(e,o,i,s)}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()}getMap(){return this.controller.getMap()}getController(){return this.controller}getLayerManager(){return this.controller.layerManager}}at.definirCustomElement("ui-canvas-cad",Lt);class le{constructor(t,e){u(this,"polylines",[]);u(this,"bancoPontosAtivo",!1);u(this,"core");this.core=t}setBancoPontosAtivo(t){this.bancoPontosAtivo=t}plotSegmentos(t,e){this.core.map&&t.forEach(o=>{const i=e.find(a=>String(a.id)===String(o.ponto_inicio_id)),s=e.find(a=>String(a.id)===String(o.ponto_fim_id));if(i&&s&&i.lat&&i.lon&&s.lat&&s.lon){const a=o.tipo_limite_sigef||o.tipo_limite||"",c=o.metodo_posicionamento_sigef||o.metodo_posicionamento||"",r=this.bancoPontosAtivo?"#94a3b8":a==="LA1"?"#10b981":"#3b82f6",l=this.core.config.perimetroWeight,p=this.bancoPontosAtivo?.4:1,d=y.polyline([[i.lat,i.lon],[s.lat,s.lon]],{color:r,weight:l,opacity:p,dashArray:a==="LN1"?"6, 6":void 0,pane:"perimetroPane"}).bindPopup(`
|
|
209
|
-
|
|
210
|
-
<div style="font-weight:700; font-size:12px; margin-bottom:3px; color:#ffffff;">${g.escapeHtml(i.nome_vertice)} ↔ ${g.escapeHtml(s.nome_vertice)}</div>
|
|
211
|
-
|
|
165
|
+
`}function hn(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 un(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)=>{Vo(n.obterContextoEventos(),o,i,a,s,t,n.colecoesDados.customMarkerClickHandler)},n.controller.context.onSegmentoClick=(o,i,a)=>{Go(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 ot(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=L.parseCoordenada(e,o,t);return!i||!Number.isFinite(i.lat)||!Number.isFinite(i.lon)?null:[i.lat,i.lon]}function pn(n,t){return n[0]===t[0]&&n[1]===t[1]}function ke(n,t){const e=n.map(o=>ot(o,t)).filter(o=>o!==null);return e.length>1&&pn(e[0],e[e.length-1])&&e.pop(),e.length>=3?e:null}function me(n,t){const e=n.map(o=>ot(o,t)).filter(o=>o!==null);return e.length>=2?e:null}function Uo(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=>ke(i,t));return o.some(i=>i===null)?null:o}function fn(n,t){const e=L.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 mn(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=L.parseCoordenada(o.lat,o.lon),s=L.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 gn(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=ke(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}const vn=new Set(["Point","LineString","Polygon","Circle","Text"]);function Tt(n,t,e){if(!n||typeof n!="object")return null;const o=n,i=o.geometria;if(!i||!vn.has(i.tipo)||o.id===void 0||o.id===null||o.id==="")return null;let a=null;switch(i.tipo){case"Point":{const r=ot(i.coordenada,e);r&&(a={tipo:"Point",coordenada:r});break}case"Text":{const r=ot(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(c=>Array.isArray(c)?me(c,e):null).filter(c=>c!==null):[];if(r.length>0)a=ft(r);else{const c=Array.isArray(i.coordenadas)?me(i.coordenadas,e):null;c&&(a=ft([c]))}break}case"Polygon":{const r=Array.isArray(i.aneis)?Uo(i.aneis,e):null;r&&(a={tipo:"Polygon",aneis:r});break}case"Circle":{const r=ot(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=Z({...s,status:o.status}),s}const ee="cad-cursores",yn=/^#[0-9a-f]{3,8}$/i,xn="#94a3b8";function Vt(n){return typeof n=="string"&&yn.test(n.trim())?n.trim():xn}const bn='<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 We(n){const t=document.createElement("div");t.style.cssText=`color:${Vt(n.cor)};position:relative;pointer-events:none`,t.innerHTML=bn;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:${Vt(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 Wo{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${Vt(t.cor)}`,s=this.marcadores.get(i);if(s)return s.marker.setLatLng(e),s.assinatura!==a&&(s.marker.setIcon(We(t)),s.assinatura=a),!0;o.getPane(ee)||(o.createPane(ee).style.zIndex="9500");const r=y.marker(e,{icon:We(t),pane:ee,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 Et=n=>`${n.camadaId}\0${n.id}`;class Xo{constructor(t){p(this,"itens",new Map);this.dep=t}get quantidade(){return this.itens.size}contem(t){return this.itens.has(Et(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(Et(a),{camadaId:a.camadaId,id:a.id}),i.add(a.camadaId));this.finalizar(o,i)}alternar(t){const e=this.assinatura(),o=Et(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=Et(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)}}const Gt=63710088e-1,Xe=111320,jt=n=>n*Math.PI/180;function ut(n){return{lat0:n[0],lon0:n[1],cos0:Math.cos(jt(n[0]))}}function ge(n,t){return[jt(n[1]-t.lon0)*t.cos0*Gt,jt(n[0]-t.lat0)*Gt]}function pt(n,t){return[t.lat0+n[1]/Gt*(180/Math.PI),t.lon0+n[0]/(Gt*t.cos0)*(180/Math.PI)]}function Ee(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 Zo(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 Ut(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 Yo(n,t){if(n.length<3||t.length<2)return null;const e=ut(n[0]),o=n.map(s=>ge(s,e)),i=t.map(s=>ge(s,e)),a=Ko(o,i,0);return a&&a.length>=2?a.map(s=>s.map(r=>pt(r,e))):null}function Ko(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 x=Zo(t[P],t[P+1],n[v],n[(v+1)%o]);x&&i.push({tLinha:P+x.t,tAnel:v+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,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),m=Math.floor(d.tAnel),f=h.slice(1,-1),g=[l.ponto];for(let P=u+1;P<=m;P++)g.push(n[P%o]);g.push(d.ponto,...[...f].reverse());const b=[d.ponto];for(let P=m+1;P<=u+o;P++)b.push(n[P%o]);b.push(l.ponto,...f);const M=Ut(n)*1e-9,C=[g,b].filter(P=>P.length>=3&&Ut(P)>M);if(C.length<2)return null;const E=[s.ponto,...t.slice(Math.floor(s.tLinha)+1)];if(i.length>2&&E.length>=2){const P=[];for(const v of C){const x=Ko(v,E,e+1);x?P.push(...x):P.push(v)}return P}return C}function mt(n,t){return n.map(e=>ge(e,t))}const J=(n,t)=>Math.hypot(n[0]-t[0],n[1]-t[1]);function Jo(n,t=0){if(n.length===0||n.some(a=>a.length<2))return null;const e=ut(n[0][0]),o=n.slice(1).map(a=>mt(a,e));let i=mt(n[0],e);for(;o.length>0;){let a=null;if(o.forEach((d,h)=>{const u=i[0],m=i[i.length-1],f=[{inverter:!1,noFim:!0,d:J(m,d[0])},{inverter:!0,noFim:!0,d:J(m,d[d.length-1])},{inverter:!1,noFim:!1,d:J(u,d[d.length-1])},{inverter:!0,noFim:!1,d:J(u,d[0])}];for(const g of f)(!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,...J(i[i.length-1],l[0])>0?l:l.slice(1)]:[...l,...J(l[l.length-1],i[0])>0?i:i.slice(1)]}return i.map(a=>pt(a,e))}function Pn(n,t,e,o){const i=Zo(n,t,e,o);return!!i&&i.t>1e-9&&i.t<1-1e-9&&i.u>1e-9}function Cn(n,t){for(let e=0;e<n.length;e++)for(let o=0;o<t.length;o++)if(Pn(n[e],n[(e+1)%n.length],t[o],t[(o+1)%t.length]))return!0;return!1}function Qo(n,t,e=0){if(n.length<3||t.length<3)return null;const o=ut(n[0]),i=mt(n,o),a=mt(t,o);if(Cn(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=J(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=>pt(d,o))}const Ze=16;function Ye(n,t,e,o){const i=[];for(let a=0;a<=Ze;a++){const s=e+(o-e)*a/Ze;i.push([n[0]+t*Math.cos(s),n[1]+t*Math.sin(s)])}return i}function zt(n,t){const e=J(n,t)||1;return[-(t[1]-n[1])/e,(t[0]-n[0])/e]}function oe(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?zt(c,l):zt(r,c),h=s===o-1&&!e?zt(r,c):zt(c,l);let u=d[0]+h[0],m=d[1]+h[1];const f=Math.hypot(u,m);if(f<1e-9){i.push([c[0]+d[0]*t,c[1]+d[1]*t]);continue}u/=f,m/=f;const g=u*d[0]+m*d[1],b=Math.min(1/Math.max(g,.5),2);i.push([c[0]+u*t*b,c[1]+m*t*b])}return i}function Sn(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 ti(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=ut(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=>pt(s,i))}if(n.tipo==="LineString"){if(t<0||n.coordenadas.length<2||Ct(n))return null;const e=ut(n.coordenadas[0]),o=mt(n.coordenadas,e),i=oe(o,t,!1),a=oe([...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=Ye(s,t,c+Math.PI/2,c-Math.PI/2),h=Ye(r,t,l+Math.PI/2,l-Math.PI/2);return[...i,...d,...a,...h].map(u=>pt(u,e))}if(n.tipo==="Polygon"){const e=n.aneis[0];if(!e||e.length<3)return null;const o=ut(e[0]);let i=mt(e,o);Sn(i)&&(i=[...i].reverse());const s=oe(i,-t,!0);return s.length<3||t<0&&Ut(s)>=Ut(i)?null:s.map(r=>pt(r,o))}return null}function ei(n,t,e){const o=i=>{const a=e/Xe,s=t/(Xe*Math.max(.01,Math.cos(jt(i[0]))));return[i[0]+a,i[1]+s]};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":return ft(G(n).map(i=>i.map(o)));case"Polygon":return{tipo:"Polygon",aneis:n.aneis.map(i=>i.map(o))}}}const Ke={m:1,km:1e3,ft:.3048,mi:1609.344},Je={m2:1,ha:1e4,km2:1e6,ac:4046.8564224,alqueire:24200};function Ln(n,t,e){return n*Ke[t]/Ke[e]}function Mn(n,t,e){return n*Je[t]/Je[e]}function wn(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 An(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 kn(n,t){return st(n,t)}function $t(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 En=111320;function gt(n,t){return n.x>=t.x1&&n.x<=t.x2&&n.y>=t.y1&&n.y<=t.y2}function Qe(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 to(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 eo(n,t,e){for(let o=1;o<n.length;o++)if(Qe(n[o-1],n[o],t))return!0;return e&&n.length>2&&Qe(n[n.length-1],n[0],t)}function zn(n,t,e){const o=e(n),i=e([n[0]+t/En,n[1]]);return Math.hypot(i.x-o.x,i.y-o.y)}function oi(n,t,e,o){if(n.oculta)return!1;const i=n.geometria,a=o==="window";switch(i.tipo){case"Point":case"Text":return gt(e(i.coordenada),t);case"LineString":{const s=G(i).map(r=>r.map(e));return a?s.every(r=>r.every(c=>gt(c,t))):s.some(r=>r.some(c=>gt(c,t))||eo(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=>gt(l,t));if(s.some(l=>l.some(d=>gt(d,t))||eo(l,t,!0)))return!0;const c={x:t.x1,y:t.y1};return to(c,r)&&!s.slice(1).some(l=>to(c,l))}case"Circle":{const s=e(i.centro),r=zn(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 ii(n,t){if(t.length<3||n.oculta)return!1;const e=i=>Ee(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 G(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 In={Point:"Ponto",LineString:"Linha",Polygon:"Polígono",Circle:"Círculo",Text:"Texto"},_n=new Set(["name","nome","category","categoria","description","descricao","author","autor","date","data","created_at","criadoEm"]),oo=6;function vt(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 Tn(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 $n(n){const t=typeof n=="object"?JSON.stringify(n):String(n);return t.length>80?`${t.slice(0,77)}...`:t}function Mt(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 Dn(n){const t=n.geometria,e=[],o=tt(t),i=K(t);if(t.tipo==="Polygon")e.push(["Área",rt(o??0)],["Perímetro",j(i??0)]),e.push(["Vértices",String(t.aneis.reduce((r,c)=>r+c.length,0))]);else if(t.tipo==="LineString"){const r=G(t);e.push(["Extensão",j(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",j(t.raioMetros)],["Área",rt(o??0)]);const[a,s]=Mt(n);return e.push(["Coordenadas",`${a.toFixed(6)}, ${s.toFixed(6)}`]),e}class ni{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(Mt(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(Mt(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=X(((g=t.estilo)==null?void 0:g.corTraco)??(e==null?void 0:e.estilo.corPrimaria),"#38bdf8"),i=(b,w="",M)=>{const C=document.createElement(b);return w&&(C.style.cssText=w),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",vt(t,["name","nome"])||t.id));const s=vt(t,["category","categoria"]),r=[In[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=vt(t,["description","descricao"]);c&&a.appendChild(i("div","font-size:11px;margin-bottom:4px",c));const l=b=>{const w=i("div","font-size:11px;margin-bottom:4px");for(const[M,C]of b){const E=i("div");E.appendChild(i("strong","",`${M}: `)),E.appendChild(document.createTextNode(C)),w.appendChild(E)}return w};a.appendChild(l(Dn(t)));const d=Object.entries(t.propriedades??{}).filter(([b,w])=>!_n.has(b)&&w!==void 0&&w!==null&&w!=="");d.length>0&&(a.appendChild(l(d.slice(0,oo).map(([b,w])=>[b,$n(w)]))),d.length>oo&&a.appendChild(i("div","font-size:10px;color:rgba(255,255,255,.55);margin-bottom:4px",`${d.length} atributos`)));const h=vt(t,["author","autor"]),u=vt(t,["date","data","created_at","criadoEm"]);if(h||u){const b=[h,u?Tn(u):""].filter(Boolean).join(" · ");a.appendChild(i("div","font-size:10px;color:rgba(255,255,255,.55);margin-bottom:4px",b))}const m=i("div","display:flex;gap:4px;flex-wrap:wrap;margin-top:6px"),f=[["inspecionar","Inspecionar"],["zoom","Zoom"]];(t.geometria.tipo==="LineString"||t.geometria.tipo==="Polygon"||t.geometria.tipo==="Point")&&f.push(["vertices","Vértices"]),t.geometria.tipo==="Point"&&f.push(["copiar","Copiar"]);for(const[b,w]of f){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",w);M.type="button",M.dataset.acao=b,M.addEventListener("click",C=>{C.stopPropagation(),this.dep.aoAcao(b,this.feicaoAtual??t)}),m.appendChild(M)}return a.appendChild(m),a}}const ai=5e3;function ze(n){return n.tipo==="Polygon"?3:n.tipo==="LineString"?2:1}function si(n,t=!1){if(n.bloqueada||t)return"bloqueada";const e=n.geometria;return e.tipo!=="Point"&&e.tipo!=="LineString"&&e.tipo!=="Polygon"?"tipo-nao-suportado":e.tipo==="Polygon"&&e.aneis.length!==1?"poligono-com-furos":Ct(e)?"multiparte":W(e).length>ai?"muitos-vertices":null}function W(n){return n.tipo==="Point"?[n.coordenada]:n.tipo==="LineString"?n.coordenadas:n.tipo==="Polygon"?n.aneis[0]??[]:[]}function wt(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 qn(n,t,e){const o=W(n).slice();return t<0||t>=o.length?n:(o[t]=e,wt(n,o))}function ri(n,t,e){if(n.tipo!=="LineString"&&n.tipo!=="Polygon")return n;const o=W(n).slice();return t<0||t>=o.length?n:(o.splice(t+1,0,e),wt(n,o))}function ci(n,t){if(n.tipo!=="LineString"&&n.tipo!=="Polygon")return null;const e=W(n);return t<0||t>=e.length||e.length<=ze(n)?null:wt(n,e.filter((o,i)=>i!==t))}function bt(n,t){return[(n[0]+t[0])/2,(n[1]+t[1])/2]}function Ie(n){const t=W(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}const li={topo:0,base:16,esquerda:0,direita:0},di=16,hi=.92,Dt={topo:"--cad-hud-topo",base:"--cad-hud-base",esquerda:"--cad-hud-esquerda",direita:"--cad-hud-direita"},_e="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 Nn(n,t,e={}){const o={...li,...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*hi,i-di)),alturaMax:Math.max(0,t-o.topo-o.base-8)}}function ui(n,t){for(const e of Object.keys(Dt)){const o=t[e];typeof o=="number"&&Number.isFinite(o)&&o>=0?n.style.setProperty(Dt[e],`${o}px`):n.style.removeProperty(Dt[e])}}const pi="cm-vertex-edit-hud",yt="cad-edicao-vertices",io="#facc15";class fi{constructor(t){p(this,"feicaoAtual",null);p(this,"pts",[]);p(this,"alcas",[]);p(this,"fantasmas",[]);p(this,"marcadorSnap",null);p(this,"hud",null);p(this,"grupo",null);this.dep=t}get ativo(){return this.feicaoAtual!==null}get feicao(){return this.feicaoAtual}iniciar(t){this.parar(),this.feicaoAtual=t,this.pts=W(t.geometria).map(o=>[o[0],o[1]]);const e=this.dep.map;if(!e.getPane(yt)){const o=e.createPane(yt);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=[],(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=W(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 wt(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.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)}),t.tipo!=="Point")for(const[o,i]of Ie(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:${io};border:2px solid #111;border-radius:2px;cursor:move`),draggable:!0,pane:yt,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}criarFantasma(t,e){const o=y.marker(bt(this.pts[t],this.pts[e]),{icon:this.icone("cad-vertex-ghost",9,`background:${io};opacity:.45;border:1px solid #111;border-radius:50%;cursor:copy`),pane:yt,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){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;a?(i=a.coordenada,t.setLatLng(i),this.mostrarSnap(i)):this.esconderSnap(),this.pts[e]=i;for(const s of this.fantasmas)(s.i===e||s.j===e)&&s.marker.setLatLng(bt(this.pts[s.i],this.pts[s.j]));this.dep.previsualizar(this.feicaoComPontos()),this.atualizarHud()}inserir(t,e){if(!this.feicaoAtual)return;const i=ri(this.geometriaAtual(),t,[e.lat,e.lng]);this.pts=W(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=ci(this.geometriaAtual(),t);if(!o)return;this.pts=W(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=bt(this.pts[t],this.pts[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:yt,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=pi,e.style.cssText=_e+"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=r=>{const c=document.createElement("span");return c.dataset.campo=r,c},i=document.createElement("strong");i.textContent="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()),e.append(i,o("nos"),o("medida"),a,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=`Nós: ${this.pts.length} (mín. ${ze(t)})`),o&&(t.tipo==="Polygon"?o.textContent=`Área: ${rt(tt(t)??0)} · Perímetro: ${j(K(t)??0)}`:t.tipo==="LineString"?o.textContent=`Extensão: ${j(K(t)??0)}`:t.tipo==="Point"&&(o.textContent=`${t.coordenada[0].toFixed(6)}, ${t.coordenada[1].toFixed(6)}`))}vertices(){return this.pts.map(t=>[t[0],t[1]])}arrastarPara(t,e){const o=this.alcas[t];o&&(o.setLatLng(e),this.aoArrastar(o,t),o.fire("dragend"))}}const Te=10,ie=(n,t)=>Math.hypot(n.x-t.x,n.y-t.y);function On(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 mi(n,t,e,o={},i){const a=o.toleranciaPx??Te,s=o.vertice!==!1,r=o.meio!==!1,c=o.aresta!==!1;let l=null,d=null,h=null;const u=(m,f)=>!m||f.distanciaPx<m.distanciaPx?f:m;for(const m of t){if(m.excluida||m.oculta)continue;const f=!!i&&i.feicaoId===m.id&&(i.camadaId===void 0||i.camadaId===m.camadaId),g=m.geometria,b={feicaoId:m.id,camadaId:m.camadaId};if(g.tipo==="Point"||g.tipo==="Text"||g.tipo==="Circle"){if(!s||f)continue;const C=g.tipo==="Circle"?g.centro:g.coordenada,E=ie(n,e(C));E<=a&&(l=u(l,{tipo:"vertice",coordenada:C,distanciaPx:E,...b}));continue}const w=g.tipo==="LineString"?G(g).map(C=>({pts:C,fechado:!1})):[{pts:W(g),fechado:g.tipo==="Polygon"}],M=f?i.vertice:void 0;for(const{pts:C,fechado:E}of w){const P=C.map(e);if(s)for(let x=0;x<C.length;x++){if(x===M)continue;const k=ie(n,P[x]);k<=a&&(l=u(l,{tipo:"vertice",coordenada:C[x],distanciaPx:k,...b}))}if(!r&&!c)continue;const v=[];for(let x=0;x<C.length-1;x++)v.push([x,x+1]);E&&C.length>2&&v.push([C.length-1,0]);for(const[x,k]of v)if(!(M!==void 0&&(x===M||k===M))&&!(f&&M===void 0)){if(r){const z=bt(C[x],C[k]),S=ie(n,e(z));S<=a&&(d=u(d,{tipo:"meio",coordenada:z,distanciaPx:S,...b}))}if(c){const{t:z,d:S}=On(n,P[x],P[k]);if(S<=a){const A=[C[x][0]+z*(C[k][0]-C[x][0]),C[x][1]+z*(C[k][1]-C[x][1])];h=u(h,{tipo:"aresta",coordenada:A,distanciaPx:S,...b})}}}}}return l??d??h}class Fn{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&&!Pe(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 no=36,Rn=.45;function Bn(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<no;a++){const s=a*2*Math.PI/no;i.push([n[0]+e*Math.sin(s),n[1]+o*Math.cos(s)])}return i}function gi(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 Hn(n,t,e=6){const o=gi(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 Vn(n,t,e=5){const o=gi(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*Rn,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 Wt=["ponto","linha","poligono","retangulo","elipse","poligono-regular","estrela","circulo","texto","caneta","medir-distancia","medir-area","dividir","selecao-laco","conta-gotas"],ve=2;function $e(n){return typeof n=="string"&&Wt.includes(n)}const ao=16;function Gn(n,t){return[2*n[0]-t[0],2*n[1]-t[1]]}function ye(n){if(n.length===0)return[];const t=[n[0].ponto];for(let e=0;e<n.length-1;e++){const o=n[e],i=n[e+1],a=o.alca??o.ponto,s=i.alca?Gn(i.ponto,i.alca):i.ponto;for(let r=1;r<=ao;r++){const c=r/ao,l=1-c,d=[l*l*l,3*l*l*c,3*l*c*c,c*c*c];t.push([d[0]*o.ponto[0]+d[1]*a[0]+d[2]*s[0]+d[3]*i.ponto[0],d[0]*o.ponto[1]+d[1]*a[1]+d[2]*s[1]+d[3]*i.ponto[1]])}}return t}const jn=(n,t)=>n[0]===t[0]&&n[1]===t[1],so={elipse:Bn,"poligono-regular":(n,t)=>Hn(n,t,6),estrela:(n,t)=>Vn(n,t,5)};class qt{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>=ve?{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&&jn(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"?ye(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>=ve?{tipo:"Circle",centro:this.pontos[0],raioMetros:e}:null}case"caneta":{if(this.ancoras.length===0)return null;const e=ye(t?[...this.ancoras,{ponto:t}]:this.ancoras);return e.length<2?null:this.ehArea&&e.length>=3?{tipo:"Polygon",aneis:[e]}:{tipo:"LineString",coordenadas:e}}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;const t=this.vertices();return this.ehArea?{tipo:"Polygon",aneis:[t]}:{tipo:"LineString",coordenadas:t}}concluirFechando(){return this.fechaNoPrimeiro?{tipo:"Polygon",aneis:[this.vertices()]}:null}comprimentoMetros(){const t=this.cursor&&this.nos>0?[...this.vertices(),this.cursor]:this.vertices();return St(t,!1)}}const vi="cm-draw-hud",xe="cad-ferramenta-ativa",lt="cad-desenho",xt="#22d3ee",Un=4,Wn=450,Xn=10,Zn={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"},Yn={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 yi{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=Pe(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 qt(t,this.fechar),i.getPane(lt)||(i.createPane(lt).style.zIndex="8500"),this.grupo=y.layerGroup().addTo(i),this.marcas=y.layerGroup().addTo(this.grupo);const a=i.getContainer();a.classList.add(xe),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(xe),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)<=Un&&o-e.t<=Wn;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)>Xn)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 qt(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 qt(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;for(const i of o)this.marcas.addLayer(y.circleMarker(i,{pane:lt,radius:4,color:"#111",weight:1,fillColor:xt,fillOpacity:1,interactive:!1}));this.atualizarHud(e)}desenharGeometria(t,e){const o={pane:lt,color:xt,weight:2,dashArray:e?"6 4":void 0,fillColor:xt,fillOpacity:.15,interactive:!1};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 i=(t.tipo==="Point",t.coordenada);return y.circleMarker(i,{...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:lt,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],j(st(d,h)))}const c={tipo:e==="medir-area"?"area":"distancia",pontos:i,comprimentoM:St(i,!1)};if(t.tipo==="Polygon")c.areaM2=tt(t)??0,c.perimetroM=K(t)??0;else if(e==="medir-distancia"&&i.length>=3){const l={tipo:"Polygon",aneis:[i]};c.areaM2=tt(l)??0,c.perimetroM=K(l)??0}return c}mostrarSnap(t){this.grupo&&(this.marcadorSnap?this.marcadorSnap.setLatLng(t):this.marcadorSnap=y.marker(t,{pane:lt,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=vi,e.style.cssText=_e+"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=Zn[t.ferramenta];const a=o("dica");a.style.opacity=".7",a.textContent=Yn[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?xt:"rgba(255,255,255,.3)"};background:${l?xt:"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: ${j(K(t)??0)}`;else if((t==null?void 0:t.tipo)==="LineString"){if(a=`Extensão: ${j(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: ${j(K(s)??0)}`}}else(t==null?void 0:t.tipo)==="Circle"&&(a=`Raio: ${j(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 xi=6,ne=(n,t)=>Math.hypot(n.x-t.x,n.y-t.y);function ro(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 Kn(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 be(n,t,e,o=xi){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=ne(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 G(c)){const h=d.map(e);for(let u=1;u<h.length;u++)l=Math.min(l,ro(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=ne(l,d);if(ne(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,m]of Ie(c))d=Math.min(d,ro(n,l[u],l[m]));if(Ee([n.y,n.x],[l.map(u=>[u.y,u.x]),...c.aneis.slice(1).map(u=>u.map(e).map(m=>[m.y,m.x]))])||d<=o){const u=Kn(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",Jn=new Set(["ponto","linha","poligono","retangulo","elipse","poligono-regular","estrela","circulo","texto","caneta"]);class Qn{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 Bt,this.cursores=new Wo(()=>this.contexto.obterMapa()),this.snap=new Fn({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 ni({obterMapa:()=>this.contexto.obterMapa(),obterCamada:e=>this.contexto.obterLayerManager().getLayerDef(e),aoAcao:(e,o)=>this.tratarAcaoPopup(e,o)}),this.selecao=new Xo({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=Tt(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 Tt({...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=(S,A)=>String((S==null?void 0:S.id)??`#${A}`),h=[],u=S=>(i.recusadas.push(...h),S),m=[];r.forEach((S,A)=>{const I=Tt(S,t,this.opcoesNormalizacao());I?m.push(I):h.push(d(S,A))});const f=this.contexto.obterLayerManager(),g=f.getLayerDef(t);if(!(!g||g.tipo===H)||!g&&m.length===0)return c.forEach((S,A)=>i.recusadas.push(d(S,A))),m.forEach(S=>h.push(S.id)),u({resultado:i,adicionadas:a,atualizadas:s});if((m.length>0||g)&&!this.garantirCamada(t,o))return m.forEach(S=>h.push(S.id)),u({resultado:i,adicionadas:a,atualizadas:s});const w=this.lista(t),M=this.posicaoDe(t),C=w.slice(),E=[],P=[];let v=!1;for(const S of l){const A=String(S),I=M.get(A);I===void 0||C[I]===null||(C[I]=null,E.push(A),i.removidas++,v=!0)}c.forEach((S,A)=>{const I=S&&typeof S=="object"&&S.id!==void 0&&S.id!==null?String(S.id):"",_=M.get(I),O=_===void 0?null:C[_],T=O?this.mesclar(O,S,t,!!o.substituirPropriedades):null;if(!T||_===void 0){i.recusadas.push(I||d(S,A));return}C[_]=T,P.push(T),s.push(T),i.atualizadas++});for(const S of m){const A=M.get(S.id);A!==void 0&&C[A]!==null?C[A]=S:(M.set(S.id,C.length),C.push(S)),P.push(S),a.push(S),i.adicionadas++}if(P.length===0&&E.length===0)return u({resultado:i,adicionadas:a,atualizadas:s});const x=v?C.filter(S=>S!==null):C,z={feicoes:x,delta:{base:w,mudadas:P,removidas:E}};return f.setLayerData(t,z),delete z.delta,v?this.posicoes.delete(t):this.posicoes.set(t,{lista:x,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)&&ii(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)&&oi(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&&ui(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=Bt.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=et(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=ot(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=et(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]]=Le(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:be({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]=Mt(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(m=>this.desenhada(m)))}return d}buscarSnapEm(t,e){const o=this.contexto.obterMapa();if(!o)return null;const i=o.latLngToContainerPoint(t),a=this.candidatasEm(t,Te);return mi({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=si(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 fi({map:s,snapLigado:()=>this.snap.ativo,alternarSnap:()=>this.snap.alternar(),buscarSnap:(u,m)=>this.buscarSnapEm(u,m),previsualizar:u=>{const m=r.getLayerInstance(u.camadaId);m&&c&&c.previsualizar(m,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 m=this.buscar(u.camadaId,u.id)??u;this.contexto.emitir("cad-edicao-concluida",{feicao:m});const f=this.selecao.obter();f.length===1&&this.popup.abrir(f[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(!$e(t))return{ok:!1,motivo:"ferramenta-invalida"};const o=this.contexto.obterMapa();if(!o)return{ok:!1,motivo:"sem-mapa"};if(Jn.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 yi({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?ot(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=be({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=>Ct(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=Yo(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((m,f)=>{const g=$t(d,this.idLivre(d.camadaId,`${d.id}-${f+1}`),{tipo:"Polygon",aneis:[m]}),b=this.adicionarFeicao(d.camadaId,g);b&&u.push(b)}),u.length!==h.length){for(const m of u)this.removerFeicao(m.camadaId,m.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=ti(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=ei(a.geometria,o.lesteM??0,o.norteM??0),r=this.adicionarFeicao(t,$t(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(m=>Ct(m.geometria)))return i("multiparte");const h=s.map(m=>m.geometria.coordenadas),u=Jo(h,c);u&&(l=ft([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?Qo(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,$t(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 co={ponto:"Ponto",linha:"Linha",poligono:"Polígono",retangulo:"Retângulo",elipse:"Elipse","poligono-regular":"Hexágono",estrela:"Estrela",circulo:"Círculo",texto:"Texto",caneta:"Caneta","medir-distancia":"Medir","medir-area":"Área",dividir:"Dividir","selecao-laco":"Laço","conta-gotas":"Cor"};function ae(n){if(!n)return[];const t=n.split(/[\s,]+/).map(o=>o.trim().toLowerCase()).filter(Boolean);if(t.includes("todas"))return[...Wt];const e=new Set(t.filter($e));return Wt.filter(o=>e.has(o))}class ta{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=co[i],a.title=co[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 ea="data-cad-estilos-externos";function oa(n){try{return Array.from(n.cssRules,t=>t.cssText).join(`
|
|
166
|
+
`)}catch{return""}}function ia(n){return typeof n=="string"?n.trim()?[n]:[]:Array.isArray(n)?n.map(t=>typeof t=="string"?t:oa(t)).filter(t=>t.trim()!==""):[]}class na{constructor(t){p(this,"textos",[]);p(this,"adotadas",[]);p(this,"fallback",null);this.shadow=t}get pedido(){return this.textos}definir(t){this.textos=ia(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(ea,""),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 bi extends lo.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 se.ListenerBag);p(this,"layerItemListeners",new se.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 Xt,this.controladorTamanho=jo(this,this.controller),this.shadow.innerHTML=dn(),this.estilosExternos=new na(this.shadow),this.mapContainer=this.shadow.getElementById("cad-map-container"),this.layersPanel=this.shadow.getElementById("qgis-layer-panel"),this.toolbarPainel=new rn({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 sn({host:this,controller:this.controller,mapContainer:this.mapContainer,setLayerOpacity:(s,r)=>this.setLayerOpacity(s,r)}),this.colecoesDados=new cn({obterController:()=>this.controller,obterChaveGrupo:()=>this.chaveGrupo,setLayerVisibility:(s,r)=>this.setLayerVisibility(s,r)});const e=new Bt,o=this.controller.context,i=this.controller.canvasInteracao.ctx;Object.assign(o,{regraVersoes:e}),this.feicoes=new Qn({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 ta({raiz:this.shadow.getElementById("cad-root"),aoEscolher:s=>{this.feicoes.alternarFerramenta(s)}}),this.barraFerramentas.montar(ae(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(ae(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(ae(i)),(l=this.barraFerramentas)==null||l.marcar(((c=this.feicoes)==null?void 0:c.ferramentaAtiva)??null);return}hn({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(){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 a=Date.now();a-this.lastCanvasClickTime<50||(this.lastCanvasClickTime=a,Bo(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},Ho(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");Ro(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}}lo.definirCustomElement("ui-canvas-cad",bi);class aa{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 m=y.polyline(h,{color:c,weight:l,opacity:d,dashArray:s==="LN1"?"6, 6":void 0,pane:"perimetroPane"}).bindPopup(`
|
|
168
|
+
<div style="font-family:sans-serif; color:rgba(255, 255, 255, 0.9); line-height:1.3;">
|
|
169
|
+
<div style="font-weight:700; font-size:12px; margin-bottom:3px; color:#ffffff;">${L.escapeHtml(i.nome_vertice)} ↔ ${L.escapeHtml(a.nome_vertice)}</div>
|
|
170
|
+
<div style="font-size:11px; color:rgba(255, 255, 255, 0.65);">Limite: ${L.escapeHtml(s)} · ${L.escapeHtml(r)}</div>
|
|
212
171
|
</div>
|
|
213
|
-
`,{className:"compact-popup",maxWidth:220}).addTo(this.core.map);this.polylines.push(
|
|
214
|
-
<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-${
|
|
172
|
+
`,{className:"compact-popup",maxWidth:220}).addTo(this.core.map);this.polylines.push(m)}})}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=L.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=L.ordenarPontosPorSequencia(h);if(u.length<2)return;for(let M=0;M<u.length-1;M++){const C=u[M],E=u[M+1],P=[[C.lat,C.lon],[E.lat,E.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 x=y.polyline(P,{color:a,weight:s,opacity:r,pane:"perimetroPane"}).addTo(this.core.map);this.polylines.push(x)}const m=u[u.length-1],f=u[0],g=[[m.lat,m.lon],[f.lat,f.lon]],b=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(b);const w=y.polyline(g,{color:a,weight:s,opacity:r,dashArray:"4, 4",pane:"perimetroPane"}).addTo(this.core.map);this.polylines.push(w)})}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=`
|
|
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}">
|
|
215
174
|
H
|
|
216
175
|
</div>
|
|
217
|
-
`,
|
|
218
|
-
<div style="font-family:
|
|
176
|
+
`,d=y.divIcon({html:l,className:"banco-leaflet-marker",iconSize:[18,18]}),h=`
|
|
177
|
+
<div style="font-family:sans-serif; color:rgba(255, 255, 255, 0.9); line-height:1.35; min-width:180px;">
|
|
219
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>
|
|
220
|
-
<div style="font-weight:700; font-size:13px; margin-bottom:3px; color:#ffffff;">${
|
|
221
|
-
<div style="font-size:11px; color:rgba(255, 255, 255, 0.7); font-family:
|
|
222
|
-
<div style="font-size:11px; color:rgba(255, 255, 255, 0.7); font-family:
|
|
223
|
-
<div style="font-size:11px; color:rgba(255, 255, 255, 0.7); margin-bottom:2px;">Alt (h): <strong>${
|
|
224
|
-
<div style="font-size:10px; color:rgba(255, 255, 255, 0.45);">Método: ${
|
|
225
|
-
${
|
|
226
|
-
</div>
|
|
227
|
-
`;y.marker([
|
|
179
|
+
<div style="font-weight:700; font-size:13px; margin-bottom:3px; color:#ffffff;">${L.escapeHtml(c.codigo_completo||c.nome_vertice)}</div>
|
|
180
|
+
<div style="font-size:11px; color:rgba(255, 255, 255, 0.7); font-family:monospace;">Este (E): ${c.este?c.este.toFixed(2):"N/A"} m</div>
|
|
181
|
+
<div style="font-size:11px; color:rgba(255, 255, 255, 0.7); font-family:monospace; margin-bottom:3px;">Norte (N): ${c.norte?c.norte.toFixed(2):"N/A"} m</div>
|
|
182
|
+
<div style="font-size:11px; color:rgba(255, 255, 255, 0.7); margin-bottom:2px;">Alt (h): <strong>${c.altitude?c.altitude.toFixed(2):"N/A"} m</strong></div>
|
|
183
|
+
<div style="font-size:10px; color:rgba(255, 255, 255, 0.45);">Método: ${L.escapeHtml(c.metodo_posicionamento)||"N/A"} · Limite: ${L.escapeHtml(c.tipo_limite)||"N/A"}</div>
|
|
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> ${L.escapeHtml(c.confrontante_descritivo)}</div>`:""}
|
|
185
|
+
</div>
|
|
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=L.agruparPontosPorChave(e,o);for(const c in i){const l=L.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 sa{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":"",m=(a=(i=this.controller)==null?void 0:i.linhas)!=null&&a.bancoPontosAtivo?"opacity-40 hover:opacity-100":"",f=Pt(d,h,l,`${u} ${m}`,`map-marker-${o.id}`),g=y.divIcon({html:f,className:"custom-leaflet-marker flex items-center justify-center",iconSize:[h+6,h+6]}),b=c?"Base Homologada PPP":r?"Base de Campo (Translação)":"Vértice de Perímetro",w=y.marker([o.lat,o.lon],{icon:g,pane:"verticesPane"});w.pontoId=o.id,(s=this.controller)!=null&&s.modoCliqueSequencialAtivo||w.bindPopup(`
|
|
228
187
|
<div style="font-family:var(--ui-fonte-base, sans-serif); color:rgba(255, 255, 255, 0.9); line-height:1.3;">
|
|
229
|
-
<div style="font-weight:700; font-size:13px; margin-bottom:4px; color:#ffffff;">${
|
|
230
|
-
<div style="font-size:11px; color:rgba(255, 255, 255, 0.65);">${
|
|
188
|
+
<div style="font-weight:700; font-size:13px; margin-bottom:4px; color:#ffffff;">${L.escapeHtml(o.nome_vertice)}</div>
|
|
189
|
+
<div style="font-size:11px; color:rgba(255, 255, 255, 0.65);">${L.escapeHtml(b)} · ${L.escapeHtml(o.tipo_ponto||o.tipo)}</div>
|
|
231
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>
|
|
232
191
|
</div>
|
|
233
|
-
`,{className:"compact-popup",maxWidth:220}),
|
|
192
|
+
`,{className:"compact-popup",maxWidth:220}),w.addTo(this.core.map),w.setZIndexOffset(1e3),w.on("click",()=>{e(o.id)}),this.markers.push(w)}})}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,m;const a=document.createElement("div");a.className="p-2 font-sans text-xs bg-[#0c1510] text-white min-w-[200px] rounded",a.innerHTML=`
|
|
234
193
|
<div class="font-bold text-purple-400 mb-1 border-b border-white/10 pb-1">Confrontante (Importado)</div>
|
|
235
|
-
<div class="mb-1"><strong>Vértice:</strong> <span class="font-mono">${
|
|
236
|
-
<div class="mb-1"><strong>Proprietário:</strong> ${
|
|
237
|
-
<div class="mb-1"><strong>Propriedade:</strong> ${
|
|
194
|
+
<div class="mb-1"><strong>Vértice:</strong> <span class="font-mono">${L.escapeHtml(i.nome_vertice||"")}</span></div>
|
|
195
|
+
<div class="mb-1"><strong>Proprietário:</strong> ${L.escapeHtml(i.nome_confrontante||"")||"Desconhecido"}</div>
|
|
196
|
+
<div class="mb-1"><strong>Propriedade:</strong> ${L.escapeHtml(i.nome_propriedade||"")||"Desconhecida"}</div>
|
|
238
197
|
<div class="mb-1"><strong>Coordenadas:</strong> ${i.lat.toFixed(7)}, ${i.lon.toFixed(7)}</div>
|
|
239
198
|
<div class="text-[10px] text-white/50 border-t border-white/5 pt-1 mt-1 font-mono uppercase tracking-wider mb-2">Pontos Imutáveis do Vizinho</div>
|
|
240
199
|
<div style="display:flex; gap:6px; border-top:1px solid rgba(255,255,255,0.1); padding-top:6px;">
|
|
@@ -245,10 +204,10 @@
|
|
|
245
204
|
Ocultar
|
|
246
205
|
</button>
|
|
247
206
|
</div>
|
|
248
|
-
`,(
|
|
207
|
+
`,(u=a.querySelector(".btn-integrar"))==null||u.addEventListener("click",()=>{window.dispatchEvent(new CustomEvent("gerencigeo:integrar_vizinho",{detail:{pontoId:i.id}}))}),(m=a.querySelector(".btn-ocultar"))==null||m.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=Pt(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=L.escapeHtml(e.nome_propriedade||"Propriedade Vizinha"),s=L.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(`
|
|
249
208
|
<div class="p-2 font-sans text-xs bg-[#0c1510] text-white min-w-[200px] rounded">
|
|
250
209
|
<div class="font-bold text-purple-400 mb-1 border-b border-white/10 pb-1">Limite do Vizinho (Importado)</div>
|
|
251
|
-
<div class="mb-1"><strong>Propriedade:</strong> ${
|
|
252
|
-
<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>
|
|
253
212
|
</div>
|
|
254
|
-
`,{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=L.agruparPontosPorChave;exports.bindPopupAcoesEvents=L.bindPopupAcoesEvents;exports.escapeHtml=L.escapeHtml;exports.extrairCentroDeWkt=L.extrairCentroDeWkt;exports.formatUTM=L.formatUTM;exports.ordenarPontosPorSequencia=L.ordenarPontosPorSequencia;exports.parseCoordenada=L.parseCoordenada;exports.renderPopupAcoesHtml=L.renderPopupAcoesHtml;exports.AgrupadorCluster=qo;exports.CADMapaController=Xt;exports.CAD_INTERACTIVE_PANES=uo;exports.CELULA_CLUSTER_PX=Lt;exports.CLASSE_FERRAMENTA_ATIVA=xe;exports.COR_SELECAO=dt;exports.CSS_POSICAO_HUD=_e;exports.CanvasCADController=Xt;exports.CanvasInteracao=yo;exports.CanvasLayerManager=Oo;exports.ControleDesenho=yi;exports.CursoresRemotos=Wo;exports.DEFAULT_CONFIG=re;exports.DEFAULT_LAYERS=pe;exports.EditorVertices=fi;exports.FERRAMENTAS=Wt;exports.FOLGA_HUD=di;exports.FRACAO_LARGURA_HUD=hi;exports.FeicaoPopup=ni;exports.FeicoesLayerRenderer=No;exports.GerenciGeoMapaController=Xt;exports.GridLayerRenderer=wo;exports.ICONES_FEICAO=_t;exports.ID_HUD_DESENHO=vi;exports.ID_HUD_EDICAO=pi;exports.IndiceEspacial=Eo;exports.LIMIAR_DENSIDADE_ALTA=Ot;exports.LIMITE_CULLING=ue;exports.LayerRendererFactory=F;exports.MARGEM_HUD_PADRAO=li;exports.MAX_PONTOS_SEM_CLUSTER=$o;exports.MAX_VERTICES_EDICAO=ai;exports.MIN_VERTICES_SIMPLIFICAR=Me;exports.MapaConfigManager=Nt;exports.MapaCore=ho;exports.MapaLinhas=aa;exports.MapaMarcadores=sa;exports.PROPRIEDADES_HUD=Dt;exports.RAIO_MINIMO_CIRCULO_M=ve;exports.RegraVersoes=Bt;exports.SelecaoFeicoes=Xo;exports.SessaoDesenho=qt;exports.TOLERANCIA_AMOSTRA_PX=xi;exports.TOLERANCIA_LINHA_PX=It;exports.TOLERANCIA_PONTO_PX=mo;exports.TOLERANCIA_SNAP_PX=Te;exports.TileLayerRenderer=xo;exports.UICanvasCAD=bi;exports.VectorLinesLayerRenderer=Co;exports.VectorPointsLayerRenderer=Lo;exports.VectorPolygonsLayerRenderer=Mo;exports.WmsLayerRenderer=bo;exports.ZOOM_DESMEMBRAR=To;exports.ZOOM_SEM_SIMPLIFICACAO=Rt;exports.agruparPontos=Fi;exports.amostrarBezier=ye;exports.aplicarMargensHud=ui;exports.areaDaGeometria=tt;exports.areaMetros2=Ao;exports.buscarSnap=mi;exports.caixaDaFeicao=he;exports.caixasSeTocam=ht;exports.centroDe=Do;exports.clonarFeicao=$t;exports.comVertices=wt;exports.comprimentoMetros=St;exports.confrontanteParaFeicao=gn;exports.consultarFeicoesNoPonto=Ce;exports.converterArea=Mn;exports.converterComprimento=Ln;exports.coordenadaDeReferencia=Mt;exports.corHexSegura=Vt;exports.corSegura=X;exports.criarControladorTamanho=jo;exports.criarLinha=ft;exports.ddParaDms=wn;exports.deslocarGeometria=ei;exports.deveAgrupar=Ht;exports.distanciaEntre=kn;exports.distanciaMetros=st;exports.dividirPoligonoComLinha=Yo;exports.dmsParaDd=An;exports.ehFerramenta=$e;exports.ehMultilinha=Ct;exports.entidadeDe=et;exports.extensaoDaGeometria=K;exports.extrairCorPonto=So;exports.fatorDensidade=Se;exports.feicaoNaCaixa=oi;exports.feicaoNoLaco=ii;exports.feicaoNoPonto=be;exports.feicaoNoTopo=_i;exports.formatarArea=rt;exports.formatarExtensao=j;exports.garantirCanvasSemEventos=go;exports.gerarBuffer=ti;exports.getPointShapeHtml=Pt;exports.inserirVertice=ri;exports.juntarLinhas=Jo;exports.juntarPoligonos=Qo;exports.limitesDaGeometria=Le;exports.minimoVertices=ze;exports.modoDensidade=Ft;exports.moverVertice=qn;exports.normalizarAnel=ke;exports.normalizarCoordenada=ot;exports.normalizarFeicaoEntrada=Tt;exports.normalizarLinha=me;exports.normalizarPoligono=Uo;exports.partesDaLinha=G;exports.pontoMedio=bt;exports.pontoNoPoligono=Ee;exports.pontoParaFeicao=fn;exports.posicaoHud=Nn;exports.processarAcaoPopup=Ho;exports.processarCliqueLivreCanvas=Bo;exports.removerVertice=ci;exports.renderizarPainelCamadas=Ro;exports.resolverCliqueCentral=vo;exports.segmentoParaFeicao=mn;exports.segmentosDe=Ie;exports.simplificarAnel=Io;exports.simplificarGeometria=_o;exports.simplificarLinha=we;exports.statusDe=Z;exports.textoRotulo=ko;exports.toleranciaPorZoom=zo;exports.tratarCliqueMarcador=Vo;exports.tratarCliqueSegmento=Go;exports.verificarEditavel=si;exports.vertices=Ae;exports.verticesDe=W;
|