You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
leaflet-components/src/components/leaflet-polygon.ts

59 lines
1.7 KiB
TypeScript

import { Polygon } from 'leaflet';
import { buildOptions } from '../core/utils.ts';
import { withProps } from '../core/with-props.ts';
import { registerChildren, unregisterChildren } from '../core/register.ts';
import { isPathStyleAttr, updatePathStyle } from '../core/path-style.ts';
import { defineProps, num, str, on } from '../core/props.ts';
import type LeafletLine from './leaflet-line.ts';
const PROPS = defineProps({
color: str('#3388ff'),
weight: num(3),
opacity: num(1.0),
fill: on(),
fillColor: str('#3388ff'),
fillOpacity: num(0.2),
});
export default class LeafletPolygon extends withProps(HTMLElement, PROPS) {
#obj?: Polygon;
#observer?: MutationObserver;
connectedCallback() {
this.#obj = new Polygon(this.#getCoords(), buildOptions(this, PROPS));
registerChildren(this, this.#obj);
this.addEventListener('line-updated', this.#syncCoords);
this.#observer = new MutationObserver(() => this.#syncCoords());
this.#observer.observe(this, { childList: true });
}
disconnectedCallback() {
this.#observer?.disconnect();
this.#observer = undefined;
this.removeEventListener('line-updated', this.#syncCoords);
unregisterChildren(this);
this.#obj?.remove();
this.#obj = undefined;
}
attributeChangedCallback(name: string, _old: string | null, val: string | null) {
if (!this.#obj) return;
if (isPathStyleAttr(name)) {
updatePathStyle(this.#obj, name, val);
}
}
#syncCoords = () => {
this.#obj?.setLatLngs(this.#getCoords());
};
#getCoords(): [number, number][] {
const lines = Array.from(this.querySelectorAll('leaflet-line')) as LeafletLine[];
return lines.map((line) => line.latlng);
}
}
customElements.define('leaflet-polygon', LeafletPolygon);