Compare commits

...

2 Commits

Author SHA1 Message Date
Buddy
1914d5bf1d chore: prep 0.1.0 for npm + JSR publish
npm name `leaflet-components` is taken by another author, so the npm package
is renamed to `leaflet-web-components`; JSR stays `@buddy/leaflet-components`.
Adds the MIT `LICENSE` file (was declared but missing).

Entry split so JSR can publish with no slow types:

- `src/index.ts` is the shared/JSR entry and no longer carries any
  `declare global`.
- `src/core/globals.ts` (new) holds the `HTMLElementTagNameMap` /
  `HTMLElementEventMap` augmentations; imported only by the new npm entry
  `src/index.npm.ts` and by `test/setup.ts`, and listed in `jsr.json`'s
  `publish.exclude` so it never enters JSR's module graph.
- `package.json` `.`/`main`/`module`/`types` now point at `dist/index.npm.*`.

Every element file switches from `class extends WithProps({...})` to a
`const PROPS` (with an explicit type) plus
`const Base: LeafletElementConstructor<TheClass, typeof PROPS> = WithProps(PROPS)`,
which is what clears JSR's `unsupported-super-class-expr` /
`missing-explicit-type` errors. Adds a `Positional<T, Obj>` alias in
`props.ts` and explicit object types on the `shared-props.ts` fragments to
keep those annotations short. Empty group tables use `Record<never, never>`.

`npx jsr publish --dry-run` now reports "Success" with zero slow-type
errors; `npm run typecheck`, `lint`, `test` (76) and `build` all pass.

CLAUDE.md, docs/ and README.md updated for the rename, the entry split, and
the `const PROPS` / `const Base` pattern.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012QpbBzyzsMCzDu2nX1zVUx
2026-09-08 21:44:20 -07:00
Buddy
d753fd82b5 refactor: split element classes from customElements.define
Every component is now two modules sharing a basename:

- src/elements/leaflet-foo.ts -- `export default class LeafletFooElement
  extends WithProps(...)`, the class only, no customElements.define, no
  side effects. src/elements/index.ts is an order-free barrel.
- src/components/leaflet-foo.ts -- three lines: import the class, define
  the tag, re-export. Importing this (or src/index.ts) registers the tag.

Plugin authors can now import a class without triggering the built-in
define, to subclass it or register it under a different tag name. Package
subpath exports `leaflet-components/elements`,
`leaflet-components/elements/leaflet-foo.js`, and
`leaflet-components/components/leaflet-foo.js` map onto dist/; jsr.json
gains an `./elements` entry.

The load-bearing ordering moves from the export statements in src/index.ts
to its `./components/*` side-effect imports (the elements barrel carries no
define, so its order is free). Classes are renamed LeafletFoo ->
LeafletFooElement, including in the HTMLElementTagNameMap augmentation.

Docs (CLAUDE.md, docs/, README.md) updated for the new layout.
2026-09-08 20:59:45 -07:00
70 changed files with 2085 additions and 1321 deletions

View File

@ -24,11 +24,11 @@ Formatting runs on `oxfmt` (oxc's Prettier-compatible formatter), configured in
### Testing
Tests run under Vitest + jsdom (`test/**/*.test.ts`), with a single setup file (`test/setup.ts`) that stubs `ResizeObserver` -- jsdom doesn't implement it, and `leaflet-map.ts` constructs one unconditionally. Real Leaflet objects work fine under jsdom for everything this library actually needs to verify (option/attribute wiring, event forwarding); no browser is required. Two things worth knowing:
Tests run under Vitest + jsdom (`test/**/*.test.ts`), with a single setup file (`test/setup.ts`) that stubs `ResizeObserver` (jsdom doesn't implement it, and `leaflet-map.ts` constructs one unconditionally) and imports `src/core/globals.ts` so the ambient `HTMLElementTagNameMap` / `HTMLElementEventMap` augmentations are in scope for the whole test program (tests import element modules directly, not the npm entry that would otherwise pull them in). Real Leaflet objects work fine under jsdom for everything this library actually needs to verify (option/attribute wiring, event forwarding); no browser is required. Two things worth knowing:
- Some Leaflet DOM state (the `<img>`/`<video>` element behind an overlay, a marker's `dragging` handler) is only created in `onAdd()`, i.e. once the layer is actually added to a real map -- tests touching that state append through a `<leaflet-map>` rather than standalone.
- `test/core/with-props.test.ts` covers the `WithProps` mixin itself against a fake Leaflet-like class (no real Leaflet needed for most of it) -- the one exception is child registration (popup/tooltip/layer binding), which needs real `Popup`/`Tooltip`/`Layer` instances because `#onChildRegister` discriminates by `instanceof`, not duck typing.
- `test/load-order.test.ts` is structurally different from every other test file on purpose: it never statically imports a component module, so nothing is `customElements.define`d until it dynamically `import()`s `src/index.ts` partway through -- after building the DOM tree with plain, undefined elements first. This is the only test that reproduces a real page's actual load order (markup parsed, _then_ the deferred module script defines everything) rather than the "components already defined before any element is created" order every other test uses. That distinction is exactly what caught the `src/index.ts` export-order bug described below -- if you add a component with a similar "parent listens for a child's announcement" relationship, extend this test rather than trusting the others to catch an ordering regression, since they structurally can't.
- `test/load-order.test.ts` is structurally different from every other test file on purpose: it never statically imports a component module, so nothing is `customElements.define`d until it dynamically `import()`s `src/index.ts` partway through -- after building the DOM tree with plain, undefined elements first. This is the only test that reproduces a real page's actual load order (markup parsed, _then_ the deferred module script defines everything) rather than the "components already defined before any element is created" order every other test uses. That distinction is exactly what catches ordering bugs in the `./components/*` import sequence in `src/index.ts` -- if you add a component with a similar "parent listens for a child's announcement" relationship, extend this test rather than trusting the others to catch an ordering regression, since they structurally can't.
`test/**` is excluded from the main `tsconfig.json` (so test code never ends up in `dist/`) and typechecked separately via `tsconfig.test.json`.
@ -38,9 +38,24 @@ To preview components in a real browser, open `index.html` with any static-file
This library wraps [Leaflet.js](https://leafletjs.com/) as native Web Components (Custom Elements). Each HTML element maps 1:1 to a Leaflet object.
### `elements/` vs `components/`
Every component is split across two files with the same basename:
- **`src/elements/leaflet-foo.ts`** — a `const PROPS`, a `const Base = WithProps(PROPS)` (explicitly typed — see below), then `export default class LeafletFooElement extends Base {...}`. The class only; **no `customElements.define`**, no side effects. `src/elements/index.ts` is a barrel re-exporting all of them by name (`LeafletFooElement`), order-free because nothing here registers a tag.
- **`src/components/leaflet-foo.ts`** — three lines: `import LeafletFooElement from '../elements/leaflet-foo.ts'`, `customElements.define('leaflet-foo', LeafletFooElement)`, `export { LeafletFooElement }`. Importing this module (or `src/index.ts` / `src/index.npm.ts`) is what actually registers the tag.
Most consumers just import the package root (or a `components/*` module) and get the tags defined. The `elements/*` classes exist for plugin authors who want to subclass an element or register it under a different tag name without triggering the built-in `define`. Package subpath exports (`leaflet-web-components/elements`, `.../elements/leaflet-foo.js`, `.../components/leaflet-foo.js`) map straight onto `dist/`.
### Two package entry points: `src/index.ts` vs `src/index.npm.ts`
- **`src/index.ts`** is the shared entry: every element class, every helper, and the load-bearing `import './components/*.ts'` side effects. **No `declare global`.** This is what `jsr.json` publishes as `.`.
- **`src/index.npm.ts`** is the npm entry — `import './core/globals.ts'; export * from './index.ts';`. `package.json`'s `.`/`main`/`module`/`types` all point at its build (`dist/index.npm.*`).
- **`src/core/globals.ts`** holds the two ambient `declare global` blocks (`HTMLElementTagNameMap`, `HTMLElementEventMap`). It is imported **only** by `src/index.npm.ts` and `test/setup.ts`, and is listed in `jsr.json`'s `publish.exclude`, so it never enters JSR's module graph — JSR's "no slow types" check rejects `declare global` anywhere it can reach. npm consumers get the augmentations automatically through the package root; JSR (`jsr:@buddy/leaflet-components`) consumers do not, and add their own tag-map/event-map typing if they want it. The whole `src/` tree still sees the augmentations at build/typecheck time because `globals.ts` is under `tsconfig.json`'s `include`.
### `WithProps` mixin: `src/core/with-props.ts`
`WithProps(PROPS, options?)` is a mixin factory: it always extends `HTMLElement` internally (there's no separate base-class parameter) and returns a constructor. Each component defines a `PROPS` table (a const record mapping property names to `PropDef` descriptors from `src/core/props.ts` — kebab-cased automatically for the attribute name) and extends `WithProps(PROPS)`. The mixin handles:
`WithProps(PROPS, options?)` is a mixin factory: it always extends `HTMLElement` internally (there's no separate base-class parameter) and returns a constructor typed `LeafletElementConstructor<TObj, TProps>`. Each element class (in `src/elements/`) defines a `PROPS` table (a const record mapping property names to `PropDef` descriptors from `src/core/props.ts` — kebab-cased automatically for the attribute name) and extends it. The mixin handles:
- `static observedAttributes`, derived from the PROPS table keys.
- Property getters/setters on the prototype (one `Object.defineProperty` per prop) that read the live Leaflet value when the prop defines a `get`, falling back to the attribute, then the default; setting encodes the value onto the attribute.
@ -49,40 +64,62 @@ This library wraps [Leaflet.js](https://leafletjs.com/) as native Web Components
- Every Leaflet event the created object fires is re-emitted on the element as `leaflet:<type>` (e.g. `leaflet:zoomend`, `leaflet:dragend`), with `detail` matching exactly what a real Leaflet `.on()` listener would receive (`type`/`target`/`sourceTarget` plus the event's own fields). This is generic and automatic: the private `#forwardEvents()` wraps the object's own `fire()` method, so no per-component or per-event-type registration is needed. Not bubbling — Leaflet already propagates layer events up to the map, so `<leaflet-map>` would otherwise see each one twice.
- `options.attach` controls how the element joins the component tree: `'children'` (default) registers with its parent and adopts registering descendants as layers/popups/tooltips; `'self'` (popups, tooltips, controls) registers with its parent but manages no children; `'none'` (the map, icons) does neither.
#### The `const PROPS` / `const Base` shape (JSR "no slow types")
An element file must not write `class Foo extends WithProps({ ... })` directly. JSR's fast-check rejects a call expression as a superclass ("super class expression too complex") and rejects any leaked type it can't resolve without full inference. So every element file does:
```ts
const PROPS: { lat: PropDef<number, LMap>; /* ...one line per prop... */ } = { ... };
const Base: LeafletElementConstructor<TheLeafletClass, typeof PROPS> = WithProps(PROPS /*, opts */);
export default class LeafletFooElement extends Base { ... }
```
- **`PROPS` needs an explicit type annotation.** Spell out `{ key: PropDef<T, Obj>; ... }`, using `typeof pathProps` / `typeof latLngProps` / `typeof tileLayerProps` in an intersection for the shared fragments (which now carry their own explicit types in `shared-props.ts`), and `Positional<T, Obj>` (alias in `props.ts` for `PropDef<T, Obj> & { option: false }`) for `positional()` props. `as const` alone is only enough when **every** value is a plain identifier reference (e.g. `leaflet-circle`, `leaflet-tile-layer`, `leaflet-polygon`); any inline `num(…)` / `str(…)` / `positional(…)` in the table forces the full annotation. Empty tables use `Record<never, never>` (not `Record<string, never>`, which would impose a `never` index signature on the subclass).
- **`Base` needs `: LeafletElementConstructor<TheLeafletClass, typeof PROPS>`** — without it JSR can't resolve the base's type either. `TheLeafletClass` is whatever `createLeafletObject` returns; the subclass still redeclares `declare readonly leafletObject?: X` to narrow it.
TypeScript typing for the above is opt-in per component, not part of `WithProps` itself — see "Typing a component's events" below.
### `leaflet-map`: `src/components/leaflet-map.ts`
### `leaflet-map`: `src/elements/leaflet-map.ts`
`LeafletMap` extends `WithProps(PROPS, { attach: 'none' })` like everything else, but builds its own Shadow DOM root in `connectedCallback` instead of relying on `createLeafletObject` alone, and terminates all bubbling `leaflet-register` events by calling `layer.addTo(this.map)` since it's the root of the component tree. Uses a `ResizeObserver` on the host element to call `map.invalidateSize()` automatically.
`LeafletMapElement` extends a `Base = WithProps(PROPS, { attach: 'none' })` like everything else, but builds its own Shadow DOM root in `connectedCallback` instead of relying on `createLeafletObject` alone, and terminates all bubbling `leaflet-register` events by calling `layer.addTo(this.map)` since it's the root of the component tree. Uses a `ResizeObserver` on the host element to call `map.invalidateSize()` automatically. `src/components/leaflet-map.ts` is the usual three-line `import` + `define` + re-export.
### Child component pattern
All non-map components extend `WithProps(PROPS, options?)`. To add a new component:
All non-map element classes extend a `Base = WithProps(PROPS, options?)`. To add a new component:
1. Define a `PROPS = {...}` const table mapping property names to `PropDef` entries (reuse fragments from `src/core/shared-props.ts` where they fit — `pathProps`, `latLngProps`, `tileLayerProps`, `urlProp`).
2. Declare `class LeafletFoo extends WithProps(PROPS)` implementing `createLeafletObject(options): L.Layer`, and `declare readonly leafletObject?: TheLeafletClass;` (the mixin's own inference of the object type from the PROPS table alone isn't reliable enough to skip this).
1. In `src/elements/leaflet-foo.ts`, define a `const PROPS` table mapping property names to `PropDef` entries (reuse fragments from `src/core/shared-props.ts` where they fit — `pathProps`, `latLngProps`, `tileLayerProps`, `urlProp`), **with an explicit type annotation** (see "The `const PROPS` / `const Base` shape" above).
2. In the same file, `const Base: LeafletElementConstructor<TheLeafletClass, typeof PROPS> = WithProps(PROPS /*, opts */);` then `export default class LeafletFooElement extends Base` implementing `createLeafletObject(options): L.Layer`, and `declare readonly leafletObject?: TheLeafletClass;` (the mixin's own inference of the object type from the PROPS table alone isn't reliable enough to skip this).
3. Provide a `set` function on individual `PropDef`s only where the default setter-based dispatch won't work (common for coordinate pairs — see `latLngProps` in shared-props.ts).
4. Call `customElements.define('leaflet-foo', LeafletFoo)` at the bottom.
5. Export from `src/index.ts`, and add the tag to the `HTMLElementTagNameMap` augmentation at the bottom of that file (needs its own `import type` — a re-export doesn't bind the name locally). **Export order in `src/index.ts` is load-bearing**, not cosmetic: if the new component listens for a bubbling announcement from some other tag (a `leaflet-register`-style child, or something like `leaflet-line-sync`), it must be exported _before_ that other tag. `customElements.define()` upgrades every matching element already in the document immediately, so on a real static-HTML page, whichever tag gets defined first wins the race — a child tag defined before its listening parent will fire its one-shot connect-time announcement into a parent that doesn't exist yet, and that announcement is gone for good. See the comment at the top of `index.ts` for the full ordering and worked example.
4. Add `src/components/leaflet-foo.ts`: `import LeafletFooElement from '../elements/leaflet-foo.ts';` then `customElements.define('leaflet-foo', LeafletFooElement);` then `export { LeafletFooElement };`.
5. Add `LeafletFooElement` to the `src/elements/index.ts` barrel (order-free), add a side-effect `import './components/leaflet-foo.ts';` to `src/index.ts`, and add the tag to the `HTMLElementTagNameMap` augmentation in `src/core/globals.ts` (npm-only; imports the class names from `../elements/index.ts`). **The order of the `./components/*` imports in `src/index.ts` is load-bearing**, not cosmetic: if the new component listens for a bubbling announcement from some other tag (a `leaflet-register`-style child, or something like `leaflet-line-sync`), its `import` must come _before_ that other tag's. `customElements.define()` upgrades every matching element already in the document immediately, so on a real static-HTML page, whichever tag gets defined first wins the race — a child tag defined before its listening parent will fire its one-shot connect-time announcement into a parent that doesn't exist yet, and that announcement is gone for good. See the comment at the top of `index.ts` for the full ordering and worked example. (The `elements/*` modules and the `elements/index.ts` barrel carry no `define`, so their order never matters.)
6. If the component fires meaningful Leaflet events (beyond nothing), compose or reuse an event map in `src/core/event-types.ts` and add `declare addEventListener: LeafletAddEventListener<TheEvents>;` / `declare removeEventListener: LeafletRemoveEventListener<TheEvents>;` (see "Typing a component's events" below).
### Special cases
- **`leaflet-polygon`** / **`leaflet-polyline`** take their vertices from `<leaflet-line>` children rather than an attribute. This is purely event-driven, not a lookup: `<leaflet-line>` fires `leaflet-line-sync` (on connect and on every lat/lng change) and `leaflet-line-remove` (on disconnect) on itself, each carrying its own position (`src/core/register.ts`); the polygon/polyline never reads a child's property or queries the DOM for them. `src/core/vertex-tracker.ts`'s `VertexTracker` (shared by both) turns that event stream into an ordered coordinate list, inserting a newly-registered vertex at its actual document position via `compareDocumentPosition` rather than assuming registration order matches DOM order. One non-obvious wrinkle `<leaflet-line>` has to work around: `disconnectedCallback` fires _after_ a node is already detached from its parent, so a bubbling dispatch from the node itself has nowhere to go on removal — it caches `parentNode` in `connectedCallback` and dispatches `leaflet-line-remove` from that cached reference instead.
- **`leaflet-popup`** / **`leaflet-tooltip`**: content comes from `innerHTML`, not attributes. `leaflet-popup` watches for DOM mutations to keep Leaflet in sync.
- **`leaflet-layer-group`** / **`leaflet-feature-group`**: passthrough containers built with `WithProps({})` (an empty props table) — they have no options of their own, but still get the standard lifecycle, child registration, and `leaflet:` event forwarding for free. Children register themselves into them via the standard bubble mechanism.
- **`leaflet-layer-group`** / **`leaflet-feature-group`**: passthrough containers built from an empty props table (`const PROPS: Record<never, never> = {}`) — they have no options of their own, but still get the standard lifecycle, child registration, and `leaflet:` event forwarding for free. Children register themselves into them via the standard bubble mechanism.
### Typing a component's events: `src/core/event-types.ts`
Two separate TypeScript augmentations make the components usable from TS, neither of which costs anything at runtime:
- **`HTMLElementTagNameMap`** (bottom of `src/index.ts`) maps every `leaflet-*` tag to its class, so `document.createElement`/`querySelector` infer the right type. Since `export { X } from '...'` re-exports don't bind `X` locally, the tag map needs its own `import type` of each class alongside the re-export.
- **`HTMLElementTagNameMap`** (in `src/core/globals.ts`, alongside the `HTMLElementEventMap` augmentation for the internal bubbling events) maps every `leaflet-*` tag to its `LeafletFooElement` class, so `document.createElement`/`querySelector` infer the right type. `globals.ts` is npm-only (imported by `src/index.npm.ts` and `test/setup.ts`, excluded from JSR) — see "Two package entry points" above.
- **Per-component `addEventListener`/`removeEventListener`** typing for `leaflet:<name>` events. `event-types.ts` defines small reusable event-name → Leaflet-payload-type fragments (`MouseEvents`, `PopupBindEvents`, `DragEvents`, etc. — mirroring how `shared-props.ts` shares prop fragments), composed per family (`PathEvents`, `MarkerEvents`, `MapEvents`, `TileLayerEvents`, `DivOverlayLayerEvents`, `GroupEvents`). A component applies its family with `declare addEventListener: LeafletAddEventListener<TheEvents>;` (and the `Remove` counterpart), the same `declare`-to-narrow-without-runtime-code idiom as `declare readonly leafletObject?: X`. Components that don't fire meaningful custom events (controls, icons, `leaflet-line`) skip this and keep the default `HTMLElementEventMap` typing.
`LeafletAddEventListener`/`LeafletRemoveEventListener` (in `with-props.ts`) deliberately have no generic `(type: string, ...)` fallback overload, unlike the real DOM API — a fallback would silently accept any unrecognized `leaflet:*` name too, which defeats the point of typing this at all. The cost is that a genuinely dynamic (non-literal) event name string needs a cast.
If you add or change what events a component fires, keep `#forwardEvents`'s `detail` shape (`with-props.ts`) in mind: it mirrors Leaflet's own `Evented#fire` merge (original data plus `type`/`target`/`sourceTarget`) so the event-types.ts payload types stay honest — don't type an event's `detail` against a Leaflet interface it wouldn't actually match at runtime.
### Output
### Output & dual publish
`tsc` compiles `src/` → `dist/` as individual ESM modules (`.js` + `.d.ts` + `.d.ts.map`) — no bundling step. Consumers import `dist/index.js` (or any individual module) directly; there is no CJS or UMD build. Leaflet is always external (never bundled). Imports within source use `.ts` extensions; `rewriteRelativeImportExtensions` in tsconfig strips them to `.js` in the tsc output (`tsconfig.json:16`).
`tsc` compiles `src/` → `dist/` as individual ESM modules (`.js` + `.d.ts` + `.d.ts.map`) — no bundling step, so `dist/elements/` and `dist/components/` mirror `src/`. There is no CJS or UMD build. Leaflet is always external (never bundled). Imports within source use `.ts` extensions; `rewriteRelativeImportExtensions` in tsconfig strips them to `.js` in the emitted `.js` (the `.d.ts` keep `.ts` specifiers, which TS resolves to the sibling `.d.ts`).
Two registries, different entry files (both pinned to the same version — keep them in step):
| Registry | Package name | Entry | Ships |
| -------- | --------------------------- | --------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| npm | `leaflet-web-components` | `package.json` `.`/`main`/`module`/`types` → `dist/index.npm.*` | compiled `dist/` + `README.md` + `LICENSE` (`files` field); `prepublishOnly` runs `build` |
| JSR | `@buddy/leaflet-components` | `jsr.json` `exports` → `./src/index.ts` (+ `./elements`) | TypeScript source directly, minus `jsr.json`'s `publish.exclude` (which drops `src/index.npm.ts`, `src/core/globals.ts`, `test/`, `docs/`, `dist/`, configs) |
The npm entry (`src/index.npm.ts`) adds the `declare global` augmentations via `src/core/globals.ts`; the JSR entry (`src/index.ts`) can't, because JSR's "no slow types" check forbids `declare global` in its published graph. That constraint is also why every element file uses the explicitly-typed `const PROPS` / `const Base` shape (see the `WithProps` section). `npx jsr publish --dry-run` is the authoritative check; it must print "Success" with no slow-type errors.

21
LICENSE Normal file
View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Buddy Sandidge
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -1,26 +1,37 @@
# leaflet-components
# leaflet-web-components
[Leaflet.js](https://leafletjs.com/) as native Web Components (Custom Elements). Each HTML element maps 1:1 to a Leaflet object with reactive attribute binding.
## Installation
```bash
npm install leaflet-components
npm install leaflet-web-components leaflet
```
Also published to JSR as [`@buddy/leaflet-components`](https://jsr.io/@buddy/leaflet-components) (`deno add jsr:@buddy/leaflet-components`). `leaflet` is always a peer dependency you install yourself; there is no CommonJS or UMD build. The examples below use the npm name — substitute `@buddy/leaflet-components` if you pull from JSR.
## Import options
The package is ESM-only — `tsc` emits `dist/` as individual modules, one per component, with no bundling step. Deep imports work for registering only what you use.
```js
// Registers all components
import 'leaflet-components';
import 'leaflet-web-components';
// Deep import — register only one component
import 'leaflet-components/dist/components/leaflet-marker.js';
// Register only one component (defines the <leaflet-marker> tag)
import 'leaflet-web-components/components/leaflet-marker.js';
```
`leaflet` is always an external dependency — you must install it yourself. There is no CommonJS or UMD build.
Each component is two modules with the same basename: `components/leaflet-marker.js` is the side-effecting one that calls `customElements.define()`, and `elements/leaflet-marker.js` is just the class (`default` export, **no** `define`). Import from `elements/` when you want to subclass a component or register it under a different tag name:
```js
// The class only — nothing is registered
import LeafletMarkerElement from 'leaflet-web-components/elements/leaflet-marker.js';
// …or the whole set, by name
import { LeafletMarkerElement, LeafletCircleElement } from 'leaflet-web-components/elements';
```
On npm the package root resolves to a build that also installs the ambient TypeScript augmentations (`HTMLElementTagNameMap` so `document.querySelector('leaflet-map')` is typed, and the custom-event map). The JSR build omits those — JSR's type rules disallow global augmentation — so from JSR you add your own if you want them.
## Usage
@ -28,7 +39,7 @@ Import once to register all custom elements, then use them declaratively in HTML
```html
<script type="module">
import 'leaflet-components';
import 'leaflet-web-components';
</script>
<leaflet-map lat="51.505" lng="-0.09" zoom="13" style="height:400px">
@ -594,20 +605,34 @@ This library's own components are built from a small toolkit — a mixin, some p
### The pattern
1. Describe your attributes as a `PROPS` table, then extend `WithProps(PROPS, options?)`.
1. Describe your attributes as a `const PROPS` table, build a base class with `const Base = WithProps(PROPS, options?)`, then `extends Base`.
2. Implement `createLeafletObject(options)`, returning whatever Leaflet object your plugin provides.
3. `declare readonly leafletObject?: TheType;` — `WithProps`'s own inference of the object type from the `PROPS` table alone isn't reliable enough to skip this (every component in this package does it).
4. Call `customElements.define('my-plugin-layer', MyPluginLayer)`.
4. Call `customElements.define('my-plugin-layer', MyPluginLayer)`. (If you want to let _your_ consumers subclass or re-register, mirror this package's split: put the class in its own module as a `default` export and keep the `define()` call in a separate side-effecting module.)
```ts
import { MyClusterGroup, type MyClusterGroupOptions } from 'some-leaflet-plugin';
import { WithProps, bool, num } from 'leaflet-components';
import {
WithProps,
bool,
num,
type PropDef,
type LeafletElementConstructor,
} from 'leaflet-web-components';
class MyClusterLayer extends WithProps({
const PROPS: {
radius: PropDef<number>;
disableClusteringAtZoom: PropDef<number>;
spiderfy: PropDef<boolean>;
} = {
radius: num(80),
disableClusteringAtZoom: num(18),
spiderfy: bool(true),
}) {
};
const Base: LeafletElementConstructor<MyClusterGroup, typeof PROPS> = WithProps(PROPS);
class MyClusterLayer extends Base {
declare readonly leafletObject?: MyClusterGroup;
createLeafletObject(options: MyClusterGroupOptions): MyClusterGroup {
@ -618,6 +643,13 @@ class MyClusterLayer extends WithProps({
customElements.define('my-cluster-layer', MyClusterLayer);
```
The two `const`s with explicit type annotations — rather than
`class X extends WithProps({ ... })` inline — are what lets this package
publish to JSR, whose type checker rejects a call expression as a superclass
and any public type it can't resolve without full inference. If you're only
consuming the package in an app (not publishing your component to JSR), the
inline `extends WithProps({ ... })` form works too.
That's it — no other integration point is needed. `WithProps` handles `observedAttributes`, attribute↔property sync, building the options object from attributes on connect, dispatching attribute changes to the matching Leaflet setter (or a `set` you provide per prop, for anything a setter can't handle), and re-emitting every event your object fires as `leaflet:<type>`.
### Attribute builders (`PROPS` table entries)
@ -636,19 +668,35 @@ Each builder's `opts` can include `set(obj, value, el)` (called on attribute cha
### Reusing the built-in fragments
Common attribute groups are already factored out and exported: `pathProps` (Leaflet `Path` styling — color, weight, dashes, fill, etc.), `latLngProps` (a synced lat/lng pair, for anything positioned on the map), `tileLayerProps` (the base `GridLayer`/`TileLayer` options), and `urlProp`. A custom vector layer plugin, for instance, can just spread `pathProps` in instead of redeclaring styling attributes:
Common attribute groups are already factored out and exported: `pathProps` (Leaflet `Path` styling — color, weight, dashes, fill, etc.), `latLngProps` (a synced lat/lng pair, for anything positioned on the map), `tileLayerProps` (the base `GridLayer`/`TileLayer` options), and `urlProp`. Each is exported with an explicit object type, so a `PROPS` annotation can pull it in with `typeof`. A custom vector layer plugin, for instance, can just spread `pathProps` in instead of redeclaring styling attributes:
```ts
import { WithProps, pathProps, positional, json } from 'leaflet-components';
import {
WithProps,
pathProps,
positional,
json,
type Positional,
type LeafletElementConstructor,
} from 'leaflet-web-components';
class MyShapeLayer extends WithProps({
const PROPS: typeof pathProps & {
data: Positional<MyData | null>;
} = {
...pathProps,
data: positional(json(null)),
}) {
data: positional(json<MyData | null>(null)),
};
const Base: LeafletElementConstructor<MyShape, typeof PROPS> = WithProps(PROPS);
class MyShapeLayer extends Base {
/* ... */
}
```
`Positional<T, Obj>` is the exported alias for a `positional()` prop's type
(`PropDef<T, Obj> & { option: false }`).
### Nesting into the tree
By default (`attach: 'children'`, the default when you omit `options`), your component registers itself with its nearest ancestor and accepts registering descendants as child layers/popups/tooltips. Use `attach: 'self'` for something that has a parent but manages no children of its own (a popup, a tooltip, a control); use `attach: 'none'` for something that's neither (an icon).
@ -665,16 +713,17 @@ import {
type LeafletAddEventListener,
type LeafletRemoveEventListener,
type PathEvents,
} from 'leaflet-components';
} from 'leaflet-web-components';
class MyShapeLayer extends WithProps({/* ... */}) {
// Base = WithProps(PROPS), as in the previous example
class MyShapeLayer extends Base {
declare addEventListener: LeafletAddEventListener<PathEvents>;
declare removeEventListener: LeafletRemoveEventListener<PathEvents>;
/* ... */
}
```
`event-types.ts`'s fragments (`MouseEvents`, `PopupBindEvents`, `DragEvents`, `TileEvents`, ...) and their compositions (`PathEvents`, `MarkerEvents`, `TileLayerEvents`, `GroupEvents`, `MapEvents`, ...) are all exported for reuse; compose your own if your plugin fires events none of them cover. If you also want `document.createElement('my-cluster-layer')` to infer your class, augment `HTMLElementTagNameMap` the same way this package does for its own tags:
`event-types.ts`'s fragments (`MouseEvents`, `PopupBindEvents`, `DragEvents`, `TileEvents`, ...) and their compositions (`PathEvents`, `MarkerEvents`, `TileLayerEvents`, `GroupEvents`, `MapEvents`, ...) are all exported for reuse; compose your own if your plugin fires events none of them cover. If you also want `document.createElement('my-cluster-layer')` to infer your class, augment `HTMLElementTagNameMap`:
```ts
declare global {
@ -684,12 +733,14 @@ declare global {
}
```
This package keeps its own version of that augmentation in a dedicated module (`src/core/globals.ts`) that its npm entry imports and its JSR entry doesn't — JSR disallows `declare global`. If you publish your plugin to JSR, do the same: keep the augmentation out of your JSR entry's module graph.
### Custom marker icons
`<leaflet-marker>` listens for a generic `icon-changed` event and calls `setIcon()` with whatever `detail.icon` holds — it doesn't check which component fired it. A component wrapping a plugin that provides its own icon (e.g. a themed marker icon set) just needs to call `emitIconChanged`:
```ts
import { emitIconChanged } from 'leaflet-components';
import { emitIconChanged } from 'leaflet-web-components';
// after building or updating your icon:
emitIconChanged(this, myPluginIcon);

View File

@ -7,21 +7,61 @@ Every `leaflet-*` custom element maps 1:1 to a single Leaflet object — a
element owns that object for its connected lifetime, holds the only reference
to it, and exposes it as `element.leafletObject`.
Nothing about the wrapping is per-object hand-written plumbing. A component
file is small (often 30–60 lines): a table of property descriptors, a
`createLeafletObject()` that calls one Leaflet constructor, a couple of
`declare` lines for types, and `customElements.define()`. Everything else —
attributes, option building, two-way sync, event forwarding, tree membership
— comes from the `WithProps` mixin.
Nothing about the wrapping is per-object hand-written plumbing. An element
file is small: an explicitly-typed `const PROPS` table of property
descriptors, a `const Base = WithProps(PROPS)`, then a class with a
`createLeafletObject()` that calls one Leaflet constructor and a couple of
`declare` lines for types. Everything else — attributes, option building,
two-way sync, event forwarding, tree membership — comes from the `WithProps`
mixin.
## `elements/` and `components/`
Each component is two files sharing a basename:
- **`src/elements/leaflet-foo.ts`** exports `default class LeafletFooElement
extends Base` (where `const Base = WithProps(PROPS)`) — the class alone, no
side effects. Import it (or the `src/elements/index.ts` barrel, which
re-exports every class by name) to get the constructor **without**
registering a tag; useful for subclassing or defining it under a different
name.
- **`src/components/leaflet-foo.ts`** is three lines: import the class,
`customElements.define('leaflet-foo', LeafletFooElement)`, re-export it.
Importing this module (or `src/index.ts` / `src/index.npm.ts`, which import
all of them in a load-bearing order — see [06](./06-load-order.md)) is what
registers the tag.
`package.json` maps `leaflet-web-components/elements`,
`.../elements/leaflet-foo.js` and `.../components/leaflet-foo.js` onto the
matching `dist/` files.
### Two package entry points
`src/index.ts` is the shared entry (all classes + the load-bearing
`./components/*` side effects, **no `declare global`**) and is what `jsr.json`
publishes. `src/index.npm.ts` is the npm entry: it re-exports `./index.ts`
**and** imports `src/core/globals.ts`, which carries the two ambient
`declare global` blocks. `globals.ts` is imported only by the npm entry (and
`test/setup.ts`) and is excluded from the JSR tarball, because JSR's "no slow
types" check rejects `declare global` anywhere in its module graph. See
[07](./07-tooling-and-build.md).
## The `WithProps` mixin
`src/core/with-props.ts`. `WithProps(PROPS, options?)` is a mixin **factory**:
it always extends `HTMLElement` internally (there is no base-class parameter)
and returns a constructor. A component does:
and returns a constructor typed `LeafletElementConstructor<TObj, TProps>`. An
element file does:
```ts
export class LeafletMarker extends WithProps(PROPS) {
const PROPS: typeof latLngProps & {
title: PropDef<string, Marker>;
/* ...one line per prop... */
} = { ...latLngProps, title: str('', { set: /* ... */ }), /* ... */ };
const Base: LeafletElementConstructor<Marker, typeof PROPS> = WithProps(PROPS);
export default class LeafletMarkerElement extends Base {
declare readonly leafletObject?: Marker;
createLeafletObject(options: MarkerOptions): Marker {
return new Marker([this.lat, this.lng], options);
@ -33,6 +73,21 @@ export class LeafletMarker extends WithProps(PROPS) {
(see [02](./02-props-and-attributes.md)). From that table alone the mixin
derives everything below.
### Why `const PROPS` / `const Base`, both explicitly typed
`class Foo extends WithProps({ ... })` is not allowed: JSR's fast-check
rejects a call expression as a superclass, and rejects any leaked type it
can't resolve without full type inference. So each file hoists the table to
`const PROPS` **with an explicit type annotation**, then
`const Base: LeafletElementConstructor<TheLeafletClass, typeof PROPS> =
WithProps(PROPS)`, then `extends Base`. The shared fragments in
`shared-props.ts` (`pathProps`, `latLngProps`, `tileLayerProps`, `urlProp`)
carry their own explicit types so a `PROPS` annotation can reference them via
`typeof`; `Positional<T, Obj>` (in `props.ts`) is the alias for a
`positional()` prop's type. `as const` with no annotation works only when
every table value is a bare identifier reference. This is a JSR constraint,
not a TypeScript one — see [07](./07-tooling-and-build.md).
### What the generated class does
- **`static observedAttributes`** — the kebab-cased attribute name of every
@ -82,10 +137,10 @@ derives everything below.
The prop table drives code generation (`observedAttributes`, the accessor
descriptors) that has to exist on the class _before_ any instance. A factory
that closes over the resolved table and defines accessors on
`Class.prototype` is the natural shape for that. `WithProps({})` — an empty
table — is still a useful base: `leaflet-layer-group` and
`leaflet-feature-group` use it to get lifecycle, child registration and event
forwarding with no options of their own.
`Class.prototype` is the natural shape for that. An empty table
(`const PROPS: Record<never, never> = {}`) is still a useful base:
`leaflet-layer-group` and `leaflet-feature-group` use it to get lifecycle,
child registration and event forwarding with no options of their own.
### Duck typing, deliberately
@ -97,8 +152,9 @@ anything about the concrete class.
## `leaflet-map` is special
`src/components/leaflet-map.ts`. It still extends `WithProps(PROPS)` with
`attach: 'none'`, but additionally:
`src/elements/leaflet-map.ts`. `LeafletMapElement` still extends a
`Base = WithProps(PROPS, { attach: 'none' })` like every other element, but
additionally:
- builds its own **Shadow DOM** in `connectedCallback` (a `<div>` container
for Leaflet, a `<style>` for `:host`, and a `<link>` to Leaflet's CSS),

View File

@ -32,11 +32,19 @@ Instead of writing `decode`/`encode` by hand, components call a factory:
| `disabled(opts?)` | the inverse of `bool(true)`: attribute named `disable-<kebab>`, `<leaflet-map disable-dragging>` reads as `dragging === false` |
| `json<T>(default, opts?)` | `JSON.parse` ↔ `JSON.stringify` — bounds, icon sizes/anchors, GeoJSON data |
`positional(def)` wraps any of the above to set `option: false`.
`positional(def)` wraps any of the above to set `option: false`. Its result
type is aliased as `Positional<T, Obj>` (= `PropDef<T, Obj> & { option:
false }`) in `props.ts`, for use in the explicit `const PROPS` annotations
each element file needs (see [01](./01-architecture.md) and
[07](./07-tooling-and-build.md)).
## Shared fragments
`src/core/shared-props.ts` — spread these into a `PROPS` table:
`src/core/shared-props.ts` — spread these into a `PROPS` table. Each is
exported with an **explicit object type** (not just `as const`), so a
`PROPS` annotation can pull it in via `typeof pathProps` / `typeof
latLngProps` / `typeof tileLayerProps` without tripping JSR's slow-type
check:
- **`latLngProps`** (`lat`, `lng`) — the coordinate pair, shared by marker,
circle, circle-marker, popup, tooltip. Both are `positional` (passed to the

View File

@ -63,14 +63,17 @@ A component narrows its listener types with a `declare` field — the same
zero-runtime idiom as `declare readonly leafletObject?: Marker`:
```ts
class LeafletCircle extends WithProps(PROPS) {
class LeafletCircleElement extends Base {
declare addEventListener: LeafletAddEventListener<PathEvents>;
declare removeEventListener: LeafletRemoveEventListener<PathEvents>;
}
```
Components that fire nothing meaningful (controls, icons, `leaflet-line`)
skip this and keep the default `HTMLElementEventMap` typing.
skip this and keep the default `HTMLElementEventMap` typing — which, for the
internal bubbling events (`leaflet-register`, `icon-changed`,
`leaflet-line-sync`, …), is itself an augmentation living in
`src/core/globals.ts` (npm-only; see [07](./07-tooling-and-build.md)).
### Why no string fallback overload

View File

@ -5,7 +5,7 @@ prop table alone.
## `leaflet-map` — shadow DOM, CSS, resize
`src/components/leaflet-map.ts`.
`src/elements/leaflet-map.ts`.
- **Shadow root** built in `connectedCallback` (not via
`createLeafletObject`): a `<div>` at `100% × 100%` for Leaflet to render
@ -28,7 +28,7 @@ prop table alone.
## `leaflet-polygon` / `leaflet-polyline` — vertices from children
`src/components/leaflet-polygon.ts`, `leaflet-polyline.ts`,
`src/elements/leaflet-polygon.ts`, `leaflet-polyline.ts`,
`src/core/vertex-tracker.ts`.
Vertices come from `<leaflet-line>` children, **event-driven, never a
@ -52,7 +52,7 @@ reference instead (`emitLineRemove(from, el)` in `register.ts`).
## `leaflet-popup` / `leaflet-tooltip` — content is markup
`src/components/leaflet-popup.ts`, `leaflet-tooltip.ts`.
`src/elements/leaflet-popup.ts`, `leaflet-tooltip.ts`.
- Content is `this.innerHTML`, passed as the `content` option, not an
attribute.
@ -65,8 +65,11 @@ reference instead (`emitLineRemove(from, el)` in `register.ts`).
## `leaflet-layer-group` / `leaflet-feature-group` — passthrough
`WithProps({})` — an empty prop table (`new LayerGroup([])` /
`new FeatureGroup([])`). No options of their own, but they still get the full
`const PROPS: Record<never, never> = {}` — an empty prop table
(`new LayerGroup([])` / `new FeatureGroup([])`). `Record<never, never>`, not
`Record<string, never>`: the latter would put a `never` string-index
signature on the generated instance type that the subclass's own members
can't satisfy. No options of their own, but they still get the full
lifecycle, child registration (`attach: 'children'`), and `leaflet:` event
forwarding. A descendant layer's `leaflet-register` is claimed by the mixin's
own `#onChildRegister` (`Layer` + parent has `addLayer` → `obj.addLayer`),
@ -75,7 +78,7 @@ registers with _its_ parent, so a group can nest in a group.
## `leaflet-control-layers` — dual role
`src/components/leaflet-control-layers.ts`. `attach: 'self'` (it's a control —
`src/elements/leaflet-control-layers.ts`. `attach: 'self'` (it's a control —
registers with the map, no children through the standard path), but it _also_
attaches its own `leaflet-register` listener to intercept its child layer
entries (`<… name="OSM" type="base" active>`): `addBaseLayer` when
@ -88,14 +91,14 @@ only dispatcher.)
## `leaflet-geojson` — style nesting
`src/components/leaflet-geojson.ts`. Extends `pathProps`, but GeoJSON takes
`src/elements/leaflet-geojson.ts`. Extends `pathProps`, but GeoJSON takes
style options nested under a `style` key so they apply to each generated
feature: `new GeoJSON(data, { style: options })`. `data` is `positional` +
`json`; its `set` does `clearLayers()` then `addData(value)`.
## `leaflet-tile-layer-wms` — extensible CRS
`src/components/leaflet-tile-layer-wms.ts`.
`src/elements/leaflet-tile-layer-wms.ts`.
- The `crs` **attribute** only covers the four CRSes Leaflet ships by name
(`EPSG3857`, `EPSG4326`, `EPSG3395`, `Simple`) via a `NAMED_CRS` lookup.

View File

@ -2,9 +2,14 @@
## The rule
**Export order in `src/index.ts` is load-bearing.** A component that listens
for a bubbling announcement from another tag must be exported — and therefore
`customElements.define()`d — **before** that other tag.
**The order of the `./components/*` side-effect imports in `src/index.ts` is
load-bearing.** A component that listens for a bubbling announcement from
another tag must be imported — and therefore `customElements.define()`d —
**before** that other tag.
(Only the `./components/*` modules call `customElements.define`. The element
classes themselves live in `src/elements/*` and the `src/elements/index.ts`
barrel; those carry no side effect, so their order is always free.)
## Why
@ -14,7 +19,9 @@ in the document **immediately and synchronously**, running
On a real static-HTML page the markup is fully parsed before the deferred
module script runs, so at `define()` time the elements already exist. The
first `define()` for a given tag wins the race:
first `define()` for a given tag wins the race, and that ordering is fixed by
the sequence of `import './components/leaflet-*.ts'` statements in
`src/index.ts`:
- If a **child** tag is defined before its listening **parent** tag, every
instance of that child in the page upgrades and fires its one-shot
@ -32,29 +39,34 @@ So parents must be defined first.
Root to leaf (this is the comment at the top of the file, kept in sync):
```
LeafletMap ← nothing can register before the root exists
LeafletControlLayers, LeafletLayerGroup,
LeafletFeatureGroup ← listen for leaflet-register from arbitrary layers
LeafletMapElement ← nothing can register before the root exists
LeafletControlLayersElement, LeafletLayerGroupElement,
LeafletFeatureGroupElement ← listen for leaflet-register from arbitrary layers
every concrete layer type (Marker, Circle,
Polygon, TileLayer, …)
LeafletLine ← child of Polygon/Polyline
LeafletPopup, LeafletTooltip ← child of any layer
LeafletIcon, LeafletDivIcon ← child of Marker
LeafletLineElement ← child of Polygon/Polyline
LeafletPopupElement, LeafletTooltipElement ← child of any layer
LeafletIconElement, LeafletDivIconElement ← child of Marker
```
Standalone controls (`LeafletControlZoom`, `LeafletControlAttribution`,
`LeafletControlScale`) have no such relationship and can go anywhere.
Standalone controls (`LeafletControlZoomElement`,
`LeafletControlAttributionElement`, `LeafletControlScaleElement`) have no such
relationship and can go anywhere.
The core re-exports (`register.ts`, `props.ts`, `with-props.ts`,
`shared-props.ts`, `event-types.ts`) come first and carry no
`customElements.define`, so their order is free.
`shared-props.ts`, `event-types.ts`) and the `export * from
'./elements/index.ts'` come first and carry no `customElements.define`, so
their order is free.
## The `HTMLElementTagNameMap` augmentation
At the bottom of `src/index.ts`. Because `export { X } from '…'` re-exports
`X` without binding it locally, the tag map needs its **own** `import type` of
every component class alongside the re-export. Those imports are type-only,
erased at build, back no `define()` — their order doesn't matter.
Lives in `src/core/globals.ts` (not `src/index.ts`), together with the
`HTMLElementEventMap` augmentation for the internal bubbling events. That
module is imported only by the npm entry `src/index.npm.ts` and by
`test/setup.ts`, and is excluded from the JSR tarball — JSR's "no slow types"
check forbids `declare global`. Its `import type { … } from
'../elements/index.ts'` is type-only, erased at build, backs no `define()` —
order doesn't matter. See [07](./07-tooling-and-build.md).
## The test that guards this

View File

@ -3,11 +3,11 @@
## Scripts
| `npm run …` | Does |
| --------------------- | -------------------------------------------------------- |
| --------------------- | ----------------------------------------------------------------------- |
| `build` | `rm -rf dist && tsc --outDir dist` |
| `typecheck` | `tsc --noEmit`, then `tsc -p tsconfig.test.json` |
| `lint` | `oxlint src test` |
| `format` | `oxfmt '*.md' 'src/**/*.{ts,js,json,md}' 'test/**/*.ts'` |
| `format` | `oxfmt '*.md' 'docs/**/*.md' 'src/**/*.{ts,js,json,md}' 'test/**/*.ts'` |
| `test` / `test:watch` | `vitest run` / `vitest` |
## TypeScript 7
@ -23,7 +23,10 @@ setup below. `tsconfig.json` highlights:
- `strict`, `isolatedModules`, `skipLibCheck`
- `include: ["src/**/*"]` only — `test/**` never reaches `dist/`. The
root-level `oxfmt.config.ts` is outside this glob too, so it's never
compiled.
compiled. Note this glob **does** pull in `src/index.npm.ts` and
`src/core/globals.ts`, so the whole `src/` tree sees the `declare global`
augmentations at build/typecheck time even though the JSR entry doesn't
import them (see "Two registries" below).
## Linting: oxlint (not ESLint)
@ -75,7 +78,11 @@ export default defineConfig({
- **`test/setup.ts`** stubs `ResizeObserver` — jsdom doesn't implement it and
`leaflet-map.ts` constructs one unconditionally, so without the stub even
_importing_ the component throws. Nothing here depends on it firing.
_importing_ the component throws. Nothing here depends on it firing. It also
`import`s `src/core/globals.ts` so the ambient `HTMLElementTagNameMap` /
`HTMLElementEventMap` augmentations are in scope for `tsconfig.test.json`
(tests import element modules directly, bypassing the npm entry that would
otherwise supply them).
- **Real Leaflet objects work under jsdom** for everything this library
verifies: option/attribute wiring, event forwarding, child binding. No
browser needed.
@ -95,23 +102,75 @@ export default defineConfig({
## Build output
`tsc` compiles `src/` → `dist/` as **individual ESM modules** — `.js` +
`.d.ts` + `.d.ts.map` per source file, no bundling step.
`.d.ts` + `.d.ts.map` per source file, no bundling step. `dist/elements/` and
`dist/components/` mirror the `src/` split one-to-one.
- Consumers import `dist/index.js` (or any single module) directly.
- Consumers import the package root (`dist/index.npm.js` on npm,
`src/index.ts` on JSR — see "Publishing" below) or any single module
directly.
- **No CJS, no UMD** build.
- **Leaflet is always external** — never bundled. It's a `dependencies` entry
and a bare `import` in the output.
- `package.json` `exports`: `.` → `dist/index.js` (+ types), plus
`./dist/*` for deep imports.
- `sideEffects: true` — the component modules call `customElements.define()`
at import time, so a bundler must not tree-shake them away.
- `package.json` `exports`: `.` → `dist/index.npm.js` (+ types — this is the
npm entry, `src/index.npm.ts` compiled; see below);
`./elements` → `dist/elements/index.js` (the class barrel, no `define`);
`./elements/*.js` and `./components/*.js` → the matching `dist/` module;
`./dist/*` still there for deep imports.
- `sideEffects: true` — the `components/*` modules (and both `index*.js`
entries) call `customElements.define()` at import time, so a bundler must
not tree-shake them away. The `elements/*` modules have no side effect.
## Publishing to two registries
| Registry | Entry | Ships |
| -------- | ------------------------------------------------- | ----------------------------------------------------------------------------- |
| npm | `package.json` `main`/`module`/`types` → `dist/…` | compiled `dist/` + `README.md` (`files` field); `prepublishOnly` runs `build` |
| JSR | `jsr.json` `exports` → `./src/index.ts` | TypeScript source directly (JSR compiles per-consumer) |
| Registry | Package name | Entry | Ships |
| -------- | --------------------------- | --------------------------------------------------------------- | -------------------------------------------------------------------------------------------- |
| npm | `leaflet-web-components` | `package.json` `.`/`main`/`module`/`types` → `dist/index.npm.*` | compiled `dist/` + `README.md` + `LICENSE` (`files` field); `prepublishOnly` runs `build` |
| JSR | `@buddy/leaflet-components` | `jsr.json` `exports` → `./src/index.ts` (+ `./elements`) | TypeScript source directly (JSR compiles per-consumer), minus `jsr.json`'s `publish.exclude` |
Both are version `0.1.0`; keep them in step. JSR publishes `src/` with its
`.ts` import extensions intact, which JSR supports natively.
Both are pinned to the same version; keep them in step. JSR publishes `src/`
with its `.ts` import extensions intact, which JSR supports natively.
### The npm/JSR entry split
The two registries resolve **different entry files**:
- **`src/index.ts`** (JSR's `.`, and the shared base) — every element class,
every helper, the load-bearing `import './components/*.ts'` side effects.
**No `declare global`.**
- **`src/index.npm.ts`** (npm's `.`) — `import './core/globals.ts'; export *
from './index.ts';`. Compiled to `dist/index.npm.js`.
- **`src/core/globals.ts`** — the two ambient `declare global` blocks
(`HTMLElementTagNameMap`, `HTMLElementEventMap`). Imported only by
`src/index.npm.ts` and `test/setup.ts`; listed in `jsr.json`'s
`publish.exclude` so it's not even uploaded to JSR.
**Why:** JSR's "no slow types" check (below) rejects `declare global` anywhere
in the module graph reachable from `jsr.json`'s `exports`. Keeping the
augmentations in a module that graph never reaches lets JSR publish with full
fast types while npm consumers still get `querySelector('leaflet-map')` /
`addEventListener('leaflet-register', …)` typing for free through the package
root. JSR (`jsr:@buddy/leaflet-components`) consumers don't get the ambient
augmentations and supply their own if they want them.
### JSR "no slow types"
JSR statically analyses the public API of what it publishes and refuses
constructs it can't resolve without a full `tsc` run. For this package that
means:
- **No `declare global`** anywhere reachable from `jsr.json`'s `exports` —
handled by the entry split above.
- **No call expression as a superclass.** `class Foo extends WithProps({…})`
is rejected; every element file uses `const Base = WithProps(PROPS)` then
`extends Base` instead.
- **Explicit types on anything that leaks into the public API.** `const PROPS`
gets a written-out `{ key: PropDef<…>; … }` annotation (or `as const` when
every value is a bare reference); `const Base` gets
`: LeafletElementConstructor<TheLeafletClass, typeof PROPS>`; the shared
fragments in `shared-props.ts` carry their own object-type annotations; the
`Positional<T, Obj>` alias in `props.ts` exists to keep those annotations
short.
`npx jsr publish --dry-run` runs the full check offline and is the gate:
it must print **"Success"** with zero slow-type errors before publishing.
Pass `--allow-dirty` to run it against an uncommitted tree.

View File

@ -12,7 +12,7 @@ top-level [`README.md`](../README.md)) and not a working cheat-sheet (that's
| [03 — Component tree & registration](./03-component-tree.md) | The `leaflet-register` bubbling protocol, `attach` modes, the other announcement events |
| [04 — Events](./04-events.md) | Re-emitting Leaflet events as `leaflet:<type>`, and how they're typed |
| [05 — Per-component special cases](./05-special-cases.md) | Where a component does something the mixin can't express generically |
| [06 — Load order](./06-load-order.md) | Why the export order in `src/index.ts` is load-bearing |
| [06 — Load order](./06-load-order.md) | Why the `./components/*` import order in `src/index.ts` is load-bearing |
| [07 — Tooling & build](./07-tooling-and-build.md) | TypeScript 7, oxlint, oxfmt, Vitest, the no-bundle build, dual publish |
## The one-paragraph version

View File

@ -1,5 +1,24 @@
{
"name": "@buddy/leaflet-components",
"version": "0.1.0",
"exports": "./src/index.ts"
"license": "MIT",
"exports": {
".": "./src/index.ts",
"./elements": "./src/elements/index.ts"
},
"publish": {
"exclude": [
"src/index.npm.ts",
"src/core/globals.ts",
"test/",
"docs/",
"demos/",
"dist/",
"index.html",
"*.config.ts",
"tsconfig*.json",
".idea/",
".claude/"
]
}
}

View File

@ -1,14 +1,26 @@
{
"name": "leaflet-components",
"name": "leaflet-web-components",
"version": "0.1.0",
"description": "LeafletJS as Web Components",
"main": "dist/index.js",
"module": "dist/index.js",
"types": "dist/index.d.ts",
"main": "dist/index.npm.js",
"module": "dist/index.npm.js",
"types": "dist/index.npm.d.ts",
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.js"
"types": "./dist/index.npm.d.ts",
"import": "./dist/index.npm.js"
},
"./elements": {
"types": "./dist/elements/index.d.ts",
"import": "./dist/elements/index.js"
},
"./elements/*.js": {
"types": "./dist/elements/*.d.ts",
"import": "./dist/elements/*.js"
},
"./components/*.js": {
"types": "./dist/components/*.d.ts",
"import": "./dist/components/*.js"
},
"./dist/*": "./dist/*",
"./package.json": "./package.json"
@ -16,7 +28,8 @@
"sideEffects": true,
"files": [
"dist",
"README.md"
"README.md",
"LICENSE"
],
"scripts": {
"build": "rm -rf dist && tsc --outDir dist",

View File

@ -1,25 +1,5 @@
import { CircleMarker, type CircleMarkerOptions } from 'leaflet';
import { num } from '../core/props.ts';
import { latLngProps, pathProps } from '../core/shared-props.ts';
import {
WithProps,
type LeafletAddEventListener,
type LeafletRemoveEventListener,
} from '../core/with-props.ts';
import type { PathEvents } from '../core/event-types.ts';
import LeafletCircleMarkerElement from '../elements/leaflet-circle-marker.ts';
export class LeafletCircleMarker extends WithProps({
...latLngProps,
radius: num<CircleMarker>(10, { get: (obj) => obj.getRadius() }),
...pathProps,
}) {
declare readonly leafletObject?: CircleMarker;
declare addEventListener: LeafletAddEventListener<PathEvents>;
declare removeEventListener: LeafletRemoveEventListener<PathEvents>;
customElements.define('leaflet-circle-marker', LeafletCircleMarkerElement);
createLeafletObject(options: CircleMarkerOptions): CircleMarker {
return new CircleMarker([this.lat, this.lng], options);
}
}
customElements.define('leaflet-circle-marker', LeafletCircleMarker);
export { LeafletCircleMarkerElement };

View File

@ -1,27 +1,5 @@
import { Circle, type CircleOptions } from 'leaflet';
import { num, positional } from '../core/props.ts';
import { latLngProps, pathProps } from '../core/shared-props.ts';
import {
WithProps,
type LeafletAddEventListener,
type LeafletRemoveEventListener,
} from '../core/with-props.ts';
import type { PathEvents } from '../core/event-types.ts';
import LeafletCircleElement from '../elements/leaflet-circle.ts';
export class LeafletCircle extends WithProps({
...latLngProps,
...pathProps,
// Leaflet has no default radius -- it throws without one -- so unlike every
// other option, this one is always passed, from the default when unset.
radius: positional(num<Circle>(1000, { get: (obj) => obj.getRadius() })),
}) {
declare readonly leafletObject?: Circle;
declare addEventListener: LeafletAddEventListener<PathEvents>;
declare removeEventListener: LeafletRemoveEventListener<PathEvents>;
customElements.define('leaflet-circle', LeafletCircleElement);
createLeafletObject(options: CircleOptions): Circle {
return new Circle([this.lat, this.lng], { ...options, radius: this.radius });
}
}
customElements.define('leaflet-circle', LeafletCircle);
export { LeafletCircleElement };

View File

@ -1,19 +1,5 @@
import { Control, type ControlPosition } from 'leaflet';
import { choice, str } from '../core/props.ts';
import { WithProps } from '../core/with-props.ts';
import LeafletControlAttributionElement from '../elements/leaflet-control-attribution.ts';
export class LeafletControlAttribution extends WithProps(
{
position: choice<ControlPosition>('bottomright'),
prefix: str(),
},
{ attach: 'self' },
) {
declare readonly leafletObject?: Control.Attribution;
customElements.define('leaflet-control-attribution', LeafletControlAttributionElement);
createLeafletObject(options: Control.AttributionOptions): Control.Attribution {
return new Control.Attribution(options);
}
}
customElements.define('leaflet-control-attribution', LeafletControlAttribution);
export { LeafletControlAttributionElement };

View File

@ -1,53 +1,5 @@
import { Control, type ControlPosition } from 'leaflet';
import { bool, choice } from '../core/props.ts';
import { WithProps } from '../core/with-props.ts';
import type { LeafletRegisterEvent } from '../core/register.ts';
import LeafletControlLayersElement from '../elements/leaflet-control-layers.ts';
export class LeafletControlLayers extends WithProps(
{
position: choice<ControlPosition>('topright'),
collapsed: bool(true),
autoZIndex: bool(true),
hideSingleBase: bool(),
sortLayers: bool(),
},
{ attach: 'self' },
) {
declare readonly leafletObject?: Control.Layers;
customElements.define('leaflet-control-layers', LeafletControlLayersElement);
createLeafletObject(options: Control.LayersOptions): Control.Layers {
return new Control.Layers({}, {}, options);
}
connectedCallback(): void {
super.connectedCallback();
this.addEventListener('leaflet-register', this.#onChildRegister);
}
disconnectedCallback(): void {
this.removeEventListener('leaflet-register', this.#onChildRegister);
super.disconnectedCallback();
}
// Every child -- present at construction or added later -- announces
// itself this way: a parent's connectedCallback always finishes before a
// child's does (even for an already-built subtree attached in one go), so
// there is no "read the children that are already here" case to handle
// separately.
#onChildRegister = (e: LeafletRegisterEvent) => {
e.stopPropagation();
const el = e.detail.element;
const layer = e.detail.leafletObject;
const name = el.getAttribute('name');
if (!name) return;
if (el.getAttribute('type') === 'base') this.leafletObject?.addBaseLayer(layer, name);
else this.leafletObject?.addOverlay(layer, name);
if (el.hasAttribute('active')) {
this.dispatchEvent(
new CustomEvent('leaflet-add-layer', { bubbles: true, detail: { layer } }),
);
}
};
}
customElements.define('leaflet-control-layers', LeafletControlLayers);
export { LeafletControlLayersElement };

View File

@ -1,22 +1,5 @@
import { Control, type ControlPosition } from 'leaflet';
import { bool, choice, num } from '../core/props.ts';
import { WithProps } from '../core/with-props.ts';
import LeafletControlScaleElement from '../elements/leaflet-control-scale.ts';
export class LeafletControlScale extends WithProps(
{
position: choice<ControlPosition>('bottomleft'),
maxWidth: num(100),
metric: bool(true),
imperial: bool(true),
updateWhenIdle: bool(),
},
{ attach: 'self' },
) {
declare readonly leafletObject?: Control.Scale;
customElements.define('leaflet-control-scale', LeafletControlScaleElement);
createLeafletObject(options: Control.ScaleOptions): Control.Scale {
return new Control.Scale(options);
}
}
customElements.define('leaflet-control-scale', LeafletControlScale);
export { LeafletControlScaleElement };

View File

@ -1,24 +1,5 @@
import { Control, type ControlPosition } from 'leaflet';
import { choice, str } from '../core/props.ts';
import { WithProps } from '../core/with-props.ts';
import LeafletControlZoomElement from '../elements/leaflet-control-zoom.ts';
// The button labels default to Leaflet's own markup, which hides the glyph
// from screen readers in favour of the title.
export class LeafletControlZoom extends WithProps(
{
position: choice<ControlPosition>('topleft'),
zoomInText: str('<span aria-hidden="true">+</span>'),
zoomInTitle: str('Zoom in'),
zoomOutText: str('<span aria-hidden="true">−</span>'),
zoomOutTitle: str('Zoom out'),
},
{ attach: 'self' },
) {
declare readonly leafletObject?: Control.Zoom;
customElements.define('leaflet-control-zoom', LeafletControlZoomElement);
createLeafletObject(options: Control.ZoomOptions): Control.Zoom {
return new Control.Zoom(options);
}
}
customElements.define('leaflet-control-zoom', LeafletControlZoom);
export { LeafletControlZoomElement };

View File

@ -1,48 +1,5 @@
import { DivIcon, type DivIconOptions, type PointExpression } from 'leaflet';
import { json, str } from '../core/props.ts';
import { emitIconChanged } from '../core/register.ts';
import { WithProps } from '../core/with-props.ts';
import LeafletDivIconElement from '../elements/leaflet-div-icon.ts';
// Like leaflet-icon, rebuilt on every change -- including changes to the
// markup, which is what the icon renders when `html` isn't set.
export class LeafletDivIcon extends WithProps(
{
iconSize: json<PointExpression>([0, 0]),
iconAnchor: json<PointExpression>([0, 0]),
popupAnchor: json<PointExpression>([0, 0]),
tooltipAnchor: json<PointExpression>([0, 0]),
className: str('leaflet-div-icon'),
html: str(),
bgPos: json<PointExpression>([0, 0]),
},
{ attach: 'none', recreate: true },
) {
declare readonly leafletObject?: DivIcon;
customElements.define('leaflet-div-icon', LeafletDivIconElement);
#observer?: MutationObserver;
createLeafletObject(options: DivIconOptions): DivIcon {
return new DivIcon(this.innerHTML ? { ...options, html: this.innerHTML } : options);
}
connectedCallback(): void {
super.connectedCallback();
this.#observer = new MutationObserver(() => {
this.recreateLeafletObject();
});
this.#observer.observe(this, { childList: true, characterData: true, subtree: true });
}
disconnectedCallback(): void {
this.#observer?.disconnect();
this.#observer = undefined;
super.disconnectedCallback();
emitIconChanged(this, null);
}
leafletObjectCreated(): void {
emitIconChanged(this, this.leafletObject);
}
}
customElements.define('leaflet-div-icon', LeafletDivIcon);
export { LeafletDivIconElement };

View File

@ -1,20 +1,5 @@
import { FeatureGroup } from 'leaflet';
import {
WithProps,
type LeafletAddEventListener,
type LeafletRemoveEventListener,
} from '../core/with-props.ts';
import type { GroupEvents } from '../core/event-types.ts';
import LeafletFeatureGroupElement from '../elements/leaflet-feature-group.ts';
// Like leaflet-layer-group, but its children share events and a bounding box.
export class LeafletFeatureGroup extends WithProps({}) {
declare readonly leafletObject?: FeatureGroup;
declare addEventListener: LeafletAddEventListener<GroupEvents>;
declare removeEventListener: LeafletRemoveEventListener<GroupEvents>;
customElements.define('leaflet-feature-group', LeafletFeatureGroupElement);
createLeafletObject(): FeatureGroup {
return new FeatureGroup([]);
}
}
customElements.define('leaflet-feature-group', LeafletFeatureGroup);
export { LeafletFeatureGroupElement };

View File

@ -1,34 +1,5 @@
import { GeoJSON, type PathOptions } from 'leaflet';
import type { GeoJsonObject } from 'geojson';
import { json, positional } from '../core/props.ts';
import { pathProps } from '../core/shared-props.ts';
import {
WithProps,
type LeafletAddEventListener,
type LeafletRemoveEventListener,
} from '../core/with-props.ts';
import type { GroupEvents } from '../core/event-types.ts';
import LeafletGeoJSONElement from '../elements/leaflet-geojson.ts';
export class LeafletGeoJSON extends WithProps({
data: positional(
json<GeoJsonObject | null>(null, {
set(obj: GeoJSON, value) {
obj.clearLayers();
if (value) obj.addData(value);
},
}),
),
...pathProps,
}) {
declare readonly leafletObject?: GeoJSON;
declare addEventListener: LeafletAddEventListener<GroupEvents>;
declare removeEventListener: LeafletRemoveEventListener<GroupEvents>;
customElements.define('leaflet-geojson', LeafletGeoJSONElement);
// Every prop but `data` is a style option, and GeoJSON takes those nested
// under `style` so they apply to each feature it builds.
createLeafletObject(options: PathOptions): GeoJSON {
return new GeoJSON(this.data, { style: options });
}
}
customElements.define('leaflet-geojson', LeafletGeoJSON);
export { LeafletGeoJSONElement };

View File

@ -1,39 +1,5 @@
import { Icon, type IconOptions, type PointExpression } from 'leaflet';
import { json, str } from '../core/props.ts';
import { emitIconChanged } from '../core/register.ts';
import { WithProps } from '../core/with-props.ts';
import LeafletIconElement from '../elements/leaflet-icon.ts';
const PROPS = {
iconUrl: str(),
iconRetinaUrl: str(),
iconSize: json<PointExpression>([0, 0]),
iconAnchor: json<PointExpression>([0, 0]),
popupAnchor: json<PointExpression>([0, 0]),
tooltipAnchor: json<PointExpression>([0, 0]),
shadowUrl: str(),
shadowRetinaUrl: str(),
shadowSize: json<PointExpression>([0, 0]),
shadowAnchor: json<PointExpression>([0, 0]),
className: str(),
} as const;
customElements.define('leaflet-icon', LeafletIconElement);
// An Icon has no setters, so every attribute change builds a new one and the
// parent marker is told to swap it in.
export class LeafletIcon extends WithProps(PROPS, { attach: 'none', recreate: true }) {
declare readonly leafletObject?: Icon;
createLeafletObject(options: Partial<IconOptions>): Icon | undefined {
return options.iconUrl ? new Icon(options as IconOptions) : undefined;
}
leafletObjectCreated(): void {
emitIconChanged(this, this.leafletObject);
}
disconnectedCallback(): void {
super.disconnectedCallback();
emitIconChanged(this, null);
}
}
customElements.define('leaflet-icon', LeafletIcon);
export { LeafletIconElement };

View File

@ -1,41 +1,5 @@
import {
ImageOverlay,
type CrossOrigin,
type ImageOverlayOptions,
type LatLngBoundsExpression,
} from 'leaflet';
import { bool, choice, json, num, positional, str } from '../core/props.ts';
import { getBounds, urlProp } from '../core/shared-props.ts';
import {
WithProps,
type LeafletAddEventListener,
type LeafletRemoveEventListener,
} from '../core/with-props.ts';
import type { PathEvents } from '../core/event-types.ts';
import LeafletImageOverlayElement from '../elements/leaflet-image-overlay.ts';
export class LeafletImageOverlay extends WithProps({
url: urlProp,
bounds: positional(json<LatLngBoundsExpression, ImageOverlay>([], { get: getBounds })),
opacity: num(1.0),
alt: str('', {
set(obj: ImageOverlay, value) {
const el = obj.getElement();
if (el) el.alt = value;
},
}),
interactive: bool(),
crossOrigin: choice<CrossOrigin>(''),
errorOverlayUrl: str(),
zIndex: num(),
className: str(),
}) {
declare readonly leafletObject?: ImageOverlay;
declare addEventListener: LeafletAddEventListener<PathEvents>;
declare removeEventListener: LeafletRemoveEventListener<PathEvents>;
customElements.define('leaflet-image-overlay', LeafletImageOverlayElement);
createLeafletObject(options: ImageOverlayOptions): ImageOverlay {
return new ImageOverlay(this.url, this.bounds, options);
}
}
customElements.define('leaflet-image-overlay', LeafletImageOverlay);
export { LeafletImageOverlayElement };

View File

@ -1,21 +1,5 @@
import { LayerGroup } from 'leaflet';
import {
WithProps,
type LeafletAddEventListener,
type LeafletRemoveEventListener,
} from '../core/with-props.ts';
import type { GroupEvents } from '../core/event-types.ts';
import LeafletLayerGroupElement from '../elements/leaflet-layer-group.ts';
// A passthrough container: it has no options of its own, and children add
// themselves to it through the standard registration bubble.
export class LeafletLayerGroup extends WithProps({}) {
declare readonly leafletObject?: LayerGroup;
declare addEventListener: LeafletAddEventListener<GroupEvents>;
declare removeEventListener: LeafletRemoveEventListener<GroupEvents>;
customElements.define('leaflet-layer-group', LeafletLayerGroupElement);
createLeafletObject(): LayerGroup {
return new LayerGroup([]);
}
}
customElements.define('leaflet-layer-group', LeafletLayerGroup);
export { LeafletLayerGroupElement };

View File

@ -1,31 +1,5 @@
import { emitLineRemove, emitLineSync } from '../core/register.ts';
import LeafletLineElement from '../elements/leaflet-line.ts';
export class LeafletLine extends HTMLElement {
static get observedAttributes() {
return ['lat', 'lng'];
}
customElements.define('leaflet-line', LeafletLineElement);
// Cached because disconnectedCallback fires after this is already detached
// from it -- see emitLineRemove.
#parent: ParentNode | null = null;
get latlng(): [number, number] {
return [+(this.getAttribute('lat') ?? 0), +(this.getAttribute('lng') ?? 0)];
}
connectedCallback(): void {
this.#parent = this.parentNode;
emitLineSync(this, this.latlng);
}
attributeChangedCallback(): void {
emitLineSync(this, this.latlng);
}
disconnectedCallback(): void {
emitLineRemove(this.#parent ?? this, this);
this.#parent = null;
}
}
customElements.define('leaflet-line', LeafletLine);
export { LeafletLineElement };

View File

@ -1,238 +1,5 @@
import { Icon, Map as LMap, type MapOptions } from 'leaflet';
import { bool, disabled, num, positional, str } from '../core/props.ts';
import {
WithProps,
type LeafletAddEventListener,
type LeafletRemoveEventListener,
} from '../core/with-props.ts';
import type { LeafletLayerEvent, LeafletRegisterEvent } from '../core/register.ts';
import type { MapEvents } from '../core/event-types.ts';
import LeafletMapElement from '../elements/leaflet-map.ts';
const DEFAULT_CSS_URL = 'https://unpkg.com/leaflet@1.9.4/dist/leaflet.css';
const DEFAULT_CSS_INTEGRITY = 'sha256-p4NxAoJBhIIN+hmNHrzRCf9tD/miZyoHS5obTRR9BMY=';
customElements.define('leaflet-map', LeafletMapElement);
interface CssHost extends HTMLElement {
applyCss(): void;
}
// The css-* attributes describe the stylesheet in the shadow root rather than
// anything about the Leaflet map, so a change just re-links it.
function relinkCss(_map: LMap, _value: string, el: HTMLElement): void {
(el as CssHost).applyCss();
}
// The root of the component tree. Every other component bubbles a
// `leaflet-register` event up to here, which is where it stops.
export class LeafletMap extends WithProps(
{
// View state. Not constructor options -- the map is positioned with setView
// once it exists -- and written back whenever the user pans or zooms.
lat: positional(
num<LMap>(0, {
event: 'moveend',
get: (map) => map.getCenter().lat,
set: (map, value) => {
map.setView([value, map.getCenter().lng], map.getZoom());
},
}),
),
lng: positional(
num<LMap>(0, {
event: 'moveend',
get: (map) => map.getCenter().lng,
set: (map, value) => {
map.setView([map.getCenter().lat, value], map.getZoom());
},
}),
),
zoom: positional(
num<LMap>(2, {
event: 'zoomend',
get: (map) => map.getZoom(),
set: (map, value) => {
map.setZoom(value);
},
}),
),
// Numeric options Leaflet lets us change after construction.
minZoom: num<LMap>(0, {
get: (map) => map.getMinZoom(),
set: (map, value) => {
map.setMinZoom(value);
},
}),
maxZoom: num<LMap>(Infinity, {
get: (map) => map.getMaxZoom(),
set: (map, value) => {
map.setMaxZoom(value);
},
}),
// Constructor-only numeric options.
zoomSnap: num(1),
zoomDelta: num(1),
keyboardPanDelta: num(80),
wheelDebounceTime: num(40),
wheelPxPerZoomLevel: num(60),
inertiaDeceleration: num(3000),
inertiaMaxSpeed: num(Infinity),
easeLinearity: num(0.2),
maxBoundsViscosity: num(0),
tapTolerance: num(15),
zoomAnimationThreshold: num(4),
transform3DLimit: num(8388608),
// Options Leaflet defaults to true, turned off with disable-* attributes.
// The interaction handlers can be toggled after construction.
scrollWheelZoom: disabled<LMap>({
set: (map, on) => (on ? map.scrollWheelZoom.enable() : map.scrollWheelZoom.disable()),
}),
dragging: disabled<LMap>({
set: (map, on) => (on ? map.dragging.enable() : map.dragging.disable()),
}),
touchZoom: disabled<LMap>({
set: (map, on) => (on ? map.touchZoom.enable() : map.touchZoom.disable()),
}),
doubleClickZoom: disabled<LMap>({
set: (map, on) => (on ? map.doubleClickZoom.enable() : map.doubleClickZoom.disable()),
}),
boxZoom: disabled<LMap>({
set: (map, on) => (on ? map.boxZoom.enable() : map.boxZoom.disable()),
}),
keyboard: disabled<LMap>({
set: (map, on) => (on ? map.keyboard.enable() : map.keyboard.disable()),
}),
closePopupOnClick: disabled(),
trackResize: disabled(),
zoomControl: disabled(),
attributionControl: disabled(),
inertia: disabled(),
zoomAnimation: disabled(),
fadeAnimation: disabled(),
markerZoomAnimation: disabled(),
bounceAtZoomLimits: disabled(),
tapHold: disabled(),
// Options Leaflet defaults to false.
preferCanvas: bool(),
worldCopyJump: bool(),
// Not Leaflet options at all -- see relinkCss above.
cssUrl: positional(str(DEFAULT_CSS_URL, { set: relinkCss })),
cssIntegrity: positional(str(DEFAULT_CSS_INTEGRITY, { set: relinkCss })),
cssCrossorigin: positional(str('', { set: relinkCss })),
},
{ attach: 'none' },
) {
declare readonly leafletObject?: LMap;
declare addEventListener: LeafletAddEventListener<MapEvents>;
declare removeEventListener: LeafletRemoveEventListener<MapEvents>;
#container?: HTMLDivElement;
#cssLink?: HTMLLinkElement;
#resizeObserver?: ResizeObserver;
createLeafletObject(options: MapOptions): LMap {
const map = new LMap(this.#container ?? this.#buildShadowRoot(), options);
// getCenter() and getZoom() throw until the view is set. Reading this.lat,
// this.lng and this.zoom here is safe for the same reason: the object
// doesn't exist yet, so the getters fall back to the attributes.
map.setView([this.lat, this.lng], this.zoom);
return map;
}
connectedCallback(): void {
this.#buildShadowRoot();
this.applyCss();
super.connectedCallback();
this.#resizeObserver = new ResizeObserver(() => this.leafletObject?.invalidateSize());
this.#resizeObserver.observe(this);
this.addEventListener('leaflet-register', this.#onRegister);
this.addEventListener('leaflet-add-layer', this.#onAddLayer);
this.addEventListener('leaflet-remove-layer', this.#onRemoveLayer);
}
disconnectedCallback(): void {
this.#resizeObserver?.disconnect();
this.#resizeObserver = undefined;
this.removeEventListener('leaflet-register', this.#onRegister);
this.removeEventListener('leaflet-add-layer', this.#onAddLayer);
this.removeEventListener('leaflet-remove-layer', this.#onRemoveLayer);
super.disconnectedCallback();
}
// Replaces the <link> in the shadow root, and derives the marker icon path
// from the same URL. Called on connect and whenever a css-* attribute
// changes. Absence and emptiness mean different things here, so this reads
// the attributes rather than the properties.
applyCss(): void {
const root = this.shadowRoot;
if (!root) return;
this.#cssLink?.remove();
this.#cssLink = undefined;
const customUrl = this.hasAttribute('css-url');
const url = customUrl ? this.getAttribute('css-url') : DEFAULT_CSS_URL;
let integrity: string | null = null;
if (this.hasAttribute('css-integrity')) {
integrity = this.getAttribute('css-integrity') ?? '';
} else if (!customUrl) {
integrity = DEFAULT_CSS_INTEGRITY;
}
let crossorigin: string | undefined;
if (this.hasAttribute('css-crossorigin')) {
crossorigin = this.getAttribute('css-crossorigin') ?? undefined;
} else if (integrity) {
crossorigin = 'anonymous';
}
const link = document.createElement('link');
link.rel = 'stylesheet';
link.href = url ?? '';
if (integrity) link.setAttribute('integrity', integrity);
if (crossorigin !== undefined) link.setAttribute('crossorigin', crossorigin);
root.append(link);
this.#cssLink = link;
Icon.Default.imagePath = url?.replace(/\/[^/]+$/u, '/images/');
}
#buildShadowRoot(): HTMLDivElement {
if (this.#container) return this.#container;
const root = this.shadowRoot ?? this.attachShadow({ mode: 'open' });
const container = document.createElement('div');
container.style.width = '100%';
container.style.height = '100%';
root.append(container);
const style = document.createElement('style');
style.textContent = ':host { display: block; width: 100%; height: 400px; }';
root.append(style);
this.#container = container;
return container;
}
#onRegister = (e: LeafletRegisterEvent) => {
e.stopPropagation();
const map = this.leafletObject;
if (map) e.detail.leafletObject.addTo(map);
};
#onAddLayer = (e: LeafletLayerEvent) => {
this.leafletObject?.addLayer(e.detail.layer);
};
#onRemoveLayer = (e: LeafletLayerEvent) => {
this.leafletObject?.removeLayer(e.detail.layer);
};
}
customElements.define('leaflet-map', LeafletMap);
export { LeafletMapElement };

View File

@ -1,62 +1,5 @@
import { Icon, Marker, type MarkerOptions } from 'leaflet';
import { bool, num, str } from '../core/props.ts';
import { latLngProps } from '../core/shared-props.ts';
import {
WithProps,
type LeafletAddEventListener,
type LeafletRemoveEventListener,
} from '../core/with-props.ts';
import type { LeafletIconChangedEvent } from '../core/register.ts';
import type { MarkerEvents } from '../core/event-types.ts';
import LeafletMarkerElement from '../elements/leaflet-marker.ts';
const PROPS = {
...latLngProps,
// title and alt end up on the <img> Leaflet renders, so live updates go there.
title: str('', {
set: (obj: Marker, value) => {
const el = obj.getElement();
if (el) el.title = value;
},
}),
alt: str('', {
set: (obj: Marker, value) => {
const el = obj.getElement() as HTMLImageElement | undefined;
if (el) el.alt = value;
},
}),
draggable: bool(false, {
set(obj: Marker, value) {
if (value) obj.dragging?.enable();
else obj.dragging?.disable();
},
}),
opacity: num(1.0),
zIndexOffset: num(),
} as const;
customElements.define('leaflet-marker', LeafletMarkerElement);
export class LeafletMarker extends WithProps(PROPS) {
declare readonly leafletObject?: Marker;
declare addEventListener: LeafletAddEventListener<MarkerEvents>;
declare removeEventListener: LeafletRemoveEventListener<MarkerEvents>;
createLeafletObject(options: MarkerOptions): Marker {
return new Marker([this.lat, this.lng], options);
}
connectedCallback(): void {
super.connectedCallback();
this.addEventListener('icon-changed', this.#onIconChanged);
}
disconnectedCallback(): void {
this.removeEventListener('icon-changed', this.#onIconChanged);
super.disconnectedCallback();
}
// A <leaflet-icon> or <leaflet-div-icon> child announces itself this way.
#onIconChanged = (e: LeafletIconChangedEvent) => {
this.leafletObject?.setIcon(e.detail.icon ?? new Icon.Default());
};
}
customElements.define('leaflet-marker', LeafletMarker);
export { LeafletMarkerElement };

View File

@ -1,49 +1,5 @@
import { Polygon, type PolylineOptions } from 'leaflet';
import { pathProps } from '../core/shared-props.ts';
import {
WithProps,
type LeafletAddEventListener,
type LeafletRemoveEventListener,
} from '../core/with-props.ts';
import type { PathEvents } from '../core/event-types.ts';
import type { LeafletLineRemoveEvent, LeafletLineSyncEvent } from '../core/register.ts';
import { VertexTracker } from '../core/vertex-tracker.ts';
import LeafletPolygonElement from '../elements/leaflet-polygon.ts';
export class LeafletPolygon extends WithProps({ ...pathProps }) {
declare readonly leafletObject?: Polygon;
declare addEventListener: LeafletAddEventListener<PathEvents>;
declare removeEventListener: LeafletRemoveEventListener<PathEvents>;
customElements.define('leaflet-polygon', LeafletPolygonElement);
#vertices = new VertexTracker();
createLeafletObject(options: PolylineOptions): Polygon {
return new Polygon(this.#vertices.coords(), options);
}
// Vertices come from <leaflet-line> children rather than an attribute --
// each one announces its own position via leaflet-line-sync/-remove, we
// never read a child's state directly.
connectedCallback(): void {
super.connectedCallback();
this.addEventListener('leaflet-line-sync', this.#onLineSync);
this.addEventListener('leaflet-line-remove', this.#onLineRemove);
}
disconnectedCallback(): void {
this.removeEventListener('leaflet-line-sync', this.#onLineSync);
this.removeEventListener('leaflet-line-remove', this.#onLineRemove);
super.disconnectedCallback();
}
#onLineSync = (e: LeafletLineSyncEvent) => {
this.#vertices.sync(e.detail.element, e.detail.latlng);
this.leafletObject?.setLatLngs(this.#vertices.coords());
};
#onLineRemove = (e: LeafletLineRemoveEvent) => {
this.#vertices.remove(e.detail.element);
this.leafletObject?.setLatLngs(this.#vertices.coords());
};
}
customElements.define('leaflet-polygon', LeafletPolygon);
export { LeafletPolygonElement };

View File

@ -1,56 +1,5 @@
import { Polyline, type PolylineOptions } from 'leaflet';
import { bool, num } from '../core/props.ts';
import { pathProps, style } from '../core/shared-props.ts';
import {
WithProps,
type LeafletAddEventListener,
type LeafletRemoveEventListener,
} from '../core/with-props.ts';
import type { PathEvents } from '../core/event-types.ts';
import type { LeafletLineRemoveEvent, LeafletLineSyncEvent } from '../core/register.ts';
import { VertexTracker } from '../core/vertex-tracker.ts';
import LeafletPolylineElement from '../elements/leaflet-polyline.ts';
export class LeafletPolyline extends WithProps({
...pathProps,
// Unlike closed shapes, a polyline is unfilled by default.
fill: bool(false, { set: style('fill') }),
smoothFactor: num(1.0),
noClip: bool(),
}) {
declare readonly leafletObject?: Polyline;
declare addEventListener: LeafletAddEventListener<PathEvents>;
declare removeEventListener: LeafletRemoveEventListener<PathEvents>;
customElements.define('leaflet-polyline', LeafletPolylineElement);
#vertices = new VertexTracker();
createLeafletObject(options: PolylineOptions): Polyline {
return new Polyline(this.#vertices.coords(), options);
}
// Vertices come from <leaflet-line> children rather than an attribute --
// each one announces its own position via leaflet-line-sync/-remove, we
// never read a child's state directly.
connectedCallback(): void {
super.connectedCallback();
this.addEventListener('leaflet-line-sync', this.#onLineSync);
this.addEventListener('leaflet-line-remove', this.#onLineRemove);
}
disconnectedCallback(): void {
this.removeEventListener('leaflet-line-sync', this.#onLineSync);
this.removeEventListener('leaflet-line-remove', this.#onLineRemove);
super.disconnectedCallback();
}
#onLineSync = (e: LeafletLineSyncEvent) => {
this.#vertices.sync(e.detail.element, e.detail.latlng);
this.leafletObject?.setLatLngs(this.#vertices.coords());
};
#onLineRemove = (e: LeafletLineRemoveEvent) => {
this.#vertices.remove(e.detail.element);
this.leafletObject?.setLatLngs(this.#vertices.coords());
};
}
customElements.define('leaflet-polyline', LeafletPolyline);
export { LeafletPolylineElement };

View File

@ -1,54 +1,5 @@
import { Popup, type PopupOptions } from 'leaflet';
import { bool, num } from '../core/props.ts';
import { latLngProps } from '../core/shared-props.ts';
import {
WithProps,
type LeafletAddEventListener,
type LeafletRemoveEventListener,
} from '../core/with-props.ts';
import type { DivOverlayLayerEvents } from '../core/event-types.ts';
import LeafletPopupElement from '../elements/leaflet-popup.ts';
export class LeafletPopup extends WithProps(
{
...latLngProps,
maxWidth: num(300),
minWidth: num(50),
maxHeight: num(),
autoPan: bool(true),
closeButton: bool(true),
autoClose: bool(true),
},
{ attach: 'self' },
) {
declare readonly leafletObject?: Popup;
declare addEventListener: LeafletAddEventListener<DivOverlayLayerEvents>;
declare removeEventListener: LeafletRemoveEventListener<DivOverlayLayerEvents>;
customElements.define('leaflet-popup', LeafletPopupElement);
#observer?: MutationObserver;
// Content is the element's markup, not an attribute. A popup only carries a
// position of its own when it isn't bound to a parent layer.
createLeafletObject(options: PopupOptions): Popup {
const popup = new Popup({ ...options, content: this.innerHTML });
if (this.hasAttribute('lat') && this.hasAttribute('lng')) {
popup.setLatLng([this.lat, this.lng]);
}
return popup;
}
connectedCallback(): void {
super.connectedCallback();
this.#observer = new MutationObserver(() => {
this.leafletObject?.setContent(this.innerHTML);
});
this.#observer.observe(this, { childList: true, characterData: true, subtree: true });
}
disconnectedCallback(): void {
this.#observer?.disconnect();
this.#observer = undefined;
super.disconnectedCallback();
}
}
customElements.define('leaflet-popup', LeafletPopup);
export { LeafletPopupElement };

View File

@ -1,24 +1,5 @@
import { Rectangle, type LatLngBoundsExpression, type PolylineOptions } from 'leaflet';
import { json, positional } from '../core/props.ts';
import { pathProps, getBounds } from '../core/shared-props.ts';
import {
WithProps,
type LeafletAddEventListener,
type LeafletRemoveEventListener,
} from '../core/with-props.ts';
import type { PathEvents } from '../core/event-types.ts';
import LeafletRectangleElement from '../elements/leaflet-rectangle.ts';
export class LeafletRectangle extends WithProps({
bounds: positional(json<LatLngBoundsExpression, Rectangle>([], { get: getBounds })),
...pathProps,
}) {
declare readonly leafletObject?: Rectangle;
declare addEventListener: LeafletAddEventListener<PathEvents>;
declare removeEventListener: LeafletRemoveEventListener<PathEvents>;
customElements.define('leaflet-rectangle', LeafletRectangleElement);
createLeafletObject(options: PolylineOptions): Rectangle {
return new Rectangle(this.bounds, options);
}
}
customElements.define('leaflet-rectangle', LeafletRectangle);
export { LeafletRectangleElement };

View File

@ -1,35 +1,5 @@
import {
SVGOverlay,
type CrossOrigin,
type ImageOverlayOptions,
type LatLngBoundsExpression,
} from 'leaflet';
import { bool, choice, json, num, positional, str } from '../core/props.ts';
import { getBounds } from '../core/shared-props.ts';
import {
WithProps,
type LeafletAddEventListener,
type LeafletRemoveEventListener,
} from '../core/with-props.ts';
import type { PathEvents } from '../core/event-types.ts';
import LeafletSVGOverlayElement from '../elements/leaflet-svg-overlay.ts';
export class LeafletSVGOverlay extends WithProps({
bounds: positional(json<LatLngBoundsExpression, SVGOverlay>([], { get: getBounds })),
opacity: num(1.0),
interactive: bool(),
crossOrigin: choice<CrossOrigin>(''),
zIndex: num(),
className: str(),
}) {
declare readonly leafletObject?: SVGOverlay;
declare addEventListener: LeafletAddEventListener<PathEvents>;
declare removeEventListener: LeafletRemoveEventListener<PathEvents>;
customElements.define('leaflet-svg-overlay', LeafletSVGOverlayElement);
createLeafletObject(options: ImageOverlayOptions): SVGOverlay {
const svg =
this.querySelector('svg') ?? document.createElementNS('http://www.w3.org/2000/svg', 'svg');
return new SVGOverlay(svg, this.bounds, options);
}
}
customElements.define('leaflet-svg-overlay', LeafletSVGOverlay);
export { LeafletSVGOverlayElement };

View File

@ -1,88 +1,5 @@
import { CRS, TileLayer, type WMSOptions, type WMSParams } from 'leaflet';
import { bool, str, type PropDef } from '../core/props.ts';
import { tileLayerProps, urlProp } from '../core/shared-props.ts';
import {
WithProps,
type LeafletAddEventListener,
type LeafletRemoveEventListener,
} from '../core/with-props.ts';
import type { TileLayerEvents } from '../core/event-types.ts';
import type { LeafletCRSChangedEvent } from '../core/register.ts';
import LeafletTileLayerWMSElement from '../elements/leaflet-tile-layer-wms.ts';
// WMS request parameters have no individual setters -- they're merged into the
// query string through setParams().
function param<T>(key: keyof WMSParams): (obj: TileLayer.WMS, value: T) => void {
return (obj, value) => {
obj.setParams({ [key]: value } as unknown as WMSParams);
};
}
customElements.define('leaflet-tile-layer-wms', LeafletTileLayerWMSElement);
// `crs` takes a CRS instance, not a primitive. The attribute only covers the
// 4 CRSes Leaflet ships by name -- a CRS Leaflet doesn't ship comes from a
// nested child announcing itself via leaflet-crs-changed instead (see
// #onCrsChanged), which takes priority over this when present. Constructor-
// only, like the rest of tileLayerProps -- Leaflet has no setter for it.
const NAMED_CRS = {
EPSG3857: CRS.EPSG3857,
EPSG4326: CRS.EPSG4326,
EPSG3395: CRS.EPSG3395,
Simple: CRS.Simple,
};
type CrsName = keyof typeof NAMED_CRS;
const crsProp: PropDef<CRS> = {
default: CRS.EPSG3857,
decode: (raw) => NAMED_CRS[raw as CrsName] ?? CRS.EPSG3857,
encode: (value) =>
value === CRS.EPSG3857
? null
: ((Object.keys(NAMED_CRS) as CrsName[]).find((name) => NAMED_CRS[name] === value) ?? null),
};
export class LeafletTileLayerWMS extends WithProps({
url: urlProp,
...tileLayerProps,
layers: str('', { set: param('layers') }),
styles: str('', { set: param('styles') }),
format: str('image/jpeg', { set: param('format') }),
transparent: bool(false, { set: param('transparent') }),
version: str('1.1.1', { set: param('version') }),
uppercase: bool(),
crs: crsProp,
}) {
declare readonly leafletObject?: TileLayer.WMS;
declare addEventListener: LeafletAddEventListener<TileLayerEvents>;
declare removeEventListener: LeafletRemoveEventListener<TileLayerEvents>;
// Set by a nested CRS-providing child; overrides the `crs` attribute's
// named lookup when present.
#childCrs?: CRS;
createLeafletObject(options: WMSOptions): TileLayer.WMS {
return new TileLayer.WMS(
this.url,
this.#childCrs ? { ...options, crs: this.#childCrs } : options,
);
}
connectedCallback(): void {
super.connectedCallback();
this.addEventListener('leaflet-crs-changed', this.#onCrsChanged);
}
disconnectedCallback(): void {
this.removeEventListener('leaflet-crs-changed', this.#onCrsChanged);
super.disconnectedCallback();
}
// A CRS Leaflet doesn't ship comes from any custom element nested here
// that fires this event -- no base class required, just this event shape
// (see register.ts). `crs` is constructor-only, so picking it up means
// rebuilding the whole layer.
#onCrsChanged = (e: LeafletCRSChangedEvent) => {
this.#childCrs = e.detail.crs ?? undefined;
this.recreateLeafletObject();
};
}
customElements.define('leaflet-tile-layer-wms', LeafletTileLayerWMS);
export { LeafletTileLayerWMSElement };

View File

@ -1,23 +1,5 @@
import { TileLayer, type TileLayerOptions } from 'leaflet';
import { tileLayerProps, urlProp } from '../core/shared-props.ts';
import {
WithProps,
type LeafletAddEventListener,
type LeafletRemoveEventListener,
} from '../core/with-props.ts';
import type { TileLayerEvents } from '../core/event-types.ts';
import LeafletTileLayerElement from '../elements/leaflet-tile-layer.ts';
export class LeafletTileLayer extends WithProps({
url: urlProp,
...tileLayerProps,
}) {
declare readonly leafletObject?: TileLayer;
declare addEventListener: LeafletAddEventListener<TileLayerEvents>;
declare removeEventListener: LeafletRemoveEventListener<TileLayerEvents>;
customElements.define('leaflet-tile-layer', LeafletTileLayerElement);
createLeafletObject(options: TileLayerOptions): TileLayer {
return new TileLayer(this.url, options);
}
}
customElements.define('leaflet-tile-layer', LeafletTileLayer);
export { LeafletTileLayerElement };

View File

@ -1,54 +1,5 @@
import { Tooltip, type Direction, type PointExpression, type TooltipOptions } from 'leaflet';
import { bool, choice, json, num, str } from '../core/props.ts';
import { latLngProps } from '../core/shared-props.ts';
import {
WithProps,
type LeafletAddEventListener,
type LeafletRemoveEventListener,
} from '../core/with-props.ts';
import type { DivOverlayLayerEvents } from '../core/event-types.ts';
import LeafletTooltipElement from '../elements/leaflet-tooltip.ts';
export class LeafletTooltip extends WithProps(
{
...latLngProps,
pane: str(),
offset: json<PointExpression>([0, 0]),
direction: choice<Direction>('auto'),
permanent: bool(),
sticky: bool(),
opacity: num(1.0),
},
{ attach: 'self' },
) {
declare readonly leafletObject?: Tooltip;
declare addEventListener: LeafletAddEventListener<DivOverlayLayerEvents>;
declare removeEventListener: LeafletRemoveEventListener<DivOverlayLayerEvents>;
customElements.define('leaflet-tooltip', LeafletTooltipElement);
#observer?: MutationObserver;
// Content is the element's markup, not an attribute. A tooltip only carries a
// position of its own when it isn't bound to a parent layer.
createLeafletObject(options: TooltipOptions): Tooltip {
const tooltip = new Tooltip({ ...options, content: this.innerHTML });
if (this.hasAttribute('lat') && this.hasAttribute('lng')) {
tooltip.setLatLng([this.lat, this.lng]);
}
return tooltip;
}
connectedCallback(): void {
super.connectedCallback();
this.#observer = new MutationObserver(() => {
this.leafletObject?.setContent(this.innerHTML);
});
this.#observer.observe(this, { childList: true, characterData: true, subtree: true });
}
disconnectedCallback(): void {
this.#observer?.disconnect();
this.#observer = undefined;
super.disconnectedCallback();
}
}
customElements.define('leaflet-tooltip', LeafletTooltip);
export { LeafletTooltipElement };

View File

@ -1,56 +1,5 @@
import {
VideoOverlay,
type CrossOrigin,
type LatLngBoundsExpression,
type VideoOverlayOptions,
} from 'leaflet';
import { bool, choice, json, num, positional, str } from '../core/props.ts';
import { getBounds, urlProp } from '../core/shared-props.ts';
import {
WithProps,
type LeafletAddEventListener,
type LeafletRemoveEventListener,
} from '../core/with-props.ts';
import type { PathEvents } from '../core/event-types.ts';
import LeafletVideoOverlayElement from '../elements/leaflet-video-overlay.ts';
// Playback options live on the <video> element Leaflet builds, so live updates
// go there rather than through a Leaflet setter.
function media(
key: 'loop' | 'autoplay' | 'muted' | 'playsInline',
): (obj: VideoOverlay, value: boolean) => void {
return (obj, value) => {
const el = obj.getElement();
if (el) el[key] = value;
};
}
customElements.define('leaflet-video-overlay', LeafletVideoOverlayElement);
export class LeafletVideoOverlay extends WithProps({
url: urlProp,
bounds: positional(json<LatLngBoundsExpression, VideoOverlay>([], { get: getBounds })),
opacity: num(1.0),
alt: str(),
interactive: bool(),
crossOrigin: choice<CrossOrigin>(''),
loop: bool(false, { set: media('loop') }),
autoplay: bool(false, { set: media('autoplay') }),
muted: bool(false, { set: media('muted') }),
playsInline: bool(false, { attribute: 'playsinline', set: media('playsInline') }),
zIndex: num(),
className: str(),
keepAspectRatio: bool(true),
errorOverlayUrl: str(),
}) {
declare readonly leafletObject?: VideoOverlay;
declare addEventListener: LeafletAddEventListener<PathEvents>;
declare removeEventListener: LeafletRemoveEventListener<PathEvents>;
createLeafletObject(options: VideoOverlayOptions): VideoOverlay {
return new VideoOverlay(this.url, this.bounds, options);
}
getElement(): HTMLVideoElement | undefined {
return this.leafletObject?.getElement();
}
}
customElements.define('leaflet-video-overlay', LeafletVideoOverlay);
export { LeafletVideoOverlayElement };

81
src/core/globals.ts Normal file
View File

@ -0,0 +1,81 @@
// Ambient DOM augmentations: the `leaflet-*` tag -> element class map, and the
// custom bubbling events the registration protocol fires. Kept in this
// standalone module -- imported only by `src/index.npm.ts`, never by
// `src/index.ts` or anything in `jsr.json`'s export graph -- because JSR's
// "no slow types" check rejects `declare global` anywhere it can reach. npm
// consumers get these automatically via the package's `.` entry; the whole
// `src/` tree also sees them at build/typecheck time because this file is
// under `tsconfig.json`'s `include`. See docs/ for the split rationale.
import type {
LeafletCRSChangedEvent,
LeafletIconChangedEvent,
LeafletLayerEvent,
LeafletLineRemoveEvent,
LeafletLineSyncEvent,
LeafletRegisterEvent,
} from './register.ts';
import type {
LeafletCircleElement,
LeafletCircleMarkerElement,
LeafletControlAttributionElement,
LeafletControlLayersElement,
LeafletControlScaleElement,
LeafletControlZoomElement,
LeafletDivIconElement,
LeafletFeatureGroupElement,
LeafletGeoJSONElement,
LeafletIconElement,
LeafletImageOverlayElement,
LeafletLayerGroupElement,
LeafletLineElement,
LeafletMapElement,
LeafletMarkerElement,
LeafletPolygonElement,
LeafletPolylineElement,
LeafletPopupElement,
LeafletRectangleElement,
LeafletSVGOverlayElement,
LeafletTileLayerElement,
LeafletTileLayerWMSElement,
LeafletTooltipElement,
LeafletVideoOverlayElement,
} from '../elements/index.ts';
declare global {
interface HTMLElementEventMap {
'leaflet-register': LeafletRegisterEvent;
'leaflet-add-layer': LeafletLayerEvent;
'leaflet-remove-layer': LeafletLayerEvent;
'icon-changed': LeafletIconChangedEvent;
'leaflet-line-sync': LeafletLineSyncEvent;
'leaflet-line-remove': LeafletLineRemoveEvent;
'leaflet-crs-changed': LeafletCRSChangedEvent;
}
interface HTMLElementTagNameMap {
'leaflet-map': LeafletMapElement;
'leaflet-marker': LeafletMarkerElement;
'leaflet-circle': LeafletCircleElement;
'leaflet-circle-marker': LeafletCircleMarkerElement;
'leaflet-line': LeafletLineElement;
'leaflet-polygon': LeafletPolygonElement;
'leaflet-polyline': LeafletPolylineElement;
'leaflet-rectangle': LeafletRectangleElement;
'leaflet-tile-layer': LeafletTileLayerElement;
'leaflet-tile-layer-wms': LeafletTileLayerWMSElement;
'leaflet-image-overlay': LeafletImageOverlayElement;
'leaflet-video-overlay': LeafletVideoOverlayElement;
'leaflet-svg-overlay': LeafletSVGOverlayElement;
'leaflet-layer-group': LeafletLayerGroupElement;
'leaflet-feature-group': LeafletFeatureGroupElement;
'leaflet-geojson': LeafletGeoJSONElement;
'leaflet-control-layers': LeafletControlLayersElement;
'leaflet-control-zoom': LeafletControlZoomElement;
'leaflet-control-attribution': LeafletControlAttributionElement;
'leaflet-control-scale': LeafletControlScaleElement;
'leaflet-popup': LeafletPopupElement;
'leaflet-tooltip': LeafletTooltipElement;
'leaflet-icon': LeafletIconElement;
'leaflet-div-icon': LeafletDivIconElement;
}
}

View File

@ -53,6 +53,12 @@ export type PropOptionValues<T> = Partial<{
[K in keyof T as T[K] extends { option: false } ? never : K]: PropValue<T[K]>;
}>;
// The type `positional()` produces: a PropDef flagged so #buildOptions skips
// it. Spelled out as an alias so element PROPS tables can be given the explicit
// type annotations JSR's "no slow types" check requires without repeating the
// intersection everywhere.
export type Positional<T, TObj = unknown> = PropDef<T, TObj> & { option: false };
// Marks a prop the Leaflet constructor takes as an argument, so it is left out
// of the options object handed to createLeafletObject().
export function positional<T extends PropDef>(def: T): T & { option: false } {

View File

@ -30,17 +30,9 @@ export type LeafletLineRemoveEvent = CustomEvent<{ element: HTMLElement }>;
// own default, mirroring icon-changed's `icon: null`.
export type LeafletCRSChangedEvent = CustomEvent<{ crs: CRS | null }>;
declare global {
interface HTMLElementEventMap {
'leaflet-register': LeafletRegisterEvent;
'leaflet-add-layer': LeafletLayerEvent;
'leaflet-remove-layer': LeafletLayerEvent;
'icon-changed': LeafletIconChangedEvent;
'leaflet-line-sync': LeafletLineSyncEvent;
'leaflet-line-remove': LeafletLineRemoveEvent;
'leaflet-crs-changed': LeafletCRSChangedEvent;
}
}
// The `HTMLElementEventMap` augmentation for these event names lives in
// `./globals.ts` (npm-only), kept out of this module so JSR -- which rejects
// `declare global` in its published graph -- can still publish it.
export function emitIconChanged(el: HTMLElement, icon: Icon | DivIcon | null | undefined) {
el.dispatchEvent(

View File

@ -56,7 +56,7 @@ export function style<T>(key: keyof PathOptions): (obj: Styleable, value: T) =>
// The source url. Passed positionally by every Leaflet constructor that takes
// one, and ignored when blank so clearing the attribute can't request nothing.
// No `get`: none of TileLayer/ImageOverlay/VideoOverlay expose a getUrl().
export const urlProp = positional(
export const urlProp: PropDef<string, Sourced> & { option: false } = positional(
str<Sourced>('', {
set(obj, value) {
if (value) obj.setUrl(value);
@ -69,7 +69,10 @@ export const urlProp = positional(
// the other's current value, and both are written back whenever the object
// moves -- which is what keeps the attributes current while a marker is
// dragged. Shared by marker, circle, circle-marker, popup and tooltip.
export const latLngProps = {
export const latLngProps: {
lat: PropDef<number, Positioned> & { option: false };
lng: PropDef<number, Positioned> & { option: false };
} = {
lat: positional(
num<Positioned>(0, {
event: 'move',
@ -88,11 +91,28 @@ export const latLngProps = {
},
}),
),
} as const;
};
// The style options every Path accepts. Defaults match Leaflet's own, so an
// absent attribute and an unset option mean the same thing.
export const pathProps = {
export const pathProps: {
stroke: PropDef<boolean, Styleable>;
color: PropDef<string, Styleable>;
weight: PropDef<number, Styleable>;
opacity: PropDef<number, Styleable>;
lineCap: PropDef<LineCapShape, Styleable>;
lineJoin: PropDef<LineJoinShape, Styleable>;
dashArray: PropDef<string, Styleable>;
dashOffset: PropDef<string, Styleable>;
fill: PropDef<boolean, Styleable>;
fillColor: PropDef<string, Styleable>;
fillOpacity: PropDef<number, Styleable>;
fillRule: PropDef<FillRule, Styleable>;
className: PropDef<string>;
interactive: PropDef<boolean>;
bubblingMouseEvents: PropDef<boolean>;
pane: PropDef<string>;
} = {
stroke: bool<Styleable>(true, { set: style('stroke') }),
color: str<Styleable>('#3388ff', { set: style('color') }),
weight: num<Styleable>(3, { set: style('weight') }),
@ -111,14 +131,39 @@ export const pathProps = {
interactive: bool(true),
bubblingMouseEvents: bool(true),
pane: str('overlay'),
} as const;
};
// The GridLayer/TileLayer options every tile source accepts, shared by
// leaflet-tile-layer and leaflet-tile-layer-wms (WMSOptions extends
// TileLayerOptions). Most are constructor-only -- Leaflet exposes no setter
// for them -- so changing the attribute after creation has no effect, same as
// leaflet-map's zoomSnap.
export const tileLayerProps = {
export const tileLayerProps: {
attribution: PropDef<string>;
minZoom: PropDef<number>;
maxZoom: PropDef<number>;
opacity: PropDef<number>;
zIndex: PropDef<number>;
subdomains: PropDef<string>;
tms: PropDef<boolean>;
zoomOffset: PropDef<number>;
zoomReverse: PropDef<boolean>;
detectRetina: PropDef<boolean>;
crossOrigin: PropDef<CrossOrigin>;
referrerPolicy: PropDef<ReferrerPolicy | undefined>;
errorTileUrl: PropDef<string>;
tileSize: PropDef<number>;
noWrap: PropDef<boolean>;
bounds: PropDef<LatLngBoundsExpression>;
className: PropDef<string>;
minNativeZoom: PropDef<number>;
maxNativeZoom: PropDef<number>;
keepBuffer: PropDef<number>;
updateWhenIdle: PropDef<boolean>;
updateWhenZooming: PropDef<boolean>;
updateInterval: PropDef<number>;
pane: PropDef<string>;
} = {
attribution: str(),
minZoom: num(0),
maxZoom: num(18),
@ -150,4 +195,4 @@ export const tileLayerProps = {
updateWhenZooming: bool(true),
updateInterval: num(200),
pane: str('tilePane'),
} as const;
};

32
src/elements/index.ts Normal file
View File

@ -0,0 +1,32 @@
// The element classes on their own -- no `customElements.define()` runs from
// anything in this file or the modules it re-exports. Import a `components/*`
// module (or `src/index.ts`) instead when you want the tags actually
// registered; reach for these when you want to subclass an element, register
// it under a different tag name, or otherwise customise before defining.
//
// Every class is the `default` export of its own module, surfaced here under
// a name. Order is irrelevant -- nothing here has a load-time side effect.
export { default as LeafletMapElement } from './leaflet-map.ts';
export { default as LeafletControlLayersElement } from './leaflet-control-layers.ts';
export { default as LeafletLayerGroupElement } from './leaflet-layer-group.ts';
export { default as LeafletFeatureGroupElement } from './leaflet-feature-group.ts';
export { default as LeafletPolygonElement } from './leaflet-polygon.ts';
export { default as LeafletPolylineElement } from './leaflet-polyline.ts';
export { default as LeafletMarkerElement } from './leaflet-marker.ts';
export { default as LeafletCircleElement } from './leaflet-circle.ts';
export { default as LeafletCircleMarkerElement } from './leaflet-circle-marker.ts';
export { default as LeafletRectangleElement } from './leaflet-rectangle.ts';
export { default as LeafletTileLayerElement } from './leaflet-tile-layer.ts';
export { default as LeafletTileLayerWMSElement } from './leaflet-tile-layer-wms.ts';
export { default as LeafletImageOverlayElement } from './leaflet-image-overlay.ts';
export { default as LeafletVideoOverlayElement } from './leaflet-video-overlay.ts';
export { default as LeafletSVGOverlayElement } from './leaflet-svg-overlay.ts';
export { default as LeafletGeoJSONElement } from './leaflet-geojson.ts';
export { default as LeafletLineElement } from './leaflet-line.ts';
export { default as LeafletControlZoomElement } from './leaflet-control-zoom.ts';
export { default as LeafletControlAttributionElement } from './leaflet-control-attribution.ts';
export { default as LeafletControlScaleElement } from './leaflet-control-scale.ts';
export { default as LeafletPopupElement } from './leaflet-popup.ts';
export { default as LeafletTooltipElement } from './leaflet-tooltip.ts';
export { default as LeafletIconElement } from './leaflet-icon.ts';
export { default as LeafletDivIconElement } from './leaflet-div-icon.ts';

View File

@ -0,0 +1,30 @@
import { CircleMarker, type CircleMarkerOptions } from 'leaflet';
import { num, type PropDef } from '../core/props.ts';
import { latLngProps, pathProps } from '../core/shared-props.ts';
import {
WithProps,
type LeafletAddEventListener,
type LeafletElementConstructor,
type LeafletRemoveEventListener,
} from '../core/with-props.ts';
import type { PathEvents } from '../core/event-types.ts';
const PROPS: typeof latLngProps &
typeof pathProps & {
radius: PropDef<number, CircleMarker>;
} = {
...latLngProps,
radius: num<CircleMarker>(10, { get: (obj) => obj.getRadius() }),
...pathProps,
};
const Base: LeafletElementConstructor<CircleMarker, typeof PROPS> = WithProps(PROPS);
export default class LeafletCircleMarkerElement extends Base {
declare readonly leafletObject?: CircleMarker;
declare addEventListener: LeafletAddEventListener<PathEvents>;
declare removeEventListener: LeafletRemoveEventListener<PathEvents>;
createLeafletObject(options: CircleMarkerOptions): CircleMarker {
return new CircleMarker([this.lat, this.lng], options);
}
}

View File

@ -0,0 +1,32 @@
import { Circle, type CircleOptions } from 'leaflet';
import { num, positional, type PropDef } from '../core/props.ts';
import { latLngProps, pathProps } from '../core/shared-props.ts';
import {
WithProps,
type LeafletAddEventListener,
type LeafletElementConstructor,
type LeafletRemoveEventListener,
} from '../core/with-props.ts';
import type { PathEvents } from '../core/event-types.ts';
// Leaflet has no default radius -- it throws without one -- so unlike every
// other option, this one is always passed, from the default when unset.
const radiusProp: PropDef<number, Circle> & { option: false } = positional(
num<Circle>(1000, { get: (obj) => obj.getRadius() }),
);
const PROPS = {
...latLngProps,
...pathProps,
radius: radiusProp,
} as const;
const Base: LeafletElementConstructor<Circle, typeof PROPS> = WithProps(PROPS);
export default class LeafletCircleElement extends Base {
declare readonly leafletObject?: Circle;
declare addEventListener: LeafletAddEventListener<PathEvents>;
declare removeEventListener: LeafletRemoveEventListener<PathEvents>;
createLeafletObject(options: CircleOptions): Circle {
return new Circle([this.lat, this.lng], { ...options, radius: this.radius });
}
}

View File

@ -0,0 +1,22 @@
import { Control, type ControlPosition } from 'leaflet';
import { choice, str, type PropDef } from '../core/props.ts';
import { WithProps, type LeafletElementConstructor } from '../core/with-props.ts';
const PROPS: {
position: PropDef<ControlPosition>;
prefix: PropDef<string>;
} = {
position: choice<ControlPosition>('bottomright'),
prefix: str(),
};
const Base: LeafletElementConstructor<Control.Attribution, typeof PROPS> = WithProps(PROPS, {
attach: 'self',
});
export default class LeafletControlAttributionElement extends Base {
declare readonly leafletObject?: Control.Attribution;
createLeafletObject(options: Control.AttributionOptions): Control.Attribution {
return new Control.Attribution(options);
}
}

View File

@ -0,0 +1,59 @@
import { Control, type ControlPosition } from 'leaflet';
import { bool, choice, type PropDef } from '../core/props.ts';
import { WithProps, type LeafletElementConstructor } from '../core/with-props.ts';
import type { LeafletRegisterEvent } from '../core/register.ts';
const PROPS: {
position: PropDef<ControlPosition>;
collapsed: PropDef<boolean>;
autoZIndex: PropDef<boolean>;
hideSingleBase: PropDef<boolean>;
sortLayers: PropDef<boolean>;
} = {
position: choice<ControlPosition>('topright'),
collapsed: bool(true),
autoZIndex: bool(true),
hideSingleBase: bool(),
sortLayers: bool(),
};
const Base: LeafletElementConstructor<Control.Layers, typeof PROPS> = WithProps(PROPS, {
attach: 'self',
});
export default class LeafletControlLayersElement extends Base {
declare readonly leafletObject?: Control.Layers;
createLeafletObject(options: Control.LayersOptions): Control.Layers {
return new Control.Layers({}, {}, options);
}
connectedCallback(): void {
super.connectedCallback();
this.addEventListener('leaflet-register', this.#onChildRegister);
}
disconnectedCallback(): void {
this.removeEventListener('leaflet-register', this.#onChildRegister);
super.disconnectedCallback();
}
// Every child -- present at construction or added later -- announces
// itself this way: a parent's connectedCallback always finishes before a
// child's does (even for an already-built subtree attached in one go), so
// there is no "read the children that are already here" case to handle
// separately.
#onChildRegister = (e: LeafletRegisterEvent) => {
e.stopPropagation();
const el = e.detail.element;
const layer = e.detail.leafletObject;
const name = el.getAttribute('name');
if (!name) return;
if (el.getAttribute('type') === 'base') this.leafletObject?.addBaseLayer(layer, name);
else this.leafletObject?.addOverlay(layer, name);
if (el.hasAttribute('active')) {
this.dispatchEvent(
new CustomEvent('leaflet-add-layer', { bubbles: true, detail: { layer } }),
);
}
};
}

View File

@ -0,0 +1,28 @@
import { Control, type ControlPosition } from 'leaflet';
import { bool, choice, num, type PropDef } from '../core/props.ts';
import { WithProps, type LeafletElementConstructor } from '../core/with-props.ts';
const PROPS: {
position: PropDef<ControlPosition>;
maxWidth: PropDef<number>;
metric: PropDef<boolean>;
imperial: PropDef<boolean>;
updateWhenIdle: PropDef<boolean>;
} = {
position: choice<ControlPosition>('bottomleft'),
maxWidth: num(100),
metric: bool(true),
imperial: bool(true),
updateWhenIdle: bool(),
};
const Base: LeafletElementConstructor<Control.Scale, typeof PROPS> = WithProps(PROPS, {
attach: 'self',
});
export default class LeafletControlScaleElement extends Base {
declare readonly leafletObject?: Control.Scale;
createLeafletObject(options: Control.ScaleOptions): Control.Scale {
return new Control.Scale(options);
}
}

View File

@ -0,0 +1,30 @@
import { Control, type ControlPosition } from 'leaflet';
import { choice, str, type PropDef } from '../core/props.ts';
import { WithProps, type LeafletElementConstructor } from '../core/with-props.ts';
// The button labels default to Leaflet's own markup, which hides the glyph
// from screen readers in favour of the title.
const PROPS: {
position: PropDef<ControlPosition>;
zoomInText: PropDef<string>;
zoomInTitle: PropDef<string>;
zoomOutText: PropDef<string>;
zoomOutTitle: PropDef<string>;
} = {
position: choice<ControlPosition>('topleft'),
zoomInText: str('<span aria-hidden="true">+</span>'),
zoomInTitle: str('Zoom in'),
zoomOutText: str('<span aria-hidden="true">−</span>'),
zoomOutTitle: str('Zoom out'),
};
const Base: LeafletElementConstructor<Control.Zoom, typeof PROPS> = WithProps(PROPS, {
attach: 'self',
});
export default class LeafletControlZoomElement extends Base {
declare readonly leafletObject?: Control.Zoom;
createLeafletObject(options: Control.ZoomOptions): Control.Zoom {
return new Control.Zoom(options);
}
}

View File

@ -0,0 +1,57 @@
import { DivIcon, type DivIconOptions, type PointExpression } from 'leaflet';
import { json, str, type PropDef } from '../core/props.ts';
import { emitIconChanged } from '../core/register.ts';
import { WithProps, type LeafletElementConstructor } from '../core/with-props.ts';
// Like leaflet-icon, rebuilt on every change -- including changes to the
// markup, which is what the icon renders when `html` isn't set.
const PROPS: {
iconSize: PropDef<PointExpression>;
iconAnchor: PropDef<PointExpression>;
popupAnchor: PropDef<PointExpression>;
tooltipAnchor: PropDef<PointExpression>;
className: PropDef<string>;
html: PropDef<string>;
bgPos: PropDef<PointExpression>;
} = {
iconSize: json<PointExpression>([0, 0]),
iconAnchor: json<PointExpression>([0, 0]),
popupAnchor: json<PointExpression>([0, 0]),
tooltipAnchor: json<PointExpression>([0, 0]),
className: str('leaflet-div-icon'),
html: str(),
bgPos: json<PointExpression>([0, 0]),
};
const Base: LeafletElementConstructor<DivIcon, typeof PROPS> = WithProps(PROPS, {
attach: 'none',
recreate: true,
});
export default class LeafletDivIconElement extends Base {
declare readonly leafletObject?: DivIcon;
#observer?: MutationObserver;
createLeafletObject(options: DivIconOptions): DivIcon {
return new DivIcon(this.innerHTML ? { ...options, html: this.innerHTML } : options);
}
connectedCallback(): void {
super.connectedCallback();
this.#observer = new MutationObserver(() => {
this.recreateLeafletObject();
});
this.#observer.observe(this, { childList: true, characterData: true, subtree: true });
}
disconnectedCallback(): void {
this.#observer?.disconnect();
this.#observer = undefined;
super.disconnectedCallback();
emitIconChanged(this, null);
}
leafletObjectCreated(): void {
emitIconChanged(this, this.leafletObject);
}
}

View File

@ -0,0 +1,22 @@
import { FeatureGroup } from 'leaflet';
import {
WithProps,
type LeafletAddEventListener,
type LeafletElementConstructor,
type LeafletRemoveEventListener,
} from '../core/with-props.ts';
import type { GroupEvents } from '../core/event-types.ts';
const PROPS: Record<never, never> = {};
const Base: LeafletElementConstructor<FeatureGroup, typeof PROPS> = WithProps(PROPS);
// Like leaflet-layer-group, but its children share events and a bounding box.
export default class LeafletFeatureGroupElement extends Base {
declare readonly leafletObject?: FeatureGroup;
declare addEventListener: LeafletAddEventListener<GroupEvents>;
declare removeEventListener: LeafletRemoveEventListener<GroupEvents>;
createLeafletObject(): FeatureGroup {
return new FeatureGroup([]);
}
}

View File

@ -0,0 +1,38 @@
import { GeoJSON, type PathOptions } from 'leaflet';
import type { GeoJsonObject } from 'geojson';
import { json, positional, type Positional } from '../core/props.ts';
import { pathProps } from '../core/shared-props.ts';
import {
WithProps,
type LeafletAddEventListener,
type LeafletElementConstructor,
type LeafletRemoveEventListener,
} from '../core/with-props.ts';
import type { GroupEvents } from '../core/event-types.ts';
const PROPS: {
data: Positional<GeoJsonObject | null, GeoJSON>;
} & typeof pathProps = {
data: positional(
json<GeoJsonObject | null>(null, {
set(obj: GeoJSON, value) {
obj.clearLayers();
if (value) obj.addData(value);
},
}),
),
...pathProps,
};
const Base: LeafletElementConstructor<GeoJSON, typeof PROPS> = WithProps(PROPS);
export default class LeafletGeoJSONElement extends Base {
declare readonly leafletObject?: GeoJSON;
declare addEventListener: LeafletAddEventListener<GroupEvents>;
declare removeEventListener: LeafletRemoveEventListener<GroupEvents>;
// Every prop but `data` is a style option, and GeoJSON takes those nested
// under `style` so they apply to each feature it builds.
createLeafletObject(options: PathOptions): GeoJSON {
return new GeoJSON(this.data, { style: options });
}
}

View File

@ -0,0 +1,54 @@
import { Icon, type IconOptions, type PointExpression } from 'leaflet';
import { json, str, type PropDef } from '../core/props.ts';
import { emitIconChanged } from '../core/register.ts';
import { WithProps, type LeafletElementConstructor } from '../core/with-props.ts';
const PROPS: {
iconUrl: PropDef<string>;
iconRetinaUrl: PropDef<string>;
iconSize: PropDef<PointExpression>;
iconAnchor: PropDef<PointExpression>;
popupAnchor: PropDef<PointExpression>;
tooltipAnchor: PropDef<PointExpression>;
shadowUrl: PropDef<string>;
shadowRetinaUrl: PropDef<string>;
shadowSize: PropDef<PointExpression>;
shadowAnchor: PropDef<PointExpression>;
className: PropDef<string>;
} = {
iconUrl: str(),
iconRetinaUrl: str(),
iconSize: json<PointExpression>([0, 0]),
iconAnchor: json<PointExpression>([0, 0]),
popupAnchor: json<PointExpression>([0, 0]),
tooltipAnchor: json<PointExpression>([0, 0]),
shadowUrl: str(),
shadowRetinaUrl: str(),
shadowSize: json<PointExpression>([0, 0]),
shadowAnchor: json<PointExpression>([0, 0]),
className: str(),
};
// An Icon has no setters, so every attribute change builds a new one and the
// parent marker is told to swap it in.
const Base: LeafletElementConstructor<Icon, typeof PROPS> = WithProps(PROPS, {
attach: 'none',
recreate: true,
});
export default class LeafletIconElement extends Base {
declare readonly leafletObject?: Icon;
createLeafletObject(options: Partial<IconOptions>): Icon | undefined {
return options.iconUrl ? new Icon(options as IconOptions) : undefined;
}
leafletObjectCreated(): void {
emitIconChanged(this, this.leafletObject);
}
disconnectedCallback(): void {
super.disconnectedCallback();
emitIconChanged(this, null);
}
}

View File

@ -0,0 +1,62 @@
import {
ImageOverlay,
type CrossOrigin,
type ImageOverlayOptions,
type LatLngBoundsExpression,
} from 'leaflet';
import {
bool,
choice,
json,
num,
positional,
str,
type PropDef,
type Positional,
} from '../core/props.ts';
import { getBounds, urlProp, type Sourced } from '../core/shared-props.ts';
import {
WithProps,
type LeafletAddEventListener,
type LeafletElementConstructor,
type LeafletRemoveEventListener,
} from '../core/with-props.ts';
import type { PathEvents } from '../core/event-types.ts';
const PROPS: {
url: PropDef<string, Sourced> & { option: false };
bounds: Positional<LatLngBoundsExpression, ImageOverlay>;
opacity: PropDef<number>;
alt: PropDef<string, ImageOverlay>;
interactive: PropDef<boolean>;
crossOrigin: PropDef<CrossOrigin>;
errorOverlayUrl: PropDef<string>;
zIndex: PropDef<number>;
className: PropDef<string>;
} = {
url: urlProp,
bounds: positional(json<LatLngBoundsExpression, ImageOverlay>([], { get: getBounds })),
opacity: num(1.0),
alt: str('', {
set(obj: ImageOverlay, value) {
const el = obj.getElement();
if (el) el.alt = value;
},
}),
interactive: bool(),
crossOrigin: choice<CrossOrigin>(''),
errorOverlayUrl: str(),
zIndex: num(),
className: str(),
};
const Base: LeafletElementConstructor<ImageOverlay, typeof PROPS> = WithProps(PROPS);
export default class LeafletImageOverlayElement extends Base {
declare readonly leafletObject?: ImageOverlay;
declare addEventListener: LeafletAddEventListener<PathEvents>;
declare removeEventListener: LeafletRemoveEventListener<PathEvents>;
createLeafletObject(options: ImageOverlayOptions): ImageOverlay {
return new ImageOverlay(this.url, this.bounds, options);
}
}

View File

@ -0,0 +1,23 @@
import { LayerGroup } from 'leaflet';
import {
WithProps,
type LeafletAddEventListener,
type LeafletElementConstructor,
type LeafletRemoveEventListener,
} from '../core/with-props.ts';
import type { GroupEvents } from '../core/event-types.ts';
const PROPS: Record<never, never> = {};
const Base: LeafletElementConstructor<LayerGroup, typeof PROPS> = WithProps(PROPS);
// A passthrough container: it has no options of its own, and children add
// themselves to it through the standard registration bubble.
export default class LeafletLayerGroupElement extends Base {
declare readonly leafletObject?: LayerGroup;
declare addEventListener: LeafletAddEventListener<GroupEvents>;
declare removeEventListener: LeafletRemoveEventListener<GroupEvents>;
createLeafletObject(): LayerGroup {
return new LayerGroup([]);
}
}

View File

@ -0,0 +1,29 @@
import { emitLineRemove, emitLineSync } from '../core/register.ts';
export default class LeafletLineElement extends HTMLElement {
static get observedAttributes(): string[] {
return ['lat', 'lng'];
}
// Cached because disconnectedCallback fires after this is already detached
// from it -- see emitLineRemove.
#parent: ParentNode | null = null;
get latlng(): [number, number] {
return [+(this.getAttribute('lat') ?? 0), +(this.getAttribute('lng') ?? 0)];
}
connectedCallback(): void {
this.#parent = this.parentNode;
emitLineSync(this, this.latlng);
}
attributeChangedCallback(): void {
emitLineSync(this, this.latlng);
}
disconnectedCallback(): void {
emitLineRemove(this.#parent ?? this, this);
this.#parent = null;
}
}

285
src/elements/leaflet-map.ts Normal file
View File

@ -0,0 +1,285 @@
import { Icon, Map as LMap, type MapOptions, version } from 'leaflet';
import {
bool,
disabled,
num,
positional,
str,
type PropDef,
type Positional,
} from '../core/props.ts';
import {
WithProps,
type LeafletAddEventListener,
type LeafletElementConstructor,
type LeafletRemoveEventListener,
} from '../core/with-props.ts';
import type { LeafletLayerEvent, LeafletRegisterEvent } from '../core/register.ts';
import type { MapEvents } from '../core/event-types.ts';
const DEFAULT_CSS_URL = `https://unpkg.com/leaflet@${version}/dist/leaflet.css`;
const DEFAULT_CSS_INTEGRITY =
version === '1.9.4' ? 'sha256-p4NxAoJBhIIN+hmNHrzRCf9tD/miZyoHS5obTRR9BMY=' : '';
interface CssHost extends HTMLElement {
applyCss(): void;
}
// The css-* attributes describe the stylesheet in the shadow root rather than
// anything about the Leaflet map, so a change just re-links it.
function relinkCss(_map: LMap, _value: string, el: HTMLElement): void {
(el as CssHost).applyCss();
}
const PROPS: {
lat: Positional<number, LMap>;
lng: Positional<number, LMap>;
zoom: Positional<number, LMap>;
minZoom: PropDef<number, LMap>;
maxZoom: PropDef<number, LMap>;
zoomSnap: PropDef<number>;
zoomDelta: PropDef<number>;
keyboardPanDelta: PropDef<number>;
wheelDebounceTime: PropDef<number>;
wheelPxPerZoomLevel: PropDef<number>;
inertiaDeceleration: PropDef<number>;
inertiaMaxSpeed: PropDef<number>;
easeLinearity: PropDef<number>;
maxBoundsViscosity: PropDef<number>;
tapTolerance: PropDef<number>;
zoomAnimationThreshold: PropDef<number>;
transform3DLimit: PropDef<number>;
scrollWheelZoom: PropDef<boolean, LMap>;
dragging: PropDef<boolean, LMap>;
touchZoom: PropDef<boolean, LMap>;
doubleClickZoom: PropDef<boolean, LMap>;
boxZoom: PropDef<boolean, LMap>;
keyboard: PropDef<boolean, LMap>;
closePopupOnClick: PropDef<boolean>;
trackResize: PropDef<boolean>;
zoomControl: PropDef<boolean>;
attributionControl: PropDef<boolean>;
inertia: PropDef<boolean>;
zoomAnimation: PropDef<boolean>;
fadeAnimation: PropDef<boolean>;
markerZoomAnimation: PropDef<boolean>;
bounceAtZoomLimits: PropDef<boolean>;
tapHold: PropDef<boolean>;
preferCanvas: PropDef<boolean>;
worldCopyJump: PropDef<boolean>;
cssUrl: Positional<string>;
cssIntegrity: Positional<string>;
cssCrossorigin: Positional<string>;
} = {
// View state. Not constructor options -- the map is positioned with setView
// once it exists -- and written back whenever the user pans or zooms.
lat: positional(
num<LMap>(0, {
event: 'moveend',
get: (map) => map.getCenter().lat,
set: (map, value) => {
map.setView([value, map.getCenter().lng], map.getZoom());
},
}),
),
lng: positional(
num<LMap>(0, {
event: 'moveend',
get: (map) => map.getCenter().lng,
set: (map, value) => {
map.setView([map.getCenter().lat, value], map.getZoom());
},
}),
),
zoom: positional(
num<LMap>(2, {
event: 'zoomend',
get: (map) => map.getZoom(),
set: (map, value) => {
map.setZoom(value);
},
}),
),
// Numeric options Leaflet lets us change after construction.
minZoom: num<LMap>(0, {
get: (map) => map.getMinZoom(),
set: (map, value) => {
map.setMinZoom(value);
},
}),
maxZoom: num<LMap>(Infinity, {
get: (map) => map.getMaxZoom(),
set: (map, value) => {
map.setMaxZoom(value);
},
}),
// Constructor-only numeric options.
zoomSnap: num(1),
zoomDelta: num(1),
keyboardPanDelta: num(80),
wheelDebounceTime: num(40),
wheelPxPerZoomLevel: num(60),
inertiaDeceleration: num(3000),
inertiaMaxSpeed: num(Infinity),
easeLinearity: num(0.2),
maxBoundsViscosity: num(0),
tapTolerance: num(15),
zoomAnimationThreshold: num(4),
transform3DLimit: num(8388608),
// Options Leaflet defaults to true, turned off with disable-* attributes.
// The interaction handlers can be toggled after construction.
scrollWheelZoom: disabled<LMap>({
set: (map, on) => (on ? map.scrollWheelZoom.enable() : map.scrollWheelZoom.disable()),
}),
dragging: disabled<LMap>({
set: (map, on) => (on ? map.dragging.enable() : map.dragging.disable()),
}),
touchZoom: disabled<LMap>({
set: (map, on) => (on ? map.touchZoom.enable() : map.touchZoom.disable()),
}),
doubleClickZoom: disabled<LMap>({
set: (map, on) => (on ? map.doubleClickZoom.enable() : map.doubleClickZoom.disable()),
}),
boxZoom: disabled<LMap>({
set: (map, on) => (on ? map.boxZoom.enable() : map.boxZoom.disable()),
}),
keyboard: disabled<LMap>({
set: (map, on) => (on ? map.keyboard.enable() : map.keyboard.disable()),
}),
closePopupOnClick: disabled(),
trackResize: disabled(),
zoomControl: disabled(),
attributionControl: disabled(),
inertia: disabled(),
zoomAnimation: disabled(),
fadeAnimation: disabled(),
markerZoomAnimation: disabled(),
bounceAtZoomLimits: disabled(),
tapHold: disabled(),
// Options Leaflet defaults to false.
preferCanvas: bool(),
worldCopyJump: bool(),
// Not Leaflet options at all -- see relinkCss above.
cssUrl: positional(str(DEFAULT_CSS_URL, { set: relinkCss })),
cssIntegrity: positional(str(DEFAULT_CSS_INTEGRITY, { set: relinkCss })),
cssCrossorigin: positional(str('', { set: relinkCss })),
};
const Base: LeafletElementConstructor<LMap, typeof PROPS> = WithProps(PROPS, { attach: 'none' });
// The root of the component tree. Every other component bubbles a
// `leaflet-register` event up to here, which is where it stops.
export default class LeafletMapElement extends Base {
declare readonly leafletObject?: LMap;
declare addEventListener: LeafletAddEventListener<MapEvents>;
declare removeEventListener: LeafletRemoveEventListener<MapEvents>;
#container?: HTMLDivElement;
#cssLink?: HTMLLinkElement;
#resizeObserver?: ResizeObserver;
createLeafletObject(options: MapOptions): LMap {
const map = new LMap(this.#container ?? this.#buildShadowRoot(), options);
// getCenter() and getZoom() throw until the view is set. Reading this.lat,
// this.lng and this.zoom here is safe for the same reason: the object
// doesn't exist yet, so the getters fall back to the attributes.
map.setView([this.lat, this.lng], this.zoom);
return map;
}
connectedCallback(): void {
this.#buildShadowRoot();
this.applyCss();
super.connectedCallback();
this.#resizeObserver = new ResizeObserver(() => this.leafletObject?.invalidateSize());
this.#resizeObserver.observe(this);
this.addEventListener('leaflet-register', this.#onRegister);
this.addEventListener('leaflet-add-layer', this.#onAddLayer);
this.addEventListener('leaflet-remove-layer', this.#onRemoveLayer);
}
disconnectedCallback(): void {
this.#resizeObserver?.disconnect();
this.#resizeObserver = undefined;
this.removeEventListener('leaflet-register', this.#onRegister);
this.removeEventListener('leaflet-add-layer', this.#onAddLayer);
this.removeEventListener('leaflet-remove-layer', this.#onRemoveLayer);
super.disconnectedCallback();
}
// Replaces the <link> in the shadow root, and derives the marker icon path
// from the same URL. Called on connect and whenever a css-* attribute
// changes. Absence and emptiness mean different things here, so this reads
// the attributes rather than the properties.
applyCss(): void {
const root = this.shadowRoot;
if (!root) return;
this.#cssLink?.remove();
this.#cssLink = undefined;
const customUrl = this.hasAttribute('css-url');
const url = customUrl ? this.getAttribute('css-url') : DEFAULT_CSS_URL;
let integrity: string | null = null;
if (this.hasAttribute('css-integrity')) {
integrity = this.getAttribute('css-integrity') ?? '';
} else if (!customUrl) {
integrity = DEFAULT_CSS_INTEGRITY;
}
let crossorigin: string | undefined;
if (this.hasAttribute('css-crossorigin')) {
crossorigin = this.getAttribute('css-crossorigin') ?? undefined;
} else if (integrity) {
crossorigin = 'anonymous';
}
const link = document.createElement('link');
link.rel = 'stylesheet';
link.href = url ?? '';
if (integrity) link.setAttribute('integrity', integrity);
if (crossorigin !== undefined) link.setAttribute('crossorigin', crossorigin);
root.append(link);
this.#cssLink = link;
Icon.Default.imagePath = url?.replace(/\/[^/]+$/u, '/images/');
}
#buildShadowRoot(): HTMLDivElement {
if (this.#container) return this.#container;
const root = this.shadowRoot ?? this.attachShadow({ mode: 'open' });
const container = document.createElement('div');
container.style.width = '100%';
container.style.height = '100%';
root.append(container);
const style = document.createElement('style');
style.textContent = ':host { display: block; width: 100%; height: 400px; }';
root.append(style);
this.#container = container;
return container;
}
#onRegister = (e: LeafletRegisterEvent) => {
e.stopPropagation();
const map = this.leafletObject;
if (map) e.detail.leafletObject.addTo(map);
};
#onAddLayer = (e: LeafletLayerEvent) => {
this.leafletObject?.addLayer(e.detail.layer);
};
#onRemoveLayer = (e: LeafletLayerEvent) => {
this.leafletObject?.removeLayer(e.detail.layer);
};
}

View File

@ -0,0 +1,68 @@
import { Icon, Marker, type MarkerOptions } from 'leaflet';
import { bool, num, str, type PropDef } from '../core/props.ts';
import { latLngProps } from '../core/shared-props.ts';
import {
WithProps,
type LeafletAddEventListener,
type LeafletElementConstructor,
type LeafletRemoveEventListener,
} from '../core/with-props.ts';
import type { LeafletIconChangedEvent } from '../core/register.ts';
import type { MarkerEvents } from '../core/event-types.ts';
const PROPS: typeof latLngProps & {
title: PropDef<string, Marker>;
alt: PropDef<string, Marker>;
draggable: PropDef<boolean, Marker>;
opacity: PropDef<number>;
zIndexOffset: PropDef<number>;
} = {
...latLngProps,
// title and alt end up on the <img> Leaflet renders, so live updates go there.
title: str('', {
set: (obj: Marker, value) => {
const el = obj.getElement();
if (el) el.title = value;
},
}),
alt: str('', {
set: (obj: Marker, value) => {
const el = obj.getElement() as HTMLImageElement | undefined;
if (el) el.alt = value;
},
}),
draggable: bool(false, {
set(obj: Marker, value) {
if (value) obj.dragging?.enable();
else obj.dragging?.disable();
},
}),
opacity: num(1.0),
zIndexOffset: num(),
};
const Base: LeafletElementConstructor<Marker, typeof PROPS> = WithProps(PROPS);
export default class LeafletMarkerElement extends Base {
declare readonly leafletObject?: Marker;
declare addEventListener: LeafletAddEventListener<MarkerEvents>;
declare removeEventListener: LeafletRemoveEventListener<MarkerEvents>;
createLeafletObject(options: MarkerOptions): Marker {
return new Marker([this.lat, this.lng], options);
}
connectedCallback(): void {
super.connectedCallback();
this.addEventListener('icon-changed', this.#onIconChanged);
}
disconnectedCallback(): void {
this.removeEventListener('icon-changed', this.#onIconChanged);
super.disconnectedCallback();
}
// A <leaflet-icon> or <leaflet-div-icon> child announces itself this way.
#onIconChanged = (e: LeafletIconChangedEvent) => {
this.leafletObject?.setIcon(e.detail.icon ?? new Icon.Default());
};
}

View File

@ -0,0 +1,51 @@
import { Polygon, type PolylineOptions } from 'leaflet';
import { pathProps } from '../core/shared-props.ts';
import {
WithProps,
type LeafletAddEventListener,
type LeafletElementConstructor,
type LeafletRemoveEventListener,
} from '../core/with-props.ts';
import type { PathEvents } from '../core/event-types.ts';
import type { LeafletLineRemoveEvent, LeafletLineSyncEvent } from '../core/register.ts';
import { VertexTracker } from '../core/vertex-tracker.ts';
const PROPS = { ...pathProps } as const;
const Base: LeafletElementConstructor<Polygon, typeof PROPS> = WithProps(PROPS);
export default class LeafletPolygonElement extends Base {
declare readonly leafletObject?: Polygon;
declare addEventListener: LeafletAddEventListener<PathEvents>;
declare removeEventListener: LeafletRemoveEventListener<PathEvents>;
#vertices = new VertexTracker();
createLeafletObject(options: PolylineOptions): Polygon {
return new Polygon(this.#vertices.coords(), options);
}
// Vertices come from <leaflet-line> children rather than an attribute --
// each one announces its own position via leaflet-line-sync/-remove, we
// never read a child's state directly.
connectedCallback(): void {
super.connectedCallback();
this.addEventListener('leaflet-line-sync', this.#onLineSync);
this.addEventListener('leaflet-line-remove', this.#onLineRemove);
}
disconnectedCallback(): void {
this.removeEventListener('leaflet-line-sync', this.#onLineSync);
this.removeEventListener('leaflet-line-remove', this.#onLineRemove);
super.disconnectedCallback();
}
#onLineSync = (e: LeafletLineSyncEvent) => {
this.#vertices.sync(e.detail.element, e.detail.latlng);
this.leafletObject?.setLatLngs(this.#vertices.coords());
};
#onLineRemove = (e: LeafletLineRemoveEvent) => {
this.#vertices.remove(e.detail.element);
this.leafletObject?.setLatLngs(this.#vertices.coords());
};
}

View File

@ -0,0 +1,62 @@
import { Polyline, type PolylineOptions } from 'leaflet';
import { bool, num, type PropDef } from '../core/props.ts';
import { pathProps, style, type Styleable } from '../core/shared-props.ts';
import {
WithProps,
type LeafletAddEventListener,
type LeafletElementConstructor,
type LeafletRemoveEventListener,
} from '../core/with-props.ts';
import type { PathEvents } from '../core/event-types.ts';
import type { LeafletLineRemoveEvent, LeafletLineSyncEvent } from '../core/register.ts';
import { VertexTracker } from '../core/vertex-tracker.ts';
const PROPS: typeof pathProps & {
fill: PropDef<boolean, Styleable>;
smoothFactor: PropDef<number>;
noClip: PropDef<boolean>;
} = {
...pathProps,
// Unlike closed shapes, a polyline is unfilled by default.
fill: bool(false, { set: style('fill') }),
smoothFactor: num(1.0),
noClip: bool(),
};
const Base: LeafletElementConstructor<Polyline, typeof PROPS> = WithProps(PROPS);
export default class LeafletPolylineElement extends Base {
declare readonly leafletObject?: Polyline;
declare addEventListener: LeafletAddEventListener<PathEvents>;
declare removeEventListener: LeafletRemoveEventListener<PathEvents>;
#vertices = new VertexTracker();
createLeafletObject(options: PolylineOptions): Polyline {
return new Polyline(this.#vertices.coords(), options);
}
// Vertices come from <leaflet-line> children rather than an attribute --
// each one announces its own position via leaflet-line-sync/-remove, we
// never read a child's state directly.
connectedCallback(): void {
super.connectedCallback();
this.addEventListener('leaflet-line-sync', this.#onLineSync);
this.addEventListener('leaflet-line-remove', this.#onLineRemove);
}
disconnectedCallback(): void {
this.removeEventListener('leaflet-line-sync', this.#onLineSync);
this.removeEventListener('leaflet-line-remove', this.#onLineRemove);
super.disconnectedCallback();
}
#onLineSync = (e: LeafletLineSyncEvent) => {
this.#vertices.sync(e.detail.element, e.detail.latlng);
this.leafletObject?.setLatLngs(this.#vertices.coords());
};
#onLineRemove = (e: LeafletLineRemoveEvent) => {
this.#vertices.remove(e.detail.element);
this.leafletObject?.setLatLngs(this.#vertices.coords());
};
}

View File

@ -0,0 +1,60 @@
import { Popup, type PopupOptions } from 'leaflet';
import { bool, num, type PropDef } from '../core/props.ts';
import { latLngProps } from '../core/shared-props.ts';
import {
WithProps,
type LeafletAddEventListener,
type LeafletElementConstructor,
type LeafletRemoveEventListener,
} from '../core/with-props.ts';
import type { DivOverlayLayerEvents } from '../core/event-types.ts';
const PROPS: typeof latLngProps & {
maxWidth: PropDef<number>;
minWidth: PropDef<number>;
maxHeight: PropDef<number>;
autoPan: PropDef<boolean>;
closeButton: PropDef<boolean>;
autoClose: PropDef<boolean>;
} = {
...latLngProps,
maxWidth: num(300),
minWidth: num(50),
maxHeight: num(),
autoPan: bool(true),
closeButton: bool(true),
autoClose: bool(true),
};
const Base: LeafletElementConstructor<Popup, typeof PROPS> = WithProps(PROPS, { attach: 'self' });
export default class LeafletPopupElement extends Base {
declare readonly leafletObject?: Popup;
declare addEventListener: LeafletAddEventListener<DivOverlayLayerEvents>;
declare removeEventListener: LeafletRemoveEventListener<DivOverlayLayerEvents>;
#observer?: MutationObserver;
// Content is the element's markup, not an attribute. A popup only carries a
// position of its own when it isn't bound to a parent layer.
createLeafletObject(options: PopupOptions): Popup {
const popup = new Popup({ ...options, content: this.innerHTML });
if (this.hasAttribute('lat') && this.hasAttribute('lng')) {
popup.setLatLng([this.lat, this.lng]);
}
return popup;
}
connectedCallback(): void {
super.connectedCallback();
this.#observer = new MutationObserver(() => {
this.leafletObject?.setContent(this.innerHTML);
});
this.#observer.observe(this, { childList: true, characterData: true, subtree: true });
}
disconnectedCallback(): void {
this.#observer?.disconnect();
this.#observer = undefined;
super.disconnectedCallback();
}
}

View File

@ -0,0 +1,28 @@
import { Rectangle, type LatLngBoundsExpression, type PolylineOptions } from 'leaflet';
import { json, positional, type Positional } from '../core/props.ts';
import { pathProps, getBounds } from '../core/shared-props.ts';
import {
WithProps,
type LeafletAddEventListener,
type LeafletElementConstructor,
type LeafletRemoveEventListener,
} from '../core/with-props.ts';
import type { PathEvents } from '../core/event-types.ts';
const PROPS: {
bounds: Positional<LatLngBoundsExpression, Rectangle>;
} & typeof pathProps = {
bounds: positional(json<LatLngBoundsExpression, Rectangle>([], { get: getBounds })),
...pathProps,
};
const Base: LeafletElementConstructor<Rectangle, typeof PROPS> = WithProps(PROPS);
export default class LeafletRectangleElement extends Base {
declare readonly leafletObject?: Rectangle;
declare addEventListener: LeafletAddEventListener<PathEvents>;
declare removeEventListener: LeafletRemoveEventListener<PathEvents>;
createLeafletObject(options: PolylineOptions): Rectangle {
return new Rectangle(this.bounds, options);
}
}

View File

@ -0,0 +1,53 @@
import {
SVGOverlay,
type CrossOrigin,
type ImageOverlayOptions,
type LatLngBoundsExpression,
} from 'leaflet';
import {
bool,
choice,
json,
num,
positional,
str,
type PropDef,
type Positional,
} from '../core/props.ts';
import { getBounds } from '../core/shared-props.ts';
import {
WithProps,
type LeafletAddEventListener,
type LeafletElementConstructor,
type LeafletRemoveEventListener,
} from '../core/with-props.ts';
import type { PathEvents } from '../core/event-types.ts';
const PROPS: {
bounds: Positional<LatLngBoundsExpression, SVGOverlay>;
opacity: PropDef<number>;
interactive: PropDef<boolean>;
crossOrigin: PropDef<CrossOrigin>;
zIndex: PropDef<number>;
className: PropDef<string>;
} = {
bounds: positional(json<LatLngBoundsExpression, SVGOverlay>([], { get: getBounds })),
opacity: num(1.0),
interactive: bool(),
crossOrigin: choice<CrossOrigin>(''),
zIndex: num(),
className: str(),
};
const Base: LeafletElementConstructor<SVGOverlay, typeof PROPS> = WithProps(PROPS);
export default class LeafletSVGOverlayElement extends Base {
declare readonly leafletObject?: SVGOverlay;
declare addEventListener: LeafletAddEventListener<PathEvents>;
declare removeEventListener: LeafletRemoveEventListener<PathEvents>;
createLeafletObject(options: ImageOverlayOptions): SVGOverlay {
const svg =
this.querySelector('svg') ?? document.createElementNS('http://www.w3.org/2000/svg', 'svg');
return new SVGOverlay(svg, this.bounds, options);
}
}

View File

@ -0,0 +1,100 @@
import { CRS, TileLayer, type WMSOptions, type WMSParams } from 'leaflet';
import { bool, str, type PropDef, type Positional } from '../core/props.ts';
import { tileLayerProps, urlProp, type Sourced } from '../core/shared-props.ts';
import {
WithProps,
type LeafletAddEventListener,
type LeafletElementConstructor,
type LeafletRemoveEventListener,
} from '../core/with-props.ts';
import type { TileLayerEvents } from '../core/event-types.ts';
import type { LeafletCRSChangedEvent } from '../core/register.ts';
// WMS request parameters have no individual setters -- they're merged into the
// query string through setParams().
function param<T>(key: keyof WMSParams): (obj: TileLayer.WMS, value: T) => void {
return (obj, value) => {
obj.setParams({ [key]: value } as unknown as WMSParams);
};
}
// `crs` takes a CRS instance, not a primitive. The attribute only covers the
// 4 CRSes Leaflet ships by name -- a CRS Leaflet doesn't ship comes from a
// nested child announcing itself via leaflet-crs-changed instead (see
// #onCrsChanged), which takes priority over this when present. Constructor-
// only, like the rest of tileLayerProps -- Leaflet has no setter for it.
const NAMED_CRS = {
EPSG3857: CRS.EPSG3857,
EPSG4326: CRS.EPSG4326,
EPSG3395: CRS.EPSG3395,
Simple: CRS.Simple,
};
type CrsName = keyof typeof NAMED_CRS;
const crsProp: PropDef<CRS> = {
default: CRS.EPSG3857,
decode: (raw) => NAMED_CRS[raw as CrsName] ?? CRS.EPSG3857,
encode: (value) =>
value === CRS.EPSG3857
? null
: ((Object.keys(NAMED_CRS) as CrsName[]).find((name) => NAMED_CRS[name] === value) ?? null),
};
const PROPS: {
url: Positional<string, Sourced>;
} & typeof tileLayerProps & {
layers: PropDef<string, TileLayer.WMS>;
styles: PropDef<string, TileLayer.WMS>;
format: PropDef<string, TileLayer.WMS>;
transparent: PropDef<boolean, TileLayer.WMS>;
version: PropDef<string, TileLayer.WMS>;
uppercase: PropDef<boolean>;
crs: PropDef<CRS>;
} = {
url: urlProp,
...tileLayerProps,
layers: str('', { set: param('layers') }),
styles: str('', { set: param('styles') }),
format: str('image/jpeg', { set: param('format') }),
transparent: bool(false, { set: param('transparent') }),
version: str('1.1.1', { set: param('version') }),
uppercase: bool(),
crs: crsProp,
};
const Base: LeafletElementConstructor<TileLayer.WMS, typeof PROPS> = WithProps(PROPS);
export default class LeafletTileLayerWMSElement extends Base {
declare readonly leafletObject?: TileLayer.WMS;
declare addEventListener: LeafletAddEventListener<TileLayerEvents>;
declare removeEventListener: LeafletRemoveEventListener<TileLayerEvents>;
// Set by a nested CRS-providing child; overrides the `crs` attribute's
// named lookup when present.
#childCrs?: CRS;
createLeafletObject(options: WMSOptions): TileLayer.WMS {
return new TileLayer.WMS(
this.url,
this.#childCrs ? { ...options, crs: this.#childCrs } : options,
);
}
connectedCallback(): void {
super.connectedCallback();
this.addEventListener('leaflet-crs-changed', this.#onCrsChanged);
}
disconnectedCallback(): void {
this.removeEventListener('leaflet-crs-changed', this.#onCrsChanged);
super.disconnectedCallback();
}
// A CRS Leaflet doesn't ship comes from any custom element nested here
// that fires this event -- no base class required, just this event shape
// (see register.ts). `crs` is constructor-only, so picking it up means
// rebuilding the whole layer.
#onCrsChanged = (e: LeafletCRSChangedEvent) => {
this.#childCrs = e.detail.crs ?? undefined;
this.recreateLeafletObject();
};
}

View File

@ -0,0 +1,25 @@
import { TileLayer, type TileLayerOptions } from 'leaflet';
import { tileLayerProps, urlProp } from '../core/shared-props.ts';
import {
WithProps,
type LeafletAddEventListener,
type LeafletElementConstructor,
type LeafletRemoveEventListener,
} from '../core/with-props.ts';
import type { TileLayerEvents } from '../core/event-types.ts';
const PROPS = {
url: urlProp,
...tileLayerProps,
} as const;
const Base: LeafletElementConstructor<TileLayer, typeof PROPS> = WithProps(PROPS);
export default class LeafletTileLayerElement extends Base {
declare readonly leafletObject?: TileLayer;
declare addEventListener: LeafletAddEventListener<TileLayerEvents>;
declare removeEventListener: LeafletRemoveEventListener<TileLayerEvents>;
createLeafletObject(options: TileLayerOptions): TileLayer {
return new TileLayer(this.url, options);
}
}

View File

@ -0,0 +1,60 @@
import { Tooltip, type Direction, type PointExpression, type TooltipOptions } from 'leaflet';
import { bool, choice, json, num, str, type PropDef } from '../core/props.ts';
import { latLngProps } from '../core/shared-props.ts';
import {
WithProps,
type LeafletAddEventListener,
type LeafletElementConstructor,
type LeafletRemoveEventListener,
} from '../core/with-props.ts';
import type { DivOverlayLayerEvents } from '../core/event-types.ts';
const PROPS: typeof latLngProps & {
pane: PropDef<string>;
offset: PropDef<PointExpression>;
direction: PropDef<Direction>;
permanent: PropDef<boolean>;
sticky: PropDef<boolean>;
opacity: PropDef<number>;
} = {
...latLngProps,
pane: str(),
offset: json<PointExpression>([0, 0]),
direction: choice<Direction>('auto'),
permanent: bool(),
sticky: bool(),
opacity: num(1.0),
};
const Base: LeafletElementConstructor<Tooltip, typeof PROPS> = WithProps(PROPS, { attach: 'self' });
export default class LeafletTooltipElement extends Base {
declare readonly leafletObject?: Tooltip;
declare addEventListener: LeafletAddEventListener<DivOverlayLayerEvents>;
declare removeEventListener: LeafletRemoveEventListener<DivOverlayLayerEvents>;
#observer?: MutationObserver;
// Content is the element's markup, not an attribute. A tooltip only carries a
// position of its own when it isn't bound to a parent layer.
createLeafletObject(options: TooltipOptions): Tooltip {
const tooltip = new Tooltip({ ...options, content: this.innerHTML });
if (this.hasAttribute('lat') && this.hasAttribute('lng')) {
tooltip.setLatLng([this.lat, this.lng]);
}
return tooltip;
}
connectedCallback(): void {
super.connectedCallback();
this.#observer = new MutationObserver(() => {
this.leafletObject?.setContent(this.innerHTML);
});
this.#observer.observe(this, { childList: true, characterData: true, subtree: true });
}
disconnectedCallback(): void {
this.#observer?.disconnect();
this.#observer = undefined;
super.disconnectedCallback();
}
}

View File

@ -0,0 +1,82 @@
import {
VideoOverlay,
type CrossOrigin,
type LatLngBoundsExpression,
type VideoOverlayOptions,
} from 'leaflet';
import {
bool,
choice,
json,
num,
positional,
str,
type PropDef,
type Positional,
} from '../core/props.ts';
import { getBounds, urlProp, type Sourced } from '../core/shared-props.ts';
import {
WithProps,
type LeafletAddEventListener,
type LeafletElementConstructor,
type LeafletRemoveEventListener,
} from '../core/with-props.ts';
import type { PathEvents } from '../core/event-types.ts';
// Playback options live on the <video> element Leaflet builds, so live updates
// go there rather than through a Leaflet setter.
function media(
key: 'loop' | 'autoplay' | 'muted' | 'playsInline',
): (obj: VideoOverlay, value: boolean) => void {
return (obj, value) => {
const el = obj.getElement();
if (el) el[key] = value;
};
}
const PROPS: {
url: Positional<string, Sourced>;
bounds: Positional<LatLngBoundsExpression, VideoOverlay>;
opacity: PropDef<number>;
alt: PropDef<string>;
interactive: PropDef<boolean>;
crossOrigin: PropDef<CrossOrigin>;
loop: PropDef<boolean, VideoOverlay>;
autoplay: PropDef<boolean, VideoOverlay>;
muted: PropDef<boolean, VideoOverlay>;
playsInline: PropDef<boolean, VideoOverlay>;
zIndex: PropDef<number>;
className: PropDef<string>;
keepAspectRatio: PropDef<boolean>;
errorOverlayUrl: PropDef<string>;
} = {
url: urlProp,
bounds: positional(json<LatLngBoundsExpression, VideoOverlay>([], { get: getBounds })),
opacity: num(1.0),
alt: str(),
interactive: bool(),
crossOrigin: choice<CrossOrigin>(''),
loop: bool(false, { set: media('loop') }),
autoplay: bool(false, { set: media('autoplay') }),
muted: bool(false, { set: media('muted') }),
playsInline: bool(false, { attribute: 'playsinline', set: media('playsInline') }),
zIndex: num(),
className: str(),
keepAspectRatio: bool(true),
errorOverlayUrl: str(),
};
const Base: LeafletElementConstructor<VideoOverlay, typeof PROPS> = WithProps(PROPS);
export default class LeafletVideoOverlayElement extends Base {
declare readonly leafletObject?: VideoOverlay;
declare addEventListener: LeafletAddEventListener<PathEvents>;
declare removeEventListener: LeafletRemoveEventListener<PathEvents>;
createLeafletObject(options: VideoOverlayOptions): VideoOverlay {
return new VideoOverlay(this.url, this.bounds, options);
}
getElement(): HTMLVideoElement | undefined {
return this.leafletObject?.getElement();
}
}

15
src/index.npm.ts Normal file
View File

@ -0,0 +1,15 @@
// npm package entry point.
//
// Identical to `./index.ts` (every element class, every helper, and the
// side-effect `customElements.define` calls) but additionally installs the
// ambient DOM augmentations from `./core/globals.ts` -- the `leaflet-*` tag
// map and the custom-event map -- so `document.querySelector('leaflet-map')`
// and `el.addEventListener('leaflet-register', ...)` are typed out of the box.
//
// `./index.ts` is kept free of that import because it is the module JSR
// publishes, and JSR's "no slow types" rule forbids `declare global` anywhere
// in the published graph. JSR consumers import `./index.ts` and can pull in
// `leaflet-components/elements` etc.; they just don't get the ambient globals.
import './core/globals.ts';
export * from './index.ts';

View File

@ -1,22 +1,28 @@
// Export order here is load-bearing, not cosmetic: customElements.define()
// upgrades every matching element already in the document immediately and
// synchronously (including running connectedCallback if already connected),
// so a "child" custom element that fires a one-shot announcement on connect
// must be defined *after* every "container" type that needs to hear it --
// otherwise every instance already in a static HTML page upgrades and
// announces itself before the listening parent exists, and that
// The order of the `./components/*` side-effect imports below is load-bearing,
// not cosmetic: each of those modules calls `customElements.define()`, and
// `customElements.define()` upgrades every matching element already in the
// document immediately and synchronously (including running connectedCallback
// if already connected). So a "child" custom element that fires a one-shot
// announcement on connect must be defined *after* every "container" type that
// needs to hear it -- otherwise every instance already in a static HTML page
// upgrades and announces itself before the listening parent exists, and that
// announcement is lost for good (connectedCallback never fires again for an
// element that stays connected). This is the same reason leaflet-map is
// exported first: nothing can register with it before it exists to listen.
// imported first: nothing can register with it before it exists to listen.
//
// The element classes themselves (`./elements/*`, re-exported just below via
// `./elements/index.ts`) carry no `customElements.define`, so their order is
// free -- only the `./components/*` imports further down register anything.
//
// The hierarchy, root to leaf:
// LeafletMap
// -> LeafletControlLayers, LeafletLayerGroup, LeafletFeatureGroup
// LeafletMapElement
// -> LeafletControlLayersElement, LeafletLayerGroupElement,
// LeafletFeatureGroupElement
// (all listen for "leaflet-register" from arbitrary layer children)
// -> every concrete layer type (Marker, Circle, Polygon, TileLayer, ...)
// -> LeafletLine (child of Polygon/Polyline specifically)
// -> LeafletPopup, LeafletTooltip (child of any layer)
// -> LeafletIcon, LeafletDivIcon (child of Marker specifically)
// -> LeafletLineElement (child of Polygon/Polyline specifically)
// -> LeafletPopupElement, LeafletTooltipElement (child of any layer)
// -> LeafletIconElement, LeafletDivIconElement (child of Marker)
// Standalone controls (Zoom/Attribution/Scale) have no such relationship and
// can go anywhere.
export * from './core/register.ts';
@ -28,84 +34,41 @@ export * from './core/props.ts';
export * from './core/with-props.ts';
export * from './core/shared-props.ts';
export * from './core/event-types.ts';
export { LeafletMap } from './components/leaflet-map.ts';
export { LeafletControlLayers } from './components/leaflet-control-layers.ts';
export { LeafletLayerGroup } from './components/leaflet-layer-group.ts';
export { LeafletFeatureGroup } from './components/leaflet-feature-group.ts';
export { LeafletPolygon } from './components/leaflet-polygon.ts';
export { LeafletPolyline } from './components/leaflet-polyline.ts';
export { LeafletMarker } from './components/leaflet-marker.ts';
export { LeafletCircle } from './components/leaflet-circle.ts';
export { LeafletCircleMarker } from './components/leaflet-circle-marker.ts';
export { LeafletRectangle } from './components/leaflet-rectangle.ts';
export { LeafletTileLayer } from './components/leaflet-tile-layer.ts';
export { LeafletTileLayerWMS } from './components/leaflet-tile-layer-wms.ts';
export { LeafletImageOverlay } from './components/leaflet-image-overlay.ts';
export { LeafletVideoOverlay } from './components/leaflet-video-overlay.ts';
export { LeafletSVGOverlay } from './components/leaflet-svg-overlay.ts';
export { LeafletGeoJSON } from './components/leaflet-geojson.ts';
export { LeafletLine } from './components/leaflet-line.ts';
export { LeafletControlZoom } from './components/leaflet-control-zoom.ts';
export { LeafletControlAttribution } from './components/leaflet-control-attribution.ts';
export { LeafletControlScale } from './components/leaflet-control-scale.ts';
export { LeafletPopup } from './components/leaflet-popup.ts';
export { LeafletTooltip } from './components/leaflet-tooltip.ts';
export { LeafletIcon } from './components/leaflet-icon.ts';
export { LeafletDivIcon } from './components/leaflet-div-icon.ts';
// `export { X } from '...'` re-exports X but doesn't bind it locally, so the
// tag map below needs its own type-only imports of the same classes. Order
// doesn't matter here -- these are erased, no customElements.define behind them.
import type { LeafletMap } from './components/leaflet-map.ts';
import type { LeafletMarker } from './components/leaflet-marker.ts';
import type { LeafletCircle } from './components/leaflet-circle.ts';
import type { LeafletCircleMarker } from './components/leaflet-circle-marker.ts';
import type { LeafletLine } from './components/leaflet-line.ts';
import type { LeafletPolygon } from './components/leaflet-polygon.ts';
import type { LeafletPolyline } from './components/leaflet-polyline.ts';
import type { LeafletRectangle } from './components/leaflet-rectangle.ts';
import type { LeafletTileLayer } from './components/leaflet-tile-layer.ts';
import type { LeafletTileLayerWMS } from './components/leaflet-tile-layer-wms.ts';
import type { LeafletImageOverlay } from './components/leaflet-image-overlay.ts';
import type { LeafletVideoOverlay } from './components/leaflet-video-overlay.ts';
import type { LeafletSVGOverlay } from './components/leaflet-svg-overlay.ts';
import type { LeafletLayerGroup } from './components/leaflet-layer-group.ts';
import type { LeafletFeatureGroup } from './components/leaflet-feature-group.ts';
import type { LeafletGeoJSON } from './components/leaflet-geojson.ts';
import type { LeafletControlLayers } from './components/leaflet-control-layers.ts';
import type { LeafletControlZoom } from './components/leaflet-control-zoom.ts';
import type { LeafletControlAttribution } from './components/leaflet-control-attribution.ts';
import type { LeafletControlScale } from './components/leaflet-control-scale.ts';
import type { LeafletPopup } from './components/leaflet-popup.ts';
import type { LeafletTooltip } from './components/leaflet-tooltip.ts';
import type { LeafletIcon } from './components/leaflet-icon.ts';
import type { LeafletDivIcon } from './components/leaflet-div-icon.ts';
// Every element class, with no tag registered. Plugin authors who want a
// class without the `customElements.define` side effect can also import this
// module directly, as `leaflet-components/elements`.
export * from './elements/index.ts';
declare global {
interface HTMLElementTagNameMap {
'leaflet-map': LeafletMap;
'leaflet-marker': LeafletMarker;
'leaflet-circle': LeafletCircle;
'leaflet-circle-marker': LeafletCircleMarker;
'leaflet-line': LeafletLine;
'leaflet-polygon': LeafletPolygon;
'leaflet-polyline': LeafletPolyline;
'leaflet-rectangle': LeafletRectangle;
'leaflet-tile-layer': LeafletTileLayer;
'leaflet-tile-layer-wms': LeafletTileLayerWMS;
'leaflet-image-overlay': LeafletImageOverlay;
'leaflet-video-overlay': LeafletVideoOverlay;
'leaflet-svg-overlay': LeafletSVGOverlay;
'leaflet-layer-group': LeafletLayerGroup;
'leaflet-feature-group': LeafletFeatureGroup;
'leaflet-geojson': LeafletGeoJSON;
'leaflet-control-layers': LeafletControlLayers;
'leaflet-control-zoom': LeafletControlZoom;
'leaflet-control-attribution': LeafletControlAttribution;
'leaflet-control-scale': LeafletControlScale;
'leaflet-popup': LeafletPopup;
'leaflet-tooltip': LeafletTooltip;
'leaflet-icon': LeafletIcon;
'leaflet-div-icon': LeafletDivIcon;
}
}
// Register every tag. Side-effect imports only -- the classes are already
// exported above. Order is load-bearing (see the comment at the top).
import './components/leaflet-map.ts';
import './components/leaflet-control-layers.ts';
import './components/leaflet-layer-group.ts';
import './components/leaflet-feature-group.ts';
import './components/leaflet-polygon.ts';
import './components/leaflet-polyline.ts';
import './components/leaflet-marker.ts';
import './components/leaflet-circle.ts';
import './components/leaflet-circle-marker.ts';
import './components/leaflet-rectangle.ts';
import './components/leaflet-tile-layer.ts';
import './components/leaflet-tile-layer-wms.ts';
import './components/leaflet-image-overlay.ts';
import './components/leaflet-video-overlay.ts';
import './components/leaflet-svg-overlay.ts';
import './components/leaflet-geojson.ts';
import './components/leaflet-line.ts';
import './components/leaflet-control-zoom.ts';
import './components/leaflet-control-attribution.ts';
import './components/leaflet-control-scale.ts';
import './components/leaflet-popup.ts';
import './components/leaflet-tooltip.ts';
import './components/leaflet-icon.ts';
import './components/leaflet-div-icon.ts';
// The `leaflet-*` tag map (HTMLElementTagNameMap) and custom-event map
// (HTMLElementEventMap) augmentations live in `./core/globals.ts`, pulled in
// by the npm entry `./index.npm.ts`. They are deliberately kept out of this
// module: JSR publishes `./index.ts` and rejects `declare global` anywhere in
// its export graph. See `./core/globals.ts` and docs/ for the split.

View File

@ -6,14 +6,16 @@
// that typecheck with "Unused '@ts-expect-error' directive".
import type { DragEndEvent, Popup } from 'leaflet';
import { describe, expectTypeOf, it } from 'vitest';
import type { LeafletMap } from '../../src/components/leaflet-map.ts';
import type { LeafletMarker } from '../../src/components/leaflet-marker.ts';
import type { LeafletControlZoom } from '../../src/components/leaflet-control-zoom.ts';
import type {
LeafletControlZoomElement,
LeafletMapElement,
LeafletMarkerElement,
} from '../../src/elements/index.ts';
describe('HTMLElementTagNameMap augmentation', () => {
it('createElement/querySelector infer the right component class', () => {
expectTypeOf(document.createElement('leaflet-map')).toEqualTypeOf<LeafletMap>();
expectTypeOf(document.createElement('leaflet-marker')).toEqualTypeOf<LeafletMarker>();
expectTypeOf(document.createElement('leaflet-map')).toEqualTypeOf<LeafletMapElement>();
expectTypeOf(document.createElement('leaflet-marker')).toEqualTypeOf<LeafletMarkerElement>();
});
});
@ -45,7 +47,9 @@ describe('per-component addEventListener typing', () => {
it('components with no custom events keep the default HTMLElementEventMap typing', () => {
const zoom = document.createElement('leaflet-control-zoom');
expectTypeOf(zoom.addEventListener).toEqualTypeOf<LeafletControlZoom['addEventListener']>();
expectTypeOf(zoom.addEventListener).toEqualTypeOf<
LeafletControlZoomElement['addEventListener']
>();
zoom.addEventListener('click', (e) => {
expectTypeOf(e).toEqualTypeOf<HTMLElementEventMap['click']>();
});

View File

@ -57,7 +57,7 @@ describe('real page load order (markup before customElements.define)', () => {
// a page does `import 'leaflet-components'`.
const lc = await import('../src/index.ts');
expect(map).toBeInstanceOf(lc.LeafletMap);
expect(map).toBeInstanceOf(lc.LeafletMapElement);
expect(map.leafletObject).toBeDefined();
expect(polygon.leafletObject?.getLatLngs()).toEqual([
[

View File

@ -1,3 +1,10 @@
// Install the ambient DOM augmentations (leaflet-* tag map, custom-event map)
// for the whole test program. In the shipped package these come in through the
// npm entry (src/index.npm.ts); the tests import element modules directly, so
// they need this explicit pull-in to type `addEventListener('leaflet-register',
// ...)` and `querySelector('leaflet-map')`.
import '../src/core/globals.ts';
// jsdom has no ResizeObserver. leaflet-map only uses it to call
// invalidateSize() on resize, which no test here depends on incidentally --
// without a stub, just importing the component throws.