Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
b3f8101
maint(docs): Start with ADR records.
thet Nov 27, 2026
53bbf9f
maint(docs): Add ADRs for the automatic pattern lifecycle.
thet Nov 27, 2026
30e0dda
feat(core basepattern): Destroy patterns automatically when removed f…
thet Nov 27, 2026
25d6f25
feat(core lifecycle): Add self managed containers.
thet Nov 27, 2026
628f022
feat(core basepattern): Add instance scoped remove_event_listener.
thet Nov 27, 2026
f3a201f
fix(core basepattern): Remove listeners registered after a destroy du…
thet Nov 27, 2026
7d27bb8
maint(docs): Add ADR 0003 for the WeakMap based event listener registry.
thet Nov 27, 2026
0f91479
feat(core events): Do not keep elements alive in the event listener r…
thet Nov 27, 2026
5dff276
maint(docs): Add ADR 0004 for event listener scopes.
thet Nov 27, 2026
8c72943
feat(core events): Add listener scopes.
thet Nov 27, 2026
72f3f70
feat(core basepattern): Use a listener scope for instance scoped list…
thet Nov 27, 2026
00c2f91
feat(pat-tooltip): Keep patterns in the tooltip content across hide a…
thet Nov 27, 2026
bfb50bb
fix(pat-depends): Update the state after a form reset.
thet Nov 27, 2026
935f5ca
fix(pat-depends): Remove the input listeners on destroy.
thet Nov 27, 2026
d9b7b15
fix(pat-autofocus): Remove the pat-update handler on destroy.
thet Nov 27, 2026
91d7a3b
fix(pat-collapsible): Remove the trigger handlers on destroy.
thet Nov 27, 2026
10a3c3e
fix(pat-scroll-marker): Disconnect the IntersectionObserver on destroy.
thet Nov 27, 2026
2710046
fix(pat-scroll): Remove the scroll end listener from the scroll conta…
thet Nov 27, 2026
246798a
fix(pat-bumper): Update all bumpers sharing a scroll container.
thet Nov 27, 2026
bebe24e
fix(pat-navigation): Remove the listeners on destroy.
thet Nov 27, 2026
a19c17a
fix(pat-validation): Remove the listeners on destroy.
thet Nov 27, 2026
70f5621
fix(pat-tooltip): Remove the listeners on destroy.
thet Nov 27, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions docs/adr/0000-README.md
Original file line number Diff line number Diff line change
@@ -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/
74 changes: 74 additions & 0 deletions docs/adr/0001-destroy-patterns-automatically-on-dom-removal.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
# 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()``. Listeners registered with
``add_event_listener`` after a ``destroy()`` during ``init()`` are removed
after ``init()``.
- ``destroy()`` only removes the ``pattern-<name>`` 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.
47 changes: 47 additions & 0 deletions docs/adr/0002-self-managed-containers-for-pattern-lifecycle.md
Original file line number Diff line number Diff line change
@@ -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.
53 changes: 53 additions & 0 deletions docs/adr/0003-weakmap-event-listener-registry.md
Original file line number Diff line number Diff line change
@@ -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<element, Map<id, listener>>``.

- 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. ``<namespace>--*``) 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.
66 changes: 66 additions & 0 deletions docs/adr/0004-event-listener-scopes.md
Original file line number Diff line number Diff line change
@@ -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 ``<namespace>--<name>`` 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
``<namespace>--*``. 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
``<pattern name>--<instance uuid>`` 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 ``*``.
81 changes: 72 additions & 9 deletions src/core/basepattern.js
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand All @@ -23,6 +24,10 @@ class BasePattern {
parser_multiple = undefined;
parser_inherit = true;

// 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.
this.name = this.constructor.name;
Expand All @@ -39,6 +44,14 @@ 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
// 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(
new Event(`pre-init.${this.name}.patterns`, {
Expand All @@ -60,6 +73,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);
Expand Down Expand Up @@ -91,6 +116,21 @@ class BasePattern {
// Initialize the pattern
await this.init();

if (this.destroyed) {
// Destroyed while initializing. Remove the listeners which
// were registered after the destroy.
this.#listeners.remove_all();
} else {
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`, {
Expand Down Expand Up @@ -147,23 +187,46 @@ 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
);
this.#listeners?.add(el, event_type, name, cb, opts);
}

/**
* 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``. Can be a wildcard
* string. Without a name, all listeners of this
* instance on the element are removed.
*/
remove_event_listener(el, name) {
this.#listeners?.remove(el, name);
}

/**
* 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() {
events.remove_event_listener(null, `${this.name}--${this.uuid}--*`);
delete this.el[`pattern-${this.name}`];
if (this.destroyed) {
return;
}
this.destroyed = true;
lifecycle.untrack(this);
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.
delete this.el[`pattern-${this.name}`];
}
}
}

Expand Down
Loading