Skip to content

Commit 08298ae

Browse files
authored
Merge pull request #1312 from Patternslib/basepattern-migration
BasePattern migration + Lazy loading Patterns
2 parents 45931a7 + 7f71942 commit 08298ae

127 files changed

Lines changed: 16221 additions & 11031 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
# 0009 Migrate patterns to BasePattern
2+
3+
Status: Accepted (2026-11-29)
4+
5+
## Context
6+
7+
Most patterns were still based on the legacy `Base.extend` or were plain
8+
objects with an `init($el)` function. Only part of them used the class based
9+
`BasePattern`, which provides per-element instances, options parsing via a
10+
static parser, instance scoped event listeners and automatic destroy when the
11+
element is removed from the document (ADR 0001, 0004).
12+
13+
Legacy patterns never cleaned up: listeners on `document`/`window`,
14+
observers, timers and third party instances (Pikaday, Select2, Slick,
15+
Masonry, ...) stayed alive after their element was removed.
16+
17+
A class based implementation is also a precondition for loading pattern
18+
implementations lazily, because a placeholder can then instantiate the real
19+
class after loading it.
20+
21+
## Decision
22+
23+
Migrate all patterns of Patternslib and of the add-ons pat-shopping-cart,
24+
pat-upload, pat-doclock and pat-tinymce to `BasePattern`, one commit per
25+
pattern, following the pat-equaliser migration (3b43307e0):
26+
27+
- Options come from the static parser.
28+
- Global listeners are instance scoped, third party instances, observers and
29+
timers are cleaned up in `destroy()`.
30+
- `destroy()` does not undo DOM changes (deferred).
31+
- jQuery listeners are kept where events are triggered via jQuery
32+
(`patterns-injected`, `pat-update`, ...), because native listeners don't
33+
receive them. They use a per-instance namespace and are removed on destroy.
34+
- The HTML API stays the same. The JavaScript API changes: the default export
35+
is the class, the jQuery plugins and static `init` methods are gone. In
36+
Patternslib the commits are marked `tech`, because the pattern integration
37+
contract for designers is unchanged; the JavaScript API change is described
38+
in each commit message. In the add-ons they are marked `breaking`.
39+
40+
Not migrated:
41+
42+
- **pat-inject**: it is a shared service as well as a pattern (`execute`,
43+
`submitSubform`, `registerTypeHandler`, `init` are called by other
44+
patterns), has module level side effects which must run on page load
45+
(history handling, the `patterns-injected` rescan listener) and relies on a
46+
timing contract with pat-validation.
47+
- **pat-ajax**: the transport service of pat-inject and pat-subform.
48+
- **pat-focus, pat-legend**: transform-only patterns without per-element
49+
instances.
50+
- **pat-grid**: CSS only.
51+
52+
## Consequences
53+
54+
- Patterns are destroyed when their element is removed and stop reacting to
55+
global events. Several leaks and long standing bugs found during the
56+
migration are fixed, as separate `fix` commits where they were separable.
57+
- All patterns initialize asynchronously, one tick later than legacy
58+
patterns did. JavaScript code must wait with
59+
`events.await_pattern_init(instance)`.
60+
- JavaScript users of the legacy APIs need to migrate to `new Pattern(el)`
61+
and instance methods. pat-modal: closing is now `close()`, `destroy()` only
62+
cleans up.
63+
- The add-ons depend on @patternslib/patternslib 9.11.1, whose `BasePattern`
64+
has neither instance scoped listeners nor automatic destroy. They use
65+
`core/events` directly and benefit from automatic destroy once they update.
Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
# 0010 Lazily loaded pattern implementations
2+
3+
Status: Accepted (2026-11-29)
4+
5+
## Context
6+
7+
All patterns imported in `src/patterns.js` end up in one eagerly loaded
8+
patterns chunk, which every page loads. Before this change it was about
9+
201 KB minified, of which about 148 KB was pattern code and about 10 KB were
10+
lookup maps of dynamic import contexts (ADR 0007). Heavy third party
11+
libraries were already imported dynamically, but the pattern code itself
12+
was not, even on pages which don't use the pattern.
13+
14+
Mockup already splits patterns into a thin registration module and a lazily
15+
imported `--implementation` module. The convention started there with the
16+
controlpanel patterns (Mockup commit fe0380c46, 2021-11-25) and is used for
17+
several patterns since (e.g. Mockup's `pat/modal/modal.js`). Mockup's
18+
patterns are `Base` patterns though, while the patterns split here are class
19+
based (ADR 0009). See "Alternatives considered".
20+
21+
Other code instantiates patterns from the registry directly, e.g.
22+
`new registry.patterns.markdown(el)` in pat-tooltip or
23+
`await new registry.patterns[name](el)` in Mockup. Registry code of other
24+
Module Federation bundles also instantiates registry entries with `new`.
25+
26+
## Decision
27+
28+
- `core/lazy-pattern.js` provides `create_lazy_pattern({name, trigger,
29+
order, load})`. It returns a small placeholder class which is registered
30+
instead of the real class. Instantiating it loads the implementation and
31+
returns a Promise of the real pattern instance. A class constructor may
32+
return an object, so the registry and other code using `new` keep working
33+
unchanged. Once loaded, the registry entry is replaced by the real class.
34+
- `events.await_pattern_init` also accepts such a Promise, so
35+
`await events.await_pattern_init(new Pattern(el))` keeps working.
36+
- A split pattern `pat/NAME/NAME.js` only contains the registration and
37+
module level code which must run on page load. The class lives in
38+
`pat/NAME/NAME--implementation.js`, which still registers itself, so
39+
importing it directly gives an eagerly registered pattern. Code which needs
40+
the class or the parser imports the `--implementation` module.
41+
- Split are patterns where it makes a difference (roughly 2 KB minified or
42+
more, including dynamic import lookup maps): calendar, navigation,
43+
scroll-marker, auto-suggest, date-picker, datetime-picker, display-time,
44+
sortable, modal, notification, bumper, image-crop, clone, masonry,
45+
gallery, carousel, auto-submit, markdown and syntax-highlight.
46+
- Kept eager, because lazy loading would break them or change what users
47+
see:
48+
- pat-inject and pat-ajax: shared services, used by many patterns and on
49+
almost every page anyway (ADR 0009).
50+
- pat-validation: must register its submit handlers before pat-inject.
51+
- pat-tooltip: imported as class and parser by Mockup and pat-tiptap.
52+
- pat-depends, pat-collapsible, pat-stacks, pat-toggle: they hide or show
53+
content on initialization. Loading them later would flash content in the
54+
wrong state.
55+
- pat-bind: renders bound values on initialization.
56+
- pat-tabs, pat-auto-scale, pat-equaliser: they adjust the layout on
57+
initialization.
58+
- Transform-only patterns (pat-legend, pat-focus) and small patterns, for
59+
which the registration module would eat most of the gain.
60+
61+
## Alternatives considered
62+
63+
- **Grafting the implementation's prototype onto the registration pattern**
64+
(Mockup's current approach, e.g. `pat/modal/modal.js`): the registration
65+
module is a `Base` pattern whose `init()` imports the implementation and
66+
copies its prototype onto the running instance with `$.extend`. This
67+
relies on `Base` specifics and does not work for `BasePattern` classes:
68+
class methods are not enumerable and are not copied, class fields are
69+
created by the implementation's constructor which never runs, private
70+
fields throw when accessed on an object not constructed by their class,
71+
and `BasePattern` parses the options with the implementation's static
72+
parser before `init()` runs.
73+
- **Wrapping a separate implementation instance** (Mockup's pat-tinymce
74+
since 2022): the registration pattern creates an implementation object in
75+
its `init()` and keeps it as `this.instance`. With a `BasePattern` class
76+
as implementation, there are two pattern instances per element. The
77+
registration pattern has already stored itself as `el["pattern-NAME"]`, so
78+
the real pattern refuses to initialize as already initialized. Destroying,
79+
lifecycle tracking and init events would have to be forwarded between the
80+
two instances.
81+
- **A placeholder which constructs the real pattern** (chosen): the real
82+
class is instantiated with its own constructor, so fields, private fields,
83+
the static parser, the initialization order and the re-initialization
84+
guard work unchanged, and the implementation modules are ordinary
85+
`BasePattern` classes. The logic lives in one helper, so each registration
86+
module is a few lines of configuration.
87+
88+
## Consequences
89+
90+
- The eagerly loaded patterns chunk went from 206.9 KB to 129.1 KB minified
91+
(60.7 KB to 38.8 KB gzipped), measured with production builds before and
92+
after splitting. The split pattern implementations and their dynamic
93+
import lookup maps are no longer part of it. The entry points grow by about
94+
0.5 KB for the additional chunk map entries.
95+
- Instantiating a registration module's class with `new` returns a Promise
96+
of the pattern instance, not the instance. Code which uses the result
97+
directly has to `await new Pattern(el)`.
98+
`events.await_pattern_init(new Pattern(el))` accepts the Promise. Code
99+
which only registers patterns or lets the registry instantiate them is not
100+
affected.
101+
- A split pattern initializes after its implementation chunk is loaded,
102+
i.e. one network round trip later on first use. Patterns which already
103+
load a library dynamically now load two chunks in sequence.
104+
- Breaking change for JavaScript users of split patterns: the default export
105+
of `NAME.js` is the placeholder class and `parser` is no longer exported
106+
there. Import `NAME--implementation.js` instead.
107+
- Bundles importing `NAME.js` for registration (e.g. Mockup's
108+
`patterns.js`) get the lazy loading without changes.

‎src/core/events.js‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -281,12 +281,26 @@ const await_event = (el, event_name) => {
281281
* Usage:
282282
* await events.await_pattern_init(PATTERN);
283283
*
284-
* @param {Pattern instance} pattern - The pattern instance.
284+
* @param {Pattern instance} pattern - The pattern instance, or a Promise of
285+
* it as returned when instantiating a lazily loaded pattern.
285286
*
286287
* @returns {Promise} - Returns a Promise which can be used for ``await`` and which will be resolved when the event is throwm.
287288
*
288289
*/
289290
const await_pattern_init = (pattern) => {
291+
if (typeof pattern?.then === "function") {
292+
// Lazily loaded patterns (see core/lazy-pattern.js) return a Promise
293+
// of the pattern instance when instantiated. The instance is created
294+
// synchronously when the Promise resolves while BasePattern
295+
// initializes in a later tick, so the listeners below are still
296+
// registered in time.
297+
return pattern.then((instance) => {
298+
if (!instance) {
299+
throw new Error("The pattern could not be loaded.");
300+
}
301+
return await_pattern_init(instance);
302+
});
303+
}
290304
// See: https://stackoverflow.com/a/44746691/1337474
291305
return new Promise((resolve, reject) => {
292306
// Case initialized

‎src/core/lazy-pattern.js‎

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
/**
2+
* Lazily loaded patterns.
3+
*
4+
* Create a lightweight placeholder pattern class, which is registered in the
5+
* patterns registry instead of the real pattern class. The real pattern
6+
* implementation is only loaded when the pattern is used for the first time.
7+
* This keeps the pattern implementation out of the eagerly loaded bundle.
8+
*
9+
* Usage - in ``example.js``:
10+
*
11+
* import registry from "../../core/registry";
12+
* import create_lazy_pattern from "../../core/lazy-pattern";
13+
*
14+
* const Pattern = create_lazy_pattern({
15+
* name: "example",
16+
* trigger: ".pat-example",
17+
* load: () => import("./example--implementation"),
18+
* });
19+
* registry.register(Pattern);
20+
* export default Pattern;
21+
*
22+
* The implementation module ``example--implementation.js`` contains the
23+
* BasePattern based class as its default export.
24+
*
25+
* Instantiating the placeholder class returns a Promise, which resolves to the
26+
* instance of the real pattern class. So the registry and code doing
27+
* ``await new registry.patterns.example(el)`` keep working.
28+
*
29+
* After the implementation was loaded, the registry entry is replaced with
30+
* the real pattern class.
31+
*/
32+
import logging from "./logging";
33+
import registry from "./registry";
34+
35+
const log = logging.getLogger("lazy-pattern");
36+
37+
export function create_lazy_pattern({ name, trigger, order, load }) {
38+
let loading = null;
39+
40+
class LazyPattern {
41+
static name = name;
42+
static trigger = trigger;
43+
static order = order;
44+
static lazy = true;
45+
46+
static async load() {
47+
if (!loading) {
48+
loading = load()
49+
.then((module) => {
50+
const Pattern = module.default;
51+
if (registry.patterns[name] === LazyPattern) {
52+
// Swap the placeholder for the real pattern, so
53+
// that further instantiations are done directly.
54+
registry.patterns[name] = Pattern;
55+
}
56+
return Pattern;
57+
})
58+
.catch((error) => {
59+
// Allow to retry loading.
60+
loading = null;
61+
throw error;
62+
});
63+
}
64+
return await loading;
65+
}
66+
67+
constructor(el, options, trigger) {
68+
// Return a Promise instead of the instance. This is allowed for
69+
// classes which do not extend another class.
70+
return LazyPattern.load().then(
71+
(Pattern) => new Pattern(el, options, trigger),
72+
(error) => {
73+
log.error(`Could not load the pattern ${name}.`, error);
74+
return null;
75+
},
76+
);
77+
}
78+
}
79+
80+
return LazyPattern;
81+
}
82+
83+
export default create_lazy_pattern;

0 commit comments

Comments
 (0)