From b3f81014cd1eb73ed77ba9854f26713b105506b0 Mon Sep 17 00:00:00 2001 From: Johannes Raggam Date: Fri, 27 Nov 2026 13:23:38 +0100 Subject: [PATCH 01/22] maint(docs): Start with ADR records. --- docs/adr/0000-README.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 docs/adr/0000-README.md diff --git a/docs/adr/0000-README.md b/docs/adr/0000-README.md new file mode 100644 index 000000000..f7716daef --- /dev/null +++ b/docs/adr/0000-README.md @@ -0,0 +1,9 @@ +# Architecture Decision Records + +This directory contains Architecture Decision Records. + +## References + +- https://www.heise.de/hintergrund/Gut-dokumentiert-Architecture-Decision-Records-4664988.html +- https://martinfowler.com/bliki/ArchitectureDecisionRecord.html +- https://adr.github.io/ From 53bbf9f8c3d8d413a50b0302c6458519c6e9dacc Mon Sep 17 00:00:00 2001 From: Johannes Raggam Date: Fri, 27 Nov 2026 13:25:54 +0100 Subject: [PATCH 02/22] maint(docs): Add ADRs for the automatic pattern lifecycle. ADR 0001: Destroy patterns automatically when they are removed from the DOM, using a single MutationObserver. ADR 0002: Self managed containers, which opt out of the automatic destroy and manage the lifecycle of their patterns themselves. Assisted-by: Claude Opus 5.5 --- ...y-patterns-automatically-on-dom-removal.md | 72 +++++++++++++++++++ ...anaged-containers-for-pattern-lifecycle.md | 47 ++++++++++++ 2 files changed, 119 insertions(+) create mode 100644 docs/adr/0001-destroy-patterns-automatically-on-dom-removal.md create mode 100644 docs/adr/0002-self-managed-containers-for-pattern-lifecycle.md diff --git a/docs/adr/0001-destroy-patterns-automatically-on-dom-removal.md b/docs/adr/0001-destroy-patterns-automatically-on-dom-removal.md new file mode 100644 index 000000000..b0488b4cc --- /dev/null +++ b/docs/adr/0001-destroy-patterns-automatically-on-dom-removal.md @@ -0,0 +1,72 @@ +# 0001 Destroy patterns automatically when removed from the DOM + +Status: Accepted (2026-11-27) + +## Context + +``BasePattern`` has a ``destroy()`` method which removes the instance scoped +event listeners and the pattern reference on the element. It was never called +automatically. Patterns whose elements were removed from the DOM — e.g. by +pat-inject replacing content — kept their listeners on ``window`` and +``document``, which also kept the pattern instance and its detached element +in memory. + +There is no usable "element removed" event: + +- Mutation events (``DOMNodeRemoved``, ``DOMNodeRemovedFromDocument``) are + deprecated and are being removed from browsers. +- ``disconnectedCallback`` only exists for custom elements. Patterns are + initialized on arbitrary elements. +- ``FinalizationRegistry`` / ``WeakRef`` are non-deterministic and cannot + work while listeners on ``window`` or ``document`` keep the instance alive. + +Explicitly destroying patterns in the code which removes DOM (e.g. +pat-inject) would miss removals by third-party code like Mockup, Vue or +custom JavaScript. + +## Decision + +A single ``MutationObserver`` on ``document.documentElement`` with +``{ childList: true, subtree: true }`` (``src/core/lifecycle.js``) destroys +patterns whose elements are removed from the document. + +- ``BasePattern`` instances are tracked in a ``Set`` after ``init()``, if + their element is part of the document. Instances on detached DOM are not + tracked. +- For each mutation batch with removed nodes, the tracked instances are + checked once and those with ``el.isConnected === false`` are destroyed. + Removed subtrees are not searched. +- Checking ``isConnected`` at callback time keeps patterns whose elements + are moved within the same task (removed and re-inserted before the + microtask runs). +- Elements which are detached and re-inserted in a later task are + destroyed. No delay is used: a delay only helps if the element comes back + within the delay, and we know of no case where this matters. +- ``destroy()`` is idempotent and sets ``this.destroyed``. The observer + untracks an instance before calling ``destroy()``, so subclasses not + calling ``super.destroy()`` are not destroyed repeatedly. +- A pattern destroyed before its initialization starts is not initialized + and throws ``not-init``. A pattern whose element is removed during + ``init()`` is destroyed after ``init()``. +- ``destroy()`` only removes the ``pattern-`` reference on the + element if it points to the destroyed instance. +- The root element is observed instead of ``document.body``, so that + replacing the body element is noticed too. The cost is the same. + +## Consequences + +- Instance scoped listeners and patterns are cleaned up without patterns + or callers having to do anything. +- The cost is one pass over the live instances per mutation batch with + removals. Observing ``childList`` only keeps the number of records low. +- Destruction is asynchronous (microtask). Tests need to wait a tick after + removing elements. +- Asynchronous code in patterns must check ``this.destroyed`` after + ``await`` and stop if the pattern was destroyed in the meantime. This + revealed such a bug in pat-tooltip, which accessed the destroyed Tippy + instance after fetching content. +- Components which detach and re-attach their own DOM need an opt-out, see + ADR 0002. +- Only class based patterns (``BasePattern``) are destroyed automatically, + not patterns based on ``src/core/base.js``. +- Removals inside shadow roots are not observed. diff --git a/docs/adr/0002-self-managed-containers-for-pattern-lifecycle.md b/docs/adr/0002-self-managed-containers-for-pattern-lifecycle.md new file mode 100644 index 000000000..2ea616853 --- /dev/null +++ b/docs/adr/0002-self-managed-containers-for-pattern-lifecycle.md @@ -0,0 +1,47 @@ +# 0002 Self managed containers for the pattern lifecycle + +Status: Accepted (2026-11-27) + +## Context + +With ADR 0001, patterns are destroyed when their element is not part of the +document anymore. Some components detach and re-attach their own DOM over an +arbitrary period of time. Tippy, used by pat-tooltip, removes the popper from +the document while the tooltip is hidden and re-inserts it on show. + +Patterns in static tooltip content would be destroyed on hide. On the next +show pat-tooltip re-scans the popper and initializes them again on DOM which +the first initialization already changed. Not every pattern supports that. + +A delay before destroying does not help, because the tooltip can be hidden +for any amount of time. + +## Decision + +Components can mark a container with the ``data-pat-lifecycle-managed`` +attribute (``lifecycle.MANAGED_ATTRIBUTE``) and manage the lifecycle of the +patterns in it themselves. + +- The observer skips disconnected instances for which + ``el.closest("[data-pat-lifecycle-managed]")`` finds a container. + ``closest`` only walks the element's current tree: if the whole container + is detached the instances are kept, if an element is removed from within + the container its patterns are destroyed as usual. +- ``lifecycle.destroy_patterns(root)`` destroys all tracked instances + within ``root``, connected or not. It also sweeps instances which were + removed from a detached managed container, since those removals are not + observed. +- pat-tooltip marks its popper, destroys the patterns in it in + ``destroy()`` and, for ``source: ajax``, on hide before the content is + replaced. + +## Consequences + +- Patterns in static tooltip content are initialized once and survive + hiding and showing. +- Components using the attribute must call ``destroy_patterns`` for their + container, otherwise those patterns are only destroyed if they are + removed from the container. +- If a pat-tooltip popper is appended to a ``target`` element which is + removed while the tooltip trigger stays, the patterns in the tooltip + content stay alive until the tooltip is destroyed. From 30e0dda0cd40ae1374422206a8aa214083c0d986 Mon Sep 17 00:00:00 2001 From: Johannes Raggam Date: Fri, 27 Nov 2026 13:25:55 +0100 Subject: [PATCH 03/22] feat(core basepattern): Destroy patterns automatically when removed from the DOM. A single MutationObserver on the document (src/core/lifecycle.js) tracks BasePattern instances after init. For each mutation batch with removed nodes, instances whose element is not connected to the document anymore are destroyed. Elements moved within the same task are kept; elements detached and re-inserted in a later task are destroyed. Instances on detached DOM are not tracked. destroy() is now idempotent and sets this.destroyed. A pattern destroyed before init is not initialized and throws not-init. A pattern whose element was removed during init is destroyed after init. destroy() only removes the pattern reference on the element if it points to the destroyed instance - before, destroying a not-initialized second instance removed the reference to the initialized first one. pat-tooltip: Do not access the Tippy instance after destroy. Async content loading continued after the pattern was destroyed and failed on the destroyed Tippy instance. Included here, as automatic destroy makes this happen. Ref: ADR 0001 Assisted-by: Claude Opus 5.5 --- src/core/basepattern.js | 46 ++++- src/core/basepattern.md | 30 +++- src/core/basepattern.test.js | 287 ++++++++++++++++++++++++++++++++ src/core/lifecycle.js | 97 +++++++++++ src/pat/tooltip/tooltip.js | 24 ++- src/pat/tooltip/tooltip.test.js | 40 +++++ 6 files changed, 518 insertions(+), 6 deletions(-) create mode 100644 src/core/lifecycle.js diff --git a/src/core/basepattern.js b/src/core/basepattern.js index f7a41a13b..c04c663f0 100644 --- a/src/core/basepattern.js +++ b/src/core/basepattern.js @@ -7,6 +7,7 @@ * For usage, see basepattern.md */ import events from "./events"; +import lifecycle from "./lifecycle"; import logging from "./logging"; import create_uuid from "./uuid"; @@ -38,6 +39,12 @@ class BasePattern { } this.el = el; this.uuid = create_uuid(); + this.destroyed = false; + + // Remember if the element was part of the document at construction + // time. Used to destroy the pattern if the element was removed while + // the pattern was initializing. + const was_connected = el.isConnected; // Notify pre-init this.el.dispatchEvent( @@ -60,6 +67,18 @@ class BasePattern { // Both limitations are gone in next tick. // window.setTimeout(async () => { + if (this.destroyed) { + // Destroyed before initialization. + log.debug(`Not initializing destroyed pattern ${this.name}.`, this.el); + this.el.dispatchEvent( + new Event(`not-init.${this.name}.patterns`, { + bubbles: true, + cancelable: false, + }) + ); + return; + } + if (typeof this.el[`pattern-${this.name}`] !== "undefined") { // Do not reinstantiate log.debug(`Not reinstatiating the pattern ${this.name}.`, this.el); @@ -91,6 +110,17 @@ class BasePattern { // Initialize the pattern await this.init(); + if (!this.destroyed) { + if (this.el.isConnected) { + // Destroy the pattern when the element is removed from + // the document. + lifecycle.track(this); + } else if (was_connected) { + // The element was removed while initializing. + this.destroy(); + } + } + // Notify that now ready this.el.dispatchEvent( new Event(`init.${this.name}.patterns`, { @@ -160,10 +190,24 @@ class BasePattern { * Destroy/remove/unload the pattern from the element. * * Also removes all event listeners registered with ``add_event_listener``. + * + * Called automatically when the pattern's element is removed from the + * document. Calling it more than once has no further effect. + * + * If you override this method, call ``super.destroy()``. */ destroy() { + if (this.destroyed) { + return; + } + this.destroyed = true; + lifecycle.untrack(this); events.remove_event_listener(null, `${this.name}--${this.uuid}--*`); - delete this.el[`pattern-${this.name}`]; + if (this.el[`pattern-${this.name}`] === this) { + // Only remove the reference if it points to this instance and not + // to another instance which was initialized on the element. + delete this.el[`pattern-${this.name}`]; + } } } diff --git a/src/core/basepattern.md b/src/core/basepattern.md index 103b2d60c..99063cf7c 100644 --- a/src/core/basepattern.md +++ b/src/core/basepattern.md @@ -82,9 +82,33 @@ name replaces the previous listener. ``destroy()`` removes all listeners of the instance, but not those of other instances of the same pattern. If you override ``destroy()``, call ``super.destroy()``. -Note: ``destroy()`` is not called automatically when the pattern's element is -removed from the DOM. Until it is called, the listeners and the element stay -referenced. +## Automatic destroy + +``destroy()`` is called automatically when the pattern's element is removed +from the document — either directly or by removing or replacing one of its +ancestors. A single ``MutationObserver`` on the document checks all live +pattern instances whenever nodes are removed (see ``src/core/lifecycle.js``). + +- Only instances whose element is part of the document after ``init()`` are + tracked. Patterns initialized on detached DOM are not destroyed + automatically. +- Moving an element within the same task (e.g. ``appendChild`` of an + existing node, or ``remove()`` followed by re-inserting it) does not + destroy the pattern. Detaching an element and re-inserting it in a later + task (e.g. after an ``await``) destroys the pattern. +- Destruction happens asynchronously in a microtask after the removal. In + tests, wait a tick after removing an element, e.g. ``await utils.timeout(1)``. +- A pattern which is destroyed before its initialization starts is not + initialized and throws ``not-init`` instead of ``init``. A pattern whose + element is removed while ``init()`` runs is destroyed after ``init()``. +- ``destroy()`` can be called multiple times, only the first call has an + effect. Afterwards ``this.destroyed`` is ``true``. Asynchronous code in + your pattern should check ``this.destroyed`` after an ``await`` and stop + if the pattern was destroyed in the meantime. +- If you override ``destroy()``, call ``super.destroy()``. +- Only class based patterns (``BasePattern``) are destroyed automatically, + not patterns based on ``src/core/base.js``. +- Removals inside shadow roots are not observed. ## Replacing a registered pattern diff --git a/src/core/basepattern.test.js b/src/core/basepattern.test.js index d28b56e40..e60389ffe 100644 --- a/src/core/basepattern.test.js +++ b/src/core/basepattern.test.js @@ -473,4 +473,291 @@ describe("Basepattern class tests", function () { ]); }); }); + + describe("9 - Automatic destroy on removal from the DOM.", function () { + let lifecycle; + let events; + + class Pat extends BasePattern { + static name = "example"; + static trigger = ".example"; + } + + beforeEach(async function () { + ({ default: lifecycle } = await import("./lifecycle")); + ({ default: events } = await import("./events")); + }); + + afterEach(function () { + document.body.innerHTML = ""; + }); + + it("9.1 - Connected instances are tracked after init.", async function () { + document.body.innerHTML = `
`; + const el = document.querySelector(".example"); + const pat = new Pat(el); + await events.await_pattern_init(pat); + + expect(pat.destroyed).toBe(false); + expect(lifecycle.is_tracked(pat)).toBe(true); + }); + + it("9.2 - Detached instances are not tracked and not destroyed.", async function () { + const el = document.createElement("div"); + const pat = new Pat(el); + await events.await_pattern_init(pat); + + expect(lifecycle.is_tracked(pat)).toBe(false); + + // Trigger the observer with an unrelated removal. + document.body.innerHTML = `
`; + document.body.innerHTML = ""; + await utils.timeout(1); + + expect(pat.destroyed).toBe(false); + expect(el["pattern-example"]).toBe(pat); + }); + + it("9.3 - Removing the element destroys the pattern.", async function () { + document.body.innerHTML = `
`; + const el = document.querySelector(".example"); + const pat = new Pat(el); + await events.await_pattern_init(pat); + + const cb = jest.fn(); + pat.add_event_listener(document, "keydown", "key", cb); + const destroy_spy = jest.spyOn(pat, "destroy"); + + el.remove(); + await utils.timeout(1); + + expect(destroy_spy).toHaveBeenCalledTimes(1); + expect(pat.destroyed).toBe(true); + expect(lifecycle.is_tracked(pat)).toBe(false); + expect(el["pattern-example"]).toBe(undefined); + + document.dispatchEvent(new KeyboardEvent("keydown")); + expect(cb).not.toHaveBeenCalled(); + }); + + it("9.4 - Removing an ancestor destroys the pattern.", async function () { + document.body.innerHTML = ` +
+
+
+ `; + const el = document.querySelector(".example"); + const pat = new Pat(el); + await events.await_pattern_init(pat); + + document.querySelector("section").remove(); + await utils.timeout(1); + + expect(pat.destroyed).toBe(true); + }); + + it("9.5 - Replacing the content destroys the pattern.", async function () { + document.body.innerHTML = `
`; + const pat = new Pat(document.querySelector(".example")); + await events.await_pattern_init(pat); + + document.body.innerHTML = `
`; + await utils.timeout(1); + + expect(pat.destroyed).toBe(true); + }); + + it("9.6 - Moving the element within the same task does not destroy the pattern.", async function () { + document.body.innerHTML = ` +
+
+ `; + const el = document.querySelector(".example"); + const pat = new Pat(el); + await events.await_pattern_init(pat); + + // appendChild removes and re-inserts the node. + document.querySelector(".b").appendChild(el); + // Explicit detach and re-attach in the same task. + el.remove(); + document.querySelector(".a").appendChild(el); + await utils.timeout(1); + + expect(pat.destroyed).toBe(false); + expect(lifecycle.is_tracked(pat)).toBe(true); + }); + + it("9.7 - Detaching and re-attaching in a later task destroys the pattern.", async function () { + document.body.innerHTML = `
`; + const el = document.querySelector(".example"); + const pat = new Pat(el); + await events.await_pattern_init(pat); + + el.remove(); + await utils.timeout(1); + document.body.appendChild(el); + await utils.timeout(1); + + expect(pat.destroyed).toBe(true); + expect(el["pattern-example"]).toBe(undefined); + }); + + it("9.8 - Only the removed instances are destroyed.", async function () { + document.body.innerHTML = ` +
+
+ `; + const pat1 = new Pat(document.querySelector("#one")); + const pat2 = new Pat(document.querySelector("#two")); + await events.await_pattern_init(pat1); + await events.await_pattern_init(pat2); + + pat1.el.remove(); + await utils.timeout(1); + + expect(pat1.destroyed).toBe(true); + expect(pat2.destroyed).toBe(false); + }); + + it("9.9 - destroy() is idempotent and untracks the instance.", async function () { + document.body.innerHTML = `
`; + const el = document.querySelector(".example"); + const pat = new Pat(el); + await events.await_pattern_init(pat); + + pat.destroy(); + expect(lifecycle.is_tracked(pat)).toBe(false); + + // A new instance on the same element must not be unregistered by + // destroying the old instance again. + const pat2 = new Pat(el); + await events.await_pattern_init(pat2); + pat.destroy(); + expect(el["pattern-example"]).toBe(pat2); + + // Removing the element destroys the new instance only once. + const destroy_spy = jest.spyOn(pat2, "destroy"); + el.remove(); + await utils.timeout(1); + expect(destroy_spy).toHaveBeenCalledTimes(1); + }); + + it("9.10 - destroy() of a not-initialized instance keeps the reference to the initialized one.", async function () { + const el = document.createElement("div"); + const pat1 = new Pat(el); + await events.await_pattern_init(pat1); + + const pat2 = new Pat(el); + await expect(events.await_pattern_init(pat2)).rejects.toBeDefined(); + + pat2.destroy(); + expect(el["pattern-example"]).toBe(pat1); + }); + + it("9.11 - A pattern destroyed before init is not initialized.", async function () { + const init_spy = jest.spyOn(Pat.prototype, "init"); + + document.body.innerHTML = `
`; + const el = document.querySelector(".example"); + const pat = new Pat(el); + pat.destroy(); + + await expect(events.await_pattern_init(pat)).rejects.toBeDefined(); + + expect(init_spy).not.toHaveBeenCalled(); + expect(el["pattern-example"]).toBe(undefined); + expect(lifecycle.is_tracked(pat)).toBe(false); + }); + + it("9.12 - A pattern removed while initializing is destroyed after init.", async function () { + class AsyncPat extends BasePattern { + static name = "example-async"; + static trigger = ".example"; + async init() { + // Element is removed while initializing. + this.el.remove(); + await utils.timeout(1); + } + } + + document.body.innerHTML = `
`; + const el = document.querySelector(".example"); + const pat = new AsyncPat(el); + await events.await_pattern_init(pat); + + expect(pat.destroyed).toBe(true); + expect(lifecycle.is_tracked(pat)).toBe(false); + expect(el["pattern-example-async"]).toBe(undefined); + }); + + it("9.13 - A pattern destroyed while initializing is not tracked.", async function () { + class AsyncPat extends BasePattern { + static name = "example-async"; + static trigger = ".example"; + async init() { + await utils.timeout(1); + } + } + + document.body.innerHTML = `
`; + const el = document.querySelector(".example"); + const pat = new AsyncPat(el); + await utils.timeout(1); // init has started. + pat.destroy(); + await events.await_pattern_init(pat); + + expect(pat.destroyed).toBe(true); + expect(lifecycle.is_tracked(pat)).toBe(false); + }); + + it("9.14 - Errors in destroy do not prevent destroying other patterns.", async function () { + class FailingPat extends BasePattern { + static name = "example-failing"; + static trigger = ".failing"; + destroy() { + super.destroy(); + throw new Error("destroy failed"); + } + } + + document.body.innerHTML = ` +
+
+ `; + const pat1 = new FailingPat(document.querySelector(".failing")); + const pat2 = new Pat(document.querySelector(".example")); + await events.await_pattern_init(pat1); + await events.await_pattern_init(pat2); + + document.body.innerHTML = ""; + await utils.timeout(1); + + expect(pat1.destroyed).toBe(true); + expect(pat2.destroyed).toBe(true); + }); + + it("9.15 - A subclass not calling super.destroy() is destroyed only once.", async function () { + const destroy_cb = jest.fn(); + class BadPat extends BasePattern { + static name = "example-bad"; + static trigger = ".bad"; + destroy() { + destroy_cb(); + } + } + + document.body.innerHTML = `
`; + const pat = new BadPat(document.querySelector(".bad")); + await events.await_pattern_init(pat); + + document.body.innerHTML = ""; + await utils.timeout(1); + document.body.innerHTML = `
`; + document.body.innerHTML = ""; + await utils.timeout(1); + + expect(destroy_cb).toHaveBeenCalledTimes(1); + expect(lifecycle.is_tracked(pat)).toBe(false); + }); + }); }); diff --git a/src/core/lifecycle.js b/src/core/lifecycle.js new file mode 100644 index 000000000..9df073a51 --- /dev/null +++ b/src/core/lifecycle.js @@ -0,0 +1,97 @@ +/** + * Pattern lifecycle - automatically destroy patterns which were removed from + * the DOM. + * + * A single MutationObserver watches the whole document for removed nodes. + * For each batch of mutations with removals, all tracked pattern instances + * are checked and those whose element is not connected to the document + * anymore are destroyed. + * + * Checking ``isConnected`` instead of searching the removed subtrees keeps + * the cost at one pass over the live instances per mutation batch and + * correctly handles nodes which are moved within the same task (removed and + * re-inserted before the observer callback runs). + * + * Nodes which are detached and re-inserted in a later task are destroyed. + */ +import logging from "./logging"; + +const log = logging.getLogger("lifecycle"); + +const live_instances = new Set(); +let observer = null; + +function destroy_instance(instance) { + // Untrack first, so that the instance is not destroyed again even if + // a subclass' ``destroy`` does not call ``super.destroy()``. + live_instances.delete(instance); + try { + instance.destroy(); + } catch (e) { + log.error(`Error destroying pattern ${instance.name}.`, e); + } +} + +function destroy_disconnected() { + for (const instance of live_instances) { + if (instance.el.isConnected) { + continue; + } + destroy_instance(instance); + } +} + +function on_mutations(records) { + if (!records.some((record) => record.removedNodes.length)) { + return; + } + destroy_disconnected(); +} + +function start_observer() { + if (observer) { + return; + } + observer = new MutationObserver(on_mutations); + // Observe the root element instead of ``document.body`` so that replacing + // the body element is noticed too. + observer.observe(document.documentElement, { childList: true, subtree: true }); +} + +/** + * Track a pattern instance and destroy it when its element is removed from + * the document. + * + * Instances on elements which are not connected to the document are not + * tracked. They would be destroyed immediately. + * + * @param {BasePattern} instance - The pattern instance. + */ +export function track(instance) { + if (!instance?.el?.isConnected) { + return; + } + live_instances.add(instance); + start_observer(); +} + +/** + * Stop tracking a pattern instance. + * + * @param {BasePattern} instance - The pattern instance. + */ +export function untrack(instance) { + live_instances.delete(instance); +} + +/** + * Check if a pattern instance is tracked. + * + * @param {BasePattern} instance - The pattern instance. + * @returns {boolean} + */ +export function is_tracked(instance) { + return live_instances.has(instance); +} + +export default { track, untrack, is_tracked }; diff --git a/src/pat/tooltip/tooltip.js b/src/pat/tooltip/tooltip.js index 94bbd9978..14a9715c7 100644 --- a/src/pat/tooltip/tooltip.js +++ b/src/pat/tooltip/tooltip.js @@ -131,13 +131,19 @@ class Pattern extends BasePattern { async hide() { // Hide this tooltip await utils.timeout(1); // wait a tick for event being processed by other handlers. + if (this.destroyed) { + return; + } this.tippy.hide(); } destroy() { // Remove this tooltip + if (this.destroyed) { + return; + } super.destroy(); // Unregister - this.tippy.destroy(); + this.tippy?.destroy(); } parseOptionsForTippy(opts) { @@ -324,6 +330,10 @@ class Pattern extends BasePattern { if (this.options.source === "ajax") { await this._get_content(); + if (this.destroyed) { + // Destroyed while fetching the content. + return; + } } // Notify parent patterns about injected content. @@ -378,16 +388,26 @@ class Pattern extends BasePattern { content = document.querySelector(selector); content = content?.innerHTML || undefined; } + if (this.destroyed) { + // Destroyed while fetching the content. + return; + } if (content) { this.tippy.setContent(content); await utils.timeout(1); // Wait a tick before forceUpdate. Might fail due to unset popperInstance. - this.tippy.popperInstance.forceUpdate(); // re-position tippy after content is known. + if (this.destroyed) { + return; + } + this.tippy.popperInstance?.forceUpdate(); // re-position tippy after content is known. } } async get_content(url = this.options.url) { // API method: _get_content + _initialize_content await this._get_content(url); + if (this.destroyed) { + return; + } this._initialize_content(); } diff --git a/src/pat/tooltip/tooltip.test.js b/src/pat/tooltip/tooltip.test.js index f11b80743..cc558b37e 100644 --- a/src/pat/tooltip/tooltip.test.js +++ b/src/pat/tooltip/tooltip.test.js @@ -1316,6 +1316,46 @@ describe("pat-tooltip", () => { expect(expected).toBe(tooltip_content); }); + it("6.9.1 - source: ajax does not fail when destroyed while fetching.", async () => { + let resolve_fetch; + global.fetch = jest.fn().mockImplementation( + () => + new Promise((resolve) => { + resolve_fetch = () => + resolve({ text: () => Promise.resolve("Fetched.") }); + }) + ); + + const $el = testutils.createTooltip({ + data: "source: ajax", + href: "http://test.com", + }); + const instance = new Pattern($el); + await events.await_pattern_init(instance); + + const spy_initialize = jest.spyOn(instance, "_initialize_content"); + const spy_set_content = jest.spyOn(instance.tippy, "setContent"); + + testutils.click($el); + await utils.timeout(1); + expect(global.fetch).toHaveBeenCalled(); + + // Remove the tooltip while the request is pending. + $el.remove(); + await utils.timeout(1); + expect(instance.destroyed).toBe(true); + + resolve_fetch(); + await utils.timeout(10); + + // The fetched content is not set on the destroyed tippy instance. + expect(spy_set_content).not.toHaveBeenCalledWith("Fetched."); + expect(spy_initialize).not.toHaveBeenCalled(); + + global.fetch.mockRestore(); + delete global.fetch; + }); + describe("6.10 - source: content-text", () => { it.each([ [ From 25d6f252972fb3f2abffbd937849024aace19983 Mon Sep 17 00:00:00 2001 From: Johannes Raggam Date: Fri, 27 Nov 2026 13:26:17 +0100 Subject: [PATCH 04/22] feat(core lifecycle): Add self managed containers. Patterns inside a detached container marked with the data-pat-lifecycle-managed attribute (lifecycle.MANAGED_ATTRIBUTE) are not destroyed automatically. Patterns removed from within such a container are destroyed as usual. This is for components which detach and re-attach their own DOM, like Tippy's popper in pat-tooltip. lifecycle.destroy_patterns(root) destroys all tracked patterns within a connected or detached subtree. Components using managed containers use it to destroy the patterns in their container. Ref: ADR 0002 Assisted-by: Claude Opus 5.5 --- src/core/basepattern.md | 37 ++++++++++ src/core/basepattern.test.js | 132 +++++++++++++++++++++++++++++++++++ src/core/lifecycle.js | 51 +++++++++++++- 3 files changed, 219 insertions(+), 1 deletion(-) diff --git a/src/core/basepattern.md b/src/core/basepattern.md index 99063cf7c..d56caf83b 100644 --- a/src/core/basepattern.md +++ b/src/core/basepattern.md @@ -110,6 +110,43 @@ pattern instances whenever nodes are removed (see ``src/core/lifecycle.js``). not patterns based on ``src/core/base.js``. - Removals inside shadow roots are not observed. +### Self managed containers + +Components which detach and re-attach their own DOM can opt out of the +automatic destroy for their content. pat-tooltip does this for its popper, +which Tippy removes from the document while the tooltip is hidden. + +Mark the container with the ``data-pat-lifecycle-managed`` attribute +(``lifecycle.MANAGED_ATTRIBUTE``). Patterns which are still inside such a +container are not destroyed while the container is detached. Patterns removed +from within the container are destroyed as usual. + +The component is then responsible for destroying the patterns in its +container, e.g. in its own ``destroy()`` or when it replaces the content: + +```javascript +import lifecycle from "@patternslib/patternslib/src/core/lifecycle"; + +class Pattern extends BasePattern { + async init() { + this.container = this.create_container(); + this.container.setAttribute(lifecycle.MANAGED_ATTRIBUTE, ""); + } + + destroy() { + if (this.destroyed) { + return; + } + super.destroy(); + lifecycle.destroy_patterns(this.container); + } +} +``` + +``lifecycle.destroy_patterns(root)`` destroys all tracked patterns within +``root``, including ``root`` itself, whether ``root`` is part of the document +or not. + ## Replacing a registered pattern The first registration of a pattern name wins — registering another pattern diff --git a/src/core/basepattern.test.js b/src/core/basepattern.test.js index e60389ffe..ad0c26656 100644 --- a/src/core/basepattern.test.js +++ b/src/core/basepattern.test.js @@ -760,4 +760,136 @@ describe("Basepattern class tests", function () { expect(lifecycle.is_tracked(pat)).toBe(false); }); }); + + describe("10 - Self managed containers.", function () { + let lifecycle; + let events; + + class Pat extends BasePattern { + static name = "example"; + static trigger = ".example"; + } + + const setup = async () => { + document.body.innerHTML = ` +
+
+
+
+
+
+
+ `; + const pat1 = new Pat(document.querySelector("#one")); + const pat2 = new Pat(document.querySelector("#two")); + const pat_outside = new Pat(document.querySelector("#outside")); + await events.await_pattern_init(pat1); + await events.await_pattern_init(pat2); + await events.await_pattern_init(pat_outside); + return { + managed: document.querySelector(".managed"), + pat1, + pat2, + pat_outside, + }; + }; + + // Trigger the observer with an unrelated removal. + const trigger_observer = async () => { + document.body.appendChild(document.createElement("div")).remove(); + await utils.timeout(1); + }; + + beforeEach(async function () { + ({ default: lifecycle } = await import("./lifecycle")); + ({ default: events } = await import("./events")); + }); + + afterEach(function () { + document.body.innerHTML = ""; + }); + + it("10.1 - Patterns in a detached managed container are not destroyed.", async function () { + const { managed, pat1, pat2 } = await setup(); + + managed.remove(); + await utils.timeout(1); + await trigger_observer(); + + expect(pat1.destroyed).toBe(false); + expect(pat2.destroyed).toBe(false); + expect(lifecycle.is_tracked(pat1)).toBe(true); + + // Re-attach in a later task. + document.body.appendChild(managed); + await utils.timeout(1); + expect(pat1.destroyed).toBe(false); + expect(pat1.el["pattern-example"]).toBe(pat1); + }); + + it("10.2 - Patterns removed from within a managed container are destroyed.", async function () { + const { pat1, pat2 } = await setup(); + + document.querySelector(".wrapper").remove(); + await utils.timeout(1); + + expect(pat1.destroyed).toBe(true); + expect(pat2.destroyed).toBe(false); + }); + + it("10.3 - destroy_patterns destroys the patterns within a subtree.", async function () { + const { managed, pat1, pat2, pat_outside } = await setup(); + + managed.remove(); + await utils.timeout(1); + + lifecycle.destroy_patterns(managed); + + expect(pat1.destroyed).toBe(true); + expect(pat2.destroyed).toBe(true); + expect(lifecycle.is_tracked(pat1)).toBe(false); + expect(lifecycle.is_tracked(pat2)).toBe(false); + expect(pat_outside.destroyed).toBe(false); + }); + + it("10.4 - destroy_patterns includes the root element.", async function () { + const { pat1, pat2 } = await setup(); + + lifecycle.destroy_patterns(pat1.el); + + expect(pat1.destroyed).toBe(true); + expect(pat2.destroyed).toBe(false); + }); + + it("10.5 - Patterns removed from a detached managed container are destroyed with the next sweep.", async function () { + const { managed, pat1, pat2 } = await setup(); + + managed.remove(); + await utils.timeout(1); + + // Not observed - the container is not part of the document. + managed.querySelector(".wrapper").remove(); + await utils.timeout(1); + expect(pat1.destroyed).toBe(false); + + // Swept on the next observed removal. + await trigger_observer(); + expect(pat1.destroyed).toBe(true); + expect(pat2.destroyed).toBe(false); + }); + + it("10.6 - destroy_patterns also sweeps patterns removed from a detached managed container.", async function () { + const { managed, pat1, pat2 } = await setup(); + + managed.remove(); + await utils.timeout(1); + const wrapper = managed.querySelector(".wrapper"); + wrapper.remove(); + + lifecycle.destroy_patterns(managed); + + expect(pat1.destroyed).toBe(true); + expect(pat2.destroyed).toBe(true); + }); + }); }); diff --git a/src/core/lifecycle.js b/src/core/lifecycle.js index 9df073a51..4d9abbfce 100644 --- a/src/core/lifecycle.js +++ b/src/core/lifecycle.js @@ -13,11 +13,26 @@ * re-inserted before the observer callback runs). * * Nodes which are detached and re-inserted in a later task are destroyed. + * + * Self managed containers + * ----------------------- + * + * Some components detach and re-attach their own DOM, e.g. pat-tooltip, + * whose popper is removed from the document while the tooltip is hidden. + * Such components mark their container with the ``data-pat-lifecycle-managed`` + * attribute (see ``MANAGED_ATTRIBUTE``). Disconnected instances which are + * still inside such a container are not destroyed. The component is + * responsible for destroying them via ``destroy_patterns``. + * + * Instances removed from within a managed container are not inside it + * anymore and are destroyed as usual. */ import logging from "./logging"; const log = logging.getLogger("lifecycle"); +export const MANAGED_ATTRIBUTE = "data-pat-lifecycle-managed"; + const live_instances = new Set(); let observer = null; @@ -37,6 +52,10 @@ function destroy_disconnected() { if (instance.el.isConnected) { continue; } + if (instance.el.closest(`[${MANAGED_ATTRIBUTE}]`)) { + // Inside a detached, self managed container. + continue; + } destroy_instance(instance); } } @@ -84,6 +103,30 @@ export function untrack(instance) { live_instances.delete(instance); } +/** + * Destroy all tracked pattern instances within a DOM subtree. + * + * Works for connected and detached subtrees. Used by components which manage + * the lifecycle of their own DOM, see ``MANAGED_ATTRIBUTE``. + * + * Also destroys tracked instances which were removed from a detached managed + * container. Those removals are not observed, because the container is not + * part of the document. + * + * @param {Node} root - The root of the subtree. Included in the search. + */ +export function destroy_patterns(root) { + if (!root) { + return; + } + for (const instance of live_instances) { + if (root.contains(instance.el)) { + destroy_instance(instance); + } + } + destroy_disconnected(); +} + /** * Check if a pattern instance is tracked. * @@ -94,4 +137,10 @@ export function is_tracked(instance) { return live_instances.has(instance); } -export default { track, untrack, is_tracked }; +export default { + MANAGED_ATTRIBUTE, + track, + untrack, + destroy_patterns, + is_tracked, +}; From 628f022bb40781e56c59aaefe56e65f6b6727aa8 Mon Sep 17 00:00:00 2001 From: Johannes Raggam Date: Fri, 27 Nov 2026 13:41:21 +0100 Subject: [PATCH 05/22] feat(core basepattern): Add instance scoped remove_event_listener. this.remove_event_listener(el, name) removes a listener registered with this.add_event_listener under the same name, without building the instance namespaced id by hand. Without an element nothing is removed, instead of removing the listener from all elements. Assisted-by: Claude Opus 5.5 --- src/core/basepattern.js | 17 +++++++++++++++++ src/core/basepattern.md | 3 +++ src/core/basepattern.test.js | 37 ++++++++++++++++++++++++++++++++++++ 3 files changed, 57 insertions(+) diff --git a/src/core/basepattern.js b/src/core/basepattern.js index c04c663f0..6eedbb2b4 100644 --- a/src/core/basepattern.js +++ b/src/core/basepattern.js @@ -186,6 +186,23 @@ class BasePattern { ); } + /** + * Remove an event listener which was registered with ``add_event_listener``. + * + * Only removes listeners of this pattern instance. + * + * @param {Node|Window} el - The element the event listener was registered on. + * @param {string} name - The name of the listener, as passed to ``add_event_listener``. + */ + remove_event_listener(el, name) { + if (!el) { + // Without an element, events.remove_event_listener would remove + // the listener from all elements. + return; + } + events.remove_event_listener(el, `${this.name}--${this.uuid}--${name}`); + } + /** * Destroy/remove/unload the pattern from the element. * diff --git a/src/core/basepattern.md b/src/core/basepattern.md index d56caf83b..bd01b5c12 100644 --- a/src/core/basepattern.md +++ b/src/core/basepattern.md @@ -82,6 +82,9 @@ name replaces the previous listener. ``destroy()`` removes all listeners of the instance, but not those of other instances of the same pattern. If you override ``destroy()``, call ``super.destroy()``. +To remove a single listener before the pattern is destroyed, use +``this.remove_event_listener(el, name)`` with the same element and name. + ## Automatic destroy ``destroy()`` is called automatically when the pattern's element is removed diff --git a/src/core/basepattern.test.js b/src/core/basepattern.test.js index ad0c26656..79ab53955 100644 --- a/src/core/basepattern.test.js +++ b/src/core/basepattern.test.js @@ -472,6 +472,43 @@ describe("Basepattern class tests", function () { `example--${pat2.uuid}--resize`, ]); }); + + it("8.4 - remove_event_listener removes only the named listener of this instance.", async function () { + const el1 = document.createElement("div"); + const el2 = document.createElement("div"); + const pat1 = new Pat(el1); + const pat2 = new Pat(el2); + await events.await_pattern_init(pat1); + await events.await_pattern_init(pat2); + + const cb1_key = jest.fn(); + const cb1_other = jest.fn(); + const cb2_key = jest.fn(); + pat1.add_event_listener(document, "keydown", "key", cb1_key); + pat1.add_event_listener(document, "keydown", "other", cb1_other); + pat2.add_event_listener(document, "keydown", "key", cb2_key); + + pat1.remove_event_listener(document, "key"); + + document.dispatchEvent(new KeyboardEvent("keydown")); + expect(cb1_key).not.toHaveBeenCalled(); + expect(cb1_other).toHaveBeenCalledTimes(1); + expect(cb2_key).toHaveBeenCalledTimes(1); + }); + + it("8.5 - remove_event_listener without an element does nothing.", async function () { + const el = document.createElement("div"); + const pat = new Pat(el); + await events.await_pattern_init(pat); + + const cb = jest.fn(); + pat.add_event_listener(document, "keydown", "key", cb); + + pat.remove_event_listener(null, "key"); + + document.dispatchEvent(new KeyboardEvent("keydown")); + expect(cb).toHaveBeenCalledTimes(1); + }); }); describe("9 - Automatic destroy on removal from the DOM.", function () { From f3a201ff25497ed2b29f2e58e61512d4726a8004 Mon Sep 17 00:00:00 2001 From: Johannes Raggam Date: Fri, 27 Nov 2026 13:46:14 +0100 Subject: [PATCH 06/22] fix(core basepattern): Remove listeners registered after a destroy during init. If a pattern was destroyed while its asynchronous init was still running, listeners registered with add_event_listener later in init were never removed. Remove them after init. Ref: ADR 0001 Assisted-by: Claude Opus 5.5 --- ...y-patterns-automatically-on-dom-removal.md | 4 +++- src/core/basepattern.js | 6 +++++- src/core/basepattern.test.js | 21 +++++++++++++++++++ 3 files changed, 29 insertions(+), 2 deletions(-) diff --git a/docs/adr/0001-destroy-patterns-automatically-on-dom-removal.md b/docs/adr/0001-destroy-patterns-automatically-on-dom-removal.md index b0488b4cc..2e46ef956 100644 --- a/docs/adr/0001-destroy-patterns-automatically-on-dom-removal.md +++ b/docs/adr/0001-destroy-patterns-automatically-on-dom-removal.md @@ -47,7 +47,9 @@ patterns whose elements are removed from the document. calling ``super.destroy()`` are not destroyed repeatedly. - A pattern destroyed before its initialization starts is not initialized and throws ``not-init``. A pattern whose element is removed during - ``init()`` is destroyed after ``init()``. + ``init()`` is destroyed after ``init()``. Listeners registered with + ``add_event_listener`` after a ``destroy()`` during ``init()`` are removed + after ``init()``. - ``destroy()`` only removes the ``pattern-`` reference on the element if it points to the destroyed instance. - The root element is observed instead of ``document.body``, so that diff --git a/src/core/basepattern.js b/src/core/basepattern.js index 6eedbb2b4..7d747936b 100644 --- a/src/core/basepattern.js +++ b/src/core/basepattern.js @@ -110,7 +110,11 @@ class BasePattern { // Initialize the pattern await this.init(); - if (!this.destroyed) { + if (this.destroyed) { + // Destroyed while initializing. Remove the listeners which + // were registered after the destroy. + events.remove_event_listener(null, `${this.name}--${this.uuid}--*`); + } else { if (this.el.isConnected) { // Destroy the pattern when the element is removed from // the document. diff --git a/src/core/basepattern.test.js b/src/core/basepattern.test.js index 79ab53955..8594e4bea 100644 --- a/src/core/basepattern.test.js +++ b/src/core/basepattern.test.js @@ -747,6 +747,27 @@ describe("Basepattern class tests", function () { expect(lifecycle.is_tracked(pat)).toBe(false); }); + it("9.13.1 - Listeners registered after a destroy during init are removed.", async function () { + const cb = jest.fn(); + class AsyncPat extends BasePattern { + static name = "example-async"; + static trigger = ".example"; + async init() { + await utils.timeout(1); + this.add_event_listener(document, "keydown", "key", cb); + } + } + + document.body.innerHTML = `
`; + const pat = new AsyncPat(document.querySelector(".example")); + await utils.timeout(1); // init has started. + pat.destroy(); + await events.await_pattern_init(pat); + + document.dispatchEvent(new KeyboardEvent("keydown")); + expect(cb).not.toHaveBeenCalled(); + }); + it("9.14 - Errors in destroy do not prevent destroying other patterns.", async function () { class FailingPat extends BasePattern { static name = "example-failing"; From 7d27bb8dd79a4c75641f46fb993c0c5367db8b6f Mon Sep 17 00:00:00 2001 From: Johannes Raggam Date: Fri, 27 Nov 2026 14:54:52 +0100 Subject: [PATCH 07/22] maint(docs): Add ADR 0003 for the WeakMap based event listener registry. Assisted-by: Claude Opus 5.5 --- .../0003-weakmap-event-listener-registry.md | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 docs/adr/0003-weakmap-event-listener-registry.md diff --git a/docs/adr/0003-weakmap-event-listener-registry.md b/docs/adr/0003-weakmap-event-listener-registry.md new file mode 100644 index 000000000..1d172c1e5 --- /dev/null +++ b/docs/adr/0003-weakmap-event-listener-registry.md @@ -0,0 +1,53 @@ +# 0003 WeakMap based event listener registry + +Status: Accepted (2026-11-27) + +## Context + +``events.add_event_listener`` stores the registered listeners in +``event_listener_map``, keyed by element, so that they can be removed by id +later. This was a ``Map``, which kept every element with registered +listeners in memory until its listeners were removed explicitly - even +after the element was removed from the DOM. Old style patterns +(``src/core/base.js``) and other code which do not remove their listeners +leaked the removed DOM this way. + +A ``Map`` was needed for removing listeners from all elements at once: +``remove_event_listener(null, id)`` and ``remove_event_listener()``. Within +Patternslib this was only used by ``BasePattern.destroy()`` (added with +ADR 0001) and by tests. + +## Decision + +``event_listener_map`` is a ``WeakMap>``. + +- The registry does not keep elements alive anymore. Elements which are + not referenced otherwise are garbage collected together with their + listeners. +- Listeners can only be removed per element. ``remove_event_listener`` + without an element logs a warning and removes nothing. +- Removing by exact id, by wildcard id (e.g. ``--*``) and all + listeners of an element keeps working, as the per element registry is + still an iterable ``Map``. +- ``BasePattern`` remembers the elements it registered listeners on via + ``this.add_event_listener`` and removes its listeners per element on + ``destroy()``. An element is forgotten when the instance's last + listener on it is removed with ``this.remove_event_listener``. + +This is released as a feature, not as a breaking change: removing listeners +from all elements at once is not used outside of Patternslib's own code and +tests. + +## Consequences + +- No more leaks via the event listener registry. +- Code which wants to remove a namespace of listeners has to know the + elements it registered them on, e.g. + ``events.remove_event_listener(document, "plone-modal-3--*")``. A + planned migration of Mockup's plone-modal from jQuery namespaced + handlers to ``events.add_event_listener`` has to remove its listeners + this way. +- The outer registry cannot be inspected or cleared as a whole anymore, + e.g. in tests. +- Keeping element-less removal would need an additional, iterable + registry of ``WeakRef`` objects to the elements. This was not done for now. From 0f91479a1ce03573739682e898ca89c2e0e5b489 Mon Sep 17 00:00:00 2001 From: Johannes Raggam Date: Fri, 27 Nov 2026 14:54:52 +0100 Subject: [PATCH 08/22] feat(core events): Do not keep elements alive in the event listener registry. event_listener_map is now a WeakMap. Elements with registered listeners are garbage collected when they are not referenced otherwise, instead of being kept in memory until their listeners are removed explicitly. As a WeakMap cannot be iterated, listeners can only be removed per element. remove_event_listener without an element logs a warning and removes nothing. Removing by id, by wildcard id and all listeners of an element keeps working. BasePattern remembers the elements it registered listeners on and removes its listeners from them on destroy. Ref: ADR 0003 Assisted-by: Claude Opus 5.5 --- src/core/basepattern.js | 45 +++++++--- src/core/basepattern.test.js | 35 +++++++- src/core/events.js | 76 +++++++++-------- src/core/events.test.js | 158 +++++++---------------------------- 4 files changed, 135 insertions(+), 179 deletions(-) diff --git a/src/core/basepattern.js b/src/core/basepattern.js index 7d747936b..e7e02bc44 100644 --- a/src/core/basepattern.js +++ b/src/core/basepattern.js @@ -6,7 +6,7 @@ * * For usage, see basepattern.md */ -import events from "./events"; +import events, { event_listener_map } from "./events"; import lifecycle from "./lifecycle"; import logging from "./logging"; import create_uuid from "./uuid"; @@ -24,6 +24,11 @@ class BasePattern { parser_multiple = undefined; parser_inherit = true; + // Elements with listeners registered via ``add_event_listener``. + // The event listener registry is a WeakMap which cannot be iterated, so + // remember the elements to remove the listeners on destroy. + _listener_els = new Set(); + constructor(el, options = {}) { // Make static variables available on instance. this.name = this.constructor.name; @@ -113,7 +118,7 @@ class BasePattern { if (this.destroyed) { // Destroyed while initializing. Remove the listeners which // were registered after the destroy. - events.remove_event_listener(null, `${this.name}--${this.uuid}--*`); + this._remove_all_event_listeners(); } else { if (this.el.isConnected) { // Destroy the pattern when the element is removed from @@ -181,13 +186,11 @@ class BasePattern { * @param {Object} [opts] - Options for the addEventListener API. */ add_event_listener(el, event_type, name, cb, opts = {}) { - events.add_event_listener( - el, - event_type, - `${this.name}--${this.uuid}--${name}`, - cb, - opts - ); + if (!el?.addEventListener) { + return; // nothing to do. + } + events.add_event_listener(el, event_type, this._listener_id(name), cb, opts); + this._listener_els.add(el); } /** @@ -200,11 +203,27 @@ class BasePattern { */ remove_event_listener(el, name) { if (!el) { - // Without an element, events.remove_event_listener would remove - // the listener from all elements. return; } - events.remove_event_listener(el, `${this.name}--${this.uuid}--${name}`); + events.remove_event_listener(el, this._listener_id(name)); + + // Forget the element if this instance has no more listeners on it. + const prefix = this._listener_id(""); + const ids = event_listener_map.get(el)?.keys() || []; + if (![...ids].some((id) => id.startsWith(prefix))) { + this._listener_els.delete(el); + } + } + + _listener_id(name) { + return `${this.name}--${this.uuid}--${name}`; + } + + _remove_all_event_listeners() { + for (const el of this._listener_els) { + events.remove_event_listener(el, this._listener_id("*")); + } + this._listener_els.clear(); } /** @@ -223,7 +242,7 @@ class BasePattern { } this.destroyed = true; lifecycle.untrack(this); - events.remove_event_listener(null, `${this.name}--${this.uuid}--*`); + this._remove_all_event_listeners(); if (this.el[`pattern-${this.name}`] === this) { // Only remove the reference if it points to this instance and not // to another instance which was initialized on the element. diff --git a/src/core/basepattern.test.js b/src/core/basepattern.test.js index 8594e4bea..46219c51f 100644 --- a/src/core/basepattern.test.js +++ b/src/core/basepattern.test.js @@ -404,7 +404,8 @@ describe("Basepattern class tests", function () { }); afterEach(function () { - events.remove_event_listener(); + events.remove_event_listener(document); + events.remove_event_listener(window); }); it("8.1 - Registers a listener under an instance namespaced id.", async function () { @@ -496,6 +497,38 @@ describe("Basepattern class tests", function () { expect(cb2_key).toHaveBeenCalledTimes(1); }); + it("8.4.1 - Elements are only remembered while the instance has listeners on them.", async function () { + const el = document.createElement("div"); + const pat = new Pat(el); + await events.await_pattern_init(pat); + + pat.add_event_listener(document, "keydown", "key", () => {}); + pat.add_event_listener(document, "keyup", "key-up", () => {}); + pat.add_event_listener(window, "resize", "resize", () => {}); + expect([...pat._listener_els]).toEqual([document, window]); + + pat.remove_event_listener(document, "key"); + expect(pat._listener_els.has(document)).toBe(true); + + pat.remove_event_listener(document, "key-up"); + expect(pat._listener_els.has(document)).toBe(false); + expect(pat._listener_els.has(window)).toBe(true); + + pat.destroy(); + expect(pat._listener_els.size).toBe(0); + expect(event_listener_map.has(window)).toBe(false); + }); + + it("8.4.2 - Elements without event listener support are not remembered.", async function () { + const el = document.createElement("div"); + const pat = new Pat(el); + await events.await_pattern_init(pat); + + pat.add_event_listener(null, "keydown", "key", () => {}); + pat.add_event_listener({}, "keydown", "key", () => {}); + expect(pat._listener_els.size).toBe(0); + }); + it("8.5 - remove_event_listener without an element does nothing.", async function () { const el = document.createElement("div"); const pat = new Pat(el); diff --git a/src/core/events.js b/src/core/events.js index 1fee7148f..f93aafcdd 100644 --- a/src/core/events.js +++ b/src/core/events.js @@ -1,18 +1,22 @@ +import logging from "./logging"; import utils from "./utils"; +const log = logging.getLogger("events"); + // Event related methods and event factories // Event listener registration for easy-to-remove event listeners. // // The id can be used as a namespace by giving it a prefix, e.g. // ``--``. Listeners with different ids coexist on the same -// event type. All listeners of a namespace on all elements can be removed with -// ``remove_event_listener(null, "--*")``. +// event type. All listeners of a namespace on an element can be removed with +// ``remove_event_listener(el, "--*")``. // -// The event_listener_map keeps a reference to the element until its listeners -// are removed. Listeners on elements which may be removed from the DOM must be -// removed explicitly, otherwise the element cannot be garbage collected. -export const event_listener_map = new Map(); +// The event_listener_map is a WeakMap and does not keep the elements alive. +// Elements which are removed from the DOM and not referenced otherwise can be +// garbage collected together with their listeners. As a WeakMap cannot be +// iterated, listeners can only be removed per element. +export const event_listener_map = new WeakMap(); /** * Delete an entry from the event_listener_map. @@ -91,46 +95,48 @@ const add_event_listener = (el, event_type, id, cb, opts = {}) => { * * If an element and id are given, the event listeners for the given element matching the id are removed. * If an element but no id is given, all event listeners for that element are removed. - * If an id but no element is given, all event listeners for any element matching the id are removed. - * If no element and no id are given, all event listeners are removed. + * Without an element nothing is removed. Listeners cannot be removed from all + * elements at once, because the event_listener_map is a WeakMap. * * The id can be a wildcard string, e.g. `test-*-event`, which would match any * event which starts with "test-" and ends with "-event". The wildcard "*" can * be anywhere in the string and also be used multiple times. If no wildcard is * present the search string is used for an exact match. * - * @param {DOM Node} [el] - The element to register the event for. + * @param {DOM Node} el - The element the event listener was registered on. * @param {string} [id] - A unique id under which the event is registered. * Can be a wildcard string. * */ const remove_event_listener = (el, id) => { - const els = el ? [el] : event_listener_map.keys(); - const id_regexp = id ? utils.regexp_from_wildcard(id) : null; - for (const el of els) { - if (!el?.removeEventListener) { - continue; // nothing to do. - } - const el_events = event_listener_map.get(el); - if (!el_events) { - continue; - } - let entries; - if (id) { - // remove event listener with matching id - entries = [...el_events.entries()].filter((entry) => - id_regexp.test(entry[0]) - ); - } else { - // remove all event listeners of element - entries = el_events.entries(); - } - for (const entry of entries || []) { - // Remove event listener - el.removeEventListener(entry[1][0], entry[1][1], entry[1][2]); - // Delete entry and, if empty, the element from event_listener_map. - _delete_entry(el, entry[0]); - } + if (!el) { + log.warn( + "remove_event_listener needs an element. Listeners cannot be removed from all elements at once.", + id + ); + return; + } + if (!el.removeEventListener) { + return; // nothing to do. + } + const el_events = event_listener_map.get(el); + if (!el_events) { + return; + } + let entries; + if (id) { + // remove event listener with matching id + const id_regexp = utils.regexp_from_wildcard(id); + entries = [...el_events.entries()].filter((entry) => id_regexp.test(entry[0])); + } else { + // remove all event listeners of element + entries = [...el_events.entries()]; + } + for (const entry of entries) { + // Remove event listener + el.removeEventListener(entry[1][0], entry[1][1], entry[1][2]); + // Delete entry and, if empty, the element from event_listener_map. + _delete_entry(el, entry[0]); } }; diff --git a/src/core/events.test.js b/src/core/events.test.js index 11b55a664..be264529f 100644 --- a/src/core/events.test.js +++ b/src/core/events.test.js @@ -1,13 +1,19 @@ import Base from "./base"; import { BasePattern } from "./basepattern"; import events, { event_listener_map } from "./events"; +import logging from "./logging"; import utils from "./utils"; describe("core.events tests", () => { describe("1 - add / remove event listener", () => { afterEach(() => { - // Clear event_listener_map after each test. - event_listener_map.clear(); + // Remove listeners on the long living elements after each test. + events.remove_event_listener(document); + events.remove_event_listener(window); + }); + + it("Uses a WeakMap, which does not keep the elements alive.", () => { + expect(event_listener_map).toBeInstanceOf(WeakMap); }); it("Registers events only once and unregisters events.", (done) => { @@ -187,8 +193,6 @@ describe("core.events tests", () => { expect(event_listener_map.get(el1).get("test_event_3")).toBeDefined(); expect(event_listener_map.get(el2).get("test_event_4")).toBeDefined(); - expect(event_listener_map.size).toBe(2); - el1.dispatchEvent(new Event("test1")); expect(cnt1).toBe(1); expect(cnt2).toBe(0); @@ -220,7 +224,6 @@ describe("core.events tests", () => { expect(event_listener_map.get(el1).get("test_event_2")).toBeDefined(); expect(event_listener_map.get(el1).get("test_event_3")).toBeDefined(); expect(event_listener_map.get(el2).get("test_event_4")).toBeDefined(); - expect(event_listener_map.size).toBe(2); // Counter should not increase anymore on event "test1" el1.dispatchEvent(new Event("test1")); @@ -238,8 +241,8 @@ describe("core.events tests", () => { // Remove all event handlers on el1 events.remove_event_listener(el1); - expect(event_listener_map.get(el1)).not.toBeDefined(); - expect(event_listener_map.size).toBe(1); + expect(event_listener_map.has(el1)).toBe(false); + expect(event_listener_map.has(el2)).toBe(true); // Counter should not increase anymore on el1 el1.dispatchEvent(new Event("test1")); @@ -256,119 +259,24 @@ describe("core.events tests", () => { expect(cnt3).toBe(3); }); - it("Remove all events matching exactly an id from any element.", () => { - const el1 = document.createElement("div"); - const el2 = document.createElement("div"); - - let cnt1 = 0; - let cnt2 = 0; - let cnt3 = 0; - - const shared_cb = () => { - cnt1++; - }; - - // register the event handlers - events.add_event_listener(el1, "test1", "test_event_1", shared_cb); - events.add_event_listener(el1, "test2", "test_event_2", shared_cb); - events.add_event_listener(el1, "test3", "test_event_3", () => cnt2++); - events.add_event_listener(el2, "test4", "test_event_4", () => cnt3++); - - expect(event_listener_map.get(el1).get("test_event_1")).toBeDefined(); - expect(event_listener_map.get(el1).get("test_event_2")).toBeDefined(); - expect(event_listener_map.get(el1).get("test_event_3")).toBeDefined(); - expect(event_listener_map.get(el2).get("test_event_4")).toBeDefined(); - - expect(event_listener_map.size).toBe(2); - - el1.dispatchEvent(new Event("test1")); - expect(cnt1).toBe(1); - expect(cnt2).toBe(0); - expect(cnt3).toBe(0); - - el1.dispatchEvent(new Event("test1")); - expect(cnt1).toBe(2); - expect(cnt2).toBe(0); - expect(cnt3).toBe(0); - - el1.dispatchEvent(new Event("test2")); - expect(cnt1).toBe(3); - expect(cnt2).toBe(0); - expect(cnt3).toBe(0); - - el1.dispatchEvent(new Event("test3")); - expect(cnt1).toBe(3); - expect(cnt2).toBe(1); - expect(cnt3).toBe(0); - - el2.dispatchEvent(new Event("test4")); - expect(cnt1).toBe(3); - expect(cnt2).toBe(1); - expect(cnt3).toBe(1); - - // Remove only test_event_1 - events.remove_event_listener(undefined, "test_event_1"); - expect(event_listener_map.get(el1).get("test_event_1")).not.toBeDefined(); - expect(event_listener_map.get(el1).get("test_event_2")).toBeDefined(); - expect(event_listener_map.get(el1).get("test_event_3")).toBeDefined(); - expect(event_listener_map.get(el2).get("test_event_4")).toBeDefined(); - expect(event_listener_map.size).toBe(2); - - // Counter should not increase anymore on event "test1" - el1.dispatchEvent(new Event("test1")); - expect(cnt1).toBe(3); - expect(cnt2).toBe(1); - expect(cnt3).toBe(1); - - // Rest should not be affected. - el1.dispatchEvent(new Event("test2")); - el1.dispatchEvent(new Event("test3")); - el2.dispatchEvent(new Event("test4")); - expect(cnt1).toBe(4); - expect(cnt2).toBe(2); - expect(cnt3).toBe(2); - - // Remove rest of event handlers on el1 - events.remove_event_listener(undefined, "test_event_2"); - events.remove_event_listener(undefined, "test_event_3"); - expect(event_listener_map.get(el1)).not.toBeDefined(); - expect(event_listener_map.size).toBe(1); - - // Counter should not increase anymore on el1 - el1.dispatchEvent(new Event("test1")); - el1.dispatchEvent(new Event("test2")); - el1.dispatchEvent(new Event("test3")); - expect(cnt1).toBe(4); - expect(cnt2).toBe(2); - expect(cnt3).toBe(2); - - // But el2 should still work. - el2.dispatchEvent(new Event("test4")); - expect(cnt1).toBe(4); - expect(cnt2).toBe(2); - expect(cnt3).toBe(3); - }); - - it("Remove all event listeners at once.", () => { - const el1 = document.createElement("div"); - const el2 = document.createElement("div"); + it("Does not remove anything without an element.", () => { + const el = document.createElement("div"); + const cb = jest.fn(); + const log = logging.getLogger("events"); + const spy_warn = jest.spyOn(log, "warn").mockImplementation(() => {}); - // register the event handlers - events.add_event_listener(el1, "test1", "test_event_1", () => {}); - events.add_event_listener(el1, "test2", "test_event_2", () => {}); - events.add_event_listener(el1, "test3", "test_event_3", () => {}); - events.add_event_listener(el2, "test4", "test_event_4", () => {}); + events.add_event_listener(el, "test", "test_event", cb); - expect(event_listener_map.get(el1).get("test_event_1")).toBeDefined(); - expect(event_listener_map.get(el1).get("test_event_2")).toBeDefined(); - expect(event_listener_map.get(el1).get("test_event_3")).toBeDefined(); - expect(event_listener_map.get(el2).get("test_event_4")).toBeDefined(); + events.remove_event_listener(null, "test_event"); + events.remove_event_listener(undefined, "test_event"); + events.remove_event_listener(); - expect(event_listener_map.size).toBe(2); + el.dispatchEvent(new Event("test")); + expect(cb).toHaveBeenCalledTimes(1); + expect(event_listener_map.get(el).has("test_event")).toBe(true); + expect(spy_warn).toHaveBeenCalledTimes(3); - // Remove all event listeners - events.remove_event_listener(); - expect(event_listener_map.size).toBe(0); + spy_warn.mockRestore(); }); it("Supports namespacing by id prefix.", () => { @@ -380,7 +288,7 @@ describe("core.events tests", () => { events.add_event_listener(document, "keydown", "a--2", cb_a2); events.add_event_listener(document, "keydown", "b--1", cb_b1); - events.remove_event_listener(null, "a--*"); + events.remove_event_listener(document, "a--*"); expect([...event_listener_map.get(document).keys()]).toEqual(["b--1"]); @@ -392,19 +300,9 @@ describe("core.events tests", () => { events.remove_event_listener(document); }); - it("Continues removing on other elements after an invalid map key.", () => { - const el = document.createElement("div"); - const cb = jest.fn(); - - // An invalid key, inserted before the valid one. - event_listener_map.set({}, new Map([["test_event", []]])); - events.add_event_listener(el, "test", "test_event", cb); - - events.remove_event_listener(null, "test_event"); - el.dispatchEvent(new Event("test")); - - expect(cb).not.toHaveBeenCalled(); - expect(event_listener_map.has(el)).toBe(false); + it("Ignores elements which do not support event listeners.", () => { + expect(() => events.add_event_listener({}, "test", "id", () => {})).not.toThrow(); + expect(() => events.remove_event_listener({}, "id")).not.toThrow(); }); it("Remove wildcard matching event listeners.", () => { From 5dff2761872717ad5ee56534743133b95d9ed46f Mon Sep 17 00:00:00 2001 From: Johannes Raggam Date: Fri, 27 Nov 2026 15:12:14 +0100 Subject: [PATCH 09/22] maint(docs): Add ADR 0004 for event listener scopes. Assisted-by: Claude Opus 5.5 --- docs/adr/0004-event-listener-scopes.md | 66 ++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 docs/adr/0004-event-listener-scopes.md diff --git a/docs/adr/0004-event-listener-scopes.md b/docs/adr/0004-event-listener-scopes.md new file mode 100644 index 000000000..beee366d0 --- /dev/null +++ b/docs/adr/0004-event-listener-scopes.md @@ -0,0 +1,66 @@ +# 0004 Event listener scopes + +Status: Accepted (2026-11-27) + +## Context + +With ADR 0003 the event listener registry is a ``WeakMap``, and listeners +can only be removed per element. Removing a namespace of listeners on all +elements at once, e.g. ``remove_event_listener(null, "plone-modal-3--*")``, +is not possible anymore. Mockup plans to replace jQuery namespaced handlers +(``.on("keydown.plone-modal-3")`` / ``.off(".plone-modal-3")``) with +``events.add_event_listener`` and needs such a namespace wide cleanup. + +``BasePattern`` already solved this for its instances: it remembers the +elements it registered listeners on and removes its listeners from them on +destroy. + +Two options were considered: + +1. A global, iterable registry of ``WeakRef`` objects to all elements with + listeners, cleaned up via a ``FinalizationRegistry``. This restores + element-less removal, but adds subtle code depending on garbage + collection timing, costs a ``WeakRef`` per registered element and every + namespace removal iterates all registered elements of the page. +2. A listener scope which tracks the elements of one namespace, generalizing + what ``BasePattern`` does. + +## Decision + +``events.listener_scope(namespace)`` returns a ``ListenerScope``: + +- ``add(el, event_type, name, cb, opts)`` registers a listener via + ``events.add_event_listener`` under the id ``--`` and + remembers the element and the name. +- ``remove(el, name)`` removes a listener of the scope from an element. + ``name`` can be a wildcard, which is matched against the scope's own + listener names. Without a name, all listeners of the scope on that + element are removed. An element is forgotten when the scope has no more + listeners on it. +- The scope only removes the ids it registered itself, instead of removing + ``--*``. A prefix wildcard would also remove listeners of + scopes whose namespace starts with the same prefix, e.g. ``a`` and + ``a--b``. +- ``remove_all()`` removes all listeners of the scope on all of its + elements. +- Without a namespace, a unique one is generated. + +``BasePattern`` uses a listener scope with the namespace +``--`` instead of its own element tracking. +The listener ids stay the same. + +The global ``WeakRef`` registry is not implemented. + +## Consequences + +- Code which needs namespace wide cleanup creates a scope and calls + ``remove_all()``, instead of relying on a global registry. +- The cost of ``remove_all()`` depends only on the scope's own elements. +- No dependency on garbage collection; the behavior is deterministic and + testable. +- A scope keeps its elements referenced until their listeners are removed + via the scope or ``remove_all()`` is called. Listeners removed otherwise, + e.g. ``once`` listeners after firing, keep their element in the scope + until then. Scopes should therefore have the lifetime of their owner, + e.g. a pattern instance. +- The namespace must not contain the wildcard character ``*``. From 8c7294362539ed852435c07ce3b7a970471c6e7f Mon Sep 17 00:00:00 2001 From: Johannes Raggam Date: Fri, 27 Nov 2026 15:12:14 +0100 Subject: [PATCH 10/22] feat(core events): Add listener scopes. events.listener_scope(namespace) returns a ListenerScope, which registers listeners via add_event_listener under the id "--" and remembers their elements and names. scope.remove(el, name) removes listeners of the scope from an element, also with wildcard names. scope.remove_all() removes all listeners of the scope on all elements. This allows removing a whole namespace of listeners, which is not possible with remove_event_listener alone since the event listener registry is a WeakMap. A scope only removes the listeners it registered itself, so scopes with overlapping namespaces do not interfere. Ref: ADR 0004 Assisted-by: Claude Opus 5.5 --- src/core/events.js | 119 ++++++++++++++++++++++++++++++++ src/core/events.test.js | 146 +++++++++++++++++++++++++++++++++++++++- 2 files changed, 264 insertions(+), 1 deletion(-) diff --git a/src/core/events.js b/src/core/events.js index f93aafcdd..b0cf7677d 100644 --- a/src/core/events.js +++ b/src/core/events.js @@ -1,5 +1,6 @@ import logging from "./logging"; import utils from "./utils"; +import create_uuid from "./uuid"; const log = logging.getLogger("events"); @@ -140,6 +141,121 @@ const remove_event_listener = (el, id) => { } }; +/** + * A scope for event listeners, which can be removed all at once. + * + * Listeners are registered via ``add_event_listener`` under the id + * ``--``. The scope remembers the elements and names of its + * listeners, so that ``remove_all`` can remove all of them on all elements - + * which is not possible with ``remove_event_listener`` alone, as the + * event_listener_map cannot be iterated. + * + * A scope only removes listeners it registered itself. It keeps its elements + * referenced until their listeners are removed via the scope. Give a scope + * the lifetime of its owner, e.g. a pattern instance, and call + * ``remove_all`` when the owner is destroyed. + * + * Usage: + * const listeners = events.listener_scope("my-modal"); + * listeners.add(document, "keydown", "close", on_keydown); + * listeners.add(window, "resize", "position", on_resize); + * listeners.remove(document, "close"); + * listeners.remove_all(); + */ +class ListenerScope { + /** + * @param {string} namespace - The namespace. Must not contain ``*``. + */ + constructor(namespace) { + this.namespace = namespace; + // element -> Set of listener names. + this._listeners = new Map(); + } + + /** + * The elements with listeners of this scope. + * + * @returns {Set} - A copy of the set of elements. + */ + get elements() { + return new Set(this._listeners.keys()); + } + + _id(name) { + return `${this.namespace}--${name}`; + } + + /** + * Add an event listener. + * + * Adding a listener under the same name on the same element replaces the + * previous one. + * + * @param {Node|Window} el - The element to register the event listener on. + * @param {string} event_type - The event type to listen for. + * @param {string} name - A name for the listener, unique within this scope. + * @param {function} cb - The event handler / callback function. + * @param {Object} [opts] - Options for the addEventListener API. + */ + add(el, event_type, name, cb, opts = {}) { + if (!el?.addEventListener) { + return; // nothing to do. + } + add_event_listener(el, event_type, this._id(name), cb, opts); + if (!this._listeners.has(el)) { + this._listeners.set(el, new Set()); + } + this._listeners.get(el).add(name); + } + + /** + * Remove event listeners of this scope from an element. + * + * @param {Node|Window} el - The element the event listeners were registered on. + * @param {string} [name] - The name of the listener. Can be a wildcard + * string. Without a name, all listeners of this + * scope on the element are removed. + */ + remove(el, name) { + const names = this._listeners.get(el); + if (!names) { + return; + } + const name_regexp = name ? utils.regexp_from_wildcard(name) : null; + for (const it of [...names]) { + if (name_regexp && !name_regexp.test(it)) { + continue; + } + remove_event_listener(el, this._id(it)); + names.delete(it); + } + if (!names.size) { + this._listeners.delete(el); + } + } + + /** + * Remove all event listeners of this scope from all elements. + */ + remove_all() { + for (const el of [...this._listeners.keys()]) { + this.remove(el); + } + } +} + +/** + * Create a scope for event listeners, which can be removed all at once. + * + * @param {string} [namespace] - The namespace. Must not contain ``*``. + * Defaults to a generated unique id. + * + * @returns {ListenerScope} - The listener scope. + */ +const listener_scope = (namespace) => { + return new ListenerScope(namespace || create_uuid()); +}; + /** * Await an event to be thrown. * @@ -331,6 +447,7 @@ const dragend_event = () => { export default { add_event_listener: add_event_listener, remove_event_listener: remove_event_listener, + listener_scope: listener_scope, await_event: await_event, await_pattern_init: await_pattern_init, generic_event: generic_event, @@ -347,3 +464,5 @@ export default { dragstart_event: dragstart_event, dragend_event: dragend_event, }; + +export { ListenerScope }; diff --git a/src/core/events.test.js b/src/core/events.test.js index be264529f..10d9a3300 100644 --- a/src/core/events.test.js +++ b/src/core/events.test.js @@ -1,6 +1,6 @@ import Base from "./base"; import { BasePattern } from "./basepattern"; -import events, { event_listener_map } from "./events"; +import events, { event_listener_map, ListenerScope } from "./events"; import logging from "./logging"; import utils from "./utils"; @@ -677,4 +677,148 @@ describe("core.events tests", () => { expect(counter).toBe(2); }); }); + + describe("6 - Listener scopes", () => { + afterEach(() => { + events.remove_event_listener(document); + events.remove_event_listener(window); + }); + + it("6.1 - Creates a scope with the given or a generated namespace.", () => { + const scope = events.listener_scope("ns"); + expect(scope).toBeInstanceOf(ListenerScope); + expect(scope.namespace).toBe("ns"); + + const scope_a = events.listener_scope(); + const scope_b = events.listener_scope(); + expect(scope_a.namespace).toBeTruthy(); + expect(scope_a.namespace).not.toBe(scope_b.namespace); + }); + + it("6.2 - Registers listeners under namespaced ids.", () => { + const scope = events.listener_scope("ns"); + const cb = jest.fn(); + + scope.add(document, "keydown", "key", cb); + + expect([...event_listener_map.get(document).keys()]).toEqual(["ns--key"]); + expect([...scope.elements]).toEqual([document]); + + document.dispatchEvent(new KeyboardEvent("keydown")); + expect(cb).toHaveBeenCalledTimes(1); + }); + + it("6.3 - Passes options on to addEventListener.", () => { + const scope = events.listener_scope("ns"); + const el = document.createElement("div"); + const cb = jest.fn(); + + scope.add(el, "test", "once", cb, { once: true }); + el.dispatchEvent(new Event("test")); + el.dispatchEvent(new Event("test")); + + expect(cb).toHaveBeenCalledTimes(1); + }); + + it("6.4 - remove removes a single listener and forgets the element after the last one.", () => { + const scope = events.listener_scope("ns"); + const cb_key = jest.fn(); + const cb_up = jest.fn(); + + scope.add(document, "keydown", "key", cb_key); + scope.add(document, "keyup", "up", cb_up); + + scope.remove(document, "key"); + expect(scope.elements.has(document)).toBe(true); + + document.dispatchEvent(new KeyboardEvent("keydown")); + document.dispatchEvent(new KeyboardEvent("keyup")); + expect(cb_key).not.toHaveBeenCalled(); + expect(cb_up).toHaveBeenCalledTimes(1); + + scope.remove(document, "up"); + expect(scope.elements.has(document)).toBe(false); + }); + + it("6.5 - remove supports wildcards and removes all listeners of the scope on an element without a name.", () => { + const scope = events.listener_scope("ns"); + const el1 = document.createElement("div"); + const el2 = document.createElement("div"); + + scope.add(el1, "test", "a-1", () => {}); + scope.add(el1, "test", "a-2", () => {}); + scope.add(el1, "test", "b-1", () => {}); + scope.add(el2, "test", "a-1", () => {}); + + scope.remove(el1, "a-*"); + expect([...event_listener_map.get(el1).keys()]).toEqual(["ns--b-1"]); + expect(event_listener_map.get(el2).has("ns--a-1")).toBe(true); + + scope.remove(el1); + expect(event_listener_map.has(el1)).toBe(false); + expect([...scope.elements]).toEqual([el2]); + }); + + it("6.6 - remove_all removes all listeners of the scope on all elements.", () => { + const scope = events.listener_scope("ns"); + const el = document.createElement("div"); + const cb_doc = jest.fn(); + const cb_win = jest.fn(); + const cb_el = jest.fn(); + + scope.add(document, "keydown", "key", cb_doc); + scope.add(window, "resize", "resize", cb_win); + scope.add(el, "test", "test", cb_el); + + scope.remove_all(); + + document.dispatchEvent(new KeyboardEvent("keydown")); + window.dispatchEvent(new Event("resize")); + el.dispatchEvent(new Event("test")); + expect(cb_doc).not.toHaveBeenCalled(); + expect(cb_win).not.toHaveBeenCalled(); + expect(cb_el).not.toHaveBeenCalled(); + expect(scope.elements.size).toBe(0); + expect(event_listener_map.has(el)).toBe(false); + }); + + it("6.7 - Scopes do not touch each other's or other listeners.", () => { + const scope_a = events.listener_scope("a"); + const scope_ab = events.listener_scope("a--b"); + const cb_a = jest.fn(); + const cb_ab = jest.fn(); + const cb_other = jest.fn(); + + scope_a.add(document, "keydown", "key", cb_a); + scope_ab.add(document, "keydown", "key", cb_ab); + events.add_event_listener(document, "keydown", "other", cb_other); + + scope_a.remove(document, "key"); + scope_a.remove_all(); + + document.dispatchEvent(new KeyboardEvent("keydown")); + expect(cb_a).not.toHaveBeenCalled(); + expect(cb_ab).toHaveBeenCalledTimes(1); + expect(cb_other).toHaveBeenCalledTimes(1); + }); + + it("6.8 - Ignores missing elements and elements without event listener support.", () => { + const scope = events.listener_scope("ns"); + + scope.add(null, "test", "test", () => {}); + scope.add({}, "test", "test", () => {}); + expect(scope.elements.size).toBe(0); + + expect(() => scope.remove(null, "test")).not.toThrow(); + expect(() => scope.remove({}, "test")).not.toThrow(); + }); + + it("6.9 - elements returns a copy.", () => { + const scope = events.listener_scope("ns"); + scope.add(document, "keydown", "key", () => {}); + + scope.elements.clear(); + expect(scope.elements.has(document)).toBe(true); + }); + }); }); From 72f3f70bb2625fcfbb526c45ecbc2cb94c8993f5 Mon Sep 17 00:00:00 2001 From: Johannes Raggam Date: Fri, 27 Nov 2026 15:14:03 +0100 Subject: [PATCH 11/22] feat(core basepattern): Use a listener scope for instance scoped listeners. BasePattern now manages the listeners registered with this.add_event_listener with an event listener scope instead of its own element tracking. The listener ids stay the same. The scope is stored in a private field, so that it cannot collide with properties of subclasses - pat-bind, for example, has its own this._listeners. this.remove_event_listener(el, name) now also accepts wildcard names, and without a name removes all listeners of the instance on the element. Add documentation for the event listener helpers and scopes in src/core/events.md. Ref: ADR 0004 Assisted-by: Claude Opus 5.5 --- src/core/basepattern.js | 49 +++++++--------------- src/core/basepattern.md | 7 +++- src/core/basepattern.test.js | 79 +++++++++++++++++++++++++++++------- src/core/events.md | 64 +++++++++++++++++++++++++++++ 4 files changed, 148 insertions(+), 51 deletions(-) create mode 100644 src/core/events.md diff --git a/src/core/basepattern.js b/src/core/basepattern.js index e7e02bc44..4d3e9f9f8 100644 --- a/src/core/basepattern.js +++ b/src/core/basepattern.js @@ -6,7 +6,7 @@ * * For usage, see basepattern.md */ -import events, { event_listener_map } from "./events"; +import events from "./events"; import lifecycle from "./lifecycle"; import logging from "./logging"; import create_uuid from "./uuid"; @@ -24,10 +24,9 @@ class BasePattern { parser_multiple = undefined; parser_inherit = true; - // Elements with listeners registered via ``add_event_listener``. - // The event listener registry is a WeakMap which cannot be iterated, so - // remember the elements to remove the listeners on destroy. - _listener_els = new Set(); + // Instance scoped event listeners, removed on destroy. + // A private field, so that it cannot collide with subclass properties. + #listeners = null; constructor(el, options = {}) { // Make static variables available on instance. @@ -44,6 +43,8 @@ class BasePattern { } this.el = el; this.uuid = create_uuid(); + + this.#listeners = events.listener_scope(`${this.name}--${this.uuid}`); this.destroyed = false; // Remember if the element was part of the document at construction @@ -118,7 +119,7 @@ class BasePattern { if (this.destroyed) { // Destroyed while initializing. Remove the listeners which // were registered after the destroy. - this._remove_all_event_listeners(); + this.#listeners.remove_all(); } else { if (this.el.isConnected) { // Destroy the pattern when the element is removed from @@ -186,11 +187,7 @@ class BasePattern { * @param {Object} [opts] - Options for the addEventListener API. */ add_event_listener(el, event_type, name, cb, opts = {}) { - if (!el?.addEventListener) { - return; // nothing to do. - } - events.add_event_listener(el, event_type, this._listener_id(name), cb, opts); - this._listener_els.add(el); + this.#listeners?.add(el, event_type, name, cb, opts); } /** @@ -199,31 +196,13 @@ class BasePattern { * Only removes listeners of this pattern instance. * * @param {Node|Window} el - The element the event listener was registered on. - * @param {string} name - The name of the listener, as passed to ``add_event_listener``. + * @param {string} [name] - The name of the listener, as passed to + * ``add_event_listener``. Can be a wildcard + * string. Without a name, all listeners of this + * instance on the element are removed. */ remove_event_listener(el, name) { - if (!el) { - return; - } - events.remove_event_listener(el, this._listener_id(name)); - - // Forget the element if this instance has no more listeners on it. - const prefix = this._listener_id(""); - const ids = event_listener_map.get(el)?.keys() || []; - if (![...ids].some((id) => id.startsWith(prefix))) { - this._listener_els.delete(el); - } - } - - _listener_id(name) { - return `${this.name}--${this.uuid}--${name}`; - } - - _remove_all_event_listeners() { - for (const el of this._listener_els) { - events.remove_event_listener(el, this._listener_id("*")); - } - this._listener_els.clear(); + this.#listeners?.remove(el, name); } /** @@ -242,7 +221,7 @@ class BasePattern { } this.destroyed = true; lifecycle.untrack(this); - this._remove_all_event_listeners(); + this.#listeners?.remove_all(); if (this.el[`pattern-${this.name}`] === this) { // Only remove the reference if it points to this instance and not // to another instance which was initialized on the element. diff --git a/src/core/basepattern.md b/src/core/basepattern.md index bd01b5c12..040bc57bc 100644 --- a/src/core/basepattern.md +++ b/src/core/basepattern.md @@ -83,7 +83,12 @@ the instance, but not those of other instances of the same pattern. If you override ``destroy()``, call ``super.destroy()``. To remove a single listener before the pattern is destroyed, use -``this.remove_event_listener(el, name)`` with the same element and name. +``this.remove_event_listener(el, name)`` with the same element and name. The +name can be a wildcard. Without a name, all listeners of the instance on that +element are removed. + +The listeners are managed by an event listener scope (see +``src/core/events.md``). ## Automatic destroy diff --git a/src/core/basepattern.test.js b/src/core/basepattern.test.js index 46219c51f..194e8e278 100644 --- a/src/core/basepattern.test.js +++ b/src/core/basepattern.test.js @@ -497,36 +497,85 @@ describe("Basepattern class tests", function () { expect(cb2_key).toHaveBeenCalledTimes(1); }); - it("8.4.1 - Elements are only remembered while the instance has listeners on them.", async function () { + it("8.4.1 - destroy() removes the remaining listeners after single listeners were removed.", async function () { const el = document.createElement("div"); const pat = new Pat(el); await events.await_pattern_init(pat); + const cb_up = jest.fn(); + const cb_resize = jest.fn(); pat.add_event_listener(document, "keydown", "key", () => {}); - pat.add_event_listener(document, "keyup", "key-up", () => {}); - pat.add_event_listener(window, "resize", "resize", () => {}); - expect([...pat._listener_els]).toEqual([document, window]); + pat.add_event_listener(document, "keyup", "key-up", cb_up); + pat.add_event_listener(window, "resize", "resize", cb_resize); pat.remove_event_listener(document, "key"); - expect(pat._listener_els.has(document)).toBe(true); - - pat.remove_event_listener(document, "key-up"); - expect(pat._listener_els.has(document)).toBe(false); - expect(pat._listener_els.has(window)).toBe(true); - pat.destroy(); - expect(pat._listener_els.size).toBe(0); + + document.dispatchEvent(new KeyboardEvent("keyup")); + window.dispatchEvent(new Event("resize")); + expect(cb_up).not.toHaveBeenCalled(); + expect(cb_resize).not.toHaveBeenCalled(); + expect(event_listener_map.has(document)).toBe(false); expect(event_listener_map.has(window)).toBe(false); }); - it("8.4.2 - Elements without event listener support are not remembered.", async function () { + it("8.4.2 - Missing elements and elements without event listener support are ignored.", async function () { const el = document.createElement("div"); const pat = new Pat(el); await events.await_pattern_init(pat); - pat.add_event_listener(null, "keydown", "key", () => {}); - pat.add_event_listener({}, "keydown", "key", () => {}); - expect(pat._listener_els.size).toBe(0); + expect(() => { + pat.add_event_listener(null, "keydown", "key", () => {}); + pat.add_event_listener({}, "keydown", "key", () => {}); + pat.remove_event_listener(null, "key"); + pat.remove_event_listener({}, "key"); + pat.destroy(); + }).not.toThrow(); + }); + + it("8.4.4 - Subclass properties do not collide with the listener scope.", async function () { + class SubPat extends Pat { + _listeners = []; + listeners = []; + } + const el = document.createElement("div"); + const pat = new SubPat(el); + await events.await_pattern_init(pat); + + const cb = jest.fn(); + pat.add_event_listener(document, "keydown", "key", cb); + pat.destroy(); + + document.dispatchEvent(new KeyboardEvent("keydown")); + expect(cb).not.toHaveBeenCalled(); + }); + + it("8.4.3 - remove_event_listener without a name removes all listeners of the instance on the element.", async function () { + const el1 = document.createElement("div"); + const el2 = document.createElement("div"); + const pat1 = new Pat(el1); + const pat2 = new Pat(el2); + await events.await_pattern_init(pat1); + await events.await_pattern_init(pat2); + + const cb1_key = jest.fn(); + const cb1_up = jest.fn(); + const cb1_resize = jest.fn(); + const cb2_key = jest.fn(); + pat1.add_event_listener(document, "keydown", "key", cb1_key); + pat1.add_event_listener(document, "keyup", "up", cb1_up); + pat1.add_event_listener(window, "resize", "resize", cb1_resize); + pat2.add_event_listener(document, "keydown", "key", cb2_key); + + pat1.remove_event_listener(document); + + document.dispatchEvent(new KeyboardEvent("keydown")); + document.dispatchEvent(new KeyboardEvent("keyup")); + window.dispatchEvent(new Event("resize")); + expect(cb1_key).not.toHaveBeenCalled(); + expect(cb1_up).not.toHaveBeenCalled(); + expect(cb1_resize).toHaveBeenCalledTimes(1); + expect(cb2_key).toHaveBeenCalledTimes(1); }); it("8.5 - remove_event_listener without an element does nothing.", async function () { diff --git a/src/core/events.md b/src/core/events.md new file mode 100644 index 000000000..972e2759e --- /dev/null +++ b/src/core/events.md @@ -0,0 +1,64 @@ +# Events + +``src/core/events.js`` contains helpers for event listeners and factories for +common events. + +## Registering event listeners + +``events.add_event_listener(el, event_type, id, cb, opts)`` registers an event +listener under an id. Registering again under the same id on the same element +replaces the previous listener. + +``events.remove_event_listener(el, id)`` removes listeners from an element: + +- With an id, the listener with that id is removed. The id can be a wildcard + string, e.g. ``my-namespace--*`` or ``test-*-event``. +- Without an id, all listeners of the element are removed. +- Without an element, nothing is removed and a warning is logged. + +```javascript +import events from "@patternslib/patternslib/src/core/events"; + +events.add_event_listener(document, "keydown", "my-modal--close", on_keydown); +events.remove_event_listener(document, "my-modal--close"); +``` + +The registry is a ``WeakMap`` and does not keep the elements alive. Elements +which are removed from the DOM and not referenced otherwise are garbage +collected together with their listeners. As a ``WeakMap`` cannot be iterated, +listeners can only be removed per element. + +## Listener scopes + +To remove all listeners of a component on all elements at once, use a +listener scope. A scope registers listeners under the id +``--`` and remembers their elements and names. + +```javascript +import events from "@patternslib/patternslib/src/core/events"; + +const listeners = events.listener_scope("my-modal-3"); + +listeners.add(document, "keydown", "close", on_keydown); +listeners.add(window, "resize", "position", on_resize, { passive: true }); + +// Remove a single listener, listeners matching a wildcard name or all +// listeners of the scope on an element. +listeners.remove(document, "close"); +listeners.remove(window, "pos*"); +listeners.remove(window); + +// Remove all listeners of the scope on all elements. +listeners.remove_all(); +``` + +- Without a namespace, ``listener_scope()`` generates a unique one. +- The namespace must not contain the wildcard character ``*``. +- A scope only removes listeners it registered itself. Scopes with + overlapping namespaces, e.g. ``a`` and ``a--b``, do not interfere. +- A scope keeps its elements referenced until their listeners are removed + via the scope. Give it the lifetime of its owner and call + ``remove_all()`` when the owner is destroyed. + +``BasePattern`` uses a listener scope for ``this.add_event_listener`` and +removes its listeners on ``destroy()``, see ``basepattern.md``. From 00c2f910c233110ecc00d1dc698403c6742e060c Mon Sep 17 00:00:00 2001 From: Johannes Raggam Date: Fri, 27 Nov 2026 13:26:17 +0100 Subject: [PATCH 12/22] feat(pat-tooltip): Keep patterns in the tooltip content across hide and show. Tippy removes the popper from the document while the tooltip is hidden. Mark the popper as self managed, so that patterns in static tooltip content are not destroyed on hide and initialized again on show. Destroy the patterns in the popper when the tooltip is destroyed, and for ajax content on hide before the content is replaced. Ref: ADR 0002 Assisted-by: Claude Opus 5.5 --- src/pat/tooltip/tooltip.js | 16 +++- src/pat/tooltip/tooltip.test.js | 126 ++++++++++++++++++++++++++++++++ 2 files changed, 141 insertions(+), 1 deletion(-) diff --git a/src/pat/tooltip/tooltip.js b/src/pat/tooltip/tooltip.js index 14a9715c7..b50584150 100644 --- a/src/pat/tooltip/tooltip.js +++ b/src/pat/tooltip/tooltip.js @@ -3,6 +3,7 @@ import { BasePattern } from "../../core/basepattern"; import logging from "../../core/logging"; import Parser from "../../core/parser"; import events from "../../core/events"; +import lifecycle from "../../core/lifecycle"; import registry from "../../core/registry"; import utils from "../../core/utils"; @@ -95,6 +96,12 @@ class Pattern extends BasePattern { Tippy.setDefaultProps(defaultProps); this.tippy = new Tippy(el, this.tippy_options); + // Tippy removes the popper from the document while the tooltip is + // hidden and re-inserts it on show. Do not destroy the patterns in + // the tooltip content when it is hidden. They are destroyed with the + // tooltip or when the content is replaced. + this.tippy.popper.setAttribute(lifecycle.MANAGED_ATTRIBUTE, ""); + if (this.options.source === "title") { // Remove ``title`` attribute when source is set to ``title`` to // disable the browser's built-in tooltip feature @@ -143,7 +150,11 @@ class Pattern extends BasePattern { return; } super.destroy(); // Unregister - this.tippy?.destroy(); + if (this.tippy) { + // Destroy the patterns in the tooltip content. + lifecycle.destroy_patterns(this.tippy.popper); + this.tippy.destroy(); + } } parseOptionsForTippy(opts) { @@ -360,6 +371,9 @@ class Pattern extends BasePattern { } if (this.options.source === "ajax") { + // The content is fetched again on the next show. Destroy the + // patterns in the current content. + lifecycle.destroy_patterns(this.tippy.popper); this.tippy.setContent(document.createElement("progress")); } } diff --git a/src/pat/tooltip/tooltip.test.js b/src/pat/tooltip/tooltip.test.js index cc558b37e..fd2cdfca7 100644 --- a/src/pat/tooltip/tooltip.test.js +++ b/src/pat/tooltip/tooltip.test.js @@ -1,6 +1,8 @@ import $ from "jquery"; import autosubmit from "../auto-submit/auto-submit"; +import { BasePattern } from "../../core/basepattern"; import events from "../../core/events"; +import lifecycle from "../../core/lifecycle"; import Pattern from "./tooltip"; import registry from "../../core/registry"; import utils from "../../core/utils"; @@ -1790,4 +1792,128 @@ this will be extracted. ); }); }); + + describe("11 - Lifecycle of patterns in the tooltip content", () => { + class Dummy extends BasePattern { + static name = "tooltip-test-dummy"; + static trigger = ".pat-tooltip-test-dummy"; + } + + const get_dummy = () => + document.querySelector(".tippy-content .pat-tooltip-test-dummy"); + + beforeEach(() => { + registry.register(Dummy); + }); + + afterEach(() => { + delete registry.patterns["tooltip-test-dummy"]; + }); + + it("11.1 - The popper is marked as self managed.", async () => { + const $el = testutils.createTooltip({ data: "trigger: click" }); + const instance = new Pattern($el); + await events.await_pattern_init(instance); + + expect(instance.tippy.popper.hasAttribute(lifecycle.MANAGED_ATTRIBUTE)).toBe( + true + ); + }); + + it("11.2 - Patterns in static content survive hiding and showing.", async () => { + document.body.innerHTML = ` + Dummy + `; + const el = document.querySelector(".pat-tooltip"); + const instance = new Pattern(el); + await events.await_pattern_init(instance); + + // Show + el.click(); + await utils.timeout(1); + await utils.timeout(1); // Wait for dummy init. + const dummy_el = get_dummy(); + const dummy = dummy_el["pattern-tooltip-test-dummy"]; + expect(dummy).toBeInstanceOf(Dummy); + expect(lifecycle.is_tracked(dummy)).toBe(true); + + // Hide - the popper is removed from the document. + instance.tippy.hide(); + await utils.timeout(1); + expect(instance.tippy.popper.isConnected).toBe(false); + expect(dummy.destroyed).toBe(false); + + // Trigger the observer with another removal. + document.body.appendChild(document.createElement("div")).remove(); + await utils.timeout(1); + expect(dummy.destroyed).toBe(false); + + // Show again - same element, same instance. + el.click(); + await utils.timeout(1); + await utils.timeout(1); + expect(get_dummy()).toBe(dummy_el); + expect(dummy_el["pattern-tooltip-test-dummy"]).toBe(dummy); + expect(dummy.destroyed).toBe(false); + }); + + it("11.3 - Patterns in ajax content are destroyed on hide.", async () => { + global.fetch = jest + .fn() + .mockImplementation( + mockFetch(`Dummy`) + ); + + const $el = testutils.createTooltip({ + data: "source: ajax", + href: "http://test.com", + }); + const instance = new Pattern($el); + await events.await_pattern_init(instance); + const spy_get_content = jest.spyOn(instance, "_get_content"); + + testutils.click($el); + await utils.timeout(1); + await spy_get_content.mock.results[0].value; // wait for the fetch + await utils.timeout(1); // wait for dummy init + const dummy = get_dummy()["pattern-tooltip-test-dummy"]; + expect(dummy).toBeInstanceOf(Dummy); + + instance.tippy.hide(); + await utils.timeout(1); + expect(dummy.destroyed).toBe(true); + expect(lifecycle.is_tracked(dummy)).toBe(false); + + global.fetch.mockRestore(); + delete global.fetch; + }); + + it("11.4 - Patterns in the tooltip content are destroyed with the tooltip.", async () => { + document.body.innerHTML = ` + Dummy + `; + const el = document.querySelector(".pat-tooltip"); + const instance = new Pattern(el); + await events.await_pattern_init(instance); + + el.click(); + await utils.timeout(1); + await utils.timeout(1); + const dummy = get_dummy()["pattern-tooltip-test-dummy"]; + + // Hide, then remove the tooltip trigger element. + instance.tippy.hide(); + await utils.timeout(1); + el.remove(); + await utils.timeout(1); + + expect(instance.destroyed).toBe(true); + expect(dummy.destroyed).toBe(true); + expect(lifecycle.is_tracked(dummy)).toBe(false); + }); + }); }); From bfb50bb32649b2263e4708f3325a807bcc9ce55d Mon Sep 17 00:00:00 2001 From: Johannes Raggam Date: Fri, 27 Nov 2026 13:41:40 +0100 Subject: [PATCH 13/22] fix(pat-depends): Update the state after a form reset. The reset handler only created a bound function of set_state without calling it, so dependent elements were not updated after a form reset. Assisted-by: Claude Opus 5.5 --- src/pat/depends/depends.js | 5 +++-- src/pat/depends/depends.test.js | 34 +++++++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 2 deletions(-) diff --git a/src/pat/depends/depends.js b/src/pat/depends/depends.js index 8cd3ed40b..5a1241018 100644 --- a/src/pat/depends/depends.js +++ b/src/pat/depends/depends.js @@ -74,9 +74,10 @@ class Pattern extends BasePattern { "reset", `pat-depends--reset--${this.uuid}`, async () => { - // TODO: note sure, what this timeout is for. + // Wait for the form reset to restore the default + // values. The reset event is thrown before. await utils.timeout(50); - this.set_state.bind(this); + this.set_state(); } ); } diff --git a/src/pat/depends/depends.test.js b/src/pat/depends/depends.test.js index eda575381..300aa68ab 100644 --- a/src/pat/depends/depends.test.js +++ b/src/pat/depends/depends.test.js @@ -1,5 +1,6 @@ import $ from "jquery"; import dom from "../../core/dom"; +import events from "../../core/events"; import pattern from "./depends"; import utils from "../../core/utils"; @@ -530,7 +531,40 @@ describe("pat-depends", function () { expect(called).toBe(false); }); + }); + describe("7 - Form reset", function () { + afterEach(function () { + document.body.innerHTML = ""; + }); + + it("7.1 - Updates the state after a form reset.", async function () { + document.body.innerHTML = ` +
+ +
+ Dependent +
+
+ `; + const el = document.querySelector(".pat-depends"); + const control = document.querySelector("#control"); + const instance = new pattern(el); + await events.await_pattern_init(instance); + expect(el.style.display).toBe("none"); + + control.checked = true; + control.dispatchEvent(new Event("input")); + expect(el.style.display).not.toBe("none"); + + // The reset restores the unchecked default state without + // throwing an input event. + document.querySelector("form").reset(); + expect(control.checked).toBe(false); + await utils.timeout(60); + + expect(el.style.display).toBe("none"); + }); }); }); From 935f5ca298a1090fbe44515a4161af636631ba25 Mon Sep 17 00:00:00 2001 From: Johannes Raggam Date: Fri, 27 Nov 2026 13:42:19 +0100 Subject: [PATCH 14/22] fix(pat-depends): Remove the input listeners on destroy. Register the listeners on the dependency inputs, their forms and the anchor click blocker with the instance scoped add_event_listener. The listeners on inputs outside the pattern element were never removed, so a destroyed pattern kept updating its removed element on input. Ref: ADR 0001 Assisted-by: Claude Opus 5.5 --- src/pat/depends/depends.js | 19 +++---- src/pat/depends/depends.test.js | 96 ++++++++++++++++++++++++++++++++- 2 files changed, 103 insertions(+), 12 deletions(-) diff --git a/src/pat/depends/depends.js b/src/pat/depends/depends.js index 5a1241018..ec0cba042 100644 --- a/src/pat/depends/depends.js +++ b/src/pat/depends/depends.js @@ -1,6 +1,5 @@ import $ from "jquery"; import { BasePattern } from "@patternslib/patternslib/src/core/basepattern"; -import events from "../../core/events"; import dom from "../../core/dom"; import logging from "../../core/logging"; import Parser from "@patternslib/patternslib/src/core/parser"; @@ -51,13 +50,13 @@ class Pattern extends BasePattern { for (const input of this.handler.getAllInputs()) { // Note: One input can be a dependency for multiple other dependent - // elements. Therefore we need to bind the events not uniquely and - // add a uuid to the event bindings id. + // elements. The listeners are scoped to this pattern instance and + // removed when it is destroyed. - events.add_event_listener( + this.add_event_listener( input, "input", - `pat-depends--input--${this.uuid}`, + "input", (e) => { if (e?.detail?.pattern_uuid === this.uuid) { // Ignore input events invoked from this pattern @@ -69,10 +68,10 @@ class Pattern extends BasePattern { ); if (input.form) { - events.add_event_listener( + this.add_event_listener( input.form, "reset", - `pat-depends--reset--${this.uuid}`, + "reset", async () => { // Wait for the form reset to restore the default // values. The reset event is thrown before. @@ -123,7 +122,7 @@ class Pattern extends BasePattern { // Restore the original click behavior for anchor elements. if (this.el.tagName === "A") { - events.remove_event_listener(this.el, "pat-depends--click"); + this.remove_event_listener(this.el, "click"); } // Remove the disabled class from the element. @@ -168,9 +167,7 @@ class Pattern extends BasePattern { // Prevent the default click behavior for anchor elements. if (this.el.tagName === "A") { - events.add_event_listener(this.el, "click", "pat-depends--click", (e) => - e.preventDefault() - ); + this.add_event_listener(this.el, "click", "click", (e) => e.preventDefault()); } // Add the disabled class to the element. diff --git a/src/pat/depends/depends.test.js b/src/pat/depends/depends.test.js index 300aa68ab..c808e0830 100644 --- a/src/pat/depends/depends.test.js +++ b/src/pat/depends/depends.test.js @@ -1,8 +1,9 @@ import $ from "jquery"; import dom from "../../core/dom"; -import events from "../../core/events"; +import events, { event_listener_map } from "../../core/events"; import pattern from "./depends"; import utils from "../../core/utils"; +import { jest } from "@jest/globals"; describe("pat-depends", function () { describe("1 - init", function () { @@ -567,4 +568,97 @@ describe("pat-depends", function () { expect(el.style.display).toBe("none"); }); }); + + describe("8 - Destroy", function () { + afterEach(function () { + document.body.innerHTML = ""; + }); + + it("8.1 - Removing the element stops reacting to the inputs.", async function () { + document.body.innerHTML = ` +
+ +
+ Dependent +
+
+ `; + + const el = document.querySelector(".pat-depends"); + const control = document.querySelector("#control"); + const form = document.querySelector("form"); + const instance = new pattern(el); + await events.await_pattern_init(instance); + + const spy_set_state = jest.spyOn(instance, "set_state"); + + el.remove(); + await utils.timeout(1); + expect(instance.destroyed).toBe(true); + + control.checked = true; + control.dispatchEvent(new Event("input")); + form.reset(); + await utils.timeout(60); + + expect(spy_set_state).not.toHaveBeenCalled(); + expect(event_listener_map.has(control)).toBe(false); + expect(event_listener_map.has(form)).toBe(false); + }); + + it("8.2 - Other instances depending on the same input keep working.", async function () { + document.body.innerHTML = ` + +
+ One +
+
+ Two +
+ `; + + const el1 = document.querySelector("#one"); + const el2 = document.querySelector("#two"); + const control = document.querySelector("#control"); + const instance1 = new pattern(el1); + const instance2 = new pattern(el2); + await events.await_pattern_init(instance1); + await events.await_pattern_init(instance2); + + el1.remove(); + await utils.timeout(1); + + control.checked = true; + control.dispatchEvent(new Event("input")); + + expect(el2.style.display).not.toBe("none"); + }); + + it("8.3 - Anchors: enabling removes the click blocker.", async function () { + document.body.innerHTML = ` + + + Link + + `; + + const el = document.querySelector(".pat-depends"); + const control = document.querySelector("#control"); + const instance = new pattern(el); + await events.await_pattern_init(instance); + + // Disabled: click is prevented. + const click1 = new MouseEvent("click", { cancelable: true }); + el.dispatchEvent(click1); + expect(click1.defaultPrevented).toBe(true); + + control.checked = true; + control.dispatchEvent(new Event("input")); + + // Enabled: click is not prevented anymore. + const click2 = new MouseEvent("click", { cancelable: true }); + el.dispatchEvent(click2); + expect(click2.defaultPrevented).toBe(false); + }); + }); }); From d9b7b15ffe513a22c0e53640da3354568608a35a Mon Sep 17 00:00:00 2001 From: Johannes Raggam Date: Fri, 27 Nov 2026 13:42:53 +0100 Subject: [PATCH 15/22] fix(pat-autofocus): Remove the pat-update handler on destroy. The pat-update handler on the document was never removed. A destroyed pattern kept reacting to pat-update events and could focus its removed element. Register the handler under an instance specific event namespace and remove it on destroy. It stays a jQuery handler, as pat-update is mostly triggered via jQuery, which does not reach native listeners. Ref: ADR 0001 Assisted-by: Claude Opus 5.5 --- src/pat/autofocus/autofocus.js | 13 ++++++- src/pat/autofocus/autofocus.test.js | 55 +++++++++++++++++++++++++++++ 2 files changed, 67 insertions(+), 1 deletion(-) diff --git a/src/pat/autofocus/autofocus.js b/src/pat/autofocus/autofocus.js index dceb77b86..189a168a3 100644 --- a/src/pat/autofocus/autofocus.js +++ b/src/pat/autofocus/autofocus.js @@ -25,7 +25,11 @@ class Pattern extends BasePattern { } // Re-focus after relevant DOM changes. - $(document).on("pat-update", (e, data) => { + // pat-update is mostly triggered via jQuery, which does not reach + // native event listeners. Use an instance specific event namespace to + // be able to remove only this instance's handler again. + this._update_event = `pat-update.pat-autofocus--${this.uuid}`; + $(document).on(this._update_event, (e, data) => { const updated = data?.dom; if (updated?.contains(this.el)) { // Only focus if the updated element is a parent of this autofocus element. @@ -36,6 +40,13 @@ class Pattern extends BasePattern { this.set_focus(); } + destroy() { + if (this._update_event) { + $(document).off(this._update_event); + } + super.destroy(); + } + set_focus() { if (dom.is_visible(this.el) && this.el.value === "") { // Set autofocus only for visible and empty inputs. diff --git a/src/pat/autofocus/autofocus.test.js b/src/pat/autofocus/autofocus.test.js index 9c42cf07c..5917d43bb 100644 --- a/src/pat/autofocus/autofocus.test.js +++ b/src/pat/autofocus/autofocus.test.js @@ -3,6 +3,7 @@ import "./autofocus"; import events from "../../core/events"; import registry from "../../core/registry"; import utils from "../../core/utils"; +import { jest } from "@jest/globals"; describe("pat-autofocus", function () { it("1 - Focus the first element.", async () => { @@ -132,4 +133,58 @@ describe("pat-autofocus", function () { ); }); }); + + describe("5 - Destroy", function () { + it("5.1 - Removing the element removes the pat-update handler.", async () => { + document.body.innerHTML = ` +
+ +
+ + `; + const input = document.querySelector("input[name=i1]"); + registry.scan(document.body); + await utils.timeout(1); // Wait for async pattern initialization. + await utils.timeout(100); // Wait for autofocus timeout. + + const instance = input["pattern-autofocus"]; + const spy_set_focus = jest.spyOn(instance, "set_focus"); + const handlers_before = $._data(document, "events")?.["pat-update"]?.length; + + document.querySelector("#c1").remove(); + await utils.timeout(1); + expect(instance.destroyed).toBe(true); + expect($._data(document, "events")?.["pat-update"]?.length || 0).toBe( + handlers_before - 1 + ); + + $(document).trigger("pat-update", { dom: document.body }); + expect(spy_set_focus).not.toHaveBeenCalled(); + }); + + it("5.2 - Other instances keep their pat-update handler.", async () => { + document.body.innerHTML = ` +
+ +
+
+ +
+ `; + registry.scan(document.body); + await utils.timeout(1); // Wait for async pattern initialization. + await utils.timeout(100); // Wait for autofocus timeout. + + document.querySelector("#c1").remove(); + await utils.timeout(1); + + document.querySelector("input[name=i2]").removeAttribute("hidden"); + $(document).trigger("pat-update", { dom: document.querySelector("#c2") }); + await utils.timeout(100); // Wait for autofocus timeout. + + expect(document.activeElement).toBe( + document.querySelector("input[name=i2]") + ); + }); + }); }); From 91d7a3b0e3b7573f348d14eb88d06165fde817ea Mon Sep 17 00:00:00 2001 From: Johannes Raggam Date: Fri, 27 Nov 2026 13:43:49 +0100 Subject: [PATCH 16/22] fix(pat-collapsible): Remove the trigger handlers on destroy. The open and close trigger handlers delegated from the document and the handlers on an external trigger were never removed, so a destroyed pattern kept toggling its removed element. Register them under an instance specific event namespace and remove them on destroy. Ref: ADR 0001 Assisted-by: Claude Opus 5.5 --- src/pat/collapsible/collapsible.js | 22 +++++-- src/pat/collapsible/collapsible.test.js | 82 +++++++++++++++++++++++++ 2 files changed, 100 insertions(+), 4 deletions(-) diff --git a/src/pat/collapsible/collapsible.js b/src/pat/collapsible/collapsible.js index 32a160564..410c00e2e 100644 --- a/src/pat/collapsible/collapsible.js +++ b/src/pat/collapsible/collapsible.js @@ -94,16 +94,22 @@ class Pattern extends BasePattern { this.$panel.show(); } + // Use an instance specific event namespace to be able to remove only + // this instance's handlers again. The trigger might be outside of the + // pattern element and the open and close triggers are delegated from + // the document. + const ns = (this._event_namespace = `pat-collapsible--${this.uuid}`); + this.$trigger .off(".pat-collapsible") - .on("click.pat-collapsible", null, $el, this._onClick.bind(this)) - .on("keypress.pat-collapsible", null, $el, this._onKeyPress.bind(this)); + .on(`click.pat-collapsible.${ns}`, null, $el, this._onClick.bind(this)) + .on(`keypress.pat-collapsible.${ns}`, null, $el, this._onKeyPress.bind(this)); // prettier-ignore if (this.options.closeTrigger) { - $(document).on("click", this.options.closeTrigger, this.close.bind(this)); + $(document).on(`click.${ns}`, this.options.closeTrigger, this.close.bind(this)); // prettier-ignore } if (this.options.openTrigger) { - $(document).on("click", this.options.openTrigger, this.open.bind(this)); + $(document).on(`click.${ns}`, this.options.openTrigger, this.open.bind(this)); // prettier-ignore } // pat-scroll support @@ -127,6 +133,14 @@ class Pattern extends BasePattern { return $el; } + destroy() { + if (this._event_namespace) { + $(document).off(`.${this._event_namespace}`); + this.$trigger.off(`.${this._event_namespace}`); + } + super.destroy(); + } + open() { if (!this.$el.hasClass("open")) { this.toggle(); diff --git a/src/pat/collapsible/collapsible.test.js b/src/pat/collapsible/collapsible.test.js index 0647cdfbb..b2bf770d9 100644 --- a/src/pat/collapsible/collapsible.test.js +++ b/src/pat/collapsible/collapsible.test.js @@ -283,4 +283,86 @@ describe("pat-collapsible", function () { }) ); }); + + describe("10 - Destroy", function () { + it("10.1 - Removing the element removes the open and close trigger handlers.", async function () { + document.body.innerHTML = ` +
+

Trigger header

+

Collapsible content

+
+ + + `; + const el = document.querySelector(".pat-collapsible"); + const instance = new Pattern(el, { transition: "none" }); + await events.await_pattern_init(instance); + + const spy_toggle = jest.spyOn(instance, "toggle"); + + el.remove(); + await utils.timeout(1); + expect(instance.destroyed).toBe(true); + + document.querySelector("#open").click(); + document.querySelector("#close").click(); + expect(spy_toggle).not.toHaveBeenCalled(); + expect($._data(document, "events")?.click).toBeUndefined(); + }); + + it("10.2 - Removing the element removes the handlers on an external trigger.", async function () { + document.body.innerHTML = ` + +
+

Collapsible content

+
+ `; + const el = document.querySelector(".pat-collapsible"); + const trigger = document.querySelector("#trigger"); + const instance = new Pattern(el, { transition: "none" }); + await events.await_pattern_init(instance); + + const spy_toggle = jest.spyOn(instance, "toggle"); + trigger.click(); + expect(spy_toggle).toHaveBeenCalledTimes(1); + + el.remove(); + await utils.timeout(1); + + trigger.click(); + expect(spy_toggle).toHaveBeenCalledTimes(1); + expect($._data(trigger, "events")).toBeUndefined(); + }); + + it("10.3 - Other instances keep their open trigger handlers.", async function () { + document.body.innerHTML = ` +
+

Trigger header

+

Collapsible content

+
+
+

Trigger header

+

Collapsible content

+
+ + `; + const el1 = document.querySelector(".c1"); + const el2 = document.querySelector(".c2"); + const instance1 = new Pattern(el1, { transition: "none" }); + const instance2 = new Pattern(el2, { transition: "none" }); + await events.await_pattern_init(instance1); + await events.await_pattern_init(instance2); + + el1.remove(); + await utils.timeout(1); + + document.querySelector("#open").click(); + await utils.timeout(1); + expect(el2.classList.contains("open")).toBe(true); + }); + }); }); From 10a3c3e7fb4415efca1cd6be4665de82f03a080d Mon Sep 17 00:00:00 2001 From: Johannes Raggam Date: Fri, 27 Nov 2026 13:44:44 +0100 Subject: [PATCH 17/22] fix(pat-scroll-marker): Disconnect the IntersectionObserver on destroy. The observer was never disconnected. The observed content elements usually stay in the page, so a destroyed scroll marker kept updating the classes on its removed links and on the content elements. Now destroy disconnects the observer, removes the current class from the content elements and pending debounced updates do not run anymore. Ref: ADR 0001 Assisted-by: Claude Opus 5.5 --- src/pat/scroll-marker/scroll-marker.js | 22 ++++++++++-- src/pat/scroll-marker/scroll-marker.test.js | 40 +++++++++++++++++++++ 2 files changed, 60 insertions(+), 2 deletions(-) diff --git a/src/pat/scroll-marker/scroll-marker.js b/src/pat/scroll-marker/scroll-marker.js index 8e8dc4ad1..ab1bffc5c 100644 --- a/src/pat/scroll-marker/scroll-marker.js +++ b/src/pat/scroll-marker/scroll-marker.js @@ -91,7 +91,7 @@ class Pattern extends BasePattern { // For debugging. this.callback_cnt = 0; - const observer = new IntersectionObserver( + this.observer = new IntersectionObserver( this.scroll_marker_callback.bind(this), { root: this.scroll_container === window ? null : this.scroll_container, @@ -99,7 +99,20 @@ class Pattern extends BasePattern { } ); for (const it of this.observables.values()) { - observer.observe(it.target); + this.observer.observe(it.target); + } + } + + destroy() { + if (this.destroyed) { + return; + } + super.destroy(); + this.observer?.disconnect(); + // Remove the current class from the content elements, which are + // usually not part of the removed pattern element. + for (const item of this.observables?.values() || []) { + item.target.classList.remove(this.options["current-content-class"]); } } @@ -134,6 +147,11 @@ class Pattern extends BasePattern { scroll_marker_current_callback() { // Set the item which is nearest to the scroll container's middle to current. + if (this.destroyed) { + // Debounced call after the pattern was destroyed. + return; + } + // First, set all to non-current. for (const item of this.observables.values()) { item.link.classList.remove(this.options["current-class"]); diff --git a/src/pat/scroll-marker/scroll-marker.test.js b/src/pat/scroll-marker/scroll-marker.test.js index cdc1f70b0..0a0dea361 100644 --- a/src/pat/scroll-marker/scroll-marker.test.js +++ b/src/pat/scroll-marker/scroll-marker.test.js @@ -374,4 +374,44 @@ describe("pat-scroll-marker", () => { expect(id3.classList.contains("scroll-marker-current")).toBe(false); }); }); + + describe("3: Destroy", () => { + it("3.1: Removing the element disconnects the observer and cleans up the content elements", async () => { + const { instance, el, id1, id2, id3 } = await create_scroll_marker(); + const spy_disconnect = jest.spyOn(instance.observer, "disconnect"); + const current = () => + [id1, id2, id3].filter((it) => + it.classList.contains("scroll-marker-current") + ); + + expect(current().length).toBe(1); + + el.remove(); + await utils.timeout(1); + + expect(instance.destroyed).toBe(true); + expect(spy_disconnect).toHaveBeenCalled(); + expect(current().length).toBe(0); + }); + + it("3.2: A pending debounced update does not run after destroy", async () => { + const { instance, el, id1, id2, id3 } = await create_scroll_marker(); + + instance.scroll_marker_callback([ + { target: id1, isIntersecting: false }, + { target: id2, isIntersecting: true }, + { target: id3, isIntersecting: true }, + ]); + el.remove(); + await utils.timeout(1); + expect(instance.destroyed).toBe(true); + + // wait for the debounced_scroll_marker_current_callback + await utils.timeout(200); + + for (const target of [id1, id2, id3]) { + expect(target.classList.contains("scroll-marker-current")).toBe(false); + } + }); + }); }); From 271004632ff20b81fde9aaace05fdcd34c5db05b Mon Sep 17 00:00:00 2001 From: Johannes Raggam Date: Fri, 27 Nov 2026 13:45:26 +0100 Subject: [PATCH 18/22] fix(pat-scroll): Remove the scroll end listener from the scroll container. The scroll end listener was registered on the scroll container or the document, but removed from the pattern element. So it was never removed and stayed on the document. All instances also shared the same listener id, so they replaced each other's listener. Register and remove the listener with the instance scoped add_event_listener and remove_event_listener on the scroll container. This also removes it when the pattern is destroyed. A delayed scroll does not run anymore if the pattern was destroyed in the meantime. Ref: ADR 0001 Assisted-by: Claude Opus 5.5 --- src/pat/scroll/scroll.js | 15 +++--- src/pat/scroll/scroll.test.js | 91 ++++++++++++++++++++++++++++++++++- 2 files changed, 99 insertions(+), 7 deletions(-) diff --git a/src/pat/scroll/scroll.js b/src/pat/scroll/scroll.js index 7e8c248ab..23e91ed4e 100644 --- a/src/pat/scroll/scroll.js +++ b/src/pat/scroll/scroll.js @@ -1,6 +1,5 @@ import { BasePattern } from "../../core/basepattern"; import dom from "../../core/dom"; -import events from "../../core/events"; import logging from "../../core/logging"; import Parser from "../../core/parser"; import registry from "../../core/registry"; @@ -50,6 +49,9 @@ class Pattern extends BasePattern { async scrollTo() { if (this.options.delay) { await utils.timeout(this.options.delay); + if (this.destroyed) { + return; + } } const target = this.get_target(); @@ -61,16 +63,17 @@ class Pattern extends BasePattern { // Set/remove classes on beginning and end of scroll this.el.classList.add("pat-scroll-animated"); + const scroll_event_el = scroll_container === window ? document : scroll_container; const debounced_scroll_end = utils.debounce(() => { this.el.classList.remove("pat-scroll-animated"); - events.remove_event_listener(this.el, "pat-scroll__scroll_end"); + this.remove_event_listener(scroll_event_el, "scroll-end"); log.debug("scroll_end"); }, 100); - events.add_event_listener( - scroll_container === window ? document : scroll_container, + this.add_event_listener( + scroll_event_el, "scroll", - "pat-scroll__scroll_end", - debounced_scroll_end.bind(this) + "scroll-end", + debounced_scroll_end ); debounced_scroll_end(); diff --git a/src/pat/scroll/scroll.test.js b/src/pat/scroll/scroll.test.js index 9916f9549..0b17ec856 100644 --- a/src/pat/scroll/scroll.test.js +++ b/src/pat/scroll/scroll.test.js @@ -1,5 +1,5 @@ import Pattern from "./scroll"; -import events from "../../core/events"; +import events, { event_listener_map } from "../../core/events"; import utils from "../../core/utils"; import { jest } from "@jest/globals"; @@ -230,4 +230,93 @@ describe("pat-scroll", function () { pat.options.selector = null; // Using href target expect(pat.get_target()).toBe(el_3); }); + + describe("10 - Scroll end listener", function () { + const scroll_end_ids = (el) => + [...(event_listener_map.get(el)?.keys() || [])].filter((id) => + id.includes("scroll-end") + ); + + afterEach(function () { + document.body.innerHTML = ""; + }); + + it("10.1 - is removed from the scroll container after scrolling.", async function () { + document.body.innerHTML = ` + p1 +

+ `; + const el = document.querySelector(".pat-scroll"); + const instance = new Pattern(el); + await events.await_pattern_init(instance); + + el.click(); + await utils.timeout(1); + expect(el.classList.contains("pat-scroll-animated")).toBe(true); + expect(scroll_end_ids(document).length).toBe(1); + + await utils.timeout(110); // wait for the scroll end debouncer. + expect(el.classList.contains("pat-scroll-animated")).toBe(false); + expect(scroll_end_ids(document).length).toBe(0); + }); + + it("10.2 - is separate for each instance.", async function () { + document.body.innerHTML = ` + p1 + p1 +

+ `; + const el1 = document.querySelector(".one"); + const el2 = document.querySelector(".two"); + const instance1 = new Pattern(el1); + const instance2 = new Pattern(el2); + await events.await_pattern_init(instance1); + await events.await_pattern_init(instance2); + + el1.click(); + el2.click(); + await utils.timeout(1); + expect(scroll_end_ids(document).length).toBe(2); + + await utils.timeout(110); // wait for the scroll end debouncer. + expect(scroll_end_ids(document).length).toBe(0); + }); + + it("10.3 - is removed on destroy.", async function () { + document.body.innerHTML = ` + p1 +

+ `; + const el = document.querySelector(".pat-scroll"); + const instance = new Pattern(el); + await events.await_pattern_init(instance); + + el.click(); + await utils.timeout(1); + expect(scroll_end_ids(document).length).toBe(1); + + el.remove(); + await utils.timeout(1); + expect(instance.destroyed).toBe(true); + expect(scroll_end_ids(document).length).toBe(0); + }); + + it("10.4 - A delayed scroll does not run after destroy.", async function () { + document.body.innerHTML = ` + p1 +

+ `; + const el = document.querySelector(".pat-scroll"); + const instance = new Pattern(el); + await events.await_pattern_init(instance); + + el.click(); + el.remove(); + await utils.timeout(60); + + expect(instance.destroyed).toBe(true); + expect(this.spy_scrollTo).not.toHaveBeenCalled(); + expect(scroll_end_ids(document).length).toBe(0); + }); + }); }); From 246798a399c7a7cc508446471cfe099db59ecf0b Mon Sep 17 00:00:00 2001 From: Johannes Raggam Date: Fri, 27 Nov 2026 13:45:51 +0100 Subject: [PATCH 19/22] fix(pat-bumper): Update all bumpers sharing a scroll container. All instances registered their scroll listener under the same id on the shared scroll container or the document. As registering under the same id replaces the previous listener, only the last bumper of a scroll container was updated. Register the listener with the instance scoped add_event_listener. This also removes it when the pattern is destroyed. Ref: ADR 0001 Assisted-by: Claude Opus 5.5 --- src/pat/bumper/bumper.js | 7 +++--- src/pat/bumper/bumper.test.js | 42 +++++++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 3 deletions(-) diff --git a/src/pat/bumper/bumper.js b/src/pat/bumper/bumper.js index 4bdd66e69..e868612f0 100644 --- a/src/pat/bumper/bumper.js +++ b/src/pat/bumper/bumper.js @@ -1,6 +1,5 @@ import { BasePattern } from "@patternslib/patternslib/src/core/basepattern"; import dom from "../../core/dom"; -import events from "../../core/events"; import Parser from "../../core/parser"; import registry from "../../core/registry"; import utils from "../../core/utils"; @@ -33,10 +32,12 @@ class Pattern extends BasePattern { const containers = new Set([this.container_x, this.container_y]); for (const container of containers) { - events.add_event_listener( + // Scoped to this instance - multiple bumpers can share the same + // scroll container. + this.add_event_listener( container || document, "scroll", - "pat_bumper__scroll", + "scroll", async () => { if (!this.ticking) { this.ticking = true; diff --git a/src/pat/bumper/bumper.test.js b/src/pat/bumper/bumper.test.js index 1503a0ec6..a9b090278 100644 --- a/src/pat/bumper/bumper.test.js +++ b/src/pat/bumper/bumper.test.js @@ -156,4 +156,46 @@ describe("pat-bumper", function () { expect(el.classList.contains("bumped-left")).toBe(false); }); }); + + describe("Scroll listeners", function () { + it("Multiple bumpers in the same scroll container are all updated.", async function () { + document.body.innerHTML = ` +
+
+ `; + const instance1 = new Bumper(document.getElementById("bump1")); + const instance2 = new Bumper(document.getElementById("bump2")); + await events.await_pattern_init(instance1); + await events.await_pattern_init(instance2); + + const spy1 = jest.spyOn(instance1, "set_bumping_classes"); + const spy2 = jest.spyOn(instance2, "set_bumping_classes"); + + document.dispatchEvent(events.scroll_event()); + await utils.animation_frame(); + + expect(spy1).toHaveBeenCalledTimes(1); + expect(spy2).toHaveBeenCalledTimes(1); + }); + + it("The scroll listener is removed on destroy.", async function () { + document.body.innerHTML = ` +
+ `; + const el = document.getElementById("bump1"); + const instance = new Bumper(el); + await events.await_pattern_init(instance); + + const spy = jest.spyOn(instance, "set_bumping_classes"); + + el.remove(); + await utils.timeout(1); + expect(instance.destroyed).toBe(true); + + document.dispatchEvent(events.scroll_event()); + await utils.animation_frame(); + + expect(spy).not.toHaveBeenCalled(); + }); + }); }); From bebe24e278b7e9efd80bae8a26871e9f14d6f2a7 Mon Sep 17 00:00:00 2001 From: Johannes Raggam Date: Fri, 27 Nov 2026 13:46:49 +0100 Subject: [PATCH 20/22] fix(pat-navigation): Remove the listeners on destroy. Register the click listener and the temporary scroll listener on the scroll container with the instance scoped add_event_listener, so that they are removed when the pattern is destroyed. The scroll listener was registered under a fixed id, shared by all instances. Ref: ADR 0001 Assisted-by: Claude Opus 5.5 --- src/pat/navigation/navigation.js | 15 +++--- src/pat/navigation/navigation.test.js | 72 ++++++++++++++++++++++++++- 2 files changed, 78 insertions(+), 9 deletions(-) diff --git a/src/pat/navigation/navigation.js b/src/pat/navigation/navigation.js index 8028a3782..59ae4e6a9 100644 --- a/src/pat/navigation/navigation.js +++ b/src/pat/navigation/navigation.js @@ -4,7 +4,6 @@ import Parser from "../../core/parser"; import ScrollMarker from "../scroll-marker/scroll-marker"; import dom from "../../core/dom"; import logging from "../../core/logging"; -import events from "../../core/events"; import registry from "../../core/registry"; import utils from "../../core/utils"; @@ -49,11 +48,11 @@ class Pattern extends BasePattern { this.debounced_scroll_marker_enabler = utils.debounce(() => { log.debug("Enable scroll-marker."); this.scroll_marker.set_current_disabled = false; - events.remove_event_listener( + this.remove_event_listener( this.scroll_marker.scroll_container === window ? document : this.scroll_marker.scroll_container, - "pat-navigation__scroll_marker_enable" + "scroll-marker-enable" ); }, 200); } @@ -65,10 +64,10 @@ class Pattern extends BasePattern { init_listeners() { const current = this.options["current-class"]; - events.add_event_listener( + this.add_event_listener( this.el, "click", - "pat_navigation_click_handler", + "click", (ev) => { // Get the click target's anchor element. The click target // might be a child of the link, e.g. a span wrapped within an @@ -92,13 +91,13 @@ class Pattern extends BasePattern { log.debug("Disable scroll-marker."); this.scroll_marker.set_current_disabled = true; this.debounced_scroll_marker_enabler(); - events.add_event_listener( + this.add_event_listener( this.scroll_marker.scroll_container === window ? document : this.scroll_marker.scroll_container, "scroll", - "pat-navigation__scroll_marker_enable", - this.debounced_scroll_marker_enabler.bind(this) + "scroll-marker-enable", + this.debounced_scroll_marker_enabler ); } } diff --git a/src/pat/navigation/navigation.test.js b/src/pat/navigation/navigation.test.js index f3863855f..5f94b7e13 100644 --- a/src/pat/navigation/navigation.test.js +++ b/src/pat/navigation/navigation.test.js @@ -1,7 +1,7 @@ import "../inject/inject"; import Pattern from "./navigation"; import Registry from "../../core/registry"; -import events from "../../core/events"; +import events, { event_listener_map } from "../../core/events"; import utils from "../../core/utils"; describe("1 - Navigation pattern tests", function () { @@ -465,3 +465,73 @@ describe("4 - Navigation pattern tests - Mark items based based clicking without expect(document.querySelector(".current a")).toBe(it222); }); }); + +describe("5 - Navigation pattern tests - Destroy.", () => { + const listener_ids = (el, name) => + [...(event_listener_map.get(el)?.keys() || [])].filter((id) => + id.includes(name) + ); + + afterEach(() => { + document.body.innerHTML = ""; + }); + + it("5.1 - Removing the navigation removes its listeners.", async () => { + document.body.innerHTML = ` + +
+
+ `; + + const nav = document.querySelector(".pat-navigation"); + const instance = new Pattern(nav); + await events.await_pattern_init(instance); + await events.await_pattern_init(instance.scroll_marker); + + expect(listener_ids(nav, "navigation--").length).toBe(1); + + // Clicking a scroll trigger temporarily disables the scroll marker + // and listens for scroll events on the scroll container. + document.querySelector("a[href='#s1']").click(); + expect(instance.scroll_marker.set_current_disabled).toBe(true); + expect(listener_ids(document, "scroll-marker-enable").length).toBe(1); + + nav.remove(); + await utils.timeout(1); + + expect(instance.destroyed).toBe(true); + expect(instance.scroll_marker.destroyed).toBe(true); + expect(listener_ids(nav, "navigation--").length).toBe(0); + expect(listener_ids(document, "scroll-marker-enable").length).toBe(0); + }); + + it("5.2 - The scroll marker is re-enabled after scrolling.", async () => { + document.body.innerHTML = ` + +
+ `; + + const nav = document.querySelector(".pat-navigation"); + const instance = new Pattern(nav); + await events.await_pattern_init(instance); + await events.await_pattern_init(instance.scroll_marker); + + document.querySelector("a[href='#s1']").click(); + expect(instance.scroll_marker.set_current_disabled).toBe(true); + + document.dispatchEvent(new Event("scroll")); + await utils.timeout(210); // Wait for the debounced enabler. + + expect(instance.scroll_marker.set_current_disabled).toBe(false); + expect(listener_ids(document, "scroll-marker-enable").length).toBe(0); + }); +}); From a19c17a59add84e7fcf5b8b5bb18949a982f3dd8 Mon Sep 17 00:00:00 2001 From: Johannes Raggam Date: Fri, 27 Nov 2026 13:47:38 +0100 Subject: [PATCH 21/22] fix(pat-validation): Remove the listeners on destroy. Register the submit and input listeners with the instance scoped add_event_listener, so that they are removed when the pattern is destroyed. Before, the listener registry kept the removed form and its inputs referenced. The input listener names do not contain the input's position anymore. When re-initializing after pat-update, an input which changed its position got a second set of listeners. Listeners of inputs which are gone after re-initializing are removed. Ref: ADR 0001 Assisted-by: Claude Opus 5.5 --- src/pat/validation/maxmin.html | 60 +++++++++++++++++++++++++++ src/pat/validation/tmp.md | 14 +++++++ src/pat/validation/validation.js | 41 +++++++++--------- src/pat/validation/validation.test.js | 59 +++++++++++++++++++++++++- 4 files changed, 151 insertions(+), 23 deletions(-) create mode 100644 src/pat/validation/maxmin.html create mode 100644 src/pat/validation/tmp.md diff --git a/src/pat/validation/maxmin.html b/src/pat/validation/maxmin.html new file mode 100644 index 000000000..dc2baa772 --- /dev/null +++ b/src/pat/validation/maxmin.html @@ -0,0 +1,60 @@ + + + + Form validation + + + + + + +

Demo with max-values / min-values support

+ + +
+ +
+ + +
+
+ + + + diff --git a/src/pat/validation/tmp.md b/src/pat/validation/tmp.md new file mode 100644 index 000000000..714b90745 --- /dev/null +++ b/src/pat/validation/tmp.md @@ -0,0 +1,14 @@ +Hi Daniël, + +we had the need to validate if at least one checkbox in a group of checkboxes was checked. +This was not yet supported by pat-validation nor by the HTML specficiation. + +As a side note - required radio buttons are supported. A `required` attribute on one or all radio inputs in a group of radio inputs is supported by the HTML specification and validated by pat-validation. + +We were in need to quickly support that in one of our projects and I did a implementation to support that. + +Please see this implementation as a draft to discuss about. + +These parameters were added: + +- min-values: The minimum number of values to be checked, selected of filled-out. diff --git a/src/pat/validation/validation.js b/src/pat/validation/validation.js index 7165e17ff..114161dd8 100644 --- a/src/pat/validation/validation.js +++ b/src/pat/validation/validation.js @@ -4,7 +4,6 @@ import $ from "jquery"; import { BasePattern } from "../../core/basepattern"; import Parser from "../../core/parser"; import dom from "../../core/dom"; -import events from "../../core/events"; import logging from "../../core/logging"; import utils from "../../core/utils"; import registry from "../../core/registry"; @@ -43,10 +42,10 @@ class Pattern extends BasePattern { static order = 100; init() { - events.add_event_listener( + this.add_event_listener( this.el, "submit", - `pat-validation--submit--validator`, + "submit", async (e) => { // On submit, check all. // Immediate, non-debounced check with submit. Otherwise submit @@ -73,38 +72,36 @@ class Pattern extends BasePattern { } initialize_inputs() { + const previous_inputs = this.inputs || []; this.inputs = [ ...this.el.querySelectorAll("input[name], select[name], textarea[name]"), ]; + + // Remove the listeners from inputs which are gone. + for (const input of previous_inputs) { + if (!this.inputs.includes(input)) { + for (const event_type of ["input", "change", "blur"]) { + this.remove_event_listener(input, event_type); + } + } + } this.disabled_elements = [ ...this.el.querySelectorAll(this.options.disableSelector), ]; - for (const [cnt, input] of this.inputs.entries()) { + for (const input of this.inputs) { // Cancelable debouncer. const debouncer = utils.debounce((e) => { logger.debug("Checking input for event", input, e); this.check_input({ input: input, event: e }); }, this.options.delay); - events.add_event_listener( - input, - "input", - `pat-validation--input-${input.name}--${cnt}--validator`, - (e) => debouncer(e) - ); - events.add_event_listener( - input, - "change", - `pat-validation--change-${input.name}--${cnt}--validator`, - (e) => debouncer(e) - ); - events.add_event_listener( - input, - "blur", - `pat-validation--blur-${input.name}--${cnt}--validator`, - (e) => debouncer(e) - ); + // Registering again under the same name replaces the listener. + for (const event_type of ["input", "change", "blur"]) { + this.add_event_listener(input, event_type, event_type, (e) => + debouncer(e) + ); + } } } diff --git a/src/pat/validation/validation.test.js b/src/pat/validation/validation.test.js index 4f34fe9d1..ef249f0cd 100644 --- a/src/pat/validation/validation.test.js +++ b/src/pat/validation/validation.test.js @@ -1,5 +1,6 @@ +import $ from "jquery"; import Pattern, { parser } from "./validation"; -import events from "../../core/events"; +import events, { event_listener_map } from "../../core/events"; import utils from "../../core/utils"; import { jest } from "@jest/globals"; @@ -1751,4 +1752,60 @@ describe("pat-validation", function () { expect(document.querySelectorAll("script").length).toBe(0); }); }); + + describe("9 - Listeners", function () { + afterEach(function () { + document.body.innerHTML = ""; + }); + + it("9.1 - Removing the form removes all listeners.", async function () { + document.body.innerHTML = ` +
+ + +
+ `; + const el = document.querySelector(".pat-validation"); + const [i1, i2] = el.querySelectorAll("[name]"); + const instance = new Pattern(el); + await events.await_pattern_init(instance); + + expect(event_listener_map.get(el).size).toBe(1); + expect(event_listener_map.get(i1).size).toBe(3); + expect(event_listener_map.get(i2).size).toBe(3); + + el.remove(); + await utils.timeout(1); + + expect(instance.destroyed).toBe(true); + expect(event_listener_map.has(el)).toBe(false); + expect(event_listener_map.has(i1)).toBe(false); + expect(event_listener_map.has(i2)).toBe(false); + }); + + it("9.2 - Re-initializing the inputs does not duplicate listeners and removes them from removed inputs.", async function () { + document.body.innerHTML = ` +
+ + +
+ `; + const el = document.querySelector(".pat-validation"); + const [i1, i2] = el.querySelectorAll("[name]"); + const instance = new Pattern(el); + await events.await_pattern_init(instance); + + // Remove the first input, so that the second one changes its position. + i1.remove(); + $(el).trigger("pat-update"); + + expect(event_listener_map.has(i1)).toBe(false); + expect(event_listener_map.get(i2).size).toBe(3); + + const spy_check_input = jest.spyOn(instance, "check_input"); + i2.dispatchEvent(new Event("input")); + await utils.timeout(instance.options.delay + 1); // wait for the debouncer. + expect(spy_check_input).toHaveBeenCalledTimes(1); + }); + }); }); From 70f5621956ed257e61b6cf41e35d4fcfbb09c945 Mon Sep 17 00:00:00 2001 From: Johannes Raggam Date: Fri, 27 Nov 2026 13:48:00 +0100 Subject: [PATCH 22/22] fix(pat-tooltip): Remove the listeners on destroy. Register the click blocker and the close-panel listener on the popper with the instance scoped add_event_listener, so that they are removed when the pattern is destroyed. Before, the listener registry kept the removed element and the popper referenced. Ref: ADR 0001 Assisted-by: Claude Opus 5.5 --- src/pat/tooltip/tooltip.js | 8 ++++---- src/pat/tooltip/tooltip.test.js | 30 +++++++++++++++++++++++++++++- 2 files changed, 33 insertions(+), 5 deletions(-) diff --git a/src/pat/tooltip/tooltip.js b/src/pat/tooltip/tooltip.js index b50584150..516780d7a 100644 --- a/src/pat/tooltip/tooltip.js +++ b/src/pat/tooltip/tooltip.js @@ -110,10 +110,10 @@ class Pattern extends BasePattern { if (this.options.trigger === "click" && this.options.source === "ajax") { // prevent default action for "click" and "mouseenter click" - events.add_event_listener( + this.add_event_listener( el, "click", - "pat-tooltip--click-prevent-default", + "click-prevent-default", (event) => { event.preventDefault(); event.stopPropagation(); @@ -320,10 +320,10 @@ class Pattern extends BasePattern { } // Store reference to method for closing panels on the tooltip element instance. - events.add_event_listener( + this.add_event_listener( this.tippy.popper, "close-panel", - "pat-tooltip--close-panel", + "close-panel", () => this.hide() ); diff --git a/src/pat/tooltip/tooltip.test.js b/src/pat/tooltip/tooltip.test.js index fd2cdfca7..1c56b9dfd 100644 --- a/src/pat/tooltip/tooltip.test.js +++ b/src/pat/tooltip/tooltip.test.js @@ -1,7 +1,7 @@ import $ from "jquery"; import autosubmit from "../auto-submit/auto-submit"; import { BasePattern } from "../../core/basepattern"; -import events from "../../core/events"; +import events, { event_listener_map } from "../../core/events"; import lifecycle from "../../core/lifecycle"; import Pattern from "./tooltip"; import registry from "../../core/registry"; @@ -1915,5 +1915,33 @@ this will be extracted. expect(dummy.destroyed).toBe(true); expect(lifecycle.is_tracked(dummy)).toBe(false); }); + + it("11.5 - The listeners on the element and the popper are removed on destroy.", async () => { + global.fetch = jest.fn().mockImplementation(mockFetch("Content")); + + const $el = testutils.createTooltip({ + data: "source: ajax; trigger: click", + href: "http://test.com", + }); + const el = $el[0]; + const instance = new Pattern($el); + await events.await_pattern_init(instance); + + testutils.click($el); + await utils.timeout(1); + const popper = instance.tippy.popper; + expect(event_listener_map.has(el)).toBe(true); + expect(event_listener_map.has(popper)).toBe(true); + + el.remove(); + await utils.timeout(1); + + expect(instance.destroyed).toBe(true); + expect(event_listener_map.has(el)).toBe(false); + expect(event_listener_map.has(popper)).toBe(false); + + global.fetch.mockRestore(); + delete global.fetch; + }); }); });