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.
76 lines
2.1 KiB
TypeScript
76 lines
2.1 KiB
TypeScript
import { Tooltip } from 'leaflet';
|
|
import type { TooltipOptions } from 'leaflet';
|
|
import { WithProps, defineProps, num, str, on } from '../core/props.ts';
|
|
import { buildOptions, numAttr, registerWithParent } from '../core/utils.ts';
|
|
|
|
const PROPS = defineProps({
|
|
lat: num(),
|
|
lng: num(),
|
|
pane: str(),
|
|
offset: str(),
|
|
direction: str('auto'),
|
|
permanent: on(),
|
|
sticky: on(),
|
|
opacity: num(1.0),
|
|
});
|
|
|
|
export class LeafletTooltip extends WithProps(HTMLElement, PROPS) {
|
|
#obj?: Tooltip;
|
|
#observer?: MutationObserver;
|
|
#syncing = false;
|
|
|
|
connectedCallback() {
|
|
this.#obj = new Tooltip({
|
|
...buildOptions(this, PROPS, ['lat', 'lng']),
|
|
content: this.innerHTML,
|
|
} as unknown as TooltipOptions);
|
|
if (this.hasAttribute('lat') && this.hasAttribute('lng')) {
|
|
this.#obj.setLatLng([numAttr(this, PROPS, 'lat'), numAttr(this, PROPS, 'lng')]);
|
|
}
|
|
// eslint-disable-next-line @typescript-eslint/unbound-method
|
|
this.#obj.on('move', this.#onChange, this);
|
|
registerWithParent(this, this.#obj);
|
|
|
|
this.#observer = new MutationObserver(() => {
|
|
this.#obj?.setContent(this.innerHTML);
|
|
});
|
|
this.#observer.observe(this, {
|
|
childList: true,
|
|
characterData: true,
|
|
subtree: true,
|
|
});
|
|
}
|
|
|
|
disconnectedCallback() {
|
|
// eslint-disable-next-line @typescript-eslint/unbound-method
|
|
this.#obj?.off('move', this.#onChange, this);
|
|
this.#observer?.disconnect();
|
|
this.#observer = undefined;
|
|
this.#obj?.remove();
|
|
this.#obj = undefined;
|
|
}
|
|
|
|
get leafletObject() {
|
|
return this.#obj;
|
|
}
|
|
|
|
attributeChangedCallback(name: string) {
|
|
if (!this.#obj || this.#syncing) return;
|
|
if (name === 'lat' || name === 'lng') {
|
|
this.#obj.setLatLng([numAttr(this, PROPS, 'lat'), numAttr(this, PROPS, 'lng')]);
|
|
}
|
|
}
|
|
|
|
#onChange() {
|
|
if (!this.#obj || this.#syncing) return;
|
|
const pos = this.#obj.getLatLng();
|
|
if (!pos) return;
|
|
this.#syncing = true;
|
|
this.setAttribute('lat', `${pos.lat}`);
|
|
this.setAttribute('lng', `${pos.lng}`);
|
|
this.#syncing = false;
|
|
}
|
|
}
|
|
|
|
customElements.define('leaflet-tooltip', LeafletTooltip);
|