From 29bfc7ff3b319e928dcf49395326b68b99a1db53 Mon Sep 17 00:00:00 2001 From: Johannes Raggam Date: Sun, 29 Nov 2026 05:48:56 +0100 Subject: [PATCH 01/61] maint(docs): Add ADR 0009 on migrating patterns to BasePattern. Assisted-by: Claude Opus 5.5 --- .../0009-migrate-patterns-to-basepattern.md | 65 +++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 docs/adr/0009-migrate-patterns-to-basepattern.md diff --git a/docs/adr/0009-migrate-patterns-to-basepattern.md b/docs/adr/0009-migrate-patterns-to-basepattern.md new file mode 100644 index 000000000..f35e7ee1e --- /dev/null +++ b/docs/adr/0009-migrate-patterns-to-basepattern.md @@ -0,0 +1,65 @@ +# 0009 Migrate patterns to BasePattern + +Status: Accepted (2026-11-29) + +## Context + +Most patterns were still based on the legacy `Base.extend` or were plain +objects with an `init($el)` function. Only part of them used the class based +`BasePattern`, which provides per-element instances, options parsing via a +static parser, instance scoped event listeners and automatic destroy when the +element is removed from the document (ADR 0001, 0004). + +Legacy patterns never cleaned up: listeners on `document`/`window`, +observers, timers and third party instances (Pikaday, Select2, Slick, +Masonry, ...) stayed alive after their element was removed. + +A class based implementation is also a precondition for loading pattern +implementations lazily, because a placeholder can then instantiate the real +class after loading it. + +## Decision + +Migrate all patterns of Patternslib and of the add-ons pat-shopping-cart, +pat-upload, pat-doclock and pat-tinymce to `BasePattern`, one commit per +pattern, following the pat-equaliser migration (3b43307e0): + +- Options come from the static parser. +- Global listeners are instance scoped, third party instances, observers and + timers are cleaned up in `destroy()`. +- `destroy()` does not undo DOM changes (deferred). +- jQuery listeners are kept where events are triggered via jQuery + (`patterns-injected`, `pat-update`, ...), because native listeners don't + receive them. They use a per-instance namespace and are removed on destroy. +- The HTML API stays the same. The JavaScript API changes: the default export + is the class, the jQuery plugins and static `init` methods are gone. In + Patternslib the commits are marked `tech`, because the pattern integration + contract for designers is unchanged; the JavaScript API change is described + in each commit message. In the add-ons they are marked `breaking`. + +Not migrated: + +- **pat-inject**: it is a shared service as well as a pattern (`execute`, + `submitSubform`, `registerTypeHandler`, `init` are called by other + patterns), has module level side effects which must run on page load + (history handling, the `patterns-injected` rescan listener) and relies on a + timing contract with pat-validation. +- **pat-ajax**: the transport service of pat-inject and pat-subform. +- **pat-focus, pat-legend**: transform-only patterns without per-element + instances. +- **pat-grid**: CSS only. + +## Consequences + +- Patterns are destroyed when their element is removed and stop reacting to + global events. Several leaks and long standing bugs found during the + migration are fixed, as separate `fix` commits where they were separable. +- All patterns initialize asynchronously, one tick later than legacy + patterns did. JavaScript code must wait with + `events.await_pattern_init(instance)`. +- JavaScript users of the legacy APIs need to migrate to `new Pattern(el)` + and instance methods. pat-modal: closing is now `close()`, `destroy()` only + cleans up. +- The add-ons depend on @patternslib/patternslib 9.11.1, whose `BasePattern` + has neither instance scoped listeners nor automatic destroy. They use + `core/events` directly and benefit from automatic destroy once they update. From 8959352e11080cb347a348d7c64ecd06a01d8b3f Mon Sep 17 00:00:00 2001 From: Johannes Raggam Date: Sun, 29 Nov 2026 05:50:26 +0100 Subject: [PATCH 02/61] tech(pat-clone): Migrate to a class based pattern. pat-clone is now based on BasePattern and gets destroyed automatically when its element is removed from the document: - The click handlers on the clone triggers, which can be anywhere in the document, and on the remove buttons are pattern instance scoped and removed on destroy. When a clone is removed, the handlers within it are removed too. Fix: reaching the `max` number of clones threw an error because the clone triggers were never collected (since 585d8ee68). The triggers are now hidden when the maximum is reached and shown again after a clone was removed. Breaking change for JavaScript users: the default export is now the pattern class. It is not created via `Base.extend` anymore and has no static `init` method. Patterns are initialized asynchronously, so wait for `events.await_pattern_init(instance)` before interacting. Ref: ADR 0009 Assisted-by: Claude Opus 5.5 --- src/pat/clone/clone.js | 48 +++++++--- src/pat/clone/clone.test.js | 176 +++++++++++++++++++++++++++++++----- 2 files changed, 185 insertions(+), 39 deletions(-) diff --git a/src/pat/clone/clone.js b/src/pat/clone/clone.js index 49028e951..a368a19fc 100644 --- a/src/pat/clone/clone.js +++ b/src/pat/clone/clone.js @@ -2,7 +2,7 @@ import $ from "jquery"; import Parser from "../../core/parser"; import registry from "../../core/registry"; -import Base from "../../core/base"; +import { BasePattern } from "../../core/basepattern"; import logging from "../../core/logging"; import dom from "../../core/dom"; import utils from "../../core/utils"; @@ -23,12 +23,13 @@ parser.addArgument( parser.addArgument("clone-element", ".clone"); parser.addAlias("remove-behavior", "remove-behaviour"); -export default Base.extend({ - name: "clone", - trigger: ".pat-clone", +class Pattern extends BasePattern { + static name = "clone"; + static trigger = ".pat-clone"; + static parser = parser; init() { - this.options = parser.parse(this.el, this.options); + this.$el = $(this.el); if (this.options.template.lastIndexOf(":", 0) === 0) { this.template = $(this.options.template, this.el)[0]; } else { @@ -42,7 +43,12 @@ export default Base.extend({ for (const clone of clones) { this.bind_remove(clone); } - }, + } + + get clone_triggers() { + // All clone triggers in the document. + return document.querySelectorAll(this.options.triggerElement); + } clone() { if (this.num_clones >= this.options.max) { @@ -98,7 +104,7 @@ export default Base.extend({ dom.hide(el_); } } - }, + } incrementValues(idx, el) { const $el = $(el); @@ -121,7 +127,7 @@ export default Base.extend({ } else if (el.data.length) { el.data = el.data.replace("#{1}", this.num_clones); } - }, + } bind_trigger(triggers) { // Bind clone trigger @@ -130,10 +136,13 @@ export default Base.extend({ node, this.options.triggerElement )) { - trigger.addEventListener("click", () => this.clone()); + // The triggers can be anywhere in the document. Register the + // event listeners instance scoped so that they are removed + // when the pattern is destroyed. + this.add_event_listener(trigger, "click", "clone", () => this.clone()); } } - }, + } bind_remove(clone) { for (const node of utils.ensureArray(clone)) { @@ -141,7 +150,7 @@ export default Base.extend({ node, this.options.remove.element )) { - remove_button.addEventListener("click", () => { + this.add_event_listener(remove_button, "click", "remove", () => { if (this.options.remove.behaviour === "confirm") { if (window.confirm(this.options.remove.confirmation) === true) { this.remove(clone); @@ -152,10 +161,17 @@ export default Base.extend({ }); } } - }, + } remove(clone) { for (const node of utils.ensureArray(clone)) { + // Remove the event listeners within the removed clone. + for (const it of dom.querySelectorAllAndMe( + node, + `${this.options.triggerElement}, ${this.options.remove.element}` + )) { + this.remove_event_listener(it); + } node.remove(); this.$el.trigger("pat-update", { pattern: "clone", @@ -169,5 +185,9 @@ export default Base.extend({ dom.show(el_); } } - }, -}); + } +} + +registry.register(Pattern); +export default Pattern; +export { Pattern }; diff --git a/src/pat/clone/clone.test.js b/src/pat/clone/clone.test.js index ea2bbae69..68c75300c 100644 --- a/src/pat/clone/clone.test.js +++ b/src/pat/clone/clone.test.js @@ -1,9 +1,19 @@ import Base from "../../core/base"; import registry from "../../core/registry"; import Clone from "./clone"; +import events from "../../core/events"; +import utils from "../../core/utils"; import $ from "jquery"; import { jest } from "@jest/globals"; +const init_clones = async (root) => { + // Initialize all pat-clone instances within root. + for (const el of root.querySelectorAll(".pat-clone")) { + const instance = new Clone(el); + await events.await_pattern_init(instance); + } +}; + describe("pat-clone", function () { describe("1 - Basic tests", function () { beforeEach(function () { @@ -15,7 +25,7 @@ describe("pat-clone", function () { jest.restoreAllMocks(); }); - it("clones the node's first child when .add-clone is clicked and places the clone after the cloned element", function () { + it("clones the node's first child when .add-clone is clicked and places the clone after the cloned element", async function () { var $lab = $("#lab"); $lab.html( '
' + @@ -23,7 +33,7 @@ describe("pat-clone", function () { ' ' + "
" ); - registry.scan($lab); + await init_clones($lab[0]); expect($("div.item").length).toBe(1); $lab.find(".add-clone").click(); expect($("div.item").length).toBe(2); @@ -38,7 +48,7 @@ describe("pat-clone", function () { "" ); - registry.scan($lab); + await init_clones($lab[0]); expect($("div.item").length).toBe(1); $lab.find(".add-clone").click(); expect($("div.item").length).toBe(2); @@ -48,7 +58,7 @@ describe("pat-clone", function () { expect($("div.item").length).toBe(4); }); - it("allows the trigger element to be configured", function () { + it("allows the trigger element to be configured", async function () { var $lab = $("#lab"); $lab.html( '
' + @@ -57,7 +67,7 @@ describe("pat-clone", function () { ' ' + "
" ); - registry.scan($lab); + await init_clones($lab[0]); expect($("div.item").length).toBe(1); $lab.find(".add-clone").click(); expect($("div.item").length).toBe(1); @@ -65,7 +75,7 @@ describe("pat-clone", function () { expect($("div.item").length).toBe(2); }); - it("allows the cloned element to be configured", function () { + it("allows the cloned element to be configured", async function () { var $lab = $("#lab"); $lab.html( '
' + @@ -74,7 +84,7 @@ describe("pat-clone", function () { "
" + '' ); - registry.scan($lab); + await init_clones($lab[0]); expect($("div.item").length).toBe(2); $lab.find(".add-clone").click(); expect($("div.item").length).toBe(3); @@ -82,7 +92,7 @@ describe("pat-clone", function () { expect($("div.item:contains('Clone template')").length).toBe(2); }); - it("will replace #{1} in element attributes with the number of the clone", function () { + it("will replace #{1} in element attributes with the number of the clone", async function () { var $lab = $("#lab"); $lab.html( '
' + @@ -90,7 +100,7 @@ describe("pat-clone", function () { "
" + '' ); - registry.scan($lab); + await init_clones($lab[0]); expect($("p.legend").length).toBe(1); expect($("p.legend:last").attr("class")).toBe("legend clone clone#{1}"); @@ -105,7 +115,7 @@ describe("pat-clone", function () { expect($("p.legend:last").attr("class")).toBe("legend clone clone3"); }); - it("will replace #{1} in the element id with the number of the clone and remove ids without the substring #{1}", function () { + it("will replace #{1} in the element id with the number of the clone and remove ids without the substring #{1}", async function () { var $lab = $("#lab"); $lab.html( '
' + @@ -113,7 +123,7 @@ describe("pat-clone", function () { "
" + '' ); - registry.scan($lab); + await init_clones($lab[0]); expect($("p.legend").length).toBe(1); expect($("p.legend:last").attr("id")).toBe("hello world#{1}"); @@ -126,7 +136,7 @@ describe("pat-clone", function () { expect($("p.legend:last").attr("id")).toBe("world3"); }); - it('has a "clone-element" argument which is necessary when starting with pre-existing clones', function () { + it('has a "clone-element" argument which is necessary when starting with pre-existing clones', async function () { jest.spyOn(window, "confirm").mockImplementation(() => { return true; }); @@ -139,7 +149,7 @@ describe("pat-clone", function () { "" + '' ); - registry.scan($lab); + await init_clones($lab[0]); expect($("div.item").length).toBe(3); $lab.find(".add-clone").click(); @@ -158,7 +168,7 @@ describe("pat-clone", function () { expect($("div.item").length).toBe(0); }); - it("will remove a clone when .remove-clone inside the clone is clicked.", function () { + it("will remove a clone when .remove-clone inside the clone is clicked.", async function () { var spy_window = jest.spyOn(window, "confirm").mockImplementation(() => { return true; }); @@ -169,7 +179,7 @@ describe("pat-clone", function () { "" + '' ); - registry.scan($lab); + await init_clones($lab[0]); expect($("div.item").length).toBe(1); $lab.find(".add-clone").click(); @@ -184,7 +194,7 @@ describe("pat-clone", function () { expect($("div.item").length).toBe(0); }); - it("allows the remove element to be configured", function () { + it("allows the remove element to be configured", async function () { var spy_window = jest.spyOn(window, "confirm").mockImplementation(() => { return true; }); @@ -195,7 +205,7 @@ describe("pat-clone", function () { "" + '' ); - registry.scan($lab); + await init_clones($lab[0]); expect($("div.item").length).toBe(1); $lab.find(".add-clone").click(); @@ -210,7 +220,7 @@ describe("pat-clone", function () { expect($("div.item").length).toBe(0); }); - it("will by default ask for confirmation before removing elements, but can be configured otherwise", function () { + it("will by default ask for confirmation before removing elements, but can be configured otherwise", async function () { var spy_confirm = jest.spyOn(window, "confirm").mockImplementation(() => { return true; }); @@ -221,7 +231,7 @@ describe("pat-clone", function () { "" + '' ); - registry.scan($lab); + await init_clones($lab[0]); expect($("div.item").length).toBe(1); $lab.find(".add-clone").click(); @@ -239,7 +249,7 @@ describe("pat-clone", function () { "" + '' ); - registry.scan($lab); + await init_clones($lab[0]); expect($("div.item").length).toBe(1); $lab.find(".add-clone").click(); @@ -263,7 +273,7 @@ describe("pat-clone", function () { registry.patterns = patterns; }); - it("will initialize patterns when cloned.", function () { + it("will initialize patterns when cloned.", async function () { Base.extend({ name: "example", trigger: ".pat-example", @@ -281,6 +291,7 @@ describe("pat-clone", function () { `; registry.scan(document.body); + await utils.timeout(1); // Without further action patterns in templates are initialized. // Not what we want, normally. @@ -296,7 +307,7 @@ describe("pat-clone", function () { ).toBe("initializedinitialized"); }); - it("will not initialize patterns in the template wrapped in disable-patterns.", function () { + it("will not initialize patterns in the template wrapped in disable-patterns.", async function () { Base.extend({ name: "example", trigger: ".pat-example", @@ -314,6 +325,7 @@ describe("pat-clone", function () { `; registry.scan(document.body); + await utils.timeout(1); // The template-pattern isn't initialized. expect( @@ -328,7 +340,7 @@ describe("pat-clone", function () { ).toBe("initialized"); }); - it("will not initialize patterns wrapped in