refactor: replace inheritance hierarchy with composable PROPS-table pattern
Remove LeafletElement and LeafletControl base classes. Every component
now self-describes its attributes via a PROPS table, derives observed-
Attributes from it, and generates prototype getters/setters in static {}.
Registration lifecycle is extracted into standalone helpers
(registerWithParent, createChildRegisterHandler). Common update
patterns (path style) are shared via imported helpers instead of
duplicated across 5+ components.
Components manage their own #obj private field instead of a shared
protected leafletObject. Leaflet-map-style declarative patterns are
now consistent across all 20 components.
main
parent
6b448ba092
commit
5f3fd5f61a
@ -1,28 +1,83 @@
|
||||
import L from 'leaflet';
|
||||
import { LeafletElement } from '../core/LeafletElement.js';
|
||||
import { Marker } from 'leaflet';
|
||||
import { registerWithParent, buildOptions, parseAttributeValue } from '../core/utils.js';
|
||||
import type { PropDef, PropTypesFromTable } from '../types/props.js';
|
||||
|
||||
const PROPS = {
|
||||
lat: { kind: 'num', attr: 'lat', default: 0 },
|
||||
lng: { kind: 'num', attr: 'lng', default: 0 },
|
||||
title: { kind: 'str', attr: 'title', default: '' },
|
||||
alt: { kind: 'str', attr: 'alt', default: '' },
|
||||
draggable: { kind: 'bool-on', attr: 'draggable' },
|
||||
opacity: { kind: 'num', attr: 'opacity', default: 1.0 },
|
||||
zIndexOffset: { kind: 'num', attr: 'z-index-offset', default: 0 },
|
||||
} satisfies Record<string, PropDef>;
|
||||
|
||||
const PROP_BY_ATTR = new Map<string, string>(
|
||||
Object.entries(PROPS).map(([name, spec]) => [spec.attr, name]),
|
||||
);
|
||||
|
||||
type PropTypes = PropTypesFromTable<typeof PROPS>;
|
||||
const TypedBase = HTMLElement as unknown as new () => HTMLElement & PropTypes;
|
||||
|
||||
export class LeafletMarker extends TypedBase {
|
||||
#obj?: Marker;
|
||||
|
||||
export class LeafletMarker extends LeafletElement {
|
||||
static get observedAttributes() {
|
||||
return ['lat', 'lng', 'title', 'alt', 'draggable', 'opacity', 'z-index-offset'];
|
||||
return Object.values(PROPS).map((s) => s.attr);
|
||||
}
|
||||
|
||||
protected createLeafletObject(): L.Layer {
|
||||
const lat = parseFloat(this.getAttribute('lat') || '0');
|
||||
const lng = parseFloat(this.getAttribute('lng') || '0');
|
||||
return new L.Marker([lat, lng], this.options);
|
||||
static {
|
||||
for (const [name, spec] of Object.entries(PROPS)) {
|
||||
Object.defineProperty(LeafletMarker.prototype, name, {
|
||||
get(this: LeafletMarker) {
|
||||
const val = this.getAttribute(spec.attr);
|
||||
if (spec.kind === 'num') return val !== null ? Number(val) : spec.default;
|
||||
if (spec.kind === 'bool-on') return this.hasAttribute(spec.attr);
|
||||
return val ?? spec.default;
|
||||
},
|
||||
set(this: LeafletMarker, v: number | string | boolean) {
|
||||
if (spec.kind === 'bool-on') this.toggleAttribute(spec.attr, !!v);
|
||||
else this.setAttribute(spec.attr, String(v));
|
||||
},
|
||||
configurable: true,
|
||||
enumerable: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
protected updateLeafletObject(property: string, value: unknown) {
|
||||
if (this.leafletObject instanceof L.Marker) {
|
||||
if (property === 'lat' || property === 'lng') {
|
||||
const lat = parseFloat(this.getAttribute('lat') || '0');
|
||||
const lng = parseFloat(this.getAttribute('lng') || '0');
|
||||
this.leafletObject.setLatLng([lat, lng]);
|
||||
connectedCallback() {
|
||||
this.#obj = new Marker(
|
||||
[this.#num('lat'), this.#num('lng')],
|
||||
buildOptions(this, PROPS, ['lat', 'lng']),
|
||||
);
|
||||
registerWithParent(this, this.#obj);
|
||||
}
|
||||
|
||||
disconnectedCallback() {
|
||||
this.#obj?.remove();
|
||||
this.#obj = undefined;
|
||||
}
|
||||
|
||||
attributeChangedCallback(name: string, _old: string | null, val: string | null) {
|
||||
if (!this.#obj) return;
|
||||
if (name === 'lat' || name === 'lng') {
|
||||
this.#obj.setLatLng([this.#num('lat'), this.#num('lng')]);
|
||||
} else {
|
||||
super.updateLeafletObject(property, value);
|
||||
const propName = PROP_BY_ATTR.get(name);
|
||||
if (!propName) return;
|
||||
const setter = `set${propName.charAt(0).toUpperCase()}${propName.slice(1)}` as keyof Marker;
|
||||
if (typeof this.#obj[setter] === 'function') {
|
||||
(this.#obj[setter] as (v: unknown) => void)(parseAttributeValue(val));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#num(name: string): number {
|
||||
const v = this.getAttribute(name);
|
||||
return v !== null
|
||||
? Number(v)
|
||||
: (PROPS[name as keyof typeof PROPS] as { default: number }).default;
|
||||
}
|
||||
}
|
||||
|
||||
customElements.define('leaflet-marker', LeafletMarker);
|
||||
|
||||
@ -1,31 +1,84 @@
|
||||
import L from 'leaflet';
|
||||
import { LeafletElement } from '../core/LeafletElement.js';
|
||||
import { SVGOverlay, LatLngBounds, LatLngBoundsExpression, LatLngExpression } from 'leaflet';
|
||||
import { registerWithParent, buildOptions, parseAttributeValue } from '../core/utils.js';
|
||||
import type { PropDef, PropTypesFromTable } from '../types/props.js';
|
||||
|
||||
const PROPS = {
|
||||
bounds: { kind: 'str', attr: 'bounds', default: '' },
|
||||
opacity: { kind: 'num', attr: 'opacity', default: 1.0 },
|
||||
interactive: { kind: 'bool-on', attr: 'interactive' },
|
||||
crossOrigin: { kind: 'str', attr: 'cross-origin', default: '' },
|
||||
zIndex: { kind: 'num', attr: 'z-index', default: 0 },
|
||||
className: { kind: 'str', attr: 'class-name', default: '' },
|
||||
} satisfies Record<string, PropDef>;
|
||||
|
||||
const PROP_BY_ATTR = new Map<string, string>(
|
||||
Object.entries(PROPS).map(([name, spec]) => [spec.attr, name]),
|
||||
);
|
||||
|
||||
type PropTypes = PropTypesFromTable<typeof PROPS>;
|
||||
const TypedBase = HTMLElement as unknown as new () => HTMLElement & PropTypes;
|
||||
|
||||
export class LeafletSVGOverlay extends TypedBase {
|
||||
#obj?: SVGOverlay;
|
||||
|
||||
export class LeafletSVGOverlay extends LeafletElement {
|
||||
static get observedAttributes() {
|
||||
return ['bounds', 'opacity', 'alt', 'interactive', 'cross-origin', 'z-index', 'className'];
|
||||
return Object.values(PROPS).map((s) => s.attr);
|
||||
}
|
||||
|
||||
static {
|
||||
for (const [name, spec] of Object.entries(PROPS)) {
|
||||
Object.defineProperty(LeafletSVGOverlay.prototype, name, {
|
||||
get(this: LeafletSVGOverlay) {
|
||||
const val = this.getAttribute(spec.attr);
|
||||
if (spec.kind === 'num') return val !== null ? Number(val) : spec.default;
|
||||
if (spec.kind === 'bool-on') return this.hasAttribute(spec.attr);
|
||||
return val ?? spec.default;
|
||||
},
|
||||
set(this: LeafletSVGOverlay, v: number | string | boolean) {
|
||||
if (spec.kind === 'bool-on') this.toggleAttribute(spec.attr, !!v);
|
||||
else this.setAttribute(spec.attr, String(v));
|
||||
},
|
||||
configurable: true,
|
||||
enumerable: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
protected createLeafletObject(): L.Layer {
|
||||
connectedCallback() {
|
||||
const svg = this.querySelector('svg');
|
||||
const bounds = this.options.bounds as L.LatLngBoundsExpression;
|
||||
if (!svg) {
|
||||
// Create a dummy SVG if none provided
|
||||
const dummy = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
|
||||
return new L.SVGOverlay(dummy, bounds, this.options);
|
||||
const dummy = !svg ? document.createElementNS('http://www.w3.org/2000/svg', 'svg') : undefined;
|
||||
this.#obj = new SVGOverlay(
|
||||
svg ?? dummy!,
|
||||
this.#parsedBounds(),
|
||||
buildOptions(this, PROPS, ['bounds']),
|
||||
);
|
||||
registerWithParent(this, this.#obj);
|
||||
}
|
||||
return new L.SVGOverlay(svg, bounds, this.options);
|
||||
|
||||
disconnectedCallback() {
|
||||
this.#obj?.remove();
|
||||
this.#obj = undefined;
|
||||
}
|
||||
|
||||
protected updateLeafletObject(property: string, value: unknown) {
|
||||
if (this.leafletObject instanceof L.SVGOverlay) {
|
||||
if (property === 'bounds') {
|
||||
this.leafletObject.setBounds(new L.LatLngBounds(value as L.LatLngExpression[]));
|
||||
attributeChangedCallback(name: string, _old: string | null, val: string | null) {
|
||||
if (!this.#obj) return;
|
||||
if (name === 'bounds') {
|
||||
this.#obj.setBounds(new LatLngBounds(this.#parsedBounds() as LatLngExpression[]));
|
||||
} else {
|
||||
super.updateLeafletObject(property, value);
|
||||
const propName = PROP_BY_ATTR.get(name);
|
||||
if (!propName) return;
|
||||
const setter =
|
||||
`set${propName.charAt(0).toUpperCase()}${propName.slice(1)}` as keyof SVGOverlay;
|
||||
if (typeof this.#obj[setter] === 'function') {
|
||||
(this.#obj[setter] as (v: unknown) => void)(parseAttributeValue(val));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#parsedBounds(): LatLngBoundsExpression {
|
||||
const raw = this.getAttribute('bounds');
|
||||
return raw ? (JSON.parse(raw) as LatLngBoundsExpression) : [];
|
||||
}
|
||||
}
|
||||
|
||||
customElements.define('leaflet-svg-overlay', LeafletSVGOverlay);
|
||||
|
||||
@ -1,36 +0,0 @@
|
||||
import { Control } from 'leaflet';
|
||||
|
||||
export abstract class LeafletControl extends HTMLElement {
|
||||
protected control?: Control;
|
||||
|
||||
static get observedAttributes(): string[] {
|
||||
return [];
|
||||
}
|
||||
|
||||
connectedCallback() {
|
||||
this.control = this.createControl();
|
||||
this.register();
|
||||
}
|
||||
|
||||
disconnectedCallback() {
|
||||
this.control?.remove();
|
||||
this.control = undefined;
|
||||
}
|
||||
|
||||
protected abstract createControl(): Control;
|
||||
|
||||
protected register() {
|
||||
if (this.control) {
|
||||
this.dispatchEvent(
|
||||
new CustomEvent('leaflet-register', {
|
||||
detail: {
|
||||
leafletObject: this.control,
|
||||
element: this,
|
||||
},
|
||||
bubbles: true,
|
||||
composed: true,
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,141 +0,0 @@
|
||||
import { Layer, Control, Popup, Tooltip, LayerGroup } from 'leaflet';
|
||||
|
||||
export interface LeafletRegisterEvent extends CustomEvent {
|
||||
detail: {
|
||||
leafletObject: Layer | Control;
|
||||
element: HTMLElement;
|
||||
};
|
||||
}
|
||||
|
||||
export abstract class LeafletElement extends HTMLElement {
|
||||
protected leafletObject?: Layer;
|
||||
protected options: Record<string, unknown> = {};
|
||||
protected _parentLayer?: Layer;
|
||||
protected _parentBindingType?: 'popup' | 'tooltip' | 'layer';
|
||||
private _registerHandler?: EventListener;
|
||||
|
||||
static get observedAttributes(): string[] {
|
||||
return [];
|
||||
}
|
||||
|
||||
connectedCallback() {
|
||||
this.initOptions();
|
||||
this.leafletObject = this.createLeafletObject();
|
||||
|
||||
this._registerHandler = ((e: LeafletRegisterEvent) => {
|
||||
if (this.leafletObject) {
|
||||
const childObj = e.detail.leafletObject;
|
||||
const childEl = e.detail.element;
|
||||
if (childObj instanceof Popup) {
|
||||
e.stopPropagation();
|
||||
this.leafletObject.bindPopup(childObj);
|
||||
if (childEl instanceof LeafletElement) {
|
||||
childEl._parentLayer = this.leafletObject;
|
||||
childEl._parentBindingType = 'popup';
|
||||
}
|
||||
} else if (childObj instanceof Tooltip) {
|
||||
e.stopPropagation();
|
||||
this.leafletObject.bindTooltip(childObj);
|
||||
if (childEl instanceof LeafletElement) {
|
||||
childEl._parentLayer = this.leafletObject;
|
||||
childEl._parentBindingType = 'tooltip';
|
||||
}
|
||||
} else if (childObj instanceof Layer && 'addLayer' in this.leafletObject) {
|
||||
e.stopPropagation();
|
||||
(this.leafletObject as LayerGroup).addLayer(childObj);
|
||||
if (childEl instanceof LeafletElement) {
|
||||
childEl._parentLayer = this.leafletObject;
|
||||
childEl._parentBindingType = 'layer';
|
||||
}
|
||||
}
|
||||
}
|
||||
}) as EventListener;
|
||||
this.addEventListener('leaflet-register', this._registerHandler);
|
||||
|
||||
this.register();
|
||||
}
|
||||
|
||||
disconnectedCallback() {
|
||||
if (this._registerHandler) {
|
||||
this.removeEventListener('leaflet-register', this._registerHandler);
|
||||
this._registerHandler = undefined;
|
||||
}
|
||||
if (!this.leafletObject) return;
|
||||
if (this._parentBindingType === 'popup' && this._parentLayer) {
|
||||
this._parentLayer.unbindPopup();
|
||||
} else if (this._parentBindingType === 'tooltip' && this._parentLayer) {
|
||||
this._parentLayer.unbindTooltip();
|
||||
} else if (
|
||||
this._parentBindingType === 'layer' &&
|
||||
this._parentLayer &&
|
||||
'removeLayer' in this._parentLayer
|
||||
) {
|
||||
(this._parentLayer as LayerGroup).removeLayer(this.leafletObject);
|
||||
} else {
|
||||
this.leafletObject.remove();
|
||||
}
|
||||
this._parentLayer = undefined;
|
||||
this._parentBindingType = undefined;
|
||||
this.leafletObject = undefined;
|
||||
}
|
||||
|
||||
protected initOptions() {
|
||||
const observed = (this.constructor as typeof LeafletElement).observedAttributes;
|
||||
observed.forEach((attr) => {
|
||||
const val = this.getAttribute(attr);
|
||||
if (val !== null) {
|
||||
this.options[camelCase(attr)] = parseAttributeValue(val);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
attributeChangedCallback(name: string, oldValue: string, newValue: string) {
|
||||
if (oldValue === newValue) return;
|
||||
const propertyName = camelCase(name);
|
||||
const parsedValue = parseAttributeValue(newValue);
|
||||
this.options[propertyName] = parsedValue;
|
||||
|
||||
if (this.leafletObject) {
|
||||
this.updateLeafletObject(propertyName, parsedValue);
|
||||
}
|
||||
}
|
||||
|
||||
protected abstract createLeafletObject(): Layer;
|
||||
|
||||
protected updateLeafletObject(property: string, value: unknown) {
|
||||
const setter = `set${property.charAt(0).toUpperCase()}${property.slice(1)}`;
|
||||
const obj = this.leafletObject as unknown as Record<string, unknown>;
|
||||
if (obj && typeof obj[setter] === 'function') {
|
||||
(obj[setter] as (val: unknown) => void)(value);
|
||||
}
|
||||
}
|
||||
|
||||
protected register() {
|
||||
if (!this.leafletObject) return;
|
||||
const event = new CustomEvent('leaflet-register', {
|
||||
detail: {
|
||||
leafletObject: this.leafletObject,
|
||||
element: this,
|
||||
},
|
||||
bubbles: true,
|
||||
composed: true,
|
||||
});
|
||||
this.dispatchEvent(event);
|
||||
}
|
||||
}
|
||||
|
||||
function camelCase(str: string): string {
|
||||
return str.replace(/-([a-z])/g, (g) => g[1].toUpperCase());
|
||||
}
|
||||
|
||||
function parseAttributeValue(value: string): unknown {
|
||||
if (value === 'true') return true;
|
||||
if (value === 'false') return false;
|
||||
const num = Number(value);
|
||||
if (!isNaN(num) && value !== '') return num;
|
||||
try {
|
||||
return JSON.parse(value);
|
||||
} catch {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,26 @@
|
||||
import { Path } from 'leaflet';
|
||||
import { parseAttributeValue } from './utils.js';
|
||||
|
||||
export const PATH_STYLE_ATTRS = new Set([
|
||||
'color',
|
||||
'weight',
|
||||
'opacity',
|
||||
'fill',
|
||||
'fill-color',
|
||||
'fill-opacity',
|
||||
'stroke',
|
||||
'dash-array',
|
||||
'dash-offset',
|
||||
'line-cap',
|
||||
'line-join',
|
||||
'fill-rule',
|
||||
]);
|
||||
|
||||
export function isPathStyleAttr(name: string): boolean {
|
||||
return PATH_STYLE_ATTRS.has(name);
|
||||
}
|
||||
|
||||
export function updatePathStyle(obj: Path, name: string, value: string | null) {
|
||||
const key = name.replace(/-([a-z])/g, (g) => g[1].toUpperCase());
|
||||
obj.setStyle({ [key]: parseAttributeValue(value) });
|
||||
}
|
||||
@ -0,0 +1,35 @@
|
||||
import { Layer, LayerGroup, Popup, Tooltip } from 'leaflet';
|
||||
|
||||
export interface LeafletRegisterEvent extends CustomEvent {
|
||||
detail: {
|
||||
leafletObject: Layer;
|
||||
element: HTMLElement;
|
||||
};
|
||||
}
|
||||
|
||||
export type ChildEntry = {
|
||||
type: 'layer' | 'popup' | 'tooltip';
|
||||
};
|
||||
|
||||
export function createChildRegisterHandler(
|
||||
container: LayerGroup,
|
||||
children: globalThis.Map<HTMLElement, ChildEntry>,
|
||||
) {
|
||||
return (e: LeafletRegisterEvent) => {
|
||||
const obj = e.detail.leafletObject;
|
||||
const el = e.detail.element;
|
||||
if (obj instanceof Popup) {
|
||||
e.stopPropagation();
|
||||
container.bindPopup(obj);
|
||||
children.set(el, { type: 'popup' });
|
||||
} else if (obj instanceof Tooltip) {
|
||||
e.stopPropagation();
|
||||
container.bindTooltip(obj);
|
||||
children.set(el, { type: 'tooltip' });
|
||||
} else if (obj instanceof Layer && 'addLayer' in container) {
|
||||
e.stopPropagation();
|
||||
container.addLayer(obj);
|
||||
children.set(el, { type: 'layer' });
|
||||
}
|
||||
};
|
||||
}
|
||||
@ -0,0 +1,57 @@
|
||||
import type { PropDef } from '../types/props.js';
|
||||
|
||||
export function camelCase(str: string): string {
|
||||
return str.replace(/-([a-z])/g, (g) => g[1].toUpperCase());
|
||||
}
|
||||
|
||||
export function parseAttributeValue(value: string | null): unknown {
|
||||
if (value === null) return null;
|
||||
if (value === 'true') return true;
|
||||
if (value === 'false') return false;
|
||||
const num = Number(value);
|
||||
if (!isNaN(num) && value !== '') return num;
|
||||
try {
|
||||
return JSON.parse(value);
|
||||
} catch {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
export function buildOptions(
|
||||
el: HTMLElement,
|
||||
props: Record<string, PropDef>,
|
||||
exclude: string[] = [],
|
||||
): Record<string, unknown> {
|
||||
const opts: Record<string, unknown> = {};
|
||||
for (const [propName, spec] of Object.entries(props)) {
|
||||
if (exclude.includes(propName)) continue;
|
||||
const val = el.getAttribute(spec.attr);
|
||||
if (val === null) {
|
||||
if ('default' in spec) opts[propName] = spec.default;
|
||||
continue;
|
||||
}
|
||||
if (spec.kind === 'num') opts[propName] = Number(val);
|
||||
else if (spec.kind === 'bool-on') opts[propName] = true;
|
||||
else if (spec.kind === 'bool-off') opts[propName] = false;
|
||||
else opts[propName] = val;
|
||||
}
|
||||
return opts;
|
||||
}
|
||||
|
||||
export function registerWithParent(el: HTMLElement, obj: unknown) {
|
||||
el.dispatchEvent(
|
||||
new CustomEvent('leaflet-register', {
|
||||
detail: { leafletObject: obj, element: el },
|
||||
bubbles: true,
|
||||
composed: true,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
export function updateViaSetter(obj: Record<string, unknown>, name: string, value: unknown) {
|
||||
const prop = camelCase(name);
|
||||
const setter = `set${prop.charAt(0).toUpperCase()}${prop.slice(1)}`;
|
||||
if (typeof obj[setter] === 'function') {
|
||||
(obj[setter] as (v: unknown) => void)(value ?? parseAttributeValue(name));
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,43 @@
|
||||
export type NumProp = {
|
||||
kind: 'num';
|
||||
attr: string;
|
||||
default: number;
|
||||
};
|
||||
|
||||
export type StrProp = {
|
||||
kind: 'str';
|
||||
attr: string;
|
||||
default: string;
|
||||
};
|
||||
|
||||
export type BoolOnProp = {
|
||||
kind: 'bool-on';
|
||||
attr: string;
|
||||
};
|
||||
|
||||
export type BoolOffProp = {
|
||||
kind: 'bool-off';
|
||||
attr: string;
|
||||
};
|
||||
|
||||
export type PropDef = NumProp | StrProp | BoolOnProp | BoolOffProp;
|
||||
|
||||
export type PropTypeOf<T extends PropDef> = T extends NumProp
|
||||
? number
|
||||
: T extends StrProp
|
||||
? string
|
||||
: boolean;
|
||||
|
||||
export type PropTypesFromTable<T extends Record<string, PropDef>> = {
|
||||
[K in keyof T]: PropTypeOf<T[K]>;
|
||||
};
|
||||
|
||||
export function attrToPropName<P extends Record<string, PropDef>>(
|
||||
props: P,
|
||||
attr: string,
|
||||
): keyof P | undefined {
|
||||
for (const [name, spec] of Object.entries(props) as [keyof P, PropDef][]) {
|
||||
if (spec.attr === attr) return name;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
Loading…
Reference in New Issue