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-tile-layer.ts

62 lines
2.1 KiB
TypeScript

import { TileLayer } from 'leaflet';
import { registerWithParent, buildOptions, parseAttributeValue } from '../core/utils.js';
import { withProps } from '../core/with-props.js';
import {
createChildRegisterHandler,
type ChildEntry,
LeafletRegisterEvent,
} from '../core/register.js';
import type { PropDef } from '../types/props.js';
const PROPS = {
url: { kind: 'str', attr: 'url', default: '' },
attribution: { kind: 'str', attr: 'attribution', default: '' },
minZoom: { kind: 'num', attr: 'min-zoom', default: 0 },
maxZoom: { kind: 'num', attr: 'max-zoom', default: 18 },
opacity: { kind: 'num', attr: 'opacity', default: 1.0 },
zIndex: { kind: 'num', attr: 'z-index', default: 0 },
} satisfies Record<string, PropDef>;
const PROP_BY_ATTR = new Map<string, string>(
Object.entries(PROPS).map(([name, spec]) => [spec.attr, name]),
);
export class LeafletTileLayer extends withProps(HTMLElement, PROPS) {
#obj?: TileLayer;
#children = new Map<HTMLElement, ChildEntry>();
#childHandler?: (e: LeafletRegisterEvent) => void;
connectedCallback() {
const url = this.getAttribute('url') || '';
this.#obj = new TileLayer(url, buildOptions(this, PROPS, ['url']));
this.#childHandler = createChildRegisterHandler(this.#obj, this.#children);
this.addEventListener('leaflet-register', this.#childHandler);
registerWithParent(this, this.#obj);
}
disconnectedCallback() {
if (this.#childHandler) this.removeEventListener('leaflet-register', this.#childHandler);
this.#children.clear();
this.#obj?.remove();
this.#obj = undefined;
}
attributeChangedCallback(name: string, _old: string | null, val: string | null) {
if (!this.#obj) return;
if (name === 'url') {
if (val) this.#obj.setUrl(val);
} else {
const propName = PROP_BY_ATTR.get(name);
if (!propName) return;
const setter =
`set${propName.charAt(0).toUpperCase()}${propName.slice(1)}` as keyof TileLayer;
if (typeof this.#obj[setter] === 'function') {
(this.#obj[setter] as (v: unknown) => void)(parseAttributeValue(val));
}
}
}
}
customElements.define('leaflet-tile-layer', LeafletTileLayer);