mount-observer 0.1.13 → 0.1.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/Events.js +9 -0
  2. package/Events.ts +12 -0
  3. package/MountObserver.js +21 -0
  4. package/MountObserver.ts +27 -0
  5. package/README.md +406 -69
  6. package/{DefineCustomElementHandler.js → handlers/DefineCustomElement.js} +103 -99
  7. package/handlers/DefineCustomElement.ts +123 -0
  8. package/handlers/EnhanceMountedElement.js +99 -0
  9. package/handlers/EnhanceMountedElement.ts +116 -0
  10. package/handlers/Events.js +110 -0
  11. package/handlers/EvtRt.js +59 -0
  12. package/handlers/GenIds.js +37 -0
  13. package/handlers/GenIds.ts +45 -0
  14. package/handlers/HTMLInclude.js +393 -0
  15. package/handlers/HTMLInclude.ts +453 -0
  16. package/handlers/HoistTemplate.js +77 -0
  17. package/handlers/HoistTemplate.ts +89 -0
  18. package/handlers/MountObserver.js +941 -0
  19. package/handlers/MountObserverScript.js +78 -0
  20. package/handlers/MountObserverScript.ts +89 -0
  21. package/handlers/ScriptExport.js +83 -0
  22. package/handlers/ScriptExport.ts +97 -0
  23. package/handlers/SharedMutationObserver.js +78 -0
  24. package/handlers/arr.js +16 -0
  25. package/handlers/connectionMonitor.js +122 -0
  26. package/handlers/elementIntersection.js +73 -0
  27. package/handlers/emitEvents.js +187 -0
  28. package/handlers/getRegistryRoot.js +52 -0
  29. package/handlers/loadImports.js +129 -0
  30. package/handlers/mediaQuery.js +90 -0
  31. package/handlers/rootSizeObserver.js +131 -0
  32. package/handlers/upShadowSearch.js +70 -0
  33. package/handlers/withScopePerimeter.js +22 -0
  34. package/index.js +2 -2
  35. package/index.ts +2 -2
  36. package/package.json +13 -3
  37. package/types/assign-gingerly/types.d.ts +244 -0
  38. package/types/be-a-beacon/types.d.ts +3 -0
  39. package/types/global.d.ts +29 -0
  40. package/types/id-generation/types.d.ts +26 -0
  41. package/types/mount-observer/types.d.ts +330 -0
  42. package/upShadowSearch.js +6 -3
  43. package/upShadowSearch.ts +6 -3
@@ -0,0 +1,330 @@
1
+ // Core types for MountObserver v2 - Polyfill Supported Scenario I
2
+
3
+ export type Constructor = new (...args: any[]) => any;
4
+
5
+ export type EventConstructor = {new(...args: any[]): Event};
6
+
7
+ export interface EventConfig {
8
+ event: string | EventConstructor;
9
+ args?: any | any[];
10
+ eventProps?: Record<string, any>;
11
+ oncePerMountedElement?: boolean;
12
+ }
13
+
14
+ export type DismountReason =
15
+ | 'media-query-failed'
16
+ | 'root-size-failed'
17
+ | 'intersection-failed'
18
+ | 'connection-failed'
19
+ | 'with-matching-failed';
20
+
21
+ export interface ConnectionCondition {
22
+ effectiveTypeIn?: string[];
23
+ downlinkMin?: number;
24
+ downlinkMax?: number;
25
+ rttMax?: number;
26
+ }
27
+
28
+ /**
29
+ * Configuration object for MountObserver that defines what elements to observe and how to handle them.
30
+ * All `where*` properties form an AND condition - elements must satisfy ALL specified conditions to mount.
31
+ *
32
+ * @template TKeys - String literal type for sub-observer keys when using the `with` property
33
+ */
34
+ export interface MountConfig<TKeys extends string = string> {
35
+ /**
36
+ * CSS selector string to match elements.
37
+ * Only elements matching this selector will be considered for mounting.
38
+ * @example 'button.fancy' or 'div > p.highlight'
39
+ */
40
+ matching?: string;
41
+
42
+ /**
43
+ * Custom element tag name(s) that must be defined before mounting occurs.
44
+ * Waits for customElements.whenDefined() to resolve for each specified tag.
45
+ * Uses the customElementRegistry of the observed root node.
46
+ * This check happens first, before any other where* conditions.
47
+ * @example 'my-button' or ['my-button', 'my-input']
48
+ */
49
+ whenDefined?: string | string[];
50
+
51
+ /**
52
+ * Constructor or array of constructors to filter elements by instance type.
53
+ * Elements must be instances of at least one of the specified constructors (OR logic for arrays).
54
+ * @example HTMLButtonElement or [HTMLInputElement, HTMLTextAreaElement]
55
+ */
56
+ whereInstanceOf?: Constructor | Constructor[];
57
+
58
+ /**
59
+ * Media query string or MediaQueryList for conditional mounting based on viewport/media conditions.
60
+ * Elements only mount when the media query matches.
61
+ * @example '(min-width: 768px)' or '(prefers-color-scheme: dark)'
62
+ */
63
+ withMediaMatching?: string | MediaQueryList;
64
+
65
+ /**
66
+ * CSS selector defining a "donut hole" scope perimeter.
67
+ * Excludes elements that are descendants of elements matching this selector.
68
+ * Useful for preventing observation of nested scopes.
69
+ * @example '.no-observe' to exclude elements inside .no-observe containers
70
+ */
71
+ withScopePerimeter?: string;
72
+
73
+ /**
74
+ * Container query string for conditional mounting based on observed root element size.
75
+ * Elements only mount when the root node matches this size condition.
76
+ * @example '(min-width: 500px)' to only mount when root is at least 500px wide
77
+ */
78
+ whereObservedRootSizeMatches?: string;
79
+
80
+ /**
81
+ * IntersectionObserver configuration for conditional mounting based on element visibility.
82
+ * Elements only mount when they intersect with the viewport according to these options.
83
+ * @example { rootMargin: '50px', threshold: 0.5 }
84
+ */
85
+ whereElementIntersectsWith?: IntersectionObserverInit;
86
+
87
+ /**
88
+ * Network connection conditions for conditional mounting.
89
+ * Elements only mount when network conditions match the specified criteria.
90
+ * Useful for adaptive loading based on connection quality.
91
+ */
92
+ whereConnectionHas?: ConnectionCondition;
93
+
94
+ /**
95
+ * When true, inverts the default registry matching behavior.
96
+ * Default (false): Only mount elements with the SAME customElementRegistry as the root node.
97
+ * When true: Only mount elements with a DIFFERENT customElementRegistry than the root node.
98
+ * Useful for cross-registry observation scenarios.
99
+ * @example true to observe elements from other shadow DOM scopes
100
+ */
101
+ whereDifferentCustomElementRegistry?: boolean;
102
+
103
+ /**
104
+ * Regular expression or string pattern to match against element's localName.
105
+ * Only elements whose localName matches this pattern will mount.
106
+ * String values are converted to RegExp.
107
+ * @example /^my-/ to match elements starting with 'my-'
108
+ * @example 'button|input' to match button or input elements
109
+ */
110
+ whereLocalNameMatches?: string | RegExp;
111
+
112
+ /**
113
+ * Module(s) to import before mounting elements.
114
+ * Can be a URL string, ImportSpec object, or array of either.
115
+ * Modules are loaded based on loadingEagerness setting.
116
+ * @example './my-component.js' or [{ url: './styles.css', type: 'css' }]
117
+ */
118
+ import?: string | ImportSpec | Array<string | ImportSpec>;
119
+
120
+ /**
121
+ * Handler(s) to execute when elements mount.
122
+ * Can be:
123
+ * - String: Name of a registered handler (e.g., 'builtIns.defineCustomElement')
124
+ * - Function: Inline callback function
125
+ * - Array: Multiple handlers to execute in order
126
+ * @example 'builtIns.defineCustomElement' or (el, ctx) => { el.classList.add('mounted') }
127
+ */
128
+ do?: string | DoCallback | (string | DoCallback)[];
129
+
130
+ /**
131
+ * Custom JavaScript check that runs after all declarative where* conditions pass.
132
+ * This is the final gate before mounting occurs.
133
+ *
134
+ * If shouldMount returns false, the element is not mounted (no do callback, no mount event).
135
+ * If shouldMount throws an error, it is treated as returning false and the error is logged.
136
+ *
137
+ * @example (el) => currentUser.hasRole('admin')
138
+ * @example (el) => el.dataset.apiKey && el.dataset.apiEndpoint
139
+ */
140
+ shouldMount?: ShouldMountCallback;
141
+
142
+ /**
143
+ * Controls when imports are loaded.
144
+ * - 'eager': Load imports immediately when MountObserver is created
145
+ * - 'lazy': Load imports only when first matching element is found (default)
146
+ */
147
+ loadingEagerness?: 'eager' | 'lazy';
148
+
149
+ /**
150
+ * Properties to assign to elements when they mount.
151
+ * Uses assign-gingerly for safe property assignment.
152
+ * @example { disabled: false, tabIndex: 0 }
153
+ */
154
+ assignOnMount?: Record<string, any>;
155
+
156
+ /**
157
+ * Properties to assign to elements when they dismount.
158
+ * Uses assign-gingerly for safe property assignment.
159
+ * @example { disabled: true }
160
+ */
161
+ assignOnDismount?: Record<string, any>;
162
+
163
+ /**
164
+ * Properties to tentatively assign on mount with automatic reversal on dismount.
165
+ * Original values are saved and restored when element dismounts.
166
+ * @example { hidden: false } - will restore original hidden value on dismount
167
+ */
168
+ stageOnMount?: Record<string, any>;
169
+
170
+ /**
171
+ * When true, enables detailed event dispatching for debugging and monitoring.
172
+ * Provides granular lifecycle events for observation.
173
+ */
174
+ getPlayByPlay?: boolean;
175
+
176
+ /**
177
+ * Event(s) to emit from mounted elements.
178
+ * Can be a single EventConfig or array of EventConfigs.
179
+ * Allows elements to dispatch custom events when mounted.
180
+ * @example { event: 'ready', args: { detail: 'mounted' } }
181
+ */
182
+ mountedElemEmits?: EventConfig | EventConfig[];
183
+
184
+ /**
185
+ * External module(s) to import MountConfig from.
186
+ * Allows separating JSON-serializable config from non-serializable handlers.
187
+ * Loaded configs are merged left-to-right, with inline config taking final precedence.
188
+ * @example './config.js' or ['./base-config.js', './override-config.js']
189
+ */
190
+ configFrom?: string | string[];
191
+
192
+ /**
193
+ * Custom data to pass to handler classes or functions.
194
+ * Allows handlers to receive additional context-specific information.
195
+ * Not used by MountObserver itself, but available in MountContext.
196
+ */
197
+ customData?: unknown;
198
+
199
+ /**
200
+ * Sub-observer configurations for hierarchical composition.
201
+ * Each key-value pair defines a sub-observer that will observe the same root node as the parent.
202
+ * Sub-observers are created when the parent's observe() method is called and automatically
203
+ * disconnected when the parent disconnects.
204
+ *
205
+ * Sub-observers operate independently with their own configurations and do not inherit
206
+ * properties from the parent observer. Each sub-observer can have its own `with` property
207
+ * for unlimited nesting depth.
208
+ *
209
+ * @example
210
+ * ```typescript
211
+ * const observer = new MountObserver({
212
+ * matching: '.parent',
213
+ * with: {
214
+ * registry: { matching: 'my-element', do: 'builtIns.defineCustomElement' },
215
+ * styles: { import: './styles.css' }
216
+ * }
217
+ * });
218
+ * ```
219
+ */
220
+ with?: {[K in TKeys]: MountConfig};
221
+ }
222
+
223
+
224
+
225
+ export interface ImportSpec {
226
+ url: string;
227
+ type?: 'js' | 'css' | 'json' | 'html';
228
+ }
229
+
230
+ /**
231
+ * Context object passed to mount handlers containing information about the mounted element and observer state.
232
+ *
233
+ * @template TKeys - String literal type for sub-observer keys when using the `with` property
234
+ */
235
+ export interface MountContext<TKeys extends string = string> {
236
+ modules: any[];
237
+ observer: IMountObserver;
238
+ rootNode: Node;
239
+
240
+ /**
241
+ * The configuration object for this observer.
242
+ * Contains all the settings that define what elements to observe and how to handle them.
243
+ */
244
+ mountConfig: MountConfig<TKeys>;
245
+
246
+ /**
247
+ * Map of sub-observers created from the `with` property in mountConfig.
248
+ * Only present when the parent observer has sub-observers defined.
249
+ * Keys match the keys from the `with` property, providing type-safe access to sub-observers.
250
+ *
251
+ * @example
252
+ * ```typescript
253
+ * do: (el, ctx) => {
254
+ * // Access sub-observers with type safety
255
+ * const registryObserver = ctx.withObservers?.registry;
256
+ * if (registryObserver) {
257
+ * console.log('Registry observer:', registryObserver);
258
+ * }
259
+ * }
260
+ * ```
261
+ */
262
+ withObservers?: {[K in TKeys]: IMountObserver};
263
+ }
264
+
265
+
266
+
267
+ export type DoCallback<TKeys extends string = string> = (mountedElement: Element, context: MountContext<TKeys>) => void;
268
+
269
+ /**
270
+ * Callback function that performs a final check before mounting an element.
271
+ * Called after all declarative where* conditions have passed.
272
+ *
273
+ * @param mountedElement - The element being considered for mounting
274
+ * @param context - The mount context containing modules, observer, config, etc.
275
+ * @returns true to allow mounting, false to prevent it
276
+ */
277
+ export type ShouldMountCallback<TKeys extends string = string> = (mountedElement: Element, context: MountContext<TKeys>) => boolean;
278
+
279
+ // export interface DoCallbacks {
280
+ // mount?: (mountedElement: Element, context: MountContext) => void;
281
+ // dismount?: (mountedElement: Element, context: MountContext) => void;
282
+ // disconnect?: (mountedElement: Element, context: MountContext) => void;
283
+ // reconnect?: (mountedElement: Element, context: MountContext) => void;
284
+ // }
285
+
286
+ export type MountScope =
287
+ | 'registry' // Observe all scopes with matching registry (new default)
288
+ | 'registryRoot' // getRegistryRoot - finds highest node with matching customElementRegistry
289
+ | 'self' // this element
290
+ | 'root' // getRootNode()
291
+ | 'shadow' // shadowRoot (throws if none)
292
+ | Element; // custom element to observe
293
+
294
+ export interface MountObserverOptions {
295
+ disconnectedSignal?: AbortSignal;
296
+ scope?: MountScope;
297
+ }
298
+
299
+ export interface WeakDual<T extends Object>{
300
+ weakSet: WeakSet<T>,
301
+ setWeak: Set<WeakRef<T>>
302
+ }
303
+
304
+ export interface WeakMapDual<T extends Object, R extends Object>{
305
+ weakMap: WeakMap<T, R>,
306
+ setWeak: Set<WeakRef<T>>
307
+ }
308
+
309
+ export interface IMountObserver extends EventTarget {
310
+ observe(observedNode: Node): Promise<void>;
311
+ disconnect(): void;
312
+ disconnectedSignal: AbortSignal;
313
+ assignGingerly(config: Record<string, any> | undefined): Promise<void>;
314
+ getNotifier(element: Element): EventTarget;
315
+ }
316
+
317
+ export interface IMountEvent extends Event {
318
+ mountedElement: Element;
319
+ modules: any[];
320
+ mountConfig: MountConfig;
321
+ mountContext: MountContext;
322
+ }
323
+
324
+ export interface IDismountEvent extends Event {
325
+ mountedElement: Element;
326
+ reason: DismountReason;
327
+ mountConfig: MountConfig;
328
+ }
329
+
330
+
package/upShadowSearch.js CHANGED
@@ -5,8 +5,11 @@
5
5
  * element's root node and continuing up through shadow DOM boundaries until the element
6
6
  * is found or the document root is reached.
7
7
  *
8
+ * Registry-aware: Only searches in root nodes that share the same customElementRegistry
9
+ * as the reference element. This respects scoped custom element registry boundaries.
10
+ *
8
11
  * Search order:
9
- * 1. Check current root node using getElementById
12
+ * 1. Check current root node using getElementById (if same registry)
10
13
  * 2. If in shadow root, check host element's properties for the ID
11
14
  * 3. Continue up to parent shadow root or document
12
15
  * 4. Handle disconnected fragments via targetFragment property
@@ -27,8 +30,8 @@
27
30
  export function upShadowSearch(ref, id) {
28
31
  let rn = ref.getRootNode();
29
32
  while (rn) {
30
- // Try getElementById on current root
31
- if ('getElementById' in rn) {
33
+ // Try getElementById on current root, but only if it shares the same registry
34
+ if ('getElementById' in rn && rn.customElementRegistry === ref.customElementRegistry) {
32
35
  const test = rn.getElementById(id);
33
36
  if (test)
34
37
  return test;
package/upShadowSearch.ts CHANGED
@@ -5,8 +5,11 @@
5
5
  * element's root node and continuing up through shadow DOM boundaries until the element
6
6
  * is found or the document root is reached.
7
7
  *
8
+ * Registry-aware: Only searches in root nodes that share the same customElementRegistry
9
+ * as the reference element. This respects scoped custom element registry boundaries.
10
+ *
8
11
  * Search order:
9
- * 1. Check current root node using getElementById
12
+ * 1. Check current root node using getElementById (if same registry)
10
13
  * 2. If in shadow root, check host element's properties for the ID
11
14
  * 3. Continue up to parent shadow root or document
12
15
  * 4. Handle disconnected fragments via targetFragment property
@@ -28,8 +31,8 @@ export function upShadowSearch(ref: Element, id: string): Element | null {
28
31
  let rn = ref.getRootNode() as DocumentFragment | ShadowRoot | Document;
29
32
 
30
33
  while (rn) {
31
- // Try getElementById on current root
32
- if ('getElementById' in rn) {
34
+ // Try getElementById on current root, but only if it shares the same registry
35
+ if ('getElementById' in rn && (rn as any).customElementRegistry === (ref as any).customElementRegistry) {
33
36
  const test = rn.getElementById(id);
34
37
  if (test) return test;
35
38
  }